Compare commits
39 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 197fed7d12 | |||
| f452f80100 | |||
| 1022160ff8 | |||
| 82eff47f38 | |||
| d351b50066 | |||
| 4366a9be8b | |||
| b5e50d1ee5 | |||
| 02b41e7a2c | |||
| d12c340743 | |||
| c90edac630 | |||
| b9192db042 | |||
| 48e507783e | |||
| d6efcb8e0b | |||
| d2f9289338 | |||
| 92e303aaa7 | |||
| 54328b197d | |||
| 5ebfe0a981 | |||
| 22d9773f1b | |||
| d89798f001 | |||
| 81c3059892 | |||
| f9fa4756e9 | |||
| 27f1203282 | |||
| f7f890c990 | |||
| 8b4e7561f4 | |||
| a6e9e2bdb8 | |||
| b798f520c8 | |||
| bae234fe15 | |||
| 79ab4460bc | |||
| 0169a16ada | |||
| b6b5bccde6 | |||
| eba256bdc9 | |||
| 72f2b94263 | |||
| bb67ebcb79 | |||
| 0bd7560b64 | |||
| a0f2d8a7b8 | |||
| 30221232c9 | |||
| 80751eb8ef | |||
| 3bbce5ce84 | |||
| 1726a584fa |
+2
-2
@@ -7,8 +7,8 @@ MYSQL_ROOT_PASSWORD=CHANGE_ME_TO_STRONG_PASSWORD
|
||||
# Grafana 管理员密码
|
||||
GRAFANA_PASSWORD=CHANGE_ME_TO_STRONG_PASSWORD
|
||||
|
||||
# PPanel Server 镜像标签(留空使用 latest)
|
||||
PPANEL_SERVER_TAG=latest
|
||||
# PPanel Server 镜像标签(由 CI/CD 传入不可变 tag,如 git SHA)
|
||||
PPANEL_SERVER_TAG=CHANGE_ME_TO_GIT_SHA
|
||||
|
||||
# AWS 区域(香港)
|
||||
AWS_REGION=ap-east-1
|
||||
|
||||
+142
-44
@@ -21,8 +21,8 @@ env:
|
||||
# SSH私钥(Gitea Secret 名称:AWS)
|
||||
SSH_KEY: ${{ secrets.AWS }}
|
||||
# TG通知
|
||||
TG_BOT_TOKEN: 8114337882:AAHkEx03HSu7RxN4IHBJJEnsK9aPPzNLIk0
|
||||
TG_CHAT_ID: "-4940243803"
|
||||
TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN }}
|
||||
TG_CHAT_ID: ${{ secrets.TG_CHAT_ID }}
|
||||
# Go构建变量
|
||||
SERVICE: vpn
|
||||
SERVICE_STYLE: vpn
|
||||
@@ -43,7 +43,7 @@ jobs:
|
||||
# 步骤1: 下载代码
|
||||
- name: 📥 下载代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
|
||||
# 步骤2: 设置动态环境变量
|
||||
- name: ⚙️ 设置动态环境变量
|
||||
run: |
|
||||
@@ -51,19 +51,22 @@ jobs:
|
||||
echo "DOCKER_TAG_SUFFIX=latest" >> $GITHUB_ENV
|
||||
echo "CONTAINER_NAME=ppanel-server" >> $GITHUB_ENV
|
||||
echo "DEPLOY_PATH=/opt/ppanel" >> $GITHUB_ENV
|
||||
echo "DEPLOY_ENV_LABEL=🚀 服务已成功部署到生产环境" >> $GITHUB_ENV
|
||||
echo "为 main 分支设置生产环境变量"
|
||||
elif [ "${{ github.ref_name }}" = "internal" ]; then
|
||||
echo "DOCKER_TAG_SUFFIX=internal" >> $GITHUB_ENV
|
||||
echo "CONTAINER_NAME=ppanel-server-internal" >> $GITHUB_ENV
|
||||
echo "DEPLOY_PATH=/root/bindbox" >> $GITHUB_ENV
|
||||
echo "DEPLOY_ENV_LABEL=🧪 服务已成功部署到测试环境" >> $GITHUB_ENV
|
||||
echo "为 internal 分支设置开发环境变量"
|
||||
else
|
||||
echo "DOCKER_TAG_SUFFIX=${{ github.ref_name }}" >> $GITHUB_ENV
|
||||
echo "CONTAINER_NAME=ppanel-server-${{ github.ref_name }}" >> $GITHUB_ENV
|
||||
echo "DEPLOY_PATH=/root/vpn_server_other" >> $GITHUB_ENV
|
||||
echo "DEPLOY_ENV_LABEL=🔧 服务已成功部署到其他环境" >> $GITHUB_ENV
|
||||
echo "为其他分支 (${{ github.ref_name }}) 设置环境变量"
|
||||
fi
|
||||
|
||||
|
||||
# 步骤3: 安装系统工具 (curl, jq) 并升级 Docker CLI 到 1.44+
|
||||
- name: 🔧 安装系统工具并升级 Docker CLI
|
||||
run: |
|
||||
@@ -111,35 +114,49 @@ jobs:
|
||||
docker --version || true
|
||||
docker version || true
|
||||
echo "客户端 API 版本:" $(docker version --format '{{.Client.APIVersion}}')
|
||||
|
||||
# 步骤4: 构建并发布到镜像仓库
|
||||
- name: 📤 构建并发布到镜像仓库
|
||||
|
||||
# 步骤4: 构建镜像
|
||||
- name: 🏗️ 构建镜像
|
||||
run: |
|
||||
echo "开始构建并推送镜像..."
|
||||
echo "开始构建镜像..."
|
||||
echo "仓库: ${{ env.REPO }}"
|
||||
echo "版本标签: ${{ env.VERSION }}"
|
||||
echo "分支标签: ${{ env.DOCKER_TAG_SUFFIX }}"
|
||||
|
||||
# 构建镜像,同时打上版本和分支两个标签
|
||||
BUILD_TAG_ARGS="-t ${{ env.REPO }}:${{ env.VERSION }}"
|
||||
if [ "${{ github.event_name }}" = "push" ]; then
|
||||
BUILD_TAG_ARGS="$BUILD_TAG_ARGS -t ${{ env.REPO }}:${{ env.DOCKER_TAG_SUFFIX }}"
|
||||
else
|
||||
echo "PR事件仅构建版本标签,不推送镜像、不部署"
|
||||
fi
|
||||
|
||||
docker build -f Dockerfile \
|
||||
--platform linux/amd64 \
|
||||
--build-arg TARGETARCH=amd64 \
|
||||
--build-arg VERSION=${{ env.VERSION }} \
|
||||
--build-arg BUILDTIME=${{ env.BUILDTIME }} \
|
||||
-t ${{ env.REPO }}:${{ env.VERSION }} \
|
||||
-t ${{ env.REPO }}:${{ env.DOCKER_TAG_SUFFIX }} \
|
||||
$BUILD_TAG_ARGS \
|
||||
.
|
||||
|
||||
|
||||
echo "镜像构建完成"
|
||||
|
||||
# 步骤5: 发布到镜像仓库
|
||||
- name: 📤 发布到镜像仓库
|
||||
if: github.event_name == 'push'
|
||||
run: |
|
||||
echo "开始推送镜像..."
|
||||
|
||||
echo "推送版本标签镜像: ${{ env.REPO }}:${{ env.VERSION }}"
|
||||
docker push ${{ env.REPO }}:${{ env.VERSION }}
|
||||
|
||||
|
||||
echo "推送分支标签镜像: ${{ env.REPO }}:${{ env.DOCKER_TAG_SUFFIX }}"
|
||||
docker push ${{ env.REPO }}:${{ env.DOCKER_TAG_SUFFIX }}
|
||||
|
||||
|
||||
echo "镜像推送完成"
|
||||
|
||||
# 调试: 打印部署目标(不输出敏感信息)
|
||||
|
||||
# 步骤6: 调试 - 打印部署目标(不输出敏感信息)
|
||||
- name: 🔍 调试 - 打印部署目标
|
||||
if: github.event_name == 'push'
|
||||
run: |
|
||||
echo "========== 部署目标调试 =========="
|
||||
echo "当前分支: ${{ github.ref_name }}"
|
||||
@@ -150,8 +167,9 @@ jobs:
|
||||
echo "DEPLOY_PATH: ${{ env.DEPLOY_PATH }}"
|
||||
echo "====================================="
|
||||
|
||||
# 步骤5: 传输配置文件
|
||||
# 步骤7: 传输配置文件
|
||||
- name: 📂 传输配置文件
|
||||
if: github.event_name == 'push'
|
||||
uses: appleboy/scp-action@v0.1.7
|
||||
with:
|
||||
host: ${{ env.SSH_HOST }}
|
||||
@@ -161,8 +179,9 @@ jobs:
|
||||
source: "docker-compose.cloud.yml"
|
||||
target: "/tmp/ppanel-deploy/"
|
||||
|
||||
# 步骤6: 连接服务器更新并启动
|
||||
# 步骤8: 连接服务器更新、健康检查并按需回滚
|
||||
- name: 🚀 连接服务器更新并启动
|
||||
if: github.event_name == 'push'
|
||||
uses: appleboy/ssh-action@v1.0.3
|
||||
with:
|
||||
host: ${{ env.SSH_HOST }}
|
||||
@@ -172,68 +191,147 @@ jobs:
|
||||
timeout: 300s
|
||||
command_timeout: 600s
|
||||
script: |
|
||||
set -e
|
||||
|
||||
echo "连接服务器成功,开始部署..."
|
||||
echo "部署目录: ${{ env.DEPLOY_PATH }}"
|
||||
echo "部署标签: ${{ env.DOCKER_TAG_SUFFIX }}"
|
||||
echo "登录用户: ${{ env.SSH_USER }}"
|
||||
|
||||
HEALTHCHECK_URL="http://127.0.0.1:8080/v1/common/heartbeat"
|
||||
NEW_TAG="${{ env.DOCKER_TAG_SUFFIX }}"
|
||||
ROLLBACK_TAG="rollback-${{ env.VERSION }}"
|
||||
SUDO=""
|
||||
if [ "${{ github.ref_name }}" = "main" ]; then
|
||||
SUDO="sudo"
|
||||
fi
|
||||
|
||||
docker_cmd() {
|
||||
if [ -n "$SUDO" ]; then
|
||||
sudo docker "$@"
|
||||
else
|
||||
docker "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
compose_with_tag() {
|
||||
tag="$1"
|
||||
shift
|
||||
if [ -n "$SUDO" ]; then
|
||||
sudo env PPANEL_SERVER_TAG="$tag" docker-compose -f docker-compose.cloud.yml "$@"
|
||||
else
|
||||
PPANEL_SERVER_TAG="$tag" docker-compose -f docker-compose.cloud.yml "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
write_previous_tag() {
|
||||
if [ -n "$SUDO" ]; then
|
||||
printf '%s\n' "${PREVIOUS_IMAGE_TAG:-}" | sudo tee .previous-ppanel-image-tag >/dev/null
|
||||
else
|
||||
printf '%s\n' "${PREVIOUS_IMAGE_TAG:-}" > .previous-ppanel-image-tag
|
||||
fi
|
||||
}
|
||||
|
||||
health_check() {
|
||||
attempt=1
|
||||
while [ "$attempt" -le 3 ]; do
|
||||
if curl -sf "$HEALTHCHECK_URL"; then
|
||||
echo
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "健康检查第 ${attempt}/3 次失败,10s 后重试..."
|
||||
attempt=$((attempt + 1))
|
||||
sleep 10
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
if [ "${{ github.ref_name }}" = "main" ]; then
|
||||
sudo mkdir -p ${{ env.DEPLOY_PATH }}
|
||||
sudo cp /tmp/ppanel-deploy/docker-compose.cloud.yml ${{ env.DEPLOY_PATH }}/docker-compose.cloud.yml
|
||||
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
|
||||
mkdir -p ${{ env.DEPLOY_PATH }}
|
||||
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
|
||||
|
||||
echo "✅ 部署命令执行完成"
|
||||
|
||||
# 步骤6: TG通知 (成功)
|
||||
|
||||
cd ${{ env.DEPLOY_PATH }}
|
||||
|
||||
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
|
||||
if: success()
|
||||
if: success() && github.event_name == 'push'
|
||||
uses: appleboy/telegram-action@master
|
||||
with:
|
||||
token: ${{ env.TG_BOT_TOKEN }}
|
||||
to: ${{ env.TG_CHAT_ID }}
|
||||
message: |
|
||||
✅ 部署成功!
|
||||
|
||||
|
||||
📦 项目: ${{ github.repository }}
|
||||
🌿 分支: ${{ github.ref_name }}
|
||||
📝 提交: ${{ github.sha }}
|
||||
👤 提交者: ${{ github.actor }}
|
||||
🕐 时间: ${{ github.event.head_commit.timestamp }}
|
||||
|
||||
🚀 服务已成功部署到生产环境
|
||||
|
||||
${{ env.DEPLOY_ENV_LABEL }}
|
||||
🩺 健康检查: 通过 (http://127.0.0.1:8080/v1/common/heartbeat)
|
||||
parse_mode: Markdown
|
||||
|
||||
# 步骤5: TG通知 (失败)
|
||||
|
||||
# 步骤10: TG通知 (失败)
|
||||
- name: 📱 发送失败通知到Telegram
|
||||
if: failure()
|
||||
if: failure() && github.event_name == 'push'
|
||||
uses: appleboy/telegram-action@master
|
||||
with:
|
||||
token: ${{ env.TG_BOT_TOKEN }}
|
||||
to: ${{ env.TG_CHAT_ID }}
|
||||
message: |
|
||||
❌ 部署失败!
|
||||
|
||||
|
||||
📦 项目: ${{ github.repository }}
|
||||
🌿 分支: ${{ github.ref_name }}
|
||||
📝 提交: ${{ github.sha }}
|
||||
👤 提交者: ${{ github.actor }}
|
||||
🕐 时间: ${{ github.event.head_commit.timestamp }}
|
||||
|
||||
|
||||
🩺 健康检查: 失败或未完成;若新版本健康检查连续 3 次失败,已自动尝试回滚并重新检查
|
||||
⚠️ 请检查构建日志获取详细信息
|
||||
parse_mode: Markdown
|
||||
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -268,6 +268,30 @@ type (
|
||||
OccurredAt int64 `json:"occurred_at"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
}
|
||||
GetLogMessageRawRequest {
|
||||
Id int64 `form:"id" validate:"required"`
|
||||
}
|
||||
GetLogMessageRawResponse {
|
||||
Id int64 `json:"id"`
|
||||
Platform string `json:"platform"`
|
||||
AppVersion string `json:"app_version"`
|
||||
OsName string `json:"os_name"`
|
||||
OsVersion string `json:"os_version"`
|
||||
DeviceId string `json:"device_id"`
|
||||
UserId *int64 `json:"user_id"`
|
||||
SessionId string `json:"session_id"`
|
||||
Level uint8 `json:"level"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
Message string `json:"message"`
|
||||
Stack string `json:"stack"`
|
||||
Context interface{} `json:"context"`
|
||||
ClientIP string `json:"client_ip"`
|
||||
UserAgent string `json:"user_agent"`
|
||||
Locale string `json:"locale"`
|
||||
Digest string `json:"digest"`
|
||||
OccurredAt int64 `json:"occurred_at"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
}
|
||||
)
|
||||
|
||||
@server (
|
||||
@@ -347,5 +371,9 @@ service ppanel {
|
||||
@doc "Get error log message detail"
|
||||
@handler GetErrorLogMessageDetail
|
||||
get /error_message/detail returns (GetErrorLogMessageDetailResponse)
|
||||
|
||||
@doc "Get log message raw detail (temporary)"
|
||||
@handler GetLogMessageRaw
|
||||
get /message/detail (GetLogMessageRawRequest) returns (GetLogMessageRawResponse)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
syntax = "v1"
|
||||
|
||||
info (
|
||||
title: "promo admin API"
|
||||
desc: "API for ppanel"
|
||||
author: "Tension"
|
||||
email: "tension@ppanel.com"
|
||||
version: "0.0.1"
|
||||
)
|
||||
|
||||
import "../types.api"
|
||||
|
||||
type (
|
||||
CreatePromoRuleRequest {
|
||||
Name string `json:"name" validate:"required,max=100"`
|
||||
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
Priority int64 `json:"priority" validate:"gte=0"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
StartTime *int64 `json:"start_time"`
|
||||
EndTime *int64 `json:"end_time"`
|
||||
}
|
||||
UpdatePromoRuleRequest {
|
||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
||||
Name string `json:"name" validate:"required,max=100"`
|
||||
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
Priority int64 `json:"priority" validate:"gte=0"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
StartTime *int64 `json:"start_time"`
|
||||
EndTime *int64 `json:"end_time"`
|
||||
}
|
||||
GetPromoRuleDetailRequest {
|
||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
||||
}
|
||||
DeletePromoRuleRequest {
|
||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
||||
}
|
||||
GetPromoRuleListRequest {
|
||||
Page int64 `form:"page" validate:"required,gt=0"`
|
||||
Size int64 `form:"size" validate:"required,gt=0,lte=200"`
|
||||
Type string `form:"type" validate:"omitempty,oneof=new_user inactive_user campaign"`
|
||||
Enabled *bool `form:"enabled"`
|
||||
Search string `form:"search,omitempty"`
|
||||
}
|
||||
GetPromoRuleListResponse {
|
||||
Total int64 `json:"total"`
|
||||
List []PromoRule `json:"list"`
|
||||
}
|
||||
SetPromoPriceRequest {
|
||||
PromoRuleId int64 `json:"promo_rule_id" validate:"required,gt=0"`
|
||||
Items []PromoPriceItem `json:"items" validate:"required,min=1,dive"`
|
||||
}
|
||||
GetPromoPriceListRequest {
|
||||
PromoRuleId int64 `form:"promo_rule_id" validate:"required,gt=0"`
|
||||
Page int64 `form:"page" validate:"required,gt=0"`
|
||||
Size int64 `form:"size" validate:"required,gt=0,lte=200"`
|
||||
}
|
||||
GetPromoPriceListResponse {
|
||||
Total int64 `json:"total"`
|
||||
List []PromoPrice `json:"list"`
|
||||
}
|
||||
DeletePromoPriceRequest {
|
||||
Id int64 `uri:"id" validate:"required,gt=0"`
|
||||
}
|
||||
GetPromoUsageListRequest {
|
||||
Page int64 `form:"page" validate:"required,gt=0"`
|
||||
Size int64 `form:"size" validate:"required,gt=0,lte=200"`
|
||||
RuleId int64 `form:"rule_id,omitempty"`
|
||||
UserId int64 `form:"user_id,omitempty"`
|
||||
SubscribeId int64 `form:"subscribe_id,omitempty"`
|
||||
OrderNo string `form:"order_no,omitempty"`
|
||||
}
|
||||
GetPromoUsageListResponse {
|
||||
Total int64 `json:"total"`
|
||||
List []PromoUsage `json:"list"`
|
||||
}
|
||||
)
|
||||
|
||||
@server (
|
||||
prefix: v1/admin/promo
|
||||
group: admin/promo
|
||||
middleware: AuthMiddleware
|
||||
)
|
||||
service ppanel {
|
||||
@doc "Create promo rule"
|
||||
@handler CreateRule
|
||||
post /rule (CreatePromoRuleRequest) returns (PromoRule)
|
||||
|
||||
@doc "Get promo rule list"
|
||||
@handler GetRuleList
|
||||
get /rule/list (GetPromoRuleListRequest) returns (GetPromoRuleListResponse)
|
||||
|
||||
@doc "Get promo rule detail"
|
||||
@handler GetRuleDetail
|
||||
get /rule/:id (GetPromoRuleDetailRequest) returns (PromoRule)
|
||||
|
||||
@doc "Update promo rule"
|
||||
@handler UpdateRule
|
||||
put /rule/:id (UpdatePromoRuleRequest) returns (PromoRule)
|
||||
|
||||
@doc "Delete promo rule"
|
||||
@handler DeleteRule
|
||||
delete /rule/:id (DeletePromoRuleRequest)
|
||||
|
||||
@doc "Set promo prices"
|
||||
@handler SetPrice
|
||||
post /price (SetPromoPriceRequest)
|
||||
|
||||
@doc "Get promo price list"
|
||||
@handler GetPriceList
|
||||
get /price/list (GetPromoPriceListRequest) returns (GetPromoPriceListResponse)
|
||||
|
||||
@doc "Delete promo price"
|
||||
@handler DeletePrice
|
||||
delete /price/:id (DeletePromoPriceRequest)
|
||||
|
||||
@doc "Get promo usage list"
|
||||
@handler GetUsageList
|
||||
get /usage/list (GetPromoUsageListRequest) returns (GetPromoUsageListResponse)
|
||||
}
|
||||
+29
-47
@@ -38,20 +38,20 @@ type (
|
||||
Id int64 `form:"id" validate:"required"`
|
||||
}
|
||||
UpdateUserBasiceInfoRequest {
|
||||
UserId int64 `json:"user_id" validate:"required"`
|
||||
Password string `json:"password"`
|
||||
Avatar string `json:"avatar"`
|
||||
Balance int64 `json:"balance"`
|
||||
Commission int64 `json:"commission"`
|
||||
ReferralPercentage uint8 `json:"referral_percentage"`
|
||||
OnlyFirstPurchase *bool `json:"only_first_purchase"`
|
||||
GiftAmount int64 `json:"gift_amount"`
|
||||
Telegram int64 `json:"telegram"`
|
||||
ReferCode string `json:"refer_code"`
|
||||
RefererId int64 `json:"referer_id"`
|
||||
Enable *bool `json:"enable"`
|
||||
IsAdmin *bool `json:"is_admin"`
|
||||
Remark string `json:"remark"`
|
||||
UserId int64 `json:"user_id" validate:"required"`
|
||||
Password string `json:"password"`
|
||||
Avatar string `json:"avatar"`
|
||||
Balance *int64 `json:"balance"`
|
||||
Commission *int64 `json:"commission"`
|
||||
ReferralPercentage uint8 `json:"referral_percentage"`
|
||||
OnlyFirstPurchase *bool `json:"only_first_purchase"`
|
||||
GiftAmount *int64 `json:"gift_amount"`
|
||||
Telegram int64 `json:"telegram"`
|
||||
ReferCode string `json:"refer_code"`
|
||||
RefererId *int64 `json:"referer_id"`
|
||||
Enable *bool `json:"enable"`
|
||||
IsAdmin *bool `json:"is_admin"`
|
||||
Remark *string `json:"remark"`
|
||||
}
|
||||
UpdateUserNotifySettingRequest {
|
||||
UserId int64 `json:"user_id" validate:"required"`
|
||||
@@ -76,29 +76,6 @@ type (
|
||||
GiftAmount int64 `json:"gift_amount"`
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
}
|
||||
UserSubscribeDetail {
|
||||
Id int64 `json:"id"`
|
||||
UserId int64 `json:"user_id"`
|
||||
User User `json:"user"`
|
||||
OrderId int64 `json:"order_id"`
|
||||
SubscribeId int64 `json:"subscribe_id"`
|
||||
Subscribe Subscribe `json:"subscribe"`
|
||||
NodeGroupId int64 `json:"node_group_id"`
|
||||
GroupLocked bool `json:"group_locked"`
|
||||
StartTime int64 `json:"start_time"`
|
||||
ExpireTime int64 `json:"expire_time"`
|
||||
ResetTime int64 `json:"reset_time"`
|
||||
Traffic int64 `json:"traffic"`
|
||||
Download int64 `json:"download"`
|
||||
Upload int64 `json:"upload"`
|
||||
Token string `json:"token"`
|
||||
Status uint8 `json:"status"`
|
||||
EffectiveSpeed int64 `json:"effective_speed"`
|
||||
IsThrottled bool `json:"is_throttled"`
|
||||
ThrottleRule string `json:"throttle_rule,omitempty"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
BatchDeleteUserRequest {
|
||||
Ids []int64 `json:"ids" validate:"required"`
|
||||
}
|
||||
@@ -158,18 +135,22 @@ type (
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
CreateUserSubscribeRequest {
|
||||
UserId int64 `json:"user_id"`
|
||||
ExpiredAt int64 `json:"expired_at"`
|
||||
Traffic int64 `json:"traffic"`
|
||||
SubscribeId int64 `json:"subscribe_id"`
|
||||
UserId int64 `json:"user_id"`
|
||||
ExpiredAt int64 `json:"expired_at"`
|
||||
Traffic int64 `json:"traffic"`
|
||||
SubscribeId int64 `json:"subscribe_id"`
|
||||
SpeedLimit int64 `json:"speed_limit,optional"`
|
||||
TrafficLimit string `json:"traffic_limit,optional"`
|
||||
}
|
||||
UpdateUserSubscribeRequest {
|
||||
UserSubscribeId int64 `json:"user_subscribe_id"`
|
||||
SubscribeId int64 `json:"subscribe_id"`
|
||||
Traffic int64 `json:"traffic"`
|
||||
ExpiredAt int64 `json:"expired_at"`
|
||||
Upload int64 `json:"upload"`
|
||||
Download int64 `json:"download"`
|
||||
UserSubscribeId int64 `json:"user_subscribe_id"`
|
||||
SubscribeId int64 `json:"subscribe_id"`
|
||||
Traffic int64 `json:"traffic"`
|
||||
ExpiredAt int64 `json:"expired_at"`
|
||||
Upload int64 `json:"upload"`
|
||||
Download int64 `json:"download"`
|
||||
SpeedLimit *int64 `json:"speed_limit,omitempty" validate:"omitempty,gte=0"`
|
||||
TrafficLimit *string `json:"traffic_limit,omitempty"`
|
||||
}
|
||||
GetUserLoginLogsRequest {
|
||||
Page int `form:"page"`
|
||||
@@ -235,6 +216,7 @@ type (
|
||||
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"`
|
||||
|
||||
+2
-13
@@ -16,13 +16,7 @@ type (
|
||||
}
|
||||
|
||||
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"`
|
||||
Url string `json:"url"`
|
||||
}
|
||||
|
||||
FileUploadInitRequest {
|
||||
@@ -47,12 +41,7 @@ type (
|
||||
}
|
||||
|
||||
FileUploadCompleteResponse {
|
||||
FileId string `json:"file_id"`
|
||||
ObjectKey string `json:"object_key"`
|
||||
Size int64 `json:"size"`
|
||||
ContentType string `json:"content_type"`
|
||||
Etag string `json:"etag"`
|
||||
Status string `json:"status"`
|
||||
Url string `json:"url"`
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
+28
-15
@@ -109,8 +109,11 @@ type (
|
||||
Rules []string `json:"rules" validate:"required"`
|
||||
}
|
||||
CommissionWithdrawRequest {
|
||||
Amount int64 `json:"amount"`
|
||||
Content string `json:"content"`
|
||||
Amount int64 `json:"amount"`
|
||||
Content string `json:"content"`
|
||||
Method uint8 `json:"method" validate:"oneof=0 1 2 3"`
|
||||
Account string `json:"account,omitempty"`
|
||||
QrCodeUrl string `json:"qr_code_url,omitempty"`
|
||||
}
|
||||
WithdrawalLog {
|
||||
Id int64 `json:"id"`
|
||||
@@ -119,9 +122,15 @@ type (
|
||||
Content string `json:"content"`
|
||||
Status uint8 `json:"status"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Method uint8 `json:"method"`
|
||||
Account string `json:"account"`
|
||||
QrCodeUrl string `json:"qr_code_url"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
CancelWithdrawalRequest {
|
||||
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
||||
}
|
||||
QueryWithdrawalLogListRequest {
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
@@ -192,21 +201,22 @@ type (
|
||||
GrowthRate string `json:"growth_rate"`
|
||||
PaidGrowthRate string `json:"paid_growth_rate"`
|
||||
}
|
||||
GetInviteSalesRequest {
|
||||
GetInviteRecordsRequest {
|
||||
Page int `form:"page"`
|
||||
Size int `form:"size"`
|
||||
StartTime int64 `form:"start_time"`
|
||||
EndTime int64 `form:"end_time"`
|
||||
}
|
||||
InvitedUserSale {
|
||||
Amount float64 `json:"amount"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
UserHash string `json:"user_hash"`
|
||||
ProductName string `json:"product_name"`
|
||||
InviteRecord {
|
||||
Role string `json:"role"`
|
||||
PeerHash string `json:"peer_hash"`
|
||||
GiftDays int64 `json:"gift_days"`
|
||||
OrderNo string `json:"order_no"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
}
|
||||
GetInviteSalesResponse {
|
||||
Total int64 `json:"total"`
|
||||
List []InvitedUserSale `json:"list"`
|
||||
GetInviteRecordsResponse {
|
||||
Total int64 `json:"total"`
|
||||
List []InviteRecord `json:"list"`
|
||||
}
|
||||
GetSubscribeStatusRequest {
|
||||
Email string `form:"email" json:"email" validate:"omitempty,email"`
|
||||
@@ -352,6 +362,10 @@ service ppanel {
|
||||
@handler CommissionWithdraw
|
||||
post /commission_withdraw (CommissionWithdrawRequest) returns (WithdrawalLog)
|
||||
|
||||
@doc "Cancel pending withdrawal"
|
||||
@handler CancelWithdrawal
|
||||
post /withdrawal_cancel (CancelWithdrawalRequest) returns (WithdrawalLog)
|
||||
|
||||
@doc "Query Withdrawal Log"
|
||||
@handler QueryWithdrawalLog
|
||||
get /withdrawal_log (QueryWithdrawalLogListRequest) returns (QueryWithdrawalLogListResponse)
|
||||
@@ -384,9 +398,9 @@ service ppanel {
|
||||
@handler GetAgentRealtime
|
||||
get /agent_realtime (GetAgentRealtimeRequest) returns (GetAgentRealtimeResponse)
|
||||
|
||||
@doc "Get Invite Sales"
|
||||
@handler GetInviteSales
|
||||
get /invite_sales (GetInviteSalesRequest) returns (GetInviteSalesResponse)
|
||||
@doc "Get Invite Records"
|
||||
@handler GetInviteRecords
|
||||
get /invite_records (GetInviteRecordsRequest) returns (GetInviteRecordsResponse)
|
||||
|
||||
@doc "Get Subscribe Status"
|
||||
@handler GetSubscribeStatus
|
||||
@@ -411,4 +425,3 @@ service ppanel {
|
||||
@handler DeviceWsConnect
|
||||
get /device_ws_connect
|
||||
}
|
||||
|
||||
|
||||
+79
-7
@@ -171,13 +171,13 @@ type (
|
||||
DeviceLimit int64 `json:"device_limit"`
|
||||
}
|
||||
VerifyConfig {
|
||||
CaptchaType string `json:"captcha_type"` // local or turnstile
|
||||
TurnstileSiteKey string `json:"turnstile_site_key"`
|
||||
TurnstileSecret string `json:"turnstile_secret"`
|
||||
EnableUserLoginCaptcha bool `json:"enable_user_login_captcha"` // User login captcha
|
||||
EnableUserRegisterCaptcha bool `json:"enable_user_register_captcha"` // User register captcha
|
||||
EnableAdminLoginCaptcha bool `json:"enable_admin_login_captcha"` // Admin login captcha
|
||||
EnableUserResetPasswordCaptcha bool `json:"enable_user_reset_password_captcha"` // User reset password captcha
|
||||
CaptchaType string `json:"captcha_type"` // local or turnstile
|
||||
TurnstileSiteKey string `json:"turnstile_site_key"`
|
||||
TurnstileSecret string `json:"turnstile_secret"`
|
||||
EnableUserLoginCaptcha bool `json:"enable_user_login_captcha"` // User login captcha
|
||||
EnableUserRegisterCaptcha bool `json:"enable_user_register_captcha"` // User register captcha
|
||||
EnableAdminLoginCaptcha bool `json:"enable_admin_login_captcha"` // Admin login captcha
|
||||
EnableUserResetPasswordCaptcha bool `json:"enable_user_reset_password_captcha"` // User reset password captcha
|
||||
}
|
||||
NodeConfig {
|
||||
NodeSecret string `json:"node_secret"`
|
||||
@@ -229,6 +229,48 @@ type (
|
||||
Quantity int64 `json:"quantity"`
|
||||
Discount float64 `json:"discount"`
|
||||
MapApple string `json:"map_apple"`
|
||||
Promo *SubscribePromo `json:"promo"`
|
||||
}
|
||||
PromoPrice {
|
||||
Id int64 `json:"id"`
|
||||
SubscribeId int64 `json:"subscribe_id"`
|
||||
PromoRuleId int64 `json:"promo_rule_id"`
|
||||
Quantity int64 `json:"quantity"`
|
||||
PromoPrice int64 `json:"promo_price"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
PromoPriceItem {
|
||||
SubscribeId int64 `json:"subscribe_id" validate:"required,gt=0"`
|
||||
Quantity int64 `json:"quantity" validate:"required,gt=0,lte=1000"`
|
||||
PromoPrice int64 `json:"promo_price" validate:"required,gt=0"`
|
||||
}
|
||||
PromoRule {
|
||||
Id int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
Priority int64 `json:"priority"`
|
||||
Enabled bool `json:"enabled"`
|
||||
StartTime *int64 `json:"start_time"`
|
||||
EndTime *int64 `json:"end_time"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
PromoUsage {
|
||||
Id int64 `json:"id"`
|
||||
UserId int64 `json:"user_id"`
|
||||
PromoRuleId int64 `json:"promo_rule_id"`
|
||||
SubscribeId int64 `json:"subscribe_id"`
|
||||
OrderNo string `json:"order_no"`
|
||||
PromoPrice int64 `json:"promo_price"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
}
|
||||
SubscribePromo {
|
||||
RuleName string `json:"rule_name"`
|
||||
RuleType string `json:"rule_type"`
|
||||
PromoPrice int64 `json:"promo_price"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
TrafficLimit {
|
||||
StatType string `json:"stat_type"`
|
||||
@@ -536,6 +578,35 @@ type (
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
UserSubscribeDetail {
|
||||
Id int64 `json:"id"`
|
||||
UserId int64 `json:"user_id"`
|
||||
User User `json:"user"`
|
||||
OrderId int64 `json:"order_id"`
|
||||
SubscribeId int64 `json:"subscribe_id"`
|
||||
Subscribe Subscribe `json:"subscribe"`
|
||||
NodeGroupId int64 `json:"node_group_id"`
|
||||
NodeGroupName string `json:"node_group_name"`
|
||||
GroupLocked bool `json:"group_locked"`
|
||||
StartTime int64 `json:"start_time"`
|
||||
ExpireTime int64 `json:"expire_time"`
|
||||
ResetTime int64 `json:"reset_time"`
|
||||
Traffic int64 `json:"traffic"`
|
||||
Download int64 `json:"download"`
|
||||
Upload int64 `json:"upload"`
|
||||
SpeedLimit int64 `json:"speed_limit"`
|
||||
TrafficLimit []TrafficLimit `json:"user_traffic_limit"`
|
||||
PlanSpeedLimit int64 `json:"plan_speed_limit"`
|
||||
Token string `json:"token"`
|
||||
Status uint8 `json:"status"`
|
||||
EffectiveSpeed int64 `json:"effective_speed"`
|
||||
IsThrottled bool `json:"is_throttled"`
|
||||
ThrottleRule string `json:"throttle_rule,omitempty"`
|
||||
ThrottleStart int64 `json:"throttle_start,omitempty"`
|
||||
ThrottleEnd int64 `json:"throttle_end,omitempty"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
UserAffiliate {
|
||||
Avatar string `json:"avatar"`
|
||||
Identifier string `json:"identifier"`
|
||||
@@ -679,6 +750,7 @@ type (
|
||||
Price int64 `json:"price"`
|
||||
Amount int64 `json:"amount"`
|
||||
Discount int64 `json:"discount"`
|
||||
PromoDiscount int64 `json:"promo_discount"`
|
||||
GiftAmount int64 `json:"gift_amount"`
|
||||
Coupon string `json:"coupon"`
|
||||
CouponDiscount int64 `json:"coupon_discount"`
|
||||
|
||||
@@ -4316,6 +4316,9 @@
|
||||
"discount": {
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
},
|
||||
"promo": {
|
||||
"$ref": "#/definitions/SubscribePromo"
|
||||
}
|
||||
},
|
||||
"title": "SubscribeDiscount",
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
# PPanel 日本东京区 AWS 部署说明
|
||||
|
||||
本目录用于在 **AWS 日本东京区 `ap-northeast-1`** 重建一套全新生产环境,并承接当前香港区 `ap-east-1` 的正式迁移。
|
||||
|
||||
如果你要看“当前已经真实跑起来的东京架构”,优先看:
|
||||
|
||||
- [`ops/hifast-current-architecture-zh.md`](/Users/Apple/code_vpn/vpn/ppanel-server/ops/hifast-current-architecture-zh.md)
|
||||
- [`configs/resource-inventory.current.md`](./configs/resource-inventory.current.md)
|
||||
|
||||
这份 README 更偏向:
|
||||
|
||||
- 目标架构
|
||||
- 资源规划
|
||||
- 部署方法
|
||||
- 后续待完成项
|
||||
|
||||
目标架构:
|
||||
|
||||
`DNS -> ALB -> WAF -> EC2(Nginx + ppanel-server + Redis + observability) -> RDS MySQL`
|
||||
|
||||
灾备链路:
|
||||
|
||||
`RDS MySQL / EC2 Redis -> 104.238.220.230 外部灾备`
|
||||
|
||||
当前仓库内已补充:
|
||||
|
||||
- 东京基础设施参数模板:[`configs/aws-jp-infra.env.example`](./configs/aws-jp-infra.env.example)
|
||||
- 东京真实实施状态登记:[`configs/resource-inventory.current.md`](./configs/resource-inventory.current.md)
|
||||
- 东京底座资源创建脚本:[`../../scripts/aws_jp_create_base_infra.sh`](../../scripts/aws_jp_create_base_infra.sh)
|
||||
- 东京资源状态检查脚本:[`../../scripts/aws_jp_describe_state.sh`](../../scripts/aws_jp_describe_state.sh)
|
||||
- MySQL 备份脚本:[`../../scripts/mysql_backup_to_s3.sh`](../../scripts/mysql_backup_to_s3.sh)
|
||||
- 10 分钟 MySQL 备份定时器安装脚本:[`../../scripts/install_mysql_backup_timer.sh`](../../scripts/install_mysql_backup_timer.sh)
|
||||
|
||||
## 1. 资源清单
|
||||
|
||||
按下面顺序创建资源:
|
||||
|
||||
1. VPC
|
||||
2. 2 个公有子网 + 2 个私有子网
|
||||
3. Internet Gateway
|
||||
4. 公有 / 私有路由表
|
||||
5. 安全组
|
||||
6. RDS MySQL
|
||||
7. EC2 本机 Redis Docker
|
||||
8. EC2
|
||||
9. ACM 证书
|
||||
10. ALB + Target Group
|
||||
11. WAF Web ACL
|
||||
12. 东京平行环境域名
|
||||
13. 东京 S3 备份桶
|
||||
|
||||
建议命名:
|
||||
|
||||
- VPC: `ppanel-jp-prod`
|
||||
- EC2: `ppanel-app-jp-01`
|
||||
- RDS: `ppanel-mysql-jp`
|
||||
- Redis container: `hifast-redis`
|
||||
- ALB: `ppanel-alb-jp`
|
||||
- WAF: `ppanel-waf-jp`
|
||||
- S3: `hifast-prod-backups-200810848252-ap-northeast-1`
|
||||
|
||||
## 2. 默认规格
|
||||
|
||||
### EC2
|
||||
|
||||
- Region: `ap-northeast-1`
|
||||
- OS: Ubuntu 24.04 LTS
|
||||
- Instance type: `t4g.large`
|
||||
- Disk: `gp3 80GB`
|
||||
- Public subnet: 是
|
||||
- IAM Role:
|
||||
- 允许读取 CloudWatch / SSM(如使用)
|
||||
- 如果要在东京 EC2 上执行 S3 备份:额外允许写入东京备份桶
|
||||
|
||||
### RDS MySQL
|
||||
|
||||
- Engine: `MySQL 8.4`
|
||||
- Class: `db.r7g.xlarge`
|
||||
- Storage: `gp3 100GB`
|
||||
- DB name: `hifast`
|
||||
- Username: `admin`
|
||||
- Public access: `Yes`
|
||||
- Charset: `utf8mb4`
|
||||
- Backup retention: `7-14 days`
|
||||
- Deletion protection: `On`
|
||||
- Multi-AZ: `Yes`(当前按 2 实例 Multi-AZ 创建)
|
||||
|
||||
说明:
|
||||
|
||||
- 当前东京 RDS 需要允许 `104.238.220.230` 从公网直连 `3306`,用于外部 MySQL 从库复制
|
||||
- 因此本阶段 RDS 使用 `public subnet group + Publicly accessible = Yes`
|
||||
- 访问面只通过 `sg-rds` 严格限制到业务 EC2 安全组和 `104.238.220.230/32`
|
||||
|
||||
### Redis
|
||||
|
||||
- 部署位置:业务 EC2 本机
|
||||
- 部署方式:Docker
|
||||
- 版本:`redis:8.2.1`
|
||||
- 监听:`0.0.0.0:6379`
|
||||
- 应用连接:`127.0.0.1:6379`
|
||||
- 安全组:仅对白名单备用节点 `104.238.220.230/32` 或同机应用开放
|
||||
|
||||
## 3. 网络与安全组
|
||||
|
||||
### 子网布局
|
||||
|
||||
- `public-a`, `public-c`: ALB / EC2
|
||||
- `private-a`, `private-c`: RDS
|
||||
|
||||
说明:
|
||||
|
||||
- 东京优先使用 `ap-northeast-1a` 和 `ap-northeast-1c`
|
||||
- 如果账户映射不同,也可以用任意 2 个可用区,但公私网必须各 2 个子网
|
||||
|
||||
### 安全组建议
|
||||
|
||||
#### `sg-alb`
|
||||
|
||||
- Inbound
|
||||
- `80/tcp` from `0.0.0.0/0`
|
||||
- `443/tcp` from `0.0.0.0/0`
|
||||
- Outbound
|
||||
- `80/tcp` to `sg-ec2`
|
||||
|
||||
#### `sg-ec2`
|
||||
|
||||
- Inbound
|
||||
- `80/tcp` from `sg-alb`
|
||||
- `22/tcp` from `你的固定运维 IP`
|
||||
- `6379/tcp` from `104.238.220.230/32`
|
||||
- Outbound
|
||||
- all
|
||||
|
||||
说明:
|
||||
|
||||
- 应用容器监听 `127.0.0.1:8080`
|
||||
- EC2 对外只让 Nginx 监听 `80`
|
||||
- Grafana / Prometheus / Tempo 仅监听 `127.0.0.1`
|
||||
|
||||
#### `sg-rds`
|
||||
|
||||
- Inbound
|
||||
- `3306/tcp` from `sg-ec2`
|
||||
- `3306/tcp` from `104.238.220.230/32`
|
||||
|
||||
## 4. ALB / Target Group / 健康检查
|
||||
|
||||
### Target Group
|
||||
|
||||
- Type: `Instance`
|
||||
- Protocol: `HTTP`
|
||||
- Port: `80`
|
||||
- Health check path: `/v1/common/heartbeat`
|
||||
- Success code: `200`
|
||||
|
||||
### ALB 监听器
|
||||
|
||||
- `80` -> redirect to `443`
|
||||
- `443` -> forward 到 target group
|
||||
|
||||
### ACM
|
||||
|
||||
- 在 `ap-northeast-1` 重新申请证书
|
||||
- 先给平行环境域名,例如:
|
||||
- `api-jp.hifast.biz`
|
||||
- `logs-jp.hifast.biz`
|
||||
|
||||
## 5. WAF 规则
|
||||
|
||||
首版至少启用:
|
||||
|
||||
1. `AWSManagedRulesCommonRuleSet`
|
||||
2. `AWSManagedRulesKnownBadInputsRuleSet`
|
||||
3. `AWSManagedRulesAmazonIpReputationList`
|
||||
4. 全站 rate-based rule
|
||||
5. 针对高风险路径的 rate-based rule
|
||||
|
||||
建议的第一版限流:
|
||||
|
||||
- 全站:每 IP `2000 / 5 分钟`
|
||||
- `/v1/public/user/subscribe`:每 IP `300 / 5 分钟`
|
||||
- 登录 / 注册 / 验证码接口:每 IP `100 / 5 分钟`
|
||||
|
||||
节点上报接口建议后续补:
|
||||
|
||||
- `/v1/server/status`
|
||||
- `/v1/server/online`
|
||||
- `/v1/server/traffic`
|
||||
|
||||
## 6. EC2 文件落地
|
||||
|
||||
在 EC2 上建议使用:
|
||||
|
||||
- 应用目录:`/opt/ppanel`
|
||||
- Nginx 配置:`/etc/nginx/sites-available/ppanel-api.conf`
|
||||
|
||||
需要上传这些文件 / 目录:
|
||||
|
||||
- `docker-compose.cloud.yml`
|
||||
- `deploy/aws/ap-northeast-1/configs/ppanel.yaml.example` -> 重命名为 `configs/ppanel.yaml`
|
||||
- `deploy/aws/ap-northeast-1/nginx/ppanel-api.conf`
|
||||
- `grafana/`
|
||||
- `loki/`
|
||||
- `prometheus/`
|
||||
- `tempo/`
|
||||
- `.env.example` -> 重命名为 `.env`
|
||||
|
||||
目标目录示例:
|
||||
|
||||
```text
|
||||
/opt/ppanel/
|
||||
docker-compose.cloud.yml
|
||||
.env
|
||||
configs/ppanel.yaml
|
||||
grafana/
|
||||
loki/
|
||||
prometheus/
|
||||
tempo/
|
||||
logs/
|
||||
cache/
|
||||
tempo_data/
|
||||
```
|
||||
|
||||
## 7. 应用配置
|
||||
|
||||
基线模板见:
|
||||
|
||||
- [`configs/ppanel.yaml.example`](./configs/ppanel.yaml.example)
|
||||
- [`nginx/ppanel-api.conf`](./nginx/ppanel-api.conf)
|
||||
|
||||
关键值必须替换:
|
||||
|
||||
- `MySQL.Addr`
|
||||
- `MySQL.Password`
|
||||
- `Redis.Host`
|
||||
- `Redis.Pass`
|
||||
- `JwtAuth.AccessSecret`
|
||||
- `Administrator.Email`
|
||||
- `Administrator.Password`
|
||||
- `AppSignature.AppSecrets.*`
|
||||
- `device.security_secret`
|
||||
- `Site.Host`
|
||||
- `Site.SiteName`
|
||||
|
||||
Redis 约定保持不变:
|
||||
|
||||
- 业务缓存:DB `0`
|
||||
- Asynq:DB `5`
|
||||
|
||||
## 8. 部署步骤
|
||||
|
||||
### 8.0 创建东京基础设施
|
||||
|
||||
如果本机或跳板机已经配置好 AWS CLI 凭据,可以先直接执行:
|
||||
|
||||
```bash
|
||||
cp deploy/aws/ap-northeast-1/configs/aws-jp-infra.env.example /root/aws-jp-infra.env
|
||||
chmod 600 /root/aws-jp-infra.env
|
||||
vim /root/aws-jp-infra.env
|
||||
|
||||
chmod +x deploy/scripts/aws_jp_create_base_infra.sh
|
||||
bash deploy/scripts/aws_jp_create_base_infra.sh /root/aws-jp-infra.env
|
||||
```
|
||||
|
||||
执行后可用下面命令随时核对东京底座状态:
|
||||
|
||||
```bash
|
||||
chmod +x deploy/scripts/aws_jp_describe_state.sh
|
||||
bash deploy/scripts/aws_jp_describe_state.sh /root/aws-jp-infra.env
|
||||
```
|
||||
|
||||
### 8.1 初始化 EC2
|
||||
|
||||
把脚本上传到东京 EC2 后执行:
|
||||
|
||||
```bash
|
||||
chmod +x deploy/scripts/bootstrap_aws_ec2.sh
|
||||
sudo APP_DIR=/opt/ppanel APP_USER=ubuntu deploy/scripts/bootstrap_aws_ec2.sh
|
||||
```
|
||||
|
||||
### 8.2 安装 Nginx 配置
|
||||
|
||||
```bash
|
||||
sudo cp deploy/aws/ap-northeast-1/nginx/ppanel-api.conf /etc/nginx/sites-available/ppanel-api.conf
|
||||
sudo ln -sf /etc/nginx/sites-available/ppanel-api.conf /etc/nginx/sites-enabled/ppanel-api.conf
|
||||
sudo nginx -t
|
||||
sudo systemctl reload nginx
|
||||
```
|
||||
|
||||
### 8.3 启动容器
|
||||
|
||||
```bash
|
||||
cd /opt/ppanel
|
||||
docker compose -f docker-compose.cloud.yml up -d
|
||||
```
|
||||
|
||||
### 8.4 预检
|
||||
|
||||
```bash
|
||||
chmod +x deploy/scripts/preflight_aws_jp.sh
|
||||
APP_DIR=/opt/ppanel \
|
||||
RDS_HOST=<TOKYO_RDS_ENDPOINT> \
|
||||
REDIS_HOST=127.0.0.1 \
|
||||
deploy/scripts/preflight_aws_jp.sh
|
||||
```
|
||||
|
||||
## 9. 数据迁移与切换
|
||||
|
||||
正式迁移请按:
|
||||
|
||||
- [`ops/hifast-aws-jp-migration-runbook-zh.md`](/Users/Apple/code_vpn/vpn/ppanel-server/ops/hifast-aws-jp-migration-runbook-zh.md)
|
||||
|
||||
执行。
|
||||
|
||||
核心原则:
|
||||
|
||||
- 先搭平行环境
|
||||
- 停机后再导出香港主数据
|
||||
- 东京验收通过后再切正式域名
|
||||
- 切换后再重挂 `104` 灾备
|
||||
|
||||
## 10. 104 灾备节点常用模板
|
||||
|
||||
如果迁移完成后要把 `104.238.220.230` 重挂为东京主站从库,可复用:
|
||||
|
||||
- [`deploy/scripts/hifast_mysql_seed_primary_and_replica.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/hifast_mysql_seed_primary_and_replica.sh)
|
||||
- [`deploy/scripts/hifast_mysql_attach_replica.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/hifast_mysql_attach_replica.sh)
|
||||
- [`deploy/scripts/hifast_redis_attach_replica.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/hifast_redis_attach_replica.sh)
|
||||
- [`deploy/scripts/hifast_data_sync_tool.sh`](/Users/Apple/code_vpn/vpn/ppanel-server/deploy/scripts/hifast_data_sync_tool.sh)
|
||||
- [`configs/replica-ops.env.example`](./configs/replica-ops.env.example)
|
||||
|
||||
## 11. 东京资源创建前置检查
|
||||
|
||||
在 AWS 控制台里至少先确认:
|
||||
|
||||
- 东京区已启用
|
||||
- `ap-northeast-1` 可创建 `t4g.large`
|
||||
- `ap-northeast-1` RDS 可创建 `db.r7g.xlarge`
|
||||
- ACM / ALB / WAF / S3 服务在东京区可正常使用
|
||||
- Tokyo 对应配额满足:
|
||||
- On-Demand Standard vCPU
|
||||
- ALB 数量
|
||||
- Elastic IP(如需)
|
||||
- RDS 实例数
|
||||
|
||||
## 12. 当前已知真实进度
|
||||
|
||||
截至 `2026-05-20`,已知状态如下:
|
||||
|
||||
- 东京 VPC `ppanel-jp-prod` 已创建
|
||||
- VPC ID: `vpc-0846b23b4a7d64eac`
|
||||
- VPC CIDR: `10.20.0.0/16`
|
||||
- 4 个子网在 AWS 控制台里曾填写完成,但提交时控制台 session 失效
|
||||
- 因此:
|
||||
- 子网是否真正创建成功,需要重新核实
|
||||
- IGW / 路由表 / 安全组 / RDS / EC2 / ALB / WAF 都应按“未完成”处理,重新复核
|
||||
|
||||
实时状态请以后续更新的 [`configs/resource-inventory.current.md`](./configs/resource-inventory.current.md) 为准。
|
||||
@@ -0,0 +1,55 @@
|
||||
AWS_REGION=ap-northeast-1
|
||||
AWS_ACCOUNT_ID=200810848252
|
||||
|
||||
VPC_NAME=ppanel-jp-prod
|
||||
VPC_ID=
|
||||
VPC_CIDR=10.20.0.0/16
|
||||
|
||||
PUBLIC_SUBNET_A_NAME=ppanel-jp-public-a
|
||||
PUBLIC_SUBNET_A_AZ=ap-northeast-1a
|
||||
PUBLIC_SUBNET_A_CIDR=10.20.0.0/24
|
||||
|
||||
PUBLIC_SUBNET_C_NAME=ppanel-jp-public-c
|
||||
PUBLIC_SUBNET_C_AZ=ap-northeast-1c
|
||||
PUBLIC_SUBNET_C_CIDR=10.20.1.0/24
|
||||
|
||||
PRIVATE_SUBNET_A_NAME=ppanel-jp-private-a
|
||||
PRIVATE_SUBNET_A_AZ=ap-northeast-1a
|
||||
PRIVATE_SUBNET_A_CIDR=10.20.10.0/24
|
||||
|
||||
PRIVATE_SUBNET_C_NAME=ppanel-jp-private-c
|
||||
PRIVATE_SUBNET_C_AZ=ap-northeast-1c
|
||||
PRIVATE_SUBNET_C_CIDR=10.20.11.0/24
|
||||
|
||||
IGW_NAME=ppanel-jp-igw
|
||||
PUBLIC_ROUTE_TABLE_NAME=ppanel-jp-public-rt
|
||||
PRIVATE_ROUTE_TABLE_NAME=ppanel-jp-private-rt
|
||||
|
||||
SG_ALB_NAME=ppanel-jp-sg-alb
|
||||
SG_EC2_NAME=ppanel-jp-sg-ec2
|
||||
SG_RDS_NAME=ppanel-jp-sg-rds
|
||||
|
||||
OPS_SSH_CIDR=CHANGE_ME_TO_YOUR_FIXED_PUBLIC_IP_OR_CIDR
|
||||
DR_REPLICA_IP=104.238.220.230/32
|
||||
|
||||
EC2_NAME=ppanel-app-jp-01
|
||||
EC2_AMI_FAMILY=ubuntu-24.04
|
||||
EC2_INSTANCE_TYPE=t4g.large
|
||||
EC2_DISK_GB=80
|
||||
EC2_KEY_PAIR=CHANGE_ME
|
||||
|
||||
RDS_IDENTIFIER=ppanel-mysql-jp
|
||||
RDS_DB_NAME=hifast
|
||||
RDS_ADMIN_USER=admin
|
||||
RDS_INSTANCE_CLASS=db.r7g.xlarge
|
||||
RDS_STORAGE_GB=100
|
||||
|
||||
ALB_NAME=ppanel-alb-jp
|
||||
TARGET_GROUP_NAME=ppanel-tg-jp
|
||||
WAF_NAME=ppanel-waf-jp
|
||||
|
||||
PARALLEL_API_DOMAIN=api-jp.hifast.biz
|
||||
PARALLEL_LOGS_DOMAIN=logs-jp.hifast.biz
|
||||
PRODUCTION_API_DOMAIN=CHANGE_ME
|
||||
|
||||
S3_BACKUP_BUCKET=hifast-prod-backups-200810848252-ap-northeast-1
|
||||
@@ -0,0 +1,19 @@
|
||||
AWS_REGION=ap-northeast-1
|
||||
S3_BUCKET=hifast-prod-backups-200810848252-ap-northeast-1
|
||||
S3_PREFIX=mysql
|
||||
BACKUP_DIR=/var/backups/hifast
|
||||
HOST_TAG=104-standby-for-jp
|
||||
KEEP_LOCAL_DAYS=3
|
||||
CHECK_REPLICA=1
|
||||
|
||||
MYSQL_HOST=127.0.0.1
|
||||
MYSQL_PORT=3306
|
||||
MYSQL_USER=backup_reader
|
||||
MYSQL_PASSWORD=CHANGE_ME
|
||||
MYSQL_SOCKET=
|
||||
MYSQL_DATABASE=hifast
|
||||
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_PORT=6379
|
||||
REDIS_PASSWORD=CHANGE_ME
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
PRIMARY_HOST=ppanel-mysql-jp.<CHANGE_ME>.ap-northeast-1.rds.amazonaws.com
|
||||
PRIMARY_PORT=3306
|
||||
PRIMARY_USER=admin
|
||||
PRIMARY_PASSWORD=CHANGE_ME
|
||||
PRIMARY_DB=hifast
|
||||
|
||||
PRIMARY_REPL_USER=repl
|
||||
PRIMARY_REPL_PASSWORD=CHANGE_ME
|
||||
PRIMARY_REPL_HOST=104.238.220.230
|
||||
PRIMARY_BINLOG_RETENTION_HOURS=24
|
||||
|
||||
REPLICA_HOST=127.0.0.1
|
||||
REPLICA_PORT=3306
|
||||
REPLICA_USER=root
|
||||
REPLICA_PASSWORD=
|
||||
REPLICA_SOCKET=/var/run/mysqld/mysqld.sock
|
||||
REPLICA_DB=hifast
|
||||
REPLICA_SOURCE_SSL=1
|
||||
|
||||
DUMP_FILE=
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
Host: 0.0.0.0
|
||||
Port: 8080
|
||||
Debug: false
|
||||
|
||||
JwtAuth:
|
||||
AccessSecret: CHANGE_ME_TO_A_LONG_RANDOM_SECRET
|
||||
AccessExpire: 604800
|
||||
|
||||
Logger:
|
||||
ServiceName: PPanel
|
||||
Mode: console
|
||||
Encoding: plain
|
||||
TimeFormat: "2006-01-02 15:04:05.000"
|
||||
Path: logs
|
||||
Level: info
|
||||
MaxContentLength: 0
|
||||
Compress: false
|
||||
Stat: true
|
||||
KeepDays: 7
|
||||
StackCooldownMillis: 100
|
||||
MaxBackups: 7
|
||||
MaxSize: 100
|
||||
Rotation: daily
|
||||
FileTimeFormat: "2006-01-02T15:04:05.000Z07:00"
|
||||
|
||||
MySQL:
|
||||
Addr: YOUR_TOKYO_RDS_ENDPOINT:3306
|
||||
Dbname: hifast
|
||||
Username: admin
|
||||
Password: CHANGE_ME_TO_TOKYO_RDS_PASSWORD
|
||||
Config: charset=utf8mb4&parseTime=true&loc=Asia%2FTokyo
|
||||
MaxIdleConns: 10
|
||||
MaxOpenConns: 100
|
||||
SlowThreshold: 1000
|
||||
|
||||
Redis:
|
||||
Host: 127.0.0.1:6379
|
||||
Pass: CHANGE_ME_TO_TOKYO_REDIS_PASSWORD
|
||||
DB: 0
|
||||
PoolSize: 100
|
||||
MinIdleConns: 10
|
||||
MaxRetries: 3
|
||||
PoolTimeout: 4
|
||||
IdleTimeout: 300
|
||||
MaxConnAge: 0
|
||||
DialTimeout: 5
|
||||
ReadTimeout: 3
|
||||
WriteTimeout: 3
|
||||
|
||||
Trace:
|
||||
Name: ppanel-server
|
||||
Endpoint: 127.0.0.1:4317
|
||||
Sampler: 0.1
|
||||
Batcher: otlpgrpc
|
||||
|
||||
Site:
|
||||
Host: api-jp.hifast.biz
|
||||
SiteName: HiFastVPN
|
||||
|
||||
Administrator:
|
||||
Email: admin@example.com
|
||||
Password: CHANGE_ME_TO_STRONG_ADMIN_PASSWORD
|
||||
|
||||
Telegram:
|
||||
Enable: false
|
||||
BotID: 0
|
||||
BotName: ""
|
||||
BotToken: ""
|
||||
GroupChatID: ""
|
||||
EnableNotify: false
|
||||
WebHookDomain: ""
|
||||
|
||||
Kutt:
|
||||
Enable: false
|
||||
ApiURL: ""
|
||||
ApiKey: ""
|
||||
TargetURL: ""
|
||||
Domain: ""
|
||||
|
||||
OpenInstall:
|
||||
Enable: false
|
||||
AppKey: ""
|
||||
ApiKey: ""
|
||||
|
||||
Loki:
|
||||
Enable: true
|
||||
URL: "http://localhost:3100"
|
||||
|
||||
AppSignature:
|
||||
AppSecrets:
|
||||
android-client: CHANGE_ME_ANDROID_SIGNATURE_SECRET
|
||||
ios-client: CHANGE_ME_IOS_SIGNATURE_SECRET
|
||||
web-client: CHANGE_ME_WEB_SIGNATURE_SECRET
|
||||
ValidWindowSeconds: 300
|
||||
SkipPrefixes:
|
||||
- /v1/notify/
|
||||
- /v1/iap/notifications
|
||||
- /v1/telegram/webhook
|
||||
- /v1/subscribe/config
|
||||
|
||||
Signature:
|
||||
EnableSignature: false
|
||||
|
||||
device:
|
||||
enable: true
|
||||
security_secret: CHANGE_ME_DEVICE_SECURITY_SECRET
|
||||
|
||||
Register:
|
||||
EnableTrial: true
|
||||
EnableTrialEmailWhitelist: true
|
||||
TrialEmailDomainWhitelist: "gmail.com,outlook.com,icloud.com,qq.com,163.com"
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
MYSQL_HOST=127.0.0.1
|
||||
MYSQL_PORT=3306
|
||||
MYSQL_USER=root
|
||||
MYSQL_PASSWORD=CHANGE_ME
|
||||
MYSQL_SOCKET=
|
||||
|
||||
REPL_SOURCE_HOST=ppanel-mysql-jp.cpo0keikgh80.ap-northeast-1.rds.amazonaws.com
|
||||
REPL_SOURCE_PORT=3306
|
||||
REPL_SOURCE_USER=repl
|
||||
REPL_SOURCE_PASSWORD=XwWrQGVWtxmXJ3etHmkFvnRSD54MKYer
|
||||
REPL_SOURCE_SSL=1
|
||||
REPL_SOURCE_LOG_FILE=mysql-bin-changelog.000189
|
||||
REPL_SOURCE_LOG_POS=185053
|
||||
REPL_SOURCE_AUTO_POSITION=1
|
||||
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_PORT=6379
|
||||
REDIS_PASSWORD=CHANGE_ME
|
||||
|
||||
REDIS_SOURCE_HOST=3.114.29.208
|
||||
REDIS_SOURCE_PORT=6379
|
||||
REDIS_SOURCE_USER=
|
||||
REDIS_SOURCE_PASSWORD=hifast67yj
|
||||
@@ -0,0 +1,187 @@
|
||||
# Tokyo Resource Inventory
|
||||
|
||||
最后更新:`2026-05-21`
|
||||
|
||||
这个文件记录当前东京迁移的真实实施状态,不是示例。
|
||||
|
||||
## Region
|
||||
|
||||
- AWS account: `hifastvpn (200810848252)`
|
||||
- Region: `ap-northeast-1`
|
||||
|
||||
## Current Status
|
||||
|
||||
- 东京迁移方案已在仓库内落地为执行资产
|
||||
- 东京 VPC 已创建
|
||||
- 东京子网、IGW、路由表已在 AWS 控制台创建并复核
|
||||
- 东京三层安全组已在 AWS 控制台创建并复核
|
||||
- 东京 VPC DNS 开关已开启,可支持公网可访问 RDS
|
||||
- 东京 S3 备份桶已在 AWS 控制台创建并复核
|
||||
- 东京 ACM 证书请求已创建,等待 DNS 验证
|
||||
- 东京 RDS MySQL 已创建完成并可用
|
||||
- 东京业务 EC2 已创建完成并绑定固定 EIP
|
||||
- 因当前本机没有可用 AWS CLI 凭据,云上资源状态仍需在 AWS 控制台或已登录环境中复查
|
||||
|
||||
## Networking
|
||||
|
||||
- VPC
|
||||
- Name: `ppanel-jp-prod`
|
||||
- VPC ID: `vpc-0846b23b4a7d64eac`
|
||||
- CIDR: `10.20.0.0/16`
|
||||
- Status: `created`
|
||||
- Public subnet A
|
||||
- Name: `ppanel-jp-public-a`
|
||||
- AZ: `ap-northeast-1a`
|
||||
- CIDR: `10.20.0.0/24`
|
||||
- Subnet ID: `subnet-091232bdb53e71490`
|
||||
- Status: `created`
|
||||
- Public subnet C
|
||||
- Name: `ppanel-jp-public-c`
|
||||
- AZ: `ap-northeast-1c`
|
||||
- CIDR: `10.20.1.0/24`
|
||||
- Subnet ID: `subnet-01ba0975c525ce8cf`
|
||||
- Status: `created`
|
||||
- Private subnet A
|
||||
- Name: `ppanel-jp-private-a`
|
||||
- AZ: `ap-northeast-1a`
|
||||
- CIDR: `10.20.10.0/24`
|
||||
- Subnet ID: `subnet-0bd13111c02f0edbe`
|
||||
- Status: `created`
|
||||
- Private subnet C
|
||||
- Name: `ppanel-jp-private-c`
|
||||
- AZ: `ap-northeast-1c`
|
||||
- CIDR: `10.20.11.0/24`
|
||||
- Subnet ID: `subnet-0d86c5c756dbc84b2`
|
||||
- Status: `created`
|
||||
- Internet Gateway
|
||||
- Name: `ppanel-jp-igw`
|
||||
- IGW ID: `igw-028041bcbf63b672c`
|
||||
- Status: `created`
|
||||
- Public route table
|
||||
- Name: `ppanel-jp-public-rt`
|
||||
- Route Table ID: `rtb-061b101080e4800e5`
|
||||
- Default route: `0.0.0.0/0 -> igw-028041bcbf63b672c`
|
||||
- Status: `created`
|
||||
- Private route table
|
||||
- Name: `ppanel-jp-private-rt`
|
||||
- Route Table ID: `rtb-0d7a191a515031c45`
|
||||
- Status: `created`
|
||||
|
||||
## Security
|
||||
|
||||
- `sg-alb`
|
||||
- Name: `ppanel-jp-sg-alb`
|
||||
- Security Group ID: `sg-0b3a23c31041a5a5a`
|
||||
- Inbound:
|
||||
- `80/tcp <- 0.0.0.0/0`
|
||||
- `443/tcp <- 0.0.0.0/0`
|
||||
- Status: `created`
|
||||
- `sg-ec2`
|
||||
- Name: `ppanel-jp-sg-ec2`
|
||||
- Security Group ID: `sg-01f2a5a81e7505c91`
|
||||
- Inbound:
|
||||
- `80/tcp <- sg-0b3a23c31041a5a5a`
|
||||
- `22/tcp <- 64.118.144.142/32`
|
||||
- `6379/tcp <- 104.238.220.230/32`
|
||||
- Status: `created`
|
||||
- `sg-rds`
|
||||
- Name: `ppanel-jp-sg-rds`
|
||||
- Security Group ID: `sg-0b71db1e2c18b57c0`
|
||||
- Inbound:
|
||||
- `3306/tcp <- sg-01f2a5a81e7505c91`
|
||||
- `3306/tcp <- 104.238.220.230/32`
|
||||
- Status: `created`
|
||||
|
||||
## Compute / Database / Edge
|
||||
|
||||
- EC2 `ppanel-app-jp-01`:
|
||||
- Instance ID: `i-07839130074cd7ed9`
|
||||
- Type: `c7i.xlarge`
|
||||
- Platform: `Ubuntu 26.04 / Linux`
|
||||
- AZ: `ap-northeast-1c`
|
||||
- VPC: `ppanel-jp-prod (vpc-0846b23b4a7d64eac)`
|
||||
- Subnet: `ppanel-jp-public-c (subnet-01ba0975c525ce8cf)`
|
||||
- Private IP: `10.20.1.168`
|
||||
- Public IP / Elastic IP: `3.114.29.208`
|
||||
- Public DNS: `ec2-3-114-29-208.ap-northeast-1.compute.amazonaws.com`
|
||||
- Security group: `ppanel-jp-sg-ec2 (sg-01f2a5a81e7505c91)`
|
||||
- Key pair: `ppanel-jp-key-20260521`
|
||||
- Root volume: `gp3 100GiB`
|
||||
- ENI: `eni-08accb427a470c9f7`
|
||||
- EIP allocation ID: `eipalloc-038b32d5c0119accf`
|
||||
- EIP association ID: `eipassoc-09184aa9161b6a4d9`
|
||||
- Status: `running`
|
||||
- SSH recovery private key: `deploy/aws/ap-northeast-1/keys/ppanel-jp-recovery`
|
||||
- SSH recovery public key: `deploy/aws/ap-northeast-1/keys/ppanel-jp-recovery.pub`
|
||||
- RDS subnet group:
|
||||
- Name: `ppanel-jp-rds-subnet-group`
|
||||
- VPC: `vpc-0846b23b4a7d64eac`
|
||||
- Subnets:
|
||||
- `subnet-0bd13111c02f0edbe` / `ppanel-jp-private-a`
|
||||
- `subnet-0d86c5c756dbc84b2` / `ppanel-jp-private-c`
|
||||
- Status: `created`
|
||||
- RDS public subnet group:
|
||||
- Name: `ppanel-jp-rds-public-subnet-group`
|
||||
- VPC: `vpc-0846b23b4a7d64eac`
|
||||
- Subnets:
|
||||
- `subnet-091232bdb53e71490` / `ppanel-jp-public-a`
|
||||
- `subnet-01ba0975c525ce8cf` / `ppanel-jp-public-c`
|
||||
- Status: `created`
|
||||
- RDS `ppanel-mysql-jp`:
|
||||
- Engine: `MySQL Community 8.4.8`
|
||||
- Class: `db.r7g.xlarge`
|
||||
- Storage: `gp3 100GiB`
|
||||
- Deployment: `Single instance (current actual state)`
|
||||
- VPC: `ppanel-jp-prod (vpc-0846b23b4a7d64eac)`
|
||||
- Subnet group: `ppanel-jp-rds-public-subnet-group`
|
||||
- Security group: `ppanel-jp-sg-rds (sg-0b71db1e2c18b57c0)`
|
||||
- Master username: `admin`
|
||||
- Credential management: `self-managed`
|
||||
- Secrets Manager managed password: `disabled`
|
||||
- Current master password visibility: `not retrievable from AWS console; reset only`
|
||||
- Public access: `enabled (set at creation time for external replication)`
|
||||
- Status: `available`
|
||||
- Endpoint: `ppanel-mysql-jp.cpo0keikgh80.ap-northeast-1.rds.amazonaws.com`
|
||||
- Public IP (resolved via public DNS): `52.196.204.186`
|
||||
- Connection test from Tokyo EC2:
|
||||
- `mysql -h ppanel-mysql-jp.cpo0keikgh80.ap-northeast-1.rds.amazonaws.com -u admin -e "select 1"`
|
||||
- Result: `ERROR 1045 (28000): Access denied for user 'admin'@'ip-10-20-1-168.ap-northeast-1.compute.internal' (using password: NO)`
|
||||
- Meaning: `network path and security group are working; only the password is missing`
|
||||
- Current admin password: `TkyRds20260521!N9mQ8sKe2vLp7Xa`
|
||||
- External replica prep for `104.238.220.230`:
|
||||
- binlog retention hours: `24`
|
||||
- replication user: `repl@104.238.220.230`
|
||||
- replication password: `XwWrQGVWtxmXJ3etHmkFvnRSD54MKYer`
|
||||
- current binlog file: `mysql-bin-changelog.000189`
|
||||
- current binlog position: `185053`
|
||||
- ALB `ppanel-alb-jp`: `not created`
|
||||
- WAF `ppanel-waf-jp`: `not created`
|
||||
- ACM certificate in `ap-northeast-1`:
|
||||
- Certificate ID: `29d0b9b6-ab37-44d9-ad9e-18fa7e9aae3a`
|
||||
- Domains:
|
||||
- `api-jp.hifast.biz`
|
||||
- `logs-jp.hifast.biz`
|
||||
- Status: `pending_validation`
|
||||
- Route 53 hosted zone in current AWS account: `not found`
|
||||
- S3 backup bucket `hifast-prod-backups-200810848252-ap-northeast-1`: `created`
|
||||
|
||||
## Domains
|
||||
|
||||
- Parallel API domain: `api-jp.hifast.biz`
|
||||
- Parallel logs domain: `logs-jp.hifast.biz`
|
||||
- Production API domain: `pending user final confirmation`
|
||||
- ACM DNS validation records pending external DNS add:
|
||||
- `api-jp.hifast.biz`
|
||||
- Name: `_0de5970dfbadaf46759447b2ea627a10.api-jp.hifast.biz.`
|
||||
- Type: `CNAME`
|
||||
- Value: `_6a632a5b85c5b3f304cc492090b741b3.jkddzztszm.acm-validations.aws.`
|
||||
- `logs-jp.hifast.biz`
|
||||
- Name: `_349a2b2bc4678d76c3ab341ccf73db61.logs-jp.hifast.biz.`
|
||||
- Type: `CNAME`
|
||||
- Value: `_74ced20dc96aa39070188605cf0ced18.jkddzztszm.acm-validations.aws.`
|
||||
|
||||
## DR
|
||||
|
||||
- DR host: `104.238.220.230`
|
||||
- Planned MySQL upstream after cutover: `Tokyo RDS`
|
||||
- Planned Redis upstream after cutover: `Tokyo EC2 public IP`
|
||||
@@ -0,0 +1,69 @@
|
||||
# Tokyo Resource Inventory Example
|
||||
|
||||
Use this file as the single source of truth while building the Tokyo environment.
|
||||
|
||||
## Region
|
||||
|
||||
- AWS account: `hifastvpn (200810848252)`
|
||||
- Region: `ap-northeast-1`
|
||||
|
||||
## DNS
|
||||
|
||||
- Production API domain: `CHANGE_ME`
|
||||
- Parallel API domain: `api-jp.hifast.biz`
|
||||
- Parallel logs domain: `logs-jp.hifast.biz`
|
||||
|
||||
## Networking
|
||||
|
||||
- VPC name: `ppanel-jp-prod`
|
||||
- VPC CIDR: `10.20.0.0/16`
|
||||
- Public subnet A: `10.20.0.0/24`
|
||||
- Public subnet C: `10.20.1.0/24`
|
||||
- Private subnet A: `10.20.10.0/24`
|
||||
- Private subnet C: `10.20.11.0/24`
|
||||
- Ops CIDR for SSH: `CHANGE_ME`
|
||||
|
||||
## Compute
|
||||
|
||||
- EC2 name: `ppanel-app-jp-01`
|
||||
- EC2 type: `t4g.large`
|
||||
- EC2 disk: `gp3 80GB`
|
||||
- SSH key pair: `CHANGE_ME`
|
||||
|
||||
## Database
|
||||
|
||||
- RDS identifier: `ppanel-mysql-jp`
|
||||
- RDS engine: `MySQL 8.4`
|
||||
- RDS class: `db.r7g.xlarge`
|
||||
- RDS storage: `gp3 100GB`
|
||||
- DB name: `hifast`
|
||||
- DB admin user: `admin`
|
||||
|
||||
## Cache
|
||||
|
||||
- Redis container: `hifast-redis`
|
||||
- Redis port: `6379`
|
||||
- Redis password: `CHANGE_ME`
|
||||
|
||||
## Security / Secrets
|
||||
|
||||
- JWT secret: `CHANGE_ME`
|
||||
- Admin email: `CHANGE_ME`
|
||||
- Admin password: `CHANGE_ME`
|
||||
- Android app signature secret: `CHANGE_ME`
|
||||
- iOS app signature secret: `CHANGE_ME`
|
||||
- Web app signature secret: `CHANGE_ME`
|
||||
- Device security secret: `CHANGE_ME`
|
||||
|
||||
## Backup
|
||||
|
||||
- S3 backup bucket: `hifast-prod-backups-200810848252-ap-northeast-1`
|
||||
- Versioning: `Enabled`
|
||||
|
||||
## DR
|
||||
|
||||
- DR host: `104.238.220.230`
|
||||
- MySQL repl user: `repl`
|
||||
- MySQL repl password: `CHANGE_ME`
|
||||
- Redis source password: `CHANGE_ME`
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACBsJxZDjKvaIdVjer3QMHRYw43wkVnzHurA2TQqHlr1YwAAAKBaQXT3WkF0
|
||||
9wAAAAtzc2gtZWQyNTUxOQAAACBsJxZDjKvaIdVjer3QMHRYw43wkVnzHurA2TQqHlr1Yw
|
||||
AAAEArWQWWwPoJp+za5JhSnrE0Pw1/TtqWRrdY5e8hULqYDGwnFkOMq9oh1WN6vdAwdFjD
|
||||
jfCRWfMe6sDZNCoeWvVjAAAAF0FwcGxlQE1hY0Jvb2stUHJvLmxvY2FsAQIDBAUG
|
||||
-----END OPENSSH PRIVATE KEY-----
|
||||
@@ -0,0 +1 @@
|
||||
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGwnFkOMq9oh1WN6vdAwdFjDjfCRWfMe6sDZNCoeWvVj Apple@MacBook-Pro.local
|
||||
@@ -0,0 +1,34 @@
|
||||
server {
|
||||
listen 80 default_server;
|
||||
listen [::]:80 default_server;
|
||||
server_name _;
|
||||
|
||||
client_max_body_size 20m;
|
||||
|
||||
access_log /var/log/nginx/ppanel-access.log;
|
||||
error_log /var/log/nginx/ppanel-error.log warn;
|
||||
|
||||
location / {
|
||||
proxy_http_version 1.1;
|
||||
proxy_pass http://127.0.0.1:8080;
|
||||
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header X-Forwarded-Port $server_port;
|
||||
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_send_timeout 60s;
|
||||
proxy_read_timeout 60s;
|
||||
}
|
||||
|
||||
location = /nginx_status {
|
||||
stub_status;
|
||||
access_log off;
|
||||
allow 127.0.0.1;
|
||||
deny all;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
[Unit]
|
||||
Description=Hifast MySQL backup to S3
|
||||
Wants=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=root
|
||||
Group=root
|
||||
EnvironmentFile=/root/backup-to-s3.env
|
||||
ExecStart=/usr/bin/env bash -lc 'exec /opt/ppanel/deploy/scripts/mysql_backup_to_s3.sh'
|
||||
Nice=10
|
||||
IOSchedulingClass=best-effort
|
||||
IOSchedulingPriority=7
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=Run Hifast MySQL backup to S3 every 10 minutes
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*:0/10
|
||||
Persistent=true
|
||||
RandomizedDelaySec=30
|
||||
Unit=hifast-mysql-backup.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,560 @@
|
||||
# 提现 & 文件上传 & 日志上报 — 用户端 API 接口文档
|
||||
|
||||
> 基于 ppanel-server 源码整理,所有时间戳均为**秒级 Unix**。
|
||||
|
||||
---
|
||||
|
||||
## 目录
|
||||
|
||||
- [一、提现接口](#一提现接口)
|
||||
- [1.1 申请提现](#11-申请提现)
|
||||
- [1.2 取消提现](#12-取消提现)
|
||||
- [1.3 查询提现记录](#13-查询提现记录)
|
||||
- [二、枚举值与状态流转](#二枚举值与状态流转)
|
||||
- [三、文件上传接口](#三文件上传接口)
|
||||
- [3.1 直传文件(小文件)](#31-直传文件小文件)
|
||||
- [3.2 初始化上传(大文件 — 预签名)](#32-初始化上传大文件--预签名)
|
||||
- [3.3 确认上传完成](#33-确认上传完成)
|
||||
- [四、日志查询接口 (Admin)](#四日志查询接口-admin)
|
||||
- [4.1 错误日志列表](#41-错误日志列表)
|
||||
- [4.2 错误日志详情](#42-错误日志详情)
|
||||
- [4.3 日志消息原始详情](#43-日志消息原始详情)
|
||||
|
||||
---
|
||||
|
||||
## 一、提现接口
|
||||
|
||||
> 认证方式: JWT(用户登录态)
|
||||
>
|
||||
> 路由前缀: `/v1/public/user`
|
||||
|
||||
### 1.1 申请提现
|
||||
|
||||
提交佣金提现申请,创建一条待审核的提现记录。
|
||||
|
||||
```
|
||||
POST /v1/public/user/commission_withdraw
|
||||
```
|
||||
|
||||
**Request Body**
|
||||
|
||||
| 字段 | 类型 | 必填 | 校验 | 说明 |
|
||||
|------|------|------|------|------|
|
||||
| `amount` | int64 | 是 | — | 提现金额(分) |
|
||||
| `method` | uint8 | 是 | `oneof=0 1 2 3` | 收款方式(见枚举表) |
|
||||
| `content` | string | 否 | — | 提现备注 |
|
||||
| `account` | string | 条件必填 | — | 收款账号 |
|
||||
| `qr_code_url` | string | 条件必填 | — | 收款码图片 URL |
|
||||
|
||||
**各收款方式的必填字段**
|
||||
|
||||
| method | 收款方式 | 必填字段 |
|
||||
|--------|---------|---------|
|
||||
| `1` 支付宝 | `qr_code_url` | 收款码图片 |
|
||||
| `2` 微信 | `qr_code_url` | 收款码图片 |
|
||||
| `3` 银行卡 | `account` | 收款账号 |
|
||||
| `0` 其他 | `account` 必填 |
|
||||
|
||||
**Request 示例**
|
||||
|
||||
```json
|
||||
{
|
||||
"amount": 5000,
|
||||
"content": "提现到支付宝",
|
||||
"method": 1,
|
||||
"account": "user@example.com",
|
||||
"qr_code_url": "https://cdn.example.com/qrcode/alipay.png"
|
||||
}
|
||||
```
|
||||
|
||||
**Response**: [`WithdrawalLog`](#withdrawallog-对象)
|
||||
|
||||
---
|
||||
|
||||
### 1.2 取消提现
|
||||
|
||||
用户取消自己的待审核提现申请,佣金退回账户。
|
||||
|
||||
```
|
||||
POST /v1/public/user/withdrawal_cancel
|
||||
```
|
||||
|
||||
**Request Body**
|
||||
|
||||
| 字段 | 类型 | 必填 | 校验 | 说明 |
|
||||
|------|------|------|------|------|
|
||||
| `withdrawal_id` | int64 | 是 | `required,gt=0` | 提现记录 ID |
|
||||
|
||||
**Request 示例**
|
||||
|
||||
```json
|
||||
{
|
||||
"withdrawal_id": 123
|
||||
}
|
||||
```
|
||||
|
||||
**Response**: [`WithdrawalLog`](#withdrawallog-对象)(状态已变为 `3=已取消`)
|
||||
|
||||
---
|
||||
|
||||
### 1.3 查询提现记录
|
||||
|
||||
分页查询当前用户的提现记录(自动按 JWT 中的 userId 过滤)。
|
||||
|
||||
```
|
||||
GET /v1/public/user/withdrawal_log
|
||||
```
|
||||
|
||||
**Query 参数**
|
||||
|
||||
| 参数 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `page` | int | 否 | 页码,默认 1 |
|
||||
| `size` | int | 否 | 每页条数,默认 10 |
|
||||
|
||||
**Request 示例**
|
||||
|
||||
```
|
||||
GET /v1/public/user/withdrawal_log?page=1&size=10
|
||||
```
|
||||
|
||||
**Response**
|
||||
|
||||
```json
|
||||
{
|
||||
"list": [WithdrawalLog, ...],
|
||||
"total": 25
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 二、枚举值与状态流转
|
||||
|
||||
### 提现状态 (`status`)
|
||||
|
||||
| 值 | 说明 |
|
||||
|----|------|
|
||||
| 0 | 待审核 |
|
||||
| 1 | 已通过 |
|
||||
| 2 | 已拒绝 |
|
||||
| 3 | 已取消 |
|
||||
|
||||
### 收款方式 (`method`)
|
||||
|
||||
| 值 | 说明 |
|
||||
|----|------|
|
||||
| 0 | 其他 |
|
||||
| 1 | 支付宝 |
|
||||
| 2 | 微信 |
|
||||
| 3 | 银行卡 |
|
||||
|
||||
### 状态流转
|
||||
|
||||
```
|
||||
┌── 管理员通过 ──▶ 已通过 (1)
|
||||
│
|
||||
待审核 (0) ──────┼── 管理员拒绝 ──▶ 已拒绝 (2)
|
||||
│
|
||||
└── 用户取消 ───▶ 已取消 (3)
|
||||
```
|
||||
|
||||
### WithdrawalLog 对象
|
||||
|
||||
所有提现接口共用的响应结构:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"user_id": 100,
|
||||
"amount": 5000,
|
||||
"content": "提现备注",
|
||||
"status": 0,
|
||||
"reason": "",
|
||||
"method": 1,
|
||||
"account": "user@example.com",
|
||||
"qr_code_url": "https://cdn.example.com/qrcode/alipay.png",
|
||||
"created_at": 1716700000,
|
||||
"updated_at": 1716700000
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `id` | int64 | 提现记录 ID |
|
||||
| `user_id` | int64 | 用户 ID |
|
||||
| `amount` | int64 | 提现金额(分) |
|
||||
| `content` | string | 提现备注 |
|
||||
| `status` | uint8 | 状态(见枚举表) |
|
||||
| `reason` | string | 拒绝原因(仅 status=2 时有值,其余 omitempty) |
|
||||
| `method` | uint8 | 收款方式(见枚举表) |
|
||||
| `account` | string | 收款账号 |
|
||||
| `qr_code_url` | string | 收款码图片 URL |
|
||||
| `created_at` | int64 | 创建时间(秒级 Unix) |
|
||||
| `updated_at` | int64 | 更新时间(秒级 Unix) |
|
||||
|
||||
---
|
||||
|
||||
## 三、文件上传接口
|
||||
|
||||
> 认证方式: JWT + DeviceMiddleware(用户登录态 + 设备认证)
|
||||
>
|
||||
> 路由前缀: `/v1/public/file`
|
||||
>
|
||||
> 存储后端: S3 兼容(RustFS)
|
||||
|
||||
提供两种上传方式:
|
||||
|
||||
| 方式 | 适用场景 | 流程 |
|
||||
|------|---------|------|
|
||||
| **直传** | 小文件(收款码等) | 1 次请求,`multipart/form-data` 直接上传 |
|
||||
| **预签名** | 大文件 / 客户端直传 S3 | init → 客户端 PUT 到预签名 URL → complete 确认 |
|
||||
|
||||
---
|
||||
|
||||
### 3.1 直传文件(小文件)
|
||||
|
||||
通过 `multipart/form-data` 直接上传文件到服务端,服务端转存至 S3。
|
||||
|
||||
```
|
||||
POST /v1/public/file/upload
|
||||
Content-Type: multipart/form-data
|
||||
```
|
||||
|
||||
**Form 参数**
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `biz_type` | string | 是 | 业务类型(如 `withdrawal_qrcode`、`avatar` 等) |
|
||||
| `file` | file | 是 | 上传的文件(multipart) |
|
||||
|
||||
**cURL 示例**
|
||||
|
||||
```bash
|
||||
curl -X POST /v1/public/file/upload \
|
||||
-H "Authorization: Bearer <token>" \
|
||||
-F "biz_type=withdrawal_qrcode" \
|
||||
-F "file=@/path/to/alipay_qr.png"
|
||||
```
|
||||
|
||||
**Response**
|
||||
|
||||
```json
|
||||
{
|
||||
"file_id": "a1b2c3d4e5f678901234",
|
||||
"file_name": "alipay_qr.png",
|
||||
"object_key": "app-upload/2026/05/27/100/alipay_qr.png__a1b2c3d4e5f678901234",
|
||||
"size": 52480,
|
||||
"content_type": "image/png",
|
||||
"etag": "\"d41d8cd98f00b204e9800998ecf8427e\"",
|
||||
"status": "completed"
|
||||
}
|
||||
```
|
||||
|
||||
**FileUploadResponse 字段说明**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `file_id` | string | 文件唯一 ID(24 字符 hex) |
|
||||
| `file_name` | string | 原始文件名 |
|
||||
| `object_key` | string | S3 对象路径 |
|
||||
| `size` | int64 | 文件大小(字节) |
|
||||
| `content_type` | string | MIME 类型 |
|
||||
| `etag` | string | S3 ETag |
|
||||
| `status` | string | 状态,直传成功即 `completed` |
|
||||
|
||||
---
|
||||
|
||||
### 3.2 初始化上传(大文件 — 预签名)
|
||||
|
||||
获取 S3 预签名 URL,客户端直接 PUT 到 S3,避免文件经过服务端。
|
||||
|
||||
```
|
||||
POST /v1/public/file/upload/init
|
||||
```
|
||||
|
||||
**Request Body**
|
||||
|
||||
| 字段 | 类型 | 必填 | 校验 | 说明 |
|
||||
|------|------|------|------|------|
|
||||
| `biz_type` | string | 是 | `required` | 业务类型 |
|
||||
| `file_name` | string | 是 | `required` | 文件名 |
|
||||
| `content_type` | string | 是 | `required` | MIME 类型(如 `image/png`) |
|
||||
| `size` | int64 | 是 | `required` | 文件大小(字节) |
|
||||
| `sha256` | string | 否 | — | 文件 SHA256(可选校验) |
|
||||
|
||||
**Request 示例**
|
||||
|
||||
```json
|
||||
{
|
||||
"biz_type": "withdrawal_qrcode",
|
||||
"file_name": "wechat_qr.png",
|
||||
"content_type": "image/png",
|
||||
"size": 102400,
|
||||
"sha256": "e3b0c44298fc1c149afbf4c8996fb924..."
|
||||
}
|
||||
```
|
||||
|
||||
**Response**
|
||||
|
||||
```json
|
||||
{
|
||||
"file_id": "b2c3d4e5f6789012345a",
|
||||
"object_key": "app-upload/2026/05/27/100/wechat_qr.png__b2c3d4e5f6789012345a",
|
||||
"upload_url": "https://s3.example.com/bucket/app-upload/...?X-Amz-Signature=...",
|
||||
"method": "PUT",
|
||||
"headers": {
|
||||
"Content-Type": "image/png"
|
||||
},
|
||||
"expired_at": 1716700300
|
||||
}
|
||||
```
|
||||
|
||||
**FileUploadInitResponse 字段说明**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `file_id` | string | 文件唯一 ID |
|
||||
| `object_key` | string | S3 对象路径 |
|
||||
| `upload_url` | string | 预签名上传 URL |
|
||||
| `method` | string | HTTP 方法(`PUT`) |
|
||||
| `headers` | map | 上传时需携带的请求头 |
|
||||
| `expired_at` | int64 | 预签名过期时间(秒级 Unix,默认 300 秒) |
|
||||
|
||||
**客户端上传流程**
|
||||
|
||||
```
|
||||
1. 调用 /upload/init 获取 upload_url
|
||||
2. 用返回的 method + headers 直接上传文件到 upload_url
|
||||
3. 上传成功后调用 /upload/complete 确认
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3.3 确认上传完成
|
||||
|
||||
客户端通过预签名 URL 上传完成后,调用此接口确认文件状态。
|
||||
|
||||
```
|
||||
POST /v1/public/file/upload/complete
|
||||
```
|
||||
|
||||
**Request Body**
|
||||
|
||||
| 字段 | 类型 | 必填 | 校验 | 说明 |
|
||||
|------|------|------|------|------|
|
||||
| `file_id` | string | 是 | `required` | init 返回的 file_id |
|
||||
|
||||
**Request 示例**
|
||||
|
||||
```json
|
||||
{
|
||||
"file_id": "b2c3d4e5f6789012345a"
|
||||
}
|
||||
```
|
||||
|
||||
**Response**
|
||||
|
||||
```json
|
||||
{
|
||||
"file_id": "b2c3d4e5f6789012345a",
|
||||
"object_key": "app-upload/2026/05/27/100/wechat_qr.png__b2c3d4e5f6789012345a",
|
||||
"size": 102400,
|
||||
"content_type": "image/png",
|
||||
"etag": "\"d41d8cd98f00b204e9800998ecf8427e\"",
|
||||
"status": "completed"
|
||||
}
|
||||
```
|
||||
|
||||
**FileUploadCompleteResponse 字段说明**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `file_id` | string | 文件唯一 ID |
|
||||
| `object_key` | string | S3 对象路径 |
|
||||
| `size` | int64 | 实际文件大小(S3 HeadObject 获取) |
|
||||
| `content_type` | string | MIME 类型 |
|
||||
| `etag` | string | S3 ETag |
|
||||
| `status` | string | `completed` |
|
||||
|
||||
**校验规则**
|
||||
|
||||
- 文件大小不能超过配置的 `S3.MaxUploadSize`
|
||||
- Content-Type 必须在配置的 `S3.AllowedContentTypes` 白名单内(若配置了)
|
||||
- complete 时会校验 S3 上的实际文件大小是否与 init 声明的一致
|
||||
- 只能确认自己发起的上传(userId 校验)
|
||||
|
||||
---
|
||||
|
||||
## 四、日志查询接口 (Admin)
|
||||
|
||||
> 认证方式: AuthMiddleware(管理员权限)
|
||||
>
|
||||
> 路由前缀: `/v1/admin/log`
|
||||
>
|
||||
> 数据来源: `log_message` 表(客户端上报的错误/崩溃日志)
|
||||
|
||||
---
|
||||
|
||||
### 4.1 错误日志列表
|
||||
|
||||
分页查询客户端上报的错误日志,支持多维度筛选。
|
||||
|
||||
```
|
||||
GET /v1/admin/log/error_message/list
|
||||
```
|
||||
|
||||
**Query 参数**
|
||||
|
||||
| 参数 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `page` | int | 是 | 页码 |
|
||||
| `size` | int | 是 | 每页条数 |
|
||||
| `platform` | string | 否 | 平台筛选(ios / android / windows / mac / harmony) |
|
||||
| `level` | uint8 | 否 | 日志级别 |
|
||||
| `user_id` | int64 | 否 | 用户 ID |
|
||||
| `device_id` | string | 否 | 设备 ID |
|
||||
| `error_code` | string | 否 | 错误码 |
|
||||
| `keyword` | string | 否 | 关键字搜索(匹配 message) |
|
||||
| `start` | int64 | 否 | 开始时间(秒级 Unix) |
|
||||
| `end` | int64 | 否 | 结束时间(秒级 Unix) |
|
||||
|
||||
**Request 示例**
|
||||
|
||||
```
|
||||
GET /v1/admin/log/error_message/list?page=1&size=20&platform=ios&start=1716600000&end=1716700000
|
||||
```
|
||||
|
||||
**Response**
|
||||
|
||||
```json
|
||||
{
|
||||
"total": 50,
|
||||
"list": [
|
||||
{
|
||||
"id": 1,
|
||||
"platform": "ios",
|
||||
"app_version": "2.1.0",
|
||||
"os_name": "iOS",
|
||||
"os_version": "17.5",
|
||||
"device_id": "A1B2C3D4",
|
||||
"user_id": 100,
|
||||
"session_id": "sess_xxx",
|
||||
"level": 3,
|
||||
"error_code": "VPN_CONNECT_FAIL",
|
||||
"message": "Failed to establish VPN tunnel",
|
||||
"created_at": 1716700000
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**ErrorLogMessage 字段说明**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `id` | int64 | 日志 ID |
|
||||
| `platform` | string | 平台 |
|
||||
| `app_version` | string | 客户端版本 |
|
||||
| `os_name` | string | 操作系统名称 |
|
||||
| `os_version` | string | 操作系统版本 |
|
||||
| `device_id` | string | 设备 ID |
|
||||
| `user_id` | int64 | 用户 ID |
|
||||
| `session_id` | string | 会话 ID |
|
||||
| `level` | uint8 | 日志级别 |
|
||||
| `error_code` | string | 错误码 |
|
||||
| `message` | string | 错误消息 |
|
||||
| `created_at` | int64 | 创建时间(秒级 Unix) |
|
||||
|
||||
---
|
||||
|
||||
### 4.2 错误日志详情
|
||||
|
||||
获取单条错误日志的完整详情(列表字段 + 堆栈/IP/UA 等扩展信息)。
|
||||
|
||||
```
|
||||
GET /v1/admin/log/error_message/detail
|
||||
```
|
||||
|
||||
**Response**
|
||||
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"platform": "ios",
|
||||
"app_version": "2.1.0",
|
||||
"os_name": "iOS",
|
||||
"os_version": "17.5",
|
||||
"device_id": "A1B2C3D4",
|
||||
"user_id": 100,
|
||||
"session_id": "sess_xxx",
|
||||
"level": 3,
|
||||
"error_code": "VPN_CONNECT_FAIL",
|
||||
"message": "Failed to establish VPN tunnel",
|
||||
"stack": "at VPNManager.connect() line 42\nat ...",
|
||||
"client_ip": "1.2.3.4",
|
||||
"user_agent": "PPanel/2.1.0 iOS/17.5",
|
||||
"locale": "zh-CN",
|
||||
"occurred_at": 1716700000,
|
||||
"created_at": 1716700000
|
||||
}
|
||||
```
|
||||
|
||||
**相比列表额外返回的字段**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `stack` | string | 堆栈信息 |
|
||||
| `client_ip` | string | 客户端 IP |
|
||||
| `user_agent` | string | User-Agent |
|
||||
| `locale` | string | 客户端语言/地区 |
|
||||
| `occurred_at` | int64 | 错误发生时间(秒级 Unix) |
|
||||
|
||||
---
|
||||
|
||||
### 4.3 日志消息原始详情
|
||||
|
||||
获取单条 `log_message` 的完整原始数据(含 context、digest 等全量字段)。
|
||||
|
||||
```
|
||||
GET /v1/admin/log/message/detail
|
||||
```
|
||||
|
||||
**Query 参数**
|
||||
|
||||
| 参数 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `id` | int64 | 是 | 日志消息 ID |
|
||||
|
||||
**Response**
|
||||
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"platform": "ios",
|
||||
"app_version": "2.1.0",
|
||||
"os_name": "iOS",
|
||||
"os_version": "17.5",
|
||||
"device_id": "A1B2C3D4",
|
||||
"user_id": 100,
|
||||
"session_id": "sess_xxx",
|
||||
"level": 3,
|
||||
"error_code": "VPN_CONNECT_FAIL",
|
||||
"message": "Failed to establish VPN tunnel",
|
||||
"stack": "at VPNManager.connect() line 42\nat ...",
|
||||
"context": { "server_id": 5, "protocol": "vmess" },
|
||||
"client_ip": "1.2.3.4",
|
||||
"user_agent": "PPanel/2.1.0 iOS/17.5",
|
||||
"locale": "zh-CN",
|
||||
"digest": "sha256_abc123...",
|
||||
"occurred_at": 1716700000,
|
||||
"created_at": 1716700000
|
||||
}
|
||||
```
|
||||
|
||||
**相比详情额外返回的字段**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `context` | any | 附加上下文(原始 JSON) |
|
||||
| `digest` | string | 内容摘要(用于去重) |
|
||||
@@ -128,6 +128,10 @@ curl -X PUT 'https://bucket.s3.ap-east-1.amazonaws.com/...' \
|
||||
说明:
|
||||
|
||||
- `Content-Type` 需和 `init` 返回的 `headers.Content-Type` 一致
|
||||
- 允许的 `Content-Type` 由服务端 `S3.AllowedContentTypes` 配置控制,默认包含:
|
||||
- 压缩包:`application/zip`、`application/x-zip-compressed`、`application/gzip`、`application/x-gzip`
|
||||
- 通用文件:`application/octet-stream`、`text/plain`、`application/json`
|
||||
- 图片:`image/jpeg`、`image/jpg`、`image/png`、`image/webp`、`image/gif`、`image/heic`、`image/heif`、`image/bmp`
|
||||
- `upload_url` 有过期时间,通常 300 秒
|
||||
- 成功时 S3 常见返回 `200` 或 `204`
|
||||
|
||||
@@ -164,11 +168,13 @@ curl -X POST 'https://tapi.hifast.biz/v1/public/file/upload/complete' \
|
||||
- 如果请求带了 `X-App-Id`,就按现有逻辑验签
|
||||
- 如果没有 `X-App-Id`,仍按旧逻辑放行
|
||||
- 如果要给该接口加签,签名时必须对原始 multipart body 计算 `BODY_SHA256`
|
||||
- 允许的 `Content-Type` 与预签名三段式一致;multipart 文件字段未显式携带 `Content-Type` 时,服务端会基于文件内容嗅探常见类型。
|
||||
|
||||
## 常见错误码
|
||||
|
||||
- `200`: 成功
|
||||
- `400`: 参数错误
|
||||
- `400 content_type is not allowed`: 文件 `Content-Type` 不在 `S3.AllowedContentTypes` 白名单内
|
||||
- `40008`: 缺少签名头
|
||||
- `40009`: 签名已过期
|
||||
- `40010`: 签名无效
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
# 提现接口文档
|
||||
|
||||
## 基础信息
|
||||
|
||||
| 项目 | 值 |
|
||||
|------|-----|
|
||||
| Base URL | `/v1/public/user` |
|
||||
| 认证方式 | JWT Token(`AuthMiddleware` + `DeviceMiddleware`) |
|
||||
| 数据表 | `user_withdrawal` |
|
||||
|
||||
## 数据模型
|
||||
|
||||
### user_withdrawal 表
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| `id` | int64 | 主键 |
|
||||
| `user_id` | int64 | 用户 ID |
|
||||
| `amount` | int64 | 提现金额(单位:分) |
|
||||
| `content` | text | 收款信息(账号、姓名等) |
|
||||
| `status` | tinyint | 0=待审核, 1=已通过, 2=已拒绝 |
|
||||
| `reason` | varchar(500) | 拒绝原因(通过时为空) |
|
||||
| `created_at` | datetime | 创建时间 |
|
||||
| `updated_at` | datetime | 更新时间 |
|
||||
|
||||
### status 枚举
|
||||
|
||||
| 值 | 含义 | 说明 |
|
||||
|----|------|------|
|
||||
| 0 | Pending(待审核) | 用户提交申请后的初始状态 |
|
||||
| 1 | Approved(已通过) | 管理员审核通过,佣金已扣减 |
|
||||
| 2 | Rejected(已拒绝) | 管理员拒绝,无需退款(申请时未扣款) |
|
||||
|
||||
---
|
||||
|
||||
## 用户端接口
|
||||
|
||||
### 1. 申请提现
|
||||
|
||||
申请佣金提现,创建一条待审核记录。申请时**不扣余额**,管理员审核通过后才扣。
|
||||
|
||||
```
|
||||
POST /v1/public/user/commission_withdraw
|
||||
```
|
||||
|
||||
#### 请求体
|
||||
|
||||
```json
|
||||
{
|
||||
"amount": 1000,
|
||||
"content": "支付宝:138xxxx1234 / 张三"
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `amount` | int64 | 是 | 提现金额(单位:分) |
|
||||
| `content` | string | 是 | 收款信息(支付宝/银行卡等) |
|
||||
|
||||
#### 成功响应
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": 1,
|
||||
"user_id": 10001,
|
||||
"amount": 1000,
|
||||
"content": "支付宝:138xxxx1234 / 张三",
|
||||
"status": 0,
|
||||
"reason": "",
|
||||
"created_at": 1716624000000,
|
||||
"updated_at": 1716624000000
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> **注意**:此接口的 `created_at` / `updated_at` 返回**毫秒级**时间戳(`.UnixMilli()`),与项目其他接口的秒级时间戳不一致。
|
||||
|
||||
#### 业务逻辑
|
||||
|
||||
1. 查询该用户所有 status=0(待审核)的提现记录,求和得 `pendingTotal`
|
||||
2. 校验可用余额:`commission >= amount + pendingTotal`
|
||||
3. 创建 `user_withdrawal` 记录,status=0
|
||||
4. **不扣减** `user.commission`,等审核通过才扣
|
||||
|
||||
#### 错误码
|
||||
|
||||
| 错误码 | 常量 | 说明 |
|
||||
|--------|------|------|
|
||||
| 20010 | `UserCommissionNotEnough` | 可用余额不足(余额 = commission - 所有 pending 提现总额) |
|
||||
| 40005 | `InvalidAccess` | 未登录 / Token 无效 |
|
||||
|
||||
#### 源码位置
|
||||
|
||||
- Handler: `internal/handler/public/user/commissionWithdrawHandler.go`
|
||||
- Logic: `internal/logic/public/user/commissionWithdrawLogic.go`
|
||||
|
||||
---
|
||||
|
||||
### 2. 查询提现记录
|
||||
|
||||
分页查询当前用户的提现记录。
|
||||
|
||||
```
|
||||
GET /v1/public/user/withdrawal_log
|
||||
```
|
||||
|
||||
#### 请求参数(Query)
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `page` | int | 否 | 页码 |
|
||||
| `size` | int | 否 | 每页数量 |
|
||||
|
||||
#### 成功响应
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"list": [
|
||||
{
|
||||
"id": 1,
|
||||
"user_id": 10001,
|
||||
"amount": 1000,
|
||||
"content": "支付宝:138xxxx1234",
|
||||
"status": 0,
|
||||
"reason": "",
|
||||
"created_at": 1716624000,
|
||||
"updated_at": 1716624000
|
||||
}
|
||||
],
|
||||
"total": 1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 源码位置
|
||||
|
||||
- Handler: `internal/handler/public/user/queryWithdrawalLogHandler.go`
|
||||
- Logic: `internal/logic/public/user/queryWithdrawalLogLogic.go`
|
||||
|
||||
> **Warning**: Logic 层尚未实现(仍为 TODO),调用会返回空响应。
|
||||
|
||||
---
|
||||
@@ -19,9 +19,10 @@ services:
|
||||
# ----------------------------------------------------
|
||||
# 1. 业务后端 (PPanel Server)
|
||||
# host 网络:可出外网,直接访问 AWS RDS/Redis;通过 127.0.0.1 访问 Tempo
|
||||
# PPANEL_SERVER_TAG 由 CI/CD 传入不可变镜像标签(如 git SHA)
|
||||
# ----------------------------------------------------
|
||||
ppanel-server:
|
||||
image: registry.kxsw.us/vpn-server:${PPANEL_SERVER_TAG:-latest}
|
||||
image: registry.kxsw.us/vpn-server:${PPANEL_SERVER_TAG:?please set PPANEL_SERVER_TAG to an immutable image tag}
|
||||
container_name: ppanel-server
|
||||
restart: always
|
||||
volumes:
|
||||
@@ -119,7 +120,7 @@ services:
|
||||
# 或配置 Nginx 反代(建议加认证)
|
||||
# ----------------------------------------------------
|
||||
grafana:
|
||||
image: grafana/grafana:latest
|
||||
image: grafana/grafana:13.0.1
|
||||
container_name: ppanel-grafana
|
||||
restart: always
|
||||
ports:
|
||||
@@ -154,7 +155,7 @@ services:
|
||||
# 6. Prometheus (指标采集)
|
||||
# ----------------------------------------------------
|
||||
prometheus:
|
||||
image: prom/prometheus:latest
|
||||
image: prom/prometheus:v3.11.3
|
||||
container_name: ppanel-prometheus
|
||||
restart: always
|
||||
ports:
|
||||
@@ -179,7 +180,7 @@ services:
|
||||
# 7. Nginx Exporter (监控宿主机 Nginx)
|
||||
# ----------------------------------------------------
|
||||
nginx-exporter:
|
||||
image: nginx/nginx-prometheus-exporter:latest
|
||||
image: nginx/nginx-prometheus-exporter:1.5.0
|
||||
container_name: ppanel-nginx-exporter
|
||||
restart: always
|
||||
command:
|
||||
@@ -198,7 +199,7 @@ services:
|
||||
# 8. Node Exporter (宿主机监控)
|
||||
# ----------------------------------------------------
|
||||
node-exporter:
|
||||
image: prom/node-exporter:latest
|
||||
image: prom/node-exporter:v1.11.1
|
||||
container_name: ppanel-node-exporter
|
||||
restart: always
|
||||
volumes:
|
||||
@@ -221,7 +222,7 @@ services:
|
||||
# 9. cAdvisor (容器监控)
|
||||
# ----------------------------------------------------
|
||||
cadvisor:
|
||||
image: gcr.io/cadvisor/cadvisor:latest
|
||||
image: gcr.io/cadvisor/cadvisor:v0.55.1
|
||||
container_name: ppanel-cadvisor
|
||||
restart: always
|
||||
volumes:
|
||||
|
||||
+1
-1
@@ -74,7 +74,7 @@ S3:
|
||||
UsePathStyle: false
|
||||
PresignExpireSeconds: 300
|
||||
MaxUploadSize: 104857600
|
||||
AllowedContentTypes: "application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json"
|
||||
AllowedContentTypes: "application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json,image/jpeg,image/jpg,image/png,image/webp,image/gif,image/heic,image/heif,image/bmp"
|
||||
|
||||
device:
|
||||
enable: true # 开启设备加密通信
|
||||
|
||||
@@ -53,6 +53,7 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2
|
||||
github.com/Masterminds/sprig/v3 v3.3.0
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.7
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.17
|
||||
|
||||
@@ -8,6 +8,8 @@ filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4
|
||||
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
|
||||
github.com/GUAIK-ORG/go-snowflake v0.0.0-20200116064823-220c4260e85f h1:RDkg3pyE1qGbBpRWmvSN9RNZC5nUrOaEPiEpEb8y2f0=
|
||||
github.com/GUAIK-ORG/go-snowflake v0.0.0-20200116064823-220c4260e85f/go.mod h1:zA7AF9RTfpluCfz0omI4t5KCMaWHUMicsZoMccnaT44=
|
||||
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
|
||||
@@ -264,6 +266,7 @@ github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
|
||||
github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
|
||||
github.com/klauspost/compress v1.17.7 h1:ehO88t2UGzQK66LMdE8tibEd1ErmzZjNEqWkjLAKQQg=
|
||||
github.com/klauspost/compress v1.17.7/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
|
||||
@@ -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,19 @@
|
||||
-- Rollback: re-deduct commission for users with pending (status=0) withdrawals.
|
||||
-- This re-applies the OLD behaviour where commission is deducted on application.
|
||||
-- Only run this if you are rolling back to the old code; do NOT run against
|
||||
-- the new code or commission will be double-deducted on approval.
|
||||
|
||||
UPDATE `user` u
|
||||
JOIN (
|
||||
SELECT user_id, COALESCE(SUM(amount), 0) AS pending_total
|
||||
FROM withdrawals
|
||||
WHERE status = 0
|
||||
GROUP BY user_id
|
||||
) p ON u.id = p.user_id
|
||||
SET u.commission = u.commission - p.pending_total
|
||||
WHERE p.pending_total > 0;
|
||||
|
||||
-- Remove the migration log entries written by the up migration.
|
||||
DELETE FROM system_logs
|
||||
WHERE type = 33
|
||||
AND content LIKE '%migration: refund pending withdrawal commission (HIF-22)%';
|
||||
@@ -0,0 +1,65 @@
|
||||
-- Migration: refund commission for existing pending (status=0) withdrawals
|
||||
--
|
||||
-- Under the old logic, commission was deducted when a withdrawal was submitted.
|
||||
-- Under the new logic, commission is only deducted on approval.
|
||||
-- This migration refunds the deducted amounts back to each user so that
|
||||
-- the system is in a consistent state before the new code is deployed.
|
||||
--
|
||||
-- Idempotency: the UPDATE only touches rows whose commission would need
|
||||
-- to increase, and each execution produces the same result because
|
||||
-- COALESCE(SUM(amount),0) is deterministic given the same pending set.
|
||||
-- Running this script multiple times is safe only if no new pending
|
||||
-- withdrawals are created between runs; deploy new code immediately after.
|
||||
|
||||
-- Compatibility: some historical databases missed migration 02122, so the
|
||||
-- withdrawals table may not exist yet. Create it idempotently before the
|
||||
-- refund logic so this migration can self-heal older installations.
|
||||
CREATE TABLE IF NOT EXISTS `withdrawals` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
|
||||
`user_id` BIGINT NOT NULL COMMENT 'User ID',
|
||||
`amount` BIGINT NOT NULL COMMENT 'Withdrawal Amount',
|
||||
`content` TEXT COMMENT 'Withdrawal Content',
|
||||
`status` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Withdrawal Status',
|
||||
`reason` VARCHAR(500) NOT NULL DEFAULT '' COMMENT 'Rejection Reason',
|
||||
`created_at` DATETIME NOT NULL COMMENT 'Creation Time',
|
||||
`updated_at` DATETIME NOT NULL COMMENT 'Update Time',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_user_id` (`user_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
INSERT IGNORE INTO `system` (`category`, `key`, `value`, `type`, `desc`, `created_at`, `updated_at`)
|
||||
VALUES
|
||||
('invite', 'WithdrawalMethod', '', 'string', 'withdrawal method', '2025-04-22 14:25:16.637', '2025-04-22 14:25:16.637');
|
||||
|
||||
-- Step 1: refund commission for all users with pending withdrawals.
|
||||
UPDATE `user` u
|
||||
JOIN (
|
||||
SELECT user_id, COALESCE(SUM(amount), 0) AS pending_total
|
||||
FROM withdrawals
|
||||
WHERE status = 0
|
||||
GROUP BY user_id
|
||||
) p ON u.id = p.user_id
|
||||
SET u.commission = u.commission + p.pending_total
|
||||
WHERE p.pending_total > 0;
|
||||
|
||||
-- Step 2: write a migration log entry for each refunded user.
|
||||
INSERT INTO system_logs (type, date, object_id, content, created_at)
|
||||
SELECT
|
||||
33 AS type,
|
||||
DATE(NOW()) AS date,
|
||||
p.user_id AS object_id,
|
||||
JSON_OBJECT(
|
||||
'type', 99,
|
||||
'amount', p.pending_total,
|
||||
'order_no', '',
|
||||
'timestamp', UNIX_TIMESTAMP(NOW()) * 1000,
|
||||
'note', 'migration: refund pending withdrawal commission (HIF-22)'
|
||||
) AS content,
|
||||
NOW() AS created_at
|
||||
FROM (
|
||||
SELECT user_id, COALESCE(SUM(amount), 0) AS pending_total
|
||||
FROM withdrawals
|
||||
WHERE status = 0
|
||||
GROUP BY user_id
|
||||
HAVING pending_total > 0
|
||||
) p;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Remove activation_context column from order table
|
||||
ALTER TABLE `order` DROP COLUMN IF EXISTS `activation_context`;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Add activation_context column to order table for Redis fallback persistence (idempotent)
|
||||
SET @col_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'order' AND COLUMN_NAME = 'activation_context');
|
||||
SET @sql = IF(@col_exists = 0, 'ALTER TABLE `order` ADD COLUMN `activation_context` TEXT DEFAULT NULL COMMENT ''Activation context JSON (guest/redemption info for DB fallback)'' AFTER `app_account_token`', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
@@ -0,0 +1,4 @@
|
||||
ALTER TABLE `withdrawals`
|
||||
DROP COLUMN `qr_code_url`,
|
||||
DROP COLUMN `account`,
|
||||
DROP COLUMN `method`;
|
||||
@@ -0,0 +1,10 @@
|
||||
SELECT COUNT(*) INTO @col_exists FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'withdrawals' AND COLUMN_NAME = 'method';
|
||||
|
||||
SET @ddl = IF(@col_exists = 0,
|
||||
'ALTER TABLE `withdrawals` ADD COLUMN `method` TINYINT(1) NOT NULL DEFAULT 0 AFTER `content`, ADD COLUMN `account` VARCHAR(255) NOT NULL DEFAULT '''' AFTER `method`, ADD COLUMN `qr_code_url` VARCHAR(500) NOT NULL DEFAULT '''' AFTER `account`',
|
||||
'SELECT 1');
|
||||
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
@@ -0,0 +1,35 @@
|
||||
SET @traffic_limit_exists = (
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'user_subscribe'
|
||||
AND COLUMN_NAME = 'traffic_limit'
|
||||
);
|
||||
|
||||
SET @traffic_limit_sql = IF(
|
||||
@traffic_limit_exists = 1,
|
||||
'ALTER TABLE `user_subscribe` DROP COLUMN `traffic_limit`',
|
||||
'SELECT 1'
|
||||
);
|
||||
|
||||
PREPARE traffic_limit_stmt FROM @traffic_limit_sql;
|
||||
EXECUTE traffic_limit_stmt;
|
||||
DEALLOCATE PREPARE traffic_limit_stmt;
|
||||
|
||||
SET @speed_limit_exists = (
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'user_subscribe'
|
||||
AND COLUMN_NAME = 'speed_limit'
|
||||
);
|
||||
|
||||
SET @speed_limit_sql = IF(
|
||||
@speed_limit_exists = 1,
|
||||
'ALTER TABLE `user_subscribe` DROP COLUMN `speed_limit`',
|
||||
'SELECT 1'
|
||||
);
|
||||
|
||||
PREPARE speed_limit_stmt FROM @speed_limit_sql;
|
||||
EXECUTE speed_limit_stmt;
|
||||
DEALLOCATE PREPARE speed_limit_stmt;
|
||||
@@ -0,0 +1,35 @@
|
||||
SET @speed_limit_exists = (
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'user_subscribe'
|
||||
AND COLUMN_NAME = 'speed_limit'
|
||||
);
|
||||
|
||||
SET @speed_limit_sql = IF(
|
||||
@speed_limit_exists = 0,
|
||||
'ALTER TABLE `user_subscribe` ADD COLUMN `speed_limit` BIGINT NOT NULL DEFAULT 0 COMMENT ''User-level speed limit override (Mbps), 0 uses plan-level'' AFTER `upload`',
|
||||
'SELECT 1'
|
||||
);
|
||||
|
||||
PREPARE speed_limit_stmt FROM @speed_limit_sql;
|
||||
EXECUTE speed_limit_stmt;
|
||||
DEALLOCATE PREPARE speed_limit_stmt;
|
||||
|
||||
SET @traffic_limit_exists = (
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'user_subscribe'
|
||||
AND COLUMN_NAME = 'traffic_limit'
|
||||
);
|
||||
|
||||
SET @traffic_limit_sql = IF(
|
||||
@traffic_limit_exists = 0,
|
||||
'ALTER TABLE `user_subscribe` ADD COLUMN `traffic_limit` TEXT DEFAULT NULL COMMENT ''User-level traffic limit override (JSON), NULL uses plan-level'' AFTER `speed_limit`',
|
||||
'SELECT 1'
|
||||
);
|
||||
|
||||
PREPARE traffic_limit_stmt FROM @traffic_limit_sql;
|
||||
EXECUTE traffic_limit_stmt;
|
||||
DEALLOCATE PREPARE traffic_limit_stmt;
|
||||
@@ -0,0 +1,39 @@
|
||||
SET @column_exists = (
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'order'
|
||||
AND COLUMN_NAME = 'promo_discount'
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@column_exists = 1,
|
||||
'ALTER TABLE `order` DROP COLUMN `promo_discount`',
|
||||
'SELECT ''Column promo_discount does not exist in order table'''
|
||||
);
|
||||
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @column_exists = (
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'order'
|
||||
AND COLUMN_NAME = 'promo_rule_id'
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@column_exists = 1,
|
||||
'ALTER TABLE `order` DROP COLUMN `promo_rule_id`',
|
||||
'SELECT ''Column promo_rule_id does not exist in order table'''
|
||||
);
|
||||
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
DROP TABLE IF EXISTS `promo_usage`;
|
||||
DROP TABLE IF EXISTS `subscribe_promo`;
|
||||
DROP TABLE IF EXISTS `promo_rule`;
|
||||
@@ -0,0 +1,213 @@
|
||||
CREATE TABLE IF NOT EXISTS `promo_rule` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`name` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '规则名称',
|
||||
`type` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '规则类型:new_user / inactive_user / campaign',
|
||||
`params` JSON NOT NULL COMMENT '类型专属参数',
|
||||
`priority` INT NOT NULL DEFAULT 0 COMMENT '优先级,数值越大越优先匹配',
|
||||
`enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用',
|
||||
`start_time` DATETIME DEFAULT NULL COMMENT '生效开始时间',
|
||||
`end_time` DATETIME DEFAULT NULL COMMENT '生效结束时间',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
`deleted_at` DATETIME DEFAULT NULL COMMENT '软删除时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_enabled_priority_deleted` (`enabled`, `deleted_at`, `priority` DESC)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表';
|
||||
|
||||
SET @index_exists = (
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'promo_rule'
|
||||
AND INDEX_NAME = 'idx_enabled_priority'
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@index_exists = 1,
|
||||
'ALTER TABLE `promo_rule` DROP INDEX `idx_enabled_priority`',
|
||||
'SELECT ''Index idx_enabled_priority does not exist on promo_rule table'''
|
||||
);
|
||||
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @index_exists = (
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'promo_rule'
|
||||
AND INDEX_NAME = 'idx_deleted_at'
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@index_exists = 1,
|
||||
'ALTER TABLE `promo_rule` DROP INDEX `idx_deleted_at`',
|
||||
'SELECT ''Index idx_deleted_at does not exist on promo_rule table'''
|
||||
);
|
||||
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @index_exists = (
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'promo_rule'
|
||||
AND INDEX_NAME = 'idx_enabled_priority_deleted'
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@index_exists = 0,
|
||||
'ALTER TABLE `promo_rule` ADD KEY `idx_enabled_priority_deleted` (`enabled`, `deleted_at`, `priority` DESC)',
|
||||
'SELECT ''Index idx_enabled_priority_deleted already exists on promo_rule table'''
|
||||
);
|
||||
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `subscribe_promo` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '套餐规格 ID',
|
||||
`quantity` BIGINT NOT NULL DEFAULT 1 COMMENT '购买数量',
|
||||
`promo_rule_id` BIGINT UNSIGNED NOT NULL COMMENT '促销规则 ID',
|
||||
`promo_price` BIGINT NOT NULL DEFAULT 0 COMMENT '该规格在此规则下的优惠价(分)',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_subscribe_quantity_rule` (`subscribe_id`, `quantity`, `promo_rule_id`),
|
||||
KEY `idx_promo_rule_id` (`promo_rule_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格促销价表';
|
||||
|
||||
SET @column_exists = (
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'subscribe_promo'
|
||||
AND COLUMN_NAME = 'quantity'
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@column_exists = 0,
|
||||
'ALTER TABLE `subscribe_promo` ADD COLUMN `quantity` BIGINT NOT NULL DEFAULT 1 COMMENT ''购买数量'' AFTER `subscribe_id`',
|
||||
'SELECT ''Column quantity already exists in subscribe_promo table'''
|
||||
);
|
||||
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @sql = IF(
|
||||
@column_exists = 1,
|
||||
'ALTER TABLE `subscribe_promo` MODIFY COLUMN `quantity` BIGINT NOT NULL DEFAULT 1 COMMENT ''购买数量''',
|
||||
'SELECT ''Column quantity does not exist in subscribe_promo table'''
|
||||
);
|
||||
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @index_exists = (
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'subscribe_promo'
|
||||
AND INDEX_NAME = 'uk_subscribe_rule'
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@index_exists = 1,
|
||||
'ALTER TABLE `subscribe_promo` DROP INDEX `uk_subscribe_rule`',
|
||||
'SELECT ''Index uk_subscribe_rule does not exist on subscribe_promo table'''
|
||||
);
|
||||
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @index_exists = (
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'subscribe_promo'
|
||||
AND INDEX_NAME = 'uk_subscribe_qty_rule'
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@index_exists = 1,
|
||||
'ALTER TABLE `subscribe_promo` DROP INDEX `uk_subscribe_qty_rule`',
|
||||
'SELECT ''Index uk_subscribe_qty_rule does not exist on subscribe_promo table'''
|
||||
);
|
||||
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @index_exists = (
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'subscribe_promo'
|
||||
AND INDEX_NAME = 'uk_subscribe_quantity_rule'
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@index_exists = 0,
|
||||
'ALTER TABLE `subscribe_promo` ADD UNIQUE KEY `uk_subscribe_quantity_rule` (`subscribe_id`, `quantity`, `promo_rule_id`)',
|
||||
'SELECT ''Index uk_subscribe_quantity_rule already exists on subscribe_promo table'''
|
||||
);
|
||||
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `promo_usage` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户 ID',
|
||||
`promo_rule_id` BIGINT UNSIGNED NOT NULL COMMENT '使用的规则 ID',
|
||||
`subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '购买的规格 ID',
|
||||
`order_no` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '关联订单号',
|
||||
`promo_price` BIGINT NOT NULL DEFAULT 0 COMMENT '使用时的促销单价(分)',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_user_rule` (`user_id`, `promo_rule_id`),
|
||||
KEY `idx_order_no` (`order_no`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销使用记录表';
|
||||
|
||||
SET @column_exists = (
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'order'
|
||||
AND COLUMN_NAME = 'promo_rule_id'
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@column_exists = 0,
|
||||
'ALTER TABLE `order` ADD COLUMN `promo_rule_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT ''促销规则ID, 0=未使用促销'' AFTER `discount`',
|
||||
'SELECT ''Column promo_rule_id already exists in order table'''
|
||||
);
|
||||
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @column_exists = (
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'order'
|
||||
AND COLUMN_NAME = 'promo_discount'
|
||||
);
|
||||
|
||||
SET @sql = IF(
|
||||
@column_exists = 0,
|
||||
'ALTER TABLE `order` ADD COLUMN `promo_discount` BIGINT NOT NULL DEFAULT 0 COMMENT ''促销优惠金额(分)'' AFTER `promo_rule_id`',
|
||||
'SELECT ''Column promo_discount already exists in order table'''
|
||||
);
|
||||
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
@@ -58,7 +58,7 @@ type S3Config struct {
|
||||
UsePathStyle bool `yaml:"UsePathStyle" default:"false"`
|
||||
PresignExpireSeconds int64 `yaml:"PresignExpireSeconds" default:"300"`
|
||||
MaxUploadSize int64 `yaml:"MaxUploadSize" default:"104857600"`
|
||||
AllowedContentTypes string `yaml:"AllowedContentTypes" default:"application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json"`
|
||||
AllowedContentTypes string `yaml:"AllowedContentTypes" default:"application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json,image/jpeg,image/jpg,image/png,image/webp,image/gif,image/heic,image/heif,image/bmp"`
|
||||
}
|
||||
|
||||
type RedisConfig struct {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package invite
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/invite"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// Get invite manage list
|
||||
func GetInviteManageListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.GetInviteManageListRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
if err := svcCtx.Validate(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
l := invite.NewGetInviteManageListLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.GetInviteManageList(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package 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,23 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
func CreateRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.CreatePromoRuleRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
if err := svcCtx.Validate(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
l := promo.NewCreateRuleLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.CreateRule(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
func DeletePriceHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.DeletePromoPriceRequest
|
||||
if err := c.ShouldBindUri(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
if err := svcCtx.Validate(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
l := promo.NewDeletePriceLogic(c.Request.Context(), svcCtx)
|
||||
err := l.DeletePrice(&req)
|
||||
result.HttpResult(c, nil, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
func DeleteRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.DeletePromoRuleRequest
|
||||
if err := c.ShouldBindUri(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
if err := svcCtx.Validate(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
l := promo.NewDeleteRuleLogic(c.Request.Context(), svcCtx)
|
||||
err := l.DeleteRule(&req)
|
||||
result.HttpResult(c, nil, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
func GetPriceListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.GetPromoPriceListRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
if err := svcCtx.Validate(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
l := promo.NewGetPriceListLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.GetPriceList(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
func GetRuleDetailHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.GetPromoRuleDetailRequest
|
||||
if err := c.ShouldBindUri(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
if err := svcCtx.Validate(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
l := promo.NewGetRuleDetailLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.GetRuleDetail(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
func GetRuleListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.GetPromoRuleListRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
if err := svcCtx.Validate(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
l := promo.NewGetRuleListLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.GetRuleList(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
func GetUsageListHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.GetPromoUsageListRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
if err := svcCtx.Validate(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
l := promo.NewGetUsageListLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.GetUsageList(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
func SetPriceHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.SetPromoPriceRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
if err := svcCtx.Validate(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
l := promo.NewSetPriceLogic(c.Request.Context(), svcCtx)
|
||||
err := l.SetPrice(&req)
|
||||
result.HttpResult(c, nil, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/promo"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
func UpdateRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.UpdatePromoRuleRequest
|
||||
if err := c.ShouldBindUri(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
_ = c.ShouldBind(&req)
|
||||
if err := svcCtx.Validate(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
l := promo.NewUpdateRuleLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.UpdateRule(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
@@ -18,9 +21,25 @@ func UpdateUserSubscribeHandler(svcCtx *svc.ServiceContext) func(c *gin.Context)
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
if err := validateUpdateUserSubscribeTrafficLimit(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
l := user.NewUpdateUserSubscribeLogic(c.Request.Context(), svcCtx)
|
||||
err := l.UpdateUserSubscribe(&req)
|
||||
result.HttpResult(c, nil, err)
|
||||
}
|
||||
}
|
||||
|
||||
func validateUpdateUserSubscribeTrafficLimit(req *types.UpdateUserSubscribeRequest) error {
|
||||
if req.TrafficLimit == nil || *req.TrafficLimit == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
var rules []types.TrafficLimit
|
||||
if err := json.Unmarshal([]byte(*req.TrafficLimit), &rules); err != nil {
|
||||
return errors.New("traffic_limit must be a valid JSON array")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
)
|
||||
|
||||
func TestUpdateUserSubscribeHandlerRejectsInvalidLimits(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
}{
|
||||
{
|
||||
name: "negative speed limit",
|
||||
body: `{"user_subscribe_id":1,"subscribe_id":1,"traffic":0,"expired_at":4102444800000,"upload":0,"download":0,"speed_limit":-1}`,
|
||||
},
|
||||
{
|
||||
name: "invalid traffic limit json",
|
||||
body: `{"user_subscribe_id":1,"subscribe_id":1,"traffic":0,"expired_at":4102444800000,"upload":0,"download":0,"traffic_limit":"not-json"}`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
router := gin.New()
|
||||
router.PUT("/v1/admin/user/subscribe", UpdateUserSubscribeHandler(&svc.ServiceContext{}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, "/v1/admin/user/subscribe", bytes.NewBufferString(tt.body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("expected HTTP 200, got %d", rec.Code)
|
||||
}
|
||||
|
||||
var resp struct {
|
||||
Code uint32 `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("unmarshal response: %v", err)
|
||||
}
|
||||
if resp.Code != xerr.InvalidParams {
|
||||
t.Fatalf("expected code %d, got %d (%s)", xerr.InvalidParams, resp.Code, resp.Msg)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -8,10 +8,10 @@ import (
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// Get invite sales data
|
||||
func GetInviteSalesHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
// Get invite gift records
|
||||
func GetInviteRecordsHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.GetInviteSalesRequest
|
||||
var req types.GetInviteRecordsRequest
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
result.ParamErrorResult(c, err)
|
||||
return
|
||||
@@ -23,8 +23,8 @@ func GetInviteSalesHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
l := user.NewGetInviteSalesLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.GetInviteSales(&req)
|
||||
l := user.NewGetInviteRecordsLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.GetInviteRecords(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -13,10 +13,12 @@ import (
|
||||
adminCoupon "github.com/perfect-panel/server/internal/handler/admin/coupon"
|
||||
adminDocument "github.com/perfect-panel/server/internal/handler/admin/document"
|
||||
adminGroup "github.com/perfect-panel/server/internal/handler/admin/group"
|
||||
adminInvite "github.com/perfect-panel/server/internal/handler/admin/invite"
|
||||
adminLog "github.com/perfect-panel/server/internal/handler/admin/log"
|
||||
adminMarketing "github.com/perfect-panel/server/internal/handler/admin/marketing"
|
||||
adminOrder "github.com/perfect-panel/server/internal/handler/admin/order"
|
||||
adminPayment "github.com/perfect-panel/server/internal/handler/admin/payment"
|
||||
adminPromo "github.com/perfect-panel/server/internal/handler/admin/promo"
|
||||
adminRedemption "github.com/perfect-panel/server/internal/handler/admin/redemption"
|
||||
adminServer "github.com/perfect-panel/server/internal/handler/admin/server"
|
||||
adminSubscribe "github.com/perfect-panel/server/internal/handler/admin/subscribe"
|
||||
@@ -193,6 +195,14 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
adminDocumentGroupRouter.GET("/list", adminDocument.GetDocumentListHandler(serverCtx))
|
||||
}
|
||||
|
||||
adminInviteGroupRouter := router.Group("/v1/admin/invite")
|
||||
adminInviteGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
||||
|
||||
{
|
||||
// Get invite manage list
|
||||
adminInviteGroupRouter.GET("/list", adminInvite.GetInviteManageListHandler(serverCtx))
|
||||
}
|
||||
|
||||
adminGroupGroupRouter := router.Group("/v1/admin/group")
|
||||
adminGroupGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
||||
|
||||
@@ -259,6 +269,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
// Get error log message detail
|
||||
adminLogGroupRouter.GET("/error_message/detail", adminLog.GetErrorLogMessageDetailHandler(serverCtx))
|
||||
|
||||
// Get log message raw detail (temporary)
|
||||
adminLogGroupRouter.GET("/message/detail", adminLog.GetLogMessageRawHandler(serverCtx))
|
||||
|
||||
// Get error log message list
|
||||
adminLogGroupRouter.GET("/error_message/list", adminLog.GetErrorLogMessageListHandler(serverCtx))
|
||||
|
||||
@@ -371,6 +384,38 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
adminPaymentGroupRouter.GET("/platform", adminPayment.GetPaymentPlatformHandler(serverCtx))
|
||||
}
|
||||
|
||||
adminPromoGroupRouter := router.Group("/v1/admin/promo")
|
||||
adminPromoGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
||||
|
||||
{
|
||||
// Create promo rule
|
||||
adminPromoGroupRouter.POST("/rule", adminPromo.CreateRuleHandler(serverCtx))
|
||||
|
||||
// Get promo rule list
|
||||
adminPromoGroupRouter.GET("/rule/list", adminPromo.GetRuleListHandler(serverCtx))
|
||||
|
||||
// Get promo rule detail
|
||||
adminPromoGroupRouter.GET("/rule/:id", adminPromo.GetRuleDetailHandler(serverCtx))
|
||||
|
||||
// Update promo rule
|
||||
adminPromoGroupRouter.PUT("/rule/:id", adminPromo.UpdateRuleHandler(serverCtx))
|
||||
|
||||
// Delete promo rule
|
||||
adminPromoGroupRouter.DELETE("/rule/:id", adminPromo.DeleteRuleHandler(serverCtx))
|
||||
|
||||
// Set promo prices
|
||||
adminPromoGroupRouter.POST("/price", adminPromo.SetPriceHandler(serverCtx))
|
||||
|
||||
// Get promo price list
|
||||
adminPromoGroupRouter.GET("/price/list", adminPromo.GetPriceListHandler(serverCtx))
|
||||
|
||||
// Delete promo price
|
||||
adminPromoGroupRouter.DELETE("/price/:id", adminPromo.DeletePriceHandler(serverCtx))
|
||||
|
||||
// Get promo usage list
|
||||
adminPromoGroupRouter.GET("/usage/list", adminPromo.GetUsageListHandler(serverCtx))
|
||||
}
|
||||
|
||||
adminRedemptionGroupRouter := router.Group("/v1/admin/redemption")
|
||||
adminRedemptionGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
||||
|
||||
@@ -975,17 +1020,16 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
}
|
||||
|
||||
publicSubscribeGroupRouter := router.Group("/v1/public/subscribe")
|
||||
publicSubscribeGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
|
||||
|
||||
{
|
||||
// Get subscribe list
|
||||
publicSubscribeGroupRouter.GET("/list", publicSubscribe.QuerySubscribeListHandler(serverCtx))
|
||||
publicSubscribeGroupRouter.GET("/list", middleware.OptionalAuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx), publicSubscribe.QuerySubscribeListHandler(serverCtx))
|
||||
|
||||
// Get user subscribe node info
|
||||
publicSubscribeGroupRouter.GET("/node/list", publicSubscribe.QueryUserSubscribeNodeListHandler(serverCtx))
|
||||
publicSubscribeGroupRouter.GET("/node/list", middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx), publicSubscribe.QueryUserSubscribeNodeListHandler(serverCtx))
|
||||
|
||||
// Get subscribe group list
|
||||
publicSubscribeGroupRouter.GET("/group/list", publicSubscribe.QuerySubscribeGroupListHandler(serverCtx))
|
||||
publicSubscribeGroupRouter.GET("/group/list", middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx), publicSubscribe.QuerySubscribeGroupListHandler(serverCtx))
|
||||
}
|
||||
|
||||
publicTicketGroupRouter := router.Group("/v1/public/ticket")
|
||||
@@ -1056,6 +1100,9 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
// Commission Withdraw
|
||||
publicUserGroupRouter.POST("/commission_withdraw", publicUser.CommissionWithdrawHandler(serverCtx))
|
||||
|
||||
// Cancel Withdrawal
|
||||
publicUserGroupRouter.POST("/withdrawal_cancel", publicUser.CancelWithdrawalHandler(serverCtx))
|
||||
|
||||
// Delete Current User Account
|
||||
publicUserGroupRouter.DELETE("/current_user_account", publicUser.DeleteCurrentUserAccountHandler(serverCtx))
|
||||
|
||||
@@ -1071,9 +1118,8 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
||||
// Query User Info
|
||||
publicUserGroupRouter.GET("/info", publicUser.QueryUserInfoHandler(serverCtx))
|
||||
|
||||
// Get Invite Sales
|
||||
publicUserGroupRouter.GET("/invite_sales", publicUser.GetInviteSalesHandler(serverCtx))
|
||||
publicUserGroupRouter.GET("/invite/sales", publicUser.GetInviteSalesHandler(serverCtx)) // alias: backward-compat
|
||||
// Get Invite Records
|
||||
publicUserGroupRouter.GET("/invite_records", publicUser.GetInviteRecordsHandler(serverCtx))
|
||||
|
||||
// Get User Invite Stats
|
||||
publicUserGroupRouter.GET("/invite_stats", publicUser.GetUserInviteStatsHandler(serverCtx))
|
||||
|
||||
@@ -29,7 +29,7 @@ func (l *DeleteSubscribeApplicationLogic) DeleteSubscribeApplication(req *types.
|
||||
err := l.svcCtx.ClientModel.Delete(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
l.Errorf("Failed to delete subscribe application with ID %d: %v", req.Id, err)
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), err.Error())
|
||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseDeletedError), err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
package invite
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
modellog "github.com/perfect-panel/server/internal/model/log"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Benefits struct {
|
||||
OrderCount int64
|
||||
HasPurchased bool
|
||||
InviterCommission int64
|
||||
InviterGiftDays int64
|
||||
InviteeGiftDays int64
|
||||
}
|
||||
|
||||
type InviteRelation struct {
|
||||
InviteeId int64
|
||||
InviterId int64
|
||||
}
|
||||
|
||||
type paidOrderRow struct {
|
||||
UserId int64 `gorm:"column:user_id"`
|
||||
OrderNo string `gorm:"column:order_no"`
|
||||
}
|
||||
|
||||
type systemLogRow struct {
|
||||
ObjectID int64 `gorm:"column:object_id"`
|
||||
Content string `gorm:"column:content"`
|
||||
}
|
||||
|
||||
func NormalizePage(page, size int) (int, int) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if size < 1 {
|
||||
size = 10
|
||||
}
|
||||
if size > 100 {
|
||||
size = 100
|
||||
}
|
||||
return page, size
|
||||
}
|
||||
|
||||
func QueryBenefits(ctx context.Context, db *gorm.DB, relations []InviteRelation) (map[int64]Benefits, error) {
|
||||
result := make(map[int64]Benefits, len(relations))
|
||||
if len(relations) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
inviteeIds := make([]int64, 0, len(relations))
|
||||
inviteeToInviter := make(map[int64]int64, len(relations))
|
||||
for _, relation := range relations {
|
||||
inviteeIds = append(inviteeIds, relation.InviteeId)
|
||||
inviteeToInviter[relation.InviteeId] = relation.InviterId
|
||||
result[relation.InviteeId] = Benefits{}
|
||||
}
|
||||
|
||||
var orderCounts []struct {
|
||||
UserId int64 `gorm:"column:user_id"`
|
||||
Cnt int64 `gorm:"column:cnt"`
|
||||
}
|
||||
if err := db.WithContext(ctx).
|
||||
Table("`order`").
|
||||
Select("user_id, COUNT(*) as cnt").
|
||||
Where("user_id IN ? AND status IN ?", inviteeIds, []int{2, 5}).
|
||||
Group("user_id").
|
||||
Scan(&orderCounts).Error; err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count invitee paid orders failed: %v", err)
|
||||
}
|
||||
for _, row := range orderCounts {
|
||||
benefit := result[row.UserId]
|
||||
benefit.OrderCount = row.Cnt
|
||||
benefit.HasPurchased = row.Cnt > 0
|
||||
result[row.UserId] = benefit
|
||||
}
|
||||
|
||||
var paidOrders []paidOrderRow
|
||||
if err := db.WithContext(ctx).
|
||||
Table("`order`").
|
||||
Select("user_id, order_no").
|
||||
Where("user_id IN ? AND status IN ?", inviteeIds, []int{2, 5}).
|
||||
Scan(&paidOrders).Error; err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invitee paid orders failed: %v", err)
|
||||
}
|
||||
if len(paidOrders) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
orderNos := make([]string, 0, len(paidOrders))
|
||||
orderToInvitee := make(map[string]int64, len(paidOrders))
|
||||
inviterIds := make([]int64, 0, len(relations))
|
||||
inviteeAndInviterSet := make(map[int64]struct{}, len(relations)*2)
|
||||
for _, order := range paidOrders {
|
||||
orderNos = append(orderNos, order.OrderNo)
|
||||
orderToInvitee[order.OrderNo] = order.UserId
|
||||
}
|
||||
for _, relation := range relations {
|
||||
inviterIds = append(inviterIds, relation.InviterId)
|
||||
inviteeAndInviterSet[relation.InviteeId] = struct{}{}
|
||||
inviteeAndInviterSet[relation.InviterId] = struct{}{}
|
||||
}
|
||||
inviteeAndInviterIds := make([]int64, 0, len(inviteeAndInviterSet))
|
||||
for userId := range inviteeAndInviterSet {
|
||||
inviteeAndInviterIds = append(inviteeAndInviterIds, userId)
|
||||
}
|
||||
|
||||
if err := fillCommissionBenefits(ctx, db, result, orderToInvitee, inviteeToInviter, orderNos, inviterIds); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := fillGiftBenefits(ctx, db, result, orderToInvitee, inviteeToInviter, orderNos, inviteeAndInviterIds); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func fillCommissionBenefits(ctx context.Context, db *gorm.DB, benefits map[int64]Benefits, orderToInvitee map[string]int64, inviteeToInviter map[int64]int64, orderNos []string, inviterIds []int64) error {
|
||||
var rows []systemLogRow
|
||||
if err := db.WithContext(ctx).
|
||||
Table("system_logs").
|
||||
Select("object_id, content").
|
||||
Where("type = ? AND object_id IN ? AND JSON_UNQUOTE(JSON_EXTRACT(content, '$.order_no')) IN ? AND JSON_EXTRACT(content, '$.type') IN ?", modellog.TypeCommission.Uint8(), inviterIds, orderNos, []int{int(modellog.CommissionTypePurchase), int(modellog.CommissionTypeRenewal)}).
|
||||
Scan(&rows).Error; err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invite commission logs failed: %v", err)
|
||||
}
|
||||
for _, row := range rows {
|
||||
content := modellog.Commission{}
|
||||
if err := content.Unmarshal([]byte(row.Content)); err != nil {
|
||||
continue
|
||||
}
|
||||
inviteeId, ok := orderToInvitee[content.OrderNo]
|
||||
if !ok || inviteeToInviter[inviteeId] != row.ObjectID {
|
||||
continue
|
||||
}
|
||||
benefit := benefits[inviteeId]
|
||||
benefit.InviterCommission += content.Amount
|
||||
benefits[inviteeId] = benefit
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func fillGiftBenefits(ctx context.Context, db *gorm.DB, benefits map[int64]Benefits, orderToInvitee map[string]int64, inviteeToInviter map[int64]int64, orderNos []string, userIds []int64) error {
|
||||
var rows []systemLogRow
|
||||
if err := db.WithContext(ctx).
|
||||
Table("system_logs").
|
||||
Select("object_id, content").
|
||||
Where("type = ? AND object_id IN ? AND JSON_UNQUOTE(JSON_EXTRACT(content, '$.order_no')) IN ?", modellog.TypeGift.Uint8(), userIds, orderNos).
|
||||
Scan(&rows).Error; err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invite gift logs failed: %v", err)
|
||||
}
|
||||
for _, row := range rows {
|
||||
content := modellog.Gift{}
|
||||
if err := content.Unmarshal([]byte(row.Content)); err != nil {
|
||||
continue
|
||||
}
|
||||
if content.Type != modellog.GiftTypeIncrease {
|
||||
continue
|
||||
}
|
||||
inviteeId, ok := orderToInvitee[content.OrderNo]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
benefit := benefits[inviteeId]
|
||||
switch row.ObjectID {
|
||||
case inviteeToInviter[inviteeId]:
|
||||
benefit.InviterGiftDays += content.Amount
|
||||
case inviteeId:
|
||||
benefit.InviteeGiftDays += content.Amount
|
||||
default:
|
||||
continue
|
||||
}
|
||||
benefits[inviteeId] = benefit
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func QueryIdentifiers(ctx context.Context, db *gorm.DB, userIds []int64) (map[int64]string, error) {
|
||||
identifiers := make(map[int64]string, len(userIds))
|
||||
if len(userIds) == 0 {
|
||||
return identifiers, nil
|
||||
}
|
||||
|
||||
type identifierRow struct {
|
||||
UserId int64 `gorm:"column:user_id"`
|
||||
Identifier string `gorm:"column:identifier"`
|
||||
}
|
||||
var rows []identifierRow
|
||||
if err := db.WithContext(ctx).
|
||||
Table("user_auth_methods uam").
|
||||
Select("uam.user_id, uam.auth_identifier as identifier").
|
||||
Joins("JOIN (SELECT user_id, MIN(id) AS id FROM user_auth_methods WHERE user_id IN ? GROUP BY user_id) first_uam ON first_uam.id = uam.id", userIds).
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query user identifiers failed: %v", err)
|
||||
}
|
||||
for _, row := range rows {
|
||||
identifiers[row.UserId] = row.Identifier
|
||||
}
|
||||
return identifiers, nil
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package invite
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type GetInviteManageListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewGetInviteManageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetInviteManageListLogic {
|
||||
return &GetInviteManageListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetInviteManageListLogic) GetInviteManageList(req *types.GetInviteManageListRequest) (resp *types.GetInviteManageListResponse, err error) {
|
||||
req.Page, req.Size = NormalizePage(req.Page, req.Size)
|
||||
|
||||
type inviteRow struct {
|
||||
InviteeId int64 `gorm:"column:invitee_id"`
|
||||
InviteeAvatar string `gorm:"column:invitee_avatar"`
|
||||
InviteeEnable bool `gorm:"column:invitee_enable"`
|
||||
InvitedAt int64 `gorm:"column:invited_at"`
|
||||
InviterId int64 `gorm:"column:inviter_id"`
|
||||
}
|
||||
|
||||
baseQuery := applyInviteManageFilters(l.svcCtx.DB.WithContext(l.ctx).
|
||||
Table("user invitee").
|
||||
Where("invitee.referer_id > 0 AND invitee.deleted_at IS NULL"), req)
|
||||
|
||||
var total int64
|
||||
if err = baseQuery.Count(&total).Error; err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count invite manage records failed: %v", err)
|
||||
}
|
||||
|
||||
var rows []inviteRow
|
||||
if err = applyInviteManageFilters(l.svcCtx.DB.WithContext(l.ctx).
|
||||
Table("user invitee").
|
||||
Select("invitee.id as invitee_id, invitee.avatar as invitee_avatar, invitee.enable as invitee_enable, UNIX_TIMESTAMP(invitee.created_at) as invited_at, invitee.referer_id as inviter_id").
|
||||
Where("invitee.referer_id > 0 AND invitee.deleted_at IS NULL"), req).
|
||||
Order("invitee.created_at DESC").
|
||||
Limit(req.Size).
|
||||
Offset((req.Page - 1) * req.Size).
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invite manage records failed: %v", err)
|
||||
}
|
||||
|
||||
relations := make([]InviteRelation, 0, len(rows))
|
||||
userIds := make([]int64, 0, len(rows)*2)
|
||||
for _, row := range rows {
|
||||
relations = append(relations, InviteRelation{InviteeId: row.InviteeId, InviterId: row.InviterId})
|
||||
userIds = append(userIds, row.InviteeId, row.InviterId)
|
||||
}
|
||||
|
||||
benefits, err := QueryBenefits(l.ctx, l.svcCtx.DB, relations)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
identifiers, err := QueryIdentifiers(l.ctx, l.svcCtx.DB, userIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
list := make([]types.InviteManageRecord, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
benefit := benefits[row.InviteeId]
|
||||
list = append(list, types.InviteManageRecord{
|
||||
InviterId: row.InviterId,
|
||||
InviterIdentifier: identifiers[row.InviterId],
|
||||
InviteeId: row.InviteeId,
|
||||
InviteeIdentifier: identifiers[row.InviteeId],
|
||||
InviteeAvatar: row.InviteeAvatar,
|
||||
InviteeEnable: row.InviteeEnable,
|
||||
InvitedAt: row.InvitedAt,
|
||||
OrderCount: benefit.OrderCount,
|
||||
HasPurchased: benefit.HasPurchased,
|
||||
InviterCommission: benefit.InviterCommission,
|
||||
InviterGiftDays: benefit.InviterGiftDays,
|
||||
InviteeGiftDays: benefit.InviteeGiftDays,
|
||||
})
|
||||
}
|
||||
|
||||
return &types.GetInviteManageListResponse{
|
||||
Total: total,
|
||||
List: list,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func applyInviteManageFilters(db *gorm.DB, req *types.GetInviteManageListRequest) *gorm.DB {
|
||||
if req.InviterId > 0 {
|
||||
db = db.Where("invitee.referer_id = ?", req.InviterId)
|
||||
}
|
||||
if req.InviteeId > 0 {
|
||||
db = db.Where("invitee.id = ?", req.InviteeId)
|
||||
}
|
||||
if req.Search != "" {
|
||||
search := "%" + req.Search + "%"
|
||||
db = db.Where(
|
||||
"(EXISTS (SELECT 1 FROM user_auth_methods inviter_auth WHERE inviter_auth.user_id = invitee.referer_id AND inviter_auth.auth_identifier LIKE ?) OR EXISTS (SELECT 1 FROM user_auth_methods invitee_auth WHERE invitee_auth.user_id = invitee.id AND invitee_auth.auth_identifier LIKE ?))",
|
||||
search,
|
||||
search,
|
||||
)
|
||||
}
|
||||
return db
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
promomodel "github.com/perfect-panel/server/internal/model/promo"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type CreateRuleLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewCreateRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateRuleLogic {
|
||||
return &CreateRuleLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *CreateRuleLogic) CreateRule(req *types.CreatePromoRuleRequest) (*types.PromoRule, error) {
|
||||
if err := validateRuleInput(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
params, err := paramsToString(req.Params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
enabled := true
|
||||
if req.Enabled != nil {
|
||||
enabled = *req.Enabled
|
||||
}
|
||||
rule := &promomodel.Rule{
|
||||
Name: req.Name,
|
||||
Type: req.Type,
|
||||
Params: params,
|
||||
Priority: req.Priority,
|
||||
Enabled: enabled,
|
||||
StartTime: unixPtrToTimePtr(req.StartTime),
|
||||
EndTime: unixPtrToTimePtr(req.EndTime),
|
||||
}
|
||||
if err := l.svcCtx.PromoModel.InsertRule(l.ctx, rule); err != nil {
|
||||
l.Errorw("[CreatePromoRule] Database Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create promo rule error: %v", err.Error())
|
||||
}
|
||||
if err := l.svcCtx.Redis.Del(l.ctx, ruleCacheKey).Err(); err != nil {
|
||||
l.Errorw("[CreatePromoRule] Delete Cache Error", logger.Field("error", err.Error()))
|
||||
}
|
||||
resp := convertRule(rule)
|
||||
return &resp, nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type DeletePriceLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewDeletePriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeletePriceLogic {
|
||||
return &DeletePriceLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *DeletePriceLogic) DeletePrice(req *types.DeletePromoPriceRequest) error {
|
||||
price, err := l.svcCtx.PromoModel.FindPrice(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
if stderrors.Is(err, gorm.ErrRecordNotFound) {
|
||||
l.Errorw("[DeletePromoPrice] Price Not Found", logger.Field("id", req.Id))
|
||||
return errors.Wrapf(xerr.NewErrCodeMsg(404, "promo price not found"), "promo price not found: %d", req.Id)
|
||||
}
|
||||
l.Errorw("[DeletePromoPrice] Find Price Error", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo price error: %v", err.Error())
|
||||
}
|
||||
if err := l.svcCtx.PromoModel.DeletePrice(l.ctx, req.Id); err != nil {
|
||||
l.Errorw("[DeletePromoPrice] Database Error", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo price error: %v", err.Error())
|
||||
}
|
||||
if err := l.svcCtx.Redis.Del(l.ctx, subscribePromoCacheKey(price.SubscribeId)).Err(); err != nil {
|
||||
l.Errorw("[DeletePromoPrice] Delete Cache Error", logger.Field("error", err.Error()))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type DeleteRuleLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewDeleteRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteRuleLogic {
|
||||
return &DeleteRuleLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *DeleteRuleLogic) DeleteRule(req *types.DeletePromoRuleRequest) error {
|
||||
if _, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id); err != nil {
|
||||
if stderrors.Is(err, gorm.ErrRecordNotFound) {
|
||||
l.Errorw("[DeletePromoRule] Rule Not Found", logger.Field("id", req.Id))
|
||||
return errors.Wrapf(xerr.NewErrCodeMsg(404, "promo rule not found"), "promo rule not found: %d", req.Id)
|
||||
}
|
||||
l.Errorw("[DeletePromoRule] Find Rule Error", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error())
|
||||
}
|
||||
if err := l.svcCtx.PromoModel.DeleteRule(l.ctx, req.Id); err != nil {
|
||||
l.Errorw("[DeletePromoRule] Database Error", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo rule error: %v", err.Error())
|
||||
}
|
||||
if err := l.svcCtx.Redis.Del(l.ctx, ruleCacheKey).Err(); err != nil {
|
||||
l.Errorw("[DeletePromoRule] Delete Cache Error", logger.Field("error", err.Error()))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
promomodel "github.com/perfect-panel/server/internal/model/promo"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
pkgerrors "github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type fakePromoModel struct{}
|
||||
|
||||
func (fakePromoModel) QueryEligibleRules(context.Context, int64, int64) ([]*promomodel.RuleWithPrice, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (fakePromoModel) InsertUsage(context.Context, *promomodel.Usage, ...*gorm.DB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fakePromoModel) InsertRule(context.Context, *promomodel.Rule) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fakePromoModel) FindRule(context.Context, int64) (*promomodel.Rule, error) {
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
func (fakePromoModel) UpdateRule(context.Context, *promomodel.Rule) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fakePromoModel) DeleteRule(context.Context, int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fakePromoModel) QueryRuleList(context.Context, int, int, string, *bool, string) (int64, []*promomodel.Rule, error) {
|
||||
return 0, nil, nil
|
||||
}
|
||||
|
||||
func (fakePromoModel) UpsertPrices(context.Context, int64, []*promomodel.SubscribePromo) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fakePromoModel) FindPrice(context.Context, int64) (*promomodel.SubscribePromo, error) {
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
func (fakePromoModel) DeletePrice(context.Context, int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fakePromoModel) QueryPriceList(context.Context, int64, int, int) (int64, []*promomodel.SubscribePromo, error) {
|
||||
return 0, nil, nil
|
||||
}
|
||||
|
||||
func (fakePromoModel) QueryUsageList(context.Context, promomodel.UsageFilter) (int64, []*promomodel.Usage, error) {
|
||||
return 0, nil, nil
|
||||
}
|
||||
|
||||
func (fakePromoModel) Transaction(context.Context, func(*gorm.DB) error) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestDeleteRuleNotFoundReturns404(t *testing.T) {
|
||||
svcCtx := &svc.ServiceContext{PromoModel: fakePromoModel{}}
|
||||
err := NewDeleteRuleLogic(context.Background(), svcCtx).DeleteRule(&types.DeletePromoRuleRequest{Id: 1})
|
||||
assertCodeError(t, err, 404)
|
||||
}
|
||||
|
||||
func TestDeletePriceNotFoundReturns404(t *testing.T) {
|
||||
svcCtx := &svc.ServiceContext{PromoModel: fakePromoModel{}}
|
||||
err := NewDeletePriceLogic(context.Background(), svcCtx).DeletePrice(&types.DeletePromoPriceRequest{Id: 1})
|
||||
assertCodeError(t, err, 404)
|
||||
}
|
||||
|
||||
func assertCodeError(t *testing.T, err error, want uint32) {
|
||||
t.Helper()
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
codeErr, ok := pkgerrors.Cause(err).(*xerr.CodeError)
|
||||
if !ok {
|
||||
t.Fatalf("expected CodeError, got %T", pkgerrors.Cause(err))
|
||||
}
|
||||
if got := codeErr.GetErrCode(); got != want {
|
||||
t.Fatalf("unexpected error code: got %d want %d", got, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetPriceListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewGetPriceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPriceListLogic {
|
||||
return &GetPriceListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetPriceListLogic) GetPriceList(req *types.GetPromoPriceListRequest) (*types.GetPromoPriceListResponse, error) {
|
||||
total, list, err := l.svcCtx.PromoModel.QueryPriceList(l.ctx, req.PromoRuleId, int(req.Page), int(req.Size))
|
||||
if err != nil {
|
||||
l.Errorw("[GetPromoPriceList] Database Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo price list error: %v", err.Error())
|
||||
}
|
||||
resp := &types.GetPromoPriceListResponse{
|
||||
Total: total,
|
||||
List: make([]types.PromoPrice, 0, len(list)),
|
||||
}
|
||||
for _, item := range list {
|
||||
resp.List = append(resp.List, convertPrice(item))
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetRuleDetailLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewGetRuleDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRuleDetailLogic {
|
||||
return &GetRuleDetailLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetRuleDetailLogic) GetRuleDetail(req *types.GetPromoRuleDetailRequest) (*types.PromoRule, error) {
|
||||
rule, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
l.Errorw("[GetPromoRuleDetail] Database Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo rule detail error: %v", err.Error())
|
||||
}
|
||||
resp := convertRule(rule)
|
||||
return &resp, nil
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetRuleListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewGetRuleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRuleListLogic {
|
||||
return &GetRuleListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetRuleListLogic) GetRuleList(req *types.GetPromoRuleListRequest) (*types.GetPromoRuleListResponse, error) {
|
||||
total, list, err := l.svcCtx.PromoModel.QueryRuleList(l.ctx, int(req.Page), int(req.Size), req.Type, req.Enabled, req.Search)
|
||||
if err != nil {
|
||||
l.Errorw("[GetPromoRuleList] Database Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo rule list error: %v", err.Error())
|
||||
}
|
||||
resp := &types.GetPromoRuleListResponse{
|
||||
Total: total,
|
||||
List: make([]types.PromoRule, 0, len(list)),
|
||||
}
|
||||
for _, item := range list {
|
||||
resp.List = append(resp.List, convertRule(item))
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
promomodel "github.com/perfect-panel/server/internal/model/promo"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type GetUsageListLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewGetUsageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUsageListLogic {
|
||||
return &GetUsageListLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *GetUsageListLogic) GetUsageList(req *types.GetPromoUsageListRequest) (*types.GetPromoUsageListResponse, error) {
|
||||
total, list, err := l.svcCtx.PromoModel.QueryUsageList(l.ctx, promomodel.UsageFilter{
|
||||
Page: int(req.Page),
|
||||
Size: int(req.Size),
|
||||
RuleId: req.RuleId,
|
||||
UserId: req.UserId,
|
||||
SubscribeId: req.SubscribeId,
|
||||
OrderNo: req.OrderNo,
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[GetPromoUsageList] Database Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo usage list error: %v", err.Error())
|
||||
}
|
||||
resp := &types.GetPromoUsageListResponse{
|
||||
Total: total,
|
||||
List: make([]types.PromoUsage, 0, len(list)),
|
||||
}
|
||||
for _, item := range list {
|
||||
resp.List = append(resp.List, convertUsage(item))
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
promomodel "github.com/perfect-panel/server/internal/model/promo"
|
||||
subscribeModel "github.com/perfect-panel/server/internal/model/subscribe"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type SetPriceLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewSetPriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SetPriceLogic {
|
||||
return &SetPriceLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *SetPriceLogic) SetPrice(req *types.SetPromoPriceRequest) error {
|
||||
if _, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.PromoRuleId); err != nil {
|
||||
l.Errorw("[SetPromoPrice] Find Rule Error", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error())
|
||||
}
|
||||
subscribeIds := make([]int64, 0, len(req.Items))
|
||||
seenSubscribeIds := make(map[int64]struct{}, len(req.Items))
|
||||
for _, item := range req.Items {
|
||||
if _, ok := seenSubscribeIds[item.SubscribeId]; ok {
|
||||
continue
|
||||
}
|
||||
seenSubscribeIds[item.SubscribeId] = struct{}{}
|
||||
subscribeIds = append(subscribeIds, item.SubscribeId)
|
||||
}
|
||||
var subscribes []*subscribeModel.Subscribe
|
||||
if err := l.svcCtx.DB.WithContext(l.ctx).Model(&subscribeModel.Subscribe{}).Where("id IN ?", subscribeIds).Find(&subscribes).Error; err != nil {
|
||||
l.Errorw("[SetPromoPrice] Find Subscribe Error", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find subscribe error: %v", err.Error())
|
||||
}
|
||||
subscribeById := make(map[int64]*subscribeModel.Subscribe, len(subscribes))
|
||||
for _, sub := range subscribes {
|
||||
subscribeById[sub.Id] = sub
|
||||
}
|
||||
items := make([]*promomodel.SubscribePromo, 0, len(req.Items))
|
||||
cacheKeys := make([]string, 0, len(req.Items))
|
||||
for _, item := range req.Items {
|
||||
sub, ok := subscribeById[item.SubscribeId]
|
||||
if !ok {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "subscribe plan not found")
|
||||
}
|
||||
originPrice := sub.UnitPrice * item.Quantity
|
||||
if item.PromoPrice >= originPrice {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "promo_price must be less than unit_price * quantity")
|
||||
}
|
||||
items = append(items, &promomodel.SubscribePromo{
|
||||
SubscribeId: item.SubscribeId,
|
||||
PromoRuleId: req.PromoRuleId,
|
||||
Quantity: item.Quantity,
|
||||
PromoPrice: item.PromoPrice,
|
||||
})
|
||||
cacheKeys = append(cacheKeys, subscribePromoCacheKey(item.SubscribeId))
|
||||
}
|
||||
if err := l.svcCtx.PromoModel.UpsertPrices(l.ctx, req.PromoRuleId, items); err != nil {
|
||||
l.Errorw("[SetPromoPrice] Database Error", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "set promo price error: %v", err.Error())
|
||||
}
|
||||
if len(cacheKeys) > 0 {
|
||||
if err := l.svcCtx.Redis.Del(l.ctx, cacheKeys...).Err(); err != nil {
|
||||
l.Errorw("[SetPromoPrice] Delete Cache Error", logger.Field("error", err.Error()))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
promomodel "github.com/perfect-panel/server/internal/model/promo"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
ruleCacheKey = "promo:rules:enabled"
|
||||
subscribeCachePref = "promo:subscribe:"
|
||||
)
|
||||
|
||||
func validateRuleInput(ruleType string, params map[string]interface{}, priority int64, startTime, endTime *int64) error {
|
||||
if priority < 0 {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "priority must be greater than or equal to 0")
|
||||
}
|
||||
if startTime != nil && endTime != nil && *startTime >= *endTime {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "start_time must be less than end_time")
|
||||
}
|
||||
switch ruleType {
|
||||
case "new_user":
|
||||
windowHours, ok := numberParam(params, "window_hours")
|
||||
if !ok || windowHours <= 0 {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "params.window_hours must be greater than 0")
|
||||
}
|
||||
case "inactive_user":
|
||||
inactiveMonths, ok := numberParam(params, "inactive_months")
|
||||
if !ok || inactiveMonths <= 0 {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "params.inactive_months must be greater than 0")
|
||||
}
|
||||
case "campaign":
|
||||
if params == nil {
|
||||
return nil
|
||||
}
|
||||
default:
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "unsupported promo rule type")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func numberParam(params map[string]interface{}, key string) (int64, bool) {
|
||||
if params == nil {
|
||||
return 0, false
|
||||
}
|
||||
value, ok := params[key]
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
switch v := value.(type) {
|
||||
case float64:
|
||||
if math.Trunc(v) != v {
|
||||
return 0, false
|
||||
}
|
||||
return int64(v), true
|
||||
case int64:
|
||||
return v, true
|
||||
case int:
|
||||
return int64(v), true
|
||||
case json.Number:
|
||||
n, err := v.Int64()
|
||||
return n, err == nil
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func paramsToString(params map[string]interface{}) (string, error) {
|
||||
if params == nil {
|
||||
params = map[string]interface{}{}
|
||||
}
|
||||
b, err := json.Marshal(params)
|
||||
if err != nil {
|
||||
return "", errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "invalid params")
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
func parseParams(data string) map[string]interface{} {
|
||||
if data == "" {
|
||||
return map[string]interface{}{}
|
||||
}
|
||||
var params map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(data), ¶ms); err != nil {
|
||||
return map[string]interface{}{}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func unixPtrToTimePtr(ts *int64) *time.Time {
|
||||
if ts == nil || *ts == 0 {
|
||||
return nil
|
||||
}
|
||||
t := time.Unix(*ts, 0)
|
||||
return &t
|
||||
}
|
||||
|
||||
func timePtrToUnixPtr(t *time.Time) *int64 {
|
||||
if t == nil {
|
||||
return nil
|
||||
}
|
||||
ts := t.Unix()
|
||||
return &ts
|
||||
}
|
||||
|
||||
func convertRule(item *promomodel.Rule) types.PromoRule {
|
||||
if item == nil {
|
||||
return types.PromoRule{}
|
||||
}
|
||||
return types.PromoRule{
|
||||
Id: item.Id,
|
||||
Name: item.Name,
|
||||
Type: item.Type,
|
||||
Params: parseParams(item.Params),
|
||||
Priority: item.Priority,
|
||||
Enabled: item.Enabled,
|
||||
StartTime: timePtrToUnixPtr(item.StartTime),
|
||||
EndTime: timePtrToUnixPtr(item.EndTime),
|
||||
CreatedAt: item.CreatedAt.Unix(),
|
||||
UpdatedAt: item.UpdatedAt.Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
func convertPrice(item *promomodel.SubscribePromo) types.PromoPrice {
|
||||
if item == nil {
|
||||
return types.PromoPrice{}
|
||||
}
|
||||
return types.PromoPrice{
|
||||
Id: item.Id,
|
||||
SubscribeId: item.SubscribeId,
|
||||
PromoRuleId: item.PromoRuleId,
|
||||
Quantity: item.Quantity,
|
||||
PromoPrice: item.PromoPrice,
|
||||
CreatedAt: item.CreatedAt.Unix(),
|
||||
UpdatedAt: item.UpdatedAt.Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
func convertUsage(item *promomodel.Usage) types.PromoUsage {
|
||||
if item == nil {
|
||||
return types.PromoUsage{}
|
||||
}
|
||||
return types.PromoUsage{
|
||||
Id: item.Id,
|
||||
UserId: item.UserId,
|
||||
PromoRuleId: item.PromoRuleId,
|
||||
SubscribeId: item.SubscribeId,
|
||||
OrderNo: item.OrderNo,
|
||||
PromoPrice: item.PromoPrice,
|
||||
CreatedAt: item.CreatedAt.Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
func subscribePromoCacheKey(subscribeId int64) string {
|
||||
return fmt.Sprintf("%s%d", subscribeCachePref, subscribeId)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package promo
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type UpdateRuleLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewUpdateRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateRuleLogic {
|
||||
return &UpdateRuleLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *UpdateRuleLogic) UpdateRule(req *types.UpdatePromoRuleRequest) (*types.PromoRule, error) {
|
||||
if err := validateRuleInput(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rule, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id)
|
||||
if err != nil {
|
||||
l.Errorw("[UpdatePromoRule] Find Rule Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error())
|
||||
}
|
||||
params, err := paramsToString(req.Params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
enabled := rule.Enabled
|
||||
if req.Enabled != nil {
|
||||
enabled = *req.Enabled
|
||||
}
|
||||
rule.Name = req.Name
|
||||
rule.Type = req.Type
|
||||
rule.Params = params
|
||||
rule.Priority = req.Priority
|
||||
rule.Enabled = enabled
|
||||
rule.StartTime = unixPtrToTimePtr(req.StartTime)
|
||||
rule.EndTime = unixPtrToTimePtr(req.EndTime)
|
||||
if err := l.svcCtx.PromoModel.UpdateRule(l.ctx, rule); err != nil {
|
||||
l.Errorw("[UpdatePromoRule] Database Error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update promo rule error: %v", err.Error())
|
||||
}
|
||||
if err := l.svcCtx.Redis.Del(l.ctx, ruleCacheKey).Err(); err != nil {
|
||||
l.Errorw("[UpdatePromoRule] Delete Cache Error", logger.Field("error", err.Error()))
|
||||
}
|
||||
resp := convertRule(rule)
|
||||
return &resp, nil
|
||||
}
|
||||
@@ -80,7 +80,7 @@ func (l *ResetSortWithNodeLogic) ResetSortWithNode(req *types.ResetSortRequest)
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -80,7 +80,7 @@ func (l *ResetSortWithServerLogic) ResetSortWithServer(req *types.ResetSortReque
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()))
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -3,11 +3,13 @@ package user
|
||||
import (
|
||||
"context"
|
||||
|
||||
adminInvite "github.com/perfect-panel/server/internal/logic/admin/invite"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type GetAdminUserInviteListLogic struct {
|
||||
@@ -25,15 +27,7 @@ func NewGetAdminUserInviteListLogic(ctx context.Context, svcCtx *svc.ServiceCont
|
||||
}
|
||||
|
||||
func (l *GetAdminUserInviteListLogic) GetAdminUserInviteList(req *types.GetAdminUserInviteListRequest) (resp *types.GetAdminUserInviteListResponse, err error) {
|
||||
if req.Page < 1 {
|
||||
req.Page = 1
|
||||
}
|
||||
if req.Size < 1 {
|
||||
req.Size = 10
|
||||
}
|
||||
if req.Size > 100 {
|
||||
req.Size = 100
|
||||
}
|
||||
req.Page, req.Size = adminInvite.NormalizePage(req.Page, req.Size)
|
||||
|
||||
type InvitedUser struct {
|
||||
Id int64 `gorm:"column:id"`
|
||||
@@ -44,19 +38,19 @@ func (l *GetAdminUserInviteListLogic) GetAdminUserInviteList(req *types.GetAdmin
|
||||
}
|
||||
|
||||
var total int64
|
||||
baseQuery := l.svcCtx.DB.WithContext(l.ctx).
|
||||
baseQuery := applyAdminUserInviteFilters(l.svcCtx.DB.WithContext(l.ctx).
|
||||
Table("user u").
|
||||
Where("u.referer_id = ? AND u.deleted_at IS NULL", req.UserId)
|
||||
Where("u.referer_id = ? AND u.deleted_at IS NULL", req.UserId), req)
|
||||
|
||||
if err = baseQuery.Count(&total).Error; err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count invited users failed: %v", err)
|
||||
}
|
||||
|
||||
var rows []InvitedUser
|
||||
err = l.svcCtx.DB.WithContext(l.ctx).
|
||||
err = applyAdminUserInviteFilters(l.svcCtx.DB.WithContext(l.ctx).
|
||||
Table("user u").
|
||||
Select("u.id, u.avatar, u.enable, UNIX_TIMESTAMP(u.created_at) as created_at, COALESCE((SELECT uam.auth_identifier FROM user_auth_methods uam WHERE uam.user_id = u.id ORDER BY uam.id ASC LIMIT 1), '') as identifier").
|
||||
Where("u.referer_id = ? AND u.deleted_at IS NULL", req.UserId).
|
||||
Where("u.referer_id = ? AND u.deleted_at IS NULL", req.UserId), req).
|
||||
Order("u.created_at DESC").
|
||||
Limit(req.Size).
|
||||
Offset((req.Page - 1) * req.Size).
|
||||
@@ -65,14 +59,29 @@ func (l *GetAdminUserInviteListLogic) GetAdminUserInviteList(req *types.GetAdmin
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invited users failed: %v", err)
|
||||
}
|
||||
|
||||
relations := make([]adminInvite.InviteRelation, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
relations = append(relations, adminInvite.InviteRelation{InviteeId: r.Id, InviterId: req.UserId})
|
||||
}
|
||||
benefits, err := adminInvite.QueryBenefits(l.ctx, l.svcCtx.DB, relations)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
list := make([]types.AdminInvitedUser, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
benefit := benefits[r.Id]
|
||||
list = append(list, types.AdminInvitedUser{
|
||||
Id: r.Id,
|
||||
Avatar: r.Avatar,
|
||||
Identifier: r.Identifier,
|
||||
Enable: r.Enable,
|
||||
CreatedAt: r.CreatedAt,
|
||||
Id: r.Id,
|
||||
Avatar: r.Avatar,
|
||||
Identifier: r.Identifier,
|
||||
Enable: r.Enable,
|
||||
CreatedAt: r.CreatedAt,
|
||||
OrderCount: benefit.OrderCount,
|
||||
HasPurchased: benefit.HasPurchased,
|
||||
InviterCommission: benefit.InviterCommission,
|
||||
InviterGiftDays: benefit.InviterGiftDays,
|
||||
InviteeGiftDays: benefit.InviteeGiftDays,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -81,3 +90,16 @@ func (l *GetAdminUserInviteListLogic) GetAdminUserInviteList(req *types.GetAdmin
|
||||
List: list,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func applyAdminUserInviteFilters(db *gorm.DB, req *types.GetAdminUserInviteListRequest) *gorm.DB {
|
||||
if req.Search != "" {
|
||||
db = db.Where("EXISTS (SELECT 1 FROM user_auth_methods uam WHERE uam.user_id = u.id AND uam.auth_identifier LIKE ?)", "%"+req.Search+"%")
|
||||
}
|
||||
if req.Enable != nil {
|
||||
db = db.Where("u.enable = ?", *req.Enable)
|
||||
}
|
||||
if req.UserIdSearch > 0 {
|
||||
db = db.Where("u.id = ?", req.UserIdSearch)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/group"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
@@ -36,6 +37,13 @@ func (l *GetUserSubscribeByIdLogic) GetUserSubscribeById(req *types.GetUserSubsc
|
||||
}
|
||||
var subscribeDetails types.UserSubscribeDetail
|
||||
tool.DeepCopy(&subscribeDetails, sub)
|
||||
subscribeDetails.SpeedLimit = sub.SpeedLimit
|
||||
if sub.TrafficLimit != nil && *sub.TrafficLimit != "" {
|
||||
_ = json.Unmarshal([]byte(*sub.TrafficLimit), &subscribeDetails.TrafficLimit)
|
||||
}
|
||||
if sub.Subscribe != nil {
|
||||
subscribeDetails.PlanSpeedLimit = sub.Subscribe.SpeedLimit
|
||||
}
|
||||
|
||||
// 填充分组名
|
||||
if sub.NodeGroupId > 0 {
|
||||
@@ -47,7 +55,17 @@ func (l *GetUserSubscribeByIdLogic) GetUserSubscribeById(req *types.GetUserSubsc
|
||||
|
||||
// Calculate speed limit status
|
||||
if sub.Subscribe != nil && sub.Status == 1 {
|
||||
result := speedlimit.Calculate(l.ctx, l.svcCtx.DB, sub.UserId, sub.Id, sub.Subscribe.SpeedLimit, sub.Subscribe.TrafficLimit)
|
||||
baseSpeed := sub.Subscribe.SpeedLimit
|
||||
if sub.SpeedLimit > 0 {
|
||||
baseSpeed = sub.SpeedLimit
|
||||
}
|
||||
|
||||
trafficLimit := sub.Subscribe.TrafficLimit
|
||||
if sub.TrafficLimit != nil && *sub.TrafficLimit != "" {
|
||||
trafficLimit = *sub.TrafficLimit
|
||||
}
|
||||
|
||||
result := speedlimit.Calculate(l.ctx, l.svcCtx.DB, sub.UserId, sub.Id, baseSpeed, trafficLimit)
|
||||
subscribeDetails.EffectiveSpeed = result.EffectiveSpeed
|
||||
subscribeDetails.IsThrottled = result.IsThrottled
|
||||
subscribeDetails.ThrottleRule = result.ThrottleRule
|
||||
|
||||
@@ -42,6 +42,9 @@ func (l *GetWithdrawalListLogic) GetWithdrawalList(req *types.GetWithdrawalListR
|
||||
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 {
|
||||
@@ -62,6 +65,9 @@ func (l *GetWithdrawalListLogic) GetWithdrawalList(req *types.GetWithdrawalListR
|
||||
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(),
|
||||
})
|
||||
|
||||
@@ -46,13 +46,13 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
|
||||
}
|
||||
|
||||
err = l.svcCtx.UserModel.Transaction(l.ctx, func(tx *gorm.DB) error {
|
||||
if userInfo.Balance != req.Balance {
|
||||
change := req.Balance - userInfo.Balance
|
||||
if req.Balance != nil && userInfo.Balance != *req.Balance {
|
||||
change := *req.Balance - userInfo.Balance
|
||||
balanceLog := log.Balance{
|
||||
Type: log.BalanceTypeAdjust,
|
||||
Amount: change,
|
||||
OrderNo: "",
|
||||
Balance: req.Balance,
|
||||
Balance: *req.Balance,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
}
|
||||
content, _ := balanceLog.Marshal()
|
||||
@@ -66,14 +66,14 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
userInfo.Balance = req.Balance
|
||||
userInfo.Balance = *req.Balance
|
||||
}
|
||||
|
||||
if userInfo.GiftAmount != req.GiftAmount {
|
||||
change := req.GiftAmount - userInfo.GiftAmount
|
||||
if req.GiftAmount != nil && userInfo.GiftAmount != *req.GiftAmount {
|
||||
change := *req.GiftAmount - userInfo.GiftAmount
|
||||
if change != 0 {
|
||||
var changeType uint16
|
||||
if userInfo.GiftAmount < req.GiftAmount {
|
||||
if userInfo.GiftAmount < *req.GiftAmount {
|
||||
changeType = log.GiftTypeIncrease
|
||||
} else {
|
||||
changeType = log.GiftTypeReduce
|
||||
@@ -81,7 +81,7 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
|
||||
giftLog := log.Gift{
|
||||
Type: changeType,
|
||||
Amount: change,
|
||||
Balance: req.GiftAmount,
|
||||
Balance: *req.GiftAmount,
|
||||
Remark: "Admin adjustment",
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
}
|
||||
@@ -96,23 +96,27 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
userInfo.GiftAmount = req.GiftAmount
|
||||
userInfo.GiftAmount = *req.GiftAmount
|
||||
}
|
||||
}
|
||||
|
||||
if req.Commission != userInfo.Commission {
|
||||
if isWithdrawalScene(req.Remark) {
|
||||
if req.Commission != nil && *req.Commission != userInfo.Commission {
|
||||
remark := ""
|
||||
if req.Remark != nil {
|
||||
remark = *req.Remark
|
||||
}
|
||||
if isWithdrawalScene(remark) {
|
||||
logWithdrawalGuard(l.Logger, userInfo.Id)
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "commission overwrite is blocked in withdrawal scene")
|
||||
}
|
||||
change := req.Commission - userInfo.Commission
|
||||
change := *req.Commission - userInfo.Commission
|
||||
if err = l.svcCtx.UserModel.UpdateCommission(l.ctx, userInfo.Id, change, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = logicCommon.WriteCommissionLog(tx, userInfo.Id, log.CommissionTypeAdjust, change, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
userInfo.Commission = req.Commission
|
||||
userInfo.Commission = *req.Commission
|
||||
}
|
||||
if req.Avatar != "" {
|
||||
userInfo.Avatar = req.Avatar
|
||||
@@ -120,15 +124,17 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
|
||||
if req.ReferCode != "" {
|
||||
userInfo.ReferCode = req.ReferCode
|
||||
}
|
||||
userInfo.RefererId = req.RefererId
|
||||
if req.RefererId != nil {
|
||||
userInfo.RefererId = *req.RefererId
|
||||
}
|
||||
if req.Enable != nil {
|
||||
userInfo.Enable = req.Enable
|
||||
}
|
||||
if req.IsAdmin != nil {
|
||||
userInfo.IsAdmin = req.IsAdmin
|
||||
}
|
||||
if req.Remark != "" {
|
||||
userInfo.Remark = req.Remark
|
||||
if req.Remark != nil {
|
||||
userInfo.Remark = *req.Remark
|
||||
}
|
||||
if req.OnlyFirstPurchase != nil {
|
||||
userInfo.OnlyFirstPurchase = req.OnlyFirstPurchase
|
||||
|
||||
@@ -39,22 +39,32 @@ func (l *UpdateUserSubscribeLogic) UpdateUserSubscribe(req *types.UpdateUserSubs
|
||||
} else {
|
||||
userSub.Status = 1
|
||||
}
|
||||
speedLimit := userSub.SpeedLimit
|
||||
if req.SpeedLimit != nil {
|
||||
speedLimit = *req.SpeedLimit
|
||||
}
|
||||
trafficLimit := userSub.TrafficLimit
|
||||
if req.TrafficLimit != nil {
|
||||
trafficLimit = req.TrafficLimit
|
||||
}
|
||||
|
||||
err = l.svcCtx.UserModel.UpdateSubscribe(l.ctx, &user.Subscribe{
|
||||
Id: userSub.Id,
|
||||
UserId: userSub.UserId,
|
||||
OrderId: userSub.OrderId,
|
||||
SubscribeId: req.SubscribeId,
|
||||
StartTime: userSub.StartTime,
|
||||
ExpireTime: time.UnixMilli(req.ExpiredAt),
|
||||
Traffic: req.Traffic,
|
||||
Download: req.Download,
|
||||
Upload: req.Upload,
|
||||
Token: userSub.Token,
|
||||
UUID: userSub.UUID,
|
||||
Status: userSub.Status,
|
||||
NodeGroupId: userSub.NodeGroupId,
|
||||
GroupLocked: userSub.GroupLocked,
|
||||
Id: userSub.Id,
|
||||
UserId: userSub.UserId,
|
||||
OrderId: userSub.OrderId,
|
||||
SubscribeId: req.SubscribeId,
|
||||
StartTime: userSub.StartTime,
|
||||
ExpireTime: time.UnixMilli(req.ExpiredAt),
|
||||
Traffic: req.Traffic,
|
||||
Download: req.Download,
|
||||
Upload: req.Upload,
|
||||
SpeedLimit: speedLimit,
|
||||
TrafficLimit: trafficLimit,
|
||||
Token: userSub.Token,
|
||||
UUID: userSub.UUID,
|
||||
Status: userSub.Status,
|
||||
NodeGroupId: userSub.NodeGroupId,
|
||||
GroupLocked: userSub.GroupLocked,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
|
||||
@@ -12,10 +12,12 @@ import (
|
||||
"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 {
|
||||
return svcCtx.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) 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" {
|
||||
@@ -24,26 +26,50 @@ func approveWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdraw
|
||||
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 = 0", withdrawalID).
|
||||
Where("id = ? AND status = ?", withdrawalID, usermodel.WithdrawalStatusPending).
|
||||
Updates(map[string]interface{}{
|
||||
"status": 1,
|
||||
"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 {
|
||||
withdrawal, err := logicCommon.LoadPendingWithdrawalForUpdate(ctx, tx, withdrawalID)
|
||||
_, 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)
|
||||
@@ -51,23 +77,14 @@ func rejectWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdrawa
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load withdrawal failed: %v", err)
|
||||
}
|
||||
|
||||
if err := tx.Model(&usermodel.Withdrawal{}).
|
||||
Where("id = ? AND status = 0", withdrawalID).
|
||||
// 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": 2,
|
||||
"status": usermodel.WithdrawalStatusRejected,
|
||||
"reason": reason,
|
||||
}).Error; err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "reject withdrawal failed: %v", err)
|
||||
}
|
||||
|
||||
if err := svcCtx.UserModel.UpdateCommission(ctx, withdrawal.UserId, withdrawal.Amount, tx); err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "refund commission failed: %v", err)
|
||||
}
|
||||
|
||||
if err := logicCommon.WriteCommissionLog(tx, withdrawal.UserId, log.CommissionTypeWithdrawReject, withdrawal.Amount, ""); err != nil {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "write commission log failed: %v", err)
|
||||
}
|
||||
return nil
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/promo"
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type PromoResult struct {
|
||||
Eligible bool
|
||||
RuleID int64
|
||||
RuleName string
|
||||
RuleType string
|
||||
PromoPrice int64
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type promoRuleParams struct {
|
||||
WindowHours int `json:"window_hours"`
|
||||
InactiveMonths int `json:"inactive_months"`
|
||||
}
|
||||
|
||||
func EvaluatePromo(ctx context.Context, svcCtx *svc.ServiceContext, userID int64, subscribeID int64, quantity int64) (*PromoResult, error) {
|
||||
result := &PromoResult{}
|
||||
if svcCtx == nil || svcCtx.PromoModel == nil || svcCtx.DB == nil || userID <= 0 || subscribeID <= 0 || quantity <= 0 {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
rules, err := svcCtx.PromoModel.QueryEligibleRules(ctx, subscribeID, quantity)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo rules failed: %v", err.Error())
|
||||
}
|
||||
if len(rules) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
var currentUser user.User
|
||||
now := time.Now()
|
||||
for _, rule := range rules {
|
||||
if rule == nil || !isPromoRuleInTimeWindow(rule, now) {
|
||||
continue
|
||||
}
|
||||
if rule.PromoPrice <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
params := promoRuleParams{}
|
||||
if rule.Params != "" {
|
||||
if err = json.Unmarshal([]byte(rule.Params), ¶ms); err != nil {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
eligible, expiresAt, err := evaluatePromoRule(ctx, svcCtx.DB, rule, params, userID, ¤tUser, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !eligible {
|
||||
continue
|
||||
}
|
||||
|
||||
return &PromoResult{
|
||||
Eligible: true,
|
||||
RuleID: rule.Id,
|
||||
RuleName: rule.Name,
|
||||
RuleType: rule.Type,
|
||||
PromoPrice: rule.PromoPrice,
|
||||
ExpiresAt: expiresAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func isPromoRuleInTimeWindow(rule *promo.RuleWithPrice, now time.Time) bool {
|
||||
if rule.StartTime != nil && !rule.StartTime.IsZero() && now.Before(*rule.StartTime) {
|
||||
return false
|
||||
}
|
||||
if rule.EndTime != nil && !rule.EndTime.IsZero() && now.After(*rule.EndTime) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func evaluatePromoRule(
|
||||
ctx context.Context,
|
||||
db *gorm.DB,
|
||||
rule *promo.RuleWithPrice,
|
||||
params promoRuleParams,
|
||||
userID int64,
|
||||
currentUser *user.User,
|
||||
now time.Time,
|
||||
) (bool, time.Time, error) {
|
||||
switch rule.Type {
|
||||
case promo.RuleTypeNewUser:
|
||||
return evaluateNewUserPromo(ctx, db, params, userID, currentUser, now)
|
||||
case promo.RuleTypeInactiveUser:
|
||||
return evaluateInactiveUserPromo(ctx, db, params, userID, promoRuleExpiresAt(rule), now)
|
||||
case promo.RuleTypeCampaign:
|
||||
return true, promoRuleExpiresAt(rule), nil
|
||||
default:
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func evaluateNewUserPromo(
|
||||
ctx context.Context,
|
||||
db *gorm.DB,
|
||||
params promoRuleParams,
|
||||
userID int64,
|
||||
currentUser *user.User,
|
||||
now time.Time,
|
||||
) (bool, time.Time, error) {
|
||||
if params.WindowHours <= 0 {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
|
||||
if currentUser.Id == 0 {
|
||||
if err := db.WithContext(ctx).Model(&user.User{}).Where("id = ?", userID).First(currentUser).Error; err != nil {
|
||||
return false, time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo user failed")
|
||||
}
|
||||
}
|
||||
|
||||
expiresAt := currentUser.CreatedAt.Add(time.Duration(params.WindowHours) * time.Hour)
|
||||
return now.Before(expiresAt), expiresAt, nil
|
||||
}
|
||||
|
||||
func evaluateInactiveUserPromo(
|
||||
ctx context.Context,
|
||||
db *gorm.DB,
|
||||
params promoRuleParams,
|
||||
userID int64,
|
||||
ruleExpiresAt time.Time,
|
||||
now time.Time,
|
||||
) (bool, time.Time, error) {
|
||||
if params.InactiveMonths <= 0 {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
|
||||
var lastSub user.Subscribe
|
||||
err := db.WithContext(ctx).
|
||||
Model(&user.Subscribe{}).
|
||||
Where("user_id = ?", userID).
|
||||
Order(clause.OrderBy{
|
||||
Expression: clause.Expr{
|
||||
SQL: "CASE WHEN expire_time = ? THEN 0 ELSE 1 END, expire_time DESC",
|
||||
Vars: []interface{}{time.UnixMilli(0)},
|
||||
},
|
||||
}).
|
||||
Limit(1).
|
||||
Take(&lastSub).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return true, ruleExpiresAt, nil
|
||||
}
|
||||
return false, time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo inactive user subscription failed")
|
||||
}
|
||||
|
||||
return evaluateInactiveUserExpire(lastSub.ExpireTime, params, now), ruleExpiresAt, nil
|
||||
}
|
||||
|
||||
func evaluateInactiveUserExpire(lastExpire time.Time, params promoRuleParams, now time.Time) bool {
|
||||
if lastExpire.Equal(time.UnixMilli(0)) {
|
||||
return false
|
||||
}
|
||||
|
||||
threshold := now.AddDate(0, -params.InactiveMonths, 0)
|
||||
return lastExpire.Before(threshold) || lastExpire.Equal(threshold)
|
||||
}
|
||||
|
||||
func promoRuleExpiresAt(rule *promo.RuleWithPrice) time.Time {
|
||||
if rule != nil && rule.EndTime != nil {
|
||||
return *rule.EndTime
|
||||
}
|
||||
return time.Time{}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestEvaluateInactiveUserExpire(t *testing.T) {
|
||||
now := time.Date(2026, 5, 27, 8, 0, 0, 0, time.UTC)
|
||||
params := promoRuleParams{InactiveMonths: 3}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
lastExpire time.Time
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "permanent subscription is not inactive",
|
||||
lastExpire: time.UnixMilli(0),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "active subscription is not inactive",
|
||||
lastExpire: now.Add(time.Hour),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "expire at threshold is inactive",
|
||||
lastExpire: now.AddDate(0, -3, 0),
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "expire before threshold is inactive",
|
||||
lastExpire: now.AddDate(0, -3, -1),
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := evaluateInactiveUserExpire(tt.lastExpire, params, now); got != tt.want {
|
||||
t.Fatalf("evaluateInactiveUserExpire() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ func LoadPendingWithdrawalForUpdate(ctx context.Context, tx *gorm.DB, withdrawal
|
||||
First(&withdrawal).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if withdrawal.Status != 0 {
|
||||
if withdrawal.Status != usermodel.WithdrawalStatusPending {
|
||||
return nil, errors.New("withdrawal status invalid")
|
||||
}
|
||||
return &withdrawal, nil
|
||||
|
||||
@@ -3,17 +3,20 @@ package notify
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
||||
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/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
iapapple "github.com/perfect-panel/server/pkg/iap/apple"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/tool"
|
||||
"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))
|
||||
return e
|
||||
}
|
||||
existing = rec
|
||||
} else {
|
||||
if txPayload.RevocationDate != nil {
|
||||
// 撤销场景:更新 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
|
||||
{
|
||||
pid := strings.ToLower(txPayload.ProductId)
|
||||
@@ -169,7 +199,12 @@ func (l *AppleIAPNotifyLogic) Handle(signedPayload string) error {
|
||||
}
|
||||
}
|
||||
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
|
||||
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),
|
||||
)...,
|
||||
)
|
||||
// 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
|
||||
}
|
||||
}
|
||||
@@ -248,7 +288,52 @@ func (l *AppleIAPNotifyLogic) Handle(signedPayload string) error {
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
@@ -80,7 +80,7 @@ func validateInitRequest(svcCtx *svc.ServiceContext, bizType, fileName, contentT
|
||||
allowed := allowedContentTypeSet(svcCtx.Config.S3.AllowedContentTypes)
|
||||
if len(allowed) > 0 {
|
||||
if _, ok := allowed[strings.ToLower(strings.TrimSpace(contentType))]; !ok {
|
||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "content_type is not allowed")
|
||||
return errors.Wrapf(xerr.NewErrCodeMsg(xerr.InvalidParams, "content_type is not allowed"), "content_type is not allowed")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"mime/multipart"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/perfect-panel/server/internal/config"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/pkg/storage"
|
||||
)
|
||||
|
||||
const testAllowedContentTypes = "application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json,image/jpeg,image/jpg,image/png,image/webp,image/gif,image/heic,image/heif,image/bmp"
|
||||
|
||||
type testMultipartFile struct {
|
||||
*strings.Reader
|
||||
}
|
||||
|
||||
func (testMultipartFile) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestValidateInitRequestAllowedContentTypes(t *testing.T) {
|
||||
svcCtx := &svc.ServiceContext{
|
||||
Config: config.Config{
|
||||
S3: config.S3Config{
|
||||
Enable: true,
|
||||
MaxUploadSize: 1024,
|
||||
AllowedContentTypes: testAllowedContentTypes,
|
||||
},
|
||||
},
|
||||
S3Store: &storage.S3Store{},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
contentType string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "allow jpeg", contentType: "image/jpeg"},
|
||||
{name: "allow png", contentType: "image/png"},
|
||||
{name: "allow webp", contentType: "image/webp"},
|
||||
{name: "reject unknown", contentType: "application/x-sh", wantErr: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := validateInitRequest(svcCtx, "app-package", "demo.bin", tt.contentType, 10)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "content_type is not allowed") {
|
||||
t.Fatalf("expected content type error, got %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("expected nil error, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSniffContentTypeDetectsCommonImages(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
data string
|
||||
want string
|
||||
}{
|
||||
{name: "jpeg", data: "\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01", want: "image/jpeg"},
|
||||
{name: "png", data: "\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR", want: "image/png"},
|
||||
{name: "webp", data: "RIFF\x1a\x00\x00\x00WEBPVP8 \x0e\x00\x00\x00", want: "image/webp"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
file := testMultipartFile{Reader: strings.NewReader(tt.data)}
|
||||
got, err := sniffContentType(&multipart.FileHeader{}, file)
|
||||
if err != nil {
|
||||
t.Fatalf("expected nil error, got %v", err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("expected %q, got %q", tt.want, got)
|
||||
}
|
||||
if pos, err := file.Seek(0, 1); err != nil || pos != 0 {
|
||||
t.Fatalf("expected reader reset to start, pos=%d err=%v", pos, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -61,11 +61,6 @@ func (l *FileUploadCompleteLogic) FileUploadComplete(req *types.FileUploadComple
|
||||
}
|
||||
|
||||
return &types.FileUploadCompleteResponse{
|
||||
FileId: meta.FileID,
|
||||
ObjectKey: meta.ObjectKey,
|
||||
Size: head.ContentLength,
|
||||
ContentType: head.ContentType,
|
||||
Etag: head.ETag,
|
||||
Status: meta.Status,
|
||||
Url: l.svcCtx.S3Store.BuildObjectURL(meta.ObjectKey),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -52,20 +52,13 @@ func (l *FileUploadLogic) FileUpload(req *types.FileUploadRequest, fileHeader *m
|
||||
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 {
|
||||
if _, err := l.svcCtx.S3Store.PutObject(l.ctx, objectKey, file, fileHeader.Size, contentType); 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,
|
||||
Url: l.svcCtx.S3Store.BuildObjectURL(objectKey),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
|
||||
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
||||
"github.com/perfect-panel/server/internal/model/order"
|
||||
@@ -48,13 +47,18 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
||||
l.Debugf("[PreCreateOrder] Quantity is less than or equal to 0, setting to 1")
|
||||
req.Quantity = 1
|
||||
}
|
||||
entitlement, entErr := commonLogic.ResolveEntitlementUser(l.ctx, l.svcCtx.DB, u.Id)
|
||||
if entErr != nil {
|
||||
return nil, entErr
|
||||
}
|
||||
|
||||
targetSubscribeID := req.SubscribeId
|
||||
orderType := uint8(1)
|
||||
isSingleModeRenewal := false
|
||||
decision, routeErr := commonLogic.ResolvePurchaseRoute(
|
||||
l.ctx,
|
||||
l.svcCtx.Config.Subscribe.SingleModel,
|
||||
u.Id,
|
||||
entitlement.EffectiveUserID,
|
||||
req.SubscribeId,
|
||||
l.svcCtx.UserModel.FindSingleModeAnchorSubscribe,
|
||||
)
|
||||
@@ -69,15 +73,44 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
||||
targetSubscribeID = decision.ResolvedSubscribeID
|
||||
isSingleModeRenewal = decision.Route == commonLogic.PurchaseRoutePurchaseToRenewal
|
||||
if isSingleModeRenewal && decision.Anchor != nil {
|
||||
orderType = 2
|
||||
l.Infow("[PreCreateOrder] single mode purchase routed to renewal preview",
|
||||
logger.Field("mode", "single"),
|
||||
logger.Field("route", "purchase_to_renewal"),
|
||||
logger.Field("anchor_user_subscribe_id", decision.Anchor.Id),
|
||||
logger.Field("user_id", u.Id),
|
||||
logger.Field("effective_user_id", entitlement.EffectiveUserID),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Keep promo eligibility preview aligned with Purchase: an existing paid subscription
|
||||
// routes the request to renewal semantics, where first-purchase promos are disabled.
|
||||
if !l.svcCtx.Config.Subscribe.SingleModel && orderType == 1 {
|
||||
var existSub user.Subscribe
|
||||
if e := l.svcCtx.DB.WithContext(l.ctx).
|
||||
Model(&user.Subscribe{}).
|
||||
Where("user_id = ? AND token != '' AND (order_id > 0 OR token LIKE 'iap:%')", entitlement.EffectiveUserID).
|
||||
Order("expire_time DESC").
|
||||
Order("updated_at DESC").
|
||||
Order("id DESC").
|
||||
First(&existSub).Error; e == nil && existSub.Id > 0 && existSub.Token != "" {
|
||||
orderType = 2
|
||||
l.Infow("[PreCreateOrder] purchase preview routed to renewal because an existing subscription was found",
|
||||
logger.Field("route_mode", "global_single_subscription"),
|
||||
logger.Field("route", "purchase_to_existing_subscription"),
|
||||
logger.Field("existing_subscribe_id", existSub.Id),
|
||||
logger.Field("existing_status", existSub.Status),
|
||||
logger.Field("user_id", u.Id),
|
||||
logger.Field("effective_user_id", entitlement.EffectiveUserID),
|
||||
logger.Field("resolved_subscribe_id", targetSubscribeID),
|
||||
)
|
||||
} else if e != nil && !errors.Is(e, gorm.ErrRecordNotFound) {
|
||||
l.Errorw("[PreCreateOrder] Database query error", logger.Field("error", e.Error()), logger.Field("user_id", u.Id))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find existing subscription error: %v", e.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// find subscribe plan
|
||||
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, targetSubscribeID)
|
||||
if err != nil {
|
||||
@@ -87,7 +120,7 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
||||
|
||||
// check subscribe plan quota limit for new purchase flow only
|
||||
if !isSingleModeRenewal && sub.Quota > 0 {
|
||||
userSub, err := l.svcCtx.UserModel.QueryUserSubscribe(l.ctx, u.Id)
|
||||
userSub, err := l.svcCtx.UserModel.QueryUserSubscribe(l.ctx, entitlement.EffectiveUserID)
|
||||
if err != nil {
|
||||
l.Errorw("[PreCreateOrder] Database query error", logger.Field("error", err.Error()), logger.Field("user_id", u.Id))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user subscription error: %v", err.Error())
|
||||
@@ -103,7 +136,7 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
||||
}
|
||||
}
|
||||
|
||||
newUserDiscount, err := resolveNewUserDiscountEligibility(l.ctx, l.svcCtx.DB, u.Id, targetSubscribeID, req.Quantity, sub.Discount)
|
||||
newUserDiscount, err := resolveNewUserDiscountEligibility(l.ctx, l.svcCtx.DB, entitlement.EffectiveUserID, targetSubscribeID, req.Quantity, sub.Discount)
|
||||
if err != nil {
|
||||
l.Errorw("[PreCreateOrder] Database query error resolving new user eligibility",
|
||||
logger.Field("error", err.Error()),
|
||||
@@ -115,14 +148,28 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SubscribeNewUserOnly), "not a new user")
|
||||
}
|
||||
|
||||
var discount float64 = 1
|
||||
if len(newUserDiscount.Discounts) > 0 {
|
||||
discount = getDiscount(newUserDiscount.Discounts, req.Quantity, newUserDiscount.EligibleForDiscount)
|
||||
priceResult, err := calculatePurchasePrice(
|
||||
l.ctx,
|
||||
l.svcCtx,
|
||||
entitlement.EffectiveUserID,
|
||||
targetSubscribeID,
|
||||
sub.UnitPrice,
|
||||
req.Quantity,
|
||||
newUserDiscount.Discounts,
|
||||
newUserDiscount.EligibleForDiscount,
|
||||
orderType == 1,
|
||||
)
|
||||
if err != nil {
|
||||
l.Errorw("[PreCreateOrder] Promo price calculation error",
|
||||
logger.Field("error", err.Error()),
|
||||
logger.Field("user_id", u.Id),
|
||||
logger.Field("subscribe_id", targetSubscribeID),
|
||||
)
|
||||
return nil, err
|
||||
}
|
||||
price := sub.UnitPrice * req.Quantity
|
||||
|
||||
amount := int64(math.Round(float64(price) * discount))
|
||||
discountAmount := price - amount
|
||||
price := priceResult.OriginalPrice
|
||||
amount := priceResult.PayableBase
|
||||
discountAmount := priceResult.DiscountAmount
|
||||
var couponAmount int64
|
||||
if req.Coupon != "" {
|
||||
couponInfo, err := l.svcCtx.CouponModel.FindOneByCode(l.ctx, req.Coupon)
|
||||
@@ -185,6 +232,7 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
||||
Price: price,
|
||||
Amount: amount,
|
||||
Discount: discountAmount,
|
||||
PromoDiscount: priceResult.PromoDiscount,
|
||||
GiftAmount: deductionAmount,
|
||||
Coupon: req.Coupon,
|
||||
CouponDiscount: couponAmount,
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
|
||||
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
)
|
||||
|
||||
type orderPriceResult struct {
|
||||
OriginalPrice int64
|
||||
PayableBase int64
|
||||
DiscountAmount int64
|
||||
PromoRuleId int64
|
||||
PromoDiscount int64
|
||||
PromoPrice int64
|
||||
}
|
||||
|
||||
func calculatePurchasePrice(
|
||||
ctx context.Context,
|
||||
svcCtx *svc.ServiceContext,
|
||||
userID int64,
|
||||
subscribeID int64,
|
||||
unitPrice int64,
|
||||
quantity int64,
|
||||
discounts []types.SubscribeDiscount,
|
||||
eligibleForDiscount bool,
|
||||
allowPromo bool,
|
||||
) (*orderPriceResult, error) {
|
||||
originalPrice := unitPrice * quantity
|
||||
result := &orderPriceResult{
|
||||
OriginalPrice: originalPrice,
|
||||
PayableBase: originalPrice,
|
||||
}
|
||||
|
||||
if allowPromo {
|
||||
promoResult, err := commonLogic.EvaluatePromo(ctx, svcCtx, userID, subscribeID, quantity)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if promoResult != nil && promoResult.Eligible && promoResult.PromoPrice < originalPrice {
|
||||
result.PayableBase = promoResult.PromoPrice
|
||||
result.PromoRuleId = promoResult.RuleID
|
||||
result.PromoDiscount = originalPrice - result.PayableBase
|
||||
result.PromoPrice = promoResult.PromoPrice
|
||||
if result.PromoDiscount < 0 {
|
||||
result.PromoDiscount = 0
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
discount := float64(1)
|
||||
if len(discounts) > 0 {
|
||||
discount = getDiscount(discounts, quantity, eligibleForDiscount)
|
||||
}
|
||||
result.PayableBase = int64(math.Round(float64(originalPrice) * discount))
|
||||
result.DiscountAmount = originalPrice - result.PayableBase
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package order
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/promo"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type fakePromoModel struct {
|
||||
rules []*promo.RuleWithPrice
|
||||
lastSubscribeID int64
|
||||
lastQuantity int64
|
||||
requireQuantity int64
|
||||
quantityMismatch []*promo.RuleWithPrice
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) QueryEligibleRules(_ context.Context, subscribeID int64, quantity int64) ([]*promo.RuleWithPrice, error) {
|
||||
m.lastSubscribeID = subscribeID
|
||||
m.lastQuantity = quantity
|
||||
if m.requireQuantity > 0 && quantity != m.requireQuantity {
|
||||
return m.quantityMismatch, nil
|
||||
}
|
||||
return m.rules, nil
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) InsertUsage(context.Context, *promo.Usage, ...*gorm.DB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) InsertRule(context.Context, *promo.Rule) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) FindRule(context.Context, int64) (*promo.Rule, error) {
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) UpdateRule(context.Context, *promo.Rule) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) DeleteRule(context.Context, int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) QueryRuleList(context.Context, int, int, string, *bool, string) (int64, []*promo.Rule, error) {
|
||||
return 0, nil, nil
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) UpsertPrices(context.Context, int64, []*promo.SubscribePromo) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) FindPrice(context.Context, int64) (*promo.SubscribePromo, error) {
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) DeletePrice(context.Context, int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) QueryPriceList(context.Context, int64, int, int) (int64, []*promo.SubscribePromo, error) {
|
||||
return 0, nil, nil
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) QueryUsageList(context.Context, promo.UsageFilter) (int64, []*promo.Usage, error) {
|
||||
return 0, nil, nil
|
||||
}
|
||||
|
||||
func (m *fakePromoModel) Transaction(context.Context, func(*gorm.DB) error) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestCalculatePurchasePricePromoUsesQuantityTierTotalPrice(t *testing.T) {
|
||||
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
|
||||
{
|
||||
Rule: promo.Rule{
|
||||
Id: 9,
|
||||
Name: "campaign",
|
||||
Type: promo.RuleTypeCampaign,
|
||||
Enabled: true,
|
||||
},
|
||||
PromoPrice: 279,
|
||||
},
|
||||
}}
|
||||
svcCtx := &svc.ServiceContext{
|
||||
DB: &gorm.DB{},
|
||||
PromoModel: model,
|
||||
}
|
||||
|
||||
result, err := calculatePurchasePrice(
|
||||
context.Background(),
|
||||
svcCtx,
|
||||
1,
|
||||
2,
|
||||
100,
|
||||
7,
|
||||
[]types.SubscribeDiscount{{Quantity: 7, Discount: 50}},
|
||||
true,
|
||||
true,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("calculatePurchasePrice returned error: %v", err)
|
||||
}
|
||||
|
||||
if result.OriginalPrice != 700 {
|
||||
t.Fatalf("OriginalPrice = %d, want 700", result.OriginalPrice)
|
||||
}
|
||||
if result.PayableBase != 279 {
|
||||
t.Fatalf("PayableBase = %d, want 279", result.PayableBase)
|
||||
}
|
||||
if result.DiscountAmount != 0 {
|
||||
t.Fatalf("DiscountAmount = %d, want 0", result.DiscountAmount)
|
||||
}
|
||||
if result.PromoRuleId != 9 {
|
||||
t.Fatalf("PromoRuleId = %d, want 9", result.PromoRuleId)
|
||||
}
|
||||
if result.PromoDiscount != 421 {
|
||||
t.Fatalf("PromoDiscount = %d, want 421", result.PromoDiscount)
|
||||
}
|
||||
if result.PromoPrice != 279 {
|
||||
t.Fatalf("PromoPrice = %d, want 279", result.PromoPrice)
|
||||
}
|
||||
if model.lastQuantity != 7 {
|
||||
t.Fatalf("promo query quantity = %d, want 7", model.lastQuantity)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) {
|
||||
model := &fakePromoModel{rules: []*promo.RuleWithPrice{
|
||||
{
|
||||
Rule: promo.Rule{
|
||||
Id: 10,
|
||||
Name: "invalid campaign",
|
||||
Type: promo.RuleTypeCampaign,
|
||||
Enabled: true,
|
||||
},
|
||||
PromoPrice: 3000,
|
||||
},
|
||||
}}
|
||||
svcCtx := &svc.ServiceContext{
|
||||
DB: &gorm.DB{},
|
||||
PromoModel: model,
|
||||
}
|
||||
|
||||
result, err := calculatePurchasePrice(
|
||||
context.Background(),
|
||||
svcCtx,
|
||||
1,
|
||||
2,
|
||||
1000,
|
||||
3,
|
||||
[]types.SubscribeDiscount{{Quantity: 3, Discount: 50}},
|
||||
true,
|
||||
true,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("calculatePurchasePrice returned error: %v", err)
|
||||
}
|
||||
|
||||
if result.PayableBase != 1500 {
|
||||
t.Fatalf("PayableBase = %d, want 1500", result.PayableBase)
|
||||
}
|
||||
if result.DiscountAmount != 1500 {
|
||||
t.Fatalf("DiscountAmount = %d, want 1500", result.DiscountAmount)
|
||||
}
|
||||
if result.PromoRuleId != 0 || result.PromoDiscount != 0 {
|
||||
t.Fatalf("promo fields = (%d, %d), want (0, 0)", result.PromoRuleId, result.PromoDiscount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalculatePurchasePricePassesQuantityToPromoEvaluation(t *testing.T) {
|
||||
promoModel := &fakePromoModel{
|
||||
requireQuantity: 6,
|
||||
rules: []*promo.RuleWithPrice{
|
||||
{
|
||||
Rule: promo.Rule{
|
||||
Id: 11,
|
||||
Name: "quantity campaign",
|
||||
Type: promo.RuleTypeCampaign,
|
||||
Enabled: true,
|
||||
},
|
||||
PromoPrice: 3000,
|
||||
},
|
||||
},
|
||||
}
|
||||
svcCtx := &svc.ServiceContext{
|
||||
DB: &gorm.DB{},
|
||||
PromoModel: promoModel,
|
||||
}
|
||||
|
||||
result, err := calculatePurchasePrice(
|
||||
context.Background(),
|
||||
svcCtx,
|
||||
1,
|
||||
2,
|
||||
1000,
|
||||
6,
|
||||
[]types.SubscribeDiscount{{Quantity: 6, Discount: 80}},
|
||||
true,
|
||||
true,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("calculatePurchasePrice returned error: %v", err)
|
||||
}
|
||||
|
||||
if promoModel.lastSubscribeID != 2 {
|
||||
t.Fatalf("lastSubscribeID = %d, want 2", promoModel.lastSubscribeID)
|
||||
}
|
||||
if promoModel.lastQuantity != 6 {
|
||||
t.Fatalf("lastQuantity = %d, want 6", promoModel.lastQuantity)
|
||||
}
|
||||
if result.PayableBase != 3000 {
|
||||
t.Fatalf("PayableBase = %d, want 3000", result.PayableBase)
|
||||
}
|
||||
if result.PromoRuleId != 11 {
|
||||
t.Fatalf("PromoRuleId = %d, want 11", result.PromoRuleId)
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package order
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -204,14 +203,28 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var discount float64 = 1
|
||||
if len(newUserDiscount.Discounts) > 0 {
|
||||
discount = getDiscount(newUserDiscount.Discounts, req.Quantity, newUserDiscount.EligibleForDiscount)
|
||||
priceResult, err := calculatePurchasePrice(
|
||||
l.ctx,
|
||||
l.svcCtx,
|
||||
u.Id,
|
||||
targetSubscribeID,
|
||||
sub.UnitPrice,
|
||||
req.Quantity,
|
||||
newUserDiscount.Discounts,
|
||||
newUserDiscount.EligibleForDiscount,
|
||||
orderType == 1,
|
||||
)
|
||||
if err != nil {
|
||||
l.Errorw("[Purchase] Promo price calculation error",
|
||||
logger.Field("error", err.Error()),
|
||||
logger.Field("user_id", u.Id),
|
||||
logger.Field("subscribe_id", targetSubscribeID),
|
||||
)
|
||||
return nil, err
|
||||
}
|
||||
price := sub.UnitPrice * req.Quantity
|
||||
// discount amount
|
||||
amount := int64(math.Round(float64(price) * discount))
|
||||
discountAmount := price - amount
|
||||
price := priceResult.OriginalPrice
|
||||
amount := priceResult.PayableBase
|
||||
discountAmount := priceResult.DiscountAmount
|
||||
|
||||
// Validate amount to prevent overflow
|
||||
if amount > MaxOrderAmount {
|
||||
@@ -306,6 +319,8 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
|
||||
Price: price,
|
||||
Amount: amount,
|
||||
Discount: discountAmount,
|
||||
PromoRuleId: priceResult.PromoRuleId,
|
||||
PromoDiscount: priceResult.PromoDiscount,
|
||||
GiftAmount: deductionAmount,
|
||||
Coupon: req.Coupon,
|
||||
CouponDiscount: coupon,
|
||||
|
||||
@@ -154,9 +154,12 @@ func (l *PurchaseLogic) Purchase(req *types.PortalPurchaseRequest) (resp *types.
|
||||
}
|
||||
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 {
|
||||
l.Errorw("[Purchase] Redis set error", logger.Field("error", err.Error()), logger.Field("order_no", orderInfo.OrderNo))
|
||||
return err
|
||||
// Persist activation context to DB so the worker can recover if Redis TTL expires.
|
||||
orderInfo.ActivationContext = string(content)
|
||||
|
||||
// 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))
|
||||
|
||||
@@ -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 {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -151,34 +151,48 @@ func (l *RedeemCodeLogic) RedeemCode(req *types.RedeemCodeRequest) (resp *types.
|
||||
}
|
||||
|
||||
// 创建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{
|
||||
UserId: u.Id,
|
||||
OrderNo: tool.GenerateTradeNo(),
|
||||
Type: 5, // 兑换类型
|
||||
Quantity: redemptionCode.Quantity,
|
||||
Price: 0, // 兑换无价格
|
||||
Amount: 0, // 兑换无金额
|
||||
Discount: 0,
|
||||
GiftAmount: 0,
|
||||
Coupon: "",
|
||||
CouponDiscount: 0,
|
||||
PaymentId: 0,
|
||||
Method: "redemption",
|
||||
FeeAmount: 0,
|
||||
Commission: 0,
|
||||
Status: 2, // 直接设置为已支付
|
||||
SubscribeId: redemptionCode.SubscribePlan,
|
||||
IsNew: isNew,
|
||||
UserId: u.Id,
|
||||
OrderNo: tool.GenerateTradeNo(),
|
||||
Type: 5, // 兑换类型
|
||||
Quantity: redemptionCode.Quantity,
|
||||
Price: 0, // 兑换无价格
|
||||
Amount: 0, // 兑换无金额
|
||||
Discount: 0,
|
||||
GiftAmount: 0,
|
||||
Coupon: "",
|
||||
CouponDiscount: 0,
|
||||
PaymentId: 0,
|
||||
Method: "redemption",
|
||||
FeeAmount: 0,
|
||||
Commission: 0,
|
||||
Status: 2, // 直接设置为已支付
|
||||
SubscribeId: redemptionCode.SubscribePlan,
|
||||
IsNew: isNew,
|
||||
ActivationContext: string(activationContextJSON),
|
||||
}
|
||||
|
||||
// 保存Order到数据库
|
||||
// 保存Order到数据库(activation_context 同步写入,作为 Redis 的持久化兜底)
|
||||
err = l.svcCtx.OrderModel.Insert(l.ctx, orderInfo)
|
||||
if err != nil {
|
||||
l.Errorw("[RedeemCode] Create order failed", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create order failed")
|
||||
}
|
||||
|
||||
// 缓存兑换码信息到Redis(供队列任务使用)
|
||||
// 缓存兑换码信息到Redis(热缓存,供队列任务快速读取,非关键路径)
|
||||
cacheKey := fmt.Sprintf("redemption_order:%s", orderInfo.OrderNo)
|
||||
cacheData := map[string]interface{}{
|
||||
"redemption_code_id": redemptionCode.Id,
|
||||
@@ -186,16 +200,8 @@ func (l *RedeemCodeLogic) RedeemCode(req *types.RedeemCodeRequest) (resp *types.
|
||||
"quantity": redemptionCode.Quantity,
|
||||
}
|
||||
jsonData, _ := json.Marshal(cacheData)
|
||||
err = l.svcCtx.Redis.Set(l.ctx, cacheKey, jsonData, 2*time.Hour).Err()
|
||||
if err != nil {
|
||||
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")
|
||||
if redisErr := l.svcCtx.Redis.Set(l.ctx, cacheKey, jsonData, 2*time.Hour).Err(); redisErr != nil {
|
||||
l.Infow("[RedeemCode] Cache redemption data failed (non-fatal, DB fallback available)", logger.Field("error", redisErr.Error()))
|
||||
}
|
||||
|
||||
// 触发队列任务
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
package subscribe
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
stderrors "errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"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/xerr"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
const (
|
||||
promoRuleTypeNewUser = "new_user"
|
||||
promoRuleTypeInactiveUser = "inactive_user"
|
||||
promoRuleTypeCampaign = "campaign"
|
||||
)
|
||||
|
||||
type subscribePromoCandidate struct {
|
||||
SubscribeId int64 `gorm:"column:subscribe_id"`
|
||||
Quantity int64 `gorm:"column:quantity"`
|
||||
RuleName string `gorm:"column:rule_name"`
|
||||
RuleType string `gorm:"column:rule_type"`
|
||||
PromoPrice int64 `gorm:"column:promo_price"`
|
||||
Params string `gorm:"column:params"`
|
||||
StartTime *time.Time `gorm:"column:start_time"`
|
||||
EndTime *time.Time `gorm:"column:end_time"`
|
||||
}
|
||||
|
||||
type promoRuleParams struct {
|
||||
WindowHours int64 `json:"window_hours"`
|
||||
InactiveMonths int `json:"inactive_months"`
|
||||
}
|
||||
|
||||
func loadSubscribePromoMap(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64) (map[int64]map[int64]*types.SubscribePromo, error) {
|
||||
result := make(map[int64]map[int64]*types.SubscribePromo)
|
||||
if len(subscribeIDs) == 0 || svcCtx == nil || svcCtx.DB == nil {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
userInfo, _ := ctx.Value(constant.CtxKeyUser).(*user.User)
|
||||
candidates, err := querySubscribePromoCandidates(ctx, svcCtx, subscribeIDs, userInfo != nil)
|
||||
if err != nil {
|
||||
if isMissingPromoTableError(err) {
|
||||
return result, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
evaluator := promoEligibilityEvaluator{ctx: ctx, db: svcCtx.DB, userInfo: userInfo}
|
||||
now := time.Now()
|
||||
for _, candidate := range candidates {
|
||||
if candidate.Quantity <= 0 {
|
||||
continue
|
||||
}
|
||||
if result[candidate.SubscribeId] == nil {
|
||||
result[candidate.SubscribeId] = make(map[int64]*types.SubscribePromo)
|
||||
}
|
||||
if _, exists := result[candidate.SubscribeId][candidate.Quantity]; exists {
|
||||
continue
|
||||
}
|
||||
if !candidate.isActive(now) {
|
||||
continue
|
||||
}
|
||||
ok, expiresAt, err := evaluator.match(candidate, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
result[candidate.SubscribeId][candidate.Quantity] = &types.SubscribePromo{
|
||||
RuleName: candidate.RuleName,
|
||||
RuleType: candidate.RuleType,
|
||||
PromoPrice: candidate.PromoPrice,
|
||||
ExpiresAt: unixSeconds(expiresAt),
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func querySubscribePromoCandidates(ctx context.Context, svcCtx *svc.ServiceContext, subscribeIDs []int64, loggedIn bool) ([]subscribePromoCandidate, error) {
|
||||
var candidates []subscribePromoCandidate
|
||||
err := subscribePromoCandidatesQuery(ctx, svcCtx.DB, subscribeIDs, loggedIn).
|
||||
Scan(&candidates).Error
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query subscribe promo candidates failed: %v", err)
|
||||
}
|
||||
return candidates, nil
|
||||
}
|
||||
|
||||
func subscribePromoCandidatesQuery(ctx context.Context, db *gorm.DB, subscribeIDs []int64, loggedIn bool) *gorm.DB {
|
||||
query := db.WithContext(ctx).
|
||||
Table("subscribe_promo AS sp").
|
||||
Select("sp.subscribe_id, sp.quantity, sp.promo_price, pr.name AS rule_name, pr.type AS rule_type, pr.params, pr.start_time, pr.end_time").
|
||||
Joins("JOIN promo_rule AS pr ON pr.id = sp.promo_rule_id AND pr.deleted_at IS NULL").
|
||||
Where("sp.subscribe_id IN ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeIDs, true)
|
||||
if !loggedIn {
|
||||
query = query.Where("pr.type = ?", promoRuleTypeCampaign)
|
||||
}
|
||||
return query.
|
||||
Order("sp.subscribe_id ASC").
|
||||
Order("sp.quantity ASC").
|
||||
Order("pr.priority DESC").
|
||||
Order("pr.id ASC")
|
||||
}
|
||||
|
||||
func (c subscribePromoCandidate) isActive(now time.Time) bool {
|
||||
if c.PromoPrice <= 0 {
|
||||
return false
|
||||
}
|
||||
if c.StartTime != nil && now.Before(*c.StartTime) {
|
||||
return false
|
||||
}
|
||||
if c.EndTime != nil && now.After(*c.EndTime) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type promoEligibilityEvaluator struct {
|
||||
ctx context.Context
|
||||
db *gorm.DB
|
||||
userInfo *user.User
|
||||
lastExpire *time.Time
|
||||
}
|
||||
|
||||
func (e *promoEligibilityEvaluator) match(candidate subscribePromoCandidate, now time.Time) (bool, time.Time, error) {
|
||||
switch candidate.RuleType {
|
||||
case promoRuleTypeCampaign:
|
||||
return true, candidate.expiresAt(), nil
|
||||
case promoRuleTypeNewUser:
|
||||
if e.userInfo == nil {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
params, err := candidate.params()
|
||||
if err != nil {
|
||||
return false, time.Time{}, err
|
||||
}
|
||||
if params.WindowHours <= 0 || e.userInfo.CreatedAt.IsZero() {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
expiresAt := e.userInfo.CreatedAt.Add(time.Duration(params.WindowHours) * time.Hour)
|
||||
return now.Before(expiresAt), expiresAt, nil
|
||||
case promoRuleTypeInactiveUser:
|
||||
if e.userInfo == nil {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
params, err := candidate.params()
|
||||
if err != nil {
|
||||
return false, time.Time{}, err
|
||||
}
|
||||
if params.InactiveMonths <= 0 {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
lastExpire, err := e.lastSubscribeExpireAt()
|
||||
if err != nil {
|
||||
return false, time.Time{}, err
|
||||
}
|
||||
if lastExpire.Equal(time.UnixMilli(0)) || lastExpire.After(now) {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
if lastExpire.IsZero() {
|
||||
return true, candidate.expiresAt(), nil
|
||||
}
|
||||
threshold := now.AddDate(0, -params.InactiveMonths, 0)
|
||||
return !lastExpire.After(threshold), candidate.expiresAt(), nil
|
||||
default:
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (e *promoEligibilityEvaluator) lastSubscribeExpireAt() (time.Time, error) {
|
||||
if e.lastExpire != nil {
|
||||
return *e.lastExpire, nil
|
||||
}
|
||||
var item user.Subscribe
|
||||
err := e.lastSubscribeExpireQuery().
|
||||
Limit(1).
|
||||
Take(&item).Error
|
||||
if err != nil {
|
||||
if stderrors.Is(err, gorm.ErrRecordNotFound) {
|
||||
zero := time.Time{}
|
||||
e.lastExpire = &zero
|
||||
return zero, nil
|
||||
}
|
||||
return time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo user last subscription failed")
|
||||
}
|
||||
e.lastExpire = &item.ExpireTime
|
||||
return item.ExpireTime, nil
|
||||
}
|
||||
|
||||
func (e *promoEligibilityEvaluator) lastSubscribeExpireQuery() *gorm.DB {
|
||||
return e.db.WithContext(e.ctx).
|
||||
Model(&user.Subscribe{}).
|
||||
Where("user_id = ?", e.userInfo.Id).
|
||||
Order(clause.OrderBy{
|
||||
Expression: clause.Expr{
|
||||
SQL: "CASE WHEN expire_time = ? THEN 0 ELSE 1 END, expire_time DESC",
|
||||
Vars: []interface{}{time.UnixMilli(0)},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (c subscribePromoCandidate) expiresAt() time.Time {
|
||||
if c.EndTime == nil {
|
||||
return time.Time{}
|
||||
}
|
||||
return *c.EndTime
|
||||
}
|
||||
|
||||
func (c subscribePromoCandidate) params() (promoRuleParams, error) {
|
||||
if c.Params == "" {
|
||||
return promoRuleParams{}, nil
|
||||
}
|
||||
var params promoRuleParams
|
||||
if err := json.Unmarshal([]byte(c.Params), ¶ms); err != nil {
|
||||
return promoRuleParams{}, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "parse promo rule params failed")
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
func unixSeconds(t time.Time) int64 {
|
||||
if t.IsZero() {
|
||||
return 0
|
||||
}
|
||||
return t.Unix()
|
||||
}
|
||||
|
||||
func isMissingPromoTableError(err error) bool {
|
||||
var mysqlErr *mysql.MySQLError
|
||||
if stderrors.As(err, &mysqlErr) {
|
||||
return mysqlErr.Number == 1146
|
||||
}
|
||||
return strings.Contains(err.Error(), "Error 1146")
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package subscribe
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/user"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestPromoEligibilityEvaluatorMatch(t *testing.T) {
|
||||
now := time.Unix(1710000000, 0)
|
||||
campaignEnd := now.Add(2 * time.Hour)
|
||||
|
||||
campaign := subscribePromoCandidate{
|
||||
RuleName: "限时活动",
|
||||
RuleType: promoRuleTypeCampaign,
|
||||
PromoPrice: 99,
|
||||
EndTime: &campaignEnd,
|
||||
}
|
||||
ok, expiresAt, err := (&promoEligibilityEvaluator{}).match(campaign, now)
|
||||
if err != nil {
|
||||
t.Fatalf("campaign match error: %v", err)
|
||||
}
|
||||
if !ok {
|
||||
t.Fatal("campaign promo should match without login")
|
||||
}
|
||||
if got, want := unixSeconds(expiresAt), campaignEnd.Unix(); got != want {
|
||||
t.Fatalf("campaign expires_at = %d, want %d", got, want)
|
||||
}
|
||||
|
||||
newUser := subscribePromoCandidate{
|
||||
RuleName: "新客7天优惠",
|
||||
RuleType: promoRuleTypeNewUser,
|
||||
PromoPrice: 279,
|
||||
Params: `{"window_hours":168}`,
|
||||
}
|
||||
ok, _, err = (&promoEligibilityEvaluator{}).match(newUser, now)
|
||||
if err != nil {
|
||||
t.Fatalf("anonymous new_user match error: %v", err)
|
||||
}
|
||||
if ok {
|
||||
t.Fatal("new_user promo should not match without login")
|
||||
}
|
||||
|
||||
userInfo := &user.User{Id: 1, CreatedAt: now.Add(-24 * time.Hour)}
|
||||
ok, expiresAt, err = (&promoEligibilityEvaluator{userInfo: userInfo}).match(newUser, now)
|
||||
if err != nil {
|
||||
t.Fatalf("logged-in new_user match error: %v", err)
|
||||
}
|
||||
if !ok {
|
||||
t.Fatal("new_user promo should match inside window")
|
||||
}
|
||||
if got, want := unixSeconds(expiresAt), userInfo.CreatedAt.Add(168*time.Hour).Unix(); got != want {
|
||||
t.Fatalf("new_user expires_at = %d, want %d", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscribePromoCandidateActiveWindow(t *testing.T) {
|
||||
now := time.Unix(1710000000, 0)
|
||||
start := now.Add(-time.Hour)
|
||||
end := now.Add(time.Hour)
|
||||
|
||||
if !(subscribePromoCandidate{PromoPrice: 1, StartTime: &start, EndTime: &end}).isActive(now) {
|
||||
t.Fatal("candidate inside active window should be active")
|
||||
}
|
||||
if (subscribePromoCandidate{PromoPrice: 0, StartTime: &start, EndTime: &end}).isActive(now) {
|
||||
t.Fatal("candidate with zero promo price should not be active")
|
||||
}
|
||||
if (subscribePromoCandidate{PromoPrice: 1, StartTime: &end}).isActive(now) {
|
||||
t.Fatal("candidate before start time should not be active")
|
||||
}
|
||||
if (subscribePromoCandidate{PromoPrice: 1, EndTime: &start}).isActive(now) {
|
||||
t.Fatal("candidate after end time should not be active")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLastSubscribeExpireAtPrioritizesPermanentSubscription(t *testing.T) {
|
||||
db, err := gorm.Open(mysql.New(mysql.Config{
|
||||
DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local",
|
||||
SkipInitializeWithVersion: true,
|
||||
}), &gorm.Config{DryRun: true, DisableAutomaticPing: true})
|
||||
if err != nil {
|
||||
t.Fatalf("open dry-run db: %v", err)
|
||||
}
|
||||
|
||||
evaluator := &promoEligibilityEvaluator{
|
||||
db: db,
|
||||
userInfo: &user.User{Id: 7},
|
||||
}
|
||||
var item user.Subscribe
|
||||
tx := evaluator.lastSubscribeExpireQuery().Limit(1).Take(&item)
|
||||
|
||||
sql := tx.Statement.SQL.String()
|
||||
if !strings.Contains(sql, "CASE WHEN expire_time = ? THEN 0 ELSE 1 END") {
|
||||
t.Fatalf("SQL missing permanent subscription priority order: %s", sql)
|
||||
}
|
||||
if strings.Contains(sql, "expire_time !=") {
|
||||
t.Fatalf("SQL should not filter out permanent subscriptions: %s", sql)
|
||||
}
|
||||
if len(tx.Statement.Vars) < 2 {
|
||||
t.Fatalf("SQL vars length = %d, want at least 2; vars=%v", len(tx.Statement.Vars), tx.Statement.Vars)
|
||||
}
|
||||
if got, want := tx.Statement.Vars[1], time.UnixMilli(0); got != want {
|
||||
t.Fatalf("permanent subscription order var = %v, want %v; vars=%v", got, want, tx.Statement.Vars)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuerySubscribePromoCandidatesIncludesQuantity(t *testing.T) {
|
||||
db, err := gorm.Open(mysql.New(mysql.Config{
|
||||
DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local",
|
||||
SkipInitializeWithVersion: true,
|
||||
}), &gorm.Config{DryRun: true, DisableAutomaticPing: true})
|
||||
if err != nil {
|
||||
t.Fatalf("open dry-run db: %v", err)
|
||||
}
|
||||
|
||||
var candidates []subscribePromoCandidate
|
||||
tx := subscribePromoCandidatesQuery(context.Background(), db, []int64{11, 12}, true).Scan(&candidates)
|
||||
stmt := tx.Statement
|
||||
sql := stmt.SQL.String()
|
||||
if !strings.Contains(sql, "sp.subscribe_id, sp.quantity, sp.promo_price") {
|
||||
t.Fatalf("SQL missing quantity select: %s", sql)
|
||||
}
|
||||
if !strings.Contains(sql, "ORDER BY sp.subscribe_id ASC,sp.quantity ASC,pr.priority DESC,pr.id ASC") {
|
||||
t.Fatalf("SQL missing quantity order: %s", sql)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplySubscribeDiscountPromosMatchesQuantity(t *testing.T) {
|
||||
subscribe := types.Subscribe{Discount: []types.SubscribeDiscount{
|
||||
{Quantity: 1},
|
||||
{Quantity: 12},
|
||||
}}
|
||||
promos := map[int64]*types.SubscribePromo{
|
||||
3: {RuleName: "季度优惠", PromoPrice: 2900},
|
||||
12: {RuleName: "年度优惠", PromoPrice: 9900},
|
||||
}
|
||||
|
||||
applySubscribeDiscountPromos(&subscribe, promos)
|
||||
if subscribe.Discount[0].Promo != nil {
|
||||
t.Fatalf("quantity 1 promo should be nil, got %+v", subscribe.Discount[0].Promo)
|
||||
}
|
||||
if subscribe.Discount[1].Promo == nil {
|
||||
t.Fatal("quantity 12 promo should match")
|
||||
}
|
||||
if got, want := subscribe.Discount[1].Promo.RuleName, "年度优惠"; got != want {
|
||||
t.Fatalf("promo rule name = %q, want %q", got, want)
|
||||
}
|
||||
|
||||
subscribe = types.Subscribe{Discount: []types.SubscribeDiscount{{Quantity: 6}}}
|
||||
applySubscribeDiscountPromos(&subscribe, promos)
|
||||
if subscribe.Discount[0].Promo != nil {
|
||||
t.Fatalf("promo should be nil when quantity does not match, got %+v", subscribe.Discount[0].Promo)
|
||||
}
|
||||
}
|
||||
@@ -47,18 +47,28 @@ func (l *QuerySubscribeListLogic) QuerySubscribeList(req *types.QuerySubscribeLi
|
||||
Total: total,
|
||||
}
|
||||
list := make([]types.Subscribe, len(data))
|
||||
subscribeIDs := make([]int64, 0, len(data))
|
||||
for i, item := range data {
|
||||
var sub types.Subscribe
|
||||
tool.DeepCopy(&sub, item)
|
||||
subscribeIDs = append(subscribeIDs, sub.Id)
|
||||
if item.Discount != "" {
|
||||
var discount []types.SubscribeDiscount
|
||||
_ = json.Unmarshal([]byte(item.Discount), &discount)
|
||||
sub.Discount = discount
|
||||
list[i] = sub
|
||||
}
|
||||
list[i] = sub
|
||||
}
|
||||
|
||||
promos, err := loadSubscribePromoMap(l.ctx, l.svcCtx, subscribeIDs)
|
||||
if err != nil {
|
||||
l.Errorw("[QuerySubscribeListLogic] Query Promo Error", logger.Field("error", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
for i := range list {
|
||||
applySubscribeDiscountPromos(&list[i], promos[list[i].Id])
|
||||
}
|
||||
|
||||
// 老版本客户端(无 X-App-Id)去掉每个套餐 discount 的最后一个
|
||||
hasAppId, _ := l.ctx.Value(constant.CtxKeyHasAppId).(bool)
|
||||
if !hasAppId {
|
||||
@@ -73,3 +83,9 @@ func (l *QuerySubscribeListLogic) QuerySubscribeList(req *types.QuerySubscribeLi
|
||||
resp.Total = int64(len(list))
|
||||
return
|
||||
}
|
||||
|
||||
func applySubscribeDiscountPromos(subscribe *types.Subscribe, promoByQuantity map[int64]*types.SubscribePromo) {
|
||||
for i := range subscribe.Discount {
|
||||
subscribe.Discount[i].Promo = promoByQuantity[subscribe.Discount[i].Quantity]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,10 +2,7 @@ package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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/user"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
@@ -38,57 +35,70 @@ func (l *CommissionWithdrawLogic) CommissionWithdraw(req *types.CommissionWithdr
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
|
||||
}
|
||||
|
||||
if u.Commission < req.Amount {
|
||||
logger.Errorf("User %d has insufficient commission balance: %.2f, requested: %.2f", u.Id, float64(u.Commission)/100, float64(req.Amount)/100)
|
||||
// Validate payment method fields
|
||||
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 == "" {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "account 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)
|
||||
}
|
||||
|
||||
tx := l.svcCtx.DB.WithContext(l.ctx).Begin()
|
||||
now := time.Now()
|
||||
|
||||
// Atomically deduct the requested amount so concurrent commission growth is preserved.
|
||||
if err = l.svcCtx.DB.WithContext(l.ctx).
|
||||
Model(&user.User{}).
|
||||
Where("id = ? AND commission >= ?", u.Id, req.Amount).
|
||||
UpdateColumn("commission", gorm.Expr("commission - ?", req.Amount)).Error; err != nil {
|
||||
tx.Rollback()
|
||||
l.Errorf("Failed to update user %d commission balance: %v", u.Id, err)
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "Failed to update user %d commission balance: %v", u.Id, err)
|
||||
}
|
||||
_ = l.svcCtx.UserModel.ClearUserCache(l.ctx, u)
|
||||
|
||||
// create withdrawal log
|
||||
if err = logicCommon.WriteCommissionLog(tx, u.Id, log.CommissionTypeConvertBalance, req.Amount, ""); 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
|
||||
|
||||
var w user.Withdrawal
|
||||
err = l.svcCtx.DB.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error {
|
||||
w = user.Withdrawal{
|
||||
UserId: u.Id,
|
||||
Amount: req.Amount,
|
||||
Content: req.Content,
|
||||
Status: user.WithdrawalStatusPending,
|
||||
Reason: "",
|
||||
Method: req.Method,
|
||||
Account: req.Account,
|
||||
QrCodeUrl: req.QrCodeUrl,
|
||||
}
|
||||
return tx.Create(&w).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)
|
||||
l.Errorf("Failed to create withdrawal 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 &types.WithdrawalLog{
|
||||
Id: w.Id,
|
||||
UserId: u.Id,
|
||||
Amount: req.Amount,
|
||||
Content: req.Content,
|
||||
Status: 0,
|
||||
Status: user.WithdrawalStatusPending,
|
||||
Reason: "",
|
||||
CreatedAt: now.UnixMilli(),
|
||||
UpdatedAt: now.UnixMilli(),
|
||||
Method: req.Method,
|
||||
Account: req.Account,
|
||||
QrCodeUrl: req.QrCodeUrl,
|
||||
CreatedAt: w.CreatedAt.UnixMilli(),
|
||||
UpdatedAt: w.UpdatedAt.UnixMilli(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user