@@ -30,7 +30,7 @@ type promoRuleParams struct {
|
|||||||
|
|
||||||
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID int64, quantity int64) (*PromoResult, error) {
|
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID int64, quantity int64) (*PromoResult, error) {
|
||||||
result := &PromoResult{}
|
result := &PromoResult{}
|
||||||
if svcCtx == nil || svcCtx.PromoModel == nil || svcCtx.DB == nil || userID <= 0 || subscribeID <= 0 || quantity <= 0 {
|
if svcCtx == nil || svcCtx.PromoModel == nil || svcCtx.DB == nil || subscribeID <= 0 || quantity <= 0 {
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,8 +101,14 @@ func evaluatePromoRule(
|
|||||||
) (bool, time.Time, error) {
|
) (bool, time.Time, error) {
|
||||||
switch rule.Type {
|
switch rule.Type {
|
||||||
case promo.RuleTypeNewUser:
|
case promo.RuleTypeNewUser:
|
||||||
|
if userID <= 0 {
|
||||||
|
return false, time.Time{}, nil
|
||||||
|
}
|
||||||
return evaluateNewUserPromo(ctx, db, params, userID, currentUser, now)
|
return evaluateNewUserPromo(ctx, db, params, userID, currentUser, now)
|
||||||
case promo.RuleTypeInactiveUser:
|
case promo.RuleTypeInactiveUser:
|
||||||
|
if userID <= 0 {
|
||||||
|
return false, time.Time{}, nil
|
||||||
|
}
|
||||||
return evaluateInactiveUserPromo(ctx, db, params, userID, promoRuleExpiresAt(rule), now)
|
return evaluateInactiveUserPromo(ctx, db, params, userID, promoRuleExpiresAt(rule), now)
|
||||||
case promo.RuleTypeCampaign:
|
case promo.RuleTypeCampaign:
|
||||||
return true, promoRuleExpiresAt(rule), nil
|
return true, promoRuleExpiresAt(rule), nil
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
package common
|
package common
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/perfect-panel/server/internal/model/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestEvaluateInactiveUserExpire(t *testing.T) {
|
func TestEvaluateInactiveUserExpire(t *testing.T) {
|
||||||
@@ -44,3 +49,99 @@ func TestEvaluateInactiveUserExpire(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestEvaluatePromoAllowsAnonymousCampaign(t *testing.T) {
|
||||||
|
end := time.Now().Add(time.Hour)
|
||||||
|
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
|
||||||
|
{
|
||||||
|
Rule: promo.Rule{
|
||||||
|
Id: 3,
|
||||||
|
Name: "campaign",
|
||||||
|
Type: promo.RuleTypeCampaign,
|
||||||
|
Enabled: true,
|
||||||
|
EndTime: &end,
|
||||||
|
},
|
||||||
|
PromoPrice: 199,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
|
||||||
|
got, err := EvaluatePromo(context.Background(), &svc.ServiceContext{DB: &gorm.DB{}, PromoModel: model}, 0, 7, 12)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("EvaluatePromo returned error: %v", err)
|
||||||
|
}
|
||||||
|
if !got.Eligible {
|
||||||
|
t.Fatal("anonymous campaign promo should be eligible")
|
||||||
|
}
|
||||||
|
if got.RuleID != 3 {
|
||||||
|
t.Fatalf("RuleID = %d, want 3", got.RuleID)
|
||||||
|
}
|
||||||
|
if got.PromoPrice != 199 {
|
||||||
|
t.Fatalf("PromoPrice = %d, want 199", got.PromoPrice)
|
||||||
|
}
|
||||||
|
if model.lastSubscribeID != 7 {
|
||||||
|
t.Fatalf("lastSubscribeID = %d, want 7", model.lastSubscribeID)
|
||||||
|
}
|
||||||
|
if model.lastQuantity != 12 {
|
||||||
|
t.Fatalf("lastQuantity = %d, want 12", model.lastQuantity)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type fakePromoModel struct {
|
||||||
|
rules []*promo.RuleWithPrice
|
||||||
|
lastSubscribeID int64
|
||||||
|
lastQuantity int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakePromoModel) QueryEligibleRules(_ context.Context, subscribeID int64, quantity int64) ([]*promo.RuleWithPrice, error) {
|
||||||
|
m.lastSubscribeID = subscribeID
|
||||||
|
m.lastQuantity = quantity
|
||||||
|
return m.rules, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakePromoModel) InsertRule(context.Context, *promo.Rule) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakePromoModel) FindRule(context.Context, int64) (*promo.Rule, error) {
|
||||||
|
return nil, gorm.ErrRecordNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakePromoModel) UpdateRule(context.Context, *promo.Rule) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakePromoModel) DeleteRule(context.Context, int64) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakePromoModel) QueryRuleList(context.Context, int, int, string, *bool, string) (int64, []*promo.Rule, error) {
|
||||||
|
return 0, nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakePromoModel) UpsertPrices(context.Context, int64, []*promo.SubscribePromo) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakePromoModel) FindPrice(context.Context, int64) (*promo.SubscribePromo, error) {
|
||||||
|
return nil, gorm.ErrRecordNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakePromoModel) DeletePrice(context.Context, int64) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakePromoModel) QueryPriceList(context.Context, promo.PriceFilter) (int64, []*promo.SubscribePromo, error) {
|
||||||
|
return 0, nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakePromoModel) QueryUsageList(context.Context, promo.UsageFilter) (int64, []*promo.Usage, error) {
|
||||||
|
return 0, nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakePromoModel) Transaction(context.Context, func(*gorm.DB) error) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -194,11 +194,12 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
|
|||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SubscribeOutOfStock), "subscribe out of stock")
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SubscribeOutOfStock), "subscribe out of stock")
|
||||||
}
|
}
|
||||||
|
|
||||||
newUserDiscount, err := resolveNewUserDiscountEligibility(l.ctx, l.svcCtx.DB, u.Id, targetSubscribeID, req.Quantity, sub.Discount)
|
newUserDiscount, err := resolveNewUserDiscountEligibility(l.ctx, l.svcCtx.DB, entitlement.EffectiveUserID, targetSubscribeID, req.Quantity, sub.Discount)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorw("[Purchase] Database query error resolving new user eligibility",
|
l.Errorw("[Purchase] Database query error resolving new user eligibility",
|
||||||
logger.Field("error", err.Error()),
|
logger.Field("error", err.Error()),
|
||||||
logger.Field("user_id", u.Id),
|
logger.Field("user_id", u.Id),
|
||||||
|
logger.Field("effective_user_id", entitlement.EffectiveUserID),
|
||||||
)
|
)
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -206,7 +207,7 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
|
|||||||
priceResult, err := calculatePurchasePrice(
|
priceResult, err := calculatePurchasePrice(
|
||||||
l.ctx,
|
l.ctx,
|
||||||
l.svcCtx,
|
l.svcCtx,
|
||||||
u.Id,
|
entitlement.EffectiveUserID,
|
||||||
targetSubscribeID,
|
targetSubscribeID,
|
||||||
sub.UnitPrice,
|
sub.UnitPrice,
|
||||||
req.Quantity,
|
req.Quantity,
|
||||||
@@ -218,6 +219,7 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
|
|||||||
l.Errorw("[Purchase] Promo price calculation error",
|
l.Errorw("[Purchase] Promo price calculation error",
|
||||||
logger.Field("error", err.Error()),
|
logger.Field("error", err.Error()),
|
||||||
logger.Field("user_id", u.Id),
|
logger.Field("user_id", u.Id),
|
||||||
|
logger.Field("effective_user_id", entitlement.EffectiveUserID),
|
||||||
logger.Field("subscribe_id", targetSubscribeID),
|
logger.Field("subscribe_id", targetSubscribeID),
|
||||||
)
|
)
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -2,12 +2,12 @@ package subscribe
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
stderrors "errors"
|
stderrors "errors"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/go-sql-driver/mysql"
|
"github.com/go-sql-driver/mysql"
|
||||||
|
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
"github.com/perfect-panel/server/internal/model/user"
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
"github.com/perfect-panel/server/internal/types"
|
"github.com/perfect-panel/server/internal/types"
|
||||||
@@ -15,7 +15,6 @@ import (
|
|||||||
"github.com/perfect-panel/server/pkg/xerr"
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/clause"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -35,11 +34,6 @@ type subscribePromoCandidate struct {
|
|||||||
EndTime *time.Time `gorm:"column:end_time"`
|
EndTime *time.Time `gorm:"column:end_time"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type promoRuleParams struct {
|
|
||||||
WindowHours int64 `json:"window_hours"`
|
|
||||||
InactiveMonths int `json:"inactive_months"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64) (map[int64]map[int64]*types.SubscribePromo, error) {
|
func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64) (map[int64]map[int64]*types.SubscribePromo, error) {
|
||||||
result := make(map[int64]map[int64]*types.SubscribePromo)
|
result := make(map[int64]map[int64]*types.SubscribePromo)
|
||||||
if len(subscribeIDs) == 0 || svcCtx == nil || svcCtx.DB == nil {
|
if len(subscribeIDs) == 0 || svcCtx == nil || svcCtx.DB == nil {
|
||||||
@@ -55,8 +49,10 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
evaluator := promoEligibilityEvaluator{ctx: ctx, db: svcCtx.DB, userInfo: userInfo}
|
userID := int64(0)
|
||||||
now := time.Now()
|
if userInfo != nil {
|
||||||
|
userID = userInfo.Id
|
||||||
|
}
|
||||||
for _, candidate := range candidates {
|
for _, candidate := range candidates {
|
||||||
if candidate.Quantity <= 0 {
|
if candidate.Quantity <= 0 {
|
||||||
continue
|
continue
|
||||||
@@ -67,21 +63,18 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
|
|||||||
if _, exists := result[candidate.SubscribeId][candidate.Quantity]; exists {
|
if _, exists := result[candidate.SubscribeId][candidate.Quantity]; exists {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if !candidate.isActive(now) {
|
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, candidate.SubscribeId, candidate.Quantity)
|
||||||
continue
|
|
||||||
}
|
|
||||||
ok, expiresAt, err := evaluator.match(candidate, now)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if !ok {
|
if promoResult == nil || !promoResult.Eligible {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
result[candidate.SubscribeId][candidate.Quantity] = &types.SubscribePromo{
|
result[candidate.SubscribeId][candidate.Quantity] = &types.SubscribePromo{
|
||||||
RuleName: candidate.RuleName,
|
RuleName: promoResult.RuleName,
|
||||||
RuleType: candidate.RuleType,
|
RuleType: promoResult.RuleType,
|
||||||
PromoPrice: candidate.PromoPrice,
|
PromoPrice: promoResult.PromoPrice,
|
||||||
ExpiresAt: unixSeconds(expiresAt),
|
ExpiresAt: unixSeconds(promoResult.ExpiresAt),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,121 +107,6 @@ func subscribePromoCandidatesQuery(ctx context.Context, db *gorm.DB, subscribeID
|
|||||||
Order("pr.id ASC")
|
Order("pr.id ASC")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c subscribePromoCandidate) isActive(now time.Time) bool {
|
|
||||||
if c.PromoPrice <= 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if c.StartTime != nil && now.Before(*c.StartTime) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if c.EndTime != nil && now.After(*c.EndTime) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
type promoEligibilityEvaluator struct {
|
|
||||||
ctx context.Context
|
|
||||||
db *gorm.DB
|
|
||||||
userInfo *user.User
|
|
||||||
lastExpire *time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *promoEligibilityEvaluator) match(candidate subscribePromoCandidate, now time.Time) (bool, time.Time, error) {
|
|
||||||
switch candidate.RuleType {
|
|
||||||
case promoRuleTypeCampaign:
|
|
||||||
return true, candidate.expiresAt(), nil
|
|
||||||
case promoRuleTypeNewUser:
|
|
||||||
if e.userInfo == nil {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
params, err := candidate.params()
|
|
||||||
if err != nil {
|
|
||||||
return false, time.Time{}, err
|
|
||||||
}
|
|
||||||
if params.WindowHours <= 0 || e.userInfo.CreatedAt.IsZero() {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
expiresAt := e.userInfo.CreatedAt.Add(time.Duration(params.WindowHours) * time.Hour)
|
|
||||||
return now.Before(expiresAt), expiresAt, nil
|
|
||||||
case promoRuleTypeInactiveUser:
|
|
||||||
if e.userInfo == nil {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
params, err := candidate.params()
|
|
||||||
if err != nil {
|
|
||||||
return false, time.Time{}, err
|
|
||||||
}
|
|
||||||
if params.InactiveMonths <= 0 {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
lastExpire, err := e.lastSubscribeExpireAt()
|
|
||||||
if err != nil {
|
|
||||||
return false, time.Time{}, err
|
|
||||||
}
|
|
||||||
if lastExpire.Equal(time.UnixMilli(0)) || lastExpire.After(now) {
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
if lastExpire.IsZero() {
|
|
||||||
return true, candidate.expiresAt(), nil
|
|
||||||
}
|
|
||||||
threshold := now.AddDate(0, -params.InactiveMonths, 0)
|
|
||||||
return !lastExpire.After(threshold), candidate.expiresAt(), nil
|
|
||||||
default:
|
|
||||||
return false, time.Time{}, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *promoEligibilityEvaluator) lastSubscribeExpireAt() (time.Time, error) {
|
|
||||||
if e.lastExpire != nil {
|
|
||||||
return *e.lastExpire, nil
|
|
||||||
}
|
|
||||||
var item user.Subscribe
|
|
||||||
err := e.lastSubscribeExpireQuery().
|
|
||||||
Limit(1).
|
|
||||||
Take(&item).Error
|
|
||||||
if err != nil {
|
|
||||||
if stderrors.Is(err, gorm.ErrRecordNotFound) {
|
|
||||||
zero := time.Time{}
|
|
||||||
e.lastExpire = &zero
|
|
||||||
return zero, nil
|
|
||||||
}
|
|
||||||
return time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo user last subscription failed")
|
|
||||||
}
|
|
||||||
e.lastExpire = &item.ExpireTime
|
|
||||||
return item.ExpireTime, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *promoEligibilityEvaluator) lastSubscribeExpireQuery() *gorm.DB {
|
|
||||||
return e.db.WithContext(e.ctx).
|
|
||||||
Model(&user.Subscribe{}).
|
|
||||||
Where("user_id = ?", e.userInfo.Id).
|
|
||||||
Order(clause.OrderBy{
|
|
||||||
Expression: clause.Expr{
|
|
||||||
SQL: "CASE WHEN expire_time = ? THEN 0 ELSE 1 END, expire_time DESC",
|
|
||||||
Vars: []interface{}{time.UnixMilli(0)},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c subscribePromoCandidate) expiresAt() time.Time {
|
|
||||||
if c.EndTime == nil {
|
|
||||||
return time.Time{}
|
|
||||||
}
|
|
||||||
return *c.EndTime
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c subscribePromoCandidate) params() (promoRuleParams, error) {
|
|
||||||
if c.Params == "" {
|
|
||||||
return promoRuleParams{}, nil
|
|
||||||
}
|
|
||||||
var params promoRuleParams
|
|
||||||
if err := json.Unmarshal([]byte(c.Params), ¶ms); err != nil {
|
|
||||||
return promoRuleParams{}, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "parse promo rule params failed")
|
|
||||||
}
|
|
||||||
return params, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func unixSeconds(t time.Time) int64 {
|
func unixSeconds(t time.Time) int64 {
|
||||||
if t.IsZero() {
|
if t.IsZero() {
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
@@ -2,114 +2,19 @@ package subscribe
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
"github.com/DATA-DOG/go-sqlmock"
|
||||||
|
"github.com/perfect-panel/server/internal/model/promo"
|
||||||
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
"github.com/perfect-panel/server/internal/types"
|
"github.com/perfect-panel/server/internal/types"
|
||||||
"gorm.io/driver/mysql"
|
"gorm.io/driver/mysql"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestPromoEligibilityEvaluatorMatch(t *testing.T) {
|
|
||||||
now := time.Unix(1710000000, 0)
|
|
||||||
campaignEnd := now.Add(2 * time.Hour)
|
|
||||||
|
|
||||||
campaign := subscribePromoCandidate{
|
|
||||||
RuleName: "限时活动",
|
|
||||||
RuleType: promoRuleTypeCampaign,
|
|
||||||
PromoPrice: 99,
|
|
||||||
EndTime: &campaignEnd,
|
|
||||||
}
|
|
||||||
ok, expiresAt, err := (&promoEligibilityEvaluator{}).match(campaign, now)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("campaign match error: %v", err)
|
|
||||||
}
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("campaign promo should match without login")
|
|
||||||
}
|
|
||||||
if got, want := unixSeconds(expiresAt), campaignEnd.Unix(); got != want {
|
|
||||||
t.Fatalf("campaign expires_at = %d, want %d", got, want)
|
|
||||||
}
|
|
||||||
|
|
||||||
newUser := subscribePromoCandidate{
|
|
||||||
RuleName: "新客7天优惠",
|
|
||||||
RuleType: promoRuleTypeNewUser,
|
|
||||||
PromoPrice: 279,
|
|
||||||
Params: `{"window_hours":168}`,
|
|
||||||
}
|
|
||||||
ok, _, err = (&promoEligibilityEvaluator{}).match(newUser, now)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("anonymous new_user match error: %v", err)
|
|
||||||
}
|
|
||||||
if ok {
|
|
||||||
t.Fatal("new_user promo should not match without login")
|
|
||||||
}
|
|
||||||
|
|
||||||
userInfo := &user.User{Id: 1, CreatedAt: now.Add(-24 * time.Hour)}
|
|
||||||
ok, expiresAt, err = (&promoEligibilityEvaluator{userInfo: userInfo}).match(newUser, now)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("logged-in new_user match error: %v", err)
|
|
||||||
}
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("new_user promo should match inside window")
|
|
||||||
}
|
|
||||||
if got, want := unixSeconds(expiresAt), userInfo.CreatedAt.Add(168*time.Hour).Unix(); got != want {
|
|
||||||
t.Fatalf("new_user expires_at = %d, want %d", got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSubscribePromoCandidateActiveWindow(t *testing.T) {
|
|
||||||
now := time.Unix(1710000000, 0)
|
|
||||||
start := now.Add(-time.Hour)
|
|
||||||
end := now.Add(time.Hour)
|
|
||||||
|
|
||||||
if !(subscribePromoCandidate{PromoPrice: 1, StartTime: &start, EndTime: &end}).isActive(now) {
|
|
||||||
t.Fatal("candidate inside active window should be active")
|
|
||||||
}
|
|
||||||
if (subscribePromoCandidate{PromoPrice: 0, StartTime: &start, EndTime: &end}).isActive(now) {
|
|
||||||
t.Fatal("candidate with zero promo price should not be active")
|
|
||||||
}
|
|
||||||
if (subscribePromoCandidate{PromoPrice: 1, StartTime: &end}).isActive(now) {
|
|
||||||
t.Fatal("candidate before start time should not be active")
|
|
||||||
}
|
|
||||||
if (subscribePromoCandidate{PromoPrice: 1, EndTime: &start}).isActive(now) {
|
|
||||||
t.Fatal("candidate after end time should not be active")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLastSubscribeExpireAtPrioritizesPermanentSubscription(t *testing.T) {
|
|
||||||
db, err := gorm.Open(mysql.New(mysql.Config{
|
|
||||||
DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local",
|
|
||||||
SkipInitializeWithVersion: true,
|
|
||||||
}), &gorm.Config{DryRun: true, DisableAutomaticPing: true})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("open dry-run db: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
evaluator := &promoEligibilityEvaluator{
|
|
||||||
db: db,
|
|
||||||
userInfo: &user.User{Id: 7},
|
|
||||||
}
|
|
||||||
var item user.Subscribe
|
|
||||||
tx := evaluator.lastSubscribeExpireQuery().Limit(1).Take(&item)
|
|
||||||
|
|
||||||
sql := tx.Statement.SQL.String()
|
|
||||||
if !strings.Contains(sql, "CASE WHEN expire_time = ? THEN 0 ELSE 1 END") {
|
|
||||||
t.Fatalf("SQL missing permanent subscription priority order: %s", sql)
|
|
||||||
}
|
|
||||||
if strings.Contains(sql, "expire_time !=") {
|
|
||||||
t.Fatalf("SQL should not filter out permanent subscriptions: %s", sql)
|
|
||||||
}
|
|
||||||
if len(tx.Statement.Vars) < 2 {
|
|
||||||
t.Fatalf("SQL vars length = %d, want at least 2; vars=%v", len(tx.Statement.Vars), tx.Statement.Vars)
|
|
||||||
}
|
|
||||||
if got, want := tx.Statement.Vars[1], time.UnixMilli(0); got != want {
|
|
||||||
t.Fatalf("permanent subscription order var = %v, want %v; vars=%v", got, want, tx.Statement.Vars)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestQuerySubscribePromoCandidatesIncludesQuantity(t *testing.T) {
|
func TestQuerySubscribePromoCandidatesIncludesQuantity(t *testing.T) {
|
||||||
db, err := gorm.Open(mysql.New(mysql.Config{
|
db, err := gorm.Open(mysql.New(mysql.Config{
|
||||||
DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local",
|
DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local",
|
||||||
@@ -131,6 +36,142 @@ func TestQuerySubscribePromoCandidatesIncludesQuantity(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLoadSubscribePromoMapUsesCommonPromoEvaluation(t *testing.T) {
|
||||||
|
db, mock, cleanup := newSubscribePromoTestDB(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
end := time.Now().Add(time.Hour)
|
||||||
|
mock.ExpectQuery("FROM subscribe_promo AS sp").
|
||||||
|
WillReturnRows(sqlmock.NewRows([]string{
|
||||||
|
"subscribe_id", "quantity", "rule_name", "rule_type", "promo_price", "params", "start_time", "end_time",
|
||||||
|
}).AddRow(11, 3, "old name", promoRuleTypeCampaign, 999, "", nil, end))
|
||||||
|
|
||||||
|
promoModel := &fakeSubscribePromoModel{rules: []*promo.RuleWithPrice{
|
||||||
|
{
|
||||||
|
Rule: promo.Rule{
|
||||||
|
Id: 8,
|
||||||
|
Name: "公共活动价",
|
||||||
|
Type: promo.RuleTypeCampaign,
|
||||||
|
Enabled: true,
|
||||||
|
EndTime: &end,
|
||||||
|
},
|
||||||
|
PromoPrice: 888,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
|
||||||
|
got, err := loadSubscribePromoMap(context.Background(), &svc.ServiceContext{DB: db, PromoModel: promoModel}, []int64{11})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("loadSubscribePromoMap returned error: %v", err)
|
||||||
|
}
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Fatalf("sql expectations: %v", err)
|
||||||
|
}
|
||||||
|
if promoModel.lastSubscribeID != 11 {
|
||||||
|
t.Fatalf("promo subscribe id = %d, want 11", promoModel.lastSubscribeID)
|
||||||
|
}
|
||||||
|
if promoModel.lastQuantity != 3 {
|
||||||
|
t.Fatalf("promo quantity = %d, want 3", promoModel.lastQuantity)
|
||||||
|
}
|
||||||
|
|
||||||
|
item := got[11][3]
|
||||||
|
if item == nil {
|
||||||
|
t.Fatal("quantity 3 promo should be present")
|
||||||
|
}
|
||||||
|
if item.RuleName != "公共活动价" {
|
||||||
|
t.Fatalf("RuleName = %q, want 公共活动价", item.RuleName)
|
||||||
|
}
|
||||||
|
if item.PromoPrice != 888 {
|
||||||
|
t.Fatalf("PromoPrice = %d, want 888", item.PromoPrice)
|
||||||
|
}
|
||||||
|
if item.ExpiresAt != end.Unix() {
|
||||||
|
t.Fatalf("ExpiresAt = %d, want %d", item.ExpiresAt, end.Unix())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type fakeSubscribePromoModel struct {
|
||||||
|
rules []*promo.RuleWithPrice
|
||||||
|
lastSubscribeID int64
|
||||||
|
lastQuantity int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakeSubscribePromoModel) QueryEligibleRules(_ context.Context, subscribeID int64, quantity int64) ([]*promo.RuleWithPrice, error) {
|
||||||
|
m.lastSubscribeID = subscribeID
|
||||||
|
m.lastQuantity = quantity
|
||||||
|
return m.rules, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakeSubscribePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakeSubscribePromoModel) InsertRule(context.Context, *promo.Rule) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakeSubscribePromoModel) FindRule(context.Context, int64) (*promo.Rule, error) {
|
||||||
|
return nil, gorm.ErrRecordNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakeSubscribePromoModel) UpdateRule(context.Context, *promo.Rule) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakeSubscribePromoModel) DeleteRule(context.Context, int64) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakeSubscribePromoModel) QueryRuleList(context.Context, int, int, string, *bool, string) (int64, []*promo.Rule, error) {
|
||||||
|
return 0, nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakeSubscribePromoModel) UpsertPrices(context.Context, int64, []*promo.SubscribePromo) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakeSubscribePromoModel) FindPrice(context.Context, int64) (*promo.SubscribePromo, error) {
|
||||||
|
return nil, gorm.ErrRecordNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakeSubscribePromoModel) DeletePrice(context.Context, int64) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakeSubscribePromoModel) QueryPriceList(context.Context, promo.PriceFilter) (int64, []*promo.SubscribePromo, error) {
|
||||||
|
return 0, nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakeSubscribePromoModel) QueryUsageList(context.Context, promo.UsageFilter) (int64, []*promo.Usage, error) {
|
||||||
|
return 0, nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *fakeSubscribePromoModel) Transaction(context.Context, func(*gorm.DB) error) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSubscribePromoTestDB(t *testing.T) (*gorm.DB, sqlmock.Sqlmock, func()) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
sqlDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherFunc(func(expectedSQL, actualSQL string) error {
|
||||||
|
if strings.Contains(actualSQL, expectedSQL) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return fmt.Errorf("actual sql %q does not contain %q", actualSQL, expectedSQL)
|
||||||
|
})))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create sqlmock: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := gorm.Open(mysql.New(mysql.Config{Conn: sqlDB, SkipInitializeWithVersion: true}), &gorm.Config{})
|
||||||
|
if err != nil {
|
||||||
|
_ = sqlDB.Close()
|
||||||
|
t.Fatalf("open gorm db: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return db, mock, func() {
|
||||||
|
_ = sqlDB.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestApplySubscribeDiscountPromosMatchesQuantity(t *testing.T) {
|
func TestApplySubscribeDiscountPromosMatchesQuantity(t *testing.T) {
|
||||||
subscribe := types.Subscribe{Discount: []types.SubscribeDiscount{
|
subscribe := types.Subscribe{Discount: []types.SubscribeDiscount{
|
||||||
{Quantity: 1},
|
{Quantity: 1},
|
||||||
|
|||||||
Reference in New Issue
Block a user