Compare commits
333 Commits
master
..
f7e26ee266
| Author | SHA1 | Date | |
|---|---|---|---|
| f7e26ee266 | |||
| 28e7fce11c | |||
| a821d306ac | |||
| 18db4f80bb | |||
| db1f7f2238 | |||
| 4775748447 | |||
| 9048bbb7f8 | |||
| 7c3c9e53a0 | |||
| 4ddb8b47b0 | |||
| 8ab36b1aaf | |||
| f1b7a7aae8 | |||
| bca1335dc6 | |||
| ba48bbc6af | |||
| cbde22ec79 | |||
| 69784b8d32 | |||
| 8543dad514 | |||
| 8a9126e626 | |||
| d8ca8de537 | |||
| aab4ce942c | |||
| 0ecf5cd45a | |||
| 021b0c618b | |||
| f44110fae5 | |||
| ac19637ad6 | |||
| 8672668c33 | |||
| 17236265c6 | |||
| c9efdf8b0e | |||
| c3d43aa26a | |||
| b0462df3c1 | |||
| 967eedcad7 | |||
| 98e0e54309 | |||
| eeb27e21ed | |||
| c85e5b278f | |||
| 8ab647c419 | |||
| 95ccb00d25 | |||
| ee9cf5f8c6 | |||
| e98a1a1207 | |||
| ea37d82d73 | |||
| 9835831415 | |||
| 080625567b | |||
| 266c0f17c1 | |||
| 225d13fb6e | |||
| 2ed1250604 | |||
| ca4a2cd07a | |||
| 73ac9187a6 | |||
| 7503e3fa8b | |||
| 532438faba | |||
| a1376b51b0 | |||
| 1e087c1aae | |||
| 2e2de02476 | |||
| aeb4e1710c | |||
| b4b80cb572 | |||
| 70e902e7ea | |||
| 14cebf22c3 | |||
| 73d25fcbcb | |||
| 01ecde45c5 | |||
| a2ebfc0b81 | |||
| 1dc2cac19a | |||
| 14db1e0cb1 | |||
| 01f4dbb83a | |||
| 0d63d6d75a | |||
| fe692fcd1d | |||
| 79b177b345 | |||
| 18b0c2d211 | |||
| e4e01c1686 | |||
| 648e7d2f14 | |||
| 0d78d63437 | |||
| 289b1c67ce | |||
| 5c990e651e | |||
| 52095eb992 | |||
| a4e4745921 | |||
| a2d0bd3c1c | |||
| b9275bc174 | |||
| 683a3934fc | |||
| e5d0b2d9ab | |||
| b0514c3e9a | |||
| d618a5abf0 | |||
| 8be12ca9bc | |||
| 5ca46b0a57 | |||
| afeeb8327c | |||
| a7d8f8be6c | |||
| 4d2da94692 | |||
| 8cd1a4e2b1 | |||
| b746812e23 | |||
| 3fbbf87c10 | |||
| b0e97f21a4 | |||
| a00ff1804c | |||
| c3810fdb7b | |||
| 203937335d | |||
| b16c63225f | |||
| 710b953120 | |||
| 45a45dc0fe | |||
| 3ca569ed1e | |||
| c315bb350c | |||
| 111f30d150 | |||
| 6d398b66bc | |||
| f46c231323 | |||
| 934919c699 | |||
| 12d84a22e4 | |||
| 9d4810eace | |||
| dc457aff9e | |||
| 3ce66a59ee | |||
| 578847d596 | |||
| 147b324658 | |||
| 6416c14f20 | |||
| e47c87f3a3 | |||
| add6e6aeb5 | |||
| 1ecce13814 | |||
| 7968cef8c3 | |||
| 7c2b154c20 | |||
| 34148b5d8a | |||
| 7ba916f00c | |||
| 79e408333d | |||
| af4f4a9ed4 | |||
| 74a7cd22b0 | |||
| aece8123c3 | |||
| e1cca219b8 | |||
| 70658041a5 | |||
| 4419c5bacd | |||
| 668226a99d | |||
| 4eec0dd5a4 | |||
| b315d11c28 | |||
| 8e60f50616 | |||
| 72faf0433a | |||
| f85e3be40e | |||
| 3616d64735 | |||
| 7f9116f12a | |||
| 01bae23df5 | |||
| 11f0d2c745 | |||
| b073bbe97d | |||
| 955a6439a0 | |||
| c6ecfb5b77 | |||
| 172917ac41 | |||
| ad2bfcd2f5 | |||
| a5f6898d06 | |||
| 83bd5839d0 | |||
| 83bc90ecf2 | |||
| 6ea3a960e7 | |||
| cbfc29e953 | |||
| fd2013b448 | |||
| b66465aa6a | |||
| a684fde472 | |||
| fbd1a4dbea | |||
| 824fa7b76c | |||
| be8a8492a9 | |||
| b429721070 | |||
| b352eea21d | |||
| 73d1dff21d | |||
| 51bf0aaa8c | |||
| d7d1021ec3 | |||
| 28a752265c | |||
| 735234f7bc | |||
| 1d9d138423 | |||
| 8c5edc6ad6 | |||
| e09ce6d13b | |||
| ee6fb5d33a | |||
| 46e55fa623 | |||
| cd2b437be5 | |||
| a92d1af4f2 | |||
| a504e7a13b | |||
| 1be28f10e9 | |||
| 325687d532 | |||
| 9c16c9c589 | |||
| 9760d1171c | |||
| 8711b205cf | |||
| d42ed57119 | |||
| e316adca1f | |||
| 18208f691c | |||
| 0457fbfac0 | |||
| c06a4d0e06 | |||
| 58df800685 | |||
| f21934e55b | |||
| 7c198f7d6f | |||
| 515135c120 | |||
| ec4d1b2567 | |||
| 42bdd59c71 | |||
| 4ff4d8cfdc | |||
| 8be85fd332 | |||
| e4bf104ae2 | |||
| b96b136fa3 | |||
| 5105bf7049 | |||
| 02ddfc7a76 | |||
| 08997e9e20 | |||
| 8defef904f | |||
| 9146d17625 | |||
| 13c3a04a48 | |||
| 1aca3d6152 | |||
| 60a6494260 | |||
| 052bb31aea | |||
| 995e2ee65a | |||
| 225b525ba1 | |||
| 7f83bceba1 | |||
| e1543416e3 | |||
| 1eb622d33f | |||
| 0b57aea5f6 | |||
| 5d8ee8fe79 | |||
| a04c2f9a19 | |||
| 6f1b8e46f5 | |||
| c352c34501 | |||
| f9b2d2da25 | |||
| 5c9671df44 | |||
| 26a920a1cc | |||
| 8a8d3c5cd9 | |||
| e695fd5184 | |||
| d272afae1c | |||
| 0caf62c3d2 | |||
| 03e697f5d3 | |||
| 326f78705d | |||
| c502afb588 | |||
| afa8e44909 | |||
| 3fada5d198 | |||
| 72fdb1841c | |||
| c0fdea6570 | |||
| 34bc980eea | |||
| 0391cb223f | |||
| 2dab555ca5 | |||
| b25111e4b4 | |||
| d537924aa9 | |||
| 2f2db4986e | |||
| dc6ecc1edf | |||
| 6f970b3783 | |||
| 95d5c82474 | |||
| 87507708ce | |||
| f6e83352d7 | |||
| c6ae7ca170 | |||
| 46f46039ea | |||
| 6894f9cc57 | |||
| 8c4a6cd12a | |||
| 524d8763ce | |||
| 236b73755c | |||
| 1e845a1510 | |||
| 0341838d19 | |||
| b04b05e4da | |||
| d691e53886 | |||
| ea35273597 | |||
| 72c8167472 | |||
| dabb278170 | |||
| 9b1138c83e | |||
| 7b12cebb45 | |||
| dc5e23892f | |||
| 9d75d673f8 | |||
| 4f8cbc3e38 | |||
| 8d97f5318c | |||
| 3ffbb2b004 | |||
| 34ed15a9bd | |||
| 110f407ae2 | |||
| 4b6295dd44 | |||
| 8db9f3a408 | |||
| 01116d5607 | |||
| 2ae720ae09 | |||
| 07904a29aa | |||
| f87c37528b | |||
| 8d683a791d | |||
| 71b09a89de | |||
| ef0e0df0ac | |||
| d5764f3b50 | |||
| ac07416352 | |||
| 4e5ed76cb6 | |||
| 025ca6d4fd | |||
| ecc8b6ce6c | |||
| 951a353881 | |||
| 9ad6e037dc | |||
| eb04caccf1 | |||
| 4a58b366b6 | |||
| cd84def61d | |||
| bbc833f2c9 | |||
| d8098b0378 | |||
| 325c2f7c82 | |||
| 62d30ec190 | |||
| 728eea4b83 | |||
| d0d3c6ee67 | |||
| e53eaf738e | |||
| 21b6b5b270 | |||
| ad2bb0a6ea | |||
| 365050b890 | |||
| 7589b4e418 | |||
| 73392a9b83 | |||
| b400b494ad | |||
| c47c03fde4 | |||
| 9a59dac6d0 | |||
| 86fd9475e4 | |||
| 03a85d5523 | |||
| 2d0d1d3461 | |||
| ccaec4a984 | |||
| 169ba7edb6 | |||
| 0327d1cc51 | |||
| e02ddab599 | |||
| 336338cff5 | |||
| acff31e652 | |||
| ad304a6880 | |||
| cb34788e53 | |||
| 13b0ffb5d8 | |||
| c9947c4ac8 | |||
| afffb7aad2 | |||
| 9720453ac4 | |||
| 1ff6d5220e | |||
| 46d91fd8ca | |||
| a24db2f73c | |||
| ca9537f862 | |||
| 94ae7e68ff | |||
| 94e1930538 | |||
| 5bbe5a3077 | |||
| 8cead01270 | |||
| 99fc14b9f9 | |||
| d3671206e1 | |||
| 0a8202788b | |||
| 855f1affd9 | |||
| 5a294e5c85 | |||
| df606a1087 | |||
| ece3552b89 | |||
| 4df3945131 | |||
| 6eb0f33421 | |||
| 25ce9f74b8 | |||
| 0f1f471590 | |||
| d9487b6885 | |||
| 9845ab8f2a | |||
| 6fa130386a | |||
| 53df8b9971 | |||
| d6625762cf | |||
| cb3b9e9cfe | |||
| 3d39236b13 | |||
| 9e57fa5762 | |||
| 9c6232bc85 | |||
| d3c7938627 | |||
| 06256946fa | |||
| 2042d386e2 | |||
| 7176754564 | |||
| a20222192e | |||
| a5c2681e88 | |||
| 5e2f750359 | |||
| 27602890ab | |||
| dfe0d652ce | |||
| 24076adf98 | |||
| 15a78abc1b |
@@ -1,12 +0,0 @@
|
||||
# 仓库内文本 blob 全部是 LF(2026-09-28 取证:git grep -P '\r' 在 HEAD 上 0 命中),
|
||||
# 但开发机 core.autocrlf=true 会在检出时改写为 CRLF。快照类测试拿 Files.readString 读
|
||||
# golden 后与代码里 append('\n') 生成的字符串逐字节比对,检出形态一变就整片红。
|
||||
# 这里把"断言会读到的文本"钉成 LF,checkout 时不再被 autocrlf 转换。
|
||||
# 只列扩展名、不写 `* text`:避免 git 去归一化 jar/png/zip 等二进制产物。
|
||||
*.txt text eol=lf
|
||||
*.md text eol=lf
|
||||
*.sql text eol=lf
|
||||
*.yml text eol=lf
|
||||
*.yaml text eol=lf
|
||||
*.json text eol=lf
|
||||
*.sh text eol=lf
|
||||
@@ -14,69 +14,13 @@ jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
container: maven:3.9-eclipse-temurin-21
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Test (Java: unit + contract + ArchUnit)
|
||||
working-directory: backend-java
|
||||
run: mvn test -q
|
||||
- name: Package
|
||||
working-directory: backend-java
|
||||
- name: Build with Maven
|
||||
run: mvn clean package -DskipTests -q
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: backend-jar
|
||||
path: backend-java/target/*.jar
|
||||
|
||||
frontend-test:
|
||||
runs-on: ubuntu-latest
|
||||
container: node:24-alpine
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Install dependencies
|
||||
working-directory: frontend-vue
|
||||
run: npm ci
|
||||
- name: Type check (vue-tsc)
|
||||
working-directory: frontend-vue
|
||||
run: npm run build
|
||||
- name: Frontend contract tests (npm test → node --test)
|
||||
working-directory: frontend-vue
|
||||
run: npm test
|
||||
|
||||
admin-frontend-test:
|
||||
# 2026-10-08 加:后管此前是 0 CI 覆盖(本 workflow 只有 backend-java 与 frontend-vue 两个 job,
|
||||
# `.gitea` 下 grep admin-frontend-vue 命中 0)⇒ 1,7xx 例契约/棘轮用例与 vue-tsc 只能手跑。
|
||||
# 本机实跑过的:npm install(112 包 3m34s,再 72 包 2m35s)→ vue-tsc --noEmit 退出 0(49.7s)
|
||||
# → node --test tests/*.test.ts 1,764 例全绿 → vitest run 挂载例 7 例全绿 → npm ci 复现通过。
|
||||
# 没跑的那半:`npm run build` 的后半 `vite build` 本机没执行——它会重写 dist/,
|
||||
# 而 dist/ 正是 scripts/_deploy_admin_vue.py 的发布输入,脏树上构建会把别人未提交的改动带进产物。
|
||||
#
|
||||
# ⚠ 前提未证实,别把这个 job 当成"CI 会跑":Gitea 26.4.5 的匿名接口
|
||||
# /api/v1/repos/super/crawler-plugin/actions/tasks 只列得出 3 次 run,最后一个停在
|
||||
# 2026-08-11T14:50(三次 status 全为 failure);此后 origin/master 又推进了 1,131 笔
|
||||
# (含 2026-10-08 12:14:57 那次 push,仓库 updated_at 也是这一刻)却没有产生任何新 run。
|
||||
# ⇒ 只能证到"这条 workflow 历史上真被 runner 执行过",证不到"现在还在执行"。
|
||||
# 要让它真兜住这一面,先恢复 runner / 确认 Actions 未被关停。
|
||||
runs-on: ubuntu-latest
|
||||
container: node:24-alpine
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Install dependencies
|
||||
working-directory: admin-frontend-vue
|
||||
run: npm ci
|
||||
- name: Type check + build (vue-tsc --noEmit && vite build)
|
||||
working-directory: admin-frontend-vue
|
||||
run: npm run build
|
||||
- name: Admin contract & ratchet tests (node --test, 不是 vitest)
|
||||
working-directory: admin-frontend-vue
|
||||
run: node --test tests/*.test.ts
|
||||
- name: Admin component mount tests (vitest + @vue/test-utils + jsdom)
|
||||
working-directory: admin-frontend-vue
|
||||
run: npm run test:mount
|
||||
|
||||
path: target/*.jar
|
||||
|
||||
-72
@@ -14,8 +14,6 @@ backend-java/target/
|
||||
backend-java/data/
|
||||
backend-java/*.log
|
||||
backend-java/logs/
|
||||
# 会话级诊断脚本残渣(2026-11-03 瘦身审计 BD-8:_diag_keyword_sync.py 有误提交风险)
|
||||
backend-java/tmp/
|
||||
backend-java/src/main/resources/application-local.yml
|
||||
backend-java/.idea/
|
||||
backend-java/*.iml
|
||||
@@ -102,7 +100,6 @@ ipython_config.py
|
||||
*.sqlite3
|
||||
|
||||
# ===== Misc =====
|
||||
.playwright-cli/
|
||||
desktop/
|
||||
ERP-Demo/
|
||||
xlsx/
|
||||
@@ -113,72 +110,3 @@ OPS_REDIS_MYSQL_OPTIMIZATION_NOTES.md
|
||||
架构.md
|
||||
*ts.%
|
||||
.omc
|
||||
|
||||
# ===== 规划文档 =====
|
||||
# docs/plans/ 与 backend-java/docs/plans/ 已从「本地不入库」改为入库(2026-10-04 用户拍定):
|
||||
# 实施计划要跨会话留存,被 gitignore 的文件在干净 worktree 出包时不存在,护栏用例也读不到。
|
||||
docs/*plan*.md
|
||||
backend-java/docs/*plan*.md
|
||||
backend-java/docs/specs/
|
||||
backend-java/docs/*audit*.md
|
||||
|
||||
# ===== 进度/规划工具(本地使用,不入库)=====
|
||||
check_progress.py
|
||||
progress.json
|
||||
progress_*.json
|
||||
|
||||
# ===== 本地预览工具(不入库)=====
|
||||
backend/_preview_mock.py
|
||||
|
||||
# ===== 战役辅助脚本与本地数据(不入库)=====
|
||||
scripts/test_task_*.py
|
||||
scripts/*_scan.py
|
||||
scripts/*_migration.py
|
||||
data/logs/
|
||||
|
||||
# ===== 本地临时目录(出包 worktree / 验证日志,不入库)=====
|
||||
/tmp/
|
||||
|
||||
# 生产库转储永不再入库(本体只留 backend-java/data/,那里已被忽略)
|
||||
backend-java/src/main/resources/db/aiimage.sql
|
||||
|
||||
# 打包前由 scripts/_git_stamp.py write 生成,随 jar 进 BOOT-INF/classes/;
|
||||
# 入库会变成"孤儿构建产物"(10-07 那笔 target/classes 里的 V148 就是这个形状造成的宕机)
|
||||
backend-java/src/main/resources/git.properties
|
||||
|
||||
# ===== 2026-10-15 瘦身审计 P0-6:补仓根日志与压缩包(§2 那 10 支历史大对象就从这个口子进来的)
|
||||
*.log
|
||||
/*.log
|
||||
*.zip
|
||||
app/update/
|
||||
app/user_data/
|
||||
target/
|
||||
*.pid
|
||||
|
||||
# ===== 2026-10-18 重构蓝图 Phase 1:只堵未来的口子(审计报告 §4.1(b))=====
|
||||
# 本仓此前 0 支构建产物入库(实测 git ls-files -i -c --exclude-standard=0),下面每条都是
|
||||
# "今天没踩到、将来会踩到"的产物面;纯新增忽略,不改任何现存规则的行为。
|
||||
# 注意:gitignore 的行内 # 不是注释(会被当模式的一部分),所以说明一律单起一行。
|
||||
# node_modules:原只写了 frontend-vue/node_modules/,admin 靠子文件兜 ⇒ 提为通用
|
||||
node_modules/
|
||||
.vite/
|
||||
**/.vite/
|
||||
playwright-report/
|
||||
blob-report/
|
||||
test-results/
|
||||
surefire-reports/
|
||||
failsafe-reports/
|
||||
# Java 编译产物此前没人挡(原只有 *$py.class)
|
||||
*.class
|
||||
*.tsbuildinfo
|
||||
*.pyd
|
||||
# Windows 原生扩展与打包残留;本仓 0 支跟踪件用这些后缀(亲测 git ls-files 计数为 0)
|
||||
*.dll
|
||||
# 关键:*.log 匹配不到 aiimage-backend.log.2026-10-11.0 这类轮转名
|
||||
*.log.*
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
desktop.ini
|
||||
# ⚠ 报告另建议把遗留的 lib//parts//var/ 收窄成 /build/、/dist/ 式根锚定前缀,本轮不做:
|
||||
# 实测盘上有 53 个 lib、87 个 dist、19 个 bin 目录,收窄等于把今天被挡住的产物一次性放成 ?? 噪声,
|
||||
# 与 Phase 1「零行为变更」的定性冲突;而它们造成的实害今天是 0(ls-files -i -c 亲测)。单独拍板。
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.env*
|
||||
!.env.example
|
||||
test-results/
|
||||
vite-dev.log
|
||||
@@ -1,39 +0,0 @@
|
||||
# Admin Frontend Vue
|
||||
|
||||
独立的后台管理前端工程,与客户端 `frontend-vue` 完全分离。
|
||||
|
||||
## 本地开发
|
||||
|
||||
```powershell
|
||||
npm install
|
||||
$env:VITE_API_TARGET = "http://127.0.0.1:18080"
|
||||
npm run dev
|
||||
```
|
||||
|
||||
开发入口:`http://localhost:5174/admin-vue/`
|
||||
|
||||
## 构建
|
||||
|
||||
```powershell
|
||||
npm run build
|
||||
npm test
|
||||
```
|
||||
|
||||
构建产物在 `dist/`,部署到 Nginx 的 `/admin-vue/` 根目录。该工程不写入客户端的 `new_web_source`,也不打进 Java JAR。
|
||||
|
||||
## 运行时契约
|
||||
|
||||
- 登录态:复用同源 Cookie/Session。
|
||||
- 当前用户:`GET /api/admin/current-user`。
|
||||
- 菜单树:`GET /api/admin/current-user/menus`,Java 返回树形菜单。
|
||||
- 退出登录:`POST /api/admin/logout`。
|
||||
- 前端路由:History 模式,基准路径 `/admin-vue/`。
|
||||
- 权限粒度:菜单/页面级,不定义按钮级权限。
|
||||
|
||||
## 首批页面
|
||||
|
||||
- `/admin-vue/account/users`
|
||||
- `/admin-vue/account/menus`
|
||||
- `/admin-vue/account/groups`
|
||||
|
||||
当前首批页面已接入 Java 现有用户、菜单和数据权限分组 API;Java 菜单接口完成树形响应和 Flyway 菜单迁移后,路由权限守卫即可按最终菜单树工作。
|
||||
@@ -1,5 +0,0 @@
|
||||
# Flask 管理能力移除 / Nginx 入口切换(module 11)
|
||||
|
||||
- /admin 由 Nginx 302 → /admin-vue/;Java 静态 admin.html/login.html 副本随发布清理。
|
||||
- Flask 管理页面/API 与版本蓝图在发布前已由 Java/Vue 覆盖(07/09 模块),此处由发布管线停用。
|
||||
- 发布验收见 tests/live/task-200/220/240(RELEASE_SMOKE=1 触发)。
|
||||
@@ -1,29 +0,0 @@
|
||||
# 仅作部署参考,实际 server/root/upstream 按环境调整。
|
||||
|
||||
location = /admin {
|
||||
return 302 /admin-vue/;
|
||||
}
|
||||
|
||||
location /admin-vue/assets/ {
|
||||
alias /var/www/admin-vue/assets/;
|
||||
try_files $uri =404;
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
}
|
||||
|
||||
location /admin-vue/ {
|
||||
alias /var/www/admin-vue/;
|
||||
try_files $uri $uri/ /admin-vue/index.html;
|
||||
add_header Cache-Control "no-cache";
|
||||
}
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://java_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Cookie $http_cookie;
|
||||
proxy_read_timeout 60s;
|
||||
proxy_send_timeout 60s;
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
# Admin Vue 发布目录结构(module 10)
|
||||
|
||||
发布目标:
|
||||
|
||||
```text
|
||||
/var/www/
|
||||
├── admin-vue-<ts>/ # 新版本临时发布目录
|
||||
│ ├── index.html
|
||||
│ └── assets/...
|
||||
├── admin-vue-prev/ # 上一版本(回滚保留)
|
||||
└── admin-vue -> admin-vue-<ts> # Nginx 根目录符号链接(原子切换)
|
||||
```
|
||||
|
||||
发布过程:
|
||||
|
||||
1. `npm ci && npm run build` 产出 `dist/`。
|
||||
2. 运行 `deploy/verify-dist.mjs`:校验 `index.html` 引用完整、assets 存在、base 为 `/admin-vue/`。
|
||||
3. 上传 `dist/` 至 `admin-vue-<ts>/`。
|
||||
4. `ln -sfn admin-vue-<ts> /var/www/admin-vue` 原子切换。
|
||||
5. 旧版本目录保留为 `admin-vue-prev`,用于快速回滚。
|
||||
@@ -1,27 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
// Admin Vue 构建产物清单校验(module 10):base=/admin-vue/ 且 index.html 引用的资源均存在。
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
||||
import { join, resolve } from 'node:path'
|
||||
|
||||
const root = resolve(process.cwd())
|
||||
const dist = join(root, 'dist')
|
||||
const index = join(dist, 'index.html')
|
||||
|
||||
function fail(message) {
|
||||
console.error(`[verify-dist] ${message}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (!existsSync(index)) fail('缺少 dist/index.html(请先 npm run build)')
|
||||
|
||||
const html = readFileSync(index, 'utf8')
|
||||
if (!html.includes('/admin-vue/')) fail('index.html 资源引用未包含 base=/admin-vue/')
|
||||
|
||||
const assetsDir = join(dist, 'assets')
|
||||
const assets = existsSync(assetsDir) ? readdirSync(assetsDir) : []
|
||||
const refs = [...html.matchAll(/(?:src|href)="\/admin-vue\/assets\/([^"]+)"/g)].map((m) => m[1])
|
||||
for (const ref of refs) {
|
||||
if (!assets.includes(ref)) fail(`index.html 引用的资源缺失: assets/${ref}`)
|
||||
}
|
||||
|
||||
console.log(`[verify-dist] ok: base=/admin-vue/, assets=${assets.length}, refs=${refs.length}`)
|
||||
@@ -1,47 +0,0 @@
|
||||
import { expect, test, type Page } from '@playwright/test'
|
||||
|
||||
// module 13 task 249:壳层换皮真实验收 —— 蓝白浅色变量生效、角色胶囊/次级退出、
|
||||
// 代表页跳转无 pageerror。断言用 CSS 变量与 DOM 结构,避免仅截图无断言。
|
||||
|
||||
async function openAdmin(page: Page) {
|
||||
await page.goto('/admin-vue/')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
}
|
||||
|
||||
test('test_task_249_shell_light_normal_primary_path', async ({ page }) => {
|
||||
await openAdmin(page)
|
||||
const vars = await page.evaluate(() => {
|
||||
const s = getComputedStyle(document.documentElement)
|
||||
return {
|
||||
sidebar: s.getPropertyValue('--admin-sidebar').trim(),
|
||||
primary: s.getPropertyValue('--admin-primary').trim(),
|
||||
}
|
||||
})
|
||||
expect(vars.sidebar).toBe('#f8fbfe')
|
||||
expect(vars.primary).toBe('#4f78a5')
|
||||
await expect(page.locator('.admin-user-role')).toHaveText('超级管理员')
|
||||
})
|
||||
|
||||
test('test_task_249_shell_light_normal_variant_input', async ({ page }) => {
|
||||
await openAdmin(page)
|
||||
await expect(page.locator('.admin-user-logout')).toBeVisible()
|
||||
await expect(page.locator('.admin-kicker')).toHaveText('运营管理控制台')
|
||||
})
|
||||
|
||||
test('test_task_249_shell_light_boundary_empty_input', async ({ page }) => {
|
||||
// 未知路由仍进 404,不因换皮破坏。
|
||||
await page.goto('/admin-vue/definitely/not/exists')
|
||||
await expect(page.locator('.not-found')).toContainText('404')
|
||||
})
|
||||
|
||||
test('test_task_249_shell_light_invalid_input_rejected', async ({ page }) => {
|
||||
// 代表页跳转整段无未捕获脚本错误。
|
||||
const errors: string[] = []
|
||||
page.on('pageerror', (error) => errors.push(error.message))
|
||||
await openAdmin(page)
|
||||
await page.goto('/admin-vue/account/menus')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('菜单管理')
|
||||
await page.goto('/admin-vue/account/groups')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('数据权限分组')
|
||||
expect(errors).toEqual([])
|
||||
})
|
||||
@@ -1,97 +0,0 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { expect, test } from '@playwright/test'
|
||||
|
||||
// 撞款控制台(DuplicateCheckPage)像素级复刻 reference asin-store-console 的真浏览器验收:
|
||||
// mock 后端跑真实数据渲染,无 pageerror;并截图本页与 reference 离线页供人工比对。
|
||||
|
||||
const REFERENCE = 'D:\\todesk\\副业\\数富AI\\crawler-plugin\\reference\\asin-store-console\\asin-store-console\\index.html'
|
||||
|
||||
test('test_dup_console_render_dup_tab_normal_primary_path', async ({ page }) => {
|
||||
const errors: string[] = []
|
||||
page.on('pageerror', (error) => errors.push(error.message))
|
||||
|
||||
await page.goto('/admin-vue/shop-center/duplicate-check')
|
||||
await expect(page.locator('.dup-head h2')).toHaveText('店铺数据撞款监控')
|
||||
// KPI + 矩阵行 + 撞款卡片都渲染出真实 mock 数据
|
||||
await expect(page.locator('.kpi')).toHaveCount(7)
|
||||
await expect(page.locator('table.matrix tbody tr').first()).toBeVisible({ timeout: 15000 })
|
||||
await expect(page.locator('.dup-card').first()).toBeVisible()
|
||||
// 分组撞款:切到「分组撞款」出现分组 chips
|
||||
await page.getByRole('button', { name: /分组撞款/ }).click()
|
||||
await expect(page.locator('.g-chip').first()).toBeVisible()
|
||||
expect(errors).toEqual([])
|
||||
await page.screenshot({ path: 'test-results/dup-console-admin-dup.jpg' })
|
||||
})
|
||||
|
||||
test('test_dup_console_render_ledger_tab_normal_variant_input', async ({ page }) => {
|
||||
const errors: string[] = []
|
||||
page.on('pageerror', (error) => errors.push(error.message))
|
||||
|
||||
await page.goto('/admin-vue/shop-center/duplicate-check')
|
||||
await expect(page.locator('.dup-head h2')).toHaveText('店铺数据撞款监控')
|
||||
await page.getByRole('button', { name: /全部ASIN台账/ }).click()
|
||||
await expect(page.locator('table.ledger tbody tr').first()).toBeVisible({ timeout: 15000 })
|
||||
// 台账 tab 下页面同时有「店铺上架分布」分页器(常显,见 tests/align-dup-console.test.ts)与台账分页器,
|
||||
// 全页 .old-pagination 会命中 2 个元素触发 strict mode;限定到台账表格(.table-wrap)紧邻的分页器。
|
||||
await expect(page.locator('.table-wrap + .old-pagination')).toBeVisible()
|
||||
expect(errors).toEqual([])
|
||||
await page.locator('.table-wrap').screenshot({ path: 'test-results/dup-console-admin-ledger.jpg' })
|
||||
})
|
||||
|
||||
test('test_dup_console_palette_matches_reference_tokens', async ({ page }) => {
|
||||
// reference 设计令牌在页面落定:主蓝 #2E5BE6、红 #D63A4A、弱红底、单元底色等(按钮蓝白统一为 #4f78a5)。
|
||||
await page.goto('/admin-vue/shop-center/duplicate-check')
|
||||
await expect(page.locator('.kpi')).toHaveCount(7)
|
||||
const got = await page.evaluate(() => {
|
||||
const cs = (sel, prop) => {
|
||||
const el = document.querySelector(sel)
|
||||
return el ? getComputedStyle(el)[prop] : null
|
||||
}
|
||||
return {
|
||||
btnPrimary: cs('.btn-primary', 'backgroundColor'),
|
||||
btnPrimaryColor: cs('.btn-primary', 'color'),
|
||||
kpiDanger: cs('.kpi.danger .k-value', 'color'),
|
||||
kpiPrimary: cs('.kpi.primary .k-value', 'color'),
|
||||
mCell: cs('.m-cell', 'backgroundColor'),
|
||||
mCellText: cs('.m-cell', 'color'),
|
||||
badgeDup: cs('.badge.dup', 'backgroundColor'),
|
||||
badgeSingle: cs('.badge.single', 'backgroundColor'),
|
||||
kSub: cs('.kpi .k-sub', 'color'),
|
||||
selectBorder: cs('.f-group select', 'borderColor'),
|
||||
kDotDanger: cs('.kpi.danger .k-dot', 'backgroundColor'),
|
||||
}
|
||||
})
|
||||
expect(got.btnPrimary).toBe('rgb(79, 120, 165)') // 全站按钮主色统一 #4f78a5(d385d999 起)
|
||||
expect(got.btnPrimaryColor).toBe('rgb(255, 255, 255)')
|
||||
expect(got.kpiDanger).toBe('rgb(214, 58, 74)')
|
||||
expect(got.kpiPrimary).toBe('rgb(46, 91, 230)')
|
||||
expect(got.mCell).toBe('rgb(234, 240, 255)')
|
||||
expect(got.mCellText).toBe('rgb(46, 91, 230)')
|
||||
expect(got.badgeDup).toBe('rgb(253, 235, 237)')
|
||||
expect(got.badgeSingle).toBe('rgb(231, 247, 239)')
|
||||
expect(got.kSub).toBe('rgb(152, 161, 177)')
|
||||
expect(got.selectBorder).toBe('rgb(213, 219, 230)')
|
||||
expect(got.kDotDanger).toBe('rgb(214, 58, 74)')
|
||||
})
|
||||
|
||||
test('test_dup_console_structure_matches_reference', async ({ page }) => {
|
||||
// 结构对齐:矩阵列=可见店铺数、台账列=reference 10 列、分组说明抽屉内 4 列。
|
||||
await page.goto('/admin-vue/shop-center/duplicate-check')
|
||||
await expect(page.locator('.kpi')).toHaveCount(7)
|
||||
await expect(page.locator('table.matrix tbody tr').first()).toBeVisible({ timeout: 15000 })
|
||||
const matrixHeaders = await page.locator('table.matrix thead th').count()
|
||||
expect(matrixHeaders).toBe(8) // ASIN + 品牌 + 6 家店
|
||||
await page.getByRole('button', { name: /全部ASIN台账/ }).click()
|
||||
await expect(page.locator('table.ledger tbody tr').first()).toBeVisible({ timeout: 15000 })
|
||||
const ledgerHeaders = await page.locator('table.ledger thead th').count()
|
||||
expect(ledgerHeaders).toBe(10)
|
||||
})
|
||||
|
||||
test('test_dup_console_reference_screenshot', async ({ page }) => {
|
||||
// reference 离线原型截图:仅供人工像素比对(不接入应用路由)。
|
||||
test.skip(!existsSync(REFERENCE), 'reference 原型不在本机,跳过比对')
|
||||
await page.goto(pathToFileURL(REFERENCE).href)
|
||||
await expect(page.locator('.kpi').first()).toBeVisible({ timeout: 15000 })
|
||||
await page.screenshot({ path: 'test-results/dup-console-reference.jpg' })
|
||||
})
|
||||
@@ -1,44 +0,0 @@
|
||||
import { expect, test, type Page } from '@playwright/test'
|
||||
|
||||
// 后台管理列表「创建时间 + 更新时间」两列验收(2026-09-19 需求):
|
||||
// 8 个实体管理列表统一展示创建/更新时间,数据取自各列表 VO。
|
||||
// mock 夹具统一给 createdAt=2026-03-01 09:15:00、updatedAt=2026-09-18 16:42:30,
|
||||
// 页面统一经 formatDateTime 归一为「YYYY-MM-DD HH:mm:ss」。
|
||||
|
||||
const CREATED = '2026-03-01 09:15:00'
|
||||
const UPDATED = '2026-09-18 16:42:30'
|
||||
|
||||
const PAGES: Array<{ title: string; path: string; heading: string }> = [
|
||||
{ title: '用户管理', path: '/admin-vue/account/users', heading: '用户列表' },
|
||||
{ title: '菜单管理', path: '/admin-vue/account/menus', heading: '菜单' },
|
||||
{ title: '密钥管理', path: '/admin-vue/account/user-secrets', heading: '用户密钥列表' },
|
||||
{ title: '品牌数据库', path: '/admin-vue/asin-center/invalid', heading: '品牌数据列表' },
|
||||
{ title: '数据去重总数据', path: '/admin-vue/asin-center/registry', heading: '数据去重总数据' },
|
||||
{ title: '查询ASIN', path: '/admin-vue/asin-center/query', heading: '查询' },
|
||||
{ title: '最低价ASIN', path: '/admin-vue/asin-center/skip-price', heading: '最低价' },
|
||||
{ title: '商品类目', path: '/admin-vue/asin-center/categories', heading: '商品类目' },
|
||||
]
|
||||
|
||||
async function openPage(page: Page, path: string) {
|
||||
await page.goto(path)
|
||||
await expect(page.locator('.panel-box table tbody tr').first()).toBeVisible({ timeout: 15000 })
|
||||
}
|
||||
|
||||
for (const spec of PAGES) {
|
||||
test(`${spec.title}:表格展示创建时间与更新时间`, async ({ page }) => {
|
||||
const errors: string[] = []
|
||||
page.on('pageerror', (error) => errors.push(error.message))
|
||||
|
||||
await openPage(page, spec.path)
|
||||
|
||||
const table = page.locator('.panel-box table').first()
|
||||
// 表头出现两列
|
||||
await expect(table.locator('thead')).toContainText('创建时间')
|
||||
await expect(table.locator('thead')).toContainText('更新时间')
|
||||
// 数据行渲染出真实时间值(非空、非占位符)
|
||||
await expect(table.locator('tbody')).toContainText(CREATED)
|
||||
await expect(table.locator('tbody')).toContainText(UPDATED)
|
||||
|
||||
expect(errors).toEqual([])
|
||||
})
|
||||
}
|
||||
@@ -1,280 +0,0 @@
|
||||
import { expect, test, type Page } from '@playwright/test'
|
||||
|
||||
// 站内通知铃铛面板验收:聚合视图(场景 × 自然日 × 事件主体用户)、展开明细、
|
||||
// 关键字/年月日区间搜索、按组分页、红点按组数。
|
||||
// 依赖 scripts/mock-admin-server.mjs 的通知夹具:14 行折成 10 组、2 组未读、3 行未读。
|
||||
// 夹具的 id 与 createdAt 同为插入时单调(与真库一致),场景显式写在夹具里而不是从 id 推。
|
||||
|
||||
// 夹具会被"标记已读"改写,而 mock 服务在 reuseExistingServer 下跨轮存活 ⇒ 每条用例前重置,
|
||||
// 否则第二遍跑会带着上一遍的已读态,绝对计数断言全漂。
|
||||
test.beforeEach(async ({ request }) => {
|
||||
await request.post('/api/admin/notifications/__reset')
|
||||
})
|
||||
|
||||
async function clearDateFilter(page: Page) {
|
||||
const picker = page.locator('.bell-panel .bell-date-picker')
|
||||
await picker.hover()
|
||||
await picker.locator('.el-range__close-icon').click()
|
||||
await expect(page.locator('.bell-page-total')).toHaveText('共 10 组 · 明细 14 条')
|
||||
}
|
||||
|
||||
async function openBell(page: Page) {
|
||||
await page.goto('/admin-vue/')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await page.locator('.admin-notification-bell .bell-trigger').click()
|
||||
await expect(page.locator('.bell-panel')).toBeVisible()
|
||||
// 面板默认按「当天」过滤,夹具是 09-10~09-13:先清空日期才能拿到全量
|
||||
await clearDateFilter(page)
|
||||
await expect(page.locator('.bell-group').first()).toBeVisible()
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开日历并等入场动画落定。
|
||||
*
|
||||
* 两件事必须先做对,否则读数全是假的:
|
||||
* ① 弹层节点是常驻的(Element 用 v-show),未打开时它也在 DOM 里、rect 全 0,
|
||||
* 所以 `toBeAttached()` 不能当「已打开」的判据;
|
||||
* ② 打开瞬间 el-zoom-in-top 把弹层 scaleY 压到 0,格子坐标整体贴到面板顶部,
|
||||
* 此时做命中测试会把「动画中」读成「被面板遮挡」。
|
||||
*/
|
||||
async function openCalendar(page: Page) {
|
||||
await page.locator('.bell-panel .bell-date-picker').click()
|
||||
const popper = page.locator('.bell-date-popper')
|
||||
await expect(popper).toBeVisible()
|
||||
await page.waitForFunction(() => {
|
||||
const pop = document.querySelector('.bell-date-popper')
|
||||
if (!pop) return false
|
||||
const style = getComputedStyle(pop)
|
||||
return style.transform === 'none' && style.opacity === '1' && pop.getBoundingClientRect().height > 0
|
||||
})
|
||||
return popper
|
||||
}
|
||||
|
||||
test('test_notification_panel_groups_and_pagination', async ({ page }) => {
|
||||
await openBell(page)
|
||||
|
||||
const panel = page.locator('.bell-panel')
|
||||
const nextPage = panel.getByRole('button', { name: '下一页' })
|
||||
|
||||
// 一页 6 组:09-13 的 4 组 + 09-12 的 2 组 ⇒ 日期头 2 个(同一天可以多组)
|
||||
await expect(page.locator('.bell-group')).toHaveCount(6)
|
||||
await expect(page.locator('.bell-day-head')).toHaveCount(2)
|
||||
await expect(page.locator('.bell-day-head').first()).toHaveText(/^(今天|昨天|\d{4}年\d{1,2}月\d{1,2}日)$/)
|
||||
await expect(page.locator('.bell-page-info')).toHaveText('1 / 2')
|
||||
await expect(page.locator('.bell-page-total')).toHaveText('共 10 组 · 明细 14 条')
|
||||
// 聚合行必须把"折叠前几条、其中几条没读"写在行上
|
||||
await expect(page.locator('.bell-group-count').first()).toHaveText('1 条 · 1 未读')
|
||||
|
||||
const page2Request = page.waitForRequest(
|
||||
(request) => request.url().includes('/api/admin/notifications/groups?') && request.url().includes('page=2'),
|
||||
)
|
||||
await nextPage.click()
|
||||
await page2Request
|
||||
|
||||
await expect(page.locator('.bell-group')).toHaveCount(4)
|
||||
await expect(page.locator('.bell-page-info')).toHaveText('2 / 2')
|
||||
await expect(nextPage).toBeDisabled()
|
||||
})
|
||||
|
||||
test('test_notification_panel_search_by_keyword', async ({ page }) => {
|
||||
await openBell(page)
|
||||
|
||||
const keywordRequest = page.waitForRequest((request) =>
|
||||
decodeURIComponent(request.url()).includes('keyword=余额不足'),
|
||||
)
|
||||
await page.locator('.bell-search-input').fill('余额不足')
|
||||
await keywordRequest
|
||||
|
||||
// 关键字命中标题/内容:夹具里 5 条含「余额不足」,且分属 5 个不同的组
|
||||
await expect(page.locator('.bell-group')).toHaveCount(5)
|
||||
await expect(page.locator('.bell-page-total')).toHaveText('共 5 组 · 明细 5 条')
|
||||
await expect(page.locator('.bell-search-reset')).toBeVisible()
|
||||
|
||||
await page.locator('.bell-search-reset').click()
|
||||
// 重置回到面板的默认视图:清空关键字、日期恢复「当天」(当天不是清空日期)
|
||||
await expect(page.locator('.bell-search-input')).toHaveValue('')
|
||||
await expect(page.locator('.bell-search-reset')).toBeHidden()
|
||||
await expect(page.locator('.bell-empty')).toHaveText('暂无通知')
|
||||
})
|
||||
|
||||
/** 红点按**组数**亮:3 条未读落在 2 个组里,徽标就是 2 而不是 3。 */
|
||||
test('test_notification_panel_badge_counts_groups_not_rows', async ({ page }) => {
|
||||
await page.goto('/admin-vue/')
|
||||
await expect(page.locator('.admin-notification-bell .bell-badge')).toHaveText('2')
|
||||
})
|
||||
|
||||
test('test_notification_panel_expand_group_loads_that_group_only', async ({ page }) => {
|
||||
await openBell(page)
|
||||
|
||||
const groups = page.locator('.bell-group')
|
||||
await expect(groups).toHaveCount(6)
|
||||
|
||||
const firstDetailRequest = page.waitForRequest((request) => {
|
||||
const url = new URL(request.url())
|
||||
return (
|
||||
url.pathname.endsWith('/api/admin/notifications') &&
|
||||
url.searchParams.get('scene') === 'secret_balance' &&
|
||||
url.searchParams.get('day') === '2026-09-13' &&
|
||||
url.searchParams.get('subjectUserId') === '1196'
|
||||
)
|
||||
})
|
||||
await groups.first().click()
|
||||
await firstDetailRequest
|
||||
await expect(page.locator('.bell-item--detail')).toHaveCount(1)
|
||||
await expect(page.locator('.bell-group--open')).toHaveCount(1)
|
||||
|
||||
// 换一组展开:上一组的明细必须收掉,不能两组明细叠在一起
|
||||
const secondDetailRequest = page.waitForRequest((request) => {
|
||||
const url = new URL(request.url())
|
||||
return (
|
||||
url.pathname.endsWith('/api/admin/notifications') &&
|
||||
url.searchParams.get('scene') === 'task_failed' &&
|
||||
url.searchParams.get('subjectUserId') === '1196'
|
||||
)
|
||||
})
|
||||
await groups.nth(1).click()
|
||||
await secondDetailRequest
|
||||
await expect(page.locator('.bell-item--detail')).toHaveCount(2)
|
||||
await expect(page.locator('.bell-group--open')).toHaveCount(1)
|
||||
|
||||
// 再点一次收起
|
||||
await groups.nth(1).click()
|
||||
await expect(page.locator('.bell-item--detail')).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('test_notification_panel_date_popper_not_covered_by_panel', async ({ page }) => {
|
||||
await openBell(page)
|
||||
await openCalendar(page)
|
||||
|
||||
// 日历与通知面板同为挂在 body 上的浮层:逐格做命中测试,最上层必须还是日历自己。
|
||||
// 通知面板 z-index 3200 高于 Element 默认弹层段(自 2000 递增)时,日历整块被压在
|
||||
// 面板底下,用户看到的就是「日期点不动」——这里必须判红而不是靠肉眼发现。
|
||||
const covered = await page.evaluate(() => {
|
||||
const pop = document.querySelector('.bell-date-popper') as HTMLElement
|
||||
const panel = document.querySelector('.bell-panel') as HTMLElement
|
||||
const blocked: string[] = []
|
||||
for (const cell of Array.from(pop.querySelectorAll<HTMLTableCellElement>('td.available'))) {
|
||||
const rect = cell.getBoundingClientRect()
|
||||
if (rect.bottom > window.innerHeight || rect.right > window.innerWidth) continue
|
||||
const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2)
|
||||
if (!hit || !pop.contains(hit)) blocked.push(String(hit?.className ?? hit?.tagName ?? 'null'))
|
||||
}
|
||||
return { blocked, popperZ: getComputedStyle(pop).zIndex, panelZ: getComputedStyle(panel).zIndex }
|
||||
})
|
||||
expect(covered.blocked, `日历被通知面板遮挡(popper=${covered.popperZ},panel=${covered.panelZ})`).toEqual([])
|
||||
})
|
||||
|
||||
/** 把左栏翻到 2026 年 9 月,返回按日取格的点击器(夹具:09-10 四条、09-12 四条、09-13 六条)。 */
|
||||
async function openRangeOnSeptember(page: Page) {
|
||||
const popper = await openCalendar(page)
|
||||
await popper.locator('.el-picker-panel__icon-btn.arrow-left').click()
|
||||
const leftPanel = popper.locator('.el-date-range-picker__content').first()
|
||||
const day = (text: string) =>
|
||||
leftPanel.locator('td.available .el-date-table-cell__text', { hasText: new RegExp(`^${text}$`) })
|
||||
await expect(day('10')).toBeVisible()
|
||||
return day
|
||||
}
|
||||
|
||||
test('test_notification_panel_search_by_day_range', async ({ page }) => {
|
||||
await openBell(page)
|
||||
const day = await openRangeOnSeptember(page)
|
||||
|
||||
// 09-10 四条折成 3 组(两个用户 × 两个场景组合)
|
||||
const rangeRequest = page.waitForRequest(
|
||||
(request) =>
|
||||
request.url().includes('startDate=2026-09-10') && request.url().includes('endDate=2026-09-12'),
|
||||
)
|
||||
await day('10').click()
|
||||
await day('12').click()
|
||||
await rangeRequest
|
||||
|
||||
await expect(page.locator('.bell-page-total')).toHaveText('共 6 组 · 明细 8 条')
|
||||
await expect(page.locator('.bell-day-head')).toHaveCount(2)
|
||||
await expect(page.locator('.bell-empty')).toHaveCount(0)
|
||||
// 选完区间后面板必须还开着:日历挂在 body 上,不能被「点击外部关闭」当成面板外
|
||||
await expect(page.locator('.bell-panel')).toBeVisible()
|
||||
})
|
||||
|
||||
test('test_notification_panel_day_range_picked_backwards', async ({ page }) => {
|
||||
await openBell(page)
|
||||
const day = await openRangeOnSeptember(page)
|
||||
|
||||
// 先点 13 再点 10:控件自己保证起 ≤ 止,落到 09-10 ~ 09-13(全量 14 条 / 10 组)
|
||||
const swappedRequest = page.waitForRequest(
|
||||
(request) =>
|
||||
request.url().includes('startDate=2026-09-10') && request.url().includes('endDate=2026-09-13'),
|
||||
)
|
||||
await day('13').click()
|
||||
await day('10').click()
|
||||
await swappedRequest
|
||||
await expect(page.locator('.bell-page-total')).toHaveText('共 10 组 · 明细 14 条')
|
||||
})
|
||||
|
||||
test('test_notification_panel_not_covered_by_page_content', async ({ page }) => {
|
||||
await openBell(page)
|
||||
|
||||
// 回归:面板挂在顶栏内时曾被页面 el-select 压住(提 z-index 无效),现改为 Teleport 到 body。
|
||||
// 这里在面板内取多点做命中测试,最上层元素必须属于面板自身。
|
||||
const covered = await page.evaluate(() => {
|
||||
const panel = document.querySelector('.bell-panel') as HTMLElement
|
||||
const rect = panel.getBoundingClientRect()
|
||||
const points: Array<[number, number]> = [
|
||||
[rect.left + 30, rect.top + 130],
|
||||
[rect.left + rect.width / 2, rect.top + rect.height / 2],
|
||||
[rect.right - 30, rect.bottom - 60],
|
||||
]
|
||||
return points
|
||||
.map(([x, y]) => document.elementsFromPoint(x, y)[0])
|
||||
.filter((el) => !!el && el !== panel && !panel.contains(el))
|
||||
.map((el) => `${el!.tagName}.${String((el as HTMLElement).className).slice(0, 40)}`)
|
||||
})
|
||||
expect(covered, '面板被页面元素遮挡').toEqual([])
|
||||
})
|
||||
|
||||
test('test_notification_panel_reference_screenshot', async ({ page }) => {
|
||||
await openBell(page)
|
||||
|
||||
const tops = await page
|
||||
.locator('.bell-group')
|
||||
.evaluateAll((els) => els.map((el) => el.getBoundingClientRect().top))
|
||||
for (let i = 1; i < tops.length; i += 1) {
|
||||
expect(tops[i], `第 ${i + 1} 组应排在第 ${i} 组下方`).toBeGreaterThan(tops[i - 1])
|
||||
}
|
||||
|
||||
await page.locator('.bell-panel').screenshot({
|
||||
path: 'test-results/notification-panel-admin-groups.jpg',
|
||||
animations: 'disabled',
|
||||
})
|
||||
await page.locator('.bell-group').first().click()
|
||||
await expect(page.locator('.bell-item--detail')).toHaveCount(1)
|
||||
await page.locator('.bell-panel').screenshot({
|
||||
path: 'test-results/notification-panel-admin-expanded.jpg',
|
||||
animations: 'disabled',
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* 已读只能进明细逐条点(口径见设计):组内未读清零,红点才掉一格。
|
||||
*/
|
||||
test('test_notification_panel_mark_read_from_detail_drops_group_last', async ({ page }) => {
|
||||
await openBell(page)
|
||||
|
||||
const group = page.locator('.bell-group').nth(1)
|
||||
await expect(group.locator('.bell-group-count')).toHaveText('2 条 · 2 未读')
|
||||
await group.click()
|
||||
await expect(page.locator('.bell-item--detail')).toHaveCount(2)
|
||||
// 每次点的都必须是「还红着」的那条:已读行点了不做事(onItemClick 直接 return),
|
||||
// 拿 .first() 连点两次会第二次点到刚读过的那条,看着像"没扣数"。
|
||||
const unread = page.locator('.bell-item--detail.bell-item--unread')
|
||||
|
||||
await unread.first().click()
|
||||
await expect(unread).toHaveCount(1)
|
||||
await expect(group.locator('.bell-group-count')).toHaveText('2 条 · 1 未读')
|
||||
// 还剩一条未读 ⇒ 这一组仍计为一个未读组,红点不动
|
||||
await expect(page.locator('.admin-notification-bell .bell-badge')).toHaveText('2')
|
||||
|
||||
await unread.first().click()
|
||||
await expect(unread).toHaveCount(0)
|
||||
await expect(group.locator('.bell-group-count')).toHaveText('2 条')
|
||||
await expect(page.locator('.admin-notification-bell .bell-badge')).toHaveText('1')
|
||||
})
|
||||
@@ -1,79 +0,0 @@
|
||||
import { expect, test, type Page } from '@playwright/test'
|
||||
|
||||
// 教程管理页验收(module 记录与版本):列表新增「版本号」列 + 上传时间列,
|
||||
// 默认按上传时间降序;版本号/上传时间表头可点击切换升降序;空版本历史行沉底。
|
||||
// 依赖 scripts/mock-admin-server.mjs 的教程包夹具(4 条,其中 1 条无版本号、1 条 09-01 历史行)。
|
||||
|
||||
async function openTutorial(page: Page) {
|
||||
await page.goto('/admin-vue/records/tutorial')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('教程管理')
|
||||
await expect(page.locator('.panel-box tbody tr').first()).toBeVisible()
|
||||
}
|
||||
|
||||
const versionTexts = (page: Page) =>
|
||||
page.locator('.panel-box tbody tr td:nth-child(3)').allTextContents()
|
||||
|
||||
const fileTexts = (page: Page) =>
|
||||
page.locator('.panel-box tbody tr td:nth-child(2) .file-name').allTextContents()
|
||||
|
||||
test('test_tutorial_list_default_desc_by_upload_time', async ({ page }) => {
|
||||
await openTutorial(page)
|
||||
|
||||
// 表头:版本号、上传时间(均带排序标记)
|
||||
await expect(page.locator('.sort-version')).toHaveText(/版本号/)
|
||||
await expect(page.locator('.sort-time')).toHaveText(/上传时间/)
|
||||
// 默认排序状态:上传时间降序(▼),版本号未激活(▲▼)
|
||||
await expect(page.locator('.sort-time .sort-mark')).toHaveText('▼')
|
||||
await expect(page.locator('.sort-version .sort-mark')).toHaveText('▲▼')
|
||||
|
||||
// 默认按上传时间降序:09-14 → 09-12 → 09-10 → 09-01;空版本行沉底
|
||||
expect(await versionTexts(page)).toEqual(['v3.10.0', 'v3.2.0', 'v3.1.0', '—'])
|
||||
expect(await fileTexts(page)).toEqual([
|
||||
'数富AI-教学客户端-v4.zip',
|
||||
'数富AI-教学客户端-v3.zip',
|
||||
'数富AI-教学客户端-v2.zip',
|
||||
'数富AI-教学客户端.zip',
|
||||
])
|
||||
// 当前生效 = 最新上传(夹具里 09-14 那条),不随列表排序变化
|
||||
await expect(page.locator('.tag-active')).toHaveCount(1)
|
||||
await expect(page.locator('.tag-active').locator('xpath=..')).toHaveText(/数富AI-教学客户端-v4\.zip/)
|
||||
})
|
||||
|
||||
test('test_tutorial_sort_toggle_by_version_and_time', async ({ page }) => {
|
||||
await openTutorial(page)
|
||||
|
||||
// 点「版本号」:首次为降序(v3.10.0 按自然序大于 v3.2.0),空版本行仍在末尾
|
||||
await page.locator('.sort-version').click()
|
||||
await expect(page.locator('.sort-version .sort-mark')).toHaveText('▼')
|
||||
expect(await versionTexts(page)).toEqual(['v3.10.0', 'v3.2.0', 'v3.1.0', '—'])
|
||||
|
||||
// 再点一次切升序
|
||||
await page.locator('.sort-version').click()
|
||||
await expect(page.locator('.sort-version .sort-mark')).toHaveText('▲')
|
||||
expect(await versionTexts(page)).toEqual(['v3.1.0', 'v3.2.0', 'v3.10.0', '—'])
|
||||
|
||||
// 点回「上传时间」:切换字段时回到降序默认
|
||||
await page.locator('.sort-time').click()
|
||||
await expect(page.locator('.sort-time .sort-mark')).toHaveText('▼')
|
||||
await expect(page.locator('.sort-version .sort-mark')).toHaveText('▲▼')
|
||||
expect(await fileTexts(page)).toEqual([
|
||||
'数富AI-教学客户端-v4.zip',
|
||||
'数富AI-教学客户端-v3.zip',
|
||||
'数富AI-教学客户端-v2.zip',
|
||||
'数富AI-教学客户端.zip',
|
||||
])
|
||||
})
|
||||
|
||||
test('test_tutorial_upload_dialog_has_version_field', async ({ page }) => {
|
||||
await openTutorial(page)
|
||||
|
||||
await page.getByRole('button', { name: '上传教程包' }).click()
|
||||
const dialog = page.locator('.el-dialog')
|
||||
await expect(dialog).toBeVisible()
|
||||
await expect(dialog.locator('.el-form-item').first()).toContainText('版本号')
|
||||
await expect(dialog.locator('input').first()).toHaveAttribute('maxlength', '64')
|
||||
|
||||
// 不选文件直接提交:提示仍以 zip 为必填(版本号可空)
|
||||
await dialog.getByRole('button', { name: '上传教程包' }).click()
|
||||
await expect(dialog.locator('.el-alert')).toContainText('请选择 zip 压缩包')
|
||||
})
|
||||
@@ -1,67 +0,0 @@
|
||||
import { expect, test, type Page } from '@playwright/test'
|
||||
|
||||
// 响应式壳层对齐现状(task-276 已移除侧边栏收起按钮/is-collapsed 机制):
|
||||
// 断言主题改为「窄屏不破版、核心地标与标题可用」。
|
||||
|
||||
async function open(page: Page, width: number, path = '/admin-vue/') {
|
||||
await page.setViewportSize({ width, height: 900 })
|
||||
await page.goto(path)
|
||||
}
|
||||
|
||||
test('test_task_017_desktop_shell_responsive_normal_primary_path', async ({ page }) => {
|
||||
await open(page, 1440)
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await expect(page.getByRole('navigation', { name: '侧边栏菜单' })).toBeVisible()
|
||||
await expect(page.locator('.admin-brand-copy strong')).toHaveText('数富AI')
|
||||
})
|
||||
|
||||
test('test_task_017_desktop_shell_responsive_normal_variant_input', async ({ page }) => {
|
||||
await open(page, 1280)
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await expect(page.getByRole('navigation', { name: '侧边栏菜单' })).toBeVisible()
|
||||
})
|
||||
|
||||
test('test_task_017_desktop_shell_responsive_normal_repeated_operation_is_idempotent', async ({ page }) => {
|
||||
await open(page, 1440)
|
||||
await page.reload()
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await expect(page.getByRole('navigation', { name: '侧边栏菜单' })).toBeVisible()
|
||||
})
|
||||
|
||||
test('test_task_017_desktop_shell_responsive_boundary_empty_input', async ({ page }) => {
|
||||
await open(page, 640)
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await expect(page.getByRole('navigation', { name: '侧边栏菜单' })).toBeVisible()
|
||||
// 窄屏侧栏自适应收缩(当前 85px 窄栏),不遮主内容标题。
|
||||
await expect(page.locator('.admin-topbar h1')).toBeVisible()
|
||||
})
|
||||
|
||||
test('test_task_017_desktop_shell_responsive_boundary_single_item', async ({ page }) => {
|
||||
await open(page, 700)
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await expect(page.locator('.admin-brand-copy strong')).toHaveText('数富AI')
|
||||
})
|
||||
|
||||
test('test_task_017_desktop_shell_responsive_boundary_limit_or_missing_field', async ({ page }) => {
|
||||
await open(page, 900)
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await open(page, 901, '/admin-vue/account/users')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
})
|
||||
|
||||
test('test_task_017_desktop_shell_responsive_invalid_input_rejected', async ({ page }) => {
|
||||
// 无折叠偏好了;刷新后壳层保持正常渲染(不因重载变样)。
|
||||
await open(page, 1440)
|
||||
await page.reload()
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await expect(page.getByRole('navigation', { name: '侧边栏菜单' })).toBeVisible()
|
||||
})
|
||||
|
||||
test('test_task_017_desktop_shell_responsive_dependency_failure_returns_actionable_message', async ({ page }) => {
|
||||
// 桌面/窄屏两种宽度下壳层均无初始化错误、导航地标可见。
|
||||
await open(page, 1440)
|
||||
await expect(page.locator('.el-alert--error')).toHaveCount(0)
|
||||
await expect(page.getByRole('navigation', { name: '侧边栏菜单' })).toBeVisible()
|
||||
await open(page, 820, '/admin-vue/account/users')
|
||||
await expect(page.locator('.el-alert--error')).toHaveCount(0)
|
||||
})
|
||||
@@ -1,78 +0,0 @@
|
||||
import { expect, test, type Page } from '@playwright/test'
|
||||
|
||||
// 壳层可访问性对齐现状(task-276 已移除侧边栏收起按钮/is-collapsed 机制):
|
||||
// 断言主题改为「跳转链接、地标唯一性、标题层级、键盘可达」。
|
||||
|
||||
async function openUsers(page: Page) {
|
||||
await page.goto('/admin-vue/')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
}
|
||||
|
||||
test('test_task_018_shell_accessibility_normal_primary_path', async ({ page }) => {
|
||||
await openUsers(page)
|
||||
await expect(page.getByRole('navigation', { name: '侧边栏菜单' })).toBeVisible()
|
||||
})
|
||||
|
||||
test('test_task_018_shell_accessibility_normal_variant_input', async ({ page }) => {
|
||||
await openUsers(page)
|
||||
const skip = page.locator('.skip-link')
|
||||
await expect(skip).toBeVisible()
|
||||
await expect(skip).toHaveAttribute('href', '#admin-content')
|
||||
})
|
||||
|
||||
test('test_task_018_shell_accessibility_normal_repeated_operation_is_idempotent', async ({ page }) => {
|
||||
await openUsers(page)
|
||||
await page.reload()
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await expect(page.getByRole('navigation', { name: '侧边栏菜单' })).toBeVisible()
|
||||
})
|
||||
|
||||
test('test_task_018_shell_accessibility_boundary_empty_input', async ({ page }) => {
|
||||
await openUsers(page)
|
||||
await expect(page.locator('.skip-link')).toHaveAttribute('href', '#admin-content')
|
||||
await expect(page.locator('#admin-content')).toHaveCount(1)
|
||||
})
|
||||
|
||||
test('test_task_018_shell_accessibility_boundary_single_item', async ({ page }) => {
|
||||
await openUsers(page)
|
||||
// 键盘可达:Tab 到跳转链接,回车跳到主内容(hash 定位)。
|
||||
await page.locator('.skip-link').focus()
|
||||
await expect(page.locator('.skip-link')).toBeFocused()
|
||||
await page.keyboard.press('Enter')
|
||||
await expect(page).toHaveURL(/#admin-content/)
|
||||
await expect(page.locator('#admin-content')).toBeVisible()
|
||||
})
|
||||
|
||||
test('test_task_018_shell_accessibility_boundary_limit_or_missing_field', async ({ page }) => {
|
||||
await openUsers(page)
|
||||
await expect(page.locator('main#admin-content')).toBeVisible()
|
||||
await expect(page.getByRole('main')).toHaveCount(1)
|
||||
})
|
||||
|
||||
test('test_task_018_shell_accessibility_invalid_input_rejected', async ({ page }) => {
|
||||
await openUsers(page)
|
||||
// 导航后无可见错误遮罩/弹层残留。
|
||||
await expect(page.locator('.el-overlay:visible')).toHaveCount(0)
|
||||
await expect(page.locator('.el-alert--error')).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('test_task_018_shell_accessibility_dependency_failure_returns_actionable_message', async ({ page }) => {
|
||||
await openUsers(page)
|
||||
// 标题层级:顶栏唯一 h1(页面标题);页面面板标题用 h3 递进。
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await expect(page.locator('h1')).toHaveCount(1)
|
||||
const hasFocusStyle = await page.evaluate(() => {
|
||||
const rules: string[] = []
|
||||
for (const sheet of document.styleSheets) {
|
||||
try {
|
||||
for (const rule of sheet.cssRules) {
|
||||
if (rule.cssText.includes(':focus-visible')) rules.push(rule.cssText)
|
||||
}
|
||||
} catch {
|
||||
// 跨域样式表忽略
|
||||
}
|
||||
}
|
||||
return rules.length > 0
|
||||
})
|
||||
expect(hasFocusStyle).toBe(true)
|
||||
})
|
||||
@@ -1,64 +0,0 @@
|
||||
import { expect, test, type Page } from '@playwright/test'
|
||||
|
||||
async function gotoRoute(page: Page, path: string) {
|
||||
await page.goto(path)
|
||||
}
|
||||
|
||||
test('test_task_019_first_batch_mount_normal_primary_path', async ({ page }) => {
|
||||
await gotoRoute(page, '/admin-vue/account/users')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
})
|
||||
|
||||
test('test_task_019_first_batch_mount_normal_variant_input', async ({ page }) => {
|
||||
await gotoRoute(page, '/admin-vue/account/menus')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('菜单管理')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('菜单管理')
|
||||
})
|
||||
|
||||
test('test_task_019_first_batch_mount_normal_repeated_operation_is_idempotent', async ({ page }) => {
|
||||
await gotoRoute(page, '/admin-vue/account/groups')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('数据权限分组')
|
||||
await gotoRoute(page, '/admin-vue/account/users')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await gotoRoute(page, '/admin-vue/account/groups')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('数据权限分组')
|
||||
})
|
||||
|
||||
test('test_task_019_first_batch_mount_boundary_empty_input', async ({ page }) => {
|
||||
// 根路由跳转到首个可见页面(用户管理)。
|
||||
await gotoRoute(page, '/admin-vue/')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await expect(page).toHaveURL(/\/account\/users$/)
|
||||
})
|
||||
|
||||
test('test_task_019_first_batch_mount_boundary_single_item', async ({ page }) => {
|
||||
await gotoRoute(page, '/admin-vue/account/menus')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('菜单管理')
|
||||
const active = page.locator('.el-menu-item.is-active')
|
||||
await expect(active).toHaveText('菜单管理')
|
||||
})
|
||||
|
||||
test('test_task_019_first_batch_mount_boundary_limit_or_missing_field', async ({ page }) => {
|
||||
// 三个页面均可从侧边栏导航切换(挂载于同一壳层实例)。
|
||||
await gotoRoute(page, '/admin-vue/account/users')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await page.getByText('菜单管理', { exact: true }).first().click()
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('菜单管理')
|
||||
await page.getByText('数据权限分组', { exact: true }).first().click()
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('数据权限分组')
|
||||
})
|
||||
|
||||
test('test_task_019_first_batch_mount_invalid_input_rejected', async ({ page }) => {
|
||||
await gotoRoute(page, '/admin-vue/no-such-page')
|
||||
await expect(page.locator('.not-found')).toBeVisible()
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('页面不存在')
|
||||
})
|
||||
|
||||
test('test_task_019_first_batch_mount_dependency_failure_returns_actionable_message', async ({ page }) => {
|
||||
// 分组内页面展示 分组->页面 两级面包屑。
|
||||
await gotoRoute(page, '/admin-vue/account/users')
|
||||
await expect(page.locator('.admin-breadcrumb')).toBeVisible()
|
||||
await expect(page.locator('.admin-breadcrumb')).toContainText('账号权限')
|
||||
await expect(page.locator('.admin-breadcrumb')).toContainText('用户管理')
|
||||
})
|
||||
@@ -1,75 +0,0 @@
|
||||
import { expect, test, type Page } from '@playwright/test'
|
||||
|
||||
async function openAdmin(page: Page) {
|
||||
await page.goto('/admin-vue/')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
}
|
||||
|
||||
test('test_task_020_shell_browser_smoke_normal_primary_path', async ({ page }) => {
|
||||
await openAdmin(page)
|
||||
await expect(page.getByRole('navigation', { name: '侧边栏菜单' })).toBeVisible()
|
||||
await expect(page.locator('.admin-user-meta strong')).toHaveText('admin')
|
||||
await expect(page.locator('.admin-user-role')).toHaveText('超级管理员')
|
||||
await expect(page.getByText('账号权限', { exact: true }).first()).toBeVisible()
|
||||
})
|
||||
|
||||
test('test_task_020_shell_browser_smoke_normal_variant_input', async ({ page }) => {
|
||||
await openAdmin(page)
|
||||
// 侧边栏菜单导航到「数据权限分组」,标题与面包屑跟随(对齐现状:无收起按钮)。
|
||||
await page.getByRole('menuitem', { name: '数据权限分组' }).click()
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('数据权限分组')
|
||||
await expect(page.locator('.admin-breadcrumb')).toBeVisible()
|
||||
})
|
||||
|
||||
test('test_task_020_shell_browser_smoke_normal_repeated_operation_is_idempotent', async ({ page }) => {
|
||||
await openAdmin(page)
|
||||
await page.reload()
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await expect(page.locator('.global-error-stack')).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('test_task_020_shell_browser_smoke_boundary_empty_input', async ({ page }) => {
|
||||
await page.goto('/admin-vue/definitely/not/exists')
|
||||
await expect(page.locator('.not-found')).toBeVisible()
|
||||
await expect(page.locator('.not-found')).toContainText('404')
|
||||
})
|
||||
|
||||
test('test_task_020_shell_browser_smoke_boundary_single_item', async ({ page }) => {
|
||||
await openAdmin(page)
|
||||
await page.getByRole('button', { name: '退出登录' }).click()
|
||||
await expect(page.locator('.el-message-box')).toBeVisible()
|
||||
await expect(page.locator('.el-message-box')).toContainText('确定要退出当前账号吗?')
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '取消' }).click()
|
||||
await expect(page.locator('.el-message-box')).toHaveCount(0)
|
||||
await expect(page).toHaveURL(/\/admin-vue\//)
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
})
|
||||
|
||||
test('test_task_020_shell_browser_smoke_boundary_limit_or_missing_field', async ({ page }) => {
|
||||
await openAdmin(page)
|
||||
await page.getByRole('button', { name: '退出登录' }).click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '退出' }).click()
|
||||
await page.waitForURL(/\/login/, { timeout: 10_000 })
|
||||
})
|
||||
|
||||
test('test_task_020_shell_browser_smoke_invalid_input_rejected', async ({ page }) => {
|
||||
// 整段冒烟无未捕获脚本错误(错误不会静默遗留到控制台)。
|
||||
const errors: string[] = []
|
||||
page.on('pageerror', (error) => errors.push(error.message))
|
||||
await openAdmin(page)
|
||||
await page.goto('/admin-vue/account/menus')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('菜单管理')
|
||||
await page.goto('/admin-vue/account/groups')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('数据权限分组')
|
||||
expect(errors).toEqual([])
|
||||
})
|
||||
|
||||
test('test_task_020_shell_browser_smoke_dependency_failure_returns_actionable_message', async ({ page }) => {
|
||||
await openAdmin(page)
|
||||
// 取消确认后无“可见”的遮罩/弹层残留(隐藏的对话框 DOM 不算);继续导航正常。
|
||||
await page.getByRole('button', { name: '退出登录' }).click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '取消' }).click()
|
||||
await expect(page.locator('.el-overlay:visible')).toHaveCount(0)
|
||||
await page.locator('.admin-brand-copy, .admin-topbar h1').first().click({ force: true })
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
})
|
||||
Generated
-3254
File diff suppressed because it is too large
Load Diff
@@ -1,33 +0,0 @@
|
||||
{
|
||||
"name": "crawler-plugin-admin-frontend-vue",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host --port 5174",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"test": "node --test tests/*.test.ts",
|
||||
"test:mount": "vitest run",
|
||||
"test:live": "node --test tests/live/*.test.ts",
|
||||
"test:browser": "playwright test"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.13.6",
|
||||
"element-plus": "^2.11.4",
|
||||
"pinia": "^3.0.3",
|
||||
"vue": "^3.5.18",
|
||||
"vue-router": "^4.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.63.0",
|
||||
"@types/node": "^26.4.1",
|
||||
"@vitejs/plugin-vue": "^6.0.1",
|
||||
"@vue/test-utils": "^2.5.1",
|
||||
"jsdom": "^30.1.2",
|
||||
"typescript": "^5.9.2",
|
||||
"vite": "^7.3.1",
|
||||
"vitest": "^5.0.3",
|
||||
"vue-tsc": "^3.0.6"
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import { defineConfig } from '@playwright/test'
|
||||
|
||||
/**
|
||||
* 浏览器验收:起 mock admin API(18100) + vite dev(E2E_PORT,默认 5174, /api 代理到 mock)。
|
||||
* 本地用已安装的 MS Edge(channel: msedge)运行,无需下载 Chromium。
|
||||
*
|
||||
* 端口必须可改:5174 被别的项目占用时 vite 会顺延到别的端口,而 reuseExistingServer
|
||||
* 会让 playwright 直接连上那个「不是本站」的服务,整份验收测的是别人的页面。
|
||||
*/
|
||||
const PORT = Number(process.env.E2E_PORT || 5174)
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
timeout: 45_000,
|
||||
expect: { timeout: 10_000 },
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
retries: 0,
|
||||
reporter: [['list']],
|
||||
use: {
|
||||
baseURL: `http://127.0.0.1:${PORT}`,
|
||||
channel: 'msedge',
|
||||
headless: true,
|
||||
viewport: { width: 1440, height: 900 },
|
||||
locale: 'zh-CN',
|
||||
},
|
||||
webServer: [
|
||||
{
|
||||
command: 'node scripts/mock-admin-server.mjs',
|
||||
port: 18100,
|
||||
reuseExistingServer: true,
|
||||
},
|
||||
{
|
||||
command: `set VITE_API_TARGET=http://127.0.0.1:18100&& npm run dev -- --port ${PORT} --strictPort`,
|
||||
port: PORT,
|
||||
reuseExistingServer: true,
|
||||
timeout: 120_000,
|
||||
},
|
||||
],
|
||||
})
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 10 KiB |
@@ -1,43 +0,0 @@
|
||||
// 样办校验:生成记录页旧版样式落地实测(本地真实栈)。
|
||||
import { chromium } from '@playwright/test'
|
||||
const BASE = 'http://localhost:5174/admin-vue'
|
||||
const browser = await chromium.launch({ channel: 'msedge', headless: true })
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } })
|
||||
await page.goto(`${BASE}/`, { waitUntil: 'networkidle' })
|
||||
await page.waitForTimeout(500)
|
||||
if (await page.locator('#loginUsername').isVisible().catch(() => false)) {
|
||||
await page.locator('#loginUsername').fill('admin')
|
||||
await page.locator('#loginPassword').fill('admin123')
|
||||
await page.locator('.btn-login').click()
|
||||
await page.waitForURL(/admin-vue\/(account|asin|shop|records)/, { timeout: 20000 }).catch(() => {})
|
||||
await page.waitForTimeout(1200)
|
||||
}
|
||||
await page.goto(`${BASE}/records/history`, { waitUntil: 'domcontentloaded' })
|
||||
await page.locator('.form-box').first().waitFor({ state: 'visible', timeout: 15000 })
|
||||
await page.waitForLoadState('networkidle').catch(() => {})
|
||||
await page.waitForTimeout(600)
|
||||
const out = await page.evaluate(() => {
|
||||
const cs = (el, prop) => (el ? getComputedStyle(el)[prop] : null)
|
||||
const fb = document.querySelector('.form-box')
|
||||
const pb = document.querySelector('.panel-box')
|
||||
const th = document.querySelector('.table-scroll th')
|
||||
const td = document.querySelector('.table-scroll td')
|
||||
const btn = document.querySelector('.form-box .btn')
|
||||
const inp = document.querySelector('.form-group input, .form-group select')
|
||||
return {
|
||||
formBox: { bg: cs(fb, 'backgroundColor'), radius: cs(fb, 'borderRadius'), border: cs(fb, 'borderTopColor') },
|
||||
panelBox: { bg: cs(pb, 'backgroundColor') },
|
||||
h3: cs(document.querySelector('.panel-box h3'), 'fontSize'),
|
||||
input: { minH: inp && cs(inp, 'minHeight'), bg: inp && cs(inp, 'backgroundColor'), radius: inp && cs(inp, 'borderRadius') },
|
||||
btn: { minH: cs(btn, 'minHeight'), bgImage: btn && getComputedStyle(btn).backgroundImage.slice(0, 60), radius: cs(btn, 'borderRadius'), color: cs(btn, 'color') },
|
||||
th: { bg: cs(th, 'backgroundColor'), color: cs(th, 'color'), fontSize: cs(th, 'fontSize'), weight: cs(th, 'fontWeight') },
|
||||
td: { color: td && cs(td, 'color'), fontSize: td && cs(td, 'fontSize') },
|
||||
tableScroll: { border: cs(document.querySelector('.table-scroll'), 'borderTopColor'), radius: cs(document.querySelector('.table-scroll'), 'borderRadius') },
|
||||
rowCount: document.querySelectorAll('.table-scroll tbody tr').length,
|
||||
thumbb: !!document.querySelector('.thumb'),
|
||||
pagination: (document.querySelector('.pagination')?.textContent || '').trim().slice(0, 60),
|
||||
modal: document.querySelector('.modal-mask') === null,
|
||||
}
|
||||
})
|
||||
console.log(JSON.stringify(out, null, 2))
|
||||
await browser.close()
|
||||
@@ -1,592 +0,0 @@
|
||||
// 本地浏览器验收用 mock(仅测试,不随前端产物发布):模拟 Admin 壳层所需的最小 API + 撞款控制台夹具。
|
||||
import { createServer } from 'node:http'
|
||||
|
||||
const PORT = Number(process.env.MOCK_PORT || 18100)
|
||||
|
||||
const MENU_TREE = [
|
||||
{
|
||||
key: 'account',
|
||||
name: '账号权限',
|
||||
children: [
|
||||
{ key: 'admin_users', name: '用户管理', route: '/account/users' },
|
||||
{ key: 'admin_columns', name: '菜单管理', route: '/account/menus' },
|
||||
{ key: 'admin_group_manage', name: '数据权限分组', route: '/account/groups' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
/* ===================== 撞款控制台夹具(对齐前端 parse 的 snake 契约) ===================== */
|
||||
const STORE_GROUP = { 店A1: '陈新辉', 店A2: '陈新辉', 店B1: '魏振峰', 店B2: '魏振峰', 店B3: '魏振峰', 店C1: '郭亚芳' }
|
||||
const GROUP_DEFS = [
|
||||
{ name: '陈新辉', shops: ['店A1', '店A2'] },
|
||||
{ name: '魏振峰', shops: ['店B1', '店B2', '店B3'] },
|
||||
{ name: '郭亚芳', shops: ['店C1'] },
|
||||
]
|
||||
|
||||
function occ(asin, brand, shop, country, day) {
|
||||
return { asin, date: `2026-08-${String(day).padStart(2, '0')} 09:00:00`, price: '9.90', brand, shop_name: shop, group_name: STORE_GROUP[shop], country_codes: [country], country }
|
||||
}
|
||||
|
||||
// 撞款种子(≥2 店在售)与单店种子
|
||||
const DUP_SEEDS = [
|
||||
{ asin: 'E0000001', brand: '品牌甲', occ: [occ('E0000001', '品牌甲', '店A1', 'UK', 20), occ('E0000001', '品牌甲', '店A1', 'UK', 24), occ('E0000001', '品牌甲', '店A2', 'DE', 22), occ('E0000001', '品牌甲', '店B1', 'FR', 21)] },
|
||||
{ asin: 'E0000002', brand: '品牌乙', occ: [occ('E0000002', '品牌乙', '店B1', 'UK', 10), occ('E0000002', '品牌乙', '店B2', 'DE', 12)] },
|
||||
{ asin: 'E0000003', brand: '品牌丙', occ: [occ('E0000003', '品牌丙', '店A2', 'DE', 15), occ('E0000003', '品牌丙', '店B3', 'IT', 16)] },
|
||||
]
|
||||
const SINGLE_SEEDS = [
|
||||
{ asin: 'E0000004', brand: '品牌甲', occ: [occ('E0000004', '品牌甲', '店A1', 'UK', 1)] },
|
||||
{ asin: 'E0000005', brand: '品牌丁', occ: [occ('E0000005', '品牌丁', '店B2', 'UK', 2), occ('E0000005', '品牌丁', '店B2', 'UK', 3)] },
|
||||
{ asin: 'E0000006', brand: '品牌戊', occ: [occ('E0000006', '品牌戊', '店C1', 'FR', 5)] },
|
||||
{ asin: 'E0000007', brand: '品牌己', occ: [occ('E0000007', '品牌己', '店B3', 'DE', 6)] },
|
||||
{ asin: 'E0000008', brand: '品牌庚', occ: [occ('E0000008', '品牌庚', '店A1', 'ES', 7)] },
|
||||
]
|
||||
|
||||
function finalizeRow(seed) {
|
||||
const stores = []
|
||||
const storeSet = new Set()
|
||||
const countries = new Set()
|
||||
let earliest = ''
|
||||
let latest = ''
|
||||
for (const o of seed.occ) {
|
||||
if (!storeSet.has(o.shop_name)) {
|
||||
storeSet.add(o.shop_name)
|
||||
stores.push(o.shop_name)
|
||||
}
|
||||
countries.add(o.country)
|
||||
if (!earliest || o.date < earliest) earliest = o.date
|
||||
if (o.date > latest) latest = o.date
|
||||
}
|
||||
const groups = [...new Set(stores.map((s) => STORE_GROUP[s] || ''))].filter(Boolean)
|
||||
return {
|
||||
asin: seed.asin,
|
||||
brand: seed.brand,
|
||||
store_count: stores.length,
|
||||
stores,
|
||||
groups,
|
||||
countries: [...countries],
|
||||
record_count: seed.occ.length,
|
||||
earliest,
|
||||
latest,
|
||||
occurrences: seed.occ,
|
||||
}
|
||||
}
|
||||
|
||||
const ALL_ROWS = [...DUP_SEEDS, ...SINGLE_SEEDS].map(finalizeRow)
|
||||
const DUP_ROWS = ALL_ROWS.filter((row) => row.store_count >= 2)
|
||||
|
||||
const SHOPS = Object.keys(STORE_GROUP).map((name) => {
|
||||
const codes = new Set()
|
||||
let recordCount = 0
|
||||
let asinCount = 0
|
||||
for (const row of ALL_ROWS) {
|
||||
if (row.stores.includes(name)) {
|
||||
asinCount += 1
|
||||
for (const o of row.occurrences) {
|
||||
if (o.shop_name === name) {
|
||||
recordCount += 1
|
||||
codes.add(o.country)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { shop_name: name, group_name: STORE_GROUP[name], country_codes: [...codes], asin_count: asinCount, record_count: recordCount }
|
||||
})
|
||||
|
||||
function computeGroups() {
|
||||
return GROUP_DEFS.map((group) => {
|
||||
const members = group.shops
|
||||
const hit = DUP_ROWS.filter((row) => members.filter((shop) => row.stores.includes(shop)).length >= 2)
|
||||
const asinUnique = ALL_ROWS.filter((row) => row.stores.some((shop) => members.includes(shop))).length
|
||||
const recordCount = ALL_ROWS.reduce((sum, row) => {
|
||||
if (row.stores.some((shop) => members.includes(shop))) sum += row.recordCount
|
||||
return sum
|
||||
}, 0)
|
||||
return { name: group.name, shop_count: members.length, asin_unique: asinUnique, record_count: recordCount, dup_count: hit.length }
|
||||
})
|
||||
}
|
||||
|
||||
const GROUPS = computeGroups()
|
||||
const RECORD_TOTAL = ALL_ROWS.reduce((sum, row) => sum + row.recordCount, 0)
|
||||
|
||||
function consolePayload() {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
pending: false,
|
||||
scanned_at: '2026-09-05 08:30:00',
|
||||
summary: {
|
||||
shop_count: SHOPS.length,
|
||||
asin_total: ALL_ROWS.length,
|
||||
record_total: RECORD_TOTAL,
|
||||
duplicate_asin_total: DUP_ROWS.length,
|
||||
duplicate_shop_count: DUP_ROWS.length ? 6 : 0,
|
||||
site_count: 5,
|
||||
asin_per_shop: 4.8,
|
||||
source: 'job',
|
||||
},
|
||||
shops: SHOPS,
|
||||
dup: DUP_ROWS,
|
||||
groups: GROUPS,
|
||||
total_dup: DUP_ROWS.length,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function json(res, payload, status = 200) {
|
||||
const body = JSON.stringify(payload)
|
||||
res.writeHead(status, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
})
|
||||
res.end(body)
|
||||
}
|
||||
|
||||
/* ===================== 教程包夹具(教程管理页:版本号列 + 上传时间排序验收用) ===================== */
|
||||
// 故意乱序给出,且含一条无版本号的历史行:页面默认应按上传时间降序、空版本行沉底。
|
||||
const TUTORIAL_PACKAGES = [
|
||||
{ id: 3, file_name: '数富AI-教学客户端-v3.zip', version: 'v3.2.0', object_key: 'tutorial/20260912090000-数富AI-教学客户端-v3.zip', file_size: 1048576, file_url: 'https://oss.aishufu.top/client/tutorial/t3.zip', created_at: '2026-09-12 09:00' },
|
||||
{ id: 1, file_name: '数富AI-教学客户端.zip', version: '', object_key: 'tutorial/数富AI-教学客户端.zip', file_size: 0, file_url: 'https://oss.aishufu.top/client/tutorial/legacy.zip', created_at: '2026-09-01 08:00' },
|
||||
{ id: 4, file_name: '数富AI-教学客户端-v4.zip', version: 'v3.10.0', object_key: 'tutorial/20260914103000-数富AI-教学客户端-v4.zip', file_size: 2097152, file_url: 'https://oss.aishufu.top/client/tutorial/t4.zip', created_at: '2026-09-14 10:30' },
|
||||
{ id: 2, file_name: '数富AI-教学客户端-v2.zip', version: 'v3.1.0', object_key: 'tutorial/20260910120000-数富AI-教学客户端-v2.zip', file_size: 524288, file_url: 'https://oss.aishufu.top/client/tutorial/t2.zip', created_at: '2026-09-10 12:00' },
|
||||
]
|
||||
|
||||
/* ===================== 站内通知夹具(铃铛面板:搜索/按天分组/分页验收用) ===================== */
|
||||
/**
|
||||
* 通知夹具。两条约定不能破:
|
||||
* ① id 与 createdAt 同为插入时单调(09-10 最早 ⇒ id 最小)——与真库一致;倒挂会让
|
||||
* "按 id 倒序即按天倒序"这种隐藏假设在 mock 里成立、上线就翻车。
|
||||
* ② 场景显式给,不从 id 取模推——否则换一批 id,「余额不足」命中数与聚合组数一起漂,
|
||||
* 用例断言就成了跟着夹具跑的活字。
|
||||
* 共 14 行、5 行密钥告警;按 场景×自然日×主体用户 折成 10 组,其中 2 组未读、3 行未读。
|
||||
*/
|
||||
const NOTIFICATIONS = [
|
||||
['2026-09-10', 18, 1, true, 'task_failed'],
|
||||
['2026-09-10', 18, 2, true, 'task_failed'],
|
||||
['2026-09-10', 18, 3, true, 'secret_balance'],
|
||||
['2026-09-10', 18, 4, true, 'task_failed'],
|
||||
['2026-09-12', 20, 1, true, 'secret_balance'],
|
||||
['2026-09-12', 20, 2, true, 'task_failed'],
|
||||
['2026-09-12', 20, 3, true, 'task_failed'],
|
||||
['2026-09-12', 20, 4, true, 'secret_balance'],
|
||||
['2026-09-13', 22, 1, true, 'task_failed'],
|
||||
['2026-09-13', 22, 2, true, 'task_failed'],
|
||||
['2026-09-13', 22, 3, true, 'secret_balance'],
|
||||
['2026-09-13', 22, 4, false, 'task_failed'],
|
||||
['2026-09-13', 22, 5, false, 'task_failed'],
|
||||
['2026-09-13', 22, 6, false, 'secret_balance'],
|
||||
].map(([day, hour, seq, read, scene], index) => notif(index + 1, day, hour, seq, read, scene))
|
||||
|
||||
const NOTIFICATION_SEED = structuredClone(NOTIFICATIONS)
|
||||
|
||||
function notif(id, day, hour, seq, read, scene) {
|
||||
const minutes = String(seq * 7).padStart(2, '0')
|
||||
const secret = scene === 'secret_balance'
|
||||
return {
|
||||
id,
|
||||
scene,
|
||||
level: secret ? 'error' : 'warning',
|
||||
title: secret ? `用户密钥异常:测试用户${seq}` : `跟价任务失败`,
|
||||
content: secret
|
||||
? `用户 测试用户${seq}(uid=${1100 + seq})的代理设置对应服务商余额不足`
|
||||
: `用户 测试用户${seq} 有 ${seq} 个跟价任务失败`,
|
||||
// 事件主体用户:与后端 V158 那列同义,聚合分组键的第三维。seq>3 归 1196、其余归 1160,
|
||||
// 让"同一天两个用户"在夹具里真的存在(否则聚合视图测不到按用户拆组这一维)。
|
||||
subjectUserId: seq > 3 ? 1196 : 1160,
|
||||
read,
|
||||
readAt: read ? `${day} ${hour}:${minutes}:00` : null,
|
||||
createdAt: `${day} ${hour}:${minutes}:00`,
|
||||
}
|
||||
}
|
||||
|
||||
/** 与后端 groups 出口同形的聚合:场景 × 自然日 × 主体用户。 */
|
||||
function groupRows(rows) {
|
||||
const byKey = new Map()
|
||||
for (const item of [...rows].sort((a, b) => b.id - a.id)) {
|
||||
const day = item.createdAt.slice(0, 10)
|
||||
const key = `${item.scene}|${day}|${item.subjectUserId ?? 'none'}`
|
||||
let group = byKey.get(key)
|
||||
if (!group) {
|
||||
group = {
|
||||
latestId: item.id,
|
||||
scene: item.scene,
|
||||
category: item.scene === 'secret_balance' ? 'config_error' : 'task_error',
|
||||
day,
|
||||
subjectUserId: item.subjectUserId ?? null,
|
||||
rowCount: 0,
|
||||
unreadCount: 0,
|
||||
level: item.level,
|
||||
title: item.title,
|
||||
content: item.content,
|
||||
createdAt: item.createdAt,
|
||||
}
|
||||
byKey.set(key, group)
|
||||
}
|
||||
group.rowCount += 1
|
||||
if (!item.read) group.unreadCount += 1
|
||||
if (item.level === 'error') group.level = 'error'
|
||||
}
|
||||
return [...byKey.values()]
|
||||
}
|
||||
|
||||
/** 通知列表:关键字匹配标题/内容,日期按年月日区间(与 Java 侧同语义)。 */
|
||||
/** 列表与聚合共用的筛选:关键字 / 日期区间 / 展开某一组(场景 + 自然日 + 主体用户)。 */
|
||||
function filteredRows(searchParams) {
|
||||
const keyword = (searchParams.get('keyword') || '').trim()
|
||||
const startDate = searchParams.get('startDate') || ''
|
||||
const endDate = searchParams.get('endDate') || ''
|
||||
const scene = searchParams.get('scene') || ''
|
||||
const day = searchParams.get('day') || ''
|
||||
const subjectUserId = searchParams.get('subjectUserId')
|
||||
const subjectUnlabelled = searchParams.get('subjectUnlabelled') === 'true'
|
||||
let rows = NOTIFICATIONS
|
||||
if (keyword) {
|
||||
rows = rows.filter((item) => `${item.title}${item.content}`.includes(keyword))
|
||||
}
|
||||
if (startDate) {
|
||||
rows = rows.filter((item) => item.createdAt.slice(0, 10) >= startDate)
|
||||
}
|
||||
if (endDate) {
|
||||
rows = rows.filter((item) => item.createdAt.slice(0, 10) <= endDate)
|
||||
}
|
||||
if (scene) {
|
||||
rows = rows.filter((item) => item.scene === scene)
|
||||
}
|
||||
if (day) {
|
||||
rows = rows.filter((item) => item.createdAt.slice(0, 10) === day)
|
||||
}
|
||||
if (subjectUserId) {
|
||||
rows = rows.filter((item) => String(item.subjectUserId) === String(subjectUserId))
|
||||
} else if (subjectUnlabelled) {
|
||||
rows = rows.filter((item) => item.subjectUserId === null || item.subjectUserId === undefined)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
function readPaging(searchParams) {
|
||||
const page = Math.max(1, Number(searchParams.get('page') || 1))
|
||||
const pageSize = Math.min(100, Math.max(1, Number(searchParams.get('pageSize') || 20)))
|
||||
return { page, pageSize, start: (page - 1) * pageSize }
|
||||
}
|
||||
|
||||
function notificationPage(searchParams) {
|
||||
const rows = filteredRows(searchParams)
|
||||
const { page, pageSize, start } = readPaging(searchParams)
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
items: rows.slice(start, start + pageSize),
|
||||
total: rows.length,
|
||||
page,
|
||||
pageSize,
|
||||
unreadCount: rows.filter((item) => !item.read).length,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** 聚合出口:分页按组切,total=组数、rowCount=折叠前的明细条数,两个都给前端。 */
|
||||
function notificationGroupsPage(searchParams) {
|
||||
const rows = filteredRows(searchParams)
|
||||
const groups = groupRows(rows)
|
||||
const { page, pageSize, start } = readPaging(searchParams)
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
groups: groups.slice(start, start + pageSize),
|
||||
total: groups.length,
|
||||
rowCount: rows.length,
|
||||
page,
|
||||
pageSize,
|
||||
unreadGroupCount: groups.filter((group) => group.unreadCount > 0).length,
|
||||
unreadCount: rows.filter((item) => !item.read).length,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
const url = (req.url || '').split('?')[0]
|
||||
const method = req.method || 'GET'
|
||||
console.log(`[mock] ${method} ${url}`)
|
||||
|
||||
if (url === '/api/admin/current-user') {
|
||||
return json(res, { success: true, data: { item: { id: 1, username: 'admin', role: 'super_admin' } } })
|
||||
}
|
||||
if (url === '/api/admin/current-user/menus') {
|
||||
return json(res, { success: true, data: { items: MENU_TREE } })
|
||||
}
|
||||
if (url === '/api/admin/logout') {
|
||||
return json(res, { success: true })
|
||||
}
|
||||
if (url === '/api/admin/users') {
|
||||
return json(res, {
|
||||
success: true,
|
||||
data: {
|
||||
items: [{ id: 1, username: 'admin', role: 'super_admin', creatorUsername: 'system', created_at: '2026-03-01 09:15:00', updated_at: '2026-09-18 16:42:30' }],
|
||||
total: 1,
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url === '/api/admin/permission-menus') {
|
||||
// 菜单管理列表:一条根节点,带创建/更新时间(验收时间列)。
|
||||
return json(res, {
|
||||
success: true,
|
||||
data: [
|
||||
{
|
||||
id: 1,
|
||||
name: '用户管理',
|
||||
column_key: 'admin_users',
|
||||
parent_id: null,
|
||||
menu_type: 'admin',
|
||||
route_path: 'account/users',
|
||||
sort_order: 10,
|
||||
created_at: '2026-03-01T09:15:00',
|
||||
updated_at: '2026-09-18T16:42:30',
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
if (url === '/api/admin/invalid-asin-data') {
|
||||
return json(res, {
|
||||
success: true,
|
||||
data: {
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
dataValue: 'B0INVALID1',
|
||||
brand: '测试品牌',
|
||||
groupId: 1,
|
||||
groupName: '测试分组',
|
||||
recordSource: 'MANUAL',
|
||||
createdAt: '2026-03-01 09:15:00',
|
||||
updatedAt: '2026-09-18 16:42:30',
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url === '/api/admin/dedupe-total-data') {
|
||||
return json(res, {
|
||||
success: true,
|
||||
data: {
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
dataValue: 'B0DEDUPE01',
|
||||
country: 'DE',
|
||||
groupId: 1,
|
||||
groupName: '测试分组',
|
||||
uploaderUserId: 1,
|
||||
username: 'admin',
|
||||
createdAt: '2026-03-01 09:15:00',
|
||||
updatedAt: '2026-09-18 16:42:30',
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url === '/api/admin/query-asins') {
|
||||
return json(res, {
|
||||
success: true,
|
||||
data: {
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
groupId: 1,
|
||||
groupName: '测试分组',
|
||||
shopName: '测试店铺',
|
||||
asinDe: 'B0QUERY001',
|
||||
asinUk: '',
|
||||
asinFr: '',
|
||||
asinIt: '',
|
||||
asinEs: '',
|
||||
createdAt: '2026-03-01 09:15:00',
|
||||
updatedAt: '2026-09-18 16:42:30',
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url === '/api/admin/skip-price-asins') {
|
||||
return json(res, {
|
||||
success: true,
|
||||
data: {
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
groupId: 1,
|
||||
groupName: '测试分组',
|
||||
shopName: '测试店铺',
|
||||
asinDe: 'B0SKIP0001',
|
||||
minimumPriceDe: 9.99,
|
||||
asinUk: '',
|
||||
minimumPriceUk: null,
|
||||
asinFr: '',
|
||||
minimumPriceFr: null,
|
||||
asinIt: '',
|
||||
minimumPriceIt: null,
|
||||
asinEs: '',
|
||||
minimumPriceEs: null,
|
||||
createdAt: '2026-03-01 09:15:00',
|
||||
updatedAt: '2026-09-18 16:42:30',
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url === '/api/admin/product-categories/children') {
|
||||
return json(res, {
|
||||
success: true,
|
||||
data: {
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
parentId: null,
|
||||
name: '护肤品',
|
||||
categoryKey: 'skincare',
|
||||
sortOrder: 10,
|
||||
description: '测试备注',
|
||||
isBuiltin: true,
|
||||
childCount: 0,
|
||||
level: 0,
|
||||
path: '护肤品',
|
||||
createdAt: '2026-03-01 09:15:00',
|
||||
updatedAt: '2026-09-18 16:42:30',
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
hasMore: false,
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url === '/api/admin/user-secrets') {
|
||||
const emptyModule = { moduleKey: '', moduleLabel: '', masked: '', full: '', exists: false, checkStatus: 'unknown', checkCode: '', checkMessage: '', checkLatencyMs: null, checkedAt: null, updatedAt: null }
|
||||
return json(res, {
|
||||
success: true,
|
||||
data: {
|
||||
items: [
|
||||
{
|
||||
userId: 1,
|
||||
username: 'admin',
|
||||
groups: [],
|
||||
leaderUsername: '',
|
||||
similarAsin: { ...emptyModule, moduleKey: 'similar-asin', moduleLabel: '货源查询密钥' },
|
||||
appearancePatent: { ...emptyModule, moduleKey: 'appearance-patent', moduleLabel: '外观专利密钥' },
|
||||
proxy: { ...emptyModule, moduleKey: 'proxy', moduleLabel: '代理设置' },
|
||||
status: 'unknown',
|
||||
statusMessage: '',
|
||||
createdAt: '2026-03-01 09:15:00',
|
||||
updatedAt: '2026-09-18 16:42:30',
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
page: 1,
|
||||
pageSize: 15,
|
||||
groupOptions: [],
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url === '/api/admin/user-secrets/balances') {
|
||||
// 余额侧写夹具(POST):两把密钥同渠道 ⇒ 界面折叠成一行;代理给「你的套餐」形状
|
||||
const llmCell = (moduleKey, moduleLabel, over = {}) => ({
|
||||
moduleKey, moduleLabel,
|
||||
channel: 'longtaitou', channelLabel: '龙抬头',
|
||||
available: true, balance: '88.888882', availableBalance: '85.288882', frozen: '3.6',
|
||||
unit: 'CREDIT', message: null, checkedAt: '2026-11-05T10:30:00', ...over,
|
||||
})
|
||||
return json(res, {
|
||||
success: true,
|
||||
data: {
|
||||
items: [
|
||||
{
|
||||
userId: 1,
|
||||
llm: [
|
||||
llmCell('appearance-patent', '外观专利密钥'),
|
||||
llmCell('similar-asin', '货源查询密钥'),
|
||||
],
|
||||
proxy: { available: true, surplus: '1234', balance: '56', scope: 'user', message: null },
|
||||
},
|
||||
],
|
||||
deniedUserIds: [],
|
||||
timedOutUserIds: [],
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url === '/api/admin/shop-manage-groups') {
|
||||
return json(res, { success: true, data: { items: [] } })
|
||||
}
|
||||
if (url === '/api/admin/shop-data-crawl/duplicate-check-console') {
|
||||
return json(res, consolePayload())
|
||||
}
|
||||
if (url === '/api/admin/shop-data-crawl/duplicate-check-ledger') {
|
||||
return json(res, {
|
||||
success: true,
|
||||
data: { pending: false, scanned_at: '2026-09-05 08:30:00', items: ALL_ROWS, total: ALL_ROWS.length, page: 1, page_size: 20 },
|
||||
})
|
||||
}
|
||||
// 已读标记会改内存里的夹具(不是幂等只读口)⇒ 用例之间要靠下面这条重置口隔离,
|
||||
// 否则同一份 mock 服务被 reuseExistingServer 复用时,第二次跑就会带着上一次的已读态。
|
||||
if (method === 'POST' && url === '/api/admin/notifications/__reset') {
|
||||
NOTIFICATIONS.splice(0, NOTIFICATIONS.length, ...structuredClone(NOTIFICATION_SEED))
|
||||
return json(res, { success: true, data: NOTIFICATIONS.length })
|
||||
}
|
||||
if (method === 'POST' && /^\/api\/admin\/notifications\/\d+\/read$/.test(url)) {
|
||||
const id = Number(url.split('/')[3])
|
||||
const item = NOTIFICATIONS.find((row) => row.id === id)
|
||||
if (item && !item.read) {
|
||||
item.read = true
|
||||
item.readAt = `${item.createdAt.slice(0, 10)} 23:59:59`
|
||||
}
|
||||
return json(res, { success: true, data: true })
|
||||
}
|
||||
if (method === 'POST' && url === '/api/admin/notifications/read-all') {
|
||||
for (const item of NOTIFICATIONS) {
|
||||
if (!item.read) {
|
||||
item.read = true
|
||||
item.readAt = `${item.createdAt.slice(0, 10)} 23:59:59`
|
||||
}
|
||||
}
|
||||
return json(res, { success: true, data: NOTIFICATIONS.length })
|
||||
}
|
||||
if (url === '/api/admin/notifications/summary') {
|
||||
const groups = groupRows(NOTIFICATIONS)
|
||||
return json(res, {
|
||||
success: true,
|
||||
data: {
|
||||
unreadCount: NOTIFICATIONS.filter((item) => !item.read).length,
|
||||
unreadGroupCount: groups.filter((group) => group.unreadCount > 0).length,
|
||||
latestId: NOTIFICATIONS.reduce((max, item) => Math.max(max, item.id), 0),
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url === '/api/admin/notifications/groups') {
|
||||
return json(res, notificationGroupsPage(new URL(req.url || '/', 'http://127.0.0.1').searchParams))
|
||||
}
|
||||
if (url === '/api/admin/notifications') {
|
||||
return json(res, notificationPage(new URL(req.url || '/', 'http://127.0.0.1').searchParams))
|
||||
}
|
||||
if (url === '/api/admin/tutorials') {
|
||||
// 与 Java 侧同契约:created_at 降序返回(页面"当前生效"取第一条)。
|
||||
const items = [...TUTORIAL_PACKAGES].sort((a, b) => (a.created_at < b.created_at ? 1 : -1))
|
||||
return json(res, { success: true, data: { items } })
|
||||
}
|
||||
if (url.startsWith('/api/')) {
|
||||
return json(res, { success: true, data: { items: [], total: 0 } })
|
||||
}
|
||||
return json(res, { success: true }, 200)
|
||||
})
|
||||
|
||||
server.listen(PORT, () => console.log(`mock admin api listening on ${PORT}`))
|
||||
@@ -1,96 +0,0 @@
|
||||
// round2 DOM 审计:登录本地真实栈后,对 15 页提取结构化观感事实(颜色/卡壳/分页坐标/按钮形态/标题/列头/空态)。
|
||||
// 用法:cd admin-frontend-vue && node scripts/round2-audit.mjs
|
||||
import { chromium } from '@playwright/test'
|
||||
|
||||
const BASE = process.env.BASE_URL || 'http://localhost:5174/admin-vue'
|
||||
|
||||
const PAGES = [
|
||||
['account-users', 'account/users'],
|
||||
['account-menus', 'account/menus'],
|
||||
['account-groups', 'account/groups'],
|
||||
['asin-registry', 'asin-center/registry'],
|
||||
['asin-invalid', 'asin-center/invalid'],
|
||||
['asin-query', 'asin-center/query'],
|
||||
['asin-categories', 'asin-center/categories'],
|
||||
['asin-skip-price', 'asin-center/skip-price'],
|
||||
['shop-keys', 'shop-center/keys'],
|
||||
['shop-shops', 'shop-center/shops'],
|
||||
['shop-data-tasks', 'shop-center/data-tasks'],
|
||||
['records-history', 'records/history'],
|
||||
['records-software-version', 'records/software-version'],
|
||||
['records-digital-human-version', 'records/digital-human-version'],
|
||||
['records-image-video-tasks', 'records/image-video-tasks'],
|
||||
]
|
||||
|
||||
const browser = await chromium.launch({ channel: 'msedge', headless: true })
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'zh-CN' })
|
||||
const page = await context.newPage()
|
||||
|
||||
async function ensureLoggedIn() {
|
||||
await page.goto(`${BASE}/`, { waitUntil: 'networkidle' })
|
||||
await page.waitForTimeout(600)
|
||||
if (await page.locator('#loginUsername').isVisible().catch(() => false)) {
|
||||
await page.locator('#loginUsername').fill('admin')
|
||||
await page.locator('#loginPassword').fill('admin123')
|
||||
await page.locator('.btn-login').click()
|
||||
await page.waitForURL(/admin-vue\/(account|asin|shop|records)/, { timeout: 20000 }).catch(() => {})
|
||||
await page.waitForTimeout(1200)
|
||||
}
|
||||
}
|
||||
await ensureLoggedIn()
|
||||
|
||||
const out = {}
|
||||
for (const [name, path] of PAGES) {
|
||||
await page.goto(`${BASE}/${path}`, { waitUntil: 'domcontentloaded' })
|
||||
await page.locator('.page-heading').first().waitFor({ state: 'visible', timeout: 12000 }).catch(() => {})
|
||||
await page.waitForLoadState('networkidle').catch(() => {})
|
||||
await page.waitForTimeout(500)
|
||||
|
||||
const fact = await page.evaluate(() => {
|
||||
const cs = (el, prop) => (el ? getComputedStyle(el)[prop] : null)
|
||||
const root = getComputedStyle(document.documentElement)
|
||||
const q = (sel) => document.querySelectorAll(sel)
|
||||
const text = (el) => (el ? (el.textContent || '').trim() : '')
|
||||
const heading = document.querySelector('.page-heading h1, .page-heading h2, .page-heading .page-title')
|
||||
const headingText = heading ? (heading.textContent || '').trim() : null
|
||||
const pags = [...q('.el-pagination')].map((p) => {
|
||||
const r = p.getBoundingClientRect()
|
||||
return { y: Math.round(r.top), x: Math.round(r.left), w: Math.round(r.width) }
|
||||
})
|
||||
const btns = [...q('.el-button')].map((b) => {
|
||||
const t = (b.textContent || '').trim().slice(0, 8)
|
||||
return { t, link: b.classList.contains('is-link'), text: b.classList.contains('is-text'), primary: b.classList.contains('el-button--primary'), danger: b.classList.contains('el-button--danger') }
|
||||
})
|
||||
const ths = [...q('.el-table__header th')].map((x) => (x.textContent || '').trim())
|
||||
const empty = q('.el-empty, .empty-tip, .empty').length
|
||||
const emptyText = text(document.querySelector('.el-empty, .empty-tip')) || null
|
||||
const indigoEls = [...q('body *')].filter((el) => {
|
||||
const b = cs(el, 'backgroundColor')
|
||||
const c = cs(el, 'color')
|
||||
return /rgb\(99,\s*102,\s*241\)|rgb\(238,\s*240,\s*254\)|#6366f1|#eef0fe/i.test(`${b} ${c}`)
|
||||
}).slice(0, 4).map((el) => ({ tag: el.tagName, cls: (el.className && String(el.className).slice(0, 60)) || '', bg: cs(el, 'backgroundColor'), color: cs(el, 'color') }))
|
||||
const cards = q('.el-card').length
|
||||
const toolbars = q('.table-toolbar, .list-toolbar').length
|
||||
const pageHeadingDesc = text(document.querySelector('.page-heading p'))
|
||||
return {
|
||||
heading: headingText, desc: (pageHeadingDesc || '').slice(0, 80),
|
||||
primary: root.getPropertyValue('--el-color-primary').trim(),
|
||||
bg: root.getPropertyValue('--el-bg-color').trim() || cs(document.body, 'backgroundColor'),
|
||||
paginations: pags, cards, toolbars,
|
||||
ths: ths.slice(0, 14), empty, emptyText,
|
||||
buttonShape: {
|
||||
total: btns.length,
|
||||
link: btns.filter((b) => b.link).length,
|
||||
textPlain: btns.filter((b) => b.text && !b.link).length,
|
||||
primarySolid: btns.filter((b) => b.primary && !b.text && !b.link).length,
|
||||
danger: btns.filter((b) => b.danger).length,
|
||||
sample: btns.slice(0, 12),
|
||||
},
|
||||
indigoEls,
|
||||
}
|
||||
})
|
||||
out[name] = { path, ...fact }
|
||||
}
|
||||
|
||||
console.log(JSON.stringify(out, null, 2))
|
||||
await browser.close()
|
||||
@@ -1,97 +0,0 @@
|
||||
// round2 现状截图基线:本地真实栈(5174 -> 18080 Java),登录后逐页截图 + 收集 pageerror/console error。
|
||||
// 用法:cd admin-frontend-vue && node scripts/round2-shots.mjs
|
||||
import { chromium } from '@playwright/test'
|
||||
import { mkdirSync } from 'node:fs'
|
||||
|
||||
const BASE = process.env.BASE_URL || 'http://localhost:5174/admin-vue'
|
||||
const OUT = 'test-results/round2-baseline'
|
||||
mkdirSync(OUT, { recursive: true })
|
||||
|
||||
const PAGES = [
|
||||
['account-users', 'account/users'],
|
||||
['account-menus', 'account/menus'],
|
||||
['account-groups', 'account/groups'],
|
||||
['asin-registry', 'asin-center/registry'],
|
||||
['asin-invalid', 'asin-center/invalid'],
|
||||
['asin-query', 'asin-center/query'],
|
||||
['asin-categories', 'asin-center/categories'],
|
||||
['asin-skip-price', 'asin-center/skip-price'],
|
||||
['shop-keys', 'shop-center/keys'],
|
||||
['shop-shops', 'shop-center/shops'],
|
||||
['shop-data-tasks', 'shop-center/data-tasks'],
|
||||
['records-history', 'records/history'],
|
||||
['records-software-version', 'records/software-version'],
|
||||
['records-digital-human-version', 'records/digital-human-version'],
|
||||
['records-image-video-tasks', 'records/image-video-tasks'],
|
||||
]
|
||||
|
||||
const browser = await chromium.launch({ channel: 'msedge', headless: true })
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'zh-CN' })
|
||||
const page = await context.newPage()
|
||||
|
||||
const problems = new Map() // page -> string[]
|
||||
page.on('pageerror', (e) => {
|
||||
const key = page.url()
|
||||
const list = problems.get(key) || []
|
||||
list.push(`pageerror: ${e.message}`)
|
||||
problems.set(key, list)
|
||||
})
|
||||
page.on('console', (m) => {
|
||||
if (m.type() === 'error') {
|
||||
const key = page.url()
|
||||
const list = problems.get(key) || []
|
||||
list.push(`console.error: ${m.text().slice(0, 300)}`)
|
||||
problems.set(key, list)
|
||||
}
|
||||
})
|
||||
|
||||
// 登录(真实 UI 表单)
|
||||
async function ensureLoggedIn() {
|
||||
await page.goto(`${BASE}/`, { waitUntil: 'networkidle' })
|
||||
await page.waitForTimeout(600)
|
||||
const loginVisible = await page.locator('#loginUsername').isVisible().catch(() => false)
|
||||
if (loginVisible) {
|
||||
await page.locator('#loginUsername').fill('admin')
|
||||
await page.locator('#loginPassword').fill('admin123')
|
||||
await page.locator('.btn-login').click()
|
||||
// 等离开登录页(进入后台)
|
||||
await page.waitForURL(/admin-vue\/(account|asin|shop|records)/, { timeout: 20000 }).catch(() => {})
|
||||
await page.waitForTimeout(1200)
|
||||
}
|
||||
}
|
||||
|
||||
await ensureLoggedIn()
|
||||
console.log('logged-in url:', page.url())
|
||||
|
||||
const report = []
|
||||
for (const [name, path] of PAGES) {
|
||||
const url = `${BASE}/${path}`
|
||||
try {
|
||||
await page.goto(url, { waitUntil: 'domcontentloaded' })
|
||||
// 等页头或内容出现(不同页标题不同,抓第一个标题/内容容器)
|
||||
await page.locator('.page-heading').first().waitFor({ state: 'visible', timeout: 12000 }).catch(() => {})
|
||||
await page.waitForLoadState('networkidle').catch(() => {})
|
||||
await page.waitForTimeout(500)
|
||||
await page.screenshot({ path: `${OUT}/${name}.jpg`, type: 'jpeg', quality: 82 })
|
||||
report.push(`ok ${name} ${url}`)
|
||||
} catch (e) {
|
||||
report.push(`FAIL ${name} ${url} :: ${String(e).slice(0, 200)}`)
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n=== screenshots ===')
|
||||
console.log(report.join('\n'))
|
||||
|
||||
console.log('\n=== page errors (运行时异常,供排查) ===')
|
||||
let anyError = false
|
||||
for (const [url, list] of problems) {
|
||||
const clean = url.replace(BASE, '')
|
||||
if (list.length) {
|
||||
anyError = true
|
||||
console.log(`-- ${clean}`)
|
||||
for (const l of [...new Set(list)]) console.log(' ', l)
|
||||
}
|
||||
}
|
||||
if (!anyError) console.log('(无 pageerror/console.error)')
|
||||
|
||||
await browser.close()
|
||||
@@ -1,45 +0,0 @@
|
||||
// round2 单批验证:guides 渲染 + 类目色点 token + 行内按钮实心(本地真实栈)。
|
||||
import { chromium } from '@playwright/test'
|
||||
const BASE = 'http://localhost:5174/admin-vue'
|
||||
const browser = await chromium.launch({ channel: 'msedge', headless: true })
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } })
|
||||
await page.goto(`${BASE}/`, { waitUntil: 'networkidle' })
|
||||
await page.waitForTimeout(500)
|
||||
if (await page.locator('#loginUsername').isVisible().catch(() => false)) {
|
||||
await page.locator('#loginUsername').fill('admin')
|
||||
await page.locator('#loginPassword').fill('admin123')
|
||||
await page.locator('.btn-login').click()
|
||||
await page.waitForURL(/admin-vue\/(account|asin|shop|records)/, { timeout: 20000 }).catch(() => {})
|
||||
await page.waitForTimeout(1200)
|
||||
}
|
||||
async function open(path) {
|
||||
await page.goto(`${BASE}/${path}`, { waitUntil: 'domcontentloaded' })
|
||||
await page.locator('.page-heading').first().waitFor({ state: 'visible', timeout: 15000 }).catch(() => {})
|
||||
await page.waitForLoadState('networkidle').catch(() => {})
|
||||
await page.waitForTimeout(600)
|
||||
}
|
||||
|
||||
await open('account/users')
|
||||
const guide = await page.locator('.operation-guide').count()
|
||||
const guideText = guide ? (await page.locator('.og-text').textContent())?.trim() : null
|
||||
console.log('users guide visible:', guide > 0, '| text:', guideText)
|
||||
|
||||
await open('asin-center/categories')
|
||||
const token = await page.evaluate(() => {
|
||||
const el = document.querySelector('.tree-node-mark')
|
||||
if (!el) return null
|
||||
const cs = getComputedStyle(el)
|
||||
return { color: cs.color, bg: cs.backgroundColor }
|
||||
})
|
||||
console.log('categories tree-node-mark:', JSON.stringify(token))
|
||||
|
||||
await open('asin-center/registry')
|
||||
const solid = await page.evaluate(() => {
|
||||
const btns = [...document.querySelectorAll('.el-table .el-button--small')]
|
||||
const linkOrText = btns.filter((b) => b.classList.contains('is-link') || b.classList.contains('is-text')).length
|
||||
const primary = btns.filter((b) => b.classList.contains('el-button--primary')).length
|
||||
return { smallSolid: btns.length, linkOrText, primary }
|
||||
})
|
||||
console.log('registry row buttons:', JSON.stringify(solid))
|
||||
|
||||
await browser.close()
|
||||
@@ -1,17 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { RouterView } from 'vue-router'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import { useGlobalErrorReporting } from '@/shared/api/error-report'
|
||||
|
||||
// 浏览器级错误兜底接线(S1-F2/AC-16):脚本级崩溃与没人接的 Promise 都进同一条上报路,
|
||||
// 卸载出口由该 composable 的 onBeforeUnmount 摘掉——根组件不卸载时它就是应用级单例。
|
||||
useGlobalErrorReporting()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- 摘掉整包 use(ElementPlus, { locale }) 后,全局配置只能走 config-provider:
|
||||
日期控件(周/月/年份)、分页组件(上一页/下一页)靠它显示中文。 -->
|
||||
<el-config-provider :locale="zhCn">
|
||||
<RouterView />
|
||||
</el-config-provider>
|
||||
</template>
|
||||
@@ -1,211 +0,0 @@
|
||||
import { http, unwrap } from '@/api/http'
|
||||
|
||||
/**
|
||||
* 大档分片阈值与片大小(AC-11):后管这一侧只有这一个出口,阈值由片大小派生。
|
||||
*
|
||||
* ⚠ 同族的 8MB 数还另有两处:用户端上传出口一处、桌面客户端分片入口一处。两边是各自
|
||||
* 独立的构建根(各自的 `@` 别名与 tsconfig include),客户端是 Python 打包物 ⇒
|
||||
* 没有共享包就合不成同一个字面量(P3-5 的边界,已登记)。
|
||||
*/
|
||||
export const CHUNK_UPLOAD_PART_SIZE = 8 * 1024 * 1024
|
||||
export const CHUNK_UPLOAD_THRESHOLD = CHUNK_UPLOAD_PART_SIZE
|
||||
|
||||
/** 每片重试次数(不含首次):单片 502/超时不该让 512MB 从 0 再来。 */
|
||||
const PART_RETRY_LIMIT = 2
|
||||
|
||||
/**
|
||||
* 逐片超时(P2-8):预算只看**这一片**有多大——60s 保底 + 每 MB 30s(8MB 片=300s)。
|
||||
* 过去按整包体积算(120s + MB×15s),512MB 包里的一个 8MB 片能拿到 128 分钟,
|
||||
* 慢链路真卡死时没人知道,进度条还会一直爬。
|
||||
*/
|
||||
export function partTimeoutOf(partBytes: number): number {
|
||||
return 60_000 + Math.ceil(partBytes / (1024 * 1024)) * 30_000
|
||||
}
|
||||
|
||||
/** 会话登记/查询只发元数据,固定预算即可;失败要快快回来,别陪整包一起放大。 */
|
||||
const REQUEST_TIMEOUT_MS = 60_000
|
||||
/** 只有拼装这一步真随整包体积走:服务端要读全部分片、复算 sha256。 */
|
||||
const COMPLETE_TIMEOUT_MS = 600_000
|
||||
|
||||
function partUrl(uploadId: string, index: number): string {
|
||||
return `/api/files/chunk/${encodeURIComponent(uploadId)}/part/${index}`
|
||||
}
|
||||
|
||||
/** 分片会话跨尝试/刷新续用:同一文件身份复用 upload_id,服务端没回收就从已达片号继续(P2-7)。 */
|
||||
interface StoredChunkSession {
|
||||
uploadId: string;
|
||||
size: number;
|
||||
lastModified: number;
|
||||
}
|
||||
|
||||
const CHUNK_SESSION_PREFIX = 'shufu:admin:chunk:'
|
||||
|
||||
function lastModifiedOf(file: Blob): number {
|
||||
const value = (file as File).lastModified
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : 0
|
||||
}
|
||||
|
||||
/** 会话键:文件名+体积+修改时间,三者同一条上传才算同一个件。 */
|
||||
export function chunkSessionKeyOf(fileName: string, file: Blob): string {
|
||||
return `${CHUNK_SESSION_PREFIX}${fileName}:${file.size}:${lastModifiedOf(file)}`
|
||||
}
|
||||
|
||||
function readStoredSession(key: string, file: Blob): string {
|
||||
if (typeof localStorage === 'undefined') return ''
|
||||
try {
|
||||
const raw = localStorage.getItem(key)
|
||||
if (!raw) return ''
|
||||
const parsed = JSON.parse(raw) as StoredChunkSession
|
||||
return parsed.size === file.size && parsed.lastModified === lastModifiedOf(file) ? parsed.uploadId : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function writeStoredSession(key: string, file: Blob, uploadId: string): void {
|
||||
if (typeof localStorage === 'undefined') return
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify({
|
||||
uploadId, size: file.size, lastModified: lastModifiedOf(file),
|
||||
} satisfies StoredChunkSession))
|
||||
} catch {
|
||||
// 存储不可用(隐私模式/配额满)只影响跨刷新续传,不影响本次上传
|
||||
}
|
||||
}
|
||||
|
||||
function clearStoredSession(key: string): void {
|
||||
if (typeof localStorage === 'undefined') return
|
||||
try {
|
||||
localStorage.removeItem(key)
|
||||
} catch {
|
||||
// 同上:清不掉只会让下次多问一次 status
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务端对「这个会话还在不在」的三种答复:还在(附带已到片号)/确实没了/问不出来。
|
||||
* 第三态是 P2-7 与 P1-11 的共同判据——过去它被当成"没会话",瞬态抖动=整包作废。
|
||||
*/
|
||||
type ProbeOutcome
|
||||
= { state: 'ok'; parts: number[] }
|
||||
| { state: 'gone' }
|
||||
| { state: 'transient' }
|
||||
|
||||
/** 后端回收会话的原文案(ChunkedUploadService.readMeta);BusinessException 不带 code ⇒ HTTP 200 出。 */
|
||||
function messageSaysSessionGone(text: unknown): boolean {
|
||||
const message = typeof text === 'string' ? text : ''
|
||||
return ['不存在', '过期'].some((marker) => message.includes(marker))
|
||||
}
|
||||
|
||||
function classifyProbe(response: unknown): ProbeOutcome {
|
||||
const status = Number((response as { status?: unknown } | null | undefined)?.status)
|
||||
if (status === 404) return { state: 'gone' }
|
||||
if (status >= 500 || status === 408 || status === 429) return { state: 'transient' }
|
||||
const body = (response as { data?: unknown } | null | undefined)?.data
|
||||
if (body && typeof body === 'object' && (body as { success?: unknown }).success === false) {
|
||||
return messageSaysSessionGone((body as { message?: unknown }).message)
|
||||
? { state: 'gone' }
|
||||
: { state: 'transient' }
|
||||
}
|
||||
const core = (unwrap<Record<string, unknown>>(body) ?? {}) as Record<string, unknown>
|
||||
const arrived = core.uploaded_parts
|
||||
return { state: 'ok', parts: Array.isArray(arrived) ? arrived.map((value) => Number(value)) : [] }
|
||||
}
|
||||
|
||||
/**
|
||||
* 探测已达片号(P2-7/与用户端 upload.ts 同一口径)。
|
||||
* validateStatus 恒真:状态码要自己判——真 404/5xx 一旦被拦截器折成 Error 就分不出原因了;
|
||||
* 能走到 catch 的就只剩网络层失败与超时,铁定瞬态。
|
||||
*/
|
||||
async function probeUploadedParts(uploadId: string): Promise<ProbeOutcome> {
|
||||
try {
|
||||
const response = await http.get(
|
||||
`/api/files/chunk/${encodeURIComponent(uploadId)}`,
|
||||
{ validateStatus: () => true },
|
||||
)
|
||||
return classifyProbe(response)
|
||||
} catch (error) {
|
||||
const status = (error as { response?: { status?: unknown } } | null | undefined)?.response?.status
|
||||
if (status === 404) return { state: 'gone' }
|
||||
if (messageSaysSessionGone((error as { message?: unknown } | null | undefined)?.message)) {
|
||||
return { state: 'gone' }
|
||||
}
|
||||
return { state: 'transient' }
|
||||
}
|
||||
}
|
||||
|
||||
/** 后管大档上传(版本包/教程包共用):会话续用 → GET 已达片号 → 逐片 POST → complete。 */
|
||||
export async function uploadFileInChunks(
|
||||
file: Blob,
|
||||
fileName: string,
|
||||
onProgress?: (percent: number) => void,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const totalParts = Math.max(1, Math.ceil(file.size / CHUNK_UPLOAD_PART_SIZE))
|
||||
const sessionKey = chunkSessionKeyOf(fileName, file)
|
||||
let uploadId = readStoredSession(sessionKey, file)
|
||||
const arrived = new Set<number>()
|
||||
if (uploadId) {
|
||||
const probed = await probeUploadedParts(uploadId)
|
||||
if (probed.state === 'gone') {
|
||||
// 服务端确实说会话没了(404/「不存在或已过期」):清掉重开,否则这个件每次都在同一个死会话上失败。
|
||||
clearStoredSession(sessionKey)
|
||||
uploadId = ''
|
||||
} else if (probed.state === 'ok') {
|
||||
probed.parts.forEach((index) => arrived.add(index))
|
||||
}
|
||||
// transient:片号未知但会话还在 ⇒ 照原会话逐片重传(后端同片覆盖,幂等),不重开 init。
|
||||
}
|
||||
if (!uploadId) {
|
||||
const initResponse = await http.post('/api/files/chunk/init', null, {
|
||||
params: { fileName, totalParts, totalBytes: file.size },
|
||||
timeout: REQUEST_TIMEOUT_MS,
|
||||
})
|
||||
const init = (unwrap(initResponse.data) ?? {}) as Record<string, unknown>
|
||||
uploadId = String(init.upload_id ?? '')
|
||||
if (!uploadId) {
|
||||
throw new Error('后端未返回分片会话,请重试')
|
||||
}
|
||||
writeStoredSession(sessionKey, file, uploadId)
|
||||
}
|
||||
|
||||
for (let index = 0; index < totalParts; index += 1) {
|
||||
if (arrived.has(index)) {
|
||||
continue
|
||||
}
|
||||
const blob = file.slice(index * CHUNK_UPLOAD_PART_SIZE,
|
||||
Math.min(file.size, (index + 1) * CHUNK_UPLOAD_PART_SIZE))
|
||||
let lastError: unknown = null
|
||||
for (let attempt = 0; attempt <= PART_RETRY_LIMIT; attempt += 1) {
|
||||
const form = new FormData()
|
||||
form.append('file', blob, `part-${index}`)
|
||||
try {
|
||||
const partResponse = await http.post(partUrl(uploadId, index), form, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
timeout: partTimeoutOf(blob.size),
|
||||
onUploadProgress: (event) => {
|
||||
if (!onProgress) return
|
||||
const perPart = Math.round(((index + (event.loaded || 0) / Math.max(blob.size, 1)) / totalParts) * 100)
|
||||
onProgress(Math.min(perPart, 99))
|
||||
},
|
||||
})
|
||||
unwrap(partResponse.data)
|
||||
arrived.add(index)
|
||||
lastError = null
|
||||
break
|
||||
} catch (error) {
|
||||
lastError = error
|
||||
}
|
||||
}
|
||||
if (lastError) {
|
||||
// 不 DELETE(P2-7):会话连同已达片号留在服务端(后端 24h 过期回收兜底),
|
||||
// 下一次点开同一个文件就从断点接着传——这才是"续传"两个字的本义。
|
||||
throw lastError instanceof Error ? lastError : new Error('分片上传失败')
|
||||
}
|
||||
}
|
||||
|
||||
const completeResponse = await http.post(
|
||||
`/api/files/chunk/${encodeURIComponent(uploadId)}/complete`, null, { timeout: COMPLETE_TIMEOUT_MS })
|
||||
clearStoredSession(sessionKey)
|
||||
if (onProgress) onProgress(100)
|
||||
return (unwrap(completeResponse.data) ?? {}) as Record<string, unknown>
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
/** 公司目录 DTO(设计文档 §2.3):纯逻辑,无框架依赖。 */
|
||||
|
||||
/** company.company_name 是 varchar(128),前端同步限长,免得撞库上 1406。 */
|
||||
export const COMPANY_NAME_MAX_LENGTH = 128
|
||||
|
||||
/** company.status:1=启用 0=停用(与 V143 列注释同口径)。 */
|
||||
export const COMPANY_STATUS_ACTIVE = 1
|
||||
export const COMPANY_STATUS_DISABLED = 0
|
||||
|
||||
/** 前端公司项(camelCase,与 Java CompanyVo 的 snake_case 线上字段对应)。 */
|
||||
export interface CompanyItem {
|
||||
id: number
|
||||
companyName: string
|
||||
status: number
|
||||
remark: string | null
|
||||
createdAt: string | null
|
||||
updatedAt: string | null
|
||||
/** 所属平台(V206):'amazon'|'jd';后端恒带值(列 NOT NULL DEFAULT 'amazon'),旧负载缺省不渲染。 */
|
||||
platform?: string
|
||||
}
|
||||
|
||||
/** 新建/改名的表单草稿。 */
|
||||
export interface CompanyDraft {
|
||||
companyName: string
|
||||
status?: number
|
||||
remark?: string | null
|
||||
/** 所属平台(V206):新建必带(页面从平台 tab 取),编辑显式下发,缺省后端不动。 */
|
||||
platform?: string
|
||||
}
|
||||
|
||||
export function text(value: unknown): string {
|
||||
return typeof value === 'string' ? value : ''
|
||||
}
|
||||
|
||||
export function trimmedOrNull(value: unknown): string | null {
|
||||
const raw = text(value).trim()
|
||||
return raw || null
|
||||
}
|
||||
|
||||
/** 校验草稿,返回错误文案;合法返回空串。 */
|
||||
export function validateCompanyDraft(draft: CompanyDraft): string {
|
||||
const name = text(draft.companyName).trim()
|
||||
if (!name) return '公司名称不能为空'
|
||||
if (name.length > COMPANY_NAME_MAX_LENGTH) {
|
||||
return `公司名称长度不能超过 ${COMPANY_NAME_MAX_LENGTH} 个字符`
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
/** 草稿 → POST/PUT 请求体(Java 侧 CompanySaveRequest 是 camelCase,与 AdminUserCreateRequest 同口径)。 */
|
||||
export function toCompanyPayload(draft: CompanyDraft): Record<string, unknown> {
|
||||
const payload: Record<string, unknown> = { companyName: text(draft.companyName).trim() }
|
||||
if (typeof draft.status === 'number') payload.status = draft.status
|
||||
payload.remark = trimmedOrNull(draft.remark)
|
||||
if (draft.platform) payload.platform = draft.platform
|
||||
return payload
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
/** 公司目录响应解析:Java CompanyVo(snake_case) → 前端 CompanyItem(camelCase)。 */
|
||||
import { unwrap } from './envelope.ts'
|
||||
import {
|
||||
COMPANY_STATUS_ACTIVE,
|
||||
COMPANY_STATUS_DISABLED,
|
||||
text,
|
||||
trimmedOrNull,
|
||||
type CompanyItem,
|
||||
} from './companies-dto.ts'
|
||||
|
||||
function numberOrNull(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : null
|
||||
}
|
||||
|
||||
/** 单条映射;无 id 视为无效行(列表中直接丢弃,避免编辑时打到 /companies/undefined)。 */
|
||||
export function toCompanyItem(raw: unknown): CompanyItem | null {
|
||||
if (!raw || typeof raw !== 'object') return null
|
||||
const r = raw as Record<string, unknown>
|
||||
const id = numberOrNull(r.id)
|
||||
if (id === null) return null
|
||||
const item: CompanyItem = {
|
||||
id,
|
||||
companyName: text(r.company_name),
|
||||
// status 列 NOT NULL,取不到就是链路异常;未知一律按停用,不把异常状态当启用。
|
||||
status: r.status === COMPANY_STATUS_ACTIVE ? COMPANY_STATUS_ACTIVE : COMPANY_STATUS_DISABLED,
|
||||
remark: trimmedOrNull(r.remark),
|
||||
createdAt: trimmedOrNull(r.created_at),
|
||||
updatedAt: trimmedOrNull(r.updated_at),
|
||||
}
|
||||
// platform 后端恒带(列 NOT NULL);旧负载/测试桩缺省就不渲染该键,字段形状与 users-model 一致。
|
||||
const platform = text(r.platform)
|
||||
if (platform) item.platform = platform
|
||||
return item
|
||||
}
|
||||
|
||||
/** 解析 GET /api/admin/companies:接受 data 为数组或 {items:[...]},success=false 抛后端文案。 */
|
||||
export function parseCompanyList(payload: unknown): CompanyItem[] {
|
||||
const core = unwrap<unknown>(payload)
|
||||
if (!core || typeof core !== 'object') return []
|
||||
const candidate = Array.isArray(core) ? core : (core as { items?: unknown }).items
|
||||
if (!Array.isArray(candidate)) return []
|
||||
return candidate
|
||||
.map((raw) => toCompanyItem(raw))
|
||||
.filter((item): item is CompanyItem => item !== null)
|
||||
}
|
||||
|
||||
/** 解析 POST/PUT 回包(data 为 CompanyVo)。 */
|
||||
export function parseCompany(payload: unknown): CompanyItem | null {
|
||||
const core = unwrap<unknown>(payload)
|
||||
if (!core || typeof core !== 'object' || Array.isArray(core)) return null
|
||||
return toCompanyItem(core)
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import { http } from './http'
|
||||
import { parseCompany, parseCompanyList } from './companies-model'
|
||||
import { toCompanyPayload, type CompanyDraft, type CompanyItem } from './companies-dto'
|
||||
|
||||
/** 公司目录(设计文档 §2.3)。GET 的可见范围由后端收窄:超管全部、公司内 admin 只自己公司。 */
|
||||
|
||||
export async function fetchCompanies(platform?: string): Promise<CompanyItem[]> {
|
||||
const { data } = await http.get('/api/admin/companies', {
|
||||
params: platform ? { platform } : {},
|
||||
})
|
||||
return parseCompanyList(data)
|
||||
}
|
||||
|
||||
export async function createCompany(draft: CompanyDraft): Promise<CompanyItem | null> {
|
||||
const { data } = await http.post('/api/admin/companies', toCompanyPayload(draft))
|
||||
return parseCompany(data)
|
||||
}
|
||||
|
||||
/** 改名 / 启停;后端不做删除,停用即 status=0。 */
|
||||
export async function updateCompany(id: number, draft: CompanyDraft): Promise<CompanyItem | null> {
|
||||
const { data } = await http.put(`/api/admin/companies/${id}`, toCompanyPayload(draft))
|
||||
return parseCompany(data)
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
import { http } from './http'
|
||||
import { unwrap } from './envelope'
|
||||
|
||||
/** 日志文件行(桌面客户端 / 麦象采集机上报)。 */
|
||||
export interface DeviceLogFileRow {
|
||||
id: number
|
||||
source: string
|
||||
deviceId: string
|
||||
deviceName: string | null
|
||||
username: string | null
|
||||
uid: number | null
|
||||
fileName: string
|
||||
logDate: string
|
||||
uploadedBytes: number
|
||||
partCount: number
|
||||
lastUploadAt: string | null
|
||||
createdAt: string | null
|
||||
}
|
||||
|
||||
export interface DeviceLogPage {
|
||||
items: DeviceLogFileRow[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
/** 云端日志保留天数(页面提示用)。 */
|
||||
retentionDays: number
|
||||
}
|
||||
|
||||
export interface DeviceLogContent {
|
||||
fileId: number
|
||||
fileName: string
|
||||
content: string
|
||||
totalBytes: number
|
||||
shownBytes: number
|
||||
truncated: boolean
|
||||
}
|
||||
|
||||
export interface DeviceLogDevice {
|
||||
source: string
|
||||
deviceId: string
|
||||
deviceName: string | null
|
||||
lastUploadAt: string | null
|
||||
}
|
||||
|
||||
export interface DeviceLogOverride {
|
||||
id: number
|
||||
source: string
|
||||
deviceId: string
|
||||
deviceName: string | null
|
||||
mode: string
|
||||
updatedAt: string | null
|
||||
}
|
||||
|
||||
export interface DeviceLogConfigData {
|
||||
globalMode: string
|
||||
overrides: DeviceLogOverride[]
|
||||
}
|
||||
|
||||
export interface DeviceLogQuery {
|
||||
source?: string
|
||||
/** 指定用户(users.id);不传=全部上报者,含 uid 为空的采集机与未登录客户端。 */
|
||||
uid?: number
|
||||
startDate?: string
|
||||
endDate?: string
|
||||
page: number
|
||||
pageSize: number
|
||||
/** 超管选中的公司 tab;null/undefined=不发这个参数,后端按「不筛」出全量(非超管恒不发)。 */
|
||||
companyId?: number | null
|
||||
}
|
||||
|
||||
/** 分页查询日志文件列表:GET /api/admin/device-logs/files */
|
||||
export async function fetchDeviceLogFiles(params: DeviceLogQuery): Promise<DeviceLogPage> {
|
||||
const query: Record<string, string | number> = { page: params.page, pageSize: params.pageSize }
|
||||
if (params.source) query.source = params.source
|
||||
if (params.uid) query.uid = params.uid
|
||||
if (params.startDate) query.startDate = params.startDate
|
||||
if (params.endDate) query.endDate = params.endDate
|
||||
// 公司值由页面组件(companyTab.requestCompanyId)传进来,本模块不读 Pinia store。
|
||||
// query 是这里逐字段点名的白名单构造 ⇒ 右半边只许取原始 params。
|
||||
if (params.companyId != null) query.company_id = params.companyId
|
||||
const { data } = await http.get('/api/admin/device-logs/files', { params: query })
|
||||
return unwrap<DeviceLogPage>(data)
|
||||
}
|
||||
|
||||
/** 查看日志尾部内容:GET /api/admin/device-logs/content */
|
||||
export async function fetchDeviceLogContent(fileId: number, maxBytes?: number): Promise<DeviceLogContent> {
|
||||
const query: Record<string, number> = { fileId }
|
||||
if (maxBytes) query.maxBytes = maxBytes
|
||||
const { data } = await http.get('/api/admin/device-logs/content', { params: query })
|
||||
return unwrap<DeviceLogContent>(data)
|
||||
}
|
||||
|
||||
/** 完整日志下载地址(同域 cookie 鉴权,直接给 a[href] 或 window.open 用)。 */
|
||||
export function deviceLogDownloadUrl(fileId: number): string {
|
||||
return `/api/admin/device-logs/download?fileId=${fileId}`
|
||||
}
|
||||
|
||||
/** 删除日志文件(片段与元数据,不可恢复):DELETE /api/admin/device-logs/{id} */
|
||||
export async function deleteDeviceLogFile(id: number): Promise<void> {
|
||||
const { data } = await http.delete(`/api/admin/device-logs/${id}`)
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
|
||||
/** 采集配置(全局默认 + 终端覆盖):GET /api/admin/device-logs/config */
|
||||
export async function fetchDeviceLogConfig(keyword?: string): Promise<DeviceLogConfigData> {
|
||||
const { data } = await http.get('/api/admin/device-logs/config', {
|
||||
params: keyword ? { keyword } : undefined,
|
||||
})
|
||||
return unwrap<DeviceLogConfigData>(data)
|
||||
}
|
||||
|
||||
/** 最近上报过的终端(覆盖选择用):GET /api/admin/device-logs/devices */
|
||||
export async function fetchDeviceLogDevices(): Promise<DeviceLogDevice[]> {
|
||||
const { data } = await http.get('/api/admin/device-logs/devices')
|
||||
return unwrap<DeviceLogDevice[]>(data)
|
||||
}
|
||||
|
||||
/** 设置全局采集模式:PUT /api/admin/device-logs/config/global */
|
||||
export async function updateDeviceLogGlobalMode(mode: string): Promise<void> {
|
||||
const { data } = await http.put('/api/admin/device-logs/config/global', undefined, { params: { mode } })
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
|
||||
/** 设置/更新终端覆盖:PUT /api/admin/device-logs/config/device */
|
||||
export async function updateDeviceLogOverride(
|
||||
source: string,
|
||||
deviceId: string,
|
||||
deviceName: string | null,
|
||||
mode: string,
|
||||
): Promise<void> {
|
||||
const { data } = await http.put('/api/admin/device-logs/config/device', undefined, {
|
||||
params: { source, deviceId, deviceName: deviceName || undefined, mode },
|
||||
})
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
|
||||
/** 删除终端覆盖(回落到全局默认):DELETE /api/admin/device-logs/config/device/{id} */
|
||||
export async function deleteDeviceLogOverride(id: number): Promise<void> {
|
||||
const { data } = await http.delete(`/api/admin/device-logs/config/device/${id}`)
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
/** API 响应解包与错误归一化(任务 22):纯函数,无框架依赖(只借 config/app 的 base 常量)。 */
|
||||
import { userNotice } from './user-notice.ts'
|
||||
import { joinAdminPath } from '../config/app.ts'
|
||||
|
||||
export const REQUEST_FALLBACK_MESSAGE = '网络异常,请稍后重试'
|
||||
|
||||
function textOf(value: Record<string, unknown>): string {
|
||||
const message = value.message
|
||||
const error = value.error
|
||||
if (typeof message === 'string' && message.trim()) return userNotice(message)
|
||||
if (typeof error === 'string' && error.trim()) return userNotice(error)
|
||||
return ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一解包 Java 响应:
|
||||
* - success=false -> 抛错(取 message/error,空则“请求失败”);
|
||||
* - 带非空 data -> 返回 data;
|
||||
* - 否则原样返回(允许 {item}/{items} 等信封由调用方再解)。
|
||||
*/
|
||||
export function unwrap<T>(payload: unknown): T {
|
||||
const value = payload as Record<string, unknown> | null
|
||||
if (!value || typeof value !== 'object') return payload as T
|
||||
if (value.success === false) {
|
||||
throw new Error(textOf(value) || '请求失败')
|
||||
}
|
||||
if ('data' in value && value.data !== null && value.data !== undefined) {
|
||||
return value.data as T
|
||||
}
|
||||
return payload as T
|
||||
}
|
||||
|
||||
/** 从任意负载取错误文案;缺省回退。 */
|
||||
export function errorTextOf(payload: unknown): string {
|
||||
if (payload instanceof Error) return userNotice(payload.message, REQUEST_FALLBACK_MESSAGE)
|
||||
if (payload && typeof payload === 'object') {
|
||||
const text = textOf(payload as Record<string, unknown>)
|
||||
if (text) return text
|
||||
}
|
||||
if (typeof payload === 'string' && payload.trim()) return payload
|
||||
return REQUEST_FALLBACK_MESSAGE
|
||||
}
|
||||
|
||||
/** 负载/状态码是否 401(未登录)。 */
|
||||
export function isUnauthorized(payload: unknown): boolean {
|
||||
const record = payload as { status?: unknown; statusCode?: unknown; code?: unknown } | null
|
||||
if (!record || typeof record !== 'object') return false
|
||||
return [record.status, record.statusCode, record.code].some((v) => v === 401)
|
||||
}
|
||||
|
||||
/** 负载/状态码是否 403(已登录但无后台权限)。 */
|
||||
export function isForbidden(payload: unknown): boolean {
|
||||
const record = payload as { status?: unknown; statusCode?: unknown; code?: unknown } | null
|
||||
if (!record || typeof record !== 'object') return false
|
||||
return [record.status, record.statusCode, record.code].some((v) => v === 403)
|
||||
}
|
||||
|
||||
/** 单设备登录:账号已在其他设备登录(4011,与后端 DeviceSessionPolicy.CODE_KICKED 对齐)。 */
|
||||
export function isKicked(payload: unknown): boolean {
|
||||
const record = payload as { code?: unknown } | null
|
||||
if (!record || typeof record !== 'object') return false
|
||||
return record.code === 4011
|
||||
}
|
||||
|
||||
/** Axios 错误(带 response)或普通 Error 统一取可展示文案。 */
|
||||
export function requestErrorMessage(error: unknown): string {
|
||||
const response = (error as { response?: { data?: unknown; status?: number } })?.response
|
||||
if (response) {
|
||||
const text = errorTextOf(response.data)
|
||||
if (text) return text
|
||||
}
|
||||
return errorTextOf(error)
|
||||
}
|
||||
|
||||
/** 当前地址作为登录跳转的 redirect 参数(encodeURIComponent 后)。 */
|
||||
export function loginRedirectTarget(location: { pathname: string; search: string }): string {
|
||||
return encodeURIComponent(`${location.pathname}${location.search}`)
|
||||
}
|
||||
|
||||
/** 登录页统一入口;401 一律跳此路径。 */
|
||||
export const LOGIN_PATH = '/login'
|
||||
|
||||
/**
|
||||
* 浏览器地址栏里的登录页形态。
|
||||
*
|
||||
* <p>LOGIN_PATH 是路由内的相对路径(axios 的 url 也用它比较),而 `window.location.pathname`
|
||||
* 带 History base,生产实际值是 `/admin-vue/login`。少这一条,"已经在登录页就别再跳"
|
||||
* 的守卫在真机上一次都没生效过:2026-10-06 那次登录失败,拦截器把整页重刷成
|
||||
* `/admin-vue/login?redirect=…`,连刚填的用户名和错误原因一起没了。</p>
|
||||
*/
|
||||
export const LOGIN_LOCATION_PATH = joinAdminPath('login')
|
||||
|
||||
/** 当前 pathname 是否处于登录页(去掉可能携带的查询串后比较)。 */
|
||||
export function isLoginLocation(pathname: string): boolean {
|
||||
if (typeof pathname !== 'string') return false
|
||||
const queryAt = pathname.indexOf('?')
|
||||
const path = queryAt >= 0 ? pathname.slice(0, queryAt) : pathname
|
||||
return path === LOGIN_PATH || path === LOGIN_LOCATION_PATH || path === `${LOGIN_LOCATION_PATH}/`
|
||||
}
|
||||
|
||||
/** 把请求 URL(相对或绝对)规整为相对路径,便于与登录入口比较。 */
|
||||
export function requestRelativePath(url: string): string {
|
||||
if (typeof url !== 'string') return ''
|
||||
const noQuery = url.split('?')[0]
|
||||
const match = noQuery.match(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/]+(.*)$/)
|
||||
return match ? match[1] : noQuery
|
||||
}
|
||||
|
||||
/**
|
||||
* 会话引导端点:只有这里的 403 才等于"这个账号进不了后台"(比如拿客户端 token 打开后台),
|
||||
* 除了去登录页没有别的出路。
|
||||
*
|
||||
* <p>其余端点的 403 是"已经登录、但缺这个模块的权限",和身份无关。把它按未登录整页跳走,
|
||||
* 等于把权限缺口伪装成登录故障:2026-10-04 那次"登录闪退"报的其实是
|
||||
* GET /api/admin/companies 的 403,代价是当前页连人带未提交的表单一起没了。</p>
|
||||
*/
|
||||
export const SESSION_BOOTSTRAP_PATHS: readonly string[] = [
|
||||
'/api/admin/current-user',
|
||||
'/api/admin/current-user/menus',
|
||||
]
|
||||
|
||||
/** 403 是否应执行"跳 /login":仅当失败的请求本身是会话引导端点。 */
|
||||
export function shouldRedirectForbidden(requestUrl: string | undefined): boolean {
|
||||
return SESSION_BOOTSTRAP_PATHS.includes(requestRelativePath(requestUrl || ''))
|
||||
}
|
||||
|
||||
/** 401 失败请求本身是否指向登录/认证端点(登录提交失败不应再被踢回登录页)。 */
|
||||
export function isAuthEndpointRequest(url: string | undefined): boolean {
|
||||
return requestRelativePath(url || '') === LOGIN_PATH
|
||||
}
|
||||
|
||||
/**
|
||||
* 401 是否应执行“跳 /login”:已处于登录页或失败请求即登录端点时不应再跳,
|
||||
* 否则会在登录页循环跳转或吞掉登录失败反馈。
|
||||
*/
|
||||
export function shouldRedirectUnauthorized(currentPathname: string, requestUrl?: string): boolean {
|
||||
if (isLoginLocation(currentPathname)) return false
|
||||
if (isAuthEndpointRequest(requestUrl)) return false
|
||||
return true
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
import axios from 'axios'
|
||||
import {
|
||||
isForbidden,
|
||||
isKicked,
|
||||
isLoginLocation,
|
||||
isUnauthorized,
|
||||
loginRedirectTarget,
|
||||
shouldRedirectForbidden,
|
||||
shouldRedirectUnauthorized,
|
||||
} from './envelope'
|
||||
|
||||
export { unwrap } from './envelope'
|
||||
|
||||
export const http = axios.create({
|
||||
baseURL: '/',
|
||||
withCredentials: true,
|
||||
timeout: 30_000,
|
||||
})
|
||||
|
||||
/** 会话失效成因(后端 X-Auth-Reason 头):disabled=已停用、deleted=已删除;其余 401 无成因。 */
|
||||
function authReasonOf(headers: unknown): string {
|
||||
const value = (headers as Record<string, unknown> | undefined)?.['x-auth-reason']
|
||||
return value === 'disabled' || value === 'deleted' ? value : ''
|
||||
}
|
||||
|
||||
function redirectToLogin(requestUrl?: string, reason = ''): void {
|
||||
if (typeof window === 'undefined') return
|
||||
// 已在登录页或失败请求即登录端点时不再跳转,避免登录页循环与吞掉登录失败反馈。
|
||||
if (!shouldRedirectUnauthorized(window.location.pathname, requestUrl)) return
|
||||
const target = loginRedirectTarget(window.location)
|
||||
// 成因随 query 带给登录页点名(停用/删除),登录页据此显示对应提示
|
||||
window.location.assign('/admin-vue/login?redirect=' + target + (reason ? `&auth=${reason}` : ''))
|
||||
}
|
||||
|
||||
/** 403 只在会话引导端点上才当"进不了后台"处理;其余端点的 403 交给页面自己把原因说出来。 */
|
||||
function redirectToLoginOnForbidden(requestUrl?: string): void {
|
||||
if (!shouldRedirectForbidden(requestUrl)) return
|
||||
redirectToLogin(requestUrl)
|
||||
}
|
||||
|
||||
/** 单设备登录:被新设备顶下线,整页回登录页(整页 reload 顺带重置会话 store,避免守卫弹回)。 */
|
||||
function redirectToLoginKicked(): void {
|
||||
if (typeof window === 'undefined') return
|
||||
if (isLoginLocation(window.location.pathname)) return
|
||||
window.location.assign('/admin-vue/login?kicked=1')
|
||||
}
|
||||
|
||||
http.interceptors.response.use(
|
||||
(response) => {
|
||||
// Java 未登录以 HTTP 200 + body.code=401 返回,需统一按未登录处理;
|
||||
// 403(已登录但无后台权限)只在会话引导端点上按"进不了后台"跳登录页,
|
||||
// 业务端点的 403 留给页面自己报错——整页跳走会把权限缺口说成登录坏了。
|
||||
// 4011(账号已在其他设备登录)单独提示,不按普通 401 处理。
|
||||
if (isKicked(response.data)) {
|
||||
redirectToLoginKicked()
|
||||
} else if (isUnauthorized(response.data)) {
|
||||
redirectToLogin(response.config?.url, authReasonOf(response.headers))
|
||||
} else if (isForbidden(response.data)) {
|
||||
redirectToLoginOnForbidden(response.config?.url)
|
||||
}
|
||||
return response
|
||||
},
|
||||
(error) => {
|
||||
if (isKicked(error?.response?.data)) {
|
||||
redirectToLoginKicked()
|
||||
} else if (error?.response?.status === 401 || isUnauthorized(error?.response?.data)) {
|
||||
redirectToLogin(error?.config?.url, authReasonOf(error?.response?.headers))
|
||||
} else if (error?.response?.status === 403 || isForbidden(error?.response?.data)) {
|
||||
redirectToLoginOnForbidden(error?.config?.url)
|
||||
}
|
||||
return Promise.reject(error)
|
||||
},
|
||||
)
|
||||
@@ -1,160 +0,0 @@
|
||||
import { http } from './http'
|
||||
import { unwrap } from './envelope'
|
||||
|
||||
/** 业务严重度:紧急 / 高危 / 中危 / 低危(后端按 scene + level 推导)。 */
|
||||
export type AdminNotificationSeverity = 'urgent' | 'high' | 'medium' | 'low'
|
||||
|
||||
export type AdminNotificationSortMode = 'severity' | 'time'
|
||||
|
||||
export const ADMIN_NOTIFICATION_SEVERITY_LABELS: Readonly<Record<AdminNotificationSeverity, string>> = {
|
||||
urgent: '紧急',
|
||||
high: '高危',
|
||||
medium: '中危',
|
||||
low: '低危',
|
||||
}
|
||||
|
||||
/** 通知里的结构化定位锚点(当前只有 task_failed 使用:桶内每个失败任务一项)。 */
|
||||
export interface AdminNotificationRef {
|
||||
taskId: number | null
|
||||
/** 任务号;品牌任务为 #<id>。任务详情接口按它查。 */
|
||||
taskNo: string
|
||||
moduleType?: string | null
|
||||
reason?: string | null
|
||||
updatedAt?: string | null
|
||||
deviceId?: string | null
|
||||
}
|
||||
|
||||
/** 单条通知(后台铃铛)。 */
|
||||
export interface AdminNotificationItem {
|
||||
id: number
|
||||
scene: string
|
||||
level: string
|
||||
/** 业务严重度;旧后端不返回时前端按 level 兜底。 */
|
||||
severity?: string
|
||||
title: string
|
||||
content: string
|
||||
/** 可点的定位锚点;旧后端/历史行没有这一列时为空。 */
|
||||
refs?: AdminNotificationRef[] | null
|
||||
read: boolean
|
||||
readAt: string | null
|
||||
createdAt: string | null
|
||||
}
|
||||
|
||||
export interface AdminNotificationPage {
|
||||
items: AdminNotificationItem[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
unreadCount: number
|
||||
}
|
||||
|
||||
export interface AdminNotificationSummary {
|
||||
unreadCount: number
|
||||
/** 有未读的聚合组数;徽标用它。unreadCount 仍是"条数",给老明细视图与对账用。 */
|
||||
unreadGroupCount?: number
|
||||
latestId: number
|
||||
}
|
||||
|
||||
/** 聚合组:一个「场景 × 自然日 × 事件主体用户」折成的一行。 */
|
||||
export interface AdminNotificationGroup {
|
||||
latestId: number
|
||||
scene: string
|
||||
category: string
|
||||
day: string
|
||||
subjectUserId: number | null
|
||||
rowCount: number
|
||||
unreadCount: number
|
||||
level: string
|
||||
/** 组内最高严重度。 */
|
||||
severity?: string
|
||||
title: string
|
||||
content: string
|
||||
createdAt: string | null
|
||||
}
|
||||
|
||||
export interface AdminNotificationGroupPage {
|
||||
groups: AdminNotificationGroup[]
|
||||
/** 组数(分页分母)。 */
|
||||
total: number
|
||||
/** 折叠前的明细条数——必须与 total 同屏,否则「共 12 条」会被读成只有 12 条通知。 */
|
||||
rowCount: number
|
||||
page: number
|
||||
pageSize: number
|
||||
unreadGroupCount: number
|
||||
unreadCount: number
|
||||
}
|
||||
|
||||
/** 铃铛轮询:未读数 + 最新通知 id。 */
|
||||
export async function fetchNotificationSummary(): Promise<AdminNotificationSummary> {
|
||||
const { data } = await http.get('/api/admin/notifications/summary')
|
||||
return unwrap<AdminNotificationSummary>(data)
|
||||
}
|
||||
|
||||
/** 列表查询参数:关键字匹配标题/内容;startDate/endDate 为年月日闭区间(yyyy-MM-dd)。 */
|
||||
export interface AdminNotificationListParams {
|
||||
page?: number
|
||||
pageSize?: number
|
||||
onlyUnread?: boolean
|
||||
keyword?: string
|
||||
startDate?: string
|
||||
endDate?: string
|
||||
/** 排序:severity(默认)或 time;默认值不下发。 */
|
||||
sort?: AdminNotificationSortMode
|
||||
/** 展开聚合组:三个条件取自该组自己返回的值,原样回传。 */
|
||||
scene?: string
|
||||
day?: string
|
||||
subjectUserId?: number | null
|
||||
/** true 表示展开「未区分用户」那一组(subject_user_id 为空的存量行)。 */
|
||||
subjectUnlabelled?: boolean
|
||||
}
|
||||
|
||||
/** 聚合列表(铃铛默认视图)。分页按组切。 */
|
||||
export async function fetchNotificationGroups(
|
||||
params: AdminNotificationListParams = {},
|
||||
): Promise<AdminNotificationGroupPage> {
|
||||
const keyword = (params.keyword ?? '').trim()
|
||||
const { data } = await http.get('/api/admin/notifications/groups', {
|
||||
params: {
|
||||
page: params.page ?? 1,
|
||||
pageSize: params.pageSize ?? 20,
|
||||
onlyUnread: params.onlyUnread ? 'true' : 'false',
|
||||
keyword: keyword || undefined,
|
||||
startDate: params.startDate || undefined,
|
||||
endDate: params.endDate || undefined,
|
||||
sort: params.sort === 'time' ? 'time' : undefined,
|
||||
},
|
||||
})
|
||||
return unwrap<AdminNotificationGroupPage>(data)
|
||||
}
|
||||
|
||||
export async function fetchNotificationList(
|
||||
params: AdminNotificationListParams = {},
|
||||
): Promise<AdminNotificationPage> {
|
||||
const keyword = (params.keyword ?? '').trim()
|
||||
const { data } = await http.get('/api/admin/notifications', {
|
||||
params: {
|
||||
page: params.page ?? 1,
|
||||
pageSize: params.pageSize ?? 20,
|
||||
onlyUnread: params.onlyUnread ? 'true' : 'false',
|
||||
keyword: keyword || undefined,
|
||||
startDate: params.startDate || undefined,
|
||||
endDate: params.endDate || undefined,
|
||||
sort: params.sort === 'time' ? 'time' : undefined,
|
||||
scene: params.scene || undefined,
|
||||
day: params.day || undefined,
|
||||
subjectUserId: params.subjectUserId ?? undefined,
|
||||
subjectUnlabelled: params.subjectUnlabelled ? 'true' : undefined,
|
||||
},
|
||||
})
|
||||
return unwrap<AdminNotificationPage>(data)
|
||||
}
|
||||
|
||||
export async function markNotificationRead(id: number): Promise<boolean> {
|
||||
const { data } = await http.post(`/api/admin/notifications/${id}/read`)
|
||||
return unwrap<boolean>(data)
|
||||
}
|
||||
|
||||
export async function markAllNotificationsRead(): Promise<number> {
|
||||
const { data } = await http.post('/api/admin/notifications/read-all')
|
||||
return unwrap<number>(data)
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import { unwrap } from './envelope.ts'
|
||||
import type { AdminMenuNode, AdminUser } from '../types/admin'
|
||||
|
||||
/** 解析当前用户响应:支持 data:{item} 与 {item}/{直接对象} 信封。 */
|
||||
export function parseCurrentUser(payload: unknown): AdminUser {
|
||||
const value = unwrap<AdminUser | { item?: AdminUser }>(payload)
|
||||
const user =
|
||||
value && typeof value === 'object' && 'item' in value && value.item
|
||||
? value.item
|
||||
: (value as AdminUser)
|
||||
if (!user || typeof user.id !== 'number') {
|
||||
throw new Error('当前用户响应缺少有效 id')
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析菜单树响应:支持 data:{items} 与 {items}/数组 信封。
|
||||
* 返回后端树形节点;空/缺省按 [] 处理,与“接口失败”(抛错) 区分开。
|
||||
*/
|
||||
export function parseMenuTree(payload: unknown): AdminMenuNode[] {
|
||||
const value = unwrap<AdminMenuNode[] | { items?: AdminMenuNode[] }>(payload)
|
||||
if (Array.isArray(value)) return value
|
||||
return (value && Array.isArray(value.items) ? value.items : []) as AdminMenuNode[]
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import { http } from './http'
|
||||
import { parseCurrentUser, parseMenuTree } from './session-model'
|
||||
import type { AdminMenuNode, AdminUser, ApiEnvelope } from '../types/admin'
|
||||
|
||||
export async function fetchCurrentUser(): Promise<AdminUser> {
|
||||
const { data } = await http.get<ApiEnvelope<{ item: AdminUser }> | AdminUser>('/api/admin/current-user')
|
||||
return parseCurrentUser(data)
|
||||
}
|
||||
|
||||
export async function fetchAdminMenuTree(): Promise<AdminMenuNode[]> {
|
||||
const { data } = await http.get<
|
||||
ApiEnvelope<{ items: AdminMenuNode[] }> | { items: AdminMenuNode[] } | AdminMenuNode[]
|
||||
>('/api/admin/current-user/menus')
|
||||
return parseMenuTree(data)
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
// 登出走 auth 模块根端点 POST /logout(下发清除会话 cookie);旧 api/admin 前缀路径后端无映射。
|
||||
await http.post('/logout', undefined, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
import { http } from './http'
|
||||
import { unwrap } from './envelope'
|
||||
|
||||
/** 客户端任务管理(后台看板):按账号 × 店铺 × 业务统一查看客户端任务,全部只读。 */
|
||||
|
||||
/** 查询参数(由页面侧 buildTaskQuery / buildVariantQuery 产出,空白项不下传)。 */
|
||||
type QueryParams = Record<string, string | number>
|
||||
|
||||
export interface TaskCenterOverview {
|
||||
shopTotal: number
|
||||
shopRunning: number
|
||||
runningTasks: number
|
||||
todayFinishedTasks: number
|
||||
stuckTasks: number
|
||||
}
|
||||
|
||||
export interface TaskCenterTaskRow {
|
||||
id: number
|
||||
taskNo: string
|
||||
moduleType: string
|
||||
moduleLabel: string
|
||||
status: string
|
||||
userId: number | null
|
||||
username: string | null
|
||||
deviceId: string | null
|
||||
deviceName: string | null
|
||||
webDevice: boolean
|
||||
shopName: string | null
|
||||
shopCount: number
|
||||
/** 目标站点国家码(后端从 request_json 归一,多国家用 / 连);该模块不写国家时为 null。 */
|
||||
country: string | null
|
||||
createdAt: string | null
|
||||
finishedAt: string | null
|
||||
lastReportAt: string | null
|
||||
progressTotal: number
|
||||
progressSuccess: number
|
||||
progressFailed: number
|
||||
currentScope: string | null
|
||||
message: string | null
|
||||
stuck: boolean
|
||||
}
|
||||
|
||||
export interface TaskCenterTaskPage {
|
||||
items: TaskCenterTaskRow[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
export interface TaskCenterShopStat {
|
||||
scopeKey: string
|
||||
total: number
|
||||
success: number
|
||||
failed: number
|
||||
}
|
||||
|
||||
export interface TaskCenterTaskDetail extends TaskCenterTaskRow {
|
||||
shops: TaskCenterShopStat[]
|
||||
errorMessage: string | null
|
||||
}
|
||||
|
||||
export interface TaskCenterVariantTaskRow {
|
||||
taskId: string
|
||||
uid: string | null
|
||||
username: string | null
|
||||
status: number | null
|
||||
statusLabel: string | null
|
||||
resMes: string | null
|
||||
taskData: string | null
|
||||
createTime: string | null
|
||||
updateTime: string | null
|
||||
}
|
||||
|
||||
export interface TaskCenterVariantPage {
|
||||
items: TaskCenterVariantTaskRow[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 汇总卡:GET /api/admin/task-center/overview
|
||||
* companyId = 公司 tab 选中的公司(超管专用,页面只从 companyTab.requestCompanyId 取);
|
||||
* null/undefined 由这里自己丢掉——不发给后端 = 按会话口径看全部,不是「筛成空」。
|
||||
*/
|
||||
export async function fetchTaskCenterOverview(companyId?: number | null): Promise<TaskCenterOverview> {
|
||||
const query: QueryParams = {}
|
||||
if (companyId != null) query.company_id = companyId
|
||||
const { data } = await http.get('/api/admin/task-center/overview', { params: query })
|
||||
return unwrap<TaskCenterOverview>(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* 店铺筛选候选(店铺库内的店铺名,精确匹配):GET /api/admin/task-center/shop-options
|
||||
* 下拉候选必须跟列表同宽:少了这一支,切 tab 后能选到别家的店铺名(选了又筛不出东西)。
|
||||
*/
|
||||
export async function fetchTaskCenterShopOptions(companyId?: number | null): Promise<string[]> {
|
||||
const query: QueryParams = {}
|
||||
if (companyId != null) query.company_id = companyId
|
||||
const { data } = await http.get('/api/admin/task-center/shop-options', { params: query })
|
||||
return unwrap<string[]>(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务分页列表:GET /api/admin/task-center/tasks
|
||||
* params 由 buildTaskQuery 构造(含 company_id,见 task-center-model.ts)。
|
||||
*/
|
||||
export async function fetchTaskCenterTasks(params: QueryParams): Promise<TaskCenterTaskPage> {
|
||||
const { data } = await http.get('/api/admin/task-center/tasks', { params })
|
||||
return unwrap<TaskCenterTaskPage>(data)
|
||||
}
|
||||
|
||||
/** 任务详情(品牌任务 taskNo 形如 brand-1):GET /api/admin/task-center/tasks/detail
|
||||
* 任务不存在或不在可见范围时后端返回 success + data:null,这里归一为 null 供页面提示(unwrap 对 null data 会回传信封)。 */
|
||||
export async function fetchTaskCenterTaskDetail(
|
||||
taskNo: string,
|
||||
companyId?: number | null,
|
||||
): Promise<TaskCenterTaskDetail | null> {
|
||||
const query: QueryParams = { taskNo }
|
||||
if (companyId != null) query.company_id = companyId
|
||||
const { data } = await http.get('/api/admin/task-center/tasks/detail', { params: query })
|
||||
const envelope = data as { data?: unknown } | null
|
||||
if (envelope && typeof envelope === 'object' && 'data' in envelope && envelope.data == null) return null
|
||||
return unwrap<TaskCenterTaskDetail>(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* 变体采集(代理麦象 console,取当前可见用户集合):GET /api/admin/task-center/variant-tasks
|
||||
* params 由 buildVariantQuery 构造(含 company_id,见 task-center-model.ts)。
|
||||
*/
|
||||
export async function fetchTaskCenterVariantTasks(params: QueryParams): Promise<TaskCenterVariantPage> {
|
||||
const { data } = await http.get('/api/admin/task-center/variant-tasks', { params })
|
||||
return unwrap<TaskCenterVariantPage>(data)
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
/**
|
||||
* 后台提示语把关(2026-10-09):只把中文给用户看。
|
||||
*
|
||||
* Java 侧仍有出口把底层异常原文写进 message/errorMessage,后台同学看到
|
||||
* `Invalid export date range` 这类句子既看不懂也没法转述给用户。这里统一换成中文兜底句,
|
||||
* 原文进 console 供对着日志核对。
|
||||
*/
|
||||
|
||||
const CJK = /[\u3400-\u4dbf\u4e00-\u9fff]/
|
||||
|
||||
export const NOTICE_FALLBACK = '操作未能完成,请稍后重试'
|
||||
|
||||
export function userNotice(text?: string | null, fallback: string = NOTICE_FALLBACK): string {
|
||||
const raw = typeof text === 'string' ? text.trim() : ''
|
||||
if (!raw) {
|
||||
return fallback
|
||||
}
|
||||
if (!CJK.test(raw)) {
|
||||
console.warn('[user-notice] 提示语原文不是中文,已换成中文兜底句,原文:', raw)
|
||||
return fallback
|
||||
}
|
||||
// 中文主干 + 英文尾巴(后端把底层异常原文拼在冒号后):留主干,尾巴只进 console
|
||||
const at = Math.max(raw.lastIndexOf(':'), raw.lastIndexOf(':'))
|
||||
if (at > 0 && !CJK.test(raw.slice(at + 1))) {
|
||||
const head = raw.slice(0, at).trim()
|
||||
if (CJK.test(head)) {
|
||||
console.warn('[user-notice] 提示语尾巴是英文,已隐去,原文:', raw)
|
||||
return head
|
||||
}
|
||||
}
|
||||
return raw
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import { http } from './http'
|
||||
import { unwrap } from './envelope'
|
||||
|
||||
/** 单用户一行:三类密钥调用次数 + 合计(口径=真实对外请求次数)。 */
|
||||
export interface AdminUserSecretUsageRow {
|
||||
userId: number
|
||||
username: string
|
||||
groups: string[]
|
||||
similarAsinCount: number
|
||||
appearancePatentCount: number
|
||||
proxyCount: number
|
||||
totalCount: number
|
||||
}
|
||||
|
||||
export interface AdminUserSecretUsagePage {
|
||||
items: AdminUserSecretUsageRow[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
/** 所选范围内(不分页)三类总次数。 */
|
||||
totalCalls: number
|
||||
similarAsinCalls: number
|
||||
appearancePatentCalls: number
|
||||
proxyCalls: number
|
||||
groupOptions?: Array<{ id: number; groupName: string }>
|
||||
}
|
||||
|
||||
export interface UserSecretUsageQuery {
|
||||
startDate?: string
|
||||
endDate?: string
|
||||
keyword?: string
|
||||
/** 按数据权限分组筛选(仅超管生效);后端参数为 snake_case。 */
|
||||
groupId?: number
|
||||
/** 公司 tab 的当前口径;不传 = 后端按操作者自己的公司(批次 1 里非超管只有这一家)。 */
|
||||
companyId?: number | null
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
/** 分页查询密钥用量:GET /api/admin/user-secret-usage(group_id 必须 snake_case)。 */
|
||||
export async function fetchUserSecretUsage(params: UserSecretUsageQuery): Promise<AdminUserSecretUsagePage> {
|
||||
const query: Record<string, string | number> = { page: params.page, pageSize: params.pageSize }
|
||||
if (params.startDate) query.startDate = params.startDate
|
||||
if (params.endDate) query.endDate = params.endDate
|
||||
if (params.keyword) query.keyword = params.keyword
|
||||
if (params.groupId) query.group_id = params.groupId
|
||||
// 用 `!= null` 而不是上面几行的 truthy 写法:这一项类型是 `number | null`(null = 没选公司)。
|
||||
// 后端把 company_id<=0 归一成「没选公司」(DataReadScope.readScope 第一行),0 与缺失等价,按类型判即可。
|
||||
if (params.companyId != null) query.company_id = params.companyId
|
||||
const { data } = await http.get('/api/admin/user-secret-usage', { params: query })
|
||||
return unwrap<AdminUserSecretUsagePage>(data)
|
||||
}
|
||||
@@ -1,200 +0,0 @@
|
||||
import { http } from './http'
|
||||
import { unwrap } from './envelope'
|
||||
|
||||
/** 单模块状态(脱敏值 + 连通性)。 */
|
||||
export interface AdminUserSecretModule {
|
||||
moduleKey: string
|
||||
moduleLabel: string
|
||||
/**
|
||||
* 货源:按模块分域,后端 `UserSecretModule.channelOrDefault` 已归一——
|
||||
* LLM 行为渠道(longtaitou/t8star),代理行为供应商(qingguo/jikip)。
|
||||
* ⚠ 界面不得用一张合表渲染这两域(代理行贴出「龙抬头」就是这么来的),
|
||||
* 走 `user-secret-model.ts` 的 `moduleSourceLabel`。
|
||||
*/
|
||||
channel?: string | null
|
||||
/** 脱敏值:代理列为 `scheme://host`,不含提取链接里的 key/pwd。 */
|
||||
masked: string
|
||||
/**
|
||||
* 完整明文值:后台侧**恒为空**(2026-11-02 `SecretMasking.maskProxy` 收口,代理链接里带着账密)。
|
||||
* 字段保留只为接口兼容;界面**不得**读它、更不得拿它做"masked 空就回落原文"的兜底,
|
||||
* 也不许有任何复制/导出整条链接的旁路。
|
||||
*/
|
||||
full: string
|
||||
exists: boolean
|
||||
/** 是否由后台代填并锁定:锁定时客户端不可修改或清空。 */
|
||||
locked: boolean
|
||||
checkStatus: string
|
||||
checkCode: string
|
||||
checkMessage: string
|
||||
checkLatencyMs: number | null
|
||||
checkedAt: string | null
|
||||
updatedAt: string | null
|
||||
}
|
||||
|
||||
/** 一行一用户:三个字段列 + 行级状态(三类都检测通过才算 passed)。 */
|
||||
export interface AdminUserSecretRow {
|
||||
userId: number
|
||||
username: string
|
||||
/** 所属数据权限分组名(可能多个)。 */
|
||||
groups: string[]
|
||||
/** 所属主管(创建人)用户名;无分组时的兜底展示。 */
|
||||
leaderUsername: string
|
||||
similarAsin: AdminUserSecretModule
|
||||
appearancePatent: AdminUserSecretModule
|
||||
proxy: AdminUserSecretModule
|
||||
status: string
|
||||
statusMessage: string
|
||||
/** 首次配置时间(三模块中最早);从未配置为 null。 */
|
||||
createdAt: string | null
|
||||
updatedAt: string | null
|
||||
}
|
||||
|
||||
export interface AdminUserSecretPage {
|
||||
items: AdminUserSecretRow[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
/** 分组筛选项(超管=全部;主管=自己带的分组)。 */
|
||||
groupOptions?: GroupOption[]
|
||||
}
|
||||
|
||||
export interface GroupOption {
|
||||
id: number
|
||||
groupName: string
|
||||
}
|
||||
|
||||
/**
|
||||
* LLM 一格的余额(**人民币口径**,后端取龙抬头 `credits` 块)。
|
||||
* 与 `AdminProxyBalanceCell` 是两套语义:这里的 `balance` 是钱、单位 CREDIT(=⚡=人民币),
|
||||
* 代理那边的 `surplus` 是「次」。界面不得用一张函数渲染两域(同 `channel` 那张表的教训)。
|
||||
*/
|
||||
export interface AdminLlmBalanceCell {
|
||||
moduleKey: string
|
||||
moduleLabel: string
|
||||
channel: string
|
||||
channelLabel: string
|
||||
available: boolean
|
||||
/** 上游原样小数串(未取整);available=false 时为 null。 */
|
||||
balance: string | null
|
||||
availableBalance: string | null
|
||||
frozen: string | null
|
||||
/** 恒为 CREDIT;不是这个值就按「认不出口径」处理,不猜。 */
|
||||
unit: string | null
|
||||
message: string | null
|
||||
checkedAt: string | null
|
||||
}
|
||||
|
||||
/** 代理余量一格:jikip 套餐口径(`surplus`=IP 次数、`scope`=谁的池子)。青果为 scope=none。 */
|
||||
export interface AdminProxyBalanceCell {
|
||||
available: boolean
|
||||
surplus: string | null
|
||||
balance: string | null
|
||||
/** user=该用户自己的套餐;platform=平台池子(不是这个用户的钱);none=查不了。 */
|
||||
scope: string | null
|
||||
message: string | null
|
||||
low?: boolean
|
||||
lowReason?: string | null
|
||||
}
|
||||
|
||||
export interface AdminUserSecretBalanceItem {
|
||||
userId: number
|
||||
llm: AdminLlmBalanceCell[]
|
||||
proxy: AdminProxyBalanceCell
|
||||
}
|
||||
|
||||
export interface AdminUserSecretBalances {
|
||||
items: AdminUserSecretBalanceItem[]
|
||||
/** 被数据权限剔出、本次没查的用户(不静默少给数)。 */
|
||||
deniedUserIds?: number[]
|
||||
/** 超出整请求时间预算、这轮没取到数的用户。 */
|
||||
timedOutUserIds?: number[]
|
||||
}
|
||||
|
||||
export interface UserSecretQuery {
|
||||
keyword?: string
|
||||
checkStatus?: string
|
||||
/** 按数据权限分组筛选(仅超管生效);后端参数为 snake_case。 */
|
||||
groupId?: number
|
||||
/** 公司 tab 的当前口径;不传 = 后端按操作者自己的公司(批次 1 里非超管只有这一家)。 */
|
||||
companyId?: number | null
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
/** 分页查询用户密钥(一行一用户):GET /api/admin/user-secrets(筛选参数必须 snake_case,camel 会被后端静默忽略)。 */
|
||||
export async function fetchUserSecretList(params: UserSecretQuery): Promise<AdminUserSecretPage> {
|
||||
const query: Record<string, string | number> = { page: params.page, pageSize: params.pageSize }
|
||||
if (params.keyword) query.keyword = params.keyword
|
||||
if (params.checkStatus) query.checkStatus = params.checkStatus
|
||||
if (params.groupId) query.group_id = params.groupId
|
||||
// 用 `!= null` 而不是上面几行的 truthy 写法:这一项类型是 `number | null`(null = 没选公司)。
|
||||
// 后端把 company_id<=0 归一成「没选公司」(DataReadScope.readScope 第一行),0 与缺失等价,按类型判即可。
|
||||
if (params.companyId != null) query.company_id = params.companyId
|
||||
const { data } = await http.get('/api/admin/user-secrets', { params: query })
|
||||
return unwrap<AdminUserSecretPage>(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新本页用户的余额侧写:POST /api/admin/user-secrets/balances。
|
||||
*
|
||||
* 实时打上游、不落库,所以服务端带三条护栏(单次 ≤20 个用户、固定并发、整请求 10s 预算),
|
||||
* 客户端的超时必须**长于**服务端预算,否则服务端还在取数、这边先报错,
|
||||
* 界面就会把「查得慢」显示成「查不到」(与铁律 10「前端超时不得短于服务端预算」同形)。
|
||||
*/
|
||||
export async function fetchAdminSecretBalances(
|
||||
userIds: number[],
|
||||
companyId?: number | null,
|
||||
): Promise<AdminUserSecretBalances> {
|
||||
const body: Record<string, unknown> = { userIds }
|
||||
if (companyId != null) body.company_id = companyId
|
||||
const { data } = await http.post('/api/admin/user-secrets/balances', body, { timeout: 30_000 })
|
||||
return unwrap<AdminUserSecretBalances>(data)
|
||||
}
|
||||
|
||||
/** 立即检测该用户全部已配置项:POST /api/admin/user-secrets/{userId}/check
|
||||
* 逐模块检测(每项最多「首查 + 传输层失败重试一次」,最坏约 31s/项),故放宽超时到 180s。 */
|
||||
export async function checkUserSecret(userId: number) {
|
||||
const { data } = await http.post(`/api/admin/user-secrets/${userId}/check`, undefined, { timeout: 180_000 })
|
||||
return unwrap<
|
||||
Array<{
|
||||
moduleKey: string
|
||||
checkStatus: string
|
||||
checkCode: string
|
||||
checkMessage: string
|
||||
checkLatencyMs: number | null
|
||||
checkedAt: string | null
|
||||
viaProxy: boolean
|
||||
}>
|
||||
>(data)
|
||||
}
|
||||
|
||||
/** 清空该用户全部密钥与代理配置:DELETE /api/admin/user-secrets/{userId} */
|
||||
export async function deleteUserSecret(userId: number): Promise<void> {
|
||||
const { data } = await http.delete(`/api/admin/user-secrets/${userId}`)
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* 代填并锁定该用户某模块配置(当前仅代理):PUT /api/admin/user-secrets/{userId}/modules/{moduleKey}
|
||||
* `value` 是**一次性写载荷**(代理为现拼的提取链接,带着 key/pwd):调用方不得把它渲染回界面、
|
||||
* 不得打进日志;`channel` 是同一单的货源(代理=供应商 key),后端据此选解析分支——
|
||||
* 不给则由后端按链接域名识别,识别不出回落默认供应商,会静默换执行方,所以本面一律显式带上。
|
||||
*/
|
||||
export async function saveUserSecretModule(
|
||||
userId: number,
|
||||
moduleKey: string,
|
||||
value: string,
|
||||
channel?: string,
|
||||
): Promise<AdminUserSecretModule> {
|
||||
const { data } = await http.put(`/api/admin/user-secrets/${userId}/modules/${moduleKey}`, {
|
||||
value,
|
||||
...(channel ? { channel } : {}),
|
||||
})
|
||||
return unwrap<AdminUserSecretModule>(data)
|
||||
}
|
||||
|
||||
/** 清空该用户某模块配置并解除锁定:DELETE /api/admin/user-secrets/{userId}/modules/{moduleKey} */
|
||||
export async function clearUserSecretModule(userId: number, moduleKey: string): Promise<void> {
|
||||
const { data } = await http.delete(`/api/admin/user-secrets/${userId}/modules/${moduleKey}`)
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
/** 用户管理列表/分页 DTO(任务 41):纯逻辑,无框架依赖,与 Java AdminUserController 对齐。 */
|
||||
import type { AdminUser } from '../types/admin'
|
||||
import type { PlatformTabId } from '../config/platform-scope.ts'
|
||||
|
||||
export const USER_PAGE_DEFAULT_SIZE = 10
|
||||
export const USER_PAGE_MIN_PAGE = 1
|
||||
export const USER_PAGE_MAX_SIZE = 200
|
||||
|
||||
/** 前端用户列表筛选/分页状态(页面局部,不入 Pinia)。 */
|
||||
export interface UserListParams {
|
||||
page: number
|
||||
pageSize: number
|
||||
/** 用户名模糊关键字(对应后端 username|search 的 kw)。 */
|
||||
keyword?: string
|
||||
createdById?: number | null
|
||||
adminId?: number | null
|
||||
/** 角色过滤(''=全部)。 */
|
||||
role?: string
|
||||
/** 公司 tab 的当前公司;由页面从 store 传入,**不住在 UserFilterState 里**
|
||||
* (normalizeUserPageParams 白名单构造会把它丢掉,取值口只认 fetchUserList 的原始入参)。 */
|
||||
companyId?: number | null
|
||||
/** 平台 tab 的当前平台(V206);同 companyId 形状:白名单构造不收,从原始入参读。 */
|
||||
platform?: PlatformTabId
|
||||
}
|
||||
|
||||
/** 序列化到 GET /api/admin/users 的查询参数(Java snake_case)。 */
|
||||
export interface UserListQuery {
|
||||
page: number
|
||||
page_size: number
|
||||
username?: string
|
||||
search?: string
|
||||
created_by_id?: number
|
||||
admin_id?: number
|
||||
role?: string
|
||||
company_id?: number
|
||||
platform?: string
|
||||
}
|
||||
|
||||
/** 用户列表项即 AdminUser(与 Java AdminUserItemVo 字段对齐)。 */
|
||||
export type AdminUserItem = AdminUser
|
||||
|
||||
/** 分页结果:与 Java AdminUserListVo.items/total/page/page_size 归一后的前端 DTO。 */
|
||||
export interface UserPageResult {
|
||||
items: AdminUserItem[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
currentUserId?: number | null
|
||||
currentUserUsername?: string
|
||||
admins?: Array<{ id: number; username: string }>
|
||||
}
|
||||
|
||||
function finiteInt(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : null
|
||||
}
|
||||
|
||||
/** 归一化分页/筛选参数:页码下限 1、页大小 1..上限,空关键字视为无过滤。 */
|
||||
export function normalizeUserPageParams(raw: Partial<UserListParams>): UserListParams {
|
||||
const page = Math.max(finiteInt(raw.page) ?? USER_PAGE_MIN_PAGE, USER_PAGE_MIN_PAGE)
|
||||
const rawSize = finiteInt(raw.pageSize)
|
||||
const pageSize =
|
||||
rawSize === null || rawSize < USER_PAGE_MIN_PAGE
|
||||
? USER_PAGE_DEFAULT_SIZE
|
||||
: Math.min(rawSize, USER_PAGE_MAX_SIZE)
|
||||
const keyword = typeof raw.keyword === 'string' ? raw.keyword.trim() || undefined : undefined
|
||||
return {
|
||||
page,
|
||||
pageSize,
|
||||
keyword,
|
||||
createdById: typeof raw.createdById === 'number' ? raw.createdById : null,
|
||||
adminId: typeof raw.adminId === 'number' ? raw.adminId : null,
|
||||
role: typeof raw.role === 'string' ? raw.role.trim() || undefined : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/** 把前端分页/筛选状态转成 Java 查询参数(缺省字段不下发)。 */
|
||||
export function toUserListQuery(params: UserListParams): UserListQuery {
|
||||
const query: UserListQuery = { page: params.page, page_size: params.pageSize }
|
||||
if (params.keyword) query.username = params.keyword
|
||||
if (params.createdById != null) query.created_by_id = params.createdById
|
||||
if (params.adminId != null) query.admin_id = params.adminId
|
||||
if (params.role) query.role = params.role
|
||||
return query
|
||||
}
|
||||
|
||||
/** 无数据分页结果缺省值(首屏/加载前占位)。 */
|
||||
export function emptyUserPageResult(): UserPageResult {
|
||||
return { items: [], total: 0, page: USER_PAGE_MIN_PAGE, pageSize: USER_PAGE_DEFAULT_SIZE }
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
/** 用户 API 响应解析模型:列表分页(任务 42)与新建用户(任务 46)负载归一。 */
|
||||
import { unwrap } from './envelope.ts'
|
||||
import { emptyUserPageResult, type UserPageResult } from './users-dto.ts'
|
||||
import type { AdminUser } from '../types/admin'
|
||||
|
||||
function text(value: unknown): string {
|
||||
return typeof value === 'string' ? value : ''
|
||||
}
|
||||
|
||||
function numberOrNull(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : null
|
||||
}
|
||||
|
||||
/** 把 Java AdminUserItemVo(snake_case) 映射为前端 AdminUser(camelCase);缺 id 视为无效。 */
|
||||
export function toAdminUserItem(raw: unknown): AdminUser | null {
|
||||
if (!raw || typeof raw !== 'object') return null
|
||||
const r = raw as Record<string, unknown>
|
||||
const id = numberOrNull(r.id)
|
||||
if (id === null) return null
|
||||
const item: AdminUser = { id, username: text(r.username), role: text(r.role) }
|
||||
const quota = numberOrNull(r.jd_publish_quota)
|
||||
if (quota !== null) item.jdPublishQuota = quota
|
||||
const platform = text(r.platform)
|
||||
if (platform) item.platform = platform
|
||||
if (typeof r.is_admin === 'boolean') item.isAdmin = r.is_admin
|
||||
const createdById = numberOrNull(r.created_by_id)
|
||||
if (createdById !== null) item.createdById = createdById
|
||||
const createdAt = text(r.created_at)
|
||||
if (createdAt) item.createdAt = createdAt
|
||||
const updatedAt = text(r.updated_at)
|
||||
if (updatedAt) item.updatedAt = updatedAt
|
||||
const creator = text(r.creator_username)
|
||||
if (creator) item.creatorUsername = creator
|
||||
const expiresAt = text(r.expires_at)
|
||||
if (expiresAt) item.expiresAt = expiresAt
|
||||
const disabledAt = text(r.disabled_at)
|
||||
if (disabledAt) item.disabledAt = disabledAt
|
||||
const abbr = text(r.pinyin_abbr)
|
||||
if (abbr) item.pinyinAbbr = abbr
|
||||
return item
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化 Java 用户列表负载(data:{items,total,page,page_size} 或已解包 VO)为前端
|
||||
* UserPageResult;空/缺省字段回默认,success=false 抛后端 message。
|
||||
*/
|
||||
export function parseUserPage(payload: unknown): UserPageResult {
|
||||
const out = emptyUserPageResult()
|
||||
const core = unwrap<unknown>(payload)
|
||||
if (!core || typeof core !== 'object') return out
|
||||
const record = core as Record<string, unknown>
|
||||
if (Array.isArray(record.items)) {
|
||||
out.items = record.items
|
||||
.map((raw) => toAdminUserItem(raw))
|
||||
.filter((item): item is AdminUser => item !== null)
|
||||
}
|
||||
if (typeof record.total === 'number') out.total = record.total
|
||||
if (typeof record.page === 'number' && record.page >= 1) out.page = Math.floor(record.page)
|
||||
const rawSize = record.page_size ?? record.pageSize
|
||||
if (typeof rawSize === 'number' && rawSize >= 1) out.pageSize = Math.floor(rawSize)
|
||||
if (typeof record.current_user_id === 'number') out.currentUserId = record.current_user_id
|
||||
if (typeof record.current_user_username === 'string') out.currentUserUsername = record.current_user_username
|
||||
if (Array.isArray(record.admins)) {
|
||||
out.admins = record.admins
|
||||
.map((raw) => {
|
||||
if (!raw || typeof raw !== 'object') return null
|
||||
const r = raw as Record<string, unknown>
|
||||
const id = numberOrNull(r.id)
|
||||
if (id === null) return null
|
||||
return { id, username: text(r.username) }
|
||||
})
|
||||
.filter((a): a is { id: number; username: string } => a !== null)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 解包新建用户响应并取回新用户 id(POST /api/admin/user 的 data 为 userId)。 */
|
||||
export function parseCreatedUserId(payload: unknown): number {
|
||||
const data = unwrap<unknown>(payload)
|
||||
const id = typeof data === 'number' && Number.isFinite(data) ? Math.floor(data) : null
|
||||
if (id === null || id < 1) throw new Error('创建用户响应异常:未返回有效的用户 ID')
|
||||
return id
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { http } from './http'
|
||||
import { unwrap } from './envelope'
|
||||
import { parseUserPage } from './users-model'
|
||||
import {
|
||||
normalizeUserPageParams,
|
||||
toUserListQuery,
|
||||
type UserListParams,
|
||||
type UserPageResult,
|
||||
} from './users-dto'
|
||||
|
||||
/** 分页查询用户列表:归一化参数 → GET /api/admin/users → 解析 Java 分页负载。 */
|
||||
export async function fetchUserList(params: Partial<UserListParams> = {}): Promise<UserPageResult> {
|
||||
const normalized = normalizeUserPageParams(params)
|
||||
const query = toUserListQuery(normalized)
|
||||
// normalizeUserPageParams 是白名单构造(只点名 page/pageSize/keyword/createdById/adminId/role),
|
||||
// 公司值必须从原始 params 读:写成 normalized.companyId 会 TS 绿、运行时恒 undefined。
|
||||
if (params.companyId != null) query.company_id = params.companyId
|
||||
// 平台值(V206)同 companyId 形状:白名单构造不收,只认原始入参。
|
||||
if (params.platform) query.platform = params.platform
|
||||
const { data } = await http.get('/api/admin/users', { params: query })
|
||||
return parseUserPage(data)
|
||||
}
|
||||
|
||||
/** 删除用户:DELETE /api/admin/user/{uid},success=false 由 unwrap 抛后端 message。 */
|
||||
export async function deleteUser(uid: number): Promise<void> {
|
||||
const { data } = await http.delete<unknown>(`/api/admin/user/${uid}`)
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* 停用/解除停用:PUT /api/admin/user/{uid} 只带 disabled 开关(V155)。
|
||||
* 停用是硬停点:该账号已发令牌在下一次请求就被拒(401),客户端与后台会被强制退出到登录页。
|
||||
*/
|
||||
export async function setUserDisabled(uid: number, disabled: boolean): Promise<void> {
|
||||
const { data } = await http.put<unknown>(`/api/admin/user/${uid}`, { disabled })
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { copyFeedback, isCopySupported } from './copy-model'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
|
||||
const props = defineProps<{ text: string }>()
|
||||
|
||||
async function handleCopy(): Promise<void> {
|
||||
if (!props.text || !isCopySupported()) {
|
||||
ElMessage.warning(copyFeedback(''))
|
||||
return
|
||||
}
|
||||
try {
|
||||
await navigator.clipboard.writeText(props.text)
|
||||
ElMessage.success(copyFeedback(props.text))
|
||||
} catch {
|
||||
showAdminFeedback(copyFeedback(''), 'error')
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="copy-text" role="button" tabindex="0" :title="text" @click="handleCopy"><slot>{{ text }}</slot></span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.copy-text { cursor: pointer; }
|
||||
</style>
|
||||
@@ -1,164 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 到期续费提醒(V146,2026-10-05 需求):
|
||||
* 「管理员快过期的时候(仅剩 5 天不到开始)要在数富后台界面上有个弹窗去提醒,
|
||||
* 只能缩小但是不能关闭,直到续费超过 5 天才消失。」
|
||||
*
|
||||
* - 数据源:/api/admin/current-user 的 expiresAt/daysToExpire(session store 的 user 上);
|
||||
* 只反映账号自身 expires_at,不级联——续费是账号自己的事。
|
||||
* - 触发:0 ≤ daysToExpire < 5(剩余不足 5 天)。刷新/重新登录后按最新值判定,
|
||||
* 续费到 ≥5 天自动消失,无需手动关。
|
||||
* - 只能缩小不能关闭:无关闭按钮;缩小态是右下角常驻浮标,点开即恢复。
|
||||
* - 缩小状态按「用户 + 到期值」记 localStorage:续费(到期值变化)后重置为展开。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 展示阈值(天):daysToExpire < EXPIRY_NOTICE_DAYS 时展示。需求口径 = 5(不足 5 天)。 */
|
||||
threshold?: number
|
||||
}>()
|
||||
|
||||
const THRESHOLD = props.threshold ?? 5
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const user = computed(() => session.user)
|
||||
const daysToExpire = computed<number | null>(() => {
|
||||
const value = user.value?.daysToExpire
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : null
|
||||
})
|
||||
const visible = computed(() => daysToExpire.value !== null && daysToExpire.value < THRESHOLD)
|
||||
const expiresAt = computed(() => (user.value?.expiresAt || '').trim())
|
||||
|
||||
const minimized = ref(false)
|
||||
const minimizedKey = computed(() =>
|
||||
user.value ? `admin-expiry-notice-min:${user.value.id}:${expiresAt.value}` : '',
|
||||
)
|
||||
watch(
|
||||
minimizedKey,
|
||||
(key) => {
|
||||
minimized.value = key ? localStorage.getItem(key) === '1' : false
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
function minimize(): void {
|
||||
minimized.value = true
|
||||
if (minimizedKey.value) {
|
||||
try {
|
||||
localStorage.setItem(minimizedKey.value, '1')
|
||||
} catch {
|
||||
/* localStorage 不可用时仅本次会话生效 */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function restore(): void {
|
||||
minimized.value = false
|
||||
if (minimizedKey.value) {
|
||||
try {
|
||||
localStorage.removeItem(minimizedKey.value)
|
||||
} catch {
|
||||
/* 同上 */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const daysText = computed(() => {
|
||||
const days = daysToExpire.value
|
||||
if (days === null) return ''
|
||||
return days <= 0 ? '不足 1 天' : `还剩 ${days} 天`
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<template v-if="visible">
|
||||
<div
|
||||
v-if="!minimized"
|
||||
class="expiry-notice"
|
||||
role="alert"
|
||||
aria-live="assertive"
|
||||
>
|
||||
<div class="expiry-notice-body">
|
||||
<strong>服务即将到期</strong>
|
||||
<span>
|
||||
您的账号{{ expiresAt ? `(${expiresAt})` : '' }}即将到期,{{ daysText }}。
|
||||
到期后账号将无法登录,名下账号与正在执行的任务也会一并停止,请联系管理员续费。
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
class="expiry-notice-min"
|
||||
type="button"
|
||||
title="收起(不可关闭,续费前会一直提醒)"
|
||||
@click="minimize"
|
||||
>
|
||||
收起
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-else
|
||||
class="expiry-notice-chip"
|
||||
type="button"
|
||||
:title="`服务即将到期:${daysText},点击展开`"
|
||||
@click="restore"
|
||||
>
|
||||
⏰ {{ daysText }}
|
||||
</button>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.expiry-notice {
|
||||
position: fixed;
|
||||
right: 24px;
|
||||
bottom: 24px;
|
||||
z-index: 3000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
max-width: 420px;
|
||||
padding: 14px 16px;
|
||||
border: 1px solid #e4b363;
|
||||
border-radius: 12px;
|
||||
background: #fffaf0;
|
||||
color: #7a4d0b;
|
||||
box-shadow: 0 12px 32px -18px rgba(122, 77, 11, 0.55);
|
||||
}
|
||||
.expiry-notice-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.expiry-notice-body strong {
|
||||
font-size: 14px;
|
||||
}
|
||||
.expiry-notice-min {
|
||||
flex-shrink: 0;
|
||||
padding: 6px 12px;
|
||||
border: 1px solid #e4b363;
|
||||
border-radius: 8px;
|
||||
background: #ffffff;
|
||||
color: #7a4d0b;
|
||||
font-size: 12.5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.expiry-notice-min:hover {
|
||||
background: #fdf3dd;
|
||||
}
|
||||
.expiry-notice-chip {
|
||||
position: fixed;
|
||||
right: 24px;
|
||||
bottom: 24px;
|
||||
z-index: 3000;
|
||||
padding: 8px 14px;
|
||||
border: 1px solid #e4b363;
|
||||
border-radius: 999px;
|
||||
background: #fffaf0;
|
||||
color: #7a4d0b;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 8px 20px -12px rgba(122, 77, 11, 0.5);
|
||||
}
|
||||
</style>
|
||||
@@ -1,53 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/** 列表加载失败条(四面9分口径 · 后管「模板内失败态只有 4/24 页」)。
|
||||
* 两件事一起做:把失败原因留在页面上(不是一闪而过的 toast),并给出一个真能重跑的出口。
|
||||
* 重试动作由父页面传回自己的取数函数,本组件不自己发请求、也不放占位按钮。 */
|
||||
import { LOAD_FAILURE_RETRY_LABEL } from './load-failure-model'
|
||||
|
||||
defineProps<{ message: string }>()
|
||||
defineEmits<{ (event: 'retry'): void }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="load-failure-bar" role="alert">
|
||||
<span class="load-failure-bar-text">{{ message }}</span>
|
||||
<button class="load-failure-bar-retry" type="button" @click="$emit('retry')">{{ LOAD_FAILURE_RETRY_LABEL }}</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 自带样式:各页的 .btn 是 scoped 的,套不到子组件内部的元素上。 */
|
||||
.load-failure-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin: 0 0 14px;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid #e0bfc4;
|
||||
border-radius: 10px;
|
||||
background: #fdf3f4;
|
||||
color: #8f4650;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.load-failure-bar-text {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.load-failure-bar-retry {
|
||||
flex: none;
|
||||
min-height: 32px;
|
||||
padding: 5px 14px;
|
||||
border: 1px solid #b35f6a;
|
||||
border-radius: 8px;
|
||||
background: linear-gradient(135deg, #c06d77, #b35f6a);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.load-failure-bar-retry:hover {
|
||||
background: linear-gradient(135deg, #cb7c84, #b96570);
|
||||
}
|
||||
</style>
|
||||
@@ -1,781 +0,0 @@
|
||||
<template>
|
||||
<div ref="rootRef" class="admin-notification-bell">
|
||||
<button
|
||||
type="button"
|
||||
class="bell-trigger"
|
||||
:class="{ 'bell-trigger--active': panelOpen }"
|
||||
:title="unreadCount > 0 ? `通知(${unreadCount} 条未读)` : '通知'"
|
||||
aria-label="通知"
|
||||
@click="togglePanel"
|
||||
>
|
||||
<svg
|
||||
class="bell-icon"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" />
|
||||
<path d="M13.73 21a2 2 0 0 1-3.46 0" />
|
||||
</svg>
|
||||
<span v-if="badgeText" class="bell-badge">{{ badgeText }}</span>
|
||||
</button>
|
||||
|
||||
<!-- 面板挂到 body 上(fixed 定位):顶栏内绝对定位时会被列表页 el-select 等页面内容压住,提 z-index 无效 -->
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="panelOpen"
|
||||
ref="panelRef"
|
||||
class="bell-panel"
|
||||
:style="panelStyle"
|
||||
role="dialog"
|
||||
aria-label="通知列表"
|
||||
>
|
||||
<div class="bell-panel-head">
|
||||
<span class="bell-panel-title">通知</span>
|
||||
<button
|
||||
v-if="unreadCount > 0"
|
||||
type="button"
|
||||
class="bell-read-all"
|
||||
:disabled="markingAll"
|
||||
@click="readAll"
|
||||
>
|
||||
{{ markingAll ? '处理中...' : '全部已读' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="bell-search">
|
||||
<input
|
||||
v-model="keyword"
|
||||
type="text"
|
||||
class="bell-search-input"
|
||||
placeholder="搜索标题或内容"
|
||||
aria-label="搜索通知"
|
||||
@input="onKeywordInput"
|
||||
/>
|
||||
<div class="bell-search-days">
|
||||
<el-date-picker
|
||||
:model-value="dateRangeValue"
|
||||
type="daterange"
|
||||
value-format="YYYY-MM-DD"
|
||||
start-placeholder="开始日期"
|
||||
end-placeholder="结束日期"
|
||||
range-separator="至"
|
||||
size="small"
|
||||
class="bell-date-picker"
|
||||
popper-class="bell-date-popper"
|
||||
:clearable="true"
|
||||
@update:model-value="onDateRangeChange"
|
||||
@change="reload"
|
||||
/>
|
||||
<button v-if="hasFilter" type="button" class="bell-search-reset" @click="resetFilters">
|
||||
重置
|
||||
</button>
|
||||
</div>
|
||||
<div class="bell-sort-chips" role="group" aria-label="通知排序">
|
||||
<span class="bell-sort-label">排序</span>
|
||||
<button
|
||||
type="button"
|
||||
class="bell-sort-chip"
|
||||
:class="{ 'is-active': sortMode === 'severity' }"
|
||||
@click="setSortMode('severity')"
|
||||
>
|
||||
严重度
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="bell-sort-chip"
|
||||
:class="{ 'is-active': sortMode === 'time' }"
|
||||
@click="setSortMode('time')"
|
||||
>
|
||||
时间
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="loading && !groups.length" class="bell-empty">正在加载...</div>
|
||||
<div v-else-if="loadError && !groups.length" class="bell-empty bell-empty--error">{{ loadError }}</div>
|
||||
<div v-else-if="!groups.length" class="bell-empty">{{ hasFilter ? '没有符合条件的通知' : '暂无通知' }}</div>
|
||||
<ul v-else class="bell-list">
|
||||
<template v-for="(group, index) in groups" :key="notificationGroupKey(group)">
|
||||
<!-- 严重度排序会跨天交错,日期头只在时间排序下有意义 -->
|
||||
<li v-if="sortMode === 'time' && startsNewDay(index)" class="bell-day-head">{{ formatDayLabel(group.day) }}</li>
|
||||
<li
|
||||
class="bell-group"
|
||||
:class="[`bell-item--${group.level || 'warning'}`, { 'bell-group--open': isExpanded(group) }]"
|
||||
@click="toggleGroup(group)"
|
||||
>
|
||||
<div class="bell-item-head">
|
||||
<span class="bell-severity-tag" :class="`bell-severity-tag--${itemSeverity(group)}`">
|
||||
{{ severityLabel(group) }}
|
||||
</span>
|
||||
<span class="bell-item-title">{{ group.title }}</span>
|
||||
<span class="bell-item-time">{{ formatTime(group.createdAt) }}</span>
|
||||
</div>
|
||||
<div class="bell-item-content">{{ group.content }}</div>
|
||||
<div class="bell-group-foot">
|
||||
<span class="bell-group-count">{{ formatGroupCounts(group.rowCount, group.unreadCount) }}</span>
|
||||
<span class="bell-group-toggle">{{ isExpanded(group) ? '收起明细' : '展开明细' }}</span>
|
||||
</div>
|
||||
</li>
|
||||
<!-- 已读只能进明细逐条点:聚合行上的点击只做展开,避免"看一眼顺手把没看过的全标成已读" -->
|
||||
<template v-if="isExpanded(group)">
|
||||
<li v-if="detailLoading" class="bell-empty bell-empty--detail">正在加载明细...</li>
|
||||
<li v-else-if="!details.length" class="bell-empty bell-empty--detail">这一组里没有通知</li>
|
||||
<li
|
||||
v-for="item in details"
|
||||
:key="item.id"
|
||||
class="bell-item bell-item--detail"
|
||||
:class="{ 'bell-item--unread': !item.read }"
|
||||
@click="onItemClick(item)"
|
||||
>
|
||||
<div class="bell-item-head">
|
||||
<span class="bell-severity-tag" :class="`bell-severity-tag--${itemSeverity(item)}`">
|
||||
{{ severityLabel(item) }}
|
||||
</span>
|
||||
<span class="bell-item-title">{{ item.title }}</span>
|
||||
<span class="bell-item-time">{{ formatTime(item.createdAt) }}</span>
|
||||
</div>
|
||||
<div class="bell-item-content">{{ item.content }}</div>
|
||||
<div v-if="item.refs && item.refs.length" class="bell-ref-list">
|
||||
<button
|
||||
v-for="ref in item.refs"
|
||||
:key="`${item.id}-${ref.taskNo}`"
|
||||
type="button"
|
||||
class="bell-ref-link"
|
||||
:title="ref.reason || `查看任务 ${ref.taskNo}`"
|
||||
@click.stop="openTaskRef(item, ref)"
|
||||
>
|
||||
{{ ref.taskNo }}<span v-if="ref.reason" class="bell-ref-reason">:{{ ref.reason }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
<li v-if="!detailLoading && detailTotal > details.length" class="bell-detail-more">
|
||||
另有 {{ detailTotal - details.length }} 条未列出,可缩小日期范围后查看
|
||||
</li>
|
||||
</template>
|
||||
</template>
|
||||
</ul>
|
||||
|
||||
<div class="bell-panel-foot">
|
||||
<button
|
||||
type="button"
|
||||
class="bell-page-btn"
|
||||
:disabled="page <= 1 || loading"
|
||||
@click="goPage(page - 1)"
|
||||
>
|
||||
上一页
|
||||
</button>
|
||||
<span class="bell-page-info">{{ page }} / {{ totalPages }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="bell-page-btn"
|
||||
:disabled="page >= totalPages || loading"
|
||||
@click="goPage(page + 1)"
|
||||
>
|
||||
下一页
|
||||
</button>
|
||||
<span class="bell-page-total">共 {{ total }} 组 · 明细 {{ rowCount }} 条</span>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import type { AdminNotificationItem, AdminNotificationRef } from '@/api/notifications'
|
||||
import {
|
||||
NOTIFICATION_POLL_INTERVAL_MS,
|
||||
formatDayLabel,
|
||||
formatGroupCounts,
|
||||
formatNotificationTime,
|
||||
notificationGroupKey,
|
||||
taskCenterRouteForRef,
|
||||
} from '@/layout/notification-bell-model'
|
||||
import { todayDateInput } from '@/utils/datetime'
|
||||
import {
|
||||
itemLevel,
|
||||
itemSeverity,
|
||||
severityLabel,
|
||||
startsNewDay as groupStartsNewDay,
|
||||
useNotificationBellPanel,
|
||||
} from '@/layout/notification-bell-panel'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const router = useRouter()
|
||||
|
||||
/**
|
||||
* 面板的数据流(聚合组、明细、两个计数、防抖与取数)整块在 notification-bell-panel.ts。
|
||||
* 那一层是真函数,`npm test` 能直接跑判据;组件只留 DOM 相关的一半:
|
||||
* 面板开合、fixed 定位、外部点击关闭、60s 轮询定时器。
|
||||
*/
|
||||
const {
|
||||
badgeText,
|
||||
dateRangeValue,
|
||||
detailLoading,
|
||||
detailTotal,
|
||||
details,
|
||||
goPage,
|
||||
groups,
|
||||
hasFilter,
|
||||
isExpanded,
|
||||
keyword,
|
||||
loadError,
|
||||
loading,
|
||||
markingAll,
|
||||
onItemClick,
|
||||
onDateRangeChange,
|
||||
onKeywordInput,
|
||||
page,
|
||||
readAll,
|
||||
refreshSummary,
|
||||
reload,
|
||||
resetFilters,
|
||||
rowCount,
|
||||
setSortMode,
|
||||
sortMode,
|
||||
toggleGroup,
|
||||
total,
|
||||
totalPages,
|
||||
unreadCount,
|
||||
} = useNotificationBellPanel({ uid: () => session.user?.id ?? 0, today: () => todayDateInput() })
|
||||
|
||||
/** 点锚点:先按原逻辑标已读,再跳任务中心(路由带 taskNo,页面进来自动开详情抽屉)。 */
|
||||
function openTaskRef(item: AdminNotificationItem, ref: AdminNotificationRef): void {
|
||||
const target = taskCenterRouteForRef(ref)
|
||||
if (!target) {
|
||||
return
|
||||
}
|
||||
void onItemClick(item)
|
||||
void router.push(target)
|
||||
}
|
||||
|
||||
const rootRef = ref<HTMLElement | null>(null)
|
||||
const panelRef = ref<HTMLElement | null>(null)
|
||||
const panelStyle = ref<Record<string, string>>({})
|
||||
const panelOpen = ref(false)
|
||||
|
||||
/** 模板里仍是 startsNewDay(index):组序列在面板层,这里只补一次取值。 */
|
||||
function startsNewDay(index: number): boolean {
|
||||
return groupStartsNewDay(groups.value, index)
|
||||
}
|
||||
|
||||
function formatTime(value: string | null) {
|
||||
return formatNotificationTime(value)
|
||||
}
|
||||
|
||||
/** 面板挂到 body 后用 fixed 定位,位置按触发器实时算(右对齐在铃铛下方)。 */
|
||||
function syncPanelPosition() {
|
||||
const trigger = rootRef.value
|
||||
if (!trigger) return
|
||||
const rect = trigger.getBoundingClientRect()
|
||||
panelStyle.value = {
|
||||
top: `${Math.round(rect.bottom + 10)}px`,
|
||||
right: `${Math.max(8, Math.round(window.innerWidth - rect.right))}px`,
|
||||
}
|
||||
}
|
||||
|
||||
function togglePanel() {
|
||||
panelOpen.value = !panelOpen.value
|
||||
if (panelOpen.value) {
|
||||
syncPanelPosition()
|
||||
reload()
|
||||
}
|
||||
}
|
||||
|
||||
/** 点击组件外部关闭面板(面板已 Teleport 到 body,需连同面板自身一起判断)。 */
|
||||
function onDocumentMouseDown(event: MouseEvent) {
|
||||
if (!panelOpen.value) return
|
||||
const target = event.target
|
||||
if (!(target instanceof Node)) return
|
||||
if (rootRef.value?.contains(target) || panelRef.value?.contains(target)) return
|
||||
panelOpen.value = false
|
||||
}
|
||||
|
||||
/** 窗口尺寸变化时重新对齐面板。 */
|
||||
function onWindowResize() {
|
||||
if (panelOpen.value) {
|
||||
syncPanelPosition()
|
||||
}
|
||||
}
|
||||
|
||||
/** 页面回到前台时立即刷新一次未读数。 */
|
||||
function onVisibilityChange() {
|
||||
if (typeof document !== 'undefined' && document.visibilityState === 'visible') {
|
||||
refreshSummary()
|
||||
}
|
||||
}
|
||||
|
||||
let pollTimer: number | null = null
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('mousedown', onDocumentMouseDown)
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
window.addEventListener('resize', onWindowResize)
|
||||
refreshSummary()
|
||||
pollTimer = window.setInterval(() => {
|
||||
if (typeof document !== 'undefined' && document.visibilityState !== 'visible') {
|
||||
return
|
||||
}
|
||||
refreshSummary()
|
||||
}, NOTIFICATION_POLL_INTERVAL_MS)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener('mousedown', onDocumentMouseDown)
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
window.removeEventListener('resize', onWindowResize)
|
||||
if (pollTimer != null) {
|
||||
window.clearInterval(pollTimer)
|
||||
pollTimer = null
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.admin-notification-bell {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.bell-trigger {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
padding: 0;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 9px;
|
||||
background: transparent;
|
||||
color: var(--admin-muted, #5b6f83);
|
||||
cursor: pointer;
|
||||
transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;
|
||||
}
|
||||
|
||||
.bell-trigger:hover,
|
||||
.bell-trigger--active {
|
||||
background: #edf5fb;
|
||||
border-color: #cbd9e6;
|
||||
color: var(--admin-primary-strong, #2f5d8b);
|
||||
}
|
||||
|
||||
.bell-icon {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.bell-badge {
|
||||
position: absolute;
|
||||
top: 1px;
|
||||
right: 0;
|
||||
min-width: 16px;
|
||||
height: 16px;
|
||||
padding: 0 4px;
|
||||
box-sizing: border-box;
|
||||
border-radius: 999px;
|
||||
background: #d64545;
|
||||
color: #ffffff;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
line-height: 16px;
|
||||
text-align: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.bell-panel {
|
||||
position: fixed;
|
||||
z-index: 3200;
|
||||
width: 380px;
|
||||
max-width: calc(100vw - 32px);
|
||||
max-height: 520px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border: 1px solid var(--admin-border, #d8e3ee);
|
||||
border-radius: 12px;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 18px 48px rgba(39, 67, 94, 0.22);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.bell-panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 12px 14px;
|
||||
border-bottom: 1px solid #edf1f5;
|
||||
}
|
||||
|
||||
.bell-panel-title {
|
||||
color: var(--admin-text, #24384d);
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.bell-read-all {
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--admin-primary-strong, #2f5d8b);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.bell-read-all:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.bell-empty {
|
||||
padding: 36px 0;
|
||||
color: #8a99a8;
|
||||
font-size: 13px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.bell-empty--error {
|
||||
color: #b23c3c;
|
||||
}
|
||||
|
||||
.bell-list {
|
||||
flex: 1;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.bell-item {
|
||||
padding: 11px 14px;
|
||||
border-bottom: 1px solid #f0f3f7;
|
||||
cursor: pointer;
|
||||
transition: background 0.12s ease;
|
||||
}
|
||||
|
||||
.bell-item:hover {
|
||||
background: #f7f9fc;
|
||||
}
|
||||
|
||||
/* ---- 聚合行(默认视图的一级)与明细行(展开后的二级)---- */
|
||||
.bell-group {
|
||||
padding: 11px 14px 8px;
|
||||
border-bottom: 1px solid #f0f3f7;
|
||||
cursor: pointer;
|
||||
transition: background 0.12s ease;
|
||||
}
|
||||
|
||||
.bell-group:hover {
|
||||
background: #f7f9fc;
|
||||
}
|
||||
|
||||
.bell-group--open {
|
||||
background: #f4f8fd;
|
||||
}
|
||||
|
||||
.bell-group-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.bell-group-count {
|
||||
color: #7c8b9a;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.bell-group-toggle {
|
||||
color: var(--admin-primary-strong, #2f5d8b);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* 明细缩进 + 左侧一道竖线,让"这是上面那一组里的东西"看得出来,而不是又一批同级通知 */
|
||||
.bell-item--detail {
|
||||
padding-left: 26px;
|
||||
background: #fcfdfe;
|
||||
border-bottom-color: #f5f8fb;
|
||||
}
|
||||
|
||||
.bell-item--detail::before {
|
||||
content: '';
|
||||
display: inline-block;
|
||||
width: 2px;
|
||||
height: 26px;
|
||||
margin: 0 0 -8px -14px;
|
||||
border-radius: 2px;
|
||||
background: #dce7f2;
|
||||
}
|
||||
|
||||
.bell-empty--detail {
|
||||
padding: 14px 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.bell-detail-more {
|
||||
padding: 8px 14px;
|
||||
color: #8a99a8;
|
||||
font-size: 11px;
|
||||
text-align: center;
|
||||
background: #fcfdfe;
|
||||
}
|
||||
|
||||
.bell-item--unread {
|
||||
background: #f2f6ff;
|
||||
}
|
||||
|
||||
.bell-item--unread .bell-item-title::before {
|
||||
content: '';
|
||||
display: inline-block;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
margin-right: 7px;
|
||||
border-radius: 50%;
|
||||
background: #d64545;
|
||||
vertical-align: 1px;
|
||||
}
|
||||
|
||||
.bell-item-head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.bell-item-title {
|
||||
flex: 1;
|
||||
color: var(--admin-text, #24384d);
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.bell-severity-tag {
|
||||
flex-shrink: 0;
|
||||
padding: 1px 6px;
|
||||
border: 1px solid currentColor;
|
||||
border-radius: 999px;
|
||||
font-size: 10.5px;
|
||||
font-weight: 600;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.bell-severity-tag--urgent {
|
||||
background: #fdecec;
|
||||
color: #c92a2a;
|
||||
}
|
||||
|
||||
.bell-severity-tag--high {
|
||||
background: #fdf3e2;
|
||||
color: #b26a12;
|
||||
}
|
||||
|
||||
.bell-severity-tag--medium {
|
||||
background: #eaf2fb;
|
||||
color: #2f6fb3;
|
||||
}
|
||||
|
||||
.bell-severity-tag--low {
|
||||
background: #f1f4f7;
|
||||
color: #6b7c8e;
|
||||
}
|
||||
|
||||
.bell-item--error .bell-item-title {
|
||||
color: #b23c3c;
|
||||
}
|
||||
|
||||
.bell-item--warning .bell-item-title {
|
||||
color: #a8793e;
|
||||
}
|
||||
|
||||
.bell-item--info .bell-item-title {
|
||||
color: var(--admin-primary-strong, #2f5d8b);
|
||||
}
|
||||
|
||||
.bell-item-time {
|
||||
flex-shrink: 0;
|
||||
color: #9aa6b3;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.bell-item-content {
|
||||
margin-top: 4px;
|
||||
color: #667085;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
/* 定位锚点:任务号可点,直达任务详情。压低视觉权重,不与正文抢注意力。 */
|
||||
.bell-ref-list { display: flex; flex-direction: column; gap: 2px; margin-top: 6px; }
|
||||
.bell-ref-link { padding: 0; border: none; background: none; color: var(--admin-primary, #2f5d8b); font-family: inherit; font-size: 12px; line-height: 1.5; text-align: left; word-break: break-all; cursor: pointer; }
|
||||
.bell-ref-link:hover { text-decoration: underline; }
|
||||
.bell-ref-reason { color: #8a94a6; }
|
||||
|
||||
.bell-search {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 10px 12px;
|
||||
border-bottom: 1px solid #edf1f5;
|
||||
background: #fafcfe;
|
||||
}
|
||||
|
||||
.bell-search-input,
|
||||
.bell-date-input {
|
||||
height: 28px;
|
||||
padding: 0 8px;
|
||||
box-sizing: border-box;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 6px;
|
||||
background: #ffffff;
|
||||
color: var(--admin-text, #24384d);
|
||||
font-size: 12px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.bell-search-input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.bell-search-input:focus,
|
||||
.bell-date-input:focus {
|
||||
border-color: var(--admin-primary-strong, #2f5d8b);
|
||||
}
|
||||
|
||||
.bell-search-days {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.bell-date-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.bell-date-sep {
|
||||
color: #8a99a8;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.bell-search-reset {
|
||||
flex-shrink: 0;
|
||||
padding: 0 8px;
|
||||
height: 28px;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 6px;
|
||||
background: #ffffff;
|
||||
color: var(--admin-primary-strong, #2f5d8b);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.bell-search-reset:hover {
|
||||
background: #edf5fb;
|
||||
}
|
||||
|
||||
.bell-sort-chips {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.bell-sort-label {
|
||||
color: #8a99a8;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.bell-sort-chip {
|
||||
height: 24px;
|
||||
padding: 0 10px;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 12px;
|
||||
background: #ffffff;
|
||||
color: #667085;
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
transition: color 0.15s ease, border-color 0.15s ease, background 0.15s ease;
|
||||
}
|
||||
|
||||
.bell-sort-chip:hover {
|
||||
border-color: var(--admin-primary-strong, #2f5d8b);
|
||||
color: var(--admin-primary-strong, #2f5d8b);
|
||||
}
|
||||
|
||||
.bell-sort-chip.is-active {
|
||||
border-color: var(--admin-primary-strong, #2f5d8b);
|
||||
background: #edf5fb;
|
||||
color: var(--admin-primary-strong, #2f5d8b);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.bell-day-head {
|
||||
padding: 6px 14px;
|
||||
background: #f4f7fa;
|
||||
color: #7c8b9a;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
.bell-panel-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
padding: 7px 12px;
|
||||
border-top: 1px solid #edf1f5;
|
||||
}
|
||||
|
||||
.bell-page-btn {
|
||||
padding: 3px 10px;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 6px;
|
||||
background: #ffffff;
|
||||
color: var(--admin-primary-strong, #2f5d8b);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.bell-page-btn:hover:not(:disabled) {
|
||||
background: #edf5fb;
|
||||
}
|
||||
|
||||
.bell-page-btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.bell-page-info {
|
||||
color: var(--admin-text, #24384d);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.bell-page-total {
|
||||
color: #9aa6b3;
|
||||
font-size: 11px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<style>
|
||||
/* 日期选择面板与通知面板同为 body 级浮层,须压在通知面板(3200)之上:
|
||||
Element 弹层只自 2000 起递增,不抬就会被面板挡住,表现为「日期点不动」。 */
|
||||
.bell-date-popper {
|
||||
z-index: 3300 !important;
|
||||
}
|
||||
</style>
|
||||
@@ -1,121 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/** 旧版风格分页(像素复刻 admin.html .pagination)+ 每页条数下拉(10/20/50/100)。
|
||||
* props: total / page / pageSize / sizes(默认 10/20/50/100) / showTotal(默认 true) / jump(默认 true)。 */
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
sizes?: number[]
|
||||
showTotal?: boolean
|
||||
jump?: boolean
|
||||
}>(),
|
||||
{ sizes: () => [10, 20, 50, 100], showTotal: true, jump: true },
|
||||
)
|
||||
const emit = defineEmits<{
|
||||
(e: 'change', page: number): void
|
||||
(e: 'size-change', size: number): void
|
||||
}>()
|
||||
|
||||
const jumpPage = ref('')
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(props.total / props.pageSize)))
|
||||
|
||||
function go(next: number) {
|
||||
if (next < 1 || next > totalPages.value || next === props.page) return
|
||||
emit('change', next)
|
||||
}
|
||||
|
||||
function goJump() {
|
||||
const n = Number.parseInt(jumpPage.value, 10)
|
||||
if (Number.isNaN(n)) return
|
||||
jumpPage.value = ''
|
||||
go(Math.min(Math.max(n, 1), totalPages.value))
|
||||
}
|
||||
|
||||
function onSizeChange(event: Event) {
|
||||
const value = Number((event.target as HTMLSelectElement).value)
|
||||
if (Number.isFinite(value) && value > 0) emit('size-change', value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="old-pagination">
|
||||
<span v-if="showTotal" class="page-total">共 {{ total }} 条</span>
|
||||
<select class="page-size-select" :value="pageSize" @change="onSizeChange">
|
||||
<option v-for="size in sizes" :key="size" :value="size">{{ size }}条/页</option>
|
||||
</select>
|
||||
<button type="button" :disabled="page <= 1" @click="go(page - 1)">上一页</button>
|
||||
<span class="page-cur">第 {{ page }} / {{ totalPages }} 页</span>
|
||||
<button type="button" :disabled="page >= totalPages" @click="go(page + 1)">下一页</button>
|
||||
<span v-if="jump" class="page-jump">
|
||||
跳至
|
||||
<input v-model="jumpPage" type="text" inputmode="numeric" @keyup.enter="goJump" />
|
||||
页
|
||||
<button type="button" @click="goJump">跳转</button>
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.old-pagination {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-top: 18px;
|
||||
color: #5b6f83;
|
||||
font-size: 13px;
|
||||
}
|
||||
.old-pagination button {
|
||||
min-height: 30px;
|
||||
padding: 4px 12px;
|
||||
border: 1px solid #c7d7e5;
|
||||
border-radius: 8px;
|
||||
background: #ffffff;
|
||||
color: #5b6f83;
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.old-pagination button:hover:not(:disabled) {
|
||||
background: #edf5fb;
|
||||
border-color: #95b1cb;
|
||||
color: #2f5d8b;
|
||||
}
|
||||
.old-pagination button:disabled {
|
||||
background: #eef3f7;
|
||||
color: #9baaba;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.page-total {
|
||||
margin-right: 4px;
|
||||
}
|
||||
.page-size-select {
|
||||
min-height: 30px;
|
||||
padding: 3px 8px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 8px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
}
|
||||
.page-jump {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.page-jump input {
|
||||
width: 56px;
|
||||
min-height: 30px;
|
||||
padding: 4px 8px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 8px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
}
|
||||
</style>
|
||||
@@ -1,68 +0,0 @@
|
||||
/**
|
||||
* 二次确认模型(module 13 task 245):文案/按钮键规则对齐 admin-interactions.js ——
|
||||
* 优先显式 message,否则由行名拼接「确认删除“X”吗?此操作可能影响已有数据。」;
|
||||
* danger(删除/清空/删除导入类)默认标题「删除前确认」、确认键「确认删除」。
|
||||
* 纯逻辑、无 UI 依赖,便于单测;打开入口见 admin-confirm.ts。
|
||||
*/
|
||||
export const ADMIN_CONFIRM = {
|
||||
dangerTitle: '删除前确认',
|
||||
defaultTitle: '请确认操作',
|
||||
confirmDeleteOk: '确认删除',
|
||||
confirmOk: '确认操作',
|
||||
cancel: '取消',
|
||||
deleteMessageSuffix: '此操作可能影响已有数据。',
|
||||
} as const
|
||||
|
||||
export interface AdminConfirmPlan {
|
||||
danger: boolean
|
||||
title: string
|
||||
message: string
|
||||
confirmText: string
|
||||
cancelText: string
|
||||
type: 'warning' | 'info'
|
||||
}
|
||||
|
||||
/** 由目标名称生成删除确认文案;无名称时退化为「该项」。 */
|
||||
export function confirmMessageFor(targetName?: string): string {
|
||||
const name = typeof targetName === 'string' && targetName.trim() ? `“${targetName.trim()}”` : '该项'
|
||||
return `确认删除${name}吗?${ADMIN_CONFIRM.deleteMessageSuffix}`
|
||||
}
|
||||
|
||||
export interface AdminConfirmOptions {
|
||||
danger?: boolean
|
||||
targetName?: string
|
||||
message?: string
|
||||
title?: string
|
||||
confirmText?: string
|
||||
}
|
||||
|
||||
/** 归一出二次确认计划:显式字段优先,否则按 danger/目标名落默认值。 */
|
||||
export function createConfirmPlan(opts: AdminConfirmOptions): AdminConfirmPlan {
|
||||
const danger = opts.danger !== false
|
||||
const message = opts.message && opts.message.trim() ? opts.message.trim() : confirmMessageFor(opts.targetName)
|
||||
return {
|
||||
danger,
|
||||
title: opts.title ?? (danger ? ADMIN_CONFIRM.dangerTitle : ADMIN_CONFIRM.defaultTitle),
|
||||
message,
|
||||
confirmText: opts.confirmText ?? (danger ? ADMIN_CONFIRM.confirmDeleteOk : ADMIN_CONFIRM.confirmOk),
|
||||
cancelText: ADMIN_CONFIRM.cancel,
|
||||
type: danger ? 'warning' : 'info',
|
||||
}
|
||||
}
|
||||
|
||||
// 并发防护:同一时刻只允许一个确认框在途(拒绝重复弹出)。
|
||||
let confirmLocked = false
|
||||
|
||||
export function acquireConfirmLock(): boolean {
|
||||
if (confirmLocked) return false
|
||||
confirmLocked = true
|
||||
return true
|
||||
}
|
||||
|
||||
export function releaseConfirmLock(): void {
|
||||
confirmLocked = false
|
||||
}
|
||||
|
||||
export function isConfirmLocked(): boolean {
|
||||
return confirmLocked
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
/**
|
||||
* 二次确认打开入口(module 13 task 245):把模型计划交给 ElMessageBox,并对
|
||||
* 确认/取消统一归约为 boolean;并发锁拒绝重复弹出。
|
||||
*/
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import {
|
||||
acquireConfirmLock,
|
||||
createConfirmPlan,
|
||||
releaseConfirmLock,
|
||||
type AdminConfirmOptions,
|
||||
} from './admin-confirm-model'
|
||||
|
||||
export async function openAdminConfirm(options: AdminConfirmOptions = {}): Promise<boolean> {
|
||||
const plan = createConfirmPlan(options)
|
||||
if (!acquireConfirmLock()) return false
|
||||
try {
|
||||
return await ElMessageBox.confirm(plan.message, plan.title, {
|
||||
confirmButtonText: plan.confirmText,
|
||||
cancelButtonText: plan.cancelText,
|
||||
type: plan.type,
|
||||
}).then(
|
||||
() => true,
|
||||
() => false,
|
||||
)
|
||||
} finally {
|
||||
releaseConfirmLock()
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
/**
|
||||
* 反馈 UI 接线(module 13 task 246):把模型语义接到 ElMessage 与 busy 锁上。
|
||||
* 页面统一用 showAdminFeedback / runBusy,避免各页 ElMessage 直接散打文案。
|
||||
*/
|
||||
import { ElMessage } from 'element-plus'
|
||||
import {
|
||||
endBusy,
|
||||
normalizeFeedback,
|
||||
tryBeginBusy,
|
||||
type AdminFeedbackKind,
|
||||
} from './admin-feedback'
|
||||
|
||||
export function showAdminFeedback(message?: string, kind?: AdminFeedbackKind): void {
|
||||
const { kind: k, message: m } = normalizeFeedback(message, kind)
|
||||
if (k === 'success') ElMessage.success(m)
|
||||
else if (k === 'error') ElMessage.error(m)
|
||||
else ElMessage.warning(m)
|
||||
}
|
||||
|
||||
/** 以 busy 锁包裹一个提交动作;已在途则直接返回 undefined,防止重复提交。 */
|
||||
export async function runBusy<T>(task: () => Promise<T>): Promise<T | undefined> {
|
||||
if (!tryBeginBusy()) return undefined
|
||||
try {
|
||||
return await task()
|
||||
} finally {
|
||||
endBusy()
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
/**
|
||||
* 反馈语义模型(module 13 task 246):成功/错误/警告统一文案与 busy 防重入。
|
||||
* 纯逻辑、不依赖 Element;UI 接线见 admin-feedback-ui.ts。
|
||||
*/
|
||||
export type AdminFeedbackKind = 'success' | 'error' | 'warning'
|
||||
|
||||
export const FEEDBACK_TEXT = {
|
||||
successDefault: '操作成功',
|
||||
errorDefault: '操作失败,请稍后重试',
|
||||
warningDefault: '请确认后再继续',
|
||||
busySuffix: '中…',
|
||||
} as const
|
||||
|
||||
export interface NormalizedFeedback {
|
||||
kind: AdminFeedbackKind
|
||||
message: string
|
||||
}
|
||||
|
||||
const KIND_DEFAULT: Record<AdminFeedbackKind, string> = {
|
||||
success: FEEDBACK_TEXT.successDefault,
|
||||
error: FEEDBACK_TEXT.errorDefault,
|
||||
warning: FEEDBACK_TEXT.warningDefault,
|
||||
}
|
||||
|
||||
/** 归一反饋消息:显式 message 保留并去首尾空白,空值按 kind 落默认文案。 */
|
||||
export function normalizeFeedback(message?: string, kind?: AdminFeedbackKind): NormalizedFeedback {
|
||||
const k: AdminFeedbackKind = kind ?? 'warning'
|
||||
const trimmed = typeof message === 'string' ? message.trim() : ''
|
||||
return { kind: k, message: trimmed ? trimmed : KIND_DEFAULT[k] }
|
||||
}
|
||||
|
||||
/** 忙碌按钮文案:「保存」→「保存中…」;已以「中」结尾则不重复补。 */
|
||||
export function busyLabel(verb: string): string {
|
||||
const v = (verb || '处理').trim()
|
||||
return v.endsWith('中') ? `${v}…` : `${v}${FEEDBACK_TEXT.busySuffix}`
|
||||
}
|
||||
|
||||
/** 把 Error/字符串/未知错误转成可行动错误文案;空值回默认错误。 */
|
||||
export function actionableErrorText(error: unknown): string {
|
||||
if (error instanceof Error && error.message && error.message.trim()) return error.message.trim()
|
||||
if (typeof error === 'string' && error.trim()) return error.trim()
|
||||
return FEEDBACK_TEXT.errorDefault
|
||||
}
|
||||
|
||||
// busy 单例锁:表单提交/导出等防重复进入。
|
||||
let busy = false
|
||||
|
||||
export function tryBeginBusy(): boolean {
|
||||
if (busy) return false
|
||||
busy = true
|
||||
return true
|
||||
}
|
||||
|
||||
export function endBusy(): void {
|
||||
busy = false
|
||||
}
|
||||
|
||||
export function isBusy(): boolean {
|
||||
return busy
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
/**
|
||||
* 复制文本反馈模型(module 13 task 247):非空给出「已复制 X」,失败/空值给降级文案。
|
||||
*/
|
||||
export const COPY_FEEDBACK_FALLBACK = '复制失败,请手动选择'
|
||||
|
||||
export function copyFeedback(text: string): string {
|
||||
const t = typeof text === 'string' ? text.trim() : ''
|
||||
return t ? `已复制 ${t}` : COPY_FEEDBACK_FALLBACK
|
||||
}
|
||||
|
||||
export function isCopySupported(): boolean {
|
||||
return typeof navigator !== 'undefined' && typeof navigator.clipboard?.writeText === 'function'
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
/**
|
||||
* 列表加载失败态模型(四面9分口径 · 后管「模板内失败态只有 4/24 页」):
|
||||
* 把「请求失败了」归一成一条可读中文,配 LoadFailureBar.vue 的那个真能重跑的按钮用。
|
||||
*
|
||||
* 纯逻辑、不依赖 Vue 也不依赖 Element,`node --test` 直接 import 跑行为断言。
|
||||
* 文案把关复用 api/user-notice:后端把底层异常原文拼进 message 时,界面只留中文主干。
|
||||
*/
|
||||
import { userNotice } from '../api/user-notice.ts'
|
||||
|
||||
/** 失败条上那个按钮的字样:必须是「重试」而不是一句「知道了」——撤入口同时得是出口。 */
|
||||
export const LOAD_FAILURE_RETRY_LABEL = '重试'
|
||||
|
||||
/** 从 axios 错误 / Error / 字符串里取后端给的原因;取不到、或原文不是中文时返回空串。 */
|
||||
export function failureDetail(error: unknown): string {
|
||||
const data = (error as { response?: { data?: unknown } } | undefined)?.response?.data
|
||||
if (data && typeof data === 'object') {
|
||||
const record = data as Record<string, unknown>
|
||||
for (const key of ['message', 'error', 'msg']) {
|
||||
const value = record[key]
|
||||
if (typeof value === 'string' && value.trim()) return userNotice(value, '')
|
||||
}
|
||||
}
|
||||
if (error instanceof Error && error.message.trim()) return userNotice(error.message, '')
|
||||
if (typeof error === 'string' && error.trim()) return userNotice(error, '')
|
||||
return ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 后端按范围拒掉的句子(`无权操作该总数据`、`缺少归属公司…`)补一句人话:
|
||||
* 这类失败不是页面坏了,重试一百次也是同一个结果,得把出路说清楚。
|
||||
*/
|
||||
export const SCOPE_REFUSAL_NOTE = '这一行不在你当前可操作的分组/公司范围内,需要由平台超级管理员处理'
|
||||
const SCOPE_REFUSAL = /无权|缺少归属公司/
|
||||
|
||||
/** 命中范围拒绝时返回补充说明,否则空串。 */
|
||||
export function scopeRefusalNote(detail: string): string {
|
||||
return SCOPE_REFUSAL.test(detail || '') ? SCOPE_REFUSAL_NOTE : ''
|
||||
}
|
||||
|
||||
/** 「本页兜底文案:后端原因」;没有可读原因时只留兜底文案,不拼出「加载失败:」这种半截句。 */
|
||||
export function loadFailureMessage(error: unknown, fallback: string): string {
|
||||
const head = (fallback || '').trim()
|
||||
const detail = failureDetail(error)
|
||||
if (!detail) return head
|
||||
const note = scopeRefusalNote(detail)
|
||||
const reason = note ? `${detail}(${note})` : detail
|
||||
if (!head || head.includes(detail)) return head || reason
|
||||
return `${head}:${reason}`
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
/**
|
||||
* /admin-vue/ 基准路径与 History 路由约定(任务 2 冻结的单一事实源)。
|
||||
* Vite base、Vue Router history base、Nginx location 三者必须共用此常量。
|
||||
*/
|
||||
export const APP_BASE_PATH = '/admin-vue/'
|
||||
|
||||
/** 前端路由一律使用 History 模式,不引入 hash(旧 #tab 兼容不在目标契约内)。 */
|
||||
export const APP_HISTORY_MODE = 'history' as const
|
||||
|
||||
function invalidBaseMessage(value: unknown): string {
|
||||
return `管理后台 base 路径非法: ${JSON.stringify(value)},必须以 / 开头且形如 /xxx/,不允许空值或 ..`
|
||||
}
|
||||
|
||||
/** 校验并归一化 base 路径:保证以 / 开头、无 ..、无内部连续斜杠、以单个 / 结尾。 */
|
||||
export function ensureAppBasePath(value: string): string {
|
||||
if (typeof value !== 'string' || value.length === 0) throw new Error(invalidBaseMessage(value))
|
||||
if (!value.startsWith('/')) throw new Error(invalidBaseMessage(value))
|
||||
if (value.includes('//')) throw new Error(invalidBaseMessage(value))
|
||||
if (value.includes('..')) throw new Error(invalidBaseMessage(value))
|
||||
return value.endsWith('/') ? value : `${value}/`
|
||||
}
|
||||
|
||||
/** 把后台页面相对路径段拼成绝对 URL(不含 base 前缀的历史兼容子路径段由路由负责)。 */
|
||||
export function joinAdminPath(...segments: string[]): string {
|
||||
const parts: string[] = []
|
||||
for (const segment of segments) {
|
||||
for (const raw of segment.split('/')) {
|
||||
const part = raw.trim()
|
||||
if (!part || part === '.') continue
|
||||
if (part === '..') {
|
||||
throw new Error(`admin 路由段不允许出现 ..(越权跳转): ${segments.join('/')}`)
|
||||
}
|
||||
parts.push(part)
|
||||
}
|
||||
}
|
||||
if (parts.length === 0) return APP_BASE_PATH
|
||||
return `${APP_BASE_PATH}${parts.join('/')}`
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
/** 公司口径的唯一清单(设计文档 §8)。
|
||||
* 单独成文件而不是塞进 routes.ts:routes.ts 被 menu-route-map.ts import,
|
||||
* 而护栏用例要从这里反过来读注册表,放在一起会成环。 */
|
||||
|
||||
/** 角色内在闸门:只有超管可见可读写,与 user_column_permission 无关。 */
|
||||
export const SUPER_ADMIN_ONLY_MENU_KEYS: readonly string[] = ['admin_companies']
|
||||
|
||||
export interface CompanyScopedPage {
|
||||
/** 与 routes.ts 的 menuKey 逐字一致。 */
|
||||
menuKey: string
|
||||
/** 相对 admin-frontend-vue 的 api/取数模块路径;护栏逐文件断言它真的带了 company_id。 */
|
||||
apiFiles: string[]
|
||||
/** 页面组件路径;护栏断言它 watch 了 tab.activeId(否则切 tab 不重取数,tab 是装饰品)。 */
|
||||
pageFiles: string[]
|
||||
}
|
||||
|
||||
/** 参与公司 tab 的页(spec §3 归属普查:批次 1 = 9 个 A 类页里除去依赖二期 V145 的去重库)。
|
||||
* 后续批次往里加行时,同一笔提交必须带上对应 api 文件的 company_id,否则新用例红。 */
|
||||
export const COMPANY_SCOPED_PAGES: readonly CompanyScopedPage[] = [
|
||||
{ menuKey: 'admin_task_center', apiFiles: ['src/api/task-center.ts', 'src/pages/task-center/task-center-model.ts'], pageFiles: ['src/pages/task-center/TaskCenterBoardPage.vue'] },
|
||||
{ menuKey: 'admin_image_video_tasks', apiFiles: ['src/pages/tasks/image-video-api.ts'], pageFiles: ['src/pages/tasks/ImageVideoTasksPage.vue'] },
|
||||
{ menuKey: 'admin_user_secret_usage', apiFiles: ['src/api/user-secret-usage.ts'], pageFiles: ['src/pages/account/UserSecretUsagePage.vue'] },
|
||||
{ menuKey: 'admin_user_secrets', apiFiles: ['src/api/user-secrets.ts'], pageFiles: ['src/pages/account/UserSecretsPage.vue'] },
|
||||
{ menuKey: 'admin_history', apiFiles: ['src/pages/records/history-api.ts'], pageFiles: ['src/pages/records/RecordsHistoryPage.vue'] },
|
||||
{ menuKey: 'admin_device_logs', apiFiles: ['src/api/device-logs.ts'], pageFiles: ['src/pages/records/DeviceLogsPage.vue'] },
|
||||
{ menuKey: 'admin_group_manage', apiFiles: ['src/pages/account/shop-group-api.ts'], pageFiles: ['src/pages/account/GroupsPage.vue'] },
|
||||
{ menuKey: 'admin_shop_manage', apiFiles: ['src/pages/shop/shop-manage-api.ts'], pageFiles: ['src/pages/shop/ShopManagePage.vue'] },
|
||||
// 批次 2(控制方 2026-10-05 点名「切 tab 数据还一样」那五页):读门已在后端接上(V145 补归属 / V147 加列),
|
||||
// 这一批把前端接线补齐。apiFiles 只列**真的把 company_id 拼进请求**的模块:
|
||||
// 各页的 *-filter.ts 与 asin-filter.ts 只带 camel 的 companyId 字段(类型 + 白名单构造都不点名它),
|
||||
// 列进来会让正向判据去盯一个本来就不该出现 snake_case 的文件。
|
||||
// 【这两页已于 2026-10-06 退出注册表】admin_invalid_asin_data(品牌数据库)与 admin_product_categories
|
||||
// (商品类目)按控制方定案退回**全平台共享**,摘的不只是 tab:后端读写两侧的 company_id 谓词一起删
|
||||
// (V151 退唯一键)。反向钉在 tests/company-tab-wiring.test.ts——把它们再加回来必须先推翻那条定案。
|
||||
// dedupe-import-api.ts 是 10-09 补进来的:导入/删除导入这两支写侧出口原先不发 company_id,
|
||||
// 超管在别家 tab 点「新增导入」,数据落进了超管自己那一家(group_id 却是别家的组)=归属分裂。
|
||||
{ menuKey: 'admin_dedupe_total_data', apiFiles: ['src/pages/asin/dedupe-total-api.ts', 'src/pages/asin/dedupe-total-export.ts', 'src/pages/asin/dedupe-import-api.ts'], pageFiles: ['src/pages/asin/DedupeRegistryPage.vue'] },
|
||||
{ menuKey: 'admin_query_asin', apiFiles: ['src/pages/asin/query-asin-api.ts', 'src/pages/asin/query-asin-export.ts'], pageFiles: ['src/pages/asin/QueryAsinPage.vue'] },
|
||||
{ menuKey: 'admin_skip_price_asin', apiFiles: ['src/pages/asin/skip-price-api.ts', 'src/pages/asin/skip-price-export.ts'], pageFiles: ['src/pages/asin/SkipPricePage.vue'] },
|
||||
// 批次 3(控制方 2026-10-05 点名「店铺撞款监控 店铺数据也要做隔离」)。这两页的可见集不是按 company_id 列筛的,
|
||||
// 而是「本公司账号名下的店铺」:后端由 DataReadScope 把公司 → 成员账号 → biz_shop_manage.created_by_id 逐级推导,
|
||||
// 前端只负责把 activeId 当 company_id 送下去。
|
||||
{ menuKey: 'admin_shop_data_duplicate_check', apiFiles: ['src/pages/tasks/duplicate-console-api.ts'], pageFiles: ['src/pages/tasks/DuplicateCheckPage.vue'] },
|
||||
// 关键词使用记录(2026-10-25):只读留痕按行 company_id 收窄;超管切 tab 重取,非超管后端强制本公司。
|
||||
{ menuKey: 'admin_keyword_usage', apiFiles: ['src/pages/tasks/keyword-usage-api.ts'], pageFiles: ['src/pages/tasks/KeywordUsagePage.vue'] },
|
||||
{ menuKey: 'admin_shop_data_crawl_tasks', apiFiles: ['src/pages/tasks/shop-data-api.ts'], pageFiles: ['src/pages/tasks/ShopDataTasksPage.vue'] },
|
||||
// 批次 4(控制方 2026-10-05 点名「菜单权限和用户管理也要区分公司 tab 的数据」)。
|
||||
// 这一页的后端早就认 company_id(AdminUserService 只在**站点超管**身上用它筛,公司超管恒锁本公司),
|
||||
// 断的是前端:users-dto 的 UserListQuery 里连这个字段都没有 ⇒ 三家 tab 看到的是同一份全量列表。
|
||||
{ menuKey: 'admin_users', apiFiles: ['src/api/users.ts', 'src/pages/account/user-menu-auth-api.ts'], pageFiles: ['src/pages/account/UsersPage.vue'] },
|
||||
// 批次 5(控制方 2026-10-06 点名「店铺密钥管理的数据按照公司区分」)。biz_shop_key 原先零归属列,
|
||||
// 拿到这一页菜单的任意管理员读的是同一池全平台紫鸟令牌,而列表 VO 把令牌原文整列下发(悬停即得全文)。
|
||||
// V150 加 company_id;后端读门是 readCompanyIdOrOwn ⇒ 非超管连 company_id 都不带也一律锁本公司,
|
||||
// 这一页的 tab 只对超管改变行数(非超管恒锁本公司,与其余页同形)。
|
||||
{ menuKey: 'admin_shop_keys', apiFiles: ['src/pages/shop/shop-key-api.ts'], pageFiles: ['src/pages/shop/ShopKeysPage.vue'] },
|
||||
// 批次 6(控制方 2026-10-06 点名「菜单权限也加字段来区分」,并选了「每家公司一套菜单树」那一档)。
|
||||
// V149 给 columns 加 company_id 并把 52 行复制成每家一套 ⇒ 同一 column_key 在别家有另一份 id:
|
||||
// 不带 company_id 时后端只给操作者本公司那一棵(2026-10-06 生产实测),超管切看别家必须显式带;
|
||||
// 而一旦漏带又去勾别家的项,提交的 id 属于另一棵树,后端按本公司菜单集校验就会撞
|
||||
// 「无效的菜单权限项」。写侧(编辑/删除/重排)不带参数——归属由那一行的 id 与操作者公司共同判定,
|
||||
// 跨公司写后端 403(见 docs/ops/menu-company-tree-design-2026-10-06.md §5)。
|
||||
{ menuKey: 'admin_columns', apiFiles: ['src/pages/account/menu-manage-api.ts'], pageFiles: ['src/pages/account/MenusPage.vue'] },
|
||||
// 外观专利无侵权数据(2026-11-10 v1.3):出表成功自动同步的只读明细,归属物化在行 company_id 列
|
||||
// (V189,同店铺密钥形状)⇒ 后端正门 readCompanyIdOrOwn(超管显式传才收窄,非超管强制本公司)。
|
||||
{ menuKey: 'admin_appearance_patent_clean_items', apiFiles: ['src/pages/patent/appearance-patent-clean-api.ts'], pageFiles: ['src/pages/patent/AppearancePatentCleanItemsPage.vue'] },
|
||||
// 京东数据库(2026-11-14 v1.4)已于 2026-11-16 退出注册表(用户定案「删除掉公司 tab,参考品牌
|
||||
// 数据库」=品牌库 2026-10-06 先例同形):数据全平台公共(行 company_id 只剩"哪家公司客户端
|
||||
// 同步的"来源标记),摘的不只是 tab——页面/api 的 company_id 发送口与后端读侧 company_id 谓词
|
||||
// (superAdminScopedCompanyId)同窗一起摘。反向钉在 tests/company-tab-wiring.test.ts 的
|
||||
// 「公司维度不得回流」清单里,再加回来必须先推翻这条定案。
|
||||
]
|
||||
@@ -1,43 +0,0 @@
|
||||
/** 平台 tab 口径的唯一清单(2026-11-16 用户定案「亚马逊/京东不混一起」)。
|
||||
* 仿 company-scope.ts 的形状:单独成文件而不是塞进 routes.ts——护栏用例要从这里
|
||||
* 反读清单与注册表对撞,放在一起会成环。 */
|
||||
|
||||
export type PlatformTabId = 'amazon' | 'jd'
|
||||
|
||||
export interface PlatformTabDef {
|
||||
id: PlatformTabId
|
||||
label: string
|
||||
}
|
||||
|
||||
/** 侧边栏顶部平台 tab 的固定顺序:亚马逊在前(存量主体),京东在后。 */
|
||||
export const PLATFORM_TABS: readonly PlatformTabDef[] = [
|
||||
{ id: 'amazon', label: '亚马逊' },
|
||||
{ id: 'jd', label: '京东' },
|
||||
]
|
||||
|
||||
/** 京东侧独占菜单的 menuKey 唯一清单(与 routes.ts 的 menuKey 逐字一致,用例钉住)。
|
||||
* 2026-11-17 加京东分类管理(用户口径「这边分组是京东的分组管理的而不是亚马逊的」——
|
||||
* 分类管理子菜单归京东侧,不与亚马逊侧混排)。
|
||||
* 后续京东新页面上线把 key 加进这里即可,清单外的 key(含店铺管理/生成记录等
|
||||
* 存量页)一律归亚马逊或双侧清单。 */
|
||||
export const JD_MENU_KEYS: readonly string[] = [
|
||||
'admin_jd_database',
|
||||
'admin_jd_category_manage',
|
||||
]
|
||||
|
||||
/** 双侧共用菜单(2026-11-17 用户口径「这些亚马逊这边也要有」):三个账号域页面在两个
|
||||
* 平台 tab 下都显示——同一套组件、按当前 tab 给接口传 platform,各自只看/管各自平台的
|
||||
* 账号、分组、公司(后端 V206 三表加列,存量默认亚马逊,京东侧数据在编辑弹窗里翻档)。 */
|
||||
export const BOTH_PLATFORM_MENU_KEYS: readonly string[] = [
|
||||
'admin_users',
|
||||
'admin_group_manage',
|
||||
'admin_companies',
|
||||
]
|
||||
|
||||
/** menuKey → 平台归属清单(唯一判定出口):京东独占 → ['jd'];双侧清单 → ['amazon','jd'];
|
||||
* 其余(未知 key 在内)默认亚马逊。 */
|
||||
export function platformsOfMenuKey(key: string): PlatformTabId[] {
|
||||
if (JD_MENU_KEYS.includes(key)) return ['jd']
|
||||
if (BOTH_PLATFORM_MENU_KEYS.includes(key)) return ['amazon', 'jd']
|
||||
return ['amazon']
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
import { existsSync, readFileSync, readdirSync } from 'node:fs'
|
||||
import { join, resolve } from 'node:path'
|
||||
|
||||
export const STANDALONE_PACKAGE_NAME = 'crawler-plugin-admin-frontend-vue'
|
||||
|
||||
/** 后台壳层允许存在的源码目录(任务 1 冻结的工作区边界,供验收脚本复用)。 */
|
||||
export const ADMIN_SOURCE_DIRS = [
|
||||
'src/layout',
|
||||
'src/router',
|
||||
'src/styles',
|
||||
'src/types',
|
||||
'src/config',
|
||||
'src/pages',
|
||||
] as const
|
||||
|
||||
export const REQUIRED_MANIFEST_FILES = [
|
||||
'package.json',
|
||||
'index.html',
|
||||
'vite.config.ts',
|
||||
'tsconfig.json',
|
||||
'src/main.ts',
|
||||
'src/App.vue',
|
||||
] as const
|
||||
|
||||
// 客户端工程耦合标记:后台工程内出现即代表越界。用带路径/产物语义的标记,
|
||||
// 避免与本工程自身包名后缀(…admin-frontend-vue)误匹配。扫描时排除本文件自身。
|
||||
export const FORBIDDEN_COUPLING_TOKENS = [
|
||||
'new_web_source',
|
||||
'frontend-vue/',
|
||||
'app_client',
|
||||
] as const
|
||||
|
||||
const SELF_SCAN_EXCLUSIONS = new Set(['src/config/workspace.ts', 'playwright.config.ts'])
|
||||
const SCAN_EXTENSIONS = /\.(ts|tsx|vue|css|html|json|js)$/
|
||||
|
||||
export function walk(rootDir: string, base = ''): string[] {
|
||||
const found: string[] = []
|
||||
for (const entry of readdirSync(join(rootDir, base), { withFileTypes: true })) {
|
||||
if (['node_modules', 'dist', '.git', 'tests', 'e2e', 'scripts', 'deploy'].includes(entry.name)) continue
|
||||
const rel = base ? `${base}/${entry.name}` : entry.name
|
||||
if (entry.isDirectory()) found.push(...walk(rootDir, rel))
|
||||
else if (SCAN_EXTENSIONS.test(entry.name)) found.push(rel)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
function fileExists(rootDir: string, path: string): boolean {
|
||||
return existsSync(join(rootDir, path))
|
||||
}
|
||||
|
||||
/** 从当前目录向上定位独立后台工程根目录,找不到时给出可操作错误。 */
|
||||
export function resolveWorkspaceRoot(cwd = process.cwd()): string {
|
||||
let dir = resolve(cwd)
|
||||
for (let i = 0; i < 6; i += 1) {
|
||||
if (fileExists(dir, 'package.json')) return dir
|
||||
const parent = resolve(dir, '..')
|
||||
if (parent === dir) break
|
||||
dir = parent
|
||||
}
|
||||
throw new Error(`在 ${cwd} 向上 6 层内找不到 package.json,请在 admin-frontend-vue 工程目录内执行`)
|
||||
}
|
||||
|
||||
export interface WorkspacePackage {
|
||||
name: string
|
||||
private: boolean
|
||||
scripts: Record<string, string>
|
||||
dependencies: Record<string, string>
|
||||
devDependencies: Record<string, string>
|
||||
}
|
||||
|
||||
export function readWorkspacePackage(rootDir = resolveWorkspaceRoot()): WorkspacePackage {
|
||||
const raw = JSON.parse(readFileSync(join(rootDir, 'package.json'), 'utf8')) as Partial<WorkspacePackage> & { private?: boolean }
|
||||
return {
|
||||
name: raw.name || '',
|
||||
private: raw.private !== false,
|
||||
scripts: raw.scripts || {},
|
||||
dependencies: raw.dependencies || {},
|
||||
devDependencies: raw.devDependencies || {},
|
||||
}
|
||||
}
|
||||
|
||||
/** 校验独立工程边界,返回违规清单(空数组 = 边界成立)。 */
|
||||
export function collectBoundaryViolations(rootDir = resolveWorkspaceRoot()): string[] {
|
||||
const violations: string[] = []
|
||||
const pkgPath = join(rootDir, 'package.json')
|
||||
const pkg: WorkspacePackage = fileExists(rootDir, 'package.json')
|
||||
? readWorkspacePackage(rootDir)
|
||||
: { name: '', private: false, scripts: {}, dependencies: {}, devDependencies: {} }
|
||||
if (!fileExists(rootDir, 'package.json')) violations.push(`缺少必需清单文件 package.json(在 ${pkgPath})`)
|
||||
|
||||
if (pkg.name !== STANDALONE_PACKAGE_NAME) {
|
||||
violations.push(`package.name 应为 ${STANDALONE_PACKAGE_NAME},实际为 ${pkg.name || '(空)'}`)
|
||||
}
|
||||
if (!pkg.private) violations.push('package.private 应为 true(后台工程不允许被外部发布依赖)')
|
||||
|
||||
for (const file of REQUIRED_MANIFEST_FILES) {
|
||||
if (!fileExists(rootDir, file)) violations.push(`缺少必需清单文件 ${file}`)
|
||||
}
|
||||
for (const dir of ADMIN_SOURCE_DIRS) {
|
||||
if (!fileExists(rootDir, dir)) violations.push(`缺少允许源码目录 ${dir}`)
|
||||
}
|
||||
|
||||
for (const file of walk(rootDir)) {
|
||||
if (SELF_SCAN_EXCLUSIONS.has(file)) continue
|
||||
const content = readFileSync(join(rootDir, file), 'utf8')
|
||||
for (const token of FORBIDDEN_COUPLING_TOKENS) {
|
||||
if (content.includes(token)) {
|
||||
violations.push(`${file} 引用了客户端耦合 token "${token}",超出后台工程边界`)
|
||||
}
|
||||
}
|
||||
}
|
||||
return violations
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { joinAdminPath } from '@/config/app'
|
||||
import { pageTitleOf, topbarUserOf } from '@/layout/topbar-model'
|
||||
import { groupKeysForActive, toSidebarEntries } from '@/layout/menu-mapper'
|
||||
import { filterMenuTreeByPlatform, visiblePlatformsFor } from '@/layout/platform-menu-filter'
|
||||
import { PLATFORM_TABS, platformsOfMenuKey } from '@/config/platform-scope'
|
||||
import { usePlatformTabStore } from '@/stores/platform-tab'
|
||||
import { firstVisiblePath } from '@/router/helpers'
|
||||
import {
|
||||
EMPTY_MENU_DESCRIPTION,
|
||||
EMPTY_MENU_TITLE,
|
||||
shouldShowEmptyMenu,
|
||||
} from '@/layout/empty-state'
|
||||
import GlobalErrorContainer from '@/layout/GlobalErrorContainer.vue'
|
||||
import NotificationBell from '@/components/NotificationBell.vue'
|
||||
import ExpiryNotice from '@/components/ExpiryNotice.vue'
|
||||
import OperationGuide from '@/layout/OperationGuide.vue'
|
||||
import CompanyTabs from '@/layout/CompanyTabs.vue'
|
||||
import { crumbsForActiveRoute, resolveDocumentTitle, updateDocumentTitle } from '@/layout/title-breadcrumb'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import {
|
||||
LOGOUT_CONFIRM_CANCEL,
|
||||
LOGOUT_CONFIRM_MESSAGE,
|
||||
LOGOUT_CONFIRM_OK,
|
||||
LOGOUT_CONFIRM_TITLE,
|
||||
runLogout,
|
||||
} from '@/layout/logout'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const session = useAdminSessionStore()
|
||||
|
||||
const activePath = computed(() => route.path)
|
||||
const platformTab = usePlatformTabStore()
|
||||
// 平台 tab(亚马逊/京东,2026-11-16「不混」定案)只做显示分组:准入仍是 session.menuTree
|
||||
// (后端按权限裁剪)+路由守卫,这里只把当前用户已被授权的菜单按平台分侧展示。
|
||||
const menuEntries = computed(() =>
|
||||
toSidebarEntries(filterMenuTreeByPlatform(session.menuTree, platformTab.active)),
|
||||
)
|
||||
const visibleTabIds = computed(() => visiblePlatformsFor(session.menuTree))
|
||||
const visibleTabDefs = computed(() => PLATFORM_TABS.filter((tab) => visibleTabIds.value.includes(tab.id)))
|
||||
const showPlatformTabs = computed(() => visibleTabIds.value.length > 1)
|
||||
const openedKeys = computed(() => groupKeysForActive(menuEntries.value, route.path))
|
||||
const emptyMenu = computed(() => shouldShowEmptyMenu(menuEntries.value.length > 0, session.loading, session.initialized))
|
||||
const pageTitle = computed(() => pageTitleOf(route.meta.title))
|
||||
const userVm = computed(() => topbarUserOf(session.user))
|
||||
const breadcrumbs = computed(() => crumbsForActiveRoute(session.menuTree, route.path))
|
||||
const logoUrl = joinAdminPath('assets', 'logo.jpg')
|
||||
|
||||
watch(
|
||||
pageTitle,
|
||||
(title) => updateDocumentTitle(resolveDocumentTitle(title), typeof document !== 'undefined' ? document : null),
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
// 直达 URL/面包屑跳到另一平台的页面时,tab 指示自动跟过去(与侧边栏保持一致)。
|
||||
// 双侧清单里的页面(账号域三页)两个 tab 都算归属:当前 tab 已含它就不动。
|
||||
watch(
|
||||
() => route.meta.menuKey as string | undefined,
|
||||
(menuKey) => {
|
||||
if (!menuKey) return
|
||||
const owners = platformsOfMenuKey(menuKey)
|
||||
if (owners.includes(platformTab.active)) return
|
||||
const target = owners.find((platform) => visibleTabIds.value.includes(platform))
|
||||
if (target && target !== platformTab.active) {
|
||||
platformTab.setActive(target)
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
// 切到另一侧 tab 时当前页多半不在那边:跳到该侧第一个可见页;该侧为空(tab 不可见)则不动。
|
||||
// 双侧清单里的页面(账号域三页)切 tab 不跳转——页面自己按当前平台过滤数据。
|
||||
watch(
|
||||
() => platformTab.active,
|
||||
(tab) => {
|
||||
const menuKey = route.meta.menuKey as string | undefined
|
||||
if (!menuKey || platformsOfMenuKey(menuKey).includes(tab)) return
|
||||
const first = firstVisiblePath(filterMenuTreeByPlatform(session.menuTree, tab))
|
||||
if (first) void router.replace(first)
|
||||
},
|
||||
)
|
||||
|
||||
async function signOut() {
|
||||
try {
|
||||
await runLogout({
|
||||
confirm: () =>
|
||||
ElMessageBox.confirm(LOGOUT_CONFIRM_MESSAGE, LOGOUT_CONFIRM_TITLE, {
|
||||
confirmButtonText: LOGOUT_CONFIRM_OK,
|
||||
cancelButtonText: LOGOUT_CONFIRM_CANCEL,
|
||||
type: 'warning',
|
||||
}).then(
|
||||
() => true,
|
||||
() => false,
|
||||
),
|
||||
signOut: () => session.signOut(),
|
||||
})
|
||||
} catch (error) {
|
||||
showAdminFeedback(error instanceof Error ? error.message : '退出登录失败', 'error')
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="admin-shell">
|
||||
<a class="skip-link" href="#admin-content">跳到主内容</a>
|
||||
<aside class="admin-sidebar" role="navigation" aria-label="侧边栏菜单">
|
||||
<div class="admin-brand">
|
||||
<img :src="logoUrl" alt="数富AI" class="admin-brand-logo" />
|
||||
<div class="admin-brand-copy">
|
||||
<strong>数富AI</strong>
|
||||
<span>电商运营管理后台</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav v-if="showPlatformTabs" class="admin-platform-tabs" role="tablist" aria-label="按平台切换菜单">
|
||||
<button
|
||||
v-for="tab in visibleTabDefs"
|
||||
:key="tab.id"
|
||||
type="button"
|
||||
role="tab"
|
||||
class="admin-platform-tab"
|
||||
:class="{ 'is-active': tab.id === platformTab.active }"
|
||||
:aria-selected="tab.id === platformTab.active"
|
||||
@click="platformTab.setActive(tab.id)"
|
||||
>{{ tab.label }}</button>
|
||||
</nav>
|
||||
|
||||
<el-scrollbar class="admin-menu-scroll">
|
||||
<el-menu :default-active="activePath" :default-openeds="openedKeys" router class="admin-menu">
|
||||
<template v-for="entry in menuEntries" :key="entry.key">
|
||||
<el-sub-menu v-if="entry.kind === 'group'" :index="entry.key">
|
||||
<template #title>
|
||||
<span class="menu-group-title">{{ entry.name }}</span>
|
||||
</template>
|
||||
<el-menu-item v-for="item in entry.children" :key="item.key" :index="item.route">
|
||||
{{ item.name }}
|
||||
</el-menu-item>
|
||||
</el-sub-menu>
|
||||
<el-menu-item v-else :key="entry.key" :index="entry.route">
|
||||
{{ entry.name }}
|
||||
</el-menu-item>
|
||||
</template>
|
||||
</el-menu>
|
||||
<el-empty v-if="emptyMenu" :description="EMPTY_MENU_TITLE" :image-size="72" />
|
||||
</el-scrollbar>
|
||||
</aside>
|
||||
|
||||
<section class="admin-main">
|
||||
<header class="admin-topbar">
|
||||
<div class="admin-topbar-title">
|
||||
<span class="admin-kicker">运营管理控制台</span>
|
||||
<h1>{{ pageTitle }}</h1>
|
||||
</div>
|
||||
<div class="admin-user">
|
||||
<NotificationBell />
|
||||
<div class="admin-user-meta">
|
||||
<strong>{{ userVm.username }}</strong>
|
||||
</div>
|
||||
<span v-if="userVm.role" class="admin-user-role">{{ userVm.role }}</span>
|
||||
<el-button class="admin-user-logout" @click="signOut">退出登录</el-button>
|
||||
</div>
|
||||
</header>
|
||||
<main id="admin-content" class="admin-content">
|
||||
<el-breadcrumb v-if="breadcrumbs.length > 1" class="admin-breadcrumb" separator="/">
|
||||
<el-breadcrumb-item v-for="crumb in breadcrumbs" :key="crumb.key">{{ crumb.name }}</el-breadcrumb-item>
|
||||
</el-breadcrumb>
|
||||
<CompanyTabs />
|
||||
<OperationGuide />
|
||||
<GlobalErrorContainer />
|
||||
<el-alert v-if="session.error" :title="session.error" type="error" show-icon :closable="false" />
|
||||
<el-empty
|
||||
v-if="emptyMenu && route.path === '/'"
|
||||
:title="EMPTY_MENU_TITLE"
|
||||
:description="EMPTY_MENU_DESCRIPTION"
|
||||
:image-size="96"
|
||||
/>
|
||||
<RouterView v-else />
|
||||
</main>
|
||||
</section>
|
||||
<ExpiryNotice />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.admin-topbar-title { min-width: 0; }
|
||||
</style>
|
||||
@@ -1,72 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/** 页面上方的公司 tab(spec §4、§9.3):只有超管看得到,而且只画在**注册表里真的按公司取数的那些页**上——
|
||||
* 选中哪家由哪一枚 tab 带 is-active 表达,这里不再挂第二处"这家是谁"的文案(§12 第 5 条把页头提示条算未批的界面暴露),
|
||||
* 提示条只讲这一页怎么办,不讲 tab(2026-10-14 公司观感那句已从引导文案撤掉,见 operation-guides 文件头)。 */
|
||||
import { computed, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { COMPANY_STATUS_ACTIVE } from '@/api/companies-dto'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { companyTabAppliesTo, companyTabInitFailureMessage } from '@/layout/company-tab-model'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
|
||||
const route = useRoute()
|
||||
const tab = useCompanyTabStore()
|
||||
const session = useAdminSessionStore()
|
||||
const tabs = computed(() => tab.companies.filter((c) => c.status === COMPANY_STATUS_ACTIVE))
|
||||
const show = computed(() => tab.visibleForOperator && companyTabAppliesTo(route.meta.menuKey))
|
||||
|
||||
watch(() => session.isSuperAdmin, (v) => {
|
||||
if (!v) return
|
||||
// 2026-10-05 修复轮 1:改前这里是 `void tab.initialize()`,store 里也只有 try/finally ⇒
|
||||
// GET /companies 抛错时异常变成 unhandled rejection(全仓 src 无 errorHandler/unhandledrejection 兜底),
|
||||
// 现场只剩"tab 条没画出来",Task 13 人工清单第一项无从判断是权限问题还是接口挂了。
|
||||
// 取不到目录 ⇒ fail-closed 不画 tab 条:store 不翻转 loaded,visibleForOperator 仍为 false,观感与改前一致。
|
||||
// store 照 admin-session.ts:37-39 的口径 catch 出 error 之后仍然 rethrow,所以这一侧必须 .catch 接住。
|
||||
// 模板里仍不长出任何新的常驻文字/提示条/图标(§12 第 5 条未批的暴露),但失败不许只剩 console.warn:
|
||||
// 文案由 company-tab-model 出,可见出口统一走 admin-feedback-ui 的 showAdminFeedback(一次性提示)。
|
||||
tab.initialize().catch((error: unknown) => {
|
||||
console.warn('[company-tab] 公司目录没取到,tab 条不渲染', error)
|
||||
showAdminFeedback(companyTabInitFailureMessage(error), 'warning')
|
||||
})
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="show" class="company-tabs" role="tablist" aria-label="按公司查看数据">
|
||||
<button
|
||||
v-for="item in tabs"
|
||||
:key="item.id"
|
||||
type="button"
|
||||
role="tab"
|
||||
class="company-tab"
|
||||
:class="{ 'is-active': item.id === tab.activeId }"
|
||||
:aria-selected="item.id === tab.activeId"
|
||||
@click="tab.setActiveId(item.id)"
|
||||
>{{ item.companyName }}</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 只给上面那几枚 tab 上样式:tab 条本身不产出任何文字节点,公司名一律来自 item.companyName。 */
|
||||
.company-tabs {
|
||||
display: flex; flex-wrap: wrap; align-items: flex-end; gap: 4px;
|
||||
margin: 0 0 14px; padding: 0 2px;
|
||||
border-bottom: 1px solid var(--admin-border);
|
||||
}
|
||||
.company-tab {
|
||||
padding: 6px 16px;
|
||||
border: 1px solid transparent; border-bottom: 0;
|
||||
border-radius: 10px 10px 0 0;
|
||||
background: none; cursor: pointer;
|
||||
font: inherit; font-size: 13px; line-height: 1.7;
|
||||
color: var(--admin-sidebar-text);
|
||||
}
|
||||
.company-tab:hover { color: var(--admin-primary-strong); background: var(--admin-primary-soft); }
|
||||
.company-tab.is-active {
|
||||
border-color: var(--admin-border);
|
||||
background: #fff;
|
||||
color: var(--admin-primary-strong); font-weight: 650;
|
||||
box-shadow: inset 0 -2px 0 var(--admin-primary);
|
||||
}
|
||||
</style>
|
||||
@@ -1,35 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import {
|
||||
dismissGlobalError,
|
||||
subscribeGlobalError,
|
||||
type GlobalErrorItem,
|
||||
} from '@/layout/error-bus'
|
||||
|
||||
const errors = ref<GlobalErrorItem[]>([])
|
||||
let unsubscribe: (() => void) | null = null
|
||||
|
||||
onMounted(() => {
|
||||
unsubscribe = subscribeGlobalError((list) => {
|
||||
errors.value = list
|
||||
})
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
unsubscribe?.()
|
||||
unsubscribe = null
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="errors.length" class="global-error-stack" role="alert" aria-live="assertive">
|
||||
<el-alert
|
||||
v-for="item in errors"
|
||||
:key="item.id"
|
||||
:title="item.message"
|
||||
type="error"
|
||||
show-icon
|
||||
:closable="true"
|
||||
@close="dismissGlobalError(item.id)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,85 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/** 当前页面操作提示条:对齐旧版 admin-interactions.js 的 adminOperationGuide。每页文案逐条登记在
|
||||
* OPERATION_GUIDES 里,条数**不在这里数**(写死一个页数就会过期:公司 tab 那批把 group-manage 从
|
||||
* 通用 fallback 改成自带文案时,上一版注释里的数字就已经是错的了)——分母由 align-operation-guide
|
||||
* 那组用例按路由注册表钉着。
|
||||
* 挂在 AdminLayout 内容区顶部,随 route.meta.menuKey 切换文案;折叠态存 localStorage。 */
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { OPERATION_GUIDE_STORAGE_KEY, operationGuideFor } from '@/layout/operation-guides'
|
||||
|
||||
const route = useRoute()
|
||||
const guide = computed(() => operationGuideFor(route.meta.menuKey))
|
||||
|
||||
function readCollapsed(): boolean {
|
||||
try {
|
||||
return localStorage.getItem(OPERATION_GUIDE_STORAGE_KEY) === '1'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
function persistCollapsed(value: boolean) {
|
||||
try {
|
||||
localStorage.setItem(OPERATION_GUIDE_STORAGE_KEY, value ? '1' : '0')
|
||||
} catch {
|
||||
// 忽略隐私模式写入失败
|
||||
}
|
||||
}
|
||||
const collapsed = ref(readCollapsed())
|
||||
function toggle() {
|
||||
collapsed.value = !collapsed.value
|
||||
persistCollapsed(collapsed.value)
|
||||
}
|
||||
watch(collapsed, (v) => persistCollapsed(v))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside v-if="guide" class="operation-guide" :class="{ 'is-collapsed': collapsed }" aria-label="当前页面操作提示">
|
||||
<div class="og-head">
|
||||
<span class="og-title">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"></circle><path d="M12 11v5"></path><path d="M12 8h.01"></path></svg>
|
||||
当前页面操作提示
|
||||
</span>
|
||||
<button type="button" class="og-toggle" :aria-expanded="!collapsed" @click="toggle">
|
||||
{{ collapsed ? '展开提示' : '收起提示' }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-show="!collapsed" class="og-body">
|
||||
<p class="og-text">{{ guide.text }}</p>
|
||||
<ol v-if="guide.steps.length" class="og-steps">
|
||||
<li v-for="step in guide.steps" :key="step">{{ step }}</li>
|
||||
</ol>
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.operation-guide {
|
||||
display: flex; flex-direction: column;
|
||||
margin: 0 0 18px; padding: 12px 16px;
|
||||
border: 1px solid #cddbe6; border-radius: 12px;
|
||||
background: linear-gradient(180deg, #fbfdfe, #f4f8fc);
|
||||
box-shadow: 0 10px 26px -24px rgba(39, 67, 94, 0.3);
|
||||
color: var(--admin-text);
|
||||
}
|
||||
.operation-guide.is-collapsed { padding: 8px 16px; }
|
||||
.og-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.og-title {
|
||||
display: inline-flex; align-items: center; gap: 7px;
|
||||
font-size: 13px; font-weight: 650; color: var(--admin-primary-strong);
|
||||
}
|
||||
.og-title svg { width: 15px; height: 15px; }
|
||||
.og-toggle {
|
||||
padding: 0; border: 0; background: none; cursor: pointer;
|
||||
font: inherit; font-size: 12px; color: #6b8096;
|
||||
}
|
||||
.og-toggle:hover { color: var(--admin-primary-strong); }
|
||||
.og-body { margin-top: 8px; padding-left: 22px; }
|
||||
.og-text { margin: 0; color: #40586e; font-size: 13px; line-height: 1.7; }
|
||||
.og-steps { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 0; padding: 0; list-style: none; }
|
||||
.og-steps li {
|
||||
padding: 2px 10px; border-radius: 999px;
|
||||
background: #e9f1f8; border: 1px solid #d3e0ea;
|
||||
color: #2f4a63; font-size: 12px; line-height: 1.7;
|
||||
}
|
||||
</style>
|
||||
@@ -1,45 +0,0 @@
|
||||
/** 公司 tab 的三支纯函数(store 与护栏用例共用,不依赖 pinia / 组件)。
|
||||
* import 用相对路径 + 显式 `.ts`:本文件被 tests 以 `node --test` 直接 import,而测试侧没有
|
||||
* vite 的 `@` 别名解析器,写成 `@/api/...` 会 ERR_MODULE_NOT_FOUND(护栏因此读源码而非常规 import,
|
||||
* 见 tests/company-tab-wiring.test.ts 用 readSource 的原因)。 */
|
||||
import { COMPANY_STATUS_ACTIVE, type CompanyItem } from '../api/companies-dto.ts'
|
||||
import { COMPANY_SCOPED_PAGES } from '../config/company-scope.ts'
|
||||
|
||||
/** 参与公司隔离的页(注册表那份 menuKey 的集合形态)。判据**只有这一份来源**:
|
||||
* 另立一张"哪些页不画 tab"的黑名单,下一个新页会默认长出一条点了没反应的 tab(2026-10-06 的成因)。 */
|
||||
const SCOPED_MENU_KEYS: ReadonlySet<string> = new Set(COMPANY_SCOPED_PAGES.map((page) => page.menuKey))
|
||||
|
||||
/**
|
||||
* 这一页切了公司**有没有用**。与 store 的 `visibleForOperator` 是两个正交问题,不是同一问的两把尺子:
|
||||
* 那一条答「目录取到了吗、这名下有几家可切」,这一条答「当前这页吃不吃公司维度」。
|
||||
* 壳层把 tab 挂在所有页上时,公司管理页头顶就压着一排点了不重取数的 tab(控制方 2026-10-06 点名)。
|
||||
*/
|
||||
export function companyTabAppliesTo(menuKey: unknown): boolean {
|
||||
return typeof menuKey === 'string' && SCOPED_MENU_KEYS.has(menuKey)
|
||||
}
|
||||
|
||||
/** 超管的读范围公司。非超管恒 null——它的公司是固定的,下传一个常数只会让人以为这页在按公司筛。 */
|
||||
export function companyIdForRequest(isSuperAdmin: boolean, activeId: number | null): number | null {
|
||||
return isSuperAdmin ? activeId : null
|
||||
}
|
||||
|
||||
/**
|
||||
* 公司目录没取到时的可见文案(四面9分口径 §2 后管「错误静默」)。
|
||||
*
|
||||
* <p>改前 CompanyTabs.vue 的 `.catch` 只 console.warn,现场只剩「tab 条没画出来」,
|
||||
* 判断不了是权限问题还是接口挂了。文案住在这里(不引组件、不引 element-plus),
|
||||
* 可见出口由组件用 admin-feedback-ui 的 showAdminFeedback 承接;tab 条模板本身仍不产出
|
||||
* 任何文字节点(§12 第 5 条那处未批的页头暴露没被绕过——这是一次性提示,不是常驻文案)。</p>
|
||||
*/
|
||||
export function companyTabInitFailureMessage(error: unknown): string {
|
||||
const base = '公司目录没取到,公司切换条暂不可用'
|
||||
const reason = error instanceof Error ? error.message.trim() : String(error ?? '').trim()
|
||||
return reason ? `${base}:${reason}` : base
|
||||
}
|
||||
|
||||
/** 「默认选中第一家」= id 最小的启用公司(spec §4 口径:不是超管自己所属公司,也不是返回顺序首条)。 */
|
||||
export function firstSelectableCompanyId(companies: readonly CompanyItem[]): number | null {
|
||||
const active = companies.filter((c) => c.status === COMPANY_STATUS_ACTIVE && c.id > 0)
|
||||
if (!active.length) return null
|
||||
return active.reduce((min, c) => (c.id < min ? c.id : min), active[0].id)
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
/** 无菜单权限空状态(任务 11)文案与判定。 */
|
||||
export const EMPTY_MENU_TITLE = '暂无可用菜单'
|
||||
export const EMPTY_MENU_DESCRIPTION = '请联系管理员为你的账号分配菜单权限'
|
||||
|
||||
/**
|
||||
* 是否展示无菜单空态:会话已初始化、未在加载、且没有任何可渲染菜单。
|
||||
* 加载中不闪空态;初始化失败由错误条提示而非空态。
|
||||
*/
|
||||
export function shouldShowEmptyMenu(hasMenus: boolean, loading: boolean, initialized: boolean): boolean {
|
||||
return Boolean(initialized) && !loading && !hasMenus
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
/** 全局请求错误提示容器(任务 13):框架无关的订阅式错误总线。 */
|
||||
|
||||
export interface GlobalErrorItem {
|
||||
id: number
|
||||
message: string
|
||||
}
|
||||
|
||||
export const GLOBAL_ERROR_LIMIT = 3
|
||||
export const GLOBAL_ERROR_FALLBACK = '请求失败,请稍后重试'
|
||||
|
||||
/** 把任意负载归一化为可展示文案。 */
|
||||
export function normalizeErrorMessage(message: unknown): string {
|
||||
if (message instanceof Error) return message.message.trim() || GLOBAL_ERROR_FALLBACK
|
||||
if (typeof message === 'string') return message.trim() || GLOBAL_ERROR_FALLBACK
|
||||
return GLOBAL_ERROR_FALLBACK
|
||||
}
|
||||
|
||||
type Listener = (items: GlobalErrorItem[]) => void
|
||||
|
||||
let items: GlobalErrorItem[] = []
|
||||
let nextId = 1
|
||||
const listeners = new Set<Listener>()
|
||||
|
||||
function emit(): void {
|
||||
for (const listener of listeners) listener(items.slice())
|
||||
}
|
||||
|
||||
/** 订阅错误流,返回取消订阅函数(组件卸载时必须调用以防泄漏)。 */
|
||||
export function subscribeGlobalError(listener: Listener): () => void {
|
||||
listeners.add(listener)
|
||||
listener(items.slice())
|
||||
return () => {
|
||||
listeners.delete(listener)
|
||||
}
|
||||
}
|
||||
|
||||
/** 通知一条全局请求错误;超出上限丢弃最旧,保证不堆积。 */
|
||||
export function notifyGlobalError(message: unknown): void {
|
||||
items = [...items, { id: nextId++, message: normalizeErrorMessage(message) }].slice(-GLOBAL_ERROR_LIMIT)
|
||||
emit()
|
||||
}
|
||||
|
||||
/** 按 id 关闭单条。 */
|
||||
export function dismissGlobalError(id: number): void {
|
||||
items = items.filter((item) => item.id !== id)
|
||||
emit()
|
||||
}
|
||||
|
||||
export function clearGlobalErrors(): void {
|
||||
items = []
|
||||
emit()
|
||||
}
|
||||
|
||||
export function snapshotGlobalErrors(): GlobalErrorItem[] {
|
||||
return items.slice()
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
/** 壳层退出登录交互(任务 16):确认后执行,取消/拒绝一律不退出。 */
|
||||
|
||||
export const LOGOUT_CONFIRM_TITLE = '退出登录'
|
||||
export const LOGOUT_CONFIRM_MESSAGE = '确定要退出当前账号吗?'
|
||||
export const LOGOUT_CONFIRM_OK = '退出'
|
||||
export const LOGOUT_CONFIRM_CANCEL = '取消'
|
||||
|
||||
export interface LogoutDeps {
|
||||
/** 用户确认对话框,resolve true 表示确认退出。 */
|
||||
confirm: () => Promise<boolean>
|
||||
/** 真正执行退出(清状态 + 跳登录页)。 */
|
||||
signOut: () => Promise<void>
|
||||
}
|
||||
|
||||
/** 退出流程:先确认;确认后执行退出;signOut/confirm 异常向上抛由调用方反馈。 */
|
||||
export async function runLogout({ confirm, signOut }: LogoutDeps): Promise<void> {
|
||||
const proceed = await confirm()
|
||||
if (!proceed) return
|
||||
await signOut()
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import type { AdminMenuNode } from '../types/admin'
|
||||
|
||||
export interface SidebarItem {
|
||||
key: string
|
||||
name: string
|
||||
route: string
|
||||
}
|
||||
|
||||
/** 侧边栏渲染项:分组(含子页面)或单页面项(含顶级路由叶节点)。 */
|
||||
export type SidebarEntry =
|
||||
| { kind: 'group'; key: string; name: string; children: SidebarItem[] }
|
||||
| { kind: 'item'; key: string; name: string; route: string }
|
||||
|
||||
/**
|
||||
* 后端菜单树 -> 侧边栏节点映射规则(任务 6):
|
||||
* - 有可路由子节点的节点渲染为分组,只保留带 route 的子项;
|
||||
* - 无子节点但有 route 的节点渲染为单页面项(不丢顶级叶菜单);
|
||||
* - 既无子节点也无 route 的节点跳过(点不进去的纯占位不展示)。
|
||||
*/
|
||||
export function toSidebarEntries(nodes: AdminMenuNode[] | null | undefined): SidebarEntry[] {
|
||||
const entries: SidebarEntry[] = []
|
||||
for (const node of nodes || []) {
|
||||
const name = node.name || ''
|
||||
const key = node.key || ''
|
||||
const children: SidebarItem[] = (node.children || [])
|
||||
.filter((child): child is AdminMenuNode & { route: string } => Boolean(child.route))
|
||||
.map((child) => ({ key: child.key || '', name: child.name || '', route: child.route }))
|
||||
if (children.length > 0) {
|
||||
entries.push({ kind: 'group', key, name, children })
|
||||
} else if (node.route) {
|
||||
entries.push({ kind: 'item', key, name, route: node.route })
|
||||
}
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
/** 计算需默认展开的分组 key:分组下含当前激活路由子项时返回该分组 key。 */
|
||||
export function groupKeysForActive(entries: SidebarEntry[], activeRoute: string): string[] {
|
||||
const keys: string[] = []
|
||||
for (const entry of entries) {
|
||||
if (entry.kind === 'group' && entry.children.some((child) => child.route === activeRoute)) {
|
||||
keys.push(entry.key)
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
@@ -1,222 +0,0 @@
|
||||
/**
|
||||
* 后台铃铛通知纯逻辑:未读徽标文案、新通知判定、「已提醒过」去重记录、时间展示。
|
||||
* 轮询调度与渲染在 NotificationBell.vue;这里只放可单测的纯函数与存储读写。
|
||||
*/
|
||||
|
||||
/** 未读轮询间隔(60 秒)。 */
|
||||
export const NOTIFICATION_POLL_INTERVAL_MS = 60_000
|
||||
|
||||
const NOTIFIED_KEY_PREFIX = 'admin-notification:last-notified-id'
|
||||
|
||||
/** 未读徽标文案:0 或非法值显示空串,>99 显示 99+。 */
|
||||
export function formatUnreadBadge(count: number | null | undefined): string {
|
||||
const value = Number(count ?? 0)
|
||||
if (!Number.isFinite(value) || value <= 0) {
|
||||
return ''
|
||||
}
|
||||
return value > 99 ? '99+' : String(Math.floor(value))
|
||||
}
|
||||
|
||||
/** 是否出现新通知:latestId 大于上次已提醒过的 id。 */
|
||||
export function hasNewNotification(
|
||||
latestId: number | null | undefined,
|
||||
lastNotifiedId: number | null | undefined,
|
||||
): boolean {
|
||||
const latest = Number(latestId ?? 0)
|
||||
const notified = Number(lastNotifiedId ?? 0)
|
||||
if (!Number.isFinite(latest) || latest <= 0) {
|
||||
return false
|
||||
}
|
||||
return latest > (Number.isFinite(notified) && notified > 0 ? notified : 0)
|
||||
}
|
||||
|
||||
function storageKey(uid: string | number | null | undefined): string {
|
||||
const normalized = uid === null || uid === undefined || String(uid).trim() === '' ? '0' : String(uid)
|
||||
return `${NOTIFIED_KEY_PREFIX}:${normalized}`
|
||||
}
|
||||
|
||||
/** 读取当前管理员「已提醒过的最大通知 id」。 */
|
||||
export function readLastNotifiedId(uid: string | number | null | undefined): number {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(storageKey(uid))
|
||||
const value = Number(raw ?? 0)
|
||||
return Number.isFinite(value) && value > 0 ? value : 0
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
export function writeLastNotifiedId(uid: string | number | null | undefined, id: number): void {
|
||||
try {
|
||||
if (Number.isFinite(id) && id > 0) {
|
||||
window.localStorage.setItem(storageKey(uid), String(Math.floor(id)))
|
||||
}
|
||||
} catch {
|
||||
/* 存储不可用时静默忽略(退化为每次都提醒,不影响功能) */
|
||||
}
|
||||
}
|
||||
|
||||
/** 通知所属日期键(本地时区 yyyy-MM-dd);时间缺失/非法返回空串。 */
|
||||
export function notificationDayKey(value: string | null | undefined): string {
|
||||
if (!value) {
|
||||
return ''
|
||||
}
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return ''
|
||||
}
|
||||
const pad = (input: number) => String(input).padStart(2, '0')
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
|
||||
}
|
||||
|
||||
/** 日期组头文案:今天 / 昨天 / 2026年9月11日;空键兜底「未知时间」。 */
|
||||
export function formatDayLabel(day: string, now: Date = new Date()): string {
|
||||
if (!day) {
|
||||
return '未知时间'
|
||||
}
|
||||
if (day === notificationDayKey(now.toISOString())) {
|
||||
return '今天'
|
||||
}
|
||||
const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)
|
||||
if (day === notificationDayKey(yesterday.toISOString())) {
|
||||
return '昨天'
|
||||
}
|
||||
const [year, month, date] = day.split('-').map((part) => Number(part))
|
||||
if (!Number.isFinite(year) || !Number.isFinite(month) || !Number.isFinite(date)) {
|
||||
return day
|
||||
}
|
||||
return `${year}年${month}月${date}日`
|
||||
}
|
||||
|
||||
/** 通知时间展示:今天只显示 HH:mm;昨天显示「昨天 HH:mm」;更早显示 MM-DD HH:mm。 */
|
||||
export function formatNotificationTime(
|
||||
value: string | null | undefined,
|
||||
now: Date = new Date(),
|
||||
): string {
|
||||
if (!value) {
|
||||
return ''
|
||||
}
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return ''
|
||||
}
|
||||
const pad = (input: number) => String(input).padStart(2, '0')
|
||||
const hourMinute = `${pad(date.getHours())}:${pad(date.getMinutes())}`
|
||||
const sameDay =
|
||||
date.getFullYear() === now.getFullYear() &&
|
||||
date.getMonth() === now.getMonth() &&
|
||||
date.getDate() === now.getDate()
|
||||
if (sameDay) {
|
||||
return hourMinute
|
||||
}
|
||||
const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)
|
||||
const isYesterday =
|
||||
date.getFullYear() === yesterday.getFullYear() &&
|
||||
date.getMonth() === yesterday.getMonth() &&
|
||||
date.getDate() === yesterday.getDate()
|
||||
if (isYesterday) {
|
||||
return `昨天 ${hourMinute}`
|
||||
}
|
||||
return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${hourMinute}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚合组的稳定键:场景 × 自然日 × 事件主体用户,与后端的分组键逐字对应。
|
||||
* 主体为空(存量未标注那一组)要参与拼键,否则两组不同主体的组会撞成同一个 key,
|
||||
* 展开态就会串台——点开 A 组、展开的却是 B 组。
|
||||
*/
|
||||
export function notificationGroupKey(group: {
|
||||
scene?: string | null
|
||||
day?: string | null
|
||||
subjectUserId?: number | string | null
|
||||
}): string {
|
||||
const subject =
|
||||
group.subjectUserId === null || group.subjectUserId === undefined ? 'none' : String(group.subjectUserId)
|
||||
return `${group.scene ?? ''}|${group.day ?? ''}|${subject}`
|
||||
}
|
||||
|
||||
/** 组行上的计数徽语:折叠前有几条、其中几条没读。只报一个数就会被读成"一共就这些通知"。 */
|
||||
export function formatGroupCounts(rowCount: number | null | undefined, unreadCount: number | null | undefined): string {
|
||||
const total = Number(rowCount ?? 0)
|
||||
const unread = Number(unreadCount ?? 0)
|
||||
return unread > 0 ? `${total} 条 · ${unread} 未读` : `${total} 条`
|
||||
}
|
||||
|
||||
/**
|
||||
* 失败反馈的文案与「同场故障只提示一次」的闸门(四面9分口径 §2 后管「错误静默」)。
|
||||
*
|
||||
* <p>改前 NotificationBell.vue 的两处 catch 只 console.warn:未读数接口挂了红点静默消失、
|
||||
* 点通知标已读失败界面纹丝不动,使用者无从判断是"没有通知"还是"接口没通"(全仓 src 无
|
||||
* errorHandler/unhandledrejection 兜底)。文案在这里出、可见出口由组件注入
|
||||
* ({@code showAdminFeedback}),模型层不引 element-plus ⇒ 这一族判据能用 node --test 直接跑真函数,
|
||||
* 不必退化成读源码的钉子。</p>
|
||||
*/
|
||||
export type BellFeedbackKind = 'success' | 'error' | 'warning'
|
||||
|
||||
/** 可见提示的出口:组件把 admin-feedback-ui 的 showAdminFeedback 递进来。 */
|
||||
export type BellFeedbackSink = (message: string, kind: BellFeedbackKind) => void
|
||||
|
||||
function failureReason(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message.trim()
|
||||
}
|
||||
return String(error ?? '').trim()
|
||||
}
|
||||
|
||||
/** 未读数刷新失败的提示文案:带上原因,便于区分"接口挂了"与"没权限"。 */
|
||||
export function summaryFailureMessage(error: unknown): string {
|
||||
const reason = failureReason(error)
|
||||
return reason ? `通知未读数刷新失败:${reason}` : '通知未读数刷新失败'
|
||||
}
|
||||
|
||||
/** 标记已读失败的提示文案:点了必须有回应,失败也要有回应。 */
|
||||
export function markReadFailureMessage(error: unknown): string {
|
||||
const reason = failureReason(error)
|
||||
return reason ? `这条通知没能标记为已读:${reason}` : '这条通知没能标记为已读'
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮询失败的提示闸门:一轮 60s,同一场故障只提示一次,成功一轮后重新武装。
|
||||
* 不设闸等于把「静默失败」换成「每分钟打扰一次」,两个都是错的口径。
|
||||
*/
|
||||
export function createSummaryFailureAlerter(feedback: BellFeedbackSink): {
|
||||
reportFailure(error: unknown): void
|
||||
reportSuccess(): void
|
||||
isArmed(): boolean
|
||||
} {
|
||||
let alerted = false
|
||||
return {
|
||||
reportFailure(error: unknown): void {
|
||||
if (alerted) {
|
||||
return
|
||||
}
|
||||
alerted = true
|
||||
feedback(summaryFailureMessage(error), 'warning')
|
||||
},
|
||||
reportSuccess(): void {
|
||||
alerted = false
|
||||
},
|
||||
isArmed(): boolean {
|
||||
return alerted
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** 通知锚点的最小形状(与 AdminNotificationRef 对齐);不 import api 类型,保持本模块可被 node --test 直接跑。 */
|
||||
export interface NotificationTaskRef {
|
||||
taskNo?: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务锚点 → 任务中心深链。taskNo 是任务详情接口的唯一入参,空值不给链接
|
||||
* (宁可只显示文本,也不跳到一个必然查不到的任务上)。
|
||||
*/
|
||||
export function taskCenterRouteForRef(
|
||||
ref: NotificationTaskRef | null | undefined,
|
||||
): { path: string; query: { taskNo: string } } | null {
|
||||
const taskNo = String(ref?.taskNo ?? '').trim()
|
||||
if (!taskNo) {
|
||||
return null
|
||||
}
|
||||
return { path: '/task-center/board', query: { taskNo } }
|
||||
}
|
||||
@@ -1,420 +0,0 @@
|
||||
/**
|
||||
* 铃铛面板的状态机(10-13 通知聚合改造从 NotificationBell.vue 拆出)。
|
||||
*
|
||||
* 为什么单独一层:聚合两级(组行 ⇄ 明细行)带来 14 个 ref 与一整条数据流,
|
||||
* 全塞进 SFC 后组件 877 行,撞上可读棘轮 800 行上限。拆出来同时解决另一件事——
|
||||
* 组件在本面只能用 readSource 钉形状(`npm test` 那把尺子),而这一层是真函数,
|
||||
* 能被 node --test 直接跑:红点按组数、组内没读完不许掉、下钻三维、换页清展开态
|
||||
* 这些判据从此判的是行为,不是源码里有没有那行字。
|
||||
*
|
||||
* 组件只留 DOM 相关的那一半:面板开合、fixed 定位、外部点击关闭、60s 轮询定时器。
|
||||
*/
|
||||
import { computed, onUnmounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
import {
|
||||
ADMIN_NOTIFICATION_SEVERITY_LABELS,
|
||||
fetchNotificationGroups,
|
||||
fetchNotificationList,
|
||||
fetchNotificationSummary,
|
||||
markAllNotificationsRead,
|
||||
markNotificationRead,
|
||||
type AdminNotificationGroup,
|
||||
type AdminNotificationItem,
|
||||
type AdminNotificationSeverity,
|
||||
type AdminNotificationSortMode,
|
||||
} from '@/api/notifications'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import {
|
||||
createSummaryFailureAlerter,
|
||||
formatUnreadBadge,
|
||||
hasNewNotification,
|
||||
markReadFailureMessage,
|
||||
notificationGroupKey,
|
||||
readLastNotifiedId,
|
||||
writeLastNotifiedId,
|
||||
} from '@/layout/notification-bell-model'
|
||||
|
||||
/** 聚合行比单条高(多一行计数与展开入口),一页 6 组刚好是面板的高度量级。 */
|
||||
export const PANEL_PAGE_SIZE = 6
|
||||
/** 展开一组时列出的明细上限:一组最多可能有几百条,全塞进 DOM 会把面板撑到不可滚动。 */
|
||||
export const PANEL_DETAIL_LIMIT = 50
|
||||
|
||||
/** 关键字输入的防抖:每敲一个字都打一次接口没必要。 */
|
||||
const KEYWORD_DEBOUNCE_MS = 300
|
||||
|
||||
type Uid = number | string
|
||||
|
||||
export interface NotificationPanelOptions {
|
||||
/** 当前管理员 id:已提醒水位按人存,不能按机器存。 */
|
||||
uid: () => Uid
|
||||
/** 「今天」由组件供给:日期控件长在组件上,
|
||||
* 「凡渲染日期筛选的页必须自己接默认值」那把尺子(date-filter-default-today)只走 .vue,
|
||||
* 初值搬进这一层就等于从尺子的视野里消失。 */
|
||||
today: () => string
|
||||
}
|
||||
|
||||
/** 起止日期倒挂时自动交换,避免用户只看到「没有符合条件的通知」不知原因。 */
|
||||
export function normalizedDayRange(startDate: string, endDate: string): { startDate?: string; endDate?: string } {
|
||||
let start = startDate
|
||||
let end = endDate
|
||||
if (start && end && start > end) {
|
||||
const swapped = start
|
||||
start = end
|
||||
end = swapped
|
||||
}
|
||||
return { startDate: start || undefined, endDate: end || undefined }
|
||||
}
|
||||
|
||||
/** 下钻条件:三维缺一维就会把别的主体的行混进这一组的明细(同场景同一天有好几组)。 */
|
||||
export function detailQueryFor(
|
||||
group: AdminNotificationGroup,
|
||||
sort: AdminNotificationSortMode = 'severity',
|
||||
) {
|
||||
return {
|
||||
page: 1,
|
||||
pageSize: PANEL_DETAIL_LIMIT,
|
||||
sort,
|
||||
scene: group.scene,
|
||||
day: group.day,
|
||||
subjectUserId: group.subjectUserId,
|
||||
subjectUnlabelled: group.subjectUserId === null || group.subjectUserId === undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/** 读完一条后重算两个计数:组内未读清零,红点(按组数)才掉那一格。 */
|
||||
export function applyMarkReadToCounts(
|
||||
groups: AdminNotificationGroup[],
|
||||
expandedKey: string,
|
||||
unreadCount: number,
|
||||
unreadGroupCount: number,
|
||||
): { unreadCount: number; unreadGroupCount: number } {
|
||||
const owner = groups.find((group) => notificationGroupKey(group) === expandedKey)
|
||||
if (owner && owner.unreadCount > 0) {
|
||||
owner.unreadCount -= 1
|
||||
if (owner.unreadCount === 0) {
|
||||
return { unreadCount: Math.max(0, unreadCount - 1), unreadGroupCount: Math.max(0, unreadGroupCount - 1) }
|
||||
}
|
||||
}
|
||||
return { unreadCount: Math.max(0, unreadCount - 1), unreadGroupCount }
|
||||
}
|
||||
|
||||
/** 聚合页返回:组数与明细条数两个数都要留,只给一个就会被读成「一共就这些通知」。 */
|
||||
export function applyGroupsPage(result: Awaited<ReturnType<typeof fetchNotificationGroups>>, fallback: {
|
||||
unreadCount: number
|
||||
unreadGroupCount: number
|
||||
}) {
|
||||
const list = Array.isArray(result?.groups) ? result.groups : []
|
||||
return {
|
||||
groups: list,
|
||||
total: Number(result?.total ?? list.length),
|
||||
rowCount: Number(result?.rowCount ?? list.length),
|
||||
unreadCount: Number(result?.unreadCount ?? fallback.unreadCount),
|
||||
unreadGroupCount: Number(result?.unreadGroupCount ?? fallback.unreadGroupCount),
|
||||
}
|
||||
}
|
||||
|
||||
/** 无筛选的首页就是最新数据,顺带把「已提醒过的最大 id」推上去;有筛选时最新 id 不代表真实最新。 */
|
||||
export function latestIdWorthRecording(list: AdminNotificationGroup[]): number {
|
||||
if (!list.length) return 0
|
||||
const latest = Number(list[0].latestId)
|
||||
return latest > 0 ? latest : 0
|
||||
}
|
||||
|
||||
/** 日期头只在"与上一组不是同一天"时出现:同一天可能有多个组(多个用户/多个场景)。 */
|
||||
export function startsNewDay(groups: AdminNotificationGroup[], index: number): boolean {
|
||||
if (index === 0) return true
|
||||
return groups[index - 1]?.day !== groups[index]?.day
|
||||
}
|
||||
|
||||
/** 级别:聚合行与明细行共用同一条规则,否则同一件事在两处颜色不一样。 */
|
||||
export function itemLevel(item: { level: string }): 'error' | 'warning' | 'info' {
|
||||
return item.level === 'error' || item.level === 'info' ? item.level : 'warning'
|
||||
}
|
||||
|
||||
/** 严重度兜底:新后端直接给 severity;旧后端没这列时按 level 推,绝不让标签空白。 */
|
||||
export function itemSeverity(item: {
|
||||
severity?: string | null
|
||||
level?: string | null
|
||||
}): AdminNotificationSeverity {
|
||||
const value = item.severity
|
||||
if (value === 'urgent' || value === 'high' || value === 'medium' || value === 'low') {
|
||||
return value
|
||||
}
|
||||
if (item.level === 'error') return 'urgent'
|
||||
if (item.level === 'info') return 'low'
|
||||
return 'high'
|
||||
}
|
||||
|
||||
export function severityLabel(item: { severity?: string | null; level?: string | null }): string {
|
||||
return ADMIN_NOTIFICATION_SEVERITY_LABELS[itemSeverity(item)]
|
||||
}
|
||||
|
||||
export function useNotificationBellPanel(options: NotificationPanelOptions) {
|
||||
const uid = options.uid
|
||||
const today = options.today
|
||||
|
||||
const unreadCount = ref(0)
|
||||
const unreadGroupCount = ref(0)
|
||||
const groups = ref<AdminNotificationGroup[]>([])
|
||||
const total = ref(0)
|
||||
const rowCount = ref(0)
|
||||
const page = ref(1)
|
||||
const loading = ref(false)
|
||||
const markingAll = ref(false)
|
||||
const loadError = ref('')
|
||||
const keyword = ref('')
|
||||
const startDate = ref(today())
|
||||
const endDate = ref(today())
|
||||
/** 默认按严重度;可切「按时间」。 */
|
||||
const sortMode = ref<AdminNotificationSortMode>('severity')
|
||||
const expandedKey = ref('')
|
||||
const details = ref<AdminNotificationItem[]>([])
|
||||
const detailTotal = ref(0)
|
||||
const detailLoading = ref(false)
|
||||
|
||||
/** 徽标按**组数**亮:同类事件一天刷几十条不该把红点做成计数器;后端没给这个字段时退回条数。 */
|
||||
const badgeText = computed(() => formatUnreadBadge(unreadGroupCount.value || unreadCount.value))
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / PANEL_PAGE_SIZE)))
|
||||
/** 日期恒为「当天」是默认视图、不算主动筛选:若计入,「无筛选才记录已提醒 id」的分支会永久失效。 */
|
||||
const hasFilter = computed(() => Boolean(keyword.value.trim()))
|
||||
/** el-date-picker 的绑定桥:内部仍用 startDate/endDate 两个 ref,模板 v-model 走这一层。 */
|
||||
const dateRangeValue = computed<[string, string] | null>(() =>
|
||||
startDate.value && endDate.value ? [startDate.value, endDate.value] : null,
|
||||
)
|
||||
|
||||
const summaryFailures = createSummaryFailureAlerter((message, kind) => showAdminFeedback(message, kind))
|
||||
|
||||
function onDateRangeChange(value: [string, string] | null) {
|
||||
const start = value?.[0]
|
||||
const end = value?.[1]
|
||||
startDate.value = start ? String(start) : ''
|
||||
endDate.value = end ? String(end) : ''
|
||||
}
|
||||
|
||||
function collapse() {
|
||||
expandedKey.value = ''
|
||||
details.value = []
|
||||
detailTotal.value = 0
|
||||
detailLoading.value = false
|
||||
}
|
||||
|
||||
function isExpanded(group: AdminNotificationGroup): boolean {
|
||||
return expandedKey.value === notificationGroupKey(group)
|
||||
}
|
||||
|
||||
async function refreshSummary() {
|
||||
try {
|
||||
const summary = await fetchNotificationSummary()
|
||||
summaryFailures.reportSuccess()
|
||||
unreadCount.value = Number(summary?.unreadCount ?? 0)
|
||||
unreadGroupCount.value = Number(summary?.unreadGroupCount ?? 0)
|
||||
const latestId = Number(summary?.latestId ?? 0)
|
||||
if (hasNewNotification(latestId, readLastNotifiedId(uid()))) {
|
||||
ElMessage.warning('收到新的告警通知,请点击右上角铃铛查看')
|
||||
writeLastNotifiedId(uid(), latestId)
|
||||
console.log('[admin-notification] 检测到新通知 latestId=', latestId)
|
||||
}
|
||||
} catch (error) {
|
||||
// 接口失败时红点不亮(与改前一致),但要让用户知道「没数」不等于「没通知」:
|
||||
// 同一场故障只提示一次,成功一轮后重新武装(见 createSummaryFailureAlerter)。
|
||||
console.warn('[admin-notification] 未读数刷新失败(静默降级):', error)
|
||||
summaryFailures.reportFailure(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPage(targetPage: number) {
|
||||
if (loading.value) return
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await fetchNotificationGroups({
|
||||
page: targetPage,
|
||||
pageSize: PANEL_PAGE_SIZE,
|
||||
keyword: keyword.value,
|
||||
sort: sortMode.value,
|
||||
...normalizedDayRange(startDate.value, endDate.value),
|
||||
})
|
||||
const applied = applyGroupsPage(result, {
|
||||
unreadCount: unreadCount.value,
|
||||
unreadGroupCount: unreadGroupCount.value,
|
||||
})
|
||||
groups.value = applied.groups
|
||||
total.value = applied.total
|
||||
rowCount.value = applied.rowCount
|
||||
unreadCount.value = applied.unreadCount
|
||||
unreadGroupCount.value = applied.unreadGroupCount
|
||||
page.value = targetPage
|
||||
loadError.value = ''
|
||||
// 换页/重查后展开态必须清掉:旧组的明细列表与新页的组对不上,会串台
|
||||
collapse()
|
||||
if (targetPage <= 1 && !hasFilter.value) {
|
||||
const latest = latestIdWorthRecording(applied.groups)
|
||||
if (latest > 0) {
|
||||
writeLastNotifiedId(uid(), Math.max(readLastNotifiedId(uid()), latest))
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// 列表加载失败在面板内提示,不弹全局消息打扰用户
|
||||
console.warn('[admin-notification] 通知列表加载失败:', error)
|
||||
loadError.value = error instanceof Error ? error.message : '通知加载失败'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleGroup(group: AdminNotificationGroup) {
|
||||
if (isExpanded(group)) {
|
||||
collapse()
|
||||
return
|
||||
}
|
||||
collapse()
|
||||
const key = notificationGroupKey(group)
|
||||
expandedKey.value = key
|
||||
detailLoading.value = true
|
||||
try {
|
||||
const result = await fetchNotificationList(detailQueryFor(group, sortMode.value))
|
||||
// 请求期间用户可能已经收起了另一组:晚到的结果不能盖掉当前展开的那组
|
||||
if (expandedKey.value !== key) return
|
||||
details.value = Array.isArray(result?.items) ? result.items : []
|
||||
detailTotal.value = Number(result?.total ?? details.value.length)
|
||||
} catch (error) {
|
||||
if (expandedKey.value !== key) return
|
||||
details.value = []
|
||||
detailTotal.value = 0
|
||||
showAdminFeedback(error instanceof Error ? error.message : '明细加载失败', 'error')
|
||||
} finally {
|
||||
if (expandedKey.value === key) {
|
||||
detailLoading.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function goPage(targetPage: number) {
|
||||
const safe = Math.min(Math.max(1, targetPage), totalPages.value)
|
||||
if (safe === page.value || loading.value) return
|
||||
void loadPage(safe)
|
||||
}
|
||||
|
||||
/** 搜索/日期变化后回到第一页重新查询。 */
|
||||
function reload() {
|
||||
void loadPage(1)
|
||||
}
|
||||
|
||||
function resetFilters() {
|
||||
keyword.value = ''
|
||||
startDate.value = today()
|
||||
endDate.value = today()
|
||||
void loadPage(1)
|
||||
}
|
||||
|
||||
/** 排序切换:同一档不重复请求;切换后回到第一页并收起明细。 */
|
||||
function setSortMode(value: AdminNotificationSortMode) {
|
||||
if (sortMode.value === value) {
|
||||
return
|
||||
}
|
||||
sortMode.value = value
|
||||
void loadPage(1)
|
||||
}
|
||||
|
||||
async function onItemClick(item: AdminNotificationItem) {
|
||||
if (item.read) return
|
||||
try {
|
||||
await markNotificationRead(item.id)
|
||||
item.read = true
|
||||
const next = applyMarkReadToCounts(
|
||||
groups.value,
|
||||
expandedKey.value,
|
||||
unreadCount.value,
|
||||
unreadGroupCount.value,
|
||||
)
|
||||
unreadCount.value = next.unreadCount
|
||||
unreadGroupCount.value = next.unreadGroupCount
|
||||
} catch (error) {
|
||||
// 改前只 console.warn:点了通知没反应,用户只能反复点。失败必须可见(统一出口)。
|
||||
console.warn('[admin-notification] 标记已读失败:', error)
|
||||
showAdminFeedback(markReadFailureMessage(error), 'error')
|
||||
}
|
||||
}
|
||||
|
||||
async function readAll() {
|
||||
if (markingAll.value || unreadCount.value === 0) return
|
||||
markingAll.value = true
|
||||
try {
|
||||
await markAllNotificationsRead()
|
||||
for (const group of groups.value) {
|
||||
group.unreadCount = 0
|
||||
}
|
||||
for (const item of details.value) {
|
||||
item.read = true
|
||||
}
|
||||
unreadCount.value = 0
|
||||
unreadGroupCount.value = 0
|
||||
} catch (error) {
|
||||
console.warn('[admin-notification] 全部已读失败:', error)
|
||||
showAdminFeedback(error instanceof Error ? error.message : '操作失败', 'error')
|
||||
} finally {
|
||||
markingAll.value = false
|
||||
}
|
||||
}
|
||||
|
||||
let searchTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
onUnmounted(dispose)
|
||||
|
||||
function onKeywordInput() {
|
||||
if (searchTimer != null) {
|
||||
clearTimeout(searchTimer)
|
||||
}
|
||||
searchTimer = setTimeout(() => {
|
||||
searchTimer = null
|
||||
void loadPage(1)
|
||||
}, KEYWORD_DEBOUNCE_MS)
|
||||
}
|
||||
|
||||
/** 防抖里那次没发出去的请求不许在面板关掉后落地:钩子挂在 composable 自己身上,
|
||||
* "有 setTimeout 的文件必须也有卸载钩子"这条配对判据因此由构造成立,不靠调用方记得清。 */
|
||||
function dispose() {
|
||||
if (searchTimer != null) {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
unreadCount,
|
||||
unreadGroupCount,
|
||||
groups,
|
||||
total,
|
||||
rowCount,
|
||||
page,
|
||||
loading,
|
||||
markingAll,
|
||||
loadError,
|
||||
keyword,
|
||||
startDate,
|
||||
endDate,
|
||||
expandedKey,
|
||||
details,
|
||||
detailTotal,
|
||||
detailLoading,
|
||||
badgeText,
|
||||
totalPages,
|
||||
hasFilter,
|
||||
sortMode,
|
||||
setSortMode,
|
||||
dateRangeValue,
|
||||
onDateRangeChange,
|
||||
refreshSummary,
|
||||
loadPage,
|
||||
isExpanded,
|
||||
toggleGroup,
|
||||
goPage,
|
||||
reload,
|
||||
onKeywordInput,
|
||||
resetFilters,
|
||||
onItemClick,
|
||||
readAll,
|
||||
}
|
||||
}
|
||||
|
||||
export type NotificationPanel = ReturnType<typeof useNotificationBellPanel>
|
||||
@@ -1,141 +0,0 @@
|
||||
/**
|
||||
* 每菜单页的操作提示(guides)文案,对齐旧版 backend/static/admin-interactions.js 的 guides 表原文
|
||||
* (duplicate-check 为例外页不展示)。key = 路由 meta.menuKey。
|
||||
* 2026-10-14 控制方定案:提示条按 menuKey 取、不分支角色,谁能进这一页谁就看得到,
|
||||
* 于是"超级管理员可用上方公司 tab 切换公司""本页全平台共享,不按公司区分"这类只描述超管观感的句子
|
||||
* 会摊到普通账号脸上 —— 整批撤掉,文案回到旧版原文。tab 本身与它的接线没动。
|
||||
* 反向守门:tests/align-operation-guide.test.ts 钉这几句不得回流。
|
||||
*/
|
||||
export interface OperationGuideData {
|
||||
text: string
|
||||
steps: string[]
|
||||
}
|
||||
|
||||
export const OPERATION_GUIDE_FALLBACK: OperationGuideData = {
|
||||
text: '先使用筛选定位记录,再进行新增、编辑、导出等操作。涉及删除的数据会要求二次确认。',
|
||||
steps: ['选择筛选条件', '处理记录', '核对反馈'],
|
||||
}
|
||||
|
||||
/** 折叠状态 localStorage key(沿用旧版 shufuAdminGuideCollapsed 语义)。 */
|
||||
export const OPERATION_GUIDE_STORAGE_KEY = 'shufuAdminGuideCollapsed'
|
||||
|
||||
export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
|
||||
admin_users: {
|
||||
text: '先用筛选定位账号,再编辑角色和菜单权限;删除账号会要求二次确认。',
|
||||
steps: ['筛选账号', '编辑权限', '确认保存'],
|
||||
},
|
||||
admin_columns: {
|
||||
text: '菜单会影响后台和软件端的可见范围。先填写名称并选择对应页面,再设置上级菜单;顺序直接拖动列表左侧手柄调整。',
|
||||
steps: ['新增或调整菜单', '设置层级', '拖动排序'],
|
||||
},
|
||||
admin_group_manage: {
|
||||
text: '数据权限分组决定"哪些账号能看到哪些店铺",分组按负责人和归属账号聚拢。',
|
||||
steps: ['选择分组', '维护负责人与归属账号', '核对店铺可见范围'],
|
||||
},
|
||||
admin_user_secrets: {
|
||||
text: '用户密钥按账号绑定,列表只展示脱敏值。可对单条立即检测连通性;清空后该用户需要重新配置密钥。',
|
||||
steps: ['筛选用户或状态', '立即检测连通性', '必要时清空'],
|
||||
},
|
||||
admin_companies: {
|
||||
text: '公司决定账号归属:新建普通账号/管理员自动落在操作者自己所在的公司,页面上不出现公司选项——要给别的公司建号,请用那个公司自己的管理员登录。唯一例外是「公司超级管理员」:由站点超管开设、需在建号弹窗中显式选择所属公司。公司只做启用/停用,不提供删除。',
|
||||
steps: ['查看公司列表', '新建公司', '改名或启停'],
|
||||
},
|
||||
admin_dedupe_total_data: {
|
||||
text: '支持按关键词、用户、分组和国家筛选;导入前先确认所选分组,导出会按日期范围生成文件。',
|
||||
steps: ['选择分组', '筛选或导入', '核对并导出'],
|
||||
},
|
||||
admin_invalid_asin_data: {
|
||||
text: '维护不符合规则的 ASIN 或品牌。添加后可使用上方筛选快速回查。',
|
||||
steps: ['填写 ASIN/品牌', '选择分组', '保存并回查'],
|
||||
},
|
||||
admin_query_asin: {
|
||||
text: '查询 ASIN 以店铺为单位维护。列表里点击 ASIN 即可复制,点右侧「配置」可一次维护该店铺所有站点的 ASIN。',
|
||||
steps: ['筛选店铺', '打开配置抽屉', '保存或导出'],
|
||||
},
|
||||
admin_product_categories: {
|
||||
text: '类目树支持展开查看层级。搜索、编辑和删除都在同一列表中完成。',
|
||||
steps: ['搜索类目', '展开层级', '新增或编辑'],
|
||||
},
|
||||
admin_skip_price_asin: {
|
||||
text: '最低价 ASIN 以店铺为单位维护。列表里点击 ASIN 即可复制,点右侧「配置」可一次维护该店铺所有站点的 ASIN 与最低价。',
|
||||
steps: ['筛选店铺', '打开配置抽屉', '保存或批量导入'],
|
||||
},
|
||||
admin_shop_keys: {
|
||||
text: '紫鸟令牌属于敏感配置。白名单状态可悬停查看检测详情,编辑前请先核对账号名称。',
|
||||
steps: ['新增或筛选密钥', '查看白名单状态', '编辑或删除'],
|
||||
},
|
||||
admin_shop_manage: {
|
||||
text: '店铺信息按分组管理。长商城名会自动缩略,悬停即可查看完整内容。',
|
||||
steps: ['选择分组', '维护店铺信息', '筛选核对结果'],
|
||||
},
|
||||
admin_shop_data_crawl_tasks: {
|
||||
text: '店铺数据任务按状态和时间筛选。批量操作前请核对已选任务。',
|
||||
steps: ['筛选任务', '检查状态', '执行批量操作'],
|
||||
},
|
||||
admin_brand_gating: {
|
||||
text: '维护不符合规则的品牌(品牌Gating / 类目Gating)。新增后可用下方筛选快速回查;云端 Gating 库与前端排查软件同步同一份数据,命中后会自动拦截。',
|
||||
steps: ['新增或批量导入', '筛选回查', '按需解除或删除'],
|
||||
},
|
||||
admin_keyword_usage: {
|
||||
text: '本页记录所有关键词操作,只读、不可删除、永久留痕可追溯;与桌面端互通:桌面复制、添加、删除关键词会自动写入本页,两端同源。',
|
||||
steps: ['选择公司与筛选条件', '切换使用/删除记录', '核对操作人与时间'],
|
||||
},
|
||||
// admin_shop_data_duplicate_check(店铺撞款监控)为例外页:不展示全局提示条,不参与对齐。
|
||||
admin_image_video_tasks: {
|
||||
text: '可先使用筛选缩小任务范围,再查看任务状态、结果和权限范围。',
|
||||
steps: ['设置筛选', '查看任务结果', '按需处理任务'],
|
||||
},
|
||||
admin_history: {
|
||||
text: '生成记录可按用户和时间范围回溯,用于核对结果文件和执行时间。',
|
||||
steps: ['设置时间范围', '筛选记录', '查看结果预览'],
|
||||
},
|
||||
admin_version: {
|
||||
text: '上传版本后请核对版本号和下载链接,再通知用户更新。',
|
||||
steps: ['上传压缩包', '检查版本记录', '维护历史版本'],
|
||||
},
|
||||
admin_tutorial: {
|
||||
text: '上传新的教程压缩包后即刻生效:工具台首页「立即下载教程」以下载最新上传的包为准。确认旧包不再需要后再删除。',
|
||||
steps: ['上传教程压缩包', '到工具台核对下载', '清理历史包'],
|
||||
},
|
||||
admin_workbench_client_package: {
|
||||
text: '上传新的工作台客户端 ZIP 包后即刻生效;服务端会复算 sha256 供客户端校验。确认旧包不再需要后再删除。',
|
||||
steps: ['填写版本号并上传 ZIP', '核对版本与 sha256', '清理历史包'],
|
||||
},
|
||||
digital_human_version: {
|
||||
text: '数字人版本需先上传草稿,再发布并标记最新版本。',
|
||||
steps: ['上传草稿', '确认更新日志', '发布或设为最新'],
|
||||
},
|
||||
admin_device_logs: {
|
||||
text: '桌面客户端与麦象采集机上报的日志按来源、日期和关键字筛选;可查看日志尾部、下载完整文件或删除云端记录,云端日志按保留期自动清理。',
|
||||
steps: ['选择来源与日期', '查看或下载日志', '必要时删除'],
|
||||
},
|
||||
admin_user_secret_usage: {
|
||||
text: '按日期范围统计各用户的密钥调用次数(货源查询与外观专利按 LLM 请求次数、代理按提取次数),用于评估用户资源损耗。',
|
||||
steps: ['选择日期范围', '筛选用户或分组', '核对各模块次数'],
|
||||
},
|
||||
admin_task_center: {
|
||||
text: '按账号、业务、状态、店铺和创建时间筛出客户端任务,点任务查看明细与分组结果;顶部汇总卡给当前在跑与疑似卡住的总量。',
|
||||
steps: ['按条件筛任务', '查看任务明细', '核对汇总卡'],
|
||||
},
|
||||
admin_appearance_patent_clean_items: {
|
||||
text: '本页只读:出表成功后「结论=无侵权」的明细自动同步到这里,按分公司隔离分页展示;支持任务号/ASIN/国家/同步日期筛选,下载原表请到任务中心取结果文件。',
|
||||
steps: ['筛选记录', '核对结论明细', '到任务中心下载原表'],
|
||||
},
|
||||
admin_jd_database: {
|
||||
text: '本页只读:客户端采集的京东店铺商品自动同步到这里(同店铺同商品只保留最新一次),按分公司隔离分页展示;点行查看全部属性与图片,可用自定义分组归档商品。',
|
||||
steps: ['筛选商品记录', '查看属性与图片明细', '按分组归档管理'],
|
||||
},
|
||||
admin_jd_category_manage: {
|
||||
text: '本页维护京东自定义分类:分类按数据权限分组隔离,当前组只组长/超管可新建、改名、删除(删除不删商品,只解挂归属);给商品归类请到「京东数据库」页勾选后「批量编辑分类」。',
|
||||
steps: ['切换分组', '新建或改名分类', '到京东数据库页归类商品'],
|
||||
},
|
||||
}
|
||||
|
||||
/** 全部有独立/兜底提示的后台业务菜单 key。 */
|
||||
export const OPERATION_GUIDE_MENU_KEYS = Object.keys(OPERATION_GUIDES)
|
||||
|
||||
/** 返回指定菜单 key 的提示数据;menuKey 不在已知集合时返回 null(登录/404 等页面不展示)。 */
|
||||
export function operationGuideFor(menuKey: unknown): OperationGuideData | null {
|
||||
if (typeof menuKey !== 'string' || !menuKey) return null
|
||||
return OPERATION_GUIDES[menuKey] ?? null
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import type { AdminMenuNode } from '../types/admin'
|
||||
import { PLATFORM_TABS, platformsOfMenuKey } from '../config/platform-scope.ts'
|
||||
import type { PlatformTabId } from '../config/platform-scope.ts'
|
||||
import { firstVisiblePath } from '../router/helpers.ts'
|
||||
|
||||
/**
|
||||
* 按平台 tab 过滤后端菜单树(2026-11-16「亚马逊/京东不混」):**只做显示分组,不做鉴权**——
|
||||
* 准入仍由 session.menuTree(后端按权限裁剪)与路由守卫负责,这里只是把当前用户已被授权的
|
||||
* 菜单按平台分到两个 tab 下展示。
|
||||
* 规则:叶子按 platformsOfMenuKey(key) 是否包含当前平台留下(双侧清单里的账号域三页两个
|
||||
* tab 都显示);分组节点(admin_group_*)自身的 key 不参与平台判定,按「留住的子项数 > 0」
|
||||
* 决定去留——否则京东 tab 下「账号与权限」这类混合分组会被整组误剪。节点的 key/name/
|
||||
* route/children 形状原样透传(浅拷贝不改写),toSidebarEntries、groupKeysForActive 与
|
||||
* 面包屑都不受影响。
|
||||
*/
|
||||
export function filterMenuTreeByPlatform(
|
||||
nodes: AdminMenuNode[] | null | undefined,
|
||||
platform: PlatformTabId,
|
||||
): AdminMenuNode[] {
|
||||
const filtered: AdminMenuNode[] = []
|
||||
for (const node of nodes || []) {
|
||||
const children = filterMenuTreeByPlatform(node.children, platform)
|
||||
if (children.length > 0) {
|
||||
filtered.push({ ...node, children })
|
||||
continue
|
||||
}
|
||||
if ((node.children || []).length > 0) continue
|
||||
if (platformsOfMenuKey(node.key || '').includes(platform)) filtered.push({ ...node })
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
/** 当前用户在哪些平台下至少有一个可点页面(tab 显示依据);顺序固定随 PLATFORM_TABS。
|
||||
* 「可点」沿用 firstVisiblePath 这一把尺子(有 route 即可点),不另写第二处判定。 */
|
||||
export function visiblePlatformsFor(nodes: AdminMenuNode[] | null | undefined): PlatformTabId[] {
|
||||
return PLATFORM_TABS
|
||||
.filter((tab) => firstVisiblePath(filterMenuTreeByPlatform(nodes, tab.id)) !== '')
|
||||
.map((tab) => tab.id)
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
/** 侧边栏折叠与窄屏布局状态(任务 14):宽高常量、阈值、偏好持久化。 */
|
||||
|
||||
export const SIDEBAR_EXPANDED_WIDTH = 248
|
||||
export const SIDEBAR_COLLAPSED_WIDTH = 64
|
||||
export const SIDEBAR_NARROW_THRESHOLD = 900
|
||||
|
||||
/** 视口窄到需要自动收起侧边栏。 */
|
||||
export function isNarrowScreen(width: number): boolean {
|
||||
return width > 0 && width <= SIDEBAR_NARROW_THRESHOLD
|
||||
}
|
||||
|
||||
/** 反转折叠状态。 */
|
||||
export function toggleCollapsed(current: boolean): boolean {
|
||||
return !current
|
||||
}
|
||||
|
||||
export type CollapseStorage = Pick<Storage, 'getItem' | 'setItem'> | null
|
||||
|
||||
const PREFERENCE_KEY = 'admin.sidebar.collapsed'
|
||||
|
||||
function parsePreference(raw: string | null): boolean | null {
|
||||
return raw === 'true' ? true : raw === 'false' ? false : null
|
||||
}
|
||||
|
||||
/** 读取持久化偏好;无存储或值非法返回 null。 */
|
||||
export function readCollapsePreference(storage: CollapseStorage): boolean | null {
|
||||
try {
|
||||
return parsePreference(storage?.getItem(PREFERENCE_KEY) ?? null)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** 写入折叠偏好;存储不可用时静默失败(不阻断交互)。 */
|
||||
export function writeCollapsePreference(storage: CollapseStorage, collapsed: boolean): void {
|
||||
try {
|
||||
storage?.setItem(PREFERENCE_KEY, String(collapsed))
|
||||
} catch {
|
||||
// localStorage 不可用(隐私模式等)时忽略
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始折叠值:优先持久化偏好;无偏好时窄屏自动折叠、宽屏展开。
|
||||
* width<=0(如 SSR/未知)视为无法判定,回退 false。
|
||||
*/
|
||||
export function initialCollapsed(width: number, storage: CollapseStorage): boolean {
|
||||
const preference = readCollapsePreference(storage)
|
||||
if (preference !== null) return preference
|
||||
return isNarrowScreen(width)
|
||||
}
|
||||
|
||||
/** 侧边栏应占用的像素宽(用于宽度计算/测试,不直接改 CSS)。 */
|
||||
export function sidebarPixelWidth(collapsed: boolean): number {
|
||||
return collapsed ? SIDEBAR_COLLAPSED_WIDTH : SIDEBAR_EXPANDED_WIDTH
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import type { AdminMenuNode } from '../types/admin'
|
||||
|
||||
export const ADMIN_BRAND = '数富AI'
|
||||
|
||||
/** 文档标题规则:`页面标题 - 数富AI`;无页面标题时仅品牌。 */
|
||||
export function resolveDocumentTitle(pageTitle: string, brand: string = ADMIN_BRAND): string {
|
||||
const trimmed = (pageTitle || '').trim()
|
||||
return trimmed ? `${trimmed} - ${brand}` : brand
|
||||
}
|
||||
|
||||
/** 同步 HTML 文档标题;doc 为空(如非浏览器环境)时静默跳过。 */
|
||||
export function updateDocumentTitle(title: string, doc: { title: string } | null | undefined): void {
|
||||
if (doc) doc.title = title
|
||||
}
|
||||
|
||||
export interface BreadcrumbItem {
|
||||
key: string
|
||||
name: string
|
||||
route?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 面包屑规则:在菜单树中定位激活路由,返回“分组 -> 页面”层级(顶层叶子只返回自身)。
|
||||
* 无命中返回空数组,不伪造路径。
|
||||
*/
|
||||
export function crumbsForActiveRoute(nodes: AdminMenuNode[] | null | undefined, activeRoute: string): BreadcrumbItem[] {
|
||||
for (const node of nodes || []) {
|
||||
if (node.route === activeRoute) return [{ key: node.key, name: node.name, route: node.route }]
|
||||
const children = node.children || []
|
||||
for (const child of children) {
|
||||
if (child.route === activeRoute) {
|
||||
return [
|
||||
{ key: node.key, name: node.name },
|
||||
{ key: child.key, name: child.name, route: child.route },
|
||||
]
|
||||
}
|
||||
}
|
||||
const nested = crumbsForActiveRoute(children, activeRoute)
|
||||
if (nested.length) return [{ key: node.key, name: node.name }, ...nested]
|
||||
}
|
||||
return []
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import type { AdminUser } from '../types/admin.ts'
|
||||
import { roleLabel } from '../types/admin.ts'
|
||||
|
||||
/** 无 meta.title 时的壳层缺省标题。 */
|
||||
export const ADMIN_DEFAULT_TITLE = '管理后台'
|
||||
|
||||
/** 页面标题模型:由路由 meta.title 驱动,空值回落缺省标题。 */
|
||||
export function pageTitleOf(title: string | null | undefined): string {
|
||||
const value = typeof title === 'string' ? title.trim() : ''
|
||||
return value || ADMIN_DEFAULT_TITLE
|
||||
}
|
||||
|
||||
export interface TopbarUserViewModel {
|
||||
username: string
|
||||
role: string
|
||||
hasUser: boolean
|
||||
}
|
||||
|
||||
/** 顶部栏用户模型:用户信息或未登录空态统一为可渲染视图模型。 */
|
||||
export function topbarUserOf(user: AdminUser | null | undefined): TopbarUserViewModel {
|
||||
if (!user) return { username: '当前用户', role: '', hasUser: false }
|
||||
return {
|
||||
username: user.username || '当前用户',
|
||||
role: roleLabel(user.role) || user.role || '',
|
||||
hasUser: true,
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import { installElement } from '@/plugins/element'
|
||||
import { reportClientError } from '@/shared/api/error-report'
|
||||
import '@/styles/main.css'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
|
||||
// 全局错误兜底(S1-F2/AC-16):渲染期异常、未捕获 Promise、脚本级崩溃三类都必须
|
||||
// 可见 + 上报,否则线上白屏只剩浏览器 console,运维永远没有现场。
|
||||
// 出口分两处,各按自己的时机生效:
|
||||
// - Vue 渲染/生命周期异常:挂在这里的 app.config.errorHandler(必须早于 mount,
|
||||
// 首屏就崩也不漏);
|
||||
// - window error 与 unhandledrejection:由 App.vue setup 调 useGlobalErrorReporting()
|
||||
// 接线,卸载出口在 onBeforeUnmount 里摘监听与提示定时器(只定义不接线等于没接)。
|
||||
// 上报本体(内存环 + 脱敏 + sendBeacon)在 @/shared/api/error-report。
|
||||
function installGlobalError(app: ReturnType<typeof createApp>): void {
|
||||
app.config.errorHandler = (error, _instance, info) => {
|
||||
reportClientError({
|
||||
kind: 'vue-render',
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
stack: error instanceof Error ? error.stack ?? '' : String(error),
|
||||
route: router.currentRoute.value.fullPath,
|
||||
ts: Date.now(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Element Plus 改为按需注册(见 src/plugins/element.ts);全局中文语言包改由
|
||||
// App.vue 的 <el-config-provider :locale="zhCn"> 提供,不要再在这里 use(ElementPlus)。
|
||||
const app = createApp(App)
|
||||
app.use(createPinia())
|
||||
app.use(router)
|
||||
installElement(app)
|
||||
installGlobalError(app)
|
||||
app.mount('#app')
|
||||
@@ -1,283 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/** 公司管理(设计文档 §2.3):列表 + 新建 + 改名/启停。
|
||||
* 可见范围由后端收窄(超管全部、公司内 admin 只自己公司);写操作仅超管,这里隐藏入口只是配合,
|
||||
* 真正的把关在 CompanyController,页面不得当作权限边界。 */
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { fetchCompanies } from '@/api/companies'
|
||||
import { COMPANY_STATUS_ACTIVE, type CompanyItem } from '@/api/companies-dto'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { usePlatformTabStore } from '@/stores/platform-tab'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import CompanyEditorDialog from './CompanyEditorDialog.vue'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
// 平台 tab(V206):公司列表按当前平台过滤,新建默认落当前平台。
|
||||
const platformTab = usePlatformTabStore()
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<CompanyItem[]>([])
|
||||
const editorVisible = ref(false)
|
||||
const editingCompany = ref<CompanyItem | null>(null)
|
||||
const filterKeyword = ref('')
|
||||
|
||||
const canManage = computed(() => session.isSuperAdmin)
|
||||
const filteredRows = computed(() => {
|
||||
const kw = filterKeyword.value.trim().toLowerCase()
|
||||
if (!kw) return rows.value
|
||||
return rows.value.filter((c) => (c.companyName || '').toLowerCase().includes(kw))
|
||||
})
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const pagedRows = computed(() => filteredRows.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||
|
||||
function changePage(p: number) { page.value = p }
|
||||
function changeSize(size: number) { pageSize.value = size; page.value = 1 }
|
||||
|
||||
async function loadCompanies() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
rows.value = await fetchCompanies(platformTab.active)
|
||||
} catch (error) {
|
||||
loadFailure.value = error instanceof Error ? error.message : '公司列表加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
editingCompany.value = null
|
||||
editorVisible.value = true
|
||||
}
|
||||
|
||||
function openEdit(company: CompanyItem) {
|
||||
editingCompany.value = company
|
||||
editorVisible.value = true
|
||||
}
|
||||
|
||||
// 切平台 tab(V206)= 重新取数:公司归属按平台分列,两 tab 各看各的公司。
|
||||
watch(() => platformTab.active, () => {
|
||||
page.value = 1
|
||||
void loadCompanies()
|
||||
})
|
||||
|
||||
onMounted(loadCompanies)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="companies-view">
|
||||
<section class="panel-box">
|
||||
<div class="companies-head">
|
||||
<h3>公司列表</h3>
|
||||
<button v-if="canManage" class="btn" type="button" @click="openCreate">新建公司</button>
|
||||
</div>
|
||||
|
||||
<div class="form-row companies-filter-row">
|
||||
<div class="form-group" style="min-width: 200px">
|
||||
<label>公司名称</label>
|
||||
<input v-model="filterKeyword" type="text" placeholder="输入公司名称" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadCompanies" />
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 58px">序号</th>
|
||||
<th>公司名称</th>
|
||||
<th style="width: 90px">状态</th>
|
||||
<th style="width: 24%">备注</th>
|
||||
<th style="width: 160px">创建时间</th>
|
||||
<th style="width: 160px">修改时间</th>
|
||||
<th style="width: 90px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-if="filteredRows.length">
|
||||
<tr v-for="(company, index) in pagedRows" :key="company.id">
|
||||
<td>{{ index + 1 }}</td>
|
||||
<td>{{ company.companyName || '-' }}</td>
|
||||
<td>
|
||||
<span :class="company.status === COMPANY_STATUS_ACTIVE ? 'state-on' : 'state-off'">
|
||||
{{ company.status === COMPANY_STATUS_ACTIVE ? '启用' : '停用' }}
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ company.remark || '-' }}</td>
|
||||
<td>{{ formatDateTime(company.createdAt) }}</td>
|
||||
<td>{{ formatDateTime(company.updatedAt || company.createdAt) }}</td>
|
||||
<td class="ops-cell">
|
||||
<button v-if="canManage" class="btn btn-sm" type="button" @click="openEdit(company)">编辑</button>
|
||||
<span v-else class="cell-none">-</span>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td colspan="7" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td colspan="7" class="empty-tip">{{ filterKeyword.trim() ? '暂无匹配公司' : '暂无公司' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<OldPagination
|
||||
v-if="filteredRows.length > 0"
|
||||
:total="filteredRows.length"
|
||||
:page="page"
|
||||
:page-size="pageSize"
|
||||
@change="changePage"
|
||||
@size-change="changeSize"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<CompanyEditorDialog v-model="editorVisible" :company="editingCompany" :platform="platformTab.active" @saved="loadCompanies" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.companies-view {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
color: #24384d;
|
||||
}
|
||||
.panel-box {
|
||||
width: 100%;
|
||||
padding: 20px 22px 24px;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(145deg, #ffffff, #f9fbfd);
|
||||
box-shadow: 0 1px 2px rgba(39, 67, 94, 0.04), 0 14px 30px -24px rgba(39, 67, 94, 0.28);
|
||||
}
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
}
|
||||
.companies-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.companies-filter-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 14px 18px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.companies-filter-row .form-group {
|
||||
flex: 1 1 200px;
|
||||
}
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
}
|
||||
.form-group label {
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.form-group input {
|
||||
min-height: 42px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.form-group input:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 42px;
|
||||
padding: 9px 18px;
|
||||
border: 1px solid #4f78a5;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #7094ba, #5d83ac);
|
||||
}
|
||||
.btn-sm {
|
||||
min-height: 36px;
|
||||
padding: 7px 12px;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.table-scroll {
|
||||
width: 100%;
|
||||
overflow-x: auto;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 10px;
|
||||
background: #ffffff;
|
||||
}
|
||||
.table-scroll table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
}
|
||||
.table-scroll th,
|
||||
.table-scroll td {
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
font-size: 13.5px;
|
||||
line-height: 1.5;
|
||||
border-bottom: 1px solid #e0e8ef;
|
||||
vertical-align: middle;
|
||||
word-break: break-word;
|
||||
}
|
||||
.table-scroll th {
|
||||
background: #edf4fa;
|
||||
color: #4e6479;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.table-scroll tbody tr:hover td {
|
||||
background: #f1f7fb;
|
||||
}
|
||||
.table-scroll tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.state-on {
|
||||
color: #2e7d5b;
|
||||
}
|
||||
.state-off {
|
||||
color: #b35f6a;
|
||||
}
|
||||
.ops-cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.cell-none {
|
||||
color: #8293a5;
|
||||
}
|
||||
.empty-tip {
|
||||
padding: 44px 24px;
|
||||
text-align: center;
|
||||
color: #8293a5;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,101 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import type { PlatformTabId } from '@/config/platform-scope'
|
||||
import { createCompany, updateCompany } from '@/api/companies'
|
||||
import {
|
||||
COMPANY_NAME_MAX_LENGTH,
|
||||
COMPANY_STATUS_ACTIVE,
|
||||
COMPANY_STATUS_DISABLED,
|
||||
validateCompanyDraft,
|
||||
type CompanyDraft,
|
||||
type CompanyItem,
|
||||
} from '@/api/companies-dto'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { actionableErrorText } from '@/components/admin-feedback'
|
||||
|
||||
/** 新建/编辑公司(改名 + 启停 + 备注 + 所属平台 V206);写操作仅超管可用,权限由后端把关。 */
|
||||
const props = defineProps<{ modelValue: boolean; company: CompanyItem | null; platform?: PlatformTabId }>()
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'saved'): void }>()
|
||||
|
||||
const form = ref<CompanyDraft>({ companyName: '', status: COMPANY_STATUS_ACTIVE, remark: '', platform: 'amazon' })
|
||||
const errorText = ref('')
|
||||
const busy = ref(false)
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(open) => {
|
||||
if (!open) return
|
||||
form.value = props.company
|
||||
? {
|
||||
companyName: props.company.companyName,
|
||||
status: props.company.status,
|
||||
remark: props.company.remark || '',
|
||||
platform: props.company.platform === 'jd' ? 'jd' : 'amazon',
|
||||
}
|
||||
: { companyName: '', status: COMPANY_STATUS_ACTIVE, remark: '', platform: props.platform ?? 'amazon' }
|
||||
errorText.value = ''
|
||||
},
|
||||
)
|
||||
|
||||
function close() {
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
|
||||
async function save() {
|
||||
errorText.value = validateCompanyDraft(form.value)
|
||||
if (errorText.value) return
|
||||
busy.value = true
|
||||
try {
|
||||
if (props.company) await updateCompany(props.company.id, form.value)
|
||||
else await createCompany(form.value)
|
||||
showAdminFeedback(props.company ? '公司已更新' : '公司已创建', 'success')
|
||||
emit('saved')
|
||||
close()
|
||||
} catch (error) {
|
||||
errorText.value = actionableErrorText(error)
|
||||
showAdminFeedback(errorText.value, 'error')
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="modelValue"
|
||||
:title="company ? '编辑公司' : '新建公司'"
|
||||
width="520px"
|
||||
:close-on-click-modal="false"
|
||||
destroy-on-close
|
||||
@update:model-value="(v: boolean) => emit('update:modelValue', v)"
|
||||
>
|
||||
<el-form label-position="top" @submit.prevent>
|
||||
<el-form-item label="公司名称" :error="errorText || undefined">
|
||||
<el-input
|
||||
v-model="form.companyName"
|
||||
:maxlength="COMPANY_NAME_MAX_LENGTH"
|
||||
placeholder="请输入公司名称(全平台唯一)"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="所属平台">
|
||||
<el-radio-group v-model="form.platform">
|
||||
<el-radio-button value="amazon">亚马逊</el-radio-button>
|
||||
<el-radio-button value="jd">京东</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="状态">
|
||||
<el-select v-model="form.status" style="width: 100%">
|
||||
<el-option :value="COMPANY_STATUS_ACTIVE" label="启用" />
|
||||
<el-option :value="COMPANY_STATUS_DISABLED" label="停用" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="备注">
|
||||
<el-input v-model="form.remark" type="textarea" :rows="2" placeholder="可留空" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="close">取消</el-button>
|
||||
<el-button type="primary" :loading="busy" @click="save">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
@@ -1,205 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import type { PlatformTabId } from '@/config/platform-scope'
|
||||
import { submitCreateUser } from './user-create-adapter'
|
||||
import {
|
||||
createEmptyCreateUserForm,
|
||||
defaultRoleChoice,
|
||||
mayCarryOwnExpiry,
|
||||
resolveRoleChoices,
|
||||
type CreatableUserRole,
|
||||
type CreateUserForm,
|
||||
type CreateUserFormErrors,
|
||||
validateCreateUserForm,
|
||||
} from './user-create-model'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { actionableErrorText } from '@/components/admin-feedback'
|
||||
import UserMenuAuthTree from './UserMenuAuthTree.vue'
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: boolean
|
||||
operatorSuper?: boolean
|
||||
/** 操作者角色(company_super_admin 也能建管理员/普通账号)。 */
|
||||
operatorRole?: string | null
|
||||
/** 所属管理员候选(列表响应 admins;仅超管创建普通账号时展示,已按当前公司 tab 收窄)。 */
|
||||
adminOptions?: Array<{ id: number; username: string }>
|
||||
/** 公司候选(站点超管创建公司超级管理员时必选)。 */
|
||||
companyOptions?: Array<{ id: number; companyName: string }>
|
||||
/** 操作者自己那家公司(会话 current-user.companyId)。 */
|
||||
operatorCompanyId?: number | null
|
||||
/** 当前公司 tab:这次建号落在哪家,就决定能建哪些角色。 */
|
||||
activeCompanyId?: number | null
|
||||
/** 当前平台 tab(V206):新号默认落当前平台,单选可改。 */
|
||||
platform?: PlatformTabId
|
||||
}>()
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'created'): void }>()
|
||||
|
||||
const form = reactive<CreateUserForm>(createEmptyCreateUserForm())
|
||||
const errors = reactive<CreateUserFormErrors>({})
|
||||
const busy = ref(false)
|
||||
|
||||
/** 角色下拉:站点超管可选公司超管/管理员/普通账号;公司超管只可选管理员/普通账号;
|
||||
* 管理员不显示角色选择(后端强制 normal)。 */
|
||||
const ROLE_LABELS: Record<CreatableUserRole, string> = {
|
||||
company_super_admin: '公司超级管理员',
|
||||
admin: '管理员',
|
||||
normal: '普通账号',
|
||||
}
|
||||
const canChooseRole = computed(() => props.operatorSuper || props.operatorRole === 'company_super_admin')
|
||||
/** 可选角色集合的唯一来源是 user-create-model 那个纯函数(后端有同一口径的一条 403)。 */
|
||||
const allowedRoles = computed<CreatableUserRole[]>(() =>
|
||||
resolveRoleChoices(props.operatorSuper === true, props.operatorCompanyId, props.activeCompanyId),
|
||||
)
|
||||
const roleChoices = computed(() => allowedRoles.value.map((value) => ({ value, label: ROLE_LABELS[value] })))
|
||||
/** 只有管理员/公司超管有「自己的到期时间」;普通账号跟随上级级联,不给它入口。 */
|
||||
const expiryEditable = computed(() => mayCarryOwnExpiry(form.role))
|
||||
|
||||
// 公司 tab 收窄了可选角色时,把残留的旧选择收敛回合法项(并清掉上一家的所属管理员):
|
||||
// 留着它,用户看到的是一个已经不给选的选项,提交会被后端 403 打回。
|
||||
watch(allowedRoles, (roles) => {
|
||||
if (roles.includes(form.role)) return
|
||||
form.role = defaultRoleChoice(roles)
|
||||
form.createdBy = null
|
||||
})
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(open) => {
|
||||
if (!open) return
|
||||
form.username = ''
|
||||
form.password = ''
|
||||
form.role = defaultRoleChoice(allowedRoles.value)
|
||||
form.columnIds = []
|
||||
form.createdBy = null
|
||||
form.expiresAt = ''
|
||||
// 预填当前 tab:跨公司时角色本来就只剩公司超管,而那一例必须带公司
|
||||
form.companyId = props.activeCompanyId ?? null
|
||||
// 预填当前平台 tab(V206):京东侧建的号默认归京东,亚马逊侧默认亚马逊。
|
||||
form.platform = props.platform ?? 'amazon'
|
||||
errors.username = undefined
|
||||
errors.password = undefined
|
||||
errors.companyId = undefined
|
||||
},
|
||||
)
|
||||
|
||||
function close(): void {
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
|
||||
async function create(): Promise<void> {
|
||||
const { valid, errors: errs } = validateCreateUserForm(form)
|
||||
Object.assign(errors, errs)
|
||||
if (!valid) return
|
||||
busy.value = true
|
||||
try {
|
||||
await submitCreateUser(form)
|
||||
showAdminFeedback('创建成功', 'success')
|
||||
// 对齐 admin:成功后弹窗不关,仅清空用户名/密码并刷新列表。
|
||||
form.username = ''
|
||||
form.password = ''
|
||||
errors.username = undefined
|
||||
errors.password = undefined
|
||||
emit('created')
|
||||
} catch (error) {
|
||||
showAdminFeedback(actionableErrorText(error), 'error')
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="modelValue"
|
||||
title="创建用户"
|
||||
width="640px"
|
||||
:close-on-click-modal="false"
|
||||
destroy-on-close
|
||||
@update:model-value="(v: boolean) => emit('update:modelValue', v)"
|
||||
>
|
||||
<el-form label-position="top" @submit.prevent>
|
||||
<el-form-item label="用户名" :error="errors.username">
|
||||
<el-input v-model="form.username" autocomplete="username" placeholder="用户名(至少 2 个字符)" @input="errors.username = undefined" />
|
||||
</el-form-item>
|
||||
<el-form-item label="密码" :error="errors.password">
|
||||
<el-input
|
||||
v-model="form.password"
|
||||
type="password"
|
||||
show-password
|
||||
autocomplete="new-password"
|
||||
placeholder="密码(至少 6 个字符)"
|
||||
@input="errors.password = undefined"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="canChooseRole" label="角色">
|
||||
<el-select filterable v-model="form.role" style="width: 200px">
|
||||
<el-option v-for="opt in roleChoices" :key="opt.value" :label="opt.label" :value="opt.value" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="所属平台">
|
||||
<el-radio-group v-model="form.platform">
|
||||
<el-radio-button value="amazon">亚马逊</el-radio-button>
|
||||
<el-radio-button value="jd">京东</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item
|
||||
v-if="operatorSuper && form.role === 'company_super_admin'"
|
||||
label="所属公司"
|
||||
:error="errors.companyId"
|
||||
>
|
||||
<el-select
|
||||
v-model="form.companyId"
|
||||
filterable
|
||||
placeholder="请选择公司(必选)"
|
||||
style="width: 240px"
|
||||
@change="errors.companyId = undefined"
|
||||
>
|
||||
<el-option
|
||||
v-for="company in props.companyOptions || []"
|
||||
:key="company.id"
|
||||
:label="company.companyName"
|
||||
:value="company.id"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="operatorSuper && form.role === 'normal'" label="所属管理员">
|
||||
<el-select v-model="form.createdBy" clearable filterable placeholder="请选择管理员" style="width: 200px">
|
||||
<el-option
|
||||
v-for="admin in props.adminOptions || []"
|
||||
:key="admin.id"
|
||||
:label="admin.username"
|
||||
:value="admin.id"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="expiryEditable" label="到期时间(留空 = 永不过期;到期后该账号及其名下账号将停用)">
|
||||
<el-date-picker
|
||||
v-model="form.expiresAt"
|
||||
type="datetime"
|
||||
placeholder="选择到期时间"
|
||||
value-format="YYYY-MM-DD HH:mm:ss"
|
||||
format="YYYY-MM-DD HH:mm"
|
||||
style="width: 240px"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="菜单权限(勾选上级菜单会继承全部子菜单)">
|
||||
<div class="auth-tree-box">
|
||||
<UserMenuAuthTree v-model:checked="form.columnIds" :company-id="form.companyId" />
|
||||
</div>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="close">取消</el-button>
|
||||
<el-button type="primary" :loading="busy" @click="create">创建用户</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.auth-tree-box {
|
||||
width: 100%;
|
||||
border: 1px solid var(--el-border-color);
|
||||
border-radius: 9px;
|
||||
padding: 8px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,186 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import type { AdminUser } from '@/types/admin'
|
||||
import type { PlatformTabId } from '@/config/platform-scope'
|
||||
import { mayCarryOwnExpiry } from './user-create-model'
|
||||
import { fillEditUserForm, validateEditUserForm, type EditUserForm, type EditUserFormErrors } from './user-edit-model'
|
||||
import { submitEditUser } from './user-edit-adapter'
|
||||
import { loadUserMenuAuth } from './user-menu-auth-api'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { actionableErrorText } from '@/components/admin-feedback'
|
||||
import UserMenuAuthTree from './UserMenuAuthTree.vue'
|
||||
|
||||
/** companyId 由 UsersPage 把 companyTab.requestCompanyId 透传进来(本页的用户列表本来就由它筛 ⇒ 目标账号的公司
|
||||
* 就是 tab 选中的那家);弹窗自己不读 store,公司 tab 的取值口只留在页面组件那一处。
|
||||
* platform(V206)同理由页面透传:决定上架上限是否参与校验/下发(仅京东侧)。 */
|
||||
const props = defineProps<{ modelValue: boolean; user: AdminUser | null; operatorSuper?: boolean; companyId?: number | null; platform?: PlatformTabId }>()
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'updated'): void }>()
|
||||
|
||||
const form = reactive<EditUserForm>({ uid: 0, username: '', password: '', role: 'normal', columnIds: [], originalRole: '', expiresAt: '', jdPublishQuota: 5000, platform: 'amazon' })
|
||||
const errors = reactive<EditUserFormErrors>({})
|
||||
const busy = ref(false)
|
||||
const loadingAuth = ref(false)
|
||||
/** 授权是否已成功加载:未就绪时保存会把空 columnIds 提交为“清空授权”,必须拦住。 */
|
||||
const authReady = ref(false)
|
||||
/** 公司超管目标:角色单选隐藏(请求体也不带 role),只允许改密码/到期时间/菜单。 */
|
||||
const targetIsCompanySuperAdmin = computed(() => (props.user?.role || '').trim().toLowerCase() === 'company_super_admin')
|
||||
/** 上架上限只属京东口径(用户 2026-11-17:「只要在京东这边用户编辑里加就行,不需要在亚马逊那边」):
|
||||
* 亚马逊侧隐藏该项,且校验与下发都不带 quota——字段留后端不动。 */
|
||||
const includeQuota = computed(() => props.platform === 'jd')
|
||||
/** 公司超管目标的角色单选是隐藏的(改完仍是 company_super_admin),到期时间照旧可改;
|
||||
* 管理员改成普通账号时这一项消失,保存按「清空」下发(见 user-edit-model 的 roleAfter)。 */
|
||||
const expiryEditable = computed(() =>
|
||||
mayCarryOwnExpiry(targetIsCompanySuperAdmin.value ? 'company_super_admin' : form.role),
|
||||
)
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(open) => {
|
||||
if (!open || !props.user) return
|
||||
const base = fillEditUserForm(props.user)
|
||||
form.uid = base.uid
|
||||
form.username = base.username
|
||||
form.password = ''
|
||||
form.role = base.role
|
||||
form.columnIds = []
|
||||
form.originalRole = base.originalRole
|
||||
form.expiresAt = base.expiresAt
|
||||
form.jdPublishQuota = base.jdPublishQuota
|
||||
form.platform = base.platform
|
||||
errors.jdPublishQuota = undefined
|
||||
errors.password = undefined
|
||||
authReady.value = false
|
||||
void refreshAuth()
|
||||
},
|
||||
)
|
||||
|
||||
async function refreshAuth(): Promise<void> {
|
||||
if (!props.user) return
|
||||
loadingAuth.value = true
|
||||
try {
|
||||
const { checkedIds } = await loadUserMenuAuth(props.user.id, props.companyId)
|
||||
form.columnIds = checkedIds
|
||||
authReady.value = true
|
||||
} catch (error) {
|
||||
// 加载失败保持 authReady=false:保存按钮禁用,避免以空数组整树清空该用户授权。
|
||||
authReady.value = false
|
||||
showAdminFeedback(actionableErrorText(error), 'error')
|
||||
} finally {
|
||||
loadingAuth.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
|
||||
async function save(): Promise<void> {
|
||||
if (!authReady.value) {
|
||||
showAdminFeedback('菜单权限尚未加载完成,请稍后重试', 'error')
|
||||
return
|
||||
}
|
||||
const { valid, errors: errs } = validateEditUserForm(form, { includeQuota: includeQuota.value })
|
||||
Object.assign(errors, errs)
|
||||
if (!valid) return
|
||||
busy.value = true
|
||||
try {
|
||||
await submitEditUser(form, { includeQuota: includeQuota.value })
|
||||
showAdminFeedback('更新成功', 'success')
|
||||
emit('updated')
|
||||
close()
|
||||
} catch (error) {
|
||||
showAdminFeedback(actionableErrorText(error), 'error')
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="modelValue"
|
||||
title="编辑用户"
|
||||
width="640px"
|
||||
:close-on-click-modal="false"
|
||||
destroy-on-close
|
||||
@update:model-value="(v: boolean) => emit('update:modelValue', v)"
|
||||
>
|
||||
<el-form label-position="top" @submit.prevent>
|
||||
<el-form-item label="用户名">
|
||||
<el-input :model-value="form.username" readonly />
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码(不修改可留空)" :error="errors.password">
|
||||
<el-input
|
||||
v-model="form.password"
|
||||
type="password"
|
||||
show-password
|
||||
autocomplete="new-password"
|
||||
placeholder="留空则不修改密码"
|
||||
@input="errors.password = undefined"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="operatorSuper && !targetIsCompanySuperAdmin" label="角色">
|
||||
<el-radio-group v-model="form.role">
|
||||
<el-radio-button value="normal">普通账号</el-radio-button>
|
||||
<el-radio-button value="admin">管理员</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="targetIsCompanySuperAdmin" label="角色">
|
||||
<el-input model-value="公司超级管理员" readonly />
|
||||
</el-form-item>
|
||||
<el-form-item label="所属平台">
|
||||
<el-radio-group v-model="form.platform">
|
||||
<el-radio-button value="amazon">亚马逊</el-radio-button>
|
||||
<el-radio-button value="jd">京东</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="expiryEditable" label="到期时间(清空 = 永不过期;到期后该账号及其名下账号将停用)">
|
||||
<el-date-picker
|
||||
v-model="form.expiresAt"
|
||||
type="datetime"
|
||||
placeholder="选择到期时间"
|
||||
value-format="YYYY-MM-DD HH:mm:ss"
|
||||
format="YYYY-MM-DD HH:mm"
|
||||
style="width: 240px"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="includeQuota && (targetIsCompanySuperAdmin || form.role === 'admin')" label="京东上架额度(0 表示不限)" :error="errors.jdPublishQuota">
|
||||
<el-input-number v-model="form.jdPublishQuota" :min="0" :max="2147483647" :precision="0" />
|
||||
</el-form-item>
|
||||
<el-form-item v-if="props.user && props.user.creatorUsername" label="所属管理员">
|
||||
<el-input :model-value="props.user.creatorUsername" readonly />
|
||||
</el-form-item>
|
||||
<el-form-item label="菜单权限(勾选上级菜单会继承全部子菜单)">
|
||||
<div class="auth-tree-box">
|
||||
<UserMenuAuthTree v-model:checked="form.columnIds" :company-id="props.companyId" />
|
||||
<div v-if="loadingAuth" class="auth-loading">菜单权限加载中…</div>
|
||||
<div v-else-if="!authReady" class="auth-loading auth-loading-error">
|
||||
菜单权限加载失败,保存已禁用;请关闭后重试
|
||||
</div>
|
||||
</div>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="close">取消</el-button>
|
||||
<el-button type="primary" :loading="busy" :disabled="!authReady" @click="save">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.auth-tree-box {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
border: 1px solid var(--el-border-color);
|
||||
border-radius: 9px;
|
||||
padding: 8px;
|
||||
}
|
||||
.auth-loading {
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--admin-muted);
|
||||
}
|
||||
.auth-loading-error {
|
||||
color: var(--el-color-danger);
|
||||
}
|
||||
</style>
|
||||
@@ -1,158 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import type { AdminUser } from '@/types/admin'
|
||||
import type { PlatformTabId } from '@/config/platform-scope'
|
||||
import {
|
||||
eligibleGroupMembers,
|
||||
groupMemberCandidateHint,
|
||||
validateShopGroupForm,
|
||||
type ShopGroupItem,
|
||||
} from './shop-group-model'
|
||||
import { createShopGroup, updateShopGroup } from './shop-group-api'
|
||||
import { fetchUserList } from '@/api/users'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { actionableErrorText } from '@/components/admin-feedback'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
|
||||
const props = defineProps<{ modelValue: boolean; group: ShopGroupItem | null; operatorSuper?: boolean; platform?: PlatformTabId }>()
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'saved'): void }>()
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const groupName = ref('')
|
||||
/** 所属平台(V206):新建默认当前平台 tab,编辑回填分组原值,单选可翻档。 */
|
||||
const groupPlatform = ref<PlatformTabId>('amazon')
|
||||
const memberIds = ref<number[]>([])
|
||||
const errorText = ref('')
|
||||
const busy = ref(false)
|
||||
const users = ref<AdminUser[]>([])
|
||||
|
||||
/** 组长:新建=当前登录用户;编辑=分组原组长(不可改,只读展示)。 */
|
||||
const leaderUserId = computed<number | null>(() =>
|
||||
props.group ? (props.group.leaderUserId ?? null) : (session.user?.id ?? null),
|
||||
)
|
||||
const leaderUsername = computed<string>(() =>
|
||||
props.group ? (props.group.leaderUsername || '') : (session.user?.username || '当前登录用户'),
|
||||
)
|
||||
const operatorRole = computed<string>(() => session.user?.role || '')
|
||||
|
||||
/** 组员候选:按组长归属过滤(超管全量、非超管仅本组长创建的普通账号)。 */
|
||||
const memberCandidates = computed(() =>
|
||||
eligibleGroupMembers(users.value, leaderUserId.value, operatorRole.value),
|
||||
)
|
||||
const candidateHint = computed(() => groupMemberCandidateHint(memberCandidates.value.length, operatorRole.value))
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(open) => {
|
||||
if (!open) return
|
||||
groupName.value = ''
|
||||
memberIds.value = []
|
||||
errorText.value = ''
|
||||
if (props.group) {
|
||||
groupName.value = props.group.name
|
||||
memberIds.value = props.group.memberUserIds ?? []
|
||||
groupPlatform.value = props.group.platform === 'jd' ? 'jd' : 'amazon'
|
||||
} else {
|
||||
groupPlatform.value = props.platform ?? 'amazon'
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
async function loadCandidates(): Promise<void> {
|
||||
try {
|
||||
// 对齐 admin.js loadUserOptions:page=1&page_size=999 全量拉取,避免归属过滤漏人。
|
||||
// company_id 必带:不带时后端对站点超管返回全平台账号,别家公司的人就会出现在本公司分组的候选里。
|
||||
// 取的是**组长自己那家**(当前登录用户),不是公司 tab——新建时组长就是操作者本人,
|
||||
// 按 tab 取人会在超管停在别家 tab 时列出那家的人,保存时被后端"只能添加组长本公司的账号"打回。
|
||||
const page = await fetchUserList({ page: 1, pageSize: 999, companyId: session.user?.companyId ?? null })
|
||||
users.value = page.items
|
||||
} catch (error) {
|
||||
showAdminFeedback(actionableErrorText(error), 'error')
|
||||
}
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
|
||||
async function save(): Promise<void> {
|
||||
const errs = validateShopGroupForm(groupName.value)
|
||||
errorText.value = errs.groupName || ''
|
||||
if (errorText.value) return
|
||||
busy.value = true
|
||||
try {
|
||||
if (props.group) {
|
||||
await updateShopGroup(props.group.id, groupName.value, memberIds.value, groupPlatform.value)
|
||||
showAdminFeedback('更新成功', 'success')
|
||||
} else {
|
||||
// 对齐 admin:组长恒为当前登录用户,提交 createdBy=当前用户 id。
|
||||
const operatorId = session.user?.id ?? 0
|
||||
if (!operatorId) {
|
||||
showAdminFeedback('无法获取当前登录用户,请重新登录', 'error')
|
||||
return
|
||||
}
|
||||
await createShopGroup(groupName.value, memberIds.value, operatorId, groupPlatform.value)
|
||||
showAdminFeedback('创建成功', 'success')
|
||||
}
|
||||
emit('saved')
|
||||
close()
|
||||
} catch (error) {
|
||||
showAdminFeedback(actionableErrorText(error), 'error')
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadCandidates)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="modelValue"
|
||||
:title="group ? '编辑分组' : '新建分组'"
|
||||
width="600px"
|
||||
:close-on-click-modal="false"
|
||||
destroy-on-close
|
||||
@update:model-value="(v: boolean) => emit('update:modelValue', v)"
|
||||
>
|
||||
<el-form label-position="top" @submit.prevent>
|
||||
<el-form-item label="分组名称" :error="errorText || undefined">
|
||||
<el-input v-model="groupName" placeholder="请输入分组名称" />
|
||||
</el-form-item>
|
||||
<el-form-item label="所属平台">
|
||||
<el-radio-group v-model="groupPlatform">
|
||||
<el-radio-button value="amazon">亚马逊</el-radio-button>
|
||||
<el-radio-button value="jd">京东</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="组长">
|
||||
<el-input :model-value="leaderUsername" readonly placeholder="当前登录用户" />
|
||||
</el-form-item>
|
||||
<el-form-item label="组员">
|
||||
<el-select
|
||||
v-model="memberIds"
|
||||
multiple
|
||||
filterable
|
||||
collapse-tags
|
||||
placeholder="选择组员(普通账号)"
|
||||
style="width: 100%"
|
||||
>
|
||||
<el-option v-for="u in memberCandidates" :key="u.id" :label="u.username" :value="u.id" />
|
||||
</el-select>
|
||||
<div class="candidate-hint">{{ candidateHint }}(共 {{ memberCandidates.length }} 名)</div>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="close">取消</el-button>
|
||||
<el-button type="primary" :loading="busy" @click="save">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.candidate-hint {
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--admin-muted);
|
||||
}
|
||||
</style>
|
||||
@@ -1,383 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
/** 分组管理页 · 像素复刻旧版 admin.html panel-group-manage(自绘:顶部数据权限分组摘要 chips + 分组列表表格 + 新建分组;全量无分页同旧版)。
|
||||
* script 逻辑沿用现有 Vue 实现;编辑器保留现有组件。 */
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { usePlatformTabStore } from '@/stores/platform-tab'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import { deleteShopGroup, fetchShopGroups } from './shop-group-api'
|
||||
import type { ShopGroupItem } from './shop-group-model'
|
||||
import GroupEditorDialog from './GroupEditorDialog.vue'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
// 平台 tab(V206):分组列表按当前平台过滤,新建默认落当前平台。
|
||||
const platformTab = usePlatformTabStore()
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<ShopGroupItem[]>([])
|
||||
const editorVisible = ref(false)
|
||||
const editingGroup = ref<ShopGroupItem | null>(null)
|
||||
const isSuperAdmin = computed(() => session.isSuperAdmin)
|
||||
const currentUserId = computed(() => session.user?.id ?? null)
|
||||
/** 筛选:分组名称/组长 模糊过滤(用户要求账户域子菜单补筛选条件)。 */
|
||||
const filterKeyword = ref('')
|
||||
const filterLeader = ref('')
|
||||
const filteredRows = computed(() => {
|
||||
const kw = (filterKeyword.value || '').trim().toLowerCase()
|
||||
const ldr = (filterLeader.value || '').trim().toLowerCase()
|
||||
if (!kw && !ldr) return rows.value
|
||||
return rows.value.filter((g) => {
|
||||
const nameOk = !kw || (g.name || '').toLowerCase().includes(kw)
|
||||
const leaderOk = !ldr || (g.leaderUsername || '').toLowerCase().includes(ldr)
|
||||
return nameOk && leaderOk
|
||||
})
|
||||
})
|
||||
/** 全站分页统一:分组列表客户端分页(10/20/50/100)。 */
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const pagedGroups = computed(() => filteredRows.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||
function changeGroupPage(p: number) { page.value = p }
|
||||
function changeGroupSize(size: number) { pageSize.value = size; page.value = 1 }
|
||||
|
||||
function canEditOf(group: ShopGroupItem): boolean {
|
||||
if (isSuperAdmin.value) return true
|
||||
return currentUserId.value != null && group.leaderUserId != null && currentUserId.value === group.leaderUserId
|
||||
}
|
||||
|
||||
async function loadGroups() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
rows.value = await fetchShopGroups(companyTab.requestCompanyId, platformTab.active)
|
||||
} catch (error) {
|
||||
loadFailure.value = error instanceof Error ? error.message : '数据权限分组加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 切公司 = 重新取数(G1 的 pageFiles 断言盯着这一条)。
|
||||
watch(() => companyTab.activeId, () => void loadGroups())
|
||||
|
||||
// 切平台 tab(V206)= 重新取数:分组归属按平台分列,两 tab 各看各的分组。
|
||||
watch(() => platformTab.active, () => {
|
||||
page.value = 1
|
||||
void loadGroups()
|
||||
})
|
||||
|
||||
function openCreate() {
|
||||
editingGroup.value = null
|
||||
editorVisible.value = true
|
||||
}
|
||||
|
||||
function openEdit(group: ShopGroupItem) {
|
||||
if (!canEditOf(group)) return
|
||||
editingGroup.value = group
|
||||
editorVisible.value = true
|
||||
}
|
||||
|
||||
async function removeGroup(group: ShopGroupItem) {
|
||||
const ok = await openAdminConfirm({ message: `确定删除分组“${group.name}”吗?`, danger: true })
|
||||
if (!ok) return
|
||||
try {
|
||||
await deleteShopGroup(group.id)
|
||||
ElMessage.success('删除成功')
|
||||
await loadGroups()
|
||||
} catch (error) {
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadGroups)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="groups-view">
|
||||
<section class="panel-box">
|
||||
<div class="groups-head">
|
||||
<h3>分组列表</h3>
|
||||
<button class="btn" type="button" @click="openCreate">新建分组</button>
|
||||
</div>
|
||||
|
||||
<div class="form-row groups-filter-row">
|
||||
<div class="form-group" style="min-width: 200px">
|
||||
<label>分组名称</label>
|
||||
<input v-model="filterKeyword" type="text" placeholder="输入分组名称" @keyup.enter="filterKeyword = filterKeyword" />
|
||||
</div>
|
||||
<div class="form-group" style="min-width: 180px">
|
||||
<label>组长</label>
|
||||
<input v-model="filterLeader" type="text" placeholder="输入组长用户名" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadGroups" />
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 58px">序号</th>
|
||||
<th style="width: 16%">分组名称</th>
|
||||
<th style="width: 12%">组长</th>
|
||||
<th style="width: 10%">组员数量</th>
|
||||
<th>组员</th>
|
||||
<th style="width: 16%">创建时间</th>
|
||||
<th style="width: 16%">修改时间</th>
|
||||
<th style="width: 160px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-if="filteredRows.length">
|
||||
<tr v-for="(group, index) in pagedGroups" :key="group.id">
|
||||
<td>{{ index + 1 }}</td>
|
||||
<td>{{ group.name }}</td>
|
||||
<td>{{ group.leaderUsername || '-' }}</td>
|
||||
<td>{{ group.memberCount ?? (group.memberUsernames?.length ?? 0) }}</td>
|
||||
<td>
|
||||
<div class="shop-group-members">
|
||||
<span v-for="name in group.memberUsernames" :key="name" class="shop-group-member-chip">{{ name }}</span>
|
||||
<span v-if="!group.memberUsernames.length" class="member-none">无</span>
|
||||
</div>
|
||||
</td>
|
||||
<td>{{ formatDateTime(group.createdAt) }}</td>
|
||||
<td>{{ formatDateTime(group.updatedAt || group.createdAt) }}</td>
|
||||
<td class="ops-cell">
|
||||
<template v-if="canEditOf(group)">
|
||||
<button class="btn btn-sm" type="button" @click="openEdit(group)">编辑</button>
|
||||
<button class="btn btn-sm btn-danger" type="button" @click="removeGroup(group)">删除</button>
|
||||
</template>
|
||||
<span v-else class="member-none">-</span>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td colspan="8" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td colspan="8" class="empty-tip">{{ filterKeyword || filterLeader ? '暂无匹配分组' : '暂无分组' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<OldPagination v-if="filteredRows.length > 0" :total="filteredRows.length" :page="page" :page-size="pageSize" @change="changeGroupPage" @size-change="changeGroupSize" />
|
||||
</section>
|
||||
|
||||
<GroupEditorDialog
|
||||
v-model="editorVisible"
|
||||
:group="editingGroup"
|
||||
:operator-super="isSuperAdmin"
|
||||
:platform="platformTab.active"
|
||||
@saved="loadGroups"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 像素复刻旧版 admin.html panel-group-manage(蓝白末层)。 */
|
||||
.groups-view {
|
||||
font-family: inherit;
|
||||
color: #24384d;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
.form-box,
|
||||
.panel-box {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 20px 22px 24px;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(145deg, #ffffff, #f9fbfd);
|
||||
box-shadow: 0 1px 2px rgba(39, 67, 94, 0.04), 0 14px 30px -24px rgba(39, 67, 94, 0.28);
|
||||
}
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
color: #24384d;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
.groups-filter-row {
|
||||
margin: 0 0 16px;
|
||||
}
|
||||
.groups-filter-row .form-group {
|
||||
flex: 1 1 200px;
|
||||
}
|
||||
.form-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 14px 18px;
|
||||
}
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.form-group label {
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.form-group input,
|
||||
.form-group select {
|
||||
min-width: 0;
|
||||
min-height: 42px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
color-scheme: light;
|
||||
outline: none;
|
||||
transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
|
||||
}
|
||||
.form-group input:hover,
|
||||
.form-group select:hover {
|
||||
border-color: #9fb7cd;
|
||||
}
|
||||
.form-group input:focus,
|
||||
.form-group select:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
.groups-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 42px;
|
||||
padding: 9px 18px;
|
||||
border: 1px solid #4f78a5;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 8px 18px -14px rgba(79, 120, 165, 0.72);
|
||||
transition: background 160ms ease, box-shadow 160ms ease, transform 120ms ease;
|
||||
}
|
||||
.btn:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #7094ba, #5d83ac);
|
||||
box-shadow: 0 11px 22px -14px rgba(79, 120, 165, 0.8);
|
||||
}
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.btn-danger {
|
||||
background: linear-gradient(135deg, #c06d77, #b35f6a);
|
||||
border-color: #b35f6a;
|
||||
}
|
||||
.btn-danger:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #cb7c84, #b96570);
|
||||
}
|
||||
.btn-sm {
|
||||
min-height: 36px;
|
||||
padding: 7px 12px;
|
||||
}
|
||||
.table-scroll {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 10px;
|
||||
background: #ffffff;
|
||||
}
|
||||
.table-scroll table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
}
|
||||
.table-scroll th,
|
||||
.table-scroll td {
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
font-size: 13.5px;
|
||||
line-height: 1.5;
|
||||
border-bottom: 1px solid #e0e8ef;
|
||||
vertical-align: middle;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.table-scroll th {
|
||||
background: #edf4fa;
|
||||
color: #4e6479;
|
||||
border-bottom-color: #d5e1eb;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.4px;
|
||||
}
|
||||
.table-scroll tbody tr:hover td {
|
||||
background: #f1f7fb;
|
||||
}
|
||||
.table-scroll tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.table-scroll td {
|
||||
white-space: normal;
|
||||
word-break: break-word;
|
||||
}
|
||||
.shop-group-members {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
max-height: 96px;
|
||||
overflow-y: auto;
|
||||
padding-right: 4px;
|
||||
}
|
||||
.shop-group-member-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
max-width: 150px;
|
||||
padding: 3px 9px;
|
||||
border-radius: 999px;
|
||||
background: #e7f0f8;
|
||||
color: #2f5d8b;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.member-none,
|
||||
.member-more {
|
||||
color: #8293a5;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.ops-cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
white-space: nowrap;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.empty-tip {
|
||||
padding: 44px 24px;
|
||||
text-align: center;
|
||||
color: #8293a5;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,569 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
/** 菜单权限配置页 · 像素复刻旧版 admin.html panel-columns(自绘:面板头+新增菜单、拖拽手柄 ⠿、树形缩进+└、旧式表格、全量无分页同旧版)。
|
||||
* script 逻辑沿用现有 Vue 实现(拖拽分组/落点/重排保存、弹窗表单)。 */
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { createMenu, deleteMenu, loadMenuManageTree, reorderMenus, updateMenu } from './menu-manage-api'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
import {
|
||||
MENU_TYPE_OPTIONS,
|
||||
createMenuForm,
|
||||
flattenMenuNodes,
|
||||
menuDeleteReason,
|
||||
menuFormFromNode,
|
||||
menuParentCandidates,
|
||||
menuParentChangeReason,
|
||||
menuSiblingGroupKey,
|
||||
menuTypeLabel,
|
||||
nextSiblingSort,
|
||||
siblingOrderAfterDrop,
|
||||
validateMenuManageForm,
|
||||
type MenuManageForm,
|
||||
type MenuManageNode,
|
||||
} from './menu-manage-model'
|
||||
|
||||
/** 树行视图:展平 + 深度(缩进与 └ 前缀)。 */
|
||||
interface MenuRow extends MenuManageNode {
|
||||
depth: number
|
||||
}
|
||||
|
||||
const companyTab = useCompanyTabStore()
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<MenuManageNode[]>([])
|
||||
/** 筛选:菜单名称/类型(用户要求账户域子菜单补筛选条件)。 */
|
||||
const filterName = ref('')
|
||||
const filterType = ref('')
|
||||
const filteredMenuRows = computed<MenuRow[]>(() => {
|
||||
const kw = (filterName.value || '').trim().toLowerCase()
|
||||
const type = filterType.value || ''
|
||||
return menuRows.value.filter((row) => {
|
||||
const nameOk = !kw || (row.name || '').toLowerCase().includes(kw)
|
||||
const typeOk = !type || row.menuType === type
|
||||
return nameOk && typeOk
|
||||
})
|
||||
})
|
||||
/** 全站分页统一:菜单树展平行客户端分页(10/20/50/100)。 */
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const pagedMenuRows = computed(() => filteredMenuRows.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||
function changeMenuPage(p: number) { page.value = p }
|
||||
function changeMenuSize(size: number) { pageSize.value = size; page.value = 1 }
|
||||
/** 展平视图:前序 + depth。 */
|
||||
const menuRows = computed<MenuRow[]>(() => {
|
||||
const out: MenuRow[] = []
|
||||
const walk = (list: MenuManageNode[], depth: number) => {
|
||||
for (const node of list) {
|
||||
out.push({ ...node, depth })
|
||||
if (node.children?.length) walk(node.children, depth + 1)
|
||||
}
|
||||
}
|
||||
walk(rows.value, 0)
|
||||
return out
|
||||
})
|
||||
const createVisible = ref(false)
|
||||
const saving = ref(false)
|
||||
const editingNode = ref<MenuManageNode | null>(null)
|
||||
const menuForm = reactive<MenuManageForm>(createMenuForm(null, 0))
|
||||
const parentOptions = computed(() => menuParentCandidates(rows.value, menuForm.menuType))
|
||||
const dialogTitle = computed(() => (editingNode.value ? '编辑菜单' : '新增菜单'))
|
||||
/** 节点 id -> 名称,供「上级菜单」列展示。 */
|
||||
const nameById = computed(() => {
|
||||
const map = new Map<number, string>()
|
||||
for (const node of flattenMenuNodes(rows.value)) map.set(node.id, node.name)
|
||||
return map
|
||||
})
|
||||
|
||||
/** 拖拽状态:同"菜单类型+父级"分组内才可落位(对齐 admin.js columnDragState)。 */
|
||||
const dragState = ref<{ id: number; groupKey: string; menuType: string } | null>(null)
|
||||
|
||||
function parentNameOf(node: MenuManageNode): string {
|
||||
if (node.parentId == null) return '-'
|
||||
return nameById.value.get(node.parentId) ?? `#${node.parentId}`
|
||||
}
|
||||
|
||||
async function loadMenus() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
rows.value = await loadMenuManageTree(companyTab.requestCompanyId)
|
||||
} catch (error) {
|
||||
loadFailure.value = error instanceof Error ? error.message : '菜单列表加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
editingNode.value = null
|
||||
Object.assign(menuForm, createMenuForm(null, nextSiblingSort(rows.value, null)))
|
||||
createVisible.value = true
|
||||
}
|
||||
|
||||
function openEdit(node: MenuManageNode) {
|
||||
editingNode.value = node
|
||||
Object.assign(menuForm, menuFormFromNode(node))
|
||||
createVisible.value = true
|
||||
}
|
||||
|
||||
/** 菜单类型切换时:当前父菜单不属于新类型则重置为根。 */
|
||||
function onMenuTypeChange(): void {
|
||||
const candidates = menuParentCandidates(rows.value, menuForm.menuType)
|
||||
if (menuForm.parentId != null && !candidates.some((node) => node.id === menuForm.parentId)) {
|
||||
menuForm.parentId = null
|
||||
}
|
||||
}
|
||||
|
||||
function onDragStart(event: DragEvent, node: MenuManageNode): void {
|
||||
dragState.value = { id: node.id, groupKey: menuSiblingGroupKey(node), menuType: node.menuType }
|
||||
if (event.dataTransfer) {
|
||||
event.dataTransfer.effectAllowed = 'move'
|
||||
try {
|
||||
event.dataTransfer.setData('text/plain', String(node.id))
|
||||
} catch {
|
||||
// 某些浏览器 setData 受限,忽略即可。
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onDragEnd(): void {
|
||||
dragState.value = null
|
||||
}
|
||||
|
||||
function onDragOver(event: DragEvent, node: MenuManageNode): void {
|
||||
const state = dragState.value
|
||||
if (!state || state.groupKey !== menuSiblingGroupKey(node) || state.id === node.id) return
|
||||
event.preventDefault()
|
||||
if (event.dataTransfer) event.dataTransfer.dropEffect = 'move'
|
||||
}
|
||||
|
||||
async function onDrop(event: DragEvent, target: MenuManageNode): Promise<void> {
|
||||
const state = dragState.value
|
||||
dragState.value = null
|
||||
if (!state || state.groupKey !== menuSiblingGroupKey(target) || state.id === target.id) return
|
||||
event.preventDefault()
|
||||
const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
|
||||
const placeAfter = event.clientY - rect.top > rect.height / 2
|
||||
const groupIds = flattenMenuNodes(rows.value)
|
||||
.filter((node) => menuSiblingGroupKey(node) === state.groupKey)
|
||||
.map((node) => node.id)
|
||||
const next = siblingOrderAfterDrop(groupIds, state.id, target.id, placeAfter)
|
||||
if (next.join(',') === groupIds.join(',')) return
|
||||
try {
|
||||
await reorderMenus(state.menuType, next)
|
||||
ElMessage.success('排序已保存')
|
||||
await loadMenus()
|
||||
} catch (error) {
|
||||
showAdminFeedback(error instanceof Error ? error.message : '排序保存失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
async function saveMenu() {
|
||||
if (editingNode.value) {
|
||||
const reason = menuParentChangeReason(editingNode.value, menuForm.parentId)
|
||||
if (reason) {
|
||||
ElMessage.warning(reason)
|
||||
return
|
||||
}
|
||||
}
|
||||
const { valid, errors } = validateMenuManageForm(menuForm)
|
||||
if (!valid) {
|
||||
ElMessage.warning(Object.values(errors)[0])
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
try {
|
||||
if (editingNode.value) {
|
||||
await updateMenu(editingNode.value.id, menuForm)
|
||||
ElMessage.success('保存成功')
|
||||
} else {
|
||||
await createMenu(menuForm, companyTab.requestCompanyId)
|
||||
ElMessage.success('创建成功')
|
||||
}
|
||||
createVisible.value = false
|
||||
await loadMenus()
|
||||
} catch (error) {
|
||||
showAdminFeedback(error instanceof Error ? error.message : '保存失败', 'error')
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function removeMenu(node: MenuManageNode) {
|
||||
const reason = menuDeleteReason(node)
|
||||
if (reason) {
|
||||
ElMessage.warning(reason)
|
||||
return
|
||||
}
|
||||
// 对齐旧版:原生 confirm。
|
||||
if (!(await openAdminConfirm({ message: `确定删除菜单“${node.name}”吗?`, danger: true }))) return
|
||||
try {
|
||||
await deleteMenu(node.id)
|
||||
ElMessage.success('删除成功')
|
||||
await loadMenus()
|
||||
} catch (error) {
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
/** 切公司:菜单名称/类型是客户端筛选(在 filteredMenuRows 上筛,不进请求),留着上一家填的值
|
||||
* 就是拿别家的字符串去筛新一家那一套树 ⇒ 首屏「暂无匹配菜单」而输入框里还显示着它;页码回 1
|
||||
* 是因为新一家的行数不同。末尾的 void loadMenus() 才是本页唯一的数据出口。 */
|
||||
watch(() => companyTab.activeId, () => { filterName.value = ''; filterType.value = ''; page.value = 1; void loadMenus() })
|
||||
|
||||
onMounted(loadMenus)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="menus-view">
|
||||
<section class="panel-box">
|
||||
<div class="menus-head">
|
||||
<h3>菜单列表</h3>
|
||||
<button class="btn" type="button" @click="openCreate">新增菜单</button>
|
||||
</div>
|
||||
<p class="columns-drag-tip">拖动每行左侧的手柄可调整同级菜单的显示顺序,松开后自动保存。</p>
|
||||
|
||||
<div class="form-row menus-filter-row">
|
||||
<div class="form-group" style="min-width: 200px">
|
||||
<label>菜单名称</label>
|
||||
<input v-model="filterName" type="text" placeholder="输入菜单名称" />
|
||||
</div>
|
||||
<div class="form-group" style="min-width: 160px">
|
||||
<label>菜单类型</label>
|
||||
<select v-model="filterType">
|
||||
<option value="">全部</option>
|
||||
<option value="admin">后台</option>
|
||||
<option value="app">软件</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadMenus" />
|
||||
<div class="table-scroll columns-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="column-drag-cell"><span class="visually-hidden">排序</span></th>
|
||||
<th style="width: 60px">ID</th>
|
||||
<th style="width: 200px">菜单名称</th>
|
||||
<th style="width: 100px">菜单类型</th>
|
||||
<th style="width: 120px">上级菜单</th>
|
||||
<th style="width: 170px">创建时间</th>
|
||||
<th style="width: 170px">更新时间</th>
|
||||
<th style="width: 170px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-if="filteredMenuRows.length">
|
||||
<tr
|
||||
v-for="row in pagedMenuRows"
|
||||
:key="row.id"
|
||||
:class="{ 'is-column-dragging': dragState?.id === row.id }"
|
||||
@dragover="onDragOver($event, row)"
|
||||
@drop="onDrop($event, row)"
|
||||
>
|
||||
<td class="column-drag-cell">
|
||||
<span
|
||||
class="column-drag-handle"
|
||||
draggable="true"
|
||||
role="button"
|
||||
:title="`拖动调整“${row.name}”的顺序`"
|
||||
@dragstart="onDragStart($event, row)"
|
||||
@dragend="onDragEnd"
|
||||
>⠿</span>
|
||||
</td>
|
||||
<td>{{ row.id }}</td>
|
||||
<td class="name-cell">
|
||||
<span v-if="row.depth > 0" class="column-child-mark" :style="{ marginLeft: `${row.depth * 16}px` }">└</span>
|
||||
<span class="menu-name-text">{{ row.name }}</span>
|
||||
</td>
|
||||
<td><span class="menu-type-text">{{ menuTypeLabel(row.menuType) }}</span></td>
|
||||
<td>{{ parentNameOf(row) }}</td>
|
||||
<td>{{ formatDateTime(row.createdAt) }}</td>
|
||||
<td>{{ formatDateTime(row.updatedAt) }}</td>
|
||||
<td class="ops-cell">
|
||||
<button class="btn btn-sm" type="button" @click="openEdit(row)">编辑</button>
|
||||
<button
|
||||
class="btn btn-sm btn-danger"
|
||||
type="button"
|
||||
:disabled="menuDeleteReason(row) !== undefined"
|
||||
:title="menuDeleteReason(row) || undefined"
|
||||
@click="removeMenu(row)"
|
||||
>
|
||||
删除
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td colspan="8" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td colspan="8" class="empty-tip">{{ filterName || filterType ? '暂无匹配菜单' : '暂无菜单,请先在上方新增' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<OldPagination v-if="filteredMenuRows.length > 0" :total="filteredMenuRows.length" :page="page" :page-size="pageSize" @change="changeMenuPage" @size-change="changeMenuSize" />
|
||||
</section>
|
||||
|
||||
<el-dialog v-model="createVisible" :title="dialogTitle" width="520px">
|
||||
<el-form label-width="96px">
|
||||
<el-form-item label="菜单名称">
|
||||
<el-input v-model="menuForm.name" placeholder="如:用户管理" />
|
||||
</el-form-item>
|
||||
<el-form-item label="菜单类型">
|
||||
<el-select filterable v-model="menuForm.menuType" style="width: 100%" @change="onMenuTypeChange">
|
||||
<el-option v-for="opt in MENU_TYPE_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="父菜单">
|
||||
<el-select filterable v-model="menuForm.parentId" clearable placeholder="无(一级菜单)" style="width: 100%">
|
||||
<el-option
|
||||
v-for="node in parentOptions"
|
||||
:key="node.id"
|
||||
:label="node.name"
|
||||
:value="node.id"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="排序">
|
||||
<el-input-number v-model="menuForm.sortOrder" :min="0" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="createVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="saveMenu">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 像素复刻旧版 admin.html panel-columns(蓝白末层)。 */
|
||||
.menus-view {
|
||||
font-family: inherit;
|
||||
color: #24384d;
|
||||
}
|
||||
.panel-box {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 20px 22px 24px;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(145deg, #ffffff, #f9fbfd);
|
||||
box-shadow: 0 1px 2px rgba(39, 67, 94, 0.04), 0 14px 30px -24px rgba(39, 67, 94, 0.28);
|
||||
}
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
color: #24384d;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
.menus-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.columns-drag-tip {
|
||||
margin: 10px 0 16px;
|
||||
font-size: 13px;
|
||||
color: #5b6f83;
|
||||
}
|
||||
.menus-filter-row {
|
||||
margin: 0 0 16px;
|
||||
}
|
||||
.form-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 14px 18px;
|
||||
}
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.form-group label {
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.form-group input,
|
||||
.form-group select {
|
||||
min-width: 0;
|
||||
min-height: 42px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
color-scheme: light;
|
||||
outline: none;
|
||||
transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
|
||||
}
|
||||
.form-group input:hover,
|
||||
.form-group select:hover {
|
||||
border-color: #9fb7cd;
|
||||
}
|
||||
.form-group input:focus,
|
||||
.form-group select:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 42px;
|
||||
padding: 9px 18px;
|
||||
border: 1px solid #4f78a5;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 8px 18px -14px rgba(79, 120, 165, 0.72);
|
||||
transition: background 160ms ease, box-shadow 160ms ease, transform 120ms ease;
|
||||
}
|
||||
.btn:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #7094ba, #5d83ac);
|
||||
box-shadow: 0 11px 22px -14px rgba(79, 120, 165, 0.8);
|
||||
}
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.btn-danger {
|
||||
background: linear-gradient(135deg, #c06d77, #b35f6a);
|
||||
border-color: #b35f6a;
|
||||
}
|
||||
.btn-danger:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #cb7c84, #b96570);
|
||||
}
|
||||
.btn-sm {
|
||||
min-height: 36px;
|
||||
padding: 7px 12px;
|
||||
}
|
||||
.table-scroll {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 10px;
|
||||
background: #ffffff;
|
||||
}
|
||||
.table-scroll table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
}
|
||||
.columns-table-scroll > table {
|
||||
min-width: 860px;
|
||||
}
|
||||
.table-scroll th,
|
||||
.table-scroll td {
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
font-size: 13.5px;
|
||||
line-height: 1.5;
|
||||
border-bottom: 1px solid #e0e8ef;
|
||||
vertical-align: middle;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.table-scroll th {
|
||||
background: #edf4fa;
|
||||
color: #4e6479;
|
||||
border-bottom-color: #d5e1eb;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.4px;
|
||||
}
|
||||
.table-scroll tbody tr:hover td {
|
||||
background: #f1f7fb;
|
||||
}
|
||||
.table-scroll tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.column-drag-cell {
|
||||
width: 48px;
|
||||
}
|
||||
.column-drag-handle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 9px;
|
||||
background: none;
|
||||
color: #93a6b8;
|
||||
font-size: 15px;
|
||||
line-height: 1;
|
||||
cursor: grab;
|
||||
user-select: none;
|
||||
}
|
||||
.column-drag-handle:hover {
|
||||
border-color: #cbd9e6;
|
||||
background: #eef4fa;
|
||||
color: #2f5d8b;
|
||||
}
|
||||
.column-drag-handle:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
tr.is-column-dragging td {
|
||||
opacity: 0.45;
|
||||
}
|
||||
.column-child-mark {
|
||||
margin-right: 6px;
|
||||
color: #9fb1c2;
|
||||
}
|
||||
.menu-name-text {
|
||||
font-weight: 500;
|
||||
}
|
||||
.menu-type-text {
|
||||
color: #5b6f83;
|
||||
}
|
||||
.ops-cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
white-space: nowrap;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.empty-tip {
|
||||
padding: 44px 24px;
|
||||
text-align: center;
|
||||
color: #8293a5;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.visually-hidden {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
margin: -1px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
clip: rect(0 0 0 0);
|
||||
clip-path: inset(50%);
|
||||
}
|
||||
</style>
|
||||
@@ -1,248 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { saveUserSecretModule } from '@/api/user-secrets'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { actionableErrorText } from '@/components/admin-feedback'
|
||||
import {
|
||||
PROXY_MODULE_KEY,
|
||||
buildProxyEntryPayload,
|
||||
emptyProxyEntryDraft,
|
||||
validateProxyEntry,
|
||||
type ProxyEntryDraft,
|
||||
} from './user-secret-model.ts'
|
||||
|
||||
/**
|
||||
* 后台代填/改代理(2026-11-02 脱敏后重做的交互)。
|
||||
*
|
||||
* 旧交互是 `window.prompt` 预填 `row.proxy.full` 整条提取链接——后端把这条读路套上
|
||||
* `SecretMasking.maskProxy` 之后 `full` 恒空,预填必然是空的,照旧保存等于把空串顶上去、
|
||||
* 或让管理员去别处翻原文。现在收**账密**、链接在本机现拼现发:
|
||||
* - 青果:填 Authkey + Authpwd,`composeQingguoLink` 拼(青果产品页没有可复制的链接);
|
||||
* - 极客:填极客自己的提取链接(它有可复制的链接)。
|
||||
* 拼好的链接是一次性写载荷,只进 PUT 请求体:不回显、不回填、不进 tooltip、不给复制/导出旁路;
|
||||
* 保存成功即清空输入位,重开必然要从头再填(这是脱敏的应然后果,界面直接把它说出来)。
|
||||
*/
|
||||
const props = defineProps<{
|
||||
modelValue: boolean
|
||||
userId: number | null
|
||||
username: string
|
||||
/** 后端已登记的供应商(只是预选中的单选框,不是凭据)。 */
|
||||
provider?: string | null
|
||||
locked?: boolean
|
||||
}>()
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'saved'): void }>()
|
||||
|
||||
const draft = reactive<ProxyEntryDraft>(emptyProxyEntryDraft())
|
||||
const errorText = ref('')
|
||||
const busy = ref(false)
|
||||
|
||||
function resetDraft() {
|
||||
Object.assign(draft, emptyProxyEntryDraft(props.provider))
|
||||
errorText.value = ''
|
||||
}
|
||||
|
||||
// 开与关都重刷:关的时候把已经打进内存的账密/链接抹掉,不留到下一次。
|
||||
watch(() => props.modelValue, resetDraft)
|
||||
|
||||
function close() {
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (props.userId == null) return
|
||||
errorText.value = validateProxyEntry(draft)
|
||||
if (errorText.value) return
|
||||
const payload = buildProxyEntryPayload(draft)
|
||||
if (!payload) {
|
||||
errorText.value = '代理配置不完整,请重新填写'
|
||||
return
|
||||
}
|
||||
busy.value = true
|
||||
try {
|
||||
await saveUserSecretModule(props.userId, PROXY_MODULE_KEY, payload.value, payload.channel)
|
||||
showAdminFeedback(props.locked ? '已更新锁定代理' : '已代填并锁定代理', 'success')
|
||||
emit('saved')
|
||||
close()
|
||||
} catch (error) {
|
||||
// 文案以接口返回的 message 为准,前端不解释后端状态码
|
||||
errorText.value = actionableErrorText(error)
|
||||
showAdminFeedback(errorText.value, 'error')
|
||||
} finally {
|
||||
busy.value = false
|
||||
Object.assign(draft, { authkey: '', authpwd: '', link: '' })
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="modelValue" class="modal-mask" @click.self="close">
|
||||
<div class="modal" role="dialog" aria-modal="true" aria-labelledby="proxy-entry-title">
|
||||
<h3 id="proxy-entry-title">{{ locked ? '改代理' : '代填代理' }}</h3>
|
||||
<p class="modal-note">
|
||||
为「{{ username || '该用户' }}」写入代理。出于凭据保护,后台不再下发已存的提取链接原文,
|
||||
这里每次都重新填写;保存后界面只显示脱敏后的地址(不含 key/pwd)。
|
||||
</p>
|
||||
|
||||
<div class="form-group">
|
||||
<label>代理供应商</label>
|
||||
<div class="radio-row">
|
||||
<label class="radio-item">
|
||||
<input v-model="draft.provider" type="radio" value="qingguo" />
|
||||
<span>青果</span>
|
||||
</label>
|
||||
<label class="radio-item">
|
||||
<input v-model="draft.provider" type="radio" value="jikip" />
|
||||
<span>极客</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-if="draft.provider === 'qingguo'">
|
||||
<div class="form-group">
|
||||
<label>Authkey</label>
|
||||
<input v-model="draft.authkey" type="text" autocomplete="off" placeholder="青果产品页的 Authkey" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Authpwd</label>
|
||||
<input v-model="draft.authpwd" type="password" autocomplete="new-password" placeholder="青果产品页的 Authpwd" />
|
||||
<span class="field-hint">青果只填 Authkey 会被判鉴权拒绝,两把都要填。</span>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="form-group">
|
||||
<label>极客提取链接</label>
|
||||
<input
|
||||
v-model="draft.link"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
placeholder="https://api.jikip.com/ip-get?..."
|
||||
/>
|
||||
<span class="field-hint">极客有可复制的提取链接,整条粘贴进来即可。</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<p v-if="errorText" class="modal-error">{{ errorText }}</p>
|
||||
<div class="modal-actions">
|
||||
<button class="btn" type="button" :disabled="busy" @click="save">
|
||||
{{ busy ? '保存中…' : '保存' }}
|
||||
</button>
|
||||
<button class="btn btn-ghost" type="button" :disabled="busy" @click="close">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 与密钥列表页同一视觉语言(本页不用 el-* 标签:新增 el-* 要同步改按需注册表)。 */
|
||||
.modal-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 3000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 40px 20px;
|
||||
background: rgba(45, 66, 86, 0.36);
|
||||
backdrop-filter: blur(6px);
|
||||
}
|
||||
.modal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(520px, 100%);
|
||||
max-height: 84vh;
|
||||
padding: 22px 24px;
|
||||
border: 1px solid #c7d7e5;
|
||||
border-radius: 14px;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 22px 60px rgba(39, 67, 94, 0.2);
|
||||
overflow-y: auto;
|
||||
color: #24384d;
|
||||
font-family: inherit;
|
||||
}
|
||||
.modal h3 {
|
||||
margin: 0 0 10px;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
}
|
||||
.modal-note {
|
||||
margin: 0 0 14px;
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.65;
|
||||
}
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.form-group label {
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.form-group input[type='text'],
|
||||
.form-group input[type='password'] {
|
||||
min-width: 0;
|
||||
min-height: 42px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.radio-row {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
}
|
||||
.radio-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13.5px;
|
||||
font-weight: 500;
|
||||
color: #24384d;
|
||||
}
|
||||
.field-hint {
|
||||
color: #7d8fa1;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.modal-error {
|
||||
margin: 0 0 10px;
|
||||
color: #b04a5a;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 42px;
|
||||
padding: 9px 18px;
|
||||
border: 1px solid #4f78a5;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.btn-ghost {
|
||||
background: #ffffff;
|
||||
border-color: #c7d7e5;
|
||||
color: #4f78a5;
|
||||
}
|
||||
</style>
|
||||
@@ -1,138 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, ref, watch } from 'vue'
|
||||
import type { MenuOptionNode } from './user-menu-auth'
|
||||
import { compactDirectGrantIds } from './user-menu-auth'
|
||||
import { fetchGrantableMenus } from './user-menu-auth-api'
|
||||
|
||||
const props = defineProps<{ checked?: number[]; companyId?: number | null }>()
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:checked', ids: number[]): void
|
||||
(e: 'load', ok: boolean): void
|
||||
}>()
|
||||
|
||||
/** 仅暴露 el-tree 我们需要的两个方法,避免整组件类型耦合。 */
|
||||
type TreeRef = { setCheckedKeys(keys: unknown[]): void; getCheckedKeys(): unknown }
|
||||
const adminTree = ref<{ setCheckedKeys(keys: unknown[]): void; getCheckedKeys(): unknown } | null>(null)
|
||||
const appTree = ref<{ setCheckedKeys(keys: unknown[]): void; getCheckedKeys(): unknown } | null>(null)
|
||||
const data = ref<MenuOptionNode[]>([])
|
||||
const loaded = ref(false)
|
||||
|
||||
/** 两种一级分类…(与 API menuType 分区一致):后台(admin) / 桌面端(app)。 */
|
||||
const adminNodes = computed(() => data.value.filter((node) => node.type === 'admin'))
|
||||
const appNodes = computed(() => data.value.filter((node) => node.type === 'app'))
|
||||
|
||||
function applyChecked(): void {
|
||||
const ids = Array.isArray(props.checked) ? props.checked.filter((id) => typeof id === 'number' && id > 0) : []
|
||||
adminTree.value?.setCheckedKeys(ids)
|
||||
appTree.value?.setCheckedKeys(ids)
|
||||
}
|
||||
|
||||
function onCheck(): void {
|
||||
const collect = (el: { getCheckedKeys(): unknown } | null): number[] => {
|
||||
const keys = el ? el.getCheckedKeys() : []
|
||||
return (Array.isArray(keys) ? keys : []).map((key) => Number(key)).filter((id) => id > 0)
|
||||
}
|
||||
const ids = [...collect(adminTree.value), ...collect(appTree.value)]
|
||||
// 父子联动模式(未启用严格勾选)下勾选父菜单会自动全选全部子菜单;
|
||||
// 提交前压缩为最小直接授权集:父级已勾选时后代不再重复提交(后端按“父级授权
|
||||
// 展开全部后代”判断权限,与旧 admin.html 勾父清后代语义一致),
|
||||
// 并剔除置灰的祖先分组(派生勾选,操作者无权授予)。
|
||||
emit('update:checked', compactDirectGrantIds(ids, data.value))
|
||||
}
|
||||
|
||||
async function load(): Promise<void> {
|
||||
try {
|
||||
data.value = await fetchGrantableMenus(props.companyId)
|
||||
loaded.value = true
|
||||
emit('load', true)
|
||||
// el-tree 的 store 通过异步 watch 同步 props.data,setCheckedKeys 必须等树
|
||||
// 渲染完成后再应用已勾选 id,否则作用在空 store 上导致已授权不回显。
|
||||
await nextTick()
|
||||
applyChecked()
|
||||
} catch {
|
||||
loaded.value = false
|
||||
emit('load', false)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
watch(
|
||||
() => props.checked,
|
||||
() => {
|
||||
if (loaded.value) applyChecked()
|
||||
},
|
||||
)
|
||||
/** 公司换了要整棵重取:勾选集里存的是 column id,别家同名菜单是另一份 id(V149 每公司一套树),
|
||||
* 拿别家的树勾出来的 id 提交会被后端判「无效的菜单权限项」,而已授权项也因为 id 不在这棵树上勾不上。 */
|
||||
watch(
|
||||
() => props.companyId,
|
||||
() => { void load() },
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-scrollbar max-height="300px" class="user-menu-tree-scroll">
|
||||
<template v-if="adminNodes.length || appNodes.length">
|
||||
<div class="menu-group-columns">
|
||||
<div v-if="adminNodes.length" class="menu-group-block">
|
||||
<div class="menu-group-title">后台</div>
|
||||
<!-- 父子联动模式(未启用严格勾选):勾选父菜单自动全选全部子菜单,
|
||||
勾父即代表全部后代,与后端“父级授权展开后代”的权限语义一致。 -->
|
||||
<el-tree
|
||||
ref="adminTree"
|
||||
:data="adminNodes"
|
||||
node-key="id"
|
||||
show-checkbox
|
||||
default-expand-all
|
||||
:props="{ label: 'name', children: 'children', disabled: 'disabled' }"
|
||||
@check="onCheck"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="appNodes.length" class="menu-group-block">
|
||||
<div class="menu-group-title">桌面端</div>
|
||||
<el-tree
|
||||
ref="appTree"
|
||||
:data="appNodes"
|
||||
node-key="id"
|
||||
show-checkbox
|
||||
default-expand-all
|
||||
:props="{ label: 'name', children: 'children', disabled: 'disabled' }"
|
||||
@check="onCheck"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<p v-else class="menu-group-empty">暂无可用菜单</p>
|
||||
</el-scrollbar>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.menu-group-columns {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 16px;
|
||||
}
|
||||
.menu-group-block {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
padding: 0 10px 8px 0;
|
||||
}
|
||||
.menu-group-block:last-child {
|
||||
padding-right: 0;
|
||||
border-left: 1px solid #e6edf4;
|
||||
padding-left: 16px;
|
||||
}
|
||||
.menu-group-title {
|
||||
padding: 4px 0 6px;
|
||||
font-size: 12.5px;
|
||||
font-weight: 650;
|
||||
color: #40586e;
|
||||
border-bottom: 1px solid #e6edf4;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.menu-group-empty {
|
||||
margin: 12px 0;
|
||||
color: #8293a5;
|
||||
font-size: 13px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,415 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { orderedPair, todayDateInput } from '@/utils/datetime'
|
||||
import {
|
||||
fetchUserSecretUsage,
|
||||
type AdminUserSecretUsageRow,
|
||||
} from '@/api/user-secret-usage'
|
||||
import type { GroupOption } from '@/api/user-secrets'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
/** 仅超管需要分组维度:非超管数据由后端裁剪到本人分组,分组筛选/列一律不展示。 */
|
||||
const isSuperAdmin = computed(() => session.isSuperAdmin)
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<AdminUserSecretUsageRow[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(15)
|
||||
const keyword = ref('')
|
||||
const startDate = ref(todayDateInput())
|
||||
const endDate = ref(todayDateInput())
|
||||
/** min/max 挡不住手输,落值后把倒挂的起止交换回来。 */
|
||||
function clampDatePair(): void {
|
||||
const [s, e] = orderedPair(startDate.value, endDate.value)
|
||||
startDate.value = s
|
||||
endDate.value = e
|
||||
}
|
||||
|
||||
const groupFilter = ref<number | null>(null)
|
||||
const groupOptions = ref<GroupOption[]>([])
|
||||
|
||||
/** 所选范围内三类总次数(后端按筛选条件统计,不分页)。 */
|
||||
const summary = ref({ totalCalls: 0, similarAsinCalls: 0, appearancePatentCalls: 0, proxyCalls: 0 })
|
||||
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
|
||||
|
||||
function formatCount(value: number | undefined) {
|
||||
const num = Number(value || 0)
|
||||
return num.toLocaleString('zh-CN')
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchUserSecretUsage({
|
||||
startDate: startDate.value || undefined,
|
||||
endDate: endDate.value || undefined,
|
||||
keyword: keyword.value.trim() || undefined,
|
||||
groupId: groupFilter.value || undefined,
|
||||
companyId: companyTab.requestCompanyId,
|
||||
page: page.value,
|
||||
pageSize: pageSize.value,
|
||||
})
|
||||
rows.value = result?.items || []
|
||||
total.value = Number(result?.total || 0)
|
||||
groupOptions.value = result?.groupOptions || []
|
||||
summary.value = {
|
||||
totalCalls: Number(result?.totalCalls || 0),
|
||||
similarAsinCalls: Number(result?.similarAsinCalls || 0),
|
||||
appearancePatentCalls: Number(result?.appearancePatentCalls || 0),
|
||||
proxyCalls: Number(result?.proxyCalls || 0),
|
||||
}
|
||||
} catch (error) {
|
||||
loadFailure.value = error instanceof Error ? error.message : '加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 切公司 = 重新取数。不重取的页 = tab 在那页上是假的(G1 的 pageFiles 断言盯着这条)。
|
||||
watch(() => companyTab.activeId, () => void load())
|
||||
|
||||
function search() {
|
||||
page.value = 1
|
||||
load()
|
||||
}
|
||||
|
||||
function reset() {
|
||||
keyword.value = ''
|
||||
startDate.value = todayDateInput()
|
||||
endDate.value = todayDateInput()
|
||||
groupFilter.value = null
|
||||
page.value = 1
|
||||
load()
|
||||
}
|
||||
|
||||
function changePage(next: number) {
|
||||
if (next < 1 || next > totalPages.value) return
|
||||
page.value = next
|
||||
load()
|
||||
}
|
||||
|
||||
function changeSize(size: number) {
|
||||
pageSize.value = size
|
||||
page.value = 1
|
||||
load()
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="secret-usage-view">
|
||||
<section class="panel-box">
|
||||
<div class="usage-head">
|
||||
<h3>密钥用量统计</h3>
|
||||
<span class="usage-note">口径:真实对外请求次数(LLM 每次请求、代理每次成功提取)</span>
|
||||
</div>
|
||||
|
||||
<div class="summary-row">
|
||||
<div class="summary-card">
|
||||
<div class="summary-label">总调用次数</div>
|
||||
<div class="summary-value">{{ formatCount(summary.totalCalls) }}</div>
|
||||
</div>
|
||||
<div class="summary-card">
|
||||
<div class="summary-label">货源查询密钥</div>
|
||||
<div class="summary-value">{{ formatCount(summary.similarAsinCalls) }}</div>
|
||||
</div>
|
||||
<div class="summary-card">
|
||||
<div class="summary-label">外观专利密钥</div>
|
||||
<div class="summary-value">{{ formatCount(summary.appearancePatentCalls) }}</div>
|
||||
</div>
|
||||
<div class="summary-card">
|
||||
<div class="summary-label">代理提取</div>
|
||||
<div class="summary-value">{{ formatCount(summary.proxyCalls) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row usage-filter-row">
|
||||
<div class="form-group" style="min-width: 160px">
|
||||
<label>开始日期</label>
|
||||
<input v-model="startDate" type="date" :max="endDate" @change="clampDatePair" />
|
||||
</div>
|
||||
<div class="form-group" style="min-width: 160px">
|
||||
<label>结束日期</label>
|
||||
<input v-model="endDate" type="date" :min="startDate" @change="clampDatePair" />
|
||||
</div>
|
||||
<div class="form-group" style="min-width: 200px">
|
||||
<label>用户名</label>
|
||||
<input v-model="keyword" type="text" placeholder="模糊搜索用户名" @keyup.enter="search" />
|
||||
</div>
|
||||
<div class="form-group" v-if="isSuperAdmin && groupOptions.length" style="min-width: 170px">
|
||||
<label>分组</label>
|
||||
<select v-model="groupFilter">
|
||||
<option :value="null">全部分组</option>
|
||||
<option v-for="group in groupOptions" :key="group.id" :value="group.id">{{ group.groupName }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label> </label>
|
||||
<div class="filter-actions">
|
||||
<button class="btn" type="button" @click="search">查询</button>
|
||||
<button class="btn btn-ghost" type="button" @click="reset">重置</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="usage-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 58px">序号</th>
|
||||
<th style="width: 220px">用户</th>
|
||||
<th v-if="isSuperAdmin" style="width: 130px">分组</th>
|
||||
<th style="width: 170px">货源查询密钥</th>
|
||||
<th style="width: 170px">外观专利密钥</th>
|
||||
<th style="width: 150px">代理提取</th>
|
||||
<th style="width: 130px">合计</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-if="rows.length">
|
||||
<tr v-for="(row, index) in rows" :key="row.userId">
|
||||
<td>{{ (page - 1) * pageSize + index + 1 }}</td>
|
||||
<td>
|
||||
<span class="user-name">{{ row.username || `UID ${row.userId}` }}</span>
|
||||
</td>
|
||||
<td v-if="isSuperAdmin">
|
||||
<span class="group-name">{{ row.groups?.length ? row.groups.join('、') : '—' }}</span>
|
||||
</td>
|
||||
<td><span class="count-value">{{ formatCount(row.similarAsinCount) }}</span></td>
|
||||
<td><span class="count-value">{{ formatCount(row.appearancePatentCount) }}</span></td>
|
||||
<td><span class="count-value">{{ formatCount(row.proxyCount) }}</span></td>
|
||||
<td><span class="count-value count-total">{{ formatCount(row.totalCount) }}</span></td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td :colspan="isSuperAdmin ? 7 : 6" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td :colspan="isSuperAdmin ? 7 : 6" class="empty-tip">
|
||||
{{ keyword || groupFilter ? '暂无匹配记录' : '暂无用量记录' }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<OldPagination :total="total" :page="page" :page-size="pageSize" @change="changePage" @size-change="changeSize" />
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 与密钥管理页保持同一视觉语言(像素复刻后台面板风格)。 */
|
||||
.secret-usage-view {
|
||||
font-family: inherit;
|
||||
color: #24384d;
|
||||
}
|
||||
.panel-box {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 20px 22px 24px;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(145deg, #ffffff, #f9fbfd);
|
||||
box-shadow: 0 1px 2px rgba(39, 67, 94, 0.04), 0 14px 30px -24px rgba(39, 67, 94, 0.28);
|
||||
}
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
color: #24384d;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
.usage-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.usage-note {
|
||||
color: #7d8fa2;
|
||||
font-size: 12px;
|
||||
}
|
||||
.summary-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.summary-card {
|
||||
flex: 1 1 160px;
|
||||
min-width: 150px;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 10px;
|
||||
background: #f7fafd;
|
||||
}
|
||||
.summary-label {
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.summary-value {
|
||||
margin-top: 6px;
|
||||
color: #2f5d8b;
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.usage-filter-row {
|
||||
margin: 0 0 16px;
|
||||
}
|
||||
.form-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 14px 18px;
|
||||
}
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.form-group label {
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.form-group input,
|
||||
.form-group select {
|
||||
min-width: 0;
|
||||
min-height: 42px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
color-scheme: light;
|
||||
outline: none;
|
||||
transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
|
||||
}
|
||||
.form-group input:hover,
|
||||
.form-group select:hover {
|
||||
border-color: #9fb7cd;
|
||||
}
|
||||
.form-group input:focus,
|
||||
.form-group select:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
.filter-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 42px;
|
||||
padding: 9px 18px;
|
||||
border: 1px solid #4f78a5;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 8px 18px -14px rgba(79, 120, 165, 0.72);
|
||||
transition: background 160ms ease, box-shadow 160ms ease, transform 120ms ease;
|
||||
}
|
||||
.btn:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #7094ba, #5d83ac);
|
||||
}
|
||||
.btn-ghost {
|
||||
background: #ffffff;
|
||||
border-color: #c7d7e5;
|
||||
color: #4f78a5;
|
||||
box-shadow: none;
|
||||
}
|
||||
.btn-ghost:hover:not(:disabled) {
|
||||
background: #edf5fb;
|
||||
border-color: #95b1cb;
|
||||
color: #2f5d8b;
|
||||
}
|
||||
.usage-table-scroll {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 10px;
|
||||
background: #ffffff;
|
||||
}
|
||||
.usage-table-scroll table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
min-width: 1020px;
|
||||
}
|
||||
.usage-table-scroll th,
|
||||
.usage-table-scroll td {
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
font-size: 13.5px;
|
||||
line-height: 1.5;
|
||||
border-bottom: 1px solid #e0e8ef;
|
||||
vertical-align: middle;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.usage-table-scroll th {
|
||||
background: #edf4fa;
|
||||
color: #4e6479;
|
||||
border-bottom-color: #d5e1eb;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.4px;
|
||||
}
|
||||
.usage-table-scroll tbody tr:hover td {
|
||||
background: #f1f7fb;
|
||||
}
|
||||
.usage-table-scroll tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.user-name {
|
||||
color: #24384d;
|
||||
font-weight: 600;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.group-name {
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.count-value {
|
||||
color: #2f5d8b;
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.count-total {
|
||||
font-weight: 700;
|
||||
}
|
||||
.empty-tip {
|
||||
color: #8293a5;
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
@@ -1,785 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import ProxyEntryDialog from './ProxyEntryDialog.vue'
|
||||
import {
|
||||
checkUserSecret,
|
||||
clearUserSecretModule,
|
||||
deleteUserSecret,
|
||||
fetchAdminSecretBalances,
|
||||
fetchUserSecretList,
|
||||
type AdminUserSecretBalanceItem,
|
||||
type AdminUserSecretModule,
|
||||
type AdminUserSecretRow,
|
||||
type GroupOption,
|
||||
} from '@/api/user-secrets'
|
||||
import {
|
||||
PROXY_MODULE_KEY,
|
||||
llmBalanceLines,
|
||||
llmSourceLabel,
|
||||
moduleStatusBand,
|
||||
proxyBalanceLine,
|
||||
proxyDisplayText,
|
||||
proxySourceLabel,
|
||||
rowDetailLines,
|
||||
rowStatusBand,
|
||||
} from './user-secret-model.ts'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
/** 仅超管需要分组维度:非超管数据由后端裁剪到本人分组,分组筛选/列一律不展示。 */
|
||||
const isSuperAdmin = computed(() => session.isSuperAdmin)
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<AdminUserSecretRow[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(15)
|
||||
const keyword = ref('')
|
||||
const statusFilter = ref('')
|
||||
const groupFilter = ref<number | null>(null)
|
||||
/** 分组下拉(超管=全部;主管=自己带的分组,由列表接口带回)。 */
|
||||
const groupOptions = ref<GroupOption[]>([])
|
||||
/** 正在检测的行 userId,用于按钮 loading 态。 */
|
||||
const checkingId = ref<number | null>(null)
|
||||
/** 正在解锁代理的行 userId,避免重复点击(代填在弹窗里自己管 busy)。 */
|
||||
const proxyBusyId = ref<number | null>(null)
|
||||
/** 代填/改代理弹窗的目标行(脱敏后没有原文可预填,只能重填账密)。 */
|
||||
const proxyDialog = ref<{ userId: number; username: string; provider: string | null; locked: boolean } | null>(null)
|
||||
|
||||
/** 余额侧写(实时查上游、不落库):按 userId 存,列表接口本身不带这些数。 */
|
||||
const balances = ref<Record<number, AdminUserSecretBalanceItem>>({})
|
||||
const balanceLoading = ref(false)
|
||||
/** 本轮「没取到」的原因(越权剔除/上游未应答/请求失败):进工具行悬停,不弹全局打扰。 */
|
||||
const balanceNotice = ref('')
|
||||
/** 服务端单次上限 20 个用户;超出会被当场拒,所以这里按批顺取(并发留给服务端那个线程池)。 */
|
||||
const BALANCE_BATCH = 20
|
||||
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
{ value: '', label: '全部状态' },
|
||||
{ value: 'passed', label: '检测通过' },
|
||||
{ value: 'failed', label: '检测失败' },
|
||||
{ value: 'incomplete', label: '未配齐' },
|
||||
// 后端的行级值仍是 error:这一档现在既可能是「问不出结论」,也可能是「通道还没释放、等一会再点」,
|
||||
// 界面按码把后者补成「可重试」(见 user-secret-model.ts 的档位表),筛选项就得把两档都点名。
|
||||
{ value: 'error', label: '无法判定/可重试' },
|
||||
{ value: 'unknown', label: '未检测' },
|
||||
]
|
||||
|
||||
/* 状态药丸的档位表在 `user-secret-model.ts`(唯一出处,页面不带第二张表):
|
||||
行级传整行而不是 `row.status`——后端把 failed/incomplete 都判掉之后就只剩一个「error」,
|
||||
这一行到底是「查不出」还是「等青果释放」只有逐格的 `check_code` 说得清。 */
|
||||
|
||||
/**
|
||||
* 单格悬停详情:后端下发的**脱敏值** + 锁定说明 + **检测结果原文 `check_message`** + 检测时间 + 耗时。
|
||||
* 运维要判「是欠费还是被自己的采集占着」,靠的就是这句后端原文——档名只是扫一眼用的短词,
|
||||
* 前端一律不按码自己拼句子。
|
||||
* ⚠ 只读 `masked`:`full` 在后台侧恒空(2026-11-02 `SecretMasking.maskProxy` 收口),
|
||||
* 这里不做任何「masked 空就回落原文」的兜底,也不给复制整条链接的旁路。
|
||||
*/
|
||||
function moduleTooltip(module: AdminUserSecretModule | undefined) {
|
||||
if (!module || !module.exists) return '未配置'
|
||||
const parts: string[] = []
|
||||
const display = String(module.masked || '').trim()
|
||||
if (display) {
|
||||
parts.push(isProxyModule(module) ? `代理地址(已脱敏,不含 key/pwd):${display}` : `密钥:${display}`)
|
||||
}
|
||||
if (module.locked) parts.push('已由后台代填并锁定:客户端不可修改或清空,改代理需重新填写账密')
|
||||
// 后端的这句话就是给人看的结论,原样透出(不动一个字、不按码另拼一句)
|
||||
const message = String(module.checkMessage || '').trim()
|
||||
if (message) parts.push(message)
|
||||
if (module.checkedAt) parts.push(`检测时间:${formatDateTime(module.checkedAt)}`)
|
||||
if (module.checkLatencyMs != null) parts.push(`耗时:${module.checkLatencyMs}ms`)
|
||||
return parts.join(';') || '暂无检测记录'
|
||||
}
|
||||
|
||||
/** 该格是不是代理模块:按后端下发的 moduleKey 判,货源标签与文案都走这一条口径。 */
|
||||
function isProxyModule(module: AdminUserSecretModule) {
|
||||
return String(module.moduleKey || '').trim().toLowerCase() === PROXY_MODULE_KEY
|
||||
}
|
||||
|
||||
/** 分组列文案:优先分组名;未建分组的用户回退展示所属主管,便于判断归属。 */
|
||||
function groupTextOf(row: AdminUserSecretRow) {
|
||||
if (row.groups?.length) return row.groups.join('、')
|
||||
if (row.leaderUsername) return `${row.leaderUsername}(未建分组)`
|
||||
return '—'
|
||||
}
|
||||
|
||||
/**
|
||||
* 行级悬停详情:后端的行级摘要 + 逐格的 `check_message` 原文 + 更新时间。
|
||||
* 行级状态一旦补成「可重试」,管理员得能立刻看出是哪一格在等、后端原话怎么说;
|
||||
* 逐格那句一律取后端下发文本(`rowDetailLines` 只搬运、不改写、不另拼一句)。
|
||||
*/
|
||||
function rowStatusTooltip(row: AdminUserSecretRow) {
|
||||
const parts: string[] = []
|
||||
if (row.statusMessage) parts.push(row.statusMessage)
|
||||
parts.push(...rowDetailLines(row))
|
||||
if (row.updatedAt) parts.push(`最近更新:${formatDateTime(row.updatedAt)}`)
|
||||
return parts.join(';') || '暂无检测记录'
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchUserSecretList({
|
||||
keyword: keyword.value.trim() || undefined,
|
||||
checkStatus: statusFilter.value || undefined,
|
||||
groupId: groupFilter.value || undefined,
|
||||
companyId: companyTab.requestCompanyId,
|
||||
page: page.value,
|
||||
pageSize: pageSize.value,
|
||||
})
|
||||
rows.value = result?.items || []
|
||||
total.value = Number(result?.total || 0)
|
||||
groupOptions.value = result?.groupOptions || []
|
||||
void loadBalances()
|
||||
} catch (error) {
|
||||
loadFailure.value = error instanceof Error ? error.message : '加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取本页用户的余额:列表已经画完,这两列随后填(余额要实时打上游,不能让它在列表主数据前占位)。
|
||||
*
|
||||
* 失败只影响这两列并留一句说明——不 `showAdminFeedback`、不把整页判成加载失败:
|
||||
* 一次上游抖动就红整页,管理员会以为密钥数据本身出了问题。
|
||||
*/
|
||||
async function loadBalances() {
|
||||
const ids = rows.value.map((row) => row.userId)
|
||||
balances.value = {}
|
||||
balanceNotice.value = ''
|
||||
if (!ids.length) return
|
||||
balanceLoading.value = true
|
||||
try {
|
||||
const merged: Record<number, AdminUserSecretBalanceItem> = {}
|
||||
let denied = 0
|
||||
let timedOut = 0
|
||||
for (let start = 0; start < ids.length; start += BALANCE_BATCH) {
|
||||
const batch = ids.slice(start, start + BALANCE_BATCH)
|
||||
const result = await fetchAdminSecretBalances(batch, companyTab.requestCompanyId)
|
||||
for (const item of result?.items || []) {
|
||||
if (item && item.userId != null) merged[Number(item.userId)] = item
|
||||
}
|
||||
denied += result?.deniedUserIds?.length || 0
|
||||
timedOut += result?.timedOutUserIds?.length || 0
|
||||
}
|
||||
balances.value = merged
|
||||
const notices: string[] = []
|
||||
if (denied) notices.push(`${denied} 个用户不在当前数据权限内,本轮未查`)
|
||||
if (timedOut) notices.push(`${timedOut} 个用户本轮上游未应答(不是余额为 0)`)
|
||||
balanceNotice.value = notices.join(';')
|
||||
} catch (error) {
|
||||
balanceNotice.value = error instanceof Error ? error.message : '余额本轮没取到(不是余额为 0)'
|
||||
} finally {
|
||||
balanceLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 某行的 LLM 余额行(按渠道折叠);没取到时给一格占位而不是空白。 */
|
||||
function llmLinesOf(userId: number) {
|
||||
const lines = llmBalanceLines(balances.value[userId]?.llm, balanceLoading.value)
|
||||
return lines.length ? lines : [{ text: '—', title: balanceNotice.value || '本轮没取到数(不是余额为 0)' }]
|
||||
}
|
||||
|
||||
function proxyLineOf(userId: number) {
|
||||
const item = balances.value[userId]
|
||||
if (item?.proxy) return proxyBalanceLine(item.proxy, false)
|
||||
return balanceLoading.value
|
||||
? { text: '查询中…', title: '余额按实时查询,不落库' }
|
||||
: { text: '—', title: balanceNotice.value || '本轮没取到数(不是余量为 0)' }
|
||||
}
|
||||
|
||||
// 切公司 = 重新取数。不重取的页 = tab 在那页上是假的(G1 的 pageFiles 断言盯着这条)。
|
||||
watch(() => companyTab.activeId, () => void load())
|
||||
|
||||
function search() {
|
||||
page.value = 1
|
||||
load()
|
||||
}
|
||||
|
||||
function reset() {
|
||||
keyword.value = ''
|
||||
statusFilter.value = ''
|
||||
groupFilter.value = null
|
||||
page.value = 1
|
||||
load()
|
||||
}
|
||||
|
||||
/** 立即检测:真实请求该用户全部已配置项并把结果落库。 */
|
||||
async function check(row: AdminUserSecretRow) {
|
||||
checkingId.value = row.userId
|
||||
try {
|
||||
const results = await checkUserSecret(row.userId)
|
||||
if (!results || !results.length) {
|
||||
ElMessage.warning('该用户尚未配置任何密钥或代理')
|
||||
} else {
|
||||
const failed = results.filter((item) => item.checkStatus === 'failed')
|
||||
const errors = results.filter((item) => item.checkStatus === 'error')
|
||||
if (failed.length) {
|
||||
ElMessage.warning(failed[0].checkMessage || '存在检测失败项')
|
||||
} else if (errors.length) {
|
||||
// 后端这句话会区分「通道被你自己占着,等约 3 分钟」与「真的问不出结论」;
|
||||
// 硬写「无法判定」等于把可重试那一族又抹回一坨(现网 uid=1 就是这个形状)。
|
||||
ElMessage.warning(errors[0].checkMessage || '部分配置本次无法判定')
|
||||
} else {
|
||||
ElMessage.success('检测通过')
|
||||
}
|
||||
}
|
||||
load()
|
||||
} catch (error) {
|
||||
showAdminFeedback(error instanceof Error ? error.message : '检测失败', 'error')
|
||||
} finally {
|
||||
checkingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(row: AdminUserSecretRow) {
|
||||
const who = row.username || `UID ${row.userId}`
|
||||
if (!(await openAdminConfirm({ message: `确定清空「${who}」的全部密钥与代理配置吗?后台锁定的代理会一并清除并解锁,该用户需要重新配置。`, danger: true }))) return
|
||||
try {
|
||||
await deleteUserSecret(row.userId)
|
||||
ElMessage.success('已清空')
|
||||
load()
|
||||
} catch (error) {
|
||||
showAdminFeedback(error instanceof Error ? error.message : '清空失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开代填/改代理弹窗。
|
||||
* ⚠ 不预填任何已有值:后台侧 `full` 恒空(代理链接里带着 key/pwd,2026-11-02 收口后不再下发),
|
||||
* 所以这一单的语义就是「重新填账密」,界面上也没有把原文取回来的旁路。
|
||||
*/
|
||||
function openProxyDialog(row: AdminUserSecretRow) {
|
||||
proxyDialog.value = {
|
||||
userId: row.userId,
|
||||
username: row.username || `UID ${row.userId}`,
|
||||
provider: row.proxy?.channel ?? null,
|
||||
locked: Boolean(row.proxy?.locked),
|
||||
}
|
||||
}
|
||||
|
||||
/** 弹窗保存成功:关掉并重新取数(列表只拿脱敏值,不参与拼装)。 */
|
||||
function onProxySaved() {
|
||||
proxyDialog.value = null
|
||||
load()
|
||||
}
|
||||
|
||||
/** 解锁代理:清空后台代填值,该用户恢复自行配置。 */
|
||||
async function unlockProxy(row: AdminUserSecretRow) {
|
||||
const who = row.username || `UID ${row.userId}`
|
||||
if (!(await openAdminConfirm({ message: `确定解除「${who}」的代理锁定吗?解锁后当前后台代理值会被清空,客户端恢复自行配置。`, danger: true }))) return
|
||||
proxyBusyId.value = row.userId
|
||||
try {
|
||||
await clearUserSecretModule(row.userId, PROXY_MODULE_KEY)
|
||||
ElMessage.success('已解锁')
|
||||
load()
|
||||
} catch (error) {
|
||||
showAdminFeedback(error instanceof Error ? error.message : '解锁失败', 'error')
|
||||
} finally {
|
||||
proxyBusyId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function changePage(next: number) {
|
||||
if (next < 1 || next > totalPages.value) return
|
||||
page.value = next
|
||||
load()
|
||||
}
|
||||
|
||||
function changeSize(size: number) {
|
||||
pageSize.value = size
|
||||
page.value = 1
|
||||
load()
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="user-secrets-view">
|
||||
<section class="panel-box">
|
||||
<div class="secrets-head">
|
||||
<h3>用户密钥列表</h3>
|
||||
</div>
|
||||
|
||||
<div class="form-row secrets-filter-row">
|
||||
<div class="form-group" style="min-width: 220px">
|
||||
<label>用户名</label>
|
||||
<input v-model="keyword" type="text" placeholder="模糊搜索用户名" @keyup.enter="search" />
|
||||
</div>
|
||||
<div class="form-group" style="min-width: 170px">
|
||||
<label>状态(三项都通过才算通过)</label>
|
||||
<select v-model="statusFilter">
|
||||
<option v-for="option in STATUS_OPTIONS" :key="option.value" :value="option.value">{{ option.label }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group" v-if="isSuperAdmin && groupOptions.length" style="min-width: 170px">
|
||||
<label>分组</label>
|
||||
<select v-model="groupFilter">
|
||||
<option :value="null">全部分组</option>
|
||||
<option v-for="group in groupOptions" :key="group.id" :value="group.id">{{ group.groupName }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label> </label>
|
||||
<div class="filter-actions">
|
||||
<button class="btn" type="button" @click="search">查询</button>
|
||||
<button class="btn btn-ghost" type="button" @click="reset">重置</button>
|
||||
<button
|
||||
class="btn btn-ghost"
|
||||
type="button"
|
||||
:disabled="balanceLoading || !rows.length"
|
||||
:title="balanceNotice || '余额是实时查上游、不落库;这两列没取到时显示 —,不是 0'"
|
||||
@click="loadBalances"
|
||||
>
|
||||
{{ balanceLoading ? '余额查询中…' : '刷新余额' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="secrets-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 58px">序号</th>
|
||||
<th style="width: 260px">用户</th>
|
||||
<th v-if="isSuperAdmin" style="width: 130px">分组</th>
|
||||
<th style="width: 230px">货源查询密钥</th>
|
||||
<th style="width: 230px">外观专利密钥</th>
|
||||
<th style="width: 170px">LLM 余额</th>
|
||||
<th style="width: 380px">代理设置</th>
|
||||
<th style="width: 160px">代理余量</th>
|
||||
<th style="width: 130px">状态</th>
|
||||
<th style="width: 170px">创建时间</th>
|
||||
<th style="width: 170px">更新时间</th>
|
||||
<th style="width: 315px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-if="rows.length">
|
||||
<tr v-for="(row, index) in rows" :key="row.userId">
|
||||
<td>{{ (page - 1) * pageSize + index + 1 }}</td>
|
||||
<td>
|
||||
<span class="user-name">{{ row.username || '—' }}</span>
|
||||
</td>
|
||||
<td v-if="isSuperAdmin">
|
||||
<span class="creator-name">{{ groupTextOf(row) }}</span>
|
||||
</td>
|
||||
<td>
|
||||
<div class="module-cell">
|
||||
<span v-if="row.similarAsin?.exists" class="mono-mask" :title="moduleTooltip(row.similarAsin)">{{ row.similarAsin.masked }}</span>
|
||||
<span v-else class="empty-value">未配置</span>
|
||||
<span v-if="row.similarAsin?.exists" class="wh-pill is-source" title="该用户这把密钥所属渠道">
|
||||
{{ llmSourceLabel(row.similarAsin.channel) }}
|
||||
</span>
|
||||
<span class="wh-pill" :class="moduleStatusBand(row.similarAsin).tone" :title="moduleTooltip(row.similarAsin)">
|
||||
{{ moduleStatusBand(row.similarAsin).label }}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div class="module-cell">
|
||||
<span v-if="row.appearancePatent?.exists" class="mono-mask" :title="moduleTooltip(row.appearancePatent)">{{ row.appearancePatent.masked }}</span>
|
||||
<span v-else class="empty-value">未配置</span>
|
||||
<span v-if="row.appearancePatent?.exists" class="wh-pill is-source" title="该用户这把密钥所属渠道">
|
||||
{{ llmSourceLabel(row.appearancePatent.channel) }}
|
||||
</span>
|
||||
<span class="wh-pill" :class="moduleStatusBand(row.appearancePatent).tone" :title="moduleTooltip(row.appearancePatent)">
|
||||
{{ moduleStatusBand(row.appearancePatent).label }}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div class="module-cell module-cell--stack">
|
||||
<span
|
||||
v-for="(line, lineIndex) in llmLinesOf(row.userId)"
|
||||
:key="`llm-${lineIndex}`"
|
||||
class="balance-line"
|
||||
:title="line.title"
|
||||
>{{ line.text }}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div class="module-cell module-cell--stack">
|
||||
<span v-if="row.proxy?.exists" class="mono-mask" :title="moduleTooltip(row.proxy)">{{ proxyDisplayText(row.proxy) }}</span>
|
||||
<span v-else class="empty-value">未配置</span>
|
||||
<span class="module-cell-pills">
|
||||
<span v-if="row.proxy?.exists" class="wh-pill is-source" title="该用户代理所属供应商">
|
||||
{{ proxySourceLabel(row.proxy.channel) }}
|
||||
</span>
|
||||
<span class="wh-pill" :class="moduleStatusBand(row.proxy).tone" :title="moduleTooltip(row.proxy)">
|
||||
{{ moduleStatusBand(row.proxy).label }}
|
||||
</span>
|
||||
<span
|
||||
v-if="row.proxy?.locked"
|
||||
class="wh-pill is-locked"
|
||||
title="已由管理员代填并锁定:客户端不可修改或清空"
|
||||
>
|
||||
已锁定
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div class="module-cell module-cell--stack">
|
||||
<span class="balance-line" :title="proxyLineOf(row.userId).title">
|
||||
{{ proxyLineOf(row.userId).text }}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<span class="wh-pill" :class="rowStatusBand(row).tone" :title="rowStatusTooltip(row)">
|
||||
{{ rowStatusBand(row).label }}
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ formatDateTime(row.createdAt) }}</td>
|
||||
<td>{{ formatDateTime(row.updatedAt) }}</td>
|
||||
<td class="ops-cell">
|
||||
<button
|
||||
class="btn btn-sm"
|
||||
type="button"
|
||||
:disabled="checkingId === row.userId"
|
||||
@click="check(row)"
|
||||
>
|
||||
{{ checkingId === row.userId ? '检测中…' : '立即检测' }}
|
||||
</button>
|
||||
<button
|
||||
class="btn btn-sm btn-ghost"
|
||||
type="button"
|
||||
@click="openProxyDialog(row)"
|
||||
>
|
||||
{{ row.proxy?.locked ? '改代理' : '代填代理' }}
|
||||
</button>
|
||||
<button
|
||||
v-if="row.proxy?.locked"
|
||||
class="btn btn-sm btn-ghost"
|
||||
type="button"
|
||||
:disabled="proxyBusyId === row.userId"
|
||||
@click="unlockProxy(row)"
|
||||
>
|
||||
解锁
|
||||
</button>
|
||||
<button class="btn btn-sm btn-danger" type="button" @click="remove(row)">清空</button>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td :colspan="isSuperAdmin ? 12 : 11" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td :colspan="isSuperAdmin ? 12 : 11" class="empty-tip">{{ keyword || statusFilter || groupFilter ? '暂无匹配记录' : '暂无用户密钥记录' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<OldPagination :total="total" :page="page" :page-size="pageSize" @change="changePage" @size-change="changeSize" />
|
||||
</section>
|
||||
|
||||
<ProxyEntryDialog
|
||||
:model-value="proxyDialog != null"
|
||||
:user-id="proxyDialog?.userId ?? null"
|
||||
:username="proxyDialog?.username ?? ''"
|
||||
:provider="proxyDialog?.provider ?? null"
|
||||
:locked="Boolean(proxyDialog?.locked)"
|
||||
@update:model-value="(open: boolean) => { if (!open) proxyDialog = null }"
|
||||
@saved="onProxySaved"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 像素复刻旧版 admin.html 面板风格(与店铺密钥页同一视觉语言)。 */
|
||||
.user-secrets-view {
|
||||
font-family: inherit;
|
||||
color: #24384d;
|
||||
}
|
||||
.panel-box {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 20px 22px 24px;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(145deg, #ffffff, #f9fbfd);
|
||||
box-shadow: 0 1px 2px rgba(39, 67, 94, 0.04), 0 14px 30px -24px rgba(39, 67, 94, 0.28);
|
||||
}
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
color: #24384d;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
.secrets-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.secrets-filter-row {
|
||||
margin: 0 0 16px;
|
||||
}
|
||||
.form-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 14px 18px;
|
||||
}
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.form-group label {
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.form-group input,
|
||||
.form-group select {
|
||||
min-width: 0;
|
||||
min-height: 42px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
color-scheme: light;
|
||||
outline: none;
|
||||
transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
|
||||
}
|
||||
.form-group input:hover,
|
||||
.form-group select:hover {
|
||||
border-color: #9fb7cd;
|
||||
}
|
||||
.form-group input:focus,
|
||||
.form-group select:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
.filter-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 42px;
|
||||
padding: 9px 18px;
|
||||
border: 1px solid #4f78a5;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 8px 18px -14px rgba(79, 120, 165, 0.72);
|
||||
transition: background 160ms ease, box-shadow 160ms ease, transform 120ms ease;
|
||||
}
|
||||
.btn:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #7094ba, #5d83ac);
|
||||
box-shadow: 0 11px 22px -14px rgba(79, 120, 165, 0.8);
|
||||
}
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.btn-danger {
|
||||
background: linear-gradient(135deg, #c06d77, #b35f6a);
|
||||
border-color: #b35f6a;
|
||||
}
|
||||
.btn-danger:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #cb7c84, #b96570);
|
||||
}
|
||||
.btn-ghost {
|
||||
background: #ffffff;
|
||||
border-color: #c7d7e5;
|
||||
color: #4f78a5;
|
||||
box-shadow: none;
|
||||
}
|
||||
.btn-ghost:hover:not(:disabled) {
|
||||
background: #edf5fb;
|
||||
border-color: #95b1cb;
|
||||
color: #2f5d8b;
|
||||
}
|
||||
.btn-sm {
|
||||
min-height: 36px;
|
||||
padding: 7px 12px;
|
||||
}
|
||||
.secrets-table-scroll {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 10px;
|
||||
background: #ffffff;
|
||||
}
|
||||
.secrets-table-scroll table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
min-width: 1440px;
|
||||
}
|
||||
.secrets-table-scroll th,
|
||||
.secrets-table-scroll td {
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
font-size: 13.5px;
|
||||
line-height: 1.5;
|
||||
border-bottom: 1px solid #e0e8ef;
|
||||
vertical-align: middle;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.secrets-table-scroll th {
|
||||
background: #edf4fa;
|
||||
color: #4e6479;
|
||||
border-bottom-color: #d5e1eb;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.4px;
|
||||
}
|
||||
.secrets-table-scroll tbody tr:hover td {
|
||||
background: #f1f7fb;
|
||||
}
|
||||
.secrets-table-scroll tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.user-name {
|
||||
color: #24384d;
|
||||
font-weight: 600;
|
||||
/* 用户名(含中文)可完整换行展示,不截断 */
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.creator-name {
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.module-cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
/* 代理列:脱敏地址独占一行,状态药丸另起一行(列宽按最长药丸文案留的,不按整条链接) */
|
||||
.module-cell--stack {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
}
|
||||
.module-cell .mono-mask {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
/* 代理列只显示后端脱敏后的 scheme://host(短串,单行足够)。
|
||||
这里**不许**再出现"允许折行展示完整明文 + user-select:all"那套样式:
|
||||
它等于给整条带 key/pwd 的链接做了一键全选复制的旁路(2026-11-02 脱敏收口时一并拆掉)。 */
|
||||
.mono-mask {
|
||||
font-family: Consolas, "Cascadia Mono", monospace;
|
||||
font-size: 12.5px;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
.empty-value {
|
||||
color: #a7b4c1;
|
||||
}
|
||||
/* 余额列:数字按等宽数位对齐(两行叠着看差值才不用竖着对),超长进 title。 */
|
||||
.balance-line {
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-size: 12.5px;
|
||||
color: #2f4256;
|
||||
}
|
||||
.ops-cell {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.empty-tip {
|
||||
color: #8293a5;
|
||||
text-align: center;
|
||||
}
|
||||
.wh-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 2px 10px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid;
|
||||
font-size: 12px;
|
||||
line-height: 1.7;
|
||||
cursor: help;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.wh-pill.is-source {
|
||||
background: #eef2fb;
|
||||
border-color: #ccd8f2;
|
||||
color: #3d5a99;
|
||||
font-weight: 600;
|
||||
}
|
||||
.wh-pill.is-allowed {
|
||||
background: #e8f6ee;
|
||||
border-color: #b9e0c9;
|
||||
color: #2f7d52;
|
||||
}
|
||||
.wh-pill.is-blocked {
|
||||
background: #fdecef;
|
||||
border-color: #f2c4cd;
|
||||
color: #b04a5a;
|
||||
}
|
||||
.wh-pill.is-warn {
|
||||
background: #fdf6e3;
|
||||
border-color: #f0dfae;
|
||||
color: #8f6d1e;
|
||||
}
|
||||
/* 「等一会再点」这一族(无可用通道/限流/超时/网络/上游):既不红(密钥没坏)
|
||||
也不黄(不是欠费)更不是灰(不是查不出),独立一档青色——三种处置一眼分开。 */
|
||||
.wh-pill.is-retry {
|
||||
background: #e6f2f7;
|
||||
border-color: #b6d8e6;
|
||||
color: #2b6b86;
|
||||
}
|
||||
.wh-pill.is-unknown {
|
||||
background: #f0f3f6;
|
||||
border-color: #d6dee6;
|
||||
color: #6b7d8f;
|
||||
}
|
||||
.wh-pill.is-locked {
|
||||
background: #f0ecfb;
|
||||
border-color: #d5caf0;
|
||||
color: #5b4a96;
|
||||
}
|
||||
.module-cell-pills {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
</style>
|
||||
@@ -1,600 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
/** 用户管理页 · 像素复刻旧版 admin.html panel-users(自绘:panel-box + 页头按钮 + 筛选 form-row + 旧式表格/分页 + 原生 confirm 删除)。
|
||||
* script 逻辑沿用现有 Vue 实现;创建/编辑弹窗保留现有组件(含用户菜单权限树)。 */
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { AdminUser } from '@/types/admin'
|
||||
import { roleLabel } from '@/types/admin'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { usePlatformTabStore } from '@/stores/platform-tab'
|
||||
import { deleteUser, fetchUserList, setUserDisabled } from '@/api/users'
|
||||
import { fetchCompanies } from '@/api/companies'
|
||||
import { createUserFilterState, toUserListParams, type UserFilterState } from './users-filter'
|
||||
import { totalPageCount } from './user-pagination'
|
||||
import { deleteBlockReason, deleteConfirmMessage } from './user-delete-model'
|
||||
import { disableBlockReason, disableConfirmMessage, disabledBadgeText } from './user-disable-model'
|
||||
import { listPhaseOf, userListEmptyHint } from './user-list-state'
|
||||
import { editableBy } from './user-edit-model'
|
||||
import { formatExpiryCell } from './user-expiry'
|
||||
import CreateUserDialog from './CreateUserDialog.vue'
|
||||
import EditUserDialog from './EditUserDialog.vue'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import { createLatestRequestGate } from '@/utils/latest-request'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
// 平台 tab(V206):账号域三页两 tab 共用本组件,列表/新建/编辑都按当前平台收放。
|
||||
const platformTab = usePlatformTabStore()
|
||||
/** 京东侧标记:上架上限列与编辑入口只在京东 tab 显示(用户口径「不需要在亚马逊那边」)。 */
|
||||
const isJdSide = computed(() => platformTab.active === 'jd')
|
||||
const loading = ref(false)
|
||||
const loadError = ref('')
|
||||
// 用户列表竞态门(S1-F4):快速切公司/翻页只让最后一次响应落地
|
||||
const gate = createLatestRequestGate()
|
||||
const rows = ref<AdminUser[]>([])
|
||||
const total = ref(0)
|
||||
/** 所属管理员候选(来自列表响应的 admins),供超管筛选下拉使用。 */
|
||||
const admins = ref<Array<{ id: number; username: string }>>([])
|
||||
/** 公司候选(仅供建号弹窗的「公司超级管理员」下拉使用,2026-10-05 唯一豁免)。 */
|
||||
const companyOptions = ref<Array<{ id: number; companyName: string }>>([])
|
||||
/** 操作者自己那家公司(会话里的 current-user.companyId):建号弹窗据此判断当前 tab 是不是自己家。
|
||||
* 与 GroupEditorDialog 取的是同一个源——两处各取一份会靠约定对齐。 */
|
||||
const operatorCompanyId = computed<number | null>(() => session.user?.companyId ?? null)
|
||||
const filters = reactive<UserFilterState>(createUserFilterState())
|
||||
const isSuperAdmin = computed(() => session.isSuperAdmin)
|
||||
const operatorRole = computed(() => session.user?.role ?? null)
|
||||
const currentUserId = computed(() => session.user?.id ?? null)
|
||||
const statePhase = computed(() => listPhaseOf({ loading: loading.value, error: loadError.value, items: rows.value, total: total.value }))
|
||||
const jumpPage = ref('')
|
||||
const totalPages = computed(() => Math.max(1, totalPageCount(total.value, filters.pageSize)))
|
||||
|
||||
const createVisible = ref(false)
|
||||
const editVisible = ref(false)
|
||||
const editUser = ref<AdminUser | null>(null)
|
||||
|
||||
function openCreate(): void {
|
||||
createVisible.value = true
|
||||
}
|
||||
|
||||
function openEdit(row: AdminUser): void {
|
||||
if (!editableBy(row.role, operatorRole.value)) return
|
||||
editUser.value = row
|
||||
editVisible.value = true
|
||||
}
|
||||
|
||||
function editableOf(row: AdminUser): boolean {
|
||||
return editableBy(row.role, operatorRole.value)
|
||||
}
|
||||
|
||||
/** 上架上限列文案(仅京东侧渲染该列):null=旧数据未配('-'),0=不限,其余为具体条数。 */
|
||||
function quotaCellText(row: AdminUser): string {
|
||||
if (row.jdPublishQuota == null) return '-'
|
||||
return row.jdPublishQuota === 0 ? '不限' : String(row.jdPublishQuota)
|
||||
}
|
||||
|
||||
/** 列表请求参数 = 用户填的筛选态 + 当前公司 + 当前平台。公司/平台值每次现取、不写进 filters:
|
||||
* 它们由上方 tab 决定而不是用户填的筛选项,住进 filters 就等于多出第二个取值口径(Store 之外再长一个)。 */
|
||||
function listParams() {
|
||||
return { ...toUserListParams(filters), companyId: companyTab.requestCompanyId, platform: platformTab.active }
|
||||
}
|
||||
|
||||
async function loadUsers() {
|
||||
// S1-F4:快速切公司/翻页时旧响应可能后返回并覆盖新结果——回写前必须过竞态门
|
||||
const token = gate.begin()
|
||||
loading.value = true
|
||||
loadError.value = ''
|
||||
try {
|
||||
const page = await fetchUserList(listParams())
|
||||
if (!gate.isCurrent(token)) return
|
||||
rows.value = page.items
|
||||
total.value = page.total
|
||||
if (Array.isArray(page.admins)) admins.value = page.admins
|
||||
// 数据被删/筛选后总页数收缩:页码越界时回钳到末页并重新加载一次。
|
||||
const last = totalPageCount(page.total, filters.pageSize)
|
||||
if (last > 0 && filters.page > last) {
|
||||
filters.page = last
|
||||
const retried = await fetchUserList(listParams())
|
||||
if (!gate.isCurrent(token)) return
|
||||
rows.value = retried.items
|
||||
total.value = retried.total
|
||||
}
|
||||
} catch (error) {
|
||||
if (!gate.isCurrent(token)) return
|
||||
loadError.value = error instanceof Error ? error.message : '用户列表加载失败'
|
||||
showAdminFeedback(loadError.value, 'error')
|
||||
} finally {
|
||||
if (gate.isCurrent(token)) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 错误态重试:重新拉取当前筛选列表。 */
|
||||
function retry() {
|
||||
void loadUsers()
|
||||
}
|
||||
|
||||
/** 提交新筛选条件:重置回第一页再查询。 */
|
||||
function search() {
|
||||
filters.page = 1
|
||||
void loadUsers()
|
||||
}
|
||||
|
||||
async function removeUser(row: AdminUser) {
|
||||
const reason = deleteBlockReason(row, currentUserId.value)
|
||||
if (reason) {
|
||||
ElMessage.warning(reason)
|
||||
return
|
||||
}
|
||||
// 对齐旧版:浏览器原生 confirm 确认后删除。
|
||||
if (!(await openAdminConfirm({ message: deleteConfirmMessage(row), danger: true }))) return
|
||||
try {
|
||||
await deleteUser(row.id)
|
||||
ElMessage.success('删除成功')
|
||||
await loadUsers()
|
||||
} catch (error) {
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
/** 停用/解除停用:先过身份闸,原生 confirm 说出代价(对方会被强制退出到登录页)后提交。 */
|
||||
async function toggleDisable(row: AdminUser) {
|
||||
const wantDisable = !row.disabledAt
|
||||
const reason = disableBlockReason(row, currentUserId.value)
|
||||
if (reason) {
|
||||
ElMessage.warning(reason)
|
||||
return
|
||||
}
|
||||
if (!(await openAdminConfirm({ message: disableConfirmMessage(row, wantDisable), danger: false }))) return
|
||||
try {
|
||||
await setUserDisabled(row.id, wantDisable)
|
||||
ElMessage.success(wantDisable ? '已停用,该账号会被强制退出到登录页' : '已解除停用')
|
||||
await loadUsers()
|
||||
} catch (error) {
|
||||
showAdminFeedback(error instanceof Error ? error.message : '操作失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
function changePage(page: number) {
|
||||
filters.page = page
|
||||
void loadUsers()
|
||||
}
|
||||
|
||||
function changeSize(size: number) {
|
||||
filters.pageSize = size
|
||||
filters.page = 1
|
||||
void loadUsers()
|
||||
}
|
||||
|
||||
function goJump() {
|
||||
const n = Number.parseInt(jumpPage.value, 10)
|
||||
if (Number.isNaN(n)) {
|
||||
ElMessage.warning('请输入页码')
|
||||
return
|
||||
}
|
||||
changePage(Math.min(Math.max(n, 1), totalPages.value))
|
||||
}
|
||||
|
||||
// 切公司 = 重新取数,并清掉两处上一家遗留:
|
||||
// ①「所属管理员」下拉的候选(admins)随本公司的列表响应给出,上一家选中的 adminId 在新一家的下拉里不存在;
|
||||
// ② 用户名全平台唯一(V143 的唯一索引),留着上一家填的关键字去筛新一家 ⇒ 必然空页,而输入框还显示着那个值。
|
||||
watch(() => companyTab.activeId, () => { filters.createdByAdminId = null; filters.keyword = ''; filters.page = 1; void loadUsers() })
|
||||
|
||||
// 切平台 tab(V206)= 同样的重取数:列表按平台过滤,候选/关键字跨平台无意义,一并清掉。
|
||||
watch(() => platformTab.active, () => {
|
||||
filters.createdByAdminId = null
|
||||
filters.keyword = ''
|
||||
filters.page = 1
|
||||
void loadUsers()
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
void loadUsers()
|
||||
// 公司目录仅站点超管拉取(建「公司超级管理员」时选公司用);非超管不发这个请求,后端 403 兜底
|
||||
if (isSuperAdmin.value) {
|
||||
void fetchCompanies()
|
||||
.then((items) => {
|
||||
companyOptions.value = items.map((c) => ({ id: c.id, companyName: c.companyName }))
|
||||
})
|
||||
.catch(() => {
|
||||
companyOptions.value = []
|
||||
})
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="users-view">
|
||||
<section class="panel-box">
|
||||
<div class="users-head">
|
||||
<h3>用户列表</h3>
|
||||
<button class="btn" type="button" @click="openCreate">新建用户</button>
|
||||
</div>
|
||||
<p class="users-desc">当前没有开放注册入口,仅管理员可在此创建用户。层级关系:超级管理员 -> 管理员 -> 普通账号。</p>
|
||||
|
||||
<div class="form-row users-filter-row">
|
||||
<div class="form-group" style="min-width: 180px">
|
||||
<label>用户名(模糊搜索)</label>
|
||||
<input v-model="filters.keyword" type="text" placeholder="输入用户名关键字" @keyup.enter="search" />
|
||||
</div>
|
||||
<div v-if="isSuperAdmin" class="form-group" style="min-width: 160px">
|
||||
<label>所属管理员</label>
|
||||
<el-select v-model="filters.createdByAdminId" class="admin-filter" filterable clearable placeholder="全部" @change="search">
|
||||
<el-option v-for="admin in admins" :key="admin.id" :label="admin.username" :value="admin.id" />
|
||||
</el-select>
|
||||
</div>
|
||||
<div class="form-group" style="min-width: 140px">
|
||||
<label>角色</label>
|
||||
<el-select v-model="filters.role" class="admin-filter" filterable clearable placeholder="全部角色" @change="search">
|
||||
<el-option label="超级管理员" value="super_admin" />
|
||||
<el-option label="公司超级管理员" value="company_super_admin" />
|
||||
<el-option label="管理员" value="admin" />
|
||||
<el-option label="普通账号" value="normal" />
|
||||
</el-select>
|
||||
</div>
|
||||
<button class="btn" type="button" @click="search">查询</button>
|
||||
</div>
|
||||
|
||||
<div v-if="statePhase === 'error' && loadError" class="msg err">
|
||||
<span>加载失败: {{ loadError }}</span>
|
||||
<button class="btn btn-sm btn-secondary" type="button" @click="retry">重试</button>
|
||||
</div>
|
||||
|
||||
<div class="table-scroll user-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 70px">ID</th>
|
||||
<th style="width: 180px">用户名</th>
|
||||
<th style="width: 140px">角色</th>
|
||||
<th style="width: 160px">所属管理员</th>
|
||||
<th style="width: 160px">到期时间</th>
|
||||
<th v-if="isJdSide" style="width: 110px">上架上限</th>
|
||||
<th style="width: 90px">状态</th>
|
||||
<th style="width: 180px">创建时间</th>
|
||||
<th style="width: 180px">更新时间</th>
|
||||
<th style="width: 160px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-if="rows.length">
|
||||
<tr v-for="row in rows" :key="row.id">
|
||||
<td>{{ row.id }}</td>
|
||||
<td>{{ row.username }}</td>
|
||||
<td>{{ roleLabel(row.role) }}</td>
|
||||
<td>{{ row.creatorUsername || '-' }}</td>
|
||||
<td :class="{ 'expiry-cell-expired': formatExpiryCell(row).expired }">
|
||||
{{ formatExpiryCell(row).text }}
|
||||
</td>
|
||||
<td v-if="isJdSide">{{ quotaCellText(row) }}</td>
|
||||
<td class="status-cell" :class="{ 'status-cell-disabled': !!row.disabledAt }" :title="row.disabledAt ? `停用于 ${row.disabledAt}` : undefined">
|
||||
{{ disabledBadgeText(row) }}
|
||||
</td>
|
||||
<td>{{ formatDateTime(row.createdAt) }}</td>
|
||||
<td>{{ formatDateTime(row.updatedAt) }}</td>
|
||||
<td class="ops-cell">
|
||||
<button
|
||||
class="btn btn-sm"
|
||||
type="button"
|
||||
:disabled="!editableOf(row)"
|
||||
:title="!editableOf(row) ? '该账号不可编辑' : undefined"
|
||||
@click="openEdit(row)"
|
||||
>
|
||||
编辑
|
||||
</button>
|
||||
<button
|
||||
class="btn btn-sm btn-secondary"
|
||||
type="button"
|
||||
:disabled="disableBlockReason(row, currentUserId) !== undefined || !editableOf(row)"
|
||||
:title="disableBlockReason(row, currentUserId) || (!editableOf(row) ? '该账号不可操作' : undefined)"
|
||||
@click="toggleDisable(row)"
|
||||
>
|
||||
{{ row.disabledAt ? '解除停用' : '停用' }}
|
||||
</button>
|
||||
<button
|
||||
class="btn btn-sm btn-danger"
|
||||
type="button"
|
||||
:disabled="deleteBlockReason(row, currentUserId) !== undefined"
|
||||
:title="deleteBlockReason(row, currentUserId) || undefined"
|
||||
@click="removeUser(row)"
|
||||
>
|
||||
删除
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td :colspan="isJdSide ? 10 : 9" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td :colspan="isJdSide ? 10 : 9" class="empty-tip">{{ userListEmptyHint() }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<OldPagination :total="total" :page="filters.page" :page-size="filters.pageSize" @change="changePage" @size-change="changeSize" />
|
||||
</section>
|
||||
|
||||
<CreateUserDialog
|
||||
v-model="createVisible"
|
||||
:operator-super="isSuperAdmin"
|
||||
:operator-role="operatorRole"
|
||||
:admin-options="admins"
|
||||
:company-options="companyOptions"
|
||||
:operator-company-id="operatorCompanyId"
|
||||
:active-company-id="companyTab.requestCompanyId"
|
||||
:platform="platformTab.active"
|
||||
@created="loadUsers"
|
||||
/>
|
||||
<EditUserDialog v-model="editVisible" :user="editUser" :operator-super="isSuperAdmin" :company-id="companyTab.requestCompanyId" :platform="platformTab.active" @updated="loadUsers" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 像素复刻旧版 admin.html panel-users(蓝白末层)。 */
|
||||
.users-view {
|
||||
font-family: inherit;
|
||||
color: #24384d;
|
||||
}
|
||||
.panel-box {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 20px 22px 24px;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(145deg, #ffffff, #f9fbfd);
|
||||
box-shadow: 0 1px 2px rgba(39, 67, 94, 0.04), 0 14px 30px -24px rgba(39, 67, 94, 0.28);
|
||||
}
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
color: #24384d;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
.users-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.users-desc {
|
||||
margin: 10px 0 16px;
|
||||
font-size: 13px;
|
||||
color: #5b6f83;
|
||||
}
|
||||
.form-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 14px 18px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.form-group label {
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.form-group input,
|
||||
.form-group select {
|
||||
min-width: 0;
|
||||
min-height: 42px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
color-scheme: light;
|
||||
outline: none;
|
||||
transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
|
||||
}
|
||||
.form-group input:hover,
|
||||
.form-group select:hover {
|
||||
border-color: #9fb7cd;
|
||||
}
|
||||
.form-group input:focus,
|
||||
.form-group select:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 42px;
|
||||
padding: 9px 18px;
|
||||
border: 1px solid #4f78a5;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 8px 18px -14px rgba(79, 120, 165, 0.72);
|
||||
transition: background 160ms ease, box-shadow 160ms ease, transform 120ms ease;
|
||||
}
|
||||
.btn:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #7094ba, #5d83ac);
|
||||
box-shadow: 0 11px 22px -14px rgba(79, 120, 165, 0.8);
|
||||
}
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: #ffffff;
|
||||
color: #5b6f83;
|
||||
border-color: #c7d7e5;
|
||||
}
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
color: #2f5d8b;
|
||||
border-color: #95b1cb;
|
||||
background: #edf5fb;
|
||||
}
|
||||
.btn-danger {
|
||||
background: linear-gradient(135deg, #c06d77, #b35f6a);
|
||||
border-color: #b35f6a;
|
||||
}
|
||||
.btn-danger:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #cb7c84, #b96570);
|
||||
}
|
||||
.btn-sm {
|
||||
min-height: 36px;
|
||||
padding: 7px 12px;
|
||||
}
|
||||
.msg {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 14px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid;
|
||||
border-radius: 9px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.msg.err {
|
||||
color: #91474f;
|
||||
background: #f8ebeb;
|
||||
border-color: #e4c2c5;
|
||||
}
|
||||
.table-scroll {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 10px;
|
||||
background: #ffffff;
|
||||
}
|
||||
.table-scroll table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
}
|
||||
.user-table-scroll > table {
|
||||
min-width: 1120px;
|
||||
}
|
||||
.table-scroll th,
|
||||
.table-scroll td {
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
font-size: 13.5px;
|
||||
line-height: 1.5;
|
||||
border-bottom: 1px solid #e0e8ef;
|
||||
vertical-align: middle;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.table-scroll th {
|
||||
background: #edf4fa;
|
||||
color: #4e6479;
|
||||
border-bottom-color: #d5e1eb;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.4px;
|
||||
}
|
||||
.table-scroll tbody tr:hover td {
|
||||
background: #f1f7fb;
|
||||
}
|
||||
.table-scroll tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.ops-cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
white-space: nowrap;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.expiry-cell-expired {
|
||||
color: #c0392b;
|
||||
font-weight: 600;
|
||||
}
|
||||
.status-cell {
|
||||
color: #3d7158;
|
||||
}
|
||||
.status-cell-disabled {
|
||||
color: #91474f;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.empty-tip {
|
||||
padding: 44px 24px;
|
||||
text-align: center;
|
||||
color: #8293a5;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.pagination {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-top: 18px;
|
||||
color: #5b6f83;
|
||||
font-size: 13px;
|
||||
}
|
||||
.pagination button {
|
||||
min-height: 30px;
|
||||
padding: 4px 12px;
|
||||
border: 1px solid #c7d7e5;
|
||||
border-radius: 8px;
|
||||
background: #ffffff;
|
||||
color: #5b6f83;
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.pagination button:hover:not(:disabled) {
|
||||
background: #edf5fb;
|
||||
border-color: #95b1cb;
|
||||
color: #2f5d8b;
|
||||
}
|
||||
.pagination button:disabled {
|
||||
background: #eef3f7;
|
||||
color: #9baaba;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.page-size-select {
|
||||
min-height: 30px;
|
||||
padding: 3px 8px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 8px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
}
|
||||
.page-total {
|
||||
margin-right: 4px;
|
||||
}
|
||||
.page-jump {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.page-jump input {
|
||||
width: 56px;
|
||||
min-height: 30px;
|
||||
padding: 4px 8px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 8px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
}
|
||||
</style>
|
||||
@@ -1,60 +0,0 @@
|
||||
/** 菜单管理列表加载适配(任务 54):GET /api/admin/permission-menus(admin) → 展示树。 */
|
||||
import { http } from '@/api/http'
|
||||
import { unwrap } from '@/api/envelope'
|
||||
import {
|
||||
buildMenuManageTree,
|
||||
parseMenuManageItem,
|
||||
parseMenuManageList,
|
||||
toMenuCreateRequest,
|
||||
toMenuUpdateRequest,
|
||||
type MenuManageForm,
|
||||
type MenuManageNode,
|
||||
} from './menu-manage-model'
|
||||
|
||||
export const MENUS_ENDPOINT = '/api/admin/permission-menus'
|
||||
export const REORDER_ENDPOINT = '/api/admin/column/reorder'
|
||||
|
||||
/** 拉取扁平可编辑菜单节点(全量类型,对齐 admin.js loadColumns 的 /api/admin/columns 语义)。
|
||||
* 公司 tab 的值由调用方(MenusPage)传 companyTab.requestCompanyId:菜单字典 2026-10-06 起每家公司一套树,
|
||||
* 不带 company_id 时后端一律取操作者本公司(2026-10-06 生产实测:超管不带也只得本公司那 26 行),
|
||||
* 所以切到别家必须显式传,tab 的值不能省。 */
|
||||
export async function fetchMenuManageNodes(companyId?: number | null): Promise<MenuManageNode[]> {
|
||||
const query: Record<string, string | number> = {}
|
||||
if (companyId != null) query.company_id = companyId
|
||||
const { data } = await http.get<unknown>(MENUS_ENDPOINT, { params: query })
|
||||
return parseMenuManageList(data)
|
||||
}
|
||||
|
||||
/** 拉取并按 parentId 组装成展示树。 */
|
||||
export async function loadMenuManageTree(companyId?: number | null): Promise<MenuManageNode[]> {
|
||||
return buildMenuManageTree(await fetchMenuManageNodes(companyId))
|
||||
}
|
||||
|
||||
/** 新建菜单:POST /api/admin/permission-menus,返回后端落库节点。
|
||||
* 归属由端点的 company_id 决定(缺省=操作者本公司),前端不靠从树里猜。 */
|
||||
export async function createMenu(form: MenuManageForm, companyId?: number | null): Promise<MenuManageNode> {
|
||||
const query: Record<string, string | number> = {}
|
||||
if (companyId != null) query.company_id = companyId
|
||||
const { data } = await http.post<unknown>(MENUS_ENDPOINT, toMenuCreateRequest(form), { params: query })
|
||||
const created = parseMenuManageItem(unwrap<unknown>(data))
|
||||
if (!created) throw new Error('创建菜单响应异常:缺少菜单数据')
|
||||
return created
|
||||
}
|
||||
|
||||
/** 编辑菜单:PUT /api/admin/permission-menus/{id},success=false 由 unwrap 抛后端 message。 */
|
||||
export async function updateMenu(id: number, form: MenuManageForm): Promise<void> {
|
||||
const { data } = await http.put<unknown>(`${MENUS_ENDPOINT}/${id}`, toMenuUpdateRequest(form))
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
|
||||
/** 删除菜单:DELETE /api/admin/permission-menus/{id},success=false 由 unwrap 抛后端 message。 */
|
||||
export async function deleteMenu(id: number): Promise<void> {
|
||||
const { data } = await http.delete<unknown>(`${MENUS_ENDPOINT}/${id}`)
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
|
||||
/** 同级菜单排序:POST /api/admin/column/reorder 提交 { menu_type, ordered_ids }(对齐 admin.js persistColumnOrder)。 */
|
||||
export async function reorderMenus(menuType: string, orderedIds: number[]): Promise<void> {
|
||||
const { data } = await http.post<unknown>(REORDER_ENDPOINT, { menu_type: menuType, ordered_ids: orderedIds })
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
@@ -1,291 +0,0 @@
|
||||
/** 菜单管理 DTO/模型(任务 53):扁平 PermissionMenuItemVo → 可编辑节点 + 创建/更新请求体。 */
|
||||
import { unwrap } from '../../api/envelope.ts'
|
||||
|
||||
/** 后台 Vue 控制台菜单类型。 */
|
||||
export const ADMIN_MENU_TYPE = 'admin'
|
||||
|
||||
export interface MenuManageNode {
|
||||
id: number
|
||||
name: string
|
||||
/** column_key,稳定权限标识。 */
|
||||
columnKey: string
|
||||
parentId: number | null
|
||||
rootColumnKey?: string
|
||||
menuType: string
|
||||
routePath: string
|
||||
sortOrder: number
|
||||
createdAt?: string
|
||||
updatedAt?: string
|
||||
children?: MenuManageNode[]
|
||||
}
|
||||
|
||||
/** 菜单类型展示文案(对齐 admin.js:6824:admin → 后台,其余一律 → 软件)。 */
|
||||
export function menuTypeLabel(type: string | null | undefined): string {
|
||||
return (type || '').toLowerCase() === 'admin' ? '后台' : '软件'
|
||||
}
|
||||
|
||||
/** 菜单类型下拉选项(对齐 admin.html:5931-5934 后台/软件)。 */
|
||||
export const MENU_TYPE_OPTIONS: Array<{ value: 'admin' | 'app'; label: string }> = [
|
||||
{ value: 'admin', label: '后台' },
|
||||
{ value: 'app', label: '软件' },
|
||||
]
|
||||
|
||||
export interface MenuManageForm {
|
||||
name: string
|
||||
columnKey: string
|
||||
parentId: number | null
|
||||
menuType: string
|
||||
routePath: string
|
||||
sortOrder: number
|
||||
}
|
||||
|
||||
/** 请求体字段与 Java PermissionMenuCreate/UpdateRequest 对齐(camelCase)。
|
||||
* 权限标识/路由由后台自动生成,不随表单提交,故为可选字段。 */
|
||||
export interface MenuManagePayload {
|
||||
name: string
|
||||
columnKey?: string
|
||||
parentId: number | null
|
||||
menuType: string
|
||||
routePath?: string
|
||||
sortOrder: number
|
||||
}
|
||||
|
||||
export interface MenuManageFormErrors {
|
||||
name?: string
|
||||
columnKey?: string
|
||||
menuType?: string
|
||||
routePath?: string
|
||||
}
|
||||
|
||||
function numberOrNull(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : null
|
||||
}
|
||||
|
||||
function text(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : ''
|
||||
}
|
||||
|
||||
/** 排序归一:非负整数,非法回 0。 */
|
||||
export function normalizeMenuSort(value: unknown): number {
|
||||
const n = numberOrNull(value)
|
||||
return n !== null && n >= 0 ? n : 0
|
||||
}
|
||||
|
||||
/** 把单条 PermissionMenuItemVo(snake_case) 归一为可编辑节点;缺 id 视为无效。 */
|
||||
export function parseMenuManageItem(raw: unknown): MenuManageNode | null {
|
||||
if (!raw || typeof raw !== 'object') return null
|
||||
const record = raw as Record<string, unknown>
|
||||
const id = numberOrNull(record.id)
|
||||
if (id === null) return null
|
||||
const parentId = numberOrNull(record.parent_id)
|
||||
const node: MenuManageNode = {
|
||||
id,
|
||||
name: text(record.name),
|
||||
columnKey: text(record.column_key),
|
||||
parentId: parentId === null ? null : parentId,
|
||||
menuType: text(record.menu_type) || ADMIN_MENU_TYPE,
|
||||
routePath: text(record.route_path),
|
||||
sortOrder: normalizeMenuSort(record.sort_order),
|
||||
}
|
||||
const rootColumnKey = text(record.root_column_key)
|
||||
if (rootColumnKey) node.rootColumnKey = rootColumnKey
|
||||
const createdAt = text(record.created_at)
|
||||
if (createdAt) node.createdAt = createdAt
|
||||
const updatedAt = text(record.updated_at)
|
||||
if (updatedAt) node.updatedAt = updatedAt
|
||||
return node
|
||||
}
|
||||
|
||||
/** 归一化 permission-menus 响应(信封或裸数组)为可编辑节点列表。 */
|
||||
export function parseMenuManageList(payload: unknown): MenuManageNode[] {
|
||||
const data = unwrap<unknown>(payload)
|
||||
if (!Array.isArray(data)) return []
|
||||
return data
|
||||
.map((raw) => parseMenuManageItem(raw))
|
||||
.filter((node): node is MenuManageNode => node !== null)
|
||||
}
|
||||
|
||||
/** 按 parentId 组装展示树;同级按 (sortOrder,name) 升序,父缺失按根处理。 */
|
||||
export function buildMenuManageTree(items: MenuManageNode[]): MenuManageNode[] {
|
||||
const nodes = new Map<number, MenuManageNode>()
|
||||
for (const item of items) {
|
||||
nodes.set(item.id, { ...item, children: [] })
|
||||
}
|
||||
const roots: MenuManageNode[] = []
|
||||
for (const item of items) {
|
||||
const node = nodes.get(item.id)
|
||||
if (!node) continue
|
||||
const parent = item.parentId === null ? undefined : nodes.get(item.parentId)
|
||||
if (parent) {
|
||||
parent.children!.push(node)
|
||||
} else {
|
||||
roots.push(node)
|
||||
}
|
||||
}
|
||||
const order = (a: MenuManageNode, b: MenuManageNode) =>
|
||||
a.sortOrder - b.sortOrder || a.name.localeCompare(b.name)
|
||||
const sortRecursive = (nodes: MenuManageNode[]) => {
|
||||
nodes.sort(order)
|
||||
for (const node of nodes) node.children?.length && sortRecursive(node.children)
|
||||
}
|
||||
sortRecursive(roots)
|
||||
for (const item of items) {
|
||||
const node = nodes.get(item.id)
|
||||
if (node && !node.children?.length) delete node.children
|
||||
}
|
||||
return roots
|
||||
}
|
||||
|
||||
/** 展平树为列表(前序),供父级下拉/统计复用。 */
|
||||
export function flattenMenuNodes(nodes: MenuManageNode[]): MenuManageNode[] {
|
||||
const out: MenuManageNode[] = []
|
||||
const walk = (list: MenuManageNode[]) => {
|
||||
for (const node of list) {
|
||||
out.push(node)
|
||||
if (node.children?.length) walk(node.children)
|
||||
}
|
||||
}
|
||||
walk(nodes)
|
||||
return out
|
||||
}
|
||||
|
||||
/** 同级建议排序:该父下最大 sortOrder + 1;无同级返回 0。 */
|
||||
export function nextSiblingSort(items: MenuManageNode[], parentId: number | null): number {
|
||||
let max = -1
|
||||
for (const item of items) {
|
||||
if (item.parentId === parentId && item.sortOrder > max) max = item.sortOrder
|
||||
}
|
||||
return max + 1
|
||||
}
|
||||
|
||||
/** 新建菜单表单工厂:指定父节点与建议排序,其余默认(menuType=admin)。 */
|
||||
export function createMenuForm(parentId: number | null, sortOrder: number): MenuManageForm {
|
||||
return {
|
||||
...emptyMenuManageForm(),
|
||||
parentId: typeof parentId === 'number' ? parentId : null,
|
||||
sortOrder: normalizeMenuSort(sortOrder),
|
||||
}
|
||||
}
|
||||
|
||||
/** 编辑表单回填:从可编辑节点还原表单字段。 */
|
||||
export function menuFormFromNode(node: MenuManageNode): MenuManageForm {
|
||||
return {
|
||||
name: node.name,
|
||||
columnKey: node.columnKey,
|
||||
parentId: node.parentId,
|
||||
menuType: node.menuType,
|
||||
routePath: node.routePath,
|
||||
sortOrder: node.sortOrder,
|
||||
}
|
||||
}
|
||||
|
||||
/** 编辑时父节点防环校验:不可选自身或其子孙为父;返回可操作原因,否则 undefined。 */
|
||||
export function menuParentChangeReason(node: MenuManageNode, parentId: number | null): string | undefined {
|
||||
if (parentId === null || parentId === undefined) return undefined
|
||||
if (parentId === node.id) return '不能选择自身作为父菜单'
|
||||
const descendants = flattenMenuNodes(node.children ?? [])
|
||||
if (descendants.some((item) => item.id === parentId)) return '不能选择自己的子菜单作为父菜单'
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** 删除前置校验(镜像后端:仅叶子可删,避免孤儿层级);可删返回 undefined。 */
|
||||
export function menuDeleteReason(node: MenuManageNode | null | undefined): string | undefined {
|
||||
const children = node?.children
|
||||
if (Array.isArray(children) && children.length > 0) return '请先删除该菜单下的子菜单'
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** 同级拖拽/上下移:把 targetId 移动 dir 位(±1),返回新的同级 id 顺序;越界/缺失则原序。 */
|
||||
export function siblingOrderAfterMove(group: number[], targetId: number, dir: number): number[] {
|
||||
if (!Array.isArray(group) || group.length === 0) return []
|
||||
const next = [...group]
|
||||
const idx = next.indexOf(targetId)
|
||||
if (idx < 0) return next
|
||||
const to = idx + (dir === -1 || dir === 1 ? dir : 0)
|
||||
if (to < 0 || to >= next.length) return next
|
||||
const [moved] = next.splice(idx, 1)
|
||||
next.splice(to, 0, moved)
|
||||
return next
|
||||
}
|
||||
|
||||
/** 拖拽分组键:同"菜单类型 + 父级"才算同级(对齐 admin.js columnSiblingGroupKey)。 */
|
||||
export function menuSiblingGroupKey(node: MenuManageNode): string {
|
||||
return `${node.menuType || 'app'}|${node.parentId ?? ''}`
|
||||
}
|
||||
|
||||
/** 拖放排序:把 draggedId 插到 targetId 前/后,返回新的同级 id 顺序;任一 id 缺失或同 id 则原序。 */
|
||||
export function siblingOrderAfterDrop(
|
||||
group: number[],
|
||||
draggedId: number,
|
||||
targetId: number,
|
||||
placeAfter: boolean,
|
||||
): number[] {
|
||||
if (!Array.isArray(group) || group.length === 0) return []
|
||||
if (draggedId === targetId) return [...group]
|
||||
const next = [...group]
|
||||
const from = next.indexOf(draggedId)
|
||||
if (from < 0) return next
|
||||
const target = next.indexOf(targetId)
|
||||
if (target < 0) return next
|
||||
next.splice(from, 1)
|
||||
const insertAt = next.indexOf(targetId) + (placeAfter ? 1 : 0)
|
||||
next.splice(insertAt, 0, draggedId)
|
||||
return next
|
||||
}
|
||||
|
||||
/** 父菜单候选:仅同菜单类型的节点(对齐 admin 的类型联动父级下拉)。 */
|
||||
export function menuParentCandidates(nodes: MenuManageNode[], menuType: string): MenuManageNode[] {
|
||||
const type = (menuType || '').trim()
|
||||
return flattenMenuNodes(nodes).filter((node) => (node.menuType || '') === type)
|
||||
}
|
||||
|
||||
/** 同级重排请求体(对齐 admin.js persistColumnOrder:{ menu_type, ordered_ids })。 */
|
||||
export function toMenuReorderRequest(
|
||||
menuType: string,
|
||||
orderedIds: number[],
|
||||
): { menu_type: string; ordered_ids: number[] } {
|
||||
return { menu_type: text(menuType) || 'app', ordered_ids: dedupeOrderIds(orderedIds) }
|
||||
}
|
||||
|
||||
function dedupeOrderIds(ids: unknown[]): number[] {
|
||||
if (!Array.isArray(ids)) return []
|
||||
const set = new Set<number>()
|
||||
for (const v of ids) {
|
||||
const n = numberOrNull(v)
|
||||
if (n !== null && n > 0) set.add(n)
|
||||
}
|
||||
return [...set]
|
||||
}
|
||||
|
||||
/** 新建/编辑表单空值工厂:默认菜单类型为 admin、排序 0、根父节点。 */
|
||||
export function emptyMenuManageForm(): MenuManageForm {
|
||||
return { name: '', columnKey: '', parentId: null, menuType: ADMIN_MENU_TYPE, routePath: '', sortOrder: 0 }
|
||||
}
|
||||
|
||||
/** 表单校验(镜像后端 NotBlank 文案);返回逐字段错误。权限标识/路由由后台自动生成,不参与校验。 */
|
||||
export function validateMenuManageForm(form: MenuManageForm): { valid: boolean; errors: MenuManageFormErrors } {
|
||||
const errors: MenuManageFormErrors = {}
|
||||
if (!text(form.name)) errors.name = '菜单名称不能为空'
|
||||
if (!text(form.menuType)) errors.menuType = '菜单类型不能为空'
|
||||
return { valid: Object.keys(errors).length === 0, errors }
|
||||
}
|
||||
|
||||
function toMenuManagePayload(form: MenuManageForm): MenuManagePayload {
|
||||
// 权限标识(column_key)/路由(route_path) 不随表单提交:由后台自动生成(创建)或保持原值(编辑)。
|
||||
return {
|
||||
name: text(form.name),
|
||||
parentId: typeof form.parentId === 'number' ? form.parentId : null,
|
||||
menuType: text(form.menuType),
|
||||
sortOrder: normalizeMenuSort(form.sortOrder),
|
||||
}
|
||||
}
|
||||
|
||||
/** 表单 → POST /api/admin/permission-menus 请求体。 */
|
||||
export function toMenuCreateRequest(form: MenuManageForm): MenuManagePayload {
|
||||
return toMenuManagePayload(form)
|
||||
}
|
||||
|
||||
/** 表单 → PUT /api/admin/permission-menus/{id} 请求体。 */
|
||||
export function toMenuUpdateRequest(form: MenuManageForm): MenuManagePayload {
|
||||
return toMenuManagePayload(form)
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
/** 数据权限分组 API 适配(任务 59;module 13 task 253 扩展 CRUD)。 */
|
||||
import { http } from '@/api/http'
|
||||
import { unwrap } from '@/api/envelope'
|
||||
import {
|
||||
parseShopGroupItem,
|
||||
parseShopGroupList,
|
||||
toShopGroupCreatePayload,
|
||||
toShopGroupUpdatePayload,
|
||||
type ShopGroupItem,
|
||||
} from './shop-group-model'
|
||||
|
||||
export const SHOP_GROUPS_ENDPOINT = '/api/admin/shop-manages/groups'
|
||||
|
||||
/** 列表:company_id 收公司口径(钉住的取值口),platform 收平台 tab 口径(V206),都缺省就不发。 */
|
||||
export async function fetchShopGroups(companyId?: number | null, platform?: string): Promise<ShopGroupItem[]> {
|
||||
const { data } = await http.get<unknown>(SHOP_GROUPS_ENDPOINT, {
|
||||
params: {
|
||||
...(companyId != null ? { company_id: companyId } : {}),
|
||||
...(platform ? { platform } : {}),
|
||||
},
|
||||
})
|
||||
return parseShopGroupList(data)
|
||||
}
|
||||
|
||||
/** 新建分组:POST /api/admin/shop-manages/groups(创建人 = 组长 = 当前操作者)。 */
|
||||
export async function createShopGroup(
|
||||
name: string,
|
||||
memberUserIds: number[],
|
||||
createdById: number,
|
||||
platform?: string,
|
||||
): Promise<ShopGroupItem> {
|
||||
const { data } = await http.post<unknown>(SHOP_GROUPS_ENDPOINT, toShopGroupCreatePayload(name, memberUserIds, createdById, platform))
|
||||
const created = parseShopGroupItem(unwrap<unknown>(data))
|
||||
if (!created) throw new Error('创建分组响应异常:缺少分组数据')
|
||||
return created
|
||||
}
|
||||
|
||||
/** 更新分组:PUT /api/admin/shop-manages/groups/{id}。 */
|
||||
export async function updateShopGroup(id: number, name: string, memberUserIds: number[], platform?: string): Promise<ShopGroupItem> {
|
||||
const { data } = await http.put<unknown>(`${SHOP_GROUPS_ENDPOINT}/${id}`, toShopGroupUpdatePayload(name, memberUserIds, platform))
|
||||
const updated = parseShopGroupItem(unwrap<unknown>(data))
|
||||
if (!updated) throw new Error('更新分组响应异常:缺少分组数据')
|
||||
return updated
|
||||
}
|
||||
|
||||
/** 删除分组:DELETE /api/admin/shop-manages/groups/{id}。 */
|
||||
export async function deleteShopGroup(id: number): Promise<void> {
|
||||
const { data } = await http.delete<unknown>(`${SHOP_GROUPS_ENDPOINT}/${id}`)
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
/** 数据权限分组列表模型(任务 59;module 13 task 253 扩展编辑能力):解析 VO + 摘要 + 提交载荷。 */
|
||||
import { unwrap } from '../../api/envelope.ts'
|
||||
import { isSuperAdminRole, roleKind } from '../../types/admin.ts'
|
||||
|
||||
export interface ShopGroupItem {
|
||||
id: number
|
||||
name: string
|
||||
leaderUsername: string
|
||||
leaderUserId?: number
|
||||
memberCount: number
|
||||
memberUsernames: string[]
|
||||
memberUserIds?: number[]
|
||||
createdAt?: string
|
||||
updatedAt?: string
|
||||
/** 所属平台(V206):'amazon'|'jd';旧负载缺省不渲染该键。 */
|
||||
platform?: string
|
||||
}
|
||||
|
||||
export interface ShopGroupFormErrors {
|
||||
groupName?: string
|
||||
}
|
||||
|
||||
function text(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : ''
|
||||
}
|
||||
|
||||
function numberOrNull(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : null
|
||||
}
|
||||
|
||||
/** 解析单条分组项;缺 id 视为无效。 */
|
||||
export function parseShopGroupItem(raw: unknown): ShopGroupItem | null {
|
||||
if (!raw || typeof raw !== 'object') return null
|
||||
const record = raw as Record<string, unknown>
|
||||
const id = numberOrNull(record.id)
|
||||
if (id === null) return null
|
||||
const names = Array.isArray(record.memberUsernames)
|
||||
? record.memberUsernames.map((v) => text(v)).filter(Boolean)
|
||||
: []
|
||||
const memberIds = Array.isArray(record.memberUserIds)
|
||||
? record.memberUserIds.map((v) => numberOrNull(v)).filter((v): v is number => v !== null && v > 0)
|
||||
: []
|
||||
const count = numberOrNull(record.memberCount)
|
||||
const item: ShopGroupItem = {
|
||||
id,
|
||||
name: text(record.groupName ?? record.name) || `分组${id}`,
|
||||
leaderUsername: text(record.leaderUsername ?? record.leader_name),
|
||||
memberCount: count === null ? names.length : count,
|
||||
memberUsernames: names,
|
||||
}
|
||||
const leaderId = numberOrNull(record.leaderUserId ?? record.leader_user_id)
|
||||
if (leaderId !== null && leaderId > 0) item.leaderUserId = leaderId
|
||||
if (memberIds.length) item.memberUserIds = memberIds
|
||||
const createdAt = text(record.createdAt ?? record.created_at)
|
||||
if (createdAt) item.createdAt = createdAt
|
||||
const updatedAt = text(record.updatedAt ?? record.updated_at)
|
||||
if (updatedAt) item.updatedAt = updatedAt
|
||||
const platform = text(record.platform)
|
||||
if (platform) item.platform = platform
|
||||
return item
|
||||
}
|
||||
|
||||
/** 归一化分组列表响应(信封或裸数组)。 */
|
||||
export function parseShopGroupList(payload: unknown): ShopGroupItem[] {
|
||||
const data = unwrap<unknown>(payload)
|
||||
if (!Array.isArray(data)) return []
|
||||
return data
|
||||
.map((raw) => parseShopGroupItem(raw))
|
||||
.filter((item): item is ShopGroupItem => item !== null)
|
||||
}
|
||||
|
||||
/** 分组摘要:分组总数 + 组员总数。 */
|
||||
export function shopGroupSummary(groups: ShopGroupItem[]): { groupCount: number; memberTotal: number } {
|
||||
let memberTotal = 0
|
||||
for (const group of groups) memberTotal += group.memberCount || 0
|
||||
return { groupCount: groups.length, memberTotal }
|
||||
}
|
||||
|
||||
/** 分组名必填校验(镜像后端 NotBlank 文案「请输入分组名称」)。 */
|
||||
export function validateShopGroupForm(name: string): ShopGroupFormErrors {
|
||||
const errors: ShopGroupFormErrors = {}
|
||||
if (!text(name)) errors.groupName = '请输入分组名称'
|
||||
return errors
|
||||
}
|
||||
|
||||
/** 创建载荷:groupName + 成员 + 创建人(= 组长,当前操作者)+ 所属平台(V206,缺省不下发)。 */
|
||||
export function toShopGroupCreatePayload(
|
||||
name: string,
|
||||
memberUserIds: number[],
|
||||
createdById: number,
|
||||
platform?: string,
|
||||
): { groupName: string; memberUserIds: number[]; createdById: number; platform?: string } {
|
||||
const payload: { groupName: string; memberUserIds: number[]; createdById: number; platform?: string } = {
|
||||
groupName: text(name),
|
||||
memberUserIds: dedupeIds(memberUserIds),
|
||||
createdById,
|
||||
}
|
||||
if (platform) payload.platform = platform
|
||||
return payload
|
||||
}
|
||||
|
||||
/** 更新载荷:groupName + 成员 + 所属平台(V206;组长/创建人不可改)。 */
|
||||
export function toShopGroupUpdatePayload(
|
||||
name: string,
|
||||
memberUserIds: number[],
|
||||
platform?: string,
|
||||
): { groupName: string; memberUserIds: number[]; platform?: string } {
|
||||
const payload: { groupName: string; memberUserIds: number[]; platform?: string } = {
|
||||
groupName: text(name),
|
||||
memberUserIds: dedupeIds(memberUserIds),
|
||||
}
|
||||
if (platform) payload.platform = platform
|
||||
return payload
|
||||
}
|
||||
|
||||
/** 组员候选用户(对齐 admin.js getEligibleShopManageGroupUsers 的过滤语义)。 */
|
||||
export interface GroupMemberCandidateUser {
|
||||
id: number
|
||||
username: string
|
||||
role: string
|
||||
createdById?: number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 超管(站点与公司两档)永不进组员候选——它是那家公司的最高账号,不属于任何分组。
|
||||
* 与后端 `ShopManageGroupService#resolveMembers` 抛的「超级管理员不属于任何分组」同一口径。
|
||||
*/
|
||||
export function isGroupIneligibleRole(role: string | null | undefined): boolean {
|
||||
const kind = roleKind(role)
|
||||
return kind === 'super_admin' || kind === 'company_super_admin'
|
||||
}
|
||||
|
||||
/**
|
||||
* 组员候选过滤(对齐 admin.js:3020-3028,2026-10-07 收口):
|
||||
* - 组长本人永不进候选;
|
||||
* - 超管(站点/公司)永不进候选;
|
||||
* - 超管操作者可选本公司全部账号(公司维度由请求的 company_id 收窄,不在这里再判一次);
|
||||
* - 其余操作者仅可选"组长(创建人)名下"的普通账号。
|
||||
*/
|
||||
export function eligibleGroupMembers(
|
||||
users: GroupMemberCandidateUser[],
|
||||
leaderUserId: number | null,
|
||||
operatorRole: string,
|
||||
): GroupMemberCandidateUser[] {
|
||||
const leaderKey = leaderUserId != null && leaderUserId > 0 ? String(leaderUserId) : ''
|
||||
const isSuper = isSuperAdminRole(operatorRole)
|
||||
return users.filter((u) => {
|
||||
if (String(u.id) === leaderKey) return false
|
||||
if (isGroupIneligibleRole(u.role)) return false
|
||||
if (isSuper) return true
|
||||
return (
|
||||
(u.role || '').toLowerCase() === 'normal' &&
|
||||
String(u.createdById ?? '') === leaderKey
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/** 组员候选帮助文案(对齐 admin.js:3179-3182)。 */
|
||||
export function groupMemberCandidateHint(candidateCount: number, operatorRole: string): string {
|
||||
if (candidateCount > 0) return '可添加当前组长创建的普通员工账号'
|
||||
return (operatorRole || '').toLowerCase() === 'normal'
|
||||
? '普通账号没有下属普通员工时,这里会为空;当前账号只能作为组长使用。'
|
||||
: '当前组长名下暂无可添加的普通员工账号。'
|
||||
}
|
||||
|
||||
function dedupeIds(ids: unknown[]): number[] {
|
||||
if (!Array.isArray(ids)) return []
|
||||
const set = new Set<number>()
|
||||
for (const v of ids) {
|
||||
const id = numberOrNull(v)
|
||||
if (id !== null && id > 0) set.add(id)
|
||||
}
|
||||
return [...set].sort((a, b) => a - b)
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
/** 新建用户请求适配(任务 46):表单模型 → POST /api/admin/user → 新用户 id。 */
|
||||
import { http } from '@/api/http'
|
||||
import { parseCreatedUserId } from '@/api/users-model'
|
||||
import {
|
||||
toCreateUserRequest,
|
||||
validateCreateUserForm,
|
||||
type CreateUserForm,
|
||||
} from './user-create-model'
|
||||
|
||||
/** Java AdminUserController.createUser 端点。 */
|
||||
export const CREATE_USER_ENDPOINT = '/api/admin/user'
|
||||
|
||||
/**
|
||||
* 提交新建用户:先校验表单(不通过直接抛首条错误,不发请求),再序列化请求体 POST,
|
||||
* 最后解析返回的新用户 id;http/后端失败交由调用方提示,不吞异常。
|
||||
*/
|
||||
export async function submitCreateUser(form: CreateUserForm): Promise<number> {
|
||||
const { valid, errors } = validateCreateUserForm(form)
|
||||
if (!valid) {
|
||||
throw new Error(Object.values(errors)[0] || '创建用户表单校验未通过')
|
||||
}
|
||||
const { data } = await http.post<unknown>(CREATE_USER_ENDPOINT, toCreateUserRequest(form))
|
||||
return parseCreatedUserId(data)
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
/** 新建用户表单模型(任务 45):纯逻辑,镜像 Java AdminUserCreateRequest 字段与后端校验。 */
|
||||
import type { PlatformTabId } from '../../config/platform-scope.ts'
|
||||
|
||||
export const CREATE_USERNAME_MIN_LEN = 2
|
||||
export const CREATE_PASSWORD_MIN_LEN = 6
|
||||
|
||||
/**
|
||||
* 新建用户可选角色:super_admin 不可由表单创建;company_super_admin 仅站点超管可选
|
||||
* (后端 403「只有超级管理员可以创建公司超级管理员」兜底)。
|
||||
*/
|
||||
export type CreatableUserRole = 'normal' | 'admin' | 'company_super_admin'
|
||||
|
||||
export interface CreateUserForm {
|
||||
username: string
|
||||
password: string
|
||||
role: CreatableUserRole
|
||||
/** 授权菜单 id(后端 replaceDirectPermissions 用)。 */
|
||||
columnIds: number[]
|
||||
/** 所属管理员 id(超管创建普通账号时可指定,对齐 admin 的 created_by_id)。 */
|
||||
createdBy?: number | null
|
||||
/** 到期时间(yyyy-MM-dd HH:mm:ss);空串 = 永不过期(V146)。 */
|
||||
expiresAt: string
|
||||
/** 所属公司 id:仅 role=company_super_admin 时由站点超管必选(2026-10-05 需求)。 */
|
||||
companyId?: number | null
|
||||
/** 所属平台(V206):弹窗打开时预填当前平台 tab,单选可改。 */
|
||||
platform: PlatformTabId
|
||||
}
|
||||
|
||||
export interface CreateUserFormErrors {
|
||||
username?: string
|
||||
password?: string
|
||||
companyId?: string
|
||||
}
|
||||
|
||||
/** 发送 POST /api/admin/user 的请求体(与 Java AdminUserCreateRequest camelCase 对齐)。 */
|
||||
export interface CreateUserPayload {
|
||||
username: string
|
||||
password: string
|
||||
role: string
|
||||
columnIds: number[]
|
||||
/** 仅 role=normal 且选了所属管理员时发送,与参考 admin.js 的 created_by_id 语义一致。 */
|
||||
createdById?: number
|
||||
/** 到期时间;空串=永不过期,不下发。 */
|
||||
expiresAt?: string
|
||||
/** 仅 role=company_super_admin 且显式选了公司时下发——这是「建号不带 company_id」
|
||||
* 反向钉(company-user-create.test.ts)唯一豁免的例外:公司超管必须落指定公司,
|
||||
* 否则会静默落操作者自己的公司(公司 1),用户需求就是给别家公司开超管。 */
|
||||
companyId?: number
|
||||
/** 所属平台(V206):恒下发(弹窗单选默认当前平台 tab),缺省后端落 amazon。 */
|
||||
platform: PlatformTabId
|
||||
}
|
||||
|
||||
export function createEmptyCreateUserForm(): CreateUserForm {
|
||||
return { username: '', password: '', role: 'normal', columnIds: [], createdBy: null, expiresAt: '', companyId: null, platform: 'amazon' }
|
||||
}
|
||||
|
||||
/** 未知/空白/超管角色归一:admin/company_super_admin/normal 白名单,其余归 normal。 */
|
||||
export function normalizeCreateRole(role: string | null | undefined): CreatableUserRole {
|
||||
const value = (role || '').trim().toLowerCase()
|
||||
if (value === 'admin') return 'admin'
|
||||
if (value === 'company_super_admin') return 'company_super_admin'
|
||||
return 'normal'
|
||||
}
|
||||
|
||||
/**
|
||||
* 目标公司是否不是操作者自己那家。任一侧未知时按「不算跨家」处理——未知不是证据,
|
||||
* 拿它当证据会把管理员/普通账号的选项从自己家公司面前也收走。
|
||||
*/
|
||||
export function isCrossCompanyTarget(
|
||||
operatorCompanyId: number | null | undefined,
|
||||
targetCompanyId: number | null | undefined,
|
||||
): boolean {
|
||||
return operatorCompanyId != null && targetCompanyId != null && operatorCompanyId !== targetCompanyId
|
||||
}
|
||||
|
||||
/**
|
||||
* 建号弹窗的可选角色(2026-10-07 口径):站点超管停在别家公司 tab 上时,只剩「给那家开一个
|
||||
* 公司超级管理员」;组长与普通账号由那家自己的公司超管开设。
|
||||
*
|
||||
* 与后端 `AdminUserService#ensureSubSuperAccountStaysWithOperatorCompany` 同一口径,两端各写
|
||||
* 一遍的前提是这两处永远一起改——所以这里做成纯函数,用例直接喂三种角色×两种公司组合。
|
||||
*/
|
||||
export function resolveRoleChoices(
|
||||
operatorSuper: boolean,
|
||||
operatorCompanyId: number | null | undefined,
|
||||
targetCompanyId: number | null | undefined,
|
||||
): CreatableUserRole[] {
|
||||
if (!operatorSuper) return ['admin', 'normal']
|
||||
if (isCrossCompanyTarget(operatorCompanyId, targetCompanyId)) return ['company_super_admin']
|
||||
return ['company_super_admin', 'admin', 'normal']
|
||||
}
|
||||
|
||||
/**
|
||||
* 弹窗默认选中的角色:普通账号优先——那是历史默认值,也是用得最多的一档。
|
||||
* 只有 tab 收窄到不给选普通账号时(跨家公司)才退到唯一合法项,否则超管一进弹窗就落在
|
||||
* 「公司超级管理员」上,点一次创建就多出一个超管账号。
|
||||
*/
|
||||
export function defaultRoleChoice(choices: CreatableUserRole[]): CreatableUserRole {
|
||||
return choices.includes('normal') ? 'normal' : choices[0]
|
||||
}
|
||||
|
||||
/**
|
||||
* 可携带「自己的到期时间」的角色,与后端 AdminUserService#mayCarryOwnExpiry 逐字对齐
|
||||
* (normal-account-no-own-expiry.test.ts 钉两端集合相等)。普通账号的停用只由上级
|
||||
* (组长/公司超管)级联决定,给它单独设到期时间既没入口也没语义。
|
||||
*/
|
||||
export const EXPIRY_OWNABLE_ROLES: ReadonlyArray<string> = ['admin', 'company_super_admin']
|
||||
|
||||
export function mayCarryOwnExpiry(role: string | null | undefined): boolean {
|
||||
return EXPIRY_OWNABLE_ROLES.includes((role || '').trim().toLowerCase())
|
||||
}
|
||||
|
||||
/** 表单校验(镜像后端:用户名≥2、密码≥6、均必填;公司超管必须选公司);返回逐字段错误。 */
|
||||
export function validateCreateUserForm(form: CreateUserForm): {
|
||||
valid: boolean
|
||||
errors: CreateUserFormErrors
|
||||
} {
|
||||
const errors: CreateUserFormErrors = {}
|
||||
const username = (form.username || '').trim()
|
||||
if (!username) {
|
||||
errors.username = '用户名不能为空'
|
||||
} else if (username.length < CREATE_USERNAME_MIN_LEN) {
|
||||
errors.username = `用户名至少${CREATE_USERNAME_MIN_LEN}个字符`
|
||||
}
|
||||
const password = form.password || ''
|
||||
if (!password) {
|
||||
errors.password = '密码不能为空'
|
||||
} else if (password.length < CREATE_PASSWORD_MIN_LEN) {
|
||||
errors.password = `密码至少${CREATE_PASSWORD_MIN_LEN}个字符`
|
||||
}
|
||||
if (normalizeCreateRole(form.role) === 'company_super_admin' && form.companyId == null) {
|
||||
errors.companyId = '公司超级管理员必须指定所属公司'
|
||||
}
|
||||
return { valid: Object.keys(errors).length === 0, errors }
|
||||
}
|
||||
|
||||
/**
|
||||
* 表单 → 创建请求体:用户名去空格、角色归一、菜单 id 拷贝不共享引用;
|
||||
* createdById 仅在 role=normal 且选了所属管理员时携带(对齐 admin.js 的 created_by_id 语义)。
|
||||
*
|
||||
* <p>company_id 仅在 role=company_super_admin 且显式选择时下发(见 CreateUserPayload 注释);
|
||||
* 其余角色不带——归属由后端 `AdminUserService#resolveTargetCompanyId` 落操作者自己的公司,
|
||||
* 想给别的公司建普通账号,得用那个公司自己的管理员登录,不是在这里改请求体。</p>
|
||||
*
|
||||
* <p>expiresAt 只对可带到期时间的角色下发:普通账号的停用走上级级联,
|
||||
* 带了会被后端 400 打回(界面已隐藏该输入项,这里是「表单残留值」的兜底)。</p>
|
||||
*/
|
||||
export function toCreateUserRequest(form: CreateUserForm): CreateUserPayload {
|
||||
const role = normalizeCreateRole(form.role)
|
||||
const payload: CreateUserPayload = {
|
||||
username: (form.username || '').trim(),
|
||||
password: form.password || '',
|
||||
role,
|
||||
columnIds: Array.isArray(form.columnIds) ? form.columnIds.slice() : [],
|
||||
platform: form.platform,
|
||||
}
|
||||
if (payload.role === 'normal' && form.createdBy != null) {
|
||||
payload.createdById = form.createdBy
|
||||
}
|
||||
if (mayCarryOwnExpiry(role) && form.expiresAt && String(form.expiresAt).trim()) {
|
||||
payload.expiresAt = String(form.expiresAt).trim()
|
||||
}
|
||||
|
||||
if (role === 'company_super_admin' && form.companyId != null) {
|
||||
payload.companyId = form.companyId
|
||||
}
|
||||
return payload
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
/** 用户删除确认模型(任务 51):删除确认文案 + 不可删原因,镜像 Java deleteUser 约束。 */
|
||||
import type { AdminUser } from '../../types/admin'
|
||||
|
||||
/** 删除二次确认文案(对齐 admin.js:970 原文:半角引号、无补充句)。 */
|
||||
export function deleteConfirmMessage(user: AdminUser | null | undefined): string {
|
||||
const username = user?.username || ''
|
||||
return `确定删除用户 "${username}" 吗?`
|
||||
}
|
||||
|
||||
/** 返回不可删除原因;可删除时返回 undefined。 */
|
||||
export function deleteBlockReason(
|
||||
user: AdminUser | null | undefined,
|
||||
currentUserId?: number | null,
|
||||
): string | undefined {
|
||||
if (!user) return '用户信息缺失,无法删除'
|
||||
if (currentUserId != null && user.id === currentUserId) return '不能删除当前登录账号'
|
||||
if ((user.role || '').trim().toLowerCase() === 'super_admin') return '不能删除超级管理员'
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** 该用户当前是否允许删除(非缺失/非自己/非超管)。 */
|
||||
export function isDeletableUser(user: AdminUser | null | undefined, currentUserId?: number | null): boolean {
|
||||
return deleteBlockReason(user, currentUserId) === undefined
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
/** 停用/解除停用确认模型:确认文案 + 不可停原因,镜像 Java updateUser 的 disabled 闸(V155)。 */
|
||||
import type { AdminUser } from '../../types/admin'
|
||||
|
||||
/** 停用/解除的二次确认文案。停用要说出代价:对方会被立即强制退出到登录页。 */
|
||||
export function disableConfirmMessage(user: AdminUser | null | undefined, disabled: boolean): string {
|
||||
const username = user?.username || ''
|
||||
return disabled
|
||||
? `停用后 "${username}" 在客户端和后台会被立即强制退出到登录页,确定停用吗?`
|
||||
: `解除停用后 "${username}" 可以重新登录,确定解除吗?`
|
||||
}
|
||||
|
||||
/** 返回不可停用原因;可操作时返回 undefined。角色边界由编辑态(editableBy)管,这里只管身份。 */
|
||||
export function disableBlockReason(
|
||||
user: AdminUser | null | undefined,
|
||||
currentUserId?: number | null,
|
||||
): string | undefined {
|
||||
if (!user) return '用户信息缺失,无法操作'
|
||||
if (currentUserId != null && user.id === currentUserId) return '不能停用自己的账号'
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** 列表「状态」列徽标文案。 */
|
||||
export function disabledBadgeText(user: Pick<AdminUser, 'disabledAt'> | null | undefined): string {
|
||||
return user?.disabledAt ? '已停用' : '正常'
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
/** 编辑用户请求适配(module 13 task 251):表单模型 → PUT /api/admin/user/{uid}。 */
|
||||
import { http } from '@/api/http'
|
||||
import { unwrap } from '@/api/envelope'
|
||||
import {
|
||||
toEditUserUpdateRequest,
|
||||
validateEditUserForm,
|
||||
type EditUserForm,
|
||||
type EditUserFormOptions,
|
||||
} from './user-edit-model'
|
||||
|
||||
/** Java AdminUserController.updateUser 端点前缀。 */
|
||||
export const EDIT_USER_ENDPOINT = '/api/admin/user'
|
||||
|
||||
/**
|
||||
* 提交编辑用户:先校验(不通过抛首条错误),再序列化 PUT;http/后端失败交由调用方提示。
|
||||
* options.includeQuota=false(亚马逊侧)不下发上架上限——校验与序列化同口径。
|
||||
*/
|
||||
export async function submitEditUser(form: EditUserForm, options: EditUserFormOptions = {}): Promise<void> {
|
||||
const { valid, errors } = validateEditUserForm(form, options)
|
||||
if (!valid) {
|
||||
throw new Error(Object.values(errors)[0] || '编辑用户表单校验未通过')
|
||||
}
|
||||
const { data } = await http.put<unknown>(`${EDIT_USER_ENDPOINT}/${form.uid}`, toEditUserUpdateRequest(form, options))
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
/** 编辑用户表单回填模型(任务 47):从用户行回填可编辑表单,镜像 Java AdminUserUpdateRequest。 */
|
||||
import type { AdminUser } from '../../types/admin'
|
||||
import type { PlatformTabId } from '../../config/platform-scope.ts'
|
||||
import { CREATE_PASSWORD_MIN_LEN, mayCarryOwnExpiry } from './user-create-model.ts'
|
||||
|
||||
/** 编辑可选角色:站点/公司超管不可改,未知归 normal;后端只收 admin|normal。 */
|
||||
export type EditUserRole = 'normal' | 'admin'
|
||||
|
||||
export interface EditUserForm {
|
||||
jdPublishQuota: number
|
||||
uid: number
|
||||
/** 仅展示用,后端不支持改用户名。 */
|
||||
username: string
|
||||
/** 空串 = 不修改密码。 */
|
||||
password: string
|
||||
role: EditUserRole
|
||||
/** 授权菜单 id;由授权数据加载后填充。 */
|
||||
columnIds: number[]
|
||||
/** 后端原角色字符串,用于超管禁止编辑判定。 */
|
||||
originalRole: string
|
||||
/** 到期时间(yyyy-MM-dd HH:mm:ss);空串 = 永不过期。null = 后端本来就无到期。 */
|
||||
expiresAt: string
|
||||
/** 所属平台(V206):单选可翻档,未知/缺省归亚马逊(存量默认)。 */
|
||||
platform: PlatformTabId
|
||||
}
|
||||
|
||||
export interface EditUserFormErrors {
|
||||
jdPublishQuota?: string
|
||||
password?: string
|
||||
}
|
||||
|
||||
/** 序列化到 PUT /api/admin/user/{uid} 的请求体(Java AdminUserUpdateRequest,空密码不下发)。 */
|
||||
export interface EditUserUpdateRequest {
|
||||
/** 目标是公司超管时不携带(防止表单把公司超管误降级);站点超管改其密码/到期时间即可。 */
|
||||
role?: EditUserRole
|
||||
jdPublishQuota?: number
|
||||
columnIds: number[]
|
||||
password?: string
|
||||
/** 到期时间:空串=清除(恢复永不过期),有值=改期;总是下发(与后端"传了就更新"对齐)。 */
|
||||
expiresAt: string
|
||||
/** 所属平台(V206):总是下发(弹窗单选恒渲染),翻档即把记录挪到另一平台的列表。 */
|
||||
platform: PlatformTabId
|
||||
}
|
||||
|
||||
/** 行角色 → 可编辑角色:仅 admin 映射 admin,其余(含 unknown)归 normal。 */
|
||||
export function editRoleOf(role: string | null | undefined): EditUserRole {
|
||||
return (role || '').trim().toLowerCase() === 'admin' ? 'admin' : 'normal'
|
||||
}
|
||||
|
||||
/** 该角色是否允许被编辑:站点/公司超级管理员不可经普通编辑入口修改(镜像后端闸门)。 */
|
||||
export function isEditableUser(role: string | null | undefined): boolean {
|
||||
const value = (role || '').trim().toLowerCase()
|
||||
return value !== 'super_admin' && value !== 'company_super_admin'
|
||||
}
|
||||
|
||||
/**
|
||||
* 结合操作者角色判断可编辑性(UsersPage 用):公司超管的目标只有站点超管能编辑
|
||||
* (改密码/到期时间做续费),站点超管目标谁都不能编辑。
|
||||
*/
|
||||
export function editableBy(
|
||||
targetRole: string | null | undefined,
|
||||
operatorRole: string | null | undefined,
|
||||
): boolean {
|
||||
const target = (targetRole || '').trim().toLowerCase()
|
||||
if (target === 'super_admin') return false
|
||||
if (target === 'company_super_admin') return (operatorRole || '').trim().toLowerCase() === 'super_admin'
|
||||
return true
|
||||
}
|
||||
|
||||
/** 列表的 expires_at 是 yyyy-MM-dd HH:mm;日期选择器按 yyyy-MM-dd HH:mm:ss 回填,秒位补 :00。 */
|
||||
export function normalizeExpiryForPicker(raw: string | null | undefined): string {
|
||||
const value = (raw || '').trim()
|
||||
if (!value) return ''
|
||||
return /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(value) ? `${value}:00` : value
|
||||
}
|
||||
|
||||
/** 从用户行回填编辑表单:用户名只读、密码留空、columnIds 待授权加载填充。 */
|
||||
export function fillEditUserForm(user: AdminUser): EditUserForm {
|
||||
const role = typeof user.role === 'string' ? user.role.trim() : ''
|
||||
return {
|
||||
uid: user.id,
|
||||
jdPublishQuota: user.jdPublishQuota ?? 5000,
|
||||
username: user.username || '',
|
||||
password: '',
|
||||
role: editRoleOf(role),
|
||||
columnIds: [],
|
||||
originalRole: role,
|
||||
expiresAt: normalizeExpiryForPicker(user.expiresAt),
|
||||
platform: user.platform === 'jd' ? 'jd' : 'amazon',
|
||||
}
|
||||
}
|
||||
|
||||
/** 编辑表单校验选项:includeQuota=false(亚马逊侧)跳过上架上限校验——该项不下发。 */
|
||||
export interface EditUserFormOptions {
|
||||
/** 是否参与上架上限(jd_publish_quota)的校验与下发;缺省 true(京东侧)。 */
|
||||
includeQuota?: boolean
|
||||
}
|
||||
|
||||
/** 编辑表单校验:密码可留空(不改),非空时须达到最小长度。 */
|
||||
export function validateEditUserForm(
|
||||
form: EditUserForm,
|
||||
options: EditUserFormOptions = {},
|
||||
): { valid: boolean; errors: EditUserFormErrors } {
|
||||
const errors: EditUserFormErrors = {}
|
||||
const password = form.password || ''
|
||||
if (password && password.length < CREATE_PASSWORD_MIN_LEN) {
|
||||
errors.password = `密码至少${CREATE_PASSWORD_MIN_LEN}个字符,留空则不修改`
|
||||
}
|
||||
if (options.includeQuota !== false &&
|
||||
(form.role === 'admin' || form.originalRole === 'company_super_admin') &&
|
||||
(!Number.isInteger(form.jdPublishQuota) || form.jdPublishQuota < 0 || form.jdPublishQuota > 2147483647)) {
|
||||
errors.jdPublishQuota = '请输入 0 至 2147483647 的整数'
|
||||
}
|
||||
return { valid: Object.keys(errors).length === 0, errors }
|
||||
}
|
||||
|
||||
/**
|
||||
* 编辑表单 → 更新请求体:站点超管拒绝、空密码不下发、columnIds 拷贝不共享引用。
|
||||
*
|
||||
* <p>expiresAt 按「改完之后的角色」决定:目标角色不能带自己的到期时间时发空串=清空
|
||||
* (后端 400 闸门只拦「有值」,空串走既有的清除分支)。公司超管目标不带 role,
|
||||
* 它的 roleAfter 就是 company_super_admin,续费那条空串不会被误当成清空。</p>
|
||||
*
|
||||
* <p>options.includeQuota=false(亚马逊侧编辑)不下发 jdPublishQuota——上架上限是京东
|
||||
* 口径,亚马逊侧不显示也不改它(用户口径 2026-11-17);platform 恒下发(单选恒渲染)。</p>
|
||||
*/
|
||||
export function toEditUserUpdateRequest(form: EditUserForm, options: EditUserFormOptions = {}): EditUserUpdateRequest {
|
||||
const originalRole = (form.originalRole || '').trim().toLowerCase()
|
||||
if (originalRole === 'super_admin') {
|
||||
throw new Error('不能修改超级管理员')
|
||||
}
|
||||
// 公司超管目标不带 role:弹窗里的单选是给管理员/普通账号用的,带着它会整树提交把
|
||||
// 公司超管静默降级。站点超管要调角色,请删号重建或走接口。
|
||||
const keepsRole = originalRole !== 'company_super_admin'
|
||||
const nextRole: EditUserRole = form.role === 'admin' ? 'admin' : 'normal'
|
||||
const roleAfter = keepsRole ? nextRole : originalRole
|
||||
const request: EditUserUpdateRequest = {
|
||||
columnIds: Array.isArray(form.columnIds) ? form.columnIds.slice() : [],
|
||||
expiresAt: mayCarryOwnExpiry(roleAfter) ? (form.expiresAt || '').trim() : '',
|
||||
platform: form.platform,
|
||||
}
|
||||
if (keepsRole) {
|
||||
request.role = nextRole
|
||||
}
|
||||
if (options.includeQuota !== false && (roleAfter === 'admin' || roleAfter === 'company_super_admin')) {
|
||||
request.jdPublishQuota = form.jdPublishQuota
|
||||
}
|
||||
const password = form.password || ''
|
||||
if (password) request.password = password
|
||||
return request
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
/** 用户列表「到期时间」单元格渲染(V146):永不过期 / 具体时间 / 已过期。 */
|
||||
|
||||
export interface ExpiryCell {
|
||||
text: string
|
||||
expired: boolean
|
||||
}
|
||||
|
||||
/** 行 expiresAt 是 yyyy-MM-dd HH:mm 或空(后端空串=永不过期);解析失败按永不过期兜底。 */
|
||||
export function formatExpiryCell(row: { expiresAt?: string | null }): ExpiryCell {
|
||||
const raw = (row?.expiresAt || '').trim()
|
||||
if (!raw) {
|
||||
return { text: '永不过期', expired: false }
|
||||
}
|
||||
const parsed = new Date(raw.replace(' ', 'T'))
|
||||
if (Number.isNaN(parsed.getTime())) {
|
||||
return { text: raw, expired: false }
|
||||
}
|
||||
return { text: raw, expired: parsed.getTime() < Date.now() }
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user