Compare commits

...

13 Commits

Author SHA1 Message Date
架构师 c2d0db5875 修复(#143): 邀请权益查询排序 inviteeAndInviterIds 消除 map 迭代序 flake
inviteeAndInviterSet 是 map,按 range 收集到 slice 后顺序不固定,
传给 fillGiftBenefits 的 IN (?,?) 参数随之乱序,导致 sqlmock 按位置
匹配的单测 TestQueryBenefitsKeepsDirectInviteeGift 偶现失败(本地 10
次复现约 2-4 次)。

在收集后追加 slices.Sort,让生产代码本身的下游 SQL 参数稳定;同步把
测试期望改为升序。50 次重复 + race 全绿。

Co-authored-by: multica-agent <github@multica.ai>
2026-06-02 21:00:52 -07:00
shanshanzhong147 87ebfa1fac 修复(#137): DeferCloseOrder 关单前反查支付网关 (启用 confirmationPayment)
Build docker and publish / build (20.15.1) (push) Failing after 18m47s
Build docker and publish / build (20.15.1) (pull_request) Failing after 19m31s
Squash merge of fix/137-defer-close-反查网关 (1367c4f).

DeferCloseOrder 直接将 status=1 订单关单,会把已经在网关侧完成支付但
notify 静默失败的订单错误关闭。本次在关单前调用 EPay 的网关查询接口
(confirmationPayment) 拿到三态结果:

- Paid: 原子化把 status 1->2,写回 trade_no,再投递 asynq 走激活流程
- Unpaid: 继续原来的 close 事务,把 status 改为 cancelled
- Unknown / 网关失败: 保持 status=1,下一轮 DeferClose 再试

新增 closeOrderLogic_test.go (232 行),覆盖三态分支 + recoverPaidOrder
的并发幂等。单测全量 PASS, go build + go vet 均干净。E2E 验收因测试环境
访问受限暂未跑,QA 已在 issue 上注明阻塞原因 (qa_partial_blocked_on_e2e_access)。

Co-authored-by: multica-agent <github@multica.ai>
2026-06-02 20:24:32 -07:00
shanshanzhong147 ac25eb4d91 修复(#140): 去掉 cancelWithdrawalLogic 在新流程下的重复退款
Build docker and publish / build (20.15.1) (push) Has been cancelled
Build docker and publish / build (20.15.1) (pull_request) Has been cancelled
Squash merge of fix/140-去掉撤销提现的重复退款 (86896cd).

HIF-22 引入 rejectWithdrawal 反查支付网关后,cancelWithdrawalLogic 仍在
事务体内调用 UpdateCommission(+amount),对已在 rejectWithdrawal 中退还
的金额做了二次退款。本次只保留 withdrawal.status -> Cancelled,与
rejectWithdrawal 行为对齐。

新增 cancelWithdrawalLogic_test.go 用 sqlmock 严格断言:撤销 happy path
只触发 BEGIN / SELECT FOR UPDATE / UPDATE withdrawals / COMMIT 四条 SQL,
对 user / system_logs 零读零写。

Co-authored-by: multica-agent <github@multica.ai>
2026-06-02 20:23:45 -07:00
架构师 54379976ec 修复(#138): 补齐 errMsg 漏掉的错误码映射
Build docker and publish / build (20.15.1) (push) Failing after 20m57s
Build docker and publish / build (20.15.1) (pull_request) Failing after 19m44s
新增 UserCommissionNotEnough、SendSmsError、AreaCodeIsEmpty、
DeviceBindLimitExceeded、ExistAvailableTraffic 五个错误码的中文映射,
修复管理后台审批提现等接口业务校验失败时 msg 被误显为
"Internal Server Error" 的问题。

Co-authored-by: multica-agent <github@multica.ai>
2026-06-01 22:29:36 -07:00
架构师 750b7be424 修复(#136): EPay notify 静默失败硬化 + 回写 trade_no
Build docker and publish / build (20.15.1) (push) Failing after 8m55s
Build docker and publish / build (20.15.1) (pull_request) Failing after 22m22s
P01 签名校验失败由 return nil 改为返回 xerr.SignatureInvalid,handler 回 400,EPay 网关重试;Debug 旁路保留
P02 订单不存在维持 error 返回,仅 status=5 Finished 保留 nil 作幂等短路
P03 支付完成路径写入 order.trade_no = req.TradeNo,再 UpdateOrderStatus 刷缓存
附加:TradeStatus != TRADE_SUCCESS 降为 INFO 日志 + metric epay_notify_trade_not_success
抽离纯决策函数 evaluateEPayNotify,新增单测覆盖 4 个核心分支 + 签名优先级回归 + SQL 写路径 + URL 解析(9/9 PASS,-race 干净)

仅 internal/logic/notify/ePayNotifyLogic.go 与对应单测,无其他文件变更。

Co-authored-by: multica-agent <github@multica.ai>
2026-06-01 03:08:31 -07:00
架构师 aa11588c8f 修复(#129): 新注册无历史用户不再误命中沉默促销
Build docker and publish / build (20.15.1) (push) Failing after 22m17s
Build docker and publish / build (20.15.1) (pull_request) Failing after 22m28s
evaluateInactiveUserPromo 在 ErrRecordNotFound 时之前 return true,导致
新注册无任何订阅历史的用户被错误判定为"沉默用户"命中 inactive_user 规则。
改为 return false 保持判定语义一致:没有历史订阅 ≠ 沉默用户。

Squash from origin/fix/129-新注册误命中沉默促销 (77377ed)

Co-authored-by: multica-agent <github@multica.ai>
2026-06-01 00:28:26 -07:00
shanshanzhong147 c3050821d5 x
Build docker and publish / build (20.15.1) (push) Failing after 19m50s
Build docker and publish / build (20.15.1) (pull_request) Failing after 20m32s
2026-05-31 21:15:57 -07:00
shanshanzhong147 5b9f384f81 修复(#132): 退款幂等校验 + 已退款订单防重新激活
Build docker and publish / build (20.15.1) (push) Failing after 21m4s
Build docker and publish / build (20.15.1) (pull_request) Failing after 21m47s
P01:refundOrderLogic.RefundOrder 在事务内 FOR UPDATE 后、lockCommissionSource 前新增
333 退款日志扫描,命中即返回 OrderAlreadyRefunded(61006),不再写日志/扣 commission/
改 order.status。

P02:堵住已退款订单状态被回退入口
- queue/logic/order/stuckOrderRecoveryLogic.go:批扫 status=6 时新增 333 日志守卫,
  已退款订单不再被重置为 5 + 重新入队 activate(HIF-131 trace 中订单 53647 被刷回 5
  的真凶)
- queue/logic/order/activateOrderLogic.go:releaseClaim 同步加守卫做防御性兜底

新增 internal/model/log/refund.go 共享 helper HasRefundCommissionLog:
type=33 + content LIKE 走索引粗筛,再 JSON 反序列化确认 content.type==333 AND
content.order_no==orderNo,防 LIKE 子串误判。

测试:单元测试覆盖正常退款 / 已有 333 日志拒绝 / 子串误判防御 / 脏 JSON 容错;
sqlmock 严格断言命中后事务序列只含 BEGIN/SELECT order FOR UPDATE/SELECT
system_logs/ROLLBACK,无任何 commission 写入。

不做:calculateCommission、status 枚举拆分、表结构变更、支付通道 notify、用户余额回补。

Co-authored-by: multica-agent <github@multica.ai>
2026-05-31 20:19:35 -07:00
shanshanzhong147 7236ca4cf2 修复(#128): 按规则类型决定促销资格,让 InactiveUser/Campaign 对老用户生效
Build docker and publish / build (20.15.1) (push) Has been cancelled
Build docker and publish / build (20.15.1) (pull_request) Has been cancelled
此前 calculatePurchasePrice 把 allowPromo 绑死在 orderType == 1,导致只要用户
有任何过往付费订阅(含已过期),就会被 paidSubscriptionQuery 路由为续费
(orderType=2),跳过所有促销评估。后果:

  - InactiveUser 召回促销永远无法触发(其目标人群恰好就是有过期订阅的用户)
  - Campaign 全员活动对老用户 / 升级加购场景完全失效
  - 套餐列表(loadSubscribePromoMap)直接调 EvaluatePromo 不感知 orderType,
    可能显示促销价但下单时却拿到原价

修复方式:把 isFirstPurchase 下放给 EvaluatePromo,由规则类型决定 gating:

  - NewUser    要求 isFirstPurchase=true(保留首购语义)
  - InactiveUser 由规则自身的"上次订阅过期 N 月以上"条件判定
  - Campaign   时间窗内对任意用户生效

新增 common.HasPaidSubscription 助手,套餐列表与下单走同一份 isFirstPurchase
判定,确保展示价与实际下单价口径一致。

测试:补充 EvaluatePromo / calculatePurchasePrice 的 NewUser 屏蔽 + Campaign
放开用例;更新 loadSubscribePromoMap 测试覆盖新增 HasPaidSubscription 查询。

注:renewalLogic.go 仍未接入促销(属于方向 B 的彻底统一,本次未涵盖)。
2026-05-31 19:00:30 -07:00
shanshanzhong147 ae126296e3 修复(#128): 统一续费场景促销判断
Build docker and publish / build (20.15.1) (push) Failing after 23m3s
Build docker and publish / build (20.15.1) (pull_request) Failing after 19m4s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-30 23:12:39 -07:00
shanshanzhong147 1e99cfb83c 修复(#128): 兼容促销规则毫秒时间戳
Build docker and publish / build (20.15.1) (push) Failing after 19m21s
Build docker and publish / build (20.15.1) (pull_request) Failing after 19m48s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-30 04:16:21 -07:00
shanshanzhong147 0659a930f8 修复(#128): 修复家庭成员邀请流水可见性
Build docker and publish / build (20.15.1) (push) Failing after 18m41s
Build docker and publish / build (20.15.1) (pull_request) Failing after 19m16s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-30 03:27:04 -07:00
shanshanzhong147 c2d1b5a0d8 修复(#130): 统一家庭成员促销资格口径
Build docker and publish / build (20.15.1) (push) Failing after 22m15s
Build docker and publish / build (20.15.1) (pull_request) Failing after 18m6s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-30 01:58:15 -07:00
35 changed files with 2103 additions and 126 deletions
+2 -2
View File
@@ -15,10 +15,10 @@ Logger: # 日志配置
Level: debug # 日志级别: debug, info, warn, error, panic, fatal
MySQL:
Addr: 154.12.35.103:3306 # host 网络模式; bridge 模式改为 mysql:3306
Addr: 45.43.29.127:3306 # host 网络模式; bridge 模式改为 mysql:3306
Username: root # MySQL用户名
Password: jpcV41ppanel # MySQL密码,与 .env MYSQL_ROOT_PASSWORD 一致
Dbname: ppanel # MySQL数据库名
Dbname: hifast # MySQL数据库名
Config: charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai
MaxIdleConns: 10
MaxOpenConns: 100
+2
View File
@@ -2,6 +2,7 @@ package invite
import (
"context"
"slices"
modellog "github.com/perfect-panel/server/internal/model/log"
"github.com/perfect-panel/server/pkg/xerr"
@@ -113,6 +114,7 @@ func QueryBenefits(ctx context.Context, db *gorm.DB, relations []InviteRelation)
for userId := range inviteeAndInviterSet {
inviteeAndInviterIds = append(inviteeAndInviterIds, userId)
}
slices.Sort(inviteeAndInviterIds)
if err := fillCommissionBenefits(ctx, db, result, orderToInvitee, inviteeToInviter, orderNos, inviterIds); err != nil {
return nil, err
+2 -2
View File
@@ -25,7 +25,7 @@ func TestQueryBenefitsCountsFamilyOwnerGiftAsInviteeGift(t *testing.T) {
WithArgs(33, int64(100), "family-order", 331, 332).
WillReturnRows(sqlmock.NewRows([]string{"object_id", "content"}))
mock.ExpectQuery("object_id IN").
WithArgs(34, int64(900), int64(200), int64(100), "family-order").
WithArgs(34, int64(100), int64(200), int64(900), "family-order").
WillReturnRows(sqlmock.NewRows([]string{"object_id", "content"}).
AddRow(900, `{"type":341,"order_no":"family-order","amount":7,"balance":7,"remark":"邀请赠送"}`))
@@ -58,7 +58,7 @@ func TestQueryBenefitsKeepsDirectInviteeGift(t *testing.T) {
WithArgs(33, int64(100), "direct-order", 331, 332).
WillReturnRows(sqlmock.NewRows([]string{"object_id", "content"}))
mock.ExpectQuery("object_id IN").
WithArgs(34, int64(200), int64(100), "direct-order").
WithArgs(34, int64(100), int64(200), "direct-order").
WillReturnRows(sqlmock.NewRows([]string{"object_id", "content"}).
AddRow(200, `{"type":341,"order_no":"direct-order","amount":5,"balance":5,"remark":"邀请赠送"}`))
@@ -67,6 +67,17 @@ func (l *RefundOrderLogic) RefundOrder(req *types.RefundOrderRequest) error {
return errors.Wrapf(xerr.NewErrCode(xerr.OrderStatusError), "order %d status %d is not refundable", orderInfo.Id, orderInfo.Status)
}
// 幂等校验:若该 order_no 已存在 333 退款日志,拒绝再次退款。
// HIF-131 案例:订单状态被外部入口(stuckOrderRecovery 把 6 视为卡住的 claim)回退到 5,
// 让 lockCommissionSource 误抓到原始 331/332 amount 再次扣减佣金。
refunded, err := l.hasRefundLog(tx, orderInfo.OrderNo)
if err != nil {
return err
}
if refunded {
return errors.Wrapf(xerr.NewErrCode(xerr.OrderAlreadyRefunded), "order %d already has refund commission log", orderInfo.Id)
}
userSub, err := l.lockRefundTargetSubscription(tx, &orderInfo)
if err != nil {
return err
@@ -256,6 +267,13 @@ func (l *RefundOrderLogic) lockCommissionSource(tx *gorm.DB, orderNo string, ord
return nil, 0, nil
}
// hasRefundLog 检查指定 order_no 是否已有 333 (CommissionTypeRefund) 退款佣金日志。
// 仅扫 type=33 + 内容含 order_no 的命中项,再用 JSON 二次确认 content.type==333
// 防止 content.order_no 子串误判。
func (l *RefundOrderLogic) hasRefundLog(tx *gorm.DB, orderNo string) (bool, error) {
return log.HasRefundCommissionLog(tx, orderNo)
}
func (l *RefundOrderLogic) buildRefundAuditLog(
operator *modeluser.User,
orderInfo *modelorder.Order,
@@ -1,11 +1,23 @@
package order
import (
"context"
"fmt"
"strings"
"testing"
"time"
"github.com/DATA-DOG/go-sqlmock"
"github.com/perfect-panel/server/internal/svc"
modelorder "github.com/perfect-panel/server/internal/model/order"
modeluser "github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/constant"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func TestOrderStatusName(t *testing.T) {
@@ -83,3 +95,155 @@ func TestBuildRefundAuditLog(t *testing.T) {
t.Fatalf("unexpected commission transition: %+v", got)
}
}
// TestRefundOrder_RejectsWhenRefundLogExists 验证 HIF-131 / HIF-132 修复:
// 当 system_logs 已存在该订单的 333 退款佣金日志时,再次调用 RefundOrder 必须:
// 1. 返回 OrderAlreadyRefunded 错误码;
// 2. 不再查询 / 锁定 commission 来源(lockCommissionSource 不应触发);
// 3. 不写入新的 333 日志、不更新 user.commission、不更新 order.status。
//
// 通过 sqlmock 严格定义期望 SQL:只允许出现 BEGIN / SELECT order FOR UPDATE /
// SELECT system_logs(命中 333/ ROLLBACK,不允许出现 commission 锁/更新/插入。
func TestRefundOrder_RejectsWhenRefundLogExists(t *testing.T) {
const (
orderID = int64(53647)
orderNo = "202605301925431836075753253"
operatorUID = int64(519)
)
db, mock, cleanup := newRefundOrderTestDB(t)
defer cleanup()
mock.ExpectBegin()
mock.ExpectQuery("FROM `order`").
WithArgs(orderID, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "order_no", "status", "type", "commission", "user_id"}).
AddRow(orderID, orderNo, uint8(5), uint8(2), int64(2250), int64(72028)))
mock.ExpectQuery("FROM `system_logs`").
WithArgs(uint8(33), fmt.Sprintf(`%%"order_no":"%s"%%`, orderNo)).
WillReturnRows(sqlmock.NewRows([]string{"id", "content"}).
AddRow(1, fmt.Sprintf(`{"type":333,"order_no":"%s","amount":-2250,"timestamp":0}`, orderNo)))
mock.ExpectRollback()
logic := newTestRefundOrderLogic(t, db, operatorUID)
err := logic.RefundOrder(&types.RefundOrderRequest{Id: orderID, Reason: "duplicate"})
if err == nil {
t.Fatalf("RefundOrder expected error, got nil")
}
if !isErrCode(err, xerr.OrderAlreadyRefunded) {
t.Fatalf("RefundOrder error code = %v, want OrderAlreadyRefunded; raw=%v", errCodeOf(err), err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}
// TestRefundOrder_RejectsWhenStatusAlreadyRefunded 覆盖既有 status==6 拒绝路径,
// 确保新增的 333 日志校验不会破坏原有「订单已被标记为退款」短路逻辑。
func TestRefundOrder_RejectsWhenStatusAlreadyRefunded(t *testing.T) {
const (
orderID = int64(1001)
orderNo = "ORD-STATUS-6"
operatorUID = int64(519)
)
db, mock, cleanup := newRefundOrderTestDB(t)
defer cleanup()
mock.ExpectBegin()
mock.ExpectQuery("FROM `order`").
WithArgs(orderID, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "order_no", "status"}).
AddRow(orderID, orderNo, uint8(orderStatusRefunded)))
mock.ExpectRollback()
logic := newTestRefundOrderLogic(t, db, operatorUID)
err := logic.RefundOrder(&types.RefundOrderRequest{Id: orderID})
if !isErrCode(err, xerr.OrderAlreadyRefunded) {
t.Fatalf("RefundOrder error code = %v, want OrderAlreadyRefunded; raw=%v", errCodeOf(err), err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}
// TestRefundOrder_RejectsWhenStatusNotRefundable 覆盖非 2/5 状态短路。
func TestRefundOrder_RejectsWhenStatusNotRefundable(t *testing.T) {
const (
orderID = int64(1002)
orderNo = "ORD-STATUS-1"
operatorUID = int64(519)
)
db, mock, cleanup := newRefundOrderTestDB(t)
defer cleanup()
mock.ExpectBegin()
mock.ExpectQuery("FROM `order`").
WithArgs(orderID, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "order_no", "status"}).
AddRow(orderID, orderNo, uint8(1)))
mock.ExpectRollback()
logic := newTestRefundOrderLogic(t, db, operatorUID)
err := logic.RefundOrder(&types.RefundOrderRequest{Id: orderID})
if !isErrCode(err, xerr.OrderStatusError) {
t.Fatalf("RefundOrder error code = %v, want OrderStatusError; raw=%v", errCodeOf(err), err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}
func newRefundOrderTestDB(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 newTestRefundOrderLogic(t *testing.T, db *gorm.DB, operatorID int64) *RefundOrderLogic {
t.Helper()
ctx := context.WithValue(context.Background(), constant.CtxKeyUser, &modeluser.User{Id: operatorID})
return &RefundOrderLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: &svc.ServiceContext{DB: db},
}
}
// errCodeOf / isErrCode 用于绕开 wrapped error 检查内层 xerr 错误码。
func errCodeOf(err error) uint32 {
if err == nil {
return 0
}
type coder interface {
GetErrCode() uint32
}
cause := errors.Cause(err)
if c, ok := cause.(coder); ok {
return c.GetErrCode()
}
return 0
}
func isErrCode(err error, code uint32) bool {
return errCodeOf(err) == code
}
@@ -12,7 +12,11 @@ import (
"gorm.io/gorm"
)
type fakePromoModel struct{}
type fakePromoModel struct {
insertRule func(context.Context, *promomodel.Rule) error
findRule func(context.Context, int64) (*promomodel.Rule, error)
updateRule func(context.Context, *promomodel.Rule) error
}
func (fakePromoModel) QueryEligibleRules(context.Context, int64, int64) ([]*promomodel.RuleWithPrice, error) {
return nil, nil
@@ -22,15 +26,24 @@ func (fakePromoModel) InsertUsage(context.Context, *promomodel.Usage, ...*gorm.D
return nil
}
func (fakePromoModel) InsertRule(context.Context, *promomodel.Rule) error {
func (m fakePromoModel) InsertRule(ctx context.Context, rule *promomodel.Rule) error {
if m.insertRule != nil {
return m.insertRule(ctx, rule)
}
return nil
}
func (fakePromoModel) FindRule(context.Context, int64) (*promomodel.Rule, error) {
func (m fakePromoModel) FindRule(ctx context.Context, id int64) (*promomodel.Rule, error) {
if m.findRule != nil {
return m.findRule(ctx, id)
}
return nil, gorm.ErrRecordNotFound
}
func (fakePromoModel) UpdateRule(context.Context, *promomodel.Rule) error {
func (m fakePromoModel) UpdateRule(ctx context.Context, rule *promomodel.Rule) error {
if m.updateRule != nil {
return m.updateRule(ctx, rule)
}
return nil
}
@@ -0,0 +1,133 @@
package promo
import (
"context"
"testing"
"time"
promomodel "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/pkg/xerr"
pkgerrors "github.com/pkg/errors"
"github.com/redis/go-redis/v9"
)
func TestCreateRuleAcceptsMillisecondTimestamps(t *testing.T) {
startTime := int64(1777618800000)
endTime := int64(1782802800000)
var inserted *promomodel.Rule
svcCtx := &svc.ServiceContext{
Redis: redis.NewClient(&redis.Options{Addr: "127.0.0.1:0"}),
PromoModel: fakePromoModel{
insertRule: func(_ context.Context, rule *promomodel.Rule) error {
inserted = rule
return nil
},
},
}
_, err := NewCreateRuleLogic(context.Background(), svcCtx).CreateRule(&types.CreatePromoRuleRequest{
Name: "618活动",
Type: promomodel.RuleTypeInactiveUser,
Params: map[string]interface{}{"inactive_months": float64(1)},
Priority: 0,
StartTime: &startTime,
EndTime: &endTime,
})
if err != nil {
t.Fatalf("CreateRule returned error: %v", err)
}
if inserted == nil {
t.Fatal("rule was not inserted")
}
assertPromoRuleTime(t, inserted.StartTime, time.UnixMilli(startTime))
assertPromoRuleTime(t, inserted.EndTime, time.UnixMilli(endTime))
}
func TestUpdateRuleAcceptsMillisecondTimestamps(t *testing.T) {
startTime := int64(1777618800000)
endTime := int64(1782802800000)
existing := &promomodel.Rule{Id: 9, Enabled: true}
var updated *promomodel.Rule
svcCtx := &svc.ServiceContext{
Redis: redis.NewClient(&redis.Options{Addr: "127.0.0.1:0"}),
PromoModel: fakePromoModel{
findRule: func(_ context.Context, id int64) (*promomodel.Rule, error) {
if id != existing.Id {
t.Fatalf("FindRule id = %d, want %d", id, existing.Id)
}
return existing, nil
},
updateRule: func(_ context.Context, rule *promomodel.Rule) error {
updated = rule
return nil
},
},
}
_, err := NewUpdateRuleLogic(context.Background(), svcCtx).UpdateRule(&types.UpdatePromoRuleRequest{
Id: existing.Id,
Name: "618活动",
Type: promomodel.RuleTypeInactiveUser,
Params: map[string]interface{}{"inactive_months": float64(1)},
Priority: 0,
StartTime: &startTime,
EndTime: &endTime,
})
if err != nil {
t.Fatalf("UpdateRule returned error: %v", err)
}
if updated == nil {
t.Fatal("rule was not updated")
}
assertPromoRuleTime(t, updated.StartTime, time.UnixMilli(startTime))
assertPromoRuleTime(t, updated.EndTime, time.UnixMilli(endTime))
}
func TestRuleRejectsOutOfRangeTimestamp(t *testing.T) {
startTime := int64(253402300800000)
endTime := int64(253402304400000)
svcCtx := &svc.ServiceContext{PromoModel: fakePromoModel{
insertRule: func(context.Context, *promomodel.Rule) error {
t.Fatal("InsertRule should not be called for invalid timestamp")
return nil
},
}}
_, err := NewCreateRuleLogic(context.Background(), svcCtx).CreateRule(&types.CreatePromoRuleRequest{
Name: "bad time",
Type: promomodel.RuleTypeInactiveUser,
Params: map[string]interface{}{"inactive_months": float64(1)},
Priority: 0,
StartTime: &startTime,
EndTime: &endTime,
})
assertInvalidParams(t, err)
}
func assertPromoRuleTime(t *testing.T, got *time.Time, want time.Time) {
t.Helper()
if got == nil {
t.Fatalf("time is nil, want %v", want)
}
if !got.Equal(want) {
t.Fatalf("time = %v, want %v", *got, want)
}
}
func assertInvalidParams(t *testing.T, err error) {
t.Helper()
if err == nil {
t.Fatal("expected error")
}
codeErr, ok := pkgerrors.Cause(err).(*xerr.CodeError)
if !ok {
t.Fatalf("expected CodeError, got %T", pkgerrors.Cause(err))
}
if got := codeErr.GetErrCode(); got != xerr.InvalidParams {
t.Fatalf("error code = %d, want %d", got, xerr.InvalidParams)
}
}
+34 -4
View File
@@ -17,11 +17,24 @@ const (
subscribeCachePref = "promo:subscribe:"
)
var (
minPromoRuleTime = time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)
maxPromoRuleTime = time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)
)
func validateRuleInput(ruleType string, params map[string]interface{}, priority int64, startTime, endTime *int64) error {
if priority < 0 {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "priority must be greater than or equal to 0")
}
if startTime != nil && endTime != nil && *startTime >= *endTime {
startAt, err := normalizeRuleTimestamp(startTime)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "invalid start_time")
}
endAt, err := normalizeRuleTimestamp(endTime)
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "invalid end_time")
}
if startAt != nil && endAt != nil && !startAt.Before(*endAt) {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "start_time must be less than end_time")
}
switch ruleType {
@@ -93,12 +106,29 @@ func parseParams(data string) map[string]interface{} {
return params
}
func unixPtrToTimePtr(ts *int64) *time.Time {
func normalizeRuleTimestamp(ts *int64) (*time.Time, error) {
if ts == nil || *ts == 0 {
return nil, nil
}
value := *ts
var t time.Time
if value >= 1_000_000_000_000 || value <= -1_000_000_000_000 {
t = time.UnixMilli(value)
} else {
t = time.Unix(value, 0)
}
if t.Before(minPromoRuleTime) || t.After(maxPromoRuleTime) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "timestamp out of range")
}
return &t, nil
}
func unixPtrToTimePtr(ts *int64) *time.Time {
t, err := normalizeRuleTimestamp(ts)
if err != nil {
return nil
}
t := time.Unix(*ts, 0)
return &t
return t
}
func timePtrToUnixPtr(t *time.Time) *int64 {
+33
View File
@@ -0,0 +1,33 @@
package common
import (
"context"
"github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
)
// HasPaidSubscription reports whether the user owns at least one paid
// subscription record — order-backed (order_id > 0) or Apple-IAP-backed
// (token LIKE 'iap:%'). Returns false when userID or db are not usable so
// callers can fall back to the "first purchase" branch safely.
//
// This mirrors the predicate used to route /v1/public/order/purchase requests
// to renewal semantics. Keep both in sync.
func HasPaidSubscription(ctx context.Context, db *gorm.DB, userID int64) (bool, error) {
if userID <= 0 || db == nil {
return false, nil
}
var count int64
if err := db.WithContext(ctx).
Model(&user.Subscribe{}).
Where("user_id = ? AND (order_id > 0 OR token LIKE 'iap:%')", userID).
Limit(1).
Count(&count).Error; err != nil {
return false, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query paid subscription failed: %v", err.Error())
}
return count > 0, nil
}
+14 -4
View File
@@ -28,7 +28,16 @@ type promoRuleParams struct {
InactiveMonths int `json:"inactive_months"`
}
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID int64, quantity int64) (*PromoResult, error) {
// EvaluatePromo decides whether the given (user, subscribe, quantity) tuple
// qualifies for any active promo rule. Each rule type has its own gating:
// - new_user: requires isFirstPurchase=true (no prior paid subscription)
// - inactive_user: requires a previously expired subscription (rule self-check)
// - campaign: applies unconditionally within the configured time window
//
// Pass isFirstPurchase=true on order paths where the request is being routed
// as a brand-new purchase; pass false when the user already has a paid
// subscription (including expired ones) so NewUser cannot be reused.
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID int64, quantity int64, isFirstPurchase bool) (*PromoResult, error) {
result := &PromoResult{}
if svcCtx == nil || svcCtx.PromoModel == nil || svcCtx.DB == nil || subscribeID <= 0 || quantity <= 0 {
return result, nil
@@ -59,7 +68,7 @@ func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64
}
}
eligible, expiresAt, err := evaluatePromoRule(ctx, svcCtx.DB, rule, params, userID, &currentUser, now)
eligible, expiresAt, err := evaluatePromoRule(ctx, svcCtx.DB, rule, params, userID, isFirstPurchase, &currentUser, now)
if err != nil {
return nil, err
}
@@ -96,12 +105,13 @@ func evaluatePromoRule(
rule *promo.RuleWithPrice,
params promoRuleParams,
userID int64,
isFirstPurchase bool,
currentUser *user.User,
now time.Time,
) (bool, time.Time, error) {
switch rule.Type {
case promo.RuleTypeNewUser:
if userID <= 0 {
if userID <= 0 || !isFirstPurchase {
return false, time.Time{}, nil
}
return evaluateNewUserPromo(ctx, db, params, userID, currentUser, now)
@@ -165,7 +175,7 @@ func evaluateInactiveUserPromo(
Take(&lastSub).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return true, ruleExpiresAt, nil
return false, time.Time{}, nil
}
return false, time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo inactive user subscription failed")
}
+108 -1
View File
@@ -2,9 +2,13 @@ package common
import (
"context"
"regexp"
"testing"
"time"
"github.com/DATA-DOG/go-sqlmock"
"gorm.io/driver/mysql"
"github.com/perfect-panel/server/internal/model/promo"
"github.com/perfect-panel/server/internal/svc"
"gorm.io/gorm"
@@ -65,7 +69,7 @@ func TestEvaluatePromoAllowsAnonymousCampaign(t *testing.T) {
},
}}
got, err := EvaluatePromo(context.Background(), &svc.ServiceContext{DB: &gorm.DB{}, PromoModel: model}, 0, 7, 12)
got, err := EvaluatePromo(context.Background(), &svc.ServiceContext{DB: &gorm.DB{}, PromoModel: model}, 0, 7, 12, true)
if err != nil {
t.Fatalf("EvaluatePromo returned error: %v", err)
}
@@ -86,6 +90,90 @@ func TestEvaluatePromoAllowsAnonymousCampaign(t *testing.T) {
}
}
func TestEvaluatePromoCampaignAppliesToReturningUsers(t *testing.T) {
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
{
Rule: promo.Rule{
Id: 4,
Name: "campaign",
Type: promo.RuleTypeCampaign,
Enabled: true,
},
PromoPrice: 299,
},
}}
got, err := EvaluatePromo(context.Background(), &svc.ServiceContext{DB: &gorm.DB{}, PromoModel: model}, 42, 7, 1, false)
if err != nil {
t.Fatalf("EvaluatePromo returned error: %v", err)
}
if !got.Eligible {
t.Fatal("campaign promo should remain eligible for returning users (isFirstPurchase=false)")
}
if got.PromoPrice != 299 {
t.Fatalf("PromoPrice = %d, want 299", got.PromoPrice)
}
}
func TestEvaluatePromoNewUserRequiresFirstPurchase(t *testing.T) {
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
{
Rule: promo.Rule{
Id: 5,
Name: "new user",
Type: promo.RuleTypeNewUser,
Enabled: true,
Params: `{"window_hours": 72}`,
},
PromoPrice: 99,
},
}}
got, err := EvaluatePromo(context.Background(), &svc.ServiceContext{DB: &gorm.DB{}, PromoModel: model}, 42, 7, 1, false)
if err != nil {
t.Fatalf("EvaluatePromo returned error: %v", err)
}
if got.Eligible {
t.Fatal("new-user promo must be gated out when isFirstPurchase=false (user already has paid subscriptions)")
}
}
func TestEvaluatePromoRejectsInactiveRuleWhenUserHasNoSubscription(t *testing.T) {
db, mock, cleanup := newCommonPromoTestDB(t)
defer cleanup()
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
{
Rule: promo.Rule{
Id: 9,
Name: "inactive",
Type: promo.RuleTypeInactiveUser,
Params: `{"inactive_months":3}`,
Enabled: true,
},
PromoPrice: 100,
},
}}
mock.ExpectQuery(regexp.QuoteMeta("SELECT * FROM `user_subscribe` WHERE user_id = ? ORDER BY CASE WHEN expire_time = ? THEN 0 ELSE 1 END, expire_time DESC LIMIT ?")).
WithArgs(int64(51640), time.UnixMilli(0), 1).
WillReturnError(gorm.ErrRecordNotFound)
got, err := EvaluatePromo(context.Background(), &svc.ServiceContext{DB: db, PromoModel: model}, 51640, 1, 30, true)
if err != nil {
t.Fatalf("EvaluatePromo returned error: %v", err)
}
if got.Eligible {
t.Fatal("new user without subscription history should not be eligible for inactive promo")
}
if got.RuleID != 0 || got.PromoPrice != 0 {
t.Fatalf("promo fields = (%d, %d), want zero values", got.RuleID, got.PromoPrice)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet db expectations: %v", err)
}
}
type fakePromoModel struct {
rules []*promo.RuleWithPrice
lastSubscribeID int64
@@ -145,3 +233,22 @@ func (m *fakePromoModel) QueryUsageList(context.Context, promo.UsageFilter) (int
func (m *fakePromoModel) Transaction(context.Context, func(*gorm.DB) error) error {
return nil
}
func newCommonPromoTestDB(t *testing.T) (*gorm.DB, sqlmock.Sqlmock, func()) {
t.Helper()
sqlDB, mock, err := sqlmock.New()
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()
}
}
+89 -7
View File
@@ -13,6 +13,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/hibiken/asynq"
"github.com/perfect-panel/server/internal/model/order"
"github.com/perfect-panel/server/internal/model/payment"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
@@ -22,6 +23,47 @@ import (
queueType "github.com/perfect-panel/server/queue/types"
)
// epayNotifyTradeNotSuccess identifies the "buyer paid but trade not in TRADE_SUCCESS
// terminal state" branch in metrics / log search. EPay is told 200 here so it will
// not retry; we still want it visible for monitoring (HIF-135 / HIF-136).
const epayNotifyTradeNotSuccess = "epay_notify_trade_not_success"
// epayNotifyDecision encodes the post-parse decision so the branching logic can be
// unit-tested without spinning up a real OrderModel / Redis / asynq stack.
type epayNotifyDecision int
const (
// epayNotifyDecisionRejectSign: signature is invalid and debug bypass is off.
// Caller MUST return an error so the handler responds non-200 and EPay retries.
epayNotifyDecisionRejectSign epayNotifyDecision = iota
// epayNotifyDecisionAckTradeNotSuccess: trade_status != TRADE_SUCCESS
// (user cancelled / failed at gateway). Acknowledge with 200 "success" and emit
// a metric-named log for monitoring.
epayNotifyDecisionAckTradeNotSuccess
// epayNotifyDecisionAckIdempotent: order already at Finished (status=5).
// Repeat callback — ack with 200 "success", do not re-enqueue activation.
epayNotifyDecisionAckIdempotent
// epayNotifyDecisionProcess: happy path. Write trade_no, flip status to Paid,
// enqueue activation task.
epayNotifyDecisionProcess
)
// evaluateEPayNotify is a pure decision function so each branch can be unit-tested
// without DB/Redis. Caller has already located the order; orderStatus is the
// current status from the DB row.
func evaluateEPayNotify(signValid, debugBypass bool, tradeStatus string, orderStatus uint8) epayNotifyDecision {
if !signValid && !debugBypass {
return epayNotifyDecisionRejectSign
}
if tradeStatus != "TRADE_SUCCESS" {
return epayNotifyDecisionAckTradeNotSuccess
}
if orderStatus == 5 {
return epayNotifyDecisionAckIdempotent
}
return epayNotifyDecisionProcess
}
type EPayNotifyLogic struct {
logger.Logger
ctx *gin.Context
@@ -47,6 +89,8 @@ func (l *EPayNotifyLogic) EPayNotify(req *types.EPayNotifyRequest) error {
}
orderInfo, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OutTradeNo)
if err != nil {
// HIF-136 P02: order missing must propagate as error so EPay retries instead
// of being silently lost (was previously masked by a `return nil` further down).
l.Logger.Error("[EPayNotify] Find order failed", logger.Field("error", err.Error()), logger.Field("orderNo", req.OutTradeNo))
return errors.Wrapf(xerr.NewErrCode(xerr.OrderNotExist), "order not exist: %v", req.OutTradeNo)
}
@@ -65,17 +109,54 @@ func (l *EPayNotifyLogic) EPayNotify(req *types.EPayNotifyRequest) error {
}
// Verify sign
client := epay.NewClient(config.Pid, config.Url, config.Key, config.Type)
if !client.VerifySign(urlParamsToMap(l.ctx.Request.URL.RawQuery)) && !l.svcCtx.Config.Debug {
l.Logger.Error("[EPayNotify] Verify sign failed")
signValid := client.VerifySign(urlParamsToMap(l.ctx.Request.URL.RawQuery))
decision := evaluateEPayNotify(signValid, l.svcCtx.Config.Debug, req.TradeStatus, orderInfo.Status)
switch decision {
case epayNotifyDecisionRejectSign:
// HIF-136 P01: previously `return nil` here let EPay see 200 and stop retrying;
// caller still left order at status=1, which DeferCloseOrder then closed.
// Return error so handler responds non-200 and EPay retries.
l.Logger.Error("[EPayNotify] Verify sign failed",
logger.Field("order_no", req.OutTradeNo),
logger.Field("trade_no", req.TradeNo),
logger.Field("raw_query", l.ctx.Request.URL.RawQuery),
)
return errors.Wrapf(xerr.NewErrCode(xerr.SignatureInvalid), "verify sign failed: %v", req.OutTradeNo)
case epayNotifyDecisionAckTradeNotSuccess:
// User cancelled / gateway-side failure: ack 200 to stop retries, but keep
// the path observable under metric name `epay_notify_trade_not_success`.
l.Logger.Info("[EPayNotify] Trade status not success",
logger.Field("order_no", req.OutTradeNo),
logger.Field("trade_status", req.TradeStatus),
logger.Field("metric", epayNotifyTradeNotSuccess),
)
return nil
}
if req.TradeStatus != "TRADE_SUCCESS" {
l.Logger.Error("[EPayNotify] Trade status is not success", logger.Field("orderNo", req.OutTradeNo), logger.Field("tradeStatus", req.TradeStatus))
case epayNotifyDecisionAckIdempotent:
// Order already Finished — repeat callback is expected, ack with 200.
return nil
case epayNotifyDecisionProcess:
// fall through
}
if orderInfo.Status == 5 {
return nil
// HIF-136 P03: persist gateway trade_no BEFORE flipping status so post-mortems can
// reverse-lookup EPay flows to ppanel orders. Raw gorm write is acceptable here —
// the subsequent UpdateOrderStatus will invalidate the cache key (keys are by
// order_no / id, both stable across this field write).
if req.TradeNo != "" {
if err := l.svcCtx.DB.WithContext(l.ctx).
Model(&order.Order{}).
Where("order_no = ?", req.OutTradeNo).
Update("trade_no", req.TradeNo).Error; err != nil {
l.Logger.Error("[EPayNotify] Update trade_no failed",
logger.Field("error", err.Error()),
logger.Field("order_no", req.OutTradeNo),
logger.Field("trade_no", req.TradeNo),
)
return errors.Wrapf(err, "update trade_no failed: %v", req.OutTradeNo)
}
}
// Update order status
err = l.svcCtx.OrderModel.UpdateOrderStatus(l.ctx, req.OutTradeNo, 2)
if err != nil {
@@ -86,6 +167,7 @@ func (l *EPayNotifyLogic) EPayNotify(req *types.EPayNotifyRequest) error {
"[SubscriptionFlow] epay notify marked order as paid",
append(commonLogic.OrderTraceFields(orderInfo),
logger.Field("payment_platform", data.Platform),
logger.Field("trade_no", req.TradeNo),
)...,
)
// Create activate order task
@@ -0,0 +1,182 @@
package notify
import (
"context"
"fmt"
"strings"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/perfect-panel/server/internal/model/order"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// TestEvaluateEPayNotify_RejectsInvalidSign covers HIF-136 P01: sign invalid +
// debug bypass off must return rejectSign so the handler responds non-200 and
// EPay retries (was previously a silent `return nil` → 200 → no retry).
func TestEvaluateEPayNotify_RejectsInvalidSign(t *testing.T) {
got := evaluateEPayNotify(false, false, "TRADE_SUCCESS", 1)
if got != epayNotifyDecisionRejectSign {
t.Fatalf("evaluateEPayNotify(invalid sign): got %v want %v", got, epayNotifyDecisionRejectSign)
}
}
// TestEvaluateEPayNotify_DebugBypassAllowsInvalidSign documents the debug-mode
// escape hatch the issue calls out: production runs with Debug=false so this
// branch is never taken in prod, but local/dev should still flow through.
func TestEvaluateEPayNotify_DebugBypassAllowsInvalidSign(t *testing.T) {
got := evaluateEPayNotify(false, true, "TRADE_SUCCESS", 1)
if got != epayNotifyDecisionProcess {
t.Fatalf("evaluateEPayNotify(invalid sign + debug): got %v want %v", got, epayNotifyDecisionProcess)
}
}
// TestEvaluateEPayNotify_TradeNotSuccess covers the user-cancelled / gateway-failure
// branch: behaviour unchanged (return nil → 200), but caller must now emit the
// `epay_notify_trade_not_success` metric-named log instead of an Error-level one.
func TestEvaluateEPayNotify_TradeNotSuccess(t *testing.T) {
tests := []string{"TRADE_FAILED", "WAIT_BUYER_PAY", ""}
for _, ts := range tests {
t.Run(ts, func(t *testing.T) {
got := evaluateEPayNotify(true, false, ts, 1)
if got != epayNotifyDecisionAckTradeNotSuccess {
t.Fatalf("evaluateEPayNotify(trade_status=%q): got %v want %v",
ts, got, epayNotifyDecisionAckTradeNotSuccess)
}
})
}
}
// TestEvaluateEPayNotify_IdempotentForFinishedOrder covers the only legitimate
// `return nil` short-circuit retained by HIF-136: duplicate callback for an
// already Finished (status=5) order is acknowledged with 200 instead of being
// re-processed.
func TestEvaluateEPayNotify_IdempotentForFinishedOrder(t *testing.T) {
got := evaluateEPayNotify(true, false, "TRADE_SUCCESS", 5)
if got != epayNotifyDecisionAckIdempotent {
t.Fatalf("evaluateEPayNotify(status=5): got %v want %v", got, epayNotifyDecisionAckIdempotent)
}
}
// TestEvaluateEPayNotify_HappyPath covers the normal success branch: valid sign,
// trade_status=TRADE_SUCCESS, order not yet Finished → proceed to write trade_no
// + flip status + enqueue activation.
func TestEvaluateEPayNotify_HappyPath(t *testing.T) {
statuses := []uint8{1, 2, 3, 4} // anything but Finished(5)
for _, s := range statuses {
got := evaluateEPayNotify(true, false, "TRADE_SUCCESS", s)
if got != epayNotifyDecisionProcess {
t.Fatalf("evaluateEPayNotify(status=%d): got %v want %v", s, got, epayNotifyDecisionProcess)
}
}
}
// TestEvaluateEPayNotify_SignTakesPrecedenceOverIdempotency guards against a
// regression where a duplicate callback with a forged signature gets quietly
// acked because status==5 was checked before sign.
func TestEvaluateEPayNotify_SignTakesPrecedenceOverIdempotency(t *testing.T) {
got := evaluateEPayNotify(false, false, "TRADE_SUCCESS", 5)
if got != epayNotifyDecisionRejectSign {
t.Fatalf("evaluateEPayNotify(invalid sign + status=5): got %v want %v",
got, epayNotifyDecisionRejectSign)
}
}
// TestUrlParamsToMap verifies the helper used to feed VerifySign — collapses
// each query parameter to its first value and treats absent params as missing.
func TestUrlParamsToMap(t *testing.T) {
got := urlParamsToMap("pid=1001&out_trade_no=ORD-1&trade_no=EPAY-9&sign=abc&trade_status=TRADE_SUCCESS")
want := map[string]string{
"pid": "1001",
"out_trade_no": "ORD-1",
"trade_no": "EPAY-9",
"sign": "abc",
"trade_status": "TRADE_SUCCESS",
}
if len(got) != len(want) {
t.Fatalf("urlParamsToMap len = %d want %d (got=%v)", len(got), len(want), got)
}
for k, v := range want {
if got[k] != v {
t.Fatalf("urlParamsToMap[%q] = %q want %q", k, got[k], v)
}
}
}
// TestEPayNotify_TradeNoRawWrite verifies HIF-136 P03 at the SQL boundary: the
// raw gorm write hits the `order` table with the exact `trade_no` from the
// EPay request, scoped by `order_no`, and surfaces driver errors back to the
// caller (so they propagate as non-200 and EPay retries).
func TestEPayNotify_TradeNoRawWrite(t *testing.T) {
db, mock, cleanup := newEPayNotifyTestDB(t)
defer cleanup()
const (
orderNo = "202606010001"
tradeNo = "EPAY-202606010001"
)
mock.ExpectBegin()
mock.ExpectExec("UPDATE `order` SET `trade_no`").
WithArgs(tradeNo, sqlmock.AnyArg(), orderNo).
WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectCommit()
err := db.WithContext(context.Background()).
Model(&order.Order{}).
Where("order_no = ?", orderNo).
Update("trade_no", tradeNo).Error
if err != nil {
t.Fatalf("raw trade_no update: %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}
// TestEPayNotify_TradeNoRawWritePropagatesError ensures a DB-side failure during
// the trade_no backfill is not swallowed — caller returns the error so EPay
// retries instead of silently flipping status without trade_no being written.
func TestEPayNotify_TradeNoRawWritePropagatesError(t *testing.T) {
db, mock, cleanup := newEPayNotifyTestDB(t)
defer cleanup()
mock.ExpectBegin()
mock.ExpectExec("UPDATE `order` SET `trade_no`").
WillReturnError(fmt.Errorf("deadlock detected"))
mock.ExpectRollback()
err := db.WithContext(context.Background()).
Model(&order.Order{}).
Where("order_no = ?", "ORD-2").
Update("trade_no", "EPAY-2").Error
if err == nil {
t.Fatalf("expected error from raw trade_no update, got nil")
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}
func newEPayNotifyTestDB(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()
}
}
+259 -46
View File
@@ -5,9 +5,12 @@ import (
"encoding/json"
"time"
"github.com/hibiken/asynq"
"github.com/perfect-panel/server/internal/model/log"
"github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/pkg/payment/epay"
"github.com/perfect-panel/server/pkg/payment/stripe"
queueTypes "github.com/perfect-panel/server/queue/types"
"gorm.io/gorm"
"github.com/perfect-panel/server/internal/model/order"
@@ -18,19 +21,52 @@ import (
"github.com/perfect-panel/server/pkg/payment/alipay"
)
// GatewayPaymentStatus is the tri-state result of an external payment-gateway
// query. The third state (Unknown) is the whole point of HIF-137: when the
// gateway is unreachable or returns an inconclusive answer we must NOT collapse
// it to "unpaid" — that's exactly the bug that closes already-paid orders.
type GatewayPaymentStatus int
const (
// GatewayStatusUnknown — the gateway query itself failed (timeout, 5xx,
// network error, decode error) or the payment method has no gateway we can
// query. The caller must treat this as "do not close, retry later".
GatewayStatusUnknown GatewayPaymentStatus = iota
// GatewayStatusPaid — the gateway confirms the user has paid.
GatewayStatusPaid
// GatewayStatusUnpaid — the gateway confirms the order is unpaid /
// cancelled / closed on its side. Safe to close locally.
GatewayStatusUnpaid
)
type CloseOrderLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
// Test seams (injected via overrides on the returned struct). Production
// code never touches these — NewCloseOrderLogic wires the real impls.
gatewayQuery func(*order.Order) GatewayPaymentStatus
enqueueActivate func(context.Context, []byte) (string, error)
}
// NewCloseOrderLogic Close order
func NewCloseOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CloseOrderLogic {
return &CloseOrderLogic{
l := &CloseOrderLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
l.gatewayQuery = l.queryGatewayPaymentStatus
l.enqueueActivate = func(c context.Context, payload []byte) (string, error) {
task := asynq.NewTask(queueTypes.ForthwithActivateOrder, payload, asynq.MaxRetry(5))
info, err := svcCtx.Queue.EnqueueContext(c, task)
if err != nil {
return "", err
}
return info.ID, nil
}
return l
}
func (l *CloseOrderLogic) CloseOrder(req *types.CloseOrderRequest) error {
@@ -52,6 +88,31 @@ func (l *CloseOrderLogic) CloseOrder(req *types.CloseOrderRequest) error {
return nil
}
// HIF-137: before closing a pending order, ask the gateway whether it was
// actually paid. Silent callback failures must not cause us to close a
// paid order. Three branches:
// - Paid → recover to status=2 + enqueue activation (do NOT close)
// - Unpaid → fall through to the normal close flow
// - Unknown → keep status=1 and let DeferCloseOrder retry on the next tick
switch l.gatewayQuery(orderInfo) {
case GatewayStatusPaid:
return l.recoverPaidOrder(orderInfo)
case GatewayStatusUnknown:
l.Errorw("[CloseOrder] gateway query inconclusive — keeping order open (metric=close_gateway_error_kept_open)",
logger.Field("metric", "close_gateway_error_kept_open"),
logger.Field("orderNo", orderInfo.OrderNo),
logger.Field("method", orderInfo.Method),
logger.Field("trade_no", orderInfo.TradeNo),
)
return nil
}
l.Infow("[CloseOrder] gateway confirmed unpaid — proceeding with normal close (metric=close_normal)",
logger.Field("metric", "close_normal"),
logger.Field("orderNo", orderInfo.OrderNo),
logger.Field("method", orderInfo.Method),
)
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, orderInfo.SubscribeId)
if err != nil {
l.Errorw("[CloseOrder] Find subscribe info failed",
@@ -166,42 +227,117 @@ func (l *CloseOrderLogic) CloseOrder(req *types.CloseOrderRequest) error {
return nil
}
// confirmationPayment Determine whether the payment is successful
//
//nolint:unused
func (l *CloseOrderLogic) confirmationPayment(order *order.Order) bool {
paymentConfig, err := l.svcCtx.PaymentModel.FindOne(l.ctx, order.PaymentId)
// recoverPaidOrder is the "gateway said paid" branch: flip the order to
// status=2 (paid), persist the trade_no if we have one, and enqueue the same
// activation task the notify handlers would have enqueued. We deliberately
// reuse ForthwithActivateOrder so the rest of the activation pipeline
// (idempotency, claim/release, commission, etc.) stays untouched.
func (l *CloseOrderLogic) recoverPaidOrder(orderInfo *order.Order) error {
updates := map[string]any{"status": 2}
if orderInfo.TradeNo != "" {
updates["trade_no"] = orderInfo.TradeNo
}
// Race-safe: only flip 1→2. If another worker already moved the order
// forward (e.g. a late notify finally landed), do nothing.
result := l.svcCtx.DB.WithContext(l.ctx).
Model(&order.Order{}).
Where("order_no = ? AND status = ?", orderInfo.OrderNo, 1).
Updates(updates)
if result.Error != nil {
l.Errorw("[CloseOrder] gateway-paid recovery update failed — keeping order open",
logger.Field("metric", "close_gateway_error_kept_open"),
logger.Field("error", result.Error.Error()),
logger.Field("orderNo", orderInfo.OrderNo),
)
return nil
}
if result.RowsAffected == 0 {
l.Infow("[CloseOrder] gateway-paid recovery skipped — order already moved past status=1",
logger.Field("orderNo", orderInfo.OrderNo),
)
return nil
}
payload := queueTypes.ForthwithActivateOrderPayload{OrderNo: orderInfo.OrderNo}
bytes, err := json.Marshal(&payload)
if err != nil {
l.Errorw("[CloseOrder] Find payment config failed", logger.Field("error", err.Error()), logger.Field("paymentMark", order.Method))
return false
l.Errorw("[CloseOrder] marshal activation payload failed",
logger.Field("error", err.Error()),
logger.Field("orderNo", orderInfo.OrderNo),
)
return nil
}
switch order.Method {
case AlipayF2f:
if l.queryAlipay(paymentConfig, order.TradeNo) {
return true
}
case StripeAlipay:
if l.queryStripe(paymentConfig, order.TradeNo) {
return true
}
case StripeWeChatPay:
if l.queryStripe(paymentConfig, order.TradeNo) {
return true
}
default:
l.Infow("[CloseOrder] Unsupported payment method", logger.Field("paymentMethod", order.Method))
taskID, err := l.enqueueActivate(l.ctx, bytes)
if err != nil {
// Order is already at status=2; if enqueue fails the stuck-order
// recovery sweeper will pick it up. Log loudly but don't error out.
l.Errorw("[CloseOrder] enqueue activation task failed after gateway-paid recovery",
logger.Field("error", err.Error()),
logger.Field("orderNo", orderInfo.OrderNo),
)
return nil
}
return false
l.Infow("[CloseOrder] gateway-paid recovery succeeded — order promoted to paid + activation enqueued (metric=close_with_gateway_paid_recovered)",
logger.Field("metric", "close_with_gateway_paid_recovered"),
logger.Field("orderNo", orderInfo.OrderNo),
logger.Field("method", orderInfo.Method),
logger.Field("trade_no", orderInfo.TradeNo),
logger.Field("queue_task_id", taskID),
)
return nil
}
// queryAlipay Query Alipay payment status
//
//nolint:unused
func (l *CloseOrderLogic) queryAlipay(paymentConfig *payment.Payment, TradeNo string) bool {
// queryGatewayPaymentStatus dispatches to the right gateway client for the
// order's payment method and returns a tri-state result. Methods without an
// external gateway (Balance, unknown) return Unpaid — the historical close
// path is preserved for them.
func (l *CloseOrderLogic) queryGatewayPaymentStatus(orderInfo *order.Order) GatewayPaymentStatus {
switch orderInfo.Method {
case AlipayF2f:
return l.queryAlipay(orderInfo)
case StripeAlipay, StripeWeChatPay:
return l.queryStripe(orderInfo)
case Epay:
return l.queryEpay(orderInfo)
case Balance:
// Balance is settled in-process; no external gateway to ask. If status=1
// here, the balance deduction simply never completed — safe to close.
return GatewayStatusUnpaid
default:
l.Infow("[CloseOrder] no gateway query for method — falling back to close",
logger.Field("method", orderInfo.Method),
logger.Field("orderNo", orderInfo.OrderNo),
)
return GatewayStatusUnpaid
}
}
// queryAlipay queries Alipay F2F and maps the response to a tri-state.
// "trade not exist" on Alipay's side is treated as Unpaid (the user never
// completed the QR-code scan), not Unknown.
func (l *CloseOrderLogic) queryAlipay(orderInfo *order.Order) GatewayPaymentStatus {
if orderInfo.TradeNo == "" {
// Alipay F2F creates the trade lazily — no trade_no means the user
// never scanned. Treat as definitively unpaid.
return GatewayStatusUnpaid
}
paymentConfig, err := l.svcCtx.PaymentModel.FindOne(l.ctx, orderInfo.PaymentId)
if err != nil {
l.Errorw("[CloseOrder] Find payment config failed",
logger.Field("error", err.Error()),
logger.Field("paymentMark", orderInfo.Method),
)
return GatewayStatusUnknown
}
config := payment.AlipayF2FConfig{}
if err := json.Unmarshal([]byte(paymentConfig.Config), &config); err != nil {
l.Errorw("[CloseOrder] Unmarshal payment config failed", logger.Field("error", err.Error()), logger.Field("config", paymentConfig.Config))
return false
l.Errorw("[CloseOrder] Unmarshal Alipay config failed",
logger.Field("error", err.Error()),
logger.Field("orderNo", orderInfo.OrderNo),
)
return GatewayStatusUnknown
}
client := alipay.NewClient(alipay.Config{
AppId: config.AppId,
@@ -209,35 +345,112 @@ func (l *CloseOrderLogic) queryAlipay(paymentConfig *payment.Payment, TradeNo st
PublicKey: config.PublicKey,
InvoiceName: config.InvoiceName,
})
status, err := client.QueryTrade(l.ctx, TradeNo)
if client == nil {
return GatewayStatusUnknown
}
status, err := client.QueryTrade(l.ctx, orderInfo.TradeNo)
if err != nil {
l.Errorw("[CloseOrder] Query trade failed", logger.Field("error", err.Error()), logger.Field("TradeNo", TradeNo))
return false
l.Errorw("[CloseOrder] Alipay QueryTrade failed",
logger.Field("error", err.Error()),
logger.Field("orderNo", orderInfo.OrderNo),
logger.Field("tradeNo", orderInfo.TradeNo),
)
return GatewayStatusUnknown
}
if status == alipay.Success || status == alipay.Finished {
return true
switch status {
case alipay.Success, alipay.Finished:
return GatewayStatusPaid
case alipay.Pending, alipay.Closed:
return GatewayStatusUnpaid
default:
// Unknown alipay status — be conservative.
return GatewayStatusUnknown
}
return false
}
// queryStripe Query Stripe payment status
//
//nolint:unused
func (l *CloseOrderLogic) queryStripe(paymentConfig *payment.Payment, TradeNo string) bool {
// queryStripe queries Stripe PaymentIntent and maps to a tri-state.
// Any Stripe-side error (network, 5xx, decode) is Unknown — Stripe is the
// gateway most prone to silent webhook drops in this codebase, so we must not
// downgrade query failures to "unpaid".
func (l *CloseOrderLogic) queryStripe(orderInfo *order.Order) GatewayPaymentStatus {
if orderInfo.TradeNo == "" {
// Stripe's PaymentIntent ID is written into trade_no at create time.
// Missing it means the intent was never persisted — treat as unpaid.
return GatewayStatusUnpaid
}
paymentConfig, err := l.svcCtx.PaymentModel.FindOne(l.ctx, orderInfo.PaymentId)
if err != nil {
l.Errorw("[CloseOrder] Find payment config failed",
logger.Field("error", err.Error()),
logger.Field("paymentMark", orderInfo.Method),
)
return GatewayStatusUnknown
}
config := payment.StripeConfig{}
if err := json.Unmarshal([]byte(paymentConfig.Config), &config); err != nil {
l.Errorw("[CloseOrder] Unmarshal payment config failed", logger.Field("error", err.Error()), logger.Field("config", paymentConfig.Config))
return false
l.Errorw("[CloseOrder] Unmarshal Stripe config failed",
logger.Field("error", err.Error()),
logger.Field("orderNo", orderInfo.OrderNo),
)
return GatewayStatusUnknown
}
client := stripe.NewClient(stripe.Config{
PublicKey: config.PublicKey,
SecretKey: config.SecretKey,
WebhookSecret: config.WebhookSecret,
})
status, err := client.QueryOrderStatus(TradeNo)
paid, err := client.QueryOrderStatus(orderInfo.TradeNo)
if err != nil {
l.Errorw("[CloseOrder] Query order status failed", logger.Field("error", err.Error()), logger.Field("TradeNo", TradeNo))
return false
l.Errorw("[CloseOrder] Stripe QueryOrderStatus failed",
logger.Field("error", err.Error()),
logger.Field("orderNo", orderInfo.OrderNo),
logger.Field("tradeNo", orderInfo.TradeNo),
)
return GatewayStatusUnknown
}
return status
if paid {
return GatewayStatusPaid
}
return GatewayStatusUnpaid
}
// queryEpay queries EPay using out_trade_no (EPay's order endpoint accepts
// out_trade_no even when we never recorded its internal trade_no, which is the
// common case for orders that lost their notify callback).
func (l *CloseOrderLogic) queryEpay(orderInfo *order.Order) GatewayPaymentStatus {
paymentConfig, err := l.svcCtx.PaymentModel.FindOne(l.ctx, orderInfo.PaymentId)
if err != nil {
l.Errorw("[CloseOrder] Find payment config failed",
logger.Field("error", err.Error()),
logger.Field("paymentMark", orderInfo.Method),
)
return GatewayStatusUnknown
}
config := payment.EPayConfig{}
if err := json.Unmarshal([]byte(paymentConfig.Config), &config); err != nil {
l.Errorw("[CloseOrder] Unmarshal EPay config failed",
logger.Field("error", err.Error()),
logger.Field("orderNo", orderInfo.OrderNo),
)
return GatewayStatusUnknown
}
if config.Url == "" || config.Pid == "" || config.Key == "" {
l.Errorw("[CloseOrder] EPay config incomplete",
logger.Field("orderNo", orderInfo.OrderNo),
)
return GatewayStatusUnknown
}
client := epay.NewClient(config.Pid, config.Url, config.Key, config.Type)
paid, err := client.QueryOrderStatus(orderInfo.OrderNo)
if err != nil {
l.Errorw("[CloseOrder] EPay QueryOrderStatus failed",
logger.Field("error", err.Error()),
logger.Field("orderNo", orderInfo.OrderNo),
)
return GatewayStatusUnknown
}
if paid {
return GatewayStatusPaid
}
return GatewayStatusUnpaid
}
@@ -0,0 +1,232 @@
package order
import (
"context"
"fmt"
"strings"
"sync/atomic"
"testing"
"github.com/DATA-DOG/go-sqlmock"
modelorder "github.com/perfect-panel/server/internal/model/order"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/logger"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// newCloseOrderTestDB wires gorm to go-sqlmock with a substring SQL matcher,
// matching the convention used elsewhere in this package.
func newCloseOrderTestDB(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 newCloseOrderLogicForTest(db *gorm.DB) *CloseOrderLogic {
ctx := context.Background()
return &CloseOrderLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: &svc.ServiceContext{DB: db},
}
}
// TestRecoverPaidOrder_HappyPath covers HIF-137 P01 branch "gateway 已支付":
// gateway said the order was paid → we must flip status 1→2, persist
// trade_no, and enqueue exactly one ForthwithActivateOrder task. This is the
// most important regression to keep — silently dropping the enqueue here would
// re-create the bug we are fixing.
func TestRecoverPaidOrder_HappyPath(t *testing.T) {
db, mock, cleanup := newCloseOrderTestDB(t)
defer cleanup()
const (
orderNo = "ORD-PAID-1"
tradeNo = "ALIPAY-TRADE-9999"
)
mock.ExpectBegin()
mock.ExpectExec("UPDATE `order`").
WithArgs(2, tradeNo, sqlmock.AnyArg(), orderNo, 1).
WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectCommit()
var (
enqueueCalls int32
capturedPayload []byte
)
logic := newCloseOrderLogicForTest(db)
logic.enqueueActivate = func(_ context.Context, payload []byte) (string, error) {
atomic.AddInt32(&enqueueCalls, 1)
capturedPayload = append([]byte(nil), payload...)
return "task-123", nil
}
err := logic.recoverPaidOrder(&modelorder.Order{
OrderNo: orderNo,
Method: AlipayF2f,
TradeNo: tradeNo,
Status: 1,
})
if err != nil {
t.Fatalf("recoverPaidOrder error: %v", err)
}
if got := atomic.LoadInt32(&enqueueCalls); got != 1 {
t.Fatalf("expected exactly one enqueue, got %d", got)
}
if !strings.Contains(string(capturedPayload), orderNo) {
t.Fatalf("activation payload missing order_no: %q", capturedPayload)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}
// TestRecoverPaidOrder_AlreadyAdvanced covers the race: the late-arriving
// gateway-notify already flipped the order past status=1 by the time the
// deferred close ran. UPDATE returns 0 rows; we must NOT double-enqueue.
func TestRecoverPaidOrder_AlreadyAdvanced(t *testing.T) {
db, mock, cleanup := newCloseOrderTestDB(t)
defer cleanup()
const orderNo = "ORD-RACE"
mock.ExpectBegin()
mock.ExpectExec("UPDATE `order`").
WithArgs(2, sqlmock.AnyArg(), orderNo, 1).
WillReturnResult(sqlmock.NewResult(0, 0))
mock.ExpectCommit()
var enqueueCalls int32
logic := newCloseOrderLogicForTest(db)
logic.enqueueActivate = func(_ context.Context, _ []byte) (string, error) {
atomic.AddInt32(&enqueueCalls, 1)
return "should-not-fire", nil
}
err := logic.recoverPaidOrder(&modelorder.Order{
OrderNo: orderNo,
Method: Epay,
Status: 1,
})
if err != nil {
t.Fatalf("recoverPaidOrder error: %v", err)
}
if got := atomic.LoadInt32(&enqueueCalls); got != 0 {
t.Fatalf("expected no enqueue when 0 rows updated, got %d", got)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}
// TestRecoverPaidOrder_EnqueueFailureIsNotFatal covers the case where the DB
// move succeeded but the activation enqueue failed (Redis blip, etc). The
// order is already at status=2, so the stuck-order sweeper will pick it up —
// recoverPaidOrder must not return an error or revert the status.
func TestRecoverPaidOrder_EnqueueFailureIsNotFatal(t *testing.T) {
db, mock, cleanup := newCloseOrderTestDB(t)
defer cleanup()
const orderNo = "ORD-ENQ-FAIL"
mock.ExpectBegin()
mock.ExpectExec("UPDATE `order`").
WithArgs(2, sqlmock.AnyArg(), orderNo, 1).
WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectCommit()
logic := newCloseOrderLogicForTest(db)
logic.enqueueActivate = func(_ context.Context, _ []byte) (string, error) {
return "", fmt.Errorf("simulated redis outage")
}
if err := logic.recoverPaidOrder(&modelorder.Order{OrderNo: orderNo, Method: Epay}); err != nil {
t.Fatalf("recoverPaidOrder must swallow enqueue errors, got: %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}
// TestQueryGatewayPaymentStatus_NonGatewayMethods checks the "fall-through"
// branches: methods that don't talk to an external gateway (Balance, empty
// string, anything unrecognised) must report Unpaid so the legacy close path
// is preserved. This is the regression hook for the issue's acceptance
// criterion #5 ("user-initiated cancellation can still close normally").
func TestQueryGatewayPaymentStatus_NonGatewayMethods(t *testing.T) {
logic := newCloseOrderLogicForTest(nil) // no DB needed for these branches
cases := []struct {
method string
want GatewayPaymentStatus
}{
{Balance, GatewayStatusUnpaid},
{"", GatewayStatusUnpaid},
{"future-method-we-dont-know", GatewayStatusUnpaid},
}
for _, tc := range cases {
got := logic.queryGatewayPaymentStatus(&modelorder.Order{Method: tc.method})
if got != tc.want {
t.Fatalf("method=%q: got %v want %v", tc.method, got, tc.want)
}
}
}
// TestQueryGatewayPaymentStatus_AlipayNoTradeNoIsUnpaid: Alipay F2F creates
// the trade lazily — if we never recorded a trade_no, the user never scanned
// the QR code. We must report Unpaid (not Unknown) so the close proceeds.
// Without this short-circuit, every legitimately abandoned QR-code order
// would be "kept open" forever by the inconclusive-query branch.
func TestQueryGatewayPaymentStatus_AlipayNoTradeNoIsUnpaid(t *testing.T) {
logic := newCloseOrderLogicForTest(nil)
got := logic.queryGatewayPaymentStatus(&modelorder.Order{Method: AlipayF2f, TradeNo: ""})
if got != GatewayStatusUnpaid {
t.Fatalf("Alipay F2F with empty trade_no should be Unpaid, got %v", got)
}
}
// TestQueryGatewayPaymentStatus_StripeNoTradeNoIsUnpaid: same reasoning as
// the Alipay case — Stripe's PaymentIntent ID lives in trade_no; if it's
// missing the intent was never persisted.
func TestQueryGatewayPaymentStatus_StripeNoTradeNoIsUnpaid(t *testing.T) {
logic := newCloseOrderLogicForTest(nil)
for _, method := range []string{StripeAlipay, StripeWeChatPay} {
got := logic.queryGatewayPaymentStatus(&modelorder.Order{Method: method, TradeNo: ""})
if got != GatewayStatusUnpaid {
t.Fatalf("%s with empty trade_no should be Unpaid, got %v", method, got)
}
}
}
// TestCloseOrderGatewayQueryDispatch_DefaultProductionWiring asserts that the
// default gatewayQuery is wired to the real implementation (not nil) by
// NewCloseOrderLogic. Without this guard a future refactor could silently
// drop the wiring and re-create HIF-135.
func TestCloseOrderGatewayQueryDispatch_DefaultProductionWiring(t *testing.T) {
svcCtx := &svc.ServiceContext{}
l := NewCloseOrderLogic(context.Background(), svcCtx)
if l.gatewayQuery == nil {
t.Fatal("NewCloseOrderLogic must wire gatewayQuery; got nil")
}
if l.enqueueActivate == nil {
t.Fatal("NewCloseOrderLogic must wire enqueueActivate; got nil")
}
}
@@ -0,0 +1,17 @@
package order
import (
"context"
"github.com/perfect-panel/server/internal/model/user"
"gorm.io/gorm"
)
func paidSubscriptionQuery(ctx context.Context, db *gorm.DB, userID int64) *gorm.DB {
return db.WithContext(ctx).
Model(&user.Subscribe{}).
Where("user_id = ? AND (order_id > 0 OR token LIKE 'iap:%')", userID).
Order("expire_time DESC").
Order("updated_at DESC").
Order("id DESC")
}
@@ -0,0 +1,32 @@
package order
import (
"context"
"strings"
"testing"
"github.com/perfect-panel/server/internal/model/user"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func TestPaidSubscriptionQueryIncludesOrderBackedSubscriptionWithoutToken(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)
}
var sub user.Subscribe
tx := paidSubscriptionQuery(context.Background(), db, 510).First(&sub)
sql := tx.Statement.SQL.String()
if strings.Contains(sql, "token != ''") {
t.Fatalf("paid subscription query should not require non-empty token: %s", sql)
}
if !strings.Contains(sql, "order_id > 0 OR token LIKE 'iap:%'") {
t.Fatalf("paid subscription query should include order-backed or iap-backed subscriptions: %s", sql)
}
}
@@ -88,13 +88,8 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
// routes the request to renewal semantics, where first-purchase promos are disabled.
if !l.svcCtx.Config.Subscribe.SingleModel && orderType == 1 {
var existSub user.Subscribe
if e := l.svcCtx.DB.WithContext(l.ctx).
Model(&user.Subscribe{}).
Where("user_id = ? AND token != '' AND (order_id > 0 OR token LIKE 'iap:%')", entitlement.EffectiveUserID).
Order("expire_time DESC").
Order("updated_at DESC").
Order("id DESC").
First(&existSub).Error; e == nil && existSub.Id > 0 && existSub.Token != "" {
if e := paidSubscriptionQuery(l.ctx, l.svcCtx.DB, entitlement.EffectiveUserID).
First(&existSub).Error; e == nil && existSub.Id > 0 {
orderType = 2
l.Infow("[PreCreateOrder] purchase preview routed to renewal because an existing subscription was found",
logger.Field("route_mode", "global_single_subscription"),
+13 -15
View File
@@ -27,7 +27,7 @@ func calculatePurchasePrice(
quantity int64,
discounts []types.SubscribeDiscount,
eligibleForDiscount bool,
allowPromo bool,
isFirstPurchase bool,
) (*orderPriceResult, error) {
originalPrice := unitPrice * quantity
result := &orderPriceResult{
@@ -35,21 +35,19 @@ func calculatePurchasePrice(
PayableBase: originalPrice,
}
if allowPromo {
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, subscribeID, quantity)
if err != nil {
return nil, err
}
if promoResult != nil && promoResult.Eligible && promoResult.PromoPrice < originalPrice {
result.PayableBase = promoResult.PromoPrice
result.PromoRuleId = promoResult.RuleID
result.PromoDiscount = originalPrice - result.PayableBase
result.PromoPrice = promoResult.PromoPrice
if result.PromoDiscount < 0 {
result.PromoDiscount = 0
}
return result, nil
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, subscribeID, quantity, isFirstPurchase)
if err != nil {
return nil, err
}
if promoResult != nil && promoResult.Eligible && promoResult.PromoPrice < originalPrice {
result.PayableBase = promoResult.PromoPrice
result.PromoRuleId = promoResult.RuleID
result.PromoDiscount = originalPrice - result.PayableBase
result.PromoPrice = promoResult.PromoPrice
if result.PromoDiscount < 0 {
result.PromoDiscount = 0
}
return result, nil
}
discount := float64(1)
@@ -221,3 +221,79 @@ func TestCalculatePurchasePricePassesQuantityToPromoEvaluation(t *testing.T) {
t.Fatalf("PromoRuleId = %d, want 11", result.PromoRuleId)
}
}
func TestCalculatePurchasePriceCampaignAppliesToReturningUsers(t *testing.T) {
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
{
Rule: promo.Rule{
Id: 12,
Name: "campaign",
Type: promo.RuleTypeCampaign,
Enabled: true,
},
PromoPrice: 400,
},
}}
svcCtx := &svc.ServiceContext{DB: &gorm.DB{}, PromoModel: model}
// isFirstPurchase=false simulates a returning user routed to renewal; the
// Campaign promo must still apply because it has no first-purchase gate.
result, err := calculatePurchasePrice(
context.Background(),
svcCtx,
42,
2,
1000,
1,
nil,
false,
false,
)
if err != nil {
t.Fatalf("calculatePurchasePrice returned error: %v", err)
}
if result.PromoRuleId != 12 {
t.Fatalf("PromoRuleId = %d, want 12 (campaign should apply to returning users)", result.PromoRuleId)
}
if result.PayableBase != 400 {
t.Fatalf("PayableBase = %d, want 400", result.PayableBase)
}
}
func TestCalculatePurchasePriceNewUserGatedByFirstPurchase(t *testing.T) {
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
{
Rule: promo.Rule{
Id: 13,
Name: "new user",
Type: promo.RuleTypeNewUser,
Enabled: true,
Params: `{"window_hours": 72}`,
},
PromoPrice: 200,
},
}}
svcCtx := &svc.ServiceContext{DB: &gorm.DB{}, PromoModel: model}
// isFirstPurchase=false → NewUser rule must be skipped, regular discount applies.
result, err := calculatePurchasePrice(
context.Background(),
svcCtx,
42,
2,
1000,
1,
[]types.SubscribeDiscount{{Quantity: 1, Discount: 90}},
true,
false,
)
if err != nil {
t.Fatalf("calculatePurchasePrice returned error: %v", err)
}
if result.PromoRuleId != 0 || result.PromoDiscount != 0 {
t.Fatalf("promo fields = (%d, %d), want (0, 0) when isFirstPurchase=false", result.PromoRuleId, result.PromoDiscount)
}
if result.PayableBase != 900 {
t.Fatalf("PayableBase = %d, want 900 (regular 90%% discount)", result.PayableBase)
}
}
+2 -7
View File
@@ -129,13 +129,8 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
// 防止不同套餐购买创建第二条订阅。
if !l.svcCtx.Config.Subscribe.SingleModel && orderType == 1 {
var existSub user.Subscribe
if e := l.svcCtx.DB.WithContext(l.ctx).
Model(&user.Subscribe{}).
Where("user_id = ? AND token != '' AND (order_id > 0 OR token LIKE 'iap:%')", entitlement.EffectiveUserID).
Order("expire_time DESC").
Order("updated_at DESC").
Order("id DESC").
First(&existSub).Error; e == nil && existSub.Id > 0 && existSub.Token != "" {
if e := paidSubscriptionQuery(l.ctx, l.svcCtx.DB, entitlement.EffectiveUserID).
First(&existSub).Error; e == nil && existSub.Id > 0 {
orderType = 2
parentOrderID = existSub.OrderId
subscribeToken = existSub.Token
+17 -5
View File
@@ -41,6 +41,22 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
}
userInfo, _ := ctx.Value(constant.CtxKeyUser).(*user.User)
userID := int64(0)
isFirstPurchase := true
if userInfo != nil {
entitlement, err := commonLogic.ResolveEntitlementUser(ctx, svcCtx.DB, userInfo.Id)
if err != nil {
return nil, err
}
userID = entitlement.EffectiveUserID
hasPaid, err := commonLogic.HasPaidSubscription(ctx, svcCtx.DB, userID)
if err != nil {
return nil, err
}
isFirstPurchase = !hasPaid
}
candidates, err := querySubscribePromoCandidates(ctx, svcCtx, subscribeIDs, userInfo != nil)
if err != nil {
if isMissingPromoTableError(err) {
@@ -49,10 +65,6 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
return nil, err
}
userID := int64(0)
if userInfo != nil {
userID = userInfo.Id
}
for _, candidate := range candidates {
if candidate.Quantity <= 0 {
continue
@@ -63,7 +75,7 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
if _, exists := result[candidate.SubscribeId][candidate.Quantity]; exists {
continue
}
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, candidate.SubscribeId, candidate.Quantity)
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, candidate.SubscribeId, candidate.Quantity, isFirstPurchase)
if err != nil {
return nil, err
}
@@ -9,8 +9,10 @@ import (
"github.com/DATA-DOG/go-sqlmock"
"github.com/perfect-panel/server/internal/model/promo"
"github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/constant"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
@@ -88,6 +90,66 @@ func TestLoadSubscribePromoMapUsesCommonPromoEvaluation(t *testing.T) {
}
}
func TestLoadSubscribePromoMapUsesFamilyOwnerForInactivePromo(t *testing.T) {
db, mock, cleanup := newSubscribePromoTestDB(t)
defer cleanup()
memberUserID := int64(51637)
ownerUserID := int64(510)
subscribeID := int64(11)
quantity := int64(30)
now := time.Now()
end := now.Add(24 * time.Hour)
mock.ExpectQuery("FROM `user_family_member`").
WithArgs(memberUserID, user.FamilyMemberActive, 1).
WillReturnRows(sqlmock.NewRows([]string{"role", "family_status", "owner_user_id"}).
AddRow(user.FamilyRoleMember, user.FamilyStatusActive, ownerUserID))
mock.ExpectQuery("SELECT count(*) FROM `user_subscribe`").
WithArgs(ownerUserID, 1).
WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(0))
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(subscribeID, quantity, "回归用户01", promoRuleTypeInactiveUser, 100, `{"inactive_months":1}`, nil, end))
mock.ExpectQuery("FROM `user_subscribe`").
WithArgs(ownerUserID, time.UnixMilli(0), 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "user_id", "subscribe_id", "expire_time"}).
AddRow(131, ownerUserID, 1, now.AddDate(0, 1, 0)))
ctx := context.WithValue(context.Background(), constant.CtxKeyUser, &user.User{Id: memberUserID})
promoModel := &fakeSubscribePromoModel{rules: []*promo.RuleWithPrice{
{
Rule: promo.Rule{
Id: 8,
Name: "回归用户01",
Type: promo.RuleTypeInactiveUser,
Enabled: true,
Params: `{"inactive_months":1}`,
EndTime: &end,
},
PromoPrice: 100,
},
}}
got, err := loadSubscribePromoMap(ctx, &svc.ServiceContext{DB: db, PromoModel: promoModel}, []int64{subscribeID})
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 != subscribeID {
t.Fatalf("promo subscribe id = %d, want %d", promoModel.lastSubscribeID, subscribeID)
}
if promoModel.lastQuantity != quantity {
t.Fatalf("promo quantity = %d, want %d", promoModel.lastQuantity, quantity)
}
if got[subscribeID][quantity] != nil {
t.Fatalf("family member should not receive inactive promo when owner has active subscription, got %+v", got[subscribeID][quantity])
}
}
type fakeSubscribePromoModel struct {
rules []*promo.RuleWithPrice
lastSubscribeID int64
@@ -4,7 +4,6 @@ import (
"context"
logicCommon "github.com/perfect-panel/server/internal/logic/common"
"github.com/perfect-panel/server/internal/model/log"
"github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
@@ -57,13 +56,10 @@ func (l *CancelWithdrawalLogic) CancelWithdrawal(req *types.CancelWithdrawalRequ
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "cancel withdrawal failed: %v", txErr)
}
if txErr = l.svcCtx.UserModel.UpdateCommission(l.ctx, withdrawal.UserId, withdrawal.Amount, tx); txErr != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "refund commission failed: %v", txErr)
}
if txErr = logicCommon.WriteCommissionLog(tx, withdrawal.UserId, log.CommissionTypeWithdrawCancel, withdrawal.Amount, ""); txErr != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "write commission log failed: %v", txErr)
}
// Commission was NOT deducted at application time under the HIF-22
// approval flow, so cancellation requires no refund — only a status
// update. Refunding here would mint phantom commission and pollute
// reconciliation (mirrors rejectWithdrawal in admin/user/withdrawalCommon.go).
return nil
})
@@ -0,0 +1,228 @@
package user
import (
"context"
"fmt"
"strings"
"testing"
"github.com/DATA-DOG/go-sqlmock"
usermodel "github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/constant"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// TestCancelWithdrawal_DoesNotRefundCommission 验证 HIF-140 修复:
// 用户撤销 pending 提现的事务体必须只更新 withdrawal.status
// 严禁触发 UpdateCommissioncommission 列读 / 写)或写 333/338 commission 日志。
//
// sqlmock 严格匹配期望 SQL:只允许出现 BEGIN / SELECT withdrawal FOR UPDATE /
// UPDATE withdrawal SET status / COMMIT,不允许出现 SELECT/UPDATE `user` 或
// INSERT system_logs。
func TestCancelWithdrawal_DoesNotRefundCommission(t *testing.T) {
const (
withdrawalID = int64(987654)
userID = int64(42)
amount = int64(2500)
)
db, mock, cleanup := newCancelWithdrawalTestDB(t)
defer cleanup()
mock.ExpectBegin()
mock.ExpectQuery("FROM `withdrawals`").
WithArgs(withdrawalID, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "user_id", "amount", "status"}).
AddRow(withdrawalID, userID, amount, usermodel.WithdrawalStatusPending))
mock.ExpectExec("UPDATE `withdrawals` SET").
WithArgs(usermodel.WithdrawalStatusCancelled, sqlmock.AnyArg(), withdrawalID, usermodel.WithdrawalStatusPending).
WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectCommit()
logic := newTestCancelWithdrawalLogic(t, db, userID)
resp, err := logic.CancelWithdrawal(&types.CancelWithdrawalRequest{WithdrawalId: withdrawalID})
if err != nil {
t.Fatalf("CancelWithdrawal unexpected error: %v", err)
}
if resp == nil || resp.Id != withdrawalID {
t.Fatalf("CancelWithdrawal response = %+v, want id=%d", resp, withdrawalID)
}
if resp.Status != usermodel.WithdrawalStatusCancelled {
t.Fatalf("CancelWithdrawal status = %d, want %d", resp.Status, usermodel.WithdrawalStatusCancelled)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}
// TestCancelWithdrawal_RejectsNonPending 覆盖:状态非 pending(已批准/拒绝/已撤销)
// 时撤销必须短路返回 WithdrawalStatusInvalid,且不得写任何状态或佣金。
func TestCancelWithdrawal_RejectsNonPending(t *testing.T) {
const (
withdrawalID = int64(55555)
userID = int64(42)
)
cases := []struct {
name string
status uint8
}{
{"already approved", usermodel.WithdrawalStatusApproved},
{"already rejected", usermodel.WithdrawalStatusRejected},
{"already cancelled", usermodel.WithdrawalStatusCancelled},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
db, mock, cleanup := newCancelWithdrawalTestDB(t)
defer cleanup()
mock.ExpectBegin()
mock.ExpectQuery("FROM `withdrawals`").
WithArgs(withdrawalID, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "user_id", "amount", "status"}).
AddRow(withdrawalID, userID, int64(2500), tc.status))
mock.ExpectRollback()
logic := newTestCancelWithdrawalLogic(t, db, userID)
_, err := logic.CancelWithdrawal(&types.CancelWithdrawalRequest{WithdrawalId: withdrawalID})
if !isCancelErrCode(err, xerr.WithdrawalStatusInvalid) {
t.Fatalf("CancelWithdrawal err = %v, want WithdrawalStatusInvalid", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
})
}
}
// TestCancelWithdrawal_RejectsOtherUserWithdrawal 覆盖:当前登录用户尝试撤销
// 不属于自己的 pending 提现,必须返回 PermissionDenied 且不得写库。
func TestCancelWithdrawal_RejectsOtherUserWithdrawal(t *testing.T) {
const (
withdrawalID = int64(33333)
ownerUserID = int64(99)
attackerID = int64(42)
)
db, mock, cleanup := newCancelWithdrawalTestDB(t)
defer cleanup()
mock.ExpectBegin()
mock.ExpectQuery("FROM `withdrawals`").
WithArgs(withdrawalID, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "user_id", "amount", "status"}).
AddRow(withdrawalID, ownerUserID, int64(2500), usermodel.WithdrawalStatusPending))
mock.ExpectRollback()
logic := newTestCancelWithdrawalLogic(t, db, attackerID)
_, err := logic.CancelWithdrawal(&types.CancelWithdrawalRequest{WithdrawalId: withdrawalID})
if !isCancelErrCode(err, xerr.PermissionDenied) {
t.Fatalf("CancelWithdrawal err = %v, want PermissionDenied", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}
// TestCancelWithdrawal_ConcurrentRaceLosesViaFORUPDATE 模拟撤销与审批并发的场景:
// 第二个 cancel 在 LoadPendingWithdrawalForUpdate 取到行时,状态已被先到的 approve
// 改成 1FOR UPDATE 行锁让出后看到的最新状态),cancel 应当短路返回错误,
// 严禁继续往下写 status 或动 commission。
func TestCancelWithdrawal_ConcurrentRaceLosesViaFORUPDATE(t *testing.T) {
const (
withdrawalID = int64(77777)
userID = int64(42)
)
db, mock, cleanup := newCancelWithdrawalTestDB(t)
defer cleanup()
mock.ExpectBegin()
mock.ExpectQuery("FROM `withdrawals`").
WithArgs(withdrawalID, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "user_id", "amount", "status"}).
AddRow(withdrawalID, userID, int64(2500), usermodel.WithdrawalStatusApproved))
mock.ExpectRollback()
logic := newTestCancelWithdrawalLogic(t, db, userID)
_, err := logic.CancelWithdrawal(&types.CancelWithdrawalRequest{WithdrawalId: withdrawalID})
if !isCancelErrCode(err, xerr.WithdrawalStatusInvalid) {
t.Fatalf("CancelWithdrawal err = %v, want WithdrawalStatusInvalid (loser of race)", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}
func newCancelWithdrawalTestDB(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 newTestCancelWithdrawalLogic(t *testing.T, db *gorm.DB, userID int64) *CancelWithdrawalLogic {
t.Helper()
ctx := context.WithValue(context.Background(), constant.CtxKeyUser, &usermodel.User{Id: userID})
return &CancelWithdrawalLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: &svc.ServiceContext{
DB: db,
UserModel: stubUserModelForCancel{},
},
}
}
// stubUserModelForCancel 是 user.Model 的零依赖替身,仅覆盖 CancelWithdrawal 必须
// 调用的 ClearUserCache。其它方法被调用会导致 nil-interface panic,正好可以暴露
// 测试边界外的意外依赖。
type stubUserModelForCancel struct {
usermodel.Model
}
func (stubUserModelForCancel) ClearUserCache(_ context.Context, _ ...*usermodel.User) error {
return nil
}
func cancelErrCodeOf(err error) uint32 {
if err == nil {
return 0
}
type coder interface {
GetErrCode() uint32
}
cause := errors.Cause(err)
if c, ok := cause.(coder); ok {
return c.GetErrCode()
}
return 0
}
func isCancelErrCode(err error, code uint32) bool {
return cancelErrCodeOf(err) == code
}
@@ -113,12 +113,17 @@ func (l *GetInviteRecordsLogic) GetInviteRecords(req *types.GetInviteRecordsRequ
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query orders failed: %v", err.Error())
}
visibleUserIdSet := make(map[int64]struct{}, len(visibleUserIds))
for _, userId := range visibleUserIds {
visibleUserIdSet[userId] = struct{}{}
}
allRecords := make([]types.InviteRecord, 0, len(parsedLogs))
for _, parsed := range parsedLogs {
content := parsed.content
logItem := parsed.log
orderInfo, hasOrder := orders[content.OrderNo]
if !l.canViewInviteRecord(u.Id, logItem.ObjectId, hasOrder, orderInfo) {
if !l.canViewInviteRecord(u.Id, logItem.ObjectId, visibleUserIdSet, hasOrder, orderInfo) {
continue
}
@@ -177,17 +182,17 @@ func (l *GetInviteRecordsLogic) resolveInviteRecordVisibleUserIds(currentUserId
return nil, err
}
func (l *GetInviteRecordsLogic) canViewInviteRecord(currentUserId, logObjectId int64, hasOrder bool, orderInfo inviteOrderUser) bool {
func (l *GetInviteRecordsLogic) canViewInviteRecord(currentUserId, logObjectId int64, visibleUserIds map[int64]struct{}, hasOrder bool, orderInfo inviteOrderUser) bool {
if _, ok := visibleUserIds[logObjectId]; !ok {
return false
}
if logObjectId == currentUserId {
if hasOrder {
return orderInfo.UserId == currentUserId || orderInfo.RefererId == currentUserId
}
return true
}
if !hasOrder {
return false
}
return orderInfo.UserId == currentUserId && orderInfo.SubscriptionUserId == logObjectId
return true
}
func normalizeInviteRecordsPagination(req *types.GetInviteRecordsRequest) {
@@ -123,6 +123,33 @@ func TestGetInviteRecordsFamilyMemberSeesOwnerGiftLog(t *testing.T) {
assertInviteRecordsExpectations(t, mock)
}
func TestGetInviteRecordsFamilyMemberSeesAllOwnerGiftLogs(t *testing.T) {
svcCtx, mock, cleanup := newInviteRecordsTestSvc(t)
defer cleanup()
expectInviteRecordsFamilyMember(t, mock, 51637, 510)
mock.ExpectQuery("SELECT id, object_id, content").
WithArgs(34, int64(51637), int64(510), "邀请赠送").
WillReturnRows(sqlmock.NewRows([]string{"id", "object_id", "content", "created_at"}).
AddRow(6, 510, `{"order_no":"owner-order","amount":7,"remark":"邀请赠送"}`, 1779934630000))
mock.ExpectQuery("SELECT `order`.order_no, `order`.user_id, `order`.subscription_user_id, invitee.referer_id FROM `order`").
WithArgs("owner-order").
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id", "subscription_user_id", "referer_id"}).AddRow("owner-order", 571, 571, 510))
resp, err := NewGetInviteRecordsLogic(inviteRecordsContext(51637, 0), svcCtx).GetInviteRecords(&types.GetInviteRecordsRequest{Page: 1, Size: 10})
if err != nil {
t.Fatalf("GetInviteRecords returned error: %v", err)
}
assertInviteRecordResponse(t, resp, types.InviteRecord{
Role: inviteRecordRoleInviter,
PeerHash: hash.InvitePeerHash(571),
GiftDays: 7,
OrderNo: "owner-order",
CreatedAt: 1779934630000,
})
assertInviteRecordsExpectations(t, mock)
}
func TestGetInviteRecordsOwnerDoesNotSeeMemberGiftLog(t *testing.T) {
svcCtx, mock, cleanup := newInviteRecordsTestSvc(t)
defer cleanup()
+38
View File
@@ -0,0 +1,38 @@
package log
import (
"fmt"
"gorm.io/gorm"
)
// HasRefundCommissionLog 判断指定订单号是否已写入 333 退款佣金日志。
// 用于 refund 主流程做幂等校验,以及 stuck-order recovery / activate worker
// 区分「已退款」(terminal)与「短暂 claimed」(transient)这两种共用 status=6
// 的语义。
//
// 实现细节:
// 1. type=33 + content LIKE '%"order_no":"<orderNo>"%' 先走索引粗筛;
// 2. 命中项再用 JSON 反序列化精确比对 content.type==333 与 content.order_no
// 避免 order_no 出现在其它字段子串里产生误判。
func HasRefundCommissionLog(tx *gorm.DB, orderNo string) (bool, error) {
if orderNo == "" {
return false, nil
}
var logs []SystemLog
if err := tx.Model(&SystemLog{}).
Where("type = ? AND content LIKE ?", TypeCommission.Uint8(), fmt.Sprintf("%%\"order_no\":\"%s\"%%", orderNo)).
Find(&logs).Error; err != nil {
return false, fmt.Errorf("query refund commission log failed: %w", err)
}
for _, item := range logs {
var content Commission
if err := content.Unmarshal([]byte(item.Content)); err != nil {
continue
}
if content.Type == CommissionTypeRefund && content.OrderNo == orderNo {
return true, nil
}
}
return false, nil
}
+172
View File
@@ -0,0 +1,172 @@
package log
import (
"fmt"
"strings"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func TestHasRefundCommissionLog(t *testing.T) {
const orderNo = "ORD-REFUND-1"
t.Run("returns true when 333 log exists for the order", func(t *testing.T) {
db, mock, cleanup := newRefundLogTestDB(t)
defer cleanup()
mock.ExpectQuery("FROM `system_logs`").
WithArgs(uint8(33), fmt.Sprintf(`%%"order_no":"%s"%%`, orderNo)).
WillReturnRows(sqlmock.NewRows([]string{"id", "content"}).
AddRow(1, fmt.Sprintf(`{"type":331,"order_no":"%s","amount":100}`, orderNo)).
AddRow(2, fmt.Sprintf(`{"type":333,"order_no":"%s","amount":-100}`, orderNo)))
got, err := HasRefundCommissionLog(db, orderNo)
if err != nil {
t.Fatalf("HasRefundCommissionLog error: %v", err)
}
if !got {
t.Fatalf("HasRefundCommissionLog = false, want true")
}
assertRefundLogExpectations(t, mock)
})
t.Run("returns false when only 331/332 logs exist", func(t *testing.T) {
db, mock, cleanup := newRefundLogTestDB(t)
defer cleanup()
mock.ExpectQuery("FROM `system_logs`").
WithArgs(uint8(33), fmt.Sprintf(`%%"order_no":"%s"%%`, orderNo)).
WillReturnRows(sqlmock.NewRows([]string{"id", "content"}).
AddRow(1, fmt.Sprintf(`{"type":331,"order_no":"%s","amount":100}`, orderNo)).
AddRow(2, fmt.Sprintf(`{"type":332,"order_no":"%s","amount":50}`, orderNo)))
got, err := HasRefundCommissionLog(db, orderNo)
if err != nil {
t.Fatalf("HasRefundCommissionLog error: %v", err)
}
if got {
t.Fatalf("HasRefundCommissionLog = true, want false")
}
assertRefundLogExpectations(t, mock)
})
t.Run("returns false when no log exists for the order", func(t *testing.T) {
db, mock, cleanup := newRefundLogTestDB(t)
defer cleanup()
mock.ExpectQuery("FROM `system_logs`").
WithArgs(uint8(33), fmt.Sprintf(`%%"order_no":"%s"%%`, orderNo)).
WillReturnRows(sqlmock.NewRows([]string{"id", "content"}))
got, err := HasRefundCommissionLog(db, orderNo)
if err != nil {
t.Fatalf("HasRefundCommissionLog error: %v", err)
}
if got {
t.Fatalf("HasRefundCommissionLog = true, want false")
}
assertRefundLogExpectations(t, mock)
})
t.Run("returns false for empty order_no without querying", func(t *testing.T) {
db, mock, cleanup := newRefundLogTestDB(t)
defer cleanup()
got, err := HasRefundCommissionLog(db, "")
if err != nil {
t.Fatalf("HasRefundCommissionLog error: %v", err)
}
if got {
t.Fatalf("HasRefundCommissionLog = true, want false")
}
assertRefundLogExpectations(t, mock)
})
t.Run("ignores 333 log when order_no in content does not match", func(t *testing.T) {
// Defensive: LIKE pattern may match a substring; JSON match catches it.
db, mock, cleanup := newRefundLogTestDB(t)
defer cleanup()
mock.ExpectQuery("FROM `system_logs`").
WithArgs(uint8(33), fmt.Sprintf(`%%"order_no":"%s"%%`, orderNo)).
WillReturnRows(sqlmock.NewRows([]string{"id", "content"}).
AddRow(1, `{"type":333,"order_no":"OTHER","amount":-100}`))
got, err := HasRefundCommissionLog(db, orderNo)
if err != nil {
t.Fatalf("HasRefundCommissionLog error: %v", err)
}
if got {
t.Fatalf("HasRefundCommissionLog = true, want false (different order_no)")
}
assertRefundLogExpectations(t, mock)
})
t.Run("ignores malformed json content", func(t *testing.T) {
db, mock, cleanup := newRefundLogTestDB(t)
defer cleanup()
mock.ExpectQuery("FROM `system_logs`").
WithArgs(uint8(33), fmt.Sprintf(`%%"order_no":"%s"%%`, orderNo)).
WillReturnRows(sqlmock.NewRows([]string{"id", "content"}).
AddRow(1, `not a json`).
AddRow(2, fmt.Sprintf(`{"type":333,"order_no":"%s","amount":-100}`, orderNo)))
got, err := HasRefundCommissionLog(db, orderNo)
if err != nil {
t.Fatalf("HasRefundCommissionLog error: %v", err)
}
if !got {
t.Fatalf("HasRefundCommissionLog = false, want true")
}
assertRefundLogExpectations(t, mock)
})
t.Run("returns error when db query fails", func(t *testing.T) {
db, mock, cleanup := newRefundLogTestDB(t)
defer cleanup()
mock.ExpectQuery("FROM `system_logs`").
WithArgs(uint8(33), fmt.Sprintf(`%%"order_no":"%s"%%`, orderNo)).
WillReturnError(fmt.Errorf("connection lost"))
if _, err := HasRefundCommissionLog(db, orderNo); err == nil {
t.Fatalf("expected error, got nil")
}
assertRefundLogExpectations(t, mock)
})
}
func newRefundLogTestDB(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 assertRefundLogExpectations(t *testing.T, mock sqlmock.Sqlmock) {
t.Helper()
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}
+1 -1
View File
@@ -67,7 +67,7 @@ func (m *defaultUserModel) FindSingleModeAnchorSubscribe(ctx context.Context, us
var data Subscribe
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, _ interface{}) error {
return conn.Model(&Subscribe{}).
Where("user_id = ? AND token != '' AND (order_id > 0 OR token LIKE 'iap:%') AND `status` IN ?", userId, []int64{0, 1, 2, 3, 4, 5}).
Where("user_id = ? AND (order_id > 0 OR token LIKE 'iap:%') AND `status` IN ?", userId, []int64{0, 1, 2, 3, 4, 5}).
Order("expire_time DESC").
Order("updated_at DESC").
Order("id DESC").
+22 -7
View File
@@ -2,6 +2,7 @@ package epay
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
@@ -88,28 +89,42 @@ func (c *Client) VerifySign(params map[string]string) bool {
return c.createSign(params) == params["sign"]
}
func (c *Client) QueryOrderStatus(orderNo string) bool {
// QueryOrderStatus returns (paid, err). A non-nil err means the query itself
// failed (network / 5xx / decode error) and the result is inconclusive — callers
// MUST NOT treat that as "unpaid". A nil err with paid=false means the gateway
// answered and reported the order is not paid.
func (c *Client) QueryOrderStatus(orderNo string) (bool, error) {
client := http.Client{
Timeout: 5 * time.Second,
}
resp, err := client.Get(c.Url + "/api.php" + "?act=order" + "&pid=" + c.Pid + "&key=" + c.Key + "&out_trade_no=" + orderNo)
if err != nil {
logger.Error("[Epay] QueryOrderStatus error", logger.Field("orderNo", orderNo), logger.Field("error", err.Error()))
return false
return false, fmt.Errorf("epay query request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 500 {
err := fmt.Errorf("epay query upstream status %d", resp.StatusCode)
logger.Error("[Epay] QueryOrderStatus upstream 5xx", logger.Field("orderNo", orderNo), logger.Field("status", resp.StatusCode))
return false, err
}
value, err := io.ReadAll(resp.Body)
if err != nil {
logger.Error("[Epay] QueryOrderStatus error", logger.Field("orderNo", orderNo), logger.Field("error", err.Error()))
return false
return false, fmt.Errorf("epay query read body failed: %w", err)
}
var response queryOrderStatusResponse
err = json.Unmarshal(value, &response)
if err != nil {
if err = json.Unmarshal(value, &response); err != nil {
logger.Error("[Epay] QueryOrderStatus error", logger.Field("orderNo", orderNo), logger.Field("error", err.Error()))
return false
return false, fmt.Errorf("epay query decode failed: %w", err)
}
return response.Status == 1
// EPay API contract: code != 1 means the API itself errored (e.g. wrong key).
// Treat it as a query failure, not a definitive "unpaid", to avoid wrongly
// closing a paid order under a transient upstream config error.
if response.Code != 1 {
return false, fmt.Errorf("epay query api code=%d msg=%q", response.Code, response.Msg)
}
return response.Status == 1, nil
}
// StructToMap converts a struct to map[string]string
+6
View File
@@ -37,6 +37,7 @@ func init() {
TelegramNotBound: "Telegram not bound ",
UserNotBindOauth: "User not bind oauth method",
InviteCodeError: "Invite code error",
UserCommissionNotEnough: "佣金余额不足",
RegisterIPLimit: "Too many registrations",
EmailBindError: "Email already bound",
UserBindInviteCodeExist: "Invite code already bound",
@@ -82,6 +83,8 @@ func init() {
// System error
DebugModeError: "Debug mode is enabled",
SendSmsError: "短信发送失败",
GetAuthenticatorError: "Unsupported login method",
AuthenticatorNotSupportedError: "The authenticator does not support this method",
@@ -94,15 +97,18 @@ func init() {
TelephoneExist: "Telephone already exists",
DeviceExist: "device exists",
PasswordIsEmpty: "password is empty",
AreaCodeIsEmpty: "国家区号不能为空",
TelephoneError: "telephone number error",
DeviceNotExist: "Device does not exist",
UseridNotMatch: "Userid not match",
DeviceBindLimitExceeded: "设备绑定数量已达上限",
// Order error
OrderNotExist: "Order does not exist",
PaymentMethodNotFound: "Payment method not found",
OrderStatusError: "Order status error",
InsufficientOfPeriod: "Insufficient number of period",
ExistAvailableTraffic: "存在可用流量",
OrderAlreadyRefunded: "Order already refunded",
OrderRefundNoSubscription: "Refund target subscription not found",
OrderRefundCommissionMismatch: "Refund commission source not found",
+45
View File
@@ -0,0 +1,45 @@
package xerr
import "testing"
// TestMapErrMsg_MissingCodesAreFilled 覆盖 HIF-138 中补齐的 5 个错误码:
// 这些码之前在 message 表中缺失,导致 MapErrMsg 回退到 "Internal Server Error"。
func TestMapErrMsg_MissingCodesAreFilled(t *testing.T) {
cases := []struct {
name string
code uint32
want string
}{
{"UserCommissionNotEnough", UserCommissionNotEnough, "佣金余额不足"},
{"SendSmsError", SendSmsError, "短信发送失败"},
{"AreaCodeIsEmpty", AreaCodeIsEmpty, "国家区号不能为空"},
{"DeviceBindLimitExceeded", DeviceBindLimitExceeded, "设备绑定数量已达上限"},
{"ExistAvailableTraffic", ExistAvailableTraffic, "存在可用流量"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := MapErrMsg(tc.code)
if got == "Internal Server Error" {
t.Fatalf("MapErrMsg(%d) fell back to Internal Server Error; expected %q", tc.code, tc.want)
}
if got != tc.want {
t.Errorf("MapErrMsg(%d) = %q, want %q", tc.code, got, tc.want)
}
if !IsCodeErr(tc.code) {
t.Errorf("IsCodeErr(%d) = false, want true", tc.code)
}
})
}
}
// TestMapErrMsg_UnknownCodeFallsBack 验证未定义码仍然安全回退,不 panic。
func TestMapErrMsg_UnknownCodeFallsBack(t *testing.T) {
const unknown uint32 = 99999
if got := MapErrMsg(unknown); got != "Internal Server Error" {
t.Errorf("MapErrMsg(%d) = %q, want %q", unknown, got, "Internal Server Error")
}
if IsCodeErr(unknown) {
t.Errorf("IsCodeErr(%d) = true, want false", unknown)
}
}
+19
View File
@@ -272,6 +272,25 @@ func (l *ActivateOrderLogic) claimAndGetOrder(ctx context.Context, orderNo strin
}
func (l *ActivateOrderLogic) releaseClaim(ctx context.Context, orderNo string) error {
// 终态守卫:OrderStatusClaimed(6) 与 orderStatusRefunded(6) 共用同一枚举值。
// 若已存在 333 退款日志,说明此处的 status=6 是「已退款」,不能再降回 5,
// 否则下次 activate 会重新激活订阅、且管理员可二次触发退款导致佣金被多次扣减。
// 详见 HIF-131 / HIF-132。
refunded, err := log.HasRefundCommissionLog(l.svc.DB.WithContext(ctx), orderNo)
if err != nil {
logger.WithContext(ctx).Error("Check refund log before release claim failed",
logger.Field("error", err.Error()),
logger.Field("order_no", orderNo),
)
return fmt.Errorf("check refund log failed for order %s: %w", orderNo, err)
}
if refunded {
logger.WithContext(ctx).Info("Skip release claim for refunded order (status=6 + refund log)",
logger.Field("order_no", orderNo),
)
return nil
}
if err := l.svc.DB.WithContext(ctx).
Model(&order.Order{}).
Where("order_no = ? AND status = ?", orderNo, OrderStatusClaimed).
@@ -6,6 +6,7 @@ import (
"time"
"github.com/hibiken/asynq"
logmodel "github.com/perfect-panel/server/internal/model/log"
"github.com/perfect-panel/server/internal/model/order"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/logger"
@@ -54,6 +55,25 @@ func (l *StuckOrderRecoveryLogic) ProcessTask(ctx context.Context, _ *asynq.Task
for i := range stuckOrders {
o := &stuckOrders[i]
// 终态守卫:OrderStatusClaimed(6) 与 orderStatusRefunded(6) 共用同一枚举值,
// 若该订单已写入 333 退款佣金日志,说明状态 6 表示「已退款」而非「短暂 claim」,
// 必须跳过,否则会把已退款订单重置为 5 + 重新入队 activate,导致重复退款。
// 详见 HIF-131 / HIF-132。
refunded, err := logmodel.HasRefundCommissionLog(l.svc.DB.WithContext(ctx), o.OrderNo)
if err != nil {
logger.WithContext(ctx).Error("[StuckOrderRecovery] Failed to check refund log",
logger.Field("order_no", o.OrderNo),
logger.Field("error", err.Error()),
)
continue
}
if refunded {
logger.WithContext(ctx).Info("[StuckOrderRecovery] Skip refunded order (status=6 + refund log)",
logger.Field("order_no", o.OrderNo),
)
continue
}
result := l.svc.DB.WithContext(ctx).
Model(&order.Order{}).
Where("order_no = ? AND status = ?", o.OrderNo, OrderStatusClaimed).