Compare commits

...

30 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
shanshanzhong147 3644e9ce3f 修复(#128): 统一促销价格资格口径
Build docker and publish / build (20.15.1) (push) Failing after 18m40s
Build docker and publish / build (20.15.1) (pull_request) Failing after 19m24s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-29 22:42:04 -07:00
shanshanzhong147 e5d6539d79 修复(#126): 修复家庭组邀请记录漏查验收分支
Build docker and publish / build (20.15.1) (push) Failing after 20m3s
Build docker and publish / build (20.15.1) (pull_request) Failing after 21m10s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-29 20:35:37 -07:00
shanshanzhong147 e17dc4a273 修复: GET /v1/admin/promo/price/list 字段不匹配导致 400
Build docker and publish / build (20.15.1) (push) Failing after 21m12s
Build docker and publish / build (20.15.1) (pull_request) Failing after 22m17s
前端发 rule_id/subscribe_id (均可选), 后端 API 定义为 promo_rule_id
(required), 直接返回 "PromoRuleId is a required field"。

对齐前端约定 (与 usage/list 命名一致):
- API: promo_rule_id(required) → rule_id + subscribe_id, 均可选
- model.QueryPriceList: 改为接 PriceFilter, 按条件过滤
- 同步 fake mock 与校验测试签名
2026-05-29 01:04:37 -07:00
shanshanzhong147 b162022d39 修复: 邀请列表 UNIX_TIMESTAMP 在 DATETIME(N) 上返回小数导致 Scan int64 失败
Build docker and publish / build (20.15.1) (pull_request) Successful in 7m37s
Build docker and publish / build (20.15.1) (push) Failing after 20m37s
MySQL DATETIME 带小数秒精度时, UNIX_TIMESTAMP() 返回 "1779966403.631"
形式的 DECIMAL, Go 端 int64 字段无法 Scan, 触发 100 条 Scan error,
前端拿到的 invited_at/created_at 全为 0。

改用 CAST(UNIX_TIMESTAMP(...) AS SIGNED) 在 SQL 层截断转 BIGINT,
与 getInviteRecordsLogic / getInviteSalesLogic 的现有约定一致。
2026-05-28 23:15:13 -07:00
shanshanzhong147 075c1215ca 还原: 撤销 fefbd4f5 的 go-zero stub 方案,回到 goctl 1.7.2 + gin 原生 routes
Build docker and publish / build (20.15.1) (pull_request) Failing after 21m54s
Build docker and publish / build (20.15.1) (push) Failing after 20m31s
fefbd4f5 (#104) 用本地 third_party/gozero stub 假冒 go-zero 依赖,
让 goctl 1.9.2 生成的 rest.Server/rest.Route 风格 routes.go 能编译,
但带来非标 vendor、Dockerfile 漏拷、新人误解等维护成本。

本次回到 fefbd4f5 之前的方案:
- routes.go 用 gin 原生 publicUserGroupRouter.GET(...) 风格(goctl 1.7.2)
- server.go 直接 handler.RegisterHandlers(r, svc),无需 rest.NewGinServer
- svc/serviceContext.go 不再持有 AuthMiddleware/DeviceMiddleware/ServerMiddleware 字段
- go.mod 删除 zeromicro/go-zero require + replace 指令
- 删除 third_party/gozero/ stub 模块
- 删除 fefbd4f5 引入的 28 个 goctl 生成的空 stub 文件和 nodeserver/apple 转发器
- Dockerfile 不再需要 COPY third_party/

invite_sales 还原路由保留(gin 老风格写法)。
2026-05-28 21:46:33 -07:00
shanshanzhong147 8ba4471791 修复: Dockerfile 在 go mod download 前拷贝 third_party
Build docker and publish / build (20.15.1) (push) Failing after 26m23s
Build docker and publish / build (20.15.1) (pull_request) Failing after 24m3s
fefbd4f5 (#104) 引入了 replace github.com/zeromicro/go-zero => ./third_party/gozero,
但 Dockerfile 只 COPY 了 go.mod/go.sum, 导致 go mod download 找不到 replace 目标
报 "open /build/third_party/gozero/go.mod: no such file or directory"。
2026-05-28 21:24:28 -07:00
shanshanzhong147 3e265bd837 新功能: 还原 v1/public/user/invite_sales 接口 + promo schema 修复迁移
Build docker and publish / build (20.15.1) (push) Failing after 13m47s
Build docker and publish / build (20.15.1) (pull_request) Failing after 15m7s
- 还原 /v1/public/user/invite_sales 接口及 /invite/sales 别名(与 invite_records 并存)
  逻辑/handler/types 与 197fed7d 删除前版本完全一致,按 fefbd4f5 新 routes 结构注册
- 新增迁移 02155_promo_schema_fix: 幂等修复 subscribe_promo / order 列类型与索引偏差
- 同步 etc/ppanel.yaml 数据库连接配置
- 补齐相关需求与设计文档
2026-05-28 20:46:37 -07:00
shanshanzhong147 fefbd4f56a 修复(#104): 修复 goctl 重新生成代码漂移
Build docker and publish / build (20.15.1) (push) Failing after 58s
Build docker and publish / build (20.15.1) (pull_request) Failing after 52s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 23:54:26 -07:00
shanshanzhong147 197fed7d12 新功能(#102): 新增邀请记录接口并删除旧邀请销售接口
Build docker and publish / build (20.15.1) (push) Failing after 10m56s
Build docker and publish / build (20.15.1) (pull_request) Successful in 8m50s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 22:50:16 -07:00
shanshanzhong147 f452f80100 配置(#98): 扩展文件上传 Content-Type 白名单支持图片
Build docker and publish / build (20.15.1) (push) Failing after 9m55s
Build docker and publish / build (20.15.1) (pull_request) Successful in 8m7s
- 在 etc/ppanel.yaml 与 internal/config/config.go 的 S3.AllowedContentTypes 新增 image/jpeg,image/jpg,image/png,image/webp,image/gif,image/heic,image/heif,image/bmp
- 保留原 zip/gzip/text/json/octet-stream
- validateInitRequest 在拒绝时携带 content_type is not allowed 业务消息
- 新增 internal/logic/public/file/common_test.go,覆盖允许/拒绝及无 Content-Type 嗅探
- doc/tapi-file-upload-zh.md 同步允许类型列表与错误码说明

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 19:50:51 -07:00
shanshanzhong147 1022160ff8 新功能(#89): 增强邀请列表接口 + 新增全局邀请管理接口
Build docker and publish / build (20.15.1) (push) Failing after 9m30s
Build docker and publish / build (20.15.1) (pull_request) Successful in 7m48s
P01: GET /v1/admin/user/invite/list 增加 search/enable/user_id_search
筛选参数,响应新增 order_count/has_purchased/inviter_commission/
inviter_gift_days/invitee_gift_days 权益字段。

P02: 新增 GET /v1/admin/invite/list 全局邀请管理接口,支持按
邀请人/被邀请人筛选和搜索,返回邀请关系及权益聚合数据。

共用 QueryBenefits 批量查询防 N+1,分页上限 100。

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 10:32:28 -07:00
shanshanzhong147 82eff47f38 新功能(#69): 用户级限速覆盖 — 数据层 + 核心逻辑 + 管理接口
Build docker and publish / build (20.15.1) (push) Failing after 8m52s
Build docker and publish / build (20.15.1) (pull_request) Successful in 7m51s
- 新增 migration 02153: user_subscribe 表添加 speed_limit、traffic_limit 列(幂等)
- model 层 Subscribe/SubscribeDetails 新增用户级限速字段(*string 类型支持 nil 回退)
- server 用户列表和管理员详情接口支持用户级限速覆盖优先级计算
- 更新管理员订阅更新接口支持写入/清除用户级限速

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 08:07:16 -07:00
shanshanzhong147 d351b50066 修复(#71): 管理员订阅限速接口拒绝负数限速和非法 traffic_limit
Build docker and publish / build (20.15.1) (push) Failing after 8m50s
Build docker and publish / build (20.15.1) (pull_request) Successful in 7m56s
- SpeedLimit 加 validate:"gte=0" 校验
- TrafficLimit 加 JSON 格式校验
- 新增单测覆盖负数限速和非法 JSON 场景

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 07:13:05 -07:00
shanshanzhong147 4366a9be8b 修复(#79): 促销管理后台API + 审查问题修复
Build docker and publish / build (20.15.1) (push) Failing after 9m10s
Build docker and publish / build (20.15.1) (pull_request) Successful in 8m18s
- 实现促销管理接口:规则CRUD、优惠价配置、使用记录查询
- 修复 UpsertPrices 新增记录时提前 return 的问题
- DeleteRule/DeletePrice 不存在记录返回 code=404
- SetPromoPriceRequest.items 空数组校验
- 分页参数限制 page>0、1<=size<=200
- 下单侧促销价格按数量档总价口径计算(含 #87 修复)

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 06:32:42 -07:00
shanshanzhong147 b5e50d1ee5 修复(#75): 按数量精确匹配套餐列表促销
Build docker and publish / build (20.15.1) (push) Failing after 9m2s
Build docker and publish / build (20.15.1) (pull_request) Successful in 7m58s
- loadSubscribePromoMap 返回 map[subscribeID]map[quantity]*SubscribePromo 二级映射
- 候选查询按 subscribe_id、quantity、priority DESC 排序,一次取出所有 quantity 档位
- 下单路径 QueryEligibleRules 将 quantity 条件移至 JOIN,精确匹配
- 永久订阅(expire_time=0)用 CASE WHEN 排序兜底,不再误判为回归促销
- 新增 promoEligibility、model、subscribe promo 单元测试

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 06:22:49 -07:00
shanshanzhong147 02b41e7a2c 修复(#85): 促销系统 quantity 设计修正补丁(跨任务统一修复)
Build docker and publish / build (20.15.1) (push) Failing after 8m50s
Build docker and publish / build (20.15.1) (pull_request) Successful in 8m19s
- subscribe_promo 表加 quantity 字段,BIGINT NOT NULL DEFAULT 1
- EvaluatePromo 加 quantity 参数,按 subscribeID + quantity 精确匹配
- Promo 从 Subscribe 顶层移到 SubscribeDiscount
- 查询加 quantity,返回 map[subscribeID][quantity] 二级映射
- recordPromoUsage 错误向上传播,不再静默吞掉
- preCreate 和 purchase 的 allowPromo 判定统一为 orderType==1
- 迁移脚本增加幂等处理(guarded DROP/ADD/MODIFY)

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 05:57:21 -07:00
shanshanzhong147 d12c340743 新功能(#77): 套餐列表 API 返回规格级促销信息
Build docker and publish / build (20.15.1) (push) Failing after 8m23s
Build docker and publish / build (20.15.1) (pull_request) Successful in 7m54s
将 promo 字段从 Subscribe 顶层移至 SubscribeDiscount(discount[] 项内),
促销查询按 subscribe_id + quantity 维度写入,每个规格独立命中最高优先级规则。

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 02:19:58 -07:00
98 changed files with 8212 additions and 624 deletions
+50
View File
@@ -0,0 +1,50 @@
syntax = "v1"
info (
title: "Invite API"
desc: "API for ppanel"
author: "Tension"
email: "tension@ppanel.com"
version: "0.0.1"
)
import "../types.api"
type (
GetInviteManageListRequest {
Page int `form:"page"`
Size int `form:"size"`
Search string `form:"search"`
InviterId int64 `form:"inviter_id"`
InviteeId int64 `form:"invitee_id"`
}
InviteManageRecord {
InviterId int64 `json:"inviter_id"`
InviterIdentifier string `json:"inviter_identifier"`
InviteeId int64 `json:"invitee_id"`
InviteeIdentifier string `json:"invitee_identifier"`
InviteeAvatar string `json:"invitee_avatar"`
InviteeEnable bool `json:"invitee_enable"`
InvitedAt int64 `json:"invited_at"`
OrderCount int64 `json:"order_count"`
HasPurchased bool `json:"has_purchased"`
InviterCommission int64 `json:"inviter_commission"`
InviterGiftDays int64 `json:"inviter_gift_days"`
InviteeGiftDays int64 `json:"invitee_gift_days"`
}
GetInviteManageListResponse {
Total int64 `json:"total"`
List []InviteManageRecord `json:"list"`
}
)
@server (
prefix: v1/admin/invite
group: admin/invite
middleware: AuthMiddleware
)
service ppanel {
@doc "Get invite manage list"
@handler GetInviteManageList
get /list (GetInviteManageListRequest) returns (GetInviteManageListResponse)
}
+122
View File
@@ -0,0 +1,122 @@
syntax = "v1"
info (
title: "promo admin API"
desc: "API for ppanel"
author: "Tension"
email: "tension@ppanel.com"
version: "0.0.1"
)
import "../types.api"
type (
CreatePromoRuleRequest {
Name string `json:"name" validate:"required,max=100"`
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
Params map[string]interface{} `json:"params"`
Priority int64 `json:"priority" validate:"gte=0"`
Enabled *bool `json:"enabled"`
StartTime *int64 `json:"start_time"`
EndTime *int64 `json:"end_time"`
}
UpdatePromoRuleRequest {
Id int64 `uri:"id" validate:"required,gt=0"`
Name string `json:"name" validate:"required,max=100"`
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
Params map[string]interface{} `json:"params"`
Priority int64 `json:"priority" validate:"gte=0"`
Enabled *bool `json:"enabled"`
StartTime *int64 `json:"start_time"`
EndTime *int64 `json:"end_time"`
}
GetPromoRuleDetailRequest {
Id int64 `uri:"id" validate:"required,gt=0"`
}
DeletePromoRuleRequest {
Id int64 `uri:"id" validate:"required,gt=0"`
}
GetPromoRuleListRequest {
Page int64 `form:"page" validate:"required,gt=0"`
Size int64 `form:"size" validate:"required,gt=0,lte=200"`
Type string `form:"type" validate:"omitempty,oneof=new_user inactive_user campaign"`
Enabled *bool `form:"enabled"`
Search string `form:"search,omitempty"`
}
GetPromoRuleListResponse {
Total int64 `json:"total"`
List []PromoRule `json:"list"`
}
SetPromoPriceRequest {
PromoRuleId int64 `json:"promo_rule_id" validate:"required,gt=0"`
Items []PromoPriceItem `json:"items" validate:"required,min=1,dive"`
}
GetPromoPriceListRequest {
Page int64 `form:"page" validate:"required,gt=0"`
Size int64 `form:"size" validate:"required,gt=0,lte=200"`
RuleId int64 `form:"rule_id,omitempty"`
SubscribeId int64 `form:"subscribe_id,omitempty"`
}
GetPromoPriceListResponse {
Total int64 `json:"total"`
List []PromoPrice `json:"list"`
}
DeletePromoPriceRequest {
Id int64 `uri:"id" validate:"required,gt=0"`
}
GetPromoUsageListRequest {
Page int64 `form:"page" validate:"required,gt=0"`
Size int64 `form:"size" validate:"required,gt=0,lte=200"`
RuleId int64 `form:"rule_id,omitempty"`
UserId int64 `form:"user_id,omitempty"`
SubscribeId int64 `form:"subscribe_id,omitempty"`
OrderNo string `form:"order_no,omitempty"`
}
GetPromoUsageListResponse {
Total int64 `json:"total"`
List []PromoUsage `json:"list"`
}
)
@server (
prefix: v1/admin/promo
group: admin/promo
middleware: AuthMiddleware
)
service ppanel {
@doc "Create promo rule"
@handler CreateRule
post /rule (CreatePromoRuleRequest) returns (PromoRule)
@doc "Get promo rule list"
@handler GetRuleList
get /rule/list (GetPromoRuleListRequest) returns (GetPromoRuleListResponse)
@doc "Get promo rule detail"
@handler GetRuleDetail
get /rule/:id (GetPromoRuleDetailRequest) returns (PromoRule)
@doc "Update promo rule"
@handler UpdateRule
put /rule/:id (UpdatePromoRuleRequest) returns (PromoRule)
@doc "Delete promo rule"
@handler DeleteRule
delete /rule/:id (DeletePromoRuleRequest)
@doc "Set promo prices"
@handler SetPrice
post /price (SetPromoPriceRequest)
@doc "Get promo price list"
@handler GetPriceList
get /price/list (GetPromoPriceListRequest) returns (GetPromoPriceListResponse)
@doc "Delete promo price"
@handler DeletePrice
delete /price/:id (DeletePromoPriceRequest)
@doc "Get promo usage list"
@handler GetUsageList
get /usage/list (GetPromoUsageListRequest) returns (GetPromoUsageListResponse)
}
+2 -1
View File
@@ -46,6 +46,7 @@ type (
SpeedLimit int64 `json:"speed_limit"` SpeedLimit int64 `json:"speed_limit"`
DeviceLimit int64 `json:"device_limit"` DeviceLimit int64 `json:"device_limit"`
Quota int64 `json:"quota"` Quota int64 `json:"quota"`
NewUserOnly *bool `json:"new_user_only"`
Nodes []int64 `json:"nodes"` Nodes []int64 `json:"nodes"`
NodeTags []string `json:"node_tags"` NodeTags []string `json:"node_tags"`
NodeGroupIds []int64 `json:"node_group_ids,omitempty"` NodeGroupIds []int64 `json:"node_group_ids,omitempty"`
@@ -74,6 +75,7 @@ type (
SpeedLimit int64 `json:"speed_limit"` SpeedLimit int64 `json:"speed_limit"`
DeviceLimit int64 `json:"device_limit"` DeviceLimit int64 `json:"device_limit"`
Quota int64 `json:"quota"` Quota int64 `json:"quota"`
NewUserOnly *bool `json:"new_user_only"`
Nodes []int64 `json:"nodes"` Nodes []int64 `json:"nodes"`
NodeTags []string `json:"node_tags"` NodeTags []string `json:"node_tags"`
NodeGroupIds []int64 `json:"node_group_ids,omitempty"` NodeGroupIds []int64 `json:"node_group_ids,omitempty"`
@@ -175,4 +177,3 @@ service ppanel {
@handler ResetAllSubscribeToken @handler ResetAllSubscribeToken
post /reset_all_token returns (ResetAllSubscribeTokenResponse) post /reset_all_token returns (ResetAllSubscribeTokenResponse)
} }
+45 -1
View File
@@ -23,10 +23,12 @@ type (
SubscribeId *int64 `form:"subscribe_id,omitempty"` SubscribeId *int64 `form:"subscribe_id,omitempty"`
UserSubscribeId *int64 `form:"user_subscribe_id,omitempty"` UserSubscribeId *int64 `form:"user_subscribe_id,omitempty"`
ShortCode string `form:"short_code,omitempty"` ShortCode string `form:"short_code,omitempty"`
DeviceId *int64 `form:"device_id,omitempty"`
FamilyJoined *bool `form:"family_joined,omitempty"` FamilyJoined *bool `form:"family_joined,omitempty"`
FamilyStatus string `form:"family_status,omitempty"` FamilyStatus string `form:"family_status,omitempty"`
FamilyOwnerUserId *int64 `form:"family_owner_user_id,omitempty"` FamilyOwnerUserId *int64 `form:"family_owner_user_id,omitempty"`
FamilyId *int64 `form:"family_id,omitempty"` FamilyId *int64 `form:"family_id,omitempty"`
SortOrder string `form:"sort_order,omitempty"`
} }
// GetUserListResponse // GetUserListResponse
GetUserListResponse { GetUserListResponse {
@@ -149,7 +151,7 @@ type (
ExpiredAt int64 `json:"expired_at"` ExpiredAt int64 `json:"expired_at"`
Upload int64 `json:"upload"` Upload int64 `json:"upload"`
Download int64 `json:"download"` Download int64 `json:"download"`
SpeedLimit *int64 `json:"speed_limit,omitempty"` SpeedLimit *int64 `json:"speed_limit,omitempty" validate:"omitempty,gte=0"`
TrafficLimit *string `json:"traffic_limit,omitempty"` TrafficLimit *string `json:"traffic_limit,omitempty"`
} }
GetUserLoginLogsRequest { GetUserLoginLogsRequest {
@@ -229,6 +231,40 @@ type (
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"` WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
Reason string `json:"reason" validate:"required,max=500"` Reason string `json:"reason" validate:"required,max=500"`
} }
GetAdminUserInviteStatsRequest {
UserId int64 `form:"user_id" validate:"required"`
}
GetAdminUserInviteStatsResponse {
InviteCount int64 `json:"invite_count"`
TotalCommission int64 `json:"total_commission"`
CurrentCommission int64 `json:"current_commission"`
ReferralPercentage uint8 `json:"referral_percentage"`
OnlyFirstPurchase bool `json:"only_first_purchase"`
}
GetAdminUserInviteListRequest {
UserId int64 `form:"user_id" validate:"required"`
Page int `form:"page"`
Size int `form:"size"`
Search string `form:"search"`
Enable *int `form:"enable"`
UserIdSearch int64 `form:"user_id_search"`
}
AdminInvitedUser {
Id int64 `json:"id"`
Avatar string `json:"avatar"`
Identifier string `json:"identifier"`
Enable bool `json:"enable"`
CreatedAt int64 `json:"created_at"`
OrderCount int64 `json:"order_count"`
HasPurchased bool `json:"has_purchased"`
InviterCommission int64 `json:"inviter_commission"`
InviterGiftDays int64 `json:"inviter_gift_days"`
InviteeGiftDays int64 `json:"invitee_gift_days"`
}
GetAdminUserInviteListResponse {
Total int64 `json:"total"`
List []AdminInvitedUser `json:"list"`
}
) )
@server ( @server (
@@ -381,4 +417,12 @@ service ppanel {
@doc "Reject withdrawal" @doc "Reject withdrawal"
@handler RejectWithdrawal @handler RejectWithdrawal
post /withdrawal/reject (RejectWithdrawalRequest) post /withdrawal/reject (RejectWithdrawalRequest)
@doc "Get admin user invite stats"
@handler GetAdminUserInviteStats
get /invite/stats (GetAdminUserInviteStatsRequest) returns (GetAdminUserInviteStatsResponse)
@doc "Get admin user invite list"
@handler GetAdminUserInviteList
get /invite/list (GetAdminUserInviteListRequest) returns (GetAdminUserInviteListResponse)
} }
+2 -3
View File
@@ -111,7 +111,7 @@ type (
@server ( @server (
prefix: v1/server prefix: v1/server
group: server group: node/server
middleware: ServerMiddleware middleware: ServerMiddleware
) )
service ppanel { service ppanel {
@@ -138,11 +138,10 @@ service ppanel {
@server ( @server (
prefix: v2/server prefix: v2/server
group: server group: node/server
) )
service ppanel { service ppanel {
@doc "Get Server Protocol Config" @doc "Get Server Protocol Config"
@handler QueryServerProtocolConfig @handler QueryServerProtocolConfig
get /:server_id (QueryServerConfigRequest) returns (QueryServerConfigResponse) get /:server_id (QueryServerConfigRequest) returns (QueryServerConfigResponse)
} }
+21 -1
View File
@@ -201,6 +201,23 @@ type (
GrowthRate string `json:"growth_rate"` GrowthRate string `json:"growth_rate"`
PaidGrowthRate string `json:"paid_growth_rate"` PaidGrowthRate string `json:"paid_growth_rate"`
} }
GetInviteRecordsRequest {
Page int `form:"page"`
Size int `form:"size"`
StartTime int64 `form:"start_time"`
EndTime int64 `form:"end_time"`
}
InviteRecord {
Role string `json:"role"`
PeerHash string `json:"peer_hash"`
GiftDays int64 `json:"gift_days"`
OrderNo string `json:"order_no"`
CreatedAt int64 `json:"created_at"`
}
GetInviteRecordsResponse {
Total int64 `json:"total"`
List []InviteRecord `json:"list"`
}
GetInviteSalesRequest { GetInviteSalesRequest {
Page int `form:"page"` Page int `form:"page"`
Size int `form:"size"` Size int `form:"size"`
@@ -397,6 +414,10 @@ service ppanel {
@handler GetAgentRealtime @handler GetAgentRealtime
get /agent_realtime (GetAgentRealtimeRequest) returns (GetAgentRealtimeResponse) get /agent_realtime (GetAgentRealtimeRequest) returns (GetAgentRealtimeResponse)
@doc "Get Invite Records"
@handler GetInviteRecords
get /invite_records (GetInviteRecordsRequest) returns (GetInviteRecordsResponse)
@doc "Get Invite Sales" @doc "Get Invite Sales"
@handler GetInviteSales @handler GetInviteSales
get /invite_sales (GetInviteSalesRequest) returns (GetInviteSalesResponse) get /invite_sales (GetInviteSalesRequest) returns (GetInviteSalesResponse)
@@ -424,4 +445,3 @@ service ppanel {
@handler DeviceWsConnect @handler DeviceWsConnect
get /device_ws_connect get /device_ws_connect
} }
+58 -15
View File
@@ -160,15 +160,17 @@ type (
OnlyRealDevice bool `json:"only_real_device"` OnlyRealDevice bool `json:"only_real_device"`
} }
RegisterConfig { RegisterConfig {
StopRegister bool `json:"stop_register"` StopRegister bool `json:"stop_register"`
EnableTrial bool `json:"enable_trial"` EnableTrial bool `json:"enable_trial"`
TrialSubscribe int64 `json:"trial_subscribe"` EnableTrialEmailWhitelist bool `json:"enable_trial_email_whitelist"`
TrialTime int64 `json:"trial_time"` TrialSubscribe int64 `json:"trial_subscribe"`
TrialTimeUnit string `json:"trial_time_unit"` TrialTime int64 `json:"trial_time"`
EnableIpRegisterLimit bool `json:"enable_ip_register_limit"` TrialTimeUnit string `json:"trial_time_unit"`
IpRegisterLimit int64 `json:"ip_register_limit"` TrialEmailDomainWhitelist string `json:"trial_email_domain_whitelist"`
IpRegisterLimitDuration int64 `json:"ip_register_limit_duration"` EnableIpRegisterLimit bool `json:"enable_ip_register_limit"`
DeviceLimit int64 `json:"device_limit"` IpRegisterLimit int64 `json:"ip_register_limit"`
IpRegisterLimitDuration int64 `json:"ip_register_limit_duration"`
DeviceLimit int64 `json:"device_limit"`
} }
VerifyConfig { VerifyConfig {
CaptchaType string `json:"captcha_type"` // local or turnstile CaptchaType string `json:"captcha_type"` // local or turnstile
@@ -226,9 +228,46 @@ type (
CurrencySymbol string `json:"currency_symbol"` CurrencySymbol string `json:"currency_symbol"`
} }
SubscribeDiscount { SubscribeDiscount {
Quantity int64 `json:"quantity"` Quantity int64 `json:"quantity"`
Discount float64 `json:"discount"` Discount float64 `json:"discount"`
MapApple string `json:"map_apple"` NewUserOnly bool `json:"new_user_only"`
MapApple string `json:"map_apple"`
Promo *SubscribePromo `json:"promo"`
}
PromoPrice {
Id int64 `json:"id"`
SubscribeId int64 `json:"subscribe_id"`
PromoRuleId int64 `json:"promo_rule_id"`
Quantity int64 `json:"quantity"`
PromoPrice int64 `json:"promo_price"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
PromoPriceItem {
SubscribeId int64 `json:"subscribe_id" validate:"required,gt=0"`
Quantity int64 `json:"quantity" validate:"required,gt=0,lte=1000"`
PromoPrice int64 `json:"promo_price" validate:"required,gt=0"`
}
PromoRule {
Id int64 `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Params map[string]interface{} `json:"params"`
Priority int64 `json:"priority"`
Enabled bool `json:"enabled"`
StartTime *int64 `json:"start_time"`
EndTime *int64 `json:"end_time"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
PromoUsage {
Id int64 `json:"id"`
UserId int64 `json:"user_id"`
PromoRuleId int64 `json:"promo_rule_id"`
SubscribeId int64 `json:"subscribe_id"`
OrderNo string `json:"order_no"`
PromoPrice int64 `json:"promo_price"`
CreatedAt int64 `json:"created_at"`
} }
SubscribePromo { SubscribePromo {
RuleName string `json:"rule_name"` RuleName string `json:"rule_name"`
@@ -250,7 +289,6 @@ type (
UnitPrice int64 `json:"unit_price"` UnitPrice int64 `json:"unit_price"`
UnitTime string `json:"unit_time"` UnitTime string `json:"unit_time"`
Discount []SubscribeDiscount `json:"discount"` Discount []SubscribeDiscount `json:"discount"`
Promo *SubscribePromo `json:"promo"`
NodeCount int64 `json:"node_count"` NodeCount int64 `json:"node_count"`
Replacement int64 `json:"replacement"` Replacement int64 `json:"replacement"`
Inventory int64 `json:"inventory"` Inventory int64 `json:"inventory"`
@@ -258,6 +296,7 @@ type (
SpeedLimit int64 `json:"speed_limit"` SpeedLimit int64 `json:"speed_limit"`
DeviceLimit int64 `json:"device_limit"` DeviceLimit int64 `json:"device_limit"`
Quota int64 `json:"quota"` Quota int64 `json:"quota"`
NewUserOnly bool `json:"new_user_only"`
Nodes []int64 `json:"nodes"` Nodes []int64 `json:"nodes"`
NodeTags []string `json:"node_tags"` NodeTags []string `json:"node_tags"`
NodeGroupIds []int64 `json:"node_group_ids,omitempty"` NodeGroupIds []int64 `json:"node_group_ids,omitempty"`
@@ -522,10 +561,13 @@ type (
} }
UserSubscribe { UserSubscribe {
Id int64 `json:"id"` Id int64 `json:"id"`
IdStr string `json:"id_str"`
UserId int64 `json:"user_id"` UserId int64 `json:"user_id"`
OrderId int64 `json:"order_id"` OrderId int64 `json:"order_id"`
SubscribeId int64 `json:"subscribe_id"` SubscribeId int64 `json:"subscribe_id"`
Subscribe Subscribe `json:"subscribe"` Subscribe Subscribe `json:"subscribe"`
NodeGroupId int64 `json:"node_group_id"`
NodeGroupName string `json:"node_group_name"`
StartTime int64 `json:"start_time"` StartTime int64 `json:"start_time"`
ExpireTime int64 `json:"expire_time"` ExpireTime int64 `json:"expire_time"`
FinishedAt int64 `json:"finished_at"` FinishedAt int64 `json:"finished_at"`
@@ -871,8 +913,9 @@ type (
Sandbox *bool `json:"sandbox,omitempty"` Sandbox *bool `json:"sandbox,omitempty"`
} }
AttachAppleTransactionResponse { AttachAppleTransactionResponse {
ExpiresAt int64 `json:"expires_at"` ExpiresAt int64 `json:"expires_at"`
Tier string `json:"tier"` Tier string `json:"tier"`
ExistingOrderNo string `json:"existing_order_no,omitempty"`
} }
RestoreAppleTransactionsRequest { RestoreAppleTransactionsRequest {
Transactions []string `json:"transactions" validate:"required"` Transactions []string `json:"transactions" validate:"required"`
+3
View File
@@ -4316,6 +4316,9 @@
"discount": { "discount": {
"type": "number", "type": "number",
"format": "double" "format": "double"
},
"promo": {
"$ref": "#/definitions/SubscribePromo"
} }
}, },
"title": "SubscribeDiscount", "title": "SubscribeDiscount",
@@ -0,0 +1,559 @@
# App 邀请列表与商品套餐折扣需求梳理
本文基于当前 `ppanel-server` 代码现状,对以下两个需求做整理:
1. App 需要一个“邀请列表/邀请记录”接口。
2. 商品套餐需要补充“折扣信息”,当存在折扣时,App 需要做样式展示,并支持用户继续下单购买。
目标是帮助产品、前端、后端快速统一口径,明确:
- 现在已有哪些接口可以复用
- 哪些地方确实需要新增
- “接口增加三个字段”更适合加在哪一层
---
## 1. 需求结论
### 1.1 邀请列表
当前公开侧已经有一部分邀请能力,但**没有一个完全匹配“App 邀请记录列表”语义的公开接口**。
现状:
- 已有 `GET /v1/public/user/affiliate/list`
- 能返回“我邀请了哪些用户”
- 但字段较少,只包含基础信息
- 已有 `GET /v1/public/user/invite_sales`
- 返回的是“被邀请用户的成交订单记录”
- 不是“邀请用户记录列表”
- 已有 `GET /v1/public/user/invite_stats`
- 返回邀请统计
- 不是列表
结论:
- 如果 App 只是要展示“我邀请了哪些人”,`/affiliate/list` 可以复用。
- 如果 App 需要展示“邀请时间、是否购买、购买次数、带来的佣金/赠送天数”等完整邀请记录,则**建议新增一个公开接口**。
### 1.2 商品套餐折扣
当前公开侧套餐列表接口 `GET /v1/public/subscribe/list` **已经返回 `discount` 字段**,下单预览接口 `POST /v1/public/order/pre` 也已经支持折扣计算。
现状:
- 套餐列表已有折扣规则数组 `discount`
- 预下单接口已有:
- 原价 `price`
- 实付 `amount`
- 折扣金额 `discount`
- 活动优惠 `promo_discount`
- 优惠券减免 `coupon_discount`
- 手续费 `fee_amount`
结论:
- 后端**不是完全没有折扣能力**,而是“已经有计算能力,但 App 展示层使用起来不够直接”。
- 如果需求明确要求“接口增加三个字段”,**更推荐补在套餐列表返回的 `discount[]` 子项里**,而不是直接加在下单接口里。
---
## 2. 当前代码现状
## 2.1 邀请相关
### 2.1.1 已有公开接口
#### A. 邀请基础列表
接口:
- `GET /v1/public/user/affiliate/list`
请求:
- `page`
- `size`
返回结构:
- `total`
- `list[]`
- `identifier`
- `avatar`
- `registered_at`
- `enable`
特点:
- 能表达“我邀请了谁”
- 不能表达“是否购买 / 购买次数 / 给我带来多少收益”
对应代码:
- `apis/public/user.api`
- `internal/logic/public/user/queryUserAffiliateListLogic.go`
#### B. 邀请成交记录
接口:
- `GET /v1/public/user/invite_sales`
返回结构:
- `total`
- `list[]`
- `amount`
- `updated_at`
- `user_hash`
- `product_name`
特点:
- 更像“邀请带来的订单流水”
- 不是邀请用户列表
对应代码:
- `internal/logic/public/user/getInviteSalesLogic.go`
#### C. 邀请统计
接口:
- `GET /v1/public/user/invite_stats`
返回结构:
- `friendly_count`
- `history_count`
特点:
- 只适合头部统计卡片
- 不适合列表页
对应代码:
- `internal/logic/public/user/getUserInviteStatsLogic.go`
### 2.1.2 已有后台接口
后台已经有更完整的邀请记录能力,可以直接参考:
- `GetAdminUserInviteList`
- `GetInviteManageList`
这些接口已经能返回:
- 邀请时间
- 是否购买
- 购买次数
- 邀请人佣金
- 邀请人赠送天数
- 被邀请人赠送天数
对应代码:
- `internal/logic/admin/user/getAdminUserInviteListLogic.go`
- `internal/logic/admin/invite/getInviteManageListLogic.go`
结论:
- 邀请记录的统计逻辑后端已经有现成实现思路。
- 新增 App 公开接口时,建议复用这部分逻辑,不要从零再写一套。
---
## 2.2 套餐折扣相关
### 2.2.1 套餐列表接口已有折扣规则
接口:
- `GET /v1/public/subscribe/list`
当前返回的套餐结构 `Subscribe` 中已包含:
- `unit_price`
- `discount []SubscribeDiscount`
其中 `SubscribeDiscount` 当前字段为:
- `quantity`
- `discount`
- `new_user_only`
- `map_apple`
- `promo`
对应代码:
- `apis/public/subscribe.api`
- `internal/logic/public/subscribe/querySubscribeListLogic.go`
- `internal/types/types.go`
说明:
- `discount` 是按购买数量 `quantity` 生效的阶梯折扣
- 不是单个套餐固定只有一个折扣值
### 2.2.2 预下单接口已有价格计算结果
接口:
- `POST /v1/public/order/pre`
当前已返回:
- `price`:原价
- `amount`:最终应付
- `discount`:折扣减免金额
- `promo_discount`:活动优惠金额
- `gift_amount`:礼品余额抵扣
- `coupon_discount`:优惠券减免
- `fee_amount`:手续费
对应代码:
- `apis/public/order.api`
- `internal/logic/public/order/preCreateOrderLogic.go`
说明:
- 只要 App 知道 `subscribe_id + quantity [+ coupon] [+ payment]`,就已经能拿到准确的下单金额
- 所以“下单购买”这件事本身,后端主链路已经具备
---
## 3. 差距分析
## 3.1 邀请列表的真实缺口
如果产品要的是“邀请记录页”,通常至少会关心以下内容:
- 被邀请用户
- 邀请时间
- 是否已购买
- 购买次数
- 给邀请人带来的佣金
- 双方赠送天数
而当前:
- `/affiliate/list` 只有基础用户列表
- `/invite_sales` 是订单成交记录
- `/invite_stats` 是统计值
所以当前公开侧缺一个“**邀请关系维度的邀请记录列表**”。
## 3.2 套餐折扣的真实缺口
后端目前的主要问题不是“不会算折扣”,而是:
- `discount[]` 更偏规则定义
- App 如果只想直接展示“折后价 / 优惠金额 / 折扣标签”,还需要自己再算一层
- 这会增加前端理解成本,也容易和后端口径不一致
所以当前更合理的改法是:
- 保留现有折扣规则
- 再额外补充几个**面向展示的字段**
---
## 4. 推荐方案
## 4.1 邀请记录接口
### 方案建议
新增一个公开接口,例如:
- `GET /v1/public/user/invite_records`
说明:
- 从登录态中取当前用户 ID
- 不从前端传 `user_id`
- 只查“当前用户邀请的记录”
### 请求参数建议
```json
{
"page": 1,
"size": 10
}
```
### 返回字段建议
```json
{
"total": 2,
"list": [
{
"invitee_id": 1001,
"invitee_identifier": "138****8888",
"invitee_avatar": "https://...",
"invitee_enable": true,
"invited_at": 1716800000,
"order_count": 3,
"has_purchased": true,
"inviter_commission": 1200,
"inviter_gift_days": 30,
"invitee_gift_days": 7
}
]
}
```
### 字段说明
- `invitee_id`:被邀请用户 ID
- `invitee_identifier`:被邀请用户展示账号
- `invitee_avatar`:头像
- `invitee_enable`:是否启用
- `invited_at`:邀请时间
- `order_count`:该被邀请用户产生的有效订单数
- `has_purchased`:是否已购买
- `inviter_commission`:给邀请人带来的佣金,单位建议继续沿用分
- `inviter_gift_days`:邀请人获赠天数
- `invitee_gift_days`:被邀请人获赠天数
### 实现建议
优先复用现有后台逻辑思路:
- 参考 `internal/logic/admin/user/getAdminUserInviteListLogic.go`
- 或参考 `internal/logic/admin/invite/getInviteManageListLogic.go`
公开接口与后台接口的主要差异只有两点:
- 公开接口不允许前端指定 `user_id`
- 公开接口按当前登录用户本人维度返回
### 是否可以不新增接口
可以,但前提是 App 接受以下拆分:
- 列表页用 `/affiliate/list`
- 顶部统计用 `/invite_stats`
- 订单流水页用 `/invite_sales`
如果产品要的是一个完整“邀请记录页”,不建议这样拆三次请求,前端维护成本偏高。
---
## 4.2 套餐折扣字段建议
### 核心建议
“接口增加三个字段”建议**加在 `SubscribeDiscount` 子项里**,不要直接加在 `Subscribe` 顶层。
原因:
- 折扣是按 `quantity` 生效的
- 一个套餐可能有多个折扣档位
- 如果加在套餐顶层,很难表达“买 1 个月”和“买 12 个月”对应不同折扣
### 推荐新增字段
建议在 `SubscribeDiscount` 中增加以下三个展示字段:
- `discount_price`
- `discount_amount`
- `discount_desc`
推荐结构如下:
```json
{
"quantity": 12,
"discount": 80,
"new_user_only": false,
"map_apple": "",
"promo": null,
"discount_price": 9600,
"discount_amount": 2400,
"discount_desc": "年付8折"
}
```
### 三个字段的含义
#### 1. `discount_price`
- 含义:该档位折后总价
- 计算建议:`unit_price * quantity * discount / 100`
- 单位:分
作用:
- App 可直接展示“折后价”
- 下单时直接把该项的 `quantity` 带入 `/order/pre``/order/purchase`
#### 2. `discount_amount`
- 含义:该档位比原价便宜多少钱
- 计算建议:`unit_price * quantity - discount_price`
- 单位:分
作用:
- App 可直接展示“立省 xx”
#### 3. `discount_desc`
- 含义:折扣展示文案
- 示例:
- `年付8折`
- `季付9折`
- `新用户首单8折`
作用:
- App 可直接做角标、标签、促销文案展示
### 为什么不推荐这三个字段加在下单接口
因为下单接口本来就是“结果型接口”,它已经能返回:
- 原价
- 折扣金额
- 实付金额
如果只是为了 App 卡片展示,再去每个套餐都调一次 `/order/pre`,成本会比较高:
- 请求次数多
- 页面首屏会更慢
- 前端链路更复杂
更合适的做法是:
- 套餐列表接口负责“展示友好”
- 预下单接口负责“结算准确”
---
## 5. 推荐改动清单
## 5.1 邀请列表
建议新增:
- 新接口:`GET /v1/public/user/invite_records`
建议新增类型:
- `GetUserInviteRecordsRequest`
- `UserInviteRecord`
- `GetUserInviteRecordsResponse`
建议实现位置:
- `apis/public/user.api`
- `internal/types/types.go`
- `internal/handler/public/user/`
- `internal/logic/public/user/`
## 5.2 套餐折扣
建议调整:
- `SubscribeDiscount` 增加 3 个字段:
- `discount_price`
- `discount_amount`
- `discount_desc`
建议实现位置:
- `apis/types.api`
- `internal/types/types.go`
- `internal/logic/public/subscribe/querySubscribeListLogic.go`
---
## 6. 前后端协作建议
## 6.1 App 侧调用建议
邀请页建议:
- 头部统计:`/v1/public/user/invite_stats`
- 邀请记录列表:`/v1/public/user/invite_records`
- 如果还要看成交流水:`/v1/public/user/invite_sales`
套餐页建议:
- 先调 `/v1/public/subscribe/list` 渲染套餐和折扣标签
- 用户点某个折扣档位时,带 `subscribe_id + quantity``/v1/public/order/pre`
- 用户确认后再调 `/v1/public/order/purchase`
## 6.2 单位口径建议
建议继续保持后端金额统一为“分”:
- `unit_price`
- `discount_price`
- `discount_amount`
- `amount`
- `coupon_discount`
这样可以避免前后端出现小数精度问题。
---
## 7. 最终建议
### 建议一
如果你们只是要“邀请用户名单”,可直接复用:
- `GET /v1/public/user/affiliate/list`
### 建议二
如果你们要的是完整“邀请记录”,建议新增:
- `GET /v1/public/user/invite_records`
这是本次需求里更合理的新增接口。
### 建议三
商品套餐“折扣信息”不建议重新设计一整套下单逻辑。
当前后端已经具备:
- 套餐折扣规则
- 预下单价格计算
- 正式下单购买
更推荐做法是:
-`SubscribeDiscount` 里补 3 个展示字段:
- `discount_price`
- `discount_amount`
- `discount_desc`
这样改动最小,也最贴近 App 展示场景。
---
## 8. 相关代码位置
- `internal/logic/public/user/queryUserAffiliateListLogic.go`
- `internal/logic/public/user/getInviteSalesLogic.go`
- `internal/logic/public/user/getUserInviteStatsLogic.go`
- `internal/logic/admin/user/getAdminUserInviteListLogic.go`
- `internal/logic/admin/invite/getInviteManageListLogic.go`
- `internal/logic/public/subscribe/querySubscribeListLogic.go`
- `internal/logic/public/order/preCreateOrderLogic.go`
- `internal/logic/public/order/purchaseLogic.go`
- `internal/types/types.go`
- `apis/public/user.api`
- `apis/public/subscribe.api`
- `apis/public/order.api`
+435
View File
@@ -0,0 +1,435 @@
# App 端三个接口对接文档
> 适用:移动端 / 桌面端 App
> 维护:基于当前 `internal/handler` + `internal/logic` 代码反向梳理
> 时间:2026-05-27
涉及接口:
1. [文件上传](#1-文件上传) — `POST /v1/public/file/upload`
2. [订阅列表(含促销 promo](#2-订阅列表含促销-promo) — `GET /v1/public/subscribe/list`
3. [邀请赠送记录](#3-邀请赠送记录) — `GET /v1/public/user/invite_records`
公共说明:
- BaseURL 示例:`https://tapi.hifast.biz`
- 鉴权头:`Authorization: <JWT>`(注意:**不要**写 `Bearer ` 前缀,本项目 `AuthMiddleware` 直接取 token 值)
- 业务码包在 `{ code, msg, data }` 信封中,`code = 200` 为成功
- 默认 `Accept: application/json`,可选 `lang: zh_CN`
- 经过 `AuthMiddleware` + `DeviceMiddleware` 的接口都需要登录态 + 设备绑定校验
---
## 1. 文件上传
### 1.1 Endpoint
```
POST /v1/public/file/upload
Content-Type: multipart/form-data
```
- Handler: `internal/handler/public/file/fileUploadHandler.go`
- Logic: `internal/logic/public/file/fileuploadlogic.go:33`
- 路由: `internal/handler/routes.go:934`
- 中间件: `AuthMiddleware` + `DeviceMiddleware`(必须登录)
### 1.2 请求
#### Form 参数
| 字段 | 位置 | 必填 | 说明 |
|---|---|---|---|
| `biz_type` | form | 是 | 业务分类标签,会作为对象 key 的一部分(如 `app-package``avatar` |
| `file` | form file | 是 | 待上传文件二进制 |
#### 文件约束(来自 `etc/ppanel.yaml` → `S3`,可调整)
| 项 | 默认值 |
|---|---|
| 单文件最大 | **104857600 字节(100 MiB** |
| 允许的 Content-Type | `application/zip, application/x-zip-compressed, application/gzip, application/x-gzip, application/octet-stream, text/plain, application/json, image/jpeg, image/jpg, image/png, image/webp, image/gif, image/heic, image/heif, image/bmp` |
> Content-Type 判定优先级:multipart 文件头里的 `Content-Type` → 文件嗅探(前 512 字节)→ 兜底 `application/octet-stream`。
> **前端 form 上传时尽量带上 `Content-Type`**,否则被嗅探成 `application/octet-stream` 可能不在白名单里。
### 1.3 请求示例
```bash
curl -X POST 'https://tapi.hifast.biz/v1/public/file/upload' \
-H 'Authorization: <JWT>' \
-H 'Accept: application/json' \
-F 'biz_type=app-package' \
-F 'file=@"/Users/Apple/Documents/avatar.jpg";type=image/jpeg'
```
### 1.4 响应
| 字段 | 类型 | 说明 |
|---|---|---|
| `data.url` | string | 上传完成后的可访问 URL,规则:`{S3.PublicBaseURL or S3.Endpoint}/{bucket}/{prefix}/{YYYY}/{MM}/{DD}/{userId}/{safeFileName}__{fileId}` |
成功示例:
```json
{
"code": 200,
"msg": "success",
"data": {
"url": "http://107.173.50.22:5016/hifastvpn/app-upload/2026/05/28/510/2026-05-27_20.03.55.jpg__226ad097c2ee4e3546e729c5"
}
}
```
### 1.5 错误码
| 业务码 | 触发场景 |
|---|---|
| `InvalidAccess` | 未登录 / JWT 无效 |
| `ParamError` | 缺少 `biz_type``file` |
| `InvalidParams` | `biz_type` 为空、文件名为空、size <= 0、超过 `MaxUploadSize``Content-Type` 不在白名单 |
| `ERROR` | S3 未启用(`S3.Enable=false` / S3 写入失败 |
### 1.6 前端易踩坑
1. `file` 字段名必须是 `file`,写 `image` / `upload` 都不行。
2. `biz_type` 走 form 字段(`form:"biz_type"`),不要塞 query 里。
3. 上传成功只返回 `url`,不返回 `file_id` / 大小等元数据;如需附加元数据,请走分片协议 `POST /upload/init` + `POST /upload/complete`
4. 想上传 PDF / DOC 不会成功——白名单里没有,需要后端调 `S3.AllowedContentTypes`
---
## 2. 订阅列表(含促销 promo
### 2.1 Endpoint
```
GET /v1/public/subscribe/list
```
- Handler: `internal/handler/public/subscribe/querySubscribeListHandler.go`
- Logic: `internal/logic/public/subscribe/querySubscribeListLogic.go:32`
- Promo 合并逻辑: `internal/logic/public/subscribe/promo.go`
- 路由: `internal/handler/routes.go:1026`
- 中间件: **`OptionalAuthMiddleware` + `DeviceMiddleware`**(**未登录也能请求**,但未登录时只能拿到 `rule_type = campaign` 的促销)
### 2.2 请求
#### Query 参数
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
| `language` | string | 否 | 语言筛选,传值后返回该语言版本;不传则按系统默认语言返回 |
#### 头部说明(影响返回内容)
| Header | 影响 |
|---|---|
| `Authorization` | 传则识别为登录态,能拿到 `new_user` / `inactive_user` 类型的个性化促销;不传只返回 `campaign` 类型 |
| `X-App-Id` | **不传**会被识别为"老版本客户端",每个套餐的 `discount` 列表会被**截掉最后一个元素**。新版 App 必须带 `X-App-Id` |
### 2.3 请求示例
```bash
curl -X GET 'https://tapi.hifast.biz/v1/public/subscribe/list?language=zh-CN' \
-H 'Authorization: <JWT>' \
-H 'X-App-Id: hifast-ios' \
-H 'Accept: application/json'
```
### 2.4 响应
#### 顶层
| 字段 | 类型 | 说明 |
|---|---|---|
| `data.total` | int64 | 返回的套餐数量(= `len(list)`,不是数据库总数) |
| `data.list` | Subscribe[] | 套餐列表 |
#### `Subscribe` 关键字段
| 字段 | 类型 | 说明 |
|---|---|---|
| `id` | int64 | 套餐 ID |
| `name` | string | 套餐名 |
| `language` | string | 当前返回的语言版本 |
| `description` | string | 套餐描述(可能是富文本/Markdown) |
| `unit_price` | int64 | 单时间单位**原价**,单位:**分** |
| `unit_time` | string | 时间单位,枚举:`Day` / `Month` / `Year`(注意首字母大写) |
| `discount` | SubscribeDiscount[] | 量级折扣 + 促销,按 `quantity` 升序 |
| `node_count` | int64 | 节点数 |
| `traffic` | int64 | 套餐总流量,单位:字节 |
| `speed_limit` | int64 | 限速,单位见后端约定 |
| `device_limit` | int64 | 同时在线设备数限制 |
| `quota` | int64 | 总配额 |
| `show` | bool | 是否在前端展示 |
| `sell` | bool | 是否可售卖(本接口只返回 `sell=true` |
| `show_original_price` | bool | 是否展示划线原价 |
| `reset_cycle` | int64 | 流量重置周期 |
| `renewal_reset` | bool | 续费时是否重置流量 |
| `created_at` / `updated_at` | int64 | 秒级 Unix 时间戳 |
#### `SubscribeDiscount` 字段
| 字段 | 类型 | 说明 |
|---|---|---|
| `quantity` | int64 | 购买的时间单位数量(如 1 = 1 个月,3 = 3 个月) |
| `discount` | float64 | 量级折扣比例,0 表示无折扣,0.05 表示再优惠 5% |
| `map_apple` | string | 对应 Apple IAP 商品 ID |
| `promo` | SubscribePromo \| null | **#77 新增的促销对象**,命中促销规则时下发,否则为 `null` |
#### `SubscribePromo` 字段
| 字段 | 类型 | 说明 |
|---|---|---|
| `rule_name` | string | 促销规则名(运营在后台填写,可直接给用户展示,如"新人首单 8 折" |
| `rule_type` | string | 规则类型枚举(见下表) |
| `promo_price` | int64 | **促销价**,单位:**分**。优先级高于 `unit_price * discount`,前端命中促销时按此价显示 |
| `expires_at` | int64 | 该促销对当前用户的失效时间(**秒级 Unix**),`0` 表示无明确截止 |
#### `rule_type` 枚举
| 值 | 含义 | 资格判定 |
|---|---|---|
| `campaign` | 全员/限时活动 | 仅看 `start_time` / `end_time` 是否在窗口内;**未登录也会下发** |
| `new_user` | 新用户首单 | 登录用户,且 `now < user.created_at + params.window_hours``expires_at = user.created_at + window_hours` |
| `inactive_user` | 老用户唤回 | 登录用户,且距离最近一个订阅过期已超过 `params.inactive_months` 个月;`expires_at = 规则 end_time` |
> 多条促销规则命中同一 `(subscribe_id, quantity)` 时,按 `priority DESC, id ASC` 取**首条**,不是合并。
### 2.5 响应示例
```json
{
"code": 200,
"msg": "success",
"data": {
"total": 1,
"list": [
{
"id": 1,
"name": "月付套餐",
"language": "zh-CN",
"description": "...",
"unit_price": 1000,
"unit_time": "Month",
"show_original_price": true,
"node_count": 30,
"traffic": 107374182400,
"device_limit": 3,
"discount": [
{
"quantity": 1,
"discount": 0,
"map_apple": "ios.month1",
"promo": {
"rule_name": "新人首单 8 折",
"rule_type": "new_user",
"promo_price": 800,
"expires_at": 1780500000
}
},
{
"quantity": 3,
"discount": 0.05,
"map_apple": "ios.month3",
"promo": null
}
],
"show": true,
"sell": true,
"created_at": 1764547200,
"updated_at": 1779934580
}
]
}
}
```
### 2.6 价格计算建议(前端)
对每个 `discount` 元素:
```
原价 = unit_price * quantity
量级折后价 = round(原价 * (1 - discount))
if promo != null:
实付 = promo.promo_price * quantity // 注意:promo_price 是「单价」,乘以 quantity
划线价 = 原价 // 用于展示「省 XX」
else:
实付 = 量级折后价
划线价 = 原价(show_original_price=true 时展示)
```
> 注意:`promo_price` 设计为**单价**(与 `unit_price` 同级),不是总价。
> 命中促销时建议同时显示 `rule_name`"新人首单 8 折")和倒计时(基于 `expires_at`)。
### 2.7 前端易踩坑
1. **必带 `X-App-Id`**——否则 `discount` 数组最后一个会被砍掉。
2. **促销分登录态**:未登录时只能拿到 `campaign`;未拿到 `new_user`/`inactive_user` 时先检查是否传了 `Authorization`
3. **`unit_time` 是 PascalCase**`Day` / `Month` / `Year`,别小写匹配。
4. **金额单位都是分**`unit_price``promo_price`),展示时除以 100。
5. **`expires_at = 0`** 表示无截止,不要展示成 1970 年。
6. `total` 是当前返回的条数,不是数据库总数(接口在 logic 里强制 `Size: 9999`,相当于不分页)。
---
## 3. 邀请赠送记录
> 当前用户的"邀请赠送天数"流水。包含两类:
> - 当前用户作为**邀请人**,被邀请的朋友下单触发的赠送;
> - 当前用户作为**被邀请人**,自己下单触发的对应赠送(双向赠送)。
>
> 数据源:`system_logs` 表,`type = 33 (TypeGift)` 且 `content.remark = "邀请赠送"`。
> 这里**只是赠送天数**,不包含邀请佣金(请走 affiliate 系列接口)。
### 3.1 Endpoint
```
GET /v1/public/user/invite_records
```
- Handler: `internal/handler/public/user/getInviteRecordsHandler.go`
- Logic: `internal/logic/public/user/getInviteRecordsLogic.go:61`
- 路由: `internal/handler/routes.go:1122`
- 中间件: `AuthMiddleware` + `DeviceMiddleware`(必须登录)
### 3.2 请求
#### Query 参数
| 字段 | 类型 | 必填 | 默认 | 说明 |
|---|---|---|---|---|
| `page` | int | 否 | `1` | 页码,<1 自动归一为 1 |
| `size` | int | 否 | `10` | 每页条数,<1 归一为 10**>100 截断为 100** |
| `start_time` | int64 | 否 | `0` | 起始时间(**秒级 Unix**),`0` 表示不过滤下界 |
| `end_time` | int64 | 否 | `0` | 截止时间(**秒级 Unix**),`0` 表示不过滤上界 |
> ⚠️ `start_time` / `end_time` 单位是**秒**(后端用 `FROM_UNIXTIME(?)`)。传毫秒会过滤掉所有记录。
#### 请求示例
```bash
# 不带时间过滤
curl -X GET 'https://tapi.hifast.biz/v1/public/user/invite_records?page=1&size=20' \
-H 'Authorization: <JWT>' \
-H 'Accept: application/json'
# 带时间过滤
curl -X GET 'https://tapi.hifast.biz/v1/public/user/invite_records?page=1&size=20&start_time=1764547200&end_time=1780099200' \
-H 'Authorization: <JWT>'
```
> 旧 curl 模板里的 `--data-urlencode 'page=1'` 等对 GET 是 form body,不会被读取,请用 query string。
### 3.3 响应
#### 顶层
| 字段 | 类型 | 说明 |
|---|---|---|
| `data.total` | int64 | 当前过滤条件下的**记录总数**(用于分页) |
| `data.list` | InviteRecord[] | 当前页列表,可能为空数组 `[]` |
#### `InviteRecord` 字段
| 字段 | 类型 | 说明 |
|---|---|---|
| `role` | string | 当前用户在该条记录中的角色:`inviter``invitee`(详见下表) |
| `peer_hash` | string | 对端用户的脱敏哈希(10 位定长数字字符串),用于"匿名展示朋友"。订单已删 / 对端 id 缺失时为 `""` |
| `gift_days` | int64 | 本次赠送天数(来源 `system_logs.content.amount` |
| `order_no` | string | 触发本次赠送的订单号 |
| `created_at` | int64 | 赠送时间,**毫秒级 Unix**SQL 端 `UNIX_TIMESTAMP(created_at) * 1000` |
> ⚠️ **时间戳单位不一致**:请求里的 `start_time/end_time` 是**秒**,响应里的 `created_at` 是**毫秒**。前端请区分对待。
> (与项目其它接口"统一秒级"约定不同,是该接口的当前实现。)
#### `role` 取值
| 值 | 含义 | `peer_hash` 来源 |
|---|---|---|
| `inviter` | 当前用户是**邀请人**,朋友下单触发的赠送 | 被邀请人(即订单的 `user_id`)的脱敏 hash |
| `invitee` | 当前用户是**被邀请人**,自己下单触发的赠送 | 邀请人(`user.referer_id`)的脱敏 hash |
判定规则:默认 `inviter`;若 `order.user_id == 当前用户 id`,切换为 `invitee` 并改用 `referer_id` 计算 hash。
#### 排序与分页
- 排序:`created_at DESC, id DESC`(最近一条在最前)
- 分页:`LIMIT size OFFSET (page-1)*size`
- `total` **不**受 `LIMIT/OFFSET` 影响
### 3.4 响应示例
非空:
```json
{
"code": 200,
"msg": "success",
"data": {
"total": 2,
"list": [
{
"role": "inviter",
"peer_hash": "0382716459",
"gift_days": 30,
"order_no": "20260527123456789",
"created_at": 1779934580000
},
{
"role": "invitee",
"peer_hash": "1745920031",
"gift_days": 30,
"order_no": "20260520112233445",
"created_at": 1779329780000
}
]
}
}
```
空:
```json
{
"code": 200,
"msg": "success",
"data": {
"total": 0,
"list": []
}
}
```
### 3.5 错误码
| 业务码 | 触发场景 |
|---|---|
| `InvalidAccess` | 未登录 / JWT 无效 |
| `ParamError` | 参数绑定失败 |
| `DatabaseQueryError` | DB 查询失败(count / 日志 / 订单任一) |
### 3.6 前端易踩坑
1. 传**毫秒**给 `start_time/end_time` → 永远拿到空集。请传**秒**。
2. 拿到的 `created_at` 是**毫秒****不要再 `*1000`**,直接 `new Date(created_at)` 即可。
3. 空列表是 `[]` 不是 `null`,可直接 `.map`
4. `peer_hash` 可能为 `""`UI 兜底展示"未知朋友"。
5. `size` 上限 100,传 1000 会被截断。
6. 本接口**只含赠送天数**,不含邀请佣金(佣金 → affiliate 接口)。
---
## 附录:业务码常量速查
| 名称 | HTTP 含义 | 出现场景 |
|---|---|---|
| `200` | 成功 | `{"code":200,"msg":"success",...}` |
| `InvalidAccess` | 未授权 | 未登录 / JWT 无效 / 设备未绑定 |
| `ParamError` | 参数错误 | 请求绑定失败、缺必填项 |
| `InvalidParams` | 参数校验不通过 | 业务规则校验失败(文件超限、Content-Type 不合法等) |
| `DatabaseQueryError` | DB 错 | SQL 查询失败 |
| `ERROR` | 通用错 | 第三方/中间件失败(S3 未启用、S3 写入失败等) |
+796
View File
@@ -0,0 +1,796 @@
# 促销优惠价系统设计文档
## 1. 背景与目标
### 1.1 业务需求
为套餐规格提供可配置的优惠价格能力,支持多种促销场景:
- **新客优惠**:注册 N 天内的用户享受优惠价
- **回归用户**:N 个月未活跃的用户享受优惠价
- **活动促销**:指定时间段内所有用户享受优惠价
- **未来可扩展**:首充优惠、邀请用户专属价、指定地区优惠等
### 1.2 设计原则
1. **纯新增,不改老代码**:现有的 `new_user_only` + `discount.NewUserOnly` + 24h 窗口逻辑全部保留不动
2. **固定价格,非百分比**:运营直接设定优惠价(如 $5.99),不再需要反算折扣百分比
3. **后台可配置**:规则类型、参数、时间窗口、优先级均可在管理后台配置
4. **促销价不叠加批量折扣**:促销价命中时即为最终基础单价,跳过 `getDiscount()` 的百分比折扣
### 1.3 与现有体系的关系
```
现有体系(保留不动):
subscribe.NewUserOnly → 套餐级新客限制
discount[].NewUserOnly → 折扣档位级新客限制
newUserEligibility.go → 24h 窗口 + 家庭组判定
newUserDiscountEligibility.go → 新客折扣资格组装
getDiscount() → 百分比折扣选择
order.IsNew → 订单首购标记(统计/佣金用)
新增体系(本次设计):
promo_rule 表 → 可配置的促销规则
subscribe_promo 表 → 规格×规则 的优惠价
promo_usage 表 → 使用记录(运营分析用)
EvaluatePromo() → 促销资格判定
```
**互斥规则**:促销价命中时,跳过老的百分比折扣逻辑(`getDiscount()`)。
两套体系不叠加 — 用户要么走促销价,要么走原价+百分比折扣,不会同时生效。
---
## 2. 数据模型
### 2.1 新增表:`promo_rule`(促销规则)
```sql
CREATE TABLE `promo_rule` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '规则名称,如"新客7天优惠"',
`type` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '规则类型:new_user / inactive_user / campaign',
`params` JSON NOT NULL COMMENT '类型专属参数',
`priority` INT NOT NULL DEFAULT 0 COMMENT '优先级,数值越大越优先匹配',
`enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用',
`start_time` DATETIME DEFAULT NULL COMMENT '生效开始时间,NULL=立即生效',
`end_time` DATETIME DEFAULT NULL COMMENT '生效结束时间,NULL=永不过期',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`deleted_at` DATETIME DEFAULT NULL COMMENT '软删除时间',
PRIMARY KEY (`id`),
KEY `idx_enabled_priority` (`enabled`, `priority` DESC)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表';
```
### 2.2 新增表:`subscribe_promo`(规格优惠价)
```sql
CREATE TABLE `subscribe_promo` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '套餐规格 ID',
`promo_rule_id` BIGINT UNSIGNED NOT NULL COMMENT '促销规则 ID',
`promo_price` BIGINT NOT NULL DEFAULT 0 COMMENT '该规格在此规则下的优惠价(分)',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_subscribe_rule` (`subscribe_id`, `promo_rule_id`),
KEY `idx_promo_rule_id` (`promo_rule_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格促销价表';
```
### 2.3 新增表:`promo_usage`(促销使用记录)
用于运营分析,不做强制去重约束。
```sql
CREATE TABLE `promo_usage` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户 ID',
`promo_rule_id` BIGINT UNSIGNED NOT NULL COMMENT '使用的规则 ID',
`subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '购买的规格 ID',
`order_no` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '关联订单号',
`promo_price` BIGINT NOT NULL DEFAULT 0 COMMENT '使用时的促销单价(分)',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_user_rule` (`user_id`, `promo_rule_id`),
KEY `idx_order_no` (`order_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销使用记录表';
```
### 2.4 `order` 表新增字段
```sql
ALTER TABLE `order`
ADD COLUMN `promo_rule_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '促销规则ID, 0=未使用促销',
ADD COLUMN `promo_discount` BIGINT NOT NULL DEFAULT 0 COMMENT '促销优惠金额(分)';
```
**字段说明**
| 订单字段 | 含义 | 促销命中时 | 未命中时 |
|---------|------|-----------|---------|
| `Price` | 原始总价 = `UnitPrice × Quantity` | 不变,始终记录原价 | 不变 |
| `promo_rule_id` | 使用的促销规则 | 规则 ID | 0 |
| `promo_discount` | 促销优惠金额 | `(UnitPrice - PromoPrice) × Quantity` | 0 |
| `Discount` | 百分比折扣金额 | **0**(不叠加) | 正常计算 |
| `Amount` | 最终支付金额 | 基于促销价计算 | 基于原价+折扣计算 |
**订单自证**:任何一笔订单都能独立还原其价格构成,不需要回查促销规则表:
```
Amount = Price - promo_discount - Discount - CouponDiscount + FeeAmount - GiftAmount
```
### 2.5 ER 关系
```
subscribe (1) ──── (*) subscribe_promo (*) ──── (1) promo_rule
user (1) ──────── (*) promo_usage (*) ─────────── (1) promo_rule
(*) order ← 新增 promo_rule_id, promo_discount
```
---
## 3. 规则类型定义
### 3.1 `new_user` — 新客优惠
**含义**:用户注册后 N 小时内可享受优惠价
**params 结构**
```json
{
"window_hours": 168
}
```
**判定逻辑**
```
eligible = (当前时间 - 用户注册时间) < window_hours
expires_at = 用户注册时间 + window_hours
```
**与老逻辑的区别**
| | 老逻辑 | 新逻辑 |
|--|--------|--------|
| 窗口期 | 硬编码 24h | 配置化,后台可改 |
| 判定基准 | 首台设备注册时间 + 家庭组 | 用户注册时间(`user.created_at` |
| 价格方式 | 百分比折扣 | 固定价格 |
| 与折扣叠加 | 是(百分比折扣本身) | 否(替代原价,跳过折扣) |
### 3.2 `inactive_user` — 回归用户优惠
**含义**:最近 N 个月没有活跃订阅的用户可享受优惠价
**params 结构**
```json
{
"inactive_months": 3
}
```
**判定逻辑**
```
last_active = 用户最后一个订阅的 expire_time
eligible = last_active 为空(从未购买过)
OR (当前时间 - last_active) >= inactive_months 个月
expires_at = 规则的 end_time(如有),否则无过期
```
**查询依据**`user_subscribe` 表中该用户最近一条记录的 `expire_time`
**注意**:「从未购买过」的用户同时满足 `new_user``inactive_user`,靠 `priority` 排序选择高优先级的那条。
### 3.3 `campaign` — 活动促销
**含义**:在指定时间段内,所有用户均可享受优惠价
**params 结构**
```json
{}
```
活动促销不需要额外参数,完全靠 `promo_rule.start_time``end_time` 控制。
**判定逻辑**
```
eligible = start_time <= 当前时间 <= end_time
expires_at = end_time
```
### 3.4 扩展预留
未来新增规则类型只需:
1. 定义新的 `type` 字符串(如 `first_purchase``referral``region`
2. 定义对应的 `params` 结构
3. 在判定逻辑中增加一个 `case` 分支
不需要改表结构,不需要改 API 格式。
---
## 4. 核心逻辑
### 4.1 促销资格判定
新增文件:`internal/logic/common/promoEligibility.go`
```go
type PromoResult struct {
Eligible bool
RuleID int64
RuleName string
RuleType string
PromoPrice int64 // 促销单价(分)
ExpiresAt time.Time
}
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID int64) (*PromoResult, error) {
// 1. 查询该规格关联的所有已启用规则,按 priority DESC
// 2. 遍历规则,按类型判定
// 3. 首条命中即返回
}
```
### 4.2 各类型判定函数
```go
func evaluateNewUser(user *User, params RuleParams) (bool, time.Time) {
windowHours := params.WindowHours
if windowHours <= 0 {
return false, time.Time{}
}
expiresAt := user.CreatedAt.Add(time.Duration(windowHours) * time.Hour)
eligible := time.Now().Before(expiresAt)
return eligible, expiresAt
}
func evaluateInactiveUser(ctx context.Context, userID int64, rule PromoRule) (bool, time.Time) {
inactiveMonths := rule.Params.InactiveMonths
if inactiveMonths <= 0 {
return false, time.Time{}
}
lastExpire := getLastSubscriptionExpireTime(ctx, userID)
if lastExpire.IsZero() {
return true, rule.GetExpiresAt()
}
threshold := time.Now().AddDate(0, -inactiveMonths, 0)
eligible := lastExpire.Before(threshold)
return eligible, rule.GetExpiresAt()
}
```
### 4.3 下单流程集成(不叠加方案)
`purchaseLogic.go``sub.UnitPrice * req.Quantity` 之前,插入促销价判定:
```go
// === 新增:促销价判定 ===
promoResult, promoErr := commonLogic.EvaluatePromo(l.ctx, l.svcCtx, u.Id, targetSubscribeID)
if promoErr != nil {
return nil, promoErr
}
var promoDiscount int64
var promoRuleID int64
if promoResult.Eligible {
// 促销命中 → 用促销价,跳过百分比折扣
price = promoResult.PromoPrice * req.Quantity
promoDiscount = (sub.UnitPrice * req.Quantity) - price
promoRuleID = promoResult.RuleID
discount = 1 // 不叠加批量折扣
discountAmount = 0
} else {
// 未命中 → 走原有逻辑(不动)
price = sub.UnitPrice * req.Quantity
discount = getDiscount(newUserDiscount.Discounts, req.Quantity, newUserDiscount.EligibleForDiscount)
discountAmount = price - int64(math.Round(float64(price)*discount))
}
// === 新增结束 ===
// 后续 coupon / fee / gift 逻辑完全不动
```
**订单创建时记录**
```go
orderInfo := &order.Order{
// ... 原有字段不动 ...
Price: sub.UnitPrice * req.Quantity, // 始终记录原价
PromoRuleID: promoRuleID, // 新增
PromoDiscount: promoDiscount, // 新增
Discount: discountAmount, // 促销命中时为 0
Amount: amount,
}
```
**激活时写 usage**`activateOrderLogic.go` 追加):
```go
if orderInfo.PromoRuleID > 0 {
insertPromoUsage(ctx, orderInfo.UserId, orderInfo.PromoRuleID, orderInfo.SubscribeId, orderInfo.OrderNo, promoPrice)
}
```
### 4.4 价格计算完整流程
```
┌───────────────────────────────────────────────────┐
│ 1. 判定促销 │
│ EvaluatePromo(userId, subscribeId) │
├──────────────┬────────────────────────────────────┤
│ 促销命中 │ 促销未命中 │
├──────────────┼────────────────────────────────────┤
│ basePrice │ basePrice │
│ = promoPrice│ = unitPrice │
│ │ │
│ discount = 0 │ discount = getDiscount(...) │
│ (跳过折扣) │ (百分比折扣正常生效) │
├──────────────┴────────────────────────────────────┤
│ 2. price = basePrice × quantity │
│ amount = price - discountAmount │
├───────────────────────────────────────────────────┤
│ 3. 优惠券(原有逻辑,不动) │
│ amount -= couponDiscount │
├───────────────────────────────────────────────────┤
│ 4. 手续费(原有逻辑,不动) │
│ amount += feeAmount │
├───────────────────────────────────────────────────┤
│ 5. 余额抵扣(原有逻辑,不动) │
│ amount -= giftAmount │
└───────────────────────────────────────────────────┘
```
---
## 5. 退款影响分析
### 5.1 结论:退款逻辑无需改动
当前退款流程(`refundOrderLogic.go`)基于**订单上已存储的字段**运作,不回查价格体系:
| 退款动作 | 数据来源 | 是否受促销影响 |
|---------|---------|--------------|
| 退款金额 | `order.Amount`(支付时已锁定) | 否 — Amount 已反映促销价 |
| 佣金回退 | `system_log` 表中的 commission 记录 | 否 — 佣金是基于 Amount 计算的 |
| 订阅终止 | `user_subscribe.status → 3` | 否 — 和价格无关 |
| 审计日志 | `buildRefundAuditLog()` 读订单快照 | 否 — 记录的就是实际值 |
**原因**:订单创建时所有金额字段(Price、Amount、Discount、PromoDiscount、FeeAmount 等)都已写入 `order` 表。退款只读这些已存储的值,不会重新计算价格。
### 5.2 退款后的促销资格
退款后用户的订阅被终止(`expire_time = now - 1s`)。如果用户再次购买:
| 场景 | 促销资格 | 说明 |
|------|---------|------|
| 新客退款后重新购买 | 如仍在窗口期内 → 仍然可以享受促销价 | 正常行为,`promo_usage` 只是记录不做去重 |
| 回归用户退款后重新购买 | 需重新判定 `inactive_months` | 退款后订阅 expire_time 被设为过去时间 |
| 活动促销退款后重新购买 | 如活动仍在进行 → 可以继续购买 | 活动促销不限次数 |
这些都是合理的业务行为,不需要额外处理。
### 5.3 佣金影响
佣金计算公式(`activateOrderLogic.go:1104`):
```go
amount := l.calculateCommission(orderInfo.Amount - orderInfo.FeeAmount, referralPercentage)
```
- `Amount` 在促销命中时已反映促销价(更低的金额)
- 所以佣金会相应减少 — **这是正确的行为**
- 退款时佣金回退金额从 `system_log` 读取,回退的也是减少后的佣金
**无需任何改动**
---
## 6. Apple IAP 影响分析
### 6.1 现状
- Apple IAP 价格在 App Store Connect 中配置,不支持后端动态定价
- 当前通过 `discount[].MapApple` 字段映射 Apple Product ID
- IAP 订单在 `appleIAPNotifyLogic.go` 中处理,走独立的价格逻辑
### 6.2 设计决策
**促销价不适用于 IAP 订单**。原因:
- IAP 价格由 Apple 控制,后端无法干预
- IAP 通知回调(`appleIAPNotifyLogic.go`)有独立的价格处理流程
- IAP 审计订单设 `IsNew: false`,不走常规购买逻辑
**实现方式**`EvaluatePromo()` 不需要特殊处理 — IAP 订单根本不经过 `purchaseLogic.go`,自然不会触发促销判定。
---
## 7. 各购买场景适配
### 7.1 需要集成促销的场景
| 文件 | 场景 | 集成方式 |
|------|------|---------|
| `purchaseLogic.go` | 新购 | 完整促销判定 + 不叠加逻辑 |
| `preCreateOrderLogic.go` | 价格预览 | 同上(返回 promo_discount 字段) |
### 7.2 不需要改动的场景
| 文件 | 场景 | 原因 |
|------|------|------|
| `renewalLogic.go` | 续费 | 促销价仅限首购,续费走原价+折扣 |
| `rechargeLogic.go` | 余额充值 | 充值不涉及套餐价格 |
| `redeemCodeLogic.go` | 兑换码 | 兑换码有自己的固定逻辑 |
| `recoverOrderLogic.go` | 历史导入 | 导入的是已完成订单 |
| `appleIAPNotifyLogic.go` | IAP 续订 | Apple 控制价格 |
| `portal/purchaseLogic.go` | 游客购买 | 游客无 user_id,无法判定促销资格 |
| `refundOrderLogic.go` | 退款 | 读取订单已存储的金额,不重新计算 |
| `activateOrderLogic.go` | 订单激活 | 只追加 promo_usage 写入,价格不重算 |
### 7.3 统计报表
现有统计 SQL`order/model.go` 中 8 处)按 `is_new` 拆分收入,**不需要改动**。
未来如需促销维度报表,可通过 `order.promo_rule_id` 字段扩展:
```sql
SUM(CASE WHEN promo_rule_id > 0 THEN amount ELSE 0 END) AS promo_order_amount,
SUM(CASE WHEN promo_rule_id = 0 THEN amount ELSE 0 END) AS normal_order_amount
```
---
## 8. API 设计
### 8.1 套餐列表 API(改造)
**接口**`GET /v1/public/subscribe/list`
**响应变更**:在原有 `Subscribe` 结构体中追加 `promo` 字段。
```json
{
"list": [
{
"id": 1,
"name": "基础套餐",
"unit_price": 288,
"discount": [...],
"promo": {
"rule_name": "新客7天优惠",
"rule_type": "new_user",
"promo_price": 279,
"expires_at": 1748870400
}
},
{
"id": 2,
"name": "标准套餐",
"unit_price": 688,
"promo": null
}
]
}
```
**`promo` 字段说明**
| 字段 | 类型 | 说明 |
|------|------|------|
| `rule_name` | string | 规则名称,前端展示用 |
| `rule_type` | string | 规则类型,前端可据此展示不同样式 |
| `promo_price` | int64 | 优惠单价(分),注意是单价不是总价 |
| `expires_at` | int64 | 优惠过期时间戳(秒),0 = 无过期 |
- 用户未登录时:仅展示 `campaign` 类型促销(不需要用户信息)
- 用户已登录:展示所有命中的促销
- 未命中任何规则时,`promo``null`
### 8.2 预算订单 API(改造)
**接口**`POST /v1/public/order/pre`
**响应追加字段**
```json
{
"price": 688,
"amount": 499,
"discount": 0,
"promo_discount": 189,
"coupon_discount": 0,
"fee_amount": 0,
"gift_amount": 0
}
```
| 字段 | 含义 |
|------|------|
| `price` | 原始总价 = `UnitPrice × Quantity` |
| `promo_discount` | 促销优惠 = `(UnitPrice - PromoPrice) × Quantity` |
| `discount` | 百分比折扣优惠(促销命中时为 0) |
| `amount` | 最终支付金额 |
前端可展示:~~原价 ¥6.88~~ → 促销价 ¥4.99
### 8.3 管理后台 API(新增)
#### 8.3.1 促销规则 CRUD
```
POST /v1/admin/promo/rule 创建规则
GET /v1/admin/promo/rule/list 规则列表
GET /v1/admin/promo/rule/:id 规则详情
PUT /v1/admin/promo/rule/:id 更新规则
DELETE /v1/admin/promo/rule/:id 删除规则(软删除)
```
**创建/更新请求体**
```json
{
"name": "新客7天优惠",
"type": "new_user",
"params": {
"window_hours": 168
},
"priority": 10,
"enabled": true,
"start_time": null,
"end_time": null
}
```
**校验规则**
- `type` 必须是已支持的类型
- `params``type` 做结构校验(如 `new_user` 必须有 `window_hours > 0`
- `priority` >= 0
- `start_time` < `end_time`(如果两者都提供)
#### 8.3.2 规格优惠价配置
```
POST /v1/admin/promo/price 批量设置优惠价
GET /v1/admin/promo/price/list 查询某规则下的所有优惠价
DELETE /v1/admin/promo/price/:id 删除某条优惠价
```
**批量设置请求体**
```json
{
"promo_rule_id": 1,
"items": [
{"subscribe_id": 1, "promo_price": 279},
{"subscribe_id": 2, "promo_price": 599}
]
}
```
**校验**`promo_price` 必须 < 对应规格的 `unit_price`(防止配置错误)。
#### 8.3.3 使用记录查询
```
GET /v1/admin/promo/usage/list?rule_id=1&page=1&size=20
```
---
## 9. 缓存策略
### 9.1 规则缓存
```
Key: promo:rules:enabled
Value: JSON 数组(所有启用的规则,按 priority DESC
TTL: 300 秒(5 分钟)
清除: 管理后台修改规则时主动删除
```
### 9.2 规格优惠价缓存
```
Key: promo:subscribe:{subscribe_id}
Value: JSON 数组(该规格关联的所有 rule_id → promo_price
TTL: 300 秒
清除: 管理后台修改优惠价时主动删除
```
### 9.3 注意事项
- 缓存 TTL 300 秒意味着活动 `end_time` 到期后最多 5 分钟延迟,可接受
- 管理后台操作后主动 DEL 缓存 key,确保配置变更及时生效
- `EvaluatePromo()` 缓存未命中时回查 DB
---
## 10. 确定的决策项
| 编号 | 问题 | 结论 | 原因 |
|------|------|------|------|
| D-01 | 促销价与批量折扣叠加 | **不叠加** | 促销价即最终单价,跳过 `getDiscount()` |
| D-02 | 未登录用户展示促销价 | 仅展示 `campaign` 类型 | `new_user`/`inactive_user` 需要用户信息 |
| D-03 | 续费订单适用促销价 | **仅首购** | 促销价用于拉新/回归,续费走原价 |
| D-04 | 回归用户判定方式 | 订阅过期时间 | `user_subscribe.expire_time`,数据最可靠 |
| D-05 | 多规则命中 | 按 `priority` DESC 取第一条 | 运营可控 |
| D-07 | Portal(游客)购买走促销 | **不走** | 游客无 user_id,无法判定资格 |
---
## 11. 新增文件清单
| 层级 | 新增文件 | 说明 |
|------|----------|------|
| **Model** | `internal/model/promo_rule/promo_rule.go` | 促销规则模型 |
| **Model** | `internal/model/subscribe_promo/subscribe_promo.go` | 规格优惠价模型 |
| **Model** | `internal/model/promo_usage/promo_usage.go` | 使用记录模型 |
| **Logic** | `internal/logic/common/promoEligibility.go` | 促销资格判定核心逻辑 |
| **Logic** | `internal/logic/admin/promo/` 目录(CRUD) | 管理后台逻辑 |
| **Handler** | `internal/handler/admin/promo/` 目录 | 管理后台 Handler |
| **Types** | `internal/types/types.go` 追加 | 新增结构体 |
| **Migration** | `initialize/migrate/database/02153_promo_rule.up.sql` | 建表 + order 加字段 |
| **Migration** | `initialize/migrate/database/02153_promo_rule.down.sql` | 回滚 |
### 需改动的已有文件(仅追加)
| 文件 | 改动方式 |
|------|----------|
| `internal/logic/public/subscribe/querySubscribeListLogic.go` | 追加:查促销信息,填充 `promo` |
| `internal/logic/public/order/purchaseLogic.go` | 追加:促销判定 + 不叠加分支 |
| `internal/logic/public/order/preCreateOrderLogic.go` | 追加:预算时考虑促销价 |
| `queue/logic/order/activateOrderLogic.go` | 追加:激活后写 `promo_usage` |
| `internal/model/order/order.go` | 追加:`PromoRuleID``PromoDiscount` 字段 |
| `internal/model/order/model.go` | 追加:`Details` 同步字段 |
| `internal/types/types.go` | 追加:新增结构体、响应字段 |
| `internal/svc/serviceContext.go` | 追加:注入新 Model |
| 路由配置 | 追加:管理后台路由 |
---
## 12. 运营配置示例
### 场景 1:新客 7 天优惠
```
promo_rule:
name = "新客7天优惠"
type = "new_user"
params = {"window_hours": 168}
priority = 10
enabled = true
start_time = NULL(永久生效)
end_time = NULL
subscribe_promo:
规格"7天" → promo_price = 279
规格"30天" → promo_price = 599
规格"90天" → promo_price = 1299
规格"365天" → promo_price = 4499
```
### 场景 2:回归用户优惠
```
promo_rule:
name = "回归用户专属价"
type = "inactive_user"
params = {"inactive_months": 3}
priority = 5
enabled = true
subscribe_promo:
规格"30天" → promo_price = 499
规格"90天" → promo_price = 999
```
### 场景 3:双十一全站活动
```
promo_rule:
name = "双十一特惠"
type = "campaign"
params = {}
priority = 20(优先级高于新客和回归)
enabled = true
start_time = "2026-11-01 00:00:00"
end_time = "2026-11-12 00:00:00"
subscribe_promo:
规格"90天" → promo_price = 999
规格"365天" → promo_price = 3999
```
**优先级效果**:双十一期间(priority=20),即使用户是新客(priority=10),也走双十一价格。双十一结束后,新客仍可享受新客优惠。
---
## 13. 迁移脚本
### 02153_promo_system.up.sql
```sql
-- 促销规则表
CREATE TABLE IF NOT EXISTS `promo_rule` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL DEFAULT '',
`type` VARCHAR(32) NOT NULL DEFAULT '',
`params` JSON NOT NULL,
`priority` INT NOT NULL DEFAULT 0,
`enabled` TINYINT(1) NOT NULL DEFAULT 1,
`start_time` DATETIME DEFAULT NULL,
`end_time` DATETIME DEFAULT NULL,
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`deleted_at` DATETIME DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_enabled_priority` (`enabled`, `priority` DESC)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表';
-- 规格促销价表
CREATE TABLE IF NOT EXISTS `subscribe_promo` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`subscribe_id` BIGINT UNSIGNED NOT NULL,
`promo_rule_id` BIGINT UNSIGNED NOT NULL,
`promo_price` BIGINT NOT NULL DEFAULT 0,
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_subscribe_rule` (`subscribe_id`, `promo_rule_id`),
KEY `idx_promo_rule_id` (`promo_rule_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格促销价表';
-- 促销使用记录表
CREATE TABLE IF NOT EXISTS `promo_usage` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` BIGINT UNSIGNED NOT NULL,
`promo_rule_id` BIGINT UNSIGNED NOT NULL,
`subscribe_id` BIGINT UNSIGNED NOT NULL,
`order_no` VARCHAR(255) NOT NULL DEFAULT '',
`promo_price` BIGINT NOT NULL DEFAULT 0,
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_user_rule` (`user_id`, `promo_rule_id`),
KEY `idx_order_no` (`order_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销使用记录表';
-- order 表新增促销字段
ALTER TABLE `order`
ADD COLUMN `promo_rule_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '促销规则ID, 0=未使用促销',
ADD COLUMN `promo_discount` BIGINT NOT NULL DEFAULT 0 COMMENT '促销优惠金额(分)';
```
### 02153_promo_system.down.sql
```sql
ALTER TABLE `order`
DROP COLUMN IF EXISTS `promo_discount`,
DROP COLUMN IF EXISTS `promo_rule_id`;
DROP TABLE IF EXISTS `promo_usage`;
DROP TABLE IF EXISTS `subscribe_promo`;
DROP TABLE IF EXISTS `promo_rule`;
```
---
## 14. 风险与注意事项
| 风险 | 应对 |
|------|------|
| 促销价 > 原价(配置错误) | 管理后台校验:`promo_price` 必须 < `unit_price` |
| 规则删除后已有订单受影响 | 软删除(`deleted_at`),订单上已存储 `promo_rule_id``promo_discount`,不依赖规则表 |
| 缓存与数据库不一致 | 管理后台修改时主动清缓存,判定逻辑以 DB 为准 |
| 新促销和老 NewUserOnly 折扣共存 | **互斥**:促销命中时跳过 `getDiscount()` 的百分比折扣 |
| 活动到期后 5 分钟内仍可下单 | 缓存 TTL=300s 的延迟,可接受;下单时可选择实时查 DB 校验 |
| 退款后重新购买仍享促销 | 正常行为 — `promo_usage` 只做记录不做去重 |
+6
View File
@@ -128,6 +128,10 @@ curl -X PUT 'https://bucket.s3.ap-east-1.amazonaws.com/...' \
说明: 说明:
- `Content-Type` 需和 `init` 返回的 `headers.Content-Type` 一致 - `Content-Type` 需和 `init` 返回的 `headers.Content-Type` 一致
- 允许的 `Content-Type` 由服务端 `S3.AllowedContentTypes` 配置控制,默认包含:
- 压缩包:`application/zip``application/x-zip-compressed``application/gzip``application/x-gzip`
- 通用文件:`application/octet-stream``text/plain``application/json`
- 图片:`image/jpeg``image/jpg``image/png``image/webp``image/gif``image/heic``image/heif``image/bmp`
- `upload_url` 有过期时间,通常 300 秒 - `upload_url` 有过期时间,通常 300 秒
- 成功时 S3 常见返回 `200``204` - 成功时 S3 常见返回 `200``204`
@@ -164,11 +168,13 @@ curl -X POST 'https://tapi.hifast.biz/v1/public/file/upload/complete' \
- 如果请求带了 `X-App-Id`,就按现有逻辑验签 - 如果请求带了 `X-App-Id`,就按现有逻辑验签
- 如果没有 `X-App-Id`,仍按旧逻辑放行 - 如果没有 `X-App-Id`,仍按旧逻辑放行
- 如果要给该接口加签,签名时必须对原始 multipart body 计算 `BODY_SHA256` - 如果要给该接口加签,签名时必须对原始 multipart body 计算 `BODY_SHA256`
- 允许的 `Content-Type` 与预签名三段式一致;multipart 文件字段未显式携带 `Content-Type` 时,服务端会基于文件内容嗅探常见类型。
## 常见错误码 ## 常见错误码
- `200`: 成功 - `200`: 成功
- `400`: 参数错误 - `400`: 参数错误
- `400 content_type is not allowed`: 文件 `Content-Type` 不在 `S3.AllowedContentTypes` 白名单内
- `40008`: 缺少签名头 - `40008`: 缺少签名头
- `40009`: 签名已过期 - `40009`: 签名已过期
- `40010`: 签名无效 - `40010`: 签名无效
+153
View File
@@ -0,0 +1,153 @@
# 用户端提现列表 API — 订阅字段现状调研
> 调研日期:2026-05-27
> 调研范围:用户端「提现记录列表」接口当前返回字段,重点关注是否包含订阅相关信息
## 一、接口信息
| 项目 | 值 |
|------|-----|
| 方法 | `GET` |
| 路径 | `/v1/public/user/withdrawal_log` |
| 认证 | JWT Token`AuthMiddleware` + `DeviceMiddleware` |
| 分组 | `apis/public/user.api` |
## 二、文件定位
| 层 | 路径 |
|----|------|
| API DSL | `apis/public/user.api:118` (`WithdrawalLog`) / `apis/public/user.api:368` (路由) |
| Handler | `internal/handler/public/user/queryWithdrawalLogHandler.go` |
| Logic | `internal/logic/public/user/queryWithdrawalLogLogic.go:30` |
| 类型生成 | `internal/types/types.go``WithdrawalLog``QueryWithdrawalLogListRequest``QueryWithdrawalLogListResponse` |
| 数据模型 | `internal/model/user/user.go:167` (`Withdrawal`,表名 `withdrawals` |
## 三、请求参数
```go
QueryWithdrawalLogListRequest {
Page int `form:"page"`
Size int `form:"size"`
}
```
- 默认值:`page=1``size=10`(在 logic 内兜底)
## 四、响应结构
### 4.1 顶层响应
```go
QueryWithdrawalLogListResponse {
List []WithdrawalLog `json:"list"`
Total int64 `json:"total"`
}
```
### 4.2 列表项 `WithdrawalLog`
```go
WithdrawalLog {
Id int64 `json:"id"`
UserId int64 `json:"user_id"`
Amount int64 `json:"amount"` // 单位:分
Content string `json:"content"` // 收款附加信息
Status uint8 `json:"status"` // 0:Pending 1:Approved 2:Rejected 3:Cancelled
Reason string `json:"reason,omitempty"` // 拒绝原因
Method uint8 `json:"method"` // 0:其他 1:支付宝 2:微信 3:USDT
Account string `json:"account"` // 收款账号
QrCodeUrl string `json:"qr_code_url"` // 收款码图片 URL
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
```
## 五、底层数据模型 `Withdrawal`
```go
type Withdrawal struct {
Id int64
UserId int64 // index:idx_user_id
Amount int64
Content string // type:text
Status uint8 // 0:Pending 1:Approved 2:Rejected 3:Cancelled
Reason string // varchar(500)
Method uint8 // 0:其他 1:支付宝 2:微信 3:USDT
Account string // varchar(255)
QrCodeUrl string // varchar(500)
CreatedAt time.Time
UpdatedAt time.Time
}
```
> 表名:`withdrawals`,与用户关联仅靠 `user_id` 外键,**无任何订阅 ID / 订阅快照字段**。
## 六、订阅字段现状(核心结论)
### 6.1 当前结论
| 维度 | 是否包含订阅信息 |
|------|------------------|
| API 响应(`WithdrawalLog` | ❌ 无 |
| 数据库表(`withdrawals` | ❌ 无 |
| Logic 查询逻辑 | ❌ 无 JOIN、无附加查询 `user_subscribe` |
提现记录与订阅之间**完全没有关联**。原因:佣金来源于多次订单累计,提现是从「佣金余额(`user.commission`)」整体扣减,不绑定到任何具体订阅。
### 6.2 Logic 当前实现要点
```go
// internal/logic/public/user/queryWithdrawalLogLogic.go:46-72
query := l.svcCtx.DB.WithContext(l.ctx).
Model(&user.Withdrawal{}).
Where("user_id = ?", u.Id)
// 仅按 user_id 过滤 + 分页 + 倒序,无任何 Preload / Join
```
## 七、已发现的隐患(与本次需求关联)
### 7.1 时间戳违反项目约定 ⚠️
`queryWithdrawalLogLogic.go:70-71`
```go
CreatedAt: row.CreatedAt.UnixMilli(),
UpdatedAt: row.UpdatedAt.UnixMilli(),
```
- 项目约定:**后端统一返回秒级 Unix 时间戳**(前端 `formatDate` 已按 `数字 × 1000` 处理)
- 当前实现返回毫秒级,前端会解析为约公元 +55000 年的日期,**展示必然异常**
- 修复方式:改为 `.Unix()`
> 该问题独立于「订阅字段」需求,但属于同一接口,建议同批修复。
## 八、可选扩展方向(待业务确认)
若产品希望在提现列表中展示订阅相关信息,可选方案如下:
| 方案 | 字段示意 | 实现成本 | 适用场景 |
|------|----------|----------|----------|
| A. 当前生效订阅摘要 | `current_subscribe: { id, name, expire_at }` | 中(每行额外查 `user_subscribe`) | 想让用户看到「我提的是哪个订阅产生的佣金对应的余额」 |
| B. 用户全部订阅列表 | `subscribes: [{ id, name, expire_at }]` | 高(N+1 风险) | 极少场景,需评估必要性 |
| C. 仅订阅 ID 数组 | `subscribe_ids: [int64]` | 低 | 仅前端跳详情用 |
| D. 不加,保持现状 | — | 0 | 若业务上提现与订阅本就无关 |
> **推荐先与产品确认动机**:提现是佣金余额提现,与订阅本身没有直接业务关系,加字段前需明确「让用户看到订阅信息要解决什么问题」。
## 九、相关接口(一并列出,便于对照)
| 接口 | 方法 | 路径 | 说明 |
|------|------|------|------|
| 提交提现 | POST | `/v1/public/user/commission_withdraw` | 入参 `CommissionWithdrawRequest`,返回 `WithdrawalLog` |
| 取消提现 | POST | `/v1/public/user/withdrawal_cancel` | 入参 `CancelWithdrawalRequest`,返回 `WithdrawalLog` |
| 提现记录列表 | GET | `/v1/public/user/withdrawal_log` | 本文主角 |
> 三个接口共用 `WithdrawalLog` 类型,**任何字段变更需统一同步**,否则前端类型会错位。
## 十、后续动作建议
1. **产品确认**:是否真的需要在提现列表里返回订阅字段?目的是什么?
2. **若需新增**:在 `apis/public/user.api` 修改 `WithdrawalLog`,运行 goctl 重新生成,再补 Logic 查询。
3. **顺手修复**:将 `UnixMilli()` 改为 `Unix()`(独立小 PR 即可)。
4. **如新增订阅字段**:注意三个接口(list / cancel / withdraw)的返回结构同步,避免前端类型联动断裂。
+1 -1
View File
@@ -74,7 +74,7 @@ S3:
UsePathStyle: false UsePathStyle: false
PresignExpireSeconds: 300 PresignExpireSeconds: 300
MaxUploadSize: 104857600 MaxUploadSize: 104857600
AllowedContentTypes: "application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json" AllowedContentTypes: "application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json,image/jpeg,image/jpg,image/png,image/webp,image/gif,image/heic,image/heif,image/bmp"
device: device:
enable: true # 开启设备加密通信 enable: true # 开启设备加密通信
+1
View File
@@ -53,6 +53,7 @@ require (
) )
require ( require (
github.com/DATA-DOG/go-sqlmock v1.5.2
github.com/Masterminds/sprig/v3 v3.3.0 github.com/Masterminds/sprig/v3 v3.3.0
github.com/aws/aws-sdk-go-v2 v1.41.7 github.com/aws/aws-sdk-go-v2 v1.41.7
github.com/aws/aws-sdk-go-v2/config v1.32.17 github.com/aws/aws-sdk-go-v2/config v1.32.17
+3
View File
@@ -8,6 +8,8 @@ filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
github.com/GUAIK-ORG/go-snowflake v0.0.0-20200116064823-220c4260e85f h1:RDkg3pyE1qGbBpRWmvSN9RNZC5nUrOaEPiEpEb8y2f0= github.com/GUAIK-ORG/go-snowflake v0.0.0-20200116064823-220c4260e85f h1:RDkg3pyE1qGbBpRWmvSN9RNZC5nUrOaEPiEpEb8y2f0=
github.com/GUAIK-ORG/go-snowflake v0.0.0-20200116064823-220c4260e85f/go.mod h1:zA7AF9RTfpluCfz0omI4t5KCMaWHUMicsZoMccnaT44= github.com/GUAIK-ORG/go-snowflake v0.0.0-20200116064823-220c4260e85f/go.mod h1:zA7AF9RTfpluCfz0omI4t5KCMaWHUMicsZoMccnaT44=
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
@@ -264,6 +266,7 @@ github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
github.com/klauspost/compress v1.17.7 h1:ehO88t2UGzQK66LMdE8tibEd1ErmzZjNEqWkjLAKQQg= github.com/klauspost/compress v1.17.7 h1:ehO88t2UGzQK66LMdE8tibEd1ErmzZjNEqWkjLAKQQg=
github.com/klauspost/compress v1.17.7/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= github.com/klauspost/compress v1.17.7/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
@@ -1,5 +1,35 @@
-- Purpose: Rollback user-level speed limit overrides from user_subscribe SET @traffic_limit_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'user_subscribe'
AND COLUMN_NAME = 'traffic_limit'
);
ALTER TABLE `user_subscribe` SET @traffic_limit_sql = IF(
DROP COLUMN IF EXISTS `traffic_limit`, @traffic_limit_exists = 1,
DROP COLUMN IF EXISTS `speed_limit`; 'ALTER TABLE `user_subscribe` DROP COLUMN `traffic_limit`',
'SELECT 1'
);
PREPARE traffic_limit_stmt FROM @traffic_limit_sql;
EXECUTE traffic_limit_stmt;
DEALLOCATE PREPARE traffic_limit_stmt;
SET @speed_limit_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'user_subscribe'
AND COLUMN_NAME = 'speed_limit'
);
SET @speed_limit_sql = IF(
@speed_limit_exists = 1,
'ALTER TABLE `user_subscribe` DROP COLUMN `speed_limit`',
'SELECT 1'
);
PREPARE speed_limit_stmt FROM @speed_limit_sql;
EXECUTE speed_limit_stmt;
DEALLOCATE PREPARE speed_limit_stmt;
@@ -1,6 +1,4 @@
-- Purpose: Add user-level speed limit overrides to user_subscribe SET @speed_limit_exists = (
SET @column_exists = (
SELECT COUNT(*) SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() WHERE TABLE_SCHEMA = DATABASE()
@@ -8,17 +6,17 @@ SET @column_exists = (
AND COLUMN_NAME = 'speed_limit' AND COLUMN_NAME = 'speed_limit'
); );
SET @sql = IF( SET @speed_limit_sql = IF(
@column_exists = 0, @speed_limit_exists = 0,
'ALTER TABLE `user_subscribe` ADD COLUMN `speed_limit` int NOT NULL DEFAULT 0 COMMENT ''User-level speed limit override (Mbps, 0=use plan default)'' AFTER `upload`', 'ALTER TABLE `user_subscribe` ADD COLUMN `speed_limit` BIGINT NOT NULL DEFAULT 0 COMMENT ''User-level speed limit override (Mbps), 0 uses plan-level'' AFTER `upload`',
'SELECT ''Column speed_limit already exists in user_subscribe table''' 'SELECT 1'
); );
PREPARE stmt FROM @sql; PREPARE speed_limit_stmt FROM @speed_limit_sql;
EXECUTE stmt; EXECUTE speed_limit_stmt;
DEALLOCATE PREPARE stmt; DEALLOCATE PREPARE speed_limit_stmt;
SET @column_exists = ( SET @traffic_limit_exists = (
SELECT COUNT(*) SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() WHERE TABLE_SCHEMA = DATABASE()
@@ -26,12 +24,12 @@ SET @column_exists = (
AND COLUMN_NAME = 'traffic_limit' AND COLUMN_NAME = 'traffic_limit'
); );
SET @sql = IF( SET @traffic_limit_sql = IF(
@column_exists = 0, @traffic_limit_exists = 0,
'ALTER TABLE `user_subscribe` ADD COLUMN `traffic_limit` text DEFAULT NULL COMMENT ''User-level traffic limit rules override (JSON, NULL=use plan default)'' AFTER `speed_limit`', 'ALTER TABLE `user_subscribe` ADD COLUMN `traffic_limit` TEXT DEFAULT NULL COMMENT ''User-level traffic limit override (JSON), NULL uses plan-level'' AFTER `speed_limit`',
'SELECT ''Column traffic_limit already exists in user_subscribe table''' 'SELECT 1'
); );
PREPARE stmt FROM @sql; PREPARE traffic_limit_stmt FROM @traffic_limit_sql;
EXECUTE stmt; EXECUTE traffic_limit_stmt;
DEALLOCATE PREPARE stmt; DEALLOCATE PREPARE traffic_limit_stmt;
@@ -14,19 +14,155 @@ CREATE TABLE IF NOT EXISTS `promo_rule` (
KEY `idx_enabled_priority_deleted` (`enabled`, `deleted_at`, `priority` DESC) KEY `idx_enabled_priority_deleted` (`enabled`, `deleted_at`, `priority` DESC)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表'; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表';
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'promo_rule'
AND INDEX_NAME = 'idx_enabled_priority'
);
SET @sql = IF(
@index_exists = 1,
'ALTER TABLE `promo_rule` DROP INDEX `idx_enabled_priority`',
'SELECT ''Index idx_enabled_priority does not exist on promo_rule table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'promo_rule'
AND INDEX_NAME = 'idx_deleted_at'
);
SET @sql = IF(
@index_exists = 1,
'ALTER TABLE `promo_rule` DROP INDEX `idx_deleted_at`',
'SELECT ''Index idx_deleted_at does not exist on promo_rule table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'promo_rule'
AND INDEX_NAME = 'idx_enabled_priority_deleted'
);
SET @sql = IF(
@index_exists = 0,
'ALTER TABLE `promo_rule` ADD KEY `idx_enabled_priority_deleted` (`enabled`, `deleted_at`, `priority` DESC)',
'SELECT ''Index idx_enabled_priority_deleted already exists on promo_rule table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
CREATE TABLE IF NOT EXISTS `subscribe_promo` ( CREATE TABLE IF NOT EXISTS `subscribe_promo` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '套餐规格 ID', `subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '套餐规格 ID',
`quantity` INT NOT NULL DEFAULT 0 COMMENT '购买数量', `quantity` BIGINT NOT NULL DEFAULT 1 COMMENT '购买数量',
`promo_rule_id` BIGINT UNSIGNED NOT NULL COMMENT '促销规则 ID', `promo_rule_id` BIGINT UNSIGNED NOT NULL COMMENT '促销规则 ID',
`promo_price` BIGINT NOT NULL DEFAULT 0 COMMENT '该规格在此规则下的优惠价(分)', `promo_price` BIGINT NOT NULL DEFAULT 0 COMMENT '该规格在此规则下的优惠价(分)',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
UNIQUE KEY `uk_subscribe_qty_rule` (`subscribe_id`, `quantity`, `promo_rule_id`), UNIQUE KEY `uk_subscribe_quantity_rule` (`subscribe_id`, `quantity`, `promo_rule_id`),
KEY `idx_promo_rule_id` (`promo_rule_id`) KEY `idx_promo_rule_id` (`promo_rule_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格促销价表'; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格促销价表';
SET @column_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND COLUMN_NAME = 'quantity'
);
SET @sql = IF(
@column_exists = 0,
'ALTER TABLE `subscribe_promo` ADD COLUMN `quantity` BIGINT NOT NULL DEFAULT 1 COMMENT ''购买数量'' AFTER `subscribe_id`',
'SELECT ''Column quantity already exists in subscribe_promo table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @sql = IF(
@column_exists = 1,
'ALTER TABLE `subscribe_promo` MODIFY COLUMN `quantity` BIGINT NOT NULL DEFAULT 1 COMMENT ''购买数量''',
'SELECT ''Column quantity does not exist in subscribe_promo table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND INDEX_NAME = 'uk_subscribe_rule'
);
SET @sql = IF(
@index_exists = 1,
'ALTER TABLE `subscribe_promo` DROP INDEX `uk_subscribe_rule`',
'SELECT ''Index uk_subscribe_rule does not exist on subscribe_promo table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND INDEX_NAME = 'uk_subscribe_qty_rule'
);
SET @sql = IF(
@index_exists = 1,
'ALTER TABLE `subscribe_promo` DROP INDEX `uk_subscribe_qty_rule`',
'SELECT ''Index uk_subscribe_qty_rule does not exist on subscribe_promo table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @index_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND INDEX_NAME = 'uk_subscribe_quantity_rule'
);
SET @sql = IF(
@index_exists = 0,
'ALTER TABLE `subscribe_promo` ADD UNIQUE KEY `uk_subscribe_quantity_rule` (`subscribe_id`, `quantity`, `promo_rule_id`)',
'SELECT ''Index uk_subscribe_quantity_rule already exists on subscribe_promo table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
CREATE TABLE IF NOT EXISTS `promo_usage` ( CREATE TABLE IF NOT EXISTS `promo_usage` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户 ID', `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户 ID',
@@ -0,0 +1,6 @@
-- 02155 down
--
-- 本迁移只是把 02154 的偏差修正回它应有的目标定义,没有引入新的列/表。
-- 回滚 02155 并不应该把列重新改坏成 varchar/INT NULL 的旧偏差,因此 down
-- 为空操作。若需彻底删除 promo 系统,请回滚到 02154 的 down。
SELECT '02155 has no destructive forward step; down is a no-op.';
@@ -0,0 +1,241 @@
-- 02155 Promo Schema Fix
--
-- 修复历史环境中 02154 未正确执行(或部分 GORM AutoMigrate 推断)导致的
-- promo 系统列类型 / 索引偏差。完全幂等:可重复执行。
--
-- 覆盖偏差:
-- 1) subscribe_promo.quantity 实际 int/NULL -> BIGINT NOT NULL DEFAULT 1
-- 2) subscribe_promo 唯一索引 实际 (subscribe_id, promo_rule_id) -> (subscribe_id, quantity, promo_rule_id)
-- 3) order.promo_rule_id 实际 int/NULL -> BIGINT UNSIGNED NOT NULL DEFAULT 0
-- 4) order.promo_discount 实际 varchar(255)/NULL -> BIGINT NOT NULL DEFAULT 0
--
-- 设计原则:
-- - 所有 ALTER 前先做 NULL/空串兜底,避免 NOT NULL 转换失败。
-- - 类型已经正确的环境(02154 正常跑过)不会被改动,所有 IF 判断都基于
-- INFORMATION_SCHEMA 当前真实状态。
-- - 索引差异处理 4 个分支:仅当索引确实是错的旧形态时才替换,已经是新形态则不动。
-- ============================================================================
-- 1) subscribe_promo.quantity
-- ============================================================================
-- 1.1 列不存在则补建(极端历史环境兜底)
SET @col_exists = (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND COLUMN_NAME = 'quantity'
);
SET @sql = IF(
@col_exists = 0,
'ALTER TABLE `subscribe_promo` ADD COLUMN `quantity` BIGINT NOT NULL DEFAULT 1 COMMENT ''购买数量'' AFTER `subscribe_id`',
'SELECT ''subscribe_promo.quantity exists, skip ADD'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- 1.2 NULL 兜底为 1(旧 AutoMigrate 推断列允许 NULL,必须先回填再 NOT NULL
UPDATE `subscribe_promo` SET `quantity` = 1 WHERE `quantity` IS NULL;
-- 1.3 类型 / 可空 / 默认值修正:只在与目标定义不一致时改
SET @col_def_wrong = (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND COLUMN_NAME = 'quantity'
AND (
LOWER(DATA_TYPE) <> 'bigint'
OR IS_NULLABLE = 'YES'
OR COLUMN_DEFAULT IS NULL
OR COLUMN_DEFAULT <> '1'
)
);
SET @sql = IF(
@col_def_wrong = 1,
'ALTER TABLE `subscribe_promo` MODIFY COLUMN `quantity` BIGINT NOT NULL DEFAULT 1 COMMENT ''购买数量''',
'SELECT ''subscribe_promo.quantity already matches target definition'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ============================================================================
-- 2) subscribe_promo 唯一索引:旧形态 -> (subscribe_id, quantity, promo_rule_id)
-- ============================================================================
-- 2.1 删除已知的所有旧形态唯一索引(如果存在)
SET @idx_exists = (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND INDEX_NAME = 'idx_subscribe_rule'
);
SET @sql = IF(
@idx_exists = 1,
'ALTER TABLE `subscribe_promo` DROP INDEX `idx_subscribe_rule`',
'SELECT ''subscribe_promo.idx_subscribe_rule absent'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @idx_exists = (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND INDEX_NAME = 'uk_subscribe_rule'
);
SET @sql = IF(
@idx_exists = 1,
'ALTER TABLE `subscribe_promo` DROP INDEX `uk_subscribe_rule`',
'SELECT ''subscribe_promo.uk_subscribe_rule absent'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @idx_exists = (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND INDEX_NAME = 'uk_subscribe_qty_rule'
);
SET @sql = IF(
@idx_exists = 1,
'ALTER TABLE `subscribe_promo` DROP INDEX `uk_subscribe_qty_rule`',
'SELECT ''subscribe_promo.uk_subscribe_qty_rule absent'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- 2.2 新建目标唯一索引(缺失时才建)
SET @idx_exists = (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'subscribe_promo'
AND INDEX_NAME = 'uk_subscribe_quantity_rule'
);
SET @sql = IF(
@idx_exists = 0,
'ALTER TABLE `subscribe_promo` ADD UNIQUE KEY `uk_subscribe_quantity_rule` (`subscribe_id`, `quantity`, `promo_rule_id`)',
'SELECT ''subscribe_promo.uk_subscribe_quantity_rule exists'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ============================================================================
-- 3) order.promo_rule_id -> BIGINT UNSIGNED NOT NULL DEFAULT 0
-- ============================================================================
SET @col_exists = (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'order'
AND COLUMN_NAME = 'promo_rule_id'
);
SET @sql = IF(
@col_exists = 0,
'ALTER TABLE `order` ADD COLUMN `promo_rule_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT ''促销规则ID, 0=未使用促销'' AFTER `discount`',
'SELECT ''order.promo_rule_id exists, skip ADD'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
UPDATE `order` SET `promo_rule_id` = 0 WHERE `promo_rule_id` IS NULL;
SET @col_def_wrong = (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'order'
AND COLUMN_NAME = 'promo_rule_id'
AND (
LOWER(DATA_TYPE) <> 'bigint'
OR INSTR(LOWER(COLUMN_TYPE), 'unsigned') = 0
OR IS_NULLABLE = 'YES'
OR COLUMN_DEFAULT IS NULL
OR COLUMN_DEFAULT <> '0'
)
);
SET @sql = IF(
@col_def_wrong = 1,
'ALTER TABLE `order` MODIFY COLUMN `promo_rule_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT ''促销规则ID, 0=未使用促销''',
'SELECT ''order.promo_rule_id already matches target definition'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ============================================================================
-- 4) order.promo_discount -> BIGINT NOT NULL DEFAULT 0
-- 历史 AutoMigrate 推断为 varchar(255)/NULL,金额字段错存为字符串。
-- 必须先把空串/NULL 兜底为 '0',再 MODIFY,否则 MySQL 转 BIGINT 会写 0
-- (这里我们仍兜底显式化,避免触发 strict mode 报错)。
-- ============================================================================
SET @col_exists = (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'order'
AND COLUMN_NAME = 'promo_discount'
);
SET @sql = IF(
@col_exists = 0,
'ALTER TABLE `order` ADD COLUMN `promo_discount` BIGINT NOT NULL DEFAULT 0 COMMENT ''促销优惠金额(分)'' AFTER `promo_rule_id`',
'SELECT ''order.promo_discount exists, skip ADD'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- 当且仅当当前是字符串型时做兜底(避免对已经是 BIGINT 的环境跑无谓 UPDATE
SET @col_is_string = (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'order'
AND COLUMN_NAME = 'promo_discount'
AND LOWER(DATA_TYPE) IN ('varchar', 'char', 'text')
);
SET @sql = IF(
@col_is_string = 1,
'UPDATE `order` SET `promo_discount` = ''0'' WHERE `promo_discount` IS NULL OR `promo_discount` = ''''',
'SELECT ''order.promo_discount not string type, skip backfill'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @col_def_wrong = (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'order'
AND COLUMN_NAME = 'promo_discount'
AND (
LOWER(DATA_TYPE) <> 'bigint'
OR IS_NULLABLE = 'YES'
OR COLUMN_DEFAULT IS NULL
OR COLUMN_DEFAULT <> '0'
)
);
SET @sql = IF(
@col_def_wrong = 1,
'ALTER TABLE `order` MODIFY COLUMN `promo_discount` BIGINT NOT NULL DEFAULT 0 COMMENT ''促销优惠金额(分)''',
'SELECT ''order.promo_discount already matches target definition'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
+1 -1
View File
@@ -58,7 +58,7 @@ type S3Config struct {
UsePathStyle bool `yaml:"UsePathStyle" default:"false"` UsePathStyle bool `yaml:"UsePathStyle" default:"false"`
PresignExpireSeconds int64 `yaml:"PresignExpireSeconds" default:"300"` PresignExpireSeconds int64 `yaml:"PresignExpireSeconds" default:"300"`
MaxUploadSize int64 `yaml:"MaxUploadSize" default:"104857600"` MaxUploadSize int64 `yaml:"MaxUploadSize" default:"104857600"`
AllowedContentTypes string `yaml:"AllowedContentTypes" default:"application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json"` AllowedContentTypes string `yaml:"AllowedContentTypes" default:"application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json,image/jpeg,image/jpg,image/png,image/webp,image/gif,image/heic,image/heif,image/bmp"`
} }
type RedisConfig struct { type RedisConfig struct {
@@ -0,0 +1,25 @@
package invite
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/invite"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
// Get invite manage list
func GetInviteManageListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.GetInviteManageListRequest
_ = c.ShouldBind(&req)
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := invite.NewGetInviteManageListLogic(c.Request.Context(), svcCtx)
resp, err := l.GetInviteManageList(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,23 @@
package promo
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/promo"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
func CreateRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.CreatePromoRuleRequest
_ = c.ShouldBind(&req)
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := promo.NewCreateRuleLogic(c.Request.Context(), svcCtx)
resp, err := l.CreateRule(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,26 @@
package promo
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/promo"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
func DeletePriceHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.DeletePromoPriceRequest
if err := c.ShouldBindUri(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := promo.NewDeletePriceLogic(c.Request.Context(), svcCtx)
err := l.DeletePrice(&req)
result.HttpResult(c, nil, err)
}
}
@@ -0,0 +1,26 @@
package promo
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/promo"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
func DeleteRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.DeletePromoRuleRequest
if err := c.ShouldBindUri(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := promo.NewDeleteRuleLogic(c.Request.Context(), svcCtx)
err := l.DeleteRule(&req)
result.HttpResult(c, nil, err)
}
}
@@ -0,0 +1,23 @@
package promo
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/promo"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
func GetPriceListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.GetPromoPriceListRequest
_ = c.ShouldBind(&req)
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := promo.NewGetPriceListLogic(c.Request.Context(), svcCtx)
resp, err := l.GetPriceList(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,26 @@
package promo
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/promo"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
func GetRuleDetailHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.GetPromoRuleDetailRequest
if err := c.ShouldBindUri(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := promo.NewGetRuleDetailLogic(c.Request.Context(), svcCtx)
resp, err := l.GetRuleDetail(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,23 @@
package promo
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/promo"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
func GetRuleListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.GetPromoRuleListRequest
_ = c.ShouldBind(&req)
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := promo.NewGetRuleListLogic(c.Request.Context(), svcCtx)
resp, err := l.GetRuleList(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,23 @@
package promo
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/promo"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
func GetUsageListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.GetPromoUsageListRequest
_ = c.ShouldBind(&req)
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := promo.NewGetUsageListLogic(c.Request.Context(), svcCtx)
resp, err := l.GetUsageList(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,23 @@
package promo
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/promo"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
func SetPriceHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.SetPromoPriceRequest
_ = c.ShouldBind(&req)
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := promo.NewSetPriceLogic(c.Request.Context(), svcCtx)
err := l.SetPrice(&req)
result.HttpResult(c, nil, err)
}
}
@@ -0,0 +1,27 @@
package promo
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/promo"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
func UpdateRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.UpdatePromoRuleRequest
if err := c.ShouldBindUri(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
_ = c.ShouldBind(&req)
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := promo.NewUpdateRuleLogic(c.Request.Context(), svcCtx)
resp, err := l.UpdateRule(&req)
result.HttpResult(c, resp, err)
}
}
@@ -1,6 +1,9 @@
package user package user
import ( import (
"encoding/json"
"errors"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/user" "github.com/perfect-panel/server/internal/logic/admin/user"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
@@ -18,9 +21,25 @@ func UpdateUserSubscribeHandler(svcCtx *svc.ServiceContext) func(c *gin.Context)
result.ParamErrorResult(c, validateErr) result.ParamErrorResult(c, validateErr)
return return
} }
if err := validateUpdateUserSubscribeTrafficLimit(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := user.NewUpdateUserSubscribeLogic(c.Request.Context(), svcCtx) l := user.NewUpdateUserSubscribeLogic(c.Request.Context(), svcCtx)
err := l.UpdateUserSubscribe(&req) err := l.UpdateUserSubscribe(&req)
result.HttpResult(c, nil, err) result.HttpResult(c, nil, err)
} }
} }
func validateUpdateUserSubscribeTrafficLimit(req *types.UpdateUserSubscribeRequest) error {
if req.TrafficLimit == nil || *req.TrafficLimit == "" {
return nil
}
var rules []types.TrafficLimit
if err := json.Unmarshal([]byte(*req.TrafficLimit), &rules); err != nil {
return errors.New("traffic_limit must be a valid JSON array")
}
return nil
}
@@ -0,0 +1,59 @@
package user
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/xerr"
)
func TestUpdateUserSubscribeHandlerRejectsInvalidLimits(t *testing.T) {
gin.SetMode(gin.TestMode)
tests := []struct {
name string
body string
}{
{
name: "negative speed limit",
body: `{"user_subscribe_id":1,"subscribe_id":1,"traffic":0,"expired_at":4102444800000,"upload":0,"download":0,"speed_limit":-1}`,
},
{
name: "invalid traffic limit json",
body: `{"user_subscribe_id":1,"subscribe_id":1,"traffic":0,"expired_at":4102444800000,"upload":0,"download":0,"traffic_limit":"not-json"}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
router := gin.New()
router.PUT("/v1/admin/user/subscribe", UpdateUserSubscribeHandler(&svc.ServiceContext{}))
req := httptest.NewRequest(http.MethodPut, "/v1/admin/user/subscribe", bytes.NewBufferString(tt.body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("expected HTTP 200, got %d", rec.Code)
}
var resp struct {
Code uint32 `json:"code"`
Msg string `json:"msg"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal response: %v", err)
}
if resp.Code != xerr.InvalidParams {
t.Fatalf("expected code %d, got %d (%s)", xerr.InvalidParams, resp.Code, resp.Msg)
}
})
}
}
@@ -1,24 +1,24 @@
package common package common
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/common" "github.com/perfect-panel/server/internal/logic/common"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types" "github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result" "github.com/perfect-panel/server/pkg/result"
) )
func ReportLogMessageHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) { func ReportLogMessageHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) { return func(c *gin.Context) {
var req types.ReportLogMessageRequest var req types.ReportLogMessageRequest
_ = c.ShouldBind(&req) _ = c.ShouldBind(&req)
validateErr := svcCtx.Validate(&req) validateErr := svcCtx.Validate(&req)
if validateErr != nil { if validateErr != nil {
result.ParamErrorResult(c, validateErr) result.ParamErrorResult(c, validateErr)
return return
} }
l := common.NewReportLogMessageLogic(c.Request.Context(), svcCtx) l := common.NewReportLogMessageLogic(c.Request.Context(), svcCtx)
resp, err := l.ReportLogMessage(&req, c) resp, err := l.ReportLogMessage(&req, c)
result.HttpResult(c, resp, err) result.HttpResult(c, resp, err)
} }
} }
@@ -0,0 +1,30 @@
package user
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/public/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
// Get invite gift records
func GetInviteRecordsHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.GetInviteRecordsRequest
if err := c.ShouldBind(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
validateErr := svcCtx.Validate(&req)
if validateErr != nil {
result.ParamErrorResult(c, validateErr)
return
}
l := user.NewGetInviteRecordsLogic(c.Request.Context(), svcCtx)
resp, err := l.GetInviteRecords(&req)
result.HttpResult(c, resp, err)
}
}
+45
View File
@@ -13,10 +13,12 @@ import (
adminCoupon "github.com/perfect-panel/server/internal/handler/admin/coupon" adminCoupon "github.com/perfect-panel/server/internal/handler/admin/coupon"
adminDocument "github.com/perfect-panel/server/internal/handler/admin/document" adminDocument "github.com/perfect-panel/server/internal/handler/admin/document"
adminGroup "github.com/perfect-panel/server/internal/handler/admin/group" adminGroup "github.com/perfect-panel/server/internal/handler/admin/group"
adminInvite "github.com/perfect-panel/server/internal/handler/admin/invite"
adminLog "github.com/perfect-panel/server/internal/handler/admin/log" adminLog "github.com/perfect-panel/server/internal/handler/admin/log"
adminMarketing "github.com/perfect-panel/server/internal/handler/admin/marketing" adminMarketing "github.com/perfect-panel/server/internal/handler/admin/marketing"
adminOrder "github.com/perfect-panel/server/internal/handler/admin/order" adminOrder "github.com/perfect-panel/server/internal/handler/admin/order"
adminPayment "github.com/perfect-panel/server/internal/handler/admin/payment" adminPayment "github.com/perfect-panel/server/internal/handler/admin/payment"
adminPromo "github.com/perfect-panel/server/internal/handler/admin/promo"
adminRedemption "github.com/perfect-panel/server/internal/handler/admin/redemption" adminRedemption "github.com/perfect-panel/server/internal/handler/admin/redemption"
adminServer "github.com/perfect-panel/server/internal/handler/admin/server" adminServer "github.com/perfect-panel/server/internal/handler/admin/server"
adminSubscribe "github.com/perfect-panel/server/internal/handler/admin/subscribe" adminSubscribe "github.com/perfect-panel/server/internal/handler/admin/subscribe"
@@ -193,6 +195,14 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
adminDocumentGroupRouter.GET("/list", adminDocument.GetDocumentListHandler(serverCtx)) adminDocumentGroupRouter.GET("/list", adminDocument.GetDocumentListHandler(serverCtx))
} }
adminInviteGroupRouter := router.Group("/v1/admin/invite")
adminInviteGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
{
// Get invite manage list
adminInviteGroupRouter.GET("/list", adminInvite.GetInviteManageListHandler(serverCtx))
}
adminGroupGroupRouter := router.Group("/v1/admin/group") adminGroupGroupRouter := router.Group("/v1/admin/group")
adminGroupGroupRouter.Use(middleware.AuthMiddleware(serverCtx)) adminGroupGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
@@ -374,6 +384,38 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
adminPaymentGroupRouter.GET("/platform", adminPayment.GetPaymentPlatformHandler(serverCtx)) adminPaymentGroupRouter.GET("/platform", adminPayment.GetPaymentPlatformHandler(serverCtx))
} }
adminPromoGroupRouter := router.Group("/v1/admin/promo")
adminPromoGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
{
// Create promo rule
adminPromoGroupRouter.POST("/rule", adminPromo.CreateRuleHandler(serverCtx))
// Get promo rule list
adminPromoGroupRouter.GET("/rule/list", adminPromo.GetRuleListHandler(serverCtx))
// Get promo rule detail
adminPromoGroupRouter.GET("/rule/:id", adminPromo.GetRuleDetailHandler(serverCtx))
// Update promo rule
adminPromoGroupRouter.PUT("/rule/:id", adminPromo.UpdateRuleHandler(serverCtx))
// Delete promo rule
adminPromoGroupRouter.DELETE("/rule/:id", adminPromo.DeleteRuleHandler(serverCtx))
// Set promo prices
adminPromoGroupRouter.POST("/price", adminPromo.SetPriceHandler(serverCtx))
// Get promo price list
adminPromoGroupRouter.GET("/price/list", adminPromo.GetPriceListHandler(serverCtx))
// Delete promo price
adminPromoGroupRouter.DELETE("/price/:id", adminPromo.DeletePriceHandler(serverCtx))
// Get promo usage list
adminPromoGroupRouter.GET("/usage/list", adminPromo.GetUsageListHandler(serverCtx))
}
adminRedemptionGroupRouter := router.Group("/v1/admin/redemption") adminRedemptionGroupRouter := router.Group("/v1/admin/redemption")
adminRedemptionGroupRouter.Use(middleware.AuthMiddleware(serverCtx)) adminRedemptionGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
@@ -1076,6 +1118,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
// Query User Info // Query User Info
publicUserGroupRouter.GET("/info", publicUser.QueryUserInfoHandler(serverCtx)) publicUserGroupRouter.GET("/info", publicUser.QueryUserInfoHandler(serverCtx))
// Get Invite Records
publicUserGroupRouter.GET("/invite_records", publicUser.GetInviteRecordsHandler(serverCtx))
// Get Invite Sales // Get Invite Sales
publicUserGroupRouter.GET("/invite_sales", publicUser.GetInviteSalesHandler(serverCtx)) publicUserGroupRouter.GET("/invite_sales", publicUser.GetInviteSalesHandler(serverCtx))
publicUserGroupRouter.GET("/invite/sales", publicUser.GetInviteSalesHandler(serverCtx)) // alias: backward-compat publicUserGroupRouter.GET("/invite/sales", publicUser.GetInviteSalesHandler(serverCtx)) // alias: backward-compat
+213
View File
@@ -0,0 +1,213 @@
package invite
import (
"context"
"slices"
modellog "github.com/perfect-panel/server/internal/model/log"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
)
type Benefits struct {
OrderCount int64
HasPurchased bool
InviterCommission int64
InviterGiftDays int64
InviteeGiftDays int64
}
type InviteRelation struct {
InviteeId int64
InviterId int64
}
type paidOrderRow struct {
UserId int64 `gorm:"column:user_id"`
SubscriptionUserId int64 `gorm:"column:subscription_user_id"`
OrderNo string `gorm:"column:order_no"`
}
type systemLogRow struct {
ObjectID int64 `gorm:"column:object_id"`
Content string `gorm:"column:content"`
}
func NormalizePage(page, size int) (int, int) {
if page < 1 {
page = 1
}
if size < 1 {
size = 10
}
if size > 100 {
size = 100
}
return page, size
}
func QueryBenefits(ctx context.Context, db *gorm.DB, relations []InviteRelation) (map[int64]Benefits, error) {
result := make(map[int64]Benefits, len(relations))
if len(relations) == 0 {
return result, nil
}
inviteeIds := make([]int64, 0, len(relations))
inviteeToInviter := make(map[int64]int64, len(relations))
for _, relation := range relations {
inviteeIds = append(inviteeIds, relation.InviteeId)
inviteeToInviter[relation.InviteeId] = relation.InviterId
result[relation.InviteeId] = Benefits{}
}
var orderCounts []struct {
UserId int64 `gorm:"column:user_id"`
Cnt int64 `gorm:"column:cnt"`
}
if err := db.WithContext(ctx).
Table("`order`").
Select("user_id, COUNT(*) as cnt").
Where("user_id IN ? AND status IN ?", inviteeIds, []int{2, 5}).
Group("user_id").
Scan(&orderCounts).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count invitee paid orders failed: %v", err)
}
for _, row := range orderCounts {
benefit := result[row.UserId]
benefit.OrderCount = row.Cnt
benefit.HasPurchased = row.Cnt > 0
result[row.UserId] = benefit
}
var paidOrders []paidOrderRow
if err := db.WithContext(ctx).
Table("`order`").
Select("user_id, subscription_user_id, order_no").
Where("user_id IN ? AND status IN ?", inviteeIds, []int{2, 5}).
Scan(&paidOrders).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invitee paid orders failed: %v", err)
}
if len(paidOrders) == 0 {
return result, nil
}
orderNos := make([]string, 0, len(paidOrders))
orderToInvitee := make(map[string]int64, len(paidOrders))
orderToSubscriptionUser := make(map[string]int64, len(paidOrders))
inviterIds := make([]int64, 0, len(relations))
inviteeAndInviterSet := make(map[int64]struct{}, len(relations)*2)
for _, order := range paidOrders {
orderNos = append(orderNos, order.OrderNo)
orderToInvitee[order.OrderNo] = order.UserId
if order.SubscriptionUserId > 0 && order.SubscriptionUserId != order.UserId {
orderToSubscriptionUser[order.OrderNo] = order.SubscriptionUserId
inviteeAndInviterSet[order.SubscriptionUserId] = struct{}{}
}
}
for _, relation := range relations {
inviterIds = append(inviterIds, relation.InviterId)
inviteeAndInviterSet[relation.InviteeId] = struct{}{}
inviteeAndInviterSet[relation.InviterId] = struct{}{}
}
inviteeAndInviterIds := make([]int64, 0, len(inviteeAndInviterSet))
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
}
if err := fillGiftBenefits(ctx, db, result, orderToInvitee, inviteeToInviter, orderToSubscriptionUser, orderNos, inviteeAndInviterIds); err != nil {
return nil, err
}
return result, nil
}
func fillCommissionBenefits(ctx context.Context, db *gorm.DB, benefits map[int64]Benefits, orderToInvitee map[string]int64, inviteeToInviter map[int64]int64, orderNos []string, inviterIds []int64) error {
var rows []systemLogRow
if err := db.WithContext(ctx).
Table("system_logs").
Select("object_id, content").
Where("type = ? AND object_id IN ? AND JSON_UNQUOTE(JSON_EXTRACT(content, '$.order_no')) IN ? AND JSON_EXTRACT(content, '$.type') IN ?", modellog.TypeCommission.Uint8(), inviterIds, orderNos, []int{int(modellog.CommissionTypePurchase), int(modellog.CommissionTypeRenewal)}).
Scan(&rows).Error; err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invite commission logs failed: %v", err)
}
for _, row := range rows {
content := modellog.Commission{}
if err := content.Unmarshal([]byte(row.Content)); err != nil {
continue
}
inviteeId, ok := orderToInvitee[content.OrderNo]
if !ok || inviteeToInviter[inviteeId] != row.ObjectID {
continue
}
benefit := benefits[inviteeId]
benefit.InviterCommission += content.Amount
benefits[inviteeId] = benefit
}
return nil
}
func fillGiftBenefits(ctx context.Context, db *gorm.DB, benefits map[int64]Benefits, orderToInvitee map[string]int64, inviteeToInviter map[int64]int64, orderToSubscriptionUser map[string]int64, orderNos []string, userIds []int64) error {
var rows []systemLogRow
if err := db.WithContext(ctx).
Table("system_logs").
Select("object_id, content").
Where("type = ? AND object_id IN ? AND JSON_UNQUOTE(JSON_EXTRACT(content, '$.order_no')) IN ?", modellog.TypeGift.Uint8(), userIds, orderNos).
Scan(&rows).Error; err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invite gift logs failed: %v", err)
}
for _, row := range rows {
content := modellog.Gift{}
if err := content.Unmarshal([]byte(row.Content)); err != nil {
continue
}
if content.Type != modellog.GiftTypeIncrease {
continue
}
inviteeId, ok := orderToInvitee[content.OrderNo]
if !ok {
continue
}
benefit := benefits[inviteeId]
switch row.ObjectID {
case inviteeToInviter[inviteeId]:
benefit.InviterGiftDays += content.Amount
case inviteeId:
benefit.InviteeGiftDays += content.Amount
case orderToSubscriptionUser[content.OrderNo]:
benefit.InviteeGiftDays += content.Amount
default:
continue
}
benefits[inviteeId] = benefit
}
return nil
}
func QueryIdentifiers(ctx context.Context, db *gorm.DB, userIds []int64) (map[int64]string, error) {
identifiers := make(map[int64]string, len(userIds))
if len(userIds) == 0 {
return identifiers, nil
}
type identifierRow struct {
UserId int64 `gorm:"column:user_id"`
Identifier string `gorm:"column:identifier"`
}
var rows []identifierRow
if err := db.WithContext(ctx).
Table("user_auth_methods uam").
Select("uam.user_id, uam.auth_identifier as identifier").
Joins("JOIN (SELECT user_id, MIN(id) AS id FROM user_auth_methods WHERE user_id IN ? GROUP BY user_id) first_uam ON first_uam.id = uam.id", userIds).
Scan(&rows).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query user identifiers failed: %v", err)
}
for _, row := range rows {
identifiers[row.UserId] = row.Identifier
}
return identifiers, nil
}
@@ -0,0 +1,105 @@
package invite
import (
"context"
"fmt"
"strings"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func TestQueryBenefitsCountsFamilyOwnerGiftAsInviteeGift(t *testing.T) {
db, mock, cleanup := newBenefitsTestDB(t)
defer cleanup()
mock.ExpectQuery("COUNT(*) as cnt").
WithArgs(int64(200), 2, 5).
WillReturnRows(sqlmock.NewRows([]string{"user_id", "cnt"}).AddRow(200, 1))
mock.ExpectQuery("SELECT user_id, subscription_user_id, order_no FROM `order`").
WithArgs(int64(200), 2, 5).
WillReturnRows(sqlmock.NewRows([]string{"user_id", "subscription_user_id", "order_no"}).AddRow(200, 900, "family-order"))
mock.ExpectQuery("object_id IN").
WithArgs(33, int64(100), "family-order", 331, 332).
WillReturnRows(sqlmock.NewRows([]string{"object_id", "content"}))
mock.ExpectQuery("object_id IN").
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":"邀请赠送"}`))
benefits, err := QueryBenefits(context.Background(), db, []InviteRelation{{InviteeId: 200, InviterId: 100}})
if err != nil {
t.Fatalf("QueryBenefits returned error: %v", err)
}
benefit := benefits[200]
if benefit.InviteeGiftDays != 7 {
t.Fatalf("InviteeGiftDays = %d, want 7", benefit.InviteeGiftDays)
}
if benefit.InviterGiftDays != 0 {
t.Fatalf("InviterGiftDays = %d, want 0", benefit.InviterGiftDays)
}
assertBenefitsExpectations(t, mock)
}
func TestQueryBenefitsKeepsDirectInviteeGift(t *testing.T) {
db, mock, cleanup := newBenefitsTestDB(t)
defer cleanup()
mock.ExpectQuery("COUNT(*) as cnt").
WithArgs(int64(200), 2, 5).
WillReturnRows(sqlmock.NewRows([]string{"user_id", "cnt"}).AddRow(200, 1))
mock.ExpectQuery("SELECT user_id, subscription_user_id, order_no FROM `order`").
WithArgs(int64(200), 2, 5).
WillReturnRows(sqlmock.NewRows([]string{"user_id", "subscription_user_id", "order_no"}).AddRow(200, 0, "direct-order"))
mock.ExpectQuery("object_id IN").
WithArgs(33, int64(100), "direct-order", 331, 332).
WillReturnRows(sqlmock.NewRows([]string{"object_id", "content"}))
mock.ExpectQuery("object_id IN").
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":"邀请赠送"}`))
benefits, err := QueryBenefits(context.Background(), db, []InviteRelation{{InviteeId: 200, InviterId: 100}})
if err != nil {
t.Fatalf("QueryBenefits returned error: %v", err)
}
if got := benefits[200].InviteeGiftDays; got != 5 {
t.Fatalf("InviteeGiftDays = %d, want 5", got)
}
assertBenefitsExpectations(t, mock)
}
func newBenefitsTestDB(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 assertBenefitsExpectations(t *testing.T, mock sqlmock.Sqlmock) {
t.Helper()
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}
@@ -0,0 +1,117 @@
package invite
import (
"context"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
)
type GetInviteManageListLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetInviteManageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetInviteManageListLogic {
return &GetInviteManageListLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetInviteManageListLogic) GetInviteManageList(req *types.GetInviteManageListRequest) (resp *types.GetInviteManageListResponse, err error) {
req.Page, req.Size = NormalizePage(req.Page, req.Size)
type inviteRow struct {
InviteeId int64 `gorm:"column:invitee_id"`
InviteeAvatar string `gorm:"column:invitee_avatar"`
InviteeEnable bool `gorm:"column:invitee_enable"`
InvitedAt int64 `gorm:"column:invited_at"`
InviterId int64 `gorm:"column:inviter_id"`
}
baseQuery := applyInviteManageFilters(l.svcCtx.DB.WithContext(l.ctx).
Table("user invitee").
Where("invitee.referer_id > 0 AND invitee.deleted_at IS NULL"), req)
var total int64
if err = baseQuery.Count(&total).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count invite manage records failed: %v", err)
}
var rows []inviteRow
if err = applyInviteManageFilters(l.svcCtx.DB.WithContext(l.ctx).
Table("user invitee").
Select("invitee.id as invitee_id, invitee.avatar as invitee_avatar, invitee.enable as invitee_enable, CAST(UNIX_TIMESTAMP(invitee.created_at) AS SIGNED) as invited_at, invitee.referer_id as inviter_id").
Where("invitee.referer_id > 0 AND invitee.deleted_at IS NULL"), req).
Order("invitee.created_at DESC").
Limit(req.Size).
Offset((req.Page - 1) * req.Size).
Scan(&rows).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invite manage records failed: %v", err)
}
relations := make([]InviteRelation, 0, len(rows))
userIds := make([]int64, 0, len(rows)*2)
for _, row := range rows {
relations = append(relations, InviteRelation{InviteeId: row.InviteeId, InviterId: row.InviterId})
userIds = append(userIds, row.InviteeId, row.InviterId)
}
benefits, err := QueryBenefits(l.ctx, l.svcCtx.DB, relations)
if err != nil {
return nil, err
}
identifiers, err := QueryIdentifiers(l.ctx, l.svcCtx.DB, userIds)
if err != nil {
return nil, err
}
list := make([]types.InviteManageRecord, 0, len(rows))
for _, row := range rows {
benefit := benefits[row.InviteeId]
list = append(list, types.InviteManageRecord{
InviterId: row.InviterId,
InviterIdentifier: identifiers[row.InviterId],
InviteeId: row.InviteeId,
InviteeIdentifier: identifiers[row.InviteeId],
InviteeAvatar: row.InviteeAvatar,
InviteeEnable: row.InviteeEnable,
InvitedAt: row.InvitedAt,
OrderCount: benefit.OrderCount,
HasPurchased: benefit.HasPurchased,
InviterCommission: benefit.InviterCommission,
InviterGiftDays: benefit.InviterGiftDays,
InviteeGiftDays: benefit.InviteeGiftDays,
})
}
return &types.GetInviteManageListResponse{
Total: total,
List: list,
}, nil
}
func applyInviteManageFilters(db *gorm.DB, req *types.GetInviteManageListRequest) *gorm.DB {
if req.InviterId > 0 {
db = db.Where("invitee.referer_id = ?", req.InviterId)
}
if req.InviteeId > 0 {
db = db.Where("invitee.id = ?", req.InviteeId)
}
if req.Search != "" {
search := "%" + req.Search + "%"
db = db.Where(
"(EXISTS (SELECT 1 FROM user_auth_methods inviter_auth WHERE inviter_auth.user_id = invitee.referer_id AND inviter_auth.auth_identifier LIKE ?) OR EXISTS (SELECT 1 FROM user_auth_methods invitee_auth WHERE invitee_auth.user_id = invitee.id AND invitee_auth.auth_identifier LIKE ?))",
search,
search,
)
}
return db
}
@@ -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) 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) userSub, err := l.lockRefundTargetSubscription(tx, &orderInfo)
if err != nil { if err != nil {
return err return err
@@ -256,6 +267,13 @@ func (l *RefundOrderLogic) lockCommissionSource(tx *gorm.DB, orderNo string, ord
return nil, 0, nil 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( func (l *RefundOrderLogic) buildRefundAuditLog(
operator *modeluser.User, operator *modeluser.User,
orderInfo *modelorder.Order, orderInfo *modelorder.Order,
@@ -1,11 +1,23 @@
package order package order
import ( import (
"context"
"fmt"
"strings"
"testing" "testing"
"time" "time"
"github.com/DATA-DOG/go-sqlmock"
"github.com/perfect-panel/server/internal/svc"
modelorder "github.com/perfect-panel/server/internal/model/order" modelorder "github.com/perfect-panel/server/internal/model/order"
modeluser "github.com/perfect-panel/server/internal/model/user" 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) { func TestOrderStatusName(t *testing.T) {
@@ -83,3 +95,155 @@ func TestBuildRefundAuditLog(t *testing.T) {
t.Fatalf("unexpected commission transition: %+v", got) 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
}
@@ -0,0 +1,58 @@
package promo
import (
"context"
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/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
type CreateRuleLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewCreateRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateRuleLogic {
return &CreateRuleLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *CreateRuleLogic) CreateRule(req *types.CreatePromoRuleRequest) (*types.PromoRule, error) {
if err := validateRuleInput(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
return nil, err
}
params, err := paramsToString(req.Params)
if err != nil {
return nil, err
}
enabled := true
if req.Enabled != nil {
enabled = *req.Enabled
}
rule := &promomodel.Rule{
Name: req.Name,
Type: req.Type,
Params: params,
Priority: req.Priority,
Enabled: enabled,
StartTime: unixPtrToTimePtr(req.StartTime),
EndTime: unixPtrToTimePtr(req.EndTime),
}
if err := l.svcCtx.PromoModel.InsertRule(l.ctx, rule); err != nil {
l.Errorw("[CreatePromoRule] Database Error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create promo rule error: %v", err.Error())
}
if err := l.svcCtx.Redis.Del(l.ctx, ruleCacheKey).Err(); err != nil {
l.Errorw("[CreatePromoRule] Delete Cache Error", logger.Field("error", err.Error()))
}
resp := convertRule(rule)
return &resp, nil
}
@@ -0,0 +1,47 @@
package promo
import (
"context"
stderrors "errors"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
)
type DeletePriceLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDeletePriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeletePriceLogic {
return &DeletePriceLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *DeletePriceLogic) DeletePrice(req *types.DeletePromoPriceRequest) error {
price, err := l.svcCtx.PromoModel.FindPrice(l.ctx, req.Id)
if err != nil {
if stderrors.Is(err, gorm.ErrRecordNotFound) {
l.Errorw("[DeletePromoPrice] Price Not Found", logger.Field("id", req.Id))
return errors.Wrapf(xerr.NewErrCodeMsg(404, "promo price not found"), "promo price not found: %d", req.Id)
}
l.Errorw("[DeletePromoPrice] Find Price Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo price error: %v", err.Error())
}
if err := l.svcCtx.PromoModel.DeletePrice(l.ctx, req.Id); err != nil {
l.Errorw("[DeletePromoPrice] Database Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo price error: %v", err.Error())
}
if err := l.svcCtx.Redis.Del(l.ctx, subscribePromoCacheKey(price.SubscribeId)).Err(); err != nil {
l.Errorw("[DeletePromoPrice] Delete Cache Error", logger.Field("error", err.Error()))
}
return nil
}
@@ -0,0 +1,46 @@
package promo
import (
"context"
stderrors "errors"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
)
type DeleteRuleLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDeleteRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteRuleLogic {
return &DeleteRuleLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *DeleteRuleLogic) DeleteRule(req *types.DeletePromoRuleRequest) error {
if _, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id); err != nil {
if stderrors.Is(err, gorm.ErrRecordNotFound) {
l.Errorw("[DeletePromoRule] Rule Not Found", logger.Field("id", req.Id))
return errors.Wrapf(xerr.NewErrCodeMsg(404, "promo rule not found"), "promo rule not found: %d", req.Id)
}
l.Errorw("[DeletePromoRule] Find Rule Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error())
}
if err := l.svcCtx.PromoModel.DeleteRule(l.ctx, req.Id); err != nil {
l.Errorw("[DeletePromoRule] Database Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo rule error: %v", err.Error())
}
if err := l.svcCtx.Redis.Del(l.ctx, ruleCacheKey).Err(); err != nil {
l.Errorw("[DeletePromoRule] Delete Cache Error", logger.Field("error", err.Error()))
}
return nil
}
@@ -0,0 +1,106 @@
package promo
import (
"context"
"testing"
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"
"gorm.io/gorm"
)
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
}
func (fakePromoModel) InsertUsage(context.Context, *promomodel.Usage, ...*gorm.DB) error {
return nil
}
func (m fakePromoModel) InsertRule(ctx context.Context, rule *promomodel.Rule) error {
if m.insertRule != nil {
return m.insertRule(ctx, rule)
}
return nil
}
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 (m fakePromoModel) UpdateRule(ctx context.Context, rule *promomodel.Rule) error {
if m.updateRule != nil {
return m.updateRule(ctx, rule)
}
return nil
}
func (fakePromoModel) DeleteRule(context.Context, int64) error {
return nil
}
func (fakePromoModel) QueryRuleList(context.Context, int, int, string, *bool, string) (int64, []*promomodel.Rule, error) {
return 0, nil, nil
}
func (fakePromoModel) UpsertPrices(context.Context, int64, []*promomodel.SubscribePromo) error {
return nil
}
func (fakePromoModel) FindPrice(context.Context, int64) (*promomodel.SubscribePromo, error) {
return nil, gorm.ErrRecordNotFound
}
func (fakePromoModel) DeletePrice(context.Context, int64) error {
return nil
}
func (fakePromoModel) QueryPriceList(context.Context, promomodel.PriceFilter) (int64, []*promomodel.SubscribePromo, error) {
return 0, nil, nil
}
func (fakePromoModel) QueryUsageList(context.Context, promomodel.UsageFilter) (int64, []*promomodel.Usage, error) {
return 0, nil, nil
}
func (fakePromoModel) Transaction(context.Context, func(*gorm.DB) error) error {
return nil
}
func TestDeleteRuleNotFoundReturns404(t *testing.T) {
svcCtx := &svc.ServiceContext{PromoModel: fakePromoModel{}}
err := NewDeleteRuleLogic(context.Background(), svcCtx).DeleteRule(&types.DeletePromoRuleRequest{Id: 1})
assertCodeError(t, err, 404)
}
func TestDeletePriceNotFoundReturns404(t *testing.T) {
svcCtx := &svc.ServiceContext{PromoModel: fakePromoModel{}}
err := NewDeletePriceLogic(context.Background(), svcCtx).DeletePrice(&types.DeletePromoPriceRequest{Id: 1})
assertCodeError(t, err, 404)
}
func assertCodeError(t *testing.T, err error, want uint32) {
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 != want {
t.Fatalf("unexpected error code: got %d want %d", got, want)
}
}
@@ -0,0 +1,47 @@
package promo
import (
"context"
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/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
type GetPriceListLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetPriceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPriceListLogic {
return &GetPriceListLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetPriceListLogic) GetPriceList(req *types.GetPromoPriceListRequest) (*types.GetPromoPriceListResponse, error) {
total, list, err := l.svcCtx.PromoModel.QueryPriceList(l.ctx, promomodel.PriceFilter{
Page: int(req.Page),
Size: int(req.Size),
RuleId: req.RuleId,
SubscribeId: req.SubscribeId,
})
if err != nil {
l.Errorw("[GetPromoPriceList] Database Error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo price list error: %v", err.Error())
}
resp := &types.GetPromoPriceListResponse{
Total: total,
List: make([]types.PromoPrice, 0, len(list)),
}
for _, item := range list {
resp.List = append(resp.List, convertPrice(item))
}
return resp, nil
}
@@ -0,0 +1,35 @@
package promo
import (
"context"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
type GetRuleDetailLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetRuleDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRuleDetailLogic {
return &GetRuleDetailLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetRuleDetailLogic) GetRuleDetail(req *types.GetPromoRuleDetailRequest) (*types.PromoRule, error) {
rule, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id)
if err != nil {
l.Errorw("[GetPromoRuleDetail] Database Error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo rule detail error: %v", err.Error())
}
resp := convertRule(rule)
return &resp, nil
}
@@ -0,0 +1,41 @@
package promo
import (
"context"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
type GetRuleListLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetRuleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRuleListLogic {
return &GetRuleListLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetRuleListLogic) GetRuleList(req *types.GetPromoRuleListRequest) (*types.GetPromoRuleListResponse, error) {
total, list, err := l.svcCtx.PromoModel.QueryRuleList(l.ctx, int(req.Page), int(req.Size), req.Type, req.Enabled, req.Search)
if err != nil {
l.Errorw("[GetPromoRuleList] Database Error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo rule list error: %v", err.Error())
}
resp := &types.GetPromoRuleListResponse{
Total: total,
List: make([]types.PromoRule, 0, len(list)),
}
for _, item := range list {
resp.List = append(resp.List, convertRule(item))
}
return resp, nil
}
@@ -0,0 +1,49 @@
package promo
import (
"context"
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/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
type GetUsageListLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetUsageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUsageListLogic {
return &GetUsageListLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetUsageListLogic) GetUsageList(req *types.GetPromoUsageListRequest) (*types.GetPromoUsageListResponse, error) {
total, list, err := l.svcCtx.PromoModel.QueryUsageList(l.ctx, promomodel.UsageFilter{
Page: int(req.Page),
Size: int(req.Size),
RuleId: req.RuleId,
UserId: req.UserId,
SubscribeId: req.SubscribeId,
OrderNo: req.OrderNo,
})
if err != nil {
l.Errorw("[GetPromoUsageList] Database Error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo usage list error: %v", err.Error())
}
resp := &types.GetPromoUsageListResponse{
Total: total,
List: make([]types.PromoUsage, 0, len(list)),
}
for _, item := range list {
resp.List = append(resp.List, convertUsage(item))
}
return resp, 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)
}
}
@@ -0,0 +1,81 @@
package promo
import (
"context"
promomodel "github.com/perfect-panel/server/internal/model/promo"
subscribeModel "github.com/perfect-panel/server/internal/model/subscribe"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
type SetPriceLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewSetPriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SetPriceLogic {
return &SetPriceLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *SetPriceLogic) SetPrice(req *types.SetPromoPriceRequest) error {
if _, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.PromoRuleId); err != nil {
l.Errorw("[SetPromoPrice] Find Rule Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error())
}
subscribeIds := make([]int64, 0, len(req.Items))
seenSubscribeIds := make(map[int64]struct{}, len(req.Items))
for _, item := range req.Items {
if _, ok := seenSubscribeIds[item.SubscribeId]; ok {
continue
}
seenSubscribeIds[item.SubscribeId] = struct{}{}
subscribeIds = append(subscribeIds, item.SubscribeId)
}
var subscribes []*subscribeModel.Subscribe
if err := l.svcCtx.DB.WithContext(l.ctx).Model(&subscribeModel.Subscribe{}).Where("id IN ?", subscribeIds).Find(&subscribes).Error; err != nil {
l.Errorw("[SetPromoPrice] Find Subscribe Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find subscribe error: %v", err.Error())
}
subscribeById := make(map[int64]*subscribeModel.Subscribe, len(subscribes))
for _, sub := range subscribes {
subscribeById[sub.Id] = sub
}
items := make([]*promomodel.SubscribePromo, 0, len(req.Items))
cacheKeys := make([]string, 0, len(req.Items))
for _, item := range req.Items {
sub, ok := subscribeById[item.SubscribeId]
if !ok {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "subscribe plan not found")
}
originPrice := sub.UnitPrice * item.Quantity
if item.PromoPrice >= originPrice {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "promo_price must be less than unit_price * quantity")
}
items = append(items, &promomodel.SubscribePromo{
SubscribeId: item.SubscribeId,
PromoRuleId: req.PromoRuleId,
Quantity: item.Quantity,
PromoPrice: item.PromoPrice,
})
cacheKeys = append(cacheKeys, subscribePromoCacheKey(item.SubscribeId))
}
if err := l.svcCtx.PromoModel.UpsertPrices(l.ctx, req.PromoRuleId, items); err != nil {
l.Errorw("[SetPromoPrice] Database Error", logger.Field("error", err.Error()))
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "set promo price error: %v", err.Error())
}
if len(cacheKeys) > 0 {
if err := l.svcCtx.Redis.Del(l.ctx, cacheKeys...).Err(); err != nil {
l.Errorw("[SetPromoPrice] Delete Cache Error", logger.Field("error", err.Error()))
}
}
return nil
}
+192
View File
@@ -0,0 +1,192 @@
package promo
import (
"encoding/json"
"fmt"
"math"
"time"
promomodel "github.com/perfect-panel/server/internal/model/promo"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
const (
ruleCacheKey = "promo:rules:enabled"
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")
}
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 {
case "new_user":
windowHours, ok := numberParam(params, "window_hours")
if !ok || windowHours <= 0 {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "params.window_hours must be greater than 0")
}
case "inactive_user":
inactiveMonths, ok := numberParam(params, "inactive_months")
if !ok || inactiveMonths <= 0 {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "params.inactive_months must be greater than 0")
}
case "campaign":
if params == nil {
return nil
}
default:
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "unsupported promo rule type")
}
return nil
}
func numberParam(params map[string]interface{}, key string) (int64, bool) {
if params == nil {
return 0, false
}
value, ok := params[key]
if !ok {
return 0, false
}
switch v := value.(type) {
case float64:
if math.Trunc(v) != v {
return 0, false
}
return int64(v), true
case int64:
return v, true
case int:
return int64(v), true
case json.Number:
n, err := v.Int64()
return n, err == nil
default:
return 0, false
}
}
func paramsToString(params map[string]interface{}) (string, error) {
if params == nil {
params = map[string]interface{}{}
}
b, err := json.Marshal(params)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "invalid params")
}
return string(b), nil
}
func parseParams(data string) map[string]interface{} {
if data == "" {
return map[string]interface{}{}
}
var params map[string]interface{}
if err := json.Unmarshal([]byte(data), &params); err != nil {
return map[string]interface{}{}
}
return params
}
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
}
return t
}
func timePtrToUnixPtr(t *time.Time) *int64 {
if t == nil {
return nil
}
ts := t.Unix()
return &ts
}
func convertRule(item *promomodel.Rule) types.PromoRule {
if item == nil {
return types.PromoRule{}
}
return types.PromoRule{
Id: item.Id,
Name: item.Name,
Type: item.Type,
Params: parseParams(item.Params),
Priority: item.Priority,
Enabled: item.Enabled,
StartTime: timePtrToUnixPtr(item.StartTime),
EndTime: timePtrToUnixPtr(item.EndTime),
CreatedAt: item.CreatedAt.Unix(),
UpdatedAt: item.UpdatedAt.Unix(),
}
}
func convertPrice(item *promomodel.SubscribePromo) types.PromoPrice {
if item == nil {
return types.PromoPrice{}
}
return types.PromoPrice{
Id: item.Id,
SubscribeId: item.SubscribeId,
PromoRuleId: item.PromoRuleId,
Quantity: item.Quantity,
PromoPrice: item.PromoPrice,
CreatedAt: item.CreatedAt.Unix(),
UpdatedAt: item.UpdatedAt.Unix(),
}
}
func convertUsage(item *promomodel.Usage) types.PromoUsage {
if item == nil {
return types.PromoUsage{}
}
return types.PromoUsage{
Id: item.Id,
UserId: item.UserId,
PromoRuleId: item.PromoRuleId,
SubscribeId: item.SubscribeId,
OrderNo: item.OrderNo,
PromoPrice: item.PromoPrice,
CreatedAt: item.CreatedAt.Unix(),
}
}
func subscribePromoCacheKey(subscribeId int64) string {
return fmt.Sprintf("%s%d", subscribeCachePref, subscribeId)
}
@@ -0,0 +1,60 @@
package promo
import (
"context"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
type UpdateRuleLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewUpdateRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateRuleLogic {
return &UpdateRuleLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UpdateRuleLogic) UpdateRule(req *types.UpdatePromoRuleRequest) (*types.PromoRule, error) {
if err := validateRuleInput(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
return nil, err
}
rule, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id)
if err != nil {
l.Errorw("[UpdatePromoRule] Find Rule Error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error())
}
params, err := paramsToString(req.Params)
if err != nil {
return nil, err
}
enabled := rule.Enabled
if req.Enabled != nil {
enabled = *req.Enabled
}
rule.Name = req.Name
rule.Type = req.Type
rule.Params = params
rule.Priority = req.Priority
rule.Enabled = enabled
rule.StartTime = unixPtrToTimePtr(req.StartTime)
rule.EndTime = unixPtrToTimePtr(req.EndTime)
if err := l.svcCtx.PromoModel.UpdateRule(l.ctx, rule); err != nil {
l.Errorw("[UpdatePromoRule] Database Error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update promo rule error: %v", err.Error())
}
if err := l.svcCtx.Redis.Del(l.ctx, ruleCacheKey).Err(); err != nil {
l.Errorw("[UpdatePromoRule] Delete Cache Error", logger.Field("error", err.Error()))
}
resp := convertRule(rule)
return &resp, nil
}
@@ -3,11 +3,13 @@ package user
import ( import (
"context" "context"
adminInvite "github.com/perfect-panel/server/internal/logic/admin/invite"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types" "github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger" "github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr" "github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors" "github.com/pkg/errors"
"gorm.io/gorm"
) )
type GetAdminUserInviteListLogic struct { type GetAdminUserInviteListLogic struct {
@@ -25,15 +27,7 @@ func NewGetAdminUserInviteListLogic(ctx context.Context, svcCtx *svc.ServiceCont
} }
func (l *GetAdminUserInviteListLogic) GetAdminUserInviteList(req *types.GetAdminUserInviteListRequest) (resp *types.GetAdminUserInviteListResponse, err error) { func (l *GetAdminUserInviteListLogic) GetAdminUserInviteList(req *types.GetAdminUserInviteListRequest) (resp *types.GetAdminUserInviteListResponse, err error) {
if req.Page < 1 { req.Page, req.Size = adminInvite.NormalizePage(req.Page, req.Size)
req.Page = 1
}
if req.Size < 1 {
req.Size = 10
}
if req.Size > 100 {
req.Size = 100
}
type InvitedUser struct { type InvitedUser struct {
Id int64 `gorm:"column:id"` Id int64 `gorm:"column:id"`
@@ -44,19 +38,19 @@ func (l *GetAdminUserInviteListLogic) GetAdminUserInviteList(req *types.GetAdmin
} }
var total int64 var total int64
baseQuery := l.svcCtx.DB.WithContext(l.ctx). baseQuery := applyAdminUserInviteFilters(l.svcCtx.DB.WithContext(l.ctx).
Table("user u"). Table("user u").
Where("u.referer_id = ? AND u.deleted_at IS NULL", req.UserId) Where("u.referer_id = ? AND u.deleted_at IS NULL", req.UserId), req)
if err = baseQuery.Count(&total).Error; err != nil { if err = baseQuery.Count(&total).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count invited users failed: %v", err) return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count invited users failed: %v", err)
} }
var rows []InvitedUser var rows []InvitedUser
err = l.svcCtx.DB.WithContext(l.ctx). err = applyAdminUserInviteFilters(l.svcCtx.DB.WithContext(l.ctx).
Table("user u"). Table("user u").
Select("u.id, u.avatar, u.enable, UNIX_TIMESTAMP(u.created_at) as created_at, COALESCE((SELECT uam.auth_identifier FROM user_auth_methods uam WHERE uam.user_id = u.id ORDER BY uam.id ASC LIMIT 1), '') as identifier"). Select("u.id, u.avatar, u.enable, CAST(UNIX_TIMESTAMP(u.created_at) AS SIGNED) as created_at, COALESCE((SELECT uam.auth_identifier FROM user_auth_methods uam WHERE uam.user_id = u.id ORDER BY uam.id ASC LIMIT 1), '') as identifier").
Where("u.referer_id = ? AND u.deleted_at IS NULL", req.UserId). Where("u.referer_id = ? AND u.deleted_at IS NULL", req.UserId), req).
Order("u.created_at DESC"). Order("u.created_at DESC").
Limit(req.Size). Limit(req.Size).
Offset((req.Page - 1) * req.Size). Offset((req.Page - 1) * req.Size).
@@ -65,14 +59,29 @@ func (l *GetAdminUserInviteListLogic) GetAdminUserInviteList(req *types.GetAdmin
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invited users failed: %v", err) return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invited users failed: %v", err)
} }
relations := make([]adminInvite.InviteRelation, 0, len(rows))
for _, r := range rows {
relations = append(relations, adminInvite.InviteRelation{InviteeId: r.Id, InviterId: req.UserId})
}
benefits, err := adminInvite.QueryBenefits(l.ctx, l.svcCtx.DB, relations)
if err != nil {
return nil, err
}
list := make([]types.AdminInvitedUser, 0, len(rows)) list := make([]types.AdminInvitedUser, 0, len(rows))
for _, r := range rows { for _, r := range rows {
benefit := benefits[r.Id]
list = append(list, types.AdminInvitedUser{ list = append(list, types.AdminInvitedUser{
Id: r.Id, Id: r.Id,
Avatar: r.Avatar, Avatar: r.Avatar,
Identifier: r.Identifier, Identifier: r.Identifier,
Enable: r.Enable, Enable: r.Enable,
CreatedAt: r.CreatedAt, CreatedAt: r.CreatedAt,
OrderCount: benefit.OrderCount,
HasPurchased: benefit.HasPurchased,
InviterCommission: benefit.InviterCommission,
InviterGiftDays: benefit.InviterGiftDays,
InviteeGiftDays: benefit.InviteeGiftDays,
}) })
} }
@@ -81,3 +90,16 @@ func (l *GetAdminUserInviteListLogic) GetAdminUserInviteList(req *types.GetAdmin
List: list, List: list,
}, nil }, nil
} }
func applyAdminUserInviteFilters(db *gorm.DB, req *types.GetAdminUserInviteListRequest) *gorm.DB {
if req.Search != "" {
db = db.Where("EXISTS (SELECT 1 FROM user_auth_methods uam WHERE uam.user_id = u.id AND uam.auth_identifier LIKE ?)", "%"+req.Search+"%")
}
if req.Enable != nil {
db = db.Where("u.enable = ?", *req.Enable)
}
if req.UserIdSearch > 0 {
db = db.Where("u.id = ?", req.UserIdSearch)
}
return db
}
@@ -2,6 +2,7 @@ package user
import ( import (
"context" "context"
"encoding/json"
"github.com/perfect-panel/server/internal/model/group" "github.com/perfect-panel/server/internal/model/group"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
@@ -36,6 +37,13 @@ func (l *GetUserSubscribeByIdLogic) GetUserSubscribeById(req *types.GetUserSubsc
} }
var subscribeDetails types.UserSubscribeDetail var subscribeDetails types.UserSubscribeDetail
tool.DeepCopy(&subscribeDetails, sub) tool.DeepCopy(&subscribeDetails, sub)
subscribeDetails.SpeedLimit = sub.SpeedLimit
if sub.TrafficLimit != nil && *sub.TrafficLimit != "" {
_ = json.Unmarshal([]byte(*sub.TrafficLimit), &subscribeDetails.TrafficLimit)
}
if sub.Subscribe != nil {
subscribeDetails.PlanSpeedLimit = sub.Subscribe.SpeedLimit
}
// 填充分组名 // 填充分组名
if sub.NodeGroupId > 0 { if sub.NodeGroupId > 0 {
@@ -47,7 +55,17 @@ func (l *GetUserSubscribeByIdLogic) GetUserSubscribeById(req *types.GetUserSubsc
// Calculate speed limit status // Calculate speed limit status
if sub.Subscribe != nil && sub.Status == 1 { if sub.Subscribe != nil && sub.Status == 1 {
result := speedlimit.Calculate(l.ctx, l.svcCtx.DB, sub.UserId, sub.Id, sub.Subscribe.SpeedLimit, sub.Subscribe.TrafficLimit) baseSpeed := sub.Subscribe.SpeedLimit
if sub.SpeedLimit > 0 {
baseSpeed = sub.SpeedLimit
}
trafficLimit := sub.Subscribe.TrafficLimit
if sub.TrafficLimit != nil && *sub.TrafficLimit != "" {
trafficLimit = *sub.TrafficLimit
}
result := speedlimit.Calculate(l.ctx, l.svcCtx.DB, sub.UserId, sub.Id, baseSpeed, trafficLimit)
subscribeDetails.EffectiveSpeed = result.EffectiveSpeed subscribeDetails.EffectiveSpeed = result.EffectiveSpeed
subscribeDetails.IsThrottled = result.IsThrottled subscribeDetails.IsThrottled = result.IsThrottled
subscribeDetails.ThrottleRule = result.ThrottleRule subscribeDetails.ThrottleRule = result.ThrottleRule
@@ -39,22 +39,32 @@ func (l *UpdateUserSubscribeLogic) UpdateUserSubscribe(req *types.UpdateUserSubs
} else { } else {
userSub.Status = 1 userSub.Status = 1
} }
speedLimit := userSub.SpeedLimit
if req.SpeedLimit != nil {
speedLimit = *req.SpeedLimit
}
trafficLimit := userSub.TrafficLimit
if req.TrafficLimit != nil {
trafficLimit = req.TrafficLimit
}
err = l.svcCtx.UserModel.UpdateSubscribe(l.ctx, &user.Subscribe{ err = l.svcCtx.UserModel.UpdateSubscribe(l.ctx, &user.Subscribe{
Id: userSub.Id, Id: userSub.Id,
UserId: userSub.UserId, UserId: userSub.UserId,
OrderId: userSub.OrderId, OrderId: userSub.OrderId,
SubscribeId: req.SubscribeId, SubscribeId: req.SubscribeId,
StartTime: userSub.StartTime, StartTime: userSub.StartTime,
ExpireTime: time.UnixMilli(req.ExpiredAt), ExpireTime: time.UnixMilli(req.ExpiredAt),
Traffic: req.Traffic, Traffic: req.Traffic,
Download: req.Download, Download: req.Download,
Upload: req.Upload, Upload: req.Upload,
Token: userSub.Token, SpeedLimit: speedLimit,
UUID: userSub.UUID, TrafficLimit: trafficLimit,
Status: userSub.Status, Token: userSub.Token,
NodeGroupId: userSub.NodeGroupId, UUID: userSub.UUID,
GroupLocked: userSub.GroupLocked, Status: userSub.Status,
NodeGroupId: userSub.NodeGroupId,
GroupLocked: userSub.GroupLocked,
}) })
if err != nil { if err != nil {
+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
}
+37 -7
View File
@@ -11,6 +11,7 @@ import (
"github.com/perfect-panel/server/pkg/xerr" "github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors" "github.com/pkg/errors"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause"
) )
type PromoResult struct { type PromoResult struct {
@@ -27,13 +28,22 @@ type promoRuleParams struct {
InactiveMonths int `json:"inactive_months"` InactiveMonths int `json:"inactive_months"`
} }
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID 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{} result := &PromoResult{}
if svcCtx == nil || svcCtx.PromoModel == nil || svcCtx.DB == nil || userID <= 0 || subscribeID <= 0 { if svcCtx == nil || svcCtx.PromoModel == nil || svcCtx.DB == nil || subscribeID <= 0 || quantity <= 0 {
return result, nil return result, nil
} }
rules, err := svcCtx.PromoModel.QueryEligibleRules(ctx, subscribeID) rules, err := svcCtx.PromoModel.QueryEligibleRules(ctx, subscribeID, quantity)
if err != nil { if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo rules failed: %v", err.Error()) return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo rules failed: %v", err.Error())
} }
@@ -58,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 { if err != nil {
return nil, err return nil, err
} }
@@ -95,13 +105,20 @@ func evaluatePromoRule(
rule *promo.RuleWithPrice, rule *promo.RuleWithPrice,
params promoRuleParams, params promoRuleParams,
userID int64, userID int64,
isFirstPurchase bool,
currentUser *user.User, currentUser *user.User,
now time.Time, now time.Time,
) (bool, time.Time, error) { ) (bool, time.Time, error) {
switch rule.Type { switch rule.Type {
case promo.RuleTypeNewUser: case promo.RuleTypeNewUser:
if userID <= 0 || !isFirstPurchase {
return false, time.Time{}, nil
}
return evaluateNewUserPromo(ctx, db, params, userID, currentUser, now) return evaluateNewUserPromo(ctx, db, params, userID, currentUser, now)
case promo.RuleTypeInactiveUser: case promo.RuleTypeInactiveUser:
if userID <= 0 {
return false, time.Time{}, nil
}
return evaluateInactiveUserPromo(ctx, db, params, userID, promoRuleExpiresAt(rule), now) return evaluateInactiveUserPromo(ctx, db, params, userID, promoRuleExpiresAt(rule), now)
case promo.RuleTypeCampaign: case promo.RuleTypeCampaign:
return true, promoRuleExpiresAt(rule), nil return true, promoRuleExpiresAt(rule), nil
@@ -148,18 +165,31 @@ func evaluateInactiveUserPromo(
err := db.WithContext(ctx). err := db.WithContext(ctx).
Model(&user.Subscribe{}). Model(&user.Subscribe{}).
Where("user_id = ?", userID). Where("user_id = ?", userID).
Order("expire_time DESC"). Order(clause.OrderBy{
Expression: clause.Expr{
SQL: "CASE WHEN expire_time = ? THEN 0 ELSE 1 END, expire_time DESC",
Vars: []interface{}{time.UnixMilli(0)},
},
}).
Limit(1). Limit(1).
Take(&lastSub).Error Take(&lastSub).Error
if err != nil { if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { 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") return false, time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo inactive user subscription failed")
} }
return evaluateInactiveUserExpire(lastSub.ExpireTime, params, now), ruleExpiresAt, nil
}
func evaluateInactiveUserExpire(lastExpire time.Time, params promoRuleParams, now time.Time) bool {
if lastExpire.Equal(time.UnixMilli(0)) {
return false
}
threshold := now.AddDate(0, -params.InactiveMonths, 0) threshold := now.AddDate(0, -params.InactiveMonths, 0)
return lastSub.ExpireTime.Before(threshold) || lastSub.ExpireTime.Equal(threshold), ruleExpiresAt, nil return lastExpire.Before(threshold) || lastExpire.Equal(threshold)
} }
func promoRuleExpiresAt(rule *promo.RuleWithPrice) time.Time { func promoRuleExpiresAt(rule *promo.RuleWithPrice) time.Time {
@@ -0,0 +1,254 @@
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"
)
func TestEvaluateInactiveUserExpire(t *testing.T) {
now := time.Date(2026, 5, 27, 8, 0, 0, 0, time.UTC)
params := promoRuleParams{InactiveMonths: 3}
tests := []struct {
name string
lastExpire time.Time
want bool
}{
{
name: "permanent subscription is not inactive",
lastExpire: time.UnixMilli(0),
want: false,
},
{
name: "active subscription is not inactive",
lastExpire: now.Add(time.Hour),
want: false,
},
{
name: "expire at threshold is inactive",
lastExpire: now.AddDate(0, -3, 0),
want: true,
},
{
name: "expire before threshold is inactive",
lastExpire: now.AddDate(0, -3, -1),
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := evaluateInactiveUserExpire(tt.lastExpire, params, now); got != tt.want {
t.Fatalf("evaluateInactiveUserExpire() = %v, want %v", got, tt.want)
}
})
}
}
func TestEvaluatePromoAllowsAnonymousCampaign(t *testing.T) {
end := time.Now().Add(time.Hour)
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
{
Rule: promo.Rule{
Id: 3,
Name: "campaign",
Type: promo.RuleTypeCampaign,
Enabled: true,
EndTime: &end,
},
PromoPrice: 199,
},
}}
got, err := EvaluatePromo(context.Background(), &svc.ServiceContext{DB: &gorm.DB{}, PromoModel: model}, 0, 7, 12, true)
if err != nil {
t.Fatalf("EvaluatePromo returned error: %v", err)
}
if !got.Eligible {
t.Fatal("anonymous campaign promo should be eligible")
}
if got.RuleID != 3 {
t.Fatalf("RuleID = %d, want 3", got.RuleID)
}
if got.PromoPrice != 199 {
t.Fatalf("PromoPrice = %d, want 199", got.PromoPrice)
}
if model.lastSubscribeID != 7 {
t.Fatalf("lastSubscribeID = %d, want 7", model.lastSubscribeID)
}
if model.lastQuantity != 12 {
t.Fatalf("lastQuantity = %d, want 12", model.lastQuantity)
}
}
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
lastQuantity int64
}
func (m *fakePromoModel) QueryEligibleRules(_ context.Context, subscribeID int64, quantity int64) ([]*promo.RuleWithPrice, error) {
m.lastSubscribeID = subscribeID
m.lastQuantity = quantity
return m.rules, nil
}
func (m *fakePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error {
return nil
}
func (m *fakePromoModel) InsertRule(context.Context, *promo.Rule) error {
return nil
}
func (m *fakePromoModel) FindRule(context.Context, int64) (*promo.Rule, error) {
return nil, gorm.ErrRecordNotFound
}
func (m *fakePromoModel) UpdateRule(context.Context, *promo.Rule) error {
return nil
}
func (m *fakePromoModel) DeleteRule(context.Context, int64) error {
return nil
}
func (m *fakePromoModel) QueryRuleList(context.Context, int, int, string, *bool, string) (int64, []*promo.Rule, error) {
return 0, nil, nil
}
func (m *fakePromoModel) UpsertPrices(context.Context, int64, []*promo.SubscribePromo) error {
return nil
}
func (m *fakePromoModel) FindPrice(context.Context, int64) (*promo.SubscribePromo, error) {
return nil, gorm.ErrRecordNotFound
}
func (m *fakePromoModel) DeletePrice(context.Context, int64) error {
return nil
}
func (m *fakePromoModel) QueryPriceList(context.Context, promo.PriceFilter) (int64, []*promo.SubscribePromo, error) {
return 0, nil, nil
}
func (m *fakePromoModel) QueryUsageList(context.Context, promo.UsageFilter) (int64, []*promo.Usage, error) {
return 0, nil, nil
}
func (m *fakePromoModel) Transaction(context.Context, func(*gorm.DB) error) error {
return nil
}
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/gin-gonic/gin"
"github.com/hibiken/asynq" "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/model/payment"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types" "github.com/perfect-panel/server/internal/types"
@@ -22,6 +23,47 @@ import (
queueType "github.com/perfect-panel/server/queue/types" 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 { type EPayNotifyLogic struct {
logger.Logger logger.Logger
ctx *gin.Context 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) orderInfo, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OutTradeNo)
if err != nil { 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)) 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) 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 // Verify sign
client := epay.NewClient(config.Pid, config.Url, config.Key, config.Type) client := epay.NewClient(config.Pid, config.Url, config.Key, config.Type)
if !client.VerifySign(urlParamsToMap(l.ctx.Request.URL.RawQuery)) && !l.svcCtx.Config.Debug { signValid := client.VerifySign(urlParamsToMap(l.ctx.Request.URL.RawQuery))
l.Logger.Error("[EPayNotify] Verify sign failed")
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 return nil
} case epayNotifyDecisionAckIdempotent:
if req.TradeStatus != "TRADE_SUCCESS" { // Order already Finished — repeat callback is expected, ack with 200.
l.Logger.Error("[EPayNotify] Trade status is not success", logger.Field("orderNo", req.OutTradeNo), logger.Field("tradeStatus", req.TradeStatus))
return nil 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 // Update order status
err = l.svcCtx.OrderModel.UpdateOrderStatus(l.ctx, req.OutTradeNo, 2) err = l.svcCtx.OrderModel.UpdateOrderStatus(l.ctx, req.OutTradeNo, 2)
if err != nil { if err != nil {
@@ -86,6 +167,7 @@ func (l *EPayNotifyLogic) EPayNotify(req *types.EPayNotifyRequest) error {
"[SubscriptionFlow] epay notify marked order as paid", "[SubscriptionFlow] epay notify marked order as paid",
append(commonLogic.OrderTraceFields(orderInfo), append(commonLogic.OrderTraceFields(orderInfo),
logger.Field("payment_platform", data.Platform), logger.Field("payment_platform", data.Platform),
logger.Field("trade_no", req.TradeNo),
)..., )...,
) )
// Create activate order task // 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()
}
}
+1 -1
View File
@@ -80,7 +80,7 @@ func validateInitRequest(svcCtx *svc.ServiceContext, bizType, fileName, contentT
allowed := allowedContentTypeSet(svcCtx.Config.S3.AllowedContentTypes) allowed := allowedContentTypeSet(svcCtx.Config.S3.AllowedContentTypes)
if len(allowed) > 0 { if len(allowed) > 0 {
if _, ok := allowed[strings.ToLower(strings.TrimSpace(contentType))]; !ok { if _, ok := allowed[strings.ToLower(strings.TrimSpace(contentType))]; !ok {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "content_type is not allowed") return errors.Wrapf(xerr.NewErrCodeMsg(xerr.InvalidParams, "content_type is not allowed"), "content_type is not allowed")
} }
} }
return nil return nil
+91
View File
@@ -0,0 +1,91 @@
package file
import (
"mime/multipart"
"strings"
"testing"
"github.com/perfect-panel/server/internal/config"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/storage"
)
const testAllowedContentTypes = "application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json,image/jpeg,image/jpg,image/png,image/webp,image/gif,image/heic,image/heif,image/bmp"
type testMultipartFile struct {
*strings.Reader
}
func (testMultipartFile) Close() error {
return nil
}
func TestValidateInitRequestAllowedContentTypes(t *testing.T) {
svcCtx := &svc.ServiceContext{
Config: config.Config{
S3: config.S3Config{
Enable: true,
MaxUploadSize: 1024,
AllowedContentTypes: testAllowedContentTypes,
},
},
S3Store: &storage.S3Store{},
}
tests := []struct {
name string
contentType string
wantErr bool
}{
{name: "allow jpeg", contentType: "image/jpeg"},
{name: "allow png", contentType: "image/png"},
{name: "allow webp", contentType: "image/webp"},
{name: "reject unknown", contentType: "application/x-sh", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateInitRequest(svcCtx, "app-package", "demo.bin", tt.contentType, 10)
if tt.wantErr {
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "content_type is not allowed") {
t.Fatalf("expected content type error, got %v", err)
}
return
}
if err != nil {
t.Fatalf("expected nil error, got %v", err)
}
})
}
}
func TestSniffContentTypeDetectsCommonImages(t *testing.T) {
tests := []struct {
name string
data string
want string
}{
{name: "jpeg", data: "\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01", want: "image/jpeg"},
{name: "png", data: "\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR", want: "image/png"},
{name: "webp", data: "RIFF\x1a\x00\x00\x00WEBPVP8 \x0e\x00\x00\x00", want: "image/webp"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
file := testMultipartFile{Reader: strings.NewReader(tt.data)}
got, err := sniffContentType(&multipart.FileHeader{}, file)
if err != nil {
t.Fatalf("expected nil error, got %v", err)
}
if got != tt.want {
t.Fatalf("expected %q, got %q", tt.want, got)
}
if pos, err := file.Seek(0, 1); err != nil || pos != 0 {
t.Fatalf("expected reader reset to start, pos=%d err=%v", pos, err)
}
})
}
}
+259 -46
View File
@@ -5,9 +5,12 @@ import (
"encoding/json" "encoding/json"
"time" "time"
"github.com/hibiken/asynq"
"github.com/perfect-panel/server/internal/model/log" "github.com/perfect-panel/server/internal/model/log"
"github.com/perfect-panel/server/internal/model/user" "github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/pkg/payment/epay"
"github.com/perfect-panel/server/pkg/payment/stripe" "github.com/perfect-panel/server/pkg/payment/stripe"
queueTypes "github.com/perfect-panel/server/queue/types"
"gorm.io/gorm" "gorm.io/gorm"
"github.com/perfect-panel/server/internal/model/order" "github.com/perfect-panel/server/internal/model/order"
@@ -18,19 +21,52 @@ import (
"github.com/perfect-panel/server/pkg/payment/alipay" "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 { type CloseOrderLogic struct {
logger.Logger logger.Logger
ctx context.Context ctx context.Context
svcCtx *svc.ServiceContext 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 // NewCloseOrderLogic Close order
func NewCloseOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CloseOrderLogic { func NewCloseOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CloseOrderLogic {
return &CloseOrderLogic{ l := &CloseOrderLogic{
Logger: logger.WithContext(ctx), Logger: logger.WithContext(ctx),
ctx: ctx, ctx: ctx,
svcCtx: svcCtx, 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 { func (l *CloseOrderLogic) CloseOrder(req *types.CloseOrderRequest) error {
@@ -52,6 +88,31 @@ func (l *CloseOrderLogic) CloseOrder(req *types.CloseOrderRequest) error {
return nil 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) sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, orderInfo.SubscribeId)
if err != nil { if err != nil {
l.Errorw("[CloseOrder] Find subscribe info failed", l.Errorw("[CloseOrder] Find subscribe info failed",
@@ -166,42 +227,117 @@ func (l *CloseOrderLogic) CloseOrder(req *types.CloseOrderRequest) error {
return nil return nil
} }
// confirmationPayment Determine whether the payment is successful // 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
//nolint:unused // activation task the notify handlers would have enqueued. We deliberately
func (l *CloseOrderLogic) confirmationPayment(order *order.Order) bool { // reuse ForthwithActivateOrder so the rest of the activation pipeline
paymentConfig, err := l.svcCtx.PaymentModel.FindOne(l.ctx, order.PaymentId) // (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 { if err != nil {
l.Errorw("[CloseOrder] Find payment config failed", logger.Field("error", err.Error()), logger.Field("paymentMark", order.Method)) l.Errorw("[CloseOrder] marshal activation payload failed",
return false logger.Field("error", err.Error()),
logger.Field("orderNo", orderInfo.OrderNo),
)
return nil
} }
switch order.Method { taskID, err := l.enqueueActivate(l.ctx, bytes)
case AlipayF2f: if err != nil {
if l.queryAlipay(paymentConfig, order.TradeNo) { // Order is already at status=2; if enqueue fails the stuck-order
return true // recovery sweeper will pick it up. Log loudly but don't error out.
} l.Errorw("[CloseOrder] enqueue activation task failed after gateway-paid recovery",
case StripeAlipay: logger.Field("error", err.Error()),
if l.queryStripe(paymentConfig, order.TradeNo) { logger.Field("orderNo", orderInfo.OrderNo),
return true )
} return nil
case StripeWeChatPay:
if l.queryStripe(paymentConfig, order.TradeNo) {
return true
}
default:
l.Infow("[CloseOrder] Unsupported payment method", logger.Field("paymentMethod", order.Method))
} }
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 // queryGatewayPaymentStatus dispatches to the right gateway client for the
// // order's payment method and returns a tri-state result. Methods without an
//nolint:unused // external gateway (Balance, unknown) return Unpaid — the historical close
func (l *CloseOrderLogic) queryAlipay(paymentConfig *payment.Payment, TradeNo string) bool { // 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{} config := payment.AlipayF2FConfig{}
if err := json.Unmarshal([]byte(paymentConfig.Config), &config); err != nil { 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)) l.Errorw("[CloseOrder] Unmarshal Alipay config failed",
return false logger.Field("error", err.Error()),
logger.Field("orderNo", orderInfo.OrderNo),
)
return GatewayStatusUnknown
} }
client := alipay.NewClient(alipay.Config{ client := alipay.NewClient(alipay.Config{
AppId: config.AppId, AppId: config.AppId,
@@ -209,35 +345,112 @@ func (l *CloseOrderLogic) queryAlipay(paymentConfig *payment.Payment, TradeNo st
PublicKey: config.PublicKey, PublicKey: config.PublicKey,
InvoiceName: config.InvoiceName, 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 { if err != nil {
l.Errorw("[CloseOrder] Query trade failed", logger.Field("error", err.Error()), logger.Field("TradeNo", TradeNo)) l.Errorw("[CloseOrder] Alipay QueryTrade failed",
return false logger.Field("error", err.Error()),
logger.Field("orderNo", orderInfo.OrderNo),
logger.Field("tradeNo", orderInfo.TradeNo),
)
return GatewayStatusUnknown
} }
if status == alipay.Success || status == alipay.Finished { switch status {
return true 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 // queryStripe queries Stripe PaymentIntent and maps to a tri-state.
// // Any Stripe-side error (network, 5xx, decode) is Unknown — Stripe is the
//nolint:unused // gateway most prone to silent webhook drops in this codebase, so we must not
func (l *CloseOrderLogic) queryStripe(paymentConfig *payment.Payment, TradeNo string) bool { // 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{} config := payment.StripeConfig{}
if err := json.Unmarshal([]byte(paymentConfig.Config), &config); err != nil { 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)) l.Errorw("[CloseOrder] Unmarshal Stripe config failed",
return false logger.Field("error", err.Error()),
logger.Field("orderNo", orderInfo.OrderNo),
)
return GatewayStatusUnknown
} }
client := stripe.NewClient(stripe.Config{ client := stripe.NewClient(stripe.Config{
PublicKey: config.PublicKey, PublicKey: config.PublicKey,
SecretKey: config.SecretKey, SecretKey: config.SecretKey,
WebhookSecret: config.WebhookSecret, WebhookSecret: config.WebhookSecret,
}) })
status, err := client.QueryOrderStatus(TradeNo) paid, err := client.QueryOrderStatus(orderInfo.TradeNo)
if err != nil { if err != nil {
l.Errorw("[CloseOrder] Query order status failed", logger.Field("error", err.Error()), logger.Field("TradeNo", TradeNo)) l.Errorw("[CloseOrder] Stripe QueryOrderStatus failed",
return false 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)
}
}
@@ -47,13 +47,18 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
l.Debugf("[PreCreateOrder] Quantity is less than or equal to 0, setting to 1") l.Debugf("[PreCreateOrder] Quantity is less than or equal to 0, setting to 1")
req.Quantity = 1 req.Quantity = 1
} }
entitlement, entErr := commonLogic.ResolveEntitlementUser(l.ctx, l.svcCtx.DB, u.Id)
if entErr != nil {
return nil, entErr
}
targetSubscribeID := req.SubscribeId targetSubscribeID := req.SubscribeId
orderType := uint8(1)
isSingleModeRenewal := false isSingleModeRenewal := false
decision, routeErr := commonLogic.ResolvePurchaseRoute( decision, routeErr := commonLogic.ResolvePurchaseRoute(
l.ctx, l.ctx,
l.svcCtx.Config.Subscribe.SingleModel, l.svcCtx.Config.Subscribe.SingleModel,
u.Id, entitlement.EffectiveUserID,
req.SubscribeId, req.SubscribeId,
l.svcCtx.UserModel.FindSingleModeAnchorSubscribe, l.svcCtx.UserModel.FindSingleModeAnchorSubscribe,
) )
@@ -68,15 +73,39 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
targetSubscribeID = decision.ResolvedSubscribeID targetSubscribeID = decision.ResolvedSubscribeID
isSingleModeRenewal = decision.Route == commonLogic.PurchaseRoutePurchaseToRenewal isSingleModeRenewal = decision.Route == commonLogic.PurchaseRoutePurchaseToRenewal
if isSingleModeRenewal && decision.Anchor != nil { if isSingleModeRenewal && decision.Anchor != nil {
orderType = 2
l.Infow("[PreCreateOrder] single mode purchase routed to renewal preview", l.Infow("[PreCreateOrder] single mode purchase routed to renewal preview",
logger.Field("mode", "single"), logger.Field("mode", "single"),
logger.Field("route", "purchase_to_renewal"), logger.Field("route", "purchase_to_renewal"),
logger.Field("anchor_user_subscribe_id", decision.Anchor.Id), logger.Field("anchor_user_subscribe_id", decision.Anchor.Id),
logger.Field("user_id", u.Id), logger.Field("user_id", u.Id),
logger.Field("effective_user_id", entitlement.EffectiveUserID),
) )
} }
} }
// Keep promo eligibility preview aligned with Purchase: an existing paid subscription
// 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 := 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"),
logger.Field("route", "purchase_to_existing_subscription"),
logger.Field("existing_subscribe_id", existSub.Id),
logger.Field("existing_status", existSub.Status),
logger.Field("user_id", u.Id),
logger.Field("effective_user_id", entitlement.EffectiveUserID),
logger.Field("resolved_subscribe_id", targetSubscribeID),
)
} else if e != nil && !errors.Is(e, gorm.ErrRecordNotFound) {
l.Errorw("[PreCreateOrder] Database query error", logger.Field("error", e.Error()), logger.Field("user_id", u.Id))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find existing subscription error: %v", e.Error())
}
}
// find subscribe plan // find subscribe plan
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, targetSubscribeID) sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, targetSubscribeID)
if err != nil { if err != nil {
@@ -86,7 +115,7 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
// check subscribe plan quota limit for new purchase flow only // check subscribe plan quota limit for new purchase flow only
if !isSingleModeRenewal && sub.Quota > 0 { if !isSingleModeRenewal && sub.Quota > 0 {
userSub, err := l.svcCtx.UserModel.QueryUserSubscribe(l.ctx, u.Id) userSub, err := l.svcCtx.UserModel.QueryUserSubscribe(l.ctx, entitlement.EffectiveUserID)
if err != nil { if err != nil {
l.Errorw("[PreCreateOrder] Database query error", logger.Field("error", err.Error()), logger.Field("user_id", u.Id)) l.Errorw("[PreCreateOrder] Database query error", logger.Field("error", err.Error()), logger.Field("user_id", u.Id))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user subscription error: %v", err.Error()) return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user subscription error: %v", err.Error())
@@ -102,7 +131,7 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
} }
} }
newUserDiscount, err := resolveNewUserDiscountEligibility(l.ctx, l.svcCtx.DB, u.Id, targetSubscribeID, req.Quantity, sub.Discount) newUserDiscount, err := resolveNewUserDiscountEligibility(l.ctx, l.svcCtx.DB, entitlement.EffectiveUserID, targetSubscribeID, req.Quantity, sub.Discount)
if err != nil { if err != nil {
l.Errorw("[PreCreateOrder] Database query error resolving new user eligibility", l.Errorw("[PreCreateOrder] Database query error resolving new user eligibility",
logger.Field("error", err.Error()), logger.Field("error", err.Error()),
@@ -117,13 +146,13 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
priceResult, err := calculatePurchasePrice( priceResult, err := calculatePurchasePrice(
l.ctx, l.ctx,
l.svcCtx, l.svcCtx,
u.Id, entitlement.EffectiveUserID,
targetSubscribeID, targetSubscribeID,
sub.UnitPrice, sub.UnitPrice,
req.Quantity, req.Quantity,
newUserDiscount.Discounts, newUserDiscount.Discounts,
newUserDiscount.EligibleForDiscount, newUserDiscount.EligibleForDiscount,
!isSingleModeRenewal, orderType == 1,
) )
if err != nil { if err != nil {
l.Errorw("[PreCreateOrder] Promo price calculation error", l.Errorw("[PreCreateOrder] Promo price calculation error",
+13 -15
View File
@@ -27,7 +27,7 @@ func calculatePurchasePrice(
quantity int64, quantity int64,
discounts []types.SubscribeDiscount, discounts []types.SubscribeDiscount,
eligibleForDiscount bool, eligibleForDiscount bool,
allowPromo bool, isFirstPurchase bool,
) (*orderPriceResult, error) { ) (*orderPriceResult, error) {
originalPrice := unitPrice * quantity originalPrice := unitPrice * quantity
result := &orderPriceResult{ result := &orderPriceResult{
@@ -35,21 +35,19 @@ func calculatePurchasePrice(
PayableBase: originalPrice, PayableBase: originalPrice,
} }
if allowPromo { promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, subscribeID, quantity, isFirstPurchase)
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, subscribeID) if err != nil {
if err != nil { return nil, err
return nil, err }
} if promoResult != nil && promoResult.Eligible && promoResult.PromoPrice < originalPrice {
if promoResult != nil && promoResult.Eligible && promoResult.PromoPrice < unitPrice { result.PayableBase = promoResult.PromoPrice
result.PayableBase = promoResult.PromoPrice * quantity result.PromoRuleId = promoResult.RuleID
result.PromoRuleId = promoResult.RuleID result.PromoDiscount = originalPrice - result.PayableBase
result.PromoDiscount = originalPrice - result.PayableBase result.PromoPrice = promoResult.PromoPrice
result.PromoPrice = promoResult.PromoPrice if result.PromoDiscount < 0 {
if result.PromoDiscount < 0 { result.PromoDiscount = 0
result.PromoDiscount = 0
}
return result, nil
} }
return result, nil
} }
discount := float64(1) discount := float64(1)
+223 -37
View File
@@ -11,31 +11,85 @@ import (
) )
type fakePromoModel struct { type fakePromoModel struct {
rules []*promo.RuleWithPrice rules []*promo.RuleWithPrice
lastSubscribeID int64
lastQuantity int64
requireQuantity int64
quantityMismatch []*promo.RuleWithPrice
} }
func (m fakePromoModel) QueryEligibleRules(context.Context, int64) ([]*promo.RuleWithPrice, error) { func (m *fakePromoModel) QueryEligibleRules(_ context.Context, subscribeID int64, quantity int64) ([]*promo.RuleWithPrice, error) {
m.lastSubscribeID = subscribeID
m.lastQuantity = quantity
if m.requireQuantity > 0 && quantity != m.requireQuantity {
return m.quantityMismatch, nil
}
return m.rules, nil return m.rules, nil
} }
func (m fakePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error { func (m *fakePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error {
return nil return nil
} }
func TestCalculatePurchasePricePromoSkipsPercentDiscount(t *testing.T) { func (m *fakePromoModel) InsertRule(context.Context, *promo.Rule) error {
svcCtx := &svc.ServiceContext{ return nil
DB: &gorm.DB{}, }
PromoModel: fakePromoModel{rules: []*promo.RuleWithPrice{
{ func (m *fakePromoModel) FindRule(context.Context, int64) (*promo.Rule, error) {
Rule: promo.Rule{ return nil, gorm.ErrRecordNotFound
Id: 9, }
Name: "campaign",
Type: promo.RuleTypeCampaign, func (m *fakePromoModel) UpdateRule(context.Context, *promo.Rule) error {
Enabled: true, return nil
}, }
PromoPrice: 600,
func (m *fakePromoModel) DeleteRule(context.Context, int64) error {
return nil
}
func (m *fakePromoModel) QueryRuleList(context.Context, int, int, string, *bool, string) (int64, []*promo.Rule, error) {
return 0, nil, nil
}
func (m *fakePromoModel) UpsertPrices(context.Context, int64, []*promo.SubscribePromo) error {
return nil
}
func (m *fakePromoModel) FindPrice(context.Context, int64) (*promo.SubscribePromo, error) {
return nil, gorm.ErrRecordNotFound
}
func (m *fakePromoModel) DeletePrice(context.Context, int64) error {
return nil
}
func (m *fakePromoModel) QueryPriceList(context.Context, promo.PriceFilter) (int64, []*promo.SubscribePromo, error) {
return 0, nil, nil
}
func (m *fakePromoModel) QueryUsageList(context.Context, promo.UsageFilter) (int64, []*promo.Usage, error) {
return 0, nil, nil
}
func (m *fakePromoModel) Transaction(context.Context, func(*gorm.DB) error) error {
return nil
}
func TestCalculatePurchasePricePromoUsesQuantityTierTotalPrice(t *testing.T) {
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
{
Rule: promo.Rule{
Id: 9,
Name: "campaign",
Type: promo.RuleTypeCampaign,
Enabled: true,
}, },
}}, PromoPrice: 279,
},
}}
svcCtx := &svc.ServiceContext{
DB: &gorm.DB{},
PromoModel: model,
} }
result, err := calculatePurchasePrice( result, err := calculatePurchasePrice(
@@ -43,9 +97,9 @@ func TestCalculatePurchasePricePromoSkipsPercentDiscount(t *testing.T) {
svcCtx, svcCtx,
1, 1,
2, 2,
1000, 100,
3, 7,
[]types.SubscribeDiscount{{Quantity: 3, Discount: 50}}, []types.SubscribeDiscount{{Quantity: 7, Discount: 50}},
true, true,
true, true,
) )
@@ -53,11 +107,11 @@ func TestCalculatePurchasePricePromoSkipsPercentDiscount(t *testing.T) {
t.Fatalf("calculatePurchasePrice returned error: %v", err) t.Fatalf("calculatePurchasePrice returned error: %v", err)
} }
if result.OriginalPrice != 3000 { if result.OriginalPrice != 700 {
t.Fatalf("OriginalPrice = %d, want 3000", result.OriginalPrice) t.Fatalf("OriginalPrice = %d, want 700", result.OriginalPrice)
} }
if result.PayableBase != 1800 { if result.PayableBase != 279 {
t.Fatalf("PayableBase = %d, want 1800", result.PayableBase) t.Fatalf("PayableBase = %d, want 279", result.PayableBase)
} }
if result.DiscountAmount != 0 { if result.DiscountAmount != 0 {
t.Fatalf("DiscountAmount = %d, want 0", result.DiscountAmount) t.Fatalf("DiscountAmount = %d, want 0", result.DiscountAmount)
@@ -65,25 +119,32 @@ func TestCalculatePurchasePricePromoSkipsPercentDiscount(t *testing.T) {
if result.PromoRuleId != 9 { if result.PromoRuleId != 9 {
t.Fatalf("PromoRuleId = %d, want 9", result.PromoRuleId) t.Fatalf("PromoRuleId = %d, want 9", result.PromoRuleId)
} }
if result.PromoDiscount != 1200 { if result.PromoDiscount != 421 {
t.Fatalf("PromoDiscount = %d, want 1200", result.PromoDiscount) t.Fatalf("PromoDiscount = %d, want 421", result.PromoDiscount)
}
if result.PromoPrice != 279 {
t.Fatalf("PromoPrice = %d, want 279", result.PromoPrice)
}
if model.lastQuantity != 7 {
t.Fatalf("promo query quantity = %d, want 7", model.lastQuantity)
} }
} }
func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) { func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) {
svcCtx := &svc.ServiceContext{ model := &fakePromoModel{rules: []*promo.RuleWithPrice{
DB: &gorm.DB{}, {
PromoModel: fakePromoModel{rules: []*promo.RuleWithPrice{ Rule: promo.Rule{
{ Id: 10,
Rule: promo.Rule{ Name: "invalid campaign",
Id: 10, Type: promo.RuleTypeCampaign,
Name: "invalid campaign", Enabled: true,
Type: promo.RuleTypeCampaign,
Enabled: true,
},
PromoPrice: 1000,
}, },
}}, PromoPrice: 3000,
},
}}
svcCtx := &svc.ServiceContext{
DB: &gorm.DB{},
PromoModel: model,
} }
result, err := calculatePurchasePrice( result, err := calculatePurchasePrice(
@@ -111,3 +172,128 @@ func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) {
t.Fatalf("promo fields = (%d, %d), want (0, 0)", result.PromoRuleId, result.PromoDiscount) t.Fatalf("promo fields = (%d, %d), want (0, 0)", result.PromoRuleId, result.PromoDiscount)
} }
} }
func TestCalculatePurchasePricePassesQuantityToPromoEvaluation(t *testing.T) {
promoModel := &fakePromoModel{
requireQuantity: 6,
rules: []*promo.RuleWithPrice{
{
Rule: promo.Rule{
Id: 11,
Name: "quantity campaign",
Type: promo.RuleTypeCampaign,
Enabled: true,
},
PromoPrice: 3000,
},
},
}
svcCtx := &svc.ServiceContext{
DB: &gorm.DB{},
PromoModel: promoModel,
}
result, err := calculatePurchasePrice(
context.Background(),
svcCtx,
1,
2,
1000,
6,
[]types.SubscribeDiscount{{Quantity: 6, Discount: 80}},
true,
true,
)
if err != nil {
t.Fatalf("calculatePurchasePrice returned error: %v", err)
}
if promoModel.lastSubscribeID != 2 {
t.Fatalf("lastSubscribeID = %d, want 2", promoModel.lastSubscribeID)
}
if promoModel.lastQuantity != 6 {
t.Fatalf("lastQuantity = %d, want 6", promoModel.lastQuantity)
}
if result.PayableBase != 3000 {
t.Fatalf("PayableBase = %d, want 3000", result.PayableBase)
}
if result.PromoRuleId != 11 {
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)
}
}
+6 -9
View File
@@ -129,13 +129,8 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
// 防止不同套餐购买创建第二条订阅。 // 防止不同套餐购买创建第二条订阅。
if !l.svcCtx.Config.Subscribe.SingleModel && orderType == 1 { if !l.svcCtx.Config.Subscribe.SingleModel && orderType == 1 {
var existSub user.Subscribe var existSub user.Subscribe
if e := l.svcCtx.DB.WithContext(l.ctx). if e := paidSubscriptionQuery(l.ctx, l.svcCtx.DB, entitlement.EffectiveUserID).
Model(&user.Subscribe{}). First(&existSub).Error; e == nil && existSub.Id > 0 {
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 != "" {
orderType = 2 orderType = 2
parentOrderID = existSub.OrderId parentOrderID = existSub.OrderId
subscribeToken = existSub.Token subscribeToken = existSub.Token
@@ -194,11 +189,12 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SubscribeOutOfStock), "subscribe out of stock") return nil, errors.Wrapf(xerr.NewErrCode(xerr.SubscribeOutOfStock), "subscribe out of stock")
} }
newUserDiscount, err := resolveNewUserDiscountEligibility(l.ctx, l.svcCtx.DB, u.Id, targetSubscribeID, req.Quantity, sub.Discount) newUserDiscount, err := resolveNewUserDiscountEligibility(l.ctx, l.svcCtx.DB, entitlement.EffectiveUserID, targetSubscribeID, req.Quantity, sub.Discount)
if err != nil { if err != nil {
l.Errorw("[Purchase] Database query error resolving new user eligibility", l.Errorw("[Purchase] Database query error resolving new user eligibility",
logger.Field("error", err.Error()), logger.Field("error", err.Error()),
logger.Field("user_id", u.Id), logger.Field("user_id", u.Id),
logger.Field("effective_user_id", entitlement.EffectiveUserID),
) )
return nil, err return nil, err
} }
@@ -206,7 +202,7 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
priceResult, err := calculatePurchasePrice( priceResult, err := calculatePurchasePrice(
l.ctx, l.ctx,
l.svcCtx, l.svcCtx,
u.Id, entitlement.EffectiveUserID,
targetSubscribeID, targetSubscribeID,
sub.UnitPrice, sub.UnitPrice,
req.Quantity, req.Quantity,
@@ -218,6 +214,7 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
l.Errorw("[Purchase] Promo price calculation error", l.Errorw("[Purchase] Promo price calculation error",
logger.Field("error", err.Error()), logger.Field("error", err.Error()),
logger.Field("user_id", u.Id), logger.Field("user_id", u.Id),
logger.Field("effective_user_id", entitlement.EffectiveUserID),
logger.Field("subscribe_id", targetSubscribeID), logger.Field("subscribe_id", targetSubscribeID),
) )
return nil, err return nil, err
+46 -135
View File
@@ -2,12 +2,12 @@ package subscribe
import ( import (
"context" "context"
"encoding/json"
stderrors "errors" stderrors "errors"
"strings" "strings"
"time" "time"
"github.com/go-sql-driver/mysql" "github.com/go-sql-driver/mysql"
commonLogic "github.com/perfect-panel/server/internal/logic/common"
"github.com/perfect-panel/server/internal/model/user" "github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types" "github.com/perfect-panel/server/internal/types"
@@ -25,6 +25,7 @@ const (
type subscribePromoCandidate struct { type subscribePromoCandidate struct {
SubscribeId int64 `gorm:"column:subscribe_id"` SubscribeId int64 `gorm:"column:subscribe_id"`
Quantity int64 `gorm:"column:quantity"`
RuleName string `gorm:"column:rule_name"` RuleName string `gorm:"column:rule_name"`
RuleType string `gorm:"column:rule_type"` RuleType string `gorm:"column:rule_type"`
PromoPrice int64 `gorm:"column:promo_price"` PromoPrice int64 `gorm:"column:promo_price"`
@@ -33,18 +34,29 @@ type subscribePromoCandidate struct {
EndTime *time.Time `gorm:"column:end_time"` EndTime *time.Time `gorm:"column:end_time"`
} }
type promoRuleParams struct { func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64) (map[int64]map[int64]*types.SubscribePromo, error) {
WindowHours int64 `json:"window_hours"` result := make(map[int64]map[int64]*types.SubscribePromo)
InactiveMonths int `json:"inactive_months"`
}
func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64) (map[int64]*types.SubscribePromo, error) {
result := make(map[int64]*types.SubscribePromo)
if len(subscribeIDs) == 0 || svcCtx == nil || svcCtx.DB == nil { if len(subscribeIDs) == 0 || svcCtx == nil || svcCtx.DB == nil {
return result, nil return result, nil
} }
userInfo, _ := ctx.Value(constant.CtxKeyUser).(*user.User) 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) candidates, err := querySubscribePromoCandidates(ctx, svcCtx, subscribeIDs, userInfo != nil)
if err != nil { if err != nil {
if isMissingPromoTableError(err) { if isMissingPromoTableError(err) {
@@ -53,27 +65,28 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
return nil, err return nil, err
} }
evaluator := promoEligibilityEvaluator{ctx: ctx, db: svcCtx.DB, userInfo: userInfo}
now := time.Now()
for _, candidate := range candidates { for _, candidate := range candidates {
if _, exists := result[candidate.SubscribeId]; exists { if candidate.Quantity <= 0 {
continue continue
} }
if !candidate.isActive(now) { if result[candidate.SubscribeId] == nil {
result[candidate.SubscribeId] = make(map[int64]*types.SubscribePromo)
}
if _, exists := result[candidate.SubscribeId][candidate.Quantity]; exists {
continue continue
} }
ok, expiresAt, err := evaluator.match(candidate, now) promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, candidate.SubscribeId, candidate.Quantity, isFirstPurchase)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if !ok { if promoResult == nil || !promoResult.Eligible {
continue continue
} }
result[candidate.SubscribeId] = &types.SubscribePromo{ result[candidate.SubscribeId][candidate.Quantity] = &types.SubscribePromo{
RuleName: candidate.RuleName, RuleName: promoResult.RuleName,
RuleType: candidate.RuleType, RuleType: promoResult.RuleType,
PromoPrice: candidate.PromoPrice, PromoPrice: promoResult.PromoPrice,
ExpiresAt: unixSeconds(expiresAt), ExpiresAt: unixSeconds(promoResult.ExpiresAt),
} }
} }
@@ -82,18 +95,7 @@ func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subs
func querySubscribePromoCandidates(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64, loggedIn bool) ([]subscribePromoCandidate, error) { func querySubscribePromoCandidates(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64, loggedIn bool) ([]subscribePromoCandidate, error) {
var candidates []subscribePromoCandidate var candidates []subscribePromoCandidate
query := svcCtx.DB.WithContext(ctx). err := subscribePromoCandidatesQuery(ctx, svcCtx.DB, subscribeIDs, loggedIn).
Table("subscribe_promo AS sp").
Select("sp.subscribe_id, sp.promo_price, pr.name AS rule_name, pr.type AS rule_type, pr.params, pr.start_time, pr.end_time").
Joins("JOIN promo_rule AS pr ON pr.id = sp.promo_rule_id AND pr.deleted_at IS NULL").
Where("sp.subscribe_id IN ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeIDs, true)
if !loggedIn {
query = query.Where("pr.type = ?", promoRuleTypeCampaign)
}
err := query.
Order("sp.subscribe_id ASC").
Order("pr.priority DESC").
Order("pr.id ASC").
Scan(&candidates).Error Scan(&candidates).Error
if err != nil { if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query subscribe promo candidates failed: %v", err) return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query subscribe promo candidates failed: %v", err)
@@ -101,111 +103,20 @@ func querySubscribePromoCandidates(ctx context.Context, svcCtx *svc.ServiceConte
return candidates, nil return candidates, nil
} }
func (c subscribePromoCandidate) isActive(now time.Time) bool { func subscribePromoCandidatesQuery(ctx context.Context, db *gorm.DB, subscribeIDs []int64, loggedIn bool) *gorm.DB {
if c.PromoPrice <= 0 { query := db.WithContext(ctx).
return false Table("subscribe_promo AS sp").
Select("sp.subscribe_id, sp.quantity, sp.promo_price, pr.name AS rule_name, pr.type AS rule_type, pr.params, pr.start_time, pr.end_time").
Joins("JOIN promo_rule AS pr ON pr.id = sp.promo_rule_id AND pr.deleted_at IS NULL").
Where("sp.subscribe_id IN ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeIDs, true)
if !loggedIn {
query = query.Where("pr.type = ?", promoRuleTypeCampaign)
} }
if c.StartTime != nil && now.Before(*c.StartTime) { return query.
return false Order("sp.subscribe_id ASC").
} Order("sp.quantity ASC").
if c.EndTime != nil && now.After(*c.EndTime) { Order("pr.priority DESC").
return false Order("pr.id ASC")
}
return true
}
type promoEligibilityEvaluator struct {
ctx context.Context
db *gorm.DB
userInfo *user.User
lastExpire *time.Time
}
func (e *promoEligibilityEvaluator) match(candidate subscribePromoCandidate, now time.Time) (bool, time.Time, error) {
switch candidate.RuleType {
case promoRuleTypeCampaign:
return true, candidate.expiresAt(), nil
case promoRuleTypeNewUser:
if e.userInfo == nil {
return false, time.Time{}, nil
}
params, err := candidate.params()
if err != nil {
return false, time.Time{}, err
}
if params.WindowHours <= 0 || e.userInfo.CreatedAt.IsZero() {
return false, time.Time{}, nil
}
expiresAt := e.userInfo.CreatedAt.Add(time.Duration(params.WindowHours) * time.Hour)
return now.Before(expiresAt), expiresAt, nil
case promoRuleTypeInactiveUser:
if e.userInfo == nil {
return false, time.Time{}, nil
}
params, err := candidate.params()
if err != nil {
return false, time.Time{}, err
}
if params.InactiveMonths <= 0 {
return false, time.Time{}, nil
}
lastExpire, err := e.lastSubscribeExpireAt()
if err != nil {
return false, time.Time{}, err
}
if lastExpire.Equal(time.UnixMilli(0)) || lastExpire.After(now) {
return false, time.Time{}, nil
}
if lastExpire.IsZero() {
return true, candidate.expiresAt(), nil
}
threshold := now.AddDate(0, -params.InactiveMonths, 0)
return !lastExpire.After(threshold), candidate.expiresAt(), nil
default:
return false, time.Time{}, nil
}
}
func (e *promoEligibilityEvaluator) lastSubscribeExpireAt() (time.Time, error) {
if e.lastExpire != nil {
return *e.lastExpire, nil
}
var item user.Subscribe
err := e.db.WithContext(e.ctx).
Model(&user.Subscribe{}).
Where("user_id = ?", e.userInfo.Id).
Where("expire_time != ?", time.UnixMilli(0)).
Order("expire_time DESC").
Limit(1).
Take(&item).Error
if err != nil {
if stderrors.Is(err, gorm.ErrRecordNotFound) {
zero := time.Time{}
e.lastExpire = &zero
return zero, nil
}
return time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo user last subscription failed")
}
e.lastExpire = &item.ExpireTime
return item.ExpireTime, nil
}
func (c subscribePromoCandidate) expiresAt() time.Time {
if c.EndTime == nil {
return time.Time{}
}
return *c.EndTime
}
func (c subscribePromoCandidate) params() (promoRuleParams, error) {
if c.Params == "" {
return promoRuleParams{}, nil
}
var params promoRuleParams
if err := json.Unmarshal([]byte(c.Params), &params); err != nil {
return promoRuleParams{}, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "parse promo rule params failed")
}
return params, nil
} }
func unixSeconds(t time.Time) int64 { func unixSeconds(t time.Time) int64 {
+241 -53
View File
@@ -1,75 +1,263 @@
package subscribe package subscribe
import ( import (
"context"
"fmt"
"strings"
"testing" "testing"
"time" "time"
"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/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"
) )
func TestPromoEligibilityEvaluatorMatch(t *testing.T) { func TestQuerySubscribePromoCandidatesIncludesQuantity(t *testing.T) {
now := time.Unix(1710000000, 0) db, err := gorm.Open(mysql.New(mysql.Config{
campaignEnd := now.Add(2 * time.Hour) DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local",
SkipInitializeWithVersion: true,
campaign := subscribePromoCandidate{ }), &gorm.Config{DryRun: true, DisableAutomaticPing: true})
RuleName: "限时活动",
RuleType: promoRuleTypeCampaign,
PromoPrice: 99,
EndTime: &campaignEnd,
}
ok, expiresAt, err := (&promoEligibilityEvaluator{}).match(campaign, now)
if err != nil { if err != nil {
t.Fatalf("campaign match error: %v", err) t.Fatalf("open dry-run db: %v", err)
}
if !ok {
t.Fatal("campaign promo should match without login")
}
if got, want := unixSeconds(expiresAt), campaignEnd.Unix(); got != want {
t.Fatalf("campaign expires_at = %d, want %d", got, want)
} }
newUser := subscribePromoCandidate{ var candidates []subscribePromoCandidate
RuleName: "新客7天优惠", tx := subscribePromoCandidatesQuery(context.Background(), db, []int64{11, 12}, true).Scan(&candidates)
RuleType: promoRuleTypeNewUser, stmt := tx.Statement
PromoPrice: 279, sql := stmt.SQL.String()
Params: `{"window_hours":168}`, if !strings.Contains(sql, "sp.subscribe_id, sp.quantity, sp.promo_price") {
t.Fatalf("SQL missing quantity select: %s", sql)
} }
ok, _, err = (&promoEligibilityEvaluator{}).match(newUser, now) if !strings.Contains(sql, "ORDER BY sp.subscribe_id ASC,sp.quantity ASC,pr.priority DESC,pr.id ASC") {
if err != nil { t.Fatalf("SQL missing quantity order: %s", sql)
t.Fatalf("anonymous new_user match error: %v", err)
}
if ok {
t.Fatal("new_user promo should not match without login")
}
userInfo := &user.User{Id: 1, CreatedAt: now.Add(-24 * time.Hour)}
ok, expiresAt, err = (&promoEligibilityEvaluator{userInfo: userInfo}).match(newUser, now)
if err != nil {
t.Fatalf("logged-in new_user match error: %v", err)
}
if !ok {
t.Fatal("new_user promo should match inside window")
}
if got, want := unixSeconds(expiresAt), userInfo.CreatedAt.Add(168*time.Hour).Unix(); got != want {
t.Fatalf("new_user expires_at = %d, want %d", got, want)
} }
} }
func TestSubscribePromoCandidateActiveWindow(t *testing.T) { func TestLoadSubscribePromoMapUsesCommonPromoEvaluation(t *testing.T) {
now := time.Unix(1710000000, 0) db, mock, cleanup := newSubscribePromoTestDB(t)
start := now.Add(-time.Hour) defer cleanup()
end := now.Add(time.Hour)
if !(subscribePromoCandidate{PromoPrice: 1, StartTime: &start, EndTime: &end}).isActive(now) { end := time.Now().Add(time.Hour)
t.Fatal("candidate inside active window should be active") mock.ExpectQuery("FROM subscribe_promo AS sp").
WillReturnRows(sqlmock.NewRows([]string{
"subscribe_id", "quantity", "rule_name", "rule_type", "promo_price", "params", "start_time", "end_time",
}).AddRow(11, 3, "old name", promoRuleTypeCampaign, 999, "", nil, end))
promoModel := &fakeSubscribePromoModel{rules: []*promo.RuleWithPrice{
{
Rule: promo.Rule{
Id: 8,
Name: "公共活动价",
Type: promo.RuleTypeCampaign,
Enabled: true,
EndTime: &end,
},
PromoPrice: 888,
},
}}
got, err := loadSubscribePromoMap(context.Background(), &svc.ServiceContext{DB: db, PromoModel: promoModel}, []int64{11})
if err != nil {
t.Fatalf("loadSubscribePromoMap returned error: %v", err)
} }
if (subscribePromoCandidate{PromoPrice: 0, StartTime: &start, EndTime: &end}).isActive(now) { if err := mock.ExpectationsWereMet(); err != nil {
t.Fatal("candidate with zero promo price should not be active") t.Fatalf("sql expectations: %v", err)
} }
if (subscribePromoCandidate{PromoPrice: 1, StartTime: &end}).isActive(now) { if promoModel.lastSubscribeID != 11 {
t.Fatal("candidate before start time should not be active") t.Fatalf("promo subscribe id = %d, want 11", promoModel.lastSubscribeID)
} }
if (subscribePromoCandidate{PromoPrice: 1, EndTime: &start}).isActive(now) { if promoModel.lastQuantity != 3 {
t.Fatal("candidate after end time should not be active") t.Fatalf("promo quantity = %d, want 3", promoModel.lastQuantity)
}
item := got[11][3]
if item == nil {
t.Fatal("quantity 3 promo should be present")
}
if item.RuleName != "公共活动价" {
t.Fatalf("RuleName = %q, want 公共活动价", item.RuleName)
}
if item.PromoPrice != 888 {
t.Fatalf("PromoPrice = %d, want 888", item.PromoPrice)
}
if item.ExpiresAt != end.Unix() {
t.Fatalf("ExpiresAt = %d, want %d", item.ExpiresAt, end.Unix())
}
}
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
lastQuantity int64
}
func (m *fakeSubscribePromoModel) QueryEligibleRules(_ context.Context, subscribeID int64, quantity int64) ([]*promo.RuleWithPrice, error) {
m.lastSubscribeID = subscribeID
m.lastQuantity = quantity
return m.rules, nil
}
func (m *fakeSubscribePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error {
return nil
}
func (m *fakeSubscribePromoModel) InsertRule(context.Context, *promo.Rule) error {
return nil
}
func (m *fakeSubscribePromoModel) FindRule(context.Context, int64) (*promo.Rule, error) {
return nil, gorm.ErrRecordNotFound
}
func (m *fakeSubscribePromoModel) UpdateRule(context.Context, *promo.Rule) error {
return nil
}
func (m *fakeSubscribePromoModel) DeleteRule(context.Context, int64) error {
return nil
}
func (m *fakeSubscribePromoModel) QueryRuleList(context.Context, int, int, string, *bool, string) (int64, []*promo.Rule, error) {
return 0, nil, nil
}
func (m *fakeSubscribePromoModel) UpsertPrices(context.Context, int64, []*promo.SubscribePromo) error {
return nil
}
func (m *fakeSubscribePromoModel) FindPrice(context.Context, int64) (*promo.SubscribePromo, error) {
return nil, gorm.ErrRecordNotFound
}
func (m *fakeSubscribePromoModel) DeletePrice(context.Context, int64) error {
return nil
}
func (m *fakeSubscribePromoModel) QueryPriceList(context.Context, promo.PriceFilter) (int64, []*promo.SubscribePromo, error) {
return 0, nil, nil
}
func (m *fakeSubscribePromoModel) QueryUsageList(context.Context, promo.UsageFilter) (int64, []*promo.Usage, error) {
return 0, nil, nil
}
func (m *fakeSubscribePromoModel) Transaction(context.Context, func(*gorm.DB) error) error {
return nil
}
func newSubscribePromoTestDB(t *testing.T) (*gorm.DB, sqlmock.Sqlmock, func()) {
t.Helper()
sqlDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherFunc(func(expectedSQL, actualSQL string) error {
if strings.Contains(actualSQL, expectedSQL) {
return nil
}
return fmt.Errorf("actual sql %q does not contain %q", actualSQL, expectedSQL)
})))
if err != nil {
t.Fatalf("create sqlmock: %v", err)
}
db, err := gorm.Open(mysql.New(mysql.Config{Conn: sqlDB, SkipInitializeWithVersion: true}), &gorm.Config{})
if err != nil {
_ = sqlDB.Close()
t.Fatalf("open gorm db: %v", err)
}
return db, mock, func() {
_ = sqlDB.Close()
}
}
func TestApplySubscribeDiscountPromosMatchesQuantity(t *testing.T) {
subscribe := types.Subscribe{Discount: []types.SubscribeDiscount{
{Quantity: 1},
{Quantity: 12},
}}
promos := map[int64]*types.SubscribePromo{
3: {RuleName: "季度优惠", PromoPrice: 2900},
12: {RuleName: "年度优惠", PromoPrice: 9900},
}
applySubscribeDiscountPromos(&subscribe, promos)
if subscribe.Discount[0].Promo != nil {
t.Fatalf("quantity 1 promo should be nil, got %+v", subscribe.Discount[0].Promo)
}
if subscribe.Discount[1].Promo == nil {
t.Fatal("quantity 12 promo should match")
}
if got, want := subscribe.Discount[1].Promo.RuleName, "年度优惠"; got != want {
t.Fatalf("promo rule name = %q, want %q", got, want)
}
subscribe = types.Subscribe{Discount: []types.SubscribeDiscount{{Quantity: 6}}}
applySubscribeDiscountPromos(&subscribe, promos)
if subscribe.Discount[0].Promo != nil {
t.Fatalf("promo should be nil when quantity does not match, got %+v", subscribe.Discount[0].Promo)
} }
} }
@@ -56,11 +56,19 @@ func (l *QuerySubscribeListLogic) QuerySubscribeList(req *types.QuerySubscribeLi
var discount []types.SubscribeDiscount var discount []types.SubscribeDiscount
_ = json.Unmarshal([]byte(item.Discount), &discount) _ = json.Unmarshal([]byte(item.Discount), &discount)
sub.Discount = discount sub.Discount = discount
list[i] = sub
} }
list[i] = sub list[i] = sub
} }
promos, err := loadSubscribePromoMap(l.ctx, l.svcCtx, subscribeIDs)
if err != nil {
l.Errorw("[QuerySubscribeListLogic] Query Promo Error", logger.Field("error", err.Error()))
return nil, err
}
for i := range list {
applySubscribeDiscountPromos(&list[i], promos[list[i].Id])
}
// 老版本客户端(无 X-App-Id)去掉每个套餐 discount 的最后一个 // 老版本客户端(无 X-App-Id)去掉每个套餐 discount 的最后一个
hasAppId, _ := l.ctx.Value(constant.CtxKeyHasAppId).(bool) hasAppId, _ := l.ctx.Value(constant.CtxKeyHasAppId).(bool)
if !hasAppId { if !hasAppId {
@@ -71,16 +79,13 @@ func (l *QuerySubscribeListLogic) QuerySubscribeList(req *types.QuerySubscribeLi
} }
} }
promos, err := loadSubscribePromoMap(l.ctx, l.svcCtx, subscribeIDs)
if err != nil {
l.Errorw("[QuerySubscribeListLogic] Query Promo Error", logger.Field("error", err.Error()))
return nil, err
}
for i := range list {
list[i].Promo = promos[list[i].Id]
}
resp.List = list resp.List = list
resp.Total = int64(len(list)) resp.Total = int64(len(list))
return return
} }
func applySubscribeDiscountPromos(subscribe *types.Subscribe, promoByQuantity map[int64]*types.SubscribePromo) {
for i := range subscribe.Discount {
subscribe.Discount[i].Promo = promoByQuantity[subscribe.Discount[i].Quantity]
}
}
@@ -4,7 +4,6 @@ import (
"context" "context"
logicCommon "github.com/perfect-panel/server/internal/logic/common" 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/model/user"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types" "github.com/perfect-panel/server/internal/types"
@@ -57,13 +56,10 @@ func (l *CancelWithdrawalLogic) CancelWithdrawal(req *types.CancelWithdrawalRequ
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "cancel withdrawal failed: %v", txErr) 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 { // Commission was NOT deducted at application time under the HIF-22
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "refund commission failed: %v", txErr) // 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).
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)
}
return nil 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
}
@@ -0,0 +1,262 @@
package user
import (
"context"
"encoding/json"
logmodel "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"
"github.com/perfect-panel/server/pkg/constant"
"github.com/perfect-panel/server/pkg/hash"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
)
const (
inviteRecordRoleInviter = "inviter"
inviteRecordRoleInvitee = "invitee"
)
type GetInviteRecordsLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
type inviteRecordLog struct {
Id int64 `gorm:"column:id"`
ObjectId int64 `gorm:"column:object_id"`
Content string `gorm:"column:content"`
CreatedAt int64 `gorm:"column:created_at"`
}
type inviteGiftContent struct {
OrderNo string `json:"order_no"`
Amount int64 `json:"amount"`
}
type parsedInviteRecordLog struct {
log inviteRecordLog
content inviteGiftContent
}
type inviteOrderUser struct {
OrderNo string `gorm:"column:order_no"`
UserId int64 `gorm:"column:user_id"`
SubscriptionUserId int64 `gorm:"column:subscription_user_id"`
RefererId int64 `gorm:"column:referer_id"`
}
// Get invite gift records
func NewGetInviteRecordsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetInviteRecordsLogic {
return &GetInviteRecordsLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetInviteRecordsLogic) GetInviteRecords(req *types.GetInviteRecordsRequest) (resp *types.GetInviteRecordsResponse, err error) {
u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
if !ok {
l.Errorw("[GetInviteRecords] user not found in context")
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
}
normalizeInviteRecordsPagination(req)
visibleUserIds, err := l.resolveInviteRecordVisibleUserIds(u.Id)
if err != nil {
l.Errorw("[GetInviteRecords] resolve visible users failed",
logger.Field("error", err.Error()),
logger.Field("user_id", u.Id))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "resolve visible users failed: %v", err.Error())
}
query := l.svcCtx.DB.WithContext(l.ctx).
Table("system_logs").
Where("type = ? AND object_id IN ?", logmodel.TypeGift.Uint8(), visibleUserIds).
Where("JSON_VALID(content) = 1").
Where("JSON_UNQUOTE(JSON_EXTRACT(content, '$.remark')) = ?", "邀请赠送")
if req.StartTime > 0 {
query = query.Where("created_at >= FROM_UNIXTIME(?)", req.StartTime)
}
if req.EndTime > 0 {
query = query.Where("created_at <= FROM_UNIXTIME(?)", req.EndTime)
}
var logs []inviteRecordLog
if err = query.
Select("id, object_id, content, CAST(UNIX_TIMESTAMP(created_at) * 1000 AS SIGNED) AS created_at").
Order("created_at DESC, id DESC").
Scan(&logs).Error; err != nil {
l.Errorw("[GetInviteRecords] query logs failed",
logger.Field("error", err.Error()),
logger.Field("user_id", u.Id))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query logs failed: %v", err.Error())
}
parsedLogs, orderNos := l.parseInviteRecordContents(logs)
if len(logs) == 0 || len(parsedLogs) == 0 {
return &types.GetInviteRecordsResponse{Total: 0, List: []types.InviteRecord{}}, nil
}
orders, err := l.queryInviteRecordOrders(orderNos)
if err != nil {
l.Errorw("[GetInviteRecords] query orders failed",
logger.Field("error", err.Error()),
logger.Field("user_id", u.Id))
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, visibleUserIdSet, hasOrder, orderInfo) {
continue
}
record := types.InviteRecord{
Role: inviteRecordRoleInviter,
GiftDays: content.Amount,
OrderNo: content.OrderNo,
CreatedAt: logItem.CreatedAt,
}
if hasOrder {
peerId := orderInfo.UserId
if orderInfo.UserId == u.Id {
record.Role = inviteRecordRoleInvitee
peerId = u.RefererId
}
if peerId > 0 {
record.PeerHash = hash.InvitePeerHash(peerId)
}
}
allRecords = append(allRecords, record)
}
total := int64(len(allRecords))
list := paginateInviteRecords(allRecords, req.Page, req.Size)
return &types.GetInviteRecordsResponse{
Total: total,
List: list,
}, nil
}
func (l *GetInviteRecordsLogic) resolveInviteRecordVisibleUserIds(currentUserId int64) ([]int64, error) {
visibleUserIds := []int64{currentUserId}
var relation struct {
FamilyId int64 `gorm:"column:family_id"`
Role uint8 `gorm:"column:role"`
OwnerUserId int64 `gorm:"column:owner_user_id"`
}
err := l.svcCtx.DB.WithContext(l.ctx).
Model(&user.UserFamilyMember{}).
Select("user_family_member.family_id, user_family_member.role, user_family.owner_user_id").
Joins("JOIN user_family ON user_family.id = user_family_member.family_id AND user_family.deleted_at IS NULL AND user_family.status = ?", user.FamilyStatusActive).
Where("user_family_member.user_id = ? AND user_family_member.status = ? AND user_family_member.deleted_at IS NULL", currentUserId, user.FamilyMemberActive).
First(&relation).Error
if err == nil {
if relation.Role != user.FamilyRoleOwner && relation.OwnerUserId > 0 && relation.OwnerUserId != currentUserId {
visibleUserIds = append(visibleUserIds, relation.OwnerUserId)
}
return visibleUserIds, nil
}
if errors.Is(err, gorm.ErrRecordNotFound) {
return visibleUserIds, nil
}
return nil, err
}
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
}
return true
}
func normalizeInviteRecordsPagination(req *types.GetInviteRecordsRequest) {
if req.Page < 1 {
req.Page = 1
}
if req.Size < 1 {
req.Size = 10
}
if req.Size > 100 {
req.Size = 100
}
}
func paginateInviteRecords(records []types.InviteRecord, page, size int) []types.InviteRecord {
start := (page - 1) * size
if start >= len(records) {
return []types.InviteRecord{}
}
end := start + size
if end > len(records) {
end = len(records)
}
return records[start:end]
}
func (l *GetInviteRecordsLogic) parseInviteRecordContents(logs []inviteRecordLog) ([]parsedInviteRecordLog, []string) {
parsedLogs := make([]parsedInviteRecordLog, 0, len(logs))
orderNos := make([]string, 0, len(logs))
for _, logItem := range logs {
var content inviteGiftContent
if err := json.Unmarshal([]byte(logItem.Content), &content); err != nil {
l.Infow("[GetInviteRecords] parse content failed",
logger.Field("error", err.Error()),
logger.Field("log_id", logItem.Id))
continue
}
parsedLogs = append(parsedLogs, parsedInviteRecordLog{log: logItem, content: content})
if content.OrderNo != "" {
orderNos = append(orderNos, content.OrderNo)
}
}
return parsedLogs, orderNos
}
func (l *GetInviteRecordsLogic) queryInviteRecordOrders(orderNos []string) (map[string]inviteOrderUser, error) {
orders := make(map[string]inviteOrderUser, len(orderNos))
if len(orderNos) == 0 {
return orders, nil
}
var orderData []inviteOrderUser
err := l.svcCtx.DB.WithContext(l.ctx).
Table("`order`").
Select("`order`.order_no, `order`.user_id, `order`.subscription_user_id, invitee.referer_id").
Joins("LEFT JOIN user invitee ON invitee.id = `order`.user_id").
Where("`order`.order_no IN ?", orderNos).
Scan(&orderData).Error
if err != nil {
return nil, err
}
for _, item := range orderData {
orders[item.OrderNo] = item
}
return orders, nil
}
@@ -0,0 +1,255 @@
package user
import (
"context"
"fmt"
"strings"
"testing"
"github.com/DATA-DOG/go-sqlmock"
modeluser "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/hash"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func TestGetInviteRecordsInviter(t *testing.T) {
svcCtx, mock, cleanup := newInviteRecordsTestSvc(t)
defer cleanup()
expectNoInviteRecordsFamily(t, mock, 100)
mock.ExpectQuery("SELECT id, object_id, content").
WithArgs(34, int64(100), "邀请赠送").
WillReturnRows(sqlmock.NewRows([]string{"id", "object_id", "content", "created_at"}).
AddRow(1, 100, `{"order_no":"order-1","amount":7,"remark":"邀请赠送"}`, 1779934580000))
mock.ExpectQuery("SELECT `order`.order_no, `order`.user_id, `order`.subscription_user_id, invitee.referer_id FROM `order`").
WithArgs("order-1").
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id", "subscription_user_id", "referer_id"}).AddRow("order-1", 200, 200, 100))
resp, err := NewGetInviteRecordsLogic(inviteRecordsContext(100, 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(200),
GiftDays: 7,
OrderNo: "order-1",
CreatedAt: 1779934580000,
})
assertInviteRecordsExpectations(t, mock)
}
func TestGetInviteRecordsInvitee(t *testing.T) {
svcCtx, mock, cleanup := newInviteRecordsTestSvc(t)
defer cleanup()
expectNoInviteRecordsFamily(t, mock, 200)
mock.ExpectQuery("SELECT id, object_id, content").
WithArgs(34, int64(200), "邀请赠送").
WillReturnRows(sqlmock.NewRows([]string{"id", "object_id", "content", "created_at"}).
AddRow(2, 200, `{"order_no":"order-2","amount":7,"remark":"邀请赠送"}`, 1779934590000))
mock.ExpectQuery("SELECT `order`.order_no, `order`.user_id, `order`.subscription_user_id, invitee.referer_id FROM `order`").
WithArgs("order-2").
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id", "subscription_user_id", "referer_id"}).AddRow("order-2", 200, 200, 100))
resp, err := NewGetInviteRecordsLogic(inviteRecordsContext(200, 100), svcCtx).GetInviteRecords(&types.GetInviteRecordsRequest{Page: 1, Size: 10})
if err != nil {
t.Fatalf("GetInviteRecords returned error: %v", err)
}
assertInviteRecordResponse(t, resp, types.InviteRecord{
Role: inviteRecordRoleInvitee,
PeerHash: hash.InvitePeerHash(100),
GiftDays: 7,
OrderNo: "order-2",
CreatedAt: 1779934590000,
})
assertInviteRecordsExpectations(t, mock)
}
func TestGetInviteRecordsMissingOrderReturnsDirtyRecord(t *testing.T) {
svcCtx, mock, cleanup := newInviteRecordsTestSvc(t)
defer cleanup()
expectNoInviteRecordsFamily(t, mock, 100)
mock.ExpectQuery("SELECT id, object_id, content").
WithArgs(34, int64(100), "邀请赠送").
WillReturnRows(sqlmock.NewRows([]string{"id", "object_id", "content", "created_at"}).
AddRow(3, 100, `{"order_no":"missing-order","amount":7,"remark":"邀请赠送"}`, 1779934600000))
mock.ExpectQuery("SELECT `order`.order_no, `order`.user_id, `order`.subscription_user_id, invitee.referer_id FROM `order`").
WithArgs("missing-order").
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id", "subscription_user_id", "referer_id"}))
resp, err := NewGetInviteRecordsLogic(inviteRecordsContext(100, 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,
GiftDays: 7,
OrderNo: "missing-order",
CreatedAt: 1779934600000,
})
assertInviteRecordsExpectations(t, mock)
}
func TestGetInviteRecordsFamilyMemberSeesOwnerGiftLog(t *testing.T) {
svcCtx, mock, cleanup := newInviteRecordsTestSvc(t)
defer cleanup()
expectInviteRecordsFamilyMember(t, mock, 200, 900)
mock.ExpectQuery("SELECT id, object_id, content").
WithArgs(34, int64(200), int64(900), "邀请赠送").
WillReturnRows(sqlmock.NewRows([]string{"id", "object_id", "content", "created_at"}).
AddRow(4, 900, `{"order_no":"family-order","amount":7,"remark":"邀请赠送"}`, 1779934610000))
mock.ExpectQuery("SELECT `order`.order_no, `order`.user_id, `order`.subscription_user_id, invitee.referer_id FROM `order`").
WithArgs("family-order").
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id", "subscription_user_id", "referer_id"}).AddRow("family-order", 200, 900, 100))
resp, err := NewGetInviteRecordsLogic(inviteRecordsContext(200, 100), svcCtx).GetInviteRecords(&types.GetInviteRecordsRequest{Page: 1, Size: 10})
if err != nil {
t.Fatalf("GetInviteRecords returned error: %v", err)
}
assertInviteRecordResponse(t, resp, types.InviteRecord{
Role: inviteRecordRoleInvitee,
PeerHash: hash.InvitePeerHash(100),
GiftDays: 7,
OrderNo: "family-order",
CreatedAt: 1779934610000,
})
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()
expectInviteRecordsFamilyOwner(t, mock, 900)
mock.ExpectQuery("SELECT id, object_id, content").
WithArgs(34, int64(900), "邀请赠送").
WillReturnRows(sqlmock.NewRows([]string{"id", "object_id", "content", "created_at"}).
AddRow(5, 900, `{"order_no":"member-order","amount":7,"remark":"邀请赠送"}`, 1779934620000))
mock.ExpectQuery("SELECT `order`.order_no, `order`.user_id, `order`.subscription_user_id, invitee.referer_id FROM `order`").
WithArgs("member-order").
WillReturnRows(sqlmock.NewRows([]string{"order_no", "user_id", "subscription_user_id", "referer_id"}).AddRow("member-order", 200, 900, 100))
resp, err := NewGetInviteRecordsLogic(inviteRecordsContext(900, 0), svcCtx).GetInviteRecords(&types.GetInviteRecordsRequest{Page: 1, Size: 10})
if err != nil {
t.Fatalf("GetInviteRecords returned error: %v", err)
}
if resp == nil {
t.Fatal("response is nil")
}
if resp.Total != 0 {
t.Fatalf("Total = %d, want 0", resp.Total)
}
if len(resp.List) != 0 {
t.Fatalf("len(List) = %d, want 0", len(resp.List))
}
assertInviteRecordsExpectations(t, mock)
}
func newInviteRecordsTestSvc(t *testing.T) (*svc.ServiceContext, 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 &svc.ServiceContext{DB: db}, mock, func() {
_ = sqlDB.Close()
}
}
func expectNoInviteRecordsFamily(t *testing.T, mock sqlmock.Sqlmock, userId int64) {
t.Helper()
mock.ExpectQuery("FROM `user_family_member` JOIN user_family").
WithArgs(1, userId, 1, 1).
WillReturnError(gorm.ErrRecordNotFound)
}
func expectInviteRecordsFamilyMember(t *testing.T, mock sqlmock.Sqlmock, userId, ownerUserId int64) {
t.Helper()
mock.ExpectQuery("FROM `user_family_member` JOIN user_family").
WithArgs(1, userId, 1, 1).
WillReturnRows(sqlmock.NewRows([]string{"family_id", "role", "owner_user_id"}).AddRow(800, 2, ownerUserId))
}
func expectInviteRecordsFamilyOwner(t *testing.T, mock sqlmock.Sqlmock, userId int64) {
t.Helper()
mock.ExpectQuery("FROM `user_family_member` JOIN user_family").
WithArgs(1, userId, 1, 1).
WillReturnRows(sqlmock.NewRows([]string{"family_id", "role", "owner_user_id"}).AddRow(800, 1, userId))
}
func inviteRecordsContext(userId, refererId int64) context.Context {
return context.WithValue(context.Background(), constant.CtxKeyUser, &modeluser.User{
Id: userId,
RefererId: refererId,
})
}
func assertInviteRecordResponse(t *testing.T, resp *types.GetInviteRecordsResponse, want types.InviteRecord) {
t.Helper()
if resp == nil {
t.Fatal("response is nil")
}
if resp.Total != 1 {
t.Fatalf("Total = %d, want 1", resp.Total)
}
if len(resp.List) != 1 {
t.Fatalf("len(List) = %d, want 1", len(resp.List))
}
if got := resp.List[0]; got != want {
t.Fatalf("record = %+v, want %+v", got, want)
}
}
func assertInviteRecordsExpectations(t *testing.T, mock sqlmock.Sqlmock) {
t.Helper()
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}
@@ -307,14 +307,24 @@ func (l *GetServerUserListLogic) canUseExpiredNodeGroup(userSub *user.Subscribe,
// calculateEffectiveSpeedLimit 计算用户的实际限速值(考虑按量限速规则) // calculateEffectiveSpeedLimit 计算用户的实际限速值(考虑按量限速规则)
func (l *GetServerUserListLogic) calculateEffectiveSpeedLimit(sub *subscribe.Subscribe, userSub *user.Subscribe) int64 { func (l *GetServerUserListLogic) calculateEffectiveSpeedLimit(sub *subscribe.Subscribe, userSub *user.Subscribe) int64 {
baseSpeed := sub.SpeedLimit
if userSub.SpeedLimit > 0 {
baseSpeed = userSub.SpeedLimit
}
trafficLimit := sub.TrafficLimit
if userSub.TrafficLimit != nil && *userSub.TrafficLimit != "" {
trafficLimit = *userSub.TrafficLimit
}
result := speedlimit.CalculateWithCache( result := speedlimit.CalculateWithCache(
l.ctx.Request.Context(), l.ctx.Request.Context(),
l.svcCtx.Redis, l.svcCtx.Redis,
l.svcCtx.DB, l.svcCtx.DB,
userSub.UserId, userSub.UserId,
userSub.Id, userSub.Id,
sub.SpeedLimit, baseSpeed,
sub.TrafficLimit, trafficLimit,
30*time.Second, 30*time.Second,
) )
return result.EffectiveSpeed return result.EffectiveSpeed
+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)
}
}
+183 -3
View File
@@ -2,6 +2,7 @@ package promo
import ( import (
"context" "context"
"errors"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"gorm.io/gorm" "gorm.io/gorm"
@@ -13,8 +14,35 @@ type RuleWithPrice struct {
} }
type Model interface { type Model interface {
QueryEligibleRules(ctx context.Context, subscribeId int64) ([]*RuleWithPrice, error) QueryEligibleRules(ctx context.Context, subscribeId int64, quantity int64) ([]*RuleWithPrice, error)
InsertUsage(ctx context.Context, data *Usage, tx ...*gorm.DB) error InsertUsage(ctx context.Context, data *Usage, tx ...*gorm.DB) error
InsertRule(ctx context.Context, data *Rule) error
FindRule(ctx context.Context, id int64) (*Rule, error)
UpdateRule(ctx context.Context, data *Rule) error
DeleteRule(ctx context.Context, id int64) error
QueryRuleList(ctx context.Context, page, size int, ruleType string, enabled *bool, search string) (int64, []*Rule, error)
UpsertPrices(ctx context.Context, ruleId int64, items []*SubscribePromo) error
FindPrice(ctx context.Context, id int64) (*SubscribePromo, error)
DeletePrice(ctx context.Context, id int64) error
QueryPriceList(ctx context.Context, params PriceFilter) (int64, []*SubscribePromo, error)
QueryUsageList(ctx context.Context, params UsageFilter) (int64, []*Usage, error)
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
}
type UsageFilter struct {
Page int
Size int
RuleId int64
UserId int64
SubscribeId int64
OrderNo string
}
type PriceFilter struct {
Page int
Size int
RuleId int64
SubscribeId int64
} }
type defaultPromoModel struct { type defaultPromoModel struct {
@@ -25,13 +53,13 @@ func NewModel(db *gorm.DB, _ *redis.Client) Model {
return &defaultPromoModel{db: db} return &defaultPromoModel{db: db}
} }
func (m *defaultPromoModel) QueryEligibleRules(ctx context.Context, subscribeId int64) ([]*RuleWithPrice, error) { func (m *defaultPromoModel) QueryEligibleRules(ctx context.Context, subscribeId int64, quantity int64) ([]*RuleWithPrice, error) {
var list []*RuleWithPrice var list []*RuleWithPrice
err := m.db.WithContext(ctx). err := m.db.WithContext(ctx).
Table("promo_rule AS pr"). Table("promo_rule AS pr").
Select("pr.*, sp.promo_price"). Select("pr.*, sp.promo_price").
Joins("JOIN subscribe_promo AS sp ON sp.promo_rule_id = pr.id"). Joins("JOIN subscribe_promo AS sp ON sp.promo_rule_id = pr.id").
Where("sp.subscribe_id = ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeId, true). Where("sp.subscribe_id = ? AND sp.quantity = ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeId, quantity, true).
Where("pr.deleted_at IS NULL"). Where("pr.deleted_at IS NULL").
Order("pr.priority DESC"). Order("pr.priority DESC").
Order("pr.id ASC"). Order("pr.id ASC").
@@ -46,3 +74,155 @@ func (m *defaultPromoModel) InsertUsage(ctx context.Context, data *Usage, tx ...
} }
return db.Model(&Usage{}).Create(data).Error return db.Model(&Usage{}).Create(data).Error
} }
func (m *defaultPromoModel) InsertRule(ctx context.Context, data *Rule) error {
return m.db.WithContext(ctx).Create(data).Error
}
func (m *defaultPromoModel) FindRule(ctx context.Context, id int64) (*Rule, error) {
var resp Rule
if err := m.db.WithContext(ctx).Model(&Rule{}).Where("id = ?", id).First(&resp).Error; err != nil {
return nil, err
}
return &resp, nil
}
func (m *defaultPromoModel) UpdateRule(ctx context.Context, data *Rule) error {
return m.db.WithContext(ctx).Model(&Rule{}).Where("id = ?", data.Id).Updates(map[string]interface{}{
"name": data.Name,
"type": data.Type,
"params": data.Params,
"priority": data.Priority,
"enabled": data.Enabled,
"start_time": data.StartTime,
"end_time": data.EndTime,
}).Error
}
func (m *defaultPromoModel) DeleteRule(ctx context.Context, id int64) error {
return m.db.WithContext(ctx).Delete(&Rule{}, id).Error
}
func (m *defaultPromoModel) QueryRuleList(ctx context.Context, page, size int, ruleType string, enabled *bool, search string) (int64, []*Rule, error) {
if page <= 0 {
page = 1
}
if size <= 0 {
size = 10
}
var total int64
var list []*Rule
db := m.db.WithContext(ctx).Model(&Rule{})
if ruleType != "" {
db = db.Where("type = ?", ruleType)
}
if enabled != nil {
db = db.Where("enabled = ?", *enabled)
}
if search != "" {
db = db.Where("name LIKE ?", "%"+search+"%")
}
if err := db.Count(&total).Error; err != nil {
return 0, nil, err
}
err := db.Order("priority DESC").Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&list).Error
return total, list, err
}
func (m *defaultPromoModel) UpsertPrices(ctx context.Context, ruleId int64, items []*SubscribePromo) error {
return m.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
for _, item := range items {
if item == nil {
continue
}
item.PromoRuleId = ruleId
var existing SubscribePromo
err := tx.Model(&SubscribePromo{}).
Where("subscribe_id = ? AND quantity = ? AND promo_rule_id = ?", item.SubscribeId, item.Quantity, ruleId).
First(&existing).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
if errors.Is(err, gorm.ErrRecordNotFound) {
if err := tx.Create(item).Error; err != nil {
return err
}
continue
}
existing.Quantity = item.Quantity
existing.PromoPrice = item.PromoPrice
if err := tx.Save(&existing).Error; err != nil {
return err
}
}
return nil
})
}
func (m *defaultPromoModel) FindPrice(ctx context.Context, id int64) (*SubscribePromo, error) {
var resp SubscribePromo
if err := m.db.WithContext(ctx).Model(&SubscribePromo{}).Where("id = ?", id).First(&resp).Error; err != nil {
return nil, err
}
return &resp, nil
}
func (m *defaultPromoModel) DeletePrice(ctx context.Context, id int64) error {
return m.db.WithContext(ctx).Delete(&SubscribePromo{}, id).Error
}
func (m *defaultPromoModel) QueryPriceList(ctx context.Context, params PriceFilter) (int64, []*SubscribePromo, error) {
if params.Page <= 0 {
params.Page = 1
}
if params.Size <= 0 {
params.Size = 10
}
var total int64
var list []*SubscribePromo
db := m.db.WithContext(ctx).Model(&SubscribePromo{})
if params.RuleId > 0 {
db = db.Where("promo_rule_id = ?", params.RuleId)
}
if params.SubscribeId > 0 {
db = db.Where("subscribe_id = ?", params.SubscribeId)
}
if err := db.Count(&total).Error; err != nil {
return 0, nil, err
}
err := db.Order("id DESC").Limit(params.Size).Offset((params.Page - 1) * params.Size).Find(&list).Error
return total, list, err
}
func (m *defaultPromoModel) QueryUsageList(ctx context.Context, params UsageFilter) (int64, []*Usage, error) {
if params.Page <= 0 {
params.Page = 1
}
if params.Size <= 0 {
params.Size = 10
}
var total int64
var list []*Usage
db := m.db.WithContext(ctx).Model(&Usage{})
if params.RuleId > 0 {
db = db.Where("promo_rule_id = ?", params.RuleId)
}
if params.UserId > 0 {
db = db.Where("user_id = ?", params.UserId)
}
if params.SubscribeId > 0 {
db = db.Where("subscribe_id = ?", params.SubscribeId)
}
if params.OrderNo != "" {
db = db.Where("order_no = ?", params.OrderNo)
}
if err := db.Count(&total).Error; err != nil {
return 0, nil, err
}
err := db.Order("id DESC").Limit(params.Size).Offset((params.Page - 1) * params.Size).Find(&list).Error
return total, list, err
}
func (m *defaultPromoModel) Transaction(ctx context.Context, fn func(db *gorm.DB) error) error {
return m.db.WithContext(ctx).Transaction(fn)
}
+1
View File
@@ -33,6 +33,7 @@ func (Rule) TableName() string {
type SubscribePromo struct { type SubscribePromo struct {
Id int64 `gorm:"primaryKey"` Id int64 `gorm:"primaryKey"`
SubscribeId int64 `gorm:"type:bigint unsigned;not null;comment:Subscribe ID"` SubscribeId int64 `gorm:"type:bigint unsigned;not null;comment:Subscribe ID"`
Quantity int64 `gorm:"type:int;not null;default:0;comment:购买数量"`
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;comment:Promo Rule ID"` PromoRuleId int64 `gorm:"type:bigint unsigned;not null;comment:Promo Rule ID"`
PromoPrice int64 `gorm:"type:bigint;not null;default:0;comment:Promo Price"` PromoPrice int64 `gorm:"type:bigint;not null;default:0;comment:Promo Price"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"` CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
+21 -19
View File
@@ -23,25 +23,27 @@ const (
) )
type SubscribeDetails struct { type SubscribeDetails struct {
Id int64 `gorm:"primarykey"` Id int64 `gorm:"primarykey"`
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"` UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
User *User `gorm:"foreignKey:UserId;references:Id"` User *User `gorm:"foreignKey:UserId;references:Id"`
OrderId int64 `gorm:"index:idx_order_id;not null;comment:Order ID"` OrderId int64 `gorm:"index:idx_order_id;not null;comment:Order ID"`
SubscribeId int64 `gorm:"index:idx_subscribe_id;not null;comment:Subscription ID"` SubscribeId int64 `gorm:"index:idx_subscribe_id;not null;comment:Subscription ID"`
Subscribe *subscribe.Subscribe `gorm:"foreignKey:SubscribeId;references:Id"` Subscribe *subscribe.Subscribe `gorm:"foreignKey:SubscribeId;references:Id"`
NodeGroupId int64 `gorm:"index:idx_node_group_id;not null;default:0;comment:Node Group ID (single ID)"` NodeGroupId int64 `gorm:"index:idx_node_group_id;not null;default:0;comment:Node Group ID (single ID)"`
StartTime time.Time `gorm:"default:CURRENT_TIMESTAMP(3);not null;comment:Subscription Start Time"` StartTime time.Time `gorm:"default:CURRENT_TIMESTAMP(3);not null;comment:Subscription Start Time"`
ExpireTime time.Time `gorm:"default:NULL;comment:Subscription Expire Time"` ExpireTime time.Time `gorm:"default:NULL;comment:Subscription Expire Time"`
FinishedAt *time.Time `gorm:"default:NULL;comment:Finished Time"` FinishedAt *time.Time `gorm:"default:NULL;comment:Finished Time"`
Traffic int64 `gorm:"default:0;comment:Traffic"` Traffic int64 `gorm:"default:0;comment:Traffic"`
Download int64 `gorm:"default:0;comment:Download Traffic"` Download int64 `gorm:"default:0;comment:Download Traffic"`
Upload int64 `gorm:"default:0;comment:Upload Traffic"` Upload int64 `gorm:"default:0;comment:Upload Traffic"`
Token string `gorm:"index:idx_token;unique;type:varchar(255);default:'';comment:Token"` SpeedLimit int64 `gorm:"default:0;comment:User-level speed limit override (Mbps), 0 uses plan-level"`
UUID string `gorm:"type:varchar(255);unique;index:idx_uuid;default:'';comment:UUID"` TrafficLimit *string `gorm:"type:text;default:null;comment:User-level traffic limit override (JSON), NULL uses plan-level"`
Status uint8 `gorm:"type:tinyint(1);default:0;comment:Subscription Status: 0: Pending 1: Active 2: Finished 3: Expired; 4: Cancelled"` Token string `gorm:"index:idx_token;unique;type:varchar(255);default:'';comment:Token"`
Note string `gorm:"type:varchar(500);default:'';comment:User note for subscription"` UUID string `gorm:"type:varchar(255);unique;index:idx_uuid;default:'';comment:UUID"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"` Status uint8 `gorm:"type:tinyint(1);default:0;comment:Subscription Status: 0: Pending 1: Active 2: Finished 3: Expired; 4: Cancelled"`
UpdatedAt time.Time `gorm:"comment:Update Time"` Note string `gorm:"type:varchar(500);default:'';comment:User note for subscription"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
} }
type SubscribeLogFilterParams struct { type SubscribeLogFilterParams struct {
+1 -1
View File
@@ -67,7 +67,7 @@ func (m *defaultUserModel) FindSingleModeAnchorSubscribe(ctx context.Context, us
var data Subscribe var data Subscribe
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, _ interface{}) error { err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, _ interface{}) error {
return conn.Model(&Subscribe{}). 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("expire_time DESC").
Order("updated_at DESC"). Order("updated_at DESC").
Order("id DESC"). Order("id DESC").
+2 -2
View File
@@ -101,10 +101,10 @@ type Subscribe struct {
Traffic int64 `gorm:"default:0;comment:Traffic"` Traffic int64 `gorm:"default:0;comment:Traffic"`
Download int64 `gorm:"default:0;comment:Download Traffic"` Download int64 `gorm:"default:0;comment:Download Traffic"`
Upload int64 `gorm:"default:0;comment:Upload Traffic"` Upload int64 `gorm:"default:0;comment:Upload Traffic"`
SpeedLimit int64 `gorm:"default:0;comment:User-level speed limit override (Mbps, 0=use plan default)"`
TrafficLimit string `gorm:"type:text;default:null;comment:User-level traffic limit rules override (JSON)"`
ExpiredDownload int64 `gorm:"default:0;comment:Expired period download traffic (bytes)"` ExpiredDownload int64 `gorm:"default:0;comment:Expired period download traffic (bytes)"`
ExpiredUpload int64 `gorm:"default:0;comment:Expired period upload traffic (bytes)"` ExpiredUpload int64 `gorm:"default:0;comment:Expired period upload traffic (bytes)"`
SpeedLimit int64 `gorm:"default:0;comment:User-level speed limit override (Mbps), 0 uses plan-level"`
TrafficLimit *string `gorm:"type:text;default:null;comment:User-level traffic limit override (JSON), NULL uses plan-level"`
Token string `gorm:"index:idx_token;unique;type:varchar(255);default:'';comment:Token"` Token string `gorm:"index:idx_token;unique;type:varchar(255);default:'';comment:Token"`
UUID string `gorm:"type:varchar(255);unique;index:idx_uuid;default:'';comment:UUID"` UUID string `gorm:"type:varchar(255);unique;index:idx_uuid;default:'';comment:UUID"`
Status uint8 `gorm:"type:tinyint(1);default:0;comment:Subscription Status: 0: Pending 1: Active 2: Finished 3: Expired 4: Deducted 5: stopped"` Status uint8 `gorm:"type:tinyint(1);default:0;comment:Subscription Status: 0: Pending 1: Active 2: Finished 3: Expired 4: Deducted 5: stopped"`
+58
View File
@@ -0,0 +1,58 @@
package types
import (
"testing"
"github.com/go-playground/validator/v10"
)
func TestPromoPriceItemsMustNotBeEmpty(t *testing.T) {
validate := validator.New()
req := SetPromoPriceRequest{
PromoRuleId: 1,
Items: []PromoPriceItem{},
}
if err := validate.Struct(req); err == nil {
t.Fatal("expected empty promo price items to fail validation")
}
}
func TestPromoListPageSizeLimit(t *testing.T) {
validate := validator.New()
tests := []struct {
name string
req any
}{
{
name: "rule list",
req: GetPromoRuleListRequest{
Page: 1,
Size: 201,
},
},
{
name: "price list",
req: GetPromoPriceListRequest{
RuleId: 1,
Page: 1,
Size: 201,
},
},
{
name: "usage list",
req: GetPromoUsageListRequest{
Page: 1,
Size: 201,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := validate.Struct(tt.req); err == nil {
t.Fatal("expected page size greater than 200 to fail validation")
}
})
}
}
+291 -125
View File
@@ -3,15 +3,21 @@
package types package types
import "encoding/json"
type ActivateOrderRequest struct { type ActivateOrderRequest struct {
OrderNo string `json:"order_no" validate:"required"` OrderNo string `json:"order_no" validate:"required"`
} }
type RefundOrderRequest struct { type AdminInvitedUser struct {
Id int64 `json:"id" validate:"required"` Id int64 `json:"id"`
Reason string `json:"reason,omitempty" validate:"omitempty,max=500"` Avatar string `json:"avatar"`
Identifier string `json:"identifier"`
Enable bool `json:"enable"`
CreatedAt int64 `json:"created_at"`
OrderCount int64 `json:"order_count"`
HasPurchased bool `json:"has_purchased"`
InviterCommission int64 `json:"inviter_commission"`
InviterGiftDays int64 `json:"inviter_gift_days"`
InviteeGiftDays int64 `json:"invitee_gift_days"`
} }
type Ads struct { type Ads struct {
@@ -126,6 +132,10 @@ type ApplicationVersion struct {
IsDefault bool `json:"is_default"` IsDefault bool `json:"is_default"`
} }
type ApproveWithdrawalRequest struct {
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
}
type AttachAppleTransactionByIdRequest struct { type AttachAppleTransactionByIdRequest struct {
OrderNo string `json:"order_no" validate:"required"` OrderNo string `json:"order_no" validate:"required"`
TransactionId string `json:"transaction_id" validate:"required"` TransactionId string `json:"transaction_id" validate:"required"`
@@ -251,6 +261,10 @@ type BindTelegramResponse struct {
ExpiredAt int64 `json:"expired_at"` ExpiredAt int64 `json:"expired_at"`
} }
type CancelWithdrawalRequest struct {
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
}
type CheckUserRequest struct { type CheckUserRequest struct {
Email string `form:"email" validate:"required"` Email string `form:"email" validate:"required"`
} }
@@ -436,6 +450,16 @@ type CreatePaymentMethodRequest struct {
Enable *bool `json:"enable" validate:"required"` Enable *bool `json:"enable" validate:"required"`
} }
type CreatePromoRuleRequest struct {
Name string `json:"name" validate:"required,max=100"`
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
Params map[string]interface{} `json:"params"`
Priority int64 `json:"priority" validate:"gte=0"`
Enabled *bool `json:"enabled"`
StartTime *int64 `json:"start_time"`
EndTime *int64 `json:"end_time"`
}
type CreateQuotaTaskRequest struct { type CreateQuotaTaskRequest struct {
Subscribers []int64 `json:"subscribers"` Subscribers []int64 `json:"subscribers"`
IsActive *bool `json:"is_active"` IsActive *bool `json:"is_active"`
@@ -619,6 +643,14 @@ type DeletePaymentMethodRequest struct {
Id int64 `json:"id" validate:"required"` Id int64 `json:"id" validate:"required"`
} }
type DeletePromoPriceRequest struct {
Id int64 `uri:"id" validate:"required,gt=0"`
}
type DeletePromoRuleRequest struct {
Id int64 `uri:"id" validate:"required,gt=0"`
}
type DeleteRedemptionCodeRequest struct { type DeleteRedemptionCodeRequest struct {
Id int64 `json:"id" validate:"required"` Id int64 `json:"id" validate:"required"`
} }
@@ -774,14 +806,6 @@ type FamilySummary struct {
UpdatedAt int64 `json:"updated_at"` UpdatedAt int64 `json:"updated_at"`
} }
type FileUploadRequest struct {
BizType string `form:"biz_type" validate:"required"`
}
type FileUploadResponse struct {
Url string `json:"url"`
}
type FileUploadCompleteRequest struct { type FileUploadCompleteRequest struct {
FileId string `json:"file_id" validate:"required"` FileId string `json:"file_id" validate:"required"`
} }
@@ -807,6 +831,14 @@ type FileUploadInitResponse struct {
ExpiredAt int64 `json:"expired_at"` ExpiredAt int64 `json:"expired_at"`
} }
type FileUploadRequest struct {
BizType string `form:"biz_type" validate:"required"`
}
type FileUploadResponse struct {
Url string `json:"url"`
}
type FilterBalanceLogRequest struct { type FilterBalanceLogRequest struct {
FilterLogParams FilterLogParams
UserId int64 `form:"user_id,optional"` UserId int64 `form:"user_id,optional"`
@@ -827,17 +859,6 @@ type FilterCommissionLogResponse struct {
List []CommissionLog `json:"list"` List []CommissionLog `json:"list"`
} }
type FilterOrderRefundLogRequest struct {
FilterLogParams
OrderId int64 `form:"order_id,optional"`
UserId int64 `form:"user_id,optional"`
}
type FilterOrderRefundLogResponse struct {
Total int64 `json:"total"`
List []OrderRefundLog `json:"list"`
}
type FilterEmailLogResponse struct { type FilterEmailLogResponse struct {
Total int64 `json:"total"` Total int64 `json:"total"`
List []MessageLog `json:"list"` List []MessageLog `json:"list"`
@@ -887,6 +908,17 @@ type FilterNodeListResponse struct {
List []Node `json:"list"` List []Node `json:"list"`
} }
type FilterOrderRefundLogRequest struct {
FilterLogParams
OrderId int64 `form:"order_id,optional"`
UserId int64 `form:"user_id,optional"`
}
type FilterOrderRefundLogResponse struct {
Total int64 `json:"total"`
List []OrderRefundLog `json:"list"`
}
type FilterRegisterLogRequest struct { type FilterRegisterLogRequest struct {
FilterLogParams FilterLogParams
UserId int64 `form:"user_id,optional"` UserId int64 `form:"user_id,optional"`
@@ -978,6 +1010,32 @@ type GenerateCaptchaResponse struct {
BlockImage string `json:"block_image,omitempty"` BlockImage string `json:"block_image,omitempty"`
} }
type GetAdminUserInviteListRequest struct {
UserId int64 `form:"user_id" validate:"required"`
Page int `form:"page"`
Size int `form:"size"`
Search string `form:"search"`
Enable *int `form:"enable"`
UserIdSearch int64 `form:"user_id_search"`
}
type GetAdminUserInviteListResponse struct {
Total int64 `json:"total"`
List []AdminInvitedUser `json:"list"`
}
type GetAdminUserInviteStatsRequest struct {
UserId int64 `form:"user_id" validate:"required"`
}
type GetAdminUserInviteStatsResponse struct {
InviteCount int64 `json:"invite_count"`
TotalCommission int64 `json:"total_commission"`
CurrentCommission int64 `json:"current_commission"`
ReferralPercentage uint8 `json:"referral_percentage"`
OnlyFirstPurchase bool `json:"only_first_purchase"`
}
type GetAdsDetailRequest struct { type GetAdsDetailRequest struct {
Id int64 `form:"id"` Id int64 `form:"id"`
} }
@@ -1236,6 +1294,31 @@ type GetGroupHistoryResponse struct {
List []GroupHistory `json:"list"` List []GroupHistory `json:"list"`
} }
type GetInviteManageListRequest struct {
Page int `form:"page"`
Size int `form:"size"`
Search string `form:"search"`
InviterId int64 `form:"inviter_id"`
InviteeId int64 `form:"invitee_id"`
}
type GetInviteManageListResponse struct {
Total int64 `json:"total"`
List []InviteManageRecord `json:"list"`
}
type GetInviteRecordsRequest struct {
Page int `form:"page"`
Size int `form:"size"`
StartTime int64 `form:"start_time"`
EndTime int64 `form:"end_time"`
}
type GetInviteRecordsResponse struct {
Total int64 `json:"total"`
List []InviteRecord `json:"list"`
}
type GetInviteSalesRequest struct { type GetInviteSalesRequest struct {
Page int `form:"page"` Page int `form:"page"`
Size int `form:"size"` Size int `form:"size"`
@@ -1248,6 +1331,32 @@ type GetInviteSalesResponse struct {
List []InvitedUserSale `json:"list"` List []InvitedUserSale `json:"list"`
} }
type GetLogMessageRawRequest struct {
Id int64 `form:"id" validate:"required"`
}
type GetLogMessageRawResponse struct {
Id int64 `json:"id"`
Platform string `json:"platform"`
AppVersion string `json:"app_version"`
OsName string `json:"os_name"`
OsVersion string `json:"os_version"`
DeviceId string `json:"device_id"`
UserId *int64 `json:"user_id"`
SessionId string `json:"session_id"`
Level uint8 `json:"level"`
ErrorCode string `json:"error_code"`
Message string `json:"message"`
Stack string `json:"stack"`
Context interface{} `json:"context"`
ClientIP string `json:"client_ip"`
UserAgent string `json:"user_agent"`
Locale string `json:"locale"`
Digest string `json:"digest"`
OccurredAt int64 `json:"occurred_at"`
CreatedAt int64 `json:"created_at"`
}
type GetLoginLogRequest struct { type GetLoginLogRequest struct {
Page int `form:"page"` Page int `form:"page"`
Size int `form:"size"` Size int `form:"size"`
@@ -1326,6 +1435,49 @@ type GetPreSendEmailCountResponse struct {
Count int64 `json:"count"` Count int64 `json:"count"`
} }
type GetPromoPriceListRequest struct {
Page int64 `form:"page" validate:"required,gt=0"`
Size int64 `form:"size" validate:"required,gt=0,lte=200"`
RuleId int64 `form:"rule_id,omitempty"`
SubscribeId int64 `form:"subscribe_id,omitempty"`
}
type GetPromoPriceListResponse struct {
Total int64 `json:"total"`
List []PromoPrice `json:"list"`
}
type GetPromoRuleDetailRequest struct {
Id int64 `uri:"id" validate:"required,gt=0"`
}
type GetPromoRuleListRequest struct {
Page int64 `form:"page" validate:"required,gt=0"`
Size int64 `form:"size" validate:"required,gt=0,lte=200"`
Type string `form:"type" validate:"omitempty,oneof=new_user inactive_user campaign"`
Enabled *bool `form:"enabled"`
Search string `form:"search,omitempty"`
}
type GetPromoRuleListResponse struct {
Total int64 `json:"total"`
List []PromoRule `json:"list"`
}
type GetPromoUsageListRequest struct {
Page int64 `form:"page" validate:"required,gt=0"`
Size int64 `form:"size" validate:"required,gt=0,lte=200"`
RuleId int64 `form:"rule_id,omitempty"`
UserId int64 `form:"user_id,omitempty"`
SubscribeId int64 `form:"subscribe_id,omitempty"`
OrderNo string `form:"order_no,omitempty"`
}
type GetPromoUsageListResponse struct {
Total int64 `json:"total"`
List []PromoUsage `json:"list"`
}
type GetRedemptionCodeListRequest struct { type GetRedemptionCodeListRequest struct {
Page int64 `form:"page" validate:"required"` Page int64 `form:"page" validate:"required"`
Size int64 `form:"size" validate:"required"` Size int64 `form:"size" validate:"required"`
@@ -1617,6 +1769,19 @@ type GetUserTrafficStatsResponse struct {
TotalTraffic int64 `json:"total_traffic"` TotalTraffic int64 `json:"total_traffic"`
} }
type GetWithdrawalListRequest struct {
Page int `form:"page"`
Size int `form:"size"`
UserId *int64 `form:"user_id,omitempty"`
Status *uint8 `form:"status,omitempty"`
Method *uint8 `form:"method,omitempty"`
}
type GetWithdrawalListResponse struct {
List []WithdrawalLog `json:"list"`
Total int64 `json:"total"`
}
type GiftLog struct { type GiftLog struct {
Type uint16 `json:"type"` Type uint16 `json:"type"`
UserId int64 `json:"user_id"` UserId int64 `json:"user_id"`
@@ -1677,6 +1842,29 @@ type InviteConfig struct {
GiftDays int64 `json:"gift_days"` GiftDays int64 `json:"gift_days"`
} }
type InviteManageRecord struct {
InviterId int64 `json:"inviter_id"`
InviterIdentifier string `json:"inviter_identifier"`
InviteeId int64 `json:"invitee_id"`
InviteeIdentifier string `json:"invitee_identifier"`
InviteeAvatar string `json:"invitee_avatar"`
InviteeEnable bool `json:"invitee_enable"`
InvitedAt int64 `json:"invited_at"`
OrderCount int64 `json:"order_count"`
HasPurchased bool `json:"has_purchased"`
InviterCommission int64 `json:"inviter_commission"`
InviterGiftDays int64 `json:"inviter_gift_days"`
InviteeGiftDays int64 `json:"invitee_gift_days"`
}
type InviteRecord struct {
Role string `json:"role"`
PeerHash string `json:"peer_hash"`
GiftDays int64 `json:"gift_days"`
OrderNo string `json:"order_no"`
CreatedAt int64 `json:"created_at"`
}
type InvitedUserSale struct { type InvitedUserSale struct {
Amount float64 `json:"amount"` Amount float64 `json:"amount"`
UpdatedAt int64 `json:"updated_at"` UpdatedAt int64 `json:"updated_at"`
@@ -1857,8 +2045,6 @@ type Order struct {
Amount int64 `json:"amount"` Amount int64 `json:"amount"`
GiftAmount int64 `json:"gift_amount"` GiftAmount int64 `json:"gift_amount"`
Discount int64 `json:"discount"` Discount int64 `json:"discount"`
PromoRuleId int64 `json:"promo_rule_id"`
PromoDiscount int64 `json:"promo_discount"`
Coupon string `json:"coupon"` Coupon string `json:"coupon"`
CouponDiscount int64 `json:"coupon_discount"` CouponDiscount int64 `json:"coupon_discount"`
Commission int64 `json:"commission,omitempty"` Commission int64 `json:"commission,omitempty"`
@@ -1882,8 +2068,6 @@ type OrderDetail struct {
Amount int64 `json:"amount"` Amount int64 `json:"amount"`
GiftAmount int64 `json:"gift_amount"` GiftAmount int64 `json:"gift_amount"`
Discount int64 `json:"discount"` Discount int64 `json:"discount"`
PromoRuleId int64 `json:"promo_rule_id"`
PromoDiscount int64 `json:"promo_discount"`
Coupon string `json:"coupon"` Coupon string `json:"coupon"`
CouponDiscount int64 `json:"coupon_discount"` CouponDiscount int64 `json:"coupon_discount"`
Commission int64 `json:"commission,omitempty"` Commission int64 `json:"commission,omitempty"`
@@ -2066,6 +2250,45 @@ type PrivacyPolicyConfig struct {
PrivacyPolicy string `json:"privacy_policy"` PrivacyPolicy string `json:"privacy_policy"`
} }
type PromoPrice struct {
Id int64 `json:"id"`
SubscribeId int64 `json:"subscribe_id"`
PromoRuleId int64 `json:"promo_rule_id"`
Quantity int64 `json:"quantity"`
PromoPrice int64 `json:"promo_price"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
type PromoPriceItem struct {
SubscribeId int64 `json:"subscribe_id" validate:"required,gt=0"`
Quantity int64 `json:"quantity" validate:"required,gt=0,lte=1000"`
PromoPrice int64 `json:"promo_price" validate:"required,gt=0"`
}
type PromoRule struct {
Id int64 `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Params map[string]interface{} `json:"params"`
Priority int64 `json:"priority"`
Enabled bool `json:"enabled"`
StartTime *int64 `json:"start_time"`
EndTime *int64 `json:"end_time"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
type PromoUsage struct {
Id int64 `json:"id"`
UserId int64 `json:"user_id"`
PromoRuleId int64 `json:"promo_rule_id"`
SubscribeId int64 `json:"subscribe_id"`
OrderNo string `json:"order_no"`
PromoPrice int64 `json:"promo_price"`
CreatedAt int64 `json:"created_at"`
}
type Protocol struct { type Protocol struct {
Type string `json:"type"` Type string `json:"type"`
Port uint16 `json:"port"` Port uint16 `json:"port"`
@@ -2314,10 +2537,6 @@ type QueryUserSubscribeNodeListResponse struct {
List []UserSubscribeInfo `json:"list"` List []UserSubscribeInfo `json:"list"`
} }
type CancelWithdrawalRequest struct {
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
}
type QueryWithdrawalLogListRequest struct { type QueryWithdrawalLogListRequest struct {
Page int `form:"page"` Page int `form:"page"`
Size int `form:"size"` Size int `form:"size"`
@@ -2328,28 +2547,6 @@ type QueryWithdrawalLogListResponse struct {
Total int64 `json:"total"` Total int64 `json:"total"`
} }
type GetWithdrawalListRequest struct {
Page int `form:"page"`
Size int `form:"size"`
UserId *int64 `form:"user_id,omitempty"`
Status *uint8 `form:"status,omitempty"`
Method *uint8 `form:"method,omitempty"`
}
type GetWithdrawalListResponse struct {
List []WithdrawalLog `json:"list"`
Total int64 `json:"total"`
}
type ApproveWithdrawalRequest struct {
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
}
type RejectWithdrawalRequest struct {
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
Reason string `json:"reason" validate:"required,max=500"`
}
type QuotaTask struct { type QuotaTask struct {
Id int64 `json:"id"` Id int64 `json:"id"`
Subscribers []int64 `json:"subscribers"` Subscribers []int64 `json:"subscribers"`
@@ -2436,6 +2633,11 @@ type RedemptionRecord struct {
CreatedAt int64 `json:"created_at"` CreatedAt int64 `json:"created_at"`
} }
type RefundOrderRequest struct {
Id int64 `json:"id" validate:"required"`
Reason string `json:"reason,omitempty" validate:"omitempty,max=500"`
}
type RegisterConfig struct { type RegisterConfig struct {
StopRegister bool `json:"stop_register"` StopRegister bool `json:"stop_register"`
EnableTrial bool `json:"enable_trial"` EnableTrial bool `json:"enable_trial"`
@@ -2459,6 +2661,11 @@ type RegisterLog struct {
Timestamp int64 `json:"timestamp"` Timestamp int64 `json:"timestamp"`
} }
type RejectWithdrawalRequest struct {
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
Reason string `json:"reason" validate:"required,max=500"`
}
type RemoveFamilyMemberRequest struct { type RemoveFamilyMemberRequest struct {
FamilyId int64 `json:"family_id" validate:"required,gt=0"` FamilyId int64 `json:"family_id" validate:"required,gt=0"`
UserId int64 `json:"user_id" validate:"required,gt=0"` UserId int64 `json:"user_id" validate:"required,gt=0"`
@@ -2717,6 +2924,11 @@ type SetNodeMultiplierRequest struct {
Periods []TimePeriod `json:"periods"` Periods []TimePeriod `json:"periods"`
} }
type SetPromoPriceRequest struct {
PromoRuleId int64 `json:"promo_rule_id" validate:"required,gt=0"`
Items []PromoPriceItem `json:"items" validate:"required,min=1,dive"`
}
type Shadowsocks struct { type Shadowsocks struct {
Method string `json:"method" validate:"required"` Method string `json:"method" validate:"required"`
Port int `json:"port" validate:"required"` Port int `json:"port" validate:"required"`
@@ -2774,13 +2986,6 @@ type StripePayment struct {
PublishableKey string `json:"publishable_key"` PublishableKey string `json:"publishable_key"`
} }
type SubscribePromo struct {
RuleName string `json:"rule_name"`
RuleType string `json:"rule_type"`
PromoPrice int64 `json:"promo_price"`
ExpiresAt int64 `json:"expires_at"`
}
type Subscribe struct { type Subscribe struct {
Id int64 `json:"id"` Id int64 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
@@ -2789,7 +2994,6 @@ type Subscribe struct {
UnitPrice int64 `json:"unit_price"` UnitPrice int64 `json:"unit_price"`
UnitTime string `json:"unit_time"` UnitTime string `json:"unit_time"`
Discount []SubscribeDiscount `json:"discount"` Discount []SubscribeDiscount `json:"discount"`
Promo *SubscribePromo `json:"promo"`
NodeCount int64 `json:"node_count"` NodeCount int64 `json:"node_count"`
Replacement int64 `json:"replacement"` Replacement int64 `json:"replacement"`
Inventory int64 `json:"inventory"` Inventory int64 `json:"inventory"`
@@ -2850,10 +3054,11 @@ type SubscribeConfig struct {
} }
type SubscribeDiscount struct { type SubscribeDiscount struct {
Quantity int64 `json:"quantity"` Quantity int64 `json:"quantity"`
Discount float64 `json:"discount"` Discount float64 `json:"discount"`
NewUserOnly bool `json:"new_user_only"` NewUserOnly bool `json:"new_user_only"`
MapApple string `json:"map_apple"` MapApple string `json:"map_apple"`
Promo *SubscribePromo `json:"promo"`
} }
type SubscribeGroup struct { type SubscribeGroup struct {
@@ -2883,6 +3088,13 @@ type SubscribeLog struct {
Timestamp int64 `json:"timestamp"` Timestamp int64 `json:"timestamp"`
} }
type SubscribePromo struct {
RuleName string `json:"rule_name"`
RuleType string `json:"rule_type"`
PromoPrice int64 `json:"promo_price"`
ExpiresAt int64 `json:"expires_at"`
}
type SubscribeSortRequest struct { type SubscribeSortRequest struct {
Sort []SortItem `json:"sort"` Sort []SortItem `json:"sort"`
} }
@@ -3196,6 +3408,17 @@ type UpdatePaymentMethodRequest struct {
Enable *bool `json:"enable" validate:"required"` Enable *bool `json:"enable" validate:"required"`
} }
type UpdatePromoRuleRequest struct {
Id int64 `uri:"id" validate:"required,gt=0"`
Name string `json:"name" validate:"required,max=100"`
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
Params map[string]interface{} `json:"params"`
Priority int64 `json:"priority" validate:"gte=0"`
Enabled *bool `json:"enabled"`
StartTime *int64 `json:"start_time"`
EndTime *int64 `json:"end_time"`
}
type UpdateRedemptionCodeRequest struct { type UpdateRedemptionCodeRequest struct {
Id int64 `json:"id" validate:"required"` Id int64 `json:"id" validate:"required"`
TotalCount int64 `json:"total_count,omitempty"` TotalCount int64 `json:"total_count,omitempty"`
@@ -3327,7 +3550,7 @@ type UpdateUserSubscribeRequest struct {
ExpiredAt int64 `json:"expired_at"` ExpiredAt int64 `json:"expired_at"`
Upload int64 `json:"upload"` Upload int64 `json:"upload"`
Download int64 `json:"download"` Download int64 `json:"download"`
SpeedLimit *int64 `json:"speed_limit,omitempty"` SpeedLimit *int64 `json:"speed_limit,omitempty" validate:"omitempty,gte=0"`
TrafficLimit *string `json:"traffic_limit,omitempty"` TrafficLimit *string `json:"traffic_limit,omitempty"`
} }
@@ -3354,7 +3577,7 @@ type User struct {
EnableLoginNotify bool `json:"enable_login_notify"` EnableLoginNotify bool `json:"enable_login_notify"`
EnableSubscribeNotify bool `json:"enable_subscribe_notify"` EnableSubscribeNotify bool `json:"enable_subscribe_notify"`
EnableTradeNotify bool `json:"enable_trade_notify"` EnableTradeNotify bool `json:"enable_trade_notify"`
UseStatus bool `json:"use_status"` UseStatus bool `json:"use_status"` // Whether to show the "bind email to get free trial" prompt
AuthMethods []UserAuthMethod `json:"auth_methods"` AuthMethods []UserAuthMethod `json:"auth_methods"`
UserDevices []UserDevice `json:"user_devices"` UserDevices []UserDevice `json:"user_devices"`
Rules []string `json:"rules"` Rules []string `json:"rules"`
@@ -3671,60 +3894,3 @@ type WithdrawalLog struct {
CreatedAt int64 `json:"created_at"` CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"` UpdatedAt int64 `json:"updated_at"`
} }
type GetAdminUserInviteStatsRequest struct {
UserId int64 `form:"user_id" validate:"required"`
}
type GetAdminUserInviteStatsResponse struct {
InviteCount int64 `json:"invite_count"`
TotalCommission int64 `json:"total_commission"`
CurrentCommission int64 `json:"current_commission"`
ReferralPercentage uint8 `json:"referral_percentage"`
OnlyFirstPurchase bool `json:"only_first_purchase"`
}
type GetAdminUserInviteListRequest struct {
UserId int64 `form:"user_id" validate:"required"`
Page int `form:"page"`
Size int `form:"size"`
}
type AdminInvitedUser struct {
Id int64 `json:"id"`
Avatar string `json:"avatar"`
Identifier string `json:"identifier"`
Enable bool `json:"enable"`
CreatedAt int64 `json:"created_at"`
}
type GetAdminUserInviteListResponse struct {
Total int64 `json:"total"`
List []AdminInvitedUser `json:"list"`
}
type GetLogMessageRawRequest struct {
Id int64 `form:"id" validate:"required"`
}
type GetLogMessageRawResponse struct {
Id int64 `json:"id"`
Platform string `json:"platform"`
AppVersion string `json:"app_version"`
OsName string `json:"os_name"`
OsVersion string `json:"os_version"`
DeviceId string `json:"device_id"`
UserId *int64 `json:"user_id"`
SessionId string `json:"session_id"`
Level uint8 `json:"level"`
ErrorCode string `json:"error_code"`
Message string `json:"message"`
Stack string `json:"stack"`
Context json.RawMessage `json:"context"`
ClientIP string `json:"client_ip"`
UserAgent string `json:"user_agent"`
Locale string `json:"locale"`
Digest string `json:"digest"`
OccurredAt int64 `json:"occurred_at"`
CreatedAt int64 `json:"created_at"`
}
+3
View File
@@ -3680,6 +3680,9 @@
"discount": { "discount": {
"type": "number", "type": "number",
"format": "double" "format": "double"
},
"promo": {
"$ref": "#/definitions/SubscribePromo"
} }
}, },
"title": "SubscribeDiscount", "title": "SubscribeDiscount",
+11
View File
@@ -3,15 +3,26 @@ package hash
import ( import (
"crypto/md5" "crypto/md5"
"fmt" "fmt"
"hash/fnv"
"strconv"
"github.com/spaolacci/murmur3" "github.com/spaolacci/murmur3"
) )
const invitePeerHashSalt = "ppanel_invite_" + "sales_v1"
// Hash returns the hash value of data. // Hash returns the hash value of data.
func Hash(data []byte) uint64 { func Hash(data []byte) uint64 {
return murmur3.Sum64(data) return murmur3.Sum64(data)
} }
func InvitePeerHash(userId int64) string {
h := fnv.New64a()
_, _ = h.Write([]byte(invitePeerHashSalt))
_, _ = h.Write([]byte(strconv.FormatInt(userId, 10)))
return fmt.Sprintf("%010d", h.Sum64()%10000000000)
}
// Md5 returns the md5 bytes of data. // Md5 returns the md5 bytes of data.
func Md5(data []byte) []byte { func Md5(data []byte) []byte {
digest := md5.New() digest := md5.New()
+22 -7
View File
@@ -2,6 +2,7 @@ package epay
import ( import (
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
@@ -88,28 +89,42 @@ func (c *Client) VerifySign(params map[string]string) bool {
return c.createSign(params) == params["sign"] 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{ client := http.Client{
Timeout: 5 * time.Second, Timeout: 5 * time.Second,
} }
resp, err := client.Get(c.Url + "/api.php" + "?act=order" + "&pid=" + c.Pid + "&key=" + c.Key + "&out_trade_no=" + orderNo) resp, err := client.Get(c.Url + "/api.php" + "?act=order" + "&pid=" + c.Pid + "&key=" + c.Key + "&out_trade_no=" + orderNo)
if err != nil { if err != nil {
logger.Error("[Epay] QueryOrderStatus error", logger.Field("orderNo", orderNo), logger.Field("error", err.Error())) 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() 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) value, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
logger.Error("[Epay] QueryOrderStatus error", logger.Field("orderNo", orderNo), logger.Field("error", err.Error())) 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 var response queryOrderStatusResponse
err = json.Unmarshal(value, &response) if err = json.Unmarshal(value, &response); err != nil {
if err != nil {
logger.Error("[Epay] QueryOrderStatus error", logger.Field("orderNo", orderNo), logger.Field("error", err.Error())) 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 // StructToMap converts a struct to map[string]string
+6
View File
@@ -37,6 +37,7 @@ func init() {
TelegramNotBound: "Telegram not bound ", TelegramNotBound: "Telegram not bound ",
UserNotBindOauth: "User not bind oauth method", UserNotBindOauth: "User not bind oauth method",
InviteCodeError: "Invite code error", InviteCodeError: "Invite code error",
UserCommissionNotEnough: "佣金余额不足",
RegisterIPLimit: "Too many registrations", RegisterIPLimit: "Too many registrations",
EmailBindError: "Email already bound", EmailBindError: "Email already bound",
UserBindInviteCodeExist: "Invite code already bound", UserBindInviteCodeExist: "Invite code already bound",
@@ -82,6 +83,8 @@ func init() {
// System error // System error
DebugModeError: "Debug mode is enabled", DebugModeError: "Debug mode is enabled",
SendSmsError: "短信发送失败",
GetAuthenticatorError: "Unsupported login method", GetAuthenticatorError: "Unsupported login method",
AuthenticatorNotSupportedError: "The authenticator does not support this method", AuthenticatorNotSupportedError: "The authenticator does not support this method",
@@ -94,15 +97,18 @@ func init() {
TelephoneExist: "Telephone already exists", TelephoneExist: "Telephone already exists",
DeviceExist: "device exists", DeviceExist: "device exists",
PasswordIsEmpty: "password is empty", PasswordIsEmpty: "password is empty",
AreaCodeIsEmpty: "国家区号不能为空",
TelephoneError: "telephone number error", TelephoneError: "telephone number error",
DeviceNotExist: "Device does not exist", DeviceNotExist: "Device does not exist",
UseridNotMatch: "Userid not match", UseridNotMatch: "Userid not match",
DeviceBindLimitExceeded: "设备绑定数量已达上限",
// Order error // Order error
OrderNotExist: "Order does not exist", OrderNotExist: "Order does not exist",
PaymentMethodNotFound: "Payment method not found", PaymentMethodNotFound: "Payment method not found",
OrderStatusError: "Order status error", OrderStatusError: "Order status error",
InsufficientOfPeriod: "Insufficient number of period", InsufficientOfPeriod: "Insufficient number of period",
ExistAvailableTraffic: "存在可用流量",
OrderAlreadyRefunded: "Order already refunded", OrderAlreadyRefunded: "Order already refunded",
OrderRefundNoSubscription: "Refund target subscription not found", OrderRefundNoSubscription: "Refund target subscription not found",
OrderRefundCommissionMismatch: "Refund commission source 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)
}
}
+2
View File
@@ -31,6 +31,8 @@ import (
"apis/admin/marketing.api" "apis/admin/marketing.api"
"apis/admin/application.api" "apis/admin/application.api"
"apis/admin/group.api" "apis/admin/group.api"
"apis/admin/invite.api"
"apis/admin/promo.api"
"apis/public/user.api" "apis/public/user.api"
"apis/public/subscribe.api" "apis/public/subscribe.api"
"apis/public/redemption.api" "apis/public/redemption.api"
+37 -12
View File
@@ -149,7 +149,20 @@ func (l *ActivateOrderLogic) ProcessTask(ctx context.Context, task *asynq.Task)
return err return err
} }
l.recordPromoUsage(ctx, orderInfo) if err = l.recordPromoUsage(ctx, orderInfo); err != nil {
if releaseErr := l.releaseClaim(ctx, orderInfo.OrderNo); releaseErr != nil {
logger.WithContext(ctx).Error("[ActivateOrderLogic] releaseClaim also failed, stuck recovery will handle",
logger.Field("order_no", orderInfo.OrderNo),
logger.Field("release_error", releaseErr.Error()),
)
}
logger.WithContext(ctx).Error("[ActivateOrderLogic] 促销使用记录写入失败,将重试",
logger.Field("order_no", orderInfo.OrderNo),
logger.Field("promo_rule_id", orderInfo.PromoRuleId),
logger.Field("error", err.Error()),
)
return err
}
l.finalizeCouponAndOrder(ctx, orderInfo) l.finalizeCouponAndOrder(ctx, orderInfo)
commonLogic.SubscriptionTraceInfo(logger.WithContext(ctx), commonLogic.SubscriptionTraceFlowOrder, "activation_finished", commonLogic.SubscriptionTraceInfo(logger.WithContext(ctx), commonLogic.SubscriptionTraceFlowOrder, "activation_finished",
@@ -159,9 +172,9 @@ func (l *ActivateOrderLogic) ProcessTask(ctx context.Context, task *asynq.Task)
return nil return nil
} }
func (l *ActivateOrderLogic) recordPromoUsage(ctx context.Context, orderInfo *order.Order) { func (l *ActivateOrderLogic) recordPromoUsage(ctx context.Context, orderInfo *order.Order) error {
if orderInfo == nil || orderInfo.PromoRuleId <= 0 || orderInfo.Quantity <= 0 || orderInfo.SubscribeId <= 0 || orderInfo.OrderNo == "" { if orderInfo == nil || orderInfo.PromoRuleId <= 0 || orderInfo.Quantity <= 0 || orderInfo.SubscribeId <= 0 || orderInfo.OrderNo == "" {
return return nil
} }
promoPrice := int64(0) promoPrice := int64(0)
@@ -169,10 +182,10 @@ func (l *ActivateOrderLogic) recordPromoUsage(ctx context.Context, orderInfo *or
promoPrice = (orderInfo.Price - orderInfo.PromoDiscount) / orderInfo.Quantity promoPrice = (orderInfo.Price - orderInfo.PromoDiscount) / orderInfo.Quantity
} }
if promoPrice <= 0 { if promoPrice <= 0 {
return return nil
} }
err := l.svc.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error { return l.svc.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var count int64 var count int64
if e := tx.Model(&promo.Usage{}).Where("order_no = ?", orderInfo.OrderNo).Count(&count).Error; e != nil { if e := tx.Model(&promo.Usage{}).Where("order_no = ?", orderInfo.OrderNo).Count(&count).Error; e != nil {
return e return e
@@ -188,13 +201,6 @@ func (l *ActivateOrderLogic) recordPromoUsage(ctx context.Context, orderInfo *or
PromoPrice: promoPrice, PromoPrice: promoPrice,
}, tx) }, tx)
}) })
if err != nil {
logger.WithContext(ctx).Error("Insert promo usage failed",
logger.Field("error", err.Error()),
logger.Field("order_no", orderInfo.OrderNo),
logger.Field("promo_rule_id", orderInfo.PromoRuleId),
)
}
} }
// parsePayload unMarshals the task payload into a structured format // parsePayload unMarshals the task payload into a structured format
@@ -266,6 +272,25 @@ func (l *ActivateOrderLogic) claimAndGetOrder(ctx context.Context, orderNo strin
} }
func (l *ActivateOrderLogic) releaseClaim(ctx context.Context, orderNo string) error { 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). if err := l.svc.DB.WithContext(ctx).
Model(&order.Order{}). Model(&order.Order{}).
Where("order_no = ? AND status = ?", orderNo, OrderStatusClaimed). Where("order_no = ? AND status = ?", orderNo, OrderStatusClaimed).
@@ -6,6 +6,7 @@ import (
"time" "time"
"github.com/hibiken/asynq" "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/model/order"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/logger" "github.com/perfect-panel/server/pkg/logger"
@@ -54,6 +55,25 @@ func (l *StuckOrderRecoveryLogic) ProcessTask(ctx context.Context, _ *asynq.Task
for i := range stuckOrders { for i := range stuckOrders {
o := &stuckOrders[i] 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). result := l.svc.DB.WithContext(ctx).
Model(&order.Order{}). Model(&order.Order{}).
Where("order_no = ? AND status = ?", o.OrderNo, OrderStatusClaimed). Where("order_no = ? AND status = ?", o.OrderNo, OrderStatusClaimed).
+29 -22
View File
@@ -1183,15 +1183,15 @@
] ]
} }
}, },
"/v1/public/user/invite_sales": { "/v1/public/user/invite_records": {
"get": { "get": {
"summary": "Get Invite Sales", "summary": "Get Invite Records",
"operationId": "GetInviteSales", "operationId": "GetInviteRecords",
"responses": { "responses": {
"200": { "200": {
"description": "A successful response.", "description": "A successful response.",
"schema": { "schema": {
"$ref": "#/definitions/GetInviteSalesResponse" "$ref": "#/definitions/GetInviteRecordsResponse"
} }
} }
}, },
@@ -3166,7 +3166,7 @@
"connection_records" "connection_records"
] ]
}, },
"GetInviteSalesRequest": { "GetInviteRecordsRequest": {
"type": "object", "type": "object",
"properties": { "properties": {
"page": { "page": {
@@ -3186,7 +3186,7 @@
"format": "int64" "format": "int64"
} }
}, },
"title": "GetInviteSalesRequest", "title": "GetInviteRecordsRequest",
"required": [ "required": [
"page", "page",
"size", "size",
@@ -3194,7 +3194,7 @@
"end_time" "end_time"
] ]
}, },
"GetInviteSalesResponse": { "GetInviteRecordsResponse": {
"type": "object", "type": "object",
"properties": { "properties": {
"total": { "total": {
@@ -3204,11 +3204,11 @@
"list": { "list": {
"type": "array", "type": "array",
"items": { "items": {
"$ref": "#/definitions/InvitedUserSale" "$ref": "#/definitions/InviteRecord"
} }
} }
}, },
"title": "GetInviteSalesResponse", "title": "GetInviteRecordsResponse",
"required": [ "required": [
"total", "total",
"list" "list"
@@ -3558,30 +3558,34 @@
"gift_days" "gift_days"
] ]
}, },
"InvitedUserSale": { "InviteRecord": {
"type": "object", "type": "object",
"properties": { "properties": {
"amount": { "role": {
"type": "number", "type": "string"
"format": "double"
}, },
"updated_at": { "peer_hash": {
"type": "string"
},
"gift_days": {
"type": "integer", "type": "integer",
"format": "int64" "format": "int64"
}, },
"user_hash": { "order_no": {
"type": "string" "type": "string"
}, },
"product_name": { "created_at": {
"type": "string" "type": "integer",
"format": "int64"
} }
}, },
"title": "InvitedUserSale", "title": "InviteRecord",
"required": [ "required": [
"amount", "role",
"updated_at", "peer_hash",
"user_hash", "gift_days",
"product_name" "order_no",
"created_at"
] ]
}, },
"MessageLog": { "MessageLog": {
@@ -5900,6 +5904,9 @@
"discount": { "discount": {
"type": "number", "type": "number",
"format": "double" "format": "double"
},
"promo": {
"$ref": "#/definitions/SubscribePromo"
} }
}, },
"title": "SubscribeDiscount", "title": "SubscribeDiscount",