Compare commits

...

74 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
shanshanzhong147 c90edac630 修复(#73): 修正促销迁移表结构 — subscribe_promo 加 quantity + 索引优化
Build docker and publish / build (20.15.1) (push) Failing after 8m28s
Build docker and publish / build (20.15.1) (pull_request) Successful in 7m59s
- subscribe_promo 新增 quantity 列,唯一键改为 (subscribe_id, quantity, promo_rule_id)
- promo_rule 索引合并为 idx_enabled_priority_deleted (enabled, deleted_at, priority DESC)

Co-authored-by: multica-agent <github@multica.ai>
2026-05-27 01:10:31 -07:00
shanshanzhong147 b9192db042 feat: 文件上传接口直接返回完整 URL + 提现 content 改为非必填
Build docker and publish / build (20.15.1) (push) Failing after 8m29s
Build docker and publish / build (20.15.1) (pull_request) Successful in 8m3s
- FileUploadResponse / FileUploadCompleteResponse 精简为只返回 url
- S3Store.BuildObjectURL 拼接完整访问地址
- 提现 method=0 时 content 不再参与必填校验
- 新增用户端 API 接口文档
2026-05-27 00:57:21 -07:00
shanshanzhong147 48e507783e 新功能(#77): 套餐列表返回促销信息
Build docker and publish / build (20.15.1) (push) Failing after 8m34s
Build docker and publish / build (20.15.1) (pull_request) Successful in 8m4s
- 新增 SubscribePromo 响应结构,套餐列表每项追加 promo 字段
- 新增 promo.go 促销候选规则查询与资格评估逻辑
- 重构 authMiddleware 提取 authenticateRequest,新增 OptionalAuthMiddleware
- /v1/public/subscribe/list 改为可选鉴权,未登录仅展示 campaign 类型促销
- /node/list、/group/list 保持强制鉴权不变
- 每个规格只返回最高优先级命中的规则,promo_price 为单价,expires_at 为秒级时间戳
- 新增单测覆盖 campaign/new_user 命中、活动窗口判定等场景

Co-authored-by: multica-agent <github@multica.ai>
2026-05-26 22:40:58 -07:00
shanshanzhong147 d6efcb8e0b 修复(#83): 修复脚本目录全量测试构建失败
Build docker and publish / build (20.15.1) (push) Has been cancelled
Build docker and publish / build (20.15.1) (pull_request) Successful in 8m27s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-26 22:34:19 -07:00
shanshanzhong147 d2f9289338 新功能(#76): 促销系统下单流程集成
Build docker and publish / build (20.15.1) (push) Has been cancelled
Build docker and publish / build (20.15.1) (pull_request) Successful in 8m28s
- 新增促销规则/规格促销价/使用记录模型与幂等迁移
- EvaluatePromo 支持 new_user/inactive_user/campaign 规则判定
- purchase/preCreate 接入促销判定:命中促销时跳过百分比折扣
- activate 激活后按 order_no 幂等写入 promo_usage
- 订单模型和响应结构新增 promo_rule_id、promo_discount 字段

Co-authored-by: multica-agent <github@multica.ai>
2026-05-26 22:18:44 -07:00
shanshanzhong147 92e303aaa7 修复(#80): 修复wrapf非常量格式串vet阻断
Build docker and publish / build (20.15.1) (push) Has been cancelled
Build docker and publish / build (20.15.1) (pull_request) Successful in 8m39s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-26 22:18:26 -07:00
shanshanzhong147 54328b197d 新功能(#78): 预算订单 API 返回 promo_discount 字段
Build docker and publish / build (20.15.1) (push) Has been cancelled
Build docker and publish / build (20.15.1) (pull_request) Successful in 7m54s
PreOrderResponse 新增 promo_discount 字段,未接入促销时默认返回 0。
促销命中逻辑待 HIF-76 接入后生效。

Co-authored-by: multica-agent <github@multica.ai>
2026-05-26 22:13:40 -07:00
shanshanzhong147 5ebfe0a981 新功能(#65): 添加用户订阅限速数据层字段
Build docker and publish / build (20.15.1) (push) Failing after 8m30s
Build docker and publish / build (20.15.1) (pull_request) Successful in 7m58s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-26 11:23:57 -07:00
shanshanzhong147 22d9773f1b x
Build docker and publish / build (20.15.1) (pull_request) Has been cancelled
Build docker and publish / build (20.15.1) (push) Failing after 8m56s
2026-05-26 10:02:38 -07:00
shanshanzhong147 d89798f001 merge: pull internal/internal with secrets for TG notifications
Build docker and publish / build (20.15.1) (push) Failing after 8m22s
Resolved conflict in .gitea/workflows/docker.yml by keeping
secrets-based TG_BOT_TOKEN and TG_CHAT_ID instead of hardcoded values.
2026-05-26 09:25:13 -07:00
shanshanzhong147 81c3059892 x 2026-05-26 09:14:59 -07:00
shanshanzhong147 f9fa4756e9 新功能(#41): 提现优化 — 收款方式选择 + 取消提现 + 收款码上传
Build docker and publish / build (20.15.1) (push) Failing after 8m37s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-26 08:36:25 -07:00
shanshanzhong147 27f1203282 修复(#49): 修复清空备注时数据丢失 — RefererId 改为指针类型
Co-authored-by: multica-agent <github@multica.ai>
2026-05-26 08:35:45 -07:00
shanshanzhong147 f7f890c990 配置(#47,#51): CI/CD 安全加固 + TG 通知限制 + 部署健康检查
Build docker and publish / build (20.15.1) (push) Failing after 8m35s
- TG Bot Token/Chat ID 改用 secrets,移除硬编码
- PR 事件只构建不推镜像、不部署、不发通知
- 部署后增加健康检查,失败自动回滚
- 增加环境标签区分生产/测试/其他

Co-authored-by: multica-agent <github@multica.ai>
2026-05-26 08:07:08 -07:00
shanshanzhong147 8b4e7561f4 修复: scripts 编译冲突 + order 统计 is_new 字段修正
- scripts/ 下两个独立脚本移到各自子目录,消除 package main 冲突
- model/order/model.go 统计查询 type→is_new 字段修正(7处)

Co-authored-by: multica-agent <github@multica.ai>
2026-05-26 08:06:50 -07:00
shanshanzhong147 a6e9e2bdb8 配置(#53): 固定 Docker Compose 基础设施镜像版本,移除 latest 标签
Build docker and publish / build (20.15.1) (push) Failing after 7m45s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-25 21:56:01 -07:00
shanshanzhong147 b798f520c8 fix: add zero-value guard for RefererId to prevent clearing inviter on remark update
Build docker and publish / build (20.15.1) (push) Failing after 8m39s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-25 20:04:22 -07:00
shanshanzhong147 bae234fe15 Merge remote-tracking branch 'remotes/origin/agent/agent/bfdd0bdd' into merge-to-internal
Build docker and publish / build (20.15.1) (push) Failing after 8m14s
2026-05-25 18:17:24 -07:00
shanshanzhong147 79ab4460bc feat: add GET /v1/admin/log/message/detail endpoint
Adds a temporary admin endpoint to query log_message by ID,
returning the full record including context (JSON) and digest
fields that the existing /error_message/detail endpoint omits.

Co-authored-by: multica-agent <github@multica.ai>
2026-05-25 12:18:27 -07:00
shanshanzhong147 0169a16ada fix: make refund migration compatible with legacy schemas
Build docker and publish / build (20.15.1) (push) Failing after 8m17s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-25 11:07:06 -07:00
shanshanzhong147 b6b5bccde6 fix: use withdrawals table consistently
Build docker and publish / build (20.15.1) (push) Failing after 8m20s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-25 10:43:24 -07:00
shanshanzhong147 eba256bdc9 merge: sync internal with main
Build docker and publish / build (20.15.1) (push) Failing after 8m22s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-25 10:32:06 -07:00
shanshanzhong147 72f2b94263 fix: restore missing migration files
Build docker and publish / build (20.15.1) (push) Failing after 8m16s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-25 10:20:46 -07:00
shanshanzhong147 bb67ebcb79 chore: rename activation context migration to 02151
Build docker and publish / build (20.15.1) (push) Failing after 8m27s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-25 02:21:37 -07:00
shanshanzhong147 0bd7560b64 fix: P1 activation path hardening - Bug 4-9
Bug 4: resolveRenewalActivationSubscription - add fallback by user_id+subscribe_id
  with SELECT FOR UPDATE when token lookup fails

Bug 5: appleIAPNotifyLogic - return error on product ID mapping failure instead of
  silently dropping the notification

Bug 6: NewPurchase fallback query - wrap in transaction with SELECT FOR UPDATE to
  prevent concurrent duplicate subscription creation

Bug 7: appleIAPNotifyLogic - fix UserId=0 by reverse-lookup from original purchase
  order; create renewal audit order record for DID_RENEW/SUBSCRIBED notifications

Bug 8: UpdateOrderStatus - pre-delete cache before DB write (double-delete) to
  close TOCTOU window between DB update and cache invalidation

Bug 9: validateNewUserOnlyEligibilityAtActivation - add Redis distributed lock on
  user_id to serialise concurrent new-user-only order activations

Co-authored-by: multica-agent <github@multica.ai>
2026-05-25 02:18:19 -07:00
shanshanzhong147 a0f2d8a7b8 fix: persist guest/redemption activation context to DB to survive Redis TTL expiry (Bug 1 + Bug 10)
- Add `activation_context` TEXT column to `order` table (migration 02150)
- purchaseLogic: write TemporaryOrderInfo JSON to order.ActivationContext in the same
  insert transaction; Redis write is now best-effort (non-fatal)
- redeemCodeLogic: write redemption {type, redemption_code_id, unit_time, quantity} JSON
  to order.ActivationContext at order creation; Redis write is now best-effort (non-fatal)
- getTempOrderInfo: on Redis miss, fall back to order.ActivationContext from DB;
  logs CRITICAL and returns error if both are missing (old orders with no DB record)
- RedemptionActivate: on Redis miss, fall back to order.ActivationContext from DB;
  same CRITICAL log path for legacy orders

Co-authored-by: multica-agent <github@multica.ai>
2026-05-25 02:18:19 -07:00
shanshanzhong147 30221232c9 fix: 修复订单状态机 claim 机制的三个 Bug 并增加 stuck 订单恢复
- 将 OrderStatusClaimed 从 4 改为 6,消除与 OrderStatusFailed 的值冲突
- finalizeCouponAndOrder 改用直接 DB 更新(WHERE status=6→SET status=5),
  绕过 UpdateOrderStatus 的 status<target 守卫,同时用 model.Update 刷新缓存
- releaseClaim 返回 error,调用处检查并记录日志;releaseClaim 失败由 stuck
  recovery 定时任务兜底
- claimAndGetOrder 对 status=claimed 返回可重试错误而非静默跳过;
  ProcessTask 区分 "stuck in claimed" 与 "非 paid 跳过" 两种场景
- 新增 StuckOrderRecoveryLogic:每 10 分钟扫描超时 claimed 订单,
  重置 status=paid 并重新入队 ForthwithActivateOrder,确保不依赖
  asynq 原始重试(可能已超 maxRetry)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
2026-05-25 02:18:19 -07:00
shanshanzhong147 80751eb8ef fix: move withdrawal commission deduction from application to approval
Build docker and publish / build (20.15.1) (push) Failing after 8m28s
- commissionWithdrawLogic: remove upfront commission deduction;
  balance check now includes sum of all pending withdrawals to prevent
  double-spending; transaction only creates the withdrawal record (status=0)
- approveWithdrawal: add FOR UPDATE lock on user row, balance check before
  deducting, atomic commission decrement and commission log inside one
  transaction; clear user cache after commit
- rejectWithdrawal: remove commission refund and log — commission was never
  deducted on application under the new flow
- add migration 02150: refund commission for existing status=0 withdrawals
  that were deducted under the old logic; includes rollback script

Co-authored-by: multica-agent <github@multica.ai>
2026-05-24 20:26:42 -07:00
shanshanzhong147 3bbce5ce84 fix: 修复退款与仪表盘订单统计口径
Build docker and publish / build (20.15.1) (push) Failing after 8m16s
Co-authored-by: multica-agent <github@multica.ai>
2026-05-24 17:50:29 -07:00
shanshanzhong147 1726a584fa feat: add admin order refund flow
Co-authored-by: multica-agent <github@multica.ai>
2026-05-24 17:50:23 -07:00
shanshanzhong147 fd522b6c71 path
Build docker and publish / build (20.15.1) (push) Successful in 8m56s
2026-05-19 19:35:44 -07:00
shanshanzhong147 a1184ef5ed feat: add userinfo bind-email trial use status
Build docker and publish / build (20.15.1) (push) Successful in 9m2s
2026-05-18 03:02:35 -07:00
shanshanzhong147 7c6efe9dfe x
Build docker and publish / build (20.15.1) (push) Failing after 9m23s
2026-05-16 23:58:53 -07:00
shanshanzhong147 c0ece054a0 x
Build docker and publish / build (20.15.1) (push) Failing after 9m44s
2026-05-16 04:13:05 -07:00
shanshanzhong147 0d57450283 x
Build docker and publish / build (20.15.1) (push) Has been cancelled
2026-05-15 09:53:15 -07:00
shanshanzhong147 f2033fd4b9 feat: add rustfs direct upload endpoint
Build docker and publish / build (20.15.1) (push) Failing after 8m36s
2026-05-14 23:33:50 -07:00
shanshanzhong147 3284cb45f0 ci: trigger internal branch workflow
Build docker and publish / build (20.15.1) (push) Failing after 8m36s
2026-05-14 05:58:05 -07:00
shanshanzhong147 6041bc3419 x
Build docker and publish / build (20.15.1) (push) Has been cancelled
2026-05-14 05:50:44 -07:00
shanshanzhong147 4581a6fc17 ci: use ssh key for main deploy
Build docker and publish / build (20.15.1) (push) Failing after 8m20s
2026-05-13 11:43:01 -07:00
shanshanzhong147 2bdce44e12 merge: add direct s3 upload flow
Build docker and publish / build (20.15.1) (push) Failing after 8m49s
2026-05-13 11:24:31 -07:00
shanshanzhong147 4fa9fcd232 feat: add direct s3 upload flow 2026-05-13 11:24:13 -07:00
shanshanzhong147 f6911965dc chore: snapshot current aws standby and backup tooling work 2026-05-13 10:59:03 -07:00
shanshanzhong147 c4b2ebf7e1 x
Build docker and publish / build (20.15.1) (push) Has been cancelled
2026-05-10 10:41:50 -07:00
shanshanzhong147 f946504cb8 x 2026-05-08 06:19:59 -07:00
232 changed files with 18744 additions and 13136 deletions
@@ -0,0 +1,25 @@
package main
import (
"fmt"
"github.com/perfect-panel/server/internal/config"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/conf"
)
func main() {
var c config.Config
conf.MustLoad("/private/tmp/ppanel-local-upload.yaml", &c)
ctx := svc.NewServiceContext(c)
const key = "cache:auth:method:device"
before, _ := ctx.Redis.Get(ctx.DB.Statement.Context, key).Result()
fmt.Printf("cache before=%q\n", before)
m, err := ctx.AuthModel.FindOneByMethod(ctx.DB.Statement.Context, "device")
fmt.Printf("model err=%v enabled_nil=%v", err, m == nil || m.Enabled == nil)
if m != nil && m.Enabled != nil { fmt.Printf(" enabled=%v", *m.Enabled) }
if m != nil { fmt.Printf(" config=%s", m.Config) }
fmt.Println()
after, _ := ctx.Redis.Get(ctx.DB.Statement.Context, key).Result()
fmt.Printf("cache after=%q\n", after)
}
+23
View File
@@ -0,0 +1,23 @@
package main
import (
"fmt"
initpkg "github.com/perfect-panel/server/initialize"
"github.com/perfect-panel/server/internal/config"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/conf"
)
func main() {
var c config.Config
conf.MustLoad("/private/tmp/ppanel-local-upload.yaml", &c)
ctx := svc.NewServiceContext(c)
method, err := ctx.AuthModel.FindOneByMethod(ctx.DB.Statement.Context, "device")
if err != nil {
panic(err)
}
fmt.Printf("db auth_method.enabled=%v config=%s\n", *method.Enabled, method.Config)
initpkg.Device(ctx)
fmt.Printf("ctx.Config.Device.Enable=%v SecuritySecret=%q EnableSecurity=%v\n", ctx.Config.Device.Enable, ctx.Config.Device.SecuritySecret, ctx.Config.Device.EnableSecurity)
}
+36
View File
@@ -0,0 +1,36 @@
package main
import (
"fmt"
"github.com/perfect-panel/server/internal/config"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/conf"
)
type row struct {
ID int64
Method string
Enabled int
Config string
}
func main() {
var c config.Config
conf.MustLoad("/private/tmp/ppanel-local-upload.yaml", &c)
ctx := svc.NewServiceContext(c)
var rows []row
if err := ctx.DB.Raw("SELECT id, method, enabled, config FROM auth_method WHERE method = ?", "device").Scan(&rows).Error; err != nil {
panic(err)
}
fmt.Printf("raw rows: %+v\n", rows)
m, err := ctx.AuthModel.FindOneByMethod(ctx.DB.Statement.Context, "device")
fmt.Printf("model err=%v\n", err)
if err == nil && m != nil && m.Enabled != nil {
fmt.Printf("model row: id=%d method=%s enabled=%v config=%s\n", m.Id, m.Method, *m.Enabled, m.Config)
} else {
fmt.Printf("model row nil or no enabled ptr: %#v\n", m)
}
}
+28
View File
@@ -0,0 +1,28 @@
package main
import (
"fmt"
"github.com/perfect-panel/server/internal/config"
authmodel "github.com/perfect-panel/server/internal/model/auth"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/conf"
)
func main() {
var c config.Config
conf.MustLoad("/private/tmp/ppanel-local-upload.yaml", &c)
ctx := svc.NewServiceContext(c)
var a1 authmodel.Auth
err1 := ctx.DB.Model(&authmodel.Auth{}).Where("method = ?", "device").First(&a1).Error
fmt.Printf("gorm direct err=%v enabled_nil=%v", err1, a1.Enabled == nil)
if a1.Enabled != nil { fmt.Printf(" enabled=%v", *a1.Enabled) }
fmt.Printf(" config=%s\n", a1.Config)
var a2 authmodel.Auth
err2 := ctx.DB.Table("auth_method").Where("method = ?", "device").First(&a2).Error
fmt.Printf("gorm table err=%v enabled_nil=%v", err2, a2.Enabled == nil)
if a2.Enabled != nil { fmt.Printf(" enabled=%v", *a2.Enabled) }
fmt.Printf(" config=%s\n", a2.Config)
}
+9 -2
View File
@@ -7,5 +7,12 @@ MYSQL_ROOT_PASSWORD=CHANGE_ME_TO_STRONG_PASSWORD
# Grafana 管理员密码
GRAFANA_PASSWORD=CHANGE_ME_TO_STRONG_PASSWORD
# PPanel Server 镜像标签(留空使用 latest
PPANEL_SERVER_TAG=latest
# PPanel Server 镜像标签(由 CI/CD 传入不可变 tag,如 git SHA
PPANEL_SERVER_TAG=CHANGE_ME_TO_GIT_SHA
# AWS 区域(香港)
AWS_REGION=ap-east-1
# Grafana 公开域名(如需反代)
GRAFANA_DOMAIN=logs-new.hifast.biz
GRAFANA_ROOT_URL=https://logs-new.hifast.biz
+160 -59
View File
@@ -14,14 +14,15 @@ on:
env:
# Docker镜像仓库
REPO: ${{ vars.REPO || 'registry.kxsw.us/vpn-server' }}
# SSH连接信息 (根据分支自动选择)
# SSH连接信息 (根据分支自动选择服务器和用户)
SSH_HOST: ${{ github.ref_name == 'main' && vars.SSH_HOST || vars.DEV_SSH_HOST }}
SSH_PORT: ${{ vars.SSH_PORT }}
SSH_USER: ${{ vars.SSH_USER }}
SSH_PASSWORD: ${{ github.ref_name == 'main' && vars.SSH_PASSWORD || vars.DEV_SSH_PASSWORD }}
SSH_USER: ${{ github.ref_name == 'main' && 'ubuntu' || 'root' }}
# SSH私钥(Gitea Secret 名称:AWS
SSH_KEY: ${{ secrets.AWS }}
# TG通知
TG_BOT_TOKEN: 8114337882:AAHkEx03HSu7RxN4IHBJJEnsK9aPPzNLIk0
TG_CHAT_ID: "-4940243803"
TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN }}
TG_CHAT_ID: ${{ secrets.TG_CHAT_ID }}
# Go构建变量
SERVICE: vpn
SERVICE_STYLE: vpn
@@ -42,27 +43,30 @@ jobs:
# 步骤1: 下载代码
- name: 📥 下载代码
uses: actions/checkout@v4
# 步骤2: 设置动态环境变量
- name: ⚙️ 设置动态环境变量
run: |
if [ "${{ github.ref_name }}" = "main" ]; then
echo "DOCKER_TAG_SUFFIX=latest" >> $GITHUB_ENV
echo "CONTAINER_NAME=ppanel-server" >> $GITHUB_ENV
echo "DEPLOY_PATH=/root/hifast" >> $GITHUB_ENV
echo "DEPLOY_PATH=/opt/ppanel" >> $GITHUB_ENV
echo "DEPLOY_ENV_LABEL=🚀 服务已成功部署到生产环境" >> $GITHUB_ENV
echo "为 main 分支设置生产环境变量"
elif [ "${{ github.ref_name }}" = "internal" ]; then
echo "DOCKER_TAG_SUFFIX=internal" >> $GITHUB_ENV
echo "CONTAINER_NAME=ppanel-server-internal" >> $GITHUB_ENV
echo "DEPLOY_PATH=/root/hifast" >> $GITHUB_ENV
echo "DEPLOY_PATH=/root/bindbox" >> $GITHUB_ENV
echo "DEPLOY_ENV_LABEL=🧪 服务已成功部署到测试环境" >> $GITHUB_ENV
echo "为 internal 分支设置开发环境变量"
else
echo "DOCKER_TAG_SUFFIX=${{ github.ref_name }}" >> $GITHUB_ENV
echo "CONTAINER_NAME=ppanel-server-${{ github.ref_name }}" >> $GITHUB_ENV
echo "DEPLOY_PATH=/root/vpn_server_other" >> $GITHUB_ENV
echo "DEPLOY_ENV_LABEL=🔧 服务已成功部署到其他环境" >> $GITHUB_ENV
echo "为其他分支 (${{ github.ref_name }}) 设置环境变量"
fi
# 步骤3: 安装系统工具 (curl, jq) 并升级 Docker CLI 到 1.44+
- name: 🔧 安装系统工具并升级 Docker CLI
run: |
@@ -110,127 +114,224 @@ jobs:
docker --version || true
docker version || true
echo "客户端 API 版本:" $(docker version --format '{{.Client.APIVersion}}')
# 步骤4: 构建并发布到镜像仓库
- name: 📤 构建并发布到镜像仓库
# 步骤4: 构建镜像
- name: 🏗️ 构建镜像
run: |
echo "开始构建并推送镜像..."
echo "开始构建镜像..."
echo "仓库: ${{ env.REPO }}"
echo "版本标签: ${{ env.VERSION }}"
echo "分支标签: ${{ env.DOCKER_TAG_SUFFIX }}"
# 构建镜像,同时打上版本和分支两个标签
BUILD_TAG_ARGS="-t ${{ env.REPO }}:${{ env.VERSION }}"
if [ "${{ github.event_name }}" = "push" ]; then
BUILD_TAG_ARGS="$BUILD_TAG_ARGS -t ${{ env.REPO }}:${{ env.DOCKER_TAG_SUFFIX }}"
else
echo "PR事件仅构建版本标签,不推送镜像、不部署"
fi
docker build -f Dockerfile \
--platform linux/amd64 \
--build-arg TARGETARCH=amd64 \
--build-arg VERSION=${{ env.VERSION }} \
--build-arg BUILDTIME=${{ env.BUILDTIME }} \
-t ${{ env.REPO }}:${{ env.VERSION }} \
-t ${{ env.REPO }}:${{ env.DOCKER_TAG_SUFFIX }} \
$BUILD_TAG_ARGS \
.
echo "镜像构建完成"
# 步骤5: 发布到镜像仓库
- name: 📤 发布到镜像仓库
if: github.event_name == 'push'
run: |
echo "开始推送镜像..."
echo "推送版本标签镜像: ${{ env.REPO }}:${{ env.VERSION }}"
docker push ${{ env.REPO }}:${{ env.VERSION }}
echo "推送分支标签镜像: ${{ env.REPO }}:${{ env.DOCKER_TAG_SUFFIX }}"
docker push ${{ env.REPO }}:${{ env.DOCKER_TAG_SUFFIX }}
echo "镜像推送完成"
# 调试: 打印 SSH 连接信息
- name: 🔍 调试 - 打印 SSH 连接信息
# 步骤6: 调试 - 打印部署目标(不输出敏感信息
- name: 🔍 调试 - 打印部署目标
if: github.event_name == 'push'
run: |
echo "========== SSH 连接信息调试 =========="
echo "========== 部署目标调试 =========="
echo "当前分支: ${{ github.ref_name }}"
echo "SSH_HOST: ${{ env.SSH_HOST }}"
echo "SSH_PORT: ${{ env.SSH_PORT }}"
echo "SSH_USER: ${{ env.SSH_USER }}"
echo "SSH_PASSWORD 长度: ${#SSH_PASSWORD}"
echo "SSH_PASSWORD 前3位: $(echo "$SSH_PASSWORD" | cut -c1-3)***"
echo "SSH_PASSWORD 完整值: ${{ env.SSH_PASSWORD }}"
echo "SSH认证方式: 私钥 (AWS)"
echo "DEPLOY_PATH: ${{ env.DEPLOY_PATH }}"
echo "====================================="
# 步骤5: 传输配置文件
# 步骤7: 传输配置文件
- name: 📂 传输配置文件
if: github.event_name == 'push'
uses: appleboy/scp-action@v0.1.7
with:
host: ${{ env.SSH_HOST }}
username: ${{ env.SSH_USER }}
password: ${{ env.SSH_PASSWORD }}
key: ${{ env.SSH_KEY }}
port: ${{ env.SSH_PORT }}
source: "docker-compose.cloud.yml"
target: "${{ env.DEPLOY_PATH }}/"
target: "/tmp/ppanel-deploy/"
# 步骤6: 连接服务器更新并启动
# 步骤8: 连接服务器更新、健康检查并按需回滚
- name: 🚀 连接服务器更新并启动
if: github.event_name == 'push'
uses: appleboy/ssh-action@v1.0.3
with:
host: ${{ env.SSH_HOST }}
username: ${{ env.SSH_USER }}
password: ${{ env.SSH_PASSWORD }}
key: ${{ env.SSH_KEY }}
port: ${{ env.SSH_PORT }}
timeout: 300s
command_timeout: 600s
script: |
set -e
echo "连接服务器成功,开始部署..."
echo "部署目录: ${{ env.DEPLOY_PATH }}"
echo "部署标签: ${{ env.DOCKER_TAG_SUFFIX }}"
echo "登录用户: ${{ env.SSH_USER }}"
HEALTHCHECK_URL="http://127.0.0.1:8080/v1/common/heartbeat"
NEW_TAG="${{ env.DOCKER_TAG_SUFFIX }}"
ROLLBACK_TAG="rollback-${{ env.VERSION }}"
SUDO=""
if [ "${{ github.ref_name }}" = "main" ]; then
SUDO="sudo"
fi
docker_cmd() {
if [ -n "$SUDO" ]; then
sudo docker "$@"
else
docker "$@"
fi
}
compose_with_tag() {
tag="$1"
shift
if [ -n "$SUDO" ]; then
sudo env PPANEL_SERVER_TAG="$tag" docker-compose -f docker-compose.cloud.yml "$@"
else
PPANEL_SERVER_TAG="$tag" docker-compose -f docker-compose.cloud.yml "$@"
fi
}
write_previous_tag() {
if [ -n "$SUDO" ]; then
printf '%s\n' "${PREVIOUS_IMAGE_TAG:-}" | sudo tee .previous-ppanel-image-tag >/dev/null
else
printf '%s\n' "${PREVIOUS_IMAGE_TAG:-}" > .previous-ppanel-image-tag
fi
}
health_check() {
attempt=1
while [ "$attempt" -le 3 ]; do
if curl -sf "$HEALTHCHECK_URL"; then
echo
return 0
fi
echo "健康检查第 ${attempt}/3 次失败,10s 后重试..."
attempt=$((attempt + 1))
sleep 10
done
return 1
}
if [ "${{ github.ref_name }}" = "main" ]; then
sudo mkdir -p ${{ env.DEPLOY_PATH }}
sudo cp /tmp/ppanel-deploy/docker-compose.cloud.yml ${{ env.DEPLOY_PATH }}/docker-compose.cloud.yml
else
mkdir -p ${{ env.DEPLOY_PATH }}
cp /tmp/ppanel-deploy/docker-compose.cloud.yml ${{ env.DEPLOY_PATH }}/docker-compose.cloud.yml
fi
# 进入部署目录
cd ${{ env.DEPLOY_PATH }}
# 创建/更新环境变量文件
# echo "PPANEL_SERVER_TAG=${{ env.DOCKER_TAG_SUFFIX }}" > .env
# 拉取最新镜像
echo "📥 拉取镜像..."
docker-compose -f docker-compose.cloud.yml pull ppanel-server
# 启动服务
PREVIOUS_IMAGE_TAG="$(docker_cmd inspect --format '{{.Config.Image}}' ppanel-server 2>/dev/null || true)"
PREVIOUS_IMAGE_ID="$(docker_cmd inspect --format '{{.Image}}' ppanel-server 2>/dev/null || true)"
echo "上一版本镜像tag: ${PREVIOUS_IMAGE_TAG:-未发现}"
echo "上一版本镜像ID: ${PREVIOUS_IMAGE_ID:-未发现}"
write_previous_tag
echo "📥 拉取镜像: ${{ env.REPO }}:${NEW_TAG}"
compose_with_tag "$NEW_TAG" pull ppanel-server
echo "🚀 启动服务..."
docker-compose -f docker-compose.cloud.yml up -d ppanel-server
# 清理未使用的镜像
docker image prune -f || true
echo "✅ 部署命令执行完成"
# 步骤6: TG通知 (成功)
compose_with_tag "$NEW_TAG" up -d ppanel-server
echo "🩺 部署后健康检查: ${HEALTHCHECK_URL}"
if health_check; then
docker_cmd image prune -f || true
echo "✅ 部署后健康检查通过"
echo "✅ 部署命令执行完成"
exit 0
fi
echo "❌ 部署后健康检查连续 3 次失败,开始回滚..."
if [ -n "$PREVIOUS_IMAGE_ID" ]; then
docker_cmd tag "$PREVIOUS_IMAGE_ID" "${{ env.REPO }}:${ROLLBACK_TAG}"
echo "回滚镜像tag: ${{ env.REPO }}:${ROLLBACK_TAG}"
compose_with_tag "$ROLLBACK_TAG" up -d ppanel-server
echo "🩺 回滚后健康检查: ${HEALTHCHECK_URL}"
if health_check; then
echo "✅ 回滚后健康检查通过"
else
echo "❌ 回滚后健康检查仍失败"
fi
else
echo "未找到上一版本镜像ID,无法自动回滚"
fi
docker_cmd image prune -f || true
exit 1
# 步骤9: TG通知 (成功)
- name: 📱 发送成功通知到Telegram
if: success()
if: success() && github.event_name == 'push'
uses: appleboy/telegram-action@master
with:
token: ${{ env.TG_BOT_TOKEN }}
to: ${{ env.TG_CHAT_ID }}
message: |
✅ 部署成功!
📦 项目: ${{ github.repository }}
🌿 分支: ${{ github.ref_name }}
📝 提交: ${{ github.sha }}
👤 提交者: ${{ github.actor }}
🕐 时间: ${{ github.event.head_commit.timestamp }}
🚀 服务已成功部署到生产环境
${{ env.DEPLOY_ENV_LABEL }}
🩺 健康检查: 通过 (http://127.0.0.1:8080/v1/common/heartbeat)
parse_mode: Markdown
# 步骤5: TG通知 (失败)
# 步骤10: TG通知 (失败)
- name: 📱 发送失败通知到Telegram
if: failure()
if: failure() && github.event_name == 'push'
uses: appleboy/telegram-action@master
with:
token: ${{ env.TG_BOT_TOKEN }}
to: ${{ env.TG_CHAT_ID }}
message: |
❌ 部署失败!
📦 项目: ${{ github.repository }}
🌿 分支: ${{ github.ref_name }}
📝 提交: ${{ github.sha }}
👤 提交者: ${{ github.actor }}
🕐 时间: ${{ github.event.head_commit.timestamp }}
🩺 健康检查: 失败或未完成;若新版本健康检查连续 3 次失败,已自动尝试回滚并重新检查
⚠️ 请检查构建日志获取详细信息
parse_mode: Markdown
-9026
View File
File diff suppressed because it is too large Load Diff
+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)
}
+61
View File
@@ -149,6 +149,35 @@ type (
Total int64 `json:"total"`
List []CommissionLog `json:"list"`
}
OrderRefundLog {
OrderId int64 `json:"order_id"`
OrderNo string `json:"order_no"`
OperatorUserId int64 `json:"operator_user_id"`
OperatorAuthIdentifier string `json:"operator_auth_identifier,omitempty"`
TargetUserId int64 `json:"target_user_id"`
UserSubscribeId int64 `json:"user_subscribe_id"`
RefererUserId int64 `json:"referer_user_id,omitempty"`
CommissionAmount int64 `json:"commission_amount"`
Reason string `json:"reason,omitempty"`
OrderStatusBefore uint8 `json:"order_status_before"`
OrderStatusAfter uint8 `json:"order_status_after"`
SubscribeStatusBefore uint8 `json:"subscribe_status_before"`
SubscribeStatusAfter uint8 `json:"subscribe_status_after"`
SubscribeExpireBefore int64 `json:"subscribe_expire_before"`
SubscribeExpireAfter int64 `json:"subscribe_expire_after"`
CommissionBefore int64 `json:"commission_before"`
CommissionAfter int64 `json:"commission_after"`
Timestamp int64 `json:"timestamp"`
}
FilterOrderRefundLogRequest {
FilterLogParams
OrderId int64 `form:"order_id,optional"`
UserId int64 `form:"user_id,optional"`
}
FilterOrderRefundLogResponse {
Total int64 `json:"total"`
List []OrderRefundLog `json:"list"`
}
GiftLog {
Type uint16 `json:"type"`
userId int64 `json:"user_id"`
@@ -239,6 +268,30 @@ type (
OccurredAt int64 `json:"occurred_at"`
CreatedAt int64 `json:"created_at"`
}
GetLogMessageRawRequest {
Id int64 `form:"id" validate:"required"`
}
GetLogMessageRawResponse {
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"`
}
)
@server (
@@ -291,6 +344,10 @@ service ppanel {
@handler FilterCommissionLog
get /commission/list (FilterCommissionLogRequest) returns (FilterCommissionLogResponse)
@doc "Filter order refund log"
@handler FilterOrderRefundLog
get /order/refund/list (FilterOrderRefundLogRequest) returns (FilterOrderRefundLogResponse)
@doc "Filter gift log"
@handler FilterGiftLog
get /gift/list (FilterGiftLogRequest) returns (FilterGiftLogResponse)
@@ -314,5 +371,9 @@ service ppanel {
@doc "Get error log message detail"
@handler GetErrorLogMessageDetail
get /error_message/detail returns (GetErrorLogMessageDetailResponse)
@doc "Get log message raw detail (temporary)"
@handler GetLogMessageRaw
get /message/detail (GetLogMessageRawRequest) returns (GetLogMessageRawResponse)
}
+8
View File
@@ -33,6 +33,10 @@ type (
PaymentId int64 `json:"payment_id,omitempty"`
TradeNo string `json:"trade_no,omitempty"`
}
RefundOrderRequest {
Id int64 `json:"id" validate:"required"`
Reason string `json:"reason,omitempty" validate:"omitempty,max=500"`
}
ActivateOrderRequest {
OrderNo string `json:"order_no" validate:"required"`
}
@@ -68,6 +72,10 @@ service ppanel {
@handler UpdateOrderStatus
put /status (UpdateOrderStatusRequest)
@doc "Refund order"
@handler RefundOrder
post /refund (RefundOrderRequest)
@doc "Manually activate order"
@handler ActivateOrder
post /activate (ActivateOrderRequest)
+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"`
DeviceLimit int64 `json:"device_limit"`
Quota int64 `json:"quota"`
NewUserOnly *bool `json:"new_user_only"`
Nodes []int64 `json:"nodes"`
NodeTags []string `json:"node_tags"`
NodeGroupIds []int64 `json:"node_group_ids,omitempty"`
@@ -74,6 +75,7 @@ type (
SpeedLimit int64 `json:"speed_limit"`
DeviceLimit int64 `json:"device_limit"`
Quota int64 `json:"quota"`
NewUserOnly *bool `json:"new_user_only"`
Nodes []int64 `json:"nodes"`
NodeTags []string `json:"node_tags"`
NodeGroupIds []int64 `json:"node_group_ids,omitempty"`
@@ -175,4 +177,3 @@ service ppanel {
@handler ResetAllSubscribeToken
post /reset_all_token returns (ResetAllSubscribeTokenResponse)
}
+102 -48
View File
@@ -23,10 +23,12 @@ type (
SubscribeId *int64 `form:"subscribe_id,omitempty"`
UserSubscribeId *int64 `form:"user_subscribe_id,omitempty"`
ShortCode string `form:"short_code,omitempty"`
DeviceId *int64 `form:"device_id,omitempty"`
FamilyJoined *bool `form:"family_joined,omitempty"`
FamilyStatus string `form:"family_status,omitempty"`
FamilyOwnerUserId *int64 `form:"family_owner_user_id,omitempty"`
FamilyId *int64 `form:"family_id,omitempty"`
SortOrder string `form:"sort_order,omitempty"`
}
// GetUserListResponse
GetUserListResponse {
@@ -38,20 +40,20 @@ type (
Id int64 `form:"id" validate:"required"`
}
UpdateUserBasiceInfoRequest {
UserId int64 `json:"user_id" validate:"required"`
Password string `json:"password"`
Avatar string `json:"avatar"`
Balance int64 `json:"balance"`
Commission int64 `json:"commission"`
ReferralPercentage uint8 `json:"referral_percentage"`
OnlyFirstPurchase *bool `json:"only_first_purchase"`
GiftAmount int64 `json:"gift_amount"`
Telegram int64 `json:"telegram"`
ReferCode string `json:"refer_code"`
RefererId int64 `json:"referer_id"`
Enable *bool `json:"enable"`
IsAdmin *bool `json:"is_admin"`
Remark string `json:"remark"`
UserId int64 `json:"user_id" validate:"required"`
Password string `json:"password"`
Avatar string `json:"avatar"`
Balance *int64 `json:"balance"`
Commission *int64 `json:"commission"`
ReferralPercentage uint8 `json:"referral_percentage"`
OnlyFirstPurchase *bool `json:"only_first_purchase"`
GiftAmount *int64 `json:"gift_amount"`
Telegram int64 `json:"telegram"`
ReferCode string `json:"refer_code"`
RefererId *int64 `json:"referer_id"`
Enable *bool `json:"enable"`
IsAdmin *bool `json:"is_admin"`
Remark *string `json:"remark"`
}
UpdateUserNotifySettingRequest {
UserId int64 `json:"user_id" validate:"required"`
@@ -76,29 +78,6 @@ type (
GiftAmount int64 `json:"gift_amount"`
IsAdmin bool `json:"is_admin"`
}
UserSubscribeDetail {
Id int64 `json:"id"`
UserId int64 `json:"user_id"`
User User `json:"user"`
OrderId int64 `json:"order_id"`
SubscribeId int64 `json:"subscribe_id"`
Subscribe Subscribe `json:"subscribe"`
NodeGroupId int64 `json:"node_group_id"`
GroupLocked bool `json:"group_locked"`
StartTime int64 `json:"start_time"`
ExpireTime int64 `json:"expire_time"`
ResetTime int64 `json:"reset_time"`
Traffic int64 `json:"traffic"`
Download int64 `json:"download"`
Upload int64 `json:"upload"`
Token string `json:"token"`
Status uint8 `json:"status"`
EffectiveSpeed int64 `json:"effective_speed"`
IsThrottled bool `json:"is_throttled"`
ThrottleRule string `json:"throttle_rule,omitempty"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
BatchDeleteUserRequest {
Ids []int64 `json:"ids" validate:"required"`
}
@@ -158,18 +137,22 @@ type (
Total int64 `json:"total"`
}
CreateUserSubscribeRequest {
UserId int64 `json:"user_id"`
ExpiredAt int64 `json:"expired_at"`
Traffic int64 `json:"traffic"`
SubscribeId int64 `json:"subscribe_id"`
UserId int64 `json:"user_id"`
ExpiredAt int64 `json:"expired_at"`
Traffic int64 `json:"traffic"`
SubscribeId int64 `json:"subscribe_id"`
SpeedLimit int64 `json:"speed_limit,optional"`
TrafficLimit string `json:"traffic_limit,optional"`
}
UpdateUserSubscribeRequest {
UserSubscribeId int64 `json:"user_subscribe_id"`
SubscribeId int64 `json:"subscribe_id"`
Traffic int64 `json:"traffic"`
ExpiredAt int64 `json:"expired_at"`
Upload int64 `json:"upload"`
Download int64 `json:"download"`
UserSubscribeId int64 `json:"user_subscribe_id"`
SubscribeId int64 `json:"subscribe_id"`
Traffic int64 `json:"traffic"`
ExpiredAt int64 `json:"expired_at"`
Upload int64 `json:"upload"`
Download int64 `json:"download"`
SpeedLimit *int64 `json:"speed_limit,omitempty" validate:"omitempty,gte=0"`
TrafficLimit *string `json:"traffic_limit,omitempty"`
}
GetUserLoginLogsRequest {
Page int `form:"page"`
@@ -230,6 +213,58 @@ type (
FamilyId int64 `json:"family_id" validate:"required,gt=0"`
Reason string `json:"reason,omitempty"`
}
GetWithdrawalListRequest {
Page int `form:"page"`
Size int `form:"size"`
UserId *int64 `form:"user_id,omitempty"`
Status *uint8 `form:"status,omitempty"`
Method *uint8 `form:"method,omitempty"`
}
GetWithdrawalListResponse {
List []WithdrawalLog `json:"list"`
Total int64 `json:"total"`
}
ApproveWithdrawalRequest {
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
}
RejectWithdrawalRequest {
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
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 (
@@ -370,5 +405,24 @@ service ppanel {
@doc "Dissolve family"
@handler DissolveFamily
put /family/dissolve (DissolveFamilyRequest)
}
@doc "Get withdrawal list"
@handler GetWithdrawalList
get /withdrawal/list (GetWithdrawalListRequest) returns (GetWithdrawalListResponse)
@doc "Approve withdrawal"
@handler ApproveWithdrawal
post /withdrawal/approve (ApproveWithdrawalRequest)
@doc "Reject withdrawal"
@handler RejectWithdrawal
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 (
prefix: v1/server
group: server
group: node/server
middleware: ServerMiddleware
)
service ppanel {
@@ -138,11 +138,10 @@ service ppanel {
@server (
prefix: v2/server
group: server
group: node/server
)
service ppanel {
@doc "Get Server Protocol Config"
@handler QueryServerProtocolConfig
get /:server_id (QueryServerConfigRequest) returns (QueryServerConfigResponse)
}
+65
View File
@@ -0,0 +1,65 @@
syntax = "v1"
info (
title: "File API"
desc: "API for ppanel file upload"
author: "Codex"
email: "codex@openai.com"
version: "0.0.1"
)
import "../types.api"
type (
FileUploadRequest {
BizType string `form:"biz_type" validate:"required"`
}
FileUploadResponse {
Url string `json:"url"`
}
FileUploadInitRequest {
BizType string `json:"biz_type" validate:"required"`
FileName string `json:"file_name" validate:"required"`
ContentType string `json:"content_type" validate:"required"`
Size int64 `json:"size" validate:"required"`
Sha256 string `json:"sha256"`
}
FileUploadInitResponse {
FileId string `json:"file_id"`
ObjectKey string `json:"object_key"`
UploadURL string `json:"upload_url"`
Method string `json:"method"`
Headers map[string]string `json:"headers"`
ExpiredAt int64 `json:"expired_at"`
}
FileUploadCompleteRequest {
FileId string `json:"file_id" validate:"required"`
}
FileUploadCompleteResponse {
Url string `json:"url"`
}
)
@server (
prefix: v1/public/file
group: public/file
middleware: AuthMiddleware,DeviceMiddleware
)
service ppanel {
@doc "Upload file to RustFS"
@handler FileUpload
post /upload (FileUploadRequest) returns (FileUploadResponse)
@doc "Init file upload"
@handler FileUploadInit
post /upload/init (FileUploadInitRequest) returns (FileUploadInitResponse)
@doc "Complete file upload"
@handler FileUploadComplete
post /upload/complete (FileUploadCompleteRequest) returns (FileUploadCompleteResponse)
}
+36 -3
View File
@@ -109,8 +109,11 @@ type (
Rules []string `json:"rules" validate:"required"`
}
CommissionWithdrawRequest {
Amount int64 `json:"amount"`
Content string `json:"content"`
Amount int64 `json:"amount"`
Content string `json:"content"`
Method uint8 `json:"method" validate:"oneof=0 1 2 3"`
Account string `json:"account,omitempty"`
QrCodeUrl string `json:"qr_code_url,omitempty"`
}
WithdrawalLog {
Id int64 `json:"id"`
@@ -119,9 +122,15 @@ type (
Content string `json:"content"`
Status uint8 `json:"status"`
Reason string `json:"reason,omitempty"`
Method uint8 `json:"method"`
Account string `json:"account"`
QrCodeUrl string `json:"qr_code_url"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
CancelWithdrawalRequest {
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
}
QueryWithdrawalLogListRequest {
Page int `form:"page"`
Size int `form:"size"`
@@ -192,6 +201,23 @@ type (
GrowthRate string `json:"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 {
Page int `form:"page"`
Size int `form:"size"`
@@ -352,6 +378,10 @@ service ppanel {
@handler CommissionWithdraw
post /commission_withdraw (CommissionWithdrawRequest) returns (WithdrawalLog)
@doc "Cancel pending withdrawal"
@handler CancelWithdrawal
post /withdrawal_cancel (CancelWithdrawalRequest) returns (WithdrawalLog)
@doc "Query Withdrawal Log"
@handler QueryWithdrawalLog
get /withdrawal_log (QueryWithdrawalLogListRequest) returns (QueryWithdrawalLogListResponse)
@@ -384,6 +414,10 @@ service ppanel {
@handler GetAgentRealtime
get /agent_realtime (GetAgentRealtimeRequest) returns (GetAgentRealtimeResponse)
@doc "Get Invite Records"
@handler GetInviteRecords
get /invite_records (GetInviteRecordsRequest) returns (GetInviteRecordsResponse)
@doc "Get Invite Sales"
@handler GetInviteSales
get /invite_sales (GetInviteSalesRequest) returns (GetInviteSalesResponse)
@@ -411,4 +445,3 @@ service ppanel {
@handler DeviceWsConnect
get /device_ws_connect
}
+104 -22
View File
@@ -27,6 +27,7 @@ type (
EnableLoginNotify bool `json:"enable_login_notify"`
EnableSubscribeNotify bool `json:"enable_subscribe_notify"`
EnableTradeNotify bool `json:"enable_trade_notify"`
UseStatus bool `json:"use_status"` // Whether to show the "bind email to get free trial" prompt
AuthMethods []UserAuthMethod `json:"auth_methods"`
UserDevices []UserDevice `json:"user_devices"`
Rules []string `json:"rules"`
@@ -159,24 +160,26 @@ type (
OnlyRealDevice bool `json:"only_real_device"`
}
RegisterConfig {
StopRegister bool `json:"stop_register"`
EnableTrial bool `json:"enable_trial"`
TrialSubscribe int64 `json:"trial_subscribe"`
TrialTime int64 `json:"trial_time"`
TrialTimeUnit string `json:"trial_time_unit"`
EnableIpRegisterLimit bool `json:"enable_ip_register_limit"`
IpRegisterLimit int64 `json:"ip_register_limit"`
IpRegisterLimitDuration int64 `json:"ip_register_limit_duration"`
DeviceLimit int64 `json:"device_limit"`
StopRegister bool `json:"stop_register"`
EnableTrial bool `json:"enable_trial"`
EnableTrialEmailWhitelist bool `json:"enable_trial_email_whitelist"`
TrialSubscribe int64 `json:"trial_subscribe"`
TrialTime int64 `json:"trial_time"`
TrialTimeUnit string `json:"trial_time_unit"`
TrialEmailDomainWhitelist string `json:"trial_email_domain_whitelist"`
EnableIpRegisterLimit bool `json:"enable_ip_register_limit"`
IpRegisterLimit int64 `json:"ip_register_limit"`
IpRegisterLimitDuration int64 `json:"ip_register_limit_duration"`
DeviceLimit int64 `json:"device_limit"`
}
VerifyConfig {
CaptchaType string `json:"captcha_type"` // local or turnstile
TurnstileSiteKey string `json:"turnstile_site_key"`
TurnstileSecret string `json:"turnstile_secret"`
EnableUserLoginCaptcha bool `json:"enable_user_login_captcha"` // User login captcha
EnableUserRegisterCaptcha bool `json:"enable_user_register_captcha"` // User register captcha
EnableAdminLoginCaptcha bool `json:"enable_admin_login_captcha"` // Admin login captcha
EnableUserResetPasswordCaptcha bool `json:"enable_user_reset_password_captcha"` // User reset password captcha
CaptchaType string `json:"captcha_type"` // local or turnstile
TurnstileSiteKey string `json:"turnstile_site_key"`
TurnstileSecret string `json:"turnstile_secret"`
EnableUserLoginCaptcha bool `json:"enable_user_login_captcha"` // User login captcha
EnableUserRegisterCaptcha bool `json:"enable_user_register_captcha"` // User register captcha
EnableAdminLoginCaptcha bool `json:"enable_admin_login_captcha"` // Admin login captcha
EnableUserResetPasswordCaptcha bool `json:"enable_user_reset_password_captcha"` // User reset password captcha
}
NodeConfig {
NodeSecret string `json:"node_secret"`
@@ -225,9 +228,52 @@ type (
CurrencySymbol string `json:"currency_symbol"`
}
SubscribeDiscount {
Quantity int64 `json:"quantity"`
Discount float64 `json:"discount"`
MapApple string `json:"map_apple"`
Quantity int64 `json:"quantity"`
Discount float64 `json:"discount"`
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 {
RuleName string `json:"rule_name"`
RuleType string `json:"rule_type"`
PromoPrice int64 `json:"promo_price"`
ExpiresAt int64 `json:"expires_at"`
}
TrafficLimit {
StatType string `json:"stat_type"`
@@ -250,6 +296,7 @@ type (
SpeedLimit int64 `json:"speed_limit"`
DeviceLimit int64 `json:"device_limit"`
Quota int64 `json:"quota"`
NewUserOnly bool `json:"new_user_only"`
Nodes []int64 `json:"nodes"`
NodeTags []string `json:"node_tags"`
NodeGroupIds []int64 `json:"node_group_ids,omitempty"`
@@ -426,6 +473,7 @@ type (
FeeAmount int64 `json:"fee_amount"`
TradeNo string `json:"trade_no"`
Status uint8 `json:"status"`
StatusName string `json:"status_name,omitempty"`
SubscribeId int64 `json:"subscribe_id"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
@@ -448,6 +496,7 @@ type (
FeeAmount int64 `json:"fee_amount"`
TradeNo string `json:"trade_no"`
Status uint8 `json:"status"`
StatusName string `json:"status_name,omitempty"`
SubscribeId int64 `json:"subscribe_id"`
Subscribe Subscribe `json:"subscribe"`
CreatedAt int64 `json:"created_at"`
@@ -512,10 +561,13 @@ type (
}
UserSubscribe {
Id int64 `json:"id"`
IdStr string `json:"id_str"`
UserId int64 `json:"user_id"`
OrderId int64 `json:"order_id"`
SubscribeId int64 `json:"subscribe_id"`
Subscribe Subscribe `json:"subscribe"`
NodeGroupId int64 `json:"node_group_id"`
NodeGroupName string `json:"node_group_name"`
StartTime int64 `json:"start_time"`
ExpireTime int64 `json:"expire_time"`
FinishedAt int64 `json:"finished_at"`
@@ -533,6 +585,35 @@ type (
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
UserSubscribeDetail {
Id int64 `json:"id"`
UserId int64 `json:"user_id"`
User User `json:"user"`
OrderId int64 `json:"order_id"`
SubscribeId int64 `json:"subscribe_id"`
Subscribe Subscribe `json:"subscribe"`
NodeGroupId int64 `json:"node_group_id"`
NodeGroupName string `json:"node_group_name"`
GroupLocked bool `json:"group_locked"`
StartTime int64 `json:"start_time"`
ExpireTime int64 `json:"expire_time"`
ResetTime int64 `json:"reset_time"`
Traffic int64 `json:"traffic"`
Download int64 `json:"download"`
Upload int64 `json:"upload"`
SpeedLimit int64 `json:"speed_limit"`
TrafficLimit []TrafficLimit `json:"user_traffic_limit"`
PlanSpeedLimit int64 `json:"plan_speed_limit"`
Token string `json:"token"`
Status uint8 `json:"status"`
EffectiveSpeed int64 `json:"effective_speed"`
IsThrottled bool `json:"is_throttled"`
ThrottleRule string `json:"throttle_rule,omitempty"`
ThrottleStart int64 `json:"throttle_start,omitempty"`
ThrottleEnd int64 `json:"throttle_end,omitempty"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
UserAffiliate {
Avatar string `json:"avatar"`
Identifier string `json:"identifier"`
@@ -676,6 +757,7 @@ type (
Price int64 `json:"price"`
Amount int64 `json:"amount"`
Discount int64 `json:"discount"`
PromoDiscount int64 `json:"promo_discount"`
GiftAmount int64 `json:"gift_amount"`
Coupon string `json:"coupon"`
CouponDiscount int64 `json:"coupon_discount"`
@@ -831,8 +913,9 @@ type (
Sandbox *bool `json:"sandbox,omitempty"`
}
AttachAppleTransactionResponse {
ExpiresAt int64 `json:"expires_at"`
Tier string `json:"tier"`
ExpiresAt int64 `json:"expires_at"`
Tier string `json:"tier"`
ExistingOrderNo string `json:"existing_order_no,omitempty"`
}
RestoreAppleTransactionsRequest {
Transactions []string `json:"transactions" validate:"required"`
@@ -1004,4 +1087,3 @@ type (
ConfigSnapshot map[string]interface{} `json:"config_snapshot,omitempty"`
}
)
+796
View File
@@ -0,0 +1,796 @@
package cmd
import (
"bufio"
"context"
"fmt"
"io"
"math/rand"
"os"
"sort"
"strconv"
"strings"
"time"
"github.com/perfect-panel/server/internal/config"
logmodel "github.com/perfect-panel/server/internal/model/log"
ordermodel "github.com/perfect-panel/server/internal/model/order"
usermodel "github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/pkg/conf"
"github.com/perfect-panel/server/pkg/orm"
"github.com/redis/go-redis/v9"
"github.com/spf13/cobra"
"gorm.io/gorm"
)
func init() {
retroactiveReferralCmd.Flags().StringVar(&retroAgentIdStr, "agent-id", "", "目标代理用户 ID,或 * 表示所有 referral_percentage>0 的代理(必填)")
retroactiveReferralCmd.Flags().StringVar(&retroPoolStart, "pool-start", "2025-05-04", "自然流量订单起始时间,格式 YYYY-MM-DD 或 'YYYY-MM-DD HH:MM:SS'(默认 2025-05-04")
retroactiveReferralCmd.Flags().StringVar(&retroPoolEnd, "pool-end", "", "自然流量订单截止时间,格式 YYYY-MM-DD 或 'YYYY-MM-DD HH:MM:SS'(默认今天)")
retroactiveReferralCmd.Flags().IntVar(&retroPercentage, "percentage", 120, "补偿百分比,例如 120 表示 120%(默认 120")
retroactiveReferralCmd.Flags().IntVar(&retroForceCommissionPct, "force-commission-pct", 50, "强制指定发佣比例(0=使用数据库/配置,非0时覆盖代理设置,默认 50%)")
retroactiveReferralCmd.Flags().StringVar(&retroOutput, "output", "retro_result.txt", "结果输出到指定 txt 文件(默认 retro_result.txt")
retroactiveReferralCmd.Flags().StringVar(&retroConfigPath, "config", "etc/ppanel.yaml", "配置文件路径")
retroactiveReferralCmd.Flags().StringVar(&retroAgentCreatedAfter, "agent-created-after", "", "仅处理在此日期之后注册的代理,格式 YYYY-MM-DD(留空=不限)")
retroactiveReferralCmd.Flags().StringVar(&retroLossStart, "loss-start", "2026-05-06", "数据丢失起始时间,丢失时长=现在-此时间(默认 2026-05-06")
retroactiveReferralCmd.Flags().StringVar(&retroOrderStart, "order-start", "2026-05-01", "池内用户至少有一笔 updated_at >= 此时间的订单才入池(默认 2026-05-01")
retroactiveReferralCmd.Flags().BoolVar(&retroDryRun, "dry-run", false, "仅预览,不执行写入")
rootCmd.AddCommand(retroactiveReferralCmd)
}
var (
retroAgentIdStr string
retroAgentCreatedAfter string
retroLossStart string
retroOrderStart string
retroPoolStart string
retroPoolEnd string
retroPercentage int
retroForceCommissionPct int
retroConfigPath string
retroDryRun bool
retroOutput string
)
var retroactiveReferralCmd = &cobra.Command{
Use: "retro-referral",
Short: "补单:按代理历史日均佣金补偿指定比例的用户",
Long: `统计代理从首次邀请到 pool-end 的日均佣金,
按指定百分比计算目标补偿金额,
从 pool-start 到 pool-end 的自然流量用户中随机抽取匹配的用户数量挂载到该代理。
--agent-id 支持单个 ID 或 *(处理所有 referral_percentage>0 的代理)。`,
RunE: func(cmd *cobra.Command, args []string) error {
if retroAgentIdStr == "" {
return fmt.Errorf("--agent-id 必填(单个 ID 或 *")
}
return runRetroactiveReferral()
},
}
// commissionRule holds resolved commission settings for an agent.
type commissionRule struct {
Percentage uint8
OnlyFirstPurchase bool
}
// candidateUser holds a pool user plus their pre-calculated qualifying orders.
type candidateUser struct {
Id int64
CreatedAt time.Time
Identifier string
Orders []ordermodel.Order
CommissionTotal int64
}
// agentPlan holds one agent's computed allocation plan (preview phase output).
type agentPlan struct {
Agent *usermodel.User
Rule commissionRule
Selected []candidateUser
TargetAmt float64 // in cents
PreviewCommission int64
}
func runRetroactiveReferral() error {
// ── 0. 初始化输出(终端 + 可选文件)─────────────────────────
var w io.Writer = os.Stdout
if retroOutput != "" {
f, err := os.Create(retroOutput)
if err != nil {
return fmt.Errorf("创建输出文件失败: %w", err)
}
defer f.Close()
w = io.MultiWriter(os.Stdout, f)
fmt.Printf("结果将同步写入: %s\n\n", retroOutput)
}
// ── 1. 加载配置 ──────────────────────────────────────────────
var c config.Config
conf.MustLoad(retroConfigPath, &c)
// ── 2. 初始化 DB + Redis ──────────────────────────────────────
db, err := orm.ConnectMysql(orm.Mysql{Config: c.MySQL})
if err != nil {
return fmt.Errorf("连接数据库失败: %w", err)
}
rds := redis.NewClient(&redis.Options{
Addr: c.Redis.Host,
Password: c.Redis.Pass,
DB: c.Redis.DB,
})
ctx := context.Background()
if err = rds.Ping(ctx).Err(); err != nil {
return fmt.Errorf("连接 Redis 失败: %w", err)
}
um := usermodel.NewModel(db, rds)
// ── 3. 解析时间参数 ───────────────────────────────────────────
poolStart, err := parseFlexibleTime(retroPoolStart)
if err != nil {
return fmt.Errorf("--pool-start 格式错误: %w", err)
}
poolEnd := time.Now()
if retroPoolEnd != "" {
poolEnd, err = parseFlexibleTime(retroPoolEnd)
if err != nil {
return fmt.Errorf("--pool-end 格式错误: %w", err)
}
}
if !poolEnd.After(poolStart) {
return fmt.Errorf("--pool-end 必须晚于 --pool-start")
}
// ── 4. 确定代理列表 ───────────────────────────────────────────
var agents []*usermodel.User
if retroAgentIdStr == "*" {
agents, err = queryAllActiveAgents(ctx, db, retroAgentCreatedAfter)
if err != nil {
return fmt.Errorf("查询代理列表失败: %w", err)
}
if len(agents) == 0 {
return fmt.Errorf("没有找到任何 referral_percentage>0 的代理用户")
}
fmt.Fprintf(w, "模式:全量代理,共找到 %d 个代理(referral_percentage>0\n\n", len(agents))
} else {
agentID, parseErr := strconv.ParseInt(retroAgentIdStr, 10, 64)
if parseErr != nil || agentID <= 0 {
return fmt.Errorf("--agent-id 必须是正整数或 *")
}
agent, findErr := um.FindOne(ctx, agentID)
if findErr != nil {
return fmt.Errorf("查询代理用户失败: %w", findErr)
}
if agent.DeletedAt.Valid {
return fmt.Errorf("代理用户 %d 已被删除", agentID)
}
agents = []*usermodel.User{agent}
}
if retroForceCommissionPct > 0 {
fmt.Fprintf(w, "⚠️ 强制覆盖所有代理佣金比例为 %d%%\n\n", retroForceCommissionPct)
}
// ── 5. 查询自然流量用户池(所有代理共用同一个池)────────────
// 先用 50% 规则(或强制值)预加载池,以便预览;执行时每个代理用自身规则
var orderStart time.Time
if retroOrderStart != "" {
orderStart, err = parseFlexibleTime(retroOrderStart)
if err != nil {
return fmt.Errorf("--order-start 格式错误: %w", err)
}
}
previewRule := commissionRule{Percentage: uint8(retroForceCommissionPct), OnlyFirstPurchase: false}
pool, err := queryNaturalTrafficPool(ctx, db, poolStart, poolEnd, orderStart, previewRule)
if err != nil {
return fmt.Errorf("查询自然流量用户池失败: %w", err)
}
orderStartDesc := ""
if !orderStart.IsZero() {
orderStartDesc = fmt.Sprintf(",订单 updated_at >= %s", orderStart.Format("2006-01-02"))
}
fmt.Fprintf(w, "自然流量用户池(%s ~ %sreferer_id=0,有已支付订单%s):共 %d 人\n\n",
poolStart.Format("2006-01-02 15:04"), poolEnd.Format("2006-01-02 15:04"), orderStartDesc, len(pool))
if len(pool) == 0 {
return fmt.Errorf("自然流量用户池为空,无法补充")
}
// ── 6. 逐代理生成分配计划(预览阶段)────────────────────────
// 池按顺序分配:每个代理从剩余池中取用户,避免重复分配
remainingPool := make([]candidateUser, len(pool))
copy(remainingPool, pool)
plans := make([]agentPlan, 0, len(agents))
for _, agent := range agents {
plan, planErr := buildAgentPlan(w, ctx, db, c, agent, remainingPool, poolEnd)
if planErr != nil {
fmt.Fprintf(w, "⚠️ 代理 %d 跳过: %v\n\n", agent.Id, planErr)
continue
}
// 从剩余池中移除已分配给该代理的用户
assignedSet := make(map[int64]struct{}, len(plan.Selected))
for _, u := range plan.Selected {
assignedSet[u.Id] = struct{}{}
}
newRemaining := remainingPool[:0]
for _, u := range remainingPool {
if _, used := assignedSet[u.Id]; !used {
newRemaining = append(newRemaining, u)
}
}
remainingPool = newRemaining
plans = append(plans, plan)
}
if len(plans) == 0 {
return fmt.Errorf("所有代理均无法生成分配计划")
}
// ── 7. 汇总预览 ───────────────────────────────────────────────
var grandTotalUsers int
var grandTotalCommission int64
var grandTargetAmt float64
for _, p := range plans {
grandTotalUsers += len(p.Selected)
grandTotalCommission += p.PreviewCommission
grandTargetAmt += p.TargetAmt
}
fmt.Fprintln(w, strings.Repeat("═", 75))
fmt.Fprintf(w, "汇总:共 %d 个代理,补充 %d 个用户\n", len(plans), grandTotalUsers)
fmt.Fprintf(w, " 预计追溯佣金总额: $%.2f(目标补偿金额: $%.2f\n",
float64(grandTotalCommission)/100, grandTargetAmt/100)
fmt.Fprintln(w, strings.Repeat("═", 75))
fmt.Fprintln(w)
if retroDryRun {
fmt.Fprintln(w, "[dry-run] 预览完成,未执行任何写入。")
return nil
}
// ── 8. 执行前汇总打印 ─────────────────────────────────────────
fmt.Fprintf(w, "\n┌─────────────────────────────────────────────┐\n")
fmt.Fprintf(w, "│ 即将写入数据库 │\n")
fmt.Fprintf(w, "│ 代理数量 : %-4d 个 │\n", len(plans))
fmt.Fprintf(w, "│ 补充用户 : %-4d 人 │\n", grandTotalUsers)
fmt.Fprintf(w, "│ 赠送金额 : $%-10.2f │\n", float64(grandTotalCommission)/100)
fmt.Fprintf(w, "└─────────────────────────────────────────────┘\n\n")
fmt.Printf("确认执行?(yes/no): ")
reader := bufio.NewReader(os.Stdin)
answer, _ := reader.ReadString('\n')
answer = strings.TrimSpace(strings.ToLower(answer))
if answer != "yes" && answer != "y" {
fmt.Fprintln(w, "已取消。")
return nil
}
// ── 9. 逐代理执行 ─────────────────────────────────────────────
var totalSuccess, totalFailed int
var totalCreditedOrder, totalCreditedAmt int64
for _, plan := range plans {
fmt.Fprintf(w, "\n── 执行代理 %d ──────────────────────────────────────────────\n", plan.Agent.Id)
var sc, fc int
var co, ca int64
for _, eu := range plan.Selected {
if eu.Id == plan.Agent.Id {
fmt.Fprintf(w, "[SKIP] 用户 %d 与代理相同,跳过\n", eu.Id)
fc++
continue
}
credited, amount, execErr := processOneUser(ctx, db, um, plan.Agent.Id, eu.Id, plan.Rule, orderStart)
if execErr != nil {
fmt.Fprintf(w, "[FAIL] 用户 %d: %v\n", eu.Id, execErr)
fc++
continue
}
fmt.Fprintf(w, "[OK] 用户 %d → 代理 %d,发佣 %d 单,金额 $%.2f\n",
eu.Id, plan.Agent.Id, credited, float64(amount)/100)
sc++
co += credited
ca += amount
}
// 直接删除代理的缓存 key,下次请求时从 DB 重新加载(避免 FindOne 读到旧缓存再写回)
if sc > 0 {
cacheKey := fmt.Sprintf("cache:user:id:%d", plan.Agent.Id)
_ = rds.Del(ctx, cacheKey).Err()
}
fmt.Fprintf(w, " 代理 %d 小计:成功 %d 人,失败 %d 人,佣金 $%.2f\n", plan.Agent.Id, sc, fc, float64(ca)/100)
totalSuccess += sc
totalFailed += fc
totalCreditedOrder += co
totalCreditedAmt += ca
}
// ── 10. 全局汇总 ──────────────────────────────────────────────
fmt.Fprintf(w, "\n══════════════════════════════════════════════\n")
fmt.Fprintf(w, " 成功挂载 : %d 人\n", totalSuccess)
fmt.Fprintf(w, " 失败/跳过 : %d 人\n", totalFailed)
fmt.Fprintf(w, " 追溯佣金 : %d 单,总额 $%.2f\n", totalCreditedOrder, float64(totalCreditedAmt)/100)
fmt.Fprintf(w, "══════════════════════════════════════════════\n")
return nil
}
// buildAgentPlan 计算一个代理的补单预览,同时打印预览内容,返回分配计划。
func buildAgentPlan(w io.Writer, ctx context.Context, db *gorm.DB, c config.Config,
agent *usermodel.User, pool []candidateUser, poolEnd time.Time) (agentPlan, error) {
rule := resolveCommissionRule(agent, c)
if retroForceCommissionPct > 0 {
rule.Percentage = uint8(retroForceCommissionPct)
}
// 补单场景:不区分新购/续费,所有已支付订单均参与佣金计算
rule.OnlyFirstPurchase = false
firstReferralTime, lastReferralTime, agentCreatedAt, totalReferred, totalOrders, totalCommission, err :=
queryAgentStats(ctx, db, agent.Id, poolEnd)
if err != nil {
return agentPlan{}, fmt.Errorf("查询历史数据失败: %w", err)
}
if totalReferred == 0 {
return agentPlan{}, fmt.Errorf("在 %s 之前没有任何邀请记录", poolEnd.Format("2006-01-02"))
}
lossStartTime, err := parseFlexibleTime(retroLossStart)
if err != nil {
return agentPlan{}, fmt.Errorf("--loss-start 格式错误: %w", err)
}
lossHours := time.Now().Sub(lossStartTime).Hours()
statsDays := lastReferralTime.Sub(firstReferralTime).Hours() / 24
if statsDays < 1 {
statsDays = 1
}
dailyAvgOrders := float64(totalOrders) / statsDays
avgOrdersPerUser := float64(totalOrders) / float64(totalReferred)
if avgOrdersPerUser < 1 {
avgOrdersPerUser = 1
}
dailyAvgCommission := float64(totalCommission) / statsDays
// 用用户池自身的平均佣金估算人数(避免历史费率与当前50%费率不匹配导致超发)
var poolAvgCommissionPerUser float64
if len(pool) > 0 {
var poolCommTotal int64
for _, u := range pool {
poolCommTotal += u.CommissionTotal
}
poolAvgCommissionPerUser = float64(poolCommTotal) / float64(len(pool))
}
if poolAvgCommissionPerUser < 1 {
poolAvgCommissionPerUser = 1
}
estimatedLostCommission := dailyAvgCommission * (lossHours / 24)
targetCommission := estimatedLostCommission * (float64(retroPercentage) / 100)
extraCount := int(targetCommission/poolAvgCommissionPerUser + 0.5)
if extraCount < 1 {
extraCount = 1
}
fmt.Fprintf(w, "\n═══════════════════════════════════════════════════════════\n")
fmt.Fprintf(w, " 代理 ID : %d(注册于 %s\n", agent.Id, agentCreatedAt.Format("2006-01-02 15:04:05"))
fmt.Fprintf(w, " 统计起点 : %s(首次邀请时间)\n", firstReferralTime.Format("2006-01-02 15:04:05"))
fmt.Fprintf(w, " 统计截止 : %s(最后邀请时间)\n", lastReferralTime.Format("2006-01-02 15:04:05"))
fmt.Fprintf(w, " 统计天数 : %.2f 天\n", statsDays)
fmt.Fprintf(w, " 历史邀请总人数 : %d 人\n", totalReferred)
fmt.Fprintf(w, " 下线总订单数 : %d 单(所有下线,不限时间)\n", totalOrders)
fmt.Fprintf(w, " 日均订单 : %.4f 单/天\n", dailyAvgOrders)
fmt.Fprintf(w, " 每用户平均订单 : %.4f 单\n", avgOrdersPerUser)
fmt.Fprintf(w, " 历史佣金总额 : $%.2f\n", float64(totalCommission)/100)
fmt.Fprintf(w, " 日均佣金 : $%.4f\n", dailyAvgCommission/100)
fmt.Fprintf(w, " 池内用户均佣金 : $%.4f\n", poolAvgCommissionPerUser/100)
fmt.Fprintf(w, " 佣金规则 : %d%% 仅首单=%v\n", rule.Percentage, rule.OnlyFirstPurchase)
fmt.Fprintf(w, "───────────────────────────────────────────────────────────\n")
fmt.Fprintf(w, " 丢失时长 : %.2f 小时(%s → 现在)\n",
lossHours, lossStartTime.Format("2006-01-02 15:04:05"))
fmt.Fprintf(w, " 预估丢失佣金 : $%.4f$%.4f × %.2f/24\n",
estimatedLostCommission/100, dailyAvgCommission/100, lossHours)
fmt.Fprintf(w, " 目标补偿金额 : $%.4f(× %d%%\n",
targetCommission/100, retroPercentage)
fmt.Fprintf(w, " 需补充人数 : %d 人($%.4f ÷ $%.4f\n",
extraCount, targetCommission/100, poolAvgCommissionPerUser/100)
fmt.Fprintf(w, "═══════════════════════════════════════════════════════════\n\n")
// 重新按当前代理规则计算池内用户佣金(pool 由调用方传入,已是当前规则计算好的)
if len(pool) == 0 {
return agentPlan{}, fmt.Errorf("剩余用户池为空")
}
if len(pool) < extraCount {
fmt.Fprintf(w, "⚠️ 剩余用户池只有 %d 人,少于需要的 %d 人,将全部分配\n\n", len(pool), extraCount)
extraCount = len(pool)
}
selected := randomSampleCandidates(pool, extraCount)
// 兜底追加:确保佣金合计 >= 目标
{
selectedSet := make(map[int64]struct{}, len(selected))
var selectedCommTotal int64
for _, u := range selected {
selectedSet[u.Id] = struct{}{}
selectedCommTotal += u.CommissionTotal
}
if selectedCommTotal < int64(targetCommission) {
remaining := make([]candidateUser, 0, len(pool)-len(selected))
for _, u := range pool {
if _, used := selectedSet[u.Id]; !used {
remaining = append(remaining, u)
}
}
// 按佣金从小到大排序,追加时精准补足,减少超发
sort.Slice(remaining, func(i, j int) bool {
return remaining[i].CommissionTotal < remaining[j].CommissionTotal
})
for _, u := range remaining {
if selectedCommTotal >= int64(targetCommission) {
break
}
selected = append(selected, u)
selectedCommTotal += u.CommissionTotal
}
if selectedCommTotal < int64(targetCommission) {
fmt.Fprintf(w, "⚠️ 用户池佣金不足,已抽取全部可用用户(实际 $%.2f < 目标 $%.2f\n\n",
float64(selectedCommTotal)/100, targetCommission/100)
}
}
}
// 打印选中用户明细
var previewTotalCommission int64
fmt.Fprintf(w, "随机抽取 %d 个用户(含待追溯佣金订单):\n", len(selected))
fmt.Fprintln(w, strings.Repeat("═", 75))
for i, u := range selected {
fmt.Fprintf(w, "[%d] 用户 %-10d 注册: %s %s\n",
i+1, u.Id, u.CreatedAt.Format("2006-01-02 15:04:05"), u.Identifier)
if len(u.Orders) == 0 {
fmt.Fprintln(w, " (无符合条件的订单)")
} else {
fmt.Fprintf(w, " %-38s %10s %8s %10s %s\n", "订单号", "金额", "手续费", "佣金", "类型")
fmt.Fprintf(w, " %s\n", strings.Repeat("-", 72))
for _, od := range u.Orders {
commAmt := calcCommissionAmount(od.Amount, od.FeeAmount, rule.Percentage)
orderType := "首购"
if od.Type == 2 {
orderType = "续费"
}
fmt.Fprintf(w, " %-38s $%8.2f $%6.2f $%8.2f %s\n",
od.OrderNo,
float64(od.Amount)/100,
float64(od.FeeAmount)/100,
float64(commAmt)/100,
orderType)
}
fmt.Fprintf(w, " 本用户追溯佣金合计: $%.2f\n", float64(u.CommissionTotal)/100)
}
previewTotalCommission += u.CommissionTotal
fmt.Fprintln(w)
}
fmt.Fprintln(w, strings.Repeat("═", 75))
fmt.Fprintf(w, "预计追溯佣金总额: $%.2f(目标补偿金额: $%.2f\n\n",
float64(previewTotalCommission)/100, targetCommission/100)
return agentPlan{
Agent: agent,
Rule: rule,
Selected: selected,
TargetAmt: targetCommission,
PreviewCommission: previewTotalCommission,
}, nil
}
// queryAllActiveAgents returns all agents with referral_percentage > 0, optionally filtered by created_after.
func queryAllActiveAgents(ctx context.Context, db *gorm.DB, createdAfter string) ([]*usermodel.User, error) {
q := db.WithContext(ctx).Model(&usermodel.User{}).
Where("referral_percentage > 0 AND deleted_at IS NULL")
if createdAfter != "" {
t, err := parseFlexibleTime(createdAfter)
if err != nil {
return nil, fmt.Errorf("--agent-created-after 格式错误: %w", err)
}
q = q.Where("created_at >= ?", t)
}
var agents []*usermodel.User
if err := q.Order("id ASC").Find(&agents).Error; err != nil {
return nil, err
}
return agents, nil
}
// parseFlexibleTime parses "YYYY-MM-DD HH:MM:SS" or "YYYY-MM-DD".
func parseFlexibleTime(s string) (time.Time, error) {
s = strings.TrimSpace(s)
if t, err := time.ParseInLocation("2006-01-02 15:04:05", s, time.Local); err == nil {
return t, nil
}
return time.ParseInLocation("2006-01-02", s, time.Local)
}
// queryAgentStats returns (firstReferralTime, lastReferralTime, agentCreatedAt, totalReferred, totalOrders, totalCommission, error).
func queryAgentStats(ctx context.Context, db *gorm.DB, agentID int64, endTime time.Time) (time.Time, time.Time, time.Time, int64, int64, int64, error) {
var agent usermodel.User
if err := db.WithContext(ctx).Model(&usermodel.User{}).
Where("id = ?", agentID).
First(&agent).Error; err != nil {
return time.Time{}, time.Time{}, time.Time{}, 0, 0, 0, err
}
agentCreatedAt := agent.CreatedAt
var firstUser usermodel.User
if err := db.WithContext(ctx).Model(&usermodel.User{}).
Where("referer_id = ? AND created_at >= ? AND created_at <= ? AND deleted_at IS NULL",
agentID, agentCreatedAt, endTime).
Order("created_at ASC").
First(&firstUser).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, nil
}
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, err
}
var lastUser usermodel.User
if err := db.WithContext(ctx).Model(&usermodel.User{}).
Where("referer_id = ? AND created_at >= ? AND created_at <= ? AND deleted_at IS NULL",
agentID, agentCreatedAt, endTime).
Order("created_at DESC").
First(&lastUser).Error; err != nil {
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, err
}
var totalReferred int64
if err := db.WithContext(ctx).Model(&usermodel.User{}).
Where("referer_id = ? AND created_at >= ? AND created_at <= ? AND deleted_at IS NULL",
agentID, agentCreatedAt, endTime).
Count(&totalReferred).Error; err != nil {
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, err
}
var totalOrders int64
if err := db.WithContext(ctx).Model(&ordermodel.Order{}).
Joins("JOIN user u ON u.id = `order`.user_id").
Where("u.referer_id = ?", agentID).
Where("`order`.status IN (2, 5)").
Count(&totalOrders).Error; err != nil {
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, err
}
type commResult struct{ Total int64 }
var result commResult
err := db.WithContext(ctx).Raw(`
SELECT COALESCE(SUM(
CAST(JSON_UNQUOTE(JSON_EXTRACT(content, '$.amount')) AS SIGNED)
), 0) AS total
FROM system_logs
WHERE type = 33
AND object_id = ?
AND created_at <= ?
AND JSON_UNQUOTE(JSON_EXTRACT(content, '$.type')) IN ('331', '332')
`, agentID, endTime).Scan(&result).Error
if err != nil {
return time.Time{}, time.Time{}, agentCreatedAt, 0, 0, 0, err
}
return firstUser.CreatedAt, lastUser.CreatedAt, agentCreatedAt, totalReferred, totalOrders, result.Total, nil
}
// queryNaturalTrafficPool returns pool candidates with pre-loaded qualifying orders.
// orderStart (可为零值):若非零,则只收录至少有一笔 updated_at >= orderStart 订单的用户,
// 且只加载/统计 updated_at >= orderStart 的订单(确保分配后代理能在对应月份的销售报表中看到记录)。
func queryNaturalTrafficPool(ctx context.Context, db *gorm.DB, start, end time.Time, orderStart time.Time, rule commissionRule) ([]candidateUser, error) {
type userRow struct {
Id int64
CreatedAt time.Time
AuthIdentifier string
}
var userRows []userRow
q := db.WithContext(ctx).
Table("user u").
Select("u.id, u.created_at, COALESCE(am.auth_identifier, '') AS auth_identifier").
Joins("JOIN `order` o ON o.user_id = u.id AND o.status IN (2, 5)").
Joins("LEFT JOIN user_auth_methods am ON am.user_id = u.id AND am.auth_type = 'email'").
Where("u.created_at >= ? AND u.created_at <= ?", start, end).
Where("u.referer_id = 0").
Where("u.deleted_at IS NULL")
if !orderStart.IsZero() {
// 只入池那些在 orderStart 之后有过订单的用户(保证代理销售报表里能看到)
q = q.Where("o.updated_at >= ?", orderStart)
}
if err := q.Group("u.id, u.created_at, am.auth_identifier").
Order("u.id ASC").
Scan(&userRows).Error; err != nil {
return nil, err
}
if len(userRows) == 0 {
return nil, nil
}
userIDs := make([]int64, len(userRows))
for i, r := range userRows {
userIDs[i] = r.Id
}
orderQuery := db.WithContext(ctx).Model(&ordermodel.Order{}).
Where("user_id IN ? AND status IN (2, 5)", userIDs)
if !orderStart.IsZero() {
// 只加载 orderStart 之后的订单:保证佣金统计和销售记录对齐
orderQuery = orderQuery.Where("updated_at >= ?", orderStart)
}
var allOrders []ordermodel.Order
if err := orderQuery.Order("user_id ASC, created_at ASC").Find(&allOrders).Error; err != nil {
return nil, err
}
ordersByUser := make(map[int64][]ordermodel.Order, len(userRows))
for _, od := range allOrders {
ordersByUser[od.UserId] = append(ordersByUser[od.UserId], od)
}
candidates := make([]candidateUser, 0, len(userRows))
for _, r := range userRows {
orders := ordersByUser[r.Id]
var commTotal int64
for i := range orders {
if canCreditOrder(rule, &orders[i]) {
commTotal += calcCommissionAmount(orders[i].Amount, orders[i].FeeAmount, rule.Percentage)
}
}
candidates = append(candidates, candidateUser{
Id: r.Id,
CreatedAt: r.CreatedAt,
Identifier: r.AuthIdentifier,
Orders: orders,
CommissionTotal: commTotal,
})
}
return candidates, nil
}
// randomSampleCandidates picks n random elements from pool without replacement.
func randomSampleCandidates(pool []candidateUser, n int) []candidateUser {
if n >= len(pool) {
return append([]candidateUser{}, pool...)
}
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
indices := rng.Perm(len(pool))[:n]
result := make([]candidateUser, n)
for i, idx := range indices {
result[i] = pool[idx]
}
return result
}
// processOneUser assigns agentId as referer and retroactively credits commission for qualifying orders.
func processOneUser(
ctx context.Context,
db *gorm.DB,
um usermodel.Model,
agentID, userID int64,
rule commissionRule,
orderStart time.Time,
) (int64, int64, error) {
var creditedOrders, creditedAmount int64
err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var target usermodel.User
if e := tx.Model(&usermodel.User{}).
Where("id = ? AND referer_id = 0 AND deleted_at IS NULL", userID).
First(&target).Error; e != nil {
if e == gorm.ErrRecordNotFound {
return fmt.Errorf("用户不存在或已有代理或已删除")
}
return e
}
var orders []ordermodel.Order
oq := tx.Model(&ordermodel.Order{}).
Where("user_id = ? AND status IN (2, 5)", userID)
if !orderStart.IsZero() {
oq = oq.Where("updated_at >= ?", orderStart)
}
if e := oq.Order("created_at ASC, id ASC").Find(&orders).Error; e != nil {
return e
}
if len(orders) == 0 {
return fmt.Errorf("无合格订单")
}
if e := tx.Model(&usermodel.User{}).
Where("id = ? AND referer_id = 0 AND deleted_at IS NULL", userID).
Updates(map[string]interface{}{
"referer_id": agentID,
"updated_at": time.Now(),
}).Error; e != nil {
return e
}
for i := range orders {
od := &orders[i]
if !canCreditOrder(rule, od) {
continue
}
amount := calcCommissionAmount(od.Amount, od.FeeAmount, rule.Percentage)
if amount <= 0 {
continue
}
var existCount int64
if e := tx.Model(&logmodel.SystemLog{}).
Where("type = ? AND object_id = ? AND content LIKE ?",
logmodel.TypeCommission.Uint8(), agentID,
fmt.Sprintf("%%\"%s\"%%", od.OrderNo),
).Count(&existCount).Error; e != nil {
return e
}
if existCount > 0 {
continue
}
if e := tx.Model(&usermodel.User{}).
Where("id = ? AND deleted_at IS NULL", agentID).
UpdateColumn("commission", gorm.Expr("commission + ?", amount)).Error; e != nil {
return e
}
commType := logmodel.CommissionTypePurchase
if od.Type == 2 {
commType = logmodel.CommissionTypeRenewal
}
payload := &logmodel.Commission{
Type: commType,
Amount: amount,
OrderNo: od.OrderNo,
Timestamp: od.CreatedAt.UnixMilli(),
}
content, _ := payload.Marshal()
if e := tx.Create(&logmodel.SystemLog{
Type: logmodel.TypeCommission.Uint8(),
Date: od.CreatedAt.Format("2006-01-02"),
ObjectID: agentID,
Content: string(content),
CreatedAt: od.CreatedAt,
}).Error; e != nil {
return e
}
creditedOrders++
creditedAmount += amount
}
return nil
})
if err != nil {
return 0, 0, err
}
if updated, e := um.FindOne(ctx, userID); e == nil {
_ = um.UpdateUserCache(ctx, updated)
}
return creditedOrders, creditedAmount, nil
}
func resolveCommissionRule(agent *usermodel.User, c config.Config) commissionRule {
if agent.ReferralPercentage > 0 {
onlyFirst := true
if agent.OnlyFirstPurchase != nil {
onlyFirst = *agent.OnlyFirstPurchase
}
return commissionRule{Percentage: agent.ReferralPercentage, OnlyFirstPurchase: onlyFirst}
}
return commissionRule{
Percentage: uint8(c.Invite.ReferralPercentage),
OnlyFirstPurchase: c.Invite.OnlyFirstPurchase,
}
}
func canCreditOrder(rule commissionRule, od *ordermodel.Order) bool {
if rule.Percentage == 0 {
return false
}
if rule.OnlyFirstPurchase && !od.IsNew {
return false
}
return od.Status == 2 || od.Status == 5
}
func calcCommissionAmount(amount, feeAmount int64, percentage uint8) int64 {
base := amount - feeAmount
if base <= 0 || percentage == 0 {
return 0
}
return int64(float64(base) * float64(percentage) / 100)
}
+3
View File
@@ -4316,6 +4316,9 @@
"discount": {
"type": "number",
"format": "double"
},
"promo": {
"$ref": "#/definitions/SubscribePromo"
}
},
"title": "SubscribeDiscount",
+20
View File
@@ -0,0 +1,20 @@
EC2 SSH 连接资料
服务器名称: hifast-hk-app-01
公网 IP: 43.198.248.161
登录用户: ubuntu
私钥文件:
- hifast-hk-app-01-reset
公钥文件:
- hifast-hk-app-01-reset.pub
连接命令:
ssh -i hifast-hk-app-01-reset ubuntu@43.198.248.161
如果在 Mac / Linux 上使用,先执行:
chmod 600 hifast-hk-app-01-reset
如果要给别人使用,只需要把私钥文件 hifast-hk-app-01-reset 发给对方即可。
出于安全考虑,建议通过安全渠道传输,并在后续需要时重新轮换密钥。
@@ -0,0 +1,8 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACDb6msDqmSHLv0mWgCP4vfjQ3A552qv95uQdsH94RnoCgAAAKjy5KDa8uSg
2gAAAAtzc2gtZWQyNTUxOQAAACDb6msDqmSHLv0mWgCP4vfjQ3A552qv95uQdsH94RnoCg
AAAEDwSb0b/0S6Tw8Od5hAtIKqt1JvomqQQS44Ty3xL+FjPtvqawOqZIcu/SZaAI/i9+ND
cDnnaq/3m5B2wf3hGegKAAAAIWhpZmFzdC1oay1hcHAtMDEtcmVzZXQtMjAyNi0wNS0xMA
ECAwQ=
-----END OPENSSH PRIVATE KEY-----
@@ -0,0 +1 @@
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINvqawOqZIcu/SZaAI/i9+NDcDnnaq/3m5B2wf3hGegK hifast-hk-app-01-reset-2026-05-10
+363
View File
@@ -0,0 +1,363 @@
# PPanel 香港区新 AWS 账号部署说明
本目录用于在 **新 AWS 账号** 中按 **香港区 `ap-east-1`** 重建一套全新空环境。
目标架构:
`DNS -> ALB -> WAF -> EC2(Nginx + ppanel-server + Redis + observability) -> RDS MySQL`
## 1. 资源清单
按下面顺序创建资源:
1. VPC
2. 2 个公有子网 + 2 个私有子网
3. Internet Gateway
4. 公有 / 私有路由表
5. 安全组
6. RDS MySQL
7. EC2 本机 Redis Docker
8. EC2
9. ACM 证书
10. ALB + Target Group
11. WAF Web ACL
12. 平行环境域名
建议命名:
- VPC: `ppanel-hk-prod`
- EC2: `ppanel-app-hk-01`
- RDS: `ppanel-mysql-hk`
- Redis container: `hifast-redis`
- ALB: `ppanel-alb-hk`
- WAF: `ppanel-waf-hk`
## 2. 默认规格
### EC2
- Region: `ap-east-1`
- OS: Ubuntu 24.04 LTS
- Instance type: `t4g.large` 起步
- Disk: `gp3 80GB`
- Public subnet: 是
- IAM Role: 允许读取 CloudWatch / SSM(如使用)
- 如果要在 AWS EC2 本机执行 S3 备份:额外允许写入专用备份桶
### RDS MySQL
- Engine: MySQL 8.0
- Class: `db.r7g.xlarge`
- Storage: `gp3 100GB`
- DB name: `hifast`
- Username: `admin`
- Public access: `No`
- Charset: `utf8mb4`
- Backup: `7-14 days`
### Redis
- 部署位置:业务 EC2 本机
- 部署方式:Docker
- 版本:`redis:8.2.1`
- 监听:`0.0.0.0:6379`
- 应用连接:`127.0.0.1:6379`
- 安全组:仅对白名单备用节点或同机应用开放
## 3. 网络与安全组
### 子网布局
- `public-a`, `public-b`: ALB / EC2
- `private-a`, `private-b`: RDS
### 安全组建议
#### `sg-alb`
- Inbound
- `80/tcp` from `0.0.0.0/0`
- `443/tcp` from `0.0.0.0/0`
- Outbound
- `80/tcp` to `sg-ec2`
#### `sg-ec2`
- Inbound
- `80/tcp` from `sg-alb`
- `22/tcp` from `你的固定运维 IP`
- Outbound
- all
说明:
- 应用容器监听 `127.0.0.1:8080`
- EC2 对外只让 Nginx 监听 `80`
- Grafana / Prometheus / Tempo 仅监听 `127.0.0.1`
#### `sg-rds`
- Inbound
- `3306/tcp` from `sg-ec2`
#### `sg-ec2` 额外说明
- 如果需要外部备用节点复制 Redis,再额外放行:
- `6379/tcp` from `104.238.220.230/32`
## 4. ALB / Target Group / 健康检查
### Target Group
- Type: `Instance`
- Protocol: `HTTP`
- Port: `80`
- Health check path: `/v1/common/heartbeat`
- Success code: `200`
这个路径已由项目现有接口提供,无需额外改代码。
### ALB 监听器
- `80` -> redirect to `443`
- `443` -> forward 到 target group
### ACM
-`ap-east-1` 申请证书
- 先给平行环境域名,例如:
- `api-new.hifast.biz`
- `logs-new.hifast.biz`
## 5. WAF 规则
首版至少启用:
1. `AWSManagedRulesCommonRuleSet`
2. `AWSManagedRulesKnownBadInputsRuleSet`
3. `AWSManagedRulesAmazonIpReputationList`
4. 全站 rate-based rule
5. 针对高风险路径的 rate-based rule
建议的第一版限流:
- 全站:每 IP `2000 / 5 分钟`
- `/v1/public/user/subscribe`:每 IP `300 / 5 分钟`
- 登录 / 注册 / 验证码接口:每 IP `100 / 5 分钟`
节点上报接口建议后续补:
- `/v1/server/status`
- `/v1/server/online`
- `/v1/server/traffic`
优先用节点出口 IP 白名单;没有固定出口 IP 的节点暂时保留 `secret_key`,但不要把它当成唯一防线。
## 6. EC2 文件落地
在 EC2 上建议使用:
- 应用目录:`/opt/ppanel`
- Nginx 配置:`/etc/nginx/sites-available/ppanel-api.conf`
需要上传这些文件 / 目录:
- `docker-compose.cloud.yml`
- `deploy/aws/ap-east-1/configs/ppanel.yaml.example` -> 重命名为 `configs/ppanel.yaml`
- `deploy/aws/ap-east-1/nginx/ppanel-api.conf`
- `grafana/`
- `loki/`
- `prometheus/`
- `tempo/`
- `.env.example` -> 重命名为 `.env`
目标目录示例:
```text
/opt/ppanel/
docker-compose.cloud.yml
.env
configs/ppanel.yaml
grafana/
loki/
prometheus/
tempo/
logs/
cache/
tempo_data/
```
## 7. 应用配置
基线模板见:
- [`configs/ppanel.yaml.example`](./configs/ppanel.yaml.example)
- [`nginx/ppanel-api.conf`](./nginx/ppanel-api.conf)
关键值必须替换:
- `MySQL.Addr`
- `MySQL.Password`
- `Redis.Host`
- `Redis.Pass`
- `JwtAuth.AccessSecret`
- `Administrator.Email`
- `Administrator.Password`
- `AppSignature.AppSecrets.*`
- `device.security_secret`
- `Site.Host`
- `Site.SiteName`
Redis 约定保持不变:
- 业务缓存:DB `0`
- AsynqDB `5`(代码内部已固定使用)
## 8. 部署步骤
### 8.1 初始化 EC2
把脚本上传到 EC2 后执行:
## 9. 104 灾备节点常用运维脚本
如果你要在 `104.238.220.230` 上执行数据迁移、主从重拉、主库提升,可以直接复用仓库里的这几份脚本:
- 数据导出 / 导入交互工具:
- [`deploy/scripts/hifast_data_sync_tool.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/hifast_data_sync_tool.sh)
- MySQL 主从运维工具:
- [`deploy/scripts/mysql_replica_ops.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/mysql_replica_ops.sh)
- Redis 主从运维工具:
- [`deploy/scripts/redis_replica_ops.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/redis_replica_ops.sh)
- 统一总入口:
- [`deploy/scripts/hifast_data_sync_tool.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/hifast_data_sync_tool.sh)
- 主从运维环境模板:
- [`deploy/aws/ap-east-1/configs/replica-ops.env.example`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/aws/ap-east-1/configs/replica-ops.env.example)
### 9.1 数据迁移工具
支持:
- 备份 MySQL 到 S3
- 备份 Redis 到 S3
- 从正式库导出 MySQL `sql.gz`
-`sql.gz` 导入 AWS RDS
- 从正式 Redis 导出 `RDB`
-`RDB` 导入 Docker Redis 或宿主机 Redis
- 查看 MySQL / Redis 当前主从状态
- 强制重拉 MySQL / Redis 主从
- 把 MySQL / Redis 从库提升为可写主库
示例:
```bash
bash deploy/scripts/hifast_data_sync_tool.sh /root/replica-ops.env
```
```bash
chmod +x deploy/scripts/bootstrap_aws_ec2.sh
sudo APP_DIR=/opt/ppanel deploy/scripts/bootstrap_aws_ec2.sh
```
### 8.2 安装 Nginx 配置
```bash
sudo cp deploy/aws/ap-east-1/nginx/ppanel-api.conf /etc/nginx/sites-available/ppanel-api.conf
sudo ln -sf /etc/nginx/sites-available/ppanel-api.conf /etc/nginx/sites-enabled/ppanel-api.conf
sudo nginx -t
sudo systemctl reload nginx
```
### 8.3 启动容器
```bash
cd /opt/ppanel
docker compose -f docker-compose.cloud.yml up -d
```
### 8.4 预检
```bash
chmod +x deploy/scripts/preflight_aws_hk.sh
APP_DIR=/opt/ppanel \
RDS_HOST=<new-rds-endpoint> \
REDIS_HOST=127.0.0.1 \
deploy/scripts/preflight_aws_hk.sh
```
## 9. 平行环境验证
先验证 `api-new.hifast.biz`,不要直接切正式域名。
必测项:
1. `ALB target` 为 healthy
2. `GET /v1/common/heartbeat` 返回 200
3. 管理员登录
4. 用户注册 / 登录
5. 订阅查询
6. 节点上报 `/v1/server/status`
7. 本机 Redis 可写缓存
8. Asynq 可入队并消费
## 10. 正式切换
切换前检查:
1. ALB 5xx 为 0
2. EC2 CPU / Memory 正常
3. RDS CPU / Connections 正常
4. 本机 Redis CPU / Connections / Memory 正常
5. WAF 已挂到 ALB
6. EC2 安全组没有对公网放 `8080/3333/9090/4317`
切换方式:
1. 保持新环境先跑平行域名
2. 正式域名切到新 ALB
3. 观察至少 1 小时
4. 确认无误后再处理旧环境
## 11. 监控建议
至少建这些 CloudWatch / Grafana 观测项:
- ALB `RequestCount`, `HTTPCode_ELB_5XX_Count`, `TargetResponseTime`
- EC2 `CPUUtilization`, `NetworkIn`, `NetworkOut`, `StatusCheckFailed`
- RDS `CPUUtilization`, `DatabaseConnections`, `ReadLatency`, `WriteLatency`
- Redis 容器 CPU / Memory / restart count
## 12. 这次方案的边界
本目录交付的是:
- 香港区新账号的部署模板
- 新空环境启动与验证流程
- ALB / WAF / EC2 / RDS / 本机 Redis 的落地约定
不包含:
- 旧数据迁移
- Terraform / CloudFormation 自动建资源
- Redis 托管版改造
- 多活 / 自动扩缩容
## 13. S3 备份补强
当前已落地的 S3 备份桶:
- `hifast-prod-backups-200810848252-ap-east-1`
建议与现网结合方式:
1. `RDS automated backup` 继续保留,作为第一层恢复能力
2. `104` 外部 MySQL 从库执行逻辑备份并上传到 S3,作为第二层可下载备份
3. `104` 外部 Redis 从库按需导出 `RDB` 到 S3,补齐缓存类灾备材料
仓库中已补充:
- 环境变量模板:[`configs/backup-to-s3.env.example`](./configs/backup-to-s3.env.example)
- MySQL 备份脚本:[`../../scripts/mysql_backup_to_s3.sh`](../../scripts/mysql_backup_to_s3.sh)
- Redis 备份脚本:[`../../scripts/redis_rdb_backup_to_s3.sh`](../../scripts/redis_rdb_backup_to_s3.sh)
建议把 MySQL 备份脚本优先部署到 `104`,因为它直接连接本地只读从库,对 AWS 主库扰动最小。
@@ -0,0 +1,18 @@
AWS_REGION=ap-east-1
S3_BUCKET=hifast-prod-backups-200810848252-ap-east-1
S3_PREFIX=mysql
BACKUP_DIR=/var/backups/hifast
HOST_TAG=104-standby
KEEP_LOCAL_DAYS=3
CHECK_REPLICA=1
MYSQL_HOST=127.0.0.1
MYSQL_PORT=3306
MYSQL_USER=backup_reader
MYSQL_PASSWORD=CHANGE_ME
MYSQL_SOCKET=
MYSQL_DATABASE=hifast
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=CHANGE_ME
@@ -0,0 +1,20 @@
PRIMARY_HOST=hifast-mysql-prod-v2.cd6aey40m6ag.ap-east-1.rds.amazonaws.com
PRIMARY_PORT=3306
PRIMARY_USER=admin
PRIMARY_PASSWORD=CHANGE_ME
PRIMARY_DB=hifast
PRIMARY_REPL_USER=repl
PRIMARY_REPL_PASSWORD=CHANGE_ME
PRIMARY_REPL_HOST=104.238.220.230
PRIMARY_BINLOG_RETENTION_HOURS=24
REPLICA_HOST=127.0.0.1
REPLICA_PORT=3306
REPLICA_USER=root
REPLICA_PASSWORD=
REPLICA_SOCKET=/var/run/mysqld/mysqld.sock
REPLICA_DB=hifast
REPLICA_SOURCE_SSL=1
DUMP_FILE=
@@ -0,0 +1,111 @@
Host: 0.0.0.0
Port: 8080
Debug: false
JwtAuth:
AccessSecret: CHANGE_ME_TO_A_LONG_RANDOM_SECRET
AccessExpire: 604800
Logger:
ServiceName: PPanel
Mode: console
Encoding: plain
TimeFormat: "2006-01-02 15:04:05.000"
Path: logs
Level: info
MaxContentLength: 0
Compress: false
Stat: true
KeepDays: 7
StackCooldownMillis: 100
MaxBackups: 7
MaxSize: 100
Rotation: daily
FileTimeFormat: "2006-01-02T15:04:05.000Z07:00"
MySQL:
Addr: YOUR_RDS_ENDPOINT:3306
Dbname: hifast
Username: admin
Password: CHANGE_ME_TO_RDS_PASSWORD
Config: charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai
MaxIdleConns: 10
MaxOpenConns: 100
SlowThreshold: 1000
Redis:
Host: 127.0.0.1:6379
Pass: CHANGE_ME_TO_REDIS_PASSWORD
DB: 0
PoolSize: 100
MinIdleConns: 10
MaxRetries: 3
PoolTimeout: 4
IdleTimeout: 300
MaxConnAge: 0
DialTimeout: 5
ReadTimeout: 3
WriteTimeout: 3
Trace:
Name: ppanel-server
Endpoint: 127.0.0.1:4317
Sampler: 0.1
Batcher: otlpgrpc
Site:
Host: api-new.hifast.biz
SiteName: HiFastVPN
Administrator:
Email: admin@example.com
Password: CHANGE_ME_TO_STRONG_ADMIN_PASSWORD
Telegram:
Enable: false
BotID: 0
BotName: ""
BotToken: ""
GroupChatID: ""
EnableNotify: false
WebHookDomain: ""
Kutt:
Enable: false
ApiURL: ""
ApiKey: ""
TargetURL: ""
Domain: ""
OpenInstall:
Enable: false
AppKey: ""
ApiKey: ""
Loki:
Enable: true
URL: "http://localhost:3100"
AppSignature:
AppSecrets:
android-client: CHANGE_ME_ANDROID_SIGNATURE_SECRET
ios-client: CHANGE_ME_IOS_SIGNATURE_SECRET
web-client: CHANGE_ME_WEB_SIGNATURE_SECRET
ValidWindowSeconds: 300
SkipPrefixes:
- /v1/notify/
- /v1/iap/notifications
- /v1/telegram/webhook
- /v1/subscribe/config
Signature:
EnableSignature: false
device:
enable: true
security_secret: CHANGE_ME_DEVICE_SECURITY_SECRET
Register:
EnableTrial: true
EnableTrialEmailWhitelist: true
TrialEmailDomainWhitelist: "gmail.com,outlook.com,icloud.com,qq.com,163.com"
@@ -0,0 +1,23 @@
MYSQL_HOST=127.0.0.1
MYSQL_PORT=3306
MYSQL_USER=root
MYSQL_PASSWORD=CHANGE_ME
MYSQL_SOCKET=
REPL_SOURCE_HOST=hifast-mysql-prod-v2.cd6aey40m6ag.ap-east-1.rds.amazonaws.com
REPL_SOURCE_PORT=3306
REPL_SOURCE_USER=repl
REPL_SOURCE_PASSWORD=CHANGE_ME
REPL_SOURCE_SSL=1
REPL_SOURCE_LOG_FILE=
REPL_SOURCE_LOG_POS=
REPL_SOURCE_AUTO_POSITION=1
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=CHANGE_ME
REDIS_SOURCE_HOST=18.163.33.75
REDIS_SOURCE_PORT=6379
REDIS_SOURCE_USER=
REDIS_SOURCE_PASSWORD=CHANGE_ME
@@ -0,0 +1,33 @@
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
client_max_body_size 20m;
access_log /var/log/nginx/ppanel-access.log;
error_log /var/log/nginx/ppanel-error.log warn;
location / {
proxy_http_version 1.1;
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
proxy_connect_timeout 10s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
location = /nginx_status {
stub_status;
access_log off;
allow 127.0.0.1;
deny all;
}
}
+358
View File
@@ -0,0 +1,358 @@
# PPanel 日本东京区 AWS 部署说明
本目录用于在 **AWS 日本东京区 `ap-northeast-1`** 重建一套全新生产环境,并承接当前香港区 `ap-east-1` 的正式迁移。
如果你要看“当前已经真实跑起来的东京架构”,优先看:
- [`ops/hifast-current-architecture-zh.md`](/Users/Apple/code_vpn/vpn/ppanel-server/ops/hifast-current-architecture-zh.md)
- [`configs/resource-inventory.current.md`](./configs/resource-inventory.current.md)
这份 README 更偏向:
- 目标架构
- 资源规划
- 部署方法
- 后续待完成项
目标架构:
`DNS -> ALB -> WAF -> EC2(Nginx + ppanel-server + Redis + observability) -> RDS MySQL`
灾备链路:
`RDS MySQL / EC2 Redis -> 104.238.220.230 外部灾备`
当前仓库内已补充:
- 东京基础设施参数模板:[`configs/aws-jp-infra.env.example`](./configs/aws-jp-infra.env.example)
- 东京真实实施状态登记:[`configs/resource-inventory.current.md`](./configs/resource-inventory.current.md)
- 东京底座资源创建脚本:[`../../scripts/aws_jp_create_base_infra.sh`](../../scripts/aws_jp_create_base_infra.sh)
- 东京资源状态检查脚本:[`../../scripts/aws_jp_describe_state.sh`](../../scripts/aws_jp_describe_state.sh)
- MySQL 备份脚本:[`../../scripts/mysql_backup_to_s3.sh`](../../scripts/mysql_backup_to_s3.sh)
- 10 分钟 MySQL 备份定时器安装脚本:[`../../scripts/install_mysql_backup_timer.sh`](../../scripts/install_mysql_backup_timer.sh)
## 1. 资源清单
按下面顺序创建资源:
1. VPC
2. 2 个公有子网 + 2 个私有子网
3. Internet Gateway
4. 公有 / 私有路由表
5. 安全组
6. RDS MySQL
7. EC2 本机 Redis Docker
8. EC2
9. ACM 证书
10. ALB + Target Group
11. WAF Web ACL
12. 东京平行环境域名
13. 东京 S3 备份桶
建议命名:
- VPC: `ppanel-jp-prod`
- EC2: `ppanel-app-jp-01`
- RDS: `ppanel-mysql-jp`
- Redis container: `hifast-redis`
- ALB: `ppanel-alb-jp`
- WAF: `ppanel-waf-jp`
- S3: `hifast-prod-backups-200810848252-ap-northeast-1`
## 2. 默认规格
### EC2
- Region: `ap-northeast-1`
- OS: Ubuntu 24.04 LTS
- Instance type: `t4g.large`
- Disk: `gp3 80GB`
- Public subnet: 是
- IAM Role:
- 允许读取 CloudWatch / SSM(如使用)
- 如果要在东京 EC2 上执行 S3 备份:额外允许写入东京备份桶
### RDS MySQL
- Engine: `MySQL 8.4`
- Class: `db.r7g.xlarge`
- Storage: `gp3 100GB`
- DB name: `hifast`
- Username: `admin`
- Public access: `Yes`
- Charset: `utf8mb4`
- Backup retention: `7-14 days`
- Deletion protection: `On`
- Multi-AZ: `Yes`(当前按 2 实例 Multi-AZ 创建)
说明:
- 当前东京 RDS 需要允许 `104.238.220.230` 从公网直连 `3306`,用于外部 MySQL 从库复制
- 因此本阶段 RDS 使用 `public subnet group + Publicly accessible = Yes`
- 访问面只通过 `sg-rds` 严格限制到业务 EC2 安全组和 `104.238.220.230/32`
### Redis
- 部署位置:业务 EC2 本机
- 部署方式:Docker
- 版本:`redis:8.2.1`
- 监听:`0.0.0.0:6379`
- 应用连接:`127.0.0.1:6379`
- 安全组:仅对白名单备用节点 `104.238.220.230/32` 或同机应用开放
## 3. 网络与安全组
### 子网布局
- `public-a`, `public-c`: ALB / EC2
- `private-a`, `private-c`: RDS
说明:
- 东京优先使用 `ap-northeast-1a``ap-northeast-1c`
- 如果账户映射不同,也可以用任意 2 个可用区,但公私网必须各 2 个子网
### 安全组建议
#### `sg-alb`
- Inbound
- `80/tcp` from `0.0.0.0/0`
- `443/tcp` from `0.0.0.0/0`
- Outbound
- `80/tcp` to `sg-ec2`
#### `sg-ec2`
- Inbound
- `80/tcp` from `sg-alb`
- `22/tcp` from `你的固定运维 IP`
- `6379/tcp` from `104.238.220.230/32`
- Outbound
- all
说明:
- 应用容器监听 `127.0.0.1:8080`
- EC2 对外只让 Nginx 监听 `80`
- Grafana / Prometheus / Tempo 仅监听 `127.0.0.1`
#### `sg-rds`
- Inbound
- `3306/tcp` from `sg-ec2`
- `3306/tcp` from `104.238.220.230/32`
## 4. ALB / Target Group / 健康检查
### Target Group
- Type: `Instance`
- Protocol: `HTTP`
- Port: `80`
- Health check path: `/v1/common/heartbeat`
- Success code: `200`
### ALB 监听器
- `80` -> redirect to `443`
- `443` -> forward 到 target group
### ACM
-`ap-northeast-1` 重新申请证书
- 先给平行环境域名,例如:
- `api-jp.hifast.biz`
- `logs-jp.hifast.biz`
## 5. WAF 规则
首版至少启用:
1. `AWSManagedRulesCommonRuleSet`
2. `AWSManagedRulesKnownBadInputsRuleSet`
3. `AWSManagedRulesAmazonIpReputationList`
4. 全站 rate-based rule
5. 针对高风险路径的 rate-based rule
建议的第一版限流:
- 全站:每 IP `2000 / 5 分钟`
- `/v1/public/user/subscribe`:每 IP `300 / 5 分钟`
- 登录 / 注册 / 验证码接口:每 IP `100 / 5 分钟`
节点上报接口建议后续补:
- `/v1/server/status`
- `/v1/server/online`
- `/v1/server/traffic`
## 6. EC2 文件落地
在 EC2 上建议使用:
- 应用目录:`/opt/ppanel`
- Nginx 配置:`/etc/nginx/sites-available/ppanel-api.conf`
需要上传这些文件 / 目录:
- `docker-compose.cloud.yml`
- `deploy/aws/ap-northeast-1/configs/ppanel.yaml.example` -> 重命名为 `configs/ppanel.yaml`
- `deploy/aws/ap-northeast-1/nginx/ppanel-api.conf`
- `grafana/`
- `loki/`
- `prometheus/`
- `tempo/`
- `.env.example` -> 重命名为 `.env`
目标目录示例:
```text
/opt/ppanel/
docker-compose.cloud.yml
.env
configs/ppanel.yaml
grafana/
loki/
prometheus/
tempo/
logs/
cache/
tempo_data/
```
## 7. 应用配置
基线模板见:
- [`configs/ppanel.yaml.example`](./configs/ppanel.yaml.example)
- [`nginx/ppanel-api.conf`](./nginx/ppanel-api.conf)
关键值必须替换:
- `MySQL.Addr`
- `MySQL.Password`
- `Redis.Host`
- `Redis.Pass`
- `JwtAuth.AccessSecret`
- `Administrator.Email`
- `Administrator.Password`
- `AppSignature.AppSecrets.*`
- `device.security_secret`
- `Site.Host`
- `Site.SiteName`
Redis 约定保持不变:
- 业务缓存:DB `0`
- AsynqDB `5`
## 8. 部署步骤
### 8.0 创建东京基础设施
如果本机或跳板机已经配置好 AWS CLI 凭据,可以先直接执行:
```bash
cp deploy/aws/ap-northeast-1/configs/aws-jp-infra.env.example /root/aws-jp-infra.env
chmod 600 /root/aws-jp-infra.env
vim /root/aws-jp-infra.env
chmod +x deploy/scripts/aws_jp_create_base_infra.sh
bash deploy/scripts/aws_jp_create_base_infra.sh /root/aws-jp-infra.env
```
执行后可用下面命令随时核对东京底座状态:
```bash
chmod +x deploy/scripts/aws_jp_describe_state.sh
bash deploy/scripts/aws_jp_describe_state.sh /root/aws-jp-infra.env
```
### 8.1 初始化 EC2
把脚本上传到东京 EC2 后执行:
```bash
chmod +x deploy/scripts/bootstrap_aws_ec2.sh
sudo APP_DIR=/opt/ppanel APP_USER=ubuntu deploy/scripts/bootstrap_aws_ec2.sh
```
### 8.2 安装 Nginx 配置
```bash
sudo cp deploy/aws/ap-northeast-1/nginx/ppanel-api.conf /etc/nginx/sites-available/ppanel-api.conf
sudo ln -sf /etc/nginx/sites-available/ppanel-api.conf /etc/nginx/sites-enabled/ppanel-api.conf
sudo nginx -t
sudo systemctl reload nginx
```
### 8.3 启动容器
```bash
cd /opt/ppanel
docker compose -f docker-compose.cloud.yml up -d
```
### 8.4 预检
```bash
chmod +x deploy/scripts/preflight_aws_jp.sh
APP_DIR=/opt/ppanel \
RDS_HOST=<TOKYO_RDS_ENDPOINT> \
REDIS_HOST=127.0.0.1 \
deploy/scripts/preflight_aws_jp.sh
```
## 9. 数据迁移与切换
正式迁移请按:
- [`ops/hifast-aws-jp-migration-runbook-zh.md`](/Users/Apple/code_vpn/vpn/ppanel-server/ops/hifast-aws-jp-migration-runbook-zh.md)
执行。
核心原则:
- 先搭平行环境
- 停机后再导出香港主数据
- 东京验收通过后再切正式域名
- 切换后再重挂 `104` 灾备
## 10. 104 灾备节点常用模板
如果迁移完成后要把 `104.238.220.230` 重挂为东京主站从库,可复用:
- [`deploy/scripts/hifast_mysql_seed_primary_and_replica.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/hifast_mysql_seed_primary_and_replica.sh)
- [`deploy/scripts/hifast_mysql_attach_replica.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/hifast_mysql_attach_replica.sh)
- [`deploy/scripts/hifast_redis_attach_replica.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/hifast_redis_attach_replica.sh)
- [`deploy/scripts/hifast_data_sync_tool.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/hifast_data_sync_tool.sh)
- [`configs/replica-ops.env.example`](./configs/replica-ops.env.example)
## 11. 东京资源创建前置检查
在 AWS 控制台里至少先确认:
- 东京区已启用
- `ap-northeast-1` 可创建 `t4g.large`
- `ap-northeast-1` RDS 可创建 `db.r7g.xlarge`
- ACM / ALB / WAF / S3 服务在东京区可正常使用
- Tokyo 对应配额满足:
- On-Demand Standard vCPU
- ALB 数量
- Elastic IP(如需)
- RDS 实例数
## 12. 当前已知真实进度
截至 `2026-05-20`,已知状态如下:
- 东京 VPC `ppanel-jp-prod` 已创建
- VPC ID: `vpc-0846b23b4a7d64eac`
- VPC CIDR: `10.20.0.0/16`
- 4 个子网在 AWS 控制台里曾填写完成,但提交时控制台 session 失效
- 因此:
- 子网是否真正创建成功,需要重新核实
- IGW / 路由表 / 安全组 / RDS / EC2 / ALB / WAF 都应按“未完成”处理,重新复核
实时状态请以后续更新的 [`configs/resource-inventory.current.md`](./configs/resource-inventory.current.md) 为准。
@@ -0,0 +1,55 @@
AWS_REGION=ap-northeast-1
AWS_ACCOUNT_ID=200810848252
VPC_NAME=ppanel-jp-prod
VPC_ID=
VPC_CIDR=10.20.0.0/16
PUBLIC_SUBNET_A_NAME=ppanel-jp-public-a
PUBLIC_SUBNET_A_AZ=ap-northeast-1a
PUBLIC_SUBNET_A_CIDR=10.20.0.0/24
PUBLIC_SUBNET_C_NAME=ppanel-jp-public-c
PUBLIC_SUBNET_C_AZ=ap-northeast-1c
PUBLIC_SUBNET_C_CIDR=10.20.1.0/24
PRIVATE_SUBNET_A_NAME=ppanel-jp-private-a
PRIVATE_SUBNET_A_AZ=ap-northeast-1a
PRIVATE_SUBNET_A_CIDR=10.20.10.0/24
PRIVATE_SUBNET_C_NAME=ppanel-jp-private-c
PRIVATE_SUBNET_C_AZ=ap-northeast-1c
PRIVATE_SUBNET_C_CIDR=10.20.11.0/24
IGW_NAME=ppanel-jp-igw
PUBLIC_ROUTE_TABLE_NAME=ppanel-jp-public-rt
PRIVATE_ROUTE_TABLE_NAME=ppanel-jp-private-rt
SG_ALB_NAME=ppanel-jp-sg-alb
SG_EC2_NAME=ppanel-jp-sg-ec2
SG_RDS_NAME=ppanel-jp-sg-rds
OPS_SSH_CIDR=CHANGE_ME_TO_YOUR_FIXED_PUBLIC_IP_OR_CIDR
DR_REPLICA_IP=104.238.220.230/32
EC2_NAME=ppanel-app-jp-01
EC2_AMI_FAMILY=ubuntu-24.04
EC2_INSTANCE_TYPE=t4g.large
EC2_DISK_GB=80
EC2_KEY_PAIR=CHANGE_ME
RDS_IDENTIFIER=ppanel-mysql-jp
RDS_DB_NAME=hifast
RDS_ADMIN_USER=admin
RDS_INSTANCE_CLASS=db.r7g.xlarge
RDS_STORAGE_GB=100
ALB_NAME=ppanel-alb-jp
TARGET_GROUP_NAME=ppanel-tg-jp
WAF_NAME=ppanel-waf-jp
PARALLEL_API_DOMAIN=api-jp.hifast.biz
PARALLEL_LOGS_DOMAIN=logs-jp.hifast.biz
PRODUCTION_API_DOMAIN=CHANGE_ME
S3_BACKUP_BUCKET=hifast-prod-backups-200810848252-ap-northeast-1
@@ -0,0 +1,19 @@
AWS_REGION=ap-northeast-1
S3_BUCKET=hifast-prod-backups-200810848252-ap-northeast-1
S3_PREFIX=mysql
BACKUP_DIR=/var/backups/hifast
HOST_TAG=104-standby-for-jp
KEEP_LOCAL_DAYS=3
CHECK_REPLICA=1
MYSQL_HOST=127.0.0.1
MYSQL_PORT=3306
MYSQL_USER=backup_reader
MYSQL_PASSWORD=CHANGE_ME
MYSQL_SOCKET=
MYSQL_DATABASE=hifast
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=CHANGE_ME
@@ -0,0 +1,21 @@
PRIMARY_HOST=ppanel-mysql-jp.<CHANGE_ME>.ap-northeast-1.rds.amazonaws.com
PRIMARY_PORT=3306
PRIMARY_USER=admin
PRIMARY_PASSWORD=CHANGE_ME
PRIMARY_DB=hifast
PRIMARY_REPL_USER=repl
PRIMARY_REPL_PASSWORD=CHANGE_ME
PRIMARY_REPL_HOST=104.238.220.230
PRIMARY_BINLOG_RETENTION_HOURS=24
REPLICA_HOST=127.0.0.1
REPLICA_PORT=3306
REPLICA_USER=root
REPLICA_PASSWORD=
REPLICA_SOCKET=/var/run/mysqld/mysqld.sock
REPLICA_DB=hifast
REPLICA_SOURCE_SSL=1
DUMP_FILE=
@@ -0,0 +1,112 @@
Host: 0.0.0.0
Port: 8080
Debug: false
JwtAuth:
AccessSecret: CHANGE_ME_TO_A_LONG_RANDOM_SECRET
AccessExpire: 604800
Logger:
ServiceName: PPanel
Mode: console
Encoding: plain
TimeFormat: "2006-01-02 15:04:05.000"
Path: logs
Level: info
MaxContentLength: 0
Compress: false
Stat: true
KeepDays: 7
StackCooldownMillis: 100
MaxBackups: 7
MaxSize: 100
Rotation: daily
FileTimeFormat: "2006-01-02T15:04:05.000Z07:00"
MySQL:
Addr: YOUR_TOKYO_RDS_ENDPOINT:3306
Dbname: hifast
Username: admin
Password: CHANGE_ME_TO_TOKYO_RDS_PASSWORD
Config: charset=utf8mb4&parseTime=true&loc=Asia%2FTokyo
MaxIdleConns: 10
MaxOpenConns: 100
SlowThreshold: 1000
Redis:
Host: 127.0.0.1:6379
Pass: CHANGE_ME_TO_TOKYO_REDIS_PASSWORD
DB: 0
PoolSize: 100
MinIdleConns: 10
MaxRetries: 3
PoolTimeout: 4
IdleTimeout: 300
MaxConnAge: 0
DialTimeout: 5
ReadTimeout: 3
WriteTimeout: 3
Trace:
Name: ppanel-server
Endpoint: 127.0.0.1:4317
Sampler: 0.1
Batcher: otlpgrpc
Site:
Host: api-jp.hifast.biz
SiteName: HiFastVPN
Administrator:
Email: admin@example.com
Password: CHANGE_ME_TO_STRONG_ADMIN_PASSWORD
Telegram:
Enable: false
BotID: 0
BotName: ""
BotToken: ""
GroupChatID: ""
EnableNotify: false
WebHookDomain: ""
Kutt:
Enable: false
ApiURL: ""
ApiKey: ""
TargetURL: ""
Domain: ""
OpenInstall:
Enable: false
AppKey: ""
ApiKey: ""
Loki:
Enable: true
URL: "http://localhost:3100"
AppSignature:
AppSecrets:
android-client: CHANGE_ME_ANDROID_SIGNATURE_SECRET
ios-client: CHANGE_ME_IOS_SIGNATURE_SECRET
web-client: CHANGE_ME_WEB_SIGNATURE_SECRET
ValidWindowSeconds: 300
SkipPrefixes:
- /v1/notify/
- /v1/iap/notifications
- /v1/telegram/webhook
- /v1/subscribe/config
Signature:
EnableSignature: false
device:
enable: true
security_secret: CHANGE_ME_DEVICE_SECURITY_SECRET
Register:
EnableTrial: true
EnableTrialEmailWhitelist: true
TrialEmailDomainWhitelist: "gmail.com,outlook.com,icloud.com,qq.com,163.com"
@@ -0,0 +1,23 @@
MYSQL_HOST=127.0.0.1
MYSQL_PORT=3306
MYSQL_USER=root
MYSQL_PASSWORD=CHANGE_ME
MYSQL_SOCKET=
REPL_SOURCE_HOST=ppanel-mysql-jp.cpo0keikgh80.ap-northeast-1.rds.amazonaws.com
REPL_SOURCE_PORT=3306
REPL_SOURCE_USER=repl
REPL_SOURCE_PASSWORD=XwWrQGVWtxmXJ3etHmkFvnRSD54MKYer
REPL_SOURCE_SSL=1
REPL_SOURCE_LOG_FILE=mysql-bin-changelog.000189
REPL_SOURCE_LOG_POS=185053
REPL_SOURCE_AUTO_POSITION=1
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=CHANGE_ME
REDIS_SOURCE_HOST=3.114.29.208
REDIS_SOURCE_PORT=6379
REDIS_SOURCE_USER=
REDIS_SOURCE_PASSWORD=hifast67yj
@@ -0,0 +1,187 @@
# Tokyo Resource Inventory
最后更新:`2026-05-21`
这个文件记录当前东京迁移的真实实施状态,不是示例。
## Region
- AWS account: `hifastvpn (200810848252)`
- Region: `ap-northeast-1`
## Current Status
- 东京迁移方案已在仓库内落地为执行资产
- 东京 VPC 已创建
- 东京子网、IGW、路由表已在 AWS 控制台创建并复核
- 东京三层安全组已在 AWS 控制台创建并复核
- 东京 VPC DNS 开关已开启,可支持公网可访问 RDS
- 东京 S3 备份桶已在 AWS 控制台创建并复核
- 东京 ACM 证书请求已创建,等待 DNS 验证
- 东京 RDS MySQL 已创建完成并可用
- 东京业务 EC2 已创建完成并绑定固定 EIP
- 因当前本机没有可用 AWS CLI 凭据,云上资源状态仍需在 AWS 控制台或已登录环境中复查
## Networking
- VPC
- Name: `ppanel-jp-prod`
- VPC ID: `vpc-0846b23b4a7d64eac`
- CIDR: `10.20.0.0/16`
- Status: `created`
- Public subnet A
- Name: `ppanel-jp-public-a`
- AZ: `ap-northeast-1a`
- CIDR: `10.20.0.0/24`
- Subnet ID: `subnet-091232bdb53e71490`
- Status: `created`
- Public subnet C
- Name: `ppanel-jp-public-c`
- AZ: `ap-northeast-1c`
- CIDR: `10.20.1.0/24`
- Subnet ID: `subnet-01ba0975c525ce8cf`
- Status: `created`
- Private subnet A
- Name: `ppanel-jp-private-a`
- AZ: `ap-northeast-1a`
- CIDR: `10.20.10.0/24`
- Subnet ID: `subnet-0bd13111c02f0edbe`
- Status: `created`
- Private subnet C
- Name: `ppanel-jp-private-c`
- AZ: `ap-northeast-1c`
- CIDR: `10.20.11.0/24`
- Subnet ID: `subnet-0d86c5c756dbc84b2`
- Status: `created`
- Internet Gateway
- Name: `ppanel-jp-igw`
- IGW ID: `igw-028041bcbf63b672c`
- Status: `created`
- Public route table
- Name: `ppanel-jp-public-rt`
- Route Table ID: `rtb-061b101080e4800e5`
- Default route: `0.0.0.0/0 -> igw-028041bcbf63b672c`
- Status: `created`
- Private route table
- Name: `ppanel-jp-private-rt`
- Route Table ID: `rtb-0d7a191a515031c45`
- Status: `created`
## Security
- `sg-alb`
- Name: `ppanel-jp-sg-alb`
- Security Group ID: `sg-0b3a23c31041a5a5a`
- Inbound:
- `80/tcp <- 0.0.0.0/0`
- `443/tcp <- 0.0.0.0/0`
- Status: `created`
- `sg-ec2`
- Name: `ppanel-jp-sg-ec2`
- Security Group ID: `sg-01f2a5a81e7505c91`
- Inbound:
- `80/tcp <- sg-0b3a23c31041a5a5a`
- `22/tcp <- 64.118.144.142/32`
- `6379/tcp <- 104.238.220.230/32`
- Status: `created`
- `sg-rds`
- Name: `ppanel-jp-sg-rds`
- Security Group ID: `sg-0b71db1e2c18b57c0`
- Inbound:
- `3306/tcp <- sg-01f2a5a81e7505c91`
- `3306/tcp <- 104.238.220.230/32`
- Status: `created`
## Compute / Database / Edge
- EC2 `ppanel-app-jp-01`:
- Instance ID: `i-07839130074cd7ed9`
- Type: `c7i.xlarge`
- Platform: `Ubuntu 26.04 / Linux`
- AZ: `ap-northeast-1c`
- VPC: `ppanel-jp-prod (vpc-0846b23b4a7d64eac)`
- Subnet: `ppanel-jp-public-c (subnet-01ba0975c525ce8cf)`
- Private IP: `10.20.1.168`
- Public IP / Elastic IP: `3.114.29.208`
- Public DNS: `ec2-3-114-29-208.ap-northeast-1.compute.amazonaws.com`
- Security group: `ppanel-jp-sg-ec2 (sg-01f2a5a81e7505c91)`
- Key pair: `ppanel-jp-key-20260521`
- Root volume: `gp3 100GiB`
- ENI: `eni-08accb427a470c9f7`
- EIP allocation ID: `eipalloc-038b32d5c0119accf`
- EIP association ID: `eipassoc-09184aa9161b6a4d9`
- Status: `running`
- SSH recovery private key: `deploy/aws/ap-northeast-1/keys/ppanel-jp-recovery`
- SSH recovery public key: `deploy/aws/ap-northeast-1/keys/ppanel-jp-recovery.pub`
- RDS subnet group:
- Name: `ppanel-jp-rds-subnet-group`
- VPC: `vpc-0846b23b4a7d64eac`
- Subnets:
- `subnet-0bd13111c02f0edbe` / `ppanel-jp-private-a`
- `subnet-0d86c5c756dbc84b2` / `ppanel-jp-private-c`
- Status: `created`
- RDS public subnet group:
- Name: `ppanel-jp-rds-public-subnet-group`
- VPC: `vpc-0846b23b4a7d64eac`
- Subnets:
- `subnet-091232bdb53e71490` / `ppanel-jp-public-a`
- `subnet-01ba0975c525ce8cf` / `ppanel-jp-public-c`
- Status: `created`
- RDS `ppanel-mysql-jp`:
- Engine: `MySQL Community 8.4.8`
- Class: `db.r7g.xlarge`
- Storage: `gp3 100GiB`
- Deployment: `Single instance (current actual state)`
- VPC: `ppanel-jp-prod (vpc-0846b23b4a7d64eac)`
- Subnet group: `ppanel-jp-rds-public-subnet-group`
- Security group: `ppanel-jp-sg-rds (sg-0b71db1e2c18b57c0)`
- Master username: `admin`
- Credential management: `self-managed`
- Secrets Manager managed password: `disabled`
- Current master password visibility: `not retrievable from AWS console; reset only`
- Public access: `enabled (set at creation time for external replication)`
- Status: `available`
- Endpoint: `ppanel-mysql-jp.cpo0keikgh80.ap-northeast-1.rds.amazonaws.com`
- Public IP (resolved via public DNS): `52.196.204.186`
- Connection test from Tokyo EC2:
- `mysql -h ppanel-mysql-jp.cpo0keikgh80.ap-northeast-1.rds.amazonaws.com -u admin -e "select 1"`
- Result: `ERROR 1045 (28000): Access denied for user 'admin'@'ip-10-20-1-168.ap-northeast-1.compute.internal' (using password: NO)`
- Meaning: `network path and security group are working; only the password is missing`
- Current admin password: `TkyRds20260521!N9mQ8sKe2vLp7Xa`
- External replica prep for `104.238.220.230`:
- binlog retention hours: `24`
- replication user: `repl@104.238.220.230`
- replication password: `XwWrQGVWtxmXJ3etHmkFvnRSD54MKYer`
- current binlog file: `mysql-bin-changelog.000189`
- current binlog position: `185053`
- ALB `ppanel-alb-jp`: `not created`
- WAF `ppanel-waf-jp`: `not created`
- ACM certificate in `ap-northeast-1`:
- Certificate ID: `29d0b9b6-ab37-44d9-ad9e-18fa7e9aae3a`
- Domains:
- `api-jp.hifast.biz`
- `logs-jp.hifast.biz`
- Status: `pending_validation`
- Route 53 hosted zone in current AWS account: `not found`
- S3 backup bucket `hifast-prod-backups-200810848252-ap-northeast-1`: `created`
## Domains
- Parallel API domain: `api-jp.hifast.biz`
- Parallel logs domain: `logs-jp.hifast.biz`
- Production API domain: `pending user final confirmation`
- ACM DNS validation records pending external DNS add:
- `api-jp.hifast.biz`
- Name: `_0de5970dfbadaf46759447b2ea627a10.api-jp.hifast.biz.`
- Type: `CNAME`
- Value: `_6a632a5b85c5b3f304cc492090b741b3.jkddzztszm.acm-validations.aws.`
- `logs-jp.hifast.biz`
- Name: `_349a2b2bc4678d76c3ab341ccf73db61.logs-jp.hifast.biz.`
- Type: `CNAME`
- Value: `_74ced20dc96aa39070188605cf0ced18.jkddzztszm.acm-validations.aws.`
## DR
- DR host: `104.238.220.230`
- Planned MySQL upstream after cutover: `Tokyo RDS`
- Planned Redis upstream after cutover: `Tokyo EC2 public IP`
@@ -0,0 +1,69 @@
# Tokyo Resource Inventory Example
Use this file as the single source of truth while building the Tokyo environment.
## Region
- AWS account: `hifastvpn (200810848252)`
- Region: `ap-northeast-1`
## DNS
- Production API domain: `CHANGE_ME`
- Parallel API domain: `api-jp.hifast.biz`
- Parallel logs domain: `logs-jp.hifast.biz`
## Networking
- VPC name: `ppanel-jp-prod`
- VPC CIDR: `10.20.0.0/16`
- Public subnet A: `10.20.0.0/24`
- Public subnet C: `10.20.1.0/24`
- Private subnet A: `10.20.10.0/24`
- Private subnet C: `10.20.11.0/24`
- Ops CIDR for SSH: `CHANGE_ME`
## Compute
- EC2 name: `ppanel-app-jp-01`
- EC2 type: `t4g.large`
- EC2 disk: `gp3 80GB`
- SSH key pair: `CHANGE_ME`
## Database
- RDS identifier: `ppanel-mysql-jp`
- RDS engine: `MySQL 8.4`
- RDS class: `db.r7g.xlarge`
- RDS storage: `gp3 100GB`
- DB name: `hifast`
- DB admin user: `admin`
## Cache
- Redis container: `hifast-redis`
- Redis port: `6379`
- Redis password: `CHANGE_ME`
## Security / Secrets
- JWT secret: `CHANGE_ME`
- Admin email: `CHANGE_ME`
- Admin password: `CHANGE_ME`
- Android app signature secret: `CHANGE_ME`
- iOS app signature secret: `CHANGE_ME`
- Web app signature secret: `CHANGE_ME`
- Device security secret: `CHANGE_ME`
## Backup
- S3 backup bucket: `hifast-prod-backups-200810848252-ap-northeast-1`
- Versioning: `Enabled`
## DR
- DR host: `104.238.220.230`
- MySQL repl user: `repl`
- MySQL repl password: `CHANGE_ME`
- Redis source password: `CHANGE_ME`
@@ -0,0 +1,7 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACBsJxZDjKvaIdVjer3QMHRYw43wkVnzHurA2TQqHlr1YwAAAKBaQXT3WkF0
9wAAAAtzc2gtZWQyNTUxOQAAACBsJxZDjKvaIdVjer3QMHRYw43wkVnzHurA2TQqHlr1Yw
AAAEArWQWWwPoJp+za5JhSnrE0Pw1/TtqWRrdY5e8hULqYDGwnFkOMq9oh1WN6vdAwdFjD
jfCRWfMe6sDZNCoeWvVjAAAAF0FwcGxlQE1hY0Jvb2stUHJvLmxvY2FsAQIDBAUG
-----END OPENSSH PRIVATE KEY-----
@@ -0,0 +1 @@
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGwnFkOMq9oh1WN6vdAwdFjDjfCRWfMe6sDZNCoeWvVj Apple@MacBook-Pro.local
@@ -0,0 +1,34 @@
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
client_max_body_size 20m;
access_log /var/log/nginx/ppanel-access.log;
error_log /var/log/nginx/ppanel-error.log warn;
location / {
proxy_http_version 1.1;
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
proxy_connect_timeout 10s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
location = /nginx_status {
stub_status;
access_log off;
allow 127.0.0.1;
deny all;
}
}
@@ -0,0 +1,17 @@
[Unit]
Description=Hifast MySQL backup to S3
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
User=root
Group=root
EnvironmentFile=/root/backup-to-s3.env
ExecStart=/usr/bin/env bash -lc 'exec /opt/ppanel/deploy/scripts/mysql_backup_to_s3.sh'
Nice=10
IOSchedulingClass=best-effort
IOSchedulingPriority=7
[Install]
WantedBy=multi-user.target
+11
View File
@@ -0,0 +1,11 @@
[Unit]
Description=Run Hifast MySQL backup to S3 every 10 minutes
[Timer]
OnCalendar=*:0/10
Persistent=true
RandomizedDelaySec=30
Unit=hifast-mysql-backup.service
[Install]
WantedBy=timers.target
+560
View File
@@ -0,0 +1,560 @@
# 提现 & 文件上传 & 日志上报 — 用户端 API 接口文档
> 基于 ppanel-server 源码整理,所有时间戳均为**秒级 Unix**。
---
## 目录
- [一、提现接口](#一提现接口)
- [1.1 申请提现](#11-申请提现)
- [1.2 取消提现](#12-取消提现)
- [1.3 查询提现记录](#13-查询提现记录)
- [二、枚举值与状态流转](#二枚举值与状态流转)
- [三、文件上传接口](#三文件上传接口)
- [3.1 直传文件(小文件)](#31-直传文件小文件)
- [3.2 初始化上传(大文件 — 预签名)](#32-初始化上传大文件--预签名)
- [3.3 确认上传完成](#33-确认上传完成)
- [四、日志查询接口 (Admin)](#四日志查询接口-admin)
- [4.1 错误日志列表](#41-错误日志列表)
- [4.2 错误日志详情](#42-错误日志详情)
- [4.3 日志消息原始详情](#43-日志消息原始详情)
---
## 一、提现接口
> 认证方式: JWT(用户登录态)
>
> 路由前缀: `/v1/public/user`
### 1.1 申请提现
提交佣金提现申请,创建一条待审核的提现记录。
```
POST /v1/public/user/commission_withdraw
```
**Request Body**
| 字段 | 类型 | 必填 | 校验 | 说明 |
|------|------|------|------|------|
| `amount` | int64 | 是 | — | 提现金额(分) |
| `method` | uint8 | 是 | `oneof=0 1 2 3` | 收款方式(见枚举表) |
| `content` | string | 否 | — | 提现备注 |
| `account` | string | 条件必填 | — | 收款账号 |
| `qr_code_url` | string | 条件必填 | — | 收款码图片 URL |
**各收款方式的必填字段**
| method | 收款方式 | 必填字段 |
|--------|---------|---------|
| `1` 支付宝 | `qr_code_url` | 收款码图片 |
| `2` 微信 | `qr_code_url` | 收款码图片 |
| `3` 银行卡 | `account` | 收款账号 |
| `0` 其他 | `account` 必填 |
**Request 示例**
```json
{
"amount": 5000,
"content": "提现到支付宝",
"method": 1,
"account": "user@example.com",
"qr_code_url": "https://cdn.example.com/qrcode/alipay.png"
}
```
**Response**: [`WithdrawalLog`](#withdrawallog-对象)
---
### 1.2 取消提现
用户取消自己的待审核提现申请,佣金退回账户。
```
POST /v1/public/user/withdrawal_cancel
```
**Request Body**
| 字段 | 类型 | 必填 | 校验 | 说明 |
|------|------|------|------|------|
| `withdrawal_id` | int64 | 是 | `required,gt=0` | 提现记录 ID |
**Request 示例**
```json
{
"withdrawal_id": 123
}
```
**Response**: [`WithdrawalLog`](#withdrawallog-对象)(状态已变为 `3=已取消`
---
### 1.3 查询提现记录
分页查询当前用户的提现记录(自动按 JWT 中的 userId 过滤)。
```
GET /v1/public/user/withdrawal_log
```
**Query 参数**
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `page` | int | 否 | 页码,默认 1 |
| `size` | int | 否 | 每页条数,默认 10 |
**Request 示例**
```
GET /v1/public/user/withdrawal_log?page=1&size=10
```
**Response**
```json
{
"list": [WithdrawalLog, ...],
"total": 25
}
```
---
## 二、枚举值与状态流转
### 提现状态 (`status`)
| 值 | 说明 |
|----|------|
| 0 | 待审核 |
| 1 | 已通过 |
| 2 | 已拒绝 |
| 3 | 已取消 |
### 收款方式 (`method`)
| 值 | 说明 |
|----|------|
| 0 | 其他 |
| 1 | 支付宝 |
| 2 | 微信 |
| 3 | 银行卡 |
### 状态流转
```
┌── 管理员通过 ──▶ 已通过 (1)
待审核 (0) ──────┼── 管理员拒绝 ──▶ 已拒绝 (2)
└── 用户取消 ───▶ 已取消 (3)
```
### WithdrawalLog 对象
所有提现接口共用的响应结构:
```json
{
"id": 1,
"user_id": 100,
"amount": 5000,
"content": "提现备注",
"status": 0,
"reason": "",
"method": 1,
"account": "user@example.com",
"qr_code_url": "https://cdn.example.com/qrcode/alipay.png",
"created_at": 1716700000,
"updated_at": 1716700000
}
```
| 字段 | 类型 | 说明 |
|------|------|------|
| `id` | int64 | 提现记录 ID |
| `user_id` | int64 | 用户 ID |
| `amount` | int64 | 提现金额(分) |
| `content` | string | 提现备注 |
| `status` | uint8 | 状态(见枚举表) |
| `reason` | string | 拒绝原因(仅 status=2 时有值,其余 omitempty |
| `method` | uint8 | 收款方式(见枚举表) |
| `account` | string | 收款账号 |
| `qr_code_url` | string | 收款码图片 URL |
| `created_at` | int64 | 创建时间(秒级 Unix |
| `updated_at` | int64 | 更新时间(秒级 Unix |
---
## 三、文件上传接口
> 认证方式: JWT + DeviceMiddleware(用户登录态 + 设备认证)
>
> 路由前缀: `/v1/public/file`
>
> 存储后端: S3 兼容(RustFS
提供两种上传方式:
| 方式 | 适用场景 | 流程 |
|------|---------|------|
| **直传** | 小文件(收款码等) | 1 次请求,`multipart/form-data` 直接上传 |
| **预签名** | 大文件 / 客户端直传 S3 | init → 客户端 PUT 到预签名 URL → complete 确认 |
---
### 3.1 直传文件(小文件)
通过 `multipart/form-data` 直接上传文件到服务端,服务端转存至 S3。
```
POST /v1/public/file/upload
Content-Type: multipart/form-data
```
**Form 参数**
| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `biz_type` | string | 是 | 业务类型(如 `withdrawal_qrcode``avatar` 等) |
| `file` | file | 是 | 上传的文件(multipart |
**cURL 示例**
```bash
curl -X POST /v1/public/file/upload \
-H "Authorization: Bearer <token>" \
-F "biz_type=withdrawal_qrcode" \
-F "file=@/path/to/alipay_qr.png"
```
**Response**
```json
{
"file_id": "a1b2c3d4e5f678901234",
"file_name": "alipay_qr.png",
"object_key": "app-upload/2026/05/27/100/alipay_qr.png__a1b2c3d4e5f678901234",
"size": 52480,
"content_type": "image/png",
"etag": "\"d41d8cd98f00b204e9800998ecf8427e\"",
"status": "completed"
}
```
**FileUploadResponse 字段说明**
| 字段 | 类型 | 说明 |
|------|------|------|
| `file_id` | string | 文件唯一 ID24 字符 hex |
| `file_name` | string | 原始文件名 |
| `object_key` | string | S3 对象路径 |
| `size` | int64 | 文件大小(字节) |
| `content_type` | string | MIME 类型 |
| `etag` | string | S3 ETag |
| `status` | string | 状态,直传成功即 `completed` |
---
### 3.2 初始化上传(大文件 — 预签名)
获取 S3 预签名 URL,客户端直接 PUT 到 S3,避免文件经过服务端。
```
POST /v1/public/file/upload/init
```
**Request Body**
| 字段 | 类型 | 必填 | 校验 | 说明 |
|------|------|------|------|------|
| `biz_type` | string | 是 | `required` | 业务类型 |
| `file_name` | string | 是 | `required` | 文件名 |
| `content_type` | string | 是 | `required` | MIME 类型(如 `image/png` |
| `size` | int64 | 是 | `required` | 文件大小(字节) |
| `sha256` | string | 否 | — | 文件 SHA256(可选校验) |
**Request 示例**
```json
{
"biz_type": "withdrawal_qrcode",
"file_name": "wechat_qr.png",
"content_type": "image/png",
"size": 102400,
"sha256": "e3b0c44298fc1c149afbf4c8996fb924..."
}
```
**Response**
```json
{
"file_id": "b2c3d4e5f6789012345a",
"object_key": "app-upload/2026/05/27/100/wechat_qr.png__b2c3d4e5f6789012345a",
"upload_url": "https://s3.example.com/bucket/app-upload/...?X-Amz-Signature=...",
"method": "PUT",
"headers": {
"Content-Type": "image/png"
},
"expired_at": 1716700300
}
```
**FileUploadInitResponse 字段说明**
| 字段 | 类型 | 说明 |
|------|------|------|
| `file_id` | string | 文件唯一 ID |
| `object_key` | string | S3 对象路径 |
| `upload_url` | string | 预签名上传 URL |
| `method` | string | HTTP 方法(`PUT` |
| `headers` | map | 上传时需携带的请求头 |
| `expired_at` | int64 | 预签名过期时间(秒级 Unix,默认 300 秒) |
**客户端上传流程**
```
1. 调用 /upload/init 获取 upload_url
2. 用返回的 method + headers 直接上传文件到 upload_url
3. 上传成功后调用 /upload/complete 确认
```
---
### 3.3 确认上传完成
客户端通过预签名 URL 上传完成后,调用此接口确认文件状态。
```
POST /v1/public/file/upload/complete
```
**Request Body**
| 字段 | 类型 | 必填 | 校验 | 说明 |
|------|------|------|------|------|
| `file_id` | string | 是 | `required` | init 返回的 file_id |
**Request 示例**
```json
{
"file_id": "b2c3d4e5f6789012345a"
}
```
**Response**
```json
{
"file_id": "b2c3d4e5f6789012345a",
"object_key": "app-upload/2026/05/27/100/wechat_qr.png__b2c3d4e5f6789012345a",
"size": 102400,
"content_type": "image/png",
"etag": "\"d41d8cd98f00b204e9800998ecf8427e\"",
"status": "completed"
}
```
**FileUploadCompleteResponse 字段说明**
| 字段 | 类型 | 说明 |
|------|------|------|
| `file_id` | string | 文件唯一 ID |
| `object_key` | string | S3 对象路径 |
| `size` | int64 | 实际文件大小(S3 HeadObject 获取) |
| `content_type` | string | MIME 类型 |
| `etag` | string | S3 ETag |
| `status` | string | `completed` |
**校验规则**
- 文件大小不能超过配置的 `S3.MaxUploadSize`
- Content-Type 必须在配置的 `S3.AllowedContentTypes` 白名单内(若配置了)
- complete 时会校验 S3 上的实际文件大小是否与 init 声明的一致
- 只能确认自己发起的上传(userId 校验)
---
## 四、日志查询接口 (Admin)
> 认证方式: AuthMiddleware(管理员权限)
>
> 路由前缀: `/v1/admin/log`
>
> 数据来源: `log_message` 表(客户端上报的错误/崩溃日志)
---
### 4.1 错误日志列表
分页查询客户端上报的错误日志,支持多维度筛选。
```
GET /v1/admin/log/error_message/list
```
**Query 参数**
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `page` | int | 是 | 页码 |
| `size` | int | 是 | 每页条数 |
| `platform` | string | 否 | 平台筛选(ios / android / windows / mac / harmony |
| `level` | uint8 | 否 | 日志级别 |
| `user_id` | int64 | 否 | 用户 ID |
| `device_id` | string | 否 | 设备 ID |
| `error_code` | string | 否 | 错误码 |
| `keyword` | string | 否 | 关键字搜索(匹配 message) |
| `start` | int64 | 否 | 开始时间(秒级 Unix) |
| `end` | int64 | 否 | 结束时间(秒级 Unix) |
**Request 示例**
```
GET /v1/admin/log/error_message/list?page=1&size=20&platform=ios&start=1716600000&end=1716700000
```
**Response**
```json
{
"total": 50,
"list": [
{
"id": 1,
"platform": "ios",
"app_version": "2.1.0",
"os_name": "iOS",
"os_version": "17.5",
"device_id": "A1B2C3D4",
"user_id": 100,
"session_id": "sess_xxx",
"level": 3,
"error_code": "VPN_CONNECT_FAIL",
"message": "Failed to establish VPN tunnel",
"created_at": 1716700000
}
]
}
```
**ErrorLogMessage 字段说明**
| 字段 | 类型 | 说明 |
|------|------|------|
| `id` | int64 | 日志 ID |
| `platform` | string | 平台 |
| `app_version` | string | 客户端版本 |
| `os_name` | string | 操作系统名称 |
| `os_version` | string | 操作系统版本 |
| `device_id` | string | 设备 ID |
| `user_id` | int64 | 用户 ID |
| `session_id` | string | 会话 ID |
| `level` | uint8 | 日志级别 |
| `error_code` | string | 错误码 |
| `message` | string | 错误消息 |
| `created_at` | int64 | 创建时间(秒级 Unix |
---
### 4.2 错误日志详情
获取单条错误日志的完整详情(列表字段 + 堆栈/IP/UA 等扩展信息)。
```
GET /v1/admin/log/error_message/detail
```
**Response**
```json
{
"id": 1,
"platform": "ios",
"app_version": "2.1.0",
"os_name": "iOS",
"os_version": "17.5",
"device_id": "A1B2C3D4",
"user_id": 100,
"session_id": "sess_xxx",
"level": 3,
"error_code": "VPN_CONNECT_FAIL",
"message": "Failed to establish VPN tunnel",
"stack": "at VPNManager.connect() line 42\nat ...",
"client_ip": "1.2.3.4",
"user_agent": "PPanel/2.1.0 iOS/17.5",
"locale": "zh-CN",
"occurred_at": 1716700000,
"created_at": 1716700000
}
```
**相比列表额外返回的字段**
| 字段 | 类型 | 说明 |
|------|------|------|
| `stack` | string | 堆栈信息 |
| `client_ip` | string | 客户端 IP |
| `user_agent` | string | User-Agent |
| `locale` | string | 客户端语言/地区 |
| `occurred_at` | int64 | 错误发生时间(秒级 Unix) |
---
### 4.3 日志消息原始详情
获取单条 `log_message` 的完整原始数据(含 context、digest 等全量字段)。
```
GET /v1/admin/log/message/detail
```
**Query 参数**
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `id` | int64 | 是 | 日志消息 ID |
**Response**
```json
{
"id": 1,
"platform": "ios",
"app_version": "2.1.0",
"os_name": "iOS",
"os_version": "17.5",
"device_id": "A1B2C3D4",
"user_id": 100,
"session_id": "sess_xxx",
"level": 3,
"error_code": "VPN_CONNECT_FAIL",
"message": "Failed to establish VPN tunnel",
"stack": "at VPNManager.connect() line 42\nat ...",
"context": { "server_id": 5, "protocol": "vmess" },
"client_ip": "1.2.3.4",
"user_agent": "PPanel/2.1.0 iOS/17.5",
"locale": "zh-CN",
"digest": "sha256_abc123...",
"occurred_at": 1716700000,
"created_at": 1716700000
}
```
**相比详情额外返回的字段**
| 字段 | 类型 | 说明 |
|------|------|------|
| `context` | any | 附加上下文(原始 JSON |
| `digest` | string | 内容摘要(用于去重) |
@@ -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` 只做记录不做去重 |
+190
View File
@@ -0,0 +1,190 @@
# TAPI 文件上传接入说明
本文档说明 `https://tapi.hifast.biz/v1/public/file/upload` 相关上传接口的推荐接入方式、签名规则与常见排查方式。
## 总览
上传能力包含两类接入方式:
- 推荐方式:`init -> S3 PUT -> complete`
- 兼容方式:`/upload` multipart 直传
推荐优先使用预签名三段式,因为:
- 现有签名串包含 `BODY_SHA256`
- `/upload``multipart/form-data`
- multipart 原始 body 的签名和调试成本更高
- `init``complete` 是 JSON,更适合客户端和 Apifox 调试
## 签名生效逻辑
项目保持现有旧逻辑,不做强制签名改造:
- `Signature.EnableSignature = false` 时:不校验签名
- `Signature.EnableSignature = true` 且未携带 `X-App-Id` 时:不校验签名,兼容老客户端
- `Signature.EnableSignature = true` 且携带 `X-App-Id` 时:必须同时携带并校验
- `X-Timestamp`
- `X-Nonce`
- `X-Signature`
这意味着:
- 新客户端建议始终带完整签名头
- 老客户端如果没有 `X-App-Id`,仍可按旧逻辑访问
## 签名头定义
- `X-App-Id`: 客户端标识,例如 `ios-client`
- `X-Timestamp`: Unix 秒级时间戳
- `X-Nonce`: 每次请求唯一随机串
- `X-Signature`: `HMAC-SHA256` 结果的十六进制小写字符串
## StringToSign 规则
StringToSign 由下面 7 段按换行符 `\n` 拼接:
```text
METHOD
PATH
CANONICAL_QUERY
BODY_SHA256
X-App-Id
X-Timestamp
X-Nonce
```
说明:
- `METHOD`HTTP 方法大写,例如 `POST`
- `PATH`:请求路径,例如 `/v1/public/file/upload/init`
- `CANONICAL_QUERY`:按 key 排序后的 query string,没有 query 则为空字符串
- `BODY_SHA256`:请求体原始字节的 SHA-256 十六进制小写
- 其余三项直接使用请求头值
签名计算方式:
```text
signature = hex_lower(HMAC_SHA256(app_secret, string_to_sign))
```
时间窗与防重放:
- `X-Timestamp` 默认有效时间窗是 300 秒
- `X-Nonce` 在有效时间窗内不能重复使用
## 推荐接入:预签名三段式
### 1. 初始化上传
请求:
```bash
curl -X POST 'https://tapi.hifast.biz/v1/public/file/upload/init' \
-H 'Accept: application/json, text/plain, */*' \
-H 'Content-Type: application/json' \
-H 'authorization: your-token' \
-H 'X-App-Id: ios-client' \
-H 'X-Timestamp: 1778776400' \
-H 'X-Nonce: nonce-001' \
-H 'X-Signature: your-signature' \
-d '{
"biz_type": "app-package",
"file_name": "demo.zip",
"content_type": "application/zip",
"size": 123456,
"sha256": ""
}'
```
典型返回:
```json
{
"code": 200,
"msg": "success",
"data": {
"file_id": "c29274ee26ab5aa211e0396e",
"object_key": "app-upload/app-package/519/2026/05/c29274ee26ab5aa211e0396e_demo.zip",
"upload_url": "https://bucket.s3.ap-east-1.amazonaws.com/...",
"method": "PUT",
"headers": {
"Content-Type": "application/zip"
},
"expired_at": 1778776715
}
}
```
### 2. 直传 S3
这一步是直接上传二进制文件到 S3,不走业务签名中间件。
```bash
curl -X PUT 'https://bucket.s3.ap-east-1.amazonaws.com/...' \
-H 'Content-Type: application/zip' \
--upload-file '/tmp/demo.zip'
```
说明:
- `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 秒
- 成功时 S3 常见返回 `200``204`
### 3. 完成上传
```bash
curl -X POST 'https://tapi.hifast.biz/v1/public/file/upload/complete' \
-H 'Accept: application/json, text/plain, */*' \
-H 'Content-Type: application/json' \
-H 'authorization: your-token' \
-H 'X-App-Id: ios-client' \
-H 'X-Timestamp: 1778776405' \
-H 'X-Nonce: nonce-002' \
-H 'X-Signature: your-signature' \
-d '{
"file_id": "c29274ee26ab5aa211e0396e"
}'
```
## 兼容接入:单接口 multipart 直传
接口:
- `POST /v1/public/file/upload`
表单字段:
- `biz_type`
- `file`
说明:
- 该接口继续保留,兼容旧客户端
- 如果请求带了 `X-App-Id`,就按现有逻辑验签
- 如果没有 `X-App-Id`,仍按旧逻辑放行
- 如果要给该接口加签,签名时必须对原始 multipart body 计算 `BODY_SHA256`
- 允许的 `Content-Type` 与预签名三段式一致;multipart 文件字段未显式携带 `Content-Type` 时,服务端会基于文件内容嗅探常见类型。
## 常见错误码
- `200`: 成功
- `400`: 参数错误
- `400 content_type is not allowed`: 文件 `Content-Type` 不在 `S3.AllowedContentTypes` 白名单内
- `40008`: 缺少签名头
- `40009`: 签名已过期
- `40010`: 签名无效
- `40011`: nonce 重放
- `10001`: 上传元数据不存在或对象不存在
## 排查建议
- `40008`:确认带了 `X-App-Id` 后,也同时带上 `X-Timestamp / X-Nonce / X-Signature`
- `40009`:检查客户端时间是否偏差过大
- `40010`:确认 `PATH`、query 排序、body 原始字节、secret 是否完全一致
- `40011`:确保每次请求都生成新的 `X-Nonce`
- `complete` 失败:确认 S3 `PUT` 已成功,且上传大小与 `init.size` 一致
+144
View File
@@ -0,0 +1,144 @@
# 提现接口文档
## 基础信息
| 项目 | 值 |
|------|-----|
| Base URL | `/v1/public/user` |
| 认证方式 | JWT Token`AuthMiddleware` + `DeviceMiddleware` |
| 数据表 | `user_withdrawal` |
## 数据模型
### user_withdrawal 表
| 字段 | 类型 | 说明 |
|------|------|------|
| `id` | int64 | 主键 |
| `user_id` | int64 | 用户 ID |
| `amount` | int64 | 提现金额(单位:分) |
| `content` | text | 收款信息(账号、姓名等) |
| `status` | tinyint | 0=待审核, 1=已通过, 2=已拒绝 |
| `reason` | varchar(500) | 拒绝原因(通过时为空) |
| `created_at` | datetime | 创建时间 |
| `updated_at` | datetime | 更新时间 |
### status 枚举
| 值 | 含义 | 说明 |
|----|------|------|
| 0 | Pending(待审核) | 用户提交申请后的初始状态 |
| 1 | Approved(已通过) | 管理员审核通过,佣金已扣减 |
| 2 | Rejected(已拒绝) | 管理员拒绝,无需退款(申请时未扣款) |
---
## 用户端接口
### 1. 申请提现
申请佣金提现,创建一条待审核记录。申请时**不扣余额**,管理员审核通过后才扣。
```
POST /v1/public/user/commission_withdraw
```
#### 请求体
```json
{
"amount": 1000,
"content": "支付宝:138xxxx1234 / 张三"
}
```
| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `amount` | int64 | 是 | 提现金额(单位:分) |
| `content` | string | 是 | 收款信息(支付宝/银行卡等) |
#### 成功响应
```json
{
"data": {
"id": 1,
"user_id": 10001,
"amount": 1000,
"content": "支付宝:138xxxx1234 / 张三",
"status": 0,
"reason": "",
"created_at": 1716624000000,
"updated_at": 1716624000000
}
}
```
> **注意**:此接口的 `created_at` / `updated_at` 返回**毫秒级**时间戳(`.UnixMilli()`),与项目其他接口的秒级时间戳不一致。
#### 业务逻辑
1. 查询该用户所有 status=0(待审核)的提现记录,求和得 `pendingTotal`
2. 校验可用余额:`commission >= amount + pendingTotal`
3. 创建 `user_withdrawal` 记录,status=0
4. **不扣减** `user.commission`,等审核通过才扣
#### 错误码
| 错误码 | 常量 | 说明 |
|--------|------|------|
| 20010 | `UserCommissionNotEnough` | 可用余额不足(余额 = commission - 所有 pending 提现总额) |
| 40005 | `InvalidAccess` | 未登录 / Token 无效 |
#### 源码位置
- Handler: `internal/handler/public/user/commissionWithdrawHandler.go`
- Logic: `internal/logic/public/user/commissionWithdrawLogic.go`
---
### 2. 查询提现记录
分页查询当前用户的提现记录。
```
GET /v1/public/user/withdrawal_log
```
#### 请求参数(Query
| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `page` | int | 否 | 页码 |
| `size` | int | 否 | 每页数量 |
#### 成功响应
```json
{
"data": {
"list": [
{
"id": 1,
"user_id": 10001,
"amount": 1000,
"content": "支付宝:138xxxx1234",
"status": 0,
"reason": "",
"created_at": 1716624000,
"updated_at": 1716624000
}
],
"total": 1
}
}
```
#### 源码位置
- Handler: `internal/handler/public/user/queryWithdrawalLogHandler.go`
- Logic: `internal/logic/public/user/queryWithdrawalLogLogic.go`
> **Warning**: Logic 层尚未实现(仍为 TODO),调用会返回空响应。
---
+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)的返回结构同步,避免前端类型联动断裂。
+9 -8
View File
@@ -6,7 +6,7 @@
# 4. 运行: docker-compose -f docker-compose.cloud.yml up -d
#
# 网络说明:
# ppanel-server 使用 host 网络(可出外网,直接访问 AWS RDS/ElastiCache 私网地址
# ppanel-server 使用 host 网络(可出外网,直接访问 AWS RDS / 本机 Redis
# 监控服务(Loki/Tempo/Grafana/Prometheus)在 ppanel_net bridge 网络中
# Tempo(4317) 将端口映射到 127.0.0.1ppanel-server 通过 host 网络访问
# 监控端口绑定 127.0.0.1,需通过 SSH 隧道或 Nginx 反代访问
@@ -19,9 +19,10 @@ services:
# ----------------------------------------------------
# 1. 业务后端 (PPanel Server)
# host 网络:可出外网,直接访问 AWS RDS/Redis;通过 127.0.0.1 访问 Tempo
# PPANEL_SERVER_TAG 由 CI/CD 传入不可变镜像标签(如 git SHA)
# ----------------------------------------------------
ppanel-server:
image: registry.kxsw.us/vpn-server:${PPANEL_SERVER_TAG:-latest}
image: registry.kxsw.us/vpn-server:${PPANEL_SERVER_TAG:?please set PPANEL_SERVER_TAG to an immutable image tag}
container_name: ppanel-server
restart: always
volumes:
@@ -119,11 +120,11 @@ services:
# 或配置 Nginx 反代(建议加认证)
# ----------------------------------------------------
grafana:
image: grafana/grafana:latest
image: grafana/grafana:13.0.1
container_name: ppanel-grafana
restart: always
ports:
- "127.0.0.1:3333:3000" # 仅本机可访问,需 SSH 隧道或 Nginx 反代
- "3333:3000" # 仅本机可访问,需 SSH 隧道或 Nginx 反代
environment:
- GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD:?请在 .env 文件中设置 GRAFANA_PASSWORD}
- GF_USERS_ALLOW_SIGN_UP=false
@@ -154,7 +155,7 @@ services:
# 6. Prometheus (指标采集)
# ----------------------------------------------------
prometheus:
image: prom/prometheus:latest
image: prom/prometheus:v3.11.3
container_name: ppanel-prometheus
restart: always
ports:
@@ -179,7 +180,7 @@ services:
# 7. Nginx Exporter (监控宿主机 Nginx)
# ----------------------------------------------------
nginx-exporter:
image: nginx/nginx-prometheus-exporter:latest
image: nginx/nginx-prometheus-exporter:1.5.0
container_name: ppanel-nginx-exporter
restart: always
command:
@@ -198,7 +199,7 @@ services:
# 8. Node Exporter (宿主机监控)
# ----------------------------------------------------
node-exporter:
image: prom/node-exporter:latest
image: prom/node-exporter:v1.11.1
container_name: ppanel-node-exporter
restart: always
volumes:
@@ -221,7 +222,7 @@ services:
# 9. cAdvisor (容器监控)
# ----------------------------------------------------
cadvisor:
image: gcr.io/cadvisor/cadvisor:latest
image: gcr.io/cadvisor/cadvisor:v0.55.1
container_name: ppanel-cadvisor
restart: always
volumes:
+16 -1
View File
@@ -61,6 +61,21 @@ Trace: # 链路追踪配置 (OpenTelemetry)
Batcher: otlpgrpc # 本地开发留空""; 生产填 otlpgrpc
Endpoint: "127.0.0.1:4317" # host 网络模式; bridge 模式改为 tempo:4317
S3:
Enable: false
Region: ""
Bucket: ""
Endpoint: ""
AccessKey: ""
SecretKey: ""
SessionToken: ""
Prefix: "app-upload"
PublicBaseURL: ""
UsePathStyle: false
PresignExpireSeconds: 300
MaxUploadSize: 104857600
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:
enable: true # 开启设备加密通信
security_secret: "" # AES加密密钥,需要和App端一致,key=SHA256(security_secret)[:32]
@@ -72,4 +87,4 @@ Administrator:
Register:
EnableTrial: true
EnableTrialEmailWhitelist: true
TrialEmailDomainWhitelist: "facebook.com,yahoo.com,qq.com,live.com,outlook.com,msn.com,example.com,go.com,aol.com,free.fr,aliyun.com,163.com,yandex.ru,indiatimes.com,alibaba.com,geocities.com,about.com,naver.com,netscape.com,yahoo.co.jp,earthlink.net,zoho.com,sky.com,mail.ru,angelfire.com,uol.com.br,spb.ru,yandex.com,globo.com,gmail.com,medscape.com,space.com,discovery.com,t-online.de,mac.com,icloud.com,homestead.com,lycos.com,web.id,nus.edu.sg,altavista.com,berlin.de,rambler.ru,pp.ua,comcast.net,sapo.pt,msk.ru,ancestry.com,daum.net,proton.me,law.com,bt.com,techspot.com,icq.com,sina.cn,libero.it,test.com,yourdomain.com,docomo.ne.jp,wp.pl,hotmail.com,orange.fr,onet.pl,me.com,india.com,kansascity.com,wanadoo.fr,fortunecity.com,web.de,terra.com.br,att.net,canada.com,skynet.be,ya.ru,excite.com,detik.com,compuserve.com,ig.com.br,zp.ua,gmx.net,xoom.com,mindspring.com,freeserve.co.uk,interia.pl,excite.co.jp,test.de,shaw.ca,virgilio.it,chez.com,rr.com,freenet.de,ntlworld.com,seznam.cz,arcor.de,tiscali.it,sympatico.ca,sina.com,gazeta.pl,care2.com,yam.com,r7.com,telenet.be,rcn.com,geek.com,sfr.fr,hotbot.com,cox.net,blueyonder.co.uk,tom.com,virginmedia.com,btinternet.com,iinet.net.au,rogers.com,ireland.com,pochta.ru,ozemail.com.au,catholic.org,bluewin.ch,chat.ru,virgin.net,verizon.net,erols.com,lycos.de,lycos.co.uk,protonmail.com,doityourself.com,home.nl,nate.com,casino.com,o2.co.uk,terra.es,mail.com,albawaba.com,126.com,www.com,planet.nl,sanook.com,21cn.com,online.de,name.com,i.ua,centrum.cz,rin.ru,aol.co.uk,voila.fr,walla.co.il,poste.it,netcom.com,parrot.com,charter.net,mydomain.com,mail-tester.com,myway.com,chello.nl,club-internet.fr,sdf.org,tiscali.co.uk,freeuk.com,unican.es,sci.fi,anonymize.com,sify.com,metacrawler.com,go.ro,ivillage.com,telus.net,dailypioneer.com,iespana.es,lycos.es,hey.com,sweb.cz,optusnet.com.au,alice.it,tpg.com.au,hamptonroads.com,saudia.com,lycos.nl,blackplanet.com,frontier.com,looksmart.com,pobox.com,prodigy.net,i.am,freeyellow.com,gmx.com,bigpond.com,crosswinds.net,dejanews.com,wanadoo.es,foxmail.com,eircom.net,islamonline.net,webindia123.com,oath.com,frontiernet.net,hetnet.nl,onmilwaukee.com,ukr.net,bugmenot.com,neuf.fr,kiwibox.com,za.com,iol.it,zonnet.nl,newmail.ru,pacbell.net,cogeco.ca,depechemode.com,concentric.net,aim.com,f5.si,yahoo.jp,terra.com,hot.ee,netzero.net,netins.net,sprynet.com,mailbox.org,mail2web.com,o2.pl,idirect.com,bigfoot.com,netspace.net.au,masrawy.com,supereva.it,yahoo.de,lycos.it,yeah.net,montevideo.com.uy,gmx.de,yahoo.co.uk,yahoofs.com,scubadiving.com,hushmail.com,iprimus.com.au,gportal.hu,swissinfo.org,inbox.com,bolt.com,telstra.com,bellsouth.net,spray.se,c3.hu,attbi.com,talktalk.co.uk,dynu.net,juno.com,yahoo.fr,msn.co.uk,fr.nf,pe.hu,bigpond.net.au,incredimail.com,adelphia.net,elvis.com,interfree.it,starmedia.com,seanet.com,yahoo.com.tw,zip.net,tds.net,she.com,forthnet.gr,land.ru,wow.com,dnsmadeeasy.com,webjump.com,singnet.com.sg,spacewar.com,tin.it,4mg.com,sp.nl,wowway.com,dmv.com,bangkok.com,fastmail.fm,sbcglobal.net,bright.net,usa.com,37.com,aeiou.pt,terra.cl,thirdage.com,btconnect.com,optimum.net,cableone.net,talkcity.com,blogos.com,c2i.net,iwon.com,aver.com,barcelona.com,ddnsfree.com,oi.com.br,lex.bg,roadrunner.com,airmail.net,lawyer.com,yahoo.com.cn,cu.cc,ananzi.co.za,au.ru,pipeline.com,cs.com,3ammagazine.com,gmx.at,qwest.net,btopenworld.com,easypost.com,westnet.com.au,nyc.com,korea.com,front.ru,inbox.lv,yahoo.com.br,ny.com,hispavista.com,abv.bg,mchsi.com,apollo.lv,everyone.net,terra.com.ar,singpost.com,doctor.com,garbage.com,bizhosting.com,go2net.com,clerk.com,games.com,charm.net,onlinehome.de,laposte.net" # 填你的白名单域名,逗号分隔
TrialEmailDomainWhitelist: "facebook.com,yahoo.com,qq.com,live.com,outlook.com,msn.com,example.com,go.com,aol.com,free.fr,aliyun.com,163.com,yandex.ru,indiatimes.com,alibaba.com,geocities.com,about.com,naver.com,netscape.com,yahoo.co.jp,earthlink.net,zoho.com,sky.com,mail.ru,angelfire.com,uol.com.br,spb.ru,yandex.com,globo.com,gmail.com,medscape.com,space.com,discovery.com,t-online.de,mac.com,icloud.com,homestead.com,lycos.com,web.id,nus.edu.sg,altavista.com,berlin.de,rambler.ru,pp.ua,comcast.net,sapo.pt,msk.ru,ancestry.com,daum.net,proton.me,law.com,bt.com,techspot.com,icq.com,sina.cn,libero.it,test.com,yourdomain.com,docomo.ne.jp,wp.pl,hotmail.com,orange.fr,onet.pl,me.com,india.com,kansascity.com,wanadoo.fr,fortunecity.com,web.de,terra.com.br,att.net,canada.com,skynet.be,ya.ru,excite.com,detik.com,compuserve.com,ig.com.br,zp.ua,gmx.net,xoom.com,mindspring.com,freeserve.co.uk,interia.pl,excite.co.jp,test.de,shaw.ca,virgilio.it,chez.com,rr.com,freenet.de,ntlworld.com,seznam.cz,arcor.de,tiscali.it,sympatico.ca,sina.com,gazeta.pl,care2.com,yam.com,r7.com,telenet.be,rcn.com,geek.com,sfr.fr,hotbot.com,cox.net,blueyonder.co.uk,tom.com,virginmedia.com,btinternet.com,iinet.net.au,rogers.com,ireland.com,pochta.ru,ozemail.com.au,catholic.org,bluewin.ch,chat.ru,virgin.net,verizon.net,erols.com,lycos.de,lycos.co.uk,protonmail.com,doityourself.com,home.nl,nate.com,casino.com,o2.co.uk,terra.es,mail.com,albawaba.com,126.com,www.com,planet.nl,sanook.com,21cn.com,online.de,name.com,i.ua,centrum.cz,rin.ru,aol.co.uk,voila.fr,walla.co.il,poste.it,netcom.com,parrot.com,charter.net,mydomain.com,mail-tester.com,myway.com,chello.nl,club-internet.fr,sdf.org,tiscali.co.uk,freeuk.com,unican.es,sci.fi,anonymize.com,sify.com,metacrawler.com,go.ro,ivillage.com,telus.net,dailypioneer.com,iespana.es,lycos.es,hey.com,sweb.cz,optusnet.com.au,alice.it,tpg.com.au,hamptonroads.com,saudia.com,lycos.nl,blackplanet.com,frontier.com,looksmart.com,pobox.com,prodigy.net,i.am,freeyellow.com,gmx.com,bigpond.com,crosswinds.net,dejanews.com,wanadoo.es,foxmail.com,eircom.net,islamonline.net,webindia123.com,oath.com,frontiernet.net,hetnet.nl,onmilwaukee.com,ukr.net,bugmenot.com,neuf.fr,kiwibox.com,za.com,iol.it,zonnet.nl,newmail.ru,pacbell.net,cogeco.ca,depechemode.com,concentric.net,aim.com,f5.si,yahoo.jp,terra.com,hot.ee,netzero.net,netins.net,sprynet.com,mailbox.org,mail2web.com,o2.pl,idirect.com,bigfoot.com,netspace.net.au,masrawy.com,supereva.it,yahoo.de,lycos.it,yeah.net,montevideo.com.uy,gmx.de,yahoo.co.uk,yahoofs.com,scubadiving.com,hushmail.com,iprimus.com.au,gportal.hu,swissinfo.org,inbox.com,bolt.com,telstra.com,bellsouth.net,spray.se,c3.hu,attbi.com,talktalk.co.uk,dynu.net,juno.com,yahoo.fr,msn.co.uk,fr.nf,pe.hu,bigpond.net.au,incredimail.com,adelphia.net,elvis.com,interfree.it,starmedia.com,seanet.com,yahoo.com.tw,zip.net,tds.net,she.com,forthnet.gr,land.ru,wow.com,dnsmadeeasy.com,webjump.com,singnet.com.sg,spacewar.com,tin.it,4mg.com,sp.nl,wowway.com,dmv.com,bangkok.com,fastmail.fm,sbcglobal.net,bright.net,usa.com,37.com,aeiou.pt,terra.cl,thirdage.com,btconnect.com,optimum.net,cableone.net,talkcity.com,blogos.com,c2i.net,iwon.com,aver.com,barcelona.com,ddnsfree.com,oi.com.br,lex.bg,roadrunner.com,airmail.net,lawyer.com,yahoo.com.cn,cu.cc,ananzi.co.za,au.ru,pipeline.com,cs.com,3ammagazine.com,gmx.at,qwest.net,btopenworld.com,easypost.com,westnet.com.au,nyc.com,korea.com,front.ru,inbox.lv,yahoo.com.br,ny.com,hispavista.com,abv.bg,mchsi.com,apollo.lv,everyone.net,terra.com.ar,singpost.com,doctor.com,garbage.com,bizhosting.com,go2net.com,clerk.com,games.com,charm.net,onlinehome.de,laposte.net" # 填你的白名单域名,逗号分隔
+21 -12
View File
@@ -1,13 +1,12 @@
module github.com/perfect-panel/server
go 1.23.3
go 1.24
require (
github.com/GUAIK-ORG/go-snowflake v0.0.0-20200116064823-220c4260e85f
github.com/alibabacloud-go/darabonba-openapi v0.1.18
github.com/alibabacloud-go/dysmsapi-20170525/v2 v2.0.18
github.com/alibabacloud-go/tea v1.2.2
github.com/alicebob/miniredis/v2 v2.34.0
github.com/anaskhan96/go-password-encoder v0.0.0-20201010210601-c765b799fd72
github.com/andybalholm/brotli v1.1.1
github.com/forgoer/openssl v1.6.0
@@ -32,7 +31,6 @@ require (
github.com/smartwalle/alipay/v3 v3.2.23
github.com/spf13/cast v1.7.0 // indirect
github.com/spf13/cobra v1.8.1
github.com/stretchr/testify v1.10.0
github.com/stripe/stripe-go/v81 v81.1.0
github.com/twilio/twilio-go v1.23.11
go.opentelemetry.io/otel v1.29.0
@@ -51,15 +49,20 @@ require (
gopkg.in/yaml.v3 v3.0.1
gorm.io/driver/mysql v1.5.7
gorm.io/gorm v1.30.0
gorm.io/plugin/soft_delete v1.2.1
k8s.io/apimachinery v0.31.1
)
require (
github.com/DATA-DOG/go-sqlmock v1.5.2
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/config v1.32.17
github.com/aws/aws-sdk-go-v2/credentials v1.19.16
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0
github.com/fatih/color v1.18.0
github.com/goccy/go-json v0.10.4
github.com/golang-migrate/migrate/v4 v4.18.2
github.com/mojocn/base64Captcha v1.3.8
github.com/oschwald/geoip2-golang v1.13.0
github.com/spaolacci/murmur3 v1.1.0
google.golang.org/grpc v1.64.1
@@ -79,8 +82,21 @@ require (
github.com/alibabacloud-go/tea-utils v1.4.5 // indirect
github.com/alibabacloud-go/tea-utils/v2 v2.0.7 // indirect
github.com/alibabacloud-go/tea-xml v1.1.3 // indirect
github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 // indirect
github.com/aliyun/credentials-go v1.3.10 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.0.11 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.30.17 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.21 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.42.1 // indirect
github.com/aws/smithy-go v1.25.1 // indirect
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff // indirect
github.com/bytedance/sonic v1.12.7 // indirect
github.com/bytedance/sonic/loader v0.2.3 // indirect
@@ -88,7 +104,6 @@ require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/clbanning/mxj/v2 v2.5.6 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
github.com/gin-contrib/sse v1.0.0 // indirect
@@ -114,27 +129,22 @@ require (
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mojocn/base64Captcha v1.3.8 // indirect
github.com/openzipkin/zipkin-go v0.4.2 // indirect
github.com/oschwald/maxminddb-golang v1.13.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/robfig/cron/v3 v3.0.1 // indirect
github.com/shopspring/decimal v1.4.0 // indirect
github.com/smartwalle/ncrypto v1.0.4 // indirect
github.com/smartwalle/ngx v1.0.9 // indirect
github.com/smartwalle/nsign v1.0.9 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/objx v0.5.2 // indirect
github.com/tjfoc/gmsm v1.4.1 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
github.com/yuin/gopher-lua v1.1.1 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.29.0 // indirect
go.opentelemetry.io/otel/metric v1.29.0 // indirect
go.opentelemetry.io/proto/otlp v1.3.1 // indirect
@@ -150,5 +160,4 @@ require (
google.golang.org/genproto/googleapis/rpc v0.0.0-20240513163218-0867130af1f8 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gorm.io/driver/sqlite v1.6.0 // indirect
)
+39 -22
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/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
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/go.mod h1:zA7AF9RTfpluCfz0omI4t5KCMaWHUMicsZoMccnaT44=
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
@@ -52,10 +54,6 @@ github.com/alibabacloud-go/tea-utils/v2 v2.0.7/go.mod h1:qxn986l+q33J5VkialKMqT/
github.com/alibabacloud-go/tea-xml v1.1.2/go.mod h1:Rq08vgCcCAjHyRi/M7xlHKUykZCEtyBy9+DPF6GgEu8=
github.com/alibabacloud-go/tea-xml v1.1.3 h1:7LYnm+JbOq2B+T/B0fHC4Ies4/FofC4zHzYtqw7dgt0=
github.com/alibabacloud-go/tea-xml v1.1.3/go.mod h1:Rq08vgCcCAjHyRi/M7xlHKUykZCEtyBy9+DPF6GgEu8=
github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 h1:uvdUDbHQHO85qeSydJtItA4T55Pw6BtAejd0APRJOCE=
github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
github.com/alicebob/miniredis/v2 v2.34.0 h1:mBFWMaJSNL9RwdGRyEDoAAv8OQc5UlEhLDQggTglU/0=
github.com/alicebob/miniredis/v2 v2.34.0/go.mod h1:kWShP4b58T1CW0Y5dViCd5ztzrDqRWqM3nksiyXk5s8=
github.com/aliyun/credentials-go v1.1.2/go.mod h1:ozcZaMR5kLM7pwtCMEpVmQ242suV6qTJya2bDq4X1Tw=
github.com/aliyun/credentials-go v1.3.6/go.mod h1:1LxUuX7L5YrZUWzBrRyk0SwSdH4OmPrib8NVePL3fxM=
github.com/aliyun/credentials-go v1.3.10 h1:45Xxrae/evfzQL9V10zL3xX31eqgLWEaIdCoPipOEQA=
@@ -64,6 +62,42 @@ github.com/anaskhan96/go-password-encoder v0.0.0-20201010210601-c765b799fd72 h1:
github.com/anaskhan96/go-password-encoder v0.0.0-20201010210601-c765b799fd72/go.mod h1:PsJICrlruG9QcJDYuZ0dO/2KtMDALzRbony8NkxZ2nE=
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
github.com/aws/aws-sdk-go-v2 v1.41.7 h1:DWpAJt66FmnnaRIOT/8ASTucrvuDPZASqhhLey6tLY8=
github.com/aws/aws-sdk-go-v2 v1.41.7/go.mod h1:4LAfZOPHNVNQEckOACQx60Y8pSRjIkNZQz1w92xpMJc=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10 h1:gx1AwW1Iyk9Z9dD9F4akX5gnN3QZwUB20GGKH/I+Rho=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10/go.mod h1:qqY157uZoqm5OXq/amuaBJyC9hgBCBQnsaWnPe905GY=
github.com/aws/aws-sdk-go-v2/config v1.32.17 h1:FpL4/758/diKwqbytU0prpuiu60fgXKUWCpDJtApclU=
github.com/aws/aws-sdk-go-v2/config v1.32.17/go.mod h1:OXqUMzgXytfoF9JaKkhrOYsyh72t9G+MJH8mMRaexOE=
github.com/aws/aws-sdk-go-v2/credentials v1.19.16 h1:r3RJBuU7X9ibt8RHbMjWE6y60QbKBiII6wSrXnapxSU=
github.com/aws/aws-sdk-go-v2/credentials v1.19.16/go.mod h1:6cx7zqDENJDbBIIWX6P8s0h6hqHC8Avbjh9Dseo27ug=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23 h1:UuSfcORqNSz/ey3VPRS8TcVH2Ikf0/sC+Hdj400QI6U=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23/go.mod h1:+G/OSGiOFnSOkYloKj/9M35s74LgVAdJBSD5lsFfqKg=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 h1:GpT/TrnBYuE5gan2cZbTtvP+JlHsutdmlV2YfEyNde0=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23/go.mod h1:xYWD6BS9ywC5bS3sz9Xh04whO/hzK2plt2Zkyrp4JuA=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 h1:bpd8vxhlQi2r1hiueOw02f/duEPTMK59Q4QMAoTTtTo=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23/go.mod h1:15DfR2nw+CRHIk0tqNyifu3G1YdAOy68RftkhMDDwYk=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 h1:OQqn11BtaYv1WLUowvcA30MpzIu8Ti4pcLPIIyoKZrA=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24/go.mod h1:X5ZJyfwVrWA96GzPmUCWFQaEARPR7gCrpq2E92PJwAE=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 h1:FLudkZLt5ci0ozzgkVo8BJGwvqNaZbTWb3UcucAateA=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9/go.mod h1:w7wZ/s9qK7c8g4al+UyoF1Sp/Z45UwMGcqIzLWVQHWk=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15 h1:ieLCO1JxUWuxTZ1cRd0GAaeX7O6cIxnwk7tc1LsQhC4=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15/go.mod h1:e3IzZvQ3kAWNykvE0Tr0RDZCMFInMvhku3qNpcIQXhM=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 h1:pbrxO/kuIwgEsOPLkaHu0O+m4fNgLU8B3vxQ+72jTPw=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23/go.mod h1:/CMNUqoj46HpS3MNRDEDIwcgEnrtZlKRaHNaHxIFpNA=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23 h1:03xatSQO4+AM1lTAbnRg5OK528EUg744nW7F73U8DKw=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23/go.mod h1:M8l3mwgx5ToK7wot2sBBce/ojzgnPzZXUV445gTSyE8=
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0 h1:etqBTKY581iwLL/H/S2sVgk3C9lAsTJFeXWFDsDcWOU=
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0/go.mod h1:L2dcoOgS2VSgbPLvpak2NyUPsO1TBN7M45Z4H7DlRc4=
github.com/aws/aws-sdk-go-v2/service/signin v1.0.11 h1:TdJ+HdzOBhU8+iVAOGUTU63VXopcumCOF1paFulHWZc=
github.com/aws/aws-sdk-go-v2/service/signin v1.0.11/go.mod h1:R82ZRExE/nheo0N+T8zHPcLRTcH8MGsnR3BiVGX0TwI=
github.com/aws/aws-sdk-go-v2/service/sso v1.30.17 h1:7byT8HUWrgoRp6sXjxtZwgOKfhss5fW6SkLBtqzgRoE=
github.com/aws/aws-sdk-go-v2/service/sso v1.30.17/go.mod h1:xNWknVi4Ezm1vg1QsB/5EWpAJURq22uqd38U8qKvOJc=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.21 h1:+1Kl1zx6bWi4X7cKi3VYh29h8BvsCoHQEQ6ST9X8w7w=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.21/go.mod h1:4vIRDq+CJB2xFAXZ+YgGUTiEft7oAQlhIs71xcSeuVg=
github.com/aws/aws-sdk-go-v2/service/sts v1.42.1 h1:F/M5Y9I3nwr2IEpshZgh1GeHpOItExNM9L1euNuh/fk=
github.com/aws/aws-sdk-go-v2/service/sts v1.42.1/go.mod h1:mTNxImtovCOEEuD65mKW7DCsL+2gjEH+RPEAexAzAio=
github.com/aws/smithy-go v1.25.1 h1:J8ERsGSU7d+aCmdQur5Txg6bVoYelvQJgtZehD12GkI=
github.com/aws/smithy-go v1.25.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/beevik/etree v1.1.0/go.mod h1:r8Aw8JqVegEf0w2fDnATrX9VpkMcyFeM0FhwO62wh+A=
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff h1:RmdPFa+slIr4SCBg4st/l/vZWVe9QJKMXGO60Bxbe04=
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff/go.mod h1:+RTT1BOk5P97fT2CiHkbFQwkK3mjsFAP6zCYV2aXtjw=
@@ -226,14 +260,13 @@ github.com/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8=
github.com/jinzhu/copier v0.4.0/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
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/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/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
@@ -258,9 +291,6 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.3/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
@@ -365,8 +395,6 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
github.com/yuin/goldmark v1.1.30/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0 h1:TT4fX+nBOA/+LUkobKGW1ydGcn+G3vRw9+g5HwCphpk=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0/go.mod h1:L7UH0GbB0p47T4Rri3uHjbpCFYrVrwc1I25QhNPiGK8=
go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw=
@@ -578,20 +606,9 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/driver/sqlite v1.1.3/go.mod h1:AKDgRWk8lcSQSw+9kxCJnX/yySj8G3rdwYlU57cB45c=
gorm.io/driver/sqlite v1.4.4 h1:gIufGoR0dQzjkyqDyYSCvsYR6fba1Gw5YKDqKeChxFc=
gorm.io/driver/sqlite v1.4.4/go.mod h1:0Aq3iPO+v9ZKbcdiz8gLWRw5VOPcBOPUQJFLq5e2ecI=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
gorm.io/gorm v1.20.1/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
gorm.io/gorm v1.23.0/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
gorm.io/gorm v1.30.0 h1:qbT5aPv1UH8gI99OsRlvDToLxW5zR7FzS9acZDOZcgs=
gorm.io/gorm v1.30.0/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
gorm.io/plugin/soft_delete v1.2.1 h1:qx9D/c4Xu6w5KT8LviX8DgLcB9hkKl6JC9f44Tj7cGU=
gorm.io/plugin/soft_delete v1.2.1/go.mod h1:Zv7vQctOJTGOsJ/bWgrN1n3od0GBAZgnLjEx+cApLGk=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
k8s.io/apimachinery v0.31.1 h1:mhcUBbj7KUjaVhyXILglcVjuS4nYXiwC+KKFBgIVy7U=
@@ -34,7 +34,7 @@
},
"id": 1,
"options": {
"content": "<b>AWS CloudWatch overview</b><br/>Region: ap-east-1 (Hong Kong)<br/>RDS DBInstanceIdentifier: database-1<br/>Redis ReplicationGroupId: hifastapp-redis<br/><br/>Note: Redis panels are configured using <code>ReplicationGroupId</code>. If a panel shows no data in your account, switch that dimension to the concrete <code>CacheClusterId</code> in Grafana query editor.",
"content": "<b>AWS CloudWatch overview</b><br/>Region: ap-east-1 (Hong Kong)<br/>RDS DBInstanceIdentifier: hifast-mysql-prod-v2<br/>Redis: current production uses a local Docker Redis container (<code>hifast-redis</code>) on EC2 rather than AWS ElastiCache.<br/><br/>This dashboard keeps the RDS CloudWatch panels. Redis should be observed from the local ops dashboard via Prometheus/cAdvisor instead of ElastiCache metrics.",
"mode": "html"
},
"pluginVersion": "11.0.0",
@@ -75,7 +75,7 @@
"uid": "cloudwatch"
},
"dimensions": {
"DBInstanceIdentifier": "database-1"
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
},
"metricName": "CPUUtilization",
"namespace": "AWS/RDS",
@@ -122,7 +122,7 @@
"uid": "cloudwatch"
},
"dimensions": {
"DBInstanceIdentifier": "database-1"
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
},
"metricName": "DatabaseConnections",
"namespace": "AWS/RDS",
@@ -169,7 +169,7 @@
"uid": "cloudwatch"
},
"dimensions": {
"DBInstanceIdentifier": "database-1"
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
},
"metricName": "FreeStorageSpace",
"namespace": "AWS/RDS",
@@ -216,7 +216,7 @@
"uid": "cloudwatch"
},
"dimensions": {
"DBInstanceIdentifier": "database-1"
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
},
"metricName": "ReadLatency",
"namespace": "AWS/RDS",
@@ -231,7 +231,7 @@
"uid": "cloudwatch"
},
"dimensions": {
"DBInstanceIdentifier": "database-1"
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
},
"metricName": "WriteLatency",
"namespace": "AWS/RDS",
@@ -278,7 +278,7 @@
"uid": "cloudwatch"
},
"dimensions": {
"DBInstanceIdentifier": "database-1"
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
},
"metricName": "ReadIOPS",
"namespace": "AWS/RDS",
@@ -293,7 +293,7 @@
"uid": "cloudwatch"
},
"dimensions": {
"DBInstanceIdentifier": "database-1"
"DBInstanceIdentifier": "hifast-mysql-prod-v2"
},
"metricName": "WriteIOPS",
"namespace": "AWS/RDS",
@@ -350,7 +350,7 @@
"statistic": "Average"
}
],
"title": "Redis Host CPU",
"title": "Redis Host CPU (Legacy ElastiCache)",
"type": "timeseries"
},
{
@@ -397,7 +397,7 @@
"statistic": "Average"
}
],
"title": "Redis Engine CPU",
"title": "Redis Engine CPU (Legacy ElastiCache)",
"type": "timeseries"
},
{
@@ -444,7 +444,7 @@
"statistic": "Average"
}
],
"title": "Redis Connections",
"title": "Redis Connections (Legacy ElastiCache)",
"type": "timeseries"
},
{
@@ -491,7 +491,7 @@
"statistic": "Average"
}
],
"title": "Redis Memory Usage %",
"title": "Redis Memory Usage % (Legacy ElastiCache)",
"type": "timeseries"
}
],
@@ -58,7 +58,7 @@
"uid": "P8E80F9AEF21F6940"
},
"editorMode": "code",
"expr": "sum(count_over_time({container=\"ppanel-server\"} |~ \"${user_id:raw}\" |~ \"${email:raw}\" |~ \"${order:raw}\" |~ \"${keyword:raw}\" |~ \"${level:raw}\" [5m]))",
"expr": "sum(count_over_time({compose_service=\"ppanel-server\"}[5m]))",
"queryType": "range",
"refId": "A"
}
@@ -103,7 +103,7 @@
"uid": "P8E80F9AEF21F6940"
},
"editorMode": "code",
"expr": "sum(count_over_time({container=\"ppanel-server\"} |~ \"${user_id:raw}\" |~ \"${email:raw}\" |~ \"${order:raw}\" |~ \"${keyword:raw}\" |~ \"(?i)(error|panic|fatal)\" [5m]))",
"expr": "sum(count_over_time({compose_service=\"ppanel-server\"} |~ \"(?i)(error|panic|fatal)\" [5m]))",
"queryType": "range",
"refId": "A"
}
@@ -140,7 +140,7 @@
"uid": "P8E80F9AEF21F6940"
},
"editorMode": "code",
"expr": "{container=\"ppanel-server\"} |~ \"${user_id:raw}\" |~ \"${email:raw}\" |~ \"${order:raw}\" |~ \"${keyword:raw}\" |~ \"${level:raw}\"",
"expr": "{compose_service=\"ppanel-server\"}",
"queryType": "range",
"refId": "A"
}
@@ -177,7 +177,7 @@
"uid": "P8E80F9AEF21F6940"
},
"editorMode": "code",
"expr": "{container=\"ppanel-server\"} |~ \"${user_id:raw}\" |~ \"${email:raw}\" |~ \"${order:raw}\" |~ \"${keyword:raw}\" |~ \"(?i)(error|panic|fatal)\"",
"expr": "{compose_service=\"ppanel-server\"} |~ \"(?i)(error|panic|fatal)\"",
"queryType": "range",
"refId": "A"
}
@@ -318,7 +318,7 @@
]
},
"time": {
"from": "now-7d",
"from": "now-1h",
"to": "now"
},
"timepicker": {},
@@ -449,7 +449,7 @@ CREATE TABLE IF NOT EXISTS `user_device`
`subscribe_id` bigint DEFAULT NULL COMMENT 'Subscribe ID',
`ip` varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Device Ip.',
`Identifier` varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Device Identifier.',
`user_agent` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Device User Agent.',
`user_agent` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Device User Agent.',
`online` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Online',
`enabled` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'EnableDeviceNumber',
`created_at` datetime(3) DEFAULT NULL COMMENT 'Creation Time',
@@ -0,0 +1,13 @@
-- Remove app_account_token column from order table if it exists
SET @col_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'order' AND COLUMN_NAME = 'app_account_token');
SET @sql = IF(@col_exists = 1, 'ALTER TABLE `order` DROP COLUMN `app_account_token`', 'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- Remove subscription_user_id column from order table if it exists
SET @col_exists2 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'order' AND COLUMN_NAME = 'subscription_user_id');
SET @sql2 = IF(@col_exists2 = 1, 'ALTER TABLE `order` DROP COLUMN `subscription_user_id`', 'SELECT 1');
PREPARE stmt2 FROM @sql2;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;
@@ -0,0 +1,7 @@
ALTER TABLE `log_message`
MODIFY COLUMN `app_version` VARCHAR(32) NULL,
MODIFY COLUMN `os_name` VARCHAR(32) NULL,
MODIFY COLUMN `os_version` VARCHAR(32) NULL,
MODIFY COLUMN `device_id` VARCHAR(64) NULL,
MODIFY COLUMN `session_id` VARCHAR(64) NULL,
MODIFY COLUMN `error_code` VARCHAR(64) NULL;
@@ -0,0 +1,7 @@
ALTER TABLE `log_message`
MODIFY COLUMN `app_version` VARCHAR(64) NULL,
MODIFY COLUMN `os_name` VARCHAR(64) NULL,
MODIFY COLUMN `os_version` VARCHAR(64) NULL,
MODIFY COLUMN `device_id` VARCHAR(255) NULL,
MODIFY COLUMN `session_id` VARCHAR(255) NULL,
MODIFY COLUMN `error_code` VARCHAR(128) NULL;
@@ -0,0 +1,2 @@
ALTER TABLE `user_device`
MODIFY COLUMN `user_agent` VARCHAR(64) NULL COMMENT 'Device User Agent.';
@@ -0,0 +1,2 @@
ALTER TABLE `user_device`
MODIFY COLUMN `user_agent` VARCHAR(255) NULL COMMENT 'Device User Agent.';
@@ -0,0 +1,19 @@
-- Rollback: re-deduct commission for users with pending (status=0) withdrawals.
-- This re-applies the OLD behaviour where commission is deducted on application.
-- Only run this if you are rolling back to the old code; do NOT run against
-- the new code or commission will be double-deducted on approval.
UPDATE `user` u
JOIN (
SELECT user_id, COALESCE(SUM(amount), 0) AS pending_total
FROM withdrawals
WHERE status = 0
GROUP BY user_id
) p ON u.id = p.user_id
SET u.commission = u.commission - p.pending_total
WHERE p.pending_total > 0;
-- Remove the migration log entries written by the up migration.
DELETE FROM system_logs
WHERE type = 33
AND content LIKE '%migration: refund pending withdrawal commission (HIF-22)%';
@@ -0,0 +1,65 @@
-- Migration: refund commission for existing pending (status=0) withdrawals
--
-- Under the old logic, commission was deducted when a withdrawal was submitted.
-- Under the new logic, commission is only deducted on approval.
-- This migration refunds the deducted amounts back to each user so that
-- the system is in a consistent state before the new code is deployed.
--
-- Idempotency: the UPDATE only touches rows whose commission would need
-- to increase, and each execution produces the same result because
-- COALESCE(SUM(amount),0) is deterministic given the same pending set.
-- Running this script multiple times is safe only if no new pending
-- withdrawals are created between runs; deploy new code immediately after.
-- Compatibility: some historical databases missed migration 02122, so the
-- withdrawals table may not exist yet. Create it idempotently before the
-- refund logic so this migration can self-heal older installations.
CREATE TABLE IF NOT EXISTS `withdrawals` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
`user_id` BIGINT NOT NULL COMMENT 'User ID',
`amount` BIGINT NOT NULL COMMENT 'Withdrawal Amount',
`content` TEXT COMMENT 'Withdrawal Content',
`status` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Withdrawal Status',
`reason` VARCHAR(500) NOT NULL DEFAULT '' COMMENT 'Rejection Reason',
`created_at` DATETIME NOT NULL COMMENT 'Creation Time',
`updated_at` DATETIME NOT NULL COMMENT 'Update Time',
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT IGNORE INTO `system` (`category`, `key`, `value`, `type`, `desc`, `created_at`, `updated_at`)
VALUES
('invite', 'WithdrawalMethod', '', 'string', 'withdrawal method', '2025-04-22 14:25:16.637', '2025-04-22 14:25:16.637');
-- Step 1: refund commission for all users with pending withdrawals.
UPDATE `user` u
JOIN (
SELECT user_id, COALESCE(SUM(amount), 0) AS pending_total
FROM withdrawals
WHERE status = 0
GROUP BY user_id
) p ON u.id = p.user_id
SET u.commission = u.commission + p.pending_total
WHERE p.pending_total > 0;
-- Step 2: write a migration log entry for each refunded user.
INSERT INTO system_logs (type, date, object_id, content, created_at)
SELECT
33 AS type,
DATE(NOW()) AS date,
p.user_id AS object_id,
JSON_OBJECT(
'type', 99,
'amount', p.pending_total,
'order_no', '',
'timestamp', UNIX_TIMESTAMP(NOW()) * 1000,
'note', 'migration: refund pending withdrawal commission (HIF-22)'
) AS content,
NOW() AS created_at
FROM (
SELECT user_id, COALESCE(SUM(amount), 0) AS pending_total
FROM withdrawals
WHERE status = 0
GROUP BY user_id
HAVING pending_total > 0
) p;
@@ -0,0 +1,2 @@
-- Remove activation_context column from order table
ALTER TABLE `order` DROP COLUMN IF EXISTS `activation_context`;
@@ -0,0 +1,6 @@
-- Add activation_context column to order table for Redis fallback persistence (idempotent)
SET @col_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'order' AND COLUMN_NAME = 'activation_context');
SET @sql = IF(@col_exists = 0, 'ALTER TABLE `order` ADD COLUMN `activation_context` TEXT DEFAULT NULL COMMENT ''Activation context JSON (guest/redemption info for DB fallback)'' AFTER `app_account_token`', 'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -0,0 +1,4 @@
ALTER TABLE `withdrawals`
DROP COLUMN `qr_code_url`,
DROP COLUMN `account`,
DROP COLUMN `method`;
@@ -0,0 +1,10 @@
SELECT COUNT(*) INTO @col_exists FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'withdrawals' AND COLUMN_NAME = 'method';
SET @ddl = IF(@col_exists = 0,
'ALTER TABLE `withdrawals` ADD COLUMN `method` TINYINT(1) NOT NULL DEFAULT 0 AFTER `content`, ADD COLUMN `account` VARCHAR(255) NOT NULL DEFAULT '''' AFTER `method`, ADD COLUMN `qr_code_url` VARCHAR(500) NOT NULL DEFAULT '''' AFTER `account`',
'SELECT 1');
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -0,0 +1,35 @@
SET @traffic_limit_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'user_subscribe'
AND COLUMN_NAME = 'traffic_limit'
);
SET @traffic_limit_sql = IF(
@traffic_limit_exists = 1,
'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;
@@ -0,0 +1,35 @@
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 = 0,
'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 1'
);
PREPARE speed_limit_stmt FROM @speed_limit_sql;
EXECUTE speed_limit_stmt;
DEALLOCATE PREPARE speed_limit_stmt;
SET @traffic_limit_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'user_subscribe'
AND COLUMN_NAME = 'traffic_limit'
);
SET @traffic_limit_sql = IF(
@traffic_limit_exists = 0,
'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 1'
);
PREPARE traffic_limit_stmt FROM @traffic_limit_sql;
EXECUTE traffic_limit_stmt;
DEALLOCATE PREPARE traffic_limit_stmt;
@@ -0,0 +1,39 @@
SET @column_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'order'
AND COLUMN_NAME = 'promo_discount'
);
SET @sql = IF(
@column_exists = 1,
'ALTER TABLE `order` DROP COLUMN `promo_discount`',
'SELECT ''Column promo_discount does not exist in order table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @column_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'order'
AND COLUMN_NAME = 'promo_rule_id'
);
SET @sql = IF(
@column_exists = 1,
'ALTER TABLE `order` DROP COLUMN `promo_rule_id`',
'SELECT ''Column promo_rule_id does not exist in order table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
DROP TABLE IF EXISTS `promo_usage`;
DROP TABLE IF EXISTS `subscribe_promo`;
DROP TABLE IF EXISTS `promo_rule`;
@@ -0,0 +1,213 @@
CREATE TABLE IF NOT EXISTS `promo_rule` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '规则名称',
`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 '生效开始时间',
`end_time` DATETIME DEFAULT NULL COMMENT '生效结束时间',
`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_deleted` (`enabled`, `deleted_at`, `priority` DESC)
) 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` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '套餐规格 ID',
`quantity` BIGINT NOT NULL DEFAULT 1 COMMENT '购买数量',
`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_quantity_rule` (`subscribe_id`, `quantity`, `promo_rule_id`),
KEY `idx_promo_rule_id` (`promo_rule_id`)
) 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` (
`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='促销使用记录表';
SET @column_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'order'
AND COLUMN_NAME = 'promo_rule_id'
);
SET @sql = IF(
@column_exists = 0,
'ALTER TABLE `order` ADD COLUMN `promo_rule_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT ''促销规则ID, 0=未使用促销'' AFTER `discount`',
'SELECT ''Column promo_rule_id already exists in order table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @column_exists = (
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'order'
AND COLUMN_NAME = 'promo_discount'
);
SET @sql = IF(
@column_exists = 0,
'ALTER TABLE `order` ADD COLUMN `promo_discount` BIGINT NOT NULL DEFAULT 0 COMMENT ''促销优惠金额(分)'' AFTER `promo_rule_id`',
'SELECT ''Column promo_discount already exists in order table'''
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -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;
+72
View File
@@ -20,6 +20,14 @@ type schemaColumnPatch struct {
ddl string
}
type schemaColumnDefinitionPatch struct {
table string
column string
dataType string
characterMaxLen *int64
ddl string
}
func EnsureSchemaCompatibility(ctx *svc.ServiceContext) error {
tablePatches := []schemaTablePatch{
{
@@ -142,6 +150,17 @@ func EnsureSchemaCompatibility(ctx *svc.ServiceContext) error {
},
}
varchar255 := int64(255)
columnDefinitionPatches := []schemaColumnDefinitionPatch{
{
table: "user_device",
column: "user_agent",
dataType: "varchar",
characterMaxLen: &varchar255,
ddl: "ALTER TABLE `user_device` MODIFY COLUMN `user_agent` VARCHAR(255) NULL COMMENT 'Device User Agent.';",
},
}
for _, patch := range tablePatches {
exists, err := tableExists(ctx.DB, patch.table)
if err != nil {
@@ -199,6 +218,27 @@ func EnsureSchemaCompatibility(ctx *svc.ServiceContext) error {
logger.Infof("[SchemaCompat] created missing index: %s.%s", patch.table, patch.index)
}
for _, patch := range columnDefinitionPatches {
tblExists, err := tableExists(ctx.DB, patch.table)
if err != nil {
return errors.Wrapf(err, "check table %s failed", patch.table)
}
if !tblExists {
continue
}
matches, err := columnDefinitionMatches(ctx.DB, patch.table, patch.column, patch.dataType, patch.characterMaxLen)
if err != nil {
return errors.Wrapf(err, "check column definition %s.%s failed", patch.table, patch.column)
}
if matches {
continue
}
if err = ctx.DB.Exec(patch.ddl).Error; err != nil {
return errors.Wrapf(err, "modify column %s.%s failed", patch.table, patch.column)
}
logger.Infof("[SchemaCompat] repaired column definition: %s.%s", patch.table, patch.column)
}
return nil
}
@@ -237,6 +277,38 @@ func indexExists(db *gorm.DB, table, index string) (bool, error) {
return count > 0, nil
}
func columnDefinitionMatches(db *gorm.DB, table, column, dataType string, characterMaxLen *int64) (bool, error) {
type columnMeta struct {
DataType string
CharacterMaximumLen *int64
}
var meta columnMeta
err := db.Raw(
`SELECT DATA_TYPE AS data_type, CHARACTER_MAXIMUM_LENGTH AS character_maximum_len
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?`,
table,
column,
).Scan(&meta).Error
if err != nil {
return false, err
}
if meta.DataType == "" {
return false, nil
}
if meta.DataType != dataType {
return false, nil
}
if characterMaxLen == nil {
return true, nil
}
if meta.CharacterMaximumLen == nil {
return false, nil
}
return *meta.CharacterMaximumLen == *characterMaxLen, nil
}
func _schemaCompatDebug(table, column string) string {
if column == "" {
return table
+17
View File
@@ -38,12 +38,29 @@ type Config struct {
Log Log `yaml:"Log"`
Currency Currency `yaml:"Currency"`
Trace trace.Config `yaml:"Trace"`
S3 S3Config `yaml:"S3"`
Administrator struct {
Email string `yaml:"Email" default:"admin@ppanel.dev"`
Password string `yaml:"Password" default:"password"`
} `yaml:"Administrator"`
}
type S3Config struct {
Enable bool `yaml:"Enable" default:"false"`
Region string `yaml:"Region" default:""`
Bucket string `yaml:"Bucket" default:""`
Endpoint string `yaml:"Endpoint" default:""`
AccessKey string `yaml:"AccessKey" default:""`
SecretKey string `yaml:"SecretKey" default:""`
SessionToken string `yaml:"SessionToken" default:""`
Prefix string `yaml:"Prefix" default:"app-upload"`
PublicBaseURL string `yaml:"PublicBaseURL" default:""`
UsePathStyle bool `yaml:"UsePathStyle" default:"false"`
PresignExpireSeconds int64 `yaml:"PresignExpireSeconds" default:"300"`
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,image/jpeg,image/jpg,image/png,image/webp,image/gif,image/heic,image/heif,image/bmp"`
}
type RedisConfig struct {
Host string `yaml:"Host" default:"localhost:6379"`
Pass string `yaml:"Pass" default:""`
@@ -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,25 @@
package log
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/log"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
func FilterOrderRefundLogHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.FilterOrderRefundLogRequest
_ = c.ShouldBind(&req)
validateErr := svcCtx.Validate(&req)
if validateErr != nil {
result.ParamErrorResult(c, validateErr)
return
}
l := log.NewFilterOrderRefundLogLogic(c.Request.Context(), svcCtx)
resp, err := l.FilterOrderRefundLog(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,23 @@
package log
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/log"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
func GetLogMessageRawHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.GetLogMessageRawRequest
_ = c.ShouldBind(&req)
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := log.NewGetLogMessageRawLogic(c.Request.Context(), svcCtx)
resp, err := l.GetLogMessageRaw(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,25 @@
package order
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/order"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
func RefundOrderHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.RefundOrderRequest
_ = c.ShouldBind(&req)
validateErr := svcCtx.Validate(&req)
if validateErr != nil {
result.ParamErrorResult(c, validateErr)
return
}
l := order.NewRefundOrderLogic(c.Request.Context(), svcCtx)
err := l.RefundOrder(&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 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)
}
}
@@ -0,0 +1,26 @@
package user
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
// Approve withdrawal
func ApproveWithdrawalHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.ApproveWithdrawalRequest
_ = c.ShouldBind(&req)
validateErr := svcCtx.Validate(&req)
if validateErr != nil {
result.ParamErrorResult(c, validateErr)
return
}
l := user.NewApproveWithdrawalLogic(c.Request.Context(), svcCtx)
err := l.ApproveWithdrawal(&req)
result.HttpResult(c, nil, err)
}
}
@@ -0,0 +1,26 @@
package user
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
// Get withdrawal list
func GetWithdrawalListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.GetWithdrawalListRequest
_ = c.ShouldBind(&req)
validateErr := svcCtx.Validate(&req)
if validateErr != nil {
result.ParamErrorResult(c, validateErr)
return
}
l := user.NewGetWithdrawalListLogic(c.Request.Context(), svcCtx)
resp, err := l.GetWithdrawalList(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,26 @@
package user
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
// Reject withdrawal
func RejectWithdrawalHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.RejectWithdrawalRequest
_ = c.ShouldBind(&req)
validateErr := svcCtx.Validate(&req)
if validateErr != nil {
result.ParamErrorResult(c, validateErr)
return
}
l := user.NewRejectWithdrawalLogic(c.Request.Context(), svcCtx)
err := l.RejectWithdrawal(&req)
result.HttpResult(c, nil, err)
}
}
@@ -1,6 +1,9 @@
package user
import (
"encoding/json"
"errors"
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/admin/user"
"github.com/perfect-panel/server/internal/svc"
@@ -18,9 +21,25 @@ func UpdateUserSubscribeHandler(svcCtx *svc.ServiceContext) func(c *gin.Context)
result.ParamErrorResult(c, validateErr)
return
}
if err := validateUpdateUserSubscribeTrafficLimit(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := user.NewUpdateUserSubscribeLogic(c.Request.Context(), svcCtx)
err := l.UpdateUserSubscribe(&req)
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
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/common"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/common"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
func ReportLogMessageHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.ReportLogMessageRequest
_ = c.ShouldBind(&req)
validateErr := svcCtx.Validate(&req)
if validateErr != nil {
result.ParamErrorResult(c, validateErr)
return
}
l := common.NewReportLogMessageLogic(c.Request.Context(), svcCtx)
resp, err := l.ReportLogMessage(&req, c)
result.HttpResult(c, resp, err)
}
return func(c *gin.Context) {
var req types.ReportLogMessageRequest
_ = c.ShouldBind(&req)
validateErr := svcCtx.Validate(&req)
if validateErr != nil {
result.ParamErrorResult(c, validateErr)
return
}
l := common.NewReportLogMessageLogic(c.Request.Context(), svcCtx)
resp, err := l.ReportLogMessage(&req, c)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,26 @@
package file
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/public/file"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
// Complete file upload
func FileUploadCompleteHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.FileUploadCompleteRequest
_ = c.ShouldBind(&req)
validateErr := svcCtx.Validate(&req)
if validateErr != nil {
result.ParamErrorResult(c, validateErr)
return
}
l := file.NewFileUploadCompleteLogic(c.Request.Context(), svcCtx)
resp, err := l.FileUploadComplete(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,43 @@
package file
import (
"mime/multipart"
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/public/file"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
// Upload file to RustFS
func FileUploadHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.FileUploadRequest
_ = c.ShouldBind(&req)
validateErr := svcCtx.Validate(&req)
if validateErr != nil {
result.ParamErrorResult(c, validateErr)
return
}
fileHeader, err := c.FormFile("file")
if err != nil {
result.ParamErrorResult(c, err)
return
}
fileReader, err := fileHeader.Open()
if err != nil {
result.HttpResult(c, nil, err)
return
}
defer func(file multipart.File) {
_ = file.Close()
}(fileReader)
l := file.NewFileUploadLogic(c.Request.Context(), svcCtx)
resp, err := l.FileUpload(&req, fileHeader, fileReader)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,26 @@
package file
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/public/file"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
// Init file upload
func FileUploadInitHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.FileUploadInitRequest
_ = c.ShouldBind(&req)
validateErr := svcCtx.Validate(&req)
if validateErr != nil {
result.ParamErrorResult(c, validateErr)
return
}
l := file.NewFileUploadInitLogic(c.Request.Context(), svcCtx)
resp, err := l.FileUploadInit(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,26 @@
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"
)
// Cancel Withdrawal
func CancelWithdrawalHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.CancelWithdrawalRequest
_ = c.ShouldBind(&req)
validateErr := svcCtx.Validate(&req)
if validateErr != nil {
result.ParamErrorResult(c, validateErr)
return
}
l := user.NewCancelWithdrawalLogic(c.Request.Context(), svcCtx)
resp, err := l.CancelWithdrawal(&req)
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)
}
}
+84 -4
View File
@@ -13,10 +13,12 @@ import (
adminCoupon "github.com/perfect-panel/server/internal/handler/admin/coupon"
adminDocument "github.com/perfect-panel/server/internal/handler/admin/document"
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"
adminMarketing "github.com/perfect-panel/server/internal/handler/admin/marketing"
adminOrder "github.com/perfect-panel/server/internal/handler/admin/order"
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"
adminServer "github.com/perfect-panel/server/internal/handler/admin/server"
adminSubscribe "github.com/perfect-panel/server/internal/handler/admin/subscribe"
@@ -30,6 +32,7 @@ import (
common "github.com/perfect-panel/server/internal/handler/common"
publicAnnouncement "github.com/perfect-panel/server/internal/handler/public/announcement"
publicDocument "github.com/perfect-panel/server/internal/handler/public/document"
publicFile "github.com/perfect-panel/server/internal/handler/public/file"
publicIapApple "github.com/perfect-panel/server/internal/handler/public/iap/apple"
publicOrder "github.com/perfect-panel/server/internal/handler/public/order"
publicPayment "github.com/perfect-panel/server/internal/handler/public/payment"
@@ -192,6 +195,14 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
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.Use(middleware.AuthMiddleware(serverCtx))
@@ -249,12 +260,18 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
// Filter commission log
adminLogGroupRouter.GET("/commission/list", adminLog.FilterCommissionLogHandler(serverCtx))
// Filter order refund log
adminLogGroupRouter.GET("/order/refund/list", adminLog.FilterOrderRefundLogHandler(serverCtx))
// Filter email log
adminLogGroupRouter.GET("/email/list", adminLog.FilterEmailLogHandler(serverCtx))
// Get error log message detail
adminLogGroupRouter.GET("/error_message/detail", adminLog.GetErrorLogMessageDetailHandler(serverCtx))
// Get log message raw detail (temporary)
adminLogGroupRouter.GET("/message/detail", adminLog.GetLogMessageRawHandler(serverCtx))
// Get error log message list
adminLogGroupRouter.GET("/error_message/list", adminLog.GetErrorLogMessageListHandler(serverCtx))
@@ -340,6 +357,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
// Update order status
adminOrderGroupRouter.PUT("/status", adminOrder.UpdateOrderStatusHandler(serverCtx))
// Refund order
adminOrderGroupRouter.POST("/refund", adminOrder.RefundOrderHandler(serverCtx))
// Manually activate order
adminOrderGroupRouter.POST("/activate", adminOrder.ActivateOrderHandler(serverCtx))
}
@@ -364,6 +384,38 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
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.Use(middleware.AuthMiddleware(serverCtx))
@@ -706,6 +758,15 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
// Get admin user invite list
adminUserGroupRouter.GET("/invite/list", adminUser.GetAdminUserInviteListHandler(serverCtx))
// Get withdrawal list
adminUserGroupRouter.GET("/withdrawal/list", adminUser.GetWithdrawalListHandler(serverCtx))
// Approve withdrawal
adminUserGroupRouter.POST("/withdrawal/approve", adminUser.ApproveWithdrawalHandler(serverCtx))
// Reject withdrawal
adminUserGroupRouter.POST("/withdrawal/reject", adminUser.RejectWithdrawalHandler(serverCtx))
}
authGroupRouter := router.Group("/v1/auth")
@@ -865,6 +926,20 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
publicDocumentGroupRouter.GET("/list", publicDocument.QueryDocumentListHandler(serverCtx))
}
publicFileGroupRouter := router.Group("/v1/public/file")
publicFileGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
{
// Upload file to RustFS
publicFileGroupRouter.POST("/upload", publicFile.FileUploadHandler(serverCtx))
// Init file upload
publicFileGroupRouter.POST("/upload/init", publicFile.FileUploadInitHandler(serverCtx))
// Complete file upload
publicFileGroupRouter.POST("/upload/complete", publicFile.FileUploadCompleteHandler(serverCtx))
}
publicOrderGroupRouter := router.Group("/v1/public/order")
publicOrderGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
@@ -945,17 +1020,16 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
}
publicSubscribeGroupRouter := router.Group("/v1/public/subscribe")
publicSubscribeGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
{
// Get subscribe list
publicSubscribeGroupRouter.GET("/list", publicSubscribe.QuerySubscribeListHandler(serverCtx))
publicSubscribeGroupRouter.GET("/list", middleware.OptionalAuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx), publicSubscribe.QuerySubscribeListHandler(serverCtx))
// Get user subscribe node info
publicSubscribeGroupRouter.GET("/node/list", publicSubscribe.QueryUserSubscribeNodeListHandler(serverCtx))
publicSubscribeGroupRouter.GET("/node/list", middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx), publicSubscribe.QueryUserSubscribeNodeListHandler(serverCtx))
// Get subscribe group list
publicSubscribeGroupRouter.GET("/group/list", publicSubscribe.QuerySubscribeGroupListHandler(serverCtx))
publicSubscribeGroupRouter.GET("/group/list", middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx), publicSubscribe.QuerySubscribeGroupListHandler(serverCtx))
}
publicTicketGroupRouter := router.Group("/v1/public/ticket")
@@ -1026,6 +1100,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
// Commission Withdraw
publicUserGroupRouter.POST("/commission_withdraw", publicUser.CommissionWithdrawHandler(serverCtx))
// Cancel Withdrawal
publicUserGroupRouter.POST("/withdrawal_cancel", publicUser.CancelWithdrawalHandler(serverCtx))
// Delete Current User Account
publicUserGroupRouter.DELETE("/current_user_account", publicUser.DeleteCurrentUserAccountHandler(serverCtx))
@@ -1041,6 +1118,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
// Query User Info
publicUserGroupRouter.GET("/info", publicUser.QueryUserInfoHandler(serverCtx))
// Get Invite Records
publicUserGroupRouter.GET("/invite_records", publicUser.GetInviteRecordsHandler(serverCtx))
// Get Invite Sales
publicUserGroupRouter.GET("/invite_sales", publicUser.GetInviteSalesHandler(serverCtx))
publicUserGroupRouter.GET("/invite/sales", publicUser.GetInviteSalesHandler(serverCtx)) // alias: backward-compat
@@ -29,7 +29,7 @@ func (l *DeleteSubscribeApplicationLogic) DeleteSubscribeApplication(req *types.
err := l.svcCtx.ClientModel.Delete(l.ctx, req.Id)
if err != nil {
l.Errorf("Failed to delete subscribe application with ID %d: %v", req.Id, err)
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), err.Error())
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseDeletedError), err.Error())
}
return nil
}

Some files were not shown because too many files have changed in this diff Show More