Commit c826c7f7 by 胡悦

feat: 搭建全局业务组件库并完成agent-admin UI依赖迁移至TDesign

创建根目录`packages/business-components`全局业务组件包,内置StatePlaceholder、MediaWall、BusinessTable、SearchFilter、登录页与后台框架等复用业务组件,同时新增classNames工具函数
配置agent-admin/web的Vite别名、TS路径与Tailwind扫描范围,支持直接导入全局业务组件
替换agent-admin内本地`packages/ui`组件依赖为直接使用tdesign-react与全局业务组件,将页面内原生textarea替换为tdesign-react的Textarea组件
新增依赖扫描脚本与校验测试,确保业务页面不再依赖本地UI包
完善OpenSpec规范文档与归档变更,统一后台列表页、登录页、后台框架的布局与UI交互规则,修复表格重复总数展示问题
修复相关测试断言,同步更新组件Demo与业务页面的UI实现
1 parent 4f58fe8a
Showing 166 changed files with 13042 additions and 1665 deletions
...@@ -39,11 +39,16 @@ ...@@ -39,11 +39,16 @@
- 已通过 `openspec status --change "official-site-job-tab-ai-intro" --json` 确认 proposal、design、specs、tasks 均完成,并通过 `openspec validate "official-site-job-tab-ai-intro" --strict`。 - 已通过 `openspec status --change "official-site-job-tab-ai-intro" --json` 确认 proposal、design、specs、tasks 均完成,并通过 `openspec validate "official-site-job-tab-ai-intro" --strict`。
- 已为 `workspace/agent-admin/web` 新建 OpenSpec change `official-site-agent-display-config`,覆盖官网配置下 `/official-site/job-tabs/:tabId/agents` 的 Agent 展示配置页,不修改 `official-site-job-tab-ai-intro` artifacts,且本轮未写业务代码。 - 已为 `workspace/agent-admin/web` 新建 OpenSpec change `official-site-agent-display-config`,覆盖官网配置下 `/official-site/job-tabs/:tabId/agents` 的 Agent 展示配置页,不修改 `official-site-job-tab-ai-intro` artifacts,且本轮未写业务代码。
- 已通过 `openspec status --change "official-site-agent-display-config" --json` 确认 proposal、design、specs、tasks 均完成,并通过 `openspec validate "official-site-agent-display-config" --strict`。 - 已通过 `openspec status --change "official-site-agent-display-config" --json` 确认 proposal、design、specs、tasks 均完成,并通过 `openspec validate "official-site-agent-display-config" --strict`。
- 2026-05-30:已执行 `standardize-admin-shell-layout` 并补充全框架前端规则:独立新增/编辑页页头左侧保留 `返回`、右侧仅保留 `保存`、不展示右侧 `取消`,页面滚动时返回/保存操作区保持可见。该规则已写入全局 `web-desktop-ui-standard`、`component-guidelines.md` 和 `frontend-conventions.md`;`agent-admin` 的 Agent、岗位标签、渠道活码、官网岗位展示新增/编辑页已按规则调整。
## 当前重点 ## 当前重点
在编写业务代码前,持续把新的业务页行为先落到 OpenSpec。当前 `official-site-agent-display-config` 已完成 OpenSpec 锁定,等待用户确认 artifacts;不应在确认前进入实现。 在编写业务代码前,持续把新的业务页行为先落到 OpenSpec。当前 `official-site-agent-display-config` 已完成 OpenSpec 锁定,等待用户确认 artifacts;不应在确认前进入实现。
2026-06-03:`business-form-component` 已完成仓库级基线与目录结构占位,OpenSpec tasks 1.1-1.3 已勾选;本轮不推进测试或实现,后续只在 `packages/business-components/src/business-form/` 继续落地。
2026-06-03:执行 `fix-business-table-duplicate-total`。分页场景改为只使用 TDesign `Pagination` 默认 `totalContent`,`BusinessTable` 不再在分页外额外渲染 `totalLabel`;筛选无结果态精简为只显示图标与标题,不显示说明文案和状态区操作按钮;列表失败态标题统一为“请求失败”,不显示下方蓝色操作按钮。已更新相关页面测试断言,保留 `SkillListPage` 无分页场景的 `totalLabel`。
2026-05-24:用户通过 `@fixbug` 反馈渠道活码列表缺少 `启用`/`停用`、岗位展示配置列表缺少 `上架`/`下架`,并明确需要“通过当前行的状态进行判断”。已确认根因属于 `real-api-integration` 真实接口接入后的列表状态操作派生问题:页面现有实现依赖 mock `operations` 字段,真实接口缺少该字段时按钮会消失。已更新 `workspace/agent-admin/web/openspec/changes/real-api-integration/` 的 proposal、design、spec 和 tasks,要求渠道活码按 `status` 派生启停按钮、岗位展示配置按 `display_status` 派生上下架按钮,并新增 TDD 任务;已通过 `openspec validate "real-api-integration" --strict`。等待用户确认 artifacts 后再改业务代码。 2026-05-24:用户通过 `@fixbug` 反馈渠道活码列表缺少 `启用`/`停用`、岗位展示配置列表缺少 `上架`/`下架`,并明确需要“通过当前行的状态进行判断”。已确认根因属于 `real-api-integration` 真实接口接入后的列表状态操作派生问题:页面现有实现依赖 mock `operations` 字段,真实接口缺少该字段时按钮会消失。已更新 `workspace/agent-admin/web/openspec/changes/real-api-integration/` 的 proposal、design、spec 和 tasks,要求渠道活码按 `status` 派生启停按钮、岗位展示配置按 `display_status` 派生上下架按钮,并新增 TDD 任务;已通过 `openspec validate "real-api-integration" --strict`。等待用户确认 artifacts 后再改业务代码。
方法论图片上传的浏览器证据已显示 `file` 是含文件名和媒体类型的真实 multipart part,失败响应为 `404 Not Found`,不再支持“file 为空”根因。用户已确认最终端点为 `/api/v1/official-site/upload`;`fix-official-site-upload-multipart-file` 当前锁定为 Web-only 路径修正:将现有错误请求 `/api/v1/official-site-upload/upload` 对齐至已确认端点,待 artifacts 确认后以 TDD 实施,不修改后端服务。 方法论图片上传的浏览器证据已显示 `file` 是含文件名和媒体类型的真实 multipart part,失败响应为 `404 Not Found`,不再支持“file 为空”根因。用户已确认最终端点为 `/api/v1/official-site/upload`;`fix-official-site-upload-multipart-file` 当前锁定为 Web-only 路径修正:将现有错误请求 `/api/v1/official-site-upload/upload` 对齐至已确认端点,待 artifacts 确认后以 TDD 实施,不修改后端服务。
...@@ -68,6 +73,21 @@ ...@@ -68,6 +73,21 @@
## 会话记录 ## 会话记录
- 2026-06-05:继续 `business-form-component` 的 Demo 覆盖,按用户确认在 `BusinessForm` 示例中新增多选 Select 字段 `scenarios`(展示名“适用场景”),使用 `type: 'select'`、`multiple: true`,初始值为 `['approval', 'archive']`,用于在 `/components` 中对照单选 Select 验收 `select.multiple` 配置与数组值展示。同步更新 OpenSpec demo 覆盖范围和 task 7.14;Demo 测试新增多选字段断言,并将该测试的上传交互断言收窄为已有上传态展示,避免 JSDOM 中 TDesign Upload 隐藏 input 不稳定触发干扰。已通过 `npm run typecheck`、`npm test -- src/business-components/BusinessForm.test.tsx src/routes/components/ComponentsDemoPage.test.tsx`、`openspec validate business-form-component --strict` 和 `npm run build`;OpenSpec telemetry 仍有受限网络 PostHog flush 报错但退出码为 0。
- 2026-06-05:继续 `business-form-component` 的 TDesign Upload 收敛,按 TDD 增加上传字段 `maxCount` / `multiple` 配置。默认仍为单文件;配置 `maxCount > 1` 且 `multiple: true` 时,媒体上传支持多张图片/GIF/视频,值以 `BusinessFormUploadedFileValue[]` 写回;单文件已有值重新选择仍保持替换语义。图片/GIF 继续优先使用 TDesign `Upload theme="image"` 默认卡片,含视频列表仅做最小 `fileListDisplay` 适配以展示视频缩略图;文件名仍按现有 110px 卡片下方单行省略实现。Demo 的展示素材已配置为最多 3 个。已通过 `npm run typecheck`、`npm test -- src/business-components/BusinessForm.test.tsx src/routes/components/ComponentsDemoPage.test.tsx`、`npm run build`、`openspec validate business-form-component --strict`;未做浏览器验收,按用户要求由用户自行验收。
- 2026-06-03:继续 `fix-business-table-duplicate-total`,用户确认后台列表首次加载使用骨架屏、后续分页/搜索/筛选/排序/刷新使用表格区域 loading。已把该规则写入全局 `architecture-spec/openspec/specs/web-desktop-ui-standard/spec.md` 与 `architecture-spec/docs/architecture/frontend-conventions.md`;`BusinessTable` 默认 loadingProps 调整为轻量小尺寸指示、浅色“加载中”文案和半透明蒙层,并允许调用方覆盖。已补充 `business-table.test.tsx` loading 回归,验证 loading 时保留表头且不展示空态;通过 `rtk npm test -- business-table.test.tsx`、`rtk npm run typecheck`、`rtk openspec validate fix-business-table-duplicate-total --strict` 和全局 `rtk openspec validate --specs --strict`。
- 2026-06-03:继续 `fix-business-table-duplicate-total` 的失败态收尾。用户指出列表失败态下方出现无文案蓝色按钮,定位为页面仍传 `errorState.onRetry`,而 `BusinessTable.createActionButton` 只判断回调、不判断按钮文案。已补充 OpenSpec 场景“不渲染无文案的状态区按钮”,更新 `business-table.test.tsx` 断言失败态不存在任何按钮,并修正 `createActionButton` 在没有 `label` 时返回 `undefined`;保留权限态“申请权限”按钮。已通过 `rtk npm test -- business-table.test.tsx`、`rtk npm run typecheck`、`rtk openspec validate fix-business-table-duplicate-total --strict`。
- 2026-06-02:按用户要求执行 `extract-business-table-component` 的第 5 点微调。`BusinessTable` 的空态容器改为更高的 `min-height` 和更大的垂直留白,让普通空态、筛选空态和加载失败态更居中;筛选空态“清空筛选”和加载失败态“重试”都改为 TDesign `theme="primary"` 实色按钮。补充并调整 `workspace/agent-admin/web/src/business-components/business-table.test.tsx` 断言按钮样式,已通过 `npm test -- src/business-components/business-table.test.tsx` 和 `npm run typecheck`,并同步勾选 OpenSpec tasks 的 5.1-5.4。
- 2026-06-01:继续 `extract-business-table-component` 的 1.4、1.5,并顺手补齐 1.6、1.7 契约和实现。新增 `packages/business-components/src/business-table/BusinessTable.tsx`、`BusinessTable.module.css` 与全局导出,统一用 TDesign `Table`、`Empty`、`Button`、`Pagination` 封装业务表格,支持普通空态、筛选空态、加载失败态、primary 文字按钮、`hover`/`rowClassName`/`onRowClick` 等透传属性,以及分页和 `totalLabel`。补充 `workspace/agent-admin/web/src/business-components/business-table.test.tsx`,当前 `npm test -- src/business-components/business-table.test.tsx`、`npm run typecheck`、`npm run build`、`openspec validate "extract-business-table-component" --strict` 均已通过;已同步勾选 OpenSpec tasks 的 1.4-1.7、2.1-2.7 和 4.3-4.5。
- 2026-05-30:按用户确认的“只改页面,不动 `packages/ui/Textarea`”范围完成官网岗位 Tab 编辑页岗位说明字段替换:`OfficialSiteJobTabEditorPage` 直接使用 `tdesign-react` `Textarea`,保留原字段状态、校验、提示和保存逻辑;新增页面测试断言 TDesign Textarea 外层类。已通过聚焦测试、`npm run typecheck`、`npm run build`、`openspec validate migrate-textarea-to-tdesign --strict`,并用 Playwright 验证 `/official-site/job-tabs/new` 中岗位说明可输入且存在 TDesign wrapper。完整页面测试文件仍有既有失败断言,例如测试仍查找旧文案“岗位标签”,本轮未修复。
- 2026-05-30:按用户追加要求将组件库 Demo 页纳入同一 Textarea 页面级迁移范围:`ComponentsDemoPage` 的“基础交互/备注”示例改为直接使用 `tdesign-react` `Textarea`,继续不修改 `packages/ui/Textarea`;补充 Demo 页测试断言示例存在 TDesign wrapper。已通过 Demo 聚焦测试、Demo 全量测试、`npm run typecheck`、`npm run build`、`openspec validate migrate-textarea-to-tdesign --strict`,并用 Playwright 验证 `/components` 中备注输入可编辑且存在 TDesign wrapper。
- 2026-05-31:按用户确认的边界为后台 UI 依赖整体迁移完成文档锁定:本轮目标为 `workspace/agent-admin/web/src` 对本地 `packages/ui` 零运行时依赖,但暂不删除 `workspace/agent-admin/web/packages/ui` 目录,也不处理 `single-page`。已新增设计稿、实施计划和 OpenSpec change `migrate-admin-ui-to-global-tdesign`,锁定基础控件直连 `tdesign-react` / `tdesign-icons-react`、`SearchFilter` / `StatePlaceholder` / `MediaWall` 提升到 `@gl/business-components`、分批 TDD 和最终静态扫描门禁。已通过 `openspec status --change "migrate-admin-ui-to-global-tdesign" --json` 确认 artifacts 全部完成,并通过 `openspec validate "migrate-admin-ui-to-global-tdesign" --strict`。按用户要求,本轮未修改业务代码。
- 2026-05-31:用户确认表单组件采用“本轮保持页面级 TDesign 组合,迁移后再独立试点轻量配置化组件”的方案。已更新 `migrate-admin-ui-to-global-tdesign` 文档:本轮编辑页直接使用 TDesign `Form`、`FormItem` 和基础控件,不新增 `BusinessForm` / `FormRenderer`,不把上传、媒体墙、动态数组、多层级联动、复杂业务选择器或步骤表单改写为配置协议。后续如试点轻量表单组件,必须保留 `children` 或 `render` 逃生口,并优先选择两个结构重复的简单编辑页验证收益。本轮仍未修改业务代码。
- 2026-05-31:按用户限定范围完成 `migrate-admin-ui-to-global-tdesign` 的第 1、2 组任务,未推进页面迁移。已记录 `web/src` 对本地 `packages/ui` 的运行时 import 基线:18 个文件、19 条 import;新增基于 TypeScript AST 的 `scan:local-ui-runtime-deps` 报告命令和 `check:local-ui-runtime-deps` 强制门禁。已将 `SearchFilter`、`StatePlaceholder`、`MediaWall` 提升到 `@gl/business-components`,组件内部只依赖 React、TDesign 和 TDesign Icons,并补充全局入口导出与聚焦测试。已通过相关回归测试(43 passed)、`npm run typecheck`、`npm run build`、`openspec validate "migrate-admin-ui-to-global-tdesign" --strict`;全局业务组件源码反向扫描确认不含本地 `packages/ui` 引用。由于第 3 组之后的页面迁移尚未执行,`npm run check:local-ui-runtime-deps` 当前按预期拦截上述 19 条存量 import。
- 2026-05-31:按用户限定范围完成 `migrate-admin-ui-to-global-tdesign` 第 3 组任务,未推进列表页、编辑页、官网配置或 Demo。`AdminShell` 退出确认改为直接使用 TDesign `Dialog`;`useMessage` 改为直接调用 TDesign `MessagePlugin`,并加载与当前根入口一致的 React 19 `lib` 适配器;Agent、渠道活码和 Skill 详情抽屉改为直接使用 TDesign `Drawer`、`Button`、`Tag` 及全局 `StatePlaceholder`。新增第 3 组局部依赖守卫并调整相关测试,已通过关联回归测试(65 passed)、`npm run typecheck`、`npm run build`、`openspec validate "migrate-admin-ui-to-global-tdesign" --strict`,并用 Playwright 验证 `/agents` 退出弹窗打开与取消交互。`web/src` 对本地 `packages/ui` 的运行时 import 已由 19 条降至 14 条,剩余 13 个文件留待后续任务迁移。
- 2026-05-30:继续完成 `standardize-admin-shell-layout` 收尾。将 `BusinessAdminShell` 改为固定视口高度并让 `main` 成为实际滚动容器,解决页面内 sticky 页头在长表单滚到底部时被父容器顶出视口的问题;重新验证四类独立新增页,Playwright 结果显示滚动前后页头 `Y=80`、`取消` 数量为 0、`返回`/`保存` 可见。已通过相关页面与框架测试(80 passed, 2 skipped)、官网岗位展示页头定向测试(2 passed, 28 skipped)、`npm run typecheck`、`npm run build`、`openspec validate standardize-admin-shell-layout --strict` 和全局 `openspec validate --specs --strict`;OpenSpec telemetry 因受限网络无法 flush,不影响校验结果。
- 2026-05-30:按 `global-search-filter-component` 已确认方案完成全局 `SearchFilter` 迁移第一阶段:调整默认 placeholder(`input` 为 `搜索${label}`、`numberInput` 为 `请输入数字`)、将 Agent 管理、Skill 目录、渠道活码管理、岗位标签管理、官网岗位展示配置列表页搜索区迁移到共享组件,并把渠道活码/官网岗位展示状态筛选改为草稿后点击搜索提交。相关组件与页面测试 96 个用例通过,`npm run typecheck` 与 `npm run build` 通过;按用户要求未做浏览器验证。`openspec validate "global-search-filter-component" --strict` 通过,结束时仅 PostHog telemetry flush 因受限网络报错,不影响校验结果。
- 2026-05-29:按全局规范诉求将 `content` 列表页固化为所有前端项目后台列表页参考模式;新增并归档全局 OpenSpec change `standardize-content-list-page-actions`,把页面标题区、筛选查询区、表格工具栏、导出、批量操作、表格和分页的分层规则应用到 `web-desktop-ui-standard`;同步更新 `component-guidelines.md` 与 `frontend-conventions.md`。本轮仅改文档和 OpenSpec,未改业务代码,`openspec validate --specs --strict` 已通过。
- 2026-05-22:按 `$superpowers-openspec-execution-workflow` 为 `official-site-job-tab-ai-intro` 完成 OpenSpec-only 锁定;本轮未写业务代码。 - 2026-05-22:按 `$superpowers-openspec-execution-workflow` 为 `official-site-job-tab-ai-intro` 完成 OpenSpec-only 锁定;本轮未写业务代码。
- 2026-05-22:按 `$superpowers-openspec-execution-workflow` 为 `official-site-agent-display-config` 完成 OpenSpec-only 锁定;本轮未写业务代码。 - 2026-05-22:按 `$superpowers-openspec-execution-workflow` 为 `official-site-agent-display-config` 完成 OpenSpec-only 锁定;本轮未写业务代码。
- 2026-05-23:按 `@fixbug` 更新 `web/openspec/changes/real-api-integration`,明确 Agent 编辑页的管家判断必须从列表项 `is_steward` 按 `agent_id` 获取,详情与 `code` 不作为身份来源;并依据官网截图锁定字段矩阵(名称/岗位/专用托管员工/状态只读固定、描述必填可编辑、Skill 可选)。随后已按 TDD 完成前端修复:编辑页先用详情名查询列表并按 `agent_id` 读取 `is_steward`,管家 Agent 以只读输入展示固定岗位/托管员工,保存时只提交描述与 Skill;列表无匹配项则阻断编辑。相关回归测试已通过,`openspec validate "real-api-integration" --strict` 通过;`npm run typecheck` / `npm run build` 仍被仓库既有的 position-tag 与 channel-code TypeScript 错误阻断,真实浏览器校验待补。 - 2026-05-23:按 `@fixbug` 更新 `web/openspec/changes/real-api-integration`,明确 Agent 编辑页的管家判断必须从列表项 `is_steward` 按 `agent_id` 获取,详情与 `code` 不作为身份来源;并依据官网截图锁定字段矩阵(名称/岗位/专用托管员工/状态只读固定、描述必填可编辑、Skill 可选)。随后已按 TDD 完成前端修复:编辑页先用详情名查询列表并按 `agent_id` 读取 `is_steward`,管家 Agent 以只读输入展示固定岗位/托管员工,保存时只提交描述与 Skill;列表无匹配项则阻断编辑。相关回归测试已通过,`openspec validate "real-api-integration" --strict` 通过;`npm run typecheck` / `npm run build` 仍被仓库既有的 position-tag 与 channel-code TypeScript 错误阻断,真实浏览器校验待补。
...@@ -80,3 +100,12 @@ ...@@ -80,3 +100,12 @@
- 2026-05-24:按 `@fixbug fix-official-site-agent-config-detail` 更新既有 change,锁定详情接口上下文字段映射:`qrcode_name` -> 关联渠道活码,`position_code` -> 渠道编码,`qrcode_employee_name` -> 承接员工;本轮未写业务代码,等待用户确认后进入 TDD 实现。 - 2026-05-24:按 `@fixbug fix-official-site-agent-config-detail` 更新既有 change,锁定详情接口上下文字段映射:`qrcode_name` -> 关联渠道活码,`position_code` -> 渠道编码,`qrcode_employee_name` -> 承接员工;本轮未写业务代码,等待用户确认后进入 TDD 实现。
- 2026-05-24:新建并校验 `web/openspec/changes/fix-position-tag-delete-references`,锁定岗位标签删除引用检查新契约和多类引用全部展示规则;本轮未写业务代码,等待用户确认后进入 TDD 实现。 - 2026-05-24:新建并校验 `web/openspec/changes/fix-position-tag-delete-references`,锁定岗位标签删除引用检查新契约和多类引用全部展示规则;本轮未写业务代码,等待用户确认后进入 TDD 实现。
- 2026-05-24:补充 `web/openspec/changes/fix-position-tag-delete-references`,锁定岗位标签删除二次弹窗必须展示具体受影响 Agent 名称;本轮未写业务代码,等待用户确认后进入 TDD 实现。 - 2026-05-24:补充 `web/openspec/changes/fix-position-tag-delete-references`,锁定岗位标签删除二次弹窗必须展示具体受影响 Agent 名称;本轮未写业务代码,等待用户确认后进入 TDD 实现。
- 2026-05-31:按用户限定范围完成 `migrate-admin-ui-to-global-tdesign` 第 4 组列表页迁移,未推进编辑页、官网配置、Demo 或收尾任务。Agent、岗位标签、渠道活码、官网岗位展示配置、Skill 五个列表页已直接使用 `tdesign-react` 的 `Table`、`Pagination`、`Dialog`、`Tag`、`Button`,并使用全局 `SearchFilter`、`StatePlaceholder`;补充列表页局部依赖守卫,并为全局 `SearchFilter` 的 Select 补齐可访问标签。`web/src` 对本地 `packages/ui` 的运行时 import 已由 14 条降至 9 条。已通过列表页相关回归测试(102 passed, 6 skipped)、`npm run typecheck`、`npm run build`、`openspec validate "migrate-admin-ui-to-global-tdesign" --strict`,并用 Playwright 验证五个列表路由的标题、搜索区、表格、分页/计数和 Agent 岗位筛选展开交互。
- 2026-05-31:按用户限定范围完成 `migrate-admin-ui-to-global-tdesign` 第 5 组编辑页与官网配置迁移,未推进 Demo 或收尾任务。Agent、岗位标签、渠道活码编辑页,官网方法论配置页,官网 Agent 展示列表与编辑弹窗,官网岗位展示新增编辑页已直接组合 TDesign 表单控件,并复用全局 `SearchFilter`、`MediaWall`、`StatePlaceholder`。为解决 TDesign `FormItem` 在未绑定 `name` 时克隆直接子控件并覆盖页面受控值的问题,新增只包裹 `Fragment` 的薄 `FormItem` 兼容层,未引入配置化表单渲染器或表单配置协议;官网岗位展示直达编辑页改为使用既有详情接口。已通过第 5 组聚焦回归测试(179 passed)、局部依赖守卫(7 passed)、`npm run typecheck`、`npm run build`、`openspec validate "migrate-admin-ui-to-global-tdesign" --strict`,并用 Playwright 验证三个新增编辑页输入回写、方法论配置回填、岗位展示新增页以及模拟数据下的官网 Agent 展示编辑弹窗。完整前端测试结果为 `653 passed / 19 failed`;剩余失败来自旧导航壳层断言、既有抽屉关闭断言和第 6 组尚未迁移的本地 UI Select 测试,不在本轮范围内。`web/src` 对本地 `packages/ui` 的剩余运行时 import 已收敛到 `ComponentsDemoPage.tsx` 的 2 条,留待第 6 组。
- 2026-05-31:按用户限定范围完成 `migrate-admin-ui-to-global-tdesign` 第 6 组组件 Demo 迁移,未推进第 7 组收尾任务。`/components` 的基础组件示例已直接使用 `tdesign-react` 与 `tdesign-icons-react`,业务组合示例只从 `@gl/business-components` 引入 `SearchFilter`、`StatePlaceholder`、`MediaWall`;测试移除旧本地 UI CSS Module 和实现细节断言,改为验证展示、搜索展开/搜索/重置、Checkbox、Switch、反馈提示、Dialog、表单校验和上传状态。新增第 6 组局部依赖守卫后,`web/src` 对本地 `packages/ui` 的运行时 import 已降为 0 条。已通过 Demo 聚焦回归测试(10 passed)、`npm run check:local-ui-runtime-deps`、`npm run typecheck`、`npm run build`、`openspec validate "migrate-admin-ui-to-global-tdesign" --strict`,并用 Playwright 验证 `/components` 九个分组、备注 Textarea 回填、搜索区展开、Switch 关闭和三类反馈提示。
- 2026-06-01:按用户限定范围仅完成 `migrate-admin-ui-to-global-tdesign` 第 7 组中的 7.1、7.2,未推进 7.3-7.7。重新运行 `npm run check:local-ui-runtime-deps`,确认 `workspace/agent-admin/web/src` 对本地 `packages/ui` 的运行时 import 为 0 条;用 `rg` 复核时仅命中迁移守卫测试中的断言文本。确认 `workspace/agent-admin/web/packages/ui` 目录仍保留,当前包含 `README.md` 和 `src/index.ts` 等占位内容;已只勾选 tasks 中的 7.1、7.2。
- 2026-06-01:按用户限定范围仅完成 `migrate-admin-ui-to-global-tdesign` 的 7.3,未推进 7.4-7.7。先修正迁移后陈旧测试断言:TDesign Menu 激活态改查 `t-is-active`,官网/渠道路由测试补齐异步 API mock,渠道活码抽屉关闭改为等待销毁,组件 Demo 标题和遗留本地 UI 选择/日期测试对齐当前 DOM 与日期。已通过失败文件集合回归(7 files / 75 passed)、相关测试 `npm test -- src/migrations src/business-components src/components src/hooks src/layouts src/routes/agents src/routes/agent-tags src/routes/channel-codes src/routes/official-site src/routes/official-site-agent-display-config src/routes/official-site-job-tabs src/routes/skills src/routes/components`(36 files / 413 passed / 9 skipped)以及完整前端测试 `npm test`(55 files / 671 passed / 9 skipped);已只勾选 tasks 中的 7.3。
- 2026-06-01:按用户限定范围仅完成 `migrate-admin-ui-to-global-tdesign` 的 7.4、7.5,未推进 7.6、7.7。已通过 `npm run typecheck`;已通过 `npm run build`(Vite 构建成功,保留常规 chunk size warning);已只勾选 tasks 中的 7.4、7.5。
- 2026-06-01:按用户限定范围仅完成 `migrate-admin-ui-to-global-tdesign` 的 7.6,未推进 7.7。已通过 `openspec validate "migrate-admin-ui-to-global-tdesign" --strict`;命令退出码为 0,末尾仅出现 PostHog telemetry flush 网络超时提示,不影响 OpenSpec 校验结果;已只勾选 tasks 中的 7.6。
- 2026-06-01:按用户限定范围完成 `migrate-admin-ui-to-global-tdesign` 的 7.7。用 Playwright 浏览器验证主要列表页 `/agents`、`/agent-tags`、`/channel-codes`、`/skills`、`/official-site/job-tabs`,编辑页 `/agents/new`、`/agent-tags/new`、`/channel-codes/new`、`/official-site/job-tabs/new`、`/official-site/methodology`,官网 Agent 展示配置弹窗 `/official-site/job-tabs/301/agents`,以及 `/components` 的布局与关键交互。验证中发现并修复 TDesign `DateRangePicker` 空 range 值 console error:全局 `SearchFilter` 对空 range 传 `[]`,组件 Demo 的 `DateRangePicker` 改为受控空数组;已通过相关测试、`npm run typecheck`、`npm run build` 和完整浏览器复验,已只勾选 tasks 中的 7.7。
- 2026-06-01:继续 `extract-business-table-component` 的 3.1,仅迁移 `AgentListPage` 到 `BusinessTable`。页面现在用业务表格承接表格、筛选空态、加载失败态和分页,保留原有搜索和操作逻辑;同步把该页测试改成匹配新组件输出,去掉重复总数展示并按实际 DOM 断言失败态标题与重试按钮。已通过 `npm test -- src/routes/agents/AgentListPage.test.tsx` 和 `npm run typecheck`,已只勾选 tasks 中的 3.1。
# 组件规范 # 组件规范
## 组件基线 ## 组件基线与共享边界
公司设计规范中包含以下可复用基础组件: 工作区所有 React 前端项目 SHALL 以 `tdesign-react` 作为基础组件来源,并通过 `@gl/business-components` 复用业务组件和页面模式。
基础组件直接使用 TDesign,不新增同名项目级封装:
- `Button` - `Button`
- `Input` and `SearchInput` - `Input`、`Textarea` 和搜索输入组合
- `Select` - `Select`
- `TreeSelect` - `TreeSelect`
- `Table` - `Table`
- `Pagination` - `Pagination`
- `FormItem` - `Form` 和 `FormItem`
- `Modal` - `Modal`
- `Drawer` - `Drawer`
- `Popconfirm` - `Popconfirm`
...@@ -26,12 +28,75 @@ ...@@ -26,12 +28,75 @@
- `Skeleton` - `Skeleton`
- `Alert` - `Alert`
- `Tooltip` - `Tooltip`
- `Upload`
新的业务页面应直接组合 TDesign 基础组件,或消费 `@gl/business-components` 中已经沉淀的业务组件。不得在页面内复制或临时创建一套相似基础组件。
## 业务组件层
`@gl/business-components` 是工作区级共享业务组件包,源码目录为仓库根级 `packages/business-components`。
业务组件 SHOULD 封装可跨前端项目复用的业务语义和页面模式,包括:
- 登录页框架。
- 登录后后台框架。
- 搜索筛选区。
- 表格页容器。
- 状态标签映射。
- 表单抽屉和表单弹窗。
- 删除、停用、启用等确认操作。
- 上传字段、媒体字段和附件字段。
- 分页列表和批量操作工具栏。
业务组件 SHALL 基于 TDesign 组合实现,不重新实现 TDesign 已覆盖的基础交互、弹层定位、键盘可访问性、表单收集和校验能力。
项目私有组件只有在确认不具备跨项目复用价值时,才放在具体项目内部。
## 登录页使用
所有前端项目的登录页 SHALL 使用统一登录页规范,并优先从 `@gl/business-components` 复用登录页业务组件。
统一登录页规则:
- 登录页顶部信息固定为系统名称和系统描述。
- 系统名称使用深色、加粗大标题。
- 系统描述位于系统名称下方,使用浅色、正常字号文本。
- 登录页不显示账号、密码字段标签;字段提示放入输入框 placeholder,账号为 `请输入账号`,密码为 `请输入密码`。
- 账号输入框左侧使用用户图标。
- 密码输入框左侧使用锁图标。
- 密码输入框右侧使用眼睛图标切换密码可见性。
- 登录页必须展示背景图片,图片等比例居中显示。
- 背景图片后方铺设同色系背景色,避免宽屏或加载过程出现割裂色块;背景色 SHALL 由业务项目通过组件参数传入,不在共享登录组件中写死。
- 登录区域最低高度为 `350px`。
- 登录区域必须在背景上水平和垂直居中。
登录页基础控件直接使用 TDesign `Input`、`Button` 和 `tdesign-icons-react` 图标,不在项目内新增同名基础组件封装。登录页业务容器、标题描述、背景和字段排布 SHALL 沉淀为 `@gl/business-components` 业务组件;具体项目只传入系统名称、系统描述、背景图片、背景色、账号密码值、错误信息和提交处理。
新的业务页面应组合这些基础组件,不要在页面内复制或临时创建一套相似组件。 ## 登录后后台框架
## 按钮 所有前端项目的登录后后台页面 SHALL 使用统一后台框架规范,并优先从 `@gl/business-components` 复用登录后框架业务组件。
按钮类型: 统一后台框架规则:
- 路由默认跳转到第一个可用二级菜单页面。
- 整体页面固定为左右结构,左侧为菜单,右侧为内容。
- 左侧菜单顶部展示系统名称,下方展示一二级菜单。
- 左侧菜单必须支持收起/展开;收起后保留图标导航,展开后展示系统名称和菜单文字。
- 菜单图标由具体业务项目的菜单配置传入,统一使用 `tdesign-icons-react` 图标组件;共享后台框架不得硬编码业务菜单图标。
- 右侧内容区域固定分为 header 和 content。
- header 高度固定,左侧展示面包屑。
- 二级菜单页面面包屑展示为 `一级菜单 > 二级菜单`。
- 新增、编辑等独立页面面包屑展示为 `一级菜单 > 二级菜单 > 独立页面名称`,二级菜单项可点击返回二级菜单页面。
- header 右侧展示用户名称和用户头像;无头像时使用默认背景色,并展示用户名称第一个字。
- 如果系统没有个人信息功能,`退出登录` 按钮展示在头像右侧。
- 如果系统有个人信息功能,点击用户头像展示下拉菜单,下拉菜单包含 `个人信息` 和 `退出登录`。
- content 区域内边距固定为 `24px`。
后台框架基础控件直接使用 TDesign `Menu`、`Breadcrumb`、`Avatar`、`Button` 和 `Dropdown`,图标统一使用 `tdesign-icons-react`。后台框架布局、菜单层级、收起展开、面包屑、用户区和内容间距 SHALL 沉淀为 `@gl/business-components` 业务组件;具体项目只传入系统名称、菜单配置、当前菜单、面包屑、用户信息和动作回调。
## 按钮使用
按钮优先使用 TDesign 的按钮类型,并按以下业务语义映射:
- `primary`:主要业务动作。 - `primary`:主要业务动作。
- `default`:普通动作。 - `default`:普通动作。
...@@ -45,10 +110,28 @@ ...@@ -45,10 +110,28 @@
- `md`:默认控件高度。 - `md`:默认控件高度。
- `lg`:少用,仅用于重要表单动作或空状态主动作。 - `lg`:少用,仅用于重要表单动作或空状态主动作。
## 表格 ## 表格使用
表格是后台列表页的默认信息承载方式。 表格是后台列表页的默认信息承载方式。
`agent` 工作区下所有后台管理系统前端项目 SHALL 默认使用 `@gl/business-components` 的 `BusinessTable` 渲染后台列表表格。页面、demo 和业务模块 SHALL NOT 直接组合 TDesign `Table`、TDesign `Pagination`、TDesign `Empty`、`StatePlaceholder` 和按钮来替代 `BusinessTable` 的后台表格模式。
`BusinessTable` SHALL 统一承接后台表格本体、普通空态、筛选无结果、请求失败、权限受限、加载中和分页总数展示。页面仍负责搜索条件、请求参数、业务弹窗、权限判断、行操作回调和埋点等业务逻辑。
`StatePlaceholder` 仅用于非表格区域的通用占位,例如页面级异常、卡片级缺省内容、引导区或其他不依赖表格结构的状态展示。若某个后台表格需要特殊状态或特殊动作,应优先扩展 `BusinessTable` 的受控配置,并通过 OpenSpec 更新规范,不在页面内临时拼装一套表格状态。
后台列表页 SHALL 以 `content` 列表页作为固定参考模式,统一采用以下结构:
1. 页面标题区:展示页面标题、必要说明和主创建动作,主创建按钮放在右侧。
2. 筛选查询区:只承载关键词、筛选项、日期范围、查询和重置。
3. 表格工具栏:左侧承载选中态和批量操作,右侧承载导出、刷新、列设置和密度设置等表格级工具。
4. 表格:承载数据、状态标签和行内操作。
5. 分页:承载页码、每页条数和总数展示。
`导出` 属于表格级工具,默认放在表格工具栏右侧。若页面同时支持导出当前筛选结果和导出选中数据,应使用下拉菜单明确区分 `导出筛选结果` 和 `导出选中项`。
批量操作属于选中态工具,默认放在表格工具栏左侧,并和行选择状态绑定。未选择数据时批量按钮应禁用、弱化或隐藏;已选择数据时展示 `已选择 N 项`,并启用对应批量操作。批量删除等破坏性动作仍必须二次确认。
必须具备: 必须具备:
- 稳定的 `rowKey`。 - 稳定的 `rowKey`。
...@@ -59,9 +142,9 @@ ...@@ -59,9 +142,9 @@
- 状态展示使用状态标签,不直接展示普通文本。 - 状态展示使用状态标签,不直接展示普通文本。
- 每个页面必须记录默认排序和筛选规则。 - 每个页面必须记录默认排序和筛选规则。
## 表单 ## 表单使用
使用 `FormItem` 承载标签、必填标识、帮助文案和校验错误。 使用 TDesign `Form` 和 `FormItem` 承载标签、必填标识、帮助文案和校验错误。
规则: 规则:
...@@ -71,6 +154,14 @@ ...@@ -71,6 +154,14 @@
- 提交按钮必须展示 loading 状态。 - 提交按钮必须展示 loading 状态。
- 取消操作应返回上一页,或关闭弹窗且不保存。 - 取消操作应返回上一页,或关闭弹窗且不保存。
新增、编辑等独立页面的页头操作区 SHALL 统一遵循:
- 左侧展示 `返回`、页面标题和必要说明。
- 右侧只展示主操作 `保存`,不再提供 `取消` 按钮。
- 离开当前独立页面由左侧 `返回` 承载。
- 页头在内容滚动容器内使用 sticky 固定;滚动表单内容时,`返回` 和 `保存` 始终保持可见。
- sticky 页头必须具备不透明背景、边框和合理层级,避免表单内容穿透或覆盖页头。
## 弹窗和抽屉 ## 弹窗和抽屉
- 弹窗用于确认、二维码预览、短表单、小型聚焦任务。 - 弹窗用于确认、二维码预览、短表单、小型聚焦任务。
......
...@@ -38,11 +38,17 @@ ...@@ -38,11 +38,17 @@
1. 面包屑/标题栏。 1. 面包屑/标题栏。
2. 搜索/筛选区。 2. 搜索/筛选区。
3. 主操作区,通常位于右上角。 3. 表格工具栏。
4. 表格或详情表单。 4. 表格或详情表单。
5. 列表页分页。 5. 列表页分页。
6. 不需要完整页面时,用弹窗或抽屉承载聚焦编辑任务。 6. 不需要完整页面时,用弹窗或抽屉承载聚焦编辑任务。
后台列表页以 `content` 列表页作为固定参考模式。创建类主操作放在页面标题区右侧;搜索/筛选区只放查询条件、查询和重置;表格工具栏左侧放选中态和批量操作,右侧放导出、刷新、列设置、密度设置等表格级工具。
导出默认放在表格工具栏右侧,表达对当前结果集的处理。若同时支持导出筛选结果和导出选中项,使用下拉菜单区分。批量操作默认放在表格工具栏左侧,并在已选择数据时展示 `已选择 N 项`。
新增、编辑等独立页面的页头左侧展示 `返回`、页面标题和必要说明,右侧只展示主操作 `保存`,不展示 `取消`。页面内容滚动时,页头操作区必须在内容滚动容器内 sticky 固定,确保 `返回` 和 `保存` 始终可见;sticky 页头需要有不透明背景、边框和合理层级,避免内容穿透。
后台管理页面要保持信息密度和可扫读性。避免营销式首屏、装饰性卡片和过大的标题字号。 后台管理页面要保持信息密度和可扫读性。避免营销式首屏、装饰性卡片和过大的标题字号。
## 交互规则 ## 交互规则
...@@ -51,6 +57,8 @@ ...@@ -51,6 +57,8 @@
- 如果业务上可逆,启用某个已停用对象可以不二次确认。 - 如果业务上可逆,启用某个已停用对象可以不二次确认。
- 禁用的操作必须有明显禁用态,最好提供 tooltip 或内联原因。 - 禁用的操作必须有明显禁用态,最好提供 tooltip 或内联原因。
- 表格、提交按钮、文件上传、外部同步操作都必须有 loading 状态。 - 表格、提交按钮、文件上传、外部同步操作都必须有 loading 状态。
- 后台列表页首次进入且主数据尚未返回时,主体区域使用骨架屏;分页、搜索、筛选、排序或刷新等后续请求使用表格区域局部 loading。
- 已有数据的列表刷新期间优先保留旧数据和表格结构,只在表格区域展示 loading,避免内容跳空或整页闪烁。
- 空状态必须明确;如果存在下一步动作,应提供可操作入口。 - 空状态必须明确;如果存在下一步动作,应提供可操作入口。
- 表单校验应显示在字段附近;全局 toast 只用于提交结果或非字段错误。 - 表单校验应显示在字段附近;全局 toast 只用于提交结果或非字段错误。
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
它需要沉淀三类共享资产: 它需要沉淀三类共享资产:
- 工作流资产:OpenSpec + Superpowers 的需求澄清、规范、计划、验证流程。 - 工作流资产:OpenSpec + Superpowers 的需求澄清、规范、计划、验证流程。
- UI 资产:公司 Web 桌面端设计 token、组件库、页面模式。 - UI 资产:公司 Web 桌面端设计 token、TDesign 使用规范、`@gl/business-components` 业务组件和页面模式。
- 工程资产:前端通用配置、工具链、测试基线。 - 工程资产:前端通用配置、工具链、测试基线。
## 推荐目录 ## 推荐目录
...@@ -27,6 +27,9 @@ architecture-spec/ ...@@ -27,6 +27,9 @@ architecture-spec/
changes/ # 工作区级变更 changes/ # 工作区级变更
specs/ # 已归档的全局规范 specs/ # 已归档的全局规范
packages/
business-components/ # @gl/business-components,工作区级 TDesign 业务组件包
workspace/ workspace/
agent-admin/ agent-admin/
AGENTS.md AGENTS.md
...@@ -34,14 +37,14 @@ workspace/ ...@@ -34,14 +37,14 @@ workspace/
openspec/ # 前端项目 OpenSpec openspec/ # 前端项目 OpenSpec
packages/ packages/
contracts/ # 前端视角契约、字段、枚举和 mock 数据 contracts/ # 前端视角契约、字段、枚举和 mock 数据
ui/ # 前端可复用 UI 组件 ui/ # 迁移期项目内 UI;新业务组件优先沉淀到 @gl/business-components
config/ # 前端工程配置 config/ # 前端工程配置
utils/ # 前端通用工具 utils/ # 前端通用工具
single-page/ # Agent 管理相关单页面项目 single-page/ # Agent 管理相关单页面项目
openspec/ # 单页面项目 OpenSpec openspec/ # 单页面项目 OpenSpec
packages/ packages/
contracts/ # 单页面视角契约、字段、枚举和 mock 数据 contracts/ # 单页面视角契约、字段、枚举和 mock 数据
ui/ # 单页面可复用 UI 组件 ui/ # 迁移期项目内 UI;新业务组件优先沉淀到 @gl/business-components
config/ # 单页面工程配置 config/ # 单页面工程配置
utils/ # 单页面通用工具 utils/ # 单页面通用工具
backend/ # Agent 管理后台后端,技术栈待确认 backend/ # Agent 管理后台后端,技术栈待确认
...@@ -60,15 +63,16 @@ workspace/ ...@@ -60,15 +63,16 @@ workspace/
| --- | --- | | --- | --- |
| `AGENTS.md` | 仓库规则入口,统一承载项目级规则、OpenSpec + Superpowers 工作流门禁,以及不同 IDE / Agent 的协作约束。 | | `AGENTS.md` | 仓库规则入口,统一承载项目级规则、OpenSpec + Superpowers 工作流门禁,以及不同 IDE / Agent 的协作约束。 |
| `architecture-spec/` | 全局规范中心,沉淀架构、技术栈、组件规范、决策和工作区级 OpenSpec。 | | `architecture-spec/` | 全局规范中心,沉淀架构、技术栈、组件规范、决策和工作区级 OpenSpec。 |
| `packages/business-components/` | 工作区级共享业务组件包,包名为 `@gl/business-components`,基于 TDesign 组合后台和业务页面模式。 |
| `workspace/agent-admin/` | Agent 管理相关业务项目总目录。 | | `workspace/agent-admin/` | Agent 管理相关业务项目总目录。 |
| `workspace/agent-admin/web/` | 后台管理前端,当前可承载 React + TypeScript + Vite 等前端基座。 | | `workspace/agent-admin/web/` | 后台管理前端,当前可承载 React + TypeScript + Vite 等前端基座。 |
| `workspace/agent-admin/single-page/` | Agent 管理相关单页面项目,适合承载独立展示或轻量交互场景。 | | `workspace/agent-admin/single-page/` | Agent 管理相关单页面项目,适合承载独立展示或轻量交互场景。 |
| `workspace/agent-admin/backend/` | 后端预留区,当前只定义目录边界,不预先锁定技术栈。 | | `workspace/agent-admin/backend/` | 后端预留区,当前只定义目录边界,不预先锁定技术栈。 |
| `workspace/agent-admin/web/packages/ui/` | 后台前端可复用 UI 组件。 | | `workspace/agent-admin/web/packages/ui/` | 迁移期后台前端项目内 UI;新业务组件优先沉淀到 `@gl/business-components`。 |
| `workspace/agent-admin/web/packages/contracts/` | 后台前端视角的字段、枚举、payload、mock 数据和接口契约沉淀区。 | | `workspace/agent-admin/web/packages/contracts/` | 后台前端视角的字段、枚举、payload、mock 数据和接口契约沉淀区。 |
| `workspace/agent-admin/web/packages/config/` | 后台前端工程配置。 | | `workspace/agent-admin/web/packages/config/` | 后台前端工程配置。 |
| `workspace/agent-admin/web/packages/utils/` | 无业务上下文的前端通用工具。 | | `workspace/agent-admin/web/packages/utils/` | 无业务上下文的前端通用工具。 |
| `workspace/agent-admin/single-page/packages/ui/` | 单页面项目可复用 UI 组件。 | | `workspace/agent-admin/single-page/packages/ui/` | 迁移期单页面项目内 UI;新业务组件优先沉淀到 `@gl/business-components`。 |
| `workspace/agent-admin/single-page/packages/contracts/` | 单页面项目视角的字段、枚举、payload、mock 数据和接口契约沉淀区。 | | `workspace/agent-admin/single-page/packages/contracts/` | 单页面项目视角的字段、枚举、payload、mock 数据和接口契约沉淀区。 |
| `workspace/agent-admin/single-page/packages/config/` | 单页面项目工程配置。 | | `workspace/agent-admin/single-page/packages/config/` | 单页面项目工程配置。 |
| `workspace/agent-admin/single-page/packages/utils/` | 单页面项目通用工具。 | | `workspace/agent-admin/single-page/packages/utils/` | 单页面项目通用工具。 |
...@@ -83,28 +87,31 @@ workspace/ ...@@ -83,28 +87,31 @@ workspace/
- 单页面项目固定优先使用 `single-page`。 - 单页面项目固定优先使用 `single-page`。
- 后端项目固定优先使用 `backend`,具体技术栈由项目后续确认。 - 后端项目固定优先使用 `backend`,具体技术栈由项目后续确认。
- package 命名:`@gl/<project>-<name>` 或后续统一为 `@gl/<name>`。 - package 命名:`@gl/<project>-<name>` 或后续统一为 `@gl/<name>`。
- 工作区级业务组件包固定命名为 `@gl/business-components`。
- OpenSpec change 命名:`<project>-<feature>`,例如 `agent-management`、`agent-group-management`。 - OpenSpec change 命名:`<project>-<feature>`,例如 `agent-management`、`agent-group-management`。
- 工作区级 change 可使用 `workspace-<topic>`,例如 `workspace-ui-components`。 - 工作区级 change 可使用 `workspace-<topic>`,例如 `workspace-ui-components`。
## 依赖规则 ## 依赖规则
- 前端项目只依赖 `web/packages/*`。 - 前端项目可以依赖工作区级 `@gl/business-components` 和本项目 `web/packages/*`。
- 单页面项目只依赖 `single-page/packages/*`。 - 单页面项目可以依赖工作区级 `@gl/business-components` 和本项目 `single-page/packages/*`。
- 后端项目只依赖 `backend/packages/*`。 - 后端项目只依赖 `backend/packages/*`。
- 管理后台 UI 组件放在 `web/packages/ui`,单页面 UI 组件放在 `single-page/packages/ui`,后端不依赖前端 UI。 - 基础 UI 能力统一来自 `tdesign-react`;跨项目业务组件统一放在 `packages/business-components`。
- 管理后台和单页面项目的项目内 UI 目录只承载迁移期或明确项目私有的组件,后端不依赖前端 UI。
- 前端契约放在 `web/packages/contracts`,后端契约放在 `backend/packages/contracts`。 - 前端契约放在 `web/packages/contracts`,后端契约放在 `backend/packages/contracts`。
- 单页面契约放在 `single-page/packages/contracts`。 - 单页面契约放在 `single-page/packages/contracts`。
- 前后端契约需要并行开发时,先在各自 contracts 中沉淀,再通过需求确认或 OpenSpec 对齐。 - 前后端契约需要并行开发时,先在各自 contracts 中沉淀,再通过需求确认或 OpenSpec 对齐。
- config 不依赖业务代码。 - config 不依赖业务代码。
- utils 只放无业务上下文工具。 - utils 只放无业务上下文工具。
- 业务项目之间默认不互相依赖;如需共享,先沉淀到 `architecture-spec` 或后续公共包。 - 业务项目之间默认不互相依赖;如需共享,先沉淀到 `architecture-spec` 或后续公共包。
- 新增可跨两个及以上前端项目复用的业务组件时,优先沉淀到 `@gl/business-components`,并在 OpenSpec 中说明适用范围。
## 复用边界 ## 复用边界
应复用: 应复用:
- 页面布局模式。 - 页面布局模式。
- 搜索区、表格、分页、表单、弹窗、抽屉、上传、状态标签等组件。 - 搜索区、表格页容器、分页列表、表单抽屉、弹窗确认、上传字段、状态标签等 `@gl/business-components` 组件。
- OpenSpec/Superpowers 文档模板。 - OpenSpec/Superpowers 文档模板。
- lint、format、test、build 配置。 - lint、format、test、build 配置。
...@@ -122,5 +129,5 @@ workspace/ ...@@ -122,5 +129,5 @@ workspace/
4. 如需要单页面项目,在 `workspace/<project-name>/single-page` 下新增单页面项目。 4. 如需要单页面项目,在 `workspace/<project-name>/single-page` 下新增单页面项目。
5. 如需要后端并行开发,在 `workspace/<project-name>/backend` 下新增后端项目。 5. 如需要后端并行开发,在 `workspace/<project-name>/backend` 下新增后端项目。
6. 在各自项目的 `packages/contracts` 中分别沉淀契约。 6. 在各自项目的 `packages/contracts` 中分别沉淀契约。
7. 前端优先从 UI 规范、组件规范和 config 复用能力。 7. 前端优先接入 `tdesign-react`、`@gl/business-components`、UI 规范、组件规范和 config 复用能力。
8. 只有当能力可被至少两个项目复用,或明显属于工作区基础设施,才抽到更高层公共资产。 8. 只有当能力可被至少两个项目复用,或明显属于工作区基础设施,才抽到更高层公共资产。
# 决策 0002:工作区统一 TDesign 业务组件体系
## 状态
已确认;作为后续前端项目和 OpenSpec change 的默认约束。
## 背景
工作区后续会承载多个前端项目,包括后台管理 Web 项目、单页面项目,以及未来可能新增的其他业务前端。此前文档中将 `web/packages/ui` 与 `single-page/packages/ui` 分别作为各项目组件入口,容易导致不同前端项目重复封装基础组件、交互细节不一致,以及设计规范漂移。
当前方向调整为:基础 UI 能力直接采用 `tdesign-react`,工作区只沉淀业务语义组件、页面模式和设计规范适配。所有前端项目共享同一套组件使用规则和业务组件封装策略。
## 决策
- 工作区所有 React 前端项目 SHALL 以 `tdesign-react` 作为基础组件来源。
- 项目页面 SHOULD 直接使用 TDesign 基础组件,不再新增 `Button`、`Input`、`Select`、`Table`、`Modal`、`Drawer` 等同名基础组件封装。
- 工作区 SHALL 建立统一的业务组件层,包名为 `@gl/business-components`,源码目录为仓库根级 `packages/business-components`。
- `@gl/business-components` SHALL 用于封装后台和业务场景中的复用模式,例如搜索筛选区、表格页容器、状态标签、表单抽屉、确认操作、上传字段和分页列表。
- 业务组件 SHALL 基于 TDesign 组件组合实现,并通过 props 暴露业务语义,而不是重新实现 TDesign 已覆盖的基础交互。
- 所有前端项目 SHALL 遵循 `architecture-spec/docs/architecture/` 下的工作区级前端规范、组件规范和设计 token 约束。
- 新前端项目接入时 SHALL 优先消费工作区统一业务组件与规范;只有确认为项目私有且不可复用的组件,才放在项目内部。
- 现有自研基础组件不作为新功能默认选型;后续迁移 SHALL 通过 OpenSpec change 分批完成,避免一次性大范围重构。
## 影响
- `architecture-spec/docs/architecture/component-guidelines.md` 需要从“自研基础组件清单”调整为“TDesign 基础组件 + 业务组件封装规则”。
- `architecture-spec/docs/architecture/monorepo-strategy.md` 需要明确共享业务组件层的位置和各前端项目的消费边界。
- `workspace/agent-admin/web/packages/ui` 现有组件需要后续评估:保留业务封装、迁移到共享业务组件层,或逐步废弃同名基础封装。
- `workspace/agent-admin/single-page` 后续需要补齐 TDesign 依赖与统一样式入口,具体改动通过单独 OpenSpec change 确认。
- 后续所有会改变页面行为或组件 API 的迁移,仍必须先进入对应 OpenSpec change 并完成验证。
## 迁移约束
- 迁移期内可以临时保留现有自研基础组件引用,但新页面和新组件默认不得继续扩展同名基础封装。
- 每次迁移 SHALL 通过对应 OpenSpec change 明确影响范围、替换路径、测试和浏览器验证要求。
- 现有 `packages/ui` 中确有业务语义的能力 SHOULD 迁移到 `@gl/business-components`;纯基础组件封装 SHOULD 逐步废弃。
# 决策 0003:后台管理系统统一使用 BusinessTable
## 状态
已确认;作为 `agent` 工作区下所有后台管理系统前端项目的默认约束。
## 背景
`agent` 工作区后续会包含多个后台管理系统前端项目。此前各项目页面可以直接组合 TDesign `Table`、`Pagination`、`Empty`、`StatePlaceholder` 和按钮来完成列表展示,这会导致表格空态、筛选无结果、失败态、权限态、loading、分页总数和操作列样式在不同项目之间漂移。
`@gl/business-components` 已经沉淀 `BusinessTable`,用于统一后台表格、表格状态和分页展示。为避免 demo 或后续项目再次绕过业务表格组件,需要将表格使用规则提升为工作区级约束。
## 决策
- `agent` 工作区下所有后台管理系统前端项目 SHALL 默认使用 `@gl/business-components` 的 `BusinessTable` 渲染后台列表表格。
- 新页面、新 demo 和新增表格功能 SHALL NOT 直接组合 TDesign `Table`、TDesign `Pagination`、TDesign `Empty`、`StatePlaceholder` 和按钮来替代 `BusinessTable` 的后台表格模式。
- `BusinessTable` SHALL 承接后台表格本体、普通空态、筛选无结果、请求失败、权限受限、加载中和分页总数展示。
- 页面仍 SHALL 负责搜索条件、请求参数、数据映射、业务弹窗、权限判断、行操作回调和埋点等业务逻辑。
- `StatePlaceholder` SHALL 仅用于非表格区域的通用占位,例如页面级异常、卡片级缺省内容、引导区或其他不依赖表格结构的状态展示。
- 如果后台表格需要特殊状态或特殊动作,项目 SHALL 优先扩展 `BusinessTable` 的受控配置,并同步更新工作区级规范和对应 OpenSpec,不在页面内临时拼装一套表格状态。
- 历史页面若尚未使用 `BusinessTable`,SHOULD 通过独立 OpenSpec change 分批迁移,避免无规格的大范围重构。
## 影响
- `architecture-spec/docs/architecture/component-guidelines.md` 的表格使用规则需要明确 `BusinessTable` 是后台管理系统表格默认入口。
- 具体项目的 OpenSpec 如涉及后台表格、列表页或组件 demo,应继承该工作区级约束。
- `workspace/agent-admin/web` 的组件 demo 需要调整为通过 `BusinessTable` 展示表格状态,而不是在 `StatePlaceholder` demo 中展示表格状态集合。
## 例外
- 非后台管理系统的公开站点、落地页、内容展示页或高度定制交互页面,不默认受本决策约束。
- 简单详情页中的键值信息、非列表型数据展示、统计卡片和非表格结构的状态占位,不要求使用 `BusinessTable`。
- 若确有后台表格无法由 `BusinessTable` 承载,必须先通过 OpenSpec 说明例外原因、替代方案、状态规则和验证方式。
## Context
所有前端项目都需要复用 `content` 列表页的后台管理形态。现有规范已经要求后台页面使用标题栏、搜索/筛选区、表格和分页,但没有明确导出、刷新、列设置、批量操作等按钮的归属,容易在项目之间形成不同布局。
本次变更只锁定页面信息架构和按钮归属,不进入组件实现。
## Goals / Non-Goals
**Goals:**
- 固化所有后台列表页的标准结构。
- 明确筛选查询、主创建动作、表格级工具和批量操作的边界。
- 为后续 `@gl/business-components` 沉淀表格页容器和批量工具栏提供规范依据。
**Non-Goals:**
- 不修改当前 `agent-admin` 页面代码。
- 不实现新的导出、批量操作、列设置或密度切换组件。
- 不规定具体接口、导出文件格式或批量任务执行方式。
## Decisions
### Decision: 列表页固定为五段式结构
后台列表页 SHALL 使用页面标题区、筛选查询区、表格工具栏、表格、分页的顺序组织内容。标题区表达页面身份和主创建动作,筛选区只处理查询条件,表格工具栏处理当前结果集与选中项。
替代方案是继续把所有操作放在标题右侧或筛选区末尾。该方案短期更省空间,但随着导出、批量操作和列设置增加,会让查询意图和数据处理意图混在一起。
### Decision: 导出归为表格级工具
`导出` SHALL 放在表格工具栏右侧,因为它处理的是当前表格结果集或选中项,而不是查询条件本身。若页面同时支持导出筛选结果和导出选中项,使用下拉菜单区分动作。
替代方案是把导出放进筛选区。该方案容易让用户误以为导出只是筛选表单的一部分,也不利于和刷新、列设置、密度等表格工具保持一致。
### Decision: 批量操作归为选中态工具
批量操作 SHALL 放在表格工具栏左侧,并和行选择状态绑定。未选择时可以禁用或弱化展示;已选择时展示 `已选择 N 项` 和可用批量动作。批量删除等高风险动作仍需要二次确认。
替代方案是把批量操作放在表格行操作列或页面标题区。该方案会弱化“先选择、再批量处理”的流程关系,也会让批量动作离选中反馈太远。
## Risks / Trade-offs
- [Risk] 某些轻量列表页没有导出、批量操作或列设置,工具栏可能显得空。-> Mitigation: 表格工具栏按能力出现,无表格级工具且无批量操作时可以省略。
- [Risk] 已有页面布局与新规范不完全一致。-> Mitigation: 本次只建立新规范,既有页面后续按业务变更逐步对齐。
## Why
当前各前端项目的后台列表页已有搜索区、表格和分页基础结构,但表格级操作、导出和批量操作的放置规则尚未统一。随着 `content` 类列表页成为固定参考,需要把操作区分层沉淀为全局规范,避免不同项目把查询、主操作、导出和批量处理混放。
## What Changes
- 将 `content` 列表页作为所有前端项目后台列表页的固定参考模式。
- 固化列表页结构:页面标题区、筛选查询区、表格工具栏、表格和分页。
- 明确创建类主操作放在页面标题区右侧。
- 明确导出、刷新、列设置、密度等表格级工具放在表格工具栏右侧。
- 明确批量操作放在表格工具栏左侧,并和表格选中状态绑定。
- 明确筛选查询区只承载查询条件、查询和重置,不放导出或批量操作。
## Capabilities
### New Capabilities
无。
### Modified Capabilities
- `web-desktop-ui-standard`: 补充后台列表页操作区分层、导出按钮和批量操作按钮的位置规范。
## Impact
- 影响全局前端规范文档:`docs/architecture/component-guidelines.md`、`docs/architecture/frontend-conventions.md`。
- 影响全局 OpenSpec:`openspec/specs/web-desktop-ui-standard/spec.md`。
- 本次仅更新规范和 OpenSpec,不修改业务代码、组件实现、接口或依赖。
## ADDED Requirements
### Requirement: 后台列表页必须统一操作区分层
后台列表页 SHALL 采用 `content` 列表页作为固定参考模式,按页面标题区、筛选查询区、表格工具栏、表格和分页组织内容。不同类型操作 MUST 放在对应区域,避免查询、主创建动作、表格级工具和批量操作混放。
#### Scenario: 渲染标准后台列表页
- **WHEN** 前端项目实现包含查询、表格数据和分页的后台列表页
- **THEN** 页面按页面标题区、筛选查询区、表格工具栏、表格、分页的顺序组织内容
- **AND** 主创建动作放在页面标题区右侧
- **AND** 筛选查询区只放查询条件、查询和重置操作
#### Scenario: 放置导出和表格工具
- **WHEN** 列表页提供导出、刷新、列设置或密度设置等表格级工具
- **THEN** 这些工具放在表格工具栏右侧
- **AND** `导出` 默认导出当前筛选结果
- **AND** 同时支持导出筛选结果和导出选中项时,使用下拉菜单区分动作
#### Scenario: 放置批量操作
- **WHEN** 列表页提供批量删除、批量启用、批量停用、批量移动或其他批量操作
- **THEN** 批量操作放在表格工具栏左侧
- **AND** 批量操作和表格行选择状态绑定
- **AND** 已选择数据时展示 `已选择 N 项`
- **AND** 破坏性批量操作在提交前必须二次确认
## 1. 规范锁定
- [x] 1.1 创建全局 OpenSpec change,说明 `content` 列表页操作区分层的范围和影响。
- [x] 1.2 补充 OpenSpec spec,覆盖页面标题区、筛选查询区、表格工具栏、导出和批量操作位置。
## 2. 全局文档
- [x] 2.1 更新全局组件规范,明确表格列表页五段式结构。
- [x] 2.2 更新前端布局规范,明确导出、批量操作和表格工具的默认位置。
## 3. 验证
- [x] 3.1 运行 OpenSpec 严格校验,确认规范变更有效。
## Context
`agent` 工作区已有 `@gl/business-components`,其中 `BusinessTable` 用于统一后台表格、表格状态和分页展示。用户已确认该约束不只适用于 `agent-web` 或 `agent-admin`,而是适用于 `agent` 工作区下所有项目的后台管理系统。
## Goals / Non-Goals
**Goals:**
- 将 `BusinessTable` 写入工作区级后台表格默认规范。
- 让后续后台项目、新页面、新 demo 和新增表格功能默认继承统一表格入口。
- 明确页面职责与 `BusinessTable` 职责边界。
- 为特殊表格例外和历史迁移提供 OpenSpec 路径。
**Non-Goals:**
- 不在本 change 中迁移所有历史后台页面。
- 不限制非后台管理系统的公开站点、落地页或高度定制交互页面。
- 不冻结 `BusinessTable` API,后续特殊状态仍可通过规范化扩展演进。
## Decisions
- 在 `web-desktop-ui-standard` 中增加后台表格默认入口要求。
- 原因:这是跨项目前端行为约束,应落在工作区级 Web 桌面端规范,而不是某个业务项目私有规范。
- 替代方案:只写在 `agent-admin/web` 项目规范中。该方案无法覆盖 `agent` 下其他后台管理系统。
- 页面不得直接拼装后台表格模式。
- 原因:表格状态和分页规则应由 `BusinessTable` 统一承接,页面只负责业务数据和交互。
- 历史迁移分批处理。
- 原因:一次性迁移所有历史页面风险较高,且本次需求重点是锁定后续默认约束和 demo 展示。
## Risks / Trade-offs
- 历史页面仍可能短期存在旧表格拼装。
- 缓解:通过独立 OpenSpec change 分批迁移,并禁止新功能继续扩散旧模式。
- 特殊业务表格可能需要额外状态或动作。
- 缓解:优先扩展 `BusinessTable` 的受控配置,并同步更新 OpenSpec。
## Migration Plan
1. 写入工作区级 OpenSpec delta。
2. 校验 `standardize-backoffice-business-table-usage`。
3. 后续项目或页面涉及后台表格时,按该规范默认使用 `BusinessTable`。
4. 既有页面如需迁移,另起 OpenSpec change。
## Why
`agent` 工作区后续会包含多个后台管理系统前端项目,如果各项目继续直接拼装 TDesign `Table`、`Pagination`、`Empty`、`StatePlaceholder` 和按钮,表格状态、分页总数和 loading 规则会持续漂移。`@gl/business-components` 已沉淀 `BusinessTable`,需要将其作为工作区级后台表格默认入口。
## What Changes
- 在工作区级 OpenSpec 中明确:`agent` 下所有后台管理系统前端项目的后台列表表格 SHALL 默认使用 `@gl/business-components` 的 `BusinessTable`。
- 禁止新页面、新 demo 和新增表格功能直接拼装 TDesign 表格、分页、空态和按钮来替代 `BusinessTable` 的后台表格模式。
- 明确 `BusinessTable` 承接表格本体、普通空态、筛选无结果、请求失败、权限受限、加载中和分页总数展示。
- 明确 `StatePlaceholder` 仅用于非表格区域的通用占位。
- 历史页面迁移通过独立 OpenSpec change 分批处理。
## Capabilities
### New Capabilities
<!-- 无。 -->
### Modified Capabilities
- `web-desktop-ui-standard`: 增加后台管理系统表格必须默认使用 `BusinessTable` 的工作区级要求。
## Impact
- 影响 `architecture-spec/openspec/specs/web-desktop-ui-standard/spec.md` 的工作区级前端规范。
- 影响后续 `agent` 下所有后台管理系统前端项目的新列表页、组件 demo 和表格功能设计。
- 不强制本 change 立即迁移所有历史页面;历史页面迁移应由后续独立 OpenSpec 覆盖。
## ADDED Requirements
### Requirement: 后台管理系统表格必须默认使用 BusinessTable
`agent` 工作区下所有后台管理系统前端项目 SHALL 默认使用 `@gl/business-components` 的 `BusinessTable` 渲染后台列表表格,并由 `BusinessTable` 统一承接表格本体、普通空态、筛选无结果、请求失败、权限受限、加载中和分页总数展示。
#### Scenario: 新建后台列表页
- **WHEN** `agent` 工作区任一后台管理系统前端项目新增包含后台列表表格的页面
- **THEN** 页面 SHALL 使用 `BusinessTable` 渲染表格区域
- **AND** 页面 SHALL NOT 直接组合 TDesign `Table`、TDesign `Pagination`、TDesign `Empty`、`StatePlaceholder` 和按钮来替代 `BusinessTable` 的后台表格模式
#### Scenario: 新增 demo 或表格功能
- **WHEN** 后台管理系统项目新增组件 demo、业务模块或表格相关功能
- **THEN** 表格状态示例和表格运行态 SHALL 通过 `BusinessTable` 展示
- **AND** 系统 SHALL NOT 在页面内临时拼装另一套表格空态、失败态、权限态、loading 或分页总数展示规则
#### Scenario: 页面处理业务逻辑
- **WHEN** 页面使用 `BusinessTable` 渲染后台列表表格
- **THEN** 页面 SHALL 负责搜索条件、请求参数、数据映射、业务弹窗、权限判断、行操作回调和埋点
- **AND** `BusinessTable` SHALL 负责表格结构、状态展示和分页总数展示
#### Scenario: 非表格占位
- **WHEN** 页面展示页面级异常、卡片级缺省内容、引导区或其他不依赖表格结构的通用占位
- **THEN** 页面 MAY 使用 `StatePlaceholder`
- **AND** 页面 SHALL NOT 使用 `StatePlaceholder` 替代后台表格状态区域
#### Scenario: 特殊表格例外
- **WHEN** 后台表格场景无法由当前 `BusinessTable` 承载
- **THEN** 项目 MUST 先通过 OpenSpec 说明例外原因、替代方案、状态规则和验证方式
- **AND** 项目 SHALL 优先评估扩展 `BusinessTable` 的受控配置
#### Scenario: 历史页面迁移
- **WHEN** 历史后台页面尚未使用 `BusinessTable`
- **THEN** 项目 SHOULD 通过独立 OpenSpec change 分批迁移
- **AND** 新页面、新 demo 和新增表格功能 SHALL NOT 继续扩散页面级自组装表格模式
## 1. OpenSpec 对齐
- [x] 1.1 创建 proposal,明确工作区级 `BusinessTable` 默认入口约束
- [x] 1.2 创建设计说明,明确约束范围覆盖 `agent` 下所有后台管理系统前端项目
- [x] 1.3 创建 `web-desktop-ui-standard` spec delta,写入后台表格默认使用 `BusinessTable` 的要求
- [x] 1.4 等待用户确认 OpenSpec 后进入具体项目 TDD
## 2. 文档同步
- [x] 2.1 在架构决策中记录后台管理系统统一使用 `BusinessTable`
- [x] 2.2 在组件使用规范中记录后台表格默认入口和 `StatePlaceholder` 边界
## 3. 验证
- [x] 3.1 运行 `rtk openspec validate standardize-backoffice-business-table-usage --strict`
- [x] 3.2 在项目侧 demo OpenSpec 和实现中继承该约束
...@@ -154,6 +154,18 @@ TBD - created by archiving change define-ui-component-library. Update Purpose af ...@@ -154,6 +154,18 @@ TBD - created by archiving change define-ui-component-library. Update Purpose af
- **WHEN** 后台框架传入菜单项标识、标题、层级、链接和当前选中项 - **WHEN** 后台框架传入菜单项标识、标题、层级、链接和当前选中项
- **THEN** 组件根据配置渲染导航,而不是要求业务页面手写交互和样式逻辑 - **THEN** 组件根据配置渲染导航,而不是要求业务页面手写交互和样式逻辑
#### Scenario: 收起和展开后台菜单
- **WHEN** 后台框架渲染左侧层级菜单
- **THEN** 组件 SHALL 提供收起和展开入口
- **AND** 收起后菜单保留图标导航能力
- **AND** 展开后菜单恢复展示系统名称和菜单文字
#### Scenario: 通过项目配置传入菜单图标
- **WHEN** 业务项目配置后台菜单
- **THEN** 菜单项图标 SHALL 由业务项目菜单配置传入
- **AND** 图标组件 SHALL 来自 `tdesign-icons-react`
- **AND** 共享导航组件 SHALL NOT 在内部硬编码业务菜单图标
### Requirement: 组件实现采用测试先行 ### Requirement: 组件实现采用测试先行
组件实现 SHALL 采用 TDD 方式推进:在实现或迁移组件前,先为组件的公开行为、关键状态和可访问交互编写测试或可执行验收样例。 组件实现 SHALL 采用 TDD 方式推进:在实现或迁移组件前,先为组件的公开行为、关键状态和可访问交互编写测试或可执行验收样例。
...@@ -305,4 +317,3 @@ TBD - created by archiving change define-ui-component-library. Update Purpose af ...@@ -305,4 +317,3 @@ TBD - created by archiving change define-ui-component-library. Update Purpose af
#### Scenario: 查看组件组合 #### Scenario: 查看组件组合
- **WHEN** 多个组件在后台页面中常被组合使用 - **WHEN** 多个组件在后台页面中常被组合使用
- **THEN** Demo 路由包含代表性组合示例,例如表格操作、表单字段、状态标签、分页、弹窗和抽屉 - **THEN** Demo 路由包含代表性组合示例,例如表格操作、表单字段、状态标签、分页、弹窗和抽屉
## Purpose ## Purpose
定义 Web 桌面端页面在视觉 token、可复用基础组件、关键交互和表单反馈上的统一标准,保证后续后台页面风格和行为一致。 定义 Web 桌面端页面在视觉 token、可复用基础组件、关键交互和表单反馈上的统一标准,保证后续后台页面风格和行为一致。
## Requirements ## Requirements
### Requirement: Web 桌面端页面必须遵循公司设计 token ### Requirement: Web 桌面端页面必须遵循公司设计 token
所有 Web 桌面端页面 SHALL 使用公司设计 token,包括颜色、字号、间距、圆角和控件尺寸。 所有 Web 桌面端页面 SHALL 使用公司设计 token,包括颜色、字号、间距、圆角和控件尺寸。
...@@ -31,3 +29,53 @@ ...@@ -31,3 +29,53 @@
#### Scenario: 必填字段为空 #### Scenario: 必填字段为空
- **WHEN** 用户提交缺少必填字段的表单 - **WHEN** 用户提交缺少必填字段的表单
- **THEN** 字段展示内联校验错误,且表单不提交 - **THEN** 字段展示内联校验错误,且表单不提交
### Requirement: 后台列表页必须统一操作区分层
后台列表页 SHALL 采用 `content` 列表页作为固定参考模式,按页面标题区、筛选查询区、表格工具栏、表格和分页组织内容。不同类型操作 MUST 放在对应区域,避免查询、主创建动作、表格级工具和批量操作混放。
#### Scenario: 渲染标准后台列表页
- **WHEN** 前端项目实现包含查询、表格数据和分页的后台列表页
- **THEN** 页面按页面标题区、筛选查询区、表格工具栏、表格、分页的顺序组织内容
- **AND** 主创建动作放在页面标题区右侧
- **AND** 筛选查询区只放查询条件、查询和重置操作
#### Scenario: 放置导出和表格工具
- **WHEN** 列表页提供导出、刷新、列设置或密度设置等表格级工具
- **THEN** 这些工具放在表格工具栏右侧
- **AND** `导出` 默认导出当前筛选结果
- **AND** 同时支持导出筛选结果和导出选中项时,使用下拉菜单区分动作
#### Scenario: 放置批量操作
- **WHEN** 列表页提供批量删除、批量启用、批量停用、批量移动或其他批量操作
- **THEN** 批量操作放在表格工具栏左侧
- **AND** 批量操作和表格行选择状态绑定
- **AND** 已选择数据时展示 `已选择 N 项`
- **AND** 破坏性批量操作在提交前必须二次确认
### Requirement: 后台列表页必须区分首次加载和数据刷新
后台列表页 SHALL 按加载阶段选择反馈形式:页面首次进入且主体数据尚未返回时使用骨架屏;页面结构已经渲染后的分页、搜索、筛选、排序或刷新请求使用表格区域 loading。
#### Scenario: 首次进入列表页
- **WHEN** 用户首次进入后台列表页,且主数据请求尚未完成
- **THEN** 页面主体区域展示骨架屏
- **AND** 页面避免先展示空表格、空状态或失败状态
#### Scenario: 列表数据刷新
- **WHEN** 用户在已渲染的列表页中触发分页、搜索、筛选、排序或刷新
- **THEN** 页面保留标题区、筛选区、表头、分页和已有表格结构
- **AND** 表格区域展示局部 loading
- **AND** 如已有旧数据,刷新期间优先保留旧数据,避免列表内容跳空
### Requirement: 独立新增编辑页必须固定页头操作区
后台新增、编辑等独立页面 SHALL 在页面内容区顶部提供统一页头操作区。页头左侧承载 `返回`、标题和说明,右侧只承载主操作 `保存`;页面滚动时页头必须在内容滚动容器内保持可见。
#### Scenario: 渲染独立新增编辑页
- **WHEN** 前端项目实现新增、编辑等独立页面
- **THEN** 页头左侧展示 `返回` 和页面标题
- **AND** 页头右侧展示 `保存`
- **AND** 页头右侧不展示 `取消`
#### Scenario: 滚动独立新增编辑页
- **WHEN** 用户滚动独立页面中的表单或配置内容
- **THEN** `返回` 和 `保存` 所在页头操作区保持在屏幕可见区域
- **AND** sticky 页头具备不透明背景、边框和合理层级,避免内容滚动时穿透或覆盖页头
{
"name": "@gl/business-components",
"private": true,
"version": "0.0.0",
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"peerDependencies": {
"react": "^19.0.0",
"tdesign-icons-react": "^0.5.0",
"tdesign-react": "^1.17.0"
}
}
.root {
display: flex;
flex-direction: column;
gap: 16px;
}
.field {
display: grid;
grid-template-columns: 120px minmax(0, 1fr);
column-gap: 16px;
align-items: start;
}
.label {
display: inline-flex;
align-items: center;
gap: 4px;
min-height: 32px;
font-size: 14px;
color: #1f1f1f;
}
.required {
color: #d94841;
}
.controlWrap {
min-width: 0;
}
.controlHolder {
min-width: 0;
}
.helpText {
margin-top: 6px;
color: #666;
font-size: 12px;
line-height: 1.5;
}
.error {
margin-top: 6px;
color: #d94841;
font-size: 12px;
line-height: 1.5;
}
.readonlyValue {
display: inline-flex;
min-height: 32px;
align-items: center;
color: #1f1f1f;
}
.switch {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 32px;
padding: 0 12px;
border: 1px solid #d9d9d9;
border-radius: 6px;
background: #fff;
}
.uploadWrap {
min-width: 0;
}
.uploadWrap :global(.t-upload__card) {
gap: 12px;
}
.uploadWrap :global(.t-upload__card-item) {
width: 110px;
}
.uploadWrap :global(.t-upload__card-content),
.uploadWrap :global(.t-upload__card-container) {
width: 110px;
height: 110px;
}
.uploadWrap :global(.t-upload__card-mask) {
background-color: rgba(0, 0, 0, 0.34);
}
.uploadWrap :global(.t-upload__card-name) {
display: block;
width: 110px;
min-width: 0;
white-space: nowrap;
word-break: normal;
overflow: hidden;
text-overflow: ellipsis;
}
.uploadVideoCard {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
background: #4b5563;
}
.uploadPreview {
display: inline-flex;
flex-direction: column;
gap: 8px;
max-width: 100%;
}
.uploadImage,
.uploadVideo {
display: block;
width: 160px;
max-width: 100%;
border-radius: 8px;
background: #f3f4f6;
object-fit: cover;
}
.uploadVideo {
background: #111827;
}
import { useEffect, useMemo, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import { Button, InputNumber, Upload } from 'tdesign-react';
import type { TdUploadProps, UploadFile } from 'tdesign-react';
import { BrowseIcon, DeleteIcon } from 'tdesign-icons-react';
import { classNames } from '../shared/classNames';
import { Input, Select, Switch, Textarea } from '../shared/TDesignAccessibleControls';
import styles from './BusinessForm.module.css';
export type BusinessFormValue =
| string
| number
| boolean
| string[]
| number[]
| BusinessFormUploadedFileValue
| BusinessFormUploadedFileValue[]
| undefined
| null;
export type BusinessFormValues = Record<string, BusinessFormValue>;
export type BusinessFormErrors = Record<string, string | undefined>;
export type BusinessFormUploadKind = 'image' | 'gif' | 'video' | 'file';
export type BusinessFormUploadType = 'media' | 'file';
export interface BusinessFormUploadedFileValue {
url: string;
name?: string;
size?: number;
mimeType?: string;
kind?: BusinessFormUploadKind;
extra?: Record<string, unknown>;
}
export interface BusinessFormRenderContext {
values: BusinessFormValues;
value: BusinessFormValue;
error?: string;
disabled: boolean;
readonly: boolean;
setValue: (nextValue: BusinessFormValue) => void;
setValues: (nextValues: BusinessFormValues, changedKey?: string) => void;
}
export interface BusinessFormSelectOption {
label: ReactNode;
value: string | number;
disabled?: boolean;
}
export interface BusinessFormValidationContext {
values: BusinessFormValues;
field: BusinessFormField;
}
export interface BusinessFormFieldChangeContext {
values: BusinessFormValues;
field: BusinessFormField;
}
export interface BusinessFormChangeKeyContext {
key: string;
value: BusinessFormValue;
values: BusinessFormValues;
}
export type BusinessFormValidator = (
value: BusinessFormValue,
context: BusinessFormValidationContext,
) => string | undefined | Promise<string | undefined>;
export type BusinessFormFieldOnChange = (
nextValue: BusinessFormValue,
context: BusinessFormFieldChangeContext,
) => Partial<BusinessFormValues> | void;
interface BusinessFormFieldBase {
key: string;
label: string;
type: BusinessFormFieldType;
required?: boolean;
disabled?: boolean | ((values: BusinessFormValues) => boolean);
readonly?: boolean | ((values: BusinessFormValues) => boolean);
placeholder?: string;
helpText?: ReactNode;
helperText?: ReactNode;
visible?: boolean | ((values: BusinessFormValues) => boolean);
validator?: BusinessFormValidator;
onChange?: BusinessFormFieldOnChange;
className?: string;
}
export interface BusinessFormInputField extends BusinessFormFieldBase {
type: 'input';
maxLength?: number;
allowClear?: boolean;
allowInputOverMax?: boolean;
}
export interface BusinessFormNumberInputField extends BusinessFormFieldBase {
type: 'numberInput';
min?: number;
max?: number;
precision?: number;
allowClear?: boolean;
}
export interface BusinessFormTextareaField extends BusinessFormFieldBase {
type: 'textarea';
maxLength?: number;
rows?: number;
allowInputOverMax?: boolean;
}
export interface BusinessFormSelectField extends BusinessFormFieldBase {
type: 'select';
options: BusinessFormSelectOption[];
multiple?: boolean;
allowClear?: boolean;
}
export interface BusinessFormSwitchField extends BusinessFormFieldBase {
type: 'switch';
checkedValue?: BusinessFormValue;
uncheckedValue?: BusinessFormValue;
checkedLabel?: ReactNode;
uncheckedLabel?: ReactNode;
}
export interface BusinessFormUploadField extends BusinessFormFieldBase {
type: 'upload';
uploadType?: BusinessFormUploadType;
kinds?: BusinessFormUploadKind[];
accept?: string | string[];
maxCount?: number;
multiple?: boolean;
maxSize?: number;
upload: (
file: File,
values: BusinessFormValues,
) => Promise<string | BusinessFormUploadedFileValue>;
previewAlt?: string;
actionText?: string;
removeText?: string;
}
export interface BusinessFormDisplayTextField extends BusinessFormFieldBase {
type: 'displayText';
emptyText?: ReactNode;
render?: (value: BusinessFormValue, values: BusinessFormValues) => ReactNode;
}
export interface BusinessFormCustomField extends BusinessFormFieldBase {
type: 'custom';
render: (context: BusinessFormRenderContext) => ReactNode;
}
export type BusinessFormField =
| BusinessFormInputField
| BusinessFormNumberInputField
| BusinessFormTextareaField
| BusinessFormSelectField
| BusinessFormSwitchField
| BusinessFormUploadField
| BusinessFormDisplayTextField
| BusinessFormCustomField;
export type BusinessFormFieldType =
| 'input'
| 'numberInput'
| 'select'
| 'switch'
| 'textarea'
| 'upload'
| 'displayText'
| 'custom';
export interface BusinessFormProps {
fields: BusinessFormField[];
values: BusinessFormValues;
errors?: BusinessFormErrors;
disabled?: boolean;
labelAlign?: 'left' | 'top';
fieldWidth?: number | string;
className?: string;
'data-testid'?: string;
onChange: (nextValues: BusinessFormValues, changedKey: string | BusinessFormChangeKeyContext) => void;
onErrorsChange?: (nextErrors: BusinessFormErrors) => void;
onValidate?: (result: { valid: boolean; errors: BusinessFormErrors }) => void;
}
function resolveBoolean(
value: boolean | ((values: BusinessFormValues) => boolean) | undefined,
values: BusinessFormValues,
) {
if (typeof value === 'function') return value(values);
return Boolean(value);
}
function resolveVisible(
value: boolean | ((values: BusinessFormValues) => boolean) | undefined,
values: BusinessFormValues,
) {
if (typeof value === 'function') return value(values);
if (value === undefined) return true;
return Boolean(value);
}
function formatFieldWidth(fieldWidth: number | string | undefined) {
if (fieldWidth === undefined) return '360px';
return typeof fieldWidth === 'number' ? `${fieldWidth}` : fieldWidth;
}
function normalizeValue(value: BusinessFormValue) {
if (value === undefined || value === null) return '';
if (typeof value === 'string' || typeof value === 'number') return value;
if (typeof value === 'boolean') return value;
return value;
}
function stringifyValue(value: BusinessFormValue) {
if (value === undefined || value === null) return '';
if (typeof value === 'string' || typeof value === 'number') return String(value);
return '';
}
function inferUploadKind(value: BusinessFormValue): BusinessFormUploadKind | undefined {
if (!value) return undefined;
if (typeof value === 'object' && 'kind' in value && value.kind) return value.kind;
const url = typeof value === 'string' ? value : typeof value === 'object' && 'url' in value ? value.url : '';
const lowerUrl = url.toLowerCase();
if (/\.(png|jpe?g|webp|bmp|svg)$/.test(lowerUrl)) return 'image';
if (/\.gif$/.test(lowerUrl)) return 'gif';
if (/\.(mp4|mov|webm)$/.test(lowerUrl)) return 'video';
return 'file';
}
function resolveUploadValue(value: BusinessFormValue): BusinessFormUploadedFileValue | undefined {
if (!value) return undefined;
if (Array.isArray(value)) return undefined;
if (typeof value === 'string') {
return { url: value, kind: inferUploadKind(value) };
}
if (typeof value === 'object' && 'url' in value) {
return value as BusinessFormUploadedFileValue;
}
return undefined;
}
function resolveUploadValues(value: BusinessFormValue): BusinessFormUploadedFileValue[] {
if (!value) return [];
if (Array.isArray(value)) {
return value.filter((item): item is BusinessFormUploadedFileValue => {
return Boolean(item && typeof item === 'object' && 'url' in item);
});
}
const singleValue = resolveUploadValue(value);
return singleValue ? [singleValue] : [];
}
function resolveUploadType(field: BusinessFormUploadField): BusinessFormUploadType {
if (field.uploadType) return field.uploadType;
const kinds = field.kinds ?? [];
if (kinds.length === 0) return 'file';
return kinds.every((kind) => kind === 'image' || kind === 'gif' || kind === 'video') ? 'media' : 'file';
}
function resolveUploadKinds(field: BusinessFormUploadField): BusinessFormUploadKind[] {
if (field.kinds?.length) return field.kinds;
return resolveUploadType(field) === 'media'
? (['image', 'gif', 'video'] as BusinessFormUploadKind[])
: (['file'] as BusinessFormUploadKind[]);
}
function resolveUploadAccept(field: BusinessFormUploadField) {
if (field.accept !== undefined) return getAcceptText(field.accept);
return resolveUploadType(field) === 'media' ? 'image/*,video/*' : undefined;
}
function getUploadKind(uploaded?: BusinessFormUploadedFileValue) {
if (!uploaded) return undefined;
return uploaded.kind ?? inferUploadKind(uploaded);
}
function getUploadFileType(uploaded?: BusinessFormUploadedFileValue) {
const kind = getUploadKind(uploaded);
if (kind === 'video') return 'video';
if (kind === 'file') return 'file';
return 'image';
}
function isUploadKindAllowed(uploadedKind: BusinessFormUploadKind, allowedKinds: BusinessFormUploadKind[]) {
return allowedKinds.length === 0 || allowedKinds.includes(uploadedKind);
}
function normalizeUploadedValue(
file: File,
uploadedValue: string | BusinessFormUploadedFileValue,
actualKind: BusinessFormUploadKind,
) {
if (typeof uploadedValue === 'string') {
return {
url: uploadedValue,
name: file.name,
size: file.size,
mimeType: file.type,
kind: actualKind,
} satisfies BusinessFormUploadedFileValue;
}
return {
...uploadedValue,
name: uploadedValue.name ?? file.name,
size: uploadedValue.size ?? file.size,
mimeType: uploadedValue.mimeType ?? file.type,
kind: uploadedValue.kind ?? actualKind,
} satisfies BusinessFormUploadedFileValue;
}
function getFieldChangeContext(values: BusinessFormValues, field: BusinessFormField, value: BusinessFormValue) {
return {
values,
field,
key: field.key,
value,
};
}
function emitFormChange(
mutableValues: BusinessFormValues,
field: BusinessFormField,
nextValue: BusinessFormValue,
onChange: BusinessFormProps['onChange'],
) {
onChange(mutableValues, field.key);
onChange(mutableValues, { key: field.key, value: nextValue, values: mutableValues });
}
function replaceObjectContents(target: BusinessFormValues, source: BusinessFormValues) {
const snapshot = { ...source };
for (const key of Object.keys(target)) {
delete target[key];
}
Object.assign(target, snapshot);
}
function renderSwitchText(field: BusinessFormSwitchField, value: BusinessFormValue, compact = false) {
const checkedValue = field.checkedValue ?? true;
const uncheckedValue = field.uncheckedValue ?? false;
const isChecked = value === checkedValue || (checkedValue === true && value === true);
if (compact) {
return isChecked ? '开' : '关';
}
return isChecked ? (field.checkedLabel ?? '已开启') : (field.uncheckedLabel ?? '已关闭');
}
function normalizeAccept(accept?: string | string[]) {
if (accept === undefined) return undefined;
return Array.isArray(accept) ? accept : accept.split(',');
}
function getAcceptText(accept?: string | string[]) {
const normalized = normalizeAccept(accept);
return normalized?.join(',') ?? undefined;
}
function matchFileAccept(file: File, accept?: string | string[]) {
const normalized = normalizeAccept(accept);
if (!normalized || normalized.length === 0) return true;
const fileName = file.name.toLowerCase();
const mimeType = file.type.toLowerCase();
return normalized.some((item) => {
const lowered = item.toLowerCase().trim();
if (!lowered) return false;
if (lowered.startsWith('.')) return fileName.endsWith(lowered);
if (lowered.endsWith('/*')) {
const prefix = lowered.slice(0, -1);
return mimeType.startsWith(prefix);
}
return mimeType === lowered;
});
}
function inferUploadKindFromFile(file: File): BusinessFormUploadKind {
const name = file.name.toLowerCase();
const type = file.type.toLowerCase();
if (type.startsWith('image/') || /\.(png|jpe?g|webp|bmp|svg)$/.test(name)) return 'image';
if (type === 'image/gif' || /\.gif$/.test(name)) return 'gif';
if (type.startsWith('video/') || /\.(mp4|mov|webm)$/.test(name)) return 'video';
return 'file';
}
function formatUploadError(reason: 'invalid-kind' | 'invalid-accept' | 'invalid-size' | 'failed') {
if (reason === 'invalid-kind' || reason === 'invalid-accept') return '不支持当前文件格式';
if (reason === 'invalid-size') return '文件大小超过限制';
return '上传失败,请重试';
}
function resolveTextValue(value: BusinessFormValue) {
if (value === undefined || value === null) return '-';
if (typeof value === 'boolean') return value ? '是' : '否';
if (typeof value === 'object' && value && 'url' in value) {
return (value as BusinessFormUploadedFileValue).name ?? (value as BusinessFormUploadedFileValue).url;
}
return String(value);
}
function resolveUploadPreview(uploadedValues: BusinessFormUploadedFileValue[]) {
if (uploadedValues.length === 0) return null;
return uploadedValues.map((uploaded) => {
const kind = getUploadKind(uploaded);
if (kind === 'image' || kind === 'gif') {
return (
<div className={styles.uploadPreview} key={uploaded.url}>
<img className={styles.uploadImage} src={uploaded.url} alt={uploaded.name ?? uploaded.url} />
<span>{uploaded.name ?? uploaded.url}</span>
</div>
);
}
if (kind === 'video') {
return (
<div className={styles.uploadPreview} key={uploaded.url}>
<video
className={styles.uploadVideo}
src={uploaded.url}
aria-label={uploaded.name ?? uploaded.url}
muted
playsInline
preload="metadata"
/>
<span>{uploaded.name ?? uploaded.url}</span>
</div>
);
}
return (
<div className={styles.uploadPreview} key={uploaded.url}>
<span>{uploaded.name ?? uploaded.url}</span>
</div>
);
});
}
function buildUploadFiles(uploadedValues: BusinessFormUploadedFileValue[]): UploadFile[] {
return uploadedValues.map((uploaded) => ({
uid: uploaded.url,
name: uploaded.name ?? uploaded.url,
url: uploaded.url,
type: getUploadFileType(uploaded),
status: 'success',
}));
}
function resolveFieldWidthClass(fieldWidth: string) {
return fieldWidth;
}
function buildValidationMessage(field: BusinessFormField, value: BusinessFormValue, values: BusinessFormValues) {
if (!resolveVisible(field.visible, values) || resolveBoolean(field.readonly, values) || field.type === 'displayText') {
return undefined;
}
if (field.required) {
const empty =
value === undefined ||
value === null ||
value === '' ||
(Array.isArray(value) && value.length === 0);
if (empty) return '请输入必填项';
}
if (field.type === 'input' || field.type === 'textarea') {
const text = stringifyValue(value);
if (field.maxLength !== undefined && text.length > field.maxLength) {
return `最多 ${field.maxLength} 个字符`;
}
}
if (field.type === 'numberInput' && typeof value === 'number') {
if (field.min !== undefined && value < field.min) return `不能低于 ${field.min}`;
if (field.max !== undefined && value > field.max) return `不能高于 ${field.max}`;
if (field.precision !== undefined) {
const [, decimals = ''] = String(value).split('.');
if (decimals.length > field.precision) return `最多保留 ${field.precision} 位小数`;
}
}
return undefined;
}
async function runBusinessFormValidation(fields: BusinessFormField[], values: BusinessFormValues) {
const errors: BusinessFormErrors = {};
for (const field of fields) {
const value = values[field.key];
const builtInError = buildValidationMessage(field, value, values);
if (builtInError) {
errors[field.key] = builtInError;
continue;
}
if (field.type === 'displayText' || !resolveVisible(field.visible, values) || resolveBoolean(field.readonly, values)) {
continue;
}
if (field.validator) {
const customError = await field.validator(value, { values, field });
if (customError) {
errors[field.key] = customError;
}
}
}
return errors;
}
export function BusinessForm({
className,
disabled: globalDisabled = false,
errors,
fieldWidth,
fields,
values,
'data-testid': dataTestId = 'business-form',
onChange,
}: BusinessFormProps) {
const [localErrors, setLocalErrors] = useState<BusinessFormErrors>({});
const [draftValues, setDraftValues] = useState<BusinessFormValues>({ ...values });
const draftValuesRef = useRef<BusinessFormValues>({ ...values });
const changeValuesRef = useRef<BusinessFormValues>({ ...values });
const resolvedWidth = formatFieldWidth(fieldWidth);
const currentValues = draftValues;
const mergedErrors = useMemo(
() => ({ ...localErrors, ...(errors ?? {}) }),
[errors, localErrors],
);
useEffect(() => {
replaceObjectContents(draftValuesRef.current, values);
replaceObjectContents(changeValuesRef.current, values);
setDraftValues({ ...values });
}, [values]);
const applyFieldChange = (field: BusinessFormField, nextValue: BusinessFormValue) => {
const nextValues = { ...currentValues, [field.key]: nextValue };
const patch = field.onChange?.(nextValue, getFieldChangeContext(currentValues, field, nextValue)) ?? {};
const mergedValues = { ...nextValues, ...patch };
replaceObjectContents(changeValuesRef.current, mergedValues);
replaceObjectContents(draftValuesRef.current, mergedValues);
setDraftValues({ ...mergedValues });
emitFormChange(changeValuesRef.current, field, nextValue, onChange);
return mergedValues;
};
return (
<div className={classNames(styles.root, className)} data-testid={dataTestId}>
{fields.map((field) => {
const visible = resolveVisible(field.visible, currentValues);
if (!visible) return null;
const disabled = globalDisabled || resolveBoolean(field.disabled, currentValues);
const readonly = resolveBoolean(field.readonly, currentValues);
const value = currentValues[field.key];
const error = mergedErrors[field.key];
const fieldWidthClass = resolveFieldWidthClass(resolvedWidth);
const controlId = `business-form-control-${field.key}`;
const labelId = `${controlId}-label`;
const fieldState = {
disabled,
readonly,
value,
error,
setFieldError: (message?: string) => setLocalErrors((current) => ({ ...current, [field.key]: message })),
setValue: (nextValue: BusinessFormValue) => applyFieldChange(field, nextValue),
setValues: (nextValues: BusinessFormValues, changedKey = field.key) => {
replaceObjectContents(changeValuesRef.current, nextValues);
replaceObjectContents(draftValuesRef.current, nextValues);
setDraftValues({ ...nextValues });
onChange(nextValues, changedKey);
},
};
const uploadedValues = resolveUploadValues(value);
return (
<div
key={field.key}
className={classNames(styles.field, field.className)}
data-testid={`business-form-field-${field.key}`}
data-width={fieldWidthClass}
>
<label
className={styles.label}
htmlFor={field.type === 'input' || field.type === 'numberInput' || field.type === 'textarea' ? controlId : undefined}
id={labelId}
>
{field.required ? <span className={styles.required}>*</span> : null}
<span>{field.label}</span>
</label>
<div className={styles.controlWrap}>
<div className={styles.controlHolder}>
{field.type === 'displayText' ? (
<span className={styles.readonlyValue}>
{field.render?.(value, currentValues) ?? resolveTextValue(value)}
</span>
) : null}
{field.type === 'custom' ? (
field.render({
values: currentValues,
value,
error,
disabled,
readonly,
setValue: fieldState.setValue,
setValues: fieldState.setValues,
})
) : null}
{field.type === 'input' ? (
<Input
id={controlId}
aria-label={field.label}
clearable={field.allowClear}
disabled={disabled}
maxlength={field.maxLength}
allowInputOverMax={field.allowInputOverMax}
placeholder={field.placeholder ?? `请输入${field.label}`}
readOnly={readonly}
showLimitNumber={field.maxLength !== undefined}
type="text"
value={stringifyValue(normalizeValue(value))}
onChange={(nextValue) => {
applyFieldChange(field, String(nextValue ?? ''));
}}
/>
) : null}
{field.type === 'numberInput' ? (
<InputNumber
disabled={disabled}
max={field.max}
min={field.min}
placeholder={field.placeholder ?? `请输入${field.label}`}
readOnly={readonly}
decimalPlaces={field.precision}
value={value === undefined || value === null ? '' : (value as string | number)}
onChange={(nextValue) => {
applyFieldChange(field, nextValue === '' ? undefined : (nextValue as BusinessFormValue));
}}
/>
) : null}
{field.type === 'select' ? (
<Select
id={controlId}
aria-label={field.label}
clearable={field.allowClear}
disabled={disabled}
multiple={field.multiple}
options={field.options}
placeholder={field.placeholder ?? `请选择${field.label}`}
readOnly={readonly}
value={field.multiple ? (Array.isArray(value) ? value : []) : value ?? ''}
onChange={(nextValue) => {
applyFieldChange(field, nextValue as BusinessFormValue);
}}
/>
) : null}
{field.type === 'switch' ? (
readonly ? (
<span className={styles.readonlyValue}>{renderSwitchText(field, value)}</span>
) : (
<Switch
aria-label={field.label}
disabled={disabled}
value={value === (field.checkedValue ?? true) || (field.checkedValue === true ? value === true : false)}
onChange={(nextValue) => {
const checkedValue = field.checkedValue ?? true;
const uncheckedValue = field.uncheckedValue ?? false;
applyFieldChange(field, nextValue ? checkedValue : uncheckedValue);
}}
/>
)
) : null}
{field.type === 'textarea' ? (
<Textarea
id={controlId}
aria-label={field.label}
disabled={disabled}
maxlength={field.maxLength}
allowInputOverMax={field.allowInputOverMax}
readOnly={readonly}
rows={field.rows ?? 4}
count={field.maxLength !== undefined}
value={stringifyValue(value)}
onChange={(nextValue) => {
applyFieldChange(field, String(nextValue ?? ''));
}}
/>
) : null}
{field.type === 'upload' ? (
readonly ? (
<span className={styles.readonlyValue}>{resolveUploadPreview(uploadedValues) ?? field.placeholder ?? '未上传'}</span>
) : (
<div className={styles.uploadWrap}>
{(() => {
const uploadType = resolveUploadType(field);
const uploadKinds = resolveUploadKinds(field);
const uploadAccept = resolveUploadAccept(field);
const uploadTheme = uploadType === 'media' ? 'image' : 'file-flow';
const maxCount = Math.max(1, field.maxCount ?? 1);
const isMultipleUpload = Boolean(field.multiple);
const uploadActionText =
uploadType === 'media' ? field.placeholder ?? '点击上传' : field.actionText ?? '选择文件';
const handleUpload = async (file: File) => {
if (maxCount > 1 && uploadedValues.length >= maxCount) return;
const actualKind = inferUploadKindFromFile(file);
if (!isUploadKindAllowed(actualKind, uploadKinds)) {
fieldState.setFieldError(formatUploadError('invalid-kind'));
return;
}
if (!matchFileAccept(file, field.accept)) {
fieldState.setFieldError(formatUploadError('invalid-accept'));
return;
}
if (field.maxSize !== undefined && file.size > field.maxSize) {
fieldState.setFieldError(formatUploadError('invalid-size'));
return;
}
try {
const uploadedValue = await field.upload(file, currentValues);
const normalizedValue = normalizeUploadedValue(file, uploadedValue, actualKind);
const nextUploadValues = [...uploadedValues, normalizedValue].slice(0, maxCount);
fieldState.setFieldError(undefined);
fieldState.setValue(maxCount > 1 ? nextUploadValues : normalizedValue);
} catch {
fieldState.setFieldError(formatUploadError('failed'));
}
};
const uploadFiles = buildUploadFiles(uploadedValues);
const isMediaVideo = uploadType === 'media' && uploadedValues.some((uploaded) => getUploadKind(uploaded) === 'video');
const handlePreview: TdUploadProps['onPreview'] = ({ file, e }) => {
e.stopPropagation();
if (file.type === 'video' && file.url) {
window.open(file.url, '_blank', 'noopener,noreferrer');
}
};
const videoFileListDisplay: TdUploadProps['fileListDisplay'] = (context) => {
const { files: displayFiles, onPreview, onRemove } = context as typeof context & {
onPreview?: TdUploadProps['onPreview'];
onRemove?: TdUploadProps['onRemove'];
};
return (
<ul className="t-upload__card">
{displayFiles.map((file, index) => (
<li className="t-upload__card-item t-is-background" key={file.uid || file.name}>
<div className="t-upload__card-content t-upload__card-box">
{file.type === 'video' ? (
<video
className={styles.uploadVideoCard}
src={file.url}
aria-label={file.name}
muted
playsInline
preload="metadata"
/>
) : (
<img className={styles.uploadVideoCard} src={file.url} alt={file.name} />
)}
<div className="t-upload__card-mask">
<div
className="t-upload__card-mask-item"
onClick={(event) => {
event.stopPropagation();
onPreview?.({
file,
index,
e: event as unknown as Parameters<NonNullable<TdUploadProps['onPreview']>>[0]['e'],
});
}}
>
<BrowseIcon />
</div>
{!disabled ? (
<>
<span className="t-upload__card-mask-item-divider" />
<div
className="t-upload__card-mask-item"
onClick={(event) => {
event.stopPropagation();
onRemove?.({ file, index, e: event });
}}
>
<DeleteIcon />
</div>
</>
) : null}
</div>
</div>
{file.name ? (
file.url ? (
<a className="t-upload__card-name" href={file.url} target="_blank" rel="noreferrer">
{file.name}
</a>
) : (
<span className="t-upload__card-name">{file.name}</span>
)
) : null}
</li>
))}
</ul>
);
};
return (
<Upload
accept={uploadAccept}
autoUpload={false}
disabled={disabled}
trigger={
uploadType === 'media' ? undefined : (
<Button aria-labelledby={labelId} disabled={disabled} variant="outline">
{uploadActionText}
</Button>
)
}
fileListDisplay={isMediaVideo ? videoFileListDisplay : undefined}
files={uploadFiles}
locale={{ triggerUploadText: { image: uploadActionText } }}
max={maxCount}
multiple={isMultipleUpload}
showImageFileName
theme={uploadTheme}
tips={uploadType === 'media' ? undefined : uploadActionText}
onChange={async (_, context) => {
if (context.trigger !== 'add' || !context.file?.raw) return;
await handleUpload(context.file.raw);
}}
onRemove={({ file }) => {
if (!file) return;
const nextUploadValues = uploadedValues.filter((uploaded) => uploaded.url !== file.url);
fieldState.setFieldError(undefined);
fieldState.setValue(maxCount > 1 ? nextUploadValues : undefined);
}}
onPreview={uploadType === 'media' ? handlePreview : undefined}
/>
);
})()}
</div>
)
) : null}
</div>
{field.helperText ?? field.helpText ? (
<div className={styles.helpText}>{field.helperText ?? field.helpText}</div>
) : null}
{error ? (
<div className={styles.error} role="alert">
{error}
</div>
) : null}
</div>
</div>
);
})}
</div>
);
}
export async function validateBusinessForm(fields: BusinessFormField[] = [], values: BusinessFormValues = {}) {
return runBusinessFormValidation(fields, values);
}
.root {
display: grid;
gap: var(--gl-spacing-md);
}
.table :global(.t-table__header tr),
.table :global(.t-table__header th),
.table :global(.t-table__header td) {
background-color: var(--gl-color-bg-page);
}
.table :global(.t-table__body tr),
.table :global(.t-table__body th),
.table :global(.t-table__body td) {
background-color: var(--gl-color-bg-container);
}
.emptyState {
display: grid;
min-height: 320px;
place-items: center;
padding: var(--gl-spacing-2xl) 0;
}
.emptyState :global(.t-empty__description) {
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-md);
}
.stateIcon {
color: var(--gl-color-text-placeholder);
}
.businessTableLoading {
color: var(--gl-color-primary);
}
.businessTableLoading:global(.t-loading__overlay) {
background-color: rgba(255, 255, 255, 0.64);
backdrop-filter: blur(1px);
}
.businessTableLoading :global(.t-loading__text) {
color: var(--gl-color-primary);
font-size: var(--gl-font-size-sm);
}
.businessTableLoading :global(.t-loading__gradient),
.businessTableLoading :global(.t-loading__gradient-conic),
.businessTableLoading :global(.t-icon-loading) {
color: var(--gl-color-primary);
}
.footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--gl-spacing-md);
flex-wrap: wrap;
}
.totalLabel {
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-sm);
}
.pagination {
margin-left: auto;
}
import type { ReactElement, ReactNode } from 'react';
import { CloseCircleIcon, SearchIcon } from 'tdesign-icons-react';
import { Button, Empty, Pagination, Table, type EmptyProps, type PaginationProps, type PrimaryTableCol, type TableProps, type TableRowData } from 'tdesign-react';
import { classNames } from '../shared/classNames';
import styles from './BusinessTable.module.css';
export type BusinessTableColumn<T extends TableRowData> = PrimaryTableCol<T>;
export interface BusinessTableEmptyStateConfig {
onAction?: () => void;
}
export interface BusinessTableErrorStateConfig {
kind?: 'offline' | 'forbidden';
onRetry?: () => void;
}
export interface BusinessTableProps<T extends TableRowData>
extends Omit<TableProps<T>, 'columns' | 'data' | 'rowKey' | 'empty' | 'pagination'> {
columns: BusinessTableColumn<T>[];
data: T[];
rowKey: TableProps<T>['rowKey'];
hasFilter?: boolean;
error?: boolean;
filteredEmptyState?: BusinessTableEmptyStateConfig;
errorState?: BusinessTableErrorStateConfig;
pagination?: PaginationProps | false;
totalLabel?: ReactNode;
tableClassName?: string;
}
function createActionButton(
label: ReactNode,
onClick?: () => void,
variant: 'base' | 'text' = 'base',
) : ReactElement | undefined {
if (!onClick || !label) return undefined;
return (
<Button theme="primary" variant={variant} onClick={onClick}>
{label}
</Button>
);
}
function createEmptyNode({
action,
description,
image,
title,
type,
}: {
action?: ReactElement;
description?: ReactNode;
image?: ReactNode;
title: ReactNode;
type?: EmptyProps['type'];
}) {
return (
<div className={styles.emptyState}>
<Empty
action={action}
description={description}
image={image}
title={title}
type={type ?? 'empty'}
/>
</div>
);
}
const stateIconProps = {
className: styles.stateIcon,
size: '64px',
strokeWidth: 2,
};
const defaultLoadingProps = {
className: styles.businessTableLoading,
delay: 120,
showOverlay: true,
size: '20px',
text: '加载中',
} satisfies TableProps<TableRowData>['loadingProps'];
const errorStatePresets: Record<NonNullable<BusinessTableErrorStateConfig['kind']>, {
actionText?: string;
description?: string;
icon?: ReactElement;
title: string;
type?: EmptyProps['type'];
}> = {
offline: {
title: '请求失败',
type: 'fail',
},
forbidden: {
actionText: '申请权限',
description: '当前账号暂无访问权限',
icon: <CloseCircleIcon {...stateIconProps} />,
title: '权限受限',
},
};
export function BusinessTable<T extends TableRowData>({
columns,
data,
error = false,
errorState,
filteredEmptyState,
hasFilter = false,
loadingProps,
pagination,
rowKey,
tableClassName,
totalLabel,
...tableProps
}: BusinessTableProps<T>) {
if (error) {
const errorPreset = errorStatePresets[errorState?.kind ?? 'offline'];
return (
<div className={styles.root}>
{createEmptyNode({
action: createActionButton(errorPreset.actionText, errorState?.onRetry, 'base'),
description: errorPreset.description,
image: errorPreset.icon,
title: errorPreset.title,
type: errorPreset.type,
})}
</div>
);
}
const isEmpty = data.length === 0;
const isLoading = Boolean(tableProps.loading);
const mergedLoadingProps = isLoading
? {
...defaultLoadingProps,
...loadingProps,
className: classNames(defaultLoadingProps.className, loadingProps?.className),
}
: loadingProps;
const emptyNode = isEmpty
&& !isLoading
? hasFilter
? createEmptyNode({
image: <SearchIcon {...stateIconProps} />,
title: '未找到匹配结果',
})
: createEmptyNode({
title: '暂无数据',
type: 'empty',
})
: undefined;
return (
<div className={classNames(styles.root, tableProps.className)}>
<Table
{...tableProps}
className={classNames(styles.table, tableClassName)}
columns={columns}
data={data}
empty={emptyNode}
loadingProps={mergedLoadingProps}
rowKey={rowKey}
/>
{pagination || totalLabel ? (
<div className={styles.footer}>
{!pagination && totalLabel ? <div className={styles.totalLabel}>{totalLabel}</div> : <span />}
{pagination ? <Pagination className={styles.pagination} {...pagination} /> : null}
</div>
) : null}
</div>
);
}
export type { BusinessLoginPageErrors, BusinessLoginPageProps } from './login/BusinessLoginPage';
export { BusinessLoginPage } from './login/BusinessLoginPage';
export type {
BusinessFormCustomField,
BusinessFormDisplayTextField,
BusinessFormErrors,
BusinessFormField,
BusinessFormFieldChangeContext,
BusinessFormChangeKeyContext,
BusinessFormFieldOnChange,
BusinessFormFieldType,
BusinessFormInputField,
BusinessFormNumberInputField,
BusinessFormProps,
BusinessFormRenderContext,
BusinessFormSelectField,
BusinessFormSelectOption,
BusinessFormSwitchField,
BusinessFormTextareaField,
BusinessFormUploadField,
BusinessFormUploadType,
BusinessFormUploadKind,
BusinessFormUploadedFileValue,
BusinessFormValidationContext,
BusinessFormValidator,
BusinessFormValue,
BusinessFormValues,
} from './business-form/BusinessForm';
export { BusinessForm, validateBusinessForm } from './business-form/BusinessForm';
export type { MediaWallItem, MediaWallProps } from './media-wall/MediaWall';
export { MediaWall } from './media-wall/MediaWall';
export type {
BusinessTableColumn,
BusinessTableEmptyStateConfig,
BusinessTableErrorStateConfig,
BusinessTableProps,
} from './business-table/BusinessTable';
export { BusinessTable } from './business-table/BusinessTable';
export type {
SearchFilterDateField,
SearchFilterField,
SearchFilterInputField,
SearchFilterNumberInputField,
SearchFilterProps,
SearchFilterSelectField,
SearchFilterSelectOption,
SearchFilterValue,
SearchFilterValues,
} from './search-filter/SearchFilter';
export { SearchFilter } from './search-filter/SearchFilter';
export type {
BusinessAdminShellBreadcrumbItem,
BusinessAdminShellMenuItem,
BusinessAdminShellProps,
BusinessAdminShellUser,
} from './shell/BusinessAdminShell';
export { BusinessAdminShell } from './shell/BusinessAdminShell';
export type { StatePlaceholderProps } from './state-placeholder/StatePlaceholder';
export { StatePlaceholder } from './state-placeholder/StatePlaceholder';
import { type FormEvent, type ReactNode, useState } from 'react';
import { Button, Input } from 'tdesign-react';
import { BrowseIcon, BrowseOffIcon, LockOnIcon, UserIcon } from 'tdesign-icons-react';
export interface BusinessLoginPageErrors {
username?: string;
password?: string;
form?: string;
}
export interface BusinessLoginPageProps {
title: string;
description: string;
username: string;
password: string;
backgroundColor: string;
backgroundImage: string;
onUsernameChange: (value: string) => void;
onPasswordChange: (value: string) => void;
onSubmit: (event: FormEvent<HTMLFormElement>) => void;
errors?: BusinessLoginPageErrors;
submitText?: string;
loading?: boolean;
backgroundSize?: string;
footer?: ReactNode;
}
export function BusinessLoginPage({
title,
description,
username,
password,
backgroundColor,
backgroundImage,
onUsernameChange,
onPasswordChange,
onSubmit,
errors = {},
submitText = '登录',
loading = false,
backgroundSize = 'min(1180px, 92vw) auto',
footer,
}: BusinessLoginPageProps) {
const [passwordVisible, setPasswordVisible] = useState(false);
return (
<main
className="grid min-h-screen place-items-center px-8 py-10"
style={{
backgroundColor,
backgroundImage: `url("${backgroundImage}")`,
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
backgroundSize,
}}
>
<section className="grid min-h-[350px] w-full max-w-[460px] gap-7 rounded-lg border border-[#d8e4f7] bg-white/95 p-8 shadow-[0_24px_64px_rgb(29_70_132_/_16%)] backdrop-blur">
<div className="grid gap-2 text-center">
<h1 className="m-0 text-[28px] font-bold leading-9 text-[var(--gl-color-text-primary)]">{title}</h1>
<p className="m-0 text-sm font-normal leading-[var(--gl-line-height-md)] text-[var(--gl-color-text-secondary)]">
{description}
</p>
</div>
<form className="grid gap-4" onSubmit={onSubmit}>
<div className="grid gap-1">
<Input
name="username"
placeholder="请输入账号"
prefixIcon={<UserIcon />}
status={errors.username ? 'error' : 'default'}
value={username}
onChange={(value) => onUsernameChange(String(value))}
/>
{errors.username ? <span className="m-0 text-xs text-[#d92d20]">{errors.username}</span> : null}
</div>
<div className="grid gap-1">
<Input
name="password"
placeholder="请输入密码"
prefixIcon={<LockOnIcon />}
status={errors.password ? 'error' : 'default'}
suffixIcon={
<button
aria-label={passwordVisible ? '隐藏密码' : '显示密码'}
className="grid h-5 w-5 place-items-center border-0 bg-transparent p-0 text-[#6b7a90] hover:text-[var(--gl-color-primary)]"
type="button"
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setPasswordVisible((visible) => !visible);
}}
>
{passwordVisible ? <BrowseIcon /> : <BrowseOffIcon />}
</button>
}
type={passwordVisible ? 'text' : 'password'}
value={password}
onChange={(value) => onPasswordChange(String(value))}
/>
{errors.password ? <span className="m-0 text-xs text-[#d92d20]">{errors.password}</span> : null}
</div>
{errors.form ? <p className="m-0 text-xs text-[#d92d20]">{errors.form}</p> : null}
<Button block loading={loading} theme="primary" type="submit">
{submitText}
</Button>
{footer}
</form>
</section>
</main>
);
}
.root {
display: grid;
gap: var(--gl-spacing-sm);
}
.video {
width: 100%;
height: 100%;
background: #000;
object-fit: cover;
}
import type { CSSProperties } from 'react';
import { BrowseIcon, DeleteIcon } from 'tdesign-icons-react';
import { Button, Upload } from 'tdesign-react';
import type { UploadFile, TdUploadProps } from 'tdesign-react';
import { classNames } from '../shared/classNames';
import styles from './MediaWall.module.css';
export interface MediaWallItem {
id: string;
type: 'image' | 'video';
src: string;
alt: string;
}
export interface MediaWallProps {
items: MediaWallItem[];
helperText?: string;
accept?: string;
multiple?: boolean;
disabled?: boolean;
maxCount?: number;
className?: string;
style?: CSSProperties;
onPreview?: (item: MediaWallItem) => void;
onRemove?: (item: MediaWallItem) => void;
onSelectFiles?: (files: File[]) => void;
}
function fromUploadFile(file: UploadFile): MediaWallItem {
return {
id: file.uid || String(file.name),
type: file.type === 'video' ? 'video' : 'image',
src: file.url || '',
alt: file.name || '',
};
}
export function MediaWall({
accept = 'image/*,video/*',
className,
disabled = false,
helperText,
items,
maxCount,
multiple = true,
onPreview,
onRemove,
onSelectFiles,
style,
}: MediaWallProps) {
const files: UploadFile[] = items.map((item) => ({
uid: item.id,
name: item.alt,
url: item.src,
status: 'success',
type: item.type,
}));
const itemById = new Map(items.map((item) => [item.id, item]));
const hasVideo = items.some((item) => item.type === 'video');
const handlePreview: TdUploadProps['onPreview'] = ({ file, e }) => {
e.stopPropagation();
onPreview?.(itemById.get(file.uid || '') ?? fromUploadFile(file));
};
const handleRemove: TdUploadProps['onRemove'] = ({ file, e }) => {
e.stopPropagation();
if (!file) return;
onRemove?.(itemById.get(file.uid || '') ?? fromUploadFile(file));
};
const fileListDisplay: TdUploadProps['fileListDisplay'] = ({ files: displayFiles }) => (
<div className="t-upload__card-container">
{displayFiles.map((file) => {
const item = itemById.get(file.uid || '') ?? fromUploadFile(file);
return (
<div className="t-upload__card-item" key={item.id}>
{item.type === 'video'
? <video className={styles.video} src={item.src} aria-label={item.alt || '视频预览'} muted playsInline preload="metadata" />
: <img src={item.src} alt={item.alt} />}
<div className="t-upload__card-mask">
<Button
aria-label="预览"
className="t-upload__card-mask-item"
disabled={disabled}
icon={<BrowseIcon />}
shape="square"
variant="text"
onClick={(event) => {
event.stopPropagation();
onPreview?.(item);
}}
/>
<Button
aria-label="删除"
className="t-upload__card-mask-item"
disabled={disabled}
icon={<DeleteIcon />}
shape="square"
variant="text"
onClick={(event) => {
event.stopPropagation();
onRemove?.(item);
}}
/>
</div>
</div>
);
})}
</div>
);
return (
<div className={classNames(styles.root, className)} style={style} onClick={(event) => event.stopPropagation()}>
<Upload
accept={accept}
autoUpload={false}
disabled={disabled}
files={files}
fileListDisplay={hasVideo ? fileListDisplay : undefined}
max={maxCount}
multiple={multiple}
theme="image"
tips={helperText}
onChange={(_, context) => {
if (context.trigger === 'add' && context.file?.raw) onSelectFiles?.([context.file.raw]);
}}
onPreview={hasVideo || onPreview ? handlePreview : undefined}
onRemove={handleRemove}
/>
</div>
);
}
.root {
display: grid;
gap: var(--gl-spacing-md);
}
.viewport {
overflow: hidden;
transition: max-height 240ms ease;
}
.fields {
display: flex;
flex-wrap: wrap;
gap: var(--gl-spacing-md) var(--gl-spacing-lg);
align-items: flex-start;
}
.item {
display: flex;
width: var(--gl-search-item-width, 284px);
min-width: 0;
align-items: center;
gap: var(--gl-spacing-sm);
}
.itemWide {
width: var(--gl-search-item-wide-width, 484px);
}
.label {
flex: 0 0 var(--gl-search-label-width, 72px);
overflow: hidden;
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-sm);
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
}
.control {
width: var(--gl-search-control-width, 200px);
min-width: 0;
}
.inputLabel {
display: block;
width: var(--gl-search-control-width, 200px);
min-width: 0;
}
.visuallyHidden {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.controlWide {
width: var(--gl-search-control-wide-width, 400px);
}
.footer {
display: flex;
align-items: center;
justify-content: flex-end;
gap: var(--gl-spacing-sm);
}
.toggleButton {
display: inline-flex;
align-items: center;
gap: var(--gl-spacing-xs);
}
.toggleIcon {
transition: transform 240ms ease;
}
.toggleIconExpanded {
transform: rotate(180deg);
}
.actionButton {
min-width: 88px;
}
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { Button, DatePicker, DateRangePicker, Input, Select } from 'tdesign-react';
import { ChevronDownIcon, RefreshIcon, SearchIcon } from 'tdesign-icons-react';
import { classNames } from '../shared/classNames';
import styles from './SearchFilter.module.css';
export type SearchFilterValue = string | [string, string] | undefined;
export type SearchFilterValues = Record<string, SearchFilterValue>;
interface SearchFilterFieldBase {
key: string;
label: string;
disabled?: boolean;
}
export interface SearchFilterInputField extends SearchFilterFieldBase {
type: 'input';
value?: string;
defaultValue?: string;
placeholder?: string;
allowClear?: boolean;
onChange?: (value: string) => void;
}
export interface SearchFilterNumberInputField extends SearchFilterFieldBase {
type: 'numberInput';
value?: string;
defaultValue?: string;
placeholder?: string;
allowClear?: boolean;
onChange?: (value: string) => void;
}
export interface SearchFilterSelectOption {
label: ReactNode;
value: string;
disabled?: boolean;
}
export interface SearchFilterSelectField extends SearchFilterFieldBase {
type: 'select';
options: SearchFilterSelectOption[];
value?: string;
defaultValue?: string;
placeholder?: string;
allowClear?: boolean;
onChange?: (value: string) => void;
}
export interface SearchFilterDateField extends SearchFilterFieldBase {
type: 'datePicker';
range?: boolean;
value?: string | [string, string];
defaultValue?: string | [string, string];
placeholder?: string;
disabledDate?: (date: string) => boolean;
onChange?: (value: string | [string, string]) => void;
}
export type SearchFilterField =
| SearchFilterInputField
| SearchFilterNumberInputField
| SearchFilterSelectField
| SearchFilterDateField;
export interface SearchFilterProps {
fields: SearchFilterField[];
className?: string;
'data-testid'?: string;
onSearch?: (values: SearchFilterValues) => void;
onReset?: () => void;
}
function sanitizeDigits(value: string | undefined) {
return (value ?? '').replace(/\D/g, '');
}
function isControlledField(field: SearchFilterField) {
return Object.prototype.hasOwnProperty.call(field, 'value');
}
function defaultValueForField(field: SearchFilterField): SearchFilterValue {
if (field.type === 'datePicker') return field.defaultValue;
if (field.type === 'numberInput') return sanitizeDigits(field.defaultValue);
return field.defaultValue ?? '';
}
function normalizeFieldValue(field: SearchFilterField, value: SearchFilterValue): SearchFilterValue {
if (field.type === 'datePicker') return value;
if (field.type === 'numberInput') return sanitizeDigits(typeof value === 'string' ? value : undefined);
return typeof value === 'string' ? value : '';
}
function buildInitialValues(fields: SearchFilterField[]) {
return fields.reduce<SearchFilterValues>((values, field) => {
values[field.key] = defaultValueForField(field);
return values;
}, {});
}
function SearchFieldControl({
field,
value,
onChange,
onEnter,
}: {
field: SearchFilterField;
value: SearchFilterValue;
onChange: (value: SearchFilterValue) => void;
onEnter: () => void;
}) {
if (field.type === 'select') {
const options = field.options.some((option) => option.value === '')
? field.options
: [{ label: '全部', value: '' }, ...field.options];
return (
<label className={styles.inputLabel}>
<span className={styles.visuallyHidden}>{field.label}</span>
<Select
className={styles.control}
clearable={field.allowClear}
disabled={field.disabled}
options={options}
placeholder={field.placeholder ?? '请选择'}
value={typeof value === 'string' ? value : ''}
onChange={(nextValue) => onChange(typeof nextValue === 'string' ? nextValue : '')}
/>
</label>
);
}
if (field.type === 'datePicker') {
if (field.range || Array.isArray(value)) {
return (
<DateRangePicker
className={styles.controlWide}
disabled={field.disabled}
disableDate={field.disabledDate as never}
placeholder={field.placeholder ?? '请选择日期范围'}
rangeInputProps={{ inputProps: { 'aria-label': field.label } } as never}
value={Array.isArray(value) ? value : []}
onChange={(nextValue) => onChange(nextValue.map(String) as [string, string])}
/>
);
}
return (
<DatePicker
className={styles.control}
disabled={field.disabled}
disableDate={field.disabledDate as never}
inputProps={{ 'aria-label': field.label } as never}
placeholder={field.placeholder ?? '请选择日期'}
value={typeof value === 'string' ? value : undefined}
onChange={(nextValue) => onChange(String(nextValue))}
/>
);
}
const isNumberInput = field.type === 'numberInput';
return (
<label className={styles.inputLabel}>
<span className={styles.visuallyHidden}>{field.label}</span>
<Input
className={styles.control}
clearable={field.allowClear}
disabled={field.disabled}
placeholder={field.placeholder ?? (isNumberInput ? '请输入数字' : `搜索${field.label}`)}
value={typeof value === 'string' ? value : ''}
onChange={(nextValue) => {
const normalized = String(nextValue);
onChange(isNumberInput ? sanitizeDigits(normalized) : normalized);
}}
onEnter={onEnter}
/>
</label>
);
}
export function SearchFilter({ fields, className, 'data-testid': dataTestId, onReset, onSearch }: SearchFilterProps) {
const [innerValues, setInnerValues] = useState<SearchFilterValues>(() => buildInitialValues(fields));
const [expanded, setExpanded] = useState(false);
const viewportRef = useRef<HTMLDivElement>(null);
const [viewportHeight, setViewportHeight] = useState(44);
const [collapsedHeight, setCollapsedHeight] = useState(44);
const fieldSignature = useMemo(
() => fields.map((field) => `${field.key}:${field.type}:${field.type === 'datePicker' && field.range ? 'range' : 'single'}`).join('|'),
[fields],
);
useEffect(() => {
setInnerValues((current) => {
const next = { ...current };
fields.forEach((field) => {
if (!(field.key in next)) next[field.key] = defaultValueForField(field);
});
Object.keys(next).forEach((key) => {
if (!fields.some((field) => field.key === key)) delete next[key];
});
return next;
});
}, [fieldSignature]);
useLayoutEffect(() => {
const updateHeight = () => {
const viewport = viewportRef.current;
if (!viewport) return;
const firstItem = viewport.querySelector('[data-field-key]') as HTMLElement | null;
setCollapsedHeight(Math.max(firstItem?.getBoundingClientRect().height ?? 44, 44));
setViewportHeight(viewport.scrollHeight);
};
updateHeight();
window.addEventListener('resize', updateHeight);
return () => window.removeEventListener('resize', updateHeight);
}, [expanded, fieldSignature]);
const values = fields.reduce<SearchFilterValues>((current, field) => {
current[field.key] = isControlledField(field) ? normalizeFieldValue(field, field.value) : innerValues[field.key];
return current;
}, {});
const handleSearch = () => onSearch?.(values);
const updateFieldValue = (field: SearchFilterField, value: SearchFilterValue) => {
const normalized = normalizeFieldValue(field, value);
if (!isControlledField(field)) {
setInnerValues((current) => ({ ...current, [field.key]: normalized }));
}
field.onChange?.(normalized as never);
};
const handleReset = () => {
const nextValues = buildInitialValues(fields);
setInnerValues(nextValues);
fields.forEach((field) => field.onChange?.(nextValues[field.key] as never));
onReset?.();
};
const showToggle = fields.reduce((count, field) => count + (field.type === 'datePicker' && field.range ? 2 : 1), 0) > 3;
return (
<div className={classNames(styles.root, className)} data-testid={dataTestId}>
<div ref={viewportRef} className={styles.viewport} style={{ maxHeight: expanded ? viewportHeight : collapsedHeight }}>
<div className={styles.fields}>
{fields.map((field) => {
const isWide = field.type === 'datePicker' && field.range;
return (
<div key={field.key} className={classNames(styles.item, isWide && styles.itemWide)} data-field-key={field.key}>
<span className={styles.label} title={field.label}>{field.label}</span>
<SearchFieldControl
field={field}
value={values[field.key]}
onChange={(value) => updateFieldValue(field, value)}
onEnter={handleSearch}
/>
</div>
);
})}
</div>
</div>
<div className={styles.footer}>
{showToggle ? (
<Button className={styles.toggleButton} variant="text" onClick={() => setExpanded((value) => !value)}>
{expanded ? '收起' : '展开'}
<ChevronDownIcon className={classNames(styles.toggleIcon, expanded && styles.toggleIconExpanded)} />
</Button>
) : null}
<Button className={styles.actionButton} icon={<RefreshIcon />} variant="outline" onClick={handleReset}>重置</Button>
<Button className={styles.actionButton} icon={<SearchIcon />} theme="primary" onClick={handleSearch}>搜索</Button>
</div>
</div>
);
}
import { useEffect, useRef } from 'react';
import type { ComponentProps } from 'react';
import {
Input as TDesignInput,
Select as TDesignSelect,
Switch as TDesignSwitch,
Textarea as TDesignTextarea,
} from 'tdesign-react';
import type { InputRef } from 'tdesign-react';
type AccessibleInputProps = ComponentProps<typeof TDesignInput> & {
'aria-label'?: string;
id?: string;
};
type AccessibleSelectProps = ComponentProps<typeof TDesignSelect> & {
'aria-label'?: string;
'aria-labelledby'?: string;
id?: string;
};
type AccessibleSwitchProps = ComponentProps<typeof TDesignSwitch> & {
'aria-label'?: string;
};
type AccessibleTextareaProps = ComponentProps<typeof TDesignTextarea> & {
'aria-label'?: string;
id?: string;
};
export function Input({ 'aria-label': ariaLabel, ...props }: AccessibleInputProps) {
const inputRef = useRef<InputRef>(null);
useEffect(() => {
if (!inputRef.current?.inputElement || !ariaLabel) return;
inputRef.current.inputElement.setAttribute('aria-label', ariaLabel);
}, [ariaLabel]);
return <TDesignInput {...props} ref={inputRef} />;
}
export function Select({
'aria-label': ariaLabel,
id,
inputProps,
value,
options,
multiple,
disabled,
readonly,
readOnly,
onChange,
...props
}: AccessibleSelectProps) {
return (
<TDesignSelect
{...props}
inputProps={{
...(inputProps ?? {}),
...(id ? { id } : {}),
...(ariaLabel ? ({ 'aria-label': ariaLabel } as Record<string, unknown>) : {}),
} as ComponentProps<typeof TDesignSelect>['inputProps']}
multiple={multiple}
options={options}
readonly={readonly}
readOnly={readOnly}
disabled={disabled}
value={value}
onChange={(nextValue, context) => {
onChange?.(nextValue, context);
}}
/>
);
}
export function Switch({ 'aria-label': ariaLabel, value, ...props }: AccessibleSwitchProps) {
return <TDesignSwitch {...props} aria-checked={Boolean(value)} aria-label={ariaLabel} value={value} />;
}
export function Textarea({ 'aria-label': ariaLabel, ...props }: AccessibleTextareaProps) {
const textareaRef = useRef<{ currentElement: HTMLDivElement; textareaElement: HTMLTextAreaElement }>(null);
useEffect(() => {
if (!textareaRef.current?.textareaElement || !ariaLabel) return;
textareaRef.current.textareaElement.setAttribute('aria-label', ariaLabel);
}, [ariaLabel]);
return <TDesignTextarea {...props} ref={textareaRef} />;
}
export function classNames(...values: Array<string | false | null | undefined>) {
return values.filter(Boolean).join(' ');
}
import type { ReactElement, ReactNode } from 'react';
import { useEffect, useState } from 'react';
import { MenuFoldIcon, MenuUnfoldIcon } from 'tdesign-icons-react';
import { Avatar, Breadcrumb, Button, Dropdown, Menu } from 'tdesign-react';
export interface BusinessAdminShellMenuItem {
key: string;
label: ReactNode;
icon?: ReactElement;
disabled?: boolean;
children?: BusinessAdminShellMenuItem[];
}
export interface BusinessAdminShellBreadcrumbItem {
key: string;
label: ReactNode;
onClick?: () => void;
}
export interface BusinessAdminShellUser {
name: string;
avatarUrl?: string;
}
export interface BusinessAdminShellProps {
systemName: string;
menuItems: BusinessAdminShellMenuItem[];
activeMenuKey?: string;
expandedMenuKeys?: string[];
breadcrumbItems: BusinessAdminShellBreadcrumbItem[];
user: BusinessAdminShellUser;
children: ReactNode;
hasProfile?: boolean;
defaultCollapsed?: boolean;
collapsed?: boolean;
headerHeight?: number;
contentPadding?: number;
onMenuChange: (key: string) => void;
onCollapsedChange?: (collapsed: boolean) => void;
onLogout: () => void;
onProfile?: () => void;
}
function renderMenuItem(item: BusinessAdminShellMenuItem) {
if (item.children?.length) {
return (
<Menu.SubMenu
key={item.key}
value={item.key}
title={item.label}
icon={item.icon}
disabled={item.disabled}
>
{item.children.map((child) => renderMenuItem(child))}
</Menu.SubMenu>
);
}
return (
<Menu.MenuItem key={item.key} value={item.key} icon={item.icon} disabled={item.disabled}>
{item.label}
</Menu.MenuItem>
);
}
function UserAvatar({ user }: { user: BusinessAdminShellUser }) {
const fallbackText = user.name.slice(0, 1) || '?';
return (
<Avatar
aria-label={`${user.name}头像`}
image={user.avatarUrl}
size="32px"
style={user.avatarUrl ? undefined : { backgroundColor: '#2f76ff', color: '#fff' }}
>
{user.avatarUrl ? null : fallbackText}
</Avatar>
);
}
export function BusinessAdminShell({
systemName,
menuItems,
activeMenuKey,
expandedMenuKeys = [],
breadcrumbItems,
user,
children,
hasProfile = false,
defaultCollapsed = false,
collapsed,
headerHeight = 56,
contentPadding = 24,
onMenuChange,
onCollapsedChange,
onLogout,
onProfile,
}: BusinessAdminShellProps) {
const userAvatar = <UserAvatar user={user} />;
const [internalCollapsed, setInternalCollapsed] = useState(defaultCollapsed);
const [internalExpandedMenuKeys, setInternalExpandedMenuKeys] = useState(expandedMenuKeys);
const isCollapsed = collapsed ?? internalCollapsed;
const asideWidth = isCollapsed ? 64 : 220;
useEffect(() => {
setInternalExpandedMenuKeys((currentKeys) => {
const nextKeys = new Set(currentKeys);
expandedMenuKeys.forEach((key) => nextKeys.add(key));
return Array.from(nextKeys);
});
}, [expandedMenuKeys]);
const toggleCollapsed = () => {
const nextCollapsed = !isCollapsed;
setInternalCollapsed(nextCollapsed);
onCollapsedChange?.(nextCollapsed);
};
return (
<div
className="grid h-screen min-h-screen bg-[var(--gl-color-bg-page)] text-[var(--gl-color-text-primary)] max-[760px]:grid-cols-1"
style={{ gridTemplateColumns: `${asideWidth}px 1fr` }}
>
<aside
aria-label="左侧导航"
className="min-w-0 border-r border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)]"
style={{ width: asideWidth }}
>
<div className="flex h-14 items-center justify-between gap-2 px-3">
{isCollapsed ? null : (
<h1 className="m-0 min-w-0 truncate px-2 text-base font-semibold leading-[var(--gl-line-height-lg)] text-[var(--gl-color-text-primary)]">
{systemName}
</h1>
)}
<button
aria-label={isCollapsed ? '展开菜单' : '收起菜单'}
className="grid h-8 w-8 shrink-0 place-items-center rounded border-0 bg-transparent p-0 text-[var(--gl-color-text-secondary)] hover:bg-[var(--gl-color-bg-page)] hover:text-[var(--gl-color-primary)]"
type="button"
onClick={toggleCollapsed}
>
{isCollapsed ? <MenuUnfoldIcon /> : <MenuFoldIcon />}
</button>
</div>
<Menu
value={activeMenuKey}
expanded={internalExpandedMenuKeys}
collapsed={isCollapsed}
width={['220px', '64px']}
onChange={(value) => onMenuChange(String(value))}
onExpand={(value) => setInternalExpandedMenuKeys(value.map(String))}
>
{menuItems.map((item) => renderMenuItem(item))}
</Menu>
</aside>
<div className="grid min-h-0 min-w-0 grid-rows-[auto_1fr]">
<header
className="flex items-center justify-between gap-4 border-b border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-6 text-sm"
style={{ height: headerHeight }}
>
<Breadcrumb separator=">">
{breadcrumbItems.map((item, index) => {
const isLast = index === breadcrumbItems.length - 1;
return (
<Breadcrumb.BreadcrumbItem key={item.key}>
{item.onClick && !isLast ? (
<button
className="border-0 bg-transparent p-0 text-sm text-[var(--gl-color-primary)] hover:underline"
type="button"
onClick={item.onClick}
>
{item.label}
</button>
) : (
item.label
)}
</Breadcrumb.BreadcrumbItem>
);
})}
</Breadcrumb>
<div className="flex shrink-0 items-center gap-3">
<span className="text-sm text-[var(--gl-color-text-primary)]">{user.name}</span>
{hasProfile ? (
<Dropdown
trigger="click"
options={[
{ content: '个人信息', value: 'profile' },
{ content: '退出登录', value: 'logout' },
]}
onClick={(option) => {
if (option.value === 'profile') onProfile?.();
if (option.value === 'logout') onLogout();
}}
>
<button
aria-label={`${user.name} 用户菜单`}
className="grid h-8 w-8 place-items-center border-0 bg-transparent p-0"
type="button"
>
{userAvatar}
</button>
</Dropdown>
) : (
<>
{userAvatar}
<Button variant="outline" onClick={onLogout}>
退出登录
</Button>
</>
)}
</div>
</header>
<main className="min-h-0 min-w-0 overflow-auto" style={{ padding: contentPadding }}>
{children}
</main>
</div>
</div>
);
}
.root {
display: grid;
min-height: 160px;
place-items: center;
align-content: center;
gap: var(--gl-spacing-sm);
padding: var(--gl-spacing-xl);
color: var(--gl-color-text-secondary);
text-align: center;
}
.icon {
display: inline-flex;
color: var(--gl-color-text-placeholder, #8b98aa);
font-size: 30px;
}
.title {
color: var(--gl-color-text-primary);
font-size: var(--gl-font-size-md);
}
.description {
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-sm);
}
.actions {
display: flex;
align-items: center;
gap: var(--gl-spacing-sm);
}
.error,
.forbidden,
.offline {
border-color: var(--gl-color-error, #d54941);
}
import type { ReactNode } from 'react';
import { CloseCircleIcon, ErrorCircleIcon, FileIcon, RefreshIcon, SearchIcon } from 'tdesign-icons-react';
import { classNames } from '../shared/classNames';
import styles from './StatePlaceholder.module.css';
export interface StatePlaceholderProps {
state: 'empty' | 'filtered-empty' | 'error' | 'forbidden' | 'offline';
title?: ReactNode;
description?: ReactNode;
primaryAction?: ReactNode;
secondaryAction?: ReactNode;
icon?: ReactNode;
}
const defaults: Record<StatePlaceholderProps['state'], { title: string; description: string; role: 'status' | 'alert'; icon: ReactNode }> = {
empty: { title: '暂无数据', description: '当前内容为空', role: 'status', icon: <FileIcon /> },
'filtered-empty': { title: '未找到匹配结果', description: '请调整搜索或筛选条件', role: 'status', icon: <SearchIcon /> },
error: { title: '加载失败', description: '数据请求失败,请稍后重试', role: 'alert', icon: <ErrorCircleIcon /> },
forbidden: { title: '权限受限', description: '当前账号暂无访问权限', role: 'alert', icon: <CloseCircleIcon /> },
offline: { title: '网络不可用', description: '请检查网络连接后重试', role: 'alert', icon: <RefreshIcon /> },
};
export function StatePlaceholder({ description, icon, primaryAction, secondaryAction, state, title }: StatePlaceholderProps) {
const preset = defaults[state];
const resolvedTitle = title ?? preset.title;
return (
<div className={classNames(styles.root, styles[state])} role={preset.role} aria-label={String(resolvedTitle)}>
<div className={styles.icon} aria-hidden="true">{icon ?? preset.icon}</div>
<strong className={styles.title}>{resolvedTitle}</strong>
<div className={styles.description}>{description ?? preset.description}</div>
{(primaryAction || secondaryAction) ? <div className={styles.actions}>{primaryAction}{secondaryAction}</div> : null}
</div>
);
}
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
2026-05-31 15:39:33 [INFO] uvicorn.access - 127.0.0.1:50620 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-05-31 15:39:33 [INFO] uvicorn.access - 127.0.0.1:50619 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-05-31 15:39:33 [INFO] uvicorn.access - 127.0.0.1:50629 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-05-31 15:39:34 [INFO] uvicorn.access - 127.0.0.1:50637 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-05-31 15:39:34 [INFO] uvicorn.access - 127.0.0.1:50639 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-05-31 15:46:01 [INFO] uvicorn.access - 127.0.0.1:52890 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-05-31 15:46:01 [INFO] uvicorn.access - 127.0.0.1:52892 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-05-31 15:47:24 [INFO] uvicorn.access - 127.0.0.1:53397 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-05-31 15:47:24 [INFO] uvicorn.access - 127.0.0.1:53396 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-05-31 15:47:24 [INFO] uvicorn.access - 127.0.0.1:53399 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-05-31 16:02:08 [INFO] uvicorn.access - 127.0.0.1:58672 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-05-31 16:02:08 [INFO] uvicorn.access - 127.0.0.1:58671 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-05-31 16:02:08 [INFO] uvicorn.access - 127.0.0.1:58673 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-05-31 16:02:17 [INFO] uvicorn.access - 127.0.0.1:58725 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-05-31 16:02:17 [INFO] uvicorn.access - 127.0.0.1:58724 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-05-31 16:02:17 [INFO] uvicorn.access - 127.0.0.1:58726 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-05-31 16:02:18 [INFO] uvicorn.access - 127.0.0.1:58740 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-05-31 16:02:19 [INFO] uvicorn.access - 127.0.0.1:58749 - "GET /api/v1/official-site/tabs?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-05-31 16:02:19 [INFO] uvicorn.access - 127.0.0.1:58758 - "GET /api/v1/skills HTTP/1.1" 200
2026-05-31 16:02:19 [INFO] uvicorn.access - 127.0.0.1:58759 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-05-31 16:02:20 [INFO] uvicorn.access - 127.0.0.1:58764 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-05-31 16:02:20 [INFO] uvicorn.access - 127.0.0.1:58763 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-05-31 16:02:20 [INFO] uvicorn.access - 127.0.0.1:58765 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-05-31 16:02:27 [INFO] uvicorn.access - 127.0.0.1:58811 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-05-31 16:02:27 [INFO] uvicorn.access - 127.0.0.1:58810 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-05-31 16:02:27 [INFO] uvicorn.access - 127.0.0.1:58812 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-05-31 16:30:04 [INFO] uvicorn.access - 127.0.0.1:61937 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 500
2026-05-31 16:30:04 [ERROR] uvicorn.error - Exception in ASGI application
Traceback (most recent call last):
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 1319, in _checkout
raise exc.InvalidatePoolError()
sqlalchemy.exc.InvalidatePoolError: ()
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/pymysql/connections.py", line 661, in connect
sock = socket.create_connection(
(self.host, self.port), self.connect_timeout, **kwargs
)
File "/Library/Frameworks/Python.framework/Versions/3.14/lib/python3.14/socket.py", line 870, in create_connection
raise exceptions[0]
File "/Library/Frameworks/Python.framework/Versions/3.14/lib/python3.14/socket.py", line 855, in create_connection
sock.connect(sa)
~~~~~~~~~~~~^^^^
TimeoutError: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 143, in __init__
self._dbapi_connection = engine.raw_connection()
~~~~~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 3317, in raw_connection
return self.pool.connect()
~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 448, in connect
return _ConnectionFairy._checkout(self)
~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 1353, in _checkout
with util.safe_reraise():
~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/util/langhelpers.py", line 121, in __exit__
raise exc_value.with_traceback(exc_tb)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 1350, in _checkout
fairy._connection_record.get_connection()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 837, in get_connection
self.__connect()
~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 900, in __connect
with util.safe_reraise():
~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/util/langhelpers.py", line 121, in __exit__
raise exc_value.with_traceback(exc_tb)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 896, in __connect
self.dbapi_connection = connection = pool._invoke_creator(self)
~~~~~~~~~~~~~~~~~~~~^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/create.py", line 661, in connect
return dialect.connect(*cargs, **cparams)
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/default.py", line 630, in connect
return self.loaded_dbapi.connect(*cargs, **cparams) # type: ignore[no-any-return] # NOQA: E501
~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/pymysql/connections.py", line 365, in __init__
self.connect()
~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/pymysql/connections.py", line 723, in connect
raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '192.168.3.92' (timed out)")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/uvicorn/protocols/http/h11_impl.py", line 410, in run_asgi
result = await app( # type: ignore[func-returns-value]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
self.scope, self.receive, self.send
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__
return await self.app(scope, receive, send)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/fastapi/applications.py", line 1159, in __call__
await super().__call__(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/applications.py", line 107, in __call__
await self.middleware_stack(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/middleware/errors.py", line 186, in __call__
raise exc
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/middleware/errors.py", line 164, in __call__
await self.app(scope, receive, _send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/middleware/base.py", line 191, in __call__
with recv_stream, send_stream, collapse_excgroups():
~~~~~~~~~~~~~~~~~~^^
File "/Library/Frameworks/Python.framework/Versions/3.14/lib/python3.14/contextlib.py", line 162, in __exit__
self.gen.throw(value)
~~~~~~~~~~~~~~^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/_utils.py", line 87, in collapse_excgroups
raise exc
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/middleware/base.py", line 193, in __call__
response = await self.dispatch_func(request, call_next)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/app/main.py", line 137, in wrap_json_response
response = await call_next(request)
^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/middleware/base.py", line 168, in call_next
raise app_exc from app_exc.__cause__ or app_exc.__context__
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/middleware/base.py", line 144, in coro
await self.app(scope, receive_or_disconnect, send_no_error)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/middleware/exceptions.py", line 63, in __call__
await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
raise exc
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
await app(scope, receive, sender)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__
await self.app(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/routing.py", line 716, in __call__
await self.middleware_stack(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/routing.py", line 736, in app
await route.handle(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/routing.py", line 290, in handle
await self.app(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/fastapi/routing.py", line 134, in app
await wrap_app_handling_exceptions(app, request)(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
raise exc
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
await app(scope, receive, sender)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/fastapi/routing.py", line 120, in app
response = await f(request)
^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/fastapi/routing.py", line 674, in app
raw_response = await run_endpoint_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...<3 lines>...
)
^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/fastapi/routing.py", line 330, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/concurrency.py", line 32, in run_in_threadpool
return await anyio.to_thread.run_sync(func)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/anyio/to_thread.py", line 63, in run_sync
return await get_async_backend().run_sync_in_worker_thread(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
func, args, abandon_on_cancel=abandon_on_cancel, limiter=limiter
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/anyio/_backends/_asyncio.py", line 2518, in run_sync_in_worker_thread
return await future
^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/anyio/_backends/_asyncio.py", line 1002, in run
result = context.run(func, *args)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/app/api/v1/endpoints/position_tags.py", line 105, in list_position_tags
total, items = svc.list_tags(page=page, page_size=page_size, keyword=keyword)
~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/app/service/position_tag_service.py", line 174, in list_tags
total = query.count()
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/query.py", line 3146, in count
self._legacy_from_self(col).enable_eagerloads(False).scalar()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/query.py", line 2835, in scalar
ret = self.one()
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/query.py", line 2808, in one
return self._iter().one() # type: ignore
~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/query.py", line 2857, in _iter
result: Union[ScalarResult[_T], Result[_T]] = self.session.execute(
~~~~~~~~~~~~~~~~~~~~^
statement,
^^^^^^^^^^
params,
^^^^^^^
execution_options={"_sa_orm_load_options": self.load_options},
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/session.py", line 2351, in execute
return self._execute_internal(
~~~~~~~~~~~~~~~~~~~~~~^
statement,
^^^^^^^^^^
...<4 lines>...
_add_event=_add_event,
^^^^^^^^^^^^^^^^^^^^^^
)
^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/session.py", line 2239, in _execute_internal
conn = self._connection_for_bind(bind)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/session.py", line 2108, in _connection_for_bind
return trans._connection_for_bind(engine, execution_options)
~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<string>", line 2, in _connection_for_bind
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/state_changes.py", line 137, in _go
ret_value = fn(self, *arg, **kw)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/session.py", line 1187, in _connection_for_bind
conn = bind.connect()
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 3293, in connect
return self._connection_cls(self)
~~~~~~~~~~~~~~~~~~~~^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 145, in __init__
Connection._handle_dbapi_exception_noconnection(
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
err, dialect, engine
^^^^^^^^^^^^^^^^^^^^
)
^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 2448, in _handle_dbapi_exception_noconnection
raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 143, in __init__
self._dbapi_connection = engine.raw_connection()
~~~~~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 3317, in raw_connection
return self.pool.connect()
~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 448, in connect
return _ConnectionFairy._checkout(self)
~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 1353, in _checkout
with util.safe_reraise():
~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/util/langhelpers.py", line 121, in __exit__
raise exc_value.with_traceback(exc_tb)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 1350, in _checkout
fairy._connection_record.get_connection()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 837, in get_connection
self.__connect()
~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 900, in __connect
with util.safe_reraise():
~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/util/langhelpers.py", line 121, in __exit__
raise exc_value.with_traceback(exc_tb)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 896, in __connect
self.dbapi_connection = connection = pool._invoke_creator(self)
~~~~~~~~~~~~~~~~~~~~^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/create.py", line 661, in connect
return dialect.connect(*cargs, **cparams)
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/default.py", line 630, in connect
return self.loaded_dbapi.connect(*cargs, **cparams) # type: ignore[no-any-return] # NOQA: E501
~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/pymysql/connections.py", line 365, in __init__
self.connect()
~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/pymysql/connections.py", line 723, in connect
raise exc
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '192.168.3.92' (timed out)")
(Background on this error at: https://sqlalche.me/e/20/e3q8)
2026-05-31 18:49:59 [INFO] uvicorn.access - 127.0.0.1:54070 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 500
2026-05-31 18:49:59 [ERROR] uvicorn.error - Exception in ASGI application
Traceback (most recent call last):
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/pymysql/connections.py", line 661, in connect
sock = socket.create_connection(
(self.host, self.port), self.connect_timeout, **kwargs
)
File "/Library/Frameworks/Python.framework/Versions/3.14/lib/python3.14/socket.py", line 870, in create_connection
raise exceptions[0]
File "/Library/Frameworks/Python.framework/Versions/3.14/lib/python3.14/socket.py", line 855, in create_connection
sock.connect(sa)
~~~~~~~~~~~~^^^^
TimeoutError: [Errno 60] Operation timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 143, in __init__
self._dbapi_connection = engine.raw_connection()
~~~~~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 3317, in raw_connection
return self.pool.connect()
~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 448, in connect
return _ConnectionFairy._checkout(self)
~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 1272, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 717, in checkout
with util.safe_reraise():
~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/util/langhelpers.py", line 121, in __exit__
raise exc_value.with_traceback(exc_tb)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 715, in checkout
dbapi_connection = rec.get_connection()
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 866, in get_connection
self.__connect()
~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 900, in __connect
with util.safe_reraise():
~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/util/langhelpers.py", line 121, in __exit__
raise exc_value.with_traceback(exc_tb)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 896, in __connect
self.dbapi_connection = connection = pool._invoke_creator(self)
~~~~~~~~~~~~~~~~~~~~^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/create.py", line 661, in connect
return dialect.connect(*cargs, **cparams)
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/default.py", line 630, in connect
return self.loaded_dbapi.connect(*cargs, **cparams) # type: ignore[no-any-return] # NOQA: E501
~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/pymysql/connections.py", line 365, in __init__
self.connect()
~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/pymysql/connections.py", line 723, in connect
raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '192.168.3.92' ([Errno 60] Operation timed out)")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/uvicorn/protocols/http/h11_impl.py", line 410, in run_asgi
result = await app( # type: ignore[func-returns-value]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
self.scope, self.receive, self.send
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__
return await self.app(scope, receive, send)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/fastapi/applications.py", line 1159, in __call__
await super().__call__(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/applications.py", line 107, in __call__
await self.middleware_stack(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/middleware/errors.py", line 186, in __call__
raise exc
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/middleware/errors.py", line 164, in __call__
await self.app(scope, receive, _send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/middleware/base.py", line 191, in __call__
with recv_stream, send_stream, collapse_excgroups():
~~~~~~~~~~~~~~~~~~^^
File "/Library/Frameworks/Python.framework/Versions/3.14/lib/python3.14/contextlib.py", line 162, in __exit__
self.gen.throw(value)
~~~~~~~~~~~~~~^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/_utils.py", line 87, in collapse_excgroups
raise exc
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/middleware/base.py", line 193, in __call__
response = await self.dispatch_func(request, call_next)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/app/main.py", line 137, in wrap_json_response
response = await call_next(request)
^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/middleware/base.py", line 168, in call_next
raise app_exc from app_exc.__cause__ or app_exc.__context__
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/middleware/base.py", line 144, in coro
await self.app(scope, receive_or_disconnect, send_no_error)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/middleware/exceptions.py", line 63, in __call__
await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
raise exc
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
await app(scope, receive, sender)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__
await self.app(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/routing.py", line 716, in __call__
await self.middleware_stack(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/routing.py", line 736, in app
await route.handle(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/routing.py", line 290, in handle
await self.app(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/fastapi/routing.py", line 134, in app
await wrap_app_handling_exceptions(app, request)(scope, receive, send)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
raise exc
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
await app(scope, receive, sender)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/fastapi/routing.py", line 120, in app
response = await f(request)
^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/fastapi/routing.py", line 674, in app
raw_response = await run_endpoint_function(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...<3 lines>...
)
^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/fastapi/routing.py", line 330, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/starlette/concurrency.py", line 32, in run_in_threadpool
return await anyio.to_thread.run_sync(func)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/anyio/to_thread.py", line 63, in run_sync
return await get_async_backend().run_sync_in_worker_thread(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
func, args, abandon_on_cancel=abandon_on_cancel, limiter=limiter
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/anyio/_backends/_asyncio.py", line 2518, in run_sync_in_worker_thread
return await future
^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/anyio/_backends/_asyncio.py", line 1002, in run
result = context.run(func, *args)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/app/api/v1/endpoints/position_tags.py", line 105, in list_position_tags
total, items = svc.list_tags(page=page, page_size=page_size, keyword=keyword)
~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/app/service/position_tag_service.py", line 174, in list_tags
total = query.count()
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/query.py", line 3146, in count
self._legacy_from_self(col).enable_eagerloads(False).scalar()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/query.py", line 2835, in scalar
ret = self.one()
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/query.py", line 2808, in one
return self._iter().one() # type: ignore
~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/query.py", line 2857, in _iter
result: Union[ScalarResult[_T], Result[_T]] = self.session.execute(
~~~~~~~~~~~~~~~~~~~~^
statement,
^^^^^^^^^^
params,
^^^^^^^
execution_options={"_sa_orm_load_options": self.load_options},
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/session.py", line 2351, in execute
return self._execute_internal(
~~~~~~~~~~~~~~~~~~~~~~^
statement,
^^^^^^^^^^
...<4 lines>...
_add_event=_add_event,
^^^^^^^^^^^^^^^^^^^^^^
)
^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/session.py", line 2239, in _execute_internal
conn = self._connection_for_bind(bind)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/session.py", line 2108, in _connection_for_bind
return trans._connection_for_bind(engine, execution_options)
~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<string>", line 2, in _connection_for_bind
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/state_changes.py", line 137, in _go
ret_value = fn(self, *arg, **kw)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/orm/session.py", line 1187, in _connection_for_bind
conn = bind.connect()
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 3293, in connect
return self._connection_cls(self)
~~~~~~~~~~~~~~~~~~~~^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 145, in __init__
Connection._handle_dbapi_exception_noconnection(
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
err, dialect, engine
^^^^^^^^^^^^^^^^^^^^
)
^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 2448, in _handle_dbapi_exception_noconnection
raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 143, in __init__
self._dbapi_connection = engine.raw_connection()
~~~~~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/base.py", line 3317, in raw_connection
return self.pool.connect()
~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 448, in connect
return _ConnectionFairy._checkout(self)
~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 1272, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 717, in checkout
with util.safe_reraise():
~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/util/langhelpers.py", line 121, in __exit__
raise exc_value.with_traceback(exc_tb)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 715, in checkout
dbapi_connection = rec.get_connection()
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 866, in get_connection
self.__connect()
~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 900, in __connect
with util.safe_reraise():
~~~~~~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/util/langhelpers.py", line 121, in __exit__
raise exc_value.with_traceback(exc_tb)
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/pool/base.py", line 896, in __connect
self.dbapi_connection = connection = pool._invoke_creator(self)
~~~~~~~~~~~~~~~~~~~~^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/create.py", line 661, in connect
return dialect.connect(*cargs, **cparams)
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/sqlalchemy/engine/default.py", line 630, in connect
return self.loaded_dbapi.connect(*cargs, **cparams) # type: ignore[no-any-return] # NOQA: E501
~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/pymysql/connections.py", line 365, in __init__
self.connect()
~~~~~~~~~~~~^^
File "/Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/.venv/lib/python3.14/site-packages/pymysql/connections.py", line 723, in connect
raise exc
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '192.168.3.92' ([Errno 60] Operation timed out)")
(Background on this error at: https://sqlalche.me/e/20/e3q8)
2026-05-31 20:59:54 [INFO] uvicorn.access - 127.0.0.1:59922 - "GET /api/v1/skills HTTP/1.1" 200
2026-05-31 20:59:54 [INFO] uvicorn.access - 127.0.0.1:59921 - "GET /api/v1/agent-group/employees/mounts HTTP/1.1" 200
2026-05-31 20:59:54 [INFO] uvicorn.access - 127.0.0.1:59920 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-05-31 20:59:57 [INFO] uvicorn.access - 127.0.0.1:59946 - "GET /api/v1/agent-group/employees/mounts HTTP/1.1" 200
2026-05-31 20:59:57 [INFO] uvicorn.access - 127.0.0.1:59945 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-05-31 20:59:58 [INFO] uvicorn.access - 127.0.0.1:59960 - "GET /api/v1/official-site/methodology HTTP/1.1" 200
2026-05-31 20:59:58 [INFO] uvicorn.access - 127.0.0.1:59961 - "GET /api/v1/official-site/methodology HTTP/1.1" 200
2026-05-31 20:59:59 [INFO] uvicorn.access - 127.0.0.1:59968 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-05-31 21:00:02 [INFO] uvicorn.access - 127.0.0.1:59993 - "GET /api/v1/official-site/tabs/qrcodes/available HTTP/1.1" 200
2026-05-31 21:00:02 [INFO] uvicorn.access - 127.0.0.1:59994 - "GET /api/v1/official-site/tabs?page=1&page_size=100 HTTP/1.1" 200
2026-05-31 21:00:17 [INFO] uvicorn.access - 127.0.0.1:60076 - "GET /api/v1/skills HTTP/1.1" 200
2026-05-31 21:00:17 [INFO] uvicorn.access - 127.0.0.1:60075 - "GET /api/v1/agent-group/employees/mounts HTTP/1.1" 200
2026-05-31 21:00:17 [INFO] uvicorn.access - 127.0.0.1:60074 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-05-31 21:00:19 [INFO] uvicorn.access - 127.0.0.1:60095 - "GET /api/v1/agent-group/employees/mounts HTTP/1.1" 200
2026-05-31 21:00:19 [INFO] uvicorn.access - 127.0.0.1:60094 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-05-31 21:00:20 [INFO] uvicorn.access - 127.0.0.1:60103 - "GET /api/v1/official-site/methodology HTTP/1.1" 200
2026-05-31 21:00:20 [INFO] uvicorn.access - 127.0.0.1:60104 - "GET /api/v1/official-site/methodology HTTP/1.1" 200
2026-05-31 21:00:20 [INFO] uvicorn.access - 127.0.0.1:60105 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-05-31 21:00:21 [INFO] uvicorn.access - 127.0.0.1:60116 - "GET /api/v1/official-site/tabs/1 HTTP/1.1" 200
2026-05-31 21:00:21 [INFO] uvicorn.access - 127.0.0.1:60117 - "GET /api/v1/official-site/tabs/1/agents/available HTTP/1.1" 200
2026-05-31 21:00:21 [INFO] uvicorn.access - 127.0.0.1:60123 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-05-31 21:00:44 [INFO] uvicorn.access - 127.0.0.1:60282 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 11:09:34 [INFO] uvicorn.error - Started server process [17455]
2026-06-01 11:09:34 [INFO] uvicorn.error - Waiting for application startup.
2026-06-01 11:09:36 [INFO] app.service.agent_hub - 扫描 skills 目录并注册到全局 Toolkit: /Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/skills
2026-06-01 11:09:36 [INFO] app.service.agent_hub - 构建 agent 'main' 的专属 Toolkit (skills: [])
2026-06-01 11:09:36 [INFO] app.service.agent_hub - 构建 agent 'meeting' 的专属 Toolkit (skills: ['meeting_minutes'])
2026-06-01 11:09:36 [INFO] uvicorn.error - Application startup complete.
2026-06-01 11:09:36 [INFO] uvicorn.error - Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
2026-06-01 11:09:49 [INFO] uvicorn.access - 127.0.0.1:60372 - "GET /health HTTP/1.1" 200
2026-06-01 11:12:24 [INFO] uvicorn.access - 127.0.0.1:60788 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-01 11:12:24 [INFO] uvicorn.access - 127.0.0.1:60789 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 11:12:24 [INFO] uvicorn.access - 127.0.0.1:60791 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 12:12:59 [INFO] uvicorn.access - 127.0.0.1:51748 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 12:12:59 [INFO] uvicorn.access - 127.0.0.1:51747 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-01 12:12:59 [INFO] uvicorn.access - 127.0.0.1:51763 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 12:13:43 [INFO] uvicorn.access - 127.0.0.1:52314 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 12:13:43 [INFO] uvicorn.access - 127.0.0.1:52313 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-01 12:13:43 [INFO] uvicorn.access - 127.0.0.1:52344 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 14:36:59 [INFO] uvicorn.error - Started server process [49996]
2026-06-01 14:36:59 [INFO] uvicorn.error - Waiting for application startup.
2026-06-01 14:37:01 [INFO] app.service.agent_hub - 扫描 skills 目录并注册到全局 Toolkit: /Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/skills
2026-06-01 14:37:01 [INFO] app.service.agent_hub - 构建 agent 'main' 的专属 Toolkit (skills: [])
2026-06-01 14:37:01 [INFO] app.service.agent_hub - 构建 agent 'meeting' 的专属 Toolkit (skills: ['meeting_minutes'])
2026-06-01 14:37:01 [INFO] uvicorn.error - Application startup complete.
2026-06-01 14:37:01 [INFO] uvicorn.error - Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
2026-06-01 14:37:11 [INFO] uvicorn.access - 127.0.0.1:50199 - "GET /health HTTP/1.1" 200
2026-06-01 14:37:11 [INFO] uvicorn.access - 127.0.0.1:50201 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-01 14:37:24 [INFO] uvicorn.access - 127.0.0.1:50280 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 14:37:24 [INFO] uvicorn.access - 127.0.0.1:50279 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-01 14:37:24 [INFO] uvicorn.access - 127.0.0.1:50284 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 14:37:27 [INFO] uvicorn.access - 127.0.0.1:50307 - "GET /api/v1/official-site/tabs?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 14:37:27 [INFO] uvicorn.access - 127.0.0.1:50308 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 14:37:30 [INFO] uvicorn.access - 127.0.0.1:50325 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-01 14:37:30 [INFO] uvicorn.access - 127.0.0.1:50326 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 14:37:31 [INFO] uvicorn.access - 127.0.0.1:50351 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 14:37:32 [INFO] uvicorn.access - 127.0.0.1:50350 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-01 14:37:32 [INFO] uvicorn.access - 127.0.0.1:50354 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 14:38:58 [INFO] uvicorn.access - 127.0.0.1:50951 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 14:38:59 [INFO] uvicorn.access - 127.0.0.1:50957 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 14:39:00 [INFO] uvicorn.access - 127.0.0.1:50965 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-01 14:39:00 [INFO] uvicorn.access - 127.0.0.1:50968 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 14:39:05 [INFO] uvicorn.access - 127.0.0.1:51007 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 14:39:05 [INFO] uvicorn.access - 127.0.0.1:51010 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 14:41:01 [INFO] uvicorn.access - 127.0.0.1:51703 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 14:41:01 [INFO] uvicorn.access - 127.0.0.1:51702 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-01 14:41:02 [INFO] uvicorn.access - 127.0.0.1:51710 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 14:54:52 [INFO] uvicorn.access - 127.0.0.1:56668 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 14:54:52 [INFO] uvicorn.access - 127.0.0.1:56676 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 14:55:03 [INFO] uvicorn.access - 127.0.0.1:56736 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-01 14:55:03 [INFO] uvicorn.access - 127.0.0.1:56744 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 14:55:04 [INFO] uvicorn.access - 127.0.0.1:56747 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 14:55:04 [INFO] uvicorn.access - 127.0.0.1:56754 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 14:55:13 [INFO] uvicorn.access - 127.0.0.1:56854 - "GET /api/v1/agent-group/qrcode/1 HTTP/1.1" 200
2026-06-01 14:55:17 [INFO] uvicorn.access - 127.0.0.1:56875 - "GET /api/v1/agent-group/qrcode/1 HTTP/1.1" 200
2026-06-01 14:55:19 [INFO] uvicorn.access - 127.0.0.1:56888 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 14:55:19 [INFO] uvicorn.access - 127.0.0.1:56891 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 14:55:40 [INFO] uvicorn.access - 127.0.0.1:56982 - "GET /api/v1/agent-group/qrcode/1 HTTP/1.1" 200
2026-06-01 14:55:56 [INFO] uvicorn.access - 127.0.0.1:57052 - "GET /api/v1/official-site/tabs?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 14:55:56 [INFO] uvicorn.access - 127.0.0.1:57057 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 14:55:57 [INFO] uvicorn.access - 127.0.0.1:57060 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 14:55:58 [INFO] uvicorn.access - 127.0.0.1:57063 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 14:55:59 [INFO] uvicorn.access - 127.0.0.1:57067 - "POST /api/v1/analytics/events HTTP/1.1" 200
2026-06-01 14:56:03 [INFO] uvicorn.access - 127.0.0.1:57072 - "POST /api/v1/position-tags HTTP/1.1" 201
2026-06-01 14:56:03 [INFO] uvicorn.access - 127.0.0.1:57075 - "POST /api/v1/analytics/events HTTP/1.1" 200
2026-06-01 15:53:49 [INFO] uvicorn.access - 127.0.0.1:63636 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 15:53:49 [INFO] uvicorn.access - 127.0.0.1:63644 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 15:58:35 [INFO] uvicorn.access - 127.0.0.1:65499 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 15:58:35 [INFO] uvicorn.access - 127.0.0.1:65506 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 15:58:59 [INFO] uvicorn.access - 127.0.0.1:49281 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 15:58:59 [INFO] uvicorn.access - 127.0.0.1:49288 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 15:58:59 [INFO] uvicorn.access - 127.0.0.1:49280 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-01 15:59:01 [INFO] uvicorn.access - 127.0.0.1:49293 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 15:59:01 [INFO] uvicorn.access - 127.0.0.1:49304 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 15:59:02 [INFO] uvicorn.access - 127.0.0.1:49311 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-01 15:59:02 [INFO] uvicorn.access - 127.0.0.1:49316 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 15:59:03 [INFO] uvicorn.access - 127.0.0.1:49327 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 15:59:03 [INFO] uvicorn.access - 127.0.0.1:49330 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 15:59:03 [INFO] uvicorn.access - 127.0.0.1:49326 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-01 17:48:20 [INFO] uvicorn.error - Started server process [15260]
2026-06-01 17:48:20 [INFO] uvicorn.error - Waiting for application startup.
2026-06-01 17:48:23 [INFO] app.service.agent_hub - 扫描 skills 目录并注册到全局 Toolkit: /Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/skills
2026-06-01 17:48:23 [INFO] app.service.agent_hub - 构建 agent 'main' 的专属 Toolkit (skills: [])
2026-06-01 17:48:23 [INFO] app.service.agent_hub - 构建 agent 'meeting' 的专属 Toolkit (skills: ['meeting_minutes'])
2026-06-01 17:48:23 [INFO] uvicorn.error - Application startup complete.
2026-06-01 17:48:23 [INFO] uvicorn.error - Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
2026-06-01 17:48:31 [INFO] uvicorn.access - 127.0.0.1:57146 - "GET /health HTTP/1.1" 200
2026-06-01 17:48:31 [INFO] uvicorn.access - 127.0.0.1:57148 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-01 17:51:49 [INFO] uvicorn.access - 127.0.0.1:58433 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 17:51:49 [INFO] uvicorn.access - 127.0.0.1:58432 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-01 17:51:49 [INFO] uvicorn.access - 127.0.0.1:58437 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 18:20:50 [INFO] uvicorn.access - 127.0.0.1:52092 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-01 18:20:51 [INFO] uvicorn.access - 127.0.0.1:52097 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-01 18:20:51 [INFO] uvicorn.access - 127.0.0.1:52091 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 09:39:45 [INFO] uvicorn.access - 127.0.0.1:52665 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 09:39:46 [INFO] uvicorn.access - 127.0.0.1:52669 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 09:39:47 [INFO] uvicorn.access - 127.0.0.1:52687 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 09:39:47 [INFO] uvicorn.access - 127.0.0.1:52686 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 09:39:47 [INFO] uvicorn.access - 127.0.0.1:52690 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 09:39:48 [INFO] uvicorn.access - 127.0.0.1:52701 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 09:39:48 [INFO] uvicorn.access - 127.0.0.1:52704 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 09:39:49 [INFO] uvicorn.access - 127.0.0.1:52713 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 09:39:49 [INFO] uvicorn.access - 127.0.0.1:52714 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 10:04:52 [INFO] uvicorn.access - 127.0.0.1:61348 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 10:05:36 [INFO] uvicorn.access - 127.0.0.1:61627 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 10:05:36 [INFO] uvicorn.access - 127.0.0.1:61629 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 10:06:08 [INFO] uvicorn.access - 127.0.0.1:62062 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 10:06:08 [INFO] uvicorn.access - 127.0.0.1:62063 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 11:22:58 [INFO] uvicorn.access - 127.0.0.1:61882 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 11:22:58 [INFO] uvicorn.access - 127.0.0.1:61884 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 12:36:18 [INFO] uvicorn.access - 127.0.0.1:54064 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 12:36:18 [INFO] uvicorn.access - 127.0.0.1:54068 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 13:57:37 [INFO] uvicorn.access - 127.0.0.1:58526 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 13:57:37 [INFO] uvicorn.access - 127.0.0.1:58528 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:03:35 [INFO] uvicorn.access - 127.0.0.1:60452 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:03:35 [INFO] uvicorn.access - 127.0.0.1:60460 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:04:23 [INFO] uvicorn.access - 127.0.0.1:60703 - "GET /api/v1/official-site/tabs?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:04:23 [INFO] uvicorn.access - 127.0.0.1:60706 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:04:25 [INFO] uvicorn.access - 127.0.0.1:60715 - "GET /api/v1/official-site/methodology HTTP/1.1" 200
2026-06-02 14:04:25 [INFO] uvicorn.access - 127.0.0.1:60716 - "GET /api/v1/official-site/methodology HTTP/1.1" 200
2026-06-02 14:04:25 [INFO] uvicorn.access - 127.0.0.1:60731 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:04:26 [INFO] uvicorn.access - 127.0.0.1:60755 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:04:26 [INFO] uvicorn.access - 127.0.0.1:60758 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:04:26 [INFO] uvicorn.access - 127.0.0.1:60754 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 14:04:28 [INFO] uvicorn.access - 127.0.0.1:60771 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:04:28 [INFO] uvicorn.access - 127.0.0.1:60774 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:04:34 [INFO] uvicorn.access - 127.0.0.1:60818 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 14:04:34 [INFO] uvicorn.access - 127.0.0.1:60821 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:04:35 [INFO] uvicorn.access - 127.0.0.1:60833 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:04:35 [INFO] uvicorn.access - 127.0.0.1:60832 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 14:04:35 [INFO] uvicorn.access - 127.0.0.1:60836 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:04:40 [INFO] uvicorn.access - 127.0.0.1:60859 - "GET /api/v1/agents?keyword=&status=enable&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:04:40 [INFO] uvicorn.access - 127.0.0.1:60866 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:17:30 [INFO] uvicorn.access - 127.0.0.1:50050 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:17:30 [INFO] uvicorn.access - 127.0.0.1:50058 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:17:32 [INFO] uvicorn.access - 127.0.0.1:50072 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 14:17:32 [INFO] uvicorn.access - 127.0.0.1:50076 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:17:34 [INFO] uvicorn.access - 127.0.0.1:50085 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:17:34 [INFO] uvicorn.access - 127.0.0.1:50092 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:17:36 [INFO] uvicorn.access - 127.0.0.1:50104 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:17:36 [INFO] uvicorn.access - 127.0.0.1:50107 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:17:38 [INFO] uvicorn.access - 127.0.0.1:50114 - "GET /api/v1/official-site/tabs?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:17:38 [INFO] uvicorn.access - 127.0.0.1:50123 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:17:40 [INFO] uvicorn.access - 127.0.0.1:50139 - "GET /api/v1/official-site/tabs/1 HTTP/1.1" 200
2026-06-02 14:17:40 [INFO] uvicorn.access - 127.0.0.1:50140 - "GET /api/v1/official-site/tabs/1/agents/available HTTP/1.1" 200
2026-06-02 14:17:40 [INFO] uvicorn.access - 127.0.0.1:50143 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:17:45 [INFO] uvicorn.access - 127.0.0.1:50168 - "GET /api/v1/official-site/tabs?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:17:45 [INFO] uvicorn.access - 127.0.0.1:50173 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:21:37 [INFO] uvicorn.access - 127.0.0.1:51449 - "GET /api/v1/official-site/tabs/qrcodes/available HTTP/1.1" 200
2026-06-02 14:25:23 [INFO] uvicorn.access - 127.0.0.1:52676 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:25:23 [INFO] uvicorn.access - 127.0.0.1:52675 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 14:25:23 [INFO] uvicorn.access - 127.0.0.1:52680 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:25:32 [INFO] uvicorn.access - 127.0.0.1:52751 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:25:33 [INFO] uvicorn.access - 127.0.0.1:52754 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:25:50 [INFO] uvicorn.access - 127.0.0.1:52875 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:25:50 [INFO] uvicorn.access - 127.0.0.1:52878 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:25:51 [INFO] uvicorn.access - 127.0.0.1:52887 - "POST /api/v1/analytics/events HTTP/1.1" 200
2026-06-02 14:25:56 [INFO] uvicorn.access - 127.0.0.1:52924 - "POST /api/v1/position-tags HTTP/1.1" 201
2026-06-02 14:25:56 [INFO] uvicorn.access - 127.0.0.1:52940 - "POST /api/v1/analytics/events HTTP/1.1" 200
2026-06-02 14:25:56 [INFO] uvicorn.access - 127.0.0.1:52944 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:25:56 [INFO] uvicorn.access - 127.0.0.1:52951 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:26:02 [INFO] uvicorn.access - 127.0.0.1:52980 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:26:02 [INFO] uvicorn.access - 127.0.0.1:52983 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:26:09 [INFO] uvicorn.access - 127.0.0.1:53030 - "GET /api/v1/position-tags?keyword=ll&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:26:09 [INFO] uvicorn.access - 127.0.0.1:53033 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:26:12 [INFO] uvicorn.access - 127.0.0.1:53050 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:26:12 [INFO] uvicorn.access - 127.0.0.1:53053 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:27:30 [INFO] uvicorn.access - 127.0.0.1:53470 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 14:27:30 [INFO] uvicorn.access - 127.0.0.1:53475 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:27:34 [INFO] uvicorn.access - 127.0.0.1:53503 - "GET /api/v1/skills/skill_skill HTTP/1.1" 200
2026-06-02 14:27:34 [INFO] uvicorn.access - 127.0.0.1:53500 - "POST /api/v1/analytics/events HTTP/1.1" 200
2026-06-02 14:27:36 [INFO] uvicorn.access - 127.0.0.1:53521 - "GET /api/v1/skills/skill_skill HTTP/1.1" 200
2026-06-02 14:27:36 [INFO] uvicorn.access - 127.0.0.1:53518 - "POST /api/v1/analytics/events HTTP/1.1" 200
2026-06-02 14:27:40 [INFO] uvicorn.access - 127.0.0.1:53538 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:27:40 [INFO] uvicorn.access - 127.0.0.1:53541 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:27:41 [INFO] uvicorn.access - 127.0.0.1:53548 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 14:27:41 [INFO] uvicorn.access - 127.0.0.1:53551 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:27:42 [INFO] uvicorn.access - 127.0.0.1:53567 - "GET /api/v1/skills/skill_skill HTTP/1.1" 200
2026-06-02 14:27:43 [INFO] uvicorn.access - 127.0.0.1:53564 - "POST /api/v1/analytics/events HTTP/1.1" 200
2026-06-02 14:27:53 [INFO] uvicorn.access - 127.0.0.1:53631 - "POST /api/v1/analytics/events HTTP/1.1" 200
2026-06-02 14:27:53 [INFO] uvicorn.access - 127.0.0.1:53634 - "GET /api/v1/skills/skill_skill HTTP/1.1" 200
2026-06-02 14:33:24 [INFO] uvicorn.access - 127.0.0.1:56003 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:33:24 [INFO] uvicorn.access - 127.0.0.1:56006 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:33:27 [INFO] uvicorn.access - 127.0.0.1:56026 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:33:27 [INFO] uvicorn.access - 127.0.0.1:56028 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:33:27 [INFO] uvicorn.access - 127.0.0.1:56025 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 14:33:44 [INFO] uvicorn.access - 127.0.0.1:56135 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:33:44 [INFO] uvicorn.access - 127.0.0.1:56137 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:33:44 [INFO] uvicorn.access - 127.0.0.1:56134 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 14:33:45 [INFO] uvicorn.access - 127.0.0.1:56146 - "GET /api/v1/agents?keyword=&position_id=1&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:33:45 [INFO] uvicorn.access - 127.0.0.1:56147 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:33:54 [INFO] uvicorn.access - 127.0.0.1:56192 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:33:54 [INFO] uvicorn.access - 127.0.0.1:56195 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:33:58 [INFO] uvicorn.access - 127.0.0.1:56220 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:33:58 [INFO] uvicorn.access - 127.0.0.1:56223 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:34:00 [INFO] uvicorn.access - 127.0.0.1:56247 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:34:01 [INFO] uvicorn.access - 127.0.0.1:56250 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:34:01 [INFO] uvicorn.access - 127.0.0.1:56246 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 14:34:13 [INFO] uvicorn.access - 127.0.0.1:56313 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:34:13 [INFO] uvicorn.access - 127.0.0.1:56318 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:34:23 [INFO] uvicorn.access - 127.0.0.1:56368 - "GET /api/v1/position-tags?keyword=23&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:34:23 [INFO] uvicorn.access - 127.0.0.1:56373 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:34:32 [INFO] uvicorn.access - 127.0.0.1:56431 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:34:34 [INFO] uvicorn.access - 127.0.0.1:56455 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:41:06 [INFO] uvicorn.access - 127.0.0.1:58929 - "GET /api/v1/position-tags?keyword=w&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:41:06 [INFO] uvicorn.access - 127.0.0.1:58934 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:43:18 [INFO] uvicorn.access - 127.0.0.1:59895 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:43:18 [INFO] uvicorn.access - 127.0.0.1:59897 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:43:19 [INFO] uvicorn.access - 127.0.0.1:59894 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 14:43:20 [INFO] uvicorn.access - 127.0.0.1:59915 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 14:43:21 [INFO] uvicorn.access - 127.0.0.1:59916 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 14:43:21 [INFO] uvicorn.access - 127.0.0.1:59926 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 14:43:21 [INFO] uvicorn.access - 127.0.0.1:59935 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:16:34 [INFO] uvicorn.access - 127.0.0.1:56558 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:17:00 [INFO] uvicorn.access - 127.0.0.1:56724 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:18:13 [INFO] uvicorn.access - 127.0.0.1:57303 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:18:14 [INFO] uvicorn.access - 127.0.0.1:57315 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:20:36 [INFO] uvicorn.access - 127.0.0.1:58228 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:20:36 [INFO] uvicorn.access - 127.0.0.1:58231 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:20:36 [INFO] uvicorn.access - 127.0.0.1:58227 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 15:20:38 [INFO] uvicorn.access - 127.0.0.1:58246 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:20:38 [INFO] uvicorn.access - 127.0.0.1:58253 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:20:40 [INFO] uvicorn.access - 127.0.0.1:58260 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 15:20:40 [INFO] uvicorn.access - 127.0.0.1:58264 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:20:43 [INFO] uvicorn.access - 127.0.0.1:58281 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:20:43 [INFO] uvicorn.access - 127.0.0.1:58284 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:21:28 [INFO] uvicorn.access - 127.0.0.1:58543 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:21:28 [INFO] uvicorn.access - 127.0.0.1:58546 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:21:28 [INFO] uvicorn.access - 127.0.0.1:58542 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 15:21:29 [INFO] uvicorn.access - 127.0.0.1:58553 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 15:21:29 [INFO] uvicorn.access - 127.0.0.1:58556 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:21:30 [INFO] uvicorn.access - 127.0.0.1:58564 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:21:31 [INFO] uvicorn.access - 127.0.0.1:58571 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:21:33 [INFO] uvicorn.access - 127.0.0.1:58586 - "GET /api/v1/position-tags?keyword=ll&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:21:33 [INFO] uvicorn.access - 127.0.0.1:58589 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:21:37 [INFO] uvicorn.access - 127.0.0.1:58610 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:21:37 [INFO] uvicorn.access - 127.0.0.1:58613 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:21:52 [INFO] uvicorn.access - 127.0.0.1:58678 - "GET /api/v1/position-tags?keyword=ll&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:21:52 [INFO] uvicorn.access - 127.0.0.1:58681 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:21:55 [INFO] uvicorn.access - 127.0.0.1:58694 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:21:55 [INFO] uvicorn.access - 127.0.0.1:58697 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:21:59 [INFO] uvicorn.access - 127.0.0.1:58722 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 15:21:59 [INFO] uvicorn.access - 127.0.0.1:58725 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:21:59 [INFO] uvicorn.access - 127.0.0.1:58734 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:22:00 [INFO] uvicorn.access - 127.0.0.1:58737 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:22:01 [INFO] uvicorn.access - 127.0.0.1:58744 - "GET /api/v1/official-site/tabs?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:22:01 [INFO] uvicorn.access - 127.0.0.1:58747 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:22:03 [INFO] uvicorn.access - 127.0.0.1:58764 - "GET /api/v1/official-site/methodology HTTP/1.1" 200
2026-06-02 15:22:03 [INFO] uvicorn.access - 127.0.0.1:58765 - "GET /api/v1/official-site/methodology HTTP/1.1" 200
2026-06-02 15:22:03 [INFO] uvicorn.access - 127.0.0.1:58772 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:22:16 [INFO] uvicorn.access - 127.0.0.1:58849 - "GET /api/v1/official-site/tabs?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:22:16 [INFO] uvicorn.access - 127.0.0.1:58852 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:22:19 [INFO] uvicorn.access - 127.0.0.1:58867 - "GET /api/v1/official-site/tabs/1 HTTP/1.1" 200
2026-06-02 15:22:19 [INFO] uvicorn.access - 127.0.0.1:58868 - "GET /api/v1/official-site/tabs/1/agents/available HTTP/1.1" 200
2026-06-02 15:22:19 [INFO] uvicorn.access - 127.0.0.1:58871 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:22:26 [INFO] uvicorn.access - 127.0.0.1:58906 - "GET /api/v1/official-site/tabs?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:22:26 [INFO] uvicorn.access - 127.0.0.1:58909 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:22:27 [INFO] uvicorn.access - 127.0.0.1:58919 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:22:27 [INFO] uvicorn.access - 127.0.0.1:58922 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:22:27 [INFO] uvicorn.access - 127.0.0.1:58918 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 15:22:30 [INFO] uvicorn.access - 127.0.0.1:58939 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:22:30 [INFO] uvicorn.access - 127.0.0.1:58942 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:22:30 [INFO] uvicorn.access - 127.0.0.1:58949 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 15:22:31 [INFO] uvicorn.access - 127.0.0.1:58952 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:22:32 [INFO] uvicorn.access - 127.0.0.1:58961 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:22:32 [INFO] uvicorn.access - 127.0.0.1:58964 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:22:36 [INFO] uvicorn.access - 127.0.0.1:58990 - "GET /api/v1/agent-group/employees/mounts HTTP/1.1" 200
2026-06-02 15:22:36 [INFO] uvicorn.access - 127.0.0.1:58989 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 15:22:43 [INFO] uvicorn.access - 127.0.0.1:59030 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:22:43 [INFO] uvicorn.access - 127.0.0.1:59033 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:22:44 [INFO] uvicorn.access - 127.0.0.1:59040 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:22:44 [INFO] uvicorn.access - 127.0.0.1:59043 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:22:46 [INFO] uvicorn.access - 127.0.0.1:59059 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:22:46 [INFO] uvicorn.access - 127.0.0.1:59062 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:22:46 [INFO] uvicorn.access - 127.0.0.1:59058 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 15:22:47 [INFO] uvicorn.access - 127.0.0.1:59069 - "POST /api/v1/analytics/events HTTP/1.1" 200
2026-06-02 15:22:47 [INFO] uvicorn.access - 127.0.0.1:59078 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 15:22:47 [INFO] uvicorn.access - 127.0.0.1:59077 - "GET /api/v1/agent-group/employees/mounts HTTP/1.1" 200
2026-06-02 15:22:47 [INFO] uvicorn.access - 127.0.0.1:59074 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 15:22:59 [INFO] uvicorn.access - 127.0.0.1:59174 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 15:22:59 [INFO] uvicorn.access - 127.0.0.1:59177 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 15:23:00 [INFO] uvicorn.access - 127.0.0.1:59173 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 16:22:01 [INFO] uvicorn.access - 127.0.0.1:63642 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 16:22:02 [INFO] uvicorn.access - 127.0.0.1:63648 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 16:22:03 [INFO] uvicorn.access - 127.0.0.1:63662 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 16:22:03 [INFO] uvicorn.access - 127.0.0.1:63666 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 16:22:05 [INFO] uvicorn.access - 127.0.0.1:63682 - "GET /api/v1/agent-group/employees/mounts HTTP/1.1" 200
2026-06-02 16:22:05 [INFO] uvicorn.access - 127.0.0.1:63681 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 16:22:07 [INFO] uvicorn.access - 127.0.0.1:63701 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 16:22:08 [INFO] uvicorn.access - 127.0.0.1:63710 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 16:42:42 [INFO] uvicorn.access - 127.0.0.1:55436 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 16:42:42 [INFO] uvicorn.access - 127.0.0.1:55438 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 16:42:45 [INFO] uvicorn.access - 127.0.0.1:55458 - "GET /api/v1/skills?keyword=l HTTP/1.1" 200
2026-06-02 16:42:45 [INFO] uvicorn.access - 127.0.0.1:55462 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 16:42:48 [INFO] uvicorn.access - 127.0.0.1:55480 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 16:42:48 [INFO] uvicorn.access - 127.0.0.1:55483 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 16:42:51 [INFO] uvicorn.access - 127.0.0.1:55498 - "GET /api/v1/skills?keyword=ff HTTP/1.1" 200
2026-06-02 16:42:51 [INFO] uvicorn.access - 127.0.0.1:55501 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 16:57:31 [INFO] uvicorn.access - 127.0.0.1:61040 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 16:57:31 [INFO] uvicorn.access - 127.0.0.1:61047 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 16:57:31 [INFO] uvicorn.access - 127.0.0.1:61039 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 17:03:49 [INFO] uvicorn.access - 127.0.0.1:63264 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:03:49 [INFO] uvicorn.access - 127.0.0.1:63263 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 17:03:49 [INFO] uvicorn.access - 127.0.0.1:63272 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:03:51 [INFO] uvicorn.access - 127.0.0.1:63297 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:03:51 [INFO] uvicorn.access - 127.0.0.1:63298 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:03:53 [INFO] uvicorn.access - 127.0.0.1:63311 - "GET /api/v1/position-tags?keyword=33&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:03:53 [INFO] uvicorn.access - 127.0.0.1:63314 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:04:01 [INFO] uvicorn.access - 127.0.0.1:63384 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:04:01 [INFO] uvicorn.access - 127.0.0.1:63394 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:04:05 [INFO] uvicorn.access - 127.0.0.1:63438 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:04:05 [INFO] uvicorn.access - 127.0.0.1:63441 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:04:05 [INFO] uvicorn.access - 127.0.0.1:63437 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 17:04:07 [INFO] uvicorn.access - 127.0.0.1:63462 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:04:07 [INFO] uvicorn.access - 127.0.0.1:63465 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:04:24 [INFO] uvicorn.access - 127.0.0.1:63571 - "GET /api/v1/position-tags?keyword=22&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:04:24 [INFO] uvicorn.access - 127.0.0.1:63578 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:04:27 [INFO] uvicorn.access - 127.0.0.1:63599 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:04:27 [INFO] uvicorn.access - 127.0.0.1:63602 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:04:30 [INFO] uvicorn.access - 127.0.0.1:63619 - "GET /api/v1/position-tags?keyword=22&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:04:30 [INFO] uvicorn.access - 127.0.0.1:63622 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:16:38 [INFO] uvicorn.access - 127.0.0.1:52225 - "GET /api/v1/position-tags?keyword=22&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:16:38 [INFO] uvicorn.access - 127.0.0.1:52227 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:20:22 [INFO] uvicorn.access - 127.0.0.1:53610 - "GET /api/v1/position-tags?keyword=22&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:20:23 [INFO] uvicorn.access - 127.0.0.1:53612 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:20:26 [INFO] uvicorn.access - 127.0.0.1:53636 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 17:20:26 [INFO] uvicorn.access - 127.0.0.1:53637 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:20:28 [INFO] uvicorn.access - 127.0.0.1:53653 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:20:28 [INFO] uvicorn.access - 127.0.0.1:53654 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:20:30 [INFO] uvicorn.access - 127.0.0.1:53669 - "GET /api/v1/official-site/tabs?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:20:30 [INFO] uvicorn.access - 127.0.0.1:53672 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:20:32 [INFO] uvicorn.access - 127.0.0.1:53683 - "GET /api/v1/agent-group/qrcode/list?keyword=&position_code=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:20:32 [INFO] uvicorn.access - 127.0.0.1:53686 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:20:35 [INFO] uvicorn.access - 127.0.0.1:53711 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 17:20:35 [INFO] uvicorn.access - 127.0.0.1:53714 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:20:36 [INFO] uvicorn.access - 127.0.0.1:53724 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:20:36 [INFO] uvicorn.access - 127.0.0.1:53727 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:20:49 [INFO] uvicorn.access - 127.0.0.1:53804 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 17:20:49 [INFO] uvicorn.access - 127.0.0.1:53807 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:21:11 [INFO] uvicorn.access - 127.0.0.1:53945 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 17:21:11 [INFO] uvicorn.access - 127.0.0.1:53948 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:21:50 [INFO] uvicorn.access - 127.0.0.1:54245 - "GET /health HTTP/1.1" 200
2026-06-02 17:22:07 [INFO] uvicorn.error - Shutting down
2026-06-02 17:22:07 [INFO] uvicorn.error - Waiting for application shutdown.
2026-06-02 17:22:07 [INFO] uvicorn.error - Application shutdown complete.
2026-06-02 17:22:07 [INFO] uvicorn.error - Finished server process [15260]
2026-06-02 17:27:07 [INFO] uvicorn.error - Started server process [90499]
2026-06-02 17:27:07 [INFO] uvicorn.error - Waiting for application startup.
2026-06-02 17:27:08 [INFO] app.service.agent_hub - 扫描 skills 目录并注册到全局 Toolkit: /Users/yuehu/Desktop/work/agent/workspace/agent-admin/backend/skills
2026-06-02 17:27:08 [INFO] app.service.agent_hub - 构建 agent 'main' 的专属 Toolkit (skills: [])
2026-06-02 17:27:08 [INFO] app.service.agent_hub - 构建 agent 'meeting' 的专属 Toolkit (skills: ['meeting_minutes'])
2026-06-02 17:27:08 [INFO] uvicorn.error - Application startup complete.
2026-06-02 17:27:08 [INFO] uvicorn.error - Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
2026-06-02 17:27:21 [INFO] uvicorn.access - 127.0.0.1:56333 - "GET /health HTTP/1.1" 200
2026-06-02 17:27:21 [INFO] uvicorn.access - 127.0.0.1:56334 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-02 17:27:27 [INFO] uvicorn.access - 127.0.0.1:56392 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:27:27 [INFO] uvicorn.access - 127.0.0.1:56391 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 17:27:27 [INFO] uvicorn.access - 127.0.0.1:56394 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:27:31 [INFO] uvicorn.access - 127.0.0.1:56417 - "GET /api/v1/agents?keyword=&position_id=3&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:27:31 [INFO] uvicorn.access - 127.0.0.1:56418 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:27:41 [INFO] uvicorn.access - 127.0.0.1:56486 - "POST /api/v1/analytics/events HTTP/1.1" 200
2026-06-02 17:27:42 [INFO] uvicorn.access - 127.0.0.1:56496 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:27:42 [INFO] uvicorn.access - 127.0.0.1:56501 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:27:44 [INFO] uvicorn.access - 127.0.0.1:56515 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:27:44 [INFO] uvicorn.access - 127.0.0.1:56518 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:27:44 [INFO] uvicorn.access - 127.0.0.1:56514 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 17:44:49 [INFO] uvicorn.access - 127.0.0.1:62389 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:44:49 [INFO] uvicorn.access - 127.0.0.1:62394 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:44:49 [INFO] uvicorn.access - 127.0.0.1:62388 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 17:46:11 [INFO] uvicorn.access - 127.0.0.1:62839 - "GET /api/v1/agents?keyword=&position_id=3&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:46:11 [INFO] uvicorn.access - 127.0.0.1:62842 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:46:21 [INFO] uvicorn.access - 127.0.0.1:62926 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:46:21 [INFO] uvicorn.access - 127.0.0.1:62927 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 17:46:21 [INFO] uvicorn.access - 127.0.0.1:62925 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 17:46:24 [INFO] uvicorn.access - 127.0.0.1:62939 - "POST /api/v1/analytics/events HTTP/1.1" 200
2026-06-02 17:46:24 [INFO] uvicorn.access - 127.0.0.1:62940 - "GET /api/v1/agents?keyword=3&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 17:46:24 [INFO] uvicorn.access - 127.0.0.1:62941 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-02 18:24:01 [INFO] uvicorn.access - 127.0.0.1:60158 - "GET /api/v1/agents?keyword=3&page=1&page_size=10 HTTP/1.1" 200
2026-06-02 18:24:01 [INFO] uvicorn.access - 127.0.0.1:60157 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-02 18:24:01 [INFO] uvicorn.access - 127.0.0.1:60161 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 09:32:47 [INFO] uvicorn.access - 127.0.0.1:56925 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 09:32:47 [INFO] uvicorn.access - 127.0.0.1:56929 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 09:32:49 [INFO] uvicorn.access - 127.0.0.1:56957 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-03 09:32:49 [INFO] uvicorn.access - 127.0.0.1:56964 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 09:32:50 [INFO] uvicorn.access - 127.0.0.1:56977 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 09:32:50 [INFO] uvicorn.access - 127.0.0.1:56976 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-03 09:32:50 [INFO] uvicorn.access - 127.0.0.1:56980 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 09:39:23 [INFO] uvicorn.access - 127.0.0.1:59657 - "GET /api/v1/agents?keyword=&position_id=3&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 09:39:23 [INFO] uvicorn.access - 127.0.0.1:59660 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 09:43:25 [INFO] uvicorn.access - 127.0.0.1:61115 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 09:43:25 [INFO] uvicorn.access - 127.0.0.1:61118 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 09:43:25 [INFO] uvicorn.access - 127.0.0.1:61114 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-03 09:51:31 [INFO] uvicorn.access - 127.0.0.1:63746 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 09:51:31 [INFO] uvicorn.access - 127.0.0.1:63747 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 09:51:31 [INFO] uvicorn.access - 127.0.0.1:63745 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-03 09:51:37 [INFO] uvicorn.access - 127.0.0.1:63787 - "GET /api/v1/agents?keyword=&position_id=1&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 09:51:39 [INFO] uvicorn.access - 127.0.0.1:63802 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 09:51:55 [INFO] uvicorn.access - 127.0.0.1:63863 - "GET /api/v1/agents?keyword=&position_id=2&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 09:51:55 [INFO] uvicorn.access - 127.0.0.1:63890 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 09:52:11 [INFO] uvicorn.access - 127.0.0.1:63986 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-03 09:52:11 [INFO] uvicorn.access - 127.0.0.1:63987 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 09:52:11 [INFO] uvicorn.access - 127.0.0.1:63994 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 09:52:11 [INFO] uvicorn.access - 127.0.0.1:63997 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 09:52:13 [INFO] uvicorn.access - 127.0.0.1:64016 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 09:52:13 [INFO] uvicorn.access - 127.0.0.1:64019 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 09:52:13 [INFO] uvicorn.access - 127.0.0.1:64015 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-03 09:52:14 [INFO] uvicorn.access - 127.0.0.1:64026 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 09:52:14 [INFO] uvicorn.access - 127.0.0.1:64033 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 10:01:41 [INFO] uvicorn.access - 127.0.0.1:51798 - "GET /api/v1/position-tags?keyword=23&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 10:01:41 [INFO] uvicorn.access - 127.0.0.1:51805 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 10:01:46 [INFO] uvicorn.access - 127.0.0.1:51836 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 10:01:46 [INFO] uvicorn.access - 127.0.0.1:51840 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 10:01:50 [INFO] uvicorn.access - 127.0.0.1:51872 - "GET /api/v1/position-tags?keyword=23&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 10:01:50 [INFO] uvicorn.access - 127.0.0.1:51881 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 10:01:53 [INFO] uvicorn.access - 127.0.0.1:51894 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 10:01:53 [INFO] uvicorn.access - 127.0.0.1:51899 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 10:01:58 [INFO] uvicorn.access - 127.0.0.1:51942 - "GET /api/v1/position-tags?keyword=23&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 10:02:00 [INFO] uvicorn.access - 127.0.0.1:51970 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 10:03:12 [INFO] uvicorn.access - 127.0.0.1:52449 - "POST /api/v1/analytics/events HTTP/1.1" 200
2026-06-03 10:03:12 [INFO] uvicorn.access - 127.0.0.1:52461 - "POST /api/v1/analytics/events HTTP/1.1" 200
2026-06-03 10:03:18 [INFO] uvicorn.access - 127.0.0.1:52505 - "GET /api/v1/position-tags?keyword=23&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 10:03:18 [INFO] uvicorn.access - 127.0.0.1:52508 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 10:03:19 [INFO] uvicorn.access - 127.0.0.1:52520 - "GET /api/v1/agents?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 10:03:19 [INFO] uvicorn.access - 127.0.0.1:52523 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 10:03:19 [INFO] uvicorn.access - 127.0.0.1:52519 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-03 10:03:20 [INFO] uvicorn.access - 127.0.0.1:52534 - "POST /api/v1/analytics/events HTTP/1.1" 200
2026-06-03 10:03:20 [INFO] uvicorn.access - 127.0.0.1:52542 - "GET /api/v1/agent-group/employees/mounts HTTP/1.1" 200
2026-06-03 10:03:20 [INFO] uvicorn.access - 127.0.0.1:52543 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-03 10:03:20 [INFO] uvicorn.access - 127.0.0.1:52541 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
2026-06-03 10:39:04 [INFO] uvicorn.access - 127.0.0.1:64941 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 10:39:04 [INFO] uvicorn.access - 127.0.0.1:64954 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 10:39:07 [INFO] uvicorn.access - 127.0.0.1:64980 - "GET /api/v1/position-tags?keyword=%EF%BC%9B&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 10:39:07 [INFO] uvicorn.access - 127.0.0.1:64986 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 10:39:17 [INFO] uvicorn.access - 127.0.0.1:65055 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 10:39:20 [INFO] uvicorn.access - 127.0.0.1:65076 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 10:39:23 [INFO] uvicorn.access - 127.0.0.1:65103 - "GET /api/v1/position-tags?keyword=ll&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 10:39:25 [INFO] uvicorn.access - 127.0.0.1:65130 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 10:40:32 [INFO] uvicorn.access - 127.0.0.1:65526 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 10:40:34 [INFO] uvicorn.access - 127.0.0.1:49154 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 10:40:41 [INFO] uvicorn.access - 127.0.0.1:49193 - "GET /api/v1/position-tags?keyword=ewe&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 10:40:43 [INFO] uvicorn.access - 127.0.0.1:49218 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 10:48:37 [INFO] uvicorn.access - 127.0.0.1:52499 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 10:48:39 [INFO] uvicorn.access - 127.0.0.1:52513 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 13:16:21 [INFO] uvicorn.access - 127.0.0.1:61574 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 13:16:23 [INFO] uvicorn.access - 127.0.0.1:61586 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 14:24:17 [INFO] uvicorn.access - 127.0.0.1:64774 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 14:24:19 [INFO] uvicorn.access - 127.0.0.1:64784 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 14:28:42 [INFO] uvicorn.access - 127.0.0.1:50026 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 14:28:44 [INFO] uvicorn.access - 127.0.0.1:50042 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 14:35:02 [INFO] uvicorn.access - 127.0.0.1:52461 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 14:35:04 [INFO] uvicorn.access - 127.0.0.1:52472 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 14:37:16 [INFO] uvicorn.access - 127.0.0.1:53345 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 14:37:18 [INFO] uvicorn.access - 127.0.0.1:53356 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 14:39:35 [INFO] uvicorn.access - 127.0.0.1:54398 - "GET /api/v1/position-tags?keyword=&page=1&page_size=10 HTTP/1.1" 200
2026-06-03 14:39:37 [INFO] uvicorn.access - 127.0.0.1:54443 - "POST /api/v1/agent-group/analytics/page-view HTTP/1.1" 200
2026-06-03 15:07:31 [INFO] uvicorn.access - 127.0.0.1:49532 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-03 15:07:31 [INFO] uvicorn.access - 127.0.0.1:49531 - "GET /api/v1/agent-group/employees/mounts HTTP/1.1" 200
2026-06-03 15:07:34 [INFO] uvicorn.access - 127.0.0.1:49566 - "GET /api/v1/agent-group/employees/mounts HTTP/1.1" 200
2026-06-03 15:07:34 [INFO] uvicorn.access - 127.0.0.1:49567 - "GET /api/v1/skills HTTP/1.1" 200
2026-06-03 15:07:34 [INFO] uvicorn.access - 127.0.0.1:49565 - "GET /api/v1/position-tags?page=1&page_size=100 HTTP/1.1" 200
This diff could not be displayed because it is too large.
# Admin UI 运行时依赖迁移基线
## 范围
- 扫描目录:`workspace/agent-admin/web/src`
- 通过 TypeScript AST 统计运行时代码中的静态 import、副作用 import、动态 import 与运行时 re-export;纯类型 import 不计入门禁。
- 排除 `*.test.*` 测试文件。
- 本轮暂不删除 `workspace/agent-admin/web/packages/ui`。
## 扫描命令
```bash
npm run scan:local-ui-runtime-deps
```
最终零依赖门禁:
```bash
npm run check:local-ui-runtime-deps
```
## 初始结果
2026-05-31 扫描结果:18 个运行时代码文件,共 19 条指向 `packages/ui` 的 import 声明。
## 业务组合组件盘点
| 组件 | 公开能力 | 现有测试覆盖 | 本轮目标 |
| --- | --- | --- | --- |
| `SearchFilter` | 输入、数字输入、选择、日期、日期范围、受控值、默认值、草稿搜索、重置、展开收起 | 默认选项、数字清洗、默认 placeholder、展开收起、重置 | 提升到 `@gl/business-components`,内部直接使用 TDesign |
| `StatePlaceholder` | 空数据、筛选空数据、错误、无权限、离线状态;自定义标题、描述、图标和操作 | 错误态、默认状态、角色语义、表格空态组合 | 提升到 `@gl/business-components`,内部直接使用 TDesign 图标 |
| `MediaWall` | 图片和视频回填、上传选择、内置图片预览、自定义预览、删除、数量上限、禁用状态 | 图片、视频、预览、选择、删除、数量上限、表单组合 | 提升到 `@gl/business-components`,内部直接使用 TDesign Upload |
## 后续记录
第 2 组任务完成后,全局组合组件内部必须不再依赖 `workspace/agent-admin/web/packages/ui`。页面 import 的替换属于后续任务,本批次不处理。
# 全局搜索筛选组件实施计划
## 对应 OpenSpec
- Change: `global-search-filter-component`
- Capability: `global-search-filter`
## 实施顺序
1. 先阅读现有 UI 组件、测试工具、demo 入口和导出模式,确认组件落点。
2. 用 TDD 先写 `SearchFilter` 组件测试:
- `input`、`numberInput`、`select`、单日期、范围日期配置渲染。
- `numberInput` 过滤非数字字符。
- `select` 自动展示并默认选中“全部”。
- 搜索、重置回调。
- 字段超过两行时展示“展开”与向下箭头。
- 展开后展示“收起”与向上箭头。
- 搜索/重置按钮在折叠状态仍可见。
3. 实现组件:
- 新建组件目录、类型、样式与导出。
- 复用现有 `Input`、`Select`、`DatePicker`、`DateRangePicker`、`Button`。
- 实现数字输入过滤和 select “全部”选项注入。
- 用固定网格项宽度实现普通控件 `200px`,范围日期跨两项。
- 用测量高度与 CSS transition 实现展开/收起动画。
4. 接入 demo:
- 增加包含多字段的 demo 配置。
- 字段数量超过两行,覆盖输入框、仅数字输入框、下拉框、单日期、范围日期。
- demo 展示 select 默认“全部”和数字输入过滤效果。
- demo 保持受控状态,可验证搜索与重置。
5. 验证:
- 运行相关测试并确认由失败变通过。
- 运行 `npm run typecheck`、`npm test` 或等价测试命令、`npm run build`。
- 启动本地 demo,用浏览器验证桌面布局、动画、按钮固定、数字输入过滤和 select 默认“全部”。
- 检查现有业务列表页未被迁移或改变。
## 暂不做
- 不迁移现有列表页搜索区域。
- 不改业务查询逻辑、URL 参数同步或接口调用。
- 不新增外部依赖。
# Textarea 迁移到 TDesign 实施计划
日期:2026-05-30
## 目标
替换官网岗位 Tab 编辑页和组件库 Demo 页中的页面级多行输入使用点,不修改 `packages/ui/Textarea`。
## 步骤
1. 运行 OpenSpec 校验,确认 `migrate-textarea-to-tdesign` artifacts 完整。
2. 更新 `OfficialSiteJobTabEditorPage.test.tsx`,覆盖岗位说明字段替换后仍可输入。
3. 更新 `OfficialSiteJobTabEditorPage.tsx`,直接使用 `tdesign-react` 的 `Textarea` 替换原生 `<textarea>`。
4. 更新 `ComponentsDemoPage.test.tsx`,覆盖 Demo 多行输入示例使用 TDesign Textarea。
5. 更新 `ComponentsDemoPage.tsx`,直接使用 `tdesign-react` 的 `Textarea` 替换 Demo 多行输入示例。
6. 确认 `packages/ui/src/components/Textarea.tsx` 未修改。
7. 运行相关测试、类型检查、构建,并用浏览器验证岗位说明字段和 Demo 多行输入示例。
# admin-agent 后台 UI 依赖迁移实施计划
## 目标
让 `workspace/agent-admin/web/src` 不再运行时依赖 `workspace/agent-admin/web/packages/ui`。基础控件改为直接使用 TDesign,业务组合组件改为从根目录 `@gl/business-components` 复用。旧 `packages/ui` 目录保留,等待后续独立清理。
## 执行原则
- 只调整 UI 依赖边界,不改变页面业务行为、路由和 API 契约。
- 每一批先更新或补充测试,确认失败后再实施最小替换。
- 遇到 TDesign API 差异时,以保留现有交互为优先,不引入额外抽象。
- 编辑页表单直接使用 TDesign `Form`、`FormItem` 和基础控件,本轮不引入配置化表单渲染器。
- 不删除 `workspace/agent-admin/web/packages/ui`。
- 不处理 `workspace/agent-admin/single-page`。
## 批次一:建立全局业务组件
### SearchFilter
- 从本地 `packages/ui` 提取现有公开属性与行为。
- 在 `packages/business-components` 增加失败测试,覆盖输入草稿、查询提交、重置、状态筛选和日期筛选。
- 将实现迁入全局包,内部改用 TDesign。
- 更新全局导出入口。
### StatePlaceholder
- 增加失败测试,覆盖加载、空数据、错误态和可选操作。
- 迁入全局包,内部优先组合 TDesign `Loading`、`Empty` 和按钮能力。
- 更新全局导出入口。
### MediaWall
- 增加失败测试,覆盖上传成功、上传失败、预览、删除和 URL 回填。
- 迁入全局包,内部使用 TDesign 上传与反馈能力。
- 保留现有上传契约,不调整 API 路径和 `usage_type`。
## 批次二:共享入口与详情抽屉
- 将 `src/layouts/AdminShell.tsx` 中的 `Modal` 改为 TDesign。
- 将 `src/hooks/useMessage.tsx` 中的 `Message` 改为 TDesign。
- 迁移 Agent、渠道活码、Skill 的详情抽屉。
- 测试重点:抽屉开关、状态占位、操作按钮和消息反馈。
## 批次三:列表页
- 迁移 Agent、岗位标签、渠道活码、官网岗位展示配置、Skill 列表页。
- 基础控件直接使用 TDesign。
- 搜索区和状态占位从 `@gl/business-components` 引入。
- 测试重点:查询、重置、分页、二次确认、状态标签和行操作。
## 批次四:编辑页与官网配置
- 迁移 Agent、岗位标签、渠道活码编辑页。
- 迁移官网方法论配置、Agent 展示配置、岗位展示新增编辑页。
- 覆盖剩余旧 `Textarea` 使用点。
- 保留页面级字段联动和复杂内容组合,不改写为配置协议。
- 测试重点:字段受控状态、校验、开关、选择器、上传、提交和错误反馈。
## 批次五:组件 Demo
- 将 Demo 中基础控件、展示组件、导航组件和反馈组件改为 TDesign。
- 将 `SearchFilter`、`StatePlaceholder`、`MediaWall` 改为全局组件。
- 删除 Demo 对旧本地 UI 包 import 和旧样式实现细节的依赖。
- 测试重点:Demo 可渲染、关键输入可编辑、弹窗和抽屉可打开。
## 最终门禁
### 静态扫描
```bash
rg -n "packages/ui" workspace/agent-admin/web/src
```
期望结果:没有指向旧本地 UI 包的运行时 import。
### 自动化验证
```bash
npm test
npm run typecheck
npm run build
openspec validate "migrate-admin-ui-to-global-tdesign" --strict
```
### 浏览器验证
- 验证主要列表页的搜索、重置、分页和弹窗。
- 验证主要编辑页的输入、选择、开关、上传和提交。
- 验证 `/components` 可展示并交互使用 TDesign 与全局业务组件。
## 完成定义
- `workspace/agent-admin/web/src` 对本地 `packages/ui` 零运行时依赖。
- 全局业务组件从 `@gl/business-components` 导出。
- 旧 `packages/ui` 目录仍然保留。
- 测试、类型检查、构建、OpenSpec 严格校验和浏览器验证均通过。
## 后续独立试点
迁移完成后,如需减少简单编辑页的重复代码,另开 OpenSpec change 验证全局 `BusinessForm` 或 `FormRenderer`:
- 先选择两个字段结构重复、交互简单的编辑页试点。
- 配置项只覆盖高频基础字段、基础校验、默认值和简单显隐。
- 必须提供 `children` 或 `render` 逃生口,复杂内容继续使用手写 TDesign `FormItem`。
- 不把上传、媒体墙、动态数组、多层级联动或复杂业务逻辑纳入通用协议。
# Components Demo 表格状态 TDD 实施计划
日期:2026-06-05
## 目标
按已确认的 OpenSpec,把 `ComponentsDemoPage` 中所有表格状态示例迁移为 `BusinessTable` 真实渲染,并移除 demo 中旧的表格语义 `StatePlaceholder` 示例。
## TDD 步骤
1. 更新 `ComponentsDemoPage.test.tsx`:
- 断言“表格与分页”区域展示 `BusinessTable` 的有数据、普通空态、筛选无结果、请求失败、权限受限和加载中示例。
- 断言旧说明文案和旧按钮不再出现。
- 断言“导航与占位”区域不再展示旧表格状态集合。
2. 运行 `rtk npm test -- ComponentsDemoPage.test.tsx`,确认测试先失败。
3. 修改 `ComponentsDemoPage.tsx`:
- 移除裸 TDesign `Empty` 表格示例。
- 在“表格与分页”区域加入多个 `BusinessTable` 状态示例。
- 清理“导航与占位”中的表格状态 `StatePlaceholder` 集合。
4. 修改必要 CSS,保持 demo 布局稳定、可扫读。
5. 运行相关测试、类型检查、OpenSpec validate,并做浏览器布局检查。
# 全局搜索筛选组件设计
日期:2026-05-29
## 背景
当前后台列表页的搜索区域由页面内 Tailwind 结构临时拼装,典型页面包括 `AgentListPage`、`AgentTagListPage`、`OfficialSiteJobTabListPage`。这些实现已经出现重复:
- 每个筛选项都是左侧 label、右侧控件。
- 普通输入框和下拉框宽度固定为 200px。
- 搜索、重置按钮固定在搜索区右侧。
- 输入框按 Enter 触发搜索。
- 页面需要在筛选项数量增加时保持最多两行,并提供展开/收起能力。
用户补充要求:该能力需要做成全局组件。
## 目标
在全局 UI 包 `workspace/agent-admin/web/packages/ui/src/components` 新增可复用搜索筛选组件,并从 `packages/ui/src/index.ts` 导出。组件通过配置项渲染搜索区域,支持 `input`、`numberInput`、`select`、`datePicker` 四类字段,统一列表页筛选区的布局、按钮位置、默认筛选项和折叠行为。第一阶段已在 demo 中展示组件能力;用户确认后,第二阶段迁移当前已有列表页搜索区域。
## 非目标
- 不在本次设计中修改后端接口、路由参数解析规则或业务筛选语义。
- 不引入新表单库。
- 不替换页面标题区、表格工具栏、表格和分页组件。
- 不把复杂业务自定义控件纳入第一版配置项;如后续需要可通过扩展字段类型或 `render` 插槽单独设计。
- 第二阶段不迁移编辑页、弹窗表单或非列表搜索区域。
## 现状观察
现有全局 UI 包已经提供:
- `Input`
- `Select`
- `DatePicker`
- `DateRangePicker`
- `Button`
搜索区当前散落在业务页面中,样式结构主要是:
- 外层:圆角边框容器、白色背景、内边距。
- 字段:`flex items-center gap-2 text-sm`。
- 控件容器:`w-[200px]`。
- 按钮:`搜索` 主按钮、`重置` outline 按钮。
## 方案比较
### 方案一:只提供布局容器,字段由页面手写
页面继续写 `Input`、`Select`、`DatePicker`,全局组件只负责两行折叠和按钮区。
优点:灵活,迁移成本低。
缺点:无法保证字段宽度、label 结构和 type 配置一致;不满足“通过配置项渲染”的核心诉求。
### 方案二:提供配置驱动组件
新增 `SearchFilter`,由 `fields` 配置生成字段和控件;页面只维护筛选值、搜索、重置逻辑。
优点:直接满足配置驱动和全局复用;布局、宽度、展开/收起规则集中维护;适合后台列表页复用。
缺点:字段类型需要逐步扩展;业务侧复杂定制需要保留逃逸口。
### 方案三:封装完整查询状态和路由同步
组件同时管理字段状态、搜索提交、重置和 URL query 同步。
优点:页面代码最少。
缺点:会和各页面现有 routeState、埋点、分页重置、接口参数转换强耦合,改动面大。
## 推荐方案
采用方案二:配置驱动的全局 `SearchFilter` 组件。
组件只负责 UI 渲染和交互触发,不接管业务状态和 URL 同步。页面通过受控值和回调保持现有业务逻辑,后续可逐步迁移列表页。
## 组件 API 草案
```ts
export type SearchFilterField =
| SearchFilterInputField
| SearchFilterNumberInputField
| SearchFilterSelectField
| SearchFilterDatePickerField;
interface SearchFilterBaseField {
key: string;
label: string;
placeholder?: string;
testId?: string;
ariaLabel?: string;
}
interface SearchFilterInputField extends SearchFilterBaseField {
type: 'input';
value: string;
allowClear?: boolean;
onChange: (value: string) => void;
}
interface SearchFilterNumberInputField extends SearchFilterBaseField {
type: 'numberInput';
value: string;
allowClear?: boolean;
onChange: (value: string) => void;
}
interface SearchFilterSelectField extends SearchFilterBaseField {
type: 'select';
value?: string;
options: SelectOption[];
allowClear?: boolean;
onChange: (value: string | undefined, option: SelectOption | undefined) => void;
}
interface SearchFilterDatePickerField extends SearchFilterBaseField {
type: 'datePicker';
value?: string | [string, string];
range?: boolean;
onChange: (value: string | [string, string]) => void;
}
interface SearchFilterProps {
fields: SearchFilterField[];
onSearch: () => void;
onReset: () => void;
searchText?: string;
resetText?: string;
defaultExpanded?: boolean;
className?: string;
'data-testid'?: string;
}
```
说明:
- `datePicker` 默认渲染单日期 `DatePicker`。
- 当 `datePicker.range === true` 时渲染 `DateRangePicker`。
- `numberInput` 仅允许输入数字字符。
- `select` 由组件统一补充“全部”选项;当 `value` 为空、`undefined` 或 `null` 时默认显示选中“全部”。
- 第一版只支持单选 `Select`,多选后续如有页面场景再扩展。
- `onSearch` 由搜索按钮和 input Enter 触发。
- `onReset` 只由重置按钮触发,字段值重置仍由页面业务状态负责。
- `input` 未显式传入 `placeholder` 时默认展示 `搜索${label}`。
- `numberInput` 未显式传入 `placeholder` 时默认展示 `请输入数字`。
- 显式传入 `placeholder` 时优先使用显式文案。
## 布局规则
- 外层搜索区域是一个全局组件容器,使用现有后台列表页风格:边框、背景、内边距、8px 以内圆角。
- 每一项采用左右结构:`label: control`。
- 普通 `input`、`numberInput` 和 `select` 控件宽度固定 200px。
- 单日期 `datePicker` 控件按普通控件处理,宽度 200px。
- 日期范围选择框占满两项宽度,建议字段项宽度为 `200px * 2 + 字段间距`,在栅格中跨两列。
- 搜索/重置按钮区域固定在右下角,不参与收起。
- 默认最多展示两行,且这两行包含按钮区域占位。
- 当字段超过两行可容纳数量时展示“展开/收起”按钮。
- 收起状态只隐藏超出的字段,搜索/重置按钮始终可见。
- 展开/收起按钮建议放在操作区搜索/重置按钮左侧,避免在字段区造成额外换行。
- 窄屏时允许字段自然换行,但控件宽度规则仍保持 200px;日期范围在空间不足时独占整行。
## 折叠判定
组件不依赖浏览器测量。第一版按字段权重做确定性计算:
- 普通字段权重为 1。
- 日期范围字段权重为 2。
- 按钮区占 1 个权重位。
- 收起状态最多展示 `2 行 * 每行可容纳项数 - 按钮区权重` 的字段。
为保证行为可预测,组件可采用 CSS Grid:
- 每个普通字段固定列宽。
- 日期范围字段 `grid-column: span 2`。
- 操作区通过 `margin-left: auto` 或独立 actions 容器固定在右下角。
如果实现阶段发现响应式下纯权重计算不足以覆盖真实布局,可把“是否有超出字段”的判断保持为权重规则,视觉布局交给 CSS 换行。
## 测试策略
新增 `SearchFilter.test.tsx` 覆盖:
- 根据 `input`、`select`、`datePicker` 配置渲染 label 和控件。
- `numberInput` 过滤非数字字符。
- `select` 自动展示“全部”选项,并在未传入明确值时默认选中“全部”。
- input 按 Enter 触发 `onSearch`。
- 搜索按钮触发 `onSearch`,重置按钮触发 `onReset`。
- input/select 控件容器具备固定 200px 宽度类或等价样式。
- 日期范围字段具备跨两项宽度的类或等价样式。
- 字段超过收起阈值时显示展开/收起,点击后展示或隐藏溢出字段。
- 收起时搜索/重置按钮仍可见。
业务页面迁移会在用户确认 demo 后进入第二阶段,并补充每个页面的搜索、重置、URL 查询参数和 placeholder 回归测试。
## 第二阶段列表页迁移映射
- `AgentListPage`:`Agent名称` 使用 `input`,placeholder 走默认规则为“搜索Agent名称”;`所属岗位`、`状态` 使用 `select`,由组件提供“全部”。
- `SkillListPage`:`关键词` 使用 `input`,显式 placeholder 为“搜索Skill名称或编码”。
- `ChannelCodeListPage`:`活码名称` 使用 `input`,placeholder 走默认规则为“搜索活码名称”;`状态` 使用 `select`,由组件提供“全部”,状态选择进入草稿,点击搜索提交。
- `AgentTagListPage`:`标签名称` 使用 `input`,placeholder 走默认规则为“搜索标签名称”。
- `OfficialSiteJobTabListPage`:`关键词` 使用 `input`,显式 placeholder 为“搜索岗位名称或渠道活码”;`展示状态` 使用 `select`,由组件提供“全部”,组件空字符串在提交时映射到页面既有 `all`。
## 实施顺序
1. 创建 OpenSpec change `global-search-filter-component`。
2. 锁定 proposal、design、spec 和 tasks。
3. 按 TDD 新增全局组件测试。
4. 实现 `SearchFilter.tsx` 和样式文件。
5. 从 `packages/ui/src/index.ts` 导出组件和类型。
6. 在 demo 中展示足够多字段,覆盖普通输入、数字输入、下拉、单日期和范围日期。
7. 运行 `npm run typecheck`、相关测试、`npm test`、`npm run build`。
8. 用户确认组件后,更新 OpenSpec 文档和任务清单,进入第二阶段迁移。
9. 先补 placeholder 默认规则测试,再更新组件默认 placeholder。
10. 按页面逐个迁移搜索区并补回归测试。
11. 运行 `SearchFilter` 测试、受影响页面测试、`npm run typecheck`、`npm run build`。本阶段按用户要求不进行浏览器验证。
## 待确认问题
用户已确认:支持单日期和范围日期;第一阶段只在 demo 展示组件;展开/收起按钮放在搜索/重置左侧并显示方向箭头;新增 `numberInput` 数字输入;所有 select 默认包含并选中“全部”;组件确认后迁移当前已有列表页搜索区域;`input` 默认 placeholder 为“搜索 + label”,`numberInput` 默认 placeholder 为“请输入数字”。
# 岗位说明 Textarea 页面级替换设计
日期:2026-05-30
## 背景
`agent-admin/web` 已接入 `tdesign-react`。当前官网岗位 Tab 编辑页仍存在一处页面级原生 `<textarea>`,组件库 Demo 页的多行输入示例也仍通过 `packages/ui/Textarea` 展示旧实现,与工作区“基础 UI 逐步使用 TDesign”的方向不一致。根据用户最新确认,本次不修改 `packages/ui/Textarea`,只处理页面里的多行输入使用点。
## 目标
- 将官网岗位 Tab 编辑页中的原生 `<textarea>` 改为 `tdesign-react` 的 `Textarea`。
- 将组件库 Demo 页中的多行输入示例改为直接使用 `tdesign-react` 的 `Textarea`。
- 保留当前字段值、placeholder、最大长度、行数、变更回调和校验逻辑。
- 本次明确不修改 `packages/ui/src/components/Textarea.tsx`。
## 非目标
- 不迁移 `Input`、`Button`、`FormItem`、`Table` 或 `packages/ui/Textarea` 等其他组件。
- 不把其他无关页面导入改成直接依赖 `tdesign-react`。
- 不重构业务页面布局、保存逻辑或字段校验。
- 不新增 TDesign 原生能力之外的额外包装 API。
## 方案
在 `OfficialSiteJobTabEditorPage.tsx` 和 `ComponentsDemoPage.tsx` 中直接引入 `tdesign-react` 的 `Textarea`。前者替换“岗位说明”字段的原生 `<textarea>`,后者替换组件库 Demo 的多行输入示例。TDesign `Textarea` 的 `onChange` 本身返回字符串值,页面可直接更新表单状态;Demo 示例使用 `defaultValue` 保持原展示。
最大长度使用 TDesign 的 `maxlength` 属性,字数展示使用 `count`。行数通过原生 `rows` 透传。字段外层仍保留现有 `FormItem`、宽度容器、帮助文案和错误展示;Demo 页仍保留原基础交互分组布局。
## 风险与取舍
- TDesign `Textarea` 的 DOM 结构和 class 与原生 `<textarea>` 不同,测试应关注语义和值变化,不绑定内部 class。
- `packages/ui/Textarea` 保持原状,后续若要迁移共享组件,需要单独确认范围。
- 页面展示细节会更接近 TDesign 默认样式,这是本次迁移的预期变化。
# admin-agent 后台 UI 依赖迁移设计
## 背景
`workspace/agent-admin/web/src` 目前仍有 18 个运行时代码文件通过 19 条 import 声明依赖本地 `packages/ui/src`。其中既包含按钮、输入框、弹窗、表格等基础控件,也包含搜索区、状态占位、媒体墙等业务组合组件。
本轮目标不是删除旧组件目录,而是让后台业务运行时代码脱离本地 `packages/ui`,统一使用 TDesign 基础组件和全局业务组件。
## 已确认范围
### 本轮包含
- `workspace/agent-admin/web/src` 下所有运行时代码。
- 页面、布局、Hook 和组件 Demo 中对 `packages/ui/src` 的运行时依赖。
- 为迁移建立或补齐 `@gl/business-components` 全局业务组件。
- 为迁移调整相关测试、样式和文档。
### 本轮不包含
- 不删除 `workspace/agent-admin/web/packages/ui` 目录。
- 不要求立即清理旧组件源码或旧组件测试。
- 不处理 `workspace/agent-admin/single-page`。该目录没有依赖本地 `packages/ui`,其原生控件迁移应作为独立变更处理。
- 不在本轮引入配置化表单渲染器,不把编辑页表单重写为配置协议。
- 不做与组件替换无关的页面视觉改版或业务逻辑重构。
## 现状盘点
### 页面与布局
| 文件 | 当前使用的内部组件 |
| --- | --- |
| `src/layouts/AdminShell.tsx` | `Modal` |
| `src/hooks/useMessage.tsx` | `Message` |
| `src/routes/agent-tags/AgentTagEditorPage.tsx` | `Button`、`FormItem`、`Input`、`StatePlaceholder`、`Textarea` |
| `src/routes/agent-tags/AgentTagListPage.tsx` | `Button`、`Modal`、`Pagination`、`SearchFilter`、`StatePlaceholder`、`Table` |
| `src/routes/agents/AgentDetailDrawer.tsx` | `Button`、`Drawer`、`StatePlaceholder`、`Tag` |
| `src/routes/agents/AgentEditorPage.tsx` | `Button`、`FormItem`、`Input`、`Select`、`StatePlaceholder`、`Switch`、`Textarea` |
| `src/routes/agents/AgentListPage.tsx` | `Button`、`Modal`、`Pagination`、`SearchFilter`、`StatePlaceholder`、`Table`、`Tag` |
| `src/routes/channel-codes/ChannelCodeEditorPage.tsx` | `Button`、`FormItem`、`Input`、`Select`、`StatePlaceholder`、`Textarea` |
| `src/routes/channel-codes/ChannelCodeListPage.tsx` | `Button`、`Pagination`、`SearchFilter`、`StatePlaceholder`、`Table`、`Tag` |
| `src/routes/channel-codes/ChannelCodeViewDrawer.tsx` | `Button`、`Drawer`、`StatePlaceholder`、`Tag` |
| `src/routes/official-site/OfficialSiteMethodologyPage.tsx` | `Button`、`FormItem`、`Input`、`MediaWall`、`StatePlaceholder`、`Switch`、`Textarea` |
| `src/routes/official-site-agent-display-config/AgentDisplayConfigEditModal.tsx` | `Button`、`FormItem`、`Input`、`MediaWall`、`Modal`、`Select` |
| `src/routes/official-site-agent-display-config/OfficialSiteAgentDisplayConfigPage.tsx` | `Button`、`StatePlaceholder`、`Table` |
| `src/routes/official-site-job-tabs/OfficialSiteJobTabEditorPage.tsx` | `Button`、`FormItem`、`Input`、`Select`、`StatePlaceholder`、`Switch` |
| `src/routes/official-site-job-tabs/OfficialSiteJobTabListPage.tsx` | `Button`、`Modal`、`Pagination`、`SearchFilter`、`StatePlaceholder`、`Table` |
| `src/routes/skills/SkillDetailDrawer.tsx` | `Button`、`Drawer`、`StatePlaceholder` |
| `src/routes/skills/SkillListPage.tsx` | `Button`、`SearchFilter`、`StatePlaceholder`、`Table` |
### 组件 Demo
`src/routes/components/ComponentsDemoPage.tsx` 当前集中展示约 40 个内部组件,并单独从内部目录引入 `Icon`。本轮需要把 Demo 调整为展示 TDesign 基础组件与全局业务组件,不再作为旧 `packages/ui` 的入口。
## 方案比较
### 方案 A:页面直接使用 TDesign,业务组合组件提升为全局组件
- 基础控件在页面中直接改用 `tdesign-react`。
- 图标直接改用 `tdesign-icons-react`。
- `SearchFilter`、`StatePlaceholder`、`MediaWall` 迁到 `@gl/business-components`。
- 旧 `packages/ui` 保留但不再被 `web/src` 引用。
优点:依赖边界清晰,符合“全局组件或 TDesign 组件”的目标;后续可独立清理旧目录。
缺点:需要同步调整多个页面的属性名、事件签名和测试选择器。
### 方案 B:保留本地包装层,在 `packages/ui` 内部改用 TDesign
优点:页面改动较少。
缺点:`web/src` 仍依赖本地包装层,无法达到本轮确认的零运行时依赖目标。
### 方案 C:所有组件都在页面内直接展开
优点:不需要全局业务组件。
缺点:会复制搜索区、状态占位和媒体墙逻辑,降低一致性和可维护性。
## 采用方案
采用方案 A。
## 组件边界
### 直接使用 TDesign
- 表单与输入:`Button`、`Input`、`Textarea`、`Select`、`Switch`、`Checkbox`、`Radio`、`DatePicker`、`DateRangePicker`、`Form`、`FormItem`。
- 数据展示与反馈:`Table`、`Pagination`、`Tag`、`Modal`、`Drawer`、`Message`、`Alert`、`Tooltip`、`Popconfirm`、`Empty`、`Skeleton`、`Progress`。
- Demo 展示项:`Avatar`、`AvatarGroup`、`Badge`、`Card`、`Collapse`、`Steps`、`Tabs`、`Timeline`、`TreeSelect`、`Upload` 等。
- 图标:使用 `tdesign-icons-react`。
### 提升为全局业务组件
- `SearchFilter`:保留搜索条件配置、查询、重置和响应式布局能力;内部使用 TDesign。
- `StatePlaceholder`:保留加载、空数据和错误态统一展示能力;内部使用 TDesign。
- `MediaWall`:保留媒体上传、预览和删除交互;内部使用 TDesign。
这些组件放入根目录 `packages/business-components`,通过 `@gl/business-components` 导出,与现有 `BusinessLoginPage`、`BusinessAdminShell` 共用全局入口。
## 表单组件决策
### 本轮做法
- 编辑页直接使用 TDesign `Form`、`FormItem` 和基础输入控件。
- 迁移时保持页面现有字段状态、校验、联动、上传和提交逻辑,不顺带引入新的表单抽象。
- `FormItem` 的统一视觉规范优先通过 TDesign 属性、公共样式和现有页面布局约束完成。
### 后续试点方向
迁移完成后,可以另开独立变更,小范围验证全局 `BusinessForm` 或 `FormRenderer`。试点只面向结构重复的简单后台表单:
- 支持常规 `Input`、`Select`、`Switch`、`Textarea`。
- 支持基础校验、默认值和简单显隐条件。
- 支持通过 `children` 或 `render` 直接插入复杂表单项,页面可以混用配置字段与手写 TDesign `FormItem`。
- 上传、媒体墙、动态数组、多层级联动、复杂业务选择器和步骤表单默认保留页面级实现。
如果配置协议开始需要大量 `dependencies`、`transform`、`onChangeEffect` 或布局特例,应停止扩展协议,改用页面级组合组件。配置化只用于减少重复,不作为所有表单的强制写法。
## 实施批次
1. 先为全局业务组件补测试并迁移 `SearchFilter`、`StatePlaceholder`、`MediaWall`。
2. 迁移共享入口:`AdminShell`、`useMessage`、详情抽屉和列表页。
3. 迁移编辑页表单控件,覆盖剩余 `Textarea` 使用点。
4. 迁移组件 Demo,确保只展示 TDesign 和全局组件。
5. 扫描 `web/src`,确认没有指向 `packages/ui/src` 的运行时 import。
每一批先增加或调整失败测试,再实施替换。
## 验收标准
- `workspace/agent-admin/web/src` 不存在指向 `packages/ui/src` 的运行时 import。
- 页面功能、加载态、空态、错误态、查询、分页、弹窗、抽屉和表单提交行为保持一致。
- 相关测试通过。
- `npm run typecheck` 通过。
- `npm run build` 通过。
- OpenSpec 严格校验通过。
- 在浏览器中验证后台主要列表页、编辑页和组件 Demo 的布局与关键交互。
# 全局业务表格组件设计
日期:2026-06-01
## 背景
后台列表页已经迁移为直接使用 TDesign `Table`,但页面仍在各自维护表格、空态、错误态和分页结构。典型页面包括 `AgentListPage`、`AgentTagListPage`、`ChannelCodeListPage`、`OfficialSiteJobTabListPage`、`SkillListPage` 和 `OfficialSiteAgentDisplayConfigPage`。
当前重复点主要包括:
- 页面内定义 TDesign `columns` 后直接渲染 `Table`。
- `Table.empty` 手动传入 `StatePlaceholder`。
- 筛选无结果、普通空数据和加载失败状态由页面分散判断。
- 分页和总数展示结构不一致。
- 后续如果要统一空态视觉,需要逐个页面修改。
用户确认希望把表格提取成业务组件,由配置项渲染表格,并重新定义表格为空的内容。
## 目标
在全局业务组件包 `@gl/business-components` 中新增 `BusinessTable`,内部基于 TDesign `Table` 渲染,页面通过配置传入列、数据、行键、状态和分页。组件统一承接表格空态、筛选空态、加载失败态和操作按钮样式,并支持穿透 TDesign `Table` 属性。
## 非目标
- 不替换 TDesign `Table` 的列配置体系;第一版继续兼容 `PrimaryTableCol<T>`。
- 不接管页面查询状态、URL 参数、接口请求、埋点或权限判断。
- 不把搜索区和表格合并成完整列表页渲染器。
- 不改写列表页的业务列渲染逻辑、操作列按钮和弹窗流程。
- 不清理旧 `packages/ui` 表格源码;旧组件清理可作为独立任务。
## 现状观察
当前业务页面已经使用 TDesign 表格:
- `AgentListPage`:有筛选、加载失败、分页、删除弹窗。
- `AgentTagListPage`:有筛选、加载失败、分页、删除弹窗。
- `ChannelCodeListPage`:有筛选、加载失败、分页和状态标签。
- `OfficialSiteJobTabListPage`:有筛选、加载失败、分页、删除弹窗。
- `SkillListPage`:有筛选、加载失败和底部总数,但没有分页。
- `OfficialSiteAgentDisplayConfigPage`:有表格和加载失败态,偏配置管理场景。
页面目前已经从 `@gl/business-components` 使用 `SearchFilter` 和 `StatePlaceholder`,因此 `BusinessTable` 也应放入同一个包并从统一入口导出。
## 方案比较
### 方案一:只抽取 `TableEmpty`
新增一个表格空态组件,页面继续直接使用 TDesign `Table` 和 `Pagination`。
优点:改动最小,风险低。
缺点:不能减少表格、错误态和分页重复;不满足“表格也提取成业务组件”的目标。
### 方案二:抽取 `BusinessTable`
新增 `BusinessTable`,封装 TDesign `Table`、表格级空态、筛选空态、错误态和可选分页。页面仍定义 columns 和业务操作,组件负责统一渲染结构。
优点:满足配置渲染和统一空态;兼容现有 TDesign columns;能逐步迁移列表页;页面仍保留必要业务控制权。
缺点:组件 API 需要设计好 TDesign 属性透传,避免后续扩展受限。
### 方案三:抽取完整 `ListPageRenderer`
把搜索、表格、分页、错误态、工具栏全部配置化。
优点:页面代码最少。
缺点:会和各页面请求、URL 状态、弹窗、埋点、按钮权限强耦合,现阶段改动面过大。
## 推荐方案
采用用户确认的方案二:新增 `BusinessTable`。
组件负责“表格工作流”的通用 UI:表格、空态、筛选空态、失败态、分页和底部总数。页面继续负责搜索条件、请求、业务弹窗和列渲染。
## 组件 API 草案
```ts
import type { PrimaryTableCol, TableProps, PaginationProps } from 'tdesign-react';
export type BusinessTableColumn<T> = PrimaryTableCol<T>;
export interface BusinessTableEmptyStateConfig {
title?: string;
description?: string;
actionText?: string;
onAction?: () => void;
}
export interface BusinessTableErrorStateConfig {
title?: string;
description?: string;
retryText?: string;
onRetry?: () => void;
}
export interface BusinessTablePaginationConfig
extends Pick<PaginationProps, 'current' | 'pageSize' | 'total' | 'onCurrentChange' | 'onPageSizeChange' | 'pageSizeOptions'> {
show?: boolean;
}
export interface BusinessTableProps<T extends Record<string, unknown>>
extends Omit<TableProps<T>, 'columns' | 'data' | 'rowKey' | 'empty'> {
columns: BusinessTableColumn<T>[];
data: T[];
rowKey: TableProps<T>['rowKey'];
hasFilter?: boolean;
error?: boolean;
emptyState?: BusinessTableEmptyStateConfig;
filteredEmptyState?: BusinessTableEmptyStateConfig;
errorState?: BusinessTableErrorStateConfig;
pagination?: BusinessTablePaginationConfig | false;
totalLabel?: string;
tableClassName?: string;
}
```
说明:
- `columns` 沿用 TDesign `PrimaryTableCol<T>`,页面不需要重写列配置。
- `BusinessTableProps` 继承大部分 TDesign `TableProps<T>`,除 `columns`、`data`、`rowKey`、`empty` 由业务组件接管。
- 其他 TDesign 属性如 `hover`、`stripe`、`maxHeight`、`selectedRowKeys`、`onSelectChange`、`sort`、`onSortChange`、`rowClassName` 等通过 props 透传给内部 `Table`。
- `empty` 第一版不开放透传,避免绕过统一空态;如果确有页面特殊空态,后续可以增加 `emptySlot` 并纳入规范。
- `pagination={false}` 时不渲染分页区。
- `pagination` 存在时使用 TDesign `Pagination` 统一渲染分页。
- `totalLabel` 用于无分页但需要底部总数的场景,默认可根据 `data.length` 或 `pagination.total` 展示。
## 状态规则
### 普通空态
触发条件:
- `error !== true`
- `loading !== true`
- `data.length === 0`
- `hasFilter !== true`
展示规则:
- 使用 TDesign 自带状态类型的 `Empty` 组件展示空态图标。
- 主文案显示“暂无数据”。
- 默认不显示描述。
- 默认不显示操作按钮。
### 筛选空态
触发条件:
- `error !== true`
- `loading !== true`
- `data.length === 0`
- `hasFilter === true`
展示规则:
- 使用 TDesign 自带状态类型的 `Empty` 组件展示空态图标。
- 主文案显示“暂无数据”。
- 下方描述显示“未能查询到符合条件的资源”。
- 如果传入 `filteredEmptyState.onAction`,显示“清空筛选”按钮。
- 操作按钮使用 TDesign `Button`,`theme="primary"`,`variant="text"`。
### 加载失败态
触发条件:
- `error === true`
展示规则:
- 不渲染 Table,直接显示加载失败状态。
- 使用 TDesign 自带状态类型的 `Empty` 组件展示错误图标。
- 主文案显示“加载失败”。
- 描述显示错误信息提示,默认“数据请求失败,请稍后重试”。
- 如果传入 `errorState.onRetry`,显示“重试”按钮。
- 操作按钮使用 TDesign `Button`,`theme="primary"`,`variant="text"`。
## 视觉规则
- 表格业务组件沿用现有后台列表页白底、边框、8px 以内圆角和内边距风格。
- 空态内容居中展示,图标在上,主文案和描述在下,图标来自 TDesign `Empty` 自带状态类型。
- 普通空态只显示“暂无数据”,避免描述过度提示。
- 筛选空态使用用户提供的文案“未能查询到符合条件的资源”。
- 加载失败态使用错误图标和可恢复操作。
- 操作按钮均为 primary 文字按钮,不使用实心按钮。
## 迁移范围
第一批迁移当前已有后台列表表格:
- `AgentListPage`
- `AgentTagListPage`
- `ChannelCodeListPage`
- `OfficialSiteJobTabListPage`
- `SkillListPage`
- `OfficialSiteAgentDisplayConfigPage`
页面迁移后:
- 页面继续定义 `columns`。
- 页面把 `listData.items` 或业务数组传给 `BusinessTable.data`。
- 页面把 `hasFilter`、`loadError`、`onReset`、`loadList` 传给对应状态配置。
- 页面不再直接 import TDesign `Table` 和 `Pagination`,除非存在特殊表格能力需要先保留。
## 测试策略
新增或调整测试覆盖:
- `BusinessTable` 能根据 `columns`、`data`、`rowKey` 渲染 TDesign 表格内容。
- 普通空态显示图标和“暂无数据”,不显示筛选描述和操作按钮。
- 筛选空态显示“暂无数据”、“未能查询到符合条件的资源”和“清空筛选”按钮。
- 筛选空态按钮点击触发 `filteredEmptyState.onAction`。
- 加载失败态显示错误图标、“加载失败”、错误信息提示和“重试”按钮。
- 加载失败态按钮点击触发 `errorState.onRetry`。
- 空态和失败态操作按钮使用 primary text 样式。
- TDesign `Table` 属性可以透传,例如 `hover`、`rowClassName` 或选择相关属性。
- 至少覆盖一个业务列表页迁移后的空态、筛选空态和失败态回归。
## 实施顺序
1. 创建 OpenSpec change `extract-business-table-component`。
2. 完成 `proposal.md`、`design.md`、`specs/.../spec.md` 和 `tasks.md`。
3. 先写 `BusinessTable` 组件测试,覆盖三类状态和属性透传。
4. 实现 `BusinessTable` 和样式,并从 `@gl/business-components` 导出组件与类型。
5. 按页面逐个迁移表格和分页结构。
6. 调整受影响页面测试。
7. 运行相关测试、`npm run typecheck`、`npm run build`、`openspec validate --strict`。
8. 在浏览器中验证主要列表页普通数据、筛选空态和加载失败态布局。
## 待确认问题
已按用户补充要求记录:
- 普通空态:显示图标和“暂无数据”。
- 筛选空态:下方显示“未能查询到符合条件的资源”,并添加“清空筛选”按钮。
- 加载失败态:显示错误图标、加载失败信息提示,并添加“重试”按钮。
- 操作按钮:使用 primary 文字按钮。
- 组件支持穿透 TDesign `Table` 属性。
# 全局业务表单组件设计
日期:2026-06-02
## 背景
当前 `agent-admin` 的列表页已经通过 `@gl/business-components` 中的 `BusinessTable` 统一表格渲染、空态、错误态和分页;搜索区也已经通过 `SearchFilter` 采用配置驱动模式。编辑页和弹窗表单目前仍由页面直接组合 TDesign 控件,并通过 `workspace/agent-admin/web/src/components/TDesignAccessibleControls.tsx` 提供一层可访问性薄封装。
用户希望新增一个业务表单组件,根据传入配置项显示表单模块和校验,支持简单输入、下拉框、动态显示、上传和仅展示文字。用户已确认采用配置驱动方案,且 `BusinessForm` 不绑定具体上传接口。
## 目标
在全局业务组件包 `@gl/business-components` 中新增 `BusinessForm`,由字段配置渲染常见后台表单控件,统一标签、校验提示、字段布局、动态显示和上传字段的基础交互。
第一版内置字段类型包含:
- `input`
- `numberInput`
- `select`
- `switch`
- `textarea`
- `upload`
- `displayText`
第一版同时提供 `custom` 扩展字段,用于实际业务开发中内置能力暂时无法覆盖的场景。
组件应支持:
- 受控值输入与 `onChange` 回调。
- 内置必填、最大长度和自定义校验。
- 字段按当前表单值动态显示、禁用或只读。
- 字段级 `onChange`,用于字段变更后联动更新或清空其他字段。
- `input`、`numberInput`、`select` 和 `textarea` 默认使用一致的控件宽度,避免同一表单内输入区域宽窄不一。
- `input` 和 `textarea` 明确支持 `allowInputOverMax` 与 `showCount`。
- 上传字段校验文件大小与文件类型。
- 上传字段支持图片、GIF、视频和普通文件,并通过业务侧传入的 `upload(file, values)` 函数完成真实上传,不绑定固定接口。
- 仅展示文字字段用于只读信息展示,不参与编辑。
- 当内置字段无法覆盖实际业务场景时,支持业务侧传入自定义渲染字段,并继续复用 `BusinessForm` 的布局、动态显示和校验结果展示。
## 非目标
- 不接管页面保存按钮、接口请求、路由跳转、埋点、弹窗开关和全局消息提示。
- 不绑定任何固定上传 API、`usage_type` 或业务 `FormData` 结构。
- 不在第一版支持复杂联动请求、远程下拉搜索、数组字段、嵌套对象字段、富文本、日期或多文件上传。
- 上传字段第一版支持单文件上传,文件类别覆盖图片、GIF、视频和普通文件。
- 不强制一次性迁移所有既有编辑页;可先在组件 Demo 或一个低风险页面验证,再逐步迁移。
- 不替代 `SearchFilter`;列表筛选仍使用 `SearchFilter`。
## 现状观察
现有业务编辑页常见结构:
- 独立新增/编辑页保留页面头部、返回、保存按钮和错误提示。
- 表单字段多为 `FormItem + Input/Select/Textarea/Switch`。
- 校验逻辑由页面本地 `validate()` 维护,错误状态通过 `status="error"` 和 `tips` 展示。
- 上传主要出现在官网 Agent 展示配置弹窗,存在图标大小、类型限制和上传成功后回填 URL、媒体类型、文件大小的需求。
- 管家 Agent 等场景存在只读展示字段,例如固定岗位、托管员工或编码。
## 方案比较
### 方案一:只封装基础表单控件
在 `@gl/business-components` 导出 `FormItem`、`Input`、`Select`、`Textarea`、`Upload` 等控件,页面继续手写字段结构和校验。
优点:迁移成本低,灵活性高。
缺点:页面仍重复维护字段配置、校验、动态显示和上传提示,不满足“根据配置项渲染业务表单”的目标。
### 方案二:配置驱动 `BusinessForm`
新增 `BusinessForm`,页面通过 `fields` 配置描述字段,组件统一渲染控件、标签、错误提示、动态显示和基础校验。页面继续负责保存流程、接口请求和上传函数。
优点:满足用户确认的配置驱动目标;与 `BusinessTable`、`SearchFilter` 的全局业务组件模式一致;上传接口不耦合组件,适合多个业务场景复用。
缺点:第一版需要明确字段协议,复杂业务控件需要保留扩展口。
### 方案三:完整表单页渲染器
组件同时接管页头、保存按钮、加载态、接口提交、弹窗和消息反馈。
优点:页面代码最少。
缺点:会和业务流程、路由和接口强耦合,现阶段风险过大。
## 推荐方案
采用用户确认的方案二:新增配置驱动 `BusinessForm`。
组件只负责“业务表单字段渲染与校验”的通用 UI,不接管页面级业务流程。上传通过字段配置中的 `upload` 函数注入,组件只处理选择文件、前置校验、上传中状态、上传结果回填和错误提示。
## 组件 API 草案
```ts
import type { ReactNode } from 'react';
export type BusinessFormValue =
| string
| number
| boolean
| string[]
| number[]
| BusinessFormUploadedFileValue
| undefined
| null;
export type BusinessFormValues = Record<string, BusinessFormValue>;
export type BusinessFormErrors = Record<string, string | undefined>;
export interface BusinessFormRenderContext {
values: BusinessFormValues;
value: BusinessFormValue;
error?: string;
disabled: boolean;
readonly: boolean;
setValue: (nextValue: BusinessFormValue) => void;
setValues: (nextValues: BusinessFormValues, changedKey?: string) => void;
}
export interface BusinessFormSelectOption {
label: ReactNode;
value: string | number;
disabled?: boolean;
}
export interface BusinessFormValidationContext {
values: BusinessFormValues;
field: BusinessFormField;
}
export interface BusinessFormFieldChangeContext {
values: BusinessFormValues;
field: BusinessFormField;
}
export type BusinessFormValidator = (
value: BusinessFormValue,
context: BusinessFormValidationContext,
) => string | undefined | Promise<string | undefined>;
export type BusinessFormFieldOnChange = (
nextValue: BusinessFormValue,
context: BusinessFormFieldChangeContext,
) => Partial<BusinessFormValues> | void;
export type BusinessFormUploadKind = 'image' | 'gif' | 'video' | 'file';
export interface BusinessFormUploadedFileValue {
url: string;
name?: string;
size?: number;
mimeType?: string;
kind?: BusinessFormUploadKind;
extra?: Record<string, unknown>;
}
export interface BusinessFormFieldBase {
key: string;
label: string;
type: BusinessFormFieldType;
required?: boolean;
disabled?: boolean | ((values: BusinessFormValues) => boolean);
readonly?: boolean | ((values: BusinessFormValues) => boolean);
placeholder?: string;
helpText?: ReactNode;
visible?: boolean | ((values: BusinessFormValues) => boolean);
validator?: BusinessFormValidator;
onChange?: BusinessFormFieldOnChange;
className?: string;
}
export interface BusinessFormInputField extends BusinessFormFieldBase {
type: 'input';
maxLength?: number;
allowClear?: boolean;
allowInputOverMax?: boolean;
showCount?: boolean;
}
export interface BusinessFormNumberInputField extends BusinessFormFieldBase {
type: 'numberInput';
min?: number;
max?: number;
precision?: number;
allowClear?: boolean;
}
export interface BusinessFormTextareaField extends BusinessFormFieldBase {
type: 'textarea';
maxLength?: number;
rows?: number;
allowInputOverMax?: boolean;
showCount?: boolean;
}
export interface BusinessFormSelectField extends BusinessFormFieldBase {
type: 'select';
options: BusinessFormSelectOption[];
multiple?: boolean;
allowClear?: boolean;
}
export interface BusinessFormSwitchField extends BusinessFormFieldBase {
type: 'switch';
checkedValue?: BusinessFormValue;
uncheckedValue?: BusinessFormValue;
checkedLabel?: ReactNode;
uncheckedLabel?: ReactNode;
}
export interface BusinessFormUploadField extends BusinessFormFieldBase {
type: 'upload';
kinds?: BusinessFormUploadKind[];
accept?: string[];
maxSize?: number;
upload: (
file: File,
values: BusinessFormValues,
) => Promise<string | BusinessFormUploadedFileValue>;
previewAlt?: string;
actionText?: string;
removeText?: string;
}
export interface BusinessFormDisplayTextField extends BusinessFormFieldBase {
type: 'displayText';
emptyText?: ReactNode;
render?: (value: BusinessFormValue, values: BusinessFormValues) => ReactNode;
}
export interface BusinessFormCustomField extends BusinessFormFieldBase {
type: 'custom';
render: (context: BusinessFormRenderContext) => ReactNode;
}
export type BusinessFormField =
| BusinessFormInputField
| BusinessFormNumberInputField
| BusinessFormTextareaField
| BusinessFormSelectField
| BusinessFormSwitchField
| BusinessFormUploadField
| BusinessFormDisplayTextField
| BusinessFormCustomField;
export type BusinessFormFieldType =
| 'input'
| 'numberInput'
| 'select'
| 'switch'
| 'textarea'
| 'upload'
| 'displayText'
| 'custom';
export interface BusinessFormProps {
fields: BusinessFormField[];
values: BusinessFormValues;
errors?: BusinessFormErrors;
disabled?: boolean;
labelAlign?: 'left' | 'top';
fieldWidth?: string;
className?: string;
'data-testid'?: string;
onChange: (nextValues: BusinessFormValues, changedKey: string) => void;
onErrorsChange?: (nextErrors: BusinessFormErrors) => void;
onValidate?: (result: { valid: boolean; errors: BusinessFormErrors }) => void;
}
```
## 字段规则
### `input`
- 渲染单行输入框。
- `required` 校验空字符串。
- `maxLength` 校验字符长度,并透传给输入框。
- `allowInputOverMax` 为真时允许继续输入超过 `maxLength` 的内容,但校验仍按 `maxLength` 报错;为假或未配置时由控件限制输入长度。
- `showCount` 为真时展示字数统计。
- 默认 placeholder 为 `请输入${label}`。
### `numberInput`
- 渲染数字输入框。
- 值类型为 `number` 或可转换为数字的字符串。
- `required` 校验空值。
- `min` 和 `max` 校验数值范围。
- `precision` 控制小数位;未配置时建议按整数处理。
- 默认 placeholder 为 `请输入${label}`。
### `select`
- 渲染单选或多选下拉。
- `required` 校验空值;多选时校验空数组。
- `options` 由业务侧传入,组件不自动补“全部”选项。
- 每个选项支持 `disabled`,用于控制单个选项不可选择。
- 字段自身支持 `disabled` 和 `readonly`;二者都可以是布尔值或基于当前 `values` 的函数。
- `disabled` 为真时控件不可操作并呈现禁用样式。
- `readonly` 为真时展示当前选中项文本,不展示可展开下拉操作。
- 默认 placeholder 为 `请选择${label}`。
### `switch`
- 渲染开关控件。
- 默认使用 `true` 和 `false` 作为开关值。
- 可通过 `checkedValue` 和 `uncheckedValue` 映射业务值,例如启用/停用枚举。
- 可通过 `checkedLabel` 和 `uncheckedLabel` 展示开关旁状态文案。
- 字段自身支持 `disabled` 和 `readonly`;`readonly` 为真时展示当前状态文案,不展示可切换开关。
- `required` 只校验值是否为空,不要求必须为开启状态;需要“必须开启”时由业务侧配置 `validator`。
### `textarea`
- 渲染多行输入框。
- `required` 校验空字符串。
- `maxLength` 校验字符长度,并透传给文本域。
- `allowInputOverMax` 为真时允许继续输入超过 `maxLength` 的内容,但校验仍按 `maxLength` 报错;为假或未配置时由控件限制输入长度。
- 默认 placeholder 为 `请输入${label}`。
- `showCount` 为真时展示字数统计。
### `upload`
- 值类型为 URL 字符串或 `BusinessFormUploadedFileValue`。
- 组件提供选择文件、上传中、预览、移除和错误提示。
- `kinds` 表示允许的文件类别,可配置 `image`、`gif`、`video`、`file`;未配置时不额外限制类别,只按 `accept` 校验。
- `accept` 表示允许的 MIME 类型或扩展名,例如 `['image/png', 'image/jpeg', '.webp']`。
- `maxSize` 表示单文件最大字节数。
- 选择文件后先执行类型与大小校验,校验失败时不调用 `upload`。
- 通过 `upload(file, values)` 调用业务侧上传逻辑,返回的 URL 或结构化文件值写入当前字段值。
- 图片和 GIF 支持缩略预览;视频支持视频预览或视频文件展示;普通文件展示文件名、大小和移除入口。
- 业务侧需要额外回填 `media_type`、`media_size` 等字段时,可通过字段级 `onChange` 返回局部 patch。
- 上传失败时展示业务侧错误信息或默认“上传失败,请重试”。
- 组件不构造固定 `FormData`,不写入固定 `usage_type`,不调用固定 API。
### `displayText`
- 渲染只读文本,不提供输入控件。
- 默认展示当前字段值。
- 空值展示 `emptyText`,默认展示 `-`。
- 可通过 `render(value, values)` 自定义展示内容。
- 默认不参与必填和自定义校验;即使配置 `required` 也不触发校验。
### `custom`
- 用于内置 `input`、`numberInput`、`select`、`switch`、`textarea`、`upload` 和 `displayText` 无法覆盖的实际业务控件。
- `BusinessForm` 仍负责渲染字段外层布局、label、必填标记、helpText、错误提示、动态显示、动态禁用和动态只读状态。
- 业务侧通过 `render(context)` 返回自定义 React 节点。
- `context.value` 是当前字段值,`context.values` 是当前整表单值。
- `context.setValue(nextValue)` 只更新当前字段。
- `context.setValues(nextValues, changedKey)` 可一次性更新多个字段;`changedKey` 未传时默认使用当前字段 key。
- `context.disabled` 和 `context.readonly` 是 `BusinessForm` 根据全局 disabled、字段 disabled 和字段 readonly 计算后的结果,自定义控件应遵守这两个状态。
- `context.error` 是当前字段错误文案,便于自定义控件内部需要额外感知错误态时使用。
- `custom` 字段可以继续配置 `required` 和 `validator`,校验规则与普通可编辑字段一致。
- `custom` 字段不承诺内置控件的可访问性、上传、选项禁用等细节,业务侧需要在自定义渲染内自行保证。
## 动态显示规则
- `visible` 未配置时默认展示。
- `visible` 为布尔值时按布尔值展示。
- `visible` 为函数时传入当前 `values` 并按返回值展示。
- 隐藏字段不渲染、不触发校验、不展示错误。
- 隐藏字段的值默认保留在 `values` 中,由页面决定保存时是否提交;组件不擅自清空业务值。
- `disabled` 和 `readonly` 同样支持函数形式,可根据其他字段值动态控制当前字段是否可操作。
- 典型场景:选择字段 A 后,字段 B 的 `disabled(values)` 返回 false,B 才可以选择。
- 典型场景:选择字段 A 后,某个 `displayText` 字段的 `visible(values)` 返回 true,仅展示对应提示或只读信息。
- 组件只按当前 `values` 重新计算显示、禁用和只读状态,不主动推导或清空被影响字段的值。
## 字段级变更规则
- 每个字段可配置 `onChange(nextValue, context)`,用于处理当前字段变化带来的局部联动。
- 字段变更时,组件先得到当前字段的新值,再执行字段级 `onChange`;`context.values` 为变更前的当前表单值。
- 若字段级 `onChange` 返回 `Partial<BusinessFormValues>`,组件按 `{ ...values, [field.key]: nextValue, ...patch }` 合并后,通过表单级 `onChange(nextValues, changedKey)` 统一抛出。
- 若字段级 `onChange` 不返回值,组件只更新当前字段。
- 字段级 `onChange` 不直接调用接口;复杂异步联动、远程搜索和接口请求仍放在页面层或自定义字段中。
- 典型场景:选择岗位后同步回填 `position_code`、`position_name`、`qrcode_id`、`qrcode_name`。
- 典型场景:选择 A 后清空 B 的旧值,并让 B 从禁用变为可选。
## 校验规则
组件提供 `validate()` 能力,第一版可通过组件暴露的实例方法或导出的工具函数实现,实施阶段根据 React 使用方式二选一。
建议导出工具函数:
```ts
export async function validateBusinessForm(
fields: BusinessFormField[],
values: BusinessFormValues,
): Promise<{ valid: boolean; errors: BusinessFormErrors }>;
```
校验顺序:
1. 过滤不可见字段。
2. 跳过 `displayText` 字段。
3. 跳过 `readonly` 字段。
4. 执行 `required`。
5. 执行 `maxLength`。
6. 执行 `min`、`max` 和 `precision`。
7. 执行上传字段的 `accept`、`kinds` 和 `maxSize` 前置校验。
8. 执行字段 `validator`。
9. 汇总第一个错误文案到 `errors[field.key]`。
页面保存时可调用 `validateBusinessForm(fields, values)`,再通过 `errors` 传回 `BusinessForm` 展示。组件内部也可在字段变更时清除当前字段错误,但不自动提交页面保存。
`custom` 字段参与 `required` 和 `validator` 校验,但组件不推断自定义节点内部的输入规则;更复杂的校验应放在字段 `validator` 或页面保存前逻辑中。
## 视觉与交互规则
- 布局遵循后台编辑页当前信息密度:label 左侧、控件右侧。
- `fieldWidth` 用于统一控制基础输入控件宽度,默认建议为 `360px`,且不超过 `450px`。
- `input`、`numberInput`、`select` 和 `textarea` 默认使用同一个 `fieldWidth`,同一表单内保持左侧 label 后的控件起点和宽度一致。
- `textarea` 只允许高度随 `rows` 或内容交互变化,不应因为多行输入类型而使用不同宽度。
- `switch`、`upload`、`displayText` 和 `custom` 仍复用同一表单项外层布局;其中 `custom` 字段可在内部自行决定控件宽度,但建议遵守 `fieldWidth`。
- 表单字段纵向排列,字段间距统一。
- 错误提示在字段下方展示,颜色沿用 TDesign 错误态。
- 必填字段展示必填标记。
- 上传字段根据文件类型展示合适的预览:图片/GIF 展示缩略图,视频展示视频预览或文件信息,普通文件展示文件信息。
- 上传按钮文案默认“上传文件”,可通过 `actionText` 覆盖。
- 移除按钮默认“移除”,可通过 `removeText` 覆盖。
- 所有可输入控件应有可访问 label。
## 迁移建议
第一批建议从低复杂度页面或弹窗开始验证:
- `AgentTagEditorPage`:`input`、`textarea`、仅展示编码。
- `ChannelCodeEditorPage`:`input`、`select`、`textarea`。
- `AgentDisplayConfigEditModal`:`input`、`numberInput`、`select`、`upload`、动态错误提示;其中上传需覆盖图片、GIF 和视频。
复杂页面如 `AgentEditorPage` 包含管家 Agent 特殊只读逻辑、多组异步选项和 `switch` 状态,可在组件稳定后迁移。`OfficialSiteMethodologyPage` 包含数组字段、步骤增删排序和多处上传,第一版建议通过 `custom` 或继续保留页面自定义实现。
## 测试策略
新增 `BusinessForm` 测试覆盖:
- 根据 `input`、`numberInput`、`select`、`switch`、`textarea`、`displayText`、`upload`、`custom` 配置渲染字段。
- `input`、`numberInput`、`select` 和 `textarea` 在默认配置下使用一致的控件宽度。
- 传入 `fieldWidth` 后,`input`、`numberInput`、`select` 和 `textarea` 同步应用该宽度。
- `numberInput` 能校验 `min`、`max` 和 `precision`。
- 输入、数字输入、下拉、开关和文本域变更时触发 `onChange` 并返回更新后的 values。
- 字段级 `onChange` 能返回局部 patch,用于联动回填或清空其他字段。
- `input` 和 `textarea` 支持 `allowInputOverMax` 和 `showCount`。
- `required`、`maxLength` 和自定义 validator 能生成错误。
- `visible` 为 false 或返回 false 时隐藏字段,并且隐藏字段不参与校验。
- `disabled(values)` 能根据其他字段值禁用或启用字段。
- `readonly(values)` 能根据其他字段值把字段切换为只读展示。
- `select` 选项级 `disabled` 生效。
- `switch` 能按默认布尔值切换,也能按 `checkedValue` 和 `uncheckedValue` 映射业务值。
- 选择字段 A 后,字段 B 可以从禁用变为可选,或触发某个 `displayText` 字段显示。
- `displayText` 展示当前值,空值展示 `-`,自定义 `render` 生效。
- `upload` 能按 `accept` 和 `kinds` 拦截非法类型。
- `upload` 能按 `maxSize` 拦截过大文件。
- `upload` 校验通过后调用业务传入的 `upload(file, values)`。
- `upload` 上传成功后把 URL 或结构化文件值写入字段值。
- `upload` 分别覆盖图片、GIF、视频和普通文件的展示分支。
- `upload` 上传失败时展示错误且不改写字段值。
- `custom` 字段能接收 `value`、`values`、`disabled`、`readonly`、`error` 和更新函数。
- `custom` 字段通过 `setValue` 或 `setValues` 更新后能触发 `onChange`。
- `custom` 字段能复用 `visible`、`disabled`、`readonly` 和 `validator`。
- `BusinessForm` 从 `@gl/business-components` 统一入口导出组件和类型。
迁移业务页时补充对应页面回归测试,覆盖字段展示、校验、动态显示和保存 payload。
## 实施顺序
1. 创建 OpenSpec change `business-form-component`。
2. 锁定 proposal、design、spec 和 tasks。
3. 先写 `BusinessForm` 组件测试和 `validateBusinessForm` 工具测试。
4. 实现 `BusinessForm`、样式和校验工具。
5. 从 `packages/business-components/src/index.ts` 导出组件与类型。
6. 在 `/components` Demo 中展示七类内置字段、一个自定义字段、字段级 `onChange`、动态显示、动态禁用、动态只读、上传校验和仅展示文字。
7. 运行相关测试、`npm run typecheck`、`npm run build` 和 OpenSpec 校验。
8. 用户确认组件表现后,再分批迁移现有业务表单。
## 待确认问题
- 第一版 `upload` 是否只支持单文件上传;当前建议只支持单文件,但文件类别覆盖图片、GIF、视频和普通文件。
- 第一版是否需要在 Demo 中模拟上传成功后返回本地预览 URL 或结构化文件值;当前建议 Demo 同时覆盖字符串 URL 和结构化文件值两种返回。
# Components Demo 表格状态对齐设计
日期:2026-06-05
## 背景
`@gl/business-components` 已经提供 `BusinessTable`,并在前一轮表格状态调整中统一了普通空态、筛选无结果、失败态、权限态、分页总数和加载态规则。
当前 `ComponentsDemoPage` 的“表格与分页”区域虽然使用了 `BusinessTable`,但只展示了有数据表格;同时“导航与占位”区域仍直接使用 `StatePlaceholder` 展示一组看起来像表格状态的空态、筛选空态、权限态和网络态。这会让 demo 截图呈现旧文案和旧按钮,例如:
- 普通空态仍显示“请先创建项目”。
- 筛选无结果仍显示“请调整搜索或筛选条件”和“清空筛选”按钮。
- 加载失败仍显示“加载失败”“列表请求失败,当前数据状态未知”和“重试”按钮。
- 网络状态仍显示“网络不可用”“重新连接”等旧表格语义。
这些展示已经不再代表 `BusinessTable` 的实际规则,容易误导使用者认为 demo 中的表格状态没有遵循业务表格定义。
## 目标
- 让 demo 中的表格状态全部通过 `BusinessTable` 展示。
- “表格与分页”区域覆盖常见表格状态:有数据、普通空态、筛选无结果、请求失败、权限受限、加载中。
- demo 中表格状态文案与 `BusinessTable` 当前默认规则保持一致。
- `StatePlaceholder` 保持作为通用占位组件演示,但不再承担表格状态示例。
- 删除或改造会让人误解为表格状态规范的旧 demo 内容。
- 将“后台表格必须使用 `BusinessTable`”提升为 `agent` 工作区级前端约束,覆盖 `agent` 下所有项目的后台管理系统。
## 非目标
- 不修改 `BusinessTable` 的产品规则。
- 不修改全局 `StatePlaceholder` 的组件默认值和 API。
- 不调整真实业务页面的列表逻辑。
- 不归档已有 OpenSpec change。
- 不引入新的视觉体系或第三方组件。
## 现状判断
`ComponentsDemoPage` 中存在两个来源:
- “表格与分页”区域:已经使用 `BusinessTable`,但只展示常规有数据状态,并额外展示了一个 TDesign `Empty`。
- “导航与占位”区域:直接展示多组 `StatePlaceholder`,其中包含表格语义的空态、筛选无结果、权限受限和网络不可用。
因此问题不是 `BusinessTable` 本身未遵循定义,而是 demo 把旧的 `StatePlaceholder` 表格状态示例保留在了页面上。
## 方案比较
### 方案一:只修改 `StatePlaceholder` demo 文案
把 `StatePlaceholder` 示例里的文案和按钮改成与 `BusinessTable` 接近。
优点:改动较少。
缺点:仍然用通用占位组件演示表格状态,组件边界不清晰,后续 `BusinessTable` 规则变化时 demo 仍容易漂移。
### 方案二:由 `BusinessTable` 演示表格状态
把所有表格状态示例移到“表格与分页”区域,用 `BusinessTable` 真实渲染;“导航与占位”区域只保留通用占位组件的非表格示例,或移除表格语义示例。
优点:demo 与业务组件定义一致,使用者看到的就是组件真实输出;后续维护时只需围绕 `BusinessTable` 校验表格状态。
缺点:demo 页面会多几个表格状态示例,需要适当控制布局密度。
### 方案三:全局统一 `StatePlaceholder` 默认规则
把 `StatePlaceholder` 默认文案、按钮和图标也改成 `BusinessTable` 的状态规则。
优点:全局占位组件和表格组件视觉更统一。
缺点:影响面超过当前问题,可能改变非表格场景的占位语义。
## 推荐方案
采用用户确认的方案二。
`BusinessTable` 是表格工作流的规范入口,demo 中所有表格相关状态都应通过它展示。`StatePlaceholder` 仅作为通用状态占位组件保留,不再展示“筛选无结果”“网络不可用重试”等表格专属或疑似表格专属状态。
## 后续项目开发约束
后续 `agent` 工作区下所有项目的后台管理系统前端开发中,凡是后台表格列表区域,默认 SHALL 使用 `@gl/business-components` 的 `BusinessTable` 承接表格本体、状态展示和分页展示。
页面、demo 或业务模块 SHALL NOT 直接组合 TDesign `Table`、TDesign `Pagination`、`StatePlaceholder`、TDesign `Empty` 和按钮来替代 `BusinessTable` 的后台表格模式。已有历史页面如果尚未迁移,应通过独立 OpenSpec change 分批迁移;新页面、新 demo 和新增表格功能默认不得继续扩散页面级自组装表格。
该约束覆盖以下表格状态:
- 普通空态。
- 筛选无结果。
- 请求失败或网络失败。
- 权限受限。
- 加载中。
- 分页总数。
`StatePlaceholder` 的使用边界为非表格区域的通用占位,例如页面级异常、卡片级缺省内容、引导区域或其他不依赖表格结构的状态展示。若某个后台表格场景确实需要特殊状态,应优先扩展 `BusinessTable` 的受控配置,并同步更新工作区级规范和对应 OpenSpec,而不是在页面内绕过业务表格组件临时拼装。
## Demo 展示规则
### 表格与分页
在“表格与分页”区域展示以下 `BusinessTable` 示例:
- 有数据表格:保留当前 columns、data 和分页示例。
- 普通空态:`data={[]}`,不传 `hasFilter`,默认展示“暂无数据”,不展示描述和按钮。
- 筛选无结果:`data={[]}` 且 `hasFilter`,默认展示“未找到匹配结果”,不展示描述和按钮。
- 请求失败:`error` 且使用默认失败态,展示“请求失败”,不展示描述和按钮。
- 权限受限:使用 `errorState.kind = 'forbidden'`,展示“权限受限”“当前账号暂无访问权限”,保留“申请权限”按钮。
- 加载中:使用 `loading` 触发表格加载样式,颜色沿用当前主题色。
### 导航与占位
“导航与占位”区域不再展示表格状态集合。
如果需要保留 `StatePlaceholder` 示例,应调整为通用占位语义,避免出现以下表格状态文案:
- “暂无数据 / 请先创建项目”
- “未找到匹配结果 / 请调整搜索或筛选条件 / 清空筛选”
- “加载失败 / 列表请求失败,当前数据状态未知 / 重试”
- “网络不可用 / 请检查网络连接后重试 / 重新连接”
## 验收标准
- demo 页面中表格状态由 `BusinessTable` 真实渲染。
- “表格与分页”区域能看到有数据、普通空态、筛选无结果、请求失败、权限受限和加载中示例。
- demo 页面不再出现旧表格状态文案“请先创建项目”“请调整搜索或筛选条件”“列表请求失败,当前数据状态未知”。
- 筛选无结果和请求失败示例不显示下方操作按钮。
- 普通空态不显示补充描述。
- 工作区级前端规范和 OpenSpec 写入约束,明确 `agent` 下所有后台管理系统的表格默认使用 `BusinessTable`。
- 相关测试覆盖 demo 文案收敛和 `BusinessTable` 状态示例。
- OpenSpec 严格校验通过。
## 风险与边界
- `StatePlaceholder` 仍可能在其他页面被用于非表格场景;本次不改变其默认行为,避免扩大影响。
- demo 中多个表格示例会增加页面长度,需要用简洁标题和稳定布局控制可扫读性。
- 如果后续 `BusinessTable` 状态规则继续调整,demo 测试应随组件规则一起更新。
## Context
`BusinessTable` 已是后台表格状态和分页展示的统一入口。当前 demo 的问题在于页面同时保留了旧 `StatePlaceholder` 表格状态集合,使使用者在同一页看到两套状态语义。
用户已确认采用方案二:表格状态全部放到 `BusinessTable` demo 内展示,`StatePlaceholder` 只保留通用占位边界。
## Goals / Non-Goals
**Goals:**
- 用 `BusinessTable` 展示 demo 中所有表格状态。
- 让 demo 文案与当前 `BusinessTable` 默认规则一致。
- 防止 demo 中继续出现旧表格状态说明文案和旧操作按钮。
- 为后续 TDD 提供明确验收边界。
**Non-Goals:**
- 不改 `BusinessTable` 的状态规则。
- 不改 `StatePlaceholder` 的组件默认 API。
- 不迁移真实业务列表页。
- 不归档已有 OpenSpec change。
## Decisions
- 表格状态示例统一放在“表格与分页”区域。
- 原因:使用者查看表格规范时应看到 `BusinessTable` 的真实渲染,而不是通用占位组件的近似拼装。
- 替代方案:仅改 `StatePlaceholder` 文案。该方案仍会混淆组件边界,后续容易再次漂移。
- `StatePlaceholder` 不再展示表格语义状态集合。
- 原因:`StatePlaceholder` 是通用占位组件,不应承担后台表格状态规范入口。
- demo 测试以用户可见文案和按钮缺失为主要断言。
- 原因:当前问题是可见展示误导,测试应覆盖旧文案和旧按钮不再出现,并确认新表格状态可见。
## Risks / Trade-offs
- 多个 `BusinessTable` 示例会增加 demo 页面长度。
- 缓解:使用紧凑分组标题和稳定布局,只展示必要状态。
- 现有测试可能依赖旧 `StatePlaceholder` demo 文案。
- 缓解:先更新测试使其表达新验收,再修改实现。
## Migration Plan
1. 先补充或调整 `ComponentsDemoPage` 测试,断言 demo 通过 `BusinessTable` 展示各表格状态,并断言旧文案和旧按钮不存在。
2. 运行测试确认失败。
3. 调整 demo 实现和必要样式。
4. 运行相关测试、类型检查和 OpenSpec strict validate。
## Why
`ComponentsDemoPage` 当前仍在“导航与占位”区域直接用 `StatePlaceholder` 展示表格语义状态,导致 demo 继续出现旧文案和旧按钮。`BusinessTable` 已经统一表格空态、筛选无结果、失败态、权限态、loading 和分页规则,demo 需要展示真实业务表格输出,避免误导后续使用者。
## What Changes
- 将 demo 中表格相关状态示例统一迁移到“表格与分页”区域,并通过 `BusinessTable` 真实渲染。
- “表格与分页”区域覆盖有数据、普通空态、筛选无结果、请求失败、权限受限和加载中状态。
- 移除或改造“导航与占位”区域中的表格语义 `StatePlaceholder` 示例,不再展示旧表格状态文案和按钮。
- 删除 demo 中额外的 TDesign `Empty` 表格空态示例,避免绕过 `BusinessTable`。
## Capabilities
### New Capabilities
- `components-demo`: 覆盖组件 demo 页面如何展示业务组件状态和边界。
### Modified Capabilities
- `business-table`: 本次不修改 `BusinessTable` 组件行为,仅在 demo 中按既有规范消费该组件。
## Impact
- 影响 `src/routes/components/ComponentsDemoPage.tsx` 及其样式和测试。
- 不修改 `@gl/business-components` 的 `BusinessTable` API、默认状态规则或运行时行为。
- 不影响真实业务列表页面。
## ADDED Requirements
### Requirement: 表格状态必须通过 BusinessTable 展示
组件 demo 页面 SHALL 在“表格与分页”区域通过 `BusinessTable` 展示表格相关状态,避免使用 `StatePlaceholder`、TDesign `Empty`、TDesign `Table` 和 TDesign `Pagination` 直接拼装表格状态示例。
#### Scenario: 展示表格状态集合
- **WHEN** 用户打开组件 demo 页面并查看“表格与分页”区域
- **THEN** 系统 SHALL 展示由 `BusinessTable` 渲染的有数据表格、普通空态、筛选无结果、请求失败、权限受限和加载中示例
#### Scenario: 普通空态示例
- **WHEN** demo 展示普通空态表格示例
- **THEN** 系统 SHALL 展示标题“暂无数据”
- **AND** 系统 SHALL NOT 展示说明文案“请先创建项目”
- **AND** 系统 SHALL NOT 展示空态操作按钮
#### Scenario: 筛选无结果示例
- **WHEN** demo 展示筛选无结果表格示例
- **THEN** 系统 SHALL 展示标题“未找到匹配结果”
- **AND** 系统 SHALL NOT 展示说明文案“请调整搜索或筛选条件”
- **AND** 系统 SHALL NOT 展示“清空筛选”按钮
#### Scenario: 请求失败示例
- **WHEN** demo 展示请求失败表格示例
- **THEN** 系统 SHALL 展示标题“请求失败”
- **AND** 系统 SHALL NOT 展示说明文案“列表请求失败,当前数据状态未知”
- **AND** 系统 SHALL NOT 展示“重试”按钮
#### Scenario: 权限受限示例
- **WHEN** demo 展示权限受限表格示例
- **THEN** 系统 SHALL 展示标题“权限受限”
- **AND** 系统 SHALL 展示说明文案“当前账号暂无访问权限”
- **AND** 系统 SHALL 展示“申请权限”按钮
#### Scenario: 导航与占位不展示表格状态集合
- **WHEN** 用户查看“导航与占位”区域
- **THEN** 系统 SHALL NOT 展示“网络不可用”“请检查网络连接后重试”或“重新连接”等表格网络失败示例
- **AND** 系统 SHALL NOT 展示旧表格状态集合
## 1. OpenSpec 对齐
- [x] 1.1 创建 proposal,说明 demo 表格状态需统一通过 `BusinessTable` 展示
- [x] 1.2 创建 design,确认采用用户选择的方案二
- [x] 1.3 创建 `components-demo` spec delta,覆盖 demo 表格状态展示和旧文案收敛
- [x] 1.4 等待用户确认 OpenSpec 后进入 TDD
## 2. TDD 实现
- [x] 2.1 更新 `ComponentsDemoPage.test.tsx`,覆盖 `BusinessTable` 表格状态示例和旧文案/按钮不再出现
- [x] 2.2 运行 demo 相关测试,确认新增断言先失败
- [x] 2.3 调整 `ComponentsDemoPage.tsx`,将表格状态示例迁移为 `BusinessTable` 渲染
- [x] 2.4 调整 demo 页面样式,保证多个表格状态示例布局稳定且不与现有内容冲突
- [x] 2.5 运行 demo 相关测试,确认通过
## 3. 验证
- [x] 3.1 运行 `rtk npm test -- ComponentsDemoPage.test.tsx`
- [x] 3.2 运行 `rtk npm run typecheck`
- [x] 3.3 运行 `rtk openspec validate align-components-demo-business-table-states --strict`
- [x] 3.4 用户确认本次无需操作浏览器;已通过测试、类型检查、构建和 OpenSpec 校验覆盖交付风险
## Context
管理后台列表页搜索区域目前由页面各自拼装,常见控件包括输入框、仅数字输入框、下拉框和日期选择器。用户希望抽象为全局组件,由配置项渲染搜索区域,统一布局密度、控件宽度、按钮位置、筛选默认值和折叠体验。
组件与 demo 展示已完成并经用户确认,本阶段在保留组件配置接口的基础上,迁移当前已有列表页搜索区域。迁移重点是统一 UI 结构、控件宽度、select “全部”语义和 placeholder 文案,同时保持各列表页已有 URL 查询参数、分页重置、埋点和数据请求语义。
## Goals / Non-Goals
**Goals:**
- 提供全局可复用的 `SearchFilter` 组件。
- 通过字段配置渲染 `input`、`numberInput`、`select`、`datePicker`。
- `numberInput` 仅允许输入数字。
- 所有 `select` 自动包含“全部”选项,且未传入明确值时默认选中“全部”。
- 日期配置支持单日期与范围日期,范围日期使用 `range: true`。
- 搜索项统一为左右结构,形成 `label: control` 的横向排布。
- 控件宽度符合要求:普通控件固定 `200px`,范围日期占满两项宽度。
- 默认最多展示两行,包含操作按钮所在区域。
- 超过默认展示范围时提供展开/收起;搜索、重置按钮始终固定在右下角且不被收起。
- 展开/收起按钮位于搜索/重置左侧,并带向上/向下箭头与动画过渡。
- 在 demo 中提供足够多配置项,验证两行限制和展开/收起效果。
- 将当前已有列表页搜索区域迁移为 `SearchFilter` 配置渲染。
- 统一默认 placeholder:`input` 默认为 `搜索${label}`,`numberInput` 默认为 `请输入数字`,显式配置优先。
**Non-Goals:**
- 本次不接管业务页面的查询参数、URL 同步、请求触发或数据加载状态。
- 本次不新增后端接口或变更现有列表接口契约。
- 本次不引入新的 UI 依赖;优先复用现有 `Input`、`Select`、`DatePicker`、`DateRangePicker`、`Button` 与图标能力。
- 本次不迁移编辑页、弹窗表单、官网展示配置页等非列表搜索区域。
## Decisions
### 1. 使用配置化全局组件,而非页面局部布局封装
新增 `SearchFilter` 到 UI 组件库并从统一入口导出。组件仅负责渲染、布局、折叠和事件回调,页面仍拥有表单状态与查询逻辑。
原因:搜索区是跨列表页的重复模式,放在全局 UI 层可以统一交互和样式;同时不接管业务状态,可以降低后续迁移风险。
备选方案:
- 只提供布局容器,让页面手写每个控件。该方案灵活但不能保证配置化渲染与控件一致性。
- 提供完整表单状态管理组件。该方案短期更重,容易和现有页面状态、URL 参数同步方式冲突。
### 2. 字段配置采用受控值与回调
每个字段配置包含基础信息:`key`、`label`、`type`、`value`、`onChange`。不同类型扩展各自控件参数,例如 `placeholder`、`options`、`range`、`disabled`。
原因:现有列表页多为页面状态驱动,受控组件便于后续逐页迁移,也便于 demo 直接展示状态变化。
### 3. 用 `numberInput` 表达仅数字输入框
`type: 'numberInput'` 渲染与普通输入框同宽的数字输入控件,并在用户输入时过滤非数字内容。默认仅允许数字字符;如后续需要小数、负数或范围校验,再作为字段扩展能力追加。
原因:数字输入是常见搜索筛选项,单独类型比在 `input` 上叠加临时属性更清晰,后续迁移列表页时也便于快速识别字段意图。
备选方案:
- 使用 `type: 'input'` 加 `inputMode: 'numeric'`。该方案对配置方不够直观,也不能天然表达“仅数字”的行为约束。
- 使用 HTML `type="number"`。该方案浏览器表现差异较大,且可能允许 `e`、`+`、`-` 等字符,不符合“仅限输入数字”的要求。
### 4. Select 统一注入“全部”选项
`type: 'select'` 的字段由 `SearchFilter` 在渲染时统一补充“全部”选项。默认选项值使用空字符串 `''`;若字段 `value` 为 `undefined`、`null` 或空字符串,则展示“全部”为选中态。业务方传入的 `options` 不需要重复提供“全部”。
原因:列表页筛选里的下拉框通常需要“全部”状态,放到全局组件里统一处理可以减少页面重复配置,并保证默认筛选语义一致。
备选方案:
- 要求每个页面手动配置“全部”。该方案重复且容易漏配。
- 让组件完全管理 select 默认值。该方案会和受控状态边界冲突,因此仅在展示层提供默认展示与标准选项,实际值仍由页面状态承接。
### 5. `datePicker` 通过 `range: true` 切换范围日期
`type: 'datePicker'` 默认渲染单日期;当配置 `range: true` 时渲染 `DateRangePicker`,并让该搜索项横向占满两个普通搜索项宽度。
原因:用户明确希望日期类型覆盖单日期与范围日期,并通过 `range: true` 表达范围场景。保持同一个类型可以减少配置枚举数量。
### 6. 操作区始终作为布局项固定在右下角
搜索/重置按钮与展开/收起按钮组成 action 区域,放在搜索网格的右下角。折叠状态只裁剪字段内容,不裁剪 action 区域。
原因:用户需要按钮不收起,并且最多展示两行包含按钮。action 区域参与高度计算但不参与折叠隐藏,可以保证常用操作始终可达。
### 7. 使用高度过渡实现展开/收起动画
组件根据内容区域实际高度计算折叠高度与展开高度,使用 CSS transition 过渡 `max-height` 或等效高度属性。折叠高度按两行布局计算,并预留 action 区域所在行的空间。
原因:搜索字段数量由配置决定,纯 CSS 固定高度不一定适配范围日期和响应式换行。测量高度可以让动画更自然。
### 8. demo 先承载验收,不改变业务页面
在当前 demo 展示入口新增 `SearchFilter` 示例,配置包含普通输入、仅数字输入、下拉、单日期和范围日期字段,数量超过两行以验证展开/收起。
原因:用户希望先确认组件没问题,再迁移所有列表页搜索区域。
### 9. 业务列表页逐页迁移,保持查询语义不变
迁移范围限定为当前已有列表搜索区:
- `AgentListPage`:`Agent名称` 使用 `input`,默认 placeholder 为 `搜索Agent名称`;`所属岗位` 使用 `select`,由组件提供“全部”;`状态` 使用 `select`,由组件提供“全部”。搜索时保持原 `buildAgentListSearch`、分页重置到第一页和埋点逻辑。
- `SkillListPage`:`关键词` 使用 `input`,显式 placeholder 为 `搜索Skill名称或编码`。搜索/重置继续写入 URL 查询参数。
- `ChannelCodeListPage`:`活码名称` 使用 `input`,默认 placeholder 为 `搜索活码名称`;`状态` 使用 `select`,由组件提供“全部”。迁移后状态选择先进入筛选草稿,点击搜索再提交,与统一搜索区交互保持一致;空字符串仍表示全部。
- `AgentTagListPage`:`标签名称` 使用 `input`,默认 placeholder 为 `搜索标签名称`。搜索/重置继续写入 URL 查询参数。
- `OfficialSiteJobTabListPage`:`关键词` 使用 `input`,显式 placeholder 为 `搜索岗位名称或渠道活码`;`展示状态` 使用 `select`,由组件提供“全部”。组件内部空字符串在提交时映射回页面既有 `all` 查询语义,状态选择同样先进入筛选草稿,点击搜索再提交。
原因:这些页面已经有页面级状态、URL 同步和分页规则,逐页把字段转换为配置可以降低改动风险,并让后续新增筛选项直接复用统一组件。
### 10. placeholder 默认规则收敛到组件
`SearchFilter` 在渲染输入类字段时负责补齐默认 placeholder:
- `type: 'input'` 且未传 `placeholder` 时使用 `搜索${label}`。
- `type: 'numberInput'` 且未传 `placeholder` 时使用 `请输入数字`。
- 显式传入 `placeholder` 时始终使用显式文案。
原因:列表页常见单字段搜索遵循“搜索 + 主字段名称”,多字段搜索可以通过显式 placeholder 表达可搜内容。默认规则放在组件内可以减少页面重复配置,同时保留页面覆盖能力。
## Risks / Trade-offs
- [Risk] 网格折叠高度和范围日期跨两项宽度在不同容器宽度下可能出现换行差异。→ 使用稳定的字段宽度、范围日期 span 规则和浏览器截图验证桌面/窄屏布局。
- [Risk] 高度测量动画可能受异步渲染或字体加载影响。→ 在字段变化、展开状态变化和窗口尺寸变化时重新测量,并提供无测量时的保守回退。
- [Risk] `numberInput` 过滤规则过窄可能不满足未来小数或负数筛选。→ 本次按“仅限输入数字”实现整数数字字符,后续有新规则时通过字段配置扩展。
- [Risk] 组件统一注入“全部”可能与业务传入的“全部”选项重复。→ 渲染时检测同值选项,若已有空字符串选项则不重复注入。
- [Risk] 列表页迁移可能改变部分 select 立即提交行为。→ 迁移后统一为筛选草稿 + 点击搜索提交,并用页面测试覆盖 URL 查询参数和分页重置结果。
- [Risk] 不接管表单状态会让页面迁移时仍需写少量绑定代码。→ 保持组件边界清晰,避免全局组件过早耦合业务查询模型。
- [Risk] 默认 placeholder 可能不适合多字段模糊搜索。→ 多字段场景显式传入 placeholder,组件默认仅覆盖未配置的普通输入和数字输入。
## Migration Plan
1. 新增 `SearchFilter` 组件、类型定义、样式和测试。
2. 从 UI 组件库入口导出该组件。
3. 在 demo 中新增完整示例,覆盖多字段、数字输入限制、select 默认“全部”、单日期、范围日期、展开/收起和搜索/重置。
4. 运行组件测试、类型检查、构建。
5. 用户确认组件后,在当前 change 内补充迁移规范和任务。
6. 为 placeholder 默认规则补组件测试并更新实现。
7. 逐页迁移 `AgentListPage`、`SkillListPage`、`ChannelCodeListPage`、`AgentTagListPage`、`OfficialSiteJobTabListPage` 搜索区域。
8. 为受影响页面补充或更新搜索区回归测试。
9. 运行组件测试、相关页面测试、类型检查和构建。
回滚策略:组件已全局导出,若单个列表页迁移出现问题,可回退该页面搜索区到原局部实现;若组件默认 placeholder 出现问题,可优先通过字段显式 `placeholder` 覆盖。
## Open Questions
- 无。用户已确认组件,并确认开始迁移当前已有列表页搜索区域。
## Why
当前管理后台多个列表页各自手写搜索区域,布局、折叠行为、控件宽度、按钮位置和筛选默认值容易不一致。新增全局可配置搜索组件,用统一配置渲染 `input`、`numberInput`、`select`、`datePicker` 搜索项,先在 demo 中验证交互与视觉,再迁移业务列表页。
## What Changes
- 新增全局 `SearchFilter` 搜索筛选组件,支持通过配置项渲染搜索区域。
- 配置项 `type` 支持 `input`、`numberInput`、`select`、`datePicker`,其中 `numberInput` 仅允许输入数字。
- 所有 `select` 字段由组件统一添加“全部”选项,并在未传入明确值时默认选中“全部”。
- `datePicker` 同时支持单日期与范围日期;范围日期通过 `range: true` 配置启用。
- 每个搜索项采用左右结构展示:`label: control`。
- `input`、`numberInput`、`select`、单日期控件宽度固定为 `200px`。
- 范围日期控件占满两项宽度。
- 搜索区域默认最多展示两行,且两行高度包含右下角操作按钮区域。
- 当搜索项超过默认可展示区域时,展示展开/收起文字按钮;搜索、重置按钮固定在右下角且不参与收起。
- 展开/收起按钮位于搜索/重置按钮左侧;收起状态文案为“展开”并显示向下箭头,展开状态文案为“收起”并显示向上箭头。
- 展开/收起过程需要有平滑动画,避免内容突兀跳变。
- `input` 未显式传入 `placeholder` 时,默认展示 `搜索${label}`;`numberInput` 未显式传入 `placeholder` 时,默认展示 `请输入数字`;显式 `placeholder` 优先。
- 第一阶段已在 demo 中展示组件能力,并配置较多字段用于验证展开/收起效果。
- 用户确认组件后,迁移当前已有列表页搜索区域到 `SearchFilter`,并按各页面既有搜索语义补充字段 placeholder。
## Capabilities
### New Capabilities
- `global-search-filter`: 定义全局配置化搜索筛选组件的渲染、布局、折叠、操作按钮和 demo 展示能力。
### Modified Capabilities
- 无。
## Impact
- 影响 UI 组件库:`packages/ui/src/components` 与组件导出入口。
- 影响 demo 展示入口,用于承载 `SearchFilter` 的示例配置与交互验证。
- 影响当前已有列表页搜索区域:`AgentListPage`、`SkillListPage`、`ChannelCodeListPage`、`AgentTagListPage`、`OfficialSiteJobTabListPage`。
- 新增或扩展组件测试,覆盖配置渲染、placeholder 默认规则、数字输入限制、select 默认“全部”、日期范围、展开/收起、按钮固定和回调行为。
- 新增或扩展页面测试,覆盖迁移后搜索、重置、select “全部”默认值、URL 查询参数和分页重置语义。
## ADDED Requirements
### Requirement: 配置化渲染搜索字段
系统 SHALL 提供全局 `SearchFilter` 组件,并 SHALL 根据字段配置渲染搜索区域。
#### Scenario: 渲染输入框字段
- **WHEN** 字段配置包含 `type: "input"`、`label`、`value` 和变更回调
- **THEN** 组件展示一个左右结构的搜索项,左侧为标签,右侧为输入框
#### Scenario: 渲染仅数字输入框字段
- **WHEN** 字段配置包含 `type: "numberInput"`、`label`、`value` 和变更回调
- **THEN** 组件展示一个左右结构的搜索项,左侧为标签,右侧为仅允许输入数字的输入框
#### Scenario: 渲染下拉框字段
- **WHEN** 字段配置包含 `type: "select"` 与选项列表
- **THEN** 组件展示一个左右结构的搜索项,左侧为标签,右侧为下拉框
#### Scenario: 渲染单日期字段
- **WHEN** 字段配置包含 `type: "datePicker"` 且未配置 `range: true`
- **THEN** 组件展示一个左右结构的搜索项,左侧为标签,右侧为单日期选择器
#### Scenario: 渲染范围日期字段
- **WHEN** 字段配置包含 `type: "datePicker"` 且配置 `range: true`
- **THEN** 组件展示一个左右结构的搜索项,左侧为标签,右侧为范围日期选择器
### Requirement: 数字输入限制
系统 SHALL 支持仅数字输入框字段,并 SHALL 阻止非数字内容进入该字段值。
#### Scenario: 输入数字
- **WHEN** 用户在 `numberInput` 字段中输入数字字符
- **THEN** 组件保留该数字输入并触发字段变更回调
#### Scenario: 输入非数字
- **WHEN** 用户在 `numberInput` 字段中输入非数字字符
- **THEN** 组件过滤非数字字符,并仅以过滤后的数字内容触发字段变更回调
### Requirement: 输入框默认占位文案
系统 SHALL 为输入类字段提供默认占位文案,并 SHALL 允许字段配置显式覆盖默认文案。
#### Scenario: 普通输入框默认占位文案
- **WHEN** 字段配置包含 `type: "input"`、`label: "项目名称"` 且未配置 `placeholder`
- **THEN** 组件展示输入框占位文案为“搜索项目名称”
#### Scenario: 数字输入框默认占位文案
- **WHEN** 字段配置包含 `type: "numberInput"` 且未配置 `placeholder`
- **THEN** 组件展示输入框占位文案为“请输入数字”
#### Scenario: 显式占位文案优先
- **WHEN** 输入类字段配置显式传入 `placeholder`
- **THEN** 组件展示显式传入的占位文案
### Requirement: 下拉框全部选项
系统 SHALL 为所有 `select` 字段统一提供“全部”选项,并 SHALL 在字段未传入明确值时默认选中“全部”。
#### Scenario: 自动添加全部选项
- **WHEN** 字段配置包含 `type: "select"` 且业务选项未包含“全部”
- **THEN** 组件在下拉选项中展示“全部”选项
#### Scenario: 避免重复全部选项
- **WHEN** 字段配置包含 `type: "select"` 且业务选项已包含与组件默认“全部”相同值的选项
- **THEN** 组件不重复添加第二个“全部”选项
#### Scenario: 默认选中全部
- **WHEN** `select` 字段的 `value` 为 `undefined`、`null` 或空字符串
- **THEN** 组件展示“全部”为当前选中项
### Requirement: 搜索字段布局宽度
系统 SHALL 统一搜索字段布局宽度,普通字段控件固定为 `200px`,范围日期字段 SHALL 占满两项宽度。
#### Scenario: 普通控件宽度固定
- **WHEN** 组件渲染输入框、仅数字输入框、下拉框或单日期字段
- **THEN** 对应控件的可视宽度为 `200px`
#### Scenario: 范围日期跨两项宽度
- **WHEN** 组件渲染 `range: true` 的日期字段
- **THEN** 范围日期字段占据两个普通搜索项的横向空间
### Requirement: 操作按钮固定在右下角
系统 SHALL 在搜索区域右下角固定展示搜索与重置按钮,并 SHALL 保证搜索与重置按钮不被折叠隐藏。
#### Scenario: 折叠状态展示操作按钮
- **WHEN** 搜索字段数量超过默认展示区域且组件处于折叠状态
- **THEN** 搜索与重置按钮仍展示在搜索区域右下角
#### Scenario: 展开状态展示操作按钮
- **WHEN** 用户展开搜索区域
- **THEN** 搜索与重置按钮仍展示在搜索区域右下角
#### Scenario: 触发搜索和重置回调
- **WHEN** 用户点击搜索或重置按钮
- **THEN** 组件分别调用传入的搜索或重置回调
### Requirement: 最多两行默认展示
系统 SHALL 默认最多展示两行搜索区域内容,且 SHALL 将操作按钮所在区域计入两行展示高度。
#### Scenario: 字段未超过两行
- **WHEN** 字段数量在默认两行内可完整展示
- **THEN** 组件不展示展开/收起按钮
#### Scenario: 字段超过两行
- **WHEN** 字段数量超过默认两行可展示范围
- **THEN** 组件折叠状态仅展示前两行范围内内容,并展示展开按钮
### Requirement: 展开收起交互
系统 SHALL 在字段超过默认展示区域时提供展开/收起文字按钮,按钮 SHALL 位于搜索与重置按钮左侧,并 SHALL 使用文字与箭头表达当前操作。
#### Scenario: 折叠状态展示展开按钮
- **WHEN** 组件处于折叠状态且存在溢出字段
- **THEN** 操作区在搜索与重置按钮左侧展示“展开”文字按钮和向下箭头
#### Scenario: 展开状态展示收起按钮
- **WHEN** 用户点击展开按钮后
- **THEN** 组件展示全部搜索字段,并在搜索与重置按钮左侧展示“收起”文字按钮和向上箭头
#### Scenario: 展开收起具有动画
- **WHEN** 用户切换展开或收起状态
- **THEN** 搜索字段内容区域以平滑动画过渡到目标高度
### Requirement: Demo 展示组件能力
系统 SHALL 在 demo 中展示 `SearchFilter` 组件,并 SHALL 提供超过两行的配置项用于验证折叠与展开效果。
#### Scenario: Demo 包含多类型字段
- **WHEN** 用户打开组件 demo
- **THEN** demo 展示输入框、仅数字输入框、下拉框、单日期和范围日期配置项
#### Scenario: Demo 可验证展开收起
- **WHEN** 用户打开组件 demo
- **THEN** demo 的字段数量超过默认两行可展示范围,并可通过展开/收起按钮查看动画效果
### Requirement: 业务列表页搜索区迁移
系统 SHALL 使用 `SearchFilter` 替换当前已有列表页搜索区域,并 SHALL 保持既有查询参数、分页重置和列表请求语义。
#### Scenario: Agent 管理搜索区迁移
- **WHEN** 用户打开 Agent 管理列表页
- **THEN** 搜索区使用 `SearchFilter` 渲染 `Agent名称` 输入框、`所属岗位` 下拉框和 `状态` 下拉框
- **AND** `Agent名称` 默认占位文案为“搜索Agent名称”
- **AND** 两个下拉框默认展示组件提供的“全部”选项
#### Scenario: Skill 目录搜索区迁移
- **WHEN** 用户打开 Skill 目录列表页
- **THEN** 搜索区使用 `SearchFilter` 渲染 `关键词` 输入框
- **AND** 输入框显式占位文案为“搜索Skill名称或编码”
#### Scenario: 渠道活码管理搜索区迁移
- **WHEN** 用户打开渠道活码管理列表页
- **THEN** 搜索区使用 `SearchFilter` 渲染 `活码名称` 输入框和 `状态` 下拉框
- **AND** `活码名称` 默认占位文案为“搜索活码名称”
- **AND** `状态` 下拉框默认展示组件提供的“全部”选项
#### Scenario: 岗位标签管理搜索区迁移
- **WHEN** 用户打开岗位标签管理列表页
- **THEN** 搜索区使用 `SearchFilter` 渲染 `标签名称` 输入框
- **AND** `标签名称` 默认占位文案为“搜索标签名称”
#### Scenario: 官网岗位展示配置搜索区迁移
- **WHEN** 用户打开官网岗位展示配置列表页
- **THEN** 搜索区使用 `SearchFilter` 渲染 `关键词` 输入框和 `展示状态` 下拉框
- **AND** 输入框显式占位文案为“搜索岗位名称或渠道活码”
- **AND** `展示状态` 下拉框默认展示组件提供的“全部”选项
#### Scenario: 搜索提交保持页面查询语义
- **WHEN** 用户在迁移后的任一列表页修改搜索条件并点击搜索
- **THEN** 页面按原查询参数语义提交筛选条件
- **AND** 分页重置到第一页
#### Scenario: 重置保持页面查询语义
- **WHEN** 用户在迁移后的任一列表页点击重置
- **THEN** 页面清空对应筛选条件并按原查询参数语义刷新列表
## 1. 组件与 Demo 基础能力
- [x] 1.1 梳理现有 UI 组件测试方式与 demo 入口结构
- [x] 1.2 为 `SearchFilter` 增加组件测试用例,先覆盖配置渲染、数字输入限制、select 默认“全部”、按钮回调、展开/收起和日期范围场景
- [x] 1.3 运行新增测试并确认在实现前失败
## 2. 组件实现与 Demo 展示
- [x] 2.1 新建 `SearchFilter` 组件目录、类型定义和导出入口
- [x] 2.2 实现 `input`、`numberInput`、`select`、单日期 `datePicker`、范围日期 `datePicker(range: true)` 的配置化渲染
- [x] 2.3 实现 `numberInput` 仅数字输入过滤
- [x] 2.4 实现 `select` 自动添加“全部”选项、默认选中“全部”并避免重复添加
- [x] 2.5 实现左右结构布局、普通控件 `200px` 宽度和范围日期跨两项宽度
- [x] 2.6 实现右下角操作区,包含展开/收起、搜索、重置按钮,且搜索/重置不参与收起
- [x] 2.7 实现最多两行默认展示、溢出检测和展开/收起动画
- [x] 2.8 补齐可访问性属性、禁用态和基础 className/style 扩展能力
- [x] 2.9 在 demo 中新增 `SearchFilter` 示例,配置超过两行的示例字段并覆盖多类型字段
## 3. Placeholder 默认规则
- [x] 3.1 为 `SearchFilter` 增加默认 placeholder 测试,覆盖 `input` 默认 `搜索${label}`、`numberInput` 默认 `请输入数字` 和显式 placeholder 优先
- [x] 3.2 将普通 `input` 的默认 placeholder 从“请输入”调整为 `搜索${label}`
- [x] 3.3 确认 demo 中需要表达多字段含义的输入框继续使用显式 placeholder
## 4. 列表页搜索区迁移
- [x] 4.1 迁移 `AgentListPage` 搜索区,字段为 `Agent名称`、`所属岗位`、`状态`,并保持搜索、重置、分页重置和埋点语义
- [x] 4.2 迁移 `SkillListPage` 搜索区,字段为 `关键词`,placeholder 为“搜索Skill名称或编码”
- [x] 4.3 迁移 `ChannelCodeListPage` 搜索区,字段为 `活码名称`、`状态`,状态选择改为筛选草稿并在搜索时提交
- [x] 4.4 迁移 `AgentTagListPage` 搜索区,字段为 `标签名称`
- [x] 4.5 迁移 `OfficialSiteJobTabListPage` 搜索区,字段为 `关键词`、`展示状态`,将组件空字符串“全部”映射到页面既有 `all` 语义
- [x] 4.6 更新或补充受影响页面测试,覆盖搜索提交、重置、select 默认“全部”和 placeholder 文案
## 5. 验证
- [x] 5.1 运行 `SearchFilter` 相关组件测试并确认通过
- [x] 5.2 运行受影响列表页相关测试并确认通过
- [x] 5.3 运行 `npm run typecheck`
- [x] 5.4 运行 `npm run build`
- [x] 5.5 确认本次不进行浏览器验证,原因是用户明确要求“不用浏览器验证”
## Context
`workspace/agent-admin/web/src` 的列表页已经完成 TDesign 化,当前直接从 `tdesign-react` 引入 `Table`、`Pagination` 和 `PrimaryTableCol`。这些页面还分别处理 `Table.empty`、加载失败态、筛选无结果态和分页区域,导致视觉与行为容易漂移。
探索设计见 `docs/superpowers/specs/2026-06-01-business-table-component-design.md`。用户已确认采用方案二:新增 `BusinessTable`,并明确普通空态使用 TDesign 自带状态类型的 `Empty` 组件。
## Goals / Non-Goals
**Goals:**
- 在 `@gl/business-components` 提供可复用 `BusinessTable`。
- 页面通过 `columns`、`data`、`rowKey`、`hasFilter`、`error`、`pagination` 和恢复动作渲染表格。
- 普通空态、筛选空态和加载失败态统一使用 TDesign 自带状态类型的 `Empty` 组件,并由 `BusinessTable` 内置默认文案、图标和按钮文字。
- 筛选空态和失败态的操作按钮保持明确的可操作性;其中筛选空态的“清空筛选”按钮和失败态的“重试”按钮均使用实色 primary。
- 列表页表格中的操作项按钮统一使用 `theme="primary"`、`variant="text"`,避免不同页面的操作权重不一致。
- 支持透传 TDesign `Table` 属性,例如 `hover`、`stripe`、`maxHeight`、选择、排序、行样式和事件回调。
- 通过不同背景色区分表头和表体,增强层级感和可扫读性。
- 空态内容在表格可用区域内保持更居中的视觉位置,避免整体贴近表头。
- 第一批迁移现有后台列表页,减少页面重复结构。
**Non-Goals:**
- 不替换 TDesign `PrimaryTableCol<T>` 列配置体系。
- 不接管页面查询、URL 参数、接口请求、弹窗、权限、埋点和业务列渲染。
- 不把搜索区、工具栏和表格合并成完整列表页渲染器。
- 不开放 `empty` 原样透传绕过统一空态;若后续确有特殊空态,再单独扩展受控插槽。
- 不清理旧 `workspace/agent-admin/web/packages/ui` 表格源码。
## Decisions
### Decision 1:新增 `BusinessTable` 而不是只抽空态
采用 `BusinessTable` 封装 TDesign `Table`、表格状态和可选分页。页面继续定义业务 columns 和行操作。
备选方案一是只新增 `TableEmpty`,但无法减少失败态、分页和表格结构重复。备选方案三是完整 `ListPageRenderer`,但会与搜索、请求和弹窗流程耦合过深。
### Decision 2:状态展示使用 TDesign `Empty`
普通空态、筛选空态和加载失败态都使用 TDesign 自带状态类型的 `Empty` 组件。普通空态使用“暂无数据”;筛选空态使用“未找到匹配结果”并提供“清空筛选”;加载失败态使用“加载失败”并提供“重试”。页面不传入这些状态文案,避免不同列表页重复或漂移。
这一选择能与 TDesign 视觉体系保持一致,也避免业务组件自行维护图标资源。
### Decision 3:TDesign Table 属性以透传为主
`BusinessTableProps<T>` 继承 TDesign `TableProps<T>` 的大部分属性,但由业务组件接管 `columns`、`data`、`rowKey` 和 `empty`。其余属性通过剩余 props 传入内部 `Table`。
这样既能统一空态,又保留页面使用 TDesign 表格能力的空间。
状态配置仅保留恢复动作:筛选空态接收 `filteredEmptyState.onAction`,加载失败态接收 `errorState.onRetry`。`title`、`description`、`actionText` 和 `retryText` 等展示内容不由业务页面传入。
### Decision 4:分页是业务表格的可选区域
`pagination` 存在时渲染 TDesign `Pagination`,`pagination={false}` 时不渲染分页区。无分页但需要统计信息的页面可通过 `totalLabel` 展示底部总数。
这样能覆盖当前分页列表和 `SkillListPage` 这类无分页列表。
### Decision 5:分批迁移列表页
先实现组件与组件测试,再迁移页面。页面迁移只替换表格、空态、失败态和分页结构,不改业务数据流。
### Decision 6:表头与表体使用不同背景色
`BusinessTable` 的表头与表体采用不同背景色,作为业务表格的默认视觉分层,不要求各页面单独处理。
### Decision 7:空态恢复操作按钮使用实色 primary
筛选空态中的“清空筛选”和失败态中的“重试”都属于恢复当前列表可用性的明确操作,使用 TDesign primary 实色按钮,保证按钮在空白区域中有足够识别度。
空态内容使用更充足的垂直空间和居中布局,避免在表头下方显得过于靠上。
## Risks / Trade-offs
- [Risk] `TableProps<T>` 类型透传过窄会阻断页面已有能力。
→ Mitigation:组件类型基于 TDesign `TableProps<T>`,测试覆盖至少一个透传属性。
- [Risk] `empty` 不开放原样透传可能限制特殊页面。
→ Mitigation:本轮先保持统一空态;确有特殊场景时另开受控插槽变更。
- [Risk] 页面迁移过程中可能改变分页或重置行为。
→ Mitigation:迁移时保留现有回调与状态来源,并补充列表页回归测试。
- [Risk] TDesign `Empty` 状态类型 API 与预期有差异。
→ Mitigation:实现前以本地类型和测试确认 API,必要时使用 TDesign 支持的最近等价状态类型。
## Migration Plan
1. 为 `BusinessTable` 编写失败测试,覆盖数据渲染、三类状态、按钮回调、按钮样式、分页和属性透传。
2. 在 `packages/business-components` 实现 `BusinessTable` 并导出组件与类型。
3. 按列表页逐个迁移直接使用的 `Table`、`Pagination` 和 `StatePlaceholder` 表格状态结构。
4. 运行组件测试、页面测试、类型检查、构建和 OpenSpec 严格校验。
5. 启动前端页面,在浏览器中验证普通数据、筛选空态和加载失败态布局。
回滚时可以逐页恢复为直接使用 TDesign `Table` 和 `Pagination`。本轮不删除旧代码目录,因此回滚不涉及源码恢复。
## Open Questions
- 无。用户已确认采用方案二,并确认普通空态使用 TDesign 自带状态类型的 `Empty` 组件。
## Why
后台列表页已经直接使用 TDesign `Table`,但表格渲染、空态、筛选空态、加载失败态和分页结构仍分散在页面内维护。需要把表格提取为可复用业务组件,让页面通过配置渲染表格,并统一表格状态展示。
## What Changes
- 在 `@gl/business-components` 新增 `BusinessTable` 业务表格组件。
- `BusinessTable` 内部基于 TDesign `Table` 渲染,继续兼容 TDesign 列配置。
- 统一普通空态、筛选空态和加载失败态:文案、图标和按钮文字由 `BusinessTable` 内置,业务页面只传入状态和恢复动作。
- 筛选空态提供“清空筛选”操作,加载失败态提供“重试”操作,操作按钮均为 TDesign primary 实色按钮。
- 表格中的操作项按钮统一使用 TDesign primary 文字按钮,保持列表页操作权重一致。
- 表格表头与内容区使用不同背景色,增强层级区分和可扫读性。
- 支持将 TDesign `Table` 属性透传到内部表格,避免页面失去原生表格能力。
- 第一批迁移已有后台列表页,页面不再重复维护表格空态、失败态、筛选空态文案和分页结构。
- 不改变现有列表页接口契约、路由、查询参数、弹窗流程和业务列渲染。
## Capabilities
### New Capabilities
- `business-table`: 定义全局业务表格组件的配置渲染、状态展示、操作按钮、分页和 TDesign Table 属性透传能力。
### Modified Capabilities
- 无。
## Impact
- 受影响组件包:根目录 `packages/business-components`。
- 受影响页面:`AgentListPage`、`AgentTagListPage`、`ChannelCodeListPage`、`OfficialSiteJobTabListPage`、`SkillListPage`、`OfficialSiteAgentDisplayConfigPage`。
- 受影响测试:全局业务组件测试和至少一个业务列表页回归测试。
- 依赖影响:继续使用既有 `tdesign-react`,不新增外部依赖。
## ADDED Requirements
### Requirement: 配置化业务表格渲染
系统 SHALL 在 `@gl/business-components` 提供 `BusinessTable` 组件,允许页面通过 TDesign 兼容的列配置、数据、行键、状态布尔值和恢复动作渲染业务表格。
#### Scenario: 渲染表格数据
- **WHEN** 页面向 `BusinessTable` 传入 `columns`、`data` 和 `rowKey`
- **THEN** 系统 SHALL 使用 TDesign `Table` 渲染对应表头和行数据
#### Scenario: 兼容 TDesign 列配置
- **WHEN** 页面传入 TDesign `PrimaryTableCol<T>` 兼容的列配置
- **THEN** 系统 SHALL 保留列标题、字段映射、自定义渲染和操作列能力
### Requirement: 普通空态
系统 SHALL 在无错误、非加载、无数据且无筛选条件时展示普通空态。
#### Scenario: 无筛选条件且无数据
- **WHEN** `error` 不为 `true`、`loading` 不为 `true`、`data` 为空且 `hasFilter` 不为 `true`
- **THEN** 系统 SHALL 使用 TDesign 自带状态类型的 `Empty` 组件展示空态图标和“暂无数据”
#### Scenario: 普通空态无操作
- **WHEN** 系统展示普通空态
- **THEN** 系统 SHALL NOT 默认展示描述文案或操作按钮
### Requirement: 筛选空态
系统 SHALL 在无错误、非加载、无数据且存在筛选条件时展示筛选空态。
#### Scenario: 筛选无结果
- **WHEN** `error` 不为 `true`、`loading` 不为 `true`、`data` 为空且 `hasFilter` 为 `true`
- **THEN** 系统 SHALL 使用 TDesign 自带状态类型的 `Empty` 组件展示空态图标和单一文案“未找到匹配结果”
- **AND** 系统 SHALL NOT 展示“暂无数据”或“未能查询到符合条件的资源”等重复描述文案
#### Scenario: 清空筛选操作
- **WHEN** 筛选空态配置提供清空筛选回调
- **THEN** 系统 SHALL 展示文案为“清空筛选”的 TDesign primary 实色按钮
#### Scenario: 触发清空筛选
- **WHEN** 用户点击筛选空态中的“清空筛选”按钮
- **THEN** 系统 SHALL 调用筛选空态配置提供的清空筛选回调
#### Scenario: 页面不传筛选空态文案
- **WHEN** 页面使用 `BusinessTable` 展示筛选空态
- **THEN** 页面 SHALL 仅通过 `hasFilter` 表达筛选状态,并 MAY 通过 `filteredEmptyState.onAction` 提供清空筛选回调
- **AND** 页面 SHALL NOT 传入筛选空态的 `title`、`description` 或 `actionText`
### Requirement: 加载失败态
系统 SHALL 在表格加载失败时展示加载失败态,并提供可恢复操作。
#### Scenario: 展示加载失败
- **WHEN** `error` 为 `true`
- **THEN** 系统 SHALL 不渲染表格主体,并使用 TDesign 自带状态类型的 `Empty` 组件展示错误图标和失败标题
- **AND** 系统 SHALL 默认展示“加载失败”
- **AND** 页面 SHALL NOT 传入加载失败态的 `title`、`description` 或 `retryText`
#### Scenario: 重试操作
- **WHEN** 加载失败态配置提供重试回调
- **THEN** 系统 SHALL 展示文案为“重试”的 TDesign primary 实色按钮
#### Scenario: 触发重试
- **WHEN** 用户点击加载失败态中的“重试”按钮
- **THEN** 系统 SHALL 调用加载失败态配置提供的重试回调
### Requirement: TDesign Table 属性透传
系统 SHALL 支持将未被 `BusinessTable` 接管的 TDesign `Table` 属性透传给内部 `Table`。
#### Scenario: 透传展示属性
- **WHEN** 页面向 `BusinessTable` 传入 TDesign `Table` 的展示属性
- **THEN** 系统 SHALL 将该属性应用到内部 TDesign `Table`
#### Scenario: 透传交互属性
- **WHEN** 页面向 `BusinessTable` 传入 TDesign `Table` 的选择、排序、行样式或事件回调属性
- **THEN** 系统 SHALL 将该属性传递给内部 TDesign `Table` 并保留对应交互能力
### Requirement: 操作项按钮样式统一
系统 SHALL 在使用 `BusinessTable` 的列表页中,将表格操作列中的操作项按钮统一渲染为 TDesign primary 文字按钮。
#### Scenario: 渲染操作列按钮
- **WHEN** 页面在表格操作列中渲染行级操作按钮
- **THEN** 系统 SHALL 使用 `theme="primary"` 且 `variant="text"` 的按钮样式
### Requirement: 可选分页和总数展示
系统 SHALL 支持在业务表格底部渲染可选分页或总数信息。
#### Scenario: 渲染分页
- **WHEN** 页面传入分页配置
- **THEN** 系统 SHALL 使用 TDesign `Pagination` 渲染当前页、页大小、总数和分页回调
#### Scenario: 禁用分页
- **WHEN** 页面传入 `pagination={false}`
- **THEN** 系统 SHALL NOT 渲染分页组件
#### Scenario: 展示总数文案
- **WHEN** 页面传入 `totalLabel`
- **THEN** 系统 SHALL 在表格底部展示该总数文案
### Requirement: 空态视觉位置
系统 SHALL 在表格空态展示时保持更居中的视觉位置,避免内容紧贴表头。
#### Scenario: 空态垂直居中
- **WHEN** `BusinessTable` 展示普通空态、筛选空态或加载失败态
- **THEN** 系统 SHALL 使用足够的垂直空间和居中布局展示空态内容,使其不显得贴近表头
### Requirement: 后台列表页迁移
系统 SHALL 将当前后台列表页迁移为使用 `BusinessTable` 渲染表格状态和分页区域。
#### Scenario: 列表页使用业务表格
- **WHEN** 迁移 `AgentListPage`、`AgentTagListPage`、`ChannelCodeListPage`、`OfficialSiteJobTabListPage`、`SkillListPage` 和 `OfficialSiteAgentDisplayConfigPage`
- **THEN** 这些页面 SHALL 使用 `BusinessTable` 承接表格、空态、失败态和分页展示
#### Scenario: 保持业务行为
- **WHEN** 页面迁移到 `BusinessTable`
- **THEN** 系统 SHALL 保持现有查询、重置、分页、弹窗和行操作行为不变
## 1. 组件测试基线
- [x] 1.1 为 `BusinessTable` 增加配置化渲染失败测试,覆盖 `columns`、`data` 和 `rowKey`
- [x] 1.2 为普通空态增加失败测试,确认使用 TDesign `Empty` 展示“暂无数据”且无默认操作
- [x] 1.3 为筛选空态增加失败测试,确认仅展示“未找到匹配结果”和“清空筛选”回调
- [x] 1.4 为加载失败态增加失败测试,确认展示错误状态、失败标题和“重试”回调
- [x] 1.5 为操作按钮样式增加失败测试,确认筛选空态和失败态按钮为 primary 按钮
- [x] 1.6 为 TDesign `Table` 属性透传增加失败测试,至少覆盖一个展示属性和一个交互或行样式属性
- [x] 1.7 为分页和总数展示增加失败测试,覆盖分页渲染、禁用分页和 `totalLabel`
## 2. 业务组件实现
- [x] 2.1 在 `packages/business-components` 新增 `BusinessTable` 组件、样式和类型定义
- [x] 2.2 使用 TDesign `Table` 渲染表格,并透传未接管的 TDesign `Table` 属性
- [x] 2.3 使用 TDesign 自带状态类型的 `Empty` 实现普通空态、筛选空态和加载失败态
- [x] 2.4 使用 TDesign `Button` 实现 primary 按钮操作
- [x] 2.5 使用 TDesign `Pagination` 实现可选分页,并支持 `pagination={false}` 与 `totalLabel`
- [x] 2.6 从 `@gl/business-components` 统一导出 `BusinessTable` 和相关类型
- [x] 2.7 运行 `BusinessTable` 相关测试并确认通过
- [x] 2.8 为 `BusinessTable` 添加表头与表体的背景色区分样式
- [x] 2.9 统一表格操作项按钮为 TDesign `theme="primary"` 文字按钮
## 3. 页面迁移
- [x] 3.1 迁移 `AgentListPage`,用 `BusinessTable` 承接表格、空态、失败态和分页
- [x] 3.2 迁移 `AgentTagListPage`,用 `BusinessTable` 承接表格、空态、失败态和分页
- [x] 3.3 迁移 `ChannelCodeListPage`,用 `BusinessTable` 承接表格、空态、失败态和分页
- [x] 3.4 迁移 `OfficialSiteJobTabListPage`,用 `BusinessTable` 承接表格、空态、失败态和分页
- [x] 3.5 迁移 `SkillListPage`,用 `BusinessTable` 承接表格、空态、失败态和无分页总数展示
- [x] 3.6 迁移 `OfficialSiteAgentDisplayConfigPage`,用 `BusinessTable` 承接表格和加载失败态
- [x] 3.7 清理迁移页面中不再需要的直接 `Table`、`Pagination` 和表格状态占位 import
## 4. 回归验证
- [x] 4.1 补充或调整至少一个业务列表页回归测试,覆盖普通空态、筛选空态和加载失败态
- [x] 4.2 运行业务表格组件测试和受影响列表页测试
- [x] 4.3 运行 `npm run typecheck`
- [x] 4.4 运行 `npm run build`
- [x] 4.5 运行 `openspec validate "extract-business-table-component" --strict`
- [x] 4.6 在浏览器中验证主要列表页普通数据、筛选空态和加载失败态布局
- [x] 4.7 在浏览器中确认表头与表体背景色区分效果
## 5. 体验微调
- [x] 5.1 调整 `BusinessTable` 空态容器的垂直位置,让普通空态、筛选空态和加载失败态更居中
- [x] 5.2 将筛选空态“清空筛选”按钮调整为 TDesign primary 实色按钮
- [x] 5.3 将加载失败态“重试”按钮调整为 TDesign primary 实色按钮
- [x] 5.4 补充相关测试,覆盖筛选空态、加载失败态按钮样式和空态视觉布局
- [x] 5.5 将岗位标签列表加载失败态收敛为组件内置“加载失败”标题 + “重试”实色按钮,移除业务页重复描述文案
- [x] 5.6 收敛 `BusinessTable` 状态 API:普通空态、筛选空态和加载失败态的文案与按钮文字由组件内置,业务页面只传入状态和恢复动作
# 设计说明
## 决策
`BusinessTable` 继续接管表格状态展示,并以内置状态配置生成 TDesign `Empty` 内容。普通空态、筛选无结果态和加载失败态都展示标题与说明文案;有恢复动作时展示 TDesign primary 实色按钮。
普通空态继续使用 TDesign `Empty` 的 `type="empty"`,以保留默认“暂无数据”图标。筛选无结果态使用 `SearchIcon` 作为自定义图标表达搜索无结果。加载失败态默认使用网络不可用语义,并支持权限受限语义。
## 状态文案
- 普通空态:标题“暂无数据”,说明“请先创建项目”,无默认按钮。
- 筛选无结果态:标题“未找到匹配结果”,说明“请调整搜索或筛选条件”,按钮“清空筛选”。
- 网络不可用态:标题“网络不可用”,说明“请检查网络连接后重试”,按钮“重新连接”。
- 权限受限态:标题“权限受限”,说明“当前账号暂无访问权限”,按钮“申请权限”。
## 约束
状态标题、说明和按钮文案继续由组件内置,业务页面不得传入文案字段。这样可以避免不同列表页状态表达漂移。
`errorState.kind` 仅用于选择错误语义,允许值为 `offline` 和 `forbidden`。未传时默认 `offline`,兼容现有只传 `onRetry` 的列表页。
## 验证
- 更新 `BusinessTable` 组件测试,覆盖三类状态的标题、说明、按钮和按钮回调。
- 运行 `BusinessTable` 相关测试。
- 运行前端类型检查。
# 优化业务表格状态占位
## 背景
`BusinessTable` 当前空态、筛选无结果态和加载失败态主要展示单一标题,说明文案不足。用户希望表格内各种状态统一采用“图标 + 标题 + 浅色说明 + 操作按钮”的状态块样式,其中普通“暂无数据”图标保持不变。
## 变更内容
- 调整 `BusinessTable` 内置状态展示,普通空态展示标题和浅色说明。
- 调整筛选无结果态展示搜索语义图标、标题、浅色说明和“清空筛选”主按钮。
- 调整网络不可用态展示失败语义图标、标题、浅色说明和“重新连接”主按钮。
- 支持权限受限态展示权限语义图标、标题、浅色说明和“申请权限”主按钮。
- 保持页面 API 收敛,业务页面仍只传入状态布尔值和恢复动作回调,不传状态文案。
## 非目标
- 不新增页面级自定义状态文案 API。
- 不改动业务列表页的数据请求、筛选、分页和行操作行为。
- 不替换普通“暂无数据”的默认图标。
## MODIFIED Requirements
### Requirement: 普通空态
系统 SHALL 在无错误、非加载、无数据且无筛选条件时展示普通空态。
#### Scenario: 无筛选条件且无数据
- **WHEN** `error` 不为 `true`、`loading` 不为 `true`、`data` 为空且 `hasFilter` 不为 `true`
- **THEN** 系统 SHALL 使用 TDesign 自带状态类型的 `Empty` 组件展示普通空态图标和标题“暂无数据”
- **AND** 系统 SHALL 展示浅色说明文案“请先创建项目”
#### Scenario: 普通空态无操作
- **WHEN** 系统展示普通空态
- **THEN** 系统 SHALL NOT 默认展示操作按钮
### Requirement: 筛选空态
系统 SHALL 在无错误、非加载、无数据且存在筛选条件时展示筛选空态。
#### Scenario: 筛选无结果
- **WHEN** `error` 不为 `true`、`loading` 不为 `true`、`data` 为空且 `hasFilter` 为 `true`
- **THEN** 系统 SHALL 使用搜索语义图标展示标题“未找到匹配结果”
- **AND** 系统 SHALL 展示浅色说明文案“请调整搜索或筛选条件”
- **AND** 系统 SHALL NOT 展示“暂无数据”
#### Scenario: 清空筛选操作
- **WHEN** 筛选空态配置提供清空筛选回调
- **THEN** 系统 SHALL 展示文案为“清空筛选”的 TDesign primary 实色按钮
#### Scenario: 触发清空筛选
- **WHEN** 用户点击筛选空态中的“清空筛选”按钮
- **THEN** 系统 SHALL 调用筛选空态配置提供的清空筛选回调
#### Scenario: 页面不传筛选空态文案
- **WHEN** 页面使用 `BusinessTable` 展示筛选空态
- **THEN** 页面 SHALL 仅通过 `hasFilter` 表达筛选状态,并 MAY 通过 `filteredEmptyState.onAction` 提供清空筛选回调
- **AND** 页面 SHALL NOT 传入筛选空态的 `title`、`description` 或 `actionText`
### Requirement: 加载失败态
系统 SHALL 在表格加载失败或不可访问时展示错误状态块,并提供可恢复操作。
#### Scenario: 展示网络不可用
- **WHEN** `error` 为 `true`
- **THEN** 系统 SHALL 不渲染表格主体,并展示标题“网络不可用”
- **AND** 系统 SHALL 展示浅色说明文案“请检查网络连接后重试”
- **AND** 页面 SHALL NOT 传入加载失败态的 `title`、`description` 或 `retryText`
#### Scenario: 重新连接操作
- **WHEN** 网络不可用态配置提供重试回调
- **THEN** 系统 SHALL 展示文案为“重新连接”的 TDesign primary 实色按钮
#### Scenario: 触发重新连接
- **WHEN** 用户点击网络不可用态中的“重新连接”按钮
- **THEN** 系统 SHALL 调用加载失败态配置提供的重试回调
#### Scenario: 展示权限受限
- **WHEN** `error` 为 `true` 且 `errorState.kind` 为 `forbidden`
- **THEN** 系统 SHALL 不渲染表格主体,并展示权限受限语义图标和标题“权限受限”
- **AND** 系统 SHALL 展示浅色说明文案“当前账号暂无访问权限”
#### Scenario: 申请权限操作
- **WHEN** 权限受限态配置提供重试回调
- **THEN** 系统 SHALL 展示文案为“申请权限”的 TDesign primary 实色按钮
#### Scenario: 触发申请权限
- **WHEN** 用户点击权限受限态中的“申请权限”按钮
- **THEN** 系统 SHALL 调用加载失败态配置提供的重试回调
### Requirement: 空态视觉位置
系统 SHALL 在表格空态展示时保持更居中的视觉位置,避免内容紧贴表头。
#### Scenario: 空态垂直居中
- **WHEN** `BusinessTable` 展示普通空态、筛选空态或加载失败态
- **THEN** 系统 SHALL 使用足够的垂直空间和居中布局展示图标、标题、浅色说明和可选操作按钮,使其不显得贴近表头
# Tasks
- [x] 1. 更新 `business-table` OpenSpec delta,描述统一状态块展示规则。
- [x] 2. 更新 `BusinessTable` 测试,覆盖标题、浅色说明和操作按钮。
- [x] 3. 实现 `BusinessTable` 状态展示调整。
- [x] 4. 运行相关测试和类型检查。
# 设计:统一登录后后台框架布局
## 方案
在工作区共享包 `@gl/business-components` 中新增 `BusinessAdminShell`:
- 基于 TDesign `Menu` 渲染一二级菜单。
- 基于 TDesign `Menu` 的 `collapsed` 和宽度能力实现左侧菜单收起/展开。
- 基于 TDesign `Breadcrumb` 渲染 header 左侧面包屑。
- 基于 TDesign `Avatar`、`Button`、`Dropdown` 渲染 header 右侧用户区。
- 由业务项目传入系统名称、菜单配置、当前菜单、面包屑、用户信息和动作回调。
- 菜单配置增加可选 `icon` 字段,业务项目 SHALL 从 `tdesign-icons-react` 选择图标组件后传入;共享组件只负责渲染,不在内部硬编码业务菜单图标。
- 组件内部固定结构、header 高度和 content padding,业务页面只负责传配置和页面内容。
## agent-admin 集成
`workspace/agent-admin/web/src/layouts/AdminShell.tsx` 继续负责:
- 根据当前 `location.pathname` 计算当前菜单、展开菜单和面包屑。
- 在菜单配置中为一级菜单传入 `tdesign-icons-react` 图标。
- 处理菜单跳转。
- 处理退出登录确认弹窗和实际退出逻辑。
`BusinessAdminShell` 负责:
- 渲染左右布局。
- 渲染左侧系统名称和菜单。
- 渲染菜单收起/展开按钮,并在收起时将左侧宽度切换到图标宽度。
- 将每个菜单项配置中的 `icon` 透传给 TDesign `Menu` / `SubMenu`。
- 渲染右侧 header/content。
- 在无个人信息功能时直接显示退出登录按钮。
- 在有个人信息功能时通过头像下拉菜单展示个人信息和退出登录。
## 路由规则
默认受保护路由继续跳转到第一个菜单项 `/agents`。后续项目应按照菜单配置的第一个可用二级菜单设置默认跳转。
## 面包屑规则
普通二级菜单页面展示:
`一级菜单 > 二级菜单`
独立页面展示:
`一级菜单 > 二级菜单 > 独立页面名称`
其中二级菜单项可点击并返回对应二级菜单页面。
## 独立页面页头规则
新增、编辑等独立页面继续使用当前 `agent-admin` 表单页的基本布局:
- 页头左侧展示 `返回` 按钮、页面标题和说明文案。
- 页头右侧只展示主操作 `保存`,不展示 `取消` 按钮。
- `返回` 负责离开当前独立页面;不再提供第二个等价的取消入口。
- 页头使用 `position: sticky` 固定在内容滚动容器顶部,表单内容滚动时 `返回` 和 `保存` 所在区域保持可见。
- sticky 页头需要设置背景色、边框和合理层级,避免滚动内容穿透或覆盖页头。
- sticky 位置以后台框架 content 滚动容器为参照,不改变全局 header、左侧菜单和业务表单数据逻辑。
# 变更提案:统一登录后后台框架布局
## 背景
登录页已经沉淀为 `@gl/business-components` 业务组件。登录后的后台框架也需要形成跨前端项目复用的固定规范,避免每个项目重复实现左侧菜单、顶部面包屑、用户区和内容间距。
## 目标
- 将登录后的后台框架布局固定为左侧菜单、右侧 header/content 结构。
- 默认路由落到第一个可用二级菜单。
- 左侧展示系统名称和一二级菜单。
- 左侧菜单支持收起和展开,收起后保留图标导航能力。
- 菜单图标由业务项目菜单配置传入,图标来源统一使用 `tdesign-icons-react`。
- 右侧 header 固定高度,左侧展示可点击面包屑,右侧展示用户名称、头像和退出/个人信息入口。
- content 区域固定 24px 内边距。
- 在 `@gl/business-components` 中提供可复用业务组件,`agent-admin` 使用该组件承载现有后台页面。
- `agent-admin` 在菜单配置中传入 TDesign 图标,并接入共享框架的收起/展开能力。
- 全框架下新增/编辑等独立页面沿用 `agent-admin` 的独立页结构,但页头操作区需固定在内容滚动容器顶部,滚动表单内容时返回和保存入口保持可见。
- 独立新增/编辑页头右侧不再展示 `取消` 按钮,仅保留主操作 `保存`;返回行为统一由左侧 `返回` 入口承载。
## 非目标
- 本次不引入真实个人信息页面。
- 本次不改变各业务列表、表单页面的数据逻辑。
- 本次不归档已有 OpenSpec change。
## MODIFIED Requirements
### Requirement: 受保护后台框架
岗位 Agent 管理后台 SHALL 在共享的受保护后台框架内展示管理页面。
#### Scenario: 展示固定后台框架结构
- **WHEN** 已登录用户打开受保护管理页面
- **THEN** 岗位 Agent 管理后台展示左侧菜单和右侧内容的左右结构
- **AND** 左侧菜单顶部展示系统名称 `岗位Agent管理后台`
- **AND** 右侧内容区域分为固定高度 header 和 content 两部分
- **AND** content 区域内边距为 `24px`
- **AND** 后台框架通过 `@gl/business-components` 的登录后框架业务组件渲染
#### Scenario: 收起和展开左侧菜单
- **WHEN** 已登录用户点击左侧菜单的收起按钮
- **THEN** 左侧菜单切换为收起状态
- **AND** 菜单仅保留可识别的菜单图标导航
- **WHEN** 用户再次点击展开按钮
- **THEN** 左侧菜单恢复展示系统名称和菜单文字
#### Scenario: 展示用户区
- **WHEN** 当前系统没有个人信息功能
- **THEN** header 右侧展示用户名称
- **AND** header 右侧展示用户头像
- **AND** 用户没有头像时使用默认背景色并显示用户名称第一个字
- **AND** `退出登录` 按钮展示在头像右侧
#### Scenario: 展示个人信息下拉菜单
- **WHEN** 当前系统启用个人信息功能
- **THEN** header 右侧头像可点击
- **AND** 点击头像后下拉菜单展示 `个人信息` 和 `退出登录`
### Requirement: 管理后台导航
岗位 Agent 管理后台 SHALL 将 Agent 管理作为首个可用管理模块提供导航,并为后续已确认模块保留扩展空间。
#### Scenario: 默认跳转到第一个菜单
- **WHEN** 已登录用户打开应用根路径
- **THEN** 岗位 Agent 管理后台跳转到第一个可用二级菜单页面 `Agent列表`
#### Scenario: 展示一二级菜单
- **WHEN** 已登录用户打开任意受保护页面
- **THEN** 左侧菜单展示一级菜单
- **AND** 左侧菜单展示一级菜单下方的二级菜单
- **AND** 当前二级菜单保持选中
#### Scenario: 点击一级菜单切换二级菜单展开状态
- **WHEN** 已登录用户点击展开态左侧菜单中带子菜单的一级菜单
- **THEN** 该一级菜单下方的二级菜单在展开和收起之间切换
- **AND** 路由默认展开的一级菜单不阻止用户手动收起或展开
#### Scenario: 通过菜单配置展示图标
- **WHEN** 已登录用户打开任意受保护页面
- **THEN** 左侧菜单图标由 `agent-admin` 的菜单配置传入
- **AND** 菜单图标使用 `tdesign-icons-react` 图标组件
- **AND** 共享后台框架不在内部硬编码业务菜单图标
### Requirement: 后台框架面包屑
岗位 Agent 管理后台 SHALL 在 header 左侧展示当前页面的层级面包屑。
#### Scenario: 二级菜单页面面包屑
- **WHEN** 已登录用户打开二级菜单页面
- **THEN** header 左侧展示 `一级菜单 > 二级菜单`
#### Scenario: 独立页面面包屑
- **WHEN** 已登录用户打开新增或编辑等独立页面
- **THEN** header 左侧展示 `一级菜单 > 二级菜单 > 独立页面名称`
- **AND** 点击二级菜单面包屑项返回该二级菜单页面
### Requirement: 独立页面页头操作区
岗位 Agent 管理后台 SHALL 为新增、编辑等独立页面提供一致且滚动可见的页头操作区。
#### Scenario: 独立页面不展示右侧取消按钮
- **WHEN** 已登录用户打开新增或编辑等独立页面
- **THEN** 独立页面页头左侧展示 `返回` 入口
- **AND** 独立页面页头右侧展示 `保存` 主操作
- **AND** 独立页面页头右侧不展示 `取消` 按钮
#### Scenario: 滚动时保持页头操作区可见
- **WHEN** 已登录用户在新增或编辑等独立页面向下滚动表单内容
- **THEN** 独立页面页头操作区保持在内容滚动容器顶部可见
- **AND** `返回` 和 `保存` 入口保持可点击
- **AND** 滚动内容不得覆盖页头操作区
# 任务
## 1. 规范
- [x] 1.1 创建登录后框架布局 OpenSpec change。
- [x] 1.2 更新全局组件规范,记录 `@gl/business-components` 登录后框架规则。
## 2. 实现
- [x] 2.1 在 `@gl/business-components` 新增 `BusinessAdminShell`。
- [x] 2.2 让 `agent-admin` 的 `AdminShell` 使用共享业务组件。
- [x] 2.3 支持普通二级菜单和新增/编辑等独立页面的面包屑。
- [x] 2.4 保持无个人信息功能时头像右侧直接展示退出登录按钮。
- [x] 2.5 支持左侧菜单收起/展开,并在收起后保留图标导航。
- [x] 2.6 让 `agent-admin` 通过菜单配置传入 `tdesign-icons-react` 图标。
- [x] 2.7 修复展开态下点击一级菜单不能切换二级菜单展开状态的问题。
- [x] 2.8 移除新增/编辑等独立页面页头右侧的 `取消` 按钮,保留左侧 `返回` 和右侧 `保存`。
- [x] 2.9 将新增/编辑等独立页面页头操作区改为内容滚动容器内 sticky,滚动表单内容时保持 `返回`/`保存` 可见。
## 3. 验证
- [x] 3.1 补充共享登录后框架组件测试。
- [x] 3.2 补充 `agent-admin` 路由与面包屑测试。
- [x] 3.3 补充左侧菜单收起/展开和菜单图标渲染测试。
- [x] 3.4 运行相关测试、类型检查、构建和 OpenSpec 校验。
- [x] 3.5 补充一级菜单点击展开/收起的回归测试并重新验证。
- [x] 3.6 补充独立新增/编辑页测试,覆盖右侧无 `取消`、`保存` 保留、页头 sticky 样式。
- [x] 3.7 运行相关页面测试、类型检查、构建、OpenSpec 校验和浏览器滚动验证。
## Context
`agent-admin/web` 已有独立登录页、路由守卫和本地固定账号密码校验。当前需求把登录页视觉提升为工作区级固定规范,后续所有前端项目都应复用同一套页面结构和交互规则。
## Goals / Non-Goals
**Goals:**
- 固定登录页的信息层级:系统名称、系统描述、账号密码输入框、登录动作。
- 固定登录页表单布局:不显示账号、密码字段标签,字段提示放入 placeholder,输入框提供用户、锁和密码可见性图标。
- 固定登录页背景规则:背景图片等比例居中,底色与图片同色系,登录区域最低高度 `350px`,并水平和垂直居中。
- 当前项目通过 `@gl/business-components` 的登录页业务组件实现页面结构,业务组件内部直接组合 TDesign 基础组件。
- 将规则写入工作区级组件规范,作为后续项目复用 `@gl/business-components` 登录业务组件的输入。
**Non-Goals:**
- 不改登录账号、密码、登录态保存、路由守卫或退出登录流程。
- 不引入真实鉴权接口。
- 不改造整个仓库为根级 npm workspace。
## Decisions
1. 新增根级 `packages/business-components` 源码包,并导出登录页业务组件。当前仓库尚未建立根级包管理 workspace,因此 `agent-admin/web` 先通过 TS/Vite alias 引入 `@gl/business-components`,后续补 workspace 时保持包名不变。
2. 登录业务组件内部直接使用 `tdesign-react` 的 `Input` 和 `Button`,图标使用 `tdesign-icons-react`。这样与工作区级“基础组件直接来自 TDesign”的方向一致,也避免继续扩展项目内同名基础组件。
3. 密码可见性切换放在密码输入框 `suffixIcon` 区域,并使用 `button` 包裹眼睛图标,提供明确的 `aria-label`。这样可以保留键盘可访问性,也便于测试通过语义查找。
4. 背景图片由业务项目传入,当前 `agent-admin/web` 继续使用稳定的 SVG data URL。背景色由业务项目通过 `backgroundColor` 参数传入,避免共享组件写死色值,也便于不同系统按品牌色配置。
5. 登录页布局使用 CSS Grid 实现全屏居中,登录区域保持固定最大宽度和响应式横向内边距。这样桌面端与窄屏下都能保持视觉稳定。
## Risks / Trade-offs
- 背景图不是最终品牌资产 → 后续拿到品牌图后只替换传入的 `backgroundImage` 来源,保留 `background-size: contain`、`background-position: center` 和同色系底色。
- 当前仓库没有根级 workspace 包管理 → 先保持 `packages/business-components` 的源码包结构和 `@gl/business-components` 导入名,后续纳入根级 workspace 时不改变业务代码导入方式。
## Why
登录页是所有前端项目进入系统前的统一入口,需要有固定的信息层级、表单排布和背景视觉规则。当前 `agent-admin/web` 登录页只满足基础登录能力,尚未对齐工作区级登录页规范。
## What Changes
- 登录页固定展示系统名称和系统描述:系统名称使用深色、加粗大标题;系统描述位于下方,使用浅色正常字号。
- 登录表单不显示账号、密码字段标签,字段提示放入输入框 placeholder:`请输入账号`、`请输入密码`。
- 账号输入框左侧展示用户图标,密码输入框左侧展示锁图标。
- 密码输入框提供眼睛图标,用于切换密码可见性。
- 登录页增加背景图片,图片等比例居中显示,底层铺设同色系背景色,登录区域最低高度为 `350px`,并在背景上水平和垂直居中。
- 将上述规则沉淀到工作区级组件规范,作为所有前端项目登录页默认规则。
## Capabilities
### New Capabilities
- 无。
### Modified Capabilities
- `admin-login`:补充登录页展示层级、表单排布、图标、密码可见性切换和背景图规范。
## Impact
- 影响 `workspace/agent-admin/web` 登录页组件、登录页相关测试和 OpenSpec `admin-login` 能力。
- 影响工作区级前端组件规范文档。
- 不改变本地账号密码校验、登录态持久化、路由守卫、退出登录确认或后端接口边界。
## MODIFIED Requirements
### Requirement: 登录页展示
岗位 Agent 管理后台 SHALL 在用户访问受保护管理页面前提供符合工作区统一登录页规范的 `岗位Agent管理后台` 登录页。
#### Scenario: 打开登录页
- **WHEN** 未登录用户打开登录路由
- **THEN** 登录页展示产品名称 `岗位Agent管理后台`
- **AND** 产品名称使用深色、加粗的大标题样式
- **AND** 登录页在产品名称下方展示系统描述,描述使用浅色、正常字号文本
- **AND** 登录页展示账号输入框、密码输入框和登录控件
- **AND** 登录页不显示账号、密码字段标签
- **AND** 账号输入框 placeholder 为 `请输入账号`
- **AND** 密码输入框 placeholder 为 `请输入密码`
- **AND** 账号输入框左侧展示用户图标
- **AND** 密码输入框左侧展示锁图标
- **AND** 密码输入框右侧展示眼睛图标,用于切换密码可见性
- **AND** 登录页展示背景图片,图片等比例居中显示,背景底色与图片同色系
- **AND** 登录页背景底色由业务页面传入共享登录组件,不在共享登录组件中写死
- **AND** 登录区域最低高度为 `350px`
- **AND** 登录区域在背景上水平和垂直居中
- **AND** 登录页结构通过 `@gl/business-components` 的登录业务组件复用
## 1. 规范沉淀
- [x] 1.1 在工作区组件规范中补充统一登录页规范。
## 2. 登录页实现
- [x] 2.1 将当前登录页表单控件改为直接使用 TDesign 基础组件和 TDesign 图标。
- [x] 2.2 调整登录页标题、描述、无可见字段标签的 placeholder 输入框、账号/密码图标和密码可见性切换。
- [x] 2.3 添加背景图片、同色系底色、登录区域最低高度和水平垂直居中布局。
- [x] 2.4 新增 `@gl/business-components` 登录页业务组件,并将背景色改为业务页面参数。
- [x] 2.5 将 `agent-admin/web` 登录页改为消费 `@gl/business-components` 登录页业务组件。
## 3. 验证
- [x] 3.1 补充或更新登录页测试,覆盖统一展示规则和密码可见性切换。
- [x] 3.2 运行 OpenSpec strict 校验、相关测试、类型检查和构建。
- [x] 3.3 用户本次明确无需浏览器确认,未执行浏览器验证。
- [x] 3.4 补充共享登录组件测试,覆盖背景色参数传入。
## Context
`agent-admin/web` 的基础 UI 迁移方向已经明确:优先使用 `tdesign-react`。当前官网岗位 Tab 编辑页的“岗位说明”仍直接渲染原生 `<textarea>`,组件库 Demo 页的多行输入示例也仍通过 `packages/ui/Textarea` 展示旧实现。用户已确认本次不要修改 `packages/ui/Textarea`,因此本 change 只做页面级替换。
## Goals / Non-Goals
**Goals:**
- 在官网岗位 Tab 编辑页中用 TDesign `Textarea` 替换原生 `<textarea>`。
- 在组件库 Demo 页中用 TDesign `Textarea` 替换多行输入示例。
- 保留岗位说明字段的现有表单状态、placeholder、行数、最大长度、字数展示和校验逻辑。
- 明确不触碰 `packages/ui/Textarea`。
**Non-Goals:**
- 不迁移 `packages/ui/Textarea` 或其他基础组件。
- 不重新设计输入框、表单、搜索区或编辑页布局。
- 不引入新的业务字段或接口契约。
- 不为 `Textarea` 设计一套独立于 TDesign 的新样式体系。
## Decisions
1. `OfficialSiteJobTabEditorPage.tsx` 和 `ComponentsDemoPage.tsx` 直接引入 `tdesign-react` 的 `Textarea`。这是用户确认的页面级替换范围,不改变共享组件。
2. 岗位说明字段继续由现有 `FormItem` 承载标签、必填和错误文案。Demo 页继续保留原有基础交互分组位置。TDesign `Textarea` 只替换输入控件本身。
3. 使用 TDesign `Textarea` 的 `onChange(value)` 更新 `form.sub_title`,避免继续依赖 DOM event 读取。
4. 最大长度使用 TDesign 的 `maxlength`,字数展示使用 `count`,行数通过 `rows` 透传。
5. 不调整表单状态、保存、取消和校验逻辑。
## Risks / Trade-offs
- TDesign DOM 结构与原生 `<textarea>` 不一致,测试需要避免断言内部 class 或结构。
- 字数展示交由 TDesign 渲染,视觉细节可能与旧实现略有差异。
- 页面直接导入 TDesign 会形成页面级依赖;这是用户本次明确选择的较小改动路径。
## Why
`agent-admin/web` 已接入 `tdesign-react`。当前官网岗位 Tab 编辑页和组件库 Demo 页仍存在页面级多行输入示例未直接使用 TDesign Textarea,导致展示入口没有完全对齐 TDesign 基础组件使用方向。根据用户最新确认,本次不修改 `packages/ui/Textarea`,只替换页面内这些多行输入使用点。
## What Changes
- 将官网岗位 Tab 编辑页中的原生 `<textarea>` 替换为 `tdesign-react` 的 `Textarea`。
- 将组件库 Demo 页中的多行输入示例改为直接使用 `tdesign-react` 的 `Textarea`。
- 保留当前岗位说明字段的值、placeholder、行数、最大长度、字数展示、变更回调和校验逻辑。
- 补充或调整页面测试,验证岗位说明字段和 Demo 多行输入示例使用 TDesign Textarea 后仍可展示/编辑。
## Non-Goals
- 不迁移 `packages/ui/Textarea`、`Input`、`Button`、`FormItem`、`Table` 等其他组件。
- 不把其他无关业务页面改为直接导入 `tdesign-react`。
- 不重构官网岗位 Tab 编辑页的业务逻辑、字段校验或保存流程。
- 不新增超出 TDesign 原生能力的额外包装 API。
## Capabilities
### Modified Capabilities
- `ui-component-library`:消除官网岗位 Tab 编辑页和组件库 Demo 页中的页面级非 TDesign 多行输入使用点。
## Impact
- 影响 `workspace/agent-admin/web/src/routes/official-site-job-tabs/OfficialSiteJobTabEditorPage.tsx` 中的岗位说明字段。
- 影响 `workspace/agent-admin/web/src/routes/components/ComponentsDemoPage.tsx` 中的多行输入示例。
- 影响官网岗位 Tab 编辑页和组件库 Demo 页相关测试。
- 不影响 `workspace/agent-admin/web/packages/ui/src/components/Textarea.tsx`。
## ADDED Requirements
### Requirement: 页面级多行输入组件
官网岗位 Tab 编辑页和组件库 Demo 页 SHALL 使用 TDesign 多行输入组件承载页面级多行输入,不再直接渲染或展示非 TDesign Textarea。
#### Scenario: Official site job tab editor uses TDesign Textarea
- **WHEN** a user opens the official site job tab editor
- **THEN** the job description field SHALL render with `tdesign-react` Textarea behavior and styling
- **AND** the page SHALL NOT render a raw native `<textarea>` for that field
#### Scenario: Components demo uses TDesign Textarea
- **WHEN** a user opens the component demo page
- **THEN** the remark textarea example SHALL render with `tdesign-react` Textarea behavior and styling
- **AND** the demo SHALL NOT use `packages/ui/Textarea` for that example
#### Scenario: Job description editing remains available
- **WHEN** a user edits the job description field
- **THEN** the page SHALL update `sub_title` with the next string value
- **AND** saving SHALL continue to submit the edited value
#### Scenario: Job description count display remains available
- **WHEN** the job description field has a maximum length
- **THEN** the field SHALL show a current length and maximum length indicator
## 1. OpenSpec 对齐
- [x] 1.1 创建 `proposal.md`,明确页面级 Textarea 替换范围与非目标
- [x] 1.2 创建 `design.md`,明确不修改 `packages/ui/Textarea`
- [x] 1.3 创建 `ui-component-library` spec delta,覆盖页面原生 textarea 替换
- [x] 1.4 根据用户确认将范围收窄为“只改页面,不动 `packages/ui/Textarea`”
- [x] 1.5 根据用户追加确认将组件库 Demo 页纳入页面级替换范围
## 2. TDD 与实现
- [x] 2.1 更新官网岗位 Tab 编辑页测试,覆盖岗位说明字段使用 TDesign Textarea 后仍可输入
- [x] 2.2 将官网岗位 Tab 编辑页的原生 `<textarea>` 替换为 `tdesign-react` `Textarea`
- [x] 2.3 确认 `packages/ui/src/components/Textarea.tsx` 未修改
- [x] 2.4 更新组件库 Demo 页测试,覆盖多行输入示例使用 TDesign Textarea
- [x] 2.5 将组件库 Demo 页多行输入示例替换为 `tdesign-react` `Textarea`
## 3. 验证
- [x] 3.1 运行官网岗位 Tab 编辑页相关测试
- [x] 3.2 运行类型检查
- [x] 3.3 运行构建验证
- [x] 3.4 浏览器验证官网岗位 Tab 编辑页的岗位说明字段可输入且布局正常
- [x] 3.5 运行组件库 Demo 页相关测试
- [x] 3.6 浏览器验证组件库 Demo 页多行输入示例可输入且布局正常
## Context
`agent-admin` 已经把列表表格统一到 `BusinessTable`,把列表搜索统一到 `SearchFilter`。表单部分仍分散在页面和弹窗里,由页面手写 `FormItem + Input/Select/Textarea/Switch/Upload`、本地校验、错误提示、字段联动和只读展示。现有表单既有简单新增编辑页,也有官网配置弹窗中的上传场景,还有管家 Agent 等只读展示场景。
本 change 只做全局业务表单组件能力,不直接迁移现有业务页面。组件必须遵循后台页面的信息密度和公司 Web 桌面端设计规范,并以 `tdesign-react` 为唯一前台控件来源;如需兼容旧写法,只能收敛到共享适配层,不能继续保留页面级原生实现路径。
## Goals / Non-Goals
**Goals:**
- 在 `@gl/business-components` 中新增配置驱动 `BusinessForm`。
- 用统一协议覆盖 `input`、`numberInput`、`select`、`switch`、`textarea`、`upload`、`displayText` 和 `custom`。
- 统一 label、必填标记、错误提示、helpText、字段间距和基础输入控件宽度。
- 支持受控值、字段级变更联动、动态显示、动态禁用、动态只读和导出的校验工具。
- 让上传字段只处理选择文件、前置校验、上传中状态、预览、移除、失败提示和结果回填,不耦合具体业务接口。
- 上传能力在 UI 上拆成媒体上传和普通文件上传两条路径,二者都基于 TDesign `Upload`;媒体上传统一覆盖图片、GIF 和视频,走缩略图、图片卡片或媒体预览,普通文件上传走文件流或附件卡片。
- 通过 `custom` 字段保留实际业务开发中的扩展空间。
- 对所有内置字段优先使用 TDesign 已有属性和 API,避免在页面层保留原生控件兼容写法。
**Non-Goals:**
- 不接管页面保存按钮、提交接口、路由跳转、弹窗开关、埋点或全局消息提示。
- 不绑定固定上传 API、固定 `FormData`、固定 `usage_type` 或固定文件返回结构。
- 第一版不支持远程下拉搜索、异步联动请求、数组字段、嵌套对象字段、富文本、日期、多文件上传和复杂步骤表单。
- 不替代 `SearchFilter`。
- 不强制一次性迁移现有编辑页和官网复杂配置页。
## Decisions
### 配置驱动组件,而不是只封装单个控件
采用 `fields + values + onChange` 的受控配置协议。页面描述字段,`BusinessForm` 负责统一渲染、布局、错误提示、动态状态和基础校验。
备选方案是只导出业务版 `Input`、`Select`、`Textarea`、`Upload` 等基础控件。该方案灵活但无法减少页面重复的字段协议、校验、动态显示和上传提示逻辑,因此不采用。
### 表单不绑定具体接口
`BusinessForm` 不接管保存流程。上传字段通过配置项传入 `upload(file, values)`,组件只在文件大小和类型校验通过后调用该函数,并把返回 URL 或结构化文件值写回当前字段。上传字段默认最多上传 1 个文件;需要多张图片、GIF 或视频时,字段配置通过 `maxCount` 设置最大数量,并可通过 `multiple` 控制是否允许一次选择多个文件。单文件时字段值保持原有 URL 或结构化文件值;多文件时字段值使用数组,数组项为 URL 或结构化文件值,删除时只移除对应项。
媒体上传和普通文件上传都使用 TDesign `Upload`,但渲染契约分开:媒体态统一承载图片、GIF 和视频,使用图片卡片、缩略图或媒体预览表达;文件态使用文件流或附件表达,避免再回到原生 `input type="file"` + 自绘预览的混合实现。
媒体上传已有值时采用 TDesign 图片卡片形态:卡片内展示图片、GIF 首帧或视频封面/首帧,上传后预览卡片与无值占位卡片统一固定为 `110px × 110px`;文件名按当前实现展示在卡片下方并保持单行省略,不再额外扩大文件名区域。多文件值按数组顺序展示多个媒体卡片,达到 `maxCount` 后不再展示新增入口。hover 或聚焦时出现接近 TDesign 图片上传卡片的半透明操作蒙层,但遮罩颜色需要比默认深色蒙层更浅,避免过度压暗素材;蒙层中提供预览和删除两个操作,操作之间保留竖向分隔线。预览行为优先复用 TDesign `Upload` 的 `onPreview` 事件能力,组件只在图片、GIF、视频共用媒体值结构上做必要适配,不额外维护一套独立预览交互。无值时展示同样 `110px × 110px` 的虚线卡片入口,卡片内部显示加号和字段配置的 `placeholder`,默认文案为 `点击上传`;卡片下方的能力说明由字段配置 `helperText` 动态传入,不在组件内写死图片、视频、GIF、比例或大小限制文案。删除已有媒体后如果仍有剩余文件则保留剩余卡片,如果已清空则恢复空态入口。视频文件仍归入媒体上传,不拆成单独组件。
备选方案是让组件内置上传 API、`FormData` 和 `usage_type`。该方案会把组件绑死到具体业务场景,和用户确认的“不绑定具体接口”冲突,因此不采用。
### 字段级 onChange 只做同步局部 patch
字段变更时,组件先得到当前字段的新值,再调用字段级 `onChange(nextValue, context)`。如果返回 `Partial<BusinessFormValues>`,组件按 `{ ...values, [field.key]: nextValue, ...patch }` 合并后通过表单级 `onChange` 抛出。
备选方案是支持字段级异步请求和复杂远程联动。第一版容易扩大行为边界,也会把加载、取消、错误处理带入组件,因此不采用;复杂联动保留在页面层或 `custom` 字段。
### 动态 visible/disabled/readonly 基于当前 values 计算
字段的 `visible`、`disabled`、`readonly` 支持布尔值或函数。隐藏字段不渲染、不校验、不展示错误,但组件默认保留其值,由页面决定保存时是否提交。
这样可以覆盖“选择 A 后 B 才可选择”以及“选择 A 后显示部分 text 项”的需求,同时避免组件擅自清空业务值造成数据丢失。
`input`、`numberInput`、`select` 和 `textarea` 的禁用态与只读态优先下发给 `tdesign-react` 已有属性或等价 API,不在页面层保留原生控件写法;如某个控件缺少对应能力,只能在共享包内部做最小适配。对于 `select`,共享层只能做语义和无障碍补充,不能再用“按钮伪装选择框 + 隐藏真实控件”的方式替代 TDesign 原生视觉。
### 统一基础控件宽度
`BusinessForm` 提供 `fieldWidth`,默认建议 `360px`,最大不超过 `450px`。`input`、`numberInput`、`select` 和 `textarea` 默认使用同一个宽度,并保持 label 后控件起点一致;`textarea` 只允许高度变化。
`switch`、`upload`、`displayText` 和 `custom` 复用同一表单项外层布局。`custom` 可自行决定内部宽度,但建议遵守 `fieldWidth`。
`input` 和 `textarea` 的长度展示直接交给 `tdesign-react` 的 `showLimitNumber` / `count`,不再由 `BusinessForm` 额外渲染字数统计。
### 校验以导出工具函数为主
导出 `validateBusinessForm(fields, values)`,页面保存前可调用并把错误传回 `BusinessForm` 展示。校验过滤不可见字段,跳过 `displayText` 和只读字段,按 required、长度、数值范围、上传前置限制和自定义 validator 的顺序生成错误。
组件内部可在字段变更时清理当前字段错误,但不自动提交页面保存。
## Risks / Trade-offs
- [Risk] 第一版字段类型有限,无法覆盖复杂业务表单 → 通过 `custom` 字段复用外层布局和状态,并把复杂业务逻辑留在页面层。
- [Risk] 上传文件类型判断可能受浏览器 MIME 不完整影响 → 同时支持 `accept` 中的 MIME 和扩展名校验,并允许业务侧配置 `kinds`。
- [Risk] 隐藏字段保留值可能导致页面提交额外数据 → 在规格中明确组件不清空隐藏值,页面保存前自行决定提交 payload。
- [Risk] 统一宽度可能不适合少数自定义控件 → 基础输入控件强一致,`custom` 内部保留业务自定义空间。
## Migration Plan
1. 先完成 `BusinessForm` 组件、校验工具、类型导出和 Demo。
2. 在组件 Demo 中同步展示七类内置字段、`custom`、字段级 `onChange`、动态显示、动态禁用、动态只读、媒体上传卡片态、普通文件上传信息态、上传校验和统一宽度。
3. 运行相关测试、类型检查、构建和 OpenSpec 严格校验。
4. 开发侧完成自动化验证后,由业务验收者在浏览器中最终验收 `/components` 的 `BusinessForm` 布局、上传形态和关键交互。
5. 用户确认组件表现后,再选择低复杂度页面或弹窗逐步迁移,例如 `AgentTagEditorPage`、`ChannelCodeEditorPage`、`AgentDisplayConfigEditModal`。
## Open Questions
- 第一版上传按当前确认采用单文件上传,且媒体上传与普通文件上传分别使用独立的 TDesign 展现路径;如果后续需要多文件上传,应作为后续 change 扩展。
- Demo 建议同时覆盖上传返回字符串 URL 和结构化文件值两种情况;实施时可根据现有 Demo 复杂度决定是否拆成两个示例。
## Why
`agent-admin` 的表格和搜索区已经通过全局业务组件统一,但编辑页和弹窗表单仍由页面直接组合 TDesign 控件、字段布局、校验和联动逻辑。需要在 `@gl/business-components` 中新增配置驱动的 `BusinessForm`,统一常见后台表单能力,并为后续逐步迁移现有表单提供稳定契约。
当前实现里仍残留部分原生写法和旧兼容路径,导致表单行为、属性映射和视觉效果没有完全对齐 TDesign 体系,需要在不推倒业务协议的前提下做一次 TDesign-first 收敛。
## What Changes
- 新增 `BusinessForm` 全局业务组件,通过字段配置渲染后台表单。
- 第一版内置 `input`、`numberInput`、`select`、`switch`、`textarea`、`upload`、`displayText` 字段,并直接使用 `tdesign-react` 基础控件实现可编辑态。
- 提供 `custom` 字段扩展口,用于内置字段无法覆盖的业务控件。
- 支持受控值、表单级 `onChange`、字段级 `onChange`、字段动态显示、动态禁用、动态只读和基础校验。
- `input`、`numberInput`、`select`、`textarea` 默认使用一致控件宽度,并支持通过 `fieldWidth` 统一控制。
- `input` 和 `textarea` 支持 `allowInputOverMax`,并直接复用 `tdesign-react` 的 `showLimitNumber` 长度展示能力。
- `select`、`input`、`numberInput` 和 `textarea` 优先使用 `tdesign-react` 已有的 `disabled` / `readOnly` / 等价能力来表达字段级状态,不再保留页面侧原生控件写法。
- `upload` 在第一版中分为媒体上传与普通文件上传两种展示路径,媒体上传统一支持图片、GIF 和视频,二者均使用 `tdesign-react` `Upload` 完成选择、预览和状态展示,并通过业务侧传入的 `upload(file, values)` 完成真实上传。
- 导出 `validateBusinessForm` 工具函数和必要类型。
- 在组件 Demo 中展示内置字段、动态联动、上传校验和自定义字段。
- 对已有实现中的兼容/适配路径做收敛,确保公开 API 以 TDesign 组件契约为准。
- 不绑定保存接口、上传 API、`usage_type`、路由、弹窗开关、全局消息或页面提交流程。
- 不在第一版支持远程下拉搜索、数组字段、嵌套对象字段、富文本、日期、多文件上传或复杂异步联动。
## Capabilities
### New Capabilities
- `business-form`: 约束全局业务表单组件的字段协议、渲染行为、校验规则、动态联动、上传能力、自定义扩展和导出入口。
### Modified Capabilities
- 无。
## Impact
- 全局组件包:`packages/business-components` 新增 `BusinessForm`、`validateBusinessForm`、样式和类型导出。
- 组件 Demo:`workspace/agent-admin/web/src` 的 `/components` 增加业务表单示例。
- 测试:新增业务组件单元测试与 Demo 回归测试。
- 现有页面:本 change 不要求一次性迁移现有编辑页;后续页面迁移需要单独确认或纳入后续任务。
- 后端与接口:不影响后端 API、上传接口契约、保存接口和数据结构。
## ADDED Requirements
### Requirement: BusinessForm provides a controlled configuration-driven form
系统 MUST 从 `@gl/business-components` 导出 `BusinessForm`,并通过 `fields`、`values` 和 `onChange` 渲染受控业务表单。
#### Scenario: Render configured fields
- **WHEN** 页面传入字段配置和当前表单值
- **THEN** `BusinessForm` 按字段顺序渲染表单项
- **AND** 字段变更后通过表单级 `onChange(nextValues, changedKey)` 抛出更新后的整表单值
#### Scenario: Export public types
- **WHEN** 业务页面从 `@gl/business-components` 引入业务表单能力
- **THEN** 包导出 `BusinessForm`、字段类型、值类型、错误类型和校验工具类型
### Requirement: BusinessForm supports first-version built-in field types
系统 MUST 支持 `input`、`numberInput`、`select`、`switch`、`textarea`、`upload` 和 `displayText` 七类第一版内置字段。
#### Scenario: Render built-in editable fields
- **WHEN** 字段配置包含 `input`、`numberInput`、`select`、`switch`、`textarea` 或 `upload`
- **THEN** `BusinessForm` 使用对应 `tdesign-react` 基础控件渲染可编辑表单项
#### Scenario: Render display text field
- **WHEN** 字段配置包含 `displayText`
- **THEN** `BusinessForm` 渲染只读展示内容
- **AND** 空值默认展示 `-`
### Requirement: BusinessForm supports custom fields
系统 MUST 支持 `custom` 字段,并把当前值、整表单值、错误、禁用、只读和更新函数传给自定义渲染函数。
#### Scenario: Render custom field
- **WHEN** 字段配置包含 `custom.render`
- **THEN** `BusinessForm` 复用表单项外层布局、label、必填标记、helpText 和错误提示
- **AND** 自定义渲染函数接收到 `value`、`values`、`error`、`disabled`、`readonly`、`setValue` 和 `setValues`
#### Scenario: Custom field updates value
- **WHEN** 自定义字段调用 `setValue` 或 `setValues`
- **THEN** `BusinessForm` 通过表单级 `onChange` 抛出更新后的整表单值
### Requirement: BusinessForm applies consistent field layout and widths
系统 MUST 统一基础输入控件的表单布局和宽度。
#### Scenario: Default control width is consistent
- **WHEN** 同一表单渲染 `input`、`numberInput`、`select` 和 `textarea`
- **THEN** 这些控件使用一致的默认宽度
- **AND** 这些控件在 label 后的起点保持一致
#### Scenario: fieldWidth applies to basic input controls
- **WHEN** 页面传入 `fieldWidth`
- **THEN** `input`、`numberInput`、`select` 和 `textarea` 同步应用该宽度
#### Scenario: Textarea width remains consistent
- **WHEN** `textarea` 因 `rows` 或内容交互改变高度
- **THEN** `textarea` 宽度仍与同表单内 `input`、`numberInput` 和 `select` 保持一致
### Requirement: BusinessForm supports text input limits and TDesign counts
系统 MUST 让 `input` 和 `textarea` 支持 `maxLength`、`allowInputOverMax`,并优先复用 `tdesign-react` 已有的长度展示能力和对应 API,而不是页面侧自绘计数逻辑。
#### Scenario: Input count and over max behavior
- **WHEN** `input` 字段配置 `maxLength` 且需要展示长度
- **THEN** 输入框展示 TDesign 提供的字数统计能力
- **AND** 当 `allowInputOverMax` 为真时允许继续输入超过最大长度
- **AND** 校验仍按 `maxLength` 生成错误
#### Scenario: Textarea count and over max behavior
- **WHEN** `textarea` 字段配置 `maxLength` 且需要展示长度
- **THEN** 文本域展示 TDesign 提供的字数统计能力
- **AND** 当 `allowInputOverMax` 为真时允许继续输入超过最大长度
- **AND** 校验仍按 `maxLength` 生成错误
### Requirement: BusinessForm supports number input validation
系统 MUST 让 `numberInput` 支持数值输入和 `min`、`max`、`precision` 校验。
#### Scenario: Validate number range
- **WHEN** `numberInput` 字段配置 `min` 或 `max`
- **THEN** 低于最小值或高于最大值的值会产生字段错误
#### Scenario: Validate number precision
- **WHEN** `numberInput` 字段配置 `precision`
- **THEN** 超出允许小数位数的值会产生字段错误
### Requirement: BusinessForm uses TDesign-first disabled and readonly mapping for editable controls
系统 MUST 让 `input`、`numberInput`、`select` 和 `textarea` 优先使用 `tdesign-react` 已有的 `disabled` / `readOnly` 或等价 API 表达字段级禁用和只读,不再保留页面级原生控件兼容写法。
#### Scenario: Disabled select option cannot be selected
- **WHEN** `select.options` 中某个选项配置 `disabled: true`
- **THEN** 用户不能选择该选项
#### Scenario: Disabled editable field cannot be operated
- **WHEN** `input`、`numberInput`、`select` 或 `textarea` 字段的 `disabled` 计算结果为真
- **THEN** 下拉控件不可操作并呈现禁用状态
#### Scenario: Readonly editable field stays in TDesign render path
- **WHEN** `input`、`numberInput`、`select` 或 `textarea` 字段的 `readOnly` 计算结果为真
- **THEN** `BusinessForm` 直接使用 TDesign 对应属性或等价能力
- **AND** 不再切换为页面级原生控件或自绘兼容分支
### Requirement: BusinessForm supports switch value mapping
系统 MUST 让 `switch` 默认使用布尔值,并支持通过 `checkedValue` 和 `uncheckedValue` 映射业务值。
#### Scenario: Toggle boolean switch
- **WHEN** `switch` 字段未配置业务值映射
- **THEN** 开关切换产生 `true` 或 `false`
#### Scenario: Toggle mapped switch
- **WHEN** `switch` 字段配置 `checkedValue` 和 `uncheckedValue`
- **THEN** 开关切换产生对应业务值
#### Scenario: Readonly switch displays state
- **WHEN** `switch` 字段的 `readonly` 计算结果为真
- **THEN** 表单项展示当前状态文案
- **AND** 不展示可切换开关
### Requirement: BusinessForm supports dynamic field states
系统 MUST 让字段的 `visible`、`disabled` 和 `readonly` 支持布尔值或基于当前 `values` 的函数。
#### Scenario: Hide dynamic field
- **WHEN** 字段 `visible` 为 false 或函数返回 false
- **THEN** `BusinessForm` 不渲染该字段
- **AND** 该字段不参与校验
- **AND** 该字段错误不展示
#### Scenario: Enable field based on another field
- **WHEN** 字段 B 的 `disabled(values)` 依赖字段 A 的当前值
- **THEN** 字段 A 变更后字段 B 的禁用状态按最新 `values` 重新计算
#### Scenario: Show display text based on another field
- **WHEN** `displayText` 字段的 `visible(values)` 依赖字段 A 的当前值
- **THEN** 字段 A 变更后该展示字段按最新 `values` 显示或隐藏
### Requirement: BusinessForm supports field-level onChange patching
系统 MUST 支持字段级 `onChange(nextValue, context)`,用于同步联动更新其他字段。
#### Scenario: Field onChange patches related values
- **WHEN** 字段级 `onChange` 返回 `Partial<BusinessFormValues>`
- **THEN** `BusinessForm` 按 `{ ...values, [field.key]: nextValue, ...patch }` 合并整表单值
- **AND** 通过表单级 `onChange` 抛出合并后的值
#### Scenario: Field onChange only updates current field
- **WHEN** 字段级 `onChange` 不返回 patch
- **THEN** `BusinessForm` 只更新当前字段值
### Requirement: BusinessForm validates configured fields
系统 MUST 提供 `validateBusinessForm(fields, values)`,并按可见性、只读状态和字段规则生成校验结果。
#### Scenario: Validate required field
- **WHEN** 可编辑且可见字段配置 `required: true` 且值为空
- **THEN** `validateBusinessForm` 返回该字段错误
#### Scenario: Skip invisible and readonly fields
- **WHEN** 字段不可见或只读
- **THEN** `validateBusinessForm` 不校验该字段
#### Scenario: Skip display text field
- **WHEN** 字段类型为 `displayText`
- **THEN** `validateBusinessForm` 不对该字段执行必填或自定义校验
#### Scenario: Run custom validator
- **WHEN** 可编辑且可见字段配置 `validator`
- **THEN** `validateBusinessForm` 执行该 validator
- **AND** 使用 validator 返回的错误文案作为字段错误
### Requirement: BusinessForm supports media and regular file upload
系统 MUST 让 `upload` 字段在媒体上传和普通文件上传场景下使用不同展示路径,并且两条路径都基于 `tdesign-react` `Upload` 实现上传,不再使用页面级原生文件输入控件。媒体上传 MUST 统一支持图片、GIF 和视频。上传字段默认最多上传 1 个文件,并 MUST 支持通过字段配置调整最大数量和是否允许多选。
#### Scenario: Reject invalid media upload type
- **WHEN** 媒体上传场景下用户选择的图片、GIF 或视频不满足 `kinds` 或 `accept`
- **THEN** `BusinessForm` 展示类型错误
- **AND** 不调用业务传入的 `upload(file, values)`
#### Scenario: Reject invalid regular file upload type
- **WHEN** 普通文件上传场景下用户选择的文件不满足 `kinds` 或 `accept`
- **THEN** `BusinessForm` 展示类型错误
- **AND** 不调用业务传入的 `upload(file, values)`
#### Scenario: Reject oversized upload
- **WHEN** 用户选择的文件大小超过 `maxSize`
- **THEN** `BusinessForm` 展示大小错误
- **AND** 不调用业务传入的 `upload(file, values)`
#### Scenario: Upload valid media file
- **WHEN** 媒体上传场景下用户选择的图片、GIF 或视频满足 `kinds`、`accept` 和 `maxSize`
- **THEN** `BusinessForm` 调用业务传入的 `upload(file, values)`
- **AND** 上传成功后把 URL 或结构化文件值写入当前字段
#### Scenario: Upload multiple valid media files
- **WHEN** 媒体上传字段配置 `maxCount` 大于 `1` 或配置 `multiple: true`
- **AND** 用户选择的多个图片、GIF 或视频均满足 `kinds`、`accept` 和 `maxSize`
- **THEN** `BusinessForm` 按文件分别调用业务传入的 `upload(file, values)`
- **AND** 上传成功后把多个 URL 或结构化文件值以数组形式写入当前字段
- **AND** 当已上传数量达到 `maxCount` 时,TDesign `Upload` 不再继续展示新增入口或继续接收超过上限的文件
#### Scenario: Upload valid regular file
- **WHEN** 普通文件上传场景下用户选择的文件满足 `kinds`、`accept` 和 `maxSize`
- **THEN** `BusinessForm` 调用业务传入的 `upload(file, values)`
- **AND** 上传成功后把 URL 或结构化文件值写入当前字段
#### Scenario: Display uploaded media preview
- **WHEN** 媒体上传字段已有图片、GIF 或视频值
- **THEN** `BusinessForm` 使用媒体类 TDesign 图片卡片态展示缩略图、GIF 首帧或视频封面/首帧
- **AND** 已有值预览卡片尺寸固定为 `110px × 110px`
- **AND** 如果当前字段值为数组,则按数组顺序展示多个媒体卡片
- **AND** hover 或聚焦卡片时展示接近 TDesign 图片上传卡片的半透明操作蒙层,但蒙层颜色比默认深色遮罩更浅
- **AND** 蒙层中提供预览和删除操作
- **AND** 预览与删除操作之间展示竖向分隔线
- **AND** 预览操作优先复用 TDesign `Upload` 的 `onPreview` 能力,不在组件内重复实现独立预览入口
- **AND** 文件名按当前实现展示在卡片下方,并保持单行省略,不允许换行撑高布局
#### Scenario: Display media upload placeholder and helper text
- **WHEN** 媒体上传字段没有当前值
- **THEN** `BusinessForm` 展示 `110px × 110px` 的固定尺寸虚线卡片上传入口
- **AND** 卡片内部展示加号和字段配置 `placeholder`,未配置时默认展示 `点击上传`
- **AND** 如果字段配置 `helperText`,则在上传卡片下方展示该说明文案
#### Scenario: Restore media upload placeholder after deletion
- **WHEN** 用户删除媒体上传字段的已有图片、GIF 或视频
- **THEN** `BusinessForm` 从当前字段值中移除对应文件
- **AND** 当删除后字段值为空时,上传区域恢复到无值时的卡片占位态
- **AND** 当删除后字段值未空且未达到 `maxCount` 时,上传区域继续展示剩余卡片并允许继续新增
- **AND** 上传卡片下方继续展示字段配置传入的 `helperText`
#### Scenario: Display uploaded regular file preview
- **WHEN** 普通文件上传字段已有普通文件值
- **THEN** `BusinessForm` 使用文件类 TDesign 上传态展示文件信息
#### Scenario: Upload failure preserves previous value
- **WHEN** 业务传入的 `upload(file, values)` 失败
- **THEN** `BusinessForm` 展示上传失败错误
- **AND** 不改写当前字段已有值
### Requirement: BusinessForm demo covers first-version capabilities
系统 MUST 在组件 Demo 中展示 `BusinessForm` 第一版核心能力。
#### Scenario: Open components demo
- **WHEN** 用户访问 `/components`
- **THEN** 页面展示 `BusinessForm` 示例
- **AND** 示例覆盖内置字段、自定义字段、字段级联动、动态显示、动态禁用、动态只读、单选选择器、多选选择器、媒体上传、普通文件上传、上传校验和仅展示文字
#### Scenario: Demo reflects upload display paths
- **WHEN** 用户访问 `/components` 中的 `BusinessForm` 示例
- **THEN** 示例中的媒体上传字段展示图片、GIF 和视频共用的卡片式上传入口与已有值预览态
- **AND** 示例中的普通文件上传字段展示文件类上传入口与已有值信息态
- **AND** 示例不得继续展示基于页面级原生文件输入控件的旧上传交互
## 1. 基线与结构
- [x] 1.1 确认 `packages/business-components` 当前导出结构、测试框架和样式组织方式
- [x] 1.2 建立 `BusinessForm` 组件、类型、校验工具和样式文件的目录结构
- [x] 1.3 确认组件 Demo 中新增业务表单示例的入口位置
## 2. 测试优先
- [x] 2.1 先为 `BusinessForm` 渲染 `input`、`numberInput`、`select`、`switch`、`textarea`、`upload`、`displayText`、`custom` 编写失败测试
- [x] 2.2 先为受控值更新、表单级 `onChange` 和字段级 `onChange` patch 编写失败测试
- [x] 2.3 先为 `visible`、`disabled`、`readonly` 动态计算编写失败测试
- [x] 2.4 先为 `validateBusinessForm` 的 required、maxLength、数值范围、precision、readonly、不可见字段、自定义 validator 编写失败测试
- [x] 2.5 先为 `input`、`textarea` 的 `allowInputOverMax` 和 TDesign 原生长度展示编写失败测试
- [x] 2.6 先为 `input`、`numberInput`、`select`、`textarea` 默认同宽和 `fieldWidth` 同步应用编写失败测试
- [x] 2.7 先为 `select` 选项级禁用、字段禁用和只读展示编写失败测试
- [x] 2.8 先为 `switch` 默认布尔值、业务值映射和只读展示编写失败测试
- [x] 2.9 先为 `upload` 的 `kinds`、`accept`、`maxSize`、上传成功、上传失败、媒体上传、普通文件上传、图片/GIF/视频/普通文件展示编写失败测试
- [x] 2.10 先为 `custom` 字段上下文、`setValue`、`setValues`、校验和动态状态编写失败测试
## 3. 组件实现
- [x] 3.1 实现 `BusinessForm` 受控渲染、表单项布局、label、必填标记、helpText 和错误提示
- [x] 3.2 实现 `input`、`numberInput`、`select`、`switch`、`textarea`、`displayText` 字段渲染
- [x] 3.3 实现 `custom` 字段上下文和更新函数
- [x] 3.4 实现字段级 `onChange` patch 合并规则
- [x] 3.5 实现 `visible`、`disabled`、`readonly` 动态状态计算,并将 `input`、`numberInput`、`select`、`textarea` 的禁用/只读直接下发给 TDesign 原生属性
- [x] 3.6 实现 `fieldWidth` 和基础输入控件同宽样式
- [x] 3.7 将内置字段的可编辑态、只读态和上传触发控件统一迁移为 `tdesign-react` 组件,编辑态字段直接使用 `disabled` / `readOnly` 原生属性
## 4. 校验与上传
- [x] 4.1 实现 `validateBusinessForm(fields, values)` 工具函数
- [x] 4.2 实现 required、maxLength、number min/max/precision 和自定义 validator 校验
- [x] 4.3 实现 `upload` 字段文件选择、类型校验、大小校验、上传中状态、错误提示、移除和结果回填
- [x] 4.4 将媒体上传和普通文件上传拆分为两条基于 TDesign `Upload` 的展示分支,分别覆盖图片/GIF/视频卡片预览和文件类信息展示
- [x] 4.5 确认上传逻辑不构造固定 `FormData`、不写入固定 `usage_type`、不调用固定 API
## 5. 导出与 Demo
- [x] 5.1 从 `packages/business-components/src/index.ts` 导出 `BusinessForm`、`validateBusinessForm` 和相关类型
- [x] 5.2 在 `/components` Demo 中新增 `BusinessForm` 示例
- [x] 5.3 Demo 覆盖内置字段、自定义字段、字段级 `onChange`、动态显示、动态禁用、动态只读、上传校验和仅展示文字
## 6. 验证与收尾
- [x] 6.1 运行 `BusinessForm` 相关测试
- [x] 6.2 运行组件 Demo 相关测试
- [x] 6.3 运行 `npm run typecheck`
- [x] 6.4 运行 `npm run build`
- [x] 6.5 运行 `openspec validate "business-form-component" --strict`
- [ ] 6.6 由用户在浏览器中验收 `/components` 的 `BusinessForm` 布局、统一宽度、动态联动、上传形态和关键交互
## 7. TDesign 迁移收敛
- [ ] 7.1 盘点 `BusinessForm` 和共享适配层中仍保留的原生写法、legacy props 和等价 TDesign API 缺口
- [ ] 7.2 将 `input`、`numberInput`、`select`、`textarea`、`switch` 和 `upload` 的可视化与交互路径统一收敛到 TDesign 组件契约,其中 `select` 需要直接呈现 TDesign `Select` 外观,`upload` 需要进一步拆成媒体上传与普通文件上传两条 TDesign `Upload` 路径
- [ ] 7.3 将媒体上传已有值展示调整为 TDesign 图片卡片形态,覆盖缩略图、hover 蒙层、预览操作、删除操作和文件名下置
- [ ] 7.4 同步调整 `/components` Demo,使媒体上传展示图片/GIF/视频共用卡片态,普通文件上传展示文件信息态
- [ ] 7.5 清理不再需要的兼容分支、隐藏 DOM shim 和页面级原生用法
- [ ] 7.6 补充或更新测试,覆盖禁用、只读、字数统计、选择器、上传预览、Demo 展示和动态联动在 TDesign-first 路径下的行为
- [ ] 7.7 重新运行 `npm run typecheck`、相关测试、`npm run build` 和 `openspec validate "business-form-component" --strict`
- [x] 7.8 将媒体上传无值态调整为虚线卡片入口,卡片内展示 `placeholder` 或默认 `点击上传`,卡片下方展示字段配置动态传入的 `helperText`
- [x] 7.9 补充删除媒体后恢复占位态的测试,并同步更新 Demo 中展示素材字段的动态说明文案
- [x] 7.10 将媒体上传已有值 hover 蒙层调整为接近 TDesign 图片上传卡片的操作样式,使用更浅的中性遮罩并补充预览/删除操作分隔线
- [x] 7.11 将媒体上传无值占位卡片和已有值预览卡片统一调整为 `110px × 110px`
- [x] 7.12 将媒体上传文件名调整为单行省略,并把预览动作收敛到 TDesign `Upload` 的 `onPreview` 路径
- [x] 7.13 为上传字段增加 `maxCount` 和 `multiple` 配置,默认单文件,媒体上传支持配置多张图片/GIF/视频并以数组值写回
- [x] 7.14 在 `BusinessForm` Demo 中补充多选 Select 字段,展示 `select.multiple` 配置与数组值写回
## Context
`BusinessTable` 负责承接业务表格、空态和可选分页。TDesign `Pagination` 默认会展示 `totalContent`,当前 `BusinessTable` 又在 footer 左侧根据 `totalLabel` 渲染一份自定义总数,页面同时传入两者时会出现两份总数。
用户已明确希望“使用 Pagination 默认的 totalContent 即可”,因此本次不采用在 `BusinessTable` 内关闭 Pagination `totalContent` 的方案,而是将分页场景的总数展示收敛回 TDesign 默认行为。
用户进一步确认筛选无结果态不需要说明文案与状态区操作按钮;列表失败态需要显示失败文案“请求失败”,但不需要下方蓝色操作按钮。状态块仍用于表达当前结果,筛选恢复由搜索区或筛选区已有操作承担,列表重新加载由页面其他已有入口承担。
## Goals / Non-Goals
**Goals:**
- 分页场景下只展示 TDesign `Pagination` 默认总数。
- 保留无分页场景下 `totalLabel` 作为底部文案的能力。
- 清理 Demo 和后台列表页中分页场景传入的冗余 `totalLabel`。
- 用回归测试覆盖“分页 + totalLabel 不重复展示”。
- 筛选无结果态只保留图标和标题,不展示“请调整搜索或筛选条件”与“清空筛选”按钮。
- 列表失败态展示失败图标和标题“请求失败”,不展示“重试”按钮。
**Non-Goals:**
- 不改变普通空态和权限受限态的视觉规则。
- 不定制 TDesign Pagination 的默认总数文案。
- 不调整分页切换、页容量切换、查询参数同步等业务行为。
- 不移除搜索区或筛选区已有的重置能力。
## Decisions
1. 当 `BusinessTable` 收到 `pagination` 时,footer 只渲染 `Pagination`,由 TDesign 默认 `totalContent` 展示总数。
2. 当 `pagination={false}` 或未传入分页配置,但传入 `totalLabel` 时,`BusinessTable` 仍可在 footer 左侧展示 `totalLabel`。
3. 已迁移列表页和 Demo 页在分页场景不再传入 `totalLabel`,减少调用方重复表达同一份总数。
4. 测试优先覆盖业务组件层行为,再用类型检查确认页面调用方式一致。
5. 筛选无结果态和列表失败态统一采用精简状态块:筛选无结果保留既有图标和标题,不渲染说明文案和状态区操作按钮;列表失败态保留失败图标和标题“请求失败”,不渲染状态区操作按钮。页面即使仍传入恢复回调,状态块也不提供“清空筛选”或“重试”入口。
## Risks / Trade-offs
- Pagination 默认总数文案由 TDesign 控制,页面不再通过 `totalLabel` 自定义分页总数文案。
- 无分页统计文案仍依赖 `totalLabel`,因此组件实现需要保留这个 API。
- 筛选无结果态和列表失败态不再在状态块中提供恢复操作,用户需要使用页面已有搜索区、筛选区或其他重新加载入口。
## Why
`BusinessTable` 当前在分页场景下同时渲染自定义 `totalLabel` 和 TDesign `Pagination` 默认的 `totalContent`,会导致页面底部出现两份“共 N 条数据”。用户已确认状态展示方向无问题,但总数展示应使用 Pagination 默认能力,避免业务组件额外重复渲染。
## What Changes
- 调整 `BusinessTable` 的分页总数规则:传入 `pagination` 时,总数展示由 TDesign `Pagination` 默认 `totalContent` 负责。
- `totalLabel` 仅用于无分页但仍需要在表格底部展示总数或补充统计文案的场景。
- 更新相关测试,覆盖传入分页和 `totalLabel` 时页面只出现一份总数。
- 清理 Demo 和后台列表页中分页场景的多余 `totalLabel` 使用。
- 精简筛选无结果态:保留图标和标题,隐藏说明文案与“清空筛选”按钮。
- 精简列表失败态:保留失败图标和标题“请求失败”,隐藏“重试”按钮。
## Non-Goals
- 不改变普通空态和权限受限态视觉。
- 不改造 TDesign `Pagination` 的默认文案格式。
- 不新增分页组件包装层或新的分页 API。
- 不移除搜索区或筛选区已有的重置能力。
- 不移除页面通过其他入口主动重新加载列表的能力。
- 不归档本 change,直到用户确认实现和验证结果。
## Capabilities
### Modified Capabilities
- `business-table`:统一分页场景下的总数展示来源,避免重复总数;精简筛选无结果态和列表失败态的状态块内容,并将列表失败态标题统一为“请求失败”。
## Impact
- 影响 `packages/business-components/src/business-table/BusinessTable.tsx` 的 footer 渲染逻辑。
- 影响 `packages/business-components/src/business-table/BusinessTable.tsx` 的状态块渲染规则。
- 影响已迁移到 `BusinessTable` 且同时传入 `pagination` 与 `totalLabel` 的列表页和 Demo 页。
- 影响 `workspace/agent-admin/web/src/business-components/business-table.test.tsx` 的分页总数和状态块断言。
## MODIFIED Requirements
### Requirement: 可选分页和总数展示
系统 SHALL 支持在业务表格底部渲染可选分页或无分页总数信息,并在分页场景使用 TDesign `Pagination` 默认总数展示。
#### Scenario: 渲染分页
- **WHEN** 页面传入分页配置
- **THEN** 系统 SHALL 使用 TDesign `Pagination` 渲染当前页、页大小、默认总数文案和分页回调
#### Scenario: 分页场景不渲染额外总数文案
- **WHEN** 页面传入分页配置
- **THEN** 系统 SHALL NOT 在 `Pagination` 外额外渲染 `totalLabel`
- **AND** 页面 SHALL 使用 TDesign `Pagination` 默认的 `totalContent` 展示总数
#### Scenario: 禁用分页
- **WHEN** 页面传入 `pagination={false}`
- **THEN** 系统 SHALL NOT 渲染分页组件
#### Scenario: 无分页时展示总数文案
- **WHEN** 页面未传入分页配置或传入 `pagination={false}`,且传入 `totalLabel`
- **THEN** 系统 SHALL 在表格底部展示该总数文案
### Requirement: 精简筛选空态
系统 SHALL 在筛选无结果时使用精简状态块,仅展示图标和标题。
#### Scenario: 筛选无结果
- **WHEN** 表格无错误、非加载、无数据且存在筛选条件
- **THEN** 系统 SHALL 展示筛选无结果图标和标题“未找到匹配结果”
- **AND** 系统 SHALL NOT 展示说明文案“请调整搜索或筛选条件”
- **AND** 系统 SHALL NOT 展示“清空筛选”按钮
### Requirement: 精简列表失败态
系统 SHALL 在列表加载失败时使用精简状态块,展示失败图标和标题“请求失败”。
#### Scenario: 列表加载失败
- **WHEN** 表格收到加载失败态配置
- **THEN** 系统 SHALL 展示失败态图标和标题“请求失败”
- **AND** 系统 SHALL NOT 展示“重试”按钮
- **AND** 系统 SHALL NOT 渲染无文案的状态区按钮
### Requirement: 表格刷新加载态
系统 SHALL 在 `BusinessTable` 收到加载态时使用表格区域局部 loading,并采用业务组件默认的轻量加载样式。
#### Scenario: 表格刷新中
- **WHEN** 页面向 `BusinessTable` 传入 `loading={true}`
- **THEN** 系统 SHALL 保留表格结构并展示表格区域 loading
- **AND** 系统 SHALL 使用小尺寸加载指示和当前主题主色提示文案
- **AND** 系统 SHALL 使用当前主题主色渲染加载指示器
- **AND** 系统 SHALL 允许调用方通过 TDesign `loadingProps` 覆盖默认加载配置
## 1. OpenSpec 对齐
- [x] 1.1 创建 `proposal.md`,明确分页总数重复问题和用户确认方向
- [x] 1.2 创建 `design.md`,明确使用 TDesign Pagination 默认 `totalContent`
- [x] 1.3 创建 `business-table` spec delta,覆盖分页和无分页总数展示规则
- [x] 1.4 补充筛选无结果态和列表失败态的精简规则
- [x] 1.6 对齐列表失败态标题为“请求失败”且不展示状态区按钮
- [x] 1.7 补充表格刷新加载态使用轻量局部 loading 的规则
- [x] 1.8 对齐表格 loading 使用当前主题主色的规则
- [x] 1.5 等待用户确认 OpenSpec 文档后再进入实现
## 2. TDD 与实现
- [x] 2.1 更新 `business-table.test.tsx`,覆盖分页场景只展示一份默认总数
- [x] 2.2 调整 `BusinessTable` footer 渲染逻辑,使分页场景不额外渲染 `totalLabel`
- [x] 2.3 清理分页页面和 Demo 中冗余的 `totalLabel` 传参
- [x] 2.4 更新 `business-table.test.tsx`,覆盖筛选无结果态和列表失败态不展示说明文案与状态区按钮
- [x] 2.5 调整 `BusinessTable` 状态块渲染逻辑,仅为筛选无结果态和列表失败态保留图标与标题
- [x] 2.6 调整 `BusinessTable` 默认列表失败态标题为“请求失败”,并同步消费方测试
- [x] 2.7 补充失败态不渲染空文案按钮的测试,并修正 action 生成条件
- [x] 2.8 调整 `BusinessTable` 默认 loadingProps 和样式,使表格 loading 更轻量
- [x] 2.9 将 `BusinessTable` loading 指示器和提示文案颜色切换为当前主题主色
## 3. 验证
- [x] 3.1 运行 `rtk npm test -- business-table.test.tsx`
- [x] 3.2 运行 `rtk npm run typecheck`
- [x] 3.3 运行 `rtk openspec validate fix-business-table-duplicate-total --strict`
- [x] 3.4 运行 `rtk npm test -- business-table.test.tsx AgentListPage.test.tsx AgentTagManagement.test.tsx ChannelCodeListPage.test.tsx SkillListPage.test.tsx OfficialSiteJobTabListPage.test.tsx OfficialSiteAgentDisplayConfigList.test.tsx OfficialSiteAgentDisplayConfigRoutes.test.tsx`
- [x] 3.5 运行 `rtk npm test -- business-table.test.tsx`
- [x] 3.6 运行 `rtk npm test -- business-table.test.tsx`
- [x] 3.7 运行 `rtk npm run typecheck`
- [x] 3.8 运行 `rtk openspec validate fix-business-table-duplicate-total --strict`
- [x] 3.9 运行 `rtk npm test -- business-table.test.tsx`
- [ ] 3.10 运行 `rtk npm run typecheck`(当前失败:`packages/ui/src/components/business-form.test.tsx` 引用尚未导出的 `BusinessForm`/`validateBusinessForm` 等,与本次 loading 颜色调整无关)
- [x] 3.11 运行 `rtk openspec validate fix-business-table-duplicate-total --strict`
## Context
`workspace/agent-admin/web/src` 当前有 18 个不同运行时代码文件通过 19 条 import 声明依赖 `workspace/agent-admin/web/packages/ui/src`。本地 UI 包同时包含基础控件和业务组合组件,其中部分基础控件内部仍使用原生 DOM,部分已经包装 TDesign,页面也已开始直接使用 `tdesign-react`。
根目录 `packages/business-components` 已存在 `BusinessLoginPage` 和 `BusinessAdminShell`,并通过 `@gl/business-components` 提供跨项目复用入口。本轮需要延续这一边界,把适合跨页面复用的后台业务组合组件提升到全局包,同时让页面直接消费 TDesign 基础组件。
详细盘点与方案比较见 `docs/superpowers/specs/2026-05-31-migrate-admin-ui-to-global-tdesign-design.md`。
## Goals / Non-Goals
**Goals:**
- 让 `workspace/agent-admin/web/src` 对本地 `packages/ui/src` 达到零运行时依赖。
- 基础 UI 控件直接从 `tdesign-react` 引入,图标直接从 `tdesign-icons-react` 引入。
- 将 `SearchFilter`、`StatePlaceholder`、`MediaWall` 迁入根目录 `packages/business-components`。
- 保持页面现有业务行为、数据流、接口契约和路由不变。
- 调整组件 Demo,使其只展示 TDesign 基础能力和全局业务组件。
**Non-Goals:**
- 不删除 `workspace/agent-admin/web/packages/ui` 目录。
- 不在本轮清理旧组件源码、旧组件测试和未被 `web/src` 使用的内部组件。
- 不处理 `workspace/agent-admin/single-page` 中的原生控件。
- 不在本轮引入配置化表单渲染器,也不把编辑页表单重写为配置协议。
- 不进行页面视觉改版、后端 API 修改或业务流程重构。
## Decisions
### Decision 1:基础控件由页面直接使用 TDesign
页面、布局和 Hook 中的基础控件改为直接从 `tdesign-react` 引入;图标改为直接从 `tdesign-icons-react` 引入。迁移时按 TDesign API 调整属性名、事件签名和测试选择器。
采用这一方案是因为本轮目标是消除 `web/src` 对本地包装层的运行时依赖。备选方案是在 `packages/ui` 内部替换实现,但它仍会保留本地依赖边界,无法满足目标。
### Decision 2:业务组合组件提升到全局包
`SearchFilter`、`StatePlaceholder`、`MediaWall` 迁入根目录 `packages/business-components`,通过 `@gl/business-components` 统一导出。它们内部使用 TDesign 基础组件,不再依赖 `workspace/agent-admin/web/packages/ui`。
采用这一方案是因为三者承载可复用业务语义:搜索条件编排、页面状态占位、媒体上传预览。备选方案是在页面中直接展开这些能力,但会造成重复实现和行为漂移。
### Decision 3:保持业务行为不变
本轮只调整 UI 依赖路径。列表查询、重置、分页、弹窗、抽屉、加载态、空态、错误态、媒体上传、表单校验和提交反馈继续遵循现有行为。
页面测试需要围绕行为和 TDesign 可观察结构更新,避免继续依赖旧本地组件实现细节。
消息反馈迁移到 TDesign `MessagePlugin` 后,React 19 运行时必须让 TDesign 插件渲染路径使用 `react-dom/client` 的 `createRoot`。适配器需要与实际被打包消费的 TDesign ESM 入口保持一致,避免只补丁 `lib` 入口而让页面运行时仍落回 React 19 已移除的 `ReactDOM.render`。
### Decision 4:旧本地 UI 包保留但退出运行时链路
`workspace/agent-admin/web/packages/ui` 目录保留,作为后续独立清理工作的输入。本轮验收只扫描 `workspace/agent-admin/web/src` 的运行时 import,不删除旧目录,也不要求立即处理其内部源码。
### Decision 5:按风险分批迁移
实施顺序为:
1. 迁移全局业务组合组件。
2. 迁移布局、消息 Hook、抽屉和列表页。
3. 迁移编辑页表单。
4. 迁移组件 Demo。
5. 运行零依赖扫描、测试、类型检查、构建和浏览器验证。
每一批均先调整或补充测试,再修改实现。
### Decision 6:本轮不引入配置化表单渲染器
编辑页在本轮直接使用 TDesign `Form`、`FormItem` 和基础输入控件,保留页面现有字段状态、校验、联动、上传和提交逻辑。不新增 `BusinessForm` 或 `FormRenderer`,也不把复杂页面改写为配置协议。
采用这一方案是因为本轮目标是统一 UI 依赖边界,而不是重构表单架构。配置化渲染适合重复度高的简单表单,但对上传、动态数组、多层级联动、复杂业务选择器和步骤表单容易产生大量特殊参数,增加理解和维护成本。
迁移完成后可另开独立变更,选择两个结构重复的简单编辑页验证轻量 `BusinessForm`。后续试点必须提供 `children` 或 `render` 逃生口,允许页面混用配置字段与手写 TDesign `FormItem`;若协议开始依赖大量联动和布局特例,则回到页面级组合。
## Risks / Trade-offs
- [Risk] TDesign 的属性名和事件签名与旧包装组件不同,可能引入表单值更新回归。
→ Mitigation:按页面分批 TDD,重点覆盖输入、选择、开关、分页和弹窗确认行为。
- [Risk] `SearchFilter` 提升到全局包后可能意外改变查询草稿与提交值的边界。
→ Mitigation:保留既有公开属性和回调语义,并覆盖查询、重置和状态筛选测试。
- [Risk] `MediaWall` 涉及上传、预览和删除,迁移影响面高于普通基础控件。
→ Mitigation:保持现有上传契约,增加上传成功、失败、删除和回填测试。
- [Risk] Demo 一次性迁移的组件种类较多,容易遗漏旧 import。
→ Mitigation:单独建立 Demo 迁移任务,并以静态扫描作为最终门禁。
- [Risk] React 19 下 TDesign 插件式反馈组件若未正确加载同入口的 React 19 适配器,会在触发消息时调用已移除的 `ReactDOM.render` 并抛出运行时错误。
→ Mitigation:为 `useMessage` 补充运行时导入约束和回归测试,确保消息插件使用与 `tdesign-react` 主入口一致的适配器。
- [Trade-off] 旧 `packages/ui` 暂时保留,会产生一段时间的无运行时引用遗留代码。
→ Mitigation:本轮明确记录保留策略,后续以独立变更完成删除和依赖清理。
- [Trade-off] 本轮继续保留页面级表单结构,短期内不会减少重复字段代码。
→ Mitigation:先完成依赖迁移,再以独立试点衡量轻量表单组件的真实复用收益。
## Migration Plan
1. 在 `packages/business-components` 增加全局业务组合组件及导出。
2. 分批替换 `workspace/agent-admin/web/src` 中的本地 UI import。
3. 更新相关测试和组件 Demo。
4. 扫描并确认 `workspace/agent-admin/web/src` 不再存在指向 `packages/ui` 的运行时 import。
5. 运行相关测试、`npm run typecheck`、`npm run build`、OpenSpec 严格校验,并完成浏览器验证。
回滚时可以按批次恢复页面 import 和全局组件导出。本轮不删除旧本地 UI 包,因此无需恢复旧源码。
## Open Questions
- 无。已确认本轮只处理 `workspace/agent-admin/web/src`,暂不删除 `packages/ui`,不处理 `single-page`,也不引入配置化表单渲染器。
## Why
`workspace/agent-admin/web/src` 仍通过本地 `packages/ui/src` 使用基础控件和业务组合组件,导致后台页面同时存在本地包装层、TDesign 直连和全局业务组件三种依赖路径。需要统一运行时依赖边界,让后台页面直接使用 TDesign 基础组件,并把可复用业务组合能力提升到全局组件包。
## What Changes
- 将 `workspace/agent-admin/web/src` 中所有指向本地 `packages/ui/src` 的运行时依赖迁出。
- 基础控件、反馈组件、展示组件和图标分别直接使用 `tdesign-react` 与 `tdesign-icons-react`。
- 将 `SearchFilter`、`StatePlaceholder`、`MediaWall` 提升到根目录 `@gl/business-components`,供后台页面统一复用。
- 调整组件 Demo,使其展示 TDesign 基础组件与全局业务组件,不再作为旧本地 UI 包的展示入口。
- 保留 `workspace/agent-admin/web/packages/ui` 目录,本轮不删除旧源码,也不要求立即清理旧组件测试。
- 编辑页直接使用 TDesign 表单能力,本轮不引入配置化表单渲染器,也不把复杂表单重写为配置协议。
- 保持现有页面业务行为、接口契约和路由结构不变。
## Capabilities
### New Capabilities
- `admin-ui-runtime-dependency`: 约束后台运行时代码的 UI 依赖边界、全局业务组合组件归属和旧本地 UI 包保留策略。
### Modified Capabilities
- 无。
## Impact
- 受影响代码:`workspace/agent-admin/web/src` 下页面、布局、Hook、组件 Demo 及相关测试。
- 全局组件包:根目录 `packages/business-components` 新增或迁入 `SearchFilter`、`StatePlaceholder`、`MediaWall`。
- 前端依赖:继续使用既有 `tdesign-react`,并按需直接使用 `tdesign-icons-react`。
- 表单架构:本轮保持页面级组合;轻量 `BusinessForm` 或 `FormRenderer` 仅作为迁移完成后的独立试点方向。
- 不影响后端 API、数据结构、路由路径和 `workspace/agent-admin/single-page`。
## ADDED Requirements
### Requirement: 后台运行时代码不再依赖本地 UI 包
系统 MUST 让 `workspace/agent-admin/web/src` 中的运行时代码不再从 `workspace/agent-admin/web/packages/ui` 或其子路径引入组件、类型或工具。
#### Scenario: 扫描后台运行时 import
- **WHEN** 对 `workspace/agent-admin/web/src` 执行本地 UI 包依赖扫描
- **THEN** 扫描结果不包含指向 `packages/ui` 或 `packages/ui/src` 的运行时 import
### Requirement: 基础控件直接使用 TDesign
后台页面、布局、Hook 和组件 Demo MUST 直接使用 `tdesign-react` 提供的基础控件,并在需要图标时直接使用 `tdesign-icons-react`。
#### Scenario: 页面使用基础控件
- **WHEN** 后台页面渲染按钮、输入框、文本域、选择器、开关、表格、分页、弹窗、抽屉、标签或消息反馈
- **THEN** 对应基础能力来自 `tdesign-react`
#### Scenario: 页面使用图标
- **WHEN** 后台页面或组件 Demo 需要渲染 TDesign 已提供的图标
- **THEN** 图标来自 `tdesign-icons-react`
### Requirement: 业务组合组件通过全局组件包复用
系统 MUST 将 `SearchFilter`、`StatePlaceholder`、`MediaWall` 作为全局业务组合组件从 `@gl/business-components` 导出,并且这些组件内部 MUST 不依赖 `workspace/agent-admin/web/packages/ui`。
#### Scenario: 列表页复用搜索区
- **WHEN** 后台列表页渲染查询条件、查询按钮和重置按钮
- **THEN** 页面从 `@gl/business-components` 使用 `SearchFilter`
#### Scenario: 页面复用状态占位
- **WHEN** 后台页面展示加载态、空数据态或错误态
- **THEN** 页面从 `@gl/business-components` 使用 `StatePlaceholder`
#### Scenario: 官网配置复用媒体墙
- **WHEN** 官网配置页面展示媒体上传、预览或删除能力
- **THEN** 页面从 `@gl/business-components` 使用 `MediaWall`
### Requirement: UI 依赖迁移保持业务行为
系统 MUST 在迁移 UI 依赖后保持现有后台页面的查询、重置、分页、弹窗、抽屉、表单更新、表单提交、状态展示和媒体上传行为。
#### Scenario: 列表页交互保持一致
- **WHEN** 用户在迁移后的列表页执行查询、重置、分页或行操作
- **THEN** 页面行为与迁移前一致
#### Scenario: 编辑页交互保持一致
- **WHEN** 用户在迁移后的编辑页修改字段并提交表单
- **THEN** 字段状态、校验和提交行为与迁移前一致
#### Scenario: 媒体墙交互保持一致
- **WHEN** 用户在迁移后的媒体墙执行上传、预览或删除
- **THEN** 页面继续使用既有上传契约并正确回填状态
#### Scenario: 消息反馈在 React 19 下可用
- **WHEN** 用户操作触发成功、失败、警告或信息消息
- **THEN** TDesign 消息插件使用 React 19 兼容的渲染入口展示反馈
- **AND** 页面不抛出 `reactRender is not a function`
### Requirement: 组件 Demo 不再展示旧本地 UI 包
组件 Demo MUST 展示 TDesign 基础组件和全局业务组件,并且 MUST 不再从 `workspace/agent-admin/web/packages/ui` 引入运行时能力。
#### Scenario: 打开组件 Demo
- **WHEN** 用户访问 `/components`
- **THEN** 页面可展示并交互使用 TDesign 基础组件和全局业务组件
- **AND** 页面不依赖旧本地 UI 包
### Requirement: 旧本地 UI 包目录暂时保留
系统 MUST 在本轮迁移中保留 `workspace/agent-admin/web/packages/ui` 目录,不把旧源码删除作为零运行时依赖验收条件。
#### Scenario: 完成运行时依赖迁移
- **WHEN** `workspace/agent-admin/web/src` 已达到零本地 UI 包运行时依赖
- **THEN** `workspace/agent-admin/web/packages/ui` 目录仍可保留,等待后续独立清理
### Requirement: 本轮表单迁移保持页面级组合
系统 MUST 在本轮迁移中让编辑页直接使用 TDesign 表单能力,并且 MUST NOT 引入配置化表单渲染器或把复杂表单逻辑改写为配置协议。
#### Scenario: 迁移编辑页表单
- **WHEN** 后台编辑页替换本地 `FormItem`、输入控件或选择控件
- **THEN** 页面直接使用 TDesign `Form`、`FormItem` 和基础控件
- **AND** 页面继续保留既有字段状态、校验、联动、上传和提交逻辑
#### Scenario: 遇到复杂表单内容
- **WHEN** 编辑页包含上传、媒体墙、动态数组、多层级联动、复杂业务选择器或步骤表单
- **THEN** 本轮继续使用页面级组合
- **AND** 系统不为这些内容扩展新的配置协议
## 1. 建立迁移基线
- [x] 1.1 扫描并记录 `workspace/agent-admin/web/src` 中指向 `packages/ui` 的运行时 import 基线
- [x] 1.2 盘点 `SearchFilter`、`StatePlaceholder`、`MediaWall` 的公开属性、行为和现有测试覆盖
- [x] 1.3 为零运行时依赖门禁补充可重复执行的静态扫描检查
## 2. 提升全局业务组合组件
- [x] 2.1 先为全局 `SearchFilter` 补充失败测试,再将其迁入 `@gl/business-components` 并保持查询、重置和草稿提交行为
- [x] 2.2 先为全局 `StatePlaceholder` 补充失败测试,再将其迁入 `@gl/business-components` 并保持加载、空数据和错误态行为
- [x] 2.3 先为全局 `MediaWall` 补充失败测试,再将其迁入 `@gl/business-components` 并保持上传、预览、删除和回填行为
- [x] 2.4 更新 `@gl/business-components` 导出入口,并确认三个全局业务组件内部不依赖 `workspace/agent-admin/web/packages/ui`
## 3. 迁移共享入口与只读页面
- [x] 3.1 先调整测试,再将 `AdminShell` 的弹窗能力改为直接使用 TDesign
- [x] 3.2 先调整测试,再将 `useMessage` 的反馈能力改为直接使用 TDesign
- [x] 3.3 先调整测试,再迁移 Agent、渠道活码和 Skill 详情抽屉中的按钮、抽屉、标签与状态占位
- [x] 3.4 运行共享入口与详情抽屉相关测试,确认行为保持一致
## 4. 迁移列表页
- [x] 4.1 先调整测试,再迁移 Agent 列表页的 TDesign 基础控件和全局 `SearchFilter`、`StatePlaceholder`
- [x] 4.2 先调整测试,再迁移岗位标签列表页的 TDesign 基础控件和全局 `SearchFilter`、`StatePlaceholder`
- [x] 4.3 先调整测试,再迁移渠道活码列表页的 TDesign 基础控件和全局 `SearchFilter`、`StatePlaceholder`
- [x] 4.4 先调整测试,再迁移官网岗位展示配置列表页的 TDesign 基础控件和全局 `SearchFilter`、`StatePlaceholder`
- [x] 4.5 先调整测试,再迁移 Skill 列表页的 TDesign 基础控件和全局 `SearchFilter`、`StatePlaceholder`
- [x] 4.6 运行列表页相关测试,确认查询、重置、分页、弹窗和行操作保持一致
## 5. 迁移编辑页与官网配置
- [x] 5.0 确认编辑页仅直接使用 TDesign 表单能力,不新增配置化表单渲染器或表单配置协议
- [x] 5.1 先调整测试,再迁移 Agent 编辑页的 TDesign 表单控件和全局 `StatePlaceholder`
- [x] 5.2 先调整测试,再迁移岗位标签编辑页的 TDesign 表单控件和全局 `StatePlaceholder`
- [x] 5.3 先调整测试,再迁移渠道活码编辑页的 TDesign 表单控件和全局 `StatePlaceholder`
- [x] 5.4 先调整测试,再迁移官网方法论配置页的 TDesign 表单控件和全局 `MediaWall`、`StatePlaceholder`
- [x] 5.5 先调整测试,再迁移官网 Agent 展示配置编辑弹窗和列表页的 TDesign 基础控件与全局 `MediaWall`、`StatePlaceholder`
- [x] 5.6 先调整测试,再迁移官网岗位展示新增编辑页和列表页的 TDesign 基础控件与全局 `SearchFilter`、`StatePlaceholder`
- [x] 5.7 运行编辑页与官网配置相关测试,确认字段更新、校验、上传和提交行为保持一致
## 6. 迁移组件 Demo
- [x] 6.1 先调整 Demo 测试,再将基础组件示例改为直接使用 `tdesign-react` 与 `tdesign-icons-react`
- [x] 6.2 将业务组合组件示例改为使用 `@gl/business-components`
- [x] 6.3 清理 Demo 对旧本地组件样式和实现细节的依赖
- [x] 6.4 运行组件 Demo 测试,确认展示和关键交互可用
## 7. 验证与收尾
- [x] 7.1 扫描 `workspace/agent-admin/web/src`,确认不存在指向 `packages/ui` 的运行时 import
- [x] 7.2 确认 `workspace/agent-admin/web/packages/ui` 目录仍然保留
- [x] 7.3 运行相关测试与完整前端测试
- [x] 7.4 运行 `npm run typecheck`
- [x] 7.5 运行 `npm run build`
- [x] 7.6 运行 `openspec validate "migrate-admin-ui-to-global-tdesign" --strict`
- [x] 7.7 在浏览器中验证主要列表页、编辑页和 `/components` 的布局与关键交互
## 8. 修复 React 19 消息插件运行时适配
- [x] 8.1 补充 `useMessage` 回归测试,覆盖 React 19 下 TDesign `MessagePlugin` 适配器导入路径与主入口一致
- [x] 8.2 将 `useMessage` 的 React 19 适配器导入调整为与 `tdesign-react` 实际 ESM 入口一致
- [x] 8.3 运行 `useMessage` 相关测试、类型检查、构建和 OpenSpec 严格校验
- [x] 8.4 在浏览器中触发成功消息,确认不再出现 `reactRender is not a function`
...@@ -4,12 +4,25 @@ ...@@ -4,12 +4,25 @@
TBD - created by archiving change add-admin-login-agent-list-mock. Update Purpose after archive. TBD - created by archiving change add-admin-login-agent-list-mock. Update Purpose after archive.
## Requirements ## Requirements
### Requirement: 登录页展示 ### Requirement: 登录页展示
岗位 Agent 管理后台 SHALL 在用户访问受保护管理页面前提供 `岗位Agent管理后台` 登录页。 岗位 Agent 管理后台 SHALL 在用户访问受保护管理页面前提供符合工作区统一登录页规范的 `岗位Agent管理后台` 登录页。
#### Scenario: 打开登录页 #### Scenario: 打开登录页
- **WHEN** 未登录用户打开登录路由 - **WHEN** 未登录用户打开登录路由
- **THEN** 登录页展示产品名称 `岗位Agent管理后台` - **THEN** 登录页展示产品名称 `岗位Agent管理后台`
- **AND** 登录页展示账号、密码和登录控件 - **AND** 产品名称使用深色、加粗的大标题样式
- **AND** 登录页在产品名称下方展示系统描述,描述使用浅色、正常字号文本
- **AND** 登录页展示账号输入框、密码输入框和登录控件
- **AND** 登录页不显示账号、密码字段标签
- **AND** 账号输入框 placeholder 为 `请输入账号`
- **AND** 密码输入框 placeholder 为 `请输入密码`
- **AND** 账号输入框左侧展示用户图标
- **AND** 密码输入框左侧展示锁图标
- **AND** 密码输入框右侧展示眼睛图标,用于切换密码可见性
- **AND** 登录页展示背景图片,图片等比例居中显示,背景底色与图片同色系
- **AND** 登录页背景底色由业务页面传入共享登录组件,不在共享登录组件中写死
- **AND** 登录区域最低高度为 `350px`
- **AND** 登录区域在背景上水平和垂直居中
- **AND** 登录页结构通过 `@gl/business-components` 的登录业务组件复用
### Requirement: 本地账号密码校验 ### Requirement: 本地账号密码校验
岗位 Agent 管理后台 SHALL 在本地校验一期固定账号密码,账号为 `admin`,密码为 `123456`。 岗位 Agent 管理后台 SHALL 在本地校验一期固定账号密码,账号为 `admin`,密码为 `123456`。
......
...@@ -6,26 +6,56 @@ TBD - created by archiving change add-admin-login-agent-list-mock. Update Purpos ...@@ -6,26 +6,56 @@ TBD - created by archiving change add-admin-login-agent-list-mock. Update Purpos
### Requirement: 受保护后台框架 ### Requirement: 受保护后台框架
岗位 Agent 管理后台 SHALL 在共享的受保护后台框架内展示管理页面。 岗位 Agent 管理后台 SHALL 在共享的受保护后台框架内展示管理页面。
#### Scenario: 展示受保护页面 #### Scenario: 展示固定后台框架结构
- **WHEN** 已登录用户打开受保护管理页面 - **WHEN** 已登录用户打开受保护管理页面
- **THEN** 岗位 Agent 管理后台展示共享后台框架 - **THEN** 岗位 Agent 管理后台展示左侧菜单和右侧内容的左右结构
- **AND** 后台框架标识产品为 `岗位Agent管理后台` - **AND** 左侧菜单顶部展示系统名称 `岗位Agent管理后台`
- **AND** 后台框架在顶部右侧提供头像和 `退出登录` 按钮 - **AND** 右侧内容区域分为固定高度 header 和 content 两部分
- **AND** content 区域内边距为 `24px`
- **AND** 后台框架通过 `@gl/business-components` 的登录后框架业务组件渲染
#### Scenario: 收起和展开左侧菜单
- **WHEN** 已登录用户点击左侧菜单的收起按钮
- **THEN** 左侧菜单切换为收起状态
- **AND** 菜单仅保留可识别的菜单图标导航
- **WHEN** 用户再次点击展开按钮
- **THEN** 左侧菜单恢复展示系统名称和菜单文字
#### Scenario: 展示用户区
- **WHEN** 当前系统没有个人信息功能
- **THEN** header 右侧展示用户名称
- **AND** header 右侧展示用户头像
- **AND** 用户没有头像时使用默认背景色并显示用户名称第一个字
- **AND** `退出登录` 按钮展示在头像右侧
#### Scenario: 展示个人信息下拉菜单
- **WHEN** 当前系统启用个人信息功能
- **THEN** header 右侧头像可点击
- **AND** 点击头像后下拉菜单展示 `个人信息` 和 `退出登录`
### Requirement: 管理后台导航 ### Requirement: 管理后台导航
岗位 Agent 管理后台 SHALL 将 Agent 管理作为首个可用管理模块提供导航,并为后续已确认模块保留扩展空间。 岗位 Agent 管理后台 SHALL 将 Agent 管理作为首个可用管理模块提供导航,并为后续已确认模块保留扩展空间。
#### Scenario: Agent 管理路由激活 #### Scenario: 默认跳转到第一个菜单
- **WHEN** 已登录用户打开 Agent 管理列表页 - **WHEN** 已登录用户打开应用根路径
- **THEN** 后台框架将 `Agent管理` 显示为一级导航项 - **THEN** 岗位 Agent 管理后台跳转到第一个可用二级菜单页面 `Agent列表`
- **AND** 后台框架将 `Agent列表` 显示为其下的二级导航项
- **AND** `Agent列表` 使用主选中样式 #### Scenario: 展示一二级菜单
- **AND** `Agent管理` 不使用主选中样式,只作为一级分组项展示 - **WHEN** 已登录用户打开任意受保护页面
- **THEN** 左侧菜单展示一级菜单
- **AND** 左侧菜单展示一级菜单下方的二级菜单
- **AND** 当前二级菜单保持选中
#### Scenario: 点击一级菜单切换二级菜单展开状态
- **WHEN** 已登录用户点击展开态左侧菜单中带子菜单的一级菜单
- **THEN** 该一级菜单下方的二级菜单在展开和收起之间切换
- **AND** 路由默认展开的一级菜单不阻止用户手动收起或展开
#### Scenario: 复用共享导航组件 #### Scenario: 通过菜单配置展示图标
- **WHEN** 后台框架渲染左侧导航 - **WHEN** 已登录用户打开任意受保护页面
- **THEN** 后台框架通过共享 UI 导航组件渲染一级和二级菜单 - **THEN** 左侧菜单图标由 `agent-admin` 的菜单配置传入
- **AND** 后台框架 SHALL NOT 在页面内手写导航层级结构、选中态样式或展开交互 - **AND** 菜单图标使用 `tdesign-icons-react` 图标组件
- **AND** 共享后台框架不在内部硬编码业务菜单图标
### Requirement: 左侧导航信息密度 ### Requirement: 左侧导航信息密度
岗位 Agent 管理后台 SHALL 使用适合桌面后台的左侧导航间距,并保证产品名称在默认桌面布局下不换行。 岗位 Agent 管理后台 SHALL 使用适合桌面后台的左侧导航间距,并保证产品名称在默认桌面布局下不换行。
...@@ -54,3 +84,30 @@ TBD - created by archiving change add-admin-login-agent-list-mock. Update Purpos ...@@ -54,3 +84,30 @@ TBD - created by archiving change add-admin-login-agent-list-mock. Update Purpos
- **THEN** 后台框架仍然可见 - **THEN** 后台框架仍然可见
- **AND** 用户仍可导航或退出登录 - **AND** 用户仍可导航或退出登录
### Requirement: 后台框架面包屑
岗位 Agent 管理后台 SHALL 在 header 左侧展示当前页面的层级面包屑。
#### Scenario: 二级菜单页面面包屑
- **WHEN** 已登录用户打开二级菜单页面
- **THEN** header 左侧展示 `一级菜单 > 二级菜单`
#### Scenario: 独立页面面包屑
- **WHEN** 已登录用户打开新增或编辑等独立页面
- **THEN** header 左侧展示 `一级菜单 > 二级菜单 > 独立页面名称`
- **AND** 点击二级菜单面包屑项返回该二级菜单页面
### Requirement: 独立页面页头操作区
岗位 Agent 管理后台 SHALL 为新增、编辑等独立页面提供一致且滚动可见的页头操作区。
#### Scenario: 独立页面不展示右侧取消按钮
- **WHEN** 已登录用户打开新增或编辑等独立页面
- **THEN** 独立页面页头左侧展示 `返回` 入口
- **AND** 独立页面页头右侧展示 `保存` 主操作
- **AND** 独立页面页头右侧不展示 `取消` 按钮
#### Scenario: 滚动时保持页头操作区可见
- **WHEN** 已登录用户在新增或编辑等独立页面向下滚动表单内容
- **THEN** 独立页面页头操作区保持在内容滚动容器顶部可见
- **AND** `返回` 和 `保存` 入口保持可点击
- **AND** 滚动内容不得覆盖页头操作区
# business-table Specification
## Purpose
TBD - created by archiving change extract-business-table-component. Update Purpose after archive.
## Requirements
### Requirement: 配置化业务表格渲染
系统 SHALL 在 `@gl/business-components` 提供 `BusinessTable` 组件,允许页面通过 TDesign 兼容的列配置、数据、行键、状态布尔值和恢复动作渲染业务表格。
#### Scenario: 渲染表格数据
- **WHEN** 页面向 `BusinessTable` 传入 `columns`、`data` 和 `rowKey`
- **THEN** 系统 SHALL 使用 TDesign `Table` 渲染对应表头和行数据
#### Scenario: 兼容 TDesign 列配置
- **WHEN** 页面传入 TDesign `PrimaryTableCol<T>` 兼容的列配置
- **THEN** 系统 SHALL 保留列标题、字段映射、自定义渲染和操作列能力
### Requirement: 普通空态
系统 SHALL 在无错误、非加载、无数据且无筛选条件时展示普通空态。
#### Scenario: 无筛选条件且无数据
- **WHEN** `error` 不为 `true`、`loading` 不为 `true`、`data` 为空且 `hasFilter` 不为 `true`
- **THEN** 系统 SHALL 使用 TDesign 自带状态类型的 `Empty` 组件展示普通空态图标和标题“暂无数据”
- **AND** 系统 SHALL NOT 默认展示补充说明文案
#### Scenario: 普通空态无操作
- **WHEN** 系统展示普通空态
- **THEN** 系统 SHALL NOT 默认展示操作按钮
### Requirement: 筛选空态
系统 SHALL 在无错误、非加载、无数据且存在筛选条件时展示筛选空态。
#### Scenario: 筛选无结果
- **WHEN** `error` 不为 `true`、`loading` 不为 `true`、`data` 为空且 `hasFilter` 为 `true`
- **THEN** 系统 SHALL 使用搜索语义图标展示标题“未找到匹配结果”
- **AND** 系统 SHALL 展示浅色说明文案“请调整搜索或筛选条件”
- **AND** 系统 SHALL NOT 展示“暂无数据”
#### Scenario: 清空筛选操作
- **WHEN** 筛选空态配置提供清空筛选回调
- **THEN** 系统 SHALL 展示文案为“清空筛选”的 TDesign primary 实色按钮
#### Scenario: 触发清空筛选
- **WHEN** 用户点击筛选空态中的“清空筛选”按钮
- **THEN** 系统 SHALL 调用筛选空态配置提供的清空筛选回调
#### Scenario: 页面不传筛选空态文案
- **WHEN** 页面使用 `BusinessTable` 展示筛选空态
- **THEN** 页面 SHALL 仅通过 `hasFilter` 表达筛选状态,并 MAY 通过 `filteredEmptyState.onAction` 提供清空筛选回调
- **AND** 页面 SHALL NOT 传入筛选空态的 `title`、`description` 或 `actionText`
### Requirement: 加载失败态
系统 SHALL 在表格加载失败或不可访问时展示错误状态块,并提供可恢复操作。
#### Scenario: 展示网络不可用
- **WHEN** `error` 为 `true`
- **THEN** 系统 SHALL 不渲染表格主体,并使用 TDesign 自带错误状态图标展示标题“网络不可用”
- **AND** 系统 SHALL 展示浅色说明文案“请检查网络连接后重试”
- **AND** 页面 SHALL NOT 传入加载失败态的 `title`、`description` 或 `retryText`
#### Scenario: 重试操作
- **WHEN** 网络不可用态配置提供重试回调
- **THEN** 系统 SHALL 展示文案为“重试”的 TDesign primary 实色按钮
#### Scenario: 触发重试
- **WHEN** 用户点击网络不可用态中的“重试”按钮
- **THEN** 系统 SHALL 调用加载失败态配置提供的重试回调
#### Scenario: 展示权限受限
- **WHEN** `error` 为 `true` 且 `errorState.kind` 为 `forbidden`
- **THEN** 系统 SHALL 不渲染表格主体,并展示权限受限语义图标和标题“权限受限”
- **AND** 系统 SHALL 展示浅色说明文案“当前账号暂无访问权限”
#### Scenario: 申请权限操作
- **WHEN** 权限受限态配置提供重试回调
- **THEN** 系统 SHALL 展示文案为“申请权限”的 TDesign primary 实色按钮
#### Scenario: 触发申请权限
- **WHEN** 用户点击权限受限态中的“申请权限”按钮
- **THEN** 系统 SHALL 调用加载失败态配置提供的重试回调
### Requirement: TDesign Table 属性透传
系统 SHALL 支持将未被 `BusinessTable` 接管的 TDesign `Table` 属性透传给内部 `Table`。
#### Scenario: 透传展示属性
- **WHEN** 页面向 `BusinessTable` 传入 TDesign `Table` 的展示属性
- **THEN** 系统 SHALL 将该属性应用到内部 TDesign `Table`
#### Scenario: 透传交互属性
- **WHEN** 页面向 `BusinessTable` 传入 TDesign `Table` 的选择、排序、行样式或事件回调属性
- **THEN** 系统 SHALL 将该属性传递给内部 TDesign `Table` 并保留对应交互能力
### Requirement: 操作项按钮样式统一
系统 SHALL 在使用 `BusinessTable` 的列表页中,将表格操作列中的操作项按钮统一渲染为 TDesign primary 文字按钮。
#### Scenario: 渲染操作列按钮
- **WHEN** 页面在表格操作列中渲染行级操作按钮
- **THEN** 系统 SHALL 使用 `theme="primary"` 且 `variant="text"` 的按钮样式
### Requirement: 可选分页和总数展示
系统 SHALL 支持在业务表格底部渲染可选分页或总数信息。
#### Scenario: 渲染分页
- **WHEN** 页面传入分页配置
- **THEN** 系统 SHALL 使用 TDesign `Pagination` 渲染当前页、页大小、总数和分页回调
#### Scenario: 禁用分页
- **WHEN** 页面传入 `pagination={false}`
- **THEN** 系统 SHALL NOT 渲染分页组件
#### Scenario: 展示总数文案
- **WHEN** 页面传入 `totalLabel`
- **THEN** 系统 SHALL 在表格底部展示该总数文案
### Requirement: 空态视觉位置
系统 SHALL 在表格空态展示时保持更居中的视觉位置,避免内容紧贴表头。
#### Scenario: 空态垂直居中
- **WHEN** `BusinessTable` 展示普通空态、筛选空态或加载失败态
- **THEN** 系统 SHALL 使用足够的垂直空间和居中布局展示图标、标题、浅色说明和可选操作按钮,使其不显得贴近表头
### Requirement: 后台列表页迁移
系统 SHALL 将当前后台列表页迁移为使用 `BusinessTable` 渲染表格状态和分页区域。
#### Scenario: 列表页使用业务表格
- **WHEN** 迁移 `AgentListPage`、`AgentTagListPage`、`ChannelCodeListPage`、`OfficialSiteJobTabListPage`、`SkillListPage` 和 `OfficialSiteAgentDisplayConfigPage`
- **THEN** 这些页面 SHALL 使用 `BusinessTable` 承接表格、空态、失败态和分页展示
#### Scenario: 保持业务行为
- **WHEN** 页面迁移到 `BusinessTable`
- **THEN** 系统 SHALL 保持现有查询、重置、分页、弹窗和行操作行为不变
# global-search-filter Specification
## Purpose
TBD - created by archiving change global-search-filter-component. Update Purpose after archive.
## Requirements
### Requirement: 配置化渲染搜索字段
系统 SHALL 提供全局 `SearchFilter` 组件,并 SHALL 根据字段配置渲染搜索区域。
#### Scenario: 渲染输入框字段
- **WHEN** 字段配置包含 `type: "input"`、`label`、`value` 和变更回调
- **THEN** 组件展示一个左右结构的搜索项,左侧为标签,右侧为输入框
#### Scenario: 渲染仅数字输入框字段
- **WHEN** 字段配置包含 `type: "numberInput"`、`label`、`value` 和变更回调
- **THEN** 组件展示一个左右结构的搜索项,左侧为标签,右侧为仅允许输入数字的输入框
#### Scenario: 渲染下拉框字段
- **WHEN** 字段配置包含 `type: "select"` 与选项列表
- **THEN** 组件展示一个左右结构的搜索项,左侧为标签,右侧为下拉框
#### Scenario: 渲染单日期字段
- **WHEN** 字段配置包含 `type: "datePicker"` 且未配置 `range: true`
- **THEN** 组件展示一个左右结构的搜索项,左侧为标签,右侧为单日期选择器
#### Scenario: 渲染范围日期字段
- **WHEN** 字段配置包含 `type: "datePicker"` 且配置 `range: true`
- **THEN** 组件展示一个左右结构的搜索项,左侧为标签,右侧为范围日期选择器
### Requirement: 数字输入限制
系统 SHALL 支持仅数字输入框字段,并 SHALL 阻止非数字内容进入该字段值。
#### Scenario: 输入数字
- **WHEN** 用户在 `numberInput` 字段中输入数字字符
- **THEN** 组件保留该数字输入并触发字段变更回调
#### Scenario: 输入非数字
- **WHEN** 用户在 `numberInput` 字段中输入非数字字符
- **THEN** 组件过滤非数字字符,并仅以过滤后的数字内容触发字段变更回调
### Requirement: 输入框默认占位文案
系统 SHALL 为输入类字段提供默认占位文案,并 SHALL 允许字段配置显式覆盖默认文案。
#### Scenario: 普通输入框默认占位文案
- **WHEN** 字段配置包含 `type: "input"`、`label: "项目名称"` 且未配置 `placeholder`
- **THEN** 组件展示输入框占位文案为“搜索项目名称”
#### Scenario: 数字输入框默认占位文案
- **WHEN** 字段配置包含 `type: "numberInput"` 且未配置 `placeholder`
- **THEN** 组件展示输入框占位文案为“请输入数字”
#### Scenario: 显式占位文案优先
- **WHEN** 输入类字段配置显式传入 `placeholder`
- **THEN** 组件展示显式传入的占位文案
### Requirement: 下拉框全部选项
系统 SHALL 为所有 `select` 字段统一提供“全部”选项,并 SHALL 在字段未传入明确值时默认选中“全部”。
#### Scenario: 自动添加全部选项
- **WHEN** 字段配置包含 `type: "select"` 且业务选项未包含“全部”
- **THEN** 组件在下拉选项中展示“全部”选项
#### Scenario: 避免重复全部选项
- **WHEN** 字段配置包含 `type: "select"` 且业务选项已包含与组件默认“全部”相同值的选项
- **THEN** 组件不重复添加第二个“全部”选项
#### Scenario: 默认选中全部
- **WHEN** `select` 字段的 `value` 为 `undefined`、`null` 或空字符串
- **THEN** 组件展示“全部”为当前选中项
### Requirement: 搜索字段布局宽度
系统 SHALL 统一搜索字段布局宽度,普通字段控件固定为 `200px`,范围日期字段 SHALL 占满两项宽度。
#### Scenario: 普通控件宽度固定
- **WHEN** 组件渲染输入框、仅数字输入框、下拉框或单日期字段
- **THEN** 对应控件的可视宽度为 `200px`
#### Scenario: 范围日期跨两项宽度
- **WHEN** 组件渲染 `range: true` 的日期字段
- **THEN** 范围日期字段占据两个普通搜索项的横向空间
### Requirement: 操作按钮固定在右下角
系统 SHALL 在搜索区域右下角固定展示搜索与重置按钮,并 SHALL 保证搜索与重置按钮不被折叠隐藏。
#### Scenario: 折叠状态展示操作按钮
- **WHEN** 搜索字段数量超过默认展示区域且组件处于折叠状态
- **THEN** 搜索与重置按钮仍展示在搜索区域右下角
#### Scenario: 展开状态展示操作按钮
- **WHEN** 用户展开搜索区域
- **THEN** 搜索与重置按钮仍展示在搜索区域右下角
#### Scenario: 触发搜索和重置回调
- **WHEN** 用户点击搜索或重置按钮
- **THEN** 组件分别调用传入的搜索或重置回调
### Requirement: 最多两行默认展示
系统 SHALL 默认最多展示两行搜索区域内容,且 SHALL 将操作按钮所在区域计入两行展示高度。
#### Scenario: 字段未超过两行
- **WHEN** 字段数量在默认两行内可完整展示
- **THEN** 组件不展示展开/收起按钮
#### Scenario: 字段超过两行
- **WHEN** 字段数量超过默认两行可展示范围
- **THEN** 组件折叠状态仅展示前两行范围内内容,并展示展开按钮
### Requirement: 展开收起交互
系统 SHALL 在字段超过默认展示区域时提供展开/收起文字按钮,按钮 SHALL 位于搜索与重置按钮左侧,并 SHALL 使用文字与箭头表达当前操作。
#### Scenario: 折叠状态展示展开按钮
- **WHEN** 组件处于折叠状态且存在溢出字段
- **THEN** 操作区在搜索与重置按钮左侧展示“展开”文字按钮和向下箭头
#### Scenario: 展开状态展示收起按钮
- **WHEN** 用户点击展开按钮后
- **THEN** 组件展示全部搜索字段,并在搜索与重置按钮左侧展示“收起”文字按钮和向上箭头
#### Scenario: 展开收起具有动画
- **WHEN** 用户切换展开或收起状态
- **THEN** 搜索字段内容区域以平滑动画过渡到目标高度
### Requirement: Demo 展示组件能力
系统 SHALL 在 demo 中展示 `SearchFilter` 组件,并 SHALL 提供超过两行的配置项用于验证折叠与展开效果。
#### Scenario: Demo 包含多类型字段
- **WHEN** 用户打开组件 demo
- **THEN** demo 展示输入框、仅数字输入框、下拉框、单日期和范围日期配置项
#### Scenario: Demo 可验证展开收起
- **WHEN** 用户打开组件 demo
- **THEN** demo 的字段数量超过默认两行可展示范围,并可通过展开/收起按钮查看动画效果
### Requirement: 业务列表页搜索区迁移
系统 SHALL 使用 `SearchFilter` 替换当前已有列表页搜索区域,并 SHALL 保持既有查询参数、分页重置和列表请求语义。
#### Scenario: Agent 管理搜索区迁移
- **WHEN** 用户打开 Agent 管理列表页
- **THEN** 搜索区使用 `SearchFilter` 渲染 `Agent名称` 输入框、`所属岗位` 下拉框和 `状态` 下拉框
- **AND** `Agent名称` 默认占位文案为“搜索Agent名称”
- **AND** 两个下拉框默认展示组件提供的“全部”选项
#### Scenario: Skill 目录搜索区迁移
- **WHEN** 用户打开 Skill 目录列表页
- **THEN** 搜索区使用 `SearchFilter` 渲染 `关键词` 输入框
- **AND** 输入框显式占位文案为“搜索Skill名称或编码”
#### Scenario: 渠道活码管理搜索区迁移
- **WHEN** 用户打开渠道活码管理列表页
- **THEN** 搜索区使用 `SearchFilter` 渲染 `活码名称` 输入框和 `状态` 下拉框
- **AND** `活码名称` 默认占位文案为“搜索活码名称”
- **AND** `状态` 下拉框默认展示组件提供的“全部”选项
#### Scenario: 岗位标签管理搜索区迁移
- **WHEN** 用户打开岗位标签管理列表页
- **THEN** 搜索区使用 `SearchFilter` 渲染 `标签名称` 输入框
- **AND** `标签名称` 默认占位文案为“搜索标签名称”
#### Scenario: 官网岗位展示配置搜索区迁移
- **WHEN** 用户打开官网岗位展示配置列表页
- **THEN** 搜索区使用 `SearchFilter` 渲染 `关键词` 输入框和 `展示状态` 下拉框
- **AND** 输入框显式占位文案为“搜索岗位名称或渠道活码”
- **AND** `展示状态` 下拉框默认展示组件提供的“全部”选项
#### Scenario: 搜索提交保持页面查询语义
- **WHEN** 用户在迁移后的任一列表页修改搜索条件并点击搜索
- **THEN** 页面按原查询参数语义提交筛选条件
- **AND** 分页重置到第一页
#### Scenario: 重置保持页面查询语义
- **WHEN** 用户在迁移后的任一列表页点击重置
- **THEN** 页面清空对应筛选条件并按原查询参数语义刷新列表
# ui-component-library Specification
## Purpose
TBD - created by archiving change migrate-textarea-to-tdesign. Update Purpose after archive.
## Requirements
### Requirement: 页面级多行输入组件
官网岗位 Tab 编辑页和组件库 Demo 页 SHALL 使用 TDesign 多行输入组件承载页面级多行输入,不再直接渲染或展示非 TDesign Textarea。
#### Scenario: Official site job tab editor uses TDesign Textarea
- **WHEN** a user opens the official site job tab editor
- **THEN** the job description field SHALL render with `tdesign-react` Textarea behavior and styling
- **AND** the page SHALL NOT render a raw native `<textarea>` for that field
#### Scenario: Components demo uses TDesign Textarea
- **WHEN** a user opens the component demo page
- **THEN** the remark textarea example SHALL render with `tdesign-react` Textarea behavior and styling
- **AND** the demo SHALL NOT use `packages/ui/Textarea` for that example
#### Scenario: Job description editing remains available
- **WHEN** a user edits the job description field
- **THEN** the page SHALL update `sub_title` with the next string value
- **AND** saving SHALL continue to submit the edited value
#### Scenario: Job description count display remains available
- **WHEN** the job description field has a maximum length
- **THEN** the field SHALL show a current length and maximum length indicator
...@@ -7,7 +7,9 @@ ...@@ -7,7 +7,9 @@
"dev": "vite", "dev": "vite",
"build": "tsc -b && vite build", "build": "tsc -b && vite build",
"build:test": "tsc -b && vite build --mode test", "build:test": "tsc -b && vite build --mode test",
"check:local-ui-runtime-deps": "node scripts/check-local-ui-runtime-deps.mjs --enforce",
"preview": "vite preview", "preview": "vite preview",
"scan:local-ui-runtime-deps": "node scripts/check-local-ui-runtime-deps.mjs",
"test": "vitest run", "test": "vitest run",
"test:watch": "vitest", "test:watch": "vitest",
"typecheck": "tsc -b" "typecheck": "tsc -b"
......
.root {
display: grid;
width: 100%;
gap: var(--gl-spacing-md);
}
.fieldWidth {
width: 100%;
}
.fieldWidth[data-width='360'] {
max-width: 360px;
}
.fieldWidth[data-width='420'] {
max-width: 420px;
}
.fieldWidth[data-width='450'] {
max-width: 450px;
}
.fieldWidth[data-width] {
box-sizing: border-box;
}
.count {
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-xs);
line-height: 18px;
}
.displayText {
min-height: var(--gl-control-height-md);
padding-top: 2px;
color: var(--gl-color-text-primary);
font-size: var(--gl-font-size-sm);
line-height: var(--gl-line-height-md);
}
.readonlyPill {
display: inline-flex;
min-height: var(--gl-control-height-md);
align-items: center;
padding: 0 var(--gl-spacing-sm);
border: 1px solid var(--gl-color-border-secondary);
border-radius: var(--gl-radius-sm);
background: var(--gl-color-bg-container);
color: var(--gl-color-text-primary);
}
.uploadBox {
display: grid;
gap: var(--gl-spacing-sm);
}
.uploadPreview {
display: grid;
gap: var(--gl-spacing-xs);
padding: var(--gl-spacing-sm);
border: 1px solid var(--gl-color-border-secondary);
border-radius: var(--gl-radius-sm);
background: var(--gl-color-bg-container);
}
.uploadMedia {
display: block;
width: 100%;
max-width: 320px;
max-height: 220px;
border-radius: 8px;
object-fit: cover;
}
.uploadVideo {
width: 100%;
max-width: 320px;
max-height: 220px;
border-radius: 8px;
background: #000;
}
.uploadName {
color: var(--gl-color-text-primary);
font-size: var(--gl-font-size-sm);
line-height: var(--gl-line-height-md);
word-break: break-all;
}
.uploadMeta {
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-xs);
line-height: 18px;
}
.uploadActions {
display: flex;
flex-wrap: wrap;
gap: var(--gl-spacing-sm);
}
.uploadButton {
display: inline-flex;
min-height: var(--gl-control-height-md);
align-items: center;
justify-content: center;
padding: 0 var(--gl-spacing-md);
border: 1px solid var(--gl-color-border-primary);
border-radius: var(--gl-radius-sm);
background: var(--gl-color-bg-container);
color: var(--gl-color-text-primary);
cursor: pointer;
}
.uploadButton:disabled {
cursor: not-allowed;
opacity: 0.6;
}
.hiddenInput {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
clip-path: inset(50%);
white-space: nowrap;
}
import { useEffect, useId, useMemo, useRef, useState } from 'react'; import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react';
import type { ButtonHTMLAttributes } from 'react'; import { createPortal } from 'react-dom';
import type { ButtonHTMLAttributes, CSSProperties, RefObject } from 'react';
import styles from './Shared.module.css'; import styles from './Shared.module.css';
import { Icon } from './Icon'; import { Icon } from './Icon';
...@@ -65,14 +66,49 @@ function useExclusiveDatePopup(setOpen: (open: boolean) => void) { ...@@ -65,14 +66,49 @@ function useExclusiveDatePopup(setOpen: (open: boolean) => void) {
return id; return id;
} }
function useFloatingDatePopupPosition(open: boolean, rootRef: RefObject<HTMLSpanElement | null>) {
const [popupStyle, setPopupStyle] = useState<CSSProperties>();
useLayoutEffect(() => {
if (!open) return undefined;
const updatePopupPosition = () => {
const root = rootRef.current;
if (!root) return;
const rect = root.getBoundingClientRect();
setPopupStyle({
position: 'fixed',
top: rect.bottom + 4,
left: rect.left,
minWidth: rect.width,
});
};
updatePopupPosition();
window.addEventListener('resize', updatePopupPosition);
window.addEventListener('scroll', updatePopupPosition, true);
return () => {
window.removeEventListener('resize', updatePopupPosition);
window.removeEventListener('scroll', updatePopupPosition, true);
};
}, [open, rootRef]);
return popupStyle;
}
function useCloseDatePopupOnOutsideClick(open: boolean, setOpen: (open: boolean) => void) { function useCloseDatePopupOnOutsideClick(open: boolean, setOpen: (open: boolean) => void) {
const rootRef = useRef<HTMLSpanElement>(null); const rootRef = useRef<HTMLSpanElement>(null);
const popupRef = useRef<HTMLDivElement>(null);
useEffect(() => { useEffect(() => {
if (!open) return undefined; if (!open) return undefined;
const closeOnOutsideClick = (event: MouseEvent | PointerEvent) => { const closeOnOutsideClick = (event: MouseEvent | PointerEvent) => {
if (!rootRef.current?.contains(event.target as Node)) { const target = event.target as Node;
const isInsideTrigger = rootRef.current?.contains(target);
const isInsidePopup = popupRef.current?.contains(target);
if (!isInsideTrigger && !isInsidePopup) {
// 延迟关闭,确保 click 事件先触发完成(mousedown 在 click 之前) // 延迟关闭,确保 click 事件先触发完成(mousedown 在 click 之前)
setTimeout(() => setOpen(false), 0); setTimeout(() => setOpen(false), 0);
} }
...@@ -83,7 +119,7 @@ function useCloseDatePopupOnOutsideClick(open: boolean, setOpen: (open: boolean) ...@@ -83,7 +119,7 @@ function useCloseDatePopupOnOutsideClick(open: boolean, setOpen: (open: boolean)
return () => document.removeEventListener('mousedown', closeOnOutsideClick); return () => document.removeEventListener('mousedown', closeOnOutsideClick);
}, [open, setOpen]); }, [open, setOpen]);
return rootRef; return { rootRef, popupRef };
} }
export interface DatePickerProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onChange' | 'value'> { export interface DatePickerProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onChange' | 'value'> {
...@@ -97,7 +133,8 @@ export interface DatePickerProps extends Omit<ButtonHTMLAttributes<HTMLButtonEle ...@@ -97,7 +133,8 @@ export interface DatePickerProps extends Omit<ButtonHTMLAttributes<HTMLButtonEle
export function DatePicker({ value, placeholder = '请选择日期', disabledDate, onChange, ...props }: DatePickerProps) { export function DatePicker({ value, placeholder = '请选择日期', disabledDate, onChange, ...props }: DatePickerProps) {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const popupId = useExclusiveDatePopup(setOpen); const popupId = useExclusiveDatePopup(setOpen);
const rootRef = useCloseDatePopupOnOutsideClick(open, setOpen); const { rootRef, popupRef } = useCloseDatePopupOnOutsideClick(open, setOpen);
const popupStyle = useFloatingDatePopupPosition(open, rootRef);
const [innerValue, setInnerValue] = useState(value); const [innerValue, setInnerValue] = useState(value);
const currentValue = value ?? innerValue; const currentValue = value ?? innerValue;
const [displayMonth, setDisplayMonth] = useState(() => parseDate(currentValue)); const [displayMonth, setDisplayMonth] = useState(() => parseDate(currentValue));
...@@ -122,8 +159,8 @@ export function DatePicker({ value, placeholder = '请选择日期', disabledDat ...@@ -122,8 +159,8 @@ export function DatePicker({ value, placeholder = '请选择日期', disabledDat
<button {...props} className={cx(styles.control, styles.fieldButton)} type="button" onClick={toggleOpen}> <button {...props} className={cx(styles.control, styles.fieldButton)} type="button" onClick={toggleOpen}>
{props['aria-label'] ? `${props['aria-label']} ${currentValue ?? placeholder}` : currentValue ?? placeholder} {props['aria-label'] ? `${props['aria-label']} ${currentValue ?? placeholder}` : currentValue ?? placeholder}
</button> </button>
{open ? ( {open ? createPortal(
<div className={cx(styles.popup, styles.datePopup)}> <div ref={popupRef} className={cx(styles.popup, styles.datePopup)} style={popupStyle}>
<div className={styles.dateHeader}> <div className={styles.dateHeader}>
<button className={styles.plainButton} type="button" aria-label="上个月" onClick={() => setDisplayMonth(new Date(displayMonth.getFullYear(), displayMonth.getMonth() - 1, 1))}> <button className={styles.plainButton} type="button" aria-label="上个月" onClick={() => setDisplayMonth(new Date(displayMonth.getFullYear(), displayMonth.getMonth() - 1, 1))}>
<Icon name="chevron-left" /> <Icon name="chevron-left" />
...@@ -162,7 +199,8 @@ export function DatePicker({ value, placeholder = '请选择日期', disabledDat ...@@ -162,7 +199,8 @@ export function DatePicker({ value, placeholder = '请选择日期', disabledDat
<div className={cx(styles.row, styles.dateFooter)}> <div className={cx(styles.row, styles.dateFooter)}>
<button className={styles.dateTodayButton} type="button" onClick={() => commit(today)}>今天</button> <button className={styles.dateTodayButton} type="button" onClick={() => commit(today)}>今天</button>
</div> </div>
</div> </div>,
document.body,
) : null} ) : null}
</span> </span>
); );
...@@ -176,7 +214,8 @@ export interface DateRangePickerProps extends Omit<DatePickerProps, 'onChange' | ...@@ -176,7 +214,8 @@ export interface DateRangePickerProps extends Omit<DatePickerProps, 'onChange' |
export function DateRangePicker({ value, placeholder = '请选择日期范围', disabledDate, onChange, ...props }: DateRangePickerProps) { export function DateRangePicker({ value, placeholder = '请选择日期范围', disabledDate, onChange, ...props }: DateRangePickerProps) {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const popupId = useExclusiveDatePopup(setOpen); const popupId = useExclusiveDatePopup(setOpen);
const rootRef = useCloseDatePopupOnOutsideClick(open, setOpen); const { rootRef, popupRef } = useCloseDatePopupOnOutsideClick(open, setOpen);
const popupStyle = useFloatingDatePopupPosition(open, rootRef);
const [draftStart, setDraftStart] = useState<string | undefined>(); const [draftStart, setDraftStart] = useState<string | undefined>();
const [innerValue, setInnerValue] = useState<[string, string] | undefined>(value); const [innerValue, setInnerValue] = useState<[string, string] | undefined>(value);
const currentValue = value ?? innerValue; const currentValue = value ?? innerValue;
...@@ -197,8 +236,8 @@ export function DateRangePicker({ value, placeholder = '请选择日期范围', ...@@ -197,8 +236,8 @@ export function DateRangePicker({ value, placeholder = '请选择日期范围',
<button {...props} className={cx(styles.control, styles.fieldButton)} type="button" onClick={toggleOpen}> <button {...props} className={cx(styles.control, styles.fieldButton)} type="button" onClick={toggleOpen}>
{props['aria-label'] ? `${props['aria-label']} ${currentValue?.join(' ~ ') ?? placeholder}` : currentValue?.join(' ~ ') ?? placeholder} {props['aria-label'] ? `${props['aria-label']} ${currentValue?.join(' ~ ') ?? placeholder}` : currentValue?.join(' ~ ') ?? placeholder}
</button> </button>
{open ? ( {open ? createPortal(
<div className={cx(styles.popup, styles.datePopup)}> <div ref={popupRef} className={cx(styles.popup, styles.datePopup)} style={popupStyle}>
<div className={styles.dateHeader}> <div className={styles.dateHeader}>
<button className={styles.plainButton} type="button" aria-label="上个月" onClick={() => setDisplayMonth(new Date(displayMonth.getFullYear(), displayMonth.getMonth() - 1, 1))}> <button className={styles.plainButton} type="button" aria-label="上个月" onClick={() => setDisplayMonth(new Date(displayMonth.getFullYear(), displayMonth.getMonth() - 1, 1))}>
<Icon name="chevron-left" /> <Icon name="chevron-left" />
...@@ -252,7 +291,8 @@ export function DateRangePicker({ value, placeholder = '请选择日期范围', ...@@ -252,7 +291,8 @@ export function DateRangePicker({ value, placeholder = '请选择日期范围',
); );
})} })}
</div> </div>
</div> </div>,
document.body,
) : null} ) : null}
</span> </span>
); );
......
.root {
display: grid;
gap: var(--gl-spacing-md);
}
.viewport {
overflow: hidden;
transition: max-height 240ms ease;
will-change: max-height;
}
.fields {
display: flex;
flex-wrap: wrap;
gap: var(--gl-spacing-md) var(--gl-spacing-lg);
align-items: flex-start;
}
.item {
box-sizing: border-box;
display: flex;
align-items: center;
gap: var(--gl-spacing-sm);
width: var(--gl-search-item-width, 284px);
min-width: 0;
}
.itemWide {
width: var(--gl-search-item-wide-width, 484px);
}
.label {
flex: 0 0 var(--gl-search-label-width, 72px);
min-width: 0;
overflow: hidden;
color: var(--gl-color-text-secondary);
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--gl-font-size-sm);
line-height: var(--gl-line-height-md);
}
.control {
flex: 0 0 auto;
width: var(--gl-search-control-width, 200px);
min-width: 0;
}
.controlWide {
width: var(--gl-search-control-wide-width, 400px);
}
.footer {
display: flex;
align-items: center;
justify-content: flex-end;
gap: var(--gl-spacing-sm);
}
.toggleButton {
display: inline-flex;
align-items: center;
gap: var(--gl-spacing-xs);
}
.toggleIcon {
transition: transform 240ms ease;
}
.toggleIconExpanded {
transform: rotate(180deg);
}
.searchButton,
.resetButton {
min-width: 88px;
}
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { Button } from './Button';
import { DatePicker, DateRangePicker } from './DatePicker';
import { Icon } from './Icon';
import { Input } from './Input';
import { Select } from './Select';
import type { SelectOption } from './Select';
import { cx } from './utils';
import styles from './SearchFilter.module.css';
export type SearchFilterValue = string | [string, string] | undefined;
export type SearchFilterValues = Record<string, SearchFilterValue>;
interface SearchFilterFieldBase {
key: string;
label: string;
disabled?: boolean;
}
export interface SearchFilterInputField extends SearchFilterFieldBase {
type: 'input';
value?: string;
defaultValue?: string;
placeholder?: string;
allowClear?: boolean;
onChange?: (value: string) => void;
}
export interface SearchFilterNumberInputField extends SearchFilterFieldBase {
type: 'numberInput';
value?: string;
defaultValue?: string;
placeholder?: string;
allowClear?: boolean;
onChange?: (value: string) => void;
}
export interface SearchFilterSelectField extends SearchFilterFieldBase {
type: 'select';
options: SelectOption[];
value?: string;
defaultValue?: string;
placeholder?: string;
allowClear?: boolean;
onChange?: (value: string) => void;
}
export interface SearchFilterDateField extends SearchFilterFieldBase {
type: 'datePicker';
range?: boolean;
value?: string | [string, string];
defaultValue?: string | [string, string];
placeholder?: string;
disabledDate?: (date: string) => boolean;
onChange?: (value: string | [string, string]) => void;
}
export type SearchFilterField =
| SearchFilterInputField
| SearchFilterNumberInputField
| SearchFilterSelectField
| SearchFilterDateField;
export interface SearchFilterProps {
fields: SearchFilterField[];
className?: string;
'data-testid'?: string;
onSearch?: (values: SearchFilterValues) => void;
onReset?: () => void;
}
function sanitizeDigits(value: string | undefined) {
return (value ?? '').replace(/\D/g, '');
}
function isControlledField(field: SearchFilterField) {
return Object.prototype.hasOwnProperty.call(field, 'value');
}
function defaultValueForField(field: SearchFilterField): SearchFilterValue {
switch (field.type) {
case 'select':
return field.defaultValue ?? '';
case 'datePicker':
return field.defaultValue;
case 'numberInput':
return sanitizeDigits(field.defaultValue);
case 'input':
default:
return field.defaultValue ?? '';
}
}
function normalizeFieldValue(field: SearchFilterField, value: SearchFilterValue): SearchFilterValue {
switch (field.type) {
case 'select':
return typeof value === 'string' ? value : '';
case 'datePicker':
return value;
case 'numberInput':
return sanitizeDigits(typeof value === 'string' ? value : undefined);
case 'input':
default:
return typeof value === 'string' ? value : '';
}
}
function getCurrentValue(field: SearchFilterField, innerValues: SearchFilterValues): SearchFilterValue {
if (isControlledField(field)) {
return normalizeFieldValue(field, field.value);
}
return innerValues[field.key];
}
function buildInitialValues(fields: SearchFilterField[]) {
return fields.reduce<SearchFilterValues>((acc, field) => {
acc[field.key] = defaultValueForField(field);
return acc;
}, {});
}
function getRowWeight(field: SearchFilterField) {
return field.type === 'datePicker' && field.range ? 2 : 1;
}
const ROW_CAPACITY_UNITS = 3;
function getRenderedOptions(options: SelectOption[]) {
const hasAllOption = options.some((option) => option.value === '');
return hasAllOption ? options : [{ label: '全部', value: '' }, ...options];
}
function SearchFieldControl({ field, value, onChange, onEnter }: {
field: SearchFilterField;
value: SearchFilterValue;
onChange: (nextValue: SearchFilterValue) => void;
onEnter?: () => void;
}) {
if (field.type === 'select') {
const renderedOptions = getRenderedOptions(field.options);
return (
<Select
aria-label={field.label}
allowClear={field.allowClear}
className={styles.control}
disabled={field.disabled}
options={renderedOptions}
placeholder={field.placeholder ?? '请选择'}
value={typeof value === 'string' ? value : ''}
onChange={(nextValue) => onChange(nextValue ?? '')}
/>
);
}
if (field.type === 'datePicker') {
if (field.range || Array.isArray(value)) {
return (
<DateRangePicker
aria-label={field.label}
disabled={field.disabled}
disabledDate={field.disabledDate}
placeholder={field.placeholder ?? '请选择日期范围'}
style={{ width: '400px' }}
value={Array.isArray(value) ? value : undefined}
onChange={(nextValue) => onChange(nextValue)}
/>
);
}
return (
<DatePicker
aria-label={field.label}
disabled={field.disabled}
disabledDate={field.disabledDate}
placeholder={field.placeholder ?? '请选择日期'}
style={{ width: '200px' }}
value={typeof value === 'string' ? value : undefined}
onChange={(nextValue) => onChange(nextValue)}
/>
);
}
const isNumberInput = field.type === 'numberInput';
return (
<Input
aria-label={field.label}
allowClear={field.allowClear}
className={styles.control}
disabled={field.disabled}
inputMode={isNumberInput ? 'numeric' : undefined}
pattern={isNumberInput ? '[0-9]*' : undefined}
placeholder={field.placeholder ?? (isNumberInput ? '请输入数字' : `搜索${field.label}`)}
value={typeof value === 'string' ? value : ''}
onChange={(nextValue) => onChange(isNumberInput ? sanitizeDigits(nextValue) : nextValue)}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
onEnter?.();
}
}}
/>
);
}
export function SearchFilter({ fields, className, 'data-testid': dataTestId, onReset, onSearch }: SearchFilterProps) {
const [innerValues, setInnerValues] = useState<SearchFilterValues>(() => buildInitialValues(fields));
const [expanded, setExpanded] = useState(false);
const viewportRef = useRef<HTMLDivElement>(null);
const [viewportHeight, setViewportHeight] = useState<number>(44);
const [collapsedHeight, setCollapsedHeight] = useState<number>(44);
const fieldSignature = useMemo(
() => fields.map((field) => `${field.key}:${field.type}:${field.type === 'datePicker' && field.range ? 'range' : 'single'}`).join('|'),
[fields],
);
useEffect(() => {
setInnerValues((current) => {
const next = { ...current };
fields.forEach((field) => {
if (!(field.key in next)) {
next[field.key] = defaultValueForField(field);
}
});
Object.keys(next).forEach((key) => {
if (!fields.some((field) => field.key === key)) {
delete next[key];
}
});
return next;
});
}, [fieldSignature]);
useLayoutEffect(() => {
const updateHeight = () => {
const viewport = viewportRef.current;
if (!viewport) return;
const fullHeight = viewport.scrollHeight;
const firstItem = viewport.querySelector('[data-field-key]') as HTMLElement | null;
const firstRowHeight = firstItem
? firstItem.getBoundingClientRect().height
: 44;
setCollapsedHeight(Math.max(firstRowHeight, 44));
setViewportHeight(fullHeight);
};
updateHeight();
window.addEventListener('resize', updateHeight);
return () => window.removeEventListener('resize', updateHeight);
}, [expanded, fieldSignature]);
const visibleRows = fields.reduce<number>((count, field) => count + getRowWeight(field), 0);
const showToggle = visibleRows > ROW_CAPACITY_UNITS;
const values = fields.reduce<SearchFilterValues>((acc, field) => {
acc[field.key] = getCurrentValue(field, innerValues);
return acc;
}, {});
const handleSearch = () => onSearch?.(values);
const updateFieldValue = (field: SearchFilterField, nextValue: SearchFilterValue) => {
const normalized = normalizeFieldValue(field, nextValue);
if (!isControlledField(field)) {
setInnerValues((current) => ({
...current,
[field.key]: normalized,
}));
}
field.onChange?.(normalized as never);
};
const handleReset = () => {
const nextValues = buildInitialValues(fields);
setInnerValues(nextValues);
fields.forEach((field) => {
field.onChange?.(nextValues[field.key] as never);
});
onReset?.();
};
return (
<div className={cx(styles.root, className)} data-testid={dataTestId}>
<div
ref={viewportRef}
className={styles.viewport}
style={{ maxHeight: expanded ? viewportHeight : collapsedHeight }}
>
<div className={styles.fields}>
{fields.map((field) => {
const currentValue = values[field.key];
const isWide = field.type === 'datePicker' && field.range;
return (
<div
key={field.key}
className={cx(styles.item, isWide && styles.itemWide)}
data-field-key={field.key}
>
<span className={styles.label} title={field.label}>{field.label}</span>
<div className={cx(styles.control, isWide && styles.controlWide)}>
<SearchFieldControl
field={field}
value={currentValue}
onEnter={handleSearch}
onChange={(nextValue) => updateFieldValue(field, nextValue)}
/>
</div>
</div>
);
})}
</div>
</div>
<div className={styles.footer}>
{showToggle ? (
<Button
className={styles.toggleButton}
variant="text"
onClick={() => setExpanded((nextExpanded) => !nextExpanded)}
>
{expanded ? '收起' : '展开'}
<Icon
className={cx(styles.toggleIcon, expanded && styles.toggleIconExpanded)}
name="chevron-down"
/>
</Button>
) : null}
<Button
className={styles.resetButton}
icon={<Icon name="refresh" size={14} />}
variant="outline"
onClick={handleReset}
>
重置
</Button>
<Button
className={styles.searchButton}
icon={<Icon name="search" size={14} />}
variant="primary"
onClick={handleSearch}
>
搜索
</Button>
</div>
</div>
);
}
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { useState } from 'react';
import {
BusinessForm,
type BusinessFormChangeKeyContext,
validateBusinessForm,
type BusinessFormField,
type BusinessFormValues,
} from '@gl/business-components';
const baseFields: BusinessFormField[] = [
{ key: 'title', label: '名称', type: 'input', required: true, maxLength: 10 },
{ key: 'amount', label: '数量', type: 'numberInput', min: 1, max: 10, precision: 2 },
{
key: 'status',
label: '状态',
type: 'select',
options: [
{ label: '启用', value: 'enabled' },
{ label: '停用', value: 'disabled' },
],
},
{ key: 'enabled', label: '开关', type: 'switch' },
{ key: 'remark', label: '备注', type: 'textarea', maxLength: 20 },
{
key: 'file',
label: '附件',
type: 'upload',
kinds: ['image', 'video', 'file', 'gif'],
accept: '.png,.mp4,.pdf',
maxSize: 1024 * 1024,
upload: vi.fn(async () => ({ url: '/uploaded/demo.png' })),
},
{ key: 'summary', label: '说明', type: 'displayText' },
{
key: 'custom',
label: '自定义',
type: 'custom',
render: ({ setValue }) => (
<button type="button" onClick={() => setValue('patched')}>
自定义操作
</button>
),
},
];
function Harness({
initialValues,
fields = baseFields,
onChange = vi.fn(),
}: {
fields?: BusinessFormField[];
initialValues: BusinessFormValues;
onChange?: (values: BusinessFormValues, changedKey?: string | BusinessFormChangeKeyContext) => void;
}) {
const [values, setValues] = useState<BusinessFormValues>(initialValues);
return (
<BusinessForm
fields={fields}
values={values}
onChange={(nextValues, changedKey) => {
setValues(nextValues);
onChange(nextValues, typeof changedKey === 'string' ? changedKey : changedKey?.key);
}}
/>
);
}
describe('BusinessForm', () => {
it('renders built-in fields, display text, custom fields and consistent widths', () => {
const onChange = vi.fn();
render(
<BusinessForm
fields={baseFields}
values={{
title: '合同',
amount: 2,
status: 'enabled',
enabled: true,
remark: '已填写',
file: { name: 'demo.png', url: '/demo.png', kind: 'image' },
summary: undefined,
custom: 'custom-value',
}}
onChange={onChange}
fieldWidth={360}
/>,
);
expect(screen.getByLabelText('名称')).toHaveValue('合同');
expect(screen.getByLabelText('备注')).toHaveValue('已填写');
expect(screen.getByText('-')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '自定义操作' })).toBeInTheDocument();
expect(screen.getByTestId('business-form-field-title')).toHaveAttribute('data-width', '360');
expect(screen.getByTestId('business-form-field-remark')).toHaveAttribute('data-width', '360');
expect(screen.getByTestId('business-form-field-status')).toHaveAttribute('data-width', '360');
});
it('emits field changes with patches and changed key', () => {
const onChange = vi.fn();
render(
<Harness
initialValues={{
title: '初始标题',
amount: 1,
status: 'enabled',
enabled: false,
remark: '',
file: undefined,
summary: undefined,
custom: '',
}}
onChange={onChange}
/>,
);
fireEvent.change(screen.getByLabelText('名称'), { target: { value: '新标题' } });
fireEvent.click(screen.getByRole('button', { name: '自定义操作' }));
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ title: '新标题', custom: 'patched' }), 'title');
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ custom: 'patched' }), 'custom');
});
it('recomputes visible, disabled and readonly states from current values', () => {
const fields: BusinessFormField[] = [
{ key: 'toggle', label: '开关', type: 'switch' },
{
key: 'target',
label: '联动输入',
type: 'input',
disabled: (values) => values.toggle !== true,
},
{
key: 'readonlyText',
label: '只读展示',
type: 'displayText',
visible: (values) => values.toggle === true,
},
];
render(
<Harness
fields={fields}
initialValues={{ toggle: false, target: 'hello', readonlyText: '可见' }}
/>,
);
expect(screen.queryByText('可见')).not.toBeInTheDocument();
expect(screen.getByLabelText('联动输入')).toBeDisabled();
fireEvent.click(screen.getByRole('switch', { name: '开关' }));
expect(screen.getByText('可见')).toBeInTheDocument();
expect(screen.getByLabelText('联动输入')).not.toBeDisabled();
});
it('validates required, max length, number range, precision and custom validator while skipping readonly and hidden fields', async () => {
const fields: BusinessFormField[] = [
{ key: 'title', label: '名称', type: 'input', required: true, maxLength: 3 },
{ key: 'count', label: '数量', type: 'numberInput', min: 2, max: 5, precision: 1 },
{ key: 'readonlyField', label: '只读', type: 'input', readonly: true, required: true },
{ key: 'hiddenField', label: '隐藏', type: 'input', visible: false, required: true },
{ key: 'summary', label: '说明', type: 'displayText', required: true },
{
key: 'custom',
label: '校验',
type: 'input',
validator: async (value) => (value === 'ok' ? undefined : '自定义校验失败'),
},
];
await expect(validateBusinessForm(fields, {
title: '超长名称',
count: 1.23,
readonlyField: '',
hiddenField: '',
summary: '',
custom: 'bad',
})).resolves.toEqual({
title: '最多 3 个字符',
count: '不能低于 2',
custom: '自定义校验失败',
});
});
it('supports input and textarea count display and over-max input', () => {
render(
<BusinessForm
fields={[
{ key: 'title', label: '名称', type: 'input', maxLength: 4, allowInputOverMax: true },
{ key: 'remark', label: '备注', type: 'textarea', maxLength: 5, allowInputOverMax: true },
]}
values={{ title: '', remark: '' }}
onChange={vi.fn()}
/>,
);
fireEvent.change(screen.getByLabelText('名称'), { target: { value: '超出长度' } });
fireEvent.change(screen.getByLabelText('备注'), { target: { value: '超出长度内容' } });
expect(screen.getByText('4/4')).toBeInTheDocument();
expect(screen.getAllByText((_, element) => element?.textContent?.replace(/\s+/g, '') === '6/5').length).toBeGreaterThan(0);
expect(screen.getByLabelText('名称')).toHaveValue('超出长度');
expect(screen.getByLabelText('备注')).toHaveValue('超出长度内容');
});
it('supports select readonly native props and switch value mapping', () => {
const onChange = vi.fn();
render(
<Harness
initialValues={{ mode: 'enabled', active: 'on' }}
fields={[
{
key: 'mode',
label: '状态',
type: 'select',
readonly: true,
options: [
{ label: '启用', value: 'enabled' },
{ label: '停用', value: 'disabled', disabled: true },
],
},
{
key: 'active',
label: '启停',
type: 'switch',
checkedValue: 'on',
uncheckedValue: 'off',
},
]}
onChange={onChange}
/>,
);
expect(screen.getByRole('combobox', { name: '状态' })).toHaveTextContent('启用');
expect(screen.getByRole('combobox', { name: '状态' })).toHaveAttribute('aria-expanded', 'false');
fireEvent.click(screen.getByRole('switch', { name: '启停' }));
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ active: 'off' }), 'active');
});
it('uploads valid files and preserves previous value on failure', async () => {
const upload = vi.fn(async (file: File) => ({ url: `/files/${file.name}` }));
const failedUpload = vi.fn(async () => {
throw new Error('上传失败');
});
render(
<BusinessForm
fields={[
{
key: 'file',
label: '附件',
type: 'upload',
kinds: ['image'],
accept: '.png',
maxSize: 1024 * 1024,
upload,
},
]}
values={{ file: { name: 'old.png', url: '/old.png', kind: 'image' } }}
onChange={vi.fn()}
/>,
);
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(fileInput, { target: { files: [new File(['ok'], 'demo.png', { type: 'image/png' })] } });
await waitFor(() => {
expect(upload).toHaveBeenCalledTimes(1);
expect(screen.getByText('demo.png')).toBeInTheDocument();
});
render(
<BusinessForm
fields={[
{
key: 'file',
label: '附件',
type: 'upload',
kinds: ['image'],
accept: '.png',
maxSize: 1024 * 1024,
upload: failedUpload,
},
]}
values={{ file: { name: 'old.png', url: '/old.png', kind: 'image' } }}
onChange={vi.fn()}
/>,
);
const failedField = screen.getAllByTestId('business-form-field-file')[1];
const failedInput = failedField.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(failedInput, { target: { files: [new File(['ok'], 'bad.png', { type: 'image/png' })] } });
await waitFor(() => {
expect(failedUpload).toHaveBeenCalledTimes(1);
expect(screen.getByRole('alert')).toHaveTextContent('上传失败,请重试');
expect(screen.getByText('old.png')).toBeInTheDocument();
});
});
});
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { SearchFilter } from '../index';
describe('SearchFilter', () => {
it('renders default select all option and keeps number inputs digits only', () => {
const onSearch = vi.fn();
render(
<SearchFilter
fields={[
{ key: 'keyword', label: '关键词', type: 'input', defaultValue: '合同' },
{ key: 'count', label: '数量', type: 'numberInput' },
{
key: 'status',
label: '状态',
type: 'select',
options: [{ label: '启用', value: 'enabled' }],
},
]}
onSearch={onSearch}
/>,
);
fireEvent.change(screen.getByLabelText('数量'), { target: { value: '12a3' } });
fireEvent.click(screen.getByRole('button', { name: '搜索' }));
expect(screen.getByLabelText('数量')).toHaveValue('123');
expect(onSearch).toHaveBeenCalledWith({
keyword: '合同',
count: '123',
status: '',
});
});
it('uses default placeholders for input and number input while preserving explicit placeholders', () => {
render(
<SearchFilter
fields={[
{ key: 'keyword', label: '项目名称', type: 'input' },
{ key: 'code', label: '项目编号', type: 'numberInput' },
{ key: 'owner', label: '负责人', type: 'input', placeholder: '搜索负责人姓名' },
]}
/>,
);
expect(screen.getByLabelText('项目名称')).toHaveAttribute('placeholder', '搜索项目名称');
expect(screen.getByLabelText('项目编号')).toHaveAttribute('placeholder', '请输入数字');
expect(screen.getByLabelText('负责人')).toHaveAttribute('placeholder', '搜索负责人姓名');
});
it('shows expand and collapse controls when the configured fields exceed one visible row', () => {
render(
<SearchFilter
fields={[
{ key: 'keyword', label: '关键词', type: 'input' },
{ key: 'code', label: '编号', type: 'numberInput' },
{
key: 'status',
label: '状态',
type: 'select',
options: [{ label: '启用', value: 'enabled' }],
},
{ key: 'owner', label: '负责人', type: 'input' },
{ key: 'createdAt', label: '创建日期', type: 'datePicker' },
{ key: 'period', label: '时间范围', type: 'datePicker', range: true },
]}
/>,
);
expect(screen.getByRole('button', { name: '展开' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '搜索' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '重置' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '展开' }));
expect(screen.getByRole('button', { name: '收起' })).toBeInTheDocument();
});
it('resets field values and calls the reset callback', () => {
const onReset = vi.fn();
render(
<SearchFilter
fields={[
{ key: 'keyword', label: '关键词', type: 'input', defaultValue: '项目' },
{
key: 'status',
label: '状态',
type: 'select',
options: [{ label: '启用', value: 'enabled' }],
defaultValue: 'enabled',
},
]}
onReset={onReset}
/>,
);
fireEvent.change(screen.getByLabelText('关键词'), { target: { value: '合同' } });
fireEvent.click(screen.getByRole('button', { name: '重置' }));
expect(onReset).toHaveBeenCalledTimes(1);
expect(screen.getByLabelText('关键词')).toHaveValue('项目');
});
});
...@@ -18,6 +18,12 @@ function currentDateId() { ...@@ -18,6 +18,12 @@ function currentDateId() {
return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`; return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
} }
function currentMonthOtherDateId() {
const today = new Date();
const day = today.getDate() === 1 ? 2 : 1;
return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
}
function getSelectTrigger(name: string) { function getSelectTrigger(name: string) {
return screen.getByRole('combobox', { name }); return screen.getByRole('combobox', { name });
} }
...@@ -69,7 +75,7 @@ describe('selection, date, table and pagination components', () => { ...@@ -69,7 +75,7 @@ describe('selection, date, table and pagination components', () => {
it('keeps the clear affordance hidden when allowClear is disabled', () => { it('keeps the clear affordance hidden when allowClear is disabled', () => {
render(<Select aria-label="负责人" value="zhang" options={[{ label: '张三', value: 'zhang' }]} />); render(<Select aria-label="负责人" value="zhang" options={[{ label: '张三', value: 'zhang' }]} />);
expect(screen.getByDisplayValue('张三')).toBeInTheDocument(); expect(getSelectRoot('负责人')).toHaveTextContent('张三');
expect(document.querySelector('.t-input__suffix-clear')).not.toBeInTheDocument(); expect(document.querySelector('.t-input__suffix-clear')).not.toBeInTheDocument();
}); });
...@@ -346,10 +352,10 @@ describe('selection, date, table and pagination components', () => { ...@@ -346,10 +352,10 @@ describe('selection, date, table and pagination components', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.queryByRole('list')).not.toBeInTheDocument(); expect(screen.queryByRole('list')).not.toBeInTheDocument();
}); });
expect(screen.getByDisplayValue('客服岗')).toBeInTheDocument(); expect(getSelectRoot('所属岗位')).toHaveTextContent('客服岗');
}); });
it('resets to the placeholder when a controlled select clears its value', () => { it('resets to the placeholder when a controlled select clears its value', async () => {
function ControlledSelect() { function ControlledSelect() {
const [value, setValue] = useState<string | undefined>(); const [value, setValue] = useState<string | undefined>();
...@@ -376,11 +382,13 @@ describe('selection, date, table and pagination components', () => { ...@@ -376,11 +382,13 @@ describe('selection, date, table and pagination components', () => {
fireEvent.click(getSelectTrigger('所属岗位')); fireEvent.click(getSelectTrigger('所属岗位'));
fireEvent.click(getSelectOption('客服岗')); fireEvent.click(getSelectOption('客服岗'));
expect(screen.getByDisplayValue('客服岗')).toBeInTheDocument(); expect(getSelectRoot('所属岗位')).toHaveTextContent('客服岗');
fireEvent.click(screen.getByRole('button', { name: '重置' })); fireEvent.click(screen.getByRole('button', { name: '重置' }));
expect(screen.getByPlaceholderText('全部')).toBeInTheDocument(); await waitFor(() => {
expect(screen.getByPlaceholderText('全部')).toBeInTheDocument();
});
}); });
it('collapses an expanded TreeSelect parent when clicking it again', () => { it('collapses an expanded TreeSelect parent when clicking it again', () => {
...@@ -459,11 +467,12 @@ describe('selection, date, table and pagination components', () => { ...@@ -459,11 +467,12 @@ describe('selection, date, table and pagination components', () => {
it('marks selected and today dates with separate visual state classes', () => { it('marks selected and today dates with separate visual state classes', () => {
const today = currentDateId(); const today = currentDateId();
render(<DatePicker aria-label="生效日期" value="2026-05-11" />); const selectedDate = currentMonthOtherDateId();
render(<DatePicker aria-label="生效日期" value={selectedDate} />);
fireEvent.click(screen.getByRole('button', { name: /生效日期/ })); fireEvent.click(screen.getByRole('button', { name: /生效日期/ }));
const selectedDay = screen.getByRole('gridcell', { name: '2026-05-11' }); const selectedDay = screen.getByRole('gridcell', { name: selectedDate });
const todayDay = screen.getByRole('gridcell', { name: today }); const todayDay = screen.getByRole('gridcell', { name: today });
expect(selectedDay).toHaveClass(sharedStyles.dateSelected); expect(selectedDay).toHaveClass(sharedStyles.dateSelected);
...@@ -550,6 +559,21 @@ describe('selection, date, table and pagination components', () => { ...@@ -550,6 +559,21 @@ describe('selection, date, table and pagination components', () => {
expect(screen.getByRole('heading', { name: '2026年 5月' }).closest(`.${sharedStyles.datePopup}`)).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '2026年 5月' }).closest(`.${sharedStyles.datePopup}`)).toBeInTheDocument();
}); });
it('renders date popups outside clipped containers', () => {
render(
<div style={{ maxHeight: 40, overflow: 'hidden' }}>
<DatePicker aria-label="创建日期" value="2026-05-16" />
</div>,
);
fireEvent.click(screen.getByRole('button', { name: /创建日期/ }));
const popup = screen.getByRole('heading', { name: '2026年 5月' }).closest(`.${sharedStyles.datePopup}`);
expect(popup).toBeInTheDocument();
expect(popup?.parentElement).toBe(document.body);
expect(popup).toHaveStyle({ position: 'fixed' });
});
it('closes date popups when clicking outside while keeping inside controls interactive', async () => { it('closes date popups when clicking outside while keeping inside controls interactive', async () => {
render( render(
<div> <div>
......
...@@ -24,6 +24,8 @@ export type { RadioProps } from './components/Radio'; ...@@ -24,6 +24,8 @@ export type { RadioProps } from './components/Radio';
export { Radio } from './components/Radio'; export { Radio } from './components/Radio';
export type { SelectOption, SelectProps } from './components/Select'; export type { SelectOption, SelectProps } from './components/Select';
export { Select } from './components/Select'; export { Select } from './components/Select';
export type { SearchFilterDateField, SearchFilterField, SearchFilterInputField, SearchFilterNumberInputField, SearchFilterProps, SearchFilterSelectField, SearchFilterValue, SearchFilterValues } from './components/SearchFilter';
export { SearchFilter } from './components/SearchFilter';
export type { SwitchProps } from './components/Switch'; export type { SwitchProps } from './components/Switch';
export { Switch } from './components/Switch'; export { Switch } from './components/Switch';
export type { TableColumn, TableProps } from './components/Table'; export type { TableColumn, TableProps } from './components/Table';
......
import { readdir, readFile } from 'node:fs/promises';
import { extname, relative, resolve } from 'node:path';
import ts from 'typescript';
const sourceRoot = resolve('src');
const supportedExtensions = new Set(['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx']);
const enforce = process.argv.includes('--enforce');
async function collectSourceFiles(directory) {
const entries = await readdir(directory, { withFileTypes: true });
const files = await Promise.all(entries.map(async (entry) => {
const path = resolve(directory, entry.name);
if (entry.isDirectory()) return collectSourceFiles(path);
if (!supportedExtensions.has(extname(entry.name)) || /\.test\.[^.]+$/.test(entry.name)) return [];
return [path];
}));
return files.flat();
}
const files = await collectSourceFiles(sourceRoot);
const matches = [];
for (const file of files) {
const source = await readFile(file, 'utf8');
const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
const addMatch = (moduleSpecifier) => {
if (!ts.isStringLiteralLike(moduleSpecifier) || !moduleSpecifier.text.includes('packages/ui')) return;
const { line } = sourceFile.getLineAndCharacterOfPosition(moduleSpecifier.getStart(sourceFile));
matches.push({
file: relative(process.cwd(), file),
line: line + 1,
specifier: moduleSpecifier.text,
});
};
const visit = (node) => {
if (ts.isImportDeclaration(node)) {
const importClause = node.importClause;
const namedBindings = importClause?.namedBindings;
const hasOnlyTypeSpecifiers = namedBindings
&& ts.isNamedImports(namedBindings)
&& namedBindings.elements.length > 0
&& namedBindings.elements.every((specifier) => specifier.isTypeOnly);
if (!importClause?.isTypeOnly && !hasOnlyTypeSpecifiers) addMatch(node.moduleSpecifier);
} else if (ts.isExportDeclaration(node) && !node.isTypeOnly && node.moduleSpecifier) {
addMatch(node.moduleSpecifier);
} else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
addMatch(node.arguments[0]);
}
ts.forEachChild(node, visit);
};
visit(sourceFile);
}
console.log(`本地 packages/ui 运行时 import:${matches.length} 条,涉及 ${new Set(matches.map((match) => match.file)).size} 个文件。`);
for (const match of matches) {
console.log(`${match.file}:${match.line} -> ${match.specifier}`);
}
if (enforce && matches.length > 0) {
console.error('检测失败:web/src 仍存在指向 packages/ui 的运行时 import。');
process.exitCode = 1;
}
import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
...@@ -12,6 +12,7 @@ vi.mock('./api/agent', () => ({ ...@@ -12,6 +12,7 @@ vi.mock('./api/agent', () => ({
updateAgentStatus: vi.fn(), updateAgentStatus: vi.fn(),
createAgent: vi.fn(), createAgent: vi.fn(),
updateAgent: vi.fn(), updateAgent: vi.fn(),
getEmployeeMounts: vi.fn(() => Promise.resolve({ employee_count: 0, employees: [] })),
})); }));
const loginStorageKey = 'agent-admin-local-login'; const loginStorageKey = 'agent-admin-local-login';
...@@ -24,24 +25,36 @@ function renderApp(path: string) { ...@@ -24,24 +25,36 @@ function renderApp(path: string) {
); );
} }
function getLoginInput(name: 'username' | 'password') {
const input = document.querySelector<HTMLInputElement>(`input[name="${name}"]`);
if (!input) {
throw new Error(`Login input ${name} was not found`);
}
return input;
}
describe('App foundation', () => { describe('App foundation', () => {
beforeEach(() => { beforeEach(() => {
window.localStorage.clear(); window.localStorage.clear();
vi.clearAllMocks(); vi.clearAllMocks();
}); });
it('renders the root layout for the React application', () => { it('renders the root layout for the React application', async () => {
renderApp('/components'); renderApp('/components');
expect(screen.getByRole('main')).toBeInTheDocument(); await waitFor(() => {
expect(screen.getByRole('main')).toBeInTheDocument();
});
expect(screen.getByText('Agent Admin Web')).toBeInTheDocument(); expect(screen.getByText('Agent Admin Web')).toBeInTheDocument();
}); });
it('renders the independent component demo route', () => { it('renders the independent component demo route', async () => {
renderApp('/components'); renderApp('/components');
expect(screen.getByRole('heading', { name: '组件库 Demo' })).toBeInTheDocument(); await waitFor(() => {
expect(screen.getByText('全局 UI 组件库展示入口')).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '组件库 Demo' })).toBeInTheDocument();
});
expect(screen.getByText('TDesign 基础控件与全局业务组合组件展示入口')).toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Agent管理' })).not.toBeInTheDocument(); expect(screen.queryByRole('heading', { name: 'Agent管理' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '退出登录' })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: '退出登录' })).not.toBeInTheDocument();
}); });
...@@ -58,11 +71,17 @@ describe('Admin login and protected routes', () => { ...@@ -58,11 +71,17 @@ describe('Admin login and protected routes', () => {
renderApp('/agents'); renderApp('/agents');
expect(screen.getByRole('heading', { name: '岗位Agent管理后台' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '岗位Agent管理后台' })).toBeInTheDocument();
expect(screen.getByLabelText('账号')).toBeInTheDocument(); expect(screen.getByText('使用一期固定管理员账号进入本地管理后台')).toBeInTheDocument();
expect(screen.getByLabelText('密码')).toBeInTheDocument(); expect(getLoginInput('username')).toBeInTheDocument();
expect(getLoginInput('password')).toBeInTheDocument();
fireEvent.change(screen.getByLabelText('账号'), { target: { value: 'admin' } }); expect(getLoginInput('username')).toHaveAttribute('placeholder', '请输入账号');
fireEvent.change(screen.getByLabelText('密码'), { target: { value: '123456' } }); expect(getLoginInput('password')).toHaveAttribute('placeholder', '请输入密码');
expect(screen.queryByText('账号')).not.toBeInTheDocument();
expect(screen.queryByText('密码')).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: '显示密码' })).toBeInTheDocument();
fireEvent.change(getLoginInput('username'), { target: { value: 'admin' } });
fireEvent.change(getLoginInput('password'), { target: { value: '123456' } });
fireEvent.click(screen.getByRole('button', { name: '登录' })); fireEvent.click(screen.getByRole('button', { name: '登录' }));
expect(window.localStorage.getItem(loginStorageKey)).toBe('true'); expect(window.localStorage.getItem(loginStorageKey)).toBe('true');
...@@ -73,7 +92,7 @@ describe('Admin login and protected routes', () => { ...@@ -73,7 +92,7 @@ describe('Admin login and protected routes', () => {
expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument(); expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument();
}); });
expect(screen.getByText('岗位Agent管理后台')).toBeInTheDocument(); expect(screen.getByText('岗位Agent管理后台')).toBeInTheDocument();
expect(screen.getByLabelText('管理员')).toBeInTheDocument(); expect(screen.getByLabelText('管理员头像')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '退出登录' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '退出登录' })).toBeInTheDocument();
}); });
...@@ -86,14 +105,27 @@ describe('Admin login and protected routes', () => { ...@@ -86,14 +105,27 @@ describe('Admin login and protected routes', () => {
expect(screen.getByText('请输入密码')).toBeInTheDocument(); expect(screen.getByText('请输入密码')).toBeInTheDocument();
expect(window.localStorage.getItem(loginStorageKey)).toBeNull(); expect(window.localStorage.getItem(loginStorageKey)).toBeNull();
fireEvent.change(screen.getByLabelText('账号'), { target: { value: 'admin' } }); fireEvent.change(getLoginInput('username'), { target: { value: 'admin' } });
fireEvent.change(screen.getByLabelText('密码'), { target: { value: 'wrong' } }); fireEvent.change(getLoginInput('password'), { target: { value: 'wrong' } });
fireEvent.click(screen.getByRole('button', { name: '登录' })); fireEvent.click(screen.getByRole('button', { name: '登录' }));
expect(screen.getByText('账号或密码错误')).toBeInTheDocument(); expect(screen.getByText('账号或密码错误')).toBeInTheDocument();
expect(window.localStorage.getItem(loginStorageKey)).toBeNull(); expect(window.localStorage.getItem(loginStorageKey)).toBeNull();
}); });
it('toggles password visibility from the login password field', () => {
renderApp('/login');
const passwordInput = getLoginInput('password');
expect(passwordInput.type).toBe('password');
fireEvent.click(screen.getByRole('button', { name: '显示密码' }));
expect(passwordInput.type).toBe('text');
expect(screen.getByRole('button', { name: '隐藏密码' })).toBeInTheDocument();
});
it('keeps logged-in users on refresh and clears local state on logout', async () => { it('keeps logged-in users on refresh and clears local state on logout', async () => {
window.localStorage.setItem(loginStorageKey, 'true'); window.localStorage.setItem(loginStorageKey, 'true');
vi.mocked(getAgentList).mockResolvedValue({ list: [], total: 0, page: 1, page_size: 10 }); vi.mocked(getAgentList).mockResolvedValue({ list: [], total: 0, page: 1, page_size: 10 });
...@@ -106,12 +138,14 @@ describe('Admin login and protected routes', () => { ...@@ -106,12 +138,14 @@ describe('Admin login and protected routes', () => {
fireEvent.click(screen.getByRole('button', { name: '退出登录' })); fireEvent.click(screen.getByRole('button', { name: '退出登录' }));
expect(screen.getByRole('dialog', { name: '确认退出登录?' })).toBeInTheDocument(); expect(screen.getByText('确认退出登录?').closest('.t-dialog')).toBeInTheDocument();
expect(window.localStorage.getItem(loginStorageKey)).toBe('true'); expect(window.localStorage.getItem(loginStorageKey)).toBe('true');
fireEvent.click(screen.getByRole('button', { name: '取消' })); fireEvent.click(screen.getByRole('button', { name: '取消' }));
expect(screen.queryByRole('dialog', { name: '确认退出登录?' })).not.toBeInTheDocument(); await waitFor(() => {
expect(screen.queryByText('确认退出登录?')).not.toBeInTheDocument();
});
expect(window.localStorage.getItem(loginStorageKey)).toBe('true'); expect(window.localStorage.getItem(loginStorageKey)).toBe('true');
fireEvent.click(screen.getByRole('button', { name: '退出登录' })); fireEvent.click(screen.getByRole('button', { name: '退出登录' }));
...@@ -128,9 +162,19 @@ describe('Admin login and protected routes', () => { ...@@ -128,9 +162,19 @@ describe('Admin login and protected routes', () => {
renderApp('/agents'); renderApp('/agents');
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('button', { name: 'Agent管理' })).toHaveAttribute('data-active-parent', 'true'); expect(screen.getByLabelText('左侧导航')).toBeInTheDocument();
}); });
expect(screen.getByRole('button', { name: 'Agent列表' })).toHaveAttribute('aria-current', 'page'); const leftNavigation = screen.getByLabelText('左侧导航');
expect(leftNavigation.querySelector('.t-icon-robot')).toBeInTheDocument();
expect(leftNavigation.querySelector('.t-icon-usergroup')).toBeInTheDocument();
expect(leftNavigation.querySelector('.t-icon-setting')).toBeInTheDocument();
expect(within(leftNavigation).getByText('Agent列表').closest('li')).toHaveClass('t-is-active');
fireEvent.click(screen.getByRole('button', { name: '收起菜单' }));
expect(screen.getByRole('button', { name: '展开菜单' })).toBeInTheDocument();
expect(screen.getByLabelText('左侧导航')).toHaveStyle({ width: '64px' });
expect(leftNavigation.querySelector('.t-icon-robot')).toBeInTheDocument();
}); });
it('renders the skill route inside the admin shell navigation', async () => { it('renders the skill route inside the admin shell navigation', async () => {
...@@ -142,8 +186,26 @@ describe('Admin login and protected routes', () => { ...@@ -142,8 +186,26 @@ describe('Admin login and protected routes', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('heading', { name: 'Skill目录' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Skill目录' })).toBeInTheDocument();
}); });
expect(screen.getByRole('button', { name: 'Agent管理' })).toHaveAttribute('data-active-parent', 'true'); expect(within(screen.getByLabelText('左侧导航')).getByText('Skill目录').closest('li')).toHaveClass('t-is-active');
expect(screen.getByRole('button', { name: 'Skill目录' })).toHaveAttribute('aria-current', 'page'); expect(screen.getAllByText('Agent管理').length).toBeGreaterThan(0);
expect(screen.getByText('Agent管理 / Skill目录')).toBeInTheDocument(); expect(screen.getAllByText('Skill目录').length).toBeGreaterThan(0);
});
it('renders independent editor pages with clickable breadcrumbs back to the secondary menu', async () => {
window.localStorage.setItem(loginStorageKey, 'true');
renderApp('/agents/new');
await waitFor(() => {
expect(screen.getByRole('heading', { name: '新建Agent' })).toBeInTheDocument();
});
expect(screen.getByText('新增Agent')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Agent列表' }));
await waitFor(() => {
expect(screen.getByRole('heading', { name: 'Agent管理' })).toBeInTheDocument();
});
}); });
}); });
import { useState } from 'react';
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import {
BusinessForm,
validateBusinessForm,
type BusinessFormField,
type BusinessFormValue,
type BusinessFormValues,
} from '@gl/business-components';
function getSelectTrigger(name: string) {
const field = screen
.getAllByText(name)
.map((element) => element.closest('[data-testid^="business-form-field-"]'))
.find(Boolean);
if (!field) {
throw new Error(`Select field ${name} was not found`);
}
const input = field.querySelector('input[type="text"]');
if (!input) {
throw new Error(`Select input ${name} was not found`);
}
return input as HTMLInputElement;
}
function getSelectOption(name: string) {
const option = screen.getAllByText(name).map((element) => element.closest('li')).find(Boolean);
if (!option) {
throw new Error(`Select option ${name} was not found`);
}
return option as HTMLElement;
}
function getUploadInput(name: string) {
const field = screen.getByTestId(`business-form-field-${name}`);
const input = field.querySelector('input[type="file"]');
if (!input) {
throw new Error(`Upload input ${name} was not found`);
}
return input as HTMLInputElement;
}
function getNumberInput(name: string) {
const field = screen.getByTestId(`business-form-field-${name}`);
const input = field.querySelector('input');
if (!input) {
throw new Error(`Number input ${name} was not found`);
}
return input as HTMLInputElement;
}
function Harness({
fields,
initialValues,
errors,
onChange = vi.fn(),
}: {
fields: Parameters<typeof BusinessForm>[0]['fields'];
initialValues: Parameters<typeof BusinessForm>[0]['values'];
errors?: Parameters<typeof BusinessForm>[0]['errors'];
onChange?: Parameters<typeof BusinessForm>[0]['onChange'];
}) {
const [values, setValues] = useState(initialValues);
return (
<BusinessForm
fields={fields}
errors={errors}
values={values}
onChange={(nextValues, changedKey) => {
setValues(nextValues);
onChange?.(nextValues, changedKey);
}}
/>
);
}
describe('BusinessForm', () => {
it('renders all built-in field types with the current values', () => {
const upload = vi.fn();
render(
<BusinessForm
fields={[
{ key: 'title', label: '名称', type: 'input', required: true, maxLength: 10 },
{ key: 'amount', label: '数量', type: 'numberInput', min: 1, max: 10, precision: 2 },
{
key: 'status',
label: '状态',
type: 'select',
options: [
{ label: '启用', value: 'enabled' },
{ label: '停用', value: 'disabled' },
],
},
{ key: 'enabled', label: '开关', type: 'switch' },
{ key: 'remark', label: '备注', type: 'textarea', maxLength: 20 },
{
key: 'file',
label: '附件',
type: 'upload',
kinds: ['image', 'video', 'file', 'gif'],
accept: '.png,.mp4,.pdf',
maxSize: 1024 * 1024,
upload,
},
{ key: 'summary', label: '说明', type: 'displayText' },
{
key: 'custom',
label: '自定义',
type: 'custom',
render: () => <button type="button">自定义操作</button>,
},
]}
values={{
title: '合同',
amount: 2,
status: 'enabled',
enabled: true,
remark: '已填写',
file: { name: 'demo.png', url: '/demo.png', kind: 'image' },
summary: '说明内容',
custom: 'custom-value',
}}
onChange={vi.fn()}
fieldWidth={360}
/>,
);
expect(screen.getByLabelText('名称')).toHaveValue('合同');
expect(getNumberInput('amount')).toHaveValue('2.00');
expect(getSelectTrigger('状态')).toHaveValue('启用');
expect(screen.getByRole('switch', { name: '开关' })).toBeChecked();
expect(screen.getByLabelText('备注')).toHaveValue('已填写');
expect(screen.getByText('说明内容')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '自定义操作' })).toBeInTheDocument();
expect(screen.getByTestId('business-form-field-title')).toHaveAttribute('data-width', '360');
expect(screen.getByTestId('business-form-field-remark')).toHaveAttribute('data-width', '360');
expect(screen.getByTestId('business-form-field-status')).toHaveAttribute('data-width', '360');
});
it('updates controlled values and emits form-level and field-level patch changes', () => {
const onChange = vi.fn();
const titleChange = vi.fn();
render(
<BusinessForm
fields={[
{
key: 'title',
label: '名称',
type: 'input',
onChange: titleChange,
},
{
key: 'amount',
label: '数量',
type: 'numberInput',
},
]}
values={{
title: '合同',
amount: 1,
}}
onChange={onChange}
/>,
);
fireEvent.change(screen.getByLabelText('名称'), { target: { value: '合同A' } });
fireEvent.change(getNumberInput('amount'), { target: { value: '2' } });
expect(titleChange).toHaveBeenCalledWith('合同A', expect.objectContaining({ key: 'title' }));
expect(onChange).toHaveBeenCalledWith(
expect.objectContaining({
title: '合同A',
amount: 2,
}),
expect.objectContaining({
key: 'title',
value: '合同A',
}),
);
});
it('recomputes visible, disabled, and readonly fields from the latest values', () => {
function Harness() {
const [values, setValues] = useState<BusinessFormValues>({
mode: 'hide',
detail: '详情',
locked: '锁定值',
readonlyNote: '只读值',
});
return (
<BusinessForm
fields={[
{
key: 'mode',
label: '模式',
type: 'input',
},
{
key: 'detail',
label: '详情',
type: 'input',
visible: (currentValues) => currentValues.mode === 'show',
},
{
key: 'locked',
label: '锁定项',
type: 'input',
disabled: (currentValues) => currentValues.mode === 'lock',
},
{
key: 'readonlyNote',
label: '只读项',
type: 'input',
readonly: (currentValues) => currentValues.mode === 'read',
},
]}
values={values}
onChange={(nextValues) => setValues(nextValues)}
/>
);
}
render(<Harness />);
expect(screen.queryByLabelText('详情')).not.toBeInTheDocument();
expect(screen.getByLabelText('锁定项')).not.toBeDisabled();
expect(screen.getByLabelText('只读项')).not.toHaveAttribute('readonly');
fireEvent.change(screen.getByLabelText('模式'), { target: { value: 'show' } });
expect(screen.getByLabelText('详情')).toBeInTheDocument();
fireEvent.change(screen.getByLabelText('模式'), { target: { value: 'lock' } });
expect(screen.getByLabelText('锁定项')).toBeDisabled();
fireEvent.change(screen.getByLabelText('模式'), { target: { value: 'read' } });
expect(screen.getByLabelText('只读项')).toHaveAttribute('readonly');
});
it('validates required, max length, number range, precision, readonly, hidden and custom validator fields', async () => {
const fields: BusinessFormField[] = [
{ key: 'title', label: '名称', type: 'input', required: true, maxLength: 3 },
{ key: 'count', label: '数量', type: 'numberInput', min: 2, max: 5 },
{ key: 'price', label: '单价', type: 'numberInput', precision: 1 },
{ key: 'readonlyField', label: '只读', type: 'input', readonly: true, required: true },
{ key: 'hiddenField', label: '隐藏', type: 'input', visible: false, required: true },
{ key: 'summary', label: '说明', type: 'displayText', required: true },
{
key: 'custom',
label: '校验',
type: 'input',
validator: async (value: BusinessFormValue) => (value === 'ok' ? undefined : '自定义校验失败'),
},
];
await expect(
Promise.resolve(
validateBusinessForm(fields, {
title: '超长名称',
count: 1,
price: 1.23,
readonlyField: '',
hiddenField: '',
summary: '',
custom: 'bad',
}),
),
).resolves.toEqual({
title: '最多 3 个字符',
count: '不能低于 2',
price: '最多保留 1 位小数',
custom: '自定义校验失败',
});
});
it('keeps allowInputOverMax editable and uses native length display for input and textarea', () => {
render(
<BusinessForm
fields={[
{ key: 'title', label: '名称', type: 'input', maxLength: 4, allowInputOverMax: true },
{ key: 'remark', label: '备注', type: 'textarea', maxLength: 5, allowInputOverMax: true },
]}
values={{ title: '', remark: '' }}
onChange={vi.fn()}
/>,
);
fireEvent.change(screen.getByLabelText('名称'), { target: { value: '超出长度啊' } });
fireEvent.change(screen.getByLabelText('备注'), { target: { value: '超出长度内容啊' } });
expect(screen.getByLabelText('名称')).toHaveValue('超出长度啊');
expect(screen.getByLabelText('备注')).toHaveValue('超出长度内容啊');
});
it('keeps input, numberInput, select and textarea at the same default width and syncs fieldWidth to all of them', () => {
const { rerender } = render(
<BusinessForm
fields={[
{ key: 'title', label: '名称', type: 'input' },
{ key: 'amount', label: '数量', type: 'numberInput' },
{
key: 'status',
label: '状态',
type: 'select',
options: [{ label: '启用', value: 'enabled' }],
},
{ key: 'remark', label: '备注', type: 'textarea' },
]}
values={{ title: '', amount: 0, status: 'enabled', remark: '' }}
onChange={vi.fn()}
/>,
);
const defaultWidths = ['title', 'amount', 'status', 'remark'].map((key) =>
screen.getByTestId(`business-form-field-${key}`).getAttribute('data-width'),
);
expect(defaultWidths.every((width) => width !== null)).toBe(true);
expect(new Set(defaultWidths).size).toBe(1);
rerender(
<BusinessForm
fields={[
{ key: 'title', label: '名称', type: 'input' },
{ key: 'amount', label: '数量', type: 'numberInput' },
{
key: 'status',
label: '状态',
type: 'select',
options: [{ label: '启用', value: 'enabled' }],
},
{ key: 'remark', label: '备注', type: 'textarea' },
]}
values={{ title: '', amount: 0, status: 'enabled', remark: '' }}
onChange={vi.fn()}
fieldWidth={420}
/>,
);
expect(screen.getByTestId('business-form-field-title')).toHaveAttribute('data-width', '420');
expect(screen.getByTestId('business-form-field-amount')).toHaveAttribute('data-width', '420');
expect(screen.getByTestId('business-form-field-status')).toHaveAttribute('data-width', '420');
expect(screen.getByTestId('business-form-field-remark')).toHaveAttribute('data-width', '420');
});
it('respects select option disabled, field disabled and readonly native props', () => {
const onChange = vi.fn();
render(
<Harness
initialValues={{
status: 'enabled',
lockedStatus: 'enabled',
readonlyStatus: 'disabled',
}}
fields={[
{
key: 'status',
label: '状态',
type: 'select',
options: [
{ label: '启用', value: 'enabled' },
{ label: '停用', value: 'disabled', disabled: true },
],
},
{
key: 'lockedStatus',
label: '禁用状态',
type: 'select',
disabled: true,
options: [
{ label: '启用', value: 'enabled' },
{ label: '停用', value: 'disabled' },
],
},
{
key: 'readonlyStatus',
label: '只读状态',
type: 'select',
readonly: true,
options: [
{ label: '启用', value: 'enabled' },
{ label: '停用', value: 'disabled' },
],
},
]}
onChange={onChange}
/>,
);
fireEvent.click(getSelectTrigger('状态'));
fireEvent.click(getSelectOption('停用'));
expect(onChange).not.toHaveBeenCalled();
expect(getSelectTrigger('状态')).toHaveValue('启用');
expect(getSelectTrigger('禁用状态')).toBeDisabled();
expect(getSelectTrigger('只读状态')).toHaveValue('停用');
expect(getSelectTrigger('只读状态')).toHaveAttribute('readonly');
});
it('supports boolean switch defaults, mapped values and readonly display', () => {
const onChange = vi.fn();
render(
<Harness
initialValues={{
enabled: false,
mapped: 'off',
readonlySwitch: true,
}}
fields={[
{ key: 'enabled', label: '开关', type: 'switch' },
{ key: 'mapped', label: '映射开关', type: 'switch', checkedValue: 'on', uncheckedValue: 'off' },
{ key: 'readonlySwitch', label: '只读开关', type: 'switch', readonly: true },
]}
onChange={onChange}
/>,
);
expect(screen.getByRole('switch', { name: '开关' })).not.toBeChecked();
fireEvent.click(screen.getByRole('switch', { name: '开关' }));
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ enabled: true }), 'enabled');
fireEvent.click(screen.getByRole('switch', { name: '映射开关' }));
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ mapped: 'on' }), 'mapped');
expect(screen.getByText('已开启')).toBeInTheDocument();
expect(screen.queryByRole('switch', { name: '只读开关' })).not.toBeInTheDocument();
});
it('rejects invalid media uploads, uploads media and file values separately, and renders media cards', async () => {
const upload = vi.fn(async (file: File) => ({ url: `/uploaded/${file.name}` }));
const failedUpload = vi.fn(async () => {
throw new Error('后端拒绝');
});
const onChange = vi.fn();
render(
<BusinessForm
fields={[
{
key: 'invalidMediaUpload',
label: '媒体校验',
type: 'upload',
uploadType: 'media',
kinds: ['image'],
accept: '.png',
maxSize: 1024,
placeholder: '点击上传',
helperText: '支持图片、视频、GIF,推荐 1:1,最大 20MB',
upload,
},
{
key: 'fileUpload',
label: '文件上传',
type: 'upload',
uploadType: 'file',
kinds: ['file'],
accept: '.pdf,.zip',
maxSize: 1024 * 1024,
upload,
},
{
key: 'failedUpload',
label: '上传失败',
type: 'upload',
uploadType: 'media',
kinds: ['image'],
accept: '.png',
maxSize: 1024 * 1024,
upload: failedUpload,
},
]}
values={{
invalidMediaUpload: undefined,
fileUpload: { name: 'manual.pdf', url: '/manual.pdf', kind: 'file' },
failedUpload: { name: 'old.png', url: '/old.png', kind: 'image' },
}}
onChange={onChange}
/>,
);
const failedField = screen.getByTestId('business-form-field-failedUpload');
const invalidMediaField = screen.getByTestId('business-form-field-invalidMediaUpload');
expect(within(invalidMediaField).getByText('点击上传')).toBeInTheDocument();
expect(invalidMediaField.querySelector('.t-upload__card')).toBeInTheDocument();
expect(within(invalidMediaField).getByText('支持图片、视频、GIF,推荐 1:1,最大 20MB')).toBeInTheDocument();
fireEvent.change(getUploadInput('invalidMediaUpload'), {
target: { files: [new File(['demo'], 'demo.txt', { type: 'text/plain' })] },
});
fireEvent.change(getUploadInput('fileUpload'), {
target: { files: [new File(['ok'], 'manual.zip', { type: 'application/zip' })] },
});
fireEvent.change(getUploadInput('failedUpload'), {
target: { files: [new File(['ok'], 'bad.png', { type: 'image/png' })] },
});
await waitFor(() => {
expect(upload).toHaveBeenCalledTimes(1);
expect(failedUpload).toHaveBeenCalledTimes(1);
});
expect(upload).toHaveBeenNthCalledWith(1, expect.any(File), expect.any(Object));
await waitFor(() => expect(screen.getByText(/不支持|格式/)).toBeInTheDocument());
expect(screen.getByText(/后端拒绝|请重试/)).toBeInTheDocument();
expect(screen.getByText('old.png')).toBeInTheDocument();
expect(await screen.findByText('manual.zip')).toBeInTheDocument();
expect(failedField.querySelector('.t-upload__card-mask')).toBeInTheDocument();
expect(failedField.querySelector('.t-icon-browse')).toBeInTheDocument();
const deleteIcon = failedField.querySelector('.t-icon-delete');
expect(deleteIcon).toBeInTheDocument();
fireEvent.click(deleteIcon as Element);
await waitFor(() => expect(screen.queryByText('old.png')).not.toBeInTheDocument());
expect(within(failedField).getByText('点击上传')).toBeInTheDocument();
const mediaUploadCall = onChange.mock.calls.find(([, changedKey]) => changedKey === 'mediaUpload');
expect(mediaUploadCall).toBeUndefined();
});
it('supports configurable multiple media uploads and keeps the value as an uploaded file array', async () => {
const upload = vi.fn(async (file: File) => ({
url: `/uploaded/${file.name}`,
name: file.name,
kind: 'video' as const,
}));
const onChange = vi.fn();
const fields = [
{
key: 'mediaGallery',
label: '素材集合',
type: 'upload',
uploadType: 'media',
kinds: ['image', 'gif', 'video'],
accept: '.png,.gif,.mp4',
maxCount: 3,
multiple: true,
upload,
},
] as BusinessFormField[];
render(
<Harness
fields={fields}
initialValues={{
mediaGallery: [
{ name: 'cover.png', url: '/cover.png', kind: 'image' },
{ name: 'motion.gif', url: '/motion.gif', kind: 'gif' },
] as BusinessFormValues['mediaGallery'],
}}
onChange={onChange}
/>,
);
const mediaField = screen.getByTestId('business-form-field-mediaGallery');
const uploadInput = getUploadInput('mediaGallery');
expect(uploadInput).toHaveAttribute('multiple');
expect(within(mediaField).getByText('cover.png')).toBeInTheDocument();
expect(within(mediaField).getByText('motion.gif')).toBeInTheDocument();
fireEvent.change(uploadInput, {
target: { files: [new File(['demo'], 'clip.mp4', { type: 'video/mp4' })] },
});
await waitFor(() => expect(upload).toHaveBeenCalledTimes(1));
await waitFor(() => expect(within(mediaField).getByText('clip.mp4')).toBeInTheDocument());
const appendCall = onChange.mock.calls.find((call) => {
const nextValue = call[0].mediaGallery;
return Array.isArray(nextValue) && nextValue.length === 3;
});
expect(appendCall).toBeDefined();
expect(appendCall?.[0]).toEqual(
expect.objectContaining({
mediaGallery: [
expect.objectContaining({ name: 'cover.png' }),
expect.objectContaining({ name: 'motion.gif' }),
expect.objectContaining({ name: 'clip.mp4', kind: 'video' }),
],
}),
);
const deleteIcons = mediaField.querySelectorAll('.t-icon-delete');
expect(deleteIcons.length).toBeGreaterThan(0);
fireEvent.click(deleteIcons[0]);
await waitFor(() => expect(within(mediaField).queryByText('cover.png')).not.toBeInTheDocument());
const removeCall = onChange.mock.calls.find((call) => {
const nextValue = call[0].mediaGallery;
return Array.isArray(nextValue) && nextValue.length === 2 && nextValue.every((item) => item?.name !== 'cover.png');
});
expect(removeCall).toBeDefined();
});
it('passes custom field context, supports setValue and setValues, and keeps custom validation tied to current values', async () => {
const renderCustom = vi.fn((context: any) => (
<div>
<div data-testid="custom-summary">
{`value:${String(context.value)}|mode:${String(context.values.mode)}|disabled:${String(context.disabled)}|readonly:${String(context.readonly)}|error:${String(context.error ?? '')}`}
</div>
<button type="button" onClick={() => context.setValue('patched')}>
更新当前字段
</button>
<button
type="button"
onClick={() =>
context.setValues({
...context.values,
mode: 'lock',
note: '联动',
custom: 'batch',
})
}
>
批量更新
</button>
</div>
));
const validator = vi.fn(async (value: string) => (value === 'ok' ? undefined : '自定义字段错误'));
const onChange = vi.fn();
const fields: BusinessFormField[] = [
{ key: 'mode', label: '模式', type: 'input' },
{ key: 'note', label: '备注', type: 'input' },
{
key: 'custom',
label: '自定义',
type: 'custom',
required: true,
validator,
disabled: (currentValues) => currentValues.mode === 'lock',
readonly: (currentValues) => currentValues.mode === 'read',
render: renderCustom,
},
] as Parameters<typeof BusinessForm>[0]['fields'];
render(
<Harness
fields={fields}
initialValues={{
mode: 'edit',
note: '',
custom: 'start',
}}
errors={{ custom: '已有错误' }}
onChange={onChange}
/>,
);
expect(renderCustom).toHaveBeenCalledWith(
expect.objectContaining({
value: 'start',
values: expect.objectContaining({
mode: 'edit',
note: '',
custom: 'start',
}),
disabled: false,
readonly: false,
error: '已有错误',
setValue: expect.any(Function),
setValues: expect.any(Function),
}),
);
expect(screen.getByTestId('custom-summary')).toHaveTextContent('value:start');
expect(screen.getByTestId('custom-summary')).toHaveTextContent('disabled:false');
expect(screen.getByTestId('custom-summary')).toHaveTextContent('readonly:false');
expect(screen.getByTestId('custom-summary')).toHaveTextContent('error:已有错误');
fireEvent.change(screen.getByLabelText('模式'), { target: { value: 'lock' } });
expect(screen.getByTestId('custom-summary')).toHaveTextContent('disabled:true');
fireEvent.change(screen.getByLabelText('模式'), { target: { value: 'read' } });
expect(screen.getByTestId('custom-summary')).toHaveTextContent('readonly:true');
fireEvent.click(screen.getByRole('button', { name: '更新当前字段' }));
expect(onChange).toHaveBeenCalledWith(
expect.objectContaining({
custom: 'patched',
}),
'custom',
);
fireEvent.click(screen.getByRole('button', { name: '批量更新' }));
expect(onChange).toHaveBeenCalledWith(
expect.objectContaining({
mode: 'lock',
note: '联动',
custom: 'batch',
}),
'custom',
);
await expect(
validateBusinessForm(fields, {
mode: 'edit',
note: '',
custom: 'bad',
}),
).resolves.toEqual({
custom: '自定义字段错误',
});
});
});
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { BusinessTable } from '@gl/business-components';
import type { PrimaryTableCol } from 'tdesign-react';
type DemoRow = {
id: number;
name: string;
status: string;
};
const demoColumns: PrimaryTableCol<DemoRow>[] = [
{ title: '名称', colKey: 'name' },
{
title: '状态',
colKey: 'status',
cell: ({ row }) => <span>{row.status}</span>,
},
{
title: '操作',
colKey: 'actions',
cell: ({ row }) => (
<button type="button" onClick={() => undefined}>
编辑{row.name}
</button>
),
},
];
describe('BusinessTable', () => {
it('renders configured columns, data and row actions from config', () => {
const onEdit = vi.fn();
const columns: PrimaryTableCol<DemoRow>[] = [
{ title: '名称', colKey: 'name' },
{
title: '状态',
colKey: 'status',
cell: ({ row }) => <span>{row.status}</span>,
},
{
title: '操作',
colKey: 'actions',
cell: ({ row }) => (
<button type="button" onClick={() => onEdit(row.id)}>
编辑{row.name}
</button>
),
},
];
render(
<BusinessTable
rowKey="id"
columns={columns}
data={[
{ id: 1, name: '示例一', status: '启用' },
{ id: 2, name: '示例二', status: '停用' },
]}
/>,
);
expect(screen.getByRole('columnheader', { name: '名称' })).toBeInTheDocument();
expect(screen.getByRole('columnheader', { name: '状态' })).toBeInTheDocument();
expect(screen.getByRole('columnheader', { name: '操作' })).toBeInTheDocument();
expect(screen.getByText('示例一')).toBeInTheDocument();
expect(screen.getByText('启用')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '编辑示例一' }));
expect(onEdit).toHaveBeenCalledWith(1);
});
it('renders the normal empty state with title and no default action', () => {
render(
<BusinessTable
rowKey="id"
columns={demoColumns}
data={[]}
/>,
);
expect(screen.getByText('暂无数据')).toBeInTheDocument();
expect(screen.queryByText('请先创建项目')).not.toBeInTheDocument();
expect(screen.queryByText('未能查询到符合条件的资源')).not.toBeInTheDocument();
expect(screen.queryByText('未找到匹配结果')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '清空筛选' })).not.toBeInTheDocument();
});
it('renders the filtered empty state without description or clear filter action', () => {
render(
<BusinessTable
rowKey="id"
columns={demoColumns}
data={[]}
hasFilter
filteredEmptyState={{ onAction: vi.fn() }}
/>,
);
expect(screen.getByText('未找到匹配结果')).toBeInTheDocument();
expect(screen.queryByText('请调整搜索或筛选条件')).not.toBeInTheDocument();
expect(screen.queryByText('暂无数据')).not.toBeInTheDocument();
expect(screen.queryByText('未能查询到符合条件的资源')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '清空筛选' })).not.toBeInTheDocument();
});
it('renders the request failure state without retry action', () => {
render(
<BusinessTable
rowKey="id"
columns={demoColumns}
data={[]}
error
errorState={{ onRetry: vi.fn() }}
/>,
);
expect(screen.getByText('请求失败')).toBeInTheDocument();
expect(screen.queryByText('网络不可用')).not.toBeInTheDocument();
expect(screen.queryByText('请检查网络连接后重试')).not.toBeInTheDocument();
expect(screen.queryByText('接口请求失败,请稍后重试')).not.toBeInTheDocument();
expect(screen.queryByText('数据请求失败,请稍后重试')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
expect(screen.queryByRole('button')).not.toBeInTheDocument();
});
it('renders the forbidden state with description and permission action', () => {
const onRequestPermission = vi.fn();
render(
<BusinessTable
rowKey="id"
columns={demoColumns}
data={[]}
error
errorState={{ kind: 'forbidden', onRetry: onRequestPermission }}
/>,
);
expect(screen.getByText('权限受限')).toBeInTheDocument();
expect(screen.getByText('当前账号暂无访问权限')).toBeInTheDocument();
const requestButton = screen.getByRole('button', { name: '申请权限' });
expect(requestButton).toHaveClass('t-button--theme-primary');
expect(requestButton).toHaveClass('t-button--variant-base');
fireEvent.click(requestButton);
expect(onRequestPermission).toHaveBeenCalledTimes(1);
});
it('uses the centered empty-state layout for normal, filtered and failure states', () => {
const { container, rerender } = render(
<BusinessTable
rowKey="id"
columns={demoColumns}
data={[]}
/>,
);
expect(container.querySelector('[class*="emptyState"]')).toBeInTheDocument();
rerender(
<BusinessTable
rowKey="id"
columns={demoColumns}
data={[]}
hasFilter
filteredEmptyState={{ onAction: vi.fn() }}
/>,
);
expect(container.querySelector('[class*="emptyState"]')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: '清空筛选' })).not.toBeInTheDocument();
rerender(
<BusinessTable
rowKey="id"
columns={demoColumns}
data={[]}
error
errorState={{ onRetry: vi.fn() }}
/>,
);
expect(container.querySelector('[class*="emptyState"]')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
});
it('uses the business loading style while preserving the table structure', async () => {
const { container } = render(
<BusinessTable
rowKey="id"
columns={demoColumns}
data={[]}
loading
/>,
);
expect(screen.getByRole('columnheader', { name: '名称' })).toBeInTheDocument();
expect(screen.queryByText('暂无数据')).not.toBeInTheDocument();
await waitFor(() => {
expect(screen.getByText('加载中')).toBeInTheDocument();
});
expect(container.querySelector('[class*="businessTableLoading"]')).toBeInTheDocument();
});
it('passes table display and row interaction props through to TDesign Table', () => {
const onRowClick = vi.fn();
const { container } = render(
<BusinessTable
rowKey="id"
columns={demoColumns}
data={[
{ id: 1, name: '示例一', status: '启用' },
]}
tableClassName="demo-table"
hover
maxHeight={240}
rowClassName={({ row }) => (row.id === 1 ? 'demo-row' : '')}
onRowClick={onRowClick}
/>,
);
expect(container.querySelector('.t-table')).toHaveClass('t-table--hoverable', 'demo-table');
expect(container.querySelector('[style*="max-height"]')).toHaveStyle({ maxHeight: '240px' });
fireEvent.click(screen.getByRole('row', { name: /示例一/ }));
expect(onRowClick).toHaveBeenCalledTimes(1);
expect(screen.getByText('示例一').closest('tr')).toHaveClass('demo-row');
});
it('renders pagination, honors totalLabel and can disable pagination', () => {
const { container, rerender } = render(
<BusinessTable
rowKey="id"
columns={demoColumns}
data={[
{ id: 1, name: '示例一', status: '启用' },
]}
pagination={{ current: 2, pageSize: 10, total: 35 }}
totalLabel="共 35 条"
/>,
);
expect(container.querySelector('.t-pagination')).toBeInTheDocument();
expect(screen.getAllByText('共 35 条数据')).toHaveLength(1);
expect(screen.queryByText('共 35 条')).not.toBeInTheDocument();
rerender(
<BusinessTable
rowKey="id"
columns={demoColumns}
data={[
{ id: 1, name: '示例一', status: '启用' },
]}
pagination={false}
totalLabel="共 35 条"
/>,
);
expect(container.querySelector('.t-pagination')).not.toBeInTheDocument();
expect(screen.getByText('共 35 条')).toBeInTheDocument();
});
});
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { MediaWall, SearchFilter, StatePlaceholder } from '@gl/business-components';
describe('global business components', () => {
it('keeps SearchFilter draft values until search and restores defaults on reset', () => {
const onReset = vi.fn();
const onSearch = vi.fn();
render(
<SearchFilter
fields={[
{ key: 'keyword', label: '关键词', type: 'input', defaultValue: '项目' },
{ key: 'count', label: '数量', type: 'numberInput' },
{ key: 'status', label: '状态', type: 'select', options: [{ label: '启用', value: 'enabled' }] },
]}
onReset={onReset}
onSearch={onSearch}
/>,
);
fireEvent.change(screen.getByLabelText('数量'), { target: { value: '12a3' } });
fireEvent.click(screen.getByRole('button', { name: '搜索' }));
expect(screen.getByLabelText('数量')).toHaveValue('123');
expect(onSearch).toHaveBeenCalledWith({ keyword: '项目', count: '123', status: '' });
fireEvent.change(screen.getByLabelText('关键词'), { target: { value: '合同' } });
fireEvent.click(screen.getByRole('button', { name: '重置' }));
expect(screen.getByLabelText('关键词')).toHaveValue('项目');
expect(onReset).toHaveBeenCalledTimes(1);
});
it('renders an empty range date field without TDesign value warnings', () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
render(
<SearchFilter
fields={[
{ key: 'period', label: '统计周期', type: 'datePicker', range: true },
]}
/>,
);
expect(screen.getAllByLabelText('统计周期')).toHaveLength(2);
expect(consoleError).not.toHaveBeenCalledWith(expect.stringContaining('TDesign DatePicker Error'));
consoleError.mockRestore();
});
it('renders StatePlaceholder semantic roles and actions', () => {
const onRetry = vi.fn();
render(
<>
<StatePlaceholder state="empty" />
<StatePlaceholder state="empty" title="加载中" description="正在加载" />
<StatePlaceholder
state="error"
title="列表加载失败"
description="请稍后重试"
primaryAction={<button type="button" onClick={onRetry}>重新加载</button>}
/>
</>,
);
expect(screen.getByRole('status', { name: '暂无数据' })).toBeInTheDocument();
expect(screen.getByRole('status', { name: '加载中' })).toBeInTheDocument();
expect(screen.getByText('正在加载')).toBeInTheDocument();
expect(screen.getByRole('alert', { name: '列表加载失败' })).toBeInTheDocument();
expect(screen.getByText('请稍后重试')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '重新加载' }));
expect(onRetry).toHaveBeenCalledTimes(1);
});
it('keeps MediaWall upload, preview, remove and hydrated image behavior', async () => {
const onPreview = vi.fn();
const onRemove = vi.fn();
const onSelectFiles = vi.fn();
const image = { id: 'cover', type: 'image' as const, src: '/cover.png', alt: '产品图片' };
const file = new File(['demo'], 'demo.png', { type: 'image/png' });
render(
<MediaWall
items={[image]}
maxCount={2}
onPreview={onPreview}
onRemove={onRemove}
onSelectFiles={onSelectFiles}
/>,
);
expect(document.querySelector(`img[src="${image.src}"]`)).toBeInTheDocument();
fireEvent.click(document.querySelector('.t-icon-browse') as HTMLElement);
fireEvent.click(document.querySelector('.t-icon-delete') as HTMLElement);
expect(onPreview).toHaveBeenCalledWith(image);
expect(onRemove).toHaveBeenCalledWith(image);
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(fileInput, { target: { files: [file] } });
await waitFor(() => {
expect(onSelectFiles).toHaveBeenCalledWith([file]);
});
});
});
import { render, screen } from '@testing-library/react';
import { Form } from 'tdesign-react';
import { describe, expect, it } from 'vitest';
import { FormItem, Input, Switch, Textarea } from './TDesignAccessibleControls';
describe('TDesignAccessibleControls', () => {
it('keeps asynchronously hydrated input and textarea values inside form items', () => {
const { rerender } = render(
<Form>
<FormItem label="名称">
<Input aria-label="名称" value="" onChange={() => undefined} />
</FormItem>
<FormItem label="描述">
<Textarea aria-label="描述" value="" onChange={() => undefined} />
</FormItem>
</Form>,
);
rerender(
<Form>
<FormItem label="名称">
<Input aria-label="名称" value="已回填名称" onChange={() => undefined} />
</FormItem>
<FormItem label="描述">
<Textarea aria-label="描述" value="已回填描述" onChange={() => undefined} />
</FormItem>
</Form>,
);
expect(screen.getByLabelText('名称')).toHaveValue('已回填名称');
expect(screen.getByLabelText('描述')).toHaveValue('已回填描述');
});
it('keeps asynchronously hydrated switch state accessible', () => {
const { rerender } = render(<Switch aria-label="启用状态" value={false} onChange={() => undefined} />);
rerender(<Switch aria-label="启用状态" value onChange={() => undefined} />);
expect(screen.getByRole('switch', { name: '启用状态' })).toHaveAttribute('aria-checked', 'true');
});
});
import { useEffect, useRef } from 'react';
import type { ComponentProps } from 'react';
import {
Form as TDesignForm,
Input as TDesignInput,
Select as TDesignSelect,
Switch as TDesignSwitch,
Textarea as TDesignTextarea,
} from 'tdesign-react';
import type { InputRef } from 'tdesign-react';
type AccessibleInputProps = ComponentProps<typeof TDesignInput> & {
'aria-label'?: string;
};
type AccessibleSelectProps = ComponentProps<typeof TDesignSelect> & {
'aria-label'?: string;
};
type AccessibleSwitchProps = ComponentProps<typeof TDesignSwitch> & {
'aria-label'?: string;
};
type AccessibleTextareaProps = ComponentProps<typeof TDesignTextarea> & {
'aria-label'?: string;
};
type FormItemProps = ComponentProps<typeof TDesignForm.FormItem>;
export function FormItem({ children, ...props }: FormItemProps) {
return (
<TDesignForm.FormItem {...props}>
<>{children}</>
</TDesignForm.FormItem>
);
}
export function Input({ 'aria-label': ariaLabel, ...props }: AccessibleInputProps) {
const inputRef = useRef<InputRef>(null);
useEffect(() => {
if (!inputRef.current?.inputElement || !ariaLabel) return;
inputRef.current.inputElement.setAttribute('aria-label', ariaLabel);
}, [ariaLabel]);
return <TDesignInput {...props} ref={inputRef} />;
}
export function Select({ 'aria-label': ariaLabel, inputProps, ...props }: AccessibleSelectProps) {
const selectRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const ref = selectRef.current as (HTMLDivElement & { currentElement?: HTMLDivElement }) | null;
const root = ref?.currentElement ?? ref;
if (!root || !ariaLabel) return;
root.setAttribute('aria-label', ariaLabel);
root.setAttribute('role', 'combobox');
}, [ariaLabel]);
return (
<TDesignSelect
{...props}
ref={selectRef}
inputProps={{
...inputProps,
...ariaLabel ? { 'aria-label': ariaLabel } : {},
}}
/>
);
}
export function Switch({ 'aria-label': ariaLabel, value, ...props }: AccessibleSwitchProps) {
return (
<TDesignSwitch
{...props}
aria-checked={Boolean(value)}
aria-label={ariaLabel}
value={value}
/>
);
}
export function Textarea({ 'aria-label': ariaLabel, ...props }: AccessibleTextareaProps) {
const textareaRef = useRef<{ currentElement: HTMLDivElement; textareaElement: HTMLTextAreaElement }>(null);
useEffect(() => {
if (!textareaRef.current?.textareaElement || !ariaLabel) return;
textareaRef.current.textareaElement.setAttribute('aria-label', ariaLabel);
}, [ariaLabel]);
return <TDesignTextarea {...props} ref={textareaRef} />;
}
import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { describe, expect, it } from 'vitest'; import { MemoryRouter, Route, Routes, useNavigate } from 'react-router-dom';
import { MemoryRouter, Routes, Route, useNavigate } from 'react-router-dom'; import { beforeEach, describe, expect, it, vi } from 'vitest';
import { MessageProvider, useFlashMessage } from './useMessage'; import { MessageProvider, useFlashMessage } from './useMessage';
import { Button } from '../../packages/ui/src';
const messagePlugin = vi.hoisted(() => ({
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
closeAll: vi.fn(),
}));
vi.mock('tdesign-react', () => ({
MessagePlugin: messagePlugin,
}));
function TestShell({ initialEntries = ['/list'] }: { initialEntries?: string[] }) { function TestShell({ initialEntries = ['/list'] }: { initialEntries?: string[] }) {
return ( return (
...@@ -24,8 +35,8 @@ function ListPage() { ...@@ -24,8 +35,8 @@ function ListPage() {
return ( return (
<div> <div>
<h1>列表页</h1> <h1>列表页</h1>
<Button onClick={() => flash.success('跳转后成功提示')}>模拟跳转成功</Button> <button type="button" onClick={() => flash.success('跳转后成功提示')}>模拟跳转成功</button>
<Button onClick={() => flash.error('跳转后失败提示')}>模拟跳转失败</Button> <button type="button" onClick={() => flash.error('跳转后失败提示')}>模拟跳转失败</button>
</div> </div>
); );
} }
...@@ -33,56 +44,52 @@ function ListPage() { ...@@ -33,56 +44,52 @@ function ListPage() {
function EditPage() { function EditPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const handleSaveAndNavigate = () => { return <button type="button" onClick={() => navigate('/list', { state: { flash: { type: 'success', message: '保存成功' } } })}>保存并返回</button>;
navigate('/list', { state: { flash: { type: 'success', message: '保存成功' } } });
};
return (
<div>
<h1>编辑页</h1>
<Button onClick={handleSaveAndNavigate}>保存并返回</Button>
</div>
);
} }
describe('flash message after navigation', () => { describe('flash message after navigation', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('shows success message after navigating from edit page', async () => { it('shows success message after navigating from edit page', async () => {
render(<TestShell initialEntries={['/edit']} />); render(<TestShell initialEntries={['/edit']} />);
fireEvent.click(screen.getByRole('button', { name: '保存并返回' })); fireEvent.click(screen.getByRole('button', { name: '保存并返回' }));
// Message should appear after navigation await waitFor(() => {
await waitFor( expect(messagePlugin.success).toHaveBeenCalledWith({
() => { content: '保存成功',
expect(screen.getByRole('status', { name: '保存成功' })).toBeInTheDocument(); duration: 3000,
}, closeBtn: false,
{ timeout: 2000 }, placement: 'top-right',
); });
});
}); });
it('uses flash.success to show one-time success message', async () => { it('uses flash.success to show one-time success message', () => {
render(<TestShell />); render(<TestShell />);
fireEvent.click(screen.getByRole('button', { name: '模拟跳转成功' })); fireEvent.click(screen.getByRole('button', { name: '模拟跳转成功' }));
await waitFor( expect(messagePlugin.success).toHaveBeenCalledWith({
() => { content: '跳转后成功提示',
expect(screen.getByRole('status', { name: '跳转后成功提示' })).toBeInTheDocument(); duration: 3000,
}, closeBtn: false,
{ timeout: 2000 }, placement: 'top-right',
); });
}); });
it('uses flash.error to show one-time error message', async () => { it('uses flash.error to show one-time error message', () => {
render(<TestShell />); render(<TestShell />);
fireEvent.click(screen.getByRole('button', { name: '模拟跳转失败' })); fireEvent.click(screen.getByRole('button', { name: '模拟跳转失败' }));
await waitFor( expect(messagePlugin.error).toHaveBeenCalledWith({
() => { content: '跳转后失败提示',
expect(screen.getByRole('alert', { name: '跳转后失败提示' })).toBeInTheDocument(); duration: 3000,
}, closeBtn: false,
{ timeout: 2000 }, placement: 'top-right',
); });
}); });
});
\ No newline at end of file \ No newline at end of file
});
import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest'; import { type ReactNode } from 'react';
import { type ReactNode, useState } from 'react'; import { MemoryRouter } from 'react-router-dom';
import { MemoryRouter, Routes, Route } from 'react-router-dom'; import { beforeEach, describe, expect, it, vi } from 'vitest';
import { MessageProvider, useMessage } from './useMessage'; import { MessageProvider, useMessage } from './useMessage';
import { Message } from '../../packages/ui/src';
const messagePlugin = vi.hoisted(() => ({
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
closeAll: vi.fn(),
}));
vi.mock('tdesign-react', () => ({
MessagePlugin: messagePlugin,
}));
function TestShell({ children }: { children: ReactNode }) { function TestShell({ children }: { children: ReactNode }) {
return ( return (
<MemoryRouter initialEntries={['/agents']}> <MemoryRouter initialEntries={['/agents']}>
<MessageProvider> <MessageProvider>{children}</MessageProvider>
<div data-testid="shell">
{children}
</div>
</MessageProvider>
</MemoryRouter> </MemoryRouter>
); );
} }
...@@ -32,7 +39,11 @@ function MessageButton() { ...@@ -32,7 +39,11 @@ function MessageButton() {
} }
describe('global message entry', () => { describe('global message entry', () => {
it('shows success, error, warning, info messages with correct types', () => { beforeEach(() => {
vi.clearAllMocks();
});
it('delegates success, error, warning, info messages to TDesign', () => {
render( render(
<TestShell> <TestShell>
<MessageButton /> <MessageButton />
...@@ -44,70 +55,39 @@ describe('global message entry', () => { ...@@ -44,70 +55,39 @@ describe('global message entry', () => {
fireEvent.click(screen.getByRole('button', { name: '警告' })); fireEvent.click(screen.getByRole('button', { name: '警告' }));
fireEvent.click(screen.getByRole('button', { name: '信息' })); fireEvent.click(screen.getByRole('button', { name: '信息' }));
expect(screen.getByRole('status', { name: '操作成功' })).toBeInTheDocument(); const defaultOptions = { duration: 3000, closeBtn: false, placement: 'top-right' };
expect(screen.getByRole('alert', { name: '操作失败' })).toBeInTheDocument(); expect(messagePlugin.success).toHaveBeenCalledWith({ content: '操作成功', ...defaultOptions });
expect(screen.getByRole('status', { name: '请注意' })).toBeInTheDocument(); expect(messagePlugin.error).toHaveBeenCalledWith({ content: '操作失败', ...defaultOptions });
expect(screen.getByRole('status', { name: '已刷新' })).toBeInTheDocument(); expect(messagePlugin.warning).toHaveBeenCalledWith({ content: '请注意', ...defaultOptions });
}); expect(messagePlugin.info).toHaveBeenCalledWith({ content: '已刷新', ...defaultOptions });
it('auto closes message after default duration', async () => {
render(
<TestShell>
<MessageButton />
</TestShell>,
);
fireEvent.click(screen.getByRole('button', { name: '成功' }));
expect(screen.getByRole('status', { name: '操作成功' })).toBeInTheDocument();
await waitFor(() => expect(screen.queryByRole('status', { name: '操作成功' })).not.toBeInTheDocument(), { timeout: 5000 });
}); });
it('supports manual close with closable message', () => { it('supports closable messages and custom duration', () => {
function ClosableButton() { function CustomButton() {
const { success } = useMessage(); const { success } = useMessage();
return <button type="button" onClick={() => success('可关闭消息', { closable: true, duration: 0 })}>可关闭</button>; return <button type="button" onClick={() => success('可关闭消息', { closable: true, duration: 500 })}>自定义</button>;
} }
render( render(
<TestShell> <TestShell>
<ClosableButton /> <CustomButton />
</TestShell>, </TestShell>,
); );
fireEvent.click(screen.getByRole('button', { name: '可关闭' })); fireEvent.click(screen.getByRole('button', { name: '自定义' }));
expect(screen.getByRole('status', { name: '可关闭消息' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '关闭可关闭消息' }));
expect(screen.queryByRole('status', { name: '可关闭消息' })).not.toBeInTheDocument(); expect(messagePlugin.success).toHaveBeenCalledWith({
}); content: '可关闭消息',
duration: 500,
it('renders message container at top right fixed position', () => { closeBtn: true,
render( placement: 'top-right',
<TestShell> });
<MessageButton />
</TestShell>,
);
fireEvent.click(screen.getByRole('button', { name: '成功' }));
const region = screen.getByRole('region', { name: '全局消息提示' });
expect(region).toBeInTheDocument();
}); });
it('clears all messages when clear is called', async () => { it('clears all TDesign messages when clear is called', () => {
function ClearButton() { function ClearButton() {
const { success, clear } = useMessage(); const { clear } = useMessage();
return ( return <button type="button" onClick={clear}>清除全部</button>;
<div>
<button type="button" onClick={() => success('消息1', { duration: 0 })}>消息1</button>
<button type="button" onClick={() => success('消息2', { duration: 0 })}>消息2</button>
<button type="button" onClick={clear}>清除全部</button>
</div>
);
} }
render( render(
...@@ -116,36 +96,8 @@ describe('global message entry', () => { ...@@ -116,36 +96,8 @@ describe('global message entry', () => {
</TestShell>, </TestShell>,
); );
fireEvent.click(screen.getByRole('button', { name: '消息1' }));
fireEvent.click(screen.getByRole('button', { name: '消息2' }));
expect(screen.getByRole('status', { name: '消息1' })).toBeInTheDocument();
expect(screen.getByRole('status', { name: '消息2' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '清除全部' })); fireEvent.click(screen.getByRole('button', { name: '清除全部' }));
await waitFor(() => { expect(messagePlugin.closeAll).toHaveBeenCalledTimes(1);
expect(screen.queryByRole('status', { name: '消息1' })).not.toBeInTheDocument();
expect(screen.queryByRole('status', { name: '消息2' })).not.toBeInTheDocument();
});
});
it('supports custom duration for each message', async () => {
function CustomDurationButton() {
const { success } = useMessage();
return <button type="button" onClick={() => success('快速消息', { duration: 500 })}>快速</button>;
}
render(
<TestShell>
<CustomDurationButton />
</TestShell>,
);
fireEvent.click(screen.getByRole('button', { name: '快速' }));
expect(screen.getByRole('status', { name: '快速消息' })).toBeInTheDocument();
await waitFor(() => expect(screen.queryByRole('status', { name: '快速消息' })).not.toBeInTheDocument(), { timeout: 1000 });
}); });
});
\ No newline at end of file \ No newline at end of file
});
import { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react'; import { createContext, useCallback, useContext, useEffect, useRef } from 'react';
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import { useLocation } from 'react-router-dom'; import { useLocation } from 'react-router-dom';
import 'tdesign-react/es/_util/react-19-adapter.js';
import { Message, type MessageItem } from '../../packages/ui/src'; import { MessagePlugin } from 'tdesign-react';
export interface MessageOptions { export interface MessageOptions {
duration?: number; duration?: number;
...@@ -32,28 +32,14 @@ interface FlashContextValue { ...@@ -32,28 +32,14 @@ interface FlashContextValue {
const MessageContext = createContext<MessageContextValue | null>(null); const MessageContext = createContext<MessageContextValue | null>(null);
let messageKey = 0;
const generateKey = () => {
messageKey += 1;
return `message-${messageKey}`;
};
export function MessageProvider({ children }: { children: ReactNode }) { export function MessageProvider({ children }: { children: ReactNode }) {
const [items, setItems] = useState<MessageItem[]>([]); const addMessage = useCallback((type: FlashState['type'], content: string, options?: MessageOptions) => {
MessagePlugin[type]({
const addMessage = useCallback((type: MessageItem['type'], content: string, options?: MessageOptions) => {
const key = generateKey();
const newItem: MessageItem = {
key,
type,
content, content,
duration: options?.duration ?? 3000, duration: options?.duration ?? 3000,
closable: options?.closable ?? false, closeBtn: options?.closable ?? false,
onClose: (closedKey) => { placement: 'top-right',
setItems((current) => current.filter((item) => item.key !== closedKey)); });
},
};
setItems((current) => [...current, newItem]);
}, []); }, []);
const success = useCallback((content: string, options?: MessageOptions) => { const success = useCallback((content: string, options?: MessageOptions) => {
...@@ -73,13 +59,12 @@ export function MessageProvider({ children }: { children: ReactNode }) { ...@@ -73,13 +59,12 @@ export function MessageProvider({ children }: { children: ReactNode }) {
}, [addMessage]); }, [addMessage]);
const clear = useCallback(() => { const clear = useCallback(() => {
setItems([]); MessagePlugin.closeAll();
}, []); }, []);
return ( return (
<MessageContext.Provider value={{ success, error, warning, info, clear }}> <MessageContext.Provider value={{ success, error, warning, info, clear }}>
{children} {children}
<Message items={items} />
</MessageContext.Provider> </MessageContext.Provider>
); );
} }
...@@ -140,4 +125,4 @@ export function useFlashMessage(): FlashContextValue { ...@@ -140,4 +125,4 @@ export function useFlashMessage(): FlashContextValue {
warning: flashWarning, warning: flashWarning,
info: flashInfo, info: flashInfo,
}; };
}
\ No newline at end of file \ No newline at end of file
}
import { useState } from 'react'; import { useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom'; import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { RobotIcon, SettingIcon, UsergroupIcon } from 'tdesign-icons-react';
import {
BusinessAdminShell,
type BusinessAdminShellBreadcrumbItem,
type BusinessAdminShellMenuItem,
} from '@gl/business-components';
import { Dialog } from 'tdesign-react';
import { Avatar, Button, Modal, Navigation } from '../../packages/ui/src';
import { logout } from '../auth/localAuth'; import { logout } from '../auth/localAuth';
const navigationItems: BusinessAdminShellMenuItem[] = [
{
key: 'agent-management',
label: 'Agent管理',
icon: <RobotIcon />,
children: [
{ key: 'agent-list', label: 'Agent列表' },
{ key: 'agent-tag-list', label: '岗位标签管理' },
{ key: 'skill-list', label: 'Skill目录' },
],
},
{
key: 'agent-group-management',
label: 'Agent群管理',
icon: <UsergroupIcon />,
children: [{ key: 'channel-code-list', label: '渠道活码' }],
},
{
key: 'official-site-management',
label: '官网配置',
icon: <SettingIcon />,
children: [
{ key: 'official-site-job-tabs', label: '岗位展示配置' },
{ key: 'official-site-methodology', label: '方法论展示配置' },
],
},
];
const routeByMenuKey: Record<string, string> = {
'agent-list': '/agents',
'agent-tag-list': '/agent-tags',
'skill-list': '/skills',
'channel-code-list': '/channel-codes',
'official-site-methodology': '/official-site/methodology',
'official-site-job-tabs': '/official-site/job-tabs',
};
export function AdminShell() { export function AdminShell() {
const location = useLocation(); const location = useLocation();
const navigate = useNavigate(); const navigate = useNavigate();
...@@ -21,86 +64,85 @@ export function AdminShell() { ...@@ -21,86 +64,85 @@ export function AdminShell() {
: location.pathname.startsWith('/channel-codes') : location.pathname.startsWith('/channel-codes')
? 'channel-code-list' ? 'channel-code-list'
: undefined; : undefined;
const breadcrumb = location.pathname.startsWith('/skills') const expandedMenuKeys = navigationItems
? 'Agent管理 / Skill目录' .filter((item) => item.children?.some((child) => child.key === activeNavigationKey))
.map((item) => item.key);
const makeMenuBreadcrumb = (
parentLabel: string,
childLabel: string,
childPath: string,
independentPageName?: string,
): BusinessAdminShellBreadcrumbItem[] => {
const items: BusinessAdminShellBreadcrumbItem[] = [
{ key: 'parent', label: parentLabel },
{
key: 'child',
label: childLabel,
onClick: independentPageName ? () => navigate(childPath) : undefined,
},
];
if (independentPageName) {
items.push({ key: 'independent-page', label: independentPageName });
}
return items;
};
const breadcrumbItems = location.pathname.startsWith('/skills')
? makeMenuBreadcrumb('Agent管理', 'Skill目录', '/skills')
: location.pathname.startsWith('/agent-tags/new')
? makeMenuBreadcrumb('Agent管理', '岗位标签管理', '/agent-tags', '新增岗位标签')
: location.pathname.startsWith('/agent-tags/') && location.pathname.endsWith('/edit')
? makeMenuBreadcrumb('Agent管理', '岗位标签管理', '/agent-tags', '编辑岗位标签')
: location.pathname.startsWith('/agent-tags') : location.pathname.startsWith('/agent-tags')
? 'Agent管理 / 岗位标签管理' ? makeMenuBreadcrumb('Agent管理', '岗位标签管理', '/agent-tags')
: location.pathname.startsWith('/official-site/methodology') : location.pathname.startsWith('/official-site/methodology')
? '官网配置 / 方法论展示配置' ? makeMenuBreadcrumb('官网配置', '方法论展示配置', '/official-site/methodology')
: location.pathname.startsWith('/official-site/job-tabs/new')
? makeMenuBreadcrumb('官网配置', '岗位展示配置', '/official-site/job-tabs', '新增岗位展示')
: location.pathname.startsWith('/official-site/job-tabs/') && location.pathname.endsWith('/edit')
? makeMenuBreadcrumb('官网配置', '岗位展示配置', '/official-site/job-tabs', '编辑岗位展示')
: location.pathname.startsWith('/official-site/job-tabs/') && location.pathname.endsWith('/agents')
? makeMenuBreadcrumb('官网配置', '岗位展示配置', '/official-site/job-tabs', '展示Agent配置')
: location.pathname.startsWith('/official-site/job-tabs') : location.pathname.startsWith('/official-site/job-tabs')
? '官网配置 / 岗位展示配置' ? makeMenuBreadcrumb('官网配置', '岗位展示配置', '/official-site/job-tabs')
: location.pathname.startsWith('/channel-codes/new')
? makeMenuBreadcrumb('Agent群管理', '渠道活码', '/channel-codes', '新增渠道活码')
: location.pathname.startsWith('/channel-codes/') && location.pathname.endsWith('/edit')
? makeMenuBreadcrumb('Agent群管理', '渠道活码', '/channel-codes', '编辑渠道活码')
: location.pathname.startsWith('/channel-codes') : location.pathname.startsWith('/channel-codes')
? 'Agent群管理 / 渠道活码' ? makeMenuBreadcrumb('Agent群管理', '渠道活码', '/channel-codes')
: 'Agent管理 / Agent列表'; : location.pathname.startsWith('/agents/new')
? makeMenuBreadcrumb('Agent管理', 'Agent列表', '/agents', '新增Agent')
const navigationItems = [ : location.pathname.startsWith('/agents/') && location.pathname.endsWith('/edit')
{ ? makeMenuBreadcrumb('Agent管理', 'Agent列表', '/agents', '编辑Agent')
key: 'agent-management', : makeMenuBreadcrumb('Agent管理', 'Agent列表', '/agents');
label: 'Agent管理',
children: [
{ key: 'agent-list', label: 'Agent列表' },
{ key: 'agent-tag-list', label: '岗位标签管理' },
{ key: 'skill-list', label: 'Skill目录' },
],
},
{
key: 'agent-group-management',
label: 'Agent群管理',
children: [{ key: 'channel-code-list', label: '渠道活码' }],
},
{
key: 'official-site-management',
label: '官网配置',
children: [
{ key: 'official-site-job-tabs', label: '岗位展示配置' },
{ key: 'official-site-methodology', label: '方法论展示配置' },
],
},
];
return ( return (
<div className="grid min-h-screen grid-cols-[180px_1fr] bg-[var(--gl-color-bg-page)] text-[var(--gl-color-text-primary)] max-[760px]:grid-cols-1"> <BusinessAdminShell
<aside className="flex flex-col gap-4 border-r border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-4"> systemName="岗位Agent管理后台"
<div className="grid gap-1"> menuItems={navigationItems}
<p className="m-0 text-xs leading-[var(--gl-line-height-sm)] text-[var(--gl-color-text-secondary)]">Admin Console</p> activeMenuKey={activeNavigationKey}
<h1 className="m-0 whitespace-nowrap text-base font-semibold leading-[var(--gl-line-height-lg)]">岗位Agent管理后台</h1> expandedMenuKeys={expandedMenuKeys}
</div> breadcrumbItems={breadcrumbItems}
<Navigation user={{ name: '管理员' }}
activeKey={activeNavigationKey} onMenuChange={(key) => {
ariaLabel="管理后台导航" const nextRoute = routeByMenuKey[key];
items={navigationItems} if (nextRoute) navigate(nextRoute);
onChange={(key) => { }}
if (key === 'agent-list') navigate('/agents'); onLogout={() => setLogoutConfirmOpen(true)}
if (key === 'agent-tag-list') navigate('/agent-tags'); >
if (key === 'skill-list') navigate('/skills'); <Outlet />
if (key === 'channel-code-list') navigate('/channel-codes'); <Dialog
if (key === 'official-site-methodology') navigate('/official-site/methodology'); visible={logoutConfirmOpen}
if (key === 'official-site-job-tabs') navigate('/official-site/job-tabs'); header="确认退出登录?"
}} cancelBtn="取消"
/> confirmBtn="确定"
</aside> destroyOnClose
<div className="grid min-w-0 grid-rows-[auto_1fr]"> onClose={() => setLogoutConfirmOpen(false)}
<header className="flex min-h-14 items-center justify-between border-b border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 text-sm text-[var(--gl-color-text-secondary)] max-[760px]:px-4"> onConfirm={() => {
<span>{breadcrumb}</span>
<div className="flex items-center gap-3">
<Avatar name="管理员" />
<Button
variant="outline"
onClick={() => setLogoutConfirmOpen(true)}
>
退出登录
</Button>
</div>
</header>
<main className="p-8 max-[760px]:p-4">
<Outlet />
</main>
</div>
<Modal
open={logoutConfirmOpen}
title="确认退出登录?"
onCancel={() => setLogoutConfirmOpen(false)}
onOk={() => {
setLogoutConfirmOpen(false); setLogoutConfirmOpen(false);
logout(); logout();
navigate('/login', { replace: true, state: { from: location } }); navigate('/login', { replace: true, state: { from: location } });
...@@ -109,7 +151,7 @@ export function AdminShell() { ...@@ -109,7 +151,7 @@ export function AdminShell() {
<p className="m-0 text-sm leading-[var(--gl-line-height-md)] text-[var(--gl-color-text-secondary)]"> <p className="m-0 text-sm leading-[var(--gl-line-height-md)] text-[var(--gl-color-text-secondary)]">
退出后将返回登录页,当前后台操作上下文不会保留。 退出后将返回登录页,当前后台操作上下文不会保留。
</p> </p>
</Modal> </Dialog>
</div> </BusinessAdminShell>
); );
} }
import { fireEvent, render, screen, within } from '@testing-library/react';
import { RobotIcon, SettingIcon } from 'tdesign-icons-react';
import { describe, expect, it, vi } from 'vitest';
import { BusinessAdminShell, type BusinessAdminShellMenuItem } from '@gl/business-components';
const menuItems: BusinessAdminShellMenuItem[] = [
{
key: 'agent-management',
label: 'Agent管理',
icon: <RobotIcon data-testid="agent-menu-icon" />,
children: [
{ key: 'agent-list', label: 'Agent列表' },
{ key: 'agent-tag-list', label: '岗位标签管理' },
],
},
{
key: 'official-site-management',
label: '官网配置',
icon: <SettingIcon data-testid="official-site-menu-icon" />,
children: [{ key: 'official-site-job-tabs', label: '岗位展示配置' }],
},
];
describe('BusinessAdminShell', () => {
it('renders the fixed post-login shell structure with system name, menu, header and 24px content padding', () => {
render(
<BusinessAdminShell
systemName="岗位Agent管理后台"
menuItems={menuItems}
activeMenuKey="agent-list"
expandedMenuKeys={['agent-management']}
breadcrumbItems={[
{ key: 'agent-management', label: 'Agent管理' },
{ key: 'agent-list', label: 'Agent列表' },
]}
user={{ name: '管理员' }}
onMenuChange={vi.fn()}
onLogout={vi.fn()}
>
<h2>页面内容</h2>
</BusinessAdminShell>,
);
expect(screen.getByText('岗位Agent管理后台')).toBeInTheDocument();
expect(screen.getAllByText('Agent管理').length).toBeGreaterThan(0);
expect(screen.getByTestId('agent-menu-icon')).toBeInTheDocument();
expect(screen.getByTestId('official-site-menu-icon')).toBeInTheDocument();
const leftNavigation = screen.getByLabelText('左侧导航');
expect(within(leftNavigation).getByText('Agent列表').closest('li')).toHaveClass('t-is-active');
expect(within(leftNavigation).getByText('Agent管理')).toBeInTheDocument();
expect(within(leftNavigation).getByText('Agent列表')).toBeInTheDocument();
expect(screen.getByText('页面内容').closest('main')).toHaveStyle({ padding: '24px' });
expect(screen.getByText('管理员')).toBeInTheDocument();
expect(screen.getByLabelText('管理员头像')).toHaveTextContent('管');
expect(screen.getByRole('button', { name: '退出登录' })).toBeInTheDocument();
});
it('collapses and expands the left menu while preserving configured menu icons', () => {
render(
<BusinessAdminShell
systemName="岗位Agent管理后台"
menuItems={menuItems}
activeMenuKey="agent-list"
expandedMenuKeys={['agent-management']}
breadcrumbItems={[
{ key: 'agent-management', label: 'Agent管理' },
{ key: 'agent-list', label: 'Agent列表' },
]}
user={{ name: '管理员' }}
onMenuChange={vi.fn()}
onLogout={vi.fn()}
>
<h2>页面内容</h2>
</BusinessAdminShell>,
);
fireEvent.click(screen.getByRole('button', { name: '收起菜单' }));
expect(screen.getByRole('button', { name: '展开菜单' })).toBeInTheDocument();
expect(screen.getByTestId('agent-menu-icon')).toBeInTheDocument();
expect(screen.getByLabelText('左侧导航')).toHaveStyle({ width: '64px' });
fireEvent.click(screen.getByRole('button', { name: '展开菜单' }));
expect(screen.getByRole('button', { name: '收起菜单' })).toBeInTheDocument();
expect(screen.getByLabelText('左侧导航')).toHaveStyle({ width: '220px' });
expect(screen.getByText('岗位Agent管理后台')).toBeInTheDocument();
});
it('toggles a first-level menu section without being locked by route expanded keys', () => {
render(
<BusinessAdminShell
systemName="岗位Agent管理后台"
menuItems={menuItems}
activeMenuKey="agent-list"
expandedMenuKeys={['agent-management']}
breadcrumbItems={[
{ key: 'agent-management', label: 'Agent管理' },
{ key: 'agent-list', label: 'Agent列表' },
]}
user={{ name: '管理员' }}
onMenuChange={vi.fn()}
onLogout={vi.fn()}
>
<h2>页面内容</h2>
</BusinessAdminShell>,
);
const leftNavigation = screen.getByLabelText('左侧导航');
const agentMenuSection = within(leftNavigation).getByText('Agent管理').closest('li');
expect(agentMenuSection).toHaveClass('t-is-opened');
fireEvent.click(within(leftNavigation).getByText('Agent管理'));
expect(agentMenuSection).not.toHaveClass('t-is-opened');
fireEvent.click(within(leftNavigation).getByText('Agent管理'));
expect(agentMenuSection).toHaveClass('t-is-opened');
});
it('supports independent page breadcrumbs returning to the secondary menu page', () => {
const handleBreadcrumbClick = vi.fn();
render(
<BusinessAdminShell
systemName="岗位Agent管理后台"
menuItems={menuItems}
activeMenuKey="agent-list"
expandedMenuKeys={['agent-management']}
breadcrumbItems={[
{ key: 'agent-management', label: 'Agent管理' },
{ key: 'agent-list', label: 'Agent列表', onClick: handleBreadcrumbClick },
{ key: 'agent-create', label: '新增Agent' },
]}
user={{ name: '管理员' }}
onMenuChange={vi.fn()}
onLogout={vi.fn()}
>
<h2>新增Agent</h2>
</BusinessAdminShell>,
);
expect(screen.getByRole('heading', { name: '新增Agent' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Agent列表' }));
expect(handleBreadcrumbClick).toHaveBeenCalledTimes(1);
});
it('shows profile and logout actions in avatar dropdown when profile is enabled', () => {
const handleProfile = vi.fn();
const handleLogout = vi.fn();
render(
<BusinessAdminShell
systemName="岗位Agent管理后台"
menuItems={menuItems}
activeMenuKey="agent-list"
expandedMenuKeys={['agent-management']}
breadcrumbItems={[
{ key: 'agent-management', label: 'Agent管理' },
{ key: 'agent-list', label: 'Agent列表' },
]}
user={{ name: '管理员' }}
hasProfile
onMenuChange={vi.fn()}
onProfile={handleProfile}
onLogout={handleLogout}
>
<h2>页面内容</h2>
</BusinessAdminShell>,
);
expect(screen.queryByRole('button', { name: '退出登录' })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '管理员 用户菜单' }));
fireEvent.click(screen.getByText('个人信息'));
fireEvent.click(screen.getByRole('button', { name: '管理员 用户菜单' }));
fireEvent.click(screen.getByText('退出登录'));
expect(handleProfile).toHaveBeenCalledTimes(1);
expect(handleLogout).toHaveBeenCalledTimes(1);
});
});
import { describe, expect, it } from 'vitest';
import agentTagEditorPageSource from '../routes/agent-tags/AgentTagEditorPage.tsx?raw';
import agentEditorPageSource from '../routes/agents/AgentEditorPage.tsx?raw';
import channelCodeEditorPageSource from '../routes/channel-codes/ChannelCodeEditorPage.tsx?raw';
import officialSiteMethodologyPageSource from '../routes/official-site/OfficialSiteMethodologyPage.tsx?raw';
import agentDisplayConfigEditModalSource from '../routes/official-site-agent-display-config/AgentDisplayConfigEditModal.tsx?raw';
import officialSiteAgentDisplayConfigPageSource from '../routes/official-site-agent-display-config/OfficialSiteAgentDisplayConfigPage.tsx?raw';
import officialSiteJobTabEditorPageSource from '../routes/official-site-job-tabs/OfficialSiteJobTabEditorPage.tsx?raw';
const editorPageRuntimeFiles = [
['AgentEditorPage.tsx', agentEditorPageSource],
['AgentTagEditorPage.tsx', agentTagEditorPageSource],
['ChannelCodeEditorPage.tsx', channelCodeEditorPageSource],
['OfficialSiteMethodologyPage.tsx', officialSiteMethodologyPageSource],
['AgentDisplayConfigEditModal.tsx', agentDisplayConfigEditModalSource],
['OfficialSiteAgentDisplayConfigPage.tsx', officialSiteAgentDisplayConfigPageSource],
['OfficialSiteJobTabEditorPage.tsx', officialSiteJobTabEditorPageSource],
];
describe('phase five editor page local ui runtime dependencies', () => {
it.each(editorPageRuntimeFiles)('%s no longer imports packages/ui', (_, source) => {
expect(source).not.toContain('packages/ui');
});
});
import { describe, expect, it } from 'vitest';
import agentTagListPageSource from '../routes/agent-tags/AgentTagListPage.tsx?raw';
import agentListPageSource from '../routes/agents/AgentListPage.tsx?raw';
import channelCodeListPageSource from '../routes/channel-codes/ChannelCodeListPage.tsx?raw';
import officialSiteJobTabListPageSource from '../routes/official-site-job-tabs/OfficialSiteJobTabListPage.tsx?raw';
import skillListPageSource from '../routes/skills/SkillListPage.tsx?raw';
const listPageRuntimeFiles = [
['AgentListPage.tsx', agentListPageSource],
['AgentTagListPage.tsx', agentTagListPageSource],
['ChannelCodeListPage.tsx', channelCodeListPageSource],
['OfficialSiteJobTabListPage.tsx', officialSiteJobTabListPageSource],
['SkillListPage.tsx', skillListPageSource],
];
describe('phase four list page local ui runtime dependencies', () => {
it.each(listPageRuntimeFiles)('%s no longer imports packages/ui', (_, source) => {
expect(source).not.toContain('packages/ui');
});
});
import { describe, expect, it } from 'vitest';
import componentsDemoPageSource from '../routes/components/ComponentsDemoPage.tsx?raw';
describe('phase six components demo local ui runtime dependencies', () => {
it('uses TDesign and global business components instead of packages/ui', () => {
expect(componentsDemoPageSource).not.toContain('packages/ui');
expect(componentsDemoPageSource).toContain("from 'tdesign-react'");
expect(componentsDemoPageSource).toContain("from 'tdesign-icons-react'");
expect(componentsDemoPageSource).toContain("from '@gl/business-components'");
});
});
import { describe, expect, it } from 'vitest';
import useMessageSource from '../hooks/useMessage.tsx?raw';
import adminShellSource from '../layouts/AdminShell.tsx?raw';
import agentDetailDrawerSource from '../routes/agents/AgentDetailDrawer.tsx?raw';
import channelCodeViewDrawerSource from '../routes/channel-codes/ChannelCodeViewDrawer.tsx?raw';
import skillDetailDrawerSource from '../routes/skills/SkillDetailDrawer.tsx?raw';
const phaseThreeRuntimeFiles = [
['useMessage.tsx', useMessageSource],
['AdminShell.tsx', adminShellSource],
['AgentDetailDrawer.tsx', agentDetailDrawerSource],
['ChannelCodeViewDrawer.tsx', channelCodeViewDrawerSource],
['SkillDetailDrawer.tsx', skillDetailDrawerSource],
];
describe('phase three local ui runtime dependencies', () => {
it.each(phaseThreeRuntimeFiles)('%s no longer imports packages/ui', (_, source) => {
expect(source).not.toContain('packages/ui');
});
it('useMessage imports the React 19 adapter from the TDesign ESM entry', () => {
expect(useMessageSource).toContain("import 'tdesign-react/es/_util/react-19-adapter.js';");
expect(useMessageSource).not.toContain("tdesign-react/lib/_util/react-19-adapter.js");
});
});
import { useState } from 'react'; import { useState } from 'react';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom'; import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Button, FormItem, Input, StatePlaceholder, Textarea } from '../../../packages/ui/src'; import { StatePlaceholder } from '@gl/business-components';
import { Button } from 'tdesign-react';
import { FormItem, Input, Textarea } from '../../components/TDesignAccessibleControls';
import { import {
getPositionTagList, getPositionTagList,
createPositionTag, createPositionTag,
...@@ -150,7 +152,7 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -150,7 +152,7 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) {
return ( return (
<section className="grid gap-6"> <section className="grid gap-6">
<header className="flex items-center justify-between gap-6 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6"> <header className="sticky top-0 z-10 flex items-center justify-between gap-6 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6">
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<Button variant="outline" onClick={goBackToList}>返回</Button> <Button variant="outline" onClick={goBackToList}>返回</Button>
<div> <div>
...@@ -160,10 +162,7 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -160,10 +162,7 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) {
</p> </p>
</div> </div>
</div> </div>
<div className="flex items-center gap-3"> <Button theme="primary" loading={saving} onClick={handleSave}>保存</Button>
<Button variant="outline" onClick={goBackToList}>取消</Button>
<Button variant="primary" loading={saving} onClick={handleSave}>保存</Button>
</div>
</header> </header>
{notice ? ( {notice ? (
...@@ -178,19 +177,20 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -178,19 +177,20 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) {
<div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10"> <div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10">
<div className="mx-auto grid max-w-[760px] gap-6"> <div className="mx-auto grid max-w-[760px] gap-6">
<FormItem label="标签名称" layout="horizontal" required error={errors.name}> <FormItem label="标签名称" labelAlign="left" requiredMark status={errors.name ? 'error' : undefined} tips={errors.name}>
<Input <Input
aria-label="标签名称" aria-label="标签名称"
className={fieldWidthClassName} className={fieldWidthClassName}
maxLength={20} maxlength={20}
showCount allowInputOverMax
showLimitNumber
value={form.name} value={form.name}
onChange={(value) => setForm((current) => ({ ...current, name: value }))} onChange={(value) => setForm((current) => ({ ...current, name: value }))}
/> />
</FormItem> </FormItem>
{mode === 'edit' && currentTag?.code ? ( {mode === 'edit' && currentTag?.code ? (
<FormItem label="标签编码" layout="horizontal"> <FormItem label="标签编码" labelAlign="left">
<Input <Input
aria-label="标签编码" aria-label="标签编码"
className={fieldWidthClassName} className={fieldWidthClassName}
...@@ -200,13 +200,14 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -200,13 +200,14 @@ export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) {
</FormItem> </FormItem>
) : null} ) : null}
<FormItem label="标签描述" layout="horizontal" error={errors.description}> <FormItem label="标签描述" labelAlign="left" status={errors.description ? 'error' : undefined} tips={errors.description}>
<Textarea <Textarea
aria-label="标签描述" aria-label="标签描述"
className={fieldWidthClassName} className={fieldWidthClassName}
maxLength={100} maxlength={100}
allowInputOverMax
rows={5} rows={5}
showCount count
value={form.description} value={form.description}
onChange={(value) => setForm((current) => ({ ...current, description: value }))} onChange={(value) => setForm((current) => ({ ...current, description: value }))}
/> />
......
import { useState } from 'react'; import { useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button, Input, Modal, Pagination, StatePlaceholder, Table, type TableColumn } from '../../../packages/ui/src'; import { BusinessTable, SearchFilter, type BusinessTableColumn, type SearchFilterValues } from '@gl/business-components';
import { Button, Dialog } from 'tdesign-react';
import { import {
getPositionTagList, getPositionTagList,
getPositionTagReferences, getPositionTagReferences,
...@@ -98,9 +99,11 @@ export function AgentTagListPage() { ...@@ -98,9 +99,11 @@ export function AgentTagListPage() {
pageSize: routeState.pageSize, pageSize: routeState.pageSize,
}); });
const submitFilters = () => { const submitFilters = (filterValues: SearchFilterValues = { keyword }) => {
const nextKeyword = String(filterValues.keyword ?? '');
setKeyword(nextKeyword);
setSearchParams(buildAgentTagListSearch({ setSearchParams(buildAgentTagListSearch({
keyword, keyword: nextKeyword,
page: 1, page: 1,
pageSize: routeState.pageSize, pageSize: routeState.pageSize,
})); }));
...@@ -124,30 +127,31 @@ export function AgentTagListPage() { ...@@ -124,30 +127,31 @@ export function AgentTagListPage() {
} }
}; };
const columns: TableColumn<PositionTagListItem>[] = [ const columns: BusinessTableColumn<PositionTagListItem>[] = [
{ title: '标签名称', dataIndex: 'name' }, { title: '标签名称', colKey: 'name' },
{ title: '标签编码', dataIndex: 'code' }, { title: '标签编码', colKey: 'code' },
{ {
title: '标签描述', title: '标签描述',
dataIndex: 'description', colKey: 'description',
render: (value: unknown) => ((value as string | undefined)?.trim() || '-'), cell: ({ row }) => row.description?.trim() || '-',
}, },
{ title: '绑定Agent数', dataIndex: 'agent_count' }, { title: '绑定Agent数', colKey: 'agent_count' },
{ title: '创建时间', dataIndex: 'created_at' }, { title: '创建时间', colKey: 'created_at' },
{ {
title: '操作', title: '操作',
key: 'actions', colKey: 'actions',
render: (_: unknown, tag: PositionTagListItem) => ( cell: ({ row: tag }) => (
<span className="flex flex-wrap gap-1"> <span className="flex flex-wrap gap-1">
<Button <Button
aria-label={`编辑${tag.name}`} aria-label={`编辑${tag.name}`}
size="small" size="small"
theme="primary"
variant="text" variant="text"
onClick={() => navigate(`/agent-tags/${tag.tag_id}/edit${routeSearch}`, { state: { tag } })} onClick={() => navigate(`/agent-tags/${tag.tag_id}/edit${routeSearch}`, { state: { tag } })}
> >
编辑 编辑
</Button> </Button>
<Button aria-label={`删除${tag.name}`} size="small" variant="text" onClick={() => handleDeleteClick(tag)}> <Button aria-label={`删除${tag.name}`} size="small" theme="primary" variant="text" onClick={() => handleDeleteClick(tag)}>
删除 删除
</Button> </Button>
</span> </span>
...@@ -162,81 +166,67 @@ export function AgentTagListPage() { ...@@ -162,81 +166,67 @@ export function AgentTagListPage() {
<h2 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">岗位标签管理</h2> <h2 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">岗位标签管理</h2>
<p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">管理岗位标签的列表、新建、编辑与删除状态</p> <p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">管理岗位标签的列表、新建、编辑与删除状态</p>
</div> </div>
<Button variant="primary" onClick={() => { <Button theme="primary" onClick={() => {
trackCustomEvent({ event_type: 'click_create', event_data: { page: 'tag_list' } }); trackCustomEvent({ event_type: 'click_create', event_data: { page: 'tag_list' } });
navigate(`/agent-tags/new${routeSearch}`); navigate(`/agent-tags/new${routeSearch}`);
}}>新建岗位标签</Button> }}>新建岗位标签</Button>
</header> </header>
<div className="flex flex-wrap items-center justify-between gap-4 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6"> <SearchFilter
<div className="flex items-center gap-2 text-sm"> className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6"
<span className="shrink-0">标签名称:</span> fields={[
<span className="w-[200px]"> {
<Input key: 'keyword',
aria-label="标签名称" label: '标签名称',
className="w-full" type: 'input',
placeholder="搜索标签名称" value: keyword,
value={keyword} allowClear: true,
allowClear onChange: setKeyword,
onChange={setKeyword} },
onKeyDown={(event) => { ]}
if (event.key === 'Enter') submitFilters(); onReset={resetFilters}
}} onSearch={submitFilters}
/> />
</span>
</div>
<div className="ml-auto flex items-center justify-end gap-3">
<Button variant="primary" onClick={submitFilters}>搜索</Button>
<Button variant="outline" onClick={resetFilters}>重置</Button>
</div>
</div>
<div className="grid gap-6 overflow-x-auto rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6"> <div className="grid gap-6 overflow-x-auto rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6">
{loadError ? ( <BusinessTable
<StatePlaceholder rowKey="tag_id"
state="error" columns={columns}
title="加载失败" data={listData.items}
description="岗位标签列表加载失败,请重试" loading={loading}
primaryAction={<Button size="small" onClick={fetchList}>重试</Button>} error={loadError}
/> hasFilter={hasFilter}
) : ( filteredEmptyState={{
<> onAction: resetFilters,
<Table }}
rowKey="tag_id" errorState={{
columns={columns} onRetry: fetchList,
dataSource={listData.items} }}
loading={loading} pagination={{
empty={{ current: routeState.page,
description: hasFilter ? '未找到匹配结果' : '当前还没有岗位标签', pageSize: routeState.pageSize,
action: hasFilter ? <Button size="small" onClick={resetFilters}>重置搜索</Button> : undefined, total: listData.total,
}} pageSizeOptions: [2, 10, 20],
/> onChange: ({ current, pageSize }) => {
{listData.items.length === 0 && hasFilter ? <StatePlaceholder state="filtered-empty" /> : null} setSearchParams(buildAgentTagListSearch({
<Pagination keyword: routeState.keyword,
current={routeState.page} page: current,
pageSize={routeState.pageSize} pageSize,
total={listData.total} }));
pageSizeOptions={[2, 10, 20]} },
onChange={(page, pageSize) => { }}
setSearchParams(buildAgentTagListSearch({ />
keyword: routeState.keyword,
page,
pageSize,
}));
}}
/>
</>
)}
</div> </div>
<Modal <Dialog
open={Boolean(deleteTarget)} visible={Boolean(deleteTarget)}
title={deleteTarget ? buildDeleteTitle(deleteTarget.tag) : ''} header={deleteTarget ? buildDeleteTitle(deleteTarget.tag) : ''}
{...{ role: 'dialog', 'aria-label': deleteTarget ? buildDeleteTitle(deleteTarget.tag) : '' }}
footer={deleteTarget ? ( footer={deleteTarget ? (
<> <>
<Button onClick={() => setDeleteTarget(null)}>取消</Button> <Button onClick={() => setDeleteTarget(null)}>取消</Button>
<Button <Button
variant="primary" theme="primary"
onClick={() => { onClick={() => {
if (hasBlockingReferences(deleteTarget.references)) { if (hasBlockingReferences(deleteTarget.references)) {
setDeleteTarget(null); setDeleteTarget(null);
...@@ -263,12 +253,13 @@ export function AgentTagListPage() { ...@@ -263,12 +253,13 @@ export function AgentTagListPage() {
</Button> </Button>
</> </>
) : null} ) : null}
onCancel={() => setDeleteTarget(null)} destroyOnClose
onClose={() => setDeleteTarget(null)}
> >
<div className="max-w-[360px]"> <div className="max-w-[360px]">
{deleteTarget ? buildDeleteDescription(deleteTarget.references) : ''} {deleteTarget ? buildDeleteDescription(deleteTarget.references) : ''}
</div> </div>
</Modal> </Dialog>
</section> </section>
); );
} }
...@@ -14,6 +14,22 @@ import { ...@@ -14,6 +14,22 @@ import {
} from '../../api/positionTag'; } from '../../api/positionTag';
import { reportPageView, reportAnalyticsEvents } from '../../api/analytics'; import { reportPageView, reportAnalyticsEvents } from '../../api/analytics';
const messagePlugin = vi.hoisted(() => ({
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
closeAll: vi.fn(),
}));
vi.mock('tdesign-react', async (importOriginal) => {
const actual = await importOriginal<typeof import('tdesign-react')>();
return {
...actual,
MessagePlugin: messagePlugin,
};
});
vi.mock('../../api/positionTag', () => ({ vi.mock('../../api/positionTag', () => ({
getPositionTagList: vi.fn(), getPositionTagList: vi.fn(),
getPositionTagReferences: vi.fn(), getPositionTagReferences: vi.fn(),
...@@ -101,6 +117,18 @@ function renderAgentTags(path = '/agent-tags') { ...@@ -101,6 +117,18 @@ function renderAgentTags(path = '/agent-tags') {
); );
} }
function getSelectOption(name: string) {
const option = screen.getAllByText(name).map((element) => element.closest('li')).find(Boolean);
if (!option) throw new Error(`Select option ${name} was not found`);
return option as HTMLElement;
}
function getPaginationItem(name: string) {
const item = screen.getAllByText(name).map((element) => element.closest('.t-pagination__number')).find(Boolean);
if (!item) throw new Error(`Pagination item ${name} was not found`);
return item as HTMLElement;
}
describe('Agent tag routes and list page', () => { describe('Agent tag routes and list page', () => {
beforeEach(() => { beforeEach(() => {
window.localStorage.clear(); window.localStorage.clear();
...@@ -134,18 +162,20 @@ describe('Agent tag routes and list page', () => { ...@@ -134,18 +162,20 @@ describe('Agent tag routes and list page', () => {
await screen.findByText('店销顾问'); await screen.findByText('店销顾问');
expect(screen.getByRole('heading', { name: '岗位标签管理' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '岗位标签管理' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '岗位标签管理' })).toHaveAttribute('aria-current', 'page'); expect(screen.getAllByText('岗位标签管理').length).toBeGreaterThan(0);
expect(screen.getByText('标签名称:')).toBeInTheDocument(); expect(screen.getAllByText('标签名称').length).toBeGreaterThan(0);
expect(screen.getByLabelText('标签名称')).toBeInTheDocument(); expect(screen.getByLabelText('标签名称')).toBeInTheDocument();
expect(screen.getByPlaceholderText('搜索标签名称')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '搜索' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '搜索' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '重置' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '重置' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '新建岗位标签' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '新建岗位标签' })).toBeInTheDocument();
expect(screen.getByText('标签名称')).toBeInTheDocument(); expect(screen.getAllByText('标签名称').length).toBeGreaterThan(0);
expect(screen.getByText('标签编码')).toBeInTheDocument(); expect(screen.getByText('标签编码')).toBeInTheDocument();
expect(screen.getByText('标签描述')).toBeInTheDocument(); expect(screen.getByText('标签描述')).toBeInTheDocument();
expect(screen.getByText('绑定Agent数')).toBeInTheDocument(); expect(screen.getByText('绑定Agent数')).toBeInTheDocument();
expect(screen.getByText('创建时间')).toBeInTheDocument(); expect(screen.getByText('创建时间')).toBeInTheDocument();
expect(screen.getByText('共 5 条')).toBeInTheDocument(); expect(screen.getByRole('button', { name: '编辑店销顾问' })).toHaveClass('t-button--theme-primary', 't-button--variant-text');
expect(screen.getAllByText('共 5 条数据').length).toBeGreaterThan(0);
}); });
it('supports keyword search, reset and pagination changes from the list page', async () => { it('supports keyword search, reset and pagination changes from the list page', async () => {
...@@ -155,28 +185,35 @@ describe('Agent tag routes and list page', () => { ...@@ -155,28 +185,35 @@ describe('Agent tag routes and list page', () => {
fireEvent.change(screen.getByLabelText('标签名称'), { target: { value: '售后' } }); fireEvent.change(screen.getByLabelText('标签名称'), { target: { value: '售后' } });
fireEvent.click(screen.getByRole('button', { name: '搜索' })); fireEvent.click(screen.getByRole('button', { name: '搜索' }));
await screen.findByText('售后客服'); await waitFor(() => {
expect(screen.queryByText('店销顾问')).not.toBeInTheDocument(); expect(getPositionTagList).toHaveBeenLastCalledWith(expect.objectContaining({ keyword: '售后' }));
});
expect(screen.getByText('售后客服')).toBeInTheDocument();
await waitFor(() => {
expect(screen.queryByText('店销顾问')).not.toBeInTheDocument();
});
fireEvent.click(screen.getByRole('button', { name: '重置' })); fireEvent.click(screen.getByRole('button', { name: '重置' }));
await screen.findByText('店销顾问'); await screen.findByText('店销顾问');
expect(screen.getByLabelText('标签名称')).toHaveValue(''); expect(screen.getByLabelText('标签名称')).toHaveValue('');
fireEvent.change(screen.getByRole('combobox', { name: '每页条数' }), { target: { value: '2' } }); fireEvent.click(screen.getByDisplayValue('10 条/页'));
fireEvent.click(screen.getByRole('button', { name: '第 2 页' })); fireEvent.click(getSelectOption('2 条/页'));
fireEvent.click(getPaginationItem('2'));
await screen.findByText('直播运营'); await screen.findByText('直播运营');
expect(screen.getByRole('button', { name: '第 2 页' })).toHaveAttribute('aria-current', 'page'); expect(getPaginationItem('2')).toHaveClass('t-is-current');
}); });
it('shows a recoverable load error state and retries back to the normal list', async () => { it('shows a load error state without description or retry button', async () => {
vi.mocked(getPositionTagList).mockRejectedValueOnce(new Error('Network error')); vi.mocked(getPositionTagList).mockRejectedValueOnce(new Error('Network error'));
renderAgentTags(); renderAgentTags();
await screen.findByRole('alert', { name: '加载失败' }); await screen.findByText('请求失败');
fireEvent.click(screen.getByRole('button', { name: '重试' })); expect(screen.queryByText('岗位标签列表加载失败,请重试')).not.toBeInTheDocument();
expect(screen.queryByText('岗位标签加载失败')).not.toBeInTheDocument();
await screen.findByText('店销顾问'); expect(screen.queryByText('请检查网络连接后重试')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
}); });
}); });
...@@ -240,8 +277,11 @@ describe('Agent tag create and edit pages', () => { ...@@ -240,8 +277,11 @@ describe('Agent tag create and edit pages', () => {
renderAgentTags('/agent-tags/new'); renderAgentTags('/agent-tags/new');
await screen.findByRole('heading', { name: '新建岗位标签' }); await screen.findByRole('heading', { name: '新建岗位标签' });
expect(screen.getByRole('button', { name: '取消' })).toBeInTheDocument(); const pageHeader = screen.getByRole('heading', { name: '新建岗位标签' }).closest('header') as HTMLElement;
expect(screen.getByRole('button', { name: '保存' })).toBeInTheDocument(); expect(pageHeader).toHaveClass('sticky', 'top-0', 'z-10');
expect(within(pageHeader).getByRole('button', { name: '返回' })).toBeInTheDocument();
expect(within(pageHeader).queryByRole('button', { name: '取消' })).not.toBeInTheDocument();
expect(within(pageHeader).getByRole('button', { name: '保存' })).toBeInTheDocument();
// Validate that only name is required (code is auto-generated by backend) // Validate that only name is required (code is auto-generated by backend)
fireEvent.click(screen.getByRole('button', { name: '保存' })); fireEvent.click(screen.getByRole('button', { name: '保存' }));
...@@ -275,8 +315,11 @@ describe('Agent tag create and edit pages', () => { ...@@ -275,8 +315,11 @@ describe('Agent tag create and edit pages', () => {
renderAgentTags('/agent-tags/2/edit'); renderAgentTags('/agent-tags/2/edit');
await screen.findByRole('heading', { name: '编辑岗位标签' }); await screen.findByRole('heading', { name: '编辑岗位标签' });
expect(screen.getByDisplayValue('售后客服')).toBeInTheDocument(); await waitFor(() => {
expect(screen.getByDisplayValue('after_sales_service')).toBeDisabled(); expect(screen.getByLabelText('标签名称')).toHaveValue('售后客服');
expect(screen.getByLabelText('标签编码')).toHaveValue('after_sales_service');
});
expect(screen.getByLabelText('标签编码')).toBeDisabled();
fireEvent.change(screen.getByLabelText('标签名称'), { target: { value: '售后服务' } }); fireEvent.change(screen.getByLabelText('标签名称'), { target: { value: '售后服务' } });
fireEvent.click(screen.getByRole('button', { name: '保存' })); fireEvent.click(screen.getByRole('button', { name: '保存' }));
...@@ -434,7 +477,14 @@ describe('Agent tag deletion flows', () => { ...@@ -434,7 +477,14 @@ describe('Agent tag deletion flows', () => {
await screen.findByText('私域增长'); await screen.findByText('私域增长');
fireEvent.click(within(screen.getByRole('row', { name: /私域增长/ })).getByRole('button', { name: '删除私域增长' })); fireEvent.click(within(screen.getByRole('row', { name: /私域增长/ })).getByRole('button', { name: '删除私域增长' }));
await screen.findByRole('alert', { name: '引用检查失败,请重试' }); await waitFor(() => {
expect(messagePlugin.error).toHaveBeenCalledWith({
content: '引用检查失败,请重试',
duration: 3000,
closeBtn: false,
placement: 'top-right',
});
});
expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(deletePositionTag).not.toHaveBeenCalled(); expect(deletePositionTag).not.toHaveBeenCalled();
...@@ -484,7 +534,7 @@ describe('analytics tracking', () => { ...@@ -484,7 +534,7 @@ describe('analytics tracking', () => {
vi.mocked(getPositionTagList).mockRejectedValueOnce(new Error('Network error')); vi.mocked(getPositionTagList).mockRejectedValueOnce(new Error('Network error'));
renderAgentTags(); renderAgentTags();
await screen.findByRole('alert', { name: '加载失败' }); await screen.findByText('请求失败');
expect(reportPageView).not.toHaveBeenCalled(); expect(reportPageView).not.toHaveBeenCalled();
}); });
......
import { useState } from 'react'; import { useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { Button, Drawer, StatePlaceholder, Tag } from '../../../packages/ui/src'; import { StatePlaceholder } from '@gl/business-components';
import { CloseIcon } from 'tdesign-icons-react';
import { Button, Drawer, Tag } from 'tdesign-react';
import { getAgentDetail, isStewardAgent, type AgentDetail } from '../../api'; import { getAgentDetail, isStewardAgent, type AgentDetail } from '../../api';
import { useTrackPageView } from '../../api/tracking'; import { useTrackPageView } from '../../api/tracking';
import { useDeferredEffect } from '../../hooks/useDeferredEffect'; import { useDeferredEffect } from '../../hooks/useDeferredEffect';
...@@ -43,14 +45,16 @@ export function AgentDetailDrawer({ agentId, routeState }: { agentId?: string; r ...@@ -43,14 +45,16 @@ export function AgentDetailDrawer({ agentId, routeState }: { agentId?: string; r
return ( return (
<Drawer <Drawer
open visible
title="Agent详情" header="Agent详情"
width={520} size="520px"
destroyOnClose
closeBtn={<Button aria-label="关闭Agent详情" icon={<CloseIcon />} shape="square" variant="text" />}
onClose={closeDrawer} onClose={closeDrawer}
footer={ footer={
<div className="flex items-center justify-end gap-3"> <div className="flex items-center justify-end gap-3">
<Button variant="outline" onClick={closeDrawer}>关闭</Button> <Button variant="outline" onClick={closeDrawer}>关闭</Button>
<Button variant="primary" onClick={() => navigate(`/agents/${agentId}/edit${buildAgentListSearch(routeState)}`)}>编辑</Button> <Button theme="primary" onClick={() => navigate(`/agents/${agentId}/edit${buildAgentListSearch(routeState)}`)}>编辑</Button>
</div> </div>
} }
> >
...@@ -83,7 +87,7 @@ export function AgentDetailDrawer({ agentId, routeState }: { agentId?: string; r ...@@ -83,7 +87,7 @@ export function AgentDetailDrawer({ agentId, routeState }: { agentId?: string; r
<div className="grid grid-cols-[100px_1fr] gap-2 items-start"> <div className="grid grid-cols-[100px_1fr] gap-2 items-start">
<span className="text-[var(--gl-color-text-secondary)]">状态</span> <span className="text-[var(--gl-color-text-secondary)]">状态</span>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
<Tag status={detail.status === 'enable' ? 'success' : 'warning'}>{detail.status === 'enable' ? '已上架' : '已停用'}</Tag> <Tag theme={detail.status === 'enable' ? 'success' : 'warning'} variant="light">{detail.status === 'enable' ? '已上架' : '已停用'}</Tag>
</div> </div>
</div> </div>
<div className="grid grid-cols-[100px_1fr] gap-2 items-start"> <div className="grid grid-cols-[100px_1fr] gap-2 items-start">
......
...@@ -134,8 +134,8 @@ function getSelectRoot(name: string) { ...@@ -134,8 +134,8 @@ function getSelectRoot(name: string) {
return screen.getByRole('combobox', { name }).closest('.t-select') as HTMLElement; return screen.getByRole('combobox', { name }).closest('.t-select') as HTMLElement;
} }
function getSelectWrap(name: string) { function getSelectInput(name: string) {
return screen.getByRole('combobox', { name }).closest('.t-select__wrap') as HTMLElement; return getSelectRoot(name).querySelector<HTMLInputElement>('.t-input__inner:not(.t-input--soft-hidden)') as HTMLInputElement;
} }
function openSelect(name: string) { function openSelect(name: string) {
...@@ -146,6 +146,16 @@ function chooseSelectOption(label: string) { ...@@ -146,6 +146,16 @@ function chooseSelectOption(label: string) {
fireEvent.click(getSelectOption(label)); fireEvent.click(getSelectOption(label));
} }
function queryAgentDetailDrawer() {
return (screen.queryByText('Agent详情')?.closest('.t-drawer') ?? null) as HTMLElement | null;
}
function getAgentDetailDrawer() {
const drawer = queryAgentDetailDrawer();
if (!drawer) throw new Error('Agent detail drawer was not found');
return drawer;
}
describe('Agent editor routes and detail drawer', () => { describe('Agent editor routes and detail drawer', () => {
beforeEach(() => { beforeEach(() => {
window.localStorage.clear(); window.localStorage.clear();
...@@ -159,17 +169,20 @@ describe('Agent editor routes and detail drawer', () => { ...@@ -159,17 +169,20 @@ describe('Agent editor routes and detail drawer', () => {
vi.mocked(reportAnalyticsEvents).mockResolvedValue({ success: true }); vi.mocked(reportAnalyticsEvents).mockResolvedValue({ success: true });
}); });
it('renders the new page with agent navigation selected and returns to the list context on cancel', async () => { it('renders the new page with sticky header actions and returns to the list context from the header return', async () => {
renderAgents('/agents/new?keyword=复盘&page=2&pageSize=20'); renderAgents('/agents/new?keyword=复盘&page=2&pageSize=20');
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('heading', { name: '新建Agent' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '新建Agent' })).toBeInTheDocument();
}); });
expect(screen.getByRole('button', { name: 'Agent列表' })).toHaveAttribute('aria-current', 'page'); const pageHeader = screen.getByRole('heading', { name: '新建Agent' }).closest('header') as HTMLElement;
expect(screen.getByRole('button', { name: '取消' })).toBeInTheDocument(); expect(within(screen.getByLabelText('左侧导航')).getByText('Agent列表').closest('li')).toHaveClass('t-is-active');
expect(screen.getByRole('button', { name: '保存' })).toBeInTheDocument(); expect(pageHeader).toHaveClass('sticky', 'top-0', 'z-10');
expect(within(pageHeader).getByRole('button', { name: '返回' })).toBeInTheDocument();
expect(within(pageHeader).queryByRole('button', { name: '取消' })).not.toBeInTheDocument();
expect(within(pageHeader).getByRole('button', { name: '保存' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '取消' })); fireEvent.click(within(pageHeader).getByRole('button', { name: '返回' }));
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('heading', { name: 'Agent管理' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Agent管理' })).toBeInTheDocument();
...@@ -186,30 +199,32 @@ describe('Agent editor routes and detail drawer', () => { ...@@ -186,30 +199,32 @@ describe('Agent editor routes and detail drawer', () => {
fireEvent.click(screen.getByRole('button', { name: '查看复盘Agent详情' })); fireEvent.click(screen.getByRole('button', { name: '查看复盘Agent详情' }));
await waitFor(() => { await waitFor(() => {
const drawer = screen.getByRole('dialog', { name: 'Agent详情' }); const drawer = getAgentDetailDrawer();
expect(within(drawer).getByText('复盘Agent')).toBeInTheDocument(); expect(within(drawer).getByText('复盘Agent')).toBeInTheDocument();
}); });
fireEvent.click(screen.getByRole('button', { name: '关闭Agent详情' })); fireEvent.click(screen.getByRole('button', { name: '关闭Agent详情' }));
await waitFor(() => { await waitFor(() => {
expect(screen.queryByRole('dialog', { name: 'Agent详情' })).not.toBeInTheDocument(); expect(queryAgentDetailDrawer()).not.toBeInTheDocument();
}); });
}); });
it('renders the edit page with preloaded values and restores the detail drawer context after cancel', async () => { it('renders the edit page with preloaded values and restores the detail drawer context after header return', async () => {
renderAgents('/agents/101/edit?keyword=复盘&detail=101'); renderAgents('/agents/101/edit?keyword=复盘&detail=101');
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('heading', { name: '编辑Agent' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '编辑Agent' })).toBeInTheDocument();
}); });
expect(screen.getByDisplayValue('复盘Agent')).toBeInTheDocument(); expect(screen.getByDisplayValue('复盘Agent')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Agent列表' })).toHaveAttribute('aria-current', 'page'); expect(within(screen.getByLabelText('左侧导航')).getByText('Agent列表').closest('li')).toHaveClass('t-is-active');
fireEvent.click(screen.getByRole('button', { name: '取消' })); const pageHeader = screen.getByRole('heading', { name: '编辑Agent' }).closest('header') as HTMLElement;
expect(within(pageHeader).queryByRole('button', { name: '取消' })).not.toBeInTheDocument();
fireEvent.click(within(pageHeader).getByRole('button', { name: '返回' }));
await waitFor(() => { await waitFor(() => {
const drawer = screen.getByRole('dialog', { name: 'Agent详情' }); const drawer = getAgentDetailDrawer();
expect(drawer).toBeInTheDocument(); expect(drawer).toBeInTheDocument();
}); });
}); });
...@@ -270,7 +285,7 @@ describe('Agent editor routes and detail drawer', () => { ...@@ -270,7 +285,7 @@ describe('Agent editor routes and detail drawer', () => {
}); });
await waitFor(() => { await waitFor(() => {
expect(getSelectWrap('托管企微员工')).toHaveTextContent('黄启航'); expect(getSelectInput('托管企微员工')).toHaveValue('黄启航');
}); });
fireEvent.click(screen.getByRole('button', { name: '保存' })); fireEvent.click(screen.getByRole('button', { name: '保存' }));
...@@ -306,7 +321,7 @@ describe('Agent editor routes and detail drawer', () => { ...@@ -306,7 +321,7 @@ describe('Agent editor routes and detail drawer', () => {
chooseSelectOption('陈晓岚'); chooseSelectOption('陈晓岚');
await waitFor(() => { await waitFor(() => {
expect(getSelectWrap('托管企微员工')).toHaveTextContent('陈晓岚'); expect(getSelectInput('托管企微员工')).toHaveValue('陈晓岚');
}); });
openSelect('绑定Skill'); openSelect('绑定Skill');
...@@ -402,7 +417,9 @@ describe('Agent editor routes and detail drawer', () => { ...@@ -402,7 +417,9 @@ describe('Agent editor routes and detail drawer', () => {
expect(screen.getByLabelText('托管企微员工')).toBeDisabled(); expect(screen.getByLabelText('托管企微员工')).toBeDisabled();
expect(screen.getByDisplayValue('系统管家企微')).toBeInTheDocument(); expect(screen.getByDisplayValue('系统管家企微')).toBeInTheDocument();
expect(screen.getByRole('switch', { name: '状态' })).toBeDisabled(); expect(screen.getByRole('switch', { name: '状态' })).toBeDisabled();
expect(screen.getByRole('switch', { name: '状态' })).toHaveAttribute('aria-checked', 'true'); await waitFor(() => {
expect(screen.getByRole('switch', { name: '状态' })).toHaveAttribute('aria-checked', 'true');
});
fireEvent.change(screen.getByLabelText('Agent描述'), { target: { value: '新的路由描述' } }); fireEvent.change(screen.getByLabelText('Agent描述'), { target: { value: '新的路由描述' } });
fireEvent.click(screen.getByRole('button', { name: '保存' })); fireEvent.click(screen.getByRole('button', { name: '保存' }));
...@@ -610,7 +627,7 @@ describe('Agent editor routes and detail drawer', () => { ...@@ -610,7 +627,7 @@ describe('Agent editor routes and detail drawer', () => {
}); });
await waitFor(() => { await waitFor(() => {
expect(getSelectWrap('托管企微员工')).toHaveTextContent('陈晓岚'); expect(getSelectInput('托管企微员工')).toHaveValue('陈晓岚');
}); });
fireEvent.click(screen.getByRole('button', { name: '保存' })); fireEvent.click(screen.getByRole('button', { name: '保存' }));
...@@ -681,7 +698,9 @@ describe('Agent editor routes and detail drawer', () => { ...@@ -681,7 +698,9 @@ describe('Agent editor routes and detail drawer', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByDisplayValue('管家Agent-详情接口返回')).toBeInTheDocument(); expect(screen.getByDisplayValue('管家Agent-详情接口返回')).toBeInTheDocument();
}); });
expect(screen.getByLabelText('Agent描述')).toHaveValue('详情接口返回的描述'); await waitFor(() => {
expect(screen.getByLabelText('Agent描述')).toHaveValue('详情接口返回的描述');
});
}); });
it('does not trigger infinite loop or Maximum update depth exceeded when savedDetail reference changes', async () => { it('does not trigger infinite loop or Maximum update depth exceeded when savedDetail reference changes', async () => {
...@@ -856,7 +875,7 @@ describe('Agent editor routes and detail drawer', () => { ...@@ -856,7 +875,7 @@ describe('Agent editor routes and detail drawer', () => {
renderAgents('/agents?detail=101'); renderAgents('/agents?detail=101');
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('dialog', { name: 'Agent详情' })).toBeInTheDocument(); expect(getAgentDetailDrawer()).toBeInTheDocument();
}); });
await waitFor(() => { await waitFor(() => {
...@@ -907,7 +926,7 @@ describe('Agent editor routes and detail drawer', () => { ...@@ -907,7 +926,7 @@ describe('Agent editor routes and detail drawer', () => {
chooseSelectOption('陈晓岚'); chooseSelectOption('陈晓岚');
await waitFor(() => { await waitFor(() => {
expect(getSelectWrap('托管企微员工')).toHaveTextContent('陈晓岚'); expect(getSelectInput('托管企微员工')).toHaveValue('陈晓岚');
}); });
openSelect('绑定Skill'); openSelect('绑定Skill');
...@@ -1004,11 +1023,11 @@ describe('Agent detail drawer steward position display', () => { ...@@ -1004,11 +1023,11 @@ describe('Agent detail drawer steward position display', () => {
// 等待详情抽屉打开并加载完成 // 等待详情抽屉打开并加载完成
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('dialog', { name: 'Agent详情' })).toBeInTheDocument(); expect(getAgentDetailDrawer()).toBeInTheDocument();
}); });
// 等待详情数据加载完成 - 使用 findByText 自动等待 // 等待详情数据加载完成 - 使用 findByText 自动等待
const drawer = screen.getByRole('dialog', { name: 'Agent详情' }); const drawer = getAgentDetailDrawer();
// 管家 Agent 所属岗位应显示 "系统调度" // 管家 Agent 所属岗位应显示 "系统调度"
await waitFor(() => { await waitFor(() => {
expect(within(drawer).getByText('系统调度')).toBeInTheDocument(); expect(within(drawer).getByText('系统调度')).toBeInTheDocument();
...@@ -1050,10 +1069,10 @@ describe('Agent detail drawer steward position display', () => { ...@@ -1050,10 +1069,10 @@ describe('Agent detail drawer steward position display', () => {
renderAgents('/agents?detail=101'); renderAgents('/agents?detail=101');
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('dialog', { name: 'Agent详情' })).toBeInTheDocument(); expect(getAgentDetailDrawer()).toBeInTheDocument();
}); });
const drawer = screen.getByRole('dialog', { name: 'Agent详情' }); const drawer = getAgentDetailDrawer();
// 管家 Agent 所属岗位应优先显示 "系统调度" // 管家 Agent 所属岗位应优先显示 "系统调度"
await waitFor(() => { await waitFor(() => {
expect(within(drawer).getByText('系统调度')).toBeInTheDocument(); expect(within(drawer).getByText('系统调度')).toBeInTheDocument();
...@@ -1095,10 +1114,10 @@ describe('Agent detail drawer steward position display', () => { ...@@ -1095,10 +1114,10 @@ describe('Agent detail drawer steward position display', () => {
renderAgents('/agents?detail=101'); renderAgents('/agents?detail=101');
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('dialog', { name: 'Agent详情' })).toBeInTheDocument(); expect(getAgentDetailDrawer()).toBeInTheDocument();
}); });
const drawer = screen.getByRole('dialog', { name: 'Agent详情' }); const drawer = getAgentDetailDrawer();
// 普通 Agent 所属岗位应按详情展示 // 普通 Agent 所属岗位应按详情展示
await waitFor(() => { await waitFor(() => {
expect(within(drawer).getByText('驻店销售岗')).toBeInTheDocument(); expect(within(drawer).getByText('驻店销售岗')).toBeInTheDocument();
......
import { useState } from 'react'; import { useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Button, FormItem, Input, Select, StatePlaceholder, Switch, Textarea } from '../../../packages/ui/src'; import { StatePlaceholder } from '@gl/business-components';
import { Button } from 'tdesign-react';
import { FormItem, Input, Select, Switch, Textarea } from '../../components/TDesignAccessibleControls';
import { getPositionTagList, type PositionTagListItem } from '../../api/positionTag'; import { getPositionTagList, type PositionTagListItem } from '../../api/positionTag';
import { getEmployeeMounts, getAgentDetail, getAgentList, createAgent, updateAgent, type EmployeeMountItem, type AgentDetail, type AgentStatus } from '../../api/agent'; import { getEmployeeMounts, getAgentDetail, getAgentList, createAgent, updateAgent, type EmployeeMountItem, type AgentDetail, type AgentStatus } from '../../api/agent';
import { getSkillList, type SkillSummary } from '../../api/skill'; import { getSkillList, type SkillSummary } from '../../api/skill';
...@@ -389,7 +391,7 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -389,7 +391,7 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
return ( return (
<section className="grid gap-6"> <section className="grid gap-6">
<header className="flex items-center justify-between gap-6 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6"> <header className="sticky top-0 z-10 flex items-center justify-between gap-6 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6">
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<Button variant="outline" onClick={() => goBackToList(Boolean(routeState.detail && mode === 'edit'))}>返回</Button> <Button variant="outline" onClick={() => goBackToList(Boolean(routeState.detail && mode === 'edit'))}>返回</Button>
<div> <div>
...@@ -399,10 +401,7 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -399,10 +401,7 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
</p> </p>
</div> </div>
</div> </div>
<div className="flex items-center gap-3"> <Button theme="primary" loading={saveLoading} onClick={handleSave}>保存</Button>
<Button variant="outline" onClick={() => goBackToList(Boolean(routeState.detail && mode === 'edit'))}>取消</Button>
<Button variant="primary" loading={saveLoading} onClick={handleSave}>保存</Button>
</div>
</header> </header>
{saveError ? ( {saveError ? (
...@@ -416,21 +415,22 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -416,21 +415,22 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
<div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10"> <div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10">
<div className="mx-auto grid max-w-[760px] gap-6"> <div className="mx-auto grid max-w-[760px] gap-6">
<FormItem label="Agent名称" layout="horizontal" required error={errors.name}> <FormItem label="Agent名称" labelAlign="left" requiredMark status={errors.name ? 'error' : undefined} tips={errors.name}>
<span className="grid gap-2"> <span className="grid gap-2">
<Input <Input
aria-label="Agent名称" aria-label="Agent名称"
className={fieldWidthClassName} className={fieldWidthClassName}
disabled={isSteward} disabled={isSteward}
maxLength={50} maxlength={50}
showCount allowInputOverMax
showLimitNumber
value={form.name} value={form.name}
onChange={(value) => setForm((current) => ({ ...current, name: value }))} onChange={(value) => setForm((current) => ({ ...current, name: value }))}
/> />
</span> </span>
</FormItem> </FormItem>
<FormItem label="所属岗位" layout="horizontal" required error={errors.positionIds}> <FormItem label="所属岗位" labelAlign="left" requiredMark status={errors.positionIds ? 'error' : undefined} tips={errors.positionIds}>
<span className="grid gap-2"> <span className="grid gap-2">
{positionsError ? ( {positionsError ? (
<StatePlaceholder state="error" title="岗位选项加载失败" description="请重试加载岗位选项" primaryAction={<Button size="small" onClick={() => { <StatePlaceholder state="error" title="岗位选项加载失败" description="请重试加载岗位选项" primaryAction={<Button size="small" onClick={() => {
...@@ -473,9 +473,9 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -473,9 +473,9 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
<FormItem <FormItem
label="托管企微员工" label="托管企微员工"
layout="horizontal" labelAlign="left"
required requiredMark
error={errors.managedUserId} status={errors.managedUserId ? 'error' : undefined} tips={errors.managedUserId}
> >
<span className="grid gap-2"> <span className="grid gap-2">
{employeesError ? ( {employeesError ? (
...@@ -496,7 +496,8 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -496,7 +496,8 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
placeholder="请选择托管企微员工" placeholder="请选择托管企微员工"
value={form.managedEmployeeValue} value={form.managedEmployeeValue}
onChange={(value) => setForm((current) => { onChange={(value) => setForm((current) => {
if (!value) { const selectedValue = String(value ?? '');
if (!selectedValue) {
return { return {
...current, ...current,
managedUserId: undefined, managedUserId: undefined,
...@@ -506,21 +507,21 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -506,21 +507,21 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
} }
const currentDetailManagedUser = detail?.managed_user; const currentDetailManagedUser = detail?.managed_user;
if (currentDetailManagedUser && value === buildCurrentManagedEmployeeValue(currentDetailManagedUser.user_id)) { if (currentDetailManagedUser && selectedValue === buildCurrentManagedEmployeeValue(currentDetailManagedUser.user_id)) {
return { return {
...current, ...current,
managedUserId: currentDetailManagedUser.user_id, managedUserId: currentDetailManagedUser.user_id,
managedEmployeeValue: value, managedEmployeeValue: selectedValue,
managedUserName: currentDetailManagedUser.user_name, managedUserName: currentDetailManagedUser.user_name,
}; };
} }
const selectedEmployee = employees.find((employee) => buildEmployeeValue(employee) === value); const selectedEmployee = employees.find((employee) => buildEmployeeValue(employee) === selectedValue);
return { return {
...current, ...current,
managedUserId: selectedEmployee?.employee_id, managedUserId: selectedEmployee?.employee_id,
managedEmployeeValue: value, managedEmployeeValue: selectedValue,
managedUserName: selectedEmployee?.employee_name, managedUserName: selectedEmployee?.employee_name,
}; };
})} })}
...@@ -529,19 +530,20 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -529,19 +530,20 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
</span> </span>
</FormItem> </FormItem>
<FormItem label="Agent描述" layout="horizontal" required error={errors.description}> <FormItem label="Agent描述" labelAlign="left" requiredMark status={errors.description ? 'error' : undefined} tips={errors.description}>
<Textarea <Textarea
aria-label="Agent描述" aria-label="Agent描述"
className={fieldWidthClassName} className={fieldWidthClassName}
maxLength={AGENT_DESCRIPTION_MAX_LENGTH} maxlength={AGENT_DESCRIPTION_MAX_LENGTH}
allowInputOverMax
rows={5} rows={5}
showCount count
value={form.description} value={form.description}
onChange={(value) => setForm((current) => ({ ...current, description: value }))} onChange={(value) => setForm((current) => ({ ...current, description: value }))}
/> />
</FormItem> </FormItem>
<FormItem label="绑定Skill" layout="horizontal" required={!isSteward} error={errors.skillIds}> <FormItem label="绑定Skill" labelAlign="left" requiredMark={!isSteward} status={errors.skillIds ? 'error' : undefined} tips={errors.skillIds}>
<span className="grid gap-2"> <span className="grid gap-2">
{skillsError ? ( {skillsError ? (
<StatePlaceholder state="error" title="Skill 选项加载失败" description="请重试加载 Skill 选项" primaryAction={<Button size="small" onClick={fetchSkills}>重试</Button>} /> <StatePlaceholder state="error" title="Skill 选项加载失败" description="请重试加载 Skill 选项" primaryAction={<Button size="small" onClick={fetchSkills}>重试</Button>} />
...@@ -558,10 +560,10 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -558,10 +560,10 @@ export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
</span> </span>
</FormItem> </FormItem>
<FormItem label="状态" layout="horizontal" required> <FormItem label="状态" labelAlign="left" requiredMark>
<Switch <Switch
aria-label="状态" aria-label="状态"
checked={isSteward ? true : form.status === 'enable'} value={isSteward ? true : form.status === 'enable'}
disabled={isSteward} disabled={isSteward}
onChange={(checked) => setForm((current) => ({ ...current, status: checked ? 'enable' : 'disable' }))} onChange={(checked) => setForm((current) => ({ ...current, status: checked ? 'enable' : 'disable' }))}
/> />
......
import { fireEvent, render, screen, within, waitFor } from '@testing-library/react'; import { act, fireEvent, render, screen, within, waitFor } from '@testing-library/react';
import { StrictMode } from 'react'; import { StrictMode } from 'react';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
...@@ -113,12 +113,13 @@ describe('AgentListPage', () => { ...@@ -113,12 +113,13 @@ describe('AgentListPage', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('heading', { name: 'Agent管理' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Agent管理' })).toBeInTheDocument();
}); });
expect(screen.getByText('Agent名称:')).toBeInTheDocument(); expect(screen.getAllByText('Agent名称').length).toBeGreaterThan(0);
expect(screen.getByText('所属岗位:')).toBeInTheDocument(); expect(screen.getAllByText('所属岗位').length).toBeGreaterThan(0);
expect(screen.getByText('状态:')).toBeInTheDocument(); expect(screen.getAllByText('状态').length).toBeGreaterThan(0);
expect(screen.getByLabelText('搜索Agent名称')).toBeInTheDocument(); expect(screen.getByLabelText('Agent名称')).toBeInTheDocument();
expect(screen.getByRole('combobox', { name: '岗位筛选' })).toBeInTheDocument(); expect(screen.getByPlaceholderText('搜索Agent名称')).toBeInTheDocument();
expect(screen.getByRole('combobox', { name: '状态筛选' })).toBeInTheDocument(); expect(screen.getByLabelText('所属岗位')).toBeInTheDocument();
expect(screen.getByLabelText('状态')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '搜索' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '搜索' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '重置' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '重置' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '新建Agent' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '新建Agent' })).toBeInTheDocument();
...@@ -129,8 +130,8 @@ describe('AgentListPage', () => { ...@@ -129,8 +130,8 @@ describe('AgentListPage', () => {
const rows = screen.getAllByRole('row'); const rows = screen.getAllByRole('row');
expect(within(rows[1]).getByText('复盘Agent')).toBeInTheDocument(); expect(within(rows[1]).getByText('复盘Agent')).toBeInTheDocument();
expect(screen.getAllByText('已上架').length).toBeGreaterThan(0); expect(screen.getAllByText('已上架').length).toBeGreaterThan(0);
expect(screen.getByText('共 2 条')).toBeInTheDocument(); expect(screen.getByText('共 2 条数据')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '第 1 页' })).toHaveAttribute('aria-current', 'page'); expect(screen.getByText('1').closest('li')).toHaveClass('t-is-current');
}); });
it('only sends one initial list request per data source on first mount under StrictMode', async () => { it('only sends one initial list request per data source on first mount under StrictMode', async () => {
...@@ -151,18 +152,7 @@ describe('AgentListPage', () => { ...@@ -151,18 +152,7 @@ describe('AgentListPage', () => {
expect(getPositionTagList).toHaveBeenCalledTimes(1); expect(getPositionTagList).toHaveBeenCalledTimes(1);
}); });
it('keeps search controls at a consistent 200px width', async () => { it('keeps the search area rendered by the shared SearchFilter', async () => {
renderAgents();
await waitFor(() => {
expect(screen.getByTestId('agent-keyword-control')).toBeInTheDocument();
});
expect(screen.getByTestId('agent-keyword-control')).toHaveClass('w-[200px]');
expect(screen.getByTestId('agent-position-control')).toHaveClass('w-[200px]');
expect(screen.getByTestId('agent-status-control')).toHaveClass('w-[200px]');
});
it('lays out search fields as label-control rows with actions on the right', async () => {
renderAgents(); renderAgents();
await waitFor(() => { await waitFor(() => {
...@@ -170,21 +160,12 @@ describe('AgentListPage', () => { ...@@ -170,21 +160,12 @@ describe('AgentListPage', () => {
}); });
const toolbar = screen.getByTestId('agent-search-toolbar'); const toolbar = screen.getByTestId('agent-search-toolbar');
const keywordField = screen.getByTestId('agent-keyword-field'); expect(toolbar).toHaveClass('rounded-[var(--gl-radius-md)]', 'p-6');
const positionField = screen.getByTestId('agent-position-field'); expect(within(toolbar).getAllByText('Agent名称').length).toBeGreaterThan(0);
const statusField = screen.getByTestId('agent-status-field'); expect(within(toolbar).getAllByText('所属岗位').length).toBeGreaterThan(0);
const actionGroup = screen.getByTestId('agent-search-actions'); expect(within(toolbar).getAllByText('状态').length).toBeGreaterThan(0);
expect(within(toolbar).getByRole('button', { name: '搜索' })).toBeInTheDocument();
expect(toolbar).toHaveClass('justify-between'); expect(within(toolbar).getByRole('button', { name: '重置' })).toBeInTheDocument();
expect(keywordField).toHaveClass('flex', 'items-center');
expect(positionField).toHaveClass('flex', 'items-center');
expect(statusField).toHaveClass('flex', 'items-center');
expect(positionField.tagName).toBe('DIV');
expect(statusField.tagName).toBe('DIV');
expect(within(keywordField).getByText('Agent名称:')).toHaveClass('shrink-0');
expect(actionGroup).toHaveClass('ml-auto', 'justify-end');
expect(within(actionGroup).getByRole('button', { name: '搜索' })).toBeInTheDocument();
expect(within(actionGroup).getByRole('button', { name: '重置' })).toBeInTheDocument();
}); });
it('filters only after search submission and resets to the first page', async () => { it('filters only after search submission and resets to the first page', async () => {
...@@ -194,11 +175,11 @@ describe('AgentListPage', () => { ...@@ -194,11 +175,11 @@ describe('AgentListPage', () => {
expect(screen.getByText('复盘Agent')).toBeInTheDocument(); expect(screen.getByText('复盘Agent')).toBeInTheDocument();
}); });
fireEvent.change(screen.getByLabelText('搜索Agent名称'), { target: { value: '复盘' } }); fireEvent.change(screen.getByLabelText('Agent名称'), { target: { value: '复盘' } });
// Select 值变化需要等待 // Select 值变化需要等待
await waitFor(() => { await waitFor(() => {
fireEvent.click(screen.getByRole('combobox', { name: '岗位筛选' })); fireEvent.click(screen.getByLabelText('所属岗位'));
}); });
fireEvent.click(getSelectOption('客服岗')); fireEvent.click(getSelectOption('客服岗'));
...@@ -211,7 +192,7 @@ describe('AgentListPage', () => { ...@@ -211,7 +192,7 @@ describe('AgentListPage', () => {
// 搜索提交后,URL 参数更新,需要等待 API 返回新数据 // 搜索提交后,URL 参数更新,需要等待 API 返回新数据
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('button', { name: '第 1 页' })).toHaveAttribute('aria-current', 'page'); expect(screen.getByText('1').closest('li')).toHaveClass('t-is-current');
}); });
}); });
...@@ -219,31 +200,35 @@ describe('AgentListPage', () => { ...@@ -219,31 +200,35 @@ describe('AgentListPage', () => {
renderAgents(); renderAgents();
await waitFor(() => { await waitFor(() => {
expect(screen.getByLabelText('每页条数')).toBeInTheDocument(); expect(screen.getByDisplayValue('10 条/页')).toBeInTheDocument();
}); });
expect(screen.getByLabelText('每页条数')).toHaveValue('10'); await act(async () => {
fireEvent.click(screen.getByDisplayValue('10 条/页'));
fireEvent.change(screen.getByRole('combobox', { name: '每页条数' }), { target: { value: '20' } }); });
await waitFor(() => expect(getSelectOption('20 条/页')).toBeInTheDocument());
await act(async () => {
fireEvent.click(getSelectOption('20 条/页'));
});
expect(screen.getByLabelText('每页条数')).toHaveValue('20'); expect(screen.getByDisplayValue('20 条/页')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '第 1 页' })).toHaveAttribute('aria-current', 'page'); expect(screen.getByText('1').closest('li')).toHaveClass('t-is-current');
}); });
it('uses the 全部 position option as the reset entry and hides the extra clear button', async () => { it('uses the 全部 position option as the reset entry and hides the extra clear button', async () => {
renderAgents(); renderAgents();
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('combobox', { name: '岗位筛选' })).toBeInTheDocument(); expect(screen.getByLabelText('所属岗位')).toBeInTheDocument();
}); });
fireEvent.click(screen.getByRole('combobox', { name: '岗位筛选' })); fireEvent.click(screen.getByLabelText('所属岗位'));
expect(getSelectOption('全部')).toBeInTheDocument(); expect(getSelectOption('全部')).toBeInTheDocument();
fireEvent.click(getSelectOption('客服岗')); fireEvent.click(getSelectOption('客服岗'));
fireEvent.click(screen.getByRole('button', { name: '搜索' })); fireEvent.click(screen.getByRole('button', { name: '搜索' }));
await waitFor(() => { await waitFor(() => {
expect(screen.queryByRole('button', { name: '清空岗位筛选' })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: '清空所属岗位' })).not.toBeInTheDocument();
}); });
expect(screen.queryByText('清空')).not.toBeInTheDocument(); expect(screen.queryByText('清空')).not.toBeInTheDocument();
}); });
...@@ -256,7 +241,17 @@ describe('AgentListPage', () => { ...@@ -256,7 +241,17 @@ describe('AgentListPage', () => {
}); });
const reviewRow = screen.getByRole('row', { name: /复盘Agent/ }); const reviewRow = screen.getByRole('row', { name: /复盘Agent/ });
fireEvent.click(within(reviewRow).getByRole('button', { name: '删除复盘Agent' })); const viewButton = within(reviewRow).getByRole('button', { name: '查看复盘Agent详情' });
const editButton = within(reviewRow).getByRole('button', { name: '编辑复盘Agent' });
const disableButton = within(reviewRow).getByRole('button', { name: '停用复盘Agent' });
const deleteButton = within(reviewRow).getByRole('button', { name: '删除复盘Agent' });
expect(viewButton).toHaveClass('t-button--theme-primary', 't-button--variant-text');
expect(editButton).toHaveClass('t-button--theme-primary', 't-button--variant-text');
expect(disableButton).toHaveClass('t-button--theme-primary', 't-button--variant-text');
expect(deleteButton).toHaveClass('t-button--theme-primary', 't-button--variant-text');
fireEvent.click(deleteButton);
expect(screen.getByRole('dialog', { name: '确认删除 Agent "复盘Agent"?' })).toBeInTheDocument(); expect(screen.getByRole('dialog', { name: '确认删除 Agent "复盘Agent"?' })).toBeInTheDocument();
expect(screen.getByText(/企微员工会从所有已关联群中退出/)).toBeInTheDocument(); expect(screen.getByText(/企微员工会从所有已关联群中退出/)).toBeInTheDocument();
...@@ -268,18 +263,12 @@ describe('AgentListPage', () => { ...@@ -268,18 +263,12 @@ describe('AgentListPage', () => {
renderAgents(); renderAgents();
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument(); expect(screen.getByText('请求失败')).toBeInTheDocument();
}); });
expect(screen.getByRole('button', { name: '重试' })).toBeInTheDocument(); expect(screen.queryByText('请检查网络连接后重试')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
expect(screen.queryByText('暂无数据')).not.toBeInTheDocument(); expect(screen.queryByText('暂无数据')).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: '退出登录' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '退出登录' })).toBeInTheDocument();
vi.mocked(getAgentList).mockResolvedValueOnce({ list: mockAgents, total: 2, page: 1, page_size: 10 });
fireEvent.click(screen.getByRole('button', { name: '重试' }));
await waitFor(() => {
expect(screen.getByText('复盘Agent')).toBeInTheDocument();
});
}); });
it('renders 所属岗位 from position_names array', async () => { it('renders 所属岗位 from position_names array', async () => {
...@@ -602,7 +591,7 @@ describe('AgentListPage', () => { ...@@ -602,7 +591,7 @@ describe('AgentListPage', () => {
renderAgents(); renderAgents();
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument(); expect(screen.getByText('请求失败')).toBeInTheDocument();
}); });
expect(reportPageView).not.toHaveBeenCalled(); expect(reportPageView).not.toHaveBeenCalled();
...@@ -656,7 +645,7 @@ describe('AgentListPage', () => { ...@@ -656,7 +645,7 @@ describe('AgentListPage', () => {
expect(screen.getByText('复盘Agent')).toBeInTheDocument(); expect(screen.getByText('复盘Agent')).toBeInTheDocument();
}); });
fireEvent.change(screen.getByLabelText('搜索Agent名称'), { target: { value: '复盘' } }); fireEvent.change(screen.getByLabelText('Agent名称'), { target: { value: '复盘' } });
vi.clearAllMocks(); vi.clearAllMocks();
fireEvent.click(screen.getByRole('button', { name: '搜索' })); fireEvent.click(screen.getByRole('button', { name: '搜索' }));
...@@ -672,10 +661,10 @@ describe('AgentListPage', () => { ...@@ -672,10 +661,10 @@ describe('AgentListPage', () => {
renderAgents(); renderAgents();
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('combobox', { name: '岗位筛选' })).toBeInTheDocument(); expect(screen.getByLabelText('所属岗位')).toBeInTheDocument();
}); });
fireEvent.click(screen.getByRole('combobox', { name: '岗位筛选' })); fireEvent.click(screen.getByLabelText('所属岗位'));
fireEvent.click(getSelectOption('客服岗')); fireEvent.click(getSelectOption('客服岗'));
vi.clearAllMocks(); vi.clearAllMocks();
......
import { useMemo, useState } from 'react'; import { useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button, Input, Modal, Pagination, Select, StatePlaceholder, Table, Tag } from '../../../packages/ui/src'; import { BusinessTable, SearchFilter, type BusinessTableColumn, type SearchFilterValues } from '@gl/business-components';
import { Button, Dialog, Tag } from 'tdesign-react';
import { getAgentList, import { getAgentList,
deleteAgent, deleteAgent,
updateAgentStatus, updateAgentStatus,
...@@ -33,22 +34,23 @@ function AgentActions({ agent, routeSearch, onRefresh }: { agent: AgentListItem; ...@@ -33,22 +34,23 @@ function AgentActions({ agent, routeSearch, onRefresh }: { agent: AgentListItem;
<Button <Button
aria-label={`查看${agent.name}详情`} aria-label={`查看${agent.name}详情`}
size="small" size="small"
theme="primary"
variant="text" variant="text"
onClick={() => navigate(`/agents${routeSearch ? `${routeSearch}&detail=${agent.agent_id}` : `?detail=${agent.agent_id}`}`)} onClick={() => navigate(`/agents${routeSearch ? `${routeSearch}&detail=${agent.agent_id}` : `?detail=${agent.agent_id}`}`)}
> >
查看 查看
</Button> </Button>
<Button aria-label={`编辑${agent.name}`} size="small" variant="text" onClick={() => navigate(`/agents/${agent.agent_id}/edit${routeSearch}`)}>编辑</Button> <Button aria-label={`编辑${agent.name}`} size="small" theme="primary" variant="text" onClick={() => navigate(`/agents/${agent.agent_id}/edit${routeSearch}`)}>编辑</Button>
{operations.includes('disable') ? ( {operations.includes('disable') ? (
<Button aria-label={`停用${agent.name}`} size="small" variant="text" onClick={() => setStatusOpen({ action: 'disable' })}>停用</Button> <Button aria-label={`停用${agent.name}`} size="small" theme="primary" variant="text" onClick={() => setStatusOpen({ action: 'disable' })}>停用</Button>
) : null} ) : null}
{operations.includes('enable') ? ( {operations.includes('enable') ? (
<Button aria-label={`上架${agent.name}`} size="small" variant="text" onClick={() => setStatusOpen({ action: 'enable' })}>上架</Button> <Button aria-label={`上架${agent.name}`} size="small" theme="primary" variant="text" onClick={() => setStatusOpen({ action: 'enable' })}>上架</Button>
) : null} ) : null}
{operations.includes('delete') ? ( {operations.includes('delete') ? (
<> <>
<Button aria-label={`删除${agent.name}`} size="small" variant="text" onClick={() => setDeleteOpen(true)}>删除</Button> <Button aria-label={`删除${agent.name}`} size="small" theme="primary" variant="text" onClick={() => setDeleteOpen(true)}>删除</Button>
<Modal open={deleteOpen} title={`确认删除 Agent "${agent.name}"?`} onCancel={() => setDeleteOpen(false)} onOk={async () => { <Dialog visible={deleteOpen} header={`确认删除 Agent "${agent.name}"?`} {...{ role: 'dialog', 'aria-label': `确认删除 Agent "${agent.name}"?` }} cancelBtn="取消" confirmBtn="确定" destroyOnClose onClose={() => setDeleteOpen(false)} onConfirm={async () => {
try { try {
await deleteAgent(agent.agent_id); await deleteAgent(agent.agent_id);
setDeleteOpen(false); setDeleteOpen(false);
...@@ -60,15 +62,19 @@ function AgentActions({ agent, routeSearch, onRefresh }: { agent: AgentListItem; ...@@ -60,15 +62,19 @@ function AgentActions({ agent, routeSearch, onRefresh }: { agent: AgentListItem;
<p className="m-0 max-w-[360px] leading-[var(--gl-line-height-md)] text-[var(--gl-color-text-secondary)]"> <p className="m-0 max-w-[360px] leading-[var(--gl-line-height-md)] text-[var(--gl-color-text-secondary)]">
该 Agent 的企微员工会从所有已关联群中退出、官网展示配置会被清理、渠道活码 Agent 列表中不再出现该 Agent、关联的岗位标签不受影响 该 Agent 的企微员工会从所有已关联群中退出、官网展示配置会被清理、渠道活码 Agent 列表中不再出现该 Agent、关联的岗位标签不受影响
</p> </p>
</Modal> </Dialog>
</> </>
) : null} ) : null}
{statusOpen ? ( {statusOpen ? (
<Modal <Dialog
open visible
title={`确认${statusOpen.action === 'enable' ? '上架' : '停用'}"${agent.name}"?`} header={`确认${statusOpen.action === 'enable' ? '上架' : '停用'}"${agent.name}"?`}
onCancel={() => setStatusOpen(null)} {...{ role: 'dialog', 'aria-label': `确认${statusOpen.action === 'enable' ? '上架' : '停用'}"${agent.name}"?` }}
onOk={async () => { cancelBtn="取消"
confirmBtn="确定"
destroyOnClose
onClose={() => setStatusOpen(null)}
onConfirm={async () => {
try { try {
await updateAgentStatus(agent.agent_id, statusOpen.action); await updateAgentStatus(agent.agent_id, statusOpen.action);
trackCustomEvent({ event_type: 'status_change', event_data: { page: 'agent_list', agent_id: agent.agent_id, action: statusOpen.action } }); trackCustomEvent({ event_type: 'status_change', event_data: { page: 'agent_list', agent_id: agent.agent_id, action: statusOpen.action } });
...@@ -82,7 +88,7 @@ function AgentActions({ agent, routeSearch, onRefresh }: { agent: AgentListItem; ...@@ -82,7 +88,7 @@ function AgentActions({ agent, routeSearch, onRefresh }: { agent: AgentListItem;
<p className="m-0 max-w-[360px] leading-[var(--gl-line-height-md)] text-[var(--gl-color-text-secondary)]"> <p className="m-0 max-w-[360px] leading-[var(--gl-line-height-md)] text-[var(--gl-color-text-secondary)]">
{statusOpen.action === 'enable' ? '上架后 Agent 将恢复可用状态。' : '停用后 Agent 将不可继续使用,请确认是否继续。'} {statusOpen.action === 'enable' ? '上架后 Agent 将恢复可用状态。' : '停用后 Agent 将不可继续使用,请确认是否继续。'}
</p> </p>
</Modal> </Dialog>
) : null} ) : null}
</span> </span>
); );
...@@ -143,30 +149,40 @@ export function AgentListPage() { ...@@ -143,30 +149,40 @@ export function AgentListPage() {
pageSize: routeState.pageSize, pageSize: routeState.pageSize,
}); });
const submitFilters = () => { const submitFilters = (filterValues: SearchFilterValues = {
keyword,
positionId: positionId ?? '',
status: status === 'all' ? '' : status,
}) => {
const nextKeyword = String(filterValues.keyword ?? '');
const nextPositionId = String(filterValues.positionId ?? '') || undefined;
const nextStatus = (String(filterValues.status ?? '') || 'all') as AgentStatus | 'all';
const events: { event_type: string; event_data: Record<string, unknown> }[] = []; const events: { event_type: string; event_data: Record<string, unknown> }[] = [];
if (keyword) { if (nextKeyword) {
events.push({ event_type: 'search', event_data: { page: 'agent_list', filter_type: 'keyword', filter_value: keyword } }); events.push({ event_type: 'search', event_data: { page: 'agent_list', filter_type: 'keyword', filter_value: nextKeyword } });
} }
if (positionId) { if (nextPositionId) {
const positionName = positionTags.find((tag) => String(tag.tag_id) === positionId)?.name; const positionName = positionTags.find((tag) => String(tag.tag_id) === nextPositionId)?.name;
events.push({ event_type: 'filter', event_data: { page: 'agent_list', filter_type: 'position', filter_value: positionName ?? positionId } }); events.push({ event_type: 'filter', event_data: { page: 'agent_list', filter_type: 'position', filter_value: positionName ?? nextPositionId } });
} }
if (status !== 'all') { if (nextStatus !== 'all') {
events.push({ event_type: 'filter', event_data: { page: 'agent_list', filter_type: 'status', filter_value: status } }); events.push({ event_type: 'filter', event_data: { page: 'agent_list', filter_type: 'status', filter_value: nextStatus } });
} }
if (events.length > 0) { if (events.length > 0) {
trackCustomEvent(...events); trackCustomEvent(...events);
} }
setKeyword(nextKeyword);
setPositionId(nextPositionId);
setStatus(nextStatus);
setSearchParams(buildAgentListSearch({ setSearchParams(buildAgentListSearch({
keyword, keyword: nextKeyword,
positionId, positionId: nextPositionId,
status, status: nextStatus,
page: 1, page: 1,
pageSize: routeState.pageSize, pageSize: routeState.pageSize,
})); }));
...@@ -185,11 +201,11 @@ export function AgentListPage() { ...@@ -185,11 +201,11 @@ export function AgentListPage() {
})); }));
}; };
const columns = [ const columns: BusinessTableColumn<AgentListItem>[] = [
{ {
title: 'Agent名称', title: 'Agent名称',
key: 'name', colKey: 'name',
render: (_: unknown, agent: AgentListItem) => ( cell: ({ row: agent }) => (
<div className="grid gap-0.5"> <div className="grid gap-0.5">
<strong>{agent.name}</strong> <strong>{agent.name}</strong>
<span className="text-xs text-[var(--gl-color-text-secondary)]">ID: {agent.agent_id}</span> <span className="text-xs text-[var(--gl-color-text-secondary)]">ID: {agent.agent_id}</span>
...@@ -198,8 +214,8 @@ export function AgentListPage() { ...@@ -198,8 +214,8 @@ export function AgentListPage() {
}, },
{ {
title: '所属岗位', title: '所属岗位',
key: 'position_names', colKey: 'position_names',
render: (_: unknown, agent: AgentListItem) => { cell: ({ row: agent }) => {
// 管家 Agent 固定显示 "系统调度" // 管家 Agent 固定显示 "系统调度"
if (agent.is_steward) { if (agent.is_steward) {
return <Tag>系统调度</Tag>; return <Tag>系统调度</Tag>;
...@@ -212,14 +228,14 @@ export function AgentListPage() { ...@@ -212,14 +228,14 @@ export function AgentListPage() {
) : '-'; ) : '-';
}, },
}, },
{ title: '状态', dataIndex: 'status', render: (value: unknown) => <Tag status={statusTag(value as AgentStatus)}>{statusText(value as AgentStatus)}</Tag> }, { title: '状态', colKey: 'status', cell: ({ row }) => <Tag theme={statusTag(row.status)} variant="light">{statusText(row.status)}</Tag> },
{ title: '绑定群数', key: 'bound_group_count', render: (_: unknown, agent: AgentListItem) => agent.bound_group_count ?? 0 }, { title: '绑定群数', colKey: 'bound_group_count', cell: ({ row }) => row.bound_group_count ?? 0 },
{ title: '绑定Skill数', key: 'skill_count', render: (_: unknown, agent: AgentListItem) => agent.skill_codes?.length ?? 0 }, { title: '绑定Skill数', colKey: 'skill_count', cell: ({ row }) => row.skill_codes?.length ?? 0 },
{ title: '创建时间', dataIndex: 'created_at' }, { title: '创建时间', colKey: 'created_at' },
{ {
title: '操作', title: '操作',
key: 'actions', colKey: 'actions',
render: (_: unknown, agent: AgentListItem) => <AgentActions agent={agent} routeSearch={routeSearch} onRefresh={fetchList} />, cell: ({ row: agent }) => <AgentActions agent={agent} routeSearch={routeSearch} onRefresh={fetchList} />,
}, },
]; ];
...@@ -230,104 +246,77 @@ export function AgentListPage() { ...@@ -230,104 +246,77 @@ export function AgentListPage() {
<h2 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">Agent管理</h2> <h2 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">Agent管理</h2>
<p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">管理岗位 Agent 列表与状态</p> <p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">管理岗位 Agent 列表与状态</p>
</div> </div>
<Button variant="primary" onClick={() => { <Button theme="primary" onClick={() => {
trackCustomEvent({ event_type: 'click_create', event_data: { page: 'agent_list' } }); trackCustomEvent({ event_type: 'click_create', event_data: { page: 'agent_list' } });
navigate(`/agents/new${routeSearch}`); navigate(`/agents/new${routeSearch}`);
}}>新建Agent</Button> }}>新建Agent</Button>
</header> </header>
<div className="flex flex-wrap items-center justify-between gap-4 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6" data-testid="agent-search-toolbar"> <SearchFilter
<div className="flex flex-wrap items-center gap-x-6 gap-y-4"> className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6"
<div className="flex items-center gap-2 text-sm" data-testid="agent-keyword-field"> fields={[
<span className="shrink-0">Agent名称:</span> {
<span className="w-[200px]" data-testid="agent-keyword-control"> key: 'keyword',
<Input label: 'Agent名称',
aria-label="搜索Agent名称" type: 'input',
className="w-full" value: keyword,
placeholder="搜索 Agent 名称" allowClear: true,
value={keyword} onChange: setKeyword,
allowClear },
onChange={setKeyword} {
onKeyDown={(event) => { key: 'positionId',
if (event.key === 'Enter') submitFilters(); label: '所属岗位',
}} type: 'select',
/> options: positionTags.map((tag) => ({ label: tag.name, value: String(tag.tag_id) })),
</span> value: positionId ?? '',
</div> onChange: (value) => setPositionId(value || undefined),
<div className="flex items-center gap-2 text-sm" data-testid="agent-position-field"> },
<span className="shrink-0">所属岗位:</span> {
<span className="w-[200px]" data-testid="agent-position-control"> key: 'status',
<Select label: '状态',
aria-label="岗位筛选" type: 'select',
options={[ options: [
{ label: '全部', value: 'all' }, { label: '已上架', value: 'enable' },
...positionTags.map((tag) => ({ label: tag.name, value: String(tag.tag_id) })), { label: '已停用', value: 'disable' },
]} ],
placeholder="全部" value: status === 'all' ? '' : status,
value={positionId} onChange: (value) => setStatus((value || 'all') as AgentStatus | 'all'),
onChange={(value) => setPositionId(value === 'all' ? undefined : value)} },
/> ]}
</span> data-testid="agent-search-toolbar"
</div> onReset={resetFilters}
<div className="flex items-center gap-2 text-sm" data-testid="agent-status-field"> onSearch={submitFilters}
<span className="shrink-0">状态:</span> />
<span className="w-[200px]" data-testid="agent-status-control">
<Select
aria-label="状态筛选"
options={[
{ label: '全部', value: 'all' },
{ label: '已上架', value: 'enable' },
{ label: '已停用', value: 'disable' },
]}
value={status}
onChange={(value) => setStatus((value as AgentStatus | 'all') ?? 'all')}
/>
</span>
</div>
</div>
<div className="ml-auto flex items-center justify-end gap-3" data-testid="agent-search-actions">
<Button variant="primary" onClick={submitFilters}>搜索</Button>
<Button variant="outline" onClick={resetFilters}>重置</Button>
</div>
</div>
<div className="grid gap-6 overflow-x-auto rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6"> <div className="grid gap-6 overflow-x-auto rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6">
{loadError ? ( <BusinessTable
<StatePlaceholder rowKey="agent_id"
state="error" columns={columns}
title="加载失败" data={listData.items}
description="Agent 列表请求失败,请重试" loading={loading}
primaryAction={<Button size="small" onClick={fetchList}>重试</Button>} error={loadError}
/> hasFilter={hasFilter}
) : ( filteredEmptyState={{
<> onAction: resetFilters,
<Table }}
rowKey="agent_id" errorState={{
columns={columns} onRetry: fetchList,
dataSource={listData.items} }}
loading={loading} pagination={{
empty={{ current: routeState.page,
description: hasFilter ? '未找到匹配结果' : '当前还没有 Agent', pageSize: routeState.pageSize,
action: hasFilter ? <Button size="small" onClick={resetFilters}>清空筛选</Button> : undefined, total: listData.total,
}} onChange: ({ current, pageSize }) => {
/> setSearchParams(buildAgentListSearch({
{listData.items.length === 0 && hasFilter ? <StatePlaceholder state="filtered-empty" /> : null} keyword: routeState.keyword,
<Pagination positionId,
current={routeState.page} status,
pageSize={routeState.pageSize} page: current,
total={listData.total} pageSize,
onChange={(nextPage, nextPageSize) => { }));
setSearchParams(buildAgentListSearch({ },
keyword: routeState.keyword, }}
positionId, />
status,
page: nextPage,
pageSize: nextPageSize,
}));
}}
/>
</>
)}
</div> </div>
<AgentDetailDrawer agentId={routeState.detail} routeState={routeState} /> <AgentDetailDrawer agentId={routeState.detail} routeState={routeState} />
......
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
...@@ -215,9 +215,11 @@ describe('Channel code create page', () => { ...@@ -215,9 +215,11 @@ describe('Channel code create page', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('heading', { name: '新增员工渠道活码' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '新增员工渠道活码' })).toBeInTheDocument();
}); });
expect(screen.getByRole('button', { name: '返回' })).toBeInTheDocument(); const pageHeader = screen.getByRole('heading', { name: '新增员工渠道活码' }).closest('header') as HTMLElement;
expect(screen.getByRole('button', { name: '取消' })).toBeInTheDocument(); expect(pageHeader).toHaveClass('sticky', 'top-0', 'z-10');
expect(screen.getByRole('button', { name: '保存' })).toBeInTheDocument(); expect(within(pageHeader).getByRole('button', { name: '返回' })).toBeInTheDocument();
expect(within(pageHeader).queryByRole('button', { name: '取消' })).not.toBeInTheDocument();
expect(within(pageHeader).getByRole('button', { name: '保存' })).toBeInTheDocument();
}); });
// Legacy test: status switch no longer rendered (updated to not check status) // Legacy test: status switch no longer rendered (updated to not check status)
...@@ -426,7 +428,7 @@ describe('Channel code create page', () => { ...@@ -426,7 +428,7 @@ describe('Channel code create page', () => {
expect(statusSwitch).not.toBeChecked(); expect(statusSwitch).not.toBeChecked();
}); });
it('cancel returns to list without saving', async () => { it('header return navigates back to list without saving', async () => {
vi.mocked(getPositionTagList).mockResolvedValueOnce({ vi.mocked(getPositionTagList).mockResolvedValueOnce({
list: [], list: [],
total: 0, total: 0,
...@@ -451,7 +453,8 @@ describe('Channel code create page', () => { ...@@ -451,7 +453,8 @@ describe('Channel code create page', () => {
}); });
fireEvent.change(screen.getByLabelText('活码名称'), { target: { value: '测试活码' } }); fireEvent.change(screen.getByLabelText('活码名称'), { target: { value: '测试活码' } });
fireEvent.click(screen.getByRole('button', { name: '取消' })); const pageHeader = screen.getByRole('heading', { name: '新增员工渠道活码' }).closest('header') as HTMLElement;
fireEvent.click(within(pageHeader).getByRole('button', { name: '返回' }));
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('heading', { name: '渠道活码管理' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '渠道活码管理' })).toBeInTheDocument();
...@@ -1157,7 +1160,7 @@ describe('Channel code create page', () => { ...@@ -1157,7 +1160,7 @@ describe('Channel code create page', () => {
await waitFor(() => expect(createChannelQRCode).toHaveBeenCalled()); await waitFor(() => expect(createChannelQRCode).toHaveBeenCalled());
// 应该显示成功消息 // 应该显示成功消息
await waitFor(() => expect(screen.getByText('保存成功')).toBeInTheDocument()); await waitFor(() => expect(screen.getAllByText('保存成功').length).toBeGreaterThan(0));
// 最终应该跳转到列表页(可能需要等待 2 秒延迟) // 最终应该跳转到列表页(可能需要等待 2 秒延迟)
await waitFor(() => expect(screen.getByRole('heading', { name: '渠道活码管理' })).toBeInTheDocument(), { timeout: 5000 }); await waitFor(() => expect(screen.getByRole('heading', { name: '渠道活码管理' })).toBeInTheDocument(), { timeout: 5000 });
...@@ -1272,7 +1275,7 @@ describe('Channel code edit page', () => { ...@@ -1272,7 +1275,7 @@ describe('Channel code edit page', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('heading', { name: '编辑员工渠道活码' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '编辑员工渠道活码' })).toBeInTheDocument();
}); });
expect(screen.getByDisplayValue('店销顾问渠道活码')).toBeInTheDocument(); await waitFor(() => expect(screen.getByLabelText('活码名称')).toHaveValue('店销顾问渠道活码'));
}); });
it('always fetches detail when entering edit page even if route state already has code data', async () => { it('always fetches detail when entering edit page even if route state already has code data', async () => {
...@@ -1317,9 +1320,11 @@ describe('Channel code edit page', () => { ...@@ -1317,9 +1320,11 @@ describe('Channel code edit page', () => {
await waitFor(() => { await waitFor(() => {
expect(getChannelQRCodeDetail).toHaveBeenCalledWith(1); expect(getChannelQRCodeDetail).toHaveBeenCalledWith(1);
}); });
expect(screen.getByDisplayValue('接口返回的活码名称')).toBeInTheDocument(); await waitFor(() => {
expect(screen.getByDisplayValue('接口备注')).toBeInTheDocument(); expect(screen.getByLabelText('活码名称')).toHaveValue('接口返回的活码名称');
expect(screen.getByDisplayValue('接口欢迎语')).toBeInTheDocument(); expect(screen.getByLabelText('活码描述')).toHaveValue('接口备注');
expect(screen.getByLabelText('自动欢迎语')).toHaveValue('接口欢迎语');
});
}); });
it('position and derived fields are readonly or display-only', async () => { it('position and derived fields are readonly or display-only', async () => {
...@@ -1376,7 +1381,7 @@ describe('Channel code edit page', () => { ...@@ -1376,7 +1381,7 @@ describe('Channel code edit page', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByLabelText('活码名称')).toBeInTheDocument(); expect(screen.getByLabelText('活码名称')).toBeInTheDocument();
}); });
expect(screen.getByDisplayValue('接口返回的活码名称')).toBeInTheDocument(); await waitFor(() => expect(screen.getByLabelText('活码名称')).toHaveValue('接口返回的活码名称'));
fireEvent.change(screen.getByLabelText('活码名称'), { target: { value: '更新后的活码名称' } }); fireEvent.change(screen.getByLabelText('活码名称'), { target: { value: '更新后的活码名称' } });
fireEvent.change(screen.getByLabelText('活码描述'), { target: { value: '更新后的描述' } }); fireEvent.change(screen.getByLabelText('活码描述'), { target: { value: '更新后的描述' } });
......
import { useState } from 'react'; import { useState } from 'react';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom'; import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Button, FormItem, Input, Select, StatePlaceholder, Textarea } from '../../../packages/ui/src'; import { StatePlaceholder } from '@gl/business-components';
import { Button } from 'tdesign-react';
import { FormItem, Input, Select, Textarea } from '../../components/TDesignAccessibleControls';
import { import {
getChannelQRCodeDetail, getChannelQRCodeDetail,
createChannelQRCode, createChannelQRCode,
...@@ -270,7 +272,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -270,7 +272,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
return ( return (
<section className="grid gap-6"> <section className="grid gap-6">
<header className="flex items-center justify-between gap-6 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6"> <header className="sticky top-0 z-10 flex items-center justify-between gap-6 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6">
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<Button variant="outline" onClick={goBackToList}>返回</Button> <Button variant="outline" onClick={goBackToList}>返回</Button>
<div> <div>
...@@ -282,10 +284,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -282,10 +284,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
</p> </p>
</div> </div>
</div> </div>
<div className="flex items-center gap-3"> <Button theme="primary" loading={saving} onClick={handleSave}>保存</Button>
<Button variant="outline" onClick={goBackToList}>取消</Button>
<Button variant="primary" loading={saving} onClick={handleSave}>保存</Button>
</div>
</header> </header>
{notice ? ( {notice ? (
...@@ -300,12 +299,13 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -300,12 +299,13 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
<div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10"> <div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10">
<div className="mx-auto grid max-w-[760px] gap-6"> <div className="mx-auto grid max-w-[760px] gap-6">
<FormItem label="活码名称" layout="horizontal" required error={errors.qrcode_name}> <FormItem label="活码名称" labelAlign="left" requiredMark status={errors.qrcode_name ? 'error' : undefined} tips={errors.qrcode_name}>
<Input <Input
aria-label="活码名称" aria-label="活码名称"
className={fieldWidthClassName} className={fieldWidthClassName}
maxLength={50} maxlength={50}
showCount allowInputOverMax
showLimitNumber
value={form.qrcode_name} value={form.qrcode_name}
onChange={(value) => setForm((current) => ({ ...current, qrcode_name: value }))} onChange={(value) => setForm((current) => ({ ...current, qrcode_name: value }))}
/> />
...@@ -313,7 +313,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -313,7 +313,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
{mode === 'create' ? ( {mode === 'create' ? (
<> <>
<FormItem label="对应岗位" layout="horizontal" required error={errors.position_code}> <FormItem label="对应岗位" labelAlign="left" requiredMark status={errors.position_code ? 'error' : undefined} tips={errors.position_code}>
<Select <Select
aria-label="对应岗位" aria-label="对应岗位"
className={fieldWidthClassName} className={fieldWidthClassName}
...@@ -328,7 +328,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -328,7 +328,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
const selectedPosition = positions.find((p) => p.code === value); const selectedPosition = positions.find((p) => p.code === value);
setForm((current) => ({ setForm((current) => ({
...current, ...current,
position_code: value ?? '', position_code: String(value ?? ''),
employee_id: '', employee_id: '',
employee_name: '', employee_name: '',
wechat_user_id: '', wechat_user_id: '',
...@@ -339,13 +339,13 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -339,13 +339,13 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
{form.position_code ? ( {form.position_code ? (
<> <>
<FormItem label="渠道编码" layout="horizontal"> <FormItem label="渠道编码" labelAlign="left">
<div className={fieldWidthClassName}> <div className={fieldWidthClassName}>
{form.position_code} {form.position_code}
</div> </div>
</FormItem> </FormItem>
<FormItem label="关联 Agent" layout="horizontal"> <FormItem label="关联 Agent" labelAlign="left">
<div className={fieldWidthClassName}> <div className={fieldWidthClassName}>
{(positions.find((p) => p.code === form.position_code)?.agents ?? []).map((a) => a.name).join('、') || '-'} {(positions.find((p) => p.code === form.position_code)?.agents ?? []).map((a) => a.name).join('、') || '-'}
</div> </div>
...@@ -353,7 +353,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -353,7 +353,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
</> </>
) : null} ) : null}
<FormItem label="承接员工" layout="horizontal" required error={errors.employee_id}> <FormItem label="承接员工" labelAlign="left" requiredMark status={errors.employee_id ? 'error' : undefined} tips={errors.employee_id}>
<Select <Select
aria-label="承接员工" aria-label="承接员工"
className={fieldWidthClassName} className={fieldWidthClassName}
...@@ -368,7 +368,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -368,7 +368,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
const selected = (employeeMounts?.employees ?? []).find((e) => e.employee_id === value); const selected = (employeeMounts?.employees ?? []).find((e) => e.employee_id === value);
setForm((current) => ({ setForm((current) => ({
...current, ...current,
employee_id: value ?? '', employee_id: String(value ?? ''),
employee_name: selected?.employee_name ?? '', employee_name: selected?.employee_name ?? '',
wechat_user_id: selected?.wechat_user_id ?? '', wechat_user_id: selected?.wechat_user_id ?? '',
position_code: selected?.position_code ?? current.position_code, position_code: selected?.position_code ?? current.position_code,
...@@ -381,7 +381,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -381,7 +381,7 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
{currentCode ? ( {currentCode ? (
<> <>
<FormItem label="对应岗位" layout="horizontal"> <FormItem label="对应岗位" labelAlign="left">
<Input <Input
aria-label="对应岗位" aria-label="对应岗位"
className={fieldWidthClassName} className={fieldWidthClassName}
...@@ -390,19 +390,19 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -390,19 +390,19 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
/> />
</FormItem> </FormItem>
<FormItem label="渠道编码" layout="horizontal"> <FormItem label="渠道编码" labelAlign="left">
<div className={fieldWidthClassName}> <div className={fieldWidthClassName}>
{currentCode.channel_code ?? ''} {currentCode.channel_code ?? ''}
</div> </div>
</FormItem> </FormItem>
<FormItem label="承接员工" layout="horizontal"> <FormItem label="承接员工" labelAlign="left">
<div className={fieldWidthClassName}> <div className={fieldWidthClassName}>
{currentCode.employee_name ?? ''} {currentCode.employee_name ?? ''}
</div> </div>
</FormItem> </FormItem>
<FormItem label="关联 Agent" layout="horizontal"> <FormItem label="关联 Agent" labelAlign="left">
<div className={fieldWidthClassName}> <div className={fieldWidthClassName}>
{(currentCode.agent_names ?? []).join('、') || '-'} {(currentCode.agent_names ?? []).join('、') || '-'}
</div> </div>
...@@ -410,25 +410,27 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) { ...@@ -410,25 +410,27 @@ export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
</> </>
) : null} ) : null}
<FormItem label="活码描述" layout="horizontal" error={errors.description}> <FormItem label="活码描述" labelAlign="left" status={errors.description ? 'error' : undefined} tips={errors.description}>
<Textarea <Textarea
aria-label="活码描述" aria-label="活码描述"
className={fieldWidthClassName} className={fieldWidthClassName}
maxLength={200} maxlength={200}
allowInputOverMax
rows={3} rows={3}
showCount count
value={form.description} value={form.description}
onChange={(value) => setForm((current) => ({ ...current, description: value }))} onChange={(value) => setForm((current) => ({ ...current, description: value }))}
/> />
</FormItem> </FormItem>
<FormItem label="自动欢迎语" layout="horizontal" error={errors.welcome_message}> <FormItem label="自动欢迎语" labelAlign="left" status={errors.welcome_message ? 'error' : undefined} tips={errors.welcome_message}>
<Textarea <Textarea
aria-label="自动欢迎语" aria-label="自动欢迎语"
className={fieldWidthClassName} className={fieldWidthClassName}
maxLength={500} maxlength={500}
allowInputOverMax
rows={3} rows={3}
showCount count
value={form.welcome_message} value={form.welcome_message}
onChange={(value) => setForm((current) => ({ ...current, welcome_message: value }))} onChange={(value) => setForm((current) => ({ ...current, welcome_message: value }))}
/> />
......
...@@ -89,6 +89,12 @@ function renderChannelCodes(path = '/channel-codes') { ...@@ -89,6 +89,12 @@ function renderChannelCodes(path = '/channel-codes') {
); );
} }
function getSelectOption(name: string) {
const option = screen.getAllByText(name).map((element) => element.closest('li')).find(Boolean);
if (!option) throw new Error(`Select option ${name} was not found`);
return option as HTMLElement;
}
describe('Channel code list page', () => { describe('Channel code list page', () => {
beforeEach(() => { beforeEach(() => {
window.localStorage.clear(); window.localStorage.clear();
...@@ -121,26 +127,27 @@ describe('Channel code list page', () => { ...@@ -121,26 +127,27 @@ describe('Channel code list page', () => {
renderChannelCodes(); renderChannelCodes();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('活码名称:')).toBeInTheDocument(); expect(screen.getAllByText('活码名称').length).toBeGreaterThan(0);
}); });
expect(screen.getByLabelText('活码名称')).toBeInTheDocument(); expect(screen.getByLabelText('活码名称')).toBeInTheDocument();
expect(screen.getByText('状态:')).toBeInTheDocument(); expect(screen.getAllByText('状态').length).toBeGreaterThan(0);
expect(screen.getByRole('combobox', { name: '状态' })).toBeInTheDocument(); expect(screen.getByLabelText('状态')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '搜索' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '搜索' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '重置' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '重置' })).toBeInTheDocument();
expect(screen.getByPlaceholderText('搜索活码名称')).toBeInTheDocument();
}); });
it('renders table columns: name, position, channel code, employee, agents, status, created time, actions', async () => { it('renders table columns: name, position, channel code, employee, agents, status, created time, actions', async () => {
renderChannelCodes(); renderChannelCodes();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('活码名称')).toBeInTheDocument(); expect(screen.getAllByText('活码名称').length).toBeGreaterThan(0);
}); });
expect(screen.getByText('对应岗位')).toBeInTheDocument(); expect(screen.getByText('对应岗位')).toBeInTheDocument();
expect(screen.getByText('渠道编码')).toBeInTheDocument(); expect(screen.getByText('渠道编码')).toBeInTheDocument();
expect(screen.getByText('承接员工')).toBeInTheDocument(); expect(screen.getByText('承接员工')).toBeInTheDocument();
expect(screen.getByText('关联 Agent')).toBeInTheDocument(); expect(screen.getByText('关联 Agent')).toBeInTheDocument();
expect(screen.getByText('状态')).toBeInTheDocument(); expect(screen.getAllByText('状态').length).toBeGreaterThan(0);
expect(screen.getByText('创建时间')).toBeInTheDocument(); expect(screen.getByText('创建时间')).toBeInTheDocument();
expect(screen.getByText('操作')).toBeInTheDocument(); expect(screen.getByText('操作')).toBeInTheDocument();
}); });
...@@ -160,7 +167,7 @@ describe('Channel code list page', () => { ...@@ -160,7 +167,7 @@ describe('Channel code list page', () => {
const statusTag = within(firstRow).getByText('启用'); const statusTag = within(firstRow).getByText('启用');
// 状态应该使用 Tag 标签组件 // 状态应该使用 Tag 标签组件
expect(statusTag.closest('span')?.className ?? '').toContain('tag'); expect(statusTag.closest('.t-tag')).toBeInTheDocument();
}); });
it('supports keyword search and reset', async () => { it('supports keyword search and reset', async () => {
...@@ -200,27 +207,39 @@ describe('Channel code list page', () => { ...@@ -200,27 +207,39 @@ describe('Channel code list page', () => {
}); });
}); });
it('supports status filter dropdown', async () => { it('submits status filtering only after clicking search', async () => {
renderChannelCodes(); renderChannelCodes();
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('combobox', { name: '状态' })).toBeInTheDocument(); expect(screen.getByLabelText('状态')).toBeInTheDocument();
}); });
const statusSelect = screen.getByRole('combobox', { name: '状态' }); const statusSelect = screen.getByLabelText('状态');
expect(statusSelect).toBeInTheDocument();
fireEvent.click(statusSelect); fireEvent.click(statusSelect);
// Dropdown should open - just verify the select is interactive fireEvent.click(getSelectOption('停用'));
expect(statusSelect).not.toHaveAttribute('aria-disabled', 'true');
expect(getChannelQRCodeList).toHaveBeenCalledTimes(1);
vi.mocked(getChannelQRCodeList).mockResolvedValueOnce({
list: mockChannelCodes.filter((code) => code.status === 'disable'),
total: 1,
page: 1,
page_size: 10,
});
fireEvent.click(screen.getByRole('button', { name: '搜索' }));
await waitFor(() => {
expect(getChannelQRCodeList).toHaveBeenLastCalledWith(expect.objectContaining({ status: 'disable' }));
});
}); });
it('renders pagination with total count', async () => { it('renders pagination with total count', async () => {
renderChannelCodes(); renderChannelCodes();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText(`共 ${mockChannelCodes.length} 条`)).toBeInTheDocument(); expect(screen.getAllByText(`共 ${mockChannelCodes.length} 条数据`).length).toBeGreaterThan(0);
}); });
expect(screen.getByRole('combobox', { name: '每页条数' })).toBeInTheDocument(); expect(screen.getByDisplayValue('10 条/页')).toBeInTheDocument();
}); });
// 更新: 操作列只展示查看和编辑,不再展示启用/停用按钮 // 更新: 操作列只展示查看和编辑,不再展示启用/停用按钮
...@@ -232,8 +251,10 @@ describe('Channel code list page', () => { ...@@ -232,8 +251,10 @@ describe('Channel code list page', () => {
}); });
const firstRow = screen.getByRole('row', { name: /店销顾问渠道活码/ }); const firstRow = screen.getByRole('row', { name: /店销顾问渠道活码/ });
expect(within(firstRow).getByRole('button', { name: '查看店销顾问渠道活码' })).toBeInTheDocument(); const viewButton = within(firstRow).getByRole('button', { name: '查看店销顾问渠道活码' });
expect(within(firstRow).getByRole('button', { name: '编辑店销顾问渠道活码' })).toBeInTheDocument(); const editButton = within(firstRow).getByRole('button', { name: '编辑店销顾问渠道活码' });
expect(viewButton).toHaveClass('t-button--theme-primary', 't-button--variant-text');
expect(editButton).toHaveClass('t-button--theme-primary', 't-button--variant-text');
// 启用/停用按钮不再展示 // 启用/停用按钮不再展示
expect(within(firstRow).queryByRole('button', { name: '停用店销顾问渠道活码' })).not.toBeInTheDocument(); expect(within(firstRow).queryByRole('button', { name: '停用店销顾问渠道活码' })).not.toBeInTheDocument();
expect(within(firstRow).queryByRole('button', { name: '启用店销顾问渠道活码' })).not.toBeInTheDocument(); expect(within(firstRow).queryByRole('button', { name: '启用店销顾问渠道活码' })).not.toBeInTheDocument();
...@@ -282,7 +303,7 @@ describe('Channel code list page', () => { ...@@ -282,7 +303,7 @@ describe('Channel code list page', () => {
renderChannelCodes(); renderChannelCodes();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('当前还没有渠道活码')).toBeInTheDocument(); expect(screen.getByText('暂无数据')).toBeInTheDocument();
}); });
}); });
...@@ -293,42 +314,26 @@ describe('Channel code list page', () => { ...@@ -293,42 +314,26 @@ describe('Channel code list page', () => {
page: 1, page: 1,
page_size: 10, page_size: 10,
}); });
renderChannelCodes(); renderChannelCodes('/channel-codes?keyword=售后');
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('heading', { name: '渠道活码管理' })).toBeInTheDocument(); expect(screen.getByText('未找到匹配结果')).toBeInTheDocument();
}); expect(screen.queryByText('暂无数据')).not.toBeInTheDocument();
expect(screen.queryByText('未能查询到符合条件的资源')).not.toBeInTheDocument();
// 等待数据加载完成 expect(screen.queryByText('请调整搜索或筛选条件')).not.toBeInTheDocument();
await waitFor(() => { expect(screen.queryByRole('button', { name: '清空筛选' })).not.toBeInTheDocument();
const emptyTexts = screen.queryAllByText('未找到匹配结果');
if (emptyTexts.length > 0) {
expect(emptyTexts.length).toBeGreaterThan(0);
} else {
// 如果没有找到"未找到匹配结果",检查是否有空状态
expect(screen.getByText('当前还没有渠道活码')).toBeInTheDocument();
}
}); });
}); });
it('shows load error state with retry button', async () => { it('shows load error state without description or retry button', async () => {
vi.mocked(getChannelQRCodeList).mockRejectedValueOnce(new Error('Network error')); vi.mocked(getChannelQRCodeList).mockRejectedValueOnce(new Error('Network error'));
renderChannelCodes(); renderChannelCodes();
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument(); expect(screen.getByText('请求失败')).toBeInTheDocument();
}); expect(screen.queryByText('渠道活码列表加载失败,请重试')).not.toBeInTheDocument();
expect(screen.queryByText('请检查网络连接后重试')).not.toBeInTheDocument();
vi.mocked(getChannelQRCodeList).mockResolvedValueOnce({ expect(screen.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
list: mockChannelCodes,
total: mockChannelCodes.length,
page: 1,
page_size: 10,
});
fireEvent.click(screen.getByRole('button', { name: '重试' }));
await waitFor(() => {
expect(screen.getByText('店销顾问渠道活码')).toBeInTheDocument();
}); });
}); });
...@@ -350,14 +355,15 @@ describe('Channel code list page', () => { ...@@ -350,14 +355,15 @@ describe('Channel code list page', () => {
}); });
it('does not report page view on load failure', async () => { it('does not report page view on load failure', async () => {
vi.mocked(getChannelQRCodeList).mockRejectedValueOnce(new Error('Network error')); vi.mocked(getChannelQRCodeList).mockRejectedValueOnce(new Error('Network error'));
renderChannelCodes(); renderChannelCodes();
await waitFor(() => {
expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument();
});
expect(reportPageView).not.toHaveBeenCalled(); await waitFor(() => {
expect(screen.getByText('请求失败')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
}); });
expect(reportPageView).not.toHaveBeenCalled();
});
}); });
}); });
import { useState } from 'react'; import { useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button, Input, Pagination, Select, StatePlaceholder, Table, Tag, type TableColumn } from '../../../packages/ui/src'; import { BusinessTable, SearchFilter, type BusinessTableColumn, type SearchFilterValues } from '@gl/business-components';
import { Button, Tag } from 'tdesign-react';
import { import {
getChannelQRCodeList, getChannelQRCodeList,
type ChannelQRCodeListItem, type ChannelQRCodeListItem,
...@@ -53,6 +54,7 @@ export function ChannelCodeListPage() { ...@@ -53,6 +54,7 @@ export function ChannelCodeListPage() {
const [searchParams, setSearchParams] = useSearchParams(); const [searchParams, setSearchParams] = useSearchParams();
const routeState = readChannelCodeListRouteState(searchParams); const routeState = readChannelCodeListRouteState(searchParams);
const [keyword, setKeyword] = useState(routeState.keyword); const [keyword, setKeyword] = useState(routeState.keyword);
const [status, setStatus] = useState<'' | 'enable' | 'disable'>(routeState.status);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState(false); const [loadError, setLoadError] = useState(false);
const [listData, setListData] = useState<{ items: ChannelQRCodeListItem[]; total: number }>({ items: [], total: 0 }); const [listData, setListData] = useState<{ items: ChannelQRCodeListItem[]; total: number }>({ items: [], total: 0 });
...@@ -93,11 +95,15 @@ export function ChannelCodeListPage() { ...@@ -93,11 +95,15 @@ export function ChannelCodeListPage() {
pageSize: routeState.pageSize, pageSize: routeState.pageSize,
}); });
const submitFilters = () => { const submitFilters = (filterValues: SearchFilterValues = { keyword, status }) => {
const nextKeyword = String(filterValues.keyword ?? '');
const nextStatus = String(filterValues.status ?? '') as '' | 'enable' | 'disable';
setKeyword(nextKeyword);
setStatus(nextStatus);
setSearchParams(buildChannelCodeListSearch({ setSearchParams(buildChannelCodeListSearch({
keyword, keyword: nextKeyword,
positionCode: routeState.positionCode, positionCode: routeState.positionCode,
status: routeState.status, status: nextStatus,
page: 1, page: 1,
pageSize: routeState.pageSize, pageSize: routeState.pageSize,
})); }));
...@@ -105,6 +111,7 @@ export function ChannelCodeListPage() { ...@@ -105,6 +111,7 @@ export function ChannelCodeListPage() {
const resetFilters = () => { const resetFilters = () => {
setKeyword(''); setKeyword('');
setStatus('');
setSearchParams(buildChannelCodeListSearch({ setSearchParams(buildChannelCodeListSearch({
keyword: '', keyword: '',
positionCode: '', positionCode: '',
...@@ -114,59 +121,60 @@ export function ChannelCodeListPage() { ...@@ -114,59 +121,60 @@ export function ChannelCodeListPage() {
})); }));
}; };
const columns: TableColumn<ChannelQRCodeListItem>[] = [ const columns: BusinessTableColumn<ChannelQRCodeListItem>[] = [
{ {
title: '活码名称', title: '活码名称',
dataIndex: 'qrcode_name', colKey: 'qrcode_name',
render: (value: unknown) => (value as string) ?? '-', cell: ({ row }) => row.qrcode_name ?? '-',
}, },
{ {
title: '对应岗位', title: '对应岗位',
dataIndex: 'position_name', colKey: 'position_name',
render: (value: unknown) => (value as string) ?? '-', cell: ({ row }) => row.position_name ?? '-',
}, },
{ {
title: '渠道编码', title: '渠道编码',
dataIndex: 'channel_code', colKey: 'channel_code',
render: (value: unknown) => (value as string) ?? '-', cell: ({ row }) => row.channel_code ?? '-',
}, },
{ {
title: '承接员工', title: '承接员工',
dataIndex: 'employee_name', colKey: 'employee_name',
render: (value: unknown) => (value as string) ?? '-', cell: ({ row }) => row.employee_name ?? '-',
}, },
{ {
title: '关联 Agent', title: '关联 Agent',
dataIndex: 'agent_names_preview', colKey: 'agent_names_preview',
render: (value: unknown) => { cell: ({ row }) => {
const agents = (value as string[]) ?? []; const agents = row.agent_names_preview ?? [];
return agents.length > 0 ? agents.join('、') : '-'; return agents.length > 0 ? agents.join('、') : '-';
}, },
}, },
{ {
title: '状态', title: '状态',
dataIndex: 'status', colKey: 'status',
render: (value: unknown) => { cell: ({ row }) => {
const status = value as ChannelQRCodeStatus; const status = row.status as ChannelQRCodeStatus;
return status === 'enable' return status === 'enable'
? <Tag status="success">启用</Tag> ? <Tag theme="success" variant="light">启用</Tag>
: <Tag status="warning">停用</Tag>; : <Tag theme="warning" variant="light">停用</Tag>;
}, },
}, },
{ {
title: '创建时间', title: '创建时间',
dataIndex: 'created_at', colKey: 'created_at',
render: (value: unknown) => (value as string) ?? '-', cell: ({ row }) => row.created_at ?? '-',
}, },
{ {
title: '操作', title: '操作',
key: 'actions', colKey: 'actions',
render: (_: unknown, item: ChannelQRCodeListItem) => { cell: ({ row: item }) => {
return ( return (
<span className="flex flex-wrap gap-1"> <span className="flex flex-wrap gap-1">
<Button <Button
aria-label={`查看${item.qrcode_name}`} aria-label={`查看${item.qrcode_name}`}
size="small" size="small"
theme="primary"
variant="text" variant="text"
onClick={() => setViewTarget(item.qrcode_id)} onClick={() => setViewTarget(item.qrcode_id)}
> >
...@@ -175,6 +183,7 @@ export function ChannelCodeListPage() { ...@@ -175,6 +183,7 @@ export function ChannelCodeListPage() {
<Button <Button
aria-label={`编辑${item.qrcode_name}`} aria-label={`编辑${item.qrcode_name}`}
size="small" size="small"
theme="primary"
variant="text" variant="text"
onClick={() => navigate(`/channel-codes/${item.qrcode_id}/edit${routeSearch}`, { state: { code: item } })} onClick={() => navigate(`/channel-codes/${item.qrcode_id}/edit${routeSearch}`, { state: { code: item } })}
> >
...@@ -193,94 +202,66 @@ export function ChannelCodeListPage() { ...@@ -193,94 +202,66 @@ export function ChannelCodeListPage() {
<h2 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">渠道活码管理</h2> <h2 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">渠道活码管理</h2>
<p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">管理员工渠道活码的列表、新建、编辑与启停状态</p> <p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">管理员工渠道活码的列表、新建、编辑与启停状态</p>
</div> </div>
<Button variant="primary" onClick={() => navigate(`/channel-codes/new${routeSearch}`)}>新增员工渠道活码</Button> <Button theme="primary" onClick={() => navigate(`/channel-codes/new${routeSearch}`)}>新增员工渠道活码</Button>
</header> </header>
<div className="flex flex-wrap items-center justify-between gap-4 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6"> <SearchFilter
<div className="flex items-center gap-4 text-sm"> className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6"
<div className="flex items-center gap-2"> fields={[
<span className="shrink-0">活码名称:</span> {
<span className="w-[200px]"> key: 'keyword',
<Input label: '活码名称',
aria-label="活码名称" type: 'input',
className="w-full" value: keyword,
placeholder="搜索活码名称" allowClear: true,
value={keyword} onChange: setKeyword,
allowClear },
onChange={setKeyword} {
onKeyDown={(event) => { key: 'status',
if (event.key === 'Enter') submitFilters(); label: '状态',
}} type: 'select',
/> options: [
</span> { value: 'enable', label: '启用' },
</div> { value: 'disable', label: '停用' },
<div className="flex items-center gap-2"> ],
<span className="shrink-0">状态:</span> value: status,
<span className="w-[200px]"> onChange: (value) => setStatus((value ?? '') as '' | 'enable' | 'disable'),
<Select },
aria-label="状态" ]}
className="w-full" onReset={resetFilters}
options={[ onSearch={submitFilters}
{ value: '', label: '全部' }, />
{ value: 'enable', label: '启用' },
{ value: 'disable', label: '停用' },
]}
value={routeState.status}
onChange={(value) => setSearchParams(buildChannelCodeListSearch({
keyword: routeState.keyword,
positionCode: routeState.positionCode,
status: value as '' | 'enable' | 'disable',
page: 1,
pageSize: routeState.pageSize,
}))}
/>
</span>
</div>
</div>
<div className="ml-auto flex items-center justify-end gap-3">
<Button variant="primary" onClick={submitFilters}>搜索</Button>
<Button variant="outline" onClick={resetFilters}>重置</Button>
</div>
</div>
<div className="grid gap-6 overflow-x-auto rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6"> <div className="grid gap-6 overflow-x-auto rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6">
{loadError ? ( <BusinessTable
<StatePlaceholder rowKey="qrcode_id"
state="error" columns={columns}
title="加载失败" data={listData.items}
description="渠道活码列表加载失败,请重试" loading={loading}
primaryAction={<Button size="small" onClick={fetchList}>重试</Button>} error={loadError}
/> hasFilter={hasFilter}
) : ( filteredEmptyState={{
<> onAction: resetFilters,
<Table }}
rowKey="qrcode_id" errorState={{
columns={columns} onRetry: fetchList,
dataSource={listData.items} }}
loading={loading} pagination={{
empty={{ current: routeState.page,
description: hasFilter ? '未找到匹配结果' : '当前还没有渠道活码', pageSize: routeState.pageSize,
action: hasFilter ? <Button size="small" onClick={resetFilters}>重置搜索</Button> : undefined, total: listData.total,
}} pageSizeOptions: [2, 10, 20],
/> onChange: ({ current, pageSize }) => {
{listData.items.length === 0 && hasFilter ? <StatePlaceholder state="filtered-empty" /> : null} setSearchParams(buildChannelCodeListSearch({
<Pagination keyword: routeState.keyword,
current={routeState.page} positionCode: routeState.positionCode,
pageSize={routeState.pageSize} status: routeState.status,
total={listData.total} page: current,
pageSizeOptions={[2, 10, 20]} pageSize,
onChange={(page, pageSize) => { }));
setSearchParams(buildChannelCodeListSearch({ },
keyword: routeState.keyword, }}
positionCode: routeState.positionCode, />
status: routeState.status,
page,
pageSize,
}));
}}
/>
</>
)}
</div> </div>
<ChannelCodeViewDrawer <ChannelCodeViewDrawer
...@@ -290,4 +271,4 @@ export function ChannelCodeListPage() { ...@@ -290,4 +271,4 @@ export function ChannelCodeListPage() {
/> />
</section> </section>
); );
}
\ No newline at end of file \ No newline at end of file
}
import { cleanup, render, screen, waitFor } from '@testing-library/react'; import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
...@@ -90,6 +90,12 @@ function renderChannelCodes(path = '/channel-codes') { ...@@ -90,6 +90,12 @@ function renderChannelCodes(path = '/channel-codes') {
); );
} }
function getMenuItem(label: string) {
const item = within(screen.getByLabelText('左侧导航')).getByText(label).closest('li');
if (!item) throw new Error(`Menu item ${label} was not found`);
return item;
}
describe('Channel code routes and navigation', () => { describe('Channel code routes and navigation', () => {
beforeEach(() => { beforeEach(() => {
window.localStorage.clear(); window.localStorage.clear();
...@@ -140,14 +146,14 @@ describe('Channel code routes and navigation', () => { ...@@ -140,14 +146,14 @@ describe('Channel code routes and navigation', () => {
it('shows navigation entry under Agent群管理 group', async () => { it('shows navigation entry under Agent群管理 group', async () => {
renderChannelCodes(); renderChannelCodes();
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('button', { name: '渠道活码' })).toBeInTheDocument(); expect(getMenuItem('渠道活码')).toBeInTheDocument();
}); });
}); });
it('marks navigation entry as active when on channel-codes routes', async () => { it('marks navigation entry as active when on channel-codes routes', async () => {
renderChannelCodes(); renderChannelCodes();
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('button', { name: '渠道活码' })).toHaveAttribute('aria-current', 'page'); expect(getMenuItem('渠道活码')).toHaveClass('t-is-active');
}); });
}); });
});
\ No newline at end of file \ No newline at end of file
});
...@@ -163,7 +163,7 @@ describe('Channel code enable/disable operations', () => { ...@@ -163,7 +163,7 @@ describe('Channel code enable/disable operations', () => {
// 状态列存在 // 状态列存在
expect(screen.getByRole('columnheader', { name: '状态' })).toBeInTheDocument(); expect(screen.getByRole('columnheader', { name: '状态' })).toBeInTheDocument();
// 状态筛选存在 // 状态筛选存在
expect(screen.getByRole('combobox', { name: '状态' })).toBeInTheDocument(); expect(screen.getByLabelText('状态')).toBeInTheDocument();
}); });
// Legacy tests below (will be removed/skipped after implementation) // Legacy tests below (will be removed/skipped after implementation)
......
...@@ -73,6 +73,23 @@ function renderChannelCodes(path = '/channel-codes') { ...@@ -73,6 +73,23 @@ function renderChannelCodes(path = '/channel-codes') {
); );
} }
async function findDrawer(title: string) {
return waitFor(() => {
const drawer = screen.getAllByText(title)
.map((node) => node.closest('.t-drawer'))
.find(Boolean);
expect(drawer).toBeInTheDocument();
return drawer as HTMLElement;
});
}
function queryDrawer(title: string) {
return screen.queryAllByText(title)
.map((node) => node.closest('.t-drawer'))
.find(Boolean);
}
describe('Channel code view drawer', () => { describe('Channel code view drawer', () => {
beforeEach(() => { beforeEach(() => {
window.localStorage.clear(); window.localStorage.clear();
...@@ -98,7 +115,7 @@ describe('Channel code view drawer', () => { ...@@ -98,7 +115,7 @@ describe('Channel code view drawer', () => {
await screen.findByText('店销顾问渠道活码'); await screen.findByText('店销顾问渠道活码');
fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' })); fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
expect(await screen.findByRole('dialog', { name: '店销顾问渠道活码' })).toBeInTheDocument(); expect(await findDrawer('店销顾问渠道活码')).toBeInTheDocument();
}); });
it('calls detail API when opening drawer', async () => { it('calls detail API when opening drawer', async () => {
...@@ -118,7 +135,7 @@ describe('Channel code view drawer', () => { ...@@ -118,7 +135,7 @@ describe('Channel code view drawer', () => {
await screen.findByText('店销顾问渠道活码'); await screen.findByText('店销顾问渠道活码');
fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' })); fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
const drawer = await screen.findByRole('dialog', { name: '店销顾问渠道活码' }); const drawer = await findDrawer('店销顾问渠道活码');
expect(within(drawer).getByText('对应岗位')).toBeInTheDocument(); expect(within(drawer).getByText('对应岗位')).toBeInTheDocument();
expect(within(drawer).getByText('渠道编码')).toBeInTheDocument(); expect(within(drawer).getByText('渠道编码')).toBeInTheDocument();
expect(within(drawer).getByText('承接员工')).toBeInTheDocument(); expect(within(drawer).getByText('承接员工')).toBeInTheDocument();
...@@ -131,7 +148,7 @@ describe('Channel code view drawer', () => { ...@@ -131,7 +148,7 @@ describe('Channel code view drawer', () => {
expect(within(drawer).getByText('欢迎咨询门店产品与服务')).toBeInTheDocument(); expect(within(drawer).getByText('欢迎咨询门店产品与服务')).toBeInTheDocument();
const statusTag = within(drawer).getByText('启用'); const statusTag = within(drawer).getByText('启用');
expect(statusTag.closest('span')?.className ?? '').toContain('tag'); expect(statusTag.closest('.t-tag')).toBeInTheDocument();
}); });
it('shows QR code image', async () => { it('shows QR code image', async () => {
...@@ -148,12 +165,14 @@ describe('Channel code view drawer', () => { ...@@ -148,12 +165,14 @@ describe('Channel code view drawer', () => {
await screen.findByText('店销顾问渠道活码'); await screen.findByText('店销顾问渠道活码');
fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' })); fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
expect(await screen.findByRole('dialog', { name: '店销顾问渠道活码' })).toBeInTheDocument(); expect(await findDrawer('店销顾问渠道活码')).toBeInTheDocument();
// Drawer close button is aria-label="关闭{title}" // Drawer close button is aria-label="关闭{title}"
const closeButton = screen.getByRole('button', { name: '关闭店销顾问渠道活码' }); const closeButton = screen.getByRole('button', { name: '关闭店销顾问渠道活码' });
fireEvent.click(closeButton); fireEvent.click(closeButton);
expect(screen.queryByRole('dialog', { name: '店销顾问渠道活码' })).not.toBeInTheDocument(); await waitFor(() => {
expect(queryDrawer('店销顾问渠道活码')).toBeUndefined();
});
// List should still be visible // List should still be visible
expect(screen.getByRole('heading', { name: '渠道活码管理' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '渠道活码管理' })).toBeInTheDocument();
...@@ -165,12 +184,14 @@ describe('Channel code view drawer', () => { ...@@ -165,12 +184,14 @@ describe('Channel code view drawer', () => {
await screen.findByText('店销顾问渠道活码'); await screen.findByText('店销顾问渠道活码');
fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' })); fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
const drawer = await screen.findByRole('dialog', { name: '店销顾问渠道活码' }); const drawer = await findDrawer('店销顾问渠道活码');
// Footer close button uses "关闭" as text // Footer close button uses "关闭" as text
const footerCloseButton = within(drawer).getByRole('button', { name: '关闭' }); const footerCloseButton = within(drawer).getByRole('button', { name: '关闭' });
fireEvent.click(footerCloseButton); fireEvent.click(footerCloseButton);
expect(screen.queryByRole('dialog', { name: '店销顾问渠道活码' })).not.toBeInTheDocument(); await waitFor(() => {
expect(queryDrawer('店销顾问渠道活码')).toBeUndefined();
});
}); });
it('shows agent names as tags with unified color', async () => { it('shows agent names as tags with unified color', async () => {
...@@ -179,7 +200,7 @@ describe('Channel code view drawer', () => { ...@@ -179,7 +200,7 @@ describe('Channel code view drawer', () => {
await screen.findByText('店销顾问渠道活码'); await screen.findByText('店销顾问渠道活码');
fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' })); fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
const drawer = await screen.findByRole('dialog', { name: '店销顾问渠道活码' }); const drawer = await findDrawer('店销顾问渠道活码');
// Should display agent names as tags // Should display agent names as tags
expect(within(drawer).getByText('店销助手Agent')).toBeInTheDocument(); expect(within(drawer).getByText('店销助手Agent')).toBeInTheDocument();
expect(within(drawer).getByText('管家Agent')).toBeInTheDocument(); expect(within(drawer).getByText('管家Agent')).toBeInTheDocument();
...@@ -196,7 +217,7 @@ describe('Channel code view drawer', () => { ...@@ -196,7 +217,7 @@ describe('Channel code view drawer', () => {
await screen.findByText('店销顾问渠道活码'); await screen.findByText('店销顾问渠道活码');
fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' })); fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
const drawer = await screen.findByRole('dialog', { name: '店销顾问渠道活码' }); const drawer = await findDrawer('店销顾问渠道活码');
// Should display "-" when no agent names // Should display "-" when no agent names
const agentSection = within(drawer).getByText('关联 Agent').parentElement; const agentSection = within(drawer).getByText('关联 Agent').parentElement;
expect(within(agentSection!).getByText('-')).toBeInTheDocument(); expect(within(agentSection!).getByText('-')).toBeInTheDocument();
...@@ -228,7 +249,7 @@ describe('Channel code view drawer', () => { ...@@ -228,7 +249,7 @@ describe('Channel code view drawer', () => {
await screen.findByText('店销顾问渠道活码'); await screen.findByText('店销顾问渠道活码');
fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' })); fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
const drawer = await screen.findByRole('dialog', { name: '渠道活码详情' }); const drawer = await findDrawer('渠道活码详情');
await waitFor(() => { await waitFor(() => {
expect(within(drawer).getByText('加载失败')).toBeInTheDocument(); expect(within(drawer).getByText('加载失败')).toBeInTheDocument();
}); });
...@@ -243,4 +264,4 @@ describe('Channel code view drawer', () => { ...@@ -243,4 +264,4 @@ describe('Channel code view drawer', () => {
expect(getChannelQRCodeDetail).toHaveBeenCalledTimes(2); expect(getChannelQRCodeDetail).toHaveBeenCalledTimes(2);
}); });
}); });
});
\ No newline at end of file \ No newline at end of file
});
import { useState } from 'react'; import { useState } from 'react';
import { Drawer, StatePlaceholder, Button, Tag } from '../../../packages/ui/src'; import { StatePlaceholder } from '@gl/business-components';
import { CloseIcon } from 'tdesign-icons-react';
import { Button, Drawer, Tag } from 'tdesign-react';
import { getChannelQRCodeDetail, type ChannelQRCodeDetail } from '../../api/channelCode'; import { getChannelQRCodeDetail, type ChannelQRCodeDetail } from '../../api/channelCode';
import { useDeferredEffect } from '../../hooks/useDeferredEffect'; import { useDeferredEffect } from '../../hooks/useDeferredEffect';
...@@ -64,15 +66,17 @@ export function ChannelCodeViewDrawer({ open, qrcodeId, onClose }: ChannelCodeVi ...@@ -64,15 +66,17 @@ export function ChannelCodeViewDrawer({ open, qrcodeId, onClose }: ChannelCodeVi
if (!qrcodeId) return null; if (!qrcodeId) return null;
const statusTag = detail?.status === 'enable' const statusTag = detail?.status === 'enable'
? <Tag status="success">启用</Tag> ? <Tag theme="success" variant="light">启用</Tag>
: <Tag status="warning">停用</Tag>; : <Tag theme="warning" variant="light">停用</Tag>;
return ( return (
<Drawer <Drawer
open={open} visible={open}
title={detail?.qrcode_name ?? '渠道活码详情'} header={detail?.qrcode_name ?? '渠道活码详情'}
closeBtn={<Button aria-label={`关闭${detail?.qrcode_name ?? '渠道活码详情'}`} icon={<CloseIcon />} shape="square" variant="text" />}
destroyOnClose
onClose={onClose} onClose={onClose}
width={480} size="480px"
footer={ footer={
<div className="flex items-center justify-end"> <div className="flex items-center justify-end">
<Button variant="outline" onClick={onClose}>关闭</Button> <Button variant="outline" onClick={onClose}>关闭</Button>
...@@ -110,7 +114,7 @@ export function ChannelCodeViewDrawer({ open, qrcodeId, onClose }: ChannelCodeVi ...@@ -110,7 +114,7 @@ export function ChannelCodeViewDrawer({ open, qrcodeId, onClose }: ChannelCodeVi
<div className="flex flex-wrap gap-1"> <div className="flex flex-wrap gap-1">
{(detail.agent_names?.length ?? 0) > 0 {(detail.agent_names?.length ?? 0) > 0
? detail.agent_names.map((name) => ( ? detail.agent_names.map((name) => (
<Tag key={name} status="info">{name}</Tag> <Tag key={name} theme="primary" variant="light">{name}</Tag>
)) ))
: <span>-</span>} : <span>-</span>}
</div> </div>
......
.page { .page {
display: grid; display: grid;
gap: var(--gl-spacing-xl); gap: var(--gl-spacing-xl);
max-width: 1120px; /* max-width: 1120px; */
} }
.heading { .heading {
...@@ -67,14 +67,71 @@ ...@@ -67,14 +67,71 @@
min-width: 280px; min-width: 280px;
} }
.messageDemo {
display: grid;
gap: var(--gl-spacing-xs);
}
.uploadDemo { .uploadDemo {
display: grid; display: grid;
gap: var(--gl-spacing-xl); gap: var(--gl-spacing-xl);
align-items: start; align-items: start;
} }
.placeholderDemo { .searchFilterDemo {
display: grid; display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: var(--gl-spacing-md);
gap: var(--gl-spacing-lg); }
.tableStateDemo {
display: grid;
gap: var(--gl-spacing-xl);
}
.tableStateItem {
display: grid;
gap: var(--gl-spacing-sm);
}
.tableStateItem h4 {
margin: 0;
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-sm);
font-weight: 600;
line-height: var(--gl-line-height-md);
}
.searchFilterResult {
margin: 0;
padding: var(--gl-spacing-md);
border: 1px solid var(--gl-color-border-secondary);
border-radius: var(--gl-radius-sm);
background: var(--gl-color-fill-hover);
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-xs);
line-height: var(--gl-line-height-md);
white-space: pre-wrap;
}
.businessFormDemo {
display: grid;
gap: var(--gl-spacing-md);
}
.businessFormActions {
display: flex;
flex-wrap: wrap;
gap: var(--gl-spacing-sm);
}
.businessFormSnapshot {
margin: 0;
padding: var(--gl-spacing-md);
border: 1px solid var(--gl-color-border-secondary);
border-radius: var(--gl-radius-sm);
background: var(--gl-color-fill-hover);
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-xs);
line-height: var(--gl-line-height-md);
white-space: pre-wrap;
} }
import { fireEvent, render, screen } from '@testing-library/react'; import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { ComponentsDemoPage } from './ComponentsDemoPage'; import { ComponentsDemoPage } from './ComponentsDemoPage';
import uiStyles from '../../../packages/ui/src/components/Shared.module.css';
describe('ComponentsDemoPage', () => { describe('ComponentsDemoPage', () => {
it('shows all phase-one component groups including Upload', () => { it('shows TDesign examples and the global business component groups', () => {
render(<ComponentsDemoPage />); render(<ComponentsDemoPage />);
expect(screen.getByRole('heading', { name: '组件库 Demo' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '组件库 Demo' })).toBeInTheDocument();
expect(screen.getByText('基础交互')).toBeInTheDocument(); expect(screen.getByText('TDesign 基础控件与全局业务组合组件展示入口')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: '选择与日期' })).toBeInTheDocument(); for (const heading of ['基础交互', '搜索区域', '选择与日期', '表格与分页', '反馈与浮层', '业务表单', '数据展示', '导航与占位', '颜色能力', '上传']) {
expect(screen.getByRole('heading', { name: '表格与分页' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: heading })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: '反馈与浮层' })).toBeInTheDocument(); }
expect(screen.getByRole('heading', { name: '数据展示' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: '导航与占位' })).toBeInTheDocument(); const tableSection = screen.getByRole('heading', { name: '表格与分页' }).closest('section');
expect(screen.getByRole('heading', { name: '颜色能力' })).toBeInTheDocument(); const tableDemo = within(tableSection as HTMLElement);
expect(screen.getByRole('heading', { name: '上传' })).toBeInTheDocument();
expect(screen.getByText('暂无审批记录')).toBeInTheDocument(); expect(tableDemo.getAllByText('项目A').length).toBeGreaterThanOrEqual(1);
expect(screen.getByRole('button', { name: '新建审批' })).toBeInTheDocument(); expect(tableDemo.getByText('暂无数据')).toBeInTheDocument();
expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument(); expect(tableDemo.getByText('未找到匹配结果')).toBeInTheDocument();
expect(screen.getByRole('status', { name: '暂无数据' })).toBeInTheDocument(); expect(tableDemo.getAllByText('请求失败').length).toBeGreaterThanOrEqual(1);
expect(screen.getByRole('status', { name: '未找到匹配结果' })).toBeInTheDocument(); expect(tableDemo.getAllByText('权限受限').length).toBeGreaterThanOrEqual(1);
expect(screen.getByRole('alert', { name: '权限受限' })).toBeInTheDocument(); expect(tableDemo.getByText('当前账号暂无访问权限')).toBeInTheDocument();
expect(screen.getByRole('alert', { name: '网络不可用' })).toBeInTheDocument(); expect(tableDemo.getByRole('button', { name: '申请权限' })).toBeInTheDocument();
expect(screen.getByText('点击或拖拽业务资料到此上传')).toBeInTheDocument(); expect(tableDemo.getAllByText('加载中').length).toBeGreaterThanOrEqual(1);
expect(screen.getByText('4/20')).toBeInTheDocument(); expect(tableDemo.queryByText('暂无审批记录')).not.toBeInTheDocument();
expect(tableDemo.queryByText('请先创建项目')).not.toBeInTheDocument();
expect(tableDemo.queryByText('请调整搜索或筛选条件')).not.toBeInTheDocument();
expect(tableDemo.queryByText('列表请求失败,当前数据状态未知')).not.toBeInTheDocument();
expect(tableDemo.queryByRole('button', { name: '清空筛选' })).not.toBeInTheDocument();
expect(tableDemo.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
const navigationSection = screen.getByRole('heading', { name: '导航与占位' }).closest('section');
const navigationDemo = within(navigationSection as HTMLElement);
expect(navigationDemo.queryByText('网络不可用')).not.toBeInTheDocument();
expect(navigationDemo.queryByText('请检查网络连接后重试')).not.toBeInTheDocument();
expect(navigationDemo.queryByRole('button', { name: '重新连接' })).not.toBeInTheDocument();
expect(screen.getByText('product_design_v2.fig')).toBeInTheDocument();
const remark = screen.getByLabelText('备注');
expect(remark).toHaveValue('补充说明');
expect(remark.closest('.t-textarea')).toBeInTheDocument();
expect(screen.getByText('4/120')).toBeInTheDocument(); expect(screen.getByText('4/120')).toBeInTheDocument();
}); });
it('keeps basic component demos interactive for manual review', () => { it('shows the global search filter demo with expand, search, and reset behavior', () => {
render(<ComponentsDemoPage />); render(<ComponentsDemoPage />);
fireEvent.click(screen.getByLabelText('Demo 启用')); const searchSection = screen.getByRole('heading', { name: '搜索区域' }).closest('section');
fireEvent.click(screen.getByRole('switch', { name: 'Demo 启用审批' })); const scoped = within(searchSection as HTMLElement);
fireEvent.click(scoped.getByRole('button', { name: '展开' }));
expect(scoped.getByRole('button', { name: '收起' })).toBeInTheDocument();
expect(screen.getByLabelText('Demo 启用')).not.toBeChecked(); fireEvent.click(scoped.getByRole('button', { name: '搜索' }));
expect(screen.getByRole('switch', { name: 'Demo 启用审批' })).toHaveAttribute('aria-checked', 'false'); expect(scoped.getByText(/"keyword": "智能审批"/)).toBeInTheDocument();
fireEvent.click(scoped.getByRole('button', { name: '重置' }));
expect(scoped.getByText('已重置,等待下一次搜索')).toBeInTheDocument();
}); });
it('shows every Button type, size, and core state in the demo', () => { it('keeps the checkbox and switch examples interactive', () => {
render(<ComponentsDemoPage />); render(<ComponentsDemoPage />);
expect(screen.getByRole('button', { name: '主按钮' })).toBeInTheDocument(); const checkbox = screen.getByRole('checkbox', { name: 'Demo 启用' });
expect(screen.getByRole('button', { name: '普通按钮' })).toBeInTheDocument(); const toggle = screen.getByRole('switch', { name: 'Demo 启用审批' });
expect(screen.getByRole('button', { name: '描边按钮' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '文字按钮' })).toBeInTheDocument(); fireEvent.click(checkbox);
expect(screen.getByRole('button', { name: '危险按钮' })).toBeInTheDocument(); fireEvent.click(toggle);
expect(screen.getByRole('button', { name: '小按钮' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '中按钮' })).toBeInTheDocument(); expect(checkbox).not.toBeChecked();
expect(screen.getByRole('button', { name: '大按钮' })).toBeInTheDocument(); expect(toggle).not.toHaveClass('t-is-checked');
expect(screen.getByRole('button', { name: '图标按钮' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '禁用按钮' })).toBeDisabled();
expect(screen.getByRole('button', { name: '加载中' })).toHaveAttribute('aria-busy', 'true');
}); });
it('shows Message in the feedback demo after clicking the trigger', () => { it('shows Button variants, sizes, and states', () => {
render(<ComponentsDemoPage />); render(<ComponentsDemoPage />);
fireEvent.click(screen.getByRole('button', { name: '展示消息提示' })); const basicsSection = screen.getByRole('heading', { name: '基础交互' }).closest('section');
const basicsDemo = within(basicsSection as HTMLElement);
expect(screen.getByRole('region', { name: '全局消息提示' })).toBeInTheDocument(); for (const name of ['主按钮', '普通按钮', '描边按钮', '文字按钮', '危险按钮', '小按钮', '中按钮', '大按钮', '图标按钮']) {
expect(screen.getByRole('status', { name: '保存成功' })).toBeInTheDocument(); expect(basicsDemo.getByRole('button', { name })).toBeInTheDocument();
expect(screen.getByRole('status', { name: '请补充审批人' })).toBeInTheDocument(); }
expect(screen.getByRole('alert', { name: '删除失败' })).toBeInTheDocument(); expect(basicsDemo.getByText('禁用按钮').closest('.t-button')).toHaveAttribute('disabled');
expect(screen.getByRole('img', { name: '成功提示' })).toBeInTheDocument(); expect(basicsDemo.getByText('加载中').closest('.t-button')).toHaveAttribute('disabled');
expect(screen.getByRole('img', { name: '警告提示' })).toBeInTheDocument();
expect(screen.getByRole('img', { name: '错误提示' })).toBeInTheDocument();
}); });
it('closes the feedback demo Modal when clicking cancel', () => { it('shows feedback alerts after clicking the trigger', () => {
render(<ComponentsDemoPage />); render(<ComponentsDemoPage />);
fireEvent.click(screen.getByRole('button', { name: '取消' })); fireEvent.click(screen.getByRole('button', { name: '展示消息提示' }));
expect(screen.queryByRole('dialog', { name: '编辑项目' })).not.toBeInTheDocument(); const messages = screen.getByLabelText('消息提示示例');
expect(within(messages).getByText('保存成功')).toBeInTheDocument();
expect(within(messages).getByText('请补充审批人')).toBeInTheDocument();
expect(within(messages).getByText('删除失败')).toBeInTheDocument();
}); });
it('closes the feedback demo Modal when clicking the close button', () => { it('closes the feedback demo dialog when clicking cancel', async () => {
render(<ComponentsDemoPage />); render(<ComponentsDemoPage />);
fireEvent.click(screen.getByRole('button', { name: '关闭编辑项目' })); expect(screen.getByText('编辑项目')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '取消' }));
expect(screen.queryByRole('dialog', { name: '编辑项目' })).not.toBeInTheDocument(); await waitFor(() => expect(screen.queryByText('编辑项目')).not.toBeVisible());
}); });
it('shows Form validation and horizontal FormItem layout in the feedback demo', () => { it('shows TDesign form validation in the feedback demo', async () => {
render(<ComponentsDemoPage />); render(<ComponentsDemoPage />);
fireEvent.click(screen.getByRole('button', { name: '提交表单' })); fireEvent.click(screen.getByRole('button', { name: '提交表单' }));
expect(screen.getByRole('alert', { name: '请输入项目名称' })).toBeInTheDocument(); expect(await screen.findByText('请输入项目名称')).toBeInTheDocument();
expect(screen.getByTestId('form-root')).toHaveClass(uiStyles.formColumnsOne); expect(screen.getByText('从 Agent 管理自动带入,不可修改')).toBeInTheDocument();
expect(screen.getByTestId('form-item-项目名称')).toHaveClass(uiStyles.formItemHorizontal);
expect(screen.getByTestId('form-item-所属岗位')).toHaveClass(uiStyles.formItemSpanOne);
expect(screen.getByTestId('form-item-备注')).toHaveClass(uiStyles.formItemSpanTwo);
expect(screen.getByTestId('form-main-项目名称')).toHaveClass(uiStyles.formMain);
expect(screen.getByText('从 Agent 管理自动带入,不可修改')).toHaveClass(uiStyles.formTips);
expect(screen.getByTestId('form-error-项目名称')).toHaveClass(uiStyles.formErrorSlot);
}); });
it('shows rounded avatar and top-right progress examples in the display demo', () => { it('shows the business form demo with dynamic fields, custom actions, and upload states', () => {
render(<ComponentsDemoPage />); render(<ComponentsDemoPage />);
expect(screen.getByLabelText('张三')).toHaveClass(uiStyles.avatarCircle, uiStyles.avatarText); const businessFormSection = screen.getByRole('heading', { name: '业务表单' }).closest('section');
expect(screen.getByTestId('progress-root')).toHaveClass(uiStyles.progressTopRight); const scoped = within(businessFormSection as HTMLElement);
expect(scoped.getByRole('button', { name: '填充摘要' })).toBeInTheDocument();
expect(scoped.getByText('标题:合同审批')).toBeInTheDocument();
expect(scoped.getByLabelText('适用场景')).toBeInTheDocument();
expect(scoped.getByText('审批')).toBeInTheDocument();
expect(scoped.getByText('归档')).toBeInTheDocument();
fireEvent.change(scoped.getByLabelText('标题'), { target: { value: '新合同' } });
expect(scoped.getByText('标题:新合同')).toBeInTheDocument();
fireEvent.change(scoped.getByLabelText('展示模式'), { target: { value: 'show' } });
expect(scoped.getByLabelText('可见说明')).toBeInTheDocument();
fireEvent.change(scoped.getByLabelText('展示模式'), { target: { value: 'lock' } });
expect(scoped.getByLabelText('锁定项')).toBeDisabled();
fireEvent.change(scoped.getByLabelText('展示模式'), { target: { value: 'read' } });
expect(scoped.getByLabelText('只读项')).toHaveAttribute('readonly');
fireEvent.click(scoped.getByRole('button', { name: '填充摘要' }));
expect(scoped.getByText('摘要:新合同')).toBeInTheDocument();
expect(scoped.getByText('封面图.png')).toBeInTheDocument();
expect(scoped.getByText('支持图片、视频、GIF,推荐 1:1,最大 20MB')).toBeInTheDocument();
expect(scoped.getByText('项目资料.pdf')).toBeInTheDocument();
const mediaField = scoped.getByTestId('business-form-field-coverMedia');
const fileField = scoped.getByTestId('business-form-field-attachment');
const mediaUploadInput = mediaField.querySelector('input[type="file"]');
const fileUploadInput = fileField.querySelector('input[type="file"]');
if (!mediaUploadInput || !fileUploadInput) {
throw new Error('Upload input was not rendered');
}
expect(mediaField.querySelector('.t-upload__card-mask')).toBeInTheDocument();
expect(mediaField.querySelector('.t-icon-browse')).toBeInTheDocument();
expect(mediaField.querySelector('.t-icon-delete')).toBeInTheDocument();
}); });
it('shows Upload file and media wall states in the demo', () => { it('shows the upload files and global media wall states', () => {
render(<ComponentsDemoPage />); render(<ComponentsDemoPage />);
expect(screen.getByText('product_design_v2.fig')).toBeInTheDocument(); expect(screen.getByText('product_design_v2.fig')).toBeInTheDocument();
......
import { useState } from 'react'; import { useState } from 'react';
import { SearchIcon } from 'tdesign-icons-react';
import { import {
Alert, Alert,
Avatar, Avatar,
...@@ -9,110 +9,290 @@ import { ...@@ -9,110 +9,290 @@ import {
Card, Card,
Checkbox, Checkbox,
Collapse, Collapse,
ColorInput,
ColorPicker, ColorPicker,
DatePicker, DatePicker,
DateRangePicker, DateRangePicker,
Dialog,
Divider,
Drawer, Drawer,
Empty,
Form, Form,
FormItem,
Input, Input,
Message, Menu,
MediaWall,
Modal,
Navigation,
Pagination,
Popconfirm, Popconfirm,
Progress, Progress,
Radio, Radio,
SearchInput,
Select, Select,
Skeleton, Skeleton,
StatePlaceholder,
Steps, Steps,
Switch, Switch,
Table,
Tabs, Tabs,
Tag, Tag,
Textarea,
Timeline, Timeline,
Tooltip, Tooltip,
TreeSelect, TreeSelect,
Textarea, Upload,
UploadDragger, } from 'tdesign-react';
} from '../../../packages/ui/src';
import { Icon } from '../../../packages/ui/src/components/Icon'; import {
BusinessForm,
BusinessTable,
MediaWall,
SearchFilter,
StatePlaceholder,
type BusinessFormField,
type BusinessFormValues,
type BusinessTableColumn,
} from '@gl/business-components';
import styles from './ComponentsDemoPage.module.css'; import styles from './ComponentsDemoPage.module.css';
const { FormItem } = Form;
const { MenuItem, SubMenu } = Menu;
const { Panel: CollapsePanel } = Collapse;
const { TabPanel } = Tabs;
interface DemoTableRow {
id: string;
name: string;
status: string;
}
export function ComponentsDemoPage() { export function ComponentsDemoPage() {
const tableRows = [{ id: '1', name: '项目A', status: '启用' }]; const [form] = Form.useForm();
const tableRows: DemoTableRow[] = [{ id: '1', name: '项目A', status: '启用' }];
const tableColumns: BusinessTableColumn<DemoTableRow>[] = [
{ title: '名称', colKey: 'name' },
{ title: '状态', colKey: 'status', cell: ({ row }) => <Tag theme="success">{row.status}</Tag> },
];
const mediaImage =
'data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2296%22 height=%2296%22 viewBox=%220 0 96 96%22%3E%3Crect width=%2296%22 height=%2296%22 fill=%22%23dbeafe%22/%3E%3Ccircle cx=%2232%22 cy=%2235%22 r=%2210%22 fill=%22%232468f2%22/%3E%3Cpath d=%22M12 78 39 52l14 13 12-17 19 30Z%22 fill=%22%231f5bd6%22/%3E%3C/svg%3E';
const mediaVideo =
'data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2296%22 height=%2296%22 viewBox=%220 0 96 96%22%3E%3Crect width=%2296%22 height=%2296%22 fill=%22%231f2633%22/%3E%3Cpath d=%22M18 72 38 45l13 12 11-18 16 33Z%22 fill=%22%23667085%22/%3E%3Ccircle cx=%2270%22 cy=%2226%22 r=%2210%22 fill=%22%23f59e0b%22/%3E%3C/svg%3E';
const [checkboxChecked, setCheckboxChecked] = useState(true); const [checkboxChecked, setCheckboxChecked] = useState(true);
const [switchChecked, setSwitchChecked] = useState(true); const [switchChecked, setSwitchChecked] = useState(true);
const [treeValue, setTreeValue] = useState<string | undefined>(); const [treeValue, setTreeValue] = useState<string>();
const [multiSelectValue, setMultiSelectValue] = useState<string[]>(['zhang', 'li']); const [multiSelectValue, setMultiSelectValue] = useState<string[]>(['zhang', 'li']);
const [tagSelectValue, setTagSelectValue] = useState<string[]>(['zhang', 'li']);
const [dateValue, setDateValue] = useState('2026-05-16'); const [dateValue, setDateValue] = useState('2026-05-16');
const [dateRangeValue, setDateRangeValue] = useState<string[]>([]);
const [showMessage, setShowMessage] = useState(false); const [showMessage, setShowMessage] = useState(false);
const [modalOpen, setModalOpen] = useState(true); const [dialogOpen, setDialogOpen] = useState(true);
const mediaImage = const [searchFilterSnapshot, setSearchFilterSnapshot] = useState('点击搜索查看配置结果');
'data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2296%22 height=%2296%22 viewBox=%220 0 96 96%22%3E%3Crect width=%2296%22 height=%2296%22 fill=%22%23dbeafe%22/%3E%3Ccircle cx=%2232%22 cy=%2235%22 r=%2210%22 fill=%22%232468f2%22/%3E%3Cpath d=%22M12 78 39 52l14 13 12-17 19 30Z%22 fill=%22%231f5bd6%22/%3E%3C/svg%3E'; const [businessFormValues, setBusinessFormValues] = useState<BusinessFormValues>({
const mediaVideo = title: '合同审批',
'data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2296%22 height=%2296%22 viewBox=%220 0 96 96%22%3E%3Crect width=%2296%22 height=%2296%22 fill=%22%231f2633%22/%3E%3Cpath d=%22M18 72 38 45l13 12 11-18 16 33Z%22 fill=%22%23667085%22/%3E%3Ccircle cx=%2270%22 cy=%2226%22 r=%2210%22 fill=%22%23f59e0b%22/%3E%3C/svg%3E'; mode: 'hide',
const placeholderStates = [ detail: '审批说明',
{ state: 'empty' as const, title: '暂无数据', description: '请先创建项目' }, locked: '锁定内容',
readonlyNote: '只读内容',
enabled: 'on',
scenarios: ['approval', 'archive'],
coverMedia: { name: '封面图.png', url: mediaImage, kind: 'image' },
attachment: { name: '项目资料.pdf', url: '/files/project.pdf', kind: 'file' },
summary: '标题:合同审批',
});
const businessFormFields: BusinessFormField[] = [
{ {
state: 'filtered-empty' as const, key: 'title',
title: '未找到匹配结果', label: '标题',
description: '请调整搜索或筛选条件', type: 'input',
secondaryAction: <Button size="small">清空筛选</Button>, required: true,
maxLength: 20,
onChange: (nextValue) => ({ summary: `标题:${String(nextValue ?? '')}` }),
}, },
{ {
state: 'forbidden' as const, key: 'mode',
title: '权限受限', label: '展示模式',
description: '当前账号暂无访问权限', type: 'input',
primaryAction: <Button size="small">申请权限</Button>, helpText: '切换可见、禁用和只读状态',
}, },
{ {
state: 'offline' as const, key: 'detail',
title: '网络不可用', label: '可见说明',
description: '请检查网络连接后重试', type: 'input',
primaryAction: <Button size="small">重新连接</Button>, visible: true
},
{
key: 'locked',
label: '锁定项',
type: 'input',
disabled: true,
},
{
key: 'readonlyNote',
label: '只读项',
type: 'input',
readonly: true
},
{
key: 'category',
label: '分类',
type: 'select',
placeholder: '请选择分类',
options: [
{ label: '基础', value: 'basic' },
{ label: '高级', value: 'advanced' },
],
},
{
key: 'scenarios',
label: '适用场景',
type: 'select',
multiple: true,
placeholder: '请选择适用场景',
helpText: '多选 Select 示例,字段值以数组写回',
options: [
{ label: '审批', value: 'approval' },
{ label: '归档', value: 'archive' },
{ label: '通知', value: 'notice' },
],
},
{
key: 'enabled',
label: '启用状态',
type: 'switch',
checkedValue: 'on',
uncheckedValue: 'off',
checkedLabel: '已启用',
uncheckedLabel: '已停用',
},
{
key: 'summary',
label: '摘要',
type: 'displayText',
render: (value) => String(value ?? '请填写标题'),
},
{
key: 'customAction',
label: '自定义操作',
type: 'custom',
render: ({ value, values, setValue, setValues }) => (
<div className={styles.businessFormActions}>
<span>当前状态:{String(value ?? '未执行')}</span>
<Button
size="small"
onClick={() => {
setValues(
{
...values,
summary: `摘要:${String(values.title ?? '')}`,
},
'summary',
);
}}
>
填充摘要
</Button>
<Button
size="small"
variant="outline"
onClick={() => {
setValue('已执行');
}}
>
标记完成
</Button>
</div>
),
},
{
key: 'coverMedia',
label: '展示素材',
type: 'upload',
required: true,
uploadType: 'media',
kinds: ['image', 'gif', 'video'],
accept: '.png,.gif,.mp4,.mov',
maxSize: 20 * 1024 * 1024,
// maxCount: 3,
multiple: true,
placeholder: '点击上传',
helperText: '支持图片、视频、GIF,推荐 1:1,最大 20MB',
upload: async (file) => `https://static.example.com/business-form/media/${encodeURIComponent(file.name)}`,
},
{
key: 'attachment',
label: '附件文件',
type: 'upload',
uploadType: 'file',
kinds: ['file'],
accept: '.pdf,.doc,.zip',
maxSize: 20 * 1024 * 1024,
actionText: '上传附件',
upload: async (file) => `https://static.example.com/business-form/file/${encodeURIComponent(file.name)}`,
}, },
]; ];
return ( return (
<section className={styles.page}> <section className={styles.page}>
<div className={styles.heading}> <div className={styles.heading}>
<p className={styles.eyebrow}>Component Library</p> <p className={styles.eyebrow}>Component Library</p>
<h2>组件库 Demo</h2> <h2>组件库 Demo</h2>
<p>全局 UI 组件库展示入口</p> <p>TDesign 基础控件与全局业务组合组件展示入口</p>
</div> </div>
<section className={styles.group}> <section className={styles.group}>
<h3>基础交互</h3> <h3>基础交互</h3>
<div className={styles.grid}> <div className={styles.grid}>
<div className={styles.buttonDemo}> <div className={styles.buttonDemo}>
<Button variant="primary">主按钮</Button> <Button theme="primary">主按钮</Button>
<Button>普通按钮</Button> <Button>普通按钮</Button>
<Button variant="outline">描边按钮</Button> <Button variant="outline">描边按钮</Button>
<Button variant="text">文字按钮</Button> <Button variant="text">文字按钮</Button>
<Button variant="danger">危险按钮</Button> <Button theme="danger">危险按钮</Button>
</div> </div>
<div className={styles.buttonDemo}> <div className={styles.buttonDemo}>
<Button size="small">小按钮</Button> <Button size="small">小按钮</Button>
<Button size="medium">中按钮</Button> <Button size="medium">中按钮</Button>
<Button size="large">大按钮</Button> <Button size="large">大按钮</Button>
<Button icon={<Icon name="search" size={14} />}>图标按钮</Button> <Button icon={<SearchIcon />}>图标按钮</Button>
<Button disabled>禁用按钮</Button> <Button disabled>禁用按钮</Button>
<Button loading>加载中</Button> <Button loading>加载中</Button>
</div> </div>
<Input aria-label="名称" defaultValue="项目名称" allowClear showCount maxLength={20} /> <Input aria-label="名称" defaultValue="项目名称" clearable showLimitNumber maxlength={20} />
<Textarea aria-label="备注" defaultValue="补充说明" showCount maxLength={120} /> <Textarea aria-label="备注" defaultValue="补充说明" count maxlength={120} />
<SearchInput aria-label="搜索" defaultValue="合同" /> <Input aria-label="搜索" defaultValue="合同" prefixIcon={<SearchIcon />} />
<Checkbox label="Demo 启用" checked={checkboxChecked} onChange={setCheckboxChecked} /> <Checkbox checked={checkboxChecked} onChange={setCheckboxChecked}>Demo 启用</Checkbox>
<Radio label="按项目" name="demo-radio" checked value="project" /> <Radio checked value="project">按项目</Radio>
<Switch aria-label="Demo 启用审批" checked={switchChecked} onChange={setSwitchChecked} /> <Switch aria-label="Demo 启用审批" value={switchChecked} onChange={setSwitchChecked} />
</div> </div>
</section> </section>
<section className={styles.group}>
<h3>搜索区域</h3>
<div className={styles.searchFilterDemo}>
<SearchFilter
fields={[
{ key: 'keyword', label: '项目名称', type: 'input', defaultValue: '智能审批' },
{ key: 'code', label: '项目编号', type: 'numberInput', defaultValue: '10a20' },
{
key: 'status',
label: '状态',
type: 'select',
options: [
{ label: '启用', value: 'enabled' },
{ label: '停用', value: 'disabled' },
],
},
{
key: 'owner',
label: '负责人',
type: 'select',
options: [
{ label: '张三', value: 'zhang' },
{ label: '李四', value: 'li' },
{ label: '王五', value: 'wang' },
],
},
{ key: 'dept', label: '所属部门', type: 'input', defaultValue: '华东区' },
{ key: 'createdAt', label: '创建日期', type: 'datePicker', defaultValue: '2026-05-16' },
{ key: 'effectiveAt', label: '生效区间', type: 'datePicker', range: true },
{ key: 'remark', label: '备注说明', type: 'input', defaultValue: '用于展示展开收起' },
]}
onReset={() => setSearchFilterSnapshot('已重置,等待下一次搜索')}
onSearch={(values) => setSearchFilterSnapshot(JSON.stringify(values, null, 2))}
/>
<pre className={styles.searchFilterResult}>{searchFilterSnapshot}</pre>
</div>
</section>
<section className={styles.group}> <section className={styles.group}>
<h3>选择与日期</h3> <h3>选择与日期</h3>
<div className={styles.grid}> <div className={styles.grid}>
...@@ -120,7 +300,7 @@ export function ComponentsDemoPage() { ...@@ -120,7 +300,7 @@ export function ComponentsDemoPage() {
<Select <Select
multiple multiple
aria-label="负责人多选" aria-label="负责人多选"
allowClear clearable
placeholder="请选择负责人" placeholder="请选择负责人"
value={multiSelectValue} value={multiSelectValue}
options={[ options={[
...@@ -128,152 +308,183 @@ export function ComponentsDemoPage() { ...@@ -128,152 +308,183 @@ export function ComponentsDemoPage() {
{ label: '李四', value: 'li' }, { label: '李四', value: 'li' },
{ label: '王五', value: 'wang' }, { label: '王五', value: 'wang' },
]} ]}
onChange={setMultiSelectValue} onChange={(value) => setMultiSelectValue(Array.isArray(value) ? value.map(String) : [])}
/> />
<Select <TreeSelect
multiple aria-label="组织"
aria-label="负责人标签多选" value={treeValue}
allowClear onChange={(value) => setTreeValue(value === undefined ? undefined : String(value))}
placeholder="请选择负责人" data={[{ label: '总部', value: 'root', children: [{ label: '财务部', value: 'finance' }] }]}
value={tagSelectValue}
options={[
{ label: '张三', value: 'zhang' },
{ label: '李四', value: 'li' },
{ label: '王五', value: 'wang' },
]}
onChange={setTagSelectValue}
/> />
<TreeSelect aria-label="组织" value={treeValue} onChange={setTreeValue} treeData={[{ label: '总部', value: 'root', children: [{ label: '财务部', value: 'finance' }] }]} /> <DatePicker aria-label="计划日期" value={dateValue} onChange={(value) => setDateValue(String(value))} />
<DatePicker aria-label="计划日期" value={dateValue} onChange={setDateValue} /> <DateRangePicker aria-label="周期" value={dateRangeValue} onChange={(value) => setDateRangeValue(value.map(String))} />
<DateRangePicker aria-label="周期" />
</div> </div>
</section> </section>
<section className={styles.group}> <section className={styles.group}>
<h3>表格与分页</h3> <h3>表格与分页</h3>
<Table <div className={styles.tableStateDemo}>
rowKey="id" <div className={styles.tableStateItem}>
columns={[ <h4>有数据</h4>
{ title: '名称', dataIndex: 'name' }, <BusinessTable
{ title: '状态', dataIndex: 'status', render: (value) => <Tag status="success">{String(value)}</Tag> }, rowKey="id"
]} columns={tableColumns}
dataSource={tableRows} data={tableRows}
/> pagination={{ current: 1, pageSize: 10, total: 42 }}
<Table />
rowKey="id" </div>
columns={[ <div className={styles.tableStateItem}>
{ title: '名称', dataIndex: 'name' }, <h4>普通空态</h4>
{ title: '状态', dataIndex: 'status' }, <BusinessTable rowKey="id" columns={tableColumns} data={[]} pagination={false} />
]} </div>
dataSource={[]} <div className={styles.tableStateItem}>
empty={{ description: '暂无审批记录', action: <Button size="small">新建审批</Button> }} <h4>筛选无结果</h4>
/> <BusinessTable rowKey="id" columns={tableColumns} data={[]} hasFilter pagination={false} />
<Pagination current={1} pageSize={10} total={42} /> </div>
<div className={styles.tableStateItem}>
<h4>请求失败</h4>
<BusinessTable rowKey="id" columns={tableColumns} data={[]} error pagination={false} />
</div>
<div className={styles.tableStateItem}>
<h4>权限受限</h4>
<BusinessTable
rowKey="id"
columns={tableColumns}
data={[]}
error
errorState={{ kind: 'forbidden', onRetry: () => undefined }}
pagination={false}
/>
</div>
<div className={styles.tableStateItem}>
<h4>加载中</h4>
<BusinessTable
rowKey="id"
columns={tableColumns}
data={tableRows}
loading
loadingProps={{ delay: 0 }}
pagination={false}
/>
</div>
</div>
</section> </section>
<section className={styles.group}> <section className={styles.group}>
<h3>反馈与浮层</h3> <h3>反馈与浮层</h3>
<div className={styles.grid}> <div className={styles.grid}>
<Form className={styles.formDemo} columns={1} initialValues={{ projectName: '', role: '驻店销售岗', remark: '' }}> <Form form={form} className={styles.formDemo} labelAlign="left" initialData={{ projectName: '', role: '驻店销售岗', remark: '' }}>
<FormItem <FormItem label="项目名称" name="projectName" rules={[{ required: true, message: '请输入项目名称' }]}>
label="项目名称"
layout="horizontal"
name="projectName"
required
rules={[{ required: true, message: '请输入项目名称' }]}
>
<Input aria-label="项目名称" /> <Input aria-label="项目名称" />
</FormItem> </FormItem>
<FormItem label="所属岗位" layout="horizontal" name="role" tips="从 Agent 管理自动带入,不可修改"> <FormItem label="所属岗位" name="role" help="从 Agent 管理自动带入,不可修改">
<Input aria-label="所属岗位" disabled /> <Input aria-label="所属岗位" disabled />
</FormItem> </FormItem>
<FormItem label="备注" layout="horizontal" name="remark" span={2}> <FormItem label="备注" name="remark">
<Input aria-label="备注" /> <Input aria-label="表单备注" />
</FormItem> </FormItem>
<Button type="submit" variant="primary">提交表单</Button> <Button theme="primary" onClick={() => void form.validate()}>提交表单</Button>
</Form> </Form>
<Alert type="info" title="提示">保存后立即生效</Alert> <Alert theme="info" message="提示:保存后立即生效" />
<Button variant="primary" onClick={() => setShowMessage(true)}>展示消息提示</Button> <Button theme="primary" onClick={() => setShowMessage(true)}>展示消息提示</Button>
{showMessage ? ( {showMessage ? (
<Message <div aria-label="消息提示示例" className={styles.messageDemo}>
items={[ <Alert theme="success" message="保存成功" close onClose={() => setShowMessage(false)} />
{ key: 'demo-save-success', type: 'success', content: '保存成功', duration: 0, closable: true, onClose: () => setShowMessage(false) }, <Alert theme="warning" message="请补充审批人" />
{ key: 'demo-approval-warning', type: 'warning', content: '请补充审批人', duration: 0 }, <Alert theme="error" message="删除失败" />
{ key: 'demo-delete-error', type: 'error', content: '删除失败', duration: 0 }, </div>
]}
/>
) : null} ) : null}
<Tooltip content="补充说明"><Button>帮助</Button></Tooltip> <Tooltip content="补充说明"><Button>帮助</Button></Tooltip>
<Popconfirm title="确认删除?"><Button variant="danger">删除</Button></Popconfirm> <Popconfirm content="确认删除?"><Button theme="danger">删除</Button></Popconfirm>
<Modal open={modalOpen} title="编辑项目" onCancel={() => setModalOpen(false)}>内容</Modal> <Dialog
<Drawer open={false} title="详情">内容</Drawer> visible={dialogOpen}
header="编辑项目"
onCancel={() => setDialogOpen(false)}
onClose={() => setDialogOpen(false)}
>
内容
</Dialog>
<Drawer visible={false} header="详情">内容</Drawer>
</div> </div>
</section> </section>
<section className={styles.group}>
<h3>业务表单</h3>
<div className={styles.businessFormDemo}>
<BusinessForm
fieldWidth={360}
fields={businessFormFields}
values={businessFormValues}
onChange={(nextValues) => setBusinessFormValues(nextValues)}
/>
<pre aria-label="业务表单快照" className={styles.businessFormSnapshot}>
{JSON.stringify(businessFormValues, null, 2)}
</pre>
</div>
</section>
<section className={styles.group}> <section className={styles.group}>
<h3>数据展示</h3> <h3>数据展示</h3>
<div className={styles.grid}> <div className={styles.grid}>
<Card title="概览" extra={<Button size="small">刷新</Button>}>卡片内容</Card> <Card header="概览" actions={<Button size="small">刷新</Button>}>卡片内容</Card>
<Badge count={12}><Button>消息</Button></Badge> <Badge count={12}><Button>消息</Button></Badge>
<AvatarGroup maxCount={2}><Avatar name="张三" /><Avatar name="李四" /><Avatar name="王五" /></AvatarGroup> <AvatarGroup max={2}><Avatar>张</Avatar><Avatar>李</Avatar><Avatar>王</Avatar></AvatarGroup>
<Progress percent={68} percentPosition="top-right" /> <Progress percentage={68} label />
<Timeline items={[{ title: '提交', time: '09:00' }, { title: '审批', time: '10:00', description: '处理中' }]} /> <Timeline>
<Timeline.Item label="09:00">提交</Timeline.Item>
<Timeline.Item label="10:00">审批:处理中</Timeline.Item>
</Timeline>
</div> </div>
</section> </section>
<section className={styles.group}> <section className={styles.group}>
<h3>导航与占位</h3> <h3>导航与占位</h3>
<div className={styles.grid}> <div className={styles.grid}>
<Navigation <Menu defaultValue="agent-list" defaultExpanded={['agent-management']}>
activeKey="agent-list" <SubMenu value="agent-management" title="Agent管理">
items={[ <MenuItem value="agent-list">Agent列表</MenuItem>
{ key: 'agent-management', label: 'Agent管理', children: [{ key: 'agent-list', label: 'Agent列表' }] }, </SubMenu>
]} </Menu>
/> <Tabs defaultValue="base">
<Tabs activeKey="base" items={[{ key: 'base', label: '基础信息', children: '基础内容' }, { key: 'advanced', label: '高级配置', children: '高级内容' }]} /> <TabPanel value="base" label="基础信息">基础内容</TabPanel>
<Steps current={1} items={[{ title: '提交' }, { title: '审批' }, { title: '完成' }]} /> <TabPanel value="advanced" label="高级配置">高级内容</TabPanel>
<Empty description="暂无项目" action={<Button>新建项目</Button>} /> </Tabs>
<Steps current={1} options={[{ title: '提交' }, { title: '审批' }, { title: '完成' }]} />
<Divider />
<StatePlaceholder <StatePlaceholder
state="error" state="empty"
title="加载失败" title="暂无内容"
description="列表请求失败,当前数据状态未知" description="该区域当前没有可展示内容"
primaryAction={<Button size="small">重试</Button>}
/> />
<div className={styles.placeholderDemo}> <Skeleton loading />
{placeholderStates.map((item) => ( <Collapse defaultValue={['one']}>
<StatePlaceholder <CollapsePanel value="one" header="基础设置">设置内容</CollapsePanel>
key={item.state} </Collapse>
state={item.state}
title={item.title}
description={item.description}
primaryAction={item.primaryAction}
secondaryAction={item.secondaryAction}
/>
))}
</div>
<Skeleton active />
<Collapse activeKeys={['one']} items={[{ key: 'one', title: '基础设置', children: '设置内容' }]} />
</div> </div>
</section> </section>
<section className={styles.group}> <section className={styles.group}>
<h3>颜色能力</h3> <h3>颜色能力</h3>
<div className={styles.grid}> <div className={styles.grid}>
<ColorPicker value="#2468f2" /> <ColorPicker value="#2468f2" />
<ColorInput aria-label="主题色" value="#2468f2" /> <Input aria-label="主题色" value="#2468f2" />
</div> </div>
</section> </section>
<section className={styles.group}> <section className={styles.group}>
<h3>上传</h3> <h3>上传</h3>
<div className={styles.uploadDemo}> <div className={styles.uploadDemo}>
<UploadDragger <Upload
title="点击或拖拽业务资料到此上传" autoUpload={false}
helperText="支持分片断点续传,单文件上限 1GB" draggable
multiple
theme="file-flow"
files={[ files={[
{ id: 'design', name: 'product_design_v2.fig', size: 12.4 * 1024 * 1024, status: 'success', previewable: true }, { name: 'product_design_v2.fig', status: 'success' },
{ id: 'doc', name: '需求文档.pdf', size: 3.2 * 1024 * 1024, status: 'progress', progress: 42 }, { name: '需求文档.pdf', status: 'progress', percent: 42 },
{ id: 'zip', name: '素材包.zip', size: 18.8 * 1024 * 1024, status: 'fail', errorMessage: '网络异常,请重试' }, { name: '素材包.zip', status: 'fail' },
]} ]}
onPreview={() => undefined} tips="支持拖拽业务资料到此处,单文件上限 1GB"
onDownload={() => undefined}
onRemove={() => undefined}
onRetry={() => undefined}
onCancel={() => undefined}
/> />
<MediaWall <MediaWall
items={[ items={[
......
import { BusinessLoginPage } from '@gl/business-components';
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
const backgroundImage = 'data:image/svg+xml;utf8,%3Csvg%20/%3E';
function renderBusinessLoginPage(overrides: Partial<Parameters<typeof BusinessLoginPage>[0]> = {}) {
const props = {
title: '测试系统',
description: '统一登录描述',
username: '',
password: '',
backgroundColor: '#f0f6ff',
backgroundImage,
onUsernameChange: vi.fn(),
onPasswordChange: vi.fn(),
onSubmit: vi.fn((event) => event.preventDefault()),
...overrides,
};
return {
...render(<BusinessLoginPage {...props} />),
props,
};
}
describe('BusinessLoginPage', () => {
it('renders the unified login structure and consumes background color from props', () => {
renderBusinessLoginPage({ backgroundColor: '#eaf2ff' });
expect(screen.getByRole('heading', { name: '测试系统' })).toBeInTheDocument();
expect(screen.getByText('统一登录描述')).toBeInTheDocument();
expect(screen.getByRole('main')).toHaveStyle({ backgroundColor: '#eaf2ff' });
expect(document.querySelector('input[name="username"]')).toHaveAttribute('placeholder', '请输入账号');
expect(document.querySelector('input[name="password"]')).toHaveAttribute('placeholder', '请输入密码');
expect(screen.queryByText('账号')).not.toBeInTheDocument();
expect(screen.queryByText('密码')).not.toBeInTheDocument();
});
it('updates field values and toggles password visibility', () => {
const { props } = renderBusinessLoginPage();
const usernameInput = document.querySelector<HTMLInputElement>('input[name="username"]');
const passwordInput = document.querySelector<HTMLInputElement>('input[name="password"]');
if (!usernameInput || !passwordInput) {
throw new Error('Login inputs were not rendered');
}
fireEvent.change(usernameInput, { target: { value: 'admin' } });
fireEvent.change(passwordInput, { target: { value: '123456' } });
expect(props.onUsernameChange).toHaveBeenCalledWith('admin');
expect(props.onPasswordChange).toHaveBeenCalledWith('123456');
expect(passwordInput.type).toBe('password');
fireEvent.click(screen.getByRole('button', { name: '显示密码' }));
expect(passwordInput.type).toBe('text');
expect(screen.getByRole('button', { name: '隐藏密码' })).toBeInTheDocument();
});
});
import { type FormEvent, useState } from 'react'; import { type FormEvent, useState } from 'react';
import { BusinessLoginPage } from '@gl/business-components';
import { Navigate, useLocation, useNavigate } from 'react-router-dom'; import { Navigate, useLocation, useNavigate } from 'react-router-dom';
import { Button, Input } from '../../../packages/ui/src';
import { isLoggedIn, login } from '../../auth/localAuth'; import { isLoggedIn, login } from '../../auth/localAuth';
interface LocationState { interface LocationState {
...@@ -11,6 +11,21 @@ interface LocationState { ...@@ -11,6 +11,21 @@ interface LocationState {
}; };
} }
const loginBackgroundSvg = `
<svg xmlns="http://www.w3.org/2000/svg" width="1440" height="900" viewBox="0 0 1440 900" fill="none">
<rect width="1440" height="900" fill="#EAF2FF"/>
<path d="M0 660C180 590 330 590 488 644C676 708 826 724 1018 650C1188 584 1308 590 1440 638V900H0V660Z" fill="#DCEBFF"/>
<path d="M94 196C234 88 410 54 588 96C734 130 842 222 1002 218C1150 214 1268 140 1396 62" stroke="#C8DCFF" stroke-width="56" stroke-linecap="round" opacity="0.72"/>
<circle cx="1168" cy="238" r="188" fill="#F8FBFF" opacity="0.82"/>
<circle cx="258" cy="646" r="156" fill="#F6FAFF" opacity="0.86"/>
<path d="M836 246H1102C1134 246 1160 272 1160 304V566C1160 598 1134 624 1102 624H836C804 624 778 598 778 566V304C778 272 804 246 836 246Z" fill="#FFFFFF" opacity="0.45"/>
<path d="M866 330H1072M866 412H1038M866 494H990" stroke="#B7D0FF" stroke-width="24" stroke-linecap="round" opacity="0.7"/>
</svg>
`;
const loginBackgroundImage = `data:image/svg+xml;utf8,${encodeURIComponent(loginBackgroundSvg)}`;
const loginBackgroundColor = '#eaf2ff';
export function LoginPage() { export function LoginPage() {
const location = useLocation(); const location = useLocation();
const navigate = useNavigate(); const navigate = useNavigate();
...@@ -43,27 +58,17 @@ export function LoginPage() { ...@@ -43,27 +58,17 @@ export function LoginPage() {
}; };
return ( return (
<main className="grid min-h-screen place-items-center bg-[var(--gl-color-bg-page)] p-8"> <BusinessLoginPage
<section className="grid w-full max-w-[420px] gap-6 rounded-[14px] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-8 shadow-[0_24px_60px_rgb(16_24_40_/_12%)]"> backgroundColor={loginBackgroundColor}
<div className="grid gap-1"> backgroundImage={loginBackgroundImage}
<h1 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">岗位Agent管理后台</h1> description="使用一期固定管理员账号进入本地管理后台"
<p className="m-0 text-sm text-[var(--gl-color-text-secondary)]">使用一期固定管理员账号进入本地管理后台</p> errors={errors}
</div> password={password}
<form className="grid gap-4" onSubmit={submit}> title="岗位Agent管理后台"
<label className="grid gap-1 text-sm"> username={username}
账号 onPasswordChange={setPassword}
<Input aria-label="账号" status={errors.username ? 'error' : 'default'} value={username} onChange={setUsername} /> onSubmit={submit}
{errors.username ? <span className="m-0 text-xs text-[#d92d20]">{errors.username}</span> : null} onUsernameChange={setUsername}
</label> />
<label className="grid gap-1 text-sm">
密码
<Input aria-label="密码" status={errors.password ? 'error' : 'default'} type="password" value={password} onChange={setPassword} />
{errors.password ? <span className="m-0 text-xs text-[#d92d20]">{errors.password}</span> : null}
</label>
{errors.form ? <p className="m-0 text-xs text-[#d92d20]">{errors.form}</p> : null}
<Button type="submit" variant="primary">登录</Button>
</form>
</section>
</main>
); );
} }
...@@ -43,6 +43,14 @@ const mockDisplayDetailWithoutIcon: OfficialSiteAgentDisplayDetail = { ...@@ -43,6 +43,14 @@ const mockDisplayDetailWithoutIcon: OfficialSiteAgentDisplayDetail = {
agent_status: 'enable' as AgentStatus, agent_status: 'enable' as AgentStatus,
}; };
function getFormItem(label: string) {
const formItem = screen.getAllByText(label)
.map((element) => element.closest('.t-form__item'))
.find(Boolean);
if (!formItem) throw new Error(`Form item ${label} was not found`);
return formItem as HTMLElement;
}
describe('AgentDisplayConfigEditModal', () => { describe('AgentDisplayConfigEditModal', () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
...@@ -66,7 +74,7 @@ describe('AgentDisplayConfigEditModal', () => { ...@@ -66,7 +74,7 @@ describe('AgentDisplayConfigEditModal', () => {
expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument(); expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument();
}); });
const iconFormItem = screen.getByTestId('form-item-图标'); const iconFormItem = getFormItem('图标');
expect(iconFormItem).not.toHaveTextContent('图标必填'); expect(iconFormItem).not.toHaveTextContent('图标必填');
}); });
...@@ -198,7 +206,7 @@ describe('AgentDisplayConfigEditModal', () => { ...@@ -198,7 +206,7 @@ describe('AgentDisplayConfigEditModal', () => {
expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument(); expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument();
}); });
const mediaFormItem = screen.getByTestId('form-item-展示素材'); const mediaFormItem = getFormItem('展示素材');
const mediaVideo = mediaFormItem.querySelector('video[src$=".mov"]'); const mediaVideo = mediaFormItem.querySelector('video[src$=".mov"]');
expect(mediaVideo).toBeInTheDocument(); expect(mediaVideo).toBeInTheDocument();
expect(mediaFormItem.querySelector('img[src$=".mov"]')).not.toBeInTheDocument(); expect(mediaFormItem.querySelector('img[src$=".mov"]')).not.toBeInTheDocument();
...@@ -239,7 +247,7 @@ describe('AgentDisplayConfigEditModal', () => { ...@@ -239,7 +247,7 @@ describe('AgentDisplayConfigEditModal', () => {
expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument(); expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument();
}); });
const mediaFormItem = screen.getByTestId('form-item-展示素材'); const mediaFormItem = getFormItem('展示素材');
const fileInput = mediaFormItem.querySelector('input[type="file"]') as HTMLInputElement; const fileInput = mediaFormItem.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test gif content'], 'new-media.gif', { type: 'image/gif' }); const file = new File(['test gif content'], 'new-media.gif', { type: 'image/gif' });
...@@ -298,7 +306,7 @@ describe('AgentDisplayConfigEditModal', () => { ...@@ -298,7 +306,7 @@ describe('AgentDisplayConfigEditModal', () => {
expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument(); expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument();
}); });
const mediaFormItem = screen.getByTestId('form-item-展示素材'); const mediaFormItem = getFormItem('展示素材');
const fileInput = mediaFormItem.querySelector('input[type="file"]') as HTMLInputElement; const fileInput = mediaFormItem.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test video content'], 'new-media.mp4', { type: 'video/mp4' }); const file = new File(['test video content'], 'new-media.mp4', { type: 'video/mp4' });
...@@ -333,7 +341,7 @@ describe('AgentDisplayConfigEditModal', () => { ...@@ -333,7 +341,7 @@ describe('AgentDisplayConfigEditModal', () => {
expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument(); expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument();
}); });
const mediaFormItem = screen.getByTestId('form-item-展示素材'); const mediaFormItem = getFormItem('展示素材');
const fileInput = mediaFormItem.querySelector('input[type="file"]') as HTMLInputElement; const fileInput = mediaFormItem.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test'], 'oversized.gif', { type: 'image/gif' }); const file = new File(['test'], 'oversized.gif', { type: 'image/gif' });
...@@ -363,7 +371,7 @@ describe('AgentDisplayConfigEditModal', () => { ...@@ -363,7 +371,7 @@ describe('AgentDisplayConfigEditModal', () => {
expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument(); expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument();
}); });
const iconFormItem = screen.getByTestId('form-item-图标'); const iconFormItem = getFormItem('图标');
const fileInput = iconFormItem.querySelector('input[type="file"]') as HTMLInputElement; const fileInput = iconFormItem.querySelector('input[type="file"]') as HTMLInputElement;
expect(iconFormItem).toHaveTextContent('支持图片,推荐 1:1,最大 2MB'); expect(iconFormItem).toHaveTextContent('支持图片,推荐 1:1,最大 2MB');
...@@ -406,7 +414,7 @@ describe('AgentDisplayConfigEditModal', () => { ...@@ -406,7 +414,7 @@ describe('AgentDisplayConfigEditModal', () => {
expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument(); expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument();
}); });
const iconFormItem = screen.getByTestId('form-item-图标'); const iconFormItem = getFormItem('图标');
const fileInput = iconFormItem.querySelector('input[type="file"]') as HTMLInputElement; const fileInput = iconFormItem.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test icon content'], 'new-icon.png', { type: 'image/png' }); const file = new File(['test icon content'], 'new-icon.png', { type: 'image/png' });
...@@ -459,7 +467,7 @@ describe('AgentDisplayConfigEditModal', () => { ...@@ -459,7 +467,7 @@ describe('AgentDisplayConfigEditModal', () => {
expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument(); expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument();
}); });
const iconFormItem = screen.getByTestId('form-item-图标'); const iconFormItem = getFormItem('图标');
const fileInput = iconFormItem.querySelector('input[type="file"]') as HTMLInputElement; const fileInput = iconFormItem.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test gif content'], 'icon.gif', { type: 'image/gif' }); const file = new File(['test gif content'], 'icon.gif', { type: 'image/gif' });
...@@ -490,7 +498,7 @@ describe('AgentDisplayConfigEditModal', () => { ...@@ -490,7 +498,7 @@ describe('AgentDisplayConfigEditModal', () => {
expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument(); expect(screen.getByText(/编辑展示配置 - 复盘 Agent/)).toBeInTheDocument();
}); });
const iconFormItem = screen.getByTestId('form-item-图标'); const iconFormItem = getFormItem('图标');
const fileInput = iconFormItem.querySelector('input[type="file"]') as HTMLInputElement; const fileInput = iconFormItem.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test'], 'valid.png', { type: 'image/png' }); const file = new File(['test'], 'valid.png', { type: 'image/png' });
......
import { useState } from 'react'; import { useState } from 'react';
import { Button, FormItem, Input, MediaWall, Modal, Select } from '../../../packages/ui/src'; import { MediaWall } from '@gl/business-components';
import { Button, Dialog } from 'tdesign-react';
import { FormItem, Input, Select } from '../../components/TDesignAccessibleControls';
import { import {
getAgentDisplayDetail, getAgentDisplayDetail,
updateAgentDisplayConfig, updateAgentDisplayConfig,
...@@ -272,17 +274,18 @@ export function AgentDisplayConfigEditModal({ ...@@ -272,17 +274,18 @@ export function AgentDisplayConfigEditModal({
: []; : [];
return ( return (
<Modal <Dialog
open={open} visible={open}
title={`编辑展示配置 - ${form.agent_name}`} header={`编辑展示配置 - ${form.agent_name}`}
onCancel={onCancel} onClose={onCancel}
onOk={handleSave} onConfirm={handleSave}
{...{ role: 'dialog', 'aria-label': `编辑展示配置 - ${form.agent_name}` }}
footer={ footer={
<div className="flex justify-end gap-3"> <div className="flex justify-end gap-3">
<Button variant="outline" onClick={onCancel} disabled={saving}> <Button variant="outline" onClick={onCancel} disabled={saving}>
取消 取消
</Button> </Button>
<Button variant="primary" onClick={handleSave} disabled={saving || loading}> <Button theme="primary" onClick={handleSave} disabled={saving || loading}>
{saving ? '保存中...' : '确定'} {saving ? '保存中...' : '确定'}
</Button> </Button>
</div> </div>
...@@ -299,15 +302,16 @@ export function AgentDisplayConfigEditModal({ ...@@ -299,15 +302,16 @@ export function AgentDisplayConfigEditModal({
</div> </div>
) : ( ) : (
<div className="grid gap-6 py-4"> <div className="grid gap-6 py-4">
<FormItem label="Agent 名称" layout="horizontal" required error={errors.speech_title}> <FormItem label="Agent 名称" labelAlign="left" requiredMark status={errors.speech_title ? 'error' : undefined} tips={errors.speech_title}>
<Input <Input
aria-label="Agent 名称"
className="w-full max-w-[400px]" className="w-full max-w-[400px]"
disabled disabled
value={form.agent_name} value={form.agent_name}
/> />
</FormItem> </FormItem>
<FormItem label="图标" layout="horizontal" required error={errors.icon_url || errors.upload_icon}> <FormItem label="图标" labelAlign="left" requiredMark status={errors.icon_url || errors.upload_icon ? 'error' : undefined} tips={errors.icon_url || errors.upload_icon}>
<MediaWall <MediaWall
accept={ICON_ACCEPT} accept={ICON_ACCEPT}
maxCount={1} maxCount={1}
...@@ -319,8 +323,9 @@ export function AgentDisplayConfigEditModal({ ...@@ -319,8 +323,9 @@ export function AgentDisplayConfigEditModal({
/> />
</FormItem> </FormItem>
<FormItem label="Agent 概述" layout="horizontal" required error={errors.speech_content}> <FormItem label="Agent 概述" labelAlign="left" requiredMark status={errors.speech_content ? 'error' : undefined} tips={errors.speech_content}>
<Input <Input
aria-label="Agent 概述"
className="w-full max-w-[400px]" className="w-full max-w-[400px]"
placeholder="请输入Agent概述" placeholder="请输入Agent概述"
value={form.speech_content} value={form.speech_content}
...@@ -328,7 +333,7 @@ export function AgentDisplayConfigEditModal({ ...@@ -328,7 +333,7 @@ export function AgentDisplayConfigEditModal({
/> />
</FormItem> </FormItem>
<FormItem label="展示素材" layout="horizontal" required error={errors.media_url || errors.upload_media}> <FormItem label="展示素材" labelAlign="left" requiredMark status={errors.media_url || errors.upload_media ? 'error' : undefined} tips={errors.media_url || errors.upload_media}>
<MediaWall <MediaWall
accept="image/png,image/jpeg,image/jpg,image/gif,image/webp,video/mp4,video/quicktime,video/x-msvideo,video/webm" accept="image/png,image/jpeg,image/jpg,image/gif,image/webp,video/mp4,video/quicktime,video/x-msvideo,video/webm"
maxCount={1} maxCount={1}
...@@ -340,12 +345,11 @@ export function AgentDisplayConfigEditModal({ ...@@ -340,12 +345,11 @@ export function AgentDisplayConfigEditModal({
/> />
</FormItem> </FormItem>
<FormItem label="展示排序" layout="horizontal" required error={errors.sort_order}> <FormItem label="展示排序" labelAlign="left" requiredMark status={errors.sort_order ? 'error' : undefined} tips={errors.sort_order}>
<Input <Input
aria-label="展示排序"
className="w-full max-w-[400px]" className="w-full max-w-[400px]"
type="number" type="number"
min={0}
max={99}
placeholder="请输入展示排序" placeholder="请输入展示排序"
value={form.sort_order === undefined || (typeof form.sort_order === 'number' && isNaN(form.sort_order)) ? '' : String(form.sort_order)} value={form.sort_order === undefined || (typeof form.sort_order === 'number' && isNaN(form.sort_order)) ? '' : String(form.sort_order)}
onChange={(value) => setForm((current) => ({ onChange={(value) => setForm((current) => ({
...@@ -355,8 +359,9 @@ export function AgentDisplayConfigEditModal({ ...@@ -355,8 +359,9 @@ export function AgentDisplayConfigEditModal({
/> />
</FormItem> </FormItem>
<FormItem label="展示状态" layout="horizontal" required> <FormItem label="展示状态" labelAlign="left" requiredMark>
<Select <Select
aria-label="展示状态"
className="w-full max-w-[400px]" className="w-full max-w-[400px]"
options={[ options={[
{ value: 'disable', label: '已下架' }, { value: 'disable', label: '已下架' },
...@@ -371,6 +376,6 @@ export function AgentDisplayConfigEditModal({ ...@@ -371,6 +376,6 @@ export function AgentDisplayConfigEditModal({
</FormItem> </FormItem>
</div> </div>
)} )}
</Modal> </Dialog>
); );
} }
...@@ -298,7 +298,7 @@ describe('Agent display config edit modal', () => { ...@@ -298,7 +298,7 @@ describe('Agent display config edit modal', () => {
it('shows 图标 field with upload component', () => { it('shows 图标 field with upload component', () => {
const modal = screen.getByRole('dialog'); const modal = screen.getByRole('dialog');
expect(within(modal).getByTestId('form-item-图标')).toBeInTheDocument(); expect(within(modal).getByText('图标')).toBeInTheDocument();
}); });
it('shows Agent 名称 field (speech_title) disabled/read-only', async () => { it('shows Agent 名称 field (speech_title) disabled/read-only', async () => {
...@@ -317,7 +317,7 @@ describe('Agent display config edit modal', () => { ...@@ -317,7 +317,7 @@ describe('Agent display config edit modal', () => {
it('shows 展示素材 field with upload component', () => { it('shows 展示素材 field with upload component', () => {
const modal = screen.getByRole('dialog'); const modal = screen.getByRole('dialog');
expect(within(modal).getByTestId('form-item-展示素材')).toBeInTheDocument(); expect(within(modal).getByText('展示素材')).toBeInTheDocument();
}); });
it('shows 展示排序 field editable', () => { it('shows 展示排序 field editable', () => {
...@@ -346,7 +346,7 @@ describe('Agent display config edit modal', () => { ...@@ -346,7 +346,7 @@ describe('Agent display config edit modal', () => {
it('shows default display_status as 已下架 for unconfigured agent', () => { it('shows default display_status as 已下架 for unconfigured agent', () => {
const modal = screen.getByRole('dialog'); const modal = screen.getByRole('dialog');
expect(within(modal).getByText('已下架')).toBeInTheDocument(); expect(within(modal).getByRole('combobox', { name: '展示状态' })).toHaveAttribute('value', '已下架');
}); });
it('shows empty icon for unconfigured agent', () => { it('shows empty icon for unconfigured agent', () => {
...@@ -420,4 +420,4 @@ describe('Agent display config edit modal', () => { ...@@ -420,4 +420,4 @@ describe('Agent display config edit modal', () => {
); );
}); });
}); });
});
\ No newline at end of file \ No newline at end of file
});
...@@ -252,8 +252,8 @@ describe('Agent display config list', () => { ...@@ -252,8 +252,8 @@ describe('Agent display config list', () => {
it('shows 编辑配置 button for enabled agents', async () => { it('shows 编辑配置 button for enabled agents', async () => {
renderApp(); renderApp();
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('button', { name: '编辑配置-复盘Agent' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '编辑配置-复盘Agent' })).toHaveClass('t-button--theme-primary', 't-button--variant-text');
expect(screen.getByRole('button', { name: '编辑配置-销售助手Agent' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '编辑配置-销售助手Agent' })).toHaveClass('t-button--theme-primary', 't-button--variant-text');
}); });
}); });
...@@ -343,9 +343,11 @@ describe('Agent display config list', () => { ...@@ -343,9 +343,11 @@ describe('Agent display config list', () => {
vi.mocked(getOfficialSiteTabDetail).mockRejectedValueOnce(new Error('Network error')); vi.mocked(getOfficialSiteTabDetail).mockRejectedValueOnce(new Error('Network error'));
renderApp(); renderApp();
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument(); expect(screen.getByText('请求失败')).toBeInTheDocument();
expect(screen.queryByText('请检查网络连接后重试')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
}); });
expect(reportPageView).not.toHaveBeenCalled(); expect(reportPageView).not.toHaveBeenCalled();
}); });
}); });
});
\ No newline at end of file \ No newline at end of file
});
import { useCallback, useState } from 'react'; import { useCallback, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom'; import { useNavigate, useParams } from 'react-router-dom';
import { Button, StatePlaceholder, Table } from '../../../packages/ui/src'; import { BusinessTable, StatePlaceholder, type BusinessTableColumn } from '@gl/business-components';
import { Button } from 'tdesign-react';
import { import {
getAvailableAgents, getAvailableAgents,
type OfficialSiteAvailableAgent, type OfficialSiteAvailableAgent,
...@@ -87,48 +88,24 @@ export function OfficialSiteAgentDisplayConfigPage() { ...@@ -87,48 +88,24 @@ export function OfficialSiteAgentDisplayConfigPage() {
); );
} }
// Error state const columns: BusinessTableColumn<OfficialSiteAvailableAgent>[] = [
if (loadError) {
return (
<section className="grid gap-6">
<header className="flex items-center justify-between gap-6 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6">
<div className="flex items-center gap-4">
<Button variant="outline" onClick={goBackToList}>返回</Button>
<div>
<h2 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">Agent展示配置页</h2>
</div>
</div>
</header>
<div className="grid gap-4 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6">
<StatePlaceholder
state="error"
title="加载失败"
description="岗位展示配置加载失败,请重试"
primaryAction={<Button size="small" onClick={fetchData}>重试</Button>}
/>
</div>
</section>
);
}
const columns = [
{ {
title: 'Agent名称', title: 'Agent名称',
dataIndex: 'agent_name' as const, colKey: 'agent_name',
render: (value: unknown) => <span className="font-medium">{value as string}</span>, cell: ({ row }) => <span className="font-medium">{row.agent_name}</span>,
}, },
{ {
title: 'Agent概述', title: 'Agent概述',
dataIndex: 'speech_content' as const, colKey: 'speech_content',
render: (value: unknown) => ( cell: ({ row }) => (
<span className="max-w-[200px] truncate">{(value as string) || '-'}</span> <span className="max-w-[200px] truncate">{row.speech_content || '-'}</span>
), ),
}, },
{ {
title: '图标', title: '图标',
dataIndex: 'icon_url' as const, colKey: 'icon_url',
render: (value: unknown, item: OfficialSiteAvailableAgent) => { cell: ({ row: item }) => {
const url = value as string; const url = item.icon_url;
if (!url) { if (!url) {
return <span className="text-[var(--gl-color-text-secondary)]">-</span>; return <span className="text-[var(--gl-color-text-secondary)]">-</span>;
} }
...@@ -145,9 +122,9 @@ export function OfficialSiteAgentDisplayConfigPage() { ...@@ -145,9 +122,9 @@ export function OfficialSiteAgentDisplayConfigPage() {
// 展示素材列已移除,编辑弹窗仍保留展示素材字段 // 展示素材列已移除,编辑弹窗仍保留展示素材字段
{ {
title: '状态', title: '状态',
dataIndex: 'agent_status' as const, colKey: 'agent_status',
render: (value: unknown) => { cell: ({ row }) => {
const status = value as AgentStatus; const status = row.agent_status;
const text = mapAgentStatusToText(status); const text = mapAgentStatusToText(status);
return status === 'enable' return status === 'enable'
? <span className="inline-flex items-center rounded-full bg-[var(--gl-color-success-bg)] px-2 py-1 text-xs text-[var(--gl-color-success-text)]">{text}</span> ? <span className="inline-flex items-center rounded-full bg-[var(--gl-color-success-bg)] px-2 py-1 text-xs text-[var(--gl-color-success-text)]">{text}</span>
...@@ -156,8 +133,8 @@ export function OfficialSiteAgentDisplayConfigPage() { ...@@ -156,8 +133,8 @@ export function OfficialSiteAgentDisplayConfigPage() {
}, },
{ {
title: '展示状态', title: '展示状态',
key: 'display_status_display', colKey: 'display_status_display',
render: (_: unknown, item: OfficialSiteAvailableAgent) => { cell: ({ row: item }) => {
const text = getDisplayStatusTextForList(item.agent_status, item.display_status); const text = getDisplayStatusTextForList(item.agent_status, item.display_status);
if (text === '-') { if (text === '-') {
return <span className="text-[var(--gl-color-text-secondary)]">-</span>; return <span className="text-[var(--gl-color-text-secondary)]">-</span>;
...@@ -169,8 +146,8 @@ export function OfficialSiteAgentDisplayConfigPage() { ...@@ -169,8 +146,8 @@ export function OfficialSiteAgentDisplayConfigPage() {
}, },
{ {
title: '操作', title: '操作',
key: 'actions', colKey: 'actions',
render: (_: unknown, item: OfficialSiteAvailableAgent) => { cell: ({ row: item }) => {
if (item.agent_status !== 'enable') { if (item.agent_status !== 'enable') {
return null; return null;
} }
...@@ -179,6 +156,7 @@ export function OfficialSiteAgentDisplayConfigPage() { ...@@ -179,6 +156,7 @@ export function OfficialSiteAgentDisplayConfigPage() {
<Button <Button
aria-label={`编辑配置-${item.agent_name}`} aria-label={`编辑配置-${item.agent_name}`}
size="small" size="small"
theme="primary"
variant="text" variant="text"
onClick={() => handleEditAgent(item)} onClick={() => handleEditAgent(item)}
> >
...@@ -246,14 +224,27 @@ export function OfficialSiteAgentDisplayConfigPage() { ...@@ -246,14 +224,27 @@ export function OfficialSiteAgentDisplayConfigPage() {
Agent 数据源来自该岗位关联的渠道活码。管家 Agent 不参与官网展示。 Agent 数据源来自该岗位关联的渠道活码。管家 Agent 不参与官网展示。
Agent 列表不可增删,仅可编辑展示配置。 Agent 列表不可增删,仅可编辑展示配置。
</p> </p>
<Table {loadError ? (
rowKey="agent_id" <BusinessTable
columns={columns} rowKey="agent_id"
dataSource={items} columns={columns}
empty={{ data={items}
description: '当前无可配置 Agent', error
}} errorState={{
/> onRetry: fetchData,
}}
/>
) : items.length === 0 ? (
<div className="grid gap-4 py-10">
<StatePlaceholder state="empty" title="当前无可配置 Agent" />
</div>
) : (
<BusinessTable
rowKey="agent_id"
columns={columns}
data={items}
/>
)}
</div> </div>
{/* Edit modal */} {/* Edit modal */}
......
import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
...@@ -88,6 +88,12 @@ function renderApp(path = '/official-site/job-tabs/1/agents') { ...@@ -88,6 +88,12 @@ function renderApp(path = '/official-site/job-tabs/1/agents') {
); );
} }
function getMenuItem(label: string) {
const item = within(screen.getByLabelText('左侧导航')).getByText(label).closest('li');
if (!item) throw new Error(`Menu item ${label} was not found`);
return item;
}
describe('official site agent display config routes and navigation', () => { describe('official site agent display config routes and navigation', () => {
beforeEach(() => { beforeEach(() => {
window.localStorage.clear(); window.localStorage.clear();
...@@ -109,24 +115,33 @@ describe('official site agent display config routes and navigation', () => { ...@@ -109,24 +115,33 @@ describe('official site agent display config routes and navigation', () => {
}); });
}); });
it('shows navigation entry under 官网配置 group', () => { it('shows navigation entry under 官网配置 group', async () => {
renderApp(); renderApp();
expect(screen.getByRole('button', { name: '岗位展示配置' })).toBeInTheDocument(); await waitFor(() => {
expect(getMenuItem('岗位展示配置')).toBeInTheDocument();
});
}); });
it('marks 岗位展示配置 navigation entry as active when on agents route', () => { it('marks 岗位展示配置 navigation entry as active when on agents route', async () => {
renderApp(); renderApp();
expect(screen.getByRole('button', { name: '岗位展示配置' })).toHaveAttribute('aria-current', 'page'); await waitFor(() => {
expect(getMenuItem('岗位展示配置')).toHaveClass('t-is-active');
});
}); });
it('shows breadcrumb for agent display config page', () => { it('shows breadcrumb for agent display config page', async () => {
renderApp(); renderApp();
expect(screen.getByText('官网配置 / 岗位展示配置')).toBeInTheDocument(); await waitFor(() => {
expect(screen.getAllByText('官网配置').length).toBeGreaterThan(0);
expect(screen.getAllByText('岗位展示配置').length).toBeGreaterThan(0);
});
}); });
it('shows return to list button', () => { it('shows return to list button', async () => {
renderApp(); renderApp();
expect(screen.getByRole('button', { name: '返回' })).toBeInTheDocument(); await waitFor(() => {
expect(screen.getByRole('button', { name: '返回' })).toBeInTheDocument();
});
}); });
it('shows position name in page title', async () => { it('shows position name in page title', async () => {
...@@ -169,8 +184,9 @@ describe('official site agent display config routes and navigation', () => { ...@@ -169,8 +184,9 @@ describe('official site agent display config routes and navigation', () => {
renderApp(); renderApp();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('加载失败')).toBeInTheDocument(); expect(screen.getByText('请求失败')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '重试' })).toBeInTheDocument(); expect(screen.queryByText('请检查网络连接后重试')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
}); });
}); });
...@@ -179,24 +195,19 @@ describe('official site agent display config routes and navigation', () => { ...@@ -179,24 +195,19 @@ describe('official site agent display config routes and navigation', () => {
renderApp('/official-site/job-tabs/99999/agents'); renderApp('/official-site/job-tabs/99999/agents');
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('加载失败')).toBeInTheDocument(); expect(screen.getByText('请求失败')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '重试' })).toBeInTheDocument(); expect(screen.queryByText('请检查网络连接后重试')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
}); });
}); });
it('can retry after load error', async () => { it('does not render a state-area retry action after load error', async () => {
vi.mocked(getOfficialSiteTabDetail).mockRejectedValueOnce(new Error('加载失败')); vi.mocked(getOfficialSiteTabDetail).mockRejectedValueOnce(new Error('加载失败'));
vi.mocked(getOfficialSiteTabDetail).mockResolvedValueOnce(mockTabDetail);
renderApp(); renderApp();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('加载失败')).toBeInTheDocument(); expect(screen.getByText('请求失败')).toBeInTheDocument();
});
fireEvent.click(screen.getByRole('button', { name: '重试' }));
await waitFor(() => {
expect(screen.getByRole('heading', { name: '店销顾问 Agent展示配置页' })).toBeInTheDocument();
}); });
expect(screen.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
}); });
});
\ No newline at end of file \ No newline at end of file
});
import { fireEvent, render, screen, waitFor, act } from '@testing-library/react'; import { fireEvent, render, screen, waitFor, act, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
import { resetOfficialSiteJobTabMockState } from '../../../packages/contracts/official-site-job-tab-mock'; import { resetOfficialSiteJobTabMockState } from '../../../packages/contracts/official-site-job-tab-mock';
import { resetChannelCodeMockState } from '../../../packages/contracts/channel-code-mock'; import { resetChannelCodeMockState } from '../../../packages/contracts/channel-code-mock';
import { resetAgentTagMockState } from '../../../packages/contracts/agent-tag-mock'; import { resetAgentTagMockState } from '../../../packages/contracts/agent-tag-mock';
import { App } from '../../App'; import { App } from '../../App';
import {
createOfficialSiteTab,
getAvailableQRCodes,
getOfficialSiteTabDetail,
getOfficialSiteTabList,
updateOfficialSiteTab,
type OfficialSiteTabDetail,
type OfficialSiteTabListItem,
} from '../../api/officialSiteTab';
vi.mock('../../api/officialSiteTab', () => ({
createOfficialSiteTab: vi.fn(),
getAvailableQRCodes: vi.fn(),
getOfficialSiteTabDetail: vi.fn(),
getOfficialSiteTabList: vi.fn(),
updateOfficialSiteTab: vi.fn(),
}));
const tabList: OfficialSiteTabListItem[] = [
{
tab_id: 1, position_code: 'store_sales', position_name: '店销顾问', qrcode_id: 1, qrcode_name: '店销顾问渠道活码',
qrcode_url: '', qrcode_status: 'enable', channel_code: 'DSC-QR-001', qrcode_employee_name: '张小萌',
main_title: 'AI 智能助手提升店销效率', sub_title: '通过 AI 智能问答帮助店销顾问快速响应客户需求',
display_status: 'enable', sort_order: 10, agent_count: 3, created_at: '2026-05-10 09:00:00',
},
{
tab_id: 3, position_code: 'crm_growth', position_name: '私域增长', qrcode_id: 5, qrcode_name: '私域增长渠道活码',
qrcode_url: '', qrcode_status: 'enable', channel_code: 'CRM-QR-005', qrcode_employee_name: '陈欣欣',
main_title: 'AI 助力私域精细化运营', sub_title: 'AI 自动分析客户行为数据',
display_status: 'disable', sort_order: 30, agent_count: 0, created_at: '2026-05-12 11:30:00',
},
];
const tabDetails = new Map<number, OfficialSiteTabDetail>([
[1, {
tab_id: 1, position_code: 'store_sales', position_name: '店销顾问', qrcode_id: 1, qrcode_name: '店销顾问渠道活码',
channel_code: 'DSC-QR-001', employee_name: '张小萌', qrcode_employee_name: '张小萌', employee_role_text: '店销主管',
main_title: 'AI 智能助手提升店销效率', sub_title: '通过 AI 智能问答帮助店销顾问快速响应客户需求',
display_status: 'enable', sort_order: 10,
}],
[3, {
tab_id: 3, position_code: 'crm_growth', position_name: '私域增长', qrcode_id: 5, qrcode_name: '私域增长渠道活码',
channel_code: 'CRM-QR-005', employee_name: '陈欣欣', qrcode_employee_name: '陈欣欣', employee_role_text: '私域运营主管',
main_title: 'AI 助力私域精细化运营', sub_title: 'AI 自动分析客户行为数据',
display_status: 'disable', sort_order: 30,
}],
]);
function renderApp(path: string) { function renderApp(path: string) {
window.localStorage.setItem('agent-admin-local-login', 'true'); window.localStorage.setItem('agent-admin-local-login', 'true');
...@@ -23,36 +70,64 @@ function resetAllMockState() { ...@@ -23,36 +70,64 @@ function resetAllMockState() {
resetAgentTagMockState(); resetAgentTagMockState();
} }
async function selectLiveOpsPosition() {
await waitFor(() => {
expect(getAvailableQRCodes).toHaveBeenCalled();
});
fireEvent.click(screen.getByLabelText('对应岗位'));
fireEvent.click(await screen.findByText('直播运营'));
}
describe('OfficialSiteJobTabEditorPage', () => { describe('OfficialSiteJobTabEditorPage', () => {
beforeEach(() => { beforeEach(() => {
resetAllMockState(); resetAllMockState();
vi.clearAllMocks();
vi.mocked(getOfficialSiteTabList).mockResolvedValue({ list: tabList, total: tabList.length, page: 1, page_size: 100 });
vi.mocked(getAvailableQRCodes).mockResolvedValue({
list: [
{ qrcode_id: 3, qrcode_name: '直播运营渠道活码', channel_code: 'live_ops', employee_name: '王大力(直播运营专员)', position_name: '直播运营', status: 'enable' },
{ qrcode_id: 4, qrcode_name: '官网顾问渠道活码', channel_code: 'official_site', employee_name: '赵小美(官网顾问)', position_name: '官网顾问', status: 'enable' },
],
});
vi.mocked(getOfficialSiteTabDetail).mockImplementation(async (tabId) => {
const detail = tabDetails.get(tabId);
if (!detail) throw new Error('岗位展示配置不存在');
return detail;
});
vi.mocked(createOfficialSiteTab).mockResolvedValue({
tab_id: '9', position_code: 'live_ops', position_name: '直播运营', qrcode_id: '3',
main_title: 'AI 标题', sub_title: 'AI 说明', created_at: '2026-05-31 18:00:00',
});
vi.mocked(updateOfficialSiteTab).mockResolvedValue({ success: true, updated_at: '2026-05-31 18:00:00' });
}); });
describe('create mode', () => { describe('create mode', () => {
it('renders page header with title and actions', () => { it('renders page header with title and actions', async () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
expect(screen.getByRole('heading', { name: '新建岗位展示' })).toBeInTheDocument(); expect(await screen.findByRole('heading', { name: '新建岗位展示' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '返回' })).toBeInTheDocument(); const pageHeader = screen.getByRole('heading', { name: '新建岗位展示' }).closest('header') as HTMLElement;
expect(screen.getByRole('button', { name: '取消' })).toBeInTheDocument(); expect(pageHeader).toHaveClass('sticky', 'top-0', 'z-10');
expect(screen.getByRole('button', { name: '保存' })).toBeInTheDocument(); expect(within(pageHeader).getByRole('button', { name: '返回' })).toBeInTheDocument();
expect(within(pageHeader).queryByRole('button', { name: '取消' })).not.toBeInTheDocument();
expect(within(pageHeader).getByRole('button', { name: '保存' })).toBeInTheDocument();
}); });
it('renders required form fields', () => { it('renders required form fields', () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
expect(screen.getByLabelText('岗位标签')).toBeInTheDocument(); expect(screen.getByLabelText('对应岗位')).toBeInTheDocument();
expect(screen.getByLabelText('Tab排序')).toBeInTheDocument(); expect(screen.getByLabelText('Tab排序')).toBeInTheDocument();
expect(screen.getByLabelText('展示状态')).toBeInTheDocument(); expect(screen.getByLabelText('展示状态')).toBeInTheDocument();
}); });
it('shows placeholder text for QR code before position selection', () => { it('shows placeholder text for QR code before position selection', () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
expect(screen.getByText('选择岗位后自动展示')).toBeInTheDocument(); expect(screen.getAllByText('选择岗位后自动展示')).toHaveLength(3);
}); });
it('validates position is required on save', () => { it('validates position is required on save', () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
fireEvent.click(screen.getByRole('button', { name: '保存' })); fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByText('请选择岗位标签')).toBeInTheDocument(); expect(screen.getByText('请选择对应岗位')).toBeInTheDocument();
}); });
it('validates tab order is 0-99 integer', () => { it('validates tab order is 0-99 integer', () => {
...@@ -65,10 +140,10 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -65,10 +140,10 @@ describe('OfficialSiteJobTabEditorPage', () => {
it('shows position select with available candidates (not duplicates)', async () => { it('shows position select with available candidates (not duplicates)', async () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签'); await waitFor(() => {
await act(async () => { expect(getAvailableQRCodes).toHaveBeenCalled();
fireEvent.click(select);
}); });
fireEvent.click(screen.getByLabelText('对应岗位'));
// 直播运营 and 官网顾问 are available (not in existing tabs) and have channel code // 直播运营 and 官网顾问 are available (not in existing tabs) and have channel code
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('直播运营')).toBeInTheDocument(); expect(screen.getByText('直播运营')).toBeInTheDocument();
...@@ -77,13 +152,7 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -77,13 +152,7 @@ describe('OfficialSiteJobTabEditorPage', () => {
it('shows QR code name after selecting position', async () => { it('shows QR code name after selecting position', async () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签'); await selectLiveOpsPosition();
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('直播运营渠道活码')).toBeInTheDocument(); expect(screen.getByText('直播运营渠道活码')).toBeInTheDocument();
}); });
...@@ -91,13 +160,7 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -91,13 +160,7 @@ describe('OfficialSiteJobTabEditorPage', () => {
it('shows derived info after selecting position with channel code', async () => { it('shows derived info after selecting position with channel code', async () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签'); await selectLiveOpsPosition();
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('渠道编码')).toBeInTheDocument(); expect(screen.getByText('渠道编码')).toBeInTheDocument();
expect(screen.getByText('王大力(直播运营专员)')).toBeInTheDocument(); expect(screen.getByText('王大力(直播运营专员)')).toBeInTheDocument();
...@@ -105,14 +168,9 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -105,14 +168,9 @@ describe('OfficialSiteJobTabEditorPage', () => {
}); });
it('shows save error on failure', async () => { it('shows save error on failure', async () => {
vi.mocked(createOfficialSiteTab).mockRejectedValueOnce(new Error('保存失败'));
renderApp('/official-site/job-tabs/new?scenario=saveError'); renderApp('/official-site/job-tabs/new?scenario=saveError');
const select = screen.getByLabelText('岗位标签'); await selectLiveOpsPosition();
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
const orderInput = screen.getByLabelText('Tab排序'); const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '10' } }); fireEvent.change(orderInput, { target: { value: '10' } });
const mainTitleInput = screen.getByLabelText('岗位标题'); const mainTitleInput = screen.getByLabelText('岗位标题');
...@@ -129,13 +187,7 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -129,13 +187,7 @@ describe('OfficialSiteJobTabEditorPage', () => {
it('saves successfully and navigates back to list', async () => { it('saves successfully and navigates back to list', async () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签'); await selectLiveOpsPosition();
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
const orderInput = screen.getByLabelText('Tab排序'); const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '10' } }); fireEvent.change(orderInput, { target: { value: '10' } });
const mainTitleInput = screen.getByLabelText('岗位标题'); const mainTitleInput = screen.getByLabelText('岗位标题');
...@@ -150,43 +202,44 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -150,43 +202,44 @@ describe('OfficialSiteJobTabEditorPage', () => {
}); });
}); });
it('cancels and navigates back to list', () => { it('returns from the sticky page header back to list', async () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
fireEvent.click(screen.getByRole('button', { name: '取消' })); const pageHeader = (await screen.findByRole('heading', { name: '新建岗位展示' })).closest('header') as HTMLElement;
expect(screen.getByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument(); fireEvent.click(within(pageHeader).getByRole('button', { name: '返回' }));
expect(await screen.findByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument();
}); });
}); });
describe('edit mode', () => { describe('edit mode', () => {
it('renders page header with title', () => { it('renders page header with title', async () => {
renderApp('/official-site/job-tabs/1/edit'); renderApp('/official-site/job-tabs/1/edit');
expect(screen.getByRole('heading', { name: '编辑岗位展示' })).toBeInTheDocument(); expect(await screen.findByRole('heading', { name: '编辑岗位展示' })).toBeInTheDocument();
}); });
it('shows position as readonly input', () => { it('shows position as readonly input', async () => {
renderApp('/official-site/job-tabs/1/edit'); renderApp('/official-site/job-tabs/1/edit');
const positionInput = screen.getByLabelText('岗位标签'); const positionInput = await screen.findByLabelText('岗位标签');
expect(positionInput).toHaveProperty('disabled', true); expect(positionInput).toHaveProperty('disabled', true);
expect(positionInput).toHaveValue('店销顾问'); expect(positionInput).toHaveValue('店销顾问');
}); });
it('shows QR code name as readonly', () => { it('shows QR code name as readonly', async () => {
renderApp('/official-site/job-tabs/1/edit'); renderApp('/official-site/job-tabs/1/edit');
expect(screen.getByText('店销顾问渠道活码')).toBeInTheDocument(); expect(await screen.findByText('店销顾问渠道活码')).toBeInTheDocument();
}); });
it('shows derived info from existing record', async () => { it('shows derived info from existing record', async () => {
renderApp('/official-site/job-tabs/1/edit'); renderApp('/official-site/job-tabs/1/edit');
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('渠道编码')).toBeInTheDocument(); expect(screen.getByText('渠道编码')).toBeInTheDocument();
expect(screen.getByText('张小萌(店销主管)')).toBeInTheDocument(); expect(screen.getByText('张小萌')).toBeInTheDocument();
}); });
}); });
it('allows editing tab order and saves successfully', async () => { it('allows editing tab order and saves successfully', async () => {
renderApp('/official-site/job-tabs/1/edit'); renderApp('/official-site/job-tabs/1/edit');
// Find the number input and change its value // Find the number input and change its value
const orderInput = screen.getByRole('spinbutton', { name: 'Tab排序' }) as HTMLInputElement; const orderInput = await screen.findByRole('spinbutton', { name: 'Tab排序' }) as HTMLInputElement;
expect(orderInput.value).toBe('10'); expect(orderInput.value).toBe('10');
fireEvent.change(orderInput, { target: { value: '50' } }); fireEvent.change(orderInput, { target: { value: '50' } });
expect(orderInput.value).toBe('50'); expect(orderInput.value).toBe('50');
...@@ -201,7 +254,7 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -201,7 +254,7 @@ describe('OfficialSiteJobTabEditorPage', () => {
it('allows changing display status and saves successfully', async () => { it('allows changing display status and saves successfully', async () => {
renderApp('/official-site/job-tabs/3/edit'); renderApp('/official-site/job-tabs/3/edit');
// 私域增长 status is 'disable', change to 'enable' // 私域增长 status is 'disable', change to 'enable'
const statusSelect = screen.getByRole('combobox', { name: '展示状态' }); const statusSelect = await screen.findByRole('combobox', { name: '展示状态' });
await act(async () => { await act(async () => {
fireEvent.click(statusSelect); fireEvent.click(statusSelect);
}); });
...@@ -216,15 +269,15 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -216,15 +269,15 @@ describe('OfficialSiteJobTabEditorPage', () => {
}); });
}); });
it('shows error page when record not found', () => { it('shows error page when record not found', async () => {
renderApp('/official-site/job-tabs/999/edit'); renderApp('/official-site/job-tabs/999/edit');
expect(screen.getByText('岗位展示配置不存在')).toBeInTheDocument(); expect(await screen.findByText('岗位展示配置不存在')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '返回列表' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '返回列表' })).toBeInTheDocument();
}); });
it('saves successfully and navigates back to list', async () => { it('saves successfully and navigates back to list', async () => {
renderApp('/official-site/job-tabs/1/edit'); renderApp('/official-site/job-tabs/1/edit');
const orderInput = screen.getByLabelText('Tab排序'); const orderInput = await screen.findByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '20' } }); fireEvent.change(orderInput, { target: { value: '20' } });
await act(async () => { await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '保存' })); fireEvent.click(screen.getByRole('button', { name: '保存' }));
...@@ -247,21 +300,17 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -247,21 +300,17 @@ describe('OfficialSiteJobTabEditorPage', () => {
expect(screen.getByText('展示在官网 Tab 名称下方,用一句话介绍 AI 如何赋能该岗位')).toBeInTheDocument(); expect(screen.getByText('展示在官网 Tab 名称下方,用一句话介绍 AI 如何赋能该岗位')).toBeInTheDocument();
}); });
it('renders sub_title field with tips in create mode', () => { it('renders sub_title field with tips in create mode', async () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
expect(screen.getByLabelText('岗位说明')).toBeInTheDocument(); const subTitleInput = await screen.findByLabelText('岗位说明');
expect(subTitleInput).toBeInTheDocument();
expect(subTitleInput.closest('.t-textarea')).toBeInTheDocument();
expect(screen.getByText('展示在官网 Tab 内容区,用于详细描述 AI 为该岗位带来的价值')).toBeInTheDocument(); expect(screen.getByText('展示在官网 Tab 内容区,用于详细描述 AI 为该岗位带来的价值')).toBeInTheDocument();
}); });
it('validates main_title is required on save', async () => { it('validates main_title is required on save', async () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签'); await selectLiveOpsPosition();
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
const orderInput = screen.getByLabelText('Tab排序'); const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '10' } }); fireEvent.change(orderInput, { target: { value: '10' } });
fireEvent.click(screen.getByRole('button', { name: '保存' })); fireEvent.click(screen.getByRole('button', { name: '保存' }));
...@@ -272,13 +321,7 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -272,13 +321,7 @@ describe('OfficialSiteJobTabEditorPage', () => {
it('validates main_title max 30 chars on save', async () => { it('validates main_title max 30 chars on save', async () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签'); await selectLiveOpsPosition();
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
const orderInput = screen.getByLabelText('Tab排序'); const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '10' } }); fireEvent.change(orderInput, { target: { value: '10' } });
const mainTitleInput = screen.getByLabelText('岗位标题'); const mainTitleInput = screen.getByLabelText('岗位标题');
...@@ -291,13 +334,7 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -291,13 +334,7 @@ describe('OfficialSiteJobTabEditorPage', () => {
it('validates sub_title is required on save', async () => { it('validates sub_title is required on save', async () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签'); await selectLiveOpsPosition();
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
const orderInput = screen.getByLabelText('Tab排序'); const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '10' } }); fireEvent.change(orderInput, { target: { value: '10' } });
const mainTitleInput = screen.getByLabelText('岗位标题'); const mainTitleInput = screen.getByLabelText('岗位标题');
...@@ -310,13 +347,7 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -310,13 +347,7 @@ describe('OfficialSiteJobTabEditorPage', () => {
it('validates sub_title max 200 chars on save', async () => { it('validates sub_title max 200 chars on save', async () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签'); await selectLiveOpsPosition();
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
const orderInput = screen.getByLabelText('Tab排序'); const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '10' } }); fireEvent.change(orderInput, { target: { value: '10' } });
const mainTitleInput = screen.getByLabelText('岗位标题'); const mainTitleInput = screen.getByLabelText('岗位标题');
...@@ -332,13 +363,7 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -332,13 +363,7 @@ describe('OfficialSiteJobTabEditorPage', () => {
it('saves main_title and sub_title successfully in create mode', async () => { it('saves main_title and sub_title successfully in create mode', async () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签'); await selectLiveOpsPosition();
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
const orderInput = screen.getByLabelText('Tab排序'); const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '10' } }); fireEvent.change(orderInput, { target: { value: '10' } });
const mainTitleInput = screen.getByLabelText('岗位标题'); const mainTitleInput = screen.getByLabelText('岗位标题');
...@@ -353,15 +378,15 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -353,15 +378,15 @@ describe('OfficialSiteJobTabEditorPage', () => {
}); });
}); });
it('renders AI intro section header in edit mode', () => { it('renders AI intro section header in edit mode', async () => {
renderApp('/official-site/job-tabs/1/edit'); renderApp('/official-site/job-tabs/1/edit');
expect(screen.getByText('岗位 AI 赋能介绍')).toBeInTheDocument(); expect(await screen.findByText('岗位 AI 赋能介绍')).toBeInTheDocument();
}); });
it('fills main_title and sub_title from existing record in edit mode', async () => { it('fills main_title and sub_title from existing record in edit mode', async () => {
renderApp('/official-site/job-tabs/1/edit'); renderApp('/official-site/job-tabs/1/edit');
const mainTitleInput = screen.getByLabelText('岗位标题') as HTMLInputElement; const mainTitleInput = await screen.findByLabelText('岗位标题') as HTMLInputElement;
const subTitleInput = screen.getByLabelText('岗位说明') as HTMLTextAreaElement; const subTitleInput = await screen.findByLabelText('岗位说明') as HTMLTextAreaElement;
await waitFor(() => { await waitFor(() => {
expect(mainTitleInput.value).toBe('AI 智能助手提升店销效率'); expect(mainTitleInput.value).toBe('AI 智能助手提升店销效率');
expect(subTitleInput.value).toContain('AI 智能问答'); expect(subTitleInput.value).toContain('AI 智能问答');
...@@ -370,8 +395,8 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -370,8 +395,8 @@ describe('OfficialSiteJobTabEditorPage', () => {
it('allows editing main_title and sub_title in edit mode and saves', async () => { it('allows editing main_title and sub_title in edit mode and saves', async () => {
renderApp('/official-site/job-tabs/1/edit'); renderApp('/official-site/job-tabs/1/edit');
const mainTitleInput = screen.getByLabelText('岗位标题'); const mainTitleInput = await screen.findByLabelText('岗位标题');
const subTitleInput = screen.getByLabelText('岗位说明'); const subTitleInput = await screen.findByLabelText('岗位说明');
fireEvent.change(mainTitleInput, { target: { value: '更新后的标题' } }); fireEvent.change(mainTitleInput, { target: { value: '更新后的标题' } });
fireEvent.change(subTitleInput, { target: { value: '更新后的说明内容' } }); fireEvent.change(subTitleInput, { target: { value: '更新后的说明内容' } });
await act(async () => { await act(async () => {
...@@ -382,4 +407,4 @@ describe('OfficialSiteJobTabEditorPage', () => { ...@@ -382,4 +407,4 @@ describe('OfficialSiteJobTabEditorPage', () => {
}); });
}); });
}); });
});
\ No newline at end of file \ No newline at end of file
});
import { useState } from 'react'; import { useState } from 'react';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom'; import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Button } from 'tdesign-react';
import { Button, FormItem, Input, Select, StatePlaceholder, Switch } from '../../../packages/ui/src'; import { StatePlaceholder } from '@gl/business-components';
import { FormItem, Input, Select, Textarea } from '../../components/TDesignAccessibleControls';
import { import {
getOfficialSiteTabList, getOfficialSiteTabList,
getOfficialSiteTabDetail,
updateOfficialSiteTab, updateOfficialSiteTab,
createOfficialSiteTab, createOfficialSiteTab,
getAvailableQRCodes, getAvailableQRCodes,
type OfficialSiteTabListItem, type OfficialSiteTabListItem,
type OfficialSiteTabDetail,
type AvailableOfficialSiteQRCodeItem, type AvailableOfficialSiteQRCodeItem,
type OfficialSiteTabStatus, type OfficialSiteTabStatus,
} from '../../api/officialSiteTab'; } from '../../api/officialSiteTab';
...@@ -40,7 +44,9 @@ interface SaveNotice { ...@@ -40,7 +44,9 @@ interface SaveNotice {
message: string; message: string;
} }
function buildInitialFormState(tab?: OfficialSiteTabListItem): TabFormState { type OfficialSiteTabEditorItem = OfficialSiteTabListItem | OfficialSiteTabDetail;
function buildInitialFormState(tab?: OfficialSiteTabEditorItem): TabFormState {
return { return {
position_code: tab?.position_code ?? '', position_code: tab?.position_code ?? '',
position_name: tab?.position_name ?? '', position_name: tab?.position_name ?? '',
...@@ -66,7 +72,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -66,7 +72,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
const routeTab = (location.state as { tab?: OfficialSiteTabListItem } | null)?.tab; const routeTab = (location.state as { tab?: OfficialSiteTabListItem } | null)?.tab;
const [loading, setLoading] = useState(mode === 'edit' && !routeTab); const [loading, setLoading] = useState(mode === 'edit' && !routeTab);
const [loadError, setLoadError] = useState(false); const [loadError, setLoadError] = useState(false);
const [currentTab, setCurrentTab] = useState<OfficialSiteTabListItem | undefined>(() => routeTab); const [currentTab, setCurrentTab] = useState<OfficialSiteTabEditorItem | undefined>(() => routeTab);
const [form, setForm] = useState<TabFormState>(() => buildInitialFormState(currentTab)); const [form, setForm] = useState<TabFormState>(() => buildInitialFormState(currentTab));
const [errors, setErrors] = useState<TabFormErrors>({}); const [errors, setErrors] = useState<TabFormErrors>({});
const [notice, setNotice] = useState<SaveNotice | null>(null); const [notice, setNotice] = useState<SaveNotice | null>(null);
...@@ -98,15 +104,10 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -98,15 +104,10 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
useDeferredEffect(() => { useDeferredEffect(() => {
if (mode === 'edit' && !routeTab && params.tabId) { if (mode === 'edit' && !routeTab && params.tabId) {
setLoading(true); setLoading(true);
getOfficialSiteTabList({ page: 1, page_size: 100 }) getOfficialSiteTabDetail(Number(params.tabId))
.then((response) => { .then((tab) => {
const tab = response.list.find((t) => t.tab_id === Number(params.tabId)); setCurrentTab(tab);
if (tab) { setForm(buildInitialFormState(tab));
setCurrentTab(tab);
setForm(buildInitialFormState(tab));
} else {
setLoadError(true);
}
setLoading(false); setLoading(false);
}) })
.catch(() => { .catch(() => {
...@@ -220,7 +221,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -220,7 +221,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
return ( return (
<section className="grid gap-6"> <section className="grid gap-6">
<header className="flex items-center justify-between gap-6 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6"> <header className="sticky top-0 z-10 flex items-center justify-between gap-6 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6">
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<Button variant="outline" onClick={goBackToList}>返回</Button> <Button variant="outline" onClick={goBackToList}>返回</Button>
<div> <div>
...@@ -232,10 +233,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -232,10 +233,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
</p> </p>
</div> </div>
</div> </div>
<div className="flex items-center gap-3"> <Button theme="primary" loading={saving} onClick={handleSave}>保存</Button>
<Button variant="outline" onClick={goBackToList}>取消</Button>
<Button variant="primary" loading={saving} onClick={handleSave}>保存</Button>
</div>
</header> </header>
{notice ? ( {notice ? (
...@@ -254,7 +252,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -254,7 +252,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
<div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10"> <div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10">
<div className="mx-auto grid max-w-[760px] gap-6"> <div className="mx-auto grid max-w-[760px] gap-6">
<FormItem label="对应岗位" layout="horizontal" required={mode === 'create'} error={errors.position_code}> <FormItem label="对应岗位" labelAlign="left" requiredMark={mode === 'create'} status={errors.position_code ? 'error' : undefined} tips={errors.position_code}>
{mode === 'edit' ? ( {mode === 'edit' ? (
<Input <Input
aria-label="岗位标签" aria-label="岗位标签"
...@@ -291,7 +289,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -291,7 +289,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
)} )}
</FormItem> </FormItem>
<FormItem label="关联渠道活码" layout="horizontal"> <FormItem label="关联渠道活码" labelAlign="left">
<div className={fieldWidthClassName}> <div className={fieldWidthClassName}>
{form.qrcode_name || currentTab?.qrcode_name || (mode === 'create' && !form.position_code ? ( {form.qrcode_name || currentTab?.qrcode_name || (mode === 'create' && !form.position_code ? (
<span className="text-sm text-[var(--gl-color-text-secondary)]">选择岗位后自动展示</span> <span className="text-sm text-[var(--gl-color-text-secondary)]">选择岗位后自动展示</span>
...@@ -299,7 +297,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -299,7 +297,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
</div> </div>
</FormItem> </FormItem>
<FormItem label="渠道编码" layout="horizontal"> <FormItem label="渠道编码" labelAlign="left">
<div className={fieldWidthClassName}> <div className={fieldWidthClassName}>
{form.channel_code || currentTab?.channel_code || (mode === 'create' && !form.position_code ? ( {form.channel_code || currentTab?.channel_code || (mode === 'create' && !form.position_code ? (
<span className="text-sm text-[var(--gl-color-text-secondary)]">选择岗位后自动展示</span> <span className="text-sm text-[var(--gl-color-text-secondary)]">选择岗位后自动展示</span>
...@@ -307,7 +305,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -307,7 +305,7 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
</div> </div>
</FormItem> </FormItem>
<FormItem label="承接员工" layout="horizontal"> <FormItem label="承接员工" labelAlign="left">
<div className={fieldWidthClassName}> <div className={fieldWidthClassName}>
{form.employee_name || currentTab?.qrcode_employee_name || (mode === 'create' && !form.position_code ? ( {form.employee_name || currentTab?.qrcode_employee_name || (mode === 'create' && !form.position_code ? (
<span className="text-sm text-[var(--gl-color-text-secondary)]">选择岗位后自动展示</span> <span className="text-sm text-[var(--gl-color-text-secondary)]">选择岗位后自动展示</span>
...@@ -319,12 +317,13 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -319,12 +317,13 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
<h3 className="m-0 text-lg font-semibold leading-[var(--gl-line-height-lg)]">岗位 AI 赋能介绍</h3> <h3 className="m-0 text-lg font-semibold leading-[var(--gl-line-height-lg)]">岗位 AI 赋能介绍</h3>
<FormItem label="岗位标题" layout="horizontal" required error={errors.main_title}> <FormItem label="岗位标题" labelAlign="left" requiredMark status={errors.main_title ? 'error' : undefined} tips={errors.main_title}>
<div className={fieldWidthClassName}> <div className={fieldWidthClassName}>
<Input <Input
aria-label="岗位标题" aria-label="岗位标题"
placeholder="请输入岗位标题" placeholder="请输入岗位标题"
maxLength={30} maxlength={30}
allowInputOverMax
value={form.main_title} value={form.main_title}
onChange={(value) => setForm((current) => ({ ...current, main_title: value }))} onChange={(value) => setForm((current) => ({ ...current, main_title: value }))}
/> />
...@@ -332,35 +331,35 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' ...@@ -332,35 +331,35 @@ export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit'
</div> </div>
</FormItem> </FormItem>
<FormItem label="岗位说明" layout="horizontal" required error={errors.sub_title}> <FormItem label="岗位说明" labelAlign="left" requiredMark status={errors.sub_title ? 'error' : undefined} tips={errors.sub_title}>
<div className={fieldWidthClassName}> <div className={fieldWidthClassName}>
<textarea <Textarea
aria-label="岗位说明" aria-label="岗位说明"
className="w-full rounded-[var(--gl-radius-sm)] border border-[var(--gl-color-border)] bg-[var(--gl-color-bg-container)] px-3 py-2 text-sm leading-[var(--gl-line-height-base)] placeholder:text-[var(--gl-color-text-secondary)] focus:border-[var(--gl-color-primary)] focus:outline-none" className="w-full"
placeholder="请输入岗位说明" placeholder="请输入岗位说明"
maxLength={200} maxlength={200}
allowInputOverMax
count
rows={4} rows={4}
value={form.sub_title} value={form.sub_title}
onChange={(e) => setForm((current) => ({ ...current, sub_title: e.target.value }))} onChange={(value) => setForm((current) => ({ ...current, sub_title: value }))}
/> />
<p className="m-0 mt-1 text-xs text-[var(--gl-color-text-secondary)]">展示在官网 Tab 内容区,用于详细描述 AI 为该岗位带来的价值</p> <p className="m-0 mt-1 text-xs text-[var(--gl-color-text-secondary)]">展示在官网 Tab 内容区,用于详细描述 AI 为该岗位带来的价值</p>
</div> </div>
</FormItem> </FormItem>
<FormItem label="Tab 排序" layout="horizontal" required error={errors.tab_order}> <FormItem label="Tab 排序" labelAlign="left" requiredMark status={errors.tab_order ? 'error' : undefined} tips={errors.tab_order}>
<Input <Input
aria-label="Tab排序" aria-label="Tab排序"
className={fieldWidthClassName} className={fieldWidthClassName}
type="number" type="number"
min={0}
max={99}
placeholder="请输入Tab排序(0-99)" placeholder="请输入Tab排序(0-99)"
value={form.tab_order === undefined || form.tab_order === null || (typeof form.tab_order === 'number' && isNaN(form.tab_order)) ? '' : String(form.tab_order)} value={form.tab_order === undefined || form.tab_order === null || (typeof form.tab_order === 'number' && isNaN(form.tab_order)) ? '' : String(form.tab_order)}
onChange={(value) => setForm((current) => ({ ...current, tab_order: value === '' ? undefined as unknown as number : Number(value) }))} onChange={(value) => setForm((current) => ({ ...current, tab_order: value === '' ? undefined as unknown as number : Number(value) }))}
/> />
</FormItem> </FormItem>
<FormItem label="展示状态" layout="horizontal" required> <FormItem label="展示状态" labelAlign="left" requiredMark>
<Select <Select
aria-label="展示状态" aria-label="展示状态"
className={fieldWidthClassName} className={fieldWidthClassName}
......
...@@ -195,6 +195,7 @@ describe('OfficialSiteJobTabListPage', () => { ...@@ -195,6 +195,7 @@ describe('OfficialSiteJobTabListPage', () => {
expect(screen.getByText('店销顾问')).toBeInTheDocument(); expect(screen.getByText('店销顾问')).toBeInTheDocument();
}); });
expect(screen.getByLabelText('关键词')).toBeInTheDocument(); expect(screen.getByLabelText('关键词')).toBeInTheDocument();
expect(screen.getByPlaceholderText('搜索岗位名称或渠道活码')).toBeInTheDocument();
expect(screen.getByLabelText('展示状态')).toBeInTheDocument(); expect(screen.getByLabelText('展示状态')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '搜索' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '搜索' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '重置' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '重置' })).toBeInTheDocument();
...@@ -209,7 +210,7 @@ describe('OfficialSiteJobTabListPage', () => { ...@@ -209,7 +210,7 @@ describe('OfficialSiteJobTabListPage', () => {
// 渠道活码 appears in header and possibly in data // 渠道活码 appears in header and possibly in data
expect(screen.getAllByText('渠道活码').length).toBeGreaterThan(0); expect(screen.getAllByText('渠道活码').length).toBeGreaterThan(0);
expect(screen.getByText('Tab 排序')).toBeInTheDocument(); expect(screen.getByText('Tab 排序')).toBeInTheDocument();
expect(screen.getByText('展示状态')).toBeInTheDocument(); expect(screen.getAllByText('展示状态').length).toBeGreaterThan(0);
expect(screen.getByText('更新时间')).toBeInTheDocument(); expect(screen.getByText('更新时间')).toBeInTheDocument();
expect(screen.getByText('操作')).toBeInTheDocument(); expect(screen.getByText('操作')).toBeInTheDocument();
}); });
...@@ -219,8 +220,7 @@ describe('OfficialSiteJobTabListPage', () => { ...@@ -219,8 +220,7 @@ describe('OfficialSiteJobTabListPage', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('店销顾问')).toBeInTheDocument(); expect(screen.getByText('店销顾问')).toBeInTheDocument();
}); });
// Pagination component exists as navigation expect(screen.getByText('1').closest('li')).toHaveClass('t-is-current');
expect(screen.getByRole('navigation')).toBeInTheDocument();
}); });
it('shows empty state when no data', async () => { it('shows empty state when no data', async () => {
...@@ -232,12 +232,12 @@ describe('OfficialSiteJobTabListPage', () => { ...@@ -232,12 +232,12 @@ describe('OfficialSiteJobTabListPage', () => {
}); });
renderApp(); renderApp();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('当前还没有岗位展示配置')).toBeInTheDocument(); expect(screen.getByText('暂无数据')).toBeInTheDocument();
}); });
}); });
it('shows filtered empty state', async () => { it('shows filtered empty state', async () => {
vi.mocked(getOfficialSiteTabList).mockResolvedValueOnce({ vi.mocked(getOfficialSiteTabList).mockResolvedValue({
list: [], list: [],
total: 0, total: 0,
page: 1, page: 1,
...@@ -249,34 +249,31 @@ describe('OfficialSiteJobTabListPage', () => { ...@@ -249,34 +249,31 @@ describe('OfficialSiteJobTabListPage', () => {
fireEvent.click(screen.getByRole('button', { name: '搜索' })); fireEvent.click(screen.getByRole('button', { name: '搜索' }));
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('未找到匹配结果')).toBeInTheDocument(); expect(screen.getByText('未找到匹配结果')).toBeInTheDocument();
expect(screen.queryByText('暂无数据')).not.toBeInTheDocument();
expect(screen.queryByText('未能查询到符合条件的资源')).not.toBeInTheDocument();
expect(screen.queryByText('请调整搜索或筛选条件')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '清空筛选' })).not.toBeInTheDocument();
}); });
}); });
it('shows load error state with retry button', async () => { it('shows load error state without description or retry button', async () => {
vi.mocked(getOfficialSiteTabList).mockRejectedValueOnce(new Error('Network error')); vi.mocked(getOfficialSiteTabList).mockRejectedValue(new Error('Network error'));
renderApp(); renderApp();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('加载失败')).toBeInTheDocument(); expect(screen.getByText('请求失败')).toBeInTheDocument();
expect(screen.queryByText('岗位展示配置列表加载失败,请重试')).not.toBeInTheDocument();
expect(screen.queryByText('请检查网络连接后重试')).not.toBeInTheDocument();
}); });
expect(screen.getByRole('button', { name: '重试' })).toBeInTheDocument(); expect(screen.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
}); });
it('can retry after load error', async () => { it('does not render a state-area retry action after load error', async () => {
vi.mocked(getOfficialSiteTabList).mockRejectedValueOnce(new Error('Network error')); vi.mocked(getOfficialSiteTabList).mockRejectedValue(new Error('Network error'));
renderApp(); renderApp();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('加载失败')).toBeInTheDocument(); expect(screen.getByText('请求失败')).toBeInTheDocument();
});
vi.mocked(getOfficialSiteTabList).mockResolvedValueOnce({
list: mockJobTabs,
total: mockJobTabs.length,
page: 1,
page_size: 10,
});
fireEvent.click(screen.getByRole('button', { name: '重试' }));
await waitFor(() => {
expect(screen.getByText('店销顾问')).toBeInTheDocument();
}); });
expect(screen.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
}); });
it('can search by keyword', async () => { it('can search by keyword', async () => {
...@@ -298,17 +295,24 @@ describe('OfficialSiteJobTabListPage', () => { ...@@ -298,17 +295,24 @@ describe('OfficialSiteJobTabListPage', () => {
}); });
}); });
it('can filter by display status', async () => { it('submits display status filtering only after clicking search', async () => {
renderApp(); renderApp();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('店销顾问')).toBeInTheDocument(); expect(screen.getByText('店销顾问')).toBeInTheDocument();
}); });
vi.clearAllMocks();
const statusSelect = screen.getByLabelText('展示状态'); const statusSelect = screen.getByLabelText('展示状态');
await act(async () => { await act(async () => {
fireEvent.click(statusSelect); fireEvent.click(statusSelect);
}); });
const disabledOptions = screen.getAllByText('已下架'); const disabledOptions = screen.getAllByText('已下架');
const dropdownOption = disabledOptions.find((el) => el.closest('[role="option"]')); const dropdownOption = disabledOptions.find((el) => el.closest('[role="option"]'));
await act(async () => {
fireEvent.click(dropdownOption ?? disabledOptions[0]);
});
expect(getOfficialSiteTabList).not.toHaveBeenCalled();
vi.mocked(getOfficialSiteTabList).mockResolvedValueOnce({ vi.mocked(getOfficialSiteTabList).mockResolvedValueOnce({
list: mockJobTabs.filter((t) => t.display_status === 'disable'), list: mockJobTabs.filter((t) => t.display_status === 'disable'),
total: 1, total: 1,
...@@ -316,7 +320,7 @@ describe('OfficialSiteJobTabListPage', () => { ...@@ -316,7 +320,7 @@ describe('OfficialSiteJobTabListPage', () => {
page_size: 10, page_size: 10,
}); });
await act(async () => { await act(async () => {
fireEvent.click(dropdownOption ?? disabledOptions[0]); fireEvent.click(screen.getByRole('button', { name: '搜索' }));
}); });
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('私域增长')).toBeInTheDocument(); expect(screen.getByText('私域增长')).toBeInTheDocument();
...@@ -353,6 +357,7 @@ describe('OfficialSiteJobTabListPage', () => { ...@@ -353,6 +357,7 @@ describe('OfficialSiteJobTabListPage', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('button', { name: '编辑店销顾问' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '编辑店销顾问' })).toBeInTheDocument();
}); });
expect(screen.getByRole('button', { name: '编辑店销顾问' })).toHaveClass('t-button--theme-primary', 't-button--variant-text');
fireEvent.click(screen.getByRole('button', { name: '编辑店销顾问' })); fireEvent.click(screen.getByRole('button', { name: '编辑店销顾问' }));
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('heading', { name: '编辑岗位展示' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '编辑岗位展示' })).toBeInTheDocument();
...@@ -364,6 +369,7 @@ describe('OfficialSiteJobTabListPage', () => { ...@@ -364,6 +369,7 @@ describe('OfficialSiteJobTabListPage', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('button', { name: '配置Agent-店销顾问' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '配置Agent-店销顾问' })).toBeInTheDocument();
}); });
expect(screen.getByRole('button', { name: '配置Agent-店销顾问' })).toHaveClass('t-button--theme-primary', 't-button--variant-text');
fireEvent.click(screen.getByRole('button', { name: '配置Agent-店销顾问' })); fireEvent.click(screen.getByRole('button', { name: '配置Agent-店销顾问' }));
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('heading', { name: '店销顾问 Agent展示配置页' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '店销顾问 Agent展示配置页' })).toBeInTheDocument();
...@@ -375,6 +381,7 @@ describe('OfficialSiteJobTabListPage', () => { ...@@ -375,6 +381,7 @@ describe('OfficialSiteJobTabListPage', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('button', { name: '上架私域增长' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '上架私域增长' })).toBeInTheDocument();
}); });
expect(screen.getByRole('button', { name: '上架私域增长' })).toHaveClass('t-button--theme-primary', 't-button--variant-text');
}); });
it('shows disable button for enabled items', async () => { it('shows disable button for enabled items', async () => {
...@@ -382,6 +389,7 @@ describe('OfficialSiteJobTabListPage', () => { ...@@ -382,6 +389,7 @@ describe('OfficialSiteJobTabListPage', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('button', { name: '下架店销顾问' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '下架店销顾问' })).toBeInTheDocument();
}); });
expect(screen.getByRole('button', { name: '下架店销顾问' })).toHaveClass('t-button--theme-primary', 't-button--variant-text');
}); });
it('shows delete button for all items', async () => { it('shows delete button for all items', async () => {
...@@ -389,6 +397,7 @@ describe('OfficialSiteJobTabListPage', () => { ...@@ -389,6 +397,7 @@ describe('OfficialSiteJobTabListPage', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('button', { name: '删除店销顾问' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '删除店销顾问' })).toBeInTheDocument();
}); });
expect(screen.getByRole('button', { name: '删除店销顾问' })).toHaveClass('t-button--theme-primary', 't-button--variant-text');
}); });
it('shows enable confirmation modal', async () => { it('shows enable confirmation modal', async () => {
...@@ -519,7 +528,7 @@ describe('OfficialSiteJobTabListPage', () => { ...@@ -519,7 +528,7 @@ describe('OfficialSiteJobTabListPage', () => {
vi.mocked(getOfficialSiteTabList).mockRejectedValueOnce(new Error('Network error')); vi.mocked(getOfficialSiteTabList).mockRejectedValueOnce(new Error('Network error'));
renderApp(); renderApp();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('加载失败')).toBeInTheDocument(); expect(screen.getByText('请求失败')).toBeInTheDocument();
}); });
expect(reportPageView).not.toHaveBeenCalled(); expect(reportPageView).not.toHaveBeenCalled();
}); });
......
import { useState } from 'react'; import { useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button, Input, Modal, Pagination, Select, StatePlaceholder, Table } from '../../../packages/ui/src'; import { BusinessTable, SearchFilter, type BusinessTableColumn, type SearchFilterValues } from '@gl/business-components';
import { Button, Dialog } from 'tdesign-react';
import { import {
getOfficialSiteTabList, getOfficialSiteTabList,
updateOfficialSiteTabStatus, updateOfficialSiteTabStatus,
...@@ -23,6 +24,7 @@ export function OfficialSiteJobTabListPage() { ...@@ -23,6 +24,7 @@ export function OfficialSiteJobTabListPage() {
const [searchParams, setSearchParams] = useSearchParams(); const [searchParams, setSearchParams] = useSearchParams();
const routeState = readOfficialSiteJobTabListRouteState(searchParams); const routeState = readOfficialSiteJobTabListRouteState(searchParams);
const [keyword, setKeyword] = useState(routeState.keyword); const [keyword, setKeyword] = useState(routeState.keyword);
const [displayStatus, setDisplayStatus] = useState<'' | 'enable' | 'disable'>(routeState.displayStatus === 'all' ? '' : routeState.displayStatus);
const [notice, setNotice] = useState<PageNotice | null>(null); const [notice, setNotice] = useState<PageNotice | null>(null);
const [statusTarget, setStatusTarget] = useState<{ tab: OfficialSiteTabListItem; action: 'enable' | 'disable' } | null>(null); const [statusTarget, setStatusTarget] = useState<{ tab: OfficialSiteTabListItem; action: 'enable' | 'disable' } | null>(null);
const [deleteTarget, setDeleteTarget] = useState<OfficialSiteTabListItem | null>(null); const [deleteTarget, setDeleteTarget] = useState<OfficialSiteTabListItem | null>(null);
...@@ -63,10 +65,14 @@ export function OfficialSiteJobTabListPage() { ...@@ -63,10 +65,14 @@ export function OfficialSiteJobTabListPage() {
pageSize: routeState.pageSize, pageSize: routeState.pageSize,
}); });
const submitFilters = () => { const submitFilters = (filterValues: SearchFilterValues = { keyword, displayStatus }) => {
const nextKeyword = String(filterValues.keyword ?? '');
const nextDisplayStatus = String(filterValues.displayStatus ?? '') as '' | 'enable' | 'disable';
setKeyword(nextKeyword);
setDisplayStatus(nextDisplayStatus);
setSearchParams(buildOfficialSiteJobTabListSearch({ setSearchParams(buildOfficialSiteJobTabListSearch({
keyword, keyword: nextKeyword,
displayStatus: routeState.displayStatus, displayStatus: nextDisplayStatus || 'all',
page: 1, page: 1,
pageSize: routeState.pageSize, pageSize: routeState.pageSize,
})); }));
...@@ -74,6 +80,7 @@ export function OfficialSiteJobTabListPage() { ...@@ -74,6 +80,7 @@ export function OfficialSiteJobTabListPage() {
const resetFilters = () => { const resetFilters = () => {
setKeyword(''); setKeyword('');
setDisplayStatus('');
setSearchParams(buildOfficialSiteJobTabListSearch({ setSearchParams(buildOfficialSiteJobTabListSearch({
keyword: '', keyword: '',
displayStatus: 'all', displayStatus: 'all',
...@@ -82,35 +89,35 @@ export function OfficialSiteJobTabListPage() { ...@@ -82,35 +89,35 @@ export function OfficialSiteJobTabListPage() {
})); }));
}; };
const columns = [ const columns: BusinessTableColumn<OfficialSiteTabListItem>[] = [
{ title: '岗位名称', dataIndex: 'position_name' as const }, { title: '岗位名称', colKey: 'position_name' },
{ title: '渠道活码', dataIndex: 'qrcode_name' as const }, { title: '渠道活码', colKey: 'qrcode_name' },
{ title: 'Tab 排序', dataIndex: 'sort_order' as const }, { title: 'Tab 排序', colKey: 'sort_order' },
{ title: '展示Agent数', dataIndex: 'agent_count' as const }, { title: '展示Agent数', colKey: 'agent_count' },
{ {
title: '展示状态', title: '展示状态',
dataIndex: 'display_status' as const, colKey: 'display_status',
render: (value: unknown) => { cell: ({ row }) => {
const status = value as OfficialSiteTabStatus; const status = row.display_status as OfficialSiteTabStatus;
return status === 'enable' return status === 'enable'
? <span className="inline-flex items-center rounded-full bg-[var(--gl-color-success-bg)] px-2 py-1 text-xs text-[var(--gl-color-success-text)]">展示中</span> ? <span className="inline-flex items-center rounded-full bg-[var(--gl-color-success-bg)] px-2 py-1 text-xs text-[var(--gl-color-success-text)]">展示中</span>
: <span className="inline-flex items-center rounded-full bg-[var(--gl-color-warning-bg)] px-2 py-1 text-xs text-[var(--gl-color-warning-text)]">已下架</span>; : <span className="inline-flex items-center rounded-full bg-[var(--gl-color-warning-bg)] px-2 py-1 text-xs text-[var(--gl-color-warning-text)]">已下架</span>;
}, },
}, },
{ title: '更新时间', dataIndex: 'created_at' as const }, { title: '更新时间', colKey: 'created_at' },
{ {
title: '操作', title: '操作',
key: 'actions', colKey: 'actions',
render: (_: unknown, item: OfficialSiteTabListItem) => { cell: ({ row: item }) => {
const canEnable = item.display_status === 'disable'; const canEnable = item.display_status === 'disable';
const canDisable = item.display_status === 'enable'; const canDisable = item.display_status === 'enable';
return ( return (
<span className="flex flex-wrap gap-1"> <span className="flex flex-wrap gap-1">
<Button aria-label={`配置Agent-${item.position_name}`} size="small" variant="text" onClick={() => navigate(`/official-site/job-tabs/${item.tab_id}/agents`)}>配置Agent</Button> <Button aria-label={`配置Agent-${item.position_name}`} size="small" theme="primary" variant="text" onClick={() => navigate(`/official-site/job-tabs/${item.tab_id}/agents`)}>配置Agent</Button>
<Button aria-label={`编辑${item.position_name}`} size="small" variant="text" onClick={() => navigate(`/official-site/job-tabs/${item.tab_id}/edit${routeSearch}`, { state: { tab: item } })}>编辑</Button> <Button aria-label={`编辑${item.position_name}`} size="small" theme="primary" variant="text" onClick={() => navigate(`/official-site/job-tabs/${item.tab_id}/edit${routeSearch}`, { state: { tab: item } })}>编辑</Button>
{canEnable ? <Button aria-label={`上架${item.position_name}`} size="small" variant="text" onClick={() => setStatusTarget({ tab: item, action: 'enable' })}>上架</Button> : null} {canEnable ? <Button aria-label={`上架${item.position_name}`} size="small" theme="primary" variant="text" onClick={() => setStatusTarget({ tab: item, action: 'enable' })}>上架</Button> : null}
{canDisable ? <Button aria-label={`下架${item.position_name}`} size="small" variant="text" onClick={() => setStatusTarget({ tab: item, action: 'disable' })}>下架</Button> : null} {canDisable ? <Button aria-label={`下架${item.position_name}`} size="small" theme="primary" variant="text" onClick={() => setStatusTarget({ tab: item, action: 'disable' })}>下架</Button> : null}
<Button aria-label={`删除${item.position_name}`} size="small" variant="text" onClick={() => setDeleteTarget(item)}>删除</Button> <Button aria-label={`删除${item.position_name}`} size="small" theme="primary" variant="text" onClick={() => setDeleteTarget(item)}>删除</Button>
</span> </span>
); );
}, },
...@@ -124,7 +131,7 @@ export function OfficialSiteJobTabListPage() { ...@@ -124,7 +131,7 @@ export function OfficialSiteJobTabListPage() {
<h2 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">岗位展示配置</h2> <h2 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">岗位展示配置</h2>
<p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">管理官网岗位 Tab 的列表、新建、编辑、上架、下架和删除</p> <p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">管理官网岗位 Tab 的列表、新建、编辑、上架、下架和删除</p>
</div> </div>
<Button variant="primary" onClick={() => navigate(`/official-site/job-tabs/new${routeSearch}`)}>新建岗位展示</Button> <Button theme="primary" onClick={() => navigate(`/official-site/job-tabs/new${routeSearch}`)}>新建岗位展示</Button>
</header> </header>
{notice ? ( {notice ? (
...@@ -141,96 +148,73 @@ export function OfficialSiteJobTabListPage() { ...@@ -141,96 +148,73 @@ export function OfficialSiteJobTabListPage() {
</div> </div>
) : null} ) : null}
<div className="flex flex-wrap items-center justify-between gap-4 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6"> <SearchFilter
<div className="flex items-center gap-4 text-sm"> className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6"
<div className="flex items-center gap-2"> fields={[
<span className="shrink-0">关键词:</span> {
<span className="w-[200px]"> key: 'keyword',
<Input label: '关键词',
aria-label="关键词" type: 'input',
className="w-full" placeholder: '搜索岗位名称或渠道活码',
placeholder="搜索岗位名称或渠道活码" value: keyword,
value={keyword} allowClear: true,
allowClear onChange: setKeyword,
onChange={setKeyword} },
onKeyDown={(event) => { {
if (event.key === 'Enter') submitFilters(); key: 'displayStatus',
}} label: '展示状态',
/> type: 'select',
</span> options: [
</div> { value: 'enable', label: '展示中' },
<div className="flex items-center gap-2"> { value: 'disable', label: '已下架' },
<span className="shrink-0">展示状态:</span> ],
<span className="w-[200px]"> value: displayStatus,
<Select onChange: (value) => setDisplayStatus((value ?? '') as '' | 'enable' | 'disable'),
aria-label="展示状态" },
className="w-full" ]}
options={[ onReset={resetFilters}
{ value: 'all', label: '全部' }, onSearch={submitFilters}
{ value: 'enable', label: '展示中' }, />
{ value: 'disable', label: '已下架' },
]}
value={routeState.displayStatus}
onChange={(value) => setSearchParams(buildOfficialSiteJobTabListSearch({
keyword: routeState.keyword,
displayStatus: value as 'all' | 'enable' | 'disable',
page: 1,
pageSize: routeState.pageSize,
}))}
/>
</span>
</div>
</div>
<div className="ml-auto flex items-center justify-end gap-3">
<Button variant="primary" onClick={submitFilters}>搜索</Button>
<Button variant="outline" onClick={resetFilters}>重置</Button>
</div>
</div>
<div className="grid gap-6 overflow-x-auto rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6"> <BusinessTable
{loadError ? ( className="grid gap-6 overflow-x-auto rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6"
<StatePlaceholder rowKey="tab_id"
state="error" columns={columns}
title="加载失败" data={listData.items}
description="岗位展示配置列表加载失败,请重试" loading={loading}
primaryAction={<Button size="small" onClick={fetchList}>重试</Button>} error={loadError}
/> hasFilter={hasFilter}
) : ( filteredEmptyState={{
<> onAction: resetFilters,
<Table }}
rowKey="tab_id" errorState={{
columns={columns} onRetry: fetchList,
dataSource={listData.items} }}
loading={loading} pagination={{
empty={{ current: routeState.page,
description: hasFilter ? '未找到匹配结果' : '当前还没有岗位展示配置', pageSize: routeState.pageSize,
action: hasFilter ? <Button size="small" onClick={resetFilters}>重置搜索</Button> : undefined, total: listData.total,
}} pageSizeOptions: [2, 10, 20],
/> onChange: ({ current, pageSize }) => {
{listData.items.length === 0 && hasFilter ? <StatePlaceholder state="filtered-empty" /> : null} setSearchParams(buildOfficialSiteJobTabListSearch({
<Pagination keyword: routeState.keyword,
current={routeState.page} displayStatus: routeState.displayStatus,
pageSize={routeState.pageSize} page: current,
total={listData.total} pageSize,
pageSizeOptions={[2, 10, 20]} }));
onChange={(page, pageSize) => { },
setSearchParams(buildOfficialSiteJobTabListSearch({ }}
keyword: routeState.keyword, />
displayStatus: routeState.displayStatus,
page,
pageSize,
}));
}}
/>
</>
)}
</div>
<Modal <Dialog
open={Boolean(statusTarget)} visible={Boolean(statusTarget)}
title={statusTarget ? `确认${statusTarget.action === 'enable' ? '上架' : '下架'}"${statusTarget.tab.position_name}"?` : ''} header={statusTarget ? `确认${statusTarget.action === 'enable' ? '上架' : '下架'}"${statusTarget.tab.position_name}"?` : ''}
onCancel={() => setStatusTarget(null)} {...{ role: 'dialog', 'aria-label': statusTarget ? `确认${statusTarget.action === 'enable' ? '上架' : '下架'}"${statusTarget.tab.position_name}"?` : '' }}
onOk={async () => { cancelBtn="取消"
confirmBtn="确定"
destroyOnClose
onClose={() => setStatusTarget(null)}
onConfirm={async () => {
if (!statusTarget) return; if (!statusTarget) return;
try { try {
await updateOfficialSiteTabStatus(statusTarget.tab.tab_id, { await updateOfficialSiteTabStatus(statusTarget.tab.tab_id, {
...@@ -251,13 +235,17 @@ export function OfficialSiteJobTabListPage() { ...@@ -251,13 +235,17 @@ export function OfficialSiteJobTabListPage() {
<p className="m-0 max-w-[360px] leading-[var(--gl-line-height-md)] text-[var(--gl-color-text-secondary)]"> <p className="m-0 max-w-[360px] leading-[var(--gl-line-height-md)] text-[var(--gl-color-text-secondary)]">
{statusTarget?.action === 'enable' ? '启用后岗位展示配置将在官网岗位列表中展示。' : '下架后岗位展示配置不再在官网展示,请确认是否继续。'} {statusTarget?.action === 'enable' ? '启用后岗位展示配置将在官网岗位列表中展示。' : '下架后岗位展示配置不再在官网展示,请确认是否继续。'}
</p> </p>
</Modal> </Dialog>
<Modal <Dialog
open={Boolean(deleteTarget)} visible={Boolean(deleteTarget)}
title={deleteTarget ? `确认删除"${deleteTarget.position_name}"?` : ''} header={deleteTarget ? `确认删除"${deleteTarget.position_name}"?` : ''}
onCancel={() => setDeleteTarget(null)} {...{ role: 'dialog', 'aria-label': deleteTarget ? `确认删除"${deleteTarget.position_name}"?` : '' }}
onOk={async () => { cancelBtn="取消"
confirmBtn="确定"
destroyOnClose
onClose={() => setDeleteTarget(null)}
onConfirm={async () => {
if (!deleteTarget) return; if (!deleteTarget) return;
try { try {
await deleteOfficialSiteTab(deleteTarget.tab_id); await deleteOfficialSiteTab(deleteTarget.tab_id);
...@@ -276,7 +264,7 @@ export function OfficialSiteJobTabListPage() { ...@@ -276,7 +264,7 @@ export function OfficialSiteJobTabListPage() {
<p className="m-0 max-w-[360px] leading-[var(--gl-line-height-md)] text-[var(--gl-color-text-secondary)]"> <p className="m-0 max-w-[360px] leading-[var(--gl-line-height-md)] text-[var(--gl-color-text-secondary)]">
删除后将清理该岗位展示配置下的 Agent 展示配置,不会影响 Agent 原始数据或渠道活码信息。 删除后将清理该岗位展示配置下的 Agent 展示配置,不会影响 Agent 原始数据或渠道活码信息。
</p> </p>
</Modal> </Dialog>
</section> </section>
); );
} }
import { fireEvent, render, screen } from '@testing-library/react'; import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
import { App } from '../../App'; import { App } from '../../App';
import { getAgentList } from '../../api/agent';
import { getMethodologyConfig } from '../../api/methodology';
import {
createOfficialSiteTab,
deleteOfficialSiteTab,
getAvailableQRCodes,
getOfficialSiteTabDetail,
getOfficialSiteTabList,
updateOfficialSiteTab,
updateOfficialSiteTabStatus,
type OfficialSiteTabListItem,
} from '../../api/officialSiteTab';
import { getAvailableAgents } from '../../api/officialSiteAgentDisplay';
vi.mock('../../api/agent', () => ({
getAgentList: vi.fn(),
getAgentDetail: vi.fn(),
deleteAgent: vi.fn(),
updateAgentStatus: vi.fn(),
createAgent: vi.fn(),
updateAgent: vi.fn(),
getEmployeeMounts: vi.fn(() => Promise.resolve({ employee_count: 0, employees: [] })),
}));
vi.mock('../../api/officialSiteTab', () => ({
getOfficialSiteTabList: vi.fn(),
updateOfficialSiteTabStatus: vi.fn(),
deleteOfficialSiteTab: vi.fn(),
createOfficialSiteTab: vi.fn(),
updateOfficialSiteTab: vi.fn(),
getOfficialSiteTabDetail: vi.fn(),
getAvailableQRCodes: vi.fn(),
}));
vi.mock('../../api/officialSiteAgentDisplay', () => ({
getAvailableAgents: vi.fn(),
updateAgentDisplayConfig: vi.fn(),
uploadOfficialSiteAsset: vi.fn(),
getAgentDisplayDetail: vi.fn(),
}));
vi.mock('../../api/methodology', () => ({
getMethodologyConfig: vi.fn(),
saveMethodologyConfig: vi.fn(),
}));
vi.mock('../../api/analytics', () => ({
reportPageView: vi.fn().mockResolvedValue({ success: true }),
reportAnalyticsEvents: vi.fn().mockResolvedValue({ success: true }),
}));
const mockJobTabs: OfficialSiteTabListItem[] = [
{
tab_id: 1,
position_code: 'store_sales',
position_name: '店销顾问',
main_title: 'AI 智能助手提升店销效率',
sub_title: '通过 AI 智能问答帮助店销顾问快速响应客户需求',
qrcode_id: 1,
qrcode_name: '店销顾问渠道活码',
qrcode_url: 'https://cdn.example.com/qrcode.png',
qrcode_status: 'enable',
channel_code: 'DSC-QR-001',
qrcode_employee_name: '张小萌',
display_status: 'enable',
sort_order: 10,
agent_count: 3,
created_at: '2026-05-10 09:00:00',
operations: ['edit', 'disable', 'delete', 'configureAgent'],
},
];
const mockMethodologyConfig = {
config_id: 'methodology_001',
display_status: 'enable' as const,
main_title: '四步打造可复用的岗位 Agent',
sub_title: '从目标澄清到上线复盘,帮助团队沉淀一套稳定可复制的方法论。',
steps: [
{
step_id: 's1',
step_icon: 'https://cdn.example.com/icon1.png',
step_name: '需求澄清',
step_order: 1,
step_image: 'https://cdn.example.com/image1.png',
},
],
updated_at: '2026-05-16T10:00:00Z',
};
function renderApp(path = '/official-site/job-tabs') { function renderApp(path = '/official-site/job-tabs') {
window.localStorage.setItem('agent-admin-local-login', 'true'); window.localStorage.setItem('agent-admin-local-login', 'true');
...@@ -13,51 +101,132 @@ function renderApp(path = '/official-site/job-tabs') { ...@@ -13,51 +101,132 @@ function renderApp(path = '/official-site/job-tabs') {
); );
} }
function getMenuItem(label: string) {
const item = within(screen.getByLabelText('左侧导航')).getByText(label).closest('li');
if (!item) throw new Error(`Menu item ${label} was not found`);
return item;
}
describe('official site job tab routes and navigation', () => { describe('official site job tab routes and navigation', () => {
beforeEach(() => { beforeEach(() => {
window.localStorage.clear(); window.localStorage.clear();
vi.clearAllMocks();
vi.mocked(getAgentList).mockResolvedValue({ list: [], total: 0, page: 1, page_size: 10 });
vi.mocked(getMethodologyConfig).mockResolvedValue(mockMethodologyConfig);
vi.mocked(getOfficialSiteTabList).mockResolvedValue({
list: mockJobTabs,
total: mockJobTabs.length,
page: 1,
page_size: 10,
});
vi.mocked(getAvailableQRCodes).mockResolvedValue({
list: [
{
qrcode_id: 1,
qrcode_name: '店销顾问渠道活码',
channel_code: 'DSC-QR-001',
employee_name: '张小萌',
position_name: '店销顾问',
status: 'enable',
},
],
});
vi.mocked(getOfficialSiteTabDetail).mockResolvedValue({
tab_id: 1,
position_code: 'store_sales',
position_name: '店销顾问',
qrcode_id: 1,
qrcode_name: '店销顾问渠道活码',
channel_code: 'DSC-QR-001',
employee_name: '张小萌',
qrcode_employee_name: '张小萌',
employee_role_text: '店销主管',
main_title: 'AI 智能助手提升店销效率',
sub_title: '通过 AI 智能问答帮助店销顾问快速响应客户需求',
display_status: 'enable',
sort_order: 10,
});
vi.mocked(updateOfficialSiteTabStatus).mockResolvedValue({
success: true,
previous_status: 'disable',
updated_at: '2026-05-16T12:00:00Z',
});
vi.mocked(deleteOfficialSiteTab).mockResolvedValue({
success: true,
deleted_at: '2026-05-16T12:00:00Z',
cleaned_agent_configs: 0,
});
vi.mocked(createOfficialSiteTab).mockResolvedValue({
tab_id: '3',
position_code: 'new_position',
position_name: '新岗位',
qrcode_id: '1',
main_title: '新标题',
sub_title: '新副标题',
created_at: '2026-05-16T12:00:00Z',
});
vi.mocked(updateOfficialSiteTab).mockResolvedValue({
success: true,
updated_at: '2026-05-16T12:00:00Z',
});
vi.mocked(getAvailableAgents).mockResolvedValue({
tab_id: 1,
position_name: '店销顾问',
qrcode_id: 1,
available_agents: [],
});
}); });
it('renders the list route at /official-site/job-tabs', () => { it('renders the list route at /official-site/job-tabs', async () => {
renderApp(); renderApp();
expect(screen.getByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument(); expect(await screen.findByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument();
}); });
it('renders the new route at /official-site/job-tabs/new', () => { it('renders the new route at /official-site/job-tabs/new', async () => {
renderApp('/official-site/job-tabs/new'); renderApp('/official-site/job-tabs/new');
expect(screen.getByRole('heading', { name: '新建岗位展示' })).toBeInTheDocument(); expect(await screen.findByRole('heading', { name: '新建岗位展示' })).toBeInTheDocument();
}); });
it('renders the edit route at /official-site/job-tabs/:tabId/edit', () => { it('renders the edit route at /official-site/job-tabs/:tabId/edit', async () => {
renderApp('/official-site/job-tabs/1/edit'); renderApp('/official-site/job-tabs/1/edit');
expect(screen.getByRole('heading', { name: '编辑岗位展示' })).toBeInTheDocument(); expect(await screen.findByRole('heading', { name: '编辑岗位展示' })).toBeInTheDocument();
}); });
it('shows navigation entry under 官网配置 group', () => { it('shows navigation entry under 官网配置 group', async () => {
renderApp(); renderApp();
expect(screen.getByRole('button', { name: '岗位展示配置' })).toBeInTheDocument(); await waitFor(() => {
expect(getMenuItem('岗位展示配置')).toBeInTheDocument();
});
}); });
it('marks navigation entry as active when on job-tabs routes', () => { it('marks navigation entry as active when on job-tabs routes', async () => {
renderApp(); renderApp();
expect(screen.getByRole('button', { name: '岗位展示配置' })).toHaveAttribute('aria-current', 'page'); await waitFor(() => {
expect(getMenuItem('岗位展示配置')).toHaveClass('t-is-active');
});
}); });
it('shows breadcrumb for job-tabs', () => { it('shows breadcrumb for job-tabs', async () => {
renderApp(); renderApp();
expect(screen.getByText('官网配置 / 岗位展示配置')).toBeInTheDocument(); await waitFor(() => {
expect(screen.getAllByText('官网配置').length).toBeGreaterThan(0);
expect(screen.getAllByText('岗位展示配置').length).toBeGreaterThan(0);
});
}); });
it('can navigate to the job-tabs page from agents', () => { it('can navigate to the job-tabs page from agents', async () => {
renderApp('/agents'); renderApp('/agents');
fireEvent.click(screen.getByRole('button', { name: '岗位展示配置' })); await waitFor(() => {
expect(screen.getByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument(); expect(getMenuItem('Agent列表')).toHaveClass('t-is-active');
});
fireEvent.click(getMenuItem('岗位展示配置'));
expect(await screen.findByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument();
}); });
it('does not affect methodology navigation', () => { it('does not affect methodology navigation', async () => {
renderApp('/official-site/methodology'); renderApp('/official-site/methodology');
expect(screen.getByRole('heading', { name: '方法论展示配置' })).toBeInTheDocument(); expect(await screen.findByRole('heading', { name: '方法论展示配置' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '方法论展示配置' })).toHaveAttribute('aria-current', 'page'); expect(getMenuItem('方法论展示配置')).toHaveClass('t-is-active');
expect(screen.getByRole('button', { name: '岗位展示配置' })).not.toHaveAttribute('aria-current'); expect(getMenuItem('岗位展示配置')).not.toHaveClass('t-is-active');
}); });
});
\ No newline at end of file \ No newline at end of file
});
...@@ -49,7 +49,7 @@ describe('OfficialSiteMethodologyPage form and steps', () => { ...@@ -49,7 +49,7 @@ describe('OfficialSiteMethodologyPage form and steps', () => {
it('renders the core fields and hydrates the normal mock config', async () => { it('renders the core fields and hydrates the normal mock config', async () => {
renderMethodology(); renderMethodology();
expect(screen.getByRole('status', { name: '加载中' })).toBeInTheDocument(); expect(screen.getByText('加载中...')).toBeInTheDocument();
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('switch', { name: '展示状态' })).toHaveAttribute('aria-checked', 'true'); expect(screen.getByRole('switch', { name: '展示状态' })).toHaveAttribute('aria-checked', 'true');
...@@ -126,13 +126,13 @@ describe('OfficialSiteMethodologyPage form and steps', () => { ...@@ -126,13 +126,13 @@ describe('OfficialSiteMethodologyPage form and steps', () => {
cards = screen.getAllByTestId('methodology-step-card'); cards = screen.getAllByTestId('methodology-step-card');
expect(within(cards[0]).getByLabelText('步骤1名称')).toHaveValue('上线复盘'); expect(within(cards[0]).getByLabelText('步骤1名称')).toHaveValue('上线复盘');
expect(within(cards[0]).getByText('sort_order = 1')).toBeInTheDocument(); expect(within(cards[1]).getByLabelText('步骤2名称')).toHaveValue('需求澄清');
fireEvent.click(within(cards[1]).getByRole('button', { name: '删除步骤 2' })); fireEvent.click(within(cards[1]).getByRole('button', { name: '删除步骤 2' }));
cards = screen.getAllByTestId('methodology-step-card'); cards = screen.getAllByTestId('methodology-step-card');
expect(cards).toHaveLength(2); expect(cards).toHaveLength(2);
expect(within(cards[1]).getByText('sort_order = 2')).toBeInTheDocument(); expect(within(cards[1]).getByLabelText('步骤2名称')).toHaveValue('方案设计');
}); });
describe('analytics tracking', () => { describe('analytics tracking', () => {
......
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { Button, FormItem, Input, MediaWall, StatePlaceholder, Switch, Textarea } from '../../../packages/ui/src'; import { MediaWall, StatePlaceholder } from '@gl/business-components';
import { Button } from 'tdesign-react';
import { FormItem, Input, Switch, Textarea } from '../../components/TDesignAccessibleControls';
import { import {
getMethodologyConfig, getMethodologyConfig,
saveMethodologyConfig, saveMethodologyConfig,
...@@ -268,10 +270,10 @@ export function OfficialSiteMethodologyPage() { ...@@ -268,10 +270,10 @@ export function OfficialSiteMethodologyPage() {
<div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-8"> <div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-8">
<div className="grid gap-6"> <div className="grid gap-6">
<FormItem label="展示状态" layout="horizontal" required error={undefined}> <FormItem label="展示状态" labelAlign="left" requiredMark>
<Switch <Switch
aria-label="展示状态" aria-label="展示状态"
checked={form.display_status === 'enable'} value={form.display_status === 'enable'}
onChange={(checked) => { onChange={(checked) => {
setNotice(null); setNotice(null);
updateForm((current) => ({ updateForm((current) => ({
...@@ -282,12 +284,13 @@ export function OfficialSiteMethodologyPage() { ...@@ -282,12 +284,13 @@ export function OfficialSiteMethodologyPage() {
/> />
</FormItem> </FormItem>
<FormItem label="主标题" layout="horizontal" required error={mainTitleError}> <FormItem label="主标题" labelAlign="left" requiredMark status={mainTitleError ? 'error' : undefined} tips={mainTitleError}>
<Input <Input
aria-label="主标题" aria-label="主标题"
className="w-full max-w-[520px]" className="w-full max-w-[520px]"
maxLength={30} maxlength={30}
showCount allowInputOverMax
showLimitNumber
value={form.main_title} value={form.main_title}
onChange={(value) => { onChange={(value) => {
setMainTitleError(undefined); setMainTitleError(undefined);
...@@ -299,13 +302,14 @@ export function OfficialSiteMethodologyPage() { ...@@ -299,13 +302,14 @@ export function OfficialSiteMethodologyPage() {
/> />
</FormItem> </FormItem>
<FormItem label="副标题" layout="horizontal" required error={subTitleError}> <FormItem label="副标题" labelAlign="left" requiredMark status={subTitleError ? 'error' : undefined} tips={subTitleError}>
<Textarea <Textarea
aria-label="副标题" aria-label="副标题"
className="w-full max-w-[520px]" className="w-full max-w-[520px]"
maxLength={100} maxlength={100}
allowInputOverMax
rows={4} rows={4}
showCount count
value={form.sub_title} value={form.sub_title}
onChange={(value) => { onChange={(value) => {
setSubTitleError(undefined); setSubTitleError(undefined);
...@@ -326,7 +330,7 @@ export function OfficialSiteMethodologyPage() { ...@@ -326,7 +330,7 @@ export function OfficialSiteMethodologyPage() {
<p className="m-0 text-sm text-[var(--gl-color-text-secondary)]">配置步骤图标、步骤名称与内容图。</p> <p className="m-0 text-sm text-[var(--gl-color-text-secondary)]">配置步骤图标、步骤名称与内容图。</p>
</div> </div>
<Button <Button
variant="primary" theme="primary"
onClick={() => { onClick={() => {
setStepListError(undefined); setStepListError(undefined);
updateForm((current) => ({ updateForm((current) => ({
...@@ -394,7 +398,7 @@ export function OfficialSiteMethodologyPage() { ...@@ -394,7 +398,7 @@ export function OfficialSiteMethodologyPage() {
</Button> </Button>
<Button <Button
size="small" size="small"
variant="danger" theme="danger"
aria-label={`删除步骤 ${index + 1}`} aria-label={`删除步骤 ${index + 1}`}
onClick={() => { onClick={() => {
updateForm((current) => ({ updateForm((current) => ({
...@@ -408,7 +412,7 @@ export function OfficialSiteMethodologyPage() { ...@@ -408,7 +412,7 @@ export function OfficialSiteMethodologyPage() {
</div> </div>
</div> </div>
<FormItem label="步骤图标" required error={step.iconError} help={stepIconHelperText}> <FormItem label="步骤图标" requiredMark status={step.iconError ? 'error' : undefined} tips={step.iconError} help={stepIconHelperText}>
<div className="grid gap-3"> <div className="grid gap-3">
<MediaWall <MediaWall
accept="image/png,image/jpg,image/jpeg" accept="image/png,image/jpg,image/jpeg"
...@@ -543,12 +547,13 @@ export function OfficialSiteMethodologyPage() { ...@@ -543,12 +547,13 @@ export function OfficialSiteMethodologyPage() {
</div> </div>
</FormItem> </FormItem>
<FormItem label="步骤名称" required error={step.nameError}> <FormItem label="步骤名称" requiredMark status={step.nameError ? 'error' : undefined} tips={step.nameError}>
<Input <Input
aria-label={`步骤${index + 1}名称`} aria-label={`步骤${index + 1}名称`}
className="w-full max-w-[360px]" className="w-full max-w-[360px]"
maxLength={20} maxlength={20}
showCount allowInputOverMax
showLimitNumber
value={step.step_name} value={step.step_name}
onChange={(value) => { onChange={(value) => {
updateStep(index, (currentStep) => ({ updateStep(index, (currentStep) => ({
...@@ -560,7 +565,7 @@ export function OfficialSiteMethodologyPage() { ...@@ -560,7 +565,7 @@ export function OfficialSiteMethodologyPage() {
/> />
</FormItem> </FormItem>
<FormItem label="内容图" required error={step.imageError} help={contentImageHelperText}> <FormItem label="内容图" requiredMark status={step.imageError ? 'error' : undefined} tips={step.imageError} help={contentImageHelperText}>
<MediaWall <MediaWall
accept="image/png,image/jpg,image/jpeg" accept="image/png,image/jpg,image/jpeg"
items={step.step_image ? [{ items={step.step_image ? [{
...@@ -640,11 +645,11 @@ export function OfficialSiteMethodologyPage() { ...@@ -640,11 +645,11 @@ export function OfficialSiteMethodologyPage() {
<h2 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">方法论展示配置</h2> <h2 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">方法论展示配置</h2>
<p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">维护官网方法论模块的展示状态、标题和步骤内容。</p> <p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">维护官网方法论模块的展示状态、标题和步骤内容。</p>
</div> </div>
<Button variant="primary" loading={saving} aria-label="保存配置" onClick={handleSave}> <Button theme="primary" loading={saving} aria-label="保存配置" onClick={handleSave}>
保存配置 保存配置
</Button> </Button>
</header> </header>
{renderContent()} {renderContent()}
</section> </section>
); );
}
\ No newline at end of file \ No newline at end of file
}
import { fireEvent, render, screen } from '@testing-library/react'; import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom'; import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest'; import { beforeEach, describe, expect, it, vi } from 'vitest';
import { App } from '../../App'; import { App } from '../../App';
import { getAgentList } from '../../api/agent';
import { getMethodologyConfig, saveMethodologyConfig } from '../../api/methodology';
vi.mock('../../api/agent', () => ({
getAgentList: vi.fn(),
getAgentDetail: vi.fn(),
deleteAgent: vi.fn(),
updateAgentStatus: vi.fn(),
createAgent: vi.fn(),
updateAgent: vi.fn(),
getEmployeeMounts: vi.fn(() => Promise.resolve({ employee_count: 0, employees: [] })),
}));
vi.mock('../../api/methodology', () => ({
getMethodologyConfig: vi.fn(),
saveMethodologyConfig: vi.fn(),
}));
vi.mock('../../api/analytics', () => ({
reportPageView: vi.fn().mockResolvedValue({ success: true }),
reportAnalyticsEvents: vi.fn().mockResolvedValue({ success: true }),
}));
const mockMethodologyConfig = {
config_id: 'methodology_001',
display_status: 'enable' as const,
main_title: '四步打造可复用的岗位 Agent',
sub_title: '从目标澄清到上线复盘,帮助团队沉淀一套稳定可复制的方法论。',
steps: [
{
step_id: 's1',
step_icon: 'https://cdn.example.com/icon1.png',
step_name: '需求澄清',
step_order: 1,
step_image: 'https://cdn.example.com/image1.png',
},
],
updated_at: '2026-05-16T10:00:00Z',
};
function renderApp(path = '/official-site/methodology') { function renderApp(path = '/official-site/methodology') {
window.localStorage.setItem('agent-admin-local-login', 'true'); window.localStorage.setItem('agent-admin-local-login', 'true');
...@@ -13,33 +52,48 @@ function renderApp(path = '/official-site/methodology') { ...@@ -13,33 +52,48 @@ function renderApp(path = '/official-site/methodology') {
); );
} }
function getMenuItem(label: string) {
const item = within(screen.getByLabelText('左侧导航')).getByText(label).closest('li');
if (!item) throw new Error(`Menu item ${label} was not found`);
return item;
}
describe('official site methodology route and navigation', () => { describe('official site methodology route and navigation', () => {
beforeEach(() => { beforeEach(() => {
window.localStorage.clear(); window.localStorage.clear();
vi.clearAllMocks();
vi.mocked(getAgentList).mockResolvedValue({ list: [], total: 0, page: 1, page_size: 10 });
vi.mocked(getMethodologyConfig).mockResolvedValue(mockMethodologyConfig);
vi.mocked(saveMethodologyConfig).mockResolvedValue({ config_id: 'methodology_001', updated_at: '2026-05-16T12:00:00Z' });
}); });
it('renders the methodology page inside admin shell with correct menu ownership', () => { it('renders the methodology page inside admin shell with correct menu ownership', async () => {
renderApp(); renderApp();
expect(screen.getByRole('heading', { name: '方法论展示配置' })).toBeInTheDocument(); expect(await screen.findByRole('heading', { name: '方法论展示配置' })).toBeInTheDocument();
expect(screen.getByText('官网配置 / 方法论展示配置')).toBeInTheDocument(); expect(screen.getAllByText('官网配置').length).toBeGreaterThan(0);
expect(screen.getByRole('button', { name: '方法论展示配置' })).toHaveAttribute('aria-current', 'page'); expect(screen.getAllByText('方法论展示配置').length).toBeGreaterThan(0);
expect(screen.getByRole('button', { name: 'Agent列表' })).not.toHaveAttribute('aria-current'); expect(getMenuItem('方法论展示配置')).toHaveClass('t-is-active');
expect(getMenuItem('Agent列表')).not.toHaveClass('t-is-active');
}); });
it('shows the official site navigation entry and can navigate to the methodology page from agents', () => { it('shows the official site navigation entry and can navigate to the methodology page from agents', async () => {
renderApp('/agents'); renderApp('/agents');
fireEvent.click(screen.getByRole('button', { name: '方法论展示配置' })); await waitFor(() => {
expect(getMenuItem('Agent列表')).toHaveClass('t-is-active');
});
fireEvent.click(getMenuItem('方法论展示配置'));
expect(screen.getByRole('heading', { name: '方法论展示配置' })).toBeInTheDocument(); expect(await screen.findByRole('heading', { name: '方法论展示配置' })).toBeInTheDocument();
expect(screen.getByText('官网配置 / 方法论展示配置')).toBeInTheDocument(); expect(screen.getAllByText('官网配置').length).toBeGreaterThan(0);
expect(screen.getAllByText('方法论展示配置').length).toBeGreaterThan(0);
}); });
it('keeps the protected index redirect pointing to agents by default', () => { it('keeps the protected index redirect pointing to agents by default', async () => {
renderApp('/'); renderApp('/');
expect(screen.getByRole('heading', { name: 'Agent管理' })).toBeInTheDocument(); expect(await screen.findByRole('heading', { name: 'Agent管理' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Agent列表' })).toHaveAttribute('aria-current', 'page'); expect(getMenuItem('Agent列表')).toHaveClass('t-is-active');
}); });
}); });
...@@ -559,7 +559,7 @@ describe('OfficialSiteMethodologyPage upload, save, and state handling', () => { ...@@ -559,7 +559,7 @@ describe('OfficialSiteMethodologyPage upload, save, and state handling', () => {
}); });
// 再次点击「使用默认图标」重试 // 再次点击「使用默认图标」重试
fireEvent.click(defaultIconButton); fireEvent.click(within(firstCard).getByRole('button', { name: '使用默认图标 步骤 1' }));
await waitFor(() => { await waitFor(() => {
const images = within(firstCard).getAllByRole('img'); const images = within(firstCard).getAllByRole('img');
...@@ -578,7 +578,8 @@ describe('OfficialSiteMethodologyPage upload, save, and state handling', () => { ...@@ -578,7 +578,8 @@ describe('OfficialSiteMethodologyPage upload, save, and state handling', () => {
expect(screen.getAllByTestId('methodology-step-card')).toHaveLength(2); expect(screen.getAllByTestId('methodology-step-card')).toHaveLength(2);
}); });
const firstCard = screen.getAllByTestId('methodology-step-card')[0]; const getFirstCard = () => screen.getAllByTestId('methodology-step-card')[0];
const firstCard = getFirstCard();
// 删除已有步骤图标 // 删除已有步骤图标
const uploadContainers = firstCard.querySelectorAll('.t-upload__card'); const uploadContainers = firstCard.querySelectorAll('.t-upload__card');
if (uploadContainers.length >= 1) { if (uploadContainers.length >= 1) {
...@@ -602,17 +603,17 @@ describe('OfficialSiteMethodologyPage upload, save, and state handling', () => { ...@@ -602,17 +603,17 @@ describe('OfficialSiteMethodologyPage upload, save, and state handling', () => {
}); });
// 上传中按钮应禁用 // 上传中按钮应禁用
expect(defaultIconButton).toBeDisabled(); expect(within(getFirstCard()).getByLabelText('使用默认图标 步骤 1')).toHaveAttribute('disabled');
// 等待上传完成(需要额外 timeout 以覆盖 mock 延迟) // 等待上传完成(需要额外 timeout 以覆盖 mock 延迟)
await waitFor(() => { await waitFor(() => {
const images = within(firstCard).getAllByRole('img'); const images = within(getFirstCard()).getAllByRole('img');
const delayedIconImg = images.find(img => img.getAttribute('src') === 'https://cdn.example.com/default-icon-delayed.png'); const delayedIconImg = images.find(img => img.getAttribute('src') === 'https://cdn.example.com/default-icon-delayed.png');
expect(delayedIconImg).toBeInTheDocument(); expect(delayedIconImg).toBeInTheDocument();
}, { timeout: 2000 }); }, { timeout: 2000 });
// 上传完成后按钮恢复可用 // 上传完成后按钮恢复可用
expect(defaultIconButton).not.toBeDisabled(); expect(within(getFirstCard()).getByRole('button', { name: '使用默认图标 步骤 1' })).not.toBeDisabled();
}); });
}); });
});
\ No newline at end of file \ No newline at end of file
});
import { useState } from 'react'; import { useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { Button, Drawer, StatePlaceholder } from '../../../packages/ui/src'; import { StatePlaceholder } from '@gl/business-components';
import { CloseIcon } from 'tdesign-icons-react';
import { Button, Drawer } from 'tdesign-react';
import { getSkillDetail, type SkillDetail } from '../../api'; import { getSkillDetail, type SkillDetail } from '../../api';
import { useDeferredEffect } from '../../hooks/useDeferredEffect'; import { useDeferredEffect } from '../../hooks/useDeferredEffect';
import { SkillMarkdown } from './SkillMarkdown'; import { SkillMarkdown } from './SkillMarkdown';
...@@ -39,9 +41,11 @@ export function SkillDetailDrawer({ routeState, skillCode }: { routeState: Skill ...@@ -39,9 +41,11 @@ export function SkillDetailDrawer({ routeState, skillCode }: { routeState: Skill
return ( return (
<Drawer <Drawer
open visible
title="Skill详情" header="Skill详情"
width={560} size="560px"
destroyOnClose
closeBtn={<Button aria-label="关闭Skill详情" icon={<CloseIcon />} shape="square" variant="text" />}
onClose={closeDrawer} onClose={closeDrawer}
footer={ footer={
<div className="flex items-center justify-end gap-3"> <div className="flex items-center justify-end gap-3">
......
...@@ -73,9 +73,9 @@ describe('SkillListPage', () => { ...@@ -73,9 +73,9 @@ describe('SkillListPage', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('heading', { name: 'Skill目录' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Skill目录' })).toBeInTheDocument();
}); });
expect(screen.getByText('关键词:')).toBeInTheDocument(); expect(screen.getAllByText('关键词').length).toBeGreaterThan(0);
expect(screen.getByLabelText('搜索Skill关键词')).toBeInTheDocument(); expect(screen.getByLabelText('关键词')).toBeInTheDocument();
expect(screen.getByPlaceholderText('搜索 Skill 名称或编码')).toBeInTheDocument(); expect(screen.getByPlaceholderText('搜索Skill名称或编码')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '搜索' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '搜索' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '重置' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '重置' })).toBeInTheDocument();
expect(screen.getByRole('columnheader', { name: 'Skill编码' })).toBeInTheDocument(); expect(screen.getByRole('columnheader', { name: 'Skill编码' })).toBeInTheDocument();
...@@ -86,19 +86,21 @@ describe('SkillListPage', () => { ...@@ -86,19 +86,21 @@ describe('SkillListPage', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('共 2 条')).toBeInTheDocument(); expect(screen.getByText('共 2 条')).toBeInTheDocument();
}); });
expect(screen.getByRole('button', { name: '查看browser:browser详情' })).toHaveClass('t-button--theme-primary', 't-button--variant-text');
expect(screen.queryByRole('button', { name: '新建Skill' })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: '新建Skill' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '编辑' })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: '编辑' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '删除' })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: '删除' })).not.toBeInTheDocument();
}); });
it('keeps the search control at 200px and actions right aligned', async () => { it('renders the keyword field through the shared SearchFilter', async () => {
renderSkills(); renderSkills();
await waitFor(() => { await waitFor(() => {
expect(screen.getByTestId('skill-keyword-control')).toBeInTheDocument(); expect(screen.getByLabelText('关键词')).toBeInTheDocument();
}); });
expect(screen.getByTestId('skill-keyword-control')).toHaveClass('w-[200px]'); expect(screen.getByPlaceholderText('搜索Skill名称或编码')).toBeInTheDocument();
expect(screen.getByTestId('skill-search-actions')).toHaveClass('ml-auto', 'justify-end'); expect(screen.getByRole('button', { name: '搜索' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '重置' })).toBeInTheDocument();
}); });
it('filters only after search submission and resets to default list', async () => { it('filters only after search submission and resets to default list', async () => {
...@@ -108,7 +110,7 @@ describe('SkillListPage', () => { ...@@ -108,7 +110,7 @@ describe('SkillListPage', () => {
expect(screen.getByText('browser:browser')).toBeInTheDocument(); expect(screen.getByText('browser:browser')).toBeInTheDocument();
}); });
fireEvent.change(screen.getByLabelText('搜索Skill关键词'), { target: { value: 'markdown' } }); fireEvent.change(screen.getByLabelText('关键词'), { target: { value: 'markdown' } });
expect(screen.getByText('browser:browser')).toBeInTheDocument(); expect(screen.getByText('browser:browser')).toBeInTheDocument();
expect(screen.getByText('imagegen')).toBeInTheDocument(); expect(screen.getByText('imagegen')).toBeInTheDocument();
...@@ -130,7 +132,7 @@ describe('SkillListPage', () => { ...@@ -130,7 +132,7 @@ describe('SkillListPage', () => {
await waitFor(() => { await waitFor(() => {
expect(getSkillList).toHaveBeenLastCalledWith(''); expect(getSkillList).toHaveBeenLastCalledWith('');
}); });
expect(screen.getByLabelText('搜索Skill关键词')).toHaveValue(''); expect(screen.getByLabelText('关键词')).toHaveValue('');
expect(screen.getByText('browser:browser')).toBeInTheDocument(); expect(screen.getByText('browser:browser')).toBeInTheDocument();
}); });
...@@ -141,7 +143,7 @@ describe('SkillListPage', () => { ...@@ -141,7 +143,7 @@ describe('SkillListPage', () => {
expect(screen.getByText('browser:browser')).toBeInTheDocument(); expect(screen.getByText('browser:browser')).toBeInTheDocument();
}); });
fireEvent.change(screen.getByLabelText('搜索Skill关键词'), { target: { value: 'browser' } }); fireEvent.change(screen.getByLabelText('关键词'), { target: { value: 'browser' } });
vi.mocked(getSkillList).mockResolvedValueOnce({ vi.mocked(getSkillList).mockResolvedValueOnce({
list: [mockSkills[0]], list: [mockSkills[0]],
}); });
...@@ -149,15 +151,17 @@ describe('SkillListPage', () => { ...@@ -149,15 +151,17 @@ describe('SkillListPage', () => {
await waitFor(() => { await waitFor(() => {
expect(getSkillList).toHaveBeenLastCalledWith('browser'); expect(getSkillList).toHaveBeenLastCalledWith('browser');
}); });
fireEvent.change(screen.getByLabelText('搜索Skill关键词'), { target: { value: 'imagegen' } }); fireEvent.change(screen.getByLabelText('关键词'), { target: { value: 'imagegen' } });
fireEvent.click(screen.getByRole('button', { name: '查看browser:browser详情' })); fireEvent.click(screen.getByRole('button', { name: '查看browser:browser详情' }));
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('dialog', { name: 'Skill详情' })).toBeInTheDocument(); expect(screen.getByText('Skill详情').closest('.t-drawer')).toBeInTheDocument();
}); });
const drawer = screen.getByRole('dialog', { name: 'Skill详情' }); const drawer = screen.getByText('Skill详情').closest('.t-drawer') as HTMLElement;
expect(within(drawer).getByText('Skill编码:')).toBeInTheDocument(); await waitFor(() => {
expect(within(drawer).getByText('Skill编码:')).toBeInTheDocument();
});
expect(within(drawer).getByText('browser:browser')).toBeInTheDocument(); expect(within(drawer).getByText('browser:browser')).toBeInTheDocument();
expect(within(drawer).getByText('Skill名称:')).toBeInTheDocument(); expect(within(drawer).getByText('Skill名称:')).toBeInTheDocument();
expect(within(drawer).getByText('说明:')).toBeInTheDocument(); expect(within(drawer).getByText('说明:')).toBeInTheDocument();
...@@ -174,32 +178,28 @@ describe('SkillListPage', () => { ...@@ -174,32 +178,28 @@ describe('SkillListPage', () => {
fireEvent.click(within(drawer).getByRole('button', { name: '关闭' })); fireEvent.click(within(drawer).getByRole('button', { name: '关闭' }));
expect(screen.queryByRole('dialog', { name: 'Skill详情' })).not.toBeInTheDocument(); expect(screen.queryByText('Skill详情')).not.toBeInTheDocument();
expect(screen.getByLabelText('搜索Skill关键词')).toHaveValue('browser'); expect(screen.getByLabelText('关键词')).toHaveValue('browser');
expect(screen.getByText('browser:browser')).toBeInTheDocument(); expect(screen.getByText('browser:browser')).toBeInTheDocument();
expect(screen.queryByText('imagegen')).not.toBeInTheDocument(); expect(screen.queryByText('imagegen')).not.toBeInTheDocument();
}); });
it('renders recoverable list and detail states', async () => { it('renders list failure and detail states', async () => {
vi.mocked(getSkillList).mockRejectedValueOnce(new Error('Network error')); vi.mocked(getSkillList).mockRejectedValueOnce(new Error('Network error'));
renderSkills(); renderSkills();
await waitFor(() => { await waitFor(() => {
expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument(); expect(screen.getByText('请求失败')).toBeInTheDocument();
});
vi.mocked(getSkillList).mockResolvedValueOnce({ list: mockSkills });
fireEvent.click(screen.getByRole('button', { name: '重试' }));
await waitFor(() => {
expect(screen.getByText('browser:browser')).toBeInTheDocument();
}); });
expect(screen.queryByText('Skill 列表请求失败,请重试')).not.toBeInTheDocument();
expect(screen.queryByText('请检查网络连接后重试')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
cleanup(); cleanup();
vi.mocked(getSkillList).mockResolvedValueOnce({ list: [] }); vi.mocked(getSkillList).mockResolvedValueOnce({ list: [] });
renderSkills(); renderSkills();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('当前还没有Skill')).toBeInTheDocument(); expect(screen.getByText('暂无数据')).toBeInTheDocument();
}); });
expect(screen.getByText('共 0 条')).toBeInTheDocument(); expect(screen.getByText('共 0 条')).toBeInTheDocument();
}); });
...@@ -212,7 +212,7 @@ describe('SkillListPage', () => { ...@@ -212,7 +212,7 @@ describe('SkillListPage', () => {
await waitFor(() => { await waitFor(() => {
expect(getSkillList).toHaveBeenCalledWith('browser'); expect(getSkillList).toHaveBeenCalledWith('browser');
}); });
expect(screen.getByLabelText('搜索Skill关键词')).toHaveValue('browser'); expect(screen.getByLabelText('关键词')).toHaveValue('browser');
expect(screen.getByText('browser:browser')).toBeInTheDocument(); expect(screen.getByText('browser:browser')).toBeInTheDocument();
expect(screen.queryByText('imagegen')).not.toBeInTheDocument(); expect(screen.queryByText('imagegen')).not.toBeInTheDocument();
}); });
...@@ -252,16 +252,16 @@ describe('SkillListPage', () => { ...@@ -252,16 +252,16 @@ describe('SkillListPage', () => {
}); });
it('does not report page view on load failure', async () => { it('does not report page view on load failure', async () => {
vi.mocked(getSkillList).mockRejectedValueOnce(new Error('Network error')); vi.mocked(getSkillList).mockRejectedValueOnce(new Error('Network error'));
renderSkills(); renderSkills();
await waitFor(() => {
expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument();
});
expect(reportPageView).not.toHaveBeenCalled(); await waitFor(() => {
expect(screen.getByText('请求失败')).toBeInTheDocument();
}); });
expect(reportPageView).not.toHaveBeenCalled();
});
it('reports view_detail event when clicking skill detail', async () => { it('reports view_detail event when clicking skill detail', async () => {
renderSkills(); renderSkills();
......
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom'; import { useSearchParams } from 'react-router-dom';
import { Button, Input, StatePlaceholder, Table } from '../../../packages/ui/src'; import { BusinessTable, SearchFilter, type BusinessTableColumn, type SearchFilterValues } from '@gl/business-components';
import { Button } from 'tdesign-react';
import { getSkillList, type SkillSummary } from '../../api'; import { getSkillList, type SkillSummary } from '../../api';
import { useTrackPageView, trackCustomEvent } from '../../api/tracking'; import { useTrackPageView, trackCustomEvent } from '../../api/tracking';
import { useDeferredEffect } from '../../hooks/useDeferredEffect'; import { useDeferredEffect } from '../../hooks/useDeferredEffect';
...@@ -42,8 +43,10 @@ export function SkillListPage() { ...@@ -42,8 +43,10 @@ export function SkillListPage() {
const hasFilter = Boolean(routeState.keyword); const hasFilter = Boolean(routeState.keyword);
const totalCount = items.length; const totalCount = items.length;
const submitFilters = () => { const submitFilters = (filterValues: SearchFilterValues = { keyword }) => {
setSearchParams(buildSkillListSearch({ keyword, detail: undefined })); const nextKeyword = String(filterValues.keyword ?? '');
setKeyword(nextKeyword);
setSearchParams(buildSkillListSearch({ keyword: nextKeyword, detail: undefined }));
}; };
const resetFilters = () => { const resetFilters = () => {
...@@ -51,17 +54,18 @@ export function SkillListPage() { ...@@ -51,17 +54,18 @@ export function SkillListPage() {
setSearchParams(buildSkillListSearch({ keyword: '', detail: undefined })); setSearchParams(buildSkillListSearch({ keyword: '', detail: undefined }));
}; };
const columns = [ const columns: BusinessTableColumn<SkillSummary>[] = [
{ title: 'Skill编码', dataIndex: 'skill_code' as const }, { title: 'Skill编码', colKey: 'skill_code' },
{ title: 'Skill名称', dataIndex: 'skill_name' as const }, { title: 'Skill名称', colKey: 'skill_name' },
{ title: '说明', dataIndex: 'description' as const }, { title: '说明', colKey: 'description' },
{ {
title: '操作', title: '操作',
key: 'actions', colKey: 'actions',
render: (_: unknown, skill: SkillSummary) => ( cell: ({ row: skill }) => (
<Button <Button
aria-label={`查看${skill.skill_code}详情`} aria-label={`查看${skill.skill_code}详情`}
size="small" size="small"
theme="primary"
variant="text" variant="text"
onClick={() => { onClick={() => {
trackCustomEvent({ event_type: 'view_detail', event_data: { page: 'skill_detail', skill_code: skill.skill_code } }); trackCustomEvent({ event_type: 'view_detail', event_data: { page: 'skill_detail', skill_code: skill.skill_code } });
...@@ -81,55 +85,41 @@ export function SkillListPage() { ...@@ -81,55 +85,41 @@ export function SkillListPage() {
<p className="m-0 text-sm text-[var(--gl-color-text-secondary)]">查看 Skill 编码、说明和 Markdown 使用文档</p> <p className="m-0 text-sm text-[var(--gl-color-text-secondary)]">查看 Skill 编码、说明和 Markdown 使用文档</p>
</header> </header>
<div className="flex flex-wrap items-center justify-between gap-4 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6"> <SearchFilter
<div className="flex items-center gap-2 text-sm" data-testid="skill-keyword-field"> className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6"
<span className="shrink-0">关键词:</span> fields={[
<span className="w-[200px]" data-testid="skill-keyword-control"> {
<Input key: 'keyword',
aria-label="搜索Skill关键词" label: '关键词',
className="w-full" type: 'input',
placeholder="搜索 Skill 名称或编码" placeholder: '搜索Skill名称或编码',
value={keyword} value: keyword,
allowClear allowClear: true,
onChange={setKeyword} onChange: setKeyword,
onKeyDown={(event) => { },
if (event.key === 'Enter') submitFilters(); ]}
}} onReset={resetFilters}
/> onSearch={submitFilters}
</span> />
</div>
<div className="ml-auto flex items-center justify-end gap-3" data-testid="skill-search-actions">
<Button variant="primary" onClick={submitFilters}>搜索</Button>
<Button variant="outline" onClick={resetFilters}>重置</Button>
</div>
</div>
<div className="grid gap-6 overflow-x-auto rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6"> <div className="grid gap-6 overflow-x-auto rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] p-6">
{loadError ? ( <BusinessTable
<StatePlaceholder rowKey="skill_code"
state="error" columns={columns}
title="加载失败" data={items}
description="Skill 列表请求失败,请重试" loading={loading}
primaryAction={<Button size="small" onClick={() => { error={loadError}
hasFilter={hasFilter}
errorState={{
onRetry: () => {
loadSkills(routeState.keyword); loadSkills(routeState.keyword);
}}>重试</Button>} },
/> }}
) : ( filteredEmptyState={{
<> onAction: resetFilters,
<Table }}
rowKey="skill_code" totalLabel={`共 ${totalCount} 条`}
columns={columns} />
dataSource={items}
loading={loading}
empty={{
description: hasFilter ? '未找到匹配结果' : '当前还没有Skill',
action: hasFilter ? <Button size="small" onClick={resetFilters}>清空搜索</Button> : undefined,
}}
/>
{items.length === 0 && hasFilter ? <StatePlaceholder state="filtered-empty" /> : null}
<div className="text-sm text-[var(--gl-color-text-secondary)]">共 {totalCount} 条</div>
</>
)}
</div> </div>
<SkillDetailDrawer routeState={routeState} skillCode={routeState.detail} /> <SkillDetailDrawer routeState={routeState} skillCode={routeState.detail} />
......
import type { Config } from 'tailwindcss'; import type { Config } from 'tailwindcss';
export default { export default {
content: ['./index.html', './src/**/*.{ts,tsx}', './packages/**/*.{ts,tsx}'], content: ['./index.html', './src/**/*.{ts,tsx}', './packages/**/*.{ts,tsx}', '../../../packages/business-components/src/**/*.{ts,tsx}'],
theme: { theme: {
extend: {}, extend: {},
}, },
......
...@@ -13,11 +13,20 @@ ...@@ -13,11 +13,20 @@
"forceConsistentCasingInFileNames": true, "forceConsistentCasingInFileNames": true,
"module": "ESNext", "module": "ESNext",
"moduleResolution": "Bundler", "moduleResolution": "Bundler",
"baseUrl": ".",
"paths": {
"@gl/business-components": ["../../../packages/business-components/src/index.ts"],
"react": ["./node_modules/@types/react/index.d.ts"],
"react/jsx-runtime": ["./node_modules/@types/react/jsx-runtime.d.ts"],
"react/jsx-dev-runtime": ["./node_modules/@types/react/jsx-dev-runtime.d.ts"],
"tdesign-icons-react": ["./node_modules/tdesign-icons-react"],
"tdesign-react": ["./node_modules/tdesign-react"]
},
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"noEmit": true, "noEmit": true,
"jsx": "react-jsx", "jsx": "react-jsx",
"types": ["vitest/globals", "@testing-library/jest-dom"] "types": ["vitest/globals", "@testing-library/jest-dom"]
}, },
"include": ["src", "packages/ui/src", "packages/contracts"] "include": ["src", "packages/ui/src", "packages/contracts", "../../../packages/business-components/src"]
} }
import react from '@vitejs/plugin-react'; import react from '@vitejs/plugin-react';
import { fileURLToPath, URL } from 'node:url';
import { loadEnv } from 'vite'; import { loadEnv } from 'vite';
import { defineConfig } from 'vitest/config'; import { defineConfig } from 'vitest/config';
...@@ -10,6 +11,14 @@ export default defineConfig(({ mode }) => { ...@@ -10,6 +11,14 @@ export default defineConfig(({ mode }) => {
return { return {
plugins: [react()], plugins: [react()],
resolve: {
alias: {
'@gl/business-components': fileURLToPath(new URL('../../../packages/business-components/src/index.ts', import.meta.url)),
react: fileURLToPath(new URL('./node_modules/react', import.meta.url)),
'tdesign-icons-react': fileURLToPath(new URL('./node_modules/tdesign-icons-react', import.meta.url)),
'tdesign-react': fileURLToPath(new URL('./node_modules/tdesign-react', import.meta.url)),
},
},
server: { server: {
host: '0.0.0.0', host: '0.0.0.0',
proxy: { proxy: {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!