Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| af22430101 |
+2
-2
@@ -7,8 +7,8 @@ MYSQL_ROOT_PASSWORD=CHANGE_ME_TO_STRONG_PASSWORD
|
|||||||
# Grafana 管理员密码
|
# Grafana 管理员密码
|
||||||
GRAFANA_PASSWORD=CHANGE_ME_TO_STRONG_PASSWORD
|
GRAFANA_PASSWORD=CHANGE_ME_TO_STRONG_PASSWORD
|
||||||
|
|
||||||
# PPanel Server 镜像标签(由 CI/CD 传入不可变 tag,如 git SHA)
|
# PPanel Server 镜像标签(留空使用 latest)
|
||||||
PPANEL_SERVER_TAG=CHANGE_ME_TO_GIT_SHA
|
PPANEL_SERVER_TAG=latest
|
||||||
|
|
||||||
# AWS 区域(香港)
|
# AWS 区域(香港)
|
||||||
AWS_REGION=ap-east-1
|
AWS_REGION=ap-east-1
|
||||||
|
|||||||
+44
-142
@@ -21,8 +21,8 @@ env:
|
|||||||
# SSH私钥(Gitea Secret 名称:AWS)
|
# SSH私钥(Gitea Secret 名称:AWS)
|
||||||
SSH_KEY: ${{ secrets.AWS }}
|
SSH_KEY: ${{ secrets.AWS }}
|
||||||
# TG通知
|
# TG通知
|
||||||
TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN }}
|
TG_BOT_TOKEN: 8114337882:AAHkEx03HSu7RxN4IHBJJEnsK9aPPzNLIk0
|
||||||
TG_CHAT_ID: ${{ secrets.TG_CHAT_ID }}
|
TG_CHAT_ID: "-4940243803"
|
||||||
# Go构建变量
|
# Go构建变量
|
||||||
SERVICE: vpn
|
SERVICE: vpn
|
||||||
SERVICE_STYLE: vpn
|
SERVICE_STYLE: vpn
|
||||||
@@ -43,7 +43,7 @@ jobs:
|
|||||||
# 步骤1: 下载代码
|
# 步骤1: 下载代码
|
||||||
- name: 📥 下载代码
|
- name: 📥 下载代码
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
# 步骤2: 设置动态环境变量
|
# 步骤2: 设置动态环境变量
|
||||||
- name: ⚙️ 设置动态环境变量
|
- name: ⚙️ 设置动态环境变量
|
||||||
run: |
|
run: |
|
||||||
@@ -51,22 +51,19 @@ jobs:
|
|||||||
echo "DOCKER_TAG_SUFFIX=latest" >> $GITHUB_ENV
|
echo "DOCKER_TAG_SUFFIX=latest" >> $GITHUB_ENV
|
||||||
echo "CONTAINER_NAME=ppanel-server" >> $GITHUB_ENV
|
echo "CONTAINER_NAME=ppanel-server" >> $GITHUB_ENV
|
||||||
echo "DEPLOY_PATH=/opt/ppanel" >> $GITHUB_ENV
|
echo "DEPLOY_PATH=/opt/ppanel" >> $GITHUB_ENV
|
||||||
echo "DEPLOY_ENV_LABEL=🚀 服务已成功部署到生产环境" >> $GITHUB_ENV
|
|
||||||
echo "为 main 分支设置生产环境变量"
|
echo "为 main 分支设置生产环境变量"
|
||||||
elif [ "${{ github.ref_name }}" = "internal" ]; then
|
elif [ "${{ github.ref_name }}" = "internal" ]; then
|
||||||
echo "DOCKER_TAG_SUFFIX=internal" >> $GITHUB_ENV
|
echo "DOCKER_TAG_SUFFIX=internal" >> $GITHUB_ENV
|
||||||
echo "CONTAINER_NAME=ppanel-server-internal" >> $GITHUB_ENV
|
echo "CONTAINER_NAME=ppanel-server-internal" >> $GITHUB_ENV
|
||||||
echo "DEPLOY_PATH=/root/bindbox" >> $GITHUB_ENV
|
echo "DEPLOY_PATH=/root/bindbox" >> $GITHUB_ENV
|
||||||
echo "DEPLOY_ENV_LABEL=🧪 服务已成功部署到测试环境" >> $GITHUB_ENV
|
|
||||||
echo "为 internal 分支设置开发环境变量"
|
echo "为 internal 分支设置开发环境变量"
|
||||||
else
|
else
|
||||||
echo "DOCKER_TAG_SUFFIX=${{ github.ref_name }}" >> $GITHUB_ENV
|
echo "DOCKER_TAG_SUFFIX=${{ github.ref_name }}" >> $GITHUB_ENV
|
||||||
echo "CONTAINER_NAME=ppanel-server-${{ github.ref_name }}" >> $GITHUB_ENV
|
echo "CONTAINER_NAME=ppanel-server-${{ github.ref_name }}" >> $GITHUB_ENV
|
||||||
echo "DEPLOY_PATH=/root/vpn_server_other" >> $GITHUB_ENV
|
echo "DEPLOY_PATH=/root/vpn_server_other" >> $GITHUB_ENV
|
||||||
echo "DEPLOY_ENV_LABEL=🔧 服务已成功部署到其他环境" >> $GITHUB_ENV
|
|
||||||
echo "为其他分支 (${{ github.ref_name }}) 设置环境变量"
|
echo "为其他分支 (${{ github.ref_name }}) 设置环境变量"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 步骤3: 安装系统工具 (curl, jq) 并升级 Docker CLI 到 1.44+
|
# 步骤3: 安装系统工具 (curl, jq) 并升级 Docker CLI 到 1.44+
|
||||||
- name: 🔧 安装系统工具并升级 Docker CLI
|
- name: 🔧 安装系统工具并升级 Docker CLI
|
||||||
run: |
|
run: |
|
||||||
@@ -114,49 +111,35 @@ jobs:
|
|||||||
docker --version || true
|
docker --version || true
|
||||||
docker version || true
|
docker version || true
|
||||||
echo "客户端 API 版本:" $(docker version --format '{{.Client.APIVersion}}')
|
echo "客户端 API 版本:" $(docker version --format '{{.Client.APIVersion}}')
|
||||||
|
|
||||||
# 步骤4: 构建镜像
|
# 步骤4: 构建并发布到镜像仓库
|
||||||
- name: 🏗️ 构建镜像
|
- name: 📤 构建并发布到镜像仓库
|
||||||
run: |
|
run: |
|
||||||
echo "开始构建镜像..."
|
echo "开始构建并推送镜像..."
|
||||||
echo "仓库: ${{ env.REPO }}"
|
echo "仓库: ${{ env.REPO }}"
|
||||||
echo "版本标签: ${{ env.VERSION }}"
|
echo "版本标签: ${{ env.VERSION }}"
|
||||||
echo "分支标签: ${{ env.DOCKER_TAG_SUFFIX }}"
|
echo "分支标签: ${{ env.DOCKER_TAG_SUFFIX }}"
|
||||||
|
|
||||||
BUILD_TAG_ARGS="-t ${{ env.REPO }}:${{ env.VERSION }}"
|
# 构建镜像,同时打上版本和分支两个标签
|
||||||
if [ "${{ github.event_name }}" = "push" ]; then
|
|
||||||
BUILD_TAG_ARGS="$BUILD_TAG_ARGS -t ${{ env.REPO }}:${{ env.DOCKER_TAG_SUFFIX }}"
|
|
||||||
else
|
|
||||||
echo "PR事件仅构建版本标签,不推送镜像、不部署"
|
|
||||||
fi
|
|
||||||
|
|
||||||
docker build -f Dockerfile \
|
docker build -f Dockerfile \
|
||||||
--platform linux/amd64 \
|
--platform linux/amd64 \
|
||||||
--build-arg TARGETARCH=amd64 \
|
--build-arg TARGETARCH=amd64 \
|
||||||
--build-arg VERSION=${{ env.VERSION }} \
|
--build-arg VERSION=${{ env.VERSION }} \
|
||||||
--build-arg BUILDTIME=${{ env.BUILDTIME }} \
|
--build-arg BUILDTIME=${{ env.BUILDTIME }} \
|
||||||
$BUILD_TAG_ARGS \
|
-t ${{ env.REPO }}:${{ env.VERSION }} \
|
||||||
|
-t ${{ env.REPO }}:${{ env.DOCKER_TAG_SUFFIX }} \
|
||||||
.
|
.
|
||||||
|
|
||||||
echo "镜像构建完成"
|
|
||||||
|
|
||||||
# 步骤5: 发布到镜像仓库
|
|
||||||
- name: 📤 发布到镜像仓库
|
|
||||||
if: github.event_name == 'push'
|
|
||||||
run: |
|
|
||||||
echo "开始推送镜像..."
|
|
||||||
|
|
||||||
echo "推送版本标签镜像: ${{ env.REPO }}:${{ env.VERSION }}"
|
echo "推送版本标签镜像: ${{ env.REPO }}:${{ env.VERSION }}"
|
||||||
docker push ${{ env.REPO }}:${{ env.VERSION }}
|
docker push ${{ env.REPO }}:${{ env.VERSION }}
|
||||||
|
|
||||||
echo "推送分支标签镜像: ${{ env.REPO }}:${{ env.DOCKER_TAG_SUFFIX }}"
|
echo "推送分支标签镜像: ${{ env.REPO }}:${{ env.DOCKER_TAG_SUFFIX }}"
|
||||||
docker push ${{ env.REPO }}:${{ env.DOCKER_TAG_SUFFIX }}
|
docker push ${{ env.REPO }}:${{ env.DOCKER_TAG_SUFFIX }}
|
||||||
|
|
||||||
echo "镜像推送完成"
|
echo "镜像推送完成"
|
||||||
|
|
||||||
# 步骤6: 调试 - 打印部署目标(不输出敏感信息)
|
# 调试: 打印部署目标(不输出敏感信息)
|
||||||
- name: 🔍 调试 - 打印部署目标
|
- name: 🔍 调试 - 打印部署目标
|
||||||
if: github.event_name == 'push'
|
|
||||||
run: |
|
run: |
|
||||||
echo "========== 部署目标调试 =========="
|
echo "========== 部署目标调试 =========="
|
||||||
echo "当前分支: ${{ github.ref_name }}"
|
echo "当前分支: ${{ github.ref_name }}"
|
||||||
@@ -167,9 +150,8 @@ jobs:
|
|||||||
echo "DEPLOY_PATH: ${{ env.DEPLOY_PATH }}"
|
echo "DEPLOY_PATH: ${{ env.DEPLOY_PATH }}"
|
||||||
echo "====================================="
|
echo "====================================="
|
||||||
|
|
||||||
# 步骤7: 传输配置文件
|
# 步骤5: 传输配置文件
|
||||||
- name: 📂 传输配置文件
|
- name: 📂 传输配置文件
|
||||||
if: github.event_name == 'push'
|
|
||||||
uses: appleboy/scp-action@v0.1.7
|
uses: appleboy/scp-action@v0.1.7
|
||||||
with:
|
with:
|
||||||
host: ${{ env.SSH_HOST }}
|
host: ${{ env.SSH_HOST }}
|
||||||
@@ -179,9 +161,8 @@ jobs:
|
|||||||
source: "docker-compose.cloud.yml"
|
source: "docker-compose.cloud.yml"
|
||||||
target: "/tmp/ppanel-deploy/"
|
target: "/tmp/ppanel-deploy/"
|
||||||
|
|
||||||
# 步骤8: 连接服务器更新、健康检查并按需回滚
|
# 步骤6: 连接服务器更新并启动
|
||||||
- name: 🚀 连接服务器更新并启动
|
- name: 🚀 连接服务器更新并启动
|
||||||
if: github.event_name == 'push'
|
|
||||||
uses: appleboy/ssh-action@v1.0.3
|
uses: appleboy/ssh-action@v1.0.3
|
||||||
with:
|
with:
|
||||||
host: ${{ env.SSH_HOST }}
|
host: ${{ env.SSH_HOST }}
|
||||||
@@ -191,147 +172,68 @@ jobs:
|
|||||||
timeout: 300s
|
timeout: 300s
|
||||||
command_timeout: 600s
|
command_timeout: 600s
|
||||||
script: |
|
script: |
|
||||||
set -e
|
|
||||||
|
|
||||||
echo "连接服务器成功,开始部署..."
|
echo "连接服务器成功,开始部署..."
|
||||||
echo "部署目录: ${{ env.DEPLOY_PATH }}"
|
echo "部署目录: ${{ env.DEPLOY_PATH }}"
|
||||||
echo "部署标签: ${{ env.DOCKER_TAG_SUFFIX }}"
|
echo "部署标签: ${{ env.DOCKER_TAG_SUFFIX }}"
|
||||||
echo "登录用户: ${{ env.SSH_USER }}"
|
echo "登录用户: ${{ env.SSH_USER }}"
|
||||||
|
|
||||||
HEALTHCHECK_URL="http://127.0.0.1:8080/v1/common/heartbeat"
|
|
||||||
NEW_TAG="${{ env.DOCKER_TAG_SUFFIX }}"
|
|
||||||
ROLLBACK_TAG="rollback-${{ env.VERSION }}"
|
|
||||||
SUDO=""
|
|
||||||
if [ "${{ github.ref_name }}" = "main" ]; then
|
|
||||||
SUDO="sudo"
|
|
||||||
fi
|
|
||||||
|
|
||||||
docker_cmd() {
|
|
||||||
if [ -n "$SUDO" ]; then
|
|
||||||
sudo docker "$@"
|
|
||||||
else
|
|
||||||
docker "$@"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
compose_with_tag() {
|
|
||||||
tag="$1"
|
|
||||||
shift
|
|
||||||
if [ -n "$SUDO" ]; then
|
|
||||||
sudo env PPANEL_SERVER_TAG="$tag" docker-compose -f docker-compose.cloud.yml "$@"
|
|
||||||
else
|
|
||||||
PPANEL_SERVER_TAG="$tag" docker-compose -f docker-compose.cloud.yml "$@"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
write_previous_tag() {
|
|
||||||
if [ -n "$SUDO" ]; then
|
|
||||||
printf '%s\n' "${PREVIOUS_IMAGE_TAG:-}" | sudo tee .previous-ppanel-image-tag >/dev/null
|
|
||||||
else
|
|
||||||
printf '%s\n' "${PREVIOUS_IMAGE_TAG:-}" > .previous-ppanel-image-tag
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
health_check() {
|
|
||||||
attempt=1
|
|
||||||
while [ "$attempt" -le 3 ]; do
|
|
||||||
if curl -sf "$HEALTHCHECK_URL"; then
|
|
||||||
echo
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "健康检查第 ${attempt}/3 次失败,10s 后重试..."
|
|
||||||
attempt=$((attempt + 1))
|
|
||||||
sleep 10
|
|
||||||
done
|
|
||||||
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
if [ "${{ github.ref_name }}" = "main" ]; then
|
if [ "${{ github.ref_name }}" = "main" ]; then
|
||||||
sudo mkdir -p ${{ env.DEPLOY_PATH }}
|
sudo mkdir -p ${{ env.DEPLOY_PATH }}
|
||||||
sudo cp /tmp/ppanel-deploy/docker-compose.cloud.yml ${{ env.DEPLOY_PATH }}/docker-compose.cloud.yml
|
sudo cp /tmp/ppanel-deploy/docker-compose.cloud.yml ${{ env.DEPLOY_PATH }}/docker-compose.cloud.yml
|
||||||
|
cd ${{ env.DEPLOY_PATH }}
|
||||||
|
echo "📥 拉取镜像..."
|
||||||
|
sudo docker-compose -f docker-compose.cloud.yml pull ppanel-server
|
||||||
|
echo "🚀 启动服务..."
|
||||||
|
sudo docker-compose -f docker-compose.cloud.yml up -d ppanel-server
|
||||||
|
sudo docker image prune -f || true
|
||||||
else
|
else
|
||||||
mkdir -p ${{ env.DEPLOY_PATH }}
|
mkdir -p ${{ env.DEPLOY_PATH }}
|
||||||
cp /tmp/ppanel-deploy/docker-compose.cloud.yml ${{ env.DEPLOY_PATH }}/docker-compose.cloud.yml
|
cp /tmp/ppanel-deploy/docker-compose.cloud.yml ${{ env.DEPLOY_PATH }}/docker-compose.cloud.yml
|
||||||
|
cd ${{ env.DEPLOY_PATH }}
|
||||||
|
echo "📥 拉取镜像..."
|
||||||
|
docker-compose -f docker-compose.cloud.yml pull ppanel-server
|
||||||
|
echo "🚀 启动服务..."
|
||||||
|
docker-compose -f docker-compose.cloud.yml up -d ppanel-server
|
||||||
|
docker image prune -f || true
|
||||||
fi
|
fi
|
||||||
|
|
||||||
cd ${{ env.DEPLOY_PATH }}
|
echo "✅ 部署命令执行完成"
|
||||||
|
|
||||||
PREVIOUS_IMAGE_TAG="$(docker_cmd inspect --format '{{.Config.Image}}' ppanel-server 2>/dev/null || true)"
|
# 步骤6: TG通知 (成功)
|
||||||
PREVIOUS_IMAGE_ID="$(docker_cmd inspect --format '{{.Image}}' ppanel-server 2>/dev/null || true)"
|
|
||||||
echo "上一版本镜像tag: ${PREVIOUS_IMAGE_TAG:-未发现}"
|
|
||||||
echo "上一版本镜像ID: ${PREVIOUS_IMAGE_ID:-未发现}"
|
|
||||||
write_previous_tag
|
|
||||||
|
|
||||||
echo "📥 拉取镜像: ${{ env.REPO }}:${NEW_TAG}"
|
|
||||||
compose_with_tag "$NEW_TAG" pull ppanel-server
|
|
||||||
echo "🚀 启动服务..."
|
|
||||||
compose_with_tag "$NEW_TAG" up -d ppanel-server
|
|
||||||
|
|
||||||
echo "🩺 部署后健康检查: ${HEALTHCHECK_URL}"
|
|
||||||
if health_check; then
|
|
||||||
docker_cmd image prune -f || true
|
|
||||||
echo "✅ 部署后健康检查通过"
|
|
||||||
echo "✅ 部署命令执行完成"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "❌ 部署后健康检查连续 3 次失败,开始回滚..."
|
|
||||||
if [ -n "$PREVIOUS_IMAGE_ID" ]; then
|
|
||||||
docker_cmd tag "$PREVIOUS_IMAGE_ID" "${{ env.REPO }}:${ROLLBACK_TAG}"
|
|
||||||
echo "回滚镜像tag: ${{ env.REPO }}:${ROLLBACK_TAG}"
|
|
||||||
compose_with_tag "$ROLLBACK_TAG" up -d ppanel-server
|
|
||||||
|
|
||||||
echo "🩺 回滚后健康检查: ${HEALTHCHECK_URL}"
|
|
||||||
if health_check; then
|
|
||||||
echo "✅ 回滚后健康检查通过"
|
|
||||||
else
|
|
||||||
echo "❌ 回滚后健康检查仍失败"
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
echo "未找到上一版本镜像ID,无法自动回滚"
|
|
||||||
fi
|
|
||||||
|
|
||||||
docker_cmd image prune -f || true
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
# 步骤9: TG通知 (成功)
|
|
||||||
- name: 📱 发送成功通知到Telegram
|
- name: 📱 发送成功通知到Telegram
|
||||||
if: success() && github.event_name == 'push'
|
if: success()
|
||||||
uses: appleboy/telegram-action@master
|
uses: appleboy/telegram-action@master
|
||||||
with:
|
with:
|
||||||
token: ${{ env.TG_BOT_TOKEN }}
|
token: ${{ env.TG_BOT_TOKEN }}
|
||||||
to: ${{ env.TG_CHAT_ID }}
|
to: ${{ env.TG_CHAT_ID }}
|
||||||
message: |
|
message: |
|
||||||
✅ 部署成功!
|
✅ 部署成功!
|
||||||
|
|
||||||
📦 项目: ${{ github.repository }}
|
📦 项目: ${{ github.repository }}
|
||||||
🌿 分支: ${{ github.ref_name }}
|
🌿 分支: ${{ github.ref_name }}
|
||||||
📝 提交: ${{ github.sha }}
|
📝 提交: ${{ github.sha }}
|
||||||
👤 提交者: ${{ github.actor }}
|
👤 提交者: ${{ github.actor }}
|
||||||
🕐 时间: ${{ github.event.head_commit.timestamp }}
|
🕐 时间: ${{ github.event.head_commit.timestamp }}
|
||||||
|
|
||||||
${{ env.DEPLOY_ENV_LABEL }}
|
🚀 服务已成功部署到生产环境
|
||||||
🩺 健康检查: 通过 (http://127.0.0.1:8080/v1/common/heartbeat)
|
|
||||||
parse_mode: Markdown
|
parse_mode: Markdown
|
||||||
|
|
||||||
# 步骤10: TG通知 (失败)
|
# 步骤5: TG通知 (失败)
|
||||||
- name: 📱 发送失败通知到Telegram
|
- name: 📱 发送失败通知到Telegram
|
||||||
if: failure() && github.event_name == 'push'
|
if: failure()
|
||||||
uses: appleboy/telegram-action@master
|
uses: appleboy/telegram-action@master
|
||||||
with:
|
with:
|
||||||
token: ${{ env.TG_BOT_TOKEN }}
|
token: ${{ env.TG_BOT_TOKEN }}
|
||||||
to: ${{ env.TG_CHAT_ID }}
|
to: ${{ env.TG_CHAT_ID }}
|
||||||
message: |
|
message: |
|
||||||
❌ 部署失败!
|
❌ 部署失败!
|
||||||
|
|
||||||
📦 项目: ${{ github.repository }}
|
📦 项目: ${{ github.repository }}
|
||||||
🌿 分支: ${{ github.ref_name }}
|
🌿 分支: ${{ github.ref_name }}
|
||||||
📝 提交: ${{ github.sha }}
|
📝 提交: ${{ github.sha }}
|
||||||
👤 提交者: ${{ github.actor }}
|
👤 提交者: ${{ github.actor }}
|
||||||
🕐 时间: ${{ github.event.head_commit.timestamp }}
|
🕐 时间: ${{ github.event.head_commit.timestamp }}
|
||||||
|
|
||||||
🩺 健康检查: 失败或未完成;若新版本健康检查连续 3 次失败,已自动尝试回滚并重新检查
|
|
||||||
⚠️ 请检查构建日志获取详细信息
|
⚠️ 请检查构建日志获取详细信息
|
||||||
parse_mode: Markdown
|
parse_mode: Markdown
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
upstream api_backend {
|
||||||
|
server 127.0.0.1:8080;
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
|
||||||
|
listen 80;
|
||||||
|
server_name api.hifast.biz 4d3vsw888xgaen.hifast.biz;
|
||||||
|
location /.well-known/acme-challenge/ {
|
||||||
|
root /var/www/html;
|
||||||
|
allow all;
|
||||||
|
}
|
||||||
|
location / {
|
||||||
|
return 301 https://$host$request_uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl http2;
|
||||||
|
server_name api.hifast.biz;
|
||||||
|
client_max_body_size 150M;
|
||||||
|
ssl_certificate /etc/nginx/ssl/hifast.biz/_.hifast.biz.pem; # managed by Certbot
|
||||||
|
ssl_certificate_key /etc/nginx/ssl/hifast.biz/_.hifast.biz.key; # managed by Certbot
|
||||||
|
|
||||||
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||||
|
add_header X-Frame-Options "DENY";
|
||||||
|
|
||||||
|
add_header X-Content-Type-Options nosniff;
|
||||||
|
if ($http_user_agent ~* '(9999|91\.78)') {
|
||||||
|
return 444;
|
||||||
|
}
|
||||||
|
location ~ ^/v1/common/client/download/file/(?<download_name>Hi快VPN-(?<os>windows|mac|android)-1.0.0-ic-.*\.(?<ext>exe|dmg|apk))$ {
|
||||||
|
alias /var/www/download/Hi快VPN-$os-1.0.0.$ext;
|
||||||
|
charset utf-8;
|
||||||
|
add_header Content-Disposition 'attachment; filename="$download_name"';
|
||||||
|
add_header Content-Type application/octet-stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /v1/common/client/download/file/ {
|
||||||
|
alias /var/www/download/;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://api_backend;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl http2;
|
||||||
|
server_name 4d3vsw888xgaen.hifast.biz;
|
||||||
|
client_max_body_size 150M;
|
||||||
|
ssl_certificate /etc/nginx/ssl/hifast.biz/_.hifast.biz.pem; # managed by Certbot
|
||||||
|
ssl_certificate_key /etc/nginx/ssl/hifast.biz/_.hifast.biz.key; # managed by Certbot
|
||||||
|
|
||||||
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||||
|
add_header X-Frame-Options DENY;
|
||||||
|
add_header X-Content-Type-Options nosniff;
|
||||||
|
|
||||||
|
gzip on;
|
||||||
|
gzip_vary on;
|
||||||
|
gzip_min_length 1024;
|
||||||
|
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json image/svg+xml;
|
||||||
|
root /var/www/admin;
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -149,35 +149,6 @@ type (
|
|||||||
Total int64 `json:"total"`
|
Total int64 `json:"total"`
|
||||||
List []CommissionLog `json:"list"`
|
List []CommissionLog `json:"list"`
|
||||||
}
|
}
|
||||||
OrderRefundLog {
|
|
||||||
OrderId int64 `json:"order_id"`
|
|
||||||
OrderNo string `json:"order_no"`
|
|
||||||
OperatorUserId int64 `json:"operator_user_id"`
|
|
||||||
OperatorAuthIdentifier string `json:"operator_auth_identifier,omitempty"`
|
|
||||||
TargetUserId int64 `json:"target_user_id"`
|
|
||||||
UserSubscribeId int64 `json:"user_subscribe_id"`
|
|
||||||
RefererUserId int64 `json:"referer_user_id,omitempty"`
|
|
||||||
CommissionAmount int64 `json:"commission_amount"`
|
|
||||||
Reason string `json:"reason,omitempty"`
|
|
||||||
OrderStatusBefore uint8 `json:"order_status_before"`
|
|
||||||
OrderStatusAfter uint8 `json:"order_status_after"`
|
|
||||||
SubscribeStatusBefore uint8 `json:"subscribe_status_before"`
|
|
||||||
SubscribeStatusAfter uint8 `json:"subscribe_status_after"`
|
|
||||||
SubscribeExpireBefore int64 `json:"subscribe_expire_before"`
|
|
||||||
SubscribeExpireAfter int64 `json:"subscribe_expire_after"`
|
|
||||||
CommissionBefore int64 `json:"commission_before"`
|
|
||||||
CommissionAfter int64 `json:"commission_after"`
|
|
||||||
Timestamp int64 `json:"timestamp"`
|
|
||||||
}
|
|
||||||
FilterOrderRefundLogRequest {
|
|
||||||
FilterLogParams
|
|
||||||
OrderId int64 `form:"order_id,optional"`
|
|
||||||
UserId int64 `form:"user_id,optional"`
|
|
||||||
}
|
|
||||||
FilterOrderRefundLogResponse {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []OrderRefundLog `json:"list"`
|
|
||||||
}
|
|
||||||
GiftLog {
|
GiftLog {
|
||||||
Type uint16 `json:"type"`
|
Type uint16 `json:"type"`
|
||||||
userId int64 `json:"user_id"`
|
userId int64 `json:"user_id"`
|
||||||
@@ -268,30 +239,6 @@ type (
|
|||||||
OccurredAt int64 `json:"occurred_at"`
|
OccurredAt int64 `json:"occurred_at"`
|
||||||
CreatedAt int64 `json:"created_at"`
|
CreatedAt int64 `json:"created_at"`
|
||||||
}
|
}
|
||||||
GetLogMessageRawRequest {
|
|
||||||
Id int64 `form:"id" validate:"required"`
|
|
||||||
}
|
|
||||||
GetLogMessageRawResponse {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
Platform string `json:"platform"`
|
|
||||||
AppVersion string `json:"app_version"`
|
|
||||||
OsName string `json:"os_name"`
|
|
||||||
OsVersion string `json:"os_version"`
|
|
||||||
DeviceId string `json:"device_id"`
|
|
||||||
UserId *int64 `json:"user_id"`
|
|
||||||
SessionId string `json:"session_id"`
|
|
||||||
Level uint8 `json:"level"`
|
|
||||||
ErrorCode string `json:"error_code"`
|
|
||||||
Message string `json:"message"`
|
|
||||||
Stack string `json:"stack"`
|
|
||||||
Context interface{} `json:"context"`
|
|
||||||
ClientIP string `json:"client_ip"`
|
|
||||||
UserAgent string `json:"user_agent"`
|
|
||||||
Locale string `json:"locale"`
|
|
||||||
Digest string `json:"digest"`
|
|
||||||
OccurredAt int64 `json:"occurred_at"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@server (
|
@server (
|
||||||
@@ -344,10 +291,6 @@ service ppanel {
|
|||||||
@handler FilterCommissionLog
|
@handler FilterCommissionLog
|
||||||
get /commission/list (FilterCommissionLogRequest) returns (FilterCommissionLogResponse)
|
get /commission/list (FilterCommissionLogRequest) returns (FilterCommissionLogResponse)
|
||||||
|
|
||||||
@doc "Filter order refund log"
|
|
||||||
@handler FilterOrderRefundLog
|
|
||||||
get /order/refund/list (FilterOrderRefundLogRequest) returns (FilterOrderRefundLogResponse)
|
|
||||||
|
|
||||||
@doc "Filter gift log"
|
@doc "Filter gift log"
|
||||||
@handler FilterGiftLog
|
@handler FilterGiftLog
|
||||||
get /gift/list (FilterGiftLogRequest) returns (FilterGiftLogResponse)
|
get /gift/list (FilterGiftLogRequest) returns (FilterGiftLogResponse)
|
||||||
@@ -371,9 +314,5 @@ service ppanel {
|
|||||||
@doc "Get error log message detail"
|
@doc "Get error log message detail"
|
||||||
@handler GetErrorLogMessageDetail
|
@handler GetErrorLogMessageDetail
|
||||||
get /error_message/detail returns (GetErrorLogMessageDetailResponse)
|
get /error_message/detail returns (GetErrorLogMessageDetailResponse)
|
||||||
|
|
||||||
@doc "Get log message raw detail (temporary)"
|
|
||||||
@handler GetLogMessageRaw
|
|
||||||
get /message/detail (GetLogMessageRawRequest) returns (GetLogMessageRawResponse)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -33,10 +33,6 @@ type (
|
|||||||
PaymentId int64 `json:"payment_id,omitempty"`
|
PaymentId int64 `json:"payment_id,omitempty"`
|
||||||
TradeNo string `json:"trade_no,omitempty"`
|
TradeNo string `json:"trade_no,omitempty"`
|
||||||
}
|
}
|
||||||
RefundOrderRequest {
|
|
||||||
Id int64 `json:"id" validate:"required"`
|
|
||||||
Reason string `json:"reason,omitempty" validate:"omitempty,max=500"`
|
|
||||||
}
|
|
||||||
ActivateOrderRequest {
|
ActivateOrderRequest {
|
||||||
OrderNo string `json:"order_no" validate:"required"`
|
OrderNo string `json:"order_no" validate:"required"`
|
||||||
}
|
}
|
||||||
@@ -72,10 +68,6 @@ service ppanel {
|
|||||||
@handler UpdateOrderStatus
|
@handler UpdateOrderStatus
|
||||||
put /status (UpdateOrderStatusRequest)
|
put /status (UpdateOrderStatusRequest)
|
||||||
|
|
||||||
@doc "Refund order"
|
|
||||||
@handler RefundOrder
|
|
||||||
post /refund (RefundOrderRequest)
|
|
||||||
|
|
||||||
@doc "Manually activate order"
|
@doc "Manually activate order"
|
||||||
@handler ActivateOrder
|
@handler ActivateOrder
|
||||||
post /activate (ActivateOrderRequest)
|
post /activate (ActivateOrderRequest)
|
||||||
|
|||||||
@@ -1,155 +0,0 @@
|
|||||||
syntax = "v1"
|
|
||||||
|
|
||||||
info (
|
|
||||||
title: "Promo API"
|
|
||||||
desc: "API for ppanel"
|
|
||||||
author: "Tension"
|
|
||||||
email: "tension@ppanel.com"
|
|
||||||
version: "0.0.1"
|
|
||||||
)
|
|
||||||
|
|
||||||
import "../types.api"
|
|
||||||
|
|
||||||
type (
|
|
||||||
PromoRule {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
Params 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"`
|
|
||||||
}
|
|
||||||
CreatePromoRuleRequest {
|
|
||||||
Name string `json:"name" validate:"required,max=100"`
|
|
||||||
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
|
||||||
Params interface{} `json:"params" validate:"required"`
|
|
||||||
Priority int64 `json:"priority" validate:"gte=0"`
|
|
||||||
Enabled *bool `json:"enabled" validate:"required"`
|
|
||||||
StartTime int64 `json:"start_time" validate:"required"`
|
|
||||||
EndTime int64 `json:"end_time" validate:"required"`
|
|
||||||
}
|
|
||||||
UpdatePromoRuleRequest {
|
|
||||||
Id int64 `json:"id" validate:"required"`
|
|
||||||
Name string `json:"name" validate:"required,max=100"`
|
|
||||||
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
|
||||||
Params interface{} `json:"params" validate:"required"`
|
|
||||||
Priority int64 `json:"priority" validate:"gte=0"`
|
|
||||||
Enabled *bool `json:"enabled" validate:"required"`
|
|
||||||
StartTime int64 `json:"start_time" validate:"required"`
|
|
||||||
EndTime int64 `json:"end_time" validate:"required"`
|
|
||||||
}
|
|
||||||
DeletePromoRuleRequest {
|
|
||||||
Id int64 `path:"id" validate:"required"`
|
|
||||||
}
|
|
||||||
GetPromoRuleDetailRequest {
|
|
||||||
Id int64 `path:"id" validate:"required"`
|
|
||||||
}
|
|
||||||
GetPromoRuleListRequest {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
Type string `form:"type,omitempty" validate:"omitempty,oneof=new_user inactive_user campaign"`
|
|
||||||
Enabled *bool `form:"enabled,omitempty"`
|
|
||||||
Search string `form:"search,omitempty"`
|
|
||||||
}
|
|
||||||
GetPromoRuleListResponse {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoRule `json:"list"`
|
|
||||||
}
|
|
||||||
PromoPriceInput {
|
|
||||||
SubscribeId int64 `json:"subscribe_id" validate:"required"`
|
|
||||||
PromoPrice int64 `json:"promo_price" validate:"required,gt=0"`
|
|
||||||
}
|
|
||||||
PromoPrice {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
UnitPrice int64 `json:"unit_price"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
|
||||||
}
|
|
||||||
CreatePromoPriceRequest {
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id" validate:"required"`
|
|
||||||
Items []PromoPriceInput `json:"items" validate:"required,dive"`
|
|
||||||
}
|
|
||||||
GetPromoPriceListRequest {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
PromoRuleId int64 `form:"promo_rule_id" validate:"required"`
|
|
||||||
}
|
|
||||||
GetPromoPriceListResponse {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoPrice `json:"list"`
|
|
||||||
}
|
|
||||||
DeletePromoPriceRequest {
|
|
||||||
Id int64 `path:"id" validate:"required"`
|
|
||||||
}
|
|
||||||
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"`
|
|
||||||
}
|
|
||||||
GetPromoUsageListRequest {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
PromoRuleId 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 CreatePromoRule
|
|
||||||
post /rule (CreatePromoRuleRequest) returns (PromoRule)
|
|
||||||
|
|
||||||
@doc "Get promo rule list"
|
|
||||||
@handler GetPromoRuleList
|
|
||||||
get /rule/list (GetPromoRuleListRequest) returns (GetPromoRuleListResponse)
|
|
||||||
|
|
||||||
@doc "Get promo rule detail"
|
|
||||||
@handler GetPromoRuleDetail
|
|
||||||
get /rule/:id (GetPromoRuleDetailRequest) returns (PromoRule)
|
|
||||||
|
|
||||||
@doc "Update promo rule"
|
|
||||||
@handler UpdatePromoRule
|
|
||||||
put /rule/:id (UpdatePromoRuleRequest) returns (PromoRule)
|
|
||||||
|
|
||||||
@doc "Delete promo rule"
|
|
||||||
@handler DeletePromoRule
|
|
||||||
delete /rule/:id (DeletePromoRuleRequest)
|
|
||||||
|
|
||||||
@doc "Batch set promo price"
|
|
||||||
@handler CreatePromoPrice
|
|
||||||
post /price (CreatePromoPriceRequest)
|
|
||||||
|
|
||||||
@doc "Get promo price list"
|
|
||||||
@handler GetPromoPriceList
|
|
||||||
get /price/list (GetPromoPriceListRequest) returns (GetPromoPriceListResponse)
|
|
||||||
|
|
||||||
@doc "Delete promo price"
|
|
||||||
@handler DeletePromoPrice
|
|
||||||
delete /price/:id (DeletePromoPriceRequest)
|
|
||||||
|
|
||||||
@doc "Get promo usage list"
|
|
||||||
@handler GetPromoUsageList
|
|
||||||
get /usage/list (GetPromoUsageListRequest) returns (GetPromoUsageListResponse)
|
|
||||||
}
|
|
||||||
+47
-29
@@ -38,20 +38,20 @@ type (
|
|||||||
Id int64 `form:"id" validate:"required"`
|
Id int64 `form:"id" validate:"required"`
|
||||||
}
|
}
|
||||||
UpdateUserBasiceInfoRequest {
|
UpdateUserBasiceInfoRequest {
|
||||||
UserId int64 `json:"user_id" validate:"required"`
|
UserId int64 `json:"user_id" validate:"required"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
Avatar string `json:"avatar"`
|
Avatar string `json:"avatar"`
|
||||||
Balance *int64 `json:"balance"`
|
Balance int64 `json:"balance"`
|
||||||
Commission *int64 `json:"commission"`
|
Commission int64 `json:"commission"`
|
||||||
ReferralPercentage uint8 `json:"referral_percentage"`
|
ReferralPercentage uint8 `json:"referral_percentage"`
|
||||||
OnlyFirstPurchase *bool `json:"only_first_purchase"`
|
OnlyFirstPurchase *bool `json:"only_first_purchase"`
|
||||||
GiftAmount *int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
Telegram int64 `json:"telegram"`
|
Telegram int64 `json:"telegram"`
|
||||||
ReferCode string `json:"refer_code"`
|
ReferCode string `json:"refer_code"`
|
||||||
RefererId *int64 `json:"referer_id"`
|
RefererId int64 `json:"referer_id"`
|
||||||
Enable *bool `json:"enable"`
|
Enable *bool `json:"enable"`
|
||||||
IsAdmin *bool `json:"is_admin"`
|
IsAdmin *bool `json:"is_admin"`
|
||||||
Remark *string `json:"remark"`
|
Remark string `json:"remark"`
|
||||||
}
|
}
|
||||||
UpdateUserNotifySettingRequest {
|
UpdateUserNotifySettingRequest {
|
||||||
UserId int64 `json:"user_id" validate:"required"`
|
UserId int64 `json:"user_id" validate:"required"`
|
||||||
@@ -76,6 +76,29 @@ type (
|
|||||||
GiftAmount int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
IsAdmin bool `json:"is_admin"`
|
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 {
|
BatchDeleteUserRequest {
|
||||||
Ids []int64 `json:"ids" validate:"required"`
|
Ids []int64 `json:"ids" validate:"required"`
|
||||||
}
|
}
|
||||||
@@ -135,22 +158,18 @@ type (
|
|||||||
Total int64 `json:"total"`
|
Total int64 `json:"total"`
|
||||||
}
|
}
|
||||||
CreateUserSubscribeRequest {
|
CreateUserSubscribeRequest {
|
||||||
UserId int64 `json:"user_id"`
|
UserId int64 `json:"user_id"`
|
||||||
ExpiredAt int64 `json:"expired_at"`
|
ExpiredAt int64 `json:"expired_at"`
|
||||||
Traffic int64 `json:"traffic"`
|
Traffic int64 `json:"traffic"`
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
SpeedLimit int64 `json:"speed_limit,optional"`
|
|
||||||
TrafficLimit string `json:"traffic_limit,optional"`
|
|
||||||
}
|
}
|
||||||
UpdateUserSubscribeRequest {
|
UpdateUserSubscribeRequest {
|
||||||
UserSubscribeId int64 `json:"user_subscribe_id"`
|
UserSubscribeId int64 `json:"user_subscribe_id"`
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
Traffic int64 `json:"traffic"`
|
Traffic int64 `json:"traffic"`
|
||||||
ExpiredAt int64 `json:"expired_at"`
|
ExpiredAt int64 `json:"expired_at"`
|
||||||
Upload int64 `json:"upload"`
|
Upload int64 `json:"upload"`
|
||||||
Download int64 `json:"download"`
|
Download int64 `json:"download"`
|
||||||
SpeedLimit *int64 `json:"speed_limit,omitempty"`
|
|
||||||
TrafficLimit *string `json:"traffic_limit,omitempty"`
|
|
||||||
}
|
}
|
||||||
GetUserLoginLogsRequest {
|
GetUserLoginLogsRequest {
|
||||||
Page int `form:"page"`
|
Page int `form:"page"`
|
||||||
@@ -216,7 +235,6 @@ type (
|
|||||||
Size int `form:"size"`
|
Size int `form:"size"`
|
||||||
UserId *int64 `form:"user_id,omitempty"`
|
UserId *int64 `form:"user_id,omitempty"`
|
||||||
Status *uint8 `form:"status,omitempty"`
|
Status *uint8 `form:"status,omitempty"`
|
||||||
Method *uint8 `form:"method,omitempty"`
|
|
||||||
}
|
}
|
||||||
GetWithdrawalListResponse {
|
GetWithdrawalListResponse {
|
||||||
List []WithdrawalLog `json:"list"`
|
List []WithdrawalLog `json:"list"`
|
||||||
|
|||||||
+2
-15
@@ -109,11 +109,8 @@ type (
|
|||||||
Rules []string `json:"rules" validate:"required"`
|
Rules []string `json:"rules" validate:"required"`
|
||||||
}
|
}
|
||||||
CommissionWithdrawRequest {
|
CommissionWithdrawRequest {
|
||||||
Amount int64 `json:"amount"`
|
Amount int64 `json:"amount"`
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
Method uint8 `json:"method" validate:"oneof=0 1 2 3"`
|
|
||||||
Account string `json:"account,omitempty"`
|
|
||||||
QrCodeUrl string `json:"qr_code_url,omitempty"`
|
|
||||||
}
|
}
|
||||||
WithdrawalLog {
|
WithdrawalLog {
|
||||||
Id int64 `json:"id"`
|
Id int64 `json:"id"`
|
||||||
@@ -122,15 +119,9 @@ type (
|
|||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
Status uint8 `json:"status"`
|
Status uint8 `json:"status"`
|
||||||
Reason string `json:"reason,omitempty"`
|
Reason string `json:"reason,omitempty"`
|
||||||
Method uint8 `json:"method"`
|
|
||||||
Account string `json:"account"`
|
|
||||||
QrCodeUrl string `json:"qr_code_url"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
CreatedAt int64 `json:"created_at"`
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
UpdatedAt int64 `json:"updated_at"`
|
||||||
}
|
}
|
||||||
CancelWithdrawalRequest {
|
|
||||||
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
|
||||||
}
|
|
||||||
QueryWithdrawalLogListRequest {
|
QueryWithdrawalLogListRequest {
|
||||||
Page int `form:"page"`
|
Page int `form:"page"`
|
||||||
Size int `form:"size"`
|
Size int `form:"size"`
|
||||||
@@ -361,10 +352,6 @@ service ppanel {
|
|||||||
@handler CommissionWithdraw
|
@handler CommissionWithdraw
|
||||||
post /commission_withdraw (CommissionWithdrawRequest) returns (WithdrawalLog)
|
post /commission_withdraw (CommissionWithdrawRequest) returns (WithdrawalLog)
|
||||||
|
|
||||||
@doc "Cancel pending withdrawal"
|
|
||||||
@handler CancelWithdrawal
|
|
||||||
post /withdrawal_cancel (CancelWithdrawalRequest) returns (WithdrawalLog)
|
|
||||||
|
|
||||||
@doc "Query Withdrawal Log"
|
@doc "Query Withdrawal Log"
|
||||||
@handler QueryWithdrawalLog
|
@handler QueryWithdrawalLog
|
||||||
get /withdrawal_log (QueryWithdrawalLogListRequest) returns (QueryWithdrawalLogListResponse)
|
get /withdrawal_log (QueryWithdrawalLogListRequest) returns (QueryWithdrawalLogListResponse)
|
||||||
|
|||||||
@@ -26,6 +26,5 @@ import (
|
|||||||
"./admin/ads.api"
|
"./admin/ads.api"
|
||||||
"./admin/marketing.api"
|
"./admin/marketing.api"
|
||||||
"./admin/application.api"
|
"./admin/application.api"
|
||||||
"./admin/group.api"
|
|
||||||
"./admin/promo.api"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+7
-46
@@ -171,13 +171,13 @@ type (
|
|||||||
DeviceLimit int64 `json:"device_limit"`
|
DeviceLimit int64 `json:"device_limit"`
|
||||||
}
|
}
|
||||||
VerifyConfig {
|
VerifyConfig {
|
||||||
CaptchaType string `json:"captcha_type"` // local or turnstile
|
CaptchaType string `json:"captcha_type"` // local or turnstile
|
||||||
TurnstileSiteKey string `json:"turnstile_site_key"`
|
TurnstileSiteKey string `json:"turnstile_site_key"`
|
||||||
TurnstileSecret string `json:"turnstile_secret"`
|
TurnstileSecret string `json:"turnstile_secret"`
|
||||||
EnableUserLoginCaptcha bool `json:"enable_user_login_captcha"` // User login captcha
|
EnableUserLoginCaptcha bool `json:"enable_user_login_captcha"` // User login captcha
|
||||||
EnableUserRegisterCaptcha bool `json:"enable_user_register_captcha"` // User register captcha
|
EnableUserRegisterCaptcha bool `json:"enable_user_register_captcha"` // User register captcha
|
||||||
EnableAdminLoginCaptcha bool `json:"enable_admin_login_captcha"` // Admin login captcha
|
EnableAdminLoginCaptcha bool `json:"enable_admin_login_captcha"` // Admin login captcha
|
||||||
EnableUserResetPasswordCaptcha bool `json:"enable_user_reset_password_captcha"` // User reset password captcha
|
EnableUserResetPasswordCaptcha bool `json:"enable_user_reset_password_captcha"` // User reset password captcha
|
||||||
}
|
}
|
||||||
NodeConfig {
|
NodeConfig {
|
||||||
NodeSecret string `json:"node_secret"`
|
NodeSecret string `json:"node_secret"`
|
||||||
@@ -230,12 +230,6 @@ type (
|
|||||||
Discount float64 `json:"discount"`
|
Discount float64 `json:"discount"`
|
||||||
MapApple string `json:"map_apple"`
|
MapApple string `json:"map_apple"`
|
||||||
}
|
}
|
||||||
SubscribePromo {
|
|
||||||
RuleName string `json:"rule_name"`
|
|
||||||
RuleType string `json:"rule_type"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
ExpiresAt int64 `json:"expires_at"`
|
|
||||||
}
|
|
||||||
TrafficLimit {
|
TrafficLimit {
|
||||||
StatType string `json:"stat_type"`
|
StatType string `json:"stat_type"`
|
||||||
StatValue int64 `json:"stat_value"`
|
StatValue int64 `json:"stat_value"`
|
||||||
@@ -250,7 +244,6 @@ type (
|
|||||||
UnitPrice int64 `json:"unit_price"`
|
UnitPrice int64 `json:"unit_price"`
|
||||||
UnitTime string `json:"unit_time"`
|
UnitTime string `json:"unit_time"`
|
||||||
Discount []SubscribeDiscount `json:"discount"`
|
Discount []SubscribeDiscount `json:"discount"`
|
||||||
Promo *SubscribePromo `json:"promo"`
|
|
||||||
NodeCount int64 `json:"node_count"`
|
NodeCount int64 `json:"node_count"`
|
||||||
Replacement int64 `json:"replacement"`
|
Replacement int64 `json:"replacement"`
|
||||||
Inventory int64 `json:"inventory"`
|
Inventory int64 `json:"inventory"`
|
||||||
@@ -434,7 +427,6 @@ type (
|
|||||||
FeeAmount int64 `json:"fee_amount"`
|
FeeAmount int64 `json:"fee_amount"`
|
||||||
TradeNo string `json:"trade_no"`
|
TradeNo string `json:"trade_no"`
|
||||||
Status uint8 `json:"status"`
|
Status uint8 `json:"status"`
|
||||||
StatusName string `json:"status_name,omitempty"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
CreatedAt int64 `json:"created_at"`
|
CreatedAt int64 `json:"created_at"`
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
UpdatedAt int64 `json:"updated_at"`
|
||||||
@@ -457,7 +449,6 @@ type (
|
|||||||
FeeAmount int64 `json:"fee_amount"`
|
FeeAmount int64 `json:"fee_amount"`
|
||||||
TradeNo string `json:"trade_no"`
|
TradeNo string `json:"trade_no"`
|
||||||
Status uint8 `json:"status"`
|
Status uint8 `json:"status"`
|
||||||
StatusName string `json:"status_name,omitempty"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
Subscribe Subscribe `json:"subscribe"`
|
Subscribe Subscribe `json:"subscribe"`
|
||||||
CreatedAt int64 `json:"created_at"`
|
CreatedAt int64 `json:"created_at"`
|
||||||
@@ -543,35 +534,6 @@ type (
|
|||||||
CreatedAt int64 `json:"created_at"`
|
CreatedAt int64 `json:"created_at"`
|
||||||
UpdatedAt int64 `json:"updated_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 {
|
UserAffiliate {
|
||||||
Avatar string `json:"avatar"`
|
Avatar string `json:"avatar"`
|
||||||
Identifier string `json:"identifier"`
|
Identifier string `json:"identifier"`
|
||||||
@@ -715,7 +677,6 @@ type (
|
|||||||
Price int64 `json:"price"`
|
Price int64 `json:"price"`
|
||||||
Amount int64 `json:"amount"`
|
Amount int64 `json:"amount"`
|
||||||
Discount int64 `json:"discount"`
|
Discount int64 `json:"discount"`
|
||||||
PromoDiscount int64 `json:"promo_discount"`
|
|
||||||
GiftAmount int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
Coupon string `json:"coupon"`
|
Coupon string `json:"coupon"`
|
||||||
CouponDiscount int64 `json:"coupon_discount"`
|
CouponDiscount int64 `json:"coupon_discount"`
|
||||||
|
|||||||
@@ -1,358 +0,0 @@
|
|||||||
# 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) 为准。
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
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
|
|
||||||
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
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=
|
|
||||||
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
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"
|
|
||||||
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,187 +0,0 @@
|
|||||||
# 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`
|
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
# 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`
|
|
||||||
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
|
||||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
|
||||||
QyNTUxOQAAACBsJxZDjKvaIdVjer3QMHRYw43wkVnzHurA2TQqHlr1YwAAAKBaQXT3WkF0
|
|
||||||
9wAAAAtzc2gtZWQyNTUxOQAAACBsJxZDjKvaIdVjer3QMHRYw43wkVnzHurA2TQqHlr1Yw
|
|
||||||
AAAEArWQWWwPoJp+za5JhSnrE0Pw1/TtqWRrdY5e8hULqYDGwnFkOMq9oh1WN6vdAwdFjD
|
|
||||||
jfCRWfMe6sDZNCoeWvVjAAAAF0FwcGxlQE1hY0Jvb2stUHJvLmxvY2FsAQIDBAUG
|
|
||||||
-----END OPENSSH PRIVATE KEY-----
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGwnFkOMq9oh1WN6vdAwdFjDjfCRWfMe6sDZNCoeWvVj Apple@MacBook-Pro.local
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
[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
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
[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
|
|
||||||
@@ -1,144 +0,0 @@
|
|||||||
# 提现接口文档
|
|
||||||
|
|
||||||
## 基础信息
|
|
||||||
|
|
||||||
| 项目 | 值 |
|
|
||||||
|------|-----|
|
|
||||||
| 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,10 +19,9 @@ services:
|
|||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
# 1. 业务后端 (PPanel Server)
|
# 1. 业务后端 (PPanel Server)
|
||||||
# host 网络:可出外网,直接访问 AWS RDS/Redis;通过 127.0.0.1 访问 Tempo
|
# host 网络:可出外网,直接访问 AWS RDS/Redis;通过 127.0.0.1 访问 Tempo
|
||||||
# PPANEL_SERVER_TAG 由 CI/CD 传入不可变镜像标签(如 git SHA)
|
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
ppanel-server:
|
ppanel-server:
|
||||||
image: registry.kxsw.us/vpn-server:${PPANEL_SERVER_TAG:?please set PPANEL_SERVER_TAG to an immutable image tag}
|
image: registry.kxsw.us/vpn-server:${PPANEL_SERVER_TAG:-latest}
|
||||||
container_name: ppanel-server
|
container_name: ppanel-server
|
||||||
restart: always
|
restart: always
|
||||||
volumes:
|
volumes:
|
||||||
@@ -120,7 +119,7 @@ services:
|
|||||||
# 或配置 Nginx 反代(建议加认证)
|
# 或配置 Nginx 反代(建议加认证)
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
grafana:
|
grafana:
|
||||||
image: grafana/grafana:13.0.1
|
image: grafana/grafana:latest
|
||||||
container_name: ppanel-grafana
|
container_name: ppanel-grafana
|
||||||
restart: always
|
restart: always
|
||||||
ports:
|
ports:
|
||||||
@@ -155,7 +154,7 @@ services:
|
|||||||
# 6. Prometheus (指标采集)
|
# 6. Prometheus (指标采集)
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
prometheus:
|
prometheus:
|
||||||
image: prom/prometheus:v3.11.3
|
image: prom/prometheus:latest
|
||||||
container_name: ppanel-prometheus
|
container_name: ppanel-prometheus
|
||||||
restart: always
|
restart: always
|
||||||
ports:
|
ports:
|
||||||
@@ -180,7 +179,7 @@ services:
|
|||||||
# 7. Nginx Exporter (监控宿主机 Nginx)
|
# 7. Nginx Exporter (监控宿主机 Nginx)
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
nginx-exporter:
|
nginx-exporter:
|
||||||
image: nginx/nginx-prometheus-exporter:1.5.0
|
image: nginx/nginx-prometheus-exporter:latest
|
||||||
container_name: ppanel-nginx-exporter
|
container_name: ppanel-nginx-exporter
|
||||||
restart: always
|
restart: always
|
||||||
command:
|
command:
|
||||||
@@ -199,7 +198,7 @@ services:
|
|||||||
# 8. Node Exporter (宿主机监控)
|
# 8. Node Exporter (宿主机监控)
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
node-exporter:
|
node-exporter:
|
||||||
image: prom/node-exporter:v1.11.1
|
image: prom/node-exporter:latest
|
||||||
container_name: ppanel-node-exporter
|
container_name: ppanel-node-exporter
|
||||||
restart: always
|
restart: always
|
||||||
volumes:
|
volumes:
|
||||||
@@ -222,7 +221,7 @@ services:
|
|||||||
# 9. cAdvisor (容器监控)
|
# 9. cAdvisor (容器监控)
|
||||||
# ----------------------------------------------------
|
# ----------------------------------------------------
|
||||||
cadvisor:
|
cadvisor:
|
||||||
image: gcr.io/cadvisor/cadvisor:v0.55.1
|
image: gcr.io/cadvisor/cadvisor:latest
|
||||||
container_name: ppanel-cadvisor
|
container_name: ppanel-cadvisor
|
||||||
restart: always
|
restart: always
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
-- 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;
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
-- 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)%';
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
-- 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;
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
-- Remove activation_context column from order table
|
|
||||||
ALTER TABLE `order` DROP COLUMN IF EXISTS `activation_context`;
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
-- 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;
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
ALTER TABLE `withdrawals`
|
|
||||||
DROP COLUMN `qr_code_url`,
|
|
||||||
DROP COLUMN `account`,
|
|
||||||
DROP COLUMN `method`;
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
ALTER TABLE `withdrawals`
|
|
||||||
ADD COLUMN `method` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '收款方式 0:其他 1:支付宝 2:微信 3:银行卡' AFTER `content`,
|
|
||||||
ADD COLUMN `account` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '收款账号' AFTER `method`,
|
|
||||||
ADD COLUMN `qr_code_url` VARCHAR(500) NOT NULL DEFAULT '' COMMENT '收款码图片URL' AFTER `account`;
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
-- Purpose: Rollback user-level speed limit overrides from user_subscribe
|
|
||||||
|
|
||||||
ALTER TABLE `user_subscribe`
|
|
||||||
DROP COLUMN IF EXISTS `traffic_limit`,
|
|
||||||
DROP COLUMN IF EXISTS `speed_limit`;
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
-- Purpose: Add user-level speed limit overrides to user_subscribe
|
|
||||||
|
|
||||||
SET @column_exists = (
|
|
||||||
SELECT COUNT(*)
|
|
||||||
FROM INFORMATION_SCHEMA.COLUMNS
|
|
||||||
WHERE TABLE_SCHEMA = DATABASE()
|
|
||||||
AND TABLE_NAME = 'user_subscribe'
|
|
||||||
AND COLUMN_NAME = 'speed_limit'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@column_exists = 0,
|
|
||||||
'ALTER TABLE `user_subscribe` ADD COLUMN `speed_limit` int NOT NULL DEFAULT 0 COMMENT ''User-level speed limit override (Mbps, 0=use plan default)'' AFTER `upload`',
|
|
||||||
'SELECT ''Column speed_limit already exists in user_subscribe 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 = 'user_subscribe'
|
|
||||||
AND COLUMN_NAME = 'traffic_limit'
|
|
||||||
);
|
|
||||||
|
|
||||||
SET @sql = IF(
|
|
||||||
@column_exists = 0,
|
|
||||||
'ALTER TABLE `user_subscribe` ADD COLUMN `traffic_limit` text DEFAULT NULL COMMENT ''User-level traffic limit rules override (JSON, NULL=use plan default)'' AFTER `speed_limit`',
|
|
||||||
'SELECT ''Column traffic_limit already exists in user_subscribe table'''
|
|
||||||
);
|
|
||||||
|
|
||||||
PREPARE stmt FROM @sql;
|
|
||||||
EXECUTE stmt;
|
|
||||||
DEALLOCATE PREPARE stmt;
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
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`;
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
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` (`enabled`, `priority` DESC),
|
|
||||||
KEY `idx_deleted_at` (`deleted_at`)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='促销规则表';
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `subscribe_promo` (
|
|
||||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
|
||||||
`subscribe_id` BIGINT UNSIGNED NOT NULL COMMENT '套餐规格 ID',
|
|
||||||
`promo_rule_id` BIGINT UNSIGNED NOT NULL COMMENT '促销规则 ID',
|
|
||||||
`promo_price` BIGINT NOT NULL DEFAULT 0 COMMENT '该规格在此规则下的优惠价(分)',
|
|
||||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
|
||||||
PRIMARY KEY (`id`),
|
|
||||||
UNIQUE KEY `uk_subscribe_rule` (`subscribe_id`, `promo_rule_id`),
|
|
||||||
KEY `idx_promo_rule_id` (`promo_rule_id`)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规格促销价表';
|
|
||||||
|
|
||||||
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;
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package log
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/log"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
func FilterOrderRefundLogHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.FilterOrderRefundLogRequest
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
validateErr := svcCtx.Validate(&req)
|
|
||||||
if validateErr != nil {
|
|
||||||
result.ParamErrorResult(c, validateErr)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := log.NewFilterOrderRefundLogLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.FilterOrderRefundLog(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package order
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/perfect-panel/server/internal/logic/admin/order"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/result"
|
|
||||||
)
|
|
||||||
|
|
||||||
func RefundOrderHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.RefundOrderRequest
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
validateErr := svcCtx.Validate(&req)
|
|
||||||
if validateErr != nil {
|
|
||||||
result.ParamErrorResult(c, validateErr)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := order.NewRefundOrderLogic(c.Request.Context(), svcCtx)
|
|
||||||
err := l.RefundOrder(&req)
|
|
||||||
result.HttpResult(c, nil, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
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"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Batch set promo price
|
|
||||||
func CreatePromoPriceHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.CreatePromoPriceRequest
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := promo.NewCreatePromoPriceLogic(c.Request.Context(), svcCtx)
|
|
||||||
err := l.CreatePromoPrice(&req)
|
|
||||||
result.HttpResult(c, nil, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
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"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Create promo rule
|
|
||||||
func CreatePromoRuleHandler(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.NewCreatePromoRuleLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.CreatePromoRule(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"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"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Delete promo price
|
|
||||||
func DeletePromoPriceHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.DeletePromoPriceRequest
|
|
||||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.String(http.StatusBadRequest, "Invalid Params")
|
|
||||||
c.Abort()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
req.Id = id
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := promo.NewDeletePromoPriceLogic(c.Request.Context(), svcCtx)
|
|
||||||
err = l.DeletePromoPrice(&req)
|
|
||||||
result.HttpResult(c, nil, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"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"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Delete promo rule
|
|
||||||
func DeletePromoRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.DeletePromoRuleRequest
|
|
||||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.String(http.StatusBadRequest, "Invalid Params")
|
|
||||||
c.Abort()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
req.Id = id
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := promo.NewDeletePromoRuleLogic(c.Request.Context(), svcCtx)
|
|
||||||
err = l.DeletePromoRule(&req)
|
|
||||||
result.HttpResult(c, nil, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
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"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Get promo price list
|
|
||||||
func GetPromoPriceListHandler(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.NewGetPromoPriceListLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.GetPromoPriceList(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"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"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Get promo rule detail
|
|
||||||
func GetPromoRuleDetailHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.GetPromoRuleDetailRequest
|
|
||||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.String(http.StatusBadRequest, "Invalid Params")
|
|
||||||
c.Abort()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
req.Id = id
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := promo.NewGetPromoRuleDetailLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.GetPromoRuleDetail(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
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"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Get promo rule list
|
|
||||||
func GetPromoRuleListHandler(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.NewGetPromoRuleListLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.GetPromoRuleList(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
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"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Get promo usage list
|
|
||||||
func GetPromoUsageListHandler(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.NewGetPromoUsageListLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.GetPromoUsageList(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"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"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Update promo rule
|
|
||||||
func UpdatePromoRuleHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
var req types.UpdatePromoRuleRequest
|
|
||||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
c.String(http.StatusBadRequest, "Invalid Params")
|
|
||||||
c.Abort()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
_ = c.ShouldBind(&req)
|
|
||||||
req.Id = id
|
|
||||||
if err := svcCtx.Validate(&req); err != nil {
|
|
||||||
result.ParamErrorResult(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l := promo.NewUpdatePromoRuleLogic(c.Request.Context(), svcCtx)
|
|
||||||
resp, err := l.UpdatePromoRule(&req)
|
|
||||||
result.HttpResult(c, resp, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -17,7 +17,6 @@ import (
|
|||||||
adminMarketing "github.com/perfect-panel/server/internal/handler/admin/marketing"
|
adminMarketing "github.com/perfect-panel/server/internal/handler/admin/marketing"
|
||||||
adminOrder "github.com/perfect-panel/server/internal/handler/admin/order"
|
adminOrder "github.com/perfect-panel/server/internal/handler/admin/order"
|
||||||
adminPayment "github.com/perfect-panel/server/internal/handler/admin/payment"
|
adminPayment "github.com/perfect-panel/server/internal/handler/admin/payment"
|
||||||
adminPromo "github.com/perfect-panel/server/internal/handler/admin/promo"
|
|
||||||
adminRedemption "github.com/perfect-panel/server/internal/handler/admin/redemption"
|
adminRedemption "github.com/perfect-panel/server/internal/handler/admin/redemption"
|
||||||
adminServer "github.com/perfect-panel/server/internal/handler/admin/server"
|
adminServer "github.com/perfect-panel/server/internal/handler/admin/server"
|
||||||
adminSubscribe "github.com/perfect-panel/server/internal/handler/admin/subscribe"
|
adminSubscribe "github.com/perfect-panel/server/internal/handler/admin/subscribe"
|
||||||
@@ -251,18 +250,12 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
|||||||
// Filter commission log
|
// Filter commission log
|
||||||
adminLogGroupRouter.GET("/commission/list", adminLog.FilterCommissionLogHandler(serverCtx))
|
adminLogGroupRouter.GET("/commission/list", adminLog.FilterCommissionLogHandler(serverCtx))
|
||||||
|
|
||||||
// Filter order refund log
|
|
||||||
adminLogGroupRouter.GET("/order/refund/list", adminLog.FilterOrderRefundLogHandler(serverCtx))
|
|
||||||
|
|
||||||
// Filter email log
|
// Filter email log
|
||||||
adminLogGroupRouter.GET("/email/list", adminLog.FilterEmailLogHandler(serverCtx))
|
adminLogGroupRouter.GET("/email/list", adminLog.FilterEmailLogHandler(serverCtx))
|
||||||
|
|
||||||
// Get error log message detail
|
// Get error log message detail
|
||||||
adminLogGroupRouter.GET("/error_message/detail", adminLog.GetErrorLogMessageDetailHandler(serverCtx))
|
adminLogGroupRouter.GET("/error_message/detail", adminLog.GetErrorLogMessageDetailHandler(serverCtx))
|
||||||
|
|
||||||
// Get log message raw detail (temporary)
|
|
||||||
adminLogGroupRouter.GET("/message/detail", adminLog.GetLogMessageRawHandler(serverCtx))
|
|
||||||
|
|
||||||
// Get error log message list
|
// Get error log message list
|
||||||
adminLogGroupRouter.GET("/error_message/list", adminLog.GetErrorLogMessageListHandler(serverCtx))
|
adminLogGroupRouter.GET("/error_message/list", adminLog.GetErrorLogMessageListHandler(serverCtx))
|
||||||
|
|
||||||
@@ -348,9 +341,6 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
|||||||
// Update order status
|
// Update order status
|
||||||
adminOrderGroupRouter.PUT("/status", adminOrder.UpdateOrderStatusHandler(serverCtx))
|
adminOrderGroupRouter.PUT("/status", adminOrder.UpdateOrderStatusHandler(serverCtx))
|
||||||
|
|
||||||
// Refund order
|
|
||||||
adminOrderGroupRouter.POST("/refund", adminOrder.RefundOrderHandler(serverCtx))
|
|
||||||
|
|
||||||
// Manually activate order
|
// Manually activate order
|
||||||
adminOrderGroupRouter.POST("/activate", adminOrder.ActivateOrderHandler(serverCtx))
|
adminOrderGroupRouter.POST("/activate", adminOrder.ActivateOrderHandler(serverCtx))
|
||||||
}
|
}
|
||||||
@@ -375,38 +365,6 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
|||||||
adminPaymentGroupRouter.GET("/platform", adminPayment.GetPaymentPlatformHandler(serverCtx))
|
adminPaymentGroupRouter.GET("/platform", adminPayment.GetPaymentPlatformHandler(serverCtx))
|
||||||
}
|
}
|
||||||
|
|
||||||
adminPromoGroupRouter := router.Group("/v1/admin/promo")
|
|
||||||
adminPromoGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
|
||||||
|
|
||||||
{
|
|
||||||
// Create promo rule
|
|
||||||
adminPromoGroupRouter.POST("/rule", adminPromo.CreatePromoRuleHandler(serverCtx))
|
|
||||||
|
|
||||||
// Get promo rule list
|
|
||||||
adminPromoGroupRouter.GET("/rule/list", adminPromo.GetPromoRuleListHandler(serverCtx))
|
|
||||||
|
|
||||||
// Get promo rule detail
|
|
||||||
adminPromoGroupRouter.GET("/rule/:id", adminPromo.GetPromoRuleDetailHandler(serverCtx))
|
|
||||||
|
|
||||||
// Update promo rule
|
|
||||||
adminPromoGroupRouter.PUT("/rule/:id", adminPromo.UpdatePromoRuleHandler(serverCtx))
|
|
||||||
|
|
||||||
// Delete promo rule
|
|
||||||
adminPromoGroupRouter.DELETE("/rule/:id", adminPromo.DeletePromoRuleHandler(serverCtx))
|
|
||||||
|
|
||||||
// Batch set promo price
|
|
||||||
adminPromoGroupRouter.POST("/price", adminPromo.CreatePromoPriceHandler(serverCtx))
|
|
||||||
|
|
||||||
// Get promo price list
|
|
||||||
adminPromoGroupRouter.GET("/price/list", adminPromo.GetPromoPriceListHandler(serverCtx))
|
|
||||||
|
|
||||||
// Delete promo price
|
|
||||||
adminPromoGroupRouter.DELETE("/price/:id", adminPromo.DeletePromoPriceHandler(serverCtx))
|
|
||||||
|
|
||||||
// Get promo usage list
|
|
||||||
adminPromoGroupRouter.GET("/usage/list", adminPromo.GetPromoUsageListHandler(serverCtx))
|
|
||||||
}
|
|
||||||
|
|
||||||
adminRedemptionGroupRouter := router.Group("/v1/admin/redemption")
|
adminRedemptionGroupRouter := router.Group("/v1/admin/redemption")
|
||||||
adminRedemptionGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
adminRedemptionGroupRouter.Use(middleware.AuthMiddleware(serverCtx))
|
||||||
|
|
||||||
@@ -1011,16 +969,17 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
publicSubscribeGroupRouter := router.Group("/v1/public/subscribe")
|
publicSubscribeGroupRouter := router.Group("/v1/public/subscribe")
|
||||||
|
publicSubscribeGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
|
||||||
|
|
||||||
{
|
{
|
||||||
// Get subscribe list
|
// Get subscribe list
|
||||||
publicSubscribeGroupRouter.GET("/list", middleware.OptionalAuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx), publicSubscribe.QuerySubscribeListHandler(serverCtx))
|
publicSubscribeGroupRouter.GET("/list", publicSubscribe.QuerySubscribeListHandler(serverCtx))
|
||||||
|
|
||||||
// Get user subscribe node info
|
// Get user subscribe node info
|
||||||
publicSubscribeGroupRouter.GET("/node/list", middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx), publicSubscribe.QueryUserSubscribeNodeListHandler(serverCtx))
|
publicSubscribeGroupRouter.GET("/node/list", publicSubscribe.QueryUserSubscribeNodeListHandler(serverCtx))
|
||||||
|
|
||||||
// Get subscribe group list
|
// Get subscribe group list
|
||||||
publicSubscribeGroupRouter.GET("/group/list", middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx), publicSubscribe.QuerySubscribeGroupListHandler(serverCtx))
|
publicSubscribeGroupRouter.GET("/group/list", publicSubscribe.QuerySubscribeGroupListHandler(serverCtx))
|
||||||
}
|
}
|
||||||
|
|
||||||
publicTicketGroupRouter := router.Group("/v1/public/ticket")
|
publicTicketGroupRouter := router.Group("/v1/public/ticket")
|
||||||
@@ -1091,9 +1050,6 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
|
|||||||
// Commission Withdraw
|
// Commission Withdraw
|
||||||
publicUserGroupRouter.POST("/commission_withdraw", publicUser.CommissionWithdrawHandler(serverCtx))
|
publicUserGroupRouter.POST("/commission_withdraw", publicUser.CommissionWithdrawHandler(serverCtx))
|
||||||
|
|
||||||
// Cancel Withdrawal
|
|
||||||
publicUserGroupRouter.POST("/withdrawal_cancel", publicUser.CancelWithdrawalHandler(serverCtx))
|
|
||||||
|
|
||||||
// Delete Current User Account
|
// Delete Current User Account
|
||||||
publicUserGroupRouter.DELETE("/current_user_account", publicUser.DeleteCurrentUserAccountHandler(serverCtx))
|
publicUserGroupRouter.DELETE("/current_user_account", publicUser.DeleteCurrentUserAccountHandler(serverCtx))
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ func (l *DeleteSubscribeApplicationLogic) DeleteSubscribeApplication(req *types.
|
|||||||
err := l.svcCtx.ClientModel.Delete(l.ctx, req.Id)
|
err := l.svcCtx.ClientModel.Delete(l.ctx, req.Id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorf("Failed to delete subscribe application with ID %d: %v", req.Id, err)
|
l.Errorf("Failed to delete subscribe application with ID %d: %v", req.Id, err)
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseDeletedError), err.Error())
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), err.Error())
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,77 +0,0 @@
|
|||||||
package log
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
modellog "github.com/perfect-panel/server/internal/model/log"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type FilterOrderRefundLogLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewFilterOrderRefundLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterOrderRefundLogLogic {
|
|
||||||
return &FilterOrderRefundLogLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *FilterOrderRefundLogLogic) FilterOrderRefundLog(req *types.FilterOrderRefundLogRequest) (resp *types.FilterOrderRefundLogResponse, err error) {
|
|
||||||
data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &modellog.FilterParams{
|
|
||||||
Page: req.Page,
|
|
||||||
Size: req.Size,
|
|
||||||
Data: req.Date,
|
|
||||||
Search: req.Search,
|
|
||||||
Type: modellog.TypeOrderRefund.Uint8(),
|
|
||||||
ObjectID: req.OrderId,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("Query order refund log failed", logger.Field("error", err.Error()))
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Query order refund log failed")
|
|
||||||
}
|
|
||||||
|
|
||||||
var list []types.OrderRefundLog
|
|
||||||
for _, item := range data {
|
|
||||||
var content modellog.OrderRefund
|
|
||||||
if err := content.Unmarshal([]byte(item.Content)); err != nil {
|
|
||||||
l.Errorf("unmarshal order refund log content failed: %v", err.Error())
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if req.UserId > 0 && content.TargetUserId != req.UserId && content.RefererUserId != req.UserId && content.OperatorUserId != req.UserId {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
list = append(list, types.OrderRefundLog{
|
|
||||||
OrderId: content.OrderId,
|
|
||||||
OrderNo: content.OrderNo,
|
|
||||||
OperatorUserId: content.OperatorUserId,
|
|
||||||
OperatorAuthIdentifier: content.OperatorAuthIdentifier,
|
|
||||||
TargetUserId: content.TargetUserId,
|
|
||||||
UserSubscribeId: content.UserSubscribeId,
|
|
||||||
RefererUserId: content.RefererUserId,
|
|
||||||
CommissionAmount: content.CommissionAmount,
|
|
||||||
Reason: content.Reason,
|
|
||||||
OrderStatusBefore: content.OrderStatusBefore,
|
|
||||||
OrderStatusAfter: content.OrderStatusAfter,
|
|
||||||
SubscribeStatusBefore: content.SubscribeStatusBefore,
|
|
||||||
SubscribeStatusAfter: content.SubscribeStatusAfter,
|
|
||||||
SubscribeExpireBefore: content.SubscribeExpireBefore,
|
|
||||||
SubscribeExpireAfter: content.SubscribeExpireAfter,
|
|
||||||
CommissionBefore: content.CommissionBefore,
|
|
||||||
CommissionAfter: content.CommissionAfter,
|
|
||||||
Timestamp: content.Timestamp,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return &types.FilterOrderRefundLogResponse{
|
|
||||||
Total: total,
|
|
||||||
List: list,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
package log
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GetLogMessageRawLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewGetLogMessageRawLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetLogMessageRawLogic {
|
|
||||||
return &GetLogMessageRawLogic{Logger: logger.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *GetLogMessageRawLogic) GetLogMessageRaw(req *types.GetLogMessageRawRequest) (resp *types.GetLogMessageRawResponse, err error) {
|
|
||||||
row, err := l.svcCtx.LogMessageModel.FindOne(l.ctx, req.Id)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "FindOne log_message id=%d: %v", req.Id, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var contextJSON json.RawMessage
|
|
||||||
if row.Context != "" {
|
|
||||||
if json.Valid([]byte(row.Context)) {
|
|
||||||
contextJSON = json.RawMessage(row.Context)
|
|
||||||
} else {
|
|
||||||
b, _ := json.Marshal(row.Context)
|
|
||||||
contextJSON = b
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var occurredAt int64
|
|
||||||
if row.OccurredAt != nil {
|
|
||||||
occurredAt = row.OccurredAt.UnixMilli()
|
|
||||||
}
|
|
||||||
|
|
||||||
return &types.GetLogMessageRawResponse{
|
|
||||||
Id: row.Id,
|
|
||||||
Platform: row.Platform,
|
|
||||||
AppVersion: row.AppVersion,
|
|
||||||
OsName: row.OsName,
|
|
||||||
OsVersion: row.OsVersion,
|
|
||||||
DeviceId: row.DeviceId,
|
|
||||||
UserId: row.UserId,
|
|
||||||
SessionId: row.SessionId,
|
|
||||||
Level: row.Level,
|
|
||||||
ErrorCode: row.ErrorCode,
|
|
||||||
Message: row.Message,
|
|
||||||
Stack: row.Stack,
|
|
||||||
Context: contextJSON,
|
|
||||||
ClientIP: row.ClientIP,
|
|
||||||
UserAgent: row.UserAgent,
|
|
||||||
Locale: row.Locale,
|
|
||||||
Digest: row.Digest,
|
|
||||||
OccurredAt: occurredAt,
|
|
||||||
CreatedAt: row.CreatedAt.UnixMilli(),
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
@@ -35,28 +35,6 @@ func (l *GetOrderListLogic) GetOrderList(req *types.GetOrderListRequest) (resp *
|
|||||||
resp = &types.GetOrderListResponse{}
|
resp = &types.GetOrderListResponse{}
|
||||||
resp.List = make([]types.Order, 0)
|
resp.List = make([]types.Order, 0)
|
||||||
tool.DeepCopy(&resp.List, list)
|
tool.DeepCopy(&resp.List, list)
|
||||||
for i := range resp.List {
|
|
||||||
resp.List[i].StatusName = orderStatusName(resp.List[i].Status)
|
|
||||||
}
|
|
||||||
resp.Total = total
|
resp.Total = total
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func orderStatusName(status uint8) string {
|
|
||||||
switch status {
|
|
||||||
case 1:
|
|
||||||
return "pending"
|
|
||||||
case 2:
|
|
||||||
return "paid"
|
|
||||||
case 3:
|
|
||||||
return "closed"
|
|
||||||
case 4:
|
|
||||||
return "failed"
|
|
||||||
case 5:
|
|
||||||
return "finished"
|
|
||||||
case 6:
|
|
||||||
return "refunded"
|
|
||||||
default:
|
|
||||||
return "unknown"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,298 +0,0 @@
|
|||||||
package order
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/model/log"
|
|
||||||
modelorder "github.com/perfect-panel/server/internal/model/order"
|
|
||||||
modeluser "github.com/perfect-panel/server/internal/model/user"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/constant"
|
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"gorm.io/gorm/clause"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
orderStatusRefunded = 6
|
|
||||||
)
|
|
||||||
|
|
||||||
type RefundOrderLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRefundOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RefundOrderLogic {
|
|
||||||
return &RefundOrderLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *RefundOrderLogic) RefundOrder(req *types.RefundOrderRequest) error {
|
|
||||||
operator, ok := l.ctx.Value(constant.CtxKeyUser).(*modeluser.User)
|
|
||||||
if !ok {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
|
|
||||||
}
|
|
||||||
|
|
||||||
reason := strings.TrimSpace(req.Reason)
|
|
||||||
var cachesToClear []*modeluser.Subscribe
|
|
||||||
var planCacheIDs []int64
|
|
||||||
var userCacheTargets []*modeluser.User
|
|
||||||
|
|
||||||
err := l.svcCtx.DB.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error {
|
|
||||||
var orderInfo modelorder.Order
|
|
||||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
|
||||||
Model(&modelorder.Order{}).
|
|
||||||
Where("id = ?", req.Id).
|
|
||||||
First(&orderInfo).Error; err != nil {
|
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.OrderNotExist), "order %d not found", req.Id)
|
|
||||||
}
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query order failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if orderInfo.Status == orderStatusRefunded {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.OrderAlreadyRefunded), "order %d already refunded", orderInfo.Id)
|
|
||||||
}
|
|
||||||
if orderInfo.Status != 2 && orderInfo.Status != 5 {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.OrderStatusError), "order %d status %d is not refundable", orderInfo.Id, orderInfo.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
userSub, err := l.lockRefundTargetSubscription(tx, &orderInfo)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
orderStatusBefore := orderInfo.Status
|
|
||||||
subStatusBefore := userSub.Status
|
|
||||||
subExpireBefore := userSub.ExpireTime
|
|
||||||
now := time.Now()
|
|
||||||
|
|
||||||
referer, commissionAmount, err := l.lockCommissionSource(tx, orderInfo.OrderNo, orderInfo.Commission)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
var commissionBefore int64
|
|
||||||
var commissionAfter int64
|
|
||||||
if referer != nil {
|
|
||||||
commissionBefore = referer.Commission
|
|
||||||
commissionAfter = referer.Commission - commissionAmount
|
|
||||||
if err := tx.Model(&modeluser.User{}).
|
|
||||||
Where("id = ?", referer.Id).
|
|
||||||
UpdateColumn("commission", gorm.Expr("commission - ?", commissionAmount)).Error; err != nil {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "refund commission failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
commissionLog := log.Commission{
|
|
||||||
Type: log.CommissionTypeRefund,
|
|
||||||
Amount: -commissionAmount,
|
|
||||||
OrderNo: orderInfo.OrderNo,
|
|
||||||
Timestamp: now.UnixMilli(),
|
|
||||||
}
|
|
||||||
content, marshalErr := commissionLog.Marshal()
|
|
||||||
if marshalErr != nil {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "marshal commission refund log failed: %v", marshalErr)
|
|
||||||
}
|
|
||||||
if err := tx.Model(&log.SystemLog{}).Create(&log.SystemLog{
|
|
||||||
Type: log.TypeCommission.Uint8(),
|
|
||||||
Date: now.Format(time.DateOnly),
|
|
||||||
ObjectID: referer.Id,
|
|
||||||
Content: string(content),
|
|
||||||
CreatedAt: now,
|
|
||||||
}).Error; err != nil {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert commission refund log failed: %v", err)
|
|
||||||
}
|
|
||||||
referer.Commission = commissionAfter
|
|
||||||
userCacheTargets = append(userCacheTargets, referer)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := tx.Model(&modelorder.Order{}).
|
|
||||||
Where("id = ? AND status IN ?", orderInfo.Id, []int{2, 5}).
|
|
||||||
Update("status", orderStatusRefunded).Error; err != nil {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "refund order status update failed: %v", err)
|
|
||||||
}
|
|
||||||
orderInfo.Status = orderStatusRefunded
|
|
||||||
|
|
||||||
userSub.Status = 3
|
|
||||||
userSub.ExpireTime = now.Add(-time.Second)
|
|
||||||
userSub.FinishedAt = &now
|
|
||||||
if err := tx.Model(&modeluser.Subscribe{}).
|
|
||||||
Where("id = ?", userSub.Id).
|
|
||||||
Updates(map[string]interface{}{
|
|
||||||
"status": userSub.Status,
|
|
||||||
"expire_time": userSub.ExpireTime,
|
|
||||||
"finished_at": userSub.FinishedAt,
|
|
||||||
}).Error; err != nil {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update subscription failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
refundLog, err := l.buildRefundAuditLog(operator, &orderInfo, userSub, referer, commissionAmount, reason, orderStatusBefore, subStatusBefore, subExpireBefore, commissionBefore, commissionAfter, now)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
logContent, err := refundLog.Marshal()
|
|
||||||
if err != nil {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "marshal refund audit log failed: %v", err)
|
|
||||||
}
|
|
||||||
if err := tx.Model(&log.SystemLog{}).Create(&log.SystemLog{
|
|
||||||
Type: log.TypeOrderRefund.Uint8(),
|
|
||||||
Date: now.Format(time.DateOnly),
|
|
||||||
ObjectID: orderInfo.Id,
|
|
||||||
Content: string(logContent),
|
|
||||||
CreatedAt: now,
|
|
||||||
}).Error; err != nil {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert refund audit log failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cachesToClear = append(cachesToClear, userSub)
|
|
||||||
if userSub.SubscribeId > 0 {
|
|
||||||
planCacheIDs = append(planCacheIDs, userSub.SubscribeId)
|
|
||||||
}
|
|
||||||
if orderInfo.UserId > 0 {
|
|
||||||
orderUser := &modeluser.User{Id: orderInfo.UserId}
|
|
||||||
userCacheTargets = append(userCacheTargets, orderUser)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[RefundOrder] refund failed", logger.Field("error", err.Error()), logger.Field("order_id", req.Id))
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(cachesToClear) > 0 {
|
|
||||||
if clearErr := l.svcCtx.UserModel.ClearSubscribeCache(l.ctx, cachesToClear...); clearErr != nil {
|
|
||||||
l.Errorw("[RefundOrder] clear subscribe cache failed", logger.Field("error", clearErr.Error()), logger.Field("order_id", req.Id))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, subscribeID := range planCacheIDs {
|
|
||||||
if clearErr := l.svcCtx.SubscribeModel.ClearCache(l.ctx, subscribeID); clearErr != nil {
|
|
||||||
l.Errorw("[RefundOrder] clear subscribe cache failed", logger.Field("error", clearErr.Error()), logger.Field("subscribe_id", subscribeID))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(userCacheTargets) > 0 {
|
|
||||||
if clearErr := l.svcCtx.UserModel.ClearUserCache(l.ctx, userCacheTargets...); clearErr != nil {
|
|
||||||
l.Errorw("[RefundOrder] clear user cache failed", logger.Field("error", clearErr.Error()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *RefundOrderLogic) lockRefundTargetSubscription(tx *gorm.DB, orderInfo *modelorder.Order) (*modeluser.Subscribe, error) {
|
|
||||||
var userSub modeluser.Subscribe
|
|
||||||
err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
|
||||||
Model(&modeluser.Subscribe{}).
|
|
||||||
Where("order_id = ?", orderInfo.Id).
|
|
||||||
First(&userSub).Error
|
|
||||||
if err == nil {
|
|
||||||
return &userSub, nil
|
|
||||||
}
|
|
||||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query refund subscription failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if orderInfo.Type != 2 {
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.OrderRefundNoSubscription), "order %d has no linked subscription", orderInfo.Id)
|
|
||||||
}
|
|
||||||
|
|
||||||
if orderInfo.ParentId == 0 {
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.OrderRefundNoSubscription), "renewal order %d has no parent order", orderInfo.Id)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
|
||||||
Model(&modeluser.Subscribe{}).
|
|
||||||
Where("order_id = ?", orderInfo.ParentId).
|
|
||||||
First(&userSub).Error
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.OrderRefundNoSubscription), "renewal order %d parent subscription not found", orderInfo.Id)
|
|
||||||
}
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query renewal subscription failed: %v", err)
|
|
||||||
}
|
|
||||||
return &userSub, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *RefundOrderLogic) lockCommissionSource(tx *gorm.DB, orderNo string, orderCommission int64) (*modeluser.User, int64, error) {
|
|
||||||
var commissionLogs []log.SystemLog
|
|
||||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
|
||||||
Model(&log.SystemLog{}).
|
|
||||||
Where("type = ? AND content LIKE ?", log.TypeCommission.Uint8(), fmt.Sprintf("%%\"order_no\":\"%s\"%%", orderNo)).
|
|
||||||
Order("id DESC").
|
|
||||||
Find(&commissionLogs).Error; err != nil {
|
|
||||||
return nil, 0, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query commission log failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, item := range commissionLogs {
|
|
||||||
var content log.Commission
|
|
||||||
if err := content.Unmarshal([]byte(item.Content)); err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if content.Type != log.CommissionTypePurchase && content.Type != log.CommissionTypeRenewal {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
var referer modeluser.User
|
|
||||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
|
||||||
Model(&modeluser.User{}).
|
|
||||||
Where("id = ?", item.ObjectID).
|
|
||||||
First(&referer).Error; err != nil {
|
|
||||||
return nil, 0, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query commission owner failed: %v", err)
|
|
||||||
}
|
|
||||||
return &referer, content.Amount, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if orderCommission > 0 {
|
|
||||||
return nil, 0, errors.Wrapf(xerr.NewErrCode(xerr.OrderRefundCommissionMismatch), "order %s commission owner not found", orderNo)
|
|
||||||
}
|
|
||||||
return nil, 0, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *RefundOrderLogic) buildRefundAuditLog(
|
|
||||||
operator *modeluser.User,
|
|
||||||
orderInfo *modelorder.Order,
|
|
||||||
userSub *modeluser.Subscribe,
|
|
||||||
referer *modeluser.User,
|
|
||||||
commissionAmount int64,
|
|
||||||
reason string,
|
|
||||||
orderStatusBefore uint8,
|
|
||||||
subStatusBefore uint8,
|
|
||||||
subExpireBefore time.Time,
|
|
||||||
commissionBefore int64,
|
|
||||||
commissionAfter int64,
|
|
||||||
now time.Time,
|
|
||||||
) (*log.OrderRefund, error) {
|
|
||||||
refundLog := &log.OrderRefund{
|
|
||||||
OrderId: orderInfo.Id,
|
|
||||||
OrderNo: orderInfo.OrderNo,
|
|
||||||
OperatorUserId: operator.Id,
|
|
||||||
TargetUserId: userSub.UserId,
|
|
||||||
UserSubscribeId: userSub.Id,
|
|
||||||
CommissionAmount: commissionAmount,
|
|
||||||
Reason: reason,
|
|
||||||
OrderStatusBefore: orderStatusBefore,
|
|
||||||
OrderStatusAfter: orderInfo.Status,
|
|
||||||
SubscribeStatusBefore: subStatusBefore,
|
|
||||||
SubscribeStatusAfter: userSub.Status,
|
|
||||||
SubscribeExpireBefore: subExpireBefore.UnixMilli(),
|
|
||||||
SubscribeExpireAfter: userSub.ExpireTime.UnixMilli(),
|
|
||||||
CommissionBefore: commissionBefore,
|
|
||||||
CommissionAfter: commissionAfter,
|
|
||||||
Timestamp: now.UnixMilli(),
|
|
||||||
}
|
|
||||||
if referer != nil {
|
|
||||||
refundLog.RefererUserId = referer.Id
|
|
||||||
}
|
|
||||||
if len(operator.AuthMethods) > 0 {
|
|
||||||
refundLog.OperatorAuthIdentifier = operator.AuthMethods[0].AuthIdentifier
|
|
||||||
}
|
|
||||||
return refundLog, nil
|
|
||||||
}
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
package order
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
modelorder "github.com/perfect-panel/server/internal/model/order"
|
|
||||||
modeluser "github.com/perfect-panel/server/internal/model/user"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestOrderStatusName(t *testing.T) {
|
|
||||||
tests := map[uint8]string{
|
|
||||||
1: "pending",
|
|
||||||
2: "paid",
|
|
||||||
3: "closed",
|
|
||||||
4: "failed",
|
|
||||||
5: "finished",
|
|
||||||
6: "refunded",
|
|
||||||
7: "unknown",
|
|
||||||
}
|
|
||||||
|
|
||||||
for input, want := range tests {
|
|
||||||
if got := orderStatusName(input); got != want {
|
|
||||||
t.Fatalf("status %d: got %q want %q", input, got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBuildRefundAuditLog(t *testing.T) {
|
|
||||||
logic := &RefundOrderLogic{}
|
|
||||||
now := time.Unix(1710000000, 0)
|
|
||||||
expireBefore := now.Add(24 * time.Hour)
|
|
||||||
expireAfter := now.Add(-time.Second)
|
|
||||||
operator := &modeluser.User{
|
|
||||||
Id: 100,
|
|
||||||
AuthMethods: []modeluser.AuthMethods{
|
|
||||||
{AuthIdentifier: "admin@example.com"},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
orderInfo := &modelorder.Order{Id: 10, OrderNo: "ORD-1", Status: orderStatusRefunded}
|
|
||||||
userSub := &modeluser.Subscribe{Id: 20, UserId: 30, Status: 3, ExpireTime: expireAfter}
|
|
||||||
referer := &modeluser.User{Id: 40}
|
|
||||||
|
|
||||||
got, err := logic.buildRefundAuditLog(
|
|
||||||
operator,
|
|
||||||
orderInfo,
|
|
||||||
userSub,
|
|
||||||
referer,
|
|
||||||
500,
|
|
||||||
"manual refund",
|
|
||||||
5,
|
|
||||||
1,
|
|
||||||
expireBefore,
|
|
||||||
900,
|
|
||||||
400,
|
|
||||||
now,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("buildRefundAuditLog error: %v", err)
|
|
||||||
}
|
|
||||||
if got.OrderId != 10 || got.OrderNo != "ORD-1" {
|
|
||||||
t.Fatalf("unexpected order info: %+v", got)
|
|
||||||
}
|
|
||||||
if got.OperatorUserId != 100 || got.OperatorAuthIdentifier != "admin@example.com" {
|
|
||||||
t.Fatalf("unexpected operator info: %+v", got)
|
|
||||||
}
|
|
||||||
if got.TargetUserId != 30 || got.UserSubscribeId != 20 {
|
|
||||||
t.Fatalf("unexpected subscription info: %+v", got)
|
|
||||||
}
|
|
||||||
if got.RefererUserId != 40 || got.CommissionAmount != 500 {
|
|
||||||
t.Fatalf("unexpected commission info: %+v", got)
|
|
||||||
}
|
|
||||||
if got.OrderStatusBefore != 5 || got.OrderStatusAfter != orderStatusRefunded {
|
|
||||||
t.Fatalf("unexpected order status: %+v", got)
|
|
||||||
}
|
|
||||||
if got.SubscribeStatusBefore != 1 || got.SubscribeStatusAfter != 3 {
|
|
||||||
t.Fatalf("unexpected subscribe status: %+v", got)
|
|
||||||
}
|
|
||||||
if got.SubscribeExpireBefore != expireBefore.UnixMilli() || got.SubscribeExpireAfter != expireAfter.UnixMilli() {
|
|
||||||
t.Fatalf("unexpected expire transition: %+v", got)
|
|
||||||
}
|
|
||||||
if got.CommissionBefore != 900 || got.CommissionAfter != 400 {
|
|
||||||
t.Fatalf("unexpected commission transition: %+v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,128 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
promoModel "github.com/perfect-panel/server/internal/model/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
|
||||||
"github.com/perfect-panel/server/internal/types"
|
|
||||||
"github.com/perfect-panel/server/pkg/xerr"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
enabledRulesCacheKey = "promo:rules:enabled"
|
|
||||||
subscribePromoKeyFmt = "promo:subscribe:%d"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ruleParams struct {
|
|
||||||
WindowHours int `json:"window_hours"`
|
|
||||||
InactiveMonths int `json:"inactive_months"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func validateRulePayload(ruleType string, params json.RawMessage, priority, startTime, endTime int64) error {
|
|
||||||
if priority < 0 {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "priority must be greater than or equal to 0")
|
|
||||||
}
|
|
||||||
if startTime >= endTime {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "start_time must be less than end_time")
|
|
||||||
}
|
|
||||||
|
|
||||||
var p ruleParams
|
|
||||||
if len(params) == 0 || !json.Valid(params) {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "params must be valid json")
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(params, &p); err != nil {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "params must be valid json object")
|
|
||||||
}
|
|
||||||
|
|
||||||
switch ruleType {
|
|
||||||
case promoModel.RuleTypeNewUser:
|
|
||||||
if p.WindowHours <= 0 {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "params.window_hours must be greater than 0")
|
|
||||||
}
|
|
||||||
case promoModel.RuleTypeInactiveUser:
|
|
||||||
if p.InactiveMonths <= 0 {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "params.inactive_months must be greater than 0")
|
|
||||||
}
|
|
||||||
case promoModel.RuleTypeCampaign:
|
|
||||||
return nil
|
|
||||||
default:
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "type must be new_user, inactive_user or campaign")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func toRuleResponse(data *promoModel.Rule) types.PromoRule {
|
|
||||||
resp := types.PromoRule{
|
|
||||||
Id: data.Id,
|
|
||||||
Name: data.Name,
|
|
||||||
Type: data.Type,
|
|
||||||
Params: json.RawMessage(data.Params),
|
|
||||||
Priority: data.Priority,
|
|
||||||
Enabled: data.Enabled,
|
|
||||||
CreatedAt: data.CreatedAt.UnixMilli(),
|
|
||||||
UpdatedAt: data.UpdatedAt.UnixMilli(),
|
|
||||||
}
|
|
||||||
if data.StartTime != nil {
|
|
||||||
resp.StartTime = data.StartTime.UnixMilli()
|
|
||||||
}
|
|
||||||
if data.EndTime != nil {
|
|
||||||
resp.EndTime = data.EndTime.UnixMilli()
|
|
||||||
}
|
|
||||||
return resp
|
|
||||||
}
|
|
||||||
|
|
||||||
func toPriceResponse(data *promoModel.SubscribePromo, unitPrice int64) types.PromoPrice {
|
|
||||||
return types.PromoPrice{
|
|
||||||
Id: data.Id,
|
|
||||||
SubscribeId: data.SubscribeId,
|
|
||||||
PromoRuleId: data.PromoRuleId,
|
|
||||||
PromoPrice: data.PromoPrice,
|
|
||||||
UnitPrice: unitPrice,
|
|
||||||
CreatedAt: data.CreatedAt.UnixMilli(),
|
|
||||||
UpdatedAt: data.UpdatedAt.UnixMilli(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func toUsageResponse(data *promoModel.Usage) types.PromoUsage {
|
|
||||||
return types.PromoUsage{
|
|
||||||
Id: data.Id,
|
|
||||||
UserId: data.UserId,
|
|
||||||
PromoRuleId: data.PromoRuleId,
|
|
||||||
SubscribeId: data.SubscribeId,
|
|
||||||
OrderNo: data.OrderNo,
|
|
||||||
PromoPrice: data.PromoPrice,
|
|
||||||
CreatedAt: data.CreatedAt.UnixMilli(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func ruleTimes(startTime, endTime int64) (*time.Time, *time.Time) {
|
|
||||||
start := time.UnixMilli(startTime)
|
|
||||||
end := time.UnixMilli(endTime)
|
|
||||||
return &start, &end
|
|
||||||
}
|
|
||||||
|
|
||||||
func clearRuleCache(ctx context.Context, svcCtx *svc.ServiceContext) {
|
|
||||||
if svcCtx != nil && svcCtx.Redis != nil {
|
|
||||||
_ = svcCtx.Redis.Del(ctx, enabledRulesCacheKey).Err()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func clearSubscribePromoCache(ctx context.Context, svcCtx *svc.ServiceContext, ids ...int64) {
|
|
||||||
if svcCtx == nil || svcCtx.Redis == nil || len(ids) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
keys := make([]string, 0, len(ids))
|
|
||||||
for _, id := range ids {
|
|
||||||
keys = append(keys, fmt.Sprintf(subscribePromoKeyFmt, id))
|
|
||||||
}
|
|
||||||
_ = svcCtx.Redis.Del(ctx, keys...).Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
func wrapQueryError(msg string, err error) error {
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "%s: %v", msg, err.Error())
|
|
||||||
}
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
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 CreatePromoPriceLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Batch set promo price
|
|
||||||
func NewCreatePromoPriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePromoPriceLogic {
|
|
||||||
return &CreatePromoPriceLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *CreatePromoPriceLogic) CreatePromoPrice(req *types.CreatePromoPriceRequest) error {
|
|
||||||
if _, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.PromoRuleId); err != nil {
|
|
||||||
if promoModel.IsNotFound(err) {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "promo rule not found")
|
|
||||||
}
|
|
||||||
l.Errorw("[CreatePromoPrice] Query Rule Error", logger.Field("error", err.Error()))
|
|
||||||
return wrapQueryError("get promo rule failed", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
data := make([]*promoModel.SubscribePromo, 0, len(req.Items))
|
|
||||||
subscribeIds := make([]int64, 0, len(req.Items))
|
|
||||||
for _, item := range req.Items {
|
|
||||||
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, item.SubscribeId)
|
|
||||||
if err != nil {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "subscribe not found")
|
|
||||||
}
|
|
||||||
if item.PromoPrice >= sub.UnitPrice {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "promo_price must be less than unit_price")
|
|
||||||
}
|
|
||||||
data = append(data, &promoModel.SubscribePromo{
|
|
||||||
SubscribeId: item.SubscribeId,
|
|
||||||
PromoRuleId: req.PromoRuleId,
|
|
||||||
PromoPrice: item.PromoPrice,
|
|
||||||
})
|
|
||||||
subscribeIds = append(subscribeIds, item.SubscribeId)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := l.svcCtx.PromoModel.UpsertSubscribePromos(l.ctx, data); err != nil {
|
|
||||||
l.Errorw("[CreatePromoPrice] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "set promo price failed: %v", err.Error())
|
|
||||||
}
|
|
||||||
clearSubscribePromoCache(l.ctx, l.svcCtx, subscribeIds...)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
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 CreatePromoRuleLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create promo rule
|
|
||||||
func NewCreatePromoRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePromoRuleLogic {
|
|
||||||
return &CreatePromoRuleLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *CreatePromoRuleLogic) CreatePromoRule(req *types.CreatePromoRuleRequest) (*types.PromoRule, error) {
|
|
||||||
if err := validateRulePayload(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
start, end := ruleTimes(req.StartTime, req.EndTime)
|
|
||||||
data := &promoModel.Rule{
|
|
||||||
Name: req.Name,
|
|
||||||
Type: req.Type,
|
|
||||||
Params: string(req.Params),
|
|
||||||
Priority: req.Priority,
|
|
||||||
Enabled: *req.Enabled,
|
|
||||||
StartTime: start,
|
|
||||||
EndTime: end,
|
|
||||||
}
|
|
||||||
if err := l.svcCtx.PromoModel.InsertRule(l.ctx, data); err != nil {
|
|
||||||
l.Errorw("[CreatePromoRule] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create promo rule failed: %v", err.Error())
|
|
||||||
}
|
|
||||||
clearRuleCache(l.ctx, l.svcCtx)
|
|
||||||
resp := toRuleResponse(data)
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
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 DeletePromoPriceLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete promo price
|
|
||||||
func NewDeletePromoPriceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeletePromoPriceLogic {
|
|
||||||
return &DeletePromoPriceLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *DeletePromoPriceLogic) DeletePromoPrice(req *types.DeletePromoPriceRequest) error {
|
|
||||||
data, err := l.svcCtx.PromoModel.FindSubscribePromo(l.ctx, req.Id)
|
|
||||||
if err != nil {
|
|
||||||
if promoModel.IsNotFound(err) {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "promo price not found")
|
|
||||||
}
|
|
||||||
l.Errorw("[DeletePromoPrice] Database Query Error", logger.Field("error", err.Error()))
|
|
||||||
return wrapQueryError("get promo price failed", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = l.svcCtx.PromoModel.DeleteSubscribePromo(l.ctx, req.Id); err != nil {
|
|
||||||
l.Errorw("[DeletePromoPrice] Database Delete Error", logger.Field("error", err.Error()))
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo price failed: %v", err.Error())
|
|
||||||
}
|
|
||||||
clearSubscribePromoCache(l.ctx, l.svcCtx, data.SubscribeId)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
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 DeletePromoRuleLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete promo rule
|
|
||||||
func NewDeletePromoRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeletePromoRuleLogic {
|
|
||||||
return &DeletePromoRuleLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *DeletePromoRuleLogic) DeletePromoRule(req *types.DeletePromoRuleRequest) error {
|
|
||||||
if err := l.svcCtx.PromoModel.DeleteRule(l.ctx, req.Id); err != nil {
|
|
||||||
if promoModel.IsNotFound(err) {
|
|
||||||
return xerr.NewErrCodeMsg(xerr.InvalidParams, "promo rule not found")
|
|
||||||
}
|
|
||||||
l.Errorw("[DeletePromoRule] Database Delete Error", logger.Field("error", err.Error()))
|
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo rule failed: %v", err.Error())
|
|
||||||
}
|
|
||||||
clearRuleCache(l.ctx, l.svcCtx)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
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"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GetPromoPriceListLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get promo price list
|
|
||||||
func NewGetPromoPriceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPromoPriceListLogic {
|
|
||||||
return &GetPromoPriceListLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *GetPromoPriceListLogic) GetPromoPriceList(req *types.GetPromoPriceListRequest) (*types.GetPromoPriceListResponse, error) {
|
|
||||||
total, list, err := l.svcCtx.PromoModel.QuerySubscribePromoList(l.ctx, promoModel.SubscribePromoFilter{
|
|
||||||
Page: int(req.Page),
|
|
||||||
Size: int(req.Size),
|
|
||||||
PromoRuleId: req.PromoRuleId,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[GetPromoPriceList] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, wrapQueryError("get promo price list failed", err)
|
|
||||||
}
|
|
||||||
resp := &types.GetPromoPriceListResponse{
|
|
||||||
Total: total,
|
|
||||||
List: make([]types.PromoPrice, 0, len(list)),
|
|
||||||
}
|
|
||||||
for _, item := range list {
|
|
||||||
var unitPrice int64
|
|
||||||
sub, subErr := l.svcCtx.SubscribeModel.FindOne(l.ctx, item.SubscribeId)
|
|
||||||
if subErr == nil {
|
|
||||||
unitPrice = sub.UnitPrice
|
|
||||||
}
|
|
||||||
resp.List = append(resp.List, toPriceResponse(item, unitPrice))
|
|
||||||
}
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
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"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GetPromoRuleDetailLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get promo rule detail
|
|
||||||
func NewGetPromoRuleDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPromoRuleDetailLogic {
|
|
||||||
return &GetPromoRuleDetailLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *GetPromoRuleDetailLogic) GetPromoRuleDetail(req *types.GetPromoRuleDetailRequest) (*types.PromoRule, error) {
|
|
||||||
data, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id)
|
|
||||||
if err != nil {
|
|
||||||
if promoModel.IsNotFound(err) {
|
|
||||||
return nil, xerr.NewErrCodeMsg(xerr.InvalidParams, "promo rule not found")
|
|
||||||
}
|
|
||||||
l.Errorw("[GetPromoRuleDetail] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, wrapQueryError("get promo rule detail failed", err)
|
|
||||||
}
|
|
||||||
resp := toRuleResponse(data)
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
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"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GetPromoRuleListLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get promo rule list
|
|
||||||
func NewGetPromoRuleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPromoRuleListLogic {
|
|
||||||
return &GetPromoRuleListLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *GetPromoRuleListLogic) GetPromoRuleList(req *types.GetPromoRuleListRequest) (*types.GetPromoRuleListResponse, error) {
|
|
||||||
total, list, err := l.svcCtx.PromoModel.QueryRuleList(l.ctx, promoModel.RuleFilter{
|
|
||||||
Page: int(req.Page),
|
|
||||||
Size: int(req.Size),
|
|
||||||
Type: req.Type,
|
|
||||||
Enabled: req.Enabled,
|
|
||||||
Search: req.Search,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[GetPromoRuleList] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, wrapQueryError("get promo rule list failed", err)
|
|
||||||
}
|
|
||||||
resp := &types.GetPromoRuleListResponse{
|
|
||||||
Total: total,
|
|
||||||
List: make([]types.PromoRule, 0, len(list)),
|
|
||||||
}
|
|
||||||
for _, item := range list {
|
|
||||||
resp.List = append(resp.List, toRuleResponse(item))
|
|
||||||
}
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
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"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GetPromoUsageListLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get promo usage list
|
|
||||||
func NewGetPromoUsageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPromoUsageListLogic {
|
|
||||||
return &GetPromoUsageListLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *GetPromoUsageListLogic) GetPromoUsageList(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),
|
|
||||||
PromoRuleId: req.PromoRuleId,
|
|
||||||
UserId: req.UserId,
|
|
||||||
SubscribeId: req.SubscribeId,
|
|
||||||
OrderNo: req.OrderNo,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[GetPromoUsageList] Database Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, wrapQueryError("get promo usage list failed", err)
|
|
||||||
}
|
|
||||||
resp := &types.GetPromoUsageListResponse{
|
|
||||||
Total: total,
|
|
||||||
List: make([]types.PromoUsage, 0, len(list)),
|
|
||||||
}
|
|
||||||
for _, item := range list {
|
|
||||||
resp.List = append(resp.List, toUsageResponse(item))
|
|
||||||
}
|
|
||||||
return resp, nil
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
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 UpdatePromoRuleLogic struct {
|
|
||||||
logger.Logger
|
|
||||||
ctx context.Context
|
|
||||||
svcCtx *svc.ServiceContext
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update promo rule
|
|
||||||
func NewUpdatePromoRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePromoRuleLogic {
|
|
||||||
return &UpdatePromoRuleLogic{
|
|
||||||
Logger: logger.WithContext(ctx),
|
|
||||||
ctx: ctx,
|
|
||||||
svcCtx: svcCtx,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *UpdatePromoRuleLogic) UpdatePromoRule(req *types.UpdatePromoRuleRequest) (*types.PromoRule, error) {
|
|
||||||
if err := validateRulePayload(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
data, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id)
|
|
||||||
if err != nil {
|
|
||||||
if promoModel.IsNotFound(err) {
|
|
||||||
return nil, xerr.NewErrCodeMsg(xerr.InvalidParams, "promo rule not found")
|
|
||||||
}
|
|
||||||
l.Errorw("[UpdatePromoRule] Database Query Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, wrapQueryError("get promo rule failed", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
start, end := ruleTimes(req.StartTime, req.EndTime)
|
|
||||||
data.Name = req.Name
|
|
||||||
data.Type = req.Type
|
|
||||||
data.Params = string(req.Params)
|
|
||||||
data.Priority = req.Priority
|
|
||||||
data.Enabled = *req.Enabled
|
|
||||||
data.StartTime = start
|
|
||||||
data.EndTime = end
|
|
||||||
|
|
||||||
if err = l.svcCtx.PromoModel.UpdateRule(l.ctx, data); err != nil {
|
|
||||||
l.Errorw("[UpdatePromoRule] Database Update Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update promo rule failed: %v", err.Error())
|
|
||||||
}
|
|
||||||
clearRuleCache(l.ctx, l.svcCtx)
|
|
||||||
resp := toRuleResponse(data)
|
|
||||||
return &resp, nil
|
|
||||||
}
|
|
||||||
@@ -80,7 +80,7 @@ func (l *ResetSortWithNodeLogic) ResetSortWithNode(req *types.ResetSortRequest)
|
|||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()))
|
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()))
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ func (l *ResetSortWithServerLogic) ResetSortWithServer(req *types.ResetSortReque
|
|||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()))
|
l.Errorw("[NodeSort] Update Database Error: ", logger.Field("error", err.Error()))
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), err.Error())
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,9 +42,6 @@ func (l *GetWithdrawalListLogic) GetWithdrawalList(req *types.GetWithdrawalListR
|
|||||||
if req.Status != nil {
|
if req.Status != nil {
|
||||||
query = query.Where("status = ?", *req.Status)
|
query = query.Where("status = ?", *req.Status)
|
||||||
}
|
}
|
||||||
if req.Method != nil {
|
|
||||||
query = query.Where("method = ?", *req.Method)
|
|
||||||
}
|
|
||||||
|
|
||||||
var total int64
|
var total int64
|
||||||
if err := query.Count(&total).Error; err != nil {
|
if err := query.Count(&total).Error; err != nil {
|
||||||
@@ -65,9 +62,6 @@ func (l *GetWithdrawalListLogic) GetWithdrawalList(req *types.GetWithdrawalListR
|
|||||||
Content: row.Content,
|
Content: row.Content,
|
||||||
Status: row.Status,
|
Status: row.Status,
|
||||||
Reason: row.Reason,
|
Reason: row.Reason,
|
||||||
Method: row.Method,
|
|
||||||
Account: row.Account,
|
|
||||||
QrCodeUrl: row.QrCodeUrl,
|
|
||||||
CreatedAt: row.CreatedAt.UnixMilli(),
|
CreatedAt: row.CreatedAt.UnixMilli(),
|
||||||
UpdatedAt: row.UpdatedAt.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 {
|
err = l.svcCtx.UserModel.Transaction(l.ctx, func(tx *gorm.DB) error {
|
||||||
if req.Balance != nil && userInfo.Balance != *req.Balance {
|
if userInfo.Balance != req.Balance {
|
||||||
change := *req.Balance - userInfo.Balance
|
change := req.Balance - userInfo.Balance
|
||||||
balanceLog := log.Balance{
|
balanceLog := log.Balance{
|
||||||
Type: log.BalanceTypeAdjust,
|
Type: log.BalanceTypeAdjust,
|
||||||
Amount: change,
|
Amount: change,
|
||||||
OrderNo: "",
|
OrderNo: "",
|
||||||
Balance: *req.Balance,
|
Balance: req.Balance,
|
||||||
Timestamp: time.Now().UnixMilli(),
|
Timestamp: time.Now().UnixMilli(),
|
||||||
}
|
}
|
||||||
content, _ := balanceLog.Marshal()
|
content, _ := balanceLog.Marshal()
|
||||||
@@ -66,14 +66,14 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
userInfo.Balance = *req.Balance
|
userInfo.Balance = req.Balance
|
||||||
}
|
}
|
||||||
|
|
||||||
if req.GiftAmount != nil && userInfo.GiftAmount != *req.GiftAmount {
|
if userInfo.GiftAmount != req.GiftAmount {
|
||||||
change := *req.GiftAmount - userInfo.GiftAmount
|
change := req.GiftAmount - userInfo.GiftAmount
|
||||||
if change != 0 {
|
if change != 0 {
|
||||||
var changeType uint16
|
var changeType uint16
|
||||||
if userInfo.GiftAmount < *req.GiftAmount {
|
if userInfo.GiftAmount < req.GiftAmount {
|
||||||
changeType = log.GiftTypeIncrease
|
changeType = log.GiftTypeIncrease
|
||||||
} else {
|
} else {
|
||||||
changeType = log.GiftTypeReduce
|
changeType = log.GiftTypeReduce
|
||||||
@@ -81,7 +81,7 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
|
|||||||
giftLog := log.Gift{
|
giftLog := log.Gift{
|
||||||
Type: changeType,
|
Type: changeType,
|
||||||
Amount: change,
|
Amount: change,
|
||||||
Balance: *req.GiftAmount,
|
Balance: req.GiftAmount,
|
||||||
Remark: "Admin adjustment",
|
Remark: "Admin adjustment",
|
||||||
Timestamp: time.Now().UnixMilli(),
|
Timestamp: time.Now().UnixMilli(),
|
||||||
}
|
}
|
||||||
@@ -96,27 +96,23 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
userInfo.GiftAmount = *req.GiftAmount
|
userInfo.GiftAmount = req.GiftAmount
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if req.Commission != nil && *req.Commission != userInfo.Commission {
|
if req.Commission != userInfo.Commission {
|
||||||
remark := ""
|
if isWithdrawalScene(req.Remark) {
|
||||||
if req.Remark != nil {
|
|
||||||
remark = *req.Remark
|
|
||||||
}
|
|
||||||
if isWithdrawalScene(remark) {
|
|
||||||
logWithdrawalGuard(l.Logger, userInfo.Id)
|
logWithdrawalGuard(l.Logger, userInfo.Id)
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "commission overwrite is blocked in withdrawal scene")
|
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 {
|
if err = l.svcCtx.UserModel.UpdateCommission(l.ctx, userInfo.Id, change, tx); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if err = logicCommon.WriteCommissionLog(tx, userInfo.Id, log.CommissionTypeAdjust, change, ""); err != nil {
|
if err = logicCommon.WriteCommissionLog(tx, userInfo.Id, log.CommissionTypeAdjust, change, ""); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
userInfo.Commission = *req.Commission
|
userInfo.Commission = req.Commission
|
||||||
}
|
}
|
||||||
if req.Avatar != "" {
|
if req.Avatar != "" {
|
||||||
userInfo.Avatar = req.Avatar
|
userInfo.Avatar = req.Avatar
|
||||||
@@ -124,17 +120,15 @@ func (l *UpdateUserBasicInfoLogic) UpdateUserBasicInfo(req *types.UpdateUserBasi
|
|||||||
if req.ReferCode != "" {
|
if req.ReferCode != "" {
|
||||||
userInfo.ReferCode = req.ReferCode
|
userInfo.ReferCode = req.ReferCode
|
||||||
}
|
}
|
||||||
if req.RefererId != nil {
|
userInfo.RefererId = req.RefererId
|
||||||
userInfo.RefererId = *req.RefererId
|
|
||||||
}
|
|
||||||
if req.Enable != nil {
|
if req.Enable != nil {
|
||||||
userInfo.Enable = req.Enable
|
userInfo.Enable = req.Enable
|
||||||
}
|
}
|
||||||
if req.IsAdmin != nil {
|
if req.IsAdmin != nil {
|
||||||
userInfo.IsAdmin = req.IsAdmin
|
userInfo.IsAdmin = req.IsAdmin
|
||||||
}
|
}
|
||||||
if req.Remark != nil {
|
if req.Remark != "" {
|
||||||
userInfo.Remark = *req.Remark
|
userInfo.Remark = req.Remark
|
||||||
}
|
}
|
||||||
if req.OnlyFirstPurchase != nil {
|
if req.OnlyFirstPurchase != nil {
|
||||||
userInfo.OnlyFirstPurchase = req.OnlyFirstPurchase
|
userInfo.OnlyFirstPurchase = req.OnlyFirstPurchase
|
||||||
|
|||||||
@@ -12,12 +12,10 @@ import (
|
|||||||
"github.com/perfect-panel/server/pkg/xerr"
|
"github.com/perfect-panel/server/pkg/xerr"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/clause"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func approveWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdrawalID int64) error {
|
func approveWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdrawalID int64) error {
|
||||||
var approvedUserID int64
|
return svcCtx.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
err := svcCtx.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
||||||
withdrawal, err := logicCommon.LoadPendingWithdrawalForUpdate(ctx, tx, withdrawalID)
|
withdrawal, err := logicCommon.LoadPendingWithdrawalForUpdate(ctx, tx, withdrawalID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err.Error() == "withdrawal status invalid" {
|
if err.Error() == "withdrawal status invalid" {
|
||||||
@@ -26,50 +24,26 @@ func approveWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdraw
|
|||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load withdrawal failed: %v", err)
|
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{}).
|
if err := tx.Model(&usermodel.Withdrawal{}).
|
||||||
Where("id = ? AND status = ?", withdrawalID, usermodel.WithdrawalStatusPending).
|
Where("id = ? AND status = 0", withdrawalID).
|
||||||
Updates(map[string]interface{}{
|
Updates(map[string]interface{}{
|
||||||
"status": usermodel.WithdrawalStatusApproved,
|
"status": 1,
|
||||||
"reason": "",
|
"reason": "",
|
||||||
}).Error; err != nil {
|
}).Error; err != nil {
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "approve withdrawal failed: %v", err)
|
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 {
|
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)
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "write commission log failed: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
approvedUserID = withdrawal.UserId
|
|
||||||
return nil
|
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 {
|
func rejectWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdrawalID int64, reason string) error {
|
||||||
reason = strings.TrimSpace(reason)
|
reason = strings.TrimSpace(reason)
|
||||||
return svcCtx.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
return svcCtx.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
_, err := logicCommon.LoadPendingWithdrawalForUpdate(ctx, tx, withdrawalID)
|
withdrawal, err := logicCommon.LoadPendingWithdrawalForUpdate(ctx, tx, withdrawalID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err.Error() == "withdrawal status invalid" {
|
if err.Error() == "withdrawal status invalid" {
|
||||||
return errors.Wrapf(xerr.NewErrCode(xerr.WithdrawalStatusInvalid), "withdrawal %d already processed", withdrawalID)
|
return errors.Wrapf(xerr.NewErrCode(xerr.WithdrawalStatusInvalid), "withdrawal %d already processed", withdrawalID)
|
||||||
@@ -77,14 +51,23 @@ func rejectWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdrawa
|
|||||||
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load withdrawal failed: %v", err)
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load withdrawal failed: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Commission was NOT deducted at application time under the new logic,
|
if err := tx.Model(&usermodel.Withdrawal{}).
|
||||||
// so rejection requires no refund — only a status update.
|
Where("id = ? AND status = 0", withdrawalID).
|
||||||
return tx.Model(&usermodel.Withdrawal{}).
|
|
||||||
Where("id = ? AND status = ?", withdrawalID, usermodel.WithdrawalStatusPending).
|
|
||||||
Updates(map[string]interface{}{
|
Updates(map[string]interface{}{
|
||||||
"status": usermodel.WithdrawalStatusRejected,
|
"status": 2,
|
||||||
"reason": reason,
|
"reason": reason,
|
||||||
}).Error
|
}).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
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,170 +0,0 @@
|
|||||||
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"
|
|
||||||
)
|
|
||||||
|
|
||||||
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) (*PromoResult, error) {
|
|
||||||
result := &PromoResult{}
|
|
||||||
if svcCtx == nil || svcCtx.PromoModel == nil || svcCtx.DB == nil || userID <= 0 || subscribeID <= 0 {
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
rules, err := svcCtx.PromoModel.QueryEligibleRules(ctx, subscribeID)
|
|
||||||
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("expire_time DESC").
|
|
||||||
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")
|
|
||||||
}
|
|
||||||
|
|
||||||
threshold := now.AddDate(0, -params.InactiveMonths, 0)
|
|
||||||
return lastSub.ExpireTime.Before(threshold) || lastSub.ExpireTime.Equal(threshold), ruleExpiresAt, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func promoRuleExpiresAt(rule *promo.RuleWithPrice) time.Time {
|
|
||||||
if rule != nil && rule.EndTime != nil {
|
|
||||||
return *rule.EndTime
|
|
||||||
}
|
|
||||||
return time.Time{}
|
|
||||||
}
|
|
||||||
@@ -41,7 +41,7 @@ func LoadPendingWithdrawalForUpdate(ctx context.Context, tx *gorm.DB, withdrawal
|
|||||||
First(&withdrawal).Error; err != nil {
|
First(&withdrawal).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if withdrawal.Status != usermodel.WithdrawalStatusPending {
|
if withdrawal.Status != 0 {
|
||||||
return nil, errors.New("withdrawal status invalid")
|
return nil, errors.New("withdrawal status invalid")
|
||||||
}
|
}
|
||||||
return &withdrawal, nil
|
return &withdrawal, nil
|
||||||
|
|||||||
@@ -3,20 +3,17 @@ package notify
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
||||||
iapmodel "github.com/perfect-panel/server/internal/model/iap/apple"
|
iapmodel "github.com/perfect-panel/server/internal/model/iap/apple"
|
||||||
"github.com/perfect-panel/server/internal/model/order"
|
|
||||||
"github.com/perfect-panel/server/internal/model/subscribe"
|
"github.com/perfect-panel/server/internal/model/subscribe"
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
"github.com/perfect-panel/server/internal/model/user"
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
"github.com/perfect-panel/server/internal/types"
|
"github.com/perfect-panel/server/internal/types"
|
||||||
iapapple "github.com/perfect-panel/server/pkg/iap/apple"
|
iapapple "github.com/perfect-panel/server/pkg/iap/apple"
|
||||||
"github.com/perfect-panel/server/pkg/logger"
|
"github.com/perfect-panel/server/pkg/logger"
|
||||||
"github.com/perfect-panel/server/pkg/tool"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -87,7 +84,6 @@ func (l *AppleIAPNotifyLogic) Handle(signedPayload string) error {
|
|||||||
l.Errorw("iap notify insert transaction error", logger.Field("error", e.Error()), logger.Field("productId", txPayload.ProductId), logger.Field("originalTransactionId", txPayload.OriginalTransactionId))
|
l.Errorw("iap notify insert transaction error", logger.Field("error", e.Error()), logger.Field("productId", txPayload.ProductId), logger.Field("originalTransactionId", txPayload.OriginalTransactionId))
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
existing = rec
|
|
||||||
} else {
|
} else {
|
||||||
if txPayload.RevocationDate != nil {
|
if txPayload.RevocationDate != nil {
|
||||||
// 撤销场景:更新 revocation_at
|
// 撤销场景:更新 revocation_at
|
||||||
@@ -100,32 +96,6 @@ func (l *AppleIAPNotifyLogic) Handle(signedPayload string) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fix Bug 7: resolve userId when the IAP transaction record has no associated user.
|
|
||||||
// This can happen if the first notification for a subscription arrived before the
|
|
||||||
// in-app purchase flow created the order (race) or the order was made in a previous
|
|
||||||
// build that did not write user_id to the IAP transaction table.
|
|
||||||
if existing != nil && existing.UserId == 0 {
|
|
||||||
var origOrder order.Order
|
|
||||||
if lookupErr := db.Model(&order.Order{}).
|
|
||||||
Where("trade_no = ? AND method = ?", txPayload.OriginalTransactionId, "apple_iap").
|
|
||||||
Order("id ASC").
|
|
||||||
First(&origOrder).Error; lookupErr == nil && origOrder.UserId > 0 {
|
|
||||||
existing.UserId = origOrder.UserId
|
|
||||||
_ = db.Model(&iapmodel.Transaction{}).
|
|
||||||
Where("id = ?", existing.Id).
|
|
||||||
Update("user_id", origOrder.UserId).Error
|
|
||||||
l.Infow("iap notify resolved zero userId from original purchase order",
|
|
||||||
logger.Field("userId", origOrder.UserId),
|
|
||||||
logger.Field("originalTransactionId", txPayload.OriginalTransactionId),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
l.Errorw("CRITICAL: iap notify UserId=0 and cannot resolve from order, notification dropped",
|
|
||||||
logger.Field("originalTransactionId", txPayload.OriginalTransactionId))
|
|
||||||
return fmt.Errorf("iap notify: UserId=0 and cannot resolve from order for original_transaction_id=%s", txPayload.OriginalTransactionId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var days int64
|
var days int64
|
||||||
{
|
{
|
||||||
pid := strings.ToLower(txPayload.ProductId)
|
pid := strings.ToLower(txPayload.ProductId)
|
||||||
@@ -199,12 +169,7 @@ func (l *AppleIAPNotifyLogic) Handle(signedPayload string) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if days == 0 {
|
if days == 0 {
|
||||||
// Both string-parse and DB fallback failed to map the product to days.
|
l.Errorw("iap notify product mapping missing", logger.Field("productId", txPayload.ProductId))
|
||||||
// Return an error so Apple retries the notification; silently ignoring
|
|
||||||
// this would cause the subscriber's renewal to be lost.
|
|
||||||
l.Errorw("CRITICAL: iap notify product mapping missing, returning error to trigger retry",
|
|
||||||
logger.Field("productId", txPayload.ProductId))
|
|
||||||
return fmt.Errorf("iap product id %s could not be mapped to subscription days", txPayload.ProductId)
|
|
||||||
}
|
}
|
||||||
token := "iap:" + txPayload.OriginalTransactionId
|
token := "iap:" + txPayload.OriginalTransactionId
|
||||||
sub, e := l.svcCtx.UserModel.FindOneSubscribeByToken(l.ctx, token)
|
sub, e := l.svcCtx.UserModel.FindOneSubscribeByToken(l.ctx, token)
|
||||||
@@ -251,11 +216,6 @@ func (l *AppleIAPNotifyLogic) Handle(signedPayload string) error {
|
|||||||
logger.Field("product_id", txPayload.ProductId),
|
logger.Field("product_id", txPayload.ProductId),
|
||||||
)...,
|
)...,
|
||||||
)
|
)
|
||||||
// Create audit order record for renewal notifications (Bug 7)
|
|
||||||
if err := l.createIAPRenewalAuditOrder(db, ntype, txPayload.TransactionId, candidate.UserId, candidate.SubscribeId, candidate.Token); err != nil {
|
|
||||||
l.Errorw("iap notify fallback create renewal order error", logger.Field("error", err.Error()))
|
|
||||||
// Non-fatal: subscription already updated; order creation failure is logged only
|
|
||||||
}
|
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -288,52 +248,7 @@ func (l *AppleIAPNotifyLogic) Handle(signedPayload string) error {
|
|||||||
logger.Field("product_id", txPayload.ProductId),
|
logger.Field("product_id", txPayload.ProductId),
|
||||||
)...,
|
)...,
|
||||||
)
|
)
|
||||||
// Create audit order record for renewal notifications (Bug 7)
|
|
||||||
if err := l.createIAPRenewalAuditOrder(db, ntype, txPayload.TransactionId, sub.UserId, sub.SubscribeId, sub.Token); err != nil {
|
|
||||||
l.Errorw("iap notify create renewal order error", logger.Field("error", err.Error()))
|
|
||||||
// Non-fatal: subscription already updated; order creation failure is logged only
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// createIAPRenewalAuditOrder creates a finished renewal order record for DID_RENEW and SUBSCRIBED
|
|
||||||
// Apple SSNS notifications so that the order table has a complete financial audit trail.
|
|
||||||
// The operation is idempotent: if an order with the same trade_no already exists it is skipped.
|
|
||||||
func (l *AppleIAPNotifyLogic) createIAPRenewalAuditOrder(db *gorm.DB, ntype, transactionId string, userId, subscribeId int64, subscribeToken string) error {
|
|
||||||
if ntype != "DID_RENEW" && ntype != "SUBSCRIBED" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
// Idempotency check
|
|
||||||
var count int64
|
|
||||||
if err := db.Model(&order.Order{}).
|
|
||||||
Where("trade_no = ? AND method = ?", transactionId, "apple_iap").
|
|
||||||
Count(&count).Error; err != nil {
|
|
||||||
return fmt.Errorf("check existing iap renewal order: %w", err)
|
|
||||||
}
|
|
||||||
if count > 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
rec := &order.Order{
|
|
||||||
UserId: userId,
|
|
||||||
OrderNo: tool.GenerateTradeNo(),
|
|
||||||
Type: 2, // OrderTypeRenewal
|
|
||||||
Status: 5, // OrderStatusFinished
|
|
||||||
Method: "apple_iap",
|
|
||||||
TradeNo: transactionId,
|
|
||||||
SubscribeId: subscribeId,
|
|
||||||
SubscribeToken: subscribeToken,
|
|
||||||
Quantity: 1,
|
|
||||||
IsNew: false,
|
|
||||||
}
|
|
||||||
if err := db.Model(&order.Order{}).Create(rec).Error; err != nil {
|
|
||||||
return fmt.Errorf("create iap renewal audit order: %w", err)
|
|
||||||
}
|
|
||||||
l.Infow("iap notify created renewal audit order",
|
|
||||||
logger.Field("orderNo", rec.OrderNo),
|
|
||||||
logger.Field("transactionId", transactionId),
|
|
||||||
logger.Field("userId", userId),
|
|
||||||
)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package order
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"math"
|
||||||
|
|
||||||
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
commonLogic "github.com/perfect-panel/server/internal/logic/common"
|
||||||
"github.com/perfect-panel/server/internal/model/order"
|
"github.com/perfect-panel/server/internal/model/order"
|
||||||
@@ -114,28 +115,14 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
|||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SubscribeNewUserOnly), "not a new user")
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SubscribeNewUserOnly), "not a new user")
|
||||||
}
|
}
|
||||||
|
|
||||||
priceResult, err := calculatePurchasePrice(
|
var discount float64 = 1
|
||||||
l.ctx,
|
if len(newUserDiscount.Discounts) > 0 {
|
||||||
l.svcCtx,
|
discount = getDiscount(newUserDiscount.Discounts, req.Quantity, newUserDiscount.EligibleForDiscount)
|
||||||
u.Id,
|
|
||||||
targetSubscribeID,
|
|
||||||
sub.UnitPrice,
|
|
||||||
req.Quantity,
|
|
||||||
newUserDiscount.Discounts,
|
|
||||||
newUserDiscount.EligibleForDiscount,
|
|
||||||
!isSingleModeRenewal,
|
|
||||||
)
|
|
||||||
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 := priceResult.OriginalPrice
|
price := sub.UnitPrice * req.Quantity
|
||||||
amount := priceResult.PayableBase
|
|
||||||
discountAmount := priceResult.DiscountAmount
|
amount := int64(math.Round(float64(price) * discount))
|
||||||
|
discountAmount := price - amount
|
||||||
var couponAmount int64
|
var couponAmount int64
|
||||||
if req.Coupon != "" {
|
if req.Coupon != "" {
|
||||||
couponInfo, err := l.svcCtx.CouponModel.FindOneByCode(l.ctx, req.Coupon)
|
couponInfo, err := l.svcCtx.CouponModel.FindOneByCode(l.ctx, req.Coupon)
|
||||||
@@ -198,7 +185,6 @@ func (l *PreCreateOrderLogic) PreCreateOrder(req *types.PurchaseOrderRequest) (r
|
|||||||
Price: price,
|
Price: price,
|
||||||
Amount: amount,
|
Amount: amount,
|
||||||
Discount: discountAmount,
|
Discount: discountAmount,
|
||||||
PromoDiscount: priceResult.PromoDiscount,
|
|
||||||
GiftAmount: deductionAmount,
|
GiftAmount: deductionAmount,
|
||||||
Coupon: req.Coupon,
|
Coupon: req.Coupon,
|
||||||
CouponDiscount: couponAmount,
|
CouponDiscount: couponAmount,
|
||||||
|
|||||||
@@ -1,62 +0,0 @@
|
|||||||
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)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if promoResult != nil && promoResult.Eligible && promoResult.PromoPrice < unitPrice {
|
|
||||||
result.PayableBase = promoResult.PromoPrice * quantity
|
|
||||||
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
|
|
||||||
}
|
|
||||||
@@ -1,153 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) QueryEligibleRules(context.Context, int64) ([]*promo.RuleWithPrice, error) {
|
|
||||||
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, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
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, promo.RuleFilter) (int64, []*promo.Rule, error) {
|
|
||||||
return 0, nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) UpsertSubscribePromos(context.Context, []*promo.SubscribePromo) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) FindSubscribePromo(context.Context, int64) (*promo.SubscribePromo, error) {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) DeleteSubscribePromo(context.Context, int64) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m fakePromoModel) QuerySubscribePromoList(context.Context, promo.SubscribePromoFilter) (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 TestCalculatePurchasePricePromoSkipsPercentDiscount(t *testing.T) {
|
|
||||||
svcCtx := &svc.ServiceContext{
|
|
||||||
DB: &gorm.DB{},
|
|
||||||
PromoModel: fakePromoModel{rules: []*promo.RuleWithPrice{
|
|
||||||
{
|
|
||||||
Rule: promo.Rule{
|
|
||||||
Id: 9,
|
|
||||||
Name: "campaign",
|
|
||||||
Type: promo.RuleTypeCampaign,
|
|
||||||
Enabled: true,
|
|
||||||
},
|
|
||||||
PromoPrice: 600,
|
|
||||||
},
|
|
||||||
}},
|
|
||||||
}
|
|
||||||
|
|
||||||
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.OriginalPrice != 3000 {
|
|
||||||
t.Fatalf("OriginalPrice = %d, want 3000", result.OriginalPrice)
|
|
||||||
}
|
|
||||||
if result.PayableBase != 1800 {
|
|
||||||
t.Fatalf("PayableBase = %d, want 1800", 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 != 1200 {
|
|
||||||
t.Fatalf("PromoDiscount = %d, want 1200", result.PromoDiscount)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCalculatePurchasePriceIgnoresInvalidPromoPrice(t *testing.T) {
|
|
||||||
svcCtx := &svc.ServiceContext{
|
|
||||||
DB: &gorm.DB{},
|
|
||||||
PromoModel: fakePromoModel{rules: []*promo.RuleWithPrice{
|
|
||||||
{
|
|
||||||
Rule: promo.Rule{
|
|
||||||
Id: 10,
|
|
||||||
Name: "invalid campaign",
|
|
||||||
Type: promo.RuleTypeCampaign,
|
|
||||||
Enabled: true,
|
|
||||||
},
|
|
||||||
PromoPrice: 1000,
|
|
||||||
},
|
|
||||||
}},
|
|
||||||
}
|
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,6 +3,7 @@ package order
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"math"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -203,28 +204,14 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
priceResult, err := calculatePurchasePrice(
|
var discount float64 = 1
|
||||||
l.ctx,
|
if len(newUserDiscount.Discounts) > 0 {
|
||||||
l.svcCtx,
|
discount = getDiscount(newUserDiscount.Discounts, req.Quantity, newUserDiscount.EligibleForDiscount)
|
||||||
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 := priceResult.OriginalPrice
|
price := sub.UnitPrice * req.Quantity
|
||||||
amount := priceResult.PayableBase
|
// discount amount
|
||||||
discountAmount := priceResult.DiscountAmount
|
amount := int64(math.Round(float64(price) * discount))
|
||||||
|
discountAmount := price - amount
|
||||||
|
|
||||||
// Validate amount to prevent overflow
|
// Validate amount to prevent overflow
|
||||||
if amount > MaxOrderAmount {
|
if amount > MaxOrderAmount {
|
||||||
@@ -319,8 +306,6 @@ func (l *PurchaseLogic) Purchase(req *types.PurchaseOrderRequest) (resp *types.P
|
|||||||
Price: price,
|
Price: price,
|
||||||
Amount: amount,
|
Amount: amount,
|
||||||
Discount: discountAmount,
|
Discount: discountAmount,
|
||||||
PromoRuleId: priceResult.PromoRuleId,
|
|
||||||
PromoDiscount: priceResult.PromoDiscount,
|
|
||||||
GiftAmount: deductionAmount,
|
GiftAmount: deductionAmount,
|
||||||
Coupon: req.Coupon,
|
Coupon: req.Coupon,
|
||||||
CouponDiscount: coupon,
|
CouponDiscount: coupon,
|
||||||
|
|||||||
@@ -154,12 +154,9 @@ func (l *PurchaseLogic) Purchase(req *types.PortalPurchaseRequest) (resp *types.
|
|||||||
}
|
}
|
||||||
content, _ := tempOrder.Marshal()
|
content, _ := tempOrder.Marshal()
|
||||||
|
|
||||||
// Persist activation context to DB so the worker can recover if Redis TTL expires.
|
if _, err = l.svcCtx.Redis.Set(l.ctx, fmt.Sprintf(constant.TempOrderCacheKey, orderInfo.OrderNo), string(content), CloseOrderTimeMinutes*time.Minute).Result(); err != nil {
|
||||||
orderInfo.ActivationContext = string(content)
|
l.Errorw("[Purchase] Redis set error", logger.Field("error", err.Error()), logger.Field("order_no", orderInfo.OrderNo))
|
||||||
|
return err
|
||||||
// Write to Redis as a hot cache (best-effort; non-fatal on failure).
|
|
||||||
if _, redisErr := l.svcCtx.Redis.Set(l.ctx, fmt.Sprintf(constant.TempOrderCacheKey, orderInfo.OrderNo), string(content), CloseOrderTimeMinutes*time.Minute).Result(); redisErr != nil {
|
|
||||||
l.Infow("[Purchase] Redis set error (non-fatal, DB fallback available)", logger.Field("error", redisErr.Error()), logger.Field("order_no", orderInfo.OrderNo))
|
|
||||||
}
|
}
|
||||||
l.Infow("[Purchase] Guest order", logger.Field("order_no", orderInfo.OrderNo), logger.Field("identifier", req.Identifier))
|
l.Infow("[Purchase] Guest order", logger.Field("order_no", orderInfo.OrderNo), logger.Field("identifier", req.Identifier))
|
||||||
|
|
||||||
@@ -172,7 +169,7 @@ func (l *PurchaseLogic) Purchase(req *types.PortalPurchaseRequest) (resp *types.
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// save guest order (activation_context is included)
|
// save guest order
|
||||||
if err = l.svcCtx.OrderModel.Insert(l.ctx, orderInfo, tx); err != nil {
|
if err = l.svcCtx.OrderModel.Insert(l.ctx, orderInfo, tx); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -151,48 +151,34 @@ func (l *RedeemCodeLogic) RedeemCode(req *types.RedeemCodeRequest) (resp *types.
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 创建Order记录
|
// 创建Order记录
|
||||||
redemptionContext := struct {
|
|
||||||
Type string `json:"type"`
|
|
||||||
RedemptionCodeId int64 `json:"redemption_code_id"`
|
|
||||||
UnitTime string `json:"unit_time"`
|
|
||||||
Quantity int64 `json:"quantity"`
|
|
||||||
}{
|
|
||||||
Type: "redemption",
|
|
||||||
RedemptionCodeId: redemptionCode.Id,
|
|
||||||
UnitTime: redemptionCode.UnitTime,
|
|
||||||
Quantity: redemptionCode.Quantity,
|
|
||||||
}
|
|
||||||
activationContextJSON, _ := json.Marshal(redemptionContext)
|
|
||||||
|
|
||||||
orderInfo := &order.Order{
|
orderInfo := &order.Order{
|
||||||
UserId: u.Id,
|
UserId: u.Id,
|
||||||
OrderNo: tool.GenerateTradeNo(),
|
OrderNo: tool.GenerateTradeNo(),
|
||||||
Type: 5, // 兑换类型
|
Type: 5, // 兑换类型
|
||||||
Quantity: redemptionCode.Quantity,
|
Quantity: redemptionCode.Quantity,
|
||||||
Price: 0, // 兑换无价格
|
Price: 0, // 兑换无价格
|
||||||
Amount: 0, // 兑换无金额
|
Amount: 0, // 兑换无金额
|
||||||
Discount: 0,
|
Discount: 0,
|
||||||
GiftAmount: 0,
|
GiftAmount: 0,
|
||||||
Coupon: "",
|
Coupon: "",
|
||||||
CouponDiscount: 0,
|
CouponDiscount: 0,
|
||||||
PaymentId: 0,
|
PaymentId: 0,
|
||||||
Method: "redemption",
|
Method: "redemption",
|
||||||
FeeAmount: 0,
|
FeeAmount: 0,
|
||||||
Commission: 0,
|
Commission: 0,
|
||||||
Status: 2, // 直接设置为已支付
|
Status: 2, // 直接设置为已支付
|
||||||
SubscribeId: redemptionCode.SubscribePlan,
|
SubscribeId: redemptionCode.SubscribePlan,
|
||||||
IsNew: isNew,
|
IsNew: isNew,
|
||||||
ActivationContext: string(activationContextJSON),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 保存Order到数据库(activation_context 同步写入,作为 Redis 的持久化兜底)
|
// 保存Order到数据库
|
||||||
err = l.svcCtx.OrderModel.Insert(l.ctx, orderInfo)
|
err = l.svcCtx.OrderModel.Insert(l.ctx, orderInfo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorw("[RedeemCode] Create order failed", logger.Field("error", err.Error()))
|
l.Errorw("[RedeemCode] Create order failed", logger.Field("error", err.Error()))
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create order failed")
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create order failed")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 缓存兑换码信息到Redis(热缓存,供队列任务快速读取,非关键路径)
|
// 缓存兑换码信息到Redis(供队列任务使用)
|
||||||
cacheKey := fmt.Sprintf("redemption_order:%s", orderInfo.OrderNo)
|
cacheKey := fmt.Sprintf("redemption_order:%s", orderInfo.OrderNo)
|
||||||
cacheData := map[string]interface{}{
|
cacheData := map[string]interface{}{
|
||||||
"redemption_code_id": redemptionCode.Id,
|
"redemption_code_id": redemptionCode.Id,
|
||||||
@@ -200,8 +186,16 @@ func (l *RedeemCodeLogic) RedeemCode(req *types.RedeemCodeRequest) (resp *types.
|
|||||||
"quantity": redemptionCode.Quantity,
|
"quantity": redemptionCode.Quantity,
|
||||||
}
|
}
|
||||||
jsonData, _ := json.Marshal(cacheData)
|
jsonData, _ := json.Marshal(cacheData)
|
||||||
if redisErr := l.svcCtx.Redis.Set(l.ctx, cacheKey, jsonData, 2*time.Hour).Err(); redisErr != nil {
|
err = l.svcCtx.Redis.Set(l.ctx, cacheKey, jsonData, 2*time.Hour).Err()
|
||||||
l.Infow("[RedeemCode] Cache redemption data failed (non-fatal, DB fallback available)", logger.Field("error", redisErr.Error()))
|
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")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 触发队列任务
|
// 触发队列任务
|
||||||
|
|||||||
@@ -1,224 +0,0 @@
|
|||||||
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"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
promoRuleTypeNewUser = "new_user"
|
|
||||||
promoRuleTypeInactiveUser = "inactive_user"
|
|
||||||
promoRuleTypeCampaign = "campaign"
|
|
||||||
)
|
|
||||||
|
|
||||||
type subscribePromoCandidate struct {
|
|
||||||
SubscribeId int64 `gorm:"column:subscribe_id"`
|
|
||||||
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]*types.SubscribePromo, error) {
|
|
||||||
result := make(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 _, exists := result[candidate.SubscribeId]; 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] = &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
|
|
||||||
query := svcCtx.DB.WithContext(ctx).
|
|
||||||
Table("subscribe_promo AS sp").
|
|
||||||
Select("sp.subscribe_id, sp.promo_price, pr.name AS rule_name, pr.type AS rule_type, pr.params, pr.start_time, pr.end_time").
|
|
||||||
Joins("JOIN promo_rule AS pr ON pr.id = sp.promo_rule_id AND pr.deleted_at IS NULL").
|
|
||||||
Where("sp.subscribe_id IN ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeIDs, true)
|
|
||||||
if !loggedIn {
|
|
||||||
query = query.Where("pr.type = ?", promoRuleTypeCampaign)
|
|
||||||
}
|
|
||||||
err := query.
|
|
||||||
Order("sp.subscribe_id ASC").
|
|
||||||
Order("pr.priority DESC").
|
|
||||||
Order("pr.id ASC").
|
|
||||||
Scan(&candidates).Error
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query subscribe promo candidates failed: %v", err)
|
|
||||||
}
|
|
||||||
return candidates, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
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.db.WithContext(e.ctx).
|
|
||||||
Model(&user.Subscribe{}).
|
|
||||||
Where("user_id = ?", e.userInfo.Id).
|
|
||||||
Where("expire_time != ?", time.UnixMilli(0)).
|
|
||||||
Order("expire_time DESC").
|
|
||||||
Limit(1).
|
|
||||||
Take(&item).Error
|
|
||||||
if err != nil {
|
|
||||||
if stderrors.Is(err, gorm.ErrRecordNotFound) {
|
|
||||||
zero := time.Time{}
|
|
||||||
e.lastExpire = &zero
|
|
||||||
return zero, nil
|
|
||||||
}
|
|
||||||
return time.Time{}, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query promo user last subscription failed")
|
|
||||||
}
|
|
||||||
e.lastExpire = &item.ExpireTime
|
|
||||||
return item.ExpireTime, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c subscribePromoCandidate) expiresAt() time.Time {
|
|
||||||
if c.EndTime == nil {
|
|
||||||
return time.Time{}
|
|
||||||
}
|
|
||||||
return *c.EndTime
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c subscribePromoCandidate) params() (promoRuleParams, error) {
|
|
||||||
if c.Params == "" {
|
|
||||||
return promoRuleParams{}, nil
|
|
||||||
}
|
|
||||||
var params promoRuleParams
|
|
||||||
if err := json.Unmarshal([]byte(c.Params), ¶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")
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
package subscribe
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/perfect-panel/server/internal/model/user"
|
|
||||||
)
|
|
||||||
|
|
||||||
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")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -47,11 +47,9 @@ func (l *QuerySubscribeListLogic) QuerySubscribeList(req *types.QuerySubscribeLi
|
|||||||
Total: total,
|
Total: total,
|
||||||
}
|
}
|
||||||
list := make([]types.Subscribe, len(data))
|
list := make([]types.Subscribe, len(data))
|
||||||
subscribeIDs := make([]int64, 0, len(data))
|
|
||||||
for i, item := range data {
|
for i, item := range data {
|
||||||
var sub types.Subscribe
|
var sub types.Subscribe
|
||||||
tool.DeepCopy(&sub, item)
|
tool.DeepCopy(&sub, item)
|
||||||
subscribeIDs = append(subscribeIDs, sub.Id)
|
|
||||||
if item.Discount != "" {
|
if item.Discount != "" {
|
||||||
var discount []types.SubscribeDiscount
|
var discount []types.SubscribeDiscount
|
||||||
_ = json.Unmarshal([]byte(item.Discount), &discount)
|
_ = json.Unmarshal([]byte(item.Discount), &discount)
|
||||||
@@ -71,15 +69,6 @@ func (l *QuerySubscribeListLogic) QuerySubscribeList(req *types.QuerySubscribeLi
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
promos, err := loadSubscribePromoMap(l.ctx, l.svcCtx, subscribeIDs)
|
|
||||||
if err != nil {
|
|
||||||
l.Errorw("[QuerySubscribeListLogic] Query Promo Error", logger.Field("error", err.Error()))
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
for i := range list {
|
|
||||||
list[i].Promo = promos[list[i].Id]
|
|
||||||
}
|
|
||||||
|
|
||||||
resp.List = list
|
resp.List = list
|
||||||
resp.Total = int64(len(list))
|
resp.Total = int64(len(list))
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -1,89 +0,0 @@
|
|||||||
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,7 +2,10 @@ package user
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"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/model/user"
|
||||||
"github.com/perfect-panel/server/internal/svc"
|
"github.com/perfect-panel/server/internal/svc"
|
||||||
"github.com/perfect-panel/server/internal/types"
|
"github.com/perfect-panel/server/internal/types"
|
||||||
@@ -35,70 +38,57 @@ func (l *CommissionWithdrawLogic) CommissionWithdraw(req *types.CommissionWithdr
|
|||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate payment method fields
|
if u.Commission < req.Amount {
|
||||||
switch req.Method {
|
logger.Errorf("User %d has insufficient commission balance: %.2f, requested: %.2f", u.Id, float64(u.Commission)/100, float64(req.Amount)/100)
|
||||||
case user.WithdrawalMethodAlipay, user.WithdrawalMethodWechat:
|
|
||||||
if req.QrCodeUrl == "" {
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "qr_code_url is required for method %d", req.Method)
|
|
||||||
}
|
|
||||||
case user.WithdrawalMethodBank:
|
|
||||||
if req.Account == "" {
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "account is required for bank transfer")
|
|
||||||
}
|
|
||||||
default: // WithdrawalMethodOther
|
|
||||||
if req.Account == "" && req.Content == "" {
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "account or content is required for other methods")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sum all pending (status=0) withdrawals to compute available balance.
|
|
||||||
// Available = commission - pendingTotal; commission is only deducted on approval.
|
|
||||||
var pendingTotal int64
|
|
||||||
if err = l.svcCtx.DB.WithContext(l.ctx).
|
|
||||||
Model(&user.Withdrawal{}).
|
|
||||||
Where("user_id = ? AND status = ?", u.Id, user.WithdrawalStatusPending).
|
|
||||||
Select("COALESCE(SUM(amount), 0)").
|
|
||||||
Scan(&pendingTotal).Error; err != nil {
|
|
||||||
l.Errorf("Failed to query pending withdrawals for user %d: %v", u.Id, err)
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Failed to query pending withdrawals for user %d", u.Id)
|
|
||||||
}
|
|
||||||
|
|
||||||
if u.Commission < req.Amount+pendingTotal {
|
|
||||||
logger.Errorf("User %d insufficient available commission: total=%d pending=%d requested=%d",
|
|
||||||
u.Id, u.Commission, pendingTotal, req.Amount)
|
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserCommissionNotEnough), "User %d has insufficient commission balance", u.Id)
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.UserCommissionNotEnough), "User %d has insufficient commission balance", u.Id)
|
||||||
}
|
}
|
||||||
|
|
||||||
var w user.Withdrawal
|
tx := l.svcCtx.DB.WithContext(l.ctx).Begin()
|
||||||
err = l.svcCtx.DB.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error {
|
now := time.Now()
|
||||||
w = user.Withdrawal{
|
|
||||||
UserId: u.Id,
|
// Atomically deduct the requested amount so concurrent commission growth is preserved.
|
||||||
Amount: req.Amount,
|
if err = l.svcCtx.DB.WithContext(l.ctx).
|
||||||
Content: req.Content,
|
Model(&user.User{}).
|
||||||
Status: user.WithdrawalStatusPending,
|
Where("id = ? AND commission >= ?", u.Id, req.Amount).
|
||||||
Reason: "",
|
UpdateColumn("commission", gorm.Expr("commission - ?", req.Amount)).Error; err != nil {
|
||||||
Method: req.Method,
|
tx.Rollback()
|
||||||
Account: req.Account,
|
l.Errorf("Failed to update user %d commission balance: %v", u.Id, err)
|
||||||
QrCodeUrl: req.QrCodeUrl,
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "Failed to update user %d commission balance: %v", u.Id, err)
|
||||||
}
|
}
|
||||||
return tx.Create(&w).Error
|
_ = 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
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorf("Failed to create withdrawal for user %d: %v", u.Id, err)
|
tx.Rollback()
|
||||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "Failed to create withdrawal for user %d: %v", u.Id, err)
|
l.Errorf("Failed to create withdrawal log for user %d: %v", u.Id, err)
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "Failed to create withdrawal log for user %d: %v", u.Id, err)
|
||||||
|
}
|
||||||
|
if err = tx.Commit().Error; err != nil {
|
||||||
|
l.Errorf("Transaction commit failed for user %d withdrawal: %v", u.Id, err)
|
||||||
|
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Transaction commit failed for user %d withdrawal: %v", u.Id, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &types.WithdrawalLog{
|
return &types.WithdrawalLog{
|
||||||
Id: w.Id,
|
|
||||||
UserId: u.Id,
|
UserId: u.Id,
|
||||||
Amount: req.Amount,
|
Amount: req.Amount,
|
||||||
Content: req.Content,
|
Content: req.Content,
|
||||||
Status: user.WithdrawalStatusPending,
|
Status: 0,
|
||||||
Reason: "",
|
Reason: "",
|
||||||
Method: req.Method,
|
CreatedAt: now.UnixMilli(),
|
||||||
Account: req.Account,
|
UpdatedAt: now.UnixMilli(),
|
||||||
QrCodeUrl: req.QrCodeUrl,
|
|
||||||
CreatedAt: w.CreatedAt.UnixMilli(),
|
|
||||||
UpdatedAt: w.UpdatedAt.UnixMilli(),
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -64,9 +64,6 @@ func (l *QueryWithdrawalLogLogic) QueryWithdrawalLog(req *types.QueryWithdrawalL
|
|||||||
Content: row.Content,
|
Content: row.Content,
|
||||||
Status: row.Status,
|
Status: row.Status,
|
||||||
Reason: row.Reason,
|
Reason: row.Reason,
|
||||||
Method: row.Method,
|
|
||||||
Account: row.Account,
|
|
||||||
QrCodeUrl: row.QrCodeUrl,
|
|
||||||
CreatedAt: row.CreatedAt.UnixMilli(),
|
CreatedAt: row.CreatedAt.UnixMilli(),
|
||||||
UpdatedAt: row.UpdatedAt.UnixMilli(),
|
UpdatedAt: row.UpdatedAt.UnixMilli(),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -39,14 +39,14 @@ func (l *DeviceWsConnectLogic) DeviceWsConnect(c *gin.Context) error {
|
|||||||
value, _ = c.GetQuery("identifier")
|
value, _ = c.GetQuery("identifier")
|
||||||
if value == nil || value.(string) == "" {
|
if value == nil || value.(string) == "" {
|
||||||
l.Errorf("DeviceWsConnectLogic DeviceWsConnect identifier is empty")
|
l.Errorf("DeviceWsConnectLogic DeviceWsConnect identifier is empty")
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.InvalidParams), "identifier is empty")
|
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "identifier is empty")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
identifier := value.(string)
|
identifier := value.(string)
|
||||||
_, err := l.svcCtx.UserModel.FindOneDeviceByIdentifier(l.ctx, identifier)
|
_, err := l.svcCtx.UserModel.FindOneDeviceByIdentifier(l.ctx, identifier)
|
||||||
if err != nil && !sysErr.Is(err, gorm.ErrRecordNotFound) {
|
if err != nil && !sysErr.Is(err, gorm.ErrRecordNotFound) {
|
||||||
l.Errorf("DeviceWsConnectLogic DeviceWsConnect FindOneDeviceByIdentifier err: %v", err)
|
l.Errorf("DeviceWsConnectLogic DeviceWsConnect FindOneDeviceByIdentifier err: %v", err)
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseQueryError), err.Error())
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
value = l.ctx.Value(constant.CtxKeyUser)
|
value = l.ctx.Value(constant.CtxKeyUser)
|
||||||
@@ -67,7 +67,7 @@ func (l *DeviceWsConnectLogic) DeviceWsConnect(c *gin.Context) error {
|
|||||||
err := l.svcCtx.UserModel.InsertDevice(l.ctx, &device)
|
err := l.svcCtx.UserModel.InsertDevice(l.ctx, &device)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
l.Errorf("DeviceWsConnectLogic DeviceWsConnect InsertDevice err: %v", err)
|
l.Errorf("DeviceWsConnectLogic DeviceWsConnect InsertDevice err: %v", err)
|
||||||
return errors.Wrap(xerr.NewErrCode(xerr.DatabaseInsertError), err.Error())
|
return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//默认在线设备1
|
//默认在线设备1
|
||||||
|
|||||||
@@ -22,92 +22,77 @@ import (
|
|||||||
|
|
||||||
func AuthMiddleware(svc *svc.ServiceContext) func(c *gin.Context) {
|
func AuthMiddleware(svc *svc.ServiceContext) func(c *gin.Context) {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
if !authenticateRequest(c, svc, c.GetHeader("Authorization"), true) {
|
ctx := c.Request.Context()
|
||||||
return
|
|
||||||
}
|
|
||||||
c.Next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func OptionalAuthMiddleware(svc *svc.ServiceContext) func(c *gin.Context) {
|
jwtConfig := svc.Config.JwtAuth
|
||||||
return func(c *gin.Context) {
|
// get token from header
|
||||||
token := c.GetHeader("Authorization")
|
token := c.GetHeader("Authorization")
|
||||||
if token == "" {
|
if token == "" {
|
||||||
c.Next()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !authenticateRequest(c, svc, token, false) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.Next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func authenticateRequest(c *gin.Context, svc *svc.ServiceContext, token string, requireToken bool) bool {
|
|
||||||
ctx := c.Request.Context()
|
|
||||||
|
|
||||||
if token == "" {
|
|
||||||
if requireToken {
|
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Token Empty")
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Token Empty")
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.ErrorTokenEmpty), "Token Empty"))
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.ErrorTokenEmpty), "Token Empty"))
|
||||||
c.Abort()
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// parse token
|
||||||
|
claims, err := jwt.ParseJwtToken(token, jwtConfig.AccessSecret)
|
||||||
|
if err != nil {
|
||||||
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] ParseJwtToken", logger.Field("error", err.Error()), logger.Field("token", token))
|
||||||
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.ErrorTokenExpire), "Token Invalid"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
}
|
}
|
||||||
return !requireToken
|
|
||||||
}
|
|
||||||
|
|
||||||
claims, err := jwt.ParseJwtToken(token, svc.Config.JwtAuth.AccessSecret)
|
loginType := parseLoginType(claims)
|
||||||
if err != nil {
|
if claims["identifier"] != nil {
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] ParseJwtToken", logger.Field("error", err.Error()), logger.Field("token", token))
|
ctx = context.WithValue(ctx, constant.CtxKeyIdentifier, claims["identifier"].(string))
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.ErrorTokenExpire), "Token Invalid"))
|
}
|
||||||
c.Abort()
|
// get user id from token
|
||||||
return false
|
userId := int64(claims["UserId"].(float64))
|
||||||
}
|
// get session id from token
|
||||||
|
sessionId := claims["SessionId"].(string)
|
||||||
|
// get session id from redis
|
||||||
|
sessionIdCacheKey := fmt.Sprintf("%v:%v", config.SessionIdKey, sessionId)
|
||||||
|
value, err := svc.Redis.Get(c, sessionIdCacheKey).Result()
|
||||||
|
if err != nil {
|
||||||
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Redis Get", logger.Field("error", err.Error()), logger.Field("sessionId", sessionId))
|
||||||
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
loginType := parseLoginType(claims)
|
//verify user id
|
||||||
if claims["identifier"] != nil {
|
if value != fmt.Sprintf("%v", userId) {
|
||||||
ctx = context.WithValue(ctx, constant.CtxKeyIdentifier, claims["identifier"].(string))
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Invalid Access", logger.Field("userId", userId), logger.Field("sessionId", sessionId))
|
||||||
}
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
||||||
userId := int64(claims["UserId"].(float64))
|
c.Abort()
|
||||||
sessionId := claims["SessionId"].(string)
|
return
|
||||||
sessionIdCacheKey := fmt.Sprintf("%v:%v", config.SessionIdKey, sessionId)
|
}
|
||||||
value, err := svc.Redis.Get(c, sessionIdCacheKey).Result()
|
|
||||||
if err != nil {
|
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Redis Get", logger.Field("error", err.Error()), logger.Field("sessionId", sessionId))
|
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
|
||||||
c.Abort()
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if value != fmt.Sprintf("%v", userId) {
|
// sliding session: refresh TTL on every active request
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Invalid Access", logger.Field("userId", userId), logger.Field("sessionId", sessionId))
|
svc.Redis.Expire(c, sessionIdCacheKey, time.Duration(svc.Config.JwtAuth.AccessExpire)*time.Second)
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
|
||||||
c.Abort()
|
userInfo, err := svc.UserModel.FindOne(c, userId)
|
||||||
return false
|
if err != nil {
|
||||||
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] UserModel FindOne", logger.Field("error", err.Error()), logger.Field("userId", userId))
|
||||||
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Database Query Error"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// admin verify
|
||||||
|
paths := strings.Split(c.Request.URL.Path, "/")
|
||||||
|
if tool.StringSliceContains(paths, "admin") && !*userInfo.IsAdmin {
|
||||||
|
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Not Admin User", logger.Field("userId", userId), logger.Field("sessionId", sessionId))
|
||||||
|
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx = context.WithValue(ctx, constant.CtxLoginType, loginType)
|
||||||
|
ctx = context.WithValue(ctx, constant.CtxKeyUser, userInfo)
|
||||||
|
ctx = context.WithValue(ctx, constant.CtxKeySessionID, sessionId)
|
||||||
|
|
||||||
|
c.Request = c.Request.WithContext(ctx)
|
||||||
|
c.Next()
|
||||||
}
|
}
|
||||||
|
|
||||||
svc.Redis.Expire(c, sessionIdCacheKey, time.Duration(svc.Config.JwtAuth.AccessExpire)*time.Second)
|
|
||||||
|
|
||||||
userInfo, err := svc.UserModel.FindOne(c, userId)
|
|
||||||
if err != nil {
|
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] UserModel FindOne", logger.Field("error", err.Error()), logger.Field("userId", userId))
|
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Database Query Error"))
|
|
||||||
c.Abort()
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
paths := strings.Split(c.Request.URL.Path, "/")
|
|
||||||
if tool.StringSliceContains(paths, "admin") && !*userInfo.IsAdmin {
|
|
||||||
logger.WithContext(c.Request.Context()).Debug("[AuthMiddleware] Not Admin User", logger.Field("userId", userId), logger.Field("sessionId", sessionId))
|
|
||||||
result.HttpResult(c, nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access"))
|
|
||||||
c.Abort()
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
ctx = context.WithValue(ctx, constant.CtxLoginType, loginType)
|
|
||||||
ctx = context.WithValue(ctx, constant.CtxKeyUser, userInfo)
|
|
||||||
ctx = context.WithValue(ctx, constant.CtxKeySessionID, sessionId)
|
|
||||||
|
|
||||||
c.Request = c.Request.WithContext(ctx)
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseLoginType(claims map[string]interface{}) string {
|
func parseLoginType(claims map[string]interface{}) string {
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ const (
|
|||||||
TypeSubscribeTraffic Type = 21 // Subscription traffic log
|
TypeSubscribeTraffic Type = 21 // Subscription traffic log
|
||||||
TypeServerTraffic Type = 22 // Server traffic log
|
TypeServerTraffic Type = 22 // Server traffic log
|
||||||
TypeResetSubscribe Type = 23 // Reset subscription log
|
TypeResetSubscribe Type = 23 // Reset subscription log
|
||||||
TypeOrderRefund Type = 24 // Admin order refund log
|
|
||||||
TypeLogin Type = 30 // Login log
|
TypeLogin Type = 30 // Login log
|
||||||
TypeRegister Type = 31 // Registration log
|
TypeRegister Type = 31 // Registration log
|
||||||
TypeBalance Type = 32 // Balance log
|
TypeBalance Type = 32 // Balance log
|
||||||
@@ -51,7 +50,6 @@ const (
|
|||||||
CommissionTypeAdjust uint16 = 335 // Admin Adjust
|
CommissionTypeAdjust uint16 = 335 // Admin Adjust
|
||||||
CommissionTypeConvertBalance uint16 = 336 // Convert to Balance
|
CommissionTypeConvertBalance uint16 = 336 // Convert to Balance
|
||||||
CommissionTypeWithdrawReject uint16 = 337 // Withdraw rejected refund
|
CommissionTypeWithdrawReject uint16 = 337 // Withdraw rejected refund
|
||||||
CommissionTypeWithdrawCancel uint16 = 338 // 用户取消提现退佣金
|
|
||||||
GiftTypeIncrease uint16 = 341 // Increase
|
GiftTypeIncrease uint16 = 341 // Increase
|
||||||
GiftTypeReduce uint16 = 342 // Reduce
|
GiftTypeReduce uint16 = 342 // Reduce
|
||||||
)
|
)
|
||||||
@@ -280,42 +278,6 @@ func (c *Commission) Unmarshal(data []byte) error {
|
|||||||
return json.Unmarshal(data, aux)
|
return json.Unmarshal(data, aux)
|
||||||
}
|
}
|
||||||
|
|
||||||
type OrderRefund struct {
|
|
||||||
OrderId int64 `json:"order_id"`
|
|
||||||
OrderNo string `json:"order_no"`
|
|
||||||
OperatorUserId int64 `json:"operator_user_id"`
|
|
||||||
OperatorAuthIdentifier string `json:"operator_auth_identifier,omitempty"`
|
|
||||||
TargetUserId int64 `json:"target_user_id"`
|
|
||||||
UserSubscribeId int64 `json:"user_subscribe_id"`
|
|
||||||
RefererUserId int64 `json:"referer_user_id,omitempty"`
|
|
||||||
CommissionAmount int64 `json:"commission_amount"`
|
|
||||||
Reason string `json:"reason,omitempty"`
|
|
||||||
OrderStatusBefore uint8 `json:"order_status_before"`
|
|
||||||
OrderStatusAfter uint8 `json:"order_status_after"`
|
|
||||||
SubscribeStatusBefore uint8 `json:"subscribe_status_before"`
|
|
||||||
SubscribeStatusAfter uint8 `json:"subscribe_status_after"`
|
|
||||||
SubscribeExpireBefore int64 `json:"subscribe_expire_before"`
|
|
||||||
SubscribeExpireAfter int64 `json:"subscribe_expire_after"`
|
|
||||||
CommissionBefore int64 `json:"commission_before"`
|
|
||||||
CommissionAfter int64 `json:"commission_after"`
|
|
||||||
Timestamp int64 `json:"timestamp"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o *OrderRefund) Marshal() ([]byte, error) {
|
|
||||||
type Alias OrderRefund
|
|
||||||
return json.Marshal(&struct {
|
|
||||||
*Alias
|
|
||||||
}{
|
|
||||||
Alias: (*Alias)(o),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o *OrderRefund) Unmarshal(data []byte) error {
|
|
||||||
type Alias OrderRefund
|
|
||||||
aux := (*Alias)(o)
|
|
||||||
return json.Unmarshal(data, aux)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gift represents a gift log entry.
|
// Gift represents a gift log entry.
|
||||||
type Gift struct {
|
type Gift struct {
|
||||||
Type uint16 `json:"type"`
|
Type uint16 `json:"type"`
|
||||||
|
|||||||
@@ -22,8 +22,6 @@ type Details struct {
|
|||||||
Price int64 `gorm:"type:int;not null;default:0;comment:Original price"`
|
Price int64 `gorm:"type:int;not null;default:0;comment:Original price"`
|
||||||
Amount int64 `gorm:"type:int;not null;default:0;comment:Order Amount"`
|
Amount int64 `gorm:"type:int;not null;default:0;comment:Order Amount"`
|
||||||
Discount int64 `gorm:"type:int;not null;default:0;comment:Order Discount"`
|
Discount int64 `gorm:"type:int;not null;default:0;comment:Order Discount"`
|
||||||
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;default:0;comment:Promo Rule ID"`
|
|
||||||
PromoDiscount int64 `gorm:"type:bigint;not null;default:0;comment:Promo Discount Amount"`
|
|
||||||
Coupon string `gorm:"type:varchar(255);default:null;comment:Coupon"`
|
Coupon string `gorm:"type:varchar(255);default:null;comment:Coupon"`
|
||||||
CouponDiscount int64 `gorm:"type:int;not null;default:0;comment:Coupon Discount"`
|
CouponDiscount int64 `gorm:"type:int;not null;default:0;comment:Coupon Discount"`
|
||||||
PaymentId int64 `gorm:"type:bigint;not null;default:0;comment:Payment Id"`
|
PaymentId int64 `gorm:"type:bigint;not null;default:0;comment:Payment Id"`
|
||||||
@@ -112,10 +110,6 @@ func (m *customOrderModel) UpdateOrderStatus(ctx context.Context, orderNo string
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
keys := m.getCacheKeys(orderInfo)
|
|
||||||
// Pre-delete: evict cache before the DB write so concurrent reads during the update
|
|
||||||
// window go to DB instead of getting a stale cached status (double-delete pattern).
|
|
||||||
_ = m.DelCacheCtx(ctx, keys...)
|
|
||||||
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
|
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
|
||||||
if len(tx) > 0 {
|
if len(tx) > 0 {
|
||||||
conn = tx[0]
|
conn = tx[0]
|
||||||
@@ -129,7 +123,7 @@ func (m *customOrderModel) UpdateOrderStatus(ctx context.Context, orderNo string
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}, keys...)
|
}, m.getCacheKeys(orderInfo)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// FindOneDetailsByOrderNo Find order details by order number
|
// FindOneDetailsByOrderNo Find order details by order number
|
||||||
|
|||||||
@@ -3,34 +3,31 @@ package order
|
|||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
type Order struct {
|
type Order struct {
|
||||||
Id int64 `gorm:"primaryKey"`
|
Id int64 `gorm:"primaryKey"`
|
||||||
ParentId int64 `gorm:"type:bigint;default:null;comment:Parent Order Id"`
|
ParentId int64 `gorm:"type:bigint;default:null;comment:Parent Order Id"`
|
||||||
UserId int64 `gorm:"type:bigint;not null;default:0;comment:User Id"`
|
UserId int64 `gorm:"type:bigint;not null;default:0;comment:User Id"`
|
||||||
SubscriptionUserId int64 `gorm:"type:bigint;not null;default:0;comment:Target user ID for subscription (0=same as UserId)"`
|
SubscriptionUserId int64 `gorm:"type:bigint;not null;default:0;comment:Target user ID for subscription (0=same as UserId)"`
|
||||||
OrderNo string `gorm:"type:varchar(255);not null;default:'';unique;comment:Order No"`
|
OrderNo string `gorm:"type:varchar(255);not null;default:'';unique;comment:Order No"`
|
||||||
Type uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Order Type: 1: Subscribe, 2: Renewal, 3: ResetTraffic, 4: Recharge"`
|
Type uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Order Type: 1: Subscribe, 2: Renewal, 3: ResetTraffic, 4: Recharge"`
|
||||||
Quantity int64 `gorm:"type:bigint;not null;default:1;comment:Quantity"`
|
Quantity int64 `gorm:"type:bigint;not null;default:1;comment:Quantity"`
|
||||||
Price int64 `gorm:"type:int;not null;default:0;comment:Original price"`
|
Price int64 `gorm:"type:int;not null;default:0;comment:Original price"`
|
||||||
Amount int64 `gorm:"type:int;not null;default:0;comment:Order Amount"`
|
Amount int64 `gorm:"type:int;not null;default:0;comment:Order Amount"`
|
||||||
GiftAmount int64 `gorm:"type:int;not null;default:0;comment:User Gift Amount"`
|
GiftAmount int64 `gorm:"type:int;not null;default:0;comment:User Gift Amount"`
|
||||||
Discount int64 `gorm:"type:int;not null;default:0;comment:Discount Amount"`
|
Discount int64 `gorm:"type:int;not null;default:0;comment:Discount Amount"`
|
||||||
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;default:0;comment:Promo Rule ID"`
|
Coupon string `gorm:"type:varchar(255);default:null;comment:Coupon"`
|
||||||
PromoDiscount int64 `gorm:"type:bigint;not null;default:0;comment:Promo Discount Amount"`
|
CouponDiscount int64 `gorm:"type:int;not null;default:0;comment:Coupon Discount Amount"`
|
||||||
Coupon string `gorm:"type:varchar(255);default:null;comment:Coupon"`
|
Commission int64 `gorm:"type:int;not null;default:0;comment:Order Commission"`
|
||||||
CouponDiscount int64 `gorm:"type:int;not null;default:0;comment:Coupon Discount Amount"`
|
PaymentId int64 `gorm:"type:bigint;not null;default:0;comment:Payment Method Id"`
|
||||||
Commission int64 `gorm:"type:int;not null;default:0;comment:Order Commission"`
|
Method string `gorm:"type:varchar(255);not null;default:'';comment:Payment Method"`
|
||||||
PaymentId int64 `gorm:"type:bigint;not null;default:0;comment:Payment Method Id"`
|
FeeAmount int64 `gorm:"type:int;not null;default:0;comment:Fee Amount"`
|
||||||
Method string `gorm:"type:varchar(255);not null;default:'';comment:Payment Method"`
|
TradeNo string `gorm:"type:varchar(255);default:null;comment:Trade No"`
|
||||||
FeeAmount int64 `gorm:"type:int;not null;default:0;comment:Fee Amount"`
|
Status uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Order Status: 1: Pending, 2: Paid, 3:Close, 4: Failed, 5:Finished;"`
|
||||||
TradeNo string `gorm:"type:varchar(255);default:null;comment:Trade No"`
|
SubscribeId int64 `gorm:"type:bigint;not null;default:0;comment:Subscribe Id"`
|
||||||
Status uint8 `gorm:"type:tinyint(1);not null;default:1;comment:Order Status: 1: Pending, 2: Paid, 3:Close, 4: Failed, 5:Finished;"`
|
SubscribeToken string `gorm:"type:varchar(255);default:null;comment:Renewal Subscribe Token"`
|
||||||
SubscribeId int64 `gorm:"type:bigint;not null;default:0;comment:Subscribe Id"`
|
AppAccountToken string `gorm:"type:varchar(36);default:null;comment:Apple IAP App Account Token (UUID)"`
|
||||||
SubscribeToken string `gorm:"type:varchar(255);default:null;comment:Renewal Subscribe Token"`
|
IsNew bool `gorm:"type:tinyint(1);not null;default:0;comment:Is New Order"`
|
||||||
AppAccountToken string `gorm:"type:varchar(36);default:null;comment:Apple IAP App Account Token (UUID)"`
|
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
||||||
ActivationContext string `gorm:"type:text;default:null;comment:Activation context JSON (guest/redemption info for DB fallback)"`
|
UpdatedAt time.Time `gorm:"comment:Update Time"`
|
||||||
IsNew bool `gorm:"type:tinyint(1);not null;default:0;comment:Is New Order"`
|
|
||||||
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
|
||||||
UpdatedAt time.Time `gorm:"comment:Update Time"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type OrdersTotal struct {
|
type OrdersTotal struct {
|
||||||
|
|||||||
@@ -1,218 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
"github.com/redis/go-redis/v9"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"gorm.io/gorm/clause"
|
|
||||||
)
|
|
||||||
|
|
||||||
type RuleWithPrice struct {
|
|
||||||
Rule
|
|
||||||
PromoPrice int64 `gorm:"column:promo_price"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type RuleFilter struct {
|
|
||||||
Page int
|
|
||||||
Size int
|
|
||||||
Type string
|
|
||||||
Enabled *bool
|
|
||||||
Search string
|
|
||||||
}
|
|
||||||
|
|
||||||
type SubscribePromoFilter struct {
|
|
||||||
Page int
|
|
||||||
Size int
|
|
||||||
PromoRuleId int64
|
|
||||||
}
|
|
||||||
|
|
||||||
type UsageFilter struct {
|
|
||||||
Page int
|
|
||||||
Size int
|
|
||||||
PromoRuleId int64
|
|
||||||
UserId int64
|
|
||||||
SubscribeId int64
|
|
||||||
OrderNo string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Model interface {
|
|
||||||
QueryEligibleRules(ctx context.Context, subscribeId int64) ([]*RuleWithPrice, error)
|
|
||||||
InsertUsage(ctx context.Context, data *Usage, tx ...*gorm.DB) error
|
|
||||||
InsertRule(ctx context.Context, data *Rule) error
|
|
||||||
FindRule(ctx context.Context, id int64) (*Rule, error)
|
|
||||||
UpdateRule(ctx context.Context, data *Rule) error
|
|
||||||
DeleteRule(ctx context.Context, id int64) error
|
|
||||||
QueryRuleList(ctx context.Context, filter RuleFilter) (int64, []*Rule, error)
|
|
||||||
UpsertSubscribePromos(ctx context.Context, data []*SubscribePromo) error
|
|
||||||
FindSubscribePromo(ctx context.Context, id int64) (*SubscribePromo, error)
|
|
||||||
DeleteSubscribePromo(ctx context.Context, id int64) error
|
|
||||||
QuerySubscribePromoList(ctx context.Context, filter SubscribePromoFilter) (int64, []*SubscribePromo, error)
|
|
||||||
QueryUsageList(ctx context.Context, filter UsageFilter) (int64, []*Usage, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type defaultPromoModel struct {
|
|
||||||
db *gorm.DB
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewModel(db *gorm.DB, _ *redis.Client) Model {
|
|
||||||
return &defaultPromoModel{db: db}
|
|
||||||
}
|
|
||||||
|
|
||||||
func normalizePage(page, size int) (int, int) {
|
|
||||||
if page <= 0 {
|
|
||||||
page = 1
|
|
||||||
}
|
|
||||||
if size <= 0 {
|
|
||||||
size = 10
|
|
||||||
}
|
|
||||||
if size > 100 {
|
|
||||||
size = 100
|
|
||||||
}
|
|
||||||
return page, size
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) QueryEligibleRules(ctx context.Context, subscribeId int64) ([]*RuleWithPrice, error) {
|
|
||||||
var list []*RuleWithPrice
|
|
||||||
err := m.db.WithContext(ctx).
|
|
||||||
Table("promo_rule AS pr").
|
|
||||||
Select("pr.*, sp.promo_price").
|
|
||||||
Joins("JOIN subscribe_promo AS sp ON sp.promo_rule_id = pr.id").
|
|
||||||
Where("sp.subscribe_id = ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeId, true).
|
|
||||||
Where("pr.deleted_at IS NULL").
|
|
||||||
Order("pr.priority DESC").
|
|
||||||
Order("pr.id ASC").
|
|
||||||
Find(&list).Error
|
|
||||||
return list, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) InsertUsage(ctx context.Context, data *Usage, tx ...*gorm.DB) error {
|
|
||||||
db := m.db.WithContext(ctx)
|
|
||||||
if len(tx) > 0 {
|
|
||||||
db = tx[0].WithContext(ctx)
|
|
||||||
}
|
|
||||||
return db.Model(&Usage{}).Create(data).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) InsertRule(ctx context.Context, data *Rule) error {
|
|
||||||
return m.db.WithContext(ctx).Create(data).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) FindRule(ctx context.Context, id int64) (*Rule, error) {
|
|
||||||
var data Rule
|
|
||||||
err := m.db.WithContext(ctx).Model(&Rule{}).Where("id = ?", id).First(&data).Error
|
|
||||||
return &data, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) UpdateRule(ctx context.Context, data *Rule) error {
|
|
||||||
return m.db.WithContext(ctx).Save(data).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) DeleteRule(ctx context.Context, id int64) error {
|
|
||||||
result := m.db.WithContext(ctx).Delete(&Rule{}, id)
|
|
||||||
if result.Error != nil {
|
|
||||||
return result.Error
|
|
||||||
}
|
|
||||||
if result.RowsAffected == 0 {
|
|
||||||
return gorm.ErrRecordNotFound
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) QueryRuleList(ctx context.Context, filter RuleFilter) (int64, []*Rule, error) {
|
|
||||||
page, size := normalizePage(filter.Page, filter.Size)
|
|
||||||
var total int64
|
|
||||||
var list []*Rule
|
|
||||||
|
|
||||||
query := m.db.WithContext(ctx).Model(&Rule{})
|
|
||||||
if filter.Type != "" {
|
|
||||||
query = query.Where("type = ?", filter.Type)
|
|
||||||
}
|
|
||||||
if filter.Enabled != nil {
|
|
||||||
query = query.Where("enabled = ?", *filter.Enabled)
|
|
||||||
}
|
|
||||||
if filter.Search != "" {
|
|
||||||
search := "%" + filter.Search + "%"
|
|
||||||
query = query.Where("name LIKE ?", search)
|
|
||||||
}
|
|
||||||
if err := query.Count(&total).Error; err != nil {
|
|
||||||
return 0, nil, err
|
|
||||||
}
|
|
||||||
err := query.Order("priority DESC").Order("id DESC").
|
|
||||||
Limit(size).Offset((page - 1) * size).
|
|
||||||
Find(&list).Error
|
|
||||||
return total, list, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) UpsertSubscribePromos(ctx context.Context, data []*SubscribePromo) error {
|
|
||||||
if len(data) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return m.db.WithContext(ctx).Clauses(clause.OnConflict{
|
|
||||||
Columns: []clause.Column{{Name: "subscribe_id"}, {Name: "promo_rule_id"}},
|
|
||||||
DoUpdates: clause.AssignmentColumns([]string{"promo_price", "updated_at"}),
|
|
||||||
}).Create(&data).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) FindSubscribePromo(ctx context.Context, id int64) (*SubscribePromo, error) {
|
|
||||||
var data SubscribePromo
|
|
||||||
err := m.db.WithContext(ctx).Model(&SubscribePromo{}).Where("id = ?", id).First(&data).Error
|
|
||||||
return &data, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) DeleteSubscribePromo(ctx context.Context, id int64) error {
|
|
||||||
result := m.db.WithContext(ctx).Delete(&SubscribePromo{}, id)
|
|
||||||
if result.Error != nil {
|
|
||||||
return result.Error
|
|
||||||
}
|
|
||||||
if result.RowsAffected == 0 {
|
|
||||||
return gorm.ErrRecordNotFound
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) QuerySubscribePromoList(ctx context.Context, filter SubscribePromoFilter) (int64, []*SubscribePromo, error) {
|
|
||||||
page, size := normalizePage(filter.Page, filter.Size)
|
|
||||||
var total int64
|
|
||||||
var list []*SubscribePromo
|
|
||||||
|
|
||||||
query := m.db.WithContext(ctx).Model(&SubscribePromo{})
|
|
||||||
if filter.PromoRuleId > 0 {
|
|
||||||
query = query.Where("promo_rule_id = ?", filter.PromoRuleId)
|
|
||||||
}
|
|
||||||
if err := query.Count(&total).Error; err != nil {
|
|
||||||
return 0, nil, err
|
|
||||||
}
|
|
||||||
err := query.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&list).Error
|
|
||||||
return total, list, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *defaultPromoModel) QueryUsageList(ctx context.Context, filter UsageFilter) (int64, []*Usage, error) {
|
|
||||||
page, size := normalizePage(filter.Page, filter.Size)
|
|
||||||
var total int64
|
|
||||||
var list []*Usage
|
|
||||||
|
|
||||||
query := m.db.WithContext(ctx).Model(&Usage{})
|
|
||||||
if filter.PromoRuleId > 0 {
|
|
||||||
query = query.Where("promo_rule_id = ?", filter.PromoRuleId)
|
|
||||||
}
|
|
||||||
if filter.UserId > 0 {
|
|
||||||
query = query.Where("user_id = ?", filter.UserId)
|
|
||||||
}
|
|
||||||
if filter.SubscribeId > 0 {
|
|
||||||
query = query.Where("subscribe_id = ?", filter.SubscribeId)
|
|
||||||
}
|
|
||||||
if filter.OrderNo != "" {
|
|
||||||
query = query.Where("order_no LIKE ?", "%"+filter.OrderNo+"%")
|
|
||||||
}
|
|
||||||
if err := query.Count(&total).Error; err != nil {
|
|
||||||
return 0, nil, err
|
|
||||||
}
|
|
||||||
err := query.Order("id DESC").Limit(size).Offset((page - 1) * size).Find(&list).Error
|
|
||||||
return total, list, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsNotFound(err error) bool {
|
|
||||||
return errors.Is(err, gorm.ErrRecordNotFound)
|
|
||||||
}
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
package promo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
RuleTypeNewUser = "new_user"
|
|
||||||
RuleTypeInactiveUser = "inactive_user"
|
|
||||||
RuleTypeCampaign = "campaign"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Rule struct {
|
|
||||||
Id int64 `gorm:"primaryKey"`
|
|
||||||
Name string `gorm:"type:varchar(100);not null;default:'';comment:Rule Name"`
|
|
||||||
Type string `gorm:"type:varchar(32);not null;default:'';comment:Rule Type"`
|
|
||||||
Params string `gorm:"type:json;not null;comment:Rule Params"`
|
|
||||||
Priority int64 `gorm:"type:int;not null;default:0;comment:Priority"`
|
|
||||||
Enabled bool `gorm:"type:tinyint(1);not null;default:1;comment:Enabled"`
|
|
||||||
StartTime *time.Time `gorm:"default:null;comment:Start Time"`
|
|
||||||
EndTime *time.Time `gorm:"default:null;comment:End Time"`
|
|
||||||
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
|
||||||
UpdatedAt time.Time `gorm:"comment:Update Time"`
|
|
||||||
DeletedAt gorm.DeletedAt `gorm:"index;comment:Delete Time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (Rule) TableName() string {
|
|
||||||
return "promo_rule"
|
|
||||||
}
|
|
||||||
|
|
||||||
type SubscribePromo struct {
|
|
||||||
Id int64 `gorm:"primaryKey"`
|
|
||||||
SubscribeId int64 `gorm:"type:bigint unsigned;not null;comment:Subscribe ID"`
|
|
||||||
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;comment:Promo Rule ID"`
|
|
||||||
PromoPrice int64 `gorm:"type:bigint;not null;default:0;comment:Promo Price"`
|
|
||||||
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
|
||||||
UpdatedAt time.Time `gorm:"comment:Update Time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (SubscribePromo) TableName() string {
|
|
||||||
return "subscribe_promo"
|
|
||||||
}
|
|
||||||
|
|
||||||
type Usage struct {
|
|
||||||
Id int64 `gorm:"primaryKey"`
|
|
||||||
UserId int64 `gorm:"type:bigint unsigned;not null;comment:User ID"`
|
|
||||||
PromoRuleId int64 `gorm:"type:bigint unsigned;not null;comment:Promo Rule ID"`
|
|
||||||
SubscribeId int64 `gorm:"type:bigint unsigned;not null;comment:Subscribe ID"`
|
|
||||||
OrderNo string `gorm:"type:varchar(255);not null;default:'';comment:Order No"`
|
|
||||||
PromoPrice int64 `gorm:"type:bigint;not null;default:0;comment:Promo Price"`
|
|
||||||
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (Usage) TableName() string {
|
|
||||||
return "promo_usage"
|
|
||||||
}
|
|
||||||
@@ -378,13 +378,13 @@ func (m *customUserModel) QueryDailyUserStatisticsList(ctx context.Context, date
|
|||||||
// 子查询:统计每天的新用户订单数量
|
// 子查询:统计每天的新用户订单数量
|
||||||
newOrderSub := conn.Model(&order.Order{}).
|
newOrderSub := conn.Model(&order.Order{}).
|
||||||
Select("DATE_FORMAT(created_at, '%Y-%m-%d') AS date, COUNT(DISTINCT user_id) AS new_order_users").
|
Select("DATE_FORMAT(created_at, '%Y-%m-%d') AS date, COUNT(DISTINCT user_id) AS new_order_users").
|
||||||
Where("type = 1 AND created_at BETWEEN ? AND ? AND status IN ? AND method != ?", firstDay, date, []int64{2, 5}, "balance").
|
Where("is_new = 1 AND created_at BETWEEN ? AND ? AND status IN ?", firstDay, date, []int64{2, 5}).
|
||||||
Group("DATE_FORMAT(created_at, '%Y-%m-%d')")
|
Group("DATE_FORMAT(created_at, '%Y-%m-%d')")
|
||||||
|
|
||||||
// 子查询:统计每天的续费订单数量
|
// 子查询:统计每天的续费订单数量
|
||||||
renewalOrderSub := conn.Model(&order.Order{}).
|
renewalOrderSub := conn.Model(&order.Order{}).
|
||||||
Select("DATE_FORMAT(created_at, '%Y-%m-%d') AS date, COUNT(DISTINCT user_id) AS renewal_order_users").
|
Select("DATE_FORMAT(created_at, '%Y-%m-%d') AS date, COUNT(DISTINCT user_id) AS renewal_order_users").
|
||||||
Where("type = 2 AND created_at BETWEEN ? AND ? AND status IN ? AND method != ?", firstDay, date, []int64{2, 5}, "balance").
|
Where("is_new = 0 AND created_at BETWEEN ? AND ? AND status IN ?", firstDay, date, []int64{2, 5}).
|
||||||
Group("DATE_FORMAT(created_at, '%Y-%m-%d')")
|
Group("DATE_FORMAT(created_at, '%Y-%m-%d')")
|
||||||
|
|
||||||
return conn.Model(&User{}).
|
return conn.Model(&User{}).
|
||||||
@@ -416,13 +416,13 @@ func (m *customUserModel) QueryMonthlyUserStatisticsList(ctx context.Context, da
|
|||||||
// 子查询:每月新订单用户数量
|
// 子查询:每月新订单用户数量
|
||||||
newOrderSub := conn.Model(&order.Order{}).
|
newOrderSub := conn.Model(&order.Order{}).
|
||||||
Select("DATE_FORMAT(created_at, '%Y-%m') AS date, COUNT(DISTINCT user_id) AS new_order_users").
|
Select("DATE_FORMAT(created_at, '%Y-%m') AS date, COUNT(DISTINCT user_id) AS new_order_users").
|
||||||
Where("type = 1 AND created_at >= ? AND status IN ? AND method != ?", sixMonthsAgo, []int64{2, 5}, "balance").
|
Where("is_new = 1 AND created_at >= ? AND status IN ?", sixMonthsAgo, []int64{2, 5}).
|
||||||
Group("DATE_FORMAT(created_at, '%Y-%m')")
|
Group("DATE_FORMAT(created_at, '%Y-%m')")
|
||||||
|
|
||||||
// 子查询:每月续费订单用户数量
|
// 子查询:每月续费订单用户数量
|
||||||
renewalOrderSub := conn.Model(&order.Order{}).
|
renewalOrderSub := conn.Model(&order.Order{}).
|
||||||
Select("DATE_FORMAT(created_at, '%Y-%m') AS date, COUNT(DISTINCT user_id) AS renewal_order_users").
|
Select("DATE_FORMAT(created_at, '%Y-%m') AS date, COUNT(DISTINCT user_id) AS renewal_order_users").
|
||||||
Where("type = 2 AND created_at >= ? AND status IN ? AND method != ?", sixMonthsAgo, []int64{2, 5}, "balance").
|
Where("is_new = 0 AND created_at >= ? AND status IN ?", sixMonthsAgo, []int64{2, 5}).
|
||||||
Group("DATE_FORMAT(created_at, '%Y-%m')")
|
Group("DATE_FORMAT(created_at, '%Y-%m')")
|
||||||
|
|
||||||
return conn.Model(&User{}).
|
return conn.Model(&User{}).
|
||||||
|
|||||||
@@ -101,8 +101,6 @@ type Subscribe struct {
|
|||||||
Traffic int64 `gorm:"default:0;comment:Traffic"`
|
Traffic int64 `gorm:"default:0;comment:Traffic"`
|
||||||
Download int64 `gorm:"default:0;comment:Download Traffic"`
|
Download int64 `gorm:"default:0;comment:Download Traffic"`
|
||||||
Upload int64 `gorm:"default:0;comment:Upload Traffic"`
|
Upload int64 `gorm:"default:0;comment:Upload Traffic"`
|
||||||
SpeedLimit int64 `gorm:"default:0;comment:User-level speed limit override (Mbps, 0=use plan default)"`
|
|
||||||
TrafficLimit string `gorm:"type:text;default:null;comment:User-level traffic limit rules override (JSON)"`
|
|
||||||
ExpiredDownload int64 `gorm:"default:0;comment:Expired period download traffic (bytes)"`
|
ExpiredDownload int64 `gorm:"default:0;comment:Expired period download traffic (bytes)"`
|
||||||
ExpiredUpload int64 `gorm:"default:0;comment:Expired period upload traffic (bytes)"`
|
ExpiredUpload int64 `gorm:"default:0;comment:Expired period upload traffic (bytes)"`
|
||||||
Token string `gorm:"index:idx_token;unique;type:varchar(255);default:'';comment:Token"`
|
Token string `gorm:"index:idx_token;unique;type:varchar(255);default:'';comment:Token"`
|
||||||
@@ -169,15 +167,12 @@ type Withdrawal struct {
|
|||||||
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
|
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
|
||||||
Amount int64 `gorm:"not null;comment:Withdrawal Amount"`
|
Amount int64 `gorm:"not null;comment:Withdrawal Amount"`
|
||||||
Content string `gorm:"type:text;comment:Withdrawal Content"`
|
Content string `gorm:"type:text;comment:Withdrawal Content"`
|
||||||
Status uint8 `gorm:"type:tinyint(1);default:0;comment:Withdrawal Status: 0: Pending 1: Approved 2: Rejected 3: Cancelled"`
|
Status uint8 `gorm:"type:tinyint(1);default:0;comment:Withdrawal Status: 0: Pending 1: Approved 2: Rejected"`
|
||||||
Reason string `gorm:"type:varchar(500);default:'';comment:Rejection Reason"`
|
Reason string `gorm:"type:varchar(500);default:'';comment:Rejection Reason"`
|
||||||
Method uint8 `gorm:"type:tinyint(1);default:0;comment:收款方式 0:其他 1:支付宝 2:微信 3:银行卡"`
|
|
||||||
Account string `gorm:"type:varchar(255);default:'';comment:收款账号"`
|
|
||||||
QrCodeUrl string `gorm:"type:varchar(500);default:'';comment:收款码图片URL"`
|
|
||||||
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
|
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
|
||||||
UpdatedAt time.Time `gorm:"comment:Update Time"`
|
UpdatedAt time.Time `gorm:"comment:Update Time"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (*Withdrawal) TableName() string {
|
func (*Withdrawal) TableName() string {
|
||||||
return "withdrawals"
|
return "user_withdrawal"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
const (
|
|
||||||
WithdrawalStatusPending uint8 = 0 // 待审核
|
|
||||||
WithdrawalStatusApproved uint8 = 1 // 已通过
|
|
||||||
WithdrawalStatusRejected uint8 = 2 // 已拒绝
|
|
||||||
WithdrawalStatusCancelled uint8 = 3 // 已取消(用户自行撤回)
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
WithdrawalMethodOther uint8 = 0 // 其他
|
|
||||||
WithdrawalMethodAlipay uint8 = 1 // 支付宝
|
|
||||||
WithdrawalMethodWechat uint8 = 2 // 微信
|
|
||||||
WithdrawalMethodBank uint8 = 3 // 银行卡
|
|
||||||
)
|
|
||||||
@@ -21,7 +21,6 @@ import (
|
|||||||
logmessage "github.com/perfect-panel/server/internal/model/logmessage"
|
logmessage "github.com/perfect-panel/server/internal/model/logmessage"
|
||||||
"github.com/perfect-panel/server/internal/model/order"
|
"github.com/perfect-panel/server/internal/model/order"
|
||||||
"github.com/perfect-panel/server/internal/model/payment"
|
"github.com/perfect-panel/server/internal/model/payment"
|
||||||
"github.com/perfect-panel/server/internal/model/promo"
|
|
||||||
"github.com/perfect-panel/server/internal/model/subscribe"
|
"github.com/perfect-panel/server/internal/model/subscribe"
|
||||||
"github.com/perfect-panel/server/internal/model/system"
|
"github.com/perfect-panel/server/internal/model/system"
|
||||||
"github.com/perfect-panel/server/internal/model/ticket"
|
"github.com/perfect-panel/server/internal/model/ticket"
|
||||||
@@ -46,7 +45,7 @@ type ServiceContext struct {
|
|||||||
ExchangeRate float64
|
ExchangeRate float64
|
||||||
GeoIP *IPLocation
|
GeoIP *IPLocation
|
||||||
SignatureValidator *signature.Validator
|
SignatureValidator *signature.Validator
|
||||||
S3Store *storage.S3Store
|
S3Store *storage.S3Store
|
||||||
|
|
||||||
//NodeCache *cache.NodeCacheClient
|
//NodeCache *cache.NodeCacheClient
|
||||||
AuthModel auth.Model
|
AuthModel auth.Model
|
||||||
@@ -64,7 +63,6 @@ type ServiceContext struct {
|
|||||||
RedemptionCodeModel redemption.RedemptionCodeModel
|
RedemptionCodeModel redemption.RedemptionCodeModel
|
||||||
RedemptionRecordModel redemption.RedemptionRecordModel
|
RedemptionRecordModel redemption.RedemptionRecordModel
|
||||||
PaymentModel payment.Model
|
PaymentModel payment.Model
|
||||||
PromoModel promo.Model
|
|
||||||
DocumentModel document.Model
|
DocumentModel document.Model
|
||||||
SubscribeModel subscribe.Model
|
SubscribeModel subscribe.Model
|
||||||
TrafficLogModel traffic.Model
|
TrafficLogModel traffic.Model
|
||||||
@@ -140,7 +138,6 @@ func NewServiceContext(c config.Config) *ServiceContext {
|
|||||||
RedemptionCodeModel: redemption.NewRedemptionCodeModel(db, rds),
|
RedemptionCodeModel: redemption.NewRedemptionCodeModel(db, rds),
|
||||||
RedemptionRecordModel: redemption.NewRedemptionRecordModel(db, rds),
|
RedemptionRecordModel: redemption.NewRedemptionRecordModel(db, rds),
|
||||||
PaymentModel: payment.NewModel(db, rds),
|
PaymentModel: payment.NewModel(db, rds),
|
||||||
PromoModel: promo.NewModel(db, rds),
|
|
||||||
DocumentModel: document.NewModel(db, rds),
|
DocumentModel: document.NewModel(db, rds),
|
||||||
SubscribeModel: subscribe.NewModel(db, rds),
|
SubscribeModel: subscribe.NewModel(db, rds),
|
||||||
TrafficLogModel: traffic.NewModel(db),
|
TrafficLogModel: traffic.NewModel(db),
|
||||||
|
|||||||
+50
-262
@@ -3,17 +3,10 @@
|
|||||||
|
|
||||||
package types
|
package types
|
||||||
|
|
||||||
import "encoding/json"
|
|
||||||
|
|
||||||
type ActivateOrderRequest struct {
|
type ActivateOrderRequest struct {
|
||||||
OrderNo string `json:"order_no" validate:"required"`
|
OrderNo string `json:"order_no" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type RefundOrderRequest struct {
|
|
||||||
Id int64 `json:"id" validate:"required"`
|
|
||||||
Reason string `json:"reason,omitempty" validate:"omitempty,max=500"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Ads struct {
|
type Ads struct {
|
||||||
Id int `json:"id"`
|
Id int `json:"id"`
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
@@ -296,11 +289,8 @@ type CommissionLog struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type CommissionWithdrawRequest struct {
|
type CommissionWithdrawRequest struct {
|
||||||
Amount int64 `json:"amount"`
|
Amount int64 `json:"amount"`
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
Method uint8 `json:"method" validate:"oneof=0 1 2 3"`
|
|
||||||
Account string `json:"account,omitempty"`
|
|
||||||
QrCodeUrl string `json:"qr_code_url,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ConnectionRecords struct {
|
type ConnectionRecords struct {
|
||||||
@@ -436,21 +426,6 @@ type CreatePaymentMethodRequest struct {
|
|||||||
Enable *bool `json:"enable" validate:"required"`
|
Enable *bool `json:"enable" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreatePromoRuleRequest struct {
|
|
||||||
Name string `json:"name" validate:"required,max=100"`
|
|
||||||
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
|
||||||
Params json.RawMessage `json:"params" validate:"required"`
|
|
||||||
Priority int64 `json:"priority" validate:"gte=0"`
|
|
||||||
Enabled *bool `json:"enabled" validate:"required"`
|
|
||||||
StartTime int64 `json:"start_time" validate:"required"`
|
|
||||||
EndTime int64 `json:"end_time" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type CreatePromoPriceRequest struct {
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id" validate:"required"`
|
|
||||||
Items []PromoPriceInput `json:"items" validate:"required,dive"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type CreateQuotaTaskRequest struct {
|
type CreateQuotaTaskRequest struct {
|
||||||
Subscribers []int64 `json:"subscribers"`
|
Subscribers []int64 `json:"subscribers"`
|
||||||
IsActive *bool `json:"is_active"`
|
IsActive *bool `json:"is_active"`
|
||||||
@@ -556,12 +531,10 @@ type CreateUserRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type CreateUserSubscribeRequest struct {
|
type CreateUserSubscribeRequest struct {
|
||||||
UserId int64 `json:"user_id"`
|
UserId int64 `json:"user_id"`
|
||||||
ExpiredAt int64 `json:"expired_at"`
|
ExpiredAt int64 `json:"expired_at"`
|
||||||
Traffic int64 `json:"traffic"`
|
Traffic int64 `json:"traffic"`
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
SpeedLimit int64 `json:"speed_limit,optional"`
|
|
||||||
TrafficLimit string `json:"traffic_limit,optional"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreateUserTicketFollowRequest struct {
|
type CreateUserTicketFollowRequest struct {
|
||||||
@@ -634,14 +607,6 @@ type DeletePaymentMethodRequest struct {
|
|||||||
Id int64 `json:"id" validate:"required"`
|
Id int64 `json:"id" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type DeletePromoPriceRequest struct {
|
|
||||||
Id int64 `path:"id" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type DeletePromoRuleRequest struct {
|
|
||||||
Id int64 `path:"id" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type DeleteRedemptionCodeRequest struct {
|
type DeleteRedemptionCodeRequest struct {
|
||||||
Id int64 `json:"id" validate:"required"`
|
Id int64 `json:"id" validate:"required"`
|
||||||
}
|
}
|
||||||
@@ -861,17 +826,6 @@ type FilterCommissionLogResponse struct {
|
|||||||
List []CommissionLog `json:"list"`
|
List []CommissionLog `json:"list"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type FilterOrderRefundLogRequest struct {
|
|
||||||
FilterLogParams
|
|
||||||
OrderId int64 `form:"order_id,optional"`
|
|
||||||
UserId int64 `form:"user_id,optional"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type FilterOrderRefundLogResponse struct {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []OrderRefundLog `json:"list"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type FilterEmailLogResponse struct {
|
type FilterEmailLogResponse struct {
|
||||||
Total int64 `json:"total"`
|
Total int64 `json:"total"`
|
||||||
List []MessageLog `json:"list"`
|
List []MessageLog `json:"list"`
|
||||||
@@ -1350,48 +1304,6 @@ type GetPaymentMethodListResponse struct {
|
|||||||
List []PaymentMethodDetail `json:"list"`
|
List []PaymentMethodDetail `json:"list"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type GetPromoPriceListRequest struct {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
PromoRuleId int64 `form:"promo_rule_id" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoPriceListResponse struct {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoPrice `json:"list"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoRuleDetailRequest struct {
|
|
||||||
Id int64 `path:"id" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoRuleListRequest struct {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
Type string `form:"type,omitempty" validate:"omitempty,oneof=new_user inactive_user campaign"`
|
|
||||||
Enabled *bool `form:"enabled,omitempty"`
|
|
||||||
Search string `form:"search,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoRuleListResponse struct {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoRule `json:"list"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoUsageListRequest struct {
|
|
||||||
Page int64 `form:"page" validate:"required"`
|
|
||||||
Size int64 `form:"size" validate:"required"`
|
|
||||||
PromoRuleId int64 `form:"rule_id,omitempty"`
|
|
||||||
UserId int64 `form:"user_id,omitempty"`
|
|
||||||
SubscribeId int64 `form:"subscribe_id,omitempty"`
|
|
||||||
OrderNo string `form:"order_no,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPromoUsageListResponse struct {
|
|
||||||
Total int64 `json:"total"`
|
|
||||||
List []PromoUsage `json:"list"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetPreSendEmailCountRequest struct {
|
type GetPreSendEmailCountRequest struct {
|
||||||
Scope int8 `json:"scope"`
|
Scope int8 `json:"scope"`
|
||||||
RegisterStartTime int64 `json:"register_start_time,omitempty"`
|
RegisterStartTime int64 `json:"register_start_time,omitempty"`
|
||||||
@@ -1933,8 +1845,6 @@ type Order struct {
|
|||||||
Amount int64 `json:"amount"`
|
Amount int64 `json:"amount"`
|
||||||
GiftAmount int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
Discount int64 `json:"discount"`
|
Discount int64 `json:"discount"`
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
PromoDiscount int64 `json:"promo_discount"`
|
|
||||||
Coupon string `json:"coupon"`
|
Coupon string `json:"coupon"`
|
||||||
CouponDiscount int64 `json:"coupon_discount"`
|
CouponDiscount int64 `json:"coupon_discount"`
|
||||||
Commission int64 `json:"commission,omitempty"`
|
Commission int64 `json:"commission,omitempty"`
|
||||||
@@ -1942,7 +1852,6 @@ type Order struct {
|
|||||||
FeeAmount int64 `json:"fee_amount"`
|
FeeAmount int64 `json:"fee_amount"`
|
||||||
TradeNo string `json:"trade_no"`
|
TradeNo string `json:"trade_no"`
|
||||||
Status uint8 `json:"status"`
|
Status uint8 `json:"status"`
|
||||||
StatusName string `json:"status_name,omitempty"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
CreatedAt int64 `json:"created_at"`
|
CreatedAt int64 `json:"created_at"`
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
UpdatedAt int64 `json:"updated_at"`
|
||||||
@@ -1958,8 +1867,6 @@ type OrderDetail struct {
|
|||||||
Amount int64 `json:"amount"`
|
Amount int64 `json:"amount"`
|
||||||
GiftAmount int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
Discount int64 `json:"discount"`
|
Discount int64 `json:"discount"`
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
PromoDiscount int64 `json:"promo_discount"`
|
|
||||||
Coupon string `json:"coupon"`
|
Coupon string `json:"coupon"`
|
||||||
CouponDiscount int64 `json:"coupon_discount"`
|
CouponDiscount int64 `json:"coupon_discount"`
|
||||||
Commission int64 `json:"commission,omitempty"`
|
Commission int64 `json:"commission,omitempty"`
|
||||||
@@ -1968,34 +1875,12 @@ type OrderDetail struct {
|
|||||||
FeeAmount int64 `json:"fee_amount"`
|
FeeAmount int64 `json:"fee_amount"`
|
||||||
TradeNo string `json:"trade_no"`
|
TradeNo string `json:"trade_no"`
|
||||||
Status uint8 `json:"status"`
|
Status uint8 `json:"status"`
|
||||||
StatusName string `json:"status_name,omitempty"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
Subscribe Subscribe `json:"subscribe"`
|
Subscribe Subscribe `json:"subscribe"`
|
||||||
CreatedAt int64 `json:"created_at"`
|
CreatedAt int64 `json:"created_at"`
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
UpdatedAt int64 `json:"updated_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type OrderRefundLog struct {
|
|
||||||
OrderId int64 `json:"order_id"`
|
|
||||||
OrderNo string `json:"order_no"`
|
|
||||||
OperatorUserId int64 `json:"operator_user_id"`
|
|
||||||
OperatorAuthIdentifier string `json:"operator_auth_identifier,omitempty"`
|
|
||||||
TargetUserId int64 `json:"target_user_id"`
|
|
||||||
UserSubscribeId int64 `json:"user_subscribe_id"`
|
|
||||||
RefererUserId int64 `json:"referer_user_id,omitempty"`
|
|
||||||
CommissionAmount int64 `json:"commission_amount"`
|
|
||||||
Reason string `json:"reason,omitempty"`
|
|
||||||
OrderStatusBefore uint8 `json:"order_status_before"`
|
|
||||||
OrderStatusAfter uint8 `json:"order_status_after"`
|
|
||||||
SubscribeStatusBefore uint8 `json:"subscribe_status_before"`
|
|
||||||
SubscribeStatusAfter uint8 `json:"subscribe_status_after"`
|
|
||||||
SubscribeExpireBefore int64 `json:"subscribe_expire_before"`
|
|
||||||
SubscribeExpireAfter int64 `json:"subscribe_expire_after"`
|
|
||||||
CommissionBefore int64 `json:"commission_before"`
|
|
||||||
CommissionAfter int64 `json:"commission_after"`
|
|
||||||
Timestamp int64 `json:"timestamp"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type OrdersStatistics struct {
|
type OrdersStatistics struct {
|
||||||
Date string `json:"date,omitempty"`
|
Date string `json:"date,omitempty"`
|
||||||
AmountTotal int64 `json:"amount_total"`
|
AmountTotal int64 `json:"amount_total"`
|
||||||
@@ -2081,7 +1966,6 @@ type PreOrderResponse struct {
|
|||||||
Price int64 `json:"price"`
|
Price int64 `json:"price"`
|
||||||
Amount int64 `json:"amount"`
|
Amount int64 `json:"amount"`
|
||||||
Discount int64 `json:"discount"`
|
Discount int64 `json:"discount"`
|
||||||
PromoDiscount int64 `json:"promo_discount"`
|
|
||||||
GiftAmount int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
Coupon string `json:"coupon"`
|
Coupon string `json:"coupon"`
|
||||||
CouponDiscount int64 `json:"coupon_discount"`
|
CouponDiscount int64 `json:"coupon_discount"`
|
||||||
@@ -2104,44 +1988,6 @@ type PrePurchaseOrderResponse struct {
|
|||||||
FeeAmount int64 `json:"fee_amount"`
|
FeeAmount int64 `json:"fee_amount"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type PromoPrice struct {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
UnitPrice int64 `json:"unit_price"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PromoPriceInput struct {
|
|
||||||
SubscribeId int64 `json:"subscribe_id" validate:"required"`
|
|
||||||
PromoPrice int64 `json:"promo_price" validate:"required,gt=0"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PromoRule struct {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
Params json.RawMessage `json:"params"`
|
|
||||||
Priority int64 `json:"priority"`
|
|
||||||
Enabled bool `json:"enabled"`
|
|
||||||
StartTime int64 `json:"start_time"`
|
|
||||||
EndTime int64 `json:"end_time"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PromoUsage struct {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
UserId int64 `json:"user_id"`
|
|
||||||
PromoRuleId int64 `json:"promo_rule_id"`
|
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
|
||||||
OrderNo string `json:"order_no"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PreRenewalOrderResponse struct {
|
type PreRenewalOrderResponse struct {
|
||||||
OrderNo string `json:"orderNo"`
|
OrderNo string `json:"orderNo"`
|
||||||
}
|
}
|
||||||
@@ -2428,10 +2274,6 @@ type QueryUserSubscribeNodeListResponse struct {
|
|||||||
List []UserSubscribeInfo `json:"list"`
|
List []UserSubscribeInfo `json:"list"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type CancelWithdrawalRequest struct {
|
|
||||||
WithdrawalId int64 `json:"withdrawal_id" validate:"required,gt=0"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type QueryWithdrawalLogListRequest struct {
|
type QueryWithdrawalLogListRequest struct {
|
||||||
Page int `form:"page"`
|
Page int `form:"page"`
|
||||||
Size int `form:"size"`
|
Size int `form:"size"`
|
||||||
@@ -2447,7 +2289,6 @@ type GetWithdrawalListRequest struct {
|
|||||||
Size int `form:"size"`
|
Size int `form:"size"`
|
||||||
UserId *int64 `form:"user_id,omitempty"`
|
UserId *int64 `form:"user_id,omitempty"`
|
||||||
Status *uint8 `form:"status,omitempty"`
|
Status *uint8 `form:"status,omitempty"`
|
||||||
Method *uint8 `form:"method,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type GetWithdrawalListResponse struct {
|
type GetWithdrawalListResponse struct {
|
||||||
@@ -2888,13 +2729,6 @@ type StripePayment struct {
|
|||||||
PublishableKey string `json:"publishable_key"`
|
PublishableKey string `json:"publishable_key"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type SubscribePromo struct {
|
|
||||||
RuleName string `json:"rule_name"`
|
|
||||||
RuleType string `json:"rule_type"`
|
|
||||||
PromoPrice int64 `json:"promo_price"`
|
|
||||||
ExpiresAt int64 `json:"expires_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Subscribe struct {
|
type Subscribe struct {
|
||||||
Id int64 `json:"id"`
|
Id int64 `json:"id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
@@ -2903,7 +2737,6 @@ type Subscribe struct {
|
|||||||
UnitPrice int64 `json:"unit_price"`
|
UnitPrice int64 `json:"unit_price"`
|
||||||
UnitTime string `json:"unit_time"`
|
UnitTime string `json:"unit_time"`
|
||||||
Discount []SubscribeDiscount `json:"discount"`
|
Discount []SubscribeDiscount `json:"discount"`
|
||||||
Promo *SubscribePromo `json:"promo"`
|
|
||||||
NodeCount int64 `json:"node_count"`
|
NodeCount int64 `json:"node_count"`
|
||||||
Replacement int64 `json:"replacement"`
|
Replacement int64 `json:"replacement"`
|
||||||
Inventory int64 `json:"inventory"`
|
Inventory int64 `json:"inventory"`
|
||||||
@@ -3310,17 +3143,6 @@ type UpdatePaymentMethodRequest struct {
|
|||||||
Enable *bool `json:"enable" validate:"required"`
|
Enable *bool `json:"enable" validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type UpdatePromoRuleRequest struct {
|
|
||||||
Id int64 `json:"id" validate:"required"`
|
|
||||||
Name string `json:"name" validate:"required,max=100"`
|
|
||||||
Type string `json:"type" validate:"required,oneof=new_user inactive_user campaign"`
|
|
||||||
Params json.RawMessage `json:"params" validate:"required"`
|
|
||||||
Priority int64 `json:"priority" validate:"gte=0"`
|
|
||||||
Enabled *bool `json:"enabled" validate:"required"`
|
|
||||||
StartTime int64 `json:"start_time" validate:"required"`
|
|
||||||
EndTime int64 `json:"end_time" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UpdateRedemptionCodeRequest struct {
|
type UpdateRedemptionCodeRequest struct {
|
||||||
Id int64 `json:"id" validate:"required"`
|
Id int64 `json:"id" validate:"required"`
|
||||||
TotalCount int64 `json:"total_count,omitempty"`
|
TotalCount int64 `json:"total_count,omitempty"`
|
||||||
@@ -3401,20 +3223,20 @@ type UpdateUserAuthMethodRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type UpdateUserBasiceInfoRequest struct {
|
type UpdateUserBasiceInfoRequest struct {
|
||||||
UserId int64 `json:"user_id" validate:"required"`
|
UserId int64 `json:"user_id" validate:"required"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
Avatar string `json:"avatar"`
|
Avatar string `json:"avatar"`
|
||||||
Balance *int64 `json:"balance"`
|
Balance int64 `json:"balance"`
|
||||||
Commission *int64 `json:"commission"`
|
Commission int64 `json:"commission"`
|
||||||
ReferralPercentage uint8 `json:"referral_percentage"`
|
ReferralPercentage uint8 `json:"referral_percentage"`
|
||||||
OnlyFirstPurchase *bool `json:"only_first_purchase"`
|
OnlyFirstPurchase *bool `json:"only_first_purchase"`
|
||||||
GiftAmount *int64 `json:"gift_amount"`
|
GiftAmount int64 `json:"gift_amount"`
|
||||||
Telegram int64 `json:"telegram"`
|
Telegram int64 `json:"telegram"`
|
||||||
ReferCode string `json:"refer_code"`
|
ReferCode string `json:"refer_code"`
|
||||||
RefererId *int64 `json:"referer_id"`
|
RefererId int64 `json:"referer_id"`
|
||||||
Enable *bool `json:"enable"`
|
Enable *bool `json:"enable"`
|
||||||
IsAdmin *bool `json:"is_admin"`
|
IsAdmin *bool `json:"is_admin"`
|
||||||
Remark *string `json:"remark"`
|
Remark string `json:"remark"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type UpdateUserNotifyRequest struct {
|
type UpdateUserNotifyRequest struct {
|
||||||
@@ -3446,14 +3268,12 @@ type UpdateUserSubscribeNoteRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type UpdateUserSubscribeRequest struct {
|
type UpdateUserSubscribeRequest struct {
|
||||||
UserSubscribeId int64 `json:"user_subscribe_id"`
|
UserSubscribeId int64 `json:"user_subscribe_id"`
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
Traffic int64 `json:"traffic"`
|
Traffic int64 `json:"traffic"`
|
||||||
ExpiredAt int64 `json:"expired_at"`
|
ExpiredAt int64 `json:"expired_at"`
|
||||||
Upload int64 `json:"upload"`
|
Upload int64 `json:"upload"`
|
||||||
Download int64 `json:"download"`
|
Download int64 `json:"download"`
|
||||||
SpeedLimit *int64 `json:"speed_limit,omitempty"`
|
|
||||||
TrafficLimit *string `json:"traffic_limit,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type UpdateUserTicketStatusRequest struct {
|
type UpdateUserTicketStatusRequest struct {
|
||||||
@@ -3605,33 +3425,30 @@ type UserSubscribe struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type UserSubscribeDetail struct {
|
type UserSubscribeDetail struct {
|
||||||
Id int64 `json:"id"`
|
Id int64 `json:"id"`
|
||||||
UserId int64 `json:"user_id"`
|
UserId int64 `json:"user_id"`
|
||||||
User User `json:"user"`
|
User User `json:"user"`
|
||||||
OrderId int64 `json:"order_id"`
|
OrderId int64 `json:"order_id"`
|
||||||
SubscribeId int64 `json:"subscribe_id"`
|
SubscribeId int64 `json:"subscribe_id"`
|
||||||
Subscribe Subscribe `json:"subscribe"`
|
Subscribe Subscribe `json:"subscribe"`
|
||||||
NodeGroupId int64 `json:"node_group_id"`
|
NodeGroupId int64 `json:"node_group_id"`
|
||||||
NodeGroupName string `json:"node_group_name"`
|
NodeGroupName string `json:"node_group_name"`
|
||||||
GroupLocked bool `json:"group_locked"`
|
GroupLocked bool `json:"group_locked"`
|
||||||
StartTime int64 `json:"start_time"`
|
StartTime int64 `json:"start_time"`
|
||||||
ExpireTime int64 `json:"expire_time"`
|
ExpireTime int64 `json:"expire_time"`
|
||||||
ResetTime int64 `json:"reset_time"`
|
ResetTime int64 `json:"reset_time"`
|
||||||
Traffic int64 `json:"traffic"`
|
Traffic int64 `json:"traffic"`
|
||||||
Download int64 `json:"download"`
|
Download int64 `json:"download"`
|
||||||
Upload int64 `json:"upload"`
|
Upload int64 `json:"upload"`
|
||||||
SpeedLimit int64 `json:"speed_limit"`
|
Token string `json:"token"`
|
||||||
TrafficLimit []TrafficLimit `json:"user_traffic_limit"`
|
Status uint8 `json:"status"`
|
||||||
PlanSpeedLimit int64 `json:"plan_speed_limit"`
|
EffectiveSpeed int64 `json:"effective_speed"`
|
||||||
Token string `json:"token"`
|
IsThrottled bool `json:"is_throttled"`
|
||||||
Status uint8 `json:"status"`
|
ThrottleRule string `json:"throttle_rule,omitempty"`
|
||||||
EffectiveSpeed int64 `json:"effective_speed"`
|
ThrottleStart int64 `json:"throttle_start,omitempty"`
|
||||||
IsThrottled bool `json:"is_throttled"`
|
ThrottleEnd int64 `json:"throttle_end,omitempty"`
|
||||||
ThrottleRule string `json:"throttle_rule,omitempty"`
|
CreatedAt int64 `json:"created_at"`
|
||||||
ThrottleStart int64 `json:"throttle_start,omitempty"`
|
UpdatedAt int64 `json:"updated_at"`
|
||||||
ThrottleEnd int64 `json:"throttle_end,omitempty"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type UserSubscribeInfo struct {
|
type UserSubscribeInfo struct {
|
||||||
@@ -3790,9 +3607,6 @@ type WithdrawalLog struct {
|
|||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
Status uint8 `json:"status"`
|
Status uint8 `json:"status"`
|
||||||
Reason string `json:"reason,omitempty"`
|
Reason string `json:"reason,omitempty"`
|
||||||
Method uint8 `json:"method"`
|
|
||||||
Account string `json:"account"`
|
|
||||||
QrCodeUrl string `json:"qr_code_url"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
CreatedAt int64 `json:"created_at"`
|
||||||
UpdatedAt int64 `json:"updated_at"`
|
UpdatedAt int64 `json:"updated_at"`
|
||||||
}
|
}
|
||||||
@@ -3827,29 +3641,3 @@ type GetAdminUserInviteListResponse struct {
|
|||||||
Total int64 `json:"total"`
|
Total int64 `json:"total"`
|
||||||
List []AdminInvitedUser `json:"list"`
|
List []AdminInvitedUser `json:"list"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type GetLogMessageRawRequest struct {
|
|
||||||
Id int64 `form:"id" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetLogMessageRawResponse struct {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
Platform string `json:"platform"`
|
|
||||||
AppVersion string `json:"app_version"`
|
|
||||||
OsName string `json:"os_name"`
|
|
||||||
OsVersion string `json:"os_version"`
|
|
||||||
DeviceId string `json:"device_id"`
|
|
||||||
UserId *int64 `json:"user_id"`
|
|
||||||
SessionId string `json:"session_id"`
|
|
||||||
Level uint8 `json:"level"`
|
|
||||||
ErrorCode string `json:"error_code"`
|
|
||||||
Message string `json:"message"`
|
|
||||||
Stack string `json:"stack"`
|
|
||||||
Context json.RawMessage `json:"context"`
|
|
||||||
ClientIP string `json:"client_ip"`
|
|
||||||
UserAgent string `json:"user_agent"`
|
|
||||||
Locale string `json:"locale"`
|
|
||||||
Digest string `json:"digest"`
|
|
||||||
OccurredAt int64 `json:"occurred_at"`
|
|
||||||
CreatedAt int64 `json:"created_at"`
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
package types
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestUpdateUserBasicInfoRequestRemarkPresence(t *testing.T) {
|
|
||||||
var omitted UpdateUserBasiceInfoRequest
|
|
||||||
if err := json.Unmarshal([]byte(`{"user_id":1}`), &omitted); err != nil {
|
|
||||||
t.Fatalf("unmarshal omitted remark: %v", err)
|
|
||||||
}
|
|
||||||
if omitted.Remark != nil {
|
|
||||||
t.Fatalf("omitted remark = %q, want nil", *omitted.Remark)
|
|
||||||
}
|
|
||||||
|
|
||||||
var cleared UpdateUserBasiceInfoRequest
|
|
||||||
if err := json.Unmarshal([]byte(`{"user_id":1,"remark":""}`), &cleared); err != nil {
|
|
||||||
t.Fatalf("unmarshal empty remark: %v", err)
|
|
||||||
}
|
|
||||||
if cleared.Remark == nil {
|
|
||||||
t.Fatal("empty remark was decoded as nil, want explicit empty string")
|
|
||||||
}
|
|
||||||
if *cleared.Remark != "" {
|
|
||||||
t.Fatalf("empty remark = %q, want empty string", *cleared.Remark)
|
|
||||||
}
|
|
||||||
|
|
||||||
var updated UpdateUserBasiceInfoRequest
|
|
||||||
if err := json.Unmarshal([]byte(`{"user_id":1,"remark":"new note"}`), &updated); err != nil {
|
|
||||||
t.Fatalf("unmarshal non-empty remark: %v", err)
|
|
||||||
}
|
|
||||||
if updated.Remark == nil || *updated.Remark != "new note" {
|
|
||||||
t.Fatalf("non-empty remark = %#v, want %q", updated.Remark, "new note")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
# Docker Image Version Pins
|
|
||||||
|
|
||||||
This file records the infrastructure image versions pinned in `docker-compose.cloud.yml`.
|
|
||||||
The versions below match the images observed on the test deployment on 2026-05-26.
|
|
||||||
|
|
||||||
| Service | Image | Running version source |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| grafana | `grafana/grafana:13.0.1` | `grafana version 13.0.1` |
|
|
||||||
| prometheus | `prom/prometheus:v3.11.3` | `prometheus, version 3.11.3` |
|
|
||||||
| nginx-exporter | `nginx/nginx-prometheus-exporter:1.5.0` | image label `org.opencontainers.image.version=1.5.0` |
|
|
||||||
| node-exporter | `prom/node-exporter:v1.11.1` | `node_exporter, version 1.11.1` |
|
|
||||||
| cadvisor | `gcr.io/cadvisor/cadvisor:v0.55.1` | `cAdvisor version v0.55.1` |
|
|
||||||
|
|
||||||
The test deployment in `/root/bindbox/docker-compose.cloud.yml` also contains
|
|
||||||
live-only exporter services that are not present in this repository's
|
|
||||||
`docker-compose.cloud.yml`. They were pinned during staging validation:
|
|
||||||
|
|
||||||
| Test-only service | Image | Running version source |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| mysql-exporter | `prom/mysqld-exporter:v0.19.0` | `mysqld_exporter, version 0.19.0` |
|
|
||||||
| redis-exporter | `oliver006/redis_exporter:v1.82.0` | image label `org.opencontainers.image.version=v1.82.0` |
|
|
||||||
|
|
||||||
`ppanel-server` intentionally remains variable and requires `PPANEL_SERVER_TAG`
|
|
||||||
from CI/CD so deployments use an immutable application image tag.
|
|
||||||
|
|
||||||
## Rollback
|
|
||||||
|
|
||||||
Restore the previous compose file from git and redeploy:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
git checkout HEAD~1 -- docker-compose.cloud.yml .env.example ops/docker-image-version-pins.md
|
|
||||||
docker compose -f docker-compose.cloud.yml up -d
|
|
||||||
```
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user