Compare commits

...

28 Commits

Author SHA1 Message Date
shanshanzhong147 9cfca8ef6b fix: renumber withdrawal migration
Co-authored-by: multica-agent <github@multica.ai>
2026-05-26 09:01:17 -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
89 changed files with 3366 additions and 412 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)
}
+2 -2
View File
@@ -7,8 +7,8 @@ MYSQL_ROOT_PASSWORD=CHANGE_ME_TO_STRONG_PASSWORD
# Grafana 管理员密码 # Grafana 管理员密码
GRAFANA_PASSWORD=CHANGE_ME_TO_STRONG_PASSWORD GRAFANA_PASSWORD=CHANGE_ME_TO_STRONG_PASSWORD
# PPanel Server 镜像标签(留空使用 latest # PPanel Server 镜像标签(由 CI/CD 传入不可变 tag,如 git SHA
PPANEL_SERVER_TAG=latest PPANEL_SERVER_TAG=CHANGE_ME_TO_GIT_SHA
# AWS 区域(香港) # AWS 区域(香港)
AWS_REGION=ap-east-1 AWS_REGION=ap-east-1
+131 -31
View File
@@ -5,9 +5,11 @@ on:
push: push:
branches: branches:
- main - main
- internal
pull_request: pull_request:
branches: branches:
- main - main
- internal
env: env:
# Docker镜像仓库 # Docker镜像仓库
@@ -19,8 +21,8 @@ env:
# SSH私钥(Gitea Secret 名称:AWS # SSH私钥(Gitea Secret 名称:AWS
SSH_KEY: ${{ secrets.AWS }} SSH_KEY: ${{ secrets.AWS }}
# TG通知 # TG通知
TG_BOT_TOKEN: 8114337882:AAHkEx03HSu7RxN4IHBJJEnsK9aPPzNLIk0 TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN }}
TG_CHAT_ID: "-49402438031" TG_CHAT_ID: ${{ secrets.TG_CHAT_ID }}
# Go构建变量 # Go构建变量
SERVICE: vpn SERVICE: vpn
SERVICE_STYLE: vpn SERVICE_STYLE: vpn
@@ -49,16 +51,19 @@ jobs:
echo "DOCKER_TAG_SUFFIX=latest" >> $GITHUB_ENV echo "DOCKER_TAG_SUFFIX=latest" >> $GITHUB_ENV
echo "CONTAINER_NAME=ppanel-server" >> $GITHUB_ENV echo "CONTAINER_NAME=ppanel-server" >> $GITHUB_ENV
echo "DEPLOY_PATH=/opt/ppanel" >> $GITHUB_ENV echo "DEPLOY_PATH=/opt/ppanel" >> $GITHUB_ENV
echo "DEPLOY_ENV_LABEL=🚀 服务已成功部署到生产环境" >> $GITHUB_ENV
echo "为 main 分支设置生产环境变量" echo "为 main 分支设置生产环境变量"
elif [ "${{ github.ref_name }}" = "internal" ]; then elif [ "${{ github.ref_name }}" = "internal" ]; then
echo "DOCKER_TAG_SUFFIX=internal" >> $GITHUB_ENV echo "DOCKER_TAG_SUFFIX=internal" >> $GITHUB_ENV
echo "CONTAINER_NAME=ppanel-server-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 分支设置开发环境变量" echo "为 internal 分支设置开发环境变量"
else else
echo "DOCKER_TAG_SUFFIX=${{ github.ref_name }}" >> $GITHUB_ENV echo "DOCKER_TAG_SUFFIX=${{ github.ref_name }}" >> $GITHUB_ENV
echo "CONTAINER_NAME=ppanel-server-${{ 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_PATH=/root/vpn_server_other" >> $GITHUB_ENV
echo "DEPLOY_ENV_LABEL=🔧 服务已成功部署到其他环境" >> $GITHUB_ENV
echo "为其他分支 (${{ github.ref_name }}) 设置环境变量" echo "为其他分支 (${{ github.ref_name }}) 设置环境变量"
fi fi
@@ -110,24 +115,37 @@ jobs:
docker version || true docker version || true
echo "客户端 API 版本:" $(docker version --format '{{.Client.APIVersion}}') echo "客户端 API 版本:" $(docker version --format '{{.Client.APIVersion}}')
# 步骤4: 构建并发布到镜像仓库 # 步骤4: 构建镜像
- name: 📤 构建并发布到镜像仓库 - name: 🏗️ 构建镜像
run: | run: |
echo "开始构建并推送镜像..." echo "开始构建镜像..."
echo "仓库: ${{ env.REPO }}" echo "仓库: ${{ env.REPO }}"
echo "版本标签: ${{ env.VERSION }}" echo "版本标签: ${{ env.VERSION }}"
echo "分支标签: ${{ env.DOCKER_TAG_SUFFIX }}" 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 \ docker build -f Dockerfile \
--platform linux/amd64 \ --platform linux/amd64 \
--build-arg TARGETARCH=amd64 \ --build-arg TARGETARCH=amd64 \
--build-arg VERSION=${{ env.VERSION }} \ --build-arg VERSION=${{ env.VERSION }} \
--build-arg BUILDTIME=${{ env.BUILDTIME }} \ --build-arg BUILDTIME=${{ env.BUILDTIME }} \
-t ${{ env.REPO }}:${{ env.VERSION }} \ $BUILD_TAG_ARGS \
-t ${{ env.REPO }}:${{ env.DOCKER_TAG_SUFFIX }} \
. .
echo "镜像构建完成"
# 步骤5: 发布到镜像仓库
- name: 📤 发布到镜像仓库
if: github.event_name == 'push'
run: |
echo "开始推送镜像..."
echo "推送版本标签镜像: ${{ env.REPO }}:${{ env.VERSION }}" echo "推送版本标签镜像: ${{ env.REPO }}:${{ env.VERSION }}"
docker push ${{ env.REPO }}:${{ env.VERSION }} docker push ${{ env.REPO }}:${{ env.VERSION }}
@@ -136,8 +154,9 @@ jobs:
echo "镜像推送完成" echo "镜像推送完成"
# 调试: 打印部署目标(不输出敏感信息) # 步骤6: 调试 - 打印部署目标(不输出敏感信息)
- name: 🔍 调试 - 打印部署目标 - name: 🔍 调试 - 打印部署目标
if: github.event_name == 'push'
run: | run: |
echo "========== 部署目标调试 ==========" echo "========== 部署目标调试 =========="
echo "当前分支: ${{ github.ref_name }}" echo "当前分支: ${{ github.ref_name }}"
@@ -148,8 +167,9 @@ jobs:
echo "DEPLOY_PATH: ${{ env.DEPLOY_PATH }}" echo "DEPLOY_PATH: ${{ env.DEPLOY_PATH }}"
echo "=====================================" echo "====================================="
# 步骤5: 传输配置文件 # 步骤7: 传输配置文件
- name: 📂 传输配置文件 - name: 📂 传输配置文件
if: github.event_name == 'push'
uses: appleboy/scp-action@v0.1.7 uses: appleboy/scp-action@v0.1.7
with: with:
host: ${{ env.SSH_HOST }} host: ${{ env.SSH_HOST }}
@@ -159,8 +179,9 @@ jobs:
source: "docker-compose.cloud.yml" source: "docker-compose.cloud.yml"
target: "/tmp/ppanel-deploy/" target: "/tmp/ppanel-deploy/"
# 步骤6: 连接服务器更新并启动 # 步骤8: 连接服务器更新、健康检查并按需回滚
- name: 🚀 连接服务器更新并启动 - name: 🚀 连接服务器更新并启动
if: github.event_name == 'push'
uses: appleboy/ssh-action@v1.0.3 uses: appleboy/ssh-action@v1.0.3
with: with:
host: ${{ env.SSH_HOST }} host: ${{ env.SSH_HOST }}
@@ -170,36 +191,114 @@ jobs:
timeout: 300s timeout: 300s
command_timeout: 600s command_timeout: 600s
script: | script: |
set -e
echo "连接服务器成功,开始部署..." echo "连接服务器成功,开始部署..."
echo "部署目录: ${{ env.DEPLOY_PATH }}" echo "部署目录: ${{ env.DEPLOY_PATH }}"
echo "部署标签: ${{ env.DOCKER_TAG_SUFFIX }}" echo "部署标签: ${{ env.DOCKER_TAG_SUFFIX }}"
echo "登录用户: ${{ env.SSH_USER }}" 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 if [ "${{ github.ref_name }}" = "main" ]; then
sudo mkdir -p ${{ env.DEPLOY_PATH }} sudo mkdir -p ${{ env.DEPLOY_PATH }}
sudo cp /tmp/ppanel-deploy/docker-compose.cloud.yml ${{ env.DEPLOY_PATH }}/docker-compose.cloud.yml sudo cp /tmp/ppanel-deploy/docker-compose.cloud.yml ${{ env.DEPLOY_PATH }}/docker-compose.cloud.yml
cd ${{ env.DEPLOY_PATH }}
echo "📥 拉取镜像..."
sudo docker-compose -f docker-compose.cloud.yml pull ppanel-server
echo "🚀 启动服务..."
sudo docker-compose -f docker-compose.cloud.yml up -d ppanel-server
sudo docker image prune -f || true
else else
mkdir -p ${{ env.DEPLOY_PATH }} mkdir -p ${{ env.DEPLOY_PATH }}
cp /tmp/ppanel-deploy/docker-compose.cloud.yml ${{ env.DEPLOY_PATH }}/docker-compose.cloud.yml cp /tmp/ppanel-deploy/docker-compose.cloud.yml ${{ env.DEPLOY_PATH }}/docker-compose.cloud.yml
cd ${{ env.DEPLOY_PATH }}
echo "📥 拉取镜像..."
docker-compose -f docker-compose.cloud.yml pull ppanel-server
echo "🚀 启动服务..."
docker-compose -f docker-compose.cloud.yml up -d ppanel-server
docker image prune -f || true
fi fi
echo "✅ 部署命令执行完成" cd ${{ env.DEPLOY_PATH }}
# 步骤6: TG通知 (成功) 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 "🚀 启动服务..."
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 - name: 📱 发送成功通知到Telegram
if: success() if: success() && github.event_name == 'push'
uses: appleboy/telegram-action@master uses: appleboy/telegram-action@master
with: with:
token: ${{ env.TG_BOT_TOKEN }} token: ${{ env.TG_BOT_TOKEN }}
@@ -213,12 +312,13 @@ jobs:
👤 提交者: ${{ github.actor }} 👤 提交者: ${{ github.actor }}
🕐 时间: ${{ github.event.head_commit.timestamp }} 🕐 时间: ${{ github.event.head_commit.timestamp }}
🚀 服务已成功部署到生产环境 ${{ env.DEPLOY_ENV_LABEL }}
🩺 健康检查: 通过 (http://127.0.0.1:8080/v1/common/heartbeat)
parse_mode: Markdown parse_mode: Markdown
# 步骤5: TG通知 (失败) # 步骤10: TG通知 (失败)
- name: 📱 发送失败通知到Telegram - name: 📱 发送失败通知到Telegram
if: failure() if: failure() && github.event_name == 'push'
uses: appleboy/telegram-action@master uses: appleboy/telegram-action@master
with: with:
token: ${{ env.TG_BOT_TOKEN }} token: ${{ env.TG_BOT_TOKEN }}
@@ -232,6 +332,6 @@ jobs:
👤 提交者: ${{ github.actor }} 👤 提交者: ${{ github.actor }}
🕐 时间: ${{ github.event.head_commit.timestamp }} 🕐 时间: ${{ github.event.head_commit.timestamp }}
🩺 健康检查: 失败或未完成;若新版本健康检查连续 3 次失败,已自动尝试回滚并重新检查
⚠️ 请检查构建日志获取详细信息 ⚠️ 请检查构建日志获取详细信息
parse_mode: Markdown parse_mode: Markdown
+76
View File
@@ -0,0 +1,76 @@
upstream api_backend {
server 127.0.0.1:8080;
}
server {
listen 80;
server_name api.hifast.biz 4d3vsw888xgaen.hifast.biz;
location /.well-known/acme-challenge/ {
root /var/www/html;
allow all;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl http2;
server_name api.hifast.biz;
client_max_body_size 150M;
ssl_certificate /etc/nginx/ssl/hifast.biz/_.hifast.biz.pem; # managed by Certbot
ssl_certificate_key /etc/nginx/ssl/hifast.biz/_.hifast.biz.key; # managed by Certbot
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options "DENY";
add_header X-Content-Type-Options nosniff;
if ($http_user_agent ~* '(9999|91\.78)') {
return 444;
}
location ~ ^/v1/common/client/download/file/(?<download_name>Hi快VPN-(?<os>windows|mac|android)-1.0.0-ic-.*\.(?<ext>exe|dmg|apk))$ {
alias /var/www/download/Hi快VPN-$os-1.0.0.$ext;
charset utf-8;
add_header Content-Disposition 'attachment; filename="$download_name"';
add_header Content-Type application/octet-stream;
}
location /v1/common/client/download/file/ {
alias /var/www/download/;
}
location / {
proxy_pass http://api_backend;
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_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
server {
listen 443 ssl http2;
server_name 4d3vsw888xgaen.hifast.biz;
client_max_body_size 150M;
ssl_certificate /etc/nginx/ssl/hifast.biz/_.hifast.biz.pem; # managed by Certbot
ssl_certificate_key /etc/nginx/ssl/hifast.biz/_.hifast.biz.key; # managed by Certbot
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json image/svg+xml;
root /var/www/admin;
location / {
try_files $uri $uri/ /index.html;
}
}
+61
View File
@@ -149,6 +149,35 @@ type (
Total int64 `json:"total"` Total int64 `json:"total"`
List []CommissionLog `json:"list"` 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 { GiftLog {
Type uint16 `json:"type"` Type uint16 `json:"type"`
userId int64 `json:"user_id"` userId int64 `json:"user_id"`
@@ -239,6 +268,30 @@ type (
OccurredAt int64 `json:"occurred_at"` OccurredAt int64 `json:"occurred_at"`
CreatedAt int64 `json:"created_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 ( @server (
@@ -291,6 +344,10 @@ service ppanel {
@handler FilterCommissionLog @handler FilterCommissionLog
get /commission/list (FilterCommissionLogRequest) returns (FilterCommissionLogResponse) get /commission/list (FilterCommissionLogRequest) returns (FilterCommissionLogResponse)
@doc "Filter order refund log"
@handler FilterOrderRefundLog
get /order/refund/list (FilterOrderRefundLogRequest) returns (FilterOrderRefundLogResponse)
@doc "Filter gift log" @doc "Filter gift log"
@handler FilterGiftLog @handler FilterGiftLog
get /gift/list (FilterGiftLogRequest) returns (FilterGiftLogResponse) get /gift/list (FilterGiftLogRequest) returns (FilterGiftLogResponse)
@@ -314,5 +371,9 @@ service ppanel {
@doc "Get error log message detail" @doc "Get error log message detail"
@handler GetErrorLogMessageDetail @handler GetErrorLogMessageDetail
get /error_message/detail returns (GetErrorLogMessageDetailResponse) 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"` PaymentId int64 `json:"payment_id,omitempty"`
TradeNo string `json:"trade_no,omitempty"` TradeNo string `json:"trade_no,omitempty"`
} }
RefundOrderRequest {
Id int64 `json:"id" validate:"required"`
Reason string `json:"reason,omitempty" validate:"omitempty,max=500"`
}
ActivateOrderRequest { ActivateOrderRequest {
OrderNo string `json:"order_no" validate:"required"` OrderNo string `json:"order_no" validate:"required"`
} }
@@ -68,6 +72,10 @@ service ppanel {
@handler UpdateOrderStatus @handler UpdateOrderStatus
put /status (UpdateOrderStatusRequest) put /status (UpdateOrderStatusRequest)
@doc "Refund order"
@handler RefundOrder
post /refund (RefundOrderRequest)
@doc "Manually activate order" @doc "Manually activate order"
@handler ActivateOrder @handler ActivateOrder
post /activate (ActivateOrderRequest) post /activate (ActivateOrderRequest)
+44 -15
View File
@@ -38,20 +38,20 @@ type (
Id int64 `form:"id" validate:"required"` Id int64 `form:"id" validate:"required"`
} }
UpdateUserBasiceInfoRequest { UpdateUserBasiceInfoRequest {
UserId int64 `json:"user_id" validate:"required"` UserId int64 `json:"user_id" validate:"required"`
Password string `json:"password"` Password string `json:"password"`
Avatar string `json:"avatar"` Avatar string `json:"avatar"`
Balance int64 `json:"balance"` Balance *int64 `json:"balance"`
Commission int64 `json:"commission"` Commission *int64 `json:"commission"`
ReferralPercentage uint8 `json:"referral_percentage"` ReferralPercentage uint8 `json:"referral_percentage"`
OnlyFirstPurchase *bool `json:"only_first_purchase"` OnlyFirstPurchase *bool `json:"only_first_purchase"`
GiftAmount int64 `json:"gift_amount"` GiftAmount *int64 `json:"gift_amount"`
Telegram int64 `json:"telegram"` Telegram int64 `json:"telegram"`
ReferCode string `json:"refer_code"` ReferCode string `json:"refer_code"`
RefererId int64 `json:"referer_id"` RefererId *int64 `json:"referer_id"`
Enable *bool `json:"enable"` Enable *bool `json:"enable"`
IsAdmin *bool `json:"is_admin"` IsAdmin *bool `json:"is_admin"`
Remark string `json:"remark"` Remark *string `json:"remark"`
} }
UpdateUserNotifySettingRequest { UpdateUserNotifySettingRequest {
UserId int64 `json:"user_id" validate:"required"` UserId int64 `json:"user_id" validate:"required"`
@@ -230,6 +230,24 @@ type (
FamilyId int64 `json:"family_id" validate:"required,gt=0"` FamilyId int64 `json:"family_id" validate:"required,gt=0"`
Reason string `json:"reason,omitempty"` 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"`
}
) )
@server ( @server (
@@ -370,5 +388,16 @@ service ppanel {
@doc "Dissolve family" @doc "Dissolve family"
@handler DissolveFamily @handler DissolveFamily
put /family/dissolve (DissolveFamilyRequest) 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)
}
+18
View File
@@ -11,6 +11,20 @@ info (
import "../types.api" import "../types.api"
type ( type (
FileUploadRequest {
BizType string `form:"biz_type" validate:"required"`
}
FileUploadResponse {
FileId string `json:"file_id"`
FileName string `json:"file_name"`
ObjectKey string `json:"object_key"`
Size int64 `json:"size"`
ContentType string `json:"content_type"`
Etag string `json:"etag"`
Status string `json:"status"`
}
FileUploadInitRequest { FileUploadInitRequest {
BizType string `json:"biz_type" validate:"required"` BizType string `json:"biz_type" validate:"required"`
FileName string `json:"file_name" validate:"required"` FileName string `json:"file_name" validate:"required"`
@@ -48,6 +62,10 @@ type (
middleware: AuthMiddleware,DeviceMiddleware middleware: AuthMiddleware,DeviceMiddleware
) )
service ppanel { service ppanel {
@doc "Upload file to RustFS"
@handler FileUpload
post /upload (FileUploadRequest) returns (FileUploadResponse)
@doc "Init file upload" @doc "Init file upload"
@handler FileUploadInit @handler FileUploadInit
post /upload/init (FileUploadInitRequest) returns (FileUploadInitResponse) post /upload/init (FileUploadInitRequest) returns (FileUploadInitResponse)
+15 -2
View File
@@ -109,8 +109,11 @@ type (
Rules []string `json:"rules" validate:"required"` Rules []string `json:"rules" validate:"required"`
} }
CommissionWithdrawRequest { CommissionWithdrawRequest {
Amount int64 `json:"amount"` Amount int64 `json:"amount"`
Content string `json:"content"` 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 { WithdrawalLog {
Id int64 `json:"id"` Id int64 `json:"id"`
@@ -119,9 +122,15 @@ type (
Content string `json:"content"` Content string `json:"content"`
Status uint8 `json:"status"` Status uint8 `json:"status"`
Reason string `json:"reason,omitempty"` Reason string `json:"reason,omitempty"`
Method uint8 `json:"method"`
Account string `json:"account"`
QrCodeUrl string `json:"qr_code_url"`
CreatedAt int64 `json:"created_at"` CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"` UpdatedAt int64 `json:"updated_at"`
} }
CancelWithdrawalRequest {
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
}
QueryWithdrawalLogListRequest { QueryWithdrawalLogListRequest {
Page int `form:"page"` Page int `form:"page"`
Size int `form:"size"` Size int `form:"size"`
@@ -352,6 +361,10 @@ service ppanel {
@handler CommissionWithdraw @handler CommissionWithdraw
post /commission_withdraw (CommissionWithdrawRequest) returns (WithdrawalLog) post /commission_withdraw (CommissionWithdrawRequest) returns (WithdrawalLog)
@doc "Cancel pending withdrawal"
@handler CancelWithdrawal
post /withdrawal_cancel (CancelWithdrawalRequest) returns (WithdrawalLog)
@doc "Query Withdrawal Log" @doc "Query Withdrawal Log"
@handler QueryWithdrawalLog @handler QueryWithdrawalLog
get /withdrawal_log (QueryWithdrawalLogListRequest) returns (QueryWithdrawalLogListResponse) get /withdrawal_log (QueryWithdrawalLogListRequest) returns (QueryWithdrawalLogListResponse)
+3 -1
View File
@@ -27,6 +27,7 @@ type (
EnableLoginNotify bool `json:"enable_login_notify"` EnableLoginNotify bool `json:"enable_login_notify"`
EnableSubscribeNotify bool `json:"enable_subscribe_notify"` EnableSubscribeNotify bool `json:"enable_subscribe_notify"`
EnableTradeNotify bool `json:"enable_trade_notify"` EnableTradeNotify bool `json:"enable_trade_notify"`
UseStatus bool `json:"use_status"` // Whether to show the "bind email to get free trial" prompt
AuthMethods []UserAuthMethod `json:"auth_methods"` AuthMethods []UserAuthMethod `json:"auth_methods"`
UserDevices []UserDevice `json:"user_devices"` UserDevices []UserDevice `json:"user_devices"`
Rules []string `json:"rules"` Rules []string `json:"rules"`
@@ -426,6 +427,7 @@ type (
FeeAmount int64 `json:"fee_amount"` FeeAmount int64 `json:"fee_amount"`
TradeNo string `json:"trade_no"` TradeNo string `json:"trade_no"`
Status uint8 `json:"status"` Status uint8 `json:"status"`
StatusName string `json:"status_name,omitempty"`
SubscribeId int64 `json:"subscribe_id"` SubscribeId int64 `json:"subscribe_id"`
CreatedAt int64 `json:"created_at"` CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"` UpdatedAt int64 `json:"updated_at"`
@@ -448,6 +450,7 @@ type (
FeeAmount int64 `json:"fee_amount"` FeeAmount int64 `json:"fee_amount"`
TradeNo string `json:"trade_no"` TradeNo string `json:"trade_no"`
Status uint8 `json:"status"` Status uint8 `json:"status"`
StatusName string `json:"status_name,omitempty"`
SubscribeId int64 `json:"subscribe_id"` SubscribeId int64 `json:"subscribe_id"`
Subscribe Subscribe `json:"subscribe"` Subscribe Subscribe `json:"subscribe"`
CreatedAt int64 `json:"created_at"` CreatedAt int64 `json:"created_at"`
@@ -1004,4 +1007,3 @@ type (
ConfigSnapshot map[string]interface{} `json:"config_snapshot,omitempty"` ConfigSnapshot map[string]interface{} `json:"config_snapshot,omitempty"`
} }
) )
@@ -17,7 +17,7 @@ REDIS_HOST=127.0.0.1
REDIS_PORT=6379 REDIS_PORT=6379
REDIS_PASSWORD=CHANGE_ME REDIS_PASSWORD=CHANGE_ME
REDIS_SOURCE_HOST=43.198.248.161 REDIS_SOURCE_HOST=18.163.33.75
REDIS_SOURCE_PORT=6379 REDIS_SOURCE_PORT=6379
REDIS_SOURCE_USER= REDIS_SOURCE_USER=
REDIS_SOURCE_PASSWORD=CHANGE_ME REDIS_SOURCE_PASSWORD=CHANGE_ME
+184
View File
@@ -0,0 +1,184 @@
# 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` 一致
- `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`
## 常见错误码
- `200`: 成功
- `400`: 参数错误
- `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` 一致
+7 -6
View File
@@ -19,9 +19,10 @@ services:
# ---------------------------------------------------- # ----------------------------------------------------
# 1. 业务后端 (PPanel Server) # 1. 业务后端 (PPanel Server)
# host 网络:可出外网,直接访问 AWS RDS/Redis;通过 127.0.0.1 访问 Tempo # host 网络:可出外网,直接访问 AWS RDS/Redis;通过 127.0.0.1 访问 Tempo
# PPANEL_SERVER_TAG 由 CI/CD 传入不可变镜像标签(如 git SHA)
# ---------------------------------------------------- # ----------------------------------------------------
ppanel-server: 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 container_name: ppanel-server
restart: always restart: always
volumes: volumes:
@@ -119,7 +120,7 @@ services:
# 或配置 Nginx 反代(建议加认证) # 或配置 Nginx 反代(建议加认证)
# ---------------------------------------------------- # ----------------------------------------------------
grafana: grafana:
image: grafana/grafana:latest image: grafana/grafana:13.0.1
container_name: ppanel-grafana container_name: ppanel-grafana
restart: always restart: always
ports: ports:
@@ -154,7 +155,7 @@ services:
# 6. Prometheus (指标采集) # 6. Prometheus (指标采集)
# ---------------------------------------------------- # ----------------------------------------------------
prometheus: prometheus:
image: prom/prometheus:latest image: prom/prometheus:v3.11.3
container_name: ppanel-prometheus container_name: ppanel-prometheus
restart: always restart: always
ports: ports:
@@ -179,7 +180,7 @@ services:
# 7. Nginx Exporter (监控宿主机 Nginx) # 7. Nginx Exporter (监控宿主机 Nginx)
# ---------------------------------------------------- # ----------------------------------------------------
nginx-exporter: nginx-exporter:
image: nginx/nginx-prometheus-exporter:latest image: nginx/nginx-prometheus-exporter:1.5.0
container_name: ppanel-nginx-exporter container_name: ppanel-nginx-exporter
restart: always restart: always
command: command:
@@ -198,7 +199,7 @@ services:
# 8. Node Exporter (宿主机监控) # 8. Node Exporter (宿主机监控)
# ---------------------------------------------------- # ----------------------------------------------------
node-exporter: node-exporter:
image: prom/node-exporter:latest image: prom/node-exporter:v1.11.1
container_name: ppanel-node-exporter container_name: ppanel-node-exporter
restart: always restart: always
volumes: volumes:
@@ -221,7 +222,7 @@ services:
# 9. cAdvisor (容器监控) # 9. cAdvisor (容器监控)
# ---------------------------------------------------- # ----------------------------------------------------
cadvisor: cadvisor:
image: gcr.io/cadvisor/cadvisor:latest image: gcr.io/cadvisor/cadvisor:v0.55.1
container_name: ppanel-cadvisor container_name: ppanel-cadvisor
restart: always restart: always
volumes: volumes:
@@ -34,7 +34,7 @@
}, },
"id": 1, "id": 1,
"options": { "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" "mode": "html"
}, },
"pluginVersion": "11.0.0", "pluginVersion": "11.0.0",
@@ -75,7 +75,7 @@
"uid": "cloudwatch" "uid": "cloudwatch"
}, },
"dimensions": { "dimensions": {
"DBInstanceIdentifier": "database-1" "DBInstanceIdentifier": "hifast-mysql-prod-v2"
}, },
"metricName": "CPUUtilization", "metricName": "CPUUtilization",
"namespace": "AWS/RDS", "namespace": "AWS/RDS",
@@ -122,7 +122,7 @@
"uid": "cloudwatch" "uid": "cloudwatch"
}, },
"dimensions": { "dimensions": {
"DBInstanceIdentifier": "database-1" "DBInstanceIdentifier": "hifast-mysql-prod-v2"
}, },
"metricName": "DatabaseConnections", "metricName": "DatabaseConnections",
"namespace": "AWS/RDS", "namespace": "AWS/RDS",
@@ -169,7 +169,7 @@
"uid": "cloudwatch" "uid": "cloudwatch"
}, },
"dimensions": { "dimensions": {
"DBInstanceIdentifier": "database-1" "DBInstanceIdentifier": "hifast-mysql-prod-v2"
}, },
"metricName": "FreeStorageSpace", "metricName": "FreeStorageSpace",
"namespace": "AWS/RDS", "namespace": "AWS/RDS",
@@ -216,7 +216,7 @@
"uid": "cloudwatch" "uid": "cloudwatch"
}, },
"dimensions": { "dimensions": {
"DBInstanceIdentifier": "database-1" "DBInstanceIdentifier": "hifast-mysql-prod-v2"
}, },
"metricName": "ReadLatency", "metricName": "ReadLatency",
"namespace": "AWS/RDS", "namespace": "AWS/RDS",
@@ -231,7 +231,7 @@
"uid": "cloudwatch" "uid": "cloudwatch"
}, },
"dimensions": { "dimensions": {
"DBInstanceIdentifier": "database-1" "DBInstanceIdentifier": "hifast-mysql-prod-v2"
}, },
"metricName": "WriteLatency", "metricName": "WriteLatency",
"namespace": "AWS/RDS", "namespace": "AWS/RDS",
@@ -278,7 +278,7 @@
"uid": "cloudwatch" "uid": "cloudwatch"
}, },
"dimensions": { "dimensions": {
"DBInstanceIdentifier": "database-1" "DBInstanceIdentifier": "hifast-mysql-prod-v2"
}, },
"metricName": "ReadIOPS", "metricName": "ReadIOPS",
"namespace": "AWS/RDS", "namespace": "AWS/RDS",
@@ -293,7 +293,7 @@
"uid": "cloudwatch" "uid": "cloudwatch"
}, },
"dimensions": { "dimensions": {
"DBInstanceIdentifier": "database-1" "DBInstanceIdentifier": "hifast-mysql-prod-v2"
}, },
"metricName": "WriteIOPS", "metricName": "WriteIOPS",
"namespace": "AWS/RDS", "namespace": "AWS/RDS",
@@ -350,7 +350,7 @@
"statistic": "Average" "statistic": "Average"
} }
], ],
"title": "Redis Host CPU", "title": "Redis Host CPU (Legacy ElastiCache)",
"type": "timeseries" "type": "timeseries"
}, },
{ {
@@ -397,7 +397,7 @@
"statistic": "Average" "statistic": "Average"
} }
], ],
"title": "Redis Engine CPU", "title": "Redis Engine CPU (Legacy ElastiCache)",
"type": "timeseries" "type": "timeseries"
}, },
{ {
@@ -444,7 +444,7 @@
"statistic": "Average" "statistic": "Average"
} }
], ],
"title": "Redis Connections", "title": "Redis Connections (Legacy ElastiCache)",
"type": "timeseries" "type": "timeseries"
}, },
{ {
@@ -491,7 +491,7 @@
"statistic": "Average" "statistic": "Average"
} }
], ],
"title": "Redis Memory Usage %", "title": "Redis Memory Usage % (Legacy ElastiCache)",
"type": "timeseries" "type": "timeseries"
} }
], ],
@@ -58,7 +58,7 @@
"uid": "P8E80F9AEF21F6940" "uid": "P8E80F9AEF21F6940"
}, },
"editorMode": "code", "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", "queryType": "range",
"refId": "A" "refId": "A"
} }
@@ -103,7 +103,7 @@
"uid": "P8E80F9AEF21F6940" "uid": "P8E80F9AEF21F6940"
}, },
"editorMode": "code", "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", "queryType": "range",
"refId": "A" "refId": "A"
} }
@@ -140,7 +140,7 @@
"uid": "P8E80F9AEF21F6940" "uid": "P8E80F9AEF21F6940"
}, },
"editorMode": "code", "editorMode": "code",
"expr": "{container=\"ppanel-server\"} |~ \"${user_id:raw}\" |~ \"${email:raw}\" |~ \"${order:raw}\" |~ \"${keyword:raw}\" |~ \"${level:raw}\"", "expr": "{compose_service=\"ppanel-server\"}",
"queryType": "range", "queryType": "range",
"refId": "A" "refId": "A"
} }
@@ -177,7 +177,7 @@
"uid": "P8E80F9AEF21F6940" "uid": "P8E80F9AEF21F6940"
}, },
"editorMode": "code", "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", "queryType": "range",
"refId": "A" "refId": "A"
} }
@@ -318,7 +318,7 @@
] ]
}, },
"time": { "time": {
"from": "now-7d", "from": "now-1h",
"to": "now" "to": "now"
}, },
"timepicker": {}, "timepicker": {},
@@ -449,7 +449,7 @@ CREATE TABLE IF NOT EXISTS `user_device`
`subscribe_id` bigint DEFAULT NULL COMMENT 'Subscribe ID', `subscribe_id` bigint DEFAULT NULL COMMENT 'Subscribe ID',
`ip` varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Device Ip.', `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.', `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', `online` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Online',
`enabled` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'EnableDeviceNumber', `enabled` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'EnableDeviceNumber',
`created_at` datetime(3) DEFAULT NULL COMMENT 'Creation Time', `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,4 @@
ALTER TABLE `withdrawals`
ADD COLUMN `method` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '收款方式 0:其他 1:支付宝 2:微信 3:银行卡' AFTER `content`,
ADD COLUMN `account` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '收款账号' AFTER `method`,
ADD COLUMN `qr_code_url` VARCHAR(500) NOT NULL DEFAULT '' COMMENT '收款码图片URL' AFTER `account`;
+72
View File
@@ -20,6 +20,14 @@ type schemaColumnPatch struct {
ddl string ddl string
} }
type schemaColumnDefinitionPatch struct {
table string
column string
dataType string
characterMaxLen *int64
ddl string
}
func EnsureSchemaCompatibility(ctx *svc.ServiceContext) error { func EnsureSchemaCompatibility(ctx *svc.ServiceContext) error {
tablePatches := []schemaTablePatch{ 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 { for _, patch := range tablePatches {
exists, err := tableExists(ctx.DB, patch.table) exists, err := tableExists(ctx.DB, patch.table)
if err != nil { 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) 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 return nil
} }
@@ -237,6 +277,38 @@ func indexExists(db *gorm.DB, table, index string) (bool, error) {
return count > 0, nil 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 { func _schemaCompatDebug(table, column string) string {
if column == "" { if column == "" {
return table return table
@@ -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,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)
}
}
@@ -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 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)
}
}
+24
View File
@@ -250,12 +250,18 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
// Filter commission log // Filter commission log
adminLogGroupRouter.GET("/commission/list", adminLog.FilterCommissionLogHandler(serverCtx)) adminLogGroupRouter.GET("/commission/list", adminLog.FilterCommissionLogHandler(serverCtx))
// Filter order refund log
adminLogGroupRouter.GET("/order/refund/list", adminLog.FilterOrderRefundLogHandler(serverCtx))
// Filter email log // Filter email log
adminLogGroupRouter.GET("/email/list", adminLog.FilterEmailLogHandler(serverCtx)) adminLogGroupRouter.GET("/email/list", adminLog.FilterEmailLogHandler(serverCtx))
// Get error log message detail // Get error log message detail
adminLogGroupRouter.GET("/error_message/detail", adminLog.GetErrorLogMessageDetailHandler(serverCtx)) 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 // Get error log message list
adminLogGroupRouter.GET("/error_message/list", adminLog.GetErrorLogMessageListHandler(serverCtx)) adminLogGroupRouter.GET("/error_message/list", adminLog.GetErrorLogMessageListHandler(serverCtx))
@@ -341,6 +347,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
// Update order status // Update order status
adminOrderGroupRouter.PUT("/status", adminOrder.UpdateOrderStatusHandler(serverCtx)) adminOrderGroupRouter.PUT("/status", adminOrder.UpdateOrderStatusHandler(serverCtx))
// Refund order
adminOrderGroupRouter.POST("/refund", adminOrder.RefundOrderHandler(serverCtx))
// Manually activate order // Manually activate order
adminOrderGroupRouter.POST("/activate", adminOrder.ActivateOrderHandler(serverCtx)) adminOrderGroupRouter.POST("/activate", adminOrder.ActivateOrderHandler(serverCtx))
} }
@@ -707,6 +716,15 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
// Get admin user invite list // Get admin user invite list
adminUserGroupRouter.GET("/invite/list", adminUser.GetAdminUserInviteListHandler(serverCtx)) 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") authGroupRouter := router.Group("/v1/auth")
@@ -870,6 +888,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
publicFileGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx)) publicFileGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
{ {
// Upload file to RustFS
publicFileGroupRouter.POST("/upload", publicFile.FileUploadHandler(serverCtx))
// Init file upload // Init file upload
publicFileGroupRouter.POST("/upload/init", publicFile.FileUploadInitHandler(serverCtx)) publicFileGroupRouter.POST("/upload/init", publicFile.FileUploadInitHandler(serverCtx))
@@ -1038,6 +1059,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
// Commission Withdraw // Commission Withdraw
publicUserGroupRouter.POST("/commission_withdraw", publicUser.CommissionWithdrawHandler(serverCtx)) publicUserGroupRouter.POST("/commission_withdraw", publicUser.CommissionWithdrawHandler(serverCtx))
// Cancel Withdrawal
publicUserGroupRouter.POST("/withdrawal_cancel", publicUser.CancelWithdrawalHandler(serverCtx))
// Delete Current User Account // Delete Current User Account
publicUserGroupRouter.DELETE("/current_user_account", publicUser.DeleteCurrentUserAccountHandler(serverCtx)) publicUserGroupRouter.DELETE("/current_user_account", publicUser.DeleteCurrentUserAccountHandler(serverCtx))
@@ -0,0 +1,77 @@
package log
import (
"context"
modellog "github.com/perfect-panel/server/internal/model/log"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
type FilterOrderRefundLogLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewFilterOrderRefundLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterOrderRefundLogLogic {
return &FilterOrderRefundLogLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *FilterOrderRefundLogLogic) FilterOrderRefundLog(req *types.FilterOrderRefundLogRequest) (resp *types.FilterOrderRefundLogResponse, err error) {
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &modellog.FilterParams{
Page: req.Page,
Size: req.Size,
Data: req.Date,
Search: req.Search,
Type: modellog.TypeOrderRefund.Uint8(),
ObjectID: req.OrderId,
})
if err != nil {
l.Errorw("Query order refund log failed", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Query order refund log failed")
}
var list []types.OrderRefundLog
for _, item := range data {
var content modellog.OrderRefund
if err := content.Unmarshal([]byte(item.Content)); err != nil {
l.Errorf("unmarshal order refund log content failed: %v", err.Error())
continue
}
if req.UserId > 0 && content.TargetUserId != req.UserId && content.RefererUserId != req.UserId && content.OperatorUserId != req.UserId {
continue
}
list = append(list, types.OrderRefundLog{
OrderId: content.OrderId,
OrderNo: content.OrderNo,
OperatorUserId: content.OperatorUserId,
OperatorAuthIdentifier: content.OperatorAuthIdentifier,
TargetUserId: content.TargetUserId,
UserSubscribeId: content.UserSubscribeId,
RefererUserId: content.RefererUserId,
CommissionAmount: content.CommissionAmount,
Reason: content.Reason,
OrderStatusBefore: content.OrderStatusBefore,
OrderStatusAfter: content.OrderStatusAfter,
SubscribeStatusBefore: content.SubscribeStatusBefore,
SubscribeStatusAfter: content.SubscribeStatusAfter,
SubscribeExpireBefore: content.SubscribeExpireBefore,
SubscribeExpireAfter: content.SubscribeExpireAfter,
CommissionBefore: content.CommissionBefore,
CommissionAfter: content.CommissionAfter,
Timestamp: content.Timestamp,
})
}
return &types.FilterOrderRefundLogResponse{
Total: total,
List: list,
}, nil
}
@@ -0,0 +1,66 @@
package log
import (
"context"
"encoding/json"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
type GetLogMessageRawLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetLogMessageRawLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetLogMessageRawLogic {
return &GetLogMessageRawLogic{Logger: logger.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
func (l *GetLogMessageRawLogic) GetLogMessageRaw(req *types.GetLogMessageRawRequest) (resp *types.GetLogMessageRawResponse, err error) {
row, err := l.svcCtx.LogMessageModel.FindOne(l.ctx, req.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "FindOne log_message id=%d: %v", req.Id, err)
}
var contextJSON json.RawMessage
if row.Context != "" {
if json.Valid([]byte(row.Context)) {
contextJSON = json.RawMessage(row.Context)
} else {
b, _ := json.Marshal(row.Context)
contextJSON = b
}
}
var occurredAt int64
if row.OccurredAt != nil {
occurredAt = row.OccurredAt.UnixMilli()
}
return &types.GetLogMessageRawResponse{
Id: row.Id,
Platform: row.Platform,
AppVersion: row.AppVersion,
OsName: row.OsName,
OsVersion: row.OsVersion,
DeviceId: row.DeviceId,
UserId: row.UserId,
SessionId: row.SessionId,
Level: row.Level,
ErrorCode: row.ErrorCode,
Message: row.Message,
Stack: row.Stack,
Context: contextJSON,
ClientIP: row.ClientIP,
UserAgent: row.UserAgent,
Locale: row.Locale,
Digest: row.Digest,
OccurredAt: occurredAt,
CreatedAt: row.CreatedAt.UnixMilli(),
}, nil
}
@@ -35,6 +35,28 @@ func (l *GetOrderListLogic) GetOrderList(req *types.GetOrderListRequest) (resp *
resp = &types.GetOrderListResponse{} resp = &types.GetOrderListResponse{}
resp.List = make([]types.Order, 0) resp.List = make([]types.Order, 0)
tool.DeepCopy(&resp.List, list) tool.DeepCopy(&resp.List, list)
for i := range resp.List {
resp.List[i].StatusName = orderStatusName(resp.List[i].Status)
}
resp.Total = total resp.Total = total
return return
} }
func orderStatusName(status uint8) string {
switch status {
case 1:
return "pending"
case 2:
return "paid"
case 3:
return "closed"
case 4:
return "failed"
case 5:
return "finished"
case 6:
return "refunded"
default:
return "unknown"
}
}
@@ -0,0 +1,298 @@
package order
import (
"context"
"fmt"
"strings"
"time"
"github.com/perfect-panel/server/internal/model/log"
modelorder "github.com/perfect-panel/server/internal/model/order"
modeluser "github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/constant"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
const (
orderStatusRefunded = 6
)
type RefundOrderLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewRefundOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RefundOrderLogic {
return &RefundOrderLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *RefundOrderLogic) RefundOrder(req *types.RefundOrderRequest) error {
operator, ok := l.ctx.Value(constant.CtxKeyUser).(*modeluser.User)
if !ok {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
}
reason := strings.TrimSpace(req.Reason)
var cachesToClear []*modeluser.Subscribe
var planCacheIDs []int64
var userCacheTargets []*modeluser.User
err := l.svcCtx.DB.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error {
var orderInfo modelorder.Order
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Model(&modelorder.Order{}).
Where("id = ?", req.Id).
First(&orderInfo).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return errors.Wrapf(xerr.NewErrCode(xerr.OrderNotExist), "order %d not found", req.Id)
}
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query order failed: %v", err)
}
if orderInfo.Status == orderStatusRefunded {
return errors.Wrapf(xerr.NewErrCode(xerr.OrderAlreadyRefunded), "order %d already refunded", orderInfo.Id)
}
if orderInfo.Status != 2 && orderInfo.Status != 5 {
return errors.Wrapf(xerr.NewErrCode(xerr.OrderStatusError), "order %d status %d is not refundable", orderInfo.Id, orderInfo.Status)
}
userSub, err := l.lockRefundTargetSubscription(tx, &orderInfo)
if err != nil {
return err
}
orderStatusBefore := orderInfo.Status
subStatusBefore := userSub.Status
subExpireBefore := userSub.ExpireTime
now := time.Now()
referer, commissionAmount, err := l.lockCommissionSource(tx, orderInfo.OrderNo, orderInfo.Commission)
if err != nil {
return err
}
var commissionBefore int64
var commissionAfter int64
if referer != nil {
commissionBefore = referer.Commission
commissionAfter = referer.Commission - commissionAmount
if err := tx.Model(&modeluser.User{}).
Where("id = ?", referer.Id).
UpdateColumn("commission", gorm.Expr("commission - ?", commissionAmount)).Error; err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "refund commission failed: %v", err)
}
commissionLog := log.Commission{
Type: log.CommissionTypeRefund,
Amount: -commissionAmount,
OrderNo: orderInfo.OrderNo,
Timestamp: now.UnixMilli(),
}
content, marshalErr := commissionLog.Marshal()
if marshalErr != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "marshal commission refund log failed: %v", marshalErr)
}
if err := tx.Model(&log.SystemLog{}).Create(&log.SystemLog{
Type: log.TypeCommission.Uint8(),
Date: now.Format(time.DateOnly),
ObjectID: referer.Id,
Content: string(content),
CreatedAt: now,
}).Error; err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert commission refund log failed: %v", err)
}
referer.Commission = commissionAfter
userCacheTargets = append(userCacheTargets, referer)
}
if err := tx.Model(&modelorder.Order{}).
Where("id = ? AND status IN ?", orderInfo.Id, []int{2, 5}).
Update("status", orderStatusRefunded).Error; err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "refund order status update failed: %v", err)
}
orderInfo.Status = orderStatusRefunded
userSub.Status = 3
userSub.ExpireTime = now.Add(-time.Second)
userSub.FinishedAt = &now
if err := tx.Model(&modeluser.Subscribe{}).
Where("id = ?", userSub.Id).
Updates(map[string]interface{}{
"status": userSub.Status,
"expire_time": userSub.ExpireTime,
"finished_at": userSub.FinishedAt,
}).Error; err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update subscription failed: %v", err)
}
refundLog, err := l.buildRefundAuditLog(operator, &orderInfo, userSub, referer, commissionAmount, reason, orderStatusBefore, subStatusBefore, subExpireBefore, commissionBefore, commissionAfter, now)
if err != nil {
return err
}
logContent, err := refundLog.Marshal()
if err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "marshal refund audit log failed: %v", err)
}
if err := tx.Model(&log.SystemLog{}).Create(&log.SystemLog{
Type: log.TypeOrderRefund.Uint8(),
Date: now.Format(time.DateOnly),
ObjectID: orderInfo.Id,
Content: string(logContent),
CreatedAt: now,
}).Error; err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert refund audit log failed: %v", err)
}
cachesToClear = append(cachesToClear, userSub)
if userSub.SubscribeId > 0 {
planCacheIDs = append(planCacheIDs, userSub.SubscribeId)
}
if orderInfo.UserId > 0 {
orderUser := &modeluser.User{Id: orderInfo.UserId}
userCacheTargets = append(userCacheTargets, orderUser)
}
return nil
})
if err != nil {
l.Errorw("[RefundOrder] refund failed", logger.Field("error", err.Error()), logger.Field("order_id", req.Id))
return err
}
if len(cachesToClear) > 0 {
if clearErr := l.svcCtx.UserModel.ClearSubscribeCache(l.ctx, cachesToClear...); clearErr != nil {
l.Errorw("[RefundOrder] clear subscribe cache failed", logger.Field("error", clearErr.Error()), logger.Field("order_id", req.Id))
}
}
for _, subscribeID := range planCacheIDs {
if clearErr := l.svcCtx.SubscribeModel.ClearCache(l.ctx, subscribeID); clearErr != nil {
l.Errorw("[RefundOrder] clear subscribe cache failed", logger.Field("error", clearErr.Error()), logger.Field("subscribe_id", subscribeID))
}
}
if len(userCacheTargets) > 0 {
if clearErr := l.svcCtx.UserModel.ClearUserCache(l.ctx, userCacheTargets...); clearErr != nil {
l.Errorw("[RefundOrder] clear user cache failed", logger.Field("error", clearErr.Error()))
}
}
return nil
}
func (l *RefundOrderLogic) lockRefundTargetSubscription(tx *gorm.DB, orderInfo *modelorder.Order) (*modeluser.Subscribe, error) {
var userSub modeluser.Subscribe
err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Model(&modeluser.Subscribe{}).
Where("order_id = ?", orderInfo.Id).
First(&userSub).Error
if err == nil {
return &userSub, nil
}
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query refund subscription failed: %v", err)
}
if orderInfo.Type != 2 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.OrderRefundNoSubscription), "order %d has no linked subscription", orderInfo.Id)
}
if orderInfo.ParentId == 0 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.OrderRefundNoSubscription), "renewal order %d has no parent order", orderInfo.Id)
}
err = tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Model(&modeluser.Subscribe{}).
Where("order_id = ?", orderInfo.ParentId).
First(&userSub).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.OrderRefundNoSubscription), "renewal order %d parent subscription not found", orderInfo.Id)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query renewal subscription failed: %v", err)
}
return &userSub, nil
}
func (l *RefundOrderLogic) lockCommissionSource(tx *gorm.DB, orderNo string, orderCommission int64) (*modeluser.User, int64, error) {
var commissionLogs []log.SystemLog
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Model(&log.SystemLog{}).
Where("type = ? AND content LIKE ?", log.TypeCommission.Uint8(), fmt.Sprintf("%%\"order_no\":\"%s\"%%", orderNo)).
Order("id DESC").
Find(&commissionLogs).Error; err != nil {
return nil, 0, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query commission log failed: %v", err)
}
for _, item := range commissionLogs {
var content log.Commission
if err := content.Unmarshal([]byte(item.Content)); err != nil {
continue
}
if content.Type != log.CommissionTypePurchase && content.Type != log.CommissionTypeRenewal {
continue
}
var referer modeluser.User
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Model(&modeluser.User{}).
Where("id = ?", item.ObjectID).
First(&referer).Error; err != nil {
return nil, 0, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query commission owner failed: %v", err)
}
return &referer, content.Amount, nil
}
if orderCommission > 0 {
return nil, 0, errors.Wrapf(xerr.NewErrCode(xerr.OrderRefundCommissionMismatch), "order %s commission owner not found", orderNo)
}
return nil, 0, nil
}
func (l *RefundOrderLogic) buildRefundAuditLog(
operator *modeluser.User,
orderInfo *modelorder.Order,
userSub *modeluser.Subscribe,
referer *modeluser.User,
commissionAmount int64,
reason string,
orderStatusBefore uint8,
subStatusBefore uint8,
subExpireBefore time.Time,
commissionBefore int64,
commissionAfter int64,
now time.Time,
) (*log.OrderRefund, error) {
refundLog := &log.OrderRefund{
OrderId: orderInfo.Id,
OrderNo: orderInfo.OrderNo,
OperatorUserId: operator.Id,
TargetUserId: userSub.UserId,
UserSubscribeId: userSub.Id,
CommissionAmount: commissionAmount,
Reason: reason,
OrderStatusBefore: orderStatusBefore,
OrderStatusAfter: orderInfo.Status,
SubscribeStatusBefore: subStatusBefore,
SubscribeStatusAfter: userSub.Status,
SubscribeExpireBefore: subExpireBefore.UnixMilli(),
SubscribeExpireAfter: userSub.ExpireTime.UnixMilli(),
CommissionBefore: commissionBefore,
CommissionAfter: commissionAfter,
Timestamp: now.UnixMilli(),
}
if referer != nil {
refundLog.RefererUserId = referer.Id
}
if len(operator.AuthMethods) > 0 {
refundLog.OperatorAuthIdentifier = operator.AuthMethods[0].AuthIdentifier
}
return refundLog, nil
}
@@ -0,0 +1,85 @@
package order
import (
"testing"
"time"
modelorder "github.com/perfect-panel/server/internal/model/order"
modeluser "github.com/perfect-panel/server/internal/model/user"
)
func TestOrderStatusName(t *testing.T) {
tests := map[uint8]string{
1: "pending",
2: "paid",
3: "closed",
4: "failed",
5: "finished",
6: "refunded",
7: "unknown",
}
for input, want := range tests {
if got := orderStatusName(input); got != want {
t.Fatalf("status %d: got %q want %q", input, got, want)
}
}
}
func TestBuildRefundAuditLog(t *testing.T) {
logic := &RefundOrderLogic{}
now := time.Unix(1710000000, 0)
expireBefore := now.Add(24 * time.Hour)
expireAfter := now.Add(-time.Second)
operator := &modeluser.User{
Id: 100,
AuthMethods: []modeluser.AuthMethods{
{AuthIdentifier: "admin@example.com"},
},
}
orderInfo := &modelorder.Order{Id: 10, OrderNo: "ORD-1", Status: orderStatusRefunded}
userSub := &modeluser.Subscribe{Id: 20, UserId: 30, Status: 3, ExpireTime: expireAfter}
referer := &modeluser.User{Id: 40}
got, err := logic.buildRefundAuditLog(
operator,
orderInfo,
userSub,
referer,
500,
"manual refund",
5,
1,
expireBefore,
900,
400,
now,
)
if err != nil {
t.Fatalf("buildRefundAuditLog error: %v", err)
}
if got.OrderId != 10 || got.OrderNo != "ORD-1" {
t.Fatalf("unexpected order info: %+v", got)
}
if got.OperatorUserId != 100 || got.OperatorAuthIdentifier != "admin@example.com" {
t.Fatalf("unexpected operator info: %+v", got)
}
if got.TargetUserId != 30 || got.UserSubscribeId != 20 {
t.Fatalf("unexpected subscription info: %+v", got)
}
if got.RefererUserId != 40 || got.CommissionAmount != 500 {
t.Fatalf("unexpected commission info: %+v", got)
}
if got.OrderStatusBefore != 5 || got.OrderStatusAfter != orderStatusRefunded {
t.Fatalf("unexpected order status: %+v", got)
}
if got.SubscribeStatusBefore != 1 || got.SubscribeStatusAfter != 3 {
t.Fatalf("unexpected subscribe status: %+v", got)
}
if got.SubscribeExpireBefore != expireBefore.UnixMilli() || got.SubscribeExpireAfter != expireAfter.UnixMilli() {
t.Fatalf("unexpected expire transition: %+v", got)
}
if got.CommissionBefore != 900 || got.CommissionAfter != 400 {
t.Fatalf("unexpected commission transition: %+v", got)
}
}
@@ -0,0 +1,27 @@
package user
import (
"context"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
)
type ApproveWithdrawalLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewApproveWithdrawalLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ApproveWithdrawalLogic {
return &ApproveWithdrawalLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *ApproveWithdrawalLogic) ApproveWithdrawal(req *types.ApproveWithdrawalRequest) error {
return approveWithdrawal(l.ctx, l.svcCtx, req.WithdrawalId)
}
@@ -0,0 +1,80 @@
package user
import (
"context"
usermodel "github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
type GetWithdrawalListLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetWithdrawalListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetWithdrawalListLogic {
return &GetWithdrawalListLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetWithdrawalListLogic) GetWithdrawalList(req *types.GetWithdrawalListRequest) (*types.GetWithdrawalListResponse, error) {
page := req.Page
size := req.Size
if page <= 0 {
page = 1
}
if size <= 0 {
size = 10
}
query := l.svcCtx.DB.WithContext(l.ctx).Model(&usermodel.Withdrawal{})
if req.UserId != nil {
query = query.Where("user_id = ?", *req.UserId)
}
if req.Status != nil {
query = query.Where("status = ?", *req.Status)
}
if req.Method != nil {
query = query.Where("method = ?", *req.Method)
}
var total int64
if err := query.Count(&total).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count withdrawals failed: %v", err)
}
var rows []usermodel.Withdrawal
if err := query.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&rows).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query withdrawals failed: %v", err)
}
list := make([]types.WithdrawalLog, 0, len(rows))
for _, row := range rows {
list = append(list, types.WithdrawalLog{
Id: row.Id,
UserId: row.UserId,
Amount: row.Amount,
Content: row.Content,
Status: row.Status,
Reason: row.Reason,
Method: row.Method,
Account: row.Account,
QrCodeUrl: row.QrCodeUrl,
CreatedAt: row.CreatedAt.UnixMilli(),
UpdatedAt: row.UpdatedAt.UnixMilli(),
})
}
return &types.GetWithdrawalListResponse{
List: list,
Total: total,
}, nil
}
@@ -0,0 +1,27 @@
package user
import (
"context"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
)
type RejectWithdrawalLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewRejectWithdrawalLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RejectWithdrawalLogic {
return &RejectWithdrawalLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *RejectWithdrawalLogic) RejectWithdrawal(req *types.RejectWithdrawalRequest) error {
return rejectWithdrawal(l.ctx, l.svcCtx, req.WithdrawalId, req.Reason)
}
@@ -6,6 +6,7 @@ import (
"strings" "strings"
"time" "time"
logicCommon "github.com/perfect-panel/server/internal/logic/common"
"github.com/perfect-panel/server/internal/model/log" "github.com/perfect-panel/server/internal/model/log"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types" "github.com/perfect-panel/server/internal/types"
@@ -45,13 +46,13 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
} }
err = l.svcCtx.UserModel.Transaction(l.ctx, func(tx *gorm.DB) error { err = l.svcCtx.UserModel.Transaction(l.ctx, func(tx *gorm.DB) error {
if userInfo.Balance != req.Balance { if req.Balance != nil && userInfo.Balance != *req.Balance {
change := req.Balance - userInfo.Balance change := *req.Balance - userInfo.Balance
balanceLog := log.Balance{ balanceLog := log.Balance{
Type: log.BalanceTypeAdjust, Type: log.BalanceTypeAdjust,
Amount: change, Amount: change,
OrderNo: "", OrderNo: "",
Balance: req.Balance, Balance: *req.Balance,
Timestamp: time.Now().UnixMilli(), Timestamp: time.Now().UnixMilli(),
} }
content, _ := balanceLog.Marshal() content, _ := balanceLog.Marshal()
@@ -65,14 +66,14 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
if err != nil { if err != nil {
return err return err
} }
userInfo.Balance = req.Balance userInfo.Balance = *req.Balance
} }
if userInfo.GiftAmount != req.GiftAmount { if req.GiftAmount != nil && userInfo.GiftAmount != *req.GiftAmount {
change := req.GiftAmount - userInfo.GiftAmount change := *req.GiftAmount - userInfo.GiftAmount
if change != 0 { if change != 0 {
var changeType uint16 var changeType uint16
if userInfo.GiftAmount < req.GiftAmount { if userInfo.GiftAmount < *req.GiftAmount {
changeType = log.GiftTypeIncrease changeType = log.GiftTypeIncrease
} else { } else {
changeType = log.GiftTypeReduce changeType = log.GiftTypeReduce
@@ -80,7 +81,7 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
giftLog := log.Gift{ giftLog := log.Gift{
Type: changeType, Type: changeType,
Amount: change, Amount: change,
Balance: req.GiftAmount, Balance: *req.GiftAmount,
Remark: "Admin adjustment", Remark: "Admin adjustment",
Timestamp: time.Now().UnixMilli(), Timestamp: time.Now().UnixMilli(),
} }
@@ -95,29 +96,27 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
if err != nil { if err != nil {
return err return err
} }
userInfo.GiftAmount = req.GiftAmount userInfo.GiftAmount = *req.GiftAmount
} }
} }
if req.Commission != userInfo.Commission { if req.Commission != nil && *req.Commission != userInfo.Commission {
remark := ""
commentLog := log.Commission{ if req.Remark != nil {
Type: log.CommissionTypeAdjust, remark = *req.Remark
Amount: req.Commission - userInfo.Commission,
Timestamp: time.Now().UnixMilli(),
} }
if isWithdrawalScene(remark) {
content, _ := commentLog.Marshal() logWithdrawalGuard(l.Logger, userInfo.Id)
err = tx.Create(&log.SystemLog{ return errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "commission overwrite is blocked in withdrawal scene")
Type: log.TypeCommission.Uint8(), }
Date: time.Now().Format(time.DateOnly), change := *req.Commission - userInfo.Commission
ObjectID: userInfo.Id, if err = l.svcCtx.UserModel.UpdateCommission(l.ctx, userInfo.Id, change, tx); err != nil {
Content: string(content),
}).Error
if err != nil {
return err return err
} }
userInfo.Commission = req.Commission if err = logicCommon.WriteCommissionLog(tx, userInfo.Id, log.CommissionTypeAdjust, change, ""); err != nil {
return err
}
userInfo.Commission = *req.Commission
} }
if req.Avatar != "" { if req.Avatar != "" {
userInfo.Avatar = req.Avatar userInfo.Avatar = req.Avatar
@@ -125,15 +124,17 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
if req.ReferCode != "" { if req.ReferCode != "" {
userInfo.ReferCode = req.ReferCode userInfo.ReferCode = req.ReferCode
} }
userInfo.RefererId = req.RefererId if req.RefererId != nil {
userInfo.RefererId = *req.RefererId
}
if req.Enable != nil { if req.Enable != nil {
userInfo.Enable = req.Enable userInfo.Enable = req.Enable
} }
if req.IsAdmin != nil { if req.IsAdmin != nil {
userInfo.IsAdmin = req.IsAdmin userInfo.IsAdmin = req.IsAdmin
} }
if req.Remark != "" { if req.Remark != nil {
userInfo.Remark = req.Remark userInfo.Remark = *req.Remark
} }
if req.OnlyFirstPurchase != nil { if req.OnlyFirstPurchase != nil {
userInfo.OnlyFirstPurchase = req.OnlyFirstPurchase userInfo.OnlyFirstPurchase = req.OnlyFirstPurchase
@@ -0,0 +1,98 @@
package user
import (
"context"
"strings"
logicCommon "github.com/perfect-panel/server/internal/logic/common"
"github.com/perfect-panel/server/internal/model/log"
usermodel "github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
func approveWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdrawalID int64) error {
var approvedUserID int64
err := svcCtx.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
withdrawal, err := logicCommon.LoadPendingWithdrawalForUpdate(ctx, tx, withdrawalID)
if err != nil {
if err.Error() == "withdrawal status invalid" {
return errors.Wrapf(xerr.NewErrCode(xerr.WithdrawalStatusInvalid), "withdrawal %d already processed", withdrawalID)
}
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load withdrawal failed: %v", err)
}
// Lock user row and verify sufficient balance before deducting.
var u usermodel.User
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Where("id = ?", withdrawal.UserId).First(&u).Error; err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load user failed: %v", err)
}
if u.Commission < withdrawal.Amount {
return errors.Wrapf(xerr.NewErrCode(xerr.UserCommissionNotEnough), "user %d has insufficient commission balance", withdrawal.UserId)
}
if err := tx.Model(&usermodel.Withdrawal{}).
Where("id = ? AND status = ?", withdrawalID, usermodel.WithdrawalStatusPending).
Updates(map[string]interface{}{
"status": usermodel.WithdrawalStatusApproved,
"reason": "",
}).Error; err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "approve withdrawal failed: %v", err)
}
// Deduct commission atomically inside the transaction.
if err := tx.Model(&usermodel.User{}).
Where("id = ?", withdrawal.UserId).
UpdateColumn("commission", gorm.Expr("commission - ?", withdrawal.Amount)).Error; err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "deduct commission failed: %v", err)
}
if err := logicCommon.WriteCommissionLog(tx, withdrawal.UserId, log.CommissionTypeWithdraw, withdrawal.Amount, ""); err != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "write commission log failed: %v", err)
}
approvedUserID = withdrawal.UserId
return nil
})
if err == nil && approvedUserID > 0 {
_ = svcCtx.UserModel.ClearUserCache(ctx, &usermodel.User{Id: approvedUserID})
}
return err
}
func rejectWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdrawalID int64, reason string) error {
reason = strings.TrimSpace(reason)
return svcCtx.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
_, err := logicCommon.LoadPendingWithdrawalForUpdate(ctx, tx, withdrawalID)
if err != nil {
if err.Error() == "withdrawal status invalid" {
return errors.Wrapf(xerr.NewErrCode(xerr.WithdrawalStatusInvalid), "withdrawal %d already processed", withdrawalID)
}
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load withdrawal failed: %v", err)
}
// Commission was NOT deducted at application time under the new logic,
// so rejection requires no refund — only a status update.
return tx.Model(&usermodel.Withdrawal{}).
Where("id = ? AND status = ?", withdrawalID, usermodel.WithdrawalStatusPending).
Updates(map[string]interface{}{
"status": usermodel.WithdrawalStatusRejected,
"reason": reason,
}).Error
})
}
func isWithdrawalScene(remark string) bool {
normalized := strings.ToLower(strings.TrimSpace(remark))
return strings.Contains(normalized, "withdraw") || strings.Contains(normalized, "提现")
}
func logWithdrawalGuard(l logger.Logger, userID int64) {
l.Errorw("blocked commission overwrite in withdrawal scene", logger.Field("user_id", userID))
}
+94 -82
View File
@@ -1,108 +1,120 @@
package common package common
import ( import (
"context" "context"
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"net" "net"
"strings" "strings"
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
logmessage "github.com/perfect-panel/server/internal/model/logmessage" logmessage "github.com/perfect-panel/server/internal/model/logmessage"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types" "github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger" "github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr" "github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
type ReportLogMessageLogic struct { type ReportLogMessageLogic struct {
logger.Logger logger.Logger
ctx context.Context ctx context.Context
svcCtx *svc.ServiceContext svcCtx *svc.ServiceContext
} }
func NewReportLogMessageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReportLogMessageLogic { func NewReportLogMessageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReportLogMessageLogic {
return &ReportLogMessageLogic{ Logger: logger.WithContext(ctx), ctx: ctx, svcCtx: svcCtx } return &ReportLogMessageLogic{Logger: logger.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
} }
func (l *ReportLogMessageLogic) ReportLogMessage(req *types.ReportLogMessageRequest, c *gin.Context) (resp *types.ReportLogMessageResponse, err error) { func (l *ReportLogMessageLogic) ReportLogMessage(req *types.ReportLogMessageRequest, c *gin.Context) (resp *types.ReportLogMessageResponse, err error) {
ip := clientIP(c) ip := clientIP(c)
ua := c.GetHeader("User-Agent") ua := c.GetHeader("User-Agent")
locale := c.GetHeader("Accept-Language") locale := c.GetHeader("Accept-Language")
// 简单限流:设备ID优先,其次IP // 简单限流:设备ID优先,其次IP
limitKey := "logmsg:" + strings.TrimSpace(req.DeviceId) limitKey := "logmsg:" + strings.TrimSpace(req.DeviceId)
if limitKey == "logmsg:" { limitKey = "logmsg:" + ip } if limitKey == "logmsg:" {
count, _ := l.svcCtx.Redis.Incr(l.ctx, limitKey).Result() limitKey = "logmsg:" + ip
if count == 1 { _ = l.svcCtx.Redis.Expire(l.ctx, limitKey, 60*time.Second).Err() } }
if count > 120 { // 每分钟最多120条 count, _ := l.svcCtx.Redis.Incr(l.ctx, limitKey).Result()
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TooManyRequests), "too many reports") if count == 1 {
} _ = l.svcCtx.Redis.Expire(l.ctx, limitKey, 60*time.Second).Err()
}
if count > 120 { // 每分钟最多120条
return nil, errors.Wrapf(xerr.NewErrCode(xerr.TooManyRequests), "too many reports")
}
// 指纹生成 // 指纹生成
h := sha256.New() h := sha256.New()
h.Write([]byte(strings.Join([]string{req.Message, req.Stack, req.ErrorCode, req.AppVersion, req.Platform}, "|"))) h.Write([]byte(strings.Join([]string{req.Message, req.Stack, req.ErrorCode, req.AppVersion, req.Platform}, "|")))
digest := hex.EncodeToString(h.Sum(nil)) digest := hex.EncodeToString(h.Sum(nil))
var ctxStr string var ctxStr string
if req.Context != nil { if req.Context != nil {
if b, e := json.Marshal(req.Context); e == nil { if b, e := json.Marshal(req.Context); e == nil {
ctxStr = string(b) ctxStr = string(b)
} }
} }
var occurredAt *time.Time var occurredAt *time.Time
if req.OccurredAt > 0 { if req.OccurredAt > 0 {
t := time.UnixMilli(req.OccurredAt) t := time.UnixMilli(req.OccurredAt)
occurredAt = &t occurredAt = &t
} }
var userIdPtr *int64 var userIdPtr *int64
if req.UserId > 0 { userIdPtr = &req.UserId } if req.UserId > 0 {
userIdPtr = &req.UserId
}
row := &logmessage.LogMessage{ row := &logmessage.LogMessage{
Platform: req.Platform, Platform: safeTruncate(req.Platform, 32),
AppVersion: req.AppVersion, AppVersion: safeTruncate(req.AppVersion, 64),
OsName: req.OsName, OsName: safeTruncate(req.OsName, 64),
OsVersion: req.OsVersion, OsVersion: safeTruncate(req.OsVersion, 64),
DeviceId: req.DeviceId, DeviceId: safeTruncate(req.DeviceId, 255),
UserId: userIdPtr, UserId: userIdPtr,
SessionId: req.SessionId, SessionId: safeTruncate(req.SessionId, 255),
Level: req.Level, Level: req.Level,
ErrorCode: req.ErrorCode, ErrorCode: safeTruncate(req.ErrorCode, 128),
Message: safeTruncate(req.Message, 1024*64), Message: safeTruncate(req.Message, 1024*64),
Stack: safeTruncate(req.Stack, 1024*1024), Stack: safeTruncate(req.Stack, 1024*1024),
Context: ctxStr, Context: ctxStr,
ClientIP: ip, ClientIP: ip,
UserAgent: safeTruncate(ua, 255), UserAgent: safeTruncate(ua, 255),
Locale: safeTruncate(locale, 16), Locale: safeTruncate(locale, 16),
Digest: digest, Digest: digest,
OccurredAt: occurredAt, OccurredAt: occurredAt,
} }
if err = l.svcCtx.LogMessageModel.Insert(l.ctx, row); err != nil { if err = l.svcCtx.LogMessageModel.Insert(l.ctx, row); err != nil {
// 唯一指纹冲突时尝试查询已有记录返回ID // 唯一指纹冲突时尝试查询已有记录返回ID
ex, _, findErr := l.svcCtx.LogMessageModel.Filter(l.ctx, &logmessage.FilterParams{ Keyword: req.Message, Page: 1, Size: 1 }) ex, _, findErr := l.svcCtx.LogMessageModel.Filter(l.ctx, &logmessage.FilterParams{Keyword: req.Message, Page: 1, Size: 1})
if findErr == nil && len(ex) > 0 { if findErr == nil && len(ex) > 0 {
return &types.ReportLogMessageResponse{ Id: ex[0].Id }, nil return &types.ReportLogMessageResponse{Id: ex[0].Id}, nil
} }
l.Errorf("[ReportLogMessage] insert error: %v", err) l.Errorf("[ReportLogMessage] insert error: %v", err)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "insert log_message failed: %v", err) return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "insert log_message failed: %v", err)
} }
return &types.ReportLogMessageResponse{ Id: row.Id }, nil return &types.ReportLogMessageResponse{Id: row.Id}, nil
} }
func safeTruncate(s string, n int) string { func safeTruncate(s string, n int) string {
if len(s) <= n { return s } if len(s) <= n {
return s[:n] return s
}
return s[:n]
} }
func clientIP(c *gin.Context) string { func clientIP(c *gin.Context) string {
ip := c.ClientIP() ip := c.ClientIP()
if ip != "" { return ip } if ip != "" {
host, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)) return ip
if err == nil && host != "" { return host } }
return "" host, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr))
if err == nil && host != "" {
return host
}
return ""
} }
+48
View File
@@ -0,0 +1,48 @@
package common
import (
"context"
"time"
"github.com/perfect-panel/server/internal/model/log"
usermodel "github.com/perfect-panel/server/internal/model/user"
"github.com/pkg/errors"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
func WriteCommissionLog(tx *gorm.DB, objectID int64, logType uint16, amount int64, orderNo string) error {
logInfo := log.Commission{
Type: logType,
Amount: amount,
OrderNo: orderNo,
Timestamp: time.Now().UnixMilli(),
}
content, err := logInfo.Marshal()
if err != nil {
return err
}
return tx.Model(log.SystemLog{}).Create(&log.SystemLog{
Type: log.TypeCommission.Uint8(),
Date: time.Now().Format(time.DateOnly),
ObjectID: objectID,
Content: string(content),
CreatedAt: time.Now(),
}).Error
}
func LoadPendingWithdrawalForUpdate(ctx context.Context, tx *gorm.DB, withdrawalID int64) (*usermodel.Withdrawal, error) {
var withdrawal usermodel.Withdrawal
if err := tx.WithContext(ctx).
Clauses(clause.Locking{Strength: "UPDATE"}).
Where("id = ?", withdrawalID).
First(&withdrawal).Error; err != nil {
return nil, err
}
if withdrawal.Status != usermodel.WithdrawalStatusPending {
return nil, errors.New("withdrawal status invalid")
}
return &withdrawal, nil
}
+86 -1
View File
@@ -3,17 +3,20 @@ package notify
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"fmt"
"strconv" "strconv"
"strings" "strings"
commonLogic "github.com/perfect-panel/server/internal/logic/common" commonLogic "github.com/perfect-panel/server/internal/logic/common"
iapmodel "github.com/perfect-panel/server/internal/model/iap/apple" iapmodel "github.com/perfect-panel/server/internal/model/iap/apple"
"github.com/perfect-panel/server/internal/model/order"
"github.com/perfect-panel/server/internal/model/subscribe" "github.com/perfect-panel/server/internal/model/subscribe"
"github.com/perfect-panel/server/internal/model/user" "github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types" "github.com/perfect-panel/server/internal/types"
iapapple "github.com/perfect-panel/server/pkg/iap/apple" iapapple "github.com/perfect-panel/server/pkg/iap/apple"
"github.com/perfect-panel/server/pkg/logger" "github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/tool"
"gorm.io/gorm" "gorm.io/gorm"
) )
@@ -84,6 +87,7 @@ func (l *AppleIAPNotifyLogic) Handle(signedPayload string) error {
l.Errorw("iap notify insert transaction error", logger.Field("error", e.Error()), logger.Field("productId", txPayload.ProductId), logger.Field("originalTransactionId", txPayload.OriginalTransactionId)) l.Errorw("iap notify insert transaction error", logger.Field("error", e.Error()), logger.Field("productId", txPayload.ProductId), logger.Field("originalTransactionId", txPayload.OriginalTransactionId))
return e return e
} }
existing = rec
} else { } else {
if txPayload.RevocationDate != nil { if txPayload.RevocationDate != nil {
// 撤销场景:更新 revocation_at // 撤销场景:更新 revocation_at
@@ -96,6 +100,32 @@ func (l *AppleIAPNotifyLogic) Handle(signedPayload string) error {
} }
} }
} }
// Fix Bug 7: resolve userId when the IAP transaction record has no associated user.
// This can happen if the first notification for a subscription arrived before the
// in-app purchase flow created the order (race) or the order was made in a previous
// build that did not write user_id to the IAP transaction table.
if existing != nil && existing.UserId == 0 {
var origOrder order.Order
if lookupErr := db.Model(&order.Order{}).
Where("trade_no = ? AND method = ?", txPayload.OriginalTransactionId, "apple_iap").
Order("id ASC").
First(&origOrder).Error; lookupErr == nil && origOrder.UserId > 0 {
existing.UserId = origOrder.UserId
_ = db.Model(&iapmodel.Transaction{}).
Where("id = ?", existing.Id).
Update("user_id", origOrder.UserId).Error
l.Infow("iap notify resolved zero userId from original purchase order",
logger.Field("userId", origOrder.UserId),
logger.Field("originalTransactionId", txPayload.OriginalTransactionId),
)
} else {
l.Errorw("CRITICAL: iap notify UserId=0 and cannot resolve from order, notification dropped",
logger.Field("originalTransactionId", txPayload.OriginalTransactionId))
return fmt.Errorf("iap notify: UserId=0 and cannot resolve from order for original_transaction_id=%s", txPayload.OriginalTransactionId)
}
}
var days int64 var days int64
{ {
pid := strings.ToLower(txPayload.ProductId) pid := strings.ToLower(txPayload.ProductId)
@@ -169,7 +199,12 @@ func (l *AppleIAPNotifyLogic) Handle(signedPayload string) error {
} }
} }
if days == 0 { if days == 0 {
l.Errorw("iap notify product mapping missing", logger.Field("productId", txPayload.ProductId)) // Both string-parse and DB fallback failed to map the product to days.
// Return an error so Apple retries the notification; silently ignoring
// this would cause the subscriber's renewal to be lost.
l.Errorw("CRITICAL: iap notify product mapping missing, returning error to trigger retry",
logger.Field("productId", txPayload.ProductId))
return fmt.Errorf("iap product id %s could not be mapped to subscription days", txPayload.ProductId)
} }
token := "iap:" + txPayload.OriginalTransactionId token := "iap:" + txPayload.OriginalTransactionId
sub, e := l.svcCtx.UserModel.FindOneSubscribeByToken(l.ctx, token) sub, e := l.svcCtx.UserModel.FindOneSubscribeByToken(l.ctx, token)
@@ -216,6 +251,11 @@ func (l *AppleIAPNotifyLogic) Handle(signedPayload string) error {
logger.Field("product_id", txPayload.ProductId), logger.Field("product_id", txPayload.ProductId),
)..., )...,
) )
// Create audit order record for renewal notifications (Bug 7)
if err := l.createIAPRenewalAuditOrder(db, ntype, txPayload.TransactionId, candidate.UserId, candidate.SubscribeId, candidate.Token); err != nil {
l.Errorw("iap notify fallback create renewal order error", logger.Field("error", err.Error()))
// Non-fatal: subscription already updated; order creation failure is logged only
}
break break
} }
} }
@@ -248,7 +288,52 @@ func (l *AppleIAPNotifyLogic) Handle(signedPayload string) error {
logger.Field("product_id", txPayload.ProductId), logger.Field("product_id", txPayload.ProductId),
)..., )...,
) )
// Create audit order record for renewal notifications (Bug 7)
if err := l.createIAPRenewalAuditOrder(db, ntype, txPayload.TransactionId, sub.UserId, sub.SubscribeId, sub.Token); err != nil {
l.Errorw("iap notify create renewal order error", logger.Field("error", err.Error()))
// Non-fatal: subscription already updated; order creation failure is logged only
}
} }
return nil return nil
}) })
} }
// createIAPRenewalAuditOrder creates a finished renewal order record for DID_RENEW and SUBSCRIBED
// Apple SSNS notifications so that the order table has a complete financial audit trail.
// The operation is idempotent: if an order with the same trade_no already exists it is skipped.
func (l *AppleIAPNotifyLogic) createIAPRenewalAuditOrder(db *gorm.DB, ntype, transactionId string, userId, subscribeId int64, subscribeToken string) error {
if ntype != "DID_RENEW" && ntype != "SUBSCRIBED" {
return nil
}
// Idempotency check
var count int64
if err := db.Model(&order.Order{}).
Where("trade_no = ? AND method = ?", transactionId, "apple_iap").
Count(&count).Error; err != nil {
return fmt.Errorf("check existing iap renewal order: %w", err)
}
if count > 0 {
return nil
}
rec := &order.Order{
UserId: userId,
OrderNo: tool.GenerateTradeNo(),
Type: 2, // OrderTypeRenewal
Status: 5, // OrderStatusFinished
Method: "apple_iap",
TradeNo: transactionId,
SubscribeId: subscribeId,
SubscribeToken: subscribeToken,
Quantity: 1,
IsNew: false,
}
if err := db.Model(&order.Order{}).Create(rec).Error; err != nil {
return fmt.Errorf("create iap renewal audit order: %w", err)
}
l.Infow("iap notify created renewal audit order",
logger.Field("orderNo", rec.OrderNo),
logger.Field("transactionId", transactionId),
logger.Field("userId", userId),
)
return nil
}
+4 -4
View File
@@ -109,14 +109,14 @@ func buildObjectKey(prefix string, userID int64, bizType, fileID, fileName strin
if prefix == "" { if prefix == "" {
prefix = "app-upload" prefix = "app-upload"
} }
return fmt.Sprintf("%s/%s/%d/%04d/%02d/%s_%s", return fmt.Sprintf("%s/%04d/%02d/%02d/%d/%s__%s",
prefix, prefix,
strings.Trim(safeFileNameRegexp.ReplaceAllString(strings.ToLower(strings.TrimSpace(bizType)), "-"), "-"),
userID,
now.Year(), now.Year(),
int(now.Month()), int(now.Month()),
fileID, now.Day(),
userID,
safeFileName(fileName), safeFileName(fileName),
fileID,
) )
} }
@@ -0,0 +1,88 @@
package file
import (
"bytes"
"context"
"io"
"mime/multipart"
"net/http"
"time"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
)
type FileUploadLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// Upload file to RustFS
func NewFileUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FileUploadLogic {
return &FileUploadLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *FileUploadLogic) FileUpload(req *types.FileUploadRequest, fileHeader *multipart.FileHeader, file multipart.File) (resp *types.FileUploadResponse, err error) {
u, err := currentUserFromContext(l.ctx)
if err != nil {
return nil, err
}
if fileHeader == nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "file is required")
}
contentType, err := sniffContentType(fileHeader, file)
if err != nil {
return nil, err
}
if err := validateInitRequest(l.svcCtx, req.BizType, fileHeader.Filename, contentType, fileHeader.Size); err != nil {
return nil, err
}
now := time.Now()
fileID := buildFileID(u.Id, req.BizType, fileHeader.Filename)
objectKey := buildObjectKey(l.svcCtx.Config.S3.Prefix, u.Id, req.BizType, fileID, fileHeader.Filename, now)
putResult, err := l.svcCtx.S3Store.PutObject(l.ctx, objectKey, file, fileHeader.Size, contentType)
if err != nil {
l.Errorw("put object failed", logger.Field("error", err.Error()), logger.Field("user_id", u.Id), logger.Field("file_id", fileID))
return nil, err
}
return &types.FileUploadResponse{
FileId: fileID,
FileName: fileHeader.Filename,
ObjectKey: objectKey,
Size: fileHeader.Size,
ContentType: contentType,
Etag: putResult.ETag,
Status: fileUploadCompleteStatus,
}, nil
}
func sniffContentType(fileHeader *multipart.FileHeader, file multipart.File) (string, error) {
if headerType := fileHeader.Header.Get("Content-Type"); headerType != "" {
return headerType, nil
}
if seeker, ok := file.(io.ReadSeeker); ok {
buf := make([]byte, 512)
n, readErr := seeker.Read(buf)
if readErr != nil && readErr != io.EOF {
return "", readErr
}
if _, err := seeker.Seek(0, io.SeekStart); err != nil {
return "", err
}
return http.DetectContentType(bytes.TrimRight(buf[:n], "\x00")), nil
}
return "application/octet-stream", nil
}
@@ -154,9 +154,12 @@ func (l *PurchaseLogic) Purchase(req *types.PortalPurchaseRequest) (resp *types.
} }
content, _ := tempOrder.Marshal() content, _ := tempOrder.Marshal()
if _, err = l.svcCtx.Redis.Set(l.ctx, fmt.Sprintf(constant.TempOrderCacheKey, orderInfo.OrderNo), string(content), CloseOrderTimeMinutes*time.Minute).Result(); err != nil { // Persist activation context to DB so the worker can recover if Redis TTL expires.
l.Errorw("[Purchase] Redis set error", logger.Field("error", err.Error()), logger.Field("order_no", orderInfo.OrderNo)) orderInfo.ActivationContext = string(content)
return err
// Write to Redis as a hot cache (best-effort; non-fatal on failure).
if _, redisErr := l.svcCtx.Redis.Set(l.ctx, fmt.Sprintf(constant.TempOrderCacheKey, orderInfo.OrderNo), string(content), CloseOrderTimeMinutes*time.Minute).Result(); redisErr != nil {
l.Infow("[Purchase] Redis set error (non-fatal, DB fallback available)", logger.Field("error", redisErr.Error()), logger.Field("order_no", orderInfo.OrderNo))
} }
l.Infow("[Purchase] Guest order", logger.Field("order_no", orderInfo.OrderNo), logger.Field("identifier", req.Identifier)) l.Infow("[Purchase] Guest order", logger.Field("order_no", orderInfo.OrderNo), logger.Field("identifier", req.Identifier))
@@ -169,7 +172,7 @@ func (l *PurchaseLogic) Purchase(req *types.PortalPurchaseRequest) (resp *types.
} }
} }
// save guest order // save guest order (activation_context is included)
if err = l.svcCtx.OrderModel.Insert(l.ctx, orderInfo, tx); err != nil { if err = l.svcCtx.OrderModel.Insert(l.ctx, orderInfo, tx); err != nil {
return err return err
} }
@@ -151,34 +151,48 @@ func (l *RedeemCodeLogic) RedeemCode(req *types.RedeemCodeRequest) (resp *types.
} }
// 创建Order记录 // 创建Order记录
redemptionContext := struct {
Type string `json:"type"`
RedemptionCodeId int64 `json:"redemption_code_id"`
UnitTime string `json:"unit_time"`
Quantity int64 `json:"quantity"`
}{
Type: "redemption",
RedemptionCodeId: redemptionCode.Id,
UnitTime: redemptionCode.UnitTime,
Quantity: redemptionCode.Quantity,
}
activationContextJSON, _ := json.Marshal(redemptionContext)
orderInfo := &order.Order{ orderInfo := &order.Order{
UserId: u.Id, UserId: u.Id,
OrderNo: tool.GenerateTradeNo(), OrderNo: tool.GenerateTradeNo(),
Type: 5, // 兑换类型 Type: 5, // 兑换类型
Quantity: redemptionCode.Quantity, Quantity: redemptionCode.Quantity,
Price: 0, // 兑换无价格 Price: 0, // 兑换无价格
Amount: 0, // 兑换无金额 Amount: 0, // 兑换无金额
Discount: 0, Discount: 0,
GiftAmount: 0, GiftAmount: 0,
Coupon: "", Coupon: "",
CouponDiscount: 0, CouponDiscount: 0,
PaymentId: 0, PaymentId: 0,
Method: "redemption", Method: "redemption",
FeeAmount: 0, FeeAmount: 0,
Commission: 0, Commission: 0,
Status: 2, // 直接设置为已支付 Status: 2, // 直接设置为已支付
SubscribeId: redemptionCode.SubscribePlan, SubscribeId: redemptionCode.SubscribePlan,
IsNew: isNew, IsNew: isNew,
ActivationContext: string(activationContextJSON),
} }
// 保存Order到数据库 // 保存Order到数据库activation_context 同步写入,作为 Redis 的持久化兜底)
err = l.svcCtx.OrderModel.Insert(l.ctx, orderInfo) err = l.svcCtx.OrderModel.Insert(l.ctx, orderInfo)
if err != nil { if err != nil {
l.Errorw("[RedeemCode] Create order failed", logger.Field("error", err.Error())) l.Errorw("[RedeemCode] Create order failed", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create order failed") return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create order failed")
} }
// 缓存兑换码信息到Redis(供队列任务使用 // 缓存兑换码信息到Redis热缓存,供队列任务快速读取,非关键路径
cacheKey := fmt.Sprintf("redemption_order:%s", orderInfo.OrderNo) cacheKey := fmt.Sprintf("redemption_order:%s", orderInfo.OrderNo)
cacheData := map[string]interface{}{ cacheData := map[string]interface{}{
"redemption_code_id": redemptionCode.Id, "redemption_code_id": redemptionCode.Id,
@@ -186,16 +200,8 @@ func (l *RedeemCodeLogic) RedeemCode(req *types.RedeemCodeRequest) (resp *types.
"quantity": redemptionCode.Quantity, "quantity": redemptionCode.Quantity,
} }
jsonData, _ := json.Marshal(cacheData) jsonData, _ := json.Marshal(cacheData)
err = l.svcCtx.Redis.Set(l.ctx, cacheKey, jsonData, 2*time.Hour).Err() if redisErr := l.svcCtx.Redis.Set(l.ctx, cacheKey, jsonData, 2*time.Hour).Err(); redisErr != nil {
if err != nil { l.Infow("[RedeemCode] Cache redemption data failed (non-fatal, DB fallback available)", logger.Field("error", redisErr.Error()))
l.Errorw("[RedeemCode] Cache redemption data failed", logger.Field("error", err.Error()))
// 缓存失败,删除已创建的Order避免孤儿记录
if delErr := l.svcCtx.OrderModel.Delete(l.ctx, orderInfo.Id); delErr != nil {
l.Errorw("[RedeemCode] Delete order failed after cache error",
logger.Field("order_id", orderInfo.Id),
logger.Field("error", delErr.Error()))
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "cache redemption data failed")
} }
// 触发队列任务 // 触发队列任务
@@ -0,0 +1,89 @@
package user
import (
"context"
logicCommon "github.com/perfect-panel/server/internal/logic/common"
"github.com/perfect-panel/server/internal/model/log"
"github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/constant"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
)
type CancelWithdrawalLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewCancelWithdrawalLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CancelWithdrawalLogic {
return &CancelWithdrawalLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *CancelWithdrawalLogic) CancelWithdrawal(req *types.CancelWithdrawalRequest) (resp *types.WithdrawalLog, err error) {
u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
if !ok {
l.Error("current user is not found in context")
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
}
var withdrawal *user.Withdrawal
err = l.svcCtx.DB.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error {
var txErr error
withdrawal, txErr = logicCommon.LoadPendingWithdrawalForUpdate(l.ctx, tx, req.WithdrawalId)
if txErr != nil {
if txErr.Error() == "withdrawal status invalid" {
return errors.Wrapf(xerr.NewErrCode(xerr.WithdrawalStatusInvalid), "withdrawal %d is not in pending state", req.WithdrawalId)
}
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load withdrawal failed: %v", txErr)
}
if withdrawal.UserId != u.Id {
return errors.Wrapf(xerr.NewErrCode(xerr.PermissionDenied), "user %d cannot cancel withdrawal belonging to user %d", u.Id, withdrawal.UserId)
}
if txErr = tx.Model(&user.Withdrawal{}).
Where("id = ? AND status = ?", req.WithdrawalId, user.WithdrawalStatusPending).
Update("status", user.WithdrawalStatusCancelled).Error; txErr != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "cancel withdrawal failed: %v", txErr)
}
if txErr = l.svcCtx.UserModel.UpdateCommission(l.ctx, withdrawal.UserId, withdrawal.Amount, tx); txErr != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "refund commission failed: %v", txErr)
}
if txErr = logicCommon.WriteCommissionLog(tx, withdrawal.UserId, log.CommissionTypeWithdrawCancel, withdrawal.Amount, ""); txErr != nil {
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "write commission log failed: %v", txErr)
}
return nil
})
if err != nil {
return nil, err
}
_ = l.svcCtx.UserModel.ClearUserCache(l.ctx, u)
return &types.WithdrawalLog{
Id: withdrawal.Id,
UserId: withdrawal.UserId,
Amount: withdrawal.Amount,
Content: withdrawal.Content,
Status: user.WithdrawalStatusCancelled,
Reason: "",
Method: withdrawal.Method,
Account: withdrawal.Account,
QrCodeUrl: withdrawal.QrCodeUrl,
CreatedAt: withdrawal.CreatedAt.UnixMilli(),
UpdatedAt: withdrawal.UpdatedAt.UnixMilli(),
}, nil
}
@@ -2,9 +2,7 @@ package user
import ( import (
"context" "context"
"time"
"github.com/perfect-panel/server/internal/model/log"
"github.com/perfect-panel/server/internal/model/user" "github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types" "github.com/perfect-panel/server/internal/types"
@@ -12,6 +10,7 @@ import (
"github.com/perfect-panel/server/pkg/logger" "github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr" "github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors" "github.com/pkg/errors"
"gorm.io/gorm"
) )
type CommissionWithdrawLogic struct { type CommissionWithdrawLogic struct {
@@ -36,73 +35,70 @@ func (l *CommissionWithdrawLogic) CommissionWithdraw(req *types.CommissionWithdr
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access") return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
} }
if u.Commission < req.Amount { // Validate payment method fields
logger.Errorf("User %d has insufficient commission balance: %.2f, requested: %.2f", u.Id, float64(u.Commission)/100, float64(req.Amount)/100) switch req.Method {
case user.WithdrawalMethodAlipay, user.WithdrawalMethodWechat:
if req.QrCodeUrl == "" {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "qr_code_url is required for method %d", req.Method)
}
case user.WithdrawalMethodBank:
if req.Account == "" {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "account is required for bank transfer")
}
default: // WithdrawalMethodOther
if req.Account == "" && req.Content == "" {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "account or content is required for other methods")
}
}
// Sum all pending (status=0) withdrawals to compute available balance.
// Available = commission - pendingTotal; commission is only deducted on approval.
var pendingTotal int64
if err = l.svcCtx.DB.WithContext(l.ctx).
Model(&user.Withdrawal{}).
Where("user_id = ? AND status = ?", u.Id, user.WithdrawalStatusPending).
Select("COALESCE(SUM(amount), 0)").
Scan(&pendingTotal).Error; err != nil {
l.Errorf("Failed to query pending withdrawals for user %d: %v", u.Id, err)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Failed to query pending withdrawals for user %d", u.Id)
}
if u.Commission < req.Amount+pendingTotal {
logger.Errorf("User %d insufficient available commission: total=%d pending=%d requested=%d",
u.Id, u.Commission, pendingTotal, req.Amount)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserCommissionNotEnough), "User %d has insufficient commission balance", u.Id) return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserCommissionNotEnough), "User %d has insufficient commission balance", u.Id)
} }
tx := l.svcCtx.DB.WithContext(l.ctx).Begin() var w user.Withdrawal
err = l.svcCtx.DB.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error {
// update user commission balance w = user.Withdrawal{
u.Commission -= req.Amount UserId: u.Id,
if err = l.svcCtx.UserModel.Update(l.ctx, u, tx); err != nil { Amount: req.Amount,
tx.Rollback() Content: req.Content,
l.Errorf("Failed to update user %d commission balance: %v", u.Id, err) Status: user.WithdrawalStatusPending,
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "Failed to update user %d commission balance: %v", u.Id, err) Reason: "",
} Method: req.Method,
Account: req.Account,
// create withdrawal log QrCodeUrl: req.QrCodeUrl,
logInfo := log.Commission{ }
Type: log.CommissionTypeConvertBalance, return tx.Create(&w).Error
Amount: req.Amount, })
Timestamp: time.Now().UnixMilli(),
}
b, err := logInfo.Marshal()
if err != nil { if err != nil {
tx.Rollback() l.Errorf("Failed to create withdrawal for user %d: %v", u.Id, err)
l.Errorf("Failed to marshal commission log for user %d: %v", u.Id, err) return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "Failed to create withdrawal for user %d: %v", u.Id, err)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Failed to marshal commission log for user %d: %v", u.Id, err)
}
err = tx.Model(log.SystemLog{}).Create(&log.SystemLog{
Type: log.TypeCommission.Uint8(),
Date: time.Now().Format("2006-01-02"),
ObjectID: u.Id,
Content: string(b),
CreatedAt: time.Now(),
}).Error
if err != nil {
tx.Rollback()
l.Errorf("Failed to create commission log for user %d: %v", u.Id, err)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "Failed to create commission log for user %d: %v", u.Id, err)
}
err = tx.Model(&user.Withdrawal{}).Create(&user.Withdrawal{
UserId: u.Id,
Amount: req.Amount,
Content: req.Content,
Status: 0,
Reason: "",
}).Error
if err != nil {
tx.Rollback()
l.Errorf("Failed to create withdrawal log for user %d: %v", u.Id, err)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "Failed to create withdrawal log for user %d: %v", u.Id, err)
}
if err = tx.Commit().Error; err != nil {
l.Errorf("Transaction commit failed for user %d withdrawal: %v", u.Id, err)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Transaction commit failed for user %d withdrawal: %v", u.Id, err)
} }
return &types.WithdrawalLog{ return &types.WithdrawalLog{
Id: w.Id,
UserId: u.Id, UserId: u.Id,
Amount: req.Amount, Amount: req.Amount,
Content: req.Content, Content: req.Content,
Status: 0, Status: user.WithdrawalStatusPending,
Reason: "", Reason: "",
CreatedAt: time.Now().UnixMilli(), Method: req.Method,
Account: req.Account,
QrCodeUrl: req.QrCodeUrl,
CreatedAt: w.CreatedAt.UnixMilli(),
UpdatedAt: w.UpdatedAt.UnixMilli(),
}, nil }, nil
} }
@@ -6,7 +6,9 @@ import (
"sort" "sort"
"strings" "strings"
authlogic "github.com/perfect-panel/server/internal/logic/auth"
logicCommon "github.com/perfect-panel/server/internal/logic/common" logicCommon "github.com/perfect-panel/server/internal/logic/common"
modelOrder "github.com/perfect-panel/server/internal/model/order"
"github.com/perfect-panel/server/pkg/constant" "github.com/perfect-panel/server/pkg/constant"
"github.com/perfect-panel/server/pkg/uuidx" "github.com/perfect-panel/server/pkg/uuidx"
"github.com/perfect-panel/server/pkg/xerr" "github.com/perfect-panel/server/pkg/xerr"
@@ -44,6 +46,7 @@ func (l *QueryUserInfoLogic) QueryUserInfo() (resp *types.User, err error) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access") return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
} }
tool.DeepCopy(resp, u) tool.DeepCopy(resp, u)
resp.UseStatus = true
// 用家庭范围查设备,而不是只看当前用户自己的 UserDevices // 用家庭范围查设备,而不是只看当前用户自己的 UserDevices
scopeHelper := newFamilyScopeHelper(l.ctx, l.svcCtx) scopeHelper := newFamilyScopeHelper(l.ctx, l.svcCtx)
@@ -65,6 +68,14 @@ func (l *QueryUserInfoLogic) QueryUserInfo() (resp *types.User, err error) {
} }
resp.UserDevices = userDevices resp.UserDevices = userDevices
} }
useStatus, useStatusErr := l.resolveBindEmailTrialUseStatus(u.Id, scopeUserIds)
if useStatusErr != nil {
l.Errorw("resolve bind email trial use status failed", logger.Field("user_id", u.Id), logger.Field("error", useStatusErr.Error()))
} else {
resp.UseStatus = useStatus
}
// refer_code 为空时自动生成 // refer_code 为空时自动生成
if resp.ReferCode == "" { if resp.ReferCode == "" {
resp.ReferCode = uuidx.UserInviteCode(u.Id) resp.ReferCode = uuidx.UserInviteCode(u.Id)
@@ -108,6 +119,49 @@ func (l *QueryUserInfoLogic) QueryUserInfo() (resp *types.User, err error) {
return resp, nil return resp, nil
} }
// resolveBindEmailTrialUseStatus determines whether userinfo should show the
// "bind email to get free trial" prompt. `true` means show the prompt.
func (l *QueryUserInfoLogic) resolveBindEmailTrialUseStatus(currentUserId int64, scopeUserIds []int64) (bool, error) {
if len(scopeUserIds) == 0 {
scopeUserIds = []int64{currentUserId}
}
var hasBoundEmailCount int64
if err := l.svcCtx.DB.WithContext(l.ctx).
Model(&user.AuthMethods{}).
Where("user_id IN ? AND auth_type = ? AND auth_identifier != ''", scopeUserIds, "email").
Count(&hasBoundEmailCount).Error; err != nil {
return false, err
}
var hasPurchaseCount int64
if err := l.svcCtx.DB.WithContext(l.ctx).
Model(&modelOrder.Order{}).
Where("user_id IN ? AND type IN ? AND status IN ?", scopeUserIds, []int64{1, 2}, []int64{2, 5}).
Count(&hasPurchaseCount).Error; err != nil {
return false, err
}
hasTrial := false
registerCfg := l.svcCtx.Config.Register
if authlogic.IsTrialConfigReady(registerCfg) && registerCfg.TrialSubscribe > 0 {
var hasTrialCount int64
if err := l.svcCtx.DB.WithContext(l.ctx).
Model(&user.Subscribe{}).
Where("user_id IN ? AND subscribe_id = ?", scopeUserIds, registerCfg.TrialSubscribe).
Count(&hasTrialCount).Error; err != nil {
return false, err
}
hasTrial = hasTrialCount > 0
}
return shouldShowBindEmailTrialPrompt(hasBoundEmailCount > 0, hasPurchaseCount > 0, hasTrial), nil
}
func shouldShowBindEmailTrialPrompt(hasBoundEmail, hasPurchased, hasTrial bool) bool {
return !hasBoundEmail && !hasPurchased && !hasTrial
}
func (l *QueryUserInfoLogic) fillFamilyContext(resp *types.User, userId int64) *user.AuthMethods { func (l *QueryUserInfoLogic) fillFamilyContext(resp *types.User, userId int64) *user.AuthMethods {
type familyRelation struct { type familyRelation struct {
FamilyId int64 FamilyId int64
@@ -0,0 +1,67 @@
package user
import "testing"
func TestShouldShowBindEmailTrialPrompt(t *testing.T) {
tests := []struct {
name string
hasBoundEmail bool
hasPurchased bool
hasTrial bool
want bool
}{
{
name: "new user should see prompt",
want: true,
},
{
name: "bound email should hide prompt",
hasBoundEmail: true,
want: false,
},
{
name: "paid purchase should hide prompt",
hasPurchased: true,
want: false,
},
{
name: "trial claimed should hide prompt",
hasTrial: true,
want: false,
},
{
name: "bound email and purchase should hide prompt",
hasBoundEmail: true,
hasPurchased: true,
want: false,
},
{
name: "bound email and trial should hide prompt",
hasBoundEmail: true,
hasTrial: true,
want: false,
},
{
name: "purchase and trial should hide prompt",
hasPurchased: true,
hasTrial: true,
want: false,
},
{
name: "all blockers should hide prompt",
hasBoundEmail: true,
hasPurchased: true,
hasTrial: true,
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := shouldShowBindEmailTrialPrompt(tt.hasBoundEmail, tt.hasPurchased, tt.hasTrial)
if got != tt.want {
t.Fatalf("shouldShowBindEmailTrialPrompt(%v, %v, %v) = %v, want %v", tt.hasBoundEmail, tt.hasPurchased, tt.hasTrial, got, tt.want)
}
})
}
}
@@ -3,9 +3,13 @@ package user
import ( import (
"context" "context"
"github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc" "github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types" "github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/constant"
"github.com/perfect-panel/server/pkg/logger" "github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
) )
type QueryWithdrawalLogLogic struct { type QueryWithdrawalLogLogic struct {
@@ -24,7 +28,52 @@ func NewQueryWithdrawalLogLogic(ctx context.Context, svcCtx *svc.ServiceContext)
} }
func (l *QueryWithdrawalLogLogic) QueryWithdrawalLog(req *types.QueryWithdrawalLogListRequest) (resp *types.QueryWithdrawalLogListResponse, err error) { func (l *QueryWithdrawalLogLogic) QueryWithdrawalLog(req *types.QueryWithdrawalLogListRequest) (resp *types.QueryWithdrawalLogListResponse, err error) {
// todo: add your logic here and delete this line u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
if !ok {
l.Error("current user is not found in context")
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
}
return page := req.Page
size := req.Size
if page <= 0 {
page = 1
}
if size <= 0 {
size = 10
}
query := l.svcCtx.DB.WithContext(l.ctx).Model(&user.Withdrawal{}).Where("user_id = ?", u.Id)
var total int64
if err = query.Count(&total).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count withdrawal logs failed: %v", err)
}
var rows []user.Withdrawal
if err = query.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&rows).Error; err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query withdrawal logs failed: %v", err)
}
list := make([]types.WithdrawalLog, 0, len(rows))
for _, row := range rows {
list = append(list, types.WithdrawalLog{
Id: row.Id,
UserId: row.UserId,
Amount: row.Amount,
Content: row.Content,
Status: row.Status,
Reason: row.Reason,
Method: row.Method,
Account: row.Account,
QrCodeUrl: row.QrCodeUrl,
CreatedAt: row.CreatedAt.UnixMilli(),
UpdatedAt: row.UpdatedAt.UnixMilli(),
})
}
return &types.QueryWithdrawalLogListResponse{
List: list,
Total: total,
}, nil
} }
+17
View File
@@ -31,6 +31,8 @@ const (
ctxDecryptedQueryKey = "decrypted_query" ctxDecryptedQueryKey = "decrypted_query"
ctxEncryptedBodyKey = "encrypted_request_body" ctxEncryptedBodyKey = "encrypted_request_body"
ctxDecryptedBodyKey = "decrypted_request_body" ctxDecryptedBodyKey = "decrypted_request_body"
deviceDecryptSkipPathPublicFileUpload = "/v1/public/file/upload"
) )
func DeviceMiddleware(srvCtx *svc.ServiceContext) func(c *gin.Context) { func DeviceMiddleware(srvCtx *svc.ServiceContext) func(c *gin.Context) {
@@ -70,6 +72,14 @@ func DeviceMiddleware(srvCtx *svc.ServiceContext) func(c *gin.Context) {
} }
rw := NewResponseWriter(c, srvCtx) rw := NewResponseWriter(c, srvCtx)
if shouldSkipDeviceRequestDecrypt(c) {
c.Set(ctxDeviceDecryptStatusKey, "skipped")
c.Set(ctxDeviceDecryptReasonKey, "multipart_upload_passthrough")
c.Writer = rw
c.Next()
rw.FlushAbort()
return
}
if !rw.Decrypt() { if !rw.Decrypt() {
c.Set(ctxDeviceDecryptStatusKey, "failed") c.Set(ctxDeviceDecryptStatusKey, "failed")
if _, exists := c.Get(ctxDeviceDecryptReasonKey); !exists { if _, exists := c.Get(ctxDeviceDecryptReasonKey); !exists {
@@ -85,6 +95,13 @@ func DeviceMiddleware(srvCtx *svc.ServiceContext) func(c *gin.Context) {
} }
} }
func shouldSkipDeviceRequestDecrypt(c *gin.Context) bool {
if c.Request.URL.Path != deviceDecryptSkipPathPublicFileUpload {
return false
}
return strings.HasPrefix(strings.ToLower(strings.TrimSpace(c.GetHeader("Content-Type"))), "multipart/form-data")
}
func NewResponseWriter(c *gin.Context, srvCtx *svc.ServiceContext) (rw *ResponseWriter) { func NewResponseWriter(c *gin.Context, srvCtx *svc.ServiceContext) (rw *ResponseWriter) {
rw = &ResponseWriter{ rw = &ResponseWriter{
c: c, c: c,
+39
View File
@@ -23,6 +23,7 @@ const (
TypeSubscribeTraffic Type = 21 // Subscription traffic log TypeSubscribeTraffic Type = 21 // Subscription traffic log
TypeServerTraffic Type = 22 // Server traffic log TypeServerTraffic Type = 22 // Server traffic log
TypeResetSubscribe Type = 23 // Reset subscription log TypeResetSubscribe Type = 23 // Reset subscription log
TypeOrderRefund Type = 24 // Admin order refund log
TypeLogin Type = 30 // Login log TypeLogin Type = 30 // Login log
TypeRegister Type = 31 // Registration log TypeRegister Type = 31 // Registration log
TypeBalance Type = 32 // Balance log TypeBalance Type = 32 // Balance log
@@ -49,6 +50,8 @@ const (
CommissionTypeWithdraw uint16 = 334 // withdraw CommissionTypeWithdraw uint16 = 334 // withdraw
CommissionTypeAdjust uint16 = 335 // Admin Adjust CommissionTypeAdjust uint16 = 335 // Admin Adjust
CommissionTypeConvertBalance uint16 = 336 // Convert to Balance CommissionTypeConvertBalance uint16 = 336 // Convert to Balance
CommissionTypeWithdrawReject uint16 = 337 // Withdraw rejected refund
CommissionTypeWithdrawCancel uint16 = 338 // 用户取消提现退佣金
GiftTypeIncrease uint16 = 341 // Increase GiftTypeIncrease uint16 = 341 // Increase
GiftTypeReduce uint16 = 342 // Reduce GiftTypeReduce uint16 = 342 // Reduce
) )
@@ -277,6 +280,42 @@ func (c *Commission) Unmarshal(data []byte) error {
return json.Unmarshal(data, aux) return json.Unmarshal(data, aux)
} }
type OrderRefund struct {
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"`
}
func (o *OrderRefund) Marshal() ([]byte, error) {
type Alias OrderRefund
return json.Marshal(&struct {
*Alias
}{
Alias: (*Alias)(o),
})
}
func (o *OrderRefund) Unmarshal(data []byte) error {
type Alias OrderRefund
aux := (*Alias)(o)
return json.Unmarshal(data, aux)
}
// Gift represents a gift log entry. // Gift represents a gift log entry.
type Gift struct { type Gift struct {
Type uint16 `json:"type"` Type uint16 `json:"type"`
+19 -19
View File
@@ -3,25 +3,25 @@ package logmessage
import "time" import "time"
type LogMessage struct { type LogMessage struct {
Id int64 `gorm:"primaryKey;AUTO_INCREMENT"` Id int64 `gorm:"primaryKey;AUTO_INCREMENT"`
Platform string `gorm:"type:varchar(32);not null"` Platform string `gorm:"type:varchar(32);not null"`
AppVersion string `gorm:"type:varchar(32);default:null"` AppVersion string `gorm:"type:varchar(64);default:null"`
OsName string `gorm:"type:varchar(32);default:null"` OsName string `gorm:"type:varchar(64);default:null"`
OsVersion string `gorm:"type:varchar(32);default:null"` OsVersion string `gorm:"type:varchar(64);default:null"`
DeviceId string `gorm:"type:varchar(64);default:null"` DeviceId string `gorm:"type:varchar(255);default:null"`
UserId *int64 `gorm:"type:bigint;default:null"` UserId *int64 `gorm:"type:bigint;default:null"`
SessionId string `gorm:"type:varchar(64);default:null"` SessionId string `gorm:"type:varchar(255);default:null"`
Level uint8 `gorm:"type:tinyint(1);not null;default:3"` Level uint8 `gorm:"type:tinyint(1);not null;default:3"`
ErrorCode string `gorm:"type:varchar(64);default:null"` ErrorCode string `gorm:"type:varchar(128);default:null"`
Message string `gorm:"type:text;not null"` Message string `gorm:"type:text;not null"`
Stack string `gorm:"type:mediumtext;default:null"` Stack string `gorm:"type:mediumtext;default:null"`
Context string `gorm:"type:json;default:null"` Context string `gorm:"type:json;default:null"`
ClientIP string `gorm:"type:varchar(45);default:null"` ClientIP string `gorm:"type:varchar(45);default:null"`
UserAgent string `gorm:"type:varchar(255);default:null"` UserAgent string `gorm:"type:varchar(255);default:null"`
Locale string `gorm:"type:varchar(16);default:null"` Locale string `gorm:"type:varchar(16);default:null"`
Digest string `gorm:"type:varchar(64);uniqueIndex:uniq_digest;default:null"` Digest string `gorm:"type:varchar(64);uniqueIndex:uniq_digest;default:null"`
OccurredAt *time.Time `gorm:"type:datetime;default:null"` OccurredAt *time.Time `gorm:"type:datetime;default:null"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"` CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
} }
func (LogMessage) TableName() string { return "log_message" } func (LogMessage) TableName() string { return "log_message" }
+5 -1
View File
@@ -110,6 +110,10 @@ func (m *customOrderModel) UpdateOrderStatus(ctx context.Context, orderNo string
if err != nil { if err != nil {
return err return err
} }
keys := m.getCacheKeys(orderInfo)
// Pre-delete: evict cache before the DB write so concurrent reads during the update
// window go to DB instead of getting a stale cached status (double-delete pattern).
_ = m.DelCacheCtx(ctx, keys...)
return m.ExecCtx(ctx, func(conn *gorm.DB) error { return m.ExecCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 { if len(tx) > 0 {
conn = tx[0] conn = tx[0]
@@ -123,7 +127,7 @@ func (m *customOrderModel) UpdateOrderStatus(ctx context.Context, orderNo string
return nil return nil
} }
return nil return nil
}, m.getCacheKeys(orderInfo)...) }, keys...)
} }
// FindOneDetailsByOrderNo Find order details by order number // FindOneDetailsByOrderNo Find order details by order number
+3 -2
View File
@@ -24,8 +24,9 @@ type Order struct {
Status uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Order Status: 1: Pending, 2: Paid, 3:Close, 4: Failed, 5:Finished;"` Status uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Order Status: 1: Pending, 2: Paid, 3:Close, 4: Failed, 5:Finished;"`
SubscribeId int64 `gorm:"type:bigint;not null;default:0;comment:Subscribe Id"` SubscribeId int64 `gorm:"type:bigint;not null;default:0;comment:Subscribe Id"`
SubscribeToken string `gorm:"type:varchar(255);default:null;comment:Renewal Subscribe Token"` SubscribeToken string `gorm:"type:varchar(255);default:null;comment:Renewal Subscribe Token"`
AppAccountToken string `gorm:"type:varchar(36);default:null;comment:Apple IAP App Account Token (UUID)"` AppAccountToken string `gorm:"type:varchar(36);default:null;comment:Apple IAP App Account Token (UUID)"`
IsNew bool `gorm:"type:tinyint(1);not null;default:0;comment:Is New Order"` ActivationContext string `gorm:"type:text;default:null;comment:Activation context JSON (guest/redemption info for DB fallback)"`
IsNew bool `gorm:"type:tinyint(1);not null;default:0;comment:Is New Order"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"` CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"` UpdatedAt time.Time `gorm:"comment:Update Time"`
} }
+17
View File
@@ -26,6 +26,7 @@ type (
Insert(ctx context.Context, data *User, tx ...*gorm.DB) error Insert(ctx context.Context, data *User, tx ...*gorm.DB) error
FindOne(ctx context.Context, id int64) (*User, error) FindOne(ctx context.Context, id int64) (*User, error)
Update(ctx context.Context, data *User, tx ...*gorm.DB) error Update(ctx context.Context, data *User, tx ...*gorm.DB) error
UpdateCommission(ctx context.Context, userId int64, delta int64, tx ...*gorm.DB) error
Delete(ctx context.Context, id int64, tx ...*gorm.DB) error Delete(ctx context.Context, id int64, tx ...*gorm.DB) error
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
} }
@@ -111,6 +112,22 @@ func (m *defaultUserModel) Update(ctx context.Context, data *User, tx ...*gorm.D
return err return err
} }
func (m *defaultUserModel) UpdateCommission(ctx context.Context, userId int64, delta int64, tx ...*gorm.DB) error {
old, err := m.FindOne(ctx, userId)
if err != nil {
return err
}
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Model(&User{}).
Where("id = ?", userId).
UpdateColumn("commission", gorm.Expr("commission + ?", delta)).Error
}, m.getCacheKeys(old)...)
}
func (m *defaultUserModel) Delete(ctx context.Context, id int64, tx ...*gorm.DB) error { func (m *defaultUserModel) Delete(ctx context.Context, id int64, tx ...*gorm.DB) error {
data, err := m.FindOne(ctx, id) data, err := m.FindOne(ctx, id)
if err != nil { if err != nil {
+18
View File
@@ -8,6 +8,22 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
const userDeviceUserAgentMaxLength = 255
func normalizeDeviceForStorage(data *Device) {
if data == nil {
return
}
data.UserAgent = truncateForColumn(data.UserAgent, userDeviceUserAgentMaxLength)
}
func truncateForColumn(s string, max int) string {
if len(s) <= max {
return s
}
return s[:max]
}
func (m *customUserModel) FindOneDevice(ctx context.Context, id int64) (*Device, error) { func (m *customUserModel) FindOneDevice(ctx context.Context, id int64) (*Device, error) {
deviceIdKey := fmt.Sprintf("%s%v", cacheUserDeviceIdPrefix, id) deviceIdKey := fmt.Sprintf("%s%v", cacheUserDeviceIdPrefix, id)
var resp Device var resp Device
@@ -69,6 +85,7 @@ func (m *customUserModel) QueryDeviceListByUserIds(ctx context.Context, userIds
} }
func (m *customUserModel) UpdateDevice(ctx context.Context, data *Device, tx ...*gorm.DB) error { func (m *customUserModel) UpdateDevice(ctx context.Context, data *Device, tx ...*gorm.DB) error {
normalizeDeviceForStorage(data)
old, err := m.FindOneDevice(ctx, data.Id) old, err := m.FindOneDevice(ctx, data.Id)
if err != nil { if err != nil {
return err return err
@@ -100,6 +117,7 @@ func (m *customUserModel) DeleteDevice(ctx context.Context, id int64, tx ...*gor
} }
func (m *customUserModel) InsertDevice(ctx context.Context, data *Device, tx ...*gorm.DB) error { func (m *customUserModel) InsertDevice(ctx context.Context, data *Device, tx ...*gorm.DB) error {
normalizeDeviceForStorage(data)
defer func() { defer func() {
if clearErr := m.ClearDeviceCache(ctx, data); clearErr != nil { if clearErr := m.ClearDeviceCache(ctx, data); clearErr != nil {
// log cache clear error // log cache clear error
+4 -4
View File
@@ -378,13 +378,13 @@ func (m *customUserModel) QueryDailyUserStatisticsList(ctx context.Context, date
// 子查询:统计每天的新用户订单数量 // 子查询:统计每天的新用户订单数量
newOrderSub := conn.Model(&order.Order{}). newOrderSub := conn.Model(&order.Order{}).
Select("DATE_FORMAT(created_at, '%Y-%m-%d') AS date, COUNT(DISTINCT user_id) AS new_order_users"). Select("DATE_FORMAT(created_at, '%Y-%m-%d') AS date, COUNT(DISTINCT user_id) AS new_order_users").
Where("is_new = 1 AND created_at BETWEEN ? AND ? AND status IN ?", firstDay, date, []int64{2, 5}). Where("type = 1 AND created_at BETWEEN ? AND ? AND status IN ? AND method != ?", firstDay, date, []int64{2, 5}, "balance").
Group("DATE_FORMAT(created_at, '%Y-%m-%d')") Group("DATE_FORMAT(created_at, '%Y-%m-%d')")
// 子查询:统计每天的续费订单数量 // 子查询:统计每天的续费订单数量
renewalOrderSub := conn.Model(&order.Order{}). renewalOrderSub := conn.Model(&order.Order{}).
Select("DATE_FORMAT(created_at, '%Y-%m-%d') AS date, COUNT(DISTINCT user_id) AS renewal_order_users"). Select("DATE_FORMAT(created_at, '%Y-%m-%d') AS date, COUNT(DISTINCT user_id) AS renewal_order_users").
Where("is_new = 0 AND created_at BETWEEN ? AND ? AND status IN ?", firstDay, date, []int64{2, 5}). Where("type = 2 AND created_at BETWEEN ? AND ? AND status IN ? AND method != ?", firstDay, date, []int64{2, 5}, "balance").
Group("DATE_FORMAT(created_at, '%Y-%m-%d')") Group("DATE_FORMAT(created_at, '%Y-%m-%d')")
return conn.Model(&User{}). return conn.Model(&User{}).
@@ -416,13 +416,13 @@ func (m *customUserModel) QueryMonthlyUserStatisticsList(ctx context.Context, da
// 子查询:每月新订单用户数量 // 子查询:每月新订单用户数量
newOrderSub := conn.Model(&order.Order{}). newOrderSub := conn.Model(&order.Order{}).
Select("DATE_FORMAT(created_at, '%Y-%m') AS date, COUNT(DISTINCT user_id) AS new_order_users"). Select("DATE_FORMAT(created_at, '%Y-%m') AS date, COUNT(DISTINCT user_id) AS new_order_users").
Where("is_new = 1 AND created_at >= ? AND status IN ?", sixMonthsAgo, []int64{2, 5}). Where("type = 1 AND created_at >= ? AND status IN ? AND method != ?", sixMonthsAgo, []int64{2, 5}, "balance").
Group("DATE_FORMAT(created_at, '%Y-%m')") Group("DATE_FORMAT(created_at, '%Y-%m')")
// 子查询:每月续费订单用户数量 // 子查询:每月续费订单用户数量
renewalOrderSub := conn.Model(&order.Order{}). renewalOrderSub := conn.Model(&order.Order{}).
Select("DATE_FORMAT(created_at, '%Y-%m') AS date, COUNT(DISTINCT user_id) AS renewal_order_users"). Select("DATE_FORMAT(created_at, '%Y-%m') AS date, COUNT(DISTINCT user_id) AS renewal_order_users").
Where("is_new = 0 AND created_at >= ? AND status IN ?", sixMonthsAgo, []int64{2, 5}). Where("type = 2 AND created_at >= ? AND status IN ? AND method != ?", sixMonthsAgo, []int64{2, 5}, "balance").
Group("DATE_FORMAT(created_at, '%Y-%m')") Group("DATE_FORMAT(created_at, '%Y-%m')")
return conn.Model(&User{}). return conn.Model(&User{}).
+5 -2
View File
@@ -167,12 +167,15 @@ type Withdrawal struct {
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"` UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
Amount int64 `gorm:"not null;comment:Withdrawal Amount"` Amount int64 `gorm:"not null;comment:Withdrawal Amount"`
Content string `gorm:"type:text;comment:Withdrawal Content"` Content string `gorm:"type:text;comment:Withdrawal Content"`
Status uint8 `gorm:"type:tinyint(1);default:0;comment:Withdrawal Status: 0: Pending 1: Approved 2: Rejected"` Status uint8 `gorm:"type:tinyint(1);default:0;comment:Withdrawal Status: 0: Pending 1: Approved 2: Rejected 3: Cancelled"`
Reason string `gorm:"type:varchar(500);default:'';comment:Rejection Reason"` Reason string `gorm:"type:varchar(500);default:'';comment:Rejection Reason"`
Method uint8 `gorm:"type:tinyint(1);default:0;comment:收款方式 0:其他 1:支付宝 2:微信 3:银行卡"`
Account string `gorm:"type:varchar(255);default:'';comment:收款账号"`
QrCodeUrl string `gorm:"type:varchar(500);default:'';comment:收款码图片URL"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"` CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"` UpdatedAt time.Time `gorm:"comment:Update Time"`
} }
func (*Withdrawal) TableName() string { func (*Withdrawal) TableName() string {
return "user_withdrawal" return "withdrawals"
} }
+15
View File
@@ -0,0 +1,15 @@
package user
const (
WithdrawalStatusPending uint8 = 0 // 待审核
WithdrawalStatusApproved uint8 = 1 // 已通过
WithdrawalStatusRejected uint8 = 2 // 已拒绝
WithdrawalStatusCancelled uint8 = 3 // 已取消(用户自行撤回)
)
const (
WithdrawalMethodOther uint8 = 0 // 其他
WithdrawalMethodAlipay uint8 = 1 // 支付宝
WithdrawalMethodWechat uint8 = 2 // 微信
WithdrawalMethodBank uint8 = 3 // 银行卡
)
+130 -16
View File
@@ -3,10 +3,17 @@
package types package types
import "encoding/json"
type ActivateOrderRequest struct { type ActivateOrderRequest struct {
OrderNo string `json:"order_no" validate:"required"` OrderNo string `json:"order_no" validate:"required"`
} }
type RefundOrderRequest struct {
Id int64 `json:"id" validate:"required"`
Reason string `json:"reason,omitempty" validate:"omitempty,max=500"`
}
type Ads struct { type Ads struct {
Id int `json:"id"` Id int `json:"id"`
Title string `json:"title"` Title string `json:"title"`
@@ -289,8 +296,11 @@ type CommissionLog struct {
} }
type CommissionWithdrawRequest struct { type CommissionWithdrawRequest struct {
Amount int64 `json:"amount"` Amount int64 `json:"amount"`
Content string `json:"content"` 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"`
} }
type ConnectionRecords struct { type ConnectionRecords struct {
@@ -762,6 +772,20 @@ type FamilySummary struct {
UpdatedAt int64 `json:"updated_at"` UpdatedAt int64 `json:"updated_at"`
} }
type FileUploadRequest struct {
BizType string `form:"biz_type" validate:"required"`
}
type FileUploadResponse struct {
FileId string `json:"file_id"`
FileName string `json:"file_name"`
ObjectKey string `json:"object_key"`
Size int64 `json:"size"`
ContentType string `json:"content_type"`
Etag string `json:"etag"`
Status string `json:"status"`
}
type FileUploadCompleteRequest struct { type FileUploadCompleteRequest struct {
FileId string `json:"file_id" validate:"required"` FileId string `json:"file_id" validate:"required"`
} }
@@ -812,6 +836,17 @@ type FilterCommissionLogResponse struct {
List []CommissionLog `json:"list"` List []CommissionLog `json:"list"`
} }
type FilterOrderRefundLogRequest struct {
FilterLogParams
OrderId int64 `form:"order_id,optional"`
UserId int64 `form:"user_id,optional"`
}
type FilterOrderRefundLogResponse struct {
Total int64 `json:"total"`
List []OrderRefundLog `json:"list"`
}
type FilterEmailLogResponse struct { type FilterEmailLogResponse struct {
Total int64 `json:"total"` Total int64 `json:"total"`
List []MessageLog `json:"list"` List []MessageLog `json:"list"`
@@ -1838,6 +1873,7 @@ type Order struct {
FeeAmount int64 `json:"fee_amount"` FeeAmount int64 `json:"fee_amount"`
TradeNo string `json:"trade_no"` TradeNo string `json:"trade_no"`
Status uint8 `json:"status"` Status uint8 `json:"status"`
StatusName string `json:"status_name,omitempty"`
SubscribeId int64 `json:"subscribe_id"` SubscribeId int64 `json:"subscribe_id"`
CreatedAt int64 `json:"created_at"` CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"` UpdatedAt int64 `json:"updated_at"`
@@ -1861,12 +1897,34 @@ type OrderDetail struct {
FeeAmount int64 `json:"fee_amount"` FeeAmount int64 `json:"fee_amount"`
TradeNo string `json:"trade_no"` TradeNo string `json:"trade_no"`
Status uint8 `json:"status"` Status uint8 `json:"status"`
StatusName string `json:"status_name,omitempty"`
SubscribeId int64 `json:"subscribe_id"` SubscribeId int64 `json:"subscribe_id"`
Subscribe Subscribe `json:"subscribe"` Subscribe Subscribe `json:"subscribe"`
CreatedAt int64 `json:"created_at"` CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"` UpdatedAt int64 `json:"updated_at"`
} }
type OrderRefundLog struct {
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"`
}
type OrdersStatistics struct { type OrdersStatistics struct {
Date string `json:"date,omitempty"` Date string `json:"date,omitempty"`
AmountTotal int64 `json:"amount_total"` AmountTotal int64 `json:"amount_total"`
@@ -2260,6 +2318,10 @@ type QueryUserSubscribeNodeListResponse struct {
List []UserSubscribeInfo `json:"list"` List []UserSubscribeInfo `json:"list"`
} }
type CancelWithdrawalRequest struct {
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
}
type QueryWithdrawalLogListRequest struct { type QueryWithdrawalLogListRequest struct {
Page int `form:"page"` Page int `form:"page"`
Size int `form:"size"` Size int `form:"size"`
@@ -2270,6 +2332,28 @@ type QueryWithdrawalLogListResponse struct {
Total int64 `json:"total"` Total int64 `json:"total"`
} }
type GetWithdrawalListRequest struct {
Page int `form:"page"`
Size int `form:"size"`
UserId *int64 `form:"user_id,omitempty"`
Status *uint8 `form:"status,omitempty"`
Method *uint8 `form:"method,omitempty"`
}
type GetWithdrawalListResponse struct {
List []WithdrawalLog `json:"list"`
Total int64 `json:"total"`
}
type ApproveWithdrawalRequest struct {
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
}
type RejectWithdrawalRequest struct {
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
Reason string `json:"reason" validate:"required,max=500"`
}
type QuotaTask struct { type QuotaTask struct {
Id int64 `json:"id"` Id int64 `json:"id"`
Subscribers []int64 `json:"subscribers"` Subscribers []int64 `json:"subscribers"`
@@ -3188,20 +3272,20 @@ type UpdateUserAuthMethodRequest struct {
} }
type UpdateUserBasiceInfoRequest struct { type UpdateUserBasiceInfoRequest struct {
UserId int64 `json:"user_id" validate:"required"` UserId int64 `json:"user_id" validate:"required"`
Password string `json:"password"` Password string `json:"password"`
Avatar string `json:"avatar"` Avatar string `json:"avatar"`
Balance int64 `json:"balance"` Balance *int64 `json:"balance"`
Commission int64 `json:"commission"` Commission *int64 `json:"commission"`
ReferralPercentage uint8 `json:"referral_percentage"` ReferralPercentage uint8 `json:"referral_percentage"`
OnlyFirstPurchase *bool `json:"only_first_purchase"` OnlyFirstPurchase *bool `json:"only_first_purchase"`
GiftAmount int64 `json:"gift_amount"` GiftAmount *int64 `json:"gift_amount"`
Telegram int64 `json:"telegram"` Telegram int64 `json:"telegram"`
ReferCode string `json:"refer_code"` ReferCode string `json:"refer_code"`
RefererId int64 `json:"referer_id"` RefererId *int64 `json:"referer_id"`
Enable *bool `json:"enable"` Enable *bool `json:"enable"`
IsAdmin *bool `json:"is_admin"` IsAdmin *bool `json:"is_admin"`
Remark string `json:"remark"` Remark *string `json:"remark"`
} }
type UpdateUserNotifyRequest struct { type UpdateUserNotifyRequest struct {
@@ -3264,6 +3348,7 @@ type User struct {
EnableLoginNotify bool `json:"enable_login_notify"` EnableLoginNotify bool `json:"enable_login_notify"`
EnableSubscribeNotify bool `json:"enable_subscribe_notify"` EnableSubscribeNotify bool `json:"enable_subscribe_notify"`
EnableTradeNotify bool `json:"enable_trade_notify"` EnableTradeNotify bool `json:"enable_trade_notify"`
UseStatus bool `json:"use_status"`
AuthMethods []UserAuthMethod `json:"auth_methods"` AuthMethods []UserAuthMethod `json:"auth_methods"`
UserDevices []UserDevice `json:"user_devices"` UserDevices []UserDevice `json:"user_devices"`
Rules []string `json:"rules"` Rules []string `json:"rules"`
@@ -3571,6 +3656,9 @@ type WithdrawalLog struct {
Content string `json:"content"` Content string `json:"content"`
Status uint8 `json:"status"` Status uint8 `json:"status"`
Reason string `json:"reason,omitempty"` Reason string `json:"reason,omitempty"`
Method uint8 `json:"method"`
Account string `json:"account"`
QrCodeUrl string `json:"qr_code_url"`
CreatedAt int64 `json:"created_at"` CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"` UpdatedAt int64 `json:"updated_at"`
} }
@@ -3605,3 +3693,29 @@ type GetAdminUserInviteListResponse struct {
Total int64 `json:"total"` Total int64 `json:"total"`
List []AdminInvitedUser `json:"list"` List []AdminInvitedUser `json:"list"`
} }
type GetLogMessageRawRequest struct {
Id int64 `form:"id" validate:"required"`
}
type GetLogMessageRawResponse struct {
Id int64 `json:"id"`
Platform string `json:"platform"`
AppVersion string `json:"app_version"`
OsName string `json:"os_name"`
OsVersion string `json:"os_version"`
DeviceId string `json:"device_id"`
UserId *int64 `json:"user_id"`
SessionId string `json:"session_id"`
Level uint8 `json:"level"`
ErrorCode string `json:"error_code"`
Message string `json:"message"`
Stack string `json:"stack"`
Context json.RawMessage `json:"context"`
ClientIP string `json:"client_ip"`
UserAgent string `json:"user_agent"`
Locale string `json:"locale"`
Digest string `json:"digest"`
OccurredAt int64 `json:"occurred_at"`
CreatedAt int64 `json:"created_at"`
}
@@ -0,0 +1,35 @@
package types
import (
"encoding/json"
"testing"
)
func TestUpdateUserBasicInfoRequestRemarkPresence(t *testing.T) {
var omitted UpdateUserBasiceInfoRequest
if err := json.Unmarshal([]byte(`{"user_id":1}`), &omitted); err != nil {
t.Fatalf("unmarshal omitted remark: %v", err)
}
if omitted.Remark != nil {
t.Fatalf("omitted remark = %q, want nil", *omitted.Remark)
}
var cleared UpdateUserBasiceInfoRequest
if err := json.Unmarshal([]byte(`{"user_id":1,"remark":""}`), &cleared); err != nil {
t.Fatalf("unmarshal empty remark: %v", err)
}
if cleared.Remark == nil {
t.Fatal("empty remark was decoded as nil, want explicit empty string")
}
if *cleared.Remark != "" {
t.Fatalf("empty remark = %q, want empty string", *cleared.Remark)
}
var updated UpdateUserBasiceInfoRequest
if err := json.Unmarshal([]byte(`{"user_id":1,"remark":"new note"}`), &updated); err != nil {
t.Fatalf("unmarshal non-empty remark: %v", err)
}
if updated.Remark == nil || *updated.Remark != "new note" {
t.Fatalf("non-empty remark = %#v, want %q", updated.Remark, "new note")
}
}
+4 -4
View File
@@ -22,7 +22,7 @@
- Region: `ap-east-1` - Region: `ap-east-1`
- AWS app EC2: - AWS app EC2:
- Name: `hifast-hk-app-01` - Name: `hifast-hk-app-01`
- Public IP: `43.198.248.161` - Public IP: `18.163.33.75`
- Private IP: `10.0.1.201` - Private IP: `10.0.1.201`
- AWS MySQL: - AWS MySQL:
- Type: `RDS MySQL` - Type: `RDS MySQL`
@@ -183,7 +183,7 @@ redis-cli INFO replication
重点看: 重点看:
- `role:slave` - `role:slave`
- `master_host:43.198.248.161` - `master_host:18.163.33.75`
- `master_port:6379` - `master_port:6379`
- `master_link_status:up` - `master_link_status:up`
@@ -416,7 +416,7 @@ SHOW REPLICA STATUS\G
```bash ```bash
redis-cli CONFIG SET masterauth '0BVz9XOHf7KUfEuoFJRK-dURdKUGFiZ8QeaHpysHnKeKhLskZb55HPK121lFsKtr' redis-cli CONFIG SET masterauth '0BVz9XOHf7KUfEuoFJRK-dURdKUGFiZ8QeaHpysHnKeKhLskZb55HPK121lFsKtr'
redis-cli REPLICAOF 43.198.248.161 6379 redis-cli REPLICAOF 18.163.33.75 6379
redis-cli CONFIG SET replica-read-only yes redis-cli CONFIG SET replica-read-only yes
redis-cli INFO replication redis-cli INFO replication
``` ```
@@ -426,7 +426,7 @@ redis-cli INFO replication
检查 `/etc/redis/redis.conf` 至少包含: 检查 `/etc/redis/redis.conf` 至少包含:
```conf ```conf
replicaof 43.198.248.161 6379 replicaof 18.163.33.75 6379
masterauth 0BVz9XOHf7KUfEuoFJRK-dURdKUGFiZ8QeaHpysHnKeKhLskZb55HPK121lFsKtr masterauth 0BVz9XOHf7KUfEuoFJRK-dURdKUGFiZ8QeaHpysHnKeKhLskZb55HPK121lFsKtr
replica-read-only yes replica-read-only yes
``` ```
+33
View File
@@ -0,0 +1,33 @@
# Docker Image Version Pins
This file records the infrastructure image versions pinned in `docker-compose.cloud.yml`.
The versions below match the images observed on the test deployment on 2026-05-26.
| Service | Image | Running version source |
| --- | --- | --- |
| grafana | `grafana/grafana:13.0.1` | `grafana version 13.0.1` |
| prometheus | `prom/prometheus:v3.11.3` | `prometheus, version 3.11.3` |
| nginx-exporter | `nginx/nginx-prometheus-exporter:1.5.0` | image label `org.opencontainers.image.version=1.5.0` |
| node-exporter | `prom/node-exporter:v1.11.1` | `node_exporter, version 1.11.1` |
| cadvisor | `gcr.io/cadvisor/cadvisor:v0.55.1` | `cAdvisor version v0.55.1` |
The test deployment in `/root/bindbox/docker-compose.cloud.yml` also contains
live-only exporter services that are not present in this repository's
`docker-compose.cloud.yml`. They were pinned during staging validation:
| Test-only service | Image | Running version source |
| --- | --- | --- |
| mysql-exporter | `prom/mysqld-exporter:v0.19.0` | `mysqld_exporter, version 0.19.0` |
| redis-exporter | `oliver006/redis_exporter:v1.82.0` | image label `org.opencontainers.image.version=v1.82.0` |
`ppanel-server` intentionally remains variable and requires `PPANEL_SERVER_TAG`
from CI/CD so deployments use an immutable application image tag.
## Rollback
Restore the previous compose file from git and redeploy:
```sh
git checkout HEAD~1 -- docker-compose.cloud.yml .env.example ops/docker-image-version-pins.md
docker compose -f docker-compose.cloud.yml up -d
```
+9 -9
View File
@@ -66,7 +66,7 @@
- Instance ID: `i-079cd9d3ef3748714` - Instance ID: `i-079cd9d3ef3748714`
- 角色:当前实际生产入口 / Nginx / 业务服务 / AWS 侧 Redis 主库宿主机 - 角色:当前实际生产入口 / Nginx / 业务服务 / AWS 侧 Redis 主库宿主机
- 私网 IP: `10.0.1.201` - 私网 IP: `10.0.1.201`
- 公网 IP: `43.198.248.161` - 公网 IP: `18.163.33.75`
- 业务服务运行方式:`Docker Compose` - 业务服务运行方式:`Docker Compose`
- 业务容器:`ppanel-server` - 业务容器:`ppanel-server`
- 部署目录:`/opt/ppanel` - 部署目录:`/opt/ppanel`
@@ -103,7 +103,7 @@
- 容器名:`hifast-redis` - 容器名:`hifast-redis`
- 版本:`redis:8.2.1` - 版本:`redis:8.2.1`
- 访问端口:`6379` - 访问端口:`6379`
- 主库出口地址:`43.198.248.161:6379` - 主库出口地址:`18.163.33.75:6379`
- 应用当前实际连接:`127.0.0.1:6379` - 应用当前实际连接:`127.0.0.1:6379`
- 认证方式:已启用密码认证 - 认证方式:已启用密码认证
@@ -130,10 +130,10 @@
```mermaid ```mermaid
flowchart TB flowchart TB
USER["用户 / 客户端"] --> DNS["域名 / DNS / 入口层"] USER["用户 / 客户端"] --> DNS["域名 / DNS / 入口层"]
DNS --> APP["AWS EC2\nhifast-hk-app-01\n43.198.248.161\n10.0.1.201"] DNS --> APP["AWS EC2\nhifast-hk-app-01\n18.163.33.75\n10.0.1.201"]
APP --> RDS["AWS RDS MySQL\nhifast-mysql-prod-v2\n主库"] APP --> RDS["AWS RDS MySQL\nhifast-mysql-prod-v2\n主库"]
APP --> REDISM["AWS Redis 主库\nDocker redis:8.2.1\n43.198.248.161:6379"] APP --> REDISM["AWS Redis 主库\nDocker redis:8.2.1\n18.163.33.75:6379"]
RDS -. MySQL 备用 / 同步 .-> MYSQLS["104.238.220.230\nMySQL 备用库"] RDS -. MySQL 备用 / 同步 .-> MYSQLS["104.238.220.230\nMySQL 备用库"]
REDISM -. Redis 主从复制 .-> REDISS["104.238.220.230\n原生 Redis 8.6.3\n从库"] REDISM -. Redis 主从复制 .-> REDISS["104.238.220.230\n原生 Redis 8.6.3\n从库"]
@@ -238,7 +238,7 @@ App / Nginx
```mermaid ```mermaid
flowchart LR flowchart LR
SG["hifast-hk-app-core-sg"] --> REDIS["AWS Redis 主库\n43.198.248.161:6379"] SG["hifast-hk-app-core-sg"] --> REDIS["AWS Redis 主库\n18.163.33.75:6379"]
STANDBY["104.238.220.230/32"] --> SG STANDBY["104.238.220.230/32"] --> SG
``` ```
@@ -311,7 +311,7 @@ RDS 当前状态已经比之前干净很多:
`104.238.220.230` 连接 AWS Redis,不是通过 PEM 证书,也不是通过 SSH 登录 AWS 机器,而是直接作为 Redis 从库去访问 AWS Redis 主库: `104.238.220.230` 连接 AWS Redis,不是通过 PEM 证书,也不是通过 SSH 登录 AWS 机器,而是直接作为 Redis 从库去访问 AWS Redis 主库:
- 目标地址:`43.198.248.161:6379` - 目标地址:`18.163.33.75:6379`
- 连接方式:`TCP` - 连接方式:`TCP`
- 认证方式:`Redis 密码` - 认证方式:`Redis 密码`
- 网络前提:AWS EC2 安全组已放行 `104.238.220.230/32 -> 6379` - 网络前提:AWS EC2 安全组已放行 `104.238.220.230/32 -> 6379`
@@ -325,7 +325,7 @@ RDS 当前状态已经比之前干净很多:
示意命令: 示意命令:
```bash ```bash
redis-cli -h 43.198.248.161 -p 6379 -a '<REDIS_PASSWORD>' redis-cli -h 18.163.33.75 -p 6379 -a '<REDIS_PASSWORD>'
``` ```
### 4.6.2 104 连接 AWS MySQL RDS 的方式 ### 4.6.2 104 连接 AWS MySQL RDS 的方式
@@ -380,7 +380,7 @@ mysql -h hifast-mysql-prod-v2.cd6aey40m6ag.ap-east-1.rds.amazonaws.com -u admin
- 部署方式:Docker - 部署方式:Docker
- 版本:`8.2.1` - 版本:`8.2.1`
- 主库地址:`43.198.248.161:6379` - 主库地址:`18.163.33.75:6379`
- 运行容器:`hifast-redis` - 运行容器:`hifast-redis`
### 5.2 104 Redis 从库 ### 5.2 104 Redis 从库
@@ -417,7 +417,7 @@ mysql -h hifast-mysql-prod-v2.cd6aey40m6ag.ap-east-1.rds.amazonaws.com -u admin
```mermaid ```mermaid
flowchart LR flowchart LR
REDISMASTER["AWS Redis 主库\n43.198.248.161:6379\nDocker redis:8.2.1"] REDISMASTER["AWS Redis 主库\n18.163.33.75:6379\nDocker redis:8.2.1"]
REDISSLAVE["104.238.220.230\n原生 Redis 8.6.3\nrole: slave"] REDISSLAVE["104.238.220.230\n原生 Redis 8.6.3\nrole: slave"]
REDISMASTER --> REDISSLAVE REDISMASTER --> REDISSLAVE
``` ```
+21 -2
View File
@@ -3,6 +3,7 @@ package storage
import ( import (
"context" "context"
"fmt" "fmt"
"io"
"net/url" "net/url"
"strings" "strings"
"time" "time"
@@ -22,11 +23,15 @@ type PresignUploadResult struct {
} }
type ObjectMeta struct { type ObjectMeta struct {
ETag string ETag string
ContentType string ContentType string
ContentLength int64 ContentLength int64
} }
type PutObjectResult struct {
ETag string
}
type S3Store struct { type S3Store struct {
cfg config.S3Config cfg config.S3Config
client *s3.Client client *s3.Client
@@ -96,6 +101,20 @@ func (s *S3Store) HeadObject(ctx context.Context, objectKey string) (*ObjectMeta
}, nil }, nil
} }
func (s *S3Store) PutObject(ctx context.Context, objectKey string, body io.Reader, size int64, contentType string) (*PutObjectResult, error) {
resp, err := s.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(s.cfg.Bucket),
Key: aws.String(objectKey),
Body: body,
ContentLength: aws.Int64(size),
ContentType: aws.String(contentType),
})
if err != nil {
return nil, err
}
return &PutObjectResult{ETag: strings.Trim(aws.ToString(resp.ETag), "\"")}, nil
}
func (s *S3Store) BuildObjectURL(objectKey string) string { func (s *S3Store) BuildObjectURL(objectKey string) string {
if s.cfg.PublicBaseURL != "" { if s.cfg.PublicBaseURL != "" {
return strings.TrimRight(s.cfg.PublicBaseURL, "/") + "/" + strings.TrimLeft(objectKey, "/") return strings.TrimRight(s.cfg.PublicBaseURL, "/") + "/" + strings.TrimLeft(objectKey, "/")
+9 -5
View File
@@ -37,6 +37,7 @@ const (
FamilyNotExist uint32 = 20017 FamilyNotExist uint32 = 20017
FamilyStatusInvalid uint32 = 20018 FamilyStatusInvalid uint32 = 20018
FamilyOwnerOperationForbidden uint32 = 20019 FamilyOwnerOperationForbidden uint32 = 20019
WithdrawalStatusInvalid uint32 = 20020
) )
// Node error // Node error
@@ -140,9 +141,12 @@ const (
) )
const ( const (
OrderNotExist uint32 = 61001 OrderNotExist uint32 = 61001
PaymentMethodNotFound uint32 = 61002 PaymentMethodNotFound uint32 = 61002
OrderStatusError uint32 = 61003 OrderStatusError uint32 = 61003
InsufficientOfPeriod uint32 = 61004 InsufficientOfPeriod uint32 = 61004
ExistAvailableTraffic uint32 = 61005 ExistAvailableTraffic uint32 = 61005
OrderAlreadyRefunded uint32 = 61006
OrderRefundNoSubscription uint32 = 61007
OrderRefundCommissionMismatch uint32 = 61008
) )
+8 -4
View File
@@ -46,6 +46,7 @@ func init() {
FamilyNotExist: "家庭组不存在", FamilyNotExist: "家庭组不存在",
FamilyStatusInvalid: "家庭组状态无效", FamilyStatusInvalid: "家庭组状态无效",
FamilyOwnerOperationForbidden: "家庭组所有者不允许此操作", FamilyOwnerOperationForbidden: "家庭组所有者不允许此操作",
WithdrawalStatusInvalid: "提现状态无效",
// Node error // Node error
NodeExist: "Node already exists", NodeExist: "Node already exists",
@@ -98,10 +99,13 @@ func init() {
UseridNotMatch: "Userid not match", UseridNotMatch: "Userid not match",
// Order error // Order error
OrderNotExist: "Order does not exist", OrderNotExist: "Order does not exist",
PaymentMethodNotFound: "Payment method not found", PaymentMethodNotFound: "Payment method not found",
OrderStatusError: "Order status error", OrderStatusError: "Order status error",
InsufficientOfPeriod: "Insufficient number of period", InsufficientOfPeriod: "Insufficient number of period",
OrderAlreadyRefunded: "Order already refunded",
OrderRefundNoSubscription: "Refund target subscription not found",
OrderRefundCommissionMismatch: "Refund commission source not found",
// Permission error // Permission error
PermissionDenied: "Permission denied", PermissionDenied: "Permission denied",
+3
View File
@@ -48,4 +48,7 @@ func RegisterHandlers(mux *asynq.ServeMux, serverCtx *svc.ServiceContext) {
// Apple IAP 对账(第二层:5min 扫描 + 第三层:日终全量) // Apple IAP 对账(第二层:5min 扫描 + 第三层:日终全量)
mux.Handle(types.SchedulerIAPReconcile, iapLogic.NewReconcileLogic(serverCtx)) mux.Handle(types.SchedulerIAPReconcile, iapLogic.NewReconcileLogic(serverCtx))
mux.Handle(types.SchedulerIAPDailyReconcile, iapLogic.NewDailyReconcileLogic(serverCtx)) mux.Handle(types.SchedulerIAPDailyReconcile, iapLogic.NewDailyReconcileLogic(serverCtx))
// Stuck order recovery
mux.Handle(types.SchedulerStuckOrderRecovery, orderLogic.NewStuckOrderRecoveryLogic(serverCtx))
} }
+171 -43
View File
@@ -7,6 +7,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"strings"
"time" "time"
"github.com/perfect-panel/server/internal/logic/admin/group" "github.com/perfect-panel/server/internal/logic/admin/group"
@@ -46,7 +47,7 @@ const (
OrderStatusPaid = 2 // Order paid and ready for processing OrderStatusPaid = 2 // Order paid and ready for processing
OrderStatusClose = 3 // Order closed/cancelled OrderStatusClose = 3 // Order closed/cancelled
OrderStatusFailed = 4 // Order processing failed OrderStatusFailed = 4 // Order processing failed
OrderStatusClaimed = 4 // Internal transient claim while a worker processes the order OrderStatusClaimed = 6 // Internal transient claim while a worker processes the order
OrderStatusFinished = 5 // Order successfully completed OrderStatusFinished = 5 // Order successfully completed
) )
@@ -92,8 +93,12 @@ func (l *ActivateOrderLogic) ProcessTask(ctx context.Context, task *asynq.Task)
orderInfo, err := l.claimAndGetOrder(ctx, payload.OrderNo) orderInfo, err := l.claimAndGetOrder(ctx, payload.OrderNo)
if err != nil { if err != nil {
// 如果订单不存在或状态不对,不重试
if errors.Is(err, ErrInvalidOrderStatus) { if errors.Is(err, ErrInvalidOrderStatus) {
if strings.Contains(err.Error(), "stuck in claimed") {
logger.WithContext(ctx).Error("[ActivateOrderLogic] 订单卡在 claimed,将重试",
logger.Field("order_no", payload.OrderNo))
return err // 返回错误触发 asynq 重试
}
logger.WithContext(ctx).Info("[ActivateOrderLogic] 订单状态不是已支付,跳过", logger.WithContext(ctx).Info("[ActivateOrderLogic] 订单状态不是已支付,跳过",
logger.Field("order_no", payload.OrderNo)) logger.Field("order_no", payload.OrderNo))
return nil return nil
@@ -116,7 +121,12 @@ func (l *ActivateOrderLogic) ProcessTask(ctx context.Context, task *asynq.Task)
) )
if err = l.processOrderByType(ctx, orderInfo, payload.IAPExpireAt); err != nil { if err = l.processOrderByType(ctx, orderInfo, payload.IAPExpireAt); err != nil {
l.releaseClaim(ctx, orderInfo.OrderNo) if releaseErr := l.releaseClaim(ctx, orderInfo.OrderNo); releaseErr != nil {
logger.WithContext(ctx).Error("[ActivateOrderLogic] releaseClaim also failed, stuck recovery will handle",
logger.Field("order_no", orderInfo.OrderNo),
logger.Field("release_error", releaseErr.Error()),
)
}
logger.WithContext(ctx).Error("[ActivateOrderLogic] 处理订单失败,将重试", logger.WithContext(ctx).Error("[ActivateOrderLogic] 处理订单失败,将重试",
logger.Field("order_no", orderInfo.OrderNo), logger.Field("order_no", orderInfo.OrderNo),
logger.Field("order_type", orderInfo.Type), logger.Field("order_type", orderInfo.Type),
@@ -125,7 +135,12 @@ func (l *ActivateOrderLogic) ProcessTask(ctx context.Context, task *asynq.Task)
} }
if err = l.reconcilePostOrderSubscriptions(ctx, orderInfo); err != nil { if err = l.reconcilePostOrderSubscriptions(ctx, orderInfo); err != nil {
l.releaseClaim(ctx, orderInfo.OrderNo) if releaseErr := l.releaseClaim(ctx, orderInfo.OrderNo); releaseErr != nil {
logger.WithContext(ctx).Error("[ActivateOrderLogic] releaseClaim also failed, stuck recovery will handle",
logger.Field("order_no", orderInfo.OrderNo),
logger.Field("release_error", releaseErr.Error()),
)
}
logger.WithContext(ctx).Error("[ActivateOrderLogic] 订单订阅兜底合并失败,将重试", logger.WithContext(ctx).Error("[ActivateOrderLogic] 订单订阅兜底合并失败,将重试",
logger.Field("order_no", orderInfo.OrderNo), logger.Field("order_no", orderInfo.OrderNo),
logger.Field("order_type", orderInfo.Type), logger.Field("order_type", orderInfo.Type),
@@ -176,6 +191,15 @@ func (l *ActivateOrderLogic) claimAndGetOrder(ctx context.Context, orderNo strin
return nil, nil return nil, nil
} }
// Detect stuck claimed order — return retryable error so asynq re-tries
if orderInfo.Status == OrderStatusClaimed {
logger.WithContext(ctx).Error("Order stuck in claimed status",
logger.Field("order_no", orderInfo.OrderNo),
logger.Field("status", orderInfo.Status),
)
return nil, fmt.Errorf("order %s stuck in claimed status: %w", orderNo, ErrInvalidOrderStatus)
}
if orderInfo.Status != OrderStatusPaid { if orderInfo.Status != OrderStatusPaid {
logger.WithContext(ctx).Error("Order status error", logger.WithContext(ctx).Error("Order status error",
logger.Field("order_no", orderInfo.OrderNo), logger.Field("order_no", orderInfo.OrderNo),
@@ -201,7 +225,7 @@ func (l *ActivateOrderLogic) claimAndGetOrder(ctx context.Context, orderNo strin
return &orderInfo, nil return &orderInfo, nil
} }
func (l *ActivateOrderLogic) releaseClaim(ctx context.Context, orderNo string) { func (l *ActivateOrderLogic) releaseClaim(ctx context.Context, orderNo string) error {
if err := l.svc.DB.WithContext(ctx). if err := l.svc.DB.WithContext(ctx).
Model(&order.Order{}). Model(&order.Order{}).
Where("order_no = ? AND status = ?", orderNo, OrderStatusClaimed). Where("order_no = ? AND status = ?", orderNo, OrderStatusClaimed).
@@ -210,7 +234,9 @@ func (l *ActivateOrderLogic) releaseClaim(ctx context.Context, orderNo string) {
logger.Field("error", err.Error()), logger.Field("error", err.Error()),
logger.Field("order_no", orderNo), logger.Field("order_no", orderNo),
) )
return fmt.Errorf("release claim failed for order %s: %w", orderNo, err)
} }
return nil
} }
// processOrderByType routes order processing based on the order type // processOrderByType routes order processing based on the order type
@@ -563,14 +589,27 @@ func (l *ActivateOrderLogic) finalizeCouponAndOrder(ctx context.Context, orderIn
} }
} }
// Update order status using state-guarded UpdateOrderStatus to prevent double finalization // UpdateOrderStatus uses WHERE status < target, which blocks claimed(6)→finished(5).
if err := l.svc.OrderModel.UpdateOrderStatus(ctx, orderInfo.OrderNo, OrderStatusFinished); err != nil { // Use a direct update matching the exact claimed status, then update the full record
logger.WithContext(ctx).Error("Update order status failed", // via the model layer to properly invalidate the cache.
result := l.svc.DB.WithContext(ctx).
Model(&order.Order{}).
Where("order_no = ? AND status = ?", orderInfo.OrderNo, OrderStatusClaimed).
Update("status", OrderStatusFinished)
if result.Error != nil {
logger.WithContext(ctx).Error("Update order status from claimed to finished failed",
logger.Field("error", result.Error.Error()),
logger.Field("order_no", orderInfo.OrderNo),
)
}
// Invalidate order cache regardless of whether the DB update succeeded
orderInfo.Status = OrderStatusFinished
if err := l.svc.OrderModel.Update(ctx, orderInfo); err != nil {
logger.WithContext(ctx).Error("Update order cache after finalization failed",
logger.Field("error", err.Error()), logger.Field("error", err.Error()),
logger.Field("order_no", orderInfo.OrderNo), logger.Field("order_no", orderInfo.OrderNo),
) )
} }
orderInfo.Status = OrderStatusFinished
commonLogic.SubscriptionTraceInfo(logger.WithContext(ctx), commonLogic.SubscriptionTraceFlowOrder, "order_status_finished", commonLogic.SubscriptionTraceInfo(logger.WithContext(ctx), commonLogic.SubscriptionTraceFlowOrder, "order_status_finished",
"[SubscriptionFlow] order status updated to finished", "[SubscriptionFlow] order status updated to finished",
commonLogic.OrderTraceFields(orderInfo)..., commonLogic.OrderTraceFields(orderInfo)...,
@@ -597,7 +636,7 @@ func (l *ActivateOrderLogic) NewPurchase(ctx context.Context, orderInfo *order.O
return err return err
} }
if err = validateNewUserOnlyEligibilityAtActivation(ctx, l.svc.DB, orderInfo, sub); err != nil { if err = validateNewUserOnlyEligibilityAtActivation(ctx, l.svc.DB, l.svc.Redis, orderInfo, sub); err != nil {
return err return err
} }
@@ -675,18 +714,23 @@ func (l *ActivateOrderLogic) NewPurchase(ctx context.Context, orderInfo *order.O
// 兜底:创建新订阅前,查找用户是否已有同套餐的订阅记录(含过期/赠送), // 兜底:创建新订阅前,查找用户是否已有同套餐的订阅记录(含过期/赠送),
// 有则复用旧记录续期,避免出现重复订阅。 // 有则复用旧记录续期,避免出现重复订阅。
// 需要同时检查 UserId 和 SubscriptionUserId,因为家庭组绑定前后 owner 可能不同。 // 需要同时检查 UserId 和 SubscriptionUserId,因为家庭组绑定前后 owner 可能不同。
// 使用 SELECT ... FOR UPDATE 防止并发下多个 worker 同时选中同一订阅并创建重复记录。
if userSub == nil { if userSub == nil {
candidateUserIds := []int64{orderInfo.UserId} candidateUserIds := []int64{orderInfo.UserId}
if orderInfo.SubscriptionUserId > 0 && orderInfo.SubscriptionUserId != orderInfo.UserId { if orderInfo.SubscriptionUserId > 0 && orderInfo.SubscriptionUserId != orderInfo.UserId {
candidateUserIds = append(candidateUserIds, orderInfo.SubscriptionUserId) candidateUserIds = append(candidateUserIds, orderInfo.SubscriptionUserId)
} }
var existingSub user.Subscribe var existingSub user.Subscribe
if findErr := l.svc.DB.Model(&user.Subscribe{}). findErr := l.svc.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
Where("user_id IN ? AND token != ''", candidateUserIds). return tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Order("expire_time DESC"). Model(&user.Subscribe{}).
Order("updated_at DESC"). Where("user_id IN ? AND token != ''", candidateUserIds).
Order("id DESC"). Order("expire_time DESC").
First(&existingSub).Error; findErr == nil { Order("updated_at DESC").
Order("id DESC").
First(&existingSub).Error
})
if findErr == nil {
// 家庭组场景:订阅 owner 可能变更(如成员注册的试用 → 被家主收归), // 家庭组场景:订阅 owner 可能变更(如成员注册的试用 → 被家主收归),
// 续期前把 user_id 校正为当前订单的 SubscriptionUserId // 续期前把 user_id 校正为当前订单的 SubscriptionUserId
effectiveOwner := orderInfo.UserId effectiveOwner := orderInfo.UserId
@@ -824,26 +868,52 @@ func (l *ActivateOrderLogic) createGuestUser(ctx context.Context, orderInfo *ord
return userInfo, nil return userInfo, nil
} }
// getTempOrderInfo retrieves temporary order information from Redis cache // getTempOrderInfo retrieves temporary order information from Redis cache with DB fallback.
func (l *ActivateOrderLogic) getTempOrderInfo(ctx context.Context, orderNo string) (*constant.TemporaryOrderInfo, error) { func (l *ActivateOrderLogic) getTempOrderInfo(ctx context.Context, orderNo string) (*constant.TemporaryOrderInfo, error) {
cacheKey := fmt.Sprintf(constant.TempOrderCacheKey, orderNo) cacheKey := fmt.Sprintf(constant.TempOrderCacheKey, orderNo)
data, err := l.svc.Redis.Get(ctx, cacheKey).Result() data, err := l.svc.Redis.Get(ctx, cacheKey).Result()
if err != nil { if err == nil {
logger.WithContext(ctx).Error("Get temp order cache failed", var tempOrder constant.TemporaryOrderInfo
logger.Field("error", err.Error()), if unmarshalErr := tempOrder.Unmarshal([]byte(data)); unmarshalErr != nil {
logger.Field("cache_key", cacheKey), logger.WithContext(ctx).Error("Unmarshal temp order cache failed",
logger.Field("error", unmarshalErr.Error()),
logger.Field("cache_key", cacheKey),
logger.Field("data", data),
)
return nil, unmarshalErr
}
return &tempOrder, nil
}
// Redis miss — fall back to DB activation_context field.
logger.WithContext(ctx).Infow("Redis cache miss for temp order, falling back to DB",
logger.Field("cache_key", cacheKey),
logger.Field("error", err.Error()),
)
orderInfo, dbErr := l.svc.OrderModel.FindOneByOrderNo(ctx, orderNo)
if dbErr != nil {
logger.WithContext(ctx).Error("DB fallback for temp order failed",
logger.Field("order_no", orderNo),
logger.Field("error", dbErr.Error()),
) )
return nil, err return nil, dbErr
}
if orderInfo.ActivationContext == "" {
logger.WithContext(ctx).Error("CRITICAL: activation_context missing in DB and Redis expired; cannot recover guest order",
logger.Field("order_no", orderNo),
)
return nil, errors.New("activation context not found: Redis expired and no DB fallback available")
} }
var tempOrder constant.TemporaryOrderInfo var tempOrder constant.TemporaryOrderInfo
if err = tempOrder.Unmarshal([]byte(data)); err != nil { if unmarshalErr := tempOrder.Unmarshal([]byte(orderInfo.ActivationContext)); unmarshalErr != nil {
logger.WithContext(ctx).Error("Unmarshal temp order cache failed", logger.WithContext(ctx).Error("Unmarshal DB activation_context failed",
logger.Field("error", err.Error()), logger.Field("order_no", orderNo),
logger.Field("cache_key", cacheKey), logger.Field("error", unmarshalErr.Error()),
logger.Field("data", data),
) )
return nil, err return nil, unmarshalErr
} }
return &tempOrder, nil return &tempOrder, nil
@@ -1447,7 +1517,40 @@ func (l *ActivateOrderLogic) resolveRenewalActivationSubscription(ctx context.Co
} }
userSub, err := l.getUserSubscription(ctx, orderInfo.SubscribeToken) userSub, err := l.getUserSubscription(ctx, orderInfo.SubscribeToken)
if err != nil { if err != nil {
return nil, err // Fallback: token may have been lost (subscription deleted or owner changed).
// Locate the most recent subscription by user_id + subscribe_id with FOR UPDATE
// to prevent a concurrent worker from renewing the same record twice.
targetUserID := orderInfo.UserId
if orderInfo.SubscriptionUserId > 0 {
targetUserID = orderInfo.SubscriptionUserId
}
var fallbackSub user.Subscribe
txErr := l.svc.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
return tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Model(&user.Subscribe{}).
Where("user_id = ? AND subscribe_id = ?", targetUserID, orderInfo.SubscribeId).
Where("status IN ?", []int64{0, 1, 2, 3}).
Order("expire_time DESC").
Order("updated_at DESC").
Order("id DESC").
First(&fallbackSub).Error
})
if txErr != nil {
logger.WithContext(ctx).Error("CRITICAL: Renewal activation token and fallback lookup both failed",
logger.Field("token_error", err.Error()),
logger.Field("fallback_error", txErr.Error()),
logger.Field("order_no", orderInfo.OrderNo),
logger.Field("target_user_id", targetUserID),
logger.Field("subscribe_id", orderInfo.SubscribeId),
)
return nil, fmt.Errorf("renewal activation subscription not found by token or user_id+subscribe_id for order %s: %w", orderInfo.OrderNo, err)
}
logger.WithContext(ctx).Info("Renewal token lookup failed; found subscription via fallback user_id+subscribe_id",
logger.Field("order_no", orderInfo.OrderNo),
logger.Field("fallback_subscribe_id", fallbackSub.Id),
logger.Field("target_user_id", targetUserID),
)
userSub = &fallbackSub
} }
if orderInfo.UserId <= 0 { if orderInfo.UserId <= 0 {
return userSub, nil return userSub, nil
@@ -1743,25 +1846,50 @@ func (l *ActivateOrderLogic) RedemptionActivate(ctx context.Context, orderInfo *
return err return err
} }
// 3. 从Redis获取兑换码信息 // 3. 从Redis获取兑换码信息Redis缺失时回查DB
cacheKey := fmt.Sprintf("redemption_order:%s", orderInfo.OrderNo)
data, err := l.svc.Redis.Get(ctx, cacheKey).Result()
if err != nil {
logger.WithContext(ctx).Error("Get redemption cache failed",
logger.Field("error", err.Error()),
logger.Field("cache_key", cacheKey),
)
return err
}
var redemptionData struct { var redemptionData struct {
RedemptionCodeId int64 `json:"redemption_code_id"` RedemptionCodeId int64 `json:"redemption_code_id"`
UnitTime string `json:"unit_time"` UnitTime string `json:"unit_time"`
Quantity int64 `json:"quantity"` Quantity int64 `json:"quantity"`
} }
if err = json.Unmarshal([]byte(data), &redemptionData); err != nil {
logger.WithContext(ctx).Error("Unmarshal redemption cache failed", logger.Field("error", err.Error())) cacheKey := fmt.Sprintf("redemption_order:%s", orderInfo.OrderNo)
return err data, redisErr := l.svc.Redis.Get(ctx, cacheKey).Result()
if redisErr == nil {
if err = json.Unmarshal([]byte(data), &redemptionData); err != nil {
logger.WithContext(ctx).Error("Unmarshal redemption cache failed", logger.Field("error", err.Error()))
return err
}
} else {
// Redis miss — fall back to DB activation_context field.
logger.WithContext(ctx).Infow("Redis cache miss for redemption order, falling back to DB",
logger.Field("cache_key", cacheKey),
logger.Field("error", redisErr.Error()),
)
if orderInfo.ActivationContext == "" {
logger.WithContext(ctx).Error("CRITICAL: activation_context missing in DB and Redis expired; cannot recover redemption order",
logger.Field("order_no", orderInfo.OrderNo),
)
return errors.New("activation context not found: Redis expired and no DB fallback available")
}
var fullContext struct {
Type string `json:"type"`
RedemptionCodeId int64 `json:"redemption_code_id"`
UnitTime string `json:"unit_time"`
Quantity int64 `json:"quantity"`
}
if err = json.Unmarshal([]byte(orderInfo.ActivationContext), &fullContext); err != nil {
logger.WithContext(ctx).Error("Unmarshal DB activation_context failed",
logger.Field("order_no", orderInfo.OrderNo),
logger.Field("error", err.Error()),
)
return err
}
redemptionData.RedemptionCodeId = fullContext.RedemptionCodeId
redemptionData.UnitTime = fullContext.UnitTime
redemptionData.Quantity = fullContext.Quantity
} }
// 4. 幂等性检查:查询是否已有兑换记录 // 4. 幂等性检查:查询是否已有兑换记录
+16
View File
@@ -10,12 +10,14 @@ import (
"github.com/perfect-panel/server/internal/model/order" "github.com/perfect-panel/server/internal/model/order"
"github.com/perfect-panel/server/internal/model/subscribe" "github.com/perfect-panel/server/internal/model/subscribe"
internaltypes "github.com/perfect-panel/server/internal/types" internaltypes "github.com/perfect-panel/server/internal/types"
"github.com/redis/go-redis/v9"
"gorm.io/gorm" "gorm.io/gorm"
) )
func validateNewUserOnlyEligibilityAtActivation( func validateNewUserOnlyEligibilityAtActivation(
ctx context.Context, ctx context.Context,
db *gorm.DB, db *gorm.DB,
rdb *redis.Client,
orderInfo *order.Order, orderInfo *order.Order,
sub *subscribe.Subscribe, sub *subscribe.Subscribe,
) error { ) error {
@@ -31,6 +33,20 @@ func validateNewUserOnlyEligibilityAtActivation(
return nil return nil
} }
// Acquire a per-user distributed lock so concurrent new-user-only activations
// for the same account are serialised. Without this, two workers can both read
// historyCount=0 and both pass the check before either has written the order.
lockKey := fmt.Sprintf("new_user_only_activate:%d", orderInfo.UserId)
const lockTTL = 30 * time.Second
acquired, lockErr := rdb.SetNX(ctx, lockKey, orderInfo.OrderNo, lockTTL).Result()
if lockErr != nil {
return fmt.Errorf("new user only: acquire lock error: %w", lockErr)
}
if !acquired {
return fmt.Errorf("new user only: another activation is in progress for user %d", orderInfo.UserId)
}
defer rdb.Del(ctx, lockKey)
eligibility, err := commonLogic.ResolveNewUserEligibility(ctx, db, orderInfo.UserId) eligibility, err := commonLogic.ResolveNewUserEligibility(ctx, db, orderInfo.UserId)
if err != nil { if err != nil {
return err return err
@@ -0,0 +1,104 @@
package orderLogic
import (
"context"
"encoding/json"
"time"
"github.com/hibiken/asynq"
"github.com/perfect-panel/server/internal/model/order"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/logger"
queueTypes "github.com/perfect-panel/server/queue/types"
)
// StuckOrderRecoveryLogic scans orders stuck in claimed status and re-queues them for processing.
type StuckOrderRecoveryLogic struct {
svc *svc.ServiceContext
}
func NewStuckOrderRecoveryLogic(svc *svc.ServiceContext) *StuckOrderRecoveryLogic {
return &StuckOrderRecoveryLogic{svc: svc}
}
// ProcessTask scans for orders stuck in claimed status for over 10 minutes,
// resets them to paid, and re-enqueues the activate task so they are retried
// independently of asynq's original retry counter (which may be exhausted).
func (l *StuckOrderRecoveryLogic) ProcessTask(ctx context.Context, _ *asynq.Task) error {
cutoff := time.Now().Add(-10 * time.Minute)
var stuckOrders []order.Order
if err := l.svc.DB.WithContext(ctx).
Model(&order.Order{}).
Where("status = ? AND updated_at < ?", OrderStatusClaimed, cutoff).
Find(&stuckOrders).Error; err != nil {
logger.WithContext(ctx).Error("[StuckOrderRecovery] Failed to query stuck orders",
logger.Field("error", err.Error()),
)
return err
}
if len(stuckOrders) == 0 {
return nil
}
orderNos := make([]string, 0, len(stuckOrders))
for i := range stuckOrders {
orderNos = append(orderNos, stuckOrders[i].OrderNo)
}
logger.WithContext(ctx).Error("[StuckOrderRecovery] Found stuck claimed orders, recovering",
logger.Field("count", len(stuckOrders)),
logger.Field("order_nos", orderNos),
)
for i := range stuckOrders {
o := &stuckOrders[i]
result := l.svc.DB.WithContext(ctx).
Model(&order.Order{}).
Where("order_no = ? AND status = ?", o.OrderNo, OrderStatusClaimed).
Update("status", OrderStatusPaid)
if result.Error != nil {
logger.WithContext(ctx).Error("[StuckOrderRecovery] Failed to reset order status",
logger.Field("order_no", o.OrderNo),
logger.Field("error", result.Error.Error()),
)
continue
}
if result.RowsAffected == 0 {
// Another process already handled this order
continue
}
// Invalidate order cache
o.Status = OrderStatusPaid
if err := l.svc.OrderModel.Update(ctx, o); err != nil {
logger.WithContext(ctx).Error("[StuckOrderRecovery] Failed to update order cache",
logger.Field("order_no", o.OrderNo),
logger.Field("error", err.Error()),
)
}
// Re-enqueue activate task so the order gets processed regardless of asynq retry state
payload, err := json.Marshal(queueTypes.ForthwithActivateOrderPayload{OrderNo: o.OrderNo})
if err != nil {
logger.WithContext(ctx).Error("[StuckOrderRecovery] Failed to marshal task payload",
logger.Field("order_no", o.OrderNo),
logger.Field("error", err.Error()),
)
continue
}
if _, err = l.svc.Queue.EnqueueContext(ctx, asynq.NewTask(queueTypes.ForthwithActivateOrder, payload)); err != nil {
logger.WithContext(ctx).Error("[StuckOrderRecovery] Failed to re-enqueue activate task",
logger.Field("order_no", o.OrderNo),
logger.Field("error", err.Error()),
)
} else {
logger.WithContext(ctx).Info("[StuckOrderRecovery] Re-enqueued activate task",
logger.Field("order_no", o.OrderNo),
)
}
}
return nil
}
+3 -2
View File
@@ -5,6 +5,7 @@ const (
SchedulerTotalServerData = "scheduler:total:server" SchedulerTotalServerData = "scheduler:total:server"
SchedulerResetTraffic = "scheduler:reset:traffic" SchedulerResetTraffic = "scheduler:reset:traffic"
SchedulerTrafficStat = "scheduler:traffic:stat" SchedulerTrafficStat = "scheduler:traffic:stat"
SchedulerIAPReconcile = "scheduler:iap:reconcile" // 第二层:每 5 分钟扫描待支付 IAP 订单 SchedulerIAPReconcile = "scheduler:iap:reconcile" // 第二层:每 5 分钟扫描待支付 IAP 订单
SchedulerIAPDailyReconcile = "scheduler:iap:daily:reconcile" // 第三层:日终全量对账 SchedulerIAPDailyReconcile = "scheduler:iap:daily:reconcile" // 第三层:日终全量对账
SchedulerStuckOrderRecovery = "scheduler:stuck:order:recovery" // 扫描并恢复超时 claimed 订单
) )
+6
View File
@@ -64,6 +64,12 @@ func (m *Service) Start() {
logger.Errorf("register iap daily reconcile task failed: %s", err.Error()) logger.Errorf("register iap daily reconcile task failed: %s", err.Error())
} }
// schedule stuck order recovery: every 10 minutes
stuckOrderTask := asynq.NewTask(types.SchedulerStuckOrderRecovery, nil)
if _, err := m.server.Register("@every 10m", stuckOrderTask, asynq.MaxRetry(1)); err != nil {
logger.Errorf("register stuck order recovery task failed: %s", err.Error())
}
if err := m.server.Run(); err != nil { if err := m.server.Run(); err != nil {
logger.Errorf("run scheduler failed: %s", err.Error()) logger.Errorf("run scheduler failed: %s", err.Error())
} }
+44
View File
@@ -0,0 +1,44 @@
导出数据库:
mysqldump --socket=/var/run/mysqld/mysqld.sock -uroot -p --single-transaction --routines --triggers --events --set-gtid-purged=OFF --source-data=2 --no-tablespaces hifast > /root/data/hifast-final-0515.sql
jpcV41ppanel
gzip -1 /root/hifast-final-0515.sql
导出redis
redis-cli -a '0BVz9XOHf7KUfEuoFJRK-dURdKUGFiZ8QeaHpysHnKeKhLskZb55HPK121lFsKtr' BGSAVE
sleep 5
cp /var/lib/redis/dump.rdb /root/data/redis-backup-0515.rdb
导入数据库:
gunzip -c /root/hifast-final-0515.sql.gz | docker exec -i ppanel-mysql mysql -uroot -p'jpcV41ppanel' hifast
导入redis
docker stop ppanel-redis
docker cp /root/data/redis-backup-0515.rdb ppanel-redis:/data/dump.rdb
docker start ppanel-redis
docker exec ppanel-redis redis-cli -a 'hifast67yj' DBSIZE
docker stop ppanel-redis || true
docker rm -f ppanel-redis
rm -f /root/data/dump.rdb
rm -rf /root/data/appendonlydir
rm -f /root/data/appendonly.aof*
mkdir -p /root/data
docker pull redis:8.6.3
docker run -d \
--name ppanel-redis \
--restart always \
-p 6379:6379 \
redis:8.6.3 \
redis-server --requirepass 'hifast67yj'