Compare commits
1 Commits
ab9da7bb33
...
hotfix/wal
| Author | SHA1 | Date | |
|---|---|---|---|
| 07e55d9f38 |
11
.env
11
.env
@@ -1,11 +0,0 @@
|
||||
MIGRATIONS_DIR=migrations
|
||||
DB_HOST=cxd.whcxd.cn
|
||||
DB_PORT=16159
|
||||
DB_USER=erp_pgsql
|
||||
DB_PASSWORD=erp_2025
|
||||
DB_NAME=junhong_cmp_test
|
||||
DB_SSLMODE=disable
|
||||
GOOGLE_GEMINI_BASE_URL="http://45.155.220.179:8317" # 根据实际填写你服务器的ip地址或者域名
|
||||
GEMINI_API_KEY="sk-VoNbvr6aGpjvZX64rvhrwowrZrCgtGuX9oxykIy8F1DBg"
|
||||
GOOGLE_GENAI_USE_GCA="true"
|
||||
GEMINI_MODEL="gemini-3-pro-preview" # 如果你有gemini3权限可以填: gemini-3-pro-preview
|
||||
93
.env.local
93
.env.local
@@ -1,93 +0,0 @@
|
||||
# ============================================================================
|
||||
# 君鸿卡管系统 - 本地开发环境变量
|
||||
# 生成时间: 2026-01-30 17:45:14
|
||||
# ============================================================================
|
||||
# 使用方法:
|
||||
# source .env.local && go run cmd/api/main.go
|
||||
# 或者:
|
||||
# ./scripts/run-local.sh
|
||||
# ============================================================================
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 数据库配置(必填)
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_DATABASE_HOST="cxd.whcxd.cn"
|
||||
export JUNHONG_DATABASE_PORT="16159"
|
||||
export JUNHONG_DATABASE_USER="erp_pgsql"
|
||||
export JUNHONG_DATABASE_PASSWORD="erp_2025"
|
||||
export JUNHONG_DATABASE_DBNAME="junhong_cmp_test"
|
||||
export JUNHONG_DATABASE_SSLMODE="disable"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Redis 配置(必填)
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_REDIS_ADDRESS="cxd.whcxd.cn"
|
||||
export JUNHONG_REDIS_PORT="16299"
|
||||
export JUNHONG_REDIS_PASSWORD="cpNbWtAaqgo1YJmbMp3h"
|
||||
export JUNHONG_REDIS_DB="6"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# JWT 配置(必填)
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_JWT_SECRET_KEY="dev-secret-key-for-testing-only-32chars!"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 客户端配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 是否强制 C 端用户绑定手机号(true: 强制,false: 不强制)
|
||||
export JUNHONG_CLIENT_REQUIRE_PHONE_BINDING="true"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 服务器配置
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_SERVER_ADDRESS=":3000"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 日志配置
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_LOGGING_LEVEL="debug"
|
||||
export JUNHONG_LOGGING_DEVELOPMENT="true"
|
||||
export JUNHONG_LOGGING_APP_LOG_FILENAME="logs/app.log"
|
||||
export JUNHONG_LOGGING_ACCESS_LOG_FILENAME="logs/access.log"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Gateway 服务配置
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_GATEWAY_BASE_URL="https://open.whjhft.com/openapi"
|
||||
export JUNHONG_GATEWAY_APP_ID="LfjL0WjUqpwkItQ0"
|
||||
export JUNHONG_GATEWAY_APP_SECRET="K0DYuWzbRE6zg5bX"
|
||||
export JUNHONG_GATEWAY_TIMEOUT="30"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 对象存储配置
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_STORAGE_PROVIDER="s3"
|
||||
export JUNHONG_STORAGE_S3_ENDPOINT="http://obs-helf.cucloud.cn"
|
||||
export JUNHONG_STORAGE_S3_REGION="cn-langfang-2"
|
||||
export JUNHONG_STORAGE_S3_BUCKET="cmp"
|
||||
export JUNHONG_STORAGE_S3_ACCESS_KEY_ID="598F558CF6FF46E79D1CFC607852378C9523"
|
||||
export JUNHONG_STORAGE_S3_SECRET_ACCESS_KEY="8393425DCB2F48F1914FF39DCBC6C7B17325"
|
||||
export JUNHONG_STORAGE_S3_USE_SSL="false"
|
||||
export JUNHONG_STORAGE_S3_PATH_STYLE="true"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 迁移工具兼容配置(用于 scripts/migrate.sh)
|
||||
# ----------------------------------------------------------------------------
|
||||
export MIGRATIONS_DIR="migrations"
|
||||
export DB_HOST="cxd.whcxd.cn"
|
||||
export DB_PORT="16159"
|
||||
export DB_USER="erp_pgsql"
|
||||
export DB_PASSWORD="erp_2025"
|
||||
export DB_NAME="junhong_cmp_test"
|
||||
export DB_SSLMODE="disable"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 短信服务配置
|
||||
# ----------------------------------------------------------------------------
|
||||
export JUNHONG_SMS_GATEWAY_URL="https://gateway.sms.whjhft.com:8443"
|
||||
export JUNHONG_SMS_USERNAME="JH0001"
|
||||
export JUNHONG_SMS_PASSWORD="wwR8E4qnL6F0"
|
||||
export JUNHONG_SMS_SIGNATURE="【JHFTIOT】"
|
||||
|
||||
JUNHONG_QUEUE_CONCURRENCY=1000
|
||||
236
.env.prod
236
.env.prod
@@ -1,236 +0,0 @@
|
||||
# ==========================================================================
|
||||
# 君鸿卡管系统 - 本地开发环境变量
|
||||
# 生成时间: 2026-05-07 11:56:19
|
||||
# 配置依据: pkg/config/defaults/config.yaml + pkg/config/loader.go
|
||||
# ==========================================================================
|
||||
# 使用方法:
|
||||
# source .env.prod && go run cmd/api/main.go
|
||||
# 或者:
|
||||
# ./scripts/run-local.sh
|
||||
#
|
||||
# 说明:
|
||||
# - 未注释的 是本地启动常用或必填配置。
|
||||
# - 注释掉的 是当前有默认值、按需启用或当前主流程未使用的配置。
|
||||
# - 取消注释前请先阅读上方说明,避免覆盖嵌入配置默认值。
|
||||
# ==========================================================================
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 数据库配置(必填)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 数据库主机地址;应用启动必填。
|
||||
export JUNHONG_DATABASE_HOST=cxd.whcxd.cn
|
||||
# 数据库端口;默认 5432。
|
||||
export JUNHONG_DATABASE_PORT=16159
|
||||
# 数据库用户名;应用启动必填。
|
||||
export JUNHONG_DATABASE_USER=junhong_cmp
|
||||
# 数据库密码;应用启动必填,敏感信息请勿提交。
|
||||
export JUNHONG_DATABASE_PASSWORD=CtCom1zBzPQbpVNf3rCNxH
|
||||
# 数据库名称;应用启动必填。
|
||||
export JUNHONG_DATABASE_DBNAME=junhong_cmp_prod
|
||||
# 数据库 SSL 模式;本地通常使用 disable。
|
||||
export JUNHONG_DATABASE_SSLMODE=disable
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Redis 配置(必填)
|
||||
# ----------------------------------------------------------------------------
|
||||
# Redis 主机地址;应用启动必填。
|
||||
export JUNHONG_REDIS_ADDRESS=192.168.1.22
|
||||
# Redis 端口;默认 6379。
|
||||
export JUNHONG_REDIS_PORT=6379
|
||||
# Redis 密码;无密码时留空。
|
||||
export JUNHONG_REDIS_PASSWORD=Bm500vXEyLg0RUzw7YcyPjbRifhz
|
||||
# Redis 数据库编号;默认 0。
|
||||
export JUNHONG_REDIS_DB=0
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# JWT 配置(必填)
|
||||
# ----------------------------------------------------------------------------
|
||||
# JWT 签名密钥;必须至少 32 字符,生产环境必须单独生成。
|
||||
export JUNHONG_JWT_SECRET_KEY=a0xzpGhR3zB54JAiEJtoKnjwgAGMLmRw
|
||||
# C 端 JWT Token 有效期;默认 24h,通常无需覆盖。
|
||||
export JUNHONG_JWT_TOKEN_DURATION=24h
|
||||
# B 端访问令牌 TTL;默认 24h。
|
||||
export JUNHONG_JWT_ACCESS_TOKEN_TTL=24h
|
||||
# B 端刷新令牌 TTL;默认 168h。
|
||||
export JUNHONG_JWT_REFRESH_TOKEN_TTL=168h
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 服务器配置
|
||||
# ----------------------------------------------------------------------------
|
||||
# 服务监听地址;本地默认 :3000。
|
||||
export JUNHONG_SERVER_ADDRESS=:3527
|
||||
# 读取请求超时时间;默认 30s,通常无需覆盖。
|
||||
export JUNHONG_SERVER_READ_TIMEOUT=30s
|
||||
# 写响应超时时间;默认 30s,通常无需覆盖。
|
||||
export JUNHONG_SERVER_WRITE_TIMEOUT=30s
|
||||
# 优雅关闭超时时间;默认 30s。
|
||||
export JUNHONG_SERVER_SHUTDOWN_TIMEOUT=30s
|
||||
# Fiber 预分叉模式;本地和 macOS 开发环境通常不要启用。
|
||||
# JUNHONG_SERVER_PREFORK=false
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 日志配置
|
||||
# ----------------------------------------------------------------------------
|
||||
# 日志级别;可选 debug/info/warn/error。
|
||||
export JUNHONG_LOGGING_LEVEL=debug
|
||||
# 本地开发模式日志;生产环境应使用 false。
|
||||
export JUNHONG_LOGGING_DEVELOPMENT=true
|
||||
# 应用日志文件路径;本地写入项目 logs 目录。
|
||||
export JUNHONG_LOGGING_APP_LOG_FILENAME=logs/app.log
|
||||
# 访问日志文件路径;本地写入项目 logs 目录。
|
||||
export JUNHONG_LOGGING_ACCESS_LOG_FILENAME=logs/access.log
|
||||
# 应用日志单文件最大大小(MB);默认 100。
|
||||
export JUNHONG_LOGGING_APP_LOG_MAX_SIZE=100
|
||||
# 应用日志最多保留的旧文件数;默认 3。
|
||||
export JUNHONG_LOGGING_APP_LOG_MAX_BACKUPS=15
|
||||
# 应用日志最多保留天数;默认 7。
|
||||
export JUNHONG_LOGGING_APP_LOG_MAX_AGE=14
|
||||
# 是否压缩应用日志轮转文件;默认 true。
|
||||
export JUNHONG_LOGGING_APP_LOG_COMPRESS=true
|
||||
# 访问日志单文件最大大小(MB);默认 100。
|
||||
export JUNHONG_LOGGING_ACCESS_LOG_MAX_SIZE=100
|
||||
# 访问日志最多保留的旧文件数;默认 3。
|
||||
export JUNHONG_LOGGING_ACCESS_LOG_MAX_BACKUPS=15
|
||||
# 访问日志最多保留天数;默认 7。
|
||||
export JUNHONG_LOGGING_ACCESS_LOG_MAX_AGE=14
|
||||
# 是否压缩访问日志轮转文件;默认 true。
|
||||
export JUNHONG_LOGGING_ACCESS_LOG_COMPRESS=true
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 客户端配置
|
||||
# ----------------------------------------------------------------------------
|
||||
# 是否强制 C 端用户绑定手机号;当前默认 true。
|
||||
export JUNHONG_CLIENT_REQUIRE_PHONE_BINDING=true
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 数据库连接池配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 数据库最大打开连接数;默认 25,本地通常不用改。
|
||||
export JUNHONG_DATABASE_MAX_OPEN_CONNS=25
|
||||
# 数据库最大空闲连接数;默认 10。
|
||||
export JUNHONG_DATABASE_MAX_IDLE_CONNS=10
|
||||
# 数据库连接最大生命周期;默认 5m。
|
||||
export JUNHONG_DATABASE_CONN_MAX_LIFETIME=5m
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Redis 连接池配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# Redis 连接池大小;默认 10。
|
||||
export JUNHONG_REDIS_POOL_SIZE=20
|
||||
# Redis 最小空闲连接数;默认 5。
|
||||
export JUNHONG_REDIS_MIN_IDLE_CONNS=5
|
||||
# Redis 建连超时;默认 5s。
|
||||
export JUNHONG_REDIS_DIAL_TIMEOUT=5s
|
||||
# Redis 读取超时;默认 3s。
|
||||
export JUNHONG_REDIS_READ_TIMEOUT=3s
|
||||
# Redis 写入超时;默认 3s。
|
||||
export JUNHONG_REDIS_WRITE_TIMEOUT=3s
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 任务队列配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# Worker 并发数;默认 10。
|
||||
# JUNHONG_QUEUE_CONCURRENCY=10
|
||||
# 任务最大重试次数;默认 5。
|
||||
# JUNHONG_QUEUE_RETRY_MAX=5
|
||||
# 单个任务超时时间;默认 10m。
|
||||
# JUNHONG_QUEUE_TIMEOUT=10m
|
||||
# 队列权重 critical/default/low 当前由嵌入配置 queue.queues 管理,未绑定为环境变量。
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 限流中间件配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 是否启用全局限流;默认关闭。
|
||||
# JUNHONG_MIDDLEWARE_ENABLE_RATE_LIMITER=false
|
||||
# 限流窗口内最大请求数;默认 100。
|
||||
# JUNHONG_MIDDLEWARE_RATE_LIMITER_MAX=100
|
||||
# 限流时间窗口;默认 1m。
|
||||
# JUNHONG_MIDDLEWARE_RATE_LIMITER_EXPIRATION=1m
|
||||
# 限流存储后端;可选 memory 或 redis。
|
||||
# JUNHONG_MIDDLEWARE_RATE_LIMITER_STORAGE=memory
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 轮询配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 是否输出轮询详细日志;默认 false,排查上游数据时再开启。
|
||||
export JUNHONG_POLLING_VERBOSE_LOG=true
|
||||
# 是否启用 C 端实名自动触发;默认 true。
|
||||
# JUNHONG_POLLING_AUTO_TRIGGER_ENABLE_AUTO_TRIGGER=true
|
||||
# 自动触发使用的系统用户 ID;生产建议改成专用平台账号。
|
||||
export JUNHONG_POLLING_AUTO_TRIGGER_AUTO_TRIGGER_SYSTEM_USER_ID=1
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Worker 运行配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# Worker 角色;单实例默认 all,多实例可用 leader/consumer。
|
||||
# JUNHONG_WORKER_ROLE=all
|
||||
# Worker 实例名称;多实例部署时用于区分日志。
|
||||
# JUNHONG_WORKER_INSTANCE_NAME=''
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Gateway 服务配置
|
||||
# ----------------------------------------------------------------------------
|
||||
# Gateway API 基础 URL;已按本次输入覆盖嵌入默认值。
|
||||
export JUNHONG_GATEWAY_BASE_URL=https://open.whjhft.com/openapi
|
||||
# Gateway 应用 ID;敏感信息请勿提交。
|
||||
export JUNHONG_GATEWAY_APP_ID=LfjL0WjUqpwkItQ0
|
||||
# Gateway 应用密钥;敏感信息请勿提交。
|
||||
export JUNHONG_GATEWAY_APP_SECRET=K0DYuWzbRE6zg5bX
|
||||
# Gateway 请求超时时间(秒);有效范围 5-300。
|
||||
export JUNHONG_GATEWAY_TIMEOUT=30
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 短信服务配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 短信服务未配置时系统会跳过短信客户端初始化;需要短信验证码时再取消注释。
|
||||
# 短信网关地址;设置后 username/password/signature 也必须填写。
|
||||
export JUNHONG_SMS_GATEWAY_URL='https://gateway.sms.whjhft.com:8443'
|
||||
# 短信账号用户名。
|
||||
export JUNHONG_SMS_USERNAME='JH0001'
|
||||
# 短信账号密码;敏感信息请勿提交。
|
||||
export JUNHONG_SMS_PASSWORD='wwR8E4qnL6F0'
|
||||
# 短信签名,例如【君鸿】。
|
||||
export JUNHONG_SMS_SIGNATURE='【JHFTIOT】'
|
||||
# 短信请求超时时间;默认 10s。
|
||||
export JUNHONG_SMS_TIMEOUT=10s
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 对象存储配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 对象存储提供商;当前仅支持 s3 兼容服务。
|
||||
export JUNHONG_STORAGE_PROVIDER=s3
|
||||
# 临时文件目录;用于导入导出等临时文件。
|
||||
export JUNHONG_STORAGE_TEMP_DIR=/tmp/junhong-storage
|
||||
# S3 端点;配置后会初始化对象存储服务。
|
||||
export JUNHONG_STORAGE_S3_ENDPOINT=https://obs-helf.cucloud.cn
|
||||
# S3 区域。
|
||||
export JUNHONG_STORAGE_S3_REGION=cn-langfang-2
|
||||
# S3 存储桶名称。
|
||||
export JUNHONG_STORAGE_S3_BUCKET=cmp
|
||||
# S3 Access Key ID;敏感信息请勿提交。
|
||||
export JUNHONG_STORAGE_S3_ACCESS_KEY_ID=598F558CF6FF46E79D1CFC607852378C9523
|
||||
# S3 Secret Access Key;敏感信息请勿提交。
|
||||
export JUNHONG_STORAGE_S3_SECRET_ACCESS_KEY=8393425DCB2F48F1914FF39DCBC6C7B17325
|
||||
# 是否使用 SSL;本地兼容服务常用 false。
|
||||
export JUNHONG_STORAGE_S3_USE_SSL=false
|
||||
# 是否使用路径风格;兼容 S3 服务通常使用 true。
|
||||
export JUNHONG_STORAGE_S3_PATH_STYLE=true
|
||||
# 预签名上传 URL 有效期;默认 15m。
|
||||
export JUNHONG_STORAGE_PRESIGN_UPLOAD_EXPIRES=15m
|
||||
# 预签名下载 URL 有效期;默认 24h。
|
||||
export JUNHONG_STORAGE_PRESIGN_DOWNLOAD_EXPIRES=24h
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 默认超级管理员配置(可选)
|
||||
# ----------------------------------------------------------------------------
|
||||
# 不配置时会使用 pkg/constants 中的默认超管账号;生产环境建议在首次启动前覆盖。
|
||||
# 默认超级管理员用户名;留空则使用代码内置默认值 admin。
|
||||
export JUNHONG_DEFAULT_ADMIN_USERNAME='admin'
|
||||
# 默认超级管理员密码;留空则使用代码内置默认值 Admin@123456。
|
||||
export JUNHONG_DEFAULT_ADMIN_PASSWORD='Admin@123456'
|
||||
# 默认超级管理员手机号;留空则使用代码内置默认值 13800000000。
|
||||
# JUNHONG_DEFAULT_ADMIN_PHONE=''
|
||||
|
||||
export JUNHONG_MIDDLEWARE_CORS_ENABLED=true
|
||||
export JUNHONG_MIDDLEWARE_CORS_ALLOW_ORIGINS=https://cmp-admin.xm-iot.cn,https://cmp-agent.xm-iot.cn,https://cmp-c.xm-iot.cn
|
||||
export JUNHONG_MIDDLEWARE_CORS_ALLOW_CREDENTIALS=true
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -26,6 +26,8 @@ vendor/
|
||||
.cache/
|
||||
|
||||
# Environment variables
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Log files
|
||||
@@ -73,6 +75,7 @@ __debug_bin1621385388
|
||||
docs/admin-openapi.yaml
|
||||
/api
|
||||
/gendocs
|
||||
.env.local
|
||||
/worker
|
||||
.opencode/skills/json-canvas
|
||||
.opencode/skills/obsidian-bases
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
# PRD:IoT 卡风险状态限制 / 导入任务操作人与批量失效 / 凭证多图 / 预充值备注
|
||||
|
||||
Status: ready-for-agent
|
||||
|
||||
---
|
||||
|
||||
## Problem Statement
|
||||
|
||||
运营团队在日常工作中遇到四个独立痛点:
|
||||
|
||||
1. **风险停机/已销户卡无法有效拦截**:运营商侧将某些卡置为"风险停机"或"已销户"状态后,系统仍允许对这些卡发起复机操作,且轮询系统仍持续轮询这些卡,浪费资源并可能产生错误数据。
|
||||
|
||||
2. **导入任务无操作人信息**:IoT 卡导入任务和设备导入任务的列表中没有"操作人"字段,无法追溯是谁发起的批量操作。同时缺少批量失效订单套餐的操作入口,运营只能逐条手动处理。
|
||||
|
||||
3. **凭证只能上传一张**:后台创建订单和发起退款时,只允许上传一张凭证图片,无法满足多张凭证的业务场景(如多笔转账记录、多页合同等)。
|
||||
|
||||
4. **代理预充值缺少备注字段**:代理预充值操作无法附加运营备注,导致事后无法追溯充值的业务原因。
|
||||
|
||||
---
|
||||
|
||||
## Solution
|
||||
|
||||
1. 在复机接口和轮询系统中增加对 `gateway_extend` 字段的检查,当独立卡处于"风险停机"或"已销户"状态时,拒绝复机并停止轮询。
|
||||
|
||||
2. 在所有导入任务中快照操作人姓名;新增"批量失效订单套餐"导入任务,支持通过 CSV 批量将订单下的套餐置为失效状态。
|
||||
|
||||
3. 将订单、退款、代理预充值的凭证字段改为支持最多5张的 jsonb 数组存储。
|
||||
|
||||
4. 在代理预充值记录上新增 `remark` 备注字段,供运营创建时填写,并在列表/详情接口中返回。
|
||||
|
||||
---
|
||||
|
||||
## User Stories
|
||||
|
||||
1. 作为运营人员,当我尝试对"风险停机"状态的独立卡发起复机时,我希望系统拒绝并提示原因,以免产生无效操作。
|
||||
2. 作为运营人员,当我尝试对"已销户"状态的独立卡发起复机时,我希望系统拒绝并提示原因,以免对已注销的卡发起无意义请求。
|
||||
3. 作为运营人员,我希望"风险停机"和"已销户"的独立卡不再参与系统轮询,以免浪费轮询资源并产生噪音数据。
|
||||
4. 作为运营人员,当轮询系统检测到某张独立卡的网关状态变为"风险停机"或"已销户"时,我希望系统自动将该卡的轮询关闭,而不需要手动干预。
|
||||
5. 作为运营人员,我希望在 IoT 卡导入任务列表中看到"操作人"姓名,以便追溯每次批量导入是谁发起的。
|
||||
6. 作为运营人员,我希望在设备导入任务列表中看到"操作人"姓名,以便追溯每次批量导入是谁发起的。
|
||||
7. 作为运营人员,我希望通过上传 CSV 文件批量将一批订单的套餐置为失效,以便快速处理异常订单。
|
||||
8. 作为运营人员,我希望在创建批量失效任务时能填写备注和上传凭证(最多5张),以便记录操作原因。
|
||||
9. 作为运营人员,我希望批量失效任务完成后能看到成功数、失败数,以及失败原因(如订单号不存在),以便核查处理结果。
|
||||
10. 作为运营人员,我希望批量失效套餐只影响套餐记录本身,不触发退款和其他业务流程,让轮询系统自行根据套餐状态处理停机。
|
||||
11. 作为运营人员,我希望在创建后台订单时可以上传最多5张凭证,以便完整记录线下付款证明。
|
||||
12. 作为运营人员,我希望在发起退款申请时可以上传最多5张凭证,以便完整记录退款证明材料。
|
||||
13. 作为运营人员,我希望在代理预充值列表中看到备注内容,以便了解每笔预充值的业务背景。
|
||||
14. 作为运营人员,我希望在创建代理预充值订单时填写备注,以便记录本次充值的原因或说明。
|
||||
15. 作为开放 API 调用方,当我通过 Open API 对"风险停机"或"已销户"的独立卡调用复机接口时,我希望收到明确的错误响应。
|
||||
|
||||
---
|
||||
|
||||
## Implementation Decisions
|
||||
|
||||
### 需求一:风险停机/已销户卡限制
|
||||
|
||||
- **判断字段**:`tb_iot_card.gateway_extend` 原文值 = `"风险停机"` 或 `"已销户"`。新增两个常量 `GatewayCardExtendRiskStop`、`GatewayCardExtendCancelled`。
|
||||
- **判断范围**:仅 `is_standalone = true` 的独立卡(未绑定设备的卡)。绑定设备的卡不受此限制。
|
||||
- **复机拦截**:在 `ManualStartCard`(后台管理员入口)和 `ResumeCard`(Open API 入口)两个函数中,调用网关前先读取 DB 中已落库的 `gateway_extend`,若命中则返回业务错误,不实时查询网关。
|
||||
- **轮询停止**:轮询状态处理器(`PollingCardStatusHandler`)在将新的 `gateway_extend` 写入 DB 后,检查若命中风险状态且 `is_standalone=true`,则调用现有的 `UpdatePollingStatus(false)` 将 `enable_polling` 写为 `false`,并跳过 `requeueCard`,终止该卡的轮询循环。
|
||||
- **错误码**:复机被拒绝时返回业务错误,提示信息明确说明原因("风险停机"/"已销户")。
|
||||
|
||||
### 需求二:导入任务操作人与批量失效
|
||||
|
||||
**操作人快照:**
|
||||
- `tb_iot_card_import_task` 和 `tb_device_import_task` 表各新增 `creator_name varchar` 字段。
|
||||
- 新的批量失效任务表同样包含此字段。
|
||||
- 创建任务时从当前登录用户快照姓名写入,旧数据留空(不回填)。
|
||||
- 列表响应 DTO 新增 `creator_name` 字段。
|
||||
|
||||
**批量失效订单套餐任务:**
|
||||
- 新建模型、Store、Service、Handler,参照现有 IoT 卡导入任务的结构(CSV 上传 → 异步任务处理)。
|
||||
- CSV 格式:单列 `order_no`(无表头行约定沿用现有导入任务的处理方式)。
|
||||
- 创建接口额外支持:`remark`(字符串备注)和最多5张凭证(jsonb 存储)。
|
||||
- 处理逻辑:按行读取 `order_no` → 查询 `Order` → 找到 `PackageUsage WHERE order_id = ? AND status NOT IN (3, 4)` → 批量更新 `status = 4`(已失效)。
|
||||
- 订单不存在:记为失败(fail),继续处理后续行。
|
||||
- 订单存在但旗下套餐全部已是终态(status 3 或 4):记为成功(success)。
|
||||
- 不触发退款,不直接操作 IoT 卡停机,由轮询系统根据套餐状态自行评估。
|
||||
- 任务表命名:`tb_order_package_invalidate_task`。
|
||||
|
||||
### 需求三:凭证多图改造
|
||||
|
||||
- `tb_order.payment_voucher_key`(varchar 500)→ `jsonb`,存储 `[]string`,最多5个元素。
|
||||
- `tb_refund.refund_voucher_key`(varchar 500)→ `jsonb`,存储 `[]string`,最多5个元素。
|
||||
- `tb_agent_recharge_record.payment_voucher_key`(varchar 500)→ `jsonb`,存储 `[]string`,最多5个元素。
|
||||
- **数据迁移**(同一 Migration 语句):非空旧值 `"some_key"` → `["some_key"]`;空字符串 → `[]`。生产环境由运营手动执行 Migration。
|
||||
- 所有涉及凭证的请求 DTO 字段由 `string` 改为 `[]string`,validate 标签限制 `max=5`,每项 `max=500`。
|
||||
- 所有涉及凭证的响应 DTO 字段改为 `[]string`。
|
||||
- 不限制文件类型(上传 URL 获取接口层面不变,仅存储 key 列表)。
|
||||
|
||||
### 需求四:代理预充值备注
|
||||
|
||||
- `tb_agent_recharge_record` 新增 `remark text` 字段(可为空)。
|
||||
- `CreateAgentRechargeRequest` 新增 `remark` 字段(`omitempty`,无最大长度强限制,建议 1000 字符内)。
|
||||
- `AgentRechargeResponse` 新增 `remark` 字段(列表和详情接口均返回)。
|
||||
- 创建后不可修改,无需新增修改接口。
|
||||
|
||||
---
|
||||
|
||||
## Testing Decisions
|
||||
|
||||
本项目禁止自动化测试。验证方式:
|
||||
|
||||
- **PostgreSQL MCP**:核查 `tb_iot_card.enable_polling` 在风险状态卡被轮询后是否正确置为 `false`;核查 `tb_package_usage.status` 在批量失效任务执行后是否按预期更新;核查 jsonb 字段迁移结果。
|
||||
- **curl / Postman**:对风险停机卡调用复机接口,验证返回正确错误码;上传多张凭证创建订单,验证存储和返回正确;创建代理预充值时附带备注,验证列表返回。
|
||||
|
||||
---
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- 已绑定设备的卡(`is_standalone=false`)不受"风险停机/已销户"限制约束。
|
||||
- 批量失效订单套餐不触发退款流程。
|
||||
- 批量失效不直接调用网关停机,依赖轮询系统自行评估。
|
||||
- 历史导入任务的 `creator_name` 不回填。
|
||||
- 凭证文件类型校验(文件类型限制不在本次范围内)。
|
||||
- 代理预充值备注创建后不可修改(无修改接口)。
|
||||
|
||||
---
|
||||
|
||||
## Further Notes
|
||||
|
||||
- 凭证字段改为 jsonb 后,前端需同步更新上传组件支持多选;本 PRD 只覆盖后端改造。
|
||||
- 批量失效任务的凭证和备注字段,与代理预充值备注字段、以及需求三的多凭证设计保持一致的数据形态,便于后续统一处理。
|
||||
- "风险停机"和"已销户"的 `gateway_extend` 原文值来自上游网关,若上游修改返回值需同步更新常量。
|
||||
@@ -1,28 +0,0 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
新增两个 gateway_extend 常量(`GatewayCardExtendRiskStop = "风险停机"`、`GatewayCardExtendCancelled = "已销户"`),然后在后台复机入口(`ManualStartCard`)和 Open API 复机入口(`ResumeCard`)中增加前置拦截:
|
||||
|
||||
- 仅对 `is_standalone = true` 的独立卡生效
|
||||
- 读取 DB 中已落库的 `gateway_extend` 字段(不实时查网关)
|
||||
- 若命中 `"风险停机"` 或 `"已销户"`,立即返回业务错误,不再继续调用网关
|
||||
- 错误提示需明确说明被拒绝的原因(如"该卡已被运营商风险停机,不允许复机")
|
||||
|
||||
无 Schema 变更,不需要 Migration。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] `pkg/constants/iot.go` 新增 `GatewayCardExtendRiskStop`、`GatewayCardExtendCancelled` 两个常量
|
||||
- [ ] 后台 `ManualStartCard` 在调用网关前检查独立卡 `gateway_extend`,命中风险值时返回业务错误
|
||||
- [ ] Open API `ResumeCard` 在调用网关前检查独立卡 `gateway_extend`,命中风险值时返回业务错误
|
||||
- [ ] 已绑定设备的卡(`is_standalone = false`)不受此限制,复机正常进行
|
||||
- [ ] 返回的错误信息能区分"风险停机"和"已销户"两种情况
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - can start immediately
|
||||
@@ -1,28 +0,0 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
在 `PollingCardStatusHandler` 中,当轮询查询网关后将新的 `gateway_extend` 写入 DB,若新值命中风险常量(`GatewayCardExtendRiskStop` 或 `GatewayCardExtendCancelled`)且该卡 `is_standalone = true`,则:
|
||||
|
||||
1. 调用现有的 `UpdatePollingStatus(false)` 将 `enable_polling` 写为 `false`
|
||||
2. 跳过末尾的 `requeueCard`,终止该卡的轮询循环
|
||||
|
||||
检查时机:在 `UpdateFields` 写入 `gateway_extend` 成功之后,`requeueCard` 调用之前。
|
||||
|
||||
不需要 Schema 变更,不需要 Migration。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] 轮询处理器在写入 `gateway_extend` 后检查风险状态
|
||||
- [ ] 独立卡(`is_standalone=true`)命中风险值时调用 `UpdatePollingStatus(false)`,`tb_iot_card.enable_polling` 被置为 `false`
|
||||
- [ ] 该卡不再入队(不调用 `requeueCard`),轮询循环终止
|
||||
- [ ] 已绑定设备的卡(`is_standalone=false`)命中风险值时不触发此逻辑,轮询正常继续
|
||||
- [ ] 可通过 PostgreSQL MCP 验证:风险状态卡处理后 `enable_polling = false`
|
||||
|
||||
## Blocked by
|
||||
|
||||
- `issues/01-risk-resume-block.md`(依赖 `GatewayCardExtendRiskStop`、`GatewayCardExtendCancelled` 常量)
|
||||
@@ -1,30 +0,0 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
在现有两个导入任务表中新增操作人快照字段,并在列表接口返回:
|
||||
|
||||
- `tb_iot_card_import_task` 新增 `creator_name varchar(100)` 字段
|
||||
- `tb_device_import_task` 新增 `creator_name varchar(100)` 字段
|
||||
- 创建任务时从当前登录用户快照姓名写入(不可为 null,旧数据留空字符串)
|
||||
- IoT 卡导入任务列表响应 DTO 新增 `creator_name` 字段
|
||||
- 设备导入任务列表响应 DTO 新增 `creator_name` 字段
|
||||
|
||||
历史数据不回填,旧记录 `creator_name` 为空字符串。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Migration 为两个现有任务表各添加 `creator_name varchar(100) not null default ''` 字段
|
||||
- [ ] IoT 卡导入任务创建时写入当前用户姓名快照
|
||||
- [ ] 设备导入任务创建时写入当前用户姓名快照
|
||||
- [ ] IoT 卡导入任务列表接口返回 `creator_name` 字段
|
||||
- [ ] 设备导入任务列表接口返回 `creator_name` 字段
|
||||
- [ ] 旧记录 `creator_name` 为空字符串,不报错
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - can start immediately
|
||||
@@ -1,43 +0,0 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
新增"批量失效订单套餐"导入任务,完整实现 Model → Store → Service → Handler → Route → Worker 全链路,参照现有 IoT 卡导入任务的结构。
|
||||
|
||||
**数据模型**(新建 `tb_order_package_invalidate_task`):
|
||||
- 参照 `tb_iot_card_import_task` 的基础字段(任务编号、状态、计数、失败/跳过明细、文件存储 key、时间戳等)
|
||||
- 额外字段:`creator_name varchar(100)`、`remark text`、`voucher_keys jsonb`(存储 `[]string`,最多5个元素)
|
||||
|
||||
**上传接口**(创建任务):
|
||||
- 接受 CSV 文件(单列 `order_no`)
|
||||
- 额外参数:`remark`(字符串,可选)和 `voucher_keys`(`[]string`,最多5个,可选)
|
||||
- 写入 `creator_name` 快照
|
||||
|
||||
**Worker 处理逻辑**:
|
||||
- 逐行读取 `order_no`
|
||||
- 按 `order_no` 查询 `tb_order` 获取 `order_id`;找不到则记为失败,继续处理
|
||||
- 查询 `tb_package_usage WHERE order_id = ? AND status NOT IN (3, 4)`,批量更新 `status = 4`(已失效)
|
||||
- 订单存在但套餐全部已是终态(status 3 或 4):记为成功
|
||||
- 不触发退款,不调用网关,不直接停机
|
||||
|
||||
**列表/详情接口**:参照现有导入任务接口结构。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Migration 创建 `tb_order_package_invalidate_task` 表,包含所有必要字段
|
||||
- [ ] 创建任务接口:接受 CSV + remark + voucher_keys(最多5个),写入 creator_name 快照
|
||||
- [ ] Worker 按行处理:`order_no` 不存在 → 失败并记录原因,继续下一行
|
||||
- [ ] Worker 按行处理:订单存在且有可失效套餐 → 批量更新 `status=4` → 记为成功
|
||||
- [ ] Worker 按行处理:订单存在但套餐全为终态 → 记为成功
|
||||
- [ ] 处理过程中不调用退款接口、不操作网关
|
||||
- [ ] 列表接口返回 `creator_name`、`remark`、任务状态和计数
|
||||
- [ ] 详情接口返回失败明细(含 order_no 和原因)
|
||||
- [ ] 已在路由和文档生成器中注册
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - can start immediately
|
||||
@@ -1,36 +0,0 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
一次 Migration 完成三个现有表的凭证字段类型变更,并同时新增代理预充值备注字段:
|
||||
|
||||
**字段类型变更**(varchar(500) → jsonb):
|
||||
- `tb_order.payment_voucher_key`
|
||||
- `tb_refund.refund_voucher_key`
|
||||
- `tb_agent_recharge_record.payment_voucher_key`
|
||||
|
||||
**数据转换规则**(在同一 Migration 的 USING 子句中完成):
|
||||
- 非空旧值 `"some_key"` → `["some_key"]`
|
||||
- 空字符串 `""` → `[]`
|
||||
- NULL → `[]`
|
||||
|
||||
**新增字段**:
|
||||
- `tb_agent_recharge_record.remark text`(可为空,默认 null)
|
||||
|
||||
生产环境由运营手动执行,Migration 文件需包含完整的 UP 和 DOWN 语句。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Migration UP:三个凭证字段成功从 varchar 转为 jsonb,历史单值数据转换为单元素数组
|
||||
- [ ] Migration UP:空字符串/NULL 转换为空数组 `[]`
|
||||
- [ ] Migration UP:`tb_agent_recharge_record` 新增 `remark text` 字段
|
||||
- [ ] Migration DOWN:可回滚(jsonb → varchar,取数组第一个元素;remark 字段删除)
|
||||
- [ ] 迁移后可用 PostgreSQL MCP 验证数据格式正确
|
||||
|
||||
## Blocked by
|
||||
|
||||
None - can start immediately
|
||||
@@ -1,27 +0,0 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
将后台创建订单接口的凭证字段从单个字符串改为最多5个字符串的列表:
|
||||
|
||||
- `CreateAdminOrderRequest.payment_voucher_key`:`string` → `[]string`,validate 限制 `max=5`,每项 `max=500`
|
||||
- `OrderResponse.payment_voucher_key`(以及所有订单相关响应 DTO):`string` → `[]string`
|
||||
- Order Model 的 `PaymentVoucherKey` 字段类型改为适配 jsonb 的 `pq.StringArray` 或自定义 JSON 类型
|
||||
- Order Service 中读写 `payment_voucher_key` 的逻辑同步更新
|
||||
|
||||
Schema 变更已由 `issues/05-voucher-multi-migration.md` 完成。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] 后台创建订单接口接受 `payment_voucher_key []string`(0-5个元素),offline 支付时至少需要1个
|
||||
- [ ] 订单列表/详情接口返回 `payment_voucher_key []string`
|
||||
- [ ] 传入超过5个凭证 key 时返回参数校验错误
|
||||
- [ ] 现有无凭证的订单(wallet 支付)返回空数组,不报错
|
||||
|
||||
## Blocked by
|
||||
|
||||
- `issues/05-voucher-multi-migration.md`
|
||||
@@ -1,29 +0,0 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
将退款申请接口的凭证字段从单个字符串改为最多5个字符串的列表:
|
||||
|
||||
- `CreateRefundRequest.refund_voucher_key`:`string` → `[]string`,validate 限制 `max=5`,每项 `max=500`,required(至少1个)
|
||||
- `ResubmitRefundRequest.refund_voucher_key`:`*string` → `*[]string`(重新提交时可选替换)
|
||||
- `RefundResponse.refund_voucher_key`(以及所有退款相关响应 DTO):`string` → `[]string`
|
||||
- Refund Model 的 `RefundVoucherKey` 字段类型改为适配 jsonb 的类型
|
||||
- Refund Service 中读写 `refund_voucher_key` 的逻辑同步更新
|
||||
|
||||
Schema 变更已由 `issues/05-voucher-multi-migration.md` 完成。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] 创建退款申请接口接受 `refund_voucher_key []string`(1-5个元素,必填)
|
||||
- [ ] 重新提交退款接口的 `refund_voucher_key` 可选,传入时替换全部凭证
|
||||
- [ ] 退款列表/详情接口返回 `refund_voucher_key []string`
|
||||
- [ ] 传入超过5个凭证 key 时返回参数校验错误
|
||||
- [ ] 传入空数组时返回参数校验错误(至少需要1个)
|
||||
|
||||
## Blocked by
|
||||
|
||||
- `issues/05-voucher-multi-migration.md`
|
||||
@@ -1,35 +0,0 @@
|
||||
Status: done
|
||||
|
||||
## Parent
|
||||
|
||||
`.scratch/iot-risk-import-voucher-remark/PRD.md`
|
||||
|
||||
## What to build
|
||||
|
||||
同时完成代理预充值的凭证多图改造和备注字段接入:
|
||||
|
||||
**凭证多图**:
|
||||
- `CreateAgentRechargeRequest.payment_voucher_key`:`string` → `[]string`,validate 限制 `max=5`,每项 `max=500`(offline 支付时至少1个,微信支付时忽略)
|
||||
- `AgentRechargeResponse.payment_voucher_key`:`string` → `[]string`
|
||||
- `AgentRechargeRecord.PaymentVoucherKey` Model 字段类型改为适配 jsonb 的类型
|
||||
|
||||
**备注字段**:
|
||||
- `CreateAgentRechargeRequest` 新增 `remark string`(可选,建议不超过1000字符)
|
||||
- `AgentRechargeResponse` 新增 `remark string`(列表和详情接口均返回)
|
||||
- `AgentRechargeRecord.Remark` 在创建时写入,后续不可修改
|
||||
|
||||
AgentRecharge Service 中读写相关字段的逻辑同步更新。
|
||||
|
||||
Schema 变更(payment_voucher_key 类型 + remark 字段)已由 `issues/05-voucher-multi-migration.md` 完成。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] 创建代理预充值接口接受 `payment_voucher_key []string`(offline 时至少1个)和可选 `remark`
|
||||
- [ ] 代理预充值列表/详情接口返回 `payment_voucher_key []string` 和 `remark`
|
||||
- [ ] 传入超过5个凭证 key 时返回参数校验错误
|
||||
- [ ] 不新增 remark 修改接口,创建后备注字段只读
|
||||
- [ ] 微信支付创建预充值时可不传凭证(与现有逻辑一致)
|
||||
|
||||
## Blocked by
|
||||
|
||||
- `issues/05-voucher-multi-migration.md`
|
||||
@@ -139,8 +139,7 @@ func initHandlers(svc *services, deps *Dependencies) *Handlers {
|
||||
}(),
|
||||
WechatConfig: admin.NewWechatConfigHandler(svc.WechatConfig),
|
||||
AgentRecharge: admin.NewAgentRechargeHandler(svc.AgentRecharge, validate),
|
||||
Refund: admin.NewRefundHandler(svc.Refund),
|
||||
OrderPackageInvalidate: admin.NewOrderPackageInvalidateHandler(svc.OrderPackageInvalidate),
|
||||
Refund: admin.NewRefundHandler(svc.Refund),
|
||||
ClientWechat: app.NewClientWechatHandler(svc.WechatConfig, deps.Redis, deps.Logger),
|
||||
SuperAdmin: admin.NewSuperAdminHandler(svc.OperationPassword),
|
||||
AgentOpenAPI: openapiHandler.NewHandler(svc.AgentOpenAPI, validate),
|
||||
|
||||
@@ -46,7 +46,6 @@ import (
|
||||
|
||||
agentRechargeSvc "github.com/break/junhong_cmp_fiber/internal/service/agent_recharge"
|
||||
operationPasswordSvc "github.com/break/junhong_cmp_fiber/internal/service/operation_password"
|
||||
orderPackageInvalidateSvc "github.com/break/junhong_cmp_fiber/internal/service/order_package_invalidate"
|
||||
pollingSvc "github.com/break/junhong_cmp_fiber/internal/service/polling"
|
||||
refundSvc "github.com/break/junhong_cmp_fiber/internal/service/refund"
|
||||
shopCommissionSvc "github.com/break/junhong_cmp_fiber/internal/service/shop_commission"
|
||||
@@ -112,7 +111,6 @@ type services struct {
|
||||
OperationPassword *operationPasswordSvc.Service
|
||||
AgentOpenAPI *agentOpenAPISvc.Service
|
||||
CustomerBinding *customerBindingSvc.Service
|
||||
OrderPackageInvalidate *orderPackageInvalidateSvc.Service
|
||||
}
|
||||
|
||||
func initServices(s *stores, deps *Dependencies) *services {
|
||||
@@ -315,7 +313,6 @@ func initServices(s *stores, deps *Dependencies) *services {
|
||||
s.AssetWallet,
|
||||
deps.Logger,
|
||||
),
|
||||
CustomerBinding: customerBinding,
|
||||
OrderPackageInvalidate: orderPackageInvalidateSvc.New(s.OrderPackageInvalidateTask, deps.QueueClient),
|
||||
CustomerBinding: customerBinding,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,8 +66,6 @@ type stores struct {
|
||||
WechatConfig *postgres.WechatConfigStore
|
||||
// 退款系统
|
||||
RefundRequest *postgres.RefundStore
|
||||
// 订单套餐失效任务
|
||||
OrderPackageInvalidateTask *postgres.OrderPackageInvalidateTaskStore
|
||||
// 流量系统
|
||||
CardDailyUsage *postgres.CardDailyUsageStore
|
||||
// 资产标识符注册表
|
||||
@@ -133,9 +131,8 @@ func initStores(deps *Dependencies) *stores {
|
||||
RechargeOrder: postgres.NewRechargeOrderStore(deps.DB, deps.Redis),
|
||||
Payment: postgres.NewPaymentStore(deps.DB, deps.Redis),
|
||||
WechatConfig: postgres.NewWechatConfigStore(deps.DB, deps.Redis),
|
||||
RefundRequest: postgres.NewRefundStore(deps.DB),
|
||||
CardDailyUsage: postgres.NewCardDailyUsageStore(deps.DB),
|
||||
AssetIdentifier: postgres.NewAssetIdentifierStore(deps.DB),
|
||||
OrderPackageInvalidateTask: postgres.NewOrderPackageInvalidateTaskStore(deps.DB),
|
||||
RefundRequest: postgres.NewRefundStore(deps.DB),
|
||||
CardDailyUsage: postgres.NewCardDailyUsageStore(deps.DB),
|
||||
AssetIdentifier: postgres.NewAssetIdentifierStore(deps.DB),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,7 +63,6 @@ type Handlers struct {
|
||||
WechatConfig *admin.WechatConfigHandler
|
||||
AgentRecharge *admin.AgentRechargeHandler
|
||||
Refund *admin.RefundHandler
|
||||
OrderPackageInvalidate *admin.OrderPackageInvalidateHandler
|
||||
ClientWechat *app.ClientWechatHandler
|
||||
SuperAdmin *admin.SuperAdminHandler
|
||||
AgentOpenAPI *openapiHandler.Handler
|
||||
|
||||
@@ -33,9 +33,8 @@ type workerStores struct {
|
||||
AgentWalletTransaction *postgres.AgentWalletTransactionStore
|
||||
AssetWallet *postgres.AssetWalletStore
|
||||
AssetIdentifier *postgres.AssetIdentifierStore
|
||||
PersonalCustomer *postgres.PersonalCustomerStore
|
||||
PersonalCustomerPhone *postgres.PersonalCustomerPhoneStore
|
||||
OrderPackageInvalidateTask *postgres.OrderPackageInvalidateTaskStore
|
||||
PersonalCustomer *postgres.PersonalCustomerStore
|
||||
PersonalCustomerPhone *postgres.PersonalCustomerPhoneStore
|
||||
}
|
||||
|
||||
func initWorkerStores(deps *WorkerDependencies) *queue.WorkerStores {
|
||||
@@ -67,9 +66,8 @@ func initWorkerStores(deps *WorkerDependencies) *queue.WorkerStores {
|
||||
AgentWalletTransaction: postgres.NewAgentWalletTransactionStore(deps.DB, deps.Redis),
|
||||
AssetWallet: postgres.NewAssetWalletStore(deps.DB, deps.Redis),
|
||||
AssetIdentifier: postgres.NewAssetIdentifierStore(deps.DB),
|
||||
PersonalCustomer: postgres.NewPersonalCustomerStore(deps.DB, deps.Redis),
|
||||
PersonalCustomerPhone: postgres.NewPersonalCustomerPhoneStore(deps.DB),
|
||||
OrderPackageInvalidateTask: postgres.NewOrderPackageInvalidateTaskStore(deps.DB),
|
||||
PersonalCustomer: postgres.NewPersonalCustomerStore(deps.DB, deps.Redis),
|
||||
PersonalCustomerPhone: postgres.NewPersonalCustomerPhoneStore(deps.DB),
|
||||
}
|
||||
|
||||
return &queue.WorkerStores{
|
||||
@@ -100,8 +98,7 @@ func initWorkerStores(deps *WorkerDependencies) *queue.WorkerStores {
|
||||
AgentWalletTransaction: stores.AgentWalletTransaction,
|
||||
AssetWallet: stores.AssetWallet,
|
||||
AssetIdentifier: stores.AssetIdentifier,
|
||||
PersonalCustomer: stores.PersonalCustomer,
|
||||
PersonalCustomerPhone: stores.PersonalCustomerPhone,
|
||||
OrderPackageInvalidateTask: stores.OrderPackageInvalidateTask,
|
||||
PersonalCustomer: stores.PersonalCustomer,
|
||||
PersonalCustomerPhone: stores.PersonalCustomerPhone,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,29 +74,6 @@ func (h *AgentRechargeHandler) Get(c *fiber.Ctx) error {
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// Reject 驳回代理充值订单
|
||||
// POST /api/admin/agent-recharges/:id/reject
|
||||
func (h *AgentRechargeHandler) Reject(c *fiber.Ctx) error {
|
||||
id, err := strconv.ParseUint(c.Params("id"), 10, 64)
|
||||
if err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "无效的充值记录ID")
|
||||
}
|
||||
|
||||
var req dto.AgentRechargeRejectRequest
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
|
||||
}
|
||||
if err := h.validator.Struct(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam)
|
||||
}
|
||||
|
||||
if err := h.service.Reject(c.UserContext(), uint(id), req.RejectionReason); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.Success(c, nil)
|
||||
}
|
||||
|
||||
// OfflinePay 确认线下充值
|
||||
// POST /api/admin/agent-recharges/:id/offline-pay
|
||||
func (h *AgentRechargeHandler) OfflinePay(c *fiber.Ctx) error {
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
invalidateSvc "github.com/break/junhong_cmp_fiber/internal/service/order_package_invalidate"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/response"
|
||||
)
|
||||
|
||||
// OrderPackageInvalidateHandler 订单套餐批量失效任务 Handler
|
||||
type OrderPackageInvalidateHandler struct {
|
||||
service *invalidateSvc.Service
|
||||
}
|
||||
|
||||
// NewOrderPackageInvalidateHandler 创建 Handler 实例
|
||||
func NewOrderPackageInvalidateHandler(service *invalidateSvc.Service) *OrderPackageInvalidateHandler {
|
||||
return &OrderPackageInvalidateHandler{service: service}
|
||||
}
|
||||
|
||||
// Create 创建批量失效订单套餐任务
|
||||
// POST /api/admin/order-package-invalidate-tasks
|
||||
func (h *OrderPackageInvalidateHandler) Create(c *fiber.Ctx) error {
|
||||
userType := middleware.GetUserTypeFromContext(c.UserContext())
|
||||
if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
|
||||
return errors.New(errors.CodeForbidden, "仅平台用户可创建套餐失效任务")
|
||||
}
|
||||
|
||||
var req dto.CreateOrderPackageInvalidateTaskRequest
|
||||
if err := c.BodyParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
|
||||
}
|
||||
|
||||
if req.FileKey == "" {
|
||||
return errors.New(errors.CodeInvalidParam, "文件路径不能为空")
|
||||
}
|
||||
|
||||
result, err := h.service.Create(c.UserContext(), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.Success(c, result)
|
||||
}
|
||||
|
||||
// List 查询批量失效任务列表
|
||||
// GET /api/admin/order-package-invalidate-tasks
|
||||
func (h *OrderPackageInvalidateHandler) List(c *fiber.Ctx) error {
|
||||
userType := middleware.GetUserTypeFromContext(c.UserContext())
|
||||
if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
|
||||
return errors.New(errors.CodeForbidden, "仅平台用户可查看套餐失效任务")
|
||||
}
|
||||
|
||||
var req dto.ListOrderPackageInvalidateTaskRequest
|
||||
if err := c.QueryParser(&req); err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
|
||||
}
|
||||
|
||||
result, err := h.service.List(c.UserContext(), &req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.SuccessWithPagination(c, result.List, result.Total, result.Page, result.PageSize)
|
||||
}
|
||||
|
||||
// GetByID 查询批量失效任务详情
|
||||
// GET /api/admin/order-package-invalidate-tasks/:id
|
||||
func (h *OrderPackageInvalidateHandler) GetByID(c *fiber.Ctx) error {
|
||||
userType := middleware.GetUserTypeFromContext(c.UserContext())
|
||||
if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
|
||||
return errors.New(errors.CodeForbidden, "仅平台用户可查看套餐失效任务详情")
|
||||
}
|
||||
|
||||
idStr := c.Params("id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 64)
|
||||
if err != nil {
|
||||
return errors.New(errors.CodeInvalidParam, "无效的任务ID")
|
||||
}
|
||||
|
||||
result, err := h.service.GetByID(c.UserContext(), uint(id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return response.Success(c, result)
|
||||
}
|
||||
@@ -82,9 +82,7 @@ type AgentRechargeRecord struct {
|
||||
PaymentTransactionID *string `gorm:"column:payment_transaction_id;type:varchar(100);comment:第三方支付交易号" json:"payment_transaction_id,omitempty"`
|
||||
PaymentConfigID *uint `gorm:"column:payment_config_id;index;comment:支付配置ID(关联tb_wechat_config.id)" json:"payment_config_id,omitempty"`
|
||||
Status int `gorm:"column:status;type:int;not null;default:1;comment:充值状态(1-待支付 2-已支付 3-已完成 4-已关闭 5-已退款)" json:"status"`
|
||||
PaymentVoucherKey StringJSONBArray `gorm:"column:payment_voucher_key;type:jsonb;comment:支付凭证对象存储Key列表(线下支付时必填,最多5个,微信支付时为空)" json:"payment_voucher_key"`
|
||||
Remark string `gorm:"column:remark;type:text;comment:运营备注(创建时填写,不可修改)" json:"remark,omitempty"`
|
||||
RejectionReason *string `gorm:"column:rejection_reason;type:varchar(500);comment:驳回原因,仅驳回时写入" json:"rejection_reason,omitempty"`
|
||||
PaymentVoucherKey string `gorm:"column:payment_voucher_key;type:varchar(500);comment:支付凭证对象存储Key(线下支付时必填,微信支付时为空)" json:"payment_voucher_key,omitempty"`
|
||||
PaidAt *time.Time `gorm:"column:paid_at;comment:支付时间" json:"paid_at,omitempty"`
|
||||
CompletedAt *time.Time `gorm:"column:completed_at;comment:完成时间" json:"completed_at,omitempty"`
|
||||
ShopIDTag uint `gorm:"column:shop_id_tag;not null;index;comment:店铺ID标签(多租户过滤)" json:"shop_id_tag"`
|
||||
|
||||
@@ -29,7 +29,6 @@ type DeviceImportTask struct {
|
||||
StartedAt *time.Time `gorm:"column:started_at;comment:开始处理时间" json:"started_at"`
|
||||
CompletedAt *time.Time `gorm:"column:completed_at;comment:完成时间" json:"completed_at"`
|
||||
RealnamePolicy string `gorm:"column:realname_policy;type:varchar(20);default:'after_order';not null;comment:导入批次实名策略(none=无需实名,before_order=先实名后充值/购买,after_order=先充值/购买后实名)" json:"realname_policy"`
|
||||
CreatorName string `gorm:"column:creator_name;type:varchar(100);not null;default:'';comment:操作人姓名快照" json:"creator_name"`
|
||||
}
|
||||
|
||||
// TableName 指定表名
|
||||
|
||||
@@ -5,8 +5,7 @@ type CreateAgentRechargeRequest struct {
|
||||
ShopID uint `json:"shop_id" validate:"required" required:"true" description:"目标店铺ID,代理只能填自己店铺"`
|
||||
Amount int64 `json:"amount" validate:"required,min=1,max=100000000" required:"true" minimum:"1" maximum:"100000000" description:"充值金额(分),范围1分~100万元"`
|
||||
PaymentMethod string `json:"payment_method" validate:"required,oneof=wechat offline" required:"true" description:"支付方式 (wechat:微信在线支付, offline:线下转账仅平台可用)"`
|
||||
PaymentVoucherKey []string `json:"payment_voucher_key" validate:"omitempty,max=5,dive,max=500" maxItems:"5" description:"支付凭证对象存储Key列表(payment_method=offline 时至少1个,最多5个,微信支付时忽略)"`
|
||||
Remark string `json:"remark" validate:"omitempty,max=1000" maxLength:"1000" description:"运营备注(可选,创建后只读)"`
|
||||
PaymentVoucherKey string `json:"payment_voucher_key" validate:"omitempty,max=500" description:"支付凭证对象存储Key(payment_method=offline 时必填,微信支付时忽略)"`
|
||||
}
|
||||
|
||||
// AgentOfflinePayRequest 代理线下充值确认请求
|
||||
@@ -22,36 +21,23 @@ type AgentOfflinePayParams struct {
|
||||
|
||||
// AgentRechargeResponse 代理充值记录响应
|
||||
type AgentRechargeResponse struct {
|
||||
ID uint `json:"id" description:"充值记录ID"`
|
||||
RechargeNo string `json:"recharge_no" description:"充值单号(ARCH前缀)"`
|
||||
ShopID uint `json:"shop_id" description:"店铺ID"`
|
||||
ShopName string `json:"shop_name" description:"店铺名称"`
|
||||
AgentWalletID uint `json:"agent_wallet_id" description:"代理钱包ID"`
|
||||
Amount int64 `json:"amount" description:"充值金额(分)"`
|
||||
PaymentMethod string `json:"payment_method" description:"支付方式 (wechat:微信在线支付, offline:线下转账)"`
|
||||
PaymentChannel string `json:"payment_channel" description:"实际支付通道 (wechat_direct:微信直连, fuyou:富友, offline:线下转账)"`
|
||||
PaymentConfigID *uint `json:"payment_config_id" description:"关联支付配置ID,线下充值为null"`
|
||||
PaymentTransactionID string `json:"payment_transaction_id" description:"第三方支付流水号"`
|
||||
PaymentVoucherKey []string `json:"payment_voucher_key" description:"支付凭证对象存储Key列表(线下支付时存在,最多5个)"`
|
||||
Remark string `json:"remark,omitempty" description:"运营备注"`
|
||||
Status int `json:"status" description:"状态 (1:待支付, 2:已支付, 3:已完成, 4:已关闭, 5:已退款, 6:已驳回)"`
|
||||
StatusName string `json:"status_name" description:"状态名称(中文)"`
|
||||
RejectionReason *string `json:"rejection_reason,omitempty" description:"驳回原因,仅 status=6 时有值"`
|
||||
PaidAt *string `json:"paid_at" description:"支付时间"`
|
||||
CompletedAt *string `json:"completed_at" description:"完成时间"`
|
||||
CreatedAt string `json:"created_at" description:"创建时间"`
|
||||
UpdatedAt string `json:"updated_at" description:"更新时间"`
|
||||
}
|
||||
|
||||
// AgentRechargeRejectRequest 驳回代理充值订单请求
|
||||
type AgentRechargeRejectRequest struct {
|
||||
RejectionReason string `json:"rejection_reason" validate:"required,max=500" required:"true" description:"驳回原因(必填,最多500字)"`
|
||||
}
|
||||
|
||||
// AgentRechargeRejectParams 驳回代理充值订单聚合参数(用于文档生成)
|
||||
type AgentRechargeRejectParams struct {
|
||||
IDReq
|
||||
AgentRechargeRejectRequest
|
||||
ID uint `json:"id" description:"充值记录ID"`
|
||||
RechargeNo string `json:"recharge_no" description:"充值单号(ARCH前缀)"`
|
||||
ShopID uint `json:"shop_id" description:"店铺ID"`
|
||||
ShopName string `json:"shop_name" description:"店铺名称"`
|
||||
AgentWalletID uint `json:"agent_wallet_id" description:"代理钱包ID"`
|
||||
Amount int64 `json:"amount" description:"充值金额(分)"`
|
||||
PaymentMethod string `json:"payment_method" description:"支付方式 (wechat:微信在线支付, offline:线下转账)"`
|
||||
PaymentChannel string `json:"payment_channel" description:"实际支付通道 (wechat_direct:微信直连, fuyou:富友, offline:线下转账)"`
|
||||
PaymentConfigID *uint `json:"payment_config_id" description:"关联支付配置ID,线下充值为null"`
|
||||
PaymentTransactionID string `json:"payment_transaction_id" description:"第三方支付流水号"`
|
||||
PaymentVoucherKey string `json:"payment_voucher_key,omitempty" description:"支付凭证对象存储Key(线下支付时存在)"`
|
||||
Status int `json:"status" description:"状态 (1:待支付, 2:已支付, 3:已完成, 4:已关闭, 5:已退款)"`
|
||||
StatusName string `json:"status_name" description:"状态名称(中文)"`
|
||||
PaidAt *string `json:"paid_at" description:"支付时间"`
|
||||
CompletedAt *string `json:"completed_at" description:"完成时间"`
|
||||
CreatedAt string `json:"created_at" description:"创建时间"`
|
||||
UpdatedAt string `json:"updated_at" description:"更新时间"`
|
||||
}
|
||||
|
||||
// AgentRechargeListRequest 代理充值记录列表请求
|
||||
@@ -59,7 +45,7 @@ type AgentRechargeListRequest struct {
|
||||
Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码,默认1"`
|
||||
PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页条数,默认20,最大100"`
|
||||
ShopID *uint `json:"shop_id" query:"shop_id" description:"按店铺ID过滤"`
|
||||
Status *int `json:"status" query:"status" description:"按状态过滤 (1:待支付, 2:已支付, 3:已完成, 4:已关闭, 5:已退款, 6:已驳回)"`
|
||||
Status *int `json:"status" query:"status" description:"按状态过滤 (1:待支付, 2:已支付, 3:已完成, 4:已关闭, 5:已退款)"`
|
||||
StartDate string `json:"start_date" query:"start_date" description:"创建时间起始日期(YYYY-MM-DD)"`
|
||||
EndDate string `json:"end_date" query:"end_date" description:"创建时间截止日期(YYYY-MM-DD)"`
|
||||
}
|
||||
|
||||
@@ -39,7 +39,6 @@ type DeviceImportTaskResponse struct {
|
||||
StartedAt *time.Time `json:"started_at,omitempty" description:"开始处理时间"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty" description:"完成时间"`
|
||||
ErrorMessage string `json:"error_message,omitempty" description:"错误信息"`
|
||||
CreatorName string `json:"creator_name" description:"操作人姓名"`
|
||||
CreatedAt time.Time `json:"created_at" description:"创建时间"`
|
||||
}
|
||||
|
||||
|
||||
@@ -126,7 +126,6 @@ type ImportTaskResponse struct {
|
||||
StartedAt *time.Time `json:"started_at,omitempty" description:"开始处理时间"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty" description:"完成时间"`
|
||||
ErrorMessage string `json:"error_message,omitempty" description:"错误信息"`
|
||||
CreatorName string `json:"creator_name" description:"操作人姓名"`
|
||||
CreatedAt time.Time `json:"created_at" description:"创建时间"`
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ type CreateAdminOrderRequest struct {
|
||||
Identifier string `json:"identifier" validate:"required,min=1,max=100" required:"true" minLength:"1" maxLength:"100" description:"资产标识符(ICCID 或 VirtualNo)"`
|
||||
PackageIDs []uint `json:"package_ids" validate:"required,min=1,max=10,dive,min=1" required:"true" minItems:"1" maxItems:"10" description:"套餐ID列表"`
|
||||
PaymentMethod string `json:"payment_method" validate:"required,oneof=wallet offline" required:"true" description:"支付方式 (wallet:钱包支付, offline:线下支付)"`
|
||||
PaymentVoucherKey []string `json:"payment_voucher_key" validate:"omitempty,max=5,dive,max=500" maxItems:"5" description:"线下支付凭证对象存储file_key列表(payment_method=offline时至少1个,最多5个,通过/storage/upload-url上传图片后获得)"`
|
||||
PaymentVoucherKey string `json:"payment_voucher_key" validate:"omitempty,max=500" maxLength:"500" description:"线下支付凭证对象存储file_key(payment_method=offline时必填,通过/storage/upload-url上传图片后获得)"`
|
||||
}
|
||||
|
||||
type OrderListRequest struct {
|
||||
@@ -63,7 +63,7 @@ type OrderResponse struct {
|
||||
PaymentStatus int `json:"payment_status" description:"支付状态 (1:待支付, 2:已支付, 3:已取消, 4:已退款)"`
|
||||
PaymentStatusText string `json:"payment_status_text" description:"支付状态文本"`
|
||||
PaidAt *time.Time `json:"paid_at,omitempty" description:"支付时间"`
|
||||
PaymentVoucherKey []string `json:"payment_voucher_key" description:"线下支付凭证对象存储file_key列表(线下支付订单有值,最多5个)"`
|
||||
PaymentVoucherKey string `json:"payment_voucher_key,omitempty" description:"线下支付凭证对象存储file_key(仅线下支付订单有值)"`
|
||||
IsPurchaseOnBehalf bool `json:"is_purchase_on_behalf" description:"是否为代购订单"`
|
||||
CommissionStatus int `json:"commission_status" description:"佣金流程状态 (1:待计算, 2:已完成, 3:待人工处理)"`
|
||||
CommissionStatusName string `json:"commission_status_name" description:"佣金流程状态名称(中文)"`
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
package dto
|
||||
|
||||
// CreateOrderPackageInvalidateTaskRequest 创建订单套餐失效任务请求
|
||||
type CreateOrderPackageInvalidateTaskRequest struct {
|
||||
FileKey string `json:"file_key" validate:"required,max=500" required:"true" maxLength:"500" description:"CSV文件对象存储Key(通过/storage/upload-url上传后获得;CSV单列 order_no)"`
|
||||
VoucherKeys []string `json:"voucher_keys" validate:"omitempty,max=5,dive,max=500" maxItems:"5" description:"支付凭证对象存储Key列表(可选,最多5个)"`
|
||||
Remark string `json:"remark" validate:"omitempty,max=1000" maxLength:"1000" description:"运营备注(可选,创建后只读)"`
|
||||
}
|
||||
|
||||
// OrderPackageInvalidateTaskResponse 任务详情响应
|
||||
type OrderPackageInvalidateTaskResponse struct {
|
||||
ID uint `json:"id" description:"任务ID"`
|
||||
TaskNo string `json:"task_no" description:"任务编号"`
|
||||
Status int `json:"status" description:"任务状态 (1:待处理, 2:处理中, 3:已完成, 4:失败)"`
|
||||
StatusName string `json:"status_name" description:"状态名称(中文)"`
|
||||
TotalCount int `json:"total_count" description:"总行数"`
|
||||
SuccessCount int `json:"success_count" description:"成功数"`
|
||||
FailCount int `json:"fail_count" description:"失败数"`
|
||||
FileName string `json:"file_name" description:"原始文件名"`
|
||||
VoucherKeys []string `json:"voucher_keys" description:"支付凭证Key列表"`
|
||||
Remark string `json:"remark,omitempty" description:"运营备注"`
|
||||
CreatorName string `json:"creator_name" description:"操作人姓名"`
|
||||
ErrorMessage string `json:"error_message,omitempty" description:"任务级错误信息"`
|
||||
StartedAt *string `json:"started_at,omitempty" description:"开始处理时间"`
|
||||
CompletedAt *string `json:"completed_at,omitempty" description:"完成时间"`
|
||||
CreatedAt string `json:"created_at" description:"创建时间"`
|
||||
UpdatedAt string `json:"updated_at" description:"更新时间"`
|
||||
}
|
||||
|
||||
// OrderPackageInvalidateTaskDetailResponse 任务详情(含失败明细)
|
||||
type OrderPackageInvalidateTaskDetailResponse struct {
|
||||
OrderPackageInvalidateTaskResponse
|
||||
FailedItems []InvalidateFailedItem `json:"failed_items" description:"失败记录列表"`
|
||||
}
|
||||
|
||||
// InvalidateFailedItem 失效失败记录
|
||||
type InvalidateFailedItem struct {
|
||||
Line int `json:"line" description:"CSV 行号"`
|
||||
OrderNo string `json:"order_no" description:"订单号"`
|
||||
Reason string `json:"reason" description:"失败原因"`
|
||||
}
|
||||
|
||||
// ListOrderPackageInvalidateTaskRequest 任务列表查询请求
|
||||
type ListOrderPackageInvalidateTaskRequest struct {
|
||||
Page int `json:"page" query:"page" validate:"omitempty,min=1" minimum:"1" description:"页码(默认1)"`
|
||||
PageSize int `json:"page_size" query:"page_size" validate:"omitempty,min=1,max=100" minimum:"1" maximum:"100" description:"每页条数(默认20,最大100)"`
|
||||
Status *int `json:"status" query:"status" validate:"omitempty,min=1,max=4" minimum:"1" maximum:"4" description:"按状态过滤 (1:待处理, 2:处理中, 3:已完成, 4:失败)"`
|
||||
}
|
||||
|
||||
// OrderPackageInvalidateTaskListResponse 任务列表响应
|
||||
type OrderPackageInvalidateTaskListResponse struct {
|
||||
Total int64 `json:"total" description:"总记录数"`
|
||||
Page int `json:"page" description:"当前页码"`
|
||||
PageSize int `json:"size" description:"每页条数"`
|
||||
List []*OrderPackageInvalidateTaskResponse `json:"items" description:"任务列表"`
|
||||
}
|
||||
@@ -5,7 +5,7 @@ type CreateRefundRequest struct {
|
||||
OrderID uint `json:"order_id" validate:"required" required:"true" description:"关联订单ID"`
|
||||
ActualReceivedAmount int64 `json:"actual_received_amount" validate:"required,min=1" required:"true" minimum:"1" description:"实收金额(分)"`
|
||||
RequestedRefundAmount int64 `json:"requested_refund_amount" validate:"required,min=1" required:"true" minimum:"1" description:"申请退款金额(分)"`
|
||||
RefundVoucherKey []string `json:"refund_voucher_key" validate:"required,min=1,max=5,dive,max=500" required:"true" minItems:"1" maxItems:"5" description:"退款凭证对象存储file_key列表(至少1个,最多5个,通过/storage/upload-url上传图片后获得)"`
|
||||
RefundVoucherKey string `json:"refund_voucher_key" validate:"required,min=1,max=500" required:"true" minLength:"1" maxLength:"500" description:"退款凭证对象存储file_key(通过/storage/upload-url上传图片后获得)"`
|
||||
RefundReason string `json:"refund_reason" validate:"omitempty,max=1000" maxLength:"1000" description:"退款原因"`
|
||||
PackageUsageID *uint `json:"package_usage_id" validate:"omitempty" description:"关联套餐使用记录ID(可选)"`
|
||||
}
|
||||
@@ -27,7 +27,7 @@ type ResubmitRefundRequest struct {
|
||||
ID uint `json:"-" params:"id" path:"id" validate:"required" description:"退款申请ID"`
|
||||
ActualReceivedAmount *int64 `json:"actual_received_amount" validate:"omitempty,min=1" minimum:"1" description:"实收金额(分)"`
|
||||
RequestedRefundAmount *int64 `json:"requested_refund_amount" validate:"omitempty,min=1" minimum:"1" description:"申请退款金额(分)"`
|
||||
RefundVoucherKey *[]string `json:"refund_voucher_key" validate:"omitempty,max=5,dive,max=500" maxItems:"5" description:"退款凭证对象存储file_key列表(重新提交时可替换;历史记录缺失时必填,最多5个)"`
|
||||
RefundVoucherKey *string `json:"refund_voucher_key" validate:"omitempty,max=500" maxLength:"500" description:"退款凭证对象存储file_key(重新提交时可替换;历史记录缺失时必填)"`
|
||||
RefundReason *string `json:"refund_reason" validate:"omitempty,max=1000" maxLength:"1000" description:"退款原因"`
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ type RefundResponse struct {
|
||||
ActualReceivedAmount int64 `json:"actual_received_amount" description:"实收金额(分)"`
|
||||
RequestedRefundAmount int64 `json:"requested_refund_amount" description:"申请退款金额(分)"`
|
||||
ApprovedRefundAmount *int64 `json:"approved_refund_amount,omitempty" description:"审批实际退款金额(分)"`
|
||||
RefundVoucherKey []string `json:"refund_voucher_key" description:"退款凭证对象存储file_key列表(最多5个)"`
|
||||
RefundVoucherKey string `json:"refund_voucher_key,omitempty" description:"退款凭证对象存储file_key"`
|
||||
RefundReason string `json:"refund_reason" description:"退款原因"`
|
||||
Status int `json:"status" description:"状态 (1:待审批, 2:已通过, 3:已拒绝, 4:已退回)"`
|
||||
StatusName string `json:"status_name" description:"状态名称(中文)"`
|
||||
|
||||
@@ -33,7 +33,6 @@ type IotCardImportTask struct {
|
||||
StorageKey string `gorm:"column:storage_key;type:varchar(500);comment:对象存储文件路径" json:"storage_key,omitempty"`
|
||||
CardCategory string `gorm:"column:card_category;type:varchar(20);default:normal;not null;comment:卡业务类型(normal/industry)" json:"card_category"`
|
||||
RealnamePolicy string `gorm:"column:realname_policy;type:varchar(20);default:'after_order';not null;comment:导入批次实名策略(none=无需实名,before_order=先实名后充值/购买,after_order=先充值/购买后实名)" json:"realname_policy"`
|
||||
CreatorName string `gorm:"column:creator_name;type:varchar(100);not null;default:'';comment:操作人姓名快照" json:"creator_name"`
|
||||
}
|
||||
|
||||
// CardItem 卡信息(ICCID + MSISDN + VirtualNo)
|
||||
|
||||
@@ -70,8 +70,8 @@ type Order struct {
|
||||
// 支付配置
|
||||
PaymentConfigID *uint `gorm:"column:payment_config_id;index;comment:支付配置ID(关联tb_wechat_config.id)" json:"payment_config_id,omitempty"`
|
||||
|
||||
// 线下支付凭证对象存储 file_key 列表(最多5个,仅线下支付订单必填)
|
||||
PaymentVoucherKey StringJSONBArray `gorm:"column:payment_voucher_key;type:jsonb;comment:线下支付凭证对象存储file_key列表(jsonb存储[]string)" json:"payment_voucher_key"`
|
||||
// 线下支付凭证对象存储 file_key(仅线下支付订单必填)
|
||||
PaymentVoucherKey string `gorm:"column:payment_voucher_key;type:varchar(500);comment:线下支付凭证对象存储file_key" json:"payment_voucher_key,omitempty"`
|
||||
}
|
||||
|
||||
// TableName 指定表名
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// OrderPackageInvalidateTask 订单套餐批量失效任务模型
|
||||
type OrderPackageInvalidateTask struct {
|
||||
ID uint `gorm:"column:id;primaryKey" json:"id"`
|
||||
TaskNo string `gorm:"column:task_no;type:varchar(50);uniqueIndex;not null;comment:任务编号" json:"task_no"`
|
||||
Status int `gorm:"column:status;type:int;not null;default:1;comment:任务状态 (1:待处理, 2:处理中, 3:已完成, 4:失败)" json:"status"`
|
||||
TotalCount int `gorm:"column:total_count;type:int;not null;default:0;comment:总行数" json:"total_count"`
|
||||
SuccessCount int `gorm:"column:success_count;type:int;not null;default:0;comment:成功数" json:"success_count"`
|
||||
FailCount int `gorm:"column:fail_count;type:int;not null;default:0;comment:失败数" json:"fail_count"`
|
||||
FailedItems ImportResultItems `gorm:"column:failed_items;type:jsonb;not null;default:'[]';comment:失败记录详情(jsonb)" json:"failed_items"`
|
||||
FileName string `gorm:"column:file_name;type:varchar(255);not null;default:'';comment:原始文件名" json:"file_name"`
|
||||
StorageKey string `gorm:"column:storage_key;type:varchar(500);not null;default:'';comment:CSV 文件对象存储路径" json:"storage_key"`
|
||||
VoucherKeys StringJSONBArray `gorm:"column:voucher_keys;type:jsonb;not null;default:'[]';comment:支付凭证对象存储Key列表(最多5个)" json:"voucher_keys"`
|
||||
Remark string `gorm:"column:remark;type:text;not null;default:'';comment:运营备注(创建时填写,只读)" json:"remark"`
|
||||
CreatorName string `gorm:"column:creator_name;type:varchar(100);not null;default:'';comment:操作人姓名快照" json:"creator_name"`
|
||||
ErrorMessage string `gorm:"column:error_message;type:text;not null;default:'';comment:任务级错误信息" json:"error_message"`
|
||||
StartedAt *time.Time `gorm:"column:started_at;comment:开始处理时间" json:"started_at"`
|
||||
CompletedAt *time.Time `gorm:"column:completed_at;comment:完成时间" json:"completed_at"`
|
||||
Creator uint `gorm:"column:creator;not null;default:0;comment:创建人ID" json:"creator"`
|
||||
Updater uint `gorm:"column:updater;not null;default:0;comment:更新人ID" json:"updater"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;not null;default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at;not null;default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;index" json:"deleted_at,omitempty"`
|
||||
}
|
||||
|
||||
// TableName 指定表名
|
||||
func (OrderPackageInvalidateTask) TableName() string {
|
||||
return "tb_order_package_invalidate_task"
|
||||
}
|
||||
@@ -31,7 +31,7 @@ type RefundRequest struct {
|
||||
ApprovedRefundAmount *int64 `gorm:"column:approved_refund_amount;type:bigint;comment:审批实际退款金额(分)" json:"approved_refund_amount,omitempty"`
|
||||
|
||||
// 退款凭证、原因和状态
|
||||
RefundVoucherKey StringJSONBArray `gorm:"column:refund_voucher_key;type:jsonb;not null;comment:退款凭证对象存储file_key列表(jsonb存储[]string)" json:"refund_voucher_key"`
|
||||
RefundVoucherKey string `gorm:"column:refund_voucher_key;type:varchar(500);not null;default:'';comment:退款凭证对象存储file_key" json:"refund_voucher_key,omitempty"`
|
||||
RefundReason string `gorm:"column:refund_reason;type:text;comment:退款原因" json:"refund_reason"`
|
||||
Status int `gorm:"column:status;type:int;not null;default:1;index;comment:状态 1-待审批 2-已通过 3-已拒绝 4-已退回" json:"status"`
|
||||
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
// StringJSONBArray 用于将 []string 与 PostgreSQL jsonb 列互转
|
||||
// 读写时通过 Scan/Value 完成序列化,空切片序列化为 []
|
||||
type StringJSONBArray []string
|
||||
|
||||
// Value 写入数据库时序列化为 JSON
|
||||
func (a StringJSONBArray) Value() (driver.Value, error) {
|
||||
if a == nil {
|
||||
return "[]", nil
|
||||
}
|
||||
return json.Marshal(a)
|
||||
}
|
||||
|
||||
// Scan 从数据库读取时反序列化
|
||||
func (a *StringJSONBArray) Scan(value any) error {
|
||||
if value == nil {
|
||||
*a = StringJSONBArray{}
|
||||
return nil
|
||||
}
|
||||
b, ok := value.([]byte)
|
||||
if !ok {
|
||||
*a = StringJSONBArray{}
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(b, a)
|
||||
}
|
||||
@@ -81,30 +81,6 @@ func (s *PollingLifecycleService) OnCardStatusChanged(ctx context.Context, cardI
|
||||
s.enqueueCard(ctx, card)
|
||||
}
|
||||
|
||||
// OnBatchCardsStatusChanged 批量卡状态变化:单次 Redis pipeline 清理 + 单次 DB 批量查询
|
||||
// 替代 N 次 OnCardStatusChanged 调用,避免批量分配/回收时打满 DB 连接池
|
||||
func (s *PollingLifecycleService) OnBatchCardsStatusChanged(ctx context.Context, cardIDs []uint) {
|
||||
if len(cardIDs) == 0 {
|
||||
return
|
||||
}
|
||||
// 单次 pipeline:批量从当前分片队列移除并清理缓存
|
||||
if err := s.queueMgr.RemoveBatchFromCurrentShardQueues(ctx, cardIDs); err != nil {
|
||||
s.logger.Warn("批量卡状态变化:从队列移除失败", zap.Int("count", len(cardIDs)), zap.Error(err))
|
||||
}
|
||||
// 单次 DB 查询:批量加载所有卡信息
|
||||
cards, err := s.iotCardStore.GetByIDs(ctx, cardIDs)
|
||||
if err != nil {
|
||||
s.logger.Error("批量卡状态变化:加载卡信息失败", zap.Int("count", len(cardIDs)), zap.Error(err))
|
||||
return
|
||||
}
|
||||
for _, card := range cards {
|
||||
if !s.shouldEnqueue(ctx, card) {
|
||||
continue
|
||||
}
|
||||
s.enqueueCard(ctx, card)
|
||||
}
|
||||
}
|
||||
|
||||
// OnCardDeleted 卡删除后移除所有队列并清理缓存
|
||||
func (s *PollingLifecycleService) OnCardDeleted(ctx context.Context, cardID uint) {
|
||||
if err := s.queueMgr.OnCardDeleted(ctx, cardID); err != nil {
|
||||
|
||||
@@ -125,9 +125,6 @@ func RegisterAdminRoutes(router fiber.Router, handlers *bootstrap.Handlers, midd
|
||||
if handlers.Refund != nil {
|
||||
registerRefundRoutes(authGroup, handlers.Refund, doc, basePath)
|
||||
}
|
||||
if handlers.OrderPackageInvalidate != nil {
|
||||
registerOrderPackageInvalidateRoutes(authGroup, handlers.OrderPackageInvalidate, doc, basePath)
|
||||
}
|
||||
if handlers.SuperAdmin != nil {
|
||||
registerSuperAdminRoutes(authGroup, handlers.SuperAdmin, doc, basePath)
|
||||
}
|
||||
|
||||
@@ -52,12 +52,4 @@ func registerAgentRechargeRoutes(router fiber.Router, handler *admin.AgentRechar
|
||||
Output: new(dto.AgentRechargeResponse),
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
Register(group, doc, groupPath, "POST", "/:id/reject", handler.Reject, RouteSpec{
|
||||
Summary: "驳回代理充值订单",
|
||||
Tags: []string{"代理预充值"},
|
||||
Input: new(dto.AgentRechargeRejectParams),
|
||||
Output: nil,
|
||||
Auth: true,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/handler/admin"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/openapi"
|
||||
)
|
||||
|
||||
// registerOrderPackageInvalidateRoutes 注册订单套餐批量失效任务路由
|
||||
func registerOrderPackageInvalidateRoutes(router fiber.Router, handler *admin.OrderPackageInvalidateHandler, doc *openapi.Generator, basePath string) {
|
||||
group := router.Group("/order-package-invalidate-tasks")
|
||||
groupPath := basePath + "/order-package-invalidate-tasks"
|
||||
|
||||
Register(group, doc, groupPath, "POST", "", handler.Create, RouteSpec{
|
||||
Summary: "创建订单套餐批量失效任务",
|
||||
Description: "上传单列 CSV 文件(列名 order_no),批量将订单下的非终态套餐标记为已失效(status=4)。",
|
||||
Tags: []string{"订单套餐失效"},
|
||||
Input: new(dto.CreateOrderPackageInvalidateTaskRequest),
|
||||
Output: new(dto.OrderPackageInvalidateTaskResponse),
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
Register(group, doc, groupPath, "GET", "", handler.List, RouteSpec{
|
||||
Summary: "查询订单套餐失效任务列表",
|
||||
Tags: []string{"订单套餐失效"},
|
||||
Input: new(dto.ListOrderPackageInvalidateTaskRequest),
|
||||
Output: new(dto.OrderPackageInvalidateTaskListResponse),
|
||||
Auth: true,
|
||||
})
|
||||
|
||||
Register(group, doc, groupPath, "GET", "/:id", handler.GetByID, RouteSpec{
|
||||
Summary: "查询订单套餐失效任务详情",
|
||||
Tags: []string{"订单套餐失效"},
|
||||
Input: new(dto.IDReq),
|
||||
Output: new(dto.OrderPackageInvalidateTaskDetailResponse),
|
||||
Auth: true,
|
||||
})
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
@@ -95,7 +96,7 @@ func (s *Service) Create(ctx context.Context, req *dto.CreateAgentRechargeReques
|
||||
}
|
||||
|
||||
// 线下充值必须上传支付凭证
|
||||
if req.PaymentMethod == "offline" && len(req.PaymentVoucherKey) == 0 {
|
||||
if req.PaymentMethod == "offline" && strings.TrimSpace(req.PaymentVoucherKey) == "" {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "线下充值必须上传支付凭证")
|
||||
}
|
||||
|
||||
@@ -146,8 +147,7 @@ func (s *Service) Create(ctx context.Context, req *dto.CreateAgentRechargeReques
|
||||
PaymentMethod: req.PaymentMethod,
|
||||
PaymentChannel: &paymentChannel,
|
||||
PaymentConfigID: paymentConfigID,
|
||||
PaymentVoucherKey: model.StringJSONBArray(req.PaymentVoucherKey),
|
||||
Remark: req.Remark,
|
||||
PaymentVoucherKey: strings.TrimSpace(req.PaymentVoucherKey),
|
||||
Status: constants.RechargeStatusPending,
|
||||
ShopIDTag: wallet.ShopIDTag,
|
||||
EnterpriseIDTag: wallet.EnterpriseIDTag,
|
||||
@@ -387,35 +387,6 @@ func (s *Service) HandlePaymentCallback(ctx context.Context, rechargeNo string,
|
||||
return nil
|
||||
}
|
||||
|
||||
// Reject 驳回代理充值订单
|
||||
// 仅 status=1(待支付)的订单可驳回,驳回后状态变为 6(已驳回),为终态
|
||||
func (s *Service) Reject(ctx context.Context, id uint, rejectionReason string) error {
|
||||
record, err := s.agentRechargeStore.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return errors.New(errors.CodeNotFound, "充值记录不存在")
|
||||
}
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "查询充值记录失败")
|
||||
}
|
||||
|
||||
if record.Status != constants.RechargeStatusPending {
|
||||
return errors.New(errors.CodeInvalidStatus, "仅待支付订单可驳回")
|
||||
}
|
||||
|
||||
if err := s.agentRechargeStore.UpdateStatusWithRejection(ctx, id, rejectionReason); err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return errors.New(errors.CodeInvalidStatus, "仅待支付订单可驳回")
|
||||
}
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "驳回充值订单失败")
|
||||
}
|
||||
|
||||
s.logger.Info("代理充值订单驳回成功",
|
||||
zap.Uint("record_id", id),
|
||||
zap.String("rejection_reason", rejectionReason),
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByID 根据ID查询充值订单详情
|
||||
// GET /api/admin/agent-recharges/:id
|
||||
func (s *Service) GetByID(ctx context.Context, id uint) (*dto.AgentRechargeResponse, error) {
|
||||
@@ -515,11 +486,9 @@ func toResponse(record *model.AgentRechargeRecord, shopName string) *dto.AgentRe
|
||||
AgentWalletID: record.AgentWalletID,
|
||||
Amount: record.Amount,
|
||||
PaymentMethod: record.PaymentMethod,
|
||||
PaymentVoucherKey: []string(record.PaymentVoucherKey),
|
||||
Remark: record.Remark,
|
||||
PaymentVoucherKey: record.PaymentVoucherKey,
|
||||
Status: record.Status,
|
||||
StatusName: constants.GetRechargeStatusName(record.Status),
|
||||
RejectionReason: record.RejectionReason,
|
||||
CreatedAt: record.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
UpdatedAt: record.UpdatedAt.Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
|
||||
@@ -60,7 +60,6 @@ func (s *Service) CreateImportTask(ctx context.Context, req *dto.ImportDeviceReq
|
||||
FileName: fileName,
|
||||
StorageKey: req.FileKey,
|
||||
RealnamePolicy: req.RealnamePolicy,
|
||||
CreatorName: middleware.GetUsernameFromContext(ctx),
|
||||
}
|
||||
task.Creator = userID
|
||||
task.Updater = userID
|
||||
@@ -191,23 +190,21 @@ func (s *Service) toTaskResponse(task *model.DeviceImportTask) *dto.DeviceImport
|
||||
}
|
||||
|
||||
return &dto.DeviceImportTaskResponse{
|
||||
ID: task.ID,
|
||||
TaskNo: task.TaskNo,
|
||||
Status: task.Status,
|
||||
StatusText: getStatusText(task.Status),
|
||||
BatchNo: task.BatchNo,
|
||||
RealnamePolicy: task.RealnamePolicy,
|
||||
FileName: task.FileName,
|
||||
TotalCount: task.TotalCount,
|
||||
SuccessCount: task.SuccessCount,
|
||||
SkipCount: task.SkipCount,
|
||||
FailCount: task.FailCount,
|
||||
WarningCount: task.WarningCount,
|
||||
StartedAt: startedAt,
|
||||
CompletedAt: completedAt,
|
||||
ErrorMessage: task.ErrorMessage,
|
||||
CreatorName: task.CreatorName,
|
||||
CreatedAt: task.CreatedAt,
|
||||
ID: task.ID,
|
||||
TaskNo: task.TaskNo,
|
||||
Status: task.Status,
|
||||
StatusText: getStatusText(task.Status),
|
||||
BatchNo: task.BatchNo,
|
||||
FileName: task.FileName,
|
||||
TotalCount: task.TotalCount,
|
||||
SuccessCount: task.SuccessCount,
|
||||
SkipCount: task.SkipCount,
|
||||
FailCount: task.FailCount,
|
||||
WarningCount: task.WarningCount,
|
||||
StartedAt: startedAt,
|
||||
CompletedAt: completedAt,
|
||||
ErrorMessage: task.ErrorMessage,
|
||||
CreatedAt: task.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,8 +29,6 @@ type PollingCallback interface {
|
||||
OnCardCreated(ctx context.Context, card *model.IotCard)
|
||||
// OnCardStatusChanged 卡状态变化时的回调
|
||||
OnCardStatusChanged(ctx context.Context, cardID uint)
|
||||
// OnBatchCardsStatusChanged 批量卡状态变化时的回调(批量分配/回收场景)
|
||||
OnBatchCardsStatusChanged(ctx context.Context, cardIDs []uint)
|
||||
// OnCardDeleted 卡删除时的回调
|
||||
OnCardDeleted(ctx context.Context, cardID uint)
|
||||
// OnCardEnabled 卡启用轮询时的回调
|
||||
@@ -599,7 +597,6 @@ func (s *Service) AllocateCards(ctx context.Context, req *dto.AllocateStandalone
|
||||
|
||||
newStatus := constants.IotCardStatusDistributed
|
||||
toShopID := req.ToShopID
|
||||
allocationNo := s.assetAllocationRecordStore.GenerateAllocationNo(ctx, constants.AssetAllocationTypeAllocate)
|
||||
|
||||
err = s.db.Transaction(func(tx *gorm.DB) error {
|
||||
txIotCardStore := postgres.NewIotCardStore(tx, nil)
|
||||
@@ -609,6 +606,7 @@ func (s *Service) AllocateCards(ctx context.Context, req *dto.AllocateStandalone
|
||||
return err
|
||||
}
|
||||
|
||||
allocationNo := s.assetAllocationRecordStore.GenerateAllocationNo(ctx, constants.AssetAllocationTypeAllocate)
|
||||
records := s.buildAllocationRecords(cards, cardIDs, operatorShopID, toShopID, operatorID, allocationNo, req.Remark)
|
||||
return txRecordStore.BatchCreate(ctx, records)
|
||||
})
|
||||
@@ -633,14 +631,11 @@ func (s *Service) AllocateCards(ctx context.Context, req *dto.AllocateStandalone
|
||||
}
|
||||
s.iotCardStore.InvalidateListCountCache(ctx)
|
||||
|
||||
// 通知轮询调度器状态变化(异步执行 + 批量操作,避免 N 次单卡 DB 查询打满连接池)
|
||||
// 通知轮询调度器状态变化(卡被分配后可能需要重新匹配配置)
|
||||
if s.pollingCallback != nil && len(cardIDs) > 0 {
|
||||
cardIDsCopy := make([]uint, len(cardIDs))
|
||||
copy(cardIDsCopy, cardIDs)
|
||||
cb := s.pollingCallback
|
||||
go func() {
|
||||
cb.OnBatchCardsStatusChanged(context.Background(), cardIDsCopy)
|
||||
}()
|
||||
for _, cardID := range cardIDs {
|
||||
s.pollingCallback.OnCardStatusChanged(ctx, cardID)
|
||||
}
|
||||
}
|
||||
|
||||
shopMap := s.loadShopNames(ctx, cards)
|
||||
@@ -677,7 +672,7 @@ func (s *Service) AllocateCards(ctx context.Context, req *dto.AllocateStandalone
|
||||
TotalCount: len(cards),
|
||||
SuccessCount: len(cardIDs),
|
||||
FailCount: len(failedItems),
|
||||
AllocationNo: allocationNo,
|
||||
AllocationNo: s.assetAllocationRecordStore.GenerateAllocationNo(ctx, constants.AssetAllocationTypeAllocate),
|
||||
FailedItems: failedItems,
|
||||
}, nil
|
||||
}
|
||||
@@ -849,14 +844,11 @@ func (s *Service) RecallCards(ctx context.Context, req *dto.RecallStandaloneCard
|
||||
}
|
||||
s.iotCardStore.InvalidateListCountCache(ctx)
|
||||
|
||||
// 通知轮询调度器状态变化(异步批量执行,避免回收大批卡时打满 DB 连接池)
|
||||
// 通知轮询调度器状态变化(卡被回收后可能需要重新匹配配置)
|
||||
if s.pollingCallback != nil && len(cardIDs) > 0 {
|
||||
cardIDsCopy := make([]uint, len(cardIDs))
|
||||
copy(cardIDsCopy, cardIDs)
|
||||
cb := s.pollingCallback
|
||||
go func() {
|
||||
cb.OnBatchCardsStatusChanged(context.Background(), cardIDsCopy)
|
||||
}()
|
||||
for _, cardID := range cardIDs {
|
||||
s.pollingCallback.OnCardStatusChanged(ctx, cardID)
|
||||
}
|
||||
}
|
||||
|
||||
shopMap := s.loadShopNames(ctx, successCards)
|
||||
|
||||
@@ -132,14 +132,6 @@ func (s *StopResumeService) EvaluateAndAct(ctx context.Context, card *model.IotC
|
||||
}
|
||||
}
|
||||
|
||||
// isRiskGatewayExtend 判断网关扩展状态是否为风险状态(风险停机或已销户)
|
||||
// 独立卡命中此状态时禁止发起复机
|
||||
func isRiskGatewayExtend(extend string) bool {
|
||||
trimmed := strings.TrimSpace(extend)
|
||||
return trimmed == constants.GatewayCardExtendRiskStop ||
|
||||
trimmed == constants.GatewayCardExtendCancelled
|
||||
}
|
||||
|
||||
// isPollingStopReason 判断停机原因是否为轮询系统引起(可自动复机)
|
||||
func isPollingStopReason(reason string) bool {
|
||||
switch reason {
|
||||
@@ -700,30 +692,6 @@ func (s *StopResumeService) StartMachineSeparatedCard(ctx context.Context, card
|
||||
}
|
||||
|
||||
gatewayExtend := strings.TrimSpace(card.GatewayExtend)
|
||||
|
||||
// 独立卡处于风险停机或已销户状态时,优先返回明确的拒绝原因
|
||||
if card.IsStandalone && isRiskGatewayExtend(gatewayExtend) {
|
||||
var denyMsg string
|
||||
if gatewayExtend == constants.GatewayCardExtendRiskStop {
|
||||
denyMsg = "该卡已被运营商风险停机,不允许复机"
|
||||
} else {
|
||||
denyMsg = "该卡已被运营商销户,不允许复机"
|
||||
}
|
||||
denyErr := errors.New(errors.CodeForbidden, denyMsg)
|
||||
errorCode, errorMsg := assetAuditSvc.BuildErrorInfo(denyErr)
|
||||
s.logCardAudit(ctx, assetAuditSvc.BuildLogParams{
|
||||
OperationType: constants.AssetAuditOpCardManualStart,
|
||||
OperationDesc: "机卡分离复机被拒绝(风险状态)",
|
||||
ResultStatus: constants.AssetAuditResultDenied,
|
||||
ErrorCode: errorCode,
|
||||
ErrorMsg: errorMsg,
|
||||
AssetID: card.ID,
|
||||
AssetIdentifier: card.ICCID,
|
||||
BeforeData: cardSnapshot(card),
|
||||
})
|
||||
return denyErr
|
||||
}
|
||||
|
||||
if gatewayExtend != constants.GatewayCardExtendMachineSeparated {
|
||||
denyErr := errors.New(errors.CodeForbidden, constants.AgentOpenAPIResumeOnlyMachineSeparatedMessage)
|
||||
errorCode, errorMsg := assetAuditSvc.BuildErrorInfo(denyErr)
|
||||
@@ -912,29 +880,6 @@ func (s *StopResumeService) ManualStartCard(ctx context.Context, iccid string) e
|
||||
return denyErr
|
||||
}
|
||||
|
||||
// 独立卡处于风险停机或已销户状态时,拒绝复机
|
||||
if card.IsStandalone && isRiskGatewayExtend(card.GatewayExtend) {
|
||||
var denyMsg string
|
||||
if strings.TrimSpace(card.GatewayExtend) == constants.GatewayCardExtendRiskStop {
|
||||
denyMsg = "该卡已被运营商风险停机,不允许复机"
|
||||
} else {
|
||||
denyMsg = "该卡已被运营商销户,不允许复机"
|
||||
}
|
||||
denyErr := errors.New(errors.CodeForbidden, denyMsg)
|
||||
errorCode, errorMsg := assetAuditSvc.BuildErrorInfo(denyErr)
|
||||
s.logCardAudit(ctx, assetAuditSvc.BuildLogParams{
|
||||
OperationType: constants.AssetAuditOpCardManualStart,
|
||||
OperationDesc: "手动复机被拒绝",
|
||||
ResultStatus: constants.AssetAuditResultDenied,
|
||||
ErrorCode: errorCode,
|
||||
ErrorMsg: errorMsg,
|
||||
AssetID: card.ID,
|
||||
AssetIdentifier: card.ICCID,
|
||||
BeforeData: cardSnapshot(card),
|
||||
})
|
||||
return denyErr
|
||||
}
|
||||
|
||||
if card.RealNameStatus != constants.RealNameStatusVerified {
|
||||
denyErr := errors.New(errors.CodeForbidden, "卡未实名,无法操作")
|
||||
errorCode, errorMsg := assetAuditSvc.BuildErrorInfo(denyErr)
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
package iot_card
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestIsRiskGatewayExtend 验证网关扩展状态的风险判断逻辑
|
||||
func TestIsRiskGatewayExtend(t *testing.T) {
|
||||
cases := []struct {
|
||||
extend string
|
||||
want bool
|
||||
}{
|
||||
{"风险停机", true},
|
||||
{"已销户", true},
|
||||
{"机卡分离停机", false},
|
||||
{"待激活", false},
|
||||
{"", false},
|
||||
{" 风险停机 ", true}, // 含空白字符
|
||||
{"已注销", false}, // 非目标状态
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
got := isRiskGatewayExtend(tc.extend)
|
||||
if got != tc.want {
|
||||
t.Errorf("isRiskGatewayExtend(%q) = %v, 期望 %v", tc.extend, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -98,7 +98,6 @@ func (s *Service) CreateImportTask(ctx context.Context, req *dto.ImportIotCardRe
|
||||
StorageKey: req.FileKey,
|
||||
CardCategory: cardCategory,
|
||||
RealnamePolicy: req.RealnamePolicy,
|
||||
CreatorName: middleware.GetUsernameFromContext(ctx),
|
||||
}
|
||||
task.Creator = userID
|
||||
task.Updater = userID
|
||||
@@ -225,26 +224,24 @@ func (s *Service) toTaskResponse(task *model.IotCardImportTask) *dto.ImportTaskR
|
||||
}
|
||||
|
||||
return &dto.ImportTaskResponse{
|
||||
ID: task.ID,
|
||||
TaskNo: task.TaskNo,
|
||||
Status: task.Status,
|
||||
StatusText: getStatusText(task.Status),
|
||||
CarrierID: task.CarrierID,
|
||||
CarrierType: task.CarrierType,
|
||||
CarrierName: task.CarrierName,
|
||||
BatchNo: task.BatchNo,
|
||||
CardCategory: task.CardCategory,
|
||||
RealnamePolicy: task.RealnamePolicy,
|
||||
FileName: task.FileName,
|
||||
TotalCount: task.TotalCount,
|
||||
SuccessCount: task.SuccessCount,
|
||||
SkipCount: task.SkipCount,
|
||||
FailCount: task.FailCount,
|
||||
StartedAt: startedAt,
|
||||
CompletedAt: completedAt,
|
||||
ErrorMessage: task.ErrorMessage,
|
||||
CreatorName: task.CreatorName,
|
||||
CreatedAt: task.CreatedAt,
|
||||
ID: task.ID,
|
||||
TaskNo: task.TaskNo,
|
||||
Status: task.Status,
|
||||
StatusText: getStatusText(task.Status),
|
||||
CarrierID: task.CarrierID,
|
||||
CarrierType: task.CarrierType,
|
||||
CarrierName: task.CarrierName,
|
||||
BatchNo: task.BatchNo,
|
||||
CardCategory: task.CardCategory,
|
||||
FileName: task.FileName,
|
||||
TotalCount: task.TotalCount,
|
||||
SuccessCount: task.SuccessCount,
|
||||
SkipCount: task.SkipCount,
|
||||
FailCount: task.FailCount,
|
||||
StartedAt: startedAt,
|
||||
CompletedAt: completedAt,
|
||||
ErrorMessage: task.ErrorMessage,
|
||||
CreatedAt: task.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -182,7 +182,7 @@ func (s *Service) CreateAdminOrder(ctx context.Context, req *dto.CreateAdminOrde
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if req.PaymentMethod == model.PaymentMethodOffline && len(req.PaymentVoucherKey) == 0 {
|
||||
if req.PaymentMethod == model.PaymentMethodOffline && strings.TrimSpace(req.PaymentVoucherKey) == "" {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "线下支付必须上传支付凭证")
|
||||
}
|
||||
|
||||
@@ -453,9 +453,9 @@ func (s *Service) CreateAdminOrder(ctx context.Context, req *dto.CreateAdminOrde
|
||||
PaymentConfigID: paymentConfigID,
|
||||
}
|
||||
|
||||
// 线下支付订单写入支付凭证 file_key 列表
|
||||
// 线下支付订单写入支付凭证 file_key
|
||||
if req.PaymentMethod == model.PaymentMethodOffline {
|
||||
order.PaymentVoucherKey = model.StringJSONBArray(req.PaymentVoucherKey)
|
||||
order.PaymentVoucherKey = strings.TrimSpace(req.PaymentVoucherKey)
|
||||
}
|
||||
|
||||
if orderBuyerType == model.BuyerTypePersonal {
|
||||
@@ -2533,7 +2533,7 @@ func (s *Service) buildOrderResponse(ctx context.Context, order *model.Order, it
|
||||
PaymentStatus: order.PaymentStatus,
|
||||
PaymentStatusText: statusText,
|
||||
PaidAt: order.PaidAt,
|
||||
PaymentVoucherKey: []string(order.PaymentVoucherKey),
|
||||
PaymentVoucherKey: order.PaymentVoucherKey,
|
||||
IsPurchaseOnBehalf: order.IsPurchaseOnBehalf,
|
||||
CommissionStatus: order.CommissionStatus,
|
||||
CommissionStatusName: constants.GetOrderCommissionStatusName(order.CommissionStatus),
|
||||
|
||||
@@ -1,185 +0,0 @@
|
||||
package order_package_invalidate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model/dto"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/queue"
|
||||
)
|
||||
|
||||
// Service 订单套餐失效任务业务逻辑层
|
||||
type Service struct {
|
||||
taskStore *postgres.OrderPackageInvalidateTaskStore
|
||||
queueClient *queue.Client
|
||||
}
|
||||
|
||||
// New 创建 Service 实例
|
||||
func New(
|
||||
taskStore *postgres.OrderPackageInvalidateTaskStore,
|
||||
queueClient *queue.Client,
|
||||
) *Service {
|
||||
return &Service{
|
||||
taskStore: taskStore,
|
||||
queueClient: queueClient,
|
||||
}
|
||||
}
|
||||
|
||||
// InvalidateTaskPayload Worker 任务载荷
|
||||
type InvalidateTaskPayload struct {
|
||||
TaskID uint `json:"task_id"`
|
||||
}
|
||||
|
||||
// Create 创建订单套餐失效任务
|
||||
func (s *Service) Create(ctx context.Context, req *dto.CreateOrderPackageInvalidateTaskRequest) (*dto.OrderPackageInvalidateTaskResponse, error) {
|
||||
userID := middleware.GetUserIDFromContext(ctx)
|
||||
if userID == 0 {
|
||||
return nil, errors.New(errors.CodeUnauthorized, "未授权访问")
|
||||
}
|
||||
|
||||
task := &model.OrderPackageInvalidateTask{
|
||||
TaskNo: s.taskStore.GenerateTaskNo(),
|
||||
Status: model.ImportTaskStatusPending,
|
||||
FileName: filepath.Base(req.FileKey),
|
||||
StorageKey: req.FileKey,
|
||||
VoucherKeys: model.StringJSONBArray(req.VoucherKeys),
|
||||
Remark: req.Remark,
|
||||
CreatorName: middleware.GetUsernameFromContext(ctx),
|
||||
FailedItems: model.ImportResultItems{},
|
||||
Creator: userID,
|
||||
Updater: userID,
|
||||
}
|
||||
|
||||
if err := s.taskStore.Create(ctx, task); err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "创建任务失败")
|
||||
}
|
||||
|
||||
payload := InvalidateTaskPayload{TaskID: task.ID}
|
||||
err := s.queueClient.EnqueueTask(
|
||||
ctx,
|
||||
constants.TaskTypeOrderPackageInvalidate,
|
||||
payload,
|
||||
asynq.Queue(constants.QueueForTaskType(constants.TaskTypeOrderPackageInvalidate)),
|
||||
)
|
||||
if err != nil {
|
||||
s.taskStore.UpdateStatus(ctx, task.ID, model.ImportTaskStatusFailed, "任务入队失败: "+err.Error())
|
||||
}
|
||||
|
||||
return s.toResponse(task), nil
|
||||
}
|
||||
|
||||
// List 分页查询任务列表
|
||||
func (s *Service) List(ctx context.Context, req *dto.ListOrderPackageInvalidateTaskRequest) (*dto.OrderPackageInvalidateTaskListResponse, error) {
|
||||
if req.Page <= 0 {
|
||||
req.Page = 1
|
||||
}
|
||||
if req.PageSize <= 0 {
|
||||
req.PageSize = constants.DefaultPageSize
|
||||
}
|
||||
|
||||
opts := &store.QueryOptions{
|
||||
Page: req.Page,
|
||||
PageSize: req.PageSize,
|
||||
}
|
||||
|
||||
filters := map[string]interface{}{}
|
||||
if req.Status != nil {
|
||||
filters["status"] = *req.Status
|
||||
}
|
||||
|
||||
tasks, total, err := s.taskStore.List(ctx, opts, filters)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(errors.CodeInternalError, err, "查询任务列表失败")
|
||||
}
|
||||
|
||||
list := make([]*dto.OrderPackageInvalidateTaskResponse, 0, len(tasks))
|
||||
for _, t := range tasks {
|
||||
list = append(list, s.toResponse(t))
|
||||
}
|
||||
|
||||
return &dto.OrderPackageInvalidateTaskListResponse{
|
||||
Total: total,
|
||||
Page: req.Page,
|
||||
PageSize: req.PageSize,
|
||||
List: list,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetByID 查询任务详情(含失败明细)
|
||||
func (s *Service) GetByID(ctx context.Context, id uint) (*dto.OrderPackageInvalidateTaskDetailResponse, error) {
|
||||
task, err := s.taskStore.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, errors.New(errors.CodeNotFound, "任务不存在")
|
||||
}
|
||||
|
||||
failedItems := make([]dto.InvalidateFailedItem, 0, len(task.FailedItems))
|
||||
for _, item := range task.FailedItems {
|
||||
failedItems = append(failedItems, dto.InvalidateFailedItem{
|
||||
Line: item.Line,
|
||||
OrderNo: item.ICCID, // 复用 ImportResultItem.ICCID 存储 order_no
|
||||
Reason: item.Reason,
|
||||
})
|
||||
}
|
||||
|
||||
return &dto.OrderPackageInvalidateTaskDetailResponse{
|
||||
OrderPackageInvalidateTaskResponse: *s.toResponse(task),
|
||||
FailedItems: failedItems,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// toResponse 转换为响应 DTO
|
||||
func (s *Service) toResponse(task *model.OrderPackageInvalidateTask) *dto.OrderPackageInvalidateTaskResponse {
|
||||
resp := &dto.OrderPackageInvalidateTaskResponse{
|
||||
ID: task.ID,
|
||||
TaskNo: task.TaskNo,
|
||||
Status: task.Status,
|
||||
StatusName: invalidateTaskStatusName(task.Status),
|
||||
TotalCount: task.TotalCount,
|
||||
SuccessCount: task.SuccessCount,
|
||||
FailCount: task.FailCount,
|
||||
FileName: task.FileName,
|
||||
VoucherKeys: []string(task.VoucherKeys),
|
||||
Remark: task.Remark,
|
||||
CreatorName: task.CreatorName,
|
||||
ErrorMessage: task.ErrorMessage,
|
||||
CreatedAt: task.CreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: task.UpdatedAt.Format(time.RFC3339),
|
||||
}
|
||||
if task.StartedAt != nil {
|
||||
t := task.StartedAt.Format(time.RFC3339)
|
||||
resp.StartedAt = &t
|
||||
}
|
||||
if task.CompletedAt != nil {
|
||||
t := task.CompletedAt.Format(time.RFC3339)
|
||||
resp.CompletedAt = &t
|
||||
}
|
||||
if resp.VoucherKeys == nil {
|
||||
resp.VoucherKeys = []string{}
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
// invalidateTaskStatusName 状态码转中文
|
||||
func invalidateTaskStatusName(status int) string {
|
||||
switch status {
|
||||
case model.ImportTaskStatusPending:
|
||||
return "待处理"
|
||||
case model.ImportTaskStatusProcessing:
|
||||
return "处理中"
|
||||
case model.ImportTaskStatusCompleted:
|
||||
return "已完成"
|
||||
case model.ImportTaskStatusFailed:
|
||||
return "失败"
|
||||
default:
|
||||
return "未知"
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
@@ -618,11 +619,11 @@ func (s *Service) Resubmit(ctx context.Context, id uint, req *dto.ResubmitRefund
|
||||
}
|
||||
refundVoucherKey := refund.RefundVoucherKey
|
||||
if req.RefundVoucherKey != nil {
|
||||
normalized, normErr := normalizeRefundVoucherKey(*req.RefundVoucherKey)
|
||||
if normErr != nil {
|
||||
return normErr
|
||||
}
|
||||
refundVoucherKey = normalized
|
||||
refundVoucherKey = *req.RefundVoucherKey
|
||||
}
|
||||
refundVoucherKey, err = normalizeRefundVoucherKey(refundVoucherKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
order, err := s.orderStore.GetByID(ctx, refund.OrderID)
|
||||
@@ -913,14 +914,15 @@ func validateApprovedRefundAmount(approvedAmount int64, requestedRefundAmount in
|
||||
return validateRequestedRefundAmountByOrder(approvedAmount, order)
|
||||
}
|
||||
|
||||
func normalizeRefundVoucherKey(keys []string) (model.StringJSONBArray, error) {
|
||||
if len(keys) == 0 {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "退款申请必须上传退款凭证")
|
||||
func normalizeRefundVoucherKey(voucherKey string) (string, error) {
|
||||
normalized := strings.TrimSpace(voucherKey)
|
||||
if normalized == "" {
|
||||
return "", errors.New(errors.CodeInvalidParam, "退款申请必须上传退款凭证")
|
||||
}
|
||||
if len(keys) > 5 {
|
||||
return nil, errors.New(errors.CodeInvalidParam, "退款凭证最多上传5个")
|
||||
if len(normalized) > 500 {
|
||||
return "", errors.New(errors.CodeInvalidParam, "退款凭证长度不能超过500")
|
||||
}
|
||||
return model.StringJSONBArray(keys), nil
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
// buildRefundResponse 将退款 Model 转换为 DTO 响应
|
||||
@@ -947,7 +949,7 @@ func buildRefundResponse(r *model.RefundRequest) *dto.RefundResponse {
|
||||
ActualReceivedAmount: r.ActualReceivedAmount,
|
||||
RequestedRefundAmount: r.RequestedRefundAmount,
|
||||
ApprovedRefundAmount: r.ApprovedRefundAmount,
|
||||
RefundVoucherKey: []string(r.RefundVoucherKey),
|
||||
RefundVoucherKey: r.RefundVoucherKey,
|
||||
RefundReason: r.RefundReason,
|
||||
Status: r.Status,
|
||||
StatusName: constants.GetRefundStatusName(r.Status),
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -75,25 +74,6 @@ func (s *AgentRechargeStore) Update(ctx context.Context, record *model.AgentRech
|
||||
return s.db.WithContext(ctx).Save(record).Error
|
||||
}
|
||||
|
||||
// UpdateStatusWithRejection 条件更新状态为已驳回并写入驳回原因
|
||||
// 仅当 status = 1(待支付)时更新,RowsAffected=0 说明订单不存在或状态已变更
|
||||
func (s *AgentRechargeStore) UpdateStatusWithRejection(ctx context.Context, id uint, rejectionReason string) error {
|
||||
result := s.db.WithContext(ctx).
|
||||
Model(&model.AgentRechargeRecord{}).
|
||||
Where("id = ? AND status = ?", id, constants.RechargeStatusPending).
|
||||
Updates(map[string]interface{}{
|
||||
"status": constants.RechargeStatusRejected,
|
||||
"rejection_reason": rejectionReason,
|
||||
})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateWithTx 更新充值记录(带事务)
|
||||
func (s *AgentRechargeStore) UpdateWithTx(ctx context.Context, tx *gorm.DB, record *model.AgentRechargeRecord) error {
|
||||
return tx.WithContext(ctx).Save(record).Error
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
)
|
||||
|
||||
// OrderPackageInvalidateTaskStore 订单套餐失效任务数据访问层
|
||||
type OrderPackageInvalidateTaskStore struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewOrderPackageInvalidateTaskStore 创建 OrderPackageInvalidateTaskStore 实例
|
||||
func NewOrderPackageInvalidateTaskStore(db *gorm.DB) *OrderPackageInvalidateTaskStore {
|
||||
return &OrderPackageInvalidateTaskStore{db: db}
|
||||
}
|
||||
|
||||
// Create 创建任务
|
||||
func (s *OrderPackageInvalidateTaskStore) Create(ctx context.Context, task *model.OrderPackageInvalidateTask) error {
|
||||
return s.db.WithContext(ctx).Create(task).Error
|
||||
}
|
||||
|
||||
// GetByID 按主键查询任务(Worker 直接查询,不过滤租户)
|
||||
func (s *OrderPackageInvalidateTaskStore) GetByID(ctx context.Context, id uint) (*model.OrderPackageInvalidateTask, error) {
|
||||
var task model.OrderPackageInvalidateTask
|
||||
if err := s.db.WithContext(ctx).Where("id = ?", id).First(&task).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &task, nil
|
||||
}
|
||||
|
||||
// List 分页查询任务列表
|
||||
func (s *OrderPackageInvalidateTaskStore) List(ctx context.Context, opts *store.QueryOptions, filters map[string]interface{}) ([]*model.OrderPackageInvalidateTask, int64, error) {
|
||||
var tasks []*model.OrderPackageInvalidateTask
|
||||
var total int64
|
||||
|
||||
query := s.db.WithContext(ctx).Model(&model.OrderPackageInvalidateTask{})
|
||||
|
||||
if status, ok := filters["status"].(int); ok && status > 0 {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if opts == nil {
|
||||
opts = &store.QueryOptions{
|
||||
Page: 1,
|
||||
PageSize: constants.DefaultPageSize,
|
||||
}
|
||||
}
|
||||
offset := (opts.Page - 1) * opts.PageSize
|
||||
query = query.Offset(offset).Limit(opts.PageSize).Order("created_at DESC")
|
||||
|
||||
if err := query.Find(&tasks).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return tasks, total, nil
|
||||
}
|
||||
|
||||
// UpdateStatus 更新任务状态
|
||||
func (s *OrderPackageInvalidateTaskStore) UpdateStatus(ctx context.Context, id uint, status int, errorMessage string) error {
|
||||
updates := map[string]interface{}{
|
||||
"status": status,
|
||||
"updated_at": time.Now(),
|
||||
}
|
||||
if status == model.ImportTaskStatusProcessing {
|
||||
updates["started_at"] = time.Now()
|
||||
}
|
||||
if status == model.ImportTaskStatusCompleted || status == model.ImportTaskStatusFailed {
|
||||
updates["completed_at"] = time.Now()
|
||||
}
|
||||
if errorMessage != "" {
|
||||
updates["error_message"] = errorMessage
|
||||
}
|
||||
return s.db.WithContext(ctx).Model(&model.OrderPackageInvalidateTask{}).Where("id = ?", id).Updates(updates).Error
|
||||
}
|
||||
|
||||
// UpdateResult 更新任务计数和失败明细
|
||||
func (s *OrderPackageInvalidateTaskStore) UpdateResult(ctx context.Context, id uint, totalCount, successCount, failCount int, failedItems model.ImportResultItems) error {
|
||||
updates := map[string]interface{}{
|
||||
"total_count": totalCount,
|
||||
"success_count": successCount,
|
||||
"fail_count": failCount,
|
||||
"failed_items": failedItems,
|
||||
"updated_at": time.Now(),
|
||||
}
|
||||
return s.db.WithContext(ctx).Model(&model.OrderPackageInvalidateTask{}).Where("id = ?", id).Updates(updates).Error
|
||||
}
|
||||
|
||||
// GenerateTaskNo 生成任务编号(OPINV-YYYYMMDD-XXXXXX)
|
||||
func (s *OrderPackageInvalidateTaskStore) GenerateTaskNo() string {
|
||||
now := time.Now()
|
||||
dateStr := now.Format("20060102")
|
||||
seq := now.UnixNano() % 1000000
|
||||
return fmt.Sprintf("OPINV-%s-%06d", dateStr, seq)
|
||||
}
|
||||
@@ -131,15 +131,6 @@ func (s *PackageUsageStore) GetAddonsByMasterID(ctx context.Context, masterUsage
|
||||
return usages, nil
|
||||
}
|
||||
|
||||
// ListActiveByOrderID 查询订单下所有非终态套餐记录(status NOT IN 已过期=3, 已失效=4)
|
||||
func (s *PackageUsageStore) ListActiveByOrderID(ctx context.Context, orderID uint) ([]*model.PackageUsage, error) {
|
||||
var usages []*model.PackageUsage
|
||||
err := s.db.WithContext(ctx).
|
||||
Where("order_id = ? AND status NOT IN ?", orderID, []int{3, 4}).
|
||||
Find(&usages).Error
|
||||
return usages, err
|
||||
}
|
||||
|
||||
// BatchUpdateStatus 批量更新加油包状态
|
||||
func (s *PackageUsageStore) BatchUpdateStatus(ctx context.Context, ids []uint, status int) error {
|
||||
if len(ids) == 0 {
|
||||
|
||||
@@ -1,257 +0,0 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/csv"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/bytedance/sonic"
|
||||
"github.com/hibiken/asynq"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/storage"
|
||||
)
|
||||
|
||||
// OrderPackageInvalidatePayload 批量失效订单套餐任务载荷
|
||||
type OrderPackageInvalidatePayload struct {
|
||||
TaskID uint `json:"task_id"`
|
||||
}
|
||||
|
||||
// OrderPackageInvalidateHandler 批量失效订单套餐任务处理器
|
||||
type OrderPackageInvalidateHandler struct {
|
||||
taskStore *postgres.OrderPackageInvalidateTaskStore
|
||||
orderStore *postgres.OrderStore
|
||||
packageUsageStore *postgres.PackageUsageStore
|
||||
storageService *storage.Service
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewOrderPackageInvalidateHandler 创建处理器实例
|
||||
func NewOrderPackageInvalidateHandler(
|
||||
taskStore *postgres.OrderPackageInvalidateTaskStore,
|
||||
orderStore *postgres.OrderStore,
|
||||
packageUsageStore *postgres.PackageUsageStore,
|
||||
storageSvc *storage.Service,
|
||||
logger *zap.Logger,
|
||||
) *OrderPackageInvalidateHandler {
|
||||
return &OrderPackageInvalidateHandler{
|
||||
taskStore: taskStore,
|
||||
orderStore: orderStore,
|
||||
packageUsageStore: packageUsageStore,
|
||||
storageService: storageSvc,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Handle 处理批量失效订单套餐任务
|
||||
// POST /api/admin/order-package-invalidate-tasks
|
||||
func (h *OrderPackageInvalidateHandler) Handle(ctx context.Context, t *asynq.Task) error {
|
||||
var payload OrderPackageInvalidatePayload
|
||||
if err := sonic.Unmarshal(t.Payload(), &payload); err != nil {
|
||||
h.logger.Error("解析批量失效任务载荷失败",
|
||||
zap.Error(err),
|
||||
zap.String("task_id", t.ResultWriter().TaskID()),
|
||||
)
|
||||
return asynq.SkipRetry
|
||||
}
|
||||
|
||||
importTask, err := h.taskStore.GetByID(ctx, payload.TaskID)
|
||||
if err != nil {
|
||||
h.logger.Error("获取批量失效任务失败",
|
||||
zap.Uint("task_id", payload.TaskID),
|
||||
zap.Error(err),
|
||||
)
|
||||
return asynq.SkipRetry
|
||||
}
|
||||
|
||||
if importTask.Status != model.ImportTaskStatusPending {
|
||||
h.logger.Info("批量失效任务已处理,跳过",
|
||||
zap.Uint("task_id", payload.TaskID),
|
||||
zap.Int("status", importTask.Status),
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
h.taskStore.UpdateStatus(ctx, importTask.ID, model.ImportTaskStatusProcessing, "")
|
||||
|
||||
h.logger.Info("开始处理批量失效订单套餐任务",
|
||||
zap.Uint("task_id", importTask.ID),
|
||||
zap.String("task_no", importTask.TaskNo),
|
||||
)
|
||||
|
||||
orderNos, err := h.downloadAndParseCSV(ctx, importTask)
|
||||
if err != nil {
|
||||
h.logger.Error("下载或解析 CSV 失败",
|
||||
zap.Uint("task_id", importTask.ID),
|
||||
zap.Error(err),
|
||||
)
|
||||
h.taskStore.UpdateStatus(ctx, importTask.ID, model.ImportTaskStatusFailed, err.Error())
|
||||
return asynq.SkipRetry
|
||||
}
|
||||
|
||||
successCount, failedItems := h.processRows(ctx, orderNos)
|
||||
failCount := len(failedItems)
|
||||
totalCount := len(orderNos)
|
||||
|
||||
h.taskStore.UpdateResult(ctx, importTask.ID, totalCount, successCount, failCount,
|
||||
model.ImportResultItems(toImportResultItems(failedItems)))
|
||||
|
||||
if failCount > 0 && successCount == 0 {
|
||||
h.taskStore.UpdateStatus(ctx, importTask.ID, model.ImportTaskStatusFailed, "所有行均处理失败")
|
||||
} else {
|
||||
h.taskStore.UpdateStatus(ctx, importTask.ID, model.ImportTaskStatusCompleted, "")
|
||||
}
|
||||
|
||||
h.logger.Info("批量失效订单套餐任务完成",
|
||||
zap.Uint("task_id", importTask.ID),
|
||||
zap.Int("total", totalCount),
|
||||
zap.Int("success", successCount),
|
||||
zap.Int("fail", failCount),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// invalidateRow 单行处理结果
|
||||
type invalidateRow struct {
|
||||
line int
|
||||
orderNo string
|
||||
reason string
|
||||
}
|
||||
|
||||
// processRows 逐行处理订单号,返回成功数和失败列表
|
||||
func (h *OrderPackageInvalidateHandler) processRows(ctx context.Context, rows []string) (int, []invalidateRow) {
|
||||
successCount := 0
|
||||
var failed []invalidateRow
|
||||
|
||||
for i, orderNo := range rows {
|
||||
line := i + 2 // 第1行为表头,数据从第2行开始
|
||||
if err := h.processOneOrder(ctx, orderNo); err != nil {
|
||||
failed = append(failed, invalidateRow{line: line, orderNo: orderNo, reason: err.Error()})
|
||||
} else {
|
||||
successCount++
|
||||
}
|
||||
}
|
||||
|
||||
return successCount, failed
|
||||
}
|
||||
|
||||
// processOneOrder 处理单个订单号:查订单 → 查套餐 → 批量更新状态=4
|
||||
func (h *OrderPackageInvalidateHandler) processOneOrder(ctx context.Context, orderNo string) error {
|
||||
order, err := h.orderStore.GetByOrderNo(ctx, orderNo)
|
||||
if err != nil {
|
||||
return errOrderNotFound(orderNo)
|
||||
}
|
||||
|
||||
usages, err := h.packageUsageStore.ListActiveByOrderID(ctx, order.ID)
|
||||
if err != nil {
|
||||
return errQueryFailed(orderNo)
|
||||
}
|
||||
|
||||
if len(usages) == 0 {
|
||||
// 套餐全部已是终态,视为成功
|
||||
return nil
|
||||
}
|
||||
|
||||
ids := make([]uint, 0, len(usages))
|
||||
for _, u := range usages {
|
||||
ids = append(ids, u.ID)
|
||||
}
|
||||
|
||||
if err := h.packageUsageStore.BatchUpdateStatus(ctx, ids, constants.PackageUsageStatusInvalidated); err != nil {
|
||||
return errUpdateFailed(orderNo)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// downloadAndParseCSV 从对象存储下载 CSV 并解析 order_no 列
|
||||
func (h *OrderPackageInvalidateHandler) downloadAndParseCSV(ctx context.Context, task *model.OrderPackageInvalidateTask) ([]string, error) {
|
||||
if h.storageService == nil {
|
||||
return nil, ErrStorageNotConfigured
|
||||
}
|
||||
if task.StorageKey == "" {
|
||||
return nil, ErrStorageKeyEmpty
|
||||
}
|
||||
|
||||
localPath, cleanup, err := h.storageService.DownloadToTemp(ctx, task.StorageKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer cleanup()
|
||||
|
||||
return parseOrderNoCSV(localPath)
|
||||
}
|
||||
|
||||
// parseOrderNoCSV 解析单列 CSV(第一列为 order_no,首行为表头)
|
||||
func parseOrderNoCSV(filePath string) ([]string, error) {
|
||||
f, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
reader := csv.NewReader(f)
|
||||
reader.TrimLeadingSpace = true
|
||||
|
||||
var orderNos []string
|
||||
firstRow := true
|
||||
for {
|
||||
record, err := reader.Read()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if firstRow {
|
||||
firstRow = false
|
||||
continue // 跳过表头
|
||||
}
|
||||
if len(record) == 0 {
|
||||
continue
|
||||
}
|
||||
orderNo := strings.TrimSpace(record[0])
|
||||
if orderNo == "" {
|
||||
continue
|
||||
}
|
||||
orderNos = append(orderNos, orderNo)
|
||||
}
|
||||
|
||||
return orderNos, nil
|
||||
}
|
||||
|
||||
// toImportResultItems 将内部失败记录转换为通用失败明细格式
|
||||
// 复用 ImportResultItem,ICCID 字段存储 order_no
|
||||
func toImportResultItems(rows []invalidateRow) []model.ImportResultItem {
|
||||
items := make([]model.ImportResultItem, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
items = append(items, model.ImportResultItem{
|
||||
Line: r.line,
|
||||
ICCID: r.orderNo,
|
||||
Reason: r.reason,
|
||||
})
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func errOrderNotFound(orderNo string) error {
|
||||
return orderInvalidateError("订单不存在: " + orderNo)
|
||||
}
|
||||
|
||||
func errQueryFailed(orderNo string) error {
|
||||
return orderInvalidateError("查询套餐失败: " + orderNo)
|
||||
}
|
||||
|
||||
func errUpdateFailed(orderNo string) error {
|
||||
return orderInvalidateError("更新套餐状态失败: " + orderNo)
|
||||
}
|
||||
|
||||
type orderInvalidateError string
|
||||
|
||||
func (e orderInvalidateError) Error() string { return string(e) }
|
||||
@@ -9,23 +9,11 @@ import (
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/gateway"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
iot_card_svc "github.com/break/junhong_cmp_fiber/internal/service/iot_card"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
)
|
||||
|
||||
// shouldStopPollingForRisk 判断轮询到风险 gateway_extend 时是否应停止该卡的轮询
|
||||
// 仅独立卡(is_standalone=true)命中风险状态时才停止;绑定设备的卡不受此逻辑约束
|
||||
func shouldStopPollingForRisk(card *model.IotCard, newGatewayExtend string) bool {
|
||||
if !card.IsStandalone {
|
||||
return false
|
||||
}
|
||||
extend := strings.TrimSpace(newGatewayExtend)
|
||||
return extend == constants.GatewayCardExtendRiskStop ||
|
||||
extend == constants.GatewayCardExtendCancelled
|
||||
}
|
||||
|
||||
// PollingCardStatusHandler 卡开停机状态轮询任务处理器
|
||||
// 职责:调 Gateway 查卡状态(正常/停机/准备)→ 映射为 network_status → 写 DB → 触发停复机评估
|
||||
// 不做:直接停复机决策,委托给 StopResumeService.EvaluateAndAct
|
||||
@@ -153,19 +141,6 @@ func (h *PollingCardStatusHandler) Handle(ctx context.Context, t *asynq.Task) er
|
||||
h.base.updateCardCache(ctx, cardID, cacheUpdates)
|
||||
}
|
||||
|
||||
// 独立卡写入风险 gateway_extend 后:关闭轮询,终止循环
|
||||
if statusQueried && shouldStopPollingForRisk(card, gatewayExtend) {
|
||||
if updateErr := h.iotCardStore.UpdatePollingStatus(ctx, cardID, false); updateErr != nil {
|
||||
h.base.logger.Warn("关闭风险卡轮询状态失败",
|
||||
zap.Uint("card_id", cardID), zap.String("gateway_extend", gatewayExtend), zap.Error(updateErr))
|
||||
} else {
|
||||
h.base.logger.Info("独立卡命中风险状态,已关闭轮询",
|
||||
zap.Uint("card_id", cardID), zap.String("gateway_extend", gatewayExtend))
|
||||
}
|
||||
h.base.updateStats(ctx, constants.TaskTypePollingCardStatus, true, time.Since(startTime))
|
||||
return nil // 不再入队,终止轮询循环
|
||||
}
|
||||
|
||||
if statusChanged {
|
||||
h.base.logger.Info("卡状态已变化",
|
||||
zap.Uint("card_id", cardID),
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
)
|
||||
|
||||
// TestShouldStopPolling 验证风险状态独立卡的轮询停止判断逻辑
|
||||
func TestShouldStopPolling(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
isStandalone bool
|
||||
gatewayExtend string
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "独立卡+风险停机 -> 停止轮询",
|
||||
isStandalone: true,
|
||||
gatewayExtend: constants.GatewayCardExtendRiskStop,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "独立卡+已销户 -> 停止轮询",
|
||||
isStandalone: true,
|
||||
gatewayExtend: constants.GatewayCardExtendCancelled,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "非独立卡+风险停机 -> 不停止轮询",
|
||||
isStandalone: false,
|
||||
gatewayExtend: constants.GatewayCardExtendRiskStop,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "独立卡+机卡分离停机 -> 不停止轮询",
|
||||
isStandalone: true,
|
||||
gatewayExtend: constants.GatewayCardExtendMachineSeparated,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "独立卡+空扩展 -> 不停止轮询",
|
||||
isStandalone: true,
|
||||
gatewayExtend: "",
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
card := &model.IotCard{
|
||||
IsStandalone: tc.isStandalone,
|
||||
GatewayExtend: tc.gatewayExtend,
|
||||
}
|
||||
got := shouldStopPollingForRisk(card, tc.gatewayExtend)
|
||||
if got != tc.want {
|
||||
t.Errorf("shouldStopPollingForRisk(standalone=%v, extend=%q) = %v, 期望 %v",
|
||||
tc.isStandalone, tc.gatewayExtend, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
ALTER TABLE tb_iot_card_import_task DROP COLUMN IF EXISTS creator_name;
|
||||
ALTER TABLE tb_device_import_task DROP COLUMN IF EXISTS creator_name;
|
||||
@@ -1,7 +0,0 @@
|
||||
-- 为 IoT 卡导入任务表和设备导入任务表添加操作人快照字段
|
||||
-- 旧记录 creator_name 留空字符串,新任务创建时从登录用户快照姓名
|
||||
ALTER TABLE tb_iot_card_import_task
|
||||
ADD COLUMN IF NOT EXISTS creator_name varchar(100) NOT NULL DEFAULT '';
|
||||
|
||||
ALTER TABLE tb_device_import_task
|
||||
ADD COLUMN IF NOT EXISTS creator_name varchar(100) NOT NULL DEFAULT '';
|
||||
@@ -1,14 +0,0 @@
|
||||
-- 回滚:jsonb 数组 → varchar(500),取第一个元素;空数组 → ''
|
||||
ALTER TABLE tb_order
|
||||
ALTER COLUMN payment_voucher_key TYPE varchar(500)
|
||||
USING COALESCE(payment_voucher_key->>0, '');
|
||||
|
||||
ALTER TABLE tb_refund_request
|
||||
ALTER COLUMN refund_voucher_key TYPE varchar(500)
|
||||
USING COALESCE(refund_voucher_key->>0, '');
|
||||
|
||||
ALTER TABLE tb_agent_recharge_record
|
||||
ALTER COLUMN payment_voucher_key TYPE varchar(500)
|
||||
USING COALESCE(payment_voucher_key->>0, '');
|
||||
|
||||
ALTER TABLE tb_agent_recharge_record DROP COLUMN IF EXISTS remark;
|
||||
@@ -1,38 +0,0 @@
|
||||
-- 将三个表的凭证字段从 varchar(500) 改为 jsonb 数组存储(最多5个元素)
|
||||
-- 同时为代理预充值记录新增 remark 备注字段
|
||||
-- 注意:旧数据可能为逗号分隔多路径,用 string_to_array 拆分为数组元素
|
||||
-- USING 子句中必须显式 ::text 转换,避免 PostgreSQL 隐式将空字符串转 jsonb 报错
|
||||
|
||||
-- tb_order.payment_voucher_key: 空/NULL → [],非空 → 按逗号拆分为数组
|
||||
ALTER TABLE tb_order
|
||||
ALTER COLUMN payment_voucher_key TYPE jsonb
|
||||
USING CASE
|
||||
WHEN payment_voucher_key IS NULL OR payment_voucher_key::text = '' THEN '[]'::jsonb
|
||||
ELSE to_jsonb(string_to_array(payment_voucher_key::text, ','))
|
||||
END;
|
||||
|
||||
-- tb_refund_request.refund_voucher_key: 先删除旧 varchar DEFAULT 再转类型
|
||||
ALTER TABLE tb_refund_request
|
||||
ALTER COLUMN refund_voucher_key DROP DEFAULT;
|
||||
|
||||
ALTER TABLE tb_refund_request
|
||||
ALTER COLUMN refund_voucher_key TYPE jsonb
|
||||
USING CASE
|
||||
WHEN refund_voucher_key IS NULL OR refund_voucher_key::text = '' THEN '[]'::jsonb
|
||||
ELSE to_jsonb(string_to_array(refund_voucher_key::text, ','))
|
||||
END;
|
||||
|
||||
ALTER TABLE tb_refund_request
|
||||
ALTER COLUMN refund_voucher_key SET DEFAULT '[]'::jsonb;
|
||||
|
||||
-- tb_agent_recharge_record.payment_voucher_key: 同 tb_order
|
||||
ALTER TABLE tb_agent_recharge_record
|
||||
ALTER COLUMN payment_voucher_key TYPE jsonb
|
||||
USING CASE
|
||||
WHEN payment_voucher_key IS NULL OR payment_voucher_key::text = '' THEN '[]'::jsonb
|
||||
ELSE to_jsonb(string_to_array(payment_voucher_key::text, ','))
|
||||
END;
|
||||
|
||||
-- tb_agent_recharge_record 新增 remark 备注字段(创建后只读,NULL 表示未填写)
|
||||
ALTER TABLE tb_agent_recharge_record
|
||||
ADD COLUMN IF NOT EXISTS remark text;
|
||||
@@ -1 +0,0 @@
|
||||
DROP TABLE IF EXISTS tb_order_package_invalidate_task;
|
||||
@@ -1,25 +0,0 @@
|
||||
CREATE TABLE IF NOT EXISTS tb_order_package_invalidate_task (
|
||||
id bigserial PRIMARY KEY,
|
||||
task_no varchar(50) NOT NULL UNIQUE,
|
||||
status int NOT NULL DEFAULT 1,
|
||||
total_count int NOT NULL DEFAULT 0,
|
||||
success_count int NOT NULL DEFAULT 0,
|
||||
fail_count int NOT NULL DEFAULT 0,
|
||||
failed_items jsonb NOT NULL DEFAULT '[]',
|
||||
file_name varchar(255) NOT NULL DEFAULT '',
|
||||
storage_key varchar(500) NOT NULL DEFAULT '',
|
||||
voucher_keys jsonb NOT NULL DEFAULT '[]',
|
||||
remark text NOT NULL DEFAULT '',
|
||||
creator_name varchar(100) NOT NULL DEFAULT '',
|
||||
error_message text NOT NULL DEFAULT '',
|
||||
started_at timestamptz,
|
||||
completed_at timestamptz,
|
||||
creator bigint NOT NULL DEFAULT 0,
|
||||
updater bigint NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted_at timestamptz
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_order_pkg_inv_task_status ON tb_order_package_invalidate_task (status) WHERE deleted_at IS NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_order_pkg_inv_task_created_at ON tb_order_package_invalidate_task (created_at DESC) WHERE deleted_at IS NULL;
|
||||
@@ -67,9 +67,6 @@ const (
|
||||
TaskTypePackageQueueActivation = "package:queue:activation" // 主套餐排队激活
|
||||
TaskTypePackageDataReset = "package:data:reset" // 套餐流量重置
|
||||
|
||||
// 订单套餐失效任务类型
|
||||
TaskTypeOrderPackageInvalidate = "order:package:invalidate" // 批量失效订单套餐
|
||||
|
||||
// 订单超时任务类型
|
||||
TaskTypeOrderExpire = "order:expire" // 订单超时自动取消
|
||||
TaskTypeAutoPurchaseAfterRecharge = "task:auto_purchase_after_recharge" // 充值后自动购包
|
||||
@@ -197,7 +194,6 @@ const (
|
||||
QueuePackageFirstActivation = TaskTypePackageFirstActivation // 首次实名激活任务队列
|
||||
QueuePackageQueueActivation = TaskTypePackageQueueActivation // 主套餐排队激活任务队列
|
||||
QueuePackageDataReset = TaskTypePackageDataReset // 套餐流量重置任务队列
|
||||
QueueOrderPackageInvalidate = TaskTypeOrderPackageInvalidate // 批量失效订单套餐任务队列
|
||||
QueueOrderExpire = TaskTypeOrderExpire // 订单超时取消任务队列
|
||||
QueueAutoPurchase = TaskTypeAutoPurchaseAfterRecharge // 充值后自动购包任务队列
|
||||
QueueAlertCheck = TaskTypeAlertCheck // 告警检查任务队列
|
||||
@@ -248,8 +244,6 @@ func QueueForTaskType(taskType string) string {
|
||||
return QueuePackageQueueActivation
|
||||
case TaskTypePackageDataReset:
|
||||
return QueuePackageDataReset
|
||||
case TaskTypeOrderPackageInvalidate:
|
||||
return QueueOrderPackageInvalidate
|
||||
case TaskTypeOrderExpire:
|
||||
return QueueOrderExpire
|
||||
case TaskTypeAutoPurchaseAfterRecharge:
|
||||
@@ -274,7 +268,6 @@ func DefaultTaskQueueWeights() map[string]int {
|
||||
QueueAutoPurchase: 5,
|
||||
QueuePackageFirstActivation: 5,
|
||||
QueuePackageQueueActivation: 5,
|
||||
QueueOrderPackageInvalidate: 5,
|
||||
QueueOrderExpire: 4,
|
||||
QueueEmailSend: 4,
|
||||
QueueExportDispatch: 4,
|
||||
|
||||
@@ -60,11 +60,9 @@ const (
|
||||
GatewayCardStatusReady = "准备" // 网关卡状态:准备
|
||||
GatewayCardStatusNormal = "正常" // 网关卡状态:正常
|
||||
GatewayCardStatusStopped = "停机" // 网关卡状态:停机
|
||||
GatewayCardExtendPendingActivation = "待激活" // 网关扩展状态:待激活
|
||||
GatewayCardExtendMachineSeparated = "机卡分离停机" // 网关扩展状态:机卡分离停机
|
||||
GatewayCardExtendPendingActivation = "待激活" // 网关扩展状态:待激活
|
||||
GatewayCardExtendMachineSeparated = "机卡分离停机" // 网关扩展状态:机卡分离停机
|
||||
GatewayCardStartExtendMachineSeparated = "2" // 机卡分离复机时上传给运营商的 extend 值
|
||||
GatewayCardExtendRiskStop = "风险停机" // 网关扩展状态:运营商风险停机(独立卡不允许复机)
|
||||
GatewayCardExtendCancelled = "已销户" // 网关扩展状态:已销户(独立卡不允许复机)
|
||||
)
|
||||
|
||||
// IoT 卡停机原因
|
||||
|
||||
@@ -98,7 +98,6 @@ const (
|
||||
RechargeStatusCompleted = 3 // 已完成
|
||||
RechargeStatusClosed = 4 // 已关闭
|
||||
RechargeStatusRefunded = 5 // 已退款
|
||||
RechargeStatusRejected = 6 // 已驳回
|
||||
)
|
||||
|
||||
// 充值支付方式
|
||||
@@ -122,7 +121,7 @@ const (
|
||||
// ========== Redis Key 生成函数 ==========
|
||||
|
||||
// GetRechargeStatusName 获取充值状态名称
|
||||
// 对应 RechargeStatus* 常量:1=待支付, 2=已支付, 3=已完成, 4=已关闭, 5=已退款, 6=已驳回
|
||||
// 对应 RechargeStatus* 常量:1=待支付, 2=已支付, 3=已完成, 4=已关闭, 5=已退款
|
||||
func GetRechargeStatusName(status int) string {
|
||||
switch status {
|
||||
case RechargeStatusPending:
|
||||
@@ -135,8 +134,6 @@ func GetRechargeStatusName(status int) string {
|
||||
return "已关闭"
|
||||
case RechargeStatusRefunded:
|
||||
return "已退款"
|
||||
case RechargeStatusRejected:
|
||||
return "已驳回"
|
||||
default:
|
||||
return "未知"
|
||||
}
|
||||
|
||||
@@ -64,7 +64,6 @@ func BuildDocHandlers() *bootstrap.Handlers {
|
||||
WechatConfig: admin.NewWechatConfigHandler(nil),
|
||||
AgentRecharge: admin.NewAgentRechargeHandler(nil, nil),
|
||||
Refund: admin.NewRefundHandler(nil),
|
||||
OrderPackageInvalidate: admin.NewOrderPackageInvalidateHandler(nil),
|
||||
ClientWechat: app.NewClientWechatHandler(nil, nil, nil),
|
||||
SuperAdmin: admin.NewSuperAdminHandler(nil),
|
||||
AgentOpenAPI: openapiHandler.NewHandler(nil, nil),
|
||||
|
||||
@@ -65,7 +65,6 @@ func (h *Handler) RegisterHandlers() *asynq.ServeMux {
|
||||
|
||||
h.registerIotCardImportHandler()
|
||||
h.registerDeviceImportHandler()
|
||||
h.registerOrderPackageInvalidateHandler()
|
||||
h.registerExportHandlers()
|
||||
h.registerCommissionStatsHandlers()
|
||||
h.registerCommissionCalculationHandler()
|
||||
@@ -98,18 +97,6 @@ func (h *Handler) registerIotCardImportHandler() {
|
||||
h.logger.Info("注册 IoT 卡导入任务处理器", zap.String("task_type", constants.TaskTypeIotCardImport))
|
||||
}
|
||||
|
||||
func (h *Handler) registerOrderPackageInvalidateHandler() {
|
||||
orderPkgHandler := task.NewOrderPackageInvalidateHandler(
|
||||
h.workerResult.Stores.OrderPackageInvalidateTask,
|
||||
h.workerResult.Stores.Order,
|
||||
h.workerResult.Stores.PackageUsage,
|
||||
h.storage,
|
||||
h.logger,
|
||||
)
|
||||
h.mux.HandleFunc(constants.TaskTypeOrderPackageInvalidate, orderPkgHandler.Handle)
|
||||
h.logger.Info("注册订单套餐批量失效任务处理器", zap.String("task_type", constants.TaskTypeOrderPackageInvalidate))
|
||||
}
|
||||
|
||||
func (h *Handler) registerDeviceImportHandler() {
|
||||
deviceImportHandler := task.NewDeviceImportHandler(
|
||||
h.db,
|
||||
|
||||
@@ -46,9 +46,8 @@ type WorkerStores struct {
|
||||
AgentWalletTransaction *postgres.AgentWalletTransactionStore
|
||||
AssetWallet *postgres.AssetWalletStore
|
||||
AssetIdentifier *postgres.AssetIdentifierStore
|
||||
PersonalCustomer *postgres.PersonalCustomerStore
|
||||
PersonalCustomerPhone *postgres.PersonalCustomerPhoneStore
|
||||
OrderPackageInvalidateTask *postgres.OrderPackageInvalidateTaskStore
|
||||
PersonalCustomer *postgres.PersonalCustomerStore
|
||||
PersonalCustomerPhone *postgres.PersonalCustomerPhoneStore
|
||||
}
|
||||
|
||||
// WorkerServices Worker 侧所有 Service 的集合
|
||||
|
||||
Reference in New Issue
Block a user