修复(#128): 统一促销价格资格口径
Build docker and publish / build (20.15.1) (push) Failing after 18m40s
Build docker and publish / build (20.15.1) (pull_request) Failing after 19m24s

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
2026-05-29 22:42:04 -07:00
parent e5d6539d79
commit 3644e9ce3f
5 changed files with 263 additions and 235 deletions
+140 -99
View File
@@ -2,114 +2,19 @@ package subscribe
import (
"context"
"fmt"
"strings"
"testing"
"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"
"gorm.io/driver/mysql"
"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) {
db, err := gorm.Open(mysql.New(mysql.Config{
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) {
subscribe := types.Subscribe{Discount: []types.SubscribeDiscount{
{Quantity: 1},