a46fb83054
Closes HIF-3 (阶段 PR B) PR B:handler 真实业务对接 + 邀请钩子(迭代含 R1 修复) - 迁移 02157_lottery_grant_ledger:external_ref UNIQUE 作为发奖幂等键 - log.CommissionTypeLottery=339(架构师批准的新常量) - DispatchRequest.IdempotencyKey(架构师 review 建议第 2 条) - GrantLedger + LedgerService.Reserve:INSERT ON CONFLICT DO NOTHING 幂等 upsert - VPNDurationHandler:ResolveEffectiveUser 归位家庭 owner + UpdateSubscribe,ExpireTime 三分支对齐 grantGiftDays - CommissionHandler:UpdateCommission + WriteCommissionLog(339),发给中奖者本人,不做家庭组归位 - Handler 从 model 层迁到 logic 层(避免 model → logic 反向依赖);noop 保留在 model 层 - InviteHook:fire-and-forget 独立 goroutine + 10s timeout,扫 running 活动的 invite_success 源 - ServiceContext 新增 LotteryChance / LotteryLedger / LotteryInviteHook - activateOrderLogic.handleCommission 两条分支通过 invokeInviteHookIfEligible 助手触发,助手内统一 gate IsNew(架构师 R1 打回后的修复) 架构师 R1 打回:branch B 未按"首次付款激活"gate,续费也会给 referer 发抽奖机会 → 已通过助手函数集中收拢,避免 branch A/B 判断漂移。 测试覆盖率:model 76.5% / handler 73.2% / hook 91.7%;补 4 个回归测试覆盖 IsNew 门槛(含关键的 DoesNotFireOnRenewal)。 线上仍零可见变更:无对外路由,钩子仅在活动 status=running 时生效,Stage 1 全流程无活动记录时 loadRunningActivities 返回空。
346 lines
11 KiB
Go
346 lines
11 KiB
Go
package handler
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/DATA-DOG/go-sqlmock"
|
|
"github.com/perfect-panel/server/internal/model/lottery"
|
|
usermodel "github.com/perfect-panel/server/internal/model/user"
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// newHandlerTestDB 建一个 sqlmock 支撑的 gorm.DB,子测试直接把它当 tx 传给 handler。
|
|
func newHandlerTestDB(t *testing.T) (*gorm.DB, sqlmock.Sqlmock, func()) {
|
|
t.Helper()
|
|
sqlDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherFunc(func(expected, actual string) error {
|
|
if strings.Contains(actual, expected) {
|
|
return nil
|
|
}
|
|
return errors.New("actual sql does not contain expected: " + expected)
|
|
})))
|
|
if err != nil {
|
|
t.Fatalf("create sqlmock: %v", err)
|
|
}
|
|
db, err := gorm.Open(mysql.New(mysql.Config{Conn: sqlDB, SkipInitializeWithVersion: true}), &gorm.Config{
|
|
SkipDefaultTransaction: true,
|
|
})
|
|
if err != nil {
|
|
_ = sqlDB.Close()
|
|
t.Fatalf("open gorm db: %v", err)
|
|
}
|
|
return db, mock, func() { _ = sqlDB.Close() }
|
|
}
|
|
|
|
// fakeLedger 让 handler 单测不依赖真实 SQL,只验证控制流。
|
|
type fakeLedger struct {
|
|
reserveFn func(ctx context.Context, tx *gorm.DB, entry lottery.GrantLedger) (*lottery.GrantLedger, bool, error)
|
|
}
|
|
|
|
func (f *fakeLedger) Reserve(ctx context.Context, tx *gorm.DB, entry lottery.GrantLedger) (*lottery.GrantLedger, bool, error) {
|
|
return f.reserveFn(ctx, tx, entry)
|
|
}
|
|
|
|
// fakeUserModel 满足 usermodel.Model 里 handler 用到的两个方法。
|
|
type fakeUserModel struct {
|
|
usermodel.Model
|
|
findActive func(ctx context.Context, userID int64) (*usermodel.Subscribe, error)
|
|
updateSubscribe func(ctx context.Context, sub *usermodel.Subscribe, tx ...*gorm.DB) error
|
|
}
|
|
|
|
func (f *fakeUserModel) FindActiveSubscribe(ctx context.Context, userID int64) (*usermodel.Subscribe, error) {
|
|
return f.findActive(ctx, userID)
|
|
}
|
|
func (f *fakeUserModel) UpdateSubscribe(ctx context.Context, sub *usermodel.Subscribe, tx ...*gorm.DB) error {
|
|
return f.updateSubscribe(ctx, sub, tx...)
|
|
}
|
|
|
|
// identityResolver 单测里的家庭组归位:始终返回自身。
|
|
func identityResolver(_ context.Context, userID int64) (int64, error) { return userID, nil }
|
|
|
|
func TestVPNDuration_RequiresIdempotencyKey(t *testing.T) {
|
|
db, _, cleanup := newHandlerTestDB(t)
|
|
defer cleanup()
|
|
|
|
h := NewVPNDurationHandler(VPNDurationDeps{
|
|
Ledger: &fakeLedger{},
|
|
DB: db,
|
|
ResolveEffectiveUser: identityResolver,
|
|
})
|
|
_, err := h.Dispatch(context.Background(), db, lottery.DispatchRequest{})
|
|
if err == nil || !strings.Contains(err.Error(), "IdempotencyKey") {
|
|
t.Fatalf("expected IdempotencyKey error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestVPNDuration_RequiresTx(t *testing.T) {
|
|
h := NewVPNDurationHandler(VPNDurationDeps{Ledger: &fakeLedger{}})
|
|
_, err := h.Dispatch(context.Background(), nil, lottery.DispatchRequest{IdempotencyKey: "k"})
|
|
if err == nil || !strings.Contains(err.Error(), "transaction") {
|
|
t.Fatalf("expected tx error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestVPNDuration_IdempotentHitReturnsStoredMessage(t *testing.T) {
|
|
db, _, cleanup := newHandlerTestDB(t)
|
|
defer cleanup()
|
|
|
|
stored := lottery.GrantLedger{
|
|
Id: 9,
|
|
ExternalRef: "lottery:100:200",
|
|
Payload: `{"message":"已加 3 天到订阅"}`,
|
|
}
|
|
ledger := &fakeLedger{
|
|
reserveFn: func(_ context.Context, _ *gorm.DB, _ lottery.GrantLedger) (*lottery.GrantLedger, bool, error) {
|
|
return &stored, true, nil
|
|
},
|
|
}
|
|
fake := &fakeUserModel{
|
|
findActive: func(context.Context, int64) (*usermodel.Subscribe, error) {
|
|
t.Fatal("must NOT touch UserModel on idempotent hit")
|
|
return nil, nil
|
|
},
|
|
updateSubscribe: func(context.Context, *usermodel.Subscribe, ...*gorm.DB) error {
|
|
t.Fatal("must NOT touch UserModel on idempotent hit")
|
|
return nil
|
|
},
|
|
}
|
|
|
|
h := NewVPNDurationHandler(VPNDurationDeps{
|
|
Ledger: ledger,
|
|
UserModel: fake,
|
|
DB: db,
|
|
ResolveEffectiveUser: identityResolver,
|
|
})
|
|
res, err := h.Dispatch(context.Background(), db, lottery.DispatchRequest{
|
|
UserId: 42,
|
|
ActivityId: 100,
|
|
DrawId: 200,
|
|
Prize: lottery.Prize{Config: `{"duration_days":3}`},
|
|
IdempotencyKey: "lottery:100:200",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Dispatch: %v", err)
|
|
}
|
|
if res.State != lottery.DispatchStateAutoClaimed {
|
|
t.Fatalf("expected auto_claimed, got %q", res.State)
|
|
}
|
|
if res.Message != "已加 3 天到订阅" {
|
|
t.Fatalf("expected stored message, got %q", res.Message)
|
|
}
|
|
}
|
|
|
|
func TestVPNDuration_NoActiveSubscribeSkipsWithoutError(t *testing.T) {
|
|
db, mock, cleanup := newHandlerTestDB(t)
|
|
defer cleanup()
|
|
|
|
ledger := &fakeLedger{
|
|
reserveFn: func(_ context.Context, _ *gorm.DB, entry lottery.GrantLedger) (*lottery.GrantLedger, bool, error) {
|
|
return &lottery.GrantLedger{Id: 5, ExternalRef: entry.ExternalRef}, false, nil
|
|
},
|
|
}
|
|
fake := &fakeUserModel{
|
|
findActive: func(context.Context, int64) (*usermodel.Subscribe, error) {
|
|
return nil, gorm.ErrRecordNotFound
|
|
},
|
|
updateSubscribe: func(context.Context, *usermodel.Subscribe, ...*gorm.DB) error {
|
|
t.Fatal("must NOT UpdateSubscribe when no active sub")
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// fallback query returns no rows either
|
|
mock.ExpectQuery("FROM `user_subscribe`").
|
|
WillReturnError(gorm.ErrRecordNotFound)
|
|
mock.ExpectExec("UPDATE `lottery_grant_ledger`").
|
|
WillReturnResult(sqlmock.NewResult(0, 1))
|
|
|
|
h := NewVPNDurationHandler(VPNDurationDeps{
|
|
Ledger: ledger, UserModel: fake, DB: db, ResolveEffectiveUser: identityResolver,
|
|
})
|
|
res, err := h.Dispatch(context.Background(), db, lottery.DispatchRequest{
|
|
UserId: 42,
|
|
ActivityId: 100,
|
|
DrawId: 200,
|
|
Prize: lottery.Prize{Config: `{"duration_days":3}`},
|
|
IdempotencyKey: "lottery:100:200",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Dispatch: %v", err)
|
|
}
|
|
if res.State != lottery.DispatchStateAutoClaimed {
|
|
t.Fatalf("expected auto_claimed even on skip, got %q", res.State)
|
|
}
|
|
if !strings.Contains(res.Message, "跳过") {
|
|
t.Fatalf("expected skip message, got %q", res.Message)
|
|
}
|
|
}
|
|
|
|
func TestVPNDuration_ExtendsExistingExpireTime(t *testing.T) {
|
|
db, mock, cleanup := newHandlerTestDB(t)
|
|
defer cleanup()
|
|
|
|
future := time.Now().Add(10 * 24 * time.Hour).Truncate(time.Second)
|
|
activeSub := &usermodel.Subscribe{
|
|
Id: 77,
|
|
UserId: 42,
|
|
ExpireTime: future,
|
|
Status: 1,
|
|
}
|
|
|
|
ledger := &fakeLedger{
|
|
reserveFn: func(_ context.Context, _ *gorm.DB, _ lottery.GrantLedger) (*lottery.GrantLedger, bool, error) {
|
|
return &lottery.GrantLedger{Id: 5, ExternalRef: "lottery:100:200"}, false, nil
|
|
},
|
|
}
|
|
|
|
updateCalled := false
|
|
fake := &fakeUserModel{
|
|
findActive: func(context.Context, int64) (*usermodel.Subscribe, error) { return activeSub, nil },
|
|
updateSubscribe: func(_ context.Context, sub *usermodel.Subscribe, _ ...*gorm.DB) error {
|
|
updateCalled = true
|
|
expected := future.Add(3 * 24 * time.Hour)
|
|
if !sub.ExpireTime.Equal(expected) {
|
|
t.Fatalf("expire time not stacked: got %s want %s", sub.ExpireTime, expected)
|
|
}
|
|
if sub.Status != 1 {
|
|
t.Fatalf("expected Status=1 after grant, got %d", sub.Status)
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
mock.ExpectExec("UPDATE `lottery_grant_ledger`").
|
|
WillReturnResult(sqlmock.NewResult(0, 1))
|
|
|
|
h := NewVPNDurationHandler(VPNDurationDeps{
|
|
Ledger: ledger, UserModel: fake, DB: db, ResolveEffectiveUser: identityResolver,
|
|
})
|
|
res, err := h.Dispatch(context.Background(), db, lottery.DispatchRequest{
|
|
UserId: 42,
|
|
ActivityId: 100,
|
|
DrawId: 200,
|
|
Prize: lottery.Prize{Config: `{"duration_days":3}`},
|
|
IdempotencyKey: "lottery:100:200",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("Dispatch: %v", err)
|
|
}
|
|
if !updateCalled {
|
|
t.Fatalf("expected UpdateSubscribe to be called")
|
|
}
|
|
if res.Message != "已加 3 天到订阅" {
|
|
t.Fatalf("unexpected message: %q", res.Message)
|
|
}
|
|
}
|
|
|
|
func TestVPNDuration_ExpiredSubscribeRestartsFromNow(t *testing.T) {
|
|
db, mock, cleanup := newHandlerTestDB(t)
|
|
defer cleanup()
|
|
|
|
past := time.Now().Add(-24 * time.Hour)
|
|
activeSub := &usermodel.Subscribe{
|
|
Id: 77,
|
|
ExpireTime: past,
|
|
}
|
|
|
|
ledger := &fakeLedger{
|
|
reserveFn: func(_ context.Context, _ *gorm.DB, _ lottery.GrantLedger) (*lottery.GrantLedger, bool, error) {
|
|
return &lottery.GrantLedger{Id: 5}, false, nil
|
|
},
|
|
}
|
|
fake := &fakeUserModel{
|
|
findActive: func(context.Context, int64) (*usermodel.Subscribe, error) { return activeSub, nil },
|
|
updateSubscribe: func(_ context.Context, sub *usermodel.Subscribe, _ ...*gorm.DB) error {
|
|
delta := time.Until(sub.ExpireTime)
|
|
if delta < 3*24*time.Hour-5*time.Second || delta > 3*24*time.Hour+5*time.Second {
|
|
t.Fatalf("expected ~3 days from now, got %v", delta)
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
mock.ExpectExec("UPDATE `lottery_grant_ledger`").WillReturnResult(sqlmock.NewResult(0, 1))
|
|
|
|
h := NewVPNDurationHandler(VPNDurationDeps{
|
|
Ledger: ledger, UserModel: fake, DB: db, ResolveEffectiveUser: identityResolver,
|
|
})
|
|
_, _ = h.Dispatch(context.Background(), db, lottery.DispatchRequest{
|
|
Prize: lottery.Prize{Config: `{"duration_days":3}`},
|
|
IdempotencyKey: "k",
|
|
})
|
|
}
|
|
|
|
func TestVPNDuration_NoLimitNotExtended(t *testing.T) {
|
|
db, mock, cleanup := newHandlerTestDB(t)
|
|
defer cleanup()
|
|
|
|
noLimit := time.UnixMilli(0)
|
|
activeSub := &usermodel.Subscribe{
|
|
Id: 77,
|
|
ExpireTime: noLimit,
|
|
Status: 1,
|
|
}
|
|
|
|
ledger := &fakeLedger{
|
|
reserveFn: func(_ context.Context, _ *gorm.DB, _ lottery.GrantLedger) (*lottery.GrantLedger, bool, error) {
|
|
return &lottery.GrantLedger{Id: 5}, false, nil
|
|
},
|
|
}
|
|
fake := &fakeUserModel{
|
|
findActive: func(context.Context, int64) (*usermodel.Subscribe, error) { return activeSub, nil },
|
|
updateSubscribe: func(_ context.Context, sub *usermodel.Subscribe, _ ...*gorm.DB) error {
|
|
if !sub.ExpireTime.Equal(noLimit) {
|
|
t.Fatalf("no-limit ExpireTime must not be extended, got %v", sub.ExpireTime)
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
mock.ExpectExec("UPDATE `lottery_grant_ledger`").WillReturnResult(sqlmock.NewResult(0, 1))
|
|
|
|
h := NewVPNDurationHandler(VPNDurationDeps{
|
|
Ledger: ledger, UserModel: fake, DB: db, ResolveEffectiveUser: identityResolver,
|
|
})
|
|
_, _ = h.Dispatch(context.Background(), db, lottery.DispatchRequest{
|
|
Prize: lottery.Prize{Config: `{"duration_days":3}`},
|
|
IdempotencyKey: "k",
|
|
})
|
|
}
|
|
|
|
func TestVPNDuration_BadConfigRejected(t *testing.T) {
|
|
db, _, cleanup := newHandlerTestDB(t)
|
|
defer cleanup()
|
|
|
|
h := NewVPNDurationHandler(VPNDurationDeps{
|
|
Ledger: &fakeLedger{},
|
|
DB: db,
|
|
ResolveEffectiveUser: identityResolver,
|
|
})
|
|
tests := []struct {
|
|
name string
|
|
config string
|
|
}{
|
|
{name: "invalid json", config: `{bad`},
|
|
{name: "zero days", config: `{"duration_days":0}`},
|
|
{name: "negative days", config: `{"duration_days":-1}`},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
_, err := h.Dispatch(context.Background(), db, lottery.DispatchRequest{
|
|
Prize: lottery.Prize{Config: tt.config},
|
|
IdempotencyKey: "k",
|
|
})
|
|
if err == nil {
|
|
t.Fatalf("expected error on %s", tt.name)
|
|
}
|
|
})
|
|
}
|
|
_ = json.Unmarshal
|
|
}
|