54 Commits

Author SHA1 Message Date
luo
2f4eed917e fix: 白屏
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 2m0s
2026-10-31 13:02:18 +08:00
luo
1a1ec485a5 fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 45s
2026-10-29 17:17:55 +08:00
luo
f2614d8efb fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 54s
2026-10-28 15:18:44 +08:00
luo
06684e1fc0 fix: 轮询按运营商账户限流
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-10-26 14:31:15 +08:00
luo
049f8257fb feat: 新增网关限流
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 56s
2026-10-24 16:22:28 +08:00
luo
ecce4f6e7b fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-10-24 14:56:32 +08:00
luo
c706f543a4 fix: 隐藏原路退回
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-10-23 16:38:08 +08:00
luo
d82e716d33 fix:some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-10-21 09:54:21 +08:00
luo
22e796ba23 fix:some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-10-20 17:35:12 +08:00
luo
6dedd9f852 fix:some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-10-20 17:21:48 +08:00
luo
7f3ff10fda fix:some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-10-20 09:21:23 +08:00
luo
eeeab03295 fix:some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 46s
2026-10-19 14:42:19 +08:00
luo
0d77a7d55b fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-10-14 17:08:32 +08:00
luo
16effb69f3 fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-10-13 17:43:38 +08:00
luo
c31183205d fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 56s
2026-10-13 17:21:46 +08:00
luo
b2a76adc9a fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-10-13 11:25:03 +08:00
luo
52268859aa fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 54s
2026-10-12 11:43:12 +08:00
luo
f1006187f6 fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 46s
2026-10-12 10:56:14 +08:00
luo
944f17ec3f fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 45s
2026-10-10 15:28:30 +08:00
luo
633c88d0aa fix: 适配手机
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 54s
2026-10-08 14:34:56 +08:00
luo
f61a3f84b6 fix: 修改文案
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-10-08 09:24:21 +08:00
luo
327516dd40 fix: 修改文案
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-10-08 09:16:04 +08:00
luo
2f23aeaaba fix: 单个解绑
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 54s
2026-10-07 17:16:19 +08:00
luo
2c64957e55 fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-09-30 09:15:03 +08:00
luo
1a5f3d1e7d fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 56s
2026-09-29 18:32:51 +08:00
luo
d02ce01f6a fix: 密码长度限制
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-09-29 16:40:31 +08:00
luo
aec2a27a65 fix: 凭证识别
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 54s
2026-09-29 16:07:48 +08:00
luo
f896cad34f fix: 选择今天00:00:00-23:59:59
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-09-29 11:36:41 +08:00
luo
7a74bec337 fix: 提现审批
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 47s
2026-09-29 10:41:57 +08:00
luo
5364916b1d fix: 运营商管理
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 54s
2026-09-29 09:15:05 +08:00
luo
6655638116 fix: 批量换绑业务员模板
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 54s
2026-09-28 11:26:15 +08:00
luo
e79d599da1 feat: 修改密码全局
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 56s
2026-09-28 11:17:39 +08:00
luo
015f990fb6 fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-09-28 10:08:30 +08:00
luo
063337e6a3 fix: 工作台适配深色模式
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 54s
2026-09-23 15:34:46 +08:00
luo
c26d36154c fix:fixed_left_config
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-09-23 15:27:55 +08:00
luo
669610a84a fix:some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-09-23 09:37:11 +08:00
luo
a26d7b4284 fix: 商户池和代理充值 2026-09-22 16:46:39 +08:00
luo
10fccc4def feat: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 56s
2026-09-22 15:06:30 +08:00
luo
0a28b7d8ef feat: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-09-22 12:14:47 +08:00
luo
c136f68ab8 feat: 代理商注册列表
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-09-21 18:07:36 +08:00
luo
c5d7a260d0 fix: 恢复退款原审批提交
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-09-20 18:13:14 +08:00
luo
ffba959d45 fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 54s
2026-09-20 17:56:48 +08:00
luo
9a6761e01d fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 54s
2026-09-20 17:29:09 +08:00
luo
2c00341a7c fix: some
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
2026-09-20 16:16:54 +08:00
5c1dc59579 fix: 清理镜像构建代理配置
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 59s
2026-09-20 15:47:39 +08:00
d52219b5c8 fix: 显式指定 npm 镜像源 2026-09-20 15:39:56 +08:00
bce5d6f270 fix: 避免 Corepack 下载失败 2026-09-20 15:32:21 +08:00
42e57cf698 fix: 配置 Corepack 镜像源 2026-09-20 15:30:47 +08:00
55eec78a90 feat: 支持跨平台前端镜像部署 2026-09-20 15:25:04 +08:00
cb1561a317 fix: 修复前端部署资源保护
Some checks failed
构建并部署前端到测试环境 / build-and-deploy (push) Failing after 14s
2026-09-20 14:42:14 +08:00
luo
94764b0e0a fix: some
Some checks failed
构建并部署前端到测试环境 / build-and-deploy (push) Failing after 11m29s
2026-09-20 11:37:47 +08:00
luo
a6ce24f2f2 fix: some
Some checks failed
构建并部署前端到测试环境 / build-and-deploy (push) Failing after 50m13s
2026-09-20 10:22:39 +08:00
luo
085a83d4e4 fix: some
Some checks failed
构建并部署前端到测试环境 / build-and-deploy (push) Has been cancelled
2026-09-20 10:10:50 +08:00
luo
e37d4902ca fix: some 2026-09-18 18:32:45 +08:00
364 changed files with 34338 additions and 2149 deletions

18
.dockerignore Normal file
View File

@@ -0,0 +1,18 @@
node_modules
dist
.git
.gitea
.husky
.vscode
.idea
.DS_Store
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.env.local
.env.*.local
openspec
.codex
.claude
.agents

View File

@@ -3,6 +3,7 @@ name: 构建并部署前端到测试环境
on:
push:
branches:
- feature/gateway-rate-limit
- iteration/august
- dev
- test
@@ -16,7 +17,7 @@ env:
DEPLOY_DIR: /opt/junhong_cmp_web
jobs:
build-and-deploy:
deploy:
runs-on: ubuntu-latest
steps:
@@ -27,67 +28,49 @@ jobs:
git clone https://git.boss160.cn/luo/one-pipe-system.git .
git checkout ${{ github.sha }}
- name: 设置镜像标签
id: tag
run: |
if [ "${{ github.ref }}" = "refs/heads/iteration/august" ]; then
echo "tag=latest" >> $GITHUB_OUTPUT
elif [ "${{ github.ref }}" = "refs/heads/dev" ]; then
echo "tag=dev" >> $GITHUB_OUTPUT
elif [ "${{ github.ref }}" = "refs/heads/test" ]; then
echo "tag=test" >> $GITHUB_OUTPUT
else
echo "tag=unknown" >> $GITHUB_OUTPUT
fi
- name: 登录 Docker Registry
run: |
echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login "${{ env.REGISTRY }}" --username "${{ secrets.REGISTRY_USERNAME }}" --password-stdin
- name: 构建前端镜像
- name: 校验镜像存在
run: |
docker build -t ${{ env.IMAGE_NAME }}:${{ steps.tag.outputs.tag }} .
docker tag ${{ env.IMAGE_NAME }}:${{ steps.tag.outputs.tag }} ${{ env.IMAGE_NAME }}:${{ github.sha }}
if ! docker manifest inspect "${{ env.IMAGE_NAME }}:${{ github.sha }}" >/dev/null 2>&1; then
echo "镜像不存在:${{ env.IMAGE_NAME }}:${{ github.sha }}"
echo "请先在开发机完成 pre-push 镜像构建和推送"
exit 1
fi
- name: 推送镜像到 Registry
- name: 部署到测试环境
if: github.ref == 'refs/heads/feature/gateway-rate-limit'
run: |
docker push ${{ env.IMAGE_NAME }}:${{ steps.tag.outputs.tag }}
docker push ${{ env.IMAGE_NAME }}:${{ github.sha }}
mkdir -p "${{ env.DEPLOY_DIR }}"
cp -v docker-compose.prod.yml "${{ env.DEPLOY_DIR }}/"
cd "${{ env.DEPLOY_DIR }}"
- name: 部署到本地(仅 iteration/august 分支)
if: github.ref == 'refs/heads/iteration/august'
run: |
# 确保部署目录存在
mkdir -p ${{ env.DEPLOY_DIR }}
IMAGE_TAG=${{ github.sha }} docker compose -f docker-compose.prod.yml pull
IMAGE_TAG=${{ github.sha }} docker compose -f docker-compose.prod.yml up -d
echo "当前工作目录: $(pwd)"
echo "当前目录内容:"
ls -la
echo "等待服务健康检查通过..."
for i in $(seq 1 30); do
WEB_HEALTH=$(docker inspect junhong-cmp-web --format='{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' 2>/dev/null || true)
if [ "$WEB_HEALTH" = "healthy" ]; then
break
fi
if [ "$i" -eq 30 ]; then
echo "前端服务在等待窗口内未恢复健康"
docker compose -f docker-compose.prod.yml logs web --tail=100
exit 1
fi
sleep 2
done
# 更新 docker-compose.prod.yml
echo "更新部署配置文件..."
cp -v docker-compose.prod.yml ${{ env.DEPLOY_DIR }}/
cd ${{ env.DEPLOY_DIR }}
echo "拉取最新镜像..."
docker compose -f docker-compose.prod.yml pull
echo "重启服务..."
docker compose -f docker-compose.prod.yml up -d
echo "等待服务启动..."
sleep 5
echo "部署完成!"
docker compose -f docker-compose.prod.yml ps
IMAGE_TAG=${{ github.sha }} docker compose -f docker-compose.prod.yml ps
- name: 构建结果通知
if: always()
run: |
if [ "${{ job.status }}" = "success" ]; then
echo "构建成功: ${{ steps.tag.outputs.tag }}"
echo "镜像标签: ${{ github.sha }}"
echo "部署成功: ${{ github.sha }}"
else
echo "构建失败"
echo "部署失败"
fi

7
.gitignore vendored
View File

@@ -2,6 +2,13 @@ node_modules
.DS_Store
dist
docs
!docs/
docs/*
!docs/权限.md
!docs/api/
docs/api/*
!docs/api/package-silence.openapi.json
!docs/2026-10-26-轮询账户限流-后台接入交付.md
dist-ssr
*.local
.cursorrules

1
.husky/pre-push Executable file
View File

@@ -0,0 +1 @@
node scripts/deploy-frontend.mjs --pre-push

View File

@@ -6,15 +6,16 @@ FROM --platform=linux/amd64 node:20-alpine AS builder
# 使用阿里云镜像源加速
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
# 设置工作目录
WORKDIR /build
# 安装 pnpm
RUN corepack enable && corepack prepare pnpm@10.15.0 --activate
# 设置 npm 镜像源
# 清除宿主机注入的失效代理,再安装 pnpm
RUN npm config delete proxy && npm config delete https-proxy && npm install --global pnpm@10.15.0 --registry=https://registry.npmmirror.com
RUN pnpm config set registry https://registry.npmmirror.com
# 限制 Node 堆,防止前端构建耗尽宿主机内存
ARG NODE_OPTIONS=--max-old-space-size=1536
ENV NODE_OPTIONS=${NODE_OPTIONS}
# 复制 package.json 和 pnpm-lock.yaml(利用 Docker 缓存)
COPY package.json pnpm-lock.yaml ./

View File

@@ -1,26 +1,25 @@
version: '3.8'
services:
web:
image: registry.boss160.cn/junhong/cmp-admin-web:latest
image: registry.boss160.cn/junhong/cmp-admin-web:${IMAGE_TAG:-latest}
container_name: junhong-cmp-web
restart: unless-stopped
ports:
- '3001:80'
networks:
- junhong-network
# === 以下是新增的修复内容 ===
tmpfs:
- /run:rw
- /tmp:rw
healthcheck:
test: ['CMD', 'wget', '--no-verbose', '--tries=1', '--spider', 'http://127.0.0.1:80/health']
interval: 30s
timeout: 3s
retries: 3
start_period: 5s
logging:
driver: 'json-file'
options:
@@ -29,4 +28,4 @@ services:
networks:
junhong-network:
driver: bridge
driver: bridge

View File

@@ -0,0 +1,128 @@
# 轮询账户限流:后台接入交付
本次仅修改本后台前端,未修改独立 C 端、未推送 Git 或部署生产、未配置数据库菜单。真实接口权限和调度行为仍需测试环境联调。本地写操作全部通过 mock 验证。
## 后台配置与使用
新增菜单、隐藏详情、按钮编码和平台账号限制见 [权限增量清单](./权限.md#轮询管理运营商账户限流与调度2026-10-26-增量)。原有网关、轮询配置预览/统计、停复机记录 URL 和权限保留。仅超级管理员的维护项不列入普通配置清单。
UI 沿用店铺列表表头、可选列、分页和店铺详情返回/标题/两列布局;窄屏详情单列。时间统一店铺格式,运营商账户按名称远程搜索,搜索条件 >=4 才出现展开。
新增配置字段现可保存,旧文档“仅预览”已失效。四项间隔:空继承、0 禁止且不再继承、正数执行。编辑清空使用 clear_fields,保存 warnings 单独展示;不再发送保护期间隔。
## C 端需要同步哪些
**必须修改(文档明确要求)**
1. C 端资产详情调用 `GET /api/c/v1/asset/info` 后,不再展示保护期状态(`device_protect_status`),包括标签、说明、倒计时和相关状态分支(如有)。
2. 废弃字段可能仍返回固定 `none`,也可能缺失;兼容解析,但不能再依赖它决定页面展示或是否允许操作。不要把 `none` 当成新的异常状态。
**随新后端回归验证(不是要求 C 端增加后台功能)**
- 订单/套餐生效、有效期变化后,重新读取资产实际 `enable_polling`;后台可能自动恢复轮询,不要仅凭旧前端缓存维持“已关闭”。
- 指令队列启用时,业务受理不等于上游已完成停复机。若 C 端有即时完成提示,改为区分“已受理/处理中”和实际状态,并在合理刷新后确认。
- 资产详情读入口的请求检查、延迟确认及冷却由后端场景配置控制,C 端不要自行复制调度逻辑或高频循环触发。
C 端不需要新增本次后台菜单、告警/调度参数/导入接口;本仓库没有修改任何 C 端代码。若 C 端本来没有保护期 UI 或逻辑,第一项只需核查删除残留引用。
## 接口覆盖
文档 46 个新增操作中,已有 GatewayService 17 个、PollingConfigService 7 个,本次 PollingSchedulerService 补 22 个。自动测试逐条解析原文附录的 46 个方法/路径,与实际服务调用对照,不以数量代替路径验收。
下表路径省略 `/api/admin`。精确 URL、Query/Body 测试位于 `gateway.test.mjs`、`pollingConfigExtensions.test.mjs`、`pollingScheduler.test.mjs`。
| HTTP 操作 | 服务方法 | 后台入口 |
| --- | --- | --- |
| `DELETE /gateway-error-classifications/{id}` | `GatewayService.deleteRule` | 上游错误分类 |
| `DELETE /polling-carrier-params/{carrier_id}` | `PollingSchedulerService.resetCarrierParam` | 账户参数维护 |
| `DELETE /polling-rate-limit-groups/{id}` | `GatewayService.deleteGroup` | 网关限流组维护 |
| `GET /card-polling-pauses` | `PollingSchedulerService.getPauses` | 不轮询清单 |
| `GET /card-stop-resume-records` | `GatewayService.getRecords` | 停复机记录 |
| `GET /gateway-error-classifications` | `GatewayService.getRules` | 上游错误分类 |
| `GET /iot-cards/{id}/polling-state` | `PollingSchedulerService.getCardState` | 单卡/设备绑定卡/告警详情 |
| `GET /iot-cards/{id}/stop-resume-records` | `GatewayService.getCardRecords` | 单卡/告警详情 |
| `GET /polling-carrier-params` | `PollingSchedulerService.getCarrierParams` | 运营商账户调度参数 |
| `GET /polling-carrier-params/{carrier_id}` | `PollingSchedulerService.getCarrierParam` | 账户参数详情 |
| `GET /polling-check-scenes` | `PollingSchedulerService.getScenes` | 请求检查场景 |
| `GET /polling-configs/match-preview` | `PollingConfigService.previewMatch` | 配置匹配预览 |
| `GET /polling-configs/recalculate-due/{task_id}` | `PollingConfigService.getRecalculateTask` | 重算进度 |
| `GET /polling-failure-alerts` | `PollingSchedulerService.getAlerts` | 告警普通/停机被拒 |
| `GET /polling-failure-alerts/summary` | `PollingSchedulerService.getAlertSummary` | 告警账户汇总 |
| `GET /polling-failure-alerts/{id}` | `PollingSchedulerService.getAlert` | 告警详情 |
| `GET /polling-options` | `GatewayService.getOptions` | 网关各页枚举 |
| `GET /polling-rate-limit-groups` | `GatewayService.getGroups` | 网关限流组 |
| `GET /polling-rate-limit-groups/{id}` | `GatewayService.getGroup` | 网关限流组详情 |
| `GET /polling-stats/carrier-queues` | `PollingSchedulerService.getQueues` | 账户队列监控 |
| `GET /polling-stats/carriers` | `GatewayService.getCarrierStats` | 网关汇总/限流模式 |
| `GET /polling-stats/carriers/{carrier_id}/trend` | `GatewayService.getCarrierTrend` | 账户调用趋势 |
| `GET /polling-stats/pre-reset` | `PollingConfigService.getPreResetStats` | 重置日前统计 |
| `GET /polling-stats/tiers` | `PollingConfigService.getTierStats` | 分层统计 |
| `GET /polling-status-imports` | `PollingSchedulerService.getImports` | 导入任务列表 |
| `GET /polling-status-imports/{id}` | `PollingSchedulerService.getImport` | 导入逐行结果 |
| `GET /polling-status/impact` | `PollingSchedulerService.getImpact` | 单项/批量/导入确认 |
| `GET /stop-resume-rule/dry-run` | `PollingSchedulerService.dryRun` | 规则演练(只读) |
| `POST /devices/batch-update-polling-status` | `PollingSchedulerService.toggleDevices` | 设备批量/清单恢复 |
| `POST /gateway-error-classifications` | `GatewayService.createRule` | 上游错误分类 |
| `POST /gateway-error-classifications/test` | `GatewayService.testRule` | 错误分类测试 |
| `POST /iot-cards/batch-update-polling-status` | `PollingSchedulerService.toggleCards` | 卡批量/清单恢复 |
| `POST /polling-configs/match-preview` | `PollingConfigService.previewDraft` | 配置草稿预览 |
| `POST /polling-configs/recalculate-due` | `PollingConfigService.recalculateDue` | 重算到期 |
| `POST /polling-failure-alerts/close-polling` | `PollingSchedulerService.closeAlertPolling` | 告警批量关闭卡轮询 |
| `POST /polling-rate-limit-groups` | `GatewayService.createGroup` | 网关限流组维护 |
| `POST /polling-status-imports` | `PollingSchedulerService.createImport` | 创建导入 |
| `POST /stop-resume-rule/dry-run/export` | `PollingSchedulerService.exportDryRun` | 演练导出 |
| `PUT /gateway-error-classifications/{id}` | `GatewayService.updateRule` | 上游错误分类 |
| `PUT /gateway-error-classifications/{id}/status` | `GatewayService.setRuleStatus` | 上游错误分类 |
| `PUT /polling-carrier-params/{carrier_id}` | `PollingSchedulerService.saveCarrierParam` | 账户参数维护 |
| `PUT /polling-check-scenes/{scene}` | `PollingSchedulerService.saveScene` | 请求检查场景维护 |
| `PUT /polling-configs/priorities` | `PollingConfigService.updatePriorities` | 整体优先级(拖动/上移下移) |
| `PUT /polling-failure-alerts/{id}/status` | `PollingSchedulerService.handleAlert` | 告警处理 |
| `PUT /polling-rate-limit-groups/{id}` | `GatewayService.updateGroup` | 网关限流组维护 |
| `PUT /polling-rate-limit-groups/{id}/status` | `GatewayService.setGroupStatus` | 网关限流组维护 |
### 16 个既有接口改动的处理
| 既有接口 | 接入结果 |
| --- | --- |
| GET /polling-configs | 列表新增资产/套餐条件、重置日前窗口和间隔列 |
| GET /polling-configs/:id | 编辑读入全部新增字段,废弃保护间隔不再参与 |
| POST /polling-configs | 白名单保存新增匹配及窗口字段、三态间隔,展示 warnings |
| PUT /polling-configs/:id | clear_fields 显式清空,0 保留,展示 warnings |
| GET /assets/resolve/:identifier | 不再映射废弃保护期展示;其余资产身份不变 |
| GET /assets/:identifier/realtime-status | 不再更新保护期 UI 字段 |
| POST /assets/:identifier/refresh | 沿用刷新读取,界面无保护期展示 |
| GET /api/c/v1/asset/info | 独立 C 端同步项,本仓库不改 |
| PUT /carriers/:id | 0→1 首次不带确认;展示后端实际影响后确认重提 |
| GET /system-configs | 新增 polling 模块,复用 string/int/bool/json 编辑与校验 |
| GET /iot-cards/standalone | 三态是否轮询筛选,保留 false |
| GET /devices | 新增筛选与是否轮询列 |
| PATCH /assets/:identifier/polling-status | 先读 impact 确认,拒绝/取消恢复 UI,不提供强制参数 |
| POST /storage/upload-url | purpose=polling_status_import;校验 key 前缀后上传,成功才建任务 |
| POST /export-tasks | 三个新增场景;卡/设备保留 enable_polling 筛选 |
| GET /export-tasks | 三个场景列表、共用详情与下载权限;历史文件不做客户端改写 |
`PUT /system-configs/:key` 继续走原编辑能力,新增键来自服务器;本次不会自动修改 scheduler、rate_limit_mode、queue_enabled。
## 验证与限制
本地复现:
```powershell
$tests = @(rg --files scripts/tests -g '*.test.mjs')
node --import ./scripts/tests/register-esbuild.mjs --test $tests
.\node_modules\.bin\vue-tsc.cmd --noEmit
node scripts/tests/verifyBuild.mjs
node scripts/tests/verifyBuild.mjs --serve --scheduler
```
最后一项在 `http://127.0.0.1:5190` 启动本地 mock,所有 /api 被拦截;可使用 local-scheduler-platform/admin/agent/enterprise 模拟 token。该结果不等于线上后端已联调。
已覆盖:46 路径映射、22 新方法请求结构、null/0/false、清空与废弃字段、权限/身份、500 条和 CSV 50000 行边界、引号换行、部分成功、影响说明失败/取消、上传失败、迟到请求/账号范围切换/卸载、模板编译。旧实名管控回归改成后端实际文案确认。
生产构建的既有循环依赖、常量 v-model 和大 chunk 警告仍存在;未在本次跨范围重构。后端若将实名确认提示升级为独立错误码,可替换当前的语义识别,避免依赖提示中的“实名/确认”关键词。当前未知网络错误或不相关错误不会触发确认重试。
2026-10-26 最终回归:全量 191 项通过(本次调度接入新增 17 项,保留并升级原有回归)。类型检查、生产构建、针对性 ESLint / Prettier / 新增组件样式检查、全仓 UTF-8 编码检查通过。
浏览器使用本地 mock 验证了平台账号入口、特殊告警视图、批量 impact 确认与四类逐项结果、CSV 上传建任务/详情、演练汇总与明细、时间格式、网关 80% 成功率及 p95 超桶显示;检查了浅/深色与 375/390/768/1024/1440 宽度布局。开发热更新仍可能遇到项目既有 API 循环依赖,刷新后进行验收,不把热更新错误当作真实接口结果。
真实后端账号、数据范围、错误码、异步终态和导出文件内容需由部署后的联调确认;本次未进行线上写入、Git 推送或部署。

File diff suppressed because it is too large Load Diff

437
docs/权限.md Normal file
View File

@@ -0,0 +1,437 @@
# 权限清单
## 套餐管理:真流量预警规则
页面 URL:`/package-management/traffic-alert-rules`
| 类型 | 权限名称 | 权限编码 |
| -------- | ------------- | ------------------------------------ |
| 页面查看 | `rulesView` | `package_traffic_alert:rules_view` |
| 新增规则 | `ruleCreate` | `package_traffic_alert:rule_create` |
| 编辑规则 | `ruleUpdate` | `package_traffic_alert:rule_update` |
| 启用规则 | `ruleEnable` | `package_traffic_alert:rule_enable` |
| 停用规则 | `ruleDisable` | `package_traffic_alert:rule_disable` |
启用和停用不得复用编辑权限。
## 套餐管理:真流量达量预警
| 页面/操作 | URL | 权限名称 | 权限编码 |
| --- | --- | --- | --- |
| 预警列表 | `/package-management/traffic-alerts` | `recordsView` | `package_traffic_alert:records_view` |
| 点击套餐名称进入预警详情 | `/package-management/traffic-alerts/detail/:id` | `recordDetail` | `package_traffic_alert:record_detail` |
| 导出预警记录 | — | `export` | `package_traffic_alert:export` |
| 导出任务页面 | `/asset-management/export-task-management/export-package-traffic-alert` | `page` | `export_task:package_traffic_alert_page` |
## 店铺管理:店铺列表
| 页面/操作 | URL | 权限名称 | 权限编码 |
| --- | --- | --- | --- |
| 店铺列表 | `/shop-management/list` | `listView` | `shop:list_view` |
| 店铺详情 | `/shop-management/detail/:id` | `detailView` | `shop:detail_view` |
| 新增店铺 | — | — | `shop:add` |
| 批量交接 | — | `batch` | `shop:business_owner_batch` |
| 导入业务员 | — | `importPage` | `shop:business_owner_import_view` |
| 查看店铺详情 | — | — | `shop:detail` |
| 切换店铺状态 | — | — | `shop:modify_status` |
| 账号列表 | — | — | `shop:look_customer` |
| 默认角色 | — | — | `shop:default_role` |
| 调整实际信用额度 | — | — | `shop:credit_limit_manage` |
| 编辑店铺 | — | — | `shop:edit` |
| 删除店铺 | — | — | `shop:delete` |
| 审计记录 | — | — | `audit:shop_entry` / `audit:agent_resource_activity` |
| 资金链路 | — | — | `audit:finance_timeline` |
## 店铺管理:业务用户组
页面 URL:`/shop-management/business-user-groups`
| 类型 | 权限名称 | 权限编码 |
| -------- | --------- | ----------------------------- |
| 页面查看 | `page` | `business_user_group:page` |
| 新增 | `create` | `business_user_group:create` |
| 编辑 | `update` | `business_user_group:update` |
| 删除 | `delete` | `business_user_group:delete` |
| 成员管理 | `members` | `business_user_group:members` |
## 店铺管理:批量换绑业务员
页面 URL:`/shop-management/business-owner-import`
| 类型 | 权限名称 | 权限编码 |
| ---------------------------- | -------------- | ----------------------------------- |
| 页面查看 | `importPage` | `shop:business_owner_import_view` |
| 创建导入任务 | `importCreate` | `shop:business_owner_import_create` |
| 详情按钮 | `importDetail` | `shop:business_owner_import_detail` |
| 详情页面(当前为列表页抽屉) | `importDetail` | `shop:business_owner_import_detail` |
## 店铺管理:代理注册申请
列表不显示操作列,点击“申请店铺”名称进入详情页。
| 页面/操作 | URL | 权限名称 | 权限编码 |
| --- | --- | --- | --- |
| 申请列表 | `/shop-management/agent-distribution-registrations` | `list` | `agent_distribution_registration:list` |
| 申请详情 | `/shop-management/agent-distribution-registrations/detail/:id` | `detail` | `agent_distribution_registration:detail` |
| 恢复审批 | — | `recoverApproval` | `agent_distribution_registration:recover_approval` |
## 资产管理:手机号资产关联
页面 URL:`/asset-management/phone-asset-association`
| 类型 | 权限名称 | 权限编码 |
| ---------------- | -------------------- | ---------------------------------------------- |
| 页面查看 | `list` | `phone_asset_association:list` |
| 单条解绑 | `unbind` | `phone_asset_association:unbind` |
| 批量解绑 | `unbindBatch` | `phone_asset_association:unbind_batch` |
| 解绑导入页面 | `unbindImportPage` | `phone_asset_association:unbind_import_view` |
| 创建解绑导入任务 | `unbindImportCreate` | `phone_asset_association:unbind_import_create` |
## 资产管理:解绑导入任务
| 页面/操作 | URL | 权限名称 | 权限编码 |
| --- | --- | --- | --- |
| 任务列表 | `/asset-management/task-management/phone-asset-unbind-import-tasks` | `unbindImportPage` | `phone_asset_association:unbind_import_page` |
| 任务详情 | `/asset-management/task-management/phone-asset-unbind-import-tasks/detail` | `unbindImportDetail` | `phone_asset_association:unbind_import_detail` |
| 详情按钮 | — | `unbindImportDetail` | `asset_association:unbind_import_detail` |
## 资产管理:临期资产
页面 URL:`/asset-management/expiring-assets`
| 类型 | 权限名称 | 权限编码 |
| -------- | -------- | ----------------------- |
| 页面查看 | `page` | `expiring_asset:page` |
| 导出 | `export` | `expiring_asset:export` |
## 资产管理:导出任务页面
详情按钮为导出任务列表中的任务编号点击入口,权限编码按导出场景区分;详情页面统一使用 `id` 查询参数。
| 导出场景 | 列表页面 URL | 页面权限编码 | 详情按钮权限编码 | 详情页面 URL |
| --- | --- | --- | --- | --- |
| 设备 | `/asset-management/export-task-management/export-device` | `export_task:device_page` | `export_task:device_detail` | `/asset-management/export-task-management/export-task-detail?id=:id` |
| IoT 卡 | `/asset-management/export-task-management/export-iot-card` | `export_task:iot_card_page` | `export_task:iot_card_detail` | `/asset-management/export-task-management/export-task-detail?id=:id` |
| 订单 | `/asset-management/export-task-management/export-order` | `export_task:order_page` | `export_task:order_detail` | `/asset-management/export-task-management/export-task-detail?id=:id` |
| 套餐 | `/asset-management/export-task-management/export-package` | `export_task:package_page` | `export_task:package_detail` | `/asset-management/export-task-management/export-task-detail?id=:id` |
| 代理主钱包流水 | `/asset-management/export-task-management/export-agent-wallet-transaction` | `export_task:agent_wallet_transaction_page` | `export_task:agent_wallet_transaction_detail` | `/asset-management/export-task-management/export-task-detail?id=:id` |
| 代理充值 | `/asset-management/export-task-management/export-agent-recharge` | `export_task:agent_recharge_page` | `export_task:agent_recharge_detail` | `/asset-management/export-task-management/export-task-detail?id=:id` |
| 退款 | `/asset-management/export-task-management/export-refund` | `export_task:refund_page` | `export_task:refund_detail` | `/asset-management/export-task-management/export-task-detail?id=:id` |
| 换货 | `/asset-management/export-task-management/export-exchange` | `export_task:exchange_page` | `export_task:exchange_detail` | `/asset-management/export-task-management/export-task-detail?id=:id` |
| 佣金明细 | `/asset-management/export-task-management/export-commission-record` | `export_task:commission_record_page` | `export_task:commission_record_detail` | `/asset-management/export-task-management/export-task-detail?id=:id` |
| 套餐真流量达量预警 | `/asset-management/export-task-management/export-package-traffic-alert` | `export_task:package_traffic_alert_page` | `export_task:package_traffic_alert_detail` | `/asset-management/export-task-management/export-task-detail?id=:id` |
| 临期资产 | `/asset-management/export-task-management/export-expiring-asset` | `export_task:expiring_asset_page` | `export_task:expiring_asset_detail` | `/asset-management/export-task-management/export-task-detail?id=:id` |
| 设备激活报表 | `/asset-management/export-task-management/export-operations-activation` | `export_task:operations_activation_page` | `export_task:operations_activation_detail` | `/asset-management/export-task-management/export-task-detail?id=:id` |
| 套餐续费报表 | `/asset-management/export-task-management/export-operations-renewal` | `export_task:operations_renewal_page` | `export_task:operations_renewal_detail` | `/asset-management/export-task-management/export-task-detail?id=:id` |
## 财务管理:退款管理
| 页面/操作 | URL | 权限名称 | 权限编码 |
| --------- | ---------------------------- | ----------------- | ------------------------- |
| 退款列表 | `/finance/refund` | `page` | `refund:page` |
| 退款详情 | `/finance/refund/detail/:id` | `detailPage` | `refund:detail_page` |
| 恢复审批 | — | `recoverApproval` | `refund:recover_approval` |
## 财务管理:员工代收款账单
| 页面/操作 | URL | 权限名称 | 权限编码 |
| --- | --- | --- | --- |
| 账单列表 | `/finance/employee-collection/bills` | `billPage` | `employee_collection:bill_view` |
| 账单详情 | `/finance/employee-collection/bills/detail/:id` | `billDetail` | `employee_collection:bill_detail` |
| 创建核销申请 | — | `applicationCreate` | `employee_collection:application_create` |
| 关闭账单 | — | `billClose` | `employee_collection:bill_close` |
## 财务管理:核销申请
| 页面/操作 | URL | 权限名称 | 权限编码 |
| --- | --- | --- | --- |
| 申请列表 | `/finance/employee-collection/applications` | `applicationPage` | `employee_collection:application_view` |
| 申请详情 | `/finance/employee-collection/applications/detail/:id` | `applicationDetail` | `employee_collection:application_detail` |
| 修改并重新提交 | — | `applicationUpdate` | `employee_collection:application_update` |
| 查看凭证 | — | `applicationViewVoucher` | `employee_collection:application_view_voucher` |
| 恢复审批 | — | `applicationRecoverApproval` | `employee_collection:application_recover_approval` |
## 财务管理:收款方式管理
页面 URL:`/finance/employee-collection/payment-methods`
| 类型 | 权限名称 | 权限编码 |
| -------- | --------------------- | ------------------------------------------- |
| 页面查看 | `paymentMethodPage` | `employee_collection:payment_method_view` |
| 新增 | `paymentMethodCreate` | `employee_collection:payment_method_create` |
| 编辑 | `paymentMethodEdit` | `employee_collection:payment_method_edit` |
| 删除 | `paymentMethodDelete` | `employee_collection:payment_method_delete` |
## 财务管理:代理商资金概况
页面 URL:`/finance/agent-fund-overview`
| 类型 | 权限名称 | 权限编码 |
| ------------ | ------------------ | --------------------------------------- |
| 页面查看 | `page` | `agent_fund_overview:page` |
| 佣金明细导出 | `commissionExport` | `agent_fund_overview:commission_export` |
## 设置:商户池管理
| 页面/操作 | URL | 权限名称 | 权限编码 |
| --- | --- | --- | --- |
| 管理页面 | `/settings/payment-merchant-pools` | `page` | `payment_merchant_pool:page` |
| 商户详情 | `/settings/payment-merchant-pools/detail/:id` | `merchantDetail` | `payment_merchant_pool:merchant_detail` |
| 商户池详情 | `/settings/payment-merchant-pools/pool-detail/:id` | `poolDetail` | `payment_merchant_pool:pool_detail` |
| 新增/编辑/启停/删除商户 | — | — | `payment_merchant_pool:merchant_create` / `merchant_edit` / `merchant_toggle` / `merchant_delete` |
| 新增/编辑/启停商户池 | — | — | `payment_merchant_pool:pool_create` / `pool_edit` / `pool_toggle` |
| 保存微信授权配置 | — | `wechatAuthEdit` | `payment_merchant_pool:wechat_auth_edit` |
## 设置:H5运营弹窗配置
| 页面/操作 | URL | 权限名称 | 权限编码 |
| --- | --- | --- | --- |
| 配置列表 | `/settings/h5-popup-configuration` | `list` | `h5_popup_configuration:list` |
| 配置详情 | `/settings/h5-popup-configuration/detail/:id` | `detail` | `h5_popup_configuration:detail` |
| 新增/编辑/启用/停用 | — | — | `h5_popup_configuration:create` / `update` / `enable` / `disable` |
## 设置:资产钱包自动续费
| 页面/操作 | URL | 权限名称 | 权限编码 |
| --- | --- | --- | --- |
| 页面查看 | `/settings/asset-wallet-auto-renewal` | `page` | `asset_wallet_auto_renewal:page` |
| 保存配置 | — | `update` | `asset_wallet_auto_renewal:update` |
## 轮询管理:优先队列
页面 URL:`/polling-management/priority-queue`
| 类型 | 权限名称 | 权限编码 |
| ------------ | -------- | ------------------------------- |
| 页面查看 | `page` | `polling_priority_queue:page` |
| 人工优先入队 | `create` | `polling_priority_queue:create` |
| 查看详情 | `detail` | `polling_priority_queue:detail` |
## 运营报表:设备激活报表
页面 URL:`/operations-reports/activation`
| 类型 | 权限名称 | 权限编码 |
| -------- | ------------------ | -------------------------------------- |
| 页面查看 | `activationPage` | `operations_reports:activation_page` |
| 导出 | `activationExport` | `operations_reports:activation_export` |
## 运营报表:套餐续费报表
页面 URL:`/operations-reports/renewal`
| 类型 | 权限名称 | 权限编码 |
| -------- | --------------- | ----------------------------------- |
| 页面查看 | `renewalPage` | `operations_reports:renewal_page` |
| 导出 | `renewalExport` | `operations_reports:renewal_export` |
## 通用:导出任务详情
页面 URL:`/asset-management/export-task-management/export-task-detail`
- 页面权限:`export_task:detail_page`
- 各场景详情权限:`export_task:<scene>_detail`
- 各场景下载权限:`export_task:<scene>_download`
所有权限编码必须保持唯一;页面 URL 权限与按钮权限应分别定义。
## 轮询管理:网关限流
以下仅列普通账号需要配置的项。父菜单为已有「轮询管理」`/polling-management`,无需新增一级菜单。
| 菜单名称 | URL | 父菜单 | 菜单权限编码 |
| --- | --- | --- | --- |
| 停复机记录 | `/polling-management/stop-resume-records` | 轮询管理 | `card_stop_resume_record:page` |
| 上游错误分类 | `/polling-management/error-classifications` | 轮询管理 | `gateway_error_classification:page` |
| 网关限流组 | `/polling-management/rate-limit-groups` | 轮询管理 | `gateway_rate_limit_group:page` |
| 网关调用统计 | `/polling-management/gateway-stats` | 轮询管理 | `gateway_call_stats:page` |
| 网关限流组详情(隐藏) | `/polling-management/rate-limit-groups/detail/:id` | 轮询管理 | `gateway_rate_limit_group:detail_page` |
详情为轮询管理下的同级隐藏路由,不挂在列表组件下。`:id` 保留路由参数形式;普通账号需同时获得该隐藏菜单与「查看详情」按钮授权。
| 按钮名称 | 所属菜单/位置 | 按钮权限编码 |
| --- | --- | --- |
| 测试分类 / 草稿测试 | 上游错误分类 | `gateway_error_classification:test` |
| 查看详情 | 网关限流组 | `gateway_rate_limit_group:detail` |
| 查询趋势 | 网关调用统计 | `gateway_call_stats:trend` |
| 停复机记录 | 资产管理 → 单卡信息,卡信息头部 | `iot_info:stop_resume_records` |
| 停复机记录 | 资产管理 → 单卡信息,设备绑定卡操作区 | `device_info:stop_resume_records` |
查询、重置、分页与刷新使用页面权限,无需另配按钮。运营商名称搜索下拉需要当前账号能读取 `/api/admin/carriers`;这些前端编码不替代后端独立鉴权。
## 轮询管理:轮询配置预览与统计
本次只需新增一个菜单;已有「轮询配置」`/polling-management/config` 保留,不改旧 CRUD 权限。以下仅列普通账号需要配置的项。
| 菜单名称 | URL | 父菜单 | 菜单权限编码 |
| --- | --- | --- | --- |
| 轮询配置统计 | `/polling-management/config-stats` | 轮询管理 `/polling-management` | `polling_config_stats:page` |
| 按钮名称 | 所属菜单 | 按钮权限编码 |
| --- | --- | --- |
| 匹配预览 / 草稿预览 / 预览未保存修改 | 轮询配置 `/polling-management/config` | `polling_config:match_preview` |
| 查询重算进度 | 轮询配置 `/polling-management/config` | `polling_config:recalculate_progress` |
| 查看重置日前加密查流量效果统计 | 轮询配置统计 | `polling_config_stats:pre_reset` |
| 查看分层轮询统计 | 轮询配置统计 | `polling_config_stats:tiers` |
统计菜单权限和区域权限需同时授权;若仅授权其中一个统计区域,另一区域不会请求接口。进度查询权限只允许查询已有任务,不授予创建任务的能力。上述编码是前端配置约定,后端独立鉴权。
### 接入说明
- 当前配置预览使用 GET;草稿预览使用 POST,并在 Query 和 Body 同时传入同一 ICCID。多条草稿可覆盖已有配置或以 id=0 新增,预览不调用持久化 CRUD。
- 草稿中实名、流量、套餐、卡状态检查区分继承(null)、禁止且不再继承(0)、指定秒数(正数)。保护期已下线,表单和请求均移除。重置日前加密需明确开启,窗口和窗口内流量间隔成对设置。
- 以 2026-10-26 完整接口文档为准:资产状态、套餐状态、重置日前窗口字段现已支持创建/编辑保存;编辑清空通过 `clear_fields`,保存成功展示 `warnings`。
- 时间使用与店铺列表相同的 `formatDateTime`。运营商账户按名称远程搜索,仍提交数字 ID;搜索条件 >=4 时才显示展开按钮。
- 任务进度每 3 秒查询一次,终态、失败、关闭、路由离开和卸载后停止;保留真实 task_id、任务状态及 string 类型的响应账户 ID。
- 统计周期为 null 时显示「无周期数据」,真实 0 保留。分层统计标明 5 分钟缓存,未匹配配置的在库卡和已销售无套餐卡突出告警;刷新不宣称清除服务器缓存。
### 本地验证
```powershell
node --test scripts/tests/pollingConfigExtensions.test.mjs
.\node_modules\.bin\vue-tsc.cmd --noEmit
node scripts/tests/verifyBuild.mjs
node scripts/tests/verifyBuild.mjs --serve --polling
```
最后一条命令启动 `http://127.0.0.1:5190` 的本地模拟接口页面;所有 `/api` 请求被拦截,不会对真实后端保存配置或创建任务。当前未进行真实后端联调、菜单数据写入、Git 推送或生产部署。
2026-10-26 验证:新增轮询配置测试 20 项、全量回归 174 项通过;类型、生产构建、针对性 lint / 格式 / 编码检查通过。浏览器验证了当前预览、草稿控件、异步进度、空周期/零值统计、普通账号入口及小屏布局。生产构建仍有项目既有循环依赖、其他页面常量绑定与大 chunk 警告。
## 轮询管理:运营商账户限流与调度(2026-10-26 增量)
本节在前两次配置的基础上新增,旧菜单和旧权限不必重建。仅列非超级管理员专属的菜单/按钮;标注“平台”的项只允许 user_type=1/2,权限码不能突破身份限制。前端编码是本项目约定,后端仍需独立授权。
### 新增可见菜单
| 菜单名称 | URL | 父菜单 | 菜单权限 |
| --- | --- | --- | --- |
| 运营商账户调度参数 | `/polling-management/carrier-params` | 轮询管理 `/polling-management` | `polling_carrier_params:page` |
| 请求检查场景 | `/polling-management/check-scenes` | 轮询管理 | `polling_check_scene:page` |
| 失败告警 | `/polling-management/failure-alerts` | 轮询管理 | `polling_failure_alert:page` |
| 账户队列监控 | `/polling-management/carrier-queues` | 轮询管理 | `polling_carrier_queue:page` |
| 停复机规则演练(平台) | `/polling-management/stop-resume-dry-run` | 轮询管理 | `stop_resume_dry_run:page` |
| 不轮询清单(平台) | `/polling-management/polling-pauses` | 轮询管理 | `polling_pause:page` |
| 轮询开关导入(平台) | `/polling-management/polling-status-imports` | 轮询管理 | `polling_status_import:page` |
| 导出不轮询清单(平台) | `/asset-management/export-task-management/export-polling-pause` | 导出管理 `/asset-management/export-task-management` | `export_task:polling_pause_page` |
| 导出停机被拒告警(平台) | `/asset-management/export-task-management/export-polling-stop-refused-alert` | 导出管理 | `export_task:polling_stop_refused_alert_page` |
| 导出停复机规则演练(平台) | `/asset-management/export-task-management/export-stop-resume-rule-dry-run` | 导出管理 | `export_task:stop_resume_rule_dry_run_page` |
### 新增隐藏详情菜单
这些是独立页面,不是按钮编码,需配置隐藏路由;URL 参数保留,不替换为具体 ID。
| 菜单名称 | URL | 父菜单 | 菜单权限 |
| --- | --- | --- | --- |
| 运营商账户调度参数详情 | `/polling-management/carrier-params/detail/:carrier_id` | 轮询管理 | `polling_carrier_params:detail_page` |
| 失败告警详情 | `/polling-management/failure-alerts/detail/:id` | 轮询管理 | `polling_failure_alert:detail_page` |
| 轮询开关导入详情(平台) | `/polling-management/polling-status-imports/detail/:id` | 轮询管理 | `polling_status_import:detail_page` |
三个导出场景共用已有隐藏详情 `/asset-management/export-task-management/export-task-detail?id=任务ID`,沿用 `export_task:detail_page`,不再新增详情路由。
### 新增按钮权限编码
| 所属页面 | 按钮/能力 | 编码 |
| --- | --- | --- |
| 运营商账户调度参数 | 查看详情 | `polling_carrier_params:detail` |
| 失败告警 | 查看详情 | `polling_failure_alert:detail` |
| 失败告警 | 账户汇总 | `polling_failure_alert:summary` |
| 失败告警 | 标记已处理(仅未处理状态) | `polling_failure_alert:handle` |
| 失败告警 | 批量关闭卡轮询(平台) | `polling_failure_alert:close_polling` |
| 失败告警 | 导出停机被拒(平台) | `polling_failure_alert:export` |
| 停复机规则演练 | 导出演练明细(平台) | `stop_resume_dry_run:export` |
| 不轮询清单 | 批量开启轮询(平台) | `polling_pause:restore` |
| 不轮询清单 | 创建导出任务(平台) | `polling_pause:export` |
| 轮询开关导入 | 上传并创建任务(平台) | `polling_status_import:create` |
| 轮询开关导入 | 查看任务与逐行结果(平台) | `polling_status_import:detail` |
| IoT 卡列表 | 批量开关轮询(平台/代理) | `iot_card:batch_polling` |
| 设备列表 | 批量开关轮询(平台/代理) | `device:batch_polling` |
| 单卡资产详情 / 卡级告警详情 | 查询单卡轮询状态 | `iot_info:polling_state` |
| 设备资产详情的绑定卡 | 查询该绑定卡轮询状态 | `device_info:polling_state` |
| 导出不轮询清单 | 查看详情 / 下载 | `export_task:polling_pause_detail` / `export_task:polling_pause_download` |
| 导出停机被拒告警 | 查看详情 / 下载 | `export_task:polling_stop_refused_alert_detail` / `export_task:polling_stop_refused_alert_download` |
| 导出停复机规则演练 | 查看详情 / 下载 | `export_task:stop_resume_rule_dry_run_detail` / `export_task:stop_resume_rule_dry_run_download` |
“详情”按钮及对应隐藏详情菜单需同时授权。告警详情内查看停复机记录复用已有 `iot_info:stop_resume_records`;资产单项轮询开关复用 `iot_info:auto_polling` / `device_info:auto_polling`,无需新编码。请求检查场景、队列监控无新增普通写按钮。系统配置沿用旧菜单与权限,仅新增 polling 模块选项。
### 操作边界
- 批量只提交当前勾选 ID,最多 500 条,不扩展成全量筛选;原因必填,先读 impact 再确认。四类逐项结果完整保留,部分成功不回滚。
- 企业账号不开放批量;代理资产范围由后端校验。风险停机、已销户不提供“强制开启”。
- 账户级告警 card_id=0 不请求单卡接口、不允许勾选关闭卡轮询;停机被拒视图隐藏并剔除不支持的筛选。
- 导入仅 CSV,首行为表头,首列保留文本,最多 50000 数据行;上传成功后才创建任务。任务终态/请求失败停止自动刷新。
- 演练仅判断不执行;明细 result 不改变汇总,导出也不带 result;演练允许每页 500,其他列表最大 100。
- 调度、限流、指令队列开关不会因本次前端接入自动修改。旧并发配置仅 legacy 模式有效。
C 端同步项和接口覆盖/验证见 [本次接入交付说明](./2026-10-26-轮询账户限流-后台接入交付.md)。
本次验证:191 项回归通过;类型、生产构建、代码/样式/格式与 UTF-8 检查通过。仅本地 mock 验收,没有写入菜单数据、推送或部署;生产构建仍有项目既有循环依赖与大 chunk 警告。
## 订单分类与沉默期(2026-10-28)
后台实现已按 Apifox 定义补齐。以下为实际路由和前端权限约定;后端仍需创建真实菜单/按钮记录并独立校验权限与数据范围。未推送、部署或写入服务器菜单,真实支付/审批/退款/导出需测试环境联调。准确范围见 [执行记录](../openspec/changes/add-order-segmentation-and-package-silence/implementation.md)。
### 新增可见菜单
| 菜单名称 | URL | 父菜单 | 菜单权限 |
| --- | --- | --- | --- |
| 平台订单 | `/order-management/platform-orders` | 订单管理 `/order-management` | `orders:platform_page` |
| 代理商订单 | `/order-management/agent-orders` | 订单管理 | `orders:agent_page` |
| 在线支付订单 | `/order-management/online-orders` | 订单管理 | `orders:online_page` |
| 延期订单 | `/package-management/silence-orders` | 套餐管理 `/package-management` | `package_silence:orders_page` |
| 延期批次与异常 | `/package-management/silence-batches` | 套餐管理 | `package_silence:batches_page` |
| 沉默期临期/过期套餐 | `/package-management/silence-usages` | 套餐管理 | `package_silence:usages_page` |
| 延期政策 | `/package-management/silence-policies` | 套餐管理 | `package_silence:policies_page`(并需 `package_silence:policy`) |
| 导出平台订单 | `/asset-management/export-task-management/export-order-platform` | 导出管理 `/asset-management/export-task-management` | `export_task:order_platform_page` |
| 导出代理商订单 | `/asset-management/export-task-management/export-order-agent` | 导出管理 | `export_task:order_agent_page` |
| 导出在线支付订单 | `/asset-management/export-task-management/export-order-online` | 导出管理 | `export_task:order_online_page` |
| 导出延期订单 | `/asset-management/export-task-management/export-silence-order` | 导出管理 | `export_task:package_silence_order_page` |
| 导出沉默期套餐 | `/asset-management/export-task-management/export-silence-usage` | 导出管理 | `export_task:package_silence_usage_page` |
代理账号仅可配置平台/代理商普通订单及其导出;在线普通订单及导出只允许 user_type=1/2。企业不得配置普通订单菜单。旧普通订单列表/详情保留。沉默期模块没有额外虚构身份范围,按后端真实授权及数据范围工作。
### 新增隐藏详情菜单
| 菜单名称 | URL | 父菜单 | 菜单权限 |
| --- | --- | --- | --- |
| 延期订单详情 | `/package-management/silence-orders/detail/:id` | 套餐管理 | `package_silence:order_detail_page` |
| 延期批次详情 | `/package-management/silence-batches/detail/:id` | 套餐管理 | `package_silence:batch_detail_page` |
直接访问详情同时要求对应列表页权限、隐藏详情菜单权限和下表详情按钮权限;不能只配隐藏详情菜单。导出详情沿用已有隐藏 `export_task:detail_page` 与已有导出详情 URL。仅超管专属配置不列入普通菜单清单。
### 新增及沿用按钮权限
| 操作 | 权限编码 |
| --- | --- |
| 下单时调整本次沉默期(两个单项购买入口) | `package_silence:override` |
| 扫码付费延期、单项特殊延期 | `package_silence:extend` |
| 批量特殊延期(含 CSV 导入) | 同时需要 `package_silence:extend`、`package_silence:extend_batch` |
| 登记线下付费延期 | `package_silence:offline` |
| 异常明细重试/关闭 | `package_silence:exception` |
| 政策查询/新增/编辑/启停/匹配 | `package_silence:policy` |
| 查看延期订单详情 | `package_silence:order_detail` |
| 查看延期批次详情 | `package_silence:batch_detail` |
| 创建延期订单导出 | `package_silence:order_export` |
| 创建沉默期套餐清单导出 | `package_silence:usage_export` |
| 创建普通订单/查看详情/导出 | 沿用 `orders:add` / `orders:view_detail` / `orders:export` |
| 平台普通订单导出详情/下载 | `export_task:order_platform_detail` / `export_task:order_platform_download` |
| 代理商普通订单导出详情/下载 | `export_task:order_agent_detail` / `export_task:order_agent_download` |
| 在线普通订单导出详情/下载 | `export_task:order_online_detail` / `export_task:order_online_download` |
| 延期订单导出详情/下载 | `export_task:package_silence_order_detail` / `export_task:package_silence_order_download` |
| 沉默期套餐导出详情/下载 | `export_task:package_silence_usage_detail` / `export_task:package_silence_usage_download` |
沉默期流水、首次购买记录没有在后端文档声明独立按钮权限,继承所属资产/列表页的读取范围,不虚构按钮编码。角色配置继续使用后端真实权限树,需后端提供权限记录和 ID,前端不伪造记录。
### 操作边界与验证
- 默认商品沉默期 1–90 天,购买覆盖天数仅最小 1;付费延期天数/金额由资格和试算决定,不复制算法。
- 特殊延期 CSV 为前端解析:表头 `package_usage_id,days`,每行两个整数,转换为文档 items[];不假设后端导入文件格式。
- 政策免审批完整枚举未在 OpenAPI 给出;已有值原样保留,提供明确的 offline_paid/batch,其他值需填写后端精确编码。政策接口没有 DELETE,不提供删除。
- 二维码/线下同一快照重试复用幂等键;特殊请求结果不明时提示核对批次并阻止重复提交。待审批、已支付和已完成严格区分。
- 异常关闭必须填写原因并确认,提示在线订单可能原路退款;不直接修改套餐截止时间。
- 企业资产五项限制保持;首次购买为只读事实,不回填绑定卡或换货资产;对象缺失隐藏沉默期入口。
- 236 项测试、类型与生产构建通过;仅本地 mock 验收,没有真实支付、审批、退款、开关切换、导出、推送或部署。
### C 端同步(本仓库未修改)
独立 C 端需接入可选 silence、状态/格式化截止日及 extendable 入口;`/api/c/v1/package-silence` 下的资格、报价、自助下单/qr_content、订单状态刷新、我的延期订单/详情、流水。对象缺失或总开关关闭时隐藏入口;金额单位分、结果取后端,不能复制计费/审批算法,不调用后台 URL。资产归属由后端校验。

View File

@@ -0,0 +1,16 @@
## Context
代理注册申请由公开注册接口创建,后台需要按数据范围查询申请并展示审批提交状态。恢复审批只恢复原企业微信审批提交,不创建新的注册申请或审批实例。
## Decisions
- 使用列表页 + 独立详情页,详情页 URL 为 `/shop-management/agent-distribution-registrations/detail/:id`。
- 列表和详情均使用后端返回的 `status`、`approval_status`、`submission_status` 和名称字段,不在前端推导状态。
- 恢复按钮仅由后端返回的 `recoverable` 控制,并使用独立 `agent_distribution_registration:recover_approval` 权限。
- 详情响应直接消费后端完整手机号和注册地址,不展示密码或内部审批字段。
## Risks / Mitigations
- 状态可能在列表与详情之间发生变化 → 详情和恢复成功/失败后重新加载后端数据。
- 恢复请求并发冲突 → 后端返回错误时提示并刷新详情,不做乐观更新。
- 手机号属于敏感业务数据 → 页面仅受注册申请列表/详情权限和后端数据范围控制。

View File

@@ -0,0 +1,31 @@
# Change: 增加代理注册申请后台管理
## Why
后台目前无法查看代理扫码注册申请,也无法处理企业微信审批提交失败或结果未知的注册申请。根据 `docs/产品迭代8月份/代理注册管理.md`,需要提供申请列表、详情和恢复原审批提交入口。
## What Changes
- 新增后台代理注册申请列表页,支持状态、申请/决定时间、手机号、关键字、直接上级店铺和提交异常筛选。
- 新增注册申请详情页,展示完整手机号、注册地址、申请店铺、分销码、业务状态、审批状态和企微提交状态。
- 当 `recoverable = true` 时显示“恢复审批”,调用 `POST /api/admin/agent-distribution-registrations/{id}/recover-approval`,成功后刷新详情。
- 新增代理注册申请 API、类型、路由和权限编码。
- 权限编码:列表 `agent_distribution_registration:list`、详情 `agent_distribution_registration:detail`、恢复审批 `agent_distribution_registration:recover_approval`。
## Impact
- Affected specs: `agent-distribution-registration`
- Affected code:
- `src/api/modules/agentDistribution.ts`
- `src/types/api/agentDistribution.ts`
- `src/config/constants/augustIteration.ts`
- `src/router/routesAlias.ts`
- `src/router/routes/asyncRoutes.ts`
- `src/views/shop-management/agent-distribution-registrations/index.vue`
- `src/views/shop-management/agent-distribution-registrations/detail.vue`
- `src/locales/langs/zh.json`
- `docs/权限.md`
- Out of scope:
- C 端注册流程和代理登录流程。
- 后端审批、数据库和企业微信回调实现。
- 修改注册申请业务资料或审批结果。

View File

@@ -0,0 +1,33 @@
## ADDED Requirements
### Requirement: Agent Registration Application List
The admin frontend SHALL provide a paginated agent registration application list with the documented filters and backend response statuses.
#### Scenario: Filter registration applications
- **WHEN** an authorized user selects status, time, phone, keyword, parent shop, or submission anomaly filters
- **THEN** the frontend MUST send those filters to `GET /api/admin/agent-distribution-registrations`
- **AND** the list MUST display business, approval, and submission status names from the response
### Requirement: Agent Registration Application Detail
The admin frontend SHALL provide a detail page for `GET /api/admin/agent-distribution-registrations/{id}` and display the complete registration information returned by the backend.
#### Scenario: Open registration detail
- **WHEN** an authorized user opens a registration application
- **THEN** the frontend MUST request the application detail by ID
- **AND** MUST display the phone, address, shop, distribution code, business status, approval status, and submission status
- **AND** MUST NOT display password or internal approval fields not present in the response
### Requirement: Recover Agent Registration Approval
The frontend SHALL expose `POST /api/admin/agent-distribution-registrations/{id}/recover-approval` only when `recoverable = true` and the user has the recovery permission.
#### Scenario: Recover approval
- **GIVEN** a registration response has `recoverable = true`
- **WHEN** the user confirms “恢复审批”
- **THEN** the frontend MUST call the recovery endpoint with only the registration ID
- **AND** MUST refresh the detail after success or a state conflict

View File

@@ -0,0 +1,17 @@
## 1. API And Types
- [x] 1.1 增加代理注册申请列表、详情和恢复审批 TypeScript 类型。
- [x] 1.2 扩展 `AgentDistributionService`:列表、详情、恢复审批接口。
- [x] 1.3 增加唯一权限常量 `list`、`detail`、`recoverApproval`。
## 2. Pages And Routes
- [x] 2.1 新增注册申请列表页和筛选条件。
- [x] 2.2 新增详情页和审批/提交状态展示。
- [x] 2.3 接入“恢复审批”按钮、确认、错误提示和刷新。
- [x] 2.4 增加店铺管理下的列表/详情路由与中英文菜单文案。
## 3. Documentation And Verification
- [x] 3.1 将页面、详情和恢复审批权限写入 `docs/权限.md`。
- [x] 3.2 运行类型检查、lint、编码检查、构建和 OpenSpec 校验。

View File

@@ -20,7 +20,7 @@ The admin frontend SHALL provide a bulk purchase form that binds one uploaded ba
#### Scenario: Hide voucher upload for wallet payment
- **GIVEN** 用户选择代理钱包支付
- **GIVEN** 用户选择代理预存款支付
- **WHEN** 页面渲染或提交批量订购表单
- **THEN** 页面 MUST NOT submit a voucher file
- **AND** 页面 MUST clear or ignore a voucher selected before switching to wallet payment

View File

@@ -10,7 +10,7 @@
- [x] 2.1 新增批量订购入口和表单,支持选择代理商、支付方式和 Excel 文件。
- [x] 2.2 提供前端静态 Excel 模板下载,并限制上传文件类型和必要的文件状态。
- [x] 2.3 线下支付时显示整批支付凭证上传,钱包支付时隐藏或清理凭证字段。
- [x] 2.3 线下支付时显示整批支付凭证上传,预存款支付时隐藏或清理凭证字段。
- [x] 2.4 复用订单列表已有 `VoucherUpload` 组件展示凭证上传进度,上传未完成时禁止创建任务。
- [x] 2.5 创建请求携带 `shop_id`、`payment_method`、`file`、必要的 `voucher_file` 和 `request_id`。
- [x] 2.6 防止重复点击和重复提交,创建成功后保存 `task_id` 并进入任务详情。

View File

@@ -42,7 +42,7 @@
- src/views/shop-management/business-user-groups/index.vue(新增页面)
- src/views/shop-management/list/index.vue
- src/router/routes/asyncRoutes.ts、src/router/routesAlias.ts、src/locales/langs/{zh,en}.json
- src/template/业务负责人导入模板.csv(前端自带模板)
- src/template/批量换绑业务员模板.csv(前端自带模板)
- API contracts: 11 个端点(7 个业务用户组 + 店铺筛选/字段 + 批量交接 + 导入三步)
- Dependencies:
- docs/产品迭代8月份/业务用户组.md(7 个组端点 OpenAPI)

View File

@@ -0,0 +1,22 @@
## Context
现有前端没有运营商通道阈值命中记录页面或对应 API 类型。后端已提供只读分页查询接口,页面需忠实呈现不可变的命中时快照和周期恢复状态。
## Goals / Non-Goals
- Goals: 提供受限于平台账号的筛选、分页和证据查询;不丢失空值的历史语义。
- Non-Goals: 修改通道阈值、发起停复机、导出记录、查看卡片详情,或查询上游响应。
## Decisions
- Decision: 在系统管理路径下新增独立隐藏查询页,由运营商管理页提供入口;路由使用 `allowedUserTypes: [1, 2]`,页面自身也在请求前检查平台账号。
- Rationale: 接口只允许超级管理员和平台账号。前端隐藏/保护页面入口,后端仍是最终授权及卡数据范围过滤边界。
- Decision: 精确 ID 筛选使用数值输入,计费周期起点使用日期时间选择器,判定时间使用日期时间范围选择器;时间序列化为带时区 RFC3339 秒级字符串。
- Rationale: 与接口的精确匹配和闭区间语义一致,避免按日期截断或丢失时区。
- Decision: 页面仅展示响应快照,不再查询通道配置或根据当前阈值重算历史值。
- Rationale: 命中值冻结于判定时;历史缺失值必须保留接口规定的空值含义。
## Risks / Trade-offs
- 查询页不依赖后端菜单节点;前端入口仅对平台账号显示,页面路由限制用户类型,API 仍执行最终授权和数据范围过滤。
- 表格包含多列证据字段,采用现有可横向滚动的管理台表格以保持信息完整。

View File

@@ -0,0 +1,24 @@
# Change: 新增运营商通道阈值命中记录查询
## Why
达量停机与周期恢复需要可追溯的数字证据。运营人员需要查询每次停机判定时冻结的累计流量、实际阈值、计费周期、触发来源,以及周期解锁和复机结果;通道阈值后续变更不能影响历史记录。
## What Changes
- 在运营商管理页提供“通道阈值命中记录”入口,打开独立只读查询页并接入 `GET /api/admin/carrier-traffic-threshold-hits`。
- 支持按运营商通道 ID、IoT 卡 ID、计费周期起点精确匹配,并按判定时间闭区间筛选。
- 展示命中时的流量和阈值快照、判定/触发信息、锁状态、解锁时间、复机结果及安全失败原因。
- 仅超级管理员与平台账号可访问;数据范围过滤及越权资源不可区分由后端强制执行,前端不替代后端授权。
- 对接口定义的空历史值使用明确的“无”或“未处理/历史记录”展示,不发起额外的通道阈值或上游接口查询。
## Impact
- Affected specs: `carrier-traffic-threshold-hits`
- Affected code:
- `src/api/modules/carrierTrafficThresholdHit.ts`
- `src/types/api/carrierTrafficThresholdHit.ts`
- `src/views/system/carrier-traffic-threshold-hits/index.vue`
- `src/router/routesAlias.ts`, `src/router/routes/staticRoutes.ts`, `src/views/system/carrier-management/index.vue`
- `src/locales/langs/zh.json`, `src/locales/langs/en.json`
- Breaking changes: 无;仅新增只读查询接口消费与页面入口。

View File

@@ -0,0 +1,35 @@
## ADDED Requirements
### Requirement: Carrier Traffic Threshold Hit Record Query
The admin frontend SHALL provide a read-only paginated view of carrier traffic threshold hit records using `GET /api/admin/carrier-traffic-threshold-hits`.
#### Scenario: Restrict page access to platform accounts
- **GIVEN** a user is not a super administrator or platform account
- **WHEN** the user navigates to the carrier traffic threshold hit page
- **THEN** the frontend MUST deny access and MUST NOT issue the hit-record query
- **AND** backend authorization and card data-scope filtering MUST remain authoritative
#### Scenario: Filter hit records
- **GIVEN** an authorized platform user opens the hit-record page
- **WHEN** the user searches by optional carrier ID, card ID, billing period start, or judged-at time range
- **THEN** the frontend MUST send `carrier_id`, `card_id`, `period_start`, `start_time`, and `end_time` only when provided
- **AND** period and judged-at timestamps MUST be timezone-qualified RFC3339 values with second precision
- **AND** `start_time` and `end_time` MUST represent the API's inclusive time interval
#### Scenario: Display immutable hit evidence and recovery result
- **GIVEN** the query returns threshold-hit records
- **WHEN** the frontend renders the table
- **THEN** it MUST display record/card/carrier IDs, hit traffic, frozen threshold value and unit, billing period start, judged time, trigger source, lock status, unlock time, resume result, failure reason, and creation time
- **AND** it MUST NOT recompute hit traffic or threshold from current channel configuration
- **AND** it MUST display nullable historical traffic/threshold values as “无”, blank resume results as “未处理或历史记录”, and missing unlock/failure details as “无”
#### Scenario: Preserve server ordering and pagination
- **GIVEN** the user queries hit records
- **WHEN** the frontend loads or changes the page
- **THEN** it MUST send `page` and `page_size` (never exceeding 100)
- **AND** it MUST render the server-provided page, size, total, and item order without client-side re-sorting

View File

@@ -0,0 +1,10 @@
## 1. API Contract
- [x] 1.1 增加命中记录查询参数、记录项及分页响应类型。
- [x] 1.2 增加 `GET /api/admin/carrier-traffic-threshold-hits` 服务方法并统一导出。
## 2. Admin UI
- [x] 2.1 新增超级管理员/平台账号可访问的隐藏路由、运营商管理页入口及中英文标题。
- [x] 2.2 实现筛选、分页和命中/周期恢复快照表格,按接口约定展示空值。
- [x] 2.3 运行 OpenSpec 校验、ESLint 与生产构建。

View File

@@ -0,0 +1,41 @@
## Context
项目使用 Vue 3、TypeScript、Element Plus 和 BaseService。后端控制菜单模式下,超级管理员直接使用全部静态路由,普通用户使用授权菜单;按钮控制复用现有 `useAuth`,身份复用 `userStore.isSuperAdmin`。
## Goals / Non-Goals
- Goals: 完整接入文档声明的 API、可操作的管理页面、可靠表单校验、清晰权限配置交付。
- Non-Goals: 不实现后端限流,不改变旧轮询/停复机行为,不部署,不猜测统计指标字段。
## Decisions
- 四页统一归属「轮询管理」,不新增一级菜单:
| 页面 | URL | 父菜单 |
| --- | --- | --- |
| 停复机记录 | `/polling-management/stop-resume-records` | 轮询管理 `/polling-management` |
| 上游错误分类 | `/polling-management/error-classifications` | 轮询管理 `/polling-management` |
| 网关限流组 | `/polling-management/rate-limit-groups` | 轮询管理 `/polling-management` |
| 网关调用统计 | `/polling-management/gateway-stats` | 轮询管理 `/polling-management` |
| 网关限流组详情(隐藏路由) | `/polling-management/rate-limit-groups/detail/:id` | 轮询管理 `/polling-management` |
- 页面权限分别为 `card_stop_resume_record:page`、`gateway_error_classification:page`、`gateway_rate_limit_group:page`、`gateway_call_stats:page`,隐藏详情路由使用 `gateway_rate_limit_group:detail_page`。普通操作权限为 `gateway_error_classification:test`、`gateway_rate_limit_group:detail`、`gateway_call_stats:trend`;单卡入口按资产类型使用 `iot_info:stop_resume_records` / `device_info:stop_resume_records`。这些是前端配置约定,不声称来自后端接口文档;详情页与按钮使用独立编码,避免菜单与按钮编码冲突。
- 超级管理员维护入口不定义供普通账号分配的增删改权限;UI 与事件处理双重身份检查,后端继续独立鉴权。
- 提取专用新模块承载网关契约,避免覆盖旧 `/api/cards/{iccid}/suspend-resume-records` 接口及其不同 DTO。
- 枚举请求失败显式展示错误和重试,不把不可用枚举误报为空;未知值在只读展示中保留原值。
- 时间统一转换 RFC3339;全局记录查询必须有完整区间,单卡可使用后端默认;分页最大 100。
- 统计内部字段使用 `unknown`/记录值承载,只展示实际返回字段,空值不转成业务零;不从不明确字段推导图表或指标。
- 界面复用项目现有表格、搜索区、分页、弹窗、主题变量及状态标签;参考 UI/UX skill 的加载反馈、可访问标签、键盘焦点与响应式原则,不更换全站字体、颜色或新增表单依赖。
- 用户补充要求:列表严格复用店铺列表的 ArtSearchBar / ArtTableHeader / ArtTable / ArtTableFullScreen;详情使用店铺详情的返回、标题和双列描述表。时间展示复用同一个 `formatDateTime`,不改变请求与数据源;展开按钮仅在搜索条件数 >= 4 时出现。
- 运营商账户一律名称搜索下拉,复用 `CarrierService.getCarriers({ page: 1, page_size: 20, carrier_name })`,保留原账户名称回显,选中后仍提交 ID;趋势额外保留「无法解析账户的卡」的值 0。
## Risks / Trade-offs
- 统计契约缺字段 → 接口和数据可查看,但正式业务趋势图需后端样例或完整 DTO 后再确定。
- 前端权限编码未在 API 文档定义 → 交付明确为菜单按钮配置编码,不替代后端鉴权。
- 31 天日期窗口和不同时区 → 按实际时间戳差值校验,测试边界与非法值。
- 用户已有未提交改动 → 不碰部署文件及 package 配置,不引入新依赖。
## Validation
服务契约测试覆盖所有 17 个接口;业务测试覆盖时间范围、QPS、优先级操作、超级管理员门禁、枚举值和统计未知字段。执行 `vue-tsc --noEmit`、Vite 构建、针对性 lint/格式/编码检查。没有真实后端响应时,明确区分本地 mock 验证与线上联调。

View File

@@ -0,0 +1,32 @@
# Change: 网关限流管理前端接入
## Why
`docs/网关限流.md` 新增 17 个管理端接口,当前前端缺少网关限流组、上游错误分类、全局停复机记录及按运营商统计的入口。需要完整接入已定义契约,并在交付时提供普通账号需要配置的菜单与按钮权限,不列出仅超级管理员的操作。
## What Changes
- 在现有「轮询管理」下新增「停复机记录」「上游错误分类」「网关限流组」「网关调用统计」四个页面。
- 接入全部 17 个接口及类型;枚举通过 `GET /api/admin/polling-options` 获取,不把可配置枚举仅写死在前端。
- 停复机记录支持文档内筛选、分页、必填时间范围和 31 天跨度校验;单卡信息及设备绑定卡提供单卡历史入口,使用卡 ID 请求新接口。
- 分类规则支持分页筛选、测试现有规则和草稿;限流组支持分页筛选和详情。新建、修改、启停、删除均仅向超级管理员开放,并在操作函数中再次检查身份。
- 限流组表单校验 QPS、预留额度与高优先级操作的关系,删除和启停提供确认与防重复提交。
- 网关统计支持账户汇总及账户趋势查询,校验各接口时间参数。
- 接入路由别名、静态路由和现有后端菜单模式;使用 `xxx:xxx` 格式前端权限常量控制普通用户操作。
- 新增契约、参数校验、权限分支和交互回归测试,运行类型检查、构建及编码检查。
- 完工后输出菜单配置清单(名称、URL、父菜单)与按钮权限编码;清单仅保留非超级管理员专属项。
## Impact
- Affected specs: `gateway-rate-limit-management`(新增)。当前 `openspec list --specs` 无已归档规范;现有 `add-polling-priority-queue` 已完成,与本次新增页面并列,不修改其行为。
- Affected code: `src/types/api/`、`src/api/modules/`、`src/config/constants/`、`src/views/polling-management/`、`src/views/asset-management/asset-information/`、`src/router/routesAlias.ts`、`src/router/routes/asyncRoutes.ts`、`scripts/tests/`。
- 不修改网关后端限流算法、既有轮询调度、停复机执行动作;不自动创建数据库菜单,不推送 Git,不执行生产部署。
- 保留用户在 `.gitea/workflows/deploy.yaml` 与 `package.json` 的现有修改。
## Contract boundary
文档未提供统计接口 `carriers[]`、`points[]` 内部字段,仓库当前也没有 `docs/admin-openapi.yaml` 可补全。实现不得假定次数、失败率、时间戳等字段:先按实际响应提供可查看的动态字段表格/原始数据,并清楚提示契约未展开;有真实字段样例后才绘制业务趋势图。不得用虚构字段或零值冒充统计结果。
权限编码是前端配置约定,并非接口文档声明的后端权限;实际授权仍由后端控制。仅超级管理员限制必须依据现有 `userStore.isSuperAdmin`,不能通过配置普通按钮权限绕过。
用户于 2026-10-24 回复「直接执行」,已批准按此范围实施。

View File

@@ -0,0 +1,98 @@
## ADDED Requirements
### Requirement: 停复机记录查询
The frontend SHALL provide global stop/resume records and single-card history using the two documented admin APIs. Global queries MUST include RFC3339 `start_time` and `end_time` with an ordered range no greater than 31 days, all documented optional filters and pagination of at most 100 rows. Single-card history MUST use the card ID rather than ICCID or device ID.
#### Scenario: 查询全局记录
- **WHEN** 用户进入页面或修改筛选、页码
- **THEN** 前端 MUST 请求 `/api/admin/card-stop-resume-records`,展示记录字段及 `items/page/size/total`
- **AND** 不合法或缺失的时间区间 MUST 阻止请求并显示明确提示。
#### Scenario: 查看单卡历史
- **WHEN** 获授权用户从单卡或设备绑定卡打开历史
- **THEN** 前端 MUST 请求 `/api/admin/iot-cards/{id}/stop-resume-records`
- **AND** 无卡 ID 或无入口权限时 MUST 不请求接口,切换卡后不得残留另一张卡的结果。
### Requirement: 上游错误分类规则
The frontend SHALL implement rule listing, creation, modification, status change, deletion and non-persistent testing according to the documented fields. Rule maintenance MUST be restricted to super administrators. Testing SHALL support the current rule set and an optional valid draft, and display `matched/rule_id/category/category_name/keyword/maybe_accepted`.
#### Scenario: 普通账号测试分类
- **WHEN** 具有测试权限的用户提交操作与上游原始信息
- **THEN** 前端 MUST 调用 `/api/admin/gateway-error-classifications/test` 并展示实际命中结果
- **AND** 空信息或超过 1000 字符 MUST 不得提交,不通过增删改接口测试草稿。
#### Scenario: 超级管理员维护
- **WHEN** 超级管理员提交合法规则或确认启停、删除
- **THEN** 前端 MUST 使用对应 CRUD 或 status 接口,成功后刷新列表
- **AND** 普通账号 MUST 不显示维护入口且无法从处理函数发起维护请求。
### Requirement: 网关限流组
The frontend SHALL implement group listing, details, creation, modification, status change and deletion, including carrier/global and status filters. Maintenance MUST be restricted to super administrators. `max_qps` MUST be an integer in 1–10000, `reserved_qps` MUST be a nonnegative integer less than `max_qps`, operations MUST be nonempty, high-priority operations MUST be a subset and MUST be nonempty when reserved QPS is positive.
#### Scenario: 维护限流组
- **WHEN** 超级管理员提交限流组
- **THEN** 前端 MUST 校验文档的必填、长度、范围及操作关联约束后调用 POST 或 PUT
- **AND** 全局组 MUST 使用空账户值,不得错误提交为具体账户。
#### Scenario: 查询限流组
- **WHEN** 获授权用户查询列表或详情
- **THEN** 前端 MUST 分别调用 `/api/admin/polling-rate-limit-groups` 或 `/{id}` 并展示真实字段
- **AND** 普通账号 MUST 不能通过详情页进入维护操作。
### Requirement: 动态枚举与统计
The frontend SHALL load all seven enum collections from `/api/admin/polling-options`, and SHALL implement carrier summary and trend requests with documented parameter bounds. Undefined inner fields in `carriers` and `points` MUST be presented transparently from actual response data without invented metrics, silently substituted zeros or assumed chart series.
#### Scenario: 加载枚举
- **WHEN** 页面需要筛选、编辑或显示网关枚举
- **THEN** 前端 MUST 使用接口的 label/value,失败时提供错误反馈及重试
- **AND** 未知只读枚举值 MUST 保留原始值,不被显示为另一个已知状态。
#### Scenario: 查询汇总与趋势
- **WHEN** 用户选择合法的统计区间、运营商和聚合粒度
- **THEN** 前端 MUST 请求对应 `/api/admin/polling-stats/carriers` 或 `/{carrier_id}/trend`
- **AND** 汇总 minutes 为 1–60,趋势 minutes 不超过 10080,粒度为有效正整数,账户 0 MUST 可用
- **AND** 契约缺失的内部字段 MUST 以实际字段或原始数据展示并说明限制。
### Requirement: 菜单权限与交付
The frontend SHALL register four pages under existing polling management and honor the existing static/superadmin and backend-menu routing modes. Normal actions MUST use explicit `xxx:xxx` permissions. The handoff SHALL list menu name, URL, parent menu and button permission codes only for non-superadmin-exclusive configuration.
#### Scenario: 普通账号访问
- **WHEN** 普通账号获得相应菜单和按钮权限
- **THEN** 对应页面和普通查询、测试操作 MUST 可用
- **AND** 未授权按钮和请求 MUST 不可用,超级管理员专属维护能力 MUST 不被普通按钮权限开启。
#### Scenario: 交付配置清单
- **WHEN** 实现和验证结束
- **THEN** 交付 MUST 列出实际实现的普通菜单与按钮权限,不列出仅超级管理员专属配置
- **AND** MUST 披露未进行真实后端联调或统计字段不完整等验证限制。
### Requirement: 店铺页面一致性
The frontend SHALL reuse the shop list search, table header, column settings, fullscreen and pagination components, and the shop detail back button, title and responsive description layout. All displayed business timestamps MUST use the same `formatDateTime` formatter as the shop list. Search expansion MUST be enabled if and only if there are at least four search fields. Carrier selection MUST be a remote dropdown searched by carrier name using `/api/admin/carriers?page=1&page_size=20&carrier_name=...` while requests keep numeric IDs.
#### Scenario: 展开与时间显示
- **WHEN** 页面有少于 4 个搜索条件
- **THEN** `show-expand` MUST 为 false;4 个及以上 MUST 为 true
- **AND** 已知列表、详情及统计数据中的业务时间 MUST 展示为店铺列表相同格式,不直接显示 RFC3339 字符串。
#### Scenario: 按名称搜索运营商
- **WHEN** 用户在运营商账户下拉输入名称
- **THEN** 前端 MUST 请求 carriers 列表并携带 page=1、page_size=20、carrier_name
- **AND** 编辑回显 MUST 保留原账户名称,筛选/保存 MUST 提交所选 numeric carrier_id,趋势未解析账户 MUST 仍可选择值 0。

View File

@@ -0,0 +1,29 @@
## 1. 契约和公共能力
- [x] 1.1 确认提案并记录审批。
- [x] 1.2 新增全部接口请求、响应类型和服务方法,统一导出,复用现有认证及错误处理。
- [x] 1.3 接入动态枚举、权限常量、分页与日期/限流参数校验工具。
## 2. 页面与入口
- [x] 2.1 新增停复机记录列表,支持全部筛选字段、分页、默认最近时间段和 31 天校验。
- [x] 2.2 单卡及设备绑定卡新增停复机历史入口,使用真实卡 ID,处理权限及卡切换状态。
- [x] 2.3 新增上游错误分类页,支持列表筛选、超级管理员维护及现有规则/草稿测试结果展示。
- [x] 2.4 新增网关限流组页,支持列表、详情、超级管理员维护及关联字段校验。
- [x] 2.5 新增网关调用统计页,支持汇总、趋势参数和未定义内部字段的透明展示。
- [x] 2.6 注册路由别名、四个菜单路由及隐藏详情路由、页面权限;复用现有后端菜单解析模式。
## 3. 验证与交付
- [x] 3.1 覆盖全部服务 URL、HTTP 方法、参数和响应的契约测试。
- [x] 3.2 覆盖时间、QPS、高优先级操作子集、权限和动态枚举回归测试。
- [x] 3.3 检查加载、错误、空数据、确认、重复提交和响应式显示。
- [x] 3.4 执行类型检查、构建、相关回归测试、格式与编码检查,记录实际结果。
- [x] 3.5 交付菜单名称/URL/父菜单和按钮权限编码,仅列非超级管理员专属配置。
## 验证结果
- 全量 Node 回归 153/153 通过,其中网关新增 23 项;`vue-tsc --noEmit`、生产构建、针对性 ESLint/Stylelint、格式和 UTF-8 检查通过。
- 本地 mock 浏览器验证:列表与详情、规则测试、按运营商名称搜索、账户 0 趋势、普通账号无维护按钮及授权隐藏详情路由;375px / 768px / 1024px / 1440px 检查与局部截图复核。
- 菜单与按钮清单写入 `docs/权限.md`,本地详细接入说明位于 `docs/网关限流-前端接入说明.md`(仓库默认忽略其他 docs 文件)。
- 未进行真实后端联调、Git 推送或生产部署;统计内部字段缺失时按实际响应展示。构建仍有项目既有常量绑定、循环依赖和大 chunk 警告。

View File

@@ -0,0 +1,26 @@
## Context
Vue 3 / Element Plus 后台已有订单列表与详情、两处单项购买、套餐创建/分配/系列授权、资产当前/历史套餐、统一导出、企微审批与角色权限树。本次复用现有能力,延续店铺列表/详情标准、时间格式、条件 >=4 才展开和响应式。
## Decisions
- 原订单列表接收受控分类 props,三个薄路由入口使用独立名称缓存,按分类选择服务与导出场景,不在 query 注入 category。旧列表继续 all;企业路由门禁与请求/处理函数都限制,代理 online 严格禁止,后端继续鉴权。
- 企业操作限制使用公共账号类型判断;不能仅改一个 v-if:覆盖基础信息、绑定卡、当前套餐、历史套餐及父页处理函数,保留 start/stop、历史与只读数据。
- 套餐商品默认天数、单次购买覆盖天数、延期天数分别校验,不能共享错误的 90 天上限;null/空与 0 区分;加油包白名单剔除沉默期字段。原实名生效条件保存为只读基线,禁止转换为购买生效。
- 下单前冻结目标、表单字段和幂等标识;权限取消或资产/套餐切换不发送旧覆盖值。后端决定实际是否适用及是否审批,不靠前端成功提示推定立即生效。
- silence 可选且不可从其他套餐复用。当前/历史套餐分别展示各自响应;后端不返回对象时不猜测未启用与不适用的区别,不请求资格接口。
- 首次购买显示使用 formatDateTime;查询与导出共享同一范围转换,ICCID/IMEI 保持字符串。世代与结束原因由服务端返回,记录 DTO 不明时仅完成字段/筛选,记录弹窗保持待补契约。
- 使用现有预签名上传、凭证、二维码与审批组件,不引入依赖。延期付款金额必须取 quote,不能在浏览器自行按 30 天计费;未知的金额单位与 evidence_refs 结构是实现前置条件。
- 对文档只列 URL、未列 DTO 的延期页面,先列覆盖清单与契约缺口,不擅自制作可写空壳或推断财务模型。
## Validation
2026-10-28 契约补齐:保存 Apifox 的 21 个后台操作为 `docs/api/package-silence.openapi.json`;全部金额为整数分,前端元输入精确转换。首次购买记录使用 `/api/admin/assets/{asset_type}/{id}/first-purchase-records`,流水/首次购买记录为数组;政策列表也为数组但支持 page/page_size,因此显示上一页/下一页而不伪造总数。政策适用系列/套餐使用既有名称搜索接口。
特殊延期 CSV 在前端按 `package_usage_id,days` 两列解析,再以明确的 items[] 提交,不猜后端 import_file_key 的未说明文件格式。二维码/线下订单同一快照重试复用 request_id;特殊接口不定义幂等字段,结果不确定时阻止重复提交并提示核对批次。免审批场景保留真实返回的字符串,提供文档明确的 offline_paid/batch;其他编码需后端提供,不猜完整枚举。
先记录当前 198 项基线与 dirty worktree;新增精确请求/角色/字段校验及组件行为测试,覆盖企业 5 项操作但保留停复机、三分类服务、导出 false/0、套餐天数边界、购买覆盖与原因、无权限不发字段、加油包剔除、首次购买时间与空值、未知错误和 0 元退款。运行全量 Node 测试、vue-tsc、受影响文件 lint/format/encoding、生产构建与针对性本地 mock;不把不完整 DTO 的自造响应作为后端验收。
## Rollout and risks
无数据库迁移,不自动开沉默期总开关,旧订单路由/导出与现有菜单配置保留。新菜单是否可见仍需后端菜单数据授权;清单在实施后按实际 URL/权限交付。真实支付与审批、资产范围和文件内容需测试环境联调。C 端为独立工程,仅提供同步清单。

View File

@@ -0,0 +1,61 @@
# 执行记录:订单分类与沉默期
## 当前结论
本后台代码已按汇总文档及用户授权的 Apifox 定义补齐,原先因缺少 DTO 挂起的延期办理、政策、批次异常和记录弹窗已实现。未修改独立 C 端,未推送、部署或调用真实业务写入;不能把本地 mock 验证等同于线上验收。
## 契约来源与差异
21 个后台操作读取自用户授权的 Apifox 分享文档,留存无密码快照 [package-silence.openapi.json](../../../docs/api/package-silence.openapi.json)。本会话通过官方 Apifox MCP Server 0.0.18 的 --oas 模式验证文档读取,不代表直接实时连接整个私有项目;线上变更后需重新读取快照。
- 所有延期金额、单价均为整数分;元输入做精确整数转换,不能使用浮点金额直接提交。
- 首次购买记录真实路径为 `GET /api/admin/assets/{asset_type}/{id}/first-purchase-records`,不是汇总里带 package-silence 前缀的路径。
- 首次购买记录、沉默期流水为数组;政策列表也是数组且有 page/page_size,因此政策页不伪造 total。
- 更新政策与启停请求含 id;特殊收款时间是 offline_paid_at,线下订单是 paid_at。
- 两个沉默期导出场景依据 orders/usages 各自文档启用,filters 与列表同范围;通用导出接口对 query 的类型为字符串值,沿用 JSON 字符串 filters。之前三类普通订单仍保留汇总明确要求的对象 filters。
## 实现覆盖
| 范围 | 已实现 |
| --- | --- |
| 分类订单 | 平台/代理/在线三页、独立精确路径与 scene、旧列表详情及历史导出保留;代理禁止 online、企业禁止普通订单 |
| 企业资产限制 | 有效期、已用量、停用、轮询、实名状态五类入口和处理函数限制;授权资产停复机保持;未找到仍为普通未找到 |
| 套餐与购买 | 商品默认 1–90 天、加油包剔除、生效条件限制;单项/批量/系列分配写前校验;两处下单覆盖无 90 天上限并有权限及原因校验 |
| 资产沉默期 | 按可选 silence 展示真实状态/截止/累计;真实 usage ID 打开延期与流水;对象缺失隐藏 |
| 扫码延期 | 资格、后端报价、wechat/alipay 二维码、确认后创建、订单刷新;终态/错误/关闭停止刷新;不复制计价算法 |
| 线下登记 | 实收元转分、与报价一致、收款方式字典、交易单号、RFC3339 付款时间、1–5 张凭证、申请依据;待审批不显示已生效 |
| 特殊与批量 | 五类特殊延期、原因/依据、优惠价收款;CSV 两列转 items[],校验表头/整数/重复 ID;批量需 extend 和 extend_batch;展示真实批次与错误行 |
| 订单与批次 | 列表/详情/筛选、订单导出;批次详情逐行异常;重试/关闭需原因及确认,关闭提示可能原路退款 |
| 临期与过期 | expiring/expired/all 视图、默认 7 天、资产/店铺/套餐/截止范围及导出;延期与流水入口 |
| 延期政策 | 列表、详情加载、新增/全量编辑、启停、匹配、重叠错误;系列/套餐名称搜索;无 DELETE 不提供删除 |
| 首次购买 | 卡/设备时间列、RFC3339 筛选/导出、资产详情;列表记录入口和只读世代历史,展示来源/订单/结束原因;不伪造绑定卡或换货时间 |
| 配置与兼容 | 专用总开关/precheck/failed_items、通用配置只读、企微审批类型、六项真实权限识别、1260–1275 提示及零元退款 |
同一二维码/线下请求快照重试使用相同 request_id,不自动重发写请求。特殊延期没有文档定义的幂等参数,传输结果不确定时阻止再次提交并提示先核对批次;不得直接修改截止时间替代异常处理。
CSV 为本地解析的 `package_usage_id,days` 两列格式,经文档 items[] 提交,未猜测后端 import_file_key 的文件格式。政策免审批场景完整枚举未在 OpenAPI 列出:提供明确的 offline_paid、batch,并保留服务端现有值;其他编码由后端提供后填写,不根据中文自行造值。批次及明细未知状态原样显示,不推断“已完成”。
## 验证
当前全量 **236 项测试通过**(保留原 198 项,上一阶段 18 项,本阶段 20 项)。覆盖 21 个精确 HTTP 操作、金额精度与 0、CSV、报价失效、权限撤销/确认取消、幂等重试、迟到响应、线下凭证与审批、特殊结果不确定防重复、政策完整提交、异常 ID/原因、导出白名单与模板编译。
类型检查、生产构建、受影响代码 ESLint/Prettier/Stylelint、UTF-8 检查通过。生产构建仍有项目既有常量 v-model、API 循环依赖及大 chunk 警告,未在本轮扩大重构。
本地浏览器使用 `127.0.0.1:5190` 全 /api 拦截 mock,核验临期状态与格式化截止时间、31 天后端试算为 60 天、提交确认及订单刷新、政策编辑与 390px 窄屏、批次异常原因确认。上一阶段三类订单/角色门禁/套餐配置/总开关 mock 检查仍保留。没有请求真实支付或审批接口。
```powershell
$tests = @(rg --files scripts/tests -g '*.test.mjs')
node --import ./scripts/tests/register-esbuild.mjs --test --test-reporter=spec $tests
.\node_modules\.bin\vue-tsc.cmd --noEmit
node scripts/tests/verifyBuild.mjs
node scripts/tests/verifyBuild.mjs --serve --order-silence
openspec validate add-order-segmentation-and-package-silence --strict
```
## 菜单、权限和 C 端
完整菜单/URL/父菜单与普通按钮编码见 [权限清单](../../../docs/权限.md#订单分类与沉默期2026-10-28)。不列仅超管专属设置,不写入服务器菜单或伪造权限 ID。
C 端需要另行接入:可选 silence 状态/截止与 extendable 入口;资格、后端报价、自助订单/qr_content、订单状态刷新、我的延期订单和流水;总开关关闭或对象缺失隐藏入口;金额为分、不能复制计费/审批规则。对应 `/api/c/v1/package-silence`,不复用后台 URL;资产归属鉴权交给后端。本仓库未修改 C 端代码。
真实测试环境仍需验收:数据范围与权限、实际商户支付及查单、企微通过/驳回、异常关闭退款、上传文件和导出下载内容。全部检查只证明前端实现及本地契约行为,不证明后端已部署兼容。

View File

@@ -0,0 +1,43 @@
# Change: 订单分类拆页与套餐沉默期后台接入
## Why
依据 `docs/2026-10-27-订单拆分至沉默期-前端修改汇总(1).md`,后台尚未接入订单分类列表、企业账号操作限制、套餐沉默期及延期、首次购买套餐时间。需要保留既有订单详情、付款/审批、套餐分配与资产功能,并区分前端实现和真实后端联调。
用户于 2026-10-28 明确要求“根据文档来写提案,然后执行”,本提案完成严格校验后按该授权实施。延续只修改本后台仓库的范围,不修改独立 H5/C 端,不推送或部署。工作区已有四个轮询修复文件必须保留。
## What Changes
- 订单管理新增平台、代理商、在线支付三页,复用原列表及详情、筛选、创建能力;各自请求 `/orders/platform|agent|online`,不提交类别参数,导出分别使用 `order_platform|order_agent|order_online`。保留旧列表及历史 `order` 导出。代理隐藏在线支付页,企业隐藏订单菜单并阻止页面请求;不改变后端数据范围。
- 企业账号隐藏并在处理函数阻止资产改有效期、改已用量、停用、开关轮询、改实名状态五项操作,保留授权资产的停复机及读取。未找到不改写为无权限。
- 正式套餐新增默认沉默期(1–90 天)与付费延期开关;实名即生效必填,新建默认 30 天;购买即生效可选;加油包不显示、不提交。新增未配置筛选与导出参数、详情展示;明确生效条件不可从实名改成购买,购买改实名需同请求带天数。
- 后台两处单项下单入口增加有权限才可填写的 `silence_period_days`、`silence_reason`;购买覆盖天数仅最小 1、不套用套餐配置 90 天上限,天数存在时原因必填。保留后端审批结果,不将待审批说成已延期。
- 资产当前套餐、历史套餐按可选 `silence` 对象展示状态、截止日、累计与审批信息;对象缺失时隐藏,入口按 `extendable` 与权限控制。流水使用真实 usage ID。
- 卡/设备新增首次购买时间列、RFC3339 范围筛选、导出参数、详情与只读记录弹窗;绑定卡不伪造首次购买时间,换货历史以服务端世代与结束原因展示,不在前端推算或回填。
- 新增沉默期专用开关页(仅超管),展示 `precheck` 与 1275 的 `failed_items`;通用系统配置不写此开关。增加沉默期审批业务类型与六个权限点的前端识别;角色权限树沿用服务器数据,不伪造权限 ID。
- 完整目标包含延期资格/试算/二维码、线下付款、特殊单项/批量延期、延期订单/批次异常、临期/过期清单、延期政策以及两个沉默期导出场景;金额、审批与状态均以服务端事实为准,不复制后端计费规则。
- 错误码 1260–1275 保留服务端具体原因、限制与异常行;零元退款允许提交,后台线下购买未实名套餐仍按后端待生效状态展示。
## Contract gaps and execution boundary
首次执行时,`docs/admin-openapi.yaml`、被引用的沉默期技术方案与后端规范未提供,因此对应可写业务未实施。2026-10-28 用户补充并授权带密码的 Apifox 分享文档访问后,已取得 21 个后台操作,保存为 `docs/api/package-silence.openapi.json`(不含密码)。下面四组缺口现已按该权威定义补齐,任务第 3 节已执行;真实环境支付/审批/导出仍需联调验收。
初次记录的缺口(现已由 Apifox 补齐):
1. 延期政策 POST/PUT 字段、字段类型、级别/范围/重叠规则、列表/详情响应与状态枚举。
2. 资格 options、quote、二维码及线下订单响应的字段结构、金额单位、订单 ID/状态/支付状态;超时重试的 request_id 复用约定。
3. 特殊延期优惠收款字段名、amount 与 paid_amount 单位、evidence_refs 元素结构、批量部分成功/异常响应完整结构。
4. 流水、延期订单、批次/明细、usage 清单、首次购买记录的分页结构、筛选、时间与状态字段;未定义处不得擅自命名。
执行顺序:先完成本文可确定的订单、企业限制、套餐/下单字段、首次购买字段/筛选、审批类型和错误提示;契约缺口独立保持未完成。若执行期间补齐规范,再继续完成相应延期业务。不得以全部接口存在或本地测试通过代替完整业务验收。
## Impact
- Affected specs: 新增 `order-segmentation-and-package-silence` 接入约束;当前无已发布 specs,以 ADDED 记录,不伪造 MODIFIED 基线。
- Affected code: order、packageManage、shopPackageAllocation、asset、card、device、wecom、systemConfig、exportTask 的类型/服务/界面、路由与权限、相关工具及回归测试。
- 与 `update-october-batch-one-admin-integration` 的订单支付信息、退款审批状态,以及 `update-package-allocation-expiry-base-override` 的分配覆盖保持兼容;不重置此前轮询修复。
- 不产生真实支付、审批、资产写入、导出、开关切换或 CSV 导入;写操作验证仅本地 mock。
## Delivery
交付提案、实际改动与测试证据;菜单清单给出名称、URL、父菜单、普通按钮编码,不重复列仅超管专属项;单列 C 端同步要求和确实因契约缺失未完成的工作。

View File

@@ -0,0 +1,75 @@
## ADDED Requirements
### Requirement: 订单分类与角色边界
The admin frontend SHALL expose independent platform, agent and online order pages using the corresponding documented endpoints and export scenes without category query parameters. It MUST preserve legacy order history and the shared detail contract. Enterprise accounts MUST not query or mutate orders, and agents MUST not access online orders.
#### Scenario: 分类查询和导出
- **WHEN** 平台账号打开某类订单或创建该类导出
- **THEN** 请求 MUST 使用对应路径和 scene,保留原筛选,不改变订单详情接口。
#### Scenario: 不允许的账号
- **WHEN** 企业账号尝试进入订单页,或代理进入在线订单
- **THEN** 菜单和页面请求 MUST 被限制,不以按钮授权覆盖身份限制。
### Requirement: 企业资产操作限制
The frontend SHALL hide and block expiry adjustment, used-data adjustment, deactivation, polling toggle and realname-status adjustment for enterprise accounts across all existing asset entrypoints while preserving authorized start/stop and reads. A not-found asset response MUST remain ordinary not-found feedback.
#### Scenario: 已授权企业资产
- **WHEN** 企业账号查看已授权卡或设备
- **THEN** 五项禁止操作 MUST 不可见且处理函数不能提交,停复机仍按原权限可用。
### Requirement: 套餐默认沉默期与购买覆盖
The frontend SHALL distinguish package defaults (1–90 days), purchase overrides (minimum 1, no documented upper bound) and backend-priced extensions. Formal activation-based packages MUST require defaults with 30 days prefilled only for creation; addons MUST omit silence fields. Forbidden expiry-base transitions MUST be prevented where source data is known and backend rejection preserved otherwise.
#### Scenario: 默认配置
- **WHEN** 新建实名即生效正式套餐或将购买生效改为实名生效
- **THEN** 保存 MUST 携带有效 silence_period_days,不能从实名改为购买生效。
#### Scenario: 单次购买覆盖
- **WHEN** 有 override 权限的用户填写本次沉默期
- **THEN** 请求 MUST 同时包含有效天数与原因;无权限或未填写时不发覆盖字段,等待审批不能显示为已延期。
### Requirement: 可选沉默期与首次购买事实展示
The frontend SHALL show silence status and timestamps only when the server returns the applicable silence object. First-purchase timestamps SHALL remain read-only server facts with shared range filtering/export and generation history, never synthesized for bound cards or exchanges.
#### Scenario: 总开关关闭
- **WHEN** 套餐响应不包含 silence
- **THEN** 沉默期状态及延期入口 MUST 隐藏,不推算默认截止时间。
#### Scenario: 首次购买范围
- **WHEN** 用户按首次购买时间查询卡或设备并导出
- **THEN** 列表和导出 MUST 使用相同 RFC3339 范围,空时间仍显示为空且不开放修改。
### Requirement: 延期与审批使用真实后端契约
The frontend SHALL use documented eligibility, quote, payment, special extension, policy, batch and history contracts. Amounts and state transitions MUST remain backend facts. Undefined DTO fields or money units MUST be reported as missing prerequisites rather than implemented through guessed writes or arbitrary JSON forms.
#### Scenario: 缺少财务契约
- **WHEN** 汇总未定义政策保存字段、金额单位或收款结构且权威文档不可用
- **THEN** 对应实现项 MUST 保持未完成,交付说明准确列出需要补充的契约。
#### Scenario: 专用总开关与错误反馈
- **WHEN** 超管切换总开关或后端拒绝延期
- **THEN** 前端 MUST 走专用开关接口并展示 precheck/failed_items 或具体错误;不得用通用系统配置绕过检查。
### Requirement: 交付与验证边界
The change SHALL preserve existing routes, permissions, worktree edits and successful payment/approval behaviors. It MUST include targeted regression tests and an actual menu/permission handoff, excluding superadmin-only configuration from ordinary-user setup. H5/C-end work and real-backend validation MUST be disclosed separately.
#### Scenario: 执行交付
- **WHEN** 本轮工作停止或完成
- **THEN** 交付 MUST 区分已实现、已本地验证、真实联调待办与缺契约未实现项,不以 mock 或服务数量宣称全部完成。

View File

@@ -0,0 +1,33 @@
## 1. 提案与契约
- [x] 1.1 完整核对汇总文档、现有代码、未归档提案和四个轮询 dirty 文件。
- [x] 1.2 严格校验本提案,按用户明确的先提案后执行授权实施。
- [x] 1.3 通过用户授权的 Apifox 分享文档收齐 21 个后台操作及金额单位,保留无密码的 OpenAPI 快照;首次购买记录以真实 `/api/admin/assets/{asset_type}/{id}/first-purchase-records` 为准。
## 2. 文档明确的后台改动
- [x] 2.1 三类订单服务/独立路由/复用列表/独立导出场景,保留旧列表与详情。
- [x] 2.2 代理隐藏 online、企业隐藏订单/禁止请求;企业五项资产操作所有入口和处理函数限制,保留停复机。
- [x] 2.3a 套餐默认沉默期与延期开关、未配置筛选/导出、详情、加油包剔除与商品自身生效条件转换校验。
- [x] 2.3b 分配/批量/系列覆盖写入前复用套餐详情校验,不猜候选 metadata;覆盖不合法不发写请求,保留后端 1262 约束及原 Body。
- [x] 2.4 两处后台单项下单覆盖天数/原因、权限、正确边界与请求白名单。
- [x] 2.5 资产当前/历史套餐按可选 silence 展示状态、截止日、累计和审批状态,不伪造延期完成。
- [x] 2.6 卡/设备首次购买时间列/筛选/导出/详情,保持只读,不在绑定卡填充。
- [x] 2.7 沉默期开关专用接口/超管页/检查失败展示,通用系统配置只读。
- [x] 2.8 企微沉默期审批类型、六项权限识别、错误码提示、零元退款校验与等待实名文案核查。
## 3. 完整契约补齐后实施
- [x] 3.1 资格/后端报价与二维码延期、支付状态刷新、同快照幂等键复用与迟到响应隔离。
- [x] 3.2 线下付款登记、元转整数分、金额一致性、1~5 张凭证与真实审批状态反馈。
- [x] 3.3 特殊单项/批量 CSV 转换为文档 items[]、原因依据、优惠收款、逐行失败与异常状态;无幂等接口的超时不自动重发。
- [x] 3.4 延期订单/详情/导出、批次/明细/原因确认后重试关闭、临期/过期 usage 清单/导出。
- [x] 3.5 延期政策列表/新增/编辑/匹配/启停/重叠反馈;后端未提供 DELETE,不虚构删除。
- [x] 3.6 沉默期流水与卡/设备列表、资产详情的首次购买记录弹窗。
## 4. 验证与交付
- [x] 4.1 精确请求与角色、金额/天数边界、0/false/null、异步生命周期、审批状态与错误行回归。
- [x] 4.2 类型、全量 236 项测试、构建、lint/样式/格式/编码,保留用户已有修改和声明;执行证据见 implementation.md。
- [x] 4.3 已实施范围的本地 mock 页面与窄屏验收;真实后端未验证内容单列。
- [x] 4.4 实际菜单/URL/父菜单/普通按钮权限、C 端同步清单、接口差异与真实联调待办交付,已写入 docs/权限.md 与 implementation.md;未部署,不归档为线上已验收。

View File

@@ -32,12 +32,14 @@
### 3. 常量与权限
- **修改**: `src/config/constants/augustIteration.ts` — `AUGUST_PERMISSIONS` 新增 `packageTrafficAlert` 权限组
- `trafficAlertRules: 'package_traffic_alert:rules_view'`
- `trafficAlertRuleCreate: 'package_traffic_alert:rule_create'`
- `trafficAlertRuleUpdate: 'package_traffic_alert:rule_update'`
- `trafficAlertRecords: 'package_traffic_alert:records_view'`
- `trafficAlertRecordDetail: 'package_traffic_alert:record_detail'`
- `trafficAlertExport: 'package_traffic_alert:export'`
- `rulesView: 'package_traffic_alert:rules_view'`
- `ruleCreate: 'package_traffic_alert:rule_create'`
- `ruleUpdate: 'package_traffic_alert:rule_update'`
- `ruleEnable: 'package_traffic_alert:rule_enable'`
- `ruleDisable: 'package_traffic_alert:rule_disable'`
- `recordsView: 'package_traffic_alert:records_view'`
- `recordDetail: 'package_traffic_alert:record_detail'`
- `export: 'package_traffic_alert:export'`
- **新增/修改**: 通知状态枚举常量(1 已通知 / 2 待投递 / 3 投递失败 / 4 未通知(接收人已失效)/ 5 未通知(无有效业务员))及对应 tag 类型映射
- 若既有导出任务列表需要区分本场景,补充对应导出场景配置(场景值联调时与后端确认)

View File

@@ -2,6 +2,20 @@
## ADDED Requirements
### Requirement: 真流量预警规则按钮权限必须唯一
规则页面 SHALL 为查看、新增、编辑、启用和停用操作使用唯一的权限编码;启用和停用不得复用编辑权限。
#### Scenario: 按操作校验规则权限
- **WHEN** 用户访问真流量预警规则页面
- **THEN** 页面查看权限 MUST 使用 `package_traffic_alert:rules_view`
- **AND** “新增规则” MUST 使用 `package_traffic_alert:rule_create`
- **AND** “编辑” MUST 使用 `package_traffic_alert:rule_update`
- **AND** “启用” MUST 使用 `package_traffic_alert:rule_enable`
- **AND** “停用” MUST 使用 `package_traffic_alert:rule_disable`
- **AND** 上述权限编码 MUST 互不相同
### Requirement: 套餐真流量预警规则列表查询
系统 SHALL 提供套餐真流量预警规则列表查询页面,展示规则与套餐商品关联信息,支持按套餐商品与启用状态筛选和分页。

View File

@@ -9,7 +9,7 @@
## 2. 常量与权限
- [x] 2.1 `src/config/constants/augustIteration.ts`:`AUGUST_PERMISSIONS` 新增 `packageTrafficAlert` 权限组(rules_view / rule_create / rule_update / records_view / record_detail / export)
- [x] 2.1 `src/config/constants/augustIteration.ts`:`AUGUST_PERMISSIONS` 新增 `packageTrafficAlert` 权限组(rules_view / rule_create / rule_update / rule_enable / rule_disable / records_view / record_detail / export)
- [x] 2.2 新增通知状态常量:枚举 1-5 文案(已通知/待投递/投递失败/未通知(接收人已失效)/未通知(无有效业务员))及 tag 类型映射
- [x] 2.3 若导出任务列表需要场景区分,补充真流量预警导出场景配置(场景值与后端确认后更新 `EXPORT_TASK_SCENE_CONFIG` 及 `getExportTaskSceneName`)
@@ -29,7 +29,7 @@
## 5. 路由、菜单与国际化
- [x] 5.1 `src/router/routesAlias.ts`:新增 `TrafficAlertRules` / `TrafficAlerts` / `TrafficAlertDetail`
- [x] 5.2 `src/router/routes/asyncRoutes.ts`:套餐管理分组下新增规则页、记录页(keepAlive)与隐藏详情路由
- [x] 5.2 `src/router/routes/asyncRoutes.ts`:套餐管理分组下新增规则页、记录页(keepAlive)与隐藏详情路由;规则页 URL `/package-management/traffic-alert-rules` 增加 `rulesView` 页面权限
- [x] 5.3 `src/locales/langs/zh.json` / `en.json`:`menus.packageManagement` 新增 `trafficAlertRules` / `trafficAlerts` / `trafficAlertDetail`
## 6. 联调与验收

View File

@@ -0,0 +1,45 @@
# Change: 接入轮询配置匹配预览、调序、重算和统计
## Why
`docs/轮询配置管理_API简化版.md` 新增 7 个接口。当前 `PollingConfigService` 仅有配置 CRUD、启停和启用列表,轮询配置页面没有匹配预览、优先级整体调整、异步重算及统计入口。需要按已明确的契约补齐,并延续之前菜单、权限和界面交付标准。
## What Changes
- 为全部 7 个新增接口补充服务方法、请求/响应类型及契约测试。
- 在既有「轮询配置」`/polling-management/config` 内增加匹配预览入口:支持当前配置 GET 预览,以及携带多条未保存修改的 POST 预览。支持新增草稿(id=0)、覆盖配置和模拟停用,展示卡信息、命中配置和最终任务间隔;预览不写数据。
- 草稿表单支持资产状态、套餐状态、五项检查间隔及重置日前窗口字段,准确区分前四项间隔的 null 继承、0 禁用和正数间隔;保护期 null 不检查。新增字段仅进入文档明确的 overrides,不擅自扩展旧 CRUD 保存契约。
- 为超级管理员接入优先级排序提交和确认后的异步重算,界面和事件双重身份检查,不创建普通用户可分配的专属操作权限。
- 在既有配置页面提供按 task_id 查询重算进度入口;启动后可自动查询,关闭、卸载和终态清理轮询,失败保留任务 ID 与错误信息。
- 在「轮询管理」下新增「轮询配置统计」`/polling-management/config-stats`,包含重置日前加密查流量统计、分层统计两个独立授权区域;不额外增加一级菜单或详情路由。
- 界面沿用店铺列表及店铺详情标准;业务时间使用 `formatDateTime`;搜索展开仅在条件数 >=4 时启用;运营商账户复用按名称搜索的远程下拉。
- 完成后在 `docs/权限.md` 与最终回复列明实际新增菜单名称、URL、父菜单、页面权限和按钮权限,仅列普通账号配置。
## Impact
- Affected specs: `polling-config-extensions`(新增);仓库当前没有已归档 specs,已完成的 `add-gateway-rate-limit-management` 提供可复用账户搜索和通用交互能力,不更改它的接口与权限。
- Affected code: `src/api/modules/pollingConfig.ts`、`src/types/api/pollingConfig.ts`、类型统一导出、新权限常量、`src/views/polling-management/config/`、新增统计页、路由别名和静态路由、`scripts/tests/`、`docs/权限.md`。
- 保留当前工作区全部既有修改,包括网关限流、停复机时间控件、用户部署文件和 `package.json`。
- 不执行真实配置修改、优先级提交、重算任务创建、Git 推送或线上部署;写接口只用本地 mock 验证。
## Contract boundaries
- POST 匹配预览同时在 Query 与 JSON Body 传同一 ICCID;Body 包含必填 iccid,不能只传其中一处。
- 优先级接口没有明确成功 data DTO,不读取虚构的返回列表;成功后主动刷新配置列表。
- 重算 carrier_id 请求为 number/null,响应为 string,任务状态和计数按接口原值展示;不把重算完成误解为停复机执行或强制推后轮询。
- 两个统计接口提供明确 DTO,按该结构展示;周期 null 显示无数据,0 保留为真实零。分层统计注明 5 分钟缓存,未匹配项突出告警;统计刷新不宣称清除后端缓存。
- 新文档只明确 overrides 支持额外配置字段,未给出新版持久化 CRUD 契约。因此保留原保存行为,用独立草稿表单承载新增预览字段;待后端提供明确保存契约后再扩展原保存表单。
## Proposed ordinary-user configuration
| 项目 | URL / 编码 | 父菜单 / 位置 |
| --- | --- | --- |
| 轮询配置统计 | `/polling-management/config-stats`,页面权限 `polling_config_stats:page` | 轮询管理 |
| 匹配预览(当前配置/草稿) | `polling_config:match_preview` | 既有轮询配置 |
| 查询重算进度 | `polling_config:recalculate_progress` | 既有轮询配置 |
| 查看重置日前统计 | `polling_config_stats:pre_reset` | 轮询配置统计 |
| 查看分层统计 | `polling_config_stats:tiers` | 轮询配置统计 |
以上是前端配置约定,后端独立鉴权。既有轮询配置菜单和旧 CRUD 权限不因本次接入强制迁移。
用户于 2026-10-24 回复「执行」,并于 2026-10-26 回复「继续」,已批准按本提案实施。

View File

@@ -0,0 +1,87 @@
## ADDED Requirements
### Requirement: 当前及未保存配置匹配预览
The frontend SHALL implement GET and POST `/api/admin/polling-configs/match-preview`. ICCID MUST be nonempty and at most 30 characters. POST MUST send the identical ICCID in query and JSON body, with optional overrides. Results MUST show the card, all matched configurations and final task intervals, preserving interval/disabled/unmatched modes, inherited and draft indicators. Preview MUST NOT call create/update/delete/status APIs.
#### Scenario: 当前配置预览
- **WHEN** 获匹配预览权限的用户输入 ICCID 查询当前配置
- **THEN** 前端 MUST 发起 GET 查询并展示 card、matched、intervals,不擅自推导匹配顺序或最终间隔。
#### Scenario: 草稿覆盖预览
- **WHEN** 用户添加 id=0 的新草稿或覆盖已有配置并提交
- **THEN** 前端 MUST 发起 POST,Query 与 Body 的 iccid 一致,overrides 保留原有顺序、id 和 disabled
- **AND** 编辑未保存字段 MUST 不触发真实写接口,旧预览结果 MUST 不污染新的卡或草稿。
### Requirement: 草稿字段与检查语义
The draft form SHALL support every documented override field. The four ordinary task intervals MUST distinguish null/omitted inheritance, zero disable-without-inheritance and positive intervals subject to documented minima. Protect interval null MUST mean no check and non-null values MUST be integers of at least 30. Pre-reset window fields MUST use documented minima and clearly explain that both are required for effect. New preview-only fields MUST NOT be silently added to undocumented persisted CRUD bodies.
#### Scenario: 禁用与继承不同
- **WHEN** 用户将实名、流量、套餐或卡状态检查设为禁用
- **THEN** 对应值 MUST 为 0,不得变成 null 或被过滤掉
- **AND** 继承模式 MUST 使用 null/省略值,正数模式 MUST 校验对应 30 或 60 秒下限。
#### Scenario: 新字段隔离
- **WHEN** 草稿设置资产状态、套餐状态或重置日前窗口
- **THEN** 字段 MUST 仅进入已定义的 overrides 契约,不得因预览自动保存配置。
### Requirement: 优先级调整与异步重算
The frontend SHALL implement PUT `/api/admin/polling-configs/priorities` and POST `/api/admin/polling-configs/recalculate-due` with superadmin-only UI and event guards, explicit confirmation and duplicate-submit prevention. Ordered IDs MUST be nonempty, unique and valid; no undefined success DTO SHALL be assumed. Recalculation MUST be described as advance-only asynchronous work, not immediate completion of all card actions.
#### Scenario: 保存优先级顺序
- **WHEN** 超级管理员确认有效顺序
- **THEN** 前端 MUST 提交 ordered_ids 并在成功后重新获取列表
- **AND** 普通账号 MUST 无法通过 UI 或处理函数发起调序或重算启动。
#### Scenario: 启动重算
- **WHEN** 超级管理员选择运营商账户或全部并确认
- **THEN** 前端 MUST 提交 number/null carrier_id、保留 task_id 并展示真实任务状态,不在 POST 返回时直接宣称重算完成。
### Requirement: 任务进度查询
The frontend SHALL expose GET `/api/admin/polling-configs/recalculate-due/{task_id}` under a normal-user progress permission. It MUST show task ID, status, total/processed/advanced, response string carrier ID, errors and formatted timestamps. Automatic polling MUST cease on terminal status, closure, unmount or scope change, and late responses MUST be discarded.
#### Scenario: 查询已知任务
- **WHEN** 获进度权限的用户输入非空 task_id
- **THEN** 前端 MUST 对路径参数编码后查询并展示实际数据
- **AND** 查询权限 MUST 不授予创建重算任务的能力。
#### Scenario: 终态及关闭
- **WHEN** 任务 completed/failed 或对话框关闭、组件卸载
- **THEN** 自动查询 MUST 停止,不得后台无限轮询或由旧结果覆盖新任务。
### Requirement: 轮询配置统计
The frontend SHALL provide a new config statistics page under polling management for GET `/api/admin/polling-stats/pre-reset` and GET `/api/admin/polling-stats/tiers`, gated by page and separate ordinary view permissions. It MUST preserve null versus zero, label approximate counts, highlight unmatched-card warnings and indicate the five-minute tiers cache without promising forced cache invalidation.
#### Scenario: 重置日前统计
- **WHEN** 用户查看有数据或 null 的 previous/upcoming 周期
- **THEN** 前端 MUST 展示运营商、重置时间、套餐卡数、窗口检查/未检查及接口给定的分钟桶
- **AND** null MUST 显示无周期数据,真实 0 MUST 保留,不将桶擅自转换成未定义的差分或精确比例。
#### Scenario: 分层统计
- **WHEN** 用户打开分层统计
- **THEN** 前端 MUST 展示 by_config、by_package_state、computed_at、total_cards 和两个未匹配告警计数
- **AND** config_id=0 MUST 显示未匹配,不假定该配置存在。
### Requirement: 界面一致性与配置交付
The frontend SHALL reuse shop-list/detail conventions, `formatDateTime`, carrier-name remote search and search expansion only for at least four fields. Handoff MUST list the actual new menu name, URL, parent, page codes and ordinary action codes, excluding superadmin-exclusive configuration and distinguishing local mock verification from live integration.
#### Scenario: 菜单权限配置
- **WHEN** 本次实现交付
- **THEN** MUST 提供轮询管理下统计页及现有配置页新增按钮的准确配置
- **AND** 既有 CRUD 权限 MUST 不因未声明迁移被移除,不创建新的一级菜单。

View File

@@ -0,0 +1,30 @@
## 1. 契约与权限
- [x] 1.1 用户确认提案并记录审批。
- [x] 1.2 为 7 个接口补充类型及服务,区分预览 overrides 与既有 CRUD 请求。
- [x] 1.3 新增普通功能权限常量,复用超级管理员身份门禁与账户名称搜索。
## 2. 页面接入
- [x] 2.1 在轮询配置中接入当前配置 GET 预览和草稿 POST 预览,包含多条覆盖、停用模拟及完整结果。
- [x] 2.2 校验 ICCID、优先级、字段长度、null/0/正数间隔语义和成对生效的重置日前窗口。
- [x] 2.3 接入超级管理员调序界面、顺序与 ID 校验、确认和防重复提交。
- [x] 2.4 接入超级管理员异步重算启动、普通任务进度查询、终态与生命周期清理。
- [x] 2.5 新增轮询配置统计页,对接 pre-reset / tiers,准确展示空值、真实零、告警与缓存时间。
- [x] 2.6 注册一个统计菜单路由,沿用店铺页面、时间格式、条件数决定展开及运营商名称搜索标准。
## 3. 验证与交付
- [x] 3.1 覆盖全部 7 个新增接口 URL、方法、Query / Body、task_id 编码和返回契约。
- [x] 3.2 覆盖草稿语义、预览不写数据、权限、确认、防重、进度终态/卸载和迟到响应测试。
- [x] 3.3 检查列表、预览、统计、空状态、失败重试及响应式布局。
- [x] 3.4 运行相关和全量回归、类型检查、生产构建、针对性 lint / 格式 / 编码检查。
- [x] 3.5 在 `docs/权限.md` 与最终回复交付普通菜单和按钮配置及真实验证范围。
## 验证记录(2026-10-26)
- 新增轮询配置测试 20/20,全量 Node 回归 174/174;类型检查、生产构建、针对性 ESLint/Stylelint、格式与 UTF-8 检查通过。
- 本地 mock 浏览器复核配置列表、当前配置预览、草稿控件、确认后重算任务与自动终态停止、两种统计以及普通账号进度入口。375px 统计/进度无页面横向溢出,1440px 预览和统计截图已复核,1024px 普通账号入口已检查。
- 补正原配置列表检查间隔列的无效 slots 渲染,并使用唯一列 prop;原保存字段不变。
- 所有模拟 API 在本地拦截,未进行真实后端联调、菜单数据库写入、Git 推送或生产部署。生产构建仍提示项目既有 API 循环依赖、其他页面常量绑定及大 chunk 警告。
- 菜单与普通按钮编码已写入 `docs/权限.md`;不输出仅超级管理员专属配置。

View File

@@ -0,0 +1,50 @@
## Context
退款审批提交由后端和企业微信协同完成。网络超时或异步任务异常时,本地不能仅凭旧字段判断提交结果:已有 `sp_no` 需要同步,结果未知需要先确认,明确失败才允许恢复原提交事件。恢复必须绑定当前最新审批尝试,避免重复创建审批实例或覆盖历史材料。
## Goals / Non-Goals
- Goals: 为可恢复的退款提供一个安全、可追踪的恢复入口;展示提交状态和最近恢复结果;在列表和详情保持一致。
- Goals: 将资格判断、数据范围和并发冲突交给后端,前端只消费后端返回的可恢复标记。
- Non-Goals: 不实现审批引擎、企业微信调用、自动重试调度或新的审批流程。
## Decisions
- Decision: 新增独立的 `recoverApproval` API,而不是复用历史 `triggerApproval`。
- Rationale: `trigger-approval` 面向没有审批状态的历史记录;恢复接口面向已有审批尝试的同步/结果确认/原事件恢复,两者的幂等语义和审计含义不同。
- Decision: 以 `approval_recoverable` 作为按钮展示条件,后端作为最终授权和状态校验方。
- Rationale: 前端无法可靠重建“结果未知”和“明确失败”等状态,且状态可能在页面打开后发生变化。
- Decision: 恢复接口只接收路径中的退款 ID,响应返回完整退款详情。
- Rationale: 防止客户端篡改审批实例、材料或单号;一次响应即可刷新列表/详情所需字段。
- Decision: 将 `submission_status`、失败摘要和最近恢复时间作为普通退款响应字段展示。
- Rationale: 列表需要快速筛选/判断,详情需要审计和排障;字段由后端脱敏并保持一致。
## State and Concurrency
1. 若最新尝试已有 `sp_no`,后端执行原审批单同步。
2. 若提交结果未知,后端先确认结果;确认成功或已存在时不得再次提交。
3. 若结果明确提交失败,后端恢复原提交事件;不得创建新的尝试或审批实例。
4. 若资格在请求期间失效,接口返回状态冲突;前端提示固定文案并刷新详情/列表。
5. 后端应保证重复请求幂等,前端按钮在请求期间置为 loading,避免重复点击。
## Risks / Trade-offs
- Risk: 列表数据在恢复完成前已过期。
- Mitigation: 成功和状态冲突都强制重新请求后端;不在前端乐观修改审批状态。
- Risk: 失败摘要包含凭证或个人信息。
- Mitigation: 仅展示后端提供的脱敏 `approval_failure_summary`,前端不拼接原始异常。
- Risk: 新入口与旧历史补发入口混淆。
- Mitigation: 使用“恢复审批”文案和独立 API,保留两种入口各自的资格条件与说明。
## Migration Plan
1. 扩展退款响应类型与 API service。
2. 在列表和详情接入恢复按钮、确认/加载/错误处理和刷新逻辑。
3. 增加 API、资格显示、冲突刷新和字段展示测试。
4. 与后端联调已有单号、未知结果、明确失败和不可恢复四类状态。
## Open Questions
- `submission_status` 的完整枚举值及名称由后端提供,前端是否需要筛选取决于最终列表需求。
- 状态冲突错误是否有稳定错误码;在未确定前以前端按错误消息或统一冲突码兼容处理。

View File

@@ -0,0 +1,37 @@
# Change: 增加退款原审批恢复
## Why
退款审批提交可能出现企业微信单号已生成但本地结果未知、原提交事件明确失败,或需要重新同步已有审批单的情况。当前退款页面只有历史记录的“补发审批”能力,无法安全地恢复同一审批尝试;运营人员也缺少提交状态、失败摘要和最近恢复时间,难以判断是否可以处理。
## What Changes
- 新增 `POST /api/admin/refunds/{id}/recover-approval`,无请求体,调用后恢复原审批提交事件或确认未知结果。
- 新增 `RefundService.recoverApproval(id)`,成功响应解析为更新后的退款详情。
- 扩展退款列表和详情模型,支持 `submission_status`、`submission_status_name`、`approval_recoverable`、`approval_failure_summary`、`approval_last_recovery_at`。
- 在退款列表和详情中,仅当后端返回 `approval_recoverable = true` 且当前账号具备退款管理权限及数据范围时显示“恢复审批”。
- 恢复成功后刷新当前列表/详情;遇到状态冲突时提示“当前退款审批状态不允许恢复”并重新加载后端状态。
- 恢复动作沿用退款管理权限和数据范围,不新增审批实例、审批尝试、审批材料、审批实例 ID 或企业微信单号输入,也不替代现有历史审批“补发”能力。
## Impact
- Affected specs:
- `refund-management`
- Affected code:
- `src/api/modules/refund.ts`
- `src/types/api/refund.ts`
- `src/views/finance/refund/index.vue`
- `src/views/finance/refund/detail.vue`
- API contract:
- `POST /api/admin/refunds/{id}/recover-approval`
- `GET /api/admin/refunds`
- `GET /api/admin/refunds/{id}`
- Dependencies:
- 后端返回 `approval_recoverable` 的最终资格判断,并在服务端保证幂等、并发状态校验和数据范围校验。
- 后端成功响应包含完整退款详情,失败响应遵循现有统一错误结构。
- Out of scope:
- 创建新的审批尝试或审批实例。
- 前端直接调用企业微信、传入审批实例 ID、审批材料或 `sp_no`。
- 修改退款金额、退款方式、审批结果或渠道退款流程。
- 批量恢复、自动轮询恢复或替代 `trigger-approval` 历史审批补发。

View File

@@ -0,0 +1,86 @@
## ADDED Requirements
### Requirement: Refund Approval Recovery API
The refund service SHALL expose `POST /api/admin/refunds/{id}/recover-approval` with no request body. The operation SHALL use the existing refund-management permission and data scope, and SHALL return the updated complete refund record on success.
#### Scenario: Recover an existing approval submission
- **GIVEN** a refund record is marked `approval_recoverable = true`
- **WHEN** the client posts to `/api/admin/refunds/{id}/recover-approval`
- **THEN** the request MUST contain only the refund ID path parameter and no body
- **AND** a successful response MUST contain the updated refund detail, including the latest submission and approval fields
#### Scenario: Reject unauthorized or out-of-scope recovery
- **GIVEN** the current account lacks refund-management permission or data scope for the refund
- **WHEN** the client calls the recovery endpoint
- **THEN** the service MUST reject the request using the existing authentication/authorization error contract
### Requirement: Recovery Preserves the Original Approval Attempt
The recovery operation SHALL synchronize an existing approval identified by `sp_no`, confirm an unknown submission result before retrying, or restore the original submission event after an explicit submission failure. It MUST NOT create a new approval attempt or approval instance.
#### Scenario: Existing WeCom approval number
- **GIVEN** the latest approval attempt already has an `sp_no`
- **WHEN** recovery is requested
- **THEN** the service MUST trigger synchronization of that original approval
- **AND** MUST preserve the existing approval attempt and instance
#### Scenario: Unknown submission result
- **GIVEN** the submission result is unknown
- **WHEN** recovery is requested
- **THEN** the service MUST confirm the submission result before any resubmission
- **AND** MUST NOT create a duplicate approval when the original submission is found
#### Scenario: Explicit submission failure
- **GIVEN** the original submission is explicitly known to have failed
- **WHEN** recovery is requested
- **THEN** the service MUST restore the original submission event
- **AND** MUST NOT create a new approval attempt or approval instance
### Requirement: Refund Approval Recovery Fields
Refund list and detail responses SHALL expose `submission_status`, `submission_status_name`, `approval_recoverable`, `approval_failure_summary`, and `approval_last_recovery_at`. The failure summary MUST be a redacted diagnostic value supplied by the backend.
#### Scenario: Display recovery metadata
- **GIVEN** a refund response contains recovery metadata
- **WHEN** the list or detail page renders the record
- **THEN** it MUST display the submission status name, redacted failure summary when present, and the latest recovery time
- **AND** it MUST use `approval_recoverable` from the response without deriving eligibility from stale local fields
### Requirement: Refund Approval Recovery Entry
The refund list and detail pages SHALL show a “恢复审批” action only when the backend returns `approval_recoverable = true` and the existing refund-management permission and data scope allow access.
#### Scenario: Show recovery action for an eligible record
- **GIVEN** `approval_recoverable` is `true`
- **AND** the current account can access the refund under existing permission and data scope
- **WHEN** the page renders the record
- **THEN** the page MUST show the “恢复审批” action
#### Scenario: Hide recovery action for an ineligible record
- **GIVEN** `approval_recoverable` is `false`, absent, or the account cannot access the refund
- **WHEN** the page renders the record
- **THEN** the page MUST NOT show the “恢复审批” action
#### Scenario: Recovery succeeds
- **GIVEN** the user confirms recovery for an eligible record
- **WHEN** the recovery endpoint succeeds
- **THEN** the page MUST show a success message and reload the list or detail from the backend
- **AND** the refreshed record MUST show the latest submission and approval state
#### Scenario: Recovery conflicts with a concurrent state change
- **GIVEN** the record becomes non-recoverable before the request is processed
- **WHEN** the endpoint returns a status conflict
- **THEN** the page MUST show “当前退款审批状态不允许恢复”
- **AND** MUST reload the current record instead of applying an optimistic state

View File

@@ -0,0 +1,21 @@
## 1. Contract And Types
- [x] 1.1 在 `Refund` 列表/详情类型中增加 `submission_status`、`submission_status_name`、`approval_recoverable`、`approval_failure_summary`、`approval_last_recovery_at`。
- [x] 1.2 在 `RefundService` 增加 `recoverApproval(id)`,调用无请求体的 `POST /api/admin/refunds/{id}/recover-approval` 并返回完整 `Refund`。
- [x] 1.3 补充 API 注释和统一错误响应处理,明确不传审批实例 ID、材料或企业微信单号。
## 2. Refund List And Detail
- [x] 2.1 列表展示提交状态名称、脱敏失败摘要和最近恢复时间(按页面现有字段展示约定接入)。
- [x] 2.2 仅在 `approval_recoverable === true` 且通过现有退款管理权限/数据范围校验时显示“恢复审批”操作。
- [x] 2.3 恢复操作增加确认和请求中 loading,成功后刷新列表并展示最新响应数据。
- [x] 2.4 详情页展示上述字段和“恢复审批”操作;成功后刷新详情。
- [x] 2.5 处理状态冲突:提示“当前退款审批状态不允许恢复”,并刷新当前数据;其他后端错误沿用统一错误提示。
## 3. Verification
- [x] 3.1 核对已有 `sp_no`、提交结果未知、明确提交失败和不可恢复记录的入口展示与刷新行为。
- [x] 3.2 核对无退款权限、越权数据和 `approval_recoverable = false` 时不显示按钮。
- [x] 3.3 核对重复点击被 loading 阻止,且请求体为空、不携带审批材料或实例 ID。
- [x] 3.4 运行相关类型检查、lint、编码检查和构建。
- [x] 3.5 运行 `openspec.cmd validate add-refund-approval-recovery --strict`。

View File

@@ -0,0 +1,33 @@
## Context
头像菜单位于 `src/components/core/layouts/art-header-bar/index.vue`,当前“个人中心”通过路由跳转,“锁定屏幕”通过事件打开。`AuthService.changePassword` 已封装 `PUT /api/auth/password`,但当前 TypeScript 参数 `ChangePasswordParams` 使用 `oldPassword`、`newPassword`、`confirmPassword`,与 OpenAPI 的 `old_password`、`new_password` 不一致。HTTP 层只序列化 JSON,不会将 camelCase 自动转换成 snake_case。
## Goals / Non-Goals
- Goals: 提供头像菜单入口和简单的自助修改密码流程;遵循给定 OpenAPI 请求契约;不增加权限编码或权限判断。
- Non-Goals: 修改后端接口、增加路由、改变锁屏行为、增加权限管理配置。
## Decisions
- Decision: 使用头像菜单中的对话框承载表单,不为此功能新增页面路由。入口依次位于个人中心、修改密码、锁定屏幕。
- Decision: 表单收集当前密码、新密码和确认密码;确认密码仅用于客户端一致性校验,提交时仅构造 `{ old_password, new_password }`。
- Decision: 将 API DTO 类型调整为精确表达 OpenAPI 的 snake_case 字段,避免依赖 HTTP 层不存在的字段转换。
- Decision: 所有已登录用户均可见并可操作该入口,不使用 RBAC、按钮权限或菜单权限配置进行隐藏/拦截;API 请求仍携带现有 Bearer Token。
- Decision: 接口成功时清空敏感表单数据、提示成功,再调用 `userStore.clearLocalState()` 清除旧 token 并跳转登录页;接口失败时展示错误反馈,不记录密码值。
## Risks / Trade-offs
- 当前类型与接口字段不一致,直接复用旧 camelCase 参数会发送错误字段;以 DTO 对齐及请求验证覆盖此风险。
- 密码策略细节未在给定 OpenAPI 中定义;本次不自行新增密码复杂度规则,沿用后端校验结果并反馈错误。
## Migration Plan
无需数据迁移或后端变更。前端发布后,已登录用户可从头像菜单使用入口;回滚时可移除菜单项及对话框实现。
## Open Questions
- None.
## Session Handling
After a successful password change, clear the current client authentication state with `userStore.clearLocalState()` and redirect to the login route. Do not attempt the logout API after changing the password because the old token may already be invalid.

View File

@@ -0,0 +1,21 @@
# Change: 添加自助修改密码功能
## Why
当前头像菜单提供个人中心和锁定屏幕入口,但用户无法从该处修改自己的登录密码。认证服务已提供 `PUT /api/auth/password`,需要补齐可发现的前端入口和修改流程。
## What Changes
- 在头像菜单的“个人中心”和“锁定屏幕”之间增加“修改密码”入口。
- 点击后打开修改密码表单,提交当前密码和新密码至 `PUT /api/auth/password`。
- 按 OpenAPI 使用 `old_password`、`new_password` 请求字段;确认密码(如表单提供)只在前端校验,不发送给接口。
- 修改密码入口面向所有已登录用户,不新增权限编码、路由权限或按钮权限。
- 修改成功后清理本地认证状态并跳转登录页,要求用户使用新密码重新登录。
- 为新增文案提供中英文国际化。
## Impact
- Affected specs: `admin-authentication`
- Affected code: `src/components/core/layouts/art-header-bar/index.vue`、`src/components/core/layouts/art-header-bar/ChangePasswordDialog.vue`、`src/components/core/layouts/art-header-bar/style.scss`、`src/api/modules/auth.ts`、`src/types/api/auth.ts`、`src/locales/langs/zh.json`、`src/locales/langs/en.json`
- API: 已有 `PUT /api/auth/password`;请求体按 OpenAPI 发送 `old_password` 和 `new_password`,使用当前登录 Bearer Token。
- Authorization: 不新增前端权限配置;接口仍按认证 API 的 Bearer 认证要求调用。

View File

@@ -0,0 +1,33 @@
## ADDED Requirements
### Requirement: Self-Service Password Change Entry
The authenticated admin interface SHALL provide a password-change entry in the avatar menu between “个人中心” and “锁定屏幕”. The entry SHALL be available to every authenticated user without a frontend route, button, or menu permission check.
#### Scenario: User opens password-change form from avatar menu
- **GIVEN** the user is authenticated in the admin interface
- **WHEN** the user opens the avatar menu
- **THEN** the menu shows “个人中心”, “修改密码”, and “锁定屏幕” in that order
- **AND** selecting “修改密码” opens the password-change form
- **AND** the entry is not hidden or disabled based on a permission code
### Requirement: Change Current User Password
The password-change form SHALL collect the current password and new password, and SHALL submit them through `PUT /api/auth/password` using the current Bearer token. The request body MUST contain exactly the API fields `old_password` and `new_password`; any confirmation value used for client-side validation MUST NOT be sent. Password values MUST NOT be written to application logs.
#### Scenario: Password change succeeds
- **GIVEN** the user has entered a current password and matching new-password values
- **WHEN** the user submits the form and the API returns success
- **THEN** the frontend sends `old_password` and `new_password` to `PUT /api/auth/password`
- **AND** the frontend displays success feedback and clears the password form values
- **AND** the frontend clears the local authentication state and redirects the user to the login page
- **AND** the user must authenticate again with the new password
#### Scenario: Password change is rejected
- **GIVEN** the user submits the password-change form
- **WHEN** the API rejects the request
- **THEN** the frontend displays error feedback and does not report success
- **AND** the frontend does not log any password value

View File

@@ -0,0 +1,13 @@
## 1. 头像菜单与修改密码表单
- [x] 1.1 在头像菜单“个人中心”和“锁定屏幕”之间添加“修改密码”入口,不设置权限判断。
- [x] 1.2 实现修改密码表单,收集当前密码、新密码及确认密码,并在前端校验必填项与两次新密码一致。
- [x] 1.3 调用认证 API;请求仅包含 `old_password` 和 `new_password`,成功后清空表单并提示结果,失败时显示错误反馈。
- [x] 1.4 添加中英文菜单、表单、校验及结果提示文案。
## 2. API 契约与验证
- [x] 2.1 对齐 `ChangePasswordParams` 与 `AuthService.changePassword` 的请求 DTO,确保网络请求字段为 OpenAPI 定义的 snake_case,且不发送确认密码。
- [x] 2.2 验证菜单顺序、表单校验、成功与失败反馈,以及入口不依赖任何权限编码。
- [x] 2.3 运行相关类型检查和构建,处理本次改动引入的问题。
- [x] 2.4 密码修改成功后清理本地认证状态并跳转登录页。

View File

@@ -0,0 +1,38 @@
## Context
本次变更同时涉及任务导入弹窗、配置管理表单、公共错误处理约定和三类资产展示面。已有解绑导入 API、`VoucherUpload` 组件及 H5 配置页面能力,不新增后端接口或新的上传基础设施。
## Goals / Non-Goals
- Goals:
- 让 CSV 解绑导入沿用已有批量导入的交互模式和共享上传能力。
- 让页面错误提示遵循“公共请求层统一提示、页面不重复提示”的约定。
- 让关联手机号在列表和详情的字段、空值、图标和展示格式一致。
- Non-Goals:
- 不改变解绑导入 API、权限模型、任务处理逻辑或后端手机号数据范围。
- 不删除或迁移历史 H5 运营弹窗配置。
- 不修改其他业务页面中与本次列表加载无关的错误提示。
## Decisions
- Decision: 复用 `VoucherUpload` 作为 CSV 解绑导入的文件入口;通过 `purpose` 和 CSV 校验参数表达业务约束,提交前只使用组件产出的对象存储 key。
- Decision: `asset_detail` 仅从新增/编辑的页面选择项隐藏,历史配置的 `PAGE_NAMES`/回显映射继续保留,避免历史数据无法查看或保存时被静默改写。
- Decision: 关联手机号直接消费 `associated_phones`,使用统一的“、”拼接和 `-` 空值占位,不在前端二次脱敏,以符合接口“按资产数据范围返回完整手机号”的契约。
- Decision: 资产详情图标沿用 `BasicInfoCard` 现有 `asset-label--*` iconfont 伪元素机制,新增关联手机号对应的 class/glyph,不引入新的图标库。
## Risks / Trade-offs
- 共享上传组件的默认文件数量、大小或校验提示可能与旧弹窗不同,需要在弹窗层明确传入参数并回归关闭/重选行为。
- 隐藏 `asset_detail` 后,已存在该值的编辑表单必须允许回显,否则会造成用户误以为配置被清空;实现时需区分“历史值回显”和“新选项列表”。
- 完整手机号展示属于敏感信息,必须保持现有权限和后端资产数据范围,不得通过前端扩大查询范围。
## Migration Plan
1. 先完成组件和页面改造并通过静态检查。
2. 在测试环境验证上传任务、历史弹窗配置回显和关联手机号字段兼容性。
3. 发布前确认公共请求层已覆盖列表接口错误提示;如未覆盖,先补齐公共层再移除页面提示。
## Open Questions
- 无。上传大小上限沿用 `VoucherUpload`/现有解绑导入接口约束,若后端另有上限以接口契约为准。

View File

@@ -0,0 +1,39 @@
# Change: 统一资产导入交互并补充关联手机号展示
## Why
当前 CSV 解绑导入使用独立的弹窗和原生上传实现,与批量导入 IoT 卡的导入体验不一致,也没有复用项目已有的上传组件。H5 运营弹窗配置仍把“资产详情”作为新增配置的可选页面,列表请求失败时还会重复弹出错误提示;核销申请状态文案、设备/IoT 卡列表及资产详情中的关联手机号展示也需要与后端返回契约和现有视觉规范保持一致。
## What Changes
- 将 CSV 解绑导入弹窗调整为与“批量导入 IoT 卡”一致的导入说明、模板入口、表单布局、提交状态和底部操作区。
- CSV 文件上传改用现有通用上传组件,限定单个 `.csv` 文件并沿用 `phone_unbind_import` 上传用途;上传中禁止重复提交,上传结果和校验错误在弹窗内可见。
- 在新增/编辑运营弹窗配置的 `PAGE_OPTIONS` 中隐藏“资产详情”选项;历史配置若已命中 `asset_detail` 仍可正常展示,不因隐藏选项而丢失或改写历史数据。
- 移除 H5 运营弹窗配置列表加载 `try/catch` 中的本地 `ElMessage.error(normalizeApiError(error).message || '获取运营弹窗配置列表失败')`,由公共请求层统一负责错误提示,页面保留必要的日志和加载状态收尾。
- 将核销申请的“已撤销或已关闭”统一改为“已关闭”,同步状态选项、映射和类型注释中的用户可见文案。
- 设备管理和 IoT 卡管理列表消费并展示接口返回的 `associated_phones`,多个手机号使用统一分隔符,无关联时显示稳定占位符;按后端资产数据范围展示完整手机号,不在前端脱敏或截断。
- 在资产信息基础信息区域的“关联手机号”标签前补充与其他字段一致的图标样式,并保持空数组的占位展示。
## Impact
- Affected specs:
- `phone-asset-association-management`
- `h5-popup-configuration-management`
- `employee-collection`
- `device-management`
- `iot-card-management`
- `asset-information`
- Affected code:
- `src/views/asset-management/phone-asset-association/index.vue`
- `src/components/business/VoucherUpload.vue`(仅在需要扩展 CSV 上传参数时调整)
- `src/views/settings/h5-popup-configuration/index.vue`
- `src/views/finance/employee-collection/employeeCollectionDisplay.ts`
- `src/views/asset-management/device-list/index.vue`
- `src/views/asset-management/iot-card-management/index.vue`
- `src/types/api/device.ts`、`src/types/api/card.ts`、相关列表列配置
- `src/views/asset-management/asset-information/components/BasicInfoCard.vue`
- Related changes:
- 衔接已有 `add-phone-asset-unbind-management` 的解绑导入 API 和权限约束。
- 衔接已有 `add-h5-popup-configuration-management` 的页面枚举、历史配置展示和权限约束。
- Breaking changes: 无后端 API 破坏性变更;新增配置页面选项对运营人员的可选范围有意收窄。

View File

@@ -0,0 +1,13 @@
## ADDED Requirements
### Requirement: 资产详情关联手机号标签图标
资产信息基础信息区域展示 `associated_phones` 时,关联手机号标签 MUST 使用与其他资产字段一致的图标前缀样式。
#### Scenario: 展示关联手机号字段
- **WHEN** 资产详情渲染关联手机号字段
- **THEN** “关联手机号”标签前 MUST 显示现有 iconfont 图标
- **AND** 图标样式 MUST 与基础信息区域其他带图标标签的颜色、间距和对齐方式一致
- **AND** 手机号内容 MUST 保持现有完整值拼接和空值占位规则

View File

@@ -0,0 +1,19 @@
## ADDED Requirements
### Requirement: 设备列表展示关联手机号
设备管理列表 MUST 消费接口返回的 `associated_phones` 当前关联手机号列表,并按后端资产数据范围展示完整手机号。
#### Scenario: 设备存在关联手机号
- **GIVEN** 设备列表项包含一个或多个 `associated_phones`
- **WHEN** 设备管理列表渲染
- **THEN** 页面 MUST 展示“关联手机号”列
- **AND** 多个手机号 MUST 使用统一分隔符连接,且 MUST 不在前端脱敏或截断
#### Scenario: 设备没有关联手机号
- **GIVEN** `associated_phones` 为空数组或缺失
- **WHEN** 设备管理列表渲染
- **THEN** “关联手机号”列 MUST 显示稳定的空值占位符

View File

@@ -0,0 +1,12 @@
## ADDED Requirements
### Requirement: 核销申请关闭状态文案
核销申请状态值为关闭/撤销兼容状态时,前端用户可见文案 MUST 统一显示为“已关闭”。
#### Scenario: 显示关闭状态
- **WHEN** 核销申请列表、筛选项或详情返回兼容的关闭状态值
- **THEN** 页面 MUST 显示“已关闭”
- **AND** 页面 MUST NOT 显示“已撤销或已关闭”

View File

@@ -0,0 +1,18 @@
## ADDED Requirements
### Requirement: 运营弹窗新增页面选项与列表错误提示
运营弹窗配置页面 MUST 在新增/编辑表单的 `PAGE_OPTIONS` 中隐藏“资产详情”页面,同时 MUST 由公共请求层统一处理列表接口异常,页面不得重复弹出同一错误提示。
#### Scenario: 新增配置不提供资产详情选项
- **WHEN** 用户打开新增或编辑运营弹窗配置表单
- **THEN** 页面 MUST NOT 在可选页面列表中展示“资产详情”
- **AND** 页面 MUST 继续保留已有配置中 `asset_detail` 的名称映射和历史值回显能力
#### Scenario: 列表请求失败
- **WHEN** 运营弹窗配置列表请求在网络层或接口层失败
- **THEN** 页面 MUST 不再调用 `ElMessage.error(normalizeApiError(error).message || '获取运营弹窗配置列表失败')`
- **AND** 公共请求层 MUST 负责用户可见的错误提示,页面 MUST 仅保留日志记录及 loading 状态收尾

View File

@@ -0,0 +1,19 @@
## ADDED Requirements
### Requirement: IoT 卡列表展示关联手机号
IoT 卡管理列表 MUST 消费接口返回的 `associated_phones` 当前关联手机号列表,并按后端资产数据范围展示完整手机号。
#### Scenario: IoT 卡存在关联手机号
- **GIVEN** IoT 卡列表项包含一个或多个 `associated_phones`
- **WHEN** IoT 卡管理列表渲染
- **THEN** 页面 MUST 展示“关联手机号”列
- **AND** 多个手机号 MUST 使用统一分隔符连接,且 MUST 不在前端脱敏或截断
#### Scenario: IoT 卡没有关联手机号
- **GIVEN** `associated_phones` 为空数组或缺失
- **WHEN** IoT 卡管理列表渲染
- **THEN** “关联手机号”列 MUST 显示稳定的空值占位符

View File

@@ -0,0 +1,19 @@
## ADDED Requirements
### Requirement: CSV 解绑导入弹窗复用批量导入交互
CSV 解绑导入入口 MUST 使用与批量导入 IoT 卡一致的导入说明、模板入口、表单确认和底部操作布局,并复用项目通用上传组件完成文件选择与上传。
#### Scenario: 打开解绑导入弹窗
- **WHEN** 具备权限的用户打开 CSV 解绑导入
- **THEN** 页面 MUST 展示导入说明、模板下载、解绑原因、二次确认和明确的创建任务操作
- **AND** 弹窗 MUST 提供与批量导入 IoT 卡一致的抽屉/弹窗层次和提交状态反馈
#### Scenario: 使用共享组件上传 CSV
- **WHEN** 用户选择解绑 CSV 文件
- **THEN** 页面 MUST 使用通用上传组件,并限制为单个 `.csv` 文件
- **AND** 上传 MUST 使用 `phone_unbind_import` 用途并产出后续任务接口所需的 `file_key`
- **AND** 文件上传中 MUST 禁止重复创建任务,上传失败 MUST 在弹窗内给出可理解的校验或错误反馈

View File

@@ -0,0 +1,27 @@
# Tasks: 统一资产导入交互并补充关联手机号展示
## 1. CSV 解绑导入
- [x] 1.1 对照批量导入 IoT 卡抽屉,重排 CSV 解绑导入说明、模板下载、原因/确认表单和底部操作区。
- [x] 1.2 将 CSV 文件选择替换为通用上传组件,配置单文件、`.csv`、`phone_unbind_import` 用途及文件类型/编码提示。
- [x] 1.3 接入上传中状态、移除/重选文件和提交前校验,确保创建解绑任务仍发送 `file_key`、`reason`、`confirmed`。
- [x] 1.4 验证上传失败、重复选择文件、取消关闭和任务创建成功后的清理行为。
## 2. H5 运营弹窗配置
- [x] 2.1 从新增/编辑表单的 `PAGE_OPTIONS` 隐藏 `asset_detail`,保留历史值的名称映射和只读回显能力。
- [x] 2.2 删除列表加载 `catch` 中重复的运营弹窗配置失败 `ElMessage.error`,保留日志与 loading 状态收尾。
- [x] 2.3 验证全局请求错误提示只出现一次,且成功响应中的业务错误仍按现有响应约定处理。
## 3. 状态文案与关联手机号
- [x] 3.1 将核销申请状态“已撤销或已关闭”改为“已关闭”,同步选项、映射、注释和相关页面筛选显示。
- [x] 3.2 确认设备与 IoT 卡列表类型保留 `associated_phones: string[]`,并在默认列/列管理配置中展示“关联手机号”。
- [x] 3.3 统一多手机号拼接和空数组占位符,确认不做前端脱敏、截断或超出后端数据范围的补查。
- [x] 3.4 为资产详情“关联手机号”标签补充现有 iconfont 图标,并检查卡资产、设备资产及空值场景。
## 4. Verification
- [x] 4.1 运行相关 TypeScript/Vue 检查、编码检查和变更页面 lint。
- [x] 4.2 手工验证 CSV 导入、运营弹窗配置、核销申请、设备列表、IoT 卡列表和资产详情的关键场景。
- [x] 4.3 使用 `openspec validate update-asset-import-popup-and-phone-display --strict` 校验提案格式。

View File

@@ -0,0 +1,21 @@
# Change: 对齐业务用户组成员增量管理接口
## Why
《产品迭代8月份/修改.md》已将业务用户组成员维护从“整体替换”调整为增量增加/迁移和按组移除。当前前端仍调用旧 PUT/全局 DELETE 接口,无法展示候选成员归属和操作提示。
## What Changes
- 对齐成员查询、成员候选、增量增加/迁移、按组移除接口。
- 成员管理弹窗展示当前成员及成员关系信息。
- 候选账号展示 `add`、`already_member`、`move` 操作提示。
- 停用组允许查询和移除,但新增/迁移由后端拒绝并提示。
- 用户组列表使用接口返回的实时成员数。
- 当前成员和候选账号展示当前所属组名称、编码、启用状态,不展示内部组 ID。
- 店铺列表和详情展示业务用户组编码、名称、启用状态和业务线,不展示内部组 ID。
## Impact
- Affected specs: `business-user-group-management`
- Affected code: business user group types/API/page
- Breaking API alignment: 移除前端对旧整体替换 PUT 与全局清空 DELETE 的调用。

View File

@@ -0,0 +1,44 @@
## ADDED Requirements
### Requirement: Business User Group Metadata Visibility
The frontend SHALL display business user group metadata returned by shop and membership APIs while omitting internal group IDs from these views.
#### Scenario: Show business group fields for shops
- **WHEN** an administrator views the shop list or shop details
- **THEN** the frontend displays the business group code, name, enabled state, and business line returned by the API
- **AND** the frontend does not display the business group ID
#### Scenario: Show current group fields for members and candidates
- **WHEN** an administrator views current members or candidate accounts in the group drawer
- **THEN** the frontend displays each account's current group code, name, and enabled state
- **AND** displays "未分组" when the account has no current group
- **AND** the frontend does not display the current group ID
#### Scenario: Show current member count
- **WHEN** an administrator views the business user group list
- **THEN** the frontend displays the `member_count` returned for each group
#### Scenario: Keep member selection and username visible
- **WHEN** an administrator scrolls horizontally in either member or candidate table
- **THEN** the selection checkbox and username columns remain fixed on the left
### Requirement: Incremental Business User Group Membership
The frontend SHALL use the member query, candidate query, incremental POST add/move, and scoped DELETE remove contracts from the modification document.
#### Scenario: Add or move members
- **WHEN** the user selects candidate accounts and confirms adding members
- **THEN** the frontend MUST POST the account IDs to `/api/admin/business-user-groups/{id}/members`
- **AND** MUST refresh current members and member counts
#### Scenario: Remove current members
- **WHEN** the user selects members currently belonging to the group and confirms removal
- **THEN** the frontend MUST DELETE `/api/admin/business-user-groups/{id}/members` with the account IDs
- **AND** MUST refresh current members

View File

@@ -0,0 +1,21 @@
## 1. Contract
- [ ] 1.1 更新成员、候选和成员数类型。
- [ ] 1.2 更新 `BusinessUserGroupService` 方法与 HTTP 方法/路径。
## 2. UI
- [ ] 2.1 展示当前成员列表和成员状态。
- [ ] 2.2 使用候选接口展示归属筛选和操作提示。
- [ ] 2.3 将“整体替换”改为增量添加/迁移,将移除限定为当前组成员。
## 3. Verification
- [ ] 3.1 运行类型检查、lint、编码检查、构建和 OpenSpec 校验。
## 4. Metadata Display
- [x] 4.1 在店铺列表和详情中展示业务用户组编码、名称、启用状态及业务线,不展示组 ID。
- [x] 4.2 在成员与候选账号表中展示当前组编码、名称及启用状态,不展示组 ID。
- [x] 4.3 在业务用户组列表中展示接口返回的成员数。
- [x] 4.4 成员和候选账号表横向滚动时固定勾选框与用户名列在左侧。

View File

@@ -0,0 +1,41 @@
## Context
项目已经有网关管理、轮询配置预览与统计、单卡历史、统一导出任务、预签名 CSV 上传、运营商账户编辑和系统配置。最新文档把这些基础能力扩展为按账户调度与停复机指令队列,必须做契约升级,而不是另建同名模块。
## Decisions
- 为新增调度/告警/轮询开关契约建立独立 API 和类型模块,已存在的接口在原服务扩展。分页、枚举、账户搜索、时间格式、权限门禁和异步生命周期优先复用已验证能力。
- 仅平台账号使用现有平台身份判断(user_type=1/2),仅超级管理员使用 isSuperAdmin。每个写操作同时在入口和处理函数检查,后端继续独立鉴权;禁止用按钮权限绕过身份。
- 详情遵循店铺详情的独立隐藏兄弟路由,普通页与详情按钮使用不同权限编码;需要数据库菜单配置的隐藏详情与导出任务菜单一并交付。单卡轮询状态通过已有资产信息弹窗/页签进入,卡 ID 来自授权资产详情,绑定卡不使用设备 ID 代替。
- 展示 effective 与 configured 参数的区别;configured 为空并非零值。执行上限与 consume_capacity 的关系在可判断时前置校验,无法获知的停复机进程容量不凭空假设,由服务端验证。
- 批量、告警关闭和导入共享接口影响说明及逐项结果展示。每次确认使用目标状态对应的 impact;获取失败不展示硬编码替代文案,更不绕过确认。跨筛选、视图、资产或账号变更时清理勾选和迟到结果。
- 系统配置修改沿用现有权限,增加 polling 模块、枚举选择与 JSON 合法性提示;不因前端接入自动切换 scheduler、rate_limit_mode 或 queue_enabled。
- CSV 文件保留标识符原始文本,客户端只做文档明确的格式/数量校验;后端仍负责逐行资产范围、风险状态和权限判定。
- 模式与范围明确:observe 不宣称已拦截,队列前 500 条的 pending 计数标注近似范围;近似 QPS/p95 保留单位和接口定义。未知枚举保留原值。
## Proposed route organization
在已有「轮询管理」`/polling-management` 下新增以下可见菜单,均非仅超级管理员专属页面;其中平台限定页面还需身份控制:
| 菜单 | URL | 账号边界 |
| --- | --- | --- |
| 运营商账户调度参数 | `/polling-management/carrier-params` | 查看按后端权限;维护仅超级管理员 |
| 请求检查场景 | `/polling-management/check-scenes` | 查看按后端权限;维护仅超级管理员 |
| 失败告警 | `/polling-management/failure-alerts` | 查看、处理按权限;批量关闭仅平台 |
| 账户队列监控 | `/polling-management/carrier-queues` | 按后端权限 |
| 停复机规则演练 | `/polling-management/stop-resume-dry-run` | 仅平台 |
| 不轮询清单 | `/polling-management/polling-pauses` | 仅平台 |
| 轮询开关导入 | `/polling-management/polling-status-imports` | 仅平台 |
隐藏详情拟用 `/polling-management/carrier-params/detail/:carrier_id`、`/polling-management/failure-alerts/detail/:id`、`/polling-management/polling-status-imports/detail/:id`。导出管理沿用现有 `/asset-management/export-task-management/` 下同场景命名规则,不新建一级菜单。最终以实际注册路由和权限交付为准。
## Risks / Trade-offs
- 本次跨多个既有业务页,必须保留已有 dirty worktree:使用定点修改和基于当前状态的回归,禁止重置前一轮实现。
- C 端不在本仓库,明确外部待办;不得越出命名项目搜索或修改其他工程。
- 文档 46/16 是后端相对旧版本的统计,并非当前代码差异;以接口覆盖矩阵逐项闭环。
- 分页读取过程中数据可能变化,不能凭前端缓存自动扩大写操作目标。导入、批量操作发生部分成功后明确不可回滚,不提供虚构的整批恢复。
## Validation
覆盖所有新增/变更接口方法与 Query/Body、true/false/null/0、clear_fields、warnings、保护期删除、账号类型 1/2/3/4、五百条上限、CSV 流程、部分成功、账户级告警、特殊视图、导出场景以及异步终态/关闭/卸载。运行类型、生产构建、全量 Node 回归和针对性 lint/编码检查;浏览器使用本地 mock,明确区别于真实后端联调。

View File

@@ -0,0 +1,43 @@
# Change: 按最新运营商账户限流契约补齐调度、告警与轮询开关管理
## Why
`docs/2026-10-26-轮询按运营商账户限流-前端接口变更说明.md` 是前两轮简化文档之后的完整变更契约,包含 46 个新增接口与 16 个改动接口。当前前端已实现其中的网关管理和轮询配置扩展基础,但仍缺少账户调度、失败告警、演练、单卡排查、批量开关及导入清单,并存在必须升级的持久化配置和已废弃保护期字段。
本次以该日期文档为准做增量接入,不重复建设前两轮已有页面,不把文档中所有“新增”理解为当前项目均未实现。
## What Changes
1. 轮询配置保存升级:创建/编辑/列表/详情支持 asset_status、package_state、pre_reset_window、pre_reset_carddata_interval;四项检查间隔支持 null 继承、0 禁用、正数间隔。编辑清空显式使用 clear_fields,保存成功展示 warnings;移除 protect_check_interval。更新草稿、匹配预览和拖拽优先级,保留既有预览、进度及统计权限。
2. 保护期退场:移除后台相关输入与展示,不再请求/保存保护期间隔;兼容后端仍返回但废弃的 device_protect_status,不影响其他资产功能。
3. 现有网关页面增量:错误分类支持 terminal 类别专属 auto_disable_polling 与测试结果;限流组展示真实 observe/enforce 模式;网关调用统计按已补全 DTO 展示账户/操作汇总、失败分类、豁免来源和趋势,不再保留“字段未定义”的临时限制。成功率按 0–1 显示,p95=-1 显示超出最大桶,不伪造精确耗时。
4. 轮询管理新增「运营商账户调度参数」「请求检查场景」「失败告警」「账户队列监控」「停复机规则演练」「不轮询清单」「轮询开关导入」。失败告警使用普通列表、账户汇总、停机被拒三个视图;单卡轮询状态放入现有单卡及设备绑定卡入口,不新建一级菜单。
5. 调度参数、场景修改严格仅超级管理员;规则演练、文件导入、不轮询清单、告警批量关闭及指定导出严格仅平台账号(user_type=1/2)。普通权限不得越过账号身份边界。
6. 卡/设备列表补齐 enable_polling 筛选、列和最多 500 项的批量开关。批量提交前取 impact 文案并确认、要求原因;展示成功/跳过/失败/无权限逐项结果,部分成功不回滚。设备级联语义保持后端决定;风险停机/已销户不提供强制开启。
7. 单资产开关改为展示接口 impact 确认文案并处理拒绝响应;订单或有效期变动后读取后端实际状态,不在前端模拟自动恢复。
8. 导入复用预签名上传:purpose=polling_status_import、CSV 表头与首列标识符、最多 50000 行、file_key 前缀校验,提交后列表与逐行结果按真实状态显示。长 ICCID 保持字符串,不转数字;上传失败不得创建任务,异步轮询要清理。
9. 导出复用统一任务,增加 polling_pause、polling_stop_refused_alert、stop_resume_rule_dry_run 场景、列表/详情/下载权限和必要菜单路由;卡/设备导出携带 enable_polling,客户端不重写旧历史文件。
10. 系统配置支持 polling 模块和文档中的 string/int/bool/json 配置,以服务器返回校验规则和错误为准;轮询并发页提示仅 legacy 调度生效,并链接账户参数。运营商实名管控 0→1 改为展示后端返回的实际影响说明,确认后带 realname_control_confirm 重提,不先擅自确认。
11. 延续 UI 标准:店铺列表和详情组件、统一 formatDateTime、运营商账户名称搜索、日期范围按临期资产样式、搜索条件 >=4 才显示展开。普通账号交付清单只列实际新增/变更菜单、URL、父菜单及 xxx:xxx 权限;保留旧配置、不列仅超级管理员专属项。
## Impact
- Affected specs: `carrier-polling-scheduler-integration`(新增综合接入规范)。当前无已归档 specs;前两轮 `add-gateway-rate-limit-management`、`add-polling-config-preview-and-statistics` 已完成,不更改其既有路由 URL 与权限编码。
- Affected code: pollingConfig / gateway / asset / card / device / carrier / storage / exportTask / systemConfig 的 API、类型与界面,相关路由、权限、上传组件、导出场景配置及测试。
- 不执行后端限流调度算法或数据迁移,不在真实环境触发批量操作、导入、调序、重算、配置修改、Git 推送或生产部署。测试写操作只使用本地 mock。
- 保留工作区已有未提交的轮询配置实现与其他用户修改。
## Scope boundaries and contract risks
- 文档要求的 C 端资产详情不在当前后台仓库:检索未发现独立 C 端工程。本次只落实本仓库可定位的后台部分,C 端保护期下线在交付中明确列为外部同步项,不声称已经修改。
- 本文 46 个新增接口中,前两轮已经建立 24 个方法,预计补齐剩余 22 个;实施前按路径与方法逐项核对,不以数量替代验收。附录已给出多数新 DTO,旧接口的完整 OpenAPI 未随本文提供时,不猜测未定义字段或清空规则。
- 网关统计内部字段已经补全,覆盖前一提案的“未知字段动态展示”临时约定。轮询配置新持久化字段已经明确,覆盖上一提案“新增字段仅用于预览”的暂定边界。旧说明与回归测试需同步升级。
- warnings 未定义固定结构时以实际字符串/对象安全展示,不假设固定业务键;clear_fields 仅使用文档支持的可空字段,不任意清除配置。
- 演练 page_size 特例最大 500,其余文档分页最大 100;演练结果筛选只影响明细不影响汇总,导出接口没有 result 参数时不擅自加入。假设实名管控 on/off 账户集合不得重叠。
- 停机被拒视图仅发送文档支持的五类筛选;切换视图清除忽略项及旧勾选。账户级告警 card_id=0 不得当作有效单卡 ID 请求历史或轮询状态。
## Delivery
先实现配置/保护期和公共契约,再接调度与排查,随后接批量/导入/导出,最后完成权限矩阵、mock 浏览器和回归验证。普通菜单与按钮配置写入 `docs/权限.md` 并在最终回复给出增量清单;现有菜单和权限不重复要求用户新增。
用户于 2026-10-26 批准执行,并明确仅修改后台前端;交付时另列 C 端同步事项,不修改 C 端代码。

View File

@@ -0,0 +1,98 @@
## ADDED Requirements
### Requirement: 最新轮询配置保存契约
The admin frontend SHALL align create/update/list/detail and preview with the latest configuration fields, including asset/package matching, pre-reset window, four tri-state intervals, clear_fields and save warnings. It MUST remove protect_check_interval and must not confuse zero with null or silently discard successful-save warnings. Existing routes and permissions MUST be preserved.
#### Scenario: 保存及清空
- **WHEN** 用户保存新增条件、禁用间隔或清空可空字段
- **THEN** 前端 MUST 使用明确的更新字段和 clear_fields,保留 0、false,展示实际 warnings
- **AND** 不得继续发送保护期间隔,预览必须与同一次编辑值一致。
### Requirement: 保护期移除与兼容
The frontend SHALL remove deprecated protection-period input and UI in this repository while tolerating device_protect_status in old responses. It MUST disclose that the independently deployed C-end code is outside this repository rather than claim to modify it.
#### Scenario: 旧响应兼容
- **WHEN** 后台详情仍返回固定 none 的保护期字段
- **THEN** 页面 MUST 不显示保护期,不因废弃字段缺失影响资产查询或其他功能。
### Requirement: 账户调度、场景与状态排查
The frontend SHALL provide carrier scheduling parameter list/detail, request-check scenes, carrier queue monitoring and single-card polling state with the documented effective/configured values, queue states, confirmations and stop/resume commands. Superadmin-only writes MUST be guarded both in UI and handlers. Null defaults and real zeros MUST remain distinct.
#### Scenario: 调度参数维护
- **WHEN** 超级管理员修改参数或恢复默认
- **THEN** 前端 MUST 校验可确定的容量、比例和递增延迟约束,提交对应接口并展示服务端拒绝原因
- **AND** 普通按钮权限 MUST 不能启用专属写操作。
#### Scenario: 单卡状态排查
- **WHEN** 获授权用户从单卡或设备绑定卡查看状态
- **THEN** 前端 MUST 使用真实 card_id 请求 polling-state,展示各检查类型及 stop_resume_command
- **AND** 账户级告警 card_id=0 MUST 不得作为有效卡身份进入该入口。
### Requirement: 失败告警与停机被拒视图
The frontend SHALL provide ordinary, carrier-summary and stop-refused alert views, details, handled status and platform-only close-polling actions. Only unresolved alerts may be marked handled. The special view MUST hide and omit check_type/error_category/alert_level. Bulk results MUST distinguish success, skipped, failed and unauthorized/nonexistent without suggesting rollback.
#### Scenario: 切换特殊视图
- **WHEN** 用户切换到停机被拒
- **THEN** 请求 MUST 只带该视图支持的筛选,清除旧选择,展示额外设备/停机/套餐/轮询字段
- **AND** 导出 MUST 使用独立场景与对应权限。
#### Scenario: 批量关闭
- **WHEN** 有权限的平台账号确认关闭告警对应卡的轮询
- **THEN** 前端 MUST 提交合法 alert_ids 和原因,逐项展示结果并刷新
- **AND** 不能把账户级告警当设备级操作,不能自动重试整批已部分成功的请求。
### Requirement: 平台规则演练与实名确认
The frontend SHALL provide platform-only dry-run summary, paginated details, hypothetical carrier controls and export without executing gateway actions. Hypothetical on/off carrier sets MUST not overlap. Real carrier control changes from off to on MUST display the backend impact message and only resubmit with realname_control_confirm after explicit confirmation.
#### Scenario: 只读演练
- **WHEN** 用户运行演练或按结果筛选明细
- **THEN** 前端 MUST 仅请求 dry-run,汇总保留后端定义的范围,不调用真实停复机或修改管控接口
- **AND** 明细 result 筛选不得被描述为已改变汇总。
### Requirement: 轮询开关、清单与 CSV 导入
The frontend SHALL support card/device polling filters, batch toggles, platform pause-history and CSV import workflows. It MUST load impact descriptions from the API before confirmation, require reasons, enforce unique 1–500 asset IDs, preserve false filters, maintain string identifiers and show all item outcomes. Enterprise accounts MUST not invoke batch toggles. Upload purpose and returned key prefix MUST match the documented polling-status-import contract; file limits and async cleanup MUST be enforced.
#### Scenario: 确认并批量开关
- **WHEN** 有权限账号选择资产开启或关闭
- **THEN** 前端 MUST 展示对应 impact 后确认、提交、展示部分成功结果
- **AND** 风险停机或已销户卡不得获得强制开启选项,403 必须回滚前端开关并保留原状态。
#### Scenario: 导入任务
- **WHEN** 平台账号上传带表头的合法 CSV 并确认
- **THEN** 前端 MUST 先获取预签名、上传成功后再提交任务,保留 ICCID 原文,展示任务与逐行错误
- **AND** 上传失败不得创建任务,终态、关闭和卸载 MUST 停止自动查询。
### Requirement: 系统模式与监控指标
The frontend SHALL add the polling system-config module, support documented JSON editing, display actual rate-limit/scheduler mode, and explain legacy-only concurrency behavior. Gateway monitoring SHALL use the now-defined operation DTOs, show success rates in the correct scale, identify approximate p95/queue-sample limits and not invent missing metrics.
#### Scenario: 观察模式
- **WHEN** 接口返回 observe
- **THEN** 页面 MUST 说明只统计不拦截,区分 would_limit 与真正 rate_limited
- **AND** 不得因前端接入自动修改生产调度或限流开关。
### Requirement: 导出、路由与权限交付
The frontend SHALL integrate the three new export scenes and preserve enable_polling filters for existing card/device exports. New pages, hidden details and export-task routes MUST follow existing menu conventions. Final handoff MUST list actual incremental menu names, URLs, parents and ordinary xxx:xxx button codes, excluding superadmin-exclusive configuration and preserving previous menu codes.
#### Scenario: 配置交付
- **WHEN** 实现完成
- **THEN** 前端 MUST 同步 docs/权限.md 和最终回复中的增量菜单与按钮清单
- **AND** MUST 区分平台身份限制、普通按钮权限、真实后端验证与本地 mock,以及本仓库外的 C 端同步事项。

View File

@@ -0,0 +1,38 @@
## 1. 契约与基线
- [x] 1.1 用户批准提案,记录当前 dirty worktree 和前两轮回归基线。
- [x] 1.2 建立文档接口到现有/新增方法、页面、权限及测试的覆盖矩阵,核对 46 新增与 16 改动的实际差异。
- [x] 1.3 新增账户调度、场景、告警、队列、单卡状态、批量开关、导入/清单、演练及 impact 类型和服务。
## 2. 既有页面升级
- [x] 2.1 升级轮询配置持久化 DTO、表单、列表、clear_fields、warnings、三态间隔、保存前预览和优先级拖拽。
- [x] 2.2 清除本仓库保护期输入/展示与请求字段,保留后端废弃响应兼容;记录外部 C 端同步项。
- [x] 2.3 增加 terminal auto_disable_polling,升级错误分类列表/表单/测试。
- [x] 2.4 依完整 DTO 改造网关汇总、趋势和 observe/enforce 模式展示。
- [x] 2.5 增加 polling 系统模块与 JSON 编辑校验、旧并发页说明;运营商实名管控改用服务端影响说明二次确认。
## 3. 调度、排查与演练
- [x] 3.1 完成账户调度参数列表/详情/超级管理员维护和容量边界。
- [x] 3.2 完成请求检查场景列表及超级管理员维护、严格递增确认延迟校验。
- [x] 3.3 完成账户队列和停复机指令监控、初始化状态、真实指标及异步生命周期。
- [x] 3.4 在单卡及设备绑定卡接入轮询状态与停复机命令,校验真实卡 ID 和账号权限。
- [x] 3.5 完成失败告警普通/汇总/停机被拒视图、详情、处理、记录联动、平台批量关闭。
- [x] 3.6 完成平台规则演练、假设管控条件、汇总/分页明细、只读保障与导出。
## 4. 开关、清单与文件任务
- [x] 4.1 卡/设备列表新增轮询筛选和列,导出保留 false 筛选,接入批量开关原因、影响确认和逐项结果。
- [x] 4.2 单资产开关使用 impact 文案,处理风险/已销户拒绝,刷新后端实际状态。
- [x] 4.3 平台不轮询清单支持全部筛选、历史/系统操作者、批量开启及导出。
- [x] 4.4 平台 CSV 导入支持预签名、purpose、file_key、行数校验、创建和任务列表/逐行详情。
- [x] 4.5 接入三个导出场景及任务列表、详情、下载权限,维持历史文件兼容。
## 5. 验证与交付
- [x] 5.1 注册新可见/隐藏路由和权限,保留前两轮 URL、时间/账户搜索/展开标准。
- [x] 5.2 完成接口覆盖矩阵测试、权限与部分成功/视图切换/上传/轮询清理回归。
- [x] 5.3 验证类型、构建、全量测试、lint、格式、编码和本地 mock 浏览器交互/响应式。
- [x] 5.4 同步旧文档和 `docs/权限.md`,交付新增菜单名称/URL/父菜单、普通按钮编码;排除仅超级管理员专属项。
- [x] 5.5 明确真实联调范围、尚缺后端契约和外部 C 端同步项,不将 mock 结果当作线上验证。

View File

@@ -0,0 +1,9 @@
## Context
核销申请的审批提交状态与业务状态独立维护。恢复操作只能复用最新审批尝试和原审批实例,不能创建新的申请或审批尝试。
## Decisions
- 资格以响应中的 `recoverable` 为准,前端不根据状态字段自行推导。
- 列表提供快速入口,详情提供主要操作入口;两处共用同一恢复权限编码。
- 恢复接口只传申请 ID,结果由后端返回并触发重新加载。

View File

@@ -0,0 +1,25 @@
# Change: 补齐核销申请恢复审批
## Why
《产品迭代8月份/修改.md》新增核销申请恢复原审批接口和恢复资格字段。当前前端类型、列表和详情尚未提供恢复入口,提交失败或结果未知的核销申请无法由运营人员处理。
## What Changes
- 扩展核销申请响应类型,支持 `recoverable`、提交状态、失败摘要和最近恢复时间。
- 新增 `EmployeeCollectionService.recoverApplicationApproval(id)`。
- 核销申请列表和详情在 `recoverable = true` 且具备权限时显示“恢复审批”。
- 恢复成功或冲突后刷新详情/列表,并展示后端错误消息。
- 新增权限 `employee_collection:application_recover_approval` 并写入权限文档。
## Impact
- Affected specs: `employee-collection`
- Affected code:
- `src/types/api/employeeCollection.ts`
- `src/api/modules/employeeCollection.ts`
- `src/config/constants/augustIteration.ts`
- `src/views/finance/employee-collection/applications/index.vue`
- `src/views/finance/employee-collection/applications/detail.vue`
- `docs/权限.md`
- Out of scope: 后端接口、数据库和企业微信审批引擎实现。

View File

@@ -0,0 +1,12 @@
## ADDED Requirements
### Requirement: Recover Employee Collection Approval
The frontend SHALL expose recovery for an employee collection application only when the backend returns `recoverable = true` and the user has the recovery permission.
#### Scenario: Recover approval from application detail
- **GIVEN** a核销申请返回 `recoverable = true`
- **WHEN** the user confirms “恢复审批”
- **THEN** the frontend MUST call `POST /api/admin/employee-collection-applications/{id}/recover-approval`
- **AND** MUST reload the application data after success or conflict

View File

@@ -0,0 +1,12 @@
## 1. Implementation
- [x] 1.1 扩展核销申请类型与恢复接口响应。
- [x] 1.2 增加恢复审批 API service 和唯一权限编码。
- [x] 1.3 列表增加提交状态字段和恢复审批操作。
- [x] 1.4 详情增加提交状态字段和恢复审批操作。
- [x] 1.5 更新 `docs/权限.md`。
## 2. Verification
- [x] 2.1 运行类型检查、lint、编码检查和构建。
- [x] 2.2 运行 OpenSpec 严格校验。

View File

@@ -6,7 +6,7 @@
#### Scenario: 任务列表展示扩展字段
- **GIVEN** 用户进入业务负责人导入任务列表
- **GIVEN** 用户进入批量换绑业务员任务列表
- **WHEN** 列表加载完成
- **THEN** 前端 MUST 展示任务编号、文件名、创建人、开始/完成时间与状态中文名
- **AND** 原有状态/总数/成功/失败/创建时间展示 MUST 保留

View File

@@ -0,0 +1,125 @@
# 十月第 1 批后台适配设计
## Context
本仓库为 Vue 3/TypeScript 后台,HTTP 服务使用 `BaseService` 与 Axios,页面已有业务权限、状态映射、详情组件、异步导入导出任务。原范围排除 C 端;2026-10-14 用户追加代理扫码注册页及同一注册接口的密码校验,其余 C 端接口和页面仍排除。后台本人改密虽然使用 `/api/auth/password`,仍属于本次后台适配。
本设计依据十月第 1 批说明、用户最新确认和当前代码。用户确认不提供最新 OpenAPI;2026-10-14 修正为新密码允许特殊符号,恢复四类至少三类。实施已获批准,结果详见实施记录,没有调用真实后台写接口。
### 代码证据与修改路径
| 依据/代码证据 | 当前差异 | 修改路径 |
| --- | --- | --- |
| M3;`src/types/api/order.ts`、`src/api/modules/order.ts` | 详情与列表共用 `Order`,缺三项支付信息与支付记录 | `Order` 补公共字段,另建 `OrderDetail` 与支付记录类型,详情服务改用详情类型 |
| M8;`employeeCollectionDisplay.ts`、核销申请列表/详情 | 状态仅 0~3,可重提仅状态 2;提交状态只读名称 | 补终态 4、状态值映射与恢复/重提判断,覆盖账单关联申请 |
| M14;退款/充值/提现类型与状态映射 | 缺退款 7、充值 7、提现 5;旧重提及补发条件不认识终态 | 各业务独立扩展类型、筛选、标签和可执行操作 |
| M14;后台代理注册查询类型/详情 | 筛选仅 0~2,恢复操作仅看 `recoverable` | 补状态 3,并在业务终态下优先隐藏恢复 |
| M1;账号、客户账号、店铺、企业表单及本人改密弹窗 | 仍使用 8~32 或 6~20;旧密码也有长度规则 | 新密码使用专用校验,旧密码只保留必要输入校验 |
| M1;`AccountService.updateAccountPassword` | 独立改密发送 `{ password }`,说明要求 `{ new_password }` | 按第 1 批说明修正独立改密请求,不误改其他接口字段 |
| M12;换货创建/确认完成、`apiError.ts` | 无 1202 定制反馈;错误归一化不暴露业务 data,换货 catch 可能输出错误对象 | 在换货操作定向提取 code/msg/message/data.phone,只在提示中展示号码,不记录完整错误对象 |
| M16;预警规则与记录类型/页面 | 规则依赖已删除的 `real_data_mb`;记录未定义三项 MB 字段 | 只移除规则响应引用,补记录快照并明确 MB 单位 |
| M2;业务员导入页 | 仍写「业务员登录账号」且未注明只填手机号 | 同步说明及已有前端模板,保留逐行失败明细 |
| M23;设备导入任务页 | IMEI 被列为可选,已支持 `failed_items` | 改说明,复用失败明细,不改 Excel 模板结构 |
## Goals / Non-goals
- Goals:让后台显示、筛选、请求字段和可执行操作符合本批次说明;保留既有权限、表单内容、财务快照和导入导出流程。
- Non-goals:除代理扫码注册密码规则外的 C 端适配、后台接口实现、新审批机制、新页面架构、自动解绑手机号、前端重算预警或余额、替换设备导入模板、引入测试框架。
## Decisions
### 1. 订单详情类型与支付状态隔离
公共 `Order` 接收三项字符串字段,列表与创建响应仍使用公共类型;详情增加独立 `payments` 数组。支付记录状态 0~3 与订单 `PaymentStatus` 的 1~4 含义不同,使用独立枚举/映射,不能复用。
支付记录使用后端顺序,不自行筛掉失败或待支付记录;金额用已有分转元格式化,`paid_at`、`expire_at` 空值显示 `-`。渠道码映射 `wechat` 为微信直连 v3、`wechat_v2` 为微信直连 v2、`fuiou` 为富友;支付方式微信/支付宝与技术渠道分开展示,未知非空渠道保留原值。公共字段为空串显示 `-`,不能据此虚构支付信息。
### 2. 业务终态优先于恢复标志
六个业务各自定义终态,禁止跨业务共用数值。恢复入口使用「不是本业务审批提交失败终态 + 后端允许恢复 + 原权限允许」共同判断;即使陈旧响应仍返回 `recoverable=true`,终态也不得显示恢复按钮。
「提交结果未知」不能只凭提交状态转换成业务失败,保留原后端恢复资格判断,不扩大恢复权限。终态下隐藏恢复/补发和不适用的审批操作,查看详情、凭证等只读操作保留。
重新发起复用既有表单和文档规定的接口:核销/退款/提现使用原业务重提接口,线下充值创建新单,提现资料提交新版本。代理注册仅提示申请人重新扫码,后台不调用 `/api/c/v1`、不补建后台代注册接口。涉及预占/冻结金额时重新加载账单或佣金概览,前端不乐观加减财务数据。
核销审批提交状态使用 `approval_submission_status` 的 0 待提交、1 提交中、2 已提交、3 提交失败、4 结果未知。名称字段存在时可使用后端名称,但字段为空时需按真实数值回退,0 不能因 falsy 判断显示成缺失。
### 3. 新密码校验专用化
使用新登录密码专用工具,避免影响通用校验与其他密码。按最新修正,长度 8~12,允许英文字母、数字及所有可打印半角 ASCII 符号,四类至少三类;空白、中文、emoji、控制字符和非 ASCII 字符拒绝。不静默 trim。
字符范围为 ASCII `0x21~0x7E`,按大写、小写、数字和标点四类计数,至少三类。`Admin@12345`、`ABC1234!`、`abc1234!`、`Abcdefg!` 均有效;`abcd1234`、`ABCDEF!!` 仅两类无效。
顶栏 `z-index:100`、侧栏 `z-index:101` 导致嵌在顶栏内的改密遮罩被侧栏压住。仅给改密弹窗加 `append-to-body`,不全局提高顶栏层级或修改所有弹窗;由 Element Plus 管理完整遮罩、焦点和关闭行为。
新密码和确认密码统一长度限制、规则说明与一致性校验;本人改密 `old_password` 不设新规则的 `maxlength` 或类别限制,旧登录表单不收紧。账号编辑目前没有密码输入则不新增;若既有调用传递可选 `password`,仅非空新值需要校验,未修改密码时不发送空串。
后台七个契约:
| 场景 | 接口 | 新密码字段 |
| --- | --- | --- |
| 本人修改 | `PUT /api/auth/password` | `new_password` |
| 创建账号(含店铺/企业下的客户账号) | `POST /api/admin/accounts` | `password` |
| 修改账号 | `PUT /api/admin/accounts/{id}` | 可选 `password` |
| 独立修改账号密码 | `PUT /api/admin/accounts/{id}/password` | `new_password` |
| 创建店铺初始账号 | `POST /api/admin/shops` | `init_password` |
| 创建企业 | `POST /api/admin/enterprises` | `password` |
| 修改企业密码 | `PUT /api/admin/enterprises/{id}/password` | `password` |
用户明确追加的公开代理注册使用原 `POST /api/c/v1/agent-distribution-registrations` 和 `password` 字段。表单复用 `createNewLoginPasswordRule()`,注册服务发送前复用 `getNewLoginPasswordError()`;保留其他入参和 `withToken: false`。页面将输入上限改为 12,完整规则独立显示在输入框下,并关联 `aria-describedby`,避免移动端 placeholder 截断规则。强度反馈仅按共享校验判定合格/未合格,空格和中文不能被计作有效特殊符号;长错误文案参与正常布局,不覆盖下一个表单项。
用户进一步追加注册失败反馈:仅 `registerAgent` 请求设 `errorMessageMode: 'none'`,页面处理非零业务响应与 HTTP 异常。1050/1001 不暴露企业微信模板配置细节,统一「注册失败, 请联系管理员」,其余错误保留具体业务原因或正常网络降级;不记录密码或完整错误对象。提交进行中阻止再次提交,失败保留表单。公共 HTTP、短信与其他服务的错误提示保持原状。
公共表头 Sortable 报错作为既有列设置功能的生命周期修复:改用 `useDraggable(..., { immediate: false })` 和真实 `HTMLElement` ref,仅在列设置 Popover 已打开且进入后,目标仍连接文档时启动;关闭、卸载及 KeepAlive 停用销毁实例,晚到回调不得重新启动。列排序仍通过原 `columns` model 写回,勾选状态和其他表头功能不变。
错误消息兼容项目既有 `msg` 与说明中的 `message`,优先展示后端提供的可读字段级原因;不改变 401 等既有统一处理,不重复弹错、不输出密码值。
### 4. 换货 1202 定向错误处理
创建换货和确认完成同时覆盖 HTTP 200 的非零业务码与 Axios HTTP 错误响应,不假定只有一种承载形式。在受影响的两个服务调用范围关闭重复默认提示,局部共享处理器处理 1202,其余错误仍按既有统一错误分类/文案展示。
1202 弹窗原样使用业务 `msg`,不拼接号码或固定替换文案。只有响应明确带有效字符串 `data.phone` 时才允许带参跳转;`data=null` 的已换货等拒绝仅显示后端文案和「知道了」。只以文本渲染,不拼成 HTML。
手机号冲突且具备原关联页面查看权限时提供跳转;无权限或新资产标识缺失时仅提示,不扩大权限。禁止自动解绑。完整号码不额外写日志或本地存储;用户主动跳转的 query 参数是已明确授权的例外。
创建失败保留资产/原因等字段;完成失败重新加载换货单,保持后端「已发货待确认」事实,不乐观标记完成。解除后由用户再次提交。取消只关闭提示,不当作解绑或换货成功。
用户追加快捷定位:创建换货冻结当前新资产上下文,确认完成使用原单新资产标识;手机号只能取当前错误响应 `data.phone`,不得根据历史数组推断其他 1202 是手机号冲突。主动跳转通过 `asset_identifier` 和 `phone` query 传递目标。关联页按 1 页/20 条加载,仅选中精确匹配有效行,继续原原因和二次确认。
通过 ArtTable 透传清空/勾选方法,数据更新后 nextTick 完成实际选择。缓存重入和路由参数变更重置查询,请求序号防止过期响应覆盖;手工筛选/翻页、解绑后刷新清除旧选择。批量结果保持后端布尔契约,仅展示中文「解绑成功/解绑失败」。原查看与批量解绑权限不变。
### 5. 预警只展示快照,不重算阈值
删除 `PackageTrafficAlertRuleItem.real_data_mb` 与规则行/详情/列设置依赖。来自 `/api/admin/packages` 的套餐选项 `real_data_mb` 保留,套餐选择与规则参数校验不变。
记录列表/详情接收后端 `threshold_mb`、`used_mb`、`limit_mb`,用 MB 显示两位小数;0 显示 `0.00`,缺失/null 显示 `-`。标签分别为阈值流量、已用流量(含加油包)、总流量(含加油包)。不使用当前套餐额度重新计算历史 `threshold_mb`,不把新字段作为新的请求入参或筛选项。
### 6. 导入说明与后端结果保持一致
CSV 只同步新表头和手机号说明,不为旧表头做客户端转换、不将用户名转为手机号。发现内置模板时同步,否则仅改当前说明,任务明细保留原后端原因。
设备导入保持原下载文件与列序,将说明中的 IMEI 移到必填列;只把空值规则交给后端逐行处理,不为单行缺失拦截整个文件,不添加格式或去重限制。
## Risks / Trade-offs
- 无最新 OpenAPI:按用户确认,以第 1 批说明实施,不要求补文件;联调发现真实接口与说明不符时先反馈,不自行猜测或声称已通过联调。
- 密码口径以最新修正为准:允许半角特殊符号并按四类至少三类校验;如后端字符集合仍有不同约束,联调时反馈用户。
- 恢复旧规范与新业务终态冲突:文档注明差异,实施时优先按本批次终态处理,结果未知继续守原恢复规则。
- 改错密码/流量范围:专用新密码工具和独立规则/套餐类型限制修改范围,回归旧密码、操作密码、WiFi 密码、套餐额度。
- 换货错误提示重复或泄漏号码:两个请求定向接管提示,共享处理器保留其他错误行为,删除受影响分支的完整错误输出。
- 财务状态不同步:重提和失败后重新拉取后端数据,不修改本地冻结金额来模拟后端效果。
- 仓库未配置可直接运行的单测脚本:先检查现有测试方式,以针对性逻辑检查、类型检查、编码检查和人工联调为验收,不自动引入新框架。
## Migration plan
提案获批后,依据第 1 批说明和用户最新确认,依任务清单按公共类型/规则、各页面、联调顺序实施;前端与对应测试后端一起验收。无数据库迁移、权限迁移、历史导出重生成或自动数据修复。
回退只回退本次业务代码,不触及原有提案和用户改动;后端若仍保留新校验及终态,旧前端将重新出现展示与提交问题,因此上线/回退需确认前后端契约匹配。
## 已确认事项
1. 没有最新 `admin-openapi.yaml`,不要求提供,以第 1 批说明实施。
2. 新密码 8~12 位,大写、小写、数字、半角特殊符号至少三类,禁止空白和中文。
3. 用户明确追加的代理扫码注册密码规则纳入;其他 `/api/c/v1` 和 C 端页面排除。后台代理注册失败仍仅展示重新扫码申请指引,不代发 C 端申请。
当前没有待确认的需求问题。用户已批准实施,后台代码已适配;真实后端联调项继续在任务清单保留未完成状态。

View File

@@ -0,0 +1,123 @@
# 后台实施记录
后台代码已按第 1 批对接说明及用户确认适配。2026-10-14 用户明确追加代理扫码注册页及原注册接口的密码校验,其他 C 端仍不修改。真实后端联调尚未完成,未部署、提交或调用真实写接口。
## 结果与证据
| 证据 | 已确认结果 | 实现路径 |
| --- | --- | --- |
| 规则测试与本地订单详情 | 支付摘要、独立支付单状态、失败记录、空时间与金额展示正常 | `src/types/api/order.ts`、订单列表/详情、`orderPayment.ts` |
| 规则测试与模拟核销/代理注册详情 | 终态优先于陈旧恢复标志,核销可重提、代理注册提示重新扫码 | 核销展示工具、退款常量、注册状态辅助函数及相应页面 |
| 规则测试与模拟改密弹窗 | 按 2026-10-14 修正允许特殊符号且四类至少三类;旧密码不受新长度限制,错误说明不重叠 | `loginPassword.ts`、后台密码表单、本人改密弹窗与双语文案 |
| 规则测试与原模拟换货确认完成 | 1202 按最新规则原样展示 `msg`,有效响应手机号才提供跳转;原待确认状态保持,不自动解绑 | `exchangeError.ts`、换货页面与服务 |
| 数值测试与模拟预警规则/详情 | 规则额度移除,MB 快照两位小数,零和缺失区分,套餐商品额度保留 | 预警类型、规则页、记录列表/详情及 `trafficAlert.ts` |
| 模板和源码回归检查 | 新四列表头与手机号说明,设备 IMEI 必填说明、原 Excel 模板和行级失败反馈保持 | `shopBusinessOwnerImport.ts`、导入页面 |
ui-ux-pro-max 用于检查标签含义、错误反馈和长文案换行;保留现有 Element Plus 样式,未引入新 UI 依赖或改版。docs-generator 用于区分实施结果、可复现检查和未完成的真实联调,任务清单没有将后端验收提前标为完成。
## 复现本地验证
在项目根目录执行:
```powershell
# 63 项规则及已有回归测试;加载入口兼容 pnpm 的 esbuild 隔离布局。
node --import ./scripts/tests/register-esbuild.mjs --test --test-reporter=spec scripts/tests/*.test.mjs
npx --no-install vue-tsc --noEmit
# 生产构建输出到临时目录,关闭自动声明生成并校验原声明内容未被覆盖。
node scripts/tests/verifyBuild.mjs
openspec validate update-october-batch-one-admin-integration --strict --no-interactive
```
受影响文件 ESLint、Prettier 和 UTF-8 检查通过。生产构建存在原有搜索表单常量赋值、审计/认证循环分块和大 chunk 警告,未扩大本次修改去重构这些模块。
### 本地页面检查
```powershell
node scripts/tests/verifyBuild.mjs --serve
```
访问 `http://127.0.0.1:5190`。该预览拦截全部 `/api/` 请求且禁用真实代理,测试数据为模拟值;登录和写请求不会到真实后台。模拟账号为超级管理员,仅用于本地验收,输入满足登录页既有规则的任意测试账号密码即可。
已检查订单详情、核销失败详情、代理注册失败详情、预警详情/规则页、改密弹窗和换货完成 1202 提示;页面检查未产生 JS 错误。改密弹窗额外检查 375px 视口。
模板下载从统一 UTF-8 BOM 文本生成新 CSV,原 GBK 静态文件不再被此页面引用,没有改写用户已有模板资产。设备 Excel 模板没有修改。`src/types/components.d.ts` 与实施前内容 SHA-256 一致;已有开发服务器的自动生成曾补入本次新 Alert 声明,已改显式组件导入并只撤回该自动新增行,用户原差异保留。
## 待真实联调
1. 六类审批失败终态真实数据、权限矩阵、未知结果恢复、核销预占释放和提现重新冻结。
2. 真实支付摘要与多次支付历史、换货解除关联后成功重试及其他错误响应。
3. CSV 表头/手机号错误、逐行部分成功,以及设备 IMEI 空白/全部失败。
4. 新建与历史订单、IoT 卡、设备、预警导出文件列。
这些项目继续保留在任务清单,用户验收及部署后再归档。
## 用户追加:换货冲突快捷解绑
已在用户明确要求下补充以下行为:
- 创建换货捕获提交时新资产上下文,确认完成使用换货单的新资产标识,不使用旧资产。按用户最新修正,跳转手机号只取当前 1202 `data.phone`,缺失时不再回退历史手机号数组。
- 用户点击跳转后,路由带 `asset_identifier` 和 `phone`,目标页从 1 页/20 条精确查询。只实际勾选匹配两项条件且有效的记录,不全选历史失效记录。
- 表格勾选方法由已有 ArtTable 透传;手工取消后不立即重新勾选,重置、筛选、翻页及解绑后刷新清空旧选择;缓存重入或路由参数变化重新取目标,过期响应不能覆盖新查询。
- 批量解绑仍使用 `phone_asset_association:unbind_batch` 和原原因/二次确认表单;结果列展示「解绑成功/解绑失败」,资产类型同时显示中文,不修改后端布尔值契约。
原说明要求号码不额外记录或持久化;用户追加明确要求两项路由参数,因此用户主动跳转时允许号码进入该 URL 查询参数,不额外记录日志或写入本地存储。
新增三项自动测试,全套 66 项通过,类型检查、受影响文件 lint、编码和严格规范校验通过,生产构建通过(原有警告仍在)。本地模拟确认了完整的 1202 弹窗 → 带参跳转 → 筛选并勾选有效记录 → 手工取消禁用按钮 → 原确认表单 → 中文成功结果链路,没有调用真实后台解绑接口。
### 用户修正:区分共用的 1202 错误码
同为 1202 的「已完成过换货」响应 `data=null`,只弹出后端 `msg` 和「知道了」,不出现关联管理按钮;带有效 `data.phone` 的绑定冲突才保留原权限内的去解绑入口。两种弹窗正文都使用原始 `msg`,不再拼接手机号或固定指引。新增回归覆盖 HTTP/业务承载、null/空白/非字符串号码及资产历史数组不得绕过门槛,全套测试增至 67 项。
该修正的 67 项自动回归、类型检查、lint、格式、编码及严格规范校验通过。重新做浏览器检查时本地会话回到了资产首页,未完成两种新弹窗的视觉验证;未将此项标为已通过,也未操作真实换货或解绑数据。
## 2026-10-14:允许特殊符号与改密遮罩覆盖侧栏
最新密码规则恢复为 8~12 位,大写、小写、数字、半角特殊符号至少三类,禁止空白和中文等非法字符。`Admin@12345`、`ABC1234!`、`abc1234!`、`Abcdefg!` 可通过;仅两类、超长/过短、空白、中文、emoji 和控制字符拒绝。共享规则和双语文案已同步所有后台新密码表单及账号服务,不改旧密码输入、登录、C 端、操作密码或 WiFi 密码。
侧栏未变暗的原因是顶栏堆叠上下文(100)低于侧栏(101),改密弹窗此前在顶栏内部。加 `append-to-body` 后,DOM 检查确认实际遮罩父元素是 BODY、不在顶栏中;菜单位置命中遮罩而非菜单。1920px 和 375px 截图检查通过,整页包括侧栏一起变暗,未改变全局 z-index。
全套 68 项 Node 测试、类型检查、受影响文件 ESLint、该弹窗 Stylelint、格式、UTF-8 和规范校验通过。模拟页面中 `Admin@12345` 通过表单校验并发出本地 `PUT /api/auth/password` 请求,无表单规则错误。没有修改真实账号密码;工作区同时出现的设备 Excel 模板及其临时文件属于用户其他工作,未触及。
## 2026-10-14:全后台新密码入口复核
用户要求所有修改密码入口使用相同规则。全量搜索密码输入、独立校验、动态输入弹窗及密码服务调用后,确认既有后台入口均已引用 `loginPassword.ts`;共享规则修改会同时生效,不只影响顶栏弹窗。本次没有发现需要补改的后台密码表单,也不新建账号改密入口。
| 后台入口 | 表单文件 | 已核对字段 |
| --- | --- | --- |
| 本人修改密码 | `src/components/core/layouts/art-header-bar/ChangePasswordDialog.vue` | `new_password`、`confirm_password` |
| 平台账号创建 | `src/views/account-management/account/index.vue` | `password` |
| 店铺/企业下客户账号创建 | `src/views/common/account-list.vue` | `password` |
| 店铺初始账号创建 | `src/views/shop-management/list/index.vue` | `init_password` |
| 企业创建及企业修改密码 | `src/views/account-management/enterprise-customer/index.vue` | 两个表单各自的 `password` |
新增源码契约回归,逐项确认上述七个新密码输入使用共享提示、12 位输入上限、无 `.trim` 的绑定,以及共享校验与必填规则,没有叠加旧长度或字符正则。账号服务的可选密码修改与独立改密仍使用共享规则。仓库中未被这些表单调用的通用密码工具不改变;登录/旧密码、操作密码、WiFi/锁屏密码和公开扫码注册页继续排除。
可复现检查仍使用上面的 Node 测试命令;全套增至 69 项并通过,类型、测试文件 ESLint/格式、编码及 OpenSpec 严格校验通过。此轮为源码及自动回归核对,没有修改真实账号密码或新增权限编码。docs-generator 用于明确列出实际覆盖入口,并区分源码核对与真实后端联调。
## 2026-10-14:用户追加代理扫码注册密码规则
原扫码页按此前排除 C 端的范围保留了 8~32 位校验。用户现在明确要求该页及同一注册接口的 `password` 使用 8~12 位、四类至少三类、禁止空格和中文,本轮只将这项纳入,不扩大到其他 C 端功能。
| 证据 | 已确认结果 | 实现路径 |
| --- | --- | --- |
| 表单源码契约回归与共享规则测试 | 扫码页复用同一规则,输入上限 12,无 `.trim`,完整规则可见;强度反馈不把空格/中文算作有效符号 | `src/views/agent-registration/index.vue`、`loginPassword.ts` |
| 注册服务桩测试 | 有效三类组合原样发送;过短/超长/两类/空格/中文阻止请求;原注册路径、其他字段、免 Token 和短信调用不变 | `src/api/modules/agentDistribution.ts`、`scripts/tests/octoberBatchOne.test.mjs` |
ui-ux-pro-max 影响本次提示处理:保留既有页面与 Element Plus 样式,完整规则独立显示并关联输入框,使用文字反馈而不只用颜色,长校验错误参与正常布局。docs-generator 用于明确记录这次范围例外和未完成的浏览器验收。
全套 71 项自动测试、类型检查、受影响文件 ESLint/Stylelint、格式、UTF-8、OpenSpec 严格校验及生产构建通过。当前 CUA 浏览器列表为空,IAB 和 Chrome 均返回不可用,未完成移动端视觉检查,不将其标为通过。没有发送真实短信、提交真实注册或改变任何权限编码。
## 2026-10-14:注册单次失败提示与公共表头拖拽
用户发现公开代理注册在 1050/1001 模板错误时,公共请求层与页面 catch 分别弹消息。只给原注册请求设置 `errorMessageMode: 'none'`,页面以共享映射处理非零响应或 HTTP 错误:1050/1001 显示「注册失败, 请联系管理员」,其他可读业务原因保留。短信、后台注册审核和公共 HTTP 不改。请求进行中阻止重复提交,失败保留输入,不日志输出密码。
代理注册申请列表还报告 `Sortable: el must be an HTMLElement`。仓库唯一 VueDraggable 位于公共表头 Popover 的列设置;原组件自动启动可能拿到未渲染/已离开的空 ref。修复改用 `useDraggable` 禁止自动启动,Popover 打开且进入后仅对真实、仍连接文档的 HTMLElement 初始化;关闭、卸载和 KeepAlive 停用销毁,晚到回调忽略。原列排序双向 model、勾选状态和按钮不变。
| 证据 | 已确认结果 | 实现路径 |
| --- | --- | --- |
| 共享错误映射及服务桩测试 | 业务/HTTP 的 1050/1001 隐藏配置细节,原注册配置关闭公共消息,短信配置不变 | `agentRegistrationError.ts`、`agentDistribution.ts` |
| 实际扫码页 setup 执行测试 | 每种模板错误只调用一次指定消息;并发重复点击不新增请求;提交失败、加载状态及表单正确保留 | `octoberBatchOne.test.mjs`、扫码页 |
| 编译后的表头 Vue 生命周期测试,拖拽控制器使用桩 | 首次挂载不自动启动;空/非元素/脱离节点不启动;开关、卸载和缓存切换正确清理;列顺序及 checked 保持 | `tableHeaderDragLifecycle.test.mjs`、`ArtTableHeader.vue` |
ui-ux-pro-max 的生命周期建议用于把拖拽实例绑定真实节点和清理事件,不做视觉改版。docs-generator 用于区分桩/组件逻辑证据与真实浏览器验收。全套 78 项 Node 测试、类型、受影响文件 lint/stylelint、格式、编码、严格规范及生产构建通过;构建仍存在此前记录的常量赋值/循环分块/大 chunk 警告。当前无浏览器连接,未声称已重放用户浏览器的 console 堆栈,也未发送真实注册、短信或修改权限。

View File

@@ -0,0 +1,92 @@
# Change: 十月第 1 批后台前端对接修正
## Why
依据 [第 1 批前端对接说明](../../../docs/产品迭代10月份修改/第1批-8-9月迭代前端对接说明.md),后台现有代码仍使用旧密码校验、旧审批业务状态和旧预警规则字段,缺少订单在线支付记录与换货手机号冲突反馈。后端已部署测试环境,后台需要同步契约与交互,避免失败单据继续显示审批恢复操作、导入提示误导以及已删除字段显示异常。
用户已于 2026-10-13 批准实施。后台代码已完成适配,本地验证与真实后端联调状态分开记录在 [实施记录](./implementation.md)。原范围只管后台;2026-10-14 用户明确追加代理扫码注册页及同一注册接口的密码校验和失败提示,其余 `/api/c/v1` 接口及 C 端页面仍不在范围内。
## What Changes
- M3:后台订单列表和详情展示 `third_party_trade_no`、`payment_channel`、`payment_merchant_name`;详情新增支付记录表,详情类型与列表/创建类型分离,支付单状态独立于订单支付状态。
- M8、M14:六类后台业务补充各自的「审批提交失败」终态、筛选、标签和操作判断;显式失败不再恢复原审批,结果未知保留原有恢复资格与权限判断。
- M8:核销申请列表和详情使用真实的 `approval_submission_status` 展示审批提交状态,不能只依赖当前可能为空的名称字段;账单详情中的申请状态同步扩展。
- M1:**BREAKING**:按 2026-10-14 用户修正,后台七个密码接口相关表单、服务和类型统一到「8~12 位,大写、小写、数字、半角特殊符号至少三类,无空格或中文」,包括后台 `PUT /api/auth/password`;账号独立改密使用 `new_password`。本人改密弹窗挂载到 body,使遮罩覆盖侧栏。旧密码输入、操作密码和 WiFi 密码不套用新规则。
- 用户追加 M1:代理扫码注册页与 `POST /api/c/v1/agent-distribution-registrations` 的 `password` 复用相同校验;同步 12 位输入上限、可见规则及强度反馈,其他注册字段、短信、接口路径和免 Token 行为不变。
- 用户追加注册反馈:仅原公开代理注册请求关闭公共错误消息,页面将 1050/1001 映射为「注册失败, 请联系管理员」且每次失败只提示一次,其他业务错误按其具体原因展示;不修改公共 HTTP 处理或其他接口。
- M12:创建换货与确认完成捕获错误码 `1202`,从错误响应 `data.phone` 读取手机号,在弹窗中引导到已有「手机号资产关联」入口;不自动解绑、不新增扫码/退款前置拦截,失败时保留表单及原单状态。
- 用户追加 M12 快捷处理:跳转携带本次新资产标识与关联手机号,关联页面自动预填筛选并勾选匹配有效记录;复用原批量解绑权限和二次确认,结果表布尔值改为中文成功/失败,不自动执行解绑。
- M16:**BREAKING**:删除预警规则响应类型、规则列表及规则详情展示中对 `real_data_mb` 的依赖;预警列表和详情补齐 `used_mb`、`limit_mb` 及新增 `threshold_mb`,以 MB 展示触发时快照,说明包含加油包。套餐接口和套餐选项中的 `real_data_mb` 保留。
- M2:**BREAKING**:店铺业务员批量换绑说明及前端内置模板(如有)改用固定表头 `店铺编码,操作类型,平台登录账号,备注`,注明换绑时只填写平台用户登录手机号、清空时该列留空;不兼容旧表头,保留逐行失败原因。
- M23:设备导入文案将 IMEI 列从可选改为必填,不改变现有模板列名、列序、请求结构,也不新增 IMEI 长度、格式或重复校验;失败详情继续展示后端行号和原因。
- M13:保留退款状态 3 的重新发起入口;若存在引导在企微重新提交的文案则移除,统一指向后台退款重提流程。
- M4~M6 及 M16 导出补列:仅安排新建/历史导出任务下载回归,文件列由后端生成,不增加前端导出模板或修改历史文件。
## Scope
| 项目 | 后台纳入内容 | 不纳入内容 |
| --- | --- | --- |
| M1 | 后台七个密码接口;用户追加代理扫码注册页面及原注册接口的密码校验、失败提示 | 其他 C 端页面/接口与非登录密码 |
| M3 | `/api/admin/orders` 列表/创建响应与详情支付记录 | C 端订单请求、支付流程 |
| M8、M14 | 核销、退款、代理注册审核、线下充值、佣金提现、提现资料资格 | C 端注册申请及其他 `/api/c/v1` 调用 |
| M12、M13 | 换货冲突提示、退款重提引导及回归 | 后端手机号解绑规则、企微回调实现 |
| M16 | 预警规则与记录的展示契约、导出回归 | 预警计算、套餐商品额度调整 |
| M2、M23 | 导入说明/已有模板表头及任务失败原因 | 后端 CSV/Excel 解析器实现 |
| F1、M9 | 无 | H5 手机号绑定、登录响应、资产临期提醒、通知中心 |
### 审批失败状态与后台处理
| 后台业务 | 新业务状态 | 失败后的后台处理 |
| --- | --- | --- |
| 核销申请 | `4` | 有修改权限时,通过原 `PUT /api/admin/employee-collection-applications/{id}` 重新提交;账单重新读取可核销金额 |
| 退款 | `7` | 有重提权限时,通过原 `POST /api/admin/refunds/{id}/resubmit` 重新发起 |
| 代理注册审核 | `3` | 隐藏恢复审批,提示「请申请人重新扫码申请」;后台不代申请人发起 C 端注册请求 |
| 线下充值 | `7` | 复用现有线下新建表单,通过 `POST /api/admin/agent-recharges` 新建单,不给原单补发审批 |
| 佣金提现 | `5` | 在有操作资格的店铺提现入口,通过原 `PUT /api/admin/shops/{shop_id}/withdrawal-requests/{id}` 重新提交 |
| 提现资料资格 | `4` | 复用已有资料提交表单,通过原 `POST /api/admin/shops/{shop_id}/withdrawal-qualifications` 提交新版本 |
### 不新增的能力
- 除用户明确追加的代理扫码注册密码规则与失败提示外,不修改其他 `/api/c/v1` 服务或页面;不改变公开注册请求路径、字段和免 Token 行为。
- 不新增后端接口、权限编码、审批实例或财务冻结/释放逻辑。
- 不因密码接口清单存在而补建目前没有的账号改密页面;覆盖既有页面和服务契约,新增入口须另行确认。
- 不修改 `src/types/components.d.ts` 的用户已有改动。
## Impact
- Affected specs: `order-management`、`admin-authentication`、`employee-collection`、`refund-management`、`agent-distribution-registration`、`agent-recharge`、`commission-management`、`exchange-management`、`phone-asset-association-management`、`package-traffic-alert`、`shop-management`、`device-batch-import`。
- Affected code:
- `src/types/api/{order,account,employeeCollection,refund,agentDistributionRegistration,agentRecharge,commission,packageTrafficAlert}.ts` 及相关类型导出。
- `src/api/modules/{order,account,exchange}.ts`;其余审批相关服务仅按既有接口复用,不扩展 C 端请求。
- 用户追加:`src/views/agent-registration/index.vue`、`src/api/modules/agentDistribution.ts` 的注册密码校验与类型注释。
- `src/views/order-management/order-list/{index,detail}.vue`。
- `src/components/core/layouts/art-header-bar/ChangePasswordDialog.vue`、`src/views/account-management/{account,enterprise-customer}/index.vue`、`src/views/common/account-list.vue`、`src/views/shop-management/list/index.vue`。
- `src/views/finance/employee-collection/`、`src/views/finance/refund/`、`src/views/finance/agent-recharge/`、`src/views/shop-management/agent-distribution-registrations/`。
- `src/views/commission-management/{withdrawal-approval,my-commission}/index.vue` 及使用相同提现状态的其他后台视图。
- `src/views/asset-management/exchange-management/{index,detail}.vue`。
- `src/views/package-management/traffic-alert-rules/index.vue`、`src/views/package-management/traffic-alerts/{index,detail}.vue`。
- `src/views/shop-management/business-owner-import/index.vue`、`src/views/asset-management/task-management/device-task/index.vue`。
- `src/config/constants/{refund,commission}.ts`、新密码专用校验工具、`src/utils/business/apiError.ts`、必要的中英文文案。
- 不引入新依赖;复用现有 Vue、Element Plus、权限、表单、错误处理和异步任务机制。
### 与现有提案的关系
当前 `openspec/specs/` 无已发布能力规范,相关功能仅存在于历史未归档提案与业务代码中,因此本次沿用既有 capability 名称,以 `ADDED Requirements` 记录本批次的独立适配约束,不伪造 `MODIFIED` 基线。
- 订单:承接 `update-order-management-response-semantics`,保持操作者/销售店铺/佣金语义。
- 核销:承接 `update-employee-collection-approval-recovery`、`update-writeoff-application-and-superadmin-commission`,不回退抽屉和账单筛选优化。
- 退款:承接 `update-refund-management`、`add-refund-approval-recovery`。旧提案允许显式提交失败恢复原审批的描述,在新业务终态 `7` 下不再适用;保留结果未知的恢复路径。
- 代理注册:承接 `add-agent-registration-approval-management`,仅扩展后台审核状态和反馈。
- 充值:承接 `update-agent-self-recharge-and-offline-approval`,保留线下凭证、OCR、收款方式等已有字段。
- 佣金:承接 `add-commission-management`,保留既有店铺范围和超管选店逻辑。
- 换货:承接 `update-exchange-refund-interception-feedback`、`update-exchange-migration-and-shop-import`,`1202` 为独立定制反馈,非 `1202` 错误继续按原逻辑展示。
- 预警:承接 `add-package-traffic-alert`,其旧「规则展示当前真流量额度」描述被本批次规则响应契约取代。
- 导入:承接 `update-exchange-migration-and-shop-import`、`update-device-batch-import-contract`,保留任务字段与设备模板结构。
## 已确认的实施依据
1. 用户确认没有最新 `admin-openapi.yaml`,本次不要求提供,也不将其作为实施前置条件;接口适配以第 1 批对接说明为依据,仓库中的八月 OpenAPI 不作为十月最新版。
2. 用户于 2026-10-14 修正为允许特殊符号,恢复说明中的「四类至少三类」口径,长度 8~12 位、禁止空白和中文;半角可打印 ASCII 特殊符号均可用。此前禁止特殊符号的确认不再适用。
3. 除 2026-10-14 明确追加的代理扫码注册页/同一注册接口的密码规则与失败提示外,其他 `/api/c/v1` 和 C 端页面仍排除。
以上需求疑问已消除。详见 [设计说明](./design.md)、[任务清单](./tasks.md) 与 [实施记录](./implementation.md);如联调发现实际接口与说明或用户确认不符,先向用户反馈,不自行改变口径。

View File

@@ -0,0 +1,107 @@
## ADDED Requirements
### Requirement: 后台新登录密码统一校验
后台既有设置新登录密码的表单 SHALL 按 2026-10-14 用户修正规则校验:长度 8~12 位,大写字母、小写字母、数字、半角特殊符号四类至少包含三类。可打印 ASCII 标点符号 MUST 允许;空白、中文、控制字符、emoji 等非 ASCII 字符 MUST 拒绝,不静默 trim。
#### Scenario: 有效新密码
- **WHEN** 用户在后台本人改密、账号创建、店铺初始账号、企业创建或企业改密入口输入 `Abc12345`
- **THEN** 新密码校验 MUST 通过
- **AND** 新密码/确认密码输入限制及说明 MUST 为 8~12 位,四类字符至少包含三类,允许半角特殊符号
- **AND** 需要确认密码的表单 MUST 验证其与新密码一致
#### Scenario: 无效新密码
- **WHEN** 用户输入 7 位、13 位、只包含两类字符的密码,或包含空白、中文、emoji 等非法字符的密码
- **THEN** 前端 MUST 阻止提交并展示具体规则提示
- **AND** MUST NOT 静默 trim 密码后当作合法值提交
#### Scenario: 含特殊符号且满足三类
- **WHEN** 用户输入 `Admin@12345`、`ABC1234!`、`abc1234!` 或 `Abcdefg!`
- **THEN** 前端 MUST 按至少三类规则放行,不额外要求大写、小写和数字三者同时存在
- **AND** 提示 MUST 不再显示「不允许特殊符号」
#### Scenario: 修改账号未设置新密码
- **WHEN** 既有账号修改操作未提供可选 `password`
- **THEN** 页面 MUST NOT 因缺少密码阻止其他字段修改
- **AND** MUST NOT 提交空密码覆盖原值
- **AND** 本批次 MUST NOT 仅为接口清单补建当前没有的账号密码编辑入口
### Requirement: 后台密码接口字段与旧密码兼容
后台密码服务 SHALL 保持各接口规定的请求字段;本人改密和账号独立改密的新密码使用 `new_password`,账号创建/可选修改及企业创建/改密使用 `password`,店铺初始密码使用 `init_password`。后端字段级错误 MUST 以既有 `msg` 或提供的 `message` 展示,不替换为笼统提示,不记录密码。
#### Scenario: 独立修改账号密码
- **WHEN** 既有服务调用 `PUT /api/admin/accounts/{id}/password`
- **THEN** 请求体 MUST 按本批次说明使用 `new_password`,而不是当前旧封装的 `password`
- **AND** 本批次 MUST NOT 将其他账号接口的 `password` 改名
#### Scenario: 使用旧密码登录和本人改密
- **WHEN** 用户使用仍被后端接受的旧密码登录或填写本人改密 `old_password`
- **THEN** 前端 MUST NOT 对这些旧密码输入套用新的 8~12 位/至少三类限制
- **AND** 本人改密成功后的清理表单、清理登录态和返回登录页行为 MUST 保留
#### Scenario: 非登录密码与其余 C 端保持不变
- **WHEN** 实施本批次密码适配
- **THEN** 操作密码、WiFi 密码和通用校验器其他调用行为 MUST 保持不变
- **AND** 除用户明确追加的代理扫码注册密码校验及失败提示外,其余 C 端页面和 `/api/c/v1` 服务 MUST 不修改
#### Scenario: 展示后端字段级原因
- **WHEN** 密码相关请求返回包含具体校验原因的 `msg` 或 `message`
- **THEN** 页面 MUST 展示该原因且不重复弹错
- **AND** 请求、日志和错误反馈 MUST NOT 输出输入的密码值
### Requirement: 本人改密遮罩覆盖整个后台
本人修改密码弹窗 SHALL 使用 `append-to-body` 脱离顶栏堆叠上下文;遮罩 MUST 覆盖左侧菜单、顶栏和内容区,避免白色菜单压在遮罩上层,同时保留原表单、确认和关闭行为。
#### Scenario: 从顶栏打开改密弹窗
- **WHEN** 已登录用户打开本人修改密码弹窗
- **THEN** 弹窗遮罩 MUST 挂载到 body,左侧菜单 MUST 与页面其他背景一起变暗且不可点击
- **AND** 弹窗 MUST 继续支持 375px 视口,规则说明与错误提示不得重叠
### Requirement: 代理扫码注册密码复用统一规则
公开代理扫码注册表单及注册服务 SHALL 按用户明确追加范围复用后台新密码规则:8~12 位,大写字母、小写字母、数字、半角特殊符号至少三类,禁止空格和中文等非法字符,不静默 trim。注册路径、其他字段、短信验证码和免 Token 行为 MUST 保持不变,不扩大到其他 C 端功能。
#### Scenario: 输入有效注册密码
- **WHEN** 用户输入 `Abc12345`、`ABC1234!`、`abc1234!` 或 `Abcdefg!`
- **THEN** 表单及服务 MUST 校验通过,原样发送 `password` 至既有注册接口
- **AND** 页面 MUST 展示完整规则、12 位输入上限和「密码符合规则」反馈
#### Scenario: 输入无效注册密码
- **WHEN** 用户输入过短、过长、仅两类字符,或带空格/中文的密码
- **THEN** 表单及服务 MUST 阻止注册提交
- **AND** 页面 MUST 展示具体校验原因,不能把空格/中文显示为满足规则
- **AND** 规则说明和长错误文本 MUST 正常换行,不覆盖下一个表单项
### Requirement: 代理扫码注册失败仅提示一次
原公开代理注册请求 SHALL 关闭公共错误消息,由扫码注册页面统一处理失败;后台接口、短信及其他请求 MUST 保留原错误处理。错误码 1050/1001 MUST 显示「注册失败, 请联系管理员」,不暴露企业微信审批场景/模板配置细节。
#### Scenario: 企业微信模板错误阻止注册
- **WHEN** 注册接口以业务响应或 HTTP 错误返回 1050/1001
- **THEN** 每次失败 MUST 只显示一次「注册失败, 请联系管理员」
- **AND** 表单 MUST 保留供重试,不能显示提交成功或再显示「分销码不可用」
#### Scenario: 其他注册错误
- **WHEN** 注册失败不是 1050/1001,且后端提供可读 `msg` 或 `message`
- **THEN** 页面 MUST 只提示一次具体业务原因,不一律错误归因于分销码
- **AND** 无业务消息的网络错误 MUST 使用既有安全降级提示,不记录密码
#### Scenario: 注册提交仍在进行
- **WHEN** 用户重复点击提交,且上一次注册请求尚未完成
- **THEN** 页面 MUST 阻止并行重复提交,避免重复申请和重复失败提示

View File

@@ -0,0 +1,19 @@
## ADDED Requirements
### Requirement: 后台代理注册审批提交失败反馈
后台代理注册审核 SHALL 支持业务状态 `3`「审批提交失败」的筛选和失败标签,终态下隐藏恢复审批,并提示申请人从原扫码入口重新申请。后台 MUST NOT 为重新申请调用任何 `/api/c/v1` 接口。
#### Scenario: 审核失败申请
- **WHEN** 列表或详情收到 `status=3` 的注册申请
- **THEN** 页面 MUST 展示「审批提交失败」,查询类型和筛选 MUST 支持值 3
- **AND** MUST 隐藏恢复审批,即使陈旧响应 `recoverable=true`
- **AND** MUST 提示「请申请人重新扫码申请」,保留详情只读功能
- **AND** MUST NOT 新增后台代注册提交或修改公开注册页面
#### Scenario: 非终态未知结果仍可恢复
- **WHEN** 非失败终态申请的提交结果未知,后端允许恢复且用户有原恢复权限
- **THEN** 页面 MUST 保留原恢复审批行为并在操作后刷新详情
- **AND** MUST NOT 把提交状态数值直接当作注册业务状态

View File

@@ -0,0 +1,26 @@
## ADDED Requirements
### Requirement: 线下充值审批失败重新新建
后台线下充值 SHALL 识别业务状态 `7` 为「审批提交失败」终态,支持状态筛选和失败标签;有原创建资格的用户 SHALL 通过既有线下新建表单重新发起,使用 `POST /api/admin/agent-recharges` 新建单,而不是给原单恢复/补发审批。
#### Scenario: 失败单只读与终态操作
- **WHEN** 线下充值列表或详情展示 `status=7` 的单据
- **THEN** 页面 MUST 展示「审批提交失败」,筛选 MUST 支持值 7
- **AND** MUST 隐藏原单补发审批、恢复审批及仅适用于待处理单的确认/拒绝操作
- **AND** 原权限允许的查看详情和查看凭证 MUST 保留
#### Scenario: 重新发起线下充值
- **WHEN** 具备现有线下创建资格的用户为失败单选择重新发起
- **THEN** 页面 MUST 打开既有线下创建表单并沿用原字段校验
- **AND** 提交 MUST 使用 `POST /api/admin/agent-recharges`,不得携带原单 ID 调用虚构重提接口
- **AND** 新建成功后 MUST 刷新列表,不乐观将旧单状态改成成功
#### Scenario: 保留线上充值与原权限
- **WHEN** 实施终态适配
- **THEN** 在线支付、可用方式、线下收款方式/流水号/OCR/凭证等原行为 MUST 保持不变
- **AND** 前端 MUST NOT 为重新发起扩大原角色、店铺或创建权限
- **AND** MUST NOT 修改 C 端接口或将未知结果自动视为失败

View File

@@ -0,0 +1,37 @@
## ADDED Requirements
### Requirement: 佣金提现审批提交失败状态
后台提现审核、店铺提现记录和相关详情 SHALL 支持业务状态 `5`「审批提交失败」,各原有提现状态筛选 MUST 包含值 5;具备既有店铺操作资格的用户 SHALL 通过原提现重提接口重新提交,不复用失败审批或本地模拟冻结金额。
#### Scenario: 失败提现展示与操作
- **WHEN** 提现列表或详情收到 `status=5`
- **THEN** 页面 MUST 展示失败标签并支持筛选值 5
- **AND** MUST NOT 为该终态展示待审核专有审批或恢复旧审批操作
- **AND** 可操作的店铺提现入口 MUST 支持「重新提交」,调用 `PUT /api/admin/shops/{shop_id}/withdrawal-requests/{id}`
- **AND** 既有金额、收款信息、附件校验及店铺权限范围 MUST 保留
#### Scenario: 刷新已释放的冻结金额
- **WHEN** 失败状态已由后端释放冻结金额,或用户成功重新提交提现
- **THEN** 页面 MUST 刷新后端佣金概览和提现记录
- **AND** MUST NOT 前端自行增减冻结金额或推断新的冻结结果
### Requirement: 提现资料审批失败提交新版本
后台提现资料 SHALL 识别业务状态 `4` 为「审批提交失败」,展示失败标签并支持以值 4 筛选。原权限允许的用户 SHALL 使用已有资料表单提交新版本,不对失败实例恢复审批。
#### Scenario: 失败资料展示和重提
- **WHEN** 店铺提现资料返回 `status=4`
- **THEN** 页面 MUST 展示「审批提交失败」,资料状态筛选 MUST 支持值 4
- **AND** 有原资料提交资格时 MUST 允许复用原表单,通过 `POST /api/admin/shops/{shop_id}/withdrawal-qualifications` 提交新版本
- **AND** 成功后 MUST 刷新版本列表,保留旧版本历史,不乐观复用旧审批
- **AND** 原店铺隔离、附件校验和作废权限 MUST 保持不变
#### Scenario: 状态数值不跨业务共用
- **WHEN** 页面同时处理提现状态 5、资料状态 4 和佣金明细状态
- **THEN** 前端 MUST 使用各自业务映射
- **AND** MUST NOT 将佣金明细的状态 5「回溯」改成审批提交失败

View File

@@ -0,0 +1,27 @@
## ADDED Requirements
### Requirement: 设备导入说明标注 IMEI 必填
后台设备导入说明 SHALL 将独立 IMEI 列标注为必填,不再列作可选;现有 Excel 模板列名、列数、列序和上传结构 MUST 不变,前端 MUST NOT 增加文档以外的 IMEI 格式、长度或重复限制。
#### Scenario: 查看导入说明和模板
- **WHEN** 用户打开设备导入弹窗
- **THEN** 说明 MUST 明确 IMEI 必填,且不能因为首列允许 IMEI 作为设备标识就误认为独立 IMEI 列可省略
- **AND** 原模板下载及列结构 MUST 保持不变
- **AND** 其他已约定的设备标识、SN 和卡 ICCID 规则 MUST 保留
### Requirement: 保留设备导入行级失败反馈
设备导入任务详情 SHALL 继续按后端 `failed_items` 展示行号、设备标识和原因,IMEI 空值/空白导致的失败 MUST 不影响后端已成功导入的其他行。
#### Scenario: 混合成功与 IMEI 空值失败
- **WHEN** 任务详情返回某行原因「设备IMEI(imei)不能为空」和其他成功行
- **THEN** 页面 MUST 展示该行号和原始失败原因,保留任务成功/失败计数
- **AND** 前端 MUST NOT 因单行为空在提交前拒绝整个文件
#### Scenario: 全部失败
- **WHEN** 整个文件所有行失败,后端任务状态为失败
- **THEN** 页面 MUST 展示后端失败状态及行级明细,不当作上传成功等于导入成功

View File

@@ -0,0 +1,34 @@
## ADDED Requirements
### Requirement: 核销审批提交失败终态与重提
核销申请 SHALL 识别业务状态 `4` 为「审批提交失败」终态,申请列表、详情及账单中的关联申请状态 MUST 一致。该状态不得恢复原审批,有原修改权限的用户 SHALL 通过既有修改表单重新提交申请。
#### Scenario: 显式失败申请
- **WHEN** 核销申请 `status=4`,或账单分摊记录 `application_status=4`
- **THEN** 页面 MUST 以失败标签展示「审批提交失败」,申请筛选 MUST 包含值 4
- **AND** MUST 隐藏恢复审批,即使陈旧数据仍返回 `recoverable=true`
- **AND** 有原修改权限时 MUST 允许通过 `PUT /api/admin/employee-collection-applications/{id}` 重新提交
- **AND** MUST 保留原表单、账单分摊与权限范围
#### Scenario: 金额释放与重提结果
- **WHEN** 核销申请失败后用户刷新账单,或通过既有接口重新提交申请
- **THEN** 页面 MUST 从后端重新读取预占和可核销金额,不本地模拟释放金额
- **AND** 成功重提后 MUST 刷新申请与关联账单
### Requirement: 核销真实审批提交状态
核销列表和详情 SHALL 根据真实 `approval_submission_status` 展示 `0 待提交 / 1 提交中 / 2 已提交 / 3 提交失败 / 4 结果未知`;后端名称为空时 MUST 按数值回退,不仅依赖名称字段。
#### Scenario: 无审批上下文
- **WHEN** 申请返回 `approval_submission_status=0`
- **THEN** 列表和详情 MUST 展示「待提交」,不得因 0 为 falsy 而展示为缺失
#### Scenario: 提交结果未知
- **WHEN** 提交状态为 4,业务单并非失败终态,且后端返回 `recoverable=true`
- **THEN** 有原恢复权限的用户 MUST 仍能看到恢复审批入口
- **AND** 前端 MUST NOT 将结果未知自行当作审批提交失败或直接生成新审批

View File

@@ -0,0 +1,67 @@
## ADDED Requirements
### Requirement: 换货新资产手机号绑定冲突提示
后台创建换货和确认完成 SHALL 在错误码 `1202` 时用一次文本弹窗原样展示后端 `msg`。`1202` 同时用于已换货等业务拒绝,只有错误响应带有效字符串 `data.phone` 且用户有原查看权限时 MUST 提供解除关联跳转;处理 MUST 覆盖业务失败与 HTTP 错误,不自动解绑或扩大权限。
#### Scenario: 1202 返回手机号
- **WHEN** `POST /api/admin/exchanges` 或 `POST /api/admin/exchanges/{id}/complete` 返回 `code=1202` 且含 `data.phone`
- **THEN** 页面 MUST 原样展示后端 `msg`,不得拼接手机号或替换为固定文案
- **AND** 有原查看权限且已知新资产时 MUST 提供「前往手机号资产关联」按钮并带参跳转
- **AND** 默认错误提示与该弹窗 MUST NOT 重复展示
- **AND** 手机号 MUST 只用于用户主动发起的路由参数,不额外写日志或本地存储
- **AND** 前端 MUST NOT 自动调用单条、批量或 CSV 解绑接口
#### Scenario: 号码缺失或无管理权限
- **WHEN** 1202 响应不含有效号码,或用户没有关联管理入口权限
- **THEN** 页面 MUST 使用仅有「知道了」的提示弹窗原样展示 `msg`,不展示跳转/解绑按钮
- **AND** MUST 不根据选中资产 `associated_phones` 推断该错误为手机号绑定冲突
#### Scenario: 已完成过换货的 1202
- **WHEN** 接口返回 `code=1202,data=null,msg=该资产已完成过换货,如需再次换货请使用换货后的新资产`
- **THEN** 页面 MUST 显示该原始 `msg` 和「知道了」,不显示「前往手机号资产关联」
### Requirement: 换货冲突后保持数据并允许手动重试
1202 失败后后台 SHALL 保留当前创建表单或后端原完成状态,解除关联后允许用户手动再次提交。非 1202 错误 MUST 保留原统一反馈及业务判断。
#### Scenario: 创建失败保留表单
- **WHEN** 创建换货因 1202 被拒绝
- **THEN** 当前新旧资产、原因、换货类型和其他表单值 MUST 保留
- **AND** loading MUST 结束,取消提示 MUST NOT 被当作成功
- **AND** 用户解除关联后 MUST 可手动再次提交原接口
#### Scenario: 确认完成被拒绝
- **WHEN** 确认完成接口因 1202 被拒绝
- **THEN** 页面 MUST 刷新原换货单,并保持后端「已发货待确认」状态
- **AND** MUST NOT 乐观标记换货完成或清空当前单据
- **AND** 用户解除关联后 MUST 可手动重新确认
#### Scenario: 其他错误及原流程不变
- **WHEN** 换货接口返回非 1202 错误,包括退款拦截、权限失败、迁移失败或网络错误
- **THEN** 页面 MUST 继续按原业务文案及统一错误分类反馈,不重复弹错
- **AND** MUST NOT 新增依据扫码历史或退款状态的前置拒绝逻辑
- **AND** 当前换货迁移字段、角色限制和接口成功行为 MUST 保持不变
### Requirement: 换货冲突跳转携带新资产与手机号
收到带有效 `data.phone` 的 1202 后,用户点击「前往手机号资产关联」时,后台 SHALL 通过 `asset_identifier` 和 `phone` 路由参数传递本次提交的新资产标识与错误响应手机号。创建换货 MUST 使用提交时选中的新卡 ICCID 或设备虚拟号;确认完成 MUST 使用换货单的新资产标识,不得带入旧资产。手机号缺失时 MUST 不从 `associated_phones` 回退生成解绑入口。
#### Scenario: 创建换货选择新资产后被拒
- **WHEN** 创建请求因新资产已有手机号关联返回 1202,用户选择跳转
- **THEN** 路由 MUST 携带选中新资产的 `asset_identifier` 与对应 `phone`
- **AND** 新旧资产同时存在手机号关联时 MUST NOT 使用旧资产标识或旧手机号
- **AND** 长 ICCID MUST 保持字符串,不转为数值
#### Scenario: 确认完成失败后跳转
- **WHEN** 确认完成返回 1202,用户选择跳转
- **THEN** 路由 MUST 携带该换货单的 `new_asset_identifier` 和错误响应手机号
- **AND** 参数不完整时 MUST 不猜测缺失值或自动执行解绑

View File

@@ -0,0 +1,36 @@
## ADDED Requirements
### Requirement: 后台订单在线支付摘要
后台订单公共类型 SHALL 接收 `third_party_trade_no`、`payment_channel`、`payment_merchant_name` 三个字符串字段;订单列表和详情 MUST 分别展示交易流水号、支付渠道和收款商户,不自行推断或补造后端未提供的值。
#### Scenario: 查看个人客户已支付在线订单
- **WHEN** 后台订单列表或详情收到个人客户微信/支付宝已支付订单的支付摘要
- **THEN** 页面 MUST 展示后端返回的三个字段
- **AND** `wechat`、`wechat_v2`、`fuiou` MUST 分别展示为微信直连 v3、微信直连 v2、富友
- **AND** 未知非空渠道 MUST 保留原值,不错误映射成其他渠道
- **AND** 已退款订单返回的原支付信息 MUST 继续展示
#### Scenario: 查看无在线支付摘要的订单
- **WHEN** 代理、钱包、线下或未支付订单的三个字段为空串
- **THEN** 页面 MUST 统一展示 `-`,不得显示 `undefined` 或虚构渠道/商户
- **AND** 列表和创建响应类型 MUST NOT 要求存在详情专有的 `payments`
### Requirement: 后台订单详情支付记录
后台订单详情 SHALL 使用独立于列表/创建响应的详情类型,接收并展示 `payments` 数组。支付单状态 MUST 使用独立映射 `0 待支付 / 1 已支付 / 2 已失败 / 3 已退款`,不得复用订单支付状态枚举。
#### Scenario: 展示多个支付尝试
- **WHEN** `GET /api/admin/orders/{id}` 返回多条支付记录
- **THEN** 页面 MUST 按后端返回的创建时间倒序展示,不删除待支付或失败记录
- **AND** MUST 展示支付单号、支付方式、渠道、商户、交易流水号、金额、状态、创建/支付/过期时间
- **AND** 金额 MUST 从分转换为元,`paid_at`、`expire_at` 的 null 值 MUST 展示 `-`
#### Scenario: 无支付记录
- **WHEN** 订单详情返回 `payments=[]`
- **THEN** 页面 MUST 显示支付记录空态,不报错或生成占位支付单
- **AND** 页面 MUST NOT 为加载支付记录调用 C 端接口

View File

@@ -0,0 +1,41 @@
## ADDED Requirements
### Requirement: 预警规则不依赖已删除额度字段
后台预警规则 SHALL 按本批次响应字段展示规则,响应类型、列表、详情和列选项 MUST NOT 依赖 `real_data_mb`;套餐商品接口和套餐选项的同名额度字段 MUST 保留。
#### Scenario: 规则响应不含额度
- **WHEN** 后台加载规则列表或详情且后端不再返回 `real_data_mb`
- **THEN** 页面 MUST 不展示规则的套餐流量额度列及详情字段
- **AND** MUST 正常展示套餐、阈值百分比、启用状态、备注和更新时间
- **AND** MUST NOT 因删除字段显示 `undefined` 或产生类型错误
#### Scenario: 套餐商品额度保留
- **WHEN** 规则表单从 `/api/admin/packages` 加载套餐候选
- **THEN** 套餐类型及选项中 `real_data_mb` 的原用途 MUST 保留
- **AND** 原规则创建/修改参数与阈值百分比校验 MUST 不变
### Requirement: 预警记录展示主套餐与加油包流量快照
后台预警列表和详情 SHALL 接收并展示后端 `threshold_mb`、`used_mb`、`limit_mb`,三者单位为 MB;阈值流量 MUST 使用触发时快照,不以当前套餐额度重新计算,已用和总量说明 MUST 标注包含加油包。
#### Scenario: 展示预警流量
- **WHEN** 预警列表或详情返回三项 MB 数值
- **THEN** 页面 MUST 展示「阈值流量(MB)」「已用流量(MB,含加油包)」「总流量(MB,含加油包)」或同等明确标签
- **AND** MUST 以两位小数展示,不混用规则百分比或 GB 数值
- **AND** MUST NOT 使用当前套餐商品或前端计算覆盖 `threshold_mb`
#### Scenario: 零与缺失值
- **WHEN** 流量值为 0、null 或缺失
- **THEN** 0 MUST 展示 `0.00`,null/缺失 MUST 展示 `-`
- **AND** MUST NOT 把 0 显示为缺失或将缺失值当作 0
#### Scenario: 导出仍由后端生成
- **WHEN** 用户创建预警导出任务或下载历史文件
- **THEN** 前端 MUST 复用原导出任务流程,不新增前端列模板或重写历史文件
- **AND** 本批次验收 MUST 检查新任务最后一列阈值流量及历史任务原文件不变

View File

@@ -0,0 +1,34 @@
## ADDED Requirements
### Requirement: 按换货新资产与手机号预填查询并勾选
手机号资产关联页面 SHALL 读取路由 `asset_identifier` 和 `phone`,预填筛选并从 `page=1,page_size=20` 请求列表。用户具备原批量解绑权限时,页面 MUST 默认勾选同时匹配资产标识、手机号且 `status=1` 的当前页记录,旧资产、其他手机号和已失效记录不得勾选。
#### Scenario: 从换货冲突入口进入
- **WHEN** 路由携带新资产和手机号参数
- **THEN** 页面 MUST 使用两项参数调用 `GET /api/admin/phone-asset-associations`
- **AND** 数据渲染后 MUST 实际勾选匹配有效记录,使已有批量解绑按钮可用
- **AND** MUST 保留解除原因必填与二次确认,不自动发送解绑请求
#### Scenario: 缓存页面再次接收另一资产
- **WHEN** 关联页面已存在缓存或同一路径查询参数改变
- **THEN** 页面 MUST 重置分页、筛选和旧勾选并重新查询新的两项条件
- **AND** 过期请求 MUST NOT 覆盖最新数据或选中新目标以外的行
#### Scenario: 参数缺失、手动筛选或解绑后刷新
- **WHEN** 两项参数不完整、用户修改筛选/翻页、手工取消选择或完成批量解绑
- **THEN** 页面 MUST NOT 将无关记录全选或恢复旧勾选
- **AND** 无批量解绑权限时 MUST NOT 显示可执行的批量解绑入口
### Requirement: 批量解绑逐项结果使用中文
批量解绑结果表 SHALL 将 `success=true` 展示为「解绑成功」,`success=false` 展示为「解绑失败」,保留中文汇总、解除关系数及后端失败原因,不显示原始布尔值。
#### Scenario: 显示成功或失败结果
- **WHEN** 后端返回批量解绑逐项结果
- **THEN** 结果列 MUST 使用中文成功/失败标签,不显示 `true` 或 `false`
- **AND** 失败原因、统计值及原结果布尔类型 MUST 保持原后端契约

View File

@@ -0,0 +1,36 @@
## ADDED Requirements
### Requirement: 退款审批提交失败状态与后台重提
退款后台 SHALL 识别业务状态 `7` 为「审批提交失败」终态,列表与详情 MUST 支持该状态展示和筛选。有原重提权限的用户 SHALL 使用原退款重提表单重新发起,不得恢复失败单的原审批。
#### Scenario: 显式提交失败
- **WHEN** 退款记录 `status=7`
- **THEN** 列表和详情 MUST 展示失败标签,状态筛选 MUST 允许值 7
- **AND** MUST 隐藏恢复及补发审批,不因陈旧 `approval_recoverable=true` 重新显示
- **AND** 有重提权限时 MUST 通过 `POST /api/admin/refunds/{id}/resubmit` 重新发起
- **AND** 成功后 MUST 刷新记录,不复用旧审批实例
#### Scenario: 不混淆原路退款失败
- **WHEN** 退款记录 `status=6`
- **THEN** 页面 MUST 继续按原「原路退款失败」含义及 `anomaly_flag` 限制处理
- **AND** MUST NOT 将该状态改成审批提交失败或放宽其原有异常限制
#### Scenario: 结果未知保留恢复资格
- **WHEN** 退款提交结果未知,业务状态不是 7,后端允许恢复且用户有原权限
- **THEN** 页面 MUST 保留恢复审批入口
- **AND** MUST NOT 直接把未知结果改成终态或创建重复申请
### Requirement: 退款企微结束后使用后台重新发起
后台退款页面 SHALL 对企微拒绝/撤销/删除后返回的 `status=3` 按「已拒绝」处理,允许符合原权限和规则的后台重提。页面 MUST NOT 引导用户在企微重新提交作为后台退款重提方式。
#### Scenario: 已拒绝退款重新发起
- **WHEN** 用户查看状态 3 的退款,且具备原重提权限
- **THEN** 页面 MUST 保留后台重新发起入口并调用原 `resubmit` 接口
- **AND** 若存在「在企微重新提交」文案,MUST 移除或改为后台重新发起指引
- **AND** 换货资格 MUST 仍由换货接口判断,不新增退款状态前置拦截

View File

@@ -0,0 +1,19 @@
## ADDED Requirements
### Requirement: 业务员批量换绑使用平台登录手机号表头
后台业务员批量换绑页面 SHALL 将说明及已有前端内置模板(如有)统一为固定表头 `店铺编码,操作类型,平台登录账号,备注`,说明「平台登录账号」仅填写平台用户登录手机号。请求路径、结构、逐行结果和已有任务信息 MUST 保持不变。
#### Scenario: 换绑说明和清空规则
- **WHEN** 用户查看导入说明或下载已有前端模板
- **THEN** 表头 MUST 使用「平台登录账号」,不得保留「业务员登录账号」
- **AND** MUST 说明换绑时填写平台用户登录手机号而非用户名,清空时该列留空
- **AND** MUST NOT 自动兼容/转换旧表头或把用户名转换为手机号
#### Scenario: 展示逐行失败
- **WHEN** 后端返回表头错误或行级格式不对、手机号不存在、非平台用户、账号禁用、多账号匹配等原因
- **THEN** 页面 MUST 原样展示后端原因
- **AND** 混合结果 MUST 保留成功行与失败行,不因部分失败改为前端整批拒绝
- **AND** 接口 MUST 继续使用 `POST /api/admin/shops/business-owner-imports`

View File

@@ -0,0 +1,89 @@
## 1. 实施前核对
- [x] 1.1 用户于 2026-10-13 批准实施,仅后台,不修改 `/api/c/v1`。
- [x] 1.2 按说明落实账号独立改密、核销提交状态、预警字段和错误响应,不依赖最新 OpenAPI。
- [x] 1.3 按已确认密码规则准备长度、字符类别、非法字符及旧密码边界用例。
- [x] 1.4 核对旧提案与代码,保留权限、核销抽屉、店铺范围、原换货流程及用户改动。
## 2. 订单在线支付信息(M3)
- [x] 2.1 补订单公共摘要字段、独立支付单状态与详情类型,列表/创建不要求 `payments`。
- [x] 2.2 列表和详情展示三项支付摘要、渠道映射、未知值及空值。
- [x] 2.3 详情支付表展示字段、金额、独立状态及空时间,保留失败记录和后端顺序。
## 3. 审批提交失败终态(M8、M14)
- [x] 3.1 核销状态 4、筛选/标签、关联申请和真实提交状态;支持原表单重提,终态隐藏恢复。
- [x] 3.2 退款状态 7、筛选/标签和原 resubmit,终态禁止恢复/补发,状态 6 异常限制保留。
- [x] 3.3 后台代理注册状态 3、筛选/标签和重新扫码指引,终态隐藏恢复,不改 C 端。
- [x] 3.4 线下充值状态 7、筛选/标签及操作判断,复用原创建权限/表单发起新单。
- [x] 3.5 提现状态 5、相关后台筛选/标签/详情、原重提入口及概览刷新,不本地模拟金额。
- [x] 3.6 资料资格状态 4、筛选/标签和原资料表单提交新版本。
- [x] 3.7 本地代码与逻辑测试复核终态/未知结果、只读操作和权限判断;财务事实随 7.3 联调。
## 4. 后台新密码规则(M1)
- [x] 4.1 按 2026-10-14 修正,新密码 8~12 位,允许半角特殊符号,四类至少三类,拒绝空白/中文等字符,不 trim。
- [x] 4.2 本人改密新密码/确认限制及双语说明;旧密码仅必填,原成功行为保持;错误换行不重叠。
- [x] 4.3 账号及客户账号创建接入校验,可选修改空密码不发送,不新增入口。
- [x] 4.4 账号独立改密改为 `new_password`,其他字段不改名。
- [x] 4.5 店铺初始密码、企业创建/改密接入校验及 maxlength。
- [x] 4.6 兼容 `msg`/`message`,受影响密码操作检查非零业务码且不记录带密码的错误对象;其他密码与 C 端不改。
## 5. 换货手机号冲突反馈(M12)
- [x] 5.1 两入口共用 1202 提取/提示,兼容业务与 HTTP 错误和无号码降级。
- [x] 5.2 创建保留表单,完成失败重新读原单,用户解除后手动重试。
- [x] 5.3 按已有权限指引,不自动解绑、记录或持久化号码。
- [x] 5.4 非 1202 保持后端原因与原错误分类,不新增前置检查或重复默认提示。
## 6. 预警口径与导入说明(M16、M2、M23)
- [x] 6.1 删除规则额度引用,保留套餐商品/候选额度及规则参数。
- [x] 6.2 补三项 MB 快照、两位小数、0/空值与加油包说明,不重算历史阈值。
- [x] 6.3 新 CSV 表头及说明;下载从统一 UTF-8 BOM 文本生成,原 GBK 文件保留,逐行结果不变。
- [x] 6.4 IMEI 说明改必填,原 Excel 模板及上传/失败明细保持,不加格式或去重限制。
## 7. 回归与验收
- [x] 7.1 未发现引导企微重提的后台文案;本地测试确认状态 3 仍允许后台重提,真实流程随 7.3 联调。
- [ ] 7.2 检查订单个人在线已支付/已退款信息,未支付及代理/钱包/线下空字段,详情多个支付记录的顺序、金额、状态和空时间。
- [ ] 7.3 检查六类失败终态、状态筛选、恢复隐藏、重提入口;覆盖陈旧 recoverable=true、结果未知、无权限及刷新财务数据。
- [x] 7.4 本地规则与改密页检查长度、三类、非法字符、可选空密码及旧密码兼容;375px 错误文案不重叠,其他密码代码未改。
- [ ] 7.5 检查换货两入口 1202 有/无号码、无管理权限、用户取消、解除后重试和其他错误;确认日志不含号码、原完成状态不被误改。
- [x] 7.6 本地规则/详情页与数值测试确认规则无额度、套餐字段保留、三项 MB/0/空值及加油包文案。
- [ ] 7.7 检查 CSV 新/旧表头、用户名误填、清空行和混合成功失败;检查设备 IMEI 空白行、部分成功、全失败以及模板未改变。
- [ ] 7.8 新建订单/IoT 卡/设备/预警导出任务检查后端新增列,下载历史任务检查旧列仍在;不修改前端导出模板或历史文件。
- [x] 7.9 本地 63 项测试、受影响文件 lint、类型检查、生产构建、UTF-8、OpenSpec 严格校验通过;模拟页面检查通过,真实环境项单列。
- [x] 7.10 C 端页面/服务无差异,组件声明 SHA-256 与实施前一致;回写实际完成和待联调项。
- [ ] 7.11 完成真实测试环境联调及用户验收后归档,不以模拟页面替代后端验收。
7.2、7.3、7.5、7.7 的本地逻辑与部分模拟页面已覆盖;尚未验证真实支付、冻结/预占金额、解除后重试、导入结果与导出文件。复现方式及证据见 [实施记录](./implementation.md)。
## 8. 换货冲突关联管理快捷处理(用户追加)
- [x] 8.1 两个换货入口携带当前新资产标识和关联手机号跳转,提交时冻结目标,禁止旧资产回退。
- [x] 8.2 关联页预填两项筛选,默认 1 页/20 条,仅勾选匹配有效记录;缓存、参数变化、过期响应和手工筛选清除旧选择。
- [x] 8.3 复用原批量解绑权限、原因与二次确认,结果布尔值改中文成功/失败。
- [x] 8.4 66 项回归测试通过,本地完整跳转、实际勾选、手工取消及模拟批量结果验证通过;未操作真实资产。
- [x] 8.5 按用户修正区分共用 1202:`data=null` 只展示原始 `msg` 和「知道了」,仅带有效响应手机号才提供去解绑;不从历史数组回退。新增回归,全套 67 项通过。
## 9. 密码特殊符号与侧栏遮罩修正(2026-10-14)
- [x] 9.1 专用校验恢复四类至少三类,允许所有可打印 ASCII 标点,同步中英文提示、类型注释和回归测试。
- [x] 9.2 本人改密弹窗挂载到 body,修复左侧菜单未被遮罩覆盖,不调整全局顶栏/侧栏层级。
- [x] 9.3 全套 68 项自动测试、类型/lint/stylelint 检查通过;本地桌面和 375px 页面确认遮罩覆盖侧栏,含符号密码发出模拟改密请求,没有修改真实密码。
- [x] 9.4 按用户要求全量核对后台新密码入口,确认五个文件中的七个输入统一校验/说明/长度且不 trim;补源码契约回归,全套 69 项通过,记录覆盖范围,不修改其他密码或新增权限。
## 10. 用户追加:代理扫码注册密码(2026-10-14)
- [x] 10.1 仅将代理扫码注册页及原注册接口的密码校验纳入,保持其他 C 端范围排除,同步规范。
- [x] 10.2 表单和注册服务复用统一规则;输入上限 12,完整规则独立显示,强度反馈不误认空格/中文,不 trim 密码。
- [x] 10.3 添加有效/无效密码、原字段/路径/免 Token/短信不变的回归;全套 71 项测试与类型、lint、stylelint、格式、编码、规范和生产构建检查通过。
- [ ] 10.4 当前浏览器连接不可用,扫码页移动端视觉和真实后端注册联调待验收;未发送真实短信或注册申请。
## 11. 用户追加:注册错误提示与表头拖拽修复
- [x] 11.1 仅公开注册关闭公共消息,1050/1001 统一指定文案,其他错误按具体原因;失败保留表单,提交中阻止重复请求。
- [x] 11.2 公共列设置拖拽延后启动,校验真实且连接文档的 DOM;关闭/卸载/缓存停用销毁,列勾选和排序 model 保持。
- [x] 11.3 新增页面单次消息、HTTP/业务映射、表头生命周期回归,全套 78 项、类型、lint/stylelint、格式、编码、规范及生产构建通过;真实浏览器和后台验收仍待完成。

View File

@@ -0,0 +1,18 @@
# Change: 新建订单套餐作废任务支持下载 CSV 模板
## Why
运营创建订单套餐批量作废任务时,需要按系统要求准备订单号 CSV。当前创建抽屉只有文件上传入口,无法直接取得格式样例,容易因文件列格式不符而返工。
## What Changes
- 在新建订单套餐作废任务抽屉的 CSV 上传项旁提供“下载模板”入口。
- 下载仓库中已有的静态模板 `src/template/订单批量作废模板.csv`,保留其 `order_no` 表头,不增加模板生成接口。
- 不改变现有 CSV 上传校验、任务创建、权限或后端接口。
## Impact
- Affected specs: `order-package-invalidate-task`
- Affected code: `src/views/asset-management/task-management/order-package-invalidate-task/index.vue`
- Existing user-provided asset: `src/template/订单批量作废模板.csv`(只读取,不修改)
- Breaking changes: 无。

View File

@@ -0,0 +1,13 @@
## ADDED Requirements
### Requirement: Order Package Invalidation CSV Template Download
The admin frontend SHALL let users creating an order package invalidation task download the CSV template used by the task's CSV upload field.
#### Scenario: Download the static CSV template
- **GIVEN** 用户已打开新建订单套餐作废任务抽屉
- **WHEN** 用户点击 CSV 上传项旁的模板下载入口
- **THEN** 页面 MUST 下载静态文件 `订单批量作废模板.csv`
- **AND** 下载内容 MUST match `src/template/订单批量作废模板.csv`, including the `order_no` header
- **AND** 页面 MUST NOT make a template-generation API request

View File

@@ -0,0 +1,4 @@
## 1. Implementation
- [x] 1.1 在订单套餐作废任务创建抽屉中添加静态 CSV 模板下载入口。
- [x] 1.2 验证下载内容、文件名与现有模板一致,并运行相关前端检查。

View File

@@ -0,0 +1,11 @@
# Change: 补齐支付商户池新增响应字段展示
## Why
支付商户池接口新增启用成员数、当前命中商户和最近失败调查字段,前端类型及列表/详情尚未完整展示。
## What Changes
- 扩展商户池响应类型。
- 商户池列表和详情展示新增运行状态与最近失败字段。
- 保持现有代理充值新增参数在列表和详情中的展示。

View File

@@ -0,0 +1,10 @@
## ADDED Requirements
### Requirement: Payment Merchant Pool Runtime Fields
The merchant pool list and detail pages SHALL display enabled member count, total member count, current routed merchant, and the latest failure investigation fields returned by the backend.
#### Scenario: Display pool runtime information
- **WHEN** the pool list or detail response contains runtime fields
- **THEN** the frontend MUST display them without deriving values from stale member data

View File

@@ -0,0 +1,9 @@
## 1. Implementation
- [x] 1.1 扩展商户池类型。
- [x] 1.2 更新商户池列表和详情字段。
- [x] 1.3 校验代理充值列表/详情新增字段展示。
## 2. Verification
- [x] 2.1 运行类型检查、lint、构建和 OpenSpec 校验。

View File

@@ -15,6 +15,8 @@
"np": "vite build --mode production",
"nd": "vite build --mode development",
"serve": "vite preview",
"deploy:frontend": "node scripts/deploy-frontend.mjs --branch feature/gateway-rate-limit",
"deploy:frontend:branch": "node scripts/deploy-frontend.mjs --branch",
"lint": "eslint",
"fix": "eslint --fix",
"lint:prettier": "prettier --write \"**/*.{js,cjs,ts,json,tsx,css,less,scss,vue,html,md}\"",

158
scripts/deploy-frontend.mjs Normal file
View File

@@ -0,0 +1,158 @@
import { execFile } from 'node:child_process'
import { mkdtemp, rm } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { promisify } from 'node:util'
const execFileAsync = promisify(execFile)
export const REGISTRY = process.env.FRONTEND_REGISTRY ?? 'registry.boss160.cn'
export const IMAGE_NAME = process.env.FRONTEND_IMAGE ?? `${REGISTRY}/junhong/cmp-admin-web`
export const NODE_OPTIONS = process.env.FRONTEND_NODE_OPTIONS ?? '--max-old-space-size=1536'
const ZERO_SHA = '0'.repeat(40)
export function parseArguments(args) {
if (args.length === 1 && args[0] === '--pre-push') {
return { mode: 'pre-push' }
}
if (args[0] === '--branch' && args.length === 2 && args[1]) {
return { mode: 'branch', branch: args[1] }
}
if (args.length === 0) {
throw new Error('缺少参数:Hook 使用 --pre-push,手动构建使用 --branch <分支>')
}
throw new Error(`未知参数:${args.join(' ')}`)
}
export function parsePrePushLines(input) {
return input
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean)
.map((line) => {
const fields = line.split(/\s+/)
if (fields.length !== 4) {
throw new Error(`无法解析 pre-push 数据:${line}`)
}
const [localRef, localSha, remoteRef, remoteSha] = fields
return { localRef, localSha, remoteRef, remoteSha }
})
}
export function resolveImageTag(sha) {
if (!/^[0-9a-f]{40}$/i.test(sha)) {
throw new Error(`不是完整 commit SHA:${sha}`)
}
return sha.toLowerCase()
}
function branchFromRef(ref) {
if (!ref.startsWith('refs/heads/')) {
throw new Error(`只允许推送分支,收到:${ref}`)
}
const branch = ref.slice('refs/heads/'.length)
if (!/^[A-Za-z0-9._/-]+$/.test(branch) || branch.includes('..') || branch.startsWith('-')) {
throw new Error(`非法分支名:${branch}`)
}
return branch
}
async function run(command, args, options = {}) {
const display = [command, ...args].join(' ')
console.log(`$ ${display}`)
return execFileAsync(command, args, {
cwd: options.cwd,
env: options.env,
maxBuffer: 10 * 1024 * 1024
})
}
async function readStdin() {
const chunks = []
for await (const chunk of process.stdin) chunks.push(chunk)
return Buffer.concat(chunks).toString('utf8')
}
async function resolveBranchCommit(branch) {
branchFromRef(`refs/heads/${branch}`)
await run('git', [
'fetch',
'--quiet',
'origin',
`refs/heads/${branch}:refs/remotes/origin/${branch}`
])
const { stdout } = await run('git', ['rev-parse', `refs/remotes/origin/${branch}`])
return { branch, sha: resolveImageTag(stdout.trim()) }
}
async function buildAndPush({ branch, sha, repoRoot }) {
const imageTag = resolveImageTag(sha)
const tempDir = await mkdtemp(join(tmpdir(), 'one-pipe-frontend-'))
try {
await run('git', ['worktree', 'add', '--detach', tempDir, imageTag], { cwd: repoRoot })
await run(
'docker',
[
'buildx',
'build',
'--platform',
'linux/amd64',
'--build-arg',
'HTTP_PROXY=',
'--build-arg',
'HTTPS_PROXY=',
'--build-arg',
'ALL_PROXY=',
'--build-arg',
`NODE_OPTIONS=${NODE_OPTIONS}`,
'--tag',
`${IMAGE_NAME}:${imageTag}`,
'--push',
tempDir
],
{ cwd: repoRoot }
)
console.log(`镜像已推送:${IMAGE_NAME}:${imageTag}`)
console.log(`分支:${branch},提交:${imageTag}`)
} finally {
await run('git', ['worktree', 'remove', '--force', tempDir], { cwd: repoRoot }).catch(() => {})
await rm(tempDir, { recursive: true, force: true })
}
}
async function repoRoot() {
const { stdout } = await run('git', ['rev-parse', '--show-toplevel'])
return resolve(stdout.trim())
}
async function main() {
const options = parseArguments(process.argv.slice(2))
const root = await repoRoot()
if (options.mode === 'pre-push') {
const refs = parsePrePushLines(await readStdin())
for (const ref of refs) {
if (ref.remoteSha === ZERO_SHA || ref.localSha === ZERO_SHA) continue
const branch = branchFromRef(ref.remoteRef)
await buildAndPush({ branch, sha: ref.localSha, repoRoot: root })
}
return
}
const target = await resolveBranchCommit(options.branch)
await buildAndPush({ ...target, repoRoot: root })
console.log('手动构建完成。要触发 Gitea 自动部署,请将该分支对应提交推送到远程。')
}
if (process.argv[1] && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url))) {
main().catch((error) => {
console.error(`前端镜像部署失败:${error.message}`)
process.exitCode = 1
})
}

View File

@@ -0,0 +1,317 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
import * as vue from 'vue'
import { compileScript, parse } from '@vue/compiler-sfc'
function evaluate(source, imports) {
const compiled = ts.transpileModule(source, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
}).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', compiled)(
(name) => {
assert.ok(imports[name], `Unexpected runtime dependency: ${name}`)
return imports[name]
},
module,
module.exports
)
return module.exports
}
const basePath = 'src/views/asset-management/asset-information'
const { descriptor } = parse(readFileSync(`${basePath}/components/BasicInfoCard.vue`, 'utf8'))
const componentSource = compileScript(descriptor, {
id: 'binding-card-test',
inlineTemplate: true
}).content
const formatters = evaluate(readFileSync(`${basePath}/composables/useAssetFormatters.ts`, 'utf8'), {
'@/config/constants/carrierTypes': {
getCarrierTypeLabel: (code) => ({ CTCC: '中国电信', CMCC: '中国移动' })[code] || code
}
})
function createHostNode(tag, text = '') {
return {
tag,
text,
props: {},
children: [],
parentNode: null,
removeChild(child) {
const index = this.children.indexOf(child)
assert.notEqual(index, -1)
this.children.splice(index, 1)
child.parentNode = null
}
}
}
function mountBasicInfo(t, userType, permissions = []) {
const user = vue.reactive({ info: { id: userType, user_type: userType }, permissions })
const hasAuth = (permission) =>
Number(user.info.user_type) === 1 || user.permissions.includes(permission)
user.hasPermission = hasAuth
user.hasButton = hasAuth
const elements = Object.fromEntries(
[
'ElCard',
'ElDescriptions',
'ElDescriptionsItem',
'ElTag',
'ElTooltip',
'ElSwitch',
'ElDivider',
'ElButton',
'ElAlert',
'ElEmpty'
].map((name) => [
name,
vue.defineComponent({
name,
setup:
(_, { slots, attrs }) =>
() =>
vue.h(name, attrs, [slots.header?.(), slots.default?.()])
})
])
)
const component = evaluate(componentSource, {
vue,
'@vueuse/core': { useWindowSize: () => ({ width: vue.ref(1200) }) },
'element-plus': { ...elements, ElMessageBox: {}, ElMessage: {} },
'@element-plus/icons-vue': {
CopyDocument: vue.defineComponent(() => () => vue.h('copy-icon'))
},
'../composables/useAssetFormatters': formatters,
'@/composables/useAuth': { useAuth: () => ({ hasAuth }) },
'@/components/business/package-silence/SilenceRecordsDialog.vue': {
default: vue.defineComponent(() => () => null)
},
'@/store/modules/user': { useUserStore: () => user },
'@/config/constants': {
JULY_PERMISSIONS: { speedTier: { view: 'speed:view', update: 'speed:update' } }
},
'@/utils/business/format': { formatDateTime: (value) => String(value || '') },
'@/utils/business/packageSilence': evaluate(
readFileSync('src/utils/business/packageSilence.ts', 'utf8')
),
'@/utils/business/expiryEstimate': {
getExpiryEstimateText: () => '-',
getExpiryEstimateTooltip: () => '',
getExpiryEstimateClass: () => ''
},
'@/config/constants/audit': { AUDIT_PERMISSIONS: {} },
'@/utils/business/auditNavigation': { resolveAuditResourceTarget: () => null },
'@/components/business/audit/investigationController': { openAuditInvestigation: () => {} }
}).default
const renderer = vue.createRenderer({
createElement: (tag) => createHostNode(tag),
createText: (text) => createHostNode('#text', text),
createComment: (text) => createHostNode('#comment', text),
setText: (node, text) => {
node.text = text
},
setElementText: (node, text) => {
node.text = text
node.children = []
},
parentNode: (node) => node.parentNode,
nextSibling: (node) => {
const siblings = node.parentNode?.children || []
return siblings[siblings.indexOf(node) + 1] || null
},
patchProp: (node, key, _, value) => {
node.props[key] = value
},
insert: (node, parent, anchor) => {
node.parentNode?.removeChild(node)
const index = anchor ? parent.children.indexOf(anchor) : parent.children.length
assert.notEqual(index, -1, 'Vue tried to insert beside a node removed outside its renderer')
parent.children.splice(index, 0, node)
node.parentNode = parent
},
remove: (node) => node.parentNode?.removeChild(node)
})
const asset = vue.reactive({
asset_type: 'device',
asset_id: 101,
identifier: 'DEVICE-A',
cards: [
{
iccid: 'CARD-1',
msisdn: '13800000001',
carrier_name: '平台运营商账户',
carrier_type: 'CTCC',
slot_position: 1,
is_current: true,
network_status: 1
},
{
iccid: 'CARD-2',
msisdn: '13800000002',
carrier_name: '第二运营商账户',
carrier_type: 'CMCC',
slot_position: 2,
is_current: false,
network_status: 0
}
]
})
const root = createHostNode('root')
const app = renderer.createApp({
render: () => vue.h(component, { cardInfo: asset, deviceRealtime: null, pollingEnabled: false })
})
const directives = evaluate(readFileSync('src/directives/permission.ts', 'utf8'), {
'@/store/modules/user': { useUserStore: () => user }
})
directives.setupPermissionDirective(app)
app.directive('loading', {})
app.component(
'el-icon',
vue.defineComponent({
setup:
(_, { slots }) =>
() =>
vue.h('icon', slots.default?.())
})
)
app.mount(root)
t.after(() => app.unmount())
return { root, asset, user }
}
const textOf = (node) =>
node.tag === '#comment' ? '' : node.text + node.children.map(textOf).join('')
test('enterprise account hides polling and realname writes while authorized start/stop remain', async (t) => {
const { root, asset, user } = mountBasicInfo(t, 4)
user.permissions = [
'device_info:auto_polling',
'iot_info:auto_polling',
'iot_info:update_realname_status',
'bound_card:update_realname_status',
'iot_info:start',
'iot_info:stop'
]
await vue.nextTick()
assert.doesNotMatch(textOf(root), /自动轮询|更新实名状态/)
assert.equal(nodesWithClass(root, 'binding-card').length, 2)
asset.asset_type = 'card'
asset.network_status = 0
await vue.nextTick()
assert.match(textOf(root), /启用此卡/)
assert.doesNotMatch(textOf(root), /自动轮询|更新实名状态/)
asset.network_status = 1
await vue.nextTick()
assert.match(textOf(root), /停用此卡/)
})
const nodesWithClass = (node, className) => [
...(String(node.props.class || '')
.split(' ')
.includes(className)
? [node]
: []),
...node.children.flatMap((child) => nodesWithClass(child, className))
]
test('all account types render both binding cards; only the established carrier label rule differs', async (t) => {
for (const userType of [1, 2, 3, 4]) {
const { root } = mountBasicInfo(t, userType)
await vue.nextTick()
const cards = nodesWithClass(root, 'binding-card')
assert.equal(cards.length, 2)
assert.match(textOf(cards[0]), /CARD-1/)
assert.match(textOf(cards[1]), /CARD-2/)
assert.match(textOf(cards[0]), /13800000001/)
assert.match(textOf(cards[0]), userType < 3 ? /平台运营商账户/ : /中国电信/)
}
})
test('permission changes and current-card/status updates preserve card data without external DOM removal', async (t) => {
const { root, asset, user } = mountBasicInfo(t, 3, ['iot_info:stop'])
await vue.nextTick()
assert.match(textOf(nodesWithClass(root, 'binding-card-actions')[0]), /停用此卡/)
user.permissions = ['iot_info:start', 'bound_card:update_realname_status']
asset.cards[0].network_status = 0
asset.cards[0].is_current = false
asset.cards[1].is_current = true
await vue.nextTick()
const cards = nodesWithClass(root, 'binding-card')
assert.equal(cards.length, 2)
assert.match(textOf(cards[0]), /CARD-2/)
assert.match(textOf(cards[1]), /CARD-1/)
assert.match(textOf(nodesWithClass(cards[1], 'binding-card-actions')[0]), /启用此卡/)
assert.match(textOf(nodesWithClass(cards[1], 'binding-card-actions')[0]), /更新实名状态/)
assert.doesNotMatch(textOf(nodesWithClass(cards[1], 'binding-card-actions')[0]), /停用此卡/)
user.permissions = []
await vue.nextTick()
assert.equal(nodesWithClass(root, 'binding-card').length, 2)
for (const actions of nodesWithClass(root, 'binding-card-actions'))
assert.equal(textOf(actions).trim(), '')
})
test('missing network status renders unknown and exposes neither start nor stop', async (t) => {
const { root, asset } = mountBasicInfo(t, 3, ['iot_info:start', 'iot_info:stop'])
delete asset.cards[0].network_status
await vue.nextTick()
const card = nodesWithClass(root, 'binding-card')[0]
assert.match(textOf(card), /网络状态未知/)
assert.doesNotMatch(textOf(nodesWithClass(card, 'binding-card-actions')[0]), /启用此卡|停用此卡/)
})
test('read-only accounts render realtime start/stop transitions without losing binding-card nodes', async (t) => {
for (const userType of [2, 3, 4]) {
const { root, asset } = mountBasicInfo(t, userType)
asset.cards[0].network_status = 0
await vue.nextTick()
assert.equal(nodesWithClass(root, 'binding-card').length, 2)
assert.match(textOf(nodesWithClass(root, 'binding-card')[0]), /网络状态停机/)
asset.cards[0].network_status = 1
await vue.nextTick()
assert.match(textOf(nodesWithClass(root, 'binding-card')[0]), /网络状态正常/)
for (const actions of nodesWithClass(root, 'binding-card-actions')) {
assert.equal(textOf(actions).trim(), '')
}
}
})
test('current-first sorting does not mutate source cards; zero, one, and multiple bindings render stably', async (t) => {
const { root, asset } = mountBasicInfo(t, 2)
const originalOrder = asset.cards.map((card) => card.iccid)
asset.cards[0].is_current = false
asset.cards[1].is_current = true
await vue.nextTick()
assert.deepEqual(
asset.cards.map((card) => card.iccid),
originalOrder
)
assert.match(textOf(nodesWithClass(root, 'binding-card')[0]), /CARD-2/)
asset.cards = [asset.cards[1]]
await vue.nextTick()
assert.equal(nodesWithClass(root, 'binding-card').length, 1)
asset.cards = []
await vue.nextTick()
assert.equal(nodesWithClass(root, 'binding-card').length, 0)
})
test('device/card type switches and denied actions do not leave removed DOM anchors', async (t) => {
const { root, asset, user } = mountBasicInfo(t, 3)
asset.asset_type = 'card'
asset.iccid = 'CARD-1'
asset.network_status = 1
await vue.nextTick()
asset.network_status = 0
await vue.nextTick()
assert.equal(textOf(nodesWithClass(root, 'card-operations')[0]).trim(), '')
user.permissions = ['iot_info:start']
await vue.nextTick()
assert.match(textOf(nodesWithClass(root, 'card-operations')[0]), /启用此卡/)
asset.asset_type = 'device'
user.permissions = ['device_info:reboot']
await vue.nextTick()
assert.equal(nodesWithClass(root, 'binding-card').length, 2)
assert.match(textOf(nodesWithClass(root, 'device-operations')[0]), /重启设备/)
})

View File

@@ -0,0 +1,688 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
import * as vue from 'vue'
import { parse } from '@vue/compiler-sfc'
const sourcePath = 'src/views/asset-management/asset-information/composables/useAssetInfo.ts'
const compiledSource = ts.transpileModule(readFileSync(sourcePath, 'utf8'), {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
}).outputText
const response = (data) => ({ code: 0, data })
const deferred = () => {
let resolve, reject
const promise = new Promise((resolvePromise, rejectPromise) => {
resolve = resolvePromise
reject = rejectPromise
})
return { promise, resolve, reject }
}
const boundCards = () => [
{
card_id: 11,
iccid: 'CARD-1',
msisdn: '13800000001',
carrier_name: '运营商账户',
carrier_type: 'CTCC',
slot_position: 1,
is_current: true,
network_status: 1,
real_name_status: 1,
real_name_at: '2026-10-01T01:00:00Z',
realname_policy: 'before_order',
gateway_extend: 'old reason'
},
{
card_id: 12,
iccid: 'CARD-2',
msisdn: '13800000002',
carrier_name: '另一运营商账户',
carrier_type: 'CMCC',
slot_position: 2,
is_current: false,
network_status: 0,
real_name_status: 0,
real_name_at: null
}
]
const detail = (identifier = 'DEVICE-A', cards = boundCards()) => ({
asset_type: 'device',
asset_id: identifier === 'DEVICE-A' ? 101 : 202,
virtual_no: identifier,
bound_card_count: cards.length,
cards,
real_total_mb: 1024,
real_used_mb: 100
})
function harness(t, overrides = {}) {
const user = vue.reactive({ info: { id: 1, user_type: 1 }, isLogin: true })
const messages = []
const api = {
resolveAsset: async (identifier) => response(detail(identifier)),
getRealtimeStatus: async () => response(null),
getCurrentPackage: async () => response(null),
getAssetWallet: async () => response(null),
getAssetPackages: async () => response({ items: [], total: 0 }),
refreshAsset: async () => response(null),
...overrides
}
const imports = {
vue,
'element-plus': {
ElMessage: Object.fromEntries(
['error', 'success', 'warning'].map((type) => [
type,
(message) => messages.push({ type, message })
])
)
},
'@/api/modules': { AssetService: api },
'@/utils/business/apiRateLimit': { FrontendRateLimitError: class extends Error {} },
'@/store/modules/user': { useUserStore: () => user }
}
const module = { exports: {} }
new Function('require', 'module', 'exports', compiledSource)(
(name) => {
assert.ok(imports[name], `Unexpected runtime dependency: ${name}`)
return imports[name]
},
module,
module.exports
)
const scope = vue.effectScope()
const state = scope.run(() => module.exports.useAssetInfo())
t.after(() => scope.stop())
return { state, api, user, messages, scope }
}
test('partial realtime responses retain the complete resolved binding-card roster', async (t) => {
const { state } = harness(t, {
getRealtimeStatus: async () =>
response({
asset_type: 'device',
asset_id: 101,
cards: [{ iccid: 'CARD-1', network_status: 0 }]
})
})
await state.fetchAssetDetail('DEVICE-A')
assert.deepEqual(
state.cardInfo.value.cards.map((card) => card.iccid),
['CARD-1', 'CARD-2']
)
assert.equal(state.cardInfo.value.cards[0].network_status, 0)
assert.equal(state.cardInfo.value.cards[1].msisdn, '13800000002')
})
test('realtime fields cannot erase resolved card identity, carrier, slot, policy, or real-name time', async (t) => {
const { state } = harness(t, {
getRealtimeStatus: async () =>
response({
asset_type: 'device',
asset_id: 101,
cards: [
{
iccid: 'CARD-1',
card_id: 0,
msisdn: '',
carrier_name: '',
carrier_type: '',
slot_position: 0,
realname_policy: '',
real_name_at: 'untrusted realtime time',
network_status: 0,
real_name_status: 0,
is_current: false,
gateway_extend: ''
}
]
})
})
await state.fetchAssetDetail('DEVICE-A')
assert.deepEqual(state.cardInfo.value.cards[0], {
...boundCards()[0],
network_status: 0,
real_name_status: 0,
is_current: false,
gateway_extend: ''
})
})
test('empty or omitted realtime cards preserve the detail roster; detail reload can remove bindings', async (t) => {
const { state, api } = harness(t)
await state.fetchAssetDetail('DEVICE-A')
for (const cards of [[], undefined, null]) {
api.getRealtimeStatus = async () => response({ asset_type: 'device', asset_id: 101, cards })
await state.loadRealtimeStatus('DEVICE-A', 'device')
assert.equal(state.cardInfo.value.cards.length, 2)
}
api.resolveAsset = async () => response(detail('DEVICE-A', []))
await state.fetchAssetDetail('DEVICE-A')
assert.deepEqual(state.cardInfo.value.cards, [])
})
test('unknown realtime cards do not introduce bindings absent from the authorized detail response', async (t) => {
const { state } = harness(t, {
getRealtimeStatus: async () =>
response({ asset_type: 'device', asset_id: 101, cards: [{ iccid: 'UNRESOLVED-CARD' }] })
})
await state.fetchAssetDetail('DEVICE-A')
assert.deepEqual(
state.cardInfo.value.cards.map((card) => card.iccid),
['CARD-1', 'CARD-2']
)
})
test('realtime card order does not change the resolved roster; explicit nullable timestamps can clear', async (t) => {
const cards = boundCards()
cards[0].last_data_check_at = 'old timestamp'
const { state } = harness(t, {
resolveAsset: async () => response(detail('DEVICE-A', cards)),
getRealtimeStatus: async () =>
response({
asset_type: 'device',
asset_id: 101,
cards: [
{ iccid: 'CARD-2' },
{ iccid: 'CARD-1', last_data_check_at: null, real_name_status: null }
]
})
})
await state.fetchAssetDetail('DEVICE-A')
assert.deepEqual(
state.cardInfo.value.cards.map((card) => card.iccid),
['CARD-1', 'CARD-2']
)
assert.equal(state.cardInfo.value.cards[0].last_data_check_at, null)
assert.equal(state.cardInfo.value.cards[0].real_name_status, 1)
})
test('a late resolve response cannot replace a newer search', async (t) => {
const oldDetail = deferred()
const { state } = harness(t, {
resolveAsset: (identifier) =>
identifier === 'DEVICE-A' ? oldDetail.promise : Promise.resolve(response(detail(identifier)))
})
const oldSearch = state.fetchAssetDetail('DEVICE-A')
await state.fetchAssetDetail('DEVICE-B')
oldDetail.resolve(response(detail('DEVICE-A')))
await oldSearch
assert.equal(state.cardInfo.value.identifier, 'DEVICE-B')
})
test('late realtime responses cannot write old card data into a different asset', async (t) => {
const { state, api } = harness(t)
await state.fetchAssetDetail('DEVICE-A')
const oldRealtime = deferred()
api.getRealtimeStatus = () => oldRealtime.promise
const oldLoad = state.loadRealtimeStatus('DEVICE-A', 'device')
api.getRealtimeStatus = async () => response(null)
await state.fetchAssetDetail('DEVICE-B')
oldRealtime.resolve(
response({ asset_type: 'device', asset_id: 101, cards: [{ iccid: 'OLD-CARD' }] })
)
await oldLoad
assert.equal(state.cardInfo.value.identifier, 'DEVICE-B')
assert.deepEqual(
state.cardInfo.value.cards.map((card) => card.iccid),
['CARD-1', 'CARD-2']
)
})
test('the newest same-asset realtime request wins and stale completion cannot end its loading state', async (t) => {
const { state, api } = harness(t)
await state.fetchAssetDetail('DEVICE-A')
const older = deferred()
const newer = deferred()
api.getRealtimeStatus = () => older.promise
const oldLoad = state.loadRealtimeStatus('DEVICE-A', 'device')
api.getRealtimeStatus = () => newer.promise
const newLoad = state.loadRealtimeStatus('DEVICE-A', 'device')
older.resolve(
response({
asset_type: 'device',
asset_id: 101,
cards: [{ iccid: 'CARD-1', network_status: 0 }]
})
)
await oldLoad
assert.equal(state.realtimeLoading.value, true)
assert.equal(state.cardInfo.value.cards[0].network_status, 1)
newer.resolve(
response({
asset_type: 'device',
asset_id: 101,
cards: [{ iccid: 'CARD-1', network_status: 1 }]
})
)
await newLoad
assert.equal(state.realtimeLoading.value, false)
assert.equal(state.cardInfo.value.cards[0].network_status, 1)
})
test('realtime responses identifying a different asset are ignored', async (t) => {
const { state, api } = harness(t)
await state.fetchAssetDetail('DEVICE-A')
for (const identity of [
{ asset_type: 'device', asset_id: 202 },
{ asset_type: 'card', asset_id: 101 }
]) {
api.getRealtimeStatus = async () =>
response({ ...identity, cards: [{ iccid: 'CARD-1', network_status: 0 }] })
await state.loadRealtimeStatus('DEVICE-A', 'device')
assert.equal(state.cardInfo.value.cards[0].network_status, 1)
}
})
test('starting a new search clears previous device, package, wallet, and binding data immediately', async (t) => {
const { state, api } = harness(t)
await state.fetchAssetDetail('DEVICE-A')
state.deviceRealtime.value = { current_iccid: 'CARD-1' }
state.currentPackage.value = { package_name: 'old package' }
state.packageList.value = [{ id: 1 }]
state.walletInfo.value = { total_balance: 123 }
const newDetail = deferred()
api.resolveAsset = () => newDetail.promise
const nextSearch = state.fetchAssetDetail('DEVICE-B')
assert.equal(state.cardInfo.value, null)
assert.equal(state.deviceRealtime.value, null)
assert.equal(state.currentPackage.value, null)
assert.equal(state.walletInfo.value, null)
assert.deepEqual(state.packageList.value, [])
newDetail.resolve({ code: 403, msg: 'forbidden' })
await nextSearch
assert.equal(state.cardInfo.value, null)
})
test('changing account invalidates pending requests even when searching the same identifier', async (t) => {
const oldDetail = deferred()
const { state, user, api } = harness(t, { resolveAsset: () => oldDetail.promise })
const oldSearch = state.fetchAssetDetail('DEVICE-A')
user.info = { id: 2, user_type: 3 }
api.resolveAsset = async () => response(detail('DEVICE-A', [boundCards()[1]]))
await state.fetchAssetDetail('DEVICE-A')
oldDetail.resolve(response(detail('DEVICE-A')))
await oldSearch
assert.deepEqual(
state.cardInfo.value.cards.map((card) => card.iccid),
['CARD-2']
)
})
test('logout clears visible data and invalidates pending realtime responses', async (t) => {
const { state, user, api } = harness(t)
await state.fetchAssetDetail('DEVICE-A')
const pending = deferred()
api.getRealtimeStatus = () => pending.promise
const load = state.loadRealtimeStatus('DEVICE-A', 'device')
user.isLogin = false
assert.equal(state.cardInfo.value, null)
pending.resolve(response({ asset_type: 'device', asset_id: 101, cards: boundCards() }))
await load
assert.equal(state.cardInfo.value, null)
})
test('a late failure of an old search does not clear the current successful asset', async (t) => {
const oldDetail = deferred()
const { state } = harness(t, {
resolveAsset: (identifier) =>
identifier === 'DEVICE-A' ? oldDetail.promise : Promise.resolve(response(detail(identifier)))
})
const oldSearch = state.fetchAssetDetail('DEVICE-A')
await state.fetchAssetDetail('DEVICE-B')
oldDetail.reject(new Error('old request failed'))
await oldSearch
assert.equal(state.cardInfo.value?.identifier, 'DEVICE-B')
})
test('account types 1/2/3/4 retain the same resolved bindings despite sparse realtime fields', async (t) => {
for (const userType of [1, 2, 3, 4]) {
const { state, user } = harness(t, {
getRealtimeStatus: async () =>
response({
asset_type: 'device',
asset_id: 101,
cards: [{ iccid: 'CARD-1', carrier_name: '' }]
})
})
user.info = { id: userType, user_type: userType }
await state.fetchAssetDetail('DEVICE-A')
assert.deepEqual(state.cardInfo.value.cards, boundCards())
}
})
test('a current-card change clears the previous current flag even for a partial realtime list', async (t) => {
const { state } = harness(t, {
getRealtimeStatus: async () =>
response({
asset_type: 'device',
asset_id: 101,
cards: [{ iccid: 'CARD-2', is_current: true }]
})
})
await state.fetchAssetDetail('DEVICE-A')
assert.deepEqual(
state.cardInfo.value.cards.map((card) => card.is_current),
[false, true]
)
})
test('same-identifier re-search never takes a real-name timestamp from a previous search or realtime', async (t) => {
const { state, api } = harness(t)
await state.fetchAssetDetail('DEVICE-A')
api.resolveAsset = async () =>
response(detail('DEVICE-A', [{ ...boundCards()[0], real_name_at: null }]))
api.getRealtimeStatus = async () =>
response({
asset_type: 'device',
asset_id: 101,
cards: [{ iccid: 'CARD-1', real_name_at: 'stale time' }]
})
await state.fetchAssetDetail('DEVICE-A')
assert.equal(state.cardInfo.value.cards[0].real_name_at, null)
})
test('manual refresh resolves new binding relations and preserves the existing package page', async (t) => {
let resolveCalls = 0
const { state } = harness(t, {
resolveAsset: async () => response(detail('DEVICE-A', ++resolveCalls === 1 ? boundCards() : []))
})
await state.fetchAssetDetail('DEVICE-A')
state.packageList.value = [{ id: 88, children: [{ id: 89 }] }]
assert.equal(await state.refreshAsset('DEVICE-A', 'device'), true)
assert.equal(resolveCalls, 2)
assert.deepEqual(state.cardInfo.value.cards, [])
assert.deepEqual(state.packageList.value, [{ id: 88, children: [{ id: 89 }] }])
})
test('a pending refresh does not re-search or overwrite a newer asset', async (t) => {
const pending = deferred()
const calls = []
const { state } = harness(t, {
refreshAsset: () => pending.promise,
resolveAsset: async (identifier) => {
calls.push(identifier)
return response(detail(identifier))
}
})
await state.fetchAssetDetail('DEVICE-A')
const refresh = state.refreshAsset('DEVICE-A', 'device')
await state.fetchAssetDetail('DEVICE-B')
pending.resolve(response(null))
assert.equal(await refresh, false)
assert.equal(state.cardInfo.value.identifier, 'DEVICE-B')
assert.deepEqual(calls, ['DEVICE-A', 'DEVICE-B'])
})
test('late current-package, wallet, and package-list responses do not contaminate a new asset', async (t) => {
const { state, api } = harness(t)
await state.fetchAssetDetail('DEVICE-A')
const pending = { package: deferred(), wallet: deferred(), list: deferred() }
api.getCurrentPackage = () => pending.package.promise
api.getAssetWallet = () => pending.wallet.promise
api.getAssetPackages = () => pending.list.promise
const oldLoads = [
state.loadCurrentPackage('DEVICE-A'),
state.loadAssetWallet('DEVICE-A'),
state.loadPackageList('DEVICE-A')
]
api.getCurrentPackage = async () => response(null)
api.getAssetWallet = async () => response(null)
await state.fetchAssetDetail('DEVICE-B')
pending.package.resolve(response({ package_name: 'old package' }))
pending.wallet.resolve(response({ total_balance: 123 }))
pending.list.resolve(response({ items: [{ id: 1 }], total: 1 }))
const results = await Promise.all(oldLoads)
assert.equal(state.currentPackage.value, null)
assert.equal(state.walletInfo.value, null)
assert.deepEqual(state.packageList.value, [])
assert.equal(results[2], null)
})
test('a newer same-asset package page wins even if the older page returns last', async (t) => {
const { state, api } = harness(t)
await state.fetchAssetDetail('DEVICE-A')
const older = deferred()
api.getAssetPackages = () => older.promise
const firstPage = state.loadPackageList('DEVICE-A', 1)
api.getAssetPackages = async () =>
response({ items: [{ id: 2, children: [{ id: 3 }] }], total: 9, page: 2 })
await state.loadPackageList('DEVICE-A', 2)
older.resolve(response({ items: [{ id: 1 }], total: 1, page: 1 }))
assert.equal(await firstPage, null)
assert.deepEqual(state.packageList.value, [{ id: 2, children: [{ id: 3 }] }])
})
test('unmount invalidates outstanding resolve requests', async (t) => {
const pending = deferred()
const { state, scope } = harness(t, { resolveAsset: () => pending.promise })
const search = state.fetchAssetDetail('DEVICE-A')
scope.stop()
pending.resolve(response(detail('DEVICE-A')))
assert.equal(await search, null)
assert.equal(state.cardInfo.value, null)
})
test('failed realtime loading preserves resolved bindings and a sparse identified request can update status', async (t) => {
t.mock.method(console, 'error', () => {})
const { state, api } = harness(t, {
getRealtimeStatus: async () => {
throw new Error('realtime unavailable')
}
})
await state.fetchAssetDetail('DEVICE-A')
assert.deepEqual(state.cardInfo.value.cards, boundCards())
assert.equal(state.realtimeLoading.value, false)
api.getRealtimeStatus = async () => response({ cards: [{ iccid: 'CARD-1', network_status: 0 }] })
await state.loadRealtimeStatus('DEVICE-A', 'device')
assert.equal(state.cardInfo.value.cards[0].network_status, 0)
assert.equal(state.cardInfo.value.cards.length, 2)
})
test('updating user metadata without changing the account or data scope does not clear asset data', async (t) => {
const { state, user } = harness(t)
await state.fetchAssetDetail('DEVICE-A')
const asset = state.cardInfo.value
user.info = { ...user.info, username: 'updated display name' }
await vue.nextTick()
assert.equal(state.cardInfo.value, asset)
})
test('a disposed asset composable cannot restart loads after an operation finishes late', async (t) => {
let calls = 0
const { state, scope } = harness(t, {
resolveAsset: async () => {
calls += 1
return response(detail('DEVICE-A'))
}
})
scope.stop()
assert.equal(await state.fetchAssetDetail('DEVICE-A'), null)
assert.equal(calls, 0)
})
test('standalone card realtime status still updates while the resolved gateway IMEI remains authoritative', async (t) => {
const { state } = harness(t, {
resolveAsset: async () =>
response({
...detail('CARD-1', []),
asset_type: 'card',
iccid: 'CARD-1',
gateway_card_imei: 'resolved-imei'
}),
getRealtimeStatus: async () =>
response({
asset_type: 'card',
asset_id: 202,
network_status: 0,
real_name_status: 1,
gateway_card_imei: 'realtime-imei'
})
})
await state.fetchAssetDetail('CARD-1')
assert.equal(state.cardInfo.value.network_status, 0)
assert.equal(state.cardInfo.value.real_name_status, 1)
assert.equal(state.cardInfo.value.gateway_card_imei, 'resolved-imei')
})
function pageHandlers(state) {
const { descriptor } = parse(
readFileSync('src/views/asset-management/asset-information/index.vue', 'utf8')
)
const source = ts.createSourceFile(
'asset-information.ts',
descriptor.scriptSetup.content,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TS
)
const wanted = new Set([
'handleSearch',
'handleRefresh',
'showUpdateRealnameStatusDialog',
'handleUpdateRealnameStatusSuccess',
'handleUpdateBindingCardRealnameStatus',
'handleBindingCardRealnameStatusSuccess'
])
const declarations = []
function visit(node) {
if (ts.isVariableDeclaration(node) && wanted.has(node.name.getText(source)))
declarations.push(node.getText(source))
ts.forEachChild(node, visit)
}
visit(source)
assert.equal(declarations.length, wanted.size)
const bindings = {
useUserStore: () => ({ info: { user_type: 1 } }),
canEditRestrictedAsset: (type) => [1, 2, 3].includes(Number(type)),
cardInfo: state.cardInfo,
fetchAssetDetail: state.fetchAssetDetail,
loadPackageList: state.loadPackageList,
refreshAsset: state.refreshAsset,
refreshSubmitting: vue.ref(false),
refreshDisabled: vue.ref(false),
updateRateLimitNow: () => {},
assetSearchCardRef: vue.ref(null),
startFailureMessage: vue.ref(''),
packagePagination: vue.ref({ page: 1, total: 0, pageSize: 5, status: undefined }),
walletTransactionSearchToken: vue.ref(0),
pollingEnabled: vue.ref(false),
updateRealnameStatusDialogVisible: vue.ref(false),
bindingCardRealnameStatusDialogVisible: vue.ref(false),
bindingCardRealnameStatusIccid: vue.ref(''),
bindingCardRealnameStatusValue: vue.ref(0),
nextTick: vue.nextTick
}
const compiled = ts.transpileModule(
`let searchRequestId = 0, pollingInitializing = false, realnameStatusAsset = null, bindingCardRealnameStatusAsset = null\n${declarations.map((declaration) => `const ${declaration}`).join('\n')}\nreturn { ${[...wanted].join(', ')} }`,
{ compilerOptions: { target: ts.ScriptTarget.ES2022 } }
).outputText
return {
...new Function(...Object.keys(bindings), compiled)(...Object.values(bindings)),
...bindings
}
}
test('page search resolves a device only once and uses its canonical identifier for related requests', async (t) => {
const calls = []
const { state } = harness(t, {
resolveAsset: async (identifier) => {
calls.push(['resolve', identifier])
return response(detail('DEVICE-A'))
},
getRealtimeStatus: async (identifier) => {
calls.push(['realtime', identifier])
return response(null)
},
getAssetPackages: async (identifier) => {
calls.push(['packages', identifier])
return response({ items: [], total: 0 })
}
})
await pageHandlers(state).handleSearch({ identifier: 'IMEI-ALIAS' })
assert.deepEqual(calls, [
['resolve', 'IMEI-ALIAS'],
['realtime', 'DEVICE-A'],
['packages', 'DEVICE-A']
])
})
test('active gateway synchronization is called only by the sync button, never by searches or data reloads', async (t) => {
const syncCalls = []
const { state } = harness(t, {
refreshAsset: async (identifier) => {
syncCalls.push(identifier)
return response(null)
}
})
const page = pageHandlers(state)
await page.handleRefresh()
await page.handleSearch({ identifier: 'DEVICE-A' })
await page.handleSearch({ identifier: 'DEVICE-A' })
await state.loadRealtimeStatus('DEVICE-A', 'device')
page.handleUpdateBindingCardRealnameStatus({ card: boundCards()[0] })
await page.handleBindingCardRealnameStatusSuccess()
page.showUpdateRealnameStatusDialog()
await page.handleUpdateRealnameStatusSuccess()
assert.deepEqual(syncCalls, [])
await page.handleRefresh()
assert.deepEqual(syncCalls, ['DEVICE-A'])
await state.fetchAssetDetail('DEVICE-A')
page.refreshDisabled.value = true
await page.handleRefresh()
assert.deepEqual(syncCalls, ['DEVICE-A'])
})
test('a stale page search cannot start additional loads or reset the newer search pagination', async (t) => {
const pending = deferred()
const { state } = harness(t, {
resolveAsset: (identifier) =>
identifier === 'DEVICE-A' ? pending.promise : Promise.resolve(response(detail(identifier))),
getAssetPackages: async () => response({ items: [{ id: 2 }], total: 22 })
})
const page = pageHandlers(state)
const older = page.handleSearch({ identifier: 'DEVICE-A' })
await page.handleSearch({ identifier: 'DEVICE-B' })
pending.resolve(response(detail('DEVICE-A')))
await older
assert.equal(page.packagePagination.value.total, 22)
assert.equal(page.walletTransactionSearchToken.value, 1)
assert.equal(state.cardInfo.value.identifier, 'DEVICE-B')
})
test('successful bound-card real-name update reloads detail fields but an old dialog cannot reload a new asset', async (t) => {
let resolveCalls = 0
const { state, api } = harness(t, {
resolveAsset: async (identifier) => {
resolveCalls += 1
return response(detail(identifier))
}
})
await state.fetchAssetDetail('DEVICE-A')
const page = pageHandlers(state)
page.handleUpdateBindingCardRealnameStatus({ card: boundCards()[0] })
api.resolveAsset = async () => {
resolveCalls += 1
return response(
detail('DEVICE-A', [{ ...boundCards()[0], real_name_status: 0, real_name_at: null }])
)
}
await page.handleBindingCardRealnameStatusSuccess()
assert.equal(state.cardInfo.value.cards[0].real_name_status, 0)
assert.equal(state.cardInfo.value.cards[0].real_name_at, null)
assert.equal(resolveCalls, 2)
api.resolveAsset = async (identifier) => {
resolveCalls += 1
return response(detail(identifier))
}
page.handleUpdateBindingCardRealnameStatus({ card: boundCards()[0] })
await state.fetchAssetDetail('DEVICE-B')
await page.handleBindingCardRealnameStatusSuccess()
assert.equal(state.cardInfo.value.identifier, 'DEVICE-B')
assert.equal(resolveCalls, 3)
})

View File

@@ -0,0 +1,341 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
import { parse, compileScript, compileTemplate } from '@vue/compiler-sfc'
import * as vue from 'vue'
const read = (path) => readFileSync(path, 'utf8')
function evaluate(source, imports = {}) {
const code = ts.transpileModule(source, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
}).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', code)(
(name) => {
if (name.endsWith('.vue')) return { default: {} }
assert.ok(imports[name], `Unexpected import ${name}`)
return imports[name]
},
module,
module.exports
)
return module.exports
}
const format = evaluate(read('src/utils/business/format.ts'))
const gateway = evaluate(read('src/utils/business/gateway.ts'), { './format': format })
const polling = evaluate(read('src/utils/business/pollingScheduler.ts'), { './gateway': gateway })
const response = (data) => ({ code: 0, data })
const deferred = () => {
let resolve, reject
const promise = new Promise((a, b) => {
resolve = a
reject = b
})
return { promise, resolve, reject }
}
const tick = async () => {
await vue.nextTick()
await Promise.resolve()
await vue.nextTick()
}
function serviceHarness(overrides = {}) {
const calls = []
const service = new Proxy(
{},
{
get:
(_, method) =>
async (...args) => {
calls.push({ method, args })
return overrides[method] ? overrides[method](...args) : response({ items: [], total: 0 })
}
}
)
const modules = {
'./packageManage': { PackageManageService: service },
'./packageSeries': { PackageSeriesService: service },
'./shop': { ShopService: service },
'./card': { CardService: service },
'./device': { DeviceService: service },
'./account': { AccountService: service },
'./packageSilence': { PackageSilenceService: service },
'@/utils/business/gateway': gateway
}
return { ...evaluate(read('src/api/modules/businessOptions.ts'), modules), calls }
}
test('entity search uses documented keyword/name fields and returns labels, never database IDs as labels', async () => {
const h = serviceHarness({
getPackages: () => response({ items: [{ id: 8, package_name: '实名套餐' }], total: 41 }),
getPackageSeries: () => response({ items: [{ id: 9, series_name: '流量系列' }], total: 1 }),
getShops: () => response({ items: [{ id: 10, shop_name: '一号代理' }], total: 1 }),
getAccounts: () =>
response({ items: [{ id: 11, username: '张三', shop_name: '一号代理' }], total: 1 }),
getStandaloneIotCards: () =>
response({ items: [{ id: 12, iccid: '89860001', virtual_no: 'V-01' }], total: 1 }),
getDevices: () =>
response({ items: [{ id: 13, virtual_no: 'D-01', device_name: '设备甲' }], total: 1 })
})
for (const [kind, method, field] of [
['package', 'getPackages', 'package_name'],
['series', 'getPackageSeries', 'series_name'],
['shop', 'getShops', 'shop_name'],
['account', 'getAccounts', 'username'],
['card', 'getStandaloneIotCards', 'keyword']
]) {
const result = await h.searchBusinessOptions(kind, ' 关键字 ', 2)
assert.ok(result.options.length)
assert.equal(typeof result.options[0].value, 'number')
assert.notEqual(result.options[0].label, String(result.options[0].value))
const call = h.calls.at(-1)
assert.equal(call.method, method)
assert.deepEqual(call.args[0], { page: 2, page_size: 20, [field]: '关键字' })
assert.equal(result.hasMore, kind === 'package')
}
const assets = await h.searchBusinessOptions('asset', '01')
assert.deepEqual(
assets.options.map((x) => x.value),
['89860001', 'D-01']
)
assert.match(assets.options[0].label, /V-01/)
assert.match(assets.options[1].label, /设备甲/)
})
test('package record selection uses real usage IDs with asset/package context and readable order labels', async () => {
const h = serviceHarness({
usages: () =>
response({
items: [
{
package_usage_id: 99,
package_name: '实名套餐',
asset_identifier: '8986',
order_no: 'ORD-01'
}
],
total: 1
})
})
const result = await h.searchBusinessOptions('usage', '', 1, {
asset_identifier: '8986',
package_id: 8
})
assert.deepEqual(h.calls[0].args[0], {
page: 1,
page_size: 20,
view: 'all',
asset_identifier: '8986',
package_id: 8
})
assert.deepEqual(result.options, [{ value: 99, label: '实名套餐 · 8986 · ORD-01' }])
await h.searchBusinessOptions('usage', '8987', 1, { asset_identifier: '8986' })
assert.equal(h.calls.at(-1).args[0].asset_identifier, '8987')
})
test('asset lookup keeps permitted card results when the device lookup fails and reports the partial failure', async () => {
const h = serviceHarness({
getStandaloneIotCards: () => response({ items: [{ id: 12, iccid: '89860001' }], total: 1 }),
getDevices: () => ({ code: 403, msg: '无设备查看权限' })
})
const result = await h.searchBusinessOptions('asset', '')
assert.equal(result.options[0].value, '89860001')
assert.match(result.warning, /设备.*无设备查看权限/)
})
test('policy selection resolves existing package/series names through detail endpoints and propagates business errors', async () => {
const h = serviceHarness({
getPackageDetail: () => response({ package_name: '已有套餐' }),
getPackageSeriesDetail: () => response({ series_name: '已有系列' }),
getShops: () => ({ code: 403, msg: '无数据权限' })
})
assert.deepEqual(await h.resolveBusinessOption('package', 8), { value: 8, label: '已有套餐' })
assert.deepEqual(await h.resolveBusinessOption('series', 9), { value: 9, label: '已有系列' })
await assert.rejects(h.searchBusinessOptions('shop', ''), /无数据权限/)
})
function componentHarness({ entity = 'shop', modelValue, search, resolve, allowed = true } = {}) {
const hooks = [],
calls = [],
events = []
const user = vue.reactive({ info: { id: 1, user_type: 2, shop_id: 1 }, isLogin: true })
const props = vue.reactive({ entity, modelValue, allowed, clearable: true })
const runtime = {
...vue,
onBeforeUnmount: (fn) => hooks.push(fn),
onDeactivated: (fn) => hooks.push(fn),
onActivated() {}
}
const { descriptor } = parse(read('src/components/business/BusinessEntitySelect.vue'))
const component = evaluate(compileScript(descriptor, { id: 'entity-select' }).content, {
vue: runtime,
'@/store/modules/user': { useUserStore: () => user },
'@/utils/business/gateway': gateway,
'@/utils/business/pollingScheduler': polling,
'@/api/modules/businessOptions': {
BUSINESS_OPTION_LABELS: {
shop: '店铺',
package: '套餐',
series: '系列',
asset: '资产',
account: '操作人'
},
searchBusinessOptions: async (...args) => {
calls.push(args)
return search ? search(...args) : { options: [], hasMore: false }
},
resolveBusinessOption: resolve || (async (_, value) => ({ value, label: '已有名称' }))
}
}).default
const scope = vue.effectScope()
const state = scope.run(() =>
component.setup(props, {
expose() {},
emit: (event, value) => {
events.push([event, value])
props.modelValue = value
}
})
)
return {
state,
props,
user,
calls,
events,
dispose: () => {
hooks.forEach((fn) => fn())
scope.stop()
}
}
}
test('rapid keywords ignore late responses, selection retains its label through later searches and clear emits no ID', async () => {
const old = deferred()
const h = componentHarness({
search: (_, keyword) =>
keyword === 'old'
? old.promise
: {
options: [
{ value: keyword === 'new' ? 2 : 3, label: keyword === 'new' ? '新店铺' : '其他店铺' }
],
hasMore: false
}
})
const pending = h.state.search('old')
await h.state.search('new')
old.resolve({ options: [{ value: 1, label: '旧店铺' }], hasMore: false })
await pending
assert.deepEqual(h.state.options.value, [{ value: 2, label: '新店铺' }])
h.state.selection.value = 2
await h.state.search('other')
assert.deepEqual(
h.state.options.value.map((x) => x.label),
['新店铺', '其他店铺']
)
assert.deepEqual(h.events[0], ['update:modelValue', 2])
h.state.selection.value = undefined
assert.deepEqual(
h.state.options.value.map((x) => x.label),
['其他店铺']
)
h.dispose()
})
test('load more appends options and request failures are retryable rather than fabricated empty results', async () => {
let fail = true
const h = componentHarness({
search: (_, keyword, page) => {
if (keyword === 'fail' && fail) throw new Error('网络失败')
return { options: [{ value: page, label: `店铺${page}` }], hasMore: page < 2 }
}
})
await h.state.search('')
assert.equal(h.state.hasMore.value, true)
await h.state.load(2)
assert.deepEqual(
h.state.options.value.map((x) => x.value),
[1, 2]
)
assert.equal(h.state.hasMore.value, false)
await h.state.search('fail')
assert.equal(h.state.error.value, '网络失败')
fail = false
await h.state.load(1)
assert.equal(h.state.error.value, '')
assert.equal(h.calls.at(-1)[1], 'fail')
h.dispose()
})
test('permission/account/context changes and unmount discard in-flight results without new unauthorized requests', async () => {
for (const action of ['permission', 'account', 'context', 'unmount']) {
const pending = deferred(),
h = componentHarness({ search: () => pending.promise })
const loading = h.state.search('a')
if (action === 'permission') h.props.allowed = false
if (action === 'account') h.user.info.id = 2
if (action === 'context') h.props.context = { package_id: 8 }
if (action === 'unmount') h.dispose()
await tick()
pending.resolve({ options: [{ value: 8, label: '已失效数据' }], hasMore: true })
await loading
assert.deepEqual(h.state.options.value, [], action)
assert.equal(h.state.loading.value, false)
if (action === 'permission' || action === 'unmount') {
await h.state.search('b')
assert.equal(h.calls.length, 1)
}
if (action !== 'unmount') h.dispose()
}
})
test('existing multi-selection hydrates readable labels and system operator preserves numeric zero', async () => {
const h = componentHarness({
entity: 'package',
modelValue: [7, 8],
resolve: async (_, value) => ({ value, label: `套餐名${value}` })
})
await tick()
assert.deepEqual(
h.state.options.value.map((x) => x.label),
['套餐名7', '套餐名8']
)
h.props.modelValue = [8]
await tick()
assert.deepEqual(
h.state.options.value.map((x) => x.label),
['套餐名8']
)
h.dispose()
const account = componentHarness({ entity: 'account' })
account.props.includeSystem = true
account.state.selection.value = 0
assert.deepEqual(account.events.at(-1), ['update:modelValue', 0])
assert.deepEqual(account.state.options.value, [{ value: 0, label: '系统' }])
account.dispose()
})
test('all affected templates compile and raw-ID search controls are replaced throughout the shared pages', () => {
const files = [
'src/components/business/BusinessEntitySelect.vue',
'src/components/core/forms/art-search-bar/widget/art-search-business-select/index.vue',
'src/components/core/forms/art-search-bar/index.vue',
'src/components/business/package-silence/SilenceManagement.vue',
'src/components/business/package-silence/SilencePolicyDialog.vue',
'src/views/order-management/order-list/index.vue',
'src/views/finance/refund/index.vue',
'src/views/polling-management/priority-queue/index.vue',
'src/views/polling-management/polling-pauses/index.vue',
'src/views/asset-management/phone-asset-association/index.vue',
'src/views/asset-management/record-management/asset-assign/index.vue'
]
for (const file of files) {
const { descriptor, errors } = parse(read(file))
assert.deepEqual(errors, [], file)
assert.deepEqual(
compileTemplate({ source: descriptor.template.content, filename: file, id: file }).errors,
[],
file
)
}
const management = read(files[3])
assert.match(read(files[2]), /v-show="index < visibleItemCount"/)
for (const field of ['asset_identifier', 'package_id', 'shop_id', 'package_usage_id'])
assert.match(management, new RegExp(`entity\\('${field}'`))
assert.doesNotMatch(management, /请输入套餐 ID|number\('(?:package_id|shop_id|package_usage_id)'/)
assert.doesNotMatch(read(files[4]), /label: `ID/)
assert.doesNotMatch(read(files[7]), /请输入卡ID/)
})

View File

@@ -0,0 +1,397 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
import * as vue from 'vue'
import { compileScript, parse } from '@vue/compiler-sfc'
function evaluate(source, imports = {}, globals = {}) {
const compiled = ts.transpileModule(source, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
}).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', ...Object.keys(globals), compiled)(
(name) => {
assert.ok(imports[name], `Unexpected dependency: ${name}`)
return imports[name]
},
module,
module.exports,
...Object.values(globals)
)
return module.exports
}
const read = (path) => readFileSync(path, 'utf8')
const carrierTypes = evaluate(read('src/types/api/carrier.ts'))
const carrierConfig = evaluate(read('src/config/constants/carrierTypes.ts'), {
'@/types/api': carrierTypes
})
const checkedColumns = evaluate(read('src/composables/useCheckedColumns.ts'), { vue })
const components = Object.fromEntries(
['index', 'detail'].map((name) => {
const { descriptor } = parse(read(`src/views/system/carrier-management/${name}.vue`))
return [
name,
{ descriptor, script: compileScript(descriptor, { id: `carrier-${name}` }).content }
]
})
)
test('carrier form grid top-aligns items so helper text cannot offset adjacent controls', () => {
const style = components.index.descriptor.styles.map((block) => block.content).join('\n')
assert.match(style, /\.carrier-form-grid\s*\{[^}]*align-items:\s*start\s*;/)
})
const carrier = (enabled) => ({
id: 7,
carrier_code: 'carrier-test',
carrier_name: '测试运营商',
carrier_type: 'CMCC',
realname_control_enabled: enabled,
status: 1,
created_at: '',
updated_at: ''
})
function harness(userType, responseCarrier = carrier(1)) {
const writes = []
const attempts = []
let list
const confirmations = []
const user = vue.reactive({ info: { user_type: userType }, permissions: [], buttons: [] })
const permission = evaluate(read('src/composables/usePermission.ts'), {
vue,
'@/store/modules/user': { useUserStore: () => user }
})
const service = {
getCarriers: async () => ({ code: 0, data: { items: [responseCarrier], total: 1 } }),
getCarrierDetail: async () => ({ code: 0, data: responseCarrier }),
createCarrier: async (data) => writes.push({ method: 'create', data: { ...data } }),
updateCarrier: async (id, data) => {
attempts.push({ id, data: { ...data } })
if (
list?.originalRealnameControlEnabled.value === 0 &&
data.realname_control_enabled === 1 &&
!data.realname_control_confirm
)
throw new Error('开启实名管控将停机 12 张卡,请确认后重试')
writes.push({ method: 'update', id, data: { ...data } })
return { code: 0, data: responseCarrier }
}
}
const runtimeVue = { ...vue, onMounted: () => {} }
const imports = {
vue: runtimeVue,
'vue-router': { useRouter: () => ({ push() {} }), useRoute: () => ({ params: { id: '7' } }) },
'@vueuse/core': { useWindowSize: () => ({ width: vue.ref(1200) }) },
'@/api/modules': { CarrierService: service },
'element-plus': {
ElMessage: { success() {}, warning() {}, error() {} },
ElMessageBox: {
confirm: async (...args) => {
confirmations.push(args)
return 'confirm'
}
},
ElTag: {},
ElSwitch: {},
ElButton: {}
},
'@/composables/useCheckedColumns': checkedColumns,
'@/composables/useAuth': { useAuth: () => ({ hasAuth: () => true }) },
'@/composables/usePermission': permission,
'@/router/routesAlias': {
RoutesAlias: { CarrierDetail: '/carrier', CarrierManagement: '/carrier' }
},
'@/utils/codeGenerator': { generateCarrierCode: () => 'carrier-test' },
'@/utils/business/format': { formatDateTime: (value) => value },
'@/config/constants': {
...carrierConfig,
CommonStatus: { ENABLED: 1, DISABLED: 0 },
getStatusText: (value) => String(value)
}
}
const setup = (name) =>
evaluate(components[name].script, imports, runtimeVue).default.setup({}, { expose() {} })
list = setup('index')
return {
list,
attempts,
detail: setup('detail'),
writes,
confirmations,
messageBox: imports['element-plus'].ElMessageBox,
service
}
}
const validForm = {
validate: async (callback) => callback(true),
resetFields() {},
clearValidate() {}
}
for (const userType of [1, 2, '1', '2', 3, 4, 0, undefined]) {
const allowed = [1, 2].includes(Number(userType))
test(`user_type=${userType}: list visibility, detail visibility and create/update field access`, async () => {
const { list, detail, writes } = harness(userType)
assert.equal(list.canConfigureRealnameControl.value, allowed)
assert.equal(detail.canConfigureRealnameControl.value, allowed)
assert.equal(
list.columnOptions.some((column) => column.prop === 'realname_control_enabled'),
allowed
)
assert.equal(
list.columns.value.some((column) => column.prop === 'realname_control_enabled'),
allowed
)
assert.equal(
list.columnChecks.value.some((column) => column.prop === 'realname_control_enabled'),
allowed
)
await list.getTableData()
await detail.loadCarrier()
assert.equal(list.carrierList.value[0].realname_control_enabled, 1)
assert.equal(detail.carrier.value.realname_control_enabled, 1)
list.showDialog('add')
assert.equal(list.form.realname_control_enabled, 0)
list.form.realname_control_enabled = 1
await list.handleSubmit(validForm)
list.showDialog('edit', carrier(1))
assert.equal(list.form.realname_control_enabled, 1)
list.form.realname_control_enabled = 0
await list.handleSubmit(validForm)
assert.equal(writes.length, 2)
assert.equal(writes[0].method, 'create')
assert.equal(writes[1].method, 'update')
assert.equal(writes[1].id, 7)
for (const [index, write] of writes.entries()) {
assert.equal(Object.hasOwn(write.data, 'realname_control_enabled'), allowed)
if (allowed) assert.equal(write.data.realname_control_enabled, index === 0 ? 1 : 0)
}
})
}
test('labels preserve numeric zero and handle missing fields without inventing a state', () => {
const { getCarrierRealnameControlLabel: label } = carrierConfig
assert.equal(label(0), '不管控')
assert.equal(label(1), '管控')
assert.equal(label(undefined), '-')
assert.equal(label(null), '-')
const { list } = harness(1)
const column = list.columns.value.find((item) => item.prop === 'realname_control_enabled')
assert.equal(column.formatter(carrier(0)), '不管控')
assert.equal(column.formatter(carrier(1)), '管控')
assert.equal(column.formatter(carrier(undefined)), '-')
})
test('editing then creating resets control state; default creation sends numeric zero', async () => {
const { list, writes } = harness(2)
list.showDialog('edit', carrier(1))
list.showDialog('add')
assert.equal(list.form.realname_control_enabled, 0)
await list.handleSubmit(validForm)
assert.equal(writes[0].data.realname_control_enabled, 0)
list.showDialog('edit', carrier(0))
assert.equal(list.form.realname_control_enabled, 0)
list.showDialog('edit', carrier(undefined))
assert.equal(list.form.realname_control_enabled, 0)
})
for (const userType of [1, 2]) {
test(`user_type=${userType}: initial PUT obtains actual impact before confirmed retry`, async () => {
const { list, writes, confirmations, messageBox, attempts } = harness(userType)
list.showDialog('edit', carrier(0))
list.form.realname_control_enabled = 1
let confirm
messageBox.confirm = (...args) => {
confirmations.push(args)
return new Promise((resolve) => {
confirm = resolve
})
}
const pending = list.handleSubmit(validForm)
await new Promise((resolve) => setImmediate(resolve))
assert.equal(confirmations.length, 1)
assert.equal(confirmations[0][0], '开启实名管控将停机 12 张卡,请确认后重试')
assert.equal(attempts.length, 1)
assert.equal(attempts[0].data.realname_control_confirm, undefined)
assert.deepEqual(writes, [])
assert.equal(list.submitLoading.value, true)
await list.handleSubmit(validForm)
assert.equal(confirmations.length, 1)
confirm('confirm')
await pending
assert.equal(writes.length, 1)
assert.equal(writes[0].method, 'update')
assert.equal(writes[0].data.realname_control_enabled, 1)
assert.equal(writes[0].data.realname_control_confirm, true)
assert.equal(list.submitLoading.value, false)
})
}
for (const reason of ['cancel', 'close']) {
test(`${reason} of realname confirmation does not submit; retry requires a fresh confirmation`, async () => {
const { list, writes, messageBox } = harness(1)
list.showDialog('edit', carrier(0))
list.form.realname_control_enabled = 1
let prompts = 0
messageBox.confirm = async () => {
prompts += 1
throw reason
}
await list.handleSubmit(validForm)
assert.deepEqual(writes, [])
assert.equal(list.dialogVisible.value, true)
assert.equal(list.submitLoading.value, false)
assert.equal(list.form.realname_control_enabled, 1)
messageBox.confirm = async () => {
prompts += 1
return 'confirm'
}
await list.handleSubmit(validForm)
assert.equal(prompts, 2)
assert.equal(writes[0].data.realname_control_confirm, true)
})
}
test('unchanged, disabled, new, and unauthorized carriers never send confirmation automatically', async () => {
for (const [userType, mode, original, selected] of [
[1, 'edit', 1, 1],
[1, 'edit', 0, 0],
[2, 'edit', 1, 0],
[1, 'add', 0, 1],
[3, 'edit', 0, 1],
[4, 'edit', 0, 1]
]) {
const { list, writes, confirmations } = harness(userType)
list.showDialog(mode, carrier(original))
list.form.realname_control_enabled = selected
await list.handleSubmit(validForm)
assert.equal(confirmations.length, 0)
assert.equal(writes.length, 1)
assert.equal(Object.hasOwn(writes[0].data, 'realname_control_confirm'), false)
}
})
test('opening another carrier resets the original control state after a cancelled enabling', async () => {
const { list, writes, messageBox } = harness(2)
list.showDialog('edit', carrier(0))
list.form.realname_control_enabled = 1
messageBox.confirm = async () => {
throw 'cancel'
}
await list.handleSubmit(validForm)
list.showDialog('edit', { ...carrier(1), id: 8 })
await list.handleSubmit(validForm)
assert.equal(writes[0].id, 8)
assert.equal(Object.hasOwn(writes[0].data, 'realname_control_confirm'), false)
})
test('an unrelated PUT error never triggers confirmation or automatic retry', async (t) => {
const { list, writes, confirmations, service } = harness(2)
t.mock.method(console, 'error', () => {})
list.showDialog('edit', carrier(0))
list.form.realname_control_enabled = 1
const updateCarrier = service.updateCarrier
service.updateCarrier = async () => {
throw new Error('PUT failed')
}
await list.handleSubmit(validForm)
assert.equal(confirmations.length, 0)
assert.deepEqual(writes, [])
assert.equal(list.dialogVisible.value, true)
assert.equal(list.submitLoading.value, false)
service.updateCarrier = updateCarrier
await list.handleSubmit(validForm)
assert.equal(confirmations.length, 1)
assert.equal(writes[0].data.realname_control_confirm, true)
})
function findElement(node, predicate) {
if (node.type === 1 && predicate(node)) return node
for (const child of node.children || []) {
const match = findElement(child, predicate)
if (match) return match
}
}
test('form and detail guard the field, and the switch uses numeric 1/0', () => {
for (const [name, tag] of [
['index', 'ElFormItem'],
['detail', 'ElDescriptionsItem']
]) {
const field = findElement(
components[name].descriptor.template.ast,
(node) =>
node.tag === tag &&
node.props.some((prop) => prop.name === 'label' && prop.value?.content === '通道实名管控')
)
assert.ok(field)
assert.equal(
field.props.find((prop) => prop.type === 7 && prop.name === 'if')?.exp?.content,
'canConfigureRealnameControl'
)
if (name === 'index') {
const toggle = findElement(field, (node) => node.tag === 'ElSwitch')
for (const [arg, value] of [
['active-value', '1'],
['inactive-value', '0']
]) {
assert.equal(
toggle.props.find((prop) => prop.type === 7 && prop.arg?.content === arg)?.exp?.content,
value
)
}
}
}
})
test('carrier endpoints preserve the field in list/detail responses and create/update requests', async () => {
const calls = []
class BaseService {
static getPage(url) {
calls.push({ method: 'GET', url })
return Promise.resolve({ code: 0, data: { items: [carrier(1)] } })
}
static getOne(url) {
calls.push({ method: 'GET', url })
return Promise.resolve({ code: 0, data: carrier(0) })
}
static create(url, data) {
calls.push({ method: 'POST', url, data })
return Promise.resolve({ code: 0, data })
}
static update(url, data) {
calls.push({ method: 'PUT', url, data })
return Promise.resolve({ code: 0, data })
}
static put(url, data) {
return this.update(url, data)
}
}
const { CarrierService } = evaluate(read('src/api/modules/carrier.ts'), {
'../BaseService': { BaseService }
})
assert.equal((await CarrierService.getCarriers()).data.items[0].realname_control_enabled, 1)
assert.equal((await CarrierService.getCarrierDetail(7)).data.realname_control_enabled, 0)
await CarrierService.createCarrier({ ...carrier(1) })
await CarrierService.updateCarrier(7, {
realname_control_enabled: 1,
realname_control_confirm: true
})
assert.deepEqual(calls, [
{ method: 'GET', url: '/api/admin/carriers' },
{ method: 'GET', url: '/api/admin/carriers/7' },
{ method: 'POST', url: '/api/admin/carriers', data: carrier(1) },
{
method: 'PUT',
url: '/api/admin/carriers/7',
data: { realname_control_enabled: 1, realname_control_confirm: true }
}
])
})

View File

@@ -0,0 +1,41 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { parseArguments, parsePrePushLines, resolveImageTag } from '../deploy-frontend.mjs'
test('pre-push input resolves the exact commit being pushed', () => {
const refs = parsePrePushLines(
'refs/heads/iteration/august 94764b0e0a950fb841fd6c1e88578af34461f24c refs/heads/iteration/august 0000000000000000000000000000000000000000\n'
)
assert.deepEqual(refs, [
{
localRef: 'refs/heads/iteration/august',
localSha: '94764b0e0a950fb841fd6c1e88578af34461f24c',
remoteRef: 'refs/heads/iteration/august',
remoteSha: '0000000000000000000000000000000000000000'
}
])
})
test('deleting a remote branch does not resolve a zero commit', () => {
const refs = parsePrePushLines(
'refs/heads/iteration/august 0000000000000000000000000000000000000000 refs/heads/iteration/august 94764b0e0a950fb841fd6c1e88578af34461f24c\n'
)
assert.equal(refs[0].localSha, '0000000000000000000000000000000000000000')
})
test('manual branch mode accepts a branch and rejects unknown options', () => {
assert.deepEqual(parseArguments(['--branch', 'iteration/august']), {
mode: 'branch',
branch: 'iteration/august'
})
assert.throws(() => parseArguments(['--unknown']), /未知参数/)
})
test('image tag is the commit SHA rather than a mutable branch tag', () => {
assert.equal(
resolveImageTag('94764b0e0a950fb841fd6c1e88578af34461f24c'),
'94764b0e0a950fb841fd6c1e88578af34461f24c'
)
})

View File

@@ -0,0 +1,233 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
import * as vue from 'vue'
import { compileScript, parse } from '@vue/compiler-sfc'
function evaluate(source, imports = {}) {
const compiled = ts.transpileModule(source, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
}).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', compiled)(
(name) => {
assert.ok(imports[name], `Unexpected dependency: ${name}`)
return imports[name]
},
module,
module.exports
)
return module.exports
}
const acting = evaluate(readFileSync('src/utils/business/employeeCollectionActing.ts', 'utf8'))
const { descriptor } = parse(
readFileSync(
'src/views/finance/employee-collection/applications/components/ApplicationFormDialog.vue',
'utf8'
)
)
const componentSource = compileScript(descriptor, { id: 'collection-acting-test' }).content
const employee = { id: 10, name: '测试员工', user_type: 1 }
const bill = (id, name = employee.name, accountId = 99) => ({
id,
remaining_amount: 10000,
status: 0,
debtor_account_id: accountId,
debtor_snapshot: { account_id: accountId, account_name: name }
})
function formHarness(props = {}, candidates = [], details = {}) {
const calls = []
const detailCalls = []
const cleared = []
const user = vue.reactive({ info: { ...employee }, isSuperAdmin: true })
const service = {
getPaymentMethods: async () => ({
code: 0,
data: [{ id: 1, name: '银行转账', enabled: true }]
}),
getBills: async () => ({ code: 0, data: { items: candidates, total: candidates.length } }),
getApplicationById: async () => ({
code: 0,
data: {
allocations: Object.keys(details).map((id) => ({ bill_id: Number(id), amount: 5000 }))
}
}),
getBillById: async (id) => {
detailCalls.push(id)
return { code: 0, data: { bill: details[id] } }
},
createApplication: async (data) => {
calls.push({ method: 'create', data })
return { code: 0 }
},
updateApplication: async (id, data) => {
calls.push({ method: 'update', id, data })
return { code: 0 }
}
}
const display = {
BILL_SOURCE_OPTIONS: [],
BILL_STATUS_OPTIONS: [],
canCreateApplication: () => true,
formatCollectionCurrency: String,
normalizeCollectionList: (data) => (Array.isArray(data) ? data : data.items || []),
normalizeCollectionPage: (data) => ({ list: data.items || [], total: data.total || 0 })
}
const component = evaluate(componentSource, {
vue,
'element-plus': { ElMessage: { success() {}, error() {}, warning() {} } },
'@/api/modules': {
EmployeeCollectionService: service,
AgentRechargeService: {},
ShopService: {}
},
'@/utils/business/format': {
fenToYuan: (value) => Number(value || 0) / 100,
yuanToFen: (value) => Math.round(Number(value || 0) * 100)
},
'@/utils/business': {
getErrorMessage: String,
toVoucherKeyList: (value) => (Array.isArray(value) ? value : value ? [value] : [])
},
'@/store/modules/user': { useUserStore: () => user },
'@/utils/business/employeeCollectionActing': acting,
'@/components/business/VoucherUpload.vue': { default: {} },
'../../employeeCollectionDisplay': display
}).default
const reactiveProps = vue.reactive({
modelValue: true,
application: null,
presetBill: null,
...props
})
const state = component.setup(reactiveProps, { expose() {}, emit() {} })
state.formRef.value = {
clearValidate: (field) => cleared.push(field),
validate: async () => {
if (state.rules.value.acting_reason?.[0]?.required && !state.form.acting_reason.trim()) {
throw new Error('请填写代办原因')
}
}
}
const fillPayment = () =>
Object.assign(state.form, {
payment_method_id: 1,
paid_amount: 100,
paid_at: '2026-10-14T15:00:00+08:00',
payer_name: '付款方',
external_transaction_no: 'LOCAL_TEST',
payment_voucher_keys: ['test-voucher']
})
return { state, user, calls, cleared, detailCalls, fillPayment }
}
test('matching nonempty me.name makes a bill self-handled even when account IDs differ', () => {
assert.equal(acting.isEmployeeCollectionBillSelf(bill(1), employee), true)
assert.equal(acting.isEmployeeCollectionBillSelf(bill(1, ' 测试员工 '), employee), true)
assert.equal(acting.isEmployeeCollectionBillSelf(bill(1, '其他员工'), employee), false)
assert.equal(acting.isEmployeeCollectionBillSelf(bill(1, '', 10), employee), true)
assert.equal(
acting.isEmployeeCollectionBillSelf(bill(1, '', null), { name: '', user_type: 1 }),
false
)
assert.equal(acting.requiresEmployeeCollectionActingReason([bill(1), bill(2)], employee), false)
assert.equal(
acting.requiresEmployeeCollectionActingReason([bill(1), bill(2, '其他员工')], employee),
true
)
assert.equal(acting.requiresEmployeeCollectionActingReason([undefined], employee), true)
assert.equal(acting.requiresEmployeeCollectionActingReason([], employee), true)
assert.equal(
acting.requiresEmployeeCollectionActingReason([bill(2, '其他员工')], {
...employee,
user_type: 2
}),
false
)
})
test('creating a self-handled application has no acting reason rule and omits the field entirely', async () => {
const { state, calls, fillPayment } = formHarness({ presetBill: bill(1) })
await state.initialize()
await vue.nextTick()
fillPayment()
assert.equal(state.isActing.value, false)
assert.equal(state.rules.value.acting_reason, undefined)
state.form.acting_reason = '不得发送的残留值'
await state.handleSubmit()
assert.equal(calls[0].method, 'create')
assert.equal(Object.hasOwn(calls[0].data, 'acting_reason'), false)
assert.deepEqual(calls[0].data.allocations, [{ bill_id: 1, amount: 10000 }])
})
test('acting for another employee remains required; switching back to self clears the old value and validation', async () => {
const { state, calls, cleared, fillPayment } = formHarness()
fillPayment()
state.toggleBill(bill(2, '其他员工'))
await vue.nextTick()
assert.equal(state.rules.value.acting_reason[0].required, true)
await assert.rejects(state.handleSubmit(), /代办原因/)
assert.equal(calls.length, 0)
state.form.acting_reason = '代办核销'
state.toggleBill(bill(2, '其他员工'))
state.toggleBill(bill(1))
await vue.nextTick()
assert.equal(state.isActing.value, false)
assert.equal(state.form.acting_reason, '')
assert.ok(cleared.includes('acting_reason'))
await state.handleSubmit()
assert.equal(Object.hasOwn(calls[0].data, 'acting_reason'), false)
})
test('resubmission loads responsibility for bills outside the current candidate page and omits a historical acting reason', async () => {
const application = {
id: 8,
acting_reason: '历史代办原因',
paid_amount: 5000,
payment_method_id: 1
}
const { state, calls, detailCalls, fillPayment } = formHarness({ application }, [], {
21: bill(21)
})
await state.initialize()
await vue.nextTick()
fillPayment()
assert.deepEqual(detailCalls, [21])
assert.equal(state.displayBills.value[0].debtor_snapshot.account_name, employee.name)
assert.equal(state.isActing.value, false)
assert.equal(state.rules.value.acting_reason, undefined)
assert.equal(state.form.acting_reason, '')
await state.handleSubmit()
assert.equal(calls[0].method, 'update')
assert.equal(calls[0].id, 8)
assert.equal(Object.hasOwn(calls[0].data, 'acting_reason'), false)
assert.deepEqual(calls[0].data.allocations, [{ bill_id: 21, amount: 5000 }])
})
test('resubmission reuses responsibility from the candidate page and cannot be shadowed by an incomplete allocation cache', async () => {
const { state, detailCalls } = formHarness({ application: { id: 9 } }, [bill(1)], { 1: bill(1) })
await state.initialize()
await vue.nextTick()
assert.deepEqual(detailCalls, [])
state.selectedBillOptions.value[1] = { id: 1, remaining_amount: 10000 }
assert.equal(state.isActing.value, false)
})
test('mixed-responsibility resubmission still sends the required acting reason', async () => {
const { state, calls, fillPayment } = formHarness({ application: { id: 10 } }, [], {
1: bill(1),
2: bill(2, '其他员工')
})
await state.initialize()
await vue.nextTick()
fillPayment()
assert.equal(state.isActing.value, true)
assert.equal(state.rules.value.acting_reason[0].required, true)
state.form.acting_reason = ' 帮员工提交核销 '
await state.handleSubmit()
assert.equal(calls[0].data.acting_reason, '帮员工提交核销')
})

View File

@@ -0,0 +1,5 @@
iccid,note
89860426012345678901,local mock
89860426012345678902,skip
89860426012345678903,fail
89860426012345678904,denied
1 iccid note
2 89860426012345678901 local mock
3 89860426012345678902 skip
4 89860426012345678903 fail
5 89860426012345678904 denied

View File

@@ -0,0 +1,48 @@
[
"DELETE /gateway-error-classifications/{id}",
"DELETE /polling-carrier-params/{carrier_id}",
"DELETE /polling-rate-limit-groups/{id}",
"GET /card-polling-pauses",
"GET /card-stop-resume-records",
"GET /gateway-error-classifications",
"GET /iot-cards/{id}/polling-state",
"GET /iot-cards/{id}/stop-resume-records",
"GET /polling-carrier-params",
"GET /polling-carrier-params/{carrier_id}",
"GET /polling-check-scenes",
"GET /polling-configs/match-preview",
"GET /polling-configs/recalculate-due/{task_id}",
"GET /polling-failure-alerts",
"GET /polling-failure-alerts/summary",
"GET /polling-failure-alerts/{id}",
"GET /polling-options",
"GET /polling-rate-limit-groups",
"GET /polling-rate-limit-groups/{id}",
"GET /polling-stats/carrier-queues",
"GET /polling-stats/carriers",
"GET /polling-stats/carriers/{carrier_id}/trend",
"GET /polling-stats/pre-reset",
"GET /polling-stats/tiers",
"GET /polling-status-imports",
"GET /polling-status-imports/{id}",
"GET /polling-status/impact",
"GET /stop-resume-rule/dry-run",
"POST /devices/batch-update-polling-status",
"POST /gateway-error-classifications",
"POST /gateway-error-classifications/test",
"POST /iot-cards/batch-update-polling-status",
"POST /polling-configs/match-preview",
"POST /polling-configs/recalculate-due",
"POST /polling-failure-alerts/close-polling",
"POST /polling-rate-limit-groups",
"POST /polling-status-imports",
"POST /stop-resume-rule/dry-run/export",
"PUT /gateway-error-classifications/{id}",
"PUT /gateway-error-classifications/{id}/status",
"PUT /polling-carrier-params/{carrier_id}",
"PUT /polling-check-scenes/{scene}",
"PUT /polling-configs/priorities",
"PUT /polling-failure-alerts/{id}/status",
"PUT /polling-rate-limit-groups/{id}",
"PUT /polling-rate-limit-groups/{id}/status"
]

View File

@@ -0,0 +1,727 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
import * as vue from 'vue'
import { compileScript, parse } from '@vue/compiler-sfc'
function evaluate(source, imports = {}) {
const compiled = ts.transpileModule(source, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
}).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', compiled)(
(name) => {
assert.ok(imports[name], `Unexpected dependency: ${name}`)
return imports[name]
},
module,
module.exports
)
return module.exports
}
const source = (path) => readFileSync(path, 'utf8')
const format = evaluate(source('src/utils/business/format.ts'))
const utils = evaluate(source('src/utils/business/gateway.ts'), { './format': format })
const constants = evaluate(source('src/config/constants/gateway.ts'))
const permissions = constants.GATEWAY_PERMISSIONS
const rule = {
category: 'business',
keyword: 'failed',
match_type: 'contains',
priority: 10,
status: 1,
operations: ['stop']
}
const group = {
group_code: 'default',
group_name: '默认组',
max_qps: 20,
reserved_qps: 5,
operations: ['stop', 'start'],
high_priority_operations: ['stop'],
status: 1
}
const option = (value) => ({ value, label: `动态-${value}` })
const options = {
error_categories: ['business', 'terminal'].map(option),
exempt_sources: ['manual'].map(option),
gateway_operations: ['stop', 'start', 'query_flow', 'query_status', 'query_realname'].map(option),
match_types: ['contains', 'prefix', 'regex'].map(option),
rate_limit_modes: ['default'].map(option),
stop_resume_actions: ['stop', 'start'].map(option),
stop_resume_results: ['success', 'failed', 'unknown', 'already_target', 'skipped'].map(option)
}
const success = (data) => ({ code: 0, data, msg: 'ok' })
const page = (items) => success({ items, total: items.length, page: 1, size: 20 })
const deferred = () => {
let resolve
const promise = new Promise((done) => {
resolve = done
})
return { promise, resolve }
}
async function flush() {
await new Promise((done) => setImmediate(done))
await vue.nextTick()
}
test('all 17 gateway service contracts preserve methods, paths, params and response', async () => {
const calls = []
const response = success({ marker: true })
const http = Object.fromEntries(
['get', 'post', 'put', 'del'].map((method) => [
method,
(args) => {
calls.push({ method, ...args })
return Promise.resolve(response)
}
])
)
const base = evaluate(source('src/api/BaseService.ts'), { '@/utils/http': { default: http } })
const { GatewayService: service } = evaluate(source('src/api/modules/gateway.ts'), {
'../BaseService': base
})
const recordsQuery = {
page: 2,
page_size: 100,
carrier_id: 0,
start_time: '2026-10-01T00:00:00Z',
end_time: '2026-10-24T00:00:00Z'
}
const contracts = [
['getRecords', [recordsQuery], 'get', '/card-stop-resume-records', 'params', recordsQuery],
[
'getCardRecords',
[42, { page: 1 }],
'get',
'/iot-cards/42/stop-resume-records',
'params',
{ page: 1 }
],
['getRules', [{ status: 0 }], 'get', '/gateway-error-classifications', 'params', { status: 0 }],
['createRule', [rule], 'post', '/gateway-error-classifications', 'data', rule],
['updateRule', [7, rule], 'put', '/gateway-error-classifications/7', 'data', rule],
[
'setRuleStatus',
[7, 0],
'put',
'/gateway-error-classifications/7/status',
'data',
{ status: 0 }
],
['deleteRule', [7], 'del', '/gateway-error-classifications/7', 'params', undefined],
[
'testRule',
[{ operation: 'stop', message: 'failed', draft: rule }],
'post',
'/gateway-error-classifications/test',
'data',
{ operation: 'stop', message: 'failed', draft: rule }
],
['getOptions', [], 'get', '/polling-options', 'params', undefined],
[
'getGroups',
[{ only_global: false, carrier_id: 0, status: 0 }],
'get',
'/polling-rate-limit-groups',
'params',
{ only_global: false, carrier_id: 0, status: 0 }
],
['createGroup', [group], 'post', '/polling-rate-limit-groups', 'data', group],
['getGroup', [4], 'get', '/polling-rate-limit-groups/4', 'params', undefined],
['updateGroup', [4, group], 'put', '/polling-rate-limit-groups/4', 'data', group],
['setGroupStatus', [4, 1], 'put', '/polling-rate-limit-groups/4/status', 'data', { status: 1 }],
['deleteGroup', [4], 'del', '/polling-rate-limit-groups/4', 'params', undefined],
['getCarrierStats', [60], 'get', '/polling-stats/carriers', 'params', { minutes: 60 }],
[
'getCarrierTrend',
[0, { minutes: 10080, bucket_minutes: 60 }],
'get',
'/polling-stats/carriers/0/trend',
'params',
{ minutes: 10080, bucket_minutes: 60 }
]
]
for (const [method, args, verb, url, field, payload] of contracts) {
assert.equal(await service[method](...args), response)
assert.deepEqual(calls.at(-1), { method: verb, url: `/api/admin${url}`, [field]: payload })
}
assert.equal(calls.length, 17)
})
test('record dates are RFC3339, ordered and bounded to 31 days, optional only for cards', () => {
assert.deepEqual(utils.gatewayTimeRange(['2026-10-01T08:00:00+08:00', '2026-11-01T00:00:00Z']), {
start_time: '2026-10-01T00:00:00.000Z',
end_time: '2026-11-01T00:00:00.000Z'
})
assert.deepEqual(utils.gatewayTimeRange(null, false), {})
for (const range of [
null,
[],
[''],
['invalid', 'invalid'],
['2026-10-02', '2026-10-01'],
['2026-10-01', '2026-11-01T00:00:00.001Z']
])
assert.throws(() => utils.gatewayTimeRange(range))
const [start, end] = utils.recentGatewayRange()
assert.equal(end - start, 7 * 86400000)
})
test('limit groups validate QPS, operation subset, carrier zero and text limits', () => {
assert.doesNotThrow(() => utils.validateGatewayGroup({ ...group, carrier_id: 0 }))
assert.doesNotThrow(() =>
utils.validateGatewayGroup({ ...group, reserved_qps: 0, high_priority_operations: [] })
)
for (const patch of [
{ max_qps: 0 },
{ max_qps: 10001 },
{ max_qps: 1.5 },
{ reserved_qps: -1 },
{ reserved_qps: 20 },
{ reserved_qps: 0.5 },
{ operations: [] },
{ high_priority_operations: [] },
{ high_priority_operations: ['query_flow'] },
{ group_code: ' ' },
{ group_name: 'x'.repeat(101) },
{ carrier_id: -1 }
])
assert.throws(() => utils.validateGatewayGroup({ ...group, ...patch }))
})
test('rules validate required fields, priority and lengths, including draft rules', () => {
assert.doesNotThrow(() => utils.validateGatewayRule(rule))
for (const patch of [
{ keyword: ' ' },
{ keyword: 'x'.repeat(201) },
{ category: '' },
{ match_type: '' },
{ priority: 0 },
{ priority: 10001 },
{ priority: 1.2 },
{ remark: 'x'.repeat(501) }
])
assert.throws(() => utils.validateGatewayRule({ ...rule, ...patch }))
})
test('unknown enums and statistic fields remain visible, without fabricated zeroes', () => {
assert.equal(utils.gatewayLabel(options.gateway_operations, 'stop'), '动态-stop')
assert.equal(
utils.gatewayLabel(options.gateway_operations, 'future_operation'),
'future_operation'
)
assert.equal(utils.gatewayValue(0), '0')
assert.equal(utils.gatewayValue(false), 'false')
assert.equal(utils.gatewayValue(null), '-')
assert.deepEqual(utils.gatewayRows([{ future_metric: 12 }, 0, null]), [
{ future_metric: 12 },
{ value: 0 },
{ value: null }
])
assert.deepEqual(
utils.compactGatewayQuery({
carrier_id: 0,
status: 0,
only_global: false,
blank: '',
missing: undefined
}),
{ carrier_id: 0, status: 0, only_global: false }
)
assert.throws(() => utils.gatewayData({ code: 403, msg: '没有权限' }), /没有权限/)
})
function mountComponent(
t,
path,
{ superAdmin = false, perms = [], overrides = {}, props = {} } = {}
) {
const calls = []
const user = vue.reactive({ isSuperAdmin: superAdmin, perms })
const service = Object.fromEntries(
['getRecords', 'getCardRecords', 'getRules', 'getGroups'].map((name) => [
name,
async (...args) => {
calls.push({ name, args })
return page([])
}
])
)
Object.assign(service, { getOptions: async () => success(options) })
for (const name of [
'createRule',
'updateRule',
'setRuleStatus',
'deleteRule',
'testRule',
'createGroup',
'updateGroup',
'setGroupStatus',
'deleteGroup',
'getGroup',
'getCarrierStats',
'getCarrierTrend'
])
service[name] = async (...args) => {
calls.push({ name, args })
return success({
...group,
id: 4,
matched: true,
rule_id: 0,
category: 'business',
category_name: '业务错误',
keyword: 'failed',
maybe_accepted: false,
carriers: [],
points: [],
carrier_id: args[0]
})
}
for (const [name, handler] of Object.entries(overrides))
service[name] = async (...args) => {
calls.push({ name, args })
return handler(...args)
}
const imports = {
vue,
'vue-router': {
useRouter: () => ({
push: async (url) => {
calls.push({ name: 'navigate', args: [url] })
},
back() {}
}),
useRoute: () => ({ params: { id: '4' } })
},
'@vueuse/core': { useWindowSize: () => ({ width: vue.ref(1200) }) },
'@element-plus/icons-vue': { ArrowLeft: {} },
'@/router/routesAlias': {
RoutesAlias: { GatewayRateLimitGroupDetail: '/polling-management/rate-limit-groups/detail' }
},
'@/utils/business/format': format,
'@/api/modules/carrier': {
CarrierService: {
getCarriers: async (...args) => {
calls.push({ name: 'getCarriers', args })
if (overrides.getCarriers) return overrides.getCarriers(...args)
return page([{ id: 8, carrier_name: '模拟运营商' }])
}
}
},
'element-plus': {
ElMessage: { success() {}, error() {} },
ElMessageBox: { confirm: async () => {} }
},
'@/api/modules/gateway': { GatewayService: service },
'@/store/modules/user': { useUserStore: () => user },
'@/composables/useAuth': {
useAuth: () => ({ hasAuth: (perm) => user.isSuperAdmin || user.perms.includes(perm) })
},
'@/config/constants/gateway': constants,
'@/utils/business/gateway': utils,
'@/components/business/gateway/GatewayOptionsNotice.vue': { default: {} },
'@/components/business/gateway/GatewayRuleFields.vue': { default: {} },
'@/components/business/gateway/GatewayDynamicData.vue': { default: {} },
'@/components/business/gateway/GatewayOperationTable.vue': { default: {} },
'./GatewayOptionsNotice.vue': { default: {} }
}
imports['@/composables/useGateway'] = evaluate(source('src/composables/useGateway.ts'), imports)
const { descriptor } = parse(source(path))
const component = evaluate(
compileScript(descriptor, { id: 'gateway-test' }).content,
imports
).default
let state
const reactiveProps = vue.reactive(props)
const renderer = vue.createRenderer({
createComment: () => ({}),
insert() {},
remove() {},
parentNode: () => null,
nextSibling: () => null
})
const app = renderer.createApp({
setup() {
state = component.setup(reactiveProps, { expose() {}, emit() {} })
return () => null
}
})
app.mount({})
t.after(() => app.unmount())
return { state, calls, user, props: reactiveProps, service }
}
const rulePage = 'src/views/polling-management/error-classifications/index.vue'
const groupPage = 'src/views/polling-management/rate-limit-groups/index.vue'
const statsPage = 'src/views/polling-management/gateway-stats/index.vue'
const recordComponent = 'src/components/business/gateway/StopResumeRecords.vue'
test('ordinary users cannot maintain either rules or groups, even if handlers are called', async (t) => {
for (const [path, area, save, mutate, input] of [
[rulePage, 'rules', 'saveRule', 'changeRule', rule],
[groupPage, 'groups', 'saveGroup', 'changeGroup', group]
]) {
const { state, calls } = mountComponent(t, path, { perms: [permissions[area].page] })
await flush()
state.form.value = input
await state[save]()
await state[mutate]({ ...input, id: 1 }, true)
assert.equal(
calls.filter((call) => /create|update|delete|set.*Status/.test(call.name)).length,
0
)
assert.match(state.editorError.value, /无权/)
}
})
test('superadmin saves use write DTOs without record ids or timestamps', async (t) => {
for (const [path, save, input, method] of [
[rulePage, 'saveRule', rule, 'createRule'],
[groupPage, 'saveGroup', group, 'createGroup']
]) {
const { state, calls } = mountComponent(t, path, { superAdmin: true })
await flush()
state.form.value = { ...input }
await state[save]()
const call = calls.find((call) => call.name === method)
assert.ok(call)
assert.equal(call.args[0].id, undefined)
if (method === 'createGroup') assert.equal(call.args[0].carrier_id, null)
assert.equal(state.editorError.value, '')
}
})
test('ordinary rule tests require page + button, validate drafts, and never write rules', async (t) => {
const { state, calls, user } = mountComponent(t, rulePage, {
perms: [permissions.rules.page, permissions.rules.test]
})
await flush()
state.openTest()
state.testForm.operation = 'stop'
state.testForm.message = 'failed'
state.includeDraft.value = true
await state.runTest()
assert.equal(calls.filter((call) => call.name === 'testRule').length, 0)
state.draft.value = { ...rule }
await state.runTest()
assert.deepEqual(calls.find((call) => call.name === 'testRule').args[0], {
operation: 'stop',
message: 'failed',
draft: rule
})
assert.equal(state.testResult.value.matched, true)
user.perms = [permissions.rules.test]
await state.runTest()
assert.match(state.testError.value, /无权/)
assert.equal(calls.filter((call) => call.name === 'testRule').length, 1)
})
test('test close/reopen discards a pending result', async (t) => {
const pending = deferred()
const { state } = mountComponent(t, rulePage, {
superAdmin: true,
overrides: { testRule: () => pending.promise }
})
await flush()
state.openTest()
Object.assign(state.testForm, { operation: 'stop', message: 'failed' })
const running = state.runTest()
state.testVisible.value = false
await vue.nextTick()
state.openTest()
pending.resolve(success({ matched: true }))
await running
assert.equal(state.testResult.value, null)
})
test('enum failure is visible, blocks editing and can be retried with dynamic labels', async (t) => {
let failed = true
const { state } = mountComponent(t, rulePage, {
superAdmin: true,
overrides: {
getOptions: () => (failed ? Promise.reject(new Error('枚举不可用')) : success(options))
}
})
await flush()
assert.equal(state.optionsReady.value, false)
assert.match(state.optionsError.value, /枚举不可用/)
state.openEditor()
assert.equal(state.editorVisible.value, false)
failed = false
await state.loadOptions()
assert.equal(state.optionsReady.value, true)
assert.equal(state.label('gateway_operations', 'stop'), '动态-stop')
})
test('record queries validate time, preserve zero filters and isolate cards by real ID', async (t) => {
const { state, calls, props } = mountComponent(t, recordComponent, {
perms: [permissions.cardHistory],
props: { cardId: 42, permission: permissions.cardHistory }
})
await flush()
assert.equal(calls[0].name, 'getCardRecords')
assert.equal(calls[0].args[0], 42)
state.range.value = null
await state.search()
assert.deepEqual(calls.at(-1).args, [42, { page: 1, page_size: 20 }])
props.cardId = 43
await flush()
assert.equal(calls.at(-1).args[0], 43)
props.cardId = undefined
props.permission = permissions.records.page
await flush()
assert.match(state.error.value, /无权/)
})
test('invalid global date ranges never request records; zero carrier survives', async (t) => {
const { state, calls } = mountComponent(t, recordComponent, {
perms: [permissions.records.page],
props: { permission: permissions.records.page }
})
await flush()
calls.length = 0
state.range.value = null
await state.search()
assert.equal(calls.length, 0)
state.range.value = [new Date('2026-10-01'), new Date('2026-10-24')]
state.filters.carrier_id = 0
await state.search()
assert.equal(calls[0].args[0].carrier_id, 0)
})
test('list latest request wins and errors clear previous records', async (t) => {
const first = deferred()
const second = deferred()
let count = 0
const { state } = mountComponent(t, groupPage, {
superAdmin: true,
overrides: { getGroups: () => (++count === 1 ? first.promise : second.promise) }
})
const latest = state.load()
second.resolve(page([{ ...group, id: 2 }]))
await latest
first.resolve(page([{ ...group, id: 1 }]))
await flush()
assert.equal(state.rows.value[0].id, 2)
})
test('group details require permissions before navigation to shop-style detail page', async (t) => {
const { state, calls, user } = mountComponent(t, groupPage, { perms: [permissions.groups.page] })
await flush()
await state.openDetail(4)
assert.equal(
calls.some((call) => call.name === 'navigate'),
false
)
user.perms.push(permissions.groups.detail)
await state.openDetail(4)
assert.equal(
calls.find((call) => call.name === 'navigate').args[0],
'/polling-management/rate-limit-groups/detail/4'
)
})
test('statistics support account 0, reject bad bounds and retain raw unknown metrics', async (t) => {
const { state, calls } = mountComponent(t, statsPage, {
perms: [permissions.stats.page, permissions.stats.trend],
overrides: {
getCarrierTrend: (id) =>
success({ carrier_id: id, points: [{ new_metric: 9, future_time: '2026-10-24' }] })
}
})
await flush()
state.carrierId.value = 0
await state.loadTrend()
assert.equal(state.trend.value.carrier_id, 0)
assert.equal(state.trend.value.points[0].new_metric, 9)
state.trendMinutes.value = 10081
await state.loadTrend()
assert.equal(calls.filter((call) => call.name === 'getCarrierTrend').length, 1)
state.summaryMinutes.value = 61
await state.loadSummary()
assert.equal(calls.filter((call) => call.name === 'getCarrierStats').length, 1)
assert.equal(state.trend.value, null)
})
test('route aliases match all four pages and ordinary permissions use colon codes', () => {
const routes = source('src/router/routes/asyncRoutes.ts')
const aliases = source('src/router/routesAlias.ts')
for (const [name, segment] of [
['GatewayStopResumeRecords', 'stop-resume-records'],
['GatewayErrorClassifications', 'error-classifications'],
['GatewayRateLimitGroups', 'rate-limit-groups'],
['GatewayCallStats', 'gateway-stats']
]) {
assert.ok(routes.includes(`name: '${name}'`))
assert.ok(aliases.includes(`'/polling-management/${segment}'`))
assert.ok(source(`src/views/polling-management/${segment}/index.vue`))
}
const flattened = Object.values(permissions).flatMap((value) =>
typeof value === 'string' ? [value] : Object.values(value)
)
assert.equal(flattened.length, 10)
for (const code of flattened) assert.match(code, /^[a-z_]+:[a-z_]+$/)
})
test('detail page checks permission and formats dates using the shop formatter', async (t) => {
const path = 'src/views/polling-management/rate-limit-groups/detail.vue'
const denied = mountComponent(t, path)
await flush()
assert.equal(
denied.calls.some((call) => call.name === 'getGroup'),
false
)
const allowed = mountComponent(t, path, { perms: [permissions.groups.detailPage] })
await flush()
assert.equal(allowed.state.detail.value.id, 4)
assert.equal(allowed.state.formatDateTime('2026-10-24T10:00:00+08:00'), '2026-10-24 10:00:00')
})
test('gateway search expand toggles follow the >=4 rule', () => {
for (const path of [recordComponent, rulePage, groupPage, statsPage]) {
const matches = [...source(path).matchAll(/:show-expand="([^"]+)"/g)]
assert.ok(matches.length)
for (const match of matches) assert.match(match[1], /\.length >= 4$/)
}
})
test('record time picker matches expiring assets estimated-expiry range configuration', async (t) => {
const { descriptor } = parse(source('src/views/asset-management/expiring-assets/index.vue'))
const script = ts.createSourceFile(
'expiring-assets.ts',
descriptor.scriptSetup.content,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TS
)
let reference
function visit(node) {
if (
ts.isObjectLiteralExpression(node) &&
node.properties.some(
(property) =>
ts.isPropertyAssignment(property) &&
property.name.getText(script) === 'label' &&
ts.isStringLiteral(property.initializer) &&
property.initializer.text === '预计到期起止'
)
) {
reference = evaluate(`export const item = ${node.getText(script)}`).item
}
ts.forEachChild(node, visit)
}
visit(script)
assert.ok(reference)
const { state } = mountComponent(t, recordComponent, {
perms: [permissions.records.page],
props: { permission: permissions.records.page }
})
await flush()
const item = state.searchItems.value.find((item) => item.prop === 'range')
assert.equal(item.type, reference.type)
assert.equal(item.elColSpan, reference.elColSpan)
assert.deepEqual(item.config, reference.config)
assert.equal(item.label, '记录时间')
})
test('business timestamps match shop list formatting and IDs retain zero', () => {
const timestamp = '2026-10-24T10:00:00+08:00'
assert.equal(utils.gatewayDisplayValue(timestamp, 'created_at'), format.formatDateTime(timestamp))
assert.equal(
utils.gatewayDisplayValue({ created_at: timestamp }),
'{"created_at":"2026-10-24 10:00:00"}'
)
assert.equal(
utils.gatewayDisplayValue(1792807200, 'timestamp'),
format.formatDateTime(1792807200)
)
assert.equal(utils.gatewayDisplayValue(0, 'duration_ms'), '0')
assert.equal(utils.gatewayOptionalId('0'), 0)
assert.equal(utils.gatewayOptionalId(''), undefined)
assert.throws(() => utils.gatewayOptionalId('-1'))
})
test('carrier name search uses exact backend parameters and remembers edit labels', async (t) => {
const { state, calls } = mountComponent(t, groupPage, { superAdmin: true })
await flush()
await state.searchCarriers('运营商名称')
assert.deepEqual(calls.at(-1), {
name: 'getCarriers',
args: [{ page: 1, page_size: 20, carrier_name: '运营商名称' }]
})
state.openEditor({ ...group, id: 7, carrier_id: 99, carrier_name: '原账户' })
assert.equal(state.carrierOptions.value.find((option) => option.value === 99).label, '原账户')
assert.equal(state.form.value.carrier_id, 99)
assert.equal(state.searchItems.value[0].label, '运营商账户')
assert.equal(state.searchItems.value[0].type, 'select')
})
test('carrier search ignores a late old response and retains selected account labels', async (t) => {
const older = deferred()
const { state } = mountComponent(t, groupPage, {
superAdmin: true,
overrides: {
getCarriers: ({ carrier_name }) =>
carrier_name === 'old' ? older.promise : page([{ id: 8, carrier_name: '新账户' }])
}
})
await flush()
const first = state.searchCarriers('old')
await state.searchCarriers('new')
state.selectCarrier(8)
older.resolve(page([{ id: 9, carrier_name: '旧账户' }]))
await first
assert.equal(
state.carrierOptions.value.some((option) => option.value === 9),
false
)
assert.equal(state.carrierOptions.value.find((option) => option.value === 8).label, '新账户')
})
test('duplicate maintenance submits cannot send a second write while saving', async (t) => {
const pending = deferred()
const { state, calls } = mountComponent(t, rulePage, {
superAdmin: true,
overrides: { createRule: () => pending.promise }
})
await flush()
state.form.value = { ...rule }
const first = state.saveRule()
await state.saveRule()
assert.equal(calls.filter((call) => call.name === 'createRule').length, 1)
pending.resolve(success(rule))
await first
})
test('single-card history entry rejects missing IDs, other assets and denied permissions', () => {
const text = source('src/views/asset-management/asset-information/index.vue')
const functionText = text.match(/ {2}function showStopResumeRecords[\s\S]*?\n {2}}/)[0]
const { create } = evaluate(
`export const create = (cardInfo, hasAuth, stopResumePermission, stopResumeTarget, stopResumeVisible) => { ${functionText}; return showStopResumeRecords }`
)
const asset = vue.ref({
asset_type: 'device',
asset_id: 100,
cards: [{ card_id: 42, iccid: 'CARD' }]
})
const target = vue.ref(null)
const visible = vue.ref(false)
let allowed = false
const open = create(asset, () => allowed, vue.ref(permissions.deviceCardHistory), target, visible)
open({ cardId: 42, iccid: 'CARD' })
assert.equal(visible.value, false)
allowed = true
open({ cardId: 100, iccid: 'CARD' })
assert.equal(visible.value, false)
open({ cardId: 42, iccid: 'CARD' })
assert.equal(target.value.cardId, 42)
assert.equal(visible.value, true)
visible.value = false
asset.value = { asset_type: 'card', asset_id: 7, iccid: 'CARD-7' }
open({ cardId: 42, iccid: 'CARD' })
assert.equal(visible.value, false)
open({ cardId: 7, iccid: 'CARD-7' })
assert.equal(target.value.cardId, 7)
})

View File

@@ -0,0 +1,245 @@
// 本地浏览器验收专用;所有 /api 请求在这里终止,不会代理到真实后端。
const time = '2026-10-24T10:00:00+08:00'
const option = (value, label) => ({ value, label })
const options = {
error_categories: [
option('rate_limited_upstream', '上游频率限制'),
option('business', '业务错误')
],
exempt_sources: [option('manual', '人工')],
gateway_operations: [
option('query_flow', '查流量'),
option('query_status', '查状态'),
option('query_realname', '查实名'),
option('stop', '停机'),
option('start', '复机')
],
match_types: [option('contains', '包含'), option('prefix', '前缀'), option('regex', '正则')],
rate_limit_modes: [option('group', '限流组')],
stop_resume_actions: [option('stop', '停机'), option('start', '复机')],
stop_resume_results: [
option('success', '成功'),
option('failed', '失败'),
option('unknown', '未知'),
option('already_target', '已是目标状态'),
option('skipped', '已跳过')
]
}
const rules = [
{
id: 1,
category: 'rate_limited_upstream',
category_name: '上游频率限制',
keyword: '请求过于频繁',
match_type: 'contains',
operations: ['stop'],
priority: 10,
maybe_accepted: false,
status: 1,
remark: '本地模拟规则',
created_at: time,
updated_at: time
}
]
const groups = [
{
id: 1,
carrier_id: null,
carrier_name: '',
group_code: 'default',
group_name: '全局默认组',
operations: ['query_flow', 'stop', 'start'],
max_qps: 20,
reserved_qps: 5,
high_priority_operations: ['stop', 'start'],
status: 1,
status_name: '启用',
created_at: time,
updated_at: time
}
]
const records = [
{
id: 1,
card_id: 42,
carrier_id: 8,
iccid: 'MOCK-ICCID-42',
action: 'stop',
action_name: '停机',
result: 'success',
error_category: '',
error_category_name: '',
provider_message: '操作成功',
provider_code: '0',
attempt: 1,
command_id: 'MOCK-CMD',
source: 'manual',
scene: 'manual_stop',
reason: '本地验收',
duration_ms: 42,
created_at: time
}
]
const page = (items, url) => ({
items,
total: items.length,
page: Number(url.searchParams.get('page') || 1),
size: Number(url.searchParams.get('page_size') || 20)
})
export const mockApiPlugin = {
name: 'gateway-local-mock-api',
configureServer(server) {
server.middlewares.use(async (req, res, next) => {
const url = new URL(req.url, 'http://127.0.0.1')
const path = url.pathname
if (!path.startsWith('/api/')) return next()
let body = ''
for await (const chunk of req) body += chunk
const input = body ? JSON.parse(body) : {}
let data = page([], url)
let code = 0
let msg = 'local mock only'
if (path === '/api/auth/me' || path === '/api/auth/login') {
const viewer = req.headers.authorization?.includes('local-gateway-viewer')
const pagePermissions = [
'card_stop_resume_record:page',
'gateway_error_classification:page',
'gateway_rate_limit_group:page',
'gateway_rate_limit_group:detail_page',
'gateway_call_stats:page'
]
const menuEntries = [
['停复机记录', 'stop-resume-records', pagePermissions[0]],
['上游错误分类', 'error-classifications', pagePermissions[1]],
['网关限流组', 'rate-limit-groups', pagePermissions[2]],
['网关限流组详情', 'rate-limit-groups/detail/:id', pagePermissions[3]],
['网关调用统计', 'gateway-stats', pagePermissions[4]]
]
data = {
access_token: viewer ? 'local-gateway-viewer' : 'local-gateway-mock-only',
refresh_token: '',
expires_in: 3600,
user: {
id: viewer ? 2 : 1,
user_type: viewer ? 2 : 1,
username: viewer ? '本地只读账号' : '本地模拟管理员',
roles: [viewer ? 'R_ADMIN' : 'R_SUPER']
},
permissions: viewer ? pagePermissions : [],
buttons: viewer
? [
'gateway_error_classification:test',
'gateway_rate_limit_group:detail',
'gateway_call_stats:trend'
]
: [],
menus: viewer
? [
{
url: '/polling-management',
name: '轮询管理',
children: menuEntries.map(([name, segment, perm_code]) => ({
name,
url: `/polling-management/${segment}`,
perm_code
}))
}
]
: []
}
} else if (path === '/api/admin/polling-options') data = options
else if (path === '/api/admin/carriers')
data = page(
[
{
id: 8,
carrier_name: '模拟运营商账户',
carrier_type: 'CMCC',
status: 1,
created_at: time,
updated_at: time
}
].filter((carrier) =>
carrier.carrier_name.includes(url.searchParams.get('carrier_name') || '')
),
url
)
else if (
path === '/api/admin/card-stop-resume-records' ||
/\/iot-cards\/\d+\/stop-resume-records$/.test(path)
)
data = page(records, url)
else if (path === '/api/admin/gateway-error-classifications/test') {
data = {
matched: input.message?.includes(input.draft?.keyword || '请求过于频繁') || false,
rule_id: input.draft ? 0 : 1,
category: input.draft?.category || rules[0].category,
category_name: '上游频率限制',
keyword: input.draft?.keyword || rules[0].keyword,
maybe_accepted: false
}
} else if (
/^\/api\/admin\/(gateway-error-classifications|polling-rate-limit-groups)(\/\d+)?(\/status)?$/.test(
path
)
) {
const list = path.includes('gateway-error-classifications') ? rules : groups
const id = Number(path.split('/')[4])
const row = list.find((item) => item.id === id)
if (req.method === 'GET') data = id ? row : page(list, url)
else if (req.method === 'POST') {
data = {
...input,
id: Math.max(...list.map((item) => item.id), 0) + 1,
created_at: time,
updated_at: time
}
list.push(data)
} else if (req.method === 'PUT' && row) {
Object.assign(row, input)
if ('group_name' in row) row.status_name = row.status === 1 ? '启用' : '停用'
data = row
} else if (req.method === 'DELETE' && row) {
list.splice(list.indexOf(row), 1)
data = {}
}
} else if (path === '/api/admin/polling-stats/carriers') {
data = {
minutes: Number(url.searchParams.get('minutes') || 15),
mode: '本地模拟模式',
carriers: [
{
carrier_id: 8,
carrier_name: '模拟运营商',
example_calls: 100,
example_upstream_failures: 2
}
]
}
} else if (/\/polling-stats\/carriers\/\d+\/trend$/.test(path)) {
data = {
carrier_id: Number(path.split('/')[5]),
points: [{ example_time: time, example_calls: 10 }]
}
} else if (path.startsWith('/api/admin/assets/resolve/')) {
data = {
asset_type: 'card',
asset_id: 42,
identifier: 'MOCK-ICCID-42',
iccid: 'MOCK-ICCID-42',
status: 1,
network_status: 1,
real_name_status: 1,
carrier_name: '模拟运营商',
cards: []
}
} else if (req.method !== 'GET') {
code = 400
msg = '此本地验收接口未定义,已拦截写请求'
}
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(JSON.stringify({ code, msg, data }))
})
}
}

View File

@@ -0,0 +1,632 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import { resolve } from 'node:path'
import { createRequire } from 'node:module'
import ts from 'typescript'
import * as vue from 'vue'
import { compileScript, parse } from '@vue/compiler-sfc'
const require = createRequire(import.meta.url)
const esbuild = createRequire(require.resolve('vite'))('esbuild')
async function loadModule(entry, stubService = false) {
const result = await esbuild.build({
entryPoints: [entry],
bundle: true,
write: false,
format: 'cjs',
platform: 'node',
alias: { '@': resolve('src') },
plugins: stubService
? [
{
name: 'stub-base-service',
setup(build) {
build.onResolve({ filter: /BaseService$/ }, () => ({
path: 'base-service',
namespace: 'stub'
}))
build.onLoad({ filter: /.*/, namespace: 'stub' }, () => ({
contents: `
export class BaseService {
static calls = [];
static put(url, data, config) { this.calls.push({url, data, config}); return Promise.resolve({code:0, data:{}}); }
static update(url, data) { return this.put(url, data); }
static post(url, data, config) { this.calls.push({url, data, config}); return Promise.resolve({code:0, data:{}}); }
}`
}))
}
}
]
: []
})
const module = { exports: {} }
new Function('require', 'module', 'exports', result.outputFiles[0].text)(
require,
module,
module.exports
)
return module.exports
}
test('new login password allows special characters and requires at least three of four classes', async () => {
const { getNewLoginPasswordError, createNewLoginPasswordRule } = await loadModule(
'src/utils/validation/loginPassword.ts'
)
for (const password of [
'Abc12345',
'Abc123456789',
'Abc1234!',
'Abc1234_',
'ABC1234!',
'abc1234!',
'Abcdefg!',
'Ab1~`-=[]{}',
'Ab1;:\\|,<>/?'
])
assert.equal(getNewLoginPasswordError(password), undefined)
for (const password of [
'Abc1234',
'Abc123456789X',
'abcd1234',
'ABCD1234',
'AbcDefGh',
'ABCDEF!!',
'abcdef!!',
'123456!!',
'Abc1234 ',
' Abc12345',
'Abc1234\n',
'Abc1234中',
'Abc123😀',
'Abc12345'
]) {
assert.ok(getNewLoginPasswordError(password), `must reject ${JSON.stringify(password)}`)
}
const rule = createNewLoginPasswordRule()
for (const value of ['', undefined, null])
rule.validator({}, value, (error) => assert.equal(error, undefined))
rule.validator({}, 'Abc1234!', (error) => assert.equal(error, undefined))
rule.validator({}, 'abcdef!!', (error) => assert.ok(error instanceof Error))
for (const symbol of Array.from('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')) {
assert.equal(getNewLoginPasswordError(`Ab12345${symbol}`), undefined)
}
})
test('admin and scan-registration new-password forms share validation, hints and the 12-character input limit', async () => {
const forms = [
{
path: 'src/components/core/layouts/art-header-bar/ChangePasswordDialog.vue',
models: ['formData.new_password', 'formData.confirm_password'],
fields: ['new_password', 'confirm_password'],
hint: "t('passwordChange.passwordRule')"
},
{
path: 'src/views/account-management/account/index.vue',
models: ['formData.password'],
fields: ['password']
},
{
path: 'src/views/common/account-list.vue',
models: ['accountForm.password'],
fields: ['password']
},
{
path: 'src/views/shop-management/list/index.vue',
models: ['formData.init_password'],
fields: ['init_password']
},
{
path: 'src/views/account-management/enterprise-customer/index.vue',
models: ['form.password', 'passwordForm.password'],
fields: ['password', 'password']
},
{
path: 'src/views/agent-registration/index.vue',
models: ['form.password'],
fields: ['password'],
hint: null
}
]
for (const { path, models, fields, hint = 'NEW_LOGIN_PASSWORD_HINT' } of forms) {
const source = await readFile(path, 'utf8')
assert.match(source, /from '@\/utils\/validation\/loginPassword'/, path)
const inputs = [...source.matchAll(/<ElInput\b[\s\S]*?\/>/g)].map(([input]) => input)
for (const model of models) {
// Exact v-model also rejects a silent .trim modifier on password inputs.
const matches = inputs.filter((input) => input.includes(`v-model="${model}"`))
assert.equal(matches.length, 1, `${path}: ${model}`)
assert.match(matches[0], /type="password"/, `${path}: ${model}`)
assert.match(matches[0], /maxlength="12"/, `${path}: ${model}`)
if (hint) {
assert.ok(matches[0].includes(`:placeholder="${hint}"`), `${path}: ${model} hint`)
} else {
assert.match(matches[0], /aria-describedby="registration-password-rule"/, path)
assert.match(source, /id="registration-password-rule"[\s\S]*?NEW_LOGIN_PASSWORD_HINT/, path)
}
}
const rules = [
...source.matchAll(
/\b(password|new_password|confirm_password|init_password):\s*\[([\s\S]*?)\n\s*\]/g
)
]
assert.deepEqual(rules.map(([, field]) => field).sort(), [...fields].sort(), path)
for (const [, field, rule] of rules) {
assert.match(rule, /required: true/, `${path}: ${field}`)
assert.match(rule, /createNewLoginPasswordRule\(/, `${path}: ${field}`)
assert.doesNotMatch(rule, /\b(?:min|max|pattern):/, `${path}: ${field} stale rule`)
}
}
})
test('scan registration validates password and locally handles errors without changing public endpoint, payload or SMS behavior', async () => {
const { AgentDistributionService } = await loadModule(
'src/api/modules/agentDistribution.ts',
true
)
AgentDistributionService.calls = []
const params = {
distribution_code: 'local-test',
phone: '13800000000',
code: '123456',
shop_name: '本地测试店铺',
shop_code: 'LOCAL_TEST',
username: 'local_test'
}
for (const password of ['Abc12345', 'Abc123456789', 'ABC1234!', 'abc1234!', 'Abcdefg!']) {
await AgentDistributionService.registerAgent({ ...params, password })
assert.deepEqual(AgentDistributionService.calls.at(-1), {
url: '/api/c/v1/agent-distribution-registrations',
data: { ...params, password },
config: { requestOptions: { withToken: false, errorMessageMode: 'none' } }
})
}
for (const password of ['', 'Abc1234', 'Abc123456789X', 'abcd1234', 'Abc1234 ', 'Abc1234中']) {
await assert.rejects(AgentDistributionService.registerAgent({ ...params, password }))
}
assert.equal(AgentDistributionService.calls.length, 5)
await AgentDistributionService.sendCode({ phone: params.phone, scene: 'bind_phone' })
assert.deepEqual(AgentDistributionService.calls.at(-1), {
url: '/api/c/v1/auth/send-code',
data: { phone: params.phone, scene: 'bind_phone' },
config: { requestOptions: { withToken: false } }
})
})
test('scan registration masks template errors in both business and HTTP responses and uses only local feedback', async () => {
const { getAgentRegistrationFailureMessage } = await loadModule(
'src/utils/business/agentRegistrationError.ts'
)
for (const code of [1050, 1001, '1050', '1001']) {
const failure = { code, data: null, msg: '企业微信审批模板无效或不可访问' }
for (const value of [
failure,
{ ...failure, data: { detail: 'internal template settings' } },
{ isAxiosError: true, response: { status: 400, data: failure } },
{ isAxiosError: true, response: { status: 500, data: failure } },
{ data: failure }
]) {
assert.equal(getAgentRegistrationFailureMessage(value), '注册失败, 请联系管理员')
}
}
assert.equal(getAgentRegistrationFailureMessage({ code: 1203, msg: '验证码错误' }), '验证码错误')
assert.equal(
getAgentRegistrationFailureMessage({ code: 1204, message: '分销码不可用' }),
'分销码不可用'
)
assert.equal(
getAgentRegistrationFailureMessage({ isAxiosError: true, code: 'ECONNABORTED' }),
'请求超时,结果可能未知,请刷新确认'
)
for (const value of [null, undefined, new Error('network')]) {
assert.equal(typeof getAgentRegistrationFailureMessage(value), 'string')
}
const page = await readFile('src/views/agent-registration/index.vue', 'utf8')
assert.match(page, /ElMessage.error\(getAgentRegistrationFailureMessage\(res\)\)/)
assert.match(
page,
/catch \(error\)\s*\{\s*ElMessage.error\(getAgentRegistrationFailureMessage\(error\)\)/
)
assert.doesNotMatch(page, /ElMessage.error\('分销码不可用'\)/)
assert.match(page, /if \(!valid \|\| submitting.value\) return/)
})
test('scan registration emits exactly one masked message per template failure and retains the form for retry', async () => {
const { getAgentRegistrationFailureMessage } = await loadModule(
'src/utils/business/agentRegistrationError.ts'
)
const passwordValidation = await loadModule('src/utils/validation/loginPassword.ts')
const { descriptor } = parse(await readFile('src/views/agent-registration/index.vue', 'utf8'))
const script = compileScript(descriptor, { id: 'scan-registration-error-test' }).content
const compiled = ts.transpileModule(script, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
}).outputText
for (const code of [1050, 1001]) {
for (const rejected of [false, true]) {
const messages = []
const failure = { code, data: null, msg: '企业微信审批模板无效或不可访问' }
const imports = {
vue: { ...vue, onBeforeUnmount() {} },
'vue-router': { useRoute: () => ({ query: {} }) },
'element-plus': { ElMessage: { error: (message) => messages.push(message) } },
'@/api/modules/agentDistribution': {
AgentDistributionService: {
registerAgent: async () => {
if (rejected) throw { isAxiosError: true, response: { status: 400, data: failure } }
return failure
}
}
},
'@/utils/constants/regionData': { regionData: [] },
'@/utils/validation/loginPassword': passwordValidation,
'@/utils/business/agentRegistrationError': { getAgentRegistrationFailureMessage }
}
const module = { exports: {} }
new Function('require', 'module', 'exports', compiled)(
(name) => {
assert.ok(imports[name], `Unexpected dependency: ${name}`)
return imports[name]
},
module,
module.exports
)
const state = module.exports.default.setup({}, { expose() {} })
Object.assign(state.form, { distribution_code: 'local-test', password: 'Abc1234!' })
let submission
state.formRef.value = {
validate: (callback) => {
submission = callback(true)
}
}
state.handleSubmit()
state.handleSubmit()
await submission
assert.deepEqual(messages, ['注册失败, 请联系管理员'])
assert.equal(state.submitted.value, false)
assert.equal(state.submitting.value, false)
assert.equal(state.form.distribution_code, 'local-test')
assert.equal(state.form.password, 'Abc1234!')
}
}
})
test('scan registration password feedback uses the shared rule rather than treating spaces or Chinese as symbols', async () => {
const page = await readFile('src/views/agent-registration/index.vue', 'utf8')
assert.match(page, /return getNewLoginPasswordError\(pwd\) \? 1 : 3/)
assert.match(page, /密码符合规则/)
assert.match(page, /aria-live="polite"/)
assert.match(page, /password-form-item :deep\(\.el-form-item__error\)[\s\S]*?position: static/)
assert.doesNotMatch(page, /8-32|maxlength="32"/)
assert.match(page, /password: form.password,/)
})
test('account password requests use the right field and omit unchanged optional password', async () => {
const { AccountService } = await loadModule('src/api/modules/account.ts', true)
AccountService.calls = []
await AccountService.updateAccountPassword(12, 'Abc12345')
assert.deepEqual(AccountService.calls[0].data, { new_password: 'Abc12345' })
await AccountService.updateAccount(12, { username: 'operator', password: '' })
assert.deepEqual(AccountService.calls[1].data, { username: 'operator' })
await AccountService.updateAccount(12, { password: 'Abc1234!' })
assert.deepEqual(AccountService.calls[2].data, { password: 'Abc1234!' })
await AccountService.updateAccountPassword(12, 'ABC1234!')
assert.deepEqual(AccountService.calls[3].data, { new_password: 'ABC1234!' })
await assert.rejects(AccountService.updateAccount(12, { password: 'abcdef!!' }))
await assert.rejects(AccountService.updateAccountPassword(12, 'abcd1234'))
assert.equal(AccountService.calls.length, 4)
})
test('change-password dialog is appended to body so its overlay covers the sidebar stacking context', async () => {
const dialog = await readFile(
'src/components/core/layouts/art-header-bar/ChangePasswordDialog.vue',
'utf8'
)
assert.match(dialog, /append-to-body/)
assert.match(dialog, /createNewLoginPasswordRule\(t\('passwordChange.passwordRule'\)\)/)
for (const language of ['zh', 'en']) {
const locale = JSON.parse(await readFile(`src/locales/langs/${language}.json`, 'utf8'))
assert.doesNotMatch(locale.passwordChange.passwordRule, /不允许特殊符号|no special characters/)
}
})
test('writeoff terminal failure blocks recovery but allows resubmission; unknown result stays recoverable', async () => {
const module = await loadModule(
'src/views/finance/employee-collection/employeeCollectionDisplay.ts'
)
assert.equal(module.canRecoverApplicationApproval({ status: 4, recoverable: true }), false)
assert.equal(module.canResubmitApplication({ status: 4 }), true)
assert.equal(
module.canRecoverApplicationApproval({
status: 0,
approval_submission_status: 4,
recoverable: true
}),
true
)
assert.equal(module.canRecoverApplicationApproval({ status: 0, recoverable: false }), false)
assert.equal(module.getApplicationStatusTagType(4), 'danger')
for (const [value, label] of [
[0, '待提交'],
[1, '提交中'],
[2, '已提交'],
[3, '提交失败'],
[4, '结果未知']
]) {
assert.equal(module.getApplicationSubmissionLabel({ approval_submission_status: value }), label)
}
})
test('refund submission failure uses resubmit, not recovery, without changing status 6 anomaly handling', async () => {
const module = await loadModule('src/config/constants/refund.ts')
assert.equal(module.canRecoverRefundApproval({ status: 7, approval_recoverable: true }), false)
assert.equal(module.canResubmitRefund({ status: 7 }), true)
assert.equal(module.canResubmitRefund({ status: 3 }), true)
assert.equal(
module.canRecoverRefundApproval({
status: 1,
submission_status: 4,
approval_recoverable: true
}),
true
)
assert.equal(module.canResubmitRefund({ status: 6, anomaly_flag: 1 }), false)
assert.equal(module.canResubmitRefund({ status: 6, anomaly_flag: 0 }), true)
assert.equal(module.RefundStatusNameMap[7], '审批提交失败')
})
test('admin agent registration does not recover terminal failures and provides status fallback', async () => {
const module = await loadModule('src/types/api/agentDistributionRegistration.ts')
assert.equal(module.canRecoverAgentRegistration({ status: 3, recoverable: true }), false)
assert.equal(module.canRecoverAgentRegistration({ status: 0, recoverable: true }), true)
assert.equal(module.getAgentRegistrationStatusName({ status: 3 }), '审批提交失败')
})
test('offline recharge failure keeps read actions and starts a new order only with existing role/permission', async () => {
const { buildAgentRechargeActions } = await loadModule(
'src/views/finance/agent-recharge/agentRechargeActions.ts'
)
const row = { id: 8, status: 7, payment_method: 'offline', payment_voucher_key: ['voucher'] }
let restarted = false
const options = {
hasAuth: () => true,
canCreateOffline: true,
onRestart: () => {
restarted = true
},
onViewPaymentVoucher() {},
onConfirmPayment() {},
onReject() {},
onTriggerApproval() {}
}
const actions = buildAgentRechargeActions(row, options)
assert.deepEqual(
actions.map((action) => action.label),
['支付凭证', '重新发起']
)
actions[1].handler()
assert.equal(restarted, true)
assert.deepEqual(
buildAgentRechargeActions(row, { ...options, canCreateOffline: false }).map(
(action) => action.label
),
['支付凭证']
)
assert.deepEqual(buildAgentRechargeActions(row, { ...options, hasAuth: () => false }), [])
})
test('withdrawal failure is independently typed from commission clawback and supports resubmit', async () => {
const module = await loadModule('src/config/constants/commission.ts')
assert.equal(module.WithdrawalStatusMap[5].label, '审批提交失败')
assert.equal(module.canResubmitWithdrawal(5), true)
assert.equal(module.canResubmitWithdrawal(3), true)
assert.equal(module.canResubmitWithdrawal(1), false)
assert.equal(module.getCommissionStatusLabel(5), '回溯')
assert.equal(
module.WITHDRAWAL_QUALIFICATION_STATUS_OPTIONS.find((item) => item.value === 4).label,
'审批提交失败'
)
})
test('order payment record status is independent from order status and channels preserve unknown codes', async () => {
const module = await loadModule('src/utils/business/orderPayment.ts')
assert.equal(module.getOrderPaymentRecordStatusName(0), '待支付')
assert.equal(module.getOrderPaymentRecordStatusName(1), '已支付')
assert.equal(module.getOrderPaymentRecordStatusName(2), '已失败')
assert.equal(module.getOrderPaymentRecordStatusName(3), '已退款')
assert.equal(module.getOrderPaymentRecordTagType(2), 'danger')
assert.equal(module.getOrderPaymentChannelName('wechat'), '微信直连 v3')
assert.equal(module.getOrderPaymentChannelName('wechat_v2'), '微信直连 v2')
assert.equal(module.getOrderPaymentChannelName('fuiou'), '富友')
assert.equal(module.getOrderPaymentChannelName(''), '-')
assert.equal(module.getOrderPaymentChannelName('future-channel'), 'future-channel')
})
test('exchange phone conflicts support HTTP error and business response without inventing a missing number', async () => {
const module = await loadModule('src/utils/business/exchangeError.ts')
const failure = {
code: 1202,
data: { phone: '13800000000' },
msg: '新资产已绑定手机号,请先在后台解除该资产的手机号绑定,再重新提交换货申请'
}
assert.equal(module.getExchangePhoneConflictMessage(failure), failure.msg)
assert.equal(
module.getExchangePhoneConflictMessage({ response: { data: failure } }),
module.getExchangePhoneConflictMessage(failure)
)
assert.match(module.getExchangePhoneConflictMessage({ code: 1202 }), /换货申请未完成/)
assert.doesNotMatch(module.getExchangePhoneConflictMessage({ code: 1202 }), /undefined|null/)
assert.equal(module.getExchangePhoneConflictMessage({ code: 1206 }), undefined)
assert.equal(
module.getExchangeBusinessErrorMessage({ response: { data: { message: '迁移失败' } } }),
'迁移失败'
)
const { ExchangeService } = await loadModule('src/api/modules/exchange.ts', true)
ExchangeService.calls = []
const config = { requestOptions: { errorMessageMode: 'none' } }
await ExchangeService.completeExchange(9, config)
assert.deepEqual(ExchangeService.calls[0], {
url: '/api/admin/exchanges/9/complete',
data: {},
config
})
})
test('exchange association handoff carries only the new asset and its bound phone as strings', async () => {
const { getExchangePhoneAssociationQuery } = await loadModule(
'src/utils/business/exchangeError.ts'
)
const newAsset = { asset_identifier: '89860624590014594318', associated_phones: ['19232713115'] }
assert.deepEqual(
getExchangePhoneAssociationQuery({ code: 1202, data: { phone: '19232713115' } }, newAsset),
{
asset_identifier: '89860624590014594318',
phone: '19232713115'
}
)
assert.equal(
getExchangePhoneAssociationQuery({ response: { data: { code: 1202 } } }, newAsset),
undefined
)
assert.equal(getExchangePhoneAssociationQuery({ code: 1206 }, newAsset), undefined)
assert.equal(
getExchangePhoneAssociationQuery({ code: 1202, data: { phone: '19232713115' } }, {}),
undefined
)
assert.equal(
getExchangePhoneAssociationQuery(
{ code: 1202 },
{ asset_identifier: '89860624590014594318', associated_phones: [] }
),
undefined
)
assert.deepEqual(
getExchangePhoneAssociationQuery({ code: 1202, data: { phone: '13900000000' } }, newAsset),
{
asset_identifier: '89860624590014594318',
phone: '13900000000'
}
)
})
test('1202 with data null keeps the original msg and cannot navigate to unbind despite asset phone history', async () => {
const { getExchangePhoneConflictMessage, getExchangePhoneAssociationQuery } = await loadModule(
'src/utils/business/exchangeError.ts'
)
const failure = {
code: 1202,
data: null,
msg: '该资产已完成过换货,如需再次换货请使用换货后的新资产'
}
const newAsset = { asset_identifier: '89860624590014594318', associated_phones: ['19232713115'] }
for (const value of [failure, { response: { data: failure } }]) {
assert.equal(getExchangePhoneConflictMessage(value), failure.msg)
assert.equal(getExchangePhoneAssociationQuery(value, newAsset), undefined)
}
for (const phone of ['', ' ', null, 19232713115]) {
assert.equal(
getExchangePhoneAssociationQuery({ ...failure, data: { phone } }, newAsset),
undefined
)
}
const page = await readFile('src/views/asset-management/exchange-management/index.vue', 'utf8')
assert.match(page, /if \(!canManageAssociations\)/)
assert.match(page, /ElMessageBox.alert\(conflictMessage, '换货提示'/)
})
test('association preselection excludes old assets, different phones and invalid historical rows', async () => {
const {
getPhoneAssetAssociationTarget,
getMatchingPhoneAssetAssociations,
getPhoneAssetUnbindResultName
} = await loadModule('src/utils/business/phoneAssetAssociation.ts')
const target = getPhoneAssetAssociationTarget({
asset_identifier: ' 89860624590014594318 ',
phone: '19232713115'
})
const rows = [
{ id: 1, asset_identifier: target.asset_identifier, phone: target.phone, status: 1 },
{ id: 2, asset_identifier: '89860625770070732445', phone: target.phone, status: 1 },
{ id: 3, asset_identifier: target.asset_identifier, phone: '13900000000', status: 1 },
{ id: 4, asset_identifier: target.asset_identifier, phone: target.phone, status: 0 }
]
assert.deepEqual(
getMatchingPhoneAssetAssociations(rows, target).map((row) => row.id),
[1]
)
assert.deepEqual(getMatchingPhoneAssetAssociations(rows, { ...target, phone: '' }), [])
assert.deepEqual(
getPhoneAssetAssociationTarget({ asset_identifier: ['a', 'b'], phone: ['19232713115'] }),
{ asset_identifier: '', phone: '' }
)
assert.equal(getPhoneAssetUnbindResultName(true), '解绑成功')
assert.equal(getPhoneAssetUnbindResultName(false), '解绑失败')
})
test('association page watches handoff changes, clears stale selections and retains manual unbind confirmation', async () => {
const page = await readFile(
'src/views/asset-management/phone-asset-association/index.vue',
'utf8'
)
assert.match(page, /getPhoneAssetAssociationTarget\(route.query\)/)
assert.match(page, /toggleRowSelection\(row, true\)/)
assert.match(page, /requestId !== listRequestId/)
assert.match(page, /getPhoneAssetUnbindResultName\(row.success\)/)
assert.doesNotMatch(page, /prop="success"/)
assert.match(page, /batchForm.confirmed = false/)
assert.match(page, /batchFormRef.value\?\.validate/)
const table = await readFile('src/components/core/tables/ArtTable.vue', 'utf8')
assert.match(table, /clearSelection:.*clearSelection\(\)/)
})
test('password validation errors accept backend message as well as msg', async () => {
const { normalizeApiError } = await loadModule('src/utils/business/apiError.ts')
for (const field of ['msg', 'message']) {
assert.equal(
normalizeApiError({
isAxiosError: true,
response: { status: 400, data: { [field]: '新密码不合法' } }
}).message,
'新密码不合法'
)
}
})
test('traffic snapshots preserve zero, missing values and MB precision', async () => {
const { formatTrafficAlertMb } = await loadModule('src/utils/business/trafficAlert.ts')
assert.equal(formatTrafficAlertMb(0), '0.00')
assert.equal(formatTrafficAlertMb(1234.567), '1234.57')
for (const value of [undefined, null, NaN]) assert.equal(formatTrafficAlertMb(value), '-')
})
test('CSV download has the new exact four-column header and preserves phone identifiers as text', async () => {
const { SHOP_BUSINESS_OWNER_CSV_TEMPLATE } = await loadModule(
'src/utils/business/shopBusinessOwnerImport.ts'
)
assert.equal(SHOP_BUSINESS_OWNER_CSV_TEMPLATE.charCodeAt(0), 0xfeff)
const [header, instruction] = SHOP_BUSINESS_OWNER_CSV_TEMPLATE.slice(1).trimEnd().split('\r\n')
assert.deepEqual(header.split(','), ['店铺编码', '操作类型', '平台登录账号', '备注'])
assert.equal(instruction.split(',').length, 4)
assert.match(instruction, /手机号/)
assert.match(instruction, /清空留空/)
assert.doesNotMatch(SHOP_BUSINESS_OWNER_CSV_TEMPLATE, /业务员登录账号/)
})
test('affected view contracts preserve raw payment history, package quota and device template', async () => {
const order = await readFile('src/views/order-management/order-list/detail.vue', 'utf8')
assert.match(order, /detailData\.payments \|\| \[\]/)
assert.doesNotMatch(order, /payments\.(filter|sort)/)
const rules = await readFile('src/views/package-management/traffic-alert-rules/index.vue', 'utf8')
assert.match(rules, /item\.real_data_mb/)
assert.doesNotMatch(rules, /row\.real_data_mb|prop: 'real_data_mb'/)
const devices = await readFile(
'src/views/asset-management/task-management/device-task/index.vue',
'utf8'
)
assert.ok(
/独立的 IMEI\s+列/.test(devices),
'import instructions must require the standalone IMEI column'
)
assert.match(devices, /@\/template\/设备导入模板\.xlsx/)
assert.match(devices, /failed_items/)
})

View File

@@ -0,0 +1,271 @@
const time = '2026-10-13T10:00:00+08:00'
const order = {
id: 1,
order_no: 'MOCK-ORDER-001',
order_type: 'single_card',
buyer_type: 'personal',
payment_status: 2,
payment_status_text: '已支付',
payment_method: 'wechat',
total_amount: 1000,
actual_paid_amount: 1000,
third_party_trade_no: 'MOCK-TRADE-001',
payment_channel: 'wechat',
payment_merchant_name: '模拟收款商户',
commission_status: 2,
commission_result: 2,
created_at: time,
updated_at: time,
paid_at: time,
items: [],
payments: [
{
payment_no: 'MOCK-PAY-002',
payment_method: 'wechat',
payment_channel: 'wechat',
payment_merchant_name: '模拟收款商户',
third_party_trade_no: 'MOCK-TRADE-001',
amount: 1000,
status: 1,
created_at: time,
paid_at: time,
expire_at: null
},
{
payment_no: 'MOCK-PAY-001',
payment_method: 'alipay',
payment_channel: 'fuiou',
payment_merchant_name: '模拟收款商户',
third_party_trade_no: '',
amount: 1000,
status: 2,
created_at: time,
paid_at: null,
expire_at: null
}
]
}
const application = {
id: 1,
status: 4,
status_name: '审批提交失败',
recoverable: true,
approval_submission_status: 3,
paid_amount: 1000,
created_at: time
}
const registration = {
id: 1,
status: 3,
recoverable: true,
phone: '13800000000',
username: 'mock-user',
shop_name: '模拟店铺',
created_at: time
}
const rule = {
id: 1,
package_id: 1,
package_name: '模拟套餐',
threshold_percent: 80,
enabled: true,
enabled_name: '启用',
remark: '',
updated_at: time
}
const traffic = {
id: 1,
package_name: '模拟套餐',
threshold_percent: 80,
threshold_mb: 819.2,
used_mb: 0,
limit_mb: 1024,
triggered_at: time,
notification_status: 1,
asset_type: 'iot_card',
asset_identifier: 'MOCK-ASSET'
}
const exchange = {
id: 1,
exchange_no: 'MOCK-EXCHANGE-001',
status: 3,
status_name: '已发货待确认',
status_text: '已发货待确认',
old_asset_type: 'iot_card',
old_asset_identifier: 'MOCK-OLD-ASSET',
new_asset_identifier: 'MOCK-NEW-ASSET',
flow_type: 'shipping',
flow_type_name: '物流换货',
migration_status: 'pending',
created_at: time,
updated_at: time
}
const associations = [
{
id: 101,
asset_id: 1001,
asset_type: 'iot_card',
asset_identifier: exchange.new_asset_identifier,
phone: '13800000000',
status: 1,
status_name: '有效',
established_at: time
},
{
id: 102,
asset_id: 1001,
asset_type: 'iot_card',
asset_identifier: exchange.new_asset_identifier,
phone: '13800000000',
status: 0,
status_name: '已失效',
established_at: time
},
{
id: 103,
asset_id: 1002,
asset_type: 'iot_card',
asset_identifier: exchange.old_asset_identifier,
phone: '13800000000',
status: 1,
status_name: '有效',
established_at: time
},
{
id: 104,
asset_id: 1002,
asset_type: 'iot_card',
asset_identifier: exchange.old_asset_identifier,
phone: '13900000000',
status: 1,
status_name: '有效',
established_at: time
}
]
export const mockApiPlugin = {
name: 'october-local-mock-api',
configureServer(server) {
server.middlewares.use((req, res, next) => {
const url = new URL(req.url, 'http://127.0.0.1')
const path = url.pathname
if (!path.startsWith('/api/')) return next()
if (path === '/api/auth/login' || path === '/api/auth/me') {
const user = {
id: 1,
user_type: 1,
username: '模拟管理员',
phone: '13800000000',
roles: ['R_SUPER']
}
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(
JSON.stringify({
code: 0,
msg: 'mock',
data: {
access_token: 'local-mock-only',
refresh_token: '',
expires_in: 3600,
user,
permissions: ['*:*:*'],
buttons: [],
menus: [{ url: '/asset-management', name: '资产管理' }]
}
})
)
return
}
if (req.method !== 'GET') {
if (path === '/api/admin/exchanges/2/complete') {
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(
JSON.stringify({
code: 1202,
data: null,
msg: '该资产已完成过换货,如需再次换货请使用换货后的新资产'
})
)
return
}
if (path === '/api/admin/phone-asset-associations/batch-unbind') {
let body = ''
req.on('data', (chunk) => {
body += chunk
})
req.on('end', () => {
const request = JSON.parse(body)
const items = request.assets.map((asset) => {
const matches = associations.filter(
(row) =>
row.asset_id === asset.asset_id &&
row.asset_type === asset.asset_type &&
row.status === 1
)
matches.forEach((row) => {
row.status = 0
row.status_name = '已失效'
})
return { ...asset, success: true, unbound_count: matches.length, reason: '' }
})
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(
JSON.stringify({
code: 0,
msg: 'mock',
data: { success_count: items.length, fail_count: 0, items }
})
)
})
return
}
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(
JSON.stringify({
code: 1202,
msg: '新资产已绑定手机号,请先在后台解除该资产的手机号绑定,再重新提交换货申请',
data: { phone: '13800000000' }
})
)
return
}
const page = (items) => ({
items,
list: items,
total: items.length,
page: 1,
size: 20,
page_size: 20
})
let data = page([])
if (path === '/api/admin/phone-asset-associations')
data = page(
associations.filter(
(row) =>
(!url.searchParams.get('asset_identifier') ||
row.asset_identifier === url.searchParams.get('asset_identifier')) &&
(!url.searchParams.get('phone') || row.phone === url.searchParams.get('phone'))
)
)
if (path === '/api/admin/orders/1') data = order
if (path === '/api/admin/exchanges')
data = page([exchange, { ...exchange, id: 2, exchange_no: 'MOCK-EXCHANGE-002' }])
if (path === '/api/admin/exchanges/1') data = exchange
if (path === '/api/admin/exchanges/2')
data = { ...exchange, id: 2, exchange_no: 'MOCK-EXCHANGE-002' }
if (path === '/api/admin/orders') data = page([order])
if (path === '/api/admin/employee-collection-applications/1')
data = { application, allocations: [], attempts: [] }
if (path === '/api/admin/employee-collection-applications') data = page([application])
if (path === '/api/admin/agent-distribution-registrations/1') data = registration
if (path === '/api/admin/agent-distribution-registrations') data = page([registration])
if (path === '/api/admin/package-traffic-alert-rules') data = page([rule])
if (path === '/api/admin/package-traffic-alert-rules/1') data = rule
if (path === '/api/admin/package-traffic-alerts') data = page([traffic])
if (path === '/api/admin/package-traffic-alerts/1') data = traffic
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(JSON.stringify({ code: 0, msg: 'mock', data }))
})
}
}

Some files were not shown because too many files have changed in this diff Show More