diff --git a/backend/app/api/auth.py b/backend/app/api/auth.py index 7c07db2..0f74e24 100644 --- a/backend/app/api/auth.py +++ b/backend/app/api/auth.py @@ -257,15 +257,32 @@ def revoke_my_session(session_id: int, request: Request, user: User = Depends(re # ------------------------------------------------------------------ 账号管理 +#: 状态筛选的三档(页面顶部四张统计卡里的三张就是这三档,见 UI规范 §12) +STATUS_FILTERS = ("active", "disabled", "pending") + + @router.get("/api/users") def list_users(db: Session = Depends(get_db), _: User = Depends(require_admin), - q: str = "", role: str = "") -> dict: + q: str = "", role: str = "", status: str = "") -> dict: + """账号列表。筛选一律在服务端做(与资产库 / 模型管理中心同口径): + `q` 跨字段、`role` 单档、`status`=正常 / 已停用 / 待改初始密码。 + `counts` 恒为全库数,统计卡才不会因为「一点就把自己数字点没」而跳字。""" rows = db.scalars(select(User).order_by(User.id)).all() keyword = q.strip().lower() + if role and role not in Role.ALL: + raise HTTPException(400, "角色只能是 管理员 / 制作 / 观摩") + if status and status not in STATUS_FILTERS: + raise HTTPException(400, "状态只能是 正常 / 已停用 / 待改初始密码") out = [] for row in rows: if role and row.role != role: continue + if status == "active" and not row.is_active: + continue + if status == "disabled" and row.is_active: + continue + if status == "pending" and not (row.must_change_password and row.is_active): + continue if keyword and keyword not in " ".join([row.username, row.display_name, row.email, row.note]).lower(): continue out.append(auth_service.public_user(db, row)) diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py index 70f1ff5..97d564f 100644 --- a/backend/tests/test_auth.py +++ b/backend/tests/test_auth.py @@ -240,6 +240,52 @@ def test_admin_cannot_lock_itself_out(secured): assert secured.get("/api/users", params={"role": "viewer"}).json()["items"][0]["username"] == "admin2" +def test_user_list_filters_are_server_side(secured, member): + """账号列表的三档状态筛选(页面顶部三张统计卡点的就是它们)与 q / role 可叠加。 + + 口径:`items` 跟随筛选,`counts` 恒为全库数——否则统计卡一点就把自己的数字点没了。 + """ + watcher = member("viewer", "watcher") + maker = member("editor", "maker") + secured.cookies.clear() + sign_in(secured, **ADMIN) + + def names(**params): + return [row["username"] for row in secured.get("/api/users", params=params).json()["items"]] + + whole = secured.get("/api/users").json() + assert [row["username"] for row in whole["items"]] == ["admin", "watcher", "maker"] + assert whole["counts"]["total"] == 3 and whole["counts"]["disabled"] == 0 + + # 新建的账号一律先落在「待改初始密码」;播种出来的管理员用的还是默认口令, + # 所以它自己也在这一档里——这一档数的是「还没改过自己密码且还能登录」的账号。 + assert whole["counts"]["pending_password"] == 3 + assert names(status="pending") == ["admin", "watcher", "maker"] + assert names(status="active") == ["admin", "watcher", "maker"] + assert names(status="disabled") == [] + + # 管理员代改密码并勾掉「下次登录改密」之后,该账号才离开 pending 这一档 + secured.post(f"/api/users/{maker}/password", + json={"new_password": "Rotated#2026", "must_change": False, "revoke_sessions": True}) + assert names(status="pending") == ["admin", "watcher"] + + secured.delete(f"/api/users/{watcher}") + assert names(status="disabled") == ["watcher"] + assert names(status="active") == ["admin", "maker"] + assert names(status="pending") == ["admin"] # 停用账号不再算待改口令 + # 停用是「收回登录权」,不是从库里抹掉:全量列表与 counts 都还看得见它 + disabled = secured.get("/api/users", params={"status": "disabled"}).json() + assert disabled["counts"]["total"] == 3 and disabled["counts"]["disabled"] == 1 + # 角色 + 状态 + 关键词三个条件叠加,与页面上「统计卡 + 两条下拉 + 搜索框」一一对应 + assert names(role="viewer", status="disabled") == ["watcher"] + assert names(q="wat", status="disabled") == ["watcher"] + assert names(q="wat", status="active") == [] + + # 非法档位直接 400,不让前端把拼错的参数静默当成「没筛」 + assert secured.get("/api/users", params={"status": "nope"}).status_code == 400 + assert secured.get("/api/users", params={"role": "nope"}).status_code == 400 + + def test_duplicate_username_rejected(secured): sign_in(secured, **ADMIN) res = secured.post("/api/users", json={"username": "admin", "password": "Another#2026"}) diff --git a/docs/UI规范.md b/docs/UI规范.md index 945a009..27351ad 100644 --- a/docs/UI规范.md +++ b/docs/UI规范.md @@ -1066,7 +1066,7 @@ antd 的 `Tag.CheckableTag` 未选中态是**完全透明**的。铺进等宽格 | 平台资产库 | 仅疑似重复 / 仅多版本素材 | `duplicate_only` / 素材墙 `multi_only` | 保留(后者仅 `view==='media'`) | | 平台资产库 | 每页 | `page_size` | **移出筛选栏** → `Pager` | | 项目资产库 | 类型 / 状态 / 排序 | 与平台侧同一套参数 | 保留,同行 | -| 用户管理 | 角色 / 状态 | `GET /api/admin/users` | 保留,同行 | +| 用户管理 | 搜索 / 角色 / 状态 | `GET /api/users` 的 `q` `role` `status` | 保留,同行;四张统计卡是同一批参数的快捷入口(§13.5),`counts` 恒为全库数 | | 仪表盘 | 事件类型 / 级别 | `GET /api/events` | 保留,同行 | ### 12.1 状态类下拉的唯一来源 @@ -1149,7 +1149,7 @@ antd 的 `Tag.CheckableTag` 未选中态是**完全透明**的。铺进等宽格 提示条 / 确认框同一族,一大一小两档几何)。**不传 `icon` 就没有色块,正文满宽**;色块顶对齐标题 (它标的是「这一格是什么」),说明文字缩进正文列,不许钻到色块底下。 栅格一律 `StatGrid`,卡片列数走 `steps`,别在页面写 `grid-cols-*` 定宽;**每页卡数由内容决定** -(概览 8、用户 5、调度与交付 2),不为了凑齐一行删掉真实指标。 +(概览 8、用户 4、调度与交付 2),不为了凑齐一行删掉真实指标。 **② 只读回显:一律 `Info`。** `Info` 的 label 列由 antd 上 `colorFillAlter` 底纹(深色档在 `app.css` 抬到 7% 白,4% 压不出「这一列是标签」),值列 `overflow-wrap:anywhere`。用法三约束: @@ -1290,6 +1290,55 @@ chromeless 页面(不套顶栏 / 侧栏,也不拉需要鉴权的 `/api/meta` --- +### 13.5 管理类模块统一口径:列表 + 抽屉 + 行内动作(2026-11-06 · 用户第 1 条) + +**症状**:用户管理是唯一一个没跟上资产库 / 模型管理中心交互口径的页面——左右两栏常驻详情、 +页面顶部常驻一张新建表单、表格没有操作列、五张统计卡只有数字不能点。 +逐条改掉,并把「管理类模块」的口径写成可核对的六行: + +| 部位 | 过去(用户管理) | 现在(与资产库 / 模型管理中心同一套) | +|---|---|---| +| 详情 | 左列表 + 右「选中详情」面板各占一半,右栏平时只回显几个字段,还要维护一个 `selectedId` | **整行点开抽屉**:``,与母版卡点击是同一个动作语义 | +| 新建 | 页面顶部一张永远摊开的表单,占掉首屏三分之一,自带一套 `formDirty` / `keepForms` / `syncEdit` 脏检查 | 页头一颗 `+ 新建账号` → **与编辑共用同一张抽屉**(`width="min(980px, calc(100vw - 24px))"`,与资产库编辑抽屉同宽)。关掉抽屉就是放弃,于是根本不需要脏检查——**Kit 没有的那层状态不要自己造** | +| 行内动作 | 无操作列,停用 / 改密 / 注销会话散在详情面板的按钮排里 | 操作列四颗**纯图标** `type="text"` 按钮(编辑 / 重置密码 / 注销会话 / 停用⇄启用),逐个 `aria-label`;0 会话时「注销」disabled、停用自己 disabled;整列 `onCell` 里 `stopPropagation`,否则点图标会连带打开压在底下的抽屉 | +| 统计卡 | 五张纯展示卡,其中「活跃会话」既不是筛选入口、数字又被探针登录污染成四位数 | 四张卡**全是筛选入口**(AS-7 · §13.1),点下去等价于填筛选栏;「账号总数」那张回到的是「清空筛选」 | +| 状态语义 | 抽屉里一颗「允许登录」`Check`,与列表上的「停用」是同一件事的两种写法 | 停只在行内,抽屉只管资料;`sub` 那一行放**只读事实**(`#id · 登录名 … · 由谁创建`) | +| 筛选 | 一次拉全量再本地 `filter`,卡上的「共 N 个账号」与表里的行数各说各话 | `GET /api/users` 的 `q` `role` `status` 服务端筛(§12),搜索 320ms 防抖(与资产库同一个值),`counts` 恒为全库数,卡头右端回显「筛选出 X / Y 个账号」 | + +四条硬约束(都是从别的模块抄来的,别在管理页里再发明一遍): + +- **卡上的数字与点进去的行数必须一致**:`counts.admins` 只数**启用中**的管理员,这张卡就必须筛 + `role=admin&status=active`;只筛 `role=admin` 的话点进去比卡上多出一个停用账号。 + 后端 `pending` 同理写成 `must_change_password && is_active`——停用的账号本来就登不进去, + 不该再算「待改初始密码」。 +- **停用与重置密码不许共用一张底部**:§10 那条动作条只允许一颗 `type="primary"`, + 而停用确认是 `type="primary" danger`,同一排放不下两颗 primary。 + 于是停用留在行内(走 `confirmAction`),重置密码独立一张 ``。 +- **自动刷新不许冲掉浮层**:`useAutoRefresh(fn, 30000, reading || !!busy, !!form || !!pwd)`—— + 第 4 个参数 `paused` 必须带上「任一浮层开着」,否则 30 秒一次的轮询会盖掉敲了一半的表单。 +- **`footercheck` 必须跟着加 CASES**:`/users`(新建账号 / `@编辑账号` / `@重置密码`)。 + 行内那种只有图形的图标按钮没有可见文案,触发器写 `@无障碍名` 按 `aria-label` 找。 + **点出来的浮层是新表面,没进闸门就等于没有**(§15.7 那条老规矩)。 + +### 13.6 卡头不许复读页签、角标与分页条(2026-11-06 · 用户第 2 条) + +**症状**:资产库卡头写着「人物母版」+「共 10 个母版」,而它头顶的页签写着同一句 +「人物母版 10」,卡底 `Pager` 又写一遍「共 10 条」,第一张统计卡的 `hint` 再写一遍 +「人物 10 · 场景 6 · 声线 3」——**同一句话在 40px 内出现四遍**。 +模型管理中心是同一形状:左栏已经选中「大模型」,卡头再来一句「大模型」。 + +- **一个层级只说一次**:卡头(`.ant-card-head`)的职责是「这一栏是什么」, + 页签 / 左栏已经说过的就整块删 `title`;数量归页签角标与 `Pager`,卡头 `sub` 不再复读。 +- **删空之后的卡头只留右端 `extra` 是合法形态**(视图切换器、以及「共 N 个账号」这类 + **随筛选变化**的只读回显),不必为了「左边不能空」把标题塞回去。 +- **别顺手删掉统计卡的 `hint`**:重复的是数字,不是解释。第一张卡的 `hint` 换成 + 「点下去清空筛选,回到这一类母版的网格视图」这种**只在这里才有的信息**。 +- 探针侧只有一处要留意:`aligncheck` ② 那条父子尺拿 `.ant-card-head-title` 定位, + 只剩 `extra` 的卡头少一个样本。它量的是渲染结果,不要求每页样本数相同—— + 看的是 `ALIGN_PROBED` 总有没有掉到地板(本轮实测 181 / 底线 40),不是数标题。 + +--- + ## 14. 说明文字与表单增删(G1/G2/G3/G4/G5) 背景:分镜编辑页的老毛病是「每加一个东西就新增一行」——一行只有一个小按钮, @@ -1675,7 +1724,8 @@ NEX_ROUTES="/projects/{id}/review" NEX_THEMES=light \ 未分层赢过分层,于是页面里写 `mb-0` **压不住** kit 的下边距。归零必须写在同一层、按结构命中 (`app.css` 里那两条卡头归零尺)。 -用法 `.venv/bin/python -u scripts/ui/aligncheck.py [theme] [width]`,默认 light / 1440 跑 13 个内容页。 +用法 `NEX_BASE=http://127.0.0.1:5173 .venv/bin/python -u scripts/ui/aligncheck.py [theme] [width]`, +默认 light / 1440 跑 13 个内容页。 **反向验证(第十四轮)**:摘掉 `app.css` 那两条卡头归零尺重跑 → 报 3 处并点名 (④调度 `父·.ant-card-head-title` 偏 6、④调度 `父·.ant-card-extra` 偏 6、⑤质检 `父·.ant-card-extra` 偏 6); 装回 → `通过:全站 0 处同一行不同心 / 只读胶囊继承到标题字重`。 @@ -1703,7 +1753,15 @@ NEX_ROUTES="/projects/{id}/review" NEX_THEMES=light \ 第 ② 条一开始是**漏判**的:探针原先只比对「第一行里含按钮的直接子件」,挪进说明行之后 它被当成「本页没有主操作」放过——跨页尺必须把门牌里**任何**游离的 `.nex-action-group` 都抓出来,否则回归会静默通过(闸门安静返回 0 比误报更危险,同 §15.12 那条)。 -用法 `.venv/bin/python -u scripts/ui/symmetrycheck.py [theme] [width]`,默认 light / 1440。 +用法 `NEX_BASE=… .venv/bin/python -u scripts/ui/symmetrycheck.py [theme] [width]`,默认 light / 1440。 + +**两把尺都认 `NEX_BASE`,且都必须自报样本数(2026-11-06 补)**:它们早先把端口写死成 +`localhost:5173`,而那台端口上跑着**另一个项目**——十三页一个门牌都没量到, +于是 `通过:全站 0 处` 与 `SYM_TOTAL 0` 双双**空跑变绿**,「跨页最大跳动 0」的真相是 +压根没有第二个样本。现在 `aligncheck` 打印 `ALIGN_PROBED`(量到的容器数,底线 40, +`NEX_MIN_PROBED` 可覆盖)、`symmetrycheck` 打印 `SYM_HEADS n/13`(底线 10,`NEX_MIN_HEADS` 可覆盖), +掉到地板一律**退出码 2**(闸门自己坏了),不再冒充通过。与 §15.10 的 `FOOTER_PROBED`、 +§15.12「闸门安静返回 0 比误报更危险」是同一条规矩:**凡是「0 = 通过」的尺都必须报样本数**。 ### 15.9 `.venv/bin/python scripts/ui/feedbackcheck.py` —— 运行时证明反馈不是默认组件(R19) @@ -1714,8 +1772,10 @@ provider 漏渲染、store 被引成第二份实例,都会让 `notify()` 静 明暗两套主题各跑一遍(视口 1440×900),六组断言: 1. **A 原生框禁绝**:`page.on('dialog')` 记下任何一次 alert / confirm / prompt,有就算失败; -2. **B 真实路径的成功反馈**:`/users` 点「保存」(PATCH 同一个值,不改数据)→ `.nex-toast` 出现、 - `.ant-message` 必须一个都不许有、吐司落在视口右下角留白带(离右 / 下缘 ≤40px、中心在右下象限); +2. **B 真实路径的成功反馈**:`/users` 整行点开编辑抽屉 → 抽屉底部「保存账号」(PATCH 同一个值,不改数据) + → `.nex-toast` 出现、`.ant-message` 必须一个都不许有、吐司落在视口右下角留白带(离右 / 下缘 ≤40px、中心在右下象限); + **点完必须把指针挪开**(`pg.mouse.move`):抽屉那颗主按钮就在右下角,正对着吐司的落位带, + 手留在那儿 = 一直 hover 着吐司,C 会读到 `paused`(2026-11-06 探针自己造的假红); 3. **C 悬停暂停**:`.nex-toast-progress` 的 `animation-play-state` 必须 running → hover 后 paused → 移开恢复 running(条停了卡片却消失 = 半成品); 4. **D 队列语义**:同文案推两次只留一颗且标 `×2`;连推 7 句只剩 5 颗;`notifyLoading` 那颗不自动消失且**没有**倒计时条; @@ -1743,7 +1803,8 @@ provider 漏渲染、store 被引成第二份实例,都会让 `notify()` 静 |---|---| | 量什么 | `.ant-drawer-footer` / `.ant-modal-footer` / `.ant-modal-confirm-btns` 里可见的 `button`(`display:none` 的层与嵌套按钮各只算一次) | | 判据 | 同一底部里按钮的垂直中心落在 **2 条以上水平线** = 这一组被劈开;唯一合法的多行 = **整组竖排等宽**(每行一颗、每颗宽 ≥ 底部内宽的 92%)——于是 2+1 / 2+2 点名,430 档三颗满宽竖排放行 | -| CASES | `/assets`(编辑 / 新建人物 / 引入项目;勾一行后再开 打标签 / 批量 / 删除)、`/projects/10/library`(新建人物 / 场景 / 声线 / 打开生成台 / 编辑)、`/models`(添加大模型 / 配置)、`/projects/10/storyboard`(导入脚本 / 关键帧),外加 `BRIEF`=概览页 `button.nex-console` 展开的项目概况抽屉(含删除二次确认态那 4 颗,全站唯一 4 按钮底部) | +| CASES | `/assets`(编辑 / 新建人物 / 引入项目;勾一行后再开 打标签 / 批量 / 删除)、`/users`(新建账号 / `@编辑账号` / `@重置密码`,§13.5 那张抽屉与那张独立弹窗)、`/projects/10/library`(新建人物 / 场景 / 声线 / 打开生成台 / 编辑)、`/models`(添加大模型 / 配置)、`/projects/10/storyboard`(导入脚本 / 关键帧),外加 `BRIEF`=概览页 `button.nex-console` 展开的项目概况抽屉(含删除二次确认态那 4 颗,全站唯一 4 按钮底部) | +| 触发器写法 | 默认按**可见文案**找按钮;行内那种只有图形的图标按钮没有文案,写 `@无障碍名` 走 `main button[aria-label="…"]`(2026-11-06 随 `/users` 补) | | 覆盖口径 | 2 颗(取消+主行动)/ 3 颗(辅助 `mr-auto` + 取消 + 主行动)/ 4 颗(确认态多一颗取消)三种底部形态 | | 死闸门底线 | 报 `FOOTER_PROBED n`;`n < MIN_PROBED`(默认 8,`NEX_MIN_PROBED` 可覆盖)= 触发器或选择器漂了,闸门在**假装通过** → 退出码 2 | | 退出码 | 0 = 干净;1 = 有点名;2 = 一道都没量到(闸门自己坏了) | @@ -1751,6 +1812,7 @@ provider 漏渲染、store 被引成第二份实例,都会让 `notify()` 静 判据在 JS 里算好 `bad` 并带上 `cls`,`main` 与 `gateprobe` 共用同一条尺子—— 反向验证不许拿一份抄本去测。2026-11-03 三档(1440 / 576 / 430)全量: **`FOOTER_PROBED 30 FOOTER_BAD_TOTAL 0`**(改前同一批是 430 档 2 条)。 +2026-11-06 加进 `/users` 三张浮层后同一批全量:**`FOOTER_PROBED 39 FOOTER_BAD_TOTAL 0`**。 单档耗时约 19 分钟(每条 CASE 都要开层、量、`Esc`),别把它塞进秒级反馈回路里。 ### 15.11 `.venv/bin/python scripts/ui/btnclustercheck.py` —— 不认类名量「一组按钮被劈开」(§7 · 用户第 2 条) diff --git a/frontend/public/help/asset-management.png b/frontend/public/help/asset-management.png index c7d86bd..9b8fa2c 100644 Binary files a/frontend/public/help/asset-management.png and b/frontend/public/help/asset-management.png differ diff --git a/frontend/public/help/dashboard.png b/frontend/public/help/dashboard.png index 0113c3c..3504fbc 100644 Binary files a/frontend/public/help/dashboard.png and b/frontend/public/help/dashboard.png differ diff --git a/frontend/public/help/delivery.png b/frontend/public/help/delivery.png index 1de1e63..21027e1 100644 Binary files a/frontend/public/help/delivery.png and b/frontend/public/help/delivery.png differ diff --git a/frontend/public/help/dispatch.png b/frontend/public/help/dispatch.png index 345f8ba..3e21b9d 100644 Binary files a/frontend/public/help/dispatch.png and b/frontend/public/help/dispatch.png differ diff --git a/frontend/public/help/model-center.png b/frontend/public/help/model-center.png index d189d37..f8e2c08 100644 Binary files a/frontend/public/help/model-center.png and b/frontend/public/help/model-center.png differ diff --git a/frontend/public/help/overview.png b/frontend/public/help/overview.png index c59e9ad..7099bea 100644 Binary files a/frontend/public/help/overview.png and b/frontend/public/help/overview.png differ diff --git a/frontend/public/help/review.png b/frontend/public/help/review.png index 3c72ee5..8e0867a 100644 Binary files a/frontend/public/help/review.png and b/frontend/public/help/review.png differ diff --git a/frontend/public/help/scene-assets.png b/frontend/public/help/scene-assets.png index 148cf75..56a129a 100644 Binary files a/frontend/public/help/scene-assets.png and b/frontend/public/help/scene-assets.png differ diff --git a/frontend/public/help/storyboard-inspector.png b/frontend/public/help/storyboard-inspector.png index f92b5ea..a1766d2 100644 Binary files a/frontend/public/help/storyboard-inspector.png and b/frontend/public/help/storyboard-inspector.png differ diff --git a/frontend/public/help/storyboard.png b/frontend/public/help/storyboard.png index 320fe2e..dc4c983 100644 Binary files a/frontend/public/help/storyboard.png and b/frontend/public/help/storyboard.png differ diff --git a/frontend/public/help/timeline.png b/frontend/public/help/timeline.png index 5cb3419..d89e31e 100644 Binary files a/frontend/public/help/timeline.png and b/frontend/public/help/timeline.png differ diff --git a/frontend/public/help/voice-assets.png b/frontend/public/help/voice-assets.png index 2565715..68be94f 100644 Binary files a/frontend/public/help/voice-assets.png and b/frontend/public/help/voice-assets.png differ diff --git a/frontend/src/pages/AssetLibrary.tsx b/frontend/src/pages/AssetLibrary.tsx index a7374e9..f893f0d 100644 --- a/frontend/src/pages/AssetLibrary.tsx +++ b/frontend/src/pages/AssetLibrary.tsx @@ -1014,7 +1014,7 @@ export default function AssetLibrary() { } label="母版资产" value={totals.human + totals.scene + totals.voice} title="查看全部母版:清空筛选并回到网格视图" active={view !== 'media' && !filtersActive} onClick={focusMasters} - hint={`人物 ${totals.human} · 场景 ${totals.scene} · 声线 ${totals.voice}`} /> + hint="点下去清空筛选,回到这一类母版的网格视图" /> } label="已登记素材" value={totals.media} title="切换到跨母版的「全部素材」视角,直接翻找图片与音频" active={view === 'media'} onClick={focusWall} @@ -1044,18 +1044,14 @@ export default function AssetLibrary() { 以前外面套一层什么都不管的
,卡自己又写 p-4(antd 的卡身内边距 于是变成两层),筛选条再自己描一次边——卡里套盒子,盒子里再套盒子。 */} - 共 {wall.total} 个素材,当前第 {wall.page} / {wall.pages} 页 · 素材墙按当前类型过滤:{typeMeta.label}素材 {wall.stats?.by_owner?.[type] || 0} 个 - : filtersActive - ? `筛选出 ${resultCount} 个母版,本页 ${rows.length} 个(第 ${summary.page} / ${summary.pages} 页)` - : `共 ${resultCount} 个母版`} - /* 不给 block:PanelHead 的 right 是 flex-wrap 容器,宽度由内容决定, - block 会把三段等分成 1/3,最长的「全部素材」装不下就被 - .ant-segmented-item-label 的 overflow:hidden 裁掉半个字。 */ - right={} /> + {/* 卡头不再写标题:这一屏看的是「哪一类 / 哪个视角」,上方页签与右端切换器 + 已经各说了一遍,卡头第三次复述就成了三级重复标题(§14 G2)。 + 数量与页码交给卡底的 ——它本来就是干这件事的。 + 不给 block:PanelHead 的 right 是 flex-wrap 容器,宽度由内容决定, + block 会把切换器裁成 1/3 宽,最长的「全部素材」装不下就被 + .ant-segmented-item-label 的 overflow:hidden 切掉半个字。 */} + } /> {/* 筛选栏:坐在卡正文里,不再自己描边(站内有边框的横块只有 Card 一种)。 「每页」不在这里——分页条是 page_size 唯一的家(UI规范 §5)。 */} diff --git a/frontend/src/pages/ModelCenter.tsx b/frontend/src/pages/ModelCenter.tsx index 6b401e2..fbaee7b 100644 --- a/frontend/src/pages/ModelCenter.tsx +++ b/frontend/src/pages/ModelCenter.tsx @@ -582,10 +582,11 @@ export default function ModelCenter() { {/* 同项目总览:卡头右端只放计数,筛选条放正文(见 Dashboard 同处注释) */} {/* 「搜索」以前独占一行且右端全空:一个控件不配一行,收进卡头右端与计数同排(R2) */} + {/* 左栏那一列已经把能力名说了一遍,卡头再写一次就是同级重复标题; + 能力说明挂在计数的原生 title 上(§14 G2:口径不占版面)。 */} {selectedMeta?.label}} right={<> - {currentRows.length} / {countOf(selectedType)} 个配置 + {currentRows.length} / {countOf(selectedType)} 个配置 setKeyword(e.target.value)} /> diff --git a/frontend/src/pages/UserAdmin.tsx b/frontend/src/pages/UserAdmin.tsx index 662c3b8..8980325 100644 --- a/frontend/src/pages/UserAdmin.tsx +++ b/frontend/src/pages/UserAdmin.tsx @@ -1,22 +1,35 @@ /** - * 用户管理(仅管理员):账号列表 / 新建 / 详情编辑 / 重置密码 / 操作流水。 + * 用户管理(仅管理员)。 * - * 账号列表到点自动刷新,页头不放任何刷新控件。但自动刷新不能把管理员 - * 正在敲的表单冲掉:syncEdit() 会用服务端值重写 edit/reset 两个表单, - * 因此只要这几块里有没保存的内容,就暂停轮询,保存完自动恢复。 + * 交互口径与资产库 / 模型管理中心完全一致(UI规范 §13.5):统计卡就是筛选入口、 + * 搜索与筛选在服务端做、整行点开抽屉、"新建"与"编辑"共用同一张抽屉、 + * 停用 / 重置密码 / 注销会话是行内动作。页头只留一颗主操作「新建账号」。 + * + * 自动刷新只在浮层没打开时进行——抽屉里的表单不能被轮询冲掉。 */ import { useCallback, useEffect, useState } from 'react' import * as api from '../api/client' import { fmtAgo, fmtTime } from '../lib/format' import { useAutoRefresh } from '../hooks' import { SecretInput, Select } from '../components/forms' -import { ActionGroup, Actions, Badge, Button, Check, Ctlbar, Empty, ErrorText, Field, FieldBlock, FormRow, Heading, Input, Layout, MUTED, MUTED_MONO, Mono, PageHead, PageStack, Panel, PanelHead, SearchInput, Stack, Stat, StatGrid, Sub, Table, Tag, TextArea } from '../components/ui' +import { Button, Check, Ctlbar, Drawer, Empty, Field, FormGrid, FormRow, Input, LogBox, LogRow, Modal, MONO, MUTED_MONO, Notice, PageHead, PageStack, Panel, PanelHead, Row, SearchInput, Spinner, Stat, StatGrid, Table, Tag, TextArea, Value } from '../components/ui' import { notify, notifyBad } from '../stores/notice' import { confirmAction } from '../stores/confirm' import { roleLabel, useAuthStore } from '../stores/auth' -import { IconAdd, IconCheck, IconClock, IconKey, IconLogout, IconStop, IconTeam, IconUser } from '../components/icons' +import { IconAdd, IconCheck, IconClose, IconEdit, IconKey, IconLogout, IconShield, IconStop, IconUser } from '../components/icons' +const NOWRAP = 'whitespace-nowrap' const FALLBACK_ROLES = ['admin', 'editor', 'viewer'].map((v) => ({ value: v, label: roleLabel(v) })) +const STATUS_OPTIONS = [ + { value: '', label: '全部状态' }, + { value: 'active', label: '正常' }, + { value: 'disabled', label: '已停用' }, + { value: 'pending', label: '待改初始密码' } +] +const BLANK = { username: '', password: '', display_name: '', email: '', role: 'editor', note: '' } + +type Draft = typeof BLANK & { id?: number } +type PwdTicket = { row: any; password: string; must_change: boolean; revoke_sessions: boolean } export default function UserAdmin() { const auth = useAuthStore() @@ -26,303 +39,345 @@ export default function UserAdmin() { const [counts, setCounts] = useState({}) const [error, setError] = useState('') const [busy, setBusy] = useState('') + const [reading, setReading] = useState(false) + const [search, setSearch] = useState('') const [keyword, setKeyword] = useState('') const [roleFilter, setRoleFilter] = useState('') - const [selectedId, setSelectedId] = useState(null) - - const [create, setCreate] = useState({ username: '', password: '', display_name: '', email: '', role: 'editor', note: '' }) - const [edit, setEdit] = useState({ display_name: '', email: '', role: 'editor', is_active: true, note: '' }) - const [reset, setReset] = useState({ password: '', must_change: true, revoke_sessions: true }) + const [statusFilter, setStatusFilter] = useState('') + const [form, setForm] = useState(null) + const [pwd, setPwd] = useState(null) const roleOptions = roles.length ? roles : FALLBACK_ROLES - const selected = users.find((row) => row.id === selectedId) || null - const visible = users.filter((row) => { - if (roleFilter && row.role !== roleFilter) return false - const q = keyword.trim().toLowerCase() - if (!q) return true - return [row.username, row.display_name, row.email, row.note].join(' ').toLowerCase().includes(q) - }) + const filtersActive = !!(keyword || roleFilter || statusFilter) + const editing = !!form?.id - /** 详情表单是否已被服务端数据覆盖过(切行时同步一次,避免每次渲染都重置输入框) */ - const syncEdit = useCallback((row: any) => { - if (!row) return - setEdit({ - display_name: row.display_name || '', email: row.email || '', - role: row.role || 'editor', is_active: !!row.is_active, note: row.note || '' - }) - setReset({ password: '', must_change: true, revoke_sessions: true }) - }, []) - - const load = useCallback(async (silent = true, keepForms = false) => { - if (!silent) setBusy('读取账号') + const load = useCallback(async () => { + setReading(true) setError('') try { const [list, trail] = await Promise.all([ - api.get('/api/users'), + api.get('/api/users', { q: keyword, role: roleFilter, status: statusFilter }), api.get('/api/users/audit', { limit: 60 }) ]) - const items: any[] = list.items || [] - setUsers(items) + setUsers(list.items || []) if (list.roles?.length) setRoles(list.roles) setCounts(list.counts || {}) setAudit(trail.items || []) - setSelectedId((cur) => { - if (items.some((row) => row.id === cur)) return cur - return items[0]?.id ?? null - }) - if (!keepForms) syncEdit(items.find((row) => row.id === selectedId) || items[0]) } catch (exc: any) { setError(exc?.message || String(exc)) } finally { - setBusy('') + setReading(false) } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [selectedId, syncEdit]) + }, [keyword, roleFilter, statusFilter]) - useEffect(() => { void load(false) }, []) + useEffect(() => { void load() }, [load]) + useAutoRefresh(() => void load(), 30000, reading || !!busy, !!form || !!pwd) - const formDirty = !!selected && ( - edit.display_name !== (selected.display_name || '') || edit.email !== (selected.email || '') - || edit.role !== (selected.role || 'editor') || edit.is_active !== !!selected.is_active - || edit.note !== (selected.note || '')) - || !!reset.password - || !!(create.username || create.password || create.display_name || create.email || create.note) + /** 关键词防抖:与资产库同一条 320ms,中文输入法连打半截拼音时不反复查库 */ + useEffect(() => { + const timer = window.setTimeout(() => setKeyword(search), 320) + return () => window.clearTimeout(timer) + }, [search]) - useAutoRefresh(() => void load(true, true), 30000, !!busy, formDirty) - - function pick(row: any) { - setSelectedId(row.id) - syncEdit(row) + const patch = (next: Partial) => setForm((cur) => ({ ...(cur || BLANK), ...next })) + const clearFilters = () => { setSearch(''); setKeyword(''); setRoleFilter(''); setStatusFilter('') } + /** 统计卡切筛选:整张卡代表一组条件,点下去就是"只看这一批",因此先清掉别的条件 */ + const focusWith = (role: string, status: string) => { + setSearch(''); setKeyword(''); setRoleFilter(role); setStatusFilter(status) } + const openCreate = () => setForm({ ...BLANK }) + const openEdit = (row: any) => setForm({ + id: row.id, username: row.username, password: '', + display_name: row.display_name || '', email: row.email || '', + role: row.role || 'editor', note: row.note || '' + }) - async function createUser() { - if (!create.username.trim() || !create.password) { notifyBad('用户名和密码都不能为空'); return } - setBusy('新建账号'); setError('') + async function save() { + if (!form) return + if (!editing && (!form.username.trim() || !form.password)) { notifyBad('用户名和初始密码都不能为空'); return } + setBusy(editing ? '保存账号' : '新建账号') + setError('') try { - const made = await api.post('/api/users', { ...create, username: create.username.trim() }) - const name = made?.username || create.username.trim() - setCreate({ username: '', password: '', display_name: '', email: '', role: create.role, note: '' }) - setSelectedId(made?.id ?? null) - await load(true, true) - notify(`账号已创建:${name}`) + if (editing) { + await api.patch(`/api/users/${form.id}`, { + display_name: form.display_name, email: form.email, role: form.role, note: form.note + }) + notify(`账号「${form.username}」已更新`) + } else { + const made = await api.post('/api/users', { ...form, username: form.username.trim() }) + notify(`账号已创建:${made?.username || form.username.trim()}`) + } + setForm(null) + await load() } catch (exc: any) { setError(exc?.message || String(exc)) } finally { setBusy('') } } - async function saveEdit() { - if (!selected) return - setBusy('保存账号'); setError('') + async function toggleActive(row: any) { + const off = !!row.is_active + if (off) { + const ok = await confirmAction({ + title: `停用「${row.display_name || row.username}」?`, + desc: '停用后该账号无法登录,其全部会话立即注销,历史操作记录仍会保留。', + tone: 'warn', confirmText: '停用', confirmIcon: + }) + if (!ok) return + } + setBusy(off ? '停用账号' : '启用账号') + setError('') try { - await api.patch(`/api/users/${selected.id}`, { ...edit }) - await load(true, true) - notify(`账号「${selected.username}」已更新`) + if (off) await api.del(`/api/users/${row.id}`) + else await api.patch(`/api/users/${row.id}`, { is_active: true }) + await load() + notify(`账号「${row.username}」已${off ? '停用' : '启用'}`) + } catch (exc: any) { setError(exc?.message || String(exc)) } + finally { setBusy('') } + } + + async function kickSessions(row: any) { + const ok = await confirmAction({ + title: `注销「${row.display_name || row.username}」的登录会话?`, + desc: `${row.active_sessions || 0} 台设备需要重新登录,账号本身不受影响。`, + tone: 'warn', confirmText: '注销会话', confirmIcon: + }) + if (!ok) return + setBusy('注销会话') + setError('') + try { + const data = await api.post(`/api/users/${row.id}/sessions/revoke`) + await load() + notify(`已注销「${row.username}」的 ${data?.revoked ?? 0} 个会话`) } catch (exc: any) { setError(exc?.message || String(exc)) } finally { setBusy('') } } async function resetPassword() { - if (!selected || !reset.password) { notifyBad('请先填写新密码'); return } - setBusy('重置密码'); setError('') + if (!pwd) return + if (!pwd.password) { notifyBad('请先填写新密码'); return } + const target = pwd.row + setBusy('重置密码') + setError('') try { - await api.post(`/api/users/${selected.id}/password`, { ...reset }) - setReset((r) => ({ ...r, password: '' })) - await load(true, true) - notify(`已重置「${selected.username}」的密码${reset.revoke_sessions ? ',并注销其全部会话' : ''}`) - } catch (exc: any) { setError(exc?.message || String(exc)) } - finally { setBusy('') } - } - - async function kickSessions() { - if (!selected) return - setBusy('注销会话'); setError('') - try { - const data = await api.post(`/api/users/${selected.id}/sessions/revoke`) - await load(true, true) - notify(`已注销「${selected.username}」的 ${data?.revoked ?? 0} 个会话`) - } catch (exc: any) { setError(exc?.message || String(exc)) } - finally { setBusy('') } - } - - async function disable() { - if (!selected) return - const ok = await confirmAction({ - title: `停用「${selected.display_name || selected.username}」?`, - desc: '停用后该账号无法登录,历史操作记录仍会保留。', - tone: 'warn', confirmText: '停用', confirmIcon: - }) - if (!ok) return - setBusy('停用账号'); setError('') - try { - await api.del(`/api/users/${selected.id}`) - await load(true, true) - notify(`账号「${selected.username}」已停用`) + await api.post(`/api/users/${target.id}/password`, { + new_password: pwd.password, must_change: pwd.must_change, revoke_sessions: pwd.revoke_sessions + }) + setPwd(null) + await load() + notify(`已重置「${target.username}」的密码${pwd.revoke_sessions ? ',并注销其全部会话' : ''}`) } catch (exc: any) { setError(exc?.message || String(exc)) } finally { setBusy('') } } return ( - - {error} + 用户管理} + actions={} + /> + {error} - {/* 统计卡一共 5 项:给 5 列,别让第 5 张孤零零掉到第二行 */} - {/* 症状:档位写成「≤1600 三列」,而 1440 正是最常见的宽度——5 张卡排成 3+2, - 右下角留一个空位,看着像少了一张卡。5 这一档本来就排得下(每张 ~214px, - 标签最长 6 个字),宽屏一列铺满,窄下去才降列。 */} - {/* 五张统计卡:≥1200 就一排放完(列宽换算见 grid.tsx 的 flex 档,不再取整掉行) */} - - } label="账号总数" value={counts.total ?? users.length} /> - } label="管理员" value={counts.admins ?? 0} /> - } label="已停用" value={counts.disabled ?? 0} /> - } label="待改初始密码" value={counts.pending_password ?? 0} /> - } label="活跃会话" value={counts.sessions ?? 0} /> + {/* 四张卡同时是四个筛选入口(与资产库 AS-7 同一口径):数字点下去就到那一批账号, + 不必再去下拉里找对应的档位。数字恒为全库数,点完不会把自己点没。 */} + + } label="账号总数" value={counts.total ?? 0} + title="查看全部账号:清空搜索与筛选" + active={!filtersActive} onClick={clearFilters} + hint={`${counts.online ?? 0} 个账号 15 分钟内登录过`} /> + } label="管理员" value={counts.admins ?? 0} + title="只看启用中的管理员账号" + active={roleFilter === 'admin' && statusFilter === 'active'} + onClick={() => focusWith('admin', 'active')} + hint="可维护账号、模型配置与全部项目" /> + } label="已停用" value={counts.disabled ?? 0} + title="只看已停用的账号" + active={statusFilter === 'disabled'} onClick={() => focusWith('', 'disabled')} + hint="不能登录,历史操作仍记在其名下" /> + } label="待改初始密码" value={counts.pending_password ?? 0} + title="只看还没改过自己密码的账号" + active={statusFilter === 'pending'} onClick={() => focusWith('', 'pending')} + hint="下次登录会先被要求改自己的密码" /> - - - - {visible.length}} /> - - - setKeyword(e.target.value)} /> - - -
row.id === selectedId} - empty={没有匹配的账号。} - columns={[ - { title: '账号', key: 'name', render: (_: any, row: any) => ( - <> - {row.display_name || row.username} -

{row.username}{row.email ? ` · ${row.email}` : ''}

- - ) }, - { title: '角色', key: 'role', width: 96, render: (_: any, row: any) => - {row.role_label || roleLabel(row.role)} }, - { title: '状态', key: 'state', width: 132, render: (_: any, row: any) => ( - <> - {row.is_active ? '正常' : '已停用'} - {row.must_change_password &&

未改初始密码

} - - ) }, - { title: '最近登录', key: 'login', width: 168, render: (_: any, row: any) => ( - <> - {row.last_login_at ? fmtAgo(row.last_login_at) : '从未登录'} -

{row.login_count || 0} 次{row.last_login_ip ? ' · ' + row.last_login_ip : ''}

- - ) }, - { title: '会话', key: 'sessions', width: 72, align: 'right', render: (_: any, row: any) => row.active_sessions || 0 } - ]} - dataSource={visible} - /> - + + + + {filtersActive ? `筛选出 ${users.length} / ${counts.total ?? 0} 个账号` : `共 ${counts.total ?? 0} 个账号`} + + {busy || reading ? {busy || '读取账号'}… : null} + } /> + + + setSearch(e.target.value)} /> + + + + + +
没有匹配的账号,换个关键词或清空筛选。} + columns={[ + { title: '账号', key: 'name', render: (_: any, row: any) => ( + <> + {row.display_name || row.username} +

{row.username}{row.email ? ` · ${row.email}` : ''}

+ + ) }, + { title: '角色', key: 'role', width: 96, render: (_: any, row: any) => + {row.role_label || roleLabel(row.role)} }, + { title: '状态', key: 'state', width: 132, render: (_: any, row: any) => ( + <> + {row.is_active ? '正常' : '已停用'} + {row.must_change_password &&

未改初始密码

} + + ) }, + { title: '最近登录', key: 'login', width: 168, render: (_: any, row: any) => ( + <> + + {row.last_login_at ? fmtAgo(row.last_login_at) : '从未登录'} + +

{row.login_count || 0} 次{row.last_login_ip ? ' · ' + row.last_login_ip : ''}

+ + ) }, + { title: '会话', key: 'sessions', width: 72, align: 'right', className: NOWRAP, + render: (_: any, row: any) => row.active_sessions || 0 }, + /* 动作列不冒泡成"点行看详情",否则重置密码的弹窗底下还压着一张抽屉 */ + { title: '操作', key: 'actions', width: 190, align: 'right', className: NOWRAP, + onCell: () => ({ onClick: (ev: any) => ev.stopPropagation() }), + render: (_: any, row: any) => { + const self = row.id === auth.user?.id + return ( + + - - - - 账号操作流水} /> - {!audit.length - ? 还没有账号操作记录。 - : ( -
- {audit.map((row) => ( -
- {fmtTime(row.created_at)} - {row.actor || 'system'} - {row.message} -
- ))} -
- )} -
- - - - {selected ? ( - - #{selected.id}} /> - - - setEdit((f) => ({ ...f, display_name: e.target.value }))} /> - - - setEdit((f) => ({ ...f, email: e.target.value }))} /> - - -