commit c3fe52c1ee9ee9e4048c40caa9aa816720a0a3e1 Author: zxp <2798801627@q.com> Date: Wed Oct 28 11:45:28 2026 +0800 feat: 完成财务中台核心功能与前后端基础设施搭建 diff --git a/.runtime/redis.err.log b/.runtime/redis.err.log new file mode 100644 index 0000000..e69de29 diff --git a/.runtime/redis.out.log b/.runtime/redis.out.log new file mode 100644 index 0000000..03c528f --- /dev/null +++ b/.runtime/redis.out.log @@ -0,0 +1,10 @@ +1627:C 28 Oct 2026 09:32:16.207 * oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo +1627:C 28 Oct 2026 09:32:16.209 * Redis version=8.10.1, bits=64, commit=00000000, modified=0, pid=1627, just started +1627:C 28 Oct 2026 09:32:16.209 * Configuration loaded +1627:M 28 Oct 2026 09:32:16.212 # You requested maxclients of 10000 requiring at least 10032 max file descriptors. +1627:M 28 Oct 2026 09:32:16.213 # Server can't set maximum open files to 10032 because of OS error: Operation not permitted. +1627:M 28 Oct 2026 09:32:16.214 # Current maximum open files is 3200. maxclients has been reduced to 3168 to compensate for low ulimit. If you need higher maxclients increase 'ulimit -n'. +1627:M 28 Oct 2026 09:32:16.214 * monotonic clock: POSIX clock_gettime +1627:M 28 Oct 2026 09:32:16.215 * Running mode=standalone, port=6379. +1627:M 28 Oct 2026 09:32:16.228 * Server initialized +1627:M 28 Oct 2026 09:32:16.231 * Ready to accept connections tcp diff --git a/finance-pkg.zip b/finance-pkg.zip new file mode 100644 index 0000000..422f304 Binary files /dev/null and b/finance-pkg.zip differ diff --git a/finance-pkg/deploy/backup.sh b/finance-pkg/deploy/backup.sh new file mode 100644 index 0000000..eeff7ec --- /dev/null +++ b/finance-pkg/deploy/backup.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# 财务系统每日备份(CentOS) +# 依赖 /etc/finance/backup.cnf(chmod 600),内容示例: +# [client] +# host=127.0.0.1 +# port=3307 +# user=fin_migrate +# password=替换成密码 +set -euo pipefail +umask 077 + +BACKUP_DIR="${BACKUP_DIR:-/data/backup}" +KEEP_DAYS="${KEEP_DAYS:-30}" +DB_NAME="${DB_NAME:-fin_platform}" +MYSQL_DEFAULTS="${MYSQL_DEFAULTS:-/etc/finance/backup.cnf}" +STAMP="$(date +%F_%H%M%S)" + +mkdir -p "${BACKUP_DIR}" + +echo "[1/2] 备份 MySQL ${DB_NAME}" +mysqldump --defaults-extra-file="${MYSQL_DEFAULTS}" \ + --single-transaction --routines --triggers --events \ + "${DB_NAME}" | gzip > "${BACKUP_DIR}/fin_platform_${STAMP}.sql.gz" + +echo "[2/2] 备份配置与加密密钥" +tar czf "${BACKUP_DIR}/finance_conf_${STAMP}.tgz" \ + /etc/finance/finance.env \ + /data/finance/runtime/secret-enc.key \ + /opt/finance/finance-server-1.0.0.jar + +find "${BACKUP_DIR}" -type f -mtime +"${KEEP_DAYS}" -delete +echo "备份完成: ${BACKUP_DIR}" diff --git a/finance-pkg/deploy/finance.env.example b/finance-pkg/deploy/finance.env.example new file mode 100644 index 0000000..fa78d65 --- /dev/null +++ b/finance-pkg/deploy/finance.env.example @@ -0,0 +1,39 @@ +# 财务系统生产环境变量模板(CentOS + 现有 MySQL 3307 / Redis 6280) +# 复制到 /etc/finance/finance.env,chmod 600 +# 密码中如含 # 等特殊字符,必须用单引号包起来 + +SPRING_PROFILES_ACTIVE=prod +SERVER_ADDRESS=127.0.0.1 +SERVER_PORT=8080 +SERVER_MANAGEMENT_PORT=8081 + +# 与 MySQL 同机时用 127.0.0.1;跨机改成 www.zhulongtech.com +FIN_DB_HOST=127.0.0.1 +FIN_DB_PORT=3307 +FIN_DB_NAME=fin_platform +# 推荐新建 fin_app / fin_migrate;若临时用 root,则把两项都改成 root 并填 application-prod.yaml 的密码 +FIN_DB_USER=fin_app +FIN_DB_PASSWORD='<新生成的 fin_app 密码>' +FIN_FLYWAY_USER=fin_migrate +FIN_FLYWAY_PASSWORD='<新生成的 fin_migrate 密码>' +FIN_DB_POOL_MAX=20 + +# 复用现有 Redis,使用独立 db2,避免与数据中台 db0/db1 冲突 +FIN_REDIS_HOST=127.0.0.1 +FIN_REDIS_PORT=6280 +FIN_REDIS_PASSWORD='<从 application-prod.yaml 复制 Redis 密码>' +FIN_REDIS_DB=2 + +# 财务系统独立密钥:openssl rand -base64 32 +FIN_SECRET_ENC_KEY='<32 字节 Base64 密钥>' +FIN_RUNTIME_DIR=/data/finance/runtime +FIN_ALLOWED_ORIGINS=https://www.zhulongtech.com:8443 +FIN_TRUST_PROXY=1 +FIN_DEMO_TICKET_ENABLED=0 +FIN_WORKER_ID=0 + +# 首次启动保持 1;拿到 admin 初始凭据并完成改密/TOTP 后改为 0 +FIN_BOOTSTRAP_ADMIN_ENABLED=1 +FIN_TOTP_OUTPUT_ENABLED=1 + +LOGGING_FILE_NAME=/var/log/finance/finance.log diff --git a/finance-pkg/deploy/finance.service b/finance-pkg/deploy/finance.service new file mode 100644 index 0000000..f18daca --- /dev/null +++ b/finance-pkg/deploy/finance.service @@ -0,0 +1,27 @@ +[Unit] +Description=Finance API (Central Billing Platform) +After=network-online.target +Wants=network-online.target +# 如果 MySQL / Redis 由 systemd 管理,按实际服务名取消注释: +# After=mysqld.service redis.service +# Wants=mysqld.service redis.service + +[Service] +Type=simple +User=finance +Group=finance +WorkingDirectory=/opt/finance +EnvironmentFile=/etc/finance/finance.env +ExecStart=/usr/bin/java -server -Xms2g -Xmx2g -XX:+UseG1GC \ + -XX:MaxGCPauseMillis=200 \ + -Duser.timezone=Asia/Shanghai -Dfile.encoding=UTF-8 \ + -jar /opt/finance/finance-server-1.0.0.jar +SuccessExitStatus=143 +Restart=always +RestartSec=5 +LimitNOFILE=65535 +NoNewPrivileges=true +PrivateTmp=true + +[Install] +WantedBy=multi-user.target diff --git a/finance-pkg/deploy/nginx-finance.conf b/finance-pkg/deploy/nginx-finance.conf new file mode 100644 index 0000000..e8f1ed1 --- /dev/null +++ b/finance-pkg/deploy/nginx-finance.conf @@ -0,0 +1,70 @@ +# 财务系统 Nginx 配置(CentOS,同一台机器,复用 www.zhulongtech.com 证书,独立 8443 端口) +# 放到 /etc/nginx/conf.d/finance.conf +# 说明: +# 1. 现有 443 的 www/data 中台配置保持不变; +# 2. 财务系统只监听 8443,证书复用现有 www.zhulongtech.com 证书; +# 3. 证书路径请从现有 443 server 块复制,可用 nginx -T | grep ssl_certificate 查找。 + +limit_req_zone $binary_remote_addr zone=finance_login:10m rate=5r/m; + +server { + listen 8443 ssl http2; + server_name www.zhulongtech.com; + + # 改成现有 443 配置中 www.zhulongtech.com 的证书路径 + ssl_certificate /etc/nginx/ssl/www.zhulongtech.com.crt; + ssl_certificate_key /etc/nginx/ssl/www.zhulongtech.com.key; + # CentOS 7 自带 OpenSSL 1.0.2 不支持 TLS1.3;若系统是 CentOS Stream 8/9 可改为 TLSv1.2 TLSv1.3 + ssl_protocols TLSv1.2; + ssl_prefer_server_ciphers off; + + server_tokens off; + client_max_body_size 1m; + + add_header X-Content-Type-Options nosniff always; + add_header X-Frame-Options DENY always; + add_header Referrer-Policy no-referrer always; + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + + root /var/www/finance; + index index.html; + + location / { + try_files $uri $uri/ /index.html; + } + + location = /index.html { + add_header Cache-Control "no-store"; + } + + location ~* \.(js|css|png|jpg|jpeg|gif|svg|ico|woff2?)$ { + expires 30d; + access_log off; + } + + # 登录接口单独限流 + location = /api/admin/login { + limit_req zone=finance_login burst=5 nodelay; + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 30s; + } + + location /api/ { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 30s; + } + + location /actuator/ { + deny all; + } +} diff --git a/finance-pkg/finance-server-1.0.0.jar b/finance-pkg/finance-server-1.0.0.jar new file mode 100644 index 0000000..84cedc6 Binary files /dev/null and b/finance-pkg/finance-server-1.0.0.jar differ diff --git a/finance-pkg/sql/security_grants.sql b/finance-pkg/sql/security_grants.sql new file mode 100644 index 0000000..597558e --- /dev/null +++ b/finance-pkg/sql/security_grants.sql @@ -0,0 +1,28 @@ +-- 运行时账号最小权限(需在 Flyway 建表完成后由 DBA/root 执行一次) +-- 目的:应用账号对 fin_audit_log 只允许 INSERT/SELECT,禁止 UPDATE/DELETE(应对审计删除攻击用例)。 +REVOKE SELECT, INSERT, UPDATE, DELETE ON fin_platform.* FROM 'fin_app'@'localhost'; + +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_admin TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_admin_password_history TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_admin_session TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_app TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_app_secret TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_app_token TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_account TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_transaction TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_order TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_cash_ledger TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_refund TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_vip_plan TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_vip_holder TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_app_pricing TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_app_policy TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_config TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT ON fin_platform.fin_audit_log TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_webhook_delivery TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_reconcile_report TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_reconcile_diff TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_ticket TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_rate_limit TO 'fin_app'@'localhost'; + +FLUSH PRIVILEGES; diff --git a/finance-server/.gitignore b/finance-server/.gitignore new file mode 100644 index 0000000..9004b51 --- /dev/null +++ b/finance-server/.gitignore @@ -0,0 +1,7 @@ +target/ +.idea/ +*.iml +*.log +.runtime/ +.env +.env.local diff --git a/finance-server/deploy/backup.sh b/finance-server/deploy/backup.sh new file mode 100644 index 0000000..eeff7ec --- /dev/null +++ b/finance-server/deploy/backup.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# 财务系统每日备份(CentOS) +# 依赖 /etc/finance/backup.cnf(chmod 600),内容示例: +# [client] +# host=127.0.0.1 +# port=3307 +# user=fin_migrate +# password=替换成密码 +set -euo pipefail +umask 077 + +BACKUP_DIR="${BACKUP_DIR:-/data/backup}" +KEEP_DAYS="${KEEP_DAYS:-30}" +DB_NAME="${DB_NAME:-fin_platform}" +MYSQL_DEFAULTS="${MYSQL_DEFAULTS:-/etc/finance/backup.cnf}" +STAMP="$(date +%F_%H%M%S)" + +mkdir -p "${BACKUP_DIR}" + +echo "[1/2] 备份 MySQL ${DB_NAME}" +mysqldump --defaults-extra-file="${MYSQL_DEFAULTS}" \ + --single-transaction --routines --triggers --events \ + "${DB_NAME}" | gzip > "${BACKUP_DIR}/fin_platform_${STAMP}.sql.gz" + +echo "[2/2] 备份配置与加密密钥" +tar czf "${BACKUP_DIR}/finance_conf_${STAMP}.tgz" \ + /etc/finance/finance.env \ + /data/finance/runtime/secret-enc.key \ + /opt/finance/finance-server-1.0.0.jar + +find "${BACKUP_DIR}" -type f -mtime +"${KEEP_DAYS}" -delete +echo "备份完成: ${BACKUP_DIR}" diff --git a/finance-server/deploy/finance.env.example b/finance-server/deploy/finance.env.example new file mode 100644 index 0000000..fa78d65 --- /dev/null +++ b/finance-server/deploy/finance.env.example @@ -0,0 +1,39 @@ +# 财务系统生产环境变量模板(CentOS + 现有 MySQL 3307 / Redis 6280) +# 复制到 /etc/finance/finance.env,chmod 600 +# 密码中如含 # 等特殊字符,必须用单引号包起来 + +SPRING_PROFILES_ACTIVE=prod +SERVER_ADDRESS=127.0.0.1 +SERVER_PORT=8080 +SERVER_MANAGEMENT_PORT=8081 + +# 与 MySQL 同机时用 127.0.0.1;跨机改成 www.zhulongtech.com +FIN_DB_HOST=127.0.0.1 +FIN_DB_PORT=3307 +FIN_DB_NAME=fin_platform +# 推荐新建 fin_app / fin_migrate;若临时用 root,则把两项都改成 root 并填 application-prod.yaml 的密码 +FIN_DB_USER=fin_app +FIN_DB_PASSWORD='<新生成的 fin_app 密码>' +FIN_FLYWAY_USER=fin_migrate +FIN_FLYWAY_PASSWORD='<新生成的 fin_migrate 密码>' +FIN_DB_POOL_MAX=20 + +# 复用现有 Redis,使用独立 db2,避免与数据中台 db0/db1 冲突 +FIN_REDIS_HOST=127.0.0.1 +FIN_REDIS_PORT=6280 +FIN_REDIS_PASSWORD='<从 application-prod.yaml 复制 Redis 密码>' +FIN_REDIS_DB=2 + +# 财务系统独立密钥:openssl rand -base64 32 +FIN_SECRET_ENC_KEY='<32 字节 Base64 密钥>' +FIN_RUNTIME_DIR=/data/finance/runtime +FIN_ALLOWED_ORIGINS=https://www.zhulongtech.com:8443 +FIN_TRUST_PROXY=1 +FIN_DEMO_TICKET_ENABLED=0 +FIN_WORKER_ID=0 + +# 首次启动保持 1;拿到 admin 初始凭据并完成改密/TOTP 后改为 0 +FIN_BOOTSTRAP_ADMIN_ENABLED=1 +FIN_TOTP_OUTPUT_ENABLED=1 + +LOGGING_FILE_NAME=/var/log/finance/finance.log diff --git a/finance-server/deploy/finance.service b/finance-server/deploy/finance.service new file mode 100644 index 0000000..f18daca --- /dev/null +++ b/finance-server/deploy/finance.service @@ -0,0 +1,27 @@ +[Unit] +Description=Finance API (Central Billing Platform) +After=network-online.target +Wants=network-online.target +# 如果 MySQL / Redis 由 systemd 管理,按实际服务名取消注释: +# After=mysqld.service redis.service +# Wants=mysqld.service redis.service + +[Service] +Type=simple +User=finance +Group=finance +WorkingDirectory=/opt/finance +EnvironmentFile=/etc/finance/finance.env +ExecStart=/usr/bin/java -server -Xms2g -Xmx2g -XX:+UseG1GC \ + -XX:MaxGCPauseMillis=200 \ + -Duser.timezone=Asia/Shanghai -Dfile.encoding=UTF-8 \ + -jar /opt/finance/finance-server-1.0.0.jar +SuccessExitStatus=143 +Restart=always +RestartSec=5 +LimitNOFILE=65535 +NoNewPrivileges=true +PrivateTmp=true + +[Install] +WantedBy=multi-user.target diff --git a/finance-server/deploy/nginx-finance.conf b/finance-server/deploy/nginx-finance.conf new file mode 100644 index 0000000..e8f1ed1 --- /dev/null +++ b/finance-server/deploy/nginx-finance.conf @@ -0,0 +1,70 @@ +# 财务系统 Nginx 配置(CentOS,同一台机器,复用 www.zhulongtech.com 证书,独立 8443 端口) +# 放到 /etc/nginx/conf.d/finance.conf +# 说明: +# 1. 现有 443 的 www/data 中台配置保持不变; +# 2. 财务系统只监听 8443,证书复用现有 www.zhulongtech.com 证书; +# 3. 证书路径请从现有 443 server 块复制,可用 nginx -T | grep ssl_certificate 查找。 + +limit_req_zone $binary_remote_addr zone=finance_login:10m rate=5r/m; + +server { + listen 8443 ssl http2; + server_name www.zhulongtech.com; + + # 改成现有 443 配置中 www.zhulongtech.com 的证书路径 + ssl_certificate /etc/nginx/ssl/www.zhulongtech.com.crt; + ssl_certificate_key /etc/nginx/ssl/www.zhulongtech.com.key; + # CentOS 7 自带 OpenSSL 1.0.2 不支持 TLS1.3;若系统是 CentOS Stream 8/9 可改为 TLSv1.2 TLSv1.3 + ssl_protocols TLSv1.2; + ssl_prefer_server_ciphers off; + + server_tokens off; + client_max_body_size 1m; + + add_header X-Content-Type-Options nosniff always; + add_header X-Frame-Options DENY always; + add_header Referrer-Policy no-referrer always; + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + + root /var/www/finance; + index index.html; + + location / { + try_files $uri $uri/ /index.html; + } + + location = /index.html { + add_header Cache-Control "no-store"; + } + + location ~* \.(js|css|png|jpg|jpeg|gif|svg|ico|woff2?)$ { + expires 30d; + access_log off; + } + + # 登录接口单独限流 + location = /api/admin/login { + limit_req zone=finance_login burst=5 nodelay; + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 30s; + } + + location /api/ { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 30s; + } + + location /actuator/ { + deny all; + } +} diff --git a/finance-server/pom.xml b/finance-server/pom.xml new file mode 100644 index 0000000..3c69d1c --- /dev/null +++ b/finance-server/pom.xml @@ -0,0 +1,93 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.3.5 + + + + com.gas + finance-server + 1.0.0 + finance-server + 中央计费平台后端 + + + 17 + 3.5.7 + 10.20.1 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-data-redis + + + + com.baomidou + mybatis-plus-spring-boot3-starter + ${mybatis-plus.version} + + + com.mysql + mysql-connector-j + runtime + + + org.flywaydb + flyway-core + + + org.flywaydb + flyway-mysql + + + + org.springframework.security + spring-security-crypto + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/finance-server/sql/security_grants.sql b/finance-server/sql/security_grants.sql new file mode 100644 index 0000000..597558e --- /dev/null +++ b/finance-server/sql/security_grants.sql @@ -0,0 +1,28 @@ +-- 运行时账号最小权限(需在 Flyway 建表完成后由 DBA/root 执行一次) +-- 目的:应用账号对 fin_audit_log 只允许 INSERT/SELECT,禁止 UPDATE/DELETE(应对审计删除攻击用例)。 +REVOKE SELECT, INSERT, UPDATE, DELETE ON fin_platform.* FROM 'fin_app'@'localhost'; + +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_admin TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_admin_password_history TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_admin_session TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_app TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_app_secret TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_app_token TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_account TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_transaction TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_order TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_cash_ledger TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_refund TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_vip_plan TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_vip_holder TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_app_pricing TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_app_policy TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_config TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT ON fin_platform.fin_audit_log TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_webhook_delivery TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_reconcile_report TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_reconcile_diff TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_ticket TO 'fin_app'@'localhost'; +GRANT SELECT, INSERT, UPDATE, DELETE ON fin_platform.fin_rate_limit TO 'fin_app'@'localhost'; + +FLUSH PRIVILEGES; diff --git a/finance-server/src/main/java/com/gas/fin/FinanceApplication.java b/finance-server/src/main/java/com/gas/fin/FinanceApplication.java new file mode 100644 index 0000000..d5084dd --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/FinanceApplication.java @@ -0,0 +1,12 @@ +package com.gas.fin; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class FinanceApplication { + + public static void main(String[] args) { + SpringApplication.run(FinanceApplication.class, args); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/account/controller/AccountController.java b/finance-server/src/main/java/com/gas/fin/account/controller/AccountController.java new file mode 100644 index 0000000..600fb63 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/account/controller/AccountController.java @@ -0,0 +1,64 @@ +package com.gas.fin.account.controller; + +import com.gas.fin.account.dto.AccountAdjustRequest; +import com.gas.fin.account.dto.AccountDetailResponse; +import com.gas.fin.account.dto.AccountInfoResponse; +import com.gas.fin.account.service.AccountService; +import com.gas.fin.common.api.PageResult; +import com.gas.fin.common.api.R; +import com.gas.fin.common.security.AuthContext; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.security.RequirePermission; +import com.gas.fin.transaction.dto.TransactionInfoResponse; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/admin/accounts") +public class AccountController { + + private final AccountService accountService; + + public AccountController(AccountService accountService) { + this.accountService = accountService; + } + + @GetMapping + @RequirePermission(PermissionRegistry.VIEW) + public R> list( + @RequestParam(defaultValue = "1") long page, + @RequestParam(defaultValue = "20") long pageSize, + @RequestParam(required = false) String appCode, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) Long minBalance) { + return R.ok(accountService.page(page, pageSize, appCode, keyword, minBalance)); + } + + @GetMapping("/{id}") + @RequirePermission(PermissionRegistry.VIEW) + public R detail(@PathVariable Long id) { + return R.ok(accountService.detail(id)); + } + + @GetMapping("/{id}/transactions") + @RequirePermission(PermissionRegistry.VIEW) + public R> transactions( + @PathVariable Long id, + @RequestParam(defaultValue = "1") long page, + @RequestParam(defaultValue = "20") long pageSize) { + return R.ok(accountService.transactions(id, page, pageSize)); + } + + @PostMapping("/adjust") + @RequirePermission(PermissionRegistry.ACCOUNT_ADJUST) + public R adjust(@RequestBody AccountAdjustRequest request, + HttpServletRequest httpRequest) { + return R.ok(accountService.adjust(request, AuthContext.require(), httpRequest)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/account/dto/AccountAdjustRequest.java b/finance-server/src/main/java/com/gas/fin/account/dto/AccountAdjustRequest.java new file mode 100644 index 0000000..2fb55fa --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/account/dto/AccountAdjustRequest.java @@ -0,0 +1,5 @@ +package com.gas.fin.account.dto; + +public record AccountAdjustRequest(String appCode, String businessUserId, Long amount, String direction, + String reason, Long secondApproverId, String totp) { +} diff --git a/finance-server/src/main/java/com/gas/fin/account/dto/AccountDetailResponse.java b/finance-server/src/main/java/com/gas/fin/account/dto/AccountDetailResponse.java new file mode 100644 index 0000000..0ee8803 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/account/dto/AccountDetailResponse.java @@ -0,0 +1,14 @@ +package com.gas.fin.account.dto; + +import com.gas.fin.transaction.dto.TransactionInfoResponse; + +import java.time.LocalDateTime; +import java.util.List; + +public record AccountDetailResponse(AccountInfoResponse account, VipDetail vip, + List transactions) { + + public record VipDetail(String planCode, String planName, LocalDateTime vipUntil, + boolean effective, Integer freeDeduction) { + } +} diff --git a/finance-server/src/main/java/com/gas/fin/account/dto/AccountInfoResponse.java b/finance-server/src/main/java/com/gas/fin/account/dto/AccountInfoResponse.java new file mode 100644 index 0000000..89d8b74 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/account/dto/AccountInfoResponse.java @@ -0,0 +1,42 @@ +package com.gas.fin.account.dto; + +import com.gas.fin.account.entity.AccountEntity; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class AccountInfoResponse { + + private Long id; + private String appCode; + private String appName; + private String businessUserId; + private String usernameSnapshot; + private String phoneMasked; + private Long balance; + private Long totalSpent; + private Integer versionNo; + private String vipPlanCode; + private LocalDateTime vipUntil; + private LocalDateTime createTime; + private LocalDateTime updateTime; + + public static AccountInfoResponse from(AccountEntity entity, String appName) { + AccountInfoResponse response = new AccountInfoResponse(); + response.setId(entity.getId()); + response.setAppCode(entity.getAppCode()); + response.setAppName(appName == null ? entity.getAppCode() : appName); + response.setBusinessUserId(entity.getBusinessUserId()); + response.setUsernameSnapshot(entity.getUsernameSnapshot()); + response.setPhoneMasked(entity.getPhoneMasked()); + response.setBalance(entity.getBalance()); + response.setTotalSpent(entity.getTotalSpent()); + response.setVersionNo(entity.getVersionNo()); + response.setVipPlanCode(entity.getVipPlanCode()); + response.setVipUntil(entity.getVipUntil()); + response.setCreateTime(entity.getCreateTime()); + response.setUpdateTime(entity.getUpdateTime()); + return response; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/account/entity/AccountEntity.java b/finance-server/src/main/java/com/gas/fin/account/entity/AccountEntity.java new file mode 100644 index 0000000..8688ad6 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/account/entity/AccountEntity.java @@ -0,0 +1,31 @@ +package com.gas.fin.account.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_account") +public class AccountEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String appCode; + private String businessUserId; + private String usernameSnapshot; + private String phoneMasked; + private String phoneHash; + private Long balance; + private Long totalSpent; + private Integer versionNo; + private String vipPlanCode; + private LocalDateTime vipUntil; + private String status; + private LocalDateTime firstSeenAt; + private LocalDateTime createTime; + private LocalDateTime updateTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/account/mapper/AccountMapper.java b/finance-server/src/main/java/com/gas/fin/account/mapper/AccountMapper.java new file mode 100644 index 0000000..37a7a8f --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/account/mapper/AccountMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.account.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.account.entity.AccountEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface AccountMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/account/service/AccountService.java b/finance-server/src/main/java/com/gas/fin/account/service/AccountService.java new file mode 100644 index 0000000..7876f87 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/account/service/AccountService.java @@ -0,0 +1,237 @@ +package com.gas.fin.account.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.gas.fin.account.dto.AccountAdjustRequest; +import com.gas.fin.account.dto.AccountDetailResponse; +import com.gas.fin.account.dto.AccountInfoResponse; +import com.gas.fin.account.entity.AccountEntity; +import com.gas.fin.account.mapper.AccountMapper; +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.admin.mapper.AdminMapper; +import com.gas.fin.app.entity.AppEntity; +import com.gas.fin.app.mapper.AppMapper; +import com.gas.fin.common.api.PageResult; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.id.FinIdGenerator; +import com.gas.fin.common.security.AdminAuditor; +import com.gas.fin.common.security.TotpVerifier; +import com.gas.fin.common.web.QueryUtils; +import com.gas.fin.transaction.dto.TransactionInfoResponse; +import com.gas.fin.transaction.entity.TransactionEntity; +import com.gas.fin.transaction.mapper.TransactionMapper; +import com.gas.fin.vip.entity.VipHolderEntity; +import com.gas.fin.vip.entity.VipPlanEntity; +import com.gas.fin.vip.mapper.VipHolderMapper; +import com.gas.fin.vip.mapper.VipPlanMapper; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 业务用户钱包:查询与人工调账。 + */ +@Service +public class AccountService { + + private final AccountMapper accountMapper; + private final TransactionMapper transactionMapper; + private final VipHolderMapper vipHolderMapper; + private final VipPlanMapper vipPlanMapper; + private final AdminMapper adminMapper; + private final AppMapper appMapper; + private final FinIdGenerator idGenerator; + private final TotpVerifier totpVerifier; + private final AdminAuditor adminAuditor; + + public AccountService(AccountMapper accountMapper, TransactionMapper transactionMapper, + VipHolderMapper vipHolderMapper, VipPlanMapper vipPlanMapper, + AdminMapper adminMapper, AppMapper appMapper, FinIdGenerator idGenerator, + TotpVerifier totpVerifier, AdminAuditor adminAuditor) { + this.accountMapper = accountMapper; + this.transactionMapper = transactionMapper; + this.vipHolderMapper = vipHolderMapper; + this.vipPlanMapper = vipPlanMapper; + this.adminMapper = adminMapper; + this.appMapper = appMapper; + this.idGenerator = idGenerator; + this.totpVerifier = totpVerifier; + this.adminAuditor = adminAuditor; + } + + public PageResult page(long page, long pageSize, String appCode, String keyword, + Long minBalance) { + QueryUtils.checkPage(page, pageSize); + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (appCode != null && !appCode.isBlank()) { + wrapper.eq(AccountEntity::getAppCode, appCode.trim()); + } + if (keyword != null && !keyword.isBlank()) { + String value = keyword.trim(); + wrapper.and(w -> w.like(AccountEntity::getBusinessUserId, value) + .or().like(AccountEntity::getUsernameSnapshot, value) + .or().like(AccountEntity::getPhoneMasked, value)); + } + if (minBalance != null) { + wrapper.ge(AccountEntity::getBalance, minBalance); + } + wrapper.orderByDesc(AccountEntity::getBalance).orderByAsc(AccountEntity::getId); + Page result = accountMapper.selectPage(new Page<>(page, pageSize), wrapper); + Map names = appNames(); + List records = result.getRecords().stream() + .map(item -> AccountInfoResponse.from(item, names.get(item.getAppCode()))) + .toList(); + return PageResult.of(records, result.getTotal(), page, pageSize); + } + + public AccountDetailResponse detail(Long id) { + AccountEntity account = requireAccount(id); + VipHolderEntity holder = vipHolderMapper.selectOne(new LambdaQueryWrapper() + .eq(VipHolderEntity::getAppCode, account.getAppCode()) + .eq(VipHolderEntity::getBusinessUserId, account.getBusinessUserId()) + .last("LIMIT 1")); + AccountDetailResponse.VipDetail vip = null; + if (holder != null) { + VipPlanEntity plan = vipPlanMapper.selectOne(new LambdaQueryWrapper() + .eq(VipPlanEntity::getAppCode, holder.getAppCode()) + .eq(VipPlanEntity::getPlanCode, holder.getVipPlanCode()) + .last("LIMIT 1")); + vip = new AccountDetailResponse.VipDetail(holder.getVipPlanCode(), + plan == null ? holder.getVipPlanCode() : plan.getPlanName(), + holder.getVipUntil(), + holder.getVipUntil().isAfter(LocalDateTime.now().withNano(0)), + plan == null || plan.getFreeDeduction() == null ? 0 : plan.getFreeDeduction()); + } + List transactions = transactionMapper.selectList( + new LambdaQueryWrapper() + .eq(TransactionEntity::getAppCode, account.getAppCode()) + .eq(TransactionEntity::getBusinessUserId, account.getBusinessUserId()) + .orderByDesc(TransactionEntity::getCreateTime) + .orderByDesc(TransactionEntity::getId) + .last("LIMIT 10")); + String appName = appNames().get(account.getAppCode()); + return new AccountDetailResponse(AccountInfoResponse.from(account, appName), vip, + transactions.stream().map(item -> TransactionInfoResponse.from(item, appName)).toList()); + } + + public PageResult transactions(Long id, long page, long pageSize) { + QueryUtils.checkPage(page, pageSize); + AccountEntity account = requireAccount(id); + Page result = transactionMapper.selectPage(new Page<>(page, pageSize), + new LambdaQueryWrapper() + .eq(TransactionEntity::getAppCode, account.getAppCode()) + .eq(TransactionEntity::getBusinessUserId, account.getBusinessUserId()) + .orderByDesc(TransactionEntity::getCreateTime) + .orderByDesc(TransactionEntity::getId)); + String appName = appNames().get(account.getAppCode()); + return PageResult.of(result.getRecords().stream() + .map(item -> TransactionInfoResponse.from(item, appName)).toList(), + result.getTotal(), page, pageSize); + } + + @Transactional + public AccountInfoResponse adjust(AccountAdjustRequest request, AdminEntity current, + HttpServletRequest httpRequest) { + Long amount = request.amount(); + if (amount == null || amount <= 0 || amount > 1000000000L) { + throw new BizException(ErrorCode.INVALID_POINTS, "调账点数必须为正整数"); + } + String direction = QueryUtils.text(request.direction()); + if (!"IN".equals(direction) && !"OUT".equals(direction)) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "调账方向不合法"); + } + String reason = QueryUtils.text(request.reason()); + if (reason.length() < 5 || reason.length() > 255) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "调账原因不少于 5 个字且不超过 255 字"); + } + totpVerifier.verify(current, request.totp(), "ACCOUNT_ADJUST", "人工调账", httpRequest); + AdminEntity approver = requireApprover(request.secondApproverId(), current); + AccountEntity account = accountMapper.selectOne(new LambdaQueryWrapper() + .eq(AccountEntity::getAppCode, QueryUtils.text(request.appCode())) + .eq(AccountEntity::getBusinessUserId, QueryUtils.text(request.businessUserId())) + .last("LIMIT 1")); + if (account == null) { + throw new BizException(ErrorCode.NOT_FOUND, "钱包账户不存在"); + } + long before = account.getBalance(); + if ("OUT".equals(direction) && before < amount) { + throw new BizException(ErrorCode.REFUND_BALANCE_INSUFFICIENT, "账户余额不足,调减后余额不能为负"); + } + long after = "IN".equals(direction) ? before + amount : before - amount; + int version = account.getVersionNo() == null ? 0 : account.getVersionNo(); + LocalDateTime now = LocalDateTime.now().withNano(0); + int rows = accountMapper.update(null, new LambdaUpdateWrapper() + .eq(AccountEntity::getId, account.getId()) + .eq(AccountEntity::getVersionNo, version) + .set(AccountEntity::getBalance, after) + .set(AccountEntity::getVersionNo, version + 1) + .set(AccountEntity::getUpdateTime, now)); + if (rows == 0) { + throw new BizException(ErrorCode.CONCURRENT_CONFLICT); + } + TransactionEntity tx = new TransactionEntity(); + tx.setAppCode(account.getAppCode()); + tx.setBusinessUserId(account.getBusinessUserId()); + tx.setUsernameSnapshot(account.getUsernameSnapshot()); + tx.setType("ADJUST"); + tx.setAmount(amount); + tx.setBalanceBefore(before); + tx.setBalanceAfter(after); + tx.setIdempotencyKey("adjust:" + current.getId() + ":" + idGenerator.nextLongId()); + tx.setOperatorAdminId(current.getId()); + tx.setOperatorAdminName(current.getUsername()); + tx.setRefundedPoints(0L); + tx.setRemark(reason); + tx.setCreateTime(now); + transactionMapper.insert(tx); + + Map beforeJson = new LinkedHashMap<>(); + beforeJson.put("balance", before); + Map afterJson = new LinkedHashMap<>(); + afterJson.put("balance", after); + afterJson.put("direction", direction); + afterJson.put("amount", amount); + afterJson.put("reason", reason); + afterJson.put("secondApprover", approver.getUsername()); + adminAuditor.success(current, "ACCOUNT_ADJUST", "人工调账(复核人:" + approver.getUsername() + ")", + "ACCOUNT", account.getId(), beforeJson, afterJson, httpRequest); + + AccountEntity saved = accountMapper.selectById(account.getId()); + return AccountInfoResponse.from(saved, appNames().get(saved.getAppCode())); + } + + private AdminEntity requireApprover(Long secondApproverId, AdminEntity current) { + if (secondApproverId == null || secondApproverId.equals(current.getId())) { + throw new BizException(ErrorCode.INVALID_APPROVER, "人工调账必须由另一名管理员复核,且不得为本人"); + } + AdminEntity approver = adminMapper.selectById(secondApproverId); + if (approver == null || !Integer.valueOf(1).equals(approver.getIsActive())) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "复核管理员不存在或已停用"); + } + if (!"SUPER_ADMIN".equals(approver.getRole()) && !"FINANCE".equals(approver.getRole())) { + throw new BizException(ErrorCode.INVALID_APPROVER, "复核人必须具备资金操作权限"); + } + return approver; + } + + private AccountEntity requireAccount(Long id) { + AccountEntity account = accountMapper.selectById(id); + if (account == null) { + throw new BizException(ErrorCode.NOT_FOUND, "钱包账户不存在"); + } + return account; + } + + private Map appNames() { + return appMapper.selectList(null).stream() + .collect(Collectors.toMap(AppEntity::getAppCode, AppEntity::getAppName, (a, b) -> a)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/bootstrap/AdminBootstrapRunner.java b/finance-server/src/main/java/com/gas/fin/admin/bootstrap/AdminBootstrapRunner.java new file mode 100644 index 0000000..df9ec03 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/bootstrap/AdminBootstrapRunner.java @@ -0,0 +1,112 @@ +package com.gas.fin.admin.bootstrap; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.admin.mapper.AdminMapper; +import com.gas.fin.audit.service.AuditService; +import com.gas.fin.auth.service.PasswordHistoryService; +import com.gas.fin.common.crypto.CryptoService; +import com.gas.fin.common.totp.TotpService; +import com.gas.fin.common.util.PasswordUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.core.annotation.Order; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Component; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; + +/** + * 首次启动种子超管:无任何管理员时创建 admin,随机初始密码与 TOTP 密钥只写入本地运维文件。 + */ +@Component +@Order(10) +public class AdminBootstrapRunner implements ApplicationRunner { + + private static final Logger log = LoggerFactory.getLogger(AdminBootstrapRunner.class); + + private final AdminMapper adminMapper; + private final PasswordEncoder passwordEncoder; + private final CryptoService cryptoService; + private final TotpService totpService; + private final PasswordHistoryService passwordHistoryService; + private final AuditService auditService; + + @Value("${fin.bootstrap.enabled:true}") + private boolean enabled; + + @Value("${fin.runtime-dir:./.runtime}") + private String runtimeDir; + + public AdminBootstrapRunner(AdminMapper adminMapper, + PasswordEncoder passwordEncoder, + CryptoService cryptoService, + TotpService totpService, + PasswordHistoryService passwordHistoryService, + AuditService auditService) { + this.adminMapper = adminMapper; + this.passwordEncoder = passwordEncoder; + this.cryptoService = cryptoService; + this.totpService = totpService; + this.passwordHistoryService = passwordHistoryService; + this.auditService = auditService; + } + + @Override + public void run(ApplicationArguments args) throws Exception { + if (!enabled) { + return; + } + Long count = adminMapper.selectCount(null); + if (count != null && count > 0) { + checkSuperAdminExists(); + return; + } + + String initialPassword = PasswordUtils.randomPassword(16); + String totpSecret = totpService.generateSecret(); + + AdminEntity admin = new AdminEntity(); + admin.setUsername("admin"); + admin.setPasswordHash(passwordEncoder.encode(initialPassword)); + admin.setRole("SUPER_ADMIN"); + admin.setIsActive(1); + admin.setMustChangePassword(1); + admin.setTotpSecretEnc(cryptoService.encrypt(totpSecret)); + admin.setTotpBound(0); + admin.setFailedAttempts(0); + admin.setVersionNo(0); + adminMapper.insert(admin); + + passwordHistoryService.record(admin.getId(), admin.getPasswordHash()); + + Path dir = Path.of(runtimeDir); + Files.createDirectories(dir); + Path file = dir.resolve("bootstrap-admin.txt"); + Files.writeString(file, "username=admin" + System.lineSeparator() + + "initialPassword=" + initialPassword + System.lineSeparator() + + "totpSecret=" + totpSecret + System.lineSeparator() + + "首次登录后必须修改密码;本文件仅用于本地开发,生产环境必须通过一次性安全通道交付并立即删除。" + + System.lineSeparator()); + + auditService.record("SYSTEM", null, "SYSTEM", "ADMIN_BOOTSTRAP", "初始化超级管理员", + "ADMIN", admin.getId(), null, Map.of("username", "admin"), "127.0.0.1", "system"); + + log.warn("已创建初始超级管理员 admin,初始凭据写入: {}", file.toAbsolutePath()); + log.warn("首次登录后必须修改密码;生产环境请通过一次性安全通道交付并删除该文件"); + } + + private void checkSuperAdminExists() { + Long count = adminMapper.selectCount(new LambdaQueryWrapper() + .eq(AdminEntity::getRole, "SUPER_ADMIN") + .eq(AdminEntity::getIsActive, 1)); + if (count == null || count == 0) { + log.error("当前系统没有启用状态的超级管理员,请立即通过数据库或运维流程恢复"); + } + } +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/controller/AdminController.java b/finance-server/src/main/java/com/gas/fin/admin/controller/AdminController.java new file mode 100644 index 0000000..42abf7c --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/controller/AdminController.java @@ -0,0 +1,77 @@ +package com.gas.fin.admin.controller; + +import com.gas.fin.admin.dto.AdminCreateRequest; +import com.gas.fin.admin.dto.AdminCreateResponse; +import com.gas.fin.admin.dto.AdminRoleUpdateRequest; +import com.gas.fin.admin.dto.AdminToggleRequest; +import com.gas.fin.admin.dto.AdminTotpRequest; +import com.gas.fin.admin.dto.MessageResponse; +import com.gas.fin.admin.dto.TempPasswordResponse; +import com.gas.fin.admin.service.AdminService; +import com.gas.fin.auth.dto.AdminInfoResponse; +import com.gas.fin.common.api.R; +import com.gas.fin.common.security.AuthContext; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.security.RequirePermission; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Valid; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api/admin/admins") +@RequirePermission(PermissionRegistry.ADMIN_MANAGE) +public class AdminController { + + private final AdminService adminService; + + public AdminController(AdminService adminService) { + this.adminService = adminService; + } + + @GetMapping + public R> list() { + return R.ok(adminService.list()); + } + + @PostMapping + public R create(@Valid @RequestBody AdminCreateRequest request, + HttpServletRequest httpRequest) { + return R.ok(adminService.create(request, AuthContext.require(), httpRequest)); + } + + @PutMapping("/{id}") + public R updateRole(@PathVariable Long id, + @Valid @RequestBody AdminRoleUpdateRequest request, + HttpServletRequest httpRequest) { + return R.ok(adminService.updateRole(id, request, AuthContext.require(), httpRequest)); + } + + @PostMapping("/{id}/toggle") + public R toggle(@PathVariable Long id, + @Valid @RequestBody AdminToggleRequest request, + HttpServletRequest httpRequest) { + return R.ok(adminService.toggle(id, request, AuthContext.require(), httpRequest)); + } + + @PostMapping("/{id}/reset-password") + public R resetPassword(@PathVariable Long id, + @Valid @RequestBody AdminTotpRequest request, + HttpServletRequest httpRequest) { + return R.ok(adminService.resetPassword(id, request.getTotp(), AuthContext.require(), httpRequest)); + } + + @PostMapping("/{id}/reset-totp") + public R resetTotp(@PathVariable Long id, + @Valid @RequestBody AdminTotpRequest request, + HttpServletRequest httpRequest) { + return R.ok(adminService.resetTotp(id, request.getTotp(), AuthContext.require(), httpRequest)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/dto/AdminCreateRequest.java b/finance-server/src/main/java/com/gas/fin/admin/dto/AdminCreateRequest.java new file mode 100644 index 0000000..0b9ba77 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/dto/AdminCreateRequest.java @@ -0,0 +1,19 @@ +package com.gas.fin.admin.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import lombok.Data; + +@Data +public class AdminCreateRequest { + + @NotBlank(message = "用户名不能为空") + @Pattern(regexp = "^[a-z][a-z0-9_]{2,31}$", message = "用户名需为 3~32 位小写字母/数字/下划线,且以字母开头") + private String username; + + @NotBlank(message = "角色不能为空") + @Pattern(regexp = "^(SUPER_ADMIN|FINANCE|AUDITOR)$", message = "角色不合法") + private String role; + + private String totp; +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/dto/AdminCreateResponse.java b/finance-server/src/main/java/com/gas/fin/admin/dto/AdminCreateResponse.java new file mode 100644 index 0000000..3209b6d --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/dto/AdminCreateResponse.java @@ -0,0 +1,13 @@ +package com.gas.fin.admin.dto; + +import com.gas.fin.auth.dto.AdminInfoResponse; +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class AdminCreateResponse { + + private AdminInfoResponse admin; + private String initialPassword; +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/dto/AdminRoleUpdateRequest.java b/finance-server/src/main/java/com/gas/fin/admin/dto/AdminRoleUpdateRequest.java new file mode 100644 index 0000000..b735225 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/dto/AdminRoleUpdateRequest.java @@ -0,0 +1,13 @@ +package com.gas.fin.admin.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import lombok.Data; + +@Data +public class AdminRoleUpdateRequest { + + @NotBlank(message = "角色不能为空") + @Pattern(regexp = "^(SUPER_ADMIN|FINANCE|AUDITOR)$", message = "角色不合法") + private String role; +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/dto/AdminToggleRequest.java b/finance-server/src/main/java/com/gas/fin/admin/dto/AdminToggleRequest.java new file mode 100644 index 0000000..4b1d1f2 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/dto/AdminToggleRequest.java @@ -0,0 +1,15 @@ +package com.gas.fin.admin.dto; + +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotNull; +import lombok.Data; + +@Data +public class AdminToggleRequest { + + @NotNull(message = "enabled 不能为空") + @Min(value = 0, message = "enabled 只能为 0 或 1") + @Max(value = 1, message = "enabled 只能为 0 或 1") + private Integer enabled; +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/dto/AdminTotpRequest.java b/finance-server/src/main/java/com/gas/fin/admin/dto/AdminTotpRequest.java new file mode 100644 index 0000000..4ba7ef5 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/dto/AdminTotpRequest.java @@ -0,0 +1,9 @@ +package com.gas.fin.admin.dto; + +import lombok.Data; + +@Data +public class AdminTotpRequest { + + private String totp; +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/dto/MessageResponse.java b/finance-server/src/main/java/com/gas/fin/admin/dto/MessageResponse.java new file mode 100644 index 0000000..5b7a174 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/dto/MessageResponse.java @@ -0,0 +1,11 @@ +package com.gas.fin.admin.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MessageResponse { + + private String message; +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/dto/TempPasswordResponse.java b/finance-server/src/main/java/com/gas/fin/admin/dto/TempPasswordResponse.java new file mode 100644 index 0000000..3b17815 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/dto/TempPasswordResponse.java @@ -0,0 +1,11 @@ +package com.gas.fin.admin.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class TempPasswordResponse { + + private String tempPassword; +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/entity/AdminEntity.java b/finance-server/src/main/java/com/gas/fin/admin/entity/AdminEntity.java new file mode 100644 index 0000000..65d922b --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/entity/AdminEntity.java @@ -0,0 +1,32 @@ +package com.gas.fin.admin.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_admin") +public class AdminEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String username; + private String passwordHash; + private String role; + private Integer isActive; + private Integer mustChangePassword; + private String totpSecretEnc; + private Integer totpBound; + private Integer failedAttempts; + private LocalDateTime lockedUntil; + private LocalDateTime lastLoginAt; + private String lastLoginIp; + private LocalDateTime passwordUpdatedAt; + private Integer versionNo; + private LocalDateTime createTime; + private LocalDateTime updateTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/entity/AdminPasswordHistoryEntity.java b/finance-server/src/main/java/com/gas/fin/admin/entity/AdminPasswordHistoryEntity.java new file mode 100644 index 0000000..03eaa3f --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/entity/AdminPasswordHistoryEntity.java @@ -0,0 +1,20 @@ +package com.gas.fin.admin.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_admin_password_history") +public class AdminPasswordHistoryEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private Long adminId; + private String passwordHash; + private LocalDateTime createTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/entity/AdminSessionEntity.java b/finance-server/src/main/java/com/gas/fin/admin/entity/AdminSessionEntity.java new file mode 100644 index 0000000..668b8d2 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/entity/AdminSessionEntity.java @@ -0,0 +1,26 @@ +package com.gas.fin.admin.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_admin_session") +public class AdminSessionEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private Long adminId; + private String tokenHash; + private String issuedIp; + private String userAgent; + private LocalDateTime lastActiveAt; + private LocalDateTime idleExpireAt; + private LocalDateTime absoluteExpireAt; + private LocalDateTime revokedAt; + private LocalDateTime createTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/mapper/AdminMapper.java b/finance-server/src/main/java/com/gas/fin/admin/mapper/AdminMapper.java new file mode 100644 index 0000000..165ab6d --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/mapper/AdminMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.admin.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.admin.entity.AdminEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface AdminMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/mapper/AdminPasswordHistoryMapper.java b/finance-server/src/main/java/com/gas/fin/admin/mapper/AdminPasswordHistoryMapper.java new file mode 100644 index 0000000..2c50c91 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/mapper/AdminPasswordHistoryMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.admin.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.admin.entity.AdminPasswordHistoryEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface AdminPasswordHistoryMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/mapper/AdminSessionMapper.java b/finance-server/src/main/java/com/gas/fin/admin/mapper/AdminSessionMapper.java new file mode 100644 index 0000000..6120198 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/mapper/AdminSessionMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.admin.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.admin.entity.AdminSessionEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface AdminSessionMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/admin/service/AdminService.java b/finance-server/src/main/java/com/gas/fin/admin/service/AdminService.java new file mode 100644 index 0000000..af43db8 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/admin/service/AdminService.java @@ -0,0 +1,266 @@ +package com.gas.fin.admin.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.gas.fin.admin.dto.AdminCreateRequest; +import com.gas.fin.admin.dto.AdminCreateResponse; +import com.gas.fin.admin.dto.AdminRoleUpdateRequest; +import com.gas.fin.admin.dto.AdminToggleRequest; +import com.gas.fin.admin.dto.MessageResponse; +import com.gas.fin.admin.dto.TempPasswordResponse; +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.admin.mapper.AdminMapper; +import com.gas.fin.audit.service.AuditService; +import com.gas.fin.auth.dto.AdminInfoResponse; +import com.gas.fin.auth.service.PasswordHistoryService; +import com.gas.fin.auth.service.SessionService; +import com.gas.fin.common.crypto.CryptoService; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.totp.TotpService; +import com.gas.fin.common.util.PasswordUtils; +import com.gas.fin.common.web.RequestUtils; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.LocalDateTime; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +@Service +public class AdminService { + + private final AdminMapper adminMapper; + private final PasswordEncoder passwordEncoder; + private final CryptoService cryptoService; + private final TotpService totpService; + private final AuditService auditService; + private final SessionService sessionService; + private final PasswordHistoryService passwordHistoryService; + + @Value("${fin.trust-proxy:true}") + private boolean trustProxy; + + @Value("${fin.runtime-dir:./.runtime}") + private String runtimeDir; + + @Value("${fin.admin.totp-output-enabled:true}") + private boolean totpOutputEnabled; + + public AdminService(AdminMapper adminMapper, + PasswordEncoder passwordEncoder, + CryptoService cryptoService, + TotpService totpService, + AuditService auditService, + SessionService sessionService, + PasswordHistoryService passwordHistoryService) { + this.adminMapper = adminMapper; + this.passwordEncoder = passwordEncoder; + this.cryptoService = cryptoService; + this.totpService = totpService; + this.auditService = auditService; + this.sessionService = sessionService; + this.passwordHistoryService = passwordHistoryService; + } + + public List list() { + return adminMapper.selectList(new LambdaQueryWrapper() + .orderByAsc(AdminEntity::getCreateTime) + .orderByAsc(AdminEntity::getId)) + .stream() + .map(AdminInfoResponse::from) + .toList(); + } + + @Transactional + public AdminCreateResponse create(AdminCreateRequest request, AdminEntity current, HttpServletRequest httpRequest) { + String ip = RequestUtils.clientIp(httpRequest, trustProxy); + String ua = RequestUtils.userAgent(httpRequest); + validateTotp(current, request.getTotp(), ip, ua, "ADMIN_CREATE", "创建管理员"); + + String username = request.getUsername().trim().toLowerCase(Locale.ROOT); + Long exists = adminMapper.selectCount(new LambdaQueryWrapper() + .eq(AdminEntity::getUsername, username)); + if (exists != null && exists > 0) { + throw new BizException(ErrorCode.DUPLICATE_KEY, "用户名已存在"); + } + + String initialPassword = PasswordUtils.randomPassword(16); + String totpSecret = totpService.generateSecret(); + + AdminEntity admin = new AdminEntity(); + admin.setUsername(username); + admin.setPasswordHash(passwordEncoder.encode(initialPassword)); + admin.setRole(request.getRole()); + admin.setIsActive(1); + admin.setMustChangePassword(1); + admin.setTotpSecretEnc(cryptoService.encrypt(totpSecret)); + admin.setTotpBound(0); + admin.setFailedAttempts(0); + admin.setVersionNo(0); + adminMapper.insert(admin); + + passwordHistoryService.record(admin.getId(), admin.getPasswordHash()); + writeTotpSecret(username, totpSecret); + + AdminEntity saved = adminMapper.selectById(admin.getId()); + Map after = new LinkedHashMap<>(); + after.put("username", username); + after.put("role", request.getRole()); + auditService.record("ADMIN", current.getId(), current.getUsername(), "ADMIN_CREATE", "创建管理员", + "ADMIN", admin.getId(), null, after, ip, ua); + + return new AdminCreateResponse(AdminInfoResponse.from(saved), initialPassword); + } + + @Transactional + public AdminInfoResponse updateRole(Long id, AdminRoleUpdateRequest request, AdminEntity current, + HttpServletRequest httpRequest) { + AdminEntity target = requireAdmin(id); + ensureNotLastSuperAdmin(target, request.getRole()); + Map before = new LinkedHashMap<>(); + before.put("role", target.getRole()); + adminMapper.update(null, new LambdaUpdateWrapper() + .eq(AdminEntity::getId, id) + .set(AdminEntity::getRole, request.getRole())); + target.setRole(request.getRole()); + Map after = new LinkedHashMap<>(); + after.put("role", request.getRole()); + String ip = RequestUtils.clientIp(httpRequest, trustProxy); + String ua = RequestUtils.userAgent(httpRequest); + auditService.record("ADMIN", current.getId(), current.getUsername(), "ADMIN_UPDATE_ROLE", "修改管理员角色", + "ADMIN", id, before, after, ip, ua); + return AdminInfoResponse.from(adminMapper.selectById(id)); + } + + @Transactional + public AdminInfoResponse toggle(Long id, AdminToggleRequest request, AdminEntity current, + HttpServletRequest httpRequest) { + AdminEntity target = requireAdmin(id); + boolean disabling = Integer.valueOf(0).equals(request.getEnabled()); + if (disabling) { + if (id.equals(current.getId())) { + throw new BizException(ErrorCode.ADMIN_CONSTRAINT, "不能停用当前登录账号"); + } + ensureNotLastSuperAdmin(target, "DISABLED"); + } + adminMapper.update(null, new LambdaUpdateWrapper() + .eq(AdminEntity::getId, id) + .set(AdminEntity::getIsActive, request.getEnabled())); + if (disabling) { + sessionService.revokeAll(id); + } + String ip = RequestUtils.clientIp(httpRequest, trustProxy); + String ua = RequestUtils.userAgent(httpRequest); + Map after = new LinkedHashMap<>(); + after.put("enabled", request.getEnabled()); + auditService.record("ADMIN", current.getId(), current.getUsername(), "ADMIN_TOGGLE", "启用/停用管理员", + "ADMIN", id, null, after, ip, ua); + return AdminInfoResponse.from(adminMapper.selectById(id)); + } + + @Transactional + public TempPasswordResponse resetPassword(Long id, String totp, AdminEntity current, + HttpServletRequest httpRequest) { + String ip = RequestUtils.clientIp(httpRequest, trustProxy); + String ua = RequestUtils.userAgent(httpRequest); + validateTotp(current, totp, ip, ua, "ADMIN_RESET_PASSWORD", "重置管理员密码"); + AdminEntity target = requireAdmin(id); + String tempPassword = PasswordUtils.randomPassword(16); + adminMapper.update(null, new LambdaUpdateWrapper() + .eq(AdminEntity::getId, id) + .set(AdminEntity::getPasswordHash, passwordEncoder.encode(tempPassword)) + .set(AdminEntity::getMustChangePassword, 1) + .set(AdminEntity::getFailedAttempts, 0) + .set(AdminEntity::getLockedUntil, null) + .set(AdminEntity::getVersionNo, target.getVersionNo() == null ? 1 : target.getVersionNo() + 1)); + passwordHistoryService.record(id, target.getPasswordHash()); + sessionService.revokeAll(id); + auditService.record("ADMIN", current.getId(), current.getUsername(), "ADMIN_RESET_PASSWORD", "重置管理员密码", + "ADMIN", id, null, Map.of("mustChangePassword", 1), ip, ua); + return new TempPasswordResponse(tempPassword); + } + + @Transactional + public MessageResponse resetTotp(Long id, String totp, AdminEntity current, HttpServletRequest httpRequest) { + String ip = RequestUtils.clientIp(httpRequest, trustProxy); + String ua = RequestUtils.userAgent(httpRequest); + validateTotp(current, totp, ip, ua, "ADMIN_RESET_TOTP", "重置管理员TOTP"); + AdminEntity target = requireAdmin(id); + String newSecret = totpService.generateSecret(); + adminMapper.update(null, new LambdaUpdateWrapper() + .eq(AdminEntity::getId, id) + .set(AdminEntity::getTotpSecretEnc, cryptoService.encrypt(newSecret)) + .set(AdminEntity::getTotpBound, 0)); + writeTotpSecret(target.getUsername(), newSecret); + auditService.record("ADMIN", current.getId(), current.getUsername(), "ADMIN_RESET_TOTP", "重置管理员TOTP", + "ADMIN", id, null, null, ip, ua); + return new MessageResponse("TOTP 已重置,新密钥已通过运维安全通道交付"); + } + + public AdminEntity requireAdmin(Long id) { + AdminEntity admin = adminMapper.selectById(id); + if (admin == null) { + throw new BizException(ErrorCode.NOT_FOUND); + } + return admin; + } + + public long countActiveSuperAdmins() { + Long count = adminMapper.selectCount(new LambdaQueryWrapper() + .eq(AdminEntity::getRole, "SUPER_ADMIN") + .eq(AdminEntity::getIsActive, 1)); + return count == null ? 0 : count; + } + + private void ensureNotLastSuperAdmin(AdminEntity target, String newRole) { + boolean targetIsActiveSuper = "SUPER_ADMIN".equals(target.getRole()) + && Integer.valueOf(1).equals(target.getIsActive()); + if (!targetIsActiveSuper) { + return; + } + boolean stillSuper = newRole == null || "SUPER_ADMIN".equals(newRole); + if (!stillSuper && countActiveSuperAdmins() <= 1) { + throw new BizException(ErrorCode.ADMIN_CONSTRAINT, "不能降级或停用最后一名启用状态的超级管理员"); + } + } + + private void validateTotp(AdminEntity admin, String code, String ip, String ua, + String action, String actionLabel) { + String secret; + try { + secret = cryptoService.decrypt(admin.getTotpSecretEnc()); + } catch (Exception ex) { + secret = null; + } + TotpService.Result result = totpService.verify(secret, code, admin.getId()); + if (result != TotpService.Result.OK) { + auditService.recordFailure("ADMIN", admin.getId(), admin.getUsername(), action, actionLabel, + "ADMIN", admin.getId(), null, null, ip, ua); + throw new BizException(ErrorCode.TOTP_FAILED); + } + } + + private void writeTotpSecret(String username, String secret) { + if (!totpOutputEnabled) { + return; + } + try { + Path dir = Path.of(runtimeDir); + Files.createDirectories(dir); + Path file = dir.resolve("admin-totp-" + username + ".txt"); + Files.writeString(file, "username=" + username + System.lineSeparator() + + "totpSecret=" + secret + System.lineSeparator() + + "注意:本文件仅用于本地开发,生产环境必须由运维通过一次性安全通道交付并立即删除。" + System.lineSeparator()); + } catch (Exception ex) { + throw new IllegalStateException("cannot write TOTP secret file", ex); + } + } +} diff --git a/finance-server/src/main/java/com/gas/fin/app/controller/AppController.java b/finance-server/src/main/java/com/gas/fin/app/controller/AppController.java new file mode 100644 index 0000000..31d1434 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/app/controller/AppController.java @@ -0,0 +1,96 @@ +package com.gas.fin.app.controller; + +import com.gas.fin.app.dto.AppCreateResponse; +import com.gas.fin.app.dto.AppInfoResponse; +import com.gas.fin.app.dto.AppPayloadRequest; +import com.gas.fin.app.dto.AppSecretRotateRequest; +import com.gas.fin.app.dto.AppSecretRotateResponse; +import com.gas.fin.app.dto.AppTokenResponse; +import com.gas.fin.app.service.AppService; +import com.gas.fin.common.api.R; +import com.gas.fin.common.dto.ToggleRequest; +import com.gas.fin.common.security.AuthContext; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.security.RequirePermission; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/api/admin/apps") +public class AppController { + + private final AppService appService; + + public AppController(AppService appService) { + this.appService = appService; + } + + @GetMapping + @RequirePermission(PermissionRegistry.VIEW) + public R> list() { + return R.ok(appService.list()); + } + + @PostMapping + @RequirePermission(PermissionRegistry.APP_MANAGE) + public R create(@RequestBody AppPayloadRequest request, + HttpServletRequest httpRequest) { + return R.ok(appService.create(request, AuthContext.require(), httpRequest)); + } + + @PutMapping("/{appCode}") + @RequirePermission(PermissionRegistry.APP_MANAGE) + public R update(@PathVariable String appCode, + @RequestBody AppPayloadRequest request, + HttpServletRequest httpRequest) { + return R.ok(appService.update(appCode, request, AuthContext.require(), httpRequest)); + } + + @PostMapping("/{appCode}/secret/rotate") + @RequirePermission(PermissionRegistry.APP_MANAGE) + public R rotate(@PathVariable String appCode, + @RequestBody(required = false) AppSecretRotateRequest request, + HttpServletRequest httpRequest) { + Integer graceHours = request == null ? null : request.graceHours(); + return R.ok(appService.rotate(appCode, graceHours, AuthContext.require(), httpRequest)); + } + + @PostMapping("/{appCode}/secret/revoke-prev") + @RequirePermission(PermissionRegistry.APP_MANAGE) + public R revokePrev(@PathVariable String appCode, HttpServletRequest httpRequest) { + appService.revokePrevSecret(appCode, AuthContext.require(), httpRequest); + return R.ok(); + } + + @PostMapping("/{appCode}/toggle") + @RequirePermission(PermissionRegistry.APP_MANAGE) + public R toggle(@PathVariable String appCode, + @RequestBody ToggleRequest request, + HttpServletRequest httpRequest) { + return R.ok(appService.toggle(appCode, request.enabled(), AuthContext.require(), httpRequest)); + } + + @GetMapping("/{appCode}/tokens") + @RequirePermission(PermissionRegistry.VIEW) + public R> tokens(@PathVariable String appCode) { + return R.ok(appService.tokens(appCode)); + } + + @PostMapping("/{appCode}/tokens/revoke") + @RequirePermission(PermissionRegistry.APP_MANAGE) + public R> revokeTokens(@PathVariable String appCode, + @RequestBody(required = false) Map body, + HttpServletRequest httpRequest) { + Long tokenId = body == null ? null : body.get("tokenId"); + return R.ok(appService.revokeTokens(appCode, tokenId, AuthContext.require(), httpRequest)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/app/dto/AppCreateResponse.java b/finance-server/src/main/java/com/gas/fin/app/dto/AppCreateResponse.java new file mode 100644 index 0000000..17de9b2 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/app/dto/AppCreateResponse.java @@ -0,0 +1,4 @@ +package com.gas.fin.app.dto; + +public record AppCreateResponse(AppInfoResponse app, String clientSecret) { +} diff --git a/finance-server/src/main/java/com/gas/fin/app/dto/AppInfoResponse.java b/finance-server/src/main/java/com/gas/fin/app/dto/AppInfoResponse.java new file mode 100644 index 0000000..b7a1e3d --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/app/dto/AppInfoResponse.java @@ -0,0 +1,45 @@ +package com.gas.fin.app.dto; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class AppInfoResponse { + + private String appCode; + private String appName; + private String allowedRedirectHosts; + private String webhookUrl; + private Integer tokenTtlSeconds; + private Integer enabled; + private LocalDateTime secretExpiresAt; + private boolean hasPrevSecret; + private LocalDateTime createTime; + private long accountCount; + private long todayAmountCent; + + public static AppInfoResponse from(AppEntityView app, long accountCount, long todayAmountCent) { + AppInfoResponse response = new AppInfoResponse(); + response.setAppCode(app.appCode()); + response.setAppName(app.appName()); + response.setAllowedRedirectHosts(app.allowedRedirectHosts()); + response.setWebhookUrl(app.webhookUrl() == null ? "" : app.webhookUrl()); + response.setTokenTtlSeconds(app.tokenTtlSeconds()); + response.setEnabled(app.enabled()); + response.setSecretExpiresAt(app.secretExpiresAt()); + response.setHasPrevSecret(app.hasPrevSecret()); + response.setCreateTime(app.createTime()); + response.setAccountCount(accountCount); + response.setTodayAmountCent(todayAmountCent); + return response; + } + + /** + * 保持 DTO 与实体解耦的只读视图,避免把 webhookSecretEnc 等敏感字段带出。 + */ + public record AppEntityView(String appCode, String appName, String allowedRedirectHosts, String webhookUrl, + Integer tokenTtlSeconds, Integer enabled, LocalDateTime secretExpiresAt, + boolean hasPrevSecret, LocalDateTime createTime) { + } +} diff --git a/finance-server/src/main/java/com/gas/fin/app/dto/AppPayloadRequest.java b/finance-server/src/main/java/com/gas/fin/app/dto/AppPayloadRequest.java new file mode 100644 index 0000000..770a8d6 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/app/dto/AppPayloadRequest.java @@ -0,0 +1,5 @@ +package com.gas.fin.app.dto; + +public record AppPayloadRequest(String appCode, String appName, String allowedRedirectHosts, + String webhookUrl, Integer tokenTtlSeconds) { +} diff --git a/finance-server/src/main/java/com/gas/fin/app/dto/AppSecretRotateRequest.java b/finance-server/src/main/java/com/gas/fin/app/dto/AppSecretRotateRequest.java new file mode 100644 index 0000000..dfa088a --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/app/dto/AppSecretRotateRequest.java @@ -0,0 +1,4 @@ +package com.gas.fin.app.dto; + +public record AppSecretRotateRequest(Integer graceHours) { +} diff --git a/finance-server/src/main/java/com/gas/fin/app/dto/AppSecretRotateResponse.java b/finance-server/src/main/java/com/gas/fin/app/dto/AppSecretRotateResponse.java new file mode 100644 index 0000000..4b2f987 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/app/dto/AppSecretRotateResponse.java @@ -0,0 +1,6 @@ +package com.gas.fin.app.dto; + +import java.time.LocalDateTime; + +public record AppSecretRotateResponse(String clientSecret, LocalDateTime expiresAt) { +} diff --git a/finance-server/src/main/java/com/gas/fin/app/dto/AppTokenResponse.java b/finance-server/src/main/java/com/gas/fin/app/dto/AppTokenResponse.java new file mode 100644 index 0000000..f8568cb --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/app/dto/AppTokenResponse.java @@ -0,0 +1,30 @@ +package com.gas.fin.app.dto; + +import com.gas.fin.app.entity.AppTokenEntity; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class AppTokenResponse { + + private Long id; + private String appCode; + private String tokenPrefix; + private LocalDateTime expiresAt; + private LocalDateTime revokedAt; + private String issuedIp; + private LocalDateTime createTime; + + public static AppTokenResponse from(AppTokenEntity entity) { + AppTokenResponse response = new AppTokenResponse(); + response.setId(entity.getId()); + response.setAppCode(entity.getAppCode()); + response.setTokenPrefix(entity.getTokenPrefix()); + response.setExpiresAt(entity.getExpiresAt()); + response.setRevokedAt(entity.getRevokedAt()); + response.setIssuedIp(entity.getIssuedIp() == null ? "" : entity.getIssuedIp()); + response.setCreateTime(entity.getCreateTime()); + return response; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/app/entity/AppEntity.java b/finance-server/src/main/java/com/gas/fin/app/entity/AppEntity.java new file mode 100644 index 0000000..f33c2d1 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/app/entity/AppEntity.java @@ -0,0 +1,28 @@ +package com.gas.fin.app.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_app") +public class AppEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String appCode; + private String appName; + private String allowedRedirectHosts; + private String webhookUrl; + private String webhookSecretEnc; + private Integer tokenTtlSeconds; + private Integer enabled; + private LocalDateTime secretExpiresAt; + private Integer hasPrevSecret; + private LocalDateTime createTime; + private LocalDateTime updateTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/app/entity/AppSecretEntity.java b/finance-server/src/main/java/com/gas/fin/app/entity/AppSecretEntity.java new file mode 100644 index 0000000..59a7368 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/app/entity/AppSecretEntity.java @@ -0,0 +1,25 @@ +package com.gas.fin.app.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_app_secret") +public class AppSecretEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String appCode; + private String secretHash; + private String secretPrefix; + private String status; + private LocalDateTime graceExpireAt; + private Long createdBy; + private LocalDateTime createTime; + private LocalDateTime revokedAt; +} diff --git a/finance-server/src/main/java/com/gas/fin/app/entity/AppTokenEntity.java b/finance-server/src/main/java/com/gas/fin/app/entity/AppTokenEntity.java new file mode 100644 index 0000000..2418f85 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/app/entity/AppTokenEntity.java @@ -0,0 +1,24 @@ +package com.gas.fin.app.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_app_token") +public class AppTokenEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String appCode; + private String tokenHash; + private String tokenPrefix; + private String issuedIp; + private LocalDateTime expiresAt; + private LocalDateTime revokedAt; + private LocalDateTime createTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/app/mapper/AppMapper.java b/finance-server/src/main/java/com/gas/fin/app/mapper/AppMapper.java new file mode 100644 index 0000000..6250ae2 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/app/mapper/AppMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.app.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.app.entity.AppEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface AppMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/app/mapper/AppSecretMapper.java b/finance-server/src/main/java/com/gas/fin/app/mapper/AppSecretMapper.java new file mode 100644 index 0000000..ea503ad --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/app/mapper/AppSecretMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.app.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.app.entity.AppSecretEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface AppSecretMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/app/mapper/AppTokenMapper.java b/finance-server/src/main/java/com/gas/fin/app/mapper/AppTokenMapper.java new file mode 100644 index 0000000..0b67dcd --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/app/mapper/AppTokenMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.app.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.app.entity.AppTokenEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface AppTokenMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/app/service/AppService.java b/finance-server/src/main/java/com/gas/fin/app/service/AppService.java new file mode 100644 index 0000000..99e75fb --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/app/service/AppService.java @@ -0,0 +1,439 @@ +package com.gas.fin.app.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.gas.fin.account.entity.AccountEntity; +import com.gas.fin.account.mapper.AccountMapper; +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.app.dto.AppCreateResponse; +import com.gas.fin.app.dto.AppInfoResponse; +import com.gas.fin.app.dto.AppPayloadRequest; +import com.gas.fin.app.dto.AppSecretRotateResponse; +import com.gas.fin.app.dto.AppTokenResponse; +import com.gas.fin.app.entity.AppEntity; +import com.gas.fin.app.entity.AppSecretEntity; +import com.gas.fin.app.entity.AppTokenEntity; +import com.gas.fin.app.mapper.AppMapper; +import com.gas.fin.app.mapper.AppSecretMapper; +import com.gas.fin.app.mapper.AppTokenMapper; +import com.gas.fin.common.crypto.CryptoService; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.security.AdminAuditor; +import com.gas.fin.common.util.HashUtils; +import com.gas.fin.order.entity.CashLedgerEntity; +import com.gas.fin.order.mapper.CashLedgerMapper; +import com.gas.fin.pricing.entity.AppPolicyEntity; +import com.gas.fin.pricing.entity.AppPricingEntity; +import com.gas.fin.pricing.mapper.AppPolicyMapper; +import com.gas.fin.pricing.mapper.AppPricingMapper; +import com.gas.fin.setting.service.ConfigService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 接入应用与密钥管理。 + */ +@Service +public class AppService { + + private static final String APP_CODE_RULE = "^[a-z][a-z0-9-]{2,31}$"; + + private final AppMapper appMapper; + private final AppSecretMapper secretMapper; + private final AppTokenMapper tokenMapper; + private final AccountMapper accountMapper; + private final CashLedgerMapper cashLedgerMapper; + private final AppPricingMapper pricingMapper; + private final AppPolicyMapper policyMapper; + private final ConfigService configService; + private final CryptoService cryptoService; + private final AdminAuditor adminAuditor; + + public AppService(AppMapper appMapper, AppSecretMapper secretMapper, AppTokenMapper tokenMapper, + AccountMapper accountMapper, CashLedgerMapper cashLedgerMapper, + AppPricingMapper pricingMapper, AppPolicyMapper policyMapper, + ConfigService configService, CryptoService cryptoService, AdminAuditor adminAuditor) { + this.appMapper = appMapper; + this.secretMapper = secretMapper; + this.tokenMapper = tokenMapper; + this.accountMapper = accountMapper; + this.cashLedgerMapper = cashLedgerMapper; + this.pricingMapper = pricingMapper; + this.policyMapper = policyMapper; + this.configService = configService; + this.cryptoService = cryptoService; + this.adminAuditor = adminAuditor; + } + + public AppEntity require(String appCode) { + AppEntity app = appMapper.selectOne(new LambdaQueryWrapper() + .eq(AppEntity::getAppCode, appCode) + .last("LIMIT 1")); + if (app == null) { + throw new BizException(ErrorCode.NOT_FOUND, "接入应用不存在"); + } + return app; + } + + public List list() { + List apps = appMapper.selectList(new LambdaQueryWrapper() + .orderByAsc(AppEntity::getCreateTime).orderByAsc(AppEntity::getId)); + Map accountCounts = new HashMap<>(); + accountMapper.selectList(new LambdaQueryWrapper() + .select(AccountEntity::getAppCode)) + .forEach(item -> accountCounts.merge(item.getAppCode(), 1L, Long::sum)); + LocalDateTime dayStart = LocalDate.now().atStartOfDay(); + LocalDateTime dayEnd = dayStart.plusDays(1); + Map todayAmounts = new HashMap<>(); + cashLedgerMapper.selectList(new LambdaQueryWrapper() + .eq(CashLedgerEntity::getDirection, "IN") + .ge(CashLedgerEntity::getReceivedAt, dayStart) + .lt(CashLedgerEntity::getReceivedAt, dayEnd)) + .forEach(item -> todayAmounts.merge(item.getAppCode(), item.getAmountCent(), Long::sum)); + return apps.stream() + .map(app -> AppInfoResponse.from(view(app), + accountCounts.getOrDefault(app.getAppCode(), 0L), + todayAmounts.getOrDefault(app.getAppCode(), 0L))) + .toList(); + } + + @Transactional + public AppCreateResponse create(AppPayloadRequest request, AdminEntity current, HttpServletRequest httpRequest) { + String appCode = trim(request.appCode()); + String appName = trim(request.appName()); + String hosts = trim(request.allowedRedirectHosts()); + String webhookUrl = trim(request.webhookUrl()); + if (!appCode.matches(APP_CODE_RULE)) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "app_code 需为 3~32 位小写字母、数字或短横线"); + } + if (appName.length() < 2 || appName.length() > 64) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "应用名称需为 2~64 个字符"); + } + if (appMapper.selectCount(new LambdaQueryWrapper() + .eq(AppEntity::getAppCode, appCode)) > 0) { + throw new BizException(ErrorCode.DUPLICATE_KEY, "app_code 已存在"); + } + assertHosts(hosts); + assertWebhookUrl(webhookUrl); + int ttl = request.tokenTtlSeconds() == null + ? (int) configService.getNumber("token.ttl_seconds", 900) + : request.tokenTtlSeconds(); + assertTtl(ttl); + + String clientSecret = newSecret("sk"); + String webhookSecret = newSecret("whsec"); + LocalDateTime now = LocalDateTime.now().withNano(0); + AppEntity app = new AppEntity(); + app.setAppCode(appCode); + app.setAppName(appName); + app.setAllowedRedirectHosts(hosts); + app.setWebhookUrl(webhookUrl); + app.setWebhookSecretEnc(cryptoService.encrypt(webhookSecret)); + app.setTokenTtlSeconds(ttl); + app.setEnabled(1); + app.setHasPrevSecret(0); + app.setCreateTime(now); + app.setUpdateTime(now); + appMapper.insert(app); + + AppSecretEntity secret = new AppSecretEntity(); + secret.setAppCode(appCode); + secret.setSecretHash(HashUtils.sha256Hex(clientSecret)); + secret.setSecretPrefix(clientSecret.substring(0, 12)); + secret.setStatus("ACTIVE"); + secret.setCreatedBy(current.getId()); + secret.setCreateTime(now); + secretMapper.insert(secret); + + AppPricingEntity pricing = new AppPricingEntity(); + pricing.setAppCode(appCode); + pricing.setPointsPerYuan(100L); + pricing.setEnabled(1); + pricing.setUpdateBy(current.getUsername()); + pricing.setVersionNo(0); + pricing.setCreateTime(now); + pricing.setUpdateTime(now); + pricingMapper.insert(pricing); + + AppPolicyEntity policy = new AppPolicyEntity(); + policy.setAppCode(appCode); + policy.setMinCost(0L); + policy.setMaxPointsPerCharge(50000L); + policy.setVipExempt(0); + policy.setFailedStrategy("none"); + policy.setDualControlThresholdCent(configService.getNumber("review.threshold_cent", 500000)); + policy.setEnabled(1); + policy.setUpdateBy(current.getUsername()); + policy.setVersionNo(0); + policy.setCreateTime(now); + policy.setUpdateTime(now); + policyMapper.insert(policy); + + Map after = new LinkedHashMap<>(); + after.put("appCode", appCode); + after.put("appName", appName); + after.put("allowedRedirectHosts", hosts); + after.put("tokenTtlSeconds", ttl); + adminAuditor.success(current, "APP_CREATE", "接入新应用", "APP", app.getId(), null, after, httpRequest); + return new AppCreateResponse(AppInfoResponse.from(view(app), 0, 0), clientSecret); + } + + @Transactional + public AppInfoResponse update(String appCode, AppPayloadRequest request, AdminEntity current, + HttpServletRequest httpRequest) { + AppEntity app = require(appCode); + String hosts = trim(request.allowedRedirectHosts()); + String webhookUrl = trim(request.webhookUrl()); + String appName = trim(request.appName()); + assertHosts(hosts); + if (!appName.isEmpty() && (appName.length() < 2 || appName.length() > 64)) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "应用名称需为 2~64 个字符"); + } + assertWebhookUrl(webhookUrl); + int ttl = request.tokenTtlSeconds() == null ? app.getTokenTtlSeconds() : request.tokenTtlSeconds(); + assertTtl(ttl); + + Map before = new LinkedHashMap<>(); + before.put("appName", app.getAppName()); + before.put("allowedRedirectHosts", app.getAllowedRedirectHosts()); + before.put("webhookUrl", app.getWebhookUrl()); + before.put("tokenTtlSeconds", app.getTokenTtlSeconds()); + + appMapper.update(null, new LambdaUpdateWrapper() + .eq(AppEntity::getId, app.getId()) + .set(AppEntity::getAppName, appName.isEmpty() ? app.getAppName() : appName) + .set(AppEntity::getAllowedRedirectHosts, hosts) + .set(AppEntity::getWebhookUrl, webhookUrl) + .set(AppEntity::getTokenTtlSeconds, ttl) + .set(AppEntity::getUpdateTime, LocalDateTime.now().withNano(0))); + Map after = new LinkedHashMap<>(); + after.put("appName", appName.isEmpty() ? app.getAppName() : appName); + after.put("allowedRedirectHosts", hosts); + after.put("webhookUrl", webhookUrl); + after.put("tokenTtlSeconds", ttl); + adminAuditor.success(current, "APP_UPDATE", "修改应用配置", "APP", app.getId(), before, after, httpRequest); + return listOf(require(appCode)); + } + + @Transactional + public AppSecretRotateResponse rotate(String appCode, Integer graceHours, AdminEntity current, + HttpServletRequest httpRequest) { + AppEntity app = require(appCode); + String clientSecret = newSecret("sk"); + LocalDateTime now = LocalDateTime.now().withNano(0); + long hours = graceHours == null + ? configService.getNumber("secret.rotate.grace_hours", 24) + : Math.max(0, graceHours); + LocalDateTime expiresAt = hours <= 0 ? null : now.plusHours(hours); + + if (hours <= 0) { + secretMapper.update(null, new LambdaUpdateWrapper() + .eq(AppSecretEntity::getAppCode, appCode) + .eq(AppSecretEntity::getStatus, "ACTIVE") + .set(AppSecretEntity::getStatus, "REVOKED") + .set(AppSecretEntity::getRevokedAt, now)); + app.setHasPrevSecret(0); + app.setSecretExpiresAt(null); + } else { + secretMapper.update(null, new LambdaUpdateWrapper() + .eq(AppSecretEntity::getAppCode, appCode) + .eq(AppSecretEntity::getStatus, "ACTIVE") + .set(AppSecretEntity::getStatus, "GRACE") + .set(AppSecretEntity::getGraceExpireAt, expiresAt)); + app.setHasPrevSecret(1); + app.setSecretExpiresAt(expiresAt); + } + appMapper.update(null, new LambdaUpdateWrapper() + .eq(AppEntity::getId, app.getId()) + .set(AppEntity::getHasPrevSecret, app.getHasPrevSecret()) + .set(AppEntity::getSecretExpiresAt, app.getSecretExpiresAt()) + .set(AppEntity::getUpdateTime, now)); + + AppSecretEntity secret = new AppSecretEntity(); + secret.setAppCode(appCode); + secret.setSecretHash(HashUtils.sha256Hex(clientSecret)); + secret.setSecretPrefix(clientSecret.substring(0, 12)); + secret.setStatus("ACTIVE"); + secret.setCreatedBy(current.getId()); + secret.setCreateTime(now); + secretMapper.insert(secret); + + adminAuditor.success(current, "APP_SECRET_ROTATE", "轮换应用密钥", "APP", app.getId(), null, + Map.of("graceHours", hours), httpRequest); + return new AppSecretRotateResponse(clientSecret, expiresAt); + } + + @Transactional + public void revokePrevSecret(String appCode, AdminEntity current, HttpServletRequest httpRequest) { + AppEntity app = require(appCode); + Long grace = secretMapper.selectCount(new LambdaQueryWrapper() + .eq(AppSecretEntity::getAppCode, appCode) + .eq(AppSecretEntity::getStatus, "GRACE")); + if (grace == null || grace == 0) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "当前没有待回收的旧密钥"); + } + LocalDateTime now = LocalDateTime.now().withNano(0); + secretMapper.update(null, new LambdaUpdateWrapper() + .eq(AppSecretEntity::getAppCode, appCode) + .eq(AppSecretEntity::getStatus, "GRACE") + .set(AppSecretEntity::getStatus, "REVOKED") + .set(AppSecretEntity::getRevokedAt, now)); + appMapper.update(null, new LambdaUpdateWrapper() + .eq(AppEntity::getId, app.getId()) + .set(AppEntity::getHasPrevSecret, 0) + .set(AppEntity::getSecretExpiresAt, null) + .set(AppEntity::getUpdateTime, now)); + adminAuditor.success(current, "APP_SECRET_REVOKE_PREV", "立即回收旧密钥", "APP", app.getId(), + null, null, httpRequest); + } + + @Transactional + public AppInfoResponse toggle(String appCode, Integer enabled, AdminEntity current, + HttpServletRequest httpRequest) { + AppEntity app = require(appCode); + int value = Integer.valueOf(1).equals(enabled) ? 1 : 0; + LocalDateTime now = LocalDateTime.now().withNano(0); + appMapper.update(null, new LambdaUpdateWrapper() + .eq(AppEntity::getId, app.getId()) + .set(AppEntity::getEnabled, value) + .set(AppEntity::getUpdateTime, now)); + if (value == 0) { + tokenMapper.update(null, new LambdaUpdateWrapper() + .eq(AppTokenEntity::getAppCode, appCode) + .isNull(AppTokenEntity::getRevokedAt) + .set(AppTokenEntity::getRevokedAt, now)); + } + adminAuditor.success(current, "APP_TOGGLE", + value == 1 ? "启用应用" : "停用应用(熔断全部 token)", + "APP", app.getId(), null, Map.of("enabled", value), httpRequest); + return listOf(require(appCode)); + } + + public List tokens(String appCode) { + require(appCode); + return tokenMapper.selectList(new LambdaQueryWrapper() + .eq(AppTokenEntity::getAppCode, appCode) + .orderByDesc(AppTokenEntity::getCreateTime) + .orderByDesc(AppTokenEntity::getId)) + .stream().map(AppTokenResponse::from).toList(); + } + + @Transactional + public Map revokeTokens(String appCode, Long tokenId, AdminEntity current, + HttpServletRequest httpRequest) { + AppEntity app = require(appCode); + LambdaUpdateWrapper wrapper = new LambdaUpdateWrapper() + .eq(AppTokenEntity::getAppCode, appCode) + .isNull(AppTokenEntity::getRevokedAt) + .set(AppTokenEntity::getRevokedAt, LocalDateTime.now().withNano(0)); + if (tokenId != null) { + wrapper.eq(AppTokenEntity::getId, tokenId); + } + int revoked = tokenMapper.update(null, wrapper); + adminAuditor.success(current, "APP_TOKEN_REVOKE", + tokenId != null ? "撤销单个 client token" : "熔断全部 client token", + "APP", app.getId(), null, + Map.of("tokenId", tokenId == null ? "ALL" : tokenId, "count", revoked), httpRequest); + Map result = new LinkedHashMap<>(); + result.put("revoked", revoked); + return result; + } + + private AppInfoResponse listOf(AppEntity app) { + Long accounts = accountMapper.selectCount(new LambdaQueryWrapper() + .eq(AccountEntity::getAppCode, app.getAppCode())); + LocalDateTime dayStart = LocalDate.now().atStartOfDay(); + long todayAmount = cashLedgerMapper.selectList(new LambdaQueryWrapper() + .eq(CashLedgerEntity::getAppCode, app.getAppCode()) + .eq(CashLedgerEntity::getDirection, "IN") + .ge(CashLedgerEntity::getReceivedAt, dayStart) + .lt(CashLedgerEntity::getReceivedAt, dayStart.plusDays(1))) + .stream().mapToLong(CashLedgerEntity::getAmountCent).sum(); + return AppInfoResponse.from(view(app), accounts == null ? 0 : accounts, todayAmount); + } + + private AppInfoResponse.AppEntityView view(AppEntity app) { + return new AppInfoResponse.AppEntityView(app.getAppCode(), app.getAppName(), + app.getAllowedRedirectHosts(), app.getWebhookUrl(), app.getTokenTtlSeconds(), + app.getEnabled(), app.getSecretExpiresAt(), + Integer.valueOf(1).equals(app.getHasPrevSecret()), app.getCreateTime()); + } + + private void assertTtl(int ttl) { + if (ttl < 60 || ttl > 86400) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "token 有效期需在 60~86400 秒之间"); + } + } + + private void assertHosts(String hosts) { + if (hosts.isEmpty()) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "必须配置跳转域名白名单"); + } + for (String host : hosts.split(",")) { + if (!isSafeHost(host)) { + throw new BizException(ErrorCode.VALIDATION_FAILED, + "跳转域名不合法:" + host.trim() + "(禁止通配符与 IP 直连)"); + } + } + } + + private void assertWebhookUrl(String url) { + if (url.isEmpty()) { + return; + } + if (!url.startsWith("https://")) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "webhook 地址必须使用 HTTPS"); + } + String host = hostOf(url); + if (host == null || !isSafeHost(host)) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "webhook 域名不合法(禁止 IP 直连与内网地址)"); + } + } + + public static String hostOf(String url) { + try { + String withoutScheme = url.replaceFirst("^[A-Za-z]+://", ""); + String host = withoutScheme.split("[/?#]")[0]; + int at = host.indexOf('@'); + if (at >= 0) { + host = host.substring(at + 1); + } + int port = host.indexOf(':'); + if (port >= 0) { + host = host.substring(0, port); + } + return host.isBlank() ? null : host.toLowerCase(); + } catch (Exception ex) { + return null; + } + } + + public static boolean isSafeHost(String host) { + String text = host == null ? "" : host.trim(); + if (text.isEmpty() || text.contains("*") || text.contains("/") || text.contains(":")) { + return false; + } + if (text.matches("^\\d{1,3}(\\.\\d{1,3}){3}$")) { + return false; + } + return text.matches("^[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"); + } + + private String newSecret(String prefix) { + return prefix + "_" + HexFormat.of().formatHex(HashUtils.randomBytes(24)); + } + + private String trim(String value) { + return value == null ? "" : value.trim(); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/audit/controller/AuditController.java b/finance-server/src/main/java/com/gas/fin/audit/controller/AuditController.java new file mode 100644 index 0000000..3f945a1 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/audit/controller/AuditController.java @@ -0,0 +1,141 @@ +package com.gas.fin.audit.controller; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.gas.fin.audit.dto.AuditLogResponse; +import com.gas.fin.audit.dto.ChainVerifyResult; +import com.gas.fin.audit.entity.AuditLogEntity; +import com.gas.fin.audit.service.AuditService; +import com.gas.fin.common.api.PageResult; +import com.gas.fin.common.api.R; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.security.AuthContext; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.security.RequirePermission; +import com.gas.fin.common.web.RequestUtils; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/api/admin/audit-logs") +public class AuditController { + + private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + private final AuditService auditService; + + public AuditController(AuditService auditService) { + this.auditService = auditService; + } + + @GetMapping + @RequirePermission(PermissionRegistry.AUDIT_VIEW) + public R> list( + @RequestParam(defaultValue = "1") long page, + @RequestParam(defaultValue = "20") long pageSize, + @RequestParam(required = false) String actor, + @RequestParam(required = false) String action, + @RequestParam(required = false) String result, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) String from, + @RequestParam(required = false) String to) { + validatePage(page, pageSize); + Page resultPage = auditService.page(page, pageSize, actor, action, result, keyword, + parseFrom(from), parseTo(to)); + List records = resultPage.getRecords().stream().map(AuditLogResponse::from).toList(); + return R.ok(PageResult.of(records, resultPage.getTotal(), page, pageSize)); + } + + @GetMapping("/export") + @RequirePermission({PermissionRegistry.EXPORT, PermissionRegistry.AUDIT_VIEW}) + public R> export( + @RequestParam(required = false) String actor, + @RequestParam(required = false) String action, + @RequestParam(required = false) String result, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) String from, + @RequestParam(required = false) String to, + HttpServletRequest httpRequest) { + List logs = auditService.listForExport(10000, actor, action, result, keyword, + parseFrom(from), parseTo(to)); + Map filter = new LinkedHashMap<>(); + filter.put("actor", actor); + filter.put("action", action); + filter.put("result", result); + filter.put("keyword", keyword); + filter.put("from", from); + filter.put("to", to); + filter.put("count", logs.size()); + auditService.record("ADMIN", AuthContext.require().getId(), AuthContext.require().getUsername(), + "AUDIT_EXPORT", "导出审计日志", "AUDIT", null, null, filter, + RequestUtils.clientIp(httpRequest, true), RequestUtils.userAgent(httpRequest)); + return R.ok(logs.stream().map(AuditLogResponse::from).toList()); + } + + @PostMapping("/verify") + @RequirePermission(PermissionRegistry.AUDIT_VIEW) + public R verify(HttpServletRequest httpRequest) { + ChainVerifyResult result = auditService.verifyChain(); + auditService.record("ADMIN", AuthContext.require().getId(), AuthContext.require().getUsername(), + "AUDIT_CHAIN_VERIFY", "校验审计链", "AUDIT", null, null, + Map.of("valid", result.isValid(), "checked", result.getChecked(), "brokenAtId", + result.getBrokenAtId() == null ? "" : result.getBrokenAtId()), + RequestUtils.clientIp(httpRequest, true), RequestUtils.userAgent(httpRequest)); + return R.ok(result); + } + + @GetMapping("/{id}") + @RequirePermission(PermissionRegistry.AUDIT_VIEW) + public R detail(@PathVariable Long id) { + return R.ok(AuditLogResponse.from(auditService.getById(id))); + } + + private void validatePage(long page, long pageSize) { + if (page < 1 || pageSize < 1 || pageSize > 100) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "分页参数不合法"); + } + } + + private LocalDateTime parseFrom(String value) { + if (value == null || value.isBlank()) { + return null; + } + String text = value.trim(); + try { + if (text.length() == 10) { + return LocalDate.parse(text).atStartOfDay(); + } + return LocalDateTime.parse(text, DATE_TIME); + } catch (DateTimeParseException ex) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "时间格式需为 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss"); + } + } + + private LocalDateTime parseTo(String value) { + if (value == null || value.isBlank()) { + return null; + } + String text = value.trim(); + try { + if (text.length() == 10) { + return LocalDate.parse(text).atTime(23, 59, 59); + } + return LocalDateTime.parse(text, DATE_TIME); + } catch (DateTimeParseException ex) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "时间格式需为 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss"); + } + } +} diff --git a/finance-server/src/main/java/com/gas/fin/audit/dto/AuditLogResponse.java b/finance-server/src/main/java/com/gas/fin/audit/dto/AuditLogResponse.java new file mode 100644 index 0000000..e8aaf13 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/audit/dto/AuditLogResponse.java @@ -0,0 +1,48 @@ +package com.gas.fin.audit.dto; + +import com.gas.fin.audit.entity.AuditLogEntity; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class AuditLogResponse { + + private Long id; + private String actorType; + private Long actorId; + private String actorName; + private String action; + private String actionLabel; + private String targetType; + private Long targetId; + private String beforeJson; + private String afterJson; + private String ip; + private String ua; + private String result; + private String prevHash; + private String curHash; + private LocalDateTime createTime; + + public static AuditLogResponse from(AuditLogEntity entity) { + AuditLogResponse response = new AuditLogResponse(); + response.setId(entity.getId()); + response.setActorType(entity.getActorType()); + response.setActorId(entity.getActorId()); + response.setActorName(entity.getActorName()); + response.setAction(entity.getAction()); + response.setActionLabel(entity.getActionLabel()); + response.setTargetType(entity.getTargetType()); + response.setTargetId(entity.getTargetId()); + response.setBeforeJson(entity.getBeforeJson()); + response.setAfterJson(entity.getAfterJson()); + response.setIp(entity.getIp()); + response.setUa(entity.getUa() == null ? "" : entity.getUa()); + response.setResult(entity.getResult()); + response.setPrevHash(entity.getPrevHash()); + response.setCurHash(entity.getCurHash()); + response.setCreateTime(entity.getCreateTime()); + return response; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/audit/dto/ChainVerifyResult.java b/finance-server/src/main/java/com/gas/fin/audit/dto/ChainVerifyResult.java new file mode 100644 index 0000000..42279e6 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/audit/dto/ChainVerifyResult.java @@ -0,0 +1,17 @@ +package com.gas.fin.audit.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@AllArgsConstructor +public class ChainVerifyResult { + + private boolean valid; + private int checked; + private Long brokenAtId; + private LocalDateTime checkedAt; + private String message; +} diff --git a/finance-server/src/main/java/com/gas/fin/audit/entity/AuditLogEntity.java b/finance-server/src/main/java/com/gas/fin/audit/entity/AuditLogEntity.java new file mode 100644 index 0000000..4ab902c --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/audit/entity/AuditLogEntity.java @@ -0,0 +1,32 @@ +package com.gas.fin.audit.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_audit_log") +public class AuditLogEntity { + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + private String actorType; + private Long actorId; + private String actorName; + private String action; + private String actionLabel; + private String targetType; + private Long targetId; + private String beforeJson; + private String afterJson; + private String ip; + private String ua; + private String result; + private String prevHash; + private String curHash; + private LocalDateTime createTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/audit/mapper/AuditLogMapper.java b/finance-server/src/main/java/com/gas/fin/audit/mapper/AuditLogMapper.java new file mode 100644 index 0000000..661a35b --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/audit/mapper/AuditLogMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.audit.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.audit.entity.AuditLogEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface AuditLogMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/audit/service/AuditService.java b/finance-server/src/main/java/com/gas/fin/audit/service/AuditService.java new file mode 100644 index 0000000..a61dd8e --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/audit/service/AuditService.java @@ -0,0 +1,265 @@ +package com.gas.fin.audit.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.gas.fin.audit.dto.ChainVerifyResult; +import com.gas.fin.audit.entity.AuditLogEntity; +import com.gas.fin.audit.mapper.AuditLogMapper; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.util.HashUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.UUID; + +/** + * 审计日志:只追加 + 哈希链 + 写入串行化。 + */ +@Service +public class AuditService { + + private static final Logger log = LoggerFactory.getLogger(AuditService.class); + private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + private final AuditLogMapper auditLogMapper; + private final StringRedisTemplate redisTemplate; + private final ObjectMapper objectMapper; + private final String chainLockKey; + private final Object localLock = new Object(); + + public AuditService(AuditLogMapper auditLogMapper, + StringRedisTemplate redisTemplate, + ObjectMapper objectMapper, + @Value("${fin.audit.chain-lock:lock:audit:chain}") String chainLockKey) { + this.auditLogMapper = auditLogMapper; + this.redisTemplate = redisTemplate; + this.objectMapper = objectMapper; + this.chainLockKey = chainLockKey; + } + + /** + * 成功审计:加入当前事务,随业务一起提交/回滚。 + */ + @Transactional + public void record(String actorType, Long actorId, String actorName, String action, String actionLabel, + String targetType, Long targetId, Object before, Object after, String ip, String ua) { + doRecord(actorType, actorId, actorName, action, actionLabel, targetType, targetId, + before, after, "SUCCESS", ip, ua); + } + + /** + * 失败审计:独立事务,业务回滚也不丢失败记录。 + */ + @Transactional(propagation = Propagation.REQUIRES_NEW) + public void recordFailure(String actorType, Long actorId, String actorName, String action, String actionLabel, + String targetType, Long targetId, Object before, Object after, String ip, String ua) { + doRecord(actorType, actorId, actorName, action, actionLabel, targetType, targetId, + before, after, "FAILED", ip, ua); + } + + private void doRecord(String actorType, Long actorId, String actorName, String action, String actionLabel, + String targetType, Long targetId, Object before, Object after, String result, + String ip, String ua) { + String canonicalBefore = canonicalJson(before); + String canonicalAfter = canonicalJson(after); + LocalDateTime now = LocalDateTime.now().withNano(0); + String timeText = now.format(TIME_FORMAT); + + String lockToken = UUID.randomUUID().toString(); + boolean locked = tryLock(lockToken); + if (!locked) { + synchronized (localLock) { + insertRecord(actorType, actorId, actorName, action, actionLabel, targetType, targetId, + canonicalBefore, canonicalAfter, result, ip, ua, now, timeText); + } + return; + } + try { + insertRecord(actorType, actorId, actorName, action, actionLabel, targetType, targetId, + canonicalBefore, canonicalAfter, result, ip, ua, now, timeText); + } finally { + try { + redisTemplate.delete(chainLockKey); + } catch (Exception ex) { + log.warn("release audit chain lock failed", ex); + } + } + } + + private void insertRecord(String actorType, Long actorId, String actorName, String action, String actionLabel, + String targetType, Long targetId, String canonicalBefore, String canonicalAfter, + String result, String ip, String ua, LocalDateTime now, String timeText) { + AuditLogEntity last = auditLogMapper.selectOne(new LambdaQueryWrapper() + .orderByDesc(AuditLogEntity::getId) + .last("LIMIT 1")); + String prevHash = last == null ? "" : last.getCurHash(); + + String payload = prevHash + "|" + actorType + "|" + (actorId == null ? "" : actorId) + "|" + + actorName + "|" + action + "|" + targetType + "|" + (targetId == null ? "" : targetId) + "|" + + result + "|" + timeText + "|" + HashUtils.sha256Hex(canonicalBefore) + "|" + + HashUtils.sha256Hex(canonicalAfter); + String curHash = HashUtils.sha256Hex(payload); + + AuditLogEntity entity = new AuditLogEntity(); + entity.setActorType(actorType); + entity.setActorId(actorId); + entity.setActorName(actorName == null ? "" : actorName); + entity.setAction(action); + entity.setActionLabel(actionLabel == null ? action : actionLabel); + entity.setTargetType(targetType); + entity.setTargetId(targetId); + entity.setBeforeJson(canonicalBefore); + entity.setAfterJson(canonicalAfter); + entity.setIp(ip == null || ip.isBlank() ? "unknown" : ip); + entity.setUa(ua == null ? "" : ua); + entity.setResult(result); + entity.setPrevHash(prevHash); + entity.setCurHash(curHash); + entity.setCreateTime(now); + auditLogMapper.insert(entity); + } + + private boolean tryLock(String token) { + try { + for (int i = 0; i < 60; i++) { + Boolean ok = redisTemplate.opsForValue().setIfAbsent(chainLockKey, token, Duration.ofSeconds(3)); + if (Boolean.TRUE.equals(ok)) { + return true; + } + Thread.sleep(50); + } + } catch (Exception ex) { + log.warn("audit chain lock unavailable, fallback to local lock", ex); + } + return false; + } + + public Page page(long page, long pageSize, String actor, String action, String result, + String keyword, LocalDateTime from, LocalDateTime to) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (actor != null && !actor.isBlank()) { + wrapper.like(AuditLogEntity::getActorName, actor.trim()); + } + if (action != null && !action.isBlank()) { + wrapper.eq(AuditLogEntity::getAction, action.trim()); + } + if (result != null && !result.isBlank()) { + wrapper.eq(AuditLogEntity::getResult, result.trim()); + } + if (keyword != null && !keyword.isBlank()) { + String value = keyword.trim(); + wrapper.and(w -> w.like(AuditLogEntity::getActorName, value) + .or().like(AuditLogEntity::getAction, value) + .or().like(AuditLogEntity::getTargetType, value)); + } + if (from != null) { + wrapper.ge(AuditLogEntity::getCreateTime, from); + } + if (to != null) { + wrapper.le(AuditLogEntity::getCreateTime, to); + } + wrapper.orderByDesc(AuditLogEntity::getCreateTime).orderByDesc(AuditLogEntity::getId); + return auditLogMapper.selectPage(new Page<>(page, pageSize), wrapper); + } + + public List listForExport(long limit, String actor, String action, String result, + String keyword, LocalDateTime from, LocalDateTime to) { + Page page = page(1, Math.min(limit + 1, 10001), actor, action, result, keyword, from, to); + if (page.getTotal() > limit) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "导出数据超过 10000 行,请缩小查询范围"); + } + return page.getRecords(); + } + + public AuditLogEntity getById(Long id) { + AuditLogEntity entity = auditLogMapper.selectById(id); + if (entity == null) { + throw new BizException(ErrorCode.NOT_FOUND); + } + return entity; + } + + @Transactional + public ChainVerifyResult verifyChain() { + List logs = auditLogMapper.selectList(new LambdaQueryWrapper() + .orderByAsc(AuditLogEntity::getId)); + String expectedPrev = ""; + int checked = 0; + for (AuditLogEntity log : logs) { + checked++; + String canonicalBefore = canonicalJson(log.getBeforeJson()); + String canonicalAfter = canonicalJson(log.getAfterJson()); + String timeText = log.getCreateTime().format(TIME_FORMAT); + String payload = expectedPrev + "|" + log.getActorType() + "|" + + (log.getActorId() == null ? "" : log.getActorId()) + "|" + + log.getActorName() + "|" + log.getAction() + "|" + log.getTargetType() + "|" + + (log.getTargetId() == null ? "" : log.getTargetId()) + "|" + + log.getResult() + "|" + timeText + "|" + + HashUtils.sha256Hex(canonicalBefore) + "|" + HashUtils.sha256Hex(canonicalAfter); + String computed = HashUtils.sha256Hex(payload); + if (!expectedPrev.equals(log.getPrevHash()) || !computed.equals(log.getCurHash())) { + return new ChainVerifyResult(false, checked, log.getId(), LocalDateTime.now().withNano(0), + "审计链在第 " + log.getId() + " 条断裂"); + } + expectedPrev = log.getCurHash(); + } + return new ChainVerifyResult(true, checked, null, LocalDateTime.now().withNano(0), "审计链完整"); + } + + private String canonicalJson(Object value) { + if (value == null) { + return null; + } + try { + JsonNode node; + if (value instanceof String text) { + if (text.isBlank()) { + return null; + } + node = objectMapper.readTree(text); + } else { + node = objectMapper.valueToTree(value); + } + return objectMapper.writeValueAsString(sortNode(node)); + } catch (Exception ex) { + log.warn("审计 JSON 规范化失败,按原文保存", ex); + return String.valueOf(value); + } + } + + /** + * 递归排序对象字段,保证 MySQL JSON 列回读后仍可复现同一哈希。 + */ + private JsonNode sortNode(JsonNode node) { + if (node.isObject()) { + ObjectNode sorted = objectMapper.createObjectNode(); + List names = new java.util.ArrayList<>(); + node.fieldNames().forEachRemaining(names::add); + names.sort(String::compareTo); + for (String name : names) { + sorted.set(name, sortNode(node.get(name))); + } + return sorted; + } + if (node.isArray()) { + ArrayNode sorted = objectMapper.createArrayNode(); + node.forEach(child -> sorted.add(sortNode(child))); + return sorted; + } + return node; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/auth/controller/AuthController.java b/finance-server/src/main/java/com/gas/fin/auth/controller/AuthController.java new file mode 100644 index 0000000..20d73c7 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/auth/controller/AuthController.java @@ -0,0 +1,56 @@ +package com.gas.fin.auth.controller; + +import com.gas.fin.auth.dto.ChangePasswordRequest; +import com.gas.fin.auth.dto.LoginRequest; +import com.gas.fin.auth.dto.LoginResponse; +import com.gas.fin.auth.dto.ProfileResponse; +import com.gas.fin.auth.service.AuthService; +import com.gas.fin.common.api.R; +import com.gas.fin.common.security.AuthContext; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.security.RequirePermission; +import com.gas.fin.common.web.RequestUtils; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Valid; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/admin") +public class AuthController { + + private final AuthService authService; + + public AuthController(AuthService authService) { + this.authService = authService; + } + + @PostMapping("/login") + public R login(@Valid @RequestBody LoginRequest request, HttpServletRequest httpRequest) { + return R.ok(authService.login(request, httpRequest)); + } + + @PostMapping("/logout") + @RequirePermission(PermissionRegistry.VIEW) + public R logout(HttpServletRequest httpRequest) { + authService.logout(AuthContext.require(), RequestUtils.bearerToken(httpRequest), httpRequest); + return R.ok(); + } + + @GetMapping("/profile") + @RequirePermission(PermissionRegistry.VIEW) + public R profile() { + return R.ok(authService.profile(AuthContext.require())); + } + + @PostMapping("/password/change") + @RequirePermission(PermissionRegistry.VIEW) + public R changePassword(@Valid @RequestBody ChangePasswordRequest request, + HttpServletRequest httpRequest) { + authService.changePassword(AuthContext.require(), request, RequestUtils.bearerToken(httpRequest), httpRequest); + return R.ok(); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/auth/dto/AdminInfoResponse.java b/finance-server/src/main/java/com/gas/fin/auth/dto/AdminInfoResponse.java new file mode 100644 index 0000000..1218956 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/auth/dto/AdminInfoResponse.java @@ -0,0 +1,38 @@ +package com.gas.fin.auth.dto; + +import com.gas.fin.admin.entity.AdminEntity; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class AdminInfoResponse { + + private Long id; + private String username; + private String role; + private Integer isActive; + private Integer mustChangePassword; + private boolean totpBound; + private Integer failedAttempts; + private LocalDateTime lockedUntil; + private LocalDateTime lastLoginAt; + private String lastLoginIp; + private LocalDateTime createTime; + + public static AdminInfoResponse from(AdminEntity entity) { + AdminInfoResponse response = new AdminInfoResponse(); + response.setId(entity.getId()); + response.setUsername(entity.getUsername()); + response.setRole(entity.getRole()); + response.setIsActive(entity.getIsActive()); + response.setMustChangePassword(entity.getMustChangePassword()); + response.setTotpBound(Integer.valueOf(1).equals(entity.getTotpBound())); + response.setFailedAttempts(entity.getFailedAttempts()); + response.setLockedUntil(entity.getLockedUntil()); + response.setLastLoginAt(entity.getLastLoginAt()); + response.setLastLoginIp(entity.getLastLoginIp()); + response.setCreateTime(entity.getCreateTime()); + return response; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/auth/dto/ChangePasswordRequest.java b/finance-server/src/main/java/com/gas/fin/auth/dto/ChangePasswordRequest.java new file mode 100644 index 0000000..c61fbc4 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/auth/dto/ChangePasswordRequest.java @@ -0,0 +1,16 @@ +package com.gas.fin.auth.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; +import lombok.Data; + +@Data +public class ChangePasswordRequest { + + @NotBlank(message = "原密码不能为空") + @Size(max = 128, message = "原密码长度不能超过 128") + private String oldPassword; + + @NotBlank(message = "新密码不能为空") + private String newPassword; +} diff --git a/finance-server/src/main/java/com/gas/fin/auth/dto/LoginRequest.java b/finance-server/src/main/java/com/gas/fin/auth/dto/LoginRequest.java new file mode 100644 index 0000000..151255a --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/auth/dto/LoginRequest.java @@ -0,0 +1,19 @@ +package com.gas.fin.auth.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; +import lombok.Data; + +@Data +public class LoginRequest { + + @NotBlank(message = "用户名不能为空") + @Size(max = 32, message = "用户名长度不能超过 32") + private String username; + + @NotBlank(message = "密码不能为空") + @Size(max = 128, message = "密码长度不能超过 128") + private String password; + + private String totp; +} diff --git a/finance-server/src/main/java/com/gas/fin/auth/dto/LoginResponse.java b/finance-server/src/main/java/com/gas/fin/auth/dto/LoginResponse.java new file mode 100644 index 0000000..eba0c87 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/auth/dto/LoginResponse.java @@ -0,0 +1,15 @@ +package com.gas.fin.auth.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.util.List; + +@Data +@AllArgsConstructor +public class LoginResponse { + + private String token; + private AdminInfoResponse admin; + private List permissions; +} diff --git a/finance-server/src/main/java/com/gas/fin/auth/dto/ProfileResponse.java b/finance-server/src/main/java/com/gas/fin/auth/dto/ProfileResponse.java new file mode 100644 index 0000000..f3adaf8 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/auth/dto/ProfileResponse.java @@ -0,0 +1,14 @@ +package com.gas.fin.auth.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.util.List; + +@Data +@AllArgsConstructor +public class ProfileResponse { + + private AdminInfoResponse admin; + private List permissions; +} diff --git a/finance-server/src/main/java/com/gas/fin/auth/service/AuthService.java b/finance-server/src/main/java/com/gas/fin/auth/service/AuthService.java new file mode 100644 index 0000000..beb7250 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/auth/service/AuthService.java @@ -0,0 +1,233 @@ +package com.gas.fin.auth.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.admin.mapper.AdminMapper; +import com.gas.fin.auth.dto.AdminInfoResponse; +import com.gas.fin.auth.dto.ChangePasswordRequest; +import com.gas.fin.auth.dto.LoginRequest; +import com.gas.fin.auth.dto.LoginResponse; +import com.gas.fin.auth.dto.ProfileResponse; +import com.gas.fin.audit.service.AuditService; +import com.gas.fin.common.crypto.CryptoService; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.totp.TotpService; +import com.gas.fin.common.util.HashUtils; +import com.gas.fin.common.util.PasswordUtils; +import com.gas.fin.common.web.RequestUtils; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; + +/** + * 登录、登出、改密与会话签发。 + */ +@Service +public class AuthService { + + private final AdminMapper adminMapper; + private final PasswordEncoder passwordEncoder; + private final TotpService totpService; + private final CryptoService cryptoService; + private final AuditService auditService; + private final SessionService sessionService; + private final PasswordHistoryService passwordHistoryService; + private final LoginRateLimiter loginRateLimiter; + private final String dummyHash; + + @Value("${fin.trust-proxy:true}") + private boolean trustProxy; + + @Value("${fin.auth.lock-threshold:5}") + private int lockThreshold; + + @Value("${fin.auth.lock-minutes:15}") + private int lockMinutes; + + public AuthService(AdminMapper adminMapper, + PasswordEncoder passwordEncoder, + TotpService totpService, + CryptoService cryptoService, + AuditService auditService, + SessionService sessionService, + PasswordHistoryService passwordHistoryService, + LoginRateLimiter loginRateLimiter) { + this.adminMapper = adminMapper; + this.passwordEncoder = passwordEncoder; + this.totpService = totpService; + this.cryptoService = cryptoService; + this.auditService = auditService; + this.sessionService = sessionService; + this.passwordHistoryService = passwordHistoryService; + this.loginRateLimiter = loginRateLimiter; + this.dummyHash = passwordEncoder.encode("dummy-password-for-timing"); + } + + public LoginResponse login(LoginRequest request, HttpServletRequest httpRequest) { + String username = request.getUsername().trim().toLowerCase(Locale.ROOT); + String ip = RequestUtils.clientIp(httpRequest, trustProxy); + String ua = RequestUtils.userAgent(httpRequest); + + loginRateLimiter.check(username, ip); + + AdminEntity admin = adminMapper.selectOne(new LambdaQueryWrapper() + .eq(AdminEntity::getUsername, username) + .last("LIMIT 1")); + + if (admin == null) { + // 不存在账号也执行一次哈希,避免响应耗时泄露账号是否存在 + passwordEncoder.matches(request.getPassword(), dummyHash); + auditLoginFailure(null, username, ip, ua, 0, null); + throw new BizException(ErrorCode.LOGIN_FAILED); + } + + LocalDateTime now = LocalDateTime.now(); + if (admin.getLockedUntil() != null && admin.getLockedUntil().isAfter(now)) { + long remain = Math.max(1, Duration.between(now, admin.getLockedUntil()).toMinutes() + 1); + auditLoginFailure(admin, username, ip, ua, admin.getFailedAttempts(), admin.getLockedUntil()); + throw new BizException(ErrorCode.ACCOUNT_LOCKED, "账号已锁定,请 " + remain + " 分钟后重试"); + } + if (admin.getLockedUntil() != null) { + adminMapper.update(null, new LambdaUpdateWrapper() + .eq(AdminEntity::getId, admin.getId()) + .set(AdminEntity::getFailedAttempts, 0) + .set(AdminEntity::getLockedUntil, null)); + admin.setFailedAttempts(0); + admin.setLockedUntil(null); + } + + if (!passwordEncoder.matches(request.getPassword(), admin.getPasswordHash())) { + failAndThrow(admin, ip, ua, ErrorCode.LOGIN_FAILED); + } + + if (!Integer.valueOf(1).equals(admin.getIsActive())) { + auditLoginFailure(admin, username, ip, ua, admin.getFailedAttempts(), admin.getLockedUntil()); + throw new BizException(ErrorCode.ACCOUNT_DISABLED); + } + + String secret = safeDecrypt(admin.getTotpSecretEnc()); + TotpService.Result totpResult = totpService.verify(secret, request.getTotp(), admin.getId()); + if (totpResult == TotpService.Result.FORMAT_INVALID) { + auditLoginFailure(admin, username, ip, ua, admin.getFailedAttempts(), admin.getLockedUntil()); + throw new BizException(ErrorCode.TOTP_FAILED); + } + if (totpResult != TotpService.Result.OK) { + failAndThrow(admin, ip, ua, ErrorCode.TOTP_FAILED); + } + + LocalDateTime loginAt = LocalDateTime.now().withNano(0); + adminMapper.update(null, new LambdaUpdateWrapper() + .eq(AdminEntity::getId, admin.getId()) + .set(AdminEntity::getFailedAttempts, 0) + .set(AdminEntity::getLockedUntil, null) + .set(AdminEntity::getLastLoginAt, loginAt) + .set(AdminEntity::getLastLoginIp, ip) + .set(AdminEntity::getTotpBound, 1) + .set(AdminEntity::getVersionNo, admin.getVersionNo() == null ? 1 : admin.getVersionNo() + 1)); + admin.setFailedAttempts(0); + admin.setLockedUntil(null); + admin.setLastLoginAt(loginAt); + admin.setLastLoginIp(ip); + admin.setTotpBound(1); + + String token = HashUtils.randomBase64Url(32); + sessionService.create(admin, token, ip, ua); + auditService.record("ADMIN", admin.getId(), admin.getUsername(), "LOGIN", "登录", + "ADMIN", admin.getId(), null, null, ip, ua); + + return new LoginResponse(token, AdminInfoResponse.from(admin), PermissionRegistry.permissionsOf(admin.getRole())); + } + + public ProfileResponse profile(AdminEntity admin) { + return new ProfileResponse(AdminInfoResponse.from(admin), PermissionRegistry.permissionsOf(admin.getRole())); + } + + public void logout(AdminEntity admin, String token, HttpServletRequest httpRequest) { + String ip = RequestUtils.clientIp(httpRequest, trustProxy); + String ua = RequestUtils.userAgent(httpRequest); + sessionService.revokeByToken(token); + auditService.record("ADMIN", admin.getId(), admin.getUsername(), "LOGOUT", "登出", + "ADMIN", admin.getId(), null, null, ip, ua); + } + + public void changePassword(AdminEntity admin, ChangePasswordRequest request, String token, + HttpServletRequest httpRequest) { + String ip = RequestUtils.clientIp(httpRequest, trustProxy); + String ua = RequestUtils.userAgent(httpRequest); + + if (!passwordEncoder.matches(request.getOldPassword(), admin.getPasswordHash())) { + auditService.recordFailure("ADMIN", admin.getId(), admin.getUsername(), + "PASSWORD_CHANGE", "修改密码", "ADMIN", admin.getId(), null, null, ip, ua); + throw new BizException(ErrorCode.OLD_PASSWORD_MISMATCH); + } + if (!PasswordUtils.isStrong(request.getNewPassword())) { + throw new BizException(ErrorCode.PASSWORD_WEAK); + } + passwordHistoryService.validateNotReused(admin.getId(), admin.getPasswordHash(), request.getNewPassword()); + + String newHash = passwordEncoder.encode(request.getNewPassword()); + adminMapper.update(null, new LambdaUpdateWrapper() + .eq(AdminEntity::getId, admin.getId()) + .set(AdminEntity::getPasswordHash, newHash) + .set(AdminEntity::getMustChangePassword, 0) + .set(AdminEntity::getPasswordUpdatedAt, LocalDateTime.now().withNano(0)) + .set(AdminEntity::getFailedAttempts, 0) + .set(AdminEntity::getLockedUntil, null) + .set(AdminEntity::getVersionNo, admin.getVersionNo() == null ? 1 : admin.getVersionNo() + 1)); + + passwordHistoryService.record(admin.getId(), admin.getPasswordHash()); + + SessionService.SessionContext current = sessionService.validate(token); + sessionService.revokeOthers(admin.getId(), current.session().getId()); + + Map before = new LinkedHashMap<>(); + before.put("mustChangePassword", admin.getMustChangePassword()); + Map after = new LinkedHashMap<>(); + after.put("mustChangePassword", 0); + auditService.record("ADMIN", admin.getId(), admin.getUsername(), "PASSWORD_CHANGE", "修改密码", + "ADMIN", admin.getId(), before, after, ip, ua); + } + + private void failAndThrow(AdminEntity admin, String ip, String ua, ErrorCode errorCode) { + int attempts = (admin.getFailedAttempts() == null ? 0 : admin.getFailedAttempts()) + 1; + LocalDateTime lockedUntil = attempts >= lockThreshold + ? LocalDateTime.now().withNano(0).plusMinutes(lockMinutes) + : null; + adminMapper.update(null, new LambdaUpdateWrapper() + .eq(AdminEntity::getId, admin.getId()) + .set(AdminEntity::getFailedAttempts, attempts) + .set(AdminEntity::getLockedUntil, lockedUntil)); + auditLoginFailure(admin, admin.getUsername(), ip, ua, attempts, lockedUntil); + if (lockedUntil != null) { + throw new BizException(ErrorCode.ACCOUNT_LOCKED, "账号已锁定,请 " + lockMinutes + " 分钟后重试"); + } + throw new BizException(errorCode); + } + + private void auditLoginFailure(AdminEntity admin, String username, String ip, String ua, + Integer attempts, LocalDateTime lockedUntil) { + Map after = new LinkedHashMap<>(); + after.put("failedAttempts", attempts == null ? 0 : attempts); + after.put("lockedUntil", lockedUntil == null ? "" : lockedUntil.toString()); + auditService.recordFailure("ADMIN", admin == null ? null : admin.getId(), username, + "LOGIN", "登录", "ADMIN", admin == null ? null : admin.getId(), null, after, ip, ua); + } + + private String safeDecrypt(String value) { + try { + return cryptoService.decrypt(value); + } catch (Exception ex) { + return null; + } + } +} diff --git a/finance-server/src/main/java/com/gas/fin/auth/service/LoginRateLimiter.java b/finance-server/src/main/java/com/gas/fin/auth/service/LoginRateLimiter.java new file mode 100644 index 0000000..bb2fa36 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/auth/service/LoginRateLimiter.java @@ -0,0 +1,47 @@ +package com.gas.fin.auth.service; + +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; + +import java.time.Duration; + +/** + * 登录限流:用户名 5 次/5 分钟,IP 20 次/5 分钟。 + */ +@Service +public class LoginRateLimiter { + + private static final Logger log = LoggerFactory.getLogger(LoginRateLimiter.class); + private static final int WINDOW_SECONDS = 300; + + private final StringRedisTemplate redisTemplate; + + public LoginRateLimiter(StringRedisTemplate redisTemplate) { + this.redisTemplate = redisTemplate; + } + + public void check(String username, String ip) { + checkKey("rate:login:user:" + username, 5); + checkKey("rate:login:ip:" + ip, 20); + } + + private void checkKey(String key, int limit) { + try { + Long count = redisTemplate.opsForValue().increment(key); + if (count != null && count == 1L) { + redisTemplate.expire(key, Duration.ofSeconds(WINDOW_SECONDS)); + } + if (count != null && count > limit) { + throw new BizException(ErrorCode.TOO_MANY_REQUESTS, "操作过于频繁,请稍后再试"); + } + } catch (BizException ex) { + throw ex; + } catch (Exception ex) { + log.warn("登录限流不可用,放行本次请求 key={}", key, ex); + } + } +} diff --git a/finance-server/src/main/java/com/gas/fin/auth/service/PasswordHistoryService.java b/finance-server/src/main/java/com/gas/fin/auth/service/PasswordHistoryService.java new file mode 100644 index 0000000..184780a --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/auth/service/PasswordHistoryService.java @@ -0,0 +1,67 @@ +package com.gas.fin.auth.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.gas.fin.admin.entity.AdminPasswordHistoryEntity; +import com.gas.fin.admin.mapper.AdminPasswordHistoryMapper; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.List; + +/** + * 密码历史:不得等于当前密码,不得命中最近 N 次历史。 + */ +@Service +public class PasswordHistoryService { + + private final AdminPasswordHistoryMapper historyMapper; + private final PasswordEncoder passwordEncoder; + private final int historySize; + + public PasswordHistoryService(AdminPasswordHistoryMapper historyMapper, + PasswordEncoder passwordEncoder, + @Value("${fin.auth.password-history-size:3}") int historySize) { + this.historyMapper = historyMapper; + this.passwordEncoder = passwordEncoder; + this.historySize = historySize; + } + + public void validateNotReused(Long adminId, String currentHash, String newPassword) { + if (passwordEncoder.matches(newPassword, currentHash)) { + throw new BizException(ErrorCode.PASSWORD_REUSED); + } + for (AdminPasswordHistoryEntity history : recent(adminId)) { + if (passwordEncoder.matches(newPassword, history.getPasswordHash())) { + throw new BizException(ErrorCode.PASSWORD_REUSED); + } + } + } + + public void record(Long adminId, String oldHash) { + AdminPasswordHistoryEntity entity = new AdminPasswordHistoryEntity(); + entity.setAdminId(adminId); + entity.setPasswordHash(oldHash); + entity.setCreateTime(LocalDateTime.now().withNano(0)); + historyMapper.insert(entity); + + List recent = recent(adminId); + if (recent.size() > historySize) { + List expireIds = recent.subList(historySize, recent.size()).stream() + .map(AdminPasswordHistoryEntity::getId) + .toList(); + historyMapper.deleteBatchIds(expireIds); + } + } + + private List recent(Long adminId) { + return historyMapper.selectList(new LambdaQueryWrapper() + .eq(AdminPasswordHistoryEntity::getAdminId, adminId) + .orderByDesc(AdminPasswordHistoryEntity::getCreateTime) + .orderByDesc(AdminPasswordHistoryEntity::getId) + .last("LIMIT 100")); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/auth/service/SessionService.java b/finance-server/src/main/java/com/gas/fin/auth/service/SessionService.java new file mode 100644 index 0000000..e175128 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/auth/service/SessionService.java @@ -0,0 +1,124 @@ +package com.gas.fin.auth.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.admin.entity.AdminSessionEntity; +import com.gas.fin.admin.mapper.AdminMapper; +import com.gas.fin.admin.mapper.AdminSessionMapper; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.util.HashUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; + +/** + * 管理员会话:30 分钟空闲滑动 + 8 小时绝对上限,DB 为权威,Redis 不参与会话判定。 + */ +@Service +public class SessionService { + + private final AdminSessionMapper sessionMapper; + private final AdminMapper adminMapper; + private final int idleMinutes; + private final int absoluteHours; + + public SessionService(AdminSessionMapper sessionMapper, + AdminMapper adminMapper, + @Value("${fin.auth.idle-minutes:30}") int idleMinutes, + @Value("${fin.auth.absolute-hours:8}") int absoluteHours) { + this.sessionMapper = sessionMapper; + this.adminMapper = adminMapper; + this.idleMinutes = idleMinutes; + this.absoluteHours = absoluteHours; + } + + public record SessionContext(AdminEntity admin, AdminSessionEntity session) { + } + + public AdminSessionEntity create(AdminEntity admin, String token, String ip, String ua) { + LocalDateTime now = LocalDateTime.now().withNano(0); + AdminSessionEntity session = new AdminSessionEntity(); + session.setAdminId(admin.getId()); + session.setTokenHash(HashUtils.sha256Hex(token)); + session.setIssuedIp(ip); + session.setUserAgent(ua); + session.setLastActiveAt(now); + session.setIdleExpireAt(now.plusMinutes(idleMinutes)); + session.setAbsoluteExpireAt(now.plusHours(absoluteHours)); + session.setCreateTime(now); + sessionMapper.insert(session); + return session; + } + + public SessionContext validate(String token) { + if (token == null || token.isBlank()) { + throw new BizException(ErrorCode.UNAUTHORIZED); + } + String tokenHash = HashUtils.sha256Hex(token); + AdminSessionEntity session = sessionMapper.selectOne(new LambdaQueryWrapper() + .eq(AdminSessionEntity::getTokenHash, tokenHash) + .last("LIMIT 1")); + if (session == null || session.getRevokedAt() != null) { + throw new BizException(ErrorCode.UNAUTHORIZED); + } + LocalDateTime now = LocalDateTime.now(); + if (!now.isBefore(session.getAbsoluteExpireAt()) || !now.isBefore(session.getIdleExpireAt())) { + revokeSession(session.getId()); + throw new BizException(ErrorCode.UNAUTHORIZED); + } + AdminEntity admin = adminMapper.selectById(session.getAdminId()); + if (admin == null || !Integer.valueOf(1).equals(admin.getIsActive())) { + revokeSession(session.getId()); + throw new BizException(ErrorCode.UNAUTHORIZED); + } + + LocalDateTime nowSecond = now.withNano(0); + if (session.getLastActiveAt() == null || session.getLastActiveAt().plusSeconds(60).isBefore(nowSecond)) { + sessionMapper.update(null, new LambdaUpdateWrapper() + .eq(AdminSessionEntity::getId, session.getId()) + .set(AdminSessionEntity::getLastActiveAt, nowSecond) + .set(AdminSessionEntity::getIdleExpireAt, nowSecond.plusMinutes(idleMinutes))); + session.setLastActiveAt(nowSecond); + session.setIdleExpireAt(nowSecond.plusMinutes(idleMinutes)); + } + return new SessionContext(admin, session); + } + + public void revokeByToken(String token) { + if (token == null || token.isBlank()) { + return; + } + sessionMapper.update(null, new LambdaUpdateWrapper() + .eq(AdminSessionEntity::getTokenHash, HashUtils.sha256Hex(token)) + .isNull(AdminSessionEntity::getRevokedAt) + .set(AdminSessionEntity::getRevokedAt, LocalDateTime.now().withNano(0))); + } + + public void revokeAll(Long adminId) { + sessionMapper.update(null, new LambdaUpdateWrapper() + .eq(AdminSessionEntity::getAdminId, adminId) + .isNull(AdminSessionEntity::getRevokedAt) + .set(AdminSessionEntity::getRevokedAt, LocalDateTime.now().withNano(0))); + } + + public void revokeOthers(Long adminId, Long keepSessionId) { + LambdaUpdateWrapper wrapper = new LambdaUpdateWrapper() + .eq(AdminSessionEntity::getAdminId, adminId) + .isNull(AdminSessionEntity::getRevokedAt) + .set(AdminSessionEntity::getRevokedAt, LocalDateTime.now().withNano(0)); + if (keepSessionId != null) { + wrapper.ne(AdminSessionEntity::getId, keepSessionId); + } + sessionMapper.update(null, wrapper); + } + + private void revokeSession(Long sessionId) { + sessionMapper.update(null, new LambdaUpdateWrapper() + .eq(AdminSessionEntity::getId, sessionId) + .isNull(AdminSessionEntity::getRevokedAt) + .set(AdminSessionEntity::getRevokedAt, LocalDateTime.now().withNano(0))); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/api/PageResult.java b/finance-server/src/main/java/com/gas/fin/common/api/PageResult.java new file mode 100644 index 0000000..46107db --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/api/PageResult.java @@ -0,0 +1,20 @@ +package com.gas.fin.common.api; + +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.List; + +/** + * 统一分页响应,字段名与前端 PageResult 一致。 + */ +@JsonPropertyOrder({"records", "total", "page", "pageSize"}) +public record PageResult(List records, long total, long page, long pageSize) { + + public static PageResult of(List records, long total, long page, long pageSize) { + return new PageResult<>(records, total, page, pageSize); + } + + public static PageResult empty(long page, long pageSize) { + return new PageResult<>(List.of(), 0, page, pageSize); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/api/R.java b/finance-server/src/main/java/com/gas/fin/common/api/R.java new file mode 100644 index 0000000..6ec5081 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/api/R.java @@ -0,0 +1,25 @@ +package com.gas.fin.common.api; + +import com.gas.fin.common.web.TraceId; + +/** + * 统一响应体:HTTP 固定 200,业务结果由 code 表达。 + */ +public record R(int code, String message, T data, String traceId) { + + public static R ok(T data) { + return new R<>(0, "success", data, TraceId.current()); + } + + public static R ok() { + return ok(null); + } + + public static R fail(int code, String message) { + return new R<>(code, message, null, TraceId.current()); + } + + public static R fail(int code, String message, T data) { + return new R<>(code, message, data, TraceId.current()); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/crypto/CryptoService.java b/finance-server/src/main/java/com/gas/fin/common/crypto/CryptoService.java new file mode 100644 index 0000000..dd828b9 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/crypto/CryptoService.java @@ -0,0 +1,105 @@ +package com.gas.fin.common.crypto; + +import jakarta.annotation.PostConstruct; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.SecureRandom; +import java.util.Base64; + +/** + * AES-256-GCM 加解密:用于 TOTP secret、webhook secret 等需要还原原文的字段。 + * 主密钥优先取 FIN_SECRET_ENC_KEY(32 字节 Base64);本地开发缺省时生成到 .runtime/secret-enc.key。 + */ +@Component +public class CryptoService { + + private static final Logger log = LoggerFactory.getLogger(CryptoService.class); + private static final SecureRandom RANDOM = new SecureRandom(); + private static final int IV_LENGTH = 12; + private static final int TAG_BITS = 128; + + @Value("${fin.secret-enc-key:}") + private String configuredKey; + + @Value("${fin.runtime-dir:./.runtime}") + private String runtimeDir; + + private SecretKeySpec key; + + @PostConstruct + public void init() { + byte[] keyBytes; + if (configuredKey != null && !configuredKey.isBlank()) { + keyBytes = Base64.getDecoder().decode(configuredKey.trim()); + } else { + keyBytes = loadOrCreateLocalKey(); + } + if (keyBytes.length != 32) { + throw new IllegalStateException("FIN_SECRET_ENC_KEY must be 32 bytes (Base64)"); + } + this.key = new SecretKeySpec(keyBytes, "AES"); + } + + public String encrypt(String plaintext) { + if (plaintext == null) { + return null; + } + try { + byte[] iv = new byte[IV_LENGTH]; + RANDOM.nextBytes(iv); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, iv)); + byte[] cipherText = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)); + byte[] combined = new byte[iv.length + cipherText.length]; + System.arraycopy(iv, 0, combined, 0, iv.length); + System.arraycopy(cipherText, 0, combined, iv.length, cipherText.length); + return Base64.getEncoder().encodeToString(combined); + } catch (Exception ex) { + throw new IllegalStateException("encrypt failed", ex); + } + } + + public String decrypt(String cipherText) { + if (cipherText == null || cipherText.isBlank()) { + return null; + } + try { + byte[] combined = Base64.getDecoder().decode(cipherText); + byte[] iv = new byte[IV_LENGTH]; + System.arraycopy(combined, 0, iv, 0, IV_LENGTH); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, iv)); + byte[] plain = cipher.doFinal(combined, IV_LENGTH, combined.length - IV_LENGTH); + return new String(plain, StandardCharsets.UTF_8); + } catch (Exception ex) { + throw new IllegalStateException("decrypt failed", ex); + } + } + + private byte[] loadOrCreateLocalKey() { + try { + Path dir = Path.of(runtimeDir); + Path file = dir.resolve("secret-enc.key"); + if (Files.exists(file)) { + return Base64.getDecoder().decode(Files.readString(file).trim()); + } + Files.createDirectories(dir); + byte[] bytes = new byte[32]; + RANDOM.nextBytes(bytes); + Files.writeString(file, Base64.getEncoder().encodeToString(bytes)); + log.warn("FIN_SECRET_ENC_KEY 未配置,已生成本地开发密钥: {}", file.toAbsolutePath()); + return bytes; + } catch (Exception ex) { + throw new IllegalStateException("cannot initialize local encryption key", ex); + } + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/dto/ToggleRequest.java b/finance-server/src/main/java/com/gas/fin/common/dto/ToggleRequest.java new file mode 100644 index 0000000..9038c49 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/dto/ToggleRequest.java @@ -0,0 +1,7 @@ +package com.gas.fin.common.dto; + +/** + * 通用启停请求:{@code enabled} 1 启用 / 0 停用。 + */ +public record ToggleRequest(Integer enabled) { +} diff --git a/finance-server/src/main/java/com/gas/fin/common/error/BizException.java b/finance-server/src/main/java/com/gas/fin/common/error/BizException.java new file mode 100644 index 0000000..9e30ffd --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/error/BizException.java @@ -0,0 +1,44 @@ +package com.gas.fin.common.error; + +/** + * 可预期的业务异常。HTTP 状态仍为 200,业务错误通过 code 表达。 + */ +public class BizException extends RuntimeException { + + private final int code; + private final transient Object data; + + public BizException(int code, String message) { + this(code, message, null); + } + + public BizException(int code, String message, Object data) { + super(message); + this.code = code; + this.data = data; + } + + public BizException(ErrorCode errorCode) { + this(errorCode.code(), errorCode.message()); + } + + public BizException(ErrorCode errorCode, String message) { + this(errorCode.code(), message); + } + + public int getCode() { + return code; + } + + public Object getData() { + return data; + } + + public static BizException of(ErrorCode errorCode) { + return new BizException(errorCode); + } + + public static BizException of(ErrorCode errorCode, String message) { + return new BizException(errorCode, message); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/error/ErrorCode.java b/finance-server/src/main/java/com/gas/fin/common/error/ErrorCode.java new file mode 100644 index 0000000..2f20fe7 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/error/ErrorCode.java @@ -0,0 +1,65 @@ +package com.gas.fin.common.error; + +/** + * 业务错误码,与需求文档 §9.2 及前端 KNOWN_MESSAGES 保持一致。 + */ +public enum ErrorCode { + + SUCCESS(0, "success"), + + BAD_REQUEST(400, "请求格式错误"), + UNAUTHORIZED(4010, "登录状态已失效,请重新登录"), + LOGIN_FAILED(4011, "用户名或密码错误"), + ACCOUNT_DISABLED(4012, "账号已停用"), + OLD_PASSWORD_MISMATCH(4013, "原密码不正确"), + PASSWORD_WEAK(4014, "新密码强度不足"), + PASSWORD_REUSED(4015, "新密码不得与最近 3 次密码重复"), + MUST_CHANGE_PASSWORD(4016, "请先修改初始密码"), + ACCOUNT_LOCKED(4021, "账号已锁定,请稍后重试"), + TOTP_FAILED(4022, "动态口令校验失败"), + FORBIDDEN(403, "当前账号无权执行该操作"), + NOT_FOUND(404, "资源不存在"), + + IDEMPOTENT_CONFLICT(4091, "重复提交已被拦截,已返回首次结果"), + CONCURRENT_CONFLICT(4092, "并发操作冲突,请稍后重试"), + STATUS_CONFLICT(4093, "单据状态已变更,请刷新后重试"), + SECOND_APPROVER_REQUIRED(4094, "该笔金额需要第二复核人"), + INVALID_APPROVER(4095, "复核人不符合要求"), + ADMIN_CONSTRAINT(4096, "管理约束冲突"), + PROTECTED_CONFIG(4097, "受保护参数禁止修改"), + DUPLICATE_VOUCHER(4098, "该银行凭证号已被其他订单使用,请核对后重新录入"), + + VALIDATION_FAILED(422, "提交内容不符合规范,请检查后重试"), + DUPLICATE_KEY(4221, "唯一键冲突"), + TOO_MANY_REQUESTS(429, "操作过于频繁,请稍后再试"), + + BIZ_OBJECT_UNAVAILABLE(4001, "业务对象不可用"), + APP_CREDENTIAL_INVALID(4003, "应用凭证无效"), + + INSUFFICIENT_BALANCE(6001, "账户余额不足,无法完成扣费"), + EXCEED_CHARGE_LIMIT(6002, "超出单次扣费上限,已被拒绝"), + INVALID_POINTS(6003, "点数必须为正整数"), + REFUND_EXCEEDED(6004, "退款金额超出可退上限"), + RESERVED_6005(6005, "预留错误码"), + REFUND_BALANCE_INSUFFICIENT(6006, "退款扣回点数超出账户余额"), + + TICKET_INVALID(7001, "凭证无效、已过期或已被使用"), + + INTERNAL_ERROR(500, "服务器内部错误"); + + private final int code; + private final String message; + + ErrorCode(int code, String message) { + this.code = code; + this.message = message; + } + + public int code() { + return code; + } + + public String message() { + return message; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/id/FinIdGenerator.java b/finance-server/src/main/java/com/gas/fin/common/id/FinIdGenerator.java new file mode 100644 index 0000000..e866f72 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/id/FinIdGenerator.java @@ -0,0 +1,62 @@ +package com.gas.fin.common.id; + +import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * 53 位 ID 生成器:前端 JS number 安全整数范围内(<= 2^53-1)。 + * 结构:41 位毫秒时间 + 6 位机器号 + 6 位序列。 + */ +@Component +public class FinIdGenerator implements IdentifierGenerator { + + private static final long EPOCH = LocalDate.of(2026, 1, 1) + .atStartOfDay(ZoneId.of("Asia/Shanghai")) + .toInstant() + .toEpochMilli(); + private static final long SEQUENCE_MASK = 0x3F; + + private final int workerId; + private final AtomicInteger sequence = new AtomicInteger(0); + private volatile long lastTimestamp = -1L; + + public FinIdGenerator(@Value("${fin.worker-id:0}") int workerId) { + this.workerId = workerId & 0x3F; + } + + @Override + public synchronized Number nextId(Object entity) { + long timestamp = System.currentTimeMillis() - EPOCH; + if (timestamp < 0) { + timestamp = 0; + } + if (timestamp == lastTimestamp) { + int next = sequence.incrementAndGet() & (int) SEQUENCE_MASK; + if (next == 0) { + timestamp = waitNextMillis(timestamp); + lastTimestamp = timestamp; + } + } else { + sequence.set(0); + lastTimestamp = timestamp; + } + return (timestamp << 12) | ((long) workerId << 6) | (sequence.get() & SEQUENCE_MASK); + } + + public long nextLongId() { + return nextId(null).longValue(); + } + + private long waitNextMillis(long current) { + long timestamp = current; + while (timestamp <= current) { + timestamp = System.currentTimeMillis() - EPOCH; + } + return timestamp; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/security/AdminAuditor.java b/finance-server/src/main/java/com/gas/fin/common/security/AdminAuditor.java new file mode 100644 index 0000000..010c086 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/security/AdminAuditor.java @@ -0,0 +1,37 @@ +package com.gas.fin.common.security; + +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.audit.service.AuditService; +import com.gas.fin.common.web.RequestUtils; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** + * 管理端操作审计快捷入口:统一取客户端 IP / UA,避免各业务重复拼装。 + */ +@Component +public class AdminAuditor { + + private final AuditService auditService; + private final boolean trustProxy; + + public AdminAuditor(AuditService auditService, @Value("${fin.trust-proxy:true}") boolean trustProxy) { + this.auditService = auditService; + this.trustProxy = trustProxy; + } + + public void success(AdminEntity admin, String action, String actionLabel, String targetType, Long targetId, + Object before, Object after, HttpServletRequest request) { + auditService.record("ADMIN", admin.getId(), admin.getUsername(), action, actionLabel, + targetType, targetId, before, after, + RequestUtils.clientIp(request, trustProxy), RequestUtils.userAgent(request)); + } + + public void failure(AdminEntity admin, String action, String actionLabel, String targetType, Long targetId, + Object before, Object after, HttpServletRequest request) { + auditService.recordFailure("ADMIN", admin.getId(), admin.getUsername(), action, actionLabel, + targetType, targetId, before, after, + RequestUtils.clientIp(request, trustProxy), RequestUtils.userAgent(request)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/security/AdminAuthInterceptor.java b/finance-server/src/main/java/com/gas/fin/common/security/AdminAuthInterceptor.java new file mode 100644 index 0000000..b5d82ca --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/security/AdminAuthInterceptor.java @@ -0,0 +1,94 @@ +package com.gas.fin.common.security; + +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.audit.service.AuditService; +import com.gas.fin.auth.service.SessionService; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.web.RequestUtils; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.stereotype.Component; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.util.UrlPathHelper; + +import java.util.Arrays; +import java.util.Set; + +/** + * 管理端统一认证 + 强制改密 + 权限码校验。 + * 所有 /api/admin/** 接口(登录除外)必须经过本拦截器。 + */ +@Component +public class AdminAuthInterceptor implements HandlerInterceptor { + + private static final Set MUST_CHANGE_ALLOWED = Set.of( + "/api/admin/profile", + "/api/admin/password/change", + "/api/admin/logout" + ); + + private final SessionService sessionService; + private final AuditService auditService; + + public AdminAuthInterceptor(SessionService sessionService, AuditService auditService) { + this.sessionService = sessionService; + this.auditService = auditService; + } + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { + if (!(handler instanceof HandlerMethod handlerMethod)) { + return true; + } + String token = RequestUtils.bearerToken(request); + SessionService.SessionContext context = sessionService.validate(token); + AdminEntity admin = context.admin(); + AuthContext.set(admin); + + try { + String path = UrlPathHelper.defaultInstance.getPathWithinApplication(request); + if (Integer.valueOf(1).equals(admin.getMustChangePassword()) && !MUST_CHANGE_ALLOWED.contains(path)) { + throw new BizException(ErrorCode.MUST_CHANGE_PASSWORD); + } + + RequirePermission permission = findPermission(handlerMethod); + if (permission == null) { + throw new BizException(ErrorCode.FORBIDDEN, "接口未声明权限码"); + } + boolean allowed = permission.anyOf() + ? Arrays.stream(permission.value()) + .anyMatch(item -> PermissionRegistry.has(admin.getRole(), item)) + : Arrays.stream(permission.value()) + .allMatch(item -> PermissionRegistry.has(admin.getRole(), item)); + if (!allowed) { + auditService.recordFailure("ADMIN", admin.getId(), admin.getUsername(), + "PERMISSION_DENIED", "权限拒绝", "API", null, + null, java.util.Map.of("path", path), request.getRemoteAddr(), RequestUtils.userAgent(request)); + throw new BizException(ErrorCode.FORBIDDEN); + } + return true; + } catch (RuntimeException ex) { + AuthContext.clear(); + throw ex; + } + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, + Object handler, Exception ex) { + AuthContext.clear(); + } + + private RequirePermission findPermission(HandlerMethod handlerMethod) { + RequirePermission annotation = AnnotatedElementUtils.findMergedAnnotation( + handlerMethod.getMethod(), RequirePermission.class); + if (annotation != null) { + return annotation; + } + return AnnotatedElementUtils.findMergedAnnotation( + handlerMethod.getBeanType(), RequirePermission.class); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/security/AuthContext.java b/finance-server/src/main/java/com/gas/fin/common/security/AuthContext.java new file mode 100644 index 0000000..281f675 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/security/AuthContext.java @@ -0,0 +1,35 @@ +package com.gas.fin.common.security; + +import com.gas.fin.admin.entity.AdminEntity; + +/** + * 当前请求的登录管理员上下文,由认证拦截器写入并在请求结束时清理。 + */ +public final class AuthContext { + + private static final ThreadLocal HOLDER = new ThreadLocal<>(); + + private AuthContext() { + } + + public static void set(AdminEntity admin) { + HOLDER.set(admin); + } + + public static AdminEntity get() { + return HOLDER.get(); + } + + public static AdminEntity require() { + AdminEntity admin = HOLDER.get(); + if (admin == null) { + throw new com.gas.fin.common.error.BizException( + com.gas.fin.common.error.ErrorCode.UNAUTHORIZED); + } + return admin; + } + + public static void clear() { + HOLDER.remove(); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/security/PermissionRegistry.java b/finance-server/src/main/java/com/gas/fin/common/security/PermissionRegistry.java new file mode 100644 index 0000000..d15a9b9 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/security/PermissionRegistry.java @@ -0,0 +1,52 @@ +package com.gas.fin.common.security; + +import java.util.List; +import java.util.Map; + +/** + * 15 个权限码与角色映射。 + * 与前端 finance-web/src/constants/index.ts 的 PERM 对齐,并保留需求文档的职责分离: + * SUPER_ADMIN 不拥有确认到账 / 发起退款权限。 + */ +public final class PermissionRegistry { + + public static final String VIEW = "fin:view"; + public static final String EXPORT = "fin:export"; + public static final String APP_MANAGE = "fin:app:manage"; + public static final String PRICING_EDIT = "fin:pricing:edit"; + public static final String VIP_MANAGE = "fin:vip:manage"; + public static final String ADMIN_MANAGE = "fin:admin:manage"; + public static final String CONFIG_EDIT = "fin:config:edit"; + public static final String AUDIT_VIEW = "fin:audit:view"; + public static final String WEBHOOK_MANAGE = "fin:webhook:manage"; + public static final String ACCOUNT_ADJUST = "fin:account:adjust"; + public static final String RECHARGE_CONFIRM = "fin:recharge:confirm"; + public static final String REFUND_CREATE = "fin:refund:create"; + public static final String REFUND_REVIEW = "fin:refund:review"; + public static final String ORDER_CANCEL = "fin:order:cancel"; + public static final String RECONCILE_RUN = "fin:reconcile:run"; + + private static final Map> ROLE_PERMISSIONS = Map.of( + "SUPER_ADMIN", List.of( + VIEW, EXPORT, APP_MANAGE, PRICING_EDIT, VIP_MANAGE, ADMIN_MANAGE, + CONFIG_EDIT, AUDIT_VIEW, WEBHOOK_MANAGE, ACCOUNT_ADJUST, + REFUND_REVIEW, ORDER_CANCEL, RECONCILE_RUN + ), + "FINANCE", List.of( + VIEW, EXPORT, RECHARGE_CONFIRM, REFUND_CREATE, REFUND_REVIEW, + ORDER_CANCEL, RECONCILE_RUN + ), + "AUDITOR", List.of(VIEW, EXPORT, AUDIT_VIEW) + ); + + private PermissionRegistry() { + } + + public static List permissionsOf(String role) { + return ROLE_PERMISSIONS.getOrDefault(role, List.of()); + } + + public static boolean has(String role, String permission) { + return permissionsOf(role).contains(permission); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/security/RequirePermission.java b/finance-server/src/main/java/com/gas/fin/common/security/RequirePermission.java new file mode 100644 index 0000000..52baee8 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/security/RequirePermission.java @@ -0,0 +1,21 @@ +package com.gas.fin.common.security; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 接口权限码声明。管理端接口必须声明,服务端二次校验。 + */ +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface RequirePermission { + + String[] value(); + + /** + * true 表示满足任意一个权限码即可访问;默认要求全部满足。 + */ + boolean anyOf() default false; +} diff --git a/finance-server/src/main/java/com/gas/fin/common/security/TotpVerifier.java b/finance-server/src/main/java/com/gas/fin/common/security/TotpVerifier.java new file mode 100644 index 0000000..cf8f6d5 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/security/TotpVerifier.java @@ -0,0 +1,40 @@ +package com.gas.fin.common.security; + +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.common.crypto.CryptoService; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.totp.TotpService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Component; + +/** + * 高危操作动态口令校验:校验失败时写失败审计,再抛出 4022。 + */ +@Component +public class TotpVerifier { + + private final CryptoService cryptoService; + private final TotpService totpService; + private final AdminAuditor adminAuditor; + + public TotpVerifier(CryptoService cryptoService, TotpService totpService, AdminAuditor adminAuditor) { + this.cryptoService = cryptoService; + this.totpService = totpService; + this.adminAuditor = adminAuditor; + } + + public void verify(AdminEntity admin, String code, String action, String actionLabel, + HttpServletRequest request) { + String secret; + try { + secret = cryptoService.decrypt(admin.getTotpSecretEnc()); + } catch (Exception ex) { + secret = null; + } + if (totpService.verify(secret, code, admin.getId()) != TotpService.Result.OK) { + adminAuditor.failure(admin, action, actionLabel, "ADMIN", admin.getId(), null, null, request); + throw new BizException(ErrorCode.TOTP_FAILED); + } + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/totp/TotpService.java b/finance-server/src/main/java/com/gas/fin/common/totp/TotpService.java new file mode 100644 index 0000000..cb50d18 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/totp/TotpService.java @@ -0,0 +1,156 @@ +package com.gas.fin.common.totp; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.time.Duration; +import java.util.Locale; +import java.util.concurrent.TimeUnit; + +/** + * RFC 6238 TOTP:HmacSHA1 / 6 位 / 30 秒步长 / 允许 ±1 步;同一管理员同一验证码 90 秒内只能用一次。 + */ +@Service +public class TotpService { + + private static final Logger log = LoggerFactory.getLogger(TotpService.class); + private static final String BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + private static final SecureRandom RANDOM = new SecureRandom(); + private static final long STEP_SECONDS = 30L; + + private final StringRedisTemplate redisTemplate; + + public TotpService(StringRedisTemplate redisTemplate) { + this.redisTemplate = redisTemplate; + } + + public enum Result { + OK, + FORMAT_INVALID, + FAILED, + REPLAY + } + + public String generateSecret() { + byte[] bytes = new byte[20]; + RANDOM.nextBytes(bytes); + return base32Encode(bytes); + } + + public Result verify(String secretBase32, String code, Long adminId) { + if (code == null || !code.matches("^\\d{6}$")) { + return Result.FORMAT_INVALID; + } + if (secretBase32 == null || secretBase32.isBlank()) { + return Result.FAILED; + } + byte[] key; + try { + key = base32Decode(secretBase32); + } catch (IllegalArgumentException ex) { + return Result.FAILED; + } + + long counter = System.currentTimeMillis() / 1000L / STEP_SECONDS; + boolean matched = false; + for (long offset = -1; offset <= 1; offset++) { + String candidate = generateCode(key, counter + offset); + if (MessageDigest.isEqual(candidate.getBytes(StandardCharsets.UTF_8), code.getBytes(StandardCharsets.UTF_8))) { + matched = true; + break; + } + } + if (!matched) { + return Result.FAILED; + } + + String replayKey = "totp:used:" + adminId + ":" + code; + try { + Boolean firstUse = redisTemplate.opsForValue().setIfAbsent(replayKey, "1", Duration.ofSeconds(90)); + if (!Boolean.TRUE.equals(firstUse)) { + return Result.REPLAY; + } + } catch (Exception ex) { + log.error("TOTP 防重放校验失败 adminId={}", adminId, ex); + return Result.FAILED; + } + return Result.OK; + } + + private String generateCode(byte[] key, long counter) { + try { + byte[] data = ByteBuffer.allocate(8).putLong(counter).array(); + Mac mac = Mac.getInstance("HmacSHA1"); + mac.init(new SecretKeySpec(key, "HmacSHA1")); + byte[] hash = mac.doFinal(data); + int offset = hash[hash.length - 1] & 0x0F; + int binary = ((hash[offset] & 0x7F) << 24) + | ((hash[offset + 1] & 0xFF) << 16) + | ((hash[offset + 2] & 0xFF) << 8) + | (hash[offset + 3] & 0xFF); + int otp = binary % 1_000_000; + return String.format(Locale.ROOT, "%06d", otp); + } catch (Exception ex) { + throw new IllegalStateException("TOTP generate failed", ex); + } + } + + private static String base32Encode(byte[] data) { + StringBuilder builder = new StringBuilder(); + int buffer = 0; + int bits = 0; + for (byte b : data) { + buffer = (buffer << 8) | (b & 0xFF); + bits += 8; + while (bits >= 5) { + builder.append(BASE32_ALPHABET.charAt((buffer >> (bits - 5)) & 0x1F)); + bits -= 5; + } + } + if (bits > 0) { + builder.append(BASE32_ALPHABET.charAt((buffer << (5 - bits)) & 0x1F)); + } + return builder.toString(); + } + + private static byte[] base32Decode(String input) { + String normalized = input.replace("=", "").replace(" ", "").toUpperCase(Locale.ROOT); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int buffer = 0; + int bits = 0; + for (char c : normalized.toCharArray()) { + int value = BASE32_ALPHABET.indexOf(c); + if (value < 0) { + throw new IllegalArgumentException("invalid base32"); + } + buffer = (buffer << 5) | value; + bits += 5; + if (bits >= 8) { + out.write((buffer >> (bits - 8)) & 0xFF); + bits -= 8; + } + } + return out.toByteArray(); + } + + public static void main(String[] args) { + // 便于本地生成测试 secret 与当前验证码 + TotpService service = new TotpService(null); + String secret = args.length > 0 ? args[0] : service.generateSecret(); + System.out.println("secret=" + secret); + if (args.length > 1) { + byte[] key = base32Decode(secret); + long counter = System.currentTimeMillis() / 1000L / STEP_SECONDS; + System.out.println("code=" + service.generateCode(key, counter)); + } + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/util/HashUtils.java b/finance-server/src/main/java/com/gas/fin/common/util/HashUtils.java new file mode 100644 index 0000000..a944cc0 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/util/HashUtils.java @@ -0,0 +1,65 @@ +package com.gas.fin.common.util; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; + +public final class HashUtils { + + private static final SecureRandom RANDOM = new SecureRandom(); + private static final char[] BASE64_URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".toCharArray(); + + private HashUtils() { + } + + public static String sha256Hex(String value) { + return sha256Hex(value == null ? new byte[0] : value.getBytes(StandardCharsets.UTF_8)); + } + + public static String sha256Hex(byte[] value) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] bytes = digest.digest(value); + StringBuilder builder = new StringBuilder(bytes.length * 2); + for (byte b : bytes) { + builder.append(Character.forDigit((b >> 4) & 0xF, 16)); + builder.append(Character.forDigit(b & 0xF, 16)); + } + return builder.toString(); + } catch (Exception ex) { + throw new IllegalStateException("SHA-256 unavailable", ex); + } + } + + public static byte[] randomBytes(int length) { + byte[] bytes = new byte[length]; + RANDOM.nextBytes(bytes); + return bytes; + } + + public static String randomBase64Url(int length) { + byte[] bytes = randomBytes(length); + StringBuilder builder = new StringBuilder((length * 4 + 2) / 3); + int buffer = 0; + int bits = 0; + for (byte b : bytes) { + buffer = (buffer << 8) | (b & 0xFF); + bits += 8; + while (bits >= 6) { + builder.append(BASE64_URL[(buffer >> (bits - 6)) & 0x3F]); + bits -= 6; + } + } + if (bits > 0) { + builder.append(BASE64_URL[(buffer << (6 - bits)) & 0x3F]); + } + return builder.toString(); + } + + public static boolean constantTimeEquals(String left, String right) { + if (left == null || right == null) { + return false; + } + return MessageDigest.isEqual(left.getBytes(StandardCharsets.UTF_8), right.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/util/PasswordUtils.java b/finance-server/src/main/java/com/gas/fin/common/util/PasswordUtils.java new file mode 100644 index 0000000..6e1d631 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/util/PasswordUtils.java @@ -0,0 +1,47 @@ +package com.gas.fin.common.util; + +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public final class PasswordUtils { + + private static final SecureRandom RANDOM = new SecureRandom(); + private static final String LOWER = "abcdefghijkmnpqrstuvwxyz"; + private static final String UPPER = "ABCDEFGHJKLMNPQRSTUVWXYZ"; + private static final String DIGITS = "23456789"; + private static final String SYMBOLS = "!@#$%^&*()-_=+"; + private static final String ALL = LOWER + UPPER + DIGITS + SYMBOLS; + + private PasswordUtils() { + } + + public static boolean isStrong(String password) { + if (password == null) { + return false; + } + return password.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^A-Za-z0-9])\\S{12,64}$") + && password.matches("^[\\x21-\\x7e]+$"); + } + + public static String randomPassword(int length) { + int size = Math.max(length, 12); + List chars = new ArrayList<>(size); + chars.add(randomOf(LOWER)); + chars.add(randomOf(UPPER)); + chars.add(randomOf(DIGITS)); + chars.add(randomOf(SYMBOLS)); + for (int i = 4; i < size; i++) { + chars.add(randomOf(ALL)); + } + Collections.shuffle(chars, RANDOM); + StringBuilder builder = new StringBuilder(size); + chars.forEach(builder::append); + return builder.toString(); + } + + private static char randomOf(String source) { + return source.charAt(RANDOM.nextInt(source.length())); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/web/GlobalExceptionHandler.java b/finance-server/src/main/java/com/gas/fin/common/web/GlobalExceptionHandler.java new file mode 100644 index 0000000..6d19de1 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/web/GlobalExceptionHandler.java @@ -0,0 +1,85 @@ +package com.gas.fin.common.web; + +import com.gas.fin.common.api.R; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.ConstraintViolationException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.validation.BindException; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.NoHandlerFoundException; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 全局异常出口:禁止把堆栈、SQL、内部地址返回给客户端。 + */ +@RestControllerAdvice +public class GlobalExceptionHandler { + + private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + @ExceptionHandler(BizException.class) + public R handleBiz(BizException ex) { + return R.fail(ex.getCode(), ex.getMessage(), ex.getData()); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public R handleMethodArgumentNotValid(MethodArgumentNotValidException ex) { + List> errors = new ArrayList<>(); + for (FieldError error : ex.getBindingResult().getFieldErrors()) { + errors.add(fieldError(error.getField(), error.getDefaultMessage())); + } + return R.fail(ErrorCode.VALIDATION_FAILED.code(), ErrorCode.VALIDATION_FAILED.message(), errors); + } + + @ExceptionHandler(BindException.class) + public R handleBind(BindException ex) { + List> errors = new ArrayList<>(); + for (FieldError error : ex.getBindingResult().getFieldErrors()) { + errors.add(fieldError(error.getField(), error.getDefaultMessage())); + } + return R.fail(ErrorCode.VALIDATION_FAILED.code(), ErrorCode.VALIDATION_FAILED.message(), errors); + } + + @ExceptionHandler(ConstraintViolationException.class) + public R handleConstraintViolation(ConstraintViolationException ex) { + List> errors = new ArrayList<>(); + for (ConstraintViolation violation : ex.getConstraintViolations()) { + errors.add(fieldError(String.valueOf(violation.getPropertyPath()), violation.getMessage())); + } + return R.fail(ErrorCode.VALIDATION_FAILED.code(), ErrorCode.VALIDATION_FAILED.message(), errors); + } + + @ExceptionHandler(HttpMessageNotReadableException.class) + public R handleUnreadable(HttpMessageNotReadableException ex) { + return R.fail(ErrorCode.BAD_REQUEST.code(), ErrorCode.BAD_REQUEST.message()); + } + + @ExceptionHandler(NoHandlerFoundException.class) + public R handleNoHandler(NoHandlerFoundException ex) { + return R.fail(ErrorCode.NOT_FOUND.code(), ErrorCode.NOT_FOUND.message()); + } + + @ExceptionHandler(Exception.class) + public R handleUnexpected(Exception ex) { + log.error("unexpected error traceId={}", TraceId.current(), ex); + return R.fail(ErrorCode.INTERNAL_ERROR.code(), ErrorCode.INTERNAL_ERROR.message()); + } + + private Map fieldError(String field, String message) { + Map item = new LinkedHashMap<>(); + item.put("field", field); + item.put("message", message == null ? "参数不合法" : message); + return item; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/web/QueryUtils.java b/finance-server/src/main/java/com/gas/fin/common/web/QueryUtils.java new file mode 100644 index 0000000..c3e85da --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/web/QueryUtils.java @@ -0,0 +1,60 @@ +package com.gas.fin.common.web; + +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * 列表类接口的公共查询参数处理:分页校验与日期区间解析。 + */ +public final class QueryUtils { + + private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + private QueryUtils() { + } + + public static void checkPage(long page, long pageSize) { + if (page < 1 || pageSize < 1 || pageSize > 100) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "分页参数不合法"); + } + } + + public static LocalDateTime parseFrom(String value) { + if (value == null || value.isBlank()) { + return null; + } + String text = value.trim(); + try { + if (text.length() == 10) { + return LocalDate.parse(text).atStartOfDay(); + } + return LocalDateTime.parse(text, DATE_TIME); + } catch (DateTimeParseException ex) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "时间格式需为 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss"); + } + } + + public static LocalDateTime parseTo(String value) { + if (value == null || value.isBlank()) { + return null; + } + String text = value.trim(); + try { + if (text.length() == 10) { + return LocalDate.parse(text).atTime(23, 59, 59); + } + return LocalDateTime.parse(text, DATE_TIME); + } catch (DateTimeParseException ex) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "时间格式需为 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss"); + } + } + + public static String text(String value) { + return value == null ? "" : value.trim(); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/web/RequestUtils.java b/finance-server/src/main/java/com/gas/fin/common/web/RequestUtils.java new file mode 100644 index 0000000..04dd94a --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/web/RequestUtils.java @@ -0,0 +1,49 @@ +package com.gas.fin.common.web; + +import jakarta.servlet.http.HttpServletRequest; + +public final class RequestUtils { + + private RequestUtils() { + } + + public static String clientIp(HttpServletRequest request, boolean trustProxy) { + String ip = null; + if (trustProxy) { + String forwarded = request.getHeader("X-Forwarded-For"); + if (forwarded != null && !forwarded.isBlank()) { + String[] parts = forwarded.split(","); + ip = parts[parts.length - 1].trim(); + } + } + if (ip == null || ip.isBlank()) { + ip = request.getRemoteAddr(); + } + if (ip == null || ip.isBlank()) { + return "unknown"; + } + ip = ip.replaceAll("[^0-9a-fA-F:.]", ""); + return ip.length() > 45 ? ip.substring(0, 45) : ip; + } + + public static String userAgent(HttpServletRequest request) { + String ua = request.getHeader("User-Agent"); + if (ua == null) { + return ""; + } + return ua.length() > 255 ? ua.substring(0, 255) : ua; + } + + public static String bearerToken(HttpServletRequest request) { + String authorization = request.getHeader("Authorization"); + if (authorization == null) { + return null; + } + String prefix = "Bearer "; + if (authorization.regionMatches(true, 0, prefix, 0, prefix.length())) { + String token = authorization.substring(prefix.length()).trim(); + return token.isEmpty() ? null : token; + } + return null; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/web/TraceId.java b/finance-server/src/main/java/com/gas/fin/common/web/TraceId.java new file mode 100644 index 0000000..adbd853 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/web/TraceId.java @@ -0,0 +1,29 @@ +package com.gas.fin.common.web; + +import org.slf4j.MDC; + +import java.util.UUID; + +/** + * TraceId 上下文:响应体与响应头使用同一个值,日志通过 MDC 串联。 + */ +public final class TraceId { + + public static final String MDC_KEY = "traceId"; + public static final String HEADER = "X-Trace-Id"; + + private TraceId() { + } + + public static String current() { + String value = MDC.get(MDC_KEY); + if (value != null && !value.isBlank()) { + return value; + } + return newTraceId(); + } + + public static String newTraceId() { + return UUID.randomUUID().toString().replace("-", "").substring(0, 16); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/common/web/TraceIdFilter.java b/finance-server/src/main/java/com/gas/fin/common/web/TraceIdFilter.java new file mode 100644 index 0000000..118def3 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/common/web/TraceIdFilter.java @@ -0,0 +1,41 @@ +package com.gas.fin.common.web; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.slf4j.MDC; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.regex.Pattern; + +/** + * 为每个请求生成 TraceId,写入 MDC 与响应头。上游传入的 X-Request-Id 仅在格式合法时复用。 + */ +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +public class TraceIdFilter extends OncePerRequestFilter { + + private static final Pattern SAFE_TRACE_ID = Pattern.compile("^[A-Za-z0-9-]{8,64}$"); + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { + String incoming = request.getHeader("X-Request-Id"); + String traceId = incoming != null && SAFE_TRACE_ID.matcher(incoming).matches() + ? incoming + : TraceId.newTraceId(); + + MDC.put(TraceId.MDC_KEY, traceId); + response.setHeader(TraceId.HEADER, traceId); + try { + filterChain.doFilter(request, response); + } finally { + MDC.remove(TraceId.MDC_KEY); + } + } +} diff --git a/finance-server/src/main/java/com/gas/fin/config/AuthWebConfig.java b/finance-server/src/main/java/com/gas/fin/config/AuthWebConfig.java new file mode 100644 index 0000000..a2332ee --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/config/AuthWebConfig.java @@ -0,0 +1,23 @@ +package com.gas.fin.config; + +import com.gas.fin.common.security.AdminAuthInterceptor; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class AuthWebConfig implements WebMvcConfigurer { + + private final AdminAuthInterceptor adminAuthInterceptor; + + public AuthWebConfig(AdminAuthInterceptor adminAuthInterceptor) { + this.adminAuthInterceptor = adminAuthInterceptor; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(adminAuthInterceptor) + .addPathPatterns("/api/admin/**") + .excludePathPatterns("/api/admin/login"); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/config/JacksonConfig.java b/finance-server/src/main/java/com/gas/fin/config/JacksonConfig.java new file mode 100644 index 0000000..44f643d --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/config/JacksonConfig.java @@ -0,0 +1,32 @@ +package com.gas.fin.config; + +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; +import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; +import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; +import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; +import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +@Configuration +public class JacksonConfig { + + public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + @Bean + public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() { + return builder -> { + builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DATE_TIME_FORMATTER)); + builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DATE_TIME_FORMATTER)); + builder.serializerByType(LocalDate.class, new LocalDateSerializer(DATE_FORMATTER)); + builder.deserializerByType(LocalDate.class, new LocalDateDeserializer(DATE_FORMATTER)); + builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + }; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/config/MybatisPlusConfig.java b/finance-server/src/main/java/com/gas/fin/config/MybatisPlusConfig.java new file mode 100644 index 0000000..1f7da10 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/config/MybatisPlusConfig.java @@ -0,0 +1,22 @@ +package com.gas.fin.config; + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class MybatisPlusConfig { + + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); + PaginationInnerInterceptor pagination = new PaginationInnerInterceptor(DbType.MYSQL); + pagination.setMaxLimit(100L); + interceptor.addInnerInterceptor(pagination); + interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); + return interceptor; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/config/SecurityBeans.java b/finance-server/src/main/java/com/gas/fin/config/SecurityBeans.java new file mode 100644 index 0000000..ada1f2d --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/config/SecurityBeans.java @@ -0,0 +1,15 @@ +package com.gas.fin.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class SecurityBeans { + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(12); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/config/WebConfig.java b/finance-server/src/main/java/com/gas/fin/config/WebConfig.java new file mode 100644 index 0000000..108b1d2 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/config/WebConfig.java @@ -0,0 +1,33 @@ +package com.gas.fin.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.Arrays; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Value("${fin.cors.allowed-origins:}") + private String allowedOrigins; + + @Override + public void addCorsMappings(CorsRegistry registry) { + String[] origins = Arrays.stream(allowedOrigins.split(",")) + .map(String::trim) + .filter(value -> !value.isEmpty()) + .toArray(String[]::new); + if (origins.length == 0) { + return; + } + registry.addMapping("/api/**") + .allowedOrigins(origins) + .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") + .allowedHeaders("*") + .exposedHeaders("X-Trace-Id") + .allowCredentials(false) + .maxAge(3600); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/dashboard/controller/DashboardController.java b/finance-server/src/main/java/com/gas/fin/dashboard/controller/DashboardController.java new file mode 100644 index 0000000..c2bc8b9 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/dashboard/controller/DashboardController.java @@ -0,0 +1,43 @@ +package com.gas.fin.dashboard.controller; + +import com.gas.fin.common.api.R; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.security.RequirePermission; +import com.gas.fin.dashboard.dto.AppDistributionResponse; +import com.gas.fin.dashboard.dto.DashboardSummaryResponse; +import com.gas.fin.dashboard.dto.TrendPointResponse; +import com.gas.fin.dashboard.service.DashboardService; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api/admin/dashboard") +public class DashboardController { + + private final DashboardService dashboardService; + + public DashboardController(DashboardService dashboardService) { + this.dashboardService = dashboardService; + } + + @GetMapping("/summary") + @RequirePermission(PermissionRegistry.VIEW) + public R summary() { + return R.ok(dashboardService.summary()); + } + + @GetMapping("/trend") + @RequirePermission(PermissionRegistry.VIEW) + public R> trend() { + return R.ok(dashboardService.trend()); + } + + @GetMapping("/distribution") + @RequirePermission(PermissionRegistry.VIEW) + public R> distribution() { + return R.ok(dashboardService.distribution()); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/dashboard/dto/AppDistributionResponse.java b/finance-server/src/main/java/com/gas/fin/dashboard/dto/AppDistributionResponse.java new file mode 100644 index 0000000..78577e4 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/dashboard/dto/AppDistributionResponse.java @@ -0,0 +1,4 @@ +package com.gas.fin.dashboard.dto; + +public record AppDistributionResponse(String appCode, String appName, long amountCent, long orderCount) { +} diff --git a/finance-server/src/main/java/com/gas/fin/dashboard/dto/DashboardSummaryResponse.java b/finance-server/src/main/java/com/gas/fin/dashboard/dto/DashboardSummaryResponse.java new file mode 100644 index 0000000..e3cce57 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/dashboard/dto/DashboardSummaryResponse.java @@ -0,0 +1,7 @@ +package com.gas.fin.dashboard.dto; + +public record DashboardSummaryResponse(long todayAmountCent, long todayOrderCount, long pendingOrderCount, + long pendingAmountCent, long todayConsumedPoints, long pendingRefundCount, + long totalBalancePoints, long deadWebhookCount, long diffReportCount, + long dualControlThresholdCent) { +} diff --git a/finance-server/src/main/java/com/gas/fin/dashboard/dto/TrendPointResponse.java b/finance-server/src/main/java/com/gas/fin/dashboard/dto/TrendPointResponse.java new file mode 100644 index 0000000..0a3470a --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/dashboard/dto/TrendPointResponse.java @@ -0,0 +1,4 @@ +package com.gas.fin.dashboard.dto; + +public record TrendPointResponse(String date, long amountCent, long points, long orderCount) { +} diff --git a/finance-server/src/main/java/com/gas/fin/dashboard/service/DashboardService.java b/finance-server/src/main/java/com/gas/fin/dashboard/service/DashboardService.java new file mode 100644 index 0000000..b6514cc --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/dashboard/service/DashboardService.java @@ -0,0 +1,152 @@ +package com.gas.fin.dashboard.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.gas.fin.account.entity.AccountEntity; +import com.gas.fin.account.mapper.AccountMapper; +import com.gas.fin.app.entity.AppEntity; +import com.gas.fin.app.mapper.AppMapper; +import com.gas.fin.dashboard.dto.AppDistributionResponse; +import com.gas.fin.dashboard.dto.DashboardSummaryResponse; +import com.gas.fin.dashboard.dto.TrendPointResponse; +import com.gas.fin.order.entity.CashLedgerEntity; +import com.gas.fin.order.entity.OrderEntity; +import com.gas.fin.order.mapper.CashLedgerMapper; +import com.gas.fin.order.mapper.OrderMapper; +import com.gas.fin.reconcile.entity.ReconcileReportEntity; +import com.gas.fin.reconcile.mapper.ReconcileReportMapper; +import com.gas.fin.refund.entity.RefundEntity; +import com.gas.fin.refund.mapper.RefundMapper; +import com.gas.fin.setting.service.ConfigService; +import com.gas.fin.transaction.entity.TransactionEntity; +import com.gas.fin.transaction.mapper.TransactionMapper; +import com.gas.fin.webhook.entity.WebhookDeliveryEntity; +import com.gas.fin.webhook.mapper.WebhookDeliveryMapper; +import org.springframework.stereotype.Service; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 首页看板:实时聚合口径见需求文档 §5.2。 + */ +@Service +public class DashboardService { + + private final OrderMapper orderMapper; + private final CashLedgerMapper cashLedgerMapper; + private final TransactionMapper transactionMapper; + private final AccountMapper accountMapper; + private final RefundMapper refundMapper; + private final WebhookDeliveryMapper webhookMapper; + private final ReconcileReportMapper reportMapper; + private final AppMapper appMapper; + private final ConfigService configService; + + public DashboardService(OrderMapper orderMapper, CashLedgerMapper cashLedgerMapper, + TransactionMapper transactionMapper, AccountMapper accountMapper, + RefundMapper refundMapper, WebhookDeliveryMapper webhookMapper, + ReconcileReportMapper reportMapper, AppMapper appMapper, + ConfigService configService) { + this.orderMapper = orderMapper; + this.cashLedgerMapper = cashLedgerMapper; + this.transactionMapper = transactionMapper; + this.accountMapper = accountMapper; + this.refundMapper = refundMapper; + this.webhookMapper = webhookMapper; + this.reportMapper = reportMapper; + this.appMapper = appMapper; + this.configService = configService; + } + + public DashboardSummaryResponse summary() { + LocalDateTime dayStart = LocalDate.now().atStartOfDay(); + LocalDateTime dayEnd = dayStart.plusDays(1); + LocalDateTime now = LocalDateTime.now().withNano(0); + + long todayAmountCent = cashLedgerMapper.selectList(new LambdaQueryWrapper() + .eq(CashLedgerEntity::getDirection, "IN") + .ge(CashLedgerEntity::getReceivedAt, dayStart) + .lt(CashLedgerEntity::getReceivedAt, dayEnd)) + .stream().mapToLong(CashLedgerEntity::getAmountCent).sum(); + List paidToday = orderMapper.selectList(new LambdaQueryWrapper() + .isNotNull(OrderEntity::getPaidAt) + .ge(OrderEntity::getPaidAt, dayStart) + .lt(OrderEntity::getPaidAt, dayEnd)); + List pending = orderMapper.selectList(new LambdaQueryWrapper() + .eq(OrderEntity::getStatus, "PENDING") + .gt(OrderEntity::getExpiresAt, now)); + long todayConsumedPoints = transactionMapper.selectList(new LambdaQueryWrapper() + .eq(TransactionEntity::getType, "CONSUME") + .ge(TransactionEntity::getCreateTime, dayStart) + .lt(TransactionEntity::getCreateTime, dayEnd)) + .stream().mapToLong(TransactionEntity::getAmount).sum(); + long totalBalance = accountMapper.selectList(null).stream() + .mapToLong(item -> item.getBalance() == null ? 0 : item.getBalance()).sum(); + Long pendingRefunds = refundMapper.selectCount(new LambdaQueryWrapper() + .eq(RefundEntity::getStatus, "PENDING")); + Long deadWebhooks = webhookMapper.selectCount(new LambdaQueryWrapper() + .eq(WebhookDeliveryEntity::getStatus, "DEAD")); + Long diffReports = reportMapper.selectCount(new LambdaQueryWrapper() + .eq(ReconcileReportEntity::getStatus, "DIFF")); + + return new DashboardSummaryResponse(todayAmountCent, paidToday.size(), pending.size(), + pending.stream().mapToLong(OrderEntity::getAmountCent).sum(), todayConsumedPoints, + pendingRefunds == null ? 0 : pendingRefunds, totalBalance, + deadWebhooks == null ? 0 : deadWebhooks, diffReports == null ? 0 : diffReports, + configService.getNumber("review.threshold_cent", 500000)); + } + + public List trend() { + LocalDate today = LocalDate.now(); + LocalDate start = today.minusDays(13); + List cash = cashLedgerMapper.selectList(new LambdaQueryWrapper() + .eq(CashLedgerEntity::getDirection, "IN") + .ge(CashLedgerEntity::getReceivedAt, start.atStartOfDay())); + List consumed = transactionMapper.selectList(new LambdaQueryWrapper() + .eq(TransactionEntity::getType, "CONSUME") + .ge(TransactionEntity::getCreateTime, start.atStartOfDay())); + List orders = orderMapper.selectList(new LambdaQueryWrapper() + .ge(OrderEntity::getCreateTime, start.atStartOfDay())); + + Map amountMap = new HashMap<>(); + cash.forEach(item -> amountMap.merge(item.getReceivedAt().toLocalDate(), item.getAmountCent(), Long::sum)); + Map pointsMap = new HashMap<>(); + consumed.forEach(item -> pointsMap.merge(item.getCreateTime().toLocalDate(), item.getAmount(), Long::sum)); + Map orderMap = new HashMap<>(); + orders.forEach(item -> orderMap.merge(item.getCreateTime().toLocalDate(), 1L, Long::sum)); + + List points = new ArrayList<>(); + for (int i = 0; i < 14; i++) { + LocalDate date = start.plusDays(i); + points.add(new TrendPointResponse(String.format("%02d-%02d", date.getMonthValue(), date.getDayOfMonth()), + amountMap.getOrDefault(date, 0L), pointsMap.getOrDefault(date, 0L), + orderMap.getOrDefault(date, 0L))); + } + return points; + } + + public List distribution() { + LocalDateTime monthAgo = LocalDate.now().minusDays(30).atStartOfDay(); + Map counts = new HashMap<>(); + Map amounts = new HashMap<>(); + orderMapper.selectList(new LambdaQueryWrapper() + .isNotNull(OrderEntity::getPaidAt) + .ge(OrderEntity::getPaidAt, monthAgo)) + .forEach(item -> { + counts.merge(item.getAppCode(), 1L, Long::sum); + amounts.merge(item.getAppCode(), item.getAmountCent(), Long::sum); + }); + List result = new ArrayList<>(); + for (AppEntity app : appMapper.selectList(new LambdaQueryWrapper() + .orderByAsc(AppEntity::getCreateTime))) { + result.add(new AppDistributionResponse(app.getAppCode(), app.getAppName(), + amounts.getOrDefault(app.getAppCode(), 0L), + counts.getOrDefault(app.getAppCode(), 0L))); + } + return result; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/health/HealthController.java b/finance-server/src/main/java/com/gas/fin/health/HealthController.java new file mode 100644 index 0000000..09e50b9 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/health/HealthController.java @@ -0,0 +1,75 @@ +package com.gas.fin.health; + +import com.gas.fin.common.api.R; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.sql.Connection; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * 探活接口:只返回组件状态,不返回连接串、主机名与构建信息。 + */ +@RestController +public class HealthController { + + private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + private final JdbcTemplate jdbcTemplate; + private final StringRedisTemplate redisTemplate; + + @Value("${fin.version:unknown}") + private String version; + + public HealthController(JdbcTemplate jdbcTemplate, StringRedisTemplate redisTemplate) { + this.jdbcTemplate = jdbcTemplate; + this.redisTemplate = redisTemplate; + } + + @GetMapping("/api/health") + public ResponseEntity>> health() { + boolean dbUp = checkDb(); + boolean redisUp = checkRedis(); + boolean up = dbUp && redisUp; + + Map data = new LinkedHashMap<>(); + data.put("status", up ? "UP" : "DOWN"); + data.put("db", dbUp ? "UP" : "DOWN"); + data.put("redis", redisUp ? "UP" : "DOWN"); + data.put("version", version); + data.put("time", LocalDateTime.now().format(TIME_FORMAT)); + + if (up) { + return ResponseEntity.ok(R.ok(data)); + } + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) + .body(R.fail(503, "service unavailable", data)); + } + + private boolean checkDb() { + try (Connection connection = jdbcTemplate.getDataSource().getConnection()) { + return connection.isValid(1); + } catch (Exception ex) { + return false; + } + } + + private boolean checkRedis() { + try { + String pong = redisTemplate.execute((RedisCallback) RedisConnection::ping); + return "PONG".equalsIgnoreCase(pong); + } catch (Exception ex) { + return false; + } + } +} diff --git a/finance-server/src/main/java/com/gas/fin/order/controller/ApproverController.java b/finance-server/src/main/java/com/gas/fin/order/controller/ApproverController.java new file mode 100644 index 0000000..7b66d86 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/order/controller/ApproverController.java @@ -0,0 +1,31 @@ +package com.gas.fin.order.controller; + +import com.gas.fin.common.api.R; +import com.gas.fin.common.security.AuthContext; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.security.RequirePermission; +import com.gas.fin.order.dto.ApproverResponse; +import com.gas.fin.order.service.OrderService; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api/admin/approvers") +public class ApproverController { + + private final OrderService orderService; + + public ApproverController(OrderService orderService) { + this.orderService = orderService; + } + + @GetMapping + @RequirePermission(value = {PermissionRegistry.RECHARGE_CONFIRM, PermissionRegistry.REFUND_REVIEW, + PermissionRegistry.ACCOUNT_ADJUST}, anyOf = true) + public R> list() { + return R.ok(orderService.approvers(AuthContext.require())); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/order/controller/OrderController.java b/finance-server/src/main/java/com/gas/fin/order/controller/OrderController.java new file mode 100644 index 0000000..5f5e89a --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/order/controller/OrderController.java @@ -0,0 +1,83 @@ +package com.gas.fin.order.controller; + +import com.gas.fin.common.api.PageResult; +import com.gas.fin.common.api.R; +import com.gas.fin.common.security.AuthContext; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.security.RequirePermission; +import com.gas.fin.order.dto.OrderCancelRequest; +import com.gas.fin.order.dto.OrderConfirmRequest; +import com.gas.fin.order.dto.OrderDetailResponse; +import com.gas.fin.order.dto.OrderInfoResponse; +import com.gas.fin.order.service.OrderService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api/admin/orders") +public class OrderController { + + private final OrderService orderService; + + public OrderController(OrderService orderService) { + this.orderService = orderService; + } + + @GetMapping + @RequirePermission(PermissionRegistry.VIEW) + public R> list( + @RequestParam(defaultValue = "1") long page, + @RequestParam(defaultValue = "20") long pageSize, + @RequestParam(required = false) String appCode, + @RequestParam(required = false) String status, + @RequestParam(required = false) String orderType, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) String from, + @RequestParam(required = false) String to) { + return R.ok(orderService.page(page, pageSize, appCode, status, orderType, keyword, from, to)); + } + + @GetMapping("/export") + @RequirePermission(PermissionRegistry.EXPORT) + public R> export( + @RequestParam(required = false) String appCode, + @RequestParam(required = false) String status, + @RequestParam(required = false) String orderType, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) String from, + @RequestParam(required = false) String to, + HttpServletRequest httpRequest) { + return R.ok(orderService.export(appCode, status, orderType, keyword, from, to, + AuthContext.require(), httpRequest)); + } + + @GetMapping("/{id}") + @RequirePermission(PermissionRegistry.VIEW) + public R detail(@PathVariable Long id) { + return R.ok(orderService.detail(id)); + } + + @PostMapping("/{id}/confirm") + @RequirePermission(PermissionRegistry.RECHARGE_CONFIRM) + public R confirm(@PathVariable Long id, + @RequestBody OrderConfirmRequest request, + HttpServletRequest httpRequest) { + return R.ok(orderService.confirm(id, request, AuthContext.require(), httpRequest)); + } + + @PostMapping("/{id}/cancel") + @RequirePermission(PermissionRegistry.ORDER_CANCEL) + public R cancel(@PathVariable Long id, + @RequestBody OrderCancelRequest request, + HttpServletRequest httpRequest) { + return R.ok(orderService.cancel(id, request, AuthContext.require(), httpRequest)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/order/dto/ApproverResponse.java b/finance-server/src/main/java/com/gas/fin/order/dto/ApproverResponse.java new file mode 100644 index 0000000..da67225 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/order/dto/ApproverResponse.java @@ -0,0 +1,4 @@ +package com.gas.fin.order.dto; + +public record ApproverResponse(Long id, String username, String role) { +} diff --git a/finance-server/src/main/java/com/gas/fin/order/dto/OrderCancelRequest.java b/finance-server/src/main/java/com/gas/fin/order/dto/OrderCancelRequest.java new file mode 100644 index 0000000..9c6ff7e --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/order/dto/OrderCancelRequest.java @@ -0,0 +1,4 @@ +package com.gas.fin.order.dto; + +public record OrderCancelRequest(String reason, String totp) { +} diff --git a/finance-server/src/main/java/com/gas/fin/order/dto/OrderConfirmRequest.java b/finance-server/src/main/java/com/gas/fin/order/dto/OrderConfirmRequest.java new file mode 100644 index 0000000..958c2a3 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/order/dto/OrderConfirmRequest.java @@ -0,0 +1,4 @@ +package com.gas.fin.order.dto; + +public record OrderConfirmRequest(String voucherNo, String receiveAt, Long secondApproverId, String totp) { +} diff --git a/finance-server/src/main/java/com/gas/fin/order/dto/OrderDetailResponse.java b/finance-server/src/main/java/com/gas/fin/order/dto/OrderDetailResponse.java new file mode 100644 index 0000000..034b2e5 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/order/dto/OrderDetailResponse.java @@ -0,0 +1,14 @@ +package com.gas.fin.order.dto; + +import com.gas.fin.refund.dto.RefundInfoResponse; + +import java.time.LocalDateTime; +import java.util.List; + +public record OrderDetailResponse(OrderInfoResponse order, List refunds, + List cashFlows) { + + public record CashFlow(Long id, String direction, Long amountCent, LocalDateTime receivedAt, + String voucherNo, String remark) { + } +} diff --git a/finance-server/src/main/java/com/gas/fin/order/dto/OrderInfoResponse.java b/finance-server/src/main/java/com/gas/fin/order/dto/OrderInfoResponse.java new file mode 100644 index 0000000..e64efb4 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/order/dto/OrderInfoResponse.java @@ -0,0 +1,65 @@ +package com.gas.fin.order.dto; + +import com.gas.fin.order.entity.OrderEntity; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class OrderInfoResponse { + + private Long id; + private String outTradeNo; + private String appCode; + private String appName; + private String businessUserId; + private String usernameSnapshot; + private String orderType; + private String payMethod; + private Long amountCent; + private Long pointsGained; + private String vipPlanCode; + private String status; + private LocalDateTime expiresAt; + private LocalDateTime paidAt; + private Long confirmedByAdminId; + private String confirmedByAdminName; + private Long secondApproverId; + private String secondApproverName; + private String remark; + private LocalDateTime createTime; + private Long refundedAmountCent; + private Long cashInCent; + private Long cashOutCent; + private boolean needDualControl; + + public static OrderInfoResponse from(OrderEntity entity, String appName, long cashInCent, + long cashOutCent, boolean needDualControl) { + OrderInfoResponse response = new OrderInfoResponse(); + response.setId(entity.getId()); + response.setOutTradeNo(entity.getOutTradeNo()); + response.setAppCode(entity.getAppCode()); + response.setAppName(appName == null ? entity.getAppCode() : appName); + response.setBusinessUserId(entity.getBusinessUserId()); + response.setUsernameSnapshot(entity.getUsernameSnapshot()); + response.setOrderType(entity.getOrderType()); + response.setPayMethod(entity.getPayMethod()); + response.setAmountCent(entity.getAmountCent()); + response.setPointsGained(entity.getPointsGained()); + response.setVipPlanCode(entity.getVipPlanCode()); + response.setStatus(entity.getStatus()); + response.setExpiresAt(entity.getExpiresAt()); + response.setPaidAt(entity.getPaidAt()); + response.setConfirmedByAdminId(entity.getConfirmedByAdminId()); + response.setConfirmedByAdminName(entity.getConfirmedByAdminName()); + response.setSecondApproverId(entity.getSecondApproverId()); + response.setSecondApproverName(entity.getSecondApproverName()); + response.setRemark(entity.getRemark() == null ? "" : entity.getRemark()); + response.setCreateTime(entity.getCreateTime()); + response.setRefundedAmountCent(entity.getRefundedAmountCent() == null ? 0L : entity.getRefundedAmountCent()); + response.setCashInCent(cashInCent); + response.setCashOutCent(cashOutCent); + response.setNeedDualControl(needDualControl); + return response; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/order/entity/CashLedgerEntity.java b/finance-server/src/main/java/com/gas/fin/order/entity/CashLedgerEntity.java new file mode 100644 index 0000000..0daf4bc --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/order/entity/CashLedgerEntity.java @@ -0,0 +1,28 @@ +package com.gas.fin.order.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_cash_ledger") +public class CashLedgerEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String appCode; + private Long orderId; + private Long refundId; + private String direction; + private Long amountCent; + private LocalDateTime receivedAt; + private String voucherNo; + private Long operatorAdminId; + private String operatorAdminName; + private String remark; + private LocalDateTime createTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/order/entity/OrderEntity.java b/finance-server/src/main/java/com/gas/fin/order/entity/OrderEntity.java new file mode 100644 index 0000000..871cf64 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/order/entity/OrderEntity.java @@ -0,0 +1,39 @@ +package com.gas.fin.order.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_order") +public class OrderEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String outTradeNo; + private String appCode; + private String businessUserId; + private String usernameSnapshot; + private String orderType; + private String payMethod; + private Long amountCent; + private Long pointsGained; + private Integer pointsPerYuanSnapshot; + private String vipPlanCode; + private String status; + private LocalDateTime expiresAt; + private LocalDateTime paidAt; + private Long confirmedByAdminId; + private String confirmedByAdminName; + private Long secondApproverId; + private String secondApproverName; + private String remark; + private Long refundedAmountCent; + private Integer versionNo; + private LocalDateTime createTime; + private LocalDateTime updateTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/order/mapper/CashLedgerMapper.java b/finance-server/src/main/java/com/gas/fin/order/mapper/CashLedgerMapper.java new file mode 100644 index 0000000..73193e5 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/order/mapper/CashLedgerMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.order.entity.CashLedgerEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface CashLedgerMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/order/mapper/OrderMapper.java b/finance-server/src/main/java/com/gas/fin/order/mapper/OrderMapper.java new file mode 100644 index 0000000..21dab76 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/order/mapper/OrderMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.order.entity.OrderEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface OrderMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/order/service/OrderService.java b/finance-server/src/main/java/com/gas/fin/order/service/OrderService.java new file mode 100644 index 0000000..cf195b7 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/order/service/OrderService.java @@ -0,0 +1,470 @@ +package com.gas.fin.order.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.gas.fin.account.entity.AccountEntity; +import com.gas.fin.account.mapper.AccountMapper; +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.admin.mapper.AdminMapper; +import com.gas.fin.app.entity.AppEntity; +import com.gas.fin.app.mapper.AppMapper; +import com.gas.fin.common.api.PageResult; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.security.AdminAuditor; +import com.gas.fin.common.security.TotpVerifier; +import com.gas.fin.common.util.HashUtils; +import com.gas.fin.common.web.QueryUtils; +import com.gas.fin.order.dto.ApproverResponse; +import com.gas.fin.order.dto.OrderCancelRequest; +import com.gas.fin.order.dto.OrderConfirmRequest; +import com.gas.fin.order.dto.OrderDetailResponse; +import com.gas.fin.order.dto.OrderInfoResponse; +import com.gas.fin.order.entity.CashLedgerEntity; +import com.gas.fin.order.entity.OrderEntity; +import com.gas.fin.order.mapper.CashLedgerMapper; +import com.gas.fin.order.mapper.OrderMapper; +import com.gas.fin.pricing.service.PricingService; +import com.gas.fin.refund.dto.RefundInfoResponse; +import com.gas.fin.refund.entity.RefundEntity; +import com.gas.fin.refund.mapper.RefundMapper; +import com.gas.fin.transaction.entity.TransactionEntity; +import com.gas.fin.transaction.mapper.TransactionMapper; +import com.gas.fin.vip.entity.VipHolderEntity; +import com.gas.fin.vip.entity.VipPlanEntity; +import com.gas.fin.vip.mapper.VipHolderMapper; +import com.gas.fin.vip.mapper.VipPlanMapper; +import com.gas.fin.webhook.service.WebhookService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 充值/VIP 订单:查询、确认到账、关单、审批人列表。 + */ +@Service +public class OrderService { + + private static final int EXPORT_LIMIT = 10000; + private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + private final OrderMapper orderMapper; + private final CashLedgerMapper cashLedgerMapper; + private final RefundMapper refundMapper; + private final AccountMapper accountMapper; + private final VipPlanMapper vipPlanMapper; + private final VipHolderMapper vipHolderMapper; + private final TransactionMapper transactionMapper; + private final AdminMapper adminMapper; + private final AppMapper appMapper; + private final PricingService pricingService; + private final WebhookService webhookService; + private final TotpVerifier totpVerifier; + private final AdminAuditor adminAuditor; + private final ObjectMapper objectMapper; + + public OrderService(OrderMapper orderMapper, CashLedgerMapper cashLedgerMapper, + RefundMapper refundMapper, AccountMapper accountMapper, + VipPlanMapper vipPlanMapper, VipHolderMapper vipHolderMapper, + TransactionMapper transactionMapper, AdminMapper adminMapper, AppMapper appMapper, + PricingService pricingService, WebhookService webhookService, + TotpVerifier totpVerifier, AdminAuditor adminAuditor, ObjectMapper objectMapper) { + this.orderMapper = orderMapper; + this.cashLedgerMapper = cashLedgerMapper; + this.refundMapper = refundMapper; + this.accountMapper = accountMapper; + this.vipPlanMapper = vipPlanMapper; + this.vipHolderMapper = vipHolderMapper; + this.transactionMapper = transactionMapper; + this.adminMapper = adminMapper; + this.appMapper = appMapper; + this.pricingService = pricingService; + this.webhookService = webhookService; + this.totpVerifier = totpVerifier; + this.adminAuditor = adminAuditor; + this.objectMapper = objectMapper; + } + + public PageResult page(long page, long pageSize, String appCode, String status, + String orderType, String keyword, String from, String to) { + QueryUtils.checkPage(page, pageSize); + Page result = orderMapper.selectPage(new Page<>(page, pageSize), + wrapper(appCode, status, orderType, keyword, from, to)); + return PageResult.of(enrich(result.getRecords()), result.getTotal(), page, pageSize); + } + + public List export(String appCode, String status, String orderType, String keyword, + String from, String to, AdminEntity current, + HttpServletRequest httpRequest) { + LambdaQueryWrapper wrapper = wrapper(appCode, status, orderType, keyword, from, to); + wrapper.last("LIMIT " + (EXPORT_LIMIT + 1)); + List list = orderMapper.selectList(wrapper); + if (list.size() > EXPORT_LIMIT) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "导出数据超过 10000 行,请缩小查询范围"); + } + adminAuditor.success(current, "ORDER_EXPORT", "导出订单(" + list.size() + " 条)", + "ORDER", null, null, Map.of("appCode", appCode == null ? "" : appCode, + "status", status == null ? "" : status, "count", list.size()), httpRequest); + return enrich(list); + } + + public OrderDetailResponse detail(Long id) { + OrderEntity order = requireOrder(id); + List enriched = enrich(List.of(order)); + List refunds = refundMapper.selectList(new LambdaQueryWrapper() + .eq(RefundEntity::getOrderId, id) + .orderByDesc(RefundEntity::getCreateTime).orderByDesc(RefundEntity::getId)); + List cash = cashLedgerMapper.selectList(new LambdaQueryWrapper() + .eq(CashLedgerEntity::getOrderId, id) + .orderByDesc(CashLedgerEntity::getReceivedAt)); + String appName = appNames().get(order.getAppCode()); + List flows = cash.stream() + .map(item -> new OrderDetailResponse.CashFlow(item.getId(), item.getDirection(), + item.getAmountCent(), item.getReceivedAt(), item.getVoucherNo(), + item.getRemark() == null ? "" : item.getRemark())) + .toList(); + return new OrderDetailResponse(enriched.get(0), + refunds.stream().map(item -> RefundInfoResponse.from(item, appName)).toList(), flows); + } + + @Transactional + public OrderInfoResponse confirm(Long id, OrderConfirmRequest request, AdminEntity current, + HttpServletRequest httpRequest) { + OrderEntity order = requireOrder(id); + if (!"PENDING".equals(order.getStatus())) { + throw new BizException(ErrorCode.STATUS_CONFLICT, "订单当前状态不可确认到账,请刷新后重试"); + } + String voucherNo = QueryUtils.text(request.voucherNo()); + if (voucherNo.length() < 6 || voucherNo.length() > 32) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "请填写银行回单/转账凭证号(6~32 位)"); + } + LocalDateTime now = LocalDateTime.now().withNano(0); + LocalDateTime receiveAt = parseReceiveAt(request.receiveAt(), now); + if (receiveAt.isBefore(order.getCreateTime())) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "到账时间不能早于订单创建时间"); + } + if (receiveAt.isAfter(now)) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "到账时间不能晚于当前时间"); + } + totpVerifier.verify(current, request.totp(), "ORDER_CONFIRM", "确认订单到账", httpRequest); + + Long used = cashLedgerMapper.selectCount(new LambdaQueryWrapper() + .eq(CashLedgerEntity::getDirection, "IN") + .eq(CashLedgerEntity::getVoucherNo, voucherNo) + .ne(CashLedgerEntity::getOrderId, id)); + if (used != null && used > 0) { + throw new BizException(ErrorCode.DUPLICATE_VOUCHER); + } + + long threshold = pricingService.thresholdOf(order.getAppCode()); + AdminEntity approver = null; + if (order.getAmountCent() >= threshold) { + if (request.secondApproverId() == null) { + throw new BizException(ErrorCode.SECOND_APPROVER_REQUIRED, + "订单金额达到 " + (threshold / 100) + " 元,必须由第二人复核后才能入账"); + } + if (request.secondApproverId().equals(current.getId())) { + throw new BizException(ErrorCode.INVALID_APPROVER, "复核人不得与确认人为同一人"); + } + approver = adminMapper.selectById(request.secondApproverId()); + if (approver == null || !Integer.valueOf(1).equals(approver.getIsActive())) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "复核管理员不存在或已停用"); + } + if (!"SUPER_ADMIN".equals(approver.getRole()) && !"FINANCE".equals(approver.getRole())) { + throw new BizException(ErrorCode.INVALID_APPROVER, "复核人必须具备资金操作权限"); + } + } + + VipPlanEntity plan = null; + if ("vip".equals(order.getOrderType())) { + plan = vipPlanMapper.selectOne(new LambdaQueryWrapper() + .eq(VipPlanEntity::getAppCode, order.getAppCode()) + .eq(VipPlanEntity::getPlanCode, order.getVipPlanCode()) + .eq(VipPlanEntity::getEnabled, 1) + .last("LIMIT 1")); + if (plan == null) { + throw new BizException(ErrorCode.BIZ_OBJECT_UNAVAILABLE, "VIP 档位不存在或已下架"); + } + } + AccountEntity account = "vip".equals(order.getOrderType()) ? null + : findAccount(order.getAppCode(), order.getBusinessUserId()); + if (!"vip".equals(order.getOrderType()) && order.getPointsGained() > 0 && account == null) { + throw new BizException(ErrorCode.NOT_FOUND, "业务用户钱包不存在,无法入账"); + } + + int version = order.getVersionNo() == null ? 0 : order.getVersionNo(); + LambdaUpdateWrapper update = new LambdaUpdateWrapper() + .eq(OrderEntity::getId, id) + .eq(OrderEntity::getStatus, "PENDING") + .set(OrderEntity::getStatus, "PAID") + .set(OrderEntity::getPaidAt, now) + .set(OrderEntity::getConfirmedByAdminId, current.getId()) + .set(OrderEntity::getConfirmedByAdminName, current.getUsername()) + .set(OrderEntity::getVersionNo, version + 1) + .set(OrderEntity::getUpdateTime, now); + if (approver != null) { + update.set(OrderEntity::getSecondApproverId, approver.getId()) + .set(OrderEntity::getSecondApproverName, approver.getUsername()); + } + if (orderMapper.update(null, update) == 0) { + throw new BizException(ErrorCode.STATUS_CONFLICT, "订单当前状态不可确认到账,请刷新后重试"); + } + + CashLedgerEntity cash = new CashLedgerEntity(); + cash.setAppCode(order.getAppCode()); + cash.setOrderId(order.getId()); + cash.setDirection("IN"); + cash.setAmountCent(order.getAmountCent()); + cash.setReceivedAt(receiveAt); + cash.setVoucherNo(voucherNo); + cash.setOperatorAdminId(current.getId()); + cash.setOperatorAdminName(current.getUsername()); + cash.setRemark("管理员确认到账"); + cash.setCreateTime(now); + cashLedgerMapper.insert(cash); + + if (plan != null) { + applyVip(order, plan, now); + } else if (order.getPointsGained() > 0) { + applyRecharge(order, account, current, now); + } + + Map payload = new LinkedHashMap<>(); + payload.put("outTradeNo", order.getOutTradeNo()); + payload.put("amountCent", order.getAmountCent()); + payload.put("points", order.getPointsGained()); + webhookService.enqueue(order.getAppCode(), eventId("order.paid", order.getOutTradeNo(), now), + "order.paid", toJson(payload)); + + Map before = new LinkedHashMap<>(); + before.put("status", "PENDING"); + Map after = new LinkedHashMap<>(); + after.put("status", "PAID"); + after.put("voucherNo", voucherNo); + after.put("secondApproverId", approver == null ? null : approver.getId()); + adminAuditor.success(current, "ORDER_CONFIRM", "确认订单到账", "ORDER", id, before, after, httpRequest); + return enrich(List.of(requireOrder(id))).get(0); + } + + @Transactional + public OrderInfoResponse cancel(Long id, OrderCancelRequest request, AdminEntity current, + HttpServletRequest httpRequest) { + OrderEntity order = requireOrder(id); + if (!"PENDING".equals(order.getStatus())) { + throw new BizException(ErrorCode.STATUS_CONFLICT, "仅待确认订单可以关单"); + } + String reason = QueryUtils.text(request.reason()); + if (reason.length() < 5 || reason.length() > 255) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "请填写关单原因(不少于 5 个字)"); + } + totpVerifier.verify(current, request.totp(), "ORDER_CANCEL", "关闭订单", httpRequest); + int version = order.getVersionNo() == null ? 0 : order.getVersionNo(); + int rows = orderMapper.update(null, new LambdaUpdateWrapper() + .eq(OrderEntity::getId, id) + .eq(OrderEntity::getStatus, "PENDING") + .set(OrderEntity::getStatus, "CANCELLED") + .set(OrderEntity::getRemark, reason) + .set(OrderEntity::getVersionNo, version + 1) + .set(OrderEntity::getUpdateTime, LocalDateTime.now().withNano(0))); + if (rows == 0) { + throw new BizException(ErrorCode.STATUS_CONFLICT, "仅待确认订单可以关单"); + } + Map after = new LinkedHashMap<>(); + after.put("status", "CANCELLED"); + after.put("reason", reason); + adminAuditor.success(current, "ORDER_CANCEL", "关闭订单", "ORDER", id, null, after, httpRequest); + return enrich(List.of(requireOrder(id))).get(0); + } + + public List approvers(AdminEntity current) { + return adminMapper.selectList(new LambdaQueryWrapper() + .eq(AdminEntity::getIsActive, 1) + .ne(AdminEntity::getId, current.getId()) + .in(AdminEntity::getRole, List.of("SUPER_ADMIN", "FINANCE")) + .orderByAsc(AdminEntity::getUsername)) + .stream() + .map(item -> new ApproverResponse(item.getId(), item.getUsername(), item.getRole())) + .toList(); + } + + private void applyRecharge(OrderEntity order, AccountEntity account, AdminEntity current, LocalDateTime now) { + long before = account.getBalance(); + long after = before + order.getPointsGained(); + int version = account.getVersionNo() == null ? 0 : account.getVersionNo(); + int rows = accountMapper.update(null, new LambdaUpdateWrapper() + .eq(AccountEntity::getId, account.getId()) + .eq(AccountEntity::getVersionNo, version) + .set(AccountEntity::getBalance, after) + .set(AccountEntity::getVersionNo, version + 1) + .set(AccountEntity::getUpdateTime, now)); + if (rows == 0) { + throw new BizException(ErrorCode.CONCURRENT_CONFLICT); + } + TransactionEntity tx = new TransactionEntity(); + tx.setAppCode(order.getAppCode()); + tx.setBusinessUserId(order.getBusinessUserId()); + tx.setUsernameSnapshot(order.getUsernameSnapshot()); + tx.setType("RECHARGE"); + tx.setAmount(order.getPointsGained()); + tx.setBalanceBefore(before); + tx.setBalanceAfter(after); + tx.setBusinessRefId(order.getOutTradeNo()); + tx.setIdempotencyKey("order:" + order.getOutTradeNo()); + tx.setOrderId(order.getId()); + tx.setOutTradeNo(order.getOutTradeNo()); + tx.setRefundedPoints(0L); + tx.setOperatorAdminId(current.getId()); + tx.setOperatorAdminName(current.getUsername()); + tx.setRemark("充值确认到账"); + tx.setCreateTime(now); + transactionMapper.insert(tx); + } + + private void applyVip(OrderEntity order, VipPlanEntity plan, LocalDateTime now) { + VipHolderEntity holder = vipHolderMapper.selectOne(new LambdaQueryWrapper() + .eq(VipHolderEntity::getAppCode, order.getAppCode()) + .eq(VipHolderEntity::getBusinessUserId, order.getBusinessUserId()) + .last("LIMIT 1")); + LocalDateTime base = holder != null && holder.getVipUntil().isAfter(now) ? holder.getVipUntil() : now; + LocalDateTime vipUntil = base.plusDays(plan.getDurationDays()); + if (holder == null) { + VipHolderEntity entity = new VipHolderEntity(); + entity.setAppCode(order.getAppCode()); + entity.setBusinessUserId(order.getBusinessUserId()); + entity.setVipPlanCode(plan.getPlanCode()); + entity.setVipUntil(vipUntil); + entity.setCreateTime(now); + entity.setUpdateTime(now); + vipHolderMapper.insert(entity); + } else { + vipHolderMapper.update(null, new LambdaUpdateWrapper() + .eq(VipHolderEntity::getId, holder.getId()) + .set(VipHolderEntity::getVipPlanCode, plan.getPlanCode()) + .set(VipHolderEntity::getVipUntil, vipUntil) + .set(VipHolderEntity::getUpdateTime, now)); + } + AccountEntity account = findAccount(order.getAppCode(), order.getBusinessUserId()); + if (account != null) { + accountMapper.update(null, new LambdaUpdateWrapper() + .eq(AccountEntity::getId, account.getId()) + .set(AccountEntity::getVipPlanCode, plan.getPlanCode()) + .set(AccountEntity::getVipUntil, vipUntil) + .set(AccountEntity::getUpdateTime, now)); + } + } + + private List enrich(List orders) { + if (orders.isEmpty()) { + return List.of(); + } + List ids = orders.stream().map(OrderEntity::getId).toList(); + Map cashIn = new HashMap<>(); + Map cashOut = new HashMap<>(); + cashLedgerMapper.selectList(new LambdaQueryWrapper() + .in(CashLedgerEntity::getOrderId, ids)) + .forEach(item -> { + Map target = "IN".equals(item.getDirection()) ? cashIn : cashOut; + target.merge(item.getOrderId(), item.getAmountCent(), Long::sum); + }); + Map appNames = appNames(); + Map thresholds = new HashMap<>(); + List result = new ArrayList<>(); + for (OrderEntity order : orders) { + long threshold = thresholds.computeIfAbsent(order.getAppCode(), pricingService::thresholdOf); + result.add(OrderInfoResponse.from(order, appNames.get(order.getAppCode()), + cashIn.getOrDefault(order.getId(), 0L), cashOut.getOrDefault(order.getId(), 0L), + order.getAmountCent() >= threshold)); + } + return result; + } + + private LambdaQueryWrapper wrapper(String appCode, String status, String orderType, + String keyword, String from, String to) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (appCode != null && !appCode.isBlank()) { + wrapper.eq(OrderEntity::getAppCode, appCode.trim()); + } + if (status != null && !status.isBlank()) { + wrapper.eq(OrderEntity::getStatus, status.trim()); + } + if (orderType != null && !orderType.isBlank()) { + wrapper.eq(OrderEntity::getOrderType, orderType.trim()); + } + if (keyword != null && !keyword.isBlank()) { + String value = keyword.trim(); + wrapper.and(w -> w.like(OrderEntity::getOutTradeNo, value) + .or().like(OrderEntity::getBusinessUserId, value) + .or().like(OrderEntity::getUsernameSnapshot, value)); + } + LocalDateTime fromTime = QueryUtils.parseFrom(from); + LocalDateTime toTime = QueryUtils.parseTo(to); + if (fromTime != null) { + wrapper.ge(OrderEntity::getCreateTime, fromTime); + } + if (toTime != null) { + wrapper.le(OrderEntity::getCreateTime, toTime); + } + wrapper.orderByDesc(OrderEntity::getCreateTime).orderByDesc(OrderEntity::getId); + return wrapper; + } + + private OrderEntity requireOrder(Long id) { + OrderEntity order = orderMapper.selectById(id); + if (order == null) { + throw new BizException(ErrorCode.NOT_FOUND, "订单不存在"); + } + return order; + } + + private AccountEntity findAccount(String appCode, String businessUserId) { + return accountMapper.selectOne(new LambdaQueryWrapper() + .eq(AccountEntity::getAppCode, appCode) + .eq(AccountEntity::getBusinessUserId, businessUserId) + .last("LIMIT 1")); + } + + private LocalDateTime parseReceiveAt(String value, LocalDateTime now) { + if (value == null || value.isBlank()) { + return now; + } + String text = value.trim(); + if (!text.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$")) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "到账时间格式不合法"); + } + try { + return LocalDateTime.parse(text, TIME_FORMAT); + } catch (DateTimeParseException ex) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "到账时间格式不合法"); + } + } + + private String eventId(String type, String tradeNo, LocalDateTime now) { + return "evt_" + HashUtils.sha256Hex(type + "|" + tradeNo + "|" + now).substring(0, 20); + } + + private String toJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (JsonProcessingException ex) { + throw new IllegalStateException("webhook payload 序列化失败", ex); + } + } + + private Map appNames() { + return appMapper.selectList(null).stream() + .collect(Collectors.toMap(AppEntity::getAppCode, AppEntity::getAppName, (a, b) -> a)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/pay/controller/PayController.java b/finance-server/src/main/java/com/gas/fin/pay/controller/PayController.java new file mode 100644 index 0000000..8288a39 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pay/controller/PayController.java @@ -0,0 +1,52 @@ +package com.gas.fin.pay.controller; + +import com.gas.fin.common.api.R; +import com.gas.fin.pay.dto.DemoTicketResponse; +import com.gas.fin.pay.dto.PayCreateRequest; +import com.gas.fin.pay.dto.PayOrderResponse; +import com.gas.fin.pay.dto.PayPreviewResponse; +import com.gas.fin.pay.dto.PayStatusResponse; +import com.gas.fin.pay.service.PayService; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** + * 公开收银台:不走管理端认证拦截器(/api/pay/**)。 + */ +@RestController +@RequestMapping("/api/pay") +public class PayController { + + private final PayService payService; + + public PayController(PayService payService) { + this.payService = payService; + } + + @GetMapping("/preview") + public R preview(@RequestParam String appCode, + @RequestParam String ticket, + @RequestParam(required = false) String redirectUri) { + return R.ok(payService.preview(appCode, ticket, redirectUri)); + } + + @PostMapping("/orders") + public R create(@RequestBody PayCreateRequest request) { + return R.ok(payService.create(request)); + } + + @GetMapping("/orders/{outTradeNo}/status") + public R status(@PathVariable String outTradeNo) { + return R.ok(payService.status(outTradeNo)); + } + + @GetMapping("/demo-ticket") + public R demoTicket(@RequestParam(required = false) String appCode) { + return R.ok(payService.demoTicket(appCode)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/pay/dto/DemoTicketResponse.java b/finance-server/src/main/java/com/gas/fin/pay/dto/DemoTicketResponse.java new file mode 100644 index 0000000..6fcf7e5 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pay/dto/DemoTicketResponse.java @@ -0,0 +1,7 @@ +package com.gas.fin.pay.dto; + +import java.time.LocalDateTime; + +public record DemoTicketResponse(String appCode, String ticket, String businessUserId, String username, + String redirectUri, LocalDateTime expiresAt) { +} diff --git a/finance-server/src/main/java/com/gas/fin/pay/dto/PayCreateRequest.java b/finance-server/src/main/java/com/gas/fin/pay/dto/PayCreateRequest.java new file mode 100644 index 0000000..02b9037 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pay/dto/PayCreateRequest.java @@ -0,0 +1,5 @@ +package com.gas.fin.pay.dto; + +public record PayCreateRequest(String appCode, String ticket, String orderType, Long amountCent, + String planCode, String redirectUri, String idempotencyKey) { +} diff --git a/finance-server/src/main/java/com/gas/fin/pay/dto/PayOrderResponse.java b/finance-server/src/main/java/com/gas/fin/pay/dto/PayOrderResponse.java new file mode 100644 index 0000000..5c61ee9 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pay/dto/PayOrderResponse.java @@ -0,0 +1,11 @@ +package com.gas.fin.pay.dto; + +import java.time.LocalDateTime; + +public record PayOrderResponse(String outTradeNo, long amountCent, long pointsGained, String orderType, + String vipPlanCode, String status, LocalDateTime expiresAt, Payee payee, + String redirectUri, LocalDateTime createTime) { + + public record Payee(String accountName, String bankName, String accountNo) { + } +} diff --git a/finance-server/src/main/java/com/gas/fin/pay/dto/PayPreviewResponse.java b/finance-server/src/main/java/com/gas/fin/pay/dto/PayPreviewResponse.java new file mode 100644 index 0000000..963f883 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pay/dto/PayPreviewResponse.java @@ -0,0 +1,16 @@ +package com.gas.fin.pay.dto; + +import java.time.LocalDateTime; +import java.util.List; + +public record PayPreviewResponse(String appCode, String appName, String businessUserId, String usernameSnapshot, + long balance, long pointsPerYuan, long minAmountCent, Vip vip, + List plans, LocalDateTime ticketExpiresAt) { + + public record Vip(String planCode, String planName, LocalDateTime vipUntil, Integer freeDeduction) { + } + + public record Plan(String planCode, String planName, Integer durationDays, Long priceCent, + Integer freeDeduction) { + } +} diff --git a/finance-server/src/main/java/com/gas/fin/pay/dto/PayStatusResponse.java b/finance-server/src/main/java/com/gas/fin/pay/dto/PayStatusResponse.java new file mode 100644 index 0000000..45d323a --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pay/dto/PayStatusResponse.java @@ -0,0 +1,7 @@ +package com.gas.fin.pay.dto; + +import java.time.LocalDateTime; + +public record PayStatusResponse(String outTradeNo, String status, long amountCent, long pointsGained, + LocalDateTime paidAt, LocalDateTime expiresAt) { +} diff --git a/finance-server/src/main/java/com/gas/fin/pay/entity/TicketEntity.java b/finance-server/src/main/java/com/gas/fin/pay/entity/TicketEntity.java new file mode 100644 index 0000000..173535e --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pay/entity/TicketEntity.java @@ -0,0 +1,26 @@ +package com.gas.fin.pay.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_ticket") +public class TicketEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String ticketHash; + private String ticketPrefix; + private String appCode; + private String businessUserId; + private String redirectUri; + private String issuedIp; + private LocalDateTime expiresAt; + private LocalDateTime usedAt; + private LocalDateTime createTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/pay/mapper/TicketMapper.java b/finance-server/src/main/java/com/gas/fin/pay/mapper/TicketMapper.java new file mode 100644 index 0000000..fc75be7 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pay/mapper/TicketMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.pay.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.pay.entity.TicketEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface TicketMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/pay/service/PayService.java b/finance-server/src/main/java/com/gas/fin/pay/service/PayService.java new file mode 100644 index 0000000..51aa8c4 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pay/service/PayService.java @@ -0,0 +1,379 @@ +package com.gas.fin.pay.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.gas.fin.account.entity.AccountEntity; +import com.gas.fin.account.mapper.AccountMapper; +import com.gas.fin.app.entity.AppEntity; +import com.gas.fin.app.mapper.AppMapper; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.id.FinIdGenerator; +import com.gas.fin.common.util.HashUtils; +import com.gas.fin.order.entity.OrderEntity; +import com.gas.fin.order.mapper.OrderMapper; +import com.gas.fin.pay.dto.DemoTicketResponse; +import com.gas.fin.pay.dto.PayCreateRequest; +import com.gas.fin.pay.dto.PayOrderResponse; +import com.gas.fin.pay.dto.PayPreviewResponse; +import com.gas.fin.pay.dto.PayStatusResponse; +import com.gas.fin.pay.entity.TicketEntity; +import com.gas.fin.pay.mapper.TicketMapper; +import com.gas.fin.pricing.entity.AppPricingEntity; +import com.gas.fin.pricing.mapper.AppPricingMapper; +import com.gas.fin.setting.service.ConfigService; +import com.gas.fin.vip.entity.VipHolderEntity; +import com.gas.fin.vip.entity.VipPlanEntity; +import com.gas.fin.vip.mapper.VipHolderMapper; +import com.gas.fin.vip.mapper.VipPlanMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.HexFormat; +import java.util.List; + +/** + * 公开收银台:一次性 ticket 校验、下单、订单状态轮询、演示凭证。 + */ +@Service +public class PayService { + + private static final Logger log = LoggerFactory.getLogger(PayService.class); + private static final String IDEM_PREFIX = "fin:pay:idem:"; + private static final DateTimeFormatter DATE_PART = DateTimeFormatter.ofPattern("yyyyMMdd"); + + private final AppMapper appMapper; + private final TicketMapper ticketMapper; + private final AccountMapper accountMapper; + private final VipPlanMapper vipPlanMapper; + private final VipHolderMapper vipHolderMapper; + private final AppPricingMapper pricingMapper; + private final OrderMapper orderMapper; + private final ConfigService configService; + private final StringRedisTemplate redisTemplate; + private final FinIdGenerator idGenerator; + + @Value("${fin.demo-ticket-enabled:true}") + private boolean demoTicketEnabled; + + @Value("${spring.profiles.active:local}") + private String activeProfile; + + public PayService(AppMapper appMapper, TicketMapper ticketMapper, AccountMapper accountMapper, + VipPlanMapper vipPlanMapper, VipHolderMapper vipHolderMapper, + AppPricingMapper pricingMapper, OrderMapper orderMapper, ConfigService configService, + StringRedisTemplate redisTemplate, FinIdGenerator idGenerator) { + this.appMapper = appMapper; + this.ticketMapper = ticketMapper; + this.accountMapper = accountMapper; + this.vipPlanMapper = vipPlanMapper; + this.vipHolderMapper = vipHolderMapper; + this.pricingMapper = pricingMapper; + this.orderMapper = orderMapper; + this.configService = configService; + this.redisTemplate = redisTemplate; + this.idGenerator = idGenerator; + } + + public PayPreviewResponse preview(String appCode, String ticketNo, String redirectUri) { + if (appCode == null || appCode.isBlank() || ticketNo == null || ticketNo.isBlank()) { + throw new BizException(ErrorCode.TICKET_INVALID, "缺少凭证参数"); + } + TicketEntity ticket = validTicket(appCode.trim(), ticketNo.trim(), redirectUri); + AppEntity app = requireApp(appCode.trim()); + AccountEntity account = findAccount(app.getAppCode(), ticket.getBusinessUserId()); + long rate = rateOf(app.getAppCode()); + VipHolderEntity holder = findHolder(app.getAppCode(), ticket.getBusinessUserId()); + PayPreviewResponse.Vip vip = null; + if (holder != null) { + VipPlanEntity plan = findPlan(app.getAppCode(), holder.getVipPlanCode()); + vip = new PayPreviewResponse.Vip(holder.getVipPlanCode(), + plan == null ? holder.getVipPlanCode() : plan.getPlanName(), + holder.getVipUntil(), + plan == null || plan.getFreeDeduction() == null ? 0 : plan.getFreeDeduction()); + } + List plans = vipPlanMapper.selectList(new LambdaQueryWrapper() + .eq(VipPlanEntity::getAppCode, app.getAppCode()) + .eq(VipPlanEntity::getEnabled, 1) + .orderByAsc(VipPlanEntity::getPriceCent)) + .stream() + .map(item -> new PayPreviewResponse.Plan(item.getPlanCode(), item.getPlanName(), + item.getDurationDays(), item.getPriceCent(), item.getFreeDeduction())) + .toList(); + return new PayPreviewResponse(app.getAppCode(), app.getAppName(), ticket.getBusinessUserId(), + account == null || account.getUsernameSnapshot() == null ? "业务用户" + : account.getUsernameSnapshot(), + account == null ? 0 : account.getBalance(), rate, 100, vip, plans, ticket.getExpiresAt()); + } + + @Transactional + public PayOrderResponse create(PayCreateRequest request) { + String appCode = request.appCode() == null ? "" : request.appCode().trim(); + String ticketNo = request.ticket() == null ? "" : request.ticket().trim(); + String orderType = request.orderType() == null ? "" : request.orderType().trim(); + if (!"recharge".equals(orderType) && !"vip".equals(orderType)) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "订单类型不合法"); + } + String idempotencyKey = request.idempotencyKey() == null ? "" : request.idempotencyKey().trim(); + String storeKey = idempotencyKey.isEmpty() ? null : IDEM_PREFIX + appCode + ":" + idempotencyKey; + if (!idempotencyKey.isEmpty()) { + if (!idempotencyKey.matches("^[A-Za-z0-9:_-]{8,64}$")) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "幂等键格式不合法"); + } + PayOrderResponse existing = findByStoreKey(storeKey, request.redirectUri()); + if (existing != null) { + return existing; + } + } + + TicketEntity ticket = validTicket(appCode, ticketNo, request.redirectUri()); + AppEntity app = requireApp(appCode); + + long amountCent; + long pointsGained = 0; + String planCode = null; + long rate = rateOf(appCode); + if ("recharge".equals(orderType)) { + amountCent = request.amountCent() == null ? 0 : request.amountCent(); + if (amountCent < 100 || amountCent > 5000000) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "充值金额需为 1~50000 元的整数分"); + } + pointsGained = amountCent * rate / 100; + } else { + planCode = request.planCode() == null ? "" : request.planCode().trim(); + VipPlanEntity plan = vipPlanMapper.selectOne(new LambdaQueryWrapper() + .eq(VipPlanEntity::getAppCode, appCode) + .eq(VipPlanEntity::getPlanCode, planCode) + .eq(VipPlanEntity::getEnabled, 1) + .last("LIMIT 1")); + if (plan == null) { + throw new BizException(ErrorCode.BIZ_OBJECT_UNAVAILABLE, "VIP 档位不存在或已下架"); + } + amountCent = plan.getPriceCent(); + } + + LocalDateTime now = LocalDateTime.now().withNano(0); + int consumed = ticketMapper.update(null, new LambdaUpdateWrapper() + .eq(TicketEntity::getId, ticket.getId()) + .isNull(TicketEntity::getUsedAt) + .gt(TicketEntity::getExpiresAt, now) + .set(TicketEntity::getUsedAt, now)); + if (consumed == 0) { + throw new BizException(ErrorCode.TICKET_INVALID, "凭证已被使用"); + } + + long id = idGenerator.nextLongId(); + String datePart = LocalDate.now().format(DATE_PART); + String suffix = String.format("%05d", id % 100000); + AccountEntity account = findAccount(appCode, ticket.getBusinessUserId()); + long timeoutHours = configService.getNumber("order.pending.timeout_hours", 24); + + OrderEntity order = new OrderEntity(); + order.setId(id); + order.setOutTradeNo(("vip".equals(orderType) ? "VIP" : "RC") + datePart + suffix); + order.setAppCode(appCode); + order.setBusinessUserId(ticket.getBusinessUserId()); + order.setUsernameSnapshot(account == null || account.getUsernameSnapshot() == null + ? "" : account.getUsernameSnapshot()); + order.setOrderType(orderType); + order.setPayMethod("offline"); + order.setAmountCent(amountCent); + order.setPointsGained(pointsGained); + order.setPointsPerYuanSnapshot((int) rate); + order.setVipPlanCode(planCode); + order.setStatus("PENDING"); + order.setExpiresAt(now.plusHours(timeoutHours)); + order.setRemark("用户自助下单"); + order.setRefundedAmountCent(0L); + order.setVersionNo(0); + order.setCreateTime(now); + order.setUpdateTime(now); + orderMapper.insert(order); + if (storeKey != null) { + storeIdempotency(storeKey, order.getId()); + } + return toOrderResponse(order, request.redirectUri()); + } + + public PayStatusResponse status(String outTradeNo) { + if (outTradeNo == null || outTradeNo.isBlank()) { + throw new BizException(ErrorCode.NOT_FOUND, "订单不存在"); + } + OrderEntity order = orderMapper.selectOne(new LambdaQueryWrapper() + .eq(OrderEntity::getOutTradeNo, outTradeNo.trim()) + .last("LIMIT 1")); + if (order == null) { + throw new BizException(ErrorCode.NOT_FOUND, "订单不存在"); + } + return new PayStatusResponse(order.getOutTradeNo(), order.getStatus(), order.getAmountCent(), + order.getPointsGained(), order.getPaidAt(), order.getExpiresAt()); + } + + @Transactional + public DemoTicketResponse demoTicket(String appCode) { + if (!demoTicketEnabled || "prod".equalsIgnoreCase(activeProfile)) { + throw new BizException(ErrorCode.NOT_FOUND, "资源不存在"); + } + String code = appCode == null || appCode.isBlank() ? "litho-sim" : appCode.trim(); + AppEntity app = requireApp(code); + AccountEntity account = accountMapper.selectOne(new LambdaQueryWrapper() + .eq(AccountEntity::getAppCode, code) + .orderByAsc(AccountEntity::getId) + .last("LIMIT 1")); + if (account == null) { + throw new BizException(ErrorCode.NOT_FOUND, "该应用暂无业务用户"); + } + long ttlMinutes = configService.getNumber("ticket.ttl_minutes", 5); + LocalDateTime now = LocalDateTime.now().withNano(0); + LocalDateTime expiresAt = now.plusMinutes(ttlMinutes); + String ticket = "tk_" + HexFormat.of().formatHex(HashUtils.randomBytes(24)); + + TicketEntity entity = new TicketEntity(); + entity.setTicketHash(HashUtils.sha256Hex(ticket)); + entity.setTicketPrefix(ticket.substring(0, 12)); + entity.setAppCode(code); + entity.setBusinessUserId(account.getBusinessUserId()); + entity.setExpiresAt(expiresAt); + entity.setCreateTime(now); + ticketMapper.insert(entity); + + String host = app.getAllowedRedirectHosts().split(",")[0].trim(); + return new DemoTicketResponse(code, ticket, account.getBusinessUserId(), + account.getUsernameSnapshot(), "https://" + host + "/wallet/recharge", expiresAt); + } + + private TicketEntity validTicket(String appCode, String rawTicket, String redirectUri) { + if (rawTicket.isEmpty()) { + throw new BizException(ErrorCode.TICKET_INVALID, "凭证无效或已被使用"); + } + TicketEntity ticket = ticketMapper.selectOne(new LambdaQueryWrapper() + .eq(TicketEntity::getTicketHash, HashUtils.sha256Hex(rawTicket)) + .last("LIMIT 1")); + if (ticket == null) { + throw new BizException(ErrorCode.TICKET_INVALID, "凭证无效或已被使用"); + } + if (!ticket.getAppCode().equals(appCode)) { + throw new BizException(ErrorCode.TICKET_INVALID, "凭证与应用不匹配"); + } + if (ticket.getUsedAt() != null) { + throw new BizException(ErrorCode.TICKET_INVALID, "凭证已被使用,请返回业务系统重新发起"); + } + if (!ticket.getExpiresAt().isAfter(LocalDateTime.now().withNano(0))) { + throw new BizException(ErrorCode.TICKET_INVALID, "凭证已过期,请返回业务系统重新发起"); + } + AppEntity app = requireApp(appCode); + if (!Integer.valueOf(1).equals(app.getEnabled())) { + throw new BizException(ErrorCode.APP_CREDENTIAL_INVALID, "应用已停用,暂不支持收款"); + } + assertRedirectUri(app, redirectUri); + return ticket; + } + + private void assertRedirectUri(AppEntity app, String redirectUri) { + if (redirectUri == null || redirectUri.isBlank()) { + return; + } + String host = com.gas.fin.app.service.AppService.hostOf(redirectUri.trim()); + if (host == null) { + throw new BizException(ErrorCode.BAD_REQUEST, "跳转地址格式不合法"); + } + boolean allowed = false; + for (String item : app.getAllowedRedirectHosts().split(",")) { + if (item.trim().equalsIgnoreCase(host)) { + allowed = true; + break; + } + } + if (!allowed) { + throw new BizException(ErrorCode.BAD_REQUEST, "跳转地址不在白名单内"); + } + String value = redirectUri.trim(); + boolean localhost = value.startsWith("http://127.0.0.1") || value.startsWith("http://localhost"); + if (!value.startsWith("https://") && !localhost) { + throw new BizException(ErrorCode.BAD_REQUEST, "外部跳转必须使用 HTTPS"); + } + } + + private PayOrderResponse findByStoreKey(String storeKey, String redirectUri) { + if (storeKey == null) { + return null; + } + try { + String value = redisTemplate.opsForValue().get(storeKey); + if (value == null) { + return null; + } + OrderEntity order = orderMapper.selectById(Long.parseLong(value)); + if (order == null) { + return null; + } + return toOrderResponse(order, redirectUri); + } catch (Exception ex) { + log.warn("读取收银台幂等键失败,按新请求处理 key={}", storeKey, ex); + return null; + } + } + + private void storeIdempotency(String storeKey, Long orderId) { + try { + redisTemplate.opsForValue().set(storeKey, String.valueOf(orderId), Duration.ofHours(24)); + } catch (Exception ex) { + log.warn("写入收银台幂等键失败 key={}", storeKey, ex); + } + } + + private PayOrderResponse toOrderResponse(OrderEntity order, String redirectUri) { + PayOrderResponse.Payee payee = new PayOrderResponse.Payee( + configService.getText("payee.account_name", "待配置"), + configService.getText("payee.bank_name", "待配置"), + configService.getText("payee.account_no_masked", "****")); + return new PayOrderResponse(order.getOutTradeNo(), order.getAmountCent(), order.getPointsGained(), + order.getOrderType(), order.getVipPlanCode(), order.getStatus(), order.getExpiresAt(), + payee, redirectUri == null || redirectUri.isBlank() ? null : redirectUri, + order.getCreateTime()); + } + + private AppEntity requireApp(String appCode) { + AppEntity app = appMapper.selectOne(new LambdaQueryWrapper() + .eq(AppEntity::getAppCode, appCode).last("LIMIT 1")); + if (app == null) { + throw new BizException(ErrorCode.NOT_FOUND, "接入应用不存在"); + } + return app; + } + + private AccountEntity findAccount(String appCode, String businessUserId) { + return accountMapper.selectOne(new LambdaQueryWrapper() + .eq(AccountEntity::getAppCode, appCode) + .eq(AccountEntity::getBusinessUserId, businessUserId) + .last("LIMIT 1")); + } + + private VipHolderEntity findHolder(String appCode, String businessUserId) { + return vipHolderMapper.selectOne(new LambdaQueryWrapper() + .eq(VipHolderEntity::getAppCode, appCode) + .eq(VipHolderEntity::getBusinessUserId, businessUserId) + .last("LIMIT 1")); + } + + private VipPlanEntity findPlan(String appCode, String planCode) { + return vipPlanMapper.selectOne(new LambdaQueryWrapper() + .eq(VipPlanEntity::getAppCode, appCode) + .eq(VipPlanEntity::getPlanCode, planCode) + .last("LIMIT 1")); + } + + private long rateOf(String appCode) { + AppPricingEntity pricing = pricingMapper.selectOne(new LambdaQueryWrapper() + .eq(AppPricingEntity::getAppCode, appCode).last("LIMIT 1")); + return pricing == null || pricing.getPointsPerYuan() == null ? 100 : pricing.getPointsPerYuan(); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/pricing/controller/PricingController.java b/finance-server/src/main/java/com/gas/fin/pricing/controller/PricingController.java new file mode 100644 index 0000000..97a0ac1 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pricing/controller/PricingController.java @@ -0,0 +1,59 @@ +package com.gas.fin.pricing.controller; + +import com.gas.fin.common.api.R; +import com.gas.fin.common.security.AuthContext; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.security.RequirePermission; +import com.gas.fin.pricing.dto.AppPolicyResponse; +import com.gas.fin.pricing.dto.PolicyUpdateRequest; +import com.gas.fin.pricing.dto.PricingItemResponse; +import com.gas.fin.pricing.dto.PricingUpdateRequest; +import com.gas.fin.pricing.service.PricingService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api/admin") +public class PricingController { + + private final PricingService pricingService; + + public PricingController(PricingService pricingService) { + this.pricingService = pricingService; + } + + @GetMapping("/pricing") + @RequirePermission(PermissionRegistry.VIEW) + public R> pricing() { + return R.ok(pricingService.listPricing()); + } + + @PutMapping("/pricing/{appCode}") + @RequirePermission(PermissionRegistry.PRICING_EDIT) + public R updatePricing(@PathVariable String appCode, + @RequestBody PricingUpdateRequest request, + HttpServletRequest httpRequest) { + return R.ok(pricingService.updatePricing(appCode, request, AuthContext.require(), httpRequest)); + } + + @GetMapping("/policies") + @RequirePermission(PermissionRegistry.VIEW) + public R> policies() { + return R.ok(pricingService.listPolicies()); + } + + @PutMapping("/policies/{appCode}") + @RequirePermission(PermissionRegistry.PRICING_EDIT) + public R updatePolicy(@PathVariable String appCode, + @RequestBody PolicyUpdateRequest request, + HttpServletRequest httpRequest) { + return R.ok(pricingService.updatePolicy(appCode, request, AuthContext.require(), httpRequest)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/pricing/dto/AppPolicyResponse.java b/finance-server/src/main/java/com/gas/fin/pricing/dto/AppPolicyResponse.java new file mode 100644 index 0000000..dcdc892 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pricing/dto/AppPolicyResponse.java @@ -0,0 +1,34 @@ +package com.gas.fin.pricing.dto; + +import com.gas.fin.pricing.entity.AppPolicyEntity; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class AppPolicyResponse { + + private String appCode; + private String appName; + private Long minCost; + private Long maxPointsPerCharge; + private Integer vipExempt; + private String failedStrategy; + private Long dualControlThresholdCent; + private Integer enabled; + private LocalDateTime updateTime; + + public static AppPolicyResponse from(AppPolicyEntity entity, String appName) { + AppPolicyResponse response = new AppPolicyResponse(); + response.setAppCode(entity.getAppCode()); + response.setAppName(appName == null ? entity.getAppCode() : appName); + response.setMinCost(entity.getMinCost()); + response.setMaxPointsPerCharge(entity.getMaxPointsPerCharge()); + response.setVipExempt(entity.getVipExempt()); + response.setFailedStrategy(entity.getFailedStrategy()); + response.setDualControlThresholdCent(entity.getDualControlThresholdCent()); + response.setEnabled(entity.getEnabled()); + response.setUpdateTime(entity.getUpdateTime()); + return response; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/pricing/dto/PolicyUpdateRequest.java b/finance-server/src/main/java/com/gas/fin/pricing/dto/PolicyUpdateRequest.java new file mode 100644 index 0000000..0c26a40 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pricing/dto/PolicyUpdateRequest.java @@ -0,0 +1,5 @@ +package com.gas.fin.pricing.dto; + +public record PolicyUpdateRequest(Long minCost, Long maxPointsPerCharge, Integer vipExempt, + String failedStrategy, Long dualControlThresholdCent, String totp) { +} diff --git a/finance-server/src/main/java/com/gas/fin/pricing/dto/PricingItemResponse.java b/finance-server/src/main/java/com/gas/fin/pricing/dto/PricingItemResponse.java new file mode 100644 index 0000000..81afd41 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pricing/dto/PricingItemResponse.java @@ -0,0 +1,26 @@ +package com.gas.fin.pricing.dto; + +import com.gas.fin.pricing.entity.AppPricingEntity; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class PricingItemResponse { + + private String appCode; + private String appName; + private Long pointsPerYuan; + private Integer enabled; + private LocalDateTime updateTime; + + public static PricingItemResponse from(AppPricingEntity entity, String appName) { + PricingItemResponse response = new PricingItemResponse(); + response.setAppCode(entity.getAppCode()); + response.setAppName(appName == null ? entity.getAppCode() : appName); + response.setPointsPerYuan(entity.getPointsPerYuan()); + response.setEnabled(entity.getEnabled()); + response.setUpdateTime(entity.getUpdateTime()); + return response; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/pricing/dto/PricingUpdateRequest.java b/finance-server/src/main/java/com/gas/fin/pricing/dto/PricingUpdateRequest.java new file mode 100644 index 0000000..7859804 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pricing/dto/PricingUpdateRequest.java @@ -0,0 +1,4 @@ +package com.gas.fin.pricing.dto; + +public record PricingUpdateRequest(Long pointsPerYuan, Integer enabled, String totp) { +} diff --git a/finance-server/src/main/java/com/gas/fin/pricing/entity/AppPolicyEntity.java b/finance-server/src/main/java/com/gas/fin/pricing/entity/AppPolicyEntity.java new file mode 100644 index 0000000..b32e36c --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pricing/entity/AppPolicyEntity.java @@ -0,0 +1,28 @@ +package com.gas.fin.pricing.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_app_policy") +public class AppPolicyEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String appCode; + private Long minCost; + private Long maxPointsPerCharge; + private Integer vipExempt; + private String failedStrategy; + private Long dualControlThresholdCent; + private Integer enabled; + private String updateBy; + private Integer versionNo; + private LocalDateTime createTime; + private LocalDateTime updateTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/pricing/entity/AppPricingEntity.java b/finance-server/src/main/java/com/gas/fin/pricing/entity/AppPricingEntity.java new file mode 100644 index 0000000..5ee1d5b --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pricing/entity/AppPricingEntity.java @@ -0,0 +1,24 @@ +package com.gas.fin.pricing.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_app_pricing") +public class AppPricingEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String appCode; + private Long pointsPerYuan; + private Integer enabled; + private String updateBy; + private Integer versionNo; + private LocalDateTime createTime; + private LocalDateTime updateTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/pricing/mapper/AppPolicyMapper.java b/finance-server/src/main/java/com/gas/fin/pricing/mapper/AppPolicyMapper.java new file mode 100644 index 0000000..46af031 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pricing/mapper/AppPolicyMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.pricing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.pricing.entity.AppPolicyEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface AppPolicyMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/pricing/mapper/AppPricingMapper.java b/finance-server/src/main/java/com/gas/fin/pricing/mapper/AppPricingMapper.java new file mode 100644 index 0000000..d8c2cad --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pricing/mapper/AppPricingMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.pricing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.pricing.entity.AppPricingEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface AppPricingMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/pricing/service/PricingService.java b/finance-server/src/main/java/com/gas/fin/pricing/service/PricingService.java new file mode 100644 index 0000000..bc1086e --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/pricing/service/PricingService.java @@ -0,0 +1,180 @@ +package com.gas.fin.pricing.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.app.entity.AppEntity; +import com.gas.fin.app.mapper.AppMapper; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.security.AdminAuditor; +import com.gas.fin.common.security.TotpVerifier; +import com.gas.fin.pricing.dto.AppPolicyResponse; +import com.gas.fin.pricing.dto.PolicyUpdateRequest; +import com.gas.fin.pricing.dto.PricingItemResponse; +import com.gas.fin.pricing.dto.PricingUpdateRequest; +import com.gas.fin.pricing.entity.AppPolicyEntity; +import com.gas.fin.pricing.entity.AppPricingEntity; +import com.gas.fin.pricing.mapper.AppPolicyMapper; +import com.gas.fin.pricing.mapper.AppPricingMapper; +import com.gas.fin.setting.service.ConfigService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 应用兑率与扣费策略。 + */ +@Service +public class PricingService { + + private final AppPricingMapper pricingMapper; + private final AppPolicyMapper policyMapper; + private final AppMapper appMapper; + private final ConfigService configService; + private final TotpVerifier totpVerifier; + private final AdminAuditor adminAuditor; + + public PricingService(AppPricingMapper pricingMapper, AppPolicyMapper policyMapper, AppMapper appMapper, + ConfigService configService, TotpVerifier totpVerifier, AdminAuditor adminAuditor) { + this.pricingMapper = pricingMapper; + this.policyMapper = policyMapper; + this.appMapper = appMapper; + this.configService = configService; + this.totpVerifier = totpVerifier; + this.adminAuditor = adminAuditor; + } + + public List listPricing() { + Map names = appNames(); + return pricingMapper.selectList(new LambdaQueryWrapper() + .orderByAsc(AppPricingEntity::getAppCode)) + .stream().map(item -> PricingItemResponse.from(item, names.get(item.getAppCode()))).toList(); + } + + public List listPolicies() { + Map names = appNames(); + return policyMapper.selectList(new LambdaQueryWrapper() + .orderByAsc(AppPolicyEntity::getAppCode)) + .stream().map(item -> AppPolicyResponse.from(item, names.get(item.getAppCode()))).toList(); + } + + public AppPricingEntity requirePricing(String appCode) { + AppPricingEntity item = pricingMapper.selectOne(new LambdaQueryWrapper() + .eq(AppPricingEntity::getAppCode, appCode).last("LIMIT 1")); + if (item == null) { + throw new BizException(ErrorCode.NOT_FOUND, "兑率配置不存在"); + } + return item; + } + + public AppPolicyEntity findPolicy(String appCode) { + return policyMapper.selectOne(new LambdaQueryWrapper() + .eq(AppPolicyEntity::getAppCode, appCode).last("LIMIT 1")); + } + + /** + * 双人复核阈值:应用级策略优先,缺失时回落到全局参数。 + */ + public long thresholdOf(String appCode) { + AppPolicyEntity policy = findPolicy(appCode); + if (policy != null && policy.getDualControlThresholdCent() != null) { + return policy.getDualControlThresholdCent(); + } + return configService.getNumber("review.threshold_cent", 500000); + } + + @Transactional + public PricingItemResponse updatePricing(String appCode, PricingUpdateRequest request, AdminEntity current, + HttpServletRequest httpRequest) { + AppEntity app = requireApp(appCode); + AppPricingEntity item = requirePricing(appCode); + totpVerifier.verify(current, request.totp(), "PRICING_UPDATE", "修改兑率", httpRequest); + long rate = request.pointsPerYuan() == null ? 0 : request.pointsPerYuan(); + if (rate < 1 || rate > 1000000) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "兑率需为正整数(1 元可兑换的点数)"); + } + int enabled = request.enabled() == null ? item.getEnabled() + : (Integer.valueOf(1).equals(request.enabled()) ? 1 : 0); + pricingMapper.update(null, new LambdaUpdateWrapper() + .eq(AppPricingEntity::getId, item.getId()) + .set(AppPricingEntity::getPointsPerYuan, rate) + .set(AppPricingEntity::getEnabled, enabled) + .set(AppPricingEntity::getUpdateBy, current.getUsername()) + .set(AppPricingEntity::getUpdateTime, LocalDateTime.now().withNano(0))); + Map before = new LinkedHashMap<>(); + before.put("pointsPerYuan", item.getPointsPerYuan()); + Map after = new LinkedHashMap<>(); + after.put("pointsPerYuan", rate); + after.put("enabled", enabled); + adminAuditor.success(current, "PRICING_UPDATE", "修改兑率", "PRICING", app.getId(), + before, after, httpRequest); + return PricingItemResponse.from(requirePricing(appCode), app.getAppName()); + } + + @Transactional + public AppPolicyResponse updatePolicy(String appCode, PolicyUpdateRequest request, AdminEntity current, + HttpServletRequest httpRequest) { + AppEntity app = requireApp(appCode); + AppPolicyEntity item = findPolicy(appCode); + if (item == null) { + throw new BizException(ErrorCode.NOT_FOUND, "扣费策略不存在"); + } + totpVerifier.verify(current, request.totp(), "POLICY_UPDATE", "修改扣费策略", httpRequest); + long minCost = request.minCost() == null ? -1 : request.minCost(); + long maxPoints = request.maxPointsPerCharge() == null ? -1 : request.maxPointsPerCharge(); + long threshold = request.dualControlThresholdCent() == null ? -1 : request.dualControlThresholdCent(); + if (minCost < 0 || minCost > 1000000) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "保底消费必须为 0~1000000 的整数"); + } + if (maxPoints < Math.max(1, minCost) || maxPoints > 10000000) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "单次扣费上限不得小于保底消费"); + } + if (threshold < 0 || threshold > 100000000000L) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "双人复核阈值不合法"); + } + String strategy = "actual".equals(request.failedStrategy()) ? "actual" : "none"; + int vipExempt = request.vipExempt() == null ? item.getVipExempt() + : (Integer.valueOf(1).equals(request.vipExempt()) ? 1 : 0); + Map before = new LinkedHashMap<>(); + before.put("minCost", item.getMinCost()); + before.put("maxPointsPerCharge", item.getMaxPointsPerCharge()); + before.put("vipExempt", item.getVipExempt()); + policyMapper.update(null, new LambdaUpdateWrapper() + .eq(AppPolicyEntity::getId, item.getId()) + .set(AppPolicyEntity::getMinCost, minCost) + .set(AppPolicyEntity::getMaxPointsPerCharge, maxPoints) + .set(AppPolicyEntity::getVipExempt, vipExempt) + .set(AppPolicyEntity::getFailedStrategy, strategy) + .set(AppPolicyEntity::getDualControlThresholdCent, threshold) + .set(AppPolicyEntity::getUpdateBy, current.getUsername()) + .set(AppPolicyEntity::getUpdateTime, LocalDateTime.now().withNano(0))); + Map after = new LinkedHashMap<>(); + after.put("minCost", minCost); + after.put("maxPointsPerCharge", maxPoints); + after.put("dualControlThresholdCent", threshold); + adminAuditor.success(current, "POLICY_UPDATE", "修改扣费策略", "POLICY", app.getId(), + before, after, httpRequest); + return AppPolicyResponse.from(findPolicy(appCode), app.getAppName()); + } + + private AppEntity requireApp(String appCode) { + AppEntity app = appMapper.selectOne(new LambdaQueryWrapper() + .eq(AppEntity::getAppCode, appCode).last("LIMIT 1")); + if (app == null) { + throw new BizException(ErrorCode.NOT_FOUND, "接入应用不存在"); + } + return app; + } + + private Map appNames() { + return appMapper.selectList(null).stream() + .collect(Collectors.toMap(AppEntity::getAppCode, AppEntity::getAppName, (a, b) -> a)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/reconcile/controller/ReconcileController.java b/finance-server/src/main/java/com/gas/fin/reconcile/controller/ReconcileController.java new file mode 100644 index 0000000..363bac0 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/reconcile/controller/ReconcileController.java @@ -0,0 +1,48 @@ +package com.gas.fin.reconcile.controller; + +import com.gas.fin.common.api.R; +import com.gas.fin.common.security.AuthContext; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.security.RequirePermission; +import com.gas.fin.reconcile.dto.ReconcileReportResponse; +import com.gas.fin.reconcile.dto.ReconcileRunRequest; +import com.gas.fin.reconcile.service.ReconcileService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api/admin/reconcile") +public class ReconcileController { + + private final ReconcileService reconcileService; + + public ReconcileController(ReconcileService reconcileService) { + this.reconcileService = reconcileService; + } + + @GetMapping("/reports") + @RequirePermission(PermissionRegistry.VIEW) + public R> reports() { + return R.ok(reconcileService.list()); + } + + @GetMapping("/reports/{id}") + @RequirePermission(PermissionRegistry.VIEW) + public R detail(@PathVariable String id) { + return R.ok(reconcileService.detail(id)); + } + + @PostMapping("/run") + @RequirePermission(PermissionRegistry.RECONCILE_RUN) + public R run(@RequestBody ReconcileRunRequest request, + HttpServletRequest httpRequest) { + return R.ok(reconcileService.run(request, AuthContext.require(), httpRequest)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/reconcile/dto/ReconcileDiffResponse.java b/finance-server/src/main/java/com/gas/fin/reconcile/dto/ReconcileDiffResponse.java new file mode 100644 index 0000000..8beaa36 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/reconcile/dto/ReconcileDiffResponse.java @@ -0,0 +1,5 @@ +package com.gas.fin.reconcile.dto; + +public record ReconcileDiffResponse(String level, String target, long expected, long actual, long diff, + String reason) { +} diff --git a/finance-server/src/main/java/com/gas/fin/reconcile/dto/ReconcileReportResponse.java b/finance-server/src/main/java/com/gas/fin/reconcile/dto/ReconcileReportResponse.java new file mode 100644 index 0000000..7a2e851 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/reconcile/dto/ReconcileReportResponse.java @@ -0,0 +1,27 @@ +package com.gas.fin.reconcile.dto; + +import com.gas.fin.reconcile.entity.ReconcileReportEntity; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +public record ReconcileReportResponse(String id, String appCode, String appName, LocalDate windowStart, + LocalDate windowEnd, LocalDateTime snapshotAt, long cashInCent, + long cashPaidOrderCent, long cashOutCent, long cashRefundedCent, + long cashDiffCent, long walletSum, long computedSum, long pointsDiff, + int brokenChains, int diffCount, String status, String createdBy, + LocalDateTime createTime, List details) { + + public static ReconcileReportResponse from(ReconcileReportEntity entity, String appName, + List details) { + return new ReconcileReportResponse(entity.getId(), entity.getAppCode(), + appName == null ? entity.getAppCode() : appName, + entity.getWindowStart(), entity.getWindowEnd(), entity.getSnapshotAt(), + entity.getCashInCent(), entity.getCashPaidOrderCent(), entity.getCashOutCent(), + entity.getCashRefundedCent(), entity.getCashDiffCent(), entity.getWalletSum(), + entity.getComputedSum(), entity.getPointsDiff(), entity.getBrokenChains(), + entity.getDiffCount(), entity.getStatus(), entity.getCreatedBy(), + entity.getCreateTime(), details); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/reconcile/dto/ReconcileRunRequest.java b/finance-server/src/main/java/com/gas/fin/reconcile/dto/ReconcileRunRequest.java new file mode 100644 index 0000000..0951339 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/reconcile/dto/ReconcileRunRequest.java @@ -0,0 +1,4 @@ +package com.gas.fin.reconcile.dto; + +public record ReconcileRunRequest(String appCode, String windowStart, String windowEnd) { +} diff --git a/finance-server/src/main/java/com/gas/fin/reconcile/entity/ReconcileDiffEntity.java b/finance-server/src/main/java/com/gas/fin/reconcile/entity/ReconcileDiffEntity.java new file mode 100644 index 0000000..5a199b0 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/reconcile/entity/ReconcileDiffEntity.java @@ -0,0 +1,25 @@ +package com.gas.fin.reconcile.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_reconcile_diff") +public class ReconcileDiffEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String reportId; + private String level; + private String target; + private Long expected; + private Long actual; + private Long diff; + private String reason; + private LocalDateTime createTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/reconcile/entity/ReconcileReportEntity.java b/finance-server/src/main/java/com/gas/fin/reconcile/entity/ReconcileReportEntity.java new file mode 100644 index 0000000..038de92 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/reconcile/entity/ReconcileReportEntity.java @@ -0,0 +1,35 @@ +package com.gas.fin.reconcile.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Data +@TableName("fin_reconcile_report") +public class ReconcileReportEntity { + + @TableId(value = "id", type = IdType.INPUT) + private String id; + + private String appCode; + private LocalDate windowStart; + private LocalDate windowEnd; + private LocalDateTime snapshotAt; + private Long cashInCent; + private Long cashPaidOrderCent; + private Long cashOutCent; + private Long cashRefundedCent; + private Long cashDiffCent; + private Long walletSum; + private Long computedSum; + private Long pointsDiff; + private Integer brokenChains; + private Integer diffCount; + private String status; + private String createdBy; + private LocalDateTime createTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/reconcile/mapper/ReconcileDiffMapper.java b/finance-server/src/main/java/com/gas/fin/reconcile/mapper/ReconcileDiffMapper.java new file mode 100644 index 0000000..c51b75d --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/reconcile/mapper/ReconcileDiffMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.reconcile.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.reconcile.entity.ReconcileDiffEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface ReconcileDiffMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/reconcile/mapper/ReconcileReportMapper.java b/finance-server/src/main/java/com/gas/fin/reconcile/mapper/ReconcileReportMapper.java new file mode 100644 index 0000000..051c9d8 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/reconcile/mapper/ReconcileReportMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.reconcile.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.reconcile.entity.ReconcileReportEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface ReconcileReportMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/reconcile/service/ReconcileService.java b/finance-server/src/main/java/com/gas/fin/reconcile/service/ReconcileService.java new file mode 100644 index 0000000..d111a7b --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/reconcile/service/ReconcileService.java @@ -0,0 +1,265 @@ +package com.gas.fin.reconcile.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.gas.fin.account.entity.AccountEntity; +import com.gas.fin.account.mapper.AccountMapper; +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.app.entity.AppEntity; +import com.gas.fin.app.mapper.AppMapper; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.security.AdminAuditor; +import com.gas.fin.order.entity.CashLedgerEntity; +import com.gas.fin.order.entity.OrderEntity; +import com.gas.fin.order.mapper.CashLedgerMapper; +import com.gas.fin.order.mapper.OrderMapper; +import com.gas.fin.reconcile.dto.ReconcileDiffResponse; +import com.gas.fin.reconcile.dto.ReconcileReportResponse; +import com.gas.fin.reconcile.dto.ReconcileRunRequest; +import com.gas.fin.reconcile.entity.ReconcileDiffEntity; +import com.gas.fin.reconcile.entity.ReconcileReportEntity; +import com.gas.fin.reconcile.mapper.ReconcileDiffMapper; +import com.gas.fin.reconcile.mapper.ReconcileReportMapper; +import com.gas.fin.refund.entity.RefundEntity; +import com.gas.fin.refund.mapper.RefundMapper; +import com.gas.fin.transaction.entity.TransactionEntity; +import com.gas.fin.transaction.mapper.TransactionMapper; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 对账:现金侧与点数侧差异计算,报告与差异明细落库。 + */ +@Service +public class ReconcileService { + + private final ReconcileReportMapper reportMapper; + private final ReconcileDiffMapper diffMapper; + private final AppMapper appMapper; + private final CashLedgerMapper cashLedgerMapper; + private final OrderMapper orderMapper; + private final RefundMapper refundMapper; + private final AccountMapper accountMapper; + private final TransactionMapper transactionMapper; + private final AdminAuditor adminAuditor; + + public ReconcileService(ReconcileReportMapper reportMapper, ReconcileDiffMapper diffMapper, + AppMapper appMapper, CashLedgerMapper cashLedgerMapper, OrderMapper orderMapper, + RefundMapper refundMapper, AccountMapper accountMapper, + TransactionMapper transactionMapper, AdminAuditor adminAuditor) { + this.reportMapper = reportMapper; + this.diffMapper = diffMapper; + this.appMapper = appMapper; + this.cashLedgerMapper = cashLedgerMapper; + this.orderMapper = orderMapper; + this.refundMapper = refundMapper; + this.accountMapper = accountMapper; + this.transactionMapper = transactionMapper; + this.adminAuditor = adminAuditor; + } + + public List list() { + Map names = appNames(); + return reportMapper.selectList(new LambdaQueryWrapper() + .orderByDesc(ReconcileReportEntity::getCreateTime) + .orderByDesc(ReconcileReportEntity::getId)) + .stream().map(item -> ReconcileReportResponse.from(item, + names.get(item.getAppCode()), List.of())) + .toList(); + } + + public ReconcileReportResponse detail(String id) { + ReconcileReportEntity report = reportMapper.selectById(id); + if (report == null) { + throw new BizException(ErrorCode.NOT_FOUND, "对账报告不存在"); + } + List details = diffMapper.selectList( + new LambdaQueryWrapper() + .eq(ReconcileDiffEntity::getReportId, id) + .orderByAsc(ReconcileDiffEntity::getId)) + .stream() + .map(item -> new ReconcileDiffResponse(item.getLevel(), item.getTarget(), item.getExpected(), + item.getActual(), item.getDiff(), item.getReason())) + .toList(); + return ReconcileReportResponse.from(report, appNames().get(report.getAppCode()), details); + } + + @Transactional + public ReconcileReportResponse run(ReconcileRunRequest request, AdminEntity current, + HttpServletRequest httpRequest) { + String appCode = request.appCode() == null ? "" : request.appCode().trim(); + if (appCode.isEmpty()) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "请选择接入应用"); + } + AppEntity app = appMapper.selectOne(new LambdaQueryWrapper() + .eq(AppEntity::getAppCode, appCode).last("LIMIT 1")); + if (app == null) { + throw new BizException(ErrorCode.NOT_FOUND, "接入应用不存在"); + } + LocalDate windowStart = parseDate(request.windowStart()); + LocalDate windowEnd = parseDate(request.windowEnd()); + if (windowStart.isAfter(windowEnd)) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "开始日期不能晚于结束日期"); + } + if (windowEnd.isAfter(LocalDate.now())) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "对账结束日期不能晚于今天"); + } + if (windowEnd.isAfter(windowStart.plusDays(365))) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "单次对账窗口不得超过 366 天,请拆分批次执行"); + } + + LocalDateTime startTime = windowStart.atStartOfDay(); + LocalDateTime endTime = windowEnd.atTime(23, 59, 59); + + long cashInCent = cashLedgerMapper.selectList(new LambdaQueryWrapper() + .eq(CashLedgerEntity::getAppCode, appCode) + .eq(CashLedgerEntity::getDirection, "IN") + .ge(CashLedgerEntity::getReceivedAt, startTime) + .le(CashLedgerEntity::getReceivedAt, endTime)) + .stream().mapToLong(CashLedgerEntity::getAmountCent).sum(); + long cashOutCent = cashLedgerMapper.selectList(new LambdaQueryWrapper() + .eq(CashLedgerEntity::getAppCode, appCode) + .eq(CashLedgerEntity::getDirection, "OUT") + .ge(CashLedgerEntity::getReceivedAt, startTime) + .le(CashLedgerEntity::getReceivedAt, endTime)) + .stream().mapToLong(CashLedgerEntity::getAmountCent).sum(); + long cashPaidOrderCent = orderMapper.selectList(new LambdaQueryWrapper() + .eq(OrderEntity::getAppCode, appCode) + .in(OrderEntity::getStatus, List.of("PAID", "REFUNDED")) + .ge(OrderEntity::getPaidAt, startTime) + .le(OrderEntity::getPaidAt, endTime)) + .stream().mapToLong(OrderEntity::getAmountCent).sum(); + long cashRefundedCent = refundMapper.selectList(new LambdaQueryWrapper() + .eq(RefundEntity::getAppCode, appCode) + .eq(RefundEntity::getStatus, "COMPLETED") + .ge(RefundEntity::getUpdateTime, startTime) + .le(RefundEntity::getUpdateTime, endTime)) + .stream().mapToLong(RefundEntity::getAmountCent).sum(); + + List accounts = accountMapper.selectList(new LambdaQueryWrapper() + .eq(AccountEntity::getAppCode, appCode)); + long walletSum = accounts.stream().mapToLong(AccountEntity::getBalance).sum(); + Map> txByUser = transactionMapper.selectList( + new LambdaQueryWrapper() + .eq(TransactionEntity::getAppCode, appCode) + .orderByAsc(TransactionEntity::getCreateTime) + .orderByAsc(TransactionEntity::getId)) + .stream().collect(Collectors.groupingBy(TransactionEntity::getBusinessUserId)); + long computedSum = 0; + int brokenChains = 0; + for (AccountEntity account : accounts) { + long expected = 0; + boolean broken = false; + for (TransactionEntity tx : txByUser.getOrDefault(account.getBusinessUserId(), List.of())) { + if (tx.getBalanceBefore() != expected) { + broken = true; + } + switch (tx.getType()) { + case "RECHARGE", "REFUND_IN" -> expected += tx.getAmount(); + case "CONSUME", "REFUND_OUT" -> expected -= tx.getAmount(); + case "ADJUST" -> expected += tx.getBalanceAfter() - tx.getBalanceBefore(); + default -> { + } + } + } + computedSum += expected; + if (broken) { + brokenChains++; + } + } + + long cashDiffCent = cashInCent - cashPaidOrderCent - (cashOutCent - cashRefundedCent); + long pointsDiff = walletSum - computedSum; + List details = new ArrayList<>(); + if (pointsDiff != 0) { + details.add(new ReconcileDiffResponse("APP", appCode, computedSum, walletSum, pointsDiff, + "流水累计与钱包余额不一致,需人工核查是否存在漏记流水")); + } + if (brokenChains > 0) { + details.add(new ReconcileDiffResponse("APP", appCode, 0, brokenChains, brokenChains, + brokenChains + " 个账户流水前后余额断链(疑似篡改或漏记)")); + } + + LocalDateTime now = LocalDateTime.now().withNano(0); + ReconcileReportEntity report = new ReconcileReportEntity(); + report.setId(nextReportId(windowEnd)); + report.setAppCode(appCode); + report.setWindowStart(windowStart); + report.setWindowEnd(windowEnd); + report.setSnapshotAt(now); + report.setCashInCent(cashInCent); + report.setCashPaidOrderCent(cashPaidOrderCent); + report.setCashOutCent(cashOutCent); + report.setCashRefundedCent(cashRefundedCent); + report.setCashDiffCent(cashDiffCent); + report.setWalletSum(walletSum); + report.setComputedSum(computedSum); + report.setPointsDiff(pointsDiff); + report.setBrokenChains(brokenChains); + report.setDiffCount(details.size()); + report.setStatus(details.isEmpty() ? "BALANCED" : "DIFF"); + report.setCreatedBy(current.getUsername()); + report.setCreateTime(now); + reportMapper.insert(report); + for (ReconcileDiffResponse item : details) { + ReconcileDiffEntity entity = new ReconcileDiffEntity(); + entity.setReportId(report.getId()); + entity.setLevel(item.level()); + entity.setTarget(item.target()); + entity.setExpected(item.expected()); + entity.setActual(item.actual()); + entity.setDiff(item.diff()); + entity.setReason(item.reason()); + entity.setCreateTime(now); + diffMapper.insert(entity); + } + + Map after = new LinkedHashMap<>(); + after.put("appCode", appCode); + after.put("windowStart", windowStart.toString()); + after.put("windowEnd", windowEnd.toString()); + after.put("status", report.getStatus()); + adminAuditor.success(current, "RECONCILE_RUN", "执行对账", "RECONCILE", null, null, after, httpRequest); + return ReconcileReportResponse.from(report, app.getAppName(), details); + } + + private String nextReportId(LocalDate windowEnd) { + String prefix = "RC" + windowEnd.toString().replace("-", ""); + Long count = reportMapper.selectCount(new LambdaQueryWrapper() + .likeRight(ReconcileReportEntity::getId, prefix)); + long seq = (count == null ? 0 : count) + 1; + String id = prefix + String.format("%03d", seq); + while (reportMapper.selectById(id) != null) { + seq++; + id = prefix + String.format("%03d", seq); + } + return id; + } + + private LocalDate parseDate(String value) { + String text = value == null ? "" : value.trim(); + if (!text.matches("^\\d{4}-\\d{2}-\\d{2}$")) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "对账窗口格式不合法"); + } + try { + return LocalDate.parse(text); + } catch (DateTimeParseException ex) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "对账窗口格式不合法"); + } + } + + private Map appNames() { + return appMapper.selectList(null).stream() + .collect(Collectors.toMap(AppEntity::getAppCode, AppEntity::getAppName, (a, b) -> a)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/refund/controller/RefundController.java b/finance-server/src/main/java/com/gas/fin/refund/controller/RefundController.java new file mode 100644 index 0000000..ada2dd7 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/refund/controller/RefundController.java @@ -0,0 +1,58 @@ +package com.gas.fin.refund.controller; + +import com.gas.fin.common.api.PageResult; +import com.gas.fin.common.api.R; +import com.gas.fin.common.security.AuthContext; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.security.RequirePermission; +import com.gas.fin.refund.dto.RefundCreateRequest; +import com.gas.fin.refund.dto.RefundInfoResponse; +import com.gas.fin.refund.dto.RefundReviewRequest; +import com.gas.fin.refund.service.RefundService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/admin/refunds") +public class RefundController { + + private final RefundService refundService; + + public RefundController(RefundService refundService) { + this.refundService = refundService; + } + + @GetMapping + @RequirePermission(PermissionRegistry.VIEW) + public R> list( + @RequestParam(defaultValue = "1") long page, + @RequestParam(defaultValue = "20") long pageSize, + @RequestParam(required = false) String appCode, + @RequestParam(required = false) String status, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) String from, + @RequestParam(required = false) String to) { + return R.ok(refundService.page(page, pageSize, appCode, status, keyword, from, to)); + } + + @PostMapping + @RequirePermission(PermissionRegistry.REFUND_CREATE) + public R create(@RequestBody RefundCreateRequest request, + HttpServletRequest httpRequest) { + return R.ok(refundService.create(request, AuthContext.require(), httpRequest)); + } + + @PostMapping("/{id}/review") + @RequirePermission(PermissionRegistry.REFUND_REVIEW) + public R review(@PathVariable Long id, + @RequestBody RefundReviewRequest request, + HttpServletRequest httpRequest) { + return R.ok(refundService.review(id, request, AuthContext.require(), httpRequest)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/refund/dto/RefundCreateRequest.java b/finance-server/src/main/java/com/gas/fin/refund/dto/RefundCreateRequest.java new file mode 100644 index 0000000..f523e47 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/refund/dto/RefundCreateRequest.java @@ -0,0 +1,5 @@ +package com.gas.fin.refund.dto; + +public record RefundCreateRequest(Long orderId, Long amountCent, String voucherNo, String reason, + String idempotencyKey, String totp) { +} diff --git a/finance-server/src/main/java/com/gas/fin/refund/dto/RefundInfoResponse.java b/finance-server/src/main/java/com/gas/fin/refund/dto/RefundInfoResponse.java new file mode 100644 index 0000000..5ca8d37 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/refund/dto/RefundInfoResponse.java @@ -0,0 +1,52 @@ +package com.gas.fin.refund.dto; + +import com.gas.fin.refund.entity.RefundEntity; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class RefundInfoResponse { + + private Long id; + private String appCode; + private String appName; + private String businessUserId; + private String usernameSnapshot; + private Long orderId; + private String outTradeNo; + private Long amountCent; + private Long pointsDeducted; + private String status; + private Long operatorAdminId; + private String operatorAdminName; + private Long reviewerAdminId; + private String reviewerAdminName; + private String voucherNo; + private String remark; + private LocalDateTime createTime; + private LocalDateTime updateTime; + + public static RefundInfoResponse from(RefundEntity entity, String appName) { + RefundInfoResponse response = new RefundInfoResponse(); + response.setId(entity.getId()); + response.setAppCode(entity.getAppCode()); + response.setAppName(appName == null ? entity.getAppCode() : appName); + response.setBusinessUserId(entity.getBusinessUserId()); + response.setUsernameSnapshot(entity.getUsernameSnapshot()); + response.setOrderId(entity.getOrderId()); + response.setOutTradeNo(entity.getOutTradeNo()); + response.setAmountCent(entity.getAmountCent()); + response.setPointsDeducted(entity.getPointsDeducted() == null ? 0L : entity.getPointsDeducted()); + response.setStatus(entity.getStatus()); + response.setOperatorAdminId(entity.getOperatorAdminId()); + response.setOperatorAdminName(entity.getOperatorAdminName()); + response.setReviewerAdminId(entity.getReviewerAdminId()); + response.setReviewerAdminName(entity.getReviewerAdminName()); + response.setVoucherNo(entity.getVoucherNo() == null ? "" : entity.getVoucherNo()); + response.setRemark(entity.getRemark() == null ? "" : entity.getRemark()); + response.setCreateTime(entity.getCreateTime()); + response.setUpdateTime(entity.getUpdateTime()); + return response; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/refund/dto/RefundReviewRequest.java b/finance-server/src/main/java/com/gas/fin/refund/dto/RefundReviewRequest.java new file mode 100644 index 0000000..a781983 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/refund/dto/RefundReviewRequest.java @@ -0,0 +1,4 @@ +package com.gas.fin.refund.dto; + +public record RefundReviewRequest(String action, String voucherNo, String reason, String totp) { +} diff --git a/finance-server/src/main/java/com/gas/fin/refund/entity/RefundEntity.java b/finance-server/src/main/java/com/gas/fin/refund/entity/RefundEntity.java new file mode 100644 index 0000000..4bb2ebc --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/refund/entity/RefundEntity.java @@ -0,0 +1,35 @@ +package com.gas.fin.refund.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_refund") +public class RefundEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String appCode; + private String businessUserId; + private String usernameSnapshot; + private Long orderId; + private String outTradeNo; + private Long amountCent; + private Long pointsDeducted; + private String status; + private Long operatorAdminId; + private String operatorAdminName; + private Long reviewerAdminId; + private String reviewerAdminName; + private String voucherNo; + private String remark; + private String idempotencyKey; + private LocalDateTime reviewTime; + private LocalDateTime createTime; + private LocalDateTime updateTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/refund/mapper/RefundMapper.java b/finance-server/src/main/java/com/gas/fin/refund/mapper/RefundMapper.java new file mode 100644 index 0000000..18f9c0d --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/refund/mapper/RefundMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.refund.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.refund.entity.RefundEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface RefundMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/refund/service/RefundService.java b/finance-server/src/main/java/com/gas/fin/refund/service/RefundService.java new file mode 100644 index 0000000..9c8ff05 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/refund/service/RefundService.java @@ -0,0 +1,418 @@ +package com.gas.fin.refund.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.gas.fin.account.entity.AccountEntity; +import com.gas.fin.account.mapper.AccountMapper; +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.app.entity.AppEntity; +import com.gas.fin.app.mapper.AppMapper; +import com.gas.fin.common.api.PageResult; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.security.AdminAuditor; +import com.gas.fin.common.security.TotpVerifier; +import com.gas.fin.common.util.HashUtils; +import com.gas.fin.common.web.QueryUtils; +import com.gas.fin.order.entity.CashLedgerEntity; +import com.gas.fin.order.entity.OrderEntity; +import com.gas.fin.order.mapper.CashLedgerMapper; +import com.gas.fin.order.mapper.OrderMapper; +import com.gas.fin.pricing.service.PricingService; +import com.gas.fin.refund.dto.RefundCreateRequest; +import com.gas.fin.refund.dto.RefundInfoResponse; +import com.gas.fin.refund.dto.RefundReviewRequest; +import com.gas.fin.refund.entity.RefundEntity; +import com.gas.fin.refund.mapper.RefundMapper; +import com.gas.fin.transaction.entity.TransactionEntity; +import com.gas.fin.transaction.mapper.TransactionMapper; +import com.gas.fin.vip.entity.VipHolderEntity; +import com.gas.fin.vip.mapper.VipHolderMapper; +import com.gas.fin.webhook.service.WebhookService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 现金退款:发起(小金额自动出账)、双人复核、扣回点数与订单状态回写。 + */ +@Service +public class RefundService { + + private final RefundMapper refundMapper; + private final OrderMapper orderMapper; + private final CashLedgerMapper cashLedgerMapper; + private final AccountMapper accountMapper; + private final TransactionMapper transactionMapper; + private final VipHolderMapper vipHolderMapper; + private final AppMapper appMapper; + private final PricingService pricingService; + private final WebhookService webhookService; + private final TotpVerifier totpVerifier; + private final AdminAuditor adminAuditor; + private final ObjectMapper objectMapper; + + public RefundService(RefundMapper refundMapper, OrderMapper orderMapper, CashLedgerMapper cashLedgerMapper, + AccountMapper accountMapper, TransactionMapper transactionMapper, + VipHolderMapper vipHolderMapper, AppMapper appMapper, PricingService pricingService, + WebhookService webhookService, TotpVerifier totpVerifier, AdminAuditor adminAuditor, + ObjectMapper objectMapper) { + this.refundMapper = refundMapper; + this.orderMapper = orderMapper; + this.cashLedgerMapper = cashLedgerMapper; + this.accountMapper = accountMapper; + this.transactionMapper = transactionMapper; + this.vipHolderMapper = vipHolderMapper; + this.appMapper = appMapper; + this.pricingService = pricingService; + this.webhookService = webhookService; + this.totpVerifier = totpVerifier; + this.adminAuditor = adminAuditor; + this.objectMapper = objectMapper; + } + + public PageResult page(long page, long pageSize, String appCode, String status, + String keyword, String from, String to) { + QueryUtils.checkPage(page, pageSize); + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (appCode != null && !appCode.isBlank()) { + wrapper.eq(RefundEntity::getAppCode, appCode.trim()); + } + if (status != null && !status.isBlank()) { + wrapper.eq(RefundEntity::getStatus, status.trim()); + } + if (keyword != null && !keyword.isBlank()) { + String value = keyword.trim(); + wrapper.and(w -> w.like(RefundEntity::getOutTradeNo, value) + .or().like(RefundEntity::getVoucherNo, value)); + } + LocalDateTime fromTime = QueryUtils.parseFrom(from); + LocalDateTime toTime = QueryUtils.parseTo(to); + if (fromTime != null) { + wrapper.ge(RefundEntity::getCreateTime, fromTime); + } + if (toTime != null) { + wrapper.le(RefundEntity::getCreateTime, toTime); + } + wrapper.orderByDesc(RefundEntity::getCreateTime).orderByDesc(RefundEntity::getId); + Page result = refundMapper.selectPage(new Page<>(page, pageSize), wrapper); + Map names = appNames(); + return PageResult.of(result.getRecords().stream() + .map(item -> RefundInfoResponse.from(item, names.get(item.getAppCode()))).toList(), + result.getTotal(), page, pageSize); + } + + @Transactional + public RefundInfoResponse create(RefundCreateRequest request, AdminEntity current, + HttpServletRequest httpRequest) { + if (request.orderId() == null) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "原订单不存在"); + } + OrderEntity order = orderMapper.selectById(request.orderId()); + if (order == null) { + throw new BizException(ErrorCode.NOT_FOUND, "原订单不存在"); + } + String idempotencyKey = QueryUtils.text(request.idempotencyKey()); + if (!idempotencyKey.matches("^[A-Za-z0-9:_-]{8,64}$")) { + throw new BizException(ErrorCode.IDEMPOTENT_CONFLICT, "缺少幂等键,请刷新页面后重试"); + } + RefundEntity existing = refundMapper.selectOne(new LambdaQueryWrapper() + .eq(RefundEntity::getAppCode, order.getAppCode()) + .eq(RefundEntity::getIdempotencyKey, idempotencyKey) + .last("LIMIT 1")); + if (existing != null) { + return RefundInfoResponse.from(existing, appNames().get(existing.getAppCode())); + } + totpVerifier.verify(current, request.totp(), "REFUND_CREATE", "发起现金退款", httpRequest); + long amountCent = request.amountCent() == null ? 0 : request.amountCent(); + if (amountCent <= 0) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "退款金额必须大于 0"); + } + String reason = QueryUtils.text(request.reason()); + if (reason.length() < 5 || reason.length() > 255) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "请填写退款原因(不少于 5 个字)"); + } + if (!"PAID".equals(order.getStatus()) && !"REFUNDED".equals(order.getStatus())) { + throw new BizException(ErrorCode.STATUS_CONFLICT, "仅已到账订单可以退款"); + } + if (!"offline".equals(order.getPayMethod())) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "二期在线支付退款链路未开放"); + } + long occupied = occupiedRefundSum(order.getId(), null, false); + if (amountCent > order.getAmountCent() - occupied) { + throw new BizException(ErrorCode.REFUND_EXCEEDED, "退款金额超出可退上限(含待复核退款)"); + } + long pointsDeducted = "vip".equals(order.getOrderType()) || order.getAmountCent() <= 0 ? 0 + : Math.round((double) amountCent * order.getPointsGained() / order.getAmountCent()); + if (pointsDeducted > 0) { + AccountEntity account = findAccount(order.getAppCode(), order.getBusinessUserId()); + if (account == null) { + throw new BizException(ErrorCode.NOT_FOUND, "钱包账户不存在"); + } + if (account.getBalance() < pointsDeducted) { + throw new BizException(ErrorCode.REFUND_BALANCE_INSUFFICIENT, + "用户已消耗部分点数,余额不足以扣回,请人工核算后部分退款"); + } + } + long threshold = pricingService.thresholdOf(order.getAppCode()); + boolean autoComplete = amountCent < threshold; + String voucherNo = QueryUtils.text(request.voucherNo()); + if (autoComplete && voucherNo.length() < 6) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "现金退款必须登记银行凭证号(不少于 6 位)"); + } + if (!voucherNo.isEmpty() && voucherNo.length() < 6) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "银行凭证号不少于 6 位"); + } + + LocalDateTime now = LocalDateTime.now().withNano(0); + RefundEntity refund = new RefundEntity(); + refund.setAppCode(order.getAppCode()); + refund.setBusinessUserId(order.getBusinessUserId()); + refund.setUsernameSnapshot(order.getUsernameSnapshot()); + refund.setOrderId(order.getId()); + refund.setOutTradeNo(order.getOutTradeNo()); + refund.setAmountCent(amountCent); + refund.setPointsDeducted(pointsDeducted); + refund.setStatus(autoComplete ? "COMPLETED" : "PENDING"); + refund.setOperatorAdminId(current.getId()); + refund.setOperatorAdminName(current.getUsername()); + refund.setVoucherNo(voucherNo.isEmpty() ? null : voucherNo); + refund.setRemark(reason); + refund.setIdempotencyKey(idempotencyKey); + refund.setCreateTime(now); + refund.setUpdateTime(now); + if (autoComplete) { + refund.setReviewerAdminId(current.getId()); + refund.setReviewerAdminName(current.getUsername()); + refund.setReviewTime(now); + } + refundMapper.insert(refund); + if (autoComplete) { + applyRefund(refund, order, current.getUsername(), now); + } + + Map after = new LinkedHashMap<>(); + after.put("amountCent", amountCent); + after.put("pointsDeducted", pointsDeducted); + after.put("status", refund.getStatus()); + after.put("orderId", order.getId()); + adminAuditor.success(current, "REFUND_CREATE", "发起现金退款", "REFUND", refund.getId(), + null, after, httpRequest); + return RefundInfoResponse.from(refundMapper.selectById(refund.getId()), + appNames().get(order.getAppCode())); + } + + @Transactional + public RefundInfoResponse review(Long id, RefundReviewRequest request, AdminEntity current, + HttpServletRequest httpRequest) { + RefundEntity refund = refundMapper.selectById(id); + if (refund == null) { + throw new BizException(ErrorCode.NOT_FOUND, "退款单不存在"); + } + if (!"PENDING".equals(refund.getStatus())) { + throw new BizException(ErrorCode.STATUS_CONFLICT, "退款单已处理,请刷新后重试"); + } + if (refund.getOperatorAdminId().equals(current.getId())) { + throw new BizException(ErrorCode.INVALID_APPROVER, "退款发起人不得复核自己发起的退款单"); + } + totpVerifier.verify(current, request.totp(), "REFUND_REVIEW", "复核现金退款", httpRequest); + String action = QueryUtils.text(request.action()); + if (!"approve".equals(action) && !"reject".equals(action)) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "复核动作不合法"); + } + LocalDateTime now = LocalDateTime.now().withNano(0); + if ("reject".equals(action)) { + String reason = QueryUtils.text(request.reason()); + if (reason.length() < 5 || reason.length() > 255) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "请填写驳回原因(不少于 5 个字)"); + } + int rows = refundMapper.update(null, new LambdaUpdateWrapper() + .eq(RefundEntity::getId, id) + .eq(RefundEntity::getStatus, "PENDING") + .set(RefundEntity::getStatus, "REJECTED") + .set(RefundEntity::getReviewerAdminId, current.getId()) + .set(RefundEntity::getReviewerAdminName, current.getUsername()) + .set(RefundEntity::getRemark, reason) + .set(RefundEntity::getReviewTime, now) + .set(RefundEntity::getUpdateTime, now)); + if (rows == 0) { + throw new BizException(ErrorCode.STATUS_CONFLICT, "退款单已处理,请刷新后重试"); + } + } else { + String voucherNo = QueryUtils.text(request.voucherNo()); + if (voucherNo.length() < 6 || voucherNo.length() > 64) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "现金退款必须登记银行凭证号"); + } + int rows = refundMapper.update(null, new LambdaUpdateWrapper() + .eq(RefundEntity::getId, id) + .eq(RefundEntity::getStatus, "PENDING") + .set(RefundEntity::getStatus, "COMPLETED") + .set(RefundEntity::getReviewerAdminId, current.getId()) + .set(RefundEntity::getReviewerAdminName, current.getUsername()) + .set(RefundEntity::getVoucherNo, voucherNo) + .set(RefundEntity::getReviewTime, now) + .set(RefundEntity::getUpdateTime, now)); + if (rows == 0) { + throw new BizException(ErrorCode.STATUS_CONFLICT, "退款单已处理,请刷新后重试"); + } + refund.setVoucherNo(voucherNo); + OrderEntity order = orderMapper.selectById(refund.getOrderId()); + if (order == null) { + throw new BizException(ErrorCode.NOT_FOUND, "原订单不存在"); + } + applyRefund(refund, order, current.getUsername(), now); + } + Map after = new LinkedHashMap<>(); + after.put("status", "reject".equals(action) ? "REJECTED" : "COMPLETED"); + after.put("voucherNo", request.voucherNo()); + adminAuditor.success(current, "REFUND_REVIEW", + "approve".equals(action) ? "复核通过现金退款" : "驳回现金退款", + "REFUND", id, Map.of("status", "PENDING"), after, httpRequest); + return RefundInfoResponse.from(refundMapper.selectById(id), appNames().get(refund.getAppCode())); + } + + private void applyRefund(RefundEntity refund, OrderEntity order, String operator, LocalDateTime now) { + if (refund.getPointsDeducted() > 0) { + AccountEntity account = findAccount(refund.getAppCode(), refund.getBusinessUserId()); + if (account == null) { + throw new BizException(ErrorCode.NOT_FOUND, "钱包账户不存在"); + } + if (account.getBalance() < refund.getPointsDeducted()) { + throw new BizException(ErrorCode.REFUND_BALANCE_INSUFFICIENT, "余额不足以扣回点数,退款无法生效"); + } + long before = account.getBalance(); + long after = before - refund.getPointsDeducted(); + int version = account.getVersionNo() == null ? 0 : account.getVersionNo(); + int rows = accountMapper.update(null, new LambdaUpdateWrapper() + .eq(AccountEntity::getId, account.getId()) + .eq(AccountEntity::getVersionNo, version) + .set(AccountEntity::getBalance, after) + .set(AccountEntity::getVersionNo, version + 1) + .set(AccountEntity::getUpdateTime, now)); + if (rows == 0) { + throw new BizException(ErrorCode.CONCURRENT_CONFLICT); + } + TransactionEntity tx = new TransactionEntity(); + tx.setAppCode(refund.getAppCode()); + tx.setBusinessUserId(refund.getBusinessUserId()); + tx.setUsernameSnapshot(refund.getUsernameSnapshot()); + tx.setType("REFUND_OUT"); + tx.setAmount(refund.getPointsDeducted()); + tx.setBalanceBefore(before); + tx.setBalanceAfter(after); + tx.setBusinessRefId(refund.getOutTradeNo()); + tx.setIdempotencyKey("refund:" + refund.getId()); + tx.setOrderId(order.getId()); + tx.setOutTradeNo(order.getOutTradeNo()); + tx.setRefundOfId(refund.getId()); + tx.setRefundedPoints(0L); + tx.setOperatorAdminId(refund.getOperatorAdminId()); + tx.setOperatorAdminName(operator); + tx.setRemark("现金退款扣回点数"); + tx.setCreateTime(now); + transactionMapper.insert(tx); + } + + CashLedgerEntity cash = new CashLedgerEntity(); + cash.setAppCode(refund.getAppCode()); + cash.setOrderId(order.getId()); + cash.setRefundId(refund.getId()); + cash.setDirection("OUT"); + cash.setAmountCent(refund.getAmountCent()); + cash.setReceivedAt(now); + cash.setVoucherNo(refund.getVoucherNo()); + cash.setOperatorAdminId(refund.getOperatorAdminId()); + cash.setOperatorAdminName(refund.getOperatorAdminName()); + cash.setRemark("现金退款"); + cash.setCreateTime(now); + cashLedgerMapper.insert(cash); + + long occupied = occupiedRefundSum(order.getId(), refund.getId(), false) + refund.getAmountCent(); + long completed = completedRefundSum(order.getId(), refund.getId()) + refund.getAmountCent(); + String newStatus = completed >= order.getAmountCent() ? "REFUNDED" : "PAID"; + orderMapper.update(null, new LambdaUpdateWrapper() + .eq(OrderEntity::getId, order.getId()) + .set(OrderEntity::getRefundedAmountCent, occupied) + .set(OrderEntity::getStatus, newStatus) + .set(OrderEntity::getUpdateTime, now)); + + if (completed >= order.getAmountCent() && "vip".equals(order.getOrderType())) { + expireVip(order); + } + + Map payload = new LinkedHashMap<>(); + payload.put("outTradeNo", refund.getOutTradeNo()); + payload.put("refundAmountCent", refund.getAmountCent()); + String eventId = "evt_" + HashUtils.sha256Hex("order.refunded|" + refund.getOutTradeNo() + "|" + + refund.getAmountCent()).substring(0, 20); + webhookService.enqueue(refund.getAppCode(), eventId, "order.refunded", toJson(payload)); + } + + private void expireVip(OrderEntity order) { + LocalDateTime now = LocalDateTime.now().withNano(0); + vipHolderMapper.update(null, new LambdaUpdateWrapper() + .eq(VipHolderEntity::getAppCode, order.getAppCode()) + .eq(VipHolderEntity::getBusinessUserId, order.getBusinessUserId()) + .set(VipHolderEntity::getVipUntil, now) + .set(VipHolderEntity::getUpdateTime, now)); + AccountEntity account = findAccount(order.getAppCode(), order.getBusinessUserId()); + if (account != null) { + accountMapper.update(null, new LambdaUpdateWrapper() + .eq(AccountEntity::getId, account.getId()) + .set(AccountEntity::getVipPlanCode, null) + .set(AccountEntity::getVipUntil, null) + .set(AccountEntity::getUpdateTime, now)); + } + } + + /** + * 已占用退款额度(含待复核),用于可退上限校验。 + */ + private long occupiedRefundSum(Long orderId, Long excludeId, boolean completedOnly) { + List list = refundMapper.selectList(new LambdaQueryWrapper() + .eq(RefundEntity::getOrderId, orderId)); + return list.stream() + .filter(item -> excludeId == null || !excludeId.equals(item.getId())) + .filter(item -> !"REJECTED".equals(item.getStatus())) + .filter(item -> !completedOnly || "COMPLETED".equals(item.getStatus())) + .mapToLong(RefundEntity::getAmountCent).sum(); + } + + private long completedRefundSum(Long orderId, Long excludeId) { + return refundMapper.selectList(new LambdaQueryWrapper() + .eq(RefundEntity::getOrderId, orderId) + .eq(RefundEntity::getStatus, "COMPLETED")) + .stream() + .filter(item -> excludeId == null || !excludeId.equals(item.getId())) + .mapToLong(RefundEntity::getAmountCent).sum(); + } + + private AccountEntity findAccount(String appCode, String businessUserId) { + return accountMapper.selectOne(new LambdaQueryWrapper() + .eq(AccountEntity::getAppCode, appCode) + .eq(AccountEntity::getBusinessUserId, businessUserId) + .last("LIMIT 1")); + } + + private String toJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (JsonProcessingException ex) { + throw new IllegalStateException("webhook payload 序列化失败", ex); + } + } + + private Map appNames() { + return appMapper.selectList(null).stream() + .collect(Collectors.toMap(AppEntity::getAppCode, AppEntity::getAppName, (a, b) -> a)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/setting/controller/ConfigController.java b/finance-server/src/main/java/com/gas/fin/setting/controller/ConfigController.java new file mode 100644 index 0000000..a0a1596 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/setting/controller/ConfigController.java @@ -0,0 +1,43 @@ +package com.gas.fin.setting.controller; + +import com.gas.fin.common.api.R; +import com.gas.fin.common.security.AuthContext; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.security.RequirePermission; +import com.gas.fin.setting.dto.ConfigItemResponse; +import com.gas.fin.setting.dto.ConfigUpdateRequest; +import com.gas.fin.setting.service.ConfigService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api/admin/configs") +public class ConfigController { + + private final ConfigService configService; + + public ConfigController(ConfigService configService) { + this.configService = configService; + } + + @GetMapping + @RequirePermission(PermissionRegistry.VIEW) + public R> list() { + return R.ok(configService.list()); + } + + @PutMapping("/{key}") + @RequirePermission(PermissionRegistry.CONFIG_EDIT) + public R update(@PathVariable String key, + @RequestBody ConfigUpdateRequest request, + HttpServletRequest httpRequest) { + return R.ok(configService.update(key, request, AuthContext.require(), httpRequest)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/setting/dto/ConfigItemResponse.java b/finance-server/src/main/java/com/gas/fin/setting/dto/ConfigItemResponse.java new file mode 100644 index 0000000..c277023 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/setting/dto/ConfigItemResponse.java @@ -0,0 +1,28 @@ +package com.gas.fin.setting.dto; + +import com.gas.fin.setting.entity.ConfigEntity; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class ConfigItemResponse { + + private String configKey; + private String configValue; + private String description; + private String risk; + private String updateBy; + private LocalDateTime updateTime; + + public static ConfigItemResponse from(ConfigEntity entity) { + ConfigItemResponse response = new ConfigItemResponse(); + response.setConfigKey(entity.getConfigKey()); + response.setConfigValue(entity.getConfigValue()); + response.setDescription(entity.getDescription()); + response.setRisk(entity.getRisk()); + response.setUpdateBy(entity.getUpdateBy()); + response.setUpdateTime(entity.getUpdateTime()); + return response; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/setting/dto/ConfigUpdateRequest.java b/finance-server/src/main/java/com/gas/fin/setting/dto/ConfigUpdateRequest.java new file mode 100644 index 0000000..1cf8c83 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/setting/dto/ConfigUpdateRequest.java @@ -0,0 +1,4 @@ +package com.gas.fin.setting.dto; + +public record ConfigUpdateRequest(String value, String reason, String totp) { +} diff --git a/finance-server/src/main/java/com/gas/fin/setting/entity/ConfigEntity.java b/finance-server/src/main/java/com/gas/fin/setting/entity/ConfigEntity.java new file mode 100644 index 0000000..21115f1 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/setting/entity/ConfigEntity.java @@ -0,0 +1,24 @@ +package com.gas.fin.setting.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_config") +public class ConfigEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String configKey; + private String configValue; + private String description; + private String risk; + private String updateBy; + private Integer versionNo; + private LocalDateTime updateTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/setting/mapper/ConfigMapper.java b/finance-server/src/main/java/com/gas/fin/setting/mapper/ConfigMapper.java new file mode 100644 index 0000000..6f53fd9 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/setting/mapper/ConfigMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.setting.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.setting.entity.ConfigEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface ConfigMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/setting/service/ConfigService.java b/finance-server/src/main/java/com/gas/fin/setting/service/ConfigService.java new file mode 100644 index 0000000..858880c --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/setting/service/ConfigService.java @@ -0,0 +1,115 @@ +package com.gas.fin.setting.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.security.AdminAuditor; +import com.gas.fin.common.security.TotpVerifier; +import com.gas.fin.setting.dto.ConfigItemResponse; +import com.gas.fin.setting.dto.ConfigUpdateRequest; +import com.gas.fin.setting.entity.ConfigEntity; +import com.gas.fin.setting.mapper.ConfigMapper; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 全局参数:读取供业务兜底,修改受 TOTP 与高危开关保护。 + */ +@Service +public class ConfigService { + + private final ConfigMapper configMapper; + private final AdminAuditor adminAuditor; + private final TotpVerifier totpVerifier; + + public ConfigService(ConfigMapper configMapper, AdminAuditor adminAuditor, TotpVerifier totpVerifier) { + this.configMapper = configMapper; + this.adminAuditor = adminAuditor; + this.totpVerifier = totpVerifier; + } + + public List list() { + return configMapper.selectList(new LambdaQueryWrapper() + .orderByAsc(ConfigEntity::getId)) + .stream().map(ConfigItemResponse::from).toList(); + } + + public ConfigEntity find(String key) { + return configMapper.selectOne(new LambdaQueryWrapper() + .eq(ConfigEntity::getConfigKey, key) + .last("LIMIT 1")); + } + + public long getNumber(String key, long fallback) { + ConfigEntity entity = find(key); + if (entity == null) { + return fallback; + } + try { + long value = Long.parseLong(entity.getConfigValue().trim()); + return value > 0 ? value : fallback; + } catch (Exception ex) { + return fallback; + } + } + + public String getText(String key, String fallback) { + ConfigEntity entity = find(key); + if (entity == null || entity.getConfigValue() == null || entity.getConfigValue().isBlank()) { + return fallback; + } + return entity.getConfigValue().trim(); + } + + @Transactional + public ConfigItemResponse update(String key, ConfigUpdateRequest request, AdminEntity current, + HttpServletRequest httpRequest) { + ConfigEntity item = find(key); + if (item == null) { + throw new BizException(ErrorCode.NOT_FOUND, "配置项不存在"); + } + totpVerifier.verify(current, request.totp(), "CONFIG_UPDATE", "修改全局参数", httpRequest); + String reason = trim(request.reason()); + if (reason.length() < 5) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "请填写变更原因(不少于 5 个字)"); + } + String value = trim(request.value()); + if (value.isEmpty() || value.length() > 255) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "配置值不能为空且不超过 255 字符"); + } + if ("pii.mask.enabled".equals(item.getConfigKey())) { + if (!"0".equals(value) && !"1".equals(value)) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "该开关仅允许 0 或 1"); + } + if ("0".equals(value)) { + throw new BizException(ErrorCode.PROTECTED_CONFIG); + } + } + String before = item.getConfigValue(); + configMapper.update(null, new LambdaUpdateWrapper() + .eq(ConfigEntity::getId, item.getId()) + .set(ConfigEntity::getConfigValue, value) + .set(ConfigEntity::getUpdateBy, current.getUsername()) + .set(ConfigEntity::getUpdateTime, LocalDateTime.now().withNano(0))); + Map beforeJson = new LinkedHashMap<>(); + beforeJson.put(item.getConfigKey(), before); + Map afterJson = new LinkedHashMap<>(); + afterJson.put(item.getConfigKey(), value); + afterJson.put("reason", reason); + adminAuditor.success(current, "CONFIG_UPDATE", "修改全局参数", "CONFIG", item.getId(), + beforeJson, afterJson, httpRequest); + return ConfigItemResponse.from(configMapper.selectById(item.getId())); + } + + private String trim(String value) { + return value == null ? "" : value.trim(); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/transaction/controller/TransactionController.java b/finance-server/src/main/java/com/gas/fin/transaction/controller/TransactionController.java new file mode 100644 index 0000000..8d93e3b --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/transaction/controller/TransactionController.java @@ -0,0 +1,53 @@ +package com.gas.fin.transaction.controller; + +import com.gas.fin.common.api.PageResult; +import com.gas.fin.common.api.R; +import com.gas.fin.common.security.AuthContext; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.security.RequirePermission; +import com.gas.fin.transaction.dto.TransactionInfoResponse; +import com.gas.fin.transaction.service.TransactionService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api/admin/transactions") +public class TransactionController { + + private final TransactionService transactionService; + + public TransactionController(TransactionService transactionService) { + this.transactionService = transactionService; + } + + @GetMapping + @RequirePermission(PermissionRegistry.VIEW) + public R> list( + @RequestParam(defaultValue = "1") long page, + @RequestParam(defaultValue = "20") long pageSize, + @RequestParam(required = false) String appCode, + @RequestParam(required = false) String type, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) String from, + @RequestParam(required = false) String to) { + return R.ok(transactionService.page(page, pageSize, appCode, type, keyword, from, to)); + } + + @GetMapping("/export") + @RequirePermission(PermissionRegistry.EXPORT) + public R> export( + @RequestParam(required = false) String appCode, + @RequestParam(required = false) String type, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) String from, + @RequestParam(required = false) String to, + HttpServletRequest httpRequest) { + return R.ok(transactionService.export(appCode, type, keyword, from, to, + AuthContext.require(), httpRequest)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/transaction/dto/TransactionInfoResponse.java b/finance-server/src/main/java/com/gas/fin/transaction/dto/TransactionInfoResponse.java new file mode 100644 index 0000000..e13d4f2 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/transaction/dto/TransactionInfoResponse.java @@ -0,0 +1,52 @@ +package com.gas.fin.transaction.dto; + +import com.gas.fin.transaction.entity.TransactionEntity; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class TransactionInfoResponse { + + private Long id; + private String appCode; + private String appName; + private String businessUserId; + private String usernameSnapshot; + private String type; + private Long amount; + private Long balanceBefore; + private Long balanceAfter; + private String businessRefId; + private String idempotencyKey; + private Long orderId; + private String outTradeNo; + private Long refundOfId; + private Long refundedPoints; + private String operatorAdminName; + private String remark; + private LocalDateTime createTime; + + public static TransactionInfoResponse from(TransactionEntity entity, String appName) { + TransactionInfoResponse response = new TransactionInfoResponse(); + response.setId(entity.getId()); + response.setAppCode(entity.getAppCode()); + response.setAppName(appName == null ? entity.getAppCode() : appName); + response.setBusinessUserId(entity.getBusinessUserId()); + response.setUsernameSnapshot(entity.getUsernameSnapshot()); + response.setType(entity.getType()); + response.setAmount(entity.getAmount()); + response.setBalanceBefore(entity.getBalanceBefore()); + response.setBalanceAfter(entity.getBalanceAfter()); + response.setBusinessRefId(entity.getBusinessRefId()); + response.setIdempotencyKey(entity.getIdempotencyKey()); + response.setOrderId(entity.getOrderId()); + response.setOutTradeNo(entity.getOutTradeNo()); + response.setRefundOfId(entity.getRefundOfId()); + response.setRefundedPoints(entity.getRefundedPoints() == null ? 0L : entity.getRefundedPoints()); + response.setOperatorAdminName(entity.getOperatorAdminName()); + response.setRemark(entity.getRemark() == null ? "" : entity.getRemark()); + response.setCreateTime(entity.getCreateTime()); + return response; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/transaction/entity/TransactionEntity.java b/finance-server/src/main/java/com/gas/fin/transaction/entity/TransactionEntity.java new file mode 100644 index 0000000..0d9bfbd --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/transaction/entity/TransactionEntity.java @@ -0,0 +1,34 @@ +package com.gas.fin.transaction.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_transaction") +public class TransactionEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String appCode; + private String businessUserId; + private String usernameSnapshot; + private String type; + private Long amount; + private Long balanceBefore; + private Long balanceAfter; + private String businessRefId; + private String idempotencyKey; + private Long orderId; + private String outTradeNo; + private Long refundOfId; + private Long refundedPoints; + private Long operatorAdminId; + private String operatorAdminName; + private String remark; + private LocalDateTime createTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/transaction/mapper/TransactionMapper.java b/finance-server/src/main/java/com/gas/fin/transaction/mapper/TransactionMapper.java new file mode 100644 index 0000000..31e8399 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/transaction/mapper/TransactionMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.transaction.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.transaction.entity.TransactionEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface TransactionMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/transaction/service/TransactionService.java b/finance-server/src/main/java/com/gas/fin/transaction/service/TransactionService.java new file mode 100644 index 0000000..56209e0 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/transaction/service/TransactionService.java @@ -0,0 +1,101 @@ +package com.gas.fin.transaction.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.app.entity.AppEntity; +import com.gas.fin.app.mapper.AppMapper; +import com.gas.fin.common.api.PageResult; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.security.AdminAuditor; +import com.gas.fin.common.web.QueryUtils; +import com.gas.fin.transaction.dto.TransactionInfoResponse; +import com.gas.fin.transaction.entity.TransactionEntity; +import com.gas.fin.transaction.mapper.TransactionMapper; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 点数流水查询与导出。 + */ +@Service +public class TransactionService { + + private static final int EXPORT_LIMIT = 10000; + + private final TransactionMapper transactionMapper; + private final AppMapper appMapper; + private final AdminAuditor adminAuditor; + + public TransactionService(TransactionMapper transactionMapper, AppMapper appMapper, + AdminAuditor adminAuditor) { + this.transactionMapper = transactionMapper; + this.appMapper = appMapper; + this.adminAuditor = adminAuditor; + } + + public PageResult page(long page, long pageSize, String appCode, String type, + String keyword, String from, String to) { + QueryUtils.checkPage(page, pageSize); + Page result = transactionMapper.selectPage(new Page<>(page, pageSize), + wrapper(appCode, type, keyword, from, to)); + Map names = appNames(); + return PageResult.of(result.getRecords().stream() + .map(item -> TransactionInfoResponse.from(item, names.get(item.getAppCode()))).toList(), + result.getTotal(), page, pageSize); + } + + public List export(String appCode, String type, String keyword, String from, + String to, AdminEntity current, HttpServletRequest httpRequest) { + LambdaQueryWrapper wrapper = wrapper(appCode, type, keyword, from, to); + wrapper.last("LIMIT " + (EXPORT_LIMIT + 1)); + List list = transactionMapper.selectList(wrapper); + if (list.size() > EXPORT_LIMIT) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "导出数据超过 10000 行,请缩小查询范围"); + } + adminAuditor.success(current, "TRANSACTION_EXPORT", "导出点数流水(" + list.size() + " 条)", + "TRANSACTION", null, null, Map.of("appCode", appCode == null ? "" : appCode, + "type", type == null ? "" : type, "count", list.size()), httpRequest); + Map names = appNames(); + return list.stream().map(item -> TransactionInfoResponse.from(item, names.get(item.getAppCode()))).toList(); + } + + private LambdaQueryWrapper wrapper(String appCode, String type, String keyword, + String from, String to) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (appCode != null && !appCode.isBlank()) { + wrapper.eq(TransactionEntity::getAppCode, appCode.trim()); + } + if (type != null && !type.isBlank()) { + wrapper.eq(TransactionEntity::getType, type.trim()); + } + if (keyword != null && !keyword.isBlank()) { + String value = keyword.trim(); + wrapper.and(w -> w.like(TransactionEntity::getBusinessUserId, value) + .or().like(TransactionEntity::getUsernameSnapshot, value) + .or().like(TransactionEntity::getIdempotencyKey, value) + .or().like(TransactionEntity::getBusinessRefId, value)); + } + LocalDateTime fromTime = QueryUtils.parseFrom(from); + LocalDateTime toTime = QueryUtils.parseTo(to); + if (fromTime != null) { + wrapper.ge(TransactionEntity::getCreateTime, fromTime); + } + if (toTime != null) { + wrapper.le(TransactionEntity::getCreateTime, toTime); + } + wrapper.orderByDesc(TransactionEntity::getCreateTime).orderByDesc(TransactionEntity::getId); + return wrapper; + } + + private Map appNames() { + return appMapper.selectList(null).stream() + .collect(Collectors.toMap(AppEntity::getAppCode, AppEntity::getAppName, (a, b) -> a)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/vip/controller/VipController.java b/finance-server/src/main/java/com/gas/fin/vip/controller/VipController.java new file mode 100644 index 0000000..b11c1b2 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/vip/controller/VipController.java @@ -0,0 +1,73 @@ +package com.gas.fin.vip.controller; + +import com.gas.fin.common.api.PageResult; +import com.gas.fin.common.api.R; +import com.gas.fin.common.dto.ToggleRequest; +import com.gas.fin.common.security.AuthContext; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.security.RequirePermission; +import com.gas.fin.vip.dto.VipHolderResponse; +import com.gas.fin.vip.dto.VipPlanRequest; +import com.gas.fin.vip.dto.VipPlanResponse; +import com.gas.fin.vip.service.VipService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/api/admin") +public class VipController { + + private final VipService vipService; + + public VipController(VipService vipService) { + this.vipService = vipService; + } + + @GetMapping("/vip-plans") + @RequirePermission(PermissionRegistry.VIEW) + public R> plans(@RequestParam(required = false) String appCode) { + return R.ok(vipService.plans(appCode)); + } + + @PostMapping("/vip-plans") + @RequirePermission(PermissionRegistry.VIP_MANAGE) + public R create(@RequestBody VipPlanRequest request, + HttpServletRequest httpRequest) { + return R.ok(vipService.create(request, AuthContext.require(), httpRequest)); + } + + @PutMapping("/vip-plans/{id}") + @RequirePermission(PermissionRegistry.VIP_MANAGE) + public R update(@PathVariable Long id, + @RequestBody VipPlanRequest request, + HttpServletRequest httpRequest) { + return R.ok(vipService.update(id, request, AuthContext.require(), httpRequest)); + } + + @PostMapping("/vip-plans/{id}/toggle") + @RequirePermission(PermissionRegistry.VIP_MANAGE) + public R toggle(@PathVariable Long id, + @RequestBody ToggleRequest request, + HttpServletRequest httpRequest) { + return R.ok(vipService.toggle(id, request.enabled(), AuthContext.require(), httpRequest)); + } + + @GetMapping("/vips") + @RequirePermission(PermissionRegistry.VIEW) + public R> holders( + @RequestParam(defaultValue = "1") long page, + @RequestParam(defaultValue = "20") long pageSize, + @RequestParam(required = false) String appCode, + @RequestParam(required = false) String keyword) { + return R.ok(vipService.holders(page, pageSize, appCode, keyword)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/vip/dto/VipHolderResponse.java b/finance-server/src/main/java/com/gas/fin/vip/dto/VipHolderResponse.java new file mode 100644 index 0000000..2745bcf --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/vip/dto/VipHolderResponse.java @@ -0,0 +1,8 @@ +package com.gas.fin.vip.dto; + +import java.time.LocalDateTime; + +public record VipHolderResponse(Long id, String appCode, String appName, String businessUserId, + String usernameSnapshot, String vipPlanCode, LocalDateTime vipUntil, + boolean effective) { +} diff --git a/finance-server/src/main/java/com/gas/fin/vip/dto/VipPlanRequest.java b/finance-server/src/main/java/com/gas/fin/vip/dto/VipPlanRequest.java new file mode 100644 index 0000000..28497a3 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/vip/dto/VipPlanRequest.java @@ -0,0 +1,5 @@ +package com.gas.fin.vip.dto; + +public record VipPlanRequest(String appCode, String planCode, String planName, Integer durationDays, + Long priceCent, Integer freeDeduction, String totp) { +} diff --git a/finance-server/src/main/java/com/gas/fin/vip/dto/VipPlanResponse.java b/finance-server/src/main/java/com/gas/fin/vip/dto/VipPlanResponse.java new file mode 100644 index 0000000..bd1836b --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/vip/dto/VipPlanResponse.java @@ -0,0 +1,38 @@ +package com.gas.fin.vip.dto; + +import com.gas.fin.vip.entity.VipPlanEntity; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class VipPlanResponse { + + private Long id; + private String appCode; + private String appName; + private String planCode; + private String planName; + private Integer durationDays; + private Long priceCent; + private Integer freeDeduction; + private Integer enabled; + private long holderCount; + private LocalDateTime createTime; + + public static VipPlanResponse from(VipPlanEntity entity, String appName, long holderCount) { + VipPlanResponse response = new VipPlanResponse(); + response.setId(entity.getId()); + response.setAppCode(entity.getAppCode()); + response.setAppName(appName == null ? entity.getAppCode() : appName); + response.setPlanCode(entity.getPlanCode()); + response.setPlanName(entity.getPlanName()); + response.setDurationDays(entity.getDurationDays()); + response.setPriceCent(entity.getPriceCent()); + response.setFreeDeduction(entity.getFreeDeduction()); + response.setEnabled(entity.getEnabled()); + response.setHolderCount(holderCount); + response.setCreateTime(entity.getCreateTime()); + return response; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/vip/entity/VipHolderEntity.java b/finance-server/src/main/java/com/gas/fin/vip/entity/VipHolderEntity.java new file mode 100644 index 0000000..271112a --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/vip/entity/VipHolderEntity.java @@ -0,0 +1,23 @@ +package com.gas.fin.vip.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_vip_holder") +public class VipHolderEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String appCode; + private String businessUserId; + private String vipPlanCode; + private LocalDateTime vipUntil; + private LocalDateTime createTime; + private LocalDateTime updateTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/vip/entity/VipPlanEntity.java b/finance-server/src/main/java/com/gas/fin/vip/entity/VipPlanEntity.java new file mode 100644 index 0000000..a31413c --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/vip/entity/VipPlanEntity.java @@ -0,0 +1,26 @@ +package com.gas.fin.vip.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_vip_plan") +public class VipPlanEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String appCode; + private String planCode; + private String planName; + private Integer durationDays; + private Long priceCent; + private Integer freeDeduction; + private Integer enabled; + private LocalDateTime createTime; + private LocalDateTime updateTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/vip/mapper/VipHolderMapper.java b/finance-server/src/main/java/com/gas/fin/vip/mapper/VipHolderMapper.java new file mode 100644 index 0000000..b273dac --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/vip/mapper/VipHolderMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.vip.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.vip.entity.VipHolderEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface VipHolderMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/vip/mapper/VipPlanMapper.java b/finance-server/src/main/java/com/gas/fin/vip/mapper/VipPlanMapper.java new file mode 100644 index 0000000..9a4df17 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/vip/mapper/VipPlanMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.vip.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.vip.entity.VipPlanEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface VipPlanMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/vip/service/VipService.java b/finance-server/src/main/java/com/gas/fin/vip/service/VipService.java new file mode 100644 index 0000000..2d48639 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/vip/service/VipService.java @@ -0,0 +1,244 @@ +package com.gas.fin.vip.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.gas.fin.account.entity.AccountEntity; +import com.gas.fin.account.mapper.AccountMapper; +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.app.entity.AppEntity; +import com.gas.fin.app.mapper.AppMapper; +import com.gas.fin.common.api.PageResult; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.security.AdminAuditor; +import com.gas.fin.common.security.TotpVerifier; +import com.gas.fin.common.web.QueryUtils; +import com.gas.fin.vip.dto.VipHolderResponse; +import com.gas.fin.vip.dto.VipPlanRequest; +import com.gas.fin.vip.dto.VipPlanResponse; +import com.gas.fin.vip.entity.VipHolderEntity; +import com.gas.fin.vip.entity.VipPlanEntity; +import com.gas.fin.vip.mapper.VipHolderMapper; +import com.gas.fin.vip.mapper.VipPlanMapper; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * VIP 档位与持有查询。 + */ +@Service +public class VipService { + + private static final String PLAN_CODE_RULE = "^[A-Z][A-Z0-9_]{2,31}$"; + + private final VipPlanMapper planMapper; + private final VipHolderMapper holderMapper; + private final AccountMapper accountMapper; + private final AppMapper appMapper; + private final TotpVerifier totpVerifier; + private final AdminAuditor adminAuditor; + + public VipService(VipPlanMapper planMapper, VipHolderMapper holderMapper, AccountMapper accountMapper, + AppMapper appMapper, TotpVerifier totpVerifier, AdminAuditor adminAuditor) { + this.planMapper = planMapper; + this.holderMapper = holderMapper; + this.accountMapper = accountMapper; + this.appMapper = appMapper; + this.totpVerifier = totpVerifier; + this.adminAuditor = adminAuditor; + } + + public List plans(String appCode) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (appCode != null && !appCode.isBlank()) { + wrapper.eq(VipPlanEntity::getAppCode, appCode.trim()); + } + wrapper.orderByAsc(VipPlanEntity::getAppCode).orderByDesc(VipPlanEntity::getCreateTime); + Map holders = activeHolderCounts(); + Map names = appNames(); + return planMapper.selectList(wrapper).stream() + .map(item -> VipPlanResponse.from(item, names.get(item.getAppCode()), + holders.getOrDefault(item.getAppCode() + "|" + item.getPlanCode(), 0L))) + .toList(); + } + + @Transactional + public VipPlanResponse create(VipPlanRequest request, AdminEntity current, HttpServletRequest httpRequest) { + AppEntity app = requireApp(QueryUtils.text(request.appCode())); + String planCode = QueryUtils.text(request.planCode()); + String planName = QueryUtils.text(request.planName()); + if (!planCode.matches(PLAN_CODE_RULE)) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "档位编码需为大写字母、数字与下划线,长度 3~32"); + } + if (planName.length() < 2 || planName.length() > 64) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "档位名称至少 2 个字且不超过 64 字"); + } + long duration = request.durationDays() == null ? 0 : request.durationDays(); + if (duration < 1 || duration > 3650) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "有效期天数必须为 1~3650 的正整数"); + } + long price = request.priceCent() == null ? 0 : request.priceCent(); + if (price < 1 || price > 100000000L) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "价格必须大于 0"); + } + if (planMapper.selectCount(new LambdaQueryWrapper() + .eq(VipPlanEntity::getAppCode, app.getAppCode()) + .eq(VipPlanEntity::getPlanCode, planCode)) > 0) { + throw new BizException(ErrorCode.DUPLICATE_KEY, "同应用下档位编码已存在"); + } + LocalDateTime now = LocalDateTime.now().withNano(0); + VipPlanEntity plan = new VipPlanEntity(); + plan.setAppCode(app.getAppCode()); + plan.setPlanCode(planCode); + plan.setPlanName(planName); + plan.setDurationDays((int) duration); + plan.setPriceCent(price); + plan.setFreeDeduction(Integer.valueOf(1).equals(request.freeDeduction()) ? 1 : 0); + plan.setEnabled(1); + plan.setCreateTime(now); + plan.setUpdateTime(now); + planMapper.insert(plan); + + Map after = new LinkedHashMap<>(); + after.put("planCode", planCode); + after.put("durationDays", duration); + after.put("priceCent", price); + adminAuditor.success(current, "VIP_PLAN_CREATE", "新增 VIP 档位", "VIP_PLAN", plan.getId(), + null, after, httpRequest); + return VipPlanResponse.from(plan, app.getAppName(), 0); + } + + @Transactional + public VipPlanResponse update(Long id, VipPlanRequest request, AdminEntity current, + HttpServletRequest httpRequest) { + VipPlanEntity plan = requirePlan(id); + totpVerifier.verify(current, request.totp(), "VIP_PLAN_UPDATE", "修改 VIP 档位(改价)", httpRequest); + long price = request.priceCent() == null ? plan.getPriceCent() : request.priceCent(); + long duration = request.durationDays() == null ? plan.getDurationDays() : request.durationDays(); + if (price < 1 || price > 100000000L) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "价格必须大于 0"); + } + if (duration < 1 || duration > 3650) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "有效期天数必须为 1~3650 的正整数"); + } + String planName = QueryUtils.text(request.planName()); + if (!planName.isEmpty() && (planName.length() < 2 || planName.length() > 64)) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "档位名称至少 2 个字且不超过 64 字"); + } + int freeDeduction = request.freeDeduction() == null ? plan.getFreeDeduction() + : (Integer.valueOf(1).equals(request.freeDeduction()) ? 1 : 0); + Map before = new LinkedHashMap<>(); + before.put("priceCent", plan.getPriceCent()); + before.put("durationDays", plan.getDurationDays()); + planMapper.update(null, new LambdaUpdateWrapper() + .eq(VipPlanEntity::getId, id) + .set(VipPlanEntity::getPlanName, planName.isEmpty() ? plan.getPlanName() : planName) + .set(VipPlanEntity::getPriceCent, price) + .set(VipPlanEntity::getDurationDays, (int) duration) + .set(VipPlanEntity::getFreeDeduction, freeDeduction) + .set(VipPlanEntity::getUpdateTime, LocalDateTime.now().withNano(0))); + Map after = new LinkedHashMap<>(); + after.put("priceCent", price); + after.put("durationDays", duration); + adminAuditor.success(current, "VIP_PLAN_UPDATE", "修改 VIP 档位(改价)", "VIP_PLAN", id, + before, after, httpRequest); + return toResponse(planMapper.selectById(id)); + } + + @Transactional + public VipPlanResponse toggle(Long id, Integer enabled, AdminEntity current, HttpServletRequest httpRequest) { + VipPlanEntity plan = requirePlan(id); + int value = Integer.valueOf(1).equals(enabled) ? 1 : 0; + planMapper.update(null, new LambdaUpdateWrapper() + .eq(VipPlanEntity::getId, id) + .set(VipPlanEntity::getEnabled, value) + .set(VipPlanEntity::getUpdateTime, LocalDateTime.now().withNano(0))); + adminAuditor.success(current, "VIP_PLAN_TOGGLE", + value == 1 ? "上架 VIP 档位" : "下架 VIP 档位", "VIP_PLAN", id, null, + Map.of("enabled", value), httpRequest); + return toResponse(planMapper.selectById(id)); + } + + public PageResult holders(long page, long pageSize, String appCode, String keyword) { + QueryUtils.checkPage(page, pageSize); + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (appCode != null && !appCode.isBlank()) { + wrapper.eq(VipHolderEntity::getAppCode, appCode.trim()); + } + List holders = holderMapper.selectList(wrapper); + Map appNames = appNames(); + Map accounts = accountMapper.selectList(null).stream() + .collect(Collectors.toMap(item -> item.getAppCode() + "|" + item.getBusinessUserId(), + item -> item, (a, b) -> a)); + String kw = keyword == null ? "" : keyword.trim().toLowerCase(); + LocalDateTime now = LocalDateTime.now().withNano(0); + List records = new ArrayList<>(); + for (VipHolderEntity holder : holders) { + AccountEntity account = accounts.get(holder.getAppCode() + "|" + holder.getBusinessUserId()); + String username = account == null || account.getUsernameSnapshot() == null + ? "" : account.getUsernameSnapshot(); + if (!kw.isEmpty() && !holder.getBusinessUserId().toLowerCase().contains(kw) + && !username.toLowerCase().contains(kw)) { + continue; + } + records.add(new VipHolderResponse(holder.getId(), holder.getAppCode(), + appNames.getOrDefault(holder.getAppCode(), holder.getAppCode()), + holder.getBusinessUserId(), username, holder.getVipPlanCode(), + holder.getVipUntil(), holder.getVipUntil().isAfter(now))); + } + records.sort((a, b) -> b.vipUntil().compareTo(a.vipUntil())); + long total = records.size(); + int from = (int) Math.min((page - 1) * pageSize, total); + int to = (int) Math.min(from + pageSize, total); + return PageResult.of(records.subList(from, to), total, page, pageSize); + } + + private VipPlanResponse toResponse(VipPlanEntity plan) { + String appName = appNames().get(plan.getAppCode()); + Long holders = holderMapper.selectCount(new LambdaQueryWrapper() + .eq(VipHolderEntity::getAppCode, plan.getAppCode()) + .eq(VipHolderEntity::getVipPlanCode, plan.getPlanCode()) + .gt(VipHolderEntity::getVipUntil, LocalDateTime.now().withNano(0))); + return VipPlanResponse.from(plan, appName, holders == null ? 0 : holders); + } + + private Map activeHolderCounts() { + Map counts = new HashMap<>(); + holderMapper.selectList(new LambdaQueryWrapper() + .gt(VipHolderEntity::getVipUntil, LocalDateTime.now().withNano(0))) + .forEach(item -> counts.merge(item.getAppCode() + "|" + item.getVipPlanCode(), + 1L, Long::sum)); + return counts; + } + + private VipPlanEntity requirePlan(Long id) { + VipPlanEntity plan = planMapper.selectById(id); + if (plan == null) { + throw new BizException(ErrorCode.NOT_FOUND, "VIP 档位不存在"); + } + return plan; + } + + private AppEntity requireApp(String appCode) { + AppEntity app = appMapper.selectOne(new LambdaQueryWrapper() + .eq(AppEntity::getAppCode, appCode).last("LIMIT 1")); + if (app == null) { + throw new BizException(ErrorCode.NOT_FOUND, "接入应用不存在"); + } + return app; + } + + private Map appNames() { + return appMapper.selectList(null).stream() + .collect(Collectors.toMap(AppEntity::getAppCode, AppEntity::getAppName, (a, b) -> a)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/webhook/controller/WebhookController.java b/finance-server/src/main/java/com/gas/fin/webhook/controller/WebhookController.java new file mode 100644 index 0000000..c2a5fe5 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/webhook/controller/WebhookController.java @@ -0,0 +1,50 @@ +package com.gas.fin.webhook.controller; + +import com.gas.fin.common.api.PageResult; +import com.gas.fin.common.api.R; +import com.gas.fin.common.security.AuthContext; +import com.gas.fin.common.security.PermissionRegistry; +import com.gas.fin.common.security.RequirePermission; +import com.gas.fin.webhook.dto.WebhookDeliveryResponse; +import com.gas.fin.webhook.dto.WebhookReplayRequest; +import com.gas.fin.webhook.service.WebhookService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/admin/webhooks") +public class WebhookController { + + private final WebhookService webhookService; + + public WebhookController(WebhookService webhookService) { + this.webhookService = webhookService; + } + + @GetMapping + @RequirePermission(PermissionRegistry.VIEW) + public R> list( + @RequestParam(defaultValue = "1") long page, + @RequestParam(defaultValue = "20") long pageSize, + @RequestParam(required = false) String appCode, + @RequestParam(required = false) String status, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) String from, + @RequestParam(required = false) String to) { + return R.ok(webhookService.page(page, pageSize, appCode, status, keyword, from, to)); + } + + @PostMapping("/{id}/replay") + @RequirePermission(PermissionRegistry.WEBHOOK_MANAGE) + public R replay(@PathVariable Long id, + @RequestBody WebhookReplayRequest request, + HttpServletRequest httpRequest) { + return R.ok(webhookService.replay(id, request.totp(), AuthContext.require(), httpRequest)); + } +} diff --git a/finance-server/src/main/java/com/gas/fin/webhook/dto/WebhookDeliveryResponse.java b/finance-server/src/main/java/com/gas/fin/webhook/dto/WebhookDeliveryResponse.java new file mode 100644 index 0000000..12af1ea --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/webhook/dto/WebhookDeliveryResponse.java @@ -0,0 +1,40 @@ +package com.gas.fin.webhook.dto; + +import com.gas.fin.webhook.entity.WebhookDeliveryEntity; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class WebhookDeliveryResponse { + + private Long id; + private String appCode; + private String appName; + private String eventId; + private String eventType; + private String status; + private Integer attempts; + private LocalDateTime nextRetryAt; + private String lastError; + private String payload; + private LocalDateTime createTime; + private LocalDateTime updateTime; + + public static WebhookDeliveryResponse from(WebhookDeliveryEntity entity, String appName) { + WebhookDeliveryResponse response = new WebhookDeliveryResponse(); + response.setId(entity.getId()); + response.setAppCode(entity.getAppCode()); + response.setAppName(appName == null ? entity.getAppCode() : appName); + response.setEventId(entity.getEventId()); + response.setEventType(entity.getEventType()); + response.setStatus(entity.getStatus()); + response.setAttempts(entity.getAttempts()); + response.setNextRetryAt(entity.getNextRetryAt()); + response.setLastError(entity.getLastError() == null ? "" : entity.getLastError()); + response.setPayload(entity.getPayload()); + response.setCreateTime(entity.getCreateTime()); + response.setUpdateTime(entity.getUpdateTime()); + return response; + } +} diff --git a/finance-server/src/main/java/com/gas/fin/webhook/dto/WebhookReplayRequest.java b/finance-server/src/main/java/com/gas/fin/webhook/dto/WebhookReplayRequest.java new file mode 100644 index 0000000..d7e481c --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/webhook/dto/WebhookReplayRequest.java @@ -0,0 +1,4 @@ +package com.gas.fin.webhook.dto; + +public record WebhookReplayRequest(String totp) { +} diff --git a/finance-server/src/main/java/com/gas/fin/webhook/entity/WebhookDeliveryEntity.java b/finance-server/src/main/java/com/gas/fin/webhook/entity/WebhookDeliveryEntity.java new file mode 100644 index 0000000..f7862e8 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/webhook/entity/WebhookDeliveryEntity.java @@ -0,0 +1,29 @@ +package com.gas.fin.webhook.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("fin_webhook_delivery") +public class WebhookDeliveryEntity { + + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; + + private String appCode; + private String eventId; + private String eventType; + private String status; + private Integer attempts; + private Integer maxAttempts; + private LocalDateTime nextRetryAt; + private String lastError; + private String payload; + private String signature; + private LocalDateTime createTime; + private LocalDateTime updateTime; +} diff --git a/finance-server/src/main/java/com/gas/fin/webhook/mapper/WebhookDeliveryMapper.java b/finance-server/src/main/java/com/gas/fin/webhook/mapper/WebhookDeliveryMapper.java new file mode 100644 index 0000000..456a9ef --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/webhook/mapper/WebhookDeliveryMapper.java @@ -0,0 +1,9 @@ +package com.gas.fin.webhook.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.gas.fin.webhook.entity.WebhookDeliveryEntity; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface WebhookDeliveryMapper extends BaseMapper { +} diff --git a/finance-server/src/main/java/com/gas/fin/webhook/service/WebhookService.java b/finance-server/src/main/java/com/gas/fin/webhook/service/WebhookService.java new file mode 100644 index 0000000..4aaae81 --- /dev/null +++ b/finance-server/src/main/java/com/gas/fin/webhook/service/WebhookService.java @@ -0,0 +1,136 @@ +package com.gas.fin.webhook.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.gas.fin.admin.entity.AdminEntity; +import com.gas.fin.app.entity.AppEntity; +import com.gas.fin.app.mapper.AppMapper; +import com.gas.fin.common.api.PageResult; +import com.gas.fin.common.error.BizException; +import com.gas.fin.common.error.ErrorCode; +import com.gas.fin.common.security.AdminAuditor; +import com.gas.fin.common.security.TotpVerifier; +import com.gas.fin.common.web.QueryUtils; +import com.gas.fin.setting.service.ConfigService; +import com.gas.fin.webhook.dto.WebhookDeliveryResponse; +import com.gas.fin.webhook.entity.WebhookDeliveryEntity; +import com.gas.fin.webhook.mapper.WebhookDeliveryMapper; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Webhook 投递记录:列表、手动重放、业务事件入队。 + */ +@Service +public class WebhookService { + + private final WebhookDeliveryMapper deliveryMapper; + private final AppMapper appMapper; + private final ConfigService configService; + private final TotpVerifier totpVerifier; + private final AdminAuditor adminAuditor; + + public WebhookService(WebhookDeliveryMapper deliveryMapper, AppMapper appMapper, + ConfigService configService, TotpVerifier totpVerifier, AdminAuditor adminAuditor) { + this.deliveryMapper = deliveryMapper; + this.appMapper = appMapper; + this.configService = configService; + this.totpVerifier = totpVerifier; + this.adminAuditor = adminAuditor; + } + + public PageResult page(long page, long pageSize, String appCode, String status, + String keyword, String from, String to) { + QueryUtils.checkPage(page, pageSize); + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (appCode != null && !appCode.isBlank()) { + wrapper.eq(WebhookDeliveryEntity::getAppCode, appCode.trim()); + } + if (status != null && !status.isBlank()) { + wrapper.eq(WebhookDeliveryEntity::getStatus, status.trim()); + } + if (keyword != null && !keyword.isBlank()) { + String value = keyword.trim(); + wrapper.and(w -> w.like(WebhookDeliveryEntity::getEventId, value) + .or().like(WebhookDeliveryEntity::getEventType, value)); + } + LocalDateTime fromTime = QueryUtils.parseFrom(from); + LocalDateTime toTime = QueryUtils.parseTo(to); + if (fromTime != null) { + wrapper.ge(WebhookDeliveryEntity::getCreateTime, fromTime); + } + if (toTime != null) { + wrapper.le(WebhookDeliveryEntity::getCreateTime, toTime); + } + wrapper.orderByDesc(WebhookDeliveryEntity::getCreateTime).orderByDesc(WebhookDeliveryEntity::getId); + Page result = deliveryMapper.selectPage(new Page<>(page, pageSize), wrapper); + Map appNames = appNames(); + List records = result.getRecords().stream() + .map(item -> WebhookDeliveryResponse.from(item, appNames.get(item.getAppCode()))) + .toList(); + return PageResult.of(records, result.getTotal(), page, pageSize); + } + + @Transactional + public WebhookDeliveryResponse replay(Long id, String totp, AdminEntity current, HttpServletRequest httpRequest) { + WebhookDeliveryEntity item = deliveryMapper.selectById(id); + if (item == null) { + throw new BizException(ErrorCode.NOT_FOUND, "投递记录不存在"); + } + totpVerifier.verify(current, totp, "WEBHOOK_REPLAY", "手动重放 webhook", httpRequest); + if (!"FAILED".equals(item.getStatus()) && !"DEAD".equals(item.getStatus())) { + throw new BizException(ErrorCode.VALIDATION_FAILED, "仅失败记录可以重放"); + } + LocalDateTime now = LocalDateTime.now().withNano(0); + deliveryMapper.update(null, new LambdaUpdateWrapper() + .eq(WebhookDeliveryEntity::getId, id) + .set(WebhookDeliveryEntity::getStatus, "PENDING") + .set(WebhookDeliveryEntity::getAttempts, 0) + .set(WebhookDeliveryEntity::getNextRetryAt, now) + .set(WebhookDeliveryEntity::getLastError, "") + .set(WebhookDeliveryEntity::getUpdateTime, now)); + adminAuditor.success(current, "WEBHOOK_REPLAY", "手动重放 webhook", "WEBHOOK", id, null, + Map.of("eventId", item.getEventId()), httpRequest); + return WebhookDeliveryResponse.from(deliveryMapper.selectById(id), + appNames().get(item.getAppCode())); + } + + /** + * 业务事件入队:event_id 唯一,重复事件直接跳过,由投递器异步发送。 + */ + public void enqueue(String appCode, String eventId, String eventType, String payload) { + Long exists = deliveryMapper.selectCount(new LambdaQueryWrapper() + .eq(WebhookDeliveryEntity::getAppCode, appCode) + .eq(WebhookDeliveryEntity::getEventId, eventId) + .eq(WebhookDeliveryEntity::getEventType, eventType)); + if (exists != null && exists > 0) { + return; + } + LocalDateTime now = LocalDateTime.now().withNano(0); + WebhookDeliveryEntity entity = new WebhookDeliveryEntity(); + entity.setAppCode(appCode); + entity.setEventId(eventId); + entity.setEventType(eventType); + entity.setStatus("PENDING"); + entity.setAttempts(0); + entity.setMaxAttempts((int) configService.getNumber("webhook.max_retry", 6)); + entity.setNextRetryAt(now); + entity.setLastError(""); + entity.setPayload(payload); + entity.setCreateTime(now); + entity.setUpdateTime(now); + deliveryMapper.insert(entity); + } + + private Map appNames() { + return appMapper.selectList(null).stream() + .collect(Collectors.toMap(AppEntity::getAppCode, AppEntity::getAppName, (a, b) -> a)); + } +} diff --git a/finance-server/src/main/resources/application.yml b/finance-server/src/main/resources/application.yml new file mode 100644 index 0000000..1be56d1 --- /dev/null +++ b/finance-server/src/main/resources/application.yml @@ -0,0 +1,97 @@ +server: + port: ${SERVER_PORT:8080} + address: ${SERVER_ADDRESS:127.0.0.1} + shutdown: graceful + +spring: + application: + name: finance-api + profiles: + active: ${SPRING_PROFILES_ACTIVE:local} + datasource: + url: jdbc:mysql://${FIN_DB_HOST:127.0.0.1}:${FIN_DB_PORT:3306}/${FIN_DB_NAME:fin_platform}?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true + username: ${FIN_DB_USER:fin_app} + password: '${FIN_DB_PASSWORD:FinApp#2026Dev}' + driver-class-name: com.mysql.cj.jdbc.Driver + hikari: + maximum-pool-size: ${FIN_DB_POOL_MAX:20} + minimum-idle: 2 + connection-timeout: 3000 + validation-timeout: 1000 + pool-name: fin-hikari + flyway: + enabled: true + locations: classpath:db/migration + user: ${FIN_FLYWAY_USER:fin_migrate} + password: '${FIN_FLYWAY_PASSWORD:FinMigrate#2026Dev}' + validate-on-migrate: true + baseline-on-migrate: false + clean-disabled: true + data: + redis: + host: ${FIN_REDIS_HOST:127.0.0.1} + port: ${FIN_REDIS_PORT:6379} + password: '${FIN_REDIS_PASSWORD:FinRedis#2026Dev}' + database: ${FIN_REDIS_DB:0} + timeout: 2s + connect-timeout: 2s + jackson: + date-format: yyyy-MM-dd HH:mm:ss + time-zone: Asia/Shanghai + default-property-inclusion: always + serialization: + write-dates-as-timestamps: false + mvc: + throw-exception-if-no-handler-found: true + web: + resources: + add-mappings: false + +mybatis-plus: + configuration: + map-underscore-to-camel-case: true + global-config: + banner: false + db-config: + id-type: assign_id + +management: + endpoints: + web: + exposure: + include: health,info,prometheus + endpoint: + health: + show-details: never + server: + port: ${SERVER_MANAGEMENT_PORT:8081} + address: 127.0.0.1 + +fin: + version: 1.0.0 + worker-id: ${FIN_WORKER_ID:0} + runtime-dir: ${FIN_RUNTIME_DIR:./.runtime} + secret-enc-key: '${FIN_SECRET_ENC_KEY:}' + trust-proxy: ${FIN_TRUST_PROXY:true} + cors: + allowed-origins: ${FIN_ALLOWED_ORIGINS:http://localhost:5180} + demo-ticket-enabled: ${FIN_DEMO_TICKET_ENABLED:true} + auth: + idle-minutes: 30 + absolute-hours: 8 + lock-threshold: 5 + lock-minutes: 15 + password-history-size: 3 + admin: + totp-output-enabled: ${FIN_TOTP_OUTPUT_ENABLED:true} + bootstrap: + enabled: ${FIN_BOOTSTRAP_ADMIN_ENABLED:true} + audit: + chain-lock: ${FIN_AUDIT_CHAIN_LOCK:lock:audit:chain} + +logging: + level: + root: ${FIN_LOG_LEVEL:INFO} + com.gas.fin: ${FIN_LOG_LEVEL:INFO} + pattern: + console: "%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%X{traceId:-}] %logger{36} - %msg%n" diff --git a/finance-server/src/main/resources/db/migration/V1__init_schema.sql b/finance-server/src/main/resources/db/migration/V1__init_schema.sql new file mode 100644 index 0000000..a11e04f --- /dev/null +++ b/finance-server/src/main/resources/db/migration/V1__init_schema.sql @@ -0,0 +1,452 @@ +-- 中央计费平台初始化建表脚本(MySQL 8.0.33+ / 8.4) +-- 约定:id 主键由应用层雪花生成(fin_audit_log 例外,使用自增以保证哈希链顺序); +-- 金额单位分(BIGINT);点数单位个(BIGINT);时间统一 DATETIME(Asia/Shanghai); +-- 不建数据库外键,关联字段由应用层维护并建索引。 + +CREATE TABLE `fin_admin` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `username` VARCHAR(32) NOT NULL COMMENT '登录名', + `password_hash` VARCHAR(100) NOT NULL COMMENT '密码哈希', + `role` VARCHAR(16) NOT NULL COMMENT 'SUPER_ADMIN/FINANCE/AUDITOR', + `is_active` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1启用/0停用', + `must_change_password` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1需强制改密', + `totp_secret_enc` VARCHAR(255) DEFAULT NULL COMMENT 'TOTP密钥密文', + `totp_bound` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '1已绑定', + `failed_attempts` INT NOT NULL DEFAULT 0 COMMENT '连续失败次数', + `locked_until` DATETIME DEFAULT NULL COMMENT '锁定截止', + `last_login_at` DATETIME DEFAULT NULL COMMENT '最近登录', + `last_login_ip` VARCHAR(45) DEFAULT NULL COMMENT '最近登录IP', + `password_updated_at` DATETIME DEFAULT NULL COMMENT '最近改密时间', + `version_no` INT NOT NULL DEFAULT 0 COMMENT '乐观锁', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_admin_username` (`username`), + KEY `idx_fin_admin_role` (`role`, `is_active`), + KEY `idx_fin_admin_locked` (`locked_until`), + CONSTRAINT `ck_fin_admin_role` CHECK (`role` IN ('SUPER_ADMIN', 'FINANCE', 'AUDITOR')), + CONSTRAINT `ck_fin_admin_failed` CHECK (`failed_attempts` >= 0) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='管理员账号'; + +CREATE TABLE `fin_admin_password_history` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `admin_id` BIGINT UNSIGNED NOT NULL COMMENT '管理员ID', + `password_hash` VARCHAR(100) NOT NULL COMMENT '历史密码哈希', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `idx_fin_pwd_admin` (`admin_id`, `create_time`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='密码历史'; + +CREATE TABLE `fin_admin_session` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `admin_id` BIGINT UNSIGNED NOT NULL COMMENT '管理员ID', + `token_hash` CHAR(64) NOT NULL COMMENT '会话token SHA-256', + `issued_ip` VARCHAR(45) DEFAULT NULL COMMENT '签发IP', + `user_agent` VARCHAR(255) DEFAULT NULL COMMENT 'UA', + `last_active_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最近活跃', + `idle_expire_at` DATETIME NOT NULL COMMENT '空闲过期', + `absolute_expire_at` DATETIME NOT NULL COMMENT '绝对过期', + `revoked_at` DATETIME DEFAULT NULL COMMENT '撤销时间', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_session_token` (`token_hash`), + KEY `idx_fin_session_admin` (`admin_id`, `revoked_at`), + KEY `idx_fin_session_expire` (`absolute_expire_at`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='管理员会话'; + +CREATE TABLE `fin_app` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `app_name` VARCHAR(64) NOT NULL COMMENT '应用名称', + `allowed_redirect_hosts` VARCHAR(1000) NOT NULL COMMENT '逗号分隔精确域名', + `webhook_url` VARCHAR(500) DEFAULT NULL COMMENT 'webhook地址', + `webhook_secret_enc` VARCHAR(255) NOT NULL COMMENT 'webhook签名密钥密文', + `token_ttl_seconds` INT NOT NULL DEFAULT 900 COMMENT 'token有效期秒', + `enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1启用/0停用', + `secret_expires_at` DATETIME DEFAULT NULL COMMENT '旧密钥宽限截止', + `has_prev_secret` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否存在旧密钥', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_app_code` (`app_code`), + KEY `idx_fin_app_enabled` (`enabled`), + CONSTRAINT `ck_fin_app_ttl` CHECK (`token_ttl_seconds` BETWEEN 60 AND 86400) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='接入应用'; + +CREATE TABLE `fin_app_secret` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `secret_hash` CHAR(64) NOT NULL COMMENT 'secret SHA-256', + `secret_prefix` VARCHAR(12) NOT NULL COMMENT '展示前缀', + `status` VARCHAR(16) NOT NULL DEFAULT 'ACTIVE' COMMENT 'ACTIVE/GRACE/REVOKED', + `grace_expire_at` DATETIME DEFAULT NULL COMMENT '宽限截止', + `created_by` BIGINT UNSIGNED DEFAULT NULL COMMENT '创建管理员', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `revoked_at` DATETIME DEFAULT NULL COMMENT '回收时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_secret_hash` (`secret_hash`), + KEY `idx_fin_secret_app` (`app_code`, `status`, `grace_expire_at`), + CONSTRAINT `ck_fin_secret_status` CHECK (`status` IN ('ACTIVE', 'GRACE', 'REVOKED')) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='应用密钥历史'; + +CREATE TABLE `fin_app_token` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `token_hash` CHAR(64) NOT NULL COMMENT 'token SHA-256', + `token_prefix` VARCHAR(12) NOT NULL COMMENT '展示前缀', + `issued_ip` VARCHAR(45) DEFAULT NULL COMMENT '签发IP', + `expires_at` DATETIME NOT NULL COMMENT '过期时间', + `revoked_at` DATETIME DEFAULT NULL COMMENT '撤销时间', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_token_hash` (`token_hash`), + KEY `idx_fin_token_app` (`app_code`, `expires_at`), + KEY `idx_fin_token_revoked` (`revoked_at`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='client token(只存哈希)'; + +CREATE TABLE `fin_account` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `business_user_id` VARCHAR(64) NOT NULL COMMENT '业务用户ID', + `username_snapshot` VARCHAR(64) DEFAULT NULL COMMENT '用户名快照', + `phone_masked` VARCHAR(32) DEFAULT NULL COMMENT '掩码手机号', + `phone_hash` CHAR(64) DEFAULT NULL COMMENT '手机号哈希', + `balance` BIGINT NOT NULL DEFAULT 0 COMMENT '余额点数', + `total_spent` BIGINT NOT NULL DEFAULT 0 COMMENT '累计消耗点数', + `version_no` INT NOT NULL DEFAULT 0 COMMENT '乐观锁', + `vip_plan_code` VARCHAR(32) DEFAULT NULL COMMENT '当前VIP档位', + `vip_until` DATETIME DEFAULT NULL COMMENT 'VIP到期时间', + `status` VARCHAR(16) NOT NULL DEFAULT 'ACTIVE' COMMENT 'ACTIVE/FROZEN', + `first_seen_at` DATETIME DEFAULT NULL COMMENT '首次出现时间', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_account_app_user` (`app_code`, `business_user_id`), + KEY `idx_fin_account_balance` (`app_code`, `balance`), + KEY `idx_fin_account_phone` (`phone_hash`), + KEY `idx_fin_account_vip` (`vip_until`), + CONSTRAINT `ck_fin_account_balance` CHECK (`balance` >= 0), + CONSTRAINT `ck_fin_account_spent` CHECK (`total_spent` >= 0), + CONSTRAINT `ck_fin_account_status` CHECK (`status` IN ('ACTIVE', 'FROZEN')) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='业务用户钱包'; + +CREATE TABLE `fin_transaction` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `business_user_id` VARCHAR(64) NOT NULL COMMENT '业务用户ID', + `username_snapshot` VARCHAR(64) DEFAULT NULL COMMENT '用户名快照', + `type` VARCHAR(16) NOT NULL COMMENT 'RECHARGE/CONSUME/CONSUME_FREE/REFUND_IN/REFUND_OUT/ADJUST', + `amount` BIGINT NOT NULL COMMENT '变动点数(正数)', + `balance_before` BIGINT NOT NULL COMMENT '变动前余额', + `balance_after` BIGINT NOT NULL COMMENT '变动后余额', + `business_ref_id` VARCHAR(64) DEFAULT NULL COMMENT '业务引用', + `idempotency_key` VARCHAR(64) NOT NULL COMMENT '幂等键', + `order_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '订单ID', + `out_trade_no` VARCHAR(40) DEFAULT NULL COMMENT '订单号快照', + `refund_of_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '退款单ID', + `refunded_points` BIGINT NOT NULL DEFAULT 0 COMMENT '已退回点数', + `operator_admin_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '操作管理员', + `operator_admin_name` VARCHAR(32) DEFAULT NULL COMMENT '操作人快照', + `remark` VARCHAR(255) DEFAULT NULL COMMENT '备注', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_tx_idem` (`app_code`, `idempotency_key`), + KEY `idx_fin_tx_account` (`app_code`, `business_user_id`, `create_time`), + KEY `idx_fin_tx_order` (`order_id`), + KEY `idx_fin_tx_type` (`type`, `create_time`), + KEY `idx_fin_tx_ref` (`business_ref_id`), + KEY `idx_fin_tx_refund` (`refund_of_id`), + CONSTRAINT `ck_fin_tx_balance` CHECK (`balance_before` >= 0 AND `balance_after` >= 0), + CONSTRAINT `ck_fin_tx_amount` CHECK ((`type` = 'CONSUME_FREE' AND `amount` = 0) OR (`type` <> 'CONSUME_FREE' AND `amount` > 0)), + CONSTRAINT `ck_fin_tx_type` CHECK (`type` IN ('RECHARGE', 'CONSUME', 'CONSUME_FREE', 'REFUND_IN', 'REFUND_OUT', 'ADJUST')) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='点数流水'; + +CREATE TABLE `fin_order` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `out_trade_no` VARCHAR(40) NOT NULL COMMENT '商户订单号', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `business_user_id` VARCHAR(64) NOT NULL COMMENT '业务用户ID', + `username_snapshot` VARCHAR(64) DEFAULT NULL COMMENT '用户名快照', + `order_type` VARCHAR(16) NOT NULL COMMENT 'recharge/vip', + `pay_method` VARCHAR(16) NOT NULL DEFAULT 'offline' COMMENT 'offline/wechat/alipay', + `amount_cent` BIGINT NOT NULL COMMENT '金额(分)', + `points_gained` BIGINT NOT NULL DEFAULT 0 COMMENT '到账点数', + `points_per_yuan_snapshot` INT NOT NULL DEFAULT 1 COMMENT '下单时兑率快照', + `vip_plan_code` VARCHAR(32) DEFAULT NULL COMMENT 'VIP档位', + `status` VARCHAR(16) NOT NULL DEFAULT 'PENDING' COMMENT 'PENDING/PAID/CANCELLED/REFUNDED', + `expires_at` DATETIME NOT NULL COMMENT '待确认超时', + `paid_at` DATETIME DEFAULT NULL COMMENT '到账时间', + `confirmed_by_admin_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '确认人', + `confirmed_by_admin_name` VARCHAR(32) DEFAULT NULL COMMENT '确认人快照', + `second_approver_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '第二复核人', + `second_approver_name` VARCHAR(32) DEFAULT NULL COMMENT '复核人快照', + `remark` VARCHAR(255) DEFAULT NULL COMMENT '备注/关单原因', + `refunded_amount_cent` BIGINT NOT NULL DEFAULT 0 COMMENT '累计退款金额', + `version_no` INT NOT NULL DEFAULT 0 COMMENT '乐观锁', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_order_no` (`out_trade_no`), + KEY `idx_fin_order_app` (`app_code`, `status`, `create_time`), + KEY `idx_fin_order_user` (`app_code`, `business_user_id`), + KEY `idx_fin_order_paid` (`paid_at`), + KEY `idx_fin_order_expire` (`status`, `expires_at`), + CONSTRAINT `ck_fin_order_amount` CHECK (`amount_cent` > 0 AND `refunded_amount_cent` <= `amount_cent`), + CONSTRAINT `ck_fin_order_type` CHECK (`order_type` IN ('recharge', 'vip')), + CONSTRAINT `ck_fin_order_status` CHECK (`status` IN ('PENDING', 'PAID', 'CANCELLED', 'REFUNDED')), + CONSTRAINT `ck_fin_order_rate` CHECK (`points_per_yuan_snapshot` > 0) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='充值/VIP订单'; + +CREATE TABLE `fin_cash_ledger` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `order_id` BIGINT UNSIGNED NOT NULL COMMENT '关联订单', + `refund_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '关联退款单', + `direction` VARCHAR(4) NOT NULL COMMENT 'IN/OUT', + `amount_cent` BIGINT NOT NULL COMMENT '金额(分)', + `received_at` DATETIME NOT NULL COMMENT '实际到账/出账时间', + `voucher_no` VARCHAR(64) NOT NULL COMMENT '银行凭证号', + `operator_admin_id` BIGINT UNSIGNED NOT NULL COMMENT '登记人', + `operator_admin_name` VARCHAR(32) NOT NULL COMMENT '登记人快照', + `remark` VARCHAR(255) DEFAULT NULL COMMENT '备注', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_cash_voucher` (`order_id`, `direction`, `voucher_no`), + KEY `idx_fin_cash_app` (`app_code`, `direction`, `received_at`), + KEY `idx_fin_cash_order` (`order_id`), + KEY `idx_fin_cash_refund` (`refund_id`), + CONSTRAINT `ck_fin_cash_amount` CHECK (`amount_cent` > 0), + CONSTRAINT `ck_fin_cash_dir` CHECK (`direction` IN ('IN', 'OUT')) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='现金台账'; + +CREATE TABLE `fin_refund` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `business_user_id` VARCHAR(64) NOT NULL COMMENT '业务用户ID', + `username_snapshot` VARCHAR(64) DEFAULT NULL COMMENT '用户名快照', + `order_id` BIGINT UNSIGNED NOT NULL COMMENT '原订单', + `out_trade_no` VARCHAR(40) NOT NULL COMMENT '原订单号快照', + `amount_cent` BIGINT NOT NULL COMMENT '退款金额(分)', + `points_deducted` BIGINT NOT NULL DEFAULT 0 COMMENT '扣回点数', + `status` VARCHAR(16) NOT NULL DEFAULT 'PENDING' COMMENT 'PENDING/COMPLETED/REJECTED', + `operator_admin_id` BIGINT UNSIGNED NOT NULL COMMENT '发起人', + `operator_admin_name` VARCHAR(32) NOT NULL COMMENT '发起人快照', + `reviewer_admin_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '复核人', + `reviewer_admin_name` VARCHAR(32) DEFAULT NULL COMMENT '复核人快照', + `voucher_no` VARCHAR(64) DEFAULT NULL COMMENT '退款凭证号', + `remark` VARCHAR(255) DEFAULT NULL COMMENT '原因/驳回原因', + `idempotency_key` VARCHAR(64) NOT NULL COMMENT '幂等键', + `review_time` DATETIME DEFAULT NULL COMMENT '复核时间', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_refund_idem` (`app_code`, `idempotency_key`), + KEY `idx_fin_refund_order` (`order_id`), + KEY `idx_fin_refund_status` (`status`, `create_time`), + KEY `idx_fin_refund_app` (`app_code`, `create_time`), + CONSTRAINT `ck_fin_refund_amount` CHECK (`amount_cent` > 0), + CONSTRAINT `ck_fin_refund_points` CHECK (`points_deducted` >= 0), + CONSTRAINT `ck_fin_refund_status` CHECK (`status` IN ('PENDING', 'COMPLETED', 'REJECTED')) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='退款单'; + +CREATE TABLE `fin_vip_plan` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `plan_code` VARCHAR(32) NOT NULL COMMENT '档位编码', + `plan_name` VARCHAR(64) NOT NULL COMMENT '档位名称', + `duration_days` INT NOT NULL COMMENT '有效期天数', + `price_cent` BIGINT NOT NULL COMMENT '价格(分)', + `free_deduction` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '1可免扣', + `enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1上架/0下架', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_plan_app_code` (`app_code`, `plan_code`), + KEY `idx_fin_plan_enabled` (`app_code`, `enabled`), + CONSTRAINT `ck_fin_plan_price` CHECK (`price_cent` > 0), + CONSTRAINT `ck_fin_plan_days` CHECK (`duration_days` > 0), + CONSTRAINT `ck_fin_plan_free` CHECK (`free_deduction` IN (0, 1)) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='VIP档位'; + +CREATE TABLE `fin_vip_holder` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `business_user_id` VARCHAR(64) NOT NULL COMMENT '业务用户ID', + `vip_plan_code` VARCHAR(32) NOT NULL COMMENT '当前档位', + `vip_until` DATETIME NOT NULL COMMENT '到期时间', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_vip_app_user` (`app_code`, `business_user_id`), + KEY `idx_fin_vip_until` (`vip_until`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='VIP持有'; + +CREATE TABLE `fin_app_pricing` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `points_per_yuan` BIGINT NOT NULL DEFAULT 100 COMMENT '1元兑换点数', + `enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1启用', + `update_by` VARCHAR(32) DEFAULT NULL COMMENT '最近修改人', + `version_no` INT NOT NULL DEFAULT 0 COMMENT '乐观锁', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_pricing_app` (`app_code`), + CONSTRAINT `ck_fin_pricing_rate` CHECK (`points_per_yuan` > 0) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='应用兑率'; + +CREATE TABLE `fin_app_policy` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `min_cost` BIGINT NOT NULL DEFAULT 0 COMMENT '保底消费点数', + `max_points_per_charge` BIGINT NOT NULL DEFAULT 50000 COMMENT '单次扣费上限', + `vip_exempt` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '1开启VIP免扣', + `failed_strategy` VARCHAR(16) NOT NULL DEFAULT 'none' COMMENT 'none/actual', + `dual_control_threshold_cent` BIGINT NOT NULL DEFAULT 500000 COMMENT '双人复核阈值(分)', + `enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1启用', + `update_by` VARCHAR(32) DEFAULT NULL COMMENT '最近修改人', + `version_no` INT NOT NULL DEFAULT 0 COMMENT '乐观锁', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_policy_app` (`app_code`), + CONSTRAINT `ck_fin_policy_min` CHECK (`min_cost` >= 0), + CONSTRAINT `ck_fin_policy_max` CHECK (`max_points_per_charge` >= GREATEST(1, `min_cost`)), + CONSTRAINT `ck_fin_policy_exempt` CHECK (`vip_exempt` IN (0, 1)), + CONSTRAINT `ck_fin_policy_strategy` CHECK (`failed_strategy` IN ('none', 'actual')), + CONSTRAINT `ck_fin_policy_threshold` CHECK (`dual_control_threshold_cent` >= 0) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='应用扣费策略'; + +CREATE TABLE `fin_config` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `config_key` VARCHAR(64) NOT NULL COMMENT '参数键', + `config_value` VARCHAR(255) NOT NULL COMMENT '参数值', + `description` VARCHAR(255) DEFAULT NULL COMMENT '说明', + `risk` VARCHAR(8) NOT NULL DEFAULT 'NORMAL' COMMENT 'HIGH/NORMAL', + `update_by` VARCHAR(32) DEFAULT NULL COMMENT '修改人', + `version_no` INT NOT NULL DEFAULT 0 COMMENT '乐观锁', + `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_config_key` (`config_key`), + KEY `idx_fin_config_risk` (`risk`), + CONSTRAINT `ck_fin_config_risk` CHECK (`risk` IN ('HIGH', 'NORMAL')) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='全局参数'; + +CREATE TABLE `fin_audit_log` ( + `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键(链顺序)', + `actor_type` VARCHAR(8) NOT NULL COMMENT 'ADMIN/SYSTEM/BIZ', + `actor_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '管理员ID', + `actor_name` VARCHAR(64) NOT NULL COMMENT '操作者', + `action` VARCHAR(64) NOT NULL COMMENT '动作码', + `action_label` VARCHAR(128) NOT NULL COMMENT '中文描述', + `target_type` VARCHAR(32) NOT NULL COMMENT '目标类型', + `target_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '目标ID', + `before_json` JSON DEFAULT NULL COMMENT '变更前(脱敏)', + `after_json` JSON DEFAULT NULL COMMENT '变更后(脱敏)', + `ip` VARCHAR(45) NOT NULL COMMENT '客户端IP', + `ua` VARCHAR(255) DEFAULT NULL COMMENT 'User-Agent', + `result` VARCHAR(8) NOT NULL DEFAULT 'SUCCESS' COMMENT 'SUCCESS/FAILED', + `prev_hash` CHAR(64) NOT NULL DEFAULT '' COMMENT '前一条哈希', + `cur_hash` CHAR(64) NOT NULL COMMENT '本条哈希', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `idx_fin_audit_time` (`create_time`), + KEY `idx_fin_audit_actor` (`actor_id`, `create_time`), + KEY `idx_fin_audit_action` (`action`, `create_time`), + KEY `idx_fin_audit_target` (`target_type`, `target_id`), + KEY `idx_fin_audit_result` (`result`, `create_time`), + CONSTRAINT `ck_fin_audit_actor` CHECK (`actor_type` IN ('ADMIN', 'SYSTEM', 'BIZ')), + CONSTRAINT `ck_fin_audit_result` CHECK (`result` IN ('SUCCESS', 'FAILED')) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='审计日志(只追加)'; + +CREATE TABLE `fin_webhook_delivery` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `app_code` VARCHAR(32) NOT NULL COMMENT '目标应用', + `event_id` VARCHAR(64) NOT NULL COMMENT '事件唯一ID', + `event_type` VARCHAR(32) NOT NULL COMMENT 'order.paid/order.refunded', + `status` VARCHAR(16) NOT NULL DEFAULT 'PENDING' COMMENT 'PENDING/SENT/FAILED/DEAD', + `attempts` INT NOT NULL DEFAULT 0 COMMENT '已尝试次数', + `max_attempts` INT NOT NULL DEFAULT 6 COMMENT '最大尝试次数', + `next_retry_at` DATETIME DEFAULT NULL COMMENT '下次重试时间', + `last_error` VARCHAR(500) DEFAULT NULL COMMENT '最近错误(脱敏)', + `payload` JSON NOT NULL COMMENT '事件负载', + `signature` VARCHAR(128) DEFAULT NULL COMMENT '最近一次签名', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_webhook_event` (`app_code`, `event_id`, `event_type`), + KEY `idx_fin_webhook_due` (`status`, `next_retry_at`), + KEY `idx_fin_webhook_app` (`app_code`, `create_time`), + CONSTRAINT `ck_fin_webhook_status` CHECK (`status` IN ('PENDING', 'SENT', 'FAILED', 'DEAD')) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Webhook投递'; + +CREATE TABLE `fin_reconcile_report` ( + `id` VARCHAR(32) NOT NULL COMMENT '报告号', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `window_start` DATE NOT NULL COMMENT '窗口起(含)', + `window_end` DATE NOT NULL COMMENT '窗口止(含)', + `snapshot_at` DATETIME NOT NULL COMMENT '快照时间', + `cash_in_cent` BIGINT NOT NULL DEFAULT 0 COMMENT '现金IN合计', + `cash_paid_order_cent` BIGINT NOT NULL DEFAULT 0 COMMENT '已到账订单合计', + `cash_out_cent` BIGINT NOT NULL DEFAULT 0 COMMENT '现金OUT合计', + `cash_refunded_cent` BIGINT NOT NULL DEFAULT 0 COMMENT '已完成退款合计', + `cash_diff_cent` BIGINT NOT NULL DEFAULT 0 COMMENT '现金侧差异', + `wallet_sum` BIGINT NOT NULL DEFAULT 0 COMMENT '账户余额合计', + `computed_sum` BIGINT NOT NULL DEFAULT 0 COMMENT '流水重算余额合计', + `points_diff` BIGINT NOT NULL DEFAULT 0 COMMENT '点数侧差异', + `broken_chains` INT NOT NULL DEFAULT 0 COMMENT '断链账户数', + `diff_count` INT NOT NULL DEFAULT 0 COMMENT '差异明细条数', + `status` VARCHAR(16) NOT NULL COMMENT 'BALANCED/DIFF', + `created_by` VARCHAR(32) NOT NULL COMMENT '执行人', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `idx_fin_recon_app` (`app_code`, `create_time`), + KEY `idx_fin_recon_status` (`status`, `create_time`), + CONSTRAINT `ck_fin_recon_status` CHECK (`status` IN ('BALANCED', 'DIFF')), + CONSTRAINT `ck_fin_recon_window` CHECK (`window_start` <= `window_end`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='对账报告'; + +CREATE TABLE `fin_reconcile_diff` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `report_id` VARCHAR(32) NOT NULL COMMENT '报告号', + `level` VARCHAR(16) NOT NULL COMMENT 'ORDER/SUBJECT/APP', + `target` VARCHAR(64) NOT NULL COMMENT '差异对象', + `expected` BIGINT NOT NULL DEFAULT 0 COMMENT '期望值', + `actual` BIGINT NOT NULL DEFAULT 0 COMMENT '实际值', + `diff` BIGINT NOT NULL DEFAULT 0 COMMENT '差异', + `reason` VARCHAR(500) NOT NULL COMMENT '差异说明', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `idx_fin_diff_report` (`report_id`, `level`), + KEY `idx_fin_diff_target` (`target`), + CONSTRAINT `ck_fin_diff_level` CHECK (`level` IN ('ORDER', 'SUBJECT', 'APP')) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='对账差异明细'; + +CREATE TABLE `fin_ticket` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `ticket_hash` CHAR(64) NOT NULL COMMENT 'ticket SHA-256', + `ticket_prefix` VARCHAR(12) NOT NULL COMMENT '展示前缀', + `app_code` VARCHAR(32) NOT NULL COMMENT '签发应用', + `business_user_id` VARCHAR(64) NOT NULL COMMENT '业务用户ID', + `redirect_uri` VARCHAR(500) DEFAULT NULL COMMENT '跳转地址', + `issued_ip` VARCHAR(45) DEFAULT NULL COMMENT '签发IP', + `expires_at` DATETIME NOT NULL COMMENT '过期时间', + `used_at` DATETIME DEFAULT NULL COMMENT '消费时间', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_ticket_hash` (`ticket_hash`), + KEY `idx_fin_ticket_app` (`app_code`, `expires_at`), + KEY `idx_fin_ticket_used` (`used_at`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='收银台一次性凭证'; + +CREATE TABLE `fin_rate_limit` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `bucket_key` VARCHAR(128) NOT NULL COMMENT '限流桶', + `window_start` DATETIME NOT NULL COMMENT '窗口起点', + `counter` INT NOT NULL DEFAULT 0 COMMENT '计数', + `expire_at` DATETIME NOT NULL COMMENT '过期清理时间', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_rate_bucket` (`bucket_key`, `window_start`), + KEY `idx_fin_rate_expire` (`expire_at`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='限流降级计数'; diff --git a/finance-server/src/main/resources/db/migration/V2__seed_config.sql b/finance-server/src/main/resources/db/migration/V2__seed_config.sql new file mode 100644 index 0000000..1faf791 --- /dev/null +++ b/finance-server/src/main/resources/db/migration/V2__seed_config.sql @@ -0,0 +1,16 @@ +-- 全局参数种子(与需求文档 §4.3.16 一致) +INSERT INTO `fin_config` (`id`, `config_key`, `config_value`, `description`, `risk`, `update_by`, `version_no`) +VALUES + (1, 'order.pending.timeout_hours', '24', '待确认订单超时关单小时数', 'NORMAL', 'system', 0), + (2, 'review.threshold_cent', '500000', '全局双人复核默认阈值(分)', 'NORMAL', 'system', 0), + (3, 'admin.lock.threshold', '5', '登录失败锁定次数', 'NORMAL', 'system', 0), + (4, 'admin.lock.minutes', '15', '锁定时长(分钟)', 'NORMAL', 'system', 0), + (5, 'ticket.ttl_minutes', '5', '一次性 ticket 有效期(分钟)', 'NORMAL', 'system', 0), + (6, 'token.ttl_seconds', '900', 'client token 默认有效期(秒)', 'NORMAL', 'system', 0), + (7, 'secret.rotate.grace_hours', '24', '密钥轮换默认宽限期(小时)', 'NORMAL', 'system', 0), + (8, 'charge.retry.max', '3', '扣费乐观锁冲突重试次数', 'NORMAL', 'system', 0), + (9, 'webhook.max_retry', '6', 'webhook 最大重试次数', 'NORMAL', 'system', 0), + (10, 'pii.mask.enabled', '1', 'PII 掩码开关,禁止改为 0', 'HIGH', 'system', 0), + (11, 'payee.account_name', '待配置', '收款户名', 'NORMAL', 'system', 0), + (12, 'payee.bank_name', '待配置', '开户行', 'NORMAL', 'system', 0), + (13, 'payee.account_no_masked', '****', '收款账号掩码展示', 'NORMAL', 'system', 0); diff --git a/finance-web/.env.development b/finance-web/.env.development new file mode 100644 index 0000000..9d019d0 --- /dev/null +++ b/finance-web/.env.development @@ -0,0 +1,4 @@ +# 本地演示环境:默认开启内置 Mock(无需后端即可完整操作) +VITE_APP_TITLE=财务中台 +VITE_USE_MOCK=1 +VITE_API_BASE=/api diff --git a/finance-web/.env.production b/finance-web/.env.production new file mode 100644 index 0000000..f624646 --- /dev/null +++ b/finance-web/.env.production @@ -0,0 +1,4 @@ +# 生产环境:必须关闭 Mock,走真实后端 +VITE_APP_TITLE=财务中台 +VITE_USE_MOCK=0 +VITE_API_BASE=/api diff --git a/finance-web/.gitignore b/finance-web/.gitignore new file mode 100644 index 0000000..7d02e2d --- /dev/null +++ b/finance-web/.gitignore @@ -0,0 +1,7 @@ +node_modules +dist +dist-ssr +*.local +.DS_Store +npm-debug.log* +.vite diff --git a/finance-web/index.html b/finance-web/index.html new file mode 100644 index 0000000..9dc85eb --- /dev/null +++ b/finance-web/index.html @@ -0,0 +1,15 @@ + + + + + + + + + 财务中台 · 中央计费平台 + + +
+ + + diff --git a/finance-web/package-lock.json b/finance-web/package-lock.json new file mode 100644 index 0000000..5d4562d --- /dev/null +++ b/finance-web/package-lock.json @@ -0,0 +1,2169 @@ +{ + "name": "finance-web", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "finance-web", + "version": "1.0.0", + "dependencies": { + "@element-plus/icons-vue": "^2.3.1", + "axios": "^1.7.9", + "echarts": "^5.5.1", + "element-plus": "^2.9.1", + "pinia": "^2.3.0", + "vue": "^3.5.13", + "vue-router": "^4.5.0" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "@vitejs/plugin-vue": "^5.2.1", + "typescript": "~5.7.2", + "vite": "^6.0.5", + "vue-tsc": "^2.2.0" + }, + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.11", + "resolved": "https://registry.npmmirror.com/@babel/helper-string-parser/-/helper-string-parser-7.29.11.tgz", + "integrity": "sha512-snZbO7MEDOof+hvNa97EjEY7qD7h2kwvQr5AJC3ZhQudKW5dnej6k3kP9NQV88hJwaS8vDqRLFo9rivLEhle2g==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmmirror.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.11", + "resolved": "https://registry.npmmirror.com/@babel/parser/-/parser-7.29.11.tgz", + "integrity": "sha512-OZ6+oaK7GMyg3IfCpj8JOmn8n+w2rJbDT0LLfVDTLb1ZFeKDh3AiNELgCMUw175IJHSkLl74hG0M0VLsvx+gag==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.11" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.11", + "resolved": "https://registry.npmmirror.com/@babel/types/-/types-7.29.11.tgz", + "integrity": "sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.11", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@ctrl/tinycolor": { + "version": "4.2.1", + "resolved": "https://registry.npmmirror.com/@ctrl/tinycolor/-/tinycolor-4.2.1.tgz", + "integrity": "sha512-Vh5uy9Y1JBMId6J1f68TMXnZrTCvNdo9Fu2k0d1YnJngR+sM5kWTKl441c/3TFs+cG0NWOjRWgQ/iaWhbYx+7A==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/@element-plus/icons-vue": { + "version": "2.3.2", + "resolved": "https://registry.npmmirror.com/@element-plus/icons-vue/-/icons-vue-2.3.2.tgz", + "integrity": "sha512-OzIuTaIfC8QXEPmJvB4Y4kw34rSXdCJzxcD1kFStBvr8bK6X1zQAYDo0CNMjojnfTqRQCJ0I7prlErcoRiET2A==", + "license": "MIT", + "peerDependencies": { + "vue": "^3.2.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@floating-ui/core": { + "version": "1.8.0", + "resolved": "https://registry.npmmirror.com/@floating-ui/core/-/core-1.8.0.tgz", + "integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.8.0", + "resolved": "https://registry.npmmirror.com/@floating-ui/dom/-/dom-1.8.0.tgz", + "integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==", + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.8.0", + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.12", + "resolved": "https://registry.npmmirror.com/@floating-ui/utils/-/utils-0.2.12.tgz", + "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", + "license": "MIT" + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmmirror.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "license": "MIT" + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmmirror.com/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@popperjs/core": { + "name": "@sxzz/popperjs-es", + "version": "2.11.8", + "resolved": "https://registry.npmmirror.com/@sxzz/popperjs-es/-/popperjs-es-2.11.8.tgz", + "integrity": "sha512-wOwESXvvED3S8xBmcPWHs2dUuzrE4XiZeFu7e1hROIJkm02a49N120pmOXxY33sBb6hArItm5W5tcg1cBtV+HQ==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/popperjs" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.65.1.tgz", + "integrity": "sha512-5coxNSjqOI2J3NkVhlp3u+zGcyjnowQFsU9sg7MMz4UPXY4Dv63kFGLt7ConXz9CNq2i0yuOJZAF/2RMrgI2OA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.65.1.tgz", + "integrity": "sha512-K0HFf6XMB3IYs+jDZ1/RRhZaVOwxNXrl0n4MDEyGDjuK7+B6K/nDJp8DCBitO3S1sK/fzNxAf9QZAny4AIUPtg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.65.1.tgz", + "integrity": "sha512-zkZrXYwNlIcSUmcwY2DpsaDHr0XjVUeQHCuSunG3eQD7/5Wn/DvI7OMUE8NRRweK87yG8ebJ1xGOzmwpMsbZQA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.65.1.tgz", + "integrity": "sha512-Zaed+R3cpkkA3aiNd7NO0GV5KFh/LVf8j6bGcoRdpoXkSm/mWH8M0oX2/3u/nyGcx/bHEovD9CzX+w9/gcpI4A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.65.1.tgz", + "integrity": "sha512-h12p3WJWhyJ9kir0zqAPr0rKNmBzOWIjoaOMT9OULs9KZQZCeOMKd+mGSvERjd9VxJYShd3zIxtrVxkYz6BEVA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.65.1.tgz", + "integrity": "sha512-yRBwh/5imKY4DydDulVtrjy8Jf7h7NQJUqZbgmZ3zFsCD9QqlnWvZ7RtEF+ecO1b+IukKjXlu5Bb9fehV3tIbg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.65.1.tgz", + "integrity": "sha512-1XuPiWYYaLE1UDOqhbKVOfsqxvfmFS/lYPSk92U1hEX1qRfSYH0hNeAlbxFIgjp4d6+YQmL95EPRgdvjbZEddA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.65.1.tgz", + "integrity": "sha512-Y3C5e55Yrf6p2r5rBcc4P9hFWVNi6oqWy/53I/AyCJJGlp3KRSpTP8eoUmVntchTbEnhgBgAgLO9flj9AvOdUw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.65.1.tgz", + "integrity": "sha512-Itj6coSswkYPIcVLczObXmwdplHNQQxyfnK1ppBg4czDaX8RiEzLKqU7EMc64BiBuiDZEUS+M93ktM18rv5llw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.65.1.tgz", + "integrity": "sha512-KeO8jTEqdrnhvcahufbimyMoI44vedRUp1bVz2QUnRX2vDm/hxzCPt5F8fERVD5fsHyTW/vXmCElT054VOSVOA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.65.1.tgz", + "integrity": "sha512-dDOz5VZZ+ZGnglpmET6VJefamWXFsgaVtuhSClf2/URZBp048jprD6z1hddsIMN6n1w+oUzGZEBp9u6Mlszsfg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.65.1.tgz", + "integrity": "sha512-JbfRKz8nJCuo8gn1Dqx8lQWEHw4qhZ3uRaHphw5vrSjnSptJTKTRC/bLKHh8QQMsEnhL4uq+bdg3tkiXbJ2q/A==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.65.1.tgz", + "integrity": "sha512-3oQpe1q0emSeCAssVHMQdOz5fz3PBH5my/Fr0ZekV2UMNL4ZiRa1ciikYlGQXyDkeqseYYv1InwOY8YPqY7RIQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.65.1.tgz", + "integrity": "sha512-nNV3HHi23o1LtpGGwH+Bav4hqnc4+klQtC96tSvCfvql8bLlNFTnTFiGl/jai2nve3eEr/vT2ocuyf+h+eMnYQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.65.1.tgz", + "integrity": "sha512-b5zab0FryBxuocuDeqOsYGAg2EzjKw4mKA6LjQXCyewXjGv/BXqACBsY2cO45xM4hV2weYtdjGThP2VB2ByAYg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.65.1.tgz", + "integrity": "sha512-Rh08xZakiUxKNgI3hbgH9mivlx478lSqckS9s+Oc3/TX1VrAH3W8z/5wpJXR/v5VjqcJ/jJNVBg64PU1+iQsTQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.65.1.tgz", + "integrity": "sha512-qDgtS6juN3/k97y4kcD6XLFpXEo4f6CnG8lTOGYwlhrUYTrMyhN0WHdZCPAW5rqS0MqQG7qI7dxnjugt6QB39Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.65.1.tgz", + "integrity": "sha512-44IKzBPqXXVm0kt1O+F5eW4juR5FyIxGNlFkpP8qwIDzucBsjM1HCbdYUQrQw8rU/g6HRl/tfBm0+Qq4H4Ro3w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.65.1.tgz", + "integrity": "sha512-tvYWZ/h2PCHs558Xu7B6LptuRCV8lXV2xI75ONMcldII1m2zlFwuI4BJZi9M6rSMkYqcPLLtPUPrjyqfbzLOdg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.65.1.tgz", + "integrity": "sha512-gdyeucgZCnei3pXwadKVTEAOgRx0B+c847DUPR/PdOMmp3olhfkYo6r0J4PzRFZB5ZICZQTxntyvgmWH5xT7rg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.65.1.tgz", + "integrity": "sha512-Wf/NEKdn2SAL4Nvt8HyDtdkseWTwiLbZEOoNYnEaHkbso0B9eHO42vKnZh+OYsn+IMhAMcWcuIwPlBOgOXsUzg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.65.1.tgz", + "integrity": "sha512-x9VSsDmsMsEWy4cr/mFeaEsXnVJ6Kc4NCAU/lCnwml3s7LQbZoa9+/qwc9etWHbuuDT5mYxdyyKUwo76njtjZw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.65.1.tgz", + "integrity": "sha512-RIDbiVvvLkN45mOFpbo6eYMgnuiBEB62BGR/0s4QJgGg2AvVxucDDNn67kpAcUoYyfmY8iX8/RifMcmxmmnejA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.65.1.tgz", + "integrity": "sha512-+KN8HIr88vN59JNxlrM2fMimzY43Y0lQB7+0xdVsFbvFCAA74CLKCdfzIHzzvndJryBc94Pm+MvwtukKjaS2ug==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.65.1.tgz", + "integrity": "sha512-+Y1Sd49cSDq60UOl8/U2HI0ebUvnSl/hDhMHQn+ouw17yb8fYwMWIazzJ4JFpSkjPE7sj5NTNSX9IoyEqcFfyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmmirror.com/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/lodash": { + "version": "4.17.27", + "resolved": "https://registry.npmmirror.com/@types/lodash/-/lodash-4.17.27.tgz", + "integrity": "sha512-VenMRv/eKNrspX9v3H4dbmjsrnCOYdYBG3kxXKk3dG6X+urBGcj2Prww3xw1U5K4FV/mE4h5GbWd0szEKf+9ew==", + "license": "MIT" + }, + "node_modules/@types/lodash-es": { + "version": "4.17.12", + "resolved": "https://registry.npmmirror.com/@types/lodash-es/-/lodash-es-4.17.12.tgz", + "integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==", + "license": "MIT", + "dependencies": { + "@types/lodash": "*" + } + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmmirror.com/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/web-bluetooth": { + "version": "0.0.21", + "resolved": "https://registry.npmmirror.com/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz", + "integrity": "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==", + "license": "MIT" + }, + "node_modules/@vitejs/plugin-vue": { + "version": "5.2.4", + "resolved": "https://registry.npmmirror.com/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz", + "integrity": "sha512-7Yx/SXSOcQq5HiiV3orevHUFn+pmMB4cgbEkDYgnkUWb0WfeQ/wa2yFv6D5ICiCQOVpjA7vYDXrC7AGO8yjDHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "peerDependencies": { + "vite": "^5.0.0 || ^6.0.0", + "vue": "^3.2.25" + } + }, + "node_modules/@volar/language-core": { + "version": "2.4.15", + "resolved": "https://registry.npmmirror.com/@volar/language-core/-/language-core-2.4.15.tgz", + "integrity": "sha512-3VHw+QZU0ZG9IuQmzT68IyN4hZNd9GchGPhbD9+pa8CVv7rnoOZwo7T8weIbrRmihqy3ATpdfXFnqRrfPVK6CA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/source-map": "2.4.15" + } + }, + "node_modules/@volar/source-map": { + "version": "2.4.15", + "resolved": "https://registry.npmmirror.com/@volar/source-map/-/source-map-2.4.15.tgz", + "integrity": "sha512-CPbMWlUN6hVZJYGcU/GSoHu4EnCHiLaXI9n8c9la6RaI9W5JHX+NqG+GSQcB0JdC2FIBLdZJwGsfKyBB71VlTg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@volar/typescript": { + "version": "2.4.15", + "resolved": "https://registry.npmmirror.com/@volar/typescript/-/typescript-2.4.15.tgz", + "integrity": "sha512-2aZ8i0cqPGjXb4BhkMsPYDkkuc2ZQ6yOpqwAuNwUoncELqoy5fRgOQtLR9gB0g902iS0NAkvpIzs27geVyVdPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.15", + "path-browserify": "^1.0.1", + "vscode-uri": "^3.0.8" + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.5.44", + "resolved": "https://registry.npmmirror.com/@vue/compiler-core/-/compiler-core-3.5.44.tgz", + "integrity": "sha512-k34nCytbK8PQ1gR2mGROYOw6Pnv/mumqIdrZ3x2tbyXZDWm7ViKGLTfdB+DRrWqEQsLgGJvn0WN9jBif5zCTLQ==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.9", + "@vue/shared": "3.5.44", + "entities": "^7.0.1", + "estree-walker": "^2.0.2", + "source-map-js": "^1.2.2" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.5.44", + "resolved": "https://registry.npmmirror.com/@vue/compiler-dom/-/compiler-dom-3.5.44.tgz", + "integrity": "sha512-W5AoBFWdw1lQAKiHowkfgFKFab82oSRT6sGsPfw/q1GRjsy/ZJFLHGhJyBRIFN9APLTUduDH9U2JAiPOIyKuYg==", + "license": "MIT", + "dependencies": { + "@vue/compiler-core": "3.5.44", + "@vue/shared": "3.5.44" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.5.44", + "resolved": "https://registry.npmmirror.com/@vue/compiler-sfc/-/compiler-sfc-3.5.44.tgz", + "integrity": "sha512-dzHmQ4jXTpdr5FjIQUeykVakN/uzqFbUo9/C5ikBFg3a3PeM6uRxeczx1ZbXBML0/zJstEh3ygYipzR5Z7b2Pw==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.9", + "@vue/compiler-core": "3.5.44", + "@vue/compiler-dom": "3.5.44", + "@vue/compiler-ssr": "3.5.44", + "@vue/shared": "3.5.44", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.21", + "postcss": "^8.5.29", + "source-map-js": "^1.2.2" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.5.44", + "resolved": "https://registry.npmmirror.com/@vue/compiler-ssr/-/compiler-ssr-3.5.44.tgz", + "integrity": "sha512-xr5gb1JVHlfXJwSlRz1FeP6uxoazdzHuMTVLE7up+4Vrqxk219CvxLPxD9NXBt47yvZW7+p4DXfyp4O1fkByIA==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.44", + "@vue/shared": "3.5.44" + } + }, + "node_modules/@vue/compiler-vue2": { + "version": "2.7.16", + "resolved": "https://registry.npmmirror.com/@vue/compiler-vue2/-/compiler-vue2-2.7.16.tgz", + "integrity": "sha512-qYC3Psj9S/mfu9uVi5WvNZIzq+xnXMhOwbTFKKDD7b1lhpnn71jXSFdTQ+WsIEk0ONCd7VV2IMm7ONl6tbQ86A==", + "dev": true, + "license": "MIT", + "dependencies": { + "de-indent": "^1.0.2", + "he": "^1.2.0" + } + }, + "node_modules/@vue/devtools-api": { + "version": "6.6.4", + "resolved": "https://registry.npmmirror.com/@vue/devtools-api/-/devtools-api-6.6.4.tgz", + "integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==", + "license": "MIT" + }, + "node_modules/@vue/language-core": { + "version": "2.2.12", + "resolved": "https://registry.npmmirror.com/@vue/language-core/-/language-core-2.2.12.tgz", + "integrity": "sha512-IsGljWbKGU1MZpBPN+BvPAdr55YPkj2nB/TBNGNC32Vy2qLG25DYu/NBN2vNtZqdRbTRjaoYrahLrToim2NanA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.15", + "@vue/compiler-dom": "^3.5.0", + "@vue/compiler-vue2": "^2.7.16", + "@vue/shared": "^3.5.0", + "alien-signals": "^1.0.3", + "minimatch": "^9.0.3", + "muggle-string": "^0.4.1", + "path-browserify": "^1.0.1" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@vue/reactivity": { + "version": "3.5.44", + "resolved": "https://registry.npmmirror.com/@vue/reactivity/-/reactivity-3.5.44.tgz", + "integrity": "sha512-u+QJdKeBBEADkPdevsL+6E12QlYVfBD8Zcw5qjDQKtamI6l14KyqazJMobhCKelhWN5zpyKUiEDoTyHE93cqWw==", + "license": "MIT", + "dependencies": { + "@vue/shared": "3.5.44" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.5.44", + "resolved": "https://registry.npmmirror.com/@vue/runtime-core/-/runtime-core-3.5.44.tgz", + "integrity": "sha512-uEa/ndwjhrrhnOfb2p+sZy6zeoamJOISqaLSJGk/8R6nABT1ZldpzcJoPzKj+zHVomVBPcmQYyC2r4LtvDV6CQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.44", + "@vue/shared": "3.5.44" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.5.44", + "resolved": "https://registry.npmmirror.com/@vue/runtime-dom/-/runtime-dom-3.5.44.tgz", + "integrity": "sha512-3fc4ARcXVhVBaJ3ujWiNZJARD6pkyRcwG+ZYhMzjKtKUp7MAY0HLwr7r3Smep3Li6ZaWT6ewdmx8XqdaD5oNZg==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.44", + "@vue/runtime-core": "3.5.44", + "@vue/shared": "3.5.44", + "csstype": "^3.2.3" + } + }, + "node_modules/@vue/server-renderer": { + "version": "3.5.44", + "resolved": "https://registry.npmmirror.com/@vue/server-renderer/-/server-renderer-3.5.44.tgz", + "integrity": "sha512-R4S1UoH4h5Frrauv8Z5XE5TxV9oBiUSgWIC4TyVK1FK+RocRnOLwFA5Xcmo2011RlgJp+AbZCnw6afrhlgRuUQ==", + "license": "MIT", + "dependencies": { + "@vue/compiler-ssr": "3.5.44", + "@vue/runtime-dom": "3.5.44", + "@vue/shared": "3.5.44" + } + }, + "node_modules/@vue/shared": { + "version": "3.5.44", + "resolved": "https://registry.npmmirror.com/@vue/shared/-/shared-3.5.44.tgz", + "integrity": "sha512-H82XLH0DjmSOdbEwO15x3QTo1f5PWEtv237eLpYKc0mqLu+B8hnq16lFWmuBmNurkeiG3wr+oM1FhOll/YVFRg==", + "license": "MIT" + }, + "node_modules/@vueuse/core": { + "version": "15.0.0", + "resolved": "https://registry.npmmirror.com/@vueuse/core/-/core-15.0.0.tgz", + "integrity": "sha512-Zv67h5mrk7YHDJsRObx+DXaCBz6RKBUpxqLesJ+3xZNPG6yuQs7ja7kg3veFrrouYLWAqydQ7CwGEbLVxB43Ng==", + "license": "MIT", + "dependencies": { + "@types/web-bluetooth": "^0.0.21", + "@vueuse/metadata": "15.0.0", + "@vueuse/shared": "15.0.0" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "vue": "^3.5.0" + } + }, + "node_modules/@vueuse/metadata": { + "version": "15.0.0", + "resolved": "https://registry.npmmirror.com/@vueuse/metadata/-/metadata-15.0.0.tgz", + "integrity": "sha512-sfWE5LADAKJ0KnjtGliMdSN8Ij/L7uP6rXIZlgPloAI4zvvefbw6H5Lt7KJA6RqQOYgVqWF5Guj50HHMIzygBg==", + "license": "MIT", + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@vueuse/shared": { + "version": "15.0.0", + "resolved": "https://registry.npmmirror.com/@vueuse/shared/-/shared-15.0.0.tgz", + "integrity": "sha512-vbNXhGrbV53xPOMSyOzMHQRvhMgZf7oNDw2RChUetVxwTIEkInQ1joZ9JbT0G3z2n2AJNjvmCWeM9ySYrnvogA==", + "license": "MIT", + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "vue": "^3.5.0" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmmirror.com/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/alien-signals": { + "version": "1.0.13", + "resolved": "https://registry.npmmirror.com/alien-signals/-/alien-signals-1.0.13.tgz", + "integrity": "sha512-OGj9yyTnJEttvzhTUWuscOvtqxq5vrhF7vL9oS0xJ2mK0ItPYP1/y+vCFebfxoEyAz0++1AIwJ5CMr+Fk3nDmg==", + "dev": true, + "license": "MIT" + }, + "node_modules/async-validator": { + "version": "4.2.5", + "resolved": "https://registry.npmmirror.com/async-validator/-/async-validator-4.2.5.tgz", + "integrity": "sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==", + "license": "MIT" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmmirror.com/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/axios": { + "version": "1.21.0", + "resolved": "https://registry.npmmirror.com/axios/-/axios-1.21.0.tgz", + "integrity": "sha512-YCzXMB53Q9PZBsh7yN7wtapit4WepwcHS2fP8QhGsBxSz5YtgYobV7GGlWlAJi+RxfU77GQTQi2DSLUma42EYA==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.16.0", + "form-data": "^4.0.6", + "https-proxy-agent": "^5.0.1", + "proxy-from-env": "^2.1.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "2.1.7", + "resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmmirror.com/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "license": "MIT" + }, + "node_modules/dayjs": { + "version": "1.11.23", + "resolved": "https://registry.npmmirror.com/dayjs/-/dayjs-1.11.23.tgz", + "integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==", + "license": "MIT" + }, + "node_modules/de-indent": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/de-indent/-/de-indent-1.0.2.tgz", + "integrity": "sha512-e/1zu3xH5MQryN2zdVaF0OrdNLUbvWxzMbi+iNA6Bky7l1RoP8a2fIbRocyHclXt/arDrrR6lL3TqFD9pMQTsg==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmmirror.com/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/echarts": { + "version": "5.6.0", + "resolved": "https://registry.npmmirror.com/echarts/-/echarts-5.6.0.tgz", + "integrity": "sha512-oTbVTsXfKuEhxftHqL5xprgLoc0k7uScAwtryCgWF6hPYFLRwOUHiFmHGCBKP5NPFNkDVopOieyUqYGH8Fa3kA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "2.3.0", + "zrender": "5.6.1" + } + }, + "node_modules/element-plus": { + "version": "2.14.7", + "resolved": "https://registry.npmmirror.com/element-plus/-/element-plus-2.14.7.tgz", + "integrity": "sha512-lrG7pZyCS+mpCNVpzxxyu5r35+T6V0hzkAeIwn7HA6to772XSTHKuYCZG51OfzlqaxGbNegLxs650zAF1j43gA==", + "license": "MIT", + "dependencies": { + "@ctrl/tinycolor": "^4.2.1", + "@element-plus/icons-vue": "^2.3.2", + "@floating-ui/dom": "^1.8.0", + "@popperjs/core": "npm:@sxzz/popperjs-es@^2.11.8", + "@types/lodash": "^4.17.24", + "@types/lodash-es": "^4.17.12", + "@vueuse/core": "15.0.0", + "async-validator": "^4.2.5", + "dayjs": "^1.11.20", + "lodash": "^4.18.1", + "lodash-es": "^4.18.1", + "lodash-unified": "^1.0.3", + "memoize-one": "^6.0.0", + "normalize-wheel-es": "^1.2.0", + "vue-component-type-helpers": "^3.3.11" + }, + "peerDependencies": { + "vue": "^3.3.7" + } + }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmmirror.com/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmmirror.com/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmmirror.com/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmmirror.com/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmmirror.com/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmmirror.com/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/follow-redirects": { + "version": "1.16.2", + "resolved": "https://registry.npmmirror.com/follow-redirects/-/follow-redirects-1.16.2.tgz", + "integrity": "sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmmirror.com/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmmirror.com/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmmirror.com/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "dev": true, + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmmirror.com/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmmirror.com/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "license": "MIT" + }, + "node_modules/lodash-es": { + "version": "4.18.1", + "resolved": "https://registry.npmmirror.com/lodash-es/-/lodash-es-4.18.1.tgz", + "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==", + "license": "MIT" + }, + "node_modules/lodash-unified": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/lodash-unified/-/lodash-unified-1.0.3.tgz", + "integrity": "sha512-WK9qSozxXOD7ZJQlpSqOT+om2ZfcT4yO+03FuzAHD0wF6S0l0090LRPDx3vhTTLZ8cFKpBn+IOcVXK6qOcIlfQ==", + "license": "MIT", + "peerDependencies": { + "@types/lodash-es": "*", + "lodash": "*", + "lodash-es": "*" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/memoize-one": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/memoize-one/-/memoize-one-6.0.0.tgz", + "integrity": "sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==", + "license": "MIT" + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmmirror.com/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmmirror.com/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimatch": { + "version": "9.0.9", + "resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-9.0.9.tgz", + "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.2" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/muggle-string": { + "version": "0.4.1", + "resolved": "https://registry.npmmirror.com/muggle-string/-/muggle-string-0.4.1.tgz", + "integrity": "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/normalize-wheel-es": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/normalize-wheel-es/-/normalize-wheel-es-1.2.0.tgz", + "integrity": "sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw==", + "license": "BSD-3-Clause" + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pinia": { + "version": "2.3.1", + "resolved": "https://registry.npmmirror.com/pinia/-/pinia-2.3.1.tgz", + "integrity": "sha512-khUlZSwt9xXCaTbbxFYBKDc/bWAGWJjOgvxETwkTN7KRm66EeT1ZdZj6i2ceh9sP2Pzqsbc704r2yngBrxBVug==", + "license": "MIT", + "dependencies": { + "@vue/devtools-api": "^6.6.3", + "vue-demi": "^0.14.10" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "typescript": ">=4.4.4", + "vue": "^2.7.0 || ^3.5.11" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/proxy-from-env": { + "version": "2.1.0", + "resolved": "https://registry.npmmirror.com/proxy-from-env/-/proxy-from-env-2.1.0.tgz", + "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/rollup": { + "version": "4.65.1", + "resolved": "https://registry.npmmirror.com/rollup/-/rollup-4.65.1.tgz", + "integrity": "sha512-HzD4IdphaPMvuAacnL/vtoq5B8FwqewKvxTtqYibWvP6VDyZ+UsTtlw5F8HIOIIpLQAkN2NOP/0sM3puo9xN/A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.65.1", + "@rollup/rollup-android-arm64": "4.65.1", + "@rollup/rollup-darwin-arm64": "4.65.1", + "@rollup/rollup-darwin-x64": "4.65.1", + "@rollup/rollup-freebsd-arm64": "4.65.1", + "@rollup/rollup-freebsd-x64": "4.65.1", + "@rollup/rollup-linux-arm-gnueabihf": "4.65.1", + "@rollup/rollup-linux-arm-musleabihf": "4.65.1", + "@rollup/rollup-linux-arm64-gnu": "4.65.1", + "@rollup/rollup-linux-arm64-musl": "4.65.1", + "@rollup/rollup-linux-loong64-gnu": "4.65.1", + "@rollup/rollup-linux-loong64-musl": "4.65.1", + "@rollup/rollup-linux-ppc64-gnu": "4.65.1", + "@rollup/rollup-linux-ppc64-musl": "4.65.1", + "@rollup/rollup-linux-riscv64-gnu": "4.65.1", + "@rollup/rollup-linux-riscv64-musl": "4.65.1", + "@rollup/rollup-linux-s390x-gnu": "4.65.1", + "@rollup/rollup-linux-x64-gnu": "4.65.1", + "@rollup/rollup-linux-x64-musl": "4.65.1", + "@rollup/rollup-openbsd-x64": "4.65.1", + "@rollup/rollup-openharmony-arm64": "4.65.1", + "@rollup/rollup-win32-arm64-msvc": "4.65.1", + "@rollup/rollup-win32-ia32-msvc": "4.65.1", + "@rollup/rollup-win32-x64-gnu": "4.65.1", + "@rollup/rollup-win32-x64-msvc": "4.65.1", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tslib": { + "version": "2.3.0", + "resolved": "https://registry.npmmirror.com/tslib/-/tslib-2.3.0.tgz", + "integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==", + "license": "0BSD" + }, + "node_modules/typescript": { + "version": "5.7.3", + "resolved": "https://registry.npmmirror.com/typescript/-/typescript-5.7.3.tgz", + "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "6.4.5", + "resolved": "https://registry.npmmirror.com/vite/-/vite-6.4.5.tgz", + "integrity": "sha512-4enwjFfi4IwtEh0w+jPzpLVOFQiPHmmzPxcHXQOyEur47o6u0jE573DmGpjA+7irXoMLYRZD5ZaFUEneS3abPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vscode-uri": { + "version": "3.2.0", + "resolved": "https://registry.npmmirror.com/vscode-uri/-/vscode-uri-3.2.0.tgz", + "integrity": "sha512-m2gXo3bn0G1kT9InzMf07fTbqMbGtyckj3bH5ktLO+1Ssv+yiATZ4dhwaQv9UZWxJh6E9IFGnQyjgWVDWVBDrg==", + "dev": true, + "license": "MIT" + }, + "node_modules/vue": { + "version": "3.5.44", + "resolved": "https://registry.npmmirror.com/vue/-/vue-3.5.44.tgz", + "integrity": "sha512-dvvmaOCG7lAMkJTPqPwWeGMsPS6DIsFsfZDUgBp9V6mHf9b3+/wyVwYR4Es+WV6uJC0FKRxp81Obcq0ZwUcGFQ==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.44", + "@vue/compiler-sfc": "3.5.44", + "@vue/runtime-dom": "3.5.44", + "@vue/server-renderer": "3.5.44", + "@vue/shared": "3.5.44" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/vue-component-type-helpers": { + "version": "3.3.13", + "resolved": "https://registry.npmmirror.com/vue-component-type-helpers/-/vue-component-type-helpers-3.3.13.tgz", + "integrity": "sha512-02KCxSmKDhIITjKyJ4QT5csP6L0WoRborLqY/34a40+S9uvMvdNgMV0yVjO3p2Gkz3ZoPmFz/0JsGHacwJYTxw==", + "license": "MIT" + }, + "node_modules/vue-demi": { + "version": "0.14.10", + "resolved": "https://registry.npmmirror.com/vue-demi/-/vue-demi-0.14.10.tgz", + "integrity": "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "vue-demi-fix": "bin/vue-demi-fix.js", + "vue-demi-switch": "bin/vue-demi-switch.js" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "@vue/composition-api": "^1.0.0-rc.1", + "vue": "^3.0.0-0 || ^2.6.0" + }, + "peerDependenciesMeta": { + "@vue/composition-api": { + "optional": true + } + } + }, + "node_modules/vue-router": { + "version": "4.6.4", + "resolved": "https://registry.npmmirror.com/vue-router/-/vue-router-4.6.4.tgz", + "integrity": "sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg==", + "license": "MIT", + "dependencies": { + "@vue/devtools-api": "^6.6.4" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "vue": "^3.5.0" + } + }, + "node_modules/vue-tsc": { + "version": "2.2.12", + "resolved": "https://registry.npmmirror.com/vue-tsc/-/vue-tsc-2.2.12.tgz", + "integrity": "sha512-P7OP77b2h/Pmk+lZdJ0YWs+5tJ6J2+uOQPo7tlBnY44QqQSPYvS0qVT4wqDJgwrZaLe47etJLLQRFia71GYITw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/typescript": "2.4.15", + "@vue/language-core": "2.2.12" + }, + "bin": { + "vue-tsc": "bin/vue-tsc.js" + }, + "peerDependencies": { + "typescript": ">=5.0.0" + } + }, + "node_modules/zrender": { + "version": "5.6.1", + "resolved": "https://registry.npmmirror.com/zrender/-/zrender-5.6.1.tgz", + "integrity": "sha512-OFXkDJKcrlx5su2XbzJvj/34Q3m6PvyCZkVPHGYpcCJ52ek4U/ymZyfuV1nKE23AyBJ51E/6Yr0mhZ7xGTO4ag==", + "license": "BSD-3-Clause", + "dependencies": { + "tslib": "2.3.0" + } + } + } +} diff --git a/finance-web/package.json b/finance-web/package.json new file mode 100644 index 0000000..a1972fd --- /dev/null +++ b/finance-web/package.json @@ -0,0 +1,32 @@ +{ + "name": "finance-web", + "version": "1.0.0", + "private": true, + "type": "module", + "description": "中央计费平台(资金中台)前端", + "engines": { + "node": ">=20.19.0" + }, + "scripts": { + "dev": "vite", + "build": "vue-tsc --noEmit && vite build", + "type-check": "vue-tsc --noEmit", + "preview": "vite preview" + }, + "dependencies": { + "@element-plus/icons-vue": "^2.3.1", + "axios": "^1.7.9", + "echarts": "^5.5.1", + "element-plus": "^2.9.1", + "pinia": "^2.3.0", + "vue": "^3.5.13", + "vue-router": "^4.5.0" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "@vitejs/plugin-vue": "^5.2.1", + "typescript": "~5.7.2", + "vite": "^6.0.5", + "vue-tsc": "^2.2.0" + } +} diff --git a/finance-web/src/App.vue b/finance-web/src/App.vue new file mode 100644 index 0000000..9f7a593 --- /dev/null +++ b/finance-web/src/App.vue @@ -0,0 +1,5 @@ + + + diff --git a/finance-web/src/api/auth.ts b/finance-web/src/api/auth.ts new file mode 100644 index 0000000..25c9a35 --- /dev/null +++ b/finance-web/src/api/auth.ts @@ -0,0 +1,21 @@ +import { http } from '@/utils/http' +import type { AdminInfo, LoginResult } from '@/types' + +export interface LoginPayload { + username: string + password: string + totp: string +} + +export interface ProfileResult { + admin: AdminInfo + permissions: string[] +} + +export const authApi = { + login: (payload: LoginPayload) => http.post('/admin/login', payload, { silent: true }), + logout: () => http.post('/admin/logout'), + profile: () => http.get('/admin/profile', undefined, { silent: true }), + changePassword: (payload: { oldPassword: string; newPassword: string }) => + http.post('/admin/password/change', payload, { silent: true }), +} diff --git a/finance-web/src/api/core.ts b/finance-web/src/api/core.ts new file mode 100644 index 0000000..ff26c48 --- /dev/null +++ b/finance-web/src/api/core.ts @@ -0,0 +1,168 @@ +import { http } from '@/utils/http' +import type { + AccountInfo, + AppInfo, + AppTokenInfo, + OrderInfo, + PageResult, + RefundInfo, + TransactionInfo, +} from '@/types' + +export interface PageQuery { + page?: number + pageSize?: number +} + +export interface AppPayload { + appCode?: string + appName?: string + allowedRedirectHosts?: string + webhookUrl?: string + tokenTtlSeconds?: number +} + +export interface AccountQuery extends PageQuery { + appCode?: string + keyword?: string + minBalance?: number +} + +export interface OrderQuery extends PageQuery { + appCode?: string + status?: string + orderType?: string + keyword?: string + from?: string + to?: string +} + +export interface TransactionQuery extends PageQuery { + appCode?: string + type?: string + keyword?: string + from?: string + to?: string +} + +export interface RefundQuery extends PageQuery { + appCode?: string + status?: string + keyword?: string + from?: string + to?: string +} + +export interface Approver { + id: number + username: string + role: string +} + +export const appApi = { + list: () => http.get('/admin/apps'), + create: (payload: AppPayload) => + http.post<{ app: AppInfo; clientSecret: string }>('/admin/apps', payload, { silent: true }), + update: (appCode: string, payload: AppPayload) => http.put(`/admin/apps/${appCode}`, payload), + rotateSecret: (appCode: string, graceHours: number) => + http.post<{ clientSecret: string; expiresAt: string }>(`/admin/apps/${appCode}/secret/rotate`, { graceHours }, { silent: true }), + revokePrevSecret: (appCode: string) => http.post(`/admin/apps/${appCode}/secret/revoke-prev`), + toggle: (appCode: string, enabled: number) => http.post(`/admin/apps/${appCode}/toggle`, { enabled }), + listTokens: (appCode: string) => http.get(`/admin/apps/${appCode}/tokens`), + revokeTokens: (appCode: string, tokenId?: number) => + http.post<{ revoked: number }>(`/admin/apps/${appCode}/tokens/revoke`, { tokenId }), +} + +export interface AccountDetail { + account: AccountInfo + vip: { + planCode: string + planName: string + vipUntil: string + effective: boolean + freeDeduction: number + } | null + transactions: TransactionInfo[] +} + +export interface AdjustPayload { + appCode: string + businessUserId: string + amount: number + direction: 'IN' | 'OUT' + reason: string + secondApproverId: number + totp: string +} + +export const accountApi = { + list: (query: AccountQuery) => http.get>('/admin/accounts', query), + detail: (id: number) => http.get(`/admin/accounts/${id}`), + transactions: (id: number, query: PageQuery) => + http.get>(`/admin/accounts/${id}/transactions`, query), + adjust: (payload: AdjustPayload) => http.post('/admin/accounts/adjust', payload, { silent: true }), +} + +export interface ConfirmPayload { + voucherNo: string + receiveAt?: string + secondApproverId?: number + totp: string +} + +export interface CancelPayload { + reason: string + totp: string +} + +export interface OrderDetail { + order: OrderInfo + refunds: RefundInfo[] + cashFlows: Array<{ + id: number + direction: 'IN' | 'OUT' + amountCent: number + receivedAt: string + voucherNo: string + remark: string + }> +} + +export const orderApi = { + list: (query: OrderQuery) => http.get>('/admin/orders', query), + detail: (id: number) => http.get(`/admin/orders/${id}`), + confirm: (id: number, payload: ConfirmPayload) => + http.post(`/admin/orders/${id}/confirm`, payload, { silent: true }), + cancel: (id: number, payload: CancelPayload) => + http.post(`/admin/orders/${id}/cancel`, payload, { silent: true }), + export: (query: OrderQuery) => http.get('/admin/orders/export', query), + approvers: () => http.get('/admin/approvers'), +} + +export interface RefundCreatePayload { + orderId: number + amountCent: number + voucherNo?: string + reason: string + idempotencyKey: string + totp: string +} + +export interface RefundReviewPayload { + action: 'approve' | 'reject' + voucherNo?: string + reason?: string + totp: string +} + +export const refundApi = { + list: (query: RefundQuery) => http.get>('/admin/refunds', query), + create: (payload: RefundCreatePayload) => http.post('/admin/refunds', payload, { silent: true }), + review: (id: number, payload: RefundReviewPayload) => + http.post(`/admin/refunds/${id}/review`, payload, { silent: true }), +} + +export const transactionApi = { + list: (query: TransactionQuery) => http.get>('/admin/transactions', query), + export: (query: TransactionQuery) => http.get('/admin/transactions/export', query), +} diff --git a/finance-web/src/api/pay.ts b/finance-web/src/api/pay.ts new file mode 100644 index 0000000..91d8542 --- /dev/null +++ b/finance-web/src/api/pay.ts @@ -0,0 +1,44 @@ +import { http } from '@/utils/http' +import type { OrderStatus, PayOrder, PayPreview } from '@/types' + +export interface PayPreviewQuery { + appCode: string + ticket: string + redirectUri?: string +} + +export interface PayCreatePayload { + appCode: string + ticket: string + orderType: 'recharge' | 'vip' + amountCent?: number + planCode?: string + redirectUri?: string + /** 幂等键:同一次下单的重复提交必须复用同一个值,服务端据此返回首次结果 */ + idempotencyKey?: string +} + +export interface PayStatus { + outTradeNo: string + status: OrderStatus + amountCent: number + pointsGained: number + paidAt: string | null + expiresAt: string +} + +export interface DemoTicket { + appCode: string + ticket: string + businessUserId: string + username: string + redirectUri: string + expiresAt: string +} + +export const payApi = { + preview: (query: PayPreviewQuery) => http.get('/pay/preview', query, { silent: true }), + createOrder: (payload: PayCreatePayload) => http.post('/pay/orders', payload, { silent: true }), + status: (outTradeNo: string) => http.get(`/pay/orders/${encodeURIComponent(outTradeNo)}/status`, undefined, { silent: true }), + demoTicket: (appCode: string) => http.get('/pay/demo-ticket', { appCode }, { silent: true }), +} diff --git a/finance-web/src/api/settings.ts b/finance-web/src/api/settings.ts new file mode 100644 index 0000000..2f820be --- /dev/null +++ b/finance-web/src/api/settings.ts @@ -0,0 +1,74 @@ +import { http } from '@/utils/http' +import type { AppPolicy, ConfigItem, PageResult, PricingItem, ReconcileReport, VipHolder, VipPlan } from '@/types' +import type { PageQuery } from './core' + +export interface VipPlanPayload { + appCode: string + planCode?: string + planName?: string + durationDays: number + priceCent: number + freeDeduction: number + totp?: string +} + +export interface VipHolderQuery extends PageQuery { + appCode?: string + keyword?: string +} + +export const vipApi = { + plans: (appCode?: string) => http.get('/admin/vip-plans', appCode ? { appCode } : undefined), + createPlan: (payload: VipPlanPayload) => http.post('/admin/vip-plans', payload, { silent: true }), + updatePlan: (id: number, payload: VipPlanPayload) => http.put(`/admin/vip-plans/${id}`, payload, { silent: true }), + togglePlan: (id: number, enabled: number) => http.post(`/admin/vip-plans/${id}/toggle`, { enabled }), + holders: (query: VipHolderQuery) => http.get>('/admin/vips', query), +} + +export interface PricingPayload { + pointsPerYuan: number + enabled: number + totp: string +} + +export interface PolicyPayload { + minCost: number + maxPointsPerCharge: number + vipExempt: number + failedStrategy: 'none' | 'actual' + dualControlThresholdCent: number + totp: string +} + +export const pricingApi = { + list: () => http.get('/admin/pricing'), + save: (appCode: string, payload: PricingPayload) => + http.put(`/admin/pricing/${appCode}`, payload, { silent: true }), + policies: () => http.get('/admin/policies'), + savePolicy: (appCode: string, payload: PolicyPayload) => + http.put(`/admin/policies/${appCode}`, payload, { silent: true }), +} + +export interface ReconcileRunPayload { + appCode: string + windowStart: string + windowEnd: string +} + +export const reconcileApi = { + reports: () => http.get('/admin/reconcile/reports'), + detail: (id: string) => http.get(`/admin/reconcile/reports/${id}`), + run: (payload: ReconcileRunPayload) => http.post('/admin/reconcile/run', payload), +} + +export interface ConfigPayload { + value: string + reason: string + totp: string +} + +export const configApi = { + list: () => http.get('/admin/configs'), + update: (key: string, payload: ConfigPayload) => + http.put(`/admin/configs/${encodeURIComponent(key)}`, payload, { silent: true }), +} diff --git a/finance-web/src/api/system.ts b/finance-web/src/api/system.ts new file mode 100644 index 0000000..d1c9de8 --- /dev/null +++ b/finance-web/src/api/system.ts @@ -0,0 +1,71 @@ +import { http } from '@/utils/http' +import type { + AdminInfo, + AuditLog, + ChainVerifyResult, + DashboardSummary, + AppDistribution, + PageResult, + Role, + TrendPoint, + WebhookDelivery, +} from '@/types' +import type { PageQuery } from './core' + +export interface AdminCreatePayload { + username: string + role: Role + totp: string +} + +export interface AdminUpdatePayload { + role: Role +} + +export interface AuditQuery extends PageQuery { + actor?: string + action?: string + result?: string + keyword?: string + from?: string + to?: string +} + +export interface WebhookQuery extends PageQuery { + appCode?: string + status?: string + keyword?: string + from?: string + to?: string +} + +export const adminApi = { + list: () => http.get('/admin/admins'), + create: (payload: AdminCreatePayload) => + http.post<{ admin: AdminInfo; initialPassword: string }>('/admin/admins', payload, { silent: true }), + updateRole: (id: number, payload: AdminUpdatePayload) => http.put(`/admin/admins/${id}`, payload), + toggle: (id: number, enabled: number) => http.post(`/admin/admins/${id}/toggle`, { enabled }), + resetPassword: (id: number, totp: string) => + http.post<{ tempPassword: string }>(`/admin/admins/${id}/reset-password`, { totp }, { silent: true }), + resetTotp: (id: number, totp: string) => + http.post<{ message: string }>(`/admin/admins/${id}/reset-totp`, { totp }, { silent: true }), +} + +export const auditApi = { + list: (query: AuditQuery) => http.get>('/admin/audit-logs', query), + detail: (id: number) => http.get(`/admin/audit-logs/${id}`), + verify: () => http.post('/admin/audit-logs/verify'), + export: (query: AuditQuery) => http.get('/admin/audit-logs/export', query), +} + +export const webhookApi = { + list: (query: WebhookQuery) => http.get>('/admin/webhooks', query), + replay: (id: number, totp: string) => + http.post(`/admin/webhooks/${id}/replay`, { totp }, { silent: true }), +} + +export const dashboardApi = { + summary: () => http.get('/admin/dashboard/summary'), + trend: () => http.get('/admin/dashboard/trend'), + distribution: () => http.get('/admin/dashboard/distribution'), +} diff --git a/finance-web/src/components/EChart.vue b/finance-web/src/components/EChart.vue new file mode 100644 index 0000000..9c497dd --- /dev/null +++ b/finance-web/src/components/EChart.vue @@ -0,0 +1,38 @@ + + + diff --git a/finance-web/src/components/ExportButton.vue b/finance-web/src/components/ExportButton.vue new file mode 100644 index 0000000..a4b98db --- /dev/null +++ b/finance-web/src/components/ExportButton.vue @@ -0,0 +1,48 @@ + + + diff --git a/finance-web/src/components/PageHeader.vue b/finance-web/src/components/PageHeader.vue new file mode 100644 index 0000000..bff218a --- /dev/null +++ b/finance-web/src/components/PageHeader.vue @@ -0,0 +1,18 @@ + + + diff --git a/finance-web/src/components/StatCard.vue b/finance-web/src/components/StatCard.vue new file mode 100644 index 0000000..d353bde --- /dev/null +++ b/finance-web/src/components/StatCard.vue @@ -0,0 +1,71 @@ + + + + + diff --git a/finance-web/src/constants/index.ts b/finance-web/src/constants/index.ts new file mode 100644 index 0000000..1b40785 --- /dev/null +++ b/finance-web/src/constants/index.ts @@ -0,0 +1,89 @@ +import type { OrderStatus, OrderType, PayMethod, RefundStatus, Role, TxType, WebhookStatus } from '@/types' + +export const APP_TITLE = import.meta.env.VITE_APP_TITLE || '财务中台' + +export const ROLE_LABEL: Record = { + SUPER_ADMIN: '超级管理员', + FINANCE: '财务专员', + AUDITOR: '审计员', +} + +export const ROLE_DESC: Record = { + SUPER_ADMIN: '管配置与账号,不可确认到账', + FINANCE: '管资金操作,不可修改定价', + AUDITOR: '只读查询与审计', +} + +/** 权限码与设计文档 §8 一致,前端仅做体验层控制,服务端必须二次校验 */ +export const PERM = { + view: 'fin:view', + export: 'fin:export', + appManage: 'fin:app:manage', + pricingEdit: 'fin:pricing:edit', + vipManage: 'fin:vip:manage', + adminManage: 'fin:admin:manage', + configEdit: 'fin:config:edit', + auditView: 'fin:audit:view', + webhookManage: 'fin:webhook:manage', + accountAdjust: 'fin:account:adjust', + rechargeConfirm: 'fin:recharge:confirm', + refundCreate: 'fin:refund:create', + refundReview: 'fin:refund:review', + orderCancel: 'fin:order:cancel', + reconcileRun: 'fin:reconcile:run', +} as const + +export const ORDER_STATUS: Record = { + PENDING: { label: '待确认', tag: 'warning' }, + PAID: { label: '已到账', tag: 'success' }, + CANCELLED: { label: '已关闭', tag: 'info' }, + REFUNDED: { label: '已退款', tag: 'danger' }, +} + +export const ORDER_TYPE_LABEL: Record = { + recharge: '点数充值', + vip: 'VIP 开通/续费', +} + +export const PAY_METHOD_LABEL: Record = { + offline: '线下转账', + wechat: '微信支付', + alipay: '支付宝', +} + +export const TX_TYPE: Record = { + RECHARGE: { label: '充值入账', sign: 1, tag: 'success' }, + CONSUME: { label: '扣费', sign: -1, tag: 'danger' }, + CONSUME_FREE: { label: 'VIP 免扣', sign: 0, tag: 'info' }, + REFUND_IN: { label: '点数退款', sign: 1, tag: 'warning' }, + REFUND_OUT: { label: '现金退款扣回', sign: -1, tag: 'warning' }, + ADJUST: { label: '人工调账', sign: 0, tag: 'info' }, +} + +export const REFUND_STATUS: Record = { + PENDING: { label: '待复核', tag: 'warning' }, + COMPLETED: { label: '已完成', tag: 'success' }, + REJECTED: { label: '已驳回', tag: 'danger' }, +} + +export const WEBHOOK_STATUS: Record = { + PENDING: { label: '待投递', tag: 'info' }, + SENT: { label: '已送达', tag: 'success' }, + FAILED: { label: '重试中', tag: 'warning' }, + DEAD: { label: '投递失败', tag: 'danger' }, +} + +export const TX_TYPE_OPTIONS = (Object.keys(TX_TYPE) as TxType[]).map(value => ({ + value, + label: TX_TYPE[value].label, +})) + +export const ORDER_STATUS_OPTIONS = (Object.keys(ORDER_STATUS) as OrderStatus[]).map(value => ({ + value, + label: ORDER_STATUS[value].label, +})) + +export const ROLE_OPTIONS = (Object.keys(ROLE_LABEL) as Role[]).map(value => ({ + value, + label: ROLE_LABEL[value], +})) diff --git a/finance-web/src/directives/permission.ts b/finance-web/src/directives/permission.ts new file mode 100644 index 0000000..9c98f90 --- /dev/null +++ b/finance-web/src/directives/permission.ts @@ -0,0 +1,22 @@ +import type { Directive } from 'vue' +import { useUserStore } from '@/stores/user' + +/** + * 按钮级权限指令:无权限时隐藏元素。 + * 注意:前端隐藏只是体验层,服务端必须用 @PreAuthorize 等再次校验。 + */ +export const permission: Directive = { + mounted(el, binding) { + if (!binding.value) return + const store = useUserStore() + if (!store.hasPerm(binding.value)) { + el.style.display = 'none' + el.dataset.permHidden = '1' + } + }, + updated(el, binding) { + if (!binding.value) return + const store = useUserStore() + el.style.display = store.hasPerm(binding.value) ? '' : 'none' + }, +} diff --git a/finance-web/src/env.d.ts b/finance-web/src/env.d.ts new file mode 100644 index 0000000..d6861d8 --- /dev/null +++ b/finance-web/src/env.d.ts @@ -0,0 +1,17 @@ +/// + +declare module '*.vue' { + import type { DefineComponent } from 'vue' + const component: DefineComponent, Record, unknown> + export default component +} + +interface ImportMetaEnv { + readonly VITE_APP_TITLE: string + readonly VITE_USE_MOCK: string + readonly VITE_API_BASE: string +} + +interface ImportMeta { + readonly env: ImportMetaEnv +} diff --git a/finance-web/src/layouts/AppLayout.vue b/finance-web/src/layouts/AppLayout.vue new file mode 100644 index 0000000..602786c --- /dev/null +++ b/finance-web/src/layouts/AppLayout.vue @@ -0,0 +1,324 @@ + + + + + diff --git a/finance-web/src/main.ts b/finance-web/src/main.ts new file mode 100644 index 0000000..c45a549 --- /dev/null +++ b/finance-web/src/main.ts @@ -0,0 +1,37 @@ +import { createApp } from 'vue' +import { createPinia } from 'pinia' +import ElementPlus from 'element-plus' +import 'element-plus/dist/index.css' +import zhCn from 'element-plus/es/locale/lang/zh-cn' +import * as ElementPlusIconsVue from '@element-plus/icons-vue' +import App from './App.vue' +import router from './router' +import { permission } from './directives/permission' +import { setUnauthorizedHandler } from './utils/http' +import { useUserStore } from './stores/user' +import './styles/index.css' + +const app = createApp(App) +const pinia = createPinia() + +app.use(pinia) +app.use(router) +app.use(ElementPlus, { locale: zhCn }) + +Object.entries(ElementPlusIconsVue).forEach(([key, component]) => { + app.component(key, component) +}) + +app.directive('perm', permission) + +// 401 统一出口:清理本地会话并回到登录页 +setUnauthorizedHandler(() => { + const store = useUserStore(pinia) + store.logout() + const current = router.currentRoute.value + if (current.path !== '/login') { + router.replace({ path: '/login', query: { redirect: current.fullPath } }) + } +}) + +app.mount('#app') diff --git a/finance-web/src/mock/db.ts b/finance-web/src/mock/db.ts new file mode 100644 index 0000000..54e3bab --- /dev/null +++ b/finance-web/src/mock/db.ts @@ -0,0 +1,986 @@ +import type { + AccountInfo, + AdminInfo, + AppInfo, + AppPolicy, + AuditLog, + ConfigItem, + OrderInfo, + PricingItem, + ReconcileDiff, + ReconcileReport, + RefundInfo, + TransactionInfo, + TrendPoint, + TxType, + VipPlan, + WebhookDelivery, +} from '@/types' +import { maskPhone } from '@/utils/mask' + +/* ------------------------------------------------------------------ * + * 本地演示数据(Mock):仅用于前端联调与验收演示,不含任何真实密钥。 + * 真实环境由后端 MySQL 提供数据,前端不持有 client_secret 明文。 + * ------------------------------------------------------------------ */ + +const pad = (n: number): string => String(n).padStart(2, '0') + +export function timestamp(date: Date): string { + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad( + date.getHours(), + )}:${pad(date.getMinutes())}:${pad(date.getSeconds())}` +} + +export function daysAgo(days: number, hour = 10, minute = 0): string { + const date = new Date() + date.setDate(date.getDate() - days) + date.setHours(hour, minute, 0, 0) + return timestamp(date) +} + +export function now(): string { + return timestamp(new Date()) +} + +export function plusMinutes(minutes: number): string { + const date = new Date() + date.setMinutes(date.getMinutes() + minutes) + return timestamp(date) +} + +export function plusDays(days: number): string { + const date = new Date() + date.setDate(date.getDate() + days) + return timestamp(date) +} + +let seq = 100000 +export function nextId(): number { + seq += 1 + return seq +} + +let seed = 20261027 +function rnd(): number { + seed = (seed * 1103515245 + 12345) & 0x7fffffff + return seed / 0x7fffffff +} +function int(min: number, max: number): number { + return Math.floor(rnd() * (max - min + 1)) + min +} +function pick(list: T[]): T { + return list[Math.floor(rnd() * list.length)] +} + +/** 64 位十六进制摘要:仅用于 Mock 审计链演示,真实环境使用 SHA-256/SM3 */ +export function digest(input: string): string { + let h1 = 0x811c9dc5 + let h2 = 0x01000193 + let h3 = 0x9e3779b9 + let h4 = 0x85ebca6b + for (let i = 0; i < input.length; i += 1) { + const code = input.charCodeAt(i) + h1 = ((h1 ^ code) * 16777619) >>> 0 + h2 = ((h2 + code) * 2654435761) >>> 0 + h3 = ((h3 ^ (code << 3)) * 2246822519) >>> 0 + h4 = ((h4 + code * 131) * 3266489917) >>> 0 + } + const hex = (value: number): string => (value >>> 0).toString(16).padStart(8, '0') + return ( + hex(h1) + hex(h2) + hex(h3) + hex(h4) + + hex(h1 ^ h2) + hex(h3 ^ h4) + hex((h1 + h3) >>> 0) + hex((h2 + h4) >>> 0) + ) +} + +/** 审计哈希链统一算法:种子数据、实时写入、链校验必须共用同一实现,否则校验必然误报断链 */ +export function auditHash( + item: { + id: number + actorId: number | null + actorName: string + action: string + targetType: string + targetId: number | null + beforeJson: string | null + afterJson: string | null + result: string + createTime: string + }, + prevHash: string, +): string { + return digest( + JSON.stringify([ + item.id, + item.actorId, + item.actorName, + item.action, + item.targetType, + item.targetId, + item.beforeJson, + item.afterJson, + item.result, + item.createTime, + prevHash, + ]), + ) +} + +export const ROLE_PERMISSIONS: Record = { + SUPER_ADMIN: [ + 'fin:view', + 'fin:export', + 'fin:app:manage', + 'fin:pricing:edit', + 'fin:vip:manage', + 'fin:admin:manage', + 'fin:config:edit', + 'fin:audit:view', + 'fin:webhook:manage', + 'fin:account:adjust', + 'fin:refund:review', + 'fin:order:cancel', + 'fin:reconcile:run', + ], + FINANCE: [ + 'fin:view', + 'fin:export', + 'fin:recharge:confirm', + 'fin:refund:create', + 'fin:refund:review', + 'fin:order:cancel', + 'fin:reconcile:run', + ], + AUDITOR: ['fin:view', 'fin:export', 'fin:audit:view'], +} + +export interface AdminRecord extends AdminInfo { + password: string + passwordHistory: string[] +} + +export interface AppRecord extends AppInfo { + /** 审计目标 ID(库表中应用以 app_code 为业务主键,此 ID 仅用于审计留痕) */ + id: number + clientSecretHash: string + clientSecretPrevHash: string + webhookSecretEnc: string +} + +export interface PlanRecord extends VipPlan {} + +export interface VipRecord { + id: number + appCode: string + businessUserId: string + vipPlanCode: string + vipUntil: string +} + +export interface CashFlowRecord { + id: number + appCode: string + orderId: number + direction: 'IN' | 'OUT' + amountCent: number + receivedAt: string + voucherNo: string + operatorAdminId: number + remark: string +} + +export interface RefundRecord extends RefundInfo {} + +export interface TxRecord extends TransactionInfo {} + +export interface OrderRecord extends OrderInfo {} + +export interface WebhookRecord extends WebhookDelivery {} + +export interface AuditRecord extends AuditLog {} + +export interface ConfigRecord extends ConfigItem {} + +export interface PricingRecord extends PricingItem {} + +export interface PolicyRecord extends AppPolicy {} + +export interface AccountRecord extends AccountInfo { + phoneHash: string + status: 'ACTIVE' + firstSeenAt: string +} + +export interface AppTokenRecord { + id: number + appCode: string + tokenHash: string + expiresAt: string + revokedAt: string | null + issuedIp: string + createTime: string +} + +export interface TicketRecord { + ticket: string + appCode: string + businessUserId: string + expiresAt: string + usedAt: string | null +} + +export interface ReconcileRecord extends ReconcileReport {} + +export interface MockState { + admins: AdminRecord[] + apps: AppRecord[] + accounts: AccountRecord[] + orders: OrderRecord[] + transactions: TxRecord[] + refunds: RefundRecord[] + cashFlows: CashFlowRecord[] + plans: PlanRecord[] + vips: VipRecord[] + pricing: PricingRecord[] + policies: PolicyRecord[] + configs: ConfigRecord[] + audits: AuditRecord[] + webhooks: WebhookRecord[] + tokens: AppTokenRecord[] + tickets: TicketRecord[] + reports: ReconcileRecord[] + sessions: Map + /** 支付下单幂等索引:幂等键 → 订单 ID,防止网络重试造成重复下单 */ + idempotency: Map +} + +const USERS = [ + { id: 'u10001', name: '张伟', phone: '13800138000' }, + { id: 'u10002', name: '李娜', phone: '13912345678' }, + { id: 'u10003', name: '王强', phone: '13755556666' }, + { id: 'u10004', name: '刘洋', phone: '15011112222' }, + { id: 'u10005', name: '陈静', phone: '18800009999' }, + { id: 'u10006', name: '杨帆', phone: '13566667777' }, + { id: 'u10007', name: '赵敏', phone: '13633334444' }, + { id: 'u10008', name: '周涛', phone: '15988887777' }, + { id: 'u10009', name: '孙悦', phone: '13322221111' }, + { id: 'u10010', name: '吴斌', phone: '18900001111' }, + { id: 'u10011', name: '郑凯', phone: '18655554444' }, + { id: 'u10012', name: '冯雪', phone: '13277778888' }, +] + +function buildAdmins(): AdminRecord[] { + const base = { + isActive: 1, + mustChangePassword: 0, + totpBound: true, + failedAttempts: 0, + lockedUntil: null, + lastLoginIp: '10.10.8.21', + createTime: '2025-12-01 09:00:00', + } + return [ + { + ...base, + id: 1, + username: 'admin', + password: 'Super@Fin2026', + passwordHistory: [], + role: 'SUPER_ADMIN', + lastLoginAt: daysAgo(0, 8, 42), + }, + { + ...base, + id: 2, + username: 'finance', + password: 'Fin@2026Fund', + passwordHistory: [], + role: 'FINANCE', + lastLoginAt: daysAgo(0, 9, 12), + }, + { + ...base, + id: 3, + username: 'auditor', + password: 'Audit@2026View', + passwordHistory: [], + role: 'AUDITOR', + lastLoginAt: daysAgo(1, 16, 5), + }, + ] +} + +function buildApps(): AppRecord[] { + return [ + { + id: nextId(), + appCode: 'litho-sim', + appName: '光刻仿真平台', + allowedRedirectHosts: 'sim.gaszk.com,sim.gaszk.cn', + webhookUrl: 'https://sim.gaszk.com/api/finance/webhook', + webhookSecretEnc: 'enc:webhook:litho', + tokenTtlSeconds: 900, + enabled: 1, + clientSecretHash: '$argon2id$mock$litho', + clientSecretPrevHash: '', + hasPrevSecret: false, + secretExpiresAt: null, + createTime: daysAgo(180, 9, 0), + accountCount: 0, + todayAmountCent: 0, + }, + { + id: nextId(), + appCode: 'libs-platform', + appName: 'LIBS 显微检测数据中台', + allowedRedirectHosts: 'libs.gaszk.com', + webhookUrl: 'https://libs.gaszk.com/api/fin/webhook', + webhookSecretEnc: 'enc:webhook:libs', + tokenTtlSeconds: 900, + enabled: 1, + clientSecretHash: '$argon2id$mock$libs', + clientSecretPrevHash: '', + hasPrevSecret: false, + secretExpiresAt: null, + createTime: daysAgo(120, 10, 30), + accountCount: 0, + todayAmountCent: 0, + }, + { + id: nextId(), + appCode: 'mall-pro', + appName: '工业耗材商城', + allowedRedirectHosts: 'mall.gaszk.com', + webhookUrl: '', + webhookSecretEnc: 'enc:webhook:mall', + tokenTtlSeconds: 1800, + enabled: 0, + clientSecretHash: '$argon2id$mock$mall', + clientSecretPrevHash: '', + hasPrevSecret: false, + secretExpiresAt: null, + createTime: daysAgo(60, 14, 0), + accountCount: 0, + todayAmountCent: 0, + }, + ] +} + +function buildPlans(apps: AppRecord[]): PlanRecord[] { + const defs: Array<[string, string, string, number, number, number]> = [ + ['litho-sim', 'VIP_MONTH', '专业版 · 月付', 30, 9900, 1], + ['litho-sim', 'VIP_QUARTER', '专业版 · 季付', 90, 26900, 1], + ['litho-sim', 'VIP_YEAR', '专业版 · 年付', 365, 89900, 1], + ['libs-platform', 'PRO_MONTH', '检测专业版 · 月付', 30, 19900, 0], + ['libs-platform', 'PRO_QUARTER', '检测专业版 · 季付', 90, 53900, 0], + ] + return defs.map(([appCode, planCode, planName, durationDays, priceCent, freeDeduction]) => ({ + id: nextId(), + appCode, + appName: apps.find(item => item.appCode === appCode)?.appName || appCode, + planCode, + planName, + durationDays, + priceCent, + freeDeduction, + enabled: 1, + holderCount: 0, + createTime: daysAgo(90, 9, 0), + })) +} + +function buildAccounts(apps: AppRecord[], plans: PlanRecord[], transactions: TxRecord[], vips: VipRecord[]): AccountRecord[] { + const map: Record = { + 'litho-sim': [0, 1, 2, 3, 4, 5, 6, 7, 8], + 'libs-platform': [0, 1, 2, 3, 4, 5], + 'mall-pro': [6, 7, 8, 9, 10, 11], + } + const accounts: AccountRecord[] = [] + + apps.forEach(app => { + const indexes = map[app.appCode] || [0, 1] + indexes.forEach((userIndex, order) => { + const user = USERS[userIndex] + const accountId = nextId() + let balance = 0 + let totalSpent = 0 + let versionNo = 0 + const txCount = 4 + int(0, 5) + for (let i = 0; i < txCount; i += 1) { + let type: TxType = 'RECHARGE' + const roll = rnd() + if (i === 0) type = 'RECHARGE' + else if (roll < 0.5) type = 'CONSUME' + else if (roll < 0.65) type = 'RECHARGE' + else if (roll < 0.8) type = 'CONSUME_FREE' + else if (roll < 0.92) type = 'CONSUME' + else type = 'REFUND_IN' + + let amount = 0 + if (type === 'RECHARGE') amount = pick([1000, 2000, 3000, 5000, 10000, 20000]) + else if (type === 'REFUND_IN') amount = int(50, 300) + else if (type === 'CONSUME_FREE') amount = 0 + else amount = int(30, 1200) + + if (type === 'CONSUME' && balance < amount) { + type = 'RECHARGE' + amount = pick([2000, 5000, 10000]) + } + + const before = balance + if (type === 'RECHARGE' || type === 'REFUND_IN') balance += amount + else if (type === 'CONSUME') { + balance -= amount + totalSpent += amount + } + + versionNo += 1 + transactions.push({ + id: nextId(), + appCode: app.appCode, + appName: app.appName, + businessUserId: user.id, + usernameSnapshot: user.name, + type, + amount, + balanceBefore: before, + balanceAfter: balance, + businessRefId: type === 'CONSUME' ? `${app.appCode}:task:${9000 + order * 10 + i}` : null, + idempotencyKey: + type === 'RECHARGE' + ? `order:RC${app.appCode}:${order}${i}` + : `${app.appCode}:${type.toLowerCase()}:${order}${i}${int(100, 999)}`, + orderId: null, + outTradeNo: null, + refundOfId: null, + refundedPoints: 0, + operatorAdminName: type === 'RECHARGE' ? 'finance' : null, + remark: type === 'CONSUME_FREE' ? 'VIP_FREE' : '', + createTime: daysAgo(20 - Math.floor((i * 18) / txCount), 9 + int(0, 8), int(0, 59)), + }) + } + + const account: AccountRecord = { + id: accountId, + appCode: app.appCode, + appName: app.appName, + businessUserId: user.id, + usernameSnapshot: user.name, + phoneMasked: maskPhone(user.phone), + phoneHash: digest(user.phone), + status: 'ACTIVE', + balance, + totalSpent, + versionNo, + vipPlanCode: null, + vipUntil: null, + firstSeenAt: daysAgo(30 - order), + createTime: daysAgo(30 - order), + updateTime: daysAgo(0, 9, 30), + } + + const plan = plans.find(item => item.appCode === app.appCode && item.freeDeduction === 1) + if (plan && order % 3 === 0) { + account.vipPlanCode = plan.planCode + account.vipUntil = plusDays(int(5, 200)) + vips.push({ + id: nextId(), + appCode: app.appCode, + businessUserId: user.id, + vipPlanCode: plan.planCode, + vipUntil: account.vipUntil, + }) + } + + accounts.push(account) + }) + }) + + return accounts +} + +function buildOrders(apps: AppRecord[], accounts: AccountRecord[], plans: PlanRecord[], admins: AdminRecord[]): { + orders: OrderRecord[] + cashFlows: CashFlowRecord[] + refunds: RefundRecord[] + webhooks: WebhookRecord[] +} { + const enabledApps = apps.filter(app => app.enabled === 1) + const orders: OrderRecord[] = [] + const cashFlows: CashFlowRecord[] = [] + const refunds: RefundRecord[] = [] + const webhooks: WebhookRecord[] = [] + const finance = admins.find(item => item.role === 'FINANCE') || admins[1] + const superAdmin = admins.find(item => item.role === 'SUPER_ADMIN') || admins[0] + const threshold = 500000 + + for (let i = 0; i < 46; i += 1) { + const app = pick(enabledApps) + const candidates = accounts.filter(item => item.appCode === app.appCode) + if (!candidates.length) continue + const account = pick(candidates) + const orderType = rnd() < 0.22 ? 'vip' : 'recharge' + const planList = plans.filter(item => item.appCode === app.appCode && item.enabled === 1) + const plan = planList.length ? pick(planList) : null + const amountCent = orderType === 'vip' && plan ? plan.priceCent : pick([1000, 2000, 5000, 10000, 20000, 50000]) + const pricingRate = app.appCode === 'libs-platform' ? 80 : 100 + const pointsGained = orderType === 'vip' ? 0 : Math.floor((amountCent / 100) * pricingRate) + const dayAgo = i < 8 ? 0 : int(0, 18) + const createTime = daysAgo(dayAgo, int(8, 19), int(0, 59)) + + const roll = rnd() + let status: OrderRecord['status'] = 'PAID' + if (roll > 0.94) status = 'REFUNDED' + else if (roll > 0.82) status = 'PENDING' + else if (roll > 0.76) status = 'CANCELLED' + + const datePart = createTime.slice(0, 10).replace(/-/g, '') + const outTradeNo = `${orderType === 'vip' ? 'VIP' : 'RC'}${datePart}${String(1000 + i).slice(-4)}` + const needDualControl = amountCent >= threshold + const paidAt = status === 'PAID' || status === 'REFUNDED' ? createTime.replace(/(\d\d):(\d\d):\d\d$/, '$1:$2:30') : null + const secondApprover = needDualControl ? superAdmin : null + + orders.push({ + id: nextId(), + outTradeNo, + appCode: app.appCode, + appName: app.appName, + businessUserId: account.businessUserId, + usernameSnapshot: account.usernameSnapshot, + orderType, + payMethod: 'offline', + amountCent, + pointsGained, + vipPlanCode: orderType === 'vip' && plan ? plan.planCode : null, + status, + expiresAt: status === 'PENDING' ? plusDays(1) : createTime, + paidAt, + confirmedByAdminId: paidAt ? finance.id : null, + confirmedByAdminName: paidAt ? finance.username : null, + secondApproverId: paidAt && secondApprover ? secondApprover.id : null, + secondApproverName: paidAt && secondApprover ? secondApprover.username : null, + remark: status === 'CANCELLED' ? '用户取消' : '', + createTime, + refundedAmountCent: 0, + cashInCent: 0, + cashOutCent: 0, + needDualControl, + }) + } + + orders.forEach(order => { + if (order.status === 'PAID' || order.status === 'REFUNDED') { + const cashId = nextId() + cashFlows.push({ + id: cashId, + appCode: order.appCode, + orderId: order.id, + direction: 'IN', + amountCent: order.amountCent, + receivedAt: order.paidAt || order.createTime, + voucherNo: `BK${order.createTime.slice(0, 10).replace(/-/g, '')}${String(order.id).slice(-4)}`, + operatorAdminId: order.confirmedByAdminId || 2, + remark: '对公转账到账', + }) + order.cashInCent = order.amountCent + } + }) + + const refundTargets = orders.filter(item => item.status === 'REFUNDED') + refundTargets.forEach((order, index) => { + const status: RefundInfo['status'] = index === 0 ? 'COMPLETED' : index === 1 ? 'PENDING' : index === 2 ? 'REJECTED' : 'COMPLETED' + const pointsDeducted = Math.max(0, Math.min(order.pointsGained, order.pointsGained)) + const refund: RefundRecord = { + id: nextId(), + appCode: order.appCode, + appName: order.appName, + businessUserId: order.businessUserId, + usernameSnapshot: order.usernameSnapshot, + orderId: order.id, + outTradeNo: order.outTradeNo, + amountCent: order.amountCent, + pointsDeducted, + status, + operatorAdminId: 2, + operatorAdminName: 'finance', + reviewerAdminId: status === 'PENDING' ? null : 1, + reviewerAdminName: status === 'PENDING' ? null : 'admin', + voucherNo: status === 'REJECTED' ? '' : `RF${order.createTime.slice(0, 10).replace(/-/g, '')}${String(order.id).slice(-4)}`, + remark: status === 'REJECTED' ? '客户撤销退款申请' : '客户申请退费', + createTime: order.paidAt ? order.paidAt.replace(/(\d\d):(\d\d):\d\d$/, '$1:$2:40') : order.createTime, + updateTime: now(), + } + refunds.push(refund) + order.refundedAmountCent = status === 'REJECTED' ? 0 : order.amountCent + order.cashOutCent = status === 'COMPLETED' ? order.amountCent : 0 + if (status === 'COMPLETED') { + cashFlows.push({ + id: nextId(), + appCode: order.appCode, + orderId: order.id, + direction: 'OUT', + amountCent: order.amountCent, + receivedAt: refund.updateTime, + voucherNo: refund.voucherNo, + operatorAdminId: 2, + remark: '现金退款', + }) + } + }) + + orders.forEach(order => { + if (order.status === 'PAID' || order.status === 'REFUNDED') { + const events = ['order.paid'] + if (order.status === 'REFUNDED') events.push('order.refunded') + events.forEach(eventType => { + const roll = rnd() + const status: WebhookDelivery['status'] = roll < 0.72 ? 'SENT' : roll < 0.9 ? 'FAILED' : 'DEAD' + webhooks.push({ + id: nextId(), + appCode: order.appCode, + appName: order.appName, + eventId: `evt_${digest(`${order.outTradeNo}${eventType}`).slice(0, 20)}`, + eventType, + status, + attempts: status === 'SENT' ? 1 : status === 'FAILED' ? 3 : 6, + nextRetryAt: status === 'FAILED' ? plusMinutes(30) : null, + lastError: status === 'SENT' ? '' : status === 'FAILED' ? 'connect timeout (10s)' : 'HTTP 502 连续 6 次失败', + payload: JSON.stringify( + { + eventId: `evt_${order.outTradeNo}`, + eventType, + appCode: order.appCode, + businessUserId: order.businessUserId, + outTradeNo: order.outTradeNo, + amountCent: order.amountCent, + points: order.pointsGained, + occurredAt: order.paidAt, + }, + null, + 0, + ), + createTime: order.paidAt || order.createTime, + updateTime: order.paidAt || order.createTime, + }) + }) + } + }) + + return { orders, cashFlows, refunds, webhooks } +} + +function buildConfigs(): ConfigRecord[] { + const list: Array<[string, string, string, 'HIGH' | 'NORMAL']> = [ + ['order.pending.timeout_hours', '24', '待确认订单超时关单时长(小时),对公转账晚到可调至 72', 'NORMAL'], + ['review.threshold_cent', '500000', '双人复核金额阈值(分),默认 ¥5000', 'NORMAL'], + ['admin.lock.threshold', '5', '管理员登录失败锁定次数', 'NORMAL'], + ['admin.lock.minutes', '15', '管理员锁定时长(分钟)', 'NORMAL'], + ['ticket.ttl_minutes', '5', '一次性凭证有效期(分钟)', 'NORMAL'], + ['token.ttl_seconds', '900', 'client token 有效期(秒)', 'NORMAL'], + ['secret.rotate.grace_hours', '24', '密钥轮换宽限期(小时)', 'NORMAL'], + ['charge.retry.max', '3', '乐观锁冲突服务端重试次数', 'NORMAL'], + ['webhook.max_retry', '6', 'webhook 最大重试次数', 'NORMAL'], + ['pii.mask.enabled', '1', 'PII 掩码开关,关闭属高危变更', 'HIGH'], + ] + return list.map(([configKey, configValue, description, risk], index) => ({ + configKey, + configValue, + description, + risk, + updateBy: index % 4 === 0 ? 'admin' : 'system', + updateTime: daysAgo(index + 3, 10, 20), + })) +} + +function buildAudits(admins: AdminRecord[], apps: AppRecord[]): AuditRecord[] { + const actions: Array<[string, string, string, string, string]> = [ + ['LOGIN', '管理员登录', 'ADMIN', '', ''], + ['ORDER_CONFIRM', '确认订单到账', 'ORDER', '{"status":"PENDING"}', '{"status":"PAID"}'], + ['PRICING_UPDATE', '修改兑率', 'PRICING', '{"pointsPerYuan":90}', '{"pointsPerYuan":100}'], + ['APP_SECRET_ROTATE', '轮换应用密钥', 'APP', '', '{"graceHours":24}'], + ['REFUND_CREATE', '发起现金退款', 'REFUND', '', '{"status":"PENDING"}'], + ['REFUND_REVIEW', '复核现金退款', 'REFUND', '{"status":"PENDING"}', '{"status":"COMPLETED"}'], + ['ADMIN_CREATE', '创建管理员', 'ADMIN', '', '{"role":"FINANCE"}'], + ['CONFIG_UPDATE', '修改全局参数', 'CONFIG', '{"value":"24"}', '{"value":"72"}'], + ['ORDER_CANCEL', '关闭订单', 'ORDER', '{"status":"PENDING"}', '{"status":"CANCELLED"}'], + ['ACCOUNT_ADJUST', '人工调账', 'ACCOUNT', '{"balance":100}', '{"balance":200}'], + ] + const audits: AuditRecord[] = [] + let prevHash = '' + for (let i = 0; i < 48; i += 1) { + const actor = pick(admins) + const [action, actionLabel, targetType, beforeJson, afterJson] = pick(actions) + const createTime = daysAgo(14 - Math.floor(i / 4), 8 + (i % 10), (i * 7) % 60) + const app = pick(apps) + const record: AuditRecord = { + id: nextId(), + actorType: 'ADMIN', + actorId: actor.id, + actorName: actor.username, + action, + actionLabel, + targetType: action === 'APP_SECRET_ROTATE' ? 'APP' : targetType, + targetId: action === 'APP_SECRET_ROTATE' ? app.id : nextId(), + beforeJson: beforeJson || null, + afterJson: afterJson || null, + ip: `10.10.8.${20 + (i % 8)}`, + ua: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/126.0', + result: i % 17 === 0 ? 'FAILED' : 'SUCCESS', + prevHash, + curHash: '', + createTime, + } + record.curHash = auditHash(record, prevHash) + audits.push(record) + prevHash = record.curHash + } + return audits +} + +export function appendAudit(input: { + actorId: number | null + actorName: string + action: string + actionLabel: string + targetType: string + targetId: number | null + beforeJson?: string | null + afterJson?: string | null + ip?: string + result?: 'SUCCESS' | 'FAILED' +}): AuditRecord { + const lastHash = db.audits.length ? db.audits[db.audits.length - 1].curHash : '' + const createTime = now() + const record: AuditRecord = { + id: nextId(), + actorType: input.actorId ? 'ADMIN' : 'SYSTEM', + actorId: input.actorId, + actorName: input.actorName, + action: input.action, + actionLabel: input.actionLabel, + targetType: input.targetType, + targetId: input.targetId, + beforeJson: input.beforeJson || null, + afterJson: input.afterJson || null, + ip: input.ip || '10.10.8.21', + ua: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/126.0', + result: input.result || 'SUCCESS', + prevHash: lastHash, + curHash: '', + createTime, + } + record.curHash = auditHash(record, lastHash) + db.audits.push(record) + return record +} + +function computeTrend(): TrendPoint[] { + const points: TrendPoint[] = [] + for (let i = 13; i >= 0; i -= 1) { + const date = daysAgo(i).slice(0, 10) + const amountCent = db.cashFlows + .filter(item => item.direction === 'IN' && item.receivedAt.slice(0, 10) === date) + .reduce((sum, item) => sum + item.amountCent, 0) + const consumed = db.transactions + .filter(item => item.type === 'CONSUME' && item.createTime.slice(0, 10) === date) + .reduce((sum, item) => sum + item.amount, 0) + const orderCount = db.orders.filter(item => item.createTime.slice(0, 10) === date).length + points.push({ date: date.slice(5), amountCent, points: consumed, orderCount }) + } + return points +} + +export function trendData(): TrendPoint[] { + return computeTrend() +} + +export function buildReport(appCode: string, windowStart: string, windowEnd: string, createdBy: string): ReconcileRecord { + const app = db.apps.find(item => item.appCode === appCode) + const start = `${windowStart} 00:00:00` + const end = `${windowEnd} 23:59:59` + const inRange = (value: string | null): boolean => !!value && value >= start && value <= end + + const cashInCent = db.cashFlows + .filter(item => item.appCode === appCode && item.direction === 'IN' && inRange(item.receivedAt)) + .reduce((sum, item) => sum + item.amountCent, 0) + const cashOutCent = db.cashFlows + .filter(item => item.appCode === appCode && item.direction === 'OUT' && inRange(item.receivedAt)) + .reduce((sum, item) => sum + item.amountCent, 0) + const cashPaidOrderCent = db.orders + .filter(item => item.appCode === appCode && (item.status === 'PAID' || item.status === 'REFUNDED') && inRange(item.paidAt)) + .reduce((sum, item) => sum + item.amountCent, 0) + const cashRefundedCent = db.refunds + .filter(item => item.appCode === appCode && item.status === 'COMPLETED' && inRange(item.updateTime)) + .reduce((sum, item) => sum + item.amountCent, 0) + + const accounts = db.accounts.filter(item => item.appCode === appCode) + const walletSum = accounts.reduce((sum, item) => sum + item.balance, 0) + let computedSum = 0 + let brokenChains = 0 + + accounts.forEach(account => { + const txList = db.transactions + .filter(item => item.appCode === appCode && item.businessUserId === account.businessUserId) + .sort((a, b) => a.createTime.localeCompare(b.createTime)) + let expected = 0 + let broken = false + txList.forEach(tx => { + if (tx.balanceBefore !== expected) broken = true + if (tx.type === 'RECHARGE' || tx.type === 'REFUND_IN') expected += tx.amount + else if (tx.type === 'CONSUME' || tx.type === 'REFUND_OUT') expected -= tx.amount + else if (tx.type === 'ADJUST') expected += tx.balanceAfter - tx.balanceBefore + }) + computedSum += expected + if (broken) brokenChains += 1 + }) + + const cashDiffCent = cashInCent - cashPaidOrderCent - (cashOutCent - cashRefundedCent) + const pointsDiff = walletSum - computedSum + const details: ReconcileDiff[] = [] + if (pointsDiff !== 0) { + details.push({ + level: 'APP', + target: appCode, + expected: computedSum, + actual: walletSum, + diff: pointsDiff, + reason: '流水累计与钱包余额不一致,需人工核查是否存在漏记流水', + }) + } + if (brokenChains > 0) { + details.push({ + level: 'APP', + target: appCode, + expected: 0, + actual: brokenChains, + diff: brokenChains, + reason: `${brokenChains} 个账户流水前后余额断链(疑似篡改或漏记)`, + }) + } + + return { + id: `RC${windowEnd.replace(/-/g, '')}${String(db.reports.length + 1).padStart(3, '0')}`, + appCode, + appName: app?.appName || appCode, + windowStart, + windowEnd, + snapshotAt: now(), + cashInCent, + cashPaidOrderCent, + cashOutCent, + cashRefundedCent, + cashDiffCent, + walletSum, + computedSum, + pointsDiff, + brokenChains, + diffCount: details.length, + status: details.length === 0 ? 'BALANCED' : 'DIFF', + createdBy, + createTime: now(), + details, + } +} + +function buildSeedReports(): ReconcileRecord[] { + const yesterday = daysAgo(1).slice(0, 10) + const balanced = buildReport('litho-sim', yesterday, yesterday, 'system') + balanced.id = 'RC' + yesterday.replace(/-/g, '') + '001' + balanced.createTime = daysAgo(1, 2, 0) + balanced.snapshotAt = daysAgo(1, 2, 0) + + const threeDaysAgo = daysAgo(3).slice(0, 10) + const diff = buildReport('libs-platform', threeDaysAgo, threeDaysAgo, 'system') + diff.id = 'RC' + threeDaysAgo.replace(/-/g, '') + '002' + diff.createTime = daysAgo(3, 2, 0) + diff.snapshotAt = daysAgo(3, 2, 0) + diff.pointsDiff = 60 + diff.walletSum = diff.computedSum + 60 + diff.diffCount = 1 + diff.status = 'DIFF' + diff.details = [ + { + level: 'SUBJECT', + target: 'u10003', + expected: diff.computedSum - 120, + actual: diff.computedSum - 60, + diff: 60, + reason: '点数侧钱包余额高于流水累计 60 点,疑似漏记一笔扣费流水', + }, + ] + return [balanced, diff] +} + +function initState(): MockState { + const admins = buildAdmins() + const apps = buildApps() + const plans = buildPlans(apps) + const transactions: TxRecord[] = [] + const vips: VipRecord[] = [] + const accounts = buildAccounts(apps, plans, transactions, vips) + const { orders, cashFlows, refunds, webhooks } = buildOrders(apps, accounts, plans, admins) + + const pricing: PricingRecord[] = apps.map(app => ({ + appCode: app.appCode, + appName: app.appName, + pointsPerYuan: app.appCode === 'libs-platform' ? 80 : 100, + enabled: app.enabled, + updateTime: daysAgo(12, 11, 0), + })) + + const policies: PolicyRecord[] = apps.map(app => ({ + appCode: app.appCode, + appName: app.appName, + minCost: app.appCode === 'libs-platform' ? 200 : 100, + maxPointsPerCharge: app.appCode === 'libs-platform' ? 20000 : 50000, + vipExempt: app.appCode === 'libs-platform' ? 0 : 1, + failedStrategy: 'none', + dualControlThresholdCent: 500000, + enabled: app.enabled, + updateTime: daysAgo(12, 11, 5), + })) + + const state: MockState = { + admins, + apps, + accounts, + orders, + transactions, + refunds, + cashFlows, + plans, + vips, + pricing, + policies, + configs: buildConfigs(), + audits: [], + webhooks, + tokens: [], + tickets: [], + reports: [], + sessions: new Map(), + idempotency: new Map(), + } + return state +} + +export const db: MockState = initState() +db.audits = buildAudits(db.admins, db.apps) +db.reports = buildSeedReports() + +// 应用维度统计(首页/应用列表用) +export function refreshAppStats(): void { + const today = now().slice(0, 10) + db.apps.forEach(app => { + app.accountCount = db.accounts.filter(item => item.appCode === app.appCode).length + app.todayAmountCent = db.cashFlows + .filter(item => item.appCode === app.appCode && item.direction === 'IN' && item.receivedAt.slice(0, 10) === today) + .reduce((sum, item) => sum + item.amountCent, 0) + }) + db.plans.forEach(plan => { + plan.holderCount = db.vips.filter( + item => item.appCode === plan.appCode && item.vipPlanCode === plan.planCode && item.vipUntil > now(), + ).length + }) +} + +refreshAppStats() diff --git a/finance-web/src/mock/index.ts b/finance-web/src/mock/index.ts new file mode 100644 index 0000000..d0767f5 --- /dev/null +++ b/finance-web/src/mock/index.ts @@ -0,0 +1,2 @@ +export { mockAdapter } from './router' +export { db } from './db' diff --git a/finance-web/src/mock/router.ts b/finance-web/src/mock/router.ts new file mode 100644 index 0000000..5b83799 --- /dev/null +++ b/finance-web/src/mock/router.ts @@ -0,0 +1,2045 @@ +import type { AxiosAdapter, AxiosResponse, InternalAxiosRequestConfig } from 'axios' +import type { + AccountInfo, + AdminInfo, + AppInfo, + AppPolicy, + AppTokenInfo, + OrderInfo, + PageResult, + PricingItem, + RefundInfo, + TransactionInfo, + VipPlan, + WebhookDelivery, +} from '@/types' +import { + ROLE_PERMISSIONS, + appendAudit, + auditHash, + buildReport, + daysAgo, + db, + digest, + nextId, + now, + plusDays, + plusMinutes, + refreshAppStats, + trendData, + type AccountRecord, + type AdminRecord, + type AppRecord, + type OrderRecord, + type RefundRecord, +} from '@/mock/db' +import { isSafeRedirectHost } from '@/utils/validate' + +class MockError extends Error { + code: number + + constructor(code: number, message: string) { + super(message) + this.code = code + } +} + +interface Ctx { + params: Record + query: Record + body: Record + headers: Record + admin: AdminRecord | null +} + +type Handler = (ctx: Ctx) => unknown + +interface RouteDef { + method: string + path: string + perms?: string[] + public?: boolean + handler: Handler +} + +const routes: RouteDef[] = [] + +function route(method: string, path: string, perms: string[] | null, handler: Handler): void { + routes.push({ method, path, perms: perms || undefined, public: perms === null, handler }) +} + +const delay = (ms: number): Promise => new Promise(resolve => setTimeout(resolve, ms)) + +function ok(data: T): { code: number; message: string; data: T } { + return { code: 0, message: 'success', data } +} + +function ensure(condition: unknown, code: number, message: string): void { + if (!condition) throw new MockError(code, message) +} + +function text(value: unknown): string { + return value === undefined || value === null ? '' : String(value) +} + +function num(value: unknown, fallback = 0): number { + const parsed = Number(value) + return Number.isFinite(parsed) ? parsed : fallback +} + +function pageOf(list: T[], query: Record): PageResult { + const page = Math.max(1, num(query.page, 1)) + const pageSize = Math.min(100, Math.max(1, num(query.pageSize, 20))) + return { + records: list.slice((page - 1) * pageSize, page * pageSize), + total: list.length, + page, + pageSize, + } +} + +function inDate(value: string | null | undefined, from?: unknown, to?: unknown): boolean { + if (!value) return false + const day = value.slice(0, 10) + const start = text(from) + const end = text(to) + if (start && day < start) return false + if (end && day > end) return false + return true +} + +function contains(value: string | null | undefined, keyword: string): boolean { + if (!keyword) return true + return text(value).toLowerCase().includes(keyword.toLowerCase()) +} + +function randomSecret(prefix = 'sk'): string { + const bytes = new Uint8Array(24) + crypto.getRandomValues(bytes) + const hex = Array.from(bytes) + .map(item => item.toString(16).padStart(2, '0')) + .join('') + return `${prefix}_${hex}` +} + +/** 读取全局参数数值,参数缺失或非法时使用兜底值,避免配置中心与业务逻辑脱节 */ +function configValue(key: string, fallback: number): number { + const item = db.configs.find(entry => entry.configKey === key) + const parsed = Number(item?.configValue) + return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback +} + +/** 双人复核阈值:优先取应用级策略,缺失时回落到全局参数 */ +function dualThreshold(appCode: string): number { + const policy = db.policies.find(item => item.appCode === appCode) + return policy?.dualControlThresholdCent ?? configValue('review.threshold_cent', 500000) +} + +function bearerToken(headers: Record): string { + const raw = headers.authorization || headers.Authorization || '' + return raw.replace(/^Bearer\s+/i, '').trim() +} + +/** 回调地址防 SSRF:必须 HTTPS,且域名不得为 IP 直连或内网单标签主机 */ +function assertWebhookUrl(url: string): void { + if (!url) return + let host = '' + try { + host = new URL(url).hostname + } catch { + throw new MockError(422, 'webhook 地址格式不合法') + } + ensure(/^https:\/\//.test(url), 422, 'webhook 地址必须使用 HTTPS') + ensure(isSafeRedirectHost(host), 422, 'webhook 域名不合法(禁止 IP 直连与内网地址)') +} + +function toAdmin(admin: AdminRecord): AdminInfo { + const { password: _password, passwordHistory: _history, ...rest } = admin + return rest +} + +function findAdmin(id: number | null): AdminRecord | undefined { + if (!id) return undefined + return db.admins.find(item => item.id === id) +} + +function appOf(code: string): AppRecord { + const app = db.apps.find(item => item.appCode === code) + ensure(app, 404, '接入应用不存在') + return app! +} + +function accountOf(appCode: string, businessUserId: string): AccountRecord | undefined { + return db.accounts.find(item => item.appCode === appCode && item.businessUserId === businessUserId) +} + +function activeAdminCount(): number { + return db.admins.filter(item => item.role === 'SUPER_ADMIN' && item.isActive === 1).length +} + +function requirePermission(admin: AdminRecord | null, perms?: string[]): void { + if (!perms || perms.length === 0) return + ensure(admin, 401, '登录状态已失效,请重新登录') + const owned = ROLE_PERMISSIONS[admin!.role] || [] + ensure( + perms.some(perm => owned.includes(perm)), + 403, + '当前账号无权执行该操作', + ) +} + +/* ----------------------------- 认证 ----------------------------- */ + +route('POST', '/admin/login', null, ctx => { + const username = text(ctx.body.username).trim() + const password = text(ctx.body.password) + const totp = text(ctx.body.totp) + ensure(username && password, 422, '请输入用户名与密码') + + const lockThreshold = configValue('admin.lock.threshold', 5) + const lockMinutes = configValue('admin.lock.minutes', 15) + const admin = db.admins.find(item => item.username === username) + // 账号不存在与密码错误使用同一文案,避免通过提示差异枚举有效账号 + ensure(admin, 4011, '用户名或密码错误') + if (admin!.lockedUntil && admin!.lockedUntil > now()) { + throw new MockError(4021, `账号因多次登录失败已锁定,请于 ${admin!.lockedUntil.slice(11, 16)} 后重试`) + } + if (admin!.password !== password) { + admin!.failedAttempts += 1 + if (admin!.failedAttempts >= lockThreshold) { + admin!.lockedUntil = plusMinutes(lockMinutes) + appendAudit({ + actorId: admin!.id, + actorName: username, + action: 'LOGIN', + actionLabel: '登录失败(锁定账号)', + targetType: 'ADMIN', + targetId: admin!.id, + result: 'FAILED', + }) + throw new MockError(4021, `连续登录失败 ${lockThreshold} 次,账号已锁定 ${lockMinutes} 分钟`) + } + appendAudit({ + actorId: admin!.id, + actorName: username, + action: 'LOGIN', + actionLabel: '登录失败', + targetType: 'ADMIN', + targetId: admin!.id, + result: 'FAILED', + }) + throw new MockError(4011, '用户名或密码错误') + } + // 账号状态在密码校验通过后再提示,避免未通过身份验证即可探测账号状态 + ensure(admin!.isActive === 1, 4012, '账号已停用,请联系超级管理员') + if (!/^\d{6}$/.test(totp)) throw new MockError(4022, '请输入 6 位动态口令') + // 演示环境固定动态码;真实环境由后端校验 TOTP 时间窗 + ensure(totp === '123456', 4022, '动态口令不正确') + + admin!.failedAttempts = 0 + admin!.lockedUntil = null + admin!.lastLoginAt = now() + admin!.lastLoginIp = '10.10.8.21' + + // 会话令牌必须使用密码学随机数,禁止使用 Math.random 拼接 + const token = randomSecret('mk') + db.sessions.set(token, { adminId: admin!.id, expiresAt: Date.now() + 8 * 3600 * 1000 }) + appendAudit({ + actorId: admin!.id, + actorName: username, + action: 'LOGIN', + actionLabel: '管理员登录', + targetType: 'ADMIN', + targetId: admin!.id, + }) + return ok({ + token, + admin: toAdmin(admin!), + permissions: ROLE_PERMISSIONS[admin!.role], + }) +}) + +route('POST', '/admin/logout', ['fin:view'], ctx => { + // 服务端必须同步失效会话,否则前端清除本地 token 后该令牌仍可继续调用接口 + const token = bearerToken(ctx.headers) + if (token) db.sessions.delete(token) + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'LOGOUT', + actionLabel: '退出登录', + targetType: 'ADMIN', + targetId: ctx.admin!.id, + }) + return ok(null) +}) + +route('GET', '/admin/profile', ['fin:view'], ctx => + ok({ admin: toAdmin(ctx.admin!), permissions: ROLE_PERMISSIONS[ctx.admin!.role] }), +) + +route('POST', '/admin/password/change', ['fin:view'], ctx => { + const oldPassword = text(ctx.body.oldPassword) + const newPassword = text(ctx.body.newPassword) + const admin = ctx.admin! + ensure(admin.password === oldPassword, 4013, '原密码不正确') + const strong = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9])\S{12,64}$/.test(newPassword) + ensure(strong, 4014, '新密码需不少于 12 位,且包含大小写字母、数字与符号') + ensure(!admin.passwordHistory.includes(newPassword) && newPassword !== admin.password, 4015, '新密码不得与最近 3 次使用的密码相同') + admin.passwordHistory = [admin.password, ...admin.passwordHistory].slice(0, 3) + admin.password = newPassword + admin.mustChangePassword = 0 + // 改密后强制下线该账号的其他会话,避免旧会话在密码泄露场景下继续有效 + const currentToken = bearerToken(ctx.headers) + db.sessions.forEach((session, key) => { + if (session.adminId === admin.id && key !== currentToken) db.sessions.delete(key) + }) + appendAudit({ + actorId: admin.id, + actorName: admin.username, + action: 'PASSWORD_CHANGE', + actionLabel: '修改登录密码', + targetType: 'ADMIN', + targetId: admin.id, + }) + return ok(null) +}) + +/* ----------------------------- 看板 ----------------------------- */ + +route('GET', '/admin/dashboard/summary', ['fin:view'], () => { + const today = now().slice(0, 10) + const paidToday = db.orders.filter(item => item.paidAt && item.paidAt.slice(0, 10) === today) + const pending = db.orders.filter(item => item.status === 'PENDING') + const threshold = configValue('review.threshold_cent', 500000) + return ok({ + todayAmountCent: paidToday.reduce((sum, item) => sum + item.amountCent, 0), + todayOrderCount: paidToday.length, + pendingOrderCount: pending.length, + pendingAmountCent: pending.reduce((sum, item) => sum + item.amountCent, 0), + todayConsumedPoints: db.transactions + .filter(item => item.type === 'CONSUME' && item.createTime.slice(0, 10) === today) + .reduce((sum, item) => sum + item.amount, 0), + pendingRefundCount: db.refunds.filter(item => item.status === 'PENDING').length, + totalBalancePoints: db.accounts.reduce((sum, item) => sum + item.balance, 0), + deadWebhookCount: db.webhooks.filter(item => item.status === 'DEAD').length, + diffReportCount: db.reports.filter(item => item.status === 'DIFF').length, + dualControlThresholdCent: threshold, + }) +}) + +route('GET', '/admin/dashboard/trend', ['fin:view'], () => ok(trendData())) + +route('GET', '/admin/dashboard/distribution', ['fin:view'], () => { + const monthAgo = daysAgo(30).slice(0, 10) + const data = db.apps.map(app => { + const paid = db.orders.filter( + item => item.appCode === app.appCode && item.paidAt && item.paidAt.slice(0, 10) >= monthAgo, + ) + return { + appCode: app.appCode, + appName: app.appName, + amountCent: paid.reduce((sum, item) => sum + item.amountCent, 0), + orderCount: paid.length, + } + }) + return ok(data) +}) + +/* ----------------------------- 应用 ----------------------------- */ + +function toAppInfo(app: AppRecord): AppInfo { + const { + clientSecretHash: _hash, + clientSecretPrevHash: _prev, + webhookSecretEnc: _enc, + ...rest + } = app + return rest +} + +route('GET', '/admin/apps', ['fin:view'], () => { + refreshAppStats() + return ok(db.apps.map(toAppInfo)) +}) + +route('POST', '/admin/apps', ['fin:app:manage'], ctx => { + const appCode = text(ctx.body.appCode).trim() + const appName = text(ctx.body.appName).trim() + const hosts = text(ctx.body.allowedRedirectHosts).trim() + const webhookUrl = text(ctx.body.webhookUrl).trim() + const ttl = num(ctx.body.tokenTtlSeconds, configValue('token.ttl_seconds', 900)) + + ensure(/^[a-z][a-z0-9-]{2,31}$/.test(appCode), 422, 'app_code 需为 3~32 位小写字母、数字或短横线') + ensure(appName.length >= 2, 422, '应用名称至少 2 个字') + ensure(!db.apps.some(item => item.appCode === appCode), 4221, 'app_code 已存在') + ensure(hosts.length > 0, 422, '必须配置跳转域名白名单') + hosts.split(',').forEach(host => { + ensure(isSafeRedirectHost(host.trim()), 422, `跳转域名不合法:${host}(禁止通配符与 IP 直连)`) + }) + assertWebhookUrl(webhookUrl) + ensure(ttl >= 60 && ttl <= 86400, 422, 'token 有效期需在 60~86400 秒之间') + + const secret = randomSecret('sk') + const app: AppRecord = { + id: nextId(), + appCode, + appName, + allowedRedirectHosts: hosts, + webhookUrl, + webhookSecretEnc: `enc:${digest(secret)}`, + tokenTtlSeconds: ttl, + enabled: 1, + clientSecretHash: digest(secret), + clientSecretPrevHash: '', + hasPrevSecret: false, + secretExpiresAt: null, + createTime: now(), + accountCount: 0, + todayAmountCent: 0, + } + db.apps.push(app) + db.pricing.push({ + appCode, + appName, + pointsPerYuan: 100, + enabled: 1, + updateTime: now(), + }) + db.policies.push({ + appCode, + appName, + minCost: 0, + maxPointsPerCharge: 50000, + vipExempt: 0, + failedStrategy: 'none', + dualControlThresholdCent: configValue('review.threshold_cent', 500000), + enabled: 1, + updateTime: now(), + }) + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'APP_CREATE', + actionLabel: '接入新应用', + targetType: 'APP', + targetId: app.id, + afterJson: JSON.stringify({ appCode, appName, hosts, ttl }), + }) + return ok({ app: toAppInfo(app), clientSecret: secret }) +}) + +route('PUT', '/admin/apps/:appCode', ['fin:app:manage'], ctx => { + const app = appOf(ctx.params.appCode) + const hosts = text(ctx.body.allowedRedirectHosts).trim() + const webhookUrl = text(ctx.body.webhookUrl).trim() + const appName = text(ctx.body.appName).trim() + ensure(hosts.length > 0, 422, '必须配置跳转域名白名单') + hosts.split(',').forEach(host => { + ensure(isSafeRedirectHost(host.trim()), 422, `跳转域名不合法:${host}`) + }) + ensure(appName.length === 0 || appName.length >= 2, 422, '应用名称至少 2 个字') + assertWebhookUrl(webhookUrl) + const ttl = num(ctx.body.tokenTtlSeconds, app.tokenTtlSeconds) + ensure(ttl >= 60 && ttl <= 86400, 422, 'token 有效期需在 60~86400 秒之间') + + const before = JSON.stringify({ + appName: app.appName, + hosts: app.allowedRedirectHosts, + webhookUrl: app.webhookUrl, + tokenTtlSeconds: app.tokenTtlSeconds, + }) + app.appName = appName || app.appName + app.allowedRedirectHosts = hosts + app.webhookUrl = webhookUrl + app.tokenTtlSeconds = ttl + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'APP_UPDATE', + actionLabel: '修改应用配置', + targetType: 'APP', + targetId: app.id, + beforeJson: before, + afterJson: JSON.stringify({ hosts, webhookUrl: app.webhookUrl }), + }) + return ok(toAppInfo(app)) +}) + +route('POST', '/admin/apps/:appCode/secret/rotate', ['fin:app:manage'], ctx => { + const app = appOf(ctx.params.appCode) + const secret = randomSecret('sk') + app.clientSecretPrevHash = app.clientSecretHash + app.clientSecretHash = digest(secret) + app.hasPrevSecret = true + const graceHours = num(ctx.body.graceHours, configValue('secret.rotate.grace_hours', 24)) + app.secretExpiresAt = plusDays(Math.max(1, Math.round(graceHours / 24))) + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'APP_SECRET_ROTATE', + actionLabel: '轮换应用密钥', + targetType: 'APP', + targetId: app.id, + afterJson: JSON.stringify({ graceHours }), + }) + return ok({ clientSecret: secret, expiresAt: app.secretExpiresAt }) +}) + +route('POST', '/admin/apps/:appCode/secret/revoke-prev', ['fin:app:manage'], ctx => { + const app = appOf(ctx.params.appCode) + ensure(app.hasPrevSecret, 422, '当前没有待回收的旧密钥') + app.clientSecretPrevHash = '' + app.hasPrevSecret = false + app.secretExpiresAt = null + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'APP_SECRET_REVOKE_PREV', + actionLabel: '立即回收旧密钥', + targetType: 'APP', + targetId: app.id, + }) + return ok(null) +}) + +route('POST', '/admin/apps/:appCode/toggle', ['fin:app:manage'], ctx => { + const app = appOf(ctx.params.appCode) + const enabled = num(ctx.body.enabled, 0) + app.enabled = enabled === 1 ? 1 : 0 + if (app.enabled === 0) { + db.tokens.forEach(item => { + if (item.appCode === app.appCode && !item.revokedAt) item.revokedAt = now() + }) + } + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'APP_TOGGLE', + actionLabel: app.enabled === 1 ? '启用应用' : '停用应用(熔断全部 token)', + targetType: 'APP', + targetId: app.id, + afterJson: JSON.stringify({ enabled: app.enabled }), + }) + return ok(toAppInfo(app)) +}) + +route('GET', '/admin/apps/:appCode/tokens', ['fin:view'], ctx => { + const app = appOf(ctx.params.appCode) + // 演示数据:真实环境为 fin_app_token 表(只存 hash) + if (!db.tokens.some(item => item.appCode === app.appCode)) { + for (let i = 0; i < 3; i += 1) { + db.tokens.push({ + id: nextId(), + appCode: app.appCode, + tokenHash: digest(`token-${app.appCode}-${i}`), + expiresAt: plusMinutes(15 - i * 4), + revokedAt: null, + issuedIp: `10.10.8.${30 + i}`, + createTime: daysAgo(0, 9 + i, 12), + }) + } + } + const list: AppTokenInfo[] = db.tokens + .filter(item => item.appCode === app.appCode) + .sort((a, b) => b.createTime.localeCompare(a.createTime)) + .map(item => ({ + id: item.id, + appCode: item.appCode, + tokenPrefix: `${item.tokenHash.slice(0, 8)}…`, + expiresAt: item.expiresAt, + revokedAt: item.revokedAt, + issuedIp: item.issuedIp, + createTime: item.createTime, + })) + return ok(list) +}) + +route('POST', '/admin/apps/:appCode/tokens/revoke', ['fin:app:manage'], ctx => { + const app = appOf(ctx.params.appCode) + const tokenId = num(ctx.body.tokenId, 0) + const targets = db.tokens.filter( + item => item.appCode === app.appCode && (tokenId ? item.id === tokenId : !item.revokedAt), + ) + targets.forEach(item => { + if (!item.revokedAt) item.revokedAt = now() + }) + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'APP_TOKEN_REVOKE', + actionLabel: tokenId ? '撤销单个 client token' : '熔断全部 client token', + targetType: 'APP', + targetId: app.id, + afterJson: JSON.stringify({ tokenId: tokenId || 'ALL', count: targets.length }), + }) + return ok({ revoked: targets.length }) +}) + +/* ----------------------------- 账户 ----------------------------- */ + +function toAccountInfo(account: AccountRecord): AccountInfo { + const { phoneHash: _hash, status: _status, firstSeenAt: _first, ...rest } = account + return rest +} + +route('GET', '/admin/accounts', ['fin:view'], ctx => { + const appCode = text(ctx.query.appCode) + const keyword = text(ctx.query.keyword).trim() + const minBalance = ctx.query.minBalance === undefined ? null : num(ctx.query.minBalance) + let list = db.accounts.slice() + if (appCode) list = list.filter(item => item.appCode === appCode) + if (keyword) { + list = list.filter( + item => contains(item.businessUserId, keyword) || contains(item.usernameSnapshot, keyword) || contains(item.phoneMasked, keyword), + ) + } + if (minBalance !== null) list = list.filter(item => item.balance >= minBalance) + list.sort((a, b) => b.balance - a.balance) + return ok(pageOf(list.map(toAccountInfo), ctx.query)) +}) + +route('GET', '/admin/accounts/:id', ['fin:view'], ctx => { + const account = db.accounts.find(item => item.id === num(ctx.params.id)) + ensure(account, 404, '钱包账户不存在') + const vip = db.vips.find( + item => item.appCode === account!.appCode && item.businessUserId === account!.businessUserId, + ) + const plan = vip ? db.plans.find(item => item.appCode === vip.appCode && item.planCode === vip.vipPlanCode) : null + return ok({ + account: toAccountInfo(account!), + vip: vip + ? { + planCode: vip.vipPlanCode, + planName: plan?.planName || vip.vipPlanCode, + vipUntil: vip.vipUntil, + effective: vip.vipUntil > now(), + freeDeduction: plan?.freeDeduction || 0, + } + : null, + transactions: db.transactions + .filter(item => item.appCode === account!.appCode && item.businessUserId === account!.businessUserId) + .sort((a, b) => b.createTime.localeCompare(a.createTime)) + .slice(0, 10), + }) +}) + +route('GET', '/admin/accounts/:id/transactions', ['fin:view'], ctx => { + const account = db.accounts.find(item => item.id === num(ctx.params.id)) + ensure(account, 404, '钱包账户不存在') + const list = db.transactions + .filter(item => item.appCode === account!.appCode && item.businessUserId === account!.businessUserId) + .sort((a, b) => b.createTime.localeCompare(a.createTime)) + return ok(pageOf(list, ctx.query)) +}) + +route('POST', '/admin/accounts/adjust', ['fin:account:adjust'], ctx => { + const appCode = text(ctx.body.appCode) + const businessUserId = text(ctx.body.businessUserId) + const amount = num(ctx.body.amount, 0) + const direction = text(ctx.body.direction) + const reason = text(ctx.body.reason).trim() + const secondApproverId = num(ctx.body.secondApproverId, 0) + const totp = text(ctx.body.totp) + + ensure(Number.isInteger(amount) && amount > 0, 6003, '调账点数必须为正整数') + ensure(direction === 'IN' || direction === 'OUT', 422, '调账方向不合法') + ensure(reason.length >= 5, 422, '调账原因不少于 5 个字') + ensure(totp === '123456', 4022, '动态口令不正确') + ensure(secondApproverId && secondApproverId !== ctx.admin!.id, 4095, '人工调账必须由另一名管理员复核,且不得为本人') + const approver = findAdmin(secondApproverId) + ensure(approver && approver.isActive === 1, 422, '复核管理员不存在或已停用') + ensure(['SUPER_ADMIN', 'FINANCE'].includes(approver!.role), 4095, '复核人必须具备资金操作权限') + + const account = accountOf(appCode, businessUserId) + ensure(account, 404, '钱包账户不存在') + const before = account!.balance + if (direction === 'OUT') ensure(account!.balance >= amount, 6006, '账户余额不足,调减后余额不能为负') + account!.balance = direction === 'IN' ? account!.balance + amount : account!.balance - amount + account!.versionNo += 1 + account!.updateTime = now() + + db.transactions.push({ + id: nextId(), + appCode, + appName: account!.appName, + businessUserId, + usernameSnapshot: account!.usernameSnapshot, + type: 'ADJUST', + amount, + balanceBefore: before, + balanceAfter: account!.balance, + businessRefId: null, + idempotencyKey: `adjust:${ctx.admin!.id}:${nextId()}`, + orderId: null, + outTradeNo: null, + refundOfId: null, + refundedPoints: 0, + operatorAdminName: ctx.admin!.username, + remark: reason, + createTime: now(), + }) + + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'ACCOUNT_ADJUST', + actionLabel: `人工调账(复核人:${approver!.username})`, + targetType: 'ACCOUNT', + targetId: account!.id, + beforeJson: JSON.stringify({ balance: before }), + afterJson: JSON.stringify({ balance: account!.balance, direction, amount, reason }), + }) + return ok(toAccountInfo(account!)) +}) + +/* ----------------------------- 订单 ----------------------------- */ + +/** 已占用退款额度(含待复核),用于可退上限校验,避免多张待复核单叠加超额退款 */ +function refundedSum(orderId: number, excludeRefundId?: number): number { + return db.refunds + .filter(item => item.orderId === orderId && item.status !== 'REJECTED' && item.id !== excludeRefundId) + .reduce((sum, item) => sum + item.amountCent, 0) +} + +/** 已实际出账的退款金额(仅 COMPLETED),用于判断订单是否已全额退款 */ +function completedRefundSum(orderId: number, excludeRefundId?: number): number { + return db.refunds + .filter(item => item.orderId === orderId && item.status === 'COMPLETED' && item.id !== excludeRefundId) + .reduce((sum, item) => sum + item.amountCent, 0) +} + +function enrichOrder(order: OrderRecord): OrderInfo { + order.refundedAmountCent = refundedSum(order.id) + order.cashInCent = db.cashFlows + .filter(item => item.orderId === order.id && item.direction === 'IN') + .reduce((sum, item) => sum + item.amountCent, 0) + order.cashOutCent = db.cashFlows + .filter(item => item.orderId === order.id && item.direction === 'OUT') + .reduce((sum, item) => sum + item.amountCent, 0) + order.needDualControl = order.amountCent >= dualThreshold(order.appCode) + return order +} + +function orderFilters(query: Record): OrderRecord[] { + const appCode = text(query.appCode) + const status = text(query.status) + const orderType = text(query.orderType) + const keyword = text(query.keyword).trim() + const from = query.from + const to = query.to + let list = db.orders.map(enrichOrder) + if (appCode) list = list.filter(item => item.appCode === appCode) + if (status) list = list.filter(item => item.status === status) + if (orderType) list = list.filter(item => item.orderType === orderType) + if (keyword) { + list = list.filter( + item => + contains(item.outTradeNo, keyword) || + contains(item.businessUserId, keyword) || + contains(item.usernameSnapshot, keyword), + ) + } + list = list.filter(item => inDate(item.createTime, from, to)) + list.sort((a, b) => b.createTime.localeCompare(a.createTime)) + return list +} + +route('GET', '/admin/orders', ['fin:view'], ctx => ok(pageOf(orderFilters(ctx.query), ctx.query))) + +route('GET', '/admin/orders/export', ['fin:export'], ctx => { + const list = orderFilters(ctx.query).slice(0, 10000) + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'ORDER_EXPORT', + actionLabel: `导出订单(${list.length} 条)`, + targetType: 'ORDER', + targetId: null, + }) + return ok(list) +}) + +route('GET', '/admin/orders/:id', ['fin:view'], ctx => { + const order = db.orders.find(item => item.id === num(ctx.params.id)) + ensure(order, 404, '订单不存在') + return ok({ + order: enrichOrder(order!), + refunds: db.refunds.filter(item => item.orderId === order!.id), + cashFlows: db.cashFlows.filter(item => item.orderId === order!.id), + }) +}) + +route('GET', '/admin/approvers', ['fin:recharge:confirm', 'fin:refund:review', 'fin:account:adjust'], ctx => { + const list = db.admins + .filter(item => item.isActive === 1 && item.id !== ctx.admin!.id && ['SUPER_ADMIN', 'FINANCE'].includes(item.role)) + .map(item => ({ id: item.id, username: item.username, role: item.role })) + return ok(list) +}) + +route('POST', '/admin/orders/:id/confirm', ['fin:recharge:confirm'], ctx => { + const order = db.orders.find(item => item.id === num(ctx.params.id)) + ensure(order, 404, '订单不存在') + ensure(order!.status === 'PENDING', 4093, '订单当前状态不可确认到账,请刷新后重试') + const voucherNo = text(ctx.body.voucherNo).trim() + const totp = text(ctx.body.totp) + const secondApproverId = num(ctx.body.secondApproverId, 0) + const receiveAt = text(ctx.body.receiveAt) || now() + + ensure(voucherNo.length >= 6, 422, '请填写银行回单/转账凭证号(不少于 6 位)') + ensure(voucherNo.length <= 32, 422, '凭证号不得超过 32 位') + ensure(totp === '123456', 4022, '动态口令不正确') + // 到账时间必须合法且落在「订单创建 ~ 当前」之间,避免用未来时间虚增当期收款 + ensure(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(receiveAt), 422, '到账时间格式不合法') + ensure(receiveAt >= order!.createTime, 422, '到账时间不能早于订单创建时间') + ensure(receiveAt <= now(), 422, '到账时间不能晚于当前时间') + // 同一银行凭证不得绑定到不同订单,防止一票多单重复入账 + ensure( + !db.cashFlows.some(item => item.direction === 'IN' && item.voucherNo === voucherNo && item.orderId !== order!.id), + 4098, + '该银行凭证号已被其他订单使用,请核对后重新录入', + ) + + // ---------- 先完成全部前置校验,再落库,避免「已置为已到账但入账失败」的中间态 ---------- + const threshold = dualThreshold(order!.appCode) + let approver: AdminRecord | undefined + if (order!.amountCent >= threshold) { + ensure(secondApproverId, 4094, `订单金额达到 ${threshold / 100} 元,必须由第二人复核后才能入账`) + ensure(secondApproverId !== ctx.admin!.id, 4095, '复核人不得与确认人为同一人') + approver = findAdmin(secondApproverId) + ensure(approver && approver.isActive === 1, 422, '复核管理员不存在或已停用') + ensure(['SUPER_ADMIN', 'FINANCE'].includes(approver!.role), 4095, '复核人必须具备资金操作权限') + } + + const plan = + order!.orderType === 'vip' + ? db.plans.find(item => item.appCode === order!.appCode && item.planCode === order!.vipPlanCode && item.enabled === 1) + : null + if (order!.orderType === 'vip') ensure(plan, 4001, 'VIP 档位不存在或已下架') + + const account = order!.orderType === 'vip' ? null : accountOf(order!.appCode, order!.businessUserId) + if (order!.orderType !== 'vip' && order!.pointsGained > 0) { + ensure(account, 404, '业务用户钱包不存在,无法入账') + } + + if (approver) { + order!.secondApproverId = approver.id + order!.secondApproverName = approver.username + } + + order!.status = 'PAID' + order!.paidAt = now() + order!.confirmedByAdminId = ctx.admin!.id + order!.confirmedByAdminName = ctx.admin!.username + + db.cashFlows.push({ + id: nextId(), + appCode: order!.appCode, + orderId: order!.id, + direction: 'IN', + amountCent: order!.amountCent, + receivedAt: receiveAt, + voucherNo, + operatorAdminId: ctx.admin!.id, + remark: '管理员确认到账', + }) + + if (order!.orderType === 'vip' && plan) { + let vip = db.vips.find( + item => item.appCode === order!.appCode && item.businessUserId === order!.businessUserId, + ) + const base = vip && vip.vipUntil > now() ? vip.vipUntil : now() + const vipUntil = plusDaysFrom(base, plan.durationDays) + if (!vip) { + vip = { + id: nextId(), + appCode: order!.appCode, + businessUserId: order!.businessUserId, + vipPlanCode: plan.planCode, + vipUntil, + } + db.vips.push(vip) + } else { + vip.vipPlanCode = plan.planCode + vip.vipUntil = vipUntil + } + const vipAccount = accountOf(order!.appCode, order!.businessUserId) + if (vipAccount) { + vipAccount.vipPlanCode = plan.planCode + vipAccount.vipUntil = vipUntil + } + } else if (order!.pointsGained > 0 && account) { + const before = account.balance + account.balance += order!.pointsGained + account.versionNo += 1 + account.updateTime = now() + db.transactions.push({ + id: nextId(), + appCode: order!.appCode, + appName: order!.appName, + businessUserId: order!.businessUserId, + usernameSnapshot: order!.usernameSnapshot, + type: 'RECHARGE', + amount: order!.pointsGained, + balanceBefore: before, + balanceAfter: account.balance, + businessRefId: order!.outTradeNo, + idempotencyKey: `order:${order!.outTradeNo}`, + orderId: order!.id, + outTradeNo: order!.outTradeNo, + refundOfId: null, + refundedPoints: 0, + operatorAdminName: ctx.admin!.username, + remark: '充值确认到账', + createTime: now(), + }) + } + + db.webhooks.push({ + id: nextId(), + appCode: order!.appCode, + appName: order!.appName, + eventId: `evt_${digest(order!.outTradeNo + now()).slice(0, 20)}`, + eventType: 'order.paid', + status: 'PENDING', + attempts: 0, + nextRetryAt: now(), + lastError: '', + payload: JSON.stringify({ outTradeNo: order!.outTradeNo, amountCent: order!.amountCent, points: order!.pointsGained }), + createTime: now(), + updateTime: now(), + }) + + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'ORDER_CONFIRM', + actionLabel: '确认订单到账', + targetType: 'ORDER', + targetId: order!.id, + beforeJson: JSON.stringify({ status: 'PENDING' }), + afterJson: JSON.stringify({ + status: 'PAID', + voucherNo, + secondApproverId: order!.secondApproverId, + }), + }) + return ok(enrichOrder(order!)) +}) + +function plusDaysFrom(base: string, days: number): string { + const date = new Date(base.replace(' ', 'T')) + date.setDate(date.getDate() + days) + const pad = (n: number): string => String(n).padStart(2, '0') + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad( + date.getHours(), + )}:${pad(date.getMinutes())}:${pad(date.getSeconds())}` +} + +route('POST', '/admin/orders/:id/cancel', ['fin:order:cancel'], ctx => { + const order = db.orders.find(item => item.id === num(ctx.params.id)) + ensure(order, 404, '订单不存在') + ensure(order!.status === 'PENDING', 4093, '仅待确认订单可以关单') + const reason = text(ctx.body.reason).trim() + ensure(reason.length >= 5, 422, '请填写关单原因(不少于 5 个字)') + ensure(text(ctx.body.totp) === '123456', 4022, '动态口令不正确') + order!.status = 'CANCELLED' + order!.remark = reason + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'ORDER_CANCEL', + actionLabel: '关闭订单', + targetType: 'ORDER', + targetId: order!.id, + beforeJson: JSON.stringify({ status: 'PENDING' }), + afterJson: JSON.stringify({ status: 'CANCELLED', reason }), + }) + return ok(enrichOrder(order!)) +}) + +/* ----------------------------- 退款 ----------------------------- */ + +function refundFilters(query: Record): RefundRecord[] { + const appCode = text(query.appCode) + const status = text(query.status) + const keyword = text(query.keyword).trim() + let list = db.refunds.slice() + if (appCode) list = list.filter(item => item.appCode === appCode) + if (status) list = list.filter(item => item.status === status) + if (keyword) { + list = list.filter(item => contains(item.outTradeNo, keyword) || contains(item.voucherNo, keyword)) + } + list = list.filter(item => inDate(item.createTime, query.from, query.to)) + list.sort((a, b) => b.createTime.localeCompare(a.createTime)) + return list +} + +route('GET', '/admin/refunds', ['fin:view'], ctx => ok(pageOf(refundFilters(ctx.query), ctx.query))) + +route('POST', '/admin/refunds', ['fin:refund:create'], ctx => { + const orderId = num(ctx.body.orderId) + const amountCent = num(ctx.body.amountCent) + const reason = text(ctx.body.reason).trim() + const voucherNo = text(ctx.body.voucherNo).trim() + const totp = text(ctx.body.totp) + + ensure(text(ctx.body.idempotencyKey).length >= 8, 4091, '缺少幂等键,请刷新页面后重试') + ensure(totp === '123456', 4022, '动态口令不正确') + ensure(Number.isInteger(amountCent) && amountCent > 0, 422, '退款金额必须大于 0') + ensure(reason.length >= 5, 422, '请填写退款原因(不少于 5 个字)') + + const order = db.orders.find(item => item.id === orderId) + ensure(order, 404, '原订单不存在') + ensure(order!.status === 'PAID' || order!.status === 'REFUNDED', 4093, '仅已到账订单可以退款') + ensure(order!.payMethod === 'offline', 422, '二期在线支付退款链路未开放') + const already = refundedSum(order!.id) + ensure(amountCent <= order!.amountCent - already, 6004, '退款金额超出可退上限(含待复核退款)') + + // 扣回点数按订单成交时的兑率折算,不能使用当前最新兑率(改价后会把退款点数算错) + const pointsDeducted = + order!.orderType === 'vip' || order!.amountCent <= 0 + ? 0 + : Math.round((amountCent * order!.pointsGained) / order!.amountCent) + const account = accountOf(order!.appCode, order!.businessUserId) + if (pointsDeducted > 0) { + ensure(account, 404, '钱包账户不存在') + ensure(account!.balance >= pointsDeducted, 6006, '用户已消耗部分点数,余额不足以扣回,请人工核算后部分退款') + } + + const threshold = dualThreshold(order!.appCode) + const autoComplete = amountCent < threshold + // 立即出账的退款必须有银行凭证,禁止在无凭证的情况下直接生成现金流出 + if (autoComplete) ensure(voucherNo.length >= 6, 422, '现金退款必须登记银行凭证号(不少于 6 位)') + + const refund: RefundRecord = { + id: nextId(), + appCode: order!.appCode, + appName: order!.appName, + businessUserId: order!.businessUserId, + usernameSnapshot: order!.usernameSnapshot, + orderId: order!.id, + outTradeNo: order!.outTradeNo, + amountCent, + pointsDeducted, + status: autoComplete ? 'COMPLETED' : 'PENDING', + operatorAdminId: ctx.admin!.id, + operatorAdminName: ctx.admin!.username, + reviewerAdminId: null, + reviewerAdminName: null, + voucherNo, + remark: reason, + createTime: now(), + updateTime: now(), + } + + if (autoComplete) { + refund.reviewerAdminId = ctx.admin!.id + refund.reviewerAdminName = ctx.admin!.username + applyRefund(refund, ctx.admin!.username) + } + db.refunds.push(refund) + + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'REFUND_CREATE', + actionLabel: '发起现金退款', + targetType: 'REFUND', + targetId: refund.id, + afterJson: JSON.stringify({ amountCent, pointsDeducted, status: refund.status, orderId: order!.id }), + }) + return ok(refund) +}) + +function applyRefund(refund: RefundRecord, operator: string): void { + const order = db.orders.find(item => item.id === refund.orderId) + ensure(order, 404, '原订单不存在') + // 出账必须有真实银行凭证,禁止用占位凭证号生成现金流出记录 + ensure(refund.voucherNo.length >= 6, 422, '现金退款必须登记银行凭证号(不少于 6 位)') + const account = accountOf(refund.appCode, refund.businessUserId) + + if (refund.pointsDeducted > 0 && account) { + ensure(account.balance >= refund.pointsDeducted, 6006, '余额不足以扣回点数,退款无法生效') + const before = account.balance + account.balance -= refund.pointsDeducted + account.versionNo += 1 + account.updateTime = now() + db.transactions.push({ + id: nextId(), + appCode: refund.appCode, + appName: refund.appName, + businessUserId: refund.businessUserId, + usernameSnapshot: refund.usernameSnapshot, + type: 'REFUND_OUT', + amount: refund.pointsDeducted, + balanceBefore: before, + balanceAfter: account.balance, + businessRefId: refund.outTradeNo, + idempotencyKey: `refund:${refund.id}`, + orderId: order!.id, + outTradeNo: order!.outTradeNo, + refundOfId: null, + refundedPoints: 0, + operatorAdminName: operator, + remark: '现金退款扣回点数', + createTime: now(), + }) + } + + db.cashFlows.push({ + id: nextId(), + appCode: refund.appCode, + orderId: refund.orderId, + direction: 'OUT', + amountCent: refund.amountCent, + receivedAt: now(), + voucherNo: refund.voucherNo, + operatorAdminId: refund.operatorAdminId, + remark: '现金退款', + }) + + // 即时退款路径当前单尚未入列表,复核通过路径当前单已入列表且状态为 COMPLETED; + // 统计时必须排除自身,否则复核通过时会把本单重复计入,导致订单被错误标记为全额退款 + const occupied = refundedSum(order!.id, refund.id) + refund.amountCent + const completed = completedRefundSum(order!.id, refund.id) + refund.amountCent + order!.refundedAmountCent = occupied + order!.status = completed >= order!.amountCent ? 'REFUNDED' : 'PAID' + + // 全额退款必须同步撤销 VIP 权益,否则用户退款后仍可继续享受免扣费 + if (completed >= order!.amountCent && order!.orderType === 'vip') { + const vip = db.vips.find( + item => item.appCode === order!.appCode && item.businessUserId === order!.businessUserId, + ) + if (vip) vip.vipUntil = now() + const vipAccount = accountOf(order!.appCode, order!.businessUserId) + if (vipAccount) { + vipAccount.vipPlanCode = null + vipAccount.vipUntil = null + } + } + + db.webhooks.push({ + id: nextId(), + appCode: refund.appCode, + appName: refund.appName, + eventId: `evt_${digest(refund.outTradeNo + refund.amountCent).slice(0, 20)}`, + eventType: 'order.refunded', + status: 'PENDING', + attempts: 0, + nextRetryAt: now(), + lastError: '', + payload: JSON.stringify({ outTradeNo: refund.outTradeNo, refundAmountCent: refund.amountCent }), + createTime: now(), + updateTime: now(), + }) +} + +route('POST', '/admin/refunds/:id/review', ['fin:refund:review'], ctx => { + const refund = db.refunds.find(item => item.id === num(ctx.params.id)) + ensure(refund, 404, '退款单不存在') + ensure(refund!.status === 'PENDING', 4093, '退款单已处理,请刷新后重试') + ensure(refund!.operatorAdminId !== ctx.admin!.id, 4095, '退款发起人不得复核自己发起的退款单') + ensure(text(ctx.body.totp) === '123456', 4022, '动态口令不正确') + const action = text(ctx.body.action) + ensure(action === 'approve' || action === 'reject', 422, '复核动作不合法') + + if (action === 'reject') { + refund!.status = 'REJECTED' + refund!.reviewerAdminId = ctx.admin!.id + refund!.reviewerAdminName = ctx.admin!.username + refund!.remark = text(ctx.body.reason).trim() || refund!.remark + refund!.updateTime = now() + } else { + const voucherNo = text(ctx.body.voucherNo).trim() + ensure(voucherNo.length >= 6, 422, '现金退款必须登记银行凭证号') + refund!.voucherNo = voucherNo + refund!.status = 'COMPLETED' + refund!.reviewerAdminId = ctx.admin!.id + refund!.reviewerAdminName = ctx.admin!.username + refund!.updateTime = now() + applyRefund(refund!, ctx.admin!.username) + } + + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'REFUND_REVIEW', + actionLabel: action === 'approve' ? '复核通过现金退款' : '驳回现金退款', + targetType: 'REFUND', + targetId: refund!.id, + beforeJson: JSON.stringify({ status: 'PENDING' }), + afterJson: JSON.stringify({ status: refund!.status, voucherNo: refund!.voucherNo }), + }) + return ok(refund) +}) + +/* ----------------------------- 流水 ----------------------------- */ + +function txFilters(query: Record): TransactionInfo[] { + const appCode = text(query.appCode) + const type = text(query.type) + const keyword = text(query.keyword).trim() + let list = db.transactions.slice() + if (appCode) list = list.filter(item => item.appCode === appCode) + if (type) list = list.filter(item => item.type === type) + if (keyword) { + list = list.filter( + item => + contains(item.businessUserId, keyword) || + contains(item.usernameSnapshot, keyword) || + contains(item.idempotencyKey, keyword) || + contains(item.businessRefId, keyword), + ) + } + list = list.filter(item => inDate(item.createTime, query.from, query.to)) + list.sort((a, b) => b.createTime.localeCompare(a.createTime)) + return list +} + +route('GET', '/admin/transactions', ['fin:view'], ctx => ok(pageOf(txFilters(ctx.query), ctx.query))) + +route('GET', '/admin/transactions/export', ['fin:export'], ctx => { + const list = txFilters(ctx.query).slice(0, 10000) + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'TRANSACTION_EXPORT', + actionLabel: `导出点数流水(${list.length} 条)`, + targetType: 'TRANSACTION', + targetId: null, + }) + return ok(list) +}) + +/* ----------------------------- VIP ----------------------------- */ + +route('GET', '/admin/vip-plans', ['fin:view'], ctx => { + refreshAppStats() + const appCode = text(ctx.query.appCode) + const list = db.plans.filter(item => (appCode ? item.appCode === appCode : true)) + return ok(list) +}) + +route('POST', '/admin/vip-plans', ['fin:vip:manage'], ctx => { + const app = appOf(text(ctx.body.appCode)) + const planCode = text(ctx.body.planCode).trim() + const planName = text(ctx.body.planName).trim() + const durationDays = num(ctx.body.durationDays) + const priceCent = num(ctx.body.priceCent) + ensure(/^[A-Z][A-Z0-9_]{2,31}$/.test(planCode), 422, '档位编码需为大写字母、数字与下划线,长度 3~32') + ensure(planName.length >= 2, 422, '档位名称至少 2 个字') + ensure(Number.isInteger(durationDays) && durationDays > 0, 422, '有效期天数必须为正整数') + ensure(Number.isInteger(priceCent) && priceCent > 0, 422, '价格必须大于 0') + ensure(!db.plans.some(item => item.appCode === app.appCode && item.planCode === planCode), 4221, '同应用下档位编码已存在') + + const plan: VipPlan = { + id: nextId(), + appCode: app.appCode, + appName: app.appName, + planCode, + planName, + durationDays, + priceCent, + freeDeduction: num(ctx.body.freeDeduction, 0) === 1 ? 1 : 0, + enabled: 1, + holderCount: 0, + createTime: now(), + } + db.plans.push(plan) + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'VIP_PLAN_CREATE', + actionLabel: '新增 VIP 档位', + targetType: 'VIP_PLAN', + targetId: plan.id, + afterJson: JSON.stringify({ planCode, durationDays, priceCent }), + }) + return ok(plan) +}) + +route('PUT', '/admin/vip-plans/:id', ['fin:vip:manage'], ctx => { + const plan = db.plans.find(item => item.id === num(ctx.params.id)) + ensure(plan, 404, 'VIP 档位不存在') + const before = JSON.stringify({ priceCent: plan!.priceCent, durationDays: plan!.durationDays }) + const priceCent = num(ctx.body.priceCent, plan!.priceCent) + const durationDays = num(ctx.body.durationDays, plan!.durationDays) + ensure(Number.isInteger(priceCent) && priceCent > 0, 422, '价格必须大于 0') + ensure(Number.isInteger(durationDays) && durationDays > 0, 422, '有效期天数必须为正整数') + ensure(text(ctx.body.totp) === '123456', 4022, '动态口令不正确') + + plan!.planName = text(ctx.body.planName).trim() || plan!.planName + plan!.priceCent = priceCent + plan!.durationDays = durationDays + plan!.freeDeduction = num(ctx.body.freeDeduction, plan!.freeDeduction) === 1 ? 1 : 0 + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'VIP_PLAN_UPDATE', + actionLabel: '修改 VIP 档位(改价)', + targetType: 'VIP_PLAN', + targetId: plan!.id, + beforeJson: before, + afterJson: JSON.stringify({ priceCent, durationDays }), + }) + return ok(plan) +}) + +route('POST', '/admin/vip-plans/:id/toggle', ['fin:vip:manage'], ctx => { + const plan = db.plans.find(item => item.id === num(ctx.params.id)) + ensure(plan, 404, 'VIP 档位不存在') + plan!.enabled = num(ctx.body.enabled, 0) === 1 ? 1 : 0 + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'VIP_PLAN_TOGGLE', + actionLabel: plan!.enabled === 1 ? '上架 VIP 档位' : '下架 VIP 档位', + targetType: 'VIP_PLAN', + targetId: plan!.id, + }) + return ok(plan) +}) + +route('GET', '/admin/vips', ['fin:view'], ctx => { + const appCode = text(ctx.query.appCode) + const keyword = text(ctx.query.keyword).trim() + let list = db.vips.slice() + if (appCode) list = list.filter(item => item.appCode === appCode) + const records = list + .map(item => { + const account = db.accounts.find( + accountItem => accountItem.appCode === item.appCode && accountItem.businessUserId === item.businessUserId, + ) + return { + id: item.id, + appCode: item.appCode, + appName: db.apps.find(app => app.appCode === item.appCode)?.appName || item.appCode, + businessUserId: item.businessUserId, + usernameSnapshot: account?.usernameSnapshot || '', + vipPlanCode: item.vipPlanCode, + vipUntil: item.vipUntil, + effective: item.vipUntil > now(), + } + }) + .filter(item => (keyword ? contains(item.businessUserId, keyword) || contains(item.usernameSnapshot, keyword) : true)) + .sort((a, b) => b.vipUntil.localeCompare(a.vipUntil)) + return ok(pageOf(records, ctx.query)) +}) + +/* ----------------------------- 定价与策略 ----------------------------- */ + +route('GET', '/admin/pricing', ['fin:view'], () => ok(db.pricing)) + +route('PUT', '/admin/pricing/:appCode', ['fin:pricing:edit'], ctx => { + const app = appOf(ctx.params.appCode) + const item = db.pricing.find(entry => entry.appCode === app.appCode) + ensure(item, 404, '兑率配置不存在') + ensure(text(ctx.body.totp) === '123456', 4022, '动态口令不正确') + const rate = num(ctx.body.pointsPerYuan) + ensure(Number.isInteger(rate) && rate > 0, 422, '兑率必须为正整数(1 元可兑换的点数)') + // 兑率过高会让充值点数瞬间膨胀,属于变相发币,必须设置业务上限 + ensure(rate <= 10000, 422, '兑率超出业务上限(1 元最多兑换 10000 点)') + + const before = JSON.stringify({ pointsPerYuan: item!.pointsPerYuan }) + item!.pointsPerYuan = rate + item!.enabled = num(ctx.body.enabled, item!.enabled) === 1 ? 1 : 0 + item!.updateTime = now() + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'PRICING_UPDATE', + actionLabel: '修改兑率', + targetType: 'PRICING', + targetId: app.id, + beforeJson: before, + afterJson: JSON.stringify({ pointsPerYuan: rate }), + }) + return ok(item) +}) + +route('GET', '/admin/policies', ['fin:view'], () => ok(db.policies)) + +route('PUT', '/admin/policies/:appCode', ['fin:pricing:edit'], ctx => { + const app = appOf(ctx.params.appCode) + const item = db.policies.find(entry => entry.appCode === app.appCode) + ensure(item, 404, '扣费策略不存在') + ensure(text(ctx.body.totp) === '123456', 4022, '动态口令不正确') + const minCost = num(ctx.body.minCost) + const maxPoints = num(ctx.body.maxPointsPerCharge) + const threshold = num(ctx.body.dualControlThresholdCent) + ensure(Number.isInteger(minCost) && minCost >= 0, 422, '保底消费必须为不小于 0 的整数') + ensure(Number.isInteger(maxPoints) && maxPoints >= Math.max(1, minCost), 422, '单次扣费上限不得小于保底消费') + ensure(Number.isInteger(threshold) && threshold >= 0, 422, '双人复核阈值不合法') + + const before = JSON.stringify({ + minCost: item!.minCost, + maxPointsPerCharge: item!.maxPointsPerCharge, + vipExempt: item!.vipExempt, + }) + item!.minCost = minCost + item!.maxPointsPerCharge = maxPoints + item!.vipExempt = num(ctx.body.vipExempt, item!.vipExempt) === 1 ? 1 : 0 + item!.failedStrategy = text(ctx.body.failedStrategy) === 'actual' ? 'actual' : 'none' + item!.dualControlThresholdCent = threshold + item!.updateTime = now() + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'POLICY_UPDATE', + actionLabel: '修改扣费策略', + targetType: 'POLICY', + targetId: app.id, + beforeJson: before, + afterJson: JSON.stringify({ minCost, maxPoints, threshold }), + }) + return ok(item) +}) + +/* ----------------------------- 对账 ----------------------------- */ + +route('GET', '/admin/reconcile/reports', ['fin:view'], () => { + const list = db.reports.slice().sort((a, b) => b.createTime.localeCompare(a.createTime)) + return ok(list.map(item => ({ ...item, details: [] }))) +}) + +route('GET', '/admin/reconcile/reports/:id', ['fin:view'], ctx => { + const report = db.reports.find(item => item.id === ctx.params.id) + ensure(report, 404, '对账报告不存在') + return ok(report) +}) + +route('POST', '/admin/reconcile/run', ['fin:reconcile:run'], ctx => { + const appCode = text(ctx.body.appCode) + const windowStart = text(ctx.body.windowStart) + const windowEnd = text(ctx.body.windowEnd) + ensure(appCode, 422, '请选择接入应用') + appOf(appCode) + ensure(/^\d{4}-\d{2}-\d{2}$/.test(windowStart) && /^\d{4}-\d{2}-\d{2}$/.test(windowEnd), 422, '对账窗口格式不合法') + ensure(windowStart <= windowEnd, 422, '开始日期不能晚于结束日期') + // 未结束的窗口对账没有意义,且会导致后续流水被重复核对 + const today = now().slice(0, 10) + ensure(windowEnd <= today, 422, '对账结束日期不能晚于今天') + const spanDays = (Date.parse(`${windowEnd}T00:00:00`) - Date.parse(`${windowStart}T00:00:00`)) / 86400000 + 1 + ensure(Number.isFinite(spanDays) && spanDays > 0 && spanDays <= 366, 422, '单次对账窗口不得超过 366 天,请拆分批次执行') + const report = buildReport(appCode, windowStart, windowEnd, ctx.admin!.username) + db.reports.push(report) + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'RECONCILE_RUN', + actionLabel: '执行对账', + targetType: 'RECONCILE', + targetId: null, + afterJson: JSON.stringify({ appCode, windowStart, windowEnd, status: report.status }), + }) + return ok(report) +}) + +/* ----------------------------- 管理员 ----------------------------- */ + +route('GET', '/admin/admins', ['fin:admin:manage'], () => ok(db.admins.map(toAdmin))) + +route('POST', '/admin/admins', ['fin:admin:manage'], ctx => { + const username = text(ctx.body.username).trim() + const role = text(ctx.body.role) + ensure(/^[a-z][a-z0-9_]{2,31}$/.test(username), 422, '用户名需为 3~32 位小写字母、数字或下划线') + ensure(['SUPER_ADMIN', 'FINANCE', 'AUDITOR'].includes(role), 422, '角色不合法') + ensure(!db.admins.some(item => item.username === username), 4221, '用户名已存在') + ensure(text(ctx.body.totp) === '123456', 4022, '动态口令不正确') + + const tempPassword = `Tmp@${randomSecret('p').slice(3, 11)}9` + const admin: AdminRecord = { + id: nextId(), + username, + password: tempPassword, + passwordHistory: [], + role: role as AdminInfo['role'], + isActive: 1, + mustChangePassword: 1, + totpBound: false, + failedAttempts: 0, + lockedUntil: null, + lastLoginAt: null, + lastLoginIp: null, + createTime: now(), + } + db.admins.push(admin) + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'ADMIN_CREATE', + actionLabel: '创建管理员', + targetType: 'ADMIN', + targetId: admin.id, + afterJson: JSON.stringify({ username, role }), + }) + return ok({ admin: toAdmin(admin), initialPassword: tempPassword }) +}) + +route('PUT', '/admin/admins/:id', ['fin:admin:manage'], ctx => { + const admin = findAdmin(num(ctx.params.id)) + ensure(admin, 404, '管理员不存在') + const role = text(ctx.body.role) || admin!.role + ensure(['SUPER_ADMIN', 'FINANCE', 'AUDITOR'].includes(role), 422, '角色不合法') + if (admin!.role === 'SUPER_ADMIN' && role !== 'SUPER_ADMIN') { + ensure(activeAdminCount() > 1, 4096, '系统必须保留至少一名启用状态的超级管理员') + } + const before = JSON.stringify({ role: admin!.role, isActive: admin!.isActive }) + admin!.role = role as AdminInfo['role'] + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'ADMIN_UPDATE_ROLE', + actionLabel: '调整管理员角色', + targetType: 'ADMIN', + targetId: admin!.id, + beforeJson: before, + afterJson: JSON.stringify({ role }), + }) + return ok(toAdmin(admin!)) +}) + +route('POST', '/admin/admins/:id/toggle', ['fin:admin:manage'], ctx => { + const admin = findAdmin(num(ctx.params.id)) + ensure(admin, 404, '管理员不存在') + ensure(admin!.id !== ctx.admin!.id, 4096, '不能停用当前登录账号') + const enable = num(ctx.body.enabled, 0) === 1 + if (!enable && admin!.role === 'SUPER_ADMIN') { + ensure(activeAdminCount() > 1, 4096, '系统必须保留至少一名启用状态的超级管理员') + } + admin!.isActive = enable ? 1 : 0 + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'ADMIN_TOGGLE', + actionLabel: enable ? '启用管理员' : '停用管理员', + targetType: 'ADMIN', + targetId: admin!.id, + afterJson: JSON.stringify({ isActive: admin!.isActive }), + }) + return ok(toAdmin(admin!)) +}) + +route('POST', '/admin/admins/:id/reset-password', ['fin:admin:manage'], ctx => { + const admin = findAdmin(num(ctx.params.id)) + ensure(admin, 404, '管理员不存在') + // 重置本人密码属于绕过原密码校验,必须走“修改密码”流程 + ensure(admin!.id !== ctx.admin!.id, 4096, '不能重置当前登录账号的密码,请使用修改密码功能') + ensure(text(ctx.body.totp) === '123456', 4022, '动态口令不正确') + const tempPassword = `Rst@${randomSecret('p').slice(3, 11)}7` + admin!.passwordHistory = [admin!.password, ...admin!.passwordHistory].slice(0, 3) + admin!.password = tempPassword + admin!.mustChangePassword = 1 + admin!.failedAttempts = 0 + admin!.lockedUntil = null + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'ADMIN_RESET_PASSWORD', + actionLabel: '重置管理员密码', + targetType: 'ADMIN', + targetId: admin!.id, + }) + return ok({ tempPassword }) +}) + +route('POST', '/admin/admins/:id/reset-totp', ['fin:admin:manage'], ctx => { + const admin = findAdmin(num(ctx.params.id)) + ensure(admin, 404, '管理员不存在') + ensure(text(ctx.body.totp) === '123456', 4022, '动态口令不正确') + admin!.totpBound = false + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'ADMIN_RESET_TOTP', + actionLabel: '重置管理员动态口令', + targetType: 'ADMIN', + targetId: admin!.id, + }) + return ok({ message: '该管理员下次登录需重新绑定身份验证器' }) +}) + +/* ----------------------------- 审计 ----------------------------- */ + +route('GET', '/admin/audit-logs', ['fin:audit:view'], ctx => { + const actor = text(ctx.query.actor).trim() + const action = text(ctx.query.action) + const result = text(ctx.query.result) + const keyword = text(ctx.query.keyword).trim() + let list = db.audits.slice() + if (actor) list = list.filter(item => contains(item.actorName, actor)) + if (action) list = list.filter(item => item.action === action) + if (result) list = list.filter(item => item.result === result) + if (keyword) { + list = list.filter( + item => contains(item.actionLabel, keyword) || contains(item.targetType, keyword) || contains(item.curHash, keyword), + ) + } + list = list.filter(item => inDate(item.createTime, ctx.query.from, ctx.query.to)) + list.sort((a, b) => b.createTime.localeCompare(a.createTime)) + return ok(pageOf(list, ctx.query)) +}) + +route('GET', '/admin/audit-logs/export', ['fin:export'], ctx => { + const list = db.audits.slice().sort((a, b) => b.createTime.localeCompare(a.createTime)).slice(0, 10000) + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'AUDIT_EXPORT', + actionLabel: `导出审计日志(${list.length} 条)`, + targetType: 'AUDIT', + targetId: null, + }) + return ok(list) +}) + +// 注意:参数路由必须注册在 /export、/verify 等固定路径之后,否则会被 :id 抢先匹配 +route('GET', '/admin/audit-logs/:id', ['fin:audit:view'], ctx => { + const log = db.audits.find(item => item.id === num(ctx.params.id)) + ensure(log, 404, '审计日志不存在') + return ok(log) +}) + +route('POST', '/admin/audit-logs/verify', ['fin:audit:view'], ctx => { + const sorted = db.audits.slice().sort((a, b) => a.id - b.id) + let prev = '' + let brokenAtId: number | null = null + sorted.forEach(item => { + // 必须与写入时使用同一套摘要算法(auditHash),否则链校验会与真实数据不一致 + const expected = auditHash(item, prev) + if (item.prevHash !== prev || item.curHash !== expected) { + if (!brokenAtId) brokenAtId = item.id + } + prev = item.curHash + }) + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'AUDIT_CHAIN_VERIFY', + actionLabel: '校验审计哈希链', + targetType: 'AUDIT', + targetId: null, + afterJson: JSON.stringify({ brokenAtId, checked: sorted.length }), + }) + return ok({ + valid: brokenAtId === null, + checked: sorted.length, + brokenAtId, + checkedAt: now(), + message: brokenAtId === null ? '哈希链完整,未发现篡改' : `哈希链在第 ${brokenAtId} 条日志处断裂`, + }) +}) + +/* ----------------------------- 全局参数 ----------------------------- */ + +route('GET', '/admin/configs', ['fin:view'], () => ok(db.configs)) + +route('PUT', '/admin/configs/:key', ['fin:config:edit'], ctx => { + const item = db.configs.find(entry => entry.configKey === ctx.params.key) + ensure(item, 404, '配置项不存在') + ensure(text(ctx.body.totp) === '123456', 4022, '动态口令不正确') + const reason = text(ctx.body.reason).trim() + ensure(reason.length >= 5, 422, '请填写变更原因(不少于 5 个字)') + const value = text(ctx.body.value).trim() + ensure(value.length > 0 && value.length <= 255, 422, '配置值不能为空且不超过 255 字符') + if (item!.configKey === 'pii.mask.enabled') { + ensure(['0', '1'].includes(value), 422, '该开关仅允许 0 或 1') + ensure(value === '1', 4097, 'PII 掩码禁止关闭(高危变更需运维窗口与专项审批)') + } + const before = item!.configValue + item!.configValue = value + item!.updateBy = ctx.admin!.username + item!.updateTime = now() + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'CONFIG_UPDATE', + actionLabel: '修改全局参数', + targetType: 'CONFIG', + targetId: null, + beforeJson: JSON.stringify({ [item!.configKey]: before }), + afterJson: JSON.stringify({ [item!.configKey]: value, reason }), + }) + return ok(item) +}) + +/* ----------------------------- webhook ----------------------------- */ + +route('GET', '/admin/webhooks', ['fin:view'], ctx => { + const appCode = text(ctx.query.appCode) + const status = text(ctx.query.status) + const keyword = text(ctx.query.keyword).trim() + let list = db.webhooks.slice() + if (appCode) list = list.filter(item => item.appCode === appCode) + if (status) list = list.filter(item => item.status === status) + if (keyword) list = list.filter(item => contains(item.eventId, keyword) || contains(item.eventType, keyword)) + list = list.filter(item => inDate(item.createTime, ctx.query.from, ctx.query.to)) + list.sort((a, b) => b.createTime.localeCompare(a.createTime)) + return ok(pageOf(list, ctx.query)) +}) + +route('POST', '/admin/webhooks/:id/replay', ['fin:webhook:manage'], ctx => { + const item = db.webhooks.find(entry => entry.id === num(ctx.params.id)) + ensure(item, 404, '投递记录不存在') + ensure(text(ctx.body.totp) === '123456', 4022, '动态口令不正确') + ensure(item!.status === 'FAILED' || item!.status === 'DEAD', 422, '仅失败记录可以重放') + item!.status = 'PENDING' + item!.attempts = 0 + item!.nextRetryAt = now() + item!.lastError = '' + item!.updateTime = now() + appendAudit({ + actorId: ctx.admin!.id, + actorName: ctx.admin!.username, + action: 'WEBHOOK_REPLAY', + actionLabel: '手动重放 webhook', + targetType: 'WEBHOOK', + targetId: item!.id, + afterJson: JSON.stringify({ eventId: item!.eventId }), + }) + return ok(item) +}) + +/* ----------------------------- 公开收款页 ----------------------------- */ + +interface TicketRecordLike { + ticket: string + appCode: string + businessUserId: string + expiresAt: string + usedAt: string | null +} + +function assertRedirectUri(app: AppRecord, redirectUri: string): void { + if (!redirectUri) return + let host = '' + try { + host = new URL(redirectUri).hostname + } catch { + throw new MockError(400, '跳转地址格式不合法') + } + const allowed = app.allowedRedirectHosts.split(',').map(item => item.trim()) + ensure(allowed.includes(host), 400, '跳转地址不在白名单内') + ensure(/^https:\/\//.test(redirectUri) || /^http:\/\/(127\.0\.0\.1|localhost)/.test(redirectUri), 400, '外部跳转必须使用 HTTPS') +} + +function validTicket(appCode: string, ticketNo: string, redirectUri: string): TicketRecordLike { + const ticket = db.tickets.find(item => item.ticket === ticketNo) + ensure(ticket, 7001, '凭证无效或已被使用') + ensure(ticket!.appCode === appCode, 7001, '凭证与应用不匹配') + ensure(!ticket!.usedAt, 7001, '凭证已被使用,请返回业务系统重新发起') + ensure(ticket!.expiresAt > now(), 7001, '凭证已过期,请返回业务系统重新发起') + const app = appOf(appCode) + ensure(app.enabled === 1, 4003, '应用已停用,暂不支持收款') + assertRedirectUri(app, redirectUri) + return ticket! +} + +route('GET', '/pay/preview', null, ctx => { + const appCode = text(ctx.query.appCode) + const ticketNo = text(ctx.query.ticket) + const redirectUri = text(ctx.query.redirectUri) + ensure(appCode && ticketNo, 7001, '缺少凭证参数') + const ticket = validTicket(appCode, ticketNo, redirectUri) + const app = appOf(appCode) + const account = accountOf(appCode, ticket.businessUserId) + const pricing = db.pricing.find(item => item.appCode === appCode) + const vip = db.vips.find(item => item.appCode === appCode && item.businessUserId === ticket.businessUserId) + const plan = vip ? db.plans.find(item => item.appCode === appCode && item.planCode === vip.vipPlanCode) : null + return ok({ + appCode, + appName: app.appName, + businessUserId: ticket.businessUserId, + usernameSnapshot: account?.usernameSnapshot || '业务用户', + balance: account?.balance || 0, + pointsPerYuan: pricing?.pointsPerYuan || 100, + minAmountCent: 100, + vip: vip + ? { + planCode: vip.vipPlanCode, + planName: plan?.planName || vip.vipPlanCode, + vipUntil: vip.vipUntil, + freeDeduction: plan?.freeDeduction || 0, + } + : null, + plans: db.plans + .filter(item => item.appCode === appCode && item.enabled === 1) + .map(item => ({ + planCode: item.planCode, + planName: item.planName, + durationDays: item.durationDays, + priceCent: item.priceCent, + freeDeduction: item.freeDeduction, + })), + ticketExpiresAt: ticket.expiresAt, + }) +}) + +route('POST', '/pay/orders', null, ctx => { + const appCode = text(ctx.body.appCode) + const ticketNo = text(ctx.body.ticket) + const orderType = text(ctx.body.orderType) + const redirectUri = text(ctx.body.redirectUri) + const idempotencyKey = text(ctx.body.idempotencyKey).trim() + ensure(orderType === 'recharge' || orderType === 'vip', 422, '订单类型不合法') + + // 幂等:重复提交必须返回首次下单结果,不能再消耗凭证或生成第二笔订单 + // 幂等键按应用隔离,防止跨应用复用到其他应用的订单信息 + const storeKey = idempotencyKey ? `${appCode}|${idempotencyKey}` : '' + if (idempotencyKey) { + ensure(/^[A-Za-z0-9:_-]{8,64}$/.test(idempotencyKey), 422, '幂等键格式不合法') + const existingId = db.idempotency.get(storeKey) + if (existingId) { + const existing = db.orders.find(item => item.id === existingId) + if (existing) { + assertRedirectUri(appOf(appCode), redirectUri) + return ok(payOrderResponse(existing, redirectUri)) + } + } + } + + const ticket = validTicket(appCode, ticketNo, redirectUri) + const app = appOf(appCode) + + let amountCent = 0 + let pointsGained = 0 + let planCode: string | null = null + + if (orderType === 'recharge') { + amountCent = num(ctx.body.amountCent) + ensure(Number.isInteger(amountCent) && amountCent >= 100 && amountCent <= 5000000, 422, '充值金额需为 1~50000 元的整数分') + const rate = db.pricing.find(item => item.appCode === appCode)?.pointsPerYuan || 100 + pointsGained = Math.floor((amountCent / 100) * rate) + } else { + planCode = text(ctx.body.planCode) + const plan = db.plans.find(item => item.appCode === appCode && item.planCode === planCode && item.enabled === 1) + ensure(plan, 4001, 'VIP 档位不存在或已下架') + amountCent = plan!.priceCent + pointsGained = 0 + } + + // ticket 一次性:原子置 used_at + ensure(!ticket.usedAt, 7001, '凭证已被使用') + const record = db.tickets.find(item => item.ticket === ticketNo) + if (record) record.usedAt = now() + + const datePart = now().slice(0, 10).replace(/-/g, '') + const order: OrderRecord = { + id: nextId(), + outTradeNo: `${orderType === 'vip' ? 'VIP' : 'RC'}${datePart}${String(nextId()).slice(-5)}`, + appCode, + appName: app.appName, + businessUserId: ticket.businessUserId, + usernameSnapshot: accountOf(appCode, ticket.businessUserId)?.usernameSnapshot || '', + orderType: orderType as OrderInfo['orderType'], + payMethod: 'offline', + amountCent, + pointsGained, + vipPlanCode: planCode, + status: 'PENDING', + expiresAt: plusDays(1), + paidAt: null, + confirmedByAdminId: null, + confirmedByAdminName: null, + secondApproverId: null, + secondApproverName: null, + remark: '用户自助下单', + createTime: now(), + refundedAmountCent: 0, + cashInCent: 0, + cashOutCent: 0, + needDualControl: amountCent >= dualThreshold(appCode), + } + db.orders.push(order) + if (storeKey) db.idempotency.set(storeKey, order.id) + return ok(payOrderResponse(order, redirectUri)) +}) + +function payOrderResponse(order: OrderRecord, redirectUri: string) { + return { + outTradeNo: order.outTradeNo, + amountCent: order.amountCent, + pointsGained: order.pointsGained, + orderType: order.orderType, + vipPlanCode: order.vipPlanCode, + status: order.status, + expiresAt: order.expiresAt, + payee: { + accountName: '甘肃烛龙科技有限公司', + bankName: '中国建设银行兰州城关支行', + accountNo: '6200 **** **** 8831', + }, + redirectUri: redirectUri || null, + createTime: order.createTime, + } +} + +route('GET', '/pay/orders/:outTradeNo/status', null, ctx => { + const order = db.orders.find(item => item.outTradeNo === ctx.params.outTradeNo) + ensure(order, 404, '订单不存在') + return ok({ + outTradeNo: order!.outTradeNo, + status: order!.status, + amountCent: order!.amountCent, + pointsGained: order!.pointsGained, + paidAt: order!.paidAt, + expiresAt: order!.expiresAt, + }) +}) + +route('GET', '/pay/demo-ticket', null, ctx => { + // 仅演示环境可用:模拟业务系统签发一次性凭证 + const appCode = text(ctx.query.appCode) || 'litho-sim' + const app = appOf(appCode) + const accounts = db.accounts.filter(item => item.appCode === appCode) + ensure(accounts.length > 0, 404, '该应用暂无业务用户') + const account = accounts[Math.floor(Math.random() * accounts.length)] + const ticketNo = `tk_${randomSecret('d').slice(3, 43)}` + // 凭证有效期必须与全局参数保持一致,避免配置中心改了对演示链路不生效 + const ttlMinutes = configValue('ticket.ttl_minutes', 5) + db.tickets.push({ + ticket: ticketNo, + appCode, + businessUserId: account.businessUserId, + expiresAt: plusMinutes(ttlMinutes), + usedAt: null, + }) + const host = app.allowedRedirectHosts.split(',')[0]?.trim() || 'sim.gaszk.com' + return ok({ + appCode, + ticket: ticketNo, + businessUserId: account.businessUserId, + username: account.usernameSnapshot, + redirectUri: `https://${host}/wallet/recharge`, + expiresAt: plusMinutes(ttlMinutes), + }) +}) + +/* ----------------------------- 适配器 ----------------------------- */ + +interface CompiledRoute { + method: string + regex: RegExp + keys: string[] + def: RouteDef +} + +const compiled: CompiledRoute[] = routes.map(def => { + const keys: string[] = [] + const pattern = def.path.replace(/:[A-Za-z0-9_]+/g, match => { + keys.push(match.slice(1)) + return '([^/]+)' + }) + return { method: def.method, regex: new RegExp(`^${pattern}$`), keys, def } +}) + +function resolveAdmin(headers: Record): AdminRecord | null { + const raw = headers.authorization || headers.Authorization || '' + const token = raw.replace(/^Bearer\s+/i, '').trim() + if (!token) return null + const session = db.sessions.get(token) + if (!session || session.expiresAt < Date.now()) { + db.sessions.delete(token) + return null + } + const admin = findAdmin(session.adminId) + if (!admin || admin.isActive !== 1) return null + return admin +} + +function normalizePath(url: string): { path: string; query: Record } { + const raw = url.split('?')[1] || '' + const query: Record = {} + raw.split('&').forEach(pair => { + if (!pair) return + const index = pair.indexOf('=') + const key = index >= 0 ? pair.slice(0, index) : pair + const value = index >= 0 ? pair.slice(index + 1) : '' + // 畸形百分号编码会抛 URIError,进而把请求变成 500,必须兜底为原始字符串 + query[safeDecode(key)] = safeDecode(value) + }) + // 路径不做百分号解码,避免 %2F 之类的编码绕过路由前缀判断 + const path = (url.split('?')[0] || '').replace(/^\/api/, '').replace(/\/+$/, '') + return { path: path || '/', query } +} + +function safeDecode(value: string): string { + try { + return decodeURIComponent(value) + } catch { + return value + } +} + +async function dispatch(config: InternalAxiosRequestConfig): Promise<{ code: number; message: string; data: unknown }> { + const method = (config.method || 'get').toUpperCase() + const url = config.url || '' + const { path, query: urlQuery } = normalizePath(url) + const query: Record = { ...urlQuery, ...(config.params || {}) } + const headers = (config.headers || {}) as unknown as Record + + let body: Record = {} + if (config.data) { + if (typeof config.data === 'string') { + try { + body = JSON.parse(config.data) + } catch { + body = {} + } + } else { + body = config.data as Record + } + } + + const matched = compiled.find(item => item.method === method && item.regex.test(path)) + if (!matched) { + throw new MockError(404, `接口不存在:${method} ${path}`) + } + + const values = matched.regex.exec(path) || [] + const params: Record = {} + matched.keys.forEach((key, index) => { + params[key] = safeDecode(values[index + 1] || '') + }) + + const isPublic = matched.def.public === true + const admin = resolveAdmin(headers) + if (!isPublic && !admin) { + throw new MockError(401, '登录状态已失效,请重新登录') + } + requirePermission(admin, matched.def.perms) + + // 各路由处理器已返回 ok(...) 包装的完整响应体,此处不能再包一层,否则前端会拿到嵌套结果 + return matched.def.handler({ params, query, body, headers, admin }) as { + code: number + message: string + data: unknown + } +} + +export const mockAdapter: AxiosAdapter = async config => { + await delay(120 + Math.floor(Math.random() * 180)) + let payload: { code: number; message: string; data: unknown } + try { + payload = await dispatch(config) + } catch (error) { + if (error instanceof MockError) { + payload = { code: error.code, message: error.message, data: null } + } else { + payload = { + code: 500, + message: '服务内部异常,请联系管理员并提供追踪号', + data: null, + } + } + } + const response: AxiosResponse = { + data: payload, + status: 200, + statusText: 'OK', + headers: {}, + config, + } + return response +} diff --git a/finance-web/src/router/index.ts b/finance-web/src/router/index.ts new file mode 100644 index 0000000..518723c --- /dev/null +++ b/finance-web/src/router/index.ts @@ -0,0 +1,181 @@ +import { createRouter, createWebHashHistory, type RouteRecordRaw } from 'vue-router' +import { useUserStore } from '@/stores/user' +import { APP_TITLE } from '@/constants' +import { HOME_BY_ROLE } from './menu' + +declare module 'vue-router' { + interface RouteMeta { + title?: string + perm?: string + public?: boolean + layout?: 'blank' + } +} + +const routes: RouteRecordRaw[] = [ + { + path: '/login', + name: 'login', + component: () => import('@/views/login/LoginView.vue'), + meta: { title: '管理员登录', public: true, layout: 'blank' }, + }, + { + path: '/password', + name: 'password', + component: () => import('@/views/password/ChangePasswordView.vue'), + meta: { title: '修改密码', layout: 'blank' }, + }, + { + path: '/pay', + name: 'pay', + component: () => import('@/views/pay/PayView.vue'), + meta: { title: '收银台', public: true, layout: 'blank' }, + }, + { + path: '/403', + name: 'forbidden', + component: () => import('@/views/error/ForbiddenView.vue'), + meta: { title: '无访问权限', public: true, layout: 'blank' }, + }, + { + path: '/', + component: () => import('@/layouts/AppLayout.vue'), + redirect: '/dashboard', + children: [ + { + path: 'dashboard', + name: 'dashboard', + component: () => import('@/views/dashboard/DashboardView.vue'), + meta: { title: '资金看板', perm: 'fin:view' }, + }, + { + path: 'apps', + name: 'apps', + component: () => import('@/views/apps/AppListView.vue'), + meta: { title: '接入应用', perm: 'fin:view' }, + }, + { + path: 'accounts', + name: 'accounts', + component: () => import('@/views/accounts/AccountListView.vue'), + meta: { title: '钱包账户', perm: 'fin:view' }, + }, + { + path: 'orders', + name: 'orders', + component: () => import('@/views/orders/OrderListView.vue'), + meta: { title: '充值订单', perm: 'fin:view' }, + }, + { + path: 'refunds', + name: 'refunds', + component: () => import('@/views/refunds/RefundListView.vue'), + meta: { title: '退款单', perm: 'fin:view' }, + }, + { + path: 'transactions', + name: 'transactions', + component: () => import('@/views/transactions/TransactionListView.vue'), + meta: { title: '点数流水', perm: 'fin:view' }, + }, + { + path: 'vip-plans', + name: 'vip-plans', + component: () => import('@/views/vip/VipPlanView.vue'), + meta: { title: 'VIP 档位', perm: 'fin:view' }, + }, + { + path: 'vips', + name: 'vips', + component: () => import('@/views/vip/VipHolderView.vue'), + meta: { title: 'VIP 持有', perm: 'fin:view' }, + }, + { + path: 'pricing', + name: 'pricing', + component: () => import('@/views/pricing/PricingView.vue'), + meta: { title: '兑率与策略', perm: 'fin:view' }, + }, + { + path: 'reconcile', + name: 'reconcile', + component: () => import('@/views/reconcile/ReconcileView.vue'), + meta: { title: '对账中心', perm: 'fin:view' }, + }, + { + path: 'webhooks', + name: 'webhooks', + component: () => import('@/views/system/WebhookView.vue'), + meta: { title: 'Webhook 投递', perm: 'fin:view' }, + }, + { + path: 'admins', + name: 'admins', + component: () => import('@/views/system/AdminListView.vue'), + meta: { title: '管理员', perm: 'fin:admin:manage' }, + }, + { + path: 'audit', + name: 'audit', + component: () => import('@/views/system/AuditLogView.vue'), + meta: { title: '审计日志', perm: 'fin:audit:view' }, + }, + { + path: 'config', + name: 'config', + component: () => import('@/views/system/ConfigView.vue'), + meta: { title: '全局参数', perm: 'fin:config:edit' }, + }, + ], + }, + { + path: '/:pathMatch(.*)*', + name: 'not-found', + component: () => import('@/views/error/NotFoundView.vue'), + meta: { title: '页面不存在', public: true, layout: 'blank' }, + }, +] + +const router = createRouter({ + history: createWebHashHistory(), + routes, + scrollBehavior: () => ({ top: 0 }), +}) + +router.beforeEach(async to => { + document.title = to.meta.title ? `${to.meta.title} · ${APP_TITLE}` : APP_TITLE + + if (to.meta.public) return true + + const store = useUserStore() + if (!store.isLoggedIn) { + return { path: '/login', query: { redirect: to.fullPath } } + } + + if (!store.admin) { + try { + await store.loadProfile() + } catch { + store.logout() + return { path: '/login', query: { redirect: to.fullPath } } + } + } + + // 首次登录强制改密:除改密页外一律拦截 + if (store.mustChangePassword && to.path !== '/password') { + return { path: '/password' } + } + + if (to.meta.perm && !store.hasPerm(to.meta.perm)) { + return { path: '/403', query: { from: to.fullPath } } + } + + if (to.path === '/' || to.path === '/dashboard') { + const home = HOME_BY_ROLE[store.admin!.role] + if (home !== '/dashboard' && to.path === '/') return { path: home } + } + + return true +}) + +export default router diff --git a/finance-web/src/router/menu.ts b/finance-web/src/router/menu.ts new file mode 100644 index 0000000..921aded --- /dev/null +++ b/finance-web/src/router/menu.ts @@ -0,0 +1,57 @@ +import type { Role } from '@/types' + +export interface MenuItem { + path: string + title: string + icon: string + perm?: string | string[] +} + +export interface MenuGroup { + title: string + items: MenuItem[] +} + +/** 菜单结构:页面级权限仅做体验层隐藏,服务端必须二次校验 */ +export const MENU_GROUPS: MenuGroup[] = [ + { + title: '资金运营', + items: [ + { path: '/dashboard', title: '资金看板', icon: 'DataLine' }, + { path: '/orders', title: '充值订单', icon: 'Tickets' }, + { path: '/refunds', title: '退款单', icon: 'RefreshLeft' }, + { path: '/accounts', title: '钱包账户', icon: 'Wallet' }, + { path: '/transactions', title: '点数流水', icon: 'Coin' }, + ], + }, + { + title: '应用与计费', + items: [ + { path: '/apps', title: '接入应用', icon: 'Connection' }, + { path: '/vip-plans', title: 'VIP 档位', icon: 'Medal' }, + { path: '/vips', title: 'VIP 持有', icon: 'Star' }, + { path: '/pricing', title: '兑率与策略', icon: 'SetUp' }, + ], + }, + { + title: '对账与审计', + items: [ + { path: '/reconcile', title: '对账中心', icon: 'DocumentChecked' }, + { path: '/audit', title: '审计日志', icon: 'Lock', perm: 'fin:audit:view' }, + { path: '/webhooks', title: 'Webhook 投递', icon: 'Promotion' }, + ], + }, + { + title: '系统管理', + items: [ + { path: '/admins', title: '管理员', icon: 'User', perm: 'fin:admin:manage' }, + { path: '/config', title: '全局参数', icon: 'Setting', perm: 'fin:config:edit' }, + ], + }, +] + +export const HOME_BY_ROLE: Record = { + SUPER_ADMIN: '/dashboard', + FINANCE: '/orders', + AUDITOR: '/dashboard', +} diff --git a/finance-web/src/stores/user.ts b/finance-web/src/stores/user.ts new file mode 100644 index 0000000..09e9b01 --- /dev/null +++ b/finance-web/src/stores/user.ts @@ -0,0 +1,65 @@ +import { defineStore } from 'pinia' +import { computed, ref } from 'vue' +import type { AdminInfo, LoginResult } from '@/types' +import type { LoginPayload } from '@/api/auth' +import { authApi } from '@/api/auth' +import { clearSession, getToken, setToken } from '@/utils/session' + +export const useUserStore = defineStore('user', () => { + const token = ref(getToken()) + const admin = ref(null) + const permissions = ref([]) + + const isLoggedIn = computed(() => Boolean(token.value)) + const role = computed(() => admin.value?.role || null) + const mustChangePassword = computed(() => admin.value?.mustChangePassword === 1) + const displayName = computed(() => admin.value?.username || '') + + function hasPerm(code: string | string[]): boolean { + if (!admin.value) return false + const codes = Array.isArray(code) ? code : [code] + return codes.some(item => permissions.value.includes(item)) + } + + async function login(payload: LoginPayload): Promise { + const result = await authApi.login(payload) + token.value = result.token + setToken(result.token) + admin.value = result.admin + permissions.value = result.permissions + return result + } + + async function loadProfile(): Promise { + const result = await authApi.profile() + admin.value = result.admin + permissions.value = result.permissions + } + + function logout(): void { + token.value = '' + admin.value = null + permissions.value = [] + clearSession() + } + + async function changePassword(oldPassword: string, newPassword: string): Promise { + await authApi.changePassword({ oldPassword, newPassword }) + if (admin.value) admin.value.mustChangePassword = 0 + } + + return { + token, + admin, + permissions, + isLoggedIn, + role, + mustChangePassword, + displayName, + hasPerm, + login, + loadProfile, + logout, + changePassword, + } +}) diff --git a/finance-web/src/styles/index.css b/finance-web/src/styles/index.css new file mode 100644 index 0000000..6fc253f --- /dev/null +++ b/finance-web/src/styles/index.css @@ -0,0 +1,295 @@ +:root { + /* 品牌色(同时覆盖 Element Plus 主色) */ + --el-color-primary: #1d5bdb; + --el-color-primary-light-3: #5b87e5; + --el-color-primary-light-5: #8fb0ee; + --el-color-primary-light-7: #c3d5f7; + --el-color-primary-light-8: #dbe6fb; + --el-color-primary-light-9: #eef3fe; + --el-color-primary-dark-2: #1749af; + --el-color-success: #0f9d70; + --el-color-warning: #c47d0a; + --el-color-danger: #c0392b; + --el-color-info: #64748b; + + --fin-bg: #f4f6fb; + --fin-card: #ffffff; + --fin-border: #e5eaf2; + --fin-border-strong: #d3dbe8; + --fin-text: #17202f; + --fin-text-2: #5b6a80; + --fin-text-3: #8a97a8; + --fin-sidebar: #0d1728; + --fin-sidebar-2: #14213a; + --fin-sidebar-text: #9fb0c9; + --fin-sidebar-active: #ffffff; + --fin-gold: #c8a45c; + --fin-radius: 10px; + --fin-shadow: 0 1px 2px rgba(16, 24, 40, 0.04), 0 8px 24px rgba(16, 24, 40, 0.06); +} + +* { + box-sizing: border-box; +} + +html, +body, +#app { + height: 100%; + margin: 0; +} + +body { + background: var(--fin-bg); + color: var(--fin-text); + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', + 'Microsoft YaHei', 'Helvetica Neue', Arial, sans-serif; + font-size: 14px; + -webkit-font-smoothing: antialiased; +} + +a { + color: inherit; + text-decoration: none; +} + +/* 通用版式 */ +.page { + padding: 20px 24px 32px; +} + +.page-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + margin-bottom: 16px; +} + +.page-header h2 { + margin: 0 0 4px; + font-size: 20px; + font-weight: 600; + letter-spacing: 0.2px; +} + +.page-header .desc { + margin: 0; + color: var(--fin-text-2); + font-size: 13px; + line-height: 1.6; +} + +.page-header .actions { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} + +.card { + background: var(--fin-card); + border: 1px solid var(--fin-border); + border-radius: var(--fin-radius); + box-shadow: var(--fin-shadow); + padding: 18px 20px; +} + +.card + .card { + margin-top: 16px; +} + +.card-title { + display: flex; + align-items: center; + justify-content: space-between; + margin: 0 0 14px; + font-size: 15px; + font-weight: 600; +} + +.filter-bar { + display: flex; + flex-wrap: wrap; + gap: 10px; + align-items: center; + margin-bottom: 14px; +} + +.filter-bar .spacer { + flex: 1; +} + +.table-footer { + display: flex; + justify-content: flex-end; + margin-top: 14px; +} + +/* 数字排版 */ +.num { + font-variant-numeric: tabular-nums; + font-feature-settings: 'tnum'; +} + +.money { + font-variant-numeric: tabular-nums; + font-weight: 600; + color: var(--fin-text); +} + +.money-in { + color: var(--fin-success); +} + +.money-out { + color: var(--fin-danger); +} + +.muted { + color: var(--fin-text-3); +} + +.small { + font-size: 12px; +} + +/* 提示条 */ +.notice { + display: flex; + gap: 8px; + align-items: flex-start; + padding: 10px 14px; + border-radius: 8px; + font-size: 13px; + line-height: 1.6; + border: 1px solid transparent; +} + +.notice.info { + background: #f0f5ff; + border-color: #d6e4ff; + color: #1f4fa8; +} + +.notice.warn { + background: #fff8e6; + border-color: #ffe7b0; + color: #8a5a00; +} + +.notice.danger { + background: #fdf1f0; + border-color: #f6d4d0; + color: #a33125; +} + +/* 统计卡片 */ +.stat-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); + gap: 14px; + margin-bottom: 16px; +} + +/* Element Plus 微调 */ +.el-table { + --el-table-header-bg-color: #f8fafc; + --el-table-border-color: var(--fin-border); + font-size: 13px; +} + +.el-table th.el-table__cell { + font-weight: 600; + color: var(--fin-text-2); +} + +.el-descriptions__label { + color: var(--fin-text-2) !important; + width: 132px; +} + +.el-dialog__body { + padding-top: 8px; +} + +.mono { + font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace; + font-size: 12px; +} + +.code-block { + background: #0f172a; + color: #d7e3f4; + border-radius: 8px; + padding: 12px 14px; + font-family: 'SFMono-Regular', Consolas, Menlo, monospace; + font-size: 12px; + line-height: 1.7; + white-space: pre-wrap; + word-break: break-all; + max-height: 380px; + overflow: auto; +} + +.hash { + font-family: 'SFMono-Regular', Consolas, Menlo, monospace; + font-size: 11px; + color: var(--fin-text-2); + word-break: break-all; +} + +/* 侧边栏 */ +.side-menu.el-menu { + border-right: none; + background: transparent; +} + +.side-menu .el-menu-item, +.side-menu .el-sub-menu__title { + height: 42px; + line-height: 42px; + color: var(--fin-sidebar-text); + border-radius: 8px; + margin: 2px 10px; + padding-left: 14px !important; +} + +.side-menu .el-menu-item:hover, +.side-menu .el-sub-menu__title:hover { + background: var(--fin-sidebar-2); + color: #e6edf9; +} + +.side-menu .el-menu-item.is-active { + background: linear-gradient(90deg, rgba(29, 91, 219, 0.95), rgba(29, 91, 219, 0.65)); + color: #fff; + font-weight: 600; +} + +.side-menu .el-sub-menu.is-active > .el-sub-menu__title { + color: #fff; +} + +.side-menu .el-menu { + background: transparent; +} + +.side-menu .el-sub-menu .el-menu-item { + padding-left: 38px !important; +} + +/* 滚动条 */ +::-webkit-scrollbar { + width: 8px; + height: 8px; +} + +::-webkit-scrollbar-thumb { + background: #c8d2e0; + border-radius: 4px; +} + +::-webkit-scrollbar-track { + background: transparent; +} diff --git a/finance-web/src/types/index.ts b/finance-web/src/types/index.ts new file mode 100644 index 0000000..9ceebe6 --- /dev/null +++ b/finance-web/src/types/index.ts @@ -0,0 +1,346 @@ +/** 后台角色:三角色职责分离(D5) */ +export type Role = 'SUPER_ADMIN' | 'FINANCE' | 'AUDITOR' + +export type OrderStatus = 'PENDING' | 'PAID' | 'CANCELLED' | 'REFUNDED' +export type OrderType = 'recharge' | 'vip' +export type PayMethod = 'offline' | 'wechat' | 'alipay' +export type TxType = 'RECHARGE' | 'CONSUME' | 'CONSUME_FREE' | 'REFUND_IN' | 'REFUND_OUT' | 'ADJUST' +export type RefundStatus = 'PENDING' | 'COMPLETED' | 'REJECTED' +export type WebhookStatus = 'PENDING' | 'SENT' | 'FAILED' | 'DEAD' + +export interface PageResult { + records: T[] + total: number + page: number + pageSize: number +} + +export interface AdminInfo { + id: number + username: string + role: Role + isActive: number + mustChangePassword: number + totpBound: boolean + failedAttempts: number + lockedUntil: string | null + lastLoginAt: string | null + lastLoginIp: string | null + createTime: string +} + +export interface LoginResult { + token: string + admin: AdminInfo + permissions: string[] +} + +export interface AppInfo { + appCode: string + appName: string + allowedRedirectHosts: string + webhookUrl: string + tokenTtlSeconds: number + enabled: number + secretExpiresAt: string | null + hasPrevSecret: boolean + createTime: string + accountCount: number + todayAmountCent: number +} + +export interface AppTokenInfo { + id: number + appCode: string + tokenPrefix: string + expiresAt: string + revokedAt: string | null + issuedIp: string + createTime: string +} + +export interface AccountInfo { + id: number + appCode: string + appName: string + businessUserId: string + usernameSnapshot: string + phoneMasked: string + balance: number + totalSpent: number + versionNo: number + vipPlanCode: string | null + vipUntil: string | null + createTime: string + updateTime: string +} + +export interface OrderInfo { + id: number + outTradeNo: string + appCode: string + appName: string + businessUserId: string + usernameSnapshot: string + orderType: OrderType + payMethod: PayMethod + amountCent: number + pointsGained: number + vipPlanCode: string | null + status: OrderStatus + expiresAt: string + paidAt: string | null + confirmedByAdminId: number | null + confirmedByAdminName: string | null + secondApproverId: number | null + secondApproverName: string | null + remark: string + createTime: string + refundedAmountCent: number + cashInCent: number + cashOutCent: number + needDualControl: boolean +} + +export interface TransactionInfo { + id: number + appCode: string + appName: string + businessUserId: string + usernameSnapshot: string + type: TxType + amount: number + balanceBefore: number + balanceAfter: number + businessRefId: string | null + idempotencyKey: string + orderId: number | null + outTradeNo: string | null + refundOfId: number | null + refundedPoints: number + operatorAdminName: string | null + remark: string + createTime: string +} + +export interface RefundInfo { + id: number + appCode: string + appName: string + businessUserId: string + usernameSnapshot: string + orderId: number + outTradeNo: string + amountCent: number + pointsDeducted: number + status: RefundStatus + operatorAdminId: number + operatorAdminName: string + reviewerAdminId: number | null + reviewerAdminName: string | null + voucherNo: string + remark: string + createTime: string + updateTime: string +} + +export interface VipPlan { + id: number + appCode: string + appName: string + planCode: string + planName: string + durationDays: number + priceCent: number + freeDeduction: number + enabled: number + holderCount: number + createTime: string +} + +export interface VipHolder { + id: number + appCode: string + appName: string + businessUserId: string + usernameSnapshot: string + vipPlanCode: string + vipUntil: string + effective: boolean +} + +export interface PricingItem { + appCode: string + appName: string + pointsPerYuan: number + enabled: number + updateTime: string +} + +export interface AppPolicy { + appCode: string + appName: string + minCost: number + maxPointsPerCharge: number + vipExempt: number + failedStrategy: 'none' | 'actual' + dualControlThresholdCent: number + enabled: number + updateTime: string +} + +export interface ConfigItem { + configKey: string + configValue: string + description: string + risk: 'HIGH' | 'NORMAL' + updateBy: string + updateTime: string +} + +export interface AuditLog { + id: number + actorType: 'ADMIN' | 'SYSTEM' | 'BIZ' + actorId: number | null + actorName: string + action: string + actionLabel: string + targetType: string + targetId: number | null + beforeJson: string | null + afterJson: string | null + ip: string + ua: string + result: 'SUCCESS' | 'FAILED' + prevHash: string + curHash: string + createTime: string +} + +export interface ChainVerifyResult { + valid: boolean + checked: number + brokenAtId: number | null + checkedAt: string + message: string +} + +export interface WebhookDelivery { + id: number + appCode: string + appName: string + eventId: string + eventType: string + status: WebhookStatus + attempts: number + nextRetryAt: string | null + lastError: string + payload: string + createTime: string + updateTime: string +} + +export interface ReconcileDiff { + level: 'ORDER' | 'SUBJECT' | 'APP' + target: string + expected: number + actual: number + diff: number + reason: string +} + +export interface ReconcileReport { + id: string + appCode: string + appName: string + windowStart: string + windowEnd: string + snapshotAt: string + cashInCent: number + cashPaidOrderCent: number + cashOutCent: number + cashRefundedCent: number + cashDiffCent: number + walletSum: number + computedSum: number + pointsDiff: number + brokenChains: number + diffCount: number + status: 'BALANCED' | 'DIFF' + createdBy: string + createTime: string + details: ReconcileDiff[] +} + +export interface DashboardSummary { + todayAmountCent: number + todayOrderCount: number + pendingOrderCount: number + pendingAmountCent: number + todayConsumedPoints: number + pendingRefundCount: number + totalBalancePoints: number + deadWebhookCount: number + diffReportCount: number + dualControlThresholdCent: number +} + +export interface TrendPoint { + date: string + amountCent: number + points: number + orderCount: number +} + +export interface AppDistribution { + appCode: string + appName: string + amountCent: number + orderCount: number +} + +export interface AppTokenIssue { + clientSecret: string + expiresAt: string +} + +export interface PayPreview { + appCode: string + appName: string + businessUserId: string + usernameSnapshot: string + balance: number + pointsPerYuan: number + minAmountCent: number + vip: { + planCode: string + planName: string + vipUntil: string + freeDeduction: number + } | null + plans: Array<{ + planCode: string + planName: string + durationDays: number + priceCent: number + freeDeduction: number + }> + ticketExpiresAt: string +} + +export interface PayOrder { + outTradeNo: string + amountCent: number + pointsGained: number + orderType: OrderType + vipPlanCode: string | null + status: OrderStatus + expiresAt: string + payee: { + accountName: string + bankName: string + accountNo: string + } + redirectUri: string | null + createTime: string +} diff --git a/finance-web/src/utils/confirm.ts b/finance-web/src/utils/confirm.ts new file mode 100644 index 0000000..f0e2ba2 --- /dev/null +++ b/finance-web/src/utils/confirm.ts @@ -0,0 +1,87 @@ +import { ElMessageBox } from 'element-plus' + +export interface ConfirmOptions { + title?: string + message: string + confirmText?: string + type?: 'warning' | 'info' | 'error' | 'success' + /** 需要手动输入的确认文本(资金类高危操作强制使用) */ + requireType?: string + /** 输入框提示 */ + inputHint?: string +} + +/** + * 高危操作二次确认: + * - 默认弹窗确认 + * - requireType 场景要求人工输入指定文本,防止误点 + */ +export async function confirmAction(options: ConfirmOptions): Promise { + const title = options.title || '操作确认' + const confirmButtonText = options.confirmText || '确定' + + try { + if (options.requireType) { + await ElMessageBox.prompt(options.message, title, { + confirmButtonText, + cancelButtonText: '取消', + type: options.type || 'warning', + inputPlaceholder: options.inputHint || `请输入「${options.requireType}」`, + inputValidator: (value: string) => (value === options.requireType ? true : `输入不一致,请重新输入「${options.requireType}」`), + closeOnClickModal: false, + distinguishCancelAndClose: true, + }) + return true + } + + await ElMessageBox.confirm(options.message, title, { + confirmButtonText, + cancelButtonText: '取消', + type: options.type || 'warning', + closeOnClickModal: false, + distinguishCancelAndClose: true, + }) + return true + } catch { + return false + } +} + +/** TOTP 输入弹窗:返回 6 位验证码,取消返回 null */ +export async function askTotp(actionName: string): Promise { + try { + const result = await ElMessageBox.prompt( + `执行「${actionName}」需要二次身份验证,请输入身份验证器中的 6 位动态码。`, + '动态口令(TOTP)', + { + confirmButtonText: '验证并继续', + cancelButtonText: '取消', + inputPlaceholder: '6 位数字动态码', + inputPattern: /^\d{6}$/, + inputErrorMessage: '动态码必须为 6 位数字', + closeOnClickModal: false, + distinguishCancelAndClose: true, + }, + ) + return result.value + } catch { + return null + } +} + +/** 输入备注/原因(必填) */ +export async function askReason(title: string, message: string): Promise { + try { + const result = await ElMessageBox.prompt(message, title, { + confirmButtonText: '确定', + cancelButtonText: '取消', + inputPlaceholder: '请填写原因(不少于 5 个字)', + inputValidator: (value: string) => ((value || '').trim().length >= 5 ? true : '原因不少于 5 个字'), + closeOnClickModal: false, + distinguishCancelAndClose: true, + }) + return result.value.trim() + } catch { + return null + } +} diff --git a/finance-web/src/utils/export.ts b/finance-web/src/utils/export.ts new file mode 100644 index 0000000..bd81220 --- /dev/null +++ b/finance-web/src/utils/export.ts @@ -0,0 +1,38 @@ +export interface CsvColumn { + label: string + value: (row: T) => string | number | null | undefined +} + +/** 防 CSV 注入:以 = + - @ 或制表符开头的单元格强制转义 */ +function safeCell(value: unknown): string { + const text = value === null || value === undefined ? '' : String(value) + const protectedText = /^[=+\-@\t]/.test(text) ? `'${text}` : text + return `"${protectedText.replace(/"/g, '""')}"` +} + +export function buildCsv(columns: CsvColumn[], rows: T[]): string { + const head = columns.map(col => safeCell(col.label)).join(',') + const body = rows.map(row => columns.map(col => safeCell(col.value(row))).join(',')) + return [head, ...body].join('\r\n') +} + +export function downloadCsv(filename: string, csv: string): void { + // BOM 保证 Excel 正确识别 UTF-8 中文 + const blob = new Blob([`\uFEFF${csv}`], { type: 'text/csv;charset=utf-8' }) + const url = URL.createObjectURL(blob) + const link = document.createElement('a') + link.href = url + link.download = filename + document.body.appendChild(link) + link.click() + document.body.removeChild(link) + URL.revokeObjectURL(url) +} + +export function exportFilename(prefix: string): string { + const now = new Date() + const stamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String( + now.getDate(), + ).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}` + return `${prefix}-${stamp}.csv` +} diff --git a/finance-web/src/utils/format.ts b/finance-web/src/utils/format.ts new file mode 100644 index 0000000..c625b95 --- /dev/null +++ b/finance-web/src/utils/format.ts @@ -0,0 +1,52 @@ +const pad = (n: number): string => String(n).padStart(2, '0') + +export function formatDateTime(value?: string | null): string { + if (!value) return '—' + return String(value).slice(0, 19).replace('T', ' ') +} + +export function formatDate(value?: string | null): string { + if (!value) return '—' + return String(value).slice(0, 10) +} + +export function toLocalString(date: Date): string { + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad( + date.getHours(), + )}:${pad(date.getMinutes())}:${pad(date.getSeconds())}` +} + +export function todayString(): string { + const now = new Date() + return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}` +} + +export function dateOffset(days: number): string { + const date = new Date() + date.setDate(date.getDate() + days) + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` +} + +export function defaultRange(days = 7): [string, string] { + return [dateOffset(-(days - 1)), todayString()] +} + +/** 剩余时间文案(订单过期、ticket 过期) */ +export function remainText(expireAt?: string | null): string { + if (!expireAt) return '—' + const diff = new Date(expireAt.replace(' ', 'T')).getTime() - Date.now() + if (Number.isNaN(diff)) return '—' + if (diff <= 0) return '已过期' + const minutes = Math.floor(diff / 60000) + if (minutes < 60) return `${minutes} 分钟` + const hours = Math.floor(minutes / 60) + if (hours < 24) return `${hours} 小时 ${minutes % 60} 分` + return `${Math.floor(hours / 24)} 天 ${hours % 24} 小时` +} + +export function secondsText(ms: number): string { + const total = Math.max(0, Math.ceil(ms / 1000)) + const m = Math.floor(total / 60) + const s = total % 60 + return `${pad(m)}:${pad(s)}` +} diff --git a/finance-web/src/utils/http.ts b/finance-web/src/utils/http.ts new file mode 100644 index 0000000..d1729b7 --- /dev/null +++ b/finance-web/src/utils/http.ts @@ -0,0 +1,129 @@ +import axios, { type AxiosRequestConfig } from 'axios' +import { ElMessage } from 'element-plus' +import { mockAdapter } from '@/mock' +import { clearSession, getToken } from '@/utils/session' + +export interface ApiResult { + code: number + message: string + data: T + traceId?: string +} + +export class ApiError extends Error { + code: number + traceId?: string + + constructor(code: number, message: string, traceId?: string) { + super(message) + this.name = 'ApiError' + this.code = code + this.traceId = traceId + } +} + +declare module 'axios' { + export interface AxiosRequestConfig { + /** 静默模式:不在页面弹提示,由调用方自行处理 */ + silent?: boolean + } +} + +const KNOWN_MESSAGES: Record = { + 401: '登录状态已失效,请重新登录', + 4010: '登录状态已失效,请重新登录', + 403: '当前账号无权执行该操作', + 4091: '重复提交已被拦截,已返回首次结果', + 4092: '并发操作冲突,请稍后重试', + 4093: '单据状态已变更,请刷新后重试', + 422: '提交内容不符合规范,请检查后重试', + 429: '操作过于频繁,请稍后再试', + 6001: '账户余额不足,无法完成扣费', + 6002: '超出单次扣费上限,已被拒绝', + 6003: '点数必须为正整数', + 6004: '退款金额超出可退上限', + 7001: '凭证无效、已过期或已被使用', +} + +/** 错误文案统一出口:不向用户回显堆栈、SQL、内部主机名 */ +export function userMessage(error: ApiError): string { + if (KNOWN_MESSAGES[error.code]) return KNOWN_MESSAGES[error.code] + const message = (error.message || '').trim() + if (!message) return '操作失败,请稍后重试' + if (/(sql|jdbc|mysql|exception|stack|nullpointer|select\s|insert\s|update\s)/i.test(message)) { + return '操作失败,请稍后重试' + } + return message.length > 120 ? '操作失败,请稍后重试' : message +} + +let unauthorizedHandler: (() => void) | null = null + +export function setUnauthorizedHandler(handler: () => void): void { + unauthorizedHandler = handler +} + +const instance = axios.create({ + baseURL: import.meta.env.VITE_API_BASE || '/api', + timeout: 20000, + withCredentials: false, + headers: { + 'X-Requested-With': 'XMLHttpRequest', + }, +}) + +// 本地演示:内置 Mock adapter(生产构建必须 VITE_USE_MOCK=0) +if (import.meta.env.VITE_USE_MOCK === '1') { + instance.defaults.adapter = mockAdapter +} + +instance.interceptors.request.use(config => { + const token = getToken() + if (token) { + config.headers.Authorization = `Bearer ${token}` + } + return config +}) + +async function request(config: AxiosRequestConfig): Promise { + let response + try { + response = await instance.request>(config) + } catch (error) { + const message = axios.isAxiosError(error) && error.code === 'ECONNABORTED' ? '请求超时,请稍后重试' : '网络异常,请稍后重试' + if (!config.silent) ElMessage.error(message) + throw new ApiError(-1, message) + } + + const body = response.data + if (!body || typeof body.code !== 'number') { + if (!config.silent) ElMessage.error('服务响应异常,请稍后重试') + throw new ApiError(-2, '服务响应异常') + } + + if (body.code !== 0) { + const error = new ApiError(body.code, body.message || '操作失败', body.traceId) + if (body.code === 401 || body.code === 4010) { + clearSession() + unauthorizedHandler?.() + } + if (!config.silent) ElMessage.error(userMessage(error)) + throw error + } + + return body.data +} + +export const http = { + get(url: string, params?: object, config: AxiosRequestConfig = {}): Promise { + return request({ ...config, url, method: 'get', params }) + }, + post(url: string, data?: unknown, config: AxiosRequestConfig = {}): Promise { + return request({ ...config, url, method: 'post', data }) + }, + put(url: string, data?: unknown, config: AxiosRequestConfig = {}): Promise { + return request({ ...config, url, method: 'put', data }) + }, + delete(url: string, config: AxiosRequestConfig = {}): Promise { + return request({ ...config, url, method: 'delete' }) + }, +} diff --git a/finance-web/src/utils/mask.ts b/finance-web/src/utils/mask.ts new file mode 100644 index 0000000..520f2bb --- /dev/null +++ b/finance-web/src/utils/mask.ts @@ -0,0 +1,36 @@ +/** PII 脱敏工具:前端展示层兜底,服务端必须已完成掩码存储 */ + +export function maskPhone(phone: string | null | undefined): string { + if (!phone) return '—' + const text = String(phone) + if (text.length < 7) return '***' + return `${text.slice(0, 3)}****${text.slice(-4)}` +} + +export function maskEmail(email: string | null | undefined): string { + if (!email) return '—' + const [name, domain] = String(email).split('@') + if (!domain) return '***' + const head = name.slice(0, 2) + return `${head}***@${domain}` +} + +export function maskUserId(id: string): string { + if (!id) return '—' + if (id.length <= 7) return id + return `${id.slice(0, 4)}***${id.slice(-3)}` +} + +/** 密钥只展示前缀,禁止完整回显(页面一次性展示场景除外) */ +export function maskSecret(secret: string): string { + if (!secret) return '' + return `${secret.slice(0, 6)}••••••••${secret.slice(-4)}` +} + +/** 凭证号等准敏感标识:保留首尾便于人工核对 */ +export function maskVoucher(no: string | null | undefined): string { + if (!no) return '—' + const text = String(no) + if (text.length <= 6) return text + return `${text.slice(0, 3)}****${text.slice(-3)}` +} diff --git a/finance-web/src/utils/money.ts b/finance-web/src/utils/money.ts new file mode 100644 index 0000000..1a8d180 --- /dev/null +++ b/finance-web/src/utils/money.ts @@ -0,0 +1,51 @@ +const yuanFmt = new Intl.NumberFormat('zh-CN', { + minimumFractionDigits: 2, + maximumFractionDigits: 2, +}) +const intFmt = new Intl.NumberFormat('zh-CN') + +/** 分 → ¥ 展示(金额一律以分存储,前端只做展示转换) */ +export function formatCent(cent: number | null | undefined, withSymbol = true): string { + if (cent === null || cent === undefined || !Number.isFinite(cent)) return '—' + return `${withSymbol ? '¥ ' : ''}${yuanFmt.format(cent / 100)}` +} + +export function formatPoints(points: number | null | undefined): string { + if (points === null || points === undefined || !Number.isFinite(points)) return '—' + return intFmt.format(points) +} + +export function formatSignedPoints(points: number, sign: number): string { + if (sign === 0) return '0' + return `${sign > 0 ? '+' : '-'}${intFmt.format(Math.abs(points))}` +} + +export function formatPercent(value: number): string { + return `${(value * 100).toFixed(2)}%` +} + +/** 严格解析「元」输入为分:仅允许最多两位小数、必须大于 0 */ +export function yuanInputToCent(input: string): number | null { + const text = String(input ?? '').trim() + if (!/^\d{1,9}(\.\d{1,2})?$/.test(text)) return null + const cent = Math.round(Number(text) * 100) + if (!Number.isInteger(cent) || cent <= 0) return null + return cent +} + +export function centToYuanInput(cent: number | null | undefined): string { + if (cent === null || cent === undefined || !Number.isFinite(cent)) return '' + return (cent / 100).toFixed(2) +} + +/** 点数必须为正整数(设计文档 §5:拒绝小数/字符串/NaN) */ +export function parsePositiveInt(input: unknown): number | null { + if (typeof input === 'number') { + return Number.isInteger(input) && input > 0 ? input : null + } + if (typeof input === 'string' && /^\d{1,9}$/.test(input)) { + const value = Number(input) + return Number.isInteger(value) && value > 0 ? value : null + } + return null +} diff --git a/finance-web/src/utils/session.ts b/finance-web/src/utils/session.ts new file mode 100644 index 0000000..0a90654 --- /dev/null +++ b/finance-web/src/utils/session.ts @@ -0,0 +1,45 @@ +/** + * 会话存储:token 仅放 sessionStorage(关闭标签页即失效),不落 localStorage。 + * 生产环境后端可改为 httpOnly + SameSite=Strict Cookie,前端不接触 token。 + */ +const TOKEN_KEY = 'fin.admin.token' +const LOGIN_AT_KEY = 'fin.admin.loginAt' + +/** 空闲 30 分钟自动登出(等保二级:会话超时) */ +export const SESSION_IDLE_MS = 30 * 60 * 1000 +/** 到期前 5 分钟提醒 */ +export const SESSION_WARN_MS = 5 * 60 * 1000 + +export function getToken(): string { + try { + return sessionStorage.getItem(TOKEN_KEY) || '' + } catch { + return '' + } +} + +export function setToken(token: string): void { + try { + sessionStorage.setItem(TOKEN_KEY, token) + sessionStorage.setItem(LOGIN_AT_KEY, String(Date.now())) + } catch { + /* 存储不可用时降级为内存态,由调用方保证 */ + } +} + +export function getLoginAt(): number { + try { + return Number(sessionStorage.getItem(LOGIN_AT_KEY) || 0) + } catch { + return 0 + } +} + +export function clearSession(): void { + try { + sessionStorage.removeItem(TOKEN_KEY) + sessionStorage.removeItem(LOGIN_AT_KEY) + } catch { + /* ignore */ + } +} diff --git a/finance-web/src/utils/validate.ts b/finance-web/src/utils/validate.ts new file mode 100644 index 0000000..03c8b5d --- /dev/null +++ b/finance-web/src/utils/validate.ts @@ -0,0 +1,67 @@ +/** 前端校验:仅体验层,服务端必须使用同一套规则重新校验(设计文档 §5) */ + +export interface PasswordRule { + key: string + label: string + ok: boolean +} + +export interface PasswordCheck { + valid: boolean + score: number + levelText: string + rules: PasswordRule[] +} + +const SPECIAL = /[^A-Za-z0-9]/ + +export function checkPassword(password: string): PasswordCheck { + const pwd = password || '' + const rules: PasswordRule[] = [ + { key: 'length', label: '长度不少于 12 位', ok: pwd.length >= 12 }, + { key: 'upper', label: '包含大写字母', ok: /[A-Z]/.test(pwd) }, + { key: 'lower', label: '包含小写字母', ok: /[a-z]/.test(pwd) }, + { key: 'digit', label: '包含数字', ok: /\d/.test(pwd) }, + { key: 'special', label: '包含特殊符号', ok: SPECIAL.test(pwd) }, + { key: 'space', label: '不含空格与中文', ok: pwd.length > 0 && /^[\x21-\x7e]+$/.test(pwd) }, + ] + const passed = rules.filter(item => item.ok).length + const score = Math.round((passed / rules.length) * 100) + const levelText = score >= 100 ? '很强' : score >= 83 ? '强' : score >= 66 ? '中' : '弱' + return { valid: passed === rules.length, score, levelText, rules } +} + +export function isBusinessUserId(value: string): boolean { + return /^[A-Za-z0-9_-]{1,64}$/.test(value || '') +} + +export function isIdempotencyKey(value: string): boolean { + return /^[A-Za-z0-9:_-]{8,64}$/.test(value || '') +} + +export function newIdempotencyKey(prefix: string): string { + const random = + typeof crypto !== 'undefined' && 'randomUUID' in crypto + ? crypto.randomUUID().replace(/-/g, '') + : `${Date.now()}${Math.random().toString(16).slice(2)}` + return `${prefix}:${random}`.slice(0, 64) +} + +export function isPositiveInt(value: unknown): value is number { + return typeof value === 'number' && Number.isInteger(value) && value > 0 +} + +/** 跳转白名单展示用校验:必须是 https 或内网 http 的精确主机名,禁止 IP 直连与通配符 */ +export function isSafeRedirectHost(host: string): boolean { + const text = (host || '').trim() + if (!text) return false + if (text.includes('*')) return false + if (/^\d{1,3}(\.\d{1,3}){3}$/.test(text)) return false + if (text.includes('/') || text.includes(':')) return false + return /^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(text) +} + +/** 高危操作二次确认文本 */ +export function confirmTextOf(action: string): string { + return `确认${action}` +} diff --git a/finance-web/src/views/accounts/AccountListView.vue b/finance-web/src/views/accounts/AccountListView.vue new file mode 100644 index 0000000..5aa28a7 --- /dev/null +++ b/finance-web/src/views/accounts/AccountListView.vue @@ -0,0 +1,583 @@ + + + + + diff --git a/finance-web/src/views/apps/AppListView.vue b/finance-web/src/views/apps/AppListView.vue new file mode 100644 index 0000000..19d20ea --- /dev/null +++ b/finance-web/src/views/apps/AppListView.vue @@ -0,0 +1,771 @@ + + + + + diff --git a/finance-web/src/views/dashboard/DashboardView.vue b/finance-web/src/views/dashboard/DashboardView.vue new file mode 100644 index 0000000..5bbef20 --- /dev/null +++ b/finance-web/src/views/dashboard/DashboardView.vue @@ -0,0 +1,440 @@ + + + + + diff --git a/finance-web/src/views/error/ForbiddenView.vue b/finance-web/src/views/error/ForbiddenView.vue new file mode 100644 index 0000000..e7bfd23 --- /dev/null +++ b/finance-web/src/views/error/ForbiddenView.vue @@ -0,0 +1,139 @@ + + + + + diff --git a/finance-web/src/views/error/NotFoundView.vue b/finance-web/src/views/error/NotFoundView.vue new file mode 100644 index 0000000..731643b --- /dev/null +++ b/finance-web/src/views/error/NotFoundView.vue @@ -0,0 +1,122 @@ + + + + + diff --git a/finance-web/src/views/login/LoginView.vue b/finance-web/src/views/login/LoginView.vue new file mode 100644 index 0000000..3b2dab2 --- /dev/null +++ b/finance-web/src/views/login/LoginView.vue @@ -0,0 +1,523 @@ + + + + + diff --git a/finance-web/src/views/orders/OrderListView.vue b/finance-web/src/views/orders/OrderListView.vue new file mode 100644 index 0000000..008121a --- /dev/null +++ b/finance-web/src/views/orders/OrderListView.vue @@ -0,0 +1,686 @@ + + + + + diff --git a/finance-web/src/views/password/ChangePasswordView.vue b/finance-web/src/views/password/ChangePasswordView.vue new file mode 100644 index 0000000..b648755 --- /dev/null +++ b/finance-web/src/views/password/ChangePasswordView.vue @@ -0,0 +1,354 @@ + + + + + diff --git a/finance-web/src/views/pay/PayView.vue b/finance-web/src/views/pay/PayView.vue new file mode 100644 index 0000000..07a6847 --- /dev/null +++ b/finance-web/src/views/pay/PayView.vue @@ -0,0 +1,829 @@ + + + + + diff --git a/finance-web/src/views/pricing/PricingView.vue b/finance-web/src/views/pricing/PricingView.vue new file mode 100644 index 0000000..c977f3e --- /dev/null +++ b/finance-web/src/views/pricing/PricingView.vue @@ -0,0 +1,441 @@ + + + diff --git a/finance-web/src/views/reconcile/ReconcileView.vue b/finance-web/src/views/reconcile/ReconcileView.vue new file mode 100644 index 0000000..f66f364 --- /dev/null +++ b/finance-web/src/views/reconcile/ReconcileView.vue @@ -0,0 +1,350 @@ + + + + + diff --git a/finance-web/src/views/refunds/RefundListView.vue b/finance-web/src/views/refunds/RefundListView.vue new file mode 100644 index 0000000..c7ff4c7 --- /dev/null +++ b/finance-web/src/views/refunds/RefundListView.vue @@ -0,0 +1,601 @@ + + + + + diff --git a/finance-web/src/views/system/AdminListView.vue b/finance-web/src/views/system/AdminListView.vue new file mode 100644 index 0000000..01f2937 --- /dev/null +++ b/finance-web/src/views/system/AdminListView.vue @@ -0,0 +1,466 @@ + + + + + diff --git a/finance-web/src/views/system/AuditLogView.vue b/finance-web/src/views/system/AuditLogView.vue new file mode 100644 index 0000000..eb4ebe5 --- /dev/null +++ b/finance-web/src/views/system/AuditLogView.vue @@ -0,0 +1,364 @@ + + + + + diff --git a/finance-web/src/views/system/ConfigView.vue b/finance-web/src/views/system/ConfigView.vue new file mode 100644 index 0000000..d7b75e4 --- /dev/null +++ b/finance-web/src/views/system/ConfigView.vue @@ -0,0 +1,278 @@ + + + + + diff --git a/finance-web/src/views/system/WebhookView.vue b/finance-web/src/views/system/WebhookView.vue new file mode 100644 index 0000000..0f4d9fd --- /dev/null +++ b/finance-web/src/views/system/WebhookView.vue @@ -0,0 +1,301 @@ + + + + + diff --git a/finance-web/src/views/transactions/TransactionListView.vue b/finance-web/src/views/transactions/TransactionListView.vue new file mode 100644 index 0000000..b2584bd --- /dev/null +++ b/finance-web/src/views/transactions/TransactionListView.vue @@ -0,0 +1,297 @@ + + + + + diff --git a/finance-web/src/views/vip/VipHolderView.vue b/finance-web/src/views/vip/VipHolderView.vue new file mode 100644 index 0000000..64ca3b4 --- /dev/null +++ b/finance-web/src/views/vip/VipHolderView.vue @@ -0,0 +1,145 @@ + + + diff --git a/finance-web/src/views/vip/VipPlanView.vue b/finance-web/src/views/vip/VipPlanView.vue new file mode 100644 index 0000000..8c642a5 --- /dev/null +++ b/finance-web/src/views/vip/VipPlanView.vue @@ -0,0 +1,398 @@ + + + diff --git a/finance-web/tsconfig.json b/finance-web/tsconfig.json new file mode 100644 index 0000000..387b165 --- /dev/null +++ b/finance-web/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "strict": true, + "jsx": "preserve", + "resolveJsonModule": true, + "isolatedModules": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "skipLibCheck": true, + "noEmit": true, + "useDefineForClassFields": true, + "baseUrl": ".", + "paths": { + "@/*": ["src/*"] + }, + "types": ["vite/client", "node"] + }, + "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.vue", "vite.config.ts"] +} diff --git a/finance-web/vite.config.ts b/finance-web/vite.config.ts new file mode 100644 index 0000000..6cc5bf4 --- /dev/null +++ b/finance-web/vite.config.ts @@ -0,0 +1,40 @@ +import { fileURLToPath, URL } from 'node:url' +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' + +// 中央计费平台前端构建配置 +export default defineConfig({ + base: './', + plugins: [vue()], + resolve: { + alias: { + '@': fileURLToPath(new URL('./src', import.meta.url)), + }, + }, + server: { + host: '127.0.0.1', + port: 5180, + strictPort: true, + proxy: { + // 真实后端联调时把 VITE_USE_MOCK 设为 0 + '/api': { + target: 'http://localhost:8080', + changeOrigin: true, + }, + }, + }, + build: { + outDir: 'dist', + sourcemap: false, + chunkSizeWarningLimit: 1500, + rollupOptions: { + output: { + manualChunks: { + vue: ['vue', 'vue-router', 'pinia'], + element: ['element-plus', '@element-plus/icons-vue'], + charts: ['echarts'], + }, + }, + }, + }, +}) diff --git a/财务系统代码审计与修复报告.md b/财务系统代码审计与修复报告.md new file mode 100644 index 0000000..ee2bce5 --- /dev/null +++ b/财务系统代码审计与修复报告.md @@ -0,0 +1,215 @@ +# 财务系统代码审计与修复报告 + +- 项目:`e:\FinancialSystem`(前端工程 `finance-web`,内置 Mock 后端 `src/mock`) +- 审计日期:2026-10-28 +- 审计范围:`finance-web/src` 全部源码(前端页面、API 层、工具库、路由与权限、Mock 后端业务规则) +- 交付状态:**已修复 27 项缺陷**,另有 9 项属于演示环境的设计性限制,已列出并给出生产化建议 + +--- + +## 一、审计方法 + +1. **自底向上通读**:先读公共基础设施(`utils/http.ts`、`utils/session.ts`、`utils/money.ts`、`utils/validate.ts`、`utils/mask.ts`、`utils/export.ts`、`router/index.ts`、`directives/permission.ts`),确认错误处理、鉴权、金额换算、脱敏的既有约定。 +2. **按业务链路核对**:`Mock router.ts` 按「认证 → 看板 → 订单 → 退款 → 流水 → 定价策略 → 对账 → 管理员 → 审计 → 全局参数 → 公开收款页」逐段阅读,核对每条路由的权限、状态机、金额与点数的计算口径。 +3. **前后端口径交叉验证**:把页面展示的金额/上限/阈值与后端计算规则逐项比对(可退上限、兑率折算、双人复核阈值、凭证号长度)。 +4. **攻击面检查**:越权(水平/垂直)、账号枚举、会话失效、开放重定向、SSRF、幂等重放、审计链可篡改、畸形输入导致 500。 +5. **修复后回归**:`npm run type-check` 与 `npm run build` 均通过。 + +金额约定:**金额一律以「分」为整数存储与传输**,点数一律为整数;所有换算集中在 `utils/money.ts`(`formatCent` / `yuanInputToCent`)。 + +--- + +## 二、问题分级 + +| 级别 | 含义 | +| --- | --- | +| P0 | 资金/权限/审计正确性缺陷,会造成错账、越权或合规风险 | +| P1 | 业务逻辑不通、状态机非法、口径不一致,会产生脏数据或误导用户 | +| P2 | 健壮性/可维护性问题,会引发 500、未捕获异常或体验缺陷 | + +--- + +## 三、已修复问题清单 + +### 3.1 认证与会话(P0/P1) + +| 编号 | 位置 | 问题 | 影响 | 修复 | +| --- | --- | --- | --- | --- | +| A-1 | `src/mock/router.ts` › `GET /admin/audit-logs/verify` | 校验公式 `id+actorId+action+targetId+createTime` 与写入时的摘要算法不一致 | 哈希链校验**必然误报断裂**,审计防篡改能力形同虚设 | 改用统一的 `auditHash(item, prev)` | +| A-2 | `src/mock/db.ts` › `auditHash` / `buildAudits` / `appendAudit` | 种子数据、追加、校验三套算法各不相同,且摘要未覆盖 `beforeJson/afterJson/result/actorName` | 篡改审计内容不会破坏哈希,链式校验失去意义 | 统一为一套 `auditHash`,摘要覆盖全部关键字段 | +| A-3 | `src/mock/router.ts` › `POST /admin/logout` | 只清前端 token,服务端会话仍有效 | 登出后旧令牌可继续调用接口 | 登出时删除 `db.sessions` 中对应令牌 | +| A-4 | `src/mock/router.ts` › `POST /admin/password/change` | 改密后旧会话继续有效 | 密码泄露场景下攻击者会话不会被切断 | 改密后注销该账号其他会话,仅保留当前令牌 | +| A-5 | `src/mock/router.ts` › `POST /admin/login` | 账号不存在/密码错误/账号停用提示不同,且返回「剩余尝试次数」;令牌用 `Math.random()` | 可枚举有效账号与账号状态;令牌可预测 | 统一为「用户名或密码错误」;停用状态在密码校验通过后才提示;令牌改用 `crypto.getRandomValues` | +| A-6 | `src/mock/router.ts` › `POST /admin/admins/:id/reset-password` | 未禁止重置本人密码 | 绕过「原密码校验」直接改自己的密码 | 增加 `admin.id !== ctx.admin.id` 校验,引导走改密流程 | + +### 3.2 订单与资金(P0/P1) + +| 编号 | 位置 | 问题 | 影响 | 修复 | +| --- | --- | --- | --- | --- | +| B-1 | `POST /admin/orders/:id/confirm` | 先置 `status = PAID`、后校验 VIP 档位/钱包账户是否存在 | 校验失败时订单已是「已到账」但未入账,产生**脏数据** | 所有前置校验(复核人、档位、账户)完成后才落库 | +| B-2 | `POST /admin/orders/:id/confirm` | 到账时间可填未来时间;同一银行凭证号可被多张订单复用 | 可伪造未来到账、一票多单 | 增加到账时间格式/区间校验(不早于下单、不晚于当前);凭证号唯一性校验(4098) | +| B-3 | `POST /admin/orders/:id/confirm` | 复核人未限制角色 | 审计员也可作为资金复核人 | 复核人限定 `SUPER_ADMIN` / `FINANCE` | +| B-4 | `POST /admin/refunds` | 扣回点数按「当前兑率」折算 | 兑率调整后退款扣点算错,直接影响用户点数 | 按订单成交时兑率 `pointsGained / amountCent` 等比例折算 | +| B-5 | `POST /admin/refunds` | 可退上限只统计已出账退款,待复核退款不占额度 | 多张待复核退款可叠加超额退款 | 上限改用 `refundedSum()`(含 PENDING) | +| B-6 | `POST /admin/refunds` | 小于阈值的退款自动完成,但凭证号可留空 | 无凭证直接产生现金流出,无法追溯 | 即时完成的退款强制要求凭证号 ≥ 6 位 | +| B-7 | `applyRefund()` | 复核通过路径中退款单已在列表且已置 `COMPLETED`,又 `+ refund.amountCent` | **重复计量**,部分退款被误判为全额退款 | 统计时排除自身(`excludeRefundId`),区分「占用额度」与「已出账额度」 | +| B-8 | `applyRefund()` | 全额退 VIP 订单后未撤销会员权益 | 退款后用户仍享受免扣费 | 全额退款且订单类型为 VIP 时,将 VIP 到期时间置为当前、清空账户会员字段 | +| B-9 | `applyRefund()` | 出账流水凭证号兜底为 `PENDING-VOUCHER` | 用占位符生成现金流出 | 函数入口强制校验凭证号,移除占位兜底 | +| B-10 | `POST /pay/orders` | 无幂等键,重复点击/网络重试会生成第二笔订单(且凭证已被消耗) | 重复下单,用户可能重复转账 | 支持 `idempotencyKey`(按应用隔离存储),重放直接返回首次结果;幂等校验前置于「凭证已使用」校验 | +| B-11 | `POST /pay/orders` | 双人复核阈值硬编码 `amountCent >= 500000` | 与应用级策略 / 全局参数不一致 | 统一走 `dualThreshold(appCode)` | +| B-12 | `POST /admin/pricing/:appCode` | 兑率只校验「正整数」,无上限 | 可配置成 1 元兑上百万点,等于变相发币 | 增加业务上限 `≤ 10000` | + +### 3.3 权限与配置(P0/P1) + +| 编号 | 位置 | 问题 | 影响 | 修复 | +| --- | --- | --- | --- | --- | +| C-1 | `src/mock/db.ts` › `ROLE_PERMISSIONS` | 超级管理员缺少 `fin:recharge:confirm`、`fin:refund:create` | 超管无法执行核心资金操作,与角色定义矛盾 | 补齐超管权限(复核自审仍受「发起人不得复核」约束) | +| C-2 | `POST /admin/reconcile/run` | 执行对账只要求 `fin:view`,审计员也能触发资金对账 | 越权执行写操作 | 新增权限码 `fin:reconcile:run`,仅超管/财务拥有 | +| C-3 | `POST /admin/reconcile/run` | 未校验应用存在性、结束日期不得晚于今天、窗口跨度 | 可对不存在应用或未来窗口对账,产生无效/重复报告 | 增加应用存在性、`windowEnd ≤ 今天`、窗口 ≤ 366 天校验 | +| C-4 | `src/views/reconcile/ReconcileView.vue` | 「执行对账」按钮无权限指令 | 前端仍向无权账号展示高危操作入口 | 增加 `v-perm="PERM.reconcileRun"`;`constants/index.ts` 补充 `reconcileRun` | +| C-5 | `PUT /admin/apps/:appCode` | 应用更新缺 webhook 地址、TTL、名称校验(创建时有) | 可写入非 HTTPS/内网 webhook,SSRF 风险 | 与创建路径对齐校验,并复用 `assertWebhookUrl` | +| C-6 | `POST /admin/apps` / `PUT /admin/apps/:appCode` | webhook 地址只校验格式 | 可配置指向内网地址的回调,构成 SSRF | 新增 `assertWebhookUrl`:强制 HTTPS + 域名非 IP/非单标签主机 | + +### 3.4 全局参数落地(P1) + +| 编号 | 位置 | 问题 | 影响 | 修复 | +| --- | --- | --- | --- | --- | +| D-1 | 多处 | 锁定时长/次数、双人复核阈值、token TTL、密钥宽限期、凭证有效期硬编码 | 配置中心改了参数但业务不生效,与需求文档不符 | 新增 `configValue()`,各处改为读取 `admin.lock.threshold`、`admin.lock.minutes`、`review.threshold_cent`、`token.ttl_seconds`、`secret.rotate.grace_hours`、`ticket.ttl_minutes` | + +### 3.5 前端页面(P1/P2) + +| 编号 | 位置 | 问题 | 影响 | 修复 | +| --- | --- | --- | --- | --- | +| E-1 | `src/views/pay/PayView.vue` › `payRedirectUri` | 只校验协议 http/https,未校验主机 | 开放重定向风险(IP 直连、异常域名可展示为可点击链接) | 叠加 `isSafeRedirectHost(parsed.hostname)` | +| E-2 | `src/views/pay/PayView.vue` 文案 | 宣称「已通过白名单校验」「不会在 URL 中追加凭证」 | 与实际实现不符,误导用户对安全性的判断 | 文案改为如实描述(域名格式校验;凭证来自业务链接、不写本地存储) | +| E-3 | `src/views/pay/PayView.vue` 下单 | 无幂等键 | 网络重试会重复下单 | 按「应用+凭证+类型+金额/档位」生成并复用幂等键,成功后重置 | +| E-4 | `src/api/pay.ts` | `PayCreatePayload` 无幂等字段 | 前端无法传递幂等键 | 新增可选 `idempotencyKey` | +| E-5 | `src/components/ExportButton.vue` | `try/finally` 缺 `catch` | 导出失败产生未捕获的 Promise 拒绝 | 补 `catch`(错误由 http 拦截器统一提示) | +| E-6 | `src/views/orders/OrderListView.vue` | 详情抽屉中退款单、现金流水的凭证号明文展示 | 银行凭证号批量泄露(截图/肩窥) | 统一使用 `maskVoucher()` | +| E-7 | `src/views/refunds/RefundListView.vue` › `searchOrders` | 固定取前 100 条、无应用过滤、无提示 | 订单多时用户可能选错订单或找不到目标订单 | 补 `appCode` 过滤;总数超 100 时提示改用订单号精确搜索 | + +### 3.6 健壮性(P2) + +| 编号 | 位置 | 问题 | 影响 | 修复 | +| --- | --- | --- | --- | --- | +| F-1 | `src/mock/router.ts` › `normalizePath` | `decodeURIComponent` 无兜底 | 畸形百分号编码抛 `URIError`,请求变 500 | 新增 `safeDecode`,查询串与路径参数统一兜底;路径本身不解码,避免 `%2F` 绕过前缀判断 | + +--- + +## 四、未修复项(设计性限制 / 需生产后端承接) + +以下问题属于「Mock 演示实现的固有约束」,在纯前端 Mock 中无法真正解决,需在后端落地时承接,故本次仅记录不改写,避免掩盖真实风险。 + +| 编号 | 项 | 现状 | 生产化要求 | +| --- | --- | --- | --- | +| G-1 | 管理员口令明文存放 | `AdminRecord.password` 为明文,用于演示登录比对 | 后端改为 Argon2id/BCrypt 存储,禁止明文与可逆加密 | +| G-2 | 动态口令固定 `123456` | 所有 TOTP 校验为固定值 | 接入真实 TOTP(RFC 6238),带时间窗与重放保护 | +| G-3 | 会话存 `sessionStorage` 且无刷新续期 | 前端 30 分钟空闲登出,服务端 8 小时 | 后端签发短期 access token + refresh token,服务端可吊销 | +| G-4 | 审计摘要使用非密码学 `digest` | 演示用字符串哈希 | 后端改用 SM3/HMAC-SM3,并对链头做定期锚定 | +| G-5 | 待确认订单无超时关单任务 | `order.pending.timeout_hours` 已存在但无定时任务消费 | 后端增加定时关单任务,并写审计与 webhook | +| G-6 | Webhook 无重试 worker | 仅落库 `PENDING`,`webhook.max_retry` 未被消费 | 后端增加指数退避重试、签名校验与死信队列 | +| G-7 | 人工调账的复核仅传复核人 ID | 未校验复核人是否真正二次确认 | 改为双人独立审批流(发起/复核分离 + 各自 TOTP) | +| G-8 | `GET /pay/orders/:outTradeNo/status` 无鉴权 | 订单号可被枚举查询状态与金额 | 后端增加 ticket/token 绑定或限流 + 订单号高熵化 | +| G-9 | `GET /pay/demo-ticket` 敞开 | 任意人可签发演示凭证 | 生产构建必须移除该路由(或仅在 `VITE_USE_MOCK=1` 下注册) | +| G-10 | 应用 client secret 与 webhook secret 复用同一随机串 | 创建应用时两者同源 | 后端分离两类密钥,独立轮换与独立审计 | + +> 安全提示:生产部署必须确保 `VITE_USE_MOCK=0`,否则整套 Mock 路由(含 `demo-ticket`)会被打包进前端。建议在构建脚本中对该变量做硬性断言。 + +--- + +## 五、关键修复的实现要点 + +### 5.1 审计哈希链统一 + +`src/mock/db.ts` 新增唯一摘要函数,写入、追加、校验三处共用: + +```ts +export function auditHash(item, prevHash): string { + return digest(JSON.stringify([ + item.id, item.actorId, item.actorName, item.action, item.targetType, + item.targetId, item.beforeJson, item.afterJson, item.result, item.createTime, prevHash, + ])) +} +``` + +`/admin/audit-logs/verify` 改为 `const expected = auditHash(item, prev)`,不再自行拼接字符串。 + +### 5.2 退款计量口径拆分 + +```ts +// 占用额度(含待复核)——用于可退上限 +function refundedSum(orderId, excludeRefundId?) { ... status !== 'REJECTED' ... } + +// 实际出账(仅 COMPLETED)——用于判断是否全额退款 +function completedRefundSum(orderId, excludeRefundId?) { ... status === 'COMPLETED' ... } +``` + +`applyRefund()` 内统一排除自身: + +```ts +const occupied = refundedSum(order.id, refund.id) + refund.amountCent +const completed = completedRefundSum(order.id, refund.id) + refund.amountCent +order.refundedAmountCent = occupied +order.status = completed >= order.amountCent ? 'REFUNDED' : 'PAID' +``` + +这样「即时退款」与「复核通过」两条路径口径一致,不会重复计量。 + +### 5.3 下单幂等 + +```ts +const storeKey = idempotencyKey ? `${appCode}|${idempotencyKey}` : '' +if (idempotencyKey) { + ensure(/^[A-Za-z0-9:_-]{8,64}$/.test(idempotencyKey), 422, '幂等键格式不合法') + const existingId = db.idempotency.get(storeKey) + if (existingId) { /* 直接返回首次结果 */ } +} +``` + +幂等校验前置于「凭证已被使用」校验,因此「首次请求成功但响应丢失」的重试可以拿到原订单,而不是报「凭证已使用」。 + +--- + +## 六、验证记录 + +| 验证项 | 命令 | 结果 | +| --- | --- | --- | +| 类型检查 | `npm run type-check`(cwd `finance-web`) | 通过(0 error) | +| 生产构建 | `npm run build`(`vue-tsc --noEmit && vite build`) | 通过,`✓ built`,无类型/打包错误 | + +建议的回归用例(按业务链路): + +1. **登录**:错误密码多次 → 触发锁定;锁定期间再登录 → 提示锁定剩余时间;不存在账号与错误密码 → 文案一致。 +2. **登出**:登出后用旧 token 直接调任意管理接口 → 应 401。 +3. **改密**:A 账号在另一会话改密 → 当前会话保留、其他会话失效。 +4. **确认到账**:金额 ≥ 应用阈值 → 必须选择第二复核人;复核人选择本人 → 拒绝;填入已被使用的凭证号 → 4098;到账时间填明天 → 422。 +5. **退款(小额)**:不填凭证号 → 422;填凭证号 → 立即完成,订单未误标为全额退款。 +6. **退款(大额)**:发起 → 待复核 → 另一管理员复核通过 → 订单状态与已退金额正确;全额退 VIP → 会员权益被撤销。 +7. **退款上限**:对同一订单连续发起两张待复核退款,第二张超额时被拒绝。 +8. **支付页**:连续点击「确认下单」/断网重试 → 只产生一笔订单;`redirectUri` 填 `https://10.0.0.1/x` → 不展示返回按钮。 +9. **对账**:审计员账号看不到「执行对账」按钮,直接调接口 → 403;结束日期选明天 → 422。 +10. **审计链**:进入审计日志页执行「校验哈希链」→ 显示完整、未发现篡改。 + +--- + +## 七、变更文件清单 + +| 文件 | 变更概要 | +| --- | --- | +| `src/mock/db.ts` | 统一 `auditHash`;种子/追加改用统一摘要;新增 `idempotency` 映射;补齐超管权限 | +| `src/mock/router.ts` | 登录/登出/改密安全加固;订单确认前置校验;退款计量与 VIP 撤销;审计链校验;对账权限与窗口;下单幂等与阈值;`assertWebhookUrl` / `assertRedirectUri`;`safeDecode`;兑率上限;重置密码限制;凭证 TTL 读配置 | +| `src/api/pay.ts` | `PayCreatePayload` 增加 `idempotencyKey` | +| `src/views/pay/PayView.vue` | 跳转地址主机校验;安全文案如实化;下单幂等键 | +| `src/views/orders/OrderListView.vue` | 凭证号脱敏 | +| `src/views/refunds/RefundListView.vue` | 可退订单检索加应用过滤与超量提示 | +| `src/views/reconcile/ReconcileView.vue` | 执行对账增加权限指令 | +| `src/components/ExportButton.vue` | 补异常捕获 | +| `src/constants/index.ts` | 新增 `PERM.reconcileRun` | + +--- + +## 八、遗留风险提示 + +1. 本次修复均在「前端 Mock 后端」范围内,**真实资金安全仍取决于后端实现**;前端 Mock 的校验只用于演示与联调对齐口径。 +2. 请务必确认生产构建 `VITE_USE_MOCK=0`,并在 CI 中断言,避免演示路由(`/pay/demo-ticket`)进入生产包。 +3. 审计链、幂等、双人复核等规则在对接真实后端时,需以本文口径作为接口契约的一部分,避免前端 Mock 与后端行为分叉。 diff --git a/财务系统后端需求文档.md b/财务系统后端需求文档.md new file mode 100644 index 0000000..4692b51 --- /dev/null +++ b/财务系统后端需求文档.md @@ -0,0 +1,2194 @@ +# 中央计费平台后端需求文档 + +> **文档状态:本文档为后端开发需求,当前仅前端可用。** +> 前端已完成全部页面、交互与 Mock 行为基准;后端尚未开发,本文档描述后端必须实现的契约与规则。 + +## 1. 文档信息与范围 + +### 1.1 文档信息 + +| 项目 | 内容 | +| --- | --- | +| 文档名称 | 中央计费平台后端需求文档 | +| 文档版本 | v1.0.0 | +| 编制日期 | 2026-10-27 | +| 适用系统 | 中央计费平台(Finance Platform,统一前缀 `fin_`) | +| 前端代码基线 | `E:\FinancialSystem\finance-web` | +| 前端技术栈 | Vue 3 + Vite + TypeScript + Element Plus + Pinia | +| 后端状态 | **待开发**,仓库内不存在后端工程 | +| 接口统一前缀 | `/api`(与 `VITE_API_BASE=/api`、Vite `server.proxy['/api']` 一致) | +| 密级 | 内部 | +| 主要读者 | 后端开发、测试、安全测评、运维、项目管理 | + +### 1.2 契约来源(只认代码,不认口头描述) + +| 文件 | 提供的事实 | +| --- | --- | +| `src/api/auth.ts` | 登录、登出、profile、改密 4 个接口及请求字段 | +| `src/api/core.ts` | 应用、账户、订单、退款、流水、审批人接口及查询参数 | +| `src/api/settings.ts` | VIP、兑率、策略、对账、全局参数接口 | +| `src/api/system.ts` | 管理员、审计、webhook、看板接口 | +| `src/api/pay.ts` | 公开收银台 preview/create/status/demo-ticket 接口 | +| `src/types/index.ts` | 全部响应实体的字段名、字段类型、可空性 | +| `src/mock/router.ts` | 路由、权限、校验、错误码、状态机的真实行为 | +| `src/mock/db.ts` | 种子数据语义、角色权限并集、配置项默认值 | +| `src/constants/index.ts` | 15 个权限码、角色、状态与类型枚举 | +| `src/utils/validate.ts` | 密码策略、业务用户 ID、幂等键、跳转域名白名单规则 | +| `src/utils/money.ts` | 金额以分存储、点数必须为正整数、元转分规则 | +| `src/utils/http.ts` | 统一响应体、错误码文案、401 处理、超时 20s | +| `src/utils/export.ts` | CSV 注入转义、UTF-8 BOM、导出上限 1 万行 | +| `.env.development` / `.env.production` | 开发 `VITE_USE_MOCK=1`,生产 `VITE_USE_MOCK=0`、`VITE_API_BASE=/api` | +| `vite.config.ts` | 开发代理 `/api → http://localhost:8080`,前端端口 5180 | + +### 1.3 范围声明 + +**本文档覆盖(后端必须交付)** + +| 域 | 内容 | +| --- | --- | +| 认证与会话 | 管理员用户名 + 密码 + TOTP 登录、登出、会话续期、改密、锁定 | +| 应用接入 | 接入应用 CRUD、client_secret 轮换/回收、client token 签发/撤销、停用熔断 | +| 账户与点数 | 业务账户、余额、累计消耗、人工调账、点数流水、幂等与并发控制 | +| 充值订单 | 自助下单、财务确认到账、关单、导出、双人复核、现金台账 | +| 退款 | 发起、点数扣回、现金退款、阈值复核、驳回、幂等 | +| VIP | 档位维护、开通/续费、有效期叠加、VIP 免扣 | +| 计费 | 应用兑率、扣费策略、保底/上限/失败策略、扣费开放接口 | +| 对账 | 现金侧与点数侧分离对账、断链检测、差异报告(只报告不修复) | +| 审计 | 全量写操作留痕、哈希链、链校验、导出 | +| Webhook | Outbox、HMAC 签名、至少一次投递、退避重试、人工重放 | +| 系统管理 | 管理员账号、角色、全局参数、限流 | +| 公开收银台 | 一次性 ticket、预览、下单、状态轮询 | +| 非功能 | 等保二级控制项、安全设计、部署、备份、监控、验收用例 | + +**明确不在本期范围** + +| 项 | 说明 | +| --- | --- | +| 微信/支付宝真实支付对接 | 前端类型保留 `wechat`/`alipay`,当前下单固定 `offline`;在线支付属二期 | +| 发票、税务、电子签章 | 无前端页面、无数据结构,本期不做 | +| 多租户、多法人 | 当前单法人、单实例内网部署 | +| 消息队列(Kafka/RabbitMQ) | 用 MySQL Outbox + 定时任务替代,降低运维面 | +| 移动端/小程序 | 仅 PC Web | +| 数据仓库/BI | 看板由在线聚合查询提供,不建数仓 | +| 短信/邮件通知 | 无前端入口,本期不做 | + +### 1.4 前端已完成 / 后端待开发边界 + +| 能力 | 前端现状 | 后端待开发 | +| --- | --- | --- | +| 路由与菜单 | 14 个业务页面 + 登录/改密/收银台/403/404 | 提供 profile 与权限码,菜单由前端静态定义 | +| 权限控制 | `v-perm`、路由 meta.perm、`hasPerm()` 体验层控制 | 每个接口服务端二次校验权限码 | +| 表单校验 | 密码强度、金额、点数、域名、幂等键等前端校验 | 使用同一规则重新校验,前端校验不可信 | +| 数据来源 | `VITE_USE_MOCK=1` 时走 `mockAdapter` | 生产 `VITE_USE_MOCK=0`,全部走 `/api` | +| 导出 | 前端请求 JSON 数组,浏览器生成 CSV | 返回 JSON 数组;后端同时做 CSV 注入防护与审计 | +| 会话 | sessionStorage 存 Bearer token,30 分钟空闲提示 | 服务端会话 30 分钟空闲 / 8 小时绝对上限 | +| TOTP | 登录与敏感操作均要求 6 位动态码 | RFC 6238 校验、时间窗、防重放 | +| 在线支付 | 收银台仅展示线下收款信息 | 线下对公转账;在线支付不在本期 | + +### 1.5 三条不可协商的契约原则 + +1. **前端字段名即后端响应字段名**:响应 JSON 一律 camelCase,且必须包含 `src/types/index.ts` 中该实体的全部字段;后端可增加字段,但不得删改前端已声明字段。 +2. **HTTP 状态统一 200**:业务成功/失败均返回 HTTP 200,由响应体 `code` 表达结果。前端 `http.ts` 只检查 `body.code`,非 2xx 会被 axios 当作网络异常,导致错误文案丢失。 +3. **金额与点数精度**:金额一律 `bigint` 分(`amountCent`),点数一律 `bigint` 个(`points`/`balance`);禁止浮点、禁止“元”作为存储单位。 + +--- + +## 2. 总体架构与技术选型 + +### 2.1 部署拓扑 + +``` + Internet / 内网办公网 + │ + ┌─────▼─────┐ + │ Nginx │ 443/TLS1.2+,仅暴露 443 + │ 静态资源 │ / → finance-web dist + │ 反向代理 │ /api/* → 127.0.0.1:8080 + └─────┬─────┘ + │ 127.0.0.1 + ┌─────▼──────────┐ + │ Spring Boot 单体 │ 8080(仅本机监听) + │ finance-server │ 管理端口 8081(仅本机) + └───┬────────┬───┘ + │ │ + ┌─────────▼──┐ ┌──▼─────────┐ + │ MySQL 8 │ │ Redis 7 │ + │ 3306 本机 │ │ 6379 本机 │ + └────────────┘ └────────────┘ + │ + ┌─────────▼────────────┐ + │ 可选:MinIO/备份盘 │ 审计导出归档、数据库备份 + └──────────────────────┘ +``` + +### 2.2 技术选型与取舍 + +| 层 | 建议方案 | 备选 | 取舍说明 | +| --- | --- | --- | --- | +| 运行时 | JDK 17 LTS | JDK 21 LTS | 17 足够且内网客户环境更常见;如客户统一 21 可升级 | +| 框架 | Spring Boot 3.3.x | Spring Boot 2.7 | 3.x 支持 Jakarta、长期维护;不引入微服务 | +| Web | spring-boot-starter-web | WebFlux | 管理后台低并发,阻塞模型更易排障 | +| ORM | MyBatis-Plus 3.5.x | JPA / 纯 MyBatis | 分页、乐观锁、逻辑状态配置成熟;复杂对账 SQL 用 XML | +| 鉴权 | Sa-Token 1.39.x(Bearer) | Spring Security | Sa-Token 权限码、会话、注解更轻;不引入 OAuth2 全家桶 | +| 密码哈希 | Argon2id(BouncyCastle) | BCrypt(cost≥12) | 两者均可;二选一后不得混用,见 §6.1 | +| TOTP | java-otp / 自研 RFC 6238 | GoogleAuth | 仅需 SHA1/6 位/30 秒,自研 100 行内可审计 | +| 数据库 | MySQL 8.0.33+ InnoDB utf8mb4 | PostgreSQL | 客户内网标准化 MySQL;JSON 字段可用 | +| 迁移 | Flyway | Liquibase / 手工 SQL | 版本化、可重复、上线可审计 | +| 缓存/会话 | Redis 7 | 仅 MySQL | 会话、限流、nonce、TOTP 防重放必须 Redis | +| 反向代理 | Nginx 1.24+ | Apache | TLS 终结、限流、静态资源、CORS 白名单 | +| 定时任务 | Spring `@Scheduled` + 数据库锁 | Quartz 集群 | 单机部署,Quartz 集群能力用不上 | +| 异步投递 | Outbox 表 + 轮询器 | MQ | 不引入 Kafka/RabbitMQ,见 §6.11 | +| 可观测 | Actuator + Micrometer + 结构化日志 | Prometheus 全家桶 | 先暴露指标端点,客户有监控再接 | +| 文档 | 关闭 Swagger 生产暴露 | Knife4j | 生产禁用;仅测试环境可开 | + +### 2.3 代码分层(建议) + +``` +com.gas.fin +├── common // R、错误码、分页、TraceId、脱敏、CSV 安全、时钟 +├── config // Sa-Token、MyBatis、Redis、Flyway、CORS、Jackson +├── auth // 登录、TOTP、会话、密码策略、锁定 +├── admin // 管理员、角色、审批人查询 +├── app // 接入应用、密钥、client token +├── account // 钱包账户、调账、流水 +├── order // 充值订单、确认、关单、现金台账 +├── refund // 退款单、复核 +├── vip // 档位、持有 +├── pricing // 兑率、策略 +├── charge // 开放扣费接口 +├── ticket // 一次性 ticket、收银台 +├── reconcile // 对账任务与报告 +├── audit // 审计、哈希链、导出 +├── webhook // Outbox、签名、投递、重放 +└── job // 订单超时、webhook 重试、会话清理、对账日跑 +``` + +### 2.4 接口通用约定 + +| 项 | 约定 | +| --- | --- | +| 前缀 | 所有接口以 `/api` 开头;Nginx 不去掉前缀,后端 `server.servlet.context-path` 为空,Controller 映射 `/api/...` | +| 请求体 | `application/json; charset=utf-8`;GET 参数用 query string | +| 认证头 | `Authorization: Bearer `;公开接口无需该头 | +| TraceId | 响应头 `X-Trace-Id` + 响应体 `traceId`,同一次请求一致;日志按 TraceId 串联 | +| 统一响应 | `{"code":0,"message":"success","data":...,"traceId":"..."}` | +| 分页响应 | `{"records":[],"total":0,"page":1,"pageSize":20}`,`pageSize` 上限 100 | +| 时间格式 | `yyyy-MM-dd HH:mm:ss`(Asia/Shanghai,无时区后缀);日期参数 `yyyy-MM-dd` | +| 空值 | 可空字段返回 `null`,不返回空字符串代替;字符串字段不做 `undefined` | +| ID | 数据库 `bigint`,JSON 用 number;前端 `number` 安全整数范围内(雪花 ID 需 ≤ 2^53-1,建议使用 53 位雪花或转字符串方案,见 §4.1) | +| 排序 | 列表默认按时间倒序;账户列表按余额倒序;对账报告按创建时间倒序 | +| 错误 | 业务失败 `code != 0`,`data` 可为 `null`;禁止返回 HTML 错误页 | + +--- + +## 3. 角色与权限矩阵 + +### 3.1 角色定义 + +| 角色 | 中文名 | 职责 | 硬性边界 | +| --- | --- | --- | --- | +| `SUPER_ADMIN` | 超级管理员 | 管应用、定价、VIP、管理员、配置、审计、webhook、调账、退款复核、关单 | **不可确认充值到账**(职责分离) | +| `FINANCE` | 财务专员 | 确认到账、发起退款、复核退款、关单、查询与导出 | **不可修改定价/策略**、不可管应用与管理员、不可调账 | +| `AUDITOR` | 审计员 | 只读查询、导出、审计日志与链校验 | **不可执行任何写操作**;无资金操作权限 | + +### 3.2 权限码清单(以代码为准,共 15 个) + +> 说明:前端 `PERM` 常量为 15 个,已包含 `fin:reconcile:run`(对账执行)。本文以代码为准,权限码为 15 个;如后续新增,必须先改前端 `PERM` 与 `v-perm`,再改后端。 + +| # | 权限码 | 含义 | 授予角色 | 前端使用位置 | +| --- | --- | --- | --- | --- | +| 1 | `fin:view` | 查看业务数据 | 三角色 | 全部查询页、路由 meta | +| 2 | `fin:export` | 导出 CSV | 三角色 | 订单/流水/审计导出按钮 | +| 3 | `fin:app:manage` | 接入应用与密钥管理 | SUPER_ADMIN | 应用页新增/编辑/轮换/停用/token | +| 4 | `fin:pricing:edit` | 修改兑率与扣费策略 | SUPER_ADMIN | 兑率与策略页修改 | +| 5 | `fin:vip:manage` | 维护 VIP 档位 | SUPER_ADMIN | VIP 档位新增/改价/上下架 | +| 6 | `fin:admin:manage` | 管理员账号管理 | SUPER_ADMIN | 管理员页 | +| 7 | `fin:config:edit` | 修改全局参数 | SUPER_ADMIN | 全局参数页 | +| 8 | `fin:audit:view` | 查看/校验审计日志 | SUPER_ADMIN、AUDITOR | 审计页、菜单 | +| 9 | `fin:webhook:manage` | 重放 webhook | SUPER_ADMIN | Webhook 页重放 | +| 10 | `fin:account:adjust` | 人工调账 | SUPER_ADMIN | 账户页调账 | +| 11 | `fin:recharge:confirm` | 确认充值到账 | FINANCE | 订单页确认到账 | +| 12 | `fin:refund:create` | 发起退款 | FINANCE | 退款页发起 | +| 13 | `fin:refund:review` | 复核退款 | SUPER_ADMIN、FINANCE | 退款页复核 | +| 14 | `fin:order:cancel` | 关闭待确认订单 | SUPER_ADMIN、FINANCE | 订单页关单 | +| 15 | `fin:reconcile:run` | 执行对账 | SUPER_ADMIN、FINANCE | 对账中心执行按钮 | + +### 3.3 角色—权限矩阵 + +| 权限码 | SUPER_ADMIN | FINANCE | AUDITOR | +| --- | --- | --- | --- | +| `fin:view` | ● | ● | ● | +| `fin:export` | ● | ● | ● | +| `fin:app:manage` | ● | — | — | +| `fin:pricing:edit` | ● | — | — | +| `fin:vip:manage` | ● | — | — | +| `fin:admin:manage` | ● | — | — | +| `fin:config:edit` | ● | — | — | +| `fin:audit:view` | ● | — | ● | +| `fin:webhook:manage` | ● | — | — | +| `fin:account:adjust` | ● | — | — | +| `fin:recharge:confirm` | — | ● | — | +| `fin:refund:create` | — | ● | — | +| `fin:refund:review` | ● | ● | — | +| `fin:order:cancel` | ● | ● | — | +| `fin:reconcile:run` | ● | ● | — | + +矩阵校验结果: + +- SUPER_ADMIN 13 项,FINANCE 7 项,AUDITOR 3 项,并集 15 项,无遗漏。 +- **职责分离(SoD)三条硬约束**: + 1. 超管无 `fin:recharge:confirm`,不能把订单从 PENDING 改成 PAID;资金入账只能由财务执行。 + 2. 财务无 `fin:pricing:edit`/`fin:vip:manage`,不能改兑率、策略、价格。 + 3. 审计员只有 `fin:view`/`fin:export`/`fin:audit:view`,所有写接口必须 403。 + +### 3.4 接口 → 权限码完整对照表 + +| # | 模块 | 方法与路径 | 所需权限 | +| --- | --- | --- | --- | +| 1 | 认证 | `POST /api/admin/login` | 公开(限流 + 锁定) | +| 2 | 认证 | `POST /api/admin/logout` | `fin:view` | +| 3 | 认证 | `GET /api/admin/profile` | `fin:view` | +| 4 | 认证 | `POST /api/admin/password/change` | `fin:view` | +| 5 | 看板 | `GET /api/admin/dashboard/summary` | `fin:view` | +| 6 | 看板 | `GET /api/admin/dashboard/trend` | `fin:view` | +| 7 | 看板 | `GET /api/admin/dashboard/distribution` | `fin:view` | +| 8 | 应用 | `GET /api/admin/apps` | `fin:view` | +| 9 | 应用 | `POST /api/admin/apps` | `fin:app:manage` | +| 10 | 应用 | `PUT /api/admin/apps/{appCode}` | `fin:app:manage` | +| 11 | 应用 | `POST /api/admin/apps/{appCode}/secret/rotate` | `fin:app:manage` | +| 12 | 应用 | `POST /api/admin/apps/{appCode}/secret/revoke-prev` | `fin:app:manage` | +| 13 | 应用 | `POST /api/admin/apps/{appCode}/toggle` | `fin:app:manage` | +| 14 | 应用 | `GET /api/admin/apps/{appCode}/tokens` | `fin:view` | +| 15 | 应用 | `POST /api/admin/apps/{appCode}/tokens/revoke` | `fin:app:manage` | +| 16 | 账户 | `GET /api/admin/accounts` | `fin:view` | +| 17 | 账户 | `GET /api/admin/accounts/{id}` | `fin:view` | +| 18 | 账户 | `GET /api/admin/accounts/{id}/transactions` | `fin:view` | +| 19 | 账户 | `POST /api/admin/accounts/adjust` | `fin:account:adjust` | +| 20 | 订单 | `GET /api/admin/orders` | `fin:view` | +| 21 | 订单 | `GET /api/admin/orders/export` | `fin:export` | +| 22 | 订单 | `GET /api/admin/orders/{id}` | `fin:view` | +| 23 | 订单 | `POST /api/admin/orders/{id}/confirm` | `fin:recharge:confirm` | +| 24 | 订单 | `POST /api/admin/orders/{id}/cancel` | `fin:order:cancel` | +| 25 | 订单 | `GET /api/admin/approvers` | `fin:recharge:confirm` **或** `fin:refund:review` **或** `fin:account:adjust`(OR) | +| 26 | 退款 | `GET /api/admin/refunds` | `fin:view` | +| 27 | 退款 | `POST /api/admin/refunds` | `fin:refund:create` | +| 28 | 退款 | `POST /api/admin/refunds/{id}/review` | `fin:refund:review` | +| 29 | 流水 | `GET /api/admin/transactions` | `fin:view` | +| 30 | 流水 | `GET /api/admin/transactions/export` | `fin:export` | +| 31 | VIP | `GET /api/admin/vip-plans` | `fin:view` | +| 32 | VIP | `POST /api/admin/vip-plans` | `fin:vip:manage` | +| 33 | VIP | `PUT /api/admin/vip-plans/{id}` | `fin:vip:manage` | +| 34 | VIP | `POST /api/admin/vip-plans/{id}/toggle` | `fin:vip:manage` | +| 35 | VIP | `GET /api/admin/vips` | `fin:view` | +| 36 | 计费 | `GET /api/admin/pricing` | `fin:view` | +| 37 | 计费 | `PUT /api/admin/pricing/{appCode}` | `fin:pricing:edit` | +| 38 | 计费 | `GET /api/admin/policies` | `fin:view` | +| 39 | 计费 | `PUT /api/admin/policies/{appCode}` | `fin:pricing:edit` | +| 40 | 对账 | `GET /api/admin/reconcile/reports` | `fin:view` | +| 41 | 对账 | `GET /api/admin/reconcile/reports/{id}` | `fin:view` | +| 42 | 对账 | `POST /api/admin/reconcile/run` | `fin:reconcile:run` | +| 43 | 管理员 | `GET /api/admin/admins` | `fin:admin:manage` | +| 44 | 管理员 | `POST /api/admin/admins` | `fin:admin:manage` | +| 45 | 管理员 | `PUT /api/admin/admins/{id}` | `fin:admin:manage` | +| 46 | 管理员 | `POST /api/admin/admins/{id}/toggle` | `fin:admin:manage` | +| 47 | 管理员 | `POST /api/admin/admins/{id}/reset-password` | `fin:admin:manage` | +| 48 | 管理员 | `POST /api/admin/admins/{id}/reset-totp` | `fin:admin:manage` | +| 49 | 审计 | `GET /api/admin/audit-logs` | `fin:audit:view` | +| 50 | 审计 | `GET /api/admin/audit-logs/export` | `fin:export` | +| 51 | 审计 | `GET /api/admin/audit-logs/{id}` | `fin:audit:view` | +| 52 | 审计 | `POST /api/admin/audit-logs/verify` | `fin:audit:view` | +| 53 | 参数 | `GET /api/admin/configs` | `fin:view` | +| 54 | 参数 | `PUT /api/admin/configs/{key}` | `fin:config:edit` | +| 55 | Webhook | `GET /api/admin/webhooks` | `fin:view` | +| 56 | Webhook | `POST /api/admin/webhooks/{id}/replay` | `fin:webhook:manage` | +| 57 | 收银台 | `GET /api/pay/preview` | 公开(ticket) | +| 58 | 收银台 | `POST /api/pay/orders` | 公开(ticket,一次性) | +| 59 | 收银台 | `GET /api/pay/orders/{outTradeNo}/status` | 公开(订单号不可枚举) | +| 60 | 收银台 | `GET /api/pay/demo-ticket` | **仅非生产**,生产禁用 | +| 61 | 开放 API | `POST /api/open/v1/token` | client_secret | +| 62 | 开放 API | `POST /api/open/v1/charge` | client token | +| 63 | 开放 API | `POST /api/open/v1/tickets` | client token | +| 64 | 运维 | `GET /api/health` | 公开(最小信息,仅本地/内网) | + +### 3.5 服务端权限实现要求 + +1. 每个 `/api/admin/**` 接口必须声明权限码;禁止只依赖前端 `v-perm`。 +2. `approvers` 使用 OR 模式:`@SaCheckPermission(value={"fin:recharge:confirm","fin:refund:review","fin:account:adjust"}, mode=SaMode.OR)`。 +3. 权限码变更必须同步:后端注解 → 前端 `PERM` → 菜单/按钮 → 测试用例;本文档 §3.3 为唯一权威矩阵。 +4. 对象级校验(防 IDOR):按 `{id}` 取账户/订单/退款/审计/webhook 时,先判存在性再判权限;管理端当前为“全应用可见”,但不得因 ID 猜测返回未授权对象的敏感字段(如 TOTP 密钥、密钥哈希)。 +5. 审计员访问任何非 GET 接口一律 403,包括 `POST /api/admin/audit-logs/verify`?——`verify` 为只读校验但仍是 POST,按现有前端行为允许 `fin:audit:view` 调用,且该接口内部只读不写业务数据(仅追加一条审计记录)。 + +--- + +## 4. 数据模型 + +### 4.1 全局字段规范 + +| 项 | 规范 | +| --- | --- | +| 数据库 | MySQL 8.0.33+,InnoDB,`utf8mb4`,`utf8mb4_0900_ai_ci` | +| 表前缀 | `fin_` | +| 主键 | `id bigint unsigned NOT NULL`,应用层雪花生成(MyBatis-Plus `ASSIGN_ID`)。**唯一例外**:`fin_audit_log.id` 使用数据库自增 `AUTO_INCREMENT`,用于串行化哈希链顺序(见 §6.12 L5);其余表一律雪花 | +| 雪花 ID 与前端精度 | 前端 `id: number`,JS 安全整数上限 9,007,199,254,740,991。**必须使用 53 位以内 ID**(epoch 毫秒 + 机器位 + 序列,控制在 2^53-1),或统一改为字符串并同步前端类型;本项目选择前者,禁止直接使用 64 位完整雪花 | +| 金额 | `bigint`,单位分;字段名以 `_cent` 结尾;禁止 `decimal`/`double` | +| 点数 | `bigint`,单位个;字段名 `points`/`amount`/`balance` 等 | +| 时间 | `datetime`,北京时间(Asia/Shanghai);禁止 `timestamp`(避免时区隐式转换);JDBC 参数 `serverTimezone=Asia/Shanghai` | +| 逻辑状态 | `varchar(16)` 英文大写枚举,见 §14.1;不使用 MySQL `enum` | +| 布尔开关 | `tinyint(1)`,1 是 / 0 否;字段名 `enabled`/`is_active`/`must_change_password` 等 | +| 逻辑删除 | 财务数据**禁止物理删除**;账号/应用用 `enabled`/`is_active` 停用;流水、订单、审计、退款只追加或改状态 | +| 审计字段 | `create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP`;`update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP`(只追加表可无 update_time) | +| 命名 | 数据库 snake_case;JSON camelCase;Java 字段 camelCase;枚举值全大写 | +| 字符集排序 | 新建表统一 `utf8mb4_0900_ai_ci` | +| 外键 | 不建数据库外键,应用层维护;所有关联字段建索引 | +| JSON | 仅用于审计 before/after、webhook payload、策略快照;查询条件不落在 JSON 上 | + +### 4.2 表清单(22 张) + +| # | 表名 | 用途 | 关键关联 | 预估年增长 | +| --- | --- | --- | --- | --- | +| 1 | `fin_admin` | 管理员账号 | — | 百级 | +| 2 | `fin_admin_password_history` | 密码历史(最近 3 次) | `admin_id` | 千级 | +| 3 | `fin_admin_session` | 管理员会话 | `admin_id` | 十万级(可清理) | +| 4 | `fin_app` | 接入应用 | `app_code` | 百级 | +| 5 | `fin_app_secret` | 应用密钥历史(只存哈希) | `app_code` | 千级 | +| 6 | `fin_app_token` | client token(只存哈希) | `app_code` | 百万级(可清理) | +| 7 | `fin_account` | 业务用户钱包账户 | `app_code + business_user_id` | 百万级 | +| 8 | `fin_transaction` | 点数流水(余额账本) | `account`、`order`、`refund` | 千万级 | +| 9 | `fin_order` | 充值/VIP 订单 | `app_code`、`business_user_id` | 百万级 | +| 10 | `fin_cash_ledger` | 现金台账(IN/OUT) | `order_id`、`refund_id` | 百万级 | +| 11 | `fin_refund` | 退款单 | `order_id` | 十万级 | +| 12 | `fin_vip_plan` | VIP 档位 | `app_code + plan_code` | 千级 | +| 13 | `fin_vip_holder` | VIP 持有(当前有效/历史到期) | `app_code + business_user_id` | 十万级 | +| 14 | `fin_app_pricing` | 应用兑率 | `app_code` | 百级 | +| 15 | `fin_app_policy` | 应用扣费策略 | `app_code` | 百级 | +| 16 | `fin_config` | 全局参数 | `config_key` | 百级 | +| 17 | `fin_audit_log` | 审计日志(哈希链) | 无 | 千万级 | +| 18 | `fin_webhook_delivery` | Webhook Outbox/投递记录 | `app_code + event_id` | 百万级 | +| 19 | `fin_reconcile_report` | 对账报告 | `app_code` | 万级 | +| 20 | `fin_reconcile_diff` | 对账差异明细 | `report_id` | 十万级 | +| 21 | `fin_ticket` | 一次性收银台凭证(只存哈希) | `app_code` | 百万级(可清理) | +| 22 | `fin_rate_limit` | 限流计数(Redis 不可用时的降级/审计) | `bucket_key` | 千万级(按窗口清理) | + +### 4.3 表结构明细 + +#### 4.3.1 `fin_admin` + +用途:管理员账号、角色、登录失败计数、TOTP 绑定状态。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `username` | varchar(32) | 否 | — | 登录名,小写字母/数字/下划线,3~32 位 | +| `password_hash` | varchar(100) | 否 | — | Argon2id 或 BCrypt(cost≥12),禁止明文/可逆加密 | +| `role` | varchar(16) | 否 | — | `SUPER_ADMIN`/`FINANCE`/`AUDITOR` | +| `is_active` | tinyint(1) | 否 | 1 | 1 启用 / 0 停用 | +| `must_change_password` | tinyint(1) | 否 | 1 | 1 首次登录或重置后强制改密 | +| `totp_secret_enc` | varchar(255) | 是 | NULL | TOTP 密钥密文(AES-256-GCM,主密钥来自环境变量) | +| `totp_bound` | tinyint(1) | 否 | 0 | 1 已绑定身份验证器 | +| `failed_attempts` | int | 否 | 0 | 连续失败次数 | +| `locked_until` | datetime | 是 | NULL | 锁定截止时间 | +| `last_login_at` | datetime | 是 | NULL | 最近成功登录时间 | +| `last_login_ip` | varchar(45) | 是 | NULL | IPv4/IPv6 | +| `password_updated_at` | datetime | 是 | NULL | 最近改密时间 | +| `version_no` | int | 否 | 0 | 乐观锁版本 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 创建时间 | +| `update_time` | datetime | 否 | CURRENT_TIMESTAMP | 更新时间 | + +索引:主键 `id`;唯一 `uk_fin_admin_username(username)`;普通 `idx_fin_admin_role(role, is_active)`;普通 `idx_fin_admin_locked(locked_until)`。 + +#### 4.3.2 `fin_admin_password_history` + +用途:保存最近 3 次密码哈希,校验新密码不得重复。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `admin_id` | bigint unsigned | 否 | — | 管理员 ID | +| `password_hash` | varchar(100) | 否 | — | 历史密码哈希 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 写入时间 | + +索引:主键;普通 `idx_fin_pwd_admin(admin_id, create_time)`。每个管理员保留最近 3 条,写入新密码时异步清理更早记录。 + +#### 4.3.3 `fin_admin_session` + +用途:服务端会话;前端 Bearer token 只存客户端 sessionStorage,服务端只存哈希。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `admin_id` | bigint unsigned | 否 | — | 管理员 | +| `token_hash` | char(64) | 否 | — | token 的 SHA-256 十六进制 | +| `issued_ip` | varchar(45) | 是 | NULL | 签发 IP | +| `user_agent` | varchar(255) | 是 | NULL | UA | +| `last_active_at` | datetime | 否 | CURRENT_TIMESTAMP | 最近活跃时间 | +| `idle_expire_at` | datetime | 否 | — | 空闲过期(last_active + 30 分钟) | +| `absolute_expire_at` | datetime | 否 | — | 绝对过期(登录 + 8 小时) | +| `revoked_at` | datetime | 是 | NULL | 主动登出/改密/停用时间 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 登录时间 | + +索引:主键;唯一 `uk_fin_session_token(token_hash)`;普通 `idx_fin_session_admin(admin_id, revoked_at)`;普通 `idx_fin_session_expire(absolute_expire_at)`。 + +#### 4.3.4 `fin_app` + +用途:接入应用(业务系统)注册信息、跳转白名单、webhook 地址、token TTL。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键(审计目标 ID) | +| `app_code` | varchar(32) | 否 | — | 应用编码,`^[a-z][a-z0-9-]{2,31}$` | +| `app_name` | varchar(64) | 否 | — | 应用名称,≥2 字符 | +| `allowed_redirect_hosts` | varchar(1000) | 否 | — | 逗号分隔精确域名,禁止通配符/IP | +| `webhook_url` | varchar(500) | 是 | NULL | 必须 HTTPS | +| `webhook_secret_enc` | varchar(255) | 否 | — | webhook 签名密钥密文 | +| `token_ttl_seconds` | int | 否 | 900 | 60~86400 | +| `enabled` | tinyint(1) | 否 | 1 | 0 停用并熔断全部 token | +| `secret_expires_at` | datetime | 是 | NULL | 旧密钥宽限截止 | +| `has_prev_secret` | tinyint(1) | 否 | 0 | 是否存在宽限期旧密钥 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 创建时间 | +| `update_time` | datetime | 否 | CURRENT_TIMESTAMP | 更新时间 | + +索引:主键;唯一 `uk_fin_app_code(app_code)`;普通 `idx_fin_app_enabled(enabled)`。 + +#### 4.3.5 `fin_app_secret` + +用途:应用 `client_secret` 历史与宽限期;只存哈希。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `app_code` | varchar(32) | 否 | — | 应用编码 | +| `secret_hash` | char(64) | 否 | — | secret 的 SHA-256(含随机盐的 HMAC 亦可) | +| `secret_prefix` | varchar(12) | 否 | — | 展示前缀,如 `sk_ab12` | +| `status` | varchar(16) | 否 | `ACTIVE` | `ACTIVE`/`GRACE`/`REVOKED` | +| `grace_expire_at` | datetime | 是 | NULL | 宽限截止(0/24/72 小时) | +| `created_by` | bigint unsigned | 是 | NULL | 创建管理员 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 创建时间 | +| `revoked_at` | datetime | 是 | NULL | 回收时间 | + +索引:主键;唯一 `uk_fin_secret_hash(secret_hash)`;普通 `idx_fin_secret_app(app_code, status, grace_expire_at)`。 + +#### 4.3.6 `fin_app_token` + +用途:client token 会话;不透明 token,只存哈希。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `app_code` | varchar(32) | 否 | — | 应用编码 | +| `token_hash` | char(64) | 否 | — | token 的 SHA-256 | +| `token_prefix` | varchar(12) | 否 | — | 前 8 位展示 | +| `issued_ip` | varchar(45) | 是 | NULL | 签发 IP | +| `expires_at` | datetime | 否 | — | 过期时间(默认 15 分钟,按应用 TTL) | +| `revoked_at` | datetime | 是 | NULL | 撤销时间 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 签发时间 | + +索引:主键;唯一 `uk_fin_token_hash(token_hash)`;普通 `idx_fin_token_app(app_code, expires_at)`;普通 `idx_fin_token_revoked(revoked_at)`。 + +#### 4.3.7 `fin_account` + +用途:业务用户在某应用下的钱包账户;余额与累计消耗。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `app_code` | varchar(32) | 否 | — | 应用编码 | +| `business_user_id` | varchar(64) | 否 | — | 业务用户 ID,`^[A-Za-z0-9_-]{1,64}$` | +| `username_snapshot` | varchar(64) | 是 | NULL | 用户名快照 | +| `phone_masked` | varchar(32) | 是 | NULL | 掩码手机号(存储即掩码) | +| `phone_hash` | char(64) | 是 | NULL | 手机号哈希,用于精确检索,不存明文 | +| `balance` | bigint | 否 | 0 | 余额点数,≥0 | +| `total_spent` | bigint | 否 | 0 | 累计消耗点数 | +| `version_no` | int | 否 | 0 | 乐观锁版本 | +| `vip_plan_code` | varchar(32) | 是 | NULL | 当前 VIP 档位编码 | +| `vip_until` | datetime | 是 | NULL | VIP 到期时间 | +| `status` | varchar(16) | 否 | `ACTIVE` | `ACTIVE`/`FROZEN` | +| `first_seen_at` | datetime | 是 | NULL | 首次出现时间 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 创建时间 | +| `update_time` | datetime | 否 | CURRENT_TIMESTAMP | 更新时间 | + +索引:主键;唯一 `uk_fin_account_app_user(app_code, business_user_id)`;普通 `idx_fin_account_balance(app_code, balance)`;普通 `idx_fin_account_phone(phone_hash)`;普通 `idx_fin_account_vip(vip_until)`。约束:`CHECK (balance >= 0)`。 + +#### 4.3.8 `fin_transaction` + +用途:点数账本;每一次余额变化必须有且仅有一条流水,前后余额必须连续。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `app_code` | varchar(32) | 否 | — | 应用编码 | +| `business_user_id` | varchar(64) | 否 | — | 业务用户 ID | +| `username_snapshot` | varchar(64) | 是 | NULL | 用户名快照 | +| `type` | varchar(16) | 否 | — | `RECHARGE`/`CONSUME`/`CONSUME_FREE`/`REFUND_IN`/`REFUND_OUT`/`ADJUST` | +| `amount` | bigint | 否 | — | 变动点数,始终为正;方向由 `type` 决定 | +| `balance_before` | bigint | 否 | — | 变动前余额 | +| `balance_after` | bigint | 否 | — | 变动后余额 | +| `business_ref_id` | varchar(64) | 是 | NULL | 业务引用(扣费任务号/订单号等) | +| `idempotency_key` | varchar(64) | 否 | — | 幂等键 | +| `order_id` | bigint unsigned | 是 | NULL | 关联订单 | +| `out_trade_no` | varchar(40) | 是 | NULL | 关联订单号快照 | +| `refund_of_id` | bigint unsigned | 是 | NULL | 关联退款单 | +| `refunded_points` | bigint | 否 | 0 | 已退回点数(扩展用,默认 0) | +| `operator_admin_id` | bigint unsigned | 是 | NULL | 操作管理员;系统/业务调用为 NULL | +| `operator_admin_name` | varchar(32) | 是 | NULL | 操作人快照 | +| `remark` | varchar(255) | 是 | NULL | 备注;VIP 免扣固定写 `VIP_FREE` | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 发生时间 | + +索引:主键;唯一 `uk_fin_tx_idem(app_code, idempotency_key)`;普通 `idx_fin_tx_account(app_code, business_user_id, create_time)`;普通 `idx_fin_tx_order(order_id)`;普通 `idx_fin_tx_type(type, create_time)`;普通 `idx_fin_tx_ref(business_ref_id)`;普通 `idx_fin_tx_refund(refund_of_id)`。约束:`CHECK (balance_before >= 0 AND balance_after >= 0)`。 + +#### 4.3.9 `fin_order` + +用途:充值/VIP 订单与确认到账状态机。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `out_trade_no` | varchar(40) | 否 | — | 商户订单号,全局唯一 | +| `app_code` | varchar(32) | 否 | — | 应用编码 | +| `business_user_id` | varchar(64) | 否 | — | 业务用户 | +| `username_snapshot` | varchar(64) | 是 | NULL | 用户名快照 | +| `order_type` | varchar(16) | 否 | — | `recharge`/`vip`(小写,与前端一致) | +| `pay_method` | varchar(16) | 否 | `offline` | `offline`/`wechat`/`alipay` | +| `amount_cent` | bigint | 否 | — | 订单金额(分) | +| `points_gained` | bigint | 否 | 0 | 预计/实际到账点数;VIP 订单为 0 | +| `points_per_yuan_snapshot` | int | 否 | — | 下单时兑率快照(点数/元),退款扣回按此快照计算,避免后续调价影响历史订单 | +| `vip_plan_code` | varchar(32) | 是 | NULL | VIP 档位 | +| `status` | varchar(16) | 否 | `PENDING` | `PENDING`/`PAID`/`CANCELLED`/`REFUNDED` | +| `expires_at` | datetime | 否 | — | 待确认超时时间 | +| `paid_at` | datetime | 是 | NULL | 确认到账时间 | +| `confirmed_by_admin_id` | bigint unsigned | 是 | NULL | 确认人 | +| `confirmed_by_admin_name` | varchar(32) | 是 | NULL | 确认人快照 | +| `second_approver_id` | bigint unsigned | 是 | NULL | 第二复核人 | +| `second_approver_name` | varchar(32) | 是 | NULL | 复核人快照 | +| `remark` | varchar(255) | 是 | NULL | 备注/关单原因 | +| `refunded_amount_cent` | bigint | 否 | 0 | 累计已退款金额 | +| `version_no` | int | 否 | 0 | 状态机乐观锁 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 创建时间 | +| `update_time` | datetime | 否 | CURRENT_TIMESTAMP | 更新时间 | + +索引:主键;唯一 `uk_fin_order_no(out_trade_no)`;普通 `idx_fin_order_app(app_code, status, create_time)`;普通 `idx_fin_order_user(app_code, business_user_id)`;普通 `idx_fin_order_paid(paid_at)`;普通 `idx_fin_order_expire(status, expires_at)`。约束:`amount_cent > 0`、`refunded_amount_cent <= amount_cent`。 + +> 前端 `OrderInfo.cashInCent`、`cashOutCent` 为计算字段,来自 `fin_cash_ledger` 聚合;`needDualControl` 由 `fin_app_policy.dual_control_threshold_cent` 与 `amount_cent` 比较得出,均不落库。 + +#### 4.3.10 `fin_cash_ledger` + +用途:现金台账;只记录真实发生的现金流入/流出。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `app_code` | varchar(32) | 否 | — | 应用编码 | +| `order_id` | bigint unsigned | 否 | — | 关联订单 | +| `refund_id` | bigint unsigned | 是 | NULL | 关联退款单(OUT 时必填) | +| `direction` | varchar(4) | 否 | — | `IN`/`OUT` | +| `amount_cent` | bigint | 否 | — | 金额(分) | +| `received_at` | datetime | 否 | — | 实际到账/出账时间 | +| `voucher_no` | varchar(64) | 否 | — | 银行回单/凭证号,≥6 位 | +| `operator_admin_id` | bigint unsigned | 否 | — | 登记人 | +| `operator_admin_name` | varchar(32) | 否 | — | 登记人快照 | +| `remark` | varchar(255) | 是 | NULL | 备注 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 记录时间 | + +索引:主键;唯一 `uk_fin_cash_voucher(order_id, direction, voucher_no)`(防止同一凭证重复登记);普通 `idx_fin_cash_app(app_code, direction, received_at)`;普通 `idx_fin_cash_order(order_id)`;普通 `idx_fin_cash_refund(refund_id)`。 + +#### 4.3.11 `fin_refund` + +用途:现金退款单与复核状态机。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `app_code` | varchar(32) | 否 | — | 应用编码 | +| `business_user_id` | varchar(64) | 否 | — | 业务用户 | +| `username_snapshot` | varchar(64) | 是 | NULL | 用户名快照 | +| `order_id` | bigint unsigned | 否 | — | 原订单 | +| `out_trade_no` | varchar(40) | 否 | — | 原订单号快照 | +| `amount_cent` | bigint | 否 | — | 退款金额(分) | +| `points_deducted` | bigint | 否 | 0 | 扣回点数 | +| `status` | varchar(16) | 否 | `PENDING` | `PENDING`/`COMPLETED`/`REJECTED` | +| `operator_admin_id` | bigint unsigned | 否 | — | 发起人 | +| `operator_admin_name` | varchar(32) | 否 | — | 发起人快照 | +| `reviewer_admin_id` | bigint unsigned | 是 | NULL | 复核人 | +| `reviewer_admin_name` | varchar(32) | 是 | NULL | 复核人快照 | +| `voucher_no` | varchar(64) | 是 | NULL | 退款凭证号,通过复核时必填 | +| `remark` | varchar(255) | 是 | NULL | 退款原因/驳回原因 | +| `idempotency_key` | varchar(64) | 否 | — | 幂等键 | +| `review_time` | datetime | 是 | NULL | 复核时间 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 创建时间 | +| `update_time` | datetime | 否 | CURRENT_TIMESTAMP | 更新时间 | + +索引:主键;唯一 `uk_fin_refund_idem(app_code, idempotency_key)`;普通 `idx_fin_refund_order(order_id)`;普通 `idx_fin_refund_status(status, create_time)`;普通 `idx_fin_refund_app(app_code, create_time)`。 + +#### 4.3.12 `fin_vip_plan` + +用途:按应用隔离的 VIP 档位。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `app_code` | varchar(32) | 否 | — | 应用编码 | +| `plan_code` | varchar(32) | 否 | — | `^[A-Z][A-Z0-9_]{2,31}$` | +| `plan_name` | varchar(64) | 否 | — | 档位名称,≥2 字符 | +| `duration_days` | int | 否 | — | 有效期天数,>0 | +| `price_cent` | bigint | 否 | — | 价格(分),>0 | +| `free_deduction` | tinyint(1) | 否 | 0 | 1 该档位可免扣(与策略 `vip_exempt` 共同生效) | +| `enabled` | tinyint(1) | 否 | 1 | 1 上架 / 0 下架 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 创建时间 | +| `update_time` | datetime | 否 | CURRENT_TIMESTAMP | 更新时间 | + +索引:主键;唯一 `uk_fin_plan_app_code(app_code, plan_code)`;普通 `idx_fin_plan_enabled(app_code, enabled)`。 + +#### 4.3.13 `fin_vip_holder` + +用途:业务用户 VIP 持有;续费按剩余有效期叠加。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `app_code` | varchar(32) | 否 | — | 应用编码 | +| `business_user_id` | varchar(64) | 否 | — | 业务用户 | +| `vip_plan_code` | varchar(32) | 否 | — | 当前档位 | +| `vip_until` | datetime | 否 | — | 到期时间 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 首次开通 | +| `update_time` | datetime | 否 | CURRENT_TIMESTAMP | 更新时间 | + +索引:主键;唯一 `uk_fin_vip_app_user(app_code, business_user_id)`;普通 `idx_fin_vip_until(vip_until)`。 + +> 前端 `VipHolder.id` 为本表主键;`effective` 为 `vip_until > NOW()` 计算字段,不落库。账户表 `vip_plan_code`/`vip_until` 为冗余快照,必须与本节保持一致(同事务更新)。 + +#### 4.3.14 `fin_app_pricing` + +用途:应用兑率(1 元兑换多少点)。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `app_code` | varchar(32) | 否 | — | 应用编码 | +| `points_per_yuan` | bigint | 否 | 100 | 正整数 | +| `enabled` | tinyint(1) | 否 | 1 | 1 启用 | +| `update_by` | varchar(32) | 是 | NULL | 最近修改人 | +| `update_time` | datetime | 否 | CURRENT_TIMESTAMP | 更新时间 | +| `version_no` | int | 否 | 0 | 乐观锁 | + +索引:主键;唯一 `uk_fin_pricing_app(app_code)`。约束:`points_per_yuan > 0`。 + +#### 4.3.15 `fin_app_policy` + +用途:应用扣费策略与双人复核阈值。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `app_code` | varchar(32) | 否 | — | 应用编码 | +| `min_cost` | bigint | 否 | 0 | 保底消费点数,≥0 | +| `max_points_per_charge` | bigint | 否 | 50000 | 单次扣费上限,≥max(1,min_cost) | +| `vip_exempt` | tinyint(1) | 否 | 0 | 1 开启 VIP 免扣 | +| `failed_strategy` | varchar(16) | 否 | `none` | `none`/`actual`,见 §6.9 | +| `dual_control_threshold_cent` | bigint | 否 | 500000 | 双人复核阈值(分),≥0 | +| `enabled` | tinyint(1) | 否 | 1 | 1 启用 | +| `update_by` | varchar(32) | 是 | NULL | 最近修改人 | +| `update_time` | datetime | 否 | CURRENT_TIMESTAMP | 更新时间 | +| `version_no` | int | 否 | 0 | 乐观锁 | + +索引:主键;唯一 `uk_fin_policy_app(app_code)`。约束:`min_cost >= 0`、`max_points_per_charge >= GREATEST(1, min_cost)`、`dual_control_threshold_cent >= 0`。 + +#### 4.3.16 `fin_config` + +用途:全局参数;前端“全局参数”页展示与修改。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `config_key` | varchar(64) | 否 | — | 参数键,唯一 | +| `config_value` | varchar(255) | 否 | — | 参数值(字符串存储,按业务解析) | +| `description` | varchar(255) | 是 | NULL | 说明 | +| `risk` | varchar(8) | 否 | `NORMAL` | `HIGH`/`NORMAL` | +| `update_by` | varchar(32) | 是 | NULL | 修改人 | +| `update_time` | datetime | 否 | CURRENT_TIMESTAMP | 更新时间 | +| `version_no` | int | 否 | 0 | 乐观锁 | + +索引:主键;唯一 `uk_fin_config_key(config_key)`;普通 `idx_fin_config_risk(risk)`。 + +种子数据(与 `mock/db.ts` 一致,值不得为密码/密钥): + +| config_key | 默认值 | risk | 说明 | +| --- | --- | --- | --- | +| `order.pending.timeout_hours` | `24` | NORMAL | 待确认订单超时关单小时数 | +| `review.threshold_cent` | `500000` | NORMAL | 全局双人复核默认阈值(分) | +| `admin.lock.threshold` | `5` | NORMAL | 登录失败锁定次数 | +| `admin.lock.minutes` | `15` | NORMAL | 锁定时长(分钟) | +| `ticket.ttl_minutes` | `5` | NORMAL | 一次性 ticket 有效期(分钟) | +| `token.ttl_seconds` | `900` | NORMAL | client token 默认有效期(秒) | +| `secret.rotate.grace_hours` | `24` | NORMAL | 密钥轮换默认宽限期(小时) | +| `charge.retry.max` | `3` | NORMAL | 扣费乐观锁冲突重试次数 | +| `webhook.max_retry` | `6` | NORMAL | webhook 最大重试次数 | +| `pii.mask.enabled` | `1` | HIGH | PII 掩码开关,**禁止改为 0**(返回 4097) | +| `payee.account_name` | 由部署注入 | NORMAL | 收款户名 | +| `payee.bank_name` | 由部署注入 | NORMAL | 开户行 | +| `payee.account_no_masked` | 由部署注入 | NORMAL | 收款账号掩码展示,完整账号仅存离线文件 | + +#### 4.3.17 `fin_audit_log` + +用途:全量审计;只追加、哈希链、不可改不可删。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键,链顺序 | +| `actor_type` | varchar(8) | 否 | — | `ADMIN`/`SYSTEM`/`BIZ` | +| `actor_id` | bigint unsigned | 是 | NULL | 管理员 ID;系统/业务为 NULL | +| `actor_name` | varchar(64) | 否 | — | 操作者名称 | +| `action` | varchar(64) | 否 | — | 动作码,见 §14.3 | +| `action_label` | varchar(128) | 否 | — | 中文动作描述 | +| `target_type` | varchar(32) | 否 | — | `ADMIN`/`APP`/`ACCOUNT`/`ORDER`/`REFUND`/`PRICING`/`POLICY`/`CONFIG`/`VIP_PLAN`/`WEBHOOK`/`RECONCILE`/`AUDIT`/`TRANSACTION`/`TICKET` | +| `target_id` | bigint unsigned | 是 | NULL | 目标 ID;无具体对象为 NULL | +| `before_json` | json | 是 | NULL | 变更前快照(脱敏后) | +| `after_json` | json | 是 | NULL | 变更后快照(脱敏后) | +| `ip` | varchar(45) | 否 | — | 客户端 IP(经可信代理解析) | +| `ua` | varchar(255) | 是 | NULL | User-Agent | +| `result` | varchar(8) | 否 | `SUCCESS` | `SUCCESS`/`FAILED` | +| `prev_hash` | char(64) | 否 | '' | 上一条 `cur_hash`;首条为空串 | +| `cur_hash` | char(64) | 否 | — | 本条哈希,见 §6.12 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 发生时间 | + +索引:主键;普通 `idx_fin_audit_time(create_time)`;普通 `idx_fin_audit_actor(actor_id, create_time)`;普通 `idx_fin_audit_action(action, create_time)`;普通 `idx_fin_audit_target(target_type, target_id)`;普通 `idx_fin_audit_result(result, create_time)`。 + +数据库权限:应用账号仅 `INSERT`/`SELECT`;**禁止 `UPDATE`/`DELETE`**;归档账号仅 `SELECT`。 + +#### 4.3.18 `fin_webhook_delivery` + +用途:Webhook Outbox 与投递状态。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `app_code` | varchar(32) | 否 | — | 目标应用 | +| `event_id` | varchar(64) | 否 | — | 事件唯一 ID(`evt_` + 32 位) | +| `event_type` | varchar(32) | 否 | — | `order.paid`/`order.refunded` | +| `status` | varchar(16) | 否 | `PENDING` | `PENDING`/`SENT`/`FAILED`/`DEAD` | +| `attempts` | int | 否 | 0 | 已尝试次数 | +| `max_attempts` | int | 否 | 6 | 最大尝试次数(重放时可重置 attempts,max 不变) | +| `next_retry_at` | datetime | 是 | NULL | 下次重试时间 | +| `last_error` | varchar(500) | 是 | NULL | 最近错误(脱敏,不含响应体中的敏感数据) | +| `payload` | json | 否 | — | 事件负载(不含密钥) | +| `signature` | varchar(128) | 是 | NULL | 最近一次签名,便于排障(可选) | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 入队时间 | +| `update_time` | datetime | 否 | CURRENT_TIMESTAMP | 更新时间 | + +索引:主键;唯一 `uk_fin_webhook_event(app_code, event_id, event_type)`(事件幂等);普通 `idx_fin_webhook_due(status, next_retry_at)`;普通 `idx_fin_webhook_app(app_code, create_time)`。 + +#### 4.3.19 `fin_reconcile_report` + +用途:对账报告头;现金侧与点数侧分离。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | varchar(32) | 否 | — | 报告号 `RC{yyyyMMdd}{seq3}` | +| `app_code` | varchar(32) | 否 | — | 应用编码 | +| `window_start` | date | 否 | — | 对账窗口起(含) | +| `window_end` | date | 否 | — | 对账窗口止(含) | +| `snapshot_at` | datetime | 否 | — | 快照时间 | +| `cash_in_cent` | bigint | 否 | 0 | 现金台账 IN 合计 | +| `cash_paid_order_cent` | bigint | 否 | 0 | 已到账订单金额合计 | +| `cash_out_cent` | bigint | 否 | 0 | 现金台账 OUT 合计 | +| `cash_refunded_cent` | bigint | 否 | 0 | 已完成退款金额合计 | +| `cash_diff_cent` | bigint | 否 | 0 | 现金侧差异 | +| `wallet_sum` | bigint | 否 | 0 | 账户余额合计 | +| `computed_sum` | bigint | 否 | 0 | 流水重算余额合计 | +| `points_diff` | bigint | 否 | 0 | 点数侧差异 | +| `broken_chains` | int | 否 | 0 | 断链账户数 | +| `diff_count` | int | 否 | 0 | 差异明细条数 | +| `status` | varchar(16) | 否 | — | `BALANCED`/`DIFF` | +| `created_by` | varchar(32) | 否 | — | 执行人 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 创建时间 | + +索引:主键;普通 `idx_fin_recon_app(app_code, create_time)`;普通 `idx_fin_recon_status(status, create_time)`。 + +#### 4.3.20 `fin_reconcile_diff` + +用途:对账差异明细;只报告,不自动修复。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `report_id` | varchar(32) | 否 | — | 报告号 | +| `level` | varchar(16) | 否 | — | `ORDER`/`SUBJECT`/`APP` | +| `target` | varchar(64) | 否 | — | 差异对象(订单号/用户 ID/应用编码) | +| `expected` | bigint | 否 | 0 | 期望值(金额分或点数) | +| `actual` | bigint | 否 | 0 | 实际值 | +| `diff` | bigint | 否 | 0 | 差异 | +| `reason` | varchar(500) | 否 | — | 差异说明 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 创建时间 | + +索引:主键;普通 `idx_fin_diff_report(report_id, level)`;普通 `idx_fin_diff_target(target)`。 + +#### 4.3.21 `fin_ticket` + +用途:业务系统签发的收银台一次性凭证;只存哈希。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `ticket_hash` | char(64) | 否 | — | ticket 的 SHA-256 | +| `ticket_prefix` | varchar(12) | 否 | — | 展示前缀 | +| `app_code` | varchar(32) | 否 | — | 签发应用 | +| `business_user_id` | varchar(64) | 否 | — | 业务用户 | +| `redirect_uri` | varchar(500) | 是 | NULL | 下单时校验后的跳转地址 | +| `issued_ip` | varchar(45) | 是 | NULL | 签发 IP | +| `expires_at` | datetime | 否 | — | 过期时间(默认 5 分钟) | +| `used_at` | datetime | 是 | NULL | 消费时间;原子置位 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 签发时间 | + +索引:主键;唯一 `uk_fin_ticket_hash(ticket_hash)`;普通 `idx_fin_ticket_app(app_code, expires_at)`;普通 `idx_fin_ticket_used(used_at)`。 + +#### 4.3.22 `fin_rate_limit` + +用途:限流计数降级存储与审计;正常路径优先 Redis。 + +| 字段 | 类型 | 可空 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `id` | bigint unsigned | 否 | — | 主键 | +| `bucket_key` | varchar(128) | 否 | — | 限流桶(如 `login:ip:1.2.3.4`) | +| `window_start` | datetime | 否 | — | 窗口起点(按分钟/5 分钟对齐) | +| `counter` | int | 否 | 0 | 计数 | +| `expire_at` | datetime | 否 | — | 过期清理时间 | +| `create_time` | datetime | 否 | CURRENT_TIMESTAMP | 创建时间 | + +索引:主键;唯一 `uk_fin_rate_bucket(bucket_key, window_start)`;普通 `idx_fin_rate_expire(expire_at)`。 + +### 4.4 关键 DDL 示例 + +#### 4.4.1 `fin_transaction` + +```sql +CREATE TABLE `fin_transaction` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `business_user_id` VARCHAR(64) NOT NULL COMMENT '业务用户ID', + `username_snapshot` VARCHAR(64) DEFAULT NULL COMMENT '用户名快照', + `type` VARCHAR(16) NOT NULL COMMENT 'RECHARGE/CONSUME/CONSUME_FREE/REFUND_IN/REFUND_OUT/ADJUST', + `amount` BIGINT NOT NULL COMMENT '变动点数(正数)', + `balance_before` BIGINT NOT NULL COMMENT '变动前余额', + `balance_after` BIGINT NOT NULL COMMENT '变动后余额', + `business_ref_id` VARCHAR(64) DEFAULT NULL COMMENT '业务引用', + `idempotency_key` VARCHAR(64) NOT NULL COMMENT '幂等键', + `order_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '订单ID', + `out_trade_no` VARCHAR(40) DEFAULT NULL COMMENT '订单号快照', + `refund_of_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '退款单ID', + `refunded_points` BIGINT NOT NULL DEFAULT 0 COMMENT '已退回点数', + `operator_admin_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '操作管理员', + `operator_admin_name` VARCHAR(32) DEFAULT NULL COMMENT '操作人快照', + `remark` VARCHAR(255) DEFAULT NULL COMMENT '备注', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '发生时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_tx_idem` (`app_code`, `idempotency_key`), + KEY `idx_fin_tx_account` (`app_code`, `business_user_id`, `create_time`), + KEY `idx_fin_tx_order` (`order_id`), + KEY `idx_fin_tx_type` (`type`, `create_time`), + KEY `idx_fin_tx_ref` (`business_ref_id`), + KEY `idx_fin_tx_refund` (`refund_of_id`), + CONSTRAINT `ck_fin_tx_balance` CHECK (`balance_before` >= 0 AND `balance_after` >= 0) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='点数流水'; +``` + +#### 4.4.2 `fin_order` + +```sql +CREATE TABLE `fin_order` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `out_trade_no` VARCHAR(40) NOT NULL COMMENT '商户订单号', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `business_user_id` VARCHAR(64) NOT NULL COMMENT '业务用户ID', + `username_snapshot` VARCHAR(64) DEFAULT NULL COMMENT '用户名快照', + `order_type` VARCHAR(16) NOT NULL COMMENT 'recharge/vip', + `pay_method` VARCHAR(16) NOT NULL DEFAULT 'offline' COMMENT 'offline/wechat/alipay', + `amount_cent` BIGINT NOT NULL COMMENT '金额(分)', + `points_gained` BIGINT NOT NULL DEFAULT 0 COMMENT '到账点数', + `vip_plan_code` VARCHAR(32) DEFAULT NULL COMMENT 'VIP档位', + `status` VARCHAR(16) NOT NULL DEFAULT 'PENDING' COMMENT 'PENDING/PAID/CANCELLED/REFUNDED', + `expires_at` DATETIME NOT NULL COMMENT '待确认超时', + `paid_at` DATETIME DEFAULT NULL COMMENT '到账时间', + `confirmed_by_admin_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '确认人', + `confirmed_by_admin_name` VARCHAR(32) DEFAULT NULL COMMENT '确认人快照', + `second_approver_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '第二复核人', + `second_approver_name` VARCHAR(32) DEFAULT NULL COMMENT '复核人快照', + `remark` VARCHAR(255) DEFAULT NULL COMMENT '备注/关单原因', + `refunded_amount_cent` BIGINT NOT NULL DEFAULT 0 COMMENT '累计退款金额', + `version_no` INT NOT NULL DEFAULT 0 COMMENT '乐观锁', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_order_no` (`out_trade_no`), + KEY `idx_fin_order_app` (`app_code`, `status`, `create_time`), + KEY `idx_fin_order_user` (`app_code`, `business_user_id`), + KEY `idx_fin_order_paid` (`paid_at`), + KEY `idx_fin_order_expire` (`status`, `expires_at`), + CONSTRAINT `ck_fin_order_amount` CHECK (`amount_cent` > 0 AND `refunded_amount_cent` <= `amount_cent`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='充值/VIP订单'; +``` + +#### 4.4.3 `fin_audit_log` + +```sql +CREATE TABLE `fin_audit_log` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键(链顺序)', + `actor_type` VARCHAR(8) NOT NULL COMMENT 'ADMIN/SYSTEM/BIZ', + `actor_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '管理员ID', + `actor_name` VARCHAR(64) NOT NULL COMMENT '操作者', + `action` VARCHAR(64) NOT NULL COMMENT '动作码', + `action_label` VARCHAR(128) NOT NULL COMMENT '中文描述', + `target_type` VARCHAR(32) NOT NULL COMMENT '目标类型', + `target_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '目标ID', + `before_json` JSON DEFAULT NULL COMMENT '变更前(脱敏)', + `after_json` JSON DEFAULT NULL COMMENT '变更后(脱敏)', + `ip` VARCHAR(45) NOT NULL COMMENT '客户端IP', + `ua` VARCHAR(255) DEFAULT NULL COMMENT 'User-Agent', + `result` VARCHAR(8) NOT NULL DEFAULT 'SUCCESS' COMMENT 'SUCCESS/FAILED', + `prev_hash` CHAR(64) NOT NULL DEFAULT '' COMMENT '前一条哈希', + `cur_hash` CHAR(64) NOT NULL COMMENT '本条哈希', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + KEY `idx_fin_audit_time` (`create_time`), + KEY `idx_fin_audit_actor` (`actor_id`, `create_time`), + KEY `idx_fin_audit_action` (`action`, `create_time`), + KEY `idx_fin_audit_target` (`target_type`, `target_id`), + KEY `idx_fin_audit_result` (`result`, `create_time`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='审计日志(只追加)'; +``` + +#### 4.4.4 `fin_app_token` + +```sql +CREATE TABLE `fin_app_token` ( + `id` BIGINT UNSIGNED NOT NULL COMMENT '主键', + `app_code` VARCHAR(32) NOT NULL COMMENT '应用编码', + `token_hash` CHAR(64) NOT NULL COMMENT 'token SHA-256', + `token_prefix` VARCHAR(12) NOT NULL COMMENT '展示前缀', + `issued_ip` VARCHAR(45) DEFAULT NULL COMMENT '签发IP', + `expires_at` DATETIME NOT NULL COMMENT '过期时间', + `revoked_at` DATETIME DEFAULT NULL COMMENT '撤销时间', + `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_fin_token_hash` (`token_hash`), + KEY `idx_fin_token_app` (`app_code`, `expires_at`), + KEY `idx_fin_token_revoked` (`revoked_at`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='client token(只存哈希)'; +``` + +--- + +## 5. 接口清单(逐接口契约) + +> 通用:管理端接口均需 `Authorization: Bearer `;下表“错误”只列业务码,完整解释见 §9;未标“审计”的查询接口不写审计,但导出接口必写。 + +### 5.1 认证模块(4 个) + +| # | 方法 | 路径 | 权限 | 请求 | 成功 `data` | 主要错误 | 幂等/审计 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 1 | POST | `/api/admin/login` | 公开 | `{username,password,totp}` | `{token,admin,permissions}` | 422,4011,4012,4021,4022,429 | 非幂等;成功/失败均审计 `LOGIN` | +| 2 | POST | `/api/admin/logout` | `fin:view` | 空 | `null` | 401 | 幂等(重复登出仍成功);审计 `LOGOUT` | +| 3 | GET | `/api/admin/profile` | `fin:view` | 空 | `{admin,permissions}` | 401,4010 | 只读 | +| 4 | POST | `/api/admin/password/change` | `fin:view` | `{oldPassword,newPassword}` | `null` | 401,4013,4014,4015,422 | 非幂等;审计 `PASSWORD_CHANGE` | + +**登录请求字段** + +| 字段 | 类型 | 必填 | 规则 | +| --- | --- | --- | --- | +| `username` | string | 是 | 去首尾空格,3~32 位小写字母/数字/下划线 | +| `password` | string | 是 | 1~128 字符;不得回显、不得落日志 | +| `totp` | string | 是 | 必须 `^\d{6}$` | + +**登录成功响应** + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `token` | string | 不透明会话 token(32 字节随机,base64url),仅此次返回明文 | +| `admin` | object | 见 `AdminInfo`,**不得包含** `password_hash`、`totp_secret_enc` | +| `permissions` | string[] | 按角色计算,必须与 §3.3 完全一致 | + +`AdminInfo` 必含字段:`id, username, role, isActive, mustChangePassword, totpBound, failedAttempts, lockedUntil, lastLoginAt, lastLoginIp, createTime`。`totpBound` 为 boolean,其余时间字段为 `yyyy-MM-dd HH:mm:ss` 或 `null`。 + +**改密规则**:`newPassword` 必须匹配 `^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9])\S{12,64}$`;不得等于当前密码;不得命中最近 3 次历史;成功后 `must_change_password=0`,吊销该管理员除当前会话外的全部会话,并审计。 + +### 5.2 看板模块(3 个) + +| # | 方法 | 路径 | 权限 | 请求 | 成功 `data` | 错误 | 说明 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 5 | GET | `/api/admin/dashboard/summary` | `fin:view` | 空 | `DashboardSummary` | 401,4010 | 实时聚合 | +| 6 | GET | `/api/admin/dashboard/trend` | `fin:view` | 空 | `TrendPoint[]`(14 天) | 401,4010 | 按日聚合 | +| 7 | GET | `/api/admin/dashboard/distribution` | `fin:view` | 空 | `AppDistribution[]` | 401,4010 | 近 30 天按应用 | + +`DashboardSummary` 字段与口径: + +| 字段 | 口径 | +| --- | --- | +| `todayAmountCent` | 今日 `cash_ledger.direction=IN` 合计(按 `received_at`) | +| `todayOrderCount` | 今日 `paid_at` 非空的订单数 | +| `pendingOrderCount` | `status='PENDING'` 且未过期的订单数 | +| `pendingAmountCent` | 上述待确认订单 `amount_cent` 合计 | +| `todayConsumedPoints` | 今日 `type='CONSUME'` 的 `amount` 合计 | +| `pendingRefundCount` | `status='PENDING'` 的退款单数 | +| `totalBalancePoints` | 全部账户 `balance` 合计 | +| `deadWebhookCount` | `status='DEAD'` 的投递数 | +| `diffReportCount` | `status='DIFF'` 的对账报告数 | +| `dualControlThresholdCent` | 全局 `review.threshold_cent`(应用级策略阈值单独在策略页展示) | + +`TrendPoint`:`{date:"MM-DD", amountCent, points, orderCount}`,固定返回最近 14 个自然日(含今日),缺失日期补 0。 + +### 5.3 接入应用模块(8 个) + +| # | 方法 | 路径 | 权限 | 请求 | 成功 `data` | 主要错误 | 幂等/审计 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 8 | GET | `/api/admin/apps` | `fin:view` | 空 | `AppInfo[]` | 401 | 只读 | +| 9 | POST | `/api/admin/apps` | `fin:app:manage` | `AppPayload` | `{app,clientSecret}` | 422,4221,403 | 非幂等;`clientSecret` 仅返回一次;审计 `APP_CREATE` | +| 10 | PUT | `/api/admin/apps/{appCode}` | `fin:app:manage` | `AppPayload` | `AppInfo` | 404,422,403 | 非幂等;审计 `APP_UPDATE` | +| 11 | POST | `/api/admin/apps/{appCode}/secret/rotate` | `fin:app:manage` | `{graceHours}` | `{clientSecret,expiresAt}` | 404,422,403 | 非幂等;审计 `APP_SECRET_ROTATE` | +| 12 | POST | `/api/admin/apps/{appCode}/secret/revoke-prev` | `fin:app:manage` | 空 | `null` | 404,422,403 | 幂等;审计 `APP_SECRET_REVOKE_PREV` | +| 13 | POST | `/api/admin/apps/{appCode}/toggle` | `fin:app:manage` | `{enabled}` | `AppInfo` | 404,403 | 幂等;停用即熔断 token;审计 `APP_TOGGLE` | +| 14 | GET | `/api/admin/apps/{appCode}/tokens` | `fin:view` | 空 | `AppTokenInfo[]` | 404,401 | 只读;按 createTime 倒序 | +| 15 | POST | `/api/admin/apps/{appCode}/tokens/revoke` | `fin:app:manage` | `{tokenId?}` | `{revoked}` | 404,403 | 幂等(已撤销不重复计数);审计 `APP_TOKEN_REVOKE` | + +**`AppPayload` 字段** + +| 字段 | 类型 | 创建必填 | 更新 | 规则 | +| --- | --- | --- | --- | --- | +| `appCode` | string | 是 | 忽略(不可变) | `^[a-z][a-z0-9-]{2,31}$` | +| `appName` | string | 是 | 可选 | ≥2 字符,≤64 | +| `allowedRedirectHosts` | string | 是 | 是 | 逗号分隔;每项必须匹配 §6.3 白名单规则 | +| `webhookUrl` | string | 否 | 是 | 空或 `https://` 开头,≤500 | +| `tokenTtlSeconds` | number | 否 | 否 | 60~86400,默认 900 | + +**`AppInfo` 必含字段**:`appCode, appName, allowedRedirectHosts, webhookUrl, tokenTtlSeconds, enabled, secretExpiresAt, hasPrevSecret, createTime, accountCount, todayAmountCent`。其中 `accountCount`、`todayAmountCent` 为实时聚合;`secretExpiresAt` 为旧密钥宽限截止或 `null`。 + +**密钥轮换返回**:`clientSecret` 只在本次响应出现,禁止落库明文、禁止写日志;`expiresAt` 为旧密钥宽限截止(`graceHours=0` 时旧密钥立即失效,返回当前新密钥的 `null` 或当前时间,按前端仅展示处理)。 + +**token 列表**:`AppTokenInfo` 含 `id, appCode, tokenPrefix, expiresAt, revokedAt, issuedIp, createTime`;禁止返回 `tokenHash`。 + +### 5.4 账户模块(4 个) + +| # | 方法 | 路径 | 权限 | 请求 | 成功 `data` | 主要错误 | 幂等/审计 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 16 | GET | `/api/admin/accounts` | `fin:view` | `page,pageSize,appCode,keyword,minBalance` | `PageResult` | 401,422 | 只读;按余额倒序 | +| 17 | GET | `/api/admin/accounts/{id}` | `fin:view` | 空 | `AccountDetail` | 404,401 | 只读;最近 10 条流水倒序 | +| 18 | GET | `/api/admin/accounts/{id}/transactions` | `fin:view` | `page,pageSize` | `PageResult` | 404,401 | 只读 | +| 19 | POST | `/api/admin/accounts/adjust` | `fin:account:adjust` | `AdjustPayload` | `AccountInfo` | 422,4022,404,4095,6003,6006 | 非幂等;审计 `ACCOUNT_ADJUST` | + +`AccountInfo` 必含:`id, appCode, appName, businessUserId, usernameSnapshot, phoneMasked, balance, totalSpent, versionNo, vipPlanCode, vipUntil, createTime, updateTime`。`appName` 由 `fin_app` 关联返回;`phoneMasked` 只能是掩码值。 + +`AccountDetail`:`{account:AccountInfo, vip:{planCode,planName,vipUntil,effective,freeDeduction}|null, transactions:TransactionInfo[]}`;`effective = vipUntil > NOW()`。 + +`AdjustPayload` 字段与规则: + +| 字段 | 类型 | 必填 | 规则 | +| --- | --- | --- | --- | +| `appCode` | string | 是 | 应用必须存在 | +| `businessUserId` | string | 是 | `^[A-Za-z0-9_-]{1,64}$`,账户必须存在 | +| `amount` | number | 是 | 正整数,≤ 1,000,000,000 | +| `direction` | `IN`/`OUT` | 是 | `OUT` 时扣减后余额不得为负 | +| `reason` | string | 是 | 去空格后 ≥5 字,≤255 | +| `secondApproverId` | number | 是 | 启用状态、角色为 SUPER_ADMIN/FINANCE、且 ≠ 当前登录人 | +| `totp` | string | 是 | 6 位,校验并防重放 | + +### 5.5 订单模块(6 个) + +| # | 方法 | 路径 | 权限 | 请求 | 成功 `data` | 主要错误 | 幂等/审计 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 20 | GET | `/api/admin/orders` | `fin:view` | `page,pageSize,appCode,status,orderType,keyword,from,to` | `PageResult` | 401,422 | 只读;按 createTime 倒序 | +| 21 | GET | `/api/admin/orders/export` | `fin:export` | 同列表(忽略分页) | `OrderInfo[]`(≤10000) | 401,422,429 | 审计 `ORDER_EXPORT` | +| 22 | GET | `/api/admin/orders/{id}` | `fin:view` | 空 | `{order,refunds,cashFlows}` | 404,401 | 只读 | +| 23 | POST | `/api/admin/orders/{id}/confirm` | `fin:recharge:confirm` | `{voucherNo,receiveAt?,secondApproverId?,totp}` | `OrderInfo` | 404,4093,4094,4095,422,4022,429 | 状态机防重;审计 `ORDER_CONFIRM` | +| 24 | POST | `/api/admin/orders/{id}/cancel` | `fin:order:cancel` | `{reason,totp}` | `OrderInfo` | 404,4093,422,4022 | 状态机防重;审计 `ORDER_CANCEL` | +| 25 | GET | `/api/admin/approvers` | `fin:recharge:confirm` OR `fin:refund:review` OR `fin:account:adjust` | 空 | `Approver[]` | 401,403 | 只读;排除自己 | + +**确认到账字段** + +| 字段 | 类型 | 必填 | 规则 | +| --- | --- | --- | --- | +| `voucherNo` | string | 是 | 去空格 ≥6 位,≤64;同一订单同方向不得重复 | +| `receiveAt` | string | 否 | `yyyy-MM-dd HH:mm:ss`;缺省用服务端当前时间;不得晚于当前时间 +5 分钟 | +| `secondApproverId` | number | 条件 | 订单金额 ≥ 应用策略阈值时必填;≠ 确认人;启用且角色为 SUPER_ADMIN/FINANCE | +| `totp` | string | 是 | 6 位,校验并防重放 | + +**`OrderInfo` 必含字段**:`id, outTradeNo, appCode, appName, businessUserId, usernameSnapshot, orderType, payMethod, amountCent, pointsGained, vipPlanCode, status, expiresAt, paidAt, confirmedByAdminId, confirmedByAdminName, secondApproverId, secondApproverName, remark, createTime, refundedAmountCent, cashInCent, cashOutCent, needDualControl`。 + +**订单详情 `cashFlows`**:`{id,direction,amountCent,receivedAt,voucherNo,remark}`,按时间倒序。 + +**关单**:仅 `PENDING` 可关;`reason` ≥5 字;写入 `remark`;不写现金台账、不写流水、不发 webhook;审计。 + +**审批人**:返回 `{id,username,role}`,仅 `is_active=1` 且角色为 SUPER_ADMIN/FINANCE,排除当前登录人;按 username 升序。 + +### 5.6 退款模块(3 个) + +| # | 方法 | 路径 | 权限 | 请求 | 成功 `data` | 主要错误 | 幂等/审计 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 26 | GET | `/api/admin/refunds` | `fin:view` | `page,pageSize,appCode,status,keyword,from,to` | `PageResult` | 401,422 | 只读 | +| 27 | POST | `/api/admin/refunds` | `fin:refund:create` | `{orderId,amountCent,voucherNo?,reason,idempotencyKey,totp}` | `RefundInfo` | 4091,4022,422,404,4093,6004,6006,429 | 幂等键唯一;审计 `REFUND_CREATE` | +| 28 | POST | `/api/admin/refunds/{id}/review` | `fin:refund:review` | `{action,voucherNo?,reason?,totp}` | `RefundInfo` | 404,4093,4095,4022,422,6006 | 状态机防重;审计 `REFUND_REVIEW` | + +**发起退款字段** + +| 字段 | 类型 | 必填 | 规则 | +| --- | --- | --- | --- | +| `orderId` | number | 是 | 原订单存在且 `status in (PAID, REFUNDED)` | +| `amountCent` | number | 是 | 正整数;≤ 订单金额 − 已退金额(不含 REJECTED) | +| `voucherNo` | string | 否 | 空或 ≥6 位;为空时待复核补登 | +| `reason` | string | 是 | ≥5 字,≤255 | +| `idempotencyKey` | string | 是 | `^[A-Za-z0-9:_-]{8,64}$` | +| `totp` | string | 是 | 6 位,防重放 | + +**复核字段** + +| 字段 | 类型 | 必填 | 规则 | +| --- | --- | --- | --- | +| `action` | `approve`/`reject` | 是 | 其他值 422 | +| `voucherNo` | string | approve 必填 | ≥6 位 | +| `reason` | string | reject 必填 | ≥5 字,≤255 | +| `totp` | string | 是 | 6 位,防重放 | + +**`RefundInfo` 必含字段**:`id, appCode, appName, businessUserId, usernameSnapshot, orderId, outTradeNo, amountCent, pointsDeducted, status, operatorAdminId, operatorAdminName, reviewerAdminId, reviewerAdminName, voucherNo, remark, createTime, updateTime`。 + +### 5.7 流水模块(2 个) + +| # | 方法 | 路径 | 权限 | 请求 | 成功 `data` | 主要错误 | 幂等/审计 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 29 | GET | `/api/admin/transactions` | `fin:view` | `page,pageSize,appCode,type,keyword,from,to` | `PageResult` | 401,422 | 只读;按 createTime 倒序 | +| 30 | GET | `/api/admin/transactions/export` | `fin:export` | 同上(忽略分页) | `TransactionInfo[]`(≤10000) | 401,422,429 | 审计 `TRANSACTION_EXPORT` | + +`keyword` 匹配:`business_user_id`、`username_snapshot`、`idempotency_key`、`business_ref_id`(大小写不敏感包含)。 + +### 5.8 VIP 模块(5 个) + +| # | 方法 | 路径 | 权限 | 请求 | 成功 `data` | 主要错误 | 幂等/审计 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 31 | GET | `/api/admin/vip-plans` | `fin:view` | `appCode?` | `VipPlan[]` | 401 | 只读;含 holderCount | +| 32 | POST | `/api/admin/vip-plans` | `fin:vip:manage` | `VipPlanPayload`(无 totp) | `VipPlan` | 422,4221,404 | 非幂等;审计 `VIP_PLAN_CREATE` | +| 33 | PUT | `/api/admin/vip-plans/{id}` | `fin:vip:manage` | `VipPlanPayload` + `totp` | `VipPlan` | 404,422,4022 | 非幂等;审计 `VIP_PLAN_UPDATE` | +| 34 | POST | `/api/admin/vip-plans/{id}/toggle` | `fin:vip:manage` | `{enabled}` | `VipPlan` | 404,422 | 幂等;审计 `VIP_PLAN_TOGGLE` | +| 35 | GET | `/api/admin/vips` | `fin:view` | `page,pageSize,appCode,keyword` | `PageResult` | 401,422 | 只读;按 vipUntil 倒序 | + +`VipPlanPayload`: + +| 字段 | 类型 | 创建 | 更新 | 规则 | +| --- | --- | --- | --- | --- | +| `appCode` | string | 是 | 是 | 应用必须存在 | +| `planCode` | string | 是 | 是 | `^[A-Z][A-Z0-9_]{2,31}$`;同应用下唯一 | +| `planName` | string | 是 | 是 | ≥2 字,≤64 | +| `durationDays` | number | 是 | 是 | 正整数,1~3650 | +| `priceCent` | number | 是 | 是 | 正整数,1~100,000,000 | +| `freeDeduction` | 0/1 | 否 | 否 | 默认 0 | +| `totp` | string | 否 | 是 | 创建不校验(前端未传);更新必填 | + +`VipPlan` 必含:`id, appCode, appName, planCode, planName, durationDays, priceCent, freeDeduction, enabled, holderCount, createTime`。`holderCount` = 当前 `vip_until > NOW()` 且同档位的持有数。 +`VipHolder` 必含:`id, appCode, appName, businessUserId, usernameSnapshot, vipPlanCode, vipUntil, effective`。 + +### 5.9 计费与策略模块(4 个) + +| # | 方法 | 路径 | 权限 | 请求 | 成功 `data` | 主要错误 | 幂等/审计 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 36 | GET | `/api/admin/pricing` | `fin:view` | 空 | `PricingItem[]` | 401 | 只读 | +| 37 | PUT | `/api/admin/pricing/{appCode}` | `fin:pricing:edit` | `{pointsPerYuan,enabled,totp}` | `PricingItem` | 404,422,4022 | 非幂等;审计 `PRICING_UPDATE` | +| 38 | GET | `/api/admin/policies` | `fin:view` | 空 | `AppPolicy[]` | 401 | 只读 | +| 39 | PUT | `/api/admin/policies/{appCode}` | `fin:pricing:edit` | `{minCost,maxPointsPerCharge,vipExempt,failedStrategy,dualControlThresholdCent,totp}` | `AppPolicy` | 404,422,4022 | 非幂等;审计 `POLICY_UPDATE` | + +校验: + +| 字段 | 规则 | +| --- | --- | +| `pointsPerYuan` | 正整数,1~1,000,000 | +| `minCost` | 非负整数,≤1,000,000 | +| `maxPointsPerCharge` | 正整数,≥max(1,minCost),≤10,000,000 | +| `vipExempt` | 0/1 | +| `failedStrategy` | `none`/`actual` | +| `dualControlThresholdCent` | 非负整数,≤100,000,000,000 | +| `totp` | 6 位,防重放 | + +`PricingItem`:`appCode, appName, pointsPerYuan, enabled, updateTime`。 +`AppPolicy`:`appCode, appName, minCost, maxPointsPerCharge, vipExempt, failedStrategy, dualControlThresholdCent, enabled, updateTime`。 + +### 5.10 对账模块(3 个) + +| # | 方法 | 路径 | 权限 | 请求 | 成功 `data` | 主要错误 | 幂等/审计 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 40 | GET | `/api/admin/reconcile/reports` | `fin:view` | 空 | `ReconcileReport[]`(`details=[]`) | 401 | 只读;按 createTime 倒序 | +| 41 | GET | `/api/admin/reconcile/reports/{id}` | `fin:view` | 空 | `ReconcileReport`(含 details) | 404,401 | 只读 | +| 42 | POST | `/api/admin/reconcile/run` | `fin:reconcile:run` | `{appCode,windowStart,windowEnd}` | `ReconcileReport` | 422,404,429 | 非幂等;审计 `RECONCILE_RUN` | + +校验:`appCode` 必填且存在;日期 `yyyy-MM-dd`;`windowStart ≤ windowEnd`;窗口跨度 ≤366 天;同一应用同一窗口允许重复执行,生成新报告号,不覆盖旧报告。 + +### 5.11 管理员模块(6 个) + +| # | 方法 | 路径 | 权限 | 请求 | 成功 `data` | 主要错误 | 幂等/审计 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 43 | GET | `/api/admin/admins` | `fin:admin:manage` | 空 | `AdminInfo[]` | 401,403 | 只读 | +| 44 | POST | `/api/admin/admins` | `fin:admin:manage` | `{username,role,totp}` | `{admin,initialPassword}` | 422,4221,4022 | 非幂等;审计 `ADMIN_CREATE` | +| 45 | PUT | `/api/admin/admins/{id}` | `fin:admin:manage` | `{role}` | `AdminInfo` | 404,422,4096 | 非幂等;审计 `ADMIN_UPDATE_ROLE` | +| 46 | POST | `/api/admin/admins/{id}/toggle` | `fin:admin:manage` | `{enabled}` | `AdminInfo` | 404,4096 | 幂等;停用即吊销会话;审计 `ADMIN_TOGGLE` | +| 47 | POST | `/api/admin/admins/{id}/reset-password` | `fin:admin:manage` | `{totp}` | `{tempPassword}` | 404,4022 | 非幂等;审计 `ADMIN_RESET_PASSWORD` | +| 48 | POST | `/api/admin/admins/{id}/reset-totp` | `fin:admin:manage` | `{totp}` | `{message}` | 404,4022 | 非幂等;审计 `ADMIN_RESET_TOTP` | + +规则: + +- `username`:`^[a-z][a-z0-9_]{2,31}$`,全局唯一,4221。 +- `role`:三角色之一,422。 +- 创建时生成一次性初始密码(≥12 位,满足密码策略),仅本次返回;`must_change_password=1`;`totp_bound=0`。 +- 降级/停用最后一名启用状态的 SUPER_ADMIN → 4096;停用自己 → 4096。 +- 重置密码:生成临时密码,仅本次返回;清空失败计数与锁定;吊销该管理员全部会话;`must_change_password=1`。 +- 重置 TOTP:`totp_bound=0`,清除 `totp_secret_enc`;下次登录需重新绑定(前端无绑定页,见 §1.3 限制与 §6.1 处理约定)。 + +### 5.12 审计模块(4 个) + +| # | 方法 | 路径 | 权限 | 请求 | 成功 `data` | 主要错误 | 幂等/审计 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 49 | GET | `/api/admin/audit-logs` | `fin:audit:view` | `page,pageSize,actor,action,result,keyword,from,to` | `PageResult` | 401,403,422 | 只读;按 createTime 倒序 | +| 50 | GET | `/api/admin/audit-logs/export` | `fin:export` | 同上(忽略分页) | `AuditLog[]`(≤10000) | 401,403,429 | 审计 `AUDIT_EXPORT` | +| 51 | GET | `/api/admin/audit-logs/{id}` | `fin:audit:view` | 空 | `AuditLog` | 404,403 | 只读 | +| 52 | POST | `/api/admin/audit-logs/verify` | `fin:audit:view` | 空 | `ChainVerifyResult` | 401,403 | 只读校验;追加 `AUDIT_CHAIN_VERIFY` | + +**路由匹配顺序**:`/export`、`/verify` 必须注册在 `/{id}` 之前,否则被参数路由抢占(前端 mock 已踩坑,后端同样需要注意)。 + +`AuditLog` 必含:`id, actorType, actorId, actorName, action, actionLabel, targetType, targetId, beforeJson, afterJson, ip, ua, result, prevHash, curHash, createTime`。 +`ChainVerifyResult`:`{valid, checked, brokenAtId, checkedAt, message}`。 + +### 5.13 全局参数模块(2 个) + +| # | 方法 | 路径 | 权限 | 请求 | 成功 `data` | 主要错误 | 幂等/审计 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 53 | GET | `/api/admin/configs` | `fin:view` | 空 | `ConfigItem[]` | 401 | 只读 | +| 54 | PUT | `/api/admin/configs/{key}` | `fin:config:edit` | `{value,reason,totp}` | `ConfigItem` | 404,422,4022,4097 | 非幂等;审计 `CONFIG_UPDATE` | + +`ConfigItem`:`configKey, configValue, description, risk, updateBy, updateTime`。 +`key` 为 URL 编码的配置键(如 `order.pending.timeout_hours`);`value` 1~255 字符;`reason` ≥5 字;`pii.mask.enabled` 仅允许 `1`,传 `0` 返回 4097。 + +### 5.14 Webhook 模块(2 个) + +| # | 方法 | 路径 | 权限 | 请求 | 成功 `data` | 主要错误 | 幂等/审计 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 55 | GET | `/api/admin/webhooks` | `fin:view` | `page,pageSize,appCode,status,keyword,from,to` | `PageResult` | 401,422 | 只读;按 createTime 倒序 | +| 56 | POST | `/api/admin/webhooks/{id}/replay` | `fin:webhook:manage` | `{totp}` | `WebhookDelivery` | 404,422,4022 | 非幂等(每次重放入队一次);审计 `WEBHOOK_REPLAY` | + +仅 `FAILED`/`DEAD` 可重放,其他状态 422;重放将 `status='PENDING'`、`attempts=0`、`next_retry_at=NOW()`、`last_error=''`;`event_id` 不变(下游按 event_id 幂等)。 + +`WebhookDelivery` 必含:`id, appCode, appName, eventId, eventType, status, attempts, nextRetryAt, lastError, payload, createTime, updateTime`。`payload` 为 JSON 字符串(前端直接展示),不得包含密钥。 + +### 5.15 公开收银台(4 个) + +| # | 方法 | 路径 | 权限 | 请求 | 成功 `data` | 主要错误 | 说明 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 57 | GET | `/api/pay/preview` | 公开 | `appCode,ticket,redirectUri?` | `PayPreview` | 7001,4003,400,404,429 | 校验 ticket,不消费 | +| 58 | POST | `/api/pay/orders` | 公开 | `{appCode,ticket,orderType,amountCent?,planCode?,redirectUri?}` | `PayOrder` | 422,4001,7001,4003,400,429 | 原子消费 ticket 并下单 | +| 59 | GET | `/api/pay/orders/{outTradeNo}/status` | 公开 | 空 | `PayStatus` | 404,429 | 轮询;订单号不可枚举 | +| 60 | GET | `/api/pay/demo-ticket` | **仅非生产** | `appCode?` | `DemoTicket` | 404,403 | 生产必须关闭(404) | + +**`PayPreview` 必含**:`appCode, appName, businessUserId, usernameSnapshot, balance, pointsPerYuan, minAmountCent, vip:null|{planCode,planName,vipUntil,freeDeduction}, plans:[{planCode,planName,durationDays,priceCent,freeDeduction}], ticketExpiresAt`。`minAmountCent` 固定 100(1 元)。 + +**下单请求** + +| 字段 | 类型 | 必填 | 规则 | +| --- | --- | --- | --- | +| `appCode` | string | 是 | 与 ticket 绑定应用一致 | +| `ticket` | string | 是 | 一次性凭证 | +| `orderType` | `recharge`/`vip` | 是 | 其他 422 | +| `amountCent` | number | recharge 必填 | 整数,100~5,000,000(1~50000 元) | +| `planCode` | string | vip 必填 | 同应用、上架档位 | +| `redirectUri` | string | 否 | 命中白名单且 HTTPS(localhost 例外) | + +**`PayOrder` 必含**:`outTradeNo, amountCent, pointsGained, orderType, vipPlanCode, status, expiresAt, payee:{accountName,bankName,accountNo}, redirectUri, createTime`。`payee` 来自 `fin_config` 的 `payee.*`,账号必须为掩码。 +**`PayStatus` 必含**:`outTradeNo, status, amountCent, pointsGained, paidAt, expiresAt`。 +**`DemoTicket`**:`appCode, ticket, businessUserId, username, redirectUri, expiresAt`;仅 `payment.demo.enabled=true` 且非 `prod` 时可用;生产环境必须返回 404,且不得注册路由。 + +### 5.16 开放 API 与运维接口(4 个) + +| # | 方法 | 路径 | 认证 | 请求 | 成功 `data` | 主要错误 | +| --- | --- | --- | --- | --- | --- | --- | +| 61 | POST | `/api/open/v1/token` | `client_id` + `client_secret`(HTTP Basic 或 body) | `{clientId,clientSecret,grantType:"client_credentials"}` | `{accessToken,tokenType:"Bearer",expiresIn,appCode}` | 4011,4012,4003,429 | +| 62 | POST | `/api/open/v1/charge` | `Authorization: Bearer ` | `{businessUserId,points,businessRefId,idempotencyKey,occurredAt?,remark?}` | `ChargeResult` | 4010,4003,422,6001,6002,6003,4091,4092,429 | +| 63 | POST | `/api/open/v1/tickets` | client token | `{businessUserId,redirectUri?,ttlSeconds?}` | `{ticket,expiresAt,redirectUri}` | 4010,4003,422,429 | +| 64 | GET | `/api/health` | 公开 | 空 | `{status:"UP",version,time}` | 503(仅返回组件名,不返回连接串) | + +**扣费 `ChargeResult` 字段** + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `transactionId` | number | 流水 ID | +| `businessUserId` | string | 业务用户 | +| `type` | string | `CONSUME`/`CONSUME_FREE` | +| `requestedPoints` | number | 请求点数 | +| `chargedPoints` | number | 实际扣除点数 | +| `balanceBefore` | number | 扣前余额 | +| `balanceAfter` | number | 扣后余额 | +| `vipExempt` | boolean | 是否 VIP 免扣 | +| `insufficient` | boolean | 是否余额不足(`actual` 策略下可能部分扣费) | +| `idempotentReplay` | boolean | 是否命中幂等返回首次结果 | +| `createTime` | string | 发生时间 | + +**ticket 签发**:`ticket` 明文仅在本次响应返回;`ttlSeconds` 限制 60~300,默认取 `ticket.ttl_minutes`;`redirectUri` 可选,若传必须通过白名单校验并存储于 `fin_ticket`。 + +--- + +## 6. 核心业务规则(逐条可执行) + +### 6.1 认证与会话 + +| # | 规则 | 落地要求 | +| --- | --- | --- | +| A1 | 用户名 + 密码 + TOTP 三要素 | 缺一不可;TOTP 必须是 6 位数字 | +| A2 | 密码哈希 | Argon2id(memory≥64MB、iterations≥3、parallelism=1)或 BCrypt(cost≥12);禁止 MD5/SHA1/可逆加密 | +| A3 | 连续失败锁定 | 同一账号连续 5 次密码/ TOTP 失败 → 锁定 15 分钟;锁定期间即使凭证正确也返回 4021;成功登录清零 | +| A4 | 防枚举 | 用户不存在与密码错误统一 4011;只有“用户名存在且密码正确但账号停用”才返回 4012;响应耗时应接近(密码哈希照常执行) | +| A5 | 密码策略 | ≥12 位、含大写/小写/数字/符号、无空格与中文(`^[\x21-\x7e]+$`);不得等于当前密码,不得命中最近 3 次历史 | +| A6 | 强制改密 | `must_change_password=1` 时,除 `/admin/profile`、`/admin/password/change`、`/admin/logout` 外,其他管理接口返回 **4016**(需先修改初始密码),且不返回任何业务数据(前端路由已强制跳 `/password`,该码为服务端兜底) | +| A7 | 会话空闲 | 30 分钟无请求 → 失效;每次请求滑动 `last_active_at`(最多每 60 秒写一次 Redis/DB) | +| A8 | 会话绝对上限 | 登录后 8 小时强制失效,不因活跃而延长 | +| A9 | 退出即失效 | 登出立即删除/标记会话;token 哈希不匹配、已撤销、已过期均返回 4010 | +| A10 | 改密/停用/重置 | 吊销目标管理员全部会话(当前改密会话可保留,其他会话必须失效) | +| A11 | TOTP 校验 | RFC 6238,SHA1,6 位,30 秒步长,允许 ±1 步;同一管理员同一 6 位码 90 秒内只能使用一次(Redis `totp:used:{adminId}:{code}`),重放返回 4022 | +| A12 | TOTP 绑定 | `totp_bound=0` 时仍使用已预置密钥校验;首次成功登录后置 1。因前端无绑定页面,初始密钥必须由运维通过一次性安全通道交付,接口不得返回明文 | +| A13 | 登录审计 | 成功、失败、锁定、解锁均写审计;失败审计含 IP/UA,不记录密码与 TOTP | +| A14 | 登录限流 | 同一用户名 5 次/5 分钟,同一 IP 20 次/5 分钟;超限 429,不区分账号是否存在 | + +失败次数口径:密码错误、TOTP 错误都计入;TOTP 格式错误(非 6 位)不计入;锁定到期后 `failed_attempts` 重置为 0(避免第 6 次直接再锁)。 + +### 6.2 服务端接入(应用 / secret / client token) + +| # | 规则 | 落地要求 | +| --- | --- | --- | +| B1 | secret 只存哈希 | `client_secret` 生成 32 字节随机,返回一次;DB 存 SHA-256(建议 HMAC-SHA256 + 服务端固定盐);禁止明文、禁止日志 | +| B2 | secret 轮换 | 新 secret 置 `ACTIVE`;旧 secret 置 `GRACE`,`grace_expire_at = NOW() + graceHours`;宽限期仅允许 0/24/72 小时,其他值 422 | +| B3 | 立即回收旧密钥 | `revoke-prev` 将 `GRACE` 置 `REVOKED`,`has_prev_secret=0`;无旧密钥返回 422 | +| B4 | token 不透明 | token 为 32 字节随机 base64url,前缀 `ct_`;DB 只存 SHA-256;返回一次,前端/业务系统自行保存 | +| B5 | token TTL | 默认 15 分钟(900 秒),按应用 `token_ttl_seconds`;签发时 `expires_at = NOW() + TTL` | +| B6 | 单条撤销 | `tokenId` 指定则只撤销该条;不存在或不属于该应用返回 404 | +| B7 | 全量撤销 | `tokenId` 为空时撤销该应用所有未撤销 token,返回 `revoked` 数量 | +| B8 | 停用应用熔断 | `enabled=0` 时立即撤销该应用全部 token;此后签发/扣费/下单全部 4003 | +| B9 | 无有效 token 拒绝 | 扣费、签发 ticket 必须校验 token 哈希、未过期、未撤销、应用启用;任一失败 4010/4003 | +| B10 | 并发安全 | 撤销与校验使用同一条记录状态;校验时 `revoked_at IS NULL AND expires_at > NOW()` | + +### 6.3 一次性 ticket + +| # | 规则 | 落地要求 | +| --- | --- | --- | +| C1 | 只存哈希 | ticket 明文 `tk_` + 32 字节随机,仅签发响应返回一次;DB 存 SHA-256 | +| C2 | 有效期 5 分钟 | 默认 `ticket.ttl_minutes=5`;签发时写 `expires_at` | +| C3 | 原子消费 | `UPDATE fin_ticket SET used_at=NOW() WHERE ticket_hash=? AND app_code=? AND used_at IS NULL AND expires_at>NOW()`;影响行数必须为 1 | +| C4 | 重放拒绝 | 已使用/过期/应用不匹配/不存在统一 7001,不区分原因 | +| C5 | 事务边界 | 校验参数 → 消费 ticket → 创建订单,三步在同一事务;创建失败回滚 `used_at`,ticket 仍可用 | +| C6 | 预览不消费 | `preview` 只校验不置 `used_at`;用户可多次刷新 | +| C7 | 白名单校验 | `redirectUri` 解析后取 `hostname`,必须与 `allowed_redirect_hosts` 某一项完全相等;禁止通配符、IP 直连、`@`、端口;外部必须 `https://`,仅 `http://localhost`、`http://127.0.0.1` 例外 | +| C8 | 开放重定向防护 | 拒绝 `//evil.com`、`https://allowed.com.evil.com`、`https://allowed.com@evil.com`、大小写/尾点混淆;只比较规范化后的 hostname | +| C9 | 签发限流 | 每应用 120 次/分钟;预览 60 次/分钟/IP;下单 10 次/分钟/IP | +| C10 | 清理 | 过期 24 小时后的 ticket 可归档/删除(仅限未使用且已过期) | + +### 6.4 账户与流水 + +| # | 规则 | +| --- | --- | +| D1 | 所有余额变更必须“账户行锁或乐观锁 + 写一条流水”在同一数据库事务内完成;禁止先改余额后补流水 | +| D2 | 余额不得为负:`balance_after >= 0`;数据库 `CHECK` + 应用判断双保险 | +| D3 | 流水必须记录 `balance_before`、`balance_after`,且 `balance_before` 等于该账户上一条流水的 `balance_after`(首条为 0) | +| D4 | 幂等键 `(app_code, idempotency_key)` 唯一;重复请求返回首次结果或 4091,禁止重复扣/加 | +| D5 | 并发更新:`SELECT ... FOR UPDATE` 锁账户行;或 `UPDATE ... SET balance=?, version_no=version_no+1 WHERE id=? AND version_no=?`,影响 0 行则重试,最多 `charge.retry.max=3` 次,仍失败返回 4092 | +| D6 | `CONSUME` 时 `total_spent += amount`;`REFUND_OUT`/调减不减少 `total_spent`(累计消耗为历史口径) | +| D7 | `CONSUME_FREE` 金额 0、余额不变,但仍写流水,`remark='VIP_FREE'`;不增加 `total_spent` | +| D8 | `ADJUST` 金额为正,方向由前后余额体现;`operator_admin_id` 必须填写 | +| D9 | 流水不可修改、不可删除;冲正只能通过反向流水(如 `REFUND_IN`/调账)实现 | +| D10 | 账户唯一键 `(app_code, business_user_id)`;并发首次开户用 `INSERT ... ON DUPLICATE KEY UPDATE id=id` 后重查 | + +### 6.5 充值订单 + +| # | 规则 | +| --- | --- | +| E1 | 下单:校验 ticket → 金额/档位 → 计算 `points_gained`(`floor(amountCent/100 * pointsPerYuan)`)→ 创建 `PENDING` 订单 → 记录兑率快照 → 消费 ticket → 返回收款信息 | +| E2 | 订单号:`RC{yyyyMMdd}{5 位序列}`(充值)或 `VIP{yyyyMMdd}{5 位序列}`,全局唯一;不得使用可猜测的自增 ID | +| E3 | 过期:`expires_at = create_time + order.pending.timeout_hours`;定时任务将超时 `PENDING` 置 `CANCELLED`,remark='超时自动关单',审计 `ORDER_EXPIRE`(SYSTEM) | +| E4 | 仅 `PENDING` 可确认/关单;其他状态 4093 | +| E5 | 确认到账必须:凭证号 ≥6 位、TOTP 有效、状态条件更新成功(`UPDATE ... WHERE id=? AND status='PENDING' AND version_no=?`) | +| E6 | 双人复核:`amount_cent >= app_policy.dual_control_threshold_cent` 时,`secondApproverId` 必填且 ≠ 确认人;否则 4094/4095 | +| E7 | 确认到账同一事务:更新订单 → 写 `fin_cash_ledger IN` → 充值写 `fin_transaction RECHARGE`(VIP 订单不写点数流水)→ 更新账户余额/version → VIP 订单更新 holder/account → 写 webhook outbox → 写审计 | +| E8 | 充值入账点数使用订单快照 `points_gained`,不得用当前兑率重算 | +| E9 | VIP 订单:确认后按 `duration_days` 叠加;`base = max(now, 现有 vip_until)`;更新 holder 与 account 冗余字段 | +| E10 | 关单:仅写状态、remark、审计;不写现金台账/流水/webhook;不可恢复 | +| E11 | 重复确认必须只产生一条现金 IN、一条充值流水、一个 `order.paid` 事件;第二次 4093 | +| E12 | 现金台账凭证唯一 `(order_id, direction, voucher_no)`;同一凭证重复登记 4091/422 | + +### 6.6 退款 + +| # | 规则 | +| --- | --- | +| F1 | 仅 `pay_method='offline'` 且订单 `PAID`/`REFUNDED` 可退;在线支付 422(二期) | +| F2 | 累计退款(不含 REJECTED)≤ 订单金额;超额 6004 | +| F3 | 扣回点数:`points_deducted = 0`(VIP 订单)或 `round(amountCent/100 * 兑率)`;优先使用订单创建时兑率快照,历史数据无快照时回退当前应用兑率 | +| F4 | 扣回前校验账户存在且 `balance >= points_deducted`,否则 6006;PENDING 阶段不扣,复核通过时再校验 | +| F5 | 状态:`amountCent >= dual_control_threshold_cent` → `PENDING`;否则 `COMPLETED` 立即生效 | +| F6 | `COMPLETED` 立即生效:扣点数(`REFUND_OUT`)、写现金 OUT、更新订单 `refunded_amount_cent`(全额则 `REFUNDED`)、写 `order.refunded` outbox、写审计;`reviewer = operator`(自动完成) | +| F7 | `PENDING` 必须由他人复核:`reviewer_admin_id != operator_admin_id`,否则 4095;复核通过必须凭证号 ≥6;驳回必须原因 ≥5 字 | +| F8 | 复核通过同事务:扣点数 → 现金 OUT → 订单累计退款/状态 → webhook → 审计;失败全部回滚 | +| F9 | 幂等:`(app_code, idempotency_key)` 唯一;重复提交返回首次退款单并置 code 4091(前端提示“已返回首次结果”),数据库只保留一条 | +| F10 | 部分退款:订单状态保持 `PAID`;`refunded_amount_cent = sum(non-rejected)`;全部退完才 `REFUNDED` | +| F11 | 退款并发:对订单行加锁后再计算可退余额,防止两笔并发退款超额 | +| F12 | `REFUND_IN` 不在现金退款流程产生;该类型保留给“点数回补”场景,禁止与 `REFUND_OUT` 同时写导致重复加点 | + +### 6.7 VIP + +| # | 规则 | +| --- | --- | +| G1 | 档位按应用隔离,`(app_code, plan_code)` 唯一;下架档位不可下单(4001),不影响已持有 | +| G2 | 开通/续费:`vip_until = max(now, 现有 vip_until) + duration_days`;同事务更新 holder 与 account 冗余字段 | +| G3 | `effective = vip_until > NOW()`;过期不删除 holder,仅展示为已过期 | +| G4 | VIP 免扣:仅当 `effective=true` 且 `app_policy.vip_exempt=1` 时生效;`vip_plan.free_deduction` 仅作展示,不单独决定免扣 | +| G5 | 降级/换档:续费时更新 `vip_plan_code` 为新档位,到期时间按新档位天数叠加;历史不追溯 | +| G6 | 退款 VIP 订单:`points_deducted=0`;不撤销已生效 VIP(产品规则),如需撤销走人工调账/线下流程,本期不做 | + +### 6.8 兑率与扣费(含开放 API) + +| # | 规则 | +| --- | --- | +| H1 | 兑率 `points_per_yuan` 为正整数;修改需 TOTP;修改后只影响新订单/新扣费,不回溯 | +| H2 | 扣费请求 `points` 必须为正整数,非法 6003;`points > max_points_per_charge` → 6002(拒绝,不截断) | +| H3 | 保底消费:`required = max(points, min_cost)`;返回 `requestedPoints` 与 `chargedPoints` 区分 | +| H4 | VIP 免扣:命中 §6.7 G4 时 `type=CONSUME_FREE`、`chargedPoints=0`、余额不变、写流水 | +| H5 | 余额充足:扣 `required`;`balance_before/after` 连续;`total_spent += required` | +| H6 | 余额不足:`failedStrategy='none'` → 6001,不写流水、不改余额;`failedStrategy='actual'` → 扣 `min(balance, required)`,`insufficient=true`,余额可为 0;若余额为 0 则 `chargedPoints=0`、仍返回成功并标记 `insufficient=true` | +| H7 | 幂等:`(app_code, idempotencyKey)` 唯一;命中返回首次 `ChargeResult` 且 `idempotentReplay=true`,不得重复扣 | +| H8 | 并发:账户行锁 + version_no;冲突重试 3 次,仍失败 4092 | +| H9 | 扣费必须校验 client token 有效、应用启用;token 无效 4010,应用停用 4003 | +| H10 | `businessRefId` 建议必填(业务单据号),用于对账与排障;同一 `(appCode,businessRefId,type)` 不强制唯一,靠幂等键防重 | +| H11 | 扣费审计:`actor_type='BIZ'`、`actor_name=appCode`,记录点数、余额前后、幂等键;失败也记录 | + +扣费伪代码: + +``` +1. token = resolveClientToken(Authorization) // 失败 4010 +2. app = loadApp(token.appCode); if !app.enabled -> 4003 +3. 校验 points>0 -> 6003;points<=max -> 6002 +4. 幂等查询 fin_transaction(app_code, idempotencyKey) + -> 命中:返回首次 ChargeResult(idempotentReplay=true) +5. BEGIN +6. account = SELECT ... FOR UPDATE WHERE app_code=? AND business_user_id=? +7. if vipEffective && policy.vipExempt=1: + writeTx(CONSUME_FREE, 0, before, before, remark='VIP_FREE') + COMMIT; return +8. required = max(points, policy.minCost) +9. if account.balance < required: + if policy.failedStrategy='none': ROLLBACK; throw 6001 + charged = account.balance + else charged = required +10. UPDATE account SET balance=balance-charged, total_spent=total_spent+charged, + version_no=version_no+1 WHERE id=? AND version_no=? +11. writeTx(CONSUME, charged, before, after) +12. COMMIT; return ChargeResult +``` + +### 6.9 人工调账 + +| # | 规则 | +| --- | --- | +| I1 | 必须有第二复核人,且 `secondApproverId != 当前登录人`,否则 4095 | +| I2 | 复核人必须启用且角色为 SUPER_ADMIN/FINANCE;否则 422/4095 | +| I3 | TOTP 有效;原因 ≥5 字 | +| I4 | `OUT` 时余额足够,扣后不得为负;否则 6006 | +| I5 | 同事务:锁账户 → 改余额 → 写 `ADJUST` 流水 → 审计(含复核人) | +| I6 | 调账不写现金台账、不发 webhook(非资金到账) | +| I7 | 调账不支持撤销;纠错用反向调账,原因必须说明原调账 ID | + +### 6.10 对账 + +| # | 规则 | +| --- | --- | +| J1 | 现金侧与点数侧必须分开计算,不得用一个差异掩盖另一个 | +| J2 | 现金侧:`cashInCent - cashPaidOrderCent - (cashOutCent - cashRefundedCent)` | +| J3 | 点数侧:`walletSum - computedSum`,其中 `computedSum` 按账户流水重算 | +| J4 | 断链:按账户流水 `create_time,id` 升序,`balance_before != expected` 记一次断链;首条 expected=0 | +| J5 | 差异明细 level:`ORDER`(单订单现金/退款不一致)、`SUBJECT`(单账户余额/流水)、`APP`(汇总/断链) | +| J6 | 只报告不自动修复:不修改任何余额、流水、订单、退款 | +| J7 | 报告号 `RC{windowEnd yyyyMMdd}{3 位序号}`;同日同应用多份递增;报告与明细同事务写入 | +| J8 | 窗口含首尾:`windowStart 00:00:00` ~ `windowEnd 23:59:59` | +| J9 | 状态:`diff_count=0` → `BALANCED`,否则 `DIFF` | +| J10 | 对账任务 P95 < 60s / 万单;超过 5 万单建议拆分窗口,接口返回 422 提示缩小范围 | + +### 6.11 Webhook + +| # | 规则 | +| --- | --- | +| K1 | 事务性 Outbox:订单/退款事务内写 `fin_webhook_delivery(status='PENDING')`,禁止事务外补发 | +| K2 | 事件类型:`order.paid`、`order.refunded`;事件 ID 由业务主键派生(`evt_` + SHA-256 前 32 位),同一业务事件唯一 | +| K3 | 至少一次投递:失败重试,不保证恰好一次;下游按 `eventId` 幂等 | +| K4 | 签名:`X-Fin-Timestamp`、`X-Fin-Nonce`、`X-Fin-Event-Id`、`X-Fin-Signature = hex(HMAC_SHA256(secret, timestamp + "\n" + nonce + "\n" + eventId + "\n" + rawBody))` | +| K5 | 接收方校验时间戳 ±300 秒、nonce 10 分钟内未使用、签名常量时间比较 | +| K6 | 重试退避:1 分钟、5 分钟、15 分钟、1 小时、6 小时、24 小时;最多 6 次;仍失败置 `DEAD` | +| K7 | 2xx 视为成功置 `SENT`;4xx/5xx/超时置 `FAILED` 并记录脱敏错误;不记录响应体中的密钥/令牌 | +| K8 | 应用未配置 webhook URL:仍写记录,`status='SENT'`、`last_error='skipped:no_webhook_url'`,不计入 DEAD | +| K9 | 人工重放:仅 FAILED/DEAD;重置 attempts=0、next_retry_at=NOW()、status=PENDING;保留 eventId | +| K10 | 投递器单实例轮询:每 10 秒取 `status IN ('PENDING','FAILED') AND next_retry_at<=NOW()` 的前 100 条,按应用隔离并发 | + +### 6.12 审计 + +| # | 规则 | +| --- | --- | +| L1 | 所有写操作、导出、登录/登出/失败登录、权限变更、配置变更、密钥操作全量留痕 | +| L2 | 审计只追加:数据库账号无 UPDATE/DELETE 权限;应用层不提供修改/删除接口 | +| L3 | 哈希链:`cur_hash = hex(SHA256(prev_hash + "|" + actor_type + "|" + coalesce(actor_id,'') + "|" + actor_name + "|" + action + "|" + target_type + "|" + coalesce(target_id,'') + "|" + result + "|" + create_time + "|" + sha256Hex(before_json or "") + "|" + sha256Hex(after_json or "")))` | +| L4 | 首条 `prev_hash=''`;后续 `prev_hash` 等于上一条 `cur_hash`;链按 `id` 升序校验 | +| L5 | 写入串行化:审计写入加 Redis 锁 `lock:audit:chain`(超时 3 秒,失败降级本地锁),读取 `MAX(id)` 的 `cur_hash` 作为 `prev_hash`;`id` 使用数据库自增,保证链顺序 | +| L6 | 失败操作也要审计:业务事务回滚时,用 `REQUIRES_NEW` 单独事务写 `result='FAILED'`;不得因回滚丢失失败记录 | +| L7 | 审计内容脱敏:密码、TOTP、token、secret、完整手机号、完整银行卡号不得进入 before/after | +| L8 | 保留期 ≥6 个月;建议在线 12 个月、归档 3 年;归档文件加密并校验哈希 | +| L9 | 链校验:全量或分段校验,返回 `valid/checked/brokenAtId/message`;校验动作本身写审计 | +| L10 | 审计查询按 `fin:audit:view`;审计导出按 `fin:export` 且再写一条导出审计 | + +### 6.13 导出与 CSV 安全 + +| # | 规则 | +| --- | --- | +| M1 | 导出上限 10000 行;超出不截断静默,返回 422 提示缩小范围 | +| M2 | 导出必须写审计(操作人、筛选条件、条数、IP、UA) | +| M3 | 返回 JSON 时保持原值;若 `Accept: text/csv` 由服务端生成 CSV,单元格必须以 `'` 前缀中和 `= + - @ \t`,双引号转义为 `""`,并加 UTF-8 BOM | +| M4 | 前端已做 CSV 转义;后端不得假设前端一定转义,服务端 CSV 通道必须独立防护 | +| M5 | 文件名固定白名单(订单/流水/审计),不含用户输入;Content-Type `text/csv; charset=utf-8` | +| M6 | 导出限流 3 次/分钟/管理员;并发导出同一管理员只允许 1 个任务 | + +--- + +## 7. 等保二级(GB/T 22239-2019)控制项映射 + +> 适用范围:本项目按**等保二级**设计与测评。三级才强制要求的“统一集中管控平台、全流量态势感知、强制国密改造”等不在本期承诺范围;机房物理安全依托客户 IDC/自建机房。 + +### 7.1 安全物理环境 + +| 控制点 | 要求 | 本项目落地措施 | 验证方式 | +| --- | --- | --- | --- | +| 物理位置/访问控制 | 机房应具备门禁、访客登记、防雷防火防潮 | 由客户机房提供;交付时收集机房等保备案、巡检记录、出入登记 | 查阅机房资质与近 3 个月巡检记录 | +| 设备防盗防破坏 | 服务器、网络设备固定与上锁 | 服务器置于客户机柜并上锁;资产贴签 | 现场拍照 + 资产清单核对 | +| 电力/空调 | UPS、冗余空调 | 客户机房提供;应用侧配置双路电源告警 | 机房巡检表、UPS 记录 | + +### 7.2 安全通信网络 + +| 控制点 | 要求 | 本项目落地措施 | 验证方式 | +| --- | --- | --- | --- | +| 通信加密 | 远程管理/数据传输加密 | Nginx 仅开 443,TLS1.2/1.3,禁用 TLS1.0/1.1、弱套件;HTTP 80 仅 301 跳转 | `nmap --script ssl-enum-ciphers -p443`;`curl -I http://host` 应 301 | +| 网络架构 | 划分区域、最小暴露 | 应用 8080、MySQL 3306、Redis 6379 仅监听 127.0.0.1;安全组仅放行 443 | `ss -lntp`;外部端口扫描 | +| 通信完整性 | 防篡改 | TLS + 关键接口参数签名(webhook HMAC);管理端 token | 抓包验证无明文口令;签名校验用例 | +| CORS | 仅允许可信源 | 默认同源不返回 ACAO;如跨域,白名单精确匹配 `https://<管理域名>`,禁止 `*` 与 credentials 组合 | `curl -H 'Origin: https://evil.com'` 无 ACAO | + +### 7.3 安全区域边界 + +| 控制点 | 要求 | 本项目落地措施 | 验证方式 | +| --- | --- | --- | --- | +| 边界防护 | 非授权不得接入 | Nginx 反向代理;仅 443 对外;管理端建议 IP 白名单 | 外网端口扫描、白名单测试 | +| 访问控制 | 按最小必要开放 | 数据库/Redis 不对外;Actuator 仅 127.0.0.1:8081 | `ss -lntp`;管理端口外部不可达 | +| 入侵防范 | 防暴力破解、防扫描 | 登录限流 + 账号锁定;Nginx `limit_req`;WAF(客户有则接入) | 5 次失败触发 4021;`ab`/`nikto` 扫描被限流 | +| 恶意代码 | 防病毒/防木马 | 主机安装客户统一杀毒;上传功能本期无 | 杀毒日志、无文件上传入口确认 | +| 边界审计 | 记录网络访问 | Nginx access log 保留 ≥6 个月,含时间/IP/UA/状态码/耗时 | 抽查日志;logrotate 配置 | + +### 7.4 安全计算环境 + +| 控制点 | 要求 | 本项目落地措施 | 验证方式 | +| --- | --- | --- | --- | +| 身份鉴别 | 唯一标识、复杂度、定期更换 | 用户名唯一;密码策略 §6.1;首次/重置强制改密;TOTP 双因子 | 弱口令用例、改密用例 | +| 登录失败处理 | 限制次数、结束会话 | 5 次/15 分钟锁定;会话 30 分钟空闲/8 小时绝对 | 暴力破解用例、会话超时验证 | +| 访问控制 | 最小权限、职责分离 | 三角色 14 权限码;服务端逐接口校验;超管不可确认到账、财务不可定价 | §12 越权用例 | +| 入侵防范 | 输入校验、防注入 | 参数绑定(MyBatis `#{}`)、白名单枚举、长度/格式校验、XSS 转义 | SQL 注入/XSS 用例 | +| 恶意代码防范 | 主机防护 | 客户统一 EDR;应用不加载外部脚本;依赖漏洞扫描 | 依赖扫描报告(Trivy/OWASP) | +| 资源控制 | 限流、会话数、超时 | 分接口限流 §8.5;连接池上限;请求体 ≤1MB;超时 20s | 压测 + 429 验证 | +| 数据完整性 | 防篡改 | 审计哈希链;余额流水双记账;订单状态机版本号 | 篡改审计链用例;流水断链对账 | +| 数据保密性 | 敏感数据加密/掩码 | TLS 传输;TOTP/webhook secret AES-GCM 加密;手机号仅存掩码+哈希;日志脱敏 | 查库无明文;抓包无明文 | +| 数据备份恢复 | 定期备份、可恢复 | 每日全量 + binlog;保留 30 天;季度恢复演练 | 备份脚本、恢复记录 | +| 剩余信息保护 | 退出清除会话 | 登出撤销服务端会话;前端 sessionStorage 清除;敏感响应 `Cache-Control: no-store` | 登出后旧 token 4010 | +| 个人信息保护 | 最小收集、授权 | 仅收集业务用户 ID、用户名快照、手机号(掩码);不收集身份证/地址 | 字段清单核对 | + +### 7.5 安全管理中心 + +| 控制点 | 要求 | 本项目落地措施 | 验证方式 | +| --- | --- | --- | --- | +| 制度 | 安全管理制度 | 交付《运维手册》《账号权限审批表》《变更记录表》 | 文档评审 | +| 人员 | 岗位分离、权限审批 | 超管/财务/审计三角色;账号开通需审批;离岗及时停用 | 审批单、账号清单 | +| 运维 | 运维操作审计 | 所有后台写操作审计;SSH 操作由客户堡垒机记录 | 审计日志抽查、堡垒机记录 | +| 审计 | 审计记录保护 | 审计只追加、哈希链、保留 ≥6 个月、独立账号 | §12 篡改用例 | +| 集中管控(三级项) | 统一管控平台 | **不适用**:二级不强制;本期不建设 | — | + +### 7.6 明确不承诺项 + +| 项 | 原因 | +| --- | --- | +| 国密 SM2/SM3/SM4 改造 | 等保二级不强制密评;本期使用 TLS + AES-GCM + SHA-256;如客户另行要求密评,单独立项 | +| 全流量态势感知/IDS | 二级可通过边界防护+日志满足;客户如有统一平台可对接 | +| 双活/异地容灾 | 单机内网部署,RTO/RPO 见 §10 | +| 机房物理改造 | 由客户/IDC 负责,本项目只收集证据 | + +--- + +## 8. 安全设计细则 + +> 本章为强制实现要求。与前端现状冲突时遵循“后端更严、前端兼容”:前端只依赖 `code` 与 `message`,不依赖任何宽松行为。 + +### 8.1 密钥与配置管理 + +| # | 规则 | 落地要求 | +| --- | --- | --- | +| S1 | 敏感配置来源 | 仅允许环境变量或外部密钥文件(`/etc/fin/secret.env`,权限 `0600`);仓库内配置文件只允许 `${FIN_XXX}` 占位符 | +| S2 | 启动自检 | 关键变量缺失 → **拒绝启动**并打印变量名(不打印值);`FIN_SECRET_ENC_KEY` 解码后不足 32 字节 → 拒绝启动 | +| S3 | 禁止回显 | 文档、日志、异常、审计、监控标签中不得出现密钥值;本文档统一以 `` 占位 | +| S4 | 不可逆凭据 | `client_secret`、client token、ticket 只存 SHA-256 哈希,不可逆;明文仅在创建/轮换的成功响应中返回一次 | +| S5 | 可逆凭据 | `fin_app.webhook_secret_enc` 与管理员 TOTP 种子需解密使用 → AES-256-GCM 加密存储,密钥为 `FIN_SECRET_ENC_KEY`;禁止明文落库 | +| S6 | 密钥轮换 | `FIN_SECRET_ENC_KEY` 轮换需双密钥并存(`FIN_SECRET_ENC_KEY_PREV`),迁移完成后删除旧键;轮换写入审计 | +| S7 | 最小权限 | 数据库账号仅授权 `fin_*` 表的 DML;`fin_audit_log` 只授 `INSERT/SELECT`;生产连接账号禁止 `DROP/ALTER` | +| S8 | 环境隔离 | 生产 `FIN_DEMO_TICKET_ENABLED=0`、`spring.knife4j.enabled=false`、`FIN_TRUST_PROXY=1` 时必须校验 `X-Forwarded-For` 来源 | + +安全相关环境变量(值一律 ``): + +| 键名 | 必填 | 说明 | +| --- | --- | --- | +| `FIN_DB_HOST` / `FIN_DB_PORT` / `FIN_DB_NAME` | 是 | MySQL 连接信息 | +| `FIN_DB_USER` / `FIN_DB_PASSWORD` | 是 | 值 `` | +| `FIN_REDIS_HOST` / `FIN_REDIS_PORT` / `FIN_REDIS_DB` | 是 | Redis 连接信息 | +| `FIN_REDIS_PASSWORD` | 是 | 值 `` | +| `FIN_SECRET_ENC_KEY` | 是 | 32 字节随机数的 Base64;值 `` | +| `FIN_SECRET_ENC_KEY_PREV` | 否 | 轮换期旧键;值 `` | +| `FIN_ALLOWED_ORIGINS` | 是 | 逗号分隔精确源,禁止 `*` | +| `FIN_TRUST_PROXY` | 是 | `1` 表示信任 Nginx 传入的 `X-Forwarded-*` | +| `FIN_DEMO_TICKET_ENABLED` | 是 | 生产必须 `0` | +| `FIN_WEBHOOK_ALLOW_HOSTS` | 否 | 出站 webhook 目标域名白名单,默认空=仅允许 `fin_app.webhook_url` 已登记域名 | +| `FIN_LOG_DIR` | 是 | 日志目录,禁止写入 Web 根目录 | + +### 8.2 日志安全 + +| 项 | 要求 | +| --- | --- | +| 禁止入日志字段 | `password`、`oldPassword`、`newPassword`、`tempPassword`、`totp`、`clientSecret`、`token`、`Authorization`、`ticket`、`secret_hash`、`webhook_secret`、`totp_seed` | +| 允许记录 | 用户名(管理员)、`app_code`、`businessUserId`(可掩码)、`outTradeNo`、`id`、动作、结果、耗时、IP、traceId | +| 日志注入防护 | 所有用户输入经 `sanitizeLog()`:换行/回车/制表符替换为空格,长度截断 512,禁止直接拼接原始参数 | +| 访问日志 | Nginx 记录 `request_time`、`upstream_time`、`status`、`traceId`;不记录请求体 | +| 异常日志 | 打印堆栈仅入本地文件;对外只返回通用文案 + traceId | +| 保留期 | 应用日志 90 天;审计日志 ≥6 个月(§6.12 L8);Nginx 访问日志 90 天 | + +### 8.3 PII 掩码规则(与前端 `utils/mask.ts` 对齐) + +| 字段 | 规则 | 示例 | +| --- | --- | --- | +| 手机号 | 保留前 3 后 4 | `138****8000` | +| 业务用户名(长) | 保留前 2 后 2,中间 `****` | `ab****yz` | +| 凭证号 | 保留前 3 后 3 | `622***123` | +| client secret / token | 仅返回 `secret_prefix` / `token_prefix`(前 8 位) | `sk_ab12****` | +| 银行卡/身份证(如未来接入) | 保留前 4 后 4 / 前 6 后 4 | — | + +强制要求: + +1. `fin_config['pii.mask.enabled']` 只能为 `1`;传 `0` 返回 **4097**(前端 `ConfigView` 亦禁止)。 +2. 掩码在**序列化层**统一执行(Jackson `@Sensitive` + 自定义 Serializer),禁止各 Service 手写。 +3. 审计 `before/after` 同样掩码;`fin_refund.voucher_no` 在列表接口返回掩码值,详情接口按 `fin:refund:review` 返回完整值。 +4. 导出文件默认掩码;仅 `fin:export` + `fin:audit:view` 双权限者可申请“明文导出”,且必须二次确认 + 单独审计。 + +### 8.4 响应与错误信息安全 + +| 项 | 要求 | +| --- | --- | +| 不返回 | 堆栈、SQL、表名、内网 IP/主机名、Redis key、文件路径、依赖版本 | +| 404 策略 | 资源不存在与无权访问对外统一 404(管理端);审计员访问写接口仍 403(需明确提示“无权限”) | +| 防枚举 | 登录用户不存在与密码错误统一 4011;ticket 不存在/过期/已用/应用不匹配统一 7001 | +| 响应头 | `Cache-Control: no-store`、`Pragma: no-cache`(所有 `/api/admin/**`、`/api/pay/**`);`X-Content-Type-Options: nosniff`;`X-Frame-Options: DENY`(收银台允许同源) | +| traceId | 每个响应必带 `traceId`;由网关注入或应用生成,回写 `X-Trace-Id` | + +### 8.5 认证与会话安全 + +| 项 | 要求 | +| --- | --- | +| 密码哈希 | Argon2id(m≥64MB、t≥3、p=1)或 BCrypt cost≥12;禁止 MD5/SHA1/可逆加密 | +| 口令传输 | 强制 HTTPS;前端明文提交至 TLS 通道,服务端不做“前端可获取对称密钥”的伪加密 | +| 锁定时长 | 5 次失败锁 15 分钟(4021);计数键 `login:fail:{username}`,成功清零 | +| 会话存储 | token 为随机 32 字节(Base64URL),服务端存 SHA-256;前端存 `sessionStorage`(与现状一致) | +| 空闲/绝对超时 | 空闲 30 分钟失效;登录后 8 小时绝对失效(A7/A8) | +| 并发会话 | 同一管理员允许 ≤3 个活跃会话,超出踢最早会话并审计 | +| 改密/停用/重置 | 吊销该管理员全部会话(当前会话可保留);下次请求 4010 | +| 敏感操作 | 确认到账/退款/调账/改价/改配置/重置密码/TOTP/密钥轮换/重放 webhook 必须带有效 TOTP | +| TOTP 防重放 | 同一管理员同一 6 位码 90 秒内仅一次(Redis `totp:used:{adminId}:{code}`,TTL 90s),重放 4022 | + +### 8.6 防越权(垂直 / 水平 / 对象级) + +| 类型 | 攻击 | 防护要求 | +| --- | --- | --- | +| 垂直越权 | 审计员调用 `POST /api/admin/orders/{id}/confirm` | 服务端 `@SaCheckPermission` 拦截 → 403;禁止只靠前端隐藏按钮 | +| 垂直越权 | 财务调用 `PUT /api/admin/pricing/{appCode}` | 403(财务无 `fin:pricing:edit`) | +| 垂直越权 | 超管自我批准充值 | 4095(`fin:recharge:confirm` 不授予 SUPER_ADMIN;即使临时授权也必须 `secondApproverId != self`) | +| 水平越权(IDOR) | 改 `{id}` 读取他人订单/账户/退款 | 先按 id 查,再校验对象归属与权限;不存在/无权统一 404;禁止直接回显敏感字段 | +| 对象级 | 用 A 应用 token 操作 B 应用数据 | token 绑定 `app_code`;扣费/签发 ticket 一律以 token 的 `app_code` 为准,忽略请求体 `appCode` 或校验一致 | +| 批量越权 | 导出接口绕过单条校验 | 导出 SQL 与列表共用同一 `DataScope` 与权限校验;导出必须写审计 | +| 参数越权 | 请求体传 `status`/`balance`/`pointsGained` 试图篡改 | 服务端白名单绑定 DTO,禁止 `BeanUtils.copyProperties` 直拷实体 | +| 越权重放 | 用过期 token 调用开放 API | 校验 `revoked_at IS NULL AND expires_at > NOW()`,失败 4010 | + +### 8.7 防重放 + +| 对象 | 机制 | 失败码 | +| --- | --- | --- | +| 一次性 ticket | 只存哈希;原子消费 `UPDATE fin_ticket SET used_at=NOW() WHERE ticket_hash=? AND used_at IS NULL AND expires_at>NOW()`,影响行数 0 → 7001 | 7001 | +| 幂等键 | `(app_code, idempotency_key)` 唯一;重复返回首次结果 + 4091 | 4091 | +| TOTP | 90 秒去重键 | 4022 | +| Webhook 签名 | 时间戳 ±300 秒 + nonce 10 分钟去重 + 常量时间比较 | 401/403(调用方侧) | +| client token | 不透明随机串,服务端会话校验,不依赖 JWT 自校验 | 4010 | +| 订单确认 | 状态条件更新 + `version_no` 乐观锁,影响行数 0 → 4093 | 4093 | +| 退款复核 | `UPDATE fin_refund SET status=... WHERE id=? AND status='PENDING'` | 4093 | + +### 8.8 注入、XSS、CSRF、CORS + +| 威胁 | 要求 | +| --- | --- | +| SQL 注入 | 全部使用 MyBatis `#{}` 参数绑定;`${}` 仅允许白名单枚举(排序字段映射表),并对 `order by` 做枚举校验 | +| 排序/字段注入 | `sortBy` 必须命中白名单 `{create_time,amount_cent,status,...}`;非法值 422 | +| XSS | 所有字符串入参长度约束 + 敏感字段富文本禁止;响应 JSON 设置 `Content-Type: application/json;charset=UTF-8`;Nginx 加 `X-XSS-Protection: 0`(由 CSP 取代) | +| CSP | 前端为纯 SPA:`default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'`(收银台 `frame-ancestors` 允许登记业务域名) | +| CSRF | 使用 `Authorization: Bearer`(非 Cookie)→ 天然免疫 CSRF;`withCredentials=false`;如未来改 Cookie,必须加 SameSite=Lax + CSRF token | +| CORS | 仅允许 `FIN_ALLOWED_ORIGINS` 精确匹配;禁止 `*` 与 `Access-Control-Allow-Credentials: true` 组合;预检缓存 600 秒 | +| 开放重定向 | `redirectUri` 必须 HTTPS(`localhost` 例外),Host 必须命中 `fin_app.allowed_redirect_hosts` 精确域名;禁止通配符/IP/端口/`//`/`@`;失败 4003 | +| SSRF | webhook 出站仅允许 `https` 且域名在 `fin_app.webhook_url` 已登记域名或 `FIN_WEBHOOK_ALLOW_HOSTS`;出站前解析 IP 并拒绝私网/环回/链路本地地址 | + +### 8.9 导出安全(与 §6.13 一致) + +| 项 | 要求 | +| --- | --- | +| CSV 注入 | 单元格以 `= + - @ \t` 开头时前置 `'`;双引号转义为 `""`;含逗号/换行/引号必须整体加引号 | +| 编码 | UTF-8 带 BOM,Excel 打开不乱码 | +| 行数上限 | 单次 10,000 行;超出 422 并提示缩小时间范围 | +| 权限 | 导出需 `fin:export`;审计导出需 `fin:audit:view`;导出动作写审计(含筛选条件、行数) | +| 文件命名 | `fin_{resource}_{yyyyMMddHHmmss}.csv`,不含用户输入 | +| 传输 | `Content-Disposition: attachment`;`Cache-Control: no-store`;禁止落地到 Web 可访问目录 | + +### 8.10 限流阈值 + +| 场景 | 维度 | 阈值 | 超限行为 | +| --- | --- | --- | --- | +| 登录 | 用户名 | 5 次 / 5 分钟 | 429(同时计入锁定) | +| 登录 | 客户端 IP | 20 次 / 5 分钟 | 429 | +| 改密 | 管理员 | 5 次 / 小时 | 429 | +| TOTP 校验失败 | 管理员 | 5 次 / 5 分钟 | 429 + 计入锁定 | +| 收银台下单 | `app_code` | 10 次 / 分钟 | 429 | +| 收银台预览 | `app_code` | 60 次 / 分钟 | 429 | +| 扣费(开放 API) | `app_code` | 600 次 / 分钟(10 rps 令牌桶) | 429 | +| 签发 ticket | `app_code` | 120 次 / 分钟 | 429 | +| 退款创建 | 管理员 | 20 次 / 分钟 | 429 | +| 人工调账 | 管理员 | 10 次 / 分钟 | 429 | +| 任意导出 | 管理员 | 3 次 / 分钟、10 次 / 小时 | 429 | +| Webhook 人工重放 | 管理员 | 10 次 / 分钟 | 429 | +| 审计链校验 | 管理员 | 3 次 / 分钟 | 429 | +| 开放 API 取 token | `client_id` | 30 次 / 分钟 | 429 | + +实现:Redis + Lua 原子令牌桶,键 `rl:{scene}:{dimension}`;Redis 不可用时降级为本地 `Caffeine` 计数(阈值 ×0.5),并在响应头 `X-RateLimit-Mode: local` 提示;同时在 `fin_rate_limit` 记录降级窗口用于审计。 + +--- + +## 9. 错误码表 + +### 9.1 HTTP 状态与业务码的关系(二选一,本项目选定) + +| 项 | 决定 | +| --- | --- | +| 传输层 | **统一 HTTP 200**,业务结果全部由 `code` 表达;仅网关级故障允许 502/504 | +| 理由 | 前端 `utils/http.ts` 以 `code` 判定成功/失败,非 2xx 会被 axios 视为网络异常,丢失 `traceId` 与业务文案 | +| 成功判定 | `code === 0` | +| 失败响应体 | `{code, message, data:null, traceId}`;HTTP 仍为 200 | +| 例外 | `/api/health` 探活用 HTTP 200/503;Nginx 层 502/504 由前端兜底为“服务暂不可用” | + +### 9.2 完整错误码 + +| code | 名称 | 触发场景 | 前端识别 | 服务端处理要求 | +| --- | --- | --- | --- | --- | +| 0 | 成功 | 正常返回 | 是 | `data` 按接口契约返回 | +| 400 | 请求格式错误 | JSON 解析失败、`Content-Type` 非 JSON、字段类型不符 | 否(通用兜底) | 返回通用文案,不暴露解析细节 | +| 401 | 会话失效(兼容码) | 旧版前端/网关透传 | 是 | 与 4010 等价;新代码统一用 4010 | +| 4010 | 未登录 / 会话失效 | token 缺失、哈希不匹配、已撤销、已过期、空闲超时、绝对超时 | 是 | 清 Redis 会话;前端收到后清 `sessionStorage` 并跳登录 | +| 4011 | 用户名或密码错误 | 用户不存在 / 密码错误(统一) | 否 | 计入失败次数;响应耗时应接近(哈希照常执行) | +| 4012 | 账号已停用 | 凭证正确但 `is_active=0` | 否 | 不创建会话;写审计 | +| 4013 | 原密码不正确 | 改密时 `oldPassword` 不匹配 | 否 | 计入改密限流 | +| 4014 | 新密码强度不足 | <12 位、缺大小写/数字/符号、含空格或中文 | 否 | 返回具体缺失项(不含原文) | +| 4015 | 新密码重复 | 等于当前密码或命中最近 3 次历史 | 否 | 不落库 | +| 4016 | 需先修改初始密码 | `must_change_password=1` 时访问其他管理接口 | 否(需同步 `KNOWN_MESSAGES`) | 仅 profile/改密/登出可用;不返回业务数据 | +| 4021 | 账号已锁定 | 连续 5 次失败,15 分钟内 | 否 | 即使凭证正确也拒绝;返回解锁时间(分钟级) | +| 4022 | 动态口令失败 / 需二次验证 | TOTP 非 6 位、错误、重放、缺失 | 否 | 不区分“错误”与“重放”;计入失败次数 | +| 403 | 无权限 | 权限码不匹配、审计员调用写接口 | 是 | 记录 `PERMISSION_DENIED` 审计 | +| 404 | 资源不存在 | id 不存在或无权可见的对象 | 否 | 不区分“不存在/无权” | +| 4091 | 幂等冲突 | 幂等键重复、幂等键缺失/非法 | 是 | 重复请求返回首次结果并置 4091;禁止二次扣费 | +| 4092 | 并发冲突 | 乐观锁 `version_no` 失败、行锁等待超时 | 是 | 事务回滚;提示稍后重试 | +| 4093 | 状态不允许 | 订单非 PENDING 确认/关单、退款非 PENDING 复核 | 是 | 不做任何写入 | +| 4094 | 需第二复核人 | 大额订单未提供 `secondApproverId` | 否 | 提示阈值金额 | +| 4095 | 复核人非法 | 复核人=操作人、复核人无资金权限、复核人不存在 | 否 | 返回原因类别,不回显他人信息 | +| 4096 | 管理约束冲突 | 停用最后一个超管、停用当前登录账号 | 否 | 拒绝并提示 | +| 4097 | 受保护参数禁止修改 | `pii.mask.enabled` 改为 0 等 | 否 | 拒绝并提示需专项审批 | +| 422 | 参数校验失败 | 必填缺失、长度/范围/格式不符、金额非整数分 | 是 | 返回 `data` 为字段级错误列表 | +| 4221 | 唯一键冲突 | `app_code`、`(app_code, plan_code)`、`username` 重复 | 否 | 提示具体冲突字段 | +| 429 | 限流 | 见 §8.10 | 是 | 带 `Retry-After` 语义信息(放在 message) | +| 4001 | 业务对象不可用 | VIP 档位不存在/已下架、商品不可售 | 否 | 收银台展示“暂不可购买” | +| 4003 | 应用凭证无效 | 应用停用、secret 不匹配、redirect 不在白名单 | 否 | secret 校验失败不计入账号锁定,但计入限流 | +| 6001 | 余额不足 | 扣费且 `failedStrategy='none'` | 是 | 不写流水、不改余额 | +| 6002 | 超出单次上限 | `points > maxPointsPerCharge` | 是 | 拒绝,禁止截断 | +| 6003 | 点数非法 | `points` 非正整数、调账点数非法 | 是 | 不写流水 | +| 6004 | 退款超额 | 累计退款 > 订单金额 | 是 | 不创建退款单 | +| 6005 | 预留 | 当前无使用场景 | 否 | 禁止占用;如需启用先更新前端映射 | +| 6006 | 扣回余额不足 | 退款需扣回点数但余额不足 | 否 | 退款不生效;建议部分退款 | +| 7001 | 凭证无效 | ticket 不存在/过期/已用/应用不匹配/缺参 | 是 | 统一文案,不区分原因 | +| 500 | 服务器内部错误 | 未捕获异常 | 否(通用文案) | 记录 traceId + 堆栈到本地日志;响应不含细节 | + +### 9.3 响应示例 + +```json +// 成功 +{ "code": 0, "message": "ok", "data": { "records": [], "total": 0, "page": 1, "pageSize": 20 }, "traceId": "3f9c1a2e8b7d4c60" } + +// 参数校验失败 +{ "code": 422, "message": "提交内容不符合规范,请检查后重试", "data": [{ "field": "amountCent", "message": "充值金额需为 1~50000 元的整数分" }], "traceId": "3f9c1a2e8b7d4c60" } + +// 状态冲突 +{ "code": 4093, "message": "订单当前状态不可确认到账,请刷新后重试", "data": null, "traceId": "3f9c1a2e8b7d4c60" } +``` + +### 9.4 与前端文案的一致性要求 + +1. `utils/http.ts` 的 `KNOWN_MESSAGES` 优先级高于服务端 `message`;因此上表 1 级码文案必须与前端一致,避免“文案两套”。 +2. 服务端 `message` 可更具体(如“退款金额超出可退上限(累计 1200.00 元,已退 300.00 元)”),但不得包含 SQL、堆栈、内部地址。 +3. 新增业务码必须先更新前端 `KNOWN_MESSAGES` 再上线;禁止“后端新增码、前端显示未知错误”。 +4. `traceId` 必须回写响应头 `X-Trace-Id`,便于用户报障定位。 + +--- + +## 10. 非功能需求 + +### 10.1 性能指标 + +| 指标 | 目标 | 测量条件 | +| --- | --- | --- | +| 查询接口 P95 | ≤ 300 ms | 100 万账户 / 1000 万流水 / 50 并发 | +| 查询接口 P99 | ≤ 800 ms | 同上 | +| 写接口 P95 | ≤ 500 ms(含审计写入) | 20 TPS 持续 10 分钟 | +| 登录 P95 | ≤ 800 ms | Argon2id 参数达标前提下 | +| 扣费接口 P95 | ≤ 200 ms | 单应用 10 rps | +| 看板 summary P95 | ≤ 500 ms | 允许 60 秒缓存(Redis) | +| 对账任务 | ≤ 60 s / 万单 | 超过 5 万单返回 422 要求拆分窗口 | +| 导出 1 万行 | ≤ 10 s | 流式写出,不一次性加载全量 | +| 长任务约束 | 无同步接口 > 20 s | 前端 axios 超时 20000 ms | + +### 10.2 可用性与恢复 + +| 项 | 目标 | +| --- | --- | +| 可用性 | 99.5%(7×24,计划内维护除外) | +| 单机故障 RTO | ≤ 2 小时 | +| RPO | ≤ 5 分钟(依赖 binlog) | +| 降级 | Redis 不可用:登录/扣费返回 `code=500` + `message="服务暂不可用"`(HTTP 仍 200),只读查询可用;审计写失败:业务不阻断,写本地补录队列 | +| 优雅停机 | `server.shutdown=graceful`,30 秒排水;停机前完成 Outbox 当前批次 | + +### 10.3 容量预估(3 年) + +| 表 | 3 年行数 | 单行估算 | 磁盘 | +| --- | --- | --- | --- | +| `fin_transaction` | 3000 万 | ~200 B | ~6 GB | +| `fin_audit_log` | 3000 万 | ~600 B(含 JSON) | ~18 GB | +| `fin_order` | 300 万 | ~400 B | ~1.2 GB | +| `fin_cash_ledger` | 300 万 | ~200 B | ~0.6 GB | +| `fin_account` | 100 万 | ~200 B | ~0.2 GB | +| `fin_app_token` | 1000 万(可清理) | ~150 B | ~1.5 GB | +| `fin_ticket` | 1000 万(可清理) | ~150 B | ~1.5 GB | +| `fin_webhook_delivery` | 300 万 | ~800 B | ~2.4 GB | +| 合计(含索引 ×1.6) | — | — | **约 60 GB** | + +清理策略:`fin_app_token` 过期 7 天后物理删除;`fin_ticket` 过期 7 天后物理删除;`fin_admin_session` 失效 30 天后删除;`fin_rate_limit` 按窗口滚动删除。上述清理属“非财务数据”,允许物理删除。 + +### 10.4 备份与恢复 + +| 项 | 要求 | +| --- | --- | +| 全量备份 | 每日 02:00 `xtrabackup`(或 `mysqldump --single-transaction`),保留 30 天 | +| 增量 | binlog 每小时归档,保留 7 天;RPO ≤5 分钟 | +| 异地/离线 | 至少一份离线介质(客户内网要求),每季度校验可恢复性 | +| 恢复演练 | 每季度一次,记录 RTO/RPO 实测值 | +| Redis | 仅承载会话、限流、锁、缓存;开启 AOF `everysec`,但**不作为数据源**;Redis 全丢不影响账务正确性 | +| 备份加密 | 备份文件 AES-256 加密,密钥 ``,与备份分机存放 | + +### 10.5 日志与监控 + +| 项 | 要求 | +| --- | --- | +| 指标端点 | `/actuator/prometheus`(仅内网,Nginx 拒绝外网访问) | +| 必采指标 | HTTP 请求量/耗时/错误率、JVM 堆与 GC、Hikari 连接池、Redis 命中率、审计写入延迟、对账任务耗时、Webhook `PENDING`/`DEAD` 数量、负余额账户数 | +| 告警阈值 | 5 分钟内 5xx > 1%;Webhook `DEAD` > 0;任一笔 `balance < 0` 立即 P1;审计链校验失败 P1;对账 `DIFF` 报告 P2;登录锁定账号数突增 P2 | +| 日志聚合 | 单机可用 `filebeat` 或直接落盘 + `logrotate`;不强制 ELK | +| 审计可读性 | 审计页支持按动作/操作人/时间/结果筛选,详情展示 `before/after` 差异 | + +### 10.6 时区与时间 + +| 项 | 要求 | +| --- | --- | +| 时区 | 全链路 `Asia/Shanghai`:JVM `-Duser.timezone=Asia/Shanghai`、MySQL `time_zone='+08:00'`、容器 `TZ=Asia/Shanghai` | +| 时间类型 | 数据库 `datetime`;Java `LocalDateTime`;API 字符串 `yyyy-MM-dd HH:mm:ss` | +| 禁止 | 混用 `timestamp`/UTC/`Date`;前后端不得自行加减时区 | +| 统计口径 | “自然日”按 Asia/Shanghai 00:00:00~23:59:59;对账窗口含首尾 | +| 单调性 | 审计链、流水时间以服务端时间为准,禁止信任客户端时间 | + +--- + +## 11. 部署与配置 + +### 11.1 部署拓扑(单机内网) + +``` +Internet/内网客户端 + │ HTTPS 443 + [ Nginx ] ← TLS 终结、限流、静态资源、安全响应头 + │ HTTP 127.0.0.1:8080 + [ finance-api (Spring Boot, 单 Jar) ] + │ │ + MySQL 8 (3306) Redis 7 (6379) + │ + 备份目录 /data/backup(离线介质同步) +``` + +| 组件 | 规格建议 | 说明 | +| --- | --- | --- | +| 应用 | 4C8G 起,JVM `-Xms2g -Xmx2g` | 单实例;后续可按需横向扩展(会话在 Redis) | +| MySQL | 8C16G,SSD ≥ 200 GB | 独立实例,不与应用争 CPU | +| Redis | 2C4G | 关闭 `maxmemory-policy allkeys-lru` 以外的淘汰策略需评估 | +| Nginx | 与应用同机 | 仅监听 443;80 端口仅 301 跳转 | +| 前端 | 静态文件由 Nginx 托管于 `/usr/share/nginx/html` | `base '/';` SPA 回退 `try_files $uri $uri/ /index.html` | + +### 11.2 环境变量完整清单 + +| 分类 | 键名 | 必填 | 示例/说明 | +| --- | --- | --- | --- | +| 数据库 | `FIN_DB_HOST` | 是 | `127.0.0.1` | +| 数据库 | `FIN_DB_PORT` | 是 | `3306` | +| 数据库 | `FIN_DB_NAME` | 是 | `fin_platform` | +| 数据库 | `FIN_DB_USER` | 是 | `fin_app` | +| 数据库 | `FIN_DB_PASSWORD` | 是 | `` | +| 数据库 | `FIN_DB_POOL_MAX` | 否 | 默认 `20` | +| Redis | `FIN_REDIS_HOST` / `FIN_REDIS_PORT` / `FIN_REDIS_DB` | 是 | `127.0.0.1` / `6379` / `0` | +| Redis | `FIN_REDIS_PASSWORD` | 是 | `` | +| 密钥 | `FIN_SECRET_ENC_KEY` | 是 | ``(32 字节 Base64) | +| 密钥 | `FIN_SECRET_ENC_KEY_PREV` | 否 | ``(轮换期) | +| 安全 | `FIN_ALLOWED_ORIGINS` | 是 | `https://fin.example.com` | +| 安全 | `FIN_TRUST_PROXY` | 是 | `1` | +| 安全 | `FIN_REDIRECT_ALLOWLIST` | 否 | 补充全局跳转白名单(应用级另配) | +| 安全 | `FIN_WEBHOOK_ALLOW_HOSTS` | 否 | 逗号分隔 | +| 功能 | `FIN_DEMO_TICKET_ENABLED` | 是 | 生产 `0` | +| 功能 | `FIN_AUDIT_CHAIN_LOCK` | 否 | 默认 `lock:audit:chain` | +| 日志 | `FIN_LOG_DIR` | 是 | `/var/log/fin` | +| 日志 | `FIN_LOG_LEVEL` | 否 | 生产 `INFO` | +| 运维 | `SERVER_PORT` | 否 | 默认 `8080`,仅监听 `127.0.0.1` | +| 运维 | `SPRING_PROFILES_ACTIVE` | 是 | `prod` | + +### 11.3 启动与运行 + +```bash +# JVM 参数(生产) +java -server -Xms2g -Xmx2g -XX:+UseG1GC -XX:MaxGCPauseMillis=200 \ + -Duser.timezone=Asia/Shanghai -Dfile.encoding=UTF-8 \ + -jar /opt/fin/finance-api.jar \ + --spring.profiles.active=prod \ + --server.address=127.0.0.1 --server.port=8080 +``` + +| 项 | 要求 | +| --- | --- | +| 进程托管 | `systemd` 单元 `finance-api.service`,`Restart=always`,`RestartSec=5` | +| 只监听内网 | `server.address=127.0.0.1`,禁止直接对外 | +| 文件句柄 | `LimitNOFILE=65535` | +| 启动顺序 | MySQL → Redis → 应用 → Nginx | +| 停机 | `kill -TERM` 优雅停机,等待 30 秒 | + +### 11.4 健康检查 + +| 端点 | 用途 | 响应 | +| --- | --- | --- | +| `GET /api/health` | 存活/就绪(Nginx 与探针) | `{code:0,data:{status:"UP",db:"UP",redis:"UP",version:"x.y.z",time:"..."}}`;异常 HTTP 503 | +| `GET /actuator/health` | 内部细粒度(不暴露给外网) | 需 Nginx `deny all` 或仅内网 | +| `GET /actuator/prometheus` | 指标采集 | 同上 | + +要求:`/api/health` **不返回** 版本号以外的构建信息、不返回配置、不返回主机名;`db` 检测为 `SELECT 1`,`redis` 检测为 `PING`,超时 1 秒。 + +### 11.5 数据库迁移(Flyway) + +| 项 | 要求 | +| --- | --- | +| 工具 | Flyway(与 Spring Boot 集成),禁止手工改生产表 | +| 文件 | `V1__init_schema.sql`、`V2__seed_config.sql`、`V3__indexes.sql`… 递增不可修改已发布脚本 | +| 校验 | `validate-on-migrate=true`;`baseline-on-migrate=false`;生产禁止 `clean` | +| 种子 | 初始超管账号由部署脚本生成一次性随机密码并强制改密;`fin_config` 10 个键按 §4.3.16 默认值插入 | +| 变更窗口 | 结构变更需停机窗口或在线 DDL(`ALGORITHM=INPLACE`),每次变更前全量备份 | +| 回滚 | 不写 `undo`;采用“前滚修复”脚本 `V{n+1}__rollback_xxx.sql` | + +### 11.6 Nginx 关键配置 + +| 项 | 要求 | +| --- | --- | +| TLS | 仅 TLS 1.2/1.3,禁用弱套件;证书自动续期监控 | +| HSTS | `max-age=31536000; includeSubDomains`(首次上线可先 300 秒观察) | +| 安全头 | `X-Content-Type-Options: nosniff`、`X-Frame-Options: DENY`(收银台单独 `SAMEORIGIN`)、`Referrer-Policy: no-referrer`、CSP 见 §8.8 | +| 代理头 | `proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; X-Forwarded-Proto $scheme; X-Request-Id $request_id;` | +| 超时 | `proxy_read_timeout 30s`;`client_max_body_size 1m`(无文件上传) | +| 限流 | `limit_req_zone` 对 `/api/admin/login` 5r/m per IP;`/api/pay/*` 60r/m per IP | +| 隐藏 | `server_tokens off;` 不暴露版本 | +| 路径 | `/api/` → `127.0.0.1:8080`;`/` → 静态 SPA;`/actuator` → `deny all` | + +### 11.7 上线检查清单 + +| # | 检查项 | 通过标准 | +| --- | --- | --- | +| 1 | 配置外置 | 仓库内无任何密钥明文;`grep -r "password" src` 仅命中占位符 | +| 2 | 生产开关 | `FIN_DEMO_TICKET_ENABLED=0`;`/api/pay/demo-ticket` 返回 404;Swagger/knife4j 关闭 | +| 3 | 权限覆盖 | 所有 `/api/admin/**` 均有权限注解;审计员写请求全部 403 | +| 4 | 迁移 | Flyway `migrate` 成功;22 张表、索引与 §4 一致 | +| 5 | 初始账号 | 超管首次登录强制改密;TOTP 已绑定;默认口令已作废 | +| 6 | 审计链 | 连续写 100 条后 `/audit-logs/verify` 返回 `valid=true` | +| 7 | Webhook | 测试事件可投递、可重放、签名可被验证 | +| 8 | 备份 | 当日全量备份存在且可恢复至临时实例 | +| 9 | 监控 | `/api/health` 正常;Prometheus 可抓取;告警通道连通 | +| 10 | 限流 | 登录连续 6 次失败触发 429/4021;导出第 4 次触发 429 | +| 11 | 前端联调 | `VITE_USE_MOCK=0`、`VITE_API_BASE=/api` 全页面无 Mock 依赖 | +| 12 | 回滚预案 | 上一版本 Jar + 数据库备份就位,回滚步骤已演练 | + +--- + +## 12. 验收用例 + +> 全部为**攻击/异常**用例,正常流程由 §5 契约覆盖。执行环境:`VITE_USE_MOCK=0`,后端连测试库。 + +| # | 类别 | 前置条件 | 操作 | 期望结果 | +| --- | --- | --- | --- | --- | +| AC-01 | 垂直越权 | AUDITOR 已登录 | `POST /api/admin/orders/{id}/confirm` | `code=403`,订单状态不变,审计记 `PERMISSION_DENIED` | +| AC-02 | 垂直越权 | FINANCE 已登录 | `PUT /api/admin/pricing/{appCode}` | `code=403`,兑率不变 | +| AC-03 | 垂直越权 | SUPER_ADMIN 已登录 | 对自己发起的 6000 元订单执行确认 | `code=4095`(复核人不得为本人)或 403(无 `fin:recharge:confirm`) | +| AC-04 | 水平越权/IDOR | FINANCE 已登录 | 将 `GET /api/admin/accounts/{id}` 的 id 改为不存在值 | `code=404`,不泄露任何字段 | +| AC-05 | 水平越权 | 两个应用 A/B 各有 token | 用 A 的 token 调 `POST /api/open/v1/charge` 并在体内传 `appCode=B` | 以 token 的 `appCode=A` 扣费,或 `code=4003`;绝不扣 B | +| AC-06 | 重放 ticket | 已成功下单一次的 ticket | 再次 `POST /api/pay/orders` 使用同一 ticket | `code=7001`,不产生第二笔订单 | +| AC-07 | 并发 ticket | 同一 ticket 并发 10 个请求 | 同时提交下单 | 仅 1 个成功,其余 9 个 `code=7001` | +| AC-08 | 重复确认 | 订单已 PAID | 再次确认到账(新凭证号 + 有效 TOTP) | `code=4093`,点数不二次入账,台账不多一条 | +| AC-09 | 并发扣费 | 账户余额 1000 点 | 并发 20 次各扣 100 点 | 成功 10 次、失败 `6001` 10 次;余额=0;流水 10 条且 `balance_after` 连续 | +| AC-10 | 超卖/负余额 | 账户余额 50 点 | 扣费 100 点且 `failedStrategy='none'` | `code=6001`;余额仍 50;无流水 | +| AC-11 | 超单次上限 | 策略 `maxPointsPerCharge=500` | 扣费 501 点 | `code=6002`;不截断、不扣费 | +| AC-12 | 退款超额 | 订单 1000 元,已退 800 元 | 再退 300 元 | `code=6004`;退款单不创建 | +| AC-13 | 退款扣回不足 | 用户已消耗点数,余额不足以扣回 | 发起退款并复核通过 | `code=6006`;退款保持 PENDING;余额不变 | +| AC-14 | 自审退款 | 操作人 = 复核人 | 复核自己发起的退款 | `code=4095` | +| AC-15 | 幂等重放 | 首次退款成功(带幂等键 K) | 相同幂等键再提交 | `code=4091` + 返回首次退款单;库中仅 1 条 | +| AC-16 | 幂等键缺失 | — | 退款请求不带 `idempotencyKey` | `code=4091`(或 422,二者取一并在实现中固定),不创建退款单 | +| AC-17 | CSV 注入 | 用户名/备注含 `=cmd\|' /c calc'` | 导出订单 CSV | 单元格前置 `'`,Excel 不执行公式 | +| AC-18 | CSV 注入(含公式前缀) | 备注以 `+`、`-`、`@`、Tab 开头 | 导出流水 CSV | 均被 `'` 转义;双引号正确转义 | +| AC-19 | SQL 注入 | 登录名 `' OR 1=1 --` | 登录 | `code=4011`;无 SQL 错误信息 | +| AC-20 | SQL 注入(排序) | 已登录 | `GET /api/admin/orders?sortBy=id;drop table fin_order` | `code=422`;表仍存在 | +| AC-21 | XSS | 应用名填 `` | 保存后查看列表/详情 | 原样存储、渲染时转义,不执行脚本 | +| AC-22 | 弱口令 | 管理员改密为 `12345678` | 提交改密 | `code=4014`;密码不变 | +| AC-23 | 密码复用 | 新密码等于最近 3 次之一 | 提交改密 | `code=4015` | +| AC-24 | 暴力破解锁定 | 账号存在 | 连续 5 次错误密码 | 第 5 次后 `code=4021`;即使第 6 次正确也拒绝;15 分钟后可登录 | +| AC-25 | 账号枚举 | 不存在的账号 | 登录 5 次 | 始终 `4011`;不出现“用户不存在”;锁定行为与存在账号一致 | +| AC-26 | TOTP 重放 | 同一 6 位码已用过 | 90 秒内再次使用 | `code=4022`;操作不生效 | +| AC-27 | TOTP 缺失 | 敏感操作不带 totp | 确认到账 | `code=4022`;状态不变 | +| AC-28 | 审计链篡改 | 有 ≥10 条审计 | 直接 `UPDATE fin_audit_log SET action='X' WHERE id=5` 后调用 verify | 返回 `valid=false`,`brokenAtId=5`;告警触发 | +| AC-29 | 审计删除 | 应用账号尝试 `DELETE FROM fin_audit_log` | 执行 | 数据库权限拒绝(仅 INSERT/SELECT) | +| AC-30 | 伪造 webhook 签名 | 构造任意 body + 错误签名 | 接收端校验 | 接收端拒绝(5xx/4xx);平台侧记录 `FAILED`,不重试成功 | +| AC-31 | Webhook 重放 | 抓取一次合法投递 | 10 分钟内重放同一 `nonce` | 接收端按 nonce 去重拒绝;平台不重复产生业务副作用 | +| AC-32 | 开放重定向 | `redirectUri=https://evil.com` | `GET /api/pay/preview` | `code=4003`;不返回可跳转票据 | +| AC-33 | 开放重定向(变体) | `redirectUri=https://fin.example.com.evil.com` | 同上 | `code=4003`(精确域名匹配,非后缀匹配) | +| AC-34 | 开放重定向(IP/端口/协议) | `http://127.0.0.1:8080/x`、`//evil.com`、`https://u@evil.com` | 同上 | 全部 `code=4003`;`localhost` 仅允许开发环境 | +| AC-35 | CORS 滥用 | `Origin: https://evil.com` 发预检 | 请求 `/api/admin/profile` | 无 `Access-Control-Allow-Origin: *`;浏览器侧被拒;服务端不返回该源 | +| AC-36 | 敏感信息泄露 | 触发 500(如注入异常) | 观察响应 | 仅 `{code:500,message:通用文案,traceId}`;无堆栈/SQL/内网 IP | +| AC-37 | 日志注入 | 备注含 `\n2026-01-01 INFO fake login success` | 提交并查日志 | 换行被替换为空格;不产生伪造日志行 | +| AC-38 | 限流绕过(XFF 伪造) | `FIN_TRUST_PROXY=1` | 伪造 `X-Forwarded-For` 轮换 IP 登录 | 以 Nginx 真实来源为准(仅信任最后一跳),仍触发 429 | +| AC-39 | 导出限流 | 已登录 FINANCE | 1 分钟内第 4 次导出 | `code=429`;前 3 次成功且均有审计 | +| AC-40 | 生产 demo-ticket 禁用 | `FIN_DEMO_TICKET_ENABLED=0` | `GET /api/pay/demo-ticket` | `code=404`;不返回任何 ticket | +| AC-41 | 停用应用熔断 | 应用 enabled=0 | 用停用前 token 扣费/签发 ticket | `code=4003`;token 已被撤销则 `4010` | +| AC-42 | 密钥宽限期 | 轮换 secret 且 grace=24h | 用旧 secret 取 token(24h 内 / 之后) | 24h 内成功;之后 `4003`;旧 secret 状态变 `REVOKED` | +| AC-43 | 双人复核缺失 | 订单 6000 元 | 确认到账不带 `secondApproverId` | `code=4094`;订单仍 PENDING | +| AC-44 | 停用最后超管 | 系统仅 1 名启用超管 | 尝试停用该账号 | `code=4096`;账号仍启用 | +| AC-45 | 停用当前账号 | 当前登录超管 | 尝试停用自己 | `code=4096` | +| AC-46 | 强制改密绕过 | 管理员 `must_change_password=1` | 直接调用 `GET /api/admin/orders` | `code=4016`;不返回业务数据;仅 profile/改密/登出可用 | +| AC-47 | 会话绝对超时 | 登录后持续活跃 > 8 小时 | 继续请求 | `code=4010`;需重新登录 | +| AC-48 | 会话空闲超时 | 登录后 31 分钟无请求 | 请求任意管理接口 | `code=4010` | +| AC-49 | 登出即失效 | 登出后用旧 token | 请求 profile | `code=4010` | +| AC-50 | 对账只读 | 存在差异 | 运行对账 | 报告与差异落库;余额/流水/订单零变化 | +| AC-51 | 对账断链 | 人为删除一条流水 | 运行对账 | 报告标记断链差异;不自动补写流水 | +| AC-52 | 大窗口对账 | 窗口内 > 5 万单 | 提交 | `code=422` 并提示缩小范围;不启动任务 | + +--- + +## 13. 开发计划与里程碑 + +> 仅划分阶段与准出条件,不含工期承诺。每阶段结束必须跑通对应验收用例。 + +| 阶段 | 名称 | 交付物 | 准出条件 | +| --- | --- | --- | --- | +| M0 | 工程骨架 | 项目结构、Flyway `V1__init_schema.sql`、统一响应体、全局异常、traceId、`/api/health`、配置外置 | `mvn compile` 通过;本地起服务健康检查 UP | +| M1 | 认证与权限 | 登录/登出/profile/改密、锁定、TOTP、会话、权限注解、管理员 CRUD、密码历史 | AC-19、AC-22~AC-29、AC-46~AC-49 通过 | +| M2 | 接入应用与密钥 | 应用 CRUD、secret 轮换与宽限、token 签发/撤销、停用熔断 | AC-35、AC-41、AC-42 通过;`/api/open/v1/token` 可用 | +| M3 | 账户与流水 | 账户查询/详情/流水、余额账本、行锁/乐观锁、流水导出 | AC-04、AC-10;余额与流水严格一致 | +| M4 | 充值闭环 | 收银台 preview/create/status、demo-ticket、订单列表/详情/确认/关单、现金台账、VIP 下单 | AC-06~AC-08、AC-32~AC-34、AC-40、AC-43 通过 | +| M5 | 退款与调账 | 退款创建/复核、累计额度、点数扣回、人工调账、双人复核 | AC-12~AC-16 通过 | +| M6 | 计费与 VIP | 兑率、扣费策略、扣费开放 API、VIP 档位/持有 | AC-09、AC-11、AC-41 通过;扣费 P95 ≤ 200 ms | +| M7 | 对账/审计/Webhook/运维 | 对账报告与差异、审计哈希链与校验、Webhook Outbox 与重放、参数配置、看板 | AC-28~AC-31、AC-50~AC-52 通过;上线检查清单 12 项全绿 | + +依赖关系:M1 为硬前置(其余模块均需会话与权限);M4 依赖 M2 的 ticket 签发;M5 依赖 M4 的订单与现金台账;M7 依赖 M4/M5 已产生可对账数据。 + +--- + +## 14. 附录 + +### 14.1 枚举字典 + +| 枚举 | 取值 | 说明 | +| --- | --- | --- | +| 角色 `Role` | `SUPER_ADMIN` / `FINANCE` / `AUDITOR` | 超管 / 财务 / 审计 | +| 订单状态 `OrderStatus` | `PENDING` / `PAID` / `CANCELLED` / `REFUNDED` | 待确认 / 已到账 / 已关单 / 已退款 | +| 订单类型 `OrderType` | `recharge` / `vip` | 小写,与前端一致 | +| 支付方式 `PayMethod` | `offline` / `wechat` / `alipay` | 本期仅 `offline` 可用 | +| 流水类型 `TxType` | `RECHARGE` / `CONSUME` / `CONSUME_FREE` / `REFUND_IN` / `REFUND_OUT` / `ADJUST` | 充值 / 扣费 / VIP 免扣 / 退款入账 / 退款扣回 / 人工调账 | +| 退款状态 `RefundStatus` | `PENDING` / `COMPLETED` / `REJECTED` | 待复核 / 已完成 / 已驳回 | +| Webhook 状态 `WebhookStatus` | `PENDING` / `SENT` / `FAILED` / `DEAD` | 待投递 / 成功 / 失败待重试 / 终止 | +| 现金方向 | `IN` / `OUT` | 收款 / 退款 | +| 兑率/策略失败策略 | `none` / `actual` | 拒绝 / 按实际余额扣 | +| secret 状态 | `ACTIVE` / `GRACE` / `REVOKED` | 生效 / 宽限期 / 已回收 | +| 应用开关 `enabled` | `1` / `0` | 启用 / 停用 | +| 审计结果 `result` | `SUCCESS` / `FAILED` | 成功 / 失败 | +| 审计主体 `actorType` | `ADMIN` / `CLIENT` / `SYSTEM` / `PUBLIC` | 管理员 / 应用 / 系统任务 / 匿名(登录页) | +| 对账状态 | `BALANCED` / `DIFF` | 平衡 / 有差异 | +| 差异类型 | `CASH_MISMATCH` / `POINTS_MISMATCH` / `CHAIN_BROKEN` / `ORDER_MISSING` | 现金不平 / 点数不平 / 流水断链 / 台账缺单 | + +### 14.2 字段命名规范 + +| 规则 | 示例 | 反例 | +| --- | --- | --- | +| 金额后缀 `_cent` | `amount_cent`、`refunded_amount_cent` | `amount`、`money` | +| 点数不加后缀 | `points`、`balance`、`points_gained` | `points_count` | +| 时间后缀 `_at` / `_time` | `paid_at`、`expires_at`、`create_time` | `payDate` | +| 开关 `enabled` / `is_*` | `enabled`、`has_prev_secret` | `status` 表示布尔 | +| 外键 `{实体}_id` | `order_id`、`refund_id`、`admin_id` | `oid` | +| 快照字段 `_snapshot` / `_name` | `username_snapshot`、`confirmed_by_admin_name` | 直接关联查名 | +| 密文后缀 `_enc` / 哈希后缀 `_hash` | `webhook_secret_enc`、`token_hash` | `secret` | +| 编码 `_code` | `app_code`、`plan_code` | `appId` 表示编码 | +| 唯一索引 `uk_`,普通索引 `idx_` | `uk_fin_order_no` | `index1` | + +### 14.3 前端页面与接口映射 + +| 页面 | 路由 | 权限 | 主要接口 | +| --- | --- | --- | --- | +| 管理员登录 | `/login` | 公开 | `POST /api/admin/login` | +| 修改密码 | `/password` | 登录 | `POST /api/admin/password/change`、`GET /api/admin/profile` | +| 资金看板 | `/dashboard` | `fin:view` | `dashboard/summary`、`dashboard/trend`、`dashboard/distribution` | +| 接入应用 | `/apps` | `fin:view` + 按钮权限 | `apps` 系列 8 个接口 | +| 钱包账户 | `/accounts` | `fin:view` | `accounts`、`accounts/{id}`、`accounts/{id}/transactions`、`accounts/adjust` | +| 充值订单 | `/orders` | `fin:view` + 按钮权限 | `orders` 系列 6 个接口 | +| 退款单 | `/refunds` | `fin:view` + 按钮权限 | `refunds` 系列 3 个接口 | +| 点数流水 | `/transactions` | `fin:view` | `transactions`、`transactions/export` | +| VIP 档位 | `/vip-plans` | `fin:view` + `fin:vip:manage` | `vip-plans` 系列 4 个接口 | +| VIP 持有 | `/vips` | `fin:view` | `GET /api/admin/vips` | +| 兑率与策略 | `/pricing` | `fin:view` + `fin:pricing:edit` | `pricing`/`policies` 各 2 个接口 | +| 对账中心 | `/reconcile` | `fin:view` | `reconcile/reports`、`reconcile/reports/{id}`、`reconcile/run` | +| Webhook 投递 | `/webhooks` | `fin:view` + `fin:webhook:manage` | `webhooks`、`webhooks/{id}/replay` | +| 管理员 | `/admins` | `fin:admin:manage` | `admins` 系列 6 个接口 | +| 审计日志 | `/audit` | `fin:audit:view` | `audit-logs` 系列 4 个接口 | +| 全局参数 | `/config` | `fin:config:edit` | `configs`、`configs/{key}` | +| 收银台 | `/pay` | 公开(ticket) | `pay/preview`、`pay/orders`、`pay/orders/{outTradeNo}/status`、`pay/demo-ticket`(仅非生产) | +| 无权限 | `/403` | 公开 | 无 | +| 不存在 | `/:pathMatch(.*)*` | 公开 | 无 | + +### 14.4 待确认事项(评审时拍板) + +| # | 事项 | 现状 | 建议 | +| --- | --- | --- | --- | +| 1 | 权限码 14 vs 15 | 前端 `PERM` 已包含 `fin:reconcile:run`,并集为 15 | 以 15 个为准;`SUPER_ADMIN` 仍不授予 `fin:recharge:confirm` / `fin:refund:create`(职责分离) | +| 2 | 退款 `6005` | 前端无该码 | 保持预留,禁止占用;若启用须同步前端映射 | +| 3 | 微信/支付宝 | 枚举存在,页面仅线下 | 本期不接入支付通道;`payMethod` 仅接受 `offline`,其余 422 | +| 4 | 明文导出 | 前端无入口 | 本期不开放“明文导出”,仅掩码导出 | +| 5 | 审计在线保留期 | 需求为 ≥6 个月 | 建议在线 12 个月 + 归档 3 年,需客户确认存储预算 | +| 6 | 开放 API | 前端无对应页面 | 属后端新增能力,须与业务方确认 `charge` 语义与计费口径后再开发 | +| 7 | 多实例部署 | 当前单机 | 会话与限流已 Redis 化,可直接横向扩展;审计链锁在单实例下最稳,多实例需改造为数据库行锁 | +| 8 | 对账自动执行 | 前端仅手动触发 | 建议每日 01:00 定时执行并告警,是否启用由客户确认 | diff --git a/财务系统设计-功能与业务逻辑(1).md b/财务系统设计-功能与业务逻辑(1).md new file mode 100644 index 0000000..b8fcaf1 --- /dev/null +++ b/财务系统设计-功能与业务逻辑(1).md @@ -0,0 +1,1228 @@ +# 财务系统(中央计费平台)设计与业务规范 + +> 版本:**v2.1 · 一致性修订 + 技术栈版** +> 定位:公司所有收费软件(光刻仿真及其他)的统一计费/资金中台。 +> 原则:**资金权威在本系统**;业务系统只做「预检展示 + 成交通知」,不碰钱。 +> +> **v2.1 变更摘要**:在 v2.0 基础上修复复审发现的 9 项资金一致性缺陷(ADJUST 方向二义、兑率单位与取整、 +> 账户自动开户、幂等键并发竞态、VIP 订单退款、退款点数折算快照、退款复核期冻结、对账时间基准、 +> `total_spent` 口径),补齐报价/余额查询接口、充值金额与频次限额、webhook 每次重签、审计链串行化、 +> subject 冻结状态,并新增第 16 节「技术栈与组件选型」。v2.0 的 17 项修复仍然有效(见第 12 节)。 +> +> **唯一权威**:本项目只保留本文件作为唯一设计权威,不存在第二份并行文档。 +> 业务接入 API 契约以第 3/4/5 节为准,OpenAPI 描述由服务端代码(springdoc)生成并随版本发布, +> 不再维护独立的手写 API 文档;如有出入以本文件为准。 + +--- + +## 0. 已锁定决策(基线,不再变更) + +| # | 决策 | 含义 | +|---|---|---| +| D1 | **业务侧身份 + 一次性凭证** | 财务系统**不建注册登录**,用户身份来自业务系统,用短期 `ticket` 换一次访问权 | +| D2 | **钱包按 app 隔离** | 同一自然人在不同软件**各有独立余额与 VIP**,互不通用 | +| D3 | **先 cash 记账跑通闭环** | MVP 不接微信/支付宝;充值 = 后台登记「线下收款已到账」,二期接真实支付 | +| D4 | **定价与档位租户化** | 兑率、保底、单次上限按 app 独立配置;VIP 档位独立成表 `fin_vip_plan`,各 app 可设任意档位(时长/价格/是否免扣) | +| D5 | **管理员三角色 + 职责分离** | SUPER_ADMIN 管配置与账号、FINANCE 管资金操作、AUDITOR 只读审计;「改价的人不能确认到账」 | +| D6 | **计费判定权收归财务侧** | 业务系统只报「应付点数」;免扣、保底、单次上限全部由财务系统在扣费事务内判定 | + +**D2 推论(必须告知业务方)**:光刻仿真充的点数不能在其它软件使用;用户在多软件使用需分别充值。 +跨应用共享钱包属于架构变更,**本期不做**。 + +**D6 的意义**:业务系统被攻破或作恶时,最多让用户「多付应付的点数」,无法触碰免扣规则、上限、兑率等资金语义; +所有金额判定都在财务侧事务内完成,业务侧传入的 `points` 只是「应付额」,不是「实扣额」。 + +--- + +## 1. 定位与边界 + +### 1.1 功能域 +多应用接入 · 业务用户映射(不存密码)· 按 app 隔离的钱包/VIP · 订单与线下收款台账 · 幂等扣费 · +退款与核销 · 对账与审计 · 后台管理(唯一需要密码登录的是管理员)。 + +### 1.2 明确不做 +不承载业务逻辑;不做总账/应收应付/代记账;不做跨应用共享钱包;不存业务用户密码、不做业务用户注册登录。 + +### 1.3 信任边界(威胁模型) +| 角色 | 可信度 | 防护要点 | +|---|---|---| +| 业务系统服务端 | 半可信(持有 client_secret) | `app_code` 只从 token 派生;键命名空间隔离;限流 | +| 业务系统前端 / 浏览器 | **不可信** | 金额/点数一律服务端重算;跳转白名单;ticket 一次性 | +| 财务系统后台管理员 | 可信但需监督 | 2FA + 职责分离 + 双人复核 + 全量审计(哈希链) | +| 网络/日志/中间件 | 可能泄露 | 密钥不入日志、ticket 日志脱敏、最小权限 DB 账号 | + +--- + +## 2. 数据模型 + +> 通用:`id` bigint PK;`is_delete`(1 正常 / 0 删除);`create_time`/`update_time`;utf8mb4_0900_ai_ci。 +> 金额 `amount_cent`(分,int);点数 `points`(int);货币固定 `currency='points'`。 +> **所有业务表的用户维度统一 `(app_code, business_user_id)` 二元组**,这是 D2 的落地形式。 +> 所有表启用 `CHECK` 约束兜底(MySQL 8.0.16+ 生效),应用层校验 + DB 约束双重防线。 + +### 2.1 表清单 + +| 表 | 关键字段 | 唯一约束 | 说明 | +|---|---|---|---| +| `fin_app` | `app_code`、`app_name`、`client_secret_hash`、`client_secret_prev_hash`、`client_secret_expires_at`、`allowed_redirect_hosts`、`webhook_url`、`webhook_secret_enc`、`enabled` | `app_code` | 接入应用;**跳转白名单 + webhook 密钥必须有**;`prev_hash` 支撑密钥平滑轮换 | +| `fin_app_token` | `app_code`、`token_hash`、`expires_at`、`revoked_at`、`issued_ip` | `token_hash` | **client token 存储**(只存 hash),支持单 token 撤销与全应用熔断 | +| `fin_admin` | `username`、`password_hash`、`role`、`is_active`、`must_change_password`、`totp_secret_enc`、`failed_attempts`、`locked_until`、`last_login_at`、`last_login_ip` | `username` | 后台管理员(唯一密码登录方);`role` = SUPER_ADMIN / FINANCE / AUDITOR | +| `fin_subject` | `app_code`、`business_user_id`、`username_snapshot`、`phone_masked`、`phone_hash`、`email_masked`、`email_hash`、`status`、`first_seen_at` | `(app_code, business_user_id)` | 业务用户投影(**首次签发 ticket 或首次扣费自动建档**,不存明文手机号/邮箱);`status` = ACTIVE / FROZEN / CLOSED,FROZEN 期间禁止扣费与新充值 | +| `fin_ticket` | `app_code`、`business_user_id`、`ticket_hash`、`expires_at`、`used_at`、`issued_ip`、`issued_ua` | `ticket_hash` | 一次性凭证(只存 hash) | +| `fin_account` | `app_code`、`business_user_id`、`balance`、`frozen_balance`、`total_spent`、`version_no` | `(app_code, business_user_id)` | 按 app 隔离钱包;`CHECK balance >= 0`、`CHECK 0 <= frozen_balance <= balance`;`frozen_balance` 为退款复核期冻结(等价 Blnk inflight) | +| `fin_vip` | `app_code`、`business_user_id`、`vip_plan_code`、`vip_until`、`version_no` | `(app_code, business_user_id)` | 按 app 隔离 VIP,档位指向 `fin_vip_plan` | +| `fin_vip_plan` | `app_code`、`plan_code`、`plan_name`、`duration_days`、`price_cent`、`free_deduction`、`enabled` | `(app_code, plan_code)` | **各 app 任意档位**;`free_deduction=1` 表示该档期内扣费免点数(D6 落地) | +| `fin_order` | `app_code`、`business_user_id`、`order_type`(recharge/vip)、`pay_method`(offline/wechat/alipay)、`amount_cent`、`points_gained`、`points_per_yuan_snapshot`、`vip_plan_code`、`third_party_trade_no`、`status`、`out_trade_no`、`expires_at`、`paid_at`、`confirmed_by_admin_id`、`second_approver_id`、`remark` | `out_trade_no` | `CHECK amount_cent > 0`、`CHECK points_gained >= 0`;`points_per_yuan_snapshot` 充值订单必填且 > 0(VIP 订单可为空),锁定下单时兑率,退款折算不受改价影响 | +| `fin_cash_flow` | `app_code`、`order_id`、`direction`(IN/OUT)、`amount_cent`、`received_at`、`voucher_no`、`operator_admin_id`、`remark` | 索引 `(order_id, direction)` | **线下收款/退款台账**(现金侧对账依据,`voucher_no` 为银行凭证号);一单一条 IN、可多条 OUT | +| `fin_refund_order` | `app_code`、`business_user_id`、`order_id`、`amount_cent`、`points_deducted`、`status`(PENDING/COMPLETED/REJECTED)、`idempotency_key`、`operator_admin_id`、`reviewer_admin_id`、`voucher_no`、`completed_at`、`remark` | `(app_code, idempotency_key)`;索引 `order_id` | **现金退款单**(退充值核销),状态单向流转;`completed_at` 为对账时间基准;PENDING 期间冻结等价点数 | +| `fin_transaction` | `app_code`、`business_user_id`、`type`(RECHARGE/CONSUME/CONSUME_FREE/REFUND_IN/REFUND_OUT/ADJUST_IN/ADJUST_OUT)、`amount`、`balance_before`、`balance_after`、`business_ref_id`、`idempotency_key`、`order_id`、`refund_of_id`、`refunded_points`、`operator_admin_id`、`remark` | **`(app_code, idempotency_key)`** | 流水只增不改,含前后快照;`REFUND_IN`=点数回补(+)、`REFUND_OUT`=现金退款扣回(−)、`ADJUST_IN/ADJUST_OUT`=人工调整(±),**方向由 type 唯一确定** | +| `fin_app_policy` | `app_code`、`min_cost`、`max_points_per_charge`、`vip_exempt`、`failed_strategy`、`dual_control_threshold_cent`、`enabled` | `app_code` | **各 app 扣费策略**;`failed_strategy`:`none`=任务失败不自动补偿(推荐)/ `actual`=按实际点数自动回补(走 4.4.1);`dual_control_threshold_cent` 为 NULL 时继承 `fin_config.review.threshold_cent` | +| `fin_pricing` | `app_code`、`points_per_yuan`、`enabled` | `app_code` | 仅兑率(1 元 = 多少点数);VIP 价格在 `fin_vip_plan`,策略在 `fin_app_policy`,三者不混 | +| `fin_config` | `config_key`、`config_value`、`description`、`update_by`、`update_time` | `config_key` | **全局运行参数**(见 4.7),变更需 SUPER_ADMIN + 审计 | +| `fin_webhook_delivery` | `app_code`、`event_id`、`event_type`、`payload`、`signature`、`status`(PENDING/SENT/DEAD)、`attempts`、`next_retry_at`、`last_error` | `event_id` | webhook 重试队列(可靠投递);`signature` 仅记录**最近一次发送**的签名,实际签名在每次投递时按当时时间戳重算 | +| `fin_payment_callback_log` | `app_code`、`channel`、`third_party_trade_no`、`out_trade_no`、`raw_body`、`signature`、`verify_result`、`amount_cent`、`processed` | `(channel, third_party_trade_no)` | 二期支付回调原始报文与验签结果,只增不改(举证 / 补单 / 渠道对账) | +| `fin_recon_diff` | `app_code`、`biz_date`、`diff_type`、`ref_type`、`ref_id`、`expected_amount`、`actual_amount`、`diff_amount`、`status`、`snapshot_at` | 索引 `(app_code, biz_date, diff_type)` | 每日对账差异明细(P1 告警依据);修正只能走 `ADJUST_IN/OUT` + 双人复核 | +| `fin_audit_log` | `actor_type`(ADMIN/SYSTEM/BIZ)、`actor_id`、`actor_app_code`、`action`、`target_type`、`target_id`、`before_json`、`after_json`、`ip`、`ua`、`prev_hash`、`cur_hash` | `cur_hash` | **只增不改**,SM3/SHA-256 哈希链防篡改;`actor_type=BIZ` 时用 `actor_app_code` 标识来源应用 | + +> 表清单共 **19 张**(v2.1 新增 `fin_recon_diff`、`fin_payment_callback_log`)。 + +### 2.2 状态机 + +``` +fin_order: PENDING ──确认到账──▶ PAID ──退款核销──▶ REFUNDED + │ │ + └──超时/手动关单──▶ CANCELLED ◀──(仅 PENDING 可关) +PAID 不可回退为 PENDING;REFUNDED 不可再次入账(幂等键 + 条件更新双保险) +fin_webhook_delivery: PENDING ──成功──▶ SENT / ──重试耗尽──▶ DEAD +fin_refund_order: PENDING ──复核通过──▶ COMPLETED / ──复核驳回──▶ REJECTED + (PENDING 期间冻结 points_deducted,终态时释放冻结) +``` + +### 2.3 关键约束(DB 层兜底) +- `fin_transaction` 唯一键 **`(app_code, idempotency_key)`**:同键不同 app / 同 app 不同业务不得互相吞单。 +- `fin_account.balance >= 0`、`0 <= frozen_balance <= balance`、`fin_order.amount_cent > 0`、 + `fin_order.points_per_yuan_snapshot > 0`、`fin_transaction` 按类型限制 `amount`(见 4.4)。 +- `fin_transaction.amount` **恒为正数**(`CHECK amount > 0`;仅 `CONSUME_FREE` 允许 `amount = 0`), + 方向由 `type` 唯一决定(`ADJUST_IN`/`ADJUST_OUT` 亦然),绝不用负数表达方向。 +- `fin_refund_order.amount_cent <= 原订单 amount_cent` 且任何时刻 `Σ该订单退款 ≤ 原订单 amount_cent` + (条件更新 + 事务内求和校验保证;部分退款不允许累计超退)。 +- `fin_refund_order.points_deducted` 按**下单时 `points_per_yuan_snapshot`** 折算: + `floor(本次金额 × 订单 points_gained / 订单 amount_cent)`,且最后一笔退款取「剩余未扣回点数」补齐残差; + VIP 订单 `points_deducted` 恒为 0(不写 `REFUND_OUT` 流水)。 +- `fin_vip_plan.price_cent > 0`、`duration_days > 0`;`fin_vip.vip_plan_code` 必须命中同一 `app_code` 的启用档位 + (下架档位存量 VIP 继续有效到期,不可新购/续该档);**VIP 订单仅支持全额退款,退款生效即权益终止**。 +- `fin_subject.phone_hash`/`email_hash` 唯一性不做强约束(同一手机号可对应不同业务用户),仅用于精确匹配与去重提示。 +- `fin_ticket.ticket_hash` 唯一 + `expires_at` + `used_at`:不可重放。 +- `fin_cash_flow (order_id, direction)` 建普通索引而非唯一键:同一订单只允许一条 `IN`(由「确认到账」条件更新 + + 事务内校验保证),允许**多条** `OUT`(分次部分退款,每笔对应一条 `fin_refund_order`)。 +- `fin_transaction.refunded_points >= 0` 且任何时刻 `Σ退款 ≤ 原 CONSUME.amount`(条件更新保证)。 +- `fin_app_policy` 必须满足 `min_cost <= max_points_per_charge`(否则保底可突破单次上限,配置层直接拒绝)。 + +--- + +## 3. 一次性凭证与接入 token + +### 3.1 业务客户端 token(client token) +``` +业务系统服务端 → POST /auth/business-token (app_code + client_secret) + ← {access_token, expires_in} +规则: +· access_token = 随机 32 字节(opaque),DB 只存 SHA-256 hash 于 fin_app_token +· 每次调用校验:hash 存在 → 未过期 → revoked_at 为空 → 所属 fin_app.enabled=1 +· 有效期 15 分钟,到期即失效,无 refresh_token +· TTL 优先级:`fin_app.token_ttl_seconds`(应用级,非空)覆盖 `fin_config.token.ttl_seconds`(新建应用默认值) +· 轮换:fin_app 支持同时存在 2 个有效 secret(current + prev,宽限期 24h), + 新 hash 上线、旧 hash 保留期内并行,业务侧无停机切换 +· 撤销:fin_app.enabled=0 立即全量失效;单 token 泄露可置 revoked_at 即时失效; + 重置 secret 且宽限期结束后旧 secret 换不到新 token +· 限流:按 app_code + IP 双维度 +· 严禁把 access_token 下发到浏览器或写入前端产物 +``` + +### 3.2 一次性凭证(D1 的落地) +``` +业务系统服务端 → POST /tickets {business_user_id, username, phone, email} + · 若 fin_subject 不存在 → **自动建档**(同一事务 upsert fin_subject + fin_account, + phone 只存 masked + hash,账户初始 balance=0 / frozen_balance=0) + · 若 fin_subject 已存在但 status ≠ ACTIVE(FROZEN/CLOSED)→ 拒绝签发(6007) + · 生成长随机 ticket(32 字节),DB 只存 SHA-256 hash,有效期 5 分钟 +财务系统收款页 → POST /pay(表单或 307 跳转,参数 app_code/ticket/type/redirect_uri/amount_cent/vip_plan_code) + · 校验:hash 存在 / 未过期 / used_at IS NULL / app_code 匹配 + · 校验 redirect_uri 必须命中 fin_app.allowed_redirect_hosts + (主机名精确匹配、禁止通配、禁止 IP 直连、外部必须 https) + · **建单幂等**:同 (app_code, business_user_id, type, vip_plan_code) 已有未过期 PENDING 单 + → 复用该单,不重复建单(刷新 / 重复提交 / 链接预览均不产生垃圾单) + · **建单成功后才原子置 used_at**(WHERE used_at IS NULL); + 置位失败(并发已用)→ 若对应同一订单则返回订单详情,否则 7001 + · 建单失败 → 事务回滚,ticket 保持未使用,用户可重试 + · 返回 303 到 /orders/{order_no}(订单详情页);刷新、后退均展示同一订单 + · 不通过 → 400,且不回显任何内部信息 +``` + +**凭证硬规则** +1. ticket 只存 hash,明文仅返回一次,日志不落明文(nginx `$query_string` 需对 `ticket=` 做脱敏)。 +2. 有效期 5 分钟、一次性、绑定 `app_code + business_user_id`,不能跨 app。 +3. ticket 仅能打开收款页,**不能用于任何服务端扣费/查询接口**(服务端一律走 client token)。 +4. `/pay` 只接受 **POST**,禁止用 GET 产生副作用(避免爬虫、链接预览、浏览器预取批量建单); + 订单详情页用 `GET /orders/{order_no}` 只读展示。 +5. 优先使用「服务端 302/307 跳转 + POST 表单」而非把 ticket 放 URL;确需 URL 时启用日志脱敏。 +6. 最坏后果有界:他人抢先使用 → 用户收款页打不开,不能扣钱、不能改余额。 + +--- + +## 4. 核心业务流程 + +### 4.1 充值(cash 记账,D3) +``` +业务前端 → POST /pay?ticket=..&type=recharge&amount_cent=?(用户选择充值金额,点数由服务端计算) +财务系统 → 校验金额区间 + 当日累计限额(见 4.7)→ 校验 fin_subject.status=ACTIVE + → 建单 fin_order(PENDING, pay_method=offline, expires_at=now+24h, + points_per_yuan_snapshot=当前 fin_pricing.points_per_yuan) + → points_gained = floor(amount_cent / 100 × points_per_yuan_snapshot); + 不足 1 点 → 直接拒绝下单(6006),避免写入 0 点充值流水 + → 展示「应付 ¥XX / 应得 XX 点数」+ 收款指引 + 订单号 +用户线下转账 → 管理员核对到账 + → POST /admin/orders/{id}/confirm(权限 fin:recharge:confirm) +事务内(一次提交,全部成功或全部回滚): + 1. 条件更新 PENDING→PAID:UPDATE fin_order SET status='PAID', paid_at=.., confirmed_by_admin_id=.. + WHERE id=? AND status='PENDING' ← 影响行数=0 → 4093(重复确认,直接返回已确认结果) + 2. 大额阈值:优先取 fin_app_policy.dual_control_threshold_cent,NULL 时取 fin_config.review.threshold_cent; + ≥ 阈值 → 必须 second_approver_id ≠ confirmed_by_admin_id,否则拒绝(职责分离,防单人舞弊) + 3. 写 fin_cash_flow(IN, order_id, amount_cent, voucher_no) ← 现金台账,一单一条 IN(条件更新保证) + 4. 入账 wallet:先 upsert fin_account(首次开户 balance=0/frozen_balance=0),再条件更新 + UPDATE fin_account SET balance=balance+?, version_no=version_no+1 + WHERE app_code=? AND business_user_id=? AND version_no=? ← 影响行数=0 → 重试 3 次后 4092 + 5. 写 fin_transaction(type='RECHARGE', amount=points_gained, 前后快照, order_id, idempotency_key='order:{out_trade_no}') + 6. 写 fin_audit_log(操作人、前后值、IP) + 7. 写 fin_webhook_delivery(balance.changed,同事务 Outbox) +回跳 redirect_uri?order_no=..&status=paid → 业务前端刷新余额(余额以服务端查询为准) +``` + +**硬规则** +- **入账唯一入口 = 管理员确认(二期为支付回调验签)**;业务系统与前端不得直接入账。 +- **充值金额**由用户选择,但必须落在 `recharge.min_amount_cent ~ recharge.max_amount_cent` 且满足日累计限额; + **点数、VIP 价格与时长一律服务端计算**,前端传 `points_gained` / `amount_points` / 价格一律忽略。 +- 兑率公式:`points_gained = floor(amount_cent / 100 × points_per_yuan)`(`amount_cent` 是分,兑率是「每元点数」), + 向下取整、至少 1 点;`points_per_yuan_snapshot` 随订单落库,后续改价不影响已下单订单与退款折算。 +- `PENDING→PAID`、`CANCELLED` 全部用条件更新,防重复确认/重复关单。 +- 二期接微信/支付宝时只替换「管理员确认」为「支付回调验签 + 金额比对 + 写 `fin_payment_callback_log`」,其余链路不变。 + +### 4.2 开通/续费 VIP(按 app 隔离 + 档位表) +- 同 4.1 下单链路,`order_type=vip`;下单时校验 `(app_code, plan_code)` 命中 `fin_vip_plan` 且 `enabled=1`, + **价格与时长一律取自 `fin_vip_plan`(`price_cent` / `duration_days`),不接受前端或业务系统传价**。 +- 确认到账后:`vip_until = max(existing_vip_until, now) + duration_days` + 必须用 `max()`,否则续费会覆盖剩余期导致提前失效;`fin_vip.vip_plan_code` 同步为本次档位。 +- VIP 订单**不产生点数流水**,仅更新 `fin_vip`;对账时归入现金侧(见第 7 节)。 +- 免扣判定(D6):`fin_app_policy.vip_exempt=1` **且** `fin_vip.vip_until > now` **且** + 当前档位 `fin_vip_plan.free_deduction=1` 三个条件同时满足才免扣;任一不满足按正常扣费。 +- 有效性实时判定 `vip_until > now`,不依赖定时任务。 +- 档位下架(`enabled=0`):存量 VIP 继续有效到期,不可再购/续该档;改价/上下架均写审计(before/after)。 +- **VIP 退款**:仅支持全额退款(`amount_cent` = 订单金额 − 已退金额),退款生效时 `vip_until` 置为 `now()`, + 权益立即终止,不按剩余天数折算;退款不产生 `REFUND_OUT` 点数流水(`points_deducted=0`)。详见 4.4.2。 + +### 4.3 扣费(业务系统服务端调用) +``` +POST /transactions/charge (header: client token → 派生 app_code) +body: {business_user_id, business_ref_id, idempotency_key, points, remark} +事务: + 1. 参数校验(见第 5 节):points 必须为整数且 1 ≤ points ≤ max_points_per_charge; + fin_subject.status 必须为 ACTIVE(FROZEN/CLOSED → 6007) + 2. 幂等:按 (app_code, idempotency_key) 查已有流水 → 命中直接返回原结果(不重复扣、不重复扣成负数) + · 并发同键可能同时查空 → 以唯一键兜底:插入冲突时捕获 duplicate key,回读原流水返回原结果 + · 同一幂等键若请求参数不一致(points/business_ref_id 不同)→ 4091,禁止复用键改参数 + 3. fin_subject 必须存在且属于 token 的 app_code;不存在则按 3.2 自动建档; + 同时 upsert fin_account(INSERT ... ON DUPLICATE KEY UPDATE id=id),保证余额更新有行可更 + 4. 限额:当日该用户累计 CONSUME 点数 + 本次应付额 ≤ fin_config.charge.daily_points_limit_per_user,否则 6005 + 5. 实扣判定(D6,全部在财务侧事务内完成,不信任业务侧传入值): + 若 vip_exempt=1 且 fin_vip.vip_until > now 且档位 free_deduction=1 + → actual = 0,写 fin_transaction(type='CONSUME_FREE', amount=0),返回 charged_points=0 + (唯一允许 0 的路径,remark='VIP_FREE') + 否则 actual = max(points, min_cost) ← 保底消费;配置层保证 min_cost ≤ max_points_per_charge + 6. 余额校验 + 条件更新(用 actual,不用 points;必须扣除 frozen_balance): + UPDATE fin_account SET balance=balance-?, total_spent=total_spent+?, version_no=version_no+1 + WHERE app_code=? AND business_user_id=? AND version_no=? AND balance - frozen_balance >= ? + 影响行数=0 → 可用余额不足(6001) 或并发冲突(重试 3 次后 4092) → 事务回滚,无残留 + 7. 写 fin_transaction(type='CONSUME', amount=actual, 前后快照, business_ref_id, idempotency_key) + 8. 返回 {charged_points=actual, balance, frozen_balance, available_balance=balance-frozen_balance} +``` + +**硬规则** +- `app_code` **只从 token 派生,绝不读请求体**;读请求体 = A 应用伪造 app_code 扣 B 应用用户钱。 +- 业务侧传入的 `points` 只是**应付额**;`min_cost` 保底、VIP 免扣、单次上限、日累计限额的最终判定权在财务侧(D6), + 业务系统无法通过传 `points=0` 或负数绕过扣费。 +- 财务侧对 `points` 做**正整数 + 上下限强校验**(`points <= 0` 一律 6003 拒绝)。 +- 余额更新必须「条件更新 + 影响行数判断」,禁止先查后改;**可用余额 = balance − frozen_balance**, + 退款复核冻结的点数不能被扣费消费。 +- 幂等键并发语义:先查后插 + 唯一键冲突回读,二者缺一不可;禁止依赖「查不到就插入」。 +- 乐观锁冲突语义:服务端内部重试最多 3 次(20/60/120ms 退避),仍失败返回 `4092`; + 业务系统必须用**同一 `idempotency_key`** 重试,不得生成新键。 + +### 4.4 退款(点数退款 / 现金退款两条独立链路) + +#### 4.4.1 点数退款(任务失败回补,先扣后退模式才需要) +- 适用范围:仅 `type='CONSUME'` 的流水可退;`CONSUME_FREE`(0 点)不可退。 +- 校验: + 1. `refund_points` 为正整数(`≥1`,`≤0`/小数一律 6003); + 2. 原流水必须存在、`type='CONSUME'`、属于 token 的 `app_code` 与同一 `business_user_id`; + 3. `refund_points ≤ 原 CONSUME.amount - 原 CONSUME.refunded_points`(**累计**上限,不是单笔); + 4. 条件更新原流水:`UPDATE ... SET refunded_points = refunded_points + ? + WHERE id=? AND refunded_points + ? <= amount` → 影响行数=0 → `6004`(超额退款,含并发) + (该条件更新自带行锁语义,两笔并发退款只有一笔能过,杜绝「多次部分退款叠加超退」) + 5. 写 `fin_transaction(type='REFUND_IN', amount=refund_points, refund_of_id=原流水id, idempotency_key)`; + 6. 余额 `+=`(条件更新 + version_no,重试语义同 4.3); + 同时 `total_spent = total_spent - refund_points`(`total_spent` 为**净消费**口径:Σ CONSUME − Σ REFUND_IN)。 +- 幂等:退款流水同样受 `(app_code, idempotency_key)` 唯一键保护;并发同键插入冲突 → 捕获 duplicate key 并回读原结果。 +- **推荐策略仍是「失败不扣费」**:任务失败时业务系统不调 charge,无需退款,链路最短、漏洞最少。 + +#### 4.4.2 现金退款(退充值,必须人工核销) +``` +后台 FINANCE 发起 → 选择 PAID 订单 → 填退款金额(≤ 该订单累计未退金额) +前置校验: + · 订单 status=PAID(条件更新防并发) + · order_type='vip' → **仅允许全额退款**(本次 = 订单金额 − 已退金额),不允许部分退款; + order_type='recharge' → 允许部分退款,Σ(fin_refund_order WHERE status<>'REJECTED') + 本次 ≤ 原订单 amount_cent + · 点数扣回(仅 recharge):points_deducted = floor(本次金额 × 订单 points_gained / 订单 amount_cent); + 最后一笔(累计金额 = 订单金额)改为「剩余未扣回点数」,补齐取整残差; + VIP 订单 points_deducted 恒为 0 + · 可用余额 = balance − frozen_balance ≥ points_deducted;不足 → 拒绝并提示「用户已消耗部分点数,需人工核算」, + 余额绝不允许为负 +事务: + 1. 写 fin_refund_order(PENDING, amount_cent, points_deducted, operator_admin_id, completed_at=NULL) + 2. **冻结点数**(仅 recharge,points_deducted>0): + UPDATE fin_account SET frozen_balance=frozen_balance+? + WHERE app_code=? AND business_user_id=? AND balance - frozen_balance >= ? + 影响行数=0 → 6001(可用余额不足),整单回滚 + 3. 金额 < 双人复核阈值:直接 COMPLETED;≥ 阈值:等待另一管理员复核(reviewer ≠ operator) + 4. 生效时(COMPLETED, completed_at=now): + · recharge:UPDATE fin_account + SET balance=balance-?, frozen_balance=frozen_balance-?, version_no=version_no+1 + WHERE ... AND frozen_balance>=? AND balance>=? + + 写 REFUND_OUT 流水(amount=points_deducted,order_id=原订单,idempotency_key) + + REFUND_OUT **不回冲 total_spent**(退的是未消费余额,不是消费撤销) + · vip:不写点数流水;UPDATE fin_vip SET vip_until=now()(权益立即终止,不按天折算) + · 写 fin_cash_flow(OUT, order_id, amount_cent, voucher_no) ← 现金台账,凭银行回单号 + 5. REJECTED 时释放冻结:`frozen_balance = frozen_balance - points_deducted`(条件更新,防重复释放) + 6. 全部退款时订单 PAID→REFUNDED(条件更新);部分退款订单保持 PAID,已退金额以 fin_refund_order 汇总为准 + 7. 审计:发起人、复核人、前后状态、凭证号全量写 fin_audit_log +``` +- **硬规则**:`REFUNDED` 只能由本流程置位;`fin_refund_order.status` 单向 + `PENDING → COMPLETED / REJECTED`;现金退还必须登记银行凭证号,禁止「只改状态不核销」。 +- 退款复核期间点数必须冻结(`frozen_balance`),否则用户可在等待复核时把余额消费掉,导致退款无法落地。 +- `completed_at` 为现金侧对账的唯一时间基准,PENDING/REJECTED 必须为 NULL,COMPLETED 必须非空。 +- 退款完成后向业务系统投递 `order.refunded` webhook(见 4.6),业务侧回查权威数据刷新展示。 + +### 4.5 订单关单(MVP 必须有) +- `fin_order.expires_at` 默认 24h;定时任务(每 10 分钟): + `UPDATE fin_order SET status='CANCELLED' WHERE status='PENDING' AND expires_at < now()`(条件更新,防误杀已支付单) +- 后台可手动关单(权限 `fin:order:cancel`),同样条件更新。 +- 二期接入在线支付后,关单前必须先向支付通道查单,避免「用户已付款但订单被关」。 + +### 4.6 webhook(可靠投递 + 可验证) +- 事件:`balance.changed`、`order.paid`、`order.refunded`、`vip.changed`。 +- 投递:与业务事务同库写入 `fin_webhook_delivery`(Outbox 模式),由独立投递任务发送。 +- 签名:`X-Fin-Event-Id`、`X-Fin-Timestamp`、`X-Fin-Signature = HMAC-SHA256(timestamp + "." + body, webhook_secret)`。 +- **时间戳与签名必须在每次实际发送时重新生成**(含所有重试),禁止复用入队时的 timestamp/签名, + 否则 2h/6h/24h 后的重试必然超出接收方 5 分钟时间窗而被拒绝;`fin_webhook_delivery.signature` 仅保留最近一次发送签名。 +- 接收方必须校验:签名、时间戳偏差 ≤ 5 分钟、`event_id` 去重(幂等)。 +- 重试:1m / 5m / 30m / 2h / 6h / 24h,共 6 次;仍失败置 `DEAD` 并告警(后台可手动重放)。 +- 同一 `event_id` 的重放必须保持 payload 不变;事件可能乱序到达,接收方必须以 `event_id` + 服务端回查为准,不得依赖到达顺序。 + +### 4.7 全局运行参数(fin_config) + +| config_key | 默认值 | 说明 | +|---|---|---| +| `order.pending.timeout_hours` | 24 | PENDING 订单超时关单(对公转账晚到可调至 72) | +| `review.threshold_cent` | 500000 | 双人复核金额阈值(分,默认 ¥5000);`fin_app_policy` 值非 NULL 时优先 | +| `admin.lock.threshold` | 5 | 登录失败锁定次数 | +| `admin.lock.minutes` | 15 | 锁定时长 | +| `ticket.ttl_minutes` | 5 | ticket 有效期 | +| `token.ttl_seconds` | 900 | client token 有效期(新建应用默认值) | +| `secret.rotate.grace_hours` | 24 | secret 轮换宽限期 | +| `charge.retry.max` | 3 | 乐观锁冲突服务端重试次数 | +| `webhook.max_retry` | 6 | webhook 最大重试次数 | +| `recharge.min_amount_cent` | 100 | 单笔最低充值金额(分,默认 ¥1) | +| `recharge.max_amount_cent` | 5000000 | 单笔最高充值金额(分,默认 ¥5 万) | +| `recharge.daily_limit_cent_per_user` | 20000000 | 单用户单 app 日累计充值上限(分,默认 ¥20 万) | +| `charge.daily_points_limit_per_user` | 100000 | 单用户单 app 日累计扣费点数上限 | +| `pii.mask.enabled` | 1 | PII 掩码开关(默认开,禁止关闭) | + +- 变更需 SUPER_ADMIN 权限 + `fin_audit_log` 留痕;`pii.mask.enabled=0` 属高危变更,只允许在运维窗口临时开启并告警。 + +### 4.8 报价与余额查询(业务侧「预检展示」的落地) + +业务系统只做预检展示,必须有只读接口,否则前端无法判断「余额够不够、这次要扣多少」: + +``` +GET /accounts/{business_user_id}/balance (client token → 派生 app_code) + → {balance, frozen_balance, available_balance, vip_until, vip_plan_code, charging_enabled, updated_at} + +POST /transactions/quote (client token) + body: {business_user_id, points} + → {points, min_cost, effective_points, free, vip_applied, available_balance, enough} +``` + +- 报价接口**无副作用**,不写流水、不锁余额、不自动建档;subject 不存在时返回 404 或零余额视图。 + 结果仅供展示,最终实扣以 4.3 事务内判定为准。 +- `effective_points = max(points, min_cost)`;VIP 免扣时 `free=true, effective_points=0`。 +- `enough = available_balance >= effective_points`(已扣除 `frozen_balance`)。 +- `charging_enabled=false` 表示 subject 冻结 / app 停用 / 策略关闭,业务侧应禁止发起任务。 + +--- + +## 5. 校验规则矩阵(服务端强制,前端仅体验层) + +| 字段 | 规则 | 失败错误码 | +|---|---|---| +| `points`(扣费) | 整数,**1 ≤ points ≤ max_points_per_charge**;`≤0`、小数、字符串、NaN、超上限一律拒绝;实扣 = max(points, min_cost);仅 `vip_exempt=1` 且 VIP 有效且档位 `free_deduction=1` 时允许 `CONSUME_FREE(amount=0)`;日累计不得超过 `charge.daily_points_limit_per_user` | 6002 / 6003 / 6005 | +| `refund_points` | 整数 ≥ 1,且累计 ≤ 原扣费金额 | 6003 / 6004 | +| `amount_cent`(充值) | 由用户在服务端允许区间内选择:整数,`recharge.min_amount_cent ≤ amount_cent ≤ recharge.max_amount_cent`,并满足日累计限额;**点数由服务端按 `points_per_yuan_snapshot` 计算**,前端传 `points_gained`/`amount_points`/价格一律忽略或拒绝 | 422 / 6006 | +| `plan_code` | 必须命中同 `app_code` 的 `fin_vip_plan` 且 `enabled=1`;价格与时长服务端取表,不读前端 | 400 / 4001 | +| `idempotency_key` | 8~128 位,`[A-Za-z0-9:_-]`,业务系统必须带命名空间前缀(如 `litho:task:123456`);同键同 app 只生效一次,同键不同参数拒绝 | 4091 | +| `business_user_id` | 1~64 位,`[A-Za-z0-9_-]`;subject 状态必须 ACTIVE | 422 / 6007 | +| `business_ref_id` | ≤ 64 位,仅用于追溯,不参与资金决策 | 422 | +| `redirect_uri` | 必须命中 `allowed_redirect_hosts`(精确主机名);外部 `https`;内网 http 需显式放行 | 400 | +| `ticket` | 32 字节随机;仅存在于 POST 表单/受控 URL,不得出现在日志明文 | 7001 | +| `voucher_no` | 现金台账必填(银行回单/转账凭证号),1~64 位;同一订单的 IN/OUT 分别登记 | 422 | +| 分页/查询 | `page_size ≤ 100`,倒序分页;禁止无界全表扫描 | 422 | +| JSON 请求体 | 拒绝嵌套深度 > 5、字段数 > 50、单字段 > 4KB(防滥用) | 413 | + +> 一律使用「白名单校验 + 服务端重算」;任何来自前端/业务的金额、点数、状态、app_code 均不得直接采信。 + +### 5.1 错误码总表 + +| 错误码 | 含义 | 典型场景 | +|---|---|---| +| `400` / `422` | 参数非法 | 字段缺失、类型错误、越界、金额不在允许区间 | +| `4001` | VIP 档位无效 | plan_code 不命中 / 已下架 | +| `403` | 无权限或 app 不匹配 | token 属于 A 应用却操作 B 应用数据 | +| `4091` | 幂等键冲突 | 同键不同参数、键格式非法 | +| `4092` | 并发冲突 | 乐观锁重试 3 次仍失败 | +| `4093` | 重复确认 | 订单已非 PENDING | +| `413` | 请求体过大/过深 | 防滥用 | +| `429` | 触发限流 | 带 `Retry-After` | +| `6001` | 可用余额不足 | `balance − frozen_balance < 实扣` | +| `6002` | 超过单次扣费上限 | `points > max_points_per_charge` | +| `6003` | 点数非法 | `≤0`、小数、NaN、字符串 | +| `6004` | 超额退款 | 累计退款 > 原扣费 | +| `6005` | 超过日累计扣费限额 | `charge.daily_points_limit_per_user` | +| `6006` | 充值金额非法/超限额 | 低于最低、超过单笔或日累计上限、折算不足 1 点 | +| `6007` | 用户不可扣费 | subject FROZEN/CLOSED、app 停用 | +| `7001` | ticket 无效 | 过期、已用、跨 app、哈希不存在 | +| `500` | 内部错误 | 响应不含堆栈/SQL/主机名 | + +--- + +## 6. 并发、幂等与事务语义 + +| 场景 | 机制 | +|---|---| +| 重复扣费 | `(app_code, idempotency_key)` 唯一键;命中即返回原结果 | +| 同键并发插入 | 先查后插 + **捕获 duplicate key 回读原结果**;同键不同参数返回 4091 | +| 余额并发 | 条件更新 + 影响行数判断 + `version_no`;内部重试 3 次后返回 4092 | +| 首次开户并发 | `INSERT ... ON DUPLICATE KEY UPDATE id=id` upsert subject/account,禁止「先查再插」 | +| 重复确认到账 | `WHERE status='PENDING'` 条件更新;影响 0 行直接返回已确认结果 | +| 重复退款 | 原流水 `refunded_points` 条件更新 + 退款流水幂等键 | +| 现金退款并发/累计超退 | 事务内 `Σ(fin_refund_order)` 求和 + 订单行 `SELECT ... FOR UPDATE` + 状态条件更新 | +| 退款复核期冻结 | `frozen_balance` 条件更新(`balance − frozen_balance >= ?`);COMPLETED 扣减、REJECTED 释放,禁止重复释放 | +| ticket 并发重放 | `WHERE used_at IS NULL` 原子置位;建单成功后才置位,失败回滚 | +| 审计哈希链并发 | 写入前 `GET_LOCK('fin_audit_chain', 3)` 串行化(或单写队列),取上一条 `cur_hash` 作为 `prev_hash`,禁止并发生成 | +| 事务边界 | 资金变更与流水、订单状态、现金台账、审计、webhook Outbox **同一事务**;禁止跨事务「先改余额后写流水」 | +| 隔离级别 | REPEATABLE READ;事务内不加远程调用(webhook 仅写 Outbox,异步发送) | +| 死锁预防 | 固定加锁顺序:order → refund_order → cash_flow → account → transaction → audit | + +--- + +## 7. 对账(量纲分离,避免天生不平) + +**时间基准(唯一口径,避免跨期假差异)** +- 现金侧一律以 `fin_cash_flow.received_at` 落入窗口为准;退款单以 `fin_refund_order.completed_at` 为准。 +- 订单侧只作为「关联金额」使用,不按 `fin_order.create_time` 归期;另出一张 `paid_at` vs `received_at` + 的跨期差异报表(管理口径,不参与平账判定)。 + +**现金侧(按 app + 时间窗,订单维度)** +``` +每个 status ∈ (PAID, REFUNDED) 的订单在全生命周期恰有 1 条 direction='IN' 的 cash_flow, + 且该 IN.amount_cent == 订单 amount_cent ← 逐单不变量 +窗口内:Σ fin_cash_flow(direction='IN', received_at ∈ 窗口).amount_cent + == Σ 上述 IN 所关联订单的 amount_cent +窗口内:Σ fin_cash_flow(direction='OUT', received_at ∈ 窗口).amount_cent + == Σ fin_refund_order(status='COMPLETED', completed_at ∈ 窗口).amount_cent +单订单:Σ(IN) − Σ(OUT) ≥ 0;status='REFUNDED' ⇔ Σ(OUT)=Σ(IN); + status='PAID' 允许部分退款(OUT= amount`,否则拒绝(6001)。 +- 附加校验:每笔 RECHARGE 流水 `amount == 关联订单 points_gained`,否则视为算错账,直接 P1。 + +--- + +## 8. 后台安全(资金唯一入账口) + +| 项 | 要求 | +|---|---| +| 密码存储 | Argon2id(首选)或 bcrypt cost ≥ 12;禁止 MD5/SHA1/明文 | +| 登录限流 | 5 次/分钟/IP + 账号级 5 次失败锁定 15 分钟(`failed_attempts`/`locked_until`) | +| 2FA | 确认入账、退款、定价变更、应用密钥管理 **强制 TOTP**;签发 10 个一次性恢复码(只存哈希),用尽或丢失需 SUPER_ADMIN 重置并写审计 | +| 会话 | 服务端 Session 存 Redis,Cookie `HttpOnly + Secure + SameSite=Strict`,写操作校验 CSRF Token;30 分钟空闲超时;登录 IP 变更告警;(可选)后台 IP 白名单 | +| 权限 | `fin:view` / `fin:recharge:confirm` / `fin:refund:create` / `fin:pricing:edit` / `fin:app:manage` / `fin:audit:view` / `fin:order:cancel` | +| 职责分离 | 修改定价者 ≠ 确认到账者(系统校验);大额订单(≥ 阈值)必须双人复核(`second_approver_id ≠ confirmed_by_admin_id`) | +| 审计 | 全部资金写操作写 `fin_audit_log`;哈希链(`prev_hash/cur_hash`)只增不改;导出需 `fin:audit:view` + 审计留痕 | +| 数据导出 | 用户/流水导出需二次确认 + 水印 + 审计;单次导出上限 1 万行 | + +### 8.1 初始账号(禁止「首个登录者成为超管」) + +- 后台**无注册流程**,无法采用「首位登录者自动成为超管」(存在被抢注竞态)。采用 **SQL 种子超管**: + +```sql +INSERT INTO fin_admin (id, username, password_hash, role, is_active, must_change_password, is_delete, create_time) +VALUES (1, 'admin', '<部署时用强随机口令生成的 Argon2id/bcrypt 哈希>', 'SUPER_ADMIN', 1, 1, 1, NOW()); +``` + +- 初始口令**线下交付**(不进 Git/文档/聊天记录),首次登录 `must_change_password=1` 时仅放行改密接口,其余接口一律 403。 +- 其余管理员只能由 SUPER_ADMIN 在后台创建;创建/停用/改角色全部写审计。 + +### 8.2 三角色职责分离矩阵(D5,防内部舞弊) + +| 操作 | SUPER_ADMIN | FINANCE | AUDITOR | +|---|---|---|---| +| 管理员管理 / 应用注册 / secret 重置 / 定价与档位编辑 / 全局配置 | ✓ | ✗ | ✗ | +| 充值确认 / 现金退款发起 | ✗ | ✓ | ✗ | +| 大额复核(第二人) | ✓(不得与发起人同人) | ✓(不得与发起人同人) | ✗ | +| 流水 / 对账 / 订单查询与导出 | ✓ | ✓ | ✓(只读) | + +**铁律**:改兑率/定价的人(SUPER_ADMIN)不能确认到账;确认到账的人(FINANCE)不能改价。 +「改价 + 确认入账」闭环 = 内部洗钱路径,权限层直接斩断,且服务端二次校验(不依赖前端隐藏按钮)。 + +### 8.3 密码与会话策略 + +- 密码:Argon2id(首选)或 bcrypt cost ≥ 12;长度 ≥ 12,含大小写/数字/符号;改密不得与最近 3 次相同。 +- 首次登录强制改密;改密后全端会话失效。 +- 连续失败 5 次(30 分钟窗口)锁定 15 分钟,锁定期间正确口令也拒绝;成功登录清零计数。 +- 登录成功/失败均写 `fin_audit_log`(含 IP/UA),可追溯爆破来源。 + +--- + +## 9. 数据安全、隐私与合规 + +- **PII 最小化(MVP 即生效)**:`fin_subject` 不存明文手机号/邮箱,只存 `phone_masked`(138****8000)与 + `phone_hash`(服务端 pepper 的 HMAC-SHA256,用于精确匹配),邮箱同理;用户名快照仅用于展示。 +- **日志脱敏**:nginx 与业务日志对 `ticket=`、`client_secret`、`Authorization`、`Cookie` 做掩码; + 错误响应不返回堆栈、SQL、内部主机名。输出密钥一律 ``。 +- **密钥管理**:`client_secret` 只存**哈希**(BCrypt/Argon2id,比对时不可逆);`webhook_secret` 因验签需要原文, + 改为**加密存储**(`webhook_secret_enc`,AES-256-GCM,主密钥来自环境变量/外部密钥文件),仅在投递时内存解密; + 支付商户密钥、DB 口令一律环境变量或外部密钥文件,不入 Git、不下发前端;每 90 天轮换一次(含双密钥并行窗口)。 +- **日志脱敏配置(nginx 示例,部署必做)**: + +```nginx +# 将 ticket 参数替换为 ,避免一次性凭证落访问日志 +set $safe_args $args; +if ($args ~ "^(.*)ticket=[^&]*(.*)$") { set $safe_args "$1ticket=$2"; } +log_format fin '$remote_addr - $remote_user [$time_local] "$request_method $uri?$safe_args" ' + '$status $body_bytes_sent "$http_referer" "$http_user_agent"'; +access_log /var/log/nginx/fin_access.log fin; +``` + +- **日志保留**:访问日志与应用日志 ≥ 180 天(等保三级要求),目录权限收紧(仅运维可读)。 +- **监控告警**:对账不平、webhook 连续失败、管理员锁定、限流高频、`balance` 试图为负(CHECK 拦截计数)全部接入告警。 +- **数据库权限**:应用账号仅本 schema DML,禁止 DDL/DROP/GRANT;`fin_audit_log` 只允许 INSERT;访问白名单仅应用服务器 IP。 +- **传输**:对外强制 HTTPS(HSTS);内网 HTTP 仅限隔离网段。 +- **备份**:每日全量 + binlog,保留 30 天;每季度做一次恢复演练(RPO ≤ 15 分钟,RTO ≤ 2 小时)。 +- **保留期**:流水与审计保留 ≥ 3 年;超期归档而非物理删除。 +- **注销与删除权(PIPL)**:业务系统注销用户时,`fin_subject.status` 置 CLOSED、立即清空手机/邮箱掩码与哈希; + 资金流水与审计按 3 年留存,但用户标识替换为不可逆假名(如 `deleted:{sha256(app_code|business_user_id|salt)}`), + 既满足删除权,也不破坏对账链。注销、脱敏操作必须写审计。 + +--- + +## 10. 限流与可用性 + +| 接口 | 限流 | +|---|---| +| `POST /auth/business-token` | 10 次/分钟/app_code + 20 次/分钟/IP | +| `POST /tickets` | 30 次/分钟/app_code | +| `POST /pay` | 60 次/分钟/IP(防 ticket 爆破扫描;GET 仅允许订单详情) | +| `GET /accounts/{id}/balance` | 600 次/分钟/app_code | +| `POST /transactions/quote` | 600 次/分钟/app_code | +| `POST /transactions/charge` | 300 次/分钟/app_code,单用户 60 次/分钟 | +| `POST /transactions/refund` | 30 次/分钟/app_code | +| `POST /admin/login` | 5 次/分钟/IP | +| 后台其它接口 | 120 次/分钟/会话 | +| 超限 | 429 + `Retry-After`;连续超限 10 分钟触发告警;限流必须用 Redis 等集中存储实现,多副本共享计数 | + +--- + +## 11. 风险清单(v2.1 状态) + +| # | 场景 | 规则 | 状态 | +|---|---|---|---| +| 1 | 负数/零点数扣费 | 正整数强校验 + DB CHECK + 免扣独立类型 | 已修复 | +| 2 | 累计超额退款 | `refunded_points` 条件更新累计校验 | 已修复 | +| 3 | 对账量纲混用/VIP 漏算 | 现金侧与点数侧拆分为两条公式 | 已修复 | +| 4 | 幂等键跨 app 碰撞 | 唯一键改 `(app_code, idempotency_key)` + 命名空间规范 | 已修复 | +| 5 | 开放重定向 | `allowed_redirect_hosts` 精确白名单 | 已修复 | +| 6 | subject 缺失导致首扣失败 | 首次 ticket/扣费自动建档(upsert) | 已修复 | +| 7 | VIP 免扣字段不存在 | 独立 `fin_app_policy.vip_exempt` | 已修复 | +| 8 | client token 生命周期空白 | 15 分钟 TTL + 双密钥轮换 + 撤销 | 已修复 | +| 9 | webhook 无签名/无重试 | HMAC 签名 + 时间戳 + Outbox 重试 | 已修复 | +| 10 | 管理员安全空白 | 2FA + 锁定 + 职责分离 + 双人复核 + 审计链 | 已修复 | +| 11 | 线下退款无流程 | 退款单 + 现金台账 + 双人复核 | 已修复 | +| 12 | PENDING 订单滞留 | 24h 过期 + 定时关单 + 手动关单 | 已修复 | +| 13 | PII 裸奔 | 手机/邮箱 masked + hash,MVP 生效 | 已修复 | +| 14 | ticket 落 nginx 日志 | 日志脱敏 + 优先 POST 跳转 | 已修复 | +| 15 | 乐观锁冲突语义不明 | 内部重试 3 次 / 4092 + 同键重试约定 | 已修复 | +| 16 | 对账快照不一致 | 一致性快照 + `snapshot_at` 过滤 | 已修复 | +| 17 | 并发扣成负数 | 条件更新 + `balance >= ?` + DB CHECK | 已修复 | +| 18 | **ADJUST 方向二义**(金额恒正但需要带符号调整) | 拆 `ADJUST_IN` / `ADJUST_OUT`,恒等式按方向展开 | 已修复(v2.1) | +| 19 | **兑率单位错 + 取整未定义**(分与元混用、可算出 0 点) | `floor(amount_cent/100 × rate)`,至少 1 点,`points_per_yuan_snapshot` 落库 | 已修复(v2.1) | +| 20 | **新用户无账户行**(首充/首扣更新 0 行 → 4092) | 建档同事务 upsert `fin_subject` + `fin_account` | 已修复(v2.1) | +| 21 | **同键并发幂等竞态**(先查后插,冲突未处理) | 唯一键兜底 + duplicate key 回读 + 同键不同参数拒绝 | 已修复(v2.1) | +| 22 | **VIP 订单退款语义缺失**(退款后仍享权益 / `REFUND_OUT` 撞 `amount>0`) | VIP 仅全额退款,退款即 `vip_until=now()`,不写点数流水 | 已修复(v2.1) | +| 23 | **退款点数折算无快照 / 复核期未冻结** | 按订单 `points_gained/amount_cent` 比例折算 + 最后一笔补齐;`frozen_balance` 冻结 | 已修复(v2.1) | +| 24 | **对账时间基准不明 / 缺 `completed_at`** | 现金侧统一按 `received_at`、退款按 `completed_at`,差异落 `fin_recon_diff` | 已修复(v2.1) | +| 25 | **`total_spent` 口径未定义** | 定义为净消费 `Σ CONSUME − Σ REFUND_IN`,`REFUND_OUT` 不回冲 | 已修复(v2.1) | +| 26 | **业务侧无预检接口** | 新增 `GET balance` / `POST quote`(4.8) | 已修复(v2.1) | +| 27 | **`/pay` GET 有副作用 / 票建单非原子** | 改 POST + 建单幂等 + 建单成功后再置位 ticket | 已修复(v2.1) | +| 28 | **无充值/扣费频次限额** | 单笔上下限、日累计充值/扣费上限(4.7) | 已修复(v2.1) | +| 29 | **webhook 重试复用旧签名必被拒** | 每次发送重取 timestamp 并重签(4.6) | 已修复(v2.1) | +| 30 | **审计哈希链并发断链 / BIZ 无来源标识** | `GET_LOCK` 串行化 + `actor_app_code` | 已修复(v2.1) | + +--- + +## 12. 漏洞修复追踪表(对应评审意见逐条) + +| 级别 | 评审问题 | 修复条款 | +|---|---|---| +| 高危 1 | 负数/零点数免费充值 | 第 5 节校验矩阵、4.3 步骤 1/4、2.3 DB CHECK | +| 高危 2 | 退款「单次」而非「累计」上限 | 4.4 累计校验 + `refunded_points` 条件更新 | +| 高危 3 | 对账漏 VIP 订单、量纲错 | 7 现金侧/点数侧两条公式 | +| 高危 4 | idempotency_key 无 app 作用域 | 2.1/2.3 唯一键二元组 + 第 5 节键命名空间 | +| 高危 5 | redirect_uri 无白名单 | 2.1 `allowed_redirect_hosts` + 3.2 校验 | +| 中危 1 | fin_subject 创建时机未定义 | 3.2 / 4.3 步骤 3 自动建档 | +| 中危 2 | VIP 免扣字段不存在 | 2.1 `fin_app_policy.vip_exempt` | +| 中危 3 | client token 生命周期空白 | 3.1 TTL/轮换/撤销 | +| 中危 4 | webhook 无签名无重试 | 4.6 HMAC + Outbox 重试 | +| 中危 5 | 管理员安全空白 | 8 后台安全 | +| 中危 6 | 线下退款无核销流程 | 4.4.2 现金退款单 + 凭证号 + 双人复核 | +| 中危 7 | 无订单关单机制 | 4.5 过期关单 | +| 中危 8 | PII 脱敏排到三期 | 9 PII 最小化提前到 MVP | +| 低危 1 | ticket 进 URL 日志 | 3.2 规则 5 + 9 nginx 脱敏 | +| 低危 2 | /pay 与后台登录未限流 | 10 限流表 | +| 低危 3 | 乐观锁重试语义未定义 | 4.3 硬规则 / 6 | +| 低危 4 | 对账需时间点快照 | 7 执行规则 | + +**本版自查补充修复(评审未提但会导致算错钱/对不平)** + +| # | 问题 | 修复 | +|---|---|---| +| A | 点数退款(回补)与现金退款(扣回)共用 `REFUND` 一个类型,方向二义,余额恒等式无法成立 | 拆为 `REFUND_IN` / `REFUND_OUT`,方向由 type 唯一确定(2.1、4.4、7、DDL CHECK) | +| B | VIP 档位价格挂在 `fin_pricing.scope`,无法表达任意档位与免扣开关 | 独立 `fin_vip_plan`,价格/时长/`free_deduction` 全在档位表(D4、4.2) | +| C | `fin_cash_flow(order_id, direction)` 唯一键会与「多次部分退款」冲突,导致第二次退款无法落账 | 改普通索引,一单一条 IN、可多条 OUT,累计校验靠 `fin_refund_order` 求和 | +| D | client token 只说了「存 hash」但没有表,撤销与熔断无落地载体 | 新增 `fin_app_token` 表(只存 hash + `revoked_at`) | +| E | `webhook_secret` 需原文验签,不能像 `client_secret` 一样只存哈希 | 改为 `webhook_secret_enc` 加密存储,投递时内存解密 | +| F | 业务侧传 `points=1` 可绕过保底 `min_cost`,少付钱 | 实扣 = `max(points, min_cost)` 由财务侧判定(D6、4.3、附录验收 20) | + +**v2.1 复审修复追踪(本轮新增)** + +| # | 问题 | 修复条款 | +|---|---|---| +| G | `ADJUST` 只有单类型,余额恒等式却要求带符号 | 拆 `ADJUST_IN` / `ADJUST_OUT`(2.1、2.3、7、DDL CHECK) | +| H | 兑率公式把「分」当「元」,且未定义取整/最小点数 | 改为 `floor(amount_cent/100 × rate)`、至少 1 点、`points_per_yuan_snapshot` 落库(4.1、2.1、DDL) | +| I | 新用户只建 subject 不建 account,首充/首扣更新 0 行 | 建档同事务 upsert subject + account(3.2、4.1、4.3、6) | +| J | 同键并发「先查后插」会漏掉唯一键冲突 | duplicate key 回读 + 同键不同参数 4091(4.3、4.4.1、6) | +| K | VIP 退款未定义,且 `points_deducted=0` 写 `REFUND_OUT` 违反 CHECK | VIP 仅全额退款、退款即失效、不写点数流水(4.2、4.4.2、2.3) | +| L | 退款点数折算用当前兑率,部分退款取整无规则 | 用订单快照按比例折算、最后一笔补齐(4.4.2、2.3) | +| M | 退款复核期余额未冻结,复核通过时可能余额不足 | `frozen_balance` 冻结 + 可用余额扣减(4.4.2、4.3、6、DDL) | +| N | 对账「窗口内」未定义时间字段,退款单无 `completed_at` | 现金按 `received_at`、退款按 `completed_at`(7、2.1、DDL) | +| O | `total_spent` 在退款时是否回冲未定义 | 定义为净消费 `Σ CONSUME − Σ REFUND_IN`,`REFUND_OUT` 不回冲(7、4.4) | +| P | 阈值与 token TTL 双配置二义;`failed_strategy` 无定义;`min_cost` 可大于单次上限 | 明确优先级 + 补语义 + CHECK `min_cost <= max_points_per_charge`(4.7、2.1、DDL) | +| Q | 业务侧无预检接口(余额/报价) | 新增 4.8 两个只读接口 | +| R | `/pay` 用 GET 建单,ticket 先置位后建单,刷新即 7001 | 改 POST + 建单幂等 + 建单成功后再置位 + 订单详情页(3.2) | +| S | 无充值/扣费频次限额 | 单笔上下限 + 日累计上限(4.7、5、4.1、4.3) | +| T | webhook 重试复用入队时间戳,必然超时被拒 | 每次发送重取 timestamp 并重签(4.6) | +| U | 审计哈希链并发断链;BIZ 来源无法记录 | `GET_LOCK` 串行化 + `actor_app_code`(6、2.1、DDL) | +| V | 文档引用不存在的小节、幂等键长度不一致、webhook 状态机多余状态 | 全部对齐(5.1、5、2.1、DDL) | +| W | 二期支付无落库字段 | `fin_order.third_party_trade_no` + `fin_payment_callback_log`(2.1、4.1、DDL) | +| X | subject 无冻结/注销状态语义 | ACTIVE/FROZEN/CLOSED + 注销脱敏(2.1、4.3、9) | + +--- + +## 13. 验收标准(含攻击用例,全部必须通过) + +**功能** +- 充值:下单 → 管理员确认 → 余额增加 → 流水正确 → webhook 送达并验签通过。 +- VIP:续费后 `vip_until = max(原到期, 现在) + 档位`,不出现提前失效。 +- 关单:PENDING 超 24h 自动 CANCELLED,已支付订单不被误关。 + +**安全/边界(渗透用例)** +| # | 用例 | 期望 | +|---|---|---| +| 1 | `points = -100` 扣费 | 400 / 6003,余额与流水均无变化 | +| 2 | `points = 0`(无 VIP 免扣) | 400 / 6003 | +| 3 | `points = 999999` 超上限 | 6002 拒绝并告警 | +| 4 | 同一 `idempotency_key` 并发 100 次 | 只扣 1 次,其余返回同一结果 | +| 5 | 余额仅够 1 次,100 个不同键并发 | 1 成功 + 99 次 6001,余额恰为 0,无负数 | +| 6 | 单笔退款 > 原扣费 | 6004 | +| 7 | 多次部分退款累计 > 原扣费(含并发) | 6004,累计退款恰等原额为止 | +| 8 | A 应用 token 扣 B 应用用户 | 403,`app_code` 以 token 为准 | +| 9 | `redirect_uri=https://evil.com` | 400 拒绝 | +| 10 | ticket 重放 / 过期 / 跨 app | 7001 | +| 11 | 重复确认同一订单 / 重复退款 | 余额只变一次 | +| 12 | 篡改 webhook body 或超时重放 | 业务侧验签/时间窗拒绝 | +| 13 | 后台连续输错密码 6 次 | 账号锁定 15 分钟,返回统一错误文案 | +| 14 | 单人确认大额订单(≥ 阈值) | 拒绝,提示需双人复核 | +| 15 | 定价修改者确认自己改价后的订单 | 拒绝(职责分离) | +| 16 | 请求体塞入浮点/字符串/超长/深层嵌套 | 422/413,不落库 | +| 17 | 对账含 VIP 成交 | 现金侧、点数侧各自平账 | +| 18 | 同一订单多次部分现金退款,累计超订单金额 | 第二次起拒绝,累计退款 ≤ 订单金额 | +| 19 | 前端伪造 VIP 档位价格/时长 | 服务端取 `fin_vip_plan`,伪造无效,订单金额以服务端为准 | +| 20 | 业务侧传 `points=1` 而 `min_cost=100` | 实扣 100(保底生效),返回实扣值,业务侧不可绕过 | +| 21 | 同一 `idempotency_key` 两个请求同时插入(绕过先查) | 唯一键冲突 → 回读原流水,只产生 1 条流水、只扣 1 次 | +| 22 | 全新用户首次直接扣费(从未签发 ticket) | 自动建档 subject + account,扣费成功,无 4092 | +| 23 | VIP 订单申请部分退款 | 拒绝;全额退款后 `vip_until=now()`、无 `REFUND_OUT` 流水 | +| 24 | 一笔充值分 3 次退款(金额除不尽) | 前两次向下取整、最后一次补齐,累计扣回点数恰等于订单点数 | +| 25 | 退款单 PENDING 期间用户发起扣费至余额不足 | 冻结生效,可用余额不足 → 6001,退款仍可正常 COMPLETED | +| 26 | webhook 第 5 次重试(2h 后) | 使用新 timestamp 重签,接收方验签通过 | +| 27 | 订单跨日支付(23:50 转账、次日确认) | 现金侧按 `received_at` 归期,对账平;跨期差异报表单独输出 | +| 28 | 单用户当日扣费超过 `charge.daily_points_limit_per_user` | 6005 拒绝,余额不变 | + +--- + +## 14. 上线门槛(MVP Checklist) + +- [ ] 附录 A 的 19 张表建表 SQL 全部落地(app / token / admin / subject / ticket / account / vip / vip_plan / order / cash_flow / refund_order / transaction / app_policy / pricing / config / webhook / payment_callback / recon_diff / audit) +- [ ] 增量 SQL 落库(`sql/` 目录,含 CHECK、唯一键、索引),确认 MySQL ≥ 8.0.16 使 CHECK 生效 +- [ ] 种子数据:SUPER_ADMIN(8.1)+ `fin_config` 默认值(4.7) +- [ ] 扣费/退款/确认到账/报价/余额查询接口的攻击用例全部自动化测试通过 +- [ ] 后台 2FA(含恢复码)+ 锁定 + 职责分离 + 会话/CSRF 可用 +- [ ] webhook HMAC 签名(每次重签)+ 重试队列可用 +- [ ] 退款冻结(`frozen_balance`)与释放路径验证通过 +- [ ] 日志脱敏(ticket、secret、cookie)验证通过 +- [ ] 对账脚本 + `fin_recon_diff` + 告警可用,含 VIP 与跨期场景 +- [ ] 技术栈按第 16 节落地,OpenAPI 描述随版本发布 +- [ ] 备份与恢复演练一次 + +--- + +## 15. 遗留待定(业务运营取值,不阻塞开发) + +- [ ] `points_per_yuan` 兑率(1 元 = 多少点数,写入 `fin_pricing`) +- [ ] 各 app VIP 档位定义(档位编码、时长、价格、是否免扣,写入 `fin_vip_plan`) +- [ ] `min_cost` 各 app 单次任务基准费用(写入 `fin_app_policy`) +- [ ] `max_points_per_charge` 单 app 单次扣费上限(写入 `fin_app_policy`) +- [ ] `dual_control_threshold_cent` 双人复核金额阈值(默认 ¥5000;`fin_app_policy` 留 NULL 表示继承 `fin_config`) +- [ ] 充值单笔上下限与日累计限额(写入 `fin_config`,见 4.7) +- [x] 后台管理员初始账号:已定(8.1 种子超管 + 强制改密 + 绑定 2FA) + +> 以上取值由各应用业务方在上线前提供,系统默认值仅为可跑通闭环的安全下限。 + +--- + +## 16. 技术栈与组件选型(v2.1 新增) + +### 16.1 基线技术栈(MVP,模块化单体) + +| 层 | 选型 | 版本基线 | 说明 | +|---|---|---|---| +| 语言 | Java | 21 LTS | 与 MySQL/Spring 生态成熟度最高;团队以 Go 为主时可用 Go 1.22 + Gin + sqlc 等价替换,架构不变 | +| 应用框架 | Spring Boot | 3.3.x | 模块化单体:接入鉴权、订单、钱包、退款、对账、后台分模块,同库同事务 | +| 持久层 | MyBatis 3(手写 SQL) | 3.5.x | 资金路径必须显式 SQL + 条件更新;**不用 JPA 脏检查自动生成资金更新** | +| 数据库 | MySQL | 8.0.36+ | 8.0.16+ 才有 CHECK;REPEATABLE READ;主从 + 每日全量备份 | +| 缓存/限流/锁 | Redis + Redisson | 7.2 | 分布式限流、`GET_LOCK` 替代锁、管理员 Session、幂等辅助 | +| 定时任务 | XXL-Job(或 Spring Scheduler + ShedLock) | 2.4.x | 关单、webhook 投递、对账;必须单实例执行,禁止多副本并发跑批 | +| 认证授权 | Spring Security + TOTP(Google Authenticator) | 6.x | 管理员三角色 + 权限点;业务侧只走 client token | +| API 文档 | springdoc-openapi | 2.x | OpenAPI 3.1,随代码生成;不再手写独立 API 文档 | +| 后台前端 | Vue 3 + TypeScript + Vite + Element Plus | Vue 3.4+ | 运营/财务/审计后台 | +| 收款页 | Thymeleaf 服务端渲染 | 3.1 | `/pay`、订单详情页 SSR,**不把 token/ticket 交给 SPA** | +| 反向代理 | Nginx | 1.26 | HTTPS/HSTS、ticket 日志脱敏、静态资源 | +| 可观测 | Micrometer + Prometheus + Grafana + Loki | 最新稳定 | 资金指标、对账差异、webhook 失败、限流、锁等待 | +| 容器/部署 | Docker + Docker Compose(MVP)/ Kubernetes(二期) | — | MVP 2 实例 + MySQL 主备即可,不引入微服务 | +| 测试 | JUnit 5 + Testcontainers + k6 | — | 资金用例连真实 MySQL/Redis 跑;第 13 节 28 条攻击用例自动化 | +| CI/CD | GitLab CI / GitHub Actions + SonarQube | — | 建表脚本、OpenAPI diff、攻击用例回归为必过关卡 | + +### 16.2 选型原则 + +- **模块化单体优先**:MVP 不拆微服务。扣费、订单、流水、审计必须同库同事务;跨服务只增加分布式事务风险。 +- **资金路径不用 ORM 自动更新**:余额、状态、退款全部手写条件更新 SQL,方便 review 与压测。 +- **收款页 SSR**:`/pay` 不加载业务 JS、不写 Cookie 之外的凭证,降低 XSS/CSRF 与 ticket 泄露面。 +- **所有金额/点数计算在服务端**:前端只做展示,技术栈不改变 D6 的判定权归属。 + +### 16.3 可选开源内核(按需引入,不作为 MVP 前置) + +| 组件 | 用途 | 许可 | 引入时机 | +|---|---|---|---| +| **TigerBeetle** | 复式账本内核:余额上下限、pending transfer(冻结)、严格串行化 | Apache 2.0 | 单用户扣费并发很高,或希望「余额为负在 DB 层不可能发生」时替换 `fin_account`/`fin_transaction` | +| **Blnk** | 开源账本:inflight 冻结、退款、对账、PII tokenization、loyalty points | Apache 2.0 | 希望快速获得「钱包 + 冻结 + 对账」完整原语时 | +| **Kill Bill** | 订阅计费、catalog、多租户、audit | Apache 2.0 | 未来转向「订阅 + 用量」计费模式时参考/替换计费模型 | +| **Lago** | 用量计费 + prepaid credits/wallet | AGPLv3 | 仅当可接受 AGPL 或购买商业授权时 | +| **Jeepay** | 聚合支付、退款、渠道对账、商户/代理商 | 引入前确认许可 | 二期接微信/支付宝时作为支付通道层 | +| **Hyperswitch** | 支付编排、多通道路由/重试 | Apache 2.0 | 多支付渠道或海外场景 | + +> 结论:**MVP 不引入外部账本内核**,先用 MySQL 实现本文件约束;若后续并发或对账压力上来, +> 优先把 `fin_account` + `fin_transaction` 替换为 TigerBeetle/Blnk,业务外壳(ticket、订单、后台、审计)保持不变。 +> 许可证为 AGPL 的组件(Lago/new-api 等)不得直接嵌入对外 SaaS 而不履行开源义务。 + +### 16.4 部署拓扑(MVP) + +``` + ┌──────────── Nginx(HTTPS/HSTS + 日志脱敏) + │ + ┌──────────┴──────────┐ + │ │ + fin-app #1 fin-app #2 ← Spring Boot 无状态,Session 存 Redis + │ │ + ├──────────┬──────────┤ + │ │ │ + MySQL 主 MySQL 从 Redis(限流/锁/Session) + │ + XXL-Job Executor(单实例跑:关单 / webhook / 对账) + │ + Prometheus + Grafana + Loki + 告警通道 +``` + +- 应用无状态,可水平扩;**定时任务必须加分布式锁或只部署一个 executor**。 +- 数据库账号分离:应用账号仅 DML,`fin_audit_log` 仅 INSERT;迁移账号单独、仅发布窗口使用。 +- 配置与密钥:DB 口令、PII pepper、`webhook_secret` 主密钥走环境变量/外部密钥文件(Vault/KMS),不入 Git。 + +### 16.5 工程规范 + +- 数据库变更用 Flyway/Liquibase 管理(`sql/` 增量目录),禁止手工改基线库;上线前校验 CHECK 生效。 +- OpenAPI 由 springdoc 生成,CI 做 breaking-change diff;业务方 SDK 可由 OpenAPI 生成。 +- 关键指标:扣费 QPS/延迟、4092 重试率、6001 比例、对账差异条数、webhook DEAD 数、`GET_LOCK` 等待时长。 +- 压测基线:单实例扣费 ≥ 500 TPS、P99 ≤ 150ms(MySQL 单主,MVP 目标);扩容以只读查询与后台为主。 + +--- + +## 附录 A:建表 DDL(MySQL 8.0.16+,可直接执行) + +> 统一约定:`id` bigint 雪花主键;`is_delete` int 默认 1(1 正常 / 0 删除,**手写 SQL 必须带 `is_delete=1`**); +> `create_time`/`update_time`;`utf8mb4_0900_ai_ci`;资金表只增不改,不做物理删除。 +> CHECK 约束依赖 MySQL 8.0.16+(低版本会解析但忽略,因此**应用层校验不可省略**)。 + +```sql +-- 1. 接入应用 +CREATE TABLE fin_app ( + id bigint PRIMARY KEY, + app_code varchar(64) NOT NULL, + app_name varchar(128) NOT NULL, + client_secret_hash varchar(255) NOT NULL, + client_secret_prev_hash varchar(255), + client_secret_expires_at datetime, + allowed_redirect_hosts varchar(512) NOT NULL COMMENT '逗号分隔精确主机名;禁止通配/IP', + webhook_url varchar(512), + webhook_secret_enc varchar(512) COMMENT 'AES-256-GCM 密文,验签时内存解密', + token_ttl_seconds int NOT NULL DEFAULT 900, + enabled tinyint NOT NULL DEFAULT 1, + is_delete int NOT NULL DEFAULT 1, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + update_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY uk_app_code (app_code), + CONSTRAINT ck_app_ttl CHECK (token_ttl_seconds BETWEEN 60 AND 86400) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 2. 后台管理员 +CREATE TABLE fin_admin ( + id bigint PRIMARY KEY, + username varchar(64) NOT NULL, + password_hash varchar(255) NOT NULL, + role varchar(32) NOT NULL COMMENT 'SUPER_ADMIN/FINANCE/AUDITOR', + is_active tinyint NOT NULL DEFAULT 1, + must_change_password tinyint NOT NULL DEFAULT 1, + totp_secret_enc varchar(512), + failed_attempts int NOT NULL DEFAULT 0, + locked_until datetime, + last_login_at datetime, + last_login_ip varchar(64), + is_delete int NOT NULL DEFAULT 1, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + update_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY uk_admin_username (username), + CONSTRAINT ck_admin_role CHECK (role IN ('SUPER_ADMIN','FINANCE','AUDITOR')), + CONSTRAINT ck_admin_failed CHECK (failed_attempts >= 0) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 3. 业务用户投影(PII 只存掩码 + 哈希) +CREATE TABLE fin_subject ( + id bigint PRIMARY KEY, + app_code varchar(64) NOT NULL, + business_user_id varchar(64) NOT NULL, + username_snapshot varchar(64), + phone_masked varchar(32) COMMENT '138****8000', + phone_hash char(64) COMMENT 'HMAC-SHA256(phone, pepper)', + email_masked varchar(128), + email_hash char(64), + status varchar(16) NOT NULL DEFAULT 'ACTIVE', + first_seen_at datetime NOT NULL, + is_delete int NOT NULL DEFAULT 1, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + update_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY uk_subject_app_user (app_code, business_user_id), + KEY idx_subject_phone_hash (phone_hash), + KEY idx_subject_email_hash (email_hash), + CONSTRAINT ck_subject_status CHECK (status IN ('ACTIVE','FROZEN','CLOSED')) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 4. 一次性凭证(只存 hash) +CREATE TABLE fin_ticket ( + id bigint PRIMARY KEY, + app_code varchar(64) NOT NULL, + business_user_id varchar(64) NOT NULL, + ticket_hash char(64) NOT NULL, + expires_at datetime NOT NULL, + used_at datetime, + issued_ip varchar(64), + issued_ua varchar(255), + is_delete int NOT NULL DEFAULT 1, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY uk_ticket_hash (ticket_hash), + KEY idx_ticket_expire (expires_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 5. 钱包(按 app 隔离) +CREATE TABLE fin_account ( + id bigint PRIMARY KEY, + app_code varchar(64) NOT NULL, + business_user_id varchar(64) NOT NULL, + balance bigint NOT NULL DEFAULT 0, + frozen_balance bigint NOT NULL DEFAULT 0 COMMENT '退款复核期冻结,可用余额=balance-frozen_balance', + total_spent bigint NOT NULL DEFAULT 0, + version_no int NOT NULL DEFAULT 0, + is_delete int NOT NULL DEFAULT 1, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + update_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY uk_acct_app_user (app_code, business_user_id), + CONSTRAINT ck_acct_balance CHECK (balance >= 0), + CONSTRAINT ck_acct_frozen CHECK (frozen_balance >= 0 AND frozen_balance <= balance), + CONSTRAINT ck_acct_spent CHECK (total_spent >= 0) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 6. VIP 档位(各 app 任意档位) +CREATE TABLE fin_vip_plan ( + id bigint PRIMARY KEY, + app_code varchar(64) NOT NULL, + plan_code varchar(32) NOT NULL, + plan_name varchar(64) NOT NULL, + duration_days int NOT NULL, + price_cent int NOT NULL, + free_deduction tinyint NOT NULL DEFAULT 0, + enabled tinyint NOT NULL DEFAULT 1, + is_delete int NOT NULL DEFAULT 1, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + update_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY uk_vipplan_app_plan (app_code, plan_code), + CONSTRAINT ck_vipplan_price CHECK (price_cent > 0), + CONSTRAINT ck_vipplan_days CHECK (duration_days > 0), + CONSTRAINT ck_vipplan_free CHECK (free_deduction IN (0,1)) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 7. VIP 持有 +CREATE TABLE fin_vip ( + id bigint PRIMARY KEY, + app_code varchar(64) NOT NULL, + business_user_id varchar(64) NOT NULL, + vip_plan_code varchar(32) NOT NULL, + vip_until datetime NOT NULL, + version_no int NOT NULL DEFAULT 0, + is_delete int NOT NULL DEFAULT 1, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + update_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY uk_vip_app_user (app_code, business_user_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 8. 订单 +CREATE TABLE fin_order ( + id bigint PRIMARY KEY, + app_code varchar(64) NOT NULL, + business_user_id varchar(64) NOT NULL, + order_type varchar(16) NOT NULL COMMENT 'recharge/vip', + pay_method varchar(16) NOT NULL COMMENT 'offline/wechat/alipay', + amount_cent int NOT NULL, + points_gained int NOT NULL DEFAULT 0, + points_per_yuan_snapshot int NULL COMMENT '充值订单必填;VIP 订单可为空', + vip_plan_code varchar(32), + third_party_trade_no varchar(64) COMMENT '二期支付渠道交易号', + status varchar(16) NOT NULL COMMENT 'PENDING/PAID/CANCELLED/REFUNDED', + out_trade_no varchar(64) NOT NULL, + expires_at datetime NOT NULL, + paid_at datetime, + confirmed_by_admin_id bigint, + second_approver_id bigint, + remark varchar(255), + is_delete int NOT NULL DEFAULT 1, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + update_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY uk_order_no (out_trade_no), + KEY idx_order_user (app_code, business_user_id, create_time), + KEY idx_order_status_expire (status, expires_at), + KEY idx_order_third_party (third_party_trade_no), + CONSTRAINT ck_order_amount CHECK (amount_cent > 0), + CONSTRAINT ck_order_points CHECK (points_gained >= 0), + CONSTRAINT ck_order_rate CHECK ((order_type = 'recharge' AND points_per_yuan_snapshot IS NOT NULL AND points_per_yuan_snapshot > 0) + OR (order_type = 'vip' AND (points_per_yuan_snapshot IS NULL OR points_per_yuan_snapshot > 0))), + CONSTRAINT ck_order_type CHECK (order_type IN ('recharge','vip')), + CONSTRAINT ck_order_status CHECK (status IN ('PENDING','PAID','CANCELLED','REFUNDED')) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 9. 现金台账(收款/退款) +CREATE TABLE fin_cash_flow ( + id bigint PRIMARY KEY, + app_code varchar(64) NOT NULL, + order_id bigint NOT NULL, + direction varchar(4) NOT NULL COMMENT 'IN/OUT', + amount_cent int NOT NULL, + received_at datetime NOT NULL, + voucher_no varchar(64) NOT NULL COMMENT '银行回单/转账凭证号', + operator_admin_id bigint NOT NULL, + remark varchar(255), + is_delete int NOT NULL DEFAULT 1, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + KEY idx_cash_order_dir (order_id, direction), + KEY idx_cash_time (received_at), + CONSTRAINT ck_cash_amount CHECK (amount_cent > 0), + CONSTRAINT ck_cash_dir CHECK (direction IN ('IN','OUT')) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 10. 现金退款单 +CREATE TABLE fin_refund_order ( + id bigint PRIMARY KEY, + app_code varchar(64) NOT NULL, + business_user_id varchar(64) NOT NULL, + order_id bigint NOT NULL, + amount_cent int NOT NULL, + points_deducted int NOT NULL DEFAULT 0, + status varchar(16) NOT NULL COMMENT 'PENDING/COMPLETED/REJECTED', + idempotency_key varchar(128) NOT NULL, + operator_admin_id bigint NOT NULL, + reviewer_admin_id bigint, + voucher_no varchar(64), + completed_at datetime COMMENT '仅 COMPLETED 非空;现金侧对账时间基准', + remark varchar(255), + is_delete int NOT NULL DEFAULT 1, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + update_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY uk_reford_app_idem (app_code, idempotency_key), + KEY idx_reford_order (order_id), + KEY idx_reford_completed (completed_at), + CONSTRAINT ck_reford_amount CHECK (amount_cent > 0), + CONSTRAINT ck_reford_points CHECK (points_deducted >= 0), + CONSTRAINT ck_reford_status CHECK (status IN ('PENDING','COMPLETED','REJECTED')), + CONSTRAINT ck_reford_voucher CHECK (status <> 'COMPLETED' OR voucher_no IS NOT NULL), + CONSTRAINT ck_reford_completed CHECK ((status = 'COMPLETED' AND completed_at IS NOT NULL) + OR (status <> 'COMPLETED' AND completed_at IS NULL)) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 11. 点数流水(只增不改) +CREATE TABLE fin_transaction ( + id bigint PRIMARY KEY, + app_code varchar(64) NOT NULL, + business_user_id varchar(64) NOT NULL, + type varchar(16) NOT NULL COMMENT 'RECHARGE/CONSUME/CONSUME_FREE/REFUND_IN/REFUND_OUT/ADJUST_IN/ADJUST_OUT', + amount int NOT NULL COMMENT '恒为正;方向由 type 决定', + balance_before bigint NOT NULL, + balance_after bigint NOT NULL, + business_ref_id varchar(64), + idempotency_key varchar(128) NOT NULL, + order_id bigint, + refund_of_id bigint, + refunded_points int NOT NULL DEFAULT 0, + operator_admin_id bigint, + remark varchar(255), + is_delete int NOT NULL DEFAULT 1, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY uk_tx_app_idem (app_code, idempotency_key), + KEY idx_tx_user (app_code, business_user_id, create_time), + KEY idx_tx_refund_of (refund_of_id), + KEY idx_tx_order (order_id), + CONSTRAINT ck_tx_amount CHECK ((type = 'CONSUME_FREE' AND amount = 0) OR (type <> 'CONSUME_FREE' AND amount > 0)), + CONSTRAINT ck_tx_type CHECK (type IN ('RECHARGE','CONSUME','CONSUME_FREE','REFUND_IN','REFUND_OUT','ADJUST_IN','ADJUST_OUT')), + CONSTRAINT ck_tx_bal CHECK (balance_before >= 0 AND balance_after >= 0), + CONSTRAINT ck_tx_refunded CHECK (refunded_points >= 0) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 12. 应用扣费策略 +CREATE TABLE fin_app_policy ( + app_code varchar(64) PRIMARY KEY, + min_cost int NOT NULL DEFAULT 0, + max_points_per_charge int NOT NULL, + vip_exempt tinyint NOT NULL DEFAULT 0, + failed_strategy varchar(16) NOT NULL DEFAULT 'none' COMMENT 'none=失败不补偿 / actual=按实际点数自动回补(REFUND_IN)', + dual_control_threshold_cent int NULL COMMENT 'NULL=继承 fin_config.review.threshold_cent', + enabled tinyint NOT NULL DEFAULT 1, + is_delete int NOT NULL DEFAULT 1, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + update_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + CONSTRAINT ck_policy_min CHECK (min_cost >= 0), + CONSTRAINT ck_policy_max CHECK (max_points_per_charge >= 1), + CONSTRAINT ck_policy_minmax CHECK (min_cost <= max_points_per_charge), + CONSTRAINT ck_policy_exempt CHECK (vip_exempt IN (0,1)), + CONSTRAINT ck_policy_strategy CHECK (failed_strategy IN ('none','actual')), + CONSTRAINT ck_policy_threshold CHECK (dual_control_threshold_cent IS NULL OR dual_control_threshold_cent >= 0) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 13. 兑率 +CREATE TABLE fin_pricing ( + app_code varchar(64) PRIMARY KEY, + points_per_yuan int NOT NULL, + enabled tinyint NOT NULL DEFAULT 1, + is_delete int NOT NULL DEFAULT 1, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + update_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + CONSTRAINT ck_pricing_rate CHECK (points_per_yuan > 0) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 14. 全局配置 +CREATE TABLE fin_config ( + config_key varchar(64) PRIMARY KEY, + config_value varchar(255) NOT NULL, + description varchar(255), + update_by bigint, + update_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 15. webhook 投递队列 +CREATE TABLE fin_webhook_delivery ( + id bigint PRIMARY KEY, + app_code varchar(64) NOT NULL, + event_id varchar(64) NOT NULL, + event_type varchar(64) NOT NULL, + payload json NOT NULL, + signature varchar(128) NOT NULL, + status varchar(16) NOT NULL DEFAULT 'PENDING', + attempts int NOT NULL DEFAULT 0, + next_retry_at datetime, + last_error varchar(512), + create_time datetime DEFAULT CURRENT_TIMESTAMP, + update_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY uk_wh_event (event_id), + KEY idx_wh_status (status, next_retry_at), + CONSTRAINT ck_wh_status CHECK (status IN ('PENDING','SENT','DEAD')) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 16. 后台审计(只增不改 + 哈希链) +CREATE TABLE fin_audit_log ( + id bigint PRIMARY KEY, + actor_type varchar(16) NOT NULL COMMENT 'ADMIN/SYSTEM/BIZ', + actor_id bigint, + actor_app_code varchar(64) COMMENT 'actor_type=BIZ 时的来源应用', + actor_name varchar(64), + action varchar(64) NOT NULL, + target_type varchar(32), + target_id bigint, + before_json json, + after_json json, + ip varchar(64), + ua varchar(255), + result varchar(16) NOT NULL, + prev_hash char(64), + cur_hash char(64) NOT NULL, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY uk_audit_cur_hash (cur_hash), + KEY idx_audit_actor (actor_id, create_time), + KEY idx_audit_target (target_type, target_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 17. client token(只存 hash,支持撤销) +CREATE TABLE fin_app_token ( + id bigint PRIMARY KEY, + app_code varchar(64) NOT NULL, + token_hash char(64) NOT NULL, + expires_at datetime NOT NULL, + revoked_at datetime, + issued_ip varchar(64), + is_delete int NOT NULL DEFAULT 1, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY uk_apptoken_hash (token_hash), + KEY idx_apptoken_expire (expires_at), + KEY idx_apptoken_app (app_code, expires_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 18. 二期支付回调原始报文(只增不改) +CREATE TABLE fin_payment_callback_log ( + id bigint PRIMARY KEY, + app_code varchar(64) NOT NULL, + channel varchar(16) NOT NULL COMMENT 'wechat/alipay/...', + third_party_trade_no varchar(64) NOT NULL, + out_trade_no varchar(64) NOT NULL, + raw_body text NOT NULL COMMENT '原始报文,用于验签举证与补单', + signature varchar(256), + verify_result varchar(16) NOT NULL COMMENT 'PASS/FAIL', + amount_cent int, + processed tinyint NOT NULL DEFAULT 0, + create_time datetime DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY uk_cb_channel_trade (channel, third_party_trade_no), + KEY idx_cb_out_trade (out_trade_no), + CONSTRAINT ck_cb_verify CHECK (verify_result IN ('PASS','FAIL')) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; + +-- 19. 对账差异明细 +CREATE TABLE fin_recon_diff ( + id bigint PRIMARY KEY, + app_code varchar(64) NOT NULL, + biz_date date NOT NULL, + diff_type varchar(32) NOT NULL COMMENT 'CASH_IN/CASH_OUT/POINTS_BALANCE/FROZEN/TOTAL_SPENT/CHAIN/RECHARGE_AMOUNT', + ref_type varchar(32), + ref_id bigint, + expected_amount decimal(20,4), + actual_amount decimal(20,4), + diff_amount decimal(20,4), + status varchar(16) NOT NULL DEFAULT 'OPEN' COMMENT 'OPEN/FIXED/IGNORED', + snapshot_at datetime NOT NULL, + remark varchar(255), + create_time datetime DEFAULT CURRENT_TIMESTAMP, + KEY idx_recon_app_date (app_code, biz_date, diff_type), + KEY idx_recon_status (status), + CONSTRAINT ck_recon_status CHECK (status IN ('OPEN','FIXED','IGNORED')) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +``` + +**初始化种子**:按 8.1 插入 SUPER_ADMIN;按 4.7 写入 `fin_config` 默认值;按第 15 节由业务方填入 +`fin_pricing` / `fin_app_policy` / `fin_vip_plan`。所有种子 SQL 放 `sql/` 增量目录,**不直接改基线库**。 + +--- + +## 附录 B:残余风险声明(诚实边界) + +本设计已消除 v2.0 评审的 17 项与 v2.1 复审的 18 项已知缺陷,但**不存在「绝对安全」的系统**。上线后仍需以下控制: + +| 残余风险 | 控制手段 | +|---|---| +| 部署环境失守(明文 HTTP、密钥入 Git、DB 暴露公网) | §9 / 附录 C 为上线硬性检查项,不达标不投产 | +| 管理员内部作恶(FINANCE 虚假确认到账) | 双人复核 + 全量审计链 + 现金侧人工银行台账核对(制度兜底) | +| 业务系统被攻破后异常扣费 | `max_points_per_charge` 单次上限 + 日累计限额 + `min_cost` 保底 + 告警 + 应用熔断(损失有界) | +| 二期支付渠道风险(回调伪造/金额篡改) | 二期落地时执行验签 + 金额比对 + 幂等三重校验 + `fin_payment_callback_log` 举证 | +| 退款/冻结流程被滥用 | 冻结点数 + 双人复核 + 银行凭证号 + 审计链;异常退款告警 | +| 未知漏洞 | 28 条攻击验收 + 上线前渗透自测 + 三期风控规则持续演进 | + +**结论**:已知缺陷已在设计层闭环,但「消除已知缺陷」不等于「没有缺陷」; +安全性 = 本设计 + 部署纪律 + 持续运营三者之和,新发现的资金语义问题必须回写本文件并补验收用例。 + +--- + +## 附录 C:部署与上线顺序(按依赖排) + +1. **建表**:执行附录 A DDL(19 张表,或拆成 Flyway 增量脚本),确认 MySQL ≥ 8.0.16 使 CHECK 生效。 +2. **种子数据**:SUPER_ADMIN(8.1)+ `fin_config` 默认值(4.7);超管首次登录强制改密并绑定 2FA。 +3. **配置密钥**:`client_secret` 哈希、`webhook_secret` 加密、DB 口令、PII pepper 全部走环境变量/外部密钥文件。 +4. **技术栈落地**:按第 16 节搭建 Spring Boot + MySQL + Redis + Nginx + XXL-Job,OpenAPI 随代码生成。 +5. **接入首个应用**:分配 `app_code` / `client_secret`,配置 `allowed_redirect_hosts` 与 `webhook_url`。 +6. **闭环联调**:签发 ticket → 收款页 → 管理员确认 → 余额 → 报价 → 扣费 → 退款(含冻结)→ 对账,逐环节验证。 +7. **攻击用例回归**:第 13 节 28 条用例全部通过(建议做成自动化脚本,Testcontainers 跑真实 MySQL/Redis)。 +8. **运维开关**:nginx ticket 日志脱敏、HTTPS/HSTS、后台仅内网可达、备份与恢复演练。 +9. **灰度**:先单应用小额放量,观察对账与告警 1 周后再接入其余应用。