Commit 109adfed by imwangxiaozhou

Merge branch 'ai-workflow-dev' of http://192.168.3.233:8090/ai/ai-workflow into ai-workflow-dev

2 parents 7bb77fa5 9b59f1b0
Showing 154 changed files with 18243 additions and 930 deletions
# 当前状态:yuehu / agent-admin # 当前状态:yuehu / agent-admin
日期:2026-05-16 日期:2026-05-22
## 已完成 ## 已完成
...@@ -23,12 +23,34 @@ ...@@ -23,12 +23,34 @@
- 已通过 `npm run typecheck`、`npm test`、`npm run build`、`openspec validate define-ui-component-library --strict`,并确认 `http://127.0.0.1:5173/components` 返回 200。浏览器插件运行时初始化连续超时,因此 OpenSpec 任务 11.4 暂未勾选。 - 已通过 `npm run typecheck`、`npm test`、`npm run build`、`openspec validate define-ui-component-library --strict`,并确认 `http://127.0.0.1:5173/components` 返回 200。浏览器插件运行时初始化连续超时,因此 OpenSpec 任务 11.4 暂未勾选。
- 已根据人工浏览器反馈更新 `define-ui-component-library` 的 design/tasks,并修正 TreeSelect/Select/Collapse 箭头图标、TreeSelect 选中态、DatePicker 面板结构、SearchInput 图标尺寸、Checkbox/Switch Demo 可交互状态。 - 已根据人工浏览器反馈更新 `define-ui-component-library` 的 design/tasks,并修正 TreeSelect/Select/Collapse 箭头图标、TreeSelect 选中态、DatePicker 面板结构、SearchInput 图标尺寸、Checkbox/Switch Demo 可交互状态。
- 修正后已通过 `npm run typecheck`、`npm test`、`npm run build`、`openspec validate define-ui-component-library --strict`,并再次确认 `/components` 返回 200。右侧浏览器插件连接仍超时,所以 11.4 继续保持未勾选。 - 修正后已通过 `npm run typecheck`、`npm test`、`npm run build`、`openspec validate define-ui-component-library --strict`,并再次确认 `/components` 返回 200。右侧浏览器插件连接仍超时,所以 11.4 继续保持未勾选。
- 已为 `workspace/agent-admin/web` 新建 OpenSpec change `skill-list-markdown-drawer`,覆盖 `/skills` 只读列表、关键词搜索、详情抽屉、Markdown 基础渲染、代码块样式、抽屉内滚动和 mock 状态。
- 已同步更新 `workspace/agent-admin/web/docs/frontend-foundation.md`,把 Markdown 渲染和抽屉内容区独立滚动记为基础能力边界,避免混入业务 OpenSpec。
- 已完成 `openspec validate skill-list-markdown-drawer --strict`,当前该 change 的 proposal、design、specs、tasks 均已通过校验。
- 已按 `$openspec-superpowers-workflow` 为 `workspace/agent-admin/web` 完成 `agent-tags-management` 的 Superpowers 探索设计稿与 OpenSpec artifacts。
- `agent-tags-management` 已确认采用 `/agent-tags` 列表页、`/agent-tags/new` 独立新建页、`/agent-tags/:tagId/edit` 独立编辑页;新建/编辑页头右上角按钮固定为 `取消`、`保存`;编辑页不新增岗位标签详情接口,优先使用列表点击时的 route state,刷新或直达时按 `tagId` 从列表 mock 数据源兜底。
- 已通过 `openspec status --change "agent-tags-management" --json` 确认 proposal、design、specs、tasks 均完成,并通过 `openspec validate "agent-tags-management" --strict`。
- 已根据 `packages/contracts/frontend-api-contract.md` 的 `### 5.4 检查岗位标签引用` 更新 `agent-tags-management` 删除规则:删除前先查引用;仅 Agent 引用时提示 `删除后这些 Agent 将失去该标签` 并要求确认;渠道活码引用提示 `请先删除关联的渠道活码` 并阻断;官网 Tab 引用提示 `请先删除关联的官网 Tab 配置` 并阻断;阻塞引用解除后方可删除。
- 已为 `workspace/agent-admin/web` 创建 OpenSpec change `channel-code-management`,覆盖 `/channel-codes` 列表、`/channel-codes/new` 新建、`/channel-codes/:codeId/edit` 编辑、查看活码抽屉、启停二次确认、停用业务阻断、二维码图片失败状态和渠道活码最小 mock 契约。
- 已通过 `openspec status --change "channel-code-management" --json` 确认 proposal、design、specs、tasks 均完成,并通过 `openspec validate "channel-code-management" --strict`。
- 已根据用户确认的 change name `admin-interaction-consistency` 创建 `workspace/agent-admin/web/openspec/changes/admin-interaction-consistency/`,完成 proposal、design、spec 和 tasks,覆盖后台全局操作反馈、跳转后一次性提示、导航层级区分和列表搜索 placeholder 一致性。
- 已检查 active changes 中的列表搜索 placeholder 冲突,并将 `channel-code-management` 的活码名称搜索 placeholder 从 `请输入活码名称` 对齐为 `搜索活码名称`。
- 已通过 `openspec status --change "admin-interaction-consistency" --json` 确认 artifacts 完成,并通过 `openspec validate "admin-interaction-consistency" --strict` 与 `openspec validate "channel-code-management" --strict`。
- 已为 `workspace/agent-admin/web` 新建 OpenSpec change `official-site-job-tab-ai-intro`,覆盖岗位展示配置新增/编辑页的“岗位 AI 赋能介绍”模块、`main_title`/`sub_title` 字段契约、为空与超长校验、mock fixture 场景和既有岗位展示规则不变。
- 已通过 `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,且本轮未写业务代码。
- 已通过 `openspec status --change "official-site-agent-display-config" --json` 确认 proposal、design、specs、tasks 均完成,并通过 `openspec validate "official-site-agent-display-config" --strict`。
## 当前重点 ## 当前重点
在编写业务代码前,先完成全局前端基座和全局 UI 组件库。 在编写业务代码前,持续把新的业务页行为先落到 OpenSpec。当前 `official-site-agent-display-config` 已完成 OpenSpec 锁定,等待用户确认 artifacts;不应在确认前进入实现。
## 下一步 ## 下一步
1. 在右侧浏览器插件恢复后,补做 `/components` 可视化验收并勾选 `define-ui-component-library` 任务 11.4。 1. 等待用户确认 `official-site-agent-display-config` OpenSpec artifacts。
2. 根据人工评审继续细化组件视觉和交互边界。 2. 若确认进入实现阶段,先按 tasks 编写前端契约、mock fixture 与页面测试,再实现路由页面、上下文展示、列表状态映射、编辑弹窗、上传校验和保存反馈。
3. 实现后运行 `npm run typecheck`、`npm test`、`npm run build`,并用浏览器验证 `/official-site/job-tabs/:tabId/agents` 的布局、返回列表、停用不可编辑、上传错误和保存反馈。
## 会话记录
- 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 锁定;本轮未写业务代码。
...@@ -99,9 +99,13 @@ ...@@ -99,9 +99,13 @@
### 选择类组件需要明确选中反馈 ### 选择类组件需要明确选中反馈
`Select` 与 `TreeSelect` SHALL 在选中后展示清晰选中态:触发器文字显示当前选中项,面板内对应项显示主色文字或浅主色背景,并暴露 `aria-selected`。树形节点展开后,父节点保持层级关系,叶子节点选中效果不得只依赖触发器文字。 `Select` 单选模式与 `TreeSelect` SHALL 在选中后展示清晰选中态:触发器文字显示当前选中项,面板内对应项显示主色文字或浅主色背景,并暴露 `aria-selected`。树形节点展开后,父节点保持层级关系,叶子节点选中效果不得只依赖触发器文字。
`Select` 在用户点击某个选项后 SHALL 立即关闭当前下拉面板,避免面板停留在页面上遮挡后续字段或操作区。该关闭行为对受控与非受控用法保持一致。 `Select` 还 SHALL 支持多选模式。多选模式下 `value` 语义应扩展为多值集合,用户点击未选项时加入当前集合,点击已选项时从集合中移除,面板保持打开以便继续勾选或取消。触发器需要支持可配置的已选项展示方式:默认摘要模式优先显示首个已选项的文案,其余已选项折叠为 `+N` 计数形式,例如 `北京 +2`;另可切换为 Tag 模式,以 `Tag` 形式展示每个已选项。面板内选中项需要展示勾选态;`allowClear` 在存在任意已选值时展示,并清空全部已选项。
`Select` 单选模式在用户点击某个选项后 SHALL 立即关闭当前下拉面板,避免面板停留在页面上遮挡后续字段或操作区。该关闭行为对受控与非受控用法保持一致;多选模式则 SHALL 保持面板打开,以便继续勾选或取消其他选项。
`Select` 的下拉面板 SHALL 支持点击页面其他区域自动关闭。该外部点击收起行为对单选和多选模式都生效;点击触发器自身、面板内部选项、Tag 删除按钮或清空按钮时,不应被误判为外部点击。
`Select` 的清空入口 SHALL 保持显式可配置。业务页面未开启 `allowClear` 时,组件不得在控件下方自动渲染独立 `清空` 按钮;当业务页面将“恢复默认值”设计为重新选择 `全部` 选项时,组件只负责展示当前值和下拉面板,不额外叠加第二套重置入口。 `Select` 的清空入口 SHALL 保持显式可配置。业务页面未开启 `allowClear` 时,组件不得在控件下方自动渲染独立 `清空` 按钮;当业务页面将“恢复默认值”设计为重新选择 `全部` 选项时,组件只负责展示当前值和下拉面板,不额外叠加第二套重置入口。
......
...@@ -11,6 +11,7 @@ ...@@ -11,6 +11,7 @@
- 补充通用状态占位组件,用于统一表达空数据、筛选无结果、加载失败、权限受限等页面或列表内容状态,并明确加载失败不得误用“暂无数据”。 - 补充通用状态占位组件,用于统一表达空数据、筛选无结果、加载失败、权限受限等页面或列表内容状态,并明确加载失败不得误用“暂无数据”。
- 补充可复用后台导航组件能力,承载一级/二级菜单、父子级选中态和层级结构,避免业务页面手写侧边菜单。 - 补充可复用后台导航组件能力,承载一级/二级菜单、父子级选中态和层级结构,避免业务页面手写侧边菜单。
- 补齐 `Pagination` 的当前页可见选中态,以及跳转输入框按 Enter 直接触发跳转的键盘交互。 - 补齐 `Pagination` 的当前页可见选中态,以及跳转输入框按 Enter 直接触发跳转的键盘交互。
- 为 `Select` 补充多选能力,支持多值受控/非受控、选项勾选态、下拉外部点击收起、摘要与 Tag 两种已选项展示、清空全部已选项和后台筛选场景复用。
- 确认一期组件库使用 React、TypeScript、CSS Variables 与 CSS Modules / 普通 CSS 实现;组件内部不依赖 Tailwind CSS。 - 确认一期组件库使用 React、TypeScript、CSS Variables 与 CSS Modules / 普通 CSS 实现;组件内部不依赖 Tailwind CSS。
- 允许后续业务页面使用 Tailwind CSS 做页面级布局,但组件必须自带完整规范样式,并通过受控 API、`className`、`style` 和 CSS 变量支持扩展。 - 允许后续业务页面使用 Tailwind CSS 做页面级布局,但组件必须自带完整规范样式,并通过受控 API、`className`、`style` 和 CSS 变量支持扩展。
- 在保持当前目录结构不调整的前提下,将组件能力按全局可复用资产设计,避免绑定单一业务项目。 - 在保持当前目录结构不调整的前提下,将组件能力按全局可复用资产设计,避免绑定单一业务项目。
...@@ -31,5 +32,6 @@ ...@@ -31,5 +32,6 @@
- 影响前端组件架构和后续业务页面实现规则。 - 影响前端组件架构和后续业务页面实现规则。
- 预计涉及目标前端应用或 UI 包、共享 UI 组件导出、样式 token、状态占位组件、组件测试工具链,以及组件 Demo 页路由。 - 预计涉及目标前端应用或 UI 包、共享 UI 组件导出、样式 token、状态占位组件、组件测试工具链,以及组件 Demo 页路由。
- 预计涉及 `Select` 的值类型扩展、多选交互、选中态展示、触发器摘要/Tag 展示配置、测试用例和 Demo 路由。
- 技术选型影响一期组件源码组织、样式实现方式、组件测试方式和后续业务页面使用边界。 - 技术选型影响一期组件源码组织、样式实现方式、组件测试方式和后续业务页面使用边界。
- 不引入后端 API、数据存储或业务流程变更。 - 不引入后端 API、数据存储或业务流程变更。
...@@ -84,6 +84,10 @@ ...@@ -84,6 +84,10 @@
### Requirement: Select 支持后台筛选工作流 ### Requirement: Select 支持后台筛选工作流
`Select` SHALL 支持后台筛选类表单的标准交互,包括选择后自动收起,以及按业务决定是否展示独立清空入口。 `Select` SHALL 支持后台筛选类表单的标准交互,包括选择后自动收起,以及按业务决定是否展示独立清空入口。
#### Scenario: 点击页面其他区域关闭下拉
- **WHEN** `Select` 下拉面板处于展开状态且用户点击触发器与面板以外的页面区域
- **THEN** 当前下拉面板自动关闭
#### Scenario: 选择后关闭下拉面板 #### Scenario: 选择后关闭下拉面板
- **WHEN** 用户在 `Select` 下拉面板中选择任一可用选项 - **WHEN** 用户在 `Select` 下拉面板中选择任一可用选项
- **THEN** 组件更新当前值 - **THEN** 组件更新当前值
...@@ -98,6 +102,38 @@ ...@@ -98,6 +102,38 @@
- **THEN** 组件展示独立的 `清空` 按钮 - **THEN** 组件展示独立的 `清空` 按钮
- **AND** 用户点击后将当前值重置为空 - **AND** 用户点击后将当前值重置为空
### Requirement: Select 支持单选与多选模式
`Select` SHALL 支持多选模式以承载可并行筛选的字段。多选模式下组件以集合值维护已选项,面板内选中态和清空行为需与单选模式区分。
#### Scenario: 多选模式下勾选多个选项
- **WHEN** `Select` 开启多选模式且用户点击一个未选中的可用选项
- **THEN** 该选项加入已选集合
- **AND** 面板保持打开,便于继续选择或取消其他选项
#### Scenario: 多选模式下取消已选项
- **WHEN** `Select` 开启多选模式且用户点击一个已选中的可用选项
- **THEN** 该选项从已选集合中移除
- **AND** 面板保持打开,便于继续调整选择
#### Scenario: 多选模式下清空全部已选项
- **WHEN** `Select` 开启多选模式、业务页面开启 `allowClear` 且当前已有任意选中值
- **THEN** 组件展示独立的 `清空` 按钮
- **AND** 用户点击后清空全部已选项
#### Scenario: 多选模式下展示摘要
- **WHEN** `Select` 开启多选模式且当前已配置摘要展示方式并已有多个已选项
- **THEN** 触发器优先展示首个已选项的文案
- **AND** 其余已选项折叠为 `+N` 计数摘要
#### Scenario: 多选模式下展示标签
- **WHEN** `Select` 开启多选模式且当前已配置 Tag 展示方式并已有多个已选项
- **THEN** 触发器以内嵌 `Tag` 形式展示每个已选项
- **AND** 用户可以通过 `Tag` 的关闭入口移除对应已选项
#### Scenario: 保持单选工作流兼容
- **WHEN** `Select` 未开启多选模式
- **THEN** 组件继续遵循单选工作流:选择后更新当前值并关闭下拉面板
### Requirement: Navigation 支持后台层级菜单 ### Requirement: Navigation 支持后台层级菜单
共享导航组件 SHALL 支持后台左侧层级菜单工作流,统一承载一级/二级菜单结构、父子级选中态和数据驱动渲染。 共享导航组件 SHALL 支持后台左侧层级菜单工作流,统一承载一级/二级菜单结构、父子级选中态和数据驱动渲染。
......
...@@ -32,7 +32,9 @@ ...@@ -32,7 +32,9 @@
- [x] 3.9 根据人工验收修正选择类下拉互斥:同一页面中 `Select` 与 `TreeSelect` 只能同时打开一个下拉面板,打开新的选择器时自动关闭旧面板,并补充回归测试。 - [x] 3.9 根据人工验收修正选择类下拉互斥:同一页面中 `Select` 与 `TreeSelect` 只能同时打开一个下拉面板,打开新的选择器时自动关闭旧面板,并补充回归测试。
- [x] 3.10 根据人工验收修正选择类下拉定位:`Select` 与 `TreeSelect` 下拉面板定位在触发器下方并脱离文档流,不挤压下面元素,补充样式回归测试。 - [x] 3.10 根据人工验收修正选择类下拉定位:`Select` 与 `TreeSelect` 下拉面板定位在触发器下方并脱离文档流,不挤压下面元素,补充样式回归测试。
- [x] 3.11 根据人工验收修正 `TreeSelect` 父节点收起交互:再次点击已展开父节点时收起子节点并更新箭头与 `aria-expanded`,补充回归测试。 - [x] 3.11 根据人工验收修正 `TreeSelect` 父节点收起交互:再次点击已展开父节点时收起子节点并更新箭头与 `aria-expanded`,补充回归测试。
- [ ] 3.12 根据人工验收补齐 `Select` 后台筛选交互:选中选项后自动收起下拉面板,并确认 `allowClear` 关闭时不展示独立 `清空` 按钮,补充回归测试。 - [x] 3.12 根据人工验收补齐 `Select` 下拉收起交互:单选选择后自动收起,多选保持展开并支持点击页面其他区域关闭,下拉外部点击与触发器内部点击行为补充回归测试。
- [x] 3.13 根据人工验收补齐 `Select` 多选接口和 TDD 用例:定义多选值集合、已选项切换、清空全部已选项、多选摘要/Tag 展示配置和多选模式下的面板保持打开行为,并先写失败测试和审核注释。
- [x] 3.14 根据人工验收实现 `Select` 多选逻辑和样式:完成多选勾选态、触发器摘要/Tag 展示、Tag 删除样式、清空全部已选项、单选/多选兼容与回归测试。
## 4. 日期组件 ## 4. 日期组件
...@@ -58,7 +60,7 @@ ...@@ -58,7 +60,7 @@
- [x] 5.3 实现 `Table` 状态逻辑:完成 loading、empty、排序、筛选、行选择和操作列逻辑,并补齐单元测试、审核注释。 - [x] 5.3 实现 `Table` 状态逻辑:完成 loading、empty、排序、筛选、行选择和操作列逻辑,并补齐单元测试、审核注释。
- [x] 5.4 实现 `Table` 样式:完成表头、行 hover、选择列、操作列、loading 蒙层和空状态样式,并补齐渲染测试和审核注释。 - [x] 5.4 实现 `Table` 样式:完成表头、行 hover、选择列、操作列、loading 蒙层和空状态样式,并补齐渲染测试和审核注释。
- [x] 5.5 实现 `Pagination`:包含接口定义、页码/每页条数/总数/跳页逻辑、分页样式、单元测试、审核注释。 - [x] 5.5 实现 `Pagination`:包含接口定义、页码/每页条数/总数/跳页逻辑、分页样式、单元测试、审核注释。
- [ ] 5.5a 根据人工验收补齐 `Pagination` 当前页选中态与键盘跳转:当前页按钮展示明显选中态,跳转输入框按 Enter 触发页码跳转,并补充回归测试和审核注释。 - [x] 5.5a 根据人工验收补齐 `Pagination` 当前页选中态与键盘跳转:当前页按钮展示明显选中态,跳转输入框按 Enter 触发页码跳转,并补充回归测试和审核注释。
- [x] 5.6 验证 `Table` 与 `Pagination`、`Tag`、`Badge`、`Button`、`Popconfirm` 的组合示例和审核注释。 - [x] 5.6 验证 `Table` 与 `Pagination`、`Tag`、`Badge`、`Button`、`Popconfirm` 的组合示例和审核注释。
- [x] 5.7 根据人工验收增强 `Table` 空状态:保留 `emptyText` 兼容,新增可配置 `empty` 插槽,默认复用统一空状态视觉,并在 Demo 表格模块展示空表格样例,补充回归测试和审核注释。 - [x] 5.7 根据人工验收增强 `Table` 空状态:保留 `emptyText` 兼容,新增可配置 `empty` 插槽,默认复用统一空状态视觉,并在 Demo 表格模块展示空表格样例,补充回归测试和审核注释。
...@@ -103,8 +105,8 @@ ...@@ -103,8 +105,8 @@
- [x] 8.5 实现 `SkeletonAvatar`、`SkeletonParagraph`、`SkeletonButton` 和 `SkeletonInput`:包含接口定义、组合逻辑、形态样式、单元测试、审核注释。 - [x] 8.5 实现 `SkeletonAvatar`、`SkeletonParagraph`、`SkeletonButton` 和 `SkeletonInput`:包含接口定义、组合逻辑、形态样式、单元测试、审核注释。
- [x] 8.6 根据人工验收统一 `Collapse` 等展开箭头:与选择类组件复用同一箭头图标资产,补充样式回归测试。 - [x] 8.6 根据人工验收统一 `Collapse` 等展开箭头:与选择类组件复用同一箭头图标资产,补充样式回归测试。
- [x] 8.7 实现 `StatePlaceholder` 基础接口与请求失败态:支持 `error` 状态、标题、说明、主操作、次操作、图标、可访问性角色、单元测试和审核注释,并确保失败态不使用“暂无数据”文案。 - [x] 8.7 实现 `StatePlaceholder` 基础接口与请求失败态:支持 `error` 状态、标题、说明、主操作、次操作、图标、可访问性角色、单元测试和审核注释,并确保失败态不使用“暂无数据”文案。
- [ ] 8.8 补齐 `StatePlaceholder` 其他语义状态验收:覆盖 `empty`、`filtered-empty`、`forbidden` 和 `offline` 的专项测试,确认默认标题、说明、角色和样式语义符合规范。 - [x] 8.8 补齐 `StatePlaceholder` 其他语义状态验收:覆盖 `empty`、`filtered-empty`、`forbidden` 和 `offline` 的专项测试,确认默认标题、说明、角色和样式语义符合规范。
- [ ] 8.9 扩展共享 `Navigation` 组件以支持后台侧边导航:覆盖一级/二级菜单、父子级选中态、数据驱动渲染,补充单元测试、Demo 示例和审核注释。 - [x] 8.9 扩展共享 `Navigation` 组件以支持后台侧边导航:覆盖一级/二级菜单、父子级选中态、数据驱动渲染,补充单元测试、Demo 示例和审核注释。
## 9. 颜色能力组件 ## 9. 颜色能力组件
...@@ -125,7 +127,7 @@ ...@@ -125,7 +127,7 @@
- [x] 10.8 根据人工确认新增 `Upload` Demo:展示文件拖拽上传完成、上传中、失败状态,以及图片/视频媒体墙,补充 Demo 回归测试。 - [x] 10.8 根据人工确认新增 `Upload` Demo:展示文件拖拽上传完成、上传中、失败状态,以及图片/视频媒体墙,补充 Demo 回归测试。
- [x] 10.9 根据人工确认补齐基础输入 Demo:展示 `Input` 与 `Textarea` 的简洁长度显示配置,补充 Demo 回归测试。 - [x] 10.9 根据人工确认补齐基础输入 Demo:展示 `Input` 与 `Textarea` 的简洁长度显示配置,补充 Demo 回归测试。
- [x] 10.10 补齐 `StatePlaceholder` 请求失败 Demo:展示加载失败状态,并覆盖加载失败提供重试操作、不展示“暂无数据”的验收样例。 - [x] 10.10 补齐 `StatePlaceholder` 请求失败 Demo:展示加载失败状态,并覆盖加载失败提供重试操作、不展示“暂无数据”的验收样例。
- [ ] 10.11 补齐 `StatePlaceholder` 全状态 Demo:展示空数据、筛选无结果、权限受限和离线不可用状态,便于人工验收全部状态占位视觉。 - [x] 10.11 补齐 `StatePlaceholder` 全状态 Demo:展示空数据、筛选无结果、权限受限和离线不可用状态,便于人工验收全部状态占位视觉。
## 10A. 上传组件 ## 10A. 上传组件
...@@ -138,6 +140,6 @@ ...@@ -138,6 +140,6 @@
- [x] 11.1 运行目标前端项目的类型检查,确认组件接口和导出边界无类型错误。 - [x] 11.1 运行目标前端项目的类型检查,确认组件接口和导出边界无类型错误。
- [x] 11.2 运行组件相关单元测试,确认每个组件的接口定义、逻辑实现、样式状态和关键交互均被覆盖。 - [x] 11.2 运行组件相关单元测试,确认每个组件的接口定义、逻辑实现、样式状态和关键交互均被覆盖。
- [x] 11.3 如果目标项目存在额外测试命令,运行相关自动化测试。 - [x] 11.3 如果目标项目存在额外测试命令,运行相关自动化测试。
- [ ] 11.4 启动前端应用,并在浏览器中验证独立组件 Demo 路由的布局、交互和设计一致性。 - [x] 11.4 启动前端应用,并在浏览器中验证独立组件 Demo 路由的布局、交互和设计一致性。
- [ ] 11.5 确认 Demo 路由展示全部一期组件,并纳入 `Upload`,同时排除其他 `App.tsx` 中的 demo-only 组件。 - [x] 11.5 确认 Demo 路由展示全部一期组件,并纳入 `Upload`,同时排除其他 `App.tsx` 中的 demo-only 组件。
- [x] 11.6 后续验证 `StatePlaceholder` 可在表格或列表内容区域承载失败态,并保持页面框架、筛选区和导航区可用。 - [x] 11.6 后续验证 `StatePlaceholder` 可在表格或列表内容区域承载失败态,并保持页面框架、筛选区和导航区可用。
# frontend-app-foundation Specification
## Purpose
TBD - created by archiving change define-frontend-app-foundation. Update Purpose after archive.
## Requirements
### Requirement: 统一 React 前端技术栈
monorepo 前端应用 SHALL 使用 React + TypeScript 作为统一应用开发技术栈。新建前端应用 SHALL 以该技术栈为默认选择,除非后续 OpenSpec change 明确批准例外。
#### Scenario: 创建新的前端应用
- **WHEN** 需要在 monorepo 中创建新的 Web 前端应用
- **THEN** 应用技术栈 SHALL 使用 React + TypeScript
#### Scenario: 定义组件和页面接口
- **WHEN** 前端应用定义组件 props、路由参数、页面状态或 mock 数据结构
- **THEN** 相关接口 SHALL 使用 TypeScript 类型显式表达
### Requirement: 统一前端构建与路由方案
monorepo 前端应用 SHALL 使用 Vite 作为构建与本地开发工具,并使用 React Router 管理客户端路由。
#### Scenario: 启动本地前端开发
- **WHEN** 开发者启动前端应用本地开发环境
- **THEN** 应用 SHALL 通过 Vite 提供本地开发服务器
#### Scenario: 添加应用路由
- **WHEN** 前端应用需要新增页面或功能入口
- **THEN** 页面入口 SHALL 通过 React Router 注册为客户端路由
### Requirement: 组件 Demo 独立路由
前端基座 SHALL 支持全局 UI 组件库的独立 Demo 路由。默认路径 SHALL 为 `/components`,除非落地应用已有路径冲突。
#### Scenario: 访问组件 Demo 页面
- **WHEN** 用户访问 `/components`
- **THEN** 系统 SHALL 展示全局 UI 组件库的一期组件示例入口
#### Scenario: 默认路径冲突
- **WHEN** `/components` 与落地应用已有路由冲突
- **THEN** 实施任务 SHALL 记录冲突原因,并选择一个等价的独立组件 Demo 路由
### Requirement: 统一前端测试方案
monorepo 前端应用 SHALL 使用 Vitest 和 React Testing Library 作为默认测试方案。测试 SHALL 优先验证用户可观察行为、组件接口和关键交互状态。
#### Scenario: 新增组件或页面行为
- **WHEN** 新增或修改前端组件、路由页面或交互行为
- **THEN** 实施 SHALL 提供对应的 Vitest 与 React Testing Library 测试,或记录无法自动化覆盖的原因
#### Scenario: 验证前端基座
- **WHEN** 前端应用结构完成或更新
- **THEN** 实施 SHALL 运行类型检查和相关测试命令,并记录验证结果
### Requirement: 前端基座实现采用 TDD
前端基座实现 SHALL 采用测试先行方式。新增或修改应用入口、基础路由、组件 Demo 路由、样式入口、测试环境或可观察交互行为前,实施 SHALL 先编写失败测试或可执行验收样例,确认失败原因与目标能力缺失一致,再补充最小实现使测试通过。
#### Scenario: 实现基础路由前先写测试
- **WHEN** 实施基础路由或 `/components` Demo 路由
- **THEN** 实施 SHALL 先编写路由渲染测试并确认测试失败,再实现路由注册和页面入口
#### Scenario: 实现应用入口前先写测试
- **WHEN** 实施前端应用入口、根组件或基础布局
- **THEN** 实施 SHALL 先编写入口渲染测试或可执行验收样例并确认失败,再补充最小实现
#### Scenario: 配置无法先写行为测试
- **WHEN** 某个配置类任务无法合理先写自动化行为测试
- **THEN** 实施 SHALL 记录原因,并通过类型检查、测试命令或浏览器验证作为替代验收
### Requirement: 样式职责边界
全局 UI 组件内部 SHALL 使用 CSS Variables + CSS Modules / 普通 CSS 实现完整规范样式。业务页面 MAY 使用 Tailwind CSS 做页面级布局,但 SHALL NOT 依赖 Tailwind CSS 覆盖组件内部结构样式。
#### Scenario: 实现全局 UI 组件样式
- **WHEN** 实现或修改全局 UI 组件
- **THEN** 组件内部样式 SHALL 使用 CSS Variables + CSS Modules / 普通 CSS,并自带符合设计规范的默认样式
#### Scenario: 编写业务页面布局
- **WHEN** 业务页面需要组织页面布局、间距、栅格或容器
- **THEN** 页面 MAY 使用 Tailwind CSS 完成页面级布局
#### Scenario: 定制组件表现
- **WHEN** 业务页面需要调整组件表现
- **THEN** 页面 SHALL 优先通过组件 props、CSS 变量、`className` 或 `style` 进行受控扩展
### Requirement: 当前目录结构内落地
前端基座 SHALL 在当前 monorepo 目录结构内落地。`workspace/agent-admin/web` SHALL 作为首个承载项目,但该基座规则 SHALL 面向 monorepo 后续所有 React 前端项目。
#### Scenario: 首次落地前端基座
- **WHEN** 实施本前端基座
- **THEN** 首个落地范围 SHALL 位于当前 `workspace/agent-admin/web` 目录结构内
#### Scenario: 后续目录重组
- **WHEN** 需要将前端基座迁移到新的全局工作区或共享包结构
- **THEN** 迁移 SHALL 通过新的 OpenSpec change 定义范围、影响和迁移计划
### Requirement: 与全局 UI 组件库协同
前端基座 SHALL 为全局 UI 组件库提供稳定承载规则,包括组件导入、样式入口、测试运行和 Demo 路由接入方式。
#### Scenario: 接入全局 UI 组件库
- **WHEN** 前端应用使用全局 UI 组件库
- **THEN** 应用 SHALL 通过稳定导出入口导入组件,并加载组件库要求的基础样式入口
#### Scenario: 展示组件库内容
- **WHEN** 全局 UI 组件库完成一期组件定义
- **THEN** 前端基座 SHALL 支持在独立 Demo 路由中展示组件默认态、关键状态和组合示例
# ui-component-library Specification
## Purpose
TBD - created by archiving change define-ui-component-library. Update Purpose after archive.
## Requirements
### Requirement: 一期组件库范围
系统 SHALL 基于已上传设计规范中的独立组件文件,提供一期 Web 桌面端 UI 组件库。
一期范围 SHALL 包含 `Button`、`Input`、`Textarea`、`SearchInput`、`TreeSelect`、`Table`、`Badge`、`Pagination`、`Alert`、`Message`、`Modal`、`FormItem`、`Card`、`DatePicker`、`DateRangePicker`、`Switch`、`Tag`、`Avatar`、`AvatarGroup`、`Tooltip`、`Popconfirm`、`Progress`、`Statistic`、`Timeline`、`Tabs`、`Drawer`、`Steps`、`Checkbox`、`Radio`、`Select`、`Empty`、`StatePlaceholder`、`Skeleton`、`SkeletonAvatar`、`SkeletonParagraph`、`SkeletonButton`、`SkeletonInput`、`Collapse`、`ColorPicker`、`ColorInput` 和 `Upload`。
#### Scenario: 实现一期组件
- **WHEN** 实现组件库
- **THEN** 一期范围内的每个组件都可作为项目级可复用组件使用
#### Scenario: 避免纳入 demo-only 组件
- **WHEN** `App.tsx` 中存在不是独立组件文件的 demo-only 组件
- **THEN** 本 change 不要求实现这些 demo-only 组件
### Requirement: Upload 支持文件拖拽上传形态
`Upload` SHALL 提供大拖拽上传框与下方文件项列表,用于资料、附件、合同、导入文件等非媒体文件上传场景。
#### Scenario: 展示文件上传入口
- **WHEN** 页面渲染文件上传入口
- **THEN** 上传框 SHALL 采用约 500px 宽、208px 高的大拖拽区域,使用浅品牌色圆形底上传图标,并在框内展示主文案和限制辅助文案
#### Scenario: 展示文件任务状态
- **WHEN** 文件进入上传任务列表
- **THEN** 文件项 SHALL 展示文件图标、文件名、文件大小、状态和状态对应操作
#### Scenario: 操作完成文件
- **WHEN** 文件上传已完成
- **THEN** 文件项 SHALL 预留预览、下载和删除入口
#### Scenario: 操作失败文件
- **WHEN** 文件上传失败
- **THEN** 文件项 SHALL 展示失败状态,并提供重试和删除入口
#### Scenario: 处理校验失败
- **WHEN** 文件在业务校验阶段失败
- **THEN** 文件 SHALL NOT 进入上传任务列表,业务侧 SHOULD 使用 Toast 提示校验原因
### Requirement: Upload 支持图片和视频媒体墙形态
`Upload` SHALL 提供媒体墙形态,用于图片和视频资源上传与管理。
#### Scenario: 展示媒体墙
- **WHEN** 页面渲染媒体墙
- **THEN** 媒体项 SHALL 使用约 96px × 96px 的方形格,图片展示缩略图,视频展示封面缩略图和播放图标
#### Scenario: 继续添加媒体
- **WHEN** 媒体墙存在已上传素材
- **THEN** 上传入口 SHALL 放在所有媒体项最后
#### Scenario: 展示媒体限制说明
- **WHEN** 媒体墙需要说明格式、大小或数量限制
- **THEN** 限制说明 SHALL 展示在媒体墙下方,而不是塞入上传格内部
#### Scenario: 预览媒体
- **WHEN** 用户点击图片或视频媒体项
- **THEN** 组件 SHALL 触发预览回调;图片放大展示和视频播放弹层由业务侧组合实现
### Requirement: 基础输入组件支持简洁长度显示
基础输入组件 SHALL 支持简洁长度显示能力,覆盖单行 `Input` 与多行 `Textarea`。
#### Scenario: 展示单行输入长度
- **WHEN** `Input` 启用 `showCount` 且提供 `maxLength`
- **THEN** 组件 SHALL 在输入框内展示当前长度与上限的简洁格式,例如 `12/100`
#### Scenario: 展示多行输入长度
- **WHEN** `Textarea` 启用 `showCount` 且提供 `maxLength`
- **THEN** 组件 SHALL 在控件右下方或等效的紧凑位置展示当前长度与上限的简洁格式,例如 `12/100`
#### Scenario: 仅展示当前长度
- **WHEN** `showCount` 已开启但未配置 `maxLength`
- **THEN** 组件 MAY 只展示当前长度,不强制显示上限
#### Scenario: 保持业务校验独立
- **WHEN** 输入内容超出业务允许范围
- **THEN** 组件 SHALL NOT 代替表单校验或业务拦截,超限处理仍由业务侧决定
### Requirement: 组件遵循 Web 桌面端设计规则
组件库 SHALL 遵循项目 Web 桌面端设计规则,包括颜色、字号、间距、圆角、控件尺寸、加载态、禁用态、错误态和交互反馈。
#### Scenario: 渲染组件状态
- **WHEN** 组件支持禁用、加载、选中、激活、空状态或错误状态
- **THEN** 这些状态使用项目 Web 桌面端设计 token,并与已上传设计规范保持视觉一致
### Requirement: Select 支持后台筛选工作流
`Select` SHALL 支持后台筛选类表单的标准交互,包括选择后自动收起,以及按业务决定是否展示独立清空入口。
#### Scenario: 点击页面其他区域关闭下拉
- **WHEN** `Select` 下拉面板处于展开状态且用户点击触发器与面板以外的页面区域
- **THEN** 当前下拉面板自动关闭
#### Scenario: 选择后关闭下拉面板
- **WHEN** 用户在 `Select` 下拉面板中选择任一可用选项
- **THEN** 组件更新当前值
- **AND** 当前下拉面板立即关闭
#### Scenario: 未开启清空能力
- **WHEN** 业务页面未为 `Select` 开启 `allowClear`
- **THEN** 组件不展示独立的 `清空` 按钮
#### Scenario: 开启清空能力
- **WHEN** 业务页面为 `Select` 开启 `allowClear` 且当前已有选中值
- **THEN** 组件展示独立的 `清空` 按钮
- **AND** 用户点击后将当前值重置为空
### Requirement: Select 支持单选与多选模式
`Select` SHALL 支持多选模式以承载可并行筛选的字段。多选模式下组件以集合值维护已选项,面板内选中态和清空行为需与单选模式区分。
#### Scenario: 多选模式下勾选多个选项
- **WHEN** `Select` 开启多选模式且用户点击一个未选中的可用选项
- **THEN** 该选项加入已选集合
- **AND** 面板保持打开,便于继续选择或取消其他选项
#### Scenario: 多选模式下取消已选项
- **WHEN** `Select` 开启多选模式且用户点击一个已选中的可用选项
- **THEN** 该选项从已选集合中移除
- **AND** 面板保持打开,便于继续调整选择
#### Scenario: 多选模式下清空全部已选项
- **WHEN** `Select` 开启多选模式、业务页面开启 `allowClear` 且当前已有任意选中值
- **THEN** 组件展示独立的 `清空` 按钮
- **AND** 用户点击后清空全部已选项
#### Scenario: 多选模式下展示摘要
- **WHEN** `Select` 开启多选模式且当前已配置摘要展示方式并已有多个已选项
- **THEN** 触发器优先展示首个已选项的文案
- **AND** 其余已选项折叠为 `+N` 计数摘要
#### Scenario: 多选模式下展示标签
- **WHEN** `Select` 开启多选模式且当前已配置 Tag 展示方式并已有多个已选项
- **THEN** 触发器以内嵌 `Tag` 形式展示每个已选项
- **AND** 用户可以通过 `Tag` 的关闭入口移除对应已选项
#### Scenario: 保持单选工作流兼容
- **WHEN** `Select` 未开启多选模式
- **THEN** 组件继续遵循单选工作流:选择后更新当前值并关闭下拉面板
### Requirement: Navigation 支持后台层级菜单
共享导航组件 SHALL 支持后台左侧层级菜单工作流,统一承载一级/二级菜单结构、父子级选中态和数据驱动渲染。
#### Scenario: 渲染一级和二级菜单
- **WHEN** 后台框架传入包含父子层级的导航数据
- **THEN** 组件渲染一级菜单项及其对应的二级菜单项
- **AND** 业务页面无需手写导航层级 DOM 结构
#### Scenario: 二级菜单激活时联动父级样式
- **WHEN** 当前选中项是某个一级菜单下的二级菜单
- **THEN** 该二级菜单展示主选中样式
- **AND** 对应一级菜单同步展示轻度选中样式
#### Scenario: 通过配置驱动导航
- **WHEN** 后台框架传入菜单项标识、标题、层级、链接和当前选中项
- **THEN** 组件根据配置渲染导航,而不是要求业务页面手写交互和样式逻辑
### Requirement: 组件实现采用测试先行
组件实现 SHALL 采用 TDD 方式推进:在实现或迁移组件前,先为组件的公开行为、关键状态和可访问交互编写测试或可执行验收样例。
#### Scenario: 开始实现组件模块
- **WHEN** 开始实现任一逻辑模块内的组件
- **THEN** 先补充该模块组件的行为测试、状态测试或可执行验收样例,再编写组件实现
#### Scenario: 验证设计一致性
- **WHEN** 组件实现完成
- **THEN** 通过自动化测试、Demo 路由和浏览器视觉检查验证组件符合 Web 桌面端设计规则
### Requirement: 组件源码包含审核注释
每个组件源码 SHALL 包含面向人工审核的必要注释,用于说明组件用途、核心 props、关键状态、复杂交互逻辑和设计规范约束。
#### Scenario: 审核组件源码
- **WHEN** 人工审核任一组件源码
- **THEN** 审核者可以通过注释快速理解组件用途、对外接口和关键实现约束
#### Scenario: 编写复杂组件逻辑
- **WHEN** 组件包含树形展开、日期面板、表格状态、弹层滚动锁定等复杂逻辑
- **THEN** 复杂逻辑附近包含简洁注释说明设计意图和边界条件
### Requirement: 组件导出边界稳定
系统 SHALL 通过稳定的共享 UI 导入边界暴露一期组件,供后续业务页面使用。
#### Scenario: 业务页面使用组件
- **WHEN** 后续业务页面需要一期 UI 组件
- **THEN** 页面可以从共享 UI 边界导入组件,而不是复制页面局部组件代码
### Requirement: 表单相关组件支持字段绑定和校验展示
表单相关组件 SHALL 支持通过 `Form` 和 `FormItem` 组合使用,使字段值收集、必填校验、标签、必填标识、帮助文案和校验错误展示保持统一。
#### Scenario: 展示字段错误
- **WHEN** 表单字段存在校验错误
- **THEN** 错误通过字段对应的 `FormItem` 展示在字段附近
#### Scenario: 提交前执行必填校验
- **WHEN** 用户提交包含必填字段的表单
- **THEN** `Form` 在字段为空时阻止提交成功回调,并由对应 `FormItem` 展示必填错误
#### Scenario: 表单项布局和错误占位
- **WHEN** 表单项配置为横向或纵向布局
- **THEN** `FormItem` 按配置展示 label 与控件,并在控件下方保留稳定错误信息区域
#### Scenario: 展示控件右侧辅助提示
- **WHEN** 表单项配置 `tips`
- **THEN** `FormItem` 在输入控件右侧展示弱提示文字,并与控件下方的帮助和错误信息区分展示
#### Scenario: 配置表单项一行展示数量
- **WHEN** 表单配置 `columns=2`
- **THEN** 普通 `FormItem` 以两个一行的栅格密度展示,并允许单个 `FormItem` 通过 `span=2` 独占整行
### Requirement: Table 支持后台列表工作流
表格组件 SHALL 支持后台列表工作流,包括稳定 row key、加载态、空状态、可选行选择、操作列、状态标签组合、排序能力以及筛选 hook 或配置。
#### Scenario: 渲染加载中的列表
- **WHEN** 表格数据正在加载
- **THEN** 表格展示加载状态,并保持结构布局稳定
#### Scenario: 渲染空列表
- **WHEN** 表格数据为空
- **THEN** 表格展示空状态
#### Scenario: 渲染行操作
- **WHEN** 表格行存在可用操作
- **THEN** 表格可以在操作列中渲染紧凑操作控件
### Requirement: Pagination 支持当前页反馈和键盘跳转
分页组件 SHALL 在后台列表场景中明确展示当前页选中态,并支持跳转输入框的 Enter 键提交行为。
#### Scenario: 展示当前页
- **WHEN** 分页渲染当前页码
- **THEN** 当前页按钮 SHALL 展示可见选中态
- **AND** 当前页按钮 SHALL 暴露 `aria-current="page"`
#### Scenario: 按回车跳转
- **WHEN** 用户在跳转输入框输入目标页码并按下 Enter
- **THEN** 分页组件 SHALL 触发与点击“跳转”按钮一致的页码跳转行为
### Requirement: StatePlaceholder 统一内容状态占位
`StatePlaceholder` SHALL 作为组件库统一内容状态占位组件,覆盖空数据、筛选无结果、加载失败、权限受限和离线不可用等状态。
`StatePlaceholder` 的公开状态值 SHALL 使用 `empty`、`filtered-empty`、`error`、`forbidden` 和 `offline`。
项目内所有后台列表、表格列表、卡片列表或资源列表 SHALL 在主数据请求失败且当前数据是否为空未知时使用 `StatePlaceholder` 的 `error` 语义承载内容区失败状态。
#### Scenario: 展示空数据
- **WHEN** 请求成功且当前内容没有任何数据
- **THEN** `StatePlaceholder` 使用空状态语义展示“暂无数据”或业务自定义空态文案
#### Scenario: 展示筛选无结果
- **WHEN** 请求成功但当前搜索或筛选条件没有匹配结果
- **THEN** `StatePlaceholder` 使用 `filtered-empty` 语义展示“未找到匹配结果”或业务自定义文案,并允许业务侧提供清空筛选操作
#### Scenario: 展示加载失败
- **WHEN** 内容数据加载失败且当前数据是否为空未知
- **THEN** `StatePlaceholder` 使用 `error` 语义展示加载失败文案
- **AND** `StatePlaceholder` SHALL NOT 使用“暂无数据”作为失败态主文案
- **AND** `StatePlaceholder` 支持业务侧提供重试操作
#### Scenario: 列表请求失败
- **WHEN** 任意后台列表、表格列表、卡片列表或资源列表的主数据请求失败
- **THEN** 页面使用 `StatePlaceholder` 的 `error` 语义展示列表失败状态
- **AND** 页面保留框架、筛选区、导航区和重试操作可用
- **AND** 页面 SHALL NOT 使用 `Empty`、表格默认空态、“暂无数据”文案、`Alert` 或 `Message` 替代列表内容区失败状态
#### Scenario: 展示权限受限
- **WHEN** 当前账号没有访问内容的权限
- **THEN** `StatePlaceholder` 使用 `forbidden` 语义展示权限受限文案
#### Scenario: 展示离线不可用
- **WHEN** 当前内容因网络不可用无法加载
- **THEN** `StatePlaceholder` 使用 `offline` 语义展示网络不可用文案,并允许业务侧提供重试操作
#### Scenario: 嵌入表格内容区域
- **WHEN** 表格、列表或页面内容区需要展示可恢复失败状态
- **THEN** 业务页面可以在内容区域使用 `StatePlaceholder`,并保持页面框架、筛选区和导航区可用
#### Scenario: 区分反馈组件
- **WHEN** 页面需要表达内容区不可用或数据未知
- **THEN** 页面使用 `StatePlaceholder` 展示内容状态,而不是只使用 `Message` 或 `Alert` 替代内容占位
### Requirement: 反馈和浮层组件支持受控工作流
反馈和浮层组件 SHALL 支持后台常见受控使用方式,包括提示、弹窗、抽屉、二次确认、悬浮说明,以及适用场景下的浮层内容。
#### Scenario: 展示全局消息提示
- **WHEN** 业务操作需要展示保存成功、删除失败、校验提醒等轻量反馈
- **THEN** UI 可以在页面右上角展示自动消失的 `Message` 提示,并支持成功、错误、警告和信息类型
#### Scenario: 确认破坏性操作
- **WHEN** 用户触发行或表单中的破坏性操作
- **THEN** UI 可以在提交操作前展示确认交互
#### Scenario: 编辑时保留列表上下文
- **WHEN** 用户从列表页编辑中等复杂度的记录详情
- **THEN** UI 可以使用抽屉模式,并保留底层页面上下文
### Requirement: Demo 路由展示全部一期组件
系统 SHALL 提供独立组件 Demo 路由,在组件定义完成后展示每个一期组件。
#### Scenario: 打开组件 Demo
- **WHEN** 用户打开组件 Demo 路由
- **THEN** 页面按使用类别展示全部一期组件
#### Scenario: 查看组件状态
- **WHEN** 组件存在有意义的视觉状态
- **THEN** Demo 路由包含这些状态的代表性示例
#### Scenario: 查看组件组合
- **WHEN** 多个组件在后台页面中常被组合使用
- **THEN** Demo 路由包含代表性组合示例,例如表格操作、表单字段、状态标签、分页、弹窗和抽屉
...@@ -49,12 +49,15 @@ async def lifespan(app: FastAPI): ...@@ -49,12 +49,15 @@ async def lifespan(app: FastAPI):
im_service=im_service, im_service=im_service,
) )
# 注册会议纪要管道工具
from skills.meeting_minutes.scripts.pipeline import run_pipeline from skills.meeting_minutes.scripts.pipeline import run_pipeline
agent_hub_instance.tool_manager.register_tool( if "meeting_minutes" not in agent_hub_instance.toolkit.groups:
agent_hub_instance.toolkit.create_tool_group(
"meeting_minutes",
description="会议纪要处理:音频转写、纪要生成、docx导出、OSS上传",
)
agent_hub_instance.toolkit.register_tool_function(
run_pipeline, run_pipeline,
group="meeting_minutes", group_name="meeting_minutes",
description="执行会议纪要完整流程:接收音频 URL → Fun-ASR 转写 → Qwen3.6-plus 生成纪要 → 导出 docx → 上传 OSS 返回下载链接。各步骤状态会写入会话日志。",
) )
yield yield
......
...@@ -4,13 +4,13 @@ ...@@ -4,13 +4,13 @@
"type": "openai_compatible", "type": "openai_compatible",
"api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1", "api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1",
"model_name": "qwen3.6-plus", "model_name": "qwen3.6-plus",
"api_key": "sk-cp-22oeMKkLNyEJZY05vB9Bto-vjO45S_2mLVDzf4Q6hoI65k4Dc93Xz6MSgd1pzZDnWshXU4xEEBjs_cWjCLo1vfrcE9QpOUu287fnnYIPUt3sDp3uetzf5Z8" "api_key": "sk-107dd26bca184e39bd1744af7d634488"
}, },
"summary": { "summary": {
"type": "openai_compatible", "type": "openai_compatible",
"api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1", "api_base": "https://dashscope.aliyuncs.com/compatible-mode/v1",
"model_name": "qwen3.6-plus", "model_name": "qwen3.6-plus",
"api_key": "sk-cp-22oeMKkLNyEJZY05vB9Bto-vjO45S_2mLVDzf4Q6hoI65k4Dc93Xz6MSgd1pzZDnWshXU4xEEBjs_cWjCLo1vfrcE9QpOUu287fnnYIPUt3sDp3uetzf5Z8" "api_key": "sk-107dd26bca184e39bd1744af7d634488"
} }
}, },
"meeting_minutes": { "meeting_minutes": {
......
...@@ -54,6 +54,8 @@ ...@@ -54,6 +54,8 @@
| 关联渠道活码 | 下拉单选 | 是 | 仅展示该岗位相关的已启用渠道活码 | | 关联渠道活码 | 下拉单选 | 是 | 仅展示该岗位相关的已启用渠道活码 |
| 渠道编码 | 只读文本 | 否 | 从渠道活码带入 | | 渠道编码 | 只读文本 | 否 | 从渠道活码带入 |
| 承接员工 | 只读文本 | 否 | 从渠道活码带入 | | 承接员工 | 只读文本 | 否 | 从渠道活码带入 |
| 岗位标题 | 文本 | 是 | 字段 `main_title`,最多 30 字,展示在官网 Tab 名称下方,一句话介绍 AI 如何赋能该岗位 |
| 岗位说明 | 文本域 | 是 | 字段 `sub_title`,最多 200 字,展示在官网 Tab 内容区,详细描述 AI 为该岗位带来的价值 |
| Tab 排序 | 数字 | 是 | 0-99,数字越小越靠左 | | Tab 排序 | 数字 | 是 | 0-99,数字越小越靠左 |
| 展示状态 | 开关 | 是 | 展示中/已下架 | | 展示状态 | 开关 | 是 | 展示中/已下架 |
......
## Context
`workspace/agent-admin/single-page` 负责官网 H5 展示项目。已有需求文档确认页面由接口驱动,包含 Banner、岗位 Tab、岗位体验入口、Agent 卡片和方法论模块;用户进一步确认了岗位 Tab 区域的新交互:左侧大 Agent 素材取自右侧选中的 Agent 卡片,默认选择第一个 Agent,点击 Agent 卡片后联动切换素材。
本 change 只锁定 `single-page` 的前端首页可见行为和 mock/契约准备,不进入业务代码实现。管理后台配置页属于 `web` 项目,真实后端接口、缓存、上传和数据库实现不在本 change 范围内。
## Goals / Non-Goals
**Goals:**
- 锁定 H5 官网首页模块顺序、数据消费和状态边界。
- 锁定 Banner 默认清晰、PC hover 模糊、移动端无点击模糊的交互。
- 锁定岗位 Tab 切换后岗位内容、二维码、Agent 列表和选中 Agent 素材同步切换。
- 锁定“核心能力”标签、岗位标题、岗位概述、Agent 卡片和“立即体验”在 PC 与移动端的布局关系。
- 锁定 Agent 卡片可选择、默认选择第一个 Agent、选中态和素材联动。
- 锁定二维码弹窗、方法论模块、素材类型、加载失败和空数据边界。
- 为后续 TDD 实现准备 mock 契约、fixture、响应式测试和浏览器验证任务。
**Non-Goals:**
- 不实现 H5 业务代码、样式、测试或 mock 文件。
- 不实现后台配置页面、真实接口、真实上传、真实 CDN、Redis 缓存或数据库。
- 不在 H5 前台增加埋点采集。
- 不锁定后端框架或服务端实现方式。
- 不为移动端增加 Banner 点击、触摸或长按模糊状态。
## Decisions
### Decision: 首页采用聚合接口驱动渲染
H5 首页消费 `GET /api/v1/official-site/home` 聚合数据。前端不硬编码岗位数量、岗位名称、Banner 文案/背景、二维码、Agent 卡片或方法论内容。页面状态只围绕接口返回数据派生:当前岗位、当前 Agent、二维码弹窗开关和方法论当前步骤。
替代方案是在 H5 本地保留固定岗位枚举或兜底文案,但这会与后台配置同步目标冲突,也会增加后续运营调整成本。
### Decision: 岗位能力区使用同一状态源驱动 PC 与移动布局
PC/宽屏使用左右结构:左侧展示当前选中 Agent 的大素材和“立即体验”按钮,右侧展示固定标签“核心能力”、岗位标题、岗位概述和 Agent 卡片列表。移动端使用上下结构:Tab 后依次展示大素材与“立即体验”、核心能力/标题/概述、Agent 卡片列表。两种布局共享同一套当前岗位和当前 Agent 状态,不为移动端复制独立数据流。
替代方案是移动端保留旧文档中的 2 列 Agent 网格,但用户已确认移动端参考 `demo2.html`,且新增“点击卡片切换大素材”的交互更适合纵向列表。
### Decision: Agent 卡片由展示配置驱动并承担选中交互
Agent 卡片展示 Agent 图标、Agent 标题和 Agent 概述,字段优先映射为 `icon_url`、`speech_title`、`speech_content`;若聚合接口暂未提供独立图标字段,实现阶段可在 mock 契约中保留 `icon_url`,并以素材缩略或占位作为前端降级。默认选中当前岗位第一个 Agent,切换岗位时重置为该岗位第一个 Agent。
替代方案是 Agent 卡片只展示不可点击信息,但用户已明确调整为卡片选择联动大素材,因此本 change 以选择态为准。
### Decision: Banner blur 只在支持 hover 的设备启用
Banner 默认显示清晰背景图。在 `hover: hover` 且 `pointer: fine` 的设备上,鼠标悬浮 Banner 时背景图进入模糊态,鼠标移开恢复清晰。移动端不绑定点击、触摸或聚焦触发的模糊状态,避免误触后状态不可预期。
替代方案是在移动端点击 Banner 后也触发模糊,但用户已确认移动端不额外做点击模糊状态。
### Decision: 二维码体验入口绑定岗位而非 Agent
“立即体验”按钮始终使用当前岗位的二维码,点击打开二维码弹窗。弹窗顶部展示当前岗位名称,中间展示二维码图片,底部展示“扫码添加专属服务助手”。关闭弹窗只关闭遮罩,不改变当前岗位或当前 Agent。
替代方案是将体验入口绑定到具体 Agent,但已确认用户通过岗位渠道活码体验该岗位能力,Agent 卡片只影响展示素材。
### Decision: 方法论模块保持全局
方法论模块位于岗位能力区下方,不随岗位 Tab 切换而变化。步骤支持点击切换;如果实现轻量 autoplay,用户手动点击后暂停 autoplay,避免自动切换打断阅读。
## Risks / Trade-offs
- [Risk] 后端 H5 聚合接口文档中 `media_type` 仅列出 `gif/mp4`,但用户已确认后台还支持图片。→ Mitigation: 本 change 在 H5 契约中要求接受图片、GIF、MP4;实现阶段同步前端契约草案,并把接口差异作为联调确认项。
- [Risk] `icon_url` 在既有 H5 聚合接口示例中未明确出现。→ Mitigation: mock 契约先包含 `icon_url` 以满足 Agent 卡片图标需求;真实接口未提供时前端使用素材缩略或占位降级,并在联调前确认字段。
- [Risk] MP4 带声自动播放受移动浏览器策略限制。→ Mitigation: H5 大素材和卡片素材以可见、可播放、不卡布局为优先;实现阶段采用符合浏览器策略的 `playsinline`、循环播放和失败占位,声音策略以浏览器能力降级。
- [Risk] Tab 或 Agent 数量较多时容易造成移动端横向溢出或文本重叠。→ Mitigation: Tab 固定单行横向滚动,Agent 卡片移动端纵向排列,所有文本设置响应式换行和安全宽度。
## Migration Plan
1. 补充 H5 首页前端契约草案和 mock fixture,覆盖正常数据、无岗位、无 Agent、二维码不可用、素材失败、方法论隐藏和长列表。
2. 以 TDD 实现聚合数据消费、默认岗位/Agent 选择、岗位切换、Agent 选择联动和二维码弹窗。
3. 实现 Banner hover blur、PC 左右结构、移动端上下结构、Tab 横向滚动和素材占位。
4. 实现方法论步骤切换和可选 autoplay 暂停规则。
5. 运行类型检查、测试、构建,并用浏览器验证 PC 与移动端布局和关键交互。
## Open Questions
- H5 聚合接口是否会正式提供 `icon_url` 和图片类型 `media_type=image`;若暂不提供,前端实现阶段需要明确缩略图/占位的最终策略。
- `site_title` 当前文档存在“广联Agent”“广联岗位 Agent”“岗位 Agent 管理后台”等表述差异;H5 实现以接口返回为准,不在前端写死。
## Why
官网配置后台已经在推进岗位展示配置、Agent 展示配置和方法论配置,但 `single-page` 侧还缺少可实现的 H5 官网首页规范。需要在进入 H5 开发前锁定首页模块、数据消费、岗位 Tab 联动、Agent 素材选择、二维码体验入口、Banner hover 效果和 PC/移动端适配规则。
## What Changes
- 新增 H5 官网首页能力,页面从 `GET /api/v1/official-site/home` 聚合数据渲染,不硬编码岗位、Banner、Agent、二维码或方法论内容。
- 首页模块顺序为 Banner、岗位 Tab 与岗位能力区、方法论模块;当无岗位 Tab 时隐藏岗位 Tab 与岗位能力区。
- Banner 默认展示清晰背景图;在支持 hover 的 PC/宽屏设备上鼠标悬浮后展示模糊背景图效果,鼠标移开恢复清晰;移动端不额外做点击或触摸模糊状态。
- 岗位 Tab 由接口返回数据驱动,默认选中第一个岗位;切换岗位后同步切换岗位标题、岗位概述、二维码、Agent 卡片和左侧大 Agent 素材。
- 岗位能力区采用“核心能力”固定标签位置,展示岗位标题、岗位概述、Agent 卡片列表和“立即体验”按钮。
- Agent 卡片从当前岗位的 Agent 列表渲染,展示 Agent 图标、Agent 标题和 Agent 概述;默认选中第一个 Agent,点击卡片后切换选中态,并用该 Agent 的展示素材更新大 Agent 素材。
- “立即体验”按钮打开当前岗位二维码弹窗,二维码来自接口 URL,前端不生成二维码;关闭弹窗不改变当前岗位或 Agent 选中态。
- Agent 展示素材支持图片、GIF 和 MP4;素材加载失败时展示占位。
- 方法论模块为全局模块,不随岗位 Tab 切换而变化,支持步骤切换和可选轻量 autoplay。
- PC/宽屏采用左右结构:左侧大 Agent 素材与“立即体验”,右侧核心能力、岗位标题/概述和 Agent 卡片;移动端采用上下结构并保持 Tab 单行横向滚动。
- 补充 H5 首页 mock 契约、fixture、响应式测试和浏览器验证任务。
## Capabilities
### New Capabilities
- `official-site-h5-home`: 覆盖 H5 官网首页的数据消费、Banner 交互、岗位 Tab 联动、岗位能力区、Agent 卡片选择、二维码弹窗、方法论模块、响应式适配、状态边界和最小 mock 契约。
### Modified Capabilities
- 无。`single-page` 当前没有既有 OpenSpec capabilities,本 change 新增首页展示能力。
## Impact
- 影响 `workspace/agent-admin/single-page` 前端首页路由、组件、状态管理、样式、mock 数据、前端契约草案和测试计划。
- 依赖公开聚合接口 `GET /api/v1/official-site/home` 的字段语义;其中 Agent 素材类型需要支持图片、GIF 和 MP4。
- 不影响 `workspace/agent-admin/web` 管理后台已有 OpenSpec change,不实现后台配置页面。
- 不影响 `workspace/agent-admin/backend` 的真实接口、缓存、数据库或文件上传实现;本 change 只锁定 H5 前端消费契约和可见行为。
- H5 前台不采集任何埋点。
## ADDED Requirements
### Requirement: H5 首页聚合数据消费
H5 官网首页 SHALL 通过公开聚合数据渲染页面内容,不在前端硬编码岗位、Banner、二维码、Agent 卡片或方法论内容。
#### Scenario: 成功加载首页数据
- **WHEN** H5 官网首页加载成功
- **THEN** 页面消费 `GET /api/v1/official-site/home` 返回的聚合数据
- **AND** 页面根据返回数据渲染 Banner、岗位 Tab、岗位能力区和方法论模块
- **AND** 页面不依赖固定岗位枚举或固定 Agent 枚举
#### Scenario: 首页数据加载失败
- **WHEN** H5 首页聚合数据加载失败
- **THEN** 页面展示可恢复的错误状态
- **AND** 页面提供重新加载入口
- **AND** 页面不展示过期或硬编码的岗位内容冒充真实数据
#### Scenario: 首页不采集埋点
- **WHEN** 用户浏览 H5 官网首页、切换岗位、选择 Agent、打开二维码或切换方法论步骤
- **THEN** H5 前台不发送埋点采集请求
### Requirement: H5 Banner 展示与 hover 模糊
H5 官网首页 SHALL 展示接口返回的 Banner 文案和背景图,并只在支持 hover 的 PC/宽屏设备上启用鼠标悬浮模糊背景效果。
#### Scenario: 默认展示清晰 Banner
- **WHEN** Banner 模块渲染
- **THEN** 页面展示接口返回的标题、副标题和背景图
- **AND** 背景图默认保持清晰可读
#### Scenario: PC hover 后背景模糊
- **WHEN** 用户在支持 hover 且精细指针的设备上将鼠标悬浮到 Banner
- **THEN** Banner 背景图展示模糊效果
- **AND** Banner 文案保持清晰可读
#### Scenario: PC 鼠标移开恢复清晰
- **WHEN** Banner 背景处于 hover 模糊状态且用户将鼠标移出 Banner
- **THEN** Banner 背景图恢复清晰
#### Scenario: 移动端不触发点击模糊
- **WHEN** 用户在移动端点击、触摸或滑过 Banner
- **THEN** Banner 不进入额外的点击模糊状态
- **AND** Banner 背景保持默认清晰展示
#### Scenario: Banner 背景缺失
- **WHEN** 接口未返回可用 Banner 背景图或背景图加载失败
- **THEN** 页面展示可读的背景占位
- **AND** 标题和副标题仍保持可读
### Requirement: 岗位 Tab 数据驱动与切换
H5 官网首页 SHALL 根据接口返回的岗位 Tab 渲染导航,并在切换岗位时同步切换岗位相关内容。
#### Scenario: 展示岗位 Tab
- **WHEN** 接口返回一个或多个岗位 Tab
- **THEN** 页面展示岗位 Tab 导航
- **AND** 默认选中第一个岗位 Tab
- **AND** 当前岗位能力区展示第一个岗位的数据
#### Scenario: 切换岗位 Tab
- **WHEN** 用户点击非当前岗位 Tab
- **THEN** 页面将该岗位设置为当前岗位
- **AND** 岗位标题、岗位概述、二维码、Agent 卡片列表和大 Agent 素材同步切换为该岗位数据
- **AND** 当前选中 Agent 重置为该岗位第一个 Agent
#### Scenario: 无岗位 Tab
- **WHEN** 接口返回岗位 Tab 数量为 `0`
- **THEN** 页面不展示岗位 Tab 导航
- **AND** 页面不展示岗位能力区
- **AND** 方法论模块仍按接口配置独立渲染
#### Scenario: 岗位 Tab 过多
- **WHEN** 岗位 Tab 总宽度超过视口或容器宽度
- **THEN** Tab 导航保持单行横向滚动
- **AND** Tab 不换行
- **AND** Tab 文案不与相邻内容重叠
### Requirement: 岗位能力区内容结构
H5 官网首页 SHALL 在当前岗位能力区展示当前岗位的大 Agent 素材、体验入口、核心能力标签、岗位标题、岗位概述和 Agent 卡片。
#### Scenario: 展示当前岗位能力区
- **WHEN** 当前岗位存在
- **THEN** 页面展示当前选中 Agent 的大素材
- **AND** 页面展示 `立即体验` 按钮
- **AND** 页面在固定位置展示 `核心能力` 标签
- **AND** 页面展示当前岗位的岗位标题
- **AND** 页面展示当前岗位的岗位概述
- **AND** 页面展示当前岗位的 Agent 卡片列表
#### Scenario: 岗位标题和概述映射
- **WHEN** 页面渲染当前岗位内容
- **THEN** 岗位标题使用后台新增或编辑岗位展示配置中的岗位标题字段
- **AND** 岗位概述使用后台新增或编辑岗位展示配置中的岗位说明字段
#### Scenario: 当前岗位无 Agent
- **WHEN** 当前岗位没有可展示 Agent
- **THEN** 页面展示 Agent 素材占位
- **AND** 页面不展示错误的默认 Agent 信息
- **AND** `立即体验` 仍按当前岗位二维码可用性展示
### Requirement: Agent 卡片展示与选择联动
H5 官网首页 SHALL 将当前岗位下的 Agent 卡片作为可选择项,并用选中 Agent 的素材驱动大 Agent 素材展示。
#### Scenario: 默认选中第一个 Agent
- **WHEN** 当前岗位存在一个或多个 Agent 卡片
- **THEN** 页面默认选中第一个 Agent 卡片
- **AND** 大 Agent 素材展示第一个 Agent 的素材内容
#### Scenario: 点击 Agent 卡片切换选中项
- **WHEN** 用户点击当前岗位下未选中的 Agent 卡片
- **THEN** 页面将该卡片设置为选中状态
- **AND** 大 Agent 素材切换为该 Agent 的素材内容
- **AND** 岗位标题、岗位概述和二维码不因 Agent 切换而改变
#### Scenario: Agent 卡片内容
- **WHEN** 页面渲染 Agent 卡片
- **THEN** 每张卡片展示 Agent 图标
- **AND** 每张卡片展示 Agent 标题
- **AND** 每张卡片展示 Agent 概述
#### Scenario: Agent 字段映射
- **WHEN** 页面消费 Agent 卡片数据
- **THEN** Agent 标题优先使用 `speech_title`
- **AND** Agent 概述优先使用 `speech_content`
- **AND** Agent 图标优先使用 `icon_url`
- **AND** 大 Agent 素材使用 `media_url` 和 `media_type`
#### Scenario: Agent 图标缺失
- **WHEN** Agent 未返回可用图标或图标加载失败
- **THEN** 卡片展示图标占位
- **AND** 卡片标题和概述仍保持可读
### Requirement: Agent 素材展示
H5 官网首页 SHALL 支持图片、GIF 和 MP4 作为 Agent 展示素材,并在素材不可用时展示占位。
#### Scenario: 展示图片素材
- **WHEN** 当前选中 Agent 的 `media_type` 为图片类型
- **THEN** 大 Agent 素材区域展示该图片
#### Scenario: 展示 GIF 素材
- **WHEN** 当前选中 Agent 的 `media_type` 为 GIF
- **THEN** 大 Agent 素材区域展示该 GIF
- **AND** 素材可循环播放
#### Scenario: 展示 MP4 素材
- **WHEN** 当前选中 Agent 的 `media_type` 为 MP4
- **THEN** 大 Agent 素材区域展示该视频
- **AND** 视频支持内联播放
- **AND** 视频在浏览器允许时循环播放
#### Scenario: 素材加载失败
- **WHEN** 当前选中 Agent 的素材 URL 缺失、格式不支持或加载失败
- **THEN** 大 Agent 素材区域展示素材占位
- **AND** 页面布局不发生明显跳动或重叠
### Requirement: 岗位二维码体验弹窗
H5 官网首页 SHALL 通过当前岗位的二维码提供体验入口,二维码由接口图片 URL 渲染,前端不生成二维码。
#### Scenario: 打开二维码弹窗
- **WHEN** 用户点击当前岗位能力区的 `立即体验`
- **THEN** 页面打开二维码弹窗
- **AND** 弹窗顶部展示当前岗位名称
- **AND** 弹窗中间展示当前岗位二维码图片
- **AND** 弹窗底部展示 `扫码添加专属服务助手`
#### Scenario: 关闭二维码弹窗
- **WHEN** 用户关闭二维码弹窗
- **THEN** 页面回到关闭前的首页状态
- **AND** 当前岗位 Tab 不改变
- **AND** 当前选中 Agent 不改变
#### Scenario: 二维码不可用
- **WHEN** 当前岗位二维码 URL 缺失、状态不可用或图片加载失败
- **THEN** 页面展示二维码不可用提示
- **AND** 页面不在前端生成替代二维码
### Requirement: 方法论模块
H5 官网首页 SHALL 在岗位能力区下方展示全局方法论模块,并保持其内容不随岗位 Tab 切换而变化。
#### Scenario: 展示方法论模块
- **WHEN** 接口返回方法论为展示状态且包含步骤
- **THEN** 页面在岗位能力区下方展示方法论主标题和副标题
- **AND** 页面展示方法论步骤导航
- **AND** 页面展示当前步骤的图片或流程图
#### Scenario: 切换岗位不影响方法论
- **WHEN** 用户切换岗位 Tab
- **THEN** 方法论模块内容保持不变
- **AND** 方法论当前步骤不因岗位切换而重置
#### Scenario: 点击方法论步骤
- **WHEN** 用户点击非当前方法论步骤
- **THEN** 页面切换为该步骤内容
- **AND** 步骤图片或流程图同步切换
#### Scenario: 方法论隐藏
- **WHEN** 接口返回方法论为隐藏状态或没有可展示步骤
- **THEN** 页面不展示方法论模块
#### Scenario: 方法论 autoplay 暂停
- **WHEN** 页面实现方法论轻量 autoplay 且用户手动点击步骤
- **THEN** autoplay 暂停
- **AND** 页面保持用户选择的步骤内容
### Requirement: PC 与移动端响应式适配
H5 官网首页 SHALL 使用同一套数据状态适配 PC/宽屏和移动端布局,保证内容不重叠、不溢出且关键交互可用。
#### Scenario: PC 宽屏布局
- **WHEN** 页面在 PC 或宽屏视口展示
- **THEN** 岗位能力区采用左右结构
- **AND** 左侧展示大 Agent 素材和 `立即体验`
- **AND** 右侧展示 `核心能力`、岗位标题、岗位概述和 Agent 卡片列表
#### Scenario: 移动端布局
- **WHEN** 页面在移动端视口展示
- **THEN** 岗位能力区采用上下结构
- **AND** Tab 导航保持单行横向滚动
- **AND** 大 Agent 素材和 `立即体验` 展示在核心能力内容之前
- **AND** Agent 卡片以纵向列表展示
#### Scenario: 二维码弹窗移动端适配
- **WHEN** 用户在移动端打开二维码弹窗
- **THEN** 弹窗在安全边距内居中展示
- **AND** 二维码图片完整可见
- **AND** 关闭入口可点击
#### Scenario: 文本和控件不重叠
- **WHEN** 页面在主流手机宽度、平板宽度和 PC 宽度展示
- **THEN** 标题、岗位 Tab、按钮、卡片和弹窗文本不互相遮挡
- **AND** 长文案按容器宽度换行或截断
- **AND** 布局不出现横向页面滚动
### Requirement: H5 首页最小 mock 契约
H5 首页 SHALL 提供支撑本地开发和测试的最小 mock 契约与 fixture,且不锁定后端实现。
#### Scenario: 首页 mock 根字段
- **WHEN** 本地开发或测试加载 H5 首页 mock
- **THEN** mock 包含 `site_title`
- **AND** mock 包含 `site_subtitle`
- **AND** mock 包含 `background_image`
- **AND** mock 包含 `tabs`
- **AND** mock 包含 `methodology`
#### Scenario: 岗位 Tab mock 字段
- **WHEN** 页面消费岗位 Tab mock
- **THEN** 每个 Tab 包含 `tab_id`、`position_code`、`position_name`、`main_title`、`sub_title`、`qrcode_url`、`qrcode_status` 和 `agents`
#### Scenario: Agent mock 字段
- **WHEN** 页面消费 Agent mock
- **THEN** 每个 Agent 包含 `agent_id`、`agent_name`、`icon_url`、`media_url`、`media_type`、`speech_title`、`speech_content` 和 `status`
- **AND** `media_type` 能表达图片、GIF 和 MP4
#### Scenario: 方法论 mock 字段
- **WHEN** 页面消费方法论 mock
- **THEN** 方法论包含 `display_status`、`main_title`、`sub_title` 和 `steps`
- **AND** 每个步骤包含 `step_icon`、`step_name` 和 `step_image`
#### Scenario: 状态 fixtures
- **WHEN** 测试或本地开发需要覆盖 H5 首页状态
- **THEN** mock 提供正常首页、无岗位、无 Agent、二维码不可用、Banner 图片失败、Agent 图标失败、Agent 素材失败、方法论隐藏、岗位 Tab 过多、Agent 过多和加载失败 fixtures
## 1. 契约与 Mock 准备
- [ ] 1.1 更新 H5 首页前端契约草案,补齐 `GET /api/v1/official-site/home` 的 Banner、岗位 Tab、二维码、Agent、方法论字段,并明确 `media_type` 支持图片、GIF 和 MP4。
- [ ] 1.2 补充页面级 mock 类型和 fixture,覆盖正常首页、无岗位、无 Agent、二维码不可用、Banner 图片失败、Agent 图标失败、Agent 素材失败、方法论隐藏、岗位 Tab 过多、Agent 过多和加载失败。
- [ ] 1.3 先编写 mock 契约测试,验证默认数据可驱动 Banner、岗位 Tab、岗位能力区、Agent 卡片、二维码弹窗和方法论模块。
## 2. 首页数据与基础状态
- [ ] 2.1 先编写首页数据加载测试,覆盖成功加载、加载失败、重新加载和不使用硬编码岗位内容。
- [ ] 2.2 实现 H5 首页聚合数据加载、加载中、加载失败和重新加载状态。
- [ ] 2.3 实现当前岗位状态:有岗位时默认选择第一个岗位,无岗位时隐藏岗位 Tab 和岗位能力区。
- [ ] 2.4 实现当前 Agent 状态:当前岗位有 Agent 时默认选择第一个 Agent,岗位切换时重置为新岗位第一个 Agent。
## 3. Banner 模块
- [ ] 3.1 先编写 Banner 渲染测试,覆盖接口标题、副标题、背景图和背景图缺失占位。
- [ ] 3.2 实现 Banner 默认清晰背景图、标题、副标题和可读占位。
- [ ] 3.3 先编写 Banner hover 测试或样式断言,覆盖支持 hover 设备悬浮模糊、鼠标移开恢复。
- [ ] 3.4 实现 PC/宽屏 hover 模糊效果,并确保移动端点击或触摸不触发模糊状态。
## 4. 岗位 Tab 与岗位能力区
- [ ] 4.1 先编写岗位 Tab 测试,覆盖默认选中第一个岗位、切换岗位同步内容、Tab 多时横向滚动且不换行。
- [ ] 4.2 实现接口驱动的岗位 Tab 导航、选中态、切换逻辑和无岗位隐藏逻辑。
- [ ] 4.3 先编写岗位能力区渲染测试,覆盖 `核心能力` 固定标签、岗位标题、岗位概述、大 Agent 素材和 `立即体验` 按钮。
- [ ] 4.4 实现岗位能力区内容结构,并将岗位标题映射到 `main_title`、岗位概述映射到 `sub_title`。
## 5. Agent 卡片与素材联动
- [ ] 5.1 先编写 Agent 卡片测试,覆盖图标、标题、概述、默认选中第一个 Agent 和选中态。
- [ ] 5.2 实现 Agent 卡片列表,字段映射到 `icon_url`、`speech_title`、`speech_content`,并提供图标失败占位。
- [ ] 5.3 先编写 Agent 选择联动测试,覆盖点击卡片后大 Agent 素材切换,岗位标题、岗位概述和二维码不变。
- [ ] 5.4 实现 Agent 卡片点击选择、大 Agent 素材联动和当前岗位无 Agent 的素材占位。
- [ ] 5.5 实现图片、GIF、MP4 展示素材渲染,覆盖素材缺失、格式不支持和加载失败占位。
## 6. 二维码体验弹窗
- [ ] 6.1 先编写二维码弹窗测试,覆盖点击 `立即体验` 打开弹窗、展示岗位名称、二维码和 `扫码添加专属服务助手` 文案。
- [ ] 6.2 实现二维码弹窗打开、关闭和关闭后保持当前岗位/当前 Agent 状态。
- [ ] 6.3 实现二维码 URL 缺失、状态不可用或图片加载失败时的不可用提示,并确保前端不生成二维码。
## 7. 方法论模块
- [ ] 7.1 先编写方法论模块测试,覆盖展示状态、隐藏状态、步骤导航和步骤图片切换。
- [ ] 7.2 实现全局方法论模块,展示主标题、副标题、步骤导航和当前步骤图片。
- [ ] 7.3 实现岗位 Tab 切换时方法论内容和当前步骤不重置。
- [ ] 7.4 如实现轻量 autoplay,补充测试并实现用户手动点击步骤后暂停 autoplay。
## 8. 响应式布局与视觉适配
- [ ] 8.1 先编写响应式布局测试或组件断言,覆盖 PC 左右结构、移动端上下结构、Tab 单行横向滚动和 Agent 卡片移动端纵向列表。
- [ ] 8.2 实现 PC/宽屏布局:左侧大 Agent 素材与 `立即体验`,右侧 `核心能力`、岗位标题、岗位概述和 Agent 卡片列表。
- [ ] 8.3 实现移动端布局:Tab 后依次展示大 Agent 素材与 `立即体验`、核心能力内容、Agent 卡片纵向列表。
- [ ] 8.4 实现二维码弹窗移动端安全边距、完整二维码展示和可点击关闭入口。
- [ ] 8.5 检查并修复主流手机、平板和 PC 视口下的文本重叠、按钮溢出、横向页面滚动和素材比例问题。
## 9. 验证
- [ ] 9.1 运行 `openspec validate "official-site-h5-home" --strict`。
- [ ] 9.2 实现阶段运行 `npm run typecheck`。
- [ ] 9.3 实现阶段运行 `npm test`。
- [ ] 9.4 实现阶段运行 `npm run build`。
- [ ] 9.5 实现阶段启动本地服务,并用浏览器验证 PC 与移动端 Banner hover、岗位 Tab 切换、Agent 卡片选择、二维码弹窗、方法论切换和响应式布局。
# 岗位Agent管理后台前端地基 # 岗位Agent管理后台前端地基
更新时间:2026-05-18 更新时间:2026-05-20
## 1. 文档定位 ## 1. 文档定位
...@@ -70,6 +70,27 @@ Tailwind CSS 暂不作为本项目已启用能力。后续如业务页面确有 ...@@ -70,6 +70,27 @@ Tailwind CSS 暂不作为本项目已启用能力。后续如业务页面确有
- 当路由守卫、动态菜单、嵌套路由、路由元信息管理等路由治理复杂度明显上升时,再按实际业务需要评估是否拆出 `src/router/`。 - 当路由守卫、动态菜单、嵌套路由、路由元信息管理等路由治理复杂度明显上升时,再按实际业务需要评估是否拆出 `src/router/`。
- 路由结构演进遵循“先抽路由配置/守卫,再调整页面目录”的原则,尽量避免一次性迁移页面和路由两层职责。 - 路由结构演进遵循“先抽路由配置/守卫,再调整页面目录”的原则,尽量避免一次性迁移页面和路由两层职责。
## 5.1 子页面页头与表单骨架规则
适用于各业务模块中的独立子页面,例如新建页、编辑页和其他需要独立承载表单的页面。
- 子页面顶部左侧应展示返回按钮和页面名称,返回按钮默认回到上一个页面或上一次可恢复的列表上下文。
- 子页面顶部右侧应放置主要操作按钮,顺序固定为 `取消` 在前、`保存` 在后。
- `取消` 使用白色按钮样式,`保存` 使用 primary 实色按钮样式。
- 子页面表单主体应居中放置,避免与列表页工具栏、详情抽屉或普通内容页混淆。
- 子页面如需展示只读详情内容,应优先复用同一套页头标准,再根据场景决定是否隐藏保存按钮。
- 如果某个子页面存在特殊业务规则,可以在保持上述页头和操作区标准不变的前提下,对具体字段和校验做差异化处理。
## 5.2 子页面表单字段布局规则
适用于各业务模块中的独立子页面表单,尤其是新建页和编辑页。
- 表单字段采用名称与输入控件左右结构,标签在左、控件在右。
- 文本输入框默认宽度为 `450px`。
- `select`、多选 `select` 和其他同类下拉选择控件默认宽度为 `450px`。
- 如果某个字段需要更宽或更窄的展示,优先在页面级局部调整,但不得破坏同类字段的基础宽度标准。
- 同一子页面内,相同类型的输入控件应尽量保持一致宽度,避免表单视觉节奏不统一。
## 6. 组件使用规则 ## 6. 组件使用规则
- 页面优先使用 `packages/ui` 中已有组件。 - 页面优先使用 `packages/ui` 中已有组件。
...@@ -77,6 +98,24 @@ Tailwind CSS 暂不作为本项目已启用能力。后续如业务页面确有 ...@@ -77,6 +98,24 @@ Tailwind CSS 暂不作为本项目已启用能力。后续如业务页面确有
- 组件能力不足时,先记录缺口和业务场景,再判断是扩展组件 props、增加组合组件,还是只在页面层处理。 - 组件能力不足时,先记录缺口和业务场景,再判断是扩展组件 props、增加组合组件,还是只在页面层处理。
- 组件内部样式由组件负责,业务页面只通过 props、`className`、`style` 或 CSS 变量做受控扩展。 - 组件内部样式由组件负责,业务页面只通过 props、`className`、`style` 或 CSS 变量做受控扩展。
## 6.1 搜索区域规则
- 搜索区域中的名称输入框、下拉框采用左右结构,输入框和下拉框宽度保持一致,均为 `200px`。
- 搜索区域中的下拉框不得被 `label` 包裹,避免选择完成后下拉框无法隐藏。
- 搜索区域中的下拉框必须提供「全部」选项;表单中的下拉框无需提供「全部」选项。
- 表格分页跳转输入框中,用户按下回车后应自动触发页码跳转。
- **搜索列表输入框 placeholder 规范**:
- 单字段搜索:placeholder 格式为 `搜索 + 主字段名称`,例如 `搜索 Agent 名称`、`搜索标签名称`、`搜索活码名称`。
- 多字段搜索:placeholder 格式为 `搜索 + 字段1名称或字段2名称`,例如 Skill 列表可搜索名称或编码,placeholder 为 `搜索 Skill 名称或编码`。
- 列表页搜索输入框的 placeholder 应明确提示用户可搜索的内容,避免使用模糊的「请输入关键词」等泛化文案。
- 表单页、登录页和字段编辑区域的普通表单输入框 placeholder 不受此规则约束,按各自业务场景独立定义。
## 6.2 Markdown 与抽屉内容区边界
- 当前 `packages/ui` 尚未沉淀通用 Markdown 渲染器或统一的代码块样式组件。
- 如业务页面需要展示 Markdown,可先在页面层使用现有容器、文本和代码样式能力完成基础渲染,不把通用 Markdown 能力混进业务 OpenSpec。
- 当前 `Drawer` 组件提供基础浮层承载能力,但未把“内容区独立滚动”抽象成通用组件能力;如果后续多个页面都需要同类能力,再单独提升为地基或基础组件改造。
## 7. 状态与反馈规则 ## 7. 状态与反馈规则
页面探索和实现时必须考虑以下状态: 页面探索和实现时必须考虑以下状态:
......
...@@ -350,10 +350,12 @@ Mock 场景:正常列表、空数据、筛选无结果、下架确认、删除 ...@@ -350,10 +350,12 @@ Mock 场景:正常列表、空数据、筛选无结果、下架确认、删除
| 关联渠道活码 | 下拉单选 | 是 | 仅展示该岗位相关的已启用渠道活码 | | 关联渠道活码 | 下拉单选 | 是 | 仅展示该岗位相关的已启用渠道活码 |
| 渠道编码 | 只读文本 | 否 | 从渠道活码带入 | | 渠道编码 | 只读文本 | 否 | 从渠道活码带入 |
| 承接员工 | 只读文本 | 否 | 从渠道活码带入 | | 承接员工 | 只读文本 | 否 | 从渠道活码带入 |
| 岗位标题 | 文本 | 是 | 字段 `main_title`,最多 30 字,展示在官网 Tab 名称下方,一句话介绍 AI 如何赋能该岗位 |
| 岗位说明 | 文本域 | 是 | 字段 `sub_title`,最多 200 字,展示在官网 Tab 内容区,详细描述 AI 为该岗位带来的价值 |
| Tab 排序 | 数字 | 是 | 0-99,数字越小越靠左 | | Tab 排序 | 数字 | 是 | 0-99,数字越小越靠左 |
| 展示状态 | 开关 | 是 | 展示中/已下架 | | 展示状态 | 开关 | 是 | 展示中/已下架 |
Mock 场景:新建成功、编辑成功、岗位无启用渠道活码、排序超出范围、保存失败。 Mock 场景:新建成功、编辑成功、岗位无启用渠道活码、岗位标题/岗位说明为空、岗位标题/岗位说明超长、排序超出范围、保存失败。
## 页面:Agent 展示配置 ## 页面:Agent 展示配置
......
# 后台交互一致性设计
## 背景
本设计用于 `workspace/agent-admin/web` 的下一项 OpenSpec change,推荐名称为 `admin-interaction-consistency`。
当前后台已经有基础的反馈组件、导航组件、列表页和编辑页,但存在三类跨页面一致性问题:
- 会修改数据的操作没有统一的成功或失败提示,部分页面只在失败时显示局部提示,部分页面成功后直接跳转或关闭弹窗。
- 一级菜单和二级菜单的视觉差异不够明显,二级页面选中时父级所在分组不够清晰。
- 列表搜索输入框的 placeholder 混用 `请输入...` 和 `搜索...`,缺少统一规范。
这些问题都属于后台交互一致性,不改变业务模型和后端契约,但会影响用户确认操作结果、理解导航层级和快速识别搜索入口。
## 目标
- 所有会改变系统数据或页面配置的操作,都有明确的成功或失败提示。
- 重试按重新执行数据或配置操作处理,必须有明确的成功或失败提示。
- 查看、预览等不改变数据的主动操作,成功时不强制提示;失败时必须有明确提示或错误状态。
- 字段校验仍显示在字段附近;全局提示只用于提交结果、操作结果和非字段错误。
- 在组件库 `Navigation` 层增强一级菜单和二级菜单的视觉区分。
- 当二级菜单选中时,父级菜单也能表达“当前所在分组”,但不抢夺二级菜单的主选中状态。
- 列表搜索输入框统一使用 `搜索 + label` 的 placeholder 表达。
- 补充可测试的交互规则,避免后续页面继续产生新的不一致。
## 非目标
- 不重做后台整体视觉风格。
- 不改变菜单信息架构、路由结构或权限规则。
- 不把所有表单 placeholder 都改成 `搜索...`。
- 不用全局提示替代表单字段校验、字段说明、空态、加载失败页、预览失败状态或业务阻断详情。
- 不接入真实后端消息文案体系。
- 不重构所有已有页面状态管理,只在完成一致性目标所需范围内调整。
## 方案
采用推荐方案:基于现有组件库能力补齐应用级反馈入口,在导航组件内统一增强层级样式,并对列表搜索 placeholder 做集中规范。
### 操作反馈
现有组件库已有 `Message` 反馈展示组件,但业务应用缺少统一的消息入口。本次应在后台应用根部或 `AdminShell` 作用域内增加全局消息宿主,并提供页面可调用的消息接口。
操作反馈规则如下:
- 新建、编辑、保存、删除、启用、停用、上传、图片删除、重试等会改变数据、配置或重新执行操作的动作,成功后显示成功提示。
- 上述操作失败时显示失败提示,优先使用接口或 mock 返回的可读错误文案。
- 查看、预览等不改变数据的操作失败时,应展示失败提示或页面内错误状态;成功时不强制打扰用户。
- 保存成功后如果跳转回列表页,应通过一次性的跳转后提示展示成功结果,避免成功消息在跳转时丢失。
- 删除、启用、停用等在当前列表页完成的操作,应在操作完成后直接展示结果提示。
- 上传、图片删除等局部操作应展示操作结果;字段必填、格式错误、尺寸过大等字段级校验仍显示在控件附近。
- 保存中、删除中、启停中应禁用重复提交;全局提示不承担加载态职责。
- 二次确认弹窗仍用于危险或状态切换操作,确认后的结果由全局提示表达。
建议消息默认停留时间沿用现有组件默认值。失败消息允许用户手动关闭;成功消息可自动关闭。
### 菜单层级区分
一级菜单和二级菜单的层级表达应在 `packages/ui` 的 `Navigation` 组件中统一处理,避免各页面临时覆盖样式。
交互与视觉规则如下:
- 一级菜单作为分组入口,字号、字重、间距或背景应比二级菜单更明确。
- 二级菜单作为具体页面入口,应保持更轻量的行高和缩进。
- 二级菜单选中时,二级项保留最强的选中样式。
- 二级菜单选中时,父级一级菜单增加父级激活样式,用于表达所在分组。
- 父级激活样式应弱于二级选中样式,避免用户误以为一级菜单本身是当前页面。
- 折叠、展开、键盘访问和 `aria-current` 行为不得回退。
实现时建议为父级激活状态增加稳定 class,例如 `navigationItemParentActive`,并补充组件测试约束。
### 列表搜索 placeholder
本次仅规范“列表页工具栏中的搜索输入框”。表单输入、登录输入、字段校验、下拉选择等仍保留 `请输入...` 或 `请选择...`。
列表搜索 placeholder 统一为:
- 以 `搜索` 开头。
- 后接当前输入框搜索对象的 label。
- 中文 label 可直接拼接,例如 `搜索标签名称`、`搜索活码名称`。
- 英文或中英混排 label 保留自然空格,例如 `搜索 Agent 名称`、`搜索 Skill 名称或编码`。
首批需要统一的已知列表搜索包括:
- Agent 列表:`搜索 Agent 名称`
- 岗位标签列表:`搜索标签名称`
- 渠道活码列表:`搜索活码名称`
- Skill 列表:`搜索 Skill 名称或编码`
## 测试策略
本变更属于跨页面行为一致性调整,后续实现应默认使用 TDD。
建议测试覆盖:
- 全局消息入口可展示 success、error、warning、info,并能自动关闭或手动关闭。
- 页面保存成功后跳转回列表时,成功提示只展示一次。
- 列表删除、启用、停用成功和失败都有可观察提示。
- 上传、图片删除成功和失败都有可观察提示;字段级校验仍在控件附近。
- 导航组件在二级菜单选中时同时具备二级选中状态和父级激活状态。
- 一级菜单与二级菜单具有可断言的稳定 class 或样式差异。
- 已知列表页搜索 placeholder 均符合 `搜索 + label` 规则。
实现后需要运行:
- `npm run typecheck`
- `npm test`
- `npm run build`
- 必要的浏览器验证,重点查看导航层级、列表搜索区和典型操作提示。
## 验收标准
- 用户完成保存、新建、删除、启用、停用、上传、图片删除、重试等操作后,能看到成功或失败结果。
- 用户触发查看、预览等主动操作失败时,能看到失败提示或错误状态。
- 字段校验不被全局提示替代;用户仍能定位到具体字段问题。
- 跨页面跳转后的保存成功提示不会丢失,也不会重复出现。
- 一级菜单、二级菜单和父级激活状态能被清楚区分。
- 当前二级页面选中时,用户能看出自己所在的一级菜单分组。
- 列表搜索输入框不再出现 `请输入 + label` 的 placeholder。
- 表单输入框、登录输入框和字段校验文案不受列表搜索规范误伤。
## 推荐后续步骤
用户确认本设计文档后,进入 OpenSpec 锁定规范阶段:
1. 使用 change name `admin-interaction-consistency`。
2. 按 OpenSpec 指令创建 `proposal.md`。
3. 创建 `design.md`。
4. 创建或更新相关 capability spec。
5. 创建 `tasks.md`。
6. 经用户确认 OpenSpec artifacts 后,再进入实施计划与 TDD 编码。
## Context
`workspace/agent-admin/web` 已建立 React + TypeScript + Vite 前端基座、后台壳、组件库 Demo、Agent 列表、Skill 列表、岗位标签、官网方法论配置和渠道活码等页面能力。现有基础组件中已有 `Message` 展示组件和 `Navigation` 导航组件,但业务应用还缺少统一消息入口,页面对成功、失败、跳转后反馈和搜索 placeholder 的处理不一致。
本 change 基于 `docs/superpowers/specs/2026-05-22-admin-interaction-consistency-design.md`,进入 OpenSpec 锁定阶段,不编写业务实现代码。
## Goals / Non-Goals
**Goals:**
- 为后台应用提供统一的全局消息宿主和页面可调用的消息接口。
- 统一会修改数据、配置或重新执行操作的成功和失败提示规则。
- 支持保存成功后跳转回列表时展示一次性成功提示。
- 保持字段校验、字段说明、空态、加载失败页和预览失败状态各自职责,不用全局提示替代字段级反馈。
- 在 `Navigation` 组件中增强一级菜单、二级菜单和父级激活状态的视觉区分。
- 统一已知列表页工具栏搜索输入框 placeholder 为 `搜索 + label`。
**Non-Goals:**
- 不重做后台整体视觉风格、菜单信息架构、路由结构或权限规则。
- 不接入真实后端消息文案体系。
- 不把所有表单输入 placeholder 都改成 `搜索...`。
- 不用全局提示替代表单字段校验、业务阻断详情、空态、加载失败页或预览失败状态。
- 不重构所有页面状态管理,只调整完成一致性目标所需的范围。
## Decisions
### Decision: 在应用壳范围提供统一消息入口
后台应用 SHALL 在根部或 `AdminShell` 作用域内挂载全局消息宿主,并暴露页面可调用的消息接口。页面操作完成后只调用统一入口,不在各页面重复实现消息容器。
替代方案是在每个页面局部渲染消息组件。该方案实现快,但容易造成位置、关闭行为、跳转后丢失和测试方式不一致。
### Decision: 跳转后成功提示使用一次性状态传递
新建、编辑、保存等操作成功后如果跳转回列表页,页面 SHALL 使用一次性跳转状态或等价机制展示成功提示。提示展示后必须被消费,刷新或再次进入列表页时不得重复出现。
替代方案是在保存页展示提示后再延迟跳转。该方案会让用户等待,并与现有独立表单页保存后返回列表的工作流不一致。
### Decision: 字段级问题仍留在字段附近
字段必填、格式错误、长度超限、上传尺寸过大等校验 SHALL 继续展示在控件附近。全局消息只表达提交结果、操作结果和非字段错误。
替代方案是所有错误都使用全局消息。该方案会降低定位字段问题的效率,也会让用户难以知道具体需要修正的位置。
### Decision: 导航层级增强沉淀在组件库
一级菜单、二级菜单和父级激活状态 SHALL 在 `packages/ui` 的 `Navigation` 组件内统一表达。二级菜单选中时,二级项保留最强选中态,父级一级菜单仅展示弱一级的父级激活态。
替代方案是在各业务页面或应用壳中写样式覆盖。该方案会让菜单层级视觉分散,后续新增菜单容易继续不一致。
### Decision: 只规范列表搜索 placeholder
本 change 仅规范列表页工具栏搜索输入框 placeholder,统一为 `搜索 + label`。表单输入、登录输入、字段校验、下拉选择等仍可按语义使用 `请输入...`、`请选择...` 或其他字段提示。
替代方案是全站输入框统一 placeholder。该方案范围过大,容易误伤表单填写场景和既有字段说明。
## Risks / Trade-offs
- [Risk] 当前 active OpenSpec change 或页面实现中可能仍有 `请输入 + label` 的列表搜索文案。→ Mitigation: 实施任务中显式检查并同步更新受影响 artifacts、测试和页面。
- [Risk] 全局消息入口若与路由跳转耦合不当,可能出现提示丢失或重复展示。→ Mitigation: 为跳转后提示补充一次性展示测试。
- [Risk] 父级激活样式过强会让用户误以为一级菜单是当前页面。→ Mitigation: specs 中要求父级激活弱于二级选中,并提供稳定 class 供测试断言。
- [Risk] 操作反馈过多可能打扰用户。→ Mitigation: 查看、预览等非修改操作成功时不强制提示,仅失败时提示或展示错误状态。
## Migration Plan
1. 补充全局消息入口和跳转后一次性消息测试。
2. 实现应用壳范围的消息宿主与页面调用方式。
3. 按 TDD 补齐典型保存、删除、启停、上传、图片删除、重试的成功和失败提示。
4. 更新 `Navigation` 组件测试和样式,区分一级、二级和父级激活状态。
5. 更新已知列表页搜索 placeholder,并同步修正存在冲突的 active OpenSpec artifacts。
6. 运行类型检查、测试、构建,并在浏览器验证导航、搜索区和典型操作提示。
## Open Questions
- 无。已确认使用 change name `admin-interaction-consistency`。
## Why
后台当前已具备多个管理页面和基础组件,但跨页面操作反馈、导航层级表达和列表搜索 placeholder 存在不一致,容易让用户无法确认操作结果、误读当前菜单层级或识别搜索入口。现在需要在继续扩展业务页面前锁定统一交互规则,避免后续页面继续累积差异。
## What Changes
- 新增后台操作反馈一致性规则:保存、新建、编辑、删除、启用、停用、上传、图片删除、重试等会改变数据或重新执行操作的动作,成功和失败都必须有明确提示。
- 新增跳转后一次性成功提示规则,避免保存成功后返回列表页时提示丢失或重复展示。
- 约定查看、预览等不改变数据的主动操作成功时不强制提示,失败时必须提供全局提示或页面内错误状态。
- 在组件库 `Navigation` 中增强一级菜单、二级菜单和父级激活状态的区分,并保持现有可访问性行为不回退。
- 统一列表页工具栏搜索输入框 placeholder 为 `搜索 + label`,首批覆盖 Agent、岗位标签、渠道活码和 Skill 列表。
- 补充测试和实施任务,覆盖全局消息入口、典型页面操作提示、导航层级样式和已知列表搜索 placeholder。
## Capabilities
### New Capabilities
- `admin-interaction-consistency`: 覆盖后台跨页面操作反馈、跳转后提示、导航层级表达、父级激活状态和列表搜索 placeholder 一致性。
### Modified Capabilities
- 无。本 change 以新的跨页面一致性能力描述规则;若现有 active change 中存在冲突文案,实施时同步更新对应 artifacts 和页面测试。
## Impact
- 影响后台应用根部或 `AdminShell`:需要提供全局消息宿主和页面可调用的消息入口。
- 影响表单页、列表页和上传相关页面:需要在会改变数据或重新执行操作后展示成功或失败提示。
- 影响 `packages/ui` 的 `Navigation` 组件:需要增加父级激活状态和稳定可测试的 class 或状态表达。
- 影响已知列表页搜索区:需要统一搜索输入框 placeholder 文案。
- 影响测试:新增组件测试、页面交互测试和跨路由跳转后消息测试。
## ADDED Requirements
### Requirement: 全局操作反馈入口
后台前端 SHALL 提供统一的全局消息入口,用于展示页面级操作结果,并允许页面触发 success、error、warning 和 info 类型消息。
#### Scenario: 展示成功消息
- **WHEN** 页面通过统一消息入口触发 success 消息
- **THEN** 系统展示成功提示
- **AND** 成功提示可按默认停留时间自动关闭
#### Scenario: 展示失败消息
- **WHEN** 页面通过统一消息入口触发 error 消息
- **THEN** 系统展示失败提示
- **AND** 失败提示允许用户手动关闭
#### Scenario: 应用壳内统一承载消息
- **WHEN** 用户在后台任一页面触发全局消息
- **THEN** 消息由后台应用根部或 `AdminShell` 作用域内的统一宿主展示
- **AND** 页面不需要各自重复渲染独立消息宿主
### Requirement: 修改类操作结果提示
后台前端 SHALL 对会改变数据、配置或重新执行操作的动作展示明确的成功或失败提示。
#### Scenario: 保存成功后提示
- **WHEN** 用户完成新建、编辑或保存操作且 mock 或接口返回成功
- **THEN** 系统展示保存成功提示
#### Scenario: 保存失败后提示
- **WHEN** 用户完成新建、编辑或保存操作且 mock 或接口返回失败
- **THEN** 系统展示保存失败提示
- **AND** 优先使用 mock 或接口返回的可读错误文案
#### Scenario: 删除成功或失败后提示
- **WHEN** 用户确认删除并且删除操作完成
- **THEN** 系统按操作结果展示删除成功或删除失败提示
#### Scenario: 启用或停用成功失败后提示
- **WHEN** 用户确认启用或停用并且操作完成
- **THEN** 系统按操作结果展示启用、停用成功或失败提示
#### Scenario: 上传和图片删除结果提示
- **WHEN** 用户完成上传或图片删除操作
- **THEN** 系统按操作结果展示成功或失败提示
- **AND** 字段必填、格式错误和尺寸过大等字段级问题仍展示在控件附近
#### Scenario: 重试结果提示
- **WHEN** 用户触发重试并且重试重新执行数据或配置操作
- **THEN** 系统按重试结果展示成功或失败提示
#### Scenario: 操作中禁止重复提交
- **WHEN** 保存、删除、启用、停用、上传、图片删除或重试操作正在执行
- **THEN** 对应触发控件进入不可重复提交状态
- **AND** 全局提示不承担加载态职责
### Requirement: 跳转后一次性成功提示
后台前端 SHALL 在保存成功后跳转回列表页时保留并展示一次性成功提示,且不得重复展示。
#### Scenario: 新建成功返回列表后展示提示
- **WHEN** 用户在独立新建页保存成功并返回列表页
- **THEN** 列表页展示一次新建成功提示
#### Scenario: 编辑成功返回列表后展示提示
- **WHEN** 用户在独立编辑页保存成功并返回列表页
- **THEN** 列表页展示一次编辑成功提示
#### Scenario: 跳转后提示被消费
- **WHEN** 跳转后的成功提示已经展示过
- **THEN** 用户刷新页面或再次进入列表页时系统不重复展示该提示
### Requirement: 非修改类主动操作反馈
后台前端 SHALL 对查看、预览等不改变数据的主动操作按失败优先原则反馈,成功时不强制展示全局提示。
#### Scenario: 查看成功不强制提示
- **WHEN** 用户执行查看操作且内容成功展示
- **THEN** 系统不强制展示全局成功提示
#### Scenario: 预览成功不强制提示
- **WHEN** 用户执行预览操作且内容成功展示
- **THEN** 系统不强制展示全局成功提示
#### Scenario: 查看或预览失败有反馈
- **WHEN** 用户执行查看或预览操作且操作失败
- **THEN** 系统展示失败提示或页面内错误状态
### Requirement: 字段校验与全局提示职责分离
后台前端 SHALL 保持字段级校验在字段附近展示,全局提示仅用于提交结果、操作结果和非字段错误。
#### Scenario: 字段必填错误展示在字段附近
- **WHEN** 用户提交表单且必填字段为空
- **THEN** 系统在对应字段附近展示字段校验信息
- **AND** 系统不使用全局提示替代该字段校验信息
#### Scenario: 非字段错误使用全局提示
- **WHEN** 用户提交表单且 mock 或接口返回非字段错误
- **THEN** 系统通过全局消息入口展示错误提示
### Requirement: 导航菜单层级区分
后台前端 SHALL 在 `Navigation` 组件中清晰区分一级菜单、二级菜单和父级激活状态。
#### Scenario: 一级菜单与二级菜单视觉有差异
- **WHEN** 导航渲染同时包含一级菜单和二级菜单
- **THEN** 一级菜单通过字号、字重、间距或背景与二级菜单形成可辨识差异
- **AND** 二级菜单保持更轻量的行高或缩进表达
#### Scenario: 二级菜单选中时父级激活
- **WHEN** 当前路由命中某个二级菜单
- **THEN** 该二级菜单展示最强选中状态
- **AND** 其父级一级菜单展示父级激活状态
#### Scenario: 父级激活弱于二级选中
- **WHEN** 二级菜单选中且父级一级菜单展示父级激活状态
- **THEN** 父级激活样式弱于二级菜单选中样式
- **AND** 用户不会误以为一级菜单本身是当前页面
#### Scenario: 导航状态可测试
- **WHEN** 二级菜单选中并触发父级激活状态
- **THEN** `Navigation` 提供稳定 class 或状态标记用于测试父级激活
#### Scenario: 导航可访问性不回退
- **WHEN** 导航菜单层级样式增强后
- **THEN** 折叠、展开、键盘访问和 `aria-current` 行为保持可用
### Requirement: 列表搜索 placeholder 规范
后台前端 SHALL 将列表页工具栏搜索输入框 placeholder 统一为 `搜索 + label`,并且不影响普通表单输入框。
#### Scenario: Agent 列表搜索 placeholder
- **WHEN** 用户打开 Agent 列表页
- **THEN** 列表工具栏的 Agent 名称搜索输入框 placeholder 为 `搜索 Agent 名称`
#### Scenario: 岗位标签列表搜索 placeholder
- **WHEN** 用户打开岗位标签列表页
- **THEN** 列表工具栏的标签名称搜索输入框 placeholder 为 `搜索标签名称`
#### Scenario: 渠道活码列表搜索 placeholder
- **WHEN** 用户打开渠道活码列表页
- **THEN** 列表工具栏的活码名称搜索输入框 placeholder 为 `搜索活码名称`
#### Scenario: Skill 列表搜索 placeholder
- **WHEN** 用户打开 Skill 列表页
- **THEN** 列表工具栏的 Skill 搜索输入框 placeholder 为 `搜索 Skill 名称或编码`
#### Scenario: 表单 placeholder 不受误伤
- **WHEN** 用户打开后台表单页、登录页或字段编辑区域
- **THEN** 普通表单输入框仍可按字段语义使用 `请输入...`、`请选择...` 或其他字段提示
## 1. OpenSpec 与冲突对齐
- [x] 1.1 检查 active OpenSpec changes 中与本 change 冲突的列表搜索 placeholder 或操作反馈规则。
- [x] 1.2 若发现冲突,先同步更新受影响的 active OpenSpec artifacts 与 `tasks.md`,再进入对应代码实现。
- [x] 1.3 运行 `openspec validate admin-interaction-consistency --strict`,确认本 change artifacts 通过校验。
## 2. 全局消息入口
- [x] 2.1 先编写全局消息入口测试,覆盖 success、error、warning、info 展示、自动关闭和手动关闭。
- [x] 2.2 在后台应用根部或 `AdminShell` 作用域内实现统一消息宿主。
- [x] 2.3 提供页面可调用的消息接口,避免各页面重复渲染独立消息宿主。
## 3. 操作反馈一致性
- [x] 3.1 先编写跳转后一次性成功提示测试,覆盖新建和编辑保存成功后返回列表只提示一次。
- [x] 3.2 实现保存成功后跳转回列表的一次性成功提示机制。
- [x] 3.3 先编写典型列表操作测试,覆盖删除、启用、停用成功和失败提示。
- [x] 3.4 实现删除、启用、停用等当前列表页操作的成功和失败提示。
- [x] 3.5 先编写上传、图片删除和重试测试,覆盖成功、失败、字段级校验不被全局提示替代。
- [x] 3.6 实现上传、图片删除和重试的操作结果提示,并保持操作中不可重复提交。
- [x] 3.7 确认查看、预览等非修改类操作成功时不强制提示,失败时有全局提示或页面内错误状态。
## 4. 导航层级一致性
- [x] 4.1 先编写 `Navigation` 组件测试,覆盖一级菜单、二级菜单、二级选中、父级激活和 `aria-current` 行为。
- [x] 4.2 在 `packages/ui` 的 `Navigation` 组件中增加父级激活状态和稳定 class 或状态标记。
- [x] 4.3 调整导航样式,使一级菜单、二级菜单和父级激活状态可清楚区分,且父级激活弱于二级选中。
- [x] 4.4 验证折叠、展开和键盘访问行为不回退。
## 5. 列表搜索 placeholder
- [x] 5.1 先编写或更新 Agent、岗位标签、渠道活码和 Skill 列表搜索 placeholder 测试。
- [x] 5.2 将 Agent 列表搜索 placeholder 统一为 `搜索 Agent 名称`。
- [x] 5.3 将岗位标签列表搜索 placeholder 统一为 `搜索标签名称`。
- [x] 5.4 将渠道活码列表搜索 placeholder 统一为 `搜索活码名称`。
- [x] 5.5 将 Skill 列表搜索 placeholder 统一为 `搜索 Skill 名称或编码`。
- [x] 5.6 础认表单页、登录页和字段编辑区域的普通表单 placeholder 未被误改。
## 6. 验证
- [x] 6.1 运行相关组件和页面测试。
- [x] 6.2 运行 `npm run typecheck`。
- [x] 6.3 运行 `npm test`。
- [x] 6.4 运行 `npm run build`。
- [x] 6.5 使用浏览器验证导航层级、列表搜索区、保存后提示、列表操作提示和典型失败反馈。
- [x] 6.6 确认代码、测试和 OpenSpec 对齐后,再进入归档阶段。
# UI Component Fixes Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 在 `agent-admin` 内将 `packages/ui` 的 `Select`、文件上传、图片上传迁移为 `tdesign-react` 薄封装,并保持页面侧只做必要兼容调整。
**Architecture:** 页面继续从 `packages/ui` 导入组件,`packages/ui` 内部使用 `tdesign-react` 原生组件和 props 语义。实施时不兼容旧自定义 API、不新增额外包装属性、不重构无关页面结构或业务逻辑。
**Tech Stack:** React 19、TypeScript、Vite、Vitest、Testing Library、tdesign-react。
---
### Task 1: 依赖与样式接入
**Files:**
- Modify: `/Users/yuehu/Desktop/work/agent/workspace/agent-admin/web/package.json`
- Modify: `/Users/yuehu/Desktop/work/agent/workspace/agent-admin/web/package-lock.json`
- Inspect: `/Users/yuehu/Desktop/work/agent/workspace/agent-admin/web/src/main.tsx`
- [ ] **Step 1: 安装依赖**
Run: `rtk npm install tdesign-react@1.17.0`
Expected: `package.json` 和 `package-lock.json` 增加 `tdesign-react` 相关依赖。
- [ ] **Step 2: 确认样式入口**
检查 `src/main.tsx`,如果项目没有集中引入组件库样式,则添加 `import 'tdesign-react/es/style/index.css';`。不要在业务页面重复引入。
- [ ] **Step 3: 运行最小验证**
Run: `rtk npm run typecheck`
Expected: 当前若因尚未改组件产生类型错误,记录错误并进入后续任务;不要修改无关文件。
### Task 2: Select 薄封装
**Files:**
- Modify: `/Users/yuehu/Desktop/work/agent/workspace/agent-admin/web/packages/ui/src/components/Select.tsx`
- Modify: `/Users/yuehu/Desktop/work/agent/workspace/agent-admin/web/packages/ui/src/components/selection-date-table.test.tsx`
- Modify: `/Users/yuehu/Desktop/work/agent/workspace/agent-admin/web/src/routes/agents/AgentEditorPage.tsx`
- [ ] **Step 1: 写失败测试**
更新 `selection-date-table.test.tsx`,让多选测试验证原生标签态,不再传 `multipleDisplay` 或 `multipleTagClosable`。
Run: `rtk npm test -- packages/ui/src/components/selection-date-table.test.tsx`
Expected: 由于当前 `Select` 仍是自建 summary/tags 分支,测试应在原生标签态断言处失败。
- [ ] **Step 2: 实现最小封装**
将 `Select.tsx` 改为包装 `tdesign-react` 的 `Select`,只保留当前页面需要的 `options`、`value`、`onChange`、`multiple`、`placeholder`、`allowClear`、`disabled`、`className`、`aria-label` 等通用字段。不要保留 `multipleDisplay`、`multipleTagClosable`。
- [ ] **Step 3: 页面最小适配**
移除 `AgentEditorPage.tsx` 中传给 `Select` 的 `multipleDisplay="tags"` 和 `multipleTagClosable={false}`,不调整无关表单逻辑。
- [ ] **Step 4: 跑 Select 测试**
Run: `rtk npm test -- packages/ui/src/components/selection-date-table.test.tsx`
Expected: Select 相关测试通过;如果 TreeSelect/Date/Table 旧断言受同文件影响,只调整与 Select DOM 变化直接相关的断言。
### Task 3: 上传组件薄封装
**Files:**
- Modify: `/Users/yuehu/Desktop/work/agent/workspace/agent-admin/web/packages/ui/src/components/Upload.tsx`
- Modify: `/Users/yuehu/Desktop/work/agent/workspace/agent-admin/web/packages/ui/src/components/upload.test.tsx`
- Modify: `/Users/yuehu/Desktop/work/agent/workspace/agent-admin/web/src/routes/components/ComponentsDemoPage.tsx`
- [ ] **Step 1: 写失败测试**
更新 `upload.test.tsx`,将文件状态输入改为 `success`、`progress`、`fail`、`waiting`,并验证文件上传仍能触发选择、预览、下载、删除、重试、取消意图。
Run: `rtk npm test -- packages/ui/src/components/upload.test.tsx`
Expected: 当前类型或断言因旧枚举 `done/uploading/error` 失败。
- [ ] **Step 2: 实现文件上传封装**
将 `UploadDragger` 改为基于 `tdesign-react` 的上传能力,`UploadFileStatus` 使用 `success | fail | progress | waiting`。保留当前页面已用回调语义,不添加旧状态别名。
- [ ] **Step 3: 实现图片上传封装**
将 `MediaWall` 改为基于 `tdesign-react` 图片上传列表能力。预览和删除使用组件默认操作,不实现“点击预览后删除确认”的业务逻辑。
- [ ] **Step 4: 更新 Demo 数据**
将 `ComponentsDemoPage.tsx` 中示例文件状态从 `done/uploading/error` 改为 `success/progress/fail`。
- [ ] **Step 5: 跑上传测试**
Run: `rtk npm test -- packages/ui/src/components/upload.test.tsx`
Expected: 上传组件测试通过。
### Task 4: 页面兼容与业务测试
**Files:**
- Modify: `/Users/yuehu/Desktop/work/agent/workspace/agent-admin/web/src/routes/official-site/OfficialSiteMethodologyPage.tsx`
- Modify: `/Users/yuehu/Desktop/work/agent/workspace/agent-admin/web/src/routes/official-site/OfficialSiteMethodologyUploadSave.test.tsx`
- Modify if needed: `/Users/yuehu/Desktop/work/agent/workspace/agent-admin/web/src/routes/agents/AgentEditorFlow.test.tsx`
- [ ] **Step 1: 写失败测试**
更新 `OfficialSiteMethodologyUploadSave.test.tsx`,移除“预览即删除确认”的断言,改为通过删除按钮触发删除,通过预览按钮只验证预览意图或默认预览入口存在。
Run: `rtk npm test -- src/routes/official-site/OfficialSiteMethodologyUploadSave.test.tsx`
Expected: 当前页面仍把预览当删除时,测试失败。
- [ ] **Step 2: 页面最小适配**
移除 `OfficialSiteMethodologyPage.tsx` 中与 `tdesign-react` 默认预览、删除冲突的自定义逻辑,只保留文件校验、mock 上传、保存草稿等业务逻辑。
- [ ] **Step 3: 跑页面测试**
Run: `rtk npm test -- src/routes/official-site/OfficialSiteMethodologyUploadSave.test.tsx src/routes/agents/AgentEditorFlow.test.tsx`
Expected: 受影响页面测试通过。
### Task 5: 验证与 OpenSpec 收尾
**Files:**
- Modify: `/Users/yuehu/Desktop/work/agent/workspace/agent-admin/web/openspec/changes/ui-component-fixes/tasks.md`
- [ ] **Step 1: 运行类型检查**
Run: `rtk npm run typecheck`
Expected: 通过。
- [ ] **Step 2: 运行测试**
Run: `rtk npm test`
Expected: 通过。
- [ ] **Step 3: 运行构建**
Run: `rtk npm run build`
Expected: 通过。
- [ ] **Step 4: 浏览器验证**
启动开发服务并在浏览器检查 Agent 编辑页 Select、多选标签、组件 Demo 文件上传、官网方法论图片上传预览/删除。
- [ ] **Step 5: 更新任务状态**
将 `openspec/changes/ui-component-fixes/tasks.md` 中已完成项勾选。不要归档,等用户确认代码、测试和规范都对齐后再归档。
# 岗位标签管理设计稿
## 背景
本设计用于 OpenSpec change `agent-tags-management` 的 Superpowers 探索阶段。前置的“登录 + 管理后台框架 + Agent 管理列表页 + mock 最小契约”和 `skill-list-markdown-drawer` 已完成并归档;`agent-create-edit-detail` 仍在修复中,本次不修改其范围。
本次只做岗位标签自身管理,新增 `/agent-tags` 相关页面、最小前端 mock 契约和可测试 fixture。渠道活码、官网配置、Agent 表单联动不在本次范围内。
## 目标
- 新增岗位标签管理列表页 `/agent-tags`。
- 新增独立新建页 `/agent-tags/new`,不使用列表页弹窗或抽屉承载完整表单。
- 新增独立编辑页 `/agent-tags/:tagId/edit`,标签编码只读。
- 列表支持搜索标签名称。
- 列表展示标签名称、标签编码、标签描述、使用 Agent 数、关联渠道活码数、关联官网 Tab 数、创建时间、操作。
- 支持新建、编辑、删除岗位标签,删除前按引用检查结果处理 Agent 确认解除、渠道活码阻断和官网 Tab 阻断。
- 补充本页面所需的最小前端 mock 契约和 mock fixture,不锁定后端实现。
- 搜索区、表格、分页、表单、状态组件遵循 `frontend-foundation.md` 既有规则。
## 非目标
- 不实现渠道活码管理页、官网配置页或关联配置能力。
- 不实现 Agent 新建/编辑表单里的岗位标签联动。
- 不改动 `agent-create-edit-detail` OpenSpec 的页面范围或实现范围。
- 不扩展基础组件体系;如果发现 `frontend-foundation.md` 存在缺口,只记录为后续 foundation OpenSpec 候选。
- 不固化数据库结构;删除引用检查对齐既有前端契约 `frontend-api-contract.md` 的 `### 5.4 检查岗位标签引用`。
## 页面结构
### 管理入口
- 导航位置:建议挂在 `Agent管理` 下,菜单名为 `岗位标签管理`。
- 面包屑:
- `/agent-tags`:`Agent管理 / 岗位标签管理`
- `/agent-tags/new`:`Agent管理 / 岗位标签管理 / 新建岗位标签`
- `/agent-tags/:tagId/edit`:`Agent管理 / 岗位标签管理 / 编辑岗位标签`
### 列表页 `/agent-tags`
- 页面类型:列表页。
- 顶部标题:`岗位标签管理`。
- 主要操作:页面头部右上角放置 `新建岗位标签`,跳转 `/agent-tags/new`。
- 搜索区:
- 字段:`标签名称`。
- 输入框宽度遵循 `frontend-foundation.md` 的搜索区规则,使用 `200px`。
- placeholder:`请输入标签名称`。
- 点击 `搜索` 或在输入框回车后按标签名称搜索。
- 点击 `重置` 清空标签名称并回到第一页。
- 表格列:
- `标签名称`
- `标签编码`
- `标签描述`
- `使用 Agent 数`
- `关联渠道活码数`
- `关联官网 Tab 数`
- `创建时间`
- `操作`
- 操作列:
- `编辑`:跳转 `/agent-tags/:tagId/edit`。
- `删除`:按删除规则处理。
- 分页:
- 复用现有分页组件和页码跳转规则。
- 搜索后回到第一页。
### 新建页 `/agent-tags/new`
- 页面类型:独立表单页。
- 页头左侧:返回按钮和标题 `新建岗位标签`。
- 页头右侧:主要操作按钮固定为 `取消`、`保存`,`取消` 在前、`保存` 在后。
- 表单字段:
- `标签名称`:必填,最多 20 字。
- `标签编码`:必填,仅支持英文和下划线,不可重复。
- `标签描述`:选填,最多 100 字。
- 操作:
- 页头右上角 `保存`:通过前端校验后调用 mock 保存;成功后返回列表页。
- 页头右上角 `取消`:返回列表页,不保存。
- 说明:
- 标签编码在新建时录入并生成,生成后不可修改;因此新建页可编辑,编辑页只读。
### 编辑页 `/agent-tags/:tagId/edit`
- 页面类型:独立表单页。
- 页头左侧:返回按钮和标题 `编辑岗位标签`。
- 页头右侧:主要操作按钮固定为 `取消`、`保存`,`取消` 在前、`保存` 在后。
- 数据来源:不新增岗位标签详情接口;从列表点击 `编辑` 时优先通过路由 state 携带当前行数据初始化表单,刷新或直接访问编辑 URL 时再从岗位标签列表 mock 数据源中按 `tagId` 查找当前记录。两种路径都只使用列表项里的 `name`、`code`、`description` 初始化表单。
- 表单字段:
- `标签名称`:必填,最多 20 字。
- `标签编码`:只读展示,不允许修改。
- `标签描述`:选填,最多 100 字。
- 操作:
- 页头右上角 `保存`:通过前端校验后调用 mock 保存;成功后返回列表页。
- 页头右上角 `取消`:返回列表页,不保存。
- 状态:
- 列表 mock 数据源加载失败时展示错误状态和重试入口。
- 未找到标签时展示空/错误状态,避免进入空白表单。
## 校验与错误
- 标签名称为空:提示 `请输入标签名称`。
- 标签名称超过 20 字:提示 `标签名称最多20字`。
- 标签编码为空:提示 `请输入标签编码`。
- 标签编码格式错误:提示 `标签编码仅支持英文和下划线`。
- 标签编码重复:提示 `标签编码已存在`。
- 标签描述超过 100 字:提示 `标签描述最多100字`。
- 保存失败:展示 `保存失败,请重试`,停留在当前表单页。
- 列表加载失败:展示加载失败状态和重试入口。
## 删除规则
- 点击删除后先检查岗位标签引用,对齐 `GET /api/v1/position-tags/{tag_id}/references` 的前端契约。
- 当存在 Agent 引用且不存在阻塞引用时,允许继续删除确认,确认文案包含 `删除后这些 Agent 将失去该标签`。
- 当存在渠道活码引用时,不允许删除,提示 `请先删除关联的渠道活码`。
- 当存在官网 Tab 引用时,不允许删除,提示 `请先删除关联的官网 Tab 配置`。
- 当渠道活码或官网 Tab 阻塞引用存在时,即使也存在 Agent 引用,也不进入 Agent 解除确认。
- 以上渠道活码和官网 Tab 引用全部解除后,才允许按无引用或仅 Agent 引用流程继续删除。
- 可删除标签确认后从 mock 数据中移除,并刷新列表状态。
## Mock 契约
本次只补充岗位标签管理页面最小字段和状态,不锁定后端实现。建议在 `packages/contracts/frontend-api-contract.md` 中补充说明,并在相邻 mock 模块中提供可测试 fixture。
本次不定义岗位标签详情接口。编辑页优先使用列表点击时携带的当前行数据,缺少路由 state 时再按 `tagId` 从列表 mock 数据源兜底查找;两种路径都使用列表最小字段作为表单初始数据,避免因前端 mock 锁定后端详情接口形态。
删除前引用检查对齐 `frontend-api-contract.md` 的 `### 5.4 检查岗位标签引用`,mock fixture 需要提供最小 `blocking_references` 和 `detachable_references` 数据,用于区分渠道活码、官网 Tab 的阻塞删除和 Agent 的可确认解除。
最小列表项字段:
```ts
export interface AgentTagListMockItem {
tag_id: number;
name: string;
code: string;
description?: string;
agent_count: number;
channel_code_count: number;
official_tab_count: number;
created_at: string;
}
```
最小查询和表单字段:
```ts
export interface AgentTagListQuery {
keyword?: string;
page: number;
pageSize: number;
}
export interface AgentTagFormPayload {
name: string;
code: string;
description?: string;
}
```
Mock 场景:
- 正常列表。
- 空数据。
- 筛选无结果。
- 编码重复。
- 删除可确认。
- 仅 Agent 引用需确认。
- 被渠道活码引用不可删除。
- 被官网 Tab 引用不可删除。
- 引用检查失败。
- 加载失败。
- 保存失败。
## 测试策略
实现阶段使用 TDD,先补测试再写实现。建议覆盖:
- 列表页渲染字段、搜索、重置、分页和空/错误状态。
- 点击新建跳转独立新建页。
- 点击编辑跳转独立编辑页,且编码只读。
- 新建/编辑表单必填、长度、编码格式、编码重复和保存失败校验。
- 删除前引用检查;无引用时确认删除;仅 Agent 引用时提示 `删除后这些 Agent 将失去该标签`;被渠道活码或官网 Tab 引用时阻断删除;引用检查失败不删除。
- mock fixture 的过滤、分页、重复编码、删除阻断判断。
- 导航菜单和路由注册。
## 验证策略
实现完成后需要运行:
- `npm run typecheck`
- `npm test`
- `npm run build`
- 浏览器验证 `/agent-tags`、`/agent-tags/new`、`/agent-tags/:tagId/edit` 的布局和关键交互。
## 风险与边界
- 删除岗位标签时 Agent 引用按既有引用检查契约作为可解除引用处理,需要用户确认 `删除后这些 Agent 将失去该标签`;但本次仍不实现 Agent 表单联动页面。
- `frontend-api-contract.md` 已存在较宽泛的岗位标签接口草案;本次应以页面 mock 最小契约补充字段和状态,避免把后端接口形态锁死。
- 如果现有基础组件无法满足独立表单页布局或搜索区细节,只记录缺口,不在本 OpenSpec 内扩展组件体系。
# 渠道活码管理设计
## 背景
本设计用于 `workspace/agent-admin/web` 的下一项 OpenSpec change:`channel-code-management`。
当前后台已完成 Agent 列表、岗位标签管理、Skill 目录与官网方法论配置。本次新增「渠道活码管理」能力,服务于员工渠道活码的后台配置、展示、启停与 mock 联调契约。
## 范围
本次推荐采用「完整管理闭环」方案,覆盖:
- 渠道活码列表页 `/channel-codes`
- 新建渠道活码页 `/channel-codes/new`
- 编辑渠道活码页 `/channel-codes/:codeId/edit`
- 查看活码抽屉
- 启用、停用操作及确认
- 路由、导航、面包屑与页面状态
- 列表筛选、分页、空态、错误态
- 表单保存态、校验态、失败态
- mock 契约与 fixture
页面实现需遵循 `docs/frontend-foundation.md` 已确认规则,尤其是子页面页头、表单骨架、字段布局、搜索区「全部」选项、状态反馈和二次确认规则。
不包含:
- 真实后端实现
- 嘀加 API 调用
- 企微建群、一客一群流程
- 前端二维码生成
- 官网岗位展示配置页面
- 通用 Upload 组件迁移
- 依赖 `ui-component-fixes` 中尚未稳定的图片上传行为
## 已确认需求
### 路由与导航
- 在管理后台一级菜单「Agent群管理」下新增二级菜单「渠道活码」入口。
- `/channel-codes` 展示渠道活码列表。
- `/channel-codes/new` 展示新增员工渠道活码表单。
- `/channel-codes/:codeId/edit` 展示编辑员工渠道活码表单。
- 查看活码使用抽屉,不使用独立详情页。
- 抽屉应尽量保留列表上下文;若使用 URL 查询参数承载查看状态,刷新后应恢复抽屉。
### 列表页
列表支持:
- 活码名称模糊搜索
- 对应岗位筛选,包含「全部」选项
- 状态筛选:全部、启用、停用
- 分页
- 加载态、空态、筛选无结果态、失败态
列表字段包括:
- 活码名称
- 对应岗位
- 渠道编码
- 承接员工
- 关联 Agent
- 状态
- 创建时间
- 操作:查看、编辑、启用或停用
### 新建表单
新建页面标题为「新增员工渠道活码」,主要字段为:
- 活码名称:必填,最多 50 字。
- 对应岗位:必选,单选岗位;每个岗位仅允许创建一个渠道活码,已启用和已停用都算已创建。
- 渠道编码:只读,由岗位标签编码自动决定。
- 承接员工:只读,由托管方案或 mock 响应决定。
- 关联 Agent:只读,系统自动带入「该岗位所有已上架 Agent + 管家 Agent」。
- 活码描述:可选,最多 200 字。
- 自动欢迎语:可选,最多 500 字。
- 状态:使用开关,默认停用。
新建页作为独立子页面,遵循 `frontend-foundation.md` 的子页面规则:顶部左侧展示返回按钮和页面名称,顶部右侧展示 `取消`、`保存`,表单主体居中放置,字段采用标签在左、控件在右的结构。
选择岗位后,页面自动展示该岗位对应的渠道编码、承接员工和关联 Agent。若岗位已有渠道活码,应在岗位选择中阻止再次选择,并提示「该岗位已有渠道活码,请编辑原活码」。
### 编辑表单
编辑页复用新建页结构,但:
- 对应岗位不允许修改。
- 渠道编码不允许修改。
- 承接员工不允许修改。
- 关联 Agent 不允许修改。
- 活码名称、活码描述、自动欢迎语、状态可编辑。
### 查看活码抽屉
查看抽屉展示:
- 活码名称
- 对应岗位
- 渠道编码
- 承接员工
- 关联 Agent
- 状态
- 活码描述
- 自动欢迎语
- 二维码图片
二维码图片由 mock 返回的真实可加载图片 URL 提供,前端只负责展示和图片加载失败状态,不生成二维码。
### 启用与停用
- 列表操作中提供启用或停用。
- 启用和停用操作都需要二次确认。
- 停用后活码不可继续扫码使用;启用后恢复可用。
- 停用时,如果后台接口返回「被展示中的官网 Tab 关联」等业务阻断,前端只展示接口返回的提示信息,不在前端通过官网 Tab fixture 做本地判断。
- 已下架 Tab 不阻断的规则由后台或 mock 接口负责表达,前端不推导。
## Mock 与契约方向
本次 mock 契约以岗位维度的员工渠道活码为核心,而不是前端手动配置员工或 Agent。
建议新增或调整以下 mock API 语义:
- 查询渠道活码列表
- 查询渠道活码详情
- 查询新建表单初始化数据
- 根据岗位查询渠道编码、承接员工、关联 Agent
- 创建渠道活码
- 更新渠道活码
- 启用或停用渠道活码
关键数据结构建议包含:
- `code_id`
- `code_name`
- `position_code`
- `position_name`
- `channel_code`
- `employee_name`
- `employee_role_text`
- `agent_names`
- `status`: `enable` 或 `disable`
- `qrcode_url`
- `description`
- `welcome_message`
- `created_at`
- `updated_at`
- `operations`
fixture 至少覆盖:
- 正常列表
- 空列表
- 筛选无结果
- 加载失败
- 分页边界
- 已启用、已停用状态
- 岗位已有活码导致新建不可选
- 停用成功
- 停用被接口业务阻断
- 保存成功
- 保存字段校验失败
- 保存接口失败
- 二维码图片加载失败
## 与现有页面的关系
- `/agent-tags` 是已完成的岗位标签管理页面,作为岗位来源与一岗一码规则基础。
- 本次不实现官网「岗位展示配置」页面。
- 当前官网方法论配置页只作为已有导航和官网配置分组参考。
- 关联 Agent 展示规则使用「该岗位所有已上架 Agent + 管家 Agent」,不允许在渠道活码页面手动编辑。
## 交互成功标准
- 用户可以进入渠道活码列表,完成搜索、筛选、分页与状态识别。
- 岗位筛选包含「全部」选项,便于恢复全量列表。
- 用户可以新建渠道活码,且默认状态为停用。
- 用户新建时选择岗位后,渠道编码、承接员工、关联 Agent 自动展示且不可修改。
- 已创建过活码的岗位不能再次创建。
- 用户可以编辑既有活码,但不能修改对应岗位。
- 用户可以通过抽屉查看活码和二维码图片。
- 二维码图片加载失败时有明确失败状态。
- 用户可以启用或停用活码,启用和停用操作前都有二次确认。
- 停用业务阻断时,页面展示接口返回提示。
- 页面具备加载、空、错误、保存中、保存失败等必要状态。
- mock 契约与 fixture 能支撑以上所有状态。
## 推荐后续步骤
用户确认本设计后,进入 OpenSpec 锁定规范阶段:
1. 使用 change name `channel-code-management`。
2. 按 OpenSpec 指令创建 `proposal.md`。
3. 创建 `design.md`。
4. 创建或更新相关 capability spec。
5. 创建 `tasks.md`。
6. 经用户确认 OpenSpec artifacts 后,再进入实现计划与 TDD 编码。
# 官网配置下的方法论展示配置设计
## 背景
本设计用于 `official-site-methodology-config` OpenSpec。前置的登录、管理后台框架、Agent 管理列表页、mock 最小契约,以及 `skill-list-markdown-drawer` 已完成并归档;`agent-create-edit-detail` 仍在修复中,本次不修改其范围。
本次只新增后台官网配置下的「方法论展示配置」能力,不处理岗位展示配置、Agent 展示配置、渠道活码或 H5 官网页面。
## 目标
- 新增独立配置页 `/official-site/methodology`。
- 菜单归属为「官网配置 > 方法论展示配置」。
- 支持配置展示状态、主标题、副标题,以及方法论步骤列表。
- 支持步骤的新增、删除、排序和必填校验。
- 支持内容图 PNG/JPG/JPEG/GIF、最大 10MB 的前端 mock 上传校验,使用缩略图预览方式展示。
- 补充本页所需的最小前端 mock 契约和可测试 fixture。
## 非目标
- 不实现 H5 官网页面的展示效果。
- 不实现岗位展示配置、Agent 展示配置、渠道活码配置。
- 不接入真实文件服务或真实后端。
- 不抽象通用官网配置框架。
- 不重构现有上传、表单、开关、状态提示等基础组件。
## 方案
采用推荐方案:新增一个后台独立配置页,复用现有 AdminShell、表单、开关、上传和状态提示基础能力;将上传校验、mock 状态、保存行为控制在页面级和本页 mock 契约内。
字段模型保持最小化:
- `display_status`:`enable` 或 `disable`。
- `title`:主标题,必填,最多 30 字。
- `subtitle`:副标题,必填,最多 100 字。
- `steps`:方法论步骤数组。
- `steps[].icon`:步骤图标资源,必填;它是每个步骤用于展示的图标,不是上传进度图。
- `steps[].name`:步骤名称,必填,最多 20 字。
- `steps[].content_image`:内容图,必填,PNG/JPG/JPEG/GIF,最大 10MB,支持缩略图预览。
- `steps[].sort_order`:排序序号,由页面在添加、删除、上移、下移后维护。
## 交互边界
- 页面加载时展示 loading;加载失败展示错误状态和重试入口。
- 正常配置 fixture 展示完整表单和步骤列表。
- 关闭展示 fixture 中 `display_status=disable`,页面仍允许编辑并保存配置。
- 步骤为空 fixture 展示空步骤状态和「添加步骤」入口。
- 展示状态开启时,保存要求至少存在一个完整步骤;展示状态关闭时允许步骤为空,但已有步骤仍需满足字段校验。
- 排序先采用上移/下移按钮实现,保证键盘和测试可稳定验证,不引入拖拽依赖。
- 删除步骤后重新计算 `sort_order`。
- 保存中禁用重复提交;保存失败展示可恢复的全局错误提示。
## 上传边界
- 上传只做前端 mock 和校验,不请求真实文件服务。
- 内容图只接受 PNG/JPG/JPEG/GIF,最大 10MB。
- 内容图使用缩略图预览方式展示,点击缩略图可预览并删除。
- 图片格式错误、图片过大和 mock 上传失败分别有独立可测状态。
- 步骤图标可以采用 mock 上传或选择预置图标的页面级实现;OpenSpec 只要求它能产出最小图标资源数据,不锁定后端素材库实现。
- 上传进度、上传中、失败、重试属于上传控件临时 UI 状态,不写入方法论配置数据。
## 契约边界
前端契约只补充本页需要的最小字段和状态,不锁定服务端实现:
- 配置读取返回:加载状态、配置数据、错误信息。
- 保存请求:本页表单字段和步骤数组。
- 保存响应:成功或失败错误。
- 图片资源:最小 `id`、`name`、`url`、`mime_type`、`size_bytes`。
- fixture 覆盖:正常配置、关闭展示、步骤为空、图片上传失败、图片格式错误、图片过大、保存失败、加载失败。
## 测试策略
- 先补页面与 mock 契约相关测试,再实现。
- 覆盖字段必填、字数限制、步骤为空、步骤字段校验、上传格式、上传大小、mock 上传失败、保存失败、加载失败。
- 实现后运行 `npm run typecheck`、`npm test`、`npm run build`,并进行必要浏览器验证。
# 官网 Agent 展示配置设计
## 背景
本设计用于 `workspace/agent-admin/web` 的下一项 OpenSpec change:`official-site-agent-display-config`。
前置 `official-site-job-tabs` 已约定从岗位展示配置列表行操作「配置Agent」跳转到 `/official-site/job-tabs/:tabId/agents`,但页面内容暂未实现。本次补齐该路由下的后台 Agent 展示配置能力。范围仅限管理后台 web 前端、前端契约和 mock fixture,不实现 H5 官网页面、真实上传服务或后端接口。
## 范围
采用已确认方案:独立配置页面 + 列表展示全部可配置 Agent + 点击「编辑」打开弹窗表单。
覆盖:
- `/official-site/job-tabs/:tabId/agents` 独立页面。
- 页面顶部返回岗位展示配置列表。
- 页面展示岗位名、关联渠道活码、渠道编码、承接员工等上下文信息。
- 表格展示全部可配置 Agent,不允许前端新增或删除 Agent。
- 每个 Agent 仅允许编辑展示配置。
- 点击「编辑」打开弹窗表单。
- 展示素材复用现有上传图片组件能力,支持图片、视频、GIF,限制只能上传 1 个。
- Agent 图标保留为可配置字段,使用 `icon_url` 表示,复用上传图片组件,限制只能上传 1 个。
- Agent 停用状态只在列表中展示,停用 Agent 不展示编辑按钮。
- mock 契约和 fixture 覆盖正常、空数据、停用、上传失败、格式错误、大小错误、保存失败等状态。
不包含:
- 真实后端接口实现。
- 真实 OSS/CDN 上传。
- H5 官网页面展示。
- Agent 原始数据增删改。
- 渠道活码管理、岗位展示配置页面本身。
- 通用上传组件重构;本页只复用现有上传图片组件并配置业务规则。
## 已确认需求
### 页面结构
页面标题采用「岗位名 - Agent展示配置」,例如「驻店销售岗 - Agent展示配置」。
页面顶部包含:
- 返回列表入口,返回 `/official-site/job-tabs`。
- 标题。
- 保存按钮。
页面上下文信息包含:
- 关联渠道活码。
- 渠道编码。
- 承接员工。
页面底部或表格下方展示数据来源说明:
- Agent 数据源来自该岗位关联的渠道活码。
- 管家 Agent 不参与官网展示。
- Agent 列表不可增删,仅可编辑展示配置。
### 列表
列表展示全部可配置 Agent,即从该岗位关联渠道活码自动提取、排除管家 Agent 后的 Agent 列表。前端不提供新增或删除 Agent 展示配置入口。
列表字段包括:
- Agent 名称。
- Agent 概述。
- 展示素材。
- 排序。
- 状态。
- 展示状态。
- 操作。
字段映射:
- 页面「Agent 名称」对应契约字段 `speech_title`。
- 页面「Agent 概述」对应契约字段 `speech_content`。
`状态` 对应契约字段 `agent_status`,展示 Agent 本身状态:
- 已上架。
- 已停用。
`展示状态` 对应契约字段 `display_status`,展示 Agent 官网展示配置状态。展示规则:
- 当 `agent_status` 为已停用时,`display_status` 在列表显示为 `-`。
- 当 `agent_status` 为已上架时,`display_status` 在列表显示该 Agent 展示配置的具体状态:展示中或已下架。
- Agent 展示配置状态仍然只有 `已下架` 和 `展示中`。
操作规则:
- `agent_status` 未停用时,操作列展示「编辑」。
- `agent_status` 为已停用时,操作列不展示编辑按钮。
- 不展示新增、删除、上架、下架等独立行操作。
### 编辑弹窗
点击列表「编辑」打开「编辑展示配置 - Agent名称」弹窗。
弹窗字段包括:
- 图标:`icon_url`,使用上传图片组件,只能上传 1 个。
- Agent 名称:对应 `speech_title`,必填,最多 20 字。
- Agent 概述:对应 `speech_content`,必填,最多 100 字。
- 展示素材:使用上传图片组件,支持图片、视频、GIF,只能上传 1 个。
- 展示排序:必填,整数范围 0-99,数字越小越靠前。
- 展示状态:已下架、展示中。
首次编辑未配置 Agent 时,展示状态默认「已下架」。
弹窗状态规则:
- 弹窗内不展示「已停用」作为展示配置状态选项。
- 如果 Agent 已停用,则用户无法打开编辑弹窗,因为列表不展示编辑按钮。
- 保存中禁用重复提交。
- 保存失败保留用户已填写内容,并展示可恢复错误。
- 字段校验错误展示在字段附近。
### 上传规则
图标上传:
- 字段名:`icon_url`。
- 使用上传图片组件。
- 只能上传 1 个。
- 用于 Agent 头像或 ICON 展示。
展示素材上传:
- 使用上传图片组件。
- 支持图片、视频、GIF。
- 只能上传 1 个。
- 仍按业务字段表达为「展示素材」,避免与图标混淆。
- Agent 展示素材推荐比例 1:1。
- 素材大小限制沿用 Agent 展示素材规则,最大 20MB。
- 上传失败、格式错误、大小错误都需要有可测试错误态。
真实接口阶段,展示素材应走 `POST /api/v1/official-site/upload` 并使用 `usage_type=agent_media`;本 change 只实现 mock 上传语义,不接真实文件服务。
### 契约调整方向
前端契约需要在 Agent 展示配置保存、读取和配置项模型中补充 `icon_url` 字段。
建议最小字段:
- `agent_id`
- `agent_name`
- `agent_status`
- `icon_url`
- `media_url`
- `media_type`
- `media_size`
- `speech_title`
- `speech_content`
- `display_status`
- `sort_order`
展示配置状态:
- `display_status=disable`:已下架。
- `display_status=enable`:展示中。
Agent 本身状态:
- `agent_status=active` 或 `agent_status=enable`:已上架,可编辑。
- `agent_status=disabled` 或 `agent_status=stopped`:已停用,只展示,不可编辑。
停用联动:
- Agent 停用后,官网 H5 隐藏该 Agent,但后台列表仍展示该 Agent 及其配置状态。
- 停用 Agent 的展示配置仍保留。
- 停用 Agent 在后台列表中的展示状态显示为 `-`。
- Agent 重新启用后,可恢复编辑和展示规则。
## Mock 与 fixture
mock fixture 至少覆盖:
- 正常配置列表。
- 全部可配置 Agent 展示。
- 未配置 Agent,默认状态为已下架。
- 已配置 Agent,状态为展示中。
- Agent 已停用,列表状态展示已停用,展示状态展示 `-`,且不展示编辑按钮。
- 无可配置 Agent。
- 图标上传成功。
- 图标上传失败。
- 展示素材上传成功。
- 展示素材上传失败。
- 展示素材格式错误。
- 展示素材超过 20MB。
- 字段必填错误。
- Agent 名称超过 20 字。
- Agent 概述超过 100 字。
- 排序超出 0-99。
- 保存失败。
## 与相邻 change 的边界
- `official-site-job-tabs`:提供岗位展示配置列表和跳转入口。本 change 实现跳转后的 Agent 展示配置页面。
- `official-site-methodology-config`:已实现方法论配置。本 change 不修改方法论页面。
- `channel-code-management`:负责渠道活码管理。本 change 只消费岗位关联渠道活码信息。
- `ui-component-fixes`:负责通用组件修复。本 change 只复用上传图片组件,不在本 change 重构上传组件。
## 交互成功标准
- 用户可以从岗位展示配置列表进入 Agent 展示配置页面,并返回列表。
- 页面展示岗位、关联渠道活码、渠道编码、承接员工上下文。
- 页面展示该岗位下全部可配置 Agent。
- 页面不提供新增或删除 Agent 的能力。
- 用户可以看到 Agent 名称、Agent 概述、展示素材、排序、状态和展示状态。
- Agent 未停用时,用户可以点击「编辑」打开弹窗。
- Agent 已停用时,状态展示「已停用」,展示状态展示 `-`,不展示编辑按钮。
- Agent 已上架时,状态展示「已上架」,展示状态展示「展示中」或「已下架」。
- 弹窗中可以编辑图标、Agent 名称、Agent 概述、展示素材、排序和展示状态。
- 图标和展示素材都只能上传 1 个。
- 展示素材复用上传图片组件,并支持图片、视频、GIF。
- 首次编辑未配置 Agent 时,展示状态默认为已下架。
- 弹窗展示状态只包含已下架和展示中。
- 字段必填、字数、排序范围、上传格式、上传大小、上传失败和保存失败都有明确反馈。
- mock 契约包含 `icon_url`,并能支撑后续真实接口联调。
## 推荐后续步骤
用户确认本设计后,进入 OpenSpec 锁定规范阶段:
1. 使用 change name `official-site-agent-display-config`。
2. 运行 `openspec status --change "official-site-agent-display-config" --json` 检查 artifact 状态。
3. 按 OpenSpec 指令依次创建 `proposal.md`、`design.md`、前端相关 capability `spec.md` 和 `tasks.md`。
4. OpenSpec artifacts 确认后,再进入实现计划与 TDD 编码。
# 官网岗位展示配置设计
## 背景
本设计用于 `workspace/agent-admin/web` 的下一项 OpenSpec change:`official-site-job-tabs`。
当前后台已具备 Agent 列表、岗位标签管理、Skill 目录、渠道活码相关设计与官网方法论展示配置。官网配置下还缺少「岗位展示配置」,即官网 H5 的岗位 Tab 后台配置能力。本次只处理管理后台 web,不实现 H5 前台页面和真实后端。
本 change 仅关注 `workspace/agent-admin/web` 前端相关内容。OpenSpec artifacts、实施计划和后续实现都不应生成 `workspace/agent-admin/backend` 下的接口、模型、服务或测试文件。
## 范围
采用已确认的方案 A:「完整后台页面方案」,覆盖:
- 岗位展示配置列表页 `/official-site/job-tabs`
- 新建岗位展示页 `/official-site/job-tabs/new`
- 编辑岗位展示页 `/official-site/job-tabs/:tabId/edit`
- 列表筛选、分页、状态、排序展示、加载态、错误态、空态、筛选无结果态
- 表单保存态、保存失败态、字段校验态
- 上架、下架操作及二次确认
- 删除操作及二次确认
- 新建、编辑、上架、下架、删除和重试操作的成功/失败提示
- 路由、左侧导航、菜单高亮、面包屑
- 相关 mock 契约和 fixture
- 列表行操作「配置Agent」跳转到 `/official-site/job-tabs/:tabId/agents`
页面实现需遵循 `docs/frontend-foundation.md` 和 `docs/page-patterns.md` 的后台页面规则,包括子页面页头、表单布局、表格筛选、分页、状态反馈和二次确认。
不包含:
- `/official-site/job-tabs/:tabId/agents` 页面内容和 Agent 展示配置业务能力
- H5 官网页面
- 真实后端、真实上传、CDN、嘀加 API、企微流程
- backend 目录下的 API、模型、服务、数据库迁移或测试文件
- 方法论展示配置,已由 `official-site-methodology-config` 单独处理
- 通用 Upload 组件迁移,仍归属 `ui-component-fixes`
- 渠道活码管理实现本身;若 `channel-code-management` 尚未落地,本 change 使用 mock 的岗位关联渠道活码数据,并保持契约可衔接
## 已确认需求
### 路由与导航
- 在管理后台一级菜单「官网配置」下新增二级菜单「岗位展示配置」入口。
- `/official-site/job-tabs` 展示岗位展示配置列表。
- `/official-site/job-tabs/new` 展示新建岗位展示表单。
- `/official-site/job-tabs/:tabId/edit` 展示编辑岗位展示表单。
- 列表行操作「配置Agent」只跳转到 `/official-site/job-tabs/:tabId/agents`。
- 本 change 不实现 `/official-site/job-tabs/:tabId/agents` 的页面内容;该页面能力由后续 `official-site-agent-display-config` 处理。
- 路由、菜单高亮和面包屑应与现有 AdminShell 风格一致。
### 列表页
列表字段包括:
- 官网 Tab
- 关联渠道活码
- 展示 Agent 数
- 排序
- 状态
- 更新时间
- 操作
列表支持:
- 按官网 Tab 或关联渠道活码的关键词筛选
- 按状态筛选:全部、已下架、展示中
- 分页
- 加载态、空态、筛选无结果态、加载失败态
- 排序字段展示,数字越小在 H5 中越靠左;后台列表只展示配置值,不在本页实现 H5 排布
行操作包括:
- 配置Agent:跳转到 `/official-site/job-tabs/:tabId/agents`
- 编辑:进入 `/official-site/job-tabs/:tabId/edit`
- 上架或下架:根据当前状态展示对应操作,并在执行前二次确认
- 删除:执行前二次确认
### 新建表单
新建字段包括:
- 选择岗位标签:必选。
- 关联渠道活码:选择岗位标签后自动带出,以文本展示渠道活码标题。
- 渠道编码:默认隐藏;选择岗位标签并查询到关联渠道活码数据后,从渠道活码带入并以文本方式只读展示。
- 承接员工:默认隐藏;选择岗位标签并查询到关联渠道活码数据后,从渠道活码带入并以文本方式只读展示。
- 岗位标题:必填,字段 `main_title`,最多 30 字,展示在官网 Tab 名称下方,一句话介绍 AI 如何赋能该岗位。
- 岗位说明:必填,字段 `sub_title`,最多 200 字,展示在官网 Tab 内容区,详细描述 AI 为该岗位带来的价值。
- Tab 排序:必填,整数范围 0-99。
- 展示状态:已下架或展示中,新建默认展示中。
业务规则:
- 同一个岗位标签只能创建一个官网岗位 Tab。
- 若岗位标签已存在官网岗位 Tab,新建时应阻止重复创建,并给出明确提示。
- 岗位标签与渠道活码是一对一关系;选择岗位标签后,页面自动查询并展示该岗位关联的渠道活码。
- 关联渠道活码以文本方式展示;渠道编码和承接员工默认隐藏,只有关联渠道活码存在数据时才以文本方式展示,不提供手动选择或编辑入口。
- 若岗位未配置渠道活码,应提示「该岗位暂未配置渠道活码」,并隐藏渠道编码、承接员工字段。
- 岗位未配置渠道活码时,应阻止保存。
- 渠道编码和承接员工不可手动编辑。
- Tab 排序只校验输入范围 0-99;允许不同 Tab 使用相同排序值,不做排序冲突阻止或提示。
### 编辑表单
编辑页复用新建页结构,但字段可编辑性不同:
- 选择岗位标签不允许修改。
- 关联渠道活码不允许修改,以文本展示渠道活码标题。
- 渠道编码默认隐藏;当当前 Tab 关联渠道活码存在渠道编码数据时,以文本方式只读展示。
- 承接员工默认隐藏;当当前 Tab 关联渠道活码存在承接员工数据时,以文本方式只读展示。
- 岗位标题和岗位说明允许修改。
- 允许修改 Tab 排序和展示状态。
编辑保存仍需校验:
- 岗位标题必填,最多 30 字。
- 岗位说明必填,最多 200 字。
- Tab 排序为 0-99 范围内整数。
- 展示状态为已下架或展示中。
- 保存中禁用重复提交。
- 新建和编辑保存成功后展示成功提示,再返回列表。
- 保存失败展示可恢复的失败提示,用户可修正后重试。
- 字段校验错误仍展示在字段附近,不用全局提示替代字段附近的错误信息。
### 上架、下架与删除
- 状态包括「已下架」和「展示中」,契约值沿用 `disable` 和 `enable`;新建默认展示中。
- 下架后 H5 隐藏该 Tab,但不影响关联渠道活码状态和可用性。
- 上架后 H5 恢复展示。
- 上架和下架操作都需要二次确认。
- 上架、下架成功后展示成功提示,失败时展示失败提示并保留当前列表状态。
- 删除 Tab 时清理该 Tab 下所有 Agent 展示配置。
- 删除不删除 Agent 原始数据,不影响关联渠道活码。
- 删除操作需要二次确认,并在确认文案中说明会清理该 Tab 下的 Agent 展示配置。
- 删除成功后展示成功提示,失败时展示失败提示并保留当前列表状态。
- 列表加载失败后的重试操作需要在成功时展示成功提示,在再次失败时展示失败提示。
## Mock 与契约方向
本次只在前端契约与 mock fixture 中补充或落地官网岗位 Tab 所需能力,保持与 `frontend-api-contract.md` 中 `OfficialSiteTabStatus`、官网 Tab 列表、创建、更新、删除、状态更新和岗位渠道活码查询语义一致;不生成后端接口实现或后端测试。
建议使用以下核心数据:
- `tab_id`
- `position_code`
- `position_name`
- `qrcode_id`
- `qrcode_name`
- `channel_code`
- `employee_name`
- `main_title`
- `sub_title`
- `display_status`: `enable` 或 `disable`
- `sort_order`
- `agent_count`
- `created_at`
- `updated_at`
- `operations`
mock API 语义建议覆盖:
- 查询岗位展示配置列表
- 查询岗位展示配置详情
- 查询可创建 Tab 的岗位标签候选项
- 按岗位查询一对一关联的渠道活码信息
- 创建岗位展示配置
- 更新岗位展示配置
- 上架或下架岗位展示配置
- 删除岗位展示配置
fixture 至少覆盖:
- 正常列表
- 空列表
- 筛选无结果
- 加载失败
- 分页
- 展示中和已下架状态
- 新建成功
- 编辑成功
- 同岗位标签重复创建被阻止
- 所选岗位未配置渠道活码
- 岗位标题为空
- 岗位说明为空
- 岗位标题超出 30 字
- 岗位说明超出 200 字
- Tab 排序超出 0-99
- 保存失败
- 上架确认、成功与失败
- 下架确认、成功与失败
- 删除确认、成功与失败
- 重试成功与失败
不再覆盖「排序冲突」作为阻断场景;重复排序值允许保存。
## 与相邻 change 的边界
- `channel-code-management`:负责渠道活码管理本身。本 change 只消费「岗位一对一关联渠道活码」信息;若前者尚未实现,先用本 change 的 mock 数据承接,但字段与后续契约保持一致。
- `ui-component-fixes`:负责通用 Select、Upload、FormItem 等组件稳定性。本 change 不做通用组件迁移,不把页面级需求塞进组件修复。
- `official-site-methodology-config`:已完成官网方法论展示配置。本 change 不修改方法论页面业务能力,只在「官网配置」导航下并列新增岗位展示配置入口。
- 后续 `official-site-agent-display-config`:负责 `/official-site/job-tabs/:tabId/agents` 页面和 Agent 展示配置能力。本 change 只保留列表行跳转入口和路由约定。
## 交互成功标准
- 用户可以从「官网配置 > 岗位展示配置」进入列表页。
- 列表能展示官网 Tab、关联渠道活码、展示 Agent 数、排序、状态、更新时间和操作。
- 用户可以完成关键词筛选、状态筛选、分页,并看到加载、空、筛选无结果和加载失败状态。
- 用户可以新建岗位展示配置。
- 新建时同一岗位标签不能重复创建官网岗位 Tab。
- 新建时选择岗位标签后自动带出关联渠道活码标题;渠道编码和承接员工默认隐藏,并在关联渠道活码有数据时展示对应内容。
- 关联渠道活码以文本方式展示;渠道编码和承接员工仅在关联渠道活码有数据时以文本方式展示。
- 岗位未配置渠道活码时,提示「该岗位暂未配置渠道活码」,隐藏渠道编码、承接员工,并阻止保存。
- 用户可以编辑既有岗位展示配置,但不能修改岗位标签和关联渠道活码。
- 新建和编辑时可以填写岗位 AI 赋能介绍,包括岗位标题 `main_title` 和岗位说明 `sub_title`。
- 岗位标题最多 30 字,展示在官网 Tab 名称下方,用于一句话介绍 AI 如何赋能该岗位。
- 岗位说明最多 200 字,展示在官网 Tab 内容区,用于详细描述 AI 为该岗位带来的价值。
- 编辑时可以修改岗位标题、岗位说明、排序和展示状态。
- 排序只限制为 0-99 的整数,不限制重复值。
- 用户可以上架、下架和删除,且高影响操作都有二次确认。
- 新建、编辑、上架、下架、删除和重试都有成功/失败提示。
- 字段校验错误显示在字段附近,不被全局成功/失败提示替代。
- 删除说明清楚表达会清理该 Tab 下的 Agent 展示配置,但不影响 Agent 原始数据和渠道活码。
- 「配置Agent」行操作跳转到 `/official-site/job-tabs/:tabId/agents`,不实现该页面业务内容。
- mock 契约和 fixture 能支撑正常、空数据、筛选无结果、加载失败、保存失败、排序范围错误、岗位未配置渠道活码、重复岗位 Tab、上架确认/成功/失败、下架确认/成功/失败、删除确认/成功/失败、重试成功/失败等场景。
## 推荐后续步骤
用户确认本设计后,进入 OpenSpec 锁定规范阶段:
1. 使用 change name `official-site-job-tabs`。
2. 运行 `openspec status --change "official-site-job-tabs" --json` 检查 artifact 状态。
3. 按 OpenSpec 指令依次创建 `proposal.md`、`design.md`、前端相关 capability `spec.md` 和 `tasks.md`。
4. 经用户确认 OpenSpec artifacts 后,再进入实现计划与 TDD 编码。
## Context
`web/` 项目当前已经有 Agent 列表页、登录页和组件 Demo,但没有 `/skills` 页面。前端契约里已经存在 `GET /api/v1/skills` 和 `GET /api/v1/skills/{skill_code}`,因此这次变更的重点是把现有 Skill 契约落成一个只读目录页和详情抽屉,而不是引入新的编辑能力或新的后端方向。
这次变更主要涉及两类页面行为:
- `/skills` 列表页上的关键词搜索和只读表格。
- 列表页内打开的 Skill 详情抽屉,用于查看 Markdown 使用说明。
## Goals / Non-Goals
**Goals:**
- 提供 `/skills` 只读 Skill 列表页。
- 提供关键词搜索,快速过滤 Skill 目录,并遵循 `frontend-foundation.md` 的搜索区域规则。
- 提供列表内详情抽屉,展示 Skill 基本信息与 Markdown 文档。
- 提供 Markdown 基础渲染、代码块样式和抽屉内滚动。
- 为加载中、失败、空内容和长内容准备可测试 mock 状态。
**Non-Goals:**
- 不实现 Skill 新建、编辑、删除或排序。
- 不新增 Skill 目录相关的后端接口。
- 不把详情抽屉改造成独立详情页。
- 不在本 change 中改造公共搜索区、表格、分页或布局规则。
## Decisions
### 1. 采用“列表页 + 详情抽屉”的单页查看方式
Skill 目录只读且以浏览为主,因此列表页内直接打开详情抽屉,不单独增加详情路由。
**原因**: 这样可以保留列表上下文,避免在查看 Skill 使用说明时丢失搜索结果和页面位置。
**备选方案**: 详情页独立路由。这个方案更重,也会让查看 Skill 的路径分裂。
### 2. 列表页只展示只读信息,不提供写操作
Skill 列表页仅负责筛选和查看,不提供新建、编辑、删除或批量操作入口。
**原因**: 现阶段 Skill 目录是只读目录,写操作不属于当前产品边界。
**备选方案**: 在列表页保留占位的写操作入口。这个方案容易误导用户,也会和“目录一期只读”的契约冲突。
### 3. Markdown 采用页面层基础渲染,不引入新公共组件
Skill 详情抽屉需要展示 `doc_markdown`,但当前 `packages/ui` 还没有通用 Markdown 渲染组件。此次 change 只要求页面层实现基础 Markdown 可读效果,并用现有容器和样式表达标题、段落、列表、链接、引用、行内代码和代码块。
**原因**: 这能满足当前页面需要,同时避免把未复用的能力提前沉淀成公共组件。
**备选方案**: 先把 Markdown 渲染器做成共享基础组件。这个方案会把业务需求升级成基础设施改造,超出当前 change 范围。
### 4. 抽屉内容区独立滚动
详情抽屉需要支持长 Markdown 内容的独立滚动,避免长内容撑高整个页面。
**原因**: 用户查看长说明时仍要保留列表上下文,抽屉内滚动比整页滚动更符合列表式查看体验。
**备选方案**: 依赖页面整体滚动。这个方案会让列表上下文更容易丢失,也不利于处理超长内容。
### 5. 关键词搜索与页面状态分开表达
关键词搜索只影响列表过滤;加载失败、空结果和长内容等状态分别通过列表和详情抽屉独立表达。
**原因**: 列表查询失败、列表空数据和详情 Markdown 失败是不同层级的状态,应该分别呈现。
**备选方案**: 任一局部失败都让整页失败。这个方案实现简单,但会扩大故障面。
### 6. 关键词搜索区复用基础布局规则
Skill 列表页的关键词搜索区只承担单关键词输入,不新增业务专属下拉筛选;输入框宽度和区域排布按 `frontend-foundation.md` 的搜索区域规则执行。
**原因**: 这能避免 Skill 页的搜索区偏离项目统一规则,也能减少后续页面之间的交互差异。
**备选方案**: 为 Skill 页单独定义更宽松的搜索区样式。这个方案会让列表页和其他后台页面的搜索体验不一致。
### 7. 页面实现优先复用现有基础组件
Skill 列表页和详情抽屉应优先复用 `packages/ui` 中已有的 `Input`、`Table`、`Drawer`、`StatePlaceholder`、`Button` 等组件;若发现组件能力缺口,先记录到 `frontend-foundation.md` 或新开的基础能力 OpenSpec,再决定是否扩展组件。
**原因**: 这样可以保证本 change 只落业务页面,不悄悄修改公共组件规则,也能让缺口通过统一地基流程收敛。
**备选方案**: 在业务 change 中直接补组件能力。这个方案会混淆业务需求和基础设施改造的边界。
## Risks / Trade-offs
- [风险] Markdown 基础渲染若在多个页面复用,页面级实现会出现重复。→ 先把能力边界写清楚,后续如确需复用,再单独提基础能力 change。
- [风险] 长 Markdown 的排版和代码块样式容易失真。→ 用明确的基础语义和代码块样式约束,避免默认文本样式。
- [风险] 抽屉内滚动与页面滚动容易互相干扰。→ 把滚动容器限制在抽屉内容区,保持列表页本身稳定。
## Migration Plan
1. 先补齐 `/skills` 的页面规范和 mock 契约。
2. 复用现有 `Input`、`Table`、`Drawer`、`StatePlaceholder`、`Button` 等组件完成列表和抽屉。
3. 落地 Markdown 基础渲染和代码块样式。
4. 补齐加载中、失败、空内容和长内容状态 fixture。
5. 运行页面测试、类型检查和浏览器验证,确认列表和抽屉行为符合规范。
## Open Questions
- 无。本次设计已按现有 Skill 契约和页面边界收敛到只读目录页与详情抽屉。
## Why
岗位 Agent 管理后台已经具备 Skill 目录接口契约,但还没有对应的前端列表页。运营和研发在查看 Skill 时,需要一个只读的 `/skills` 页面,能按关键词快速检索 Skill,并在列表上下文里通过详情抽屉查看 Skill 使用说明 Markdown,而不是跳转到新的详情页。
## What Changes
- 新增 `/skills` Skill 列表页。
- 新增关键词搜索能力,支持按 Skill 目录的关键字过滤列表。
- 新增只读表格展示,按 `skill_code`、`skill_name`、`description` 展示 Skill 目录内容。
- 新增详情抽屉,在列表上下文中查看 Skill 基本信息和 `doc_markdown`。
- 新增 Markdown 基础渲染与代码块样式表达,保证 Skill 使用说明可读。
- 新增抽屉内滚动能力,长 Markdown 不会撑破页面。
- 补齐加载中、失败、空内容、长内容等 mock 状态,保证页面与抽屉可测试。
## Capabilities
### New Capabilities
- `skill-catalog`: 覆盖 `/skills` 页面、关键词搜索、只读表格、详情抽屉、Markdown 基础渲染与状态 mock。
## Impact
- 前端路由需要新增 `/skills`。
- 页面需要复用现有 `Table`、`Drawer`、`StatePlaceholder`、`Input`、`Button` 等基础组件。
- 页面需要复用现有 Skill 列表和 Skill 详情契约,不新增后端接口定义。
- 需要补充 Skill 列表页和详情抽屉的页面测试,覆盖搜索、查看、加载失败、空内容和长内容状态。
## ADDED Requirements
### Requirement: Skill 列表页结构
岗位 Agent 管理后台 SHALL 提供 `/skills` Skill 目录页,包含页面标题、关键词搜索区、只读表格和查看入口。
#### Scenario: 打开 Skill 列表页
- **WHEN** 已登录用户打开 `/skills`
- **THEN** 页面展示 Skill 目录标题
- **AND** 页面展示关键词搜索框、`搜索` 按钮、`重置` 按钮、只读表格和查看详情入口
### Requirement: 关键词搜索
Skill 目录页 SHALL 允许用户通过关键词过滤 Skill 列表。
#### Scenario: 搜索区遵循基础规则
- **WHEN** 页面渲染关键词搜索区
- **THEN** 搜索区布局遵循 `frontend-foundation.md` 中的搜索区域规则
- **AND** 关键词输入框宽度为 `200px`
- **AND** 关键词输入框 placeholder 为 `请输入Skill名称或编码`
- **AND** 页面不为该搜索区额外引入不必要的下拉筛选项
#### Scenario: 提交关键词搜索
- **WHEN** 用户输入关键词并点击 `搜索`
- **THEN** 页面根据关键词刷新 Skill 列表
- **AND** 页面将结果回到首屏状态
#### Scenario: 重置关键词
- **WHEN** 用户点击 `重置`
- **THEN** 页面清空关键词输入
- **AND** 页面恢复默认 Skill 列表
### Requirement: 只读表格
Skill 目录页 SHALL 仅以只读表格展示 Skill 目录信息,不提供写操作入口。
#### Scenario: 展示 Skill 行
- **WHEN** 页面渲染 Skill 列表
- **THEN** 每行展示 `skill_code`、`skill_name`、`description`
- **AND** 页面不展示新建、编辑、删除或批量操作入口
#### Scenario: 展示列表总数
- **WHEN** 页面渲染 Skill 列表表格
- **THEN** 页面在表格下方展示当前 Skill 总数
- **AND** 即使当前列表未启用分页,仍保留总数展示
### Requirement: 组件复用约束
Skill 列表页 SHALL 优先复用 `packages/ui` 中已有组件,并避免为单一场景临时重造重复组件能力。
#### Scenario: 复用现有组件
- **WHEN** 页面实现列表、搜索区、详情抽屉和状态反馈
- **THEN** 页面优先使用现有 `Input`、`Table`、`Drawer`、`StatePlaceholder`、`Button` 等基础组件
#### Scenario: 组件能力不足
- **WHEN** 页面发现现有组件能力不足以覆盖需求
- **THEN** 先单独记录到 `frontend-foundation.md` 或新开的基础能力 OpenSpec
- **AND** 不把公共布局、表格、分页或搜索组件规则混入本业务 change
### Requirement: 查看详情抽屉
Skill 目录页 SHALL 支持从列表页打开 Skill 详情抽屉。
#### Scenario: 查看 Skill 详情
- **WHEN** 用户点击某个 Skill 的查看入口
- **THEN** 页面打开详情抽屉
- **AND** 抽屉展示 Skill 基本信息和使用说明内容
- **AND** 关闭抽屉后返回列表上下文
### Requirement: Markdown 基础渲染
Skill 详情抽屉 SHALL 对 `doc_markdown` 提供基础 Markdown 渲染。
#### Scenario: 渲染标题与段落
- **WHEN** `doc_markdown` 包含标题、段落或列表
- **THEN** 抽屉内容按 Markdown 基础语义渲染
#### Scenario: 渲染行内代码与代码块
- **WHEN** `doc_markdown` 包含行内代码或 fenced code block
- **THEN** 抽屉展示等宽字体的代码内容
- **AND** 代码块保留换行和空白
- **AND** 长代码行可以在抽屉内横向滚动
### Requirement: 抽屉内部滚动
Skill 详情抽屉 SHALL 支持内容区独立滚动。
#### Scenario: 查看长 Markdown
- **WHEN** `doc_markdown` 内容很长
- **THEN** 抽屉内容区出现内部滚动
- **AND** 页面背景列表保持在原位置
### Requirement: 页面状态
Skill 目录页 SHALL 提供加载中、正常数据、空数据、失败和详情状态。
#### Scenario: 列表加载中
- **WHEN** Skill 列表数据正在加载
- **THEN** 页面展示加载中状态
#### Scenario: 列表空数据
- **WHEN** Skill 目录没有任何数据
- **THEN** 页面展示空数据状态
#### Scenario: 列表加载失败
- **WHEN** Skill 列表数据加载失败
- **THEN** 页面展示可恢复的失败状态
- **AND** 页面提供重试操作
#### Scenario: 详情加载失败
- **WHEN** Skill 详情加载失败
- **THEN** 详情抽屉展示失败状态
- **AND** 用户可关闭抽屉返回列表
#### Scenario: 详情空 Markdown
- **WHEN** Skill 详情返回空 `doc_markdown`
- **THEN** 抽屉展示空内容提示
### Requirement: Skill 最小 mock 契约
前端 mock 契约 SHALL 提供 Skill 列表和详情页所需的最小字段与状态 fixture。
#### Scenario: 消费 Skill 列表项
- **WHEN** 页面渲染 Skill 列表 mock
- **THEN** 列表项包含 `skill_code`、`skill_name`、`description`
#### Scenario: 消费 Skill 详情项
- **WHEN** 页面渲染 Skill 详情 mock
- **THEN** 详情项包含 `skill_code`、`skill_name`、`description`、`doc_markdown`
#### Scenario: 消费页面状态 fixtures
- **WHEN** 测试或本地开发需要 Skill 页面状态
- **THEN** mock 契约提供加载中、失败、空数据、长 Markdown、空 Markdown 和含代码块内容的 fixtures
## 1. 路由与页面骨架
- [x] 1.1 为 Skill 列表页补齐 `/skills` 路由入口与页面承载方式。
- [x] 1.2 搭建 Skill 列表页的基础骨架,统一标题、搜索区、表格和详情抽屉承载,并优先复用现有 `Input`、`Table`、`Drawer`、`StatePlaceholder`、`Button` 等组件。
- [x] 1.3 补齐从列表打开详情抽屉的页面内状态管理,确保关闭后保留搜索上下文。
- [x] 1.4 如发现组件能力缺口,先单独记录到 `frontend-foundation.md` 或基础能力 OpenSpec,不在业务 change 中改公共组件规则。
## 2. Mock 契约与状态模型
- [x] 2.1 定义 Skill 列表与 Skill 详情所需的 mock 数据模型,包含 `skill_code`、`skill_name`、`description` 和 `doc_markdown`。
- [x] 2.2 补齐页面状态 fixtures,覆盖列表加载中、列表失败、列表空数据、详情加载中、详情失败、详情空 Markdown 和长 Markdown。
- [x] 2.3 补齐关键词过滤所需的 mock 目录数据,覆盖普通内容、长内容和含代码块内容。
## 3. Skill 列表 / 详情实现
- [x] 3.1 实现只读 Skill 表格,展示 Skill 编码、名称、简介、查看入口,并在表格下方展示当前 Skill 总数。
- [x] 3.2 实现关键词搜索与重置,按 `frontend-foundation.md` 的搜索区域规则控制输入框宽度、布局、placeholder 文案和交互,支持按关键词过滤列表并回到首个结果状态。
- [x] 3.3 实现 Skill 详情抽屉,展示基本信息和 Markdown 使用说明。
- [x] 3.4 实现 Markdown 基础渲染与代码块样式,覆盖标题、段落、列表、链接、引用、行内代码和 fenced code block。
- [x] 3.5 实现抽屉内部滚动,确保长内容不会撑破页面。
## 4. 测试与验证
- [x] 4.1 补充页面测试,覆盖 Skill 列表、关键词搜索 placeholder、列表总数展示、查看详情、Markdown 渲染和抽屉关闭。
- [x] 4.2 补充状态测试,覆盖加载中、失败、空内容和长内容 mock。
- [x] 4.3 运行类型检查、相关测试和生产构建,确认无回归。
- [x] 4.4 在浏览器中验证关键流程,包括列表搜索、查看详情、Markdown 渲染、代码块样式和抽屉滚动。
- [x] 4.5 验证页面未引入新的公共布局、表格、分页或搜索组件规则。
## Context
现有 `web/` 管理后台已经具备登录、受保护后台框架和 Agent 列表页,但还没有覆盖 Agent 的新建、编辑和详情查看完整流程。页面数据草案和框架确认文档已经把新建页、编辑页和详情抽屉的路由形态定下来,因此这次变更的重点是把这些行为落成稳定、可测试的前端规范,而不是引入新的后端能力。
这次变更涉及同一实体在三种形态下的交互:
- 列表页上的详情抽屉。
- 独立的新建页。
- 独立的编辑页。
三者共享同一套 Agent 字段、选项数据和校验规则,但不同模式下对管家 Agent 的可编辑范围不同,且页面需要分别表达加载、保存、失败和选项不可用状态。
## Goals / Non-Goals
**Goals:**
- 提供 `/agents/new` 和 `/agents/:agentId/edit` 两个独立表单页。
- 提供从 `/agents` 打开的详情抽屉,并保持列表筛选、分页和滚动上下文。
- 明确普通 Agent 与管家 Agent 的差异化编辑规则。
- 为岗位标签、托管企微员工和 Skill 提供可测试的 mock 选项与加载失败状态。
- 统一新建、编辑、详情所使用的数据模型、状态模型和交互语义。
- 让 `/agents/new` 和 `/agents/:agentId/edit` 继续保持 Agent 列表二级菜单的激活态。
**Non-Goals:**
- 不在本 change 中实现真实后端接口或持久化逻辑。
- 不新增岗位标签、Skill 或托管企微员工的管理页面。
- 不修改 Agent 群管理、官网配置或后端运行时路由逻辑。
- 不把详情抽屉改造成独立详情页。
## Decisions
### 1. 采用“共享表单壳 + 模式切换”的实现方式
新建页和编辑页共享同一个表单页面骨架,仅通过 `mode=create|edit` 切换数据来源、标题、按钮文案和只读字段。详情抽屉则复用同一套展示组件,但以只读模式渲染。
页头层面,新建页和编辑页都采用顶部左侧返回按钮 + 页面名称的结构,表单主体居中展示,避免和列表页工具栏或详情抽屉混淆。
页头右侧放置 `取消` 与 `保存` 操作,顺序固定为 `取消` 在前、`保存` 在后,其中 `取消` 使用白色按钮样式,`保存` 使用 primary 实色按钮样式,确保操作优先级清晰。
表单字段层面,采用名称与输入控件左右结构,输入框、单选下拉、多选下拉和 Skill tag 选择器使用同一宽度策略:随页面空间收缩自适应,但最大宽度均为 `450px`,确保不同子页面的表单视觉节奏一致。
**原因**: 两个独立页面的字段、布局和校验几乎一致,只有数据来源和少量字段可编辑性不同。共享壳可以减少重复,保证普通 Agent 与管家 Agent 的规则一致。
**备选方案**: 分别实现新建页和编辑页两套页面。这个方案会放大维护成本,也更容易让校验、错误提示和选项加载状态出现分叉。
### 2. 详情抽屉使用列表页 query 参数承载
详情抽屉采用 `/agents?detail=:agentId` 的形式承载,打开抽屉时保留列表页当前筛选、分页和滚动状态;刷新页面后也能恢复已打开的详情。
**原因**: 这与页面数据草案和后台框架确认文档一致,也更利于深层路由刷新、浏览器前进后退和状态恢复。抽屉本身属于列表上下文的一部分,用 query 参数比单独的本地状态更稳。
**备选方案**: 仅用本地组件状态控制抽屉,或把详情做成子路由页面。前者无法自然恢复刷新状态,后者会让详情丢失“列表上下文”体验。
### 3. 用字段级可编辑配置表达管家 Agent 特殊规则
根据 `is_manager` / 管家标记,在同一表单中切换字段的可编辑性:
- 管家 Agent 固定名称、固定岗位、固定托管员工和固定上架状态。
- 管家 Agent 只允许编辑描述,Skill 可选但不强制。
- 普通 Agent 保持名称、岗位、员工、描述、Skill 和状态的完整编辑能力。
**原因**: 字段级配置比拆分出独立的管家页面更清晰,也能避免两套页面出现校验分歧。
**备选方案**: 管家 Agent 单独做一个特化页面。这个方案虽然直观,但会导致路由和交互分裂,不利于后续维护。
### 4. 表单字段交互统一采用“标签语义 + 前置引导”
普通 Agent 表单中的必填字段统一显示必填标签,除名称、所属岗位、托管企微员工、描述外,状态字段也需要在字段标题旁展示必填标签。绑定 Skill 不再使用普通多选下拉已选项展示,而是使用 tag 标签形式承载已绑定项,便于在编辑态和详情态保持一致的视觉语义。
托管企微员工字段在输入控件后追加提示文案 `请先选择所属岗位`。当尚未选择岗位时,控件保持不可用并展示这条提示;选择岗位后再按当前岗位拉取可选员工。
**原因**: 这组字段存在明显的前后依赖和视觉统一诉求。把必填标签、tag 形态和前置提示作为统一交互约束,可以减少用户误解,也能避免同一表单里出现宽度、状态表达和提示方式不一致的问题。
**备选方案**: 继续沿用不同字段各自独立的宽度和交互样式,只在校验报错时提醒用户。这个方案实现最省,但会让用户在首次填写时更难理解字段依赖和必填范围。
### 5. 选项加载采用“页面主数据与辅助选项分层加载”
Agent 详情、岗位标签、托管企微员工和 Skill 选项分开加载,彼此独立表达加载中和失败状态。页面主数据加载失败时,页面进入失败态;某个选项源失败时,只影响对应控件,不阻断整页编辑。
其中托管企微员工选项还依赖所属岗位选择:未选岗位时不触发员工加载,切换岗位后需要重新拉取当前岗位下的员工列表,并对 `已挂载Agent` 员工做不可选处理。
**原因**: 这些数据源职责不同,独立失败更符合实际使用场景,也能避免一个辅助接口失败就让整个表单不可用。
**备选方案**: 任一选项失败都阻塞整个页面。这个方案实现简单,但会放大故障面,影响可用性。
### 6. 保存后的返回行为以“恢复列表上下文并刷新列表”为优先
新建成功后返回 Agent 列表页;编辑成功后优先回到保存前的列表上下文,并保留原筛选、分页和详情抽屉状态。无论新建还是编辑成功,返回列表后都应刷新列表数据,确保最新变更可见。如果当前没有可恢复的列表上下文,则退回到 `/agents`。
**原因**: 管理员通常是在列表上下文中进行新增、编辑和查看,保存后回到列表能减少迷路感;如果来源是详情抽屉,则恢复抽屉比直接跳回空列表更连贯。
**备选方案**: 所有保存成功都固定跳回列表首页。这个方案最简单,但会丢失上下文,特别是在批量查看和连续编辑时体验较差。
## Risks / Trade-offs
- [风险] 详情抽屉通过 query 参数承载后,URL 会更复杂。→ 通过统一的路由 helper 封装打开/关闭逻辑,避免业务组件直接拼接 query。
- [风险] 管家 Agent 的字段锁定容易和普通 Agent 逻辑混在一起。→ 在表单配置层显式声明字段可编辑性,避免依赖显示文案推断规则。
- [风险] 辅助选项独立加载会产生更多状态分支。→ 为每个选项源定义统一的 loading / error / empty 表达,复用同一套状态组件。
- [风险] 保存后恢复列表上下文会增加导航处理复杂度。→ 通过 `returnTo` 或 history 回退统一处理,确保“从哪来回哪去”的行为可预测。
- [风险] 返回列表后刷新数据可能与“恢复上下文”时的滚动位置产生轻微闪动。→ 先恢复路由与筛选,再触发列表数据刷新,并复用骨架屏/局部 loading 缓解跳动。
## Migration Plan
1. 先补齐规范与 mock 契约,明确新建、编辑、详情抽屉的路由和状态。
2. 复用现有 Agent 列表页的数据模型,补充详情入口和新建入口语义。
3. 落地共享表单壳、详情抽屉和辅助选项加载。
4. 验证普通 Agent 与管家 Agent 的差异化编辑规则。
5. 运行页面测试、类型检查和浏览器验证,确认保存与返回行为符合规范。
## Open Questions
- 无。本次设计已按现有页面草案确定了路由形态、详情承载方式和管家 Agent 特殊规则。
## Why
当前 Agent 管理后台只有登录、框架和列表能力,缺少可直接使用的新增、编辑和详情查看流程。运营管理员需要在列表上下文中快速查看 Agent 详情,并通过独立表单页完成创建和编辑,同时处理管家 Agent 的特殊规则、选项加载和保存状态。
## What Changes
- 新增 Agent 创建页 `/agents/new`,用于创建普通 Agent。
- 新增 Agent 编辑页 `/agents/:agentId/edit`,用于修改 Agent 配置。
- 新增 Agent 详情抽屉,支持从列表页点击 Agent 名称或“查看”打开。
- 补齐 Agent 表单字段、必填校验、保存失败提示和加载中状态。
- 调整新建/编辑表单的输入与选择控件宽度规范,统一为随页面收缩变化且最大宽度 `450px`。
- 将绑定 Skill 的交互改为 tag 标签形式,并补齐状态字段的必填标签语义。
- 为托管企微员工字段补充岗位前置提示文案,明确先选所属岗位再选择员工。
- 补齐岗位标签、托管企微员工、Skill 选项的 mock 数据与加载失败状态。
- 落实管家 Agent 的特殊编辑规则,包括固定名称、固定岗位、固定托管员工、固定上架状态等。
- 更新 Agent 列表页入口,确保名称点击与操作入口能进入详情或编辑流程。
- 保持 `/agents/new` 和 `/agents/:agentId/edit` 下的 Agent 列表二级菜单选中态,并在保存成功后刷新列表数据。
## Capabilities
### New Capabilities
- `agent-management-editor`: 覆盖 Agent 新建页、编辑页和详情抽屉的页面结构、表单字段、校验规则、特殊编辑规则、选项加载状态与保存反馈。
### Modified Capabilities
- `agent-management-list`: 增加列表页到详情抽屉和编辑页的入口行为,并补充与 Agent 新建/编辑相关的导航与操作语义。
## Impact
- 前端路由需要新增 `/agents/new`、`/agents/:agentId/edit`,并支持列表页详情抽屉状态承载。
- Agent 列表页需要增加“查看/点击名称打开详情”的交互语义,以及与创建/编辑页联动的返回行为。
- 需要补充 Agent 表单、岗位标签、托管企微员工和 Skill 的 mock 契约与页面状态 fixture,并同步字段宽度、tag 形态和提示文案规范。
- 需要补充相关页面测试,覆盖加载、校验、保存、失败和管家 Agent 特殊规则。
- 需要补充新建/编辑页成功后列表数据刷新和二级菜单选中态的页面语义。
## ADDED Requirements
### Requirement: Agent 新建页
岗位 Agent 管理后台 SHALL 提供 `/agents/new` 独立页面用于创建普通 Agent。
#### Scenario: 打开新建页
- **WHEN** 已登录用户访问 `/agents/new`
- **THEN** 页面顶部左侧展示返回按钮和 `新建Agent` 标题
- **AND** 左侧导航中 `Agent列表` 二级菜单保持选中状态
- **AND** 用户可以点击返回按钮返回上一个页面
- **AND** 页面中间区域展示可填写的 Agent 表单
- **AND** 页面头部右侧展示 `取消` 和 `保存` 操作,且顺序为 `取消` 在前、`保存` 在后
- **AND** `取消` 使用白色按钮样式,`保存` 使用 primary 实色按钮样式
### Requirement: Agent 编辑页
岗位 Agent 管理后台 SHALL 提供 `/agents/:agentId/edit` 独立页面用于编辑 Agent。
#### Scenario: 打开编辑页
- **WHEN** 已登录用户访问 `/agents/:agentId/edit`
- **THEN** 页面顶部左侧展示返回按钮和 `编辑Agent` 标题
- **AND** 页面先调用详情接口查询对应 Agent 的现有数据
- **AND** 页面加载成功后回填对应 Agent 的现有数据
- **AND** 用户可以点击返回按钮返回上一个页面
- **AND** 页面中间区域展示可编辑的 Agent 表单
- **AND** 页面头部右侧展示 `取消` 和 `保存` 操作,且顺序为 `取消` 在前、`保存` 在后
- **AND** `取消` 使用白色按钮样式,`保存` 使用 primary 实色按钮样式
### Requirement: Agent 详情抽屉
岗位 Agent 管理后台 SHALL 支持在 `/agents` 页面通过详情抽屉查看单个 Agent。
#### Scenario: 从列表打开详情抽屉
- **WHEN** 已登录用户在 Agent 列表页点击 Agent 名称或 `查看`
- **THEN** 页面以抽屉形式展示该 Agent 的详情
- **AND** 页面保持列表当前筛选、分页和滚动上下文
- **AND** 页面使用 `detail` 查询参数标识当前打开的详情
#### Scenario: 关闭详情抽屉
- **WHEN** 已打开详情抽屉的用户关闭抽屉
- **THEN** 页面返回列表可见状态
- **AND** 页面保留关闭前的列表上下文
### Requirement: Agent 表单字段与校验
岗位 Agent 管理后台 SHALL 在新建和编辑页提供统一的 Agent 表单字段、校验与错误提示。
#### Scenario: 展示普通 Agent 表单字段
- **WHEN** 用户打开新建页或普通 Agent 编辑页
- **THEN** 页面展示 Agent 名称、所属岗位、托管企微员工、Agent 描述、绑定 Skill 和状态字段
- **AND** 表单字段采用名称与输入控件左右结构
- **AND** Agent 名称输入框、所属岗位下拉、托管企微员工下拉和绑定 Skill 控件采用一致的宽度规则
- **AND** 上述控件宽度随页面空间变化自适应收缩
- **AND** 上述控件最大宽度均为 `450px`
- **AND** 所属岗位使用多选下拉控件
- **AND** 托管企微员工使用下拉选择控件
- **AND** 托管企微员工控件后展示提示文案 `请先选择所属岗位`
- **AND** 绑定 Skill 使用 tag 标签形式的多选控件
- **AND** 状态使用开关控件
- **AND** 名称、所属岗位、托管企微员工、Agent 描述和状态字段标题旁展示必填标签
#### Scenario: Agent 名称长度限制
- **WHEN** 用户在 Agent 名称输入框输入内容
- **THEN** 页面最多允许输入 50 个字符
- **AND** 页面展示当前输入长度
#### Scenario: Agent 名称必填
- **WHEN** 用户提交表单且 Agent 名称为空
- **THEN** 页面提示 `请输入 Agent 名称`
#### Scenario: 所属岗位必填
- **WHEN** 用户提交表单且所属岗位为空
- **THEN** 页面提示 `请选择所属岗位`
#### Scenario: 托管企微员工必填
- **WHEN** 用户提交表单且托管企微员工为空
- **THEN** 页面提示 `请选择托管企微员工`
#### Scenario: 托管企微员工随岗位联动加载
- **WHEN** 用户未选择任何所属岗位
- **THEN** 页面不主动拉取托管企微员工选项
- **AND** 托管企微员工控件保持不可用状态
- **AND** 托管企微员工控件后持续展示提示文案 `请先选择所属岗位`
#### Scenario: 切换所属岗位刷新托管企微员工
- **WHEN** 用户选择或切换所属岗位
- **THEN** 页面根据当前选择的岗位重新拉取托管企微员工选项
- **AND** 每次岗位变化都刷新员工列表
#### Scenario: 置灰已挂载 Agent 员工
- **WHEN** 页面渲染托管企微员工选项
- **THEN** `status == '已挂载Agent'` 的员工置灰不可选
#### Scenario: Agent 描述必填
- **WHEN** 用户提交表单且 Agent 描述为空
- **THEN** 页面提示 `请输入 Agent 描述`
#### Scenario: 非管家 Agent Skill 必填
- **WHEN** 用户提交非管家 Agent 表单且未选择任何 Skill
- **THEN** 页面提示 `请至少绑定一个 Skill`
#### Scenario: 状态默认停用
- **WHEN** 用户打开新建页
- **THEN** 状态开关默认处于停用状态
- **AND** 状态字段标题旁展示必填标签
- **AND** 页面提交时携带状态字段
### Requirement: 管家 Agent 特殊编辑规则
岗位 Agent 管理后台 SHALL 对管家 Agent 应用固定字段与部分只读规则。
#### Scenario: 打开管家 Agent 编辑页
- **WHEN** 用户打开管家 Agent 的编辑页
- **THEN** 页面将 Agent 名称固定为 `管家Agent`
- **AND** 页面将所属岗位固定为 `系统调度`
- **AND** 页面将托管企微员工固定为管家企微员工
- **AND** 页面将状态固定为上架
- **AND** 页面仅允许编辑 Agent 描述
- **AND** 页面允许选择 Skill,但不要求必选
#### Scenario: 管家 Agent 不可修改固定字段
- **WHEN** 用户在管家 Agent 编辑页尝试修改名称、岗位、托管企微员工或状态
- **THEN** 页面不允许提交这些字段变更
### Requirement: 页面和选项状态
岗位 Agent 管理后台 SHALL 提供加载中、保存中、保存失败和选项加载失败状态。
#### Scenario: 页面数据加载中
- **WHEN** 新建页、编辑页或详情抽屉正在加载主数据
- **THEN** 页面展示加载中状态
#### Scenario: 岗位标签加载失败
- **WHEN** 所属岗位选项加载失败
- **THEN** 页面提示对应选项加载失败
- **AND** 页面允许用户重试加载该选项
#### Scenario: 托管企微员工加载失败
- **WHEN** 托管企微员工选项加载失败
- **THEN** 页面提示对应选项加载失败
- **AND** 页面允许用户重试加载该选项
#### Scenario: Skill 选项加载失败
- **WHEN** Skill 选项加载失败
- **THEN** 页面提示对应选项加载失败
- **AND** 页面允许用户重试加载该选项
#### Scenario: 保存中
- **WHEN** 用户提交 Agent 表单后请求仍在进行中
- **THEN** 页面进入保存中状态
- **AND** 页面禁用重复提交
#### Scenario: 保存失败
- **WHEN** Agent 表单保存失败
- **THEN** 页面展示 `保存失败,请重试`
### Requirement: 保存成功后的返回行为
岗位 Agent 管理后台 SHALL 在保存成功后返回可预期的列表上下文。
#### Scenario: 新建成功
- **WHEN** 用户在新建页保存成功
- **THEN** 页面返回 `/agents`
- **AND** 页面恢复发起新建前的列表上下文
- **AND** 页面刷新列表页数据
#### Scenario: 编辑成功
- **WHEN** 用户在编辑页保存成功
- **THEN** 页面返回 `/agents`
- **AND** 页面优先恢复编辑前的列表上下文
- **AND** 如果编辑前打开了详情抽屉,则页面恢复对应详情抽屉状态
- **AND** 页面刷新列表页数据
#### Scenario: 取消编辑
- **WHEN** 用户在新建页或编辑页点击取消
- **THEN** 页面返回 `/agents`
- **AND** 页面不提交任何变更
## ADDED Requirements
### Requirement: Agent 新建入口
Agent 管理列表页 SHALL 提供进入 Agent 新建页的主入口。
#### Scenario: 打开列表页
- **WHEN** 已登录用户打开 Agent 管理列表页
- **THEN** 页面展示 `新建Agent` 主操作按钮
#### Scenario: 点击新建
- **WHEN** 用户点击 `新建Agent`
- **THEN** 页面进入 `/agents/new`
### Requirement: Agent 详情入口
Agent 管理列表页 SHALL 支持从列表行打开 Agent 详情抽屉。
#### Scenario: 点击查看
- **WHEN** 用户点击列表行的 `查看`
- **THEN** 页面打开对应 Agent 的详情抽屉
- **AND** 页面保留当前筛选、分页和滚动上下文
### Requirement: 详情抽屉关闭行为
Agent 管理列表页 SHALL 在详情抽屉关闭后返回关闭前的列表上下文。
#### Scenario: 关闭详情抽屉
- **WHEN** 用户关闭已打开的 Agent 详情抽屉
- **THEN** 页面回到列表可见状态
- **AND** 页面保留关闭前的筛选、分页和滚动位置
### Requirement: Agent 页面导航状态
Agent 管理列表页及其子页面 SHALL 保持 Agent 相关二级菜单的选中状态。
#### Scenario: 打开新建页
- **WHEN** 已登录用户访问 `/agents/new`
- **THEN** 左侧导航中 `Agent列表` 二级菜单保持选中状态
#### Scenario: 打开编辑页
- **WHEN** 已登录用户访问 `/agents/:agentId/edit`
- **THEN** 左侧导航中 `Agent列表` 二级菜单保持选中状态
## 1. 路由与页面骨架
- [x] 1.1 为 Agent 新建、编辑和详情抽屉补齐路由与入口承载方式,包含 `/agents/new`、`/agents/:agentId/edit` 和 `/agents?detail=:agentId`。
- [x] 1.2 搭建新建页、编辑页和详情抽屉的共享页面骨架,统一顶部返回区、标题、右侧取消/保存操作、返回逻辑,并让新建/编辑表单主体居中展示。
- [x] 1.3 补齐列表页到新建页、编辑页和详情抽屉的导航 helper,确保能恢复列表上下文。
- [x] 1.4 保持 `Agent列表` 二级菜单在 `/agents/new` 和 `/agents/:agentId/edit` 下的选中状态。
## 2. Mock 契约与状态模型
- [x] 2.1 定义 Agent 新建/编辑/详情所需的 mock 数据模型,包含 Agent 主数据、管家 Agent 标记、岗位标签、托管企微员工和 Skill 选项。
- [x] 2.2 补齐页面状态 fixtures,覆盖主数据加载中、选项加载失败、保存中、保存失败和详情抽屉关闭场景。
- [x] 2.3 补齐普通 Agent 与管家 Agent 的 mock 差异数据,覆盖固定字段、只读字段和非必填 Skill 规则。
- [x] 2.4 补齐托管企微员工按岗位联动的 mock 数据,覆盖岗位变更后重新加载和已挂载 Agent 员工置灰场景。
## 3. Agent 新建 / 编辑 / 详情实现
- [x] 3.1 实现共享 Agent 表单,覆盖名称、所属岗位、托管企微员工、描述、Skill 和状态字段,并适配顶部页头、右侧取消/保存按钮、居中表单布局,以及输入框和选择控件统一自适应、最大宽度 `450px` 的左右结构规范。
- [x] 3.2 实现表单校验与错误提示,覆盖必填项、长度限制和非管家 Agent 的 Skill 必填规则。
- [x] 3.3 实现管家 Agent 特殊编辑规则,锁定名称、岗位、托管企微员工和状态,仅保留可编辑字段。
- [x] 3.4 实现详情抽屉只读展示,并确保关闭后保留列表筛选、分页和滚动上下文。
- [x] 3.5 实现保存流程与返回规则,覆盖新建成功回到列表、编辑成功恢复来源上下文、保存失败提示和重复提交禁用。
- [x] 3.6 接通列表页入口,确保 Agent 名称点击、`查看` 和 `新建Agent` 都能进入正确页面或抽屉。
- [x] 3.7 实现编辑页详情预加载、所属岗位多选、托管企微员工联动刷新与岗位前置 tips、Skill tag 多选和状态默认停用。
- [x] 3.8 统一必填字段标签展示,确保状态字段也显示必填标签语义。
## 4. 测试与验证
- [x] 4.1 补充单元测试或组件测试,覆盖新建页、编辑页、详情抽屉、表单校验、管家 Agent 规则和保存结果。
- [x] 4.2 补充列表页联动测试,覆盖 `新建Agent`、名称点击、`查看`、抽屉关闭和上下文恢复。
- [x] 4.3 运行类型检查、相关测试和生产构建,确认无回归。
- [x] 4.4 在浏览器中验证关键流程,包括新建、编辑、详情抽屉、选项加载失败、保存失败、顶部返回按钮、右侧取消/保存按钮顺序、居中表单布局、表单字段左右结构与宽度规范、Skill tag 展示、托管企微员工岗位前置 tips,以及保存成功后的返回行为。
- [x] 4.5 验证新建/编辑成功后列表数据已刷新,且 `/agents/new` 与 `/agents/:agentId/edit` 下导航选中状态正确。
## Context
已归档的管理后台框架与 Agent 管理列表页提供了后台壳、路由、导航、列表页、搜索区、表格、分页和 mock 契约的落地方式;`skill-list-markdown-drawer` 已归档,可作为只读列表、状态组件和 mock fixture 的参考。`agent-create-edit-detail` 仍在修复中,本 change 不修改其范围。
本次只交付岗位标签自身管理。页面结构必须遵循 `docs/frontend-foundation.md`:列表页主操作在页头右上角,独立表单子页左侧为返回按钮和页面标题,右侧操作按钮固定为 `取消`、`保存`,且 `取消` 在前、`保存` 在后。
## Goals / Non-Goals
**Goals:**
- 新增 `/agent-tags` 岗位标签列表页,展示标签名称、标签编码、标签描述、使用 Agent 数、关联渠道活码数、关联官网 Tab 数、创建时间和操作。
- 新增 `/agent-tags/new` 独立新建页,支持标签名称、标签编码、标签描述表单校验和保存。
- 新增 `/agent-tags/:tagId/edit` 独立编辑页,支持标签名称、标签描述编辑,并将标签编码只读展示。
- 删除操作先检查岗位标签引用;被 Agent 使用时二次确认解除标签,被渠道活码或官网 Tab 引用时不可删除。
- 补充最小前端 mock 契约和可测试 fixture,不锁定后端接口路径、数据库结构或详情接口形态。
**Non-Goals:**
- 不实现渠道活码管理、官网配置管理或岗位标签在 Agent 表单中的联动。
- 不新增岗位标签详情接口。
- 不修改 `agent-create-edit-detail` 的 OpenSpec、页面范围或实现范围。
- 不扩展基础组件体系;如发现基础组件规则缺口,只记录为后续 foundation OpenSpec 候选。
- 不实现 Agent 表单联动页面;删除岗位标签时仅按引用检查结果确认 Agent 自动失去该标签。
## Decisions
### Decision: 新建和编辑使用独立表单页
岗位标签新建和编辑 SHALL 使用 `/agent-tags/new` 与 `/agent-tags/:tagId/edit` 独立页面,而不是列表页弹窗或抽屉。这样符合产品经理对独立表单页的要求,也能直接复用 `frontend-foundation.md` 的子页面布局规则。
替代方案是列表页弹窗或抽屉表单。该方案交互更轻,但与当前产品要求不一致,且不利于刷新、直达和后续表单复杂度扩展。
### Decision: 列表页和表单页操作按钮放在页头右上角
`/agent-tags` 页头右上角提供 `新建岗位标签`。`/agent-tags/new` 与 `/agent-tags/:tagId/edit` 页头右上角提供 `取消`、`保存`,顺序固定为 `取消` 在前、`保存` 在后;表单主体居中承载字段。
该决策保持后台页面的一致操作心智,避免在表单底部重复放置主要操作按钮造成分散。
### Decision: 编辑页不新增详情接口
编辑页不定义岗位标签详情接口。从列表点击 `编辑` 时,优先通过路由 state 携带当前行数据初始化表单;当用户刷新或直接访问编辑 URL 时,再从岗位标签列表 mock 数据源中按 `tagId` 查找当前记录。两种路径都只使用列表最小字段中的 `name`、`code`、`description` 初始化表单。
替代方案是新增详情 mock 契约。该方案会提前锁定后端详情接口形态,与本次“只定义本页面最小字段和状态”的约束冲突。
### Decision: 删除前使用引用检查结果做级联校验
删除点击后 MUST 先获取岗位标签引用详情,对齐 `packages/contracts/frontend-api-contract.md` 的 `### 5.4 检查岗位标签引用`。引用结果分为阻塞性引用和可解除引用:
- `blocking_references.qrcode_count > 0` 时 SHALL 阻断删除,并提示 `请先删除关联的渠道活码`。
- `blocking_references.official_tab_count > 0` 时 SHALL 阻断删除,并提示 `请先删除关联的官网 Tab 配置`。
- `detachable_references.agent_count > 0` 且没有阻塞性引用时 SHALL 允许用户继续确认,确认文案包含 `删除后这些 Agent 将失去该标签`。
- 全部阻塞引用解除后方可删除;仅 Agent 引用不阻塞删除,但删除必须经过明确确认。
该决策沿用既有前端契约对岗位标签引用检查的拆分:渠道活码和官网 Tab 是阻塞引用,Agent 是可解除引用。列表计数仍用于展示,但删除权限不只依赖列表计数,避免列表数据过期导致误删。
### Decision: mock 契约保持页面最小字段并补充引用检查 fixture
岗位标签列表项最小字段为 `tag_id`、`name`、`code`、`description`、`agent_count`、`channel_code_count`、`official_tab_count`、`created_at`。查询只保留 `keyword`、`page`、`pageSize`,表单 payload 只保留 `name`、`code`、`description`。
mock fixture 需要覆盖正常列表、空数据、筛选无结果、编码重复、删除可确认、仅 Agent 引用需确认、渠道活码引用阻断、官网 Tab 引用阻断、引用检查失败、加载失败和保存失败,以支撑 TDD 和浏览器验证。
## Risks / Trade-offs
- [Risk] 编辑页刷新时没有 route state,可能无法初始化表单。→ Mitigation: 从列表 mock 数据源按 `tagId` 兜底查找;未找到时展示错误状态和返回入口。
- [Risk] 现有 `frontend-api-contract.md` 已存在较宽泛的岗位标签草案。→ Mitigation: 本 change 只补充本页面消费的最小 mock 字段和状态,不声明后端最终接口。
- [Risk] 基础组件可能缺少独立表单页某些细节能力。→ Mitigation: 本 change 只复用既有组件和规则,缺口记录为后续 foundation OpenSpec,不在本业务 change 中发散。
- [Risk] 列表引用计数可能与删除时实际引用明细不一致。→ Mitigation: 删除交互以引用检查结果为准,列表计数只作为展示信息。
- [Risk] 用户可能误解 Agent 引用是否阻断删除。→ Mitigation: 仅 Agent 引用时必须展示 `删除后这些 Agent 将失去该标签` 的确认文案;渠道活码和官网 Tab 引用直接阻断并给出对应解除提示。
## Migration Plan
1. 先补充岗位标签最小 mock 契约与 fixture,并为 fixture 行为编写测试。
2. 注册 `/agent-tags`、`/agent-tags/new`、`/agent-tags/:tagId/edit` 路由和导航入口。
3. 用 TDD 实现列表页搜索、表格、分页、状态和删除引用检查交互。
4. 用 TDD 实现独立新建/编辑页、校验、只读编码和保存失败状态。
5. 运行类型检查、测试、构建,并在浏览器中验证三个路由的布局和关键交互。
## Open Questions
- 无。本 change 已确认新建/编辑采用独立表单页,表单操作位于页头右上角,编辑页不新增详情接口。
## Why
岗位标签目前只有需求草案和较宽泛的前端契约描述,后台缺少可操作的岗位标签管理入口。为了支撑后续 Agent、渠道活码和官网 Tab 使用岗位标签,需要先交付独立的岗位标签列表、新建、编辑和删除管理能力,并以最小 mock 契约沉淀页面字段与状态。
## What Changes
- 新增岗位标签管理列表页 `/agent-tags`,支持关键词搜索、表格展示、分页、新建入口、编辑入口和删除操作;删除前根据岗位标签引用检查结果处理 Agent 解除确认、渠道活码阻断和官网 Tab 阻断。
- 新增独立新建页 `/agent-tags/new`,按基础页面规则在页头右上角提供 `取消`、`保存` 操作。
- 新增独立编辑页 `/agent-tags/:tagId/edit`,按基础页面规则在页头右上角提供 `取消`、`保存` 操作,且标签编码只读。
- 补充岗位标签页面的最小前端 mock 契约和可测试 fixture,覆盖正常、空数据、筛选无结果、编码重复、删除确认、引用阻断、加载失败和保存失败等场景。
- 不实现渠道活码、官网配置或 Agent 表单联动,不新增岗位标签详情接口,不扩展基础组件体系。
## Capabilities
### New Capabilities
- `agent-tags-management`: 覆盖岗位标签列表、新建、编辑、删除、页面状态和本页面最小 mock 契约。
### Modified Capabilities
- 无。
## Impact
- 影响后台前端路由与导航:新增 `/agent-tags`、`/agent-tags/new`、`/agent-tags/:tagId/edit`。
- 影响页面实现:新增岗位标签列表页和独立表单页,复用现有搜索区、表格、分页、表单、按钮和状态组件规则。
- 影响前端 mock 契约:对齐 `packages/contracts/frontend-api-contract.md` 的岗位标签引用检查契约,并新增岗位标签 mock fixture。
- 影响测试:新增契约 fixture、路由、列表、表单、删除和状态场景测试。
## ADDED Requirements
### Requirement: 岗位标签管理路由与导航
岗位 Agent 管理后台 SHALL 提供岗位标签管理列表页和独立新建、编辑页面,并在后台导航中提供岗位标签管理入口。
#### Scenario: 打开岗位标签列表页
- **WHEN** 已登录用户打开 `/agent-tags`
- **THEN** 页面展示标题 `岗位标签管理`
- **AND** 页面展示标签名称搜索区、表格、分页和页头右上角 `新建岗位标签` 操作
#### Scenario: 从导航进入岗位标签管理
- **WHEN** 用户在后台导航中选择 `岗位标签管理`
- **THEN** 系统跳转到 `/agent-tags`
- **AND** 导航入口归属于 `Agent管理` 相关分组
#### Scenario: 打开独立新建页
- **WHEN** 用户打开 `/agent-tags/new`
- **THEN** 页面展示独立表单页标题 `新建岗位标签`
- **AND** 页头左侧展示返回入口
- **AND** 页头右上角按顺序展示 `取消` 和 `保存`
#### Scenario: 打开独立编辑页
- **WHEN** 用户打开 `/agent-tags/:tagId/edit`
- **THEN** 页面展示独立表单页标题 `编辑岗位标签`
- **AND** 页头左侧展示返回入口
- **AND** 页头右上角按顺序展示 `取消` 和 `保存`
### Requirement: 岗位标签名称搜索
岗位标签列表页 SHALL 允许用户通过标签名称搜索岗位标签。
#### Scenario: 搜索区遵循基础规则
- **WHEN** 页面渲染岗位标签搜索区
- **THEN** 搜索区布局遵循 `frontend-foundation.md` 中的搜索区域规则
- **AND** 标签名称输入框宽度为 `200px`
- **AND** 标签名称输入框 placeholder 为 `请输入标签名称`
- **AND** 页面不为本次范围额外引入不必要的下拉筛选项
#### Scenario: 提交标签名称搜索
- **WHEN** 用户输入标签名称并点击 `搜索`
- **THEN** 页面按标签名称刷新岗位标签列表
- **AND** 页面回到第 `1` 页
#### Scenario: 回车提交标签名称搜索
- **WHEN** 用户在标签名称输入框中输入内容并按下回车
- **THEN** 页面按标签名称刷新岗位标签列表
- **AND** 页面回到第 `1` 页
#### Scenario: 重置关键词
- **WHEN** 用户点击 `重置`
- **THEN** 页面清空关键词输入
- **AND** 页面恢复默认岗位标签列表并回到第 `1` 页
### Requirement: 岗位标签表格与分页
岗位标签列表页 SHALL 以表格展示岗位标签信息,并使用分页展示列表结果。
#### Scenario: 展示岗位标签行
- **WHEN** 岗位标签列表存在数据
- **THEN** 每行展示 `标签名称`、`标签编码`、`标签描述`、`使用 Agent 数`、`关联渠道活码数`、`关联官网 Tab 数`、`创建时间` 和 `操作`
- **AND** 操作列展示 `编辑` 和 `删除`
#### Scenario: 切换分页
- **WHEN** 用户切换页码或每页条数
- **THEN** 页面按新的分页参数展示岗位标签列表
- **AND** 每页条数变化后页面回到第 `1` 页
#### Scenario: 筛选无结果
- **WHEN** 当前标签名称没有匹配的标签
- **THEN** 页面展示筛选无结果状态
- **AND** 页面允许用户调整标签名称或重置搜索
### Requirement: 岗位标签新建表单
岗位标签管理 SHALL 支持通过独立新建页创建岗位标签。
#### Scenario: 新建页字段
- **WHEN** 用户打开 `/agent-tags/new`
- **THEN** 表单展示 `标签名称`、`标签编码` 和 `标签描述`
- **AND** `标签名称` 和 `标签编码` 为必填字段
- **AND** `标签编码` 在新建页可编辑
#### Scenario: 新建页保存成功
- **WHEN** 用户填写合法且不重复的标签名称、标签编码和标签描述后点击 `保存`
- **THEN** 系统保存岗位标签 mock 数据
- **AND** 页面返回 `/agent-tags`
#### Scenario: 新建页取消
- **WHEN** 用户在新建页点击 `取消`
- **THEN** 页面返回 `/agent-tags`
- **AND** 系统不保存当前表单修改
### Requirement: 岗位标签编辑表单
岗位标签管理 SHALL 支持通过独立编辑页编辑岗位标签名称和描述,并保持标签编码不可修改。
#### Scenario: 从列表行进入编辑页
- **WHEN** 用户在岗位标签列表点击某行 `编辑`
- **THEN** 系统跳转到 `/agent-tags/:tagId/edit`
- **AND** 编辑页优先使用该行数据初始化 `标签名称`、`标签编码` 和 `标签描述`
#### Scenario: 刷新或直达编辑页
- **WHEN** 用户刷新或直接打开 `/agent-tags/:tagId/edit`
- **THEN** 编辑页从岗位标签列表 mock 数据源中按 `tagId` 查找当前记录
- **AND** 找到记录后使用列表最小字段初始化表单
#### Scenario: 编辑页不依赖详情接口
- **WHEN** 编辑页初始化表单
- **THEN** 系统不要求岗位标签详情接口或详情 mock 契约
- **AND** 表单初始值仅来自列表行数据或列表 mock 数据源兜底结果
#### Scenario: 编辑页编码只读
- **WHEN** 用户打开编辑页
- **THEN** `标签编码` 展示为只读
- **AND** 用户不能修改标签编码
#### Scenario: 编辑页保存成功
- **WHEN** 用户修改合法的标签名称或标签描述后点击 `保存`
- **THEN** 系统保存岗位标签 mock 数据
- **AND** 页面返回 `/agent-tags`
#### Scenario: 编辑页记录不存在
- **WHEN** 用户打开不存在的 `/agent-tags/:tagId/edit`
- **THEN** 页面展示可恢复的未找到或错误状态
- **AND** 页面提供返回列表入口
### Requirement: 岗位标签表单校验与保存失败
岗位标签新建和编辑表单 SHALL 对字段规则和保存失败状态提供明确反馈。
#### Scenario: 标签名称必填
- **WHEN** 用户未填写 `标签名称` 并点击 `保存`
- **THEN** 页面提示 `请输入标签名称`
- **AND** 系统不提交保存
#### Scenario: 标签名称长度限制
- **WHEN** 用户填写超过 20 字的 `标签名称` 并点击 `保存`
- **THEN** 页面提示 `标签名称最多20字`
- **AND** 系统不提交保存
#### Scenario: 标签编码必填
- **WHEN** 用户在新建页未填写 `标签编码` 并点击 `保存`
- **THEN** 页面提示 `请输入标签编码`
- **AND** 系统不提交保存
#### Scenario: 标签编码格式限制
- **WHEN** 用户在新建页填写非英文或非下划线字符的 `标签编码` 并点击 `保存`
- **THEN** 页面提示 `标签编码仅支持英文和下划线`
- **AND** 系统不提交保存
#### Scenario: 标签编码不可重复
- **WHEN** 用户在新建页填写已存在的 `标签编码` 并点击 `保存`
- **THEN** 页面提示 `标签编码已存在`
- **AND** 系统不提交保存
#### Scenario: 标签描述长度限制
- **WHEN** 用户填写超过 100 字的 `标签描述` 并点击 `保存`
- **THEN** 页面提示 `标签描述最多100字`
- **AND** 系统不提交保存
#### Scenario: 保存失败
- **WHEN** mock 保存岗位标签失败
- **THEN** 页面提示 `保存失败,请重试`
- **AND** 页面停留在当前表单页
### Requirement: 岗位标签删除引用检查
岗位标签列表页 SHALL 在删除前检查岗位标签引用,并根据 Agent、渠道活码和官网 Tab 引用结果执行确认或阻断。
#### Scenario: 删除前检查引用
- **WHEN** 用户点击岗位标签的 `删除`
- **THEN** 页面先获取该岗位标签的引用检查结果
- **AND** 引用检查结果包含阻塞性引用和可解除的 Agent 引用
#### Scenario: 无引用时确认删除
- **WHEN** 引用检查结果中不存在 Agent、渠道活码和官网 Tab 引用
- **THEN** 页面展示删除二次确认
- **AND** 用户确认后系统从 mock 数据中移除该标签并刷新列表
#### Scenario: 取消删除
- **WHEN** 用户在删除确认中取消
- **THEN** 系统不删除岗位标签
- **AND** 列表保持当前数据
#### Scenario: Agent 引用需确认解除
- **WHEN** 引用检查结果仅包含 Agent 引用
- **THEN** 页面允许继续删除确认
- **AND** 确认文案包含 `删除后这些 Agent 将失去该标签`
- **AND** 用户确认后系统删除岗位标签并使这些 Agent 失去该标签
#### Scenario: 被渠道活码引用不可删除
- **WHEN** 引用检查结果包含渠道活码引用
- **THEN** 页面阻断删除
- **AND** 页面提示 `请先删除关联的渠道活码`
#### Scenario: 被官网 Tab 引用不可删除
- **WHEN** 引用检查结果包含官网 Tab 引用
- **THEN** 页面阻断删除
- **AND** 页面提示 `请先删除关联的官网 Tab 配置`
#### Scenario: 同时存在阻塞引用和 Agent 引用
- **WHEN** 引用检查结果同时包含 Agent 引用以及渠道活码或官网 Tab 引用
- **THEN** 页面阻断删除
- **AND** 页面优先提示需要先删除关联的渠道活码或官网 Tab 配置
- **AND** 系统不进入 Agent 解除确认
#### Scenario: 引用全部解除后方可删除
- **WHEN** 渠道活码和官网 Tab 引用已全部解除
- **THEN** 页面允许按无引用或仅 Agent 引用流程继续删除
#### Scenario: 引用检查失败
- **WHEN** 删除前引用检查失败
- **THEN** 页面不删除岗位标签
- **AND** 页面展示可恢复的失败提示
### Requirement: 岗位标签页面状态
岗位标签管理 SHALL 提供正常列表、空数据、筛选无结果、加载失败、保存失败和编辑记录不存在等状态。
#### Scenario: 正常列表
- **WHEN** mock 数据源返回岗位标签列表
- **THEN** 页面展示表格行和分页信息
#### Scenario: 空数据
- **WHEN** mock 数据源没有任何岗位标签
- **THEN** 页面展示空数据状态
- **AND** 页面保留 `新建岗位标签` 入口
#### Scenario: 列表加载失败
- **WHEN** mock 数据源加载岗位标签列表失败
- **THEN** 页面展示加载失败状态
- **AND** 页面提供重试操作
### Requirement: 岗位标签最小 mock 契约
前端 mock 契约 SHALL 提供岗位标签管理页面需要的最小字段、查询参数、表单 payload 和状态 fixture,并且不锁定后端实现。
#### Scenario: 消费岗位标签列表项
- **WHEN** 页面渲染岗位标签列表 mock
- **THEN** 列表项包含 `tag_id`、`name`、`code`、`description`、`agent_count`、`channel_code_count`、`official_tab_count` 和 `created_at`
#### Scenario: 消费岗位标签查询参数
- **WHEN** 页面查询岗位标签列表 mock
- **THEN** 查询参数仅要求支持 `keyword`、`page` 和 `pageSize`
- **AND** `keyword` 仅匹配标签名称
#### Scenario: 消费岗位标签表单 payload
- **WHEN** 页面保存岗位标签 mock
- **THEN** 表单 payload 仅包含 `name`、`code` 和 `description`
#### Scenario: 不定义详情契约
- **WHEN** 页面进入编辑流程
- **THEN** mock 契约不要求岗位标签详情接口
- **AND** 编辑页使用列表行数据或列表 mock 数据源兜底初始化表单
#### Scenario: 消费岗位标签引用检查 fixture
- **WHEN** 页面执行岗位标签删除前引用检查
- **THEN** mock 契约提供与 `GET /api/v1/position-tags/{tag_id}/references` 对齐的最小引用检查结果
- **AND** 引用检查结果区分 `blocking_references` 和 `detachable_references`
#### Scenario: 消费岗位标签页面状态 fixtures
- **WHEN** 测试或本地开发需要岗位标签页面状态
- **THEN** mock 契约提供正常列表、空数据、筛选无结果、编码重复、删除可确认、仅 Agent 引用需确认、被渠道活码引用不可删除、被官网 Tab 引用不可删除、引用检查失败、加载失败和保存失败 fixtures
### Requirement: 基础组件复用约束
岗位标签管理 SHALL 复用既有前端基础组件和 `frontend-foundation.md` 页面规则,不在本 change 中发散基础组件体系。
#### Scenario: 复用既有组件
- **WHEN** 页面实现搜索区、表格、分页、表单、按钮和状态反馈
- **THEN** 页面优先复用现有内部组件和基础页面规则
#### Scenario: 基础组件规则存在缺口
- **WHEN** 实现过程中发现现有基础组件或 `frontend-foundation.md` 规则无法覆盖岗位标签页面细节
- **THEN** 只记录为后续 foundation OpenSpec 候选
- **AND** 不在本业务 change 中扩展基础组件体系
## 1. 契约与 mock fixture
- [x] 1.1 更新岗位标签前端最小 mock 契约说明,明确列表项、查询参数、表单 payload、无详情接口、引用检查和页面状态边界。
- [x] 1.2 新增岗位标签 mock fixture 与 mock 操作模块,覆盖正常列表、空数据、筛选无结果、编码重复、删除可确认、仅 Agent 引用需确认、渠道活码引用阻断、官网 Tab 引用阻断、引用检查失败、加载失败和保存失败。
- [x] 1.3 先编写岗位标签 mock fixture 测试,覆盖标签名称过滤、分页、编码唯一性、引用检查、Agent 引用确认、阻塞引用判断和保存失败场景。
## 2. 路由与导航
- [x] 2.1 先编写路由和导航测试,覆盖 `/agent-tags`、`/agent-tags/new`、`/agent-tags/:tagId/edit` 可访问和导航入口可见。
- [x] 2.2 注册岗位标签列表页、新建页、编辑页路由,并在 `Agent管理` 相关导航分组中新增 `岗位标签管理` 入口。
- [x] 2.3 确保本 change 不修改 `agent-create-edit-detail` 范围内的路由、页面和契约。
## 3. 列表页
- [x] 3.1 先编写岗位标签列表页测试,覆盖标题、页头右上角 `新建岗位标签`、搜索区、表格列、分页和行操作。
- [x] 3.2 实现 `/agent-tags` 列表页,复用 `frontend-foundation.md` 的列表页、搜索区、表格、分页和状态组件规则。
- [x] 3.3 实现标签名称搜索和重置,标签名称匹配标签名称字段,搜索或重置后回到第 `1` 页。
- [x] 3.4 实现正常列表、空数据、筛选无结果和加载失败状态,加载失败提供重试入口。
## 4. 新建与编辑表单页
- [x] 4.1 先编写岗位标签新建页测试,覆盖独立页面结构、页头右上角 `取消`/`保存`、字段校验、编码重复、保存成功和保存失败。
- [x] 4.2 先编写岗位标签编辑页测试,覆盖从列表行数据初始化、刷新或直达时按 `tagId` 从列表 mock 数据源兜底、编码只读、记录不存在状态和保存成功。
- [x] 4.3 实现 `/agent-tags/new` 独立新建页,表单字段为标签名称、标签编码、标签描述,保存成功后返回列表。
- [x] 4.4 实现 `/agent-tags/:tagId/edit` 独立编辑页,不新增详情接口,优先使用路由 state 当前行数据,缺失时按 `tagId` 从列表 mock 数据源兜底查找。
- [x] 4.5 实现表单校验:标签名称必填且最多 20 字,标签编码必填且仅英文和下划线且不可重复,标签描述最多 100 字,编辑页标签编码只读。
- [x] 4.6 实现表单页 `取消` 返回列表且不保存,`保存` 失败时停留当前页面并展示 `保存失败,请重试`。
## 5. 删除交互
- [x] 5.1 先编写删除交互测试,覆盖删除前引用检查、无引用二次确认、取消删除、确认删除刷新列表、仅 Agent 引用时提示 `删除后这些 Agent 将失去该标签`、渠道活码引用阻断、官网 Tab 引用阻断和引用检查失败。
- [x] 5.2 实现列表行删除操作,点击删除后先获取岗位标签引用检查结果,再根据结果进入确认或阻断流程。
- [x] 5.3 实现仅 Agent 引用时的删除确认,用户确认后从 mock 数据中移除标签并模拟这些 Agent 失去该标签。
- [x] 5.4 实现渠道活码引用阻断提示 `请先删除关联的渠道活码`。
- [x] 5.5 实现官网 Tab 引用阻断提示 `请先删除关联的官网 Tab 配置`。
## 6. 验证
- [x] 6.1 运行岗位标签相关测试,确认 TDD 场景通过。
- [x] 6.2 运行 `npm run typecheck`。
- [x] 6.3 运行 `npm test`。
- [x] 6.4 运行 `npm run build`。
- [x] 6.5 使用浏览器验证 `/agent-tags`、`/agent-tags/new`、`/agent-tags/:tagId/edit` 的布局、页头操作、搜索、保存和删除关键交互。
- [x] 6.6 更新 OpenSpec task 状态,并确认代码、测试和规范对齐后再进入归档阶段。
## Context
项目已完成并归档登录、管理后台框架、Agent 管理列表页、mock 最小契约,以及 `skill-list-markdown-drawer`。`agent-create-edit-detail` 仍有少量问题修复中,因此本次只新增官网配置下的方法论展示配置页,不修改 Agent 创建、编辑、详情相关范围。
当前前端已有 AdminShell、基础表单、开关、上传、状态提示和 mock 契约沉淀。本次实现应复用这些基础能力,并把官网方法论配置控制在一个独立页面和最小契约内。
## Goals / Non-Goals
**Goals:**
- 新增 `/official-site/methodology` 独立配置页。
- 菜单归属为「官网配置 > 方法论展示配置」。
- 支持展示状态、主标题、副标题和步骤列表配置。
- 支持步骤新增、删除、上移/下移排序。
- 支持步骤图标和内容图的页面级 mock 配置。
- 支持内容图 PNG/JPG/JPEG/GIF、最大 10MB 的前端校验。
- 补充本页所需最小 mock 契约和 fixture。
- 使用 TDD 覆盖加载、校验、上传 mock、保存成功与失败等状态。
**Non-Goals:**
- 不实现 H5 官网页面的展示效果。
- 不实现岗位展示配置、Agent 展示配置或渠道活码配置。
- 不接入真实文件服务或真实后端。
- 不抽象通用官网配置框架。
- 不重构现有上传、表单、开关、状态提示等基础组件。
## Decisions
### 1. 独立配置页而非通用官网配置框架
采用 `/official-site/methodology` 独立页面承载本次能力。这样可以快速锁定本页字段、校验、状态和 mock 契约,不把尚未确认的岗位展示、Agent 展示、渠道活码等配置提前抽象进来。
备选方案是先抽象官网配置框架,但当前只有方法论配置已明确,过早抽象会扩大范围并增加与未来需求冲突的风险。
### 2. 最小数据模型
页面数据使用 `display_status`、`title`、`subtitle`、`steps` 表达。步骤内只保留 `step_id`、`icon`、`name`、`content_image`、`sort_order` 等后台配置页需要的字段。
步骤图标是每个方法论步骤的展示图标资源,不是上传进度图。上传进度、失败、重试等属于上传控件临时 UI 状态,不写入配置数据。
### 3. 页面级上传 mock 和校验
内容图上传只在前端完成 mock 选择、格式校验、大小校验和失败状态模拟,不请求真实文件服务。图片资源只保留最小字段:`id`、`name`、`url`、`mime_type`、`size_bytes`。
如果现有上传组件不能直接覆盖全部错误展示,本次优先在页面级组合现有组件补齐,不把问题发散成通用上传组件重构。
### 4. 排序使用上移/下移
步骤排序采用上移/下移按钮实现。该方式满足「调整步骤排序」要求,交互稳定、可键盘操作、可测试,不引入拖拽依赖。
备选方案是拖拽排序,但当前基础组件未确认提供拖拽能力,引入拖拽会超出本次最小实现边界。
### 5. 展示状态与步骤为空的保存规则
页面允许加载和展示步骤为空的配置。展示状态开启时,保存必须至少存在一个完整步骤;展示状态关闭时允许步骤为空,但主标题、副标题和已有步骤字段仍需满足校验。
这样可以覆盖「关闭展示」和「步骤为空」两个 mock 场景,同时避免开启展示时保存无可展示内容。
## Risks / Trade-offs
- 步骤图标的真实素材来源尚未确定 → 本次只定义页面级 mock 上传或选择后的最小资源结构,不锁定后端素材库。
- 上移/下移不如拖拽直观 → 换取更低实现风险和更稳定测试;若后续确认拖拽组件,再通过新 OpenSpec 扩展。
- 关闭展示时允许步骤为空可能与未来后端规则不同 → 本次以前端后台配置页可测行为为准,不锁定服务端实现。
- 上传不接真实服务 → 本次只保证后台表单、校验和 mock 状态,真实上传联调需后续单独规范。
## Migration Plan
- 新增页面、路由、菜单和 mock 契约,不迁移已有数据。
- 若本次实现出现问题,可移除新增路由入口和 mock fixture 回退,不影响现有 Agent 与 Skill 页面。
## Open Questions
- 无阻塞问题。真实文件服务、官网 H5 展示效果和拖拽排序如需落地,应另开 OpenSpec。
## Why
官网配置需要一个后台入口来维护官网方法论模块的展示内容。当前项目已有管理后台框架和基础 mock 契约,但缺少方法论展示配置页,无法在后台验证该模块的数据结构、表单校验和保存行为。
## What Changes
- 新增独立配置页 `/official-site/methodology`,归属菜单「官网配置 > 方法论展示配置」。
- 新增方法论配置表单,包含展示状态、主标题、副标题和步骤列表。
- 支持步骤新增、删除、上移/下移排序。
- 支持每个步骤配置步骤图标、步骤名称和内容图。
- 内容图上传只做前端 mock 与校验,支持 PNG/JPG/JPEG/GIF,最大 10MB,使用缩略图预览方式展示。
- 补充本配置页需要的最小前端 mock 契约和 fixture。
- 覆盖正常配置、关闭展示、步骤为空、图片上传失败、图片格式错误、图片过大、保存失败、加载失败等 mock 场景。
- 不实现 H5 官网页面展示效果,不处理岗位展示配置、Agent 展示配置、渠道活码或真实文件服务。
## Capabilities
### New Capabilities
- `official-site-methodology-config`: 后台官网配置下的方法论展示配置页、页面级 mock 契约、表单校验和保存状态。
### Modified Capabilities
- 无。
## Impact
- 影响前端路由、管理后台菜单与面包屑。
- 影响本项目前端 mock 数据、mock 状态和 fixture。
- 影响 `packages/contracts/frontend-api-contract.md` 或相邻契约模块,新增本页最小契约说明。
- 影响相关页面测试、契约测试或 mock fixture 测试。
- 不引入真实后端、真实文件上传服务或新的通用组件重构。
## ADDED Requirements
### Requirement: 方法论展示配置页入口
系统 SHALL 在管理后台提供官网配置下的方法论展示配置页入口。
#### Scenario: 访问方法论展示配置路由
- **WHEN** 用户访问 `/official-site/methodology`
- **THEN** 系统 SHALL 展示方法论展示配置页
- **AND** 页面 SHALL 位于管理后台布局内
#### Scenario: 菜单归属正确
- **WHEN** 用户查看后台导航菜单
- **THEN** 系统 SHALL 在「官网配置」下提供「方法论展示配置」入口
- **AND** 当前页 SHALL 能体现该菜单归属或面包屑关系
### Requirement: 配置表单字段
系统 SHALL 在方法论展示配置页提供展示状态、主标题、副标题和步骤列表配置能力。
#### Scenario: 展示基础字段
- **WHEN** 配置加载成功
- **THEN** 系统 SHALL 展示展示状态开关、主标题输入框、副标题文本域和步骤配置区
#### Scenario: 展示状态字段
- **WHEN** 用户编辑展示状态
- **THEN** 系统 SHALL 支持 `enable` 和 `disable` 两种状态
- **AND** 展示状态 SHALL 为必填配置
#### Scenario: 主标题校验
- **WHEN** 用户保存空主标题或超过 30 字的主标题
- **THEN** 系统 SHALL 阻止保存
- **AND** 系统 SHALL 在主标题字段附近展示校验错误
#### Scenario: 副标题校验
- **WHEN** 用户保存空副标题或超过 100 字的副标题
- **THEN** 系统 SHALL 阻止保存
- **AND** 系统 SHALL 在副标题字段附近展示校验错误
### Requirement: 步骤配置
系统 SHALL 支持方法论步骤的添加、删除、排序和步骤字段校验。
#### Scenario: 添加步骤
- **WHEN** 用户点击「添加步骤」
- **THEN** 系统 SHALL 在步骤列表中新增一个可编辑步骤
- **AND** 新步骤 SHALL 可配置步骤图标、步骤名称和内容图
#### Scenario: 删除步骤
- **WHEN** 用户删除一个步骤
- **THEN** 系统 SHALL 从步骤列表移除该步骤
- **AND** 系统 SHALL 重新维护剩余步骤的排序序号
#### Scenario: 调整步骤排序
- **WHEN** 用户对步骤执行上移或下移
- **THEN** 系统 SHALL 调整步骤顺序
- **AND** 系统 SHALL 重新维护步骤排序序号
#### Scenario: 步骤名称校验
- **WHEN** 用户保存空步骤名称或超过 20 字的步骤名称
- **THEN** 系统 SHALL 阻止保存
- **AND** 系统 SHALL 在对应步骤名称字段附近展示校验错误
#### Scenario: 开启展示时步骤为空
- **WHEN** 展示状态为 `enable` 且步骤列表为空时用户保存
- **THEN** 系统 SHALL 阻止保存
- **AND** 系统 SHALL 提示至少添加一个方法论步骤
#### Scenario: 关闭展示时步骤为空
- **WHEN** 展示状态为 `disable` 且步骤列表为空时用户保存
- **THEN** 系统 SHALL 允许保存基础配置
- **AND** 系统 SHALL 不要求新增步骤
### Requirement: 步骤图标配置
系统 SHALL 支持为每个方法论步骤配置展示图标资源,步骤图标 SHALL 不表示上传进度。
#### Scenario: 步骤图标必填
- **WHEN** 用户保存缺少步骤图标的步骤
- **THEN** 系统 SHALL 阻止保存
- **AND** 系统 SHALL 在对应步骤图标配置区展示校验错误
#### Scenario: 步骤图标资源语义
- **WHEN** 用户完成步骤图标配置
- **THEN** 系统 SHALL 将其作为该步骤的展示图标资源保存到配置数据
- **AND** 系统 SHALL NOT 将上传进度、上传中、重试等临时状态保存为步骤图标数据
### Requirement: 内容图上传校验
系统 SHALL 对每个步骤的内容图执行前端 mock 上传和校验。
#### Scenario: 内容图必填
- **WHEN** 用户保存缺少内容图的步骤
- **THEN** 系统 SHALL 阻止保存
- **AND** 系统 SHALL 在对应内容图上传区展示校验错误
#### Scenario: 图片格式错误
- **WHEN** 用户选择非 PNG/JPG/JPEG/GIF 的内容图文件
- **THEN** 系统 SHALL 拒绝该文件
- **AND** 系统 SHALL 展示图片格式错误提示
#### Scenario: 图片过大
- **WHEN** 用户选择超过 10MB 的内容图文件
- **THEN** 系统 SHALL 拒绝该文件
- **AND** 系统 SHALL 展示图片过大提示
#### Scenario: 图片上传失败
- **WHEN** mock 上传返回失败
- **THEN** 系统 SHALL 展示图片上传失败状态
- **AND** 系统 SHALL 允许用户重新选择或重试
### Requirement: 页面状态与保存行为
系统 SHALL 覆盖方法论展示配置页的加载、保存和错误状态。
#### Scenario: 正常配置加载
- **WHEN** mock 返回正常配置
- **THEN** 系统 SHALL 使用返回数据填充配置表单和步骤列表
#### Scenario: 关闭展示配置加载
- **WHEN** mock 返回 `display_status=disable`
- **THEN** 系统 SHALL 将展示状态开关呈现为关闭
- **AND** 系统 SHALL 允许用户继续编辑并保存配置
#### Scenario: 步骤为空配置加载
- **WHEN** mock 返回空步骤列表
- **THEN** 系统 SHALL 展示空步骤状态
- **AND** 系统 SHALL 提供添加步骤入口
#### Scenario: 加载失败
- **WHEN** mock 返回加载失败
- **THEN** 系统 SHALL 展示加载失败状态
- **AND** 系统 SHALL 提供重试入口
#### Scenario: 保存成功
- **WHEN** 用户提交合法配置且 mock 保存成功
- **THEN** 系统 SHALL 展示保存成功反馈
- **AND** 系统 SHALL 防止保存期间重复提交
#### Scenario: 保存失败
- **WHEN** 用户提交合法配置但 mock 保存失败
- **THEN** 系统 SHALL 展示保存失败提示
- **AND** 系统 SHALL 保留用户当前编辑内容以便重试
### Requirement: 最小前端 mock 契约
系统 SHALL 为方法论展示配置页提供最小前端 mock 契约和可测试 fixture,且 SHALL NOT 锁定后端实现。
#### Scenario: 配置读取契约
- **WHEN** 页面请求方法论配置
- **THEN** mock 契约 SHALL 能表达加载成功、加载失败和配置数据
- **AND** 配置数据 SHALL 包含展示状态、主标题、副标题和步骤列表
#### Scenario: 配置保存契约
- **WHEN** 页面保存方法论配置
- **THEN** mock 契约 SHALL 能表达保存请求数据、保存成功和保存失败
- **AND** 保存请求 SHALL 只包含本配置页需要的最小字段
#### Scenario: fixture 覆盖
- **WHEN** 测试读取方法论配置 mock fixture
- **THEN** fixture SHALL 覆盖正常配置、关闭展示、步骤为空、图片上传失败、图片格式错误、图片过大、保存失败和加载失败
## 1. 契约与 Mock
- [x] 1.1 在前端契约文档或相邻契约模块中补充方法论展示配置的最小字段、状态和错误场景。
- [x] 1.2 准备方法论配置 mock fixture,覆盖正常配置、关闭展示、步骤为空、加载失败、保存失败、图片上传失败、图片格式错误和图片过大。
- [x] 1.3 为 mock 契约或 fixture 增加可执行测试,先验证 fixture 字段、状态枚举和错误场景可用。
## 2. 路由与导航
- [x] 2.1 新增 `/official-site/methodology` 路由并挂载到管理后台布局内。
- [x] 2.2 在后台导航中新增「官网配置 > 方法论展示配置」入口,并保持现有 Agent、Skill 范围不受影响。
- [x] 2.3 补充路由和导航相关测试,验证入口、页面归属和默认跳转不回归。
## 3. 页面表单
- [x] 3.1 先编写页面表单测试,覆盖基础字段渲染、正常配置回填、关闭展示和步骤为空。
- [x] 3.2 实现方法论展示配置页,复用现有表单、开关、按钮、状态提示和上传基础能力。
- [x] 3.3 实现主标题、副标题和展示状态字段校验。
- [x] 3.4 实现步骤添加、删除、上移、下移以及 `sort_order` 维护。
## 4. 上传与保存
- [x] 4.1 先编写上传与保存测试,覆盖步骤图标必填、内容图必填、格式错误、图片过大、mock 上传失败、保存成功和保存失败。
- [x] 4.2 实现步骤图标页面级 mock 配置,确保它表达展示图标资源而不是上传进度。
- [x] 4.3 实现内容图 PNG/JPG/JPEG、最大 10MB 的前端 mock 校验。
- [x] 4.4 实现保存行为、保存中禁用重复提交、成功反馈和失败恢复。
## 5. 状态与验证
- [x] 5.1 实现加载中、加载失败、重试、空步骤和错误提示状态。
- [x] 5.2 运行 `npm run typecheck`。
- [x] 5.3 运行 `npm test`。
- [x] 5.4 运行 `npm run build`。
- [x] 5.5 使用浏览器验证 `/official-site/methodology` 的布局、字段校验、步骤操作、上传错误和保存状态。
## Context
已归档的管理后台框架与 Agent 管理列表页提供了后台壳、路由、导航、列表页、搜索区、表格、分页和 mock 契约的落地方式;`agent-tags-management` 已归档,可作为岗位管理相关页面的参考。`frontend-foundation.md` 已确立列表页、搜索区、表格、分页、状态组件和页面布局规则。
本次只交付渠道活码自身管理。页面结构必须遵循 `docs/frontend-foundation.md`:列表页主操作在页头右上角,独立表单子页左侧为返回按钮和页面标题,右侧操作按钮固定为 `取消`、`保存`,且 `取消` 在前、`保存` 在后。
## Goals / Non-Goals
**Goals:**
- 新增 `/channel-codes` 渠道活码列表页,展示活码名称、对应岗位、渠道编码、承接员工、关联 Agent、状态、创建时间和操作。
- 新增 `/channel-codes/new` 独立新建页,支持活码名称、对应岗位、活码描述、自动欢迎语、状态表单校验和保存。
- 新增 `/channel-codes/:codeId/edit` 独立编辑页,支持活码名称、活码描述、自动欢迎语、状态编辑,岗位和派生字段只读展示。
- 新增查看抽屉,展示渠道活码详情和二维码图片。
- 实现启用和停用操作,支持二次确认和业务阻断提示。
- 补充最小前端 mock 契约和可测试 fixture,不锁定后端接口路径、数据库结构或详情接口形态。
**Non-Goals:**
- 不实现岗位标签管理、Agent 表单联动或官网配置管理。
- 不新增渠道活码详情接口。
- 不修改其他已归档 OpenSpec 的页面范围或实现范围。
- 不扩展基础组件体系;如发现基础组件规则缺口,只记录为后续 foundation OpenSpec 候选。
## Decisions
### Decision: 新建和编辑使用独立表单页
渠道活码新建和编辑 SHALL 使用 `/channel-codes/new` 与 `/channel-codes/:codeId/edit` 独立页面,而不是列表页弹窗或抽屉。这样符合产品经理对独立表单页的要求,也能直接复用 `frontend-foundation.md` 的子页面布局规则。
### Decision: 查看使用抽屉而不是独立页面
渠道活码查看 SHALL 使用抽屉而不是独立页面。详情展示为只读信息加二维码图片,不需要复杂表单交互,抽屉更符合轻量查看场景。
### Decision: 一岗一码限制
新建渠道活码时 SHALL 限制每个岗位只能创建一个渠道活码。已创建渠道活码的岗位在新建页岗位选择中不可再次选择。
### Decision: 派生字段自动展示
新建页选择岗位后 SHALL 自动展示渠道编码、承接员工和关联 Agent。这些字段由岗位派生,用户不可编辑。
### Decision: 状态默认停用
新建渠道活码时状态 SHALL 默认为停用。启用状态需要用户手动切换。
### Decision: 启停二次确认
启用和停用操作 SHALL 先展示二次确认。确认后更新状态并刷新列表。
### Decision: 停用业务阻断
当渠道活码被官网引用时,停用操作 SHALL 展示业务阻断提示,不更新状态。
\ No newline at end of file \ No newline at end of file
## Proposal: 渠道活码管理
在 `Agent群管理` 一级菜单下新增 `渠道活码` 二级菜单,提供渠道活码列表页、新建页、编辑页和查看抽屉。
### Pages
| Route | Title | Description |
|-------|-------|-------------|
| `/channel-codes` | 渠道活码 | 渠道活码列表页,支持搜索、筛选、分页、查看、编辑、启停 |
| `/channel-codes/new` | 新增员工渠道活码 | 独立新建页,一岗一码限制,派生字段自动展示 |
| `/channel-codes/:codeId/edit` | 编辑员工渠道活码 | 独立编辑页,岗位和派生字段只读 |
| `/channel-codes/:codeId` (drawer) | 活码详情 | 查看抽屉,展示详情和二维码 |
### Mock Contract
- 列表项字段:`code_id`, `code_name`, `position_code`, `position_name`, `channel_code`, `employee_name`, `employee_role_text`, `agent_names`, `status`, `created_at`, `operations`
- 详情字段:列表项字段 + `qrcode_url`, `description`, `welcome_message`, `updated_at`
- 查询参数:`keyword`, `position_code`, `status`, `page`, `pageSize`
- 表单 payload:`code_name`, `position_code` (新建), `description`, `welcome_message`, `status`
- 岗位派生信息:`channel_code`, `employee_name`, `employee_role_text`, `agent_names`, `employee_id`
- Fixtures:正常列表、空列表、筛选无结果、加载失败、分页边界、已启用、已停用、岗位已有活码、保存成功、保存失败、停用成功、停用业务阻断、二维码加载失败
### Validation Rules
- 活码名称:必填,最多 50 字
- 对应岗位:必选(新建),一岗一码限制
- 活码描述:最多 200 字
- 自动欢迎语:最多 500 字
- 状态:默认停用,必填
### Dependencies
- 复用 `frontend-foundation.md` 页面布局规则
- 复用既有 Button, Input, Select, Switch, Table, Pagination, Drawer, Popconfirm, StatePlaceholder, Tag 组件
- 不新增基础组件
\ No newline at end of file \ No newline at end of file
## ADDED Requirements
### Requirement: 渠道活码路由与导航
后台前端 SHALL 提供渠道活码列表页、独立新建页、独立编辑页,并在一级菜单 `Agent群管理` 下提供二级菜单 `渠道活码` 入口。
#### Scenario: 打开渠道活码列表页
- **WHEN** 已登录用户打开 `/channel-codes`
- **THEN** 页面展示标题 `渠道活码`
- **AND** 页面展示活码名称搜索、对应岗位筛选、状态筛选、表格、分页和页头右上角 `新增员工渠道活码` 操作
#### Scenario: 从导航进入渠道活码
- **WHEN** 用户在后台导航中选择 `渠道活码`
- **THEN** 系统跳转到 `/channel-codes`
- **AND** `渠道活码` 展示为一级菜单 `Agent群管理` 下的二级菜单
#### Scenario: 打开独立新建页
- **WHEN** 用户打开 `/channel-codes/new`
- **THEN** 页面展示独立表单页标题 `新增员工渠道活码`
- **AND** 页头左侧展示返回入口
- **AND** 页头右上角按顺序展示 `取消` 和 `保存`
#### Scenario: 打开独立编辑页
- **WHEN** 用户打开 `/channel-codes/:codeId/edit`
- **THEN** 页面展示独立表单页标题 `编辑员工渠道活码`
- **AND** 页头左侧展示返回入口
- **AND** 页头右上角按顺序展示 `取消` 和 `保存`
### Requirement: 渠道活码列表筛选
渠道活码列表页 SHALL 支持按活码名称、对应岗位和状态筛选列表,并允许用户恢复全量结果。
#### Scenario: 搜索区遵循基础规则
- **WHEN** 页面渲染渠道活码搜索区
- **THEN** 搜索区布局遵循 `frontend-foundation.md` 中的搜索区域规则
- **AND** 活码名称输入框 placeholder 为 `搜索活码名称`
- **AND** 对应岗位筛选包含 `全部` 选项
- **AND** 状态筛选包含 `全部`、`启用` 和 `停用`
#### Scenario: 提交筛选
- **WHEN** 用户输入活码名称或选择对应岗位、状态后点击 `搜索`
- **THEN** 页面按筛选条件刷新渠道活码列表
- **AND** 页面回到第 `1` 页
#### Scenario: 回车提交活码名称搜索
- **WHEN** 用户在活码名称输入框中输入内容并按下回车
- **THEN** 页面按当前筛选条件刷新渠道活码列表
- **AND** 页面回到第 `1` 页
#### Scenario: 重置筛选
- **WHEN** 用户点击 `重置`
- **THEN** 页面清空活码名称并恢复对应岗位和状态为 `全部`
- **AND** 页面恢复默认渠道活码列表并回到第 `1` 页
### Requirement: 渠道活码表格与分页
渠道活码列表页 SHALL 以表格展示渠道活码信息,并使用分页展示列表结果。
#### Scenario: 展示渠道活码行
- **WHEN** 渠道活码列表存在数据
- **THEN** 每行展示 `活码名称`、`对应岗位`、`渠道编码`、`承接员工`、`关联 Agent`、`状态`、`创建时间` 和 `操作`
- **AND** 操作列展示 `查看`、`编辑` 以及当前状态对应的 `启用` 或 `停用`
#### Scenario: 切换分页
- **WHEN** 用户切换页码或每页条数
- **THEN** 页面按新的分页参数展示渠道活码列表
- **AND** 每页条数变化后页面回到第 `1` 页
#### Scenario: 筛选无结果
- **WHEN** 当前筛选条件没有匹配的渠道活码
- **THEN** 页面展示筛选无结果状态
- **AND** 页面允许用户调整筛选条件或重置搜索
### Requirement: 渠道活码新建表单
渠道活码管理 SHALL 支持通过独立新建页创建员工渠道活码,并按岗位自动展示派生信息。
#### Scenario: 新建页字段
- **WHEN** 用户打开 `/channel-codes/new`
- **THEN** 表单展示 `活码名称`、`对应岗位`、`渠道编码`、`承接员工`、`关联 Agent`、`活码描述`、`自动欢迎语` 和 `状态`
- **AND** `活码名称` 和 `对应岗位` 为必填字段
- **AND** `渠道编码`、`承接员工` 和 `关联 Agent` 为只读展示
- **AND** `状态` 默认值为 `停用`
#### Scenario: 选择岗位后展示派生信息
- **WHEN** 用户在新建页选择可创建渠道活码的岗位
- **THEN** 页面展示该岗位对应的渠道编码
- **AND** 页面展示 mock 返回的承接员工
- **AND** 页面展示 mock 返回的关联 Agent
#### Scenario: 已有活码的岗位不可再次创建
- **WHEN** 用户在新建页查看岗位选项
- **THEN** 已启用或已停用但已经创建渠道活码的岗位不可再次选择
- **AND** 页面提示 `该岗位已有渠道活码,请编辑原活码`
#### Scenario: 新建页保存成功
- **WHEN** 用户填写合法表单并点击 `保存`
- **THEN** 系统保存渠道活码 mock 数据
- **AND** 页面返回 `/channel-codes`
#### Scenario: 新建页取消
- **WHEN** 用户在新建页点击 `取消`
- **THEN** 页面返回 `/channel-codes`
- **AND** 系统不保存当前表单修改
### Requirement: 渠道活码编辑表单
渠道活码管理 SHALL 支持编辑既有渠道活码的可变字段,并保持岗位和派生字段不可修改。
#### Scenario: 编辑页字段权限
- **WHEN** 用户打开 `/channel-codes/:codeId/edit`
- **THEN** 表单展示 `活码名称`、`对应岗位`、`渠道编码`、`承接员工`、`关联 Agent`、`活码描述`、`自动欢迎语` 和 `状态`
- **AND** `对应岗位`、`渠道编码`、`承接员工` 和 `关联 Agent` 为只读展示
- **AND** `活码名称`、`活码描述`、`自动欢迎语` 和 `状态` 可编辑
#### Scenario: 编辑页保存成功
- **WHEN** 用户修改合法的可编辑字段后点击 `保存`
- **THEN** 系统保存渠道活码 mock 数据
- **AND** 页面返回 `/channel-codes`
#### Scenario: 编辑页记录不存在
- **WHEN** 用户打开不存在的 `/channel-codes/:codeId/edit`
- **THEN** 页面展示可恢复的未找到或错误状态
- **AND** 页面提供返回列表入口
#### Scenario: 编辑页取消
- **WHEN** 用户在编辑页点击 `取消`
- **THEN** 页面返回 `/channel-codes`
- **AND** 系统不保存当前表单修改
### Requirement: 渠道活码表单校验与保存失败
渠道活码新建和编辑表单 SHALL 对字段规则和保存失败状态提供明确反馈。
#### Scenario: 活码名称必填
- **WHEN** 用户未填写 `活码名称` 并点击 `保存`
- **THEN** 页面提示 `请输入活码名称`
- **AND** 系统不提交保存
#### Scenario: 活码名称长度限制
- **WHEN** 用户填写超过 50 字的 `活码名称` 并点击 `保存`
- **THEN** 页面提示 `活码名称最多50字`
- **AND** 系统不提交保存
#### Scenario: 对应岗位必选
- **WHEN** 用户在新建页未选择 `对应岗位` 并点击 `保存`
- **THEN** 页面提示 `请选择对应岗位`
- **AND** 系统不提交保存
#### Scenario: 活码描述长度限制
- **WHEN** 用户填写超过 200 字的 `活码描述` 并点击 `保存`
- **THEN** 页面提示 `活码描述最多200字`
- **AND** 系统不提交保存
#### Scenario: 自动欢迎语长度限制
- **WHEN** 用户填写超过 500 字的 `自动欢迎语` 并点击 `保存`
- **THEN** 页面提示 `自动欢迎语最多500字`
- **AND** 系统不提交保存
#### Scenario: 保存失败
- **WHEN** mock 保存渠道活码失败
- **THEN** 页面提示 `保存失败,请重试`
- **AND** 页面停留在当前表单页
### Requirement: 查看活码抽屉
渠道活码列表页 SHALL 通过抽屉展示渠道活码详情和二维码图片。
#### Scenario: 打开查看抽屉
- **WHEN** 用户在渠道活码列表点击某行 `查看`
- **THEN** 页面打开查看活码抽屉
- **AND** 抽屉展示 `活码名称`、`对应岗位`、`渠道编码`、`承接员工`、`关联 Agent`、`状态`、`活码描述`、`自动欢迎语` 和 `二维码图片`
- **AND** 抽屉底部展示 `关闭` 按钮
#### Scenario: 展示二维码图片
- **WHEN** mock 详情返回可加载的 `qrcode_url`
- **THEN** 抽屉展示二维码图片
- **AND** 前端不生成二维码
#### Scenario: 二维码图片加载失败
- **WHEN** 二维码图片加载失败
- **THEN** 抽屉展示明确的图片加载失败状态
- **AND** 抽屉仍展示其他活码详情
#### Scenario: 查看抽屉保留列表上下文
- **WHEN** 用户在筛选或分页后的列表中打开并关闭查看抽屉
- **THEN** 页面保留当前筛选条件和分页上下文
### Requirement: 渠道活码启用与停用
渠道活码列表页 SHALL 支持启用和停用渠道活码,并在操作前展示二次确认。
#### Scenario: 启用前确认
- **WHEN** 用户点击停用状态活码的 `启用`
- **THEN** 页面展示启用二次确认
- **AND** 用户确认后系统将该活码状态更新为 `启用`
#### Scenario: 停用前确认
- **WHEN** 用户点击启用状态活码的 `停用`
- **THEN** 页面展示停用二次确认
- **AND** 用户确认后系统将该活码状态更新为 `停用`
#### Scenario: 取消启停
- **WHEN** 用户在启用或停用确认中取消
- **THEN** 系统不更新渠道活码状态
- **AND** 列表保持当前数据
#### Scenario: 停用业务阻断
- **WHEN** mock 停用接口返回业务阻断提示
- **THEN** 页面不更新渠道活码状态
- **AND** 页面展示 mock 返回的提示信息
### Requirement: 渠道活码页面状态
渠道活码管理 SHALL 提供正常列表、空数据、筛选无结果、加载失败、保存失败、编辑记录不存在和二维码图片失败等状态。
#### Scenario: 正常列表
- **WHEN** mock 数据源返回渠道活码列表
- **THEN** 页面展示表格行和分页信息
#### Scenario: 空数据
- **WHEN** mock 数据源没有任何渠道活码
- **THEN** 页面展示空数据状态
- **AND** 页面保留 `新增员工渠道活码` 入口
#### Scenario: 列表加载失败
- **WHEN** mock 数据源加载渠道活码列表失败
- **THEN** 页面展示加载失败状态
- **AND** 页面提供重试操作
### Requirement: 渠道活码最小 mock 契约
前端 mock 契约 SHALL 提供渠道活码管理页面需要的最小字段、查询参数、表单 payload、岗位派生信息和状态 fixture,并且不锁定后端实现。
#### Scenario: 消费渠道活码列表项
- **WHEN** 页面渲染渠道活码列表 mock
- **THEN** 列表项包含 `code_id`、`code_name`、`position_code`、`position_name`、`channel_code`、`employee_name`、`employee_role_text`、`agent_names`、`status`、`created_at` 和 `operations`
#### Scenario: 消费渠道活码详情
- **WHEN** 页面打开查看抽屉或编辑页
- **THEN** mock 详情包含列表项字段
- **AND** mock 详情包含 `qrcode_url`、`description`、`welcome_message` 和 `updated_at`
#### Scenario: 消费渠道活码查询参数
- **WHEN** 页面查询渠道活码列表 mock
- **THEN** 查询参数支持 `keyword`、`position_code`、`status`、`page` 和 `pageSize`
- **AND** `keyword` 匹配活码名称
#### Scenario: 消费岗位派生信息
- **WHEN** 新建页根据岗位查询渠道活码派生信息
- **THEN** mock 返回该岗位的 `channel_code`、`employee_name`、`employee_role_text` 和 `agent_names`
- **AND** mock 标识该岗位是否已经创建渠道活码
#### Scenario: 消费渠道活码表单 payload
- **WHEN** 页面创建或更新渠道活码 mock
- **THEN** 创建 payload 包含 `code_name`、`position_code`、`description`、`welcome_message` 和 `status`
- **AND** 更新 payload 仅要求可变字段 `code_name`、`description`、`welcome_message` 和 `status`
#### Scenario: 消费渠道活码状态 fixtures
- **WHEN** 测试或本地开发需要渠道活码页面状态
- **THEN** mock 契约提供正常列表、空列表、筛选无结果、加载失败、分页边界、已启用、已停用、岗位已有活码、新建保存成功、编辑保存成功、字段校验失败、保存接口失败、停用成功、停用业务阻断和二维码图片加载失败 fixtures
### Requirement: 基础组件复用约束
渠道活码管理 SHALL 复用既有前端基础组件和 `frontend-foundation.md` 页面规则,不在本 change 中发散基础组件体系。
#### Scenario: 复用既有组件
- **WHEN** 实现渠道活码管理页面
- **THEN** 页面复用既有按钮、输入框、选择器、开关、表格、分页、抽屉、反馈和确认组件
- **AND** 页面不在业务路由内临时创建可沉淀到组件库的一次性基础控件
#### Scenario: 遵循后台页面密度
- **WHEN** 渲染渠道活码列表和表单页面
- **THEN** 页面保持管理后台信息密度和可扫读性
- **AND** 页面不使用营销页式 hero、装饰卡片或无关视觉装饰
\ No newline at end of file \ No newline at end of file
## 1. 契约与 mock fixture
- [x] 1.1 更新渠道活码前端最小 mock 契约说明,明确列表项、详情、查询参数、表单 payload、岗位派生信息、启停操作和页面状态边界。
- [x] 1.2 新增渠道活码 mock fixture 与 mock 操作模块,覆盖正常列表、空列表、筛选无结果、加载失败、分页边界、已启用、已停用、岗位已有活码、保存成功、保存失败、停用成功、停用业务阻断和二维码图片加载失败。
- [x] 1.3 先编写渠道活码 mock fixture 测试,覆盖名称过滤、岗位筛选、状态筛选、分页、岗位派生信息、一岗一码限制、创建、更新、启用、停用阻断和二维码失败场景。
- [x] 1.4 实现 `/api/v1/agent-group/employee/{employee_id}/qrcodes` mock API 函数,包含 employee_id、employee_name、employee_role_text 和已配置活码列表,用于新建活码时展示员工信息。
## 2. 路由与导航
- [x] 2.1 先编写路由和导航测试,覆盖 `/channel-codes`、`/channel-codes/new`、`/channel-codes/:codeId/edit` 可访问和导航入口可见。
- [x] 2.2 注册渠道活码列表页、新建页、编辑页路由,并在一级菜单 `Agent群管理` 下新增二级菜单 `渠道活码`。
- [x] 2.3 确保本 change 不修改岗位标签管理、Agent 表单或官网方法论配置页面的既有行为范围。
## 3. 列表页
- [x] 3.1 先编写渠道活码列表页测试,覆盖标题、页头右上角 `新增员工渠道活码`、搜索区、岗位筛选、状态筛选、表格列、分页和行操作。
- [x] 3.2 实现 `/channel-codes` 列表页,复用 `frontend-foundation.md` 的列表页、搜索区、表格、分页和状态组件规则。
- [x] 3.3 实现活码名称搜索、对应岗位筛选、状态筛选和重置,搜索或重置后回到第 `1` 页。
- [x] 3.4 实现正常列表、空数据、筛选无结果和加载失败状态,加载失败提供重试入口。
## 4. 新建与编辑表单页
- [x] 4.1 先编写渠道活码新建页测试,覆盖独立页面结构、页头右上角 `取消`/`保存`、字段校验、岗位派生信息、已创建岗位不可选、默认停用、保存成功和保存失败。
- [x] 4.2 先编写渠道活码编辑页测试,覆盖字段权限、岗位和派生字段只读、可变字段编辑、记录不存在状态、保存成功和保存失败。
- [x] 4.3 实现 `/channel-codes/new` 独立新建页,表单字段为活码名称、对应岗位、渠道编码、承接员工、关联 Agent、活码描述、自动欢迎语和状态,保存成功后返回列表。
- [x] 4.4 实现新建页选择岗位后调用 `/api/v1/agent-group/employee/{employee_id}/qrcodes` mock API,获取渠道编码、承接员工和关联 Agent 自动展示,并阻止已创建渠道活码的岗位再次选择。
- [x] 4.5 实现 `/channel-codes/:codeId/edit` 独立编辑页,对应岗位、渠道编码、承接员工和关联 Agent 只读,活码名称、描述、自动欢迎语和状态可编辑。
- [x] 4.6 实现表单校验:活码名称必填且最多 50 字,对应岗位必选,活码描述最多 200 字,自动欢迎语最多 500 字。
- [x] 4.7 实现表单页 `取消` 返回列表且不保存,`保存` 失败时停留当前页面并展示 `保存失败,请重试`。
## 5. 查看抽屉
- [x] 5.1 先编写查看活码抽屉测试,覆盖打开抽屉、详情字段展示、二维码图片展示、二维码图片加载失败和关闭后保留列表上下文。
- [x] 5.2 实现列表行 `查看` 操作和查看抽屉,展示活码名称、对应岗位、渠道编码、承接员工、关联 Agent、状态、活码描述、自动欢迎语和二维码图片。
- [x] 5.3 实现二维码图片加载失败状态,并确保失败时抽屉仍展示其他活码详情。
## 6. 启用与停用
- [x] 6.1 先编写启停交互测试,覆盖启用确认、停用确认、取消操作、启用成功、停用成功和停用业务阻断。
- [x] 6.2 实现列表行启用和停用操作,点击后先展示二次确认。
- [x] 6.3 实现确认启用或停用后的 mock 状态更新和列表刷新。
- [x] 6.4 实现停用业务阻断提示,页面展示 mock 返回的提示信息且不更新状态。
## 7. 验证
- [x] 7.1 运行渠道活码相关测试,确认 TDD 场景通过。
- [x] 7.2 运行 `npm run typecheck`。
- [x] 7.3 运行 `npm test`。
- [x] 7.4 运行 `npm run build`。
- [x] 7.5 使用浏览器验证 `/channel-codes`、`/channel-codes/new`、`/channel-codes/:codeId/edit` 的布局、页头操作、搜索筛选、保存、查看抽屉和启停关键交互。
- [x] 7.6 更新 OpenSpec task 状态,并确认代码、测试和规范对齐后再进入归档阶段。
\ No newline at end of file \ No newline at end of file
## Context
`workspace/agent-admin/web` 已完成官网岗位展示配置列表页,并在列表行提供 `配置Agent` 跳转到 `/official-site/job-tabs/:tabId/agents`。本 change 基于已确认的 `docs/superpowers/specs/2026-05-22-official-site-agent-display-config-design.md`,只锁定后台 Agent 展示配置页的 OpenSpec artifacts,不进入业务代码实现。
现有 `packages/contracts/frontend-api-contract.md` 第 9 节曾沉淀过官网 Agent 展示配置接口草案,但部分旧规则与本次确认需求不一致:旧草案倾向于只返回已上架 Agent、保留删除配置接口、展示素材只写 GIF/MP4,且未覆盖 `icon_url`。本 change 以本次确认需求为准,后续实现阶段需要同步前端契约和 mock。
## Goals / Non-Goals
**Goals:**
- 新增 `/official-site/job-tabs/:tabId/agents` 独立配置页规范。
- 页面顶部展示返回列表、岗位名称和保存按钮。
- 页面只读展示关联渠道活码、渠道编码和承接员工。
- 展示从该岗位关联渠道活码自动提取的全部可配置 Agent,排除管家 Agent。
- Agent 列表不可新增或删除,仅允许编辑展示配置。
- 明确列表字段与契约字段映射:`speech_title`、`speech_content`、`icon_url`、展示素材字段、`sort_order`、`agent_status`、`display_status`。
- 明确 Agent 状态与展示状态联动:已停用 Agent 展示状态显示 `-`,不展示编辑按钮;已上架 Agent 展示具体展示状态。
- 明确默认展示配置状态为 `已下架`。
- 明确编辑弹窗字段、字段权限、上传组件选择、上传数量限制和校验规则。
- 补充页面级 mock 契约与 fixture,支撑后续 TDD 实现、类型检查、构建和浏览器验证。
**Non-Goals:**
- 不实现业务代码、测试代码或 mock 数据文件。
- 不修改 `official-site-job-tab-ai-intro`、`official-site-job-tabs` 或 `official-site-methodology-config` 的 artifacts。
- 不实现 H5 官网页面展示、真实后端接口、真实 OSS/CDN 上传或后端数据模型。
- 不提供 Agent 展示配置新增、删除、独立上架或独立下架行操作。
- 不重构通用上传组件;本页只复用现有上传图片组件并配置业务规则。
- 不把管家 Agent 纳入官网 Agent 展示配置。
## Decisions
### Decision: 使用独立配置页承载 Agent 展示配置
页面沿用岗位展示配置列表中已经确认的跳转路由 `/official-site/job-tabs/:tabId/agents`。页头左侧提供返回列表入口,标题展示岗位名称,右侧提供保存按钮。这样保持官网配置后台的信息架构稳定,也让用户在单个岗位上下文内批量查看 Agent 展示配置。
替代方案是把 Agent 配置放在岗位展示编辑页内,但会让岗位基础配置与 Agent 展示素材、排序、状态等批量配置混在一起,降低后台页面的可扫读性。
### Decision: Agent 列表展示全部可配置 Agent,不提供增删能力
Agent 数据源固定来自该岗位关联渠道活码自动提取,并排除管家 Agent。页面展示全部可配置 Agent,包括已上架和已停用 Agent;前端不提供新增、删除或手动选择 Agent 的入口。
这样可以让运营看到渠道活码下的完整可配置范围,同时避免后台页面承担 Agent 原始数据维护职责。删除 Agent 展示配置或新增配置的行为不在本页出现,展示配置只能通过编辑弹窗保存。
### Decision: 停用 Agent 保留展示但禁止编辑
`agent_status` 表达 Agent 本身状态,列表文案为 `状态`,包含 `已上架` 和 `已停用`。`display_status` 表达官网展示配置状态,列表文案为 `展示状态`,只包含 `展示中` 和 `已下架`。
当 `agent_status` 为已停用时,列表仍展示该 Agent,但展示状态显示为 `-`,操作列不展示 `编辑配置`。当 `agent_status` 为已上架时,展示状态显示具体 `display_status`。这样既保留配置可追溯性,又避免用户误以为停用 Agent 仍可被配置到官网展示。
### Decision: 字段以展示话术和素材配置为核心
列表和弹窗都使用 `speech_title` 作为 `Agent 名称`,使用 `speech_content` 作为 `Agent 概述`。`icon_url` 表示图标,展示素材使用页面级素材字段表达,排序使用 `sort_order`。
编辑弹窗中 `Agent 名称` 只读,`Agent 概述` 可编辑。这个决策以本次确认需求为准,不沿用旧草案中的 `agent_name` 作为页面主展示字段,也避免把 Agent 原始名称编辑能力误放到官网展示配置页。
### Decision: 图标和展示素材都复用上传图片组件
`icon_url` 使用上传图片组件,最多 1 个文件。展示素材也使用上传图片组件,最多 1 个文件,支持图片、视频和 GIF,不使用附件组件。展示素材推荐比例为 1:1,大小限制沿用 Agent 展示素材规则,最大 20MB。
替代方案是展示素材使用附件组件,但这会弱化图片、视频、GIF 的预览和替换体验,也与本次确认的组件选择冲突。
### Decision: 默认展示配置状态为已下架
首次编辑未配置 Agent 时,`display_status` 默认 `已下架`。弹窗展示状态只提供 `已下架` 和 `展示中` 两个选项,不出现 `已停用`。这样可以避免新生成配置未经确认就展示到 H5,同时保持 Agent 本身状态和官网展示状态的语义边界。
### Decision: 页面级保存与弹窗编辑分层
列表行点击 `编辑配置` 打开弹窗,弹窗保存只更新该 Agent 的展示配置草稿或页面状态;页头 `保存` 用于提交本页 Agent 展示配置变更。后续实现可以根据 mock 数据结构选择立即保存或页级批量保存,但用户可见行为必须保证保存中禁用重复提交、保存失败保留用户已填内容并展示可恢复错误。
## Risks / Trade-offs
- [Risk] 旧契约草案与本次确认需求存在差异,后续实现若直接复用旧接口命名可能遗漏 `icon_url` 或误带删除入口。→ Mitigation: 在本 change 的 spec 和 tasks 中明确要求更新前端契约草案与 mock 契约,并覆盖不可新增、不可删除、停用不可编辑场景。
- [Risk] “展示全部可配置 Agent”与旧文档中“筛选已上架 Agent”不一致。→ Mitigation: 以本次确认需求为准,后台列表展示已上架和已停用 Agent;H5 展示隐藏停用 Agent 属于展示端联动,不在本页过滤后台列表。
- [Risk] 上传图片组件支持视频和 GIF 可能依赖现有组件能力边界。→ Mitigation: 本 change 不重构组件,但实现任务需要验证上传图片组件可按业务 accept、数量、大小和错误态配置;如组件能力不足,应先通过已有组件扩展流程处理。
- [Risk] 页头保存与弹窗保存的最终提交粒度可能受后端接口影响。→ Mitigation: OpenSpec 锁定用户可见交互和错误反馈,真实接口对接前端契约时再确认是单项保存还是页级批量保存。
## Migration Plan
1. 补充官网 Agent 展示配置前端契约草案和 mock fixture,覆盖 `icon_url`、展示素材、状态映射、停用不可编辑、默认已下架和上传错误。
2. 注册 `/official-site/job-tabs/:tabId/agents` 页面内容,保持 `官网配置 > 岗位展示配置` 导航上下文和返回列表行为。
3. 用 TDD 实现页面上下文信息、Agent 表格、状态映射、不可增删约束和停用不可编辑规则。
4. 用 TDD 实现 `编辑配置` 弹窗、字段校验、上传图片组件配置、保存成功和保存失败状态。
5. 运行 `npm run typecheck`、`npm test`、`npm run build`,并在浏览器中验证桌面布局、弹窗、上传错误、停用 Agent 和保存反馈。
## Open Questions
- 真实接口阶段需要确认页头 `保存` 与弹窗 `保存` 的提交粒度:本期 mock 可以先按页面可见行为实现,但对接后端前需要明确是单 Agent 保存还是整页批量保存。
## Why
官网配置后台已经具备岗位展示配置列表和 `配置Agent` 跳转入口,但 `/official-site/job-tabs/:tabId/agents` 还缺少可落地的 Agent 展示配置页规范。该页面是官网配置后台最后一批新增页面之一,需要在进入前端实现前先锁定字段映射、状态规则、上传约束和不可增删边界。
## What Changes
- 新增 `/official-site/job-tabs/:tabId/agents` 独立配置页,页头展示返回列表、岗位名称和保存按钮。
- 页面只读展示岗位关联渠道活码、渠道编码和承接员工。
- Agent 数据源来自该岗位关联渠道活码自动提取的全部可配置 Agent,排除管家 Agent,但不因 Agent 停用而从后台列表隐藏。
- Agent 列表不可新增、删除或手动选择,仅允许对已上架 Agent 编辑展示配置。
- 列表字段包含 Agent 名称、Agent 概述、图标、展示素材、排序、状态、展示状态和操作,并明确字段映射到 `speech_title`、`speech_content`、`icon_url`、`agent_status`、`display_status` 等契约字段。
- `agent_status` 展示为 `状态`,包含 `已上架`、`已停用`;`display_status` 展示为 `展示状态`,包含 `展示中`、`已下架`。
- 当 Agent 已停用时,列表展示状态为 `已停用`、展示状态为 `-`,且不展示编辑按钮;当 Agent 已上架时,展示状态展示 `展示中` 或 `已下架`。
- 默认 Agent 展示配置状态为 `已下架`。
- 点击 `编辑配置` 打开弹窗表单,支持编辑图标、Agent 概述、展示素材、展示排序和展示状态;Agent 名称只读。
- 图标和展示素材均使用上传图片组件且最多 1 个文件;展示素材支持图片、视频和 GIF,不使用附件组件。
- 补充页面级 mock 契约与 fixture,覆盖正常列表、空数据、停用 Agent、默认已下架、上传失败、格式错误、大小错误、字段校验和保存失败等状态。
## Capabilities
### New Capabilities
- `official-site-agent-display-config`: 覆盖官网岗位 Agent 展示配置页的路由、上下文信息、Agent 列表、状态映射、编辑弹窗、上传规则、保存规则、页面状态和最小 mock 契约。
### Modified Capabilities
- 无。本 change 不修改 `official-site-job-tabs`、`official-site-methodology-config` 或 `official-site-job-tab-ai-intro` 的既有 artifacts。
## Impact
- 影响 `workspace/agent-admin/web` 前端路由、官网配置页面、页面级 mock 数据、前端契约草案和测试计划。
- 需要后续实现阶段补充或调整 `packages/contracts/frontend-api-contract.md` 中官网 Agent 展示配置契约,使其包含 `icon_url`,并移除前端新增、删除展示配置入口的行为假设。
- 不影响 `workspace/agent-admin/backend`,不实现真实接口、真实文件服务、H5 官网展示或岗位 AI 赋能介绍能力。
## ADDED Requirements
### Requirement: 官网 Agent 展示配置路由与页头
后台前端 SHALL 提供 `/official-site/job-tabs/:tabId/agents` 独立配置页,用于配置单个官网岗位 Tab 下的 Agent 展示信息。
#### Scenario: 打开 Agent 展示配置页
- **WHEN** 已登录用户打开 `/official-site/job-tabs/:tabId/agents`
- **THEN** 页面展示该岗位的 Agent 展示配置页
- **AND** 页头展示返回列表入口
- **AND** 页头展示岗位名称
- **AND** 页头展示 `保存` 按钮
#### Scenario: 返回岗位展示配置列表
- **WHEN** 用户点击页头返回列表入口
- **THEN** 系统跳转到 `/official-site/job-tabs`
#### Scenario: 记录不存在
- **WHEN** 用户打开不存在的 `/official-site/job-tabs/:tabId/agents`
- **THEN** 页面展示可恢复的未找到或错误状态
- **AND** 页面提供返回列表入口
### Requirement: 官网 Agent 展示配置上下文信息
Agent 展示配置页 SHALL 只读展示当前岗位 Tab 关联的渠道活码上下文。
#### Scenario: 展示渠道活码上下文
- **WHEN** 页面加载到岗位 Tab 详情
- **THEN** 页面展示 `关联渠道活码`
- **AND** 页面展示 `渠道编码`
- **AND** 页面展示 `承接员工`
- **AND** 这些字段均为只读
#### Scenario: 上下文字段为空
- **WHEN** 渠道编码或承接员工为空
- **THEN** 页面以只读空值占位展示
- **AND** 页面不允许用户在 Agent 展示配置页编辑渠道活码上下文
### Requirement: 官网 Agent 展示配置数据源与列表边界
Agent 展示配置页 SHALL 从该岗位关联渠道活码自动提取全部可配置 Agent,排除管家 Agent,并禁止新增或删除 Agent 展示配置。
#### Scenario: 展示全部可配置 Agent
- **WHEN** 页面加载 Agent 展示配置列表
- **THEN** 列表数据来自该岗位关联渠道活码自动提取的 Agent
- **AND** 列表排除管家 Agent
- **AND** 列表包含已上架和已停用的可配置 Agent
#### Scenario: 不展示新增入口
- **WHEN** 页面渲染 Agent 展示配置列表
- **THEN** 页面不展示新增 Agent 展示配置入口
- **AND** 页面不支持手动选择额外 Agent
#### Scenario: 不展示删除入口
- **WHEN** 页面渲染 Agent 展示配置列表
- **THEN** 列表行不展示删除 Agent 展示配置操作
- **AND** 页面不提供删除 Agent 原始数据或展示配置关系的能力
#### Scenario: 无可配置 Agent
- **WHEN** 渠道活码下没有可配置 Agent 或仅有关家 Agent
- **THEN** 页面展示空数据状态
- **AND** 页面说明当前没有可配置 Agent
### Requirement: 官网 Agent 展示配置列表字段
Agent 展示配置页 SHALL 以表格展示全部可配置 Agent 的展示配置字段,并使用本页确认的字段映射。
#### Scenario: 展示列表字段
- **WHEN** Agent 展示配置列表存在数据
- **THEN** 每行展示 `Agent名称`、`Agent概述`、`图标`、`展示素材`、`排序`、`状态`、`展示状态` 和 `操作`
#### Scenario: 字段映射
- **WHEN** 页面渲染 Agent 展示配置行
- **THEN** `Agent名称` 使用 `speech_title`
- **AND** `Agent概述` 使用 `speech_content`
- **AND** `图标` 使用 `icon_url`
- **AND** `排序` 使用 `sort_order`
- **AND** `状态` 使用 `agent_status`
- **AND** `展示状态` 使用 `display_status`
#### Scenario: 默认展示配置状态
- **WHEN** Agent 尚未保存展示配置
- **THEN** 页面将该 Agent 的 `display_status` 默认视为 `已下架`
### Requirement: 官网 Agent 状态与展示状态映射
Agent 展示配置页 SHALL 区分 Agent 本身状态和官网展示配置状态,并按 Agent 状态控制展示状态与操作。
#### Scenario: 已上架 Agent 展示状态
- **WHEN** `agent_status` 为已上架
- **THEN** 列表 `状态` 展示 `已上架`
- **AND** 列表 `展示状态` 展示该 Agent 的 `display_status`
- **AND** `display_status` 只展示为 `展示中` 或 `已下架`
- **AND** 操作列展示 `编辑配置`
#### Scenario: 已停用 Agent 展示状态
- **WHEN** `agent_status` 为已停用
- **THEN** 列表 `状态` 展示 `已停用`
- **AND** 列表 `展示状态` 展示 `-`
- **AND** 操作列不展示 `编辑配置`
#### Scenario: 停用 Agent 保留配置
- **WHEN** 已保存展示配置的 Agent 被停用
- **THEN** 后台列表仍展示该 Agent
- **AND** 页面保留该 Agent 的展示配置数据
- **AND** 页面不允许编辑该 Agent 展示配置
### Requirement: 官网 Agent 编辑配置弹窗
Agent 展示配置页 SHALL 允许用户对已上架 Agent 打开编辑弹窗,并在弹窗中编辑展示配置。
#### Scenario: 打开编辑弹窗
- **WHEN** 用户点击已上架 Agent 行的 `编辑配置`
- **THEN** 页面打开编辑弹窗
- **AND** 弹窗标题包含当前 Agent 名称
#### Scenario: 编辑弹窗字段
- **WHEN** 编辑弹窗打开
- **THEN** 弹窗展示 `图标`、`Agent名称`、`Agent概述`、`展示素材`、`展示排序` 和 `展示状态`
- **AND** `Agent名称` 为只读
- **AND** `Agent概述` 可编辑
- **AND** `展示排序` 可编辑
- **AND** `展示状态` 可编辑
#### Scenario: 展示状态选项
- **WHEN** 用户编辑展示状态
- **THEN** 展示状态选项只包含 `已下架` 和 `展示中`
- **AND** 弹窗内不展示 `已停用` 作为展示配置状态
#### Scenario: 未配置 Agent 的弹窗默认值
- **WHEN** 用户首次编辑未配置 Agent
- **THEN** 弹窗内展示状态默认值为 `已下架`
### Requirement: 官网 Agent 图标与展示素材上传
Agent 展示配置页 SHALL 使用上传图片组件配置图标和展示素材,并限制单个文件。
#### Scenario: 图标上传
- **WHEN** 用户编辑 `图标`
- **THEN** 字段绑定 `icon_url`
- **AND** 字段使用上传图片组件
- **AND** 最多允许上传 1 个文件
#### Scenario: 展示素材上传
- **WHEN** 用户编辑 `展示素材`
- **THEN** 字段使用上传图片组件
- **AND** 字段不使用附件组件
- **AND** 支持图片、视频和 GIF
- **AND** 最多允许上传 1 个文件
#### Scenario: 展示素材校验
- **WHEN** 用户上传不支持的展示素材格式或超过大小限制的文件
- **THEN** 页面在展示素材字段附近展示校验错误
- **AND** 页面不提交保存
#### Scenario: 上传失败
- **WHEN** 图标或展示素材 mock 上传失败
- **THEN** 页面展示对应字段的上传失败状态
- **AND** 页面允许用户重新上传
### Requirement: 官网 Agent 编辑配置校验与保存
Agent 展示配置页 SHALL 对编辑弹窗字段和页面保存状态提供明确反馈,并阻止重复提交。
#### Scenario: Agent 概述校验
- **WHEN** 用户提交空的 `Agent概述` 或超过 100 字的 `Agent概述`
- **THEN** 页面在 `Agent概述` 字段附近展示校验错误
- **AND** 页面不提交保存
#### Scenario: 展示排序校验
- **WHEN** 用户提交空的、非整数或超出 `0-99` 的 `展示排序`
- **THEN** 页面在 `展示排序` 字段附近展示校验错误
- **AND** 页面不提交保存
#### Scenario: 保存中禁用重复提交
- **WHEN** 用户提交合法配置且保存尚未完成
- **THEN** 页面禁用重复提交
#### Scenario: 保存成功
- **WHEN** 用户提交合法配置且 mock 保存成功
- **THEN** 页面更新 Agent 展示配置列表
- **AND** 页面展示保存成功提示
#### Scenario: 保存失败
- **WHEN** 用户提交合法配置但 mock 保存失败
- **THEN** 页面展示保存失败提示
- **AND** 页面保留用户已填写内容
- **AND** 用户可以修正或重试保存
#### Scenario: 字段校验不使用全局提示替代
- **WHEN** 用户提交表单且存在字段校验错误
- **THEN** 字段校验错误展示在对应字段附近
- **AND** 页面不使用全局成功或失败提示替代字段附近错误
### Requirement: 官网 Agent 展示配置最小 mock 契约
前端 mock 契约 SHALL 提供 Agent 展示配置页需要的最小字段、查询语义、保存 payload、上传结果和状态 fixture,并且不锁定后端实现。
#### Scenario: 消费 Agent 展示配置详情
- **WHEN** 页面加载 `/official-site/job-tabs/:tabId/agents`
- **THEN** mock 详情包含 `tab_id`、`position_name`、`qrcode_name`、`channel_code` 和 `employee_name`
- **AND** mock 详情包含 Agent 展示配置列表
#### Scenario: 消费 Agent 展示配置列表项
- **WHEN** 页面渲染 Agent 展示配置列表 mock
- **THEN** 列表项包含 `agent_id`、`speech_title`、`speech_content`、`icon_url`、`media_url`、`media_type`、`media_size`、`sort_order`、`agent_status` 和 `display_status`
- **AND** mock 能表达 Agent 是否为管家 Agent 并确保管家 Agent 不进入列表
#### Scenario: 消费保存 payload
- **WHEN** 页面保存 Agent 展示配置 mock
- **THEN** payload 包含 `icon_url`、`speech_content`、展示素材字段、`sort_order` 和 `display_status`
- **AND** payload 不包含新增 Agent 或删除 Agent 的操作语义
#### Scenario: 消费状态 fixtures
- **WHEN** 测试或本地开发需要 Agent 展示配置页面状态
- **THEN** mock 契约提供正常列表、空数据、默认已下架、展示中、已停用、图标上传成功、图标上传失败、展示素材上传成功、展示素材上传失败、展示素材格式错误、展示素材大小错误、字段必填错误、字数错误、排序错误、保存成功和保存失败 fixtures
### Requirement: 基础组件复用约束
Agent 展示配置页 SHALL 复用既有前端基础组件和后台页面规则,不在本 change 中发散基础组件体系。
#### Scenario: 复用既有组件
- **WHEN** 实现 Agent 展示配置页
- **THEN** 页面复用既有按钮、表格、反馈、弹窗、表单和上传图片组件
- **AND** 页面不在业务路由内临时创建可沉淀到组件库的一次性基础控件
#### Scenario: 遵循后台页面密度
- **WHEN** 渲染 Agent 展示配置页
- **THEN** 页面保持管理后台信息密度和可扫读性
- **AND** 页面不使用营销页式 hero、装饰卡片或无关视觉装饰
## 1. 契约与 Mock 准备
- [ ] 1.1 更新前端契约草案,补齐 Agent 展示配置的 `icon_url`、展示素材、`agent_status`、`display_status`、`sort_order` 字段,并移除本页新增/删除 Agent 展示配置的行为假设。
- [ ] 1.2 补充页面级 mock 类型和 fixture,覆盖正常列表、空数据、默认已下架、展示中、已停用、上传成功/失败、格式错误、大小错误、字段校验和保存失败。
- [ ] 1.3 先编写 mock 契约测试,验证管家 Agent 不进入列表、已停用 Agent 保留展示但不可编辑、未配置 Agent 默认已下架。
## 2. 路由与页面骨架
- [ ] 2.1 先编写路由测试,覆盖 `/official-site/job-tabs/:tabId/agents` 可访问,并保持 `官网配置 > 岗位展示配置` 导航上下文。
- [ ] 2.2 实现 `/official-site/job-tabs/:tabId/agents` 页面骨架,页头展示返回列表、岗位名称和保存按钮。
- [ ] 2.3 实现岗位关联渠道活码、渠道编码和承接员工的只读展示,以及记录不存在时的可恢复错误状态。
## 3. Agent 列表
- [ ] 3.1 先编写列表渲染测试,覆盖 Agent 名称、Agent 概述、图标、展示素材、排序、状态、展示状态和操作列。
- [ ] 3.2 实现 Agent 展示配置表格,字段映射到 `speech_title`、`speech_content`、`icon_url`、展示素材字段、`sort_order`、`agent_status` 和 `display_status`。
- [ ] 3.3 实现不可新增、不可删除和不可手动选择 Agent 的页面约束。
- [ ] 3.4 实现空数据状态,覆盖无可配置 Agent 或仅有关家 Agent 的场景。
## 4. 状态映射与操作权限
- [ ] 4.1 先编写状态映射测试,覆盖已上架 Agent 展示 `展示中/已下架`,已停用 Agent 展示状态为 `-`。
- [ ] 4.2 实现 `agent_status` 到 `状态` 的文案映射:已上架、已停用。
- [ ] 4.3 实现 `display_status` 到 `展示状态` 的文案映射:展示中、已下架。
- [ ] 4.4 实现已停用 Agent 不展示 `编辑配置`,已上架 Agent 展示 `编辑配置`。
## 5. 编辑配置弹窗
- [ ] 5.1 先编写弹窗打开和字段权限测试,覆盖已上架 Agent 可打开弹窗、已停用 Agent 无编辑入口。
- [ ] 5.2 实现 `编辑配置` 弹窗,字段包含图标、Agent 名称、Agent 概述、展示素材、展示排序和展示状态。
- [ ] 5.3 实现 Agent 名称只读、Agent 概述可编辑、展示排序可编辑、展示状态只包含已下架和展示中。
- [ ] 5.4 实现首次编辑未配置 Agent 时展示状态默认已下架。
## 6. 上传与校验
- [ ] 6.1 先编写上传组件配置测试,覆盖图标和展示素材都使用上传图片组件且最多 1 个文件。
- [ ] 6.2 实现 `icon_url` 图标上传,限制单个文件,并覆盖上传失败和重新上传状态。
- [ ] 6.3 实现展示素材上传,使用上传图片组件支持图片、视频、GIF,限制单个文件,不使用附件组件。
- [ ] 6.4 实现 Agent 概述必填与 100 字限制、展示排序 0-99 整数校验、展示素材格式和大小校验,字段错误展示在字段附近。
## 7. 保存与反馈
- [ ] 7.1 先编写保存测试,覆盖保存中禁用重复提交、保存成功更新列表、保存失败保留用户已填写内容。
- [ ] 7.2 实现弹窗或页面保存流程,合法配置保存成功后更新 Agent 展示配置列表并展示成功提示。
- [ ] 7.3 实现保存失败状态,展示可恢复错误并允许用户修正或重试。
- [ ] 7.4 确保字段校验错误不使用全局提示替代。
## 8. 验证
- [ ] 8.1 运行 `openspec validate "official-site-agent-display-config" --strict`。
- [ ] 8.2 实现阶段运行 `npm run typecheck`。
- [ ] 8.3 实现阶段运行 `npm test`。
- [ ] 8.4 实现阶段运行 `npm run build`。
- [ ] 8.5 实现阶段使用浏览器验证 `/official-site/job-tabs/:tabId/agents` 的桌面布局、返回列表、上下文展示、列表状态映射、编辑弹窗、上传错误、保存成功和保存失败。
## Context
`official-site-job-tabs` 已归档,岗位展示配置列表、新建、编辑、上下架、删除和配置 Agent 跳转已经作为既有能力处理。本次是官网岗位 Tab 的增量变更,只补齐新增/编辑页中的“岗位 AI 赋能介绍”模块。
参考文档 `requirements-official-site-config.md`、`page-data-drafts.md`、`2026-05-22-official-site-job-tabs-design.md` 和 `frontend-api-contract.md` 已同步过 `main_title`、`sub_title` 字段方向,但归档 change 中仍需要一个独立增量 OpenSpec 锁定模块、校验和契约要求,避免后续实现时被当成附属文案遗漏。
## Goals / Non-Goals
**Goals:**
- 在岗位展示配置新建页和编辑页增加“岗位 AI 赋能介绍”模块。
- 明确 `岗位标题` 与 `岗位说明` 的字段名、必填规则、长度规则和前台展示语义。
- 明确创建、编辑、详情和 mock 契约都必须包含 `main_title` 与 `sub_title`。
- 明确字段校验覆盖为空和超长,且错误展示在字段附近。
- 保持 `official-site-job-tabs` 已归档能力的其他规则不变。
**Non-Goals:**
- 不实现业务代码、测试代码、mock fixture 或真实后端接口。
- 不修改归档 change `official-site-job-tabs`。
- 不混入 `official-site-agent-display-config` 或 `official-site-agent-display-config` 的 Agent 展示配置页面。
- 不改变岗位标签选择、渠道活码派生展示、渠道编码、承接员工、Tab 排序、展示状态、上下架、删除、配置 Agent 跳转等既有规则。
- 不实现 H5 官网页面视觉或交互。
## Decisions
### Decision: 使用独立模块承载 AI 赋能介绍字段
新建页和编辑页在既有表单结构中增加“岗位 AI 赋能介绍”模块,模块内包含 `岗位标题` 和 `岗位说明`。这样可以让运营人员明确这两个字段影响官网岗位 Tab 的前台文案,而不是把它们误认为后台备注或普通标题字段。
替代方案是把两个字段散落在既有基础信息字段中;该方案实现成本更低,但字段语义不够清晰,容易在后续实现或验收时遗漏“AI 如何赋能该岗位”的说明目的。
### Decision: `main_title` 和 `sub_title` 同时进入创建与编辑契约
创建和编辑 payload 都必须包含 `main_title`、`sub_title`。编辑页打开详情时也必须读取并回填这两个字段,保存时允许修改。这样新建与编辑行为保持一致,并确保官网 Tab 前台展示所需文案始终有明确来源。
替代方案是只在创建时填写,编辑页不允许修改;该方案无法满足运营后续调整文案的需求。
### Decision: 前端先执行必填与长度校验
`main_title` 必填且最多 30 字,`sub_title` 必填且最多 200 字。提交前必须在字段附近展示为空和超长错误,避免用户依赖全局失败提示或后端返回才能发现问题。
长度按前端表单输入值的字符数校验。若后端未来采用不同字符统计规则,需要在后端契约确认时单独补充。
### Decision: 不改变既有岗位 Tab 业务规则
本变更只新增 AI 赋能介绍模块,不调整岗位标签、渠道活码、排序、展示状态、上下架、删除和配置 Agent 跳转规则。后续实现应在已有岗位展示配置页面能力上增量补字段,不借此重构其他流程。
## Risks / Trade-offs
- [Risk] 现有参考文档中已出现 `main_title`、`sub_title`,新 change 可能看起来与旧归档内容重复。→ Mitigation: 本 change 只作为增量验收锁定,明确不修改归档内容,并补齐模块化呈现、编辑修改、契约必含和校验场景。
- [Risk] 前端字符数校验与后端最终规则存在差异。→ Mitigation: 当前 OpenSpec 仅锁定前端需要执行的 30/200 字校验,后端联调前如有字符统计差异再追加契约变更。
- [Risk] 实现时误改上下架、删除或渠道活码规则。→ Mitigation: spec 中加入不回归要求,tasks 中单列既有规则回归验证。
## Migration Plan
本阶段只创建 OpenSpec artifacts,不进行代码迁移。
后续进入实现阶段时,应在现有岗位展示配置表单、mock 契约和测试中增量加入 `main_title`、`sub_title`,运行相关表单测试、类型检查、构建和浏览器验证。若实现后需要回滚,只移除该模块字段与对应测试,不回滚岗位展示配置既有能力。
## Open Questions
- 是否需要为 `岗位标题` 与 `岗位说明` 定义默认文案模板?当前需求未要求,默认不提供。
- 是否需要在列表页展示 `岗位标题` 或 `岗位说明`?当前需求只要求新增/编辑页填写和前台展示语义,默认不新增列表列。
## Why
`official-site-job-tabs` 已归档,但岗位展示配置新增/编辑页仍需要把“岗位 AI 赋能介绍”作为独立模块锁定,避免后续实现时遗漏 `main_title` 和 `sub_title` 的展示、保存和校验边界。
本变更补齐官网岗位 Tab 新建/编辑表单中的 AI 赋能介绍字段与接口契约要求,同时保持岗位标签、渠道活码、排序、展示状态、删除等既有规则不变。
## What Changes
- 在官网配置 -> 岗位展示配置的新建页和编辑页增加“岗位 AI 赋能介绍”模块。
- 模块包含 `岗位标题` 字段,对应接口字段 `main_title`,必填,最多 30 字。
- 模块包含 `岗位说明` 字段,对应接口字段 `sub_title`,必填,最多 200 字。
- 明确 `岗位标题` 展示在官网 Tab 名称下方,用一句话介绍 AI 如何赋能该岗位。
- 明确 `岗位说明` 展示在官网 Tab 内容区,用于详细描述 AI 为该岗位带来的价值。
- 新建和编辑保存 payload、详情数据和 mock 契约均包含 `main_title` 与 `sub_title`。
- 表单校验覆盖两个字段为空和超长,并在字段附近展示校验错误。
- 不改变岗位标签、渠道活码、渠道编码、承接员工、Tab 排序、展示状态、上下架、删除、配置 Agent 跳转等既有规则。
## Capabilities
### New Capabilities
- `official-site-job-tab-ai-intro`: 覆盖官网岗位展示配置新增/编辑页的“岗位 AI 赋能介绍”模块、`main_title`/`sub_title` 字段契约、长度校验和 mock fixture 场景。
### Modified Capabilities
- 无。当前 `openspec/specs/` 中不存在可直接修改的 `official-site-job-tabs` 活跃 capability,本变更作为归档能力的增量 capability 新建。
## Impact
- 影响后台前端页面:`/official-site/job-tabs/new` 和 `/official-site/job-tabs/:tabId/edit`。
- 影响前端接口契约与 mock:官网岗位 Tab 创建、编辑、详情和本地 fixture 需要包含 `main_title`、`sub_title` 及长度校验场景。
- 不影响 H5 前台页面实现、真实后端实现、`official-site-agent-display-config`、岗位标签管理、渠道活码管理、排序状态流转和删除规则。
## ADDED Requirements
### Requirement: 岗位 AI 赋能介绍模块
官网岗位展示配置新建页和编辑页 SHALL 提供“岗位 AI 赋能介绍”模块,用于维护官网岗位 Tab 的 AI 赋能介绍文案。
#### Scenario: 新建页展示 AI 赋能介绍模块
- **WHEN** 已登录用户打开 `/official-site/job-tabs/new`
- **THEN** 表单展示模块标题 `岗位 AI 赋能介绍`
- **AND** 模块内展示 `岗位标题` 输入项
- **AND** 模块内展示 `岗位说明` 输入项
#### Scenario: 编辑页展示并回填 AI 赋能介绍模块
- **WHEN** 已登录用户打开 `/official-site/job-tabs/:tabId/edit`
- **THEN** 表单展示模块标题 `岗位 AI 赋能介绍`
- **AND** `岗位标题` 回填当前官网岗位 Tab 的 `main_title`
- **AND** `岗位说明` 回填当前官网岗位 Tab 的 `sub_title`
#### Scenario: 编辑页允许修改 AI 赋能介绍
- **WHEN** 用户在编辑页修改 `岗位标题` 或 `岗位说明` 后点击 `保存`
- **THEN** 系统使用修改后的 `main_title` 和 `sub_title` 保存官网岗位 Tab
- **AND** 保存成功后页面返回 `/official-site/job-tabs`
### Requirement: 岗位标题字段
官网岗位展示配置新建页和编辑页 SHALL 提供 `岗位标题` 字段,对应接口字段 `main_title`,该字段必填且最多 30 字。
#### Scenario: 岗位标题语义
- **WHEN** 用户查看 `岗位标题` 字段说明或 tips
- **THEN** 页面说明该字段展示在官网 Tab 名称下方
- **AND** 页面说明该字段用于一句话介绍 AI 如何赋能该岗位
#### Scenario: 岗位标题为空
- **WHEN** 用户未填写 `岗位标题` 并点击 `保存`
- **THEN** 页面在 `岗位标题` 字段附近提示 `请输入岗位标题`
- **AND** 系统不提交保存
#### Scenario: 岗位标题超长
- **WHEN** 用户填写超过 30 字的 `岗位标题` 并点击 `保存`
- **THEN** 页面在 `岗位标题` 字段附近提示 `岗位标题最多30字`
- **AND** 系统不提交保存
#### Scenario: 岗位标题合法
- **WHEN** 用户填写 1 到 30 字的 `岗位标题`
- **THEN** 字段通过前端长度校验
### Requirement: 岗位说明字段
官网岗位展示配置新建页和编辑页 SHALL 提供 `岗位说明` 字段,对应接口字段 `sub_title`,该字段必填且最多 200 字。
#### Scenario: 岗位说明语义
- **WHEN** 用户查看 `岗位说明` 字段说明或 tips
- **THEN** 页面说明该字段展示在官网 Tab 内容区
- **AND** 页面说明该字段用于详细描述 AI 为该岗位带来的价值
#### Scenario: 岗位说明为空
- **WHEN** 用户未填写 `岗位说明` 并点击 `保存`
- **THEN** 页面在 `岗位说明` 字段附近提示 `请输入岗位说明`
- **AND** 系统不提交保存
#### Scenario: 岗位说明超长
- **WHEN** 用户填写超过 200 字的 `岗位说明` 并点击 `保存`
- **THEN** 页面在 `岗位说明` 字段附近提示 `岗位说明最多200字`
- **AND** 系统不提交保存
#### Scenario: 岗位说明合法
- **WHEN** 用户填写 1 到 200 字的 `岗位说明`
- **THEN** 字段通过前端长度校验
### Requirement: AI 赋能介绍接口契约
官网岗位展示配置的前端接口契约和 mock 契约 SHALL 在详情、创建、更新和本地 fixture 中包含 `main_title` 与 `sub_title`,并写明字段长度校验规则。
#### Scenario: 新建 payload 包含 AI 赋能介绍字段
- **WHEN** 用户在新建页填写合法表单并点击 `保存`
- **THEN** 创建官网岗位 Tab 的 payload 包含 `main_title`
- **AND** 创建官网岗位 Tab 的 payload 包含 `sub_title`
#### Scenario: 编辑 payload 包含 AI 赋能介绍字段
- **WHEN** 用户在编辑页填写合法表单并点击 `保存`
- **THEN** 更新官网岗位 Tab 的 payload 包含 `main_title`
- **AND** 更新官网岗位 Tab 的 payload 包含 `sub_title`
#### Scenario: 详情数据包含 AI 赋能介绍字段
- **WHEN** 页面打开岗位展示配置编辑页并读取官网岗位 Tab 详情
- **THEN** 详情数据包含 `main_title`
- **AND** 详情数据包含 `sub_title`
#### Scenario: mock fixture 覆盖字段校验
- **WHEN** 测试或本地开发使用官网岗位 Tab mock fixture
- **THEN** fixture 覆盖 `main_title` 为空和超过 30 字
- **AND** fixture 覆盖 `sub_title` 为空和超过 200 字
### Requirement: 既有岗位展示规则保持不变
新增“岗位 AI 赋能介绍”模块 MUST NOT 改变岗位展示配置的岗位标签、渠道活码、排序、展示状态、删除、上下架和配置 Agent 跳转等既有规则。
#### Scenario: 岗位标签与渠道活码规则保持不变
- **WHEN** 用户在新建或编辑岗位展示配置时填写 AI 赋能介绍字段
- **THEN** 选择岗位标签、关联渠道活码、渠道编码和承接员工的展示与可编辑规则保持既有行为
#### Scenario: 排序与展示状态规则保持不变
- **WHEN** 用户在新建或编辑岗位展示配置时填写 AI 赋能介绍字段
- **THEN** Tab 排序和展示状态的校验、默认值与保存规则保持既有行为
#### Scenario: 列表操作规则保持不变
- **WHEN** 岗位展示配置列表存在已填写 AI 赋能介绍字段的 Tab
- **THEN** 配置 Agent、编辑、上架、下架和删除操作保持既有行为
- **AND** 删除仍不影响 Agent 原始数据和关联渠道活码
## 1. 契约与 Mock 准备
- [x] 1.1 更新官网岗位 Tab 前端契约说明,确认详情、创建 payload、更新 payload 和 mock 类型均包含 `main_title` 与 `sub_title`。
- [x] 1.2 补充 mock fixture 或 mock 操作测试,覆盖 `main_title` 为空、`main_title` 超过 30 字、`sub_title` 为空、`sub_title` 超过 200 字。
- [x] 1.3 补充合法 mock 数据,确保岗位展示配置详情能回填 `main_title` 与 `sub_title`。
## 2. 表单测试
- [x] 2.1 先编写新建页测试,覆盖”岗位 AI 赋能介绍”模块、`岗位标题`、`岗位说明`、字段 tips、合法保存 payload。
- [x] 2.2 先编写编辑页测试,覆盖详情回填 `main_title` 与 `sub_title`、修改后保存 payload 包含新值。
- [x] 2.3 先编写表单校验测试,覆盖 `岗位标题` 为空、`岗位标题` 超过 30 字、`岗位说明` 为空、`岗位说明` 超过 200 字,并确认错误展示在字段附近。
- [x] 2.4 补充回归测试,确认岗位标签、渠道活码、渠道编码、承接员工、Tab 排序、展示状态、配置 Agent、上下架和删除规则未被本变更改动。
## 3. 页面实现
- [x] 3.1 在岗位展示配置新建页和编辑页增加”岗位 AI 赋能介绍”模块。
- [x] 3.2 实现 `岗位标题` 输入项,绑定 `main_title`,展示字段 tips,并校验必填与最多 30 字。
- [x] 3.3 实现 `岗位说明` 文本域,绑定 `sub_title`,展示字段 tips,并校验必填与最多 200 字。
- [x] 3.4 在新建和编辑保存逻辑中提交 `main_title` 与 `sub_title`,并在编辑页详情加载时回填两个字段。
## 4. 验证
- [x] 4.1 运行官网岗位 Tab 相关测试,确认 AI 赋能介绍模块、payload 和校验场景通过。
- [x] 4.2 运行 `npm run typecheck`。
- [x] 4.3 运行 `npm test`。
- [x] 4.4 运行 `npm run build`。
- [ ] 4.5 使用浏览器验证 `/official-site/job-tabs/new` 和 `/official-site/job-tabs/:tabId/edit` 的模块布局、字段 tips、为空校验、超长校验和既有规则未回归。
- [ ] 4.6 运行 `openspec validate “official-site-job-tab-ai-intro” --strict`。
## Context
`workspace/agent-admin/web` 已完成后台壳、Agent 列表、岗位标签管理、Skill 目录、渠道活码和官网方法论配置等前端能力,现有页面规则沉淀在 `docs/frontend-foundation.md` 与 `docs/page-patterns.md`。本 change 基于已确认的 `docs/superpowers/specs/2026-05-22-official-site-job-tabs-design.md`,只进入官网岗位展示配置的前端实现范围,不编写后端代码。
官网岗位 Tab 以岗位标签为核心,每个岗位标签最多创建一个官网岗位 Tab。岗位与渠道活码是一对一关系;选择岗位后,页面自动展示该岗位关联渠道活码标题。渠道编码和承接员工默认隐藏,只有关联渠道活码有对应数据时才展示内容。若岗位未配置渠道活码,则提示并阻止保存。
## Goals / Non-Goals
**Goals:**
- 新增 `/official-site/job-tabs` 岗位展示配置列表页,支持关键词筛选、状态筛选、分页、表格展示、配置 Agent 跳转、编辑、上架、下架和删除。
- 新增 `/official-site/job-tabs/new` 独立新建页,支持选择岗位标签、自动展示关联渠道活码信息、填写排序和展示状态。
- 新增 `/official-site/job-tabs/:tabId/edit` 独立编辑页,锁定岗位标签、渠道活码、渠道编码和承接员工,仅允许修改排序与展示状态。
- 补充官网岗位 Tab 最小 mock 契约与 fixture,覆盖正常、空、错误、保存成功/失败、重复岗位、无渠道活码、上下架成功/失败、删除成功/失败和重试成功/失败场景。
- 保留 `/official-site/job-tabs/:tabId/agents` 跳转约定,但不实现 Agent 展示配置业务页面。
**Non-Goals:**
- 不实现 `/official-site/job-tabs/:tabId/agents` 页面内容和 Agent 展示配置能力。
- 不实现 H5 官网页面、真实后端、真实上传、CDN、嘀加 API 或企微流程。
- 不在 `workspace/agent-admin/backend` 下生成 API、模型、服务、数据库迁移或测试文件。
- 不修改官网方法论展示配置业务能力,不迁移通用 Upload 组件。
- 不实现渠道活码管理本身,只消费岗位关联渠道活码 mock 数据。
## Decisions
### Decision: 岗位展示配置使用独立列表页和独立表单子页
岗位展示配置列表使用 `/official-site/job-tabs`,新建和编辑分别使用 `/official-site/job-tabs/new` 与 `/official-site/job-tabs/:tabId/edit`。独立子页遵循 `frontend-foundation.md`:页头左侧展示返回入口和页面标题,页头右上角按顺序展示 `取消`、`保存`,表单主体承载字段。
### Decision: 新建时岗位选择驱动渠道活码展示
新建页的岗位标签为必选单选项。选择岗位后,页面通过 mock 查询该岗位关联渠道活码;存在渠道活码时展示渠道活码标题,渠道编码和承接员工默认隐藏,并在关联渠道活码有对应数据时展示内容;不存在时提示 `该岗位暂未配置渠道活码`,继续隐藏渠道编码和承接员工并阻止保存。
### Decision: 同岗位只能创建一个官网岗位 Tab
已存在官网岗位 Tab 的岗位标签不可重复创建。新建页选择候选项或保存时都应提供明确提示,避免运营人员重复配置同一岗位。
### Decision: 编辑页锁定岗位和关联渠道活码
编辑页不允许修改岗位标签、关联渠道活码、渠道编码和承接员工,仅允许修改 `Tab 排序` 与 `展示状态`。渠道编码和承接员工默认隐藏,并在当前 Tab 关联渠道活码有对应数据时只读展示。这样保持官网 Tab 与岗位、渠道活码之间的关联稳定,避免前端承担迁移与冲突处理。
### Decision: 排序只做范围校验
`Tab 排序` 必须是 `0-99` 范围内整数。不同 Tab 允许使用相同排序值,不做排序冲突阻止或提示。
### Decision: 操作反馈与字段校验分层展示
新建、编辑保存成功后展示成功提示,再返回列表;保存失败时展示失败提示并停留当前页面。上架、下架、删除和列表加载失败后的重试操作都需要展示成功/失败提示。字段校验错误仍展示在字段附近,不用全局提示替代,避免用户失去字段定位。
### Decision: 删除只删除官网 Tab 配置
删除 Tab 时清理该 Tab 下所有 Agent 展示配置,但不删除 Agent 原始数据,不影响关联渠道活码。删除确认文案必须说明这一影响范围。
## Risks / Trade-offs
- [Risk] 岗位标签、渠道活码和官网 Tab mock 数据可能产生不一致。→ Mitigation: mock 层集中提供候选岗位和岗位渠道活码查询语义,页面只消费结果。
- [Risk] `/official-site/job-tabs/:tabId/agents` 暂不实现内容,用户可能误以为可配置 Agent。→ Mitigation: 本 change 只保证跳转约定,后续 change 实现页面内容。
- [Risk] 上下架影响 H5 展示,但本 change 不实现 H5。→ Mitigation: 前端只更新 mock 状态并在契约中保持 `enable`/`disable` 值,操作成功/失败通过前端提示反馈。
- [Risk] 删除影响 Agent 展示配置清理,真实后端规则后续可能细化。→ Mitigation: 当前只锁定前端确认提示、成功/失败反馈和 mock 删除语义,不锁定后端实现。
## Migration Plan
1. 补充官网岗位 Tab 最小 mock 契约与 fixture,并先编写 fixture 测试。
2. 注册 `/official-site/job-tabs`、`/official-site/job-tabs/new`、`/official-site/job-tabs/:tabId/edit` 和 `/official-site/job-tabs/:tabId/agents` 路由与导航入口。
3. 用 TDD 实现列表页搜索、筛选、分页、表格、状态、加载失败重试反馈、配置 Agent 跳转、上下架和删除操作。
4. 用 TDD 实现新建和编辑表单页、岗位渠道活码展示、字段附近校验、保存成功和失败提示。
5. 运行类型检查、测试、构建,并在浏览器中验证三个路由和关键交互。
## Open Questions
- 无。本 change 已确认采用完整后台页面方案。
## Why
官网 H5 的岗位 Tab 展示需要后台可配置入口。当前后台已有官网方法论展示配置、岗位标签和渠道活码等相邻能力,但缺少官网岗位展示配置列表、新建、编辑、上下架和删除闭环,运营人员无法调整官网岗位 Tab 的展示内容与顺序。
## What Changes
- 新增岗位展示配置列表页 `/official-site/job-tabs`,支持关键词筛选、状态筛选、分页、表格展示、加载态、空态、筛选无结果态和加载失败态。
- 新增独立新建页 `/official-site/job-tabs/new`,选择岗位标签后自动展示该岗位关联渠道活码;渠道编码和承接员工默认隐藏,关联渠道活码有数据时展示内容,并阻止重复创建和无渠道活码保存。
- 新增独立编辑页 `/official-site/job-tabs/:tabId/edit`,锁定岗位标签和渠道活码,仅允许修改 Tab 排序和展示状态。
- 新增列表行 `配置Agent` 跳转到 `/official-site/job-tabs/:tabId/agents`,本 change 不实现该页面业务内容。
- 新增新建、编辑、上架、下架、删除和重试操作的成功/失败提示;上架、下架和删除操作需要二次确认,删除文案说明会清理该 Tab 下的 Agent 展示配置。
- 补充官网岗位 Tab 前端 mock 契约与 fixture,覆盖列表、详情、候选岗位、岗位渠道活码、创建、更新、状态更新、删除和页面状态。
- 不实现 H5 官网页面、真实后端、真实上传、CDN、嘀加 API、企微流程或后端目录代码。
## Capabilities
### New Capabilities
- `official-site-job-tabs`: 覆盖官网岗位展示配置的路由导航、列表筛选分页、新建编辑表单、上下架删除、操作反馈、页面状态和最小 mock 契约。
### Modified Capabilities
- 无。
## Impact
- 影响后台前端路由与导航:在 `官网配置` 下新增 `岗位展示配置`,注册 `/official-site/job-tabs`、`/official-site/job-tabs/new`、`/official-site/job-tabs/:tabId/edit` 和占位跳转路由 `/official-site/job-tabs/:tabId/agents`。
- 影响页面实现:新增官网岗位 Tab 列表页和独立表单页,复用现有搜索区、表格、分页、表单、确认和状态组件规则。
- 影响前端 mock 契约:新增官网岗位 Tab 的最小消费字段、查询参数、表单 payload、岗位渠道活码派生信息和状态 fixture。
- 影响测试:新增契约 fixture、路由导航、列表筛选分页、表单校验保存、操作成功/失败提示、上下架确认、删除确认和关键跳转场景测试。
## ADDED Requirements
### Requirement: 官网岗位展示配置路由与导航
后台前端 SHALL 提供官网岗位展示配置列表页、独立新建页、独立编辑页,并在一级菜单 `官网配置` 下提供二级菜单 `岗位展示配置` 入口。
#### Scenario: 打开官网岗位展示配置列表页
- **WHEN** 已登录用户打开 `/official-site/job-tabs`
- **THEN** 页面展示标题 `岗位展示配置`
- **AND** 页面展示关键词搜索、状态筛选、表格、分页和页头右上角 `新建岗位展示` 操作
#### Scenario: 从导航进入岗位展示配置
- **WHEN** 用户在后台导航中选择 `岗位展示配置`
- **THEN** 系统跳转到 `/official-site/job-tabs`
- **AND** `岗位展示配置` 展示为一级菜单 `官网配置` 下的二级菜单
#### Scenario: 打开独立新建页
- **WHEN** 用户打开 `/official-site/job-tabs/new`
- **THEN** 页面展示独立表单页标题 `新建岗位展示`
- **AND** 页头左侧展示返回入口
- **AND** 页头右上角按顺序展示 `取消` 和 `保存`
#### Scenario: 打开独立编辑页
- **WHEN** 用户打开 `/official-site/job-tabs/:tabId/edit`
- **THEN** 页面展示独立表单页标题 `编辑岗位展示`
- **AND** 页头左侧展示返回入口
- **AND** 页头右上角按顺序展示 `取消` 和 `保存`
### Requirement: 官网岗位展示配置列表筛选
官网岗位展示配置列表页 SHALL 支持按官网 Tab 或关联渠道活码关键词和展示状态筛选列表,并允许用户恢复全量结果。
#### Scenario: 搜索区遵循基础规则
- **WHEN** 页面渲染岗位展示配置搜索区
- **THEN** 搜索区布局遵循 `frontend-foundation.md` 中的搜索区域规则
- **AND** 关键词输入框 placeholder 为 `搜索岗位名称或渠道活码`
- **AND** 状态筛选包含 `全部`、`已下架` 和 `展示中`
#### Scenario: 提交筛选
- **WHEN** 用户输入关键词或选择状态后点击 `搜索`
- **THEN** 页面按筛选条件刷新岗位展示配置列表
- **AND** 页面回到第 `1` 页
#### Scenario: 回车提交关键词搜索
- **WHEN** 用户在关键词输入框中输入内容并按下回车
- **THEN** 页面按当前筛选条件刷新岗位展示配置列表
- **AND** 页面回到第 `1` 页
#### Scenario: 重置筛选
- **WHEN** 用户点击 `重置`
- **THEN** 页面清空关键词并恢复状态为 `全部`
- **AND** 页面恢复默认岗位展示配置列表并回到第 `1` 页
### Requirement: 官网岗位展示配置表格与分页
官网岗位展示配置列表页 SHALL 以表格展示官网岗位 Tab 信息,并使用分页展示列表结果。
#### Scenario: 展示岗位 Tab 行
- **WHEN** 岗位展示配置列表存在数据
- **THEN** 每行展示 `官网 Tab`、`关联渠道活码`、`展示 Agent 数`、`排序`、`状态`、`更新时间` 和 `操作`
- **AND** 操作列展示 `配置Agent`、`编辑`、当前状态对应的 `上架` 或 `下架`,以及 `删除`
#### Scenario: 切换分页
- **WHEN** 用户切换页码或每页条数
- **THEN** 页面按新的分页参数展示岗位展示配置列表
- **AND** 每页条数变化后页面回到第 `1` 页
#### Scenario: 筛选无结果
- **WHEN** 当前筛选条件没有匹配的岗位展示配置
- **THEN** 页面展示筛选无结果状态
- **AND** 页面允许用户调整筛选条件或重置搜索
#### Scenario: 配置 Agent 跳转
- **WHEN** 用户在列表点击某行 `配置Agent`
- **THEN** 系统跳转到 `/official-site/job-tabs/:tabId/agents`
- **AND** 本 change 不要求该页面实现 Agent 展示配置业务内容
### Requirement: 官网岗位展示配置新建表单
官网岗位展示配置 SHALL 支持通过独立新建页创建岗位展示 Tab,并按岗位自动展示关联渠道活码信息。
#### Scenario: 新建页字段
- **WHEN** 用户打开 `/official-site/job-tabs/new`
- **THEN** 表单展示 `选择岗位标签`、`关联渠道活码`、`Tab排序` 和 `展示状态`
- **AND** `选择岗位标签` 和 `Tab排序` 为必填字段
- **AND** `关联渠道活码` 为只读展示
- **AND** `渠道编码` 和 `承接员工` 默认隐藏
- **AND** `展示状态` 默认值为 `展示中`
#### Scenario: 选择岗位后展示关联渠道活码
- **WHEN** 用户在新建页选择已配置渠道活码的岗位
- **THEN** 页面展示该岗位关联渠道活码标题
- **AND** 当关联渠道活码包含渠道编码时,页面展示渠道编码
- **AND** 当关联渠道活码包含承接员工时,页面展示承接员工
#### Scenario: 已有官网 Tab 的岗位不可再次创建
- **WHEN** 用户在新建页查看岗位选项
- **THEN** 已存在官网岗位 Tab 的岗位不可再次选择
- **AND** 页面提示 `该岗位已存在官网岗位展示,请编辑原配置`
#### Scenario: 岗位未配置渠道活码
- **WHEN** 用户在新建页选择未配置渠道活码的岗位
- **THEN** 页面提示 `该岗位暂未配置渠道活码`
- **AND** 页面隐藏 `渠道编码` 和 `承接员工`
- **AND** 系统阻止保存
#### Scenario: 新建页保存成功
- **WHEN** 用户填写合法表单并点击 `保存`
- **THEN** 系统保存官网岗位 Tab mock 数据
- **AND** 页面展示保存成功提示
- **AND** 页面返回 `/official-site/job-tabs`
#### Scenario: 新建页取消
- **WHEN** 用户在新建页点击 `取消`
- **THEN** 页面返回 `/official-site/job-tabs`
- **AND** 系统不保存当前表单修改
### Requirement: 官网岗位展示配置编辑表单
官网岗位展示配置 SHALL 支持编辑既有岗位展示 Tab 的排序和展示状态,并保持岗位和渠道活码不可修改。
#### Scenario: 编辑页字段权限
- **WHEN** 用户打开 `/official-site/job-tabs/:tabId/edit`
- **THEN** 表单展示 `选择岗位标签`、`关联渠道活码`、`Tab排序` 和 `展示状态`
- **AND** `选择岗位标签` 和 `关联渠道活码` 为只读展示
- **AND** `渠道编码` 和 `承接员工` 默认隐藏,并在关联渠道活码包含对应数据时只读展示
- **AND** `Tab排序` 和 `展示状态` 可编辑
#### Scenario: 编辑页保存成功
- **WHEN** 用户修改合法的排序或展示状态后点击 `保存`
- **THEN** 系统保存官网岗位 Tab mock 数据
- **AND** 页面展示保存成功提示
- **AND** 页面返回 `/official-site/job-tabs`
#### Scenario: 编辑页记录不存在
- **WHEN** 用户打开不存在的 `/official-site/job-tabs/:tabId/edit`
- **THEN** 页面展示可恢复的未找到或错误状态
- **AND** 页面提供返回列表入口
#### Scenario: 编辑页取消
- **WHEN** 用户在编辑页点击 `取消`
- **THEN** 页面返回 `/official-site/job-tabs`
- **AND** 系统不保存当前表单修改
### Requirement: 官网岗位展示配置表单校验与保存失败
官网岗位展示配置新建和编辑表单 SHALL 对字段规则和保存失败状态提供明确反馈。
#### Scenario: 岗位标签必选
- **WHEN** 用户在新建页未选择 `选择岗位标签` 并点击 `保存`
- **THEN** 页面在 `选择岗位标签` 字段附近提示 `请选择岗位标签`
- **AND** 系统不提交保存
#### Scenario: Tab 排序校验
- **WHEN** 用户未填写 `Tab排序` 或填写非整数或超出 `0-99` 的 `Tab排序` 并点击 `保存`
- **THEN** 页面在 `Tab排序` 字段附近提示 `Tab排序请输入0-99的整数`
- **AND** 系统不提交保存
#### Scenario: 展示状态合法性
- **WHEN** 用户提交的 `展示状态` 不是 `已下架` 或 `展示中`
- **THEN** 系统不提交保存
#### Scenario: 保存失败
- **WHEN** mock 保存官网岗位 Tab 失败
- **THEN** 页面提示 `保存失败,请重试`
- **AND** 页面停留在当前表单页
#### Scenario: 字段校验不使用全局提示替代
- **WHEN** 用户提交表单且存在字段校验错误
- **THEN** 字段校验错误展示在对应字段附近
- **AND** 页面不使用全局成功/失败提示替代字段附近错误
### Requirement: 官网岗位展示配置上架下架与删除
官网岗位展示配置列表页 SHALL 支持上架、下架和删除,并在操作前展示二次确认。
#### Scenario: 上架前确认
- **WHEN** 用户点击已下架岗位 Tab 的 `上架`
- **THEN** 页面展示上架二次确认
- **AND** 用户确认后系统将该岗位 Tab 状态更新为 `展示中`
- **AND** 页面展示上架成功提示
#### Scenario: 下架前确认
- **WHEN** 用户点击展示中岗位 Tab 的 `下架`
- **THEN** 页面展示下架二次确认
- **AND** 用户确认后系统将该岗位 Tab 状态更新为 `已下架`
- **AND** 页面展示下架成功提示
#### Scenario: 取消上下架
- **WHEN** 用户在上架或下架确认中取消
- **THEN** 系统不更新岗位 Tab 状态
- **AND** 列表保持当前数据
#### Scenario: 删除前确认
- **WHEN** 用户点击岗位 Tab 的 `删除`
- **THEN** 页面展示删除二次确认
- **AND** 确认文案说明删除会清理该 Tab 下的 Agent 展示配置
- **AND** 确认文案说明不影响 Agent 原始数据和关联渠道活码
#### Scenario: 删除成功
- **WHEN** 用户确认删除岗位 Tab
- **THEN** 系统删除官网岗位 Tab mock 数据
- **AND** 页面展示删除成功提示
- **AND** 列表刷新
#### Scenario: 上架失败
- **WHEN** 用户确认上架但 mock 状态更新失败
- **THEN** 页面展示上架失败提示
- **AND** 列表保持当前数据
#### Scenario: 下架失败
- **WHEN** 用户确认下架但 mock 状态更新失败
- **THEN** 页面展示下架失败提示
- **AND** 列表保持当前数据
#### Scenario: 删除失败
- **WHEN** 用户确认删除但 mock 删除失败
- **THEN** 页面展示删除失败提示
- **AND** 列表保持当前数据
### Requirement: 官网岗位展示配置页面状态
官网岗位展示配置 SHALL 提供正常列表、空数据、筛选无结果、加载失败、保存失败和编辑记录不存在等状态。
#### Scenario: 正常列表
- **WHEN** mock 数据源返回岗位展示配置列表
- **THEN** 页面展示表格行和分页信息
#### Scenario: 空数据
- **WHEN** mock 数据源没有任何岗位展示配置
- **THEN** 页面展示空数据状态
- **AND** 页面保留 `新建岗位展示` 入口
#### Scenario: 列表加载失败
- **WHEN** mock 数据源加载岗位展示配置列表失败
- **THEN** 页面展示加载失败状态
- **AND** 页面提供重试操作
#### Scenario: 列表重试成功
- **WHEN** 用户在加载失败状态点击重试且 mock 数据源加载成功
- **THEN** 页面展示重试成功提示
- **AND** 页面展示最新岗位展示配置列表
#### Scenario: 列表重试失败
- **WHEN** 用户在加载失败状态点击重试且 mock 数据源再次失败
- **THEN** 页面展示重试失败提示
- **AND** 页面保留加载失败状态和重试操作
### Requirement: 官网岗位展示配置最小 mock 契约
前端 mock 契约 SHALL 提供官网岗位展示配置页面需要的最小字段、查询参数、表单 payload、岗位渠道活码派生信息和状态 fixture,并且不锁定后端实现。
#### Scenario: 消费官网岗位 Tab 列表项
- **WHEN** 页面渲染官网岗位 Tab 列表 mock
- **THEN** 列表项包含 `tab_id`、`position_code`、`position_name`、`qrcode_id`、`qrcode_name`、`channel_code`、`employee_name`、`display_status`、`sort_order`、`agent_count`、`updated_at` 和 `operations`
#### Scenario: 消费官网岗位 Tab 详情
- **WHEN** 页面打开编辑页
- **THEN** mock 详情包含列表项字段
- **AND** mock 详情包含 `created_at`
#### Scenario: 消费官网岗位 Tab 查询参数
- **WHEN** 页面查询官网岗位 Tab 列表 mock
- **THEN** 查询参数支持 `keyword`、`display_status`、`page` 和 `pageSize`
- **AND** `keyword` 匹配官网 Tab 或关联渠道活码
#### Scenario: 消费岗位候选项
- **WHEN** 新建页查询可创建官网岗位 Tab 的岗位候选项
- **THEN** mock 返回岗位标签的 `position_code`、`position_name` 和是否已存在官网 Tab
#### Scenario: 消费岗位渠道活码信息
- **WHEN** 新建页根据岗位查询关联渠道活码
- **THEN** mock 返回该岗位的 `qrcode_id`、`qrcode_name`、`channel_code` 和 `employee_name`
- **AND** mock 能表达该岗位未配置渠道活码
#### Scenario: 消费官网岗位 Tab 表单 payload
- **WHEN** 页面创建或更新官网岗位 Tab mock
- **THEN** 创建 payload 包含 `position_code`、`sort_order` 和 `display_status`
- **AND** 更新 payload 仅要求 `sort_order` 和 `display_status`
#### Scenario: 消费官网岗位 Tab 状态 fixtures
- **WHEN** 测试或本地开发需要官网岗位 Tab 页面状态
- **THEN** mock 契约提供正常列表、空列表、筛选无结果、加载失败、重试成功、重试失败、分页边界、展示中、已下架、新建保存成功、新建保存失败、编辑保存成功、编辑保存失败、重复岗位、岗位未配置渠道活码、字段校验失败、上架成功、上架失败、下架成功、下架失败、删除成功和删除失败 fixtures
### Requirement: 基础组件复用约束
官网岗位展示配置 SHALL 复用既有前端基础组件和 `frontend-foundation.md` 页面规则,不在本 change 中发散基础组件体系。
#### Scenario: 复用既有组件
- **WHEN** 实现官网岗位展示配置页面
- **THEN** 页面复用既有按钮、输入框、选择器、表格、分页、反馈和确认组件
- **AND** 页面不在业务路由内临时创建可沉淀到组件库的一次性基础控件
#### Scenario: 遵循后台页面密度
- **WHEN** 渲染官网岗位展示配置列表和表单页面
- **THEN** 页面保持管理后台信息密度和可扫读性
- **AND** 页面不使用营销页式 hero、装饰卡片或无关视觉装饰
## 1. 契约与 mock fixture
- [x] 1.1 更新官网岗位 Tab 前端最小 mock 契约说明,明确列表项、详情、查询参数、表单 payload、岗位候选项、岗位渠道活码派生信息、保存、上下架、删除、重试和页面状态边界。
- [x] 1.2 先编写官网岗位 Tab mock fixture 测试,覆盖关键词过滤、状态筛选、分页、岗位候选项、岗位渠道活码查询、重复岗位阻止、无渠道活码阻止、创建成功/失败、更新成功/失败、上下架成功/失败、删除成功/失败和重试成功/失败。
- [x] 1.3 新增官网岗位 Tab mock fixture 与 mock 操作模块,覆盖正常列表、空列表、筛选无结果、加载失败、分页、展示中、已下架、新建成功、新建失败、编辑成功、编辑失败、同岗位重复、岗位未配置渠道活码、字段校验失败、上架成功、上架失败、下架成功、下架失败、删除成功、删除失败、重试成功和重试失败。
## 2. 路由与导航
- [x] 2.1 先编写路由和导航测试,覆盖 `/official-site/job-tabs`、`/official-site/job-tabs/new`、`/official-site/job-tabs/:tabId/edit` 可访问,`官网配置 > 岗位展示配置` 入口可见且高亮。
- [x] 2.2 注册官网岗位展示配置列表页、新建页、编辑页和配置 Agent 占位跳转路由,并在一级菜单 `官网配置` 下新增二级菜单 `岗位展示配置`(位于方法论展示配置上方)。
- [x] 2.3 确保本 change 不修改官网方法论配置、渠道活码管理、岗位标签管理或 Agent 表单的既有行为范围。
## 3. 列表页
- [x] 3.1 先编写官网岗位 Tab 列表页测试,覆盖标题、页头右上角 `新建岗位展示`、搜索区、状态筛选、表格列(含展示Agent数)、分页和行操作。
- [x] 3.2 实现 `/official-site/job-tabs` 列表页,复用 `frontend-foundation.md` 的列表页、搜索区、表格、分页和状态组件规则。
- [x] 3.3 实现按岗位名称或渠道活码关键词筛选(placeholder: "搜索岗位名称或渠道活码")、展示状态筛选(默认全部)和重置,搜索或重置后回到第 `1` 页。
- [x] 3.4 实现正常列表、空数据、筛选无结果和加载失败状态,加载失败提供重试入口,并在重试成功/失败时展示对应提示。
- [x] 3.5 实现列表行 `配置Agent` 跳转到 `/official-site/job-tabs/:tabId/agents`,不实现该页面业务内容。
## 4. 新建与编辑表单页
- [x] 4.1 先编写官网岗位 Tab 新建页测试,覆盖独立页面结构、页头右上角 `取消`/`保存`、字段附近校验、渠道编码和承接员工默认隐藏、岗位渠道活码展示、重复岗位阻止、无渠道活码阻止、默认展示中、Tab排序无默认值、保存成功提示和保存失败提示。
- [x] 4.2 先编写官网岗位 Tab 编辑页测试,覆盖字段权限、岗位和渠道活码只读、渠道编码和承接员工默认隐藏、有数据时只读展示、可变字段编辑、记录不存在状态、保存成功提示和保存失败提示。
- [x] 4.3 实现 `/official-site/job-tabs/new` 独立新建页,表单字段为选择岗位标签、关联渠道活码、Tab 排序(无默认值)和展示状态(默认展示中);渠道编码和承接员工默认隐藏,保存成功后返回列表。
- [x] 4.4 实现新建页选择岗位后查询岗位关联渠道活码,自动展示渠道活码标题,并在关联渠道活码有数据时展示渠道编码和承接员工内容,同时阻止已存在官网岗位 Tab 的岗位再次创建。
- [x] 4.5 实现岗位未配置渠道活码提示 `该岗位暂未配置渠道活码`,隐藏渠道编码和承接员工字段,并阻止保存。
- [x] 4.6 实现 `/official-site/job-tabs/:tabId/edit` 独立编辑页,岗位标签和关联渠道活码只读,渠道编码和承接员工默认隐藏且在关联渠道活码有数据时只读展示,仅 Tab 排序和展示状态可编辑。
- [x] 4.7 实现表单校验:岗位标签必选,Tab 排序必填且为 `0-99` 范围内整数,展示状态必须为 `已下架` 或 `展示中`,字段校验错误显示在字段附近。
- [x] 4.8 实现表单页 `取消` 返回列表且不保存,`保存` 成功时展示成功提示后返回列表,`保存` 失败时停留当前页面并展示 `保存失败,请重试`。
## 5. 上架、下架与删除
- [x] 5.1 先编写上架、下架和删除交互测试,覆盖上架确认、下架确认、删除确认、取消操作、操作成功/失败提示和列表刷新。
- [x] 5.2 实现列表行上架和下架操作,点击后先展示二次确认,确认后更新 mock 状态并刷新列表,成功/失败均展示对应提示。
- [x] 5.3 实现列表行删除操作,点击后先展示二次确认,确认文案说明会清理该 Tab 下的 Agent 展示配置且不影响 Agent 原始数据和渠道活码。
- [x] 5.4 实现确认删除后的 mock 删除和列表刷新,删除成功/失败均展示对应提示。
## 6. 验证
- [x] 6.1 运行官网岗位 Tab 相关测试,确认 TDD 场景通过。
- [x] 6.2 运行 `npm run typecheck`。
- [x] 6.3 运行 `npm test`。
- [x] 6.4 运行 `npm run build`。
- [x] 6.5 使用浏览器验证 `/official-site/job-tabs`、`/official-site/job-tabs/new`、`/official-site/job-tabs/:tabId/edit` 的布局、页头操作、搜索筛选、字段附近校验、保存成功/失败提示、上下架成功/失败提示、删除成功/失败提示、重试成功/失败提示和配置 Agent 跳转关键交互。
- [x] 6.6 更新 OpenSpec task 状态,并确认代码、测试和规范对齐后再进入归档阶段。
## Bugfix 记录
- [x] 2026-05-22: 菜单顺序调整 - 岗位展示配置移至方法论展示配置上方
- [x] 2026-05-22: 搜索 placeholder 更新为 "搜索岗位名称或渠道活码"
- [x] 2026-05-22: 新建页展示状态默认值改为 "展示中" (enable)
- [x] 2026-05-22: Tab排序字段移除默认值,用户需手动输入
- [x] 2026-05-22: 列表页新增 "展示Agent数" 列
- [x] 2026-05-22: 展示状态筛选默认值改为 "全部" (使用 'all' 替代空字符串)
\ No newline at end of file \ No newline at end of file
schema: spec-driven
created: 2026-05-20
\ No newline at end of file \ No newline at end of file
## Context
当前 `agent-admin` 的部分共享 UI 组件采用自建实现,但在 `Select`、文件上传、图片上传这三个场景中,问题集中且修复成本持续上升。直接让页面改用 `tdesign-react` 虽然可行,但会导致页面层的 import 和依赖边界变化,不适合当前阶段。
因此本次选择保留 `packages/ui` 作为项目内共享 UI 边界,在该层内部对 `tdesign-react` 做薄封装,以较小改动完成问题组件替换。
后续在官网方法论配置页发现,`FormItem` 将整项内容渲染为 `label`,当内部组合图片上传控件时,隐藏的文件输入会成为该 `label` 的关联控件。浏览器原生标签行为会让点击字段区域内的非上传位置也触发文件选择,包括上传虚线框外区域,以及悬浮后出现的预览、删除按钮。这类问题属于共享表单组件与复杂上传控件的组合语义问题,而不是方法论业务页面的专有事件绑定问题。
## Goals / Non-Goals
**Goals:**
- 通过调整底层实现策略,稳定 `Select` 单选、多选场景的交互与展示
- 通过引入成熟组件能力,修复文件上传、图片上传的关键交互问题
- 修复 `FormItem` 与包含文件输入的复杂控件组合时的误触发问题
- 保持页面侧导入路径不变,并尽量复用 `tdesign-react` 的原生 props 语义
- 将影响范围收敛在 `agent-admin` 项目内
**Non-Goals:**
- 不修改全局组件规范
- 不让业务页面直接依赖 `tdesign-react`
- 不一次性迁移 `agent-admin` 的全部共享组件
- 不在本次 change 中扩展超出当前页面所需的复杂上传能力
- 不在具体业务页面通过零散 `stopPropagation`、`preventDefault` 临时绕过共享组件语义问题
## Decisions
### 1. 保留 `packages/ui` 边界,不让页面直接依赖 `tdesign-react`
页面继续从 `packages/ui` 导入组件,避免业务页面直接绑定第三方库 API。这样可以减少依赖边界变化,并保留后续继续调整实现的空间。
### 2. 仅替换问题集中的三个组件
本次仅处理以下组件:
- `Select` 单选、多选
- 文件上传
- 图片上传
其余组件保持现状,避免 change 范围失控。
### 3. 采用“薄封装”而非二次自建组件库
封装层只负责以下内容:
- 维持 `packages/ui` 的导出边界
- 补齐项目内需要的默认样式、文案和最小数据映射
- 在必要时对 `tdesign-react` 数据结构做轻量适配
本次不优先兼容历史自定义扩展属性,也不重新抽象一套完整的通用组件协议,避免维护成本过高。对于 `Select`,优先采用 `tdesign-react` 现有 props 语义,多选默认按组件原生标签态表现,不再额外保留 `multipleDisplay="tags"`、`multipleTagClosable={false}` 这类自定义包装属性。
实施时明确不做旧自定义 API 兼容层、不新增 `tdesign-react` 原生能力之外的额外包装属性,也不借本次迁移重构无关页面结构或业务逻辑。
### 4. 页面行为以当前已确认需求为准,不借机扩展功能
本次目标是修复现有问题并稳定交付,不新增超出当前页面所需的高级上传能力、复杂异步传输能力或额外筛选交互。
### 5. 图片上传交互遵循 `tdesign-react` 默认能力
图片上传场景直接采用 `tdesign-react` 组件内建的预览、删除等交互能力,不额外保留当前业务页中的自定义“点击预览后再触发删除确认”逻辑。预览和删除应作为两个独立操作暴露给用户,由组件默认交互完成。
### 6. 上传文件状态采用 `tdesign-react` 原生枚举
文件上传和图片上传的文件状态字段改为使用 `tdesign-react` `UploadFile.status` 的原生枚举值:`success`、`fail`、`progress`、`waiting`。现有 `done`、`uploading`、`error` 等自建状态枚举不再作为 `packages/ui` 上传组件的对外状态协议。
### 7. `FormItem` 不用整项 `label` 包裹复杂控件
`FormItem` 应避免把包含上传、预览、删除等多操作区域的复杂控件整体包在原生 `label` 内。后续修复应把字段容器与标签文本拆开:外层使用普通容器承载布局、错误和帮助文案;标签文本只负责视觉展示和必要的可访问性关联。对于普通输入控件,可通过明确的 `id` / `htmlFor` 或控件自身语义建立关联;对于图片上传、文件上传等内部含隐藏 file input 的控件,不应让整个字段区域成为文件输入的点击代理。
该决策将误触发问题收敛在共享 `FormItem` 与上传组合层解决,避免在官网方法论页面针对步骤图标、内容图分别添加页面级事件拦截。修复完成后,只有上传组件明确的上传入口可以触发选择文件;预览、删除和字段区域内的其他空白位置不触发上传选择。
### 8. FormItem 结构调整实现方案
为落实 Decision 7,`FormItem` 组件结构调整如下:
1. **外层容器改为 `<div>`**:不再使用 `<label>` 包裹整个表单项,避免浏览器原生 label 行为让整个字段区域成为隐藏 file input 的点击代理。
2. **标签文本单独使用 `<label>` 元素**:标签文本部分单独渲染为 `<label>` 元素,仅负责视觉展示和可访问性语义。
3. **普通输入控件通过 `id` / `htmlFor` 建立关联**:对于普通输入控件(如 Input、Textarea、Select),通过给控件分配唯一 `id` 并让 label 的 `htmlFor` 指向该 id,保留点击标签聚焦输入的原生体验。
4. **复杂控件(如上传组件)不建立 label 关联**:对于内部包含隐藏 file input 的复杂控件(如 MediaWall、UploadDragger),不建立 label 的 htmlFor 关联,确保点击标签或字段空白区域不会触发文件选择。
此方案不影响普通输入控件的点击 label 聚焦体验,同时彻底解决了 FormItem 与上传组件组合时的误触发问题。
## Risks / Trade-offs
- [风险] `packages/ui` 与 `tdesign-react` 的 props 存在语义差异。
-> 缓解:只适配当前页面已使用的最小接口,不一次性做大而全映射。
- [风险] 上传类组件迁移时,已有页面测试可能需要调整。
-> 缓解:先补组件级测试,再修页面测试。
- [风险] 现有业务页对图片上传交互有自定义实现,迁移后测试断言和页面事件绑定会变化。
-> 缓解:以 `tdesign-react` 默认预览、删除交互为准,移除与默认行为冲突的页面层逻辑,并同步更新测试。
- [风险] 上传状态枚举从自建值切换到 `tdesign-react` 原生值后,Demo 数据、测试断言和页面状态判断会变化。
-> 缓解:统一按 `success`、`fail`、`progress`、`waiting` 更新类型、示例数据和测试用例,不保留旧枚举别名。
- [风险] 薄封装如果承担过多职责,会再次演化为高维护成本组件层。
-> 缓解:本次明确限制封装范围,仅服务当前项目已落地场景。
- [风险] 为了兼容旧页面写法而保留历史自定义 API,会让薄封装重新背负旧组件债。
-> 缓解:直接迁移受影响页面到 `tdesign-react` 原生 props 语义,不保留旧 API 别名,不新增额外包装属性,不做无关页面重构。
- [风险] 调整 `FormItem` 的原生标签结构可能影响普通输入控件点击 label 聚焦的体验。
-> 缓解:拆分结构时为普通输入保留明确的 `id` / `htmlFor` 关联,并补充普通输入与上传组合两类测试。
- [风险] 只在方法论页面拦截点击事件会掩盖共享组件问题,其他上传表单仍可能复现。
-> 缓解:在 `packages/ui` 的 `FormItem` 与上传组合层修复,并用方法论页面做浏览器回归验证。
## Migration Plan
1. 梳理当前页面对 `Select`、文件上传、图片上传的实际使用方式
2. 在 `packages/ui` 中为这三个组件引入 `tdesign-react` 薄封装实现
3. 保持页面侧导入路径不变,并将与 `tdesign-react` 原生 props 语义不一致的页面调用调整为最小兼容写法
4. 调整组件测试与受影响页面测试
5. 运行类型检查、测试、构建,并进行浏览器验证
6. 针对图片上传误触发回归,补充 `FormItem` 与上传组合测试,调整整项 `label` 结构,并回归验证官网方法论配置页
## Why
当前 `agent-admin` 项目中的部分共享 UI 组件在复杂交互场景下问题较多,继续基于现有自建实现逐项修补,成本高且稳定性风险较大。当前最突出的问题集中在以下组件:
1. `Select` 单选和多选场景的交互与展示不稳定
2. 文件上传组件在交互、状态展示或能力边界上存在问题
3. 图片上传组件在交互与展示上存在问题
4. `FormItem` 与图片上传组合时,整项 `label` 包裹嵌套文件输入,导致点击上传虚线框外区域、预览按钮或删除按钮也可能触发选择文件
为降低本次修复对页面层的影响,本次只在 `agent-admin` 项目内调整组件实现策略:页面继续通过 `packages/ui` 使用共享组件,由 `packages/ui` 在内部对 `tdesign-react` 做薄封装,优先替换当前问题最集中的组件。
## What Changes
- 仅在 `agent-admin` 项目内调整共享 UI 的实现策略
- 页面层继续使用 `packages/ui` 导出的组件接口
- `packages/ui` 内部针对以下组件改为基于 `tdesign-react` 的薄封装:
- `Select`(单选、多选)
- 文件上传
- 图片上传
- 根据新的实现边界,补充或调整对应测试、样式约束和使用约定
- 修复 `FormItem` 与图片上传等复杂控件组合时的标签语义,确保只有明确上传入口触发文件选择
## Non-Goals
- 不修改全局 `architecture-spec` 中的组件规范
- 不把 `agent-admin` 的全部组件迁移到 `tdesign-react`
- 不让业务页面直接依赖 `tdesign-react`
- 不在本次 change 中扩展无关组件或重构无关页面
- 不在方法论配置页面通过临时事件阻断绕过共享组件问题
## Capabilities
### Modified Capabilities
- `ui-component-library`: 调整 `agent-admin` 项目内 `Select`、文件上传、图片上传与 `FormItem` 组合场景的底层实现策略
## Impact
- 影响 `workspace/agent-admin/web/packages/ui` 中相关组件实现
- 影响 `FormItem` 与包含文件输入的复杂控件组合方式
- 可能影响已使用上述组件的页面表现、类型约束和测试
- 不影响其他项目的组件选型与实现策略
## ADDED Requirements
### Requirement: FormItem safe composition with upload controls
`FormItem` SHALL support composing file upload and image upload controls without making the entire form item a proxy for the nested file input.
#### Scenario: Upload field empty area does not open file picker
- **WHEN** a user clicks inside a `FormItem` that contains an upload control but outside the upload control's explicit trigger area
- **THEN** the system SHALL NOT open the file picker
#### Scenario: Upload preview action does not open file picker
- **WHEN** a user hovers an uploaded image and clicks the preview action
- **THEN** the system SHALL run the preview interaction
- **AND** the system SHALL NOT open the file picker
#### Scenario: Upload delete action does not open file picker
- **WHEN** a user hovers an uploaded image and clicks the delete action
- **THEN** the system SHALL run the delete interaction
- **AND** the system SHALL NOT open the file picker
#### Scenario: Explicit upload trigger opens file picker
- **WHEN** a user clicks the upload control's explicit upload trigger
- **THEN** the system SHALL open the file picker
## 1. OpenSpec 对齐
- [x] 1.1 更新 `proposal.md`,明确本次为 `agent-admin` 项目级局部组件实现策略调整
- [x] 1.2 更新 `design.md`,明确 `packages/ui` 薄封装 `tdesign-react` 的方案与边界
- [x] 1.3 用户确认更新后的 OpenSpec artifacts
## 2. Select 组件迁移
- [x] 2.1 梳理当前页面对 `Select` 单选、多选的实际用法与 props 依赖
- [x] 2.2 在 `packages/ui` 中将 `Select` 改为基于 `tdesign-react` 的薄封装
- [x] 2.3 移除页面侧对历史自定义 `Select` 扩展属性的依赖,按 `tdesign-react` 原生 props 语义做最小兼容调整
- [x] 2.4 确认不保留 `multipleDisplay`、`multipleTagClosable` 等旧自定义 API,也不新增额外包装属性
- [x] 2.5 补充或更新 `Select` 相关组件测试
## 3. 上传组件迁移
- [x] 3.1 梳理当前页面对文件上传、图片上传的实际用法与交互要求
- [x] 3.2 将上传文件状态枚举从 `done`、`uploading`、`error` 调整为 `tdesign-react` 原生的 `success`、`progress`、`fail`、`waiting`
- [x] 3.3 在 `packages/ui` 中实现基于 `tdesign-react` 的文件上传薄封装
- [x] 3.4 在 `packages/ui` 中实现基于 `tdesign-react` 的图片上传薄封装
- [x] 3.5 将页面层与 `tdesign-react` 默认预览、删除交互冲突的自定义图片操作逻辑替换掉
- [x] 3.6 确认不保留旧上传状态别名,也不新增超出 `tdesign-react` 原生能力的额外包装属性
- [x] 3.7 补充或更新上传组件相关测试
## 4. 页面联调与验证
- [x] 4.1 调整受影响页面的最小兼容代码,不重构无关页面结构或业务逻辑
- [x] 4.2 运行类型检查
- [x] 4.3 运行相关测试
- [x] 4.4 运行构建验证
- [x] 4.5 在浏览器中验证 `Select`、文件上传、图片上传的关键交互
## 5. 图片上传误触发修复
- [x] 5.1 更新受影响的 OpenSpec artifacts,明确 `FormItem` 不应通过整项 `label` 包裹复杂控件并触发嵌套文件输入
- [x] 5.2 补充或更新 `FormItem` 与图片上传组合测试,覆盖点击上传虚线框外区域不会打开文件选择弹窗
- [x] 5.3 补充或更新图片上传操作测试,覆盖悬浮后点击预览、删除按钮不会触发上传选择
- [x] 5.4 调整共享表单/上传组合实现,确保只有明确的上传入口触发选择文件,不在方法论业务页面添加临时绕行逻辑
- [x] 5.5 在浏览器中回归验证 `/official-site/methodology` 的步骤图标和内容图上传交互
## ADDED Requirements
### Requirement: 岗位标签管理路由与导航
岗位 Agent 管理后台 SHALL 提供岗位标签管理列表页和独立新建、编辑页面,并在后台导航中提供岗位标签管理入口。
#### Scenario: 打开岗位标签列表页
- **WHEN** 已登录用户打开 `/agent-tags`
- **THEN** 页面展示标题 `岗位标签管理`
- **AND** 页面展示标签名称搜索区、表格、分页和页头右上角 `新建岗位标签` 操作
#### Scenario: 从导航进入岗位标签管理
- **WHEN** 用户在后台导航中选择 `岗位标签管理`
- **THEN** 系统跳转到 `/agent-tags`
- **AND** 导航入口归属于 `Agent管理` 相关分组
#### Scenario: 打开独立新建页
- **WHEN** 用户打开 `/agent-tags/new`
- **THEN** 页面展示独立表单页标题 `新建岗位标签`
- **AND** 页头左侧展示返回入口
- **AND** 页头右上角按顺序展示 `取消` 和 `保存`
#### Scenario: 打开独立编辑页
- **WHEN** 用户打开 `/agent-tags/:tagId/edit`
- **THEN** 页面展示独立表单页标题 `编辑岗位标签`
- **AND** 页头左侧展示返回入口
- **AND** 页头右上角按顺序展示 `取消` 和 `保存`
### Requirement: 岗位标签名称搜索
岗位标签列表页 SHALL 允许用户通过标签名称搜索岗位标签。
#### Scenario: 搜索区遵循基础规则
- **WHEN** 页面渲染岗位标签搜索区
- **THEN** 搜索区布局遵循 `frontend-foundation.md` 中的搜索区域规则
- **AND** 标签名称输入框宽度为 `200px`
- **AND** 标签名称输入框 placeholder 为 `请输入标签名称`
- **AND** 页面不为本次范围额外引入不必要的下拉筛选项
#### Scenario: 提交标签名称搜索
- **WHEN** 用户输入标签名称并点击 `搜索`
- **THEN** 页面按标签名称刷新岗位标签列表
- **AND** 页面回到第 `1` 页
#### Scenario: 回车提交标签名称搜索
- **WHEN** 用户在标签名称输入框中输入内容并按下回车
- **THEN** 页面按标签名称刷新岗位标签列表
- **AND** 页面回到第 `1` 页
#### Scenario: 重置关键词
- **WHEN** 用户点击 `重置`
- **THEN** 页面清空关键词输入
- **AND** 页面恢复默认岗位标签列表并回到第 `1` 页
### Requirement: 岗位标签表格与分页
岗位标签列表页 SHALL 以表格展示岗位标签信息,并使用分页展示列表结果。
#### Scenario: 展示岗位标签行
- **WHEN** 岗位标签列表存在数据
- **THEN** 每行展示 `标签名称`、`标签编码`、`标签描述`、`使用 Agent 数`、`关联渠道活码数`、`关联官网 Tab 数`、`创建时间` 和 `操作`
- **AND** 操作列展示 `编辑` 和 `删除`
#### Scenario: 切换分页
- **WHEN** 用户切换页码或每页条数
- **THEN** 页面按新的分页参数展示岗位标签列表
- **AND** 每页条数变化后页面回到第 `1` 页
#### Scenario: 筛选无结果
- **WHEN** 当前标签名称没有匹配的标签
- **THEN** 页面展示筛选无结果状态
- **AND** 页面允许用户调整标签名称或重置搜索
### Requirement: 岗位标签新建表单
岗位标签管理 SHALL 支持通过独立新建页创建岗位标签。
#### Scenario: 新建页字段
- **WHEN** 用户打开 `/agent-tags/new`
- **THEN** 表单展示 `标签名称`、`标签编码` 和 `标签描述`
- **AND** `标签名称` 和 `标签编码` 为必填字段
- **AND** `标签编码` 在新建页可编辑
#### Scenario: 新建页保存成功
- **WHEN** 用户填写合法且不重复的标签名称、标签编码和标签描述后点击 `保存`
- **THEN** 系统保存岗位标签 mock 数据
- **AND** 页面返回 `/agent-tags`
#### Scenario: 新建页取消
- **WHEN** 用户在新建页点击 `取消`
- **THEN** 页面返回 `/agent-tags`
- **AND** 系统不保存当前表单修改
### Requirement: 岗位标签编辑表单
岗位标签管理 SHALL 支持通过独立编辑页编辑岗位标签名称和描述,并保持标签编码不可修改。
#### Scenario: 从列表行进入编辑页
- **WHEN** 用户在岗位标签列表点击某行 `编辑`
- **THEN** 系统跳转到 `/agent-tags/:tagId/edit`
- **AND** 编辑页优先使用该行数据初始化 `标签名称`、`标签编码` 和 `标签描述`
#### Scenario: 刷新或直达编辑页
- **WHEN** 用户刷新或直接打开 `/agent-tags/:tagId/edit`
- **THEN** 编辑页从岗位标签列表 mock 数据源中按 `tagId` 查找当前记录
- **AND** 找到记录后使用列表最小字段初始化表单
#### Scenario: 编辑页不依赖详情接口
- **WHEN** 编辑页初始化表单
- **THEN** 系统不要求岗位标签详情接口或详情 mock 契约
- **AND** 表单初始值仅来自列表行数据或列表 mock 数据源兜底结果
#### Scenario: 编辑页编码只读
- **WHEN** 用户打开编辑页
- **THEN** `标签编码` 展示为只读
- **AND** 用户不能修改标签编码
#### Scenario: 编辑页保存成功
- **WHEN** 用户修改合法的标签名称或标签描述后点击 `保存`
- **THEN** 系统保存岗位标签 mock 数据
- **AND** 页面返回 `/agent-tags`
#### Scenario: 编辑页记录不存在
- **WHEN** 用户打开不存在的 `/agent-tags/:tagId/edit`
- **THEN** 页面展示可恢复的未找到或错误状态
- **AND** 页面提供返回列表入口
### Requirement: 岗位标签表单校验与保存失败
岗位标签新建和编辑表单 SHALL 对字段规则和保存失败状态提供明确反馈。
#### Scenario: 标签名称必填
- **WHEN** 用户未填写 `标签名称` 并点击 `保存`
- **THEN** 页面提示 `请输入标签名称`
- **AND** 系统不提交保存
#### Scenario: 标签名称长度限制
- **WHEN** 用户填写超过 20 字的 `标签名称` 并点击 `保存`
- **THEN** 页面提示 `标签名称最多20字`
- **AND** 系统不提交保存
#### Scenario: 标签编码必填
- **WHEN** 用户在新建页未填写 `标签编码` 并点击 `保存`
- **THEN** 页面提示 `请输入标签编码`
- **AND** 系统不提交保存
#### Scenario: 标签编码格式限制
- **WHEN** 用户在新建页填写非英文或非下划线字符的 `标签编码` 并点击 `保存`
- **THEN** 页面提示 `标签编码仅支持英文和下划线`
- **AND** 系统不提交保存
#### Scenario: 标签编码不可重复
- **WHEN** 用户在新建页填写已存在的 `标签编码` 并点击 `保存`
- **THEN** 页面提示 `标签编码已存在`
- **AND** 系统不提交保存
#### Scenario: 标签描述长度限制
- **WHEN** 用户填写超过 100 字的 `标签描述` 并点击 `保存`
- **THEN** 页面提示 `标签描述最多100字`
- **AND** 系统不提交保存
#### Scenario: 保存失败
- **WHEN** mock 保存岗位标签失败
- **THEN** 页面提示 `保存失败,请重试`
- **AND** 页面停留在当前表单页
### Requirement: 岗位标签删除引用检查
岗位标签列表页 SHALL 在删除前检查岗位标签引用,并根据 Agent、渠道活码和官网 Tab 引用结果执行确认或阻断。
#### Scenario: 删除前检查引用
- **WHEN** 用户点击岗位标签的 `删除`
- **THEN** 页面先获取该岗位标签的引用检查结果
- **AND** 引用检查结果包含阻塞性引用和可解除的 Agent 引用
#### Scenario: 无引用时确认删除
- **WHEN** 引用检查结果中不存在 Agent、渠道活码和官网 Tab 引用
- **THEN** 页面展示删除二次确认
- **AND** 用户确认后系统从 mock 数据中移除该标签并刷新列表
#### Scenario: 取消删除
- **WHEN** 用户在删除确认中取消
- **THEN** 系统不删除岗位标签
- **AND** 列表保持当前数据
#### Scenario: Agent 引用需确认解除
- **WHEN** 引用检查结果仅包含 Agent 引用
- **THEN** 页面允许继续删除确认
- **AND** 确认文案包含 `删除后这些 Agent 将失去该标签`
- **AND** 用户确认后系统删除岗位标签并使这些 Agent 失去该标签
#### Scenario: 被渠道活码引用不可删除
- **WHEN** 引用检查结果包含渠道活码引用
- **THEN** 页面阻断删除
- **AND** 页面提示 `请先删除关联的渠道活码`
#### Scenario: 被官网 Tab 引用不可删除
- **WHEN** 引用检查结果包含官网 Tab 引用
- **THEN** 页面阻断删除
- **AND** 页面提示 `请先删除关联的官网 Tab 配置`
#### Scenario: 同时存在阻塞引用和 Agent 引用
- **WHEN** 引用检查结果同时包含 Agent 引用以及渠道活码或官网 Tab 引用
- **THEN** 页面阻断删除
- **AND** 页面优先提示需要先删除关联的渠道活码或官网 Tab 配置
- **AND** 系统不进入 Agent 解除确认
#### Scenario: 引用全部解除后方可删除
- **WHEN** 渠道活码和官网 Tab 引用已全部解除
- **THEN** 页面允许按无引用或仅 Agent 引用流程继续删除
#### Scenario: 引用检查失败
- **WHEN** 删除前引用检查失败
- **THEN** 页面不删除岗位标签
- **AND** 页面展示可恢复的失败提示
### Requirement: 岗位标签页面状态
岗位标签管理 SHALL 提供正常列表、空数据、筛选无结果、加载失败、保存失败和编辑记录不存在等状态。
#### Scenario: 正常列表
- **WHEN** mock 数据源返回岗位标签列表
- **THEN** 页面展示表格行和分页信息
#### Scenario: 空数据
- **WHEN** mock 数据源没有任何岗位标签
- **THEN** 页面展示空数据状态
- **AND** 页面保留 `新建岗位标签` 入口
#### Scenario: 列表加载失败
- **WHEN** mock 数据源加载岗位标签列表失败
- **THEN** 页面展示加载失败状态
- **AND** 页面提供重试操作
### Requirement: 岗位标签最小 mock 契约
前端 mock 契约 SHALL 提供岗位标签管理页面需要的最小字段、查询参数、表单 payload 和状态 fixture,并且不锁定后端实现。
#### Scenario: 消费岗位标签列表项
- **WHEN** 页面渲染岗位标签列表 mock
- **THEN** 列表项包含 `tag_id`、`name`、`code`、`description`、`agent_count`、`channel_code_count`、`official_tab_count` 和 `created_at`
#### Scenario: 消费岗位标签查询参数
- **WHEN** 页面查询岗位标签列表 mock
- **THEN** 查询参数仅要求支持 `keyword`、`page` 和 `pageSize`
- **AND** `keyword` 仅匹配标签名称
#### Scenario: 消费岗位标签表单 payload
- **WHEN** 页面保存岗位标签 mock
- **THEN** 表单 payload 仅包含 `name`、`code` 和 `description`
#### Scenario: 不定义详情契约
- **WHEN** 页面进入编辑流程
- **THEN** mock 契约不要求岗位标签详情接口
- **AND** 编辑页使用列表行数据或列表 mock 数据源兜底初始化表单
#### Scenario: 消费岗位标签引用检查 fixture
- **WHEN** 页面执行岗位标签删除前引用检查
- **THEN** mock 契约提供与 `GET /api/v1/position-tags/{tag_id}/references` 对齐的最小引用检查结果
- **AND** 引用检查结果区分 `blocking_references` 和 `detachable_references`
#### Scenario: 消费岗位标签页面状态 fixtures
- **WHEN** 测试或本地开发需要岗位标签页面状态
- **THEN** mock 契约提供正常列表、空数据、筛选无结果、编码重复、删除可确认、仅 Agent 引用需确认、被渠道活码引用不可删除、被官网 Tab 引用不可删除、引用检查失败、加载失败和保存失败 fixtures
### Requirement: 基础组件复用约束
岗位标签管理 SHALL 复用既有前端基础组件和 `frontend-foundation.md` 页面规则,不在本 change 中发散基础组件体系。
#### Scenario: 复用既有组件
- **WHEN** 页面实现搜索区、表格、分页、表单、按钮和状态反馈
- **THEN** 页面优先复用现有内部组件和基础页面规则
#### Scenario: 基础组件规则存在缺口
- **WHEN** 实现过程中发现现有基础组件或 `frontend-foundation.md` 规则无法覆盖岗位标签页面细节
- **THEN** 只记录为后续 foundation OpenSpec 候选
- **AND** 不在本业务 change 中扩展基础组件体系
# official-site-job-tab-ai-intro Specification
## Purpose
TBD - created by archiving change official-site-job-tab-ai-intro. Update Purpose after archive.
## Requirements
### Requirement: 岗位 AI 赋能介绍模块
官网岗位展示配置新建页和编辑页 SHALL 提供“岗位 AI 赋能介绍”模块,用于维护官网岗位 Tab 的 AI 赋能介绍文案。
#### Scenario: 新建页展示 AI 赋能介绍模块
- **WHEN** 已登录用户打开 `/official-site/job-tabs/new`
- **THEN** 表单展示模块标题 `岗位 AI 赋能介绍`
- **AND** 模块内展示 `岗位标题` 输入项
- **AND** 模块内展示 `岗位说明` 输入项
#### Scenario: 编辑页展示并回填 AI 赋能介绍模块
- **WHEN** 已登录用户打开 `/official-site/job-tabs/:tabId/edit`
- **THEN** 表单展示模块标题 `岗位 AI 赋能介绍`
- **AND** `岗位标题` 回填当前官网岗位 Tab 的 `main_title`
- **AND** `岗位说明` 回填当前官网岗位 Tab 的 `sub_title`
#### Scenario: 编辑页允许修改 AI 赋能介绍
- **WHEN** 用户在编辑页修改 `岗位标题` 或 `岗位说明` 后点击 `保存`
- **THEN** 系统使用修改后的 `main_title` 和 `sub_title` 保存官网岗位 Tab
- **AND** 保存成功后页面返回 `/official-site/job-tabs`
### Requirement: 岗位标题字段
官网岗位展示配置新建页和编辑页 SHALL 提供 `岗位标题` 字段,对应接口字段 `main_title`,该字段必填且最多 30 字。
#### Scenario: 岗位标题语义
- **WHEN** 用户查看 `岗位标题` 字段说明或 tips
- **THEN** 页面说明该字段展示在官网 Tab 名称下方
- **AND** 页面说明该字段用于一句话介绍 AI 如何赋能该岗位
#### Scenario: 岗位标题为空
- **WHEN** 用户未填写 `岗位标题` 并点击 `保存`
- **THEN** 页面在 `岗位标题` 字段附近提示 `请输入岗位标题`
- **AND** 系统不提交保存
#### Scenario: 岗位标题超长
- **WHEN** 用户填写超过 30 字的 `岗位标题` 并点击 `保存`
- **THEN** 页面在 `岗位标题` 字段附近提示 `岗位标题最多30字`
- **AND** 系统不提交保存
#### Scenario: 岗位标题合法
- **WHEN** 用户填写 1 到 30 字的 `岗位标题`
- **THEN** 字段通过前端长度校验
### Requirement: 岗位说明字段
官网岗位展示配置新建页和编辑页 SHALL 提供 `岗位说明` 字段,对应接口字段 `sub_title`,该字段必填且最多 200 字。
#### Scenario: 岗位说明语义
- **WHEN** 用户查看 `岗位说明` 字段说明或 tips
- **THEN** 页面说明该字段展示在官网 Tab 内容区
- **AND** 页面说明该字段用于详细描述 AI 为该岗位带来的价值
#### Scenario: 岗位说明为空
- **WHEN** 用户未填写 `岗位说明` 并点击 `保存`
- **THEN** 页面在 `岗位说明` 字段附近提示 `请输入岗位说明`
- **AND** 系统不提交保存
#### Scenario: 岗位说明超长
- **WHEN** 用户填写超过 200 字的 `岗位说明` 并点击 `保存`
- **THEN** 页面在 `岗位说明` 字段附近提示 `岗位说明最多200字`
- **AND** 系统不提交保存
#### Scenario: 岗位说明合法
- **WHEN** 用户填写 1 到 200 字的 `岗位说明`
- **THEN** 字段通过前端长度校验
### Requirement: AI 赋能介绍接口契约
官网岗位展示配置的前端接口契约和 mock 契约 SHALL 在详情、创建、更新和本地 fixture 中包含 `main_title` 与 `sub_title`,并写明字段长度校验规则。
#### Scenario: 新建 payload 包含 AI 赋能介绍字段
- **WHEN** 用户在新建页填写合法表单并点击 `保存`
- **THEN** 创建官网岗位 Tab 的 payload 包含 `main_title`
- **AND** 创建官网岗位 Tab 的 payload 包含 `sub_title`
#### Scenario: 编辑 payload 包含 AI 赋能介绍字段
- **WHEN** 用户在编辑页填写合法表单并点击 `保存`
- **THEN** 更新官网岗位 Tab 的 payload 包含 `main_title`
- **AND** 更新官网岗位 Tab 的 payload 包含 `sub_title`
#### Scenario: 详情数据包含 AI 赋能介绍字段
- **WHEN** 页面打开岗位展示配置编辑页并读取官网岗位 Tab 详情
- **THEN** 详情数据包含 `main_title`
- **AND** 详情数据包含 `sub_title`
#### Scenario: mock fixture 覆盖字段校验
- **WHEN** 测试或本地开发使用官网岗位 Tab mock fixture
- **THEN** fixture 覆盖 `main_title` 为空和超过 30 字
- **AND** fixture 覆盖 `sub_title` 为空和超过 200 字
### Requirement: 既有岗位展示规则保持不变
新增“岗位 AI 赋能介绍”模块 MUST NOT 改变岗位展示配置的岗位标签、渠道活码、排序、展示状态、删除、上下架和配置 Agent 跳转等既有规则。
#### Scenario: 岗位标签与渠道活码规则保持不变
- **WHEN** 用户在新建或编辑岗位展示配置时填写 AI 赋能介绍字段
- **THEN** 选择岗位标签、关联渠道活码、渠道编码和承接员工的展示与可编辑规则保持既有行为
#### Scenario: 排序与展示状态规则保持不变
- **WHEN** 用户在新建或编辑岗位展示配置时填写 AI 赋能介绍字段
- **THEN** Tab 排序和展示状态的校验、默认值与保存规则保持既有行为
#### Scenario: 列表操作规则保持不变
- **WHEN** 岗位展示配置列表存在已填写 AI 赋能介绍字段的 Tab
- **THEN** 配置 Agent、编辑、上架、下架和删除操作保持既有行为
- **AND** 删除仍不影响 Agent 原始数据和关联渠道活码
## ADDED Requirements
### Requirement: 方法论展示配置页入口
系统 SHALL 在管理后台提供官网配置下的方法论展示配置页入口。
#### Scenario: 访问方法论展示配置路由
- **WHEN** 用户访问 `/official-site/methodology`
- **THEN** 系统 SHALL 展示方法论展示配置页
- **AND** 页面 SHALL 位于管理后台布局内
#### Scenario: 菜单归属正确
- **WHEN** 用户查看后台导航菜单
- **THEN** 系统 SHALL 在「官网配置」下提供「方法论展示配置」入口
- **AND** 当前页 SHALL 能体现该菜单归属或面包屑关系
### Requirement: 配置表单字段
系统 SHALL 在方法论展示配置页提供展示状态、主标题、副标题和步骤列表配置能力。
#### Scenario: 展示基础字段
- **WHEN** 配置加载成功
- **THEN** 系统 SHALL 展示展示状态开关、主标题输入框、副标题文本域和步骤配置区
#### Scenario: 展示状态字段
- **WHEN** 用户编辑展示状态
- **THEN** 系统 SHALL 支持 `enable` 和 `disable` 两种状态
- **AND** 展示状态 SHALL 为必填配置
#### Scenario: 主标题校验
- **WHEN** 用户保存空主标题或超过 30 字的主标题
- **THEN** 系统 SHALL 阻止保存
- **AND** 系统 SHALL 在主标题字段附近展示校验错误
#### Scenario: 副标题校验
- **WHEN** 用户保存空副标题或超过 100 字的副标题
- **THEN** 系统 SHALL 阻止保存
- **AND** 系统 SHALL 在副标题字段附近展示校验错误
### Requirement: 步骤配置
系统 SHALL 支持方法论步骤的添加、删除、排序和步骤字段校验。
#### Scenario: 添加步骤
- **WHEN** 用户点击「添加步骤」
- **THEN** 系统 SHALL 在步骤列表中新增一个可编辑步骤
- **AND** 新步骤 SHALL 可配置步骤图标、步骤名称和内容图
#### Scenario: 删除步骤
- **WHEN** 用户删除一个步骤
- **THEN** 系统 SHALL 从步骤列表移除该步骤
- **AND** 系统 SHALL 重新维护剩余步骤的排序序号
#### Scenario: 调整步骤排序
- **WHEN** 用户对步骤执行上移或下移
- **THEN** 系统 SHALL 调整步骤顺序
- **AND** 系统 SHALL 重新维护步骤排序序号
#### Scenario: 步骤名称校验
- **WHEN** 用户保存空步骤名称或超过 20 字的步骤名称
- **THEN** 系统 SHALL 阻止保存
- **AND** 系统 SHALL 在对应步骤名称字段附近展示校验错误
#### Scenario: 开启展示时步骤为空
- **WHEN** 展示状态为 `enable` 且步骤列表为空时用户保存
- **THEN** 系统 SHALL 阻止保存
- **AND** 系统 SHALL 提示至少添加一个方法论步骤
#### Scenario: 关闭展示时步骤为空
- **WHEN** 展示状态为 `disable` 且步骤列表为空时用户保存
- **THEN** 系统 SHALL 允许保存基础配置
- **AND** 系统 SHALL 不要求新增步骤
### Requirement: 步骤图标配置
系统 SHALL 支持为每个方法论步骤配置展示图标资源,步骤图标 SHALL 不表示上传进度。
#### Scenario: 步骤图标必填
- **WHEN** 用户保存缺少步骤图标的步骤
- **THEN** 系统 SHALL 阻止保存
- **AND** 系统 SHALL 在对应步骤图标配置区展示校验错误
#### Scenario: 步骤图标资源语义
- **WHEN** 用户完成步骤图标配置
- **THEN** 系统 SHALL 将其作为该步骤的展示图标资源保存到配置数据
- **AND** 系统 SHALL NOT 将上传进度、上传中、重试等临时状态保存为步骤图标数据
### Requirement: 内容图上传校验
系统 SHALL 对每个步骤的内容图执行前端 mock 上传和校验。
#### Scenario: 内容图必填
- **WHEN** 用户保存缺少内容图的步骤
- **THEN** 系统 SHALL 阻止保存
- **AND** 系统 SHALL 在对应内容图上传区展示校验错误
#### Scenario: 图片格式错误
- **WHEN** 用户选择非 PNG/JPG/JPEG/GIF 的内容图文件
- **THEN** 系统 SHALL 拒绝该文件
- **AND** 系统 SHALL 展示图片格式错误提示
#### Scenario: 图片过大
- **WHEN** 用户选择超过 10MB 的内容图文件
- **THEN** 系统 SHALL 拒绝该文件
- **AND** 系统 SHALL 展示图片过大提示
#### Scenario: 图片上传失败
- **WHEN** mock 上传返回失败
- **THEN** 系统 SHALL 展示图片上传失败状态
- **AND** 系统 SHALL 允许用户重新选择或重试
### Requirement: 页面状态与保存行为
系统 SHALL 覆盖方法论展示配置页的加载、保存和错误状态。
#### Scenario: 正常配置加载
- **WHEN** mock 返回正常配置
- **THEN** 系统 SHALL 使用返回数据填充配置表单和步骤列表
#### Scenario: 关闭展示配置加载
- **WHEN** mock 返回 `display_status=disable`
- **THEN** 系统 SHALL 将展示状态开关呈现为关闭
- **AND** 系统 SHALL 允许用户继续编辑并保存配置
#### Scenario: 步骤为空配置加载
- **WHEN** mock 返回空步骤列表
- **THEN** 系统 SHALL 展示空步骤状态
- **AND** 系统 SHALL 提供添加步骤入口
#### Scenario: 加载失败
- **WHEN** mock 返回加载失败
- **THEN** 系统 SHALL 展示加载失败状态
- **AND** 系统 SHALL 提供重试入口
#### Scenario: 保存成功
- **WHEN** 用户提交合法配置且 mock 保存成功
- **THEN** 系统 SHALL 展示保存成功反馈
- **AND** 系统 SHALL 防止保存期间重复提交
#### Scenario: 保存失败
- **WHEN** 用户提交合法配置但 mock 保存失败
- **THEN** 系统 SHALL 展示保存失败提示
- **AND** 系统 SHALL 保留用户当前编辑内容以便重试
### Requirement: 最小前端 mock 契约
系统 SHALL 为方法论展示配置页提供最小前端 mock 契约和可测试 fixture,且 SHALL NOT 锁定后端实现。
#### Scenario: 配置读取契约
- **WHEN** 页面请求方法论配置
- **THEN** mock 契约 SHALL 能表达加载成功、加载失败和配置数据
- **AND** 配置数据 SHALL 包含展示状态、主标题、副标题和步骤列表
#### Scenario: 配置保存契约
- **WHEN** 页面保存方法论配置
- **THEN** mock 契约 SHALL 能表达保存请求数据、保存成功和保存失败
- **AND** 保存请求 SHALL 只包含本配置页需要的最小字段
#### Scenario: fixture 覆盖
- **WHEN** 测试读取方法论配置 mock fixture
- **THEN** fixture SHALL 覆盖正常配置、关闭展示、步骤为空、图片上传失败、图片格式错误、图片过大、保存失败和加载失败
# skill-catalog Specification
## Purpose
TBD - created by archiving change skill-list-markdown-drawer. Update Purpose after archive.
## Requirements
### Requirement: Skill 列表页结构
岗位 Agent 管理后台 SHALL 提供 `/skills` Skill 目录页,包含页面标题、关键词搜索区、只读表格和查看入口。
#### Scenario: 打开 Skill 列表页
- **WHEN** 已登录用户打开 `/skills`
- **THEN** 页面展示 Skill 目录标题
- **AND** 页面展示关键词搜索框、`搜索` 按钮、`重置` 按钮、只读表格和查看详情入口
### Requirement: 关键词搜索
Skill 目录页 SHALL 允许用户通过关键词过滤 Skill 列表。
#### Scenario: 搜索区遵循基础规则
- **WHEN** 页面渲染关键词搜索区
- **THEN** 搜索区布局遵循 `frontend-foundation.md` 中的搜索区域规则
- **AND** 关键词输入框宽度为 `200px`
- **AND** 关键词输入框 placeholder 为 `请输入Skill名称或编码`
- **AND** 页面不为该搜索区额外引入不必要的下拉筛选项
#### Scenario: 提交关键词搜索
- **WHEN** 用户输入关键词并点击 `搜索`
- **THEN** 页面根据关键词刷新 Skill 列表
- **AND** 页面将结果回到首屏状态
#### Scenario: 重置关键词
- **WHEN** 用户点击 `重置`
- **THEN** 页面清空关键词输入
- **AND** 页面恢复默认 Skill 列表
### Requirement: 只读表格
Skill 目录页 SHALL 仅以只读表格展示 Skill 目录信息,不提供写操作入口。
#### Scenario: 展示 Skill 行
- **WHEN** 页面渲染 Skill 列表
- **THEN** 每行展示 `skill_code`、`skill_name`、`description`
- **AND** 页面不展示新建、编辑、删除或批量操作入口
#### Scenario: 展示列表总数
- **WHEN** 页面渲染 Skill 列表表格
- **THEN** 页面在表格下方展示当前 Skill 总数
- **AND** 即使当前列表未启用分页,仍保留总数展示
### Requirement: 组件复用约束
Skill 列表页 SHALL 优先复用 `packages/ui` 中已有组件,并避免为单一场景临时重造重复组件能力。
#### Scenario: 复用现有组件
- **WHEN** 页面实现列表、搜索区、详情抽屉和状态反馈
- **THEN** 页面优先使用现有 `Input`、`Table`、`Drawer`、`StatePlaceholder`、`Button` 等基础组件
#### Scenario: 组件能力不足
- **WHEN** 页面发现现有组件能力不足以覆盖需求
- **THEN** 先单独记录到 `frontend-foundation.md` 或新开的基础能力 OpenSpec
- **AND** 不把公共布局、表格、分页或搜索组件规则混入本业务 change
### Requirement: 查看详情抽屉
Skill 目录页 SHALL 支持从列表页打开 Skill 详情抽屉。
#### Scenario: 查看 Skill 详情
- **WHEN** 用户点击某个 Skill 的查看入口
- **THEN** 页面打开详情抽屉
- **AND** 抽屉展示 Skill 基本信息和使用说明内容
- **AND** 关闭抽屉后返回列表上下文
### Requirement: Markdown 基础渲染
Skill 详情抽屉 SHALL 对 `doc_markdown` 提供基础 Markdown 渲染。
#### Scenario: 渲染标题与段落
- **WHEN** `doc_markdown` 包含标题、段落或列表
- **THEN** 抽屉内容按 Markdown 基础语义渲染
#### Scenario: 渲染行内代码与代码块
- **WHEN** `doc_markdown` 包含行内代码或 fenced code block
- **THEN** 抽屉展示等宽字体的代码内容
- **AND** 代码块保留换行和空白
- **AND** 长代码行可以在抽屉内横向滚动
### Requirement: 抽屉内部滚动
Skill 详情抽屉 SHALL 支持内容区独立滚动。
#### Scenario: 查看长 Markdown
- **WHEN** `doc_markdown` 内容很长
- **THEN** 抽屉内容区出现内部滚动
- **AND** 页面背景列表保持在原位置
### Requirement: 页面状态
Skill 目录页 SHALL 提供加载中、正常数据、空数据、失败和详情状态。
#### Scenario: 列表加载中
- **WHEN** Skill 列表数据正在加载
- **THEN** 页面展示加载中状态
#### Scenario: 列表空数据
- **WHEN** Skill 目录没有任何数据
- **THEN** 页面展示空数据状态
#### Scenario: 列表加载失败
- **WHEN** Skill 列表数据加载失败
- **THEN** 页面展示可恢复的失败状态
- **AND** 页面提供重试操作
#### Scenario: 详情加载失败
- **WHEN** Skill 详情加载失败
- **THEN** 详情抽屉展示失败状态
- **AND** 用户可关闭抽屉返回列表
#### Scenario: 详情空 Markdown
- **WHEN** Skill 详情返回空 `doc_markdown`
- **THEN** 抽屉展示空内容提示
### Requirement: Skill 最小 mock 契约
前端 mock 契约 SHALL 提供 Skill 列表和详情页所需的最小字段与状态 fixture。
#### Scenario: 消费 Skill 列表项
- **WHEN** 页面渲染 Skill 列表 mock
- **THEN** 列表项包含 `skill_code`、`skill_name`、`description`
#### Scenario: 消费 Skill 详情项
- **WHEN** 页面渲染 Skill 详情 mock
- **THEN** 详情项包含 `skill_code`、`skill_name`、`description`、`doc_markdown`
#### Scenario: 消费页面状态 fixtures
- **WHEN** 测试或本地开发需要 Skill 页面状态
- **THEN** mock 契约提供加载中、失败、空数据、长 Markdown、空 Markdown 和含代码块内容的 fixtures
...@@ -12,12 +12,14 @@ ...@@ -12,12 +12,14 @@
"react": "^19.2.3", "react": "^19.2.3",
"react-dom": "^19.2.3", "react-dom": "^19.2.3",
"react-router-dom": "^7.10.1", "react-router-dom": "^7.10.1",
"tdesign-react": "^1.17.0",
"typescript": "^5.9.3", "typescript": "^5.9.3",
"vite": "^7.3.0" "vite": "^7.3.0"
}, },
"devDependencies": { "devDependencies": {
"@testing-library/jest-dom": "^6.9.1", "@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.1", "@testing-library/react": "^16.3.1",
"@testing-library/user-event": "^14.6.1",
"@types/node": "^25.0.1", "@types/node": "^25.0.1",
"@types/react": "^19.2.7", "@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
...@@ -332,7 +334,6 @@ ...@@ -332,7 +334,6 @@
"version": "7.29.2", "version": "7.29.2",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz", "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz",
"integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==", "integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=6.9.0" "node": ">=6.9.0"
...@@ -1040,6 +1041,16 @@ ...@@ -1040,6 +1041,16 @@
"node": ">= 8" "node": ">= 8"
} }
}, },
"node_modules/@popperjs/core": {
"version": "2.11.8",
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz",
"integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/popperjs"
}
},
"node_modules/@rolldown/pluginutils": { "node_modules/@rolldown/pluginutils": {
"version": "1.0.0-rc.3", "version": "1.0.0-rc.3",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.3.tgz",
...@@ -1454,6 +1465,20 @@ ...@@ -1454,6 +1465,20 @@
} }
} }
}, },
"node_modules/@testing-library/user-event": {
"version": "14.6.1",
"resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.1.tgz",
"integrity": "sha512-vq7fv0rnt+QTXgPxr5Hjc210p6YKq2kmdziLgnsZGgLJ9e6VAShx1pACLuRjd/AS/sr7phAR58OIIpf0LlmQNw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12",
"npm": ">=6"
},
"peerDependencies": {
"@testing-library/dom": ">=7.21.4"
}
},
"node_modules/@types/aria-query": { "node_modules/@types/aria-query": {
"version": "5.0.4", "version": "5.0.4",
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
...@@ -1557,6 +1582,18 @@ ...@@ -1557,6 +1582,18 @@
"@types/react": "^19.2.0" "@types/react": "^19.2.0"
} }
}, },
"node_modules/@types/sortablejs": {
"version": "1.15.9",
"resolved": "https://registry.npmjs.org/@types/sortablejs/-/sortablejs-1.15.9.tgz",
"integrity": "sha512-7HP+rZGE2p886PKV9c9OJzLBI6BBJu1O7lJGYnPyG3fS4/duUCcngkNCjsLwIMV+WMqANe3tt4irrXHSIe68OQ==",
"license": "MIT"
},
"node_modules/@types/validator": {
"version": "13.15.10",
"resolved": "https://registry.npmjs.org/@types/validator/-/validator-13.15.10.tgz",
"integrity": "sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA==",
"license": "MIT"
},
"node_modules/@vitejs/plugin-react": { "node_modules/@vitejs/plugin-react": {
"version": "5.2.0", "version": "5.2.0",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.2.0.tgz", "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.2.0.tgz",
...@@ -1982,6 +2019,12 @@ ...@@ -1982,6 +2019,12 @@
"node": ">= 6" "node": ">= 6"
} }
}, },
"node_modules/classnames": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz",
"integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==",
"license": "MIT"
},
"node_modules/commander": { "node_modules/commander": {
"version": "4.1.1", "version": "4.1.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
...@@ -2075,7 +2118,6 @@ ...@@ -2075,7 +2118,6 @@
"version": "3.2.3", "version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/data-urls": { "node_modules/data-urls": {
...@@ -2102,6 +2144,12 @@ ...@@ -2102,6 +2144,12 @@
"node": ">=20" "node": ">=20"
} }
}, },
"node_modules/dayjs": {
"version": "1.11.10",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.10.tgz",
"integrity": "sha512-vjAczensTgRcqDERK0SR2XMwsF/tSvnvlv6VcF2GIhg6Sx4yOIt/irsr1RDJsKiIyBzJDpCoXiWWq28MqH2cnQ==",
"license": "MIT"
},
"node_modules/debug": { "node_modules/debug": {
"version": "4.4.3", "version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
...@@ -2158,6 +2206,16 @@ ...@@ -2158,6 +2206,16 @@
"license": "MIT", "license": "MIT",
"peer": true "peer": true
}, },
"node_modules/dom-helpers": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz",
"integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.8.7",
"csstype": "^3.0.2"
}
},
"node_modules/electron-to-chromium": { "node_modules/electron-to-chromium": {
"version": "1.5.356", "version": "1.5.356",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.356.tgz", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.356.tgz",
...@@ -2407,6 +2465,21 @@ ...@@ -2407,6 +2465,21 @@
"node": ">= 0.4" "node": ">= 0.4"
} }
}, },
"node_modules/hoist-non-react-statics": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz",
"integrity": "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==",
"license": "BSD-3-Clause",
"dependencies": {
"react-is": "^16.7.0"
}
},
"node_modules/hoist-non-react-statics/node_modules/react-is": {
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
"license": "MIT"
},
"node_modules/html-encoding-sniffer": { "node_modules/html-encoding-sniffer": {
"version": "6.0.0", "version": "6.0.0",
"resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz", "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz",
...@@ -2627,6 +2700,24 @@ ...@@ -2627,6 +2700,24 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/lodash-es": {
"version": "4.18.1",
"resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz",
"integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==",
"license": "MIT"
},
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
},
"bin": {
"loose-envify": "cli.js"
}
},
"node_modules/lru-cache": { "node_modules/lru-cache": {
"version": "5.1.1", "version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
...@@ -2711,6 +2802,12 @@ ...@@ -2711,6 +2802,12 @@
"node": ">=4" "node": ">=4"
} }
}, },
"node_modules/mitt": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
"integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
"license": "MIT"
},
"node_modules/ms": { "node_modules/ms": {
"version": "2.1.3", "version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
...@@ -2767,7 +2864,6 @@ ...@@ -2767,7 +2864,6 @@
"version": "4.1.1", "version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=0.10.0"
...@@ -2821,6 +2917,12 @@ ...@@ -2821,6 +2917,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/performance-now": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz",
"integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==",
"license": "MIT"
},
"node_modules/picocolors": { "node_modules/picocolors": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
...@@ -3030,6 +3132,23 @@ ...@@ -3030,6 +3132,23 @@
"node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0"
} }
}, },
"node_modules/prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.4.0",
"object-assign": "^4.1.1",
"react-is": "^16.13.1"
}
},
"node_modules/prop-types/node_modules/react-is": {
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
"license": "MIT"
},
"node_modules/punycode": { "node_modules/punycode": {
"version": "2.3.1", "version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
...@@ -3061,6 +3180,15 @@ ...@@ -3061,6 +3180,15 @@
], ],
"license": "MIT" "license": "MIT"
}, },
"node_modules/raf": {
"version": "3.4.1",
"resolved": "https://registry.npmjs.org/raf/-/raf-3.4.1.tgz",
"integrity": "sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==",
"license": "MIT",
"dependencies": {
"performance-now": "^2.1.0"
}
},
"node_modules/react": { "node_modules/react": {
"version": "19.2.6", "version": "19.2.6",
"resolved": "https://registry.npmjs.org/react/-/react-19.2.6.tgz", "resolved": "https://registry.npmjs.org/react/-/react-19.2.6.tgz",
...@@ -3082,6 +3210,12 @@ ...@@ -3082,6 +3210,12 @@
"react": "^19.2.6" "react": "^19.2.6"
} }
}, },
"node_modules/react-fast-compare": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/react-fast-compare/-/react-fast-compare-3.2.2.tgz",
"integrity": "sha512-nsO+KSNgo1SbJqJEYRE9ERzo7YtYbou/OqjSQKxV7jcKox7+usiUVZOAC+XnDOABXggQTno0Y1CpVnuWEc1boQ==",
"license": "MIT"
},
"node_modules/react-is": { "node_modules/react-is": {
"version": "17.0.2", "version": "17.0.2",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
...@@ -3137,6 +3271,22 @@ ...@@ -3137,6 +3271,22 @@
"react-dom": ">=18" "react-dom": ">=18"
} }
}, },
"node_modules/react-transition-group": {
"version": "4.4.5",
"resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz",
"integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==",
"license": "BSD-3-Clause",
"dependencies": {
"@babel/runtime": "^7.5.5",
"dom-helpers": "^5.0.1",
"loose-envify": "^1.4.0",
"prop-types": "^15.6.2"
},
"peerDependencies": {
"react": ">=16.6.0",
"react-dom": ">=16.6.0"
}
},
"node_modules/read-cache": { "node_modules/read-cache": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz",
...@@ -3187,6 +3337,12 @@ ...@@ -3187,6 +3337,12 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/regenerator-runtime": {
"version": "0.14.1",
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz",
"integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==",
"license": "MIT"
},
"node_modules/require-from-string": { "node_modules/require-from-string": {
"version": "2.0.2", "version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
...@@ -3339,6 +3495,12 @@ ...@@ -3339,6 +3495,12 @@
"dev": true, "dev": true,
"license": "ISC" "license": "ISC"
}, },
"node_modules/sortablejs": {
"version": "1.15.7",
"resolved": "https://registry.npmjs.org/sortablejs/-/sortablejs-1.15.7.tgz",
"integrity": "sha512-Kk8wLQPlS+yi1ZEf48a4+fzHa4yxjC30M/Sr2AnQu+f/MPwvvX9XjZ6OWejiz8crBsLwSq8GHqaxaET7u6ux0A==",
"license": "MIT"
},
"node_modules/source-map-js": { "node_modules/source-map-js": {
"version": "1.2.1", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
...@@ -3456,6 +3618,67 @@ ...@@ -3456,6 +3618,67 @@
"node": ">=14.0.0" "node": ">=14.0.0"
} }
}, },
"node_modules/tdesign-icons-react": {
"version": "0.6.4",
"resolved": "https://registry.npmjs.org/tdesign-icons-react/-/tdesign-icons-react-0.6.4.tgz",
"integrity": "sha512-USAoi9vBWcwcJT45VqR3dRqX1MeAsn/RhHVx4bLwplhrlvE80ZQ1N9V+6F3HqE1Qe9mMDbtRM8Ul80+lALScww==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.16.5",
"classnames": "^2.2.6"
},
"peerDependencies": {
"react": ">=16.13.1",
"react-dom": ">=16.13.1"
}
},
"node_modules/tdesign-react": {
"version": "1.17.0",
"resolved": "https://registry.npmjs.org/tdesign-react/-/tdesign-react-1.17.0.tgz",
"integrity": "sha512-Nfxp/OP34hviJlAndiR7Ll5J1mnp+oRBCtsZN/OZ77IOXR5161mZYiRMsjIvFUmIAIM/KneuuBBC6qKvOZmrLg==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "~7.26.7",
"@popperjs/core": "~2.11.2",
"@types/sortablejs": "^1.15.7",
"@types/validator": "^13.1.3",
"classnames": "~2.5.1",
"dayjs": "1.11.10",
"hoist-non-react-statics": "~3.3.2",
"lodash-es": "^4.17.21",
"mitt": "^3.0.0",
"raf": "~3.4.1",
"react-fast-compare": "^3.2.2",
"react-is": "^18.2.0",
"react-transition-group": "~4.4.1",
"sortablejs": "^1.15.7",
"tdesign-icons-react": "^0.6.4",
"tslib": "~2.3.1",
"validator": "~13.15.0"
},
"peerDependencies": {
"react": ">=16.13.1",
"react-dom": ">=16.13.1"
}
},
"node_modules/tdesign-react/node_modules/@babel/runtime": {
"version": "7.26.10",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.10.tgz",
"integrity": "sha512-2WJMeRQPHKSPemqk/awGrAiuFfzBmOIPXKizAsVhWH9YJqLZ0H+HS4c8loHGgW6utJ3E/ejXQUsiGaQy2NZ9Fw==",
"license": "MIT",
"dependencies": {
"regenerator-runtime": "^0.14.0"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/tdesign-react/node_modules/react-is": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
"integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",
"license": "MIT"
},
"node_modules/thenify": { "node_modules/thenify": {
"version": "3.3.1", "version": "3.3.1",
"resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz",
...@@ -3588,6 +3811,12 @@ ...@@ -3588,6 +3811,12 @@
"dev": true, "dev": true,
"license": "Apache-2.0" "license": "Apache-2.0"
}, },
"node_modules/tslib": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz",
"integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==",
"license": "0BSD"
},
"node_modules/typescript": { "node_modules/typescript": {
"version": "5.9.3", "version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
...@@ -3645,6 +3874,15 @@ ...@@ -3645,6 +3874,15 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/validator": {
"version": "13.15.35",
"resolved": "https://registry.npmjs.org/validator/-/validator-13.15.35.tgz",
"integrity": "sha512-TQ5pAGhd5whStmqWvYF4OjQROlmv9SMFVt37qoCBdqRffuuklWYQlCNnEs2ZaIBD1kZRNnikiZOS1eqgkar0iw==",
"license": "MIT",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/vite": { "node_modules/vite": {
"version": "7.3.3", "version": "7.3.3",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.3.tgz", "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.3.tgz",
......
...@@ -16,12 +16,14 @@ ...@@ -16,12 +16,14 @@
"react": "^19.2.3", "react": "^19.2.3",
"react-dom": "^19.2.3", "react-dom": "^19.2.3",
"react-router-dom": "^7.10.1", "react-router-dom": "^7.10.1",
"tdesign-react": "^1.17.0",
"typescript": "^5.9.3", "typescript": "^5.9.3",
"vite": "^7.3.0" "vite": "^7.3.0"
}, },
"devDependencies": { "devDependencies": {
"@testing-library/jest-dom": "^6.9.1", "@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.1", "@testing-library/react": "^16.3.1",
"@testing-library/user-event": "^14.6.1",
"@types/node": "^25.0.1", "@types/node": "^25.0.1",
"@types/react": "^19.2.7", "@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
......
import { agentListMockFixtures, agentPositionOptions, type AgentPositionOption, type AgentStatus } from './agent-list-mock';
export type AgentEditorScenario =
| 'normal'
| 'loading'
| 'positionError'
| 'employeeError'
| 'skillError'
| 'saveError'
| 'saving';
export interface AgentSkillOption {
id: string;
name: string;
}
export interface AgentEmployeeOption {
id: string;
name: string;
position_ids: string[];
status?: 'idle' | 'mounted';
}
export interface AgentDetailRecord {
agent_id: number;
name: string;
is_manager: boolean;
positions: AgentPositionOption[];
employee_id: string;
employee_name: string;
description: string;
skill_ids: string[];
status: AgentStatus;
}
export interface AgentEditorFixture {
scenario: AgentEditorScenario;
detailLoading: boolean;
positionsLoading: boolean;
positionsError: boolean;
employeesLoading: boolean;
employeesError: boolean;
skillsLoading: boolean;
skillsError: boolean;
saveLoading: boolean;
saveError: boolean;
positions: AgentPositionOption[];
skills: AgentSkillOption[];
employees: AgentEmployeeOption[];
detail?: AgentDetailRecord;
}
export interface AgentDraftPayload {
name: string;
positionIds: string[];
userId?: string;
description: string;
skillIds: string[];
status: AgentStatus;
}
export const agentSkillOptions: AgentSkillOption[] = [
{ id: 'summary', name: '会话总结' },
{ id: 'reply', name: '智能回复' },
{ id: 'quality', name: '质检分析' },
{ id: 'lead', name: '线索跟进' },
];
const employeeDirectory: AgentEmployeeOption[] = [
{ id: 'wx-sales-1', name: '陈晓岚', position_ids: ['sales'], status: 'idle' },
{ id: 'wx-sales-2', name: '黄启航', position_ids: ['sales', 'ops'], status: 'mounted' },
{ id: 'wx-service-1', name: '周语晴', position_ids: ['service'], status: 'idle' },
{ id: 'wx-ops-1', name: '林择一', position_ids: ['ops'], status: 'idle' },
{ id: 'wx-manager-1', name: '系统管家企微', position_ids: [], status: 'idle' },
];
const detailRecords: Record<string, AgentDetailRecord> = {
'1': {
agent_id: 1,
name: '管家Agent',
is_manager: true,
positions: [],
employee_id: 'wx-manager-1',
employee_name: '系统管家企微',
description: '负责系统级调度与兜底回复。',
skill_ids: [],
status: 'enable',
},
'101': {
agent_id: 101,
name: '复盘Agent',
is_manager: false,
positions: [agentPositionOptions[0]],
employee_id: 'wx-sales-1',
employee_name: '陈晓岚',
description: '负责成交复盘与客户跟进建议。',
skill_ids: ['summary', 'lead'],
status: 'enable',
},
'102': {
agent_id: 102,
name: '质检Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
employee_id: 'wx-service-1',
employee_name: '周语晴',
description: '负责会话质检与问题归因。',
skill_ids: ['quality'],
status: 'disable',
},
};
export function getAgentDetail(agentId?: string) {
if (!agentId) return undefined;
return detailRecords[agentId];
}
export function getEmployeesByPositions(positionIds: string[]) {
if (positionIds.length === 0) {
return [];
}
return employeeDirectory.filter((employee) => employee.position_ids.some((positionId) => positionIds.includes(positionId)));
}
export function getAgentEditorFixture({
agentId,
mode,
scenario = 'normal',
positionIds = [],
}: {
agentId?: string;
mode: 'create' | 'edit' | 'detail';
scenario?: AgentEditorScenario;
positionIds?: string[];
}): AgentEditorFixture {
const detail = mode === 'create' ? undefined : getAgentDetail(agentId);
const resolvedPositionIds = positionIds.length > 0
? positionIds
: detail?.positions.map((position) => position.id) ?? [];
return {
scenario,
detail,
detailLoading: scenario === 'loading' && mode !== 'create',
positionsLoading: false,
positionsError: scenario === 'positionError',
employeesLoading: false,
employeesError: scenario === 'employeeError',
skillsLoading: false,
skillsError: scenario === 'skillError',
saveLoading: scenario === 'saving',
saveError: scenario === 'saveError',
positions: agentPositionOptions,
employees: scenario === 'employeeError' ? [] : getEmployeesByPositions(resolvedPositionIds),
skills: scenario === 'skillError' ? [] : agentSkillOptions,
};
}
export function createAgentRecord(payload: AgentDraftPayload) {
const nextId = Math.max(...agentListMockFixtures.normal.items.map((item) => item.agent_id)) + 1;
const employee = employeeDirectory.find((item) => item.id === payload.userId);
return {
agent_id: nextId,
name: payload.name,
is_manager: false,
positions: agentPositionOptions.filter((position) => payload.positionIds.includes(position.id)),
employee_id: payload.userId ?? '',
employee_name: employee?.name ?? '',
description: payload.description,
skill_ids: payload.skillIds,
status: payload.status,
} satisfies AgentDetailRecord;
}
export type AgentStatus = 'enable' | 'disable'; export type AgentStatus = 'enable' | 'disable';
export type AgentAction = 'edit' | 'enable' | 'disable' | 'delete'; export type AgentAction = 'detail' | 'edit' | 'enable' | 'disable' | 'delete';
export interface AgentPositionOption { export interface AgentPositionOption {
id: string; id: string;
...@@ -49,7 +49,7 @@ const managerAgent: AgentListMockItem = { ...@@ -49,7 +49,7 @@ const managerAgent: AgentListMockItem = {
bound_group_count: 12, bound_group_count: 12,
bound_skill_count: 0, bound_skill_count: 0,
updated_at: '2026-05-19 10:30:00', updated_at: '2026-05-19 10:30:00',
available_actions: ['edit'], available_actions: ['detail', 'edit'],
}; };
const normalAgents: AgentListMockItem[] = [ const normalAgents: AgentListMockItem[] = [
...@@ -62,7 +62,7 @@ const normalAgents: AgentListMockItem[] = [ ...@@ -62,7 +62,7 @@ const normalAgents: AgentListMockItem[] = [
bound_group_count: 8, bound_group_count: 8,
bound_skill_count: 4, bound_skill_count: 4,
updated_at: '2026-05-18 16:20:00', updated_at: '2026-05-18 16:20:00',
available_actions: ['edit', 'disable', 'delete'], available_actions: ['detail', 'edit', 'disable', 'delete'],
}, },
{ {
agent_id: 102, agent_id: 102,
...@@ -73,7 +73,7 @@ const normalAgents: AgentListMockItem[] = [ ...@@ -73,7 +73,7 @@ const normalAgents: AgentListMockItem[] = [
bound_group_count: 3, bound_group_count: 3,
bound_skill_count: 2, bound_skill_count: 2,
updated_at: '2026-05-17 09:15:00', updated_at: '2026-05-17 09:15:00',
available_actions: ['edit', 'enable', 'delete'], available_actions: ['detail', 'edit', 'enable', 'delete'],
}, },
{ {
agent_id: 103, agent_id: 103,
...@@ -84,7 +84,7 @@ const normalAgents: AgentListMockItem[] = [ ...@@ -84,7 +84,7 @@ const normalAgents: AgentListMockItem[] = [
bound_group_count: 15, bound_group_count: 15,
bound_skill_count: 6, bound_skill_count: 6,
updated_at: '2026-05-16 13:05:00', updated_at: '2026-05-16 13:05:00',
available_actions: ['edit', 'disable', 'delete'], available_actions: ['detail', 'edit', 'disable', 'delete'],
}, },
{ {
agent_id: 104, agent_id: 104,
...@@ -95,7 +95,7 @@ const normalAgents: AgentListMockItem[] = [ ...@@ -95,7 +95,7 @@ const normalAgents: AgentListMockItem[] = [
bound_group_count: 5, bound_group_count: 5,
bound_skill_count: 3, bound_skill_count: 3,
updated_at: '2026-05-15 18:40:00', updated_at: '2026-05-15 18:40:00',
available_actions: ['edit', 'disable', 'delete'], available_actions: ['detail', 'edit', 'disable', 'delete'],
}, },
{ {
agent_id: 105, agent_id: 105,
...@@ -106,172 +106,7 @@ const normalAgents: AgentListMockItem[] = [ ...@@ -106,172 +106,7 @@ const normalAgents: AgentListMockItem[] = [
bound_group_count: 1, bound_group_count: 1,
bound_skill_count: 1, bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00', updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'], available_actions: ['detail', 'edit', 'enable', 'delete'],
},
{
agent_id: 105,
name: '客诉安抚Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
status: 'disable',
bound_group_count: 1,
bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'],
},
{
agent_id: 105,
name: '客诉安抚Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
status: 'disable',
bound_group_count: 1,
bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'],
},
{
agent_id: 105,
name: '客诉安抚Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
status: 'disable',
bound_group_count: 1,
bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'],
},
{
agent_id: 105,
name: '客诉安抚Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
status: 'disable',
bound_group_count: 1,
bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'],
},
{
agent_id: 105,
name: '客诉安抚Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
status: 'disable',
bound_group_count: 1,
bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'],
},
{
agent_id: 105,
name: '客诉安抚Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
status: 'disable',
bound_group_count: 1,
bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'],
},
{
agent_id: 105,
name: '客诉安抚Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
status: 'disable',
bound_group_count: 1,
bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'],
},
{
agent_id: 105,
name: '客诉安抚Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
status: 'disable',
bound_group_count: 1,
bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'],
},
{
agent_id: 105,
name: '客诉安抚Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
status: 'disable',
bound_group_count: 1,
bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'],
},
{
agent_id: 105,
name: '客诉安抚Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
status: 'disable',
bound_group_count: 1,
bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'],
},
{
agent_id: 105,
name: '客诉安抚Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
status: 'disable',
bound_group_count: 1,
bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'],
},
{
agent_id: 105,
name: '客诉安抚Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
status: 'disable',
bound_group_count: 1,
bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'],
},
{
agent_id: 105,
name: '客诉安抚Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
status: 'disable',
bound_group_count: 1,
bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'],
},
{
agent_id: 105,
name: '客诉安抚Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
status: 'disable',
bound_group_count: 1,
bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'],
},
{
agent_id: 105,
name: '客诉安抚Agent',
is_manager: false,
positions: [agentPositionOptions[1]],
status: 'disable',
bound_group_count: 1,
bound_skill_count: 1,
updated_at: '2026-05-14 11:25:00',
available_actions: ['edit', 'enable', 'delete'],
}, },
]; ];
...@@ -293,7 +128,7 @@ export const agentListMockFixtures = { ...@@ -293,7 +128,7 @@ export const agentListMockFixtures = {
], ],
total: 1, total: 1,
}, },
disabledActions: { items: [{ ...managerAgent, available_actions: ['edit'] }], total: 1 }, disabledActions: { items: [{ ...managerAgent, available_actions: ['detail', 'edit'] }], total: 1 },
paginationBoundary: { items: [managerAgent, ...normalAgents], total: 51 }, paginationBoundary: { items: [managerAgent, ...normalAgents], total: 51 },
} satisfies Record<string, AgentListMockFixture>; } satisfies Record<string, AgentListMockFixture>;
...@@ -301,6 +136,11 @@ export function sortAgentsForDisplay(items: AgentListMockItem[]) { ...@@ -301,6 +136,11 @@ export function sortAgentsForDisplay(items: AgentListMockItem[]) {
return [...items].sort((left, right) => Number(right.is_manager) - Number(left.is_manager)); return [...items].sort((left, right) => Number(right.is_manager) - Number(left.is_manager));
} }
export function getAgentListItem(agentId?: string) {
if (!agentId) return undefined;
return agentListMockFixtures.normal.items.find((item) => String(item.agent_id) === agentId);
}
export function getAgentListPage({ keyword = '', page, pageSize, positionId, source, status = 'all' }: AgentListPageQuery) { export function getAgentListPage({ keyword = '', page, pageSize, positionId, source, status = 'all' }: AgentListPageQuery) {
const normalizedKeyword = keyword.trim().toLowerCase(); const normalizedKeyword = keyword.trim().toLowerCase();
const filtered = sortAgentsForDisplay(source ?? agentListMockFixtures.normal.items).filter((agent) => { const filtered = sortAgentsForDisplay(source ?? agentListMockFixtures.normal.items).filter((agent) => {
......
import { beforeEach, describe, expect, it } from 'vitest';
import {
agentTagMockFixtures,
deleteAgentTagRecord,
getAgentTagListPage,
getAgentTagRecord,
getAgentTagReferences,
isAgentTagCodeDuplicate,
resetAgentTagMockState,
saveAgentTagRecord,
} from './agent-tag-mock';
describe('agent tag mock contract', () => {
beforeEach(() => {
window.localStorage.clear();
resetAgentTagMockState();
});
it('provides the minimal page-facing fields and required fixtures', () => {
const [tag] = agentTagMockFixtures.normal.items;
expect(tag).toMatchObject({
tag_id: expect.any(Number),
name: expect.any(String),
code: expect.any(String),
description: expect.any(String),
agent_count: expect.any(Number),
channel_code_count: expect.any(Number),
official_tab_count: expect.any(Number),
created_at: expect.any(String),
});
expect(Object.keys(agentTagMockFixtures).sort()).toEqual([
'empty',
'loadError',
'normal',
'referenceError',
'saveError',
]);
});
it('filters by tag name and paginates from page-facing query fields', () => {
expect(getAgentTagListPage({ keyword: '售后', page: 1, pageSize: 10 }).items).toHaveLength(1);
expect(getAgentTagListPage({ keyword: '直播', page: 1, pageSize: 10 }).items[0].name).toBe('直播运营');
const paged = getAgentTagListPage({ page: 2, pageSize: 2 });
expect(paged.total).toBe(5);
expect(paged.items).toHaveLength(2);
expect(paged.items[0].name).toBe('直播运营');
});
it('checks code uniqueness, returns reference fixtures, and persists create/edit/delete operations', () => {
expect(isAgentTagCodeDuplicate('store_sales')).toBe(true);
expect(isAgentTagCodeDuplicate('brand_new_tag')).toBe(false);
const agentReferenced = getAgentTagReferences(2);
expect(agentReferenced.detachable_references.agent_count).toBe(2);
expect(agentReferenced.blocking_references.qrcode_count).toBe(0);
const blocking = getAgentTagReferences(3);
expect(blocking.blocking_references.qrcode_count).toBe(1);
const created = saveAgentTagRecord({ name: '培训讲师', code: 'training_teacher', description: '负责培训赋能' });
expect(getAgentTagRecord(String(created.tag_id))?.code).toBe('training_teacher');
const updated = saveAgentTagRecord({ tagId: 2, name: '售后服务', description: '负责售后服务跟进' });
expect(updated.name).toBe('售后服务');
const deletion = deleteAgentTagRecord(2);
expect(deletion.detached_agent_ids).toEqual([101, 106]);
expect(getAgentTagRecord('2')).toBeUndefined();
});
});
export interface AgentTagMockItem extends Record<string, unknown> {
tag_id: number;
name: string;
code: string;
description: string;
agent_count: number;
channel_code_count: number;
official_tab_count: number;
created_at: string;
}
export interface AgentTagBlockingQRCodeReference {
qrcode_id: number;
channel_code: string;
employee_name: string;
status: 'enable' | 'disable';
}
export interface AgentTagBlockingOfficialTabReference {
tab_id: number;
position_name: string;
display_status: 'enable' | 'disable';
}
export interface AgentTagDetachableAgentReference {
agent_id: number;
agent_name: string;
status: 'enable' | 'disable';
}
export interface AgentTagReferences {
tag_id: number;
tag_name: string;
can_delete: boolean;
blocking_references: {
qrcode_count: number;
qrcodes: AgentTagBlockingQRCodeReference[];
official_tab_count: number;
official_tabs: AgentTagBlockingOfficialTabReference[];
};
detachable_references: {
agent_count: number;
agents: AgentTagDetachableAgentReference[];
};
hints: string[];
}
export interface AgentTagListPageQuery {
keyword?: string;
page: number;
pageSize: number;
source?: AgentTagMockItem[];
}
export interface SaveAgentTagPayload {
tagId?: number;
name: string;
code?: string;
description?: string;
}
export interface DeleteAgentTagResult {
detached_agent_ids: number[];
}
export interface AgentTagMockFixture {
items: AgentTagMockItem[];
loadError?: boolean;
saveError?: boolean;
referenceError?: boolean;
}
const savedStorageKey = 'agent-admin-saved-agent-tags';
const deletedStorageKey = 'agent-admin-deleted-agent-tags';
const baseAgentTags: AgentTagMockItem[] = [
{
tag_id: 1,
name: '店销顾问',
code: 'store_sales',
description: '负责门店销售接待与转化',
agent_count: 0,
channel_code_count: 0,
official_tab_count: 0,
created_at: '2026-05-10 09:00:00',
},
{
tag_id: 2,
name: '售后客服',
code: 'after_sales_service',
description: '负责售后问题处理与回访',
agent_count: 2,
channel_code_count: 0,
official_tab_count: 0,
created_at: '2026-05-11 10:15:00',
},
{
tag_id: 3,
name: '直播运营',
code: 'live_ops',
description: '负责直播前中后场运营',
agent_count: 0,
channel_code_count: 1,
official_tab_count: 0,
created_at: '2026-05-12 11:30:00',
},
{
tag_id: 4,
name: '官网顾问',
code: 'site_consultant',
description: '负责官网线索接待与分发',
agent_count: 0,
channel_code_count: 0,
official_tab_count: 1,
created_at: '2026-05-13 14:20:00',
},
{
tag_id: 5,
name: '私域增长',
code: 'crm_growth',
description: '负责私域拉新与留存运营',
agent_count: 1,
channel_code_count: 1,
official_tab_count: 0,
created_at: '2026-05-14 16:40:00',
},
];
const referenceFixtures: Record<number, AgentTagReferences> = {
1: {
tag_id: 1,
tag_name: '店销顾问',
can_delete: true,
blocking_references: { qrcode_count: 0, qrcodes: [], official_tab_count: 0, official_tabs: [] },
detachable_references: { agent_count: 0, agents: [] },
hints: [],
},
2: {
tag_id: 2,
tag_name: '售后客服',
can_delete: false,
blocking_references: { qrcode_count: 0, qrcodes: [], official_tab_count: 0, official_tabs: [] },
detachable_references: {
agent_count: 2,
agents: [
{ agent_id: 101, agent_name: '复盘Agent', status: 'enable' },
{ agent_id: 106, agent_name: '回访问答Agent', status: 'disable' },
],
},
hints: ['删除后这些 Agent 将失去该标签'],
},
3: {
tag_id: 3,
tag_name: '直播运营',
can_delete: false,
blocking_references: {
qrcode_count: 1,
qrcodes: [{ qrcode_id: 301, channel_code: 'live_ops_qr_01', employee_name: '林择一', status: 'enable' }],
official_tab_count: 0,
official_tabs: [],
},
detachable_references: { agent_count: 0, agents: [] },
hints: ['请先删除关联的渠道活码'],
},
4: {
tag_id: 4,
tag_name: '官网顾问',
can_delete: false,
blocking_references: {
qrcode_count: 0,
qrcodes: [],
official_tab_count: 1,
official_tabs: [{ tab_id: 401, position_name: '官网顾问', display_status: 'enable' }],
},
detachable_references: { agent_count: 0, agents: [] },
hints: ['请先删除关联的官网 Tab 配置'],
},
5: {
tag_id: 5,
tag_name: '私域增长',
can_delete: false,
blocking_references: {
qrcode_count: 1,
qrcodes: [{ qrcode_id: 501, channel_code: 'crm_growth_qr_01', employee_name: '周语晴', status: 'enable' }],
official_tab_count: 0,
official_tabs: [],
},
detachable_references: {
agent_count: 1,
agents: [{ agent_id: 105, agent_name: '客诉安抚Agent', status: 'disable' }],
},
hints: ['请先删除关联的渠道活码', '删除后这些 Agent 将失去该标签'],
},
};
function canUseStorage() {
return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';
}
function readStoredItems() {
if (!canUseStorage()) return [] as AgentTagMockItem[];
try {
const raw = window.localStorage.getItem(savedStorageKey);
return raw ? (JSON.parse(raw) as AgentTagMockItem[]) : [];
} catch {
return [];
}
}
function readDeletedIds() {
if (!canUseStorage()) return [] as number[];
try {
const raw = window.localStorage.getItem(deletedStorageKey);
return raw ? (JSON.parse(raw) as number[]) : [];
} catch {
return [];
}
}
function writeStoredItems(items: AgentTagMockItem[]) {
if (!canUseStorage()) return;
window.localStorage.setItem(savedStorageKey, JSON.stringify(items));
}
function writeDeletedIds(tagIds: number[]) {
if (!canUseStorage()) return;
window.localStorage.setItem(deletedStorageKey, JSON.stringify(tagIds));
}
export function resetAgentTagMockState() {
if (!canUseStorage()) return;
window.localStorage.removeItem(savedStorageKey);
window.localStorage.removeItem(deletedStorageKey);
}
export function getAgentTagSource() {
const deletedIds = new Set(readDeletedIds());
const savedItems = readStoredItems();
const savedById = new Map(savedItems.map((item) => [item.tag_id, item] as const));
const preservedBase = baseAgentTags
.filter((item) => !deletedIds.has(item.tag_id))
.map((item) => savedById.get(item.tag_id) ?? item);
const createdItems = savedItems.filter((item) => !baseAgentTags.some((base) => base.tag_id === item.tag_id) && !deletedIds.has(item.tag_id));
return [...preservedBase, ...createdItems].sort((left, right) => left.tag_id - right.tag_id);
}
export const agentTagMockFixtures = {
normal: { items: baseAgentTags },
empty: { items: [] },
loadError: { items: [], loadError: true },
saveError: { items: baseAgentTags, saveError: true },
referenceError: { items: baseAgentTags, referenceError: true },
} satisfies Record<string, AgentTagMockFixture>;
export function getAgentTagRecord(tagId?: string, source = getAgentTagSource()) {
if (!tagId) return undefined;
return source.find((item) => String(item.tag_id) === tagId);
}
export function isAgentTagCodeDuplicate(code: string, currentTagId?: number) {
const normalizedCode = code.trim().toLowerCase();
return getAgentTagSource().some((item) => item.tag_id !== currentTagId && item.code.toLowerCase() === normalizedCode);
}
export function getAgentTagListPage({ keyword = '', page, pageSize, source = getAgentTagSource() }: AgentTagListPageQuery) {
const normalizedKeyword = keyword.trim().toLowerCase();
const filtered = source.filter((item) => {
if (!normalizedKeyword) return true;
return item.name.toLowerCase().includes(normalizedKeyword);
});
const start = (page - 1) * pageSize;
return {
items: filtered.slice(start, start + pageSize),
page,
pageSize,
total: filtered.length,
};
}
export function saveAgentTagRecord({ code, description = '', name, tagId }: SaveAgentTagPayload) {
const source = getAgentTagSource();
const current = tagId ? source.find((item) => item.tag_id === tagId) : undefined;
const nextId = current?.tag_id ?? Math.max(0, ...source.map((item) => item.tag_id)) + 1;
const nextRecord: AgentTagMockItem = {
tag_id: nextId,
name: name.trim(),
code: current?.code ?? code?.trim() ?? '',
description: description.trim(),
agent_count: current?.agent_count ?? 0,
channel_code_count: current?.channel_code_count ?? 0,
official_tab_count: current?.official_tab_count ?? 0,
created_at: current?.created_at ?? '2026-05-21 12:00:00',
};
const savedItems = readStoredItems();
writeStoredItems([...savedItems.filter((item) => item.tag_id !== nextRecord.tag_id), nextRecord]);
writeDeletedIds(readDeletedIds().filter((item) => item !== nextRecord.tag_id));
return nextRecord;
}
export function getAgentTagReferences(tagId: number, scenario: 'normal' | 'referenceError' = 'normal') {
if (scenario === 'referenceError') {
throw new Error('reference check failed');
}
const current = getAgentTagSource().find((item) => item.tag_id === tagId);
if (!current) {
return {
tag_id: tagId,
tag_name: '',
can_delete: true,
blocking_references: { qrcode_count: 0, qrcodes: [], official_tab_count: 0, official_tabs: [] },
detachable_references: { agent_count: 0, agents: [] },
hints: [],
} satisfies AgentTagReferences;
}
const fixture = referenceFixtures[tagId];
if (!fixture) {
return {
tag_id: current.tag_id,
tag_name: current.name,
can_delete: true,
blocking_references: { qrcode_count: 0, qrcodes: [], official_tab_count: 0, official_tabs: [] },
detachable_references: { agent_count: 0, agents: [] },
hints: [],
} satisfies AgentTagReferences;
}
return {
...fixture,
tag_name: current.name,
};
}
export function deleteAgentTagRecord(tagId: number): DeleteAgentTagResult {
const references = getAgentTagReferences(tagId);
writeStoredItems(readStoredItems().filter((item) => item.tag_id !== tagId));
writeDeletedIds([...new Set([...readDeletedIds(), tagId])]);
return {
detached_agent_ids: references.detachable_references.agents.map((item) => item.agent_id),
};
}
import { beforeEach, describe, expect, it } from 'vitest';
import {
channelCodeMockFixtures,
getChannelCodeListPage,
getChannelCodeRecord,
getEmployeeQRCodes,
getPositionDerivedInfo,
getPositionsWithChannelCode,
saveChannelCodeRecord,
updateChannelCodeStatus,
resetChannelCodeMockState,
type ChannelCodeMockItem,
} from './channel-code-mock';
describe('channel code mock contract', () => {
beforeEach(() => {
window.localStorage.clear();
resetChannelCodeMockState();
});
it('provides the minimal page-facing fields and required fixtures', () => {
const [code] = channelCodeMockFixtures.normal.items;
expect(code).toMatchObject({
code_id: expect.any(Number),
code_name: expect.any(String),
position_code: expect.any(String),
position_name: expect.any(String),
channel_code: expect.any(String),
employee_name: expect.any(String),
employee_role_text: expect.any(String),
agent_names: expect.any(Array),
status: expect.any(String),
qrcode_url: expect.any(String),
description: expect.any(String),
welcome_message: expect.any(String),
created_at: expect.any(String),
updated_at: expect.any(String),
operations: expect.any(Array),
});
expect(Object.keys(channelCodeMockFixtures).sort()).toEqual([
'empty',
'filteredEmpty',
'loadError',
'normal',
'paginationBoundary',
'qrcodeLoadError',
'saveError',
'statusBlockError',
]);
});
it('filters by code name, position and status', () => {
const result1 = getChannelCodeListPage({ keyword: '售后', page: 1, pageSize: 10 });
expect(result1.items).toHaveLength(1);
expect(result1.items[0].code_name).toContain('售后');
const result2 = getChannelCodeListPage({ positionCode: 'store_sales', page: 1, pageSize: 10 });
expect(result2.items).toHaveLength(1);
expect(result2.items[0].position_code).toBe('store_sales');
const result3 = getChannelCodeListPage({ status: 'enable', page: 1, pageSize: 10 });
expect(result3.items.every((item) => item.status === 'enable')).toBe(true);
const result4 = getChannelCodeListPage({ status: 'disable', page: 1, pageSize: 10 });
expect(result4.items.every((item) => item.status === 'disable')).toBe(true);
});
it('paginates from page-facing query fields', () => {
const paged = getChannelCodeListPage({ page: 2, pageSize: 2 });
expect(paged.total).toBe(5);
expect(paged.items).toHaveLength(2);
expect(paged.page).toBe(2);
expect(paged.pageSize).toBe(2);
});
it('provides position derived info including channel code, employee and agents', () => {
const info = getPositionDerivedInfo('store_sales');
expect(info).toBeDefined();
expect(info!).toMatchObject({
position_code: 'store_sales',
position_name: expect.any(String),
channel_code: expect.any(String),
employee_name: expect.any(String),
employee_role_text: expect.any(String),
agent_names: expect.any(Array),
});
expect(info!.agent_names.length).toBeGreaterThan(0);
});
it('returns undefined for position derived info when position does not exist', () => {
const info = getPositionDerivedInfo('nonexistent_position');
expect(info).toBeUndefined();
});
it('tracks positions that already have channel codes (one position one code)', () => {
const positionsWithCodes = getPositionsWithChannelCode();
expect(positionsWithCodes).toContain('store_sales');
expect(positionsWithCodes).toContain('after_sales_service');
expect(positionsWithCodes.length).toBeGreaterThan(0);
});
it('creates a new channel code with status disable by default', () => {
const created = saveChannelCodeRecord({
code_name: '测试渠道活码',
position_code: 'live_ops',
description: '测试描述',
welcome_message: '欢迎添加',
status: 'disable',
});
expect(created.code_id).toBeGreaterThan(0);
expect(created.status).toBe('disable');
expect(created.code_name).toBe('测试渠道活码');
expect(getChannelCodeRecord(String(created.code_id))).toBeDefined();
expect(getPositionsWithChannelCode()).toContain('live_ops');
});
it('updates existing channel code without changing position', () => {
const existing = channelCodeMockFixtures.normal.items[0];
const updated = saveChannelCodeRecord({
codeId: existing.code_id,
code_name: '更新后的活码名称',
description: '更新后的描述',
welcome_message: '更新后的欢迎语',
status: 'enable',
});
expect(updated.code_id).toBe(existing.code_id);
expect(updated.code_name).toBe('更新后的活码名称');
expect(updated.position_code).toBe(existing.position_code);
expect(updated.status).toBe('enable');
});
it('enables and disables channel code status', () => {
const existing = channelCodeMockFixtures.normal.items.find((item) => item.status === 'disable');
if (!existing) throw new Error('No disabled item found');
const enabled = updateChannelCodeStatus(existing.code_id, 'enable', 'normal');
expect(enabled.status).toBe('enable');
expect(enabled.updated_at).not.toBe(existing.updated_at);
});
it('blocks disable when status update returns business blocking error', () => {
const existing = channelCodeMockFixtures.normal.items.find((item) => item.status === 'enable');
if (!existing) throw new Error('No enabled item found');
const result = updateChannelCodeStatus(existing.code_id, 'disable', 'statusBlockError');
expect(result.blocked).toBe(true);
expect(result.message).toContain('官网');
expect(result.status).toBe('enable');
});
it('handles qrcode image load error fixture', () => {
const fixture = channelCodeMockFixtures.qrcodeLoadError;
expect(fixture.items[0].qrcode_load_error).toBe(true);
});
it('returns undefined for non-existent channel code record', () => {
const record = getChannelCodeRecord('99999');
expect(record).toBeUndefined();
});
describe('getEmployeeQRCodes API', () => {
it('returns employee QR codes info for valid employee_id', () => {
// 岗位 store_sales 的员工 ID 是 1001
const response = getEmployeeQRCodes(1001);
expect(response).toBeDefined();
expect(response!.employee_id).toBe(1001);
expect(response!.employee_name).toBe('张小萌');
expect(response!.employee_role_text).toBe('店销主管');
expect(response!.qrcode_count).toBeGreaterThan(0);
expect(response!.qrcodes.length).toBeGreaterThan(0);
expect(response!.qrcodes[0].position_name).toBe('店销顾问');
});
it('returns undefined for non-existent employee_id', () => {
const response = getEmployeeQRCodes(99999);
expect(response).toBeUndefined();
});
it('includes employee derived info from API response', () => {
const response = getEmployeeQRCodes(1002); // 售后客服员工
expect(response).toBeDefined();
expect(response!.employee_name).toBe('李小燕');
expect(response!.employee_role_text).toBe('客服专员');
expect(response!.qrcodes[0].channel_code).toBe('ASC-QR-002');
});
});
});
\ No newline at end of file \ No newline at end of file
import { getAgentTagSource } from './agent-tag-mock';
export interface ChannelCodeMockItem extends Record<string, unknown> {
code_id: number;
code_name: string;
position_code: string;
position_name: string;
channel_code: string;
employee_name: string;
employee_role_text: string;
agent_names: string[];
status: 'enable' | 'disable';
qrcode_url: string;
qrcode_load_error?: boolean;
description: string;
welcome_message: string;
created_at: string;
updated_at: string;
operations: ('view' | 'edit' | 'enable' | 'disable')[];
}
export interface PositionDerivedInfo {
position_code: string;
position_name: string;
channel_code: string;
employee_id: number;
employee_name: string;
employee_role_text: string;
agent_names: string[];
}
export interface EmployeeConfiguredQRCodeItem {
qrcode_id: number;
position_name: string;
channel_code: string;
status: 'enable' | 'disable';
created_at: string;
}
export interface EmployeeConfiguredQRCodesResponse {
employee_id: number;
employee_name: string;
employee_role_text: string;
qrcode_count: number;
qrcodes: EmployeeConfiguredQRCodeItem[];
}
export interface ChannelCodeListPageQuery {
keyword?: string;
positionCode?: string;
status?: 'enable' | 'disable' | '';
page: number;
pageSize: number;
source?: ChannelCodeMockItem[];
}
export interface SaveChannelCodePayload {
codeId?: number;
code_name: string;
position_code?: string;
description?: string;
welcome_message?: string;
status?: 'enable' | 'disable';
}
export interface UpdateStatusResult {
code_id: number;
status: 'enable' | 'disable';
updated_at: string;
blocked?: boolean;
message?: string;
}
export interface ChannelCodeMockFixture {
items: ChannelCodeMockItem[];
loadError?: boolean;
saveError?: boolean;
statusBlockError?: boolean;
qrcodeLoadError?: boolean;
}
export interface PositionOption {
tag_id: number;
name: string;
code: string;
}
const savedStorageKey = 'agent-admin-saved-channel-codes';
const deletedStorageKey = 'agent-admin-deleted-channel-codes';
const statusStorageKey = 'agent-admin-channel-code-status';
const baseChannelCodes: ChannelCodeMockItem[] = [
{
code_id: 1,
code_name: '店销顾问渠道活码',
position_code: 'store_sales',
position_name: '店销顾问',
channel_code: 'DSC-QR-001',
employee_name: '张小萌',
employee_role_text: '店销主管',
agent_names: ['店销助手Agent', '管家Agent'],
status: 'enable',
qrcode_url: 'https://picsum.photos/seed/store_sales/200/200',
description: '用于门店销售渠道客户接入',
welcome_message: '欢迎咨询门店产品与服务',
created_at: '2026-05-10 09:00:00',
updated_at: '2026-05-15 10:30:00',
operations: ['view', 'edit', 'disable'],
},
{
code_id: 2,
code_name: '售后客服渠道活码',
position_code: 'after_sales_service',
position_name: '售后客服',
channel_code: 'ASC-QR-002',
employee_name: '李小燕',
employee_role_text: '客服专员',
agent_names: ['售后问答Agent', '回访问答Agent', '管家Agent'],
status: 'enable',
qrcode_url: 'https://picsum.photos/seed/after_sales/200/200',
description: '用于售后问题咨询与回访',
welcome_message: '有问题随时联系我',
created_at: '2026-05-11 10:15:00',
updated_at: '2026-05-16 11:45:00',
operations: ['view', 'edit', 'disable'],
},
{
code_id: 3,
code_name: '直播运营渠道活码',
position_code: 'live_ops',
position_name: '直播运营',
channel_code: 'LVO-QR-003',
employee_name: '王大力',
employee_role_text: '直播运营专员',
agent_names: ['直播助手Agent', '管家Agent'],
status: 'disable',
qrcode_url: 'https://picsum.photos/seed/live_ops/200/200',
description: '用于直播间观众引流',
welcome_message: '感谢观看直播,欢迎添加',
created_at: '2026-05-12 11:30:00',
updated_at: '2026-05-17 14:20:00',
operations: ['view', 'edit', 'enable'],
},
{
code_id: 4,
code_name: '官网顾问渠道活码',
position_code: 'site_consultant',
position_name: '官网顾问',
channel_code: 'WGC-QR-004',
employee_name: '赵明亮',
employee_role_text: '在线顾问',
agent_names: ['官网接待Agent', '管家Agent'],
status: 'disable',
qrcode_url: 'https://picsum.photos/seed/site_consultant/200/200',
description: '用于官网访客咨询接待',
welcome_message: '您好,有什么可以帮助您的?',
created_at: '2026-05-13 14:20:00',
updated_at: '2026-05-18 16:40:00',
operations: ['view', 'edit', 'enable'],
},
{
code_id: 5,
code_name: '私域增长渠道活码',
position_code: 'crm_growth',
position_name: '私域增长',
channel_code: 'CRM-QR-005',
employee_name: '陈欣欣',
employee_role_text: '私域运营主管',
agent_names: ['私域引流Agent', '客诉安抚Agent', '管家Agent'],
status: 'enable',
qrcode_url: 'https://picsum.photos/seed/crm_growth/200/200',
description: '用于私域流量承接与转化',
welcome_message: '欢迎加入私域社群',
created_at: '2026-05-14 16:40:00',
updated_at: '2026-05-19 18:30:00',
operations: ['view', 'edit', 'disable'],
},
];
const positionDerivedInfo: Record<string, PositionDerivedInfo> = {
store_sales: {
position_code: 'store_sales',
position_name: '店销顾问',
channel_code: 'DSC-QR-001',
employee_id: 1001,
employee_name: '张小萌',
employee_role_text: '店销主管',
agent_names: ['店销助手Agent', '管家Agent'],
},
after_sales_service: {
position_code: 'after_sales_service',
position_name: '售后客服',
channel_code: 'ASC-QR-002',
employee_id: 1002,
employee_name: '李小燕',
employee_role_text: '客服专员',
agent_names: ['售后问答Agent', '回访问答Agent', '管家Agent'],
},
live_ops: {
position_code: 'live_ops',
position_name: '直播运营',
channel_code: 'LVO-QR-003',
employee_id: 1003,
employee_name: '王大力',
employee_role_text: '直播运营专员',
agent_names: ['直播助手Agent', '管家Agent'],
},
site_consultant: {
position_code: 'site_consultant',
position_name: '官网顾问',
channel_code: 'WGC-QR-004',
employee_id: 1004,
employee_name: '赵明亮',
employee_role_text: '在线顾问',
agent_names: ['官网接待Agent', '管家Agent'],
},
crm_growth: {
position_code: 'crm_growth',
position_name: '私域增长',
channel_code: 'CRM-QR-005',
employee_id: 1005,
employee_name: '陈欣欣',
employee_role_text: '私域运营主管',
agent_names: ['私域引流Agent', '客诉安抚Agent', '管家Agent'],
},
training_teacher: {
position_code: 'training_teacher',
position_name: '培训讲师',
channel_code: 'TRT-QR-NEW',
employee_id: 1006,
employee_name: '周语晴',
employee_role_text: '培训专员',
agent_names: ['培训助手Agent', '管家Agent'],
},
};
function canUseStorage() {
return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';
}
function readStoredItems(): ChannelCodeMockItem[] {
if (!canUseStorage()) return [];
try {
const raw = window.localStorage.getItem(savedStorageKey);
return raw ? JSON.parse(raw) : [];
} catch {
return [];
}
}
function readDeletedIds(): number[] {
if (!canUseStorage()) return [];
try {
const raw = window.localStorage.getItem(deletedStorageKey);
return raw ? JSON.parse(raw) : [];
} catch {
return [];
}
}
function readStatusOverrides(): Record<number, 'enable' | 'disable'> {
if (!canUseStorage()) return {};
try {
const raw = window.localStorage.getItem(statusStorageKey);
return raw ? JSON.parse(raw) : {};
} catch {
return {};
}
}
function writeStoredItems(items: ChannelCodeMockItem[]) {
if (!canUseStorage()) return;
window.localStorage.setItem(savedStorageKey, JSON.stringify(items));
}
function writeDeletedIds(ids: number[]) {
if (!canUseStorage()) return;
window.localStorage.setItem(deletedStorageKey, JSON.stringify(ids));
}
function writeStatusOverrides(overrides: Record<number, 'enable' | 'disable'>) {
if (!canUseStorage()) return;
window.localStorage.setItem(statusStorageKey, JSON.stringify(overrides));
}
export function resetChannelCodeMockState() {
if (!canUseStorage()) return;
window.localStorage.removeItem(savedStorageKey);
window.localStorage.removeItem(deletedStorageKey);
window.localStorage.removeItem(statusStorageKey);
}
export function getChannelCodeSource(): ChannelCodeMockItem[] {
const deletedIds = new Set(readDeletedIds());
const storedItems = readStoredItems();
const storedById = new Map(storedItems.map((item) => [item.code_id, item]));
const statusOverrides = readStatusOverrides();
const preservedBase = baseChannelCodes
.filter((item) => !deletedIds.has(item.code_id))
.map((item) => {
const stored = storedById.get(item.code_id);
if (stored) return stored;
const overrideStatus = statusOverrides[item.code_id];
if (overrideStatus) {
const operations: ChannelCodeMockItem['operations'] = overrideStatus === 'enable'
? ['view', 'edit', 'disable']
: ['view', 'edit', 'enable'];
return { ...item, status: overrideStatus, operations };
}
return item;
});
const createdItems = storedItems
.filter((item) => !baseChannelCodes.some((base) => base.code_id === item.code_id))
.filter((item) => !deletedIds.has(item.code_id));
return [...preservedBase, ...createdItems].sort((a, b) => a.code_id - b.code_id);
}
export const channelCodeMockFixtures: Record<string, ChannelCodeMockFixture> = {
normal: { items: baseChannelCodes },
empty: { items: [] },
filteredEmpty: { items: [] },
loadError: { items: [], loadError: true },
paginationBoundary: { items: baseChannelCodes },
saveError: { items: baseChannelCodes, saveError: true },
statusBlockError: { items: baseChannelCodes, statusBlockError: true },
qrcodeLoadError: {
items: baseChannelCodes.map((item) => ({ ...item, qrcode_load_error: true })),
qrcodeLoadError: true,
},
};
export function getChannelCodeRecord(codeId?: string, source = getChannelCodeSource()): ChannelCodeMockItem | undefined {
if (!codeId) return undefined;
return source.find((item) => String(item.code_id) === codeId);
}
export function getPositionDerivedInfo(positionCode: string): PositionDerivedInfo | undefined {
return positionDerivedInfo[positionCode];
}
export function getPositionsWithChannelCode(source = getChannelCodeSource()): string[] {
return source.map((item) => item.position_code);
}
export interface ChannelCodeListPageResult {
items: ChannelCodeMockItem[];
page: number;
pageSize: number;
total: number;
}
export function getChannelCodeListPage({
keyword = '',
positionCode = '',
status = '',
page,
pageSize,
source = getChannelCodeSource(),
}: ChannelCodeListPageQuery): ChannelCodeListPageResult {
const normalizedKeyword = keyword.trim().toLowerCase();
const filtered = source.filter((item) => {
if (normalizedKeyword && !item.code_name.toLowerCase().includes(normalizedKeyword)) {
return false;
}
if (positionCode && item.position_code !== positionCode) {
return false;
}
if (status && item.status !== status) {
return false;
}
return true;
});
const start = (page - 1) * pageSize;
return {
items: filtered.slice(start, start + pageSize),
page,
pageSize,
total: filtered.length,
};
}
export function saveChannelCodeRecord(payload: SaveChannelCodePayload): ChannelCodeMockItem {
const source = getChannelCodeSource();
const current = payload.codeId ? source.find((item) => item.code_id === payload.codeId) : undefined;
const nextId = current?.code_id ?? Math.max(0, ...source.map((item) => item.code_id)) + 1;
const now = new Date().toISOString().replace('T', ' ').slice(0, 19);
const positionInfo = payload.position_code ? getPositionDerivedInfo(payload.position_code) : undefined;
const nextRecord: ChannelCodeMockItem = {
code_id: nextId,
code_name: payload.code_name.trim(),
position_code: current?.position_code ?? payload.position_code ?? '',
position_name: current?.position_name ?? positionInfo?.position_name ?? '',
channel_code: current?.channel_code ?? positionInfo?.channel_code ?? '',
employee_name: current?.employee_name ?? positionInfo?.employee_name ?? '',
employee_role_text: current?.employee_role_text ?? positionInfo?.employee_role_text ?? '',
agent_names: current?.agent_names ?? positionInfo?.agent_names ?? [],
status: payload.status ?? current?.status ?? 'disable',
qrcode_url: current?.qrcode_url ?? `https://picsum.photos/seed/${payload.position_code ?? nextId}/200/200`,
description: payload.description?.trim() ?? current?.description ?? '',
welcome_message: payload.welcome_message?.trim() ?? current?.welcome_message ?? '',
created_at: current?.created_at ?? now,
updated_at: now,
operations: (payload.status ?? current?.status ?? 'disable') === 'enable'
? ['view', 'edit', 'disable']
: ['view', 'edit', 'enable'],
};
const storedItems = readStoredItems();
writeStoredItems([...storedItems.filter((item) => item.code_id !== nextRecord.code_id), nextRecord]);
writeDeletedIds(readDeletedIds().filter((id) => id !== nextRecord.code_id));
return nextRecord;
}
export function updateChannelCodeStatus(
codeId: number,
targetStatus: 'enable' | 'disable',
scenario: 'normal' | 'statusBlockError' = 'normal',
): UpdateStatusResult {
const source = getChannelCodeSource();
const current = source.find((item) => item.code_id === codeId);
if (!current) {
return {
code_id: codeId,
status: targetStatus,
updated_at: new Date().toISOString().replace('T', ' ').slice(0, 19),
};
}
if (scenario === 'statusBlockError' && targetStatus === 'disable' && current.status === 'enable') {
return {
code_id: codeId,
status: 'enable',
updated_at: current.updated_at,
blocked: true,
message: '该渠道活码正在官网展示中,请先从官网配置中移除后再停用',
};
}
const now = new Date().toISOString().replace('T', ' ').slice(0, 19);
const overrides = readStatusOverrides();
overrides[codeId] = targetStatus;
writeStatusOverrides(overrides);
return {
code_id: codeId,
status: targetStatus,
updated_at: now,
};
}
export function getPositionOptions(): PositionOption[] {
return getAgentTagSource().map((tag) => ({
tag_id: tag.tag_id,
name: tag.name,
code: tag.code,
}));
}
/**
* Mock API: GET /api/v1/agent-group/employee/{employee_id}/qrcodes
* 获取员工已配置的渠道活码列表,以及可用于新建活码的派生信息。
*/
export function getEmployeeQRCodes(employeeId: number): EmployeeConfiguredQRCodesResponse | undefined {
// 从 positionDerivedInfo 中找到该员工
const positionEntry = Object.values(positionDerivedInfo).find(
(info) => info.employee_id === employeeId,
);
if (!positionEntry) {
return undefined;
}
// 获取该员工已配置的活码列表
const allCodes = getChannelCodeSource();
const employeeCodes = allCodes.filter(
(code) => code.position_code === positionEntry.position_code,
);
return {
employee_id: employeeId,
employee_name: positionEntry.employee_name,
employee_role_text: positionEntry.employee_role_text,
qrcode_count: employeeCodes.length,
qrcodes: employeeCodes.map((code) => ({
qrcode_id: code.code_id,
position_name: code.position_name,
channel_code: code.channel_code,
status: code.status,
created_at: code.created_at,
})),
};
}
\ No newline at end of file \ No newline at end of file
...@@ -367,6 +367,8 @@ interface CreateAgentPayload { ...@@ -367,6 +367,8 @@ interface CreateAgentPayload {
name: string; name: string;
/** 绑定的岗位标签 ID 列表。 */ /** 绑定的岗位标签 ID 列表。 */
position_ids: number[]; position_ids: number[];
/** 绑定的企微员工 ID。 */
user_ids: string[];
/** Agent 描述。 */ /** Agent 描述。 */
description: string; description: string;
/** 绑定的 Skill 编码列表。 */ /** 绑定的 Skill 编码列表。 */
...@@ -496,6 +498,67 @@ interface DeleteAgentResponse { ...@@ -496,6 +498,67 @@ interface DeleteAgentResponse {
### 5.1 岗位标签列表 ### 5.1 岗位标签列表
#### 5.1.1 本期前端 mock 最小契约
`agent-tags-management` 切片在没有后端接口的情况下,先使用前端本地 mock 数据驱动岗位标签管理列表页、新建页、编辑页和删除前引用检查。该 mock 契约只覆盖当前页面字段、查询参数、表单 payload 和状态 fixture,不锁定后端接口路径、详情接口形态或存储实现。
```ts
interface JobTagListMockItem {
/** 岗位标签 ID。 */
tag_id: number;
/** 岗位标签名称。 */
name: string;
/** 岗位标签编码。 */
code: string;
/** 岗位标签描述。 */
description: string;
/** 使用该岗位标签的 Agent 数。 */
agent_count: number;
/** 关联渠道活码数。 */
channel_code_count: number;
/** 关联官网 Tab 数。 */
official_tab_count: number;
/** 创建时间展示字符串。 */
created_at: string;
}
interface JobTagListMockQuery {
/** 模糊搜索,匹配岗位标签名称或编码。 */
keyword?: string;
/** 页码,从 1 开始。 */
page: number;
/** 每页条数。 */
pageSize: number;
}
interface CreateJobTagMockPayload {
name: string;
code: string;
description?: string;
}
interface UpdateJobTagMockPayload {
name: string;
description?: string;
}
```
本期 fixture 至少覆盖:
| fixture | 场景 |
|-|-|
| `normal` | 正常列表。 |
| `empty` | 初始空数据。 |
| `loadError` | 列表加载失败。 |
| `saveError` | 新建或编辑保存失败。 |
| `referenceError` | 删除前引用检查失败。 |
页面规则:
- 关键词同时匹配岗位标签名称和岗位标签编码。
- 新建和编辑页不定义详情接口;编辑页优先使用列表行数据,缺失时再按 `tag_id` 从列表 mock 数据源兜底。
- 删除前必须先获取引用检查结果;渠道活码和官网 Tab 属于阻塞引用,Agent 属于可解除引用。
`GET /api/v1/position-tags` `GET /api/v1/position-tags`
```ts ```ts
...@@ -672,6 +735,7 @@ interface JobTagReferences { ...@@ -672,6 +735,7 @@ interface JobTagReferences {
- `blocking_references`:阻塞性引用,包括渠道活码、官网 Tab,必须先手动删除。 - `blocking_references`:阻塞性引用,包括渠道活码、官网 Tab,必须先手动删除。
- `detachable_references`:可解除引用,包括 Agent,删除时自动解除。 - `detachable_references`:可解除引用,包括 Agent,删除时自动解除。
- `hints`:给前端的提示文案数组。 - `hints`:给前端的提示文案数组。
- 本期前端 mock 只要求最小引用检查结果包含 `blocking_references` 与 `detachable_references` 两组数据,并能区分“可确认删除”和“阻塞删除”。
响应 `data` 示例: 响应 `data` 示例:
...@@ -868,7 +932,7 @@ interface SkillDetail extends SkillSummary { ...@@ -868,7 +932,7 @@ interface SkillDetail extends SkillSummary {
} }
``` ```
前端以 Modal 展示 `doc_markdown` 内容。 前端以 Drawer 展示 `doc_markdown` 内容。
## 7. 渠道活码接口 ## 7. 渠道活码接口
...@@ -1463,7 +1527,7 @@ interface PositionEmployeesResponse { ...@@ -1463,7 +1527,7 @@ interface PositionEmployeesResponse {
"employee_name": "张三", "employee_name": "张三",
"wechat_user_id": "zhangsan", "wechat_user_id": "zhangsan",
"department": "销售部", "department": "销售部",
"status": "在职" "status": "已挂载Agent/未挂载Agent"
} }
] ]
} }
...@@ -1488,8 +1552,12 @@ interface EmployeeConfiguredQRCodeItem { ...@@ -1488,8 +1552,12 @@ interface EmployeeConfiguredQRCodeItem {
} }
interface EmployeeConfiguredQRCodesResponse { interface EmployeeConfiguredQRCodesResponse {
/** 员工 ID。 */
employee_id: number;
/** 员工姓名。 */ /** 员工姓名。 */
employee_name: string; employee_name: string;
/** 员工角色文本。 */
employee_role_text: string;
/** 已配置活码数量。 */ /** 已配置活码数量。 */
qrcode_count: number; qrcode_count: number;
/** 已配置活码列表。 */ /** 已配置活码列表。 */
...@@ -1501,13 +1569,15 @@ interface EmployeeConfiguredQRCodesResponse { ...@@ -1501,13 +1569,15 @@ interface EmployeeConfiguredQRCodesResponse {
```json ```json
{ {
"employee_name": "张三", "employee_id": 1001,
"employee_name": "张小萌",
"employee_role_text": "店销主管",
"qrcode_count": 3, "qrcode_count": 3,
"qrcodes": [ "qrcodes": [
{ {
"qrcode_id": 1, "qrcode_id": 1,
"position_name": "驻店销售岗", "position_name": "店销顾问",
"channel_code": "zdxs_store_sales_emp_12345", "channel_code": "DSC-QR-001",
"status": "enable", "status": "enable",
"created_at": "2026-05-15T10:00:00Z" "created_at": "2026-05-15T10:00:00Z"
} }
...@@ -1647,6 +1717,10 @@ interface OfficialSiteTabListItem { ...@@ -1647,6 +1717,10 @@ interface OfficialSiteTabListItem {
position_code: string; position_code: string;
/** 岗位展示名称。 */ /** 岗位展示名称。 */
position_name: string; position_name: string;
/** 岗位标题,最多 30 字,展示在官网 Tab 名称下方。 */
main_title: string;
/** 岗位说明,最多 200 字,展示在官网 Tab 内容区。 */
sub_title: string;
/** 关联渠道活码 ID。 */ /** 关联渠道活码 ID。 */
qrcode_id: number; qrcode_id: number;
/** 关联渠道活码二维码图片地址。 */ /** 关联渠道活码二维码图片地址。 */
...@@ -1703,6 +1777,10 @@ interface CreateOfficialSiteTabPayload { ...@@ -1703,6 +1777,10 @@ interface CreateOfficialSiteTabPayload {
position_name: string; position_name: string;
/** 关联渠道活码 ID。 */ /** 关联渠道活码 ID。 */
qrcode_id: string; qrcode_id: string;
/** 岗位标题,最多 30 字,展示在官网 Tab 名称下方。 */
main_title: string;
/** 岗位说明,最多 200 字,展示在官网 Tab 内容区。 */
sub_title: string;
/** 初始展示状态。 */ /** 初始展示状态。 */
display_status: OfficialSiteTabStatus; display_status: OfficialSiteTabStatus;
/** 展示排序,值越小越靠前。 */ /** 展示排序,值越小越靠前。 */
...@@ -1718,6 +1796,10 @@ interface CreateOfficialSiteTabResponse { ...@@ -1718,6 +1796,10 @@ interface CreateOfficialSiteTabResponse {
position_name: string; position_name: string;
/** 关联渠道活码 ID。 */ /** 关联渠道活码 ID。 */
qrcode_id: string; qrcode_id: string;
/** 岗位标题,最多 30 字,展示在官网 Tab 名称下方。 */
main_title: string;
/** 岗位说明,最多 200 字,展示在官网 Tab 内容区。 */
sub_title: string;
/** 创建时间。 */ /** 创建时间。 */
created_at: DateTimeString; created_at: DateTimeString;
} }
...@@ -1731,6 +1813,8 @@ interface CreateOfficialSiteTabResponse { ...@@ -1731,6 +1813,8 @@ interface CreateOfficialSiteTabResponse {
"position_code": "store_sales", "position_code": "store_sales",
"position_name": "驻店销售岗", "position_name": "驻店销售岗",
"qrcode_id": 5, "qrcode_id": 5,
"main_title": "AI赋能驻店销售,让每位销售都成为顶尖专家",
"sub_title": "通过AI智能分析销售录音,自动生成复盘报告,推送个性化学习内容,帮助驻店销售持续提升销售能力和业绩。",
"created_at": "2026-05-16T10:00:00Z" "created_at": "2026-05-16T10:00:00Z"
} }
``` ```
...@@ -1739,6 +1823,8 @@ interface CreateOfficialSiteTabResponse { ...@@ -1739,6 +1823,8 @@ interface CreateOfficialSiteTabResponse {
- `position_code` 必填,从岗位标签选择。 - `position_code` 必填,从岗位标签选择。
- `qrcode_id` 必填,选项仅展示已启用的渠道活码。 - `qrcode_id` 必填,选项仅展示已启用的渠道活码。
- `main_title` 必填,最多 30 字,展示在官网 Tab 名称下方,用一句话介绍 AI 如何赋能该岗位。
- `sub_title` 必填,最多 200 字,展示在官网 Tab 内容区,详细描述 AI 为该岗位带来的价值。
- `display_status` 默认 `enable`。 - `display_status` 默认 `enable`。
- `sort_order` 必填,范围 0-99。 - `sort_order` 必填,范围 0-99。
...@@ -1752,6 +1838,10 @@ interface UpdateOfficialSiteTabPayload { ...@@ -1752,6 +1838,10 @@ interface UpdateOfficialSiteTabPayload {
position_name: string; position_name: string;
/** 关联渠道活码 ID。 */ /** 关联渠道活码 ID。 */
qrcode_id: string; qrcode_id: string;
/** 岗位标题,最多 30 字,展示在官网 Tab 名称下方。 */
main_title: string;
/** 岗位说明,最多 200 字,展示在官网 Tab 内容区。 */
sub_title: string;
/** 展示状态。 */ /** 展示状态。 */
display_status: OfficialSiteTabStatus; display_status: OfficialSiteTabStatus;
/** 展示排序,值越小越靠前。 */ /** 展示排序,值越小越靠前。 */
...@@ -1888,6 +1978,122 @@ interface AvailableOfficialSiteQRCodeResponse { ...@@ -1888,6 +1978,122 @@ interface AvailableOfficialSiteQRCodeResponse {
} }
``` ```
### 8.7 官网岗位 Tab 前端 mock 最小契约
本节定义官网岗位 Tab 配置页面的前端 mock 最小契约,用于列表页、新建页、编辑页的本地开发和测试。
```ts
interface OfficialSiteJobTabMockItem {
/** Tab 配置 ID。 */
tab_id: number;
/** 岗位标签 ID。 */
position_tag_id: number;
/** 岗位标签编码。 */
position_code: string;
/** 岗位展示名称。 */
position_name: string;
/** 关联渠道活码 ID。 */
qrcode_id: number;
/** 关联渠道活码名称。 */
qrcode_name: string;
/** 渠道编码(派生信息)。 */
channel_code: string;
/** 承接员工姓名(派生信息)。 */
employee_name: string;
/** 承接员工角色(派生信息)。 */
employee_role_text: string;
/** 岗位标题,最多 30 字,展示在官网 Tab 名称下方。 */
main_title: string;
/** 岗位说明,最多 200 字,展示在官网 Tab 内容区。 */
sub_title: string;
/** Tab 排序,范围 0-99。 */
tab_order: number;
/** 展示状态。 */
display_status: 'enable' | 'disable';
/** 创建时间展示字符串。 */
created_at: string;
/** 更新时间展示字符串。 */
updated_at: string;
/** 当前行可展示的操作。 */
operations: ('edit' | 'enable' | 'disable' | 'delete' | 'configureAgent')[];
}
interface OfficialSiteJobTabListQuery {
/** 关键词,匹配岗位名称或渠道活码名称。 */
keyword?: string;
/** 展示状态筛选。 */
displayStatus?: 'enable' | 'disable' | '';
/** 页码。 */
page: number;
/** 每页条数。 */
pageSize: number;
}
interface PositionTagCandidate {
/** 岗位标签 ID。 */
tag_id: number;
/** 岗位标签名称。 */
name: string;
/** 岗位标签编码。 */
code: string;
/** 是否已配置渠道活码。 */
has_channel_code: boolean;
/** 关联渠道活码 ID(如有)。 */
qrcode_id?: number;
/** 关联渠道活码名称(如有)。 */
qrcode_name?: string;
}
interface PositionQRCodeDerivedInfo {
/** 渠道编码。 */
channel_code: string;
/** 承接员工姓名。 */
employee_name: string;
/** 承接员工角色。 */
employee_role_text: string;
}
interface SaveOfficialSiteJobTabPayload {
/** Tab 配置 ID(编辑时传入)。 */
tabId?: number;
/** 岗位标签编码(新建时必填)。 */
position_code?: string;
/** 关联渠道活码 ID(新建时必填)。 */
qrcode_id?: number;
/** 岗位标题,最多 30 字,展示在官网 Tab 名称下方。 */
main_title: string;
/** 岗位说明,最多 200 字,展示在官网 Tab 内容区。 */
sub_title: string;
/** Tab 排序,范围 0-99。 */
tab_order: number;
/** 展示状态。 */
display_status: 'enable' | 'disable';
}
```
**Fixture scenarios:**
| fixture | scenario |
|-|-|
| `normal` | 正常列表,包含展示中和已下架的 Tab |
| `empty` | 初始无数据 |
| `filteredEmpty` | 筛选无结果 |
| `loadError` | 列表加载失败 |
| `saveError` | 创建/编辑保存失败 |
| `statusBlockError` | 上架/下架被业务规则阻断 |
| `positionDuplicate` | 岗位已存在官网 Tab 配置 |
| `positionNoQRCode` | 岗位未配置渠道活码 |
**业务规则:**
- 每个岗位只能创建一个官网岗位 Tab,重复岗位阻止创建。
- 岗位必须已配置渠道活码才能创建 Tab,无渠道活码阻止创建。
- 编辑页锁定岗位和渠道活码为只读,允许修改岗位标题、岗位说明、排序和展示状态。
- 岗位标题 `main_title` 必填,最多 30 字。
- 岗位说明 `sub_title` 必填,最多 200 字。
- Tab 排序范围为 0-99 整数。
- 删除 Tab 只清理 Tab 配置和 Agent 展示配置,不影响 Agent 原始数据或渠道活码。
## 9. 官网 Agent 展示配置接口 ## 9. 官网 Agent 展示配置接口
### 9.1 可配置 Agent 列表 ### 9.1 可配置 Agent 列表
...@@ -2213,6 +2419,67 @@ interface SaveMethodologyResponse { ...@@ -2213,6 +2419,67 @@ interface SaveMethodologyResponse {
- `steps` 必填,4-10 个步骤。 - `steps` 必填,4-10 个步骤。
- 每个步骤的 `step_icon`、`step_name`、`step_order`、`step_image` 必填。 - 每个步骤的 `step_icon`、`step_name`、`step_order`、`step_image` 必填。
- `step_name` 最多 20 字。 - `step_name` 最多 20 字。
### 10.3 方法论配置页前端 mock 最小契约
在真实接口未接入前,方法论展示配置页使用页面级 mock fixture 驱动。该 mock 契约只覆盖当前后台配置页的加载、保存、图片校验和错误展示,不约束后端存储结构、文件服务实现或官网 H5 页面渲染方式。
```ts
type MethodologyDisplayStatus = "enable" | "disable";
interface MethodologyImageResource {
id: string;
name: string;
url: string;
mime_type: "image/png" | "image/jpeg";
size_bytes: number;
}
interface MethodologyIconResource {
id: string;
name: string;
url: string;
}
interface MethodologyStepRecord {
step_id: string;
step_icon?: MethodologyIconResource;
step_name: string;
step_order: number;
step_image?: MethodologyImageResource;
}
interface MethodologyConfigRecord {
config_id: string;
display_status: MethodologyDisplayStatus;
main_title: string;
sub_title: string;
steps: MethodologyStepRecord[];
updated_at?: DateTimeString;
}
```
本期 fixture 至少覆盖:
| fixture | 场景 |
|-|-|
| `normal` | 正常配置加载与保存。 |
| `disabled` | 展示状态关闭。 |
| `emptySteps` | 步骤列表为空。 |
| `loadError` | 配置加载失败。 |
| `saveError` | 配置保存失败。 |
| `uploadError` | 内容图 mock 上传失败。 |
| `invalidFileType` | 内容图格式错误。 |
| `largeFile` | 内容图超过 10MB。 |
页面规则:
- `display_status = enable` 且步骤为空时禁止保存,并提示至少添加一个方法论步骤。
- `display_status = disable` 时允许步骤为空,但标题、副标题和已有步骤字段仍需通过前端校验。
- 步骤图标表达展示图标资源,不保存上传进度、重试次数或其他临时 UI 状态。
- **步骤图标和内容图各只能配置一张图片,达到上限后隐藏上传按钮。**
- 内容图仅允许 PNG/JPG/JPEG,且文件大小不得超过 10MB。
- 步骤图标仅允许 PNG/JPG/JPEG/GIF,且文件大小不得超过 10MB。
- 步骤序号需要连续。 - 步骤序号需要连续。
- 方法论图片上传复用 `POST /api/v1/official-site/upload`。 - 方法论图片上传复用 `POST /api/v1/official-site/upload`。
......
import { describe, expect, it } from 'vitest';
import {
getMethodologyConfigFixture,
methodologyConfigMockFixtures,
validateMethodologyContentImageFile,
} from './methodology-config-mock';
describe('methodology config mock contract', () => {
it('provides the minimal page-facing config fields and step resources', () => {
const fixture = methodologyConfigMockFixtures.normal;
expect(fixture.data).toMatchObject({
config_id: expect.any(String),
display_status: expect.stringMatching(/enable|disable/),
main_title: expect.any(String),
sub_title: expect.any(String),
steps: expect.any(Array),
});
expect(fixture.data.steps[0]).toMatchObject({
step_id: expect.any(String),
step_icon: {
id: expect.any(String),
name: expect.any(String),
url: expect.any(String),
},
step_name: expect.any(String),
step_order: expect.any(Number),
step_image: {
id: expect.any(String),
name: expect.any(String),
url: expect.any(String),
mime_type: expect.stringMatching(/image\/(png|jpeg|gif)/),
size_bytes: expect.any(Number),
},
});
});
it('covers required load, save, and upload fixtures without locking a backend', () => {
expect(Object.keys(methodologyConfigMockFixtures).sort()).toEqual([
'disabled',
'emptySteps',
'invalidFileType',
'largeFile',
'loadError',
'normal',
'saveError',
'uploadError',
]);
});
it('exposes scenario lookup for page state selection', () => {
expect(getMethodologyConfigFixture('disabled').data.display_status).toBe('disable');
expect(getMethodologyConfigFixture('missing-scenario')).toBe(methodologyConfigMockFixtures.normal);
});
it('validates content image format and size with page-facing error messages', () => {
// GIF is now supported
expect(validateMethodologyContentImageFile(new File(['demo'], 'cover.gif', { type: 'image/gif' }))).toBeUndefined();
// BMP is not supported
expect(validateMethodologyContentImageFile(new File(['demo'], 'cover.bmp', { type: 'image/bmp' }))).toEqual({
code: 'invalid-file-type',
message: '内容图仅支持 PNG/JPG/JPEG/GIF',
});
const oversized = new File(['demo'], 'cover.png', { type: 'image/png' });
Object.defineProperty(oversized, 'size', { value: 10 * 1024 * 1024 + 1 });
expect(validateMethodologyContentImageFile(oversized)).toEqual({
code: 'file-too-large',
message: '内容图大小不能超过 10MB',
});
expect(validateMethodologyContentImageFile(new File(['demo'], 'cover.jpg', { type: 'image/jpeg' }))).toBeUndefined();
});
});
export type MethodologyDisplayStatus = 'enable' | 'disable';
export interface MethodologyImageResource {
id: string;
name: string;
url: string;
mime_type: string;
size_bytes: number;
}
export interface MethodologyIconResource {
id: string;
name: string;
url: string;
}
export interface MethodologyStepRecord {
step_id: string;
step_icon?: MethodologyIconResource;
step_name: string;
step_order: number;
step_image?: MethodologyImageResource;
}
export interface MethodologyConfigRecord {
config_id: string;
display_status: MethodologyDisplayStatus;
main_title: string;
sub_title: string;
steps: MethodologyStepRecord[];
updated_at?: string;
}
export interface MethodologyConfigFixture {
data: MethodologyConfigRecord;
loadError?: boolean;
saveError?: boolean;
uploadError?: boolean;
invalidFileType?: boolean;
largeFile?: boolean;
}
export interface MethodologyFileValidationError {
code: 'invalid-file-type' | 'file-too-large';
message: string;
}
const demoIcon = (id: string, name: string): MethodologyIconResource => ({
id,
name,
url: `https://mock.assets.local/icons/${id}.png`,
});
const demoImage = (id: string, name: string, mimeType: 'image/png' | 'image/jpeg' | 'image/gif', sizeBytes: number): MethodologyImageResource => ({
id,
name,
url: `https://mock.assets.local/images/${id}.${mimeType === 'image/png' ? 'png' : mimeType === 'image/gif' ? 'gif' : 'jpg'}`,
mime_type: mimeType,
size_bytes: sizeBytes,
});
const normalData: MethodologyConfigRecord = {
config_id: 'methodology-config-001',
display_status: 'enable',
main_title: '四步打造可复用的岗位 Agent',
sub_title: '从目标澄清到上线复盘,帮助团队沉淀一套稳定可复制的方法论。',
updated_at: '2026-05-21 10:30:00',
steps: [
{
step_id: 'step-1',
step_icon: demoIcon('discovery', '需求澄清图标'),
step_name: '需求澄清',
step_order: 1,
step_image: demoImage('discovery-panel', '需求澄清内容图', 'image/png', 512_000),
},
{
step_id: 'step-2',
step_icon: demoIcon('design', '方案设计图标'),
step_name: '方案设计',
step_order: 2,
step_image: demoImage('design-panel', '方案设计内容图', 'image/jpeg', 768_000),
},
],
};
export const methodologyConfigMockFixtures = {
normal: {
data: normalData,
},
disabled: {
data: {
...normalData,
display_status: 'disable',
},
},
emptySteps: {
data: {
...normalData,
steps: [],
},
},
loadError: {
data: normalData,
loadError: true,
},
saveError: {
data: normalData,
saveError: true,
},
uploadError: {
data: normalData,
uploadError: true,
},
invalidFileType: {
data: normalData,
invalidFileType: true,
},
largeFile: {
data: normalData,
largeFile: true,
},
} satisfies Record<string, MethodologyConfigFixture>;
export function getMethodologyConfigFixture(scenario?: string): MethodologyConfigFixture {
switch (scenario) {
case 'disabled':
return methodologyConfigMockFixtures.disabled;
case 'emptySteps':
return methodologyConfigMockFixtures.emptySteps;
case 'loadError':
return methodologyConfigMockFixtures.loadError;
case 'saveError':
return methodologyConfigMockFixtures.saveError;
case 'uploadError':
return methodologyConfigMockFixtures.uploadError;
case 'invalidFileType':
return methodologyConfigMockFixtures.invalidFileType;
case 'largeFile':
return methodologyConfigMockFixtures.largeFile;
default:
return methodologyConfigMockFixtures.normal;
}
}
export function validateMethodologyContentImageFile(file: File): MethodologyFileValidationError | undefined {
const acceptedTypes = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif'];
if (!acceptedTypes.includes(file.type)) {
return {
code: 'invalid-file-type',
message: '内容图仅支持 PNG/JPG/JPEG/GIF',
};
}
if (file.size > 10 * 1024 * 1024) {
return {
code: 'file-too-large',
message: '内容图大小不能超过 10MB',
};
}
return undefined;
}
import { beforeEach, describe, expect, it } from 'vitest';
import {
agentDisplayConfigMockFixtures,
getAgentDisplayConfigList,
getAgentDisplayConfigItem,
saveAgentDisplayConfig,
uploadAgentMedia,
mapAgentStatusToText,
mapDisplayStatusToText,
getDisplayStatusTextForList,
resetAgentDisplayConfigMockState,
type AgentDisplayConfigMockItem,
} from './official-site-agent-display-config-mock';
describe('official-site-agent-display-config mock contract', () => {
beforeEach(() => {
window.localStorage.clear();
resetAgentDisplayConfigMockState();
});
describe('fixtures', () => {
it('provides the minimal page-facing fields and required fixtures', () => {
const [config] = agentDisplayConfigMockFixtures.normal.items;
expect(config).toMatchObject({
agent_id: expect.any(Number),
agent_name: expect.any(String),
agent_status: expect.any(String),
icon_url: expect.any(String),
media_url: expect.any(String),
media_type: expect.any(String),
media_size: expect.any(Number),
speech_title: expect.any(String),
speech_content: expect.any(String),
display_status: expect.any(String),
sort_order: expect.any(Number),
created_at: expect.any(String),
updated_at: expect.any(String),
can_edit: expect.any(Boolean),
});
expect(Object.keys(agentDisplayConfigMockFixtures).sort()).toEqual([
'allDisabled',
'allEnabled',
'empty',
'formatError',
'loadError',
'normal',
'saveError',
'sizeError',
'uploadError',
'validationError',
]);
});
it('provides empty fixture', () => {
expect(agentDisplayConfigMockFixtures.empty.items).toEqual([]);
});
it('provides loadError fixture', () => {
expect(agentDisplayConfigMockFixtures.loadError.loadError).toBe(true);
});
it('provides saveError fixture', () => {
expect(agentDisplayConfigMockFixtures.saveError.saveError).toBe(true);
});
it('provides uploadError fixture', () => {
expect(agentDisplayConfigMockFixtures.uploadError.uploadError).toBe(true);
});
it('provides formatError fixture', () => {
expect(agentDisplayConfigMockFixtures.formatError.formatError).toBe(true);
});
it('provides sizeError fixture', () => {
expect(agentDisplayConfigMockFixtures.sizeError.sizeError).toBe(true);
});
it('provides validationError fixture', () => {
expect(agentDisplayConfigMockFixtures.validationError.validationError).toBe(true);
});
it('provides allDisabled fixture where display_status is disable', () => {
const fixture = agentDisplayConfigMockFixtures.allDisabled;
expect(fixture.items.every((item) => item.display_status === 'disable')).toBe(true);
});
it('provides allEnabled fixture where display_status is enable', () => {
const fixture = agentDisplayConfigMockFixtures.allEnabled;
expect(fixture.items.every((item) => item.display_status === 'enable')).toBe(true);
});
});
describe('getAgentDisplayConfigList', () => {
it('returns undefined for non-existent tab', () => {
const result = getAgentDisplayConfigList(99999);
expect(result).toBeUndefined();
});
it('returns tab context information', () => {
const result = getAgentDisplayConfigList(1);
expect(result).toBeDefined();
expect(result!.tab_context).toMatchObject({
tab_id: 1,
position_name: '店销顾问',
qrcode_name: '店销顾问渠道活码',
channel_code: 'DSC-QR-001',
employee_name: '张小萌',
employee_role_text: '店销主管',
});
});
it('returns Agent list for tab', () => {
const result = getAgentDisplayConfigList(1);
expect(result!.items.length).toBeGreaterThan(0);
expect(result!.total).toBe(result!.items.length);
});
it('管家 Agent 不进入列表', () => {
// Verify that agent_id = 1 (管家 Agent) is never in the list
const allResults = [getAgentDisplayConfigList(1), getAgentDisplayConfigList(2), getAgentDisplayConfigList(3)];
for (const result of allResults) {
if (result) {
expect(result.items.find((item) => item.agent_id === 1)).toBeUndefined();
}
}
});
it('已停用 Agent 保留展示但不可编辑', () => {
const result = getAgentDisplayConfigList(1);
expect(result).toBeDefined();
const disabledAgent = result!.items.find((item) => item.agent_status === 'disable');
expect(disabledAgent).toBeDefined();
expect(disabledAgent!.can_edit).toBe(false);
});
it('未配置 Agent 默认已下架', () => {
// Tab 2 has one agent that is not configured (客诉安抚Agent)
const result = getAgentDisplayConfigList(2);
expect(result).toBeDefined();
const unconfiguredAgent = result!.items.find((item) => item.media_url === '');
expect(unconfiguredAgent).toBeDefined();
expect(unconfiguredAgent!.display_status).toBe('disable');
});
it('returns empty items for loadError scenario', () => {
const result = getAgentDisplayConfigList(1, 'loadError');
expect(result).toBeDefined();
expect(result!.items).toEqual([]);
});
});
describe('getAgentDisplayConfigItem', () => {
it('returns undefined for non-existent tab', () => {
const result = getAgentDisplayConfigItem(99999, 101);
expect(result).toBeUndefined();
});
it('returns undefined for non-existent agent in tab', () => {
const result = getAgentDisplayConfigItem(1, 99999);
expect(result).toBeUndefined();
});
it('returns existing config for agent in tab', () => {
const result = getAgentDisplayConfigItem(1, 101);
expect(result).toBeDefined();
expect(result!.agent_id).toBe(101);
});
});
describe('saveAgentDisplayConfig', () => {
it('creates new config for unconfigured agent', () => {
const result = saveAgentDisplayConfig(2, {
agent_id: 105,
icon_url: 'https://cdn.example.com/test.png',
speech_title: '客诉安抚Agent',
speech_content: '安抚客户情绪,提供解决方案',
media_url: 'https://cdn.example.com/test.jpg',
display_status: 'enable',
sort_order: 10,
});
expect(result.agent_id).toBe(105);
expect(result.display_status).toBe('enable');
expect(result.sort_order).toBe(10);
expect(result.blocked).toBeFalsy();
});
it('updates existing config', () => {
const result = saveAgentDisplayConfig(1, {
agent_id: 101,
icon_url: 'https://cdn.example.com/icons/review-agent.png',
speech_title: '复盘Agent',
speech_content: '更新后的概述',
media_url: 'https://cdn.example.com/media/review-agent.mp4',
display_status: 'disable',
sort_order: 5,
});
expect(result.agent_id).toBe(101);
expect(result.speech_content).toBe('更新后的概述');
expect(result.display_status).toBe('disable');
expect(result.sort_order).toBe(5);
expect(result.blocked).toBeFalsy();
});
it('blocks save for disabled agent', () => {
// Agent 102 is disabled in tab 1
const result = saveAgentDisplayConfig(1, {
agent_id: 102,
speech_content: '尝试编辑停用Agent',
display_status: 'enable',
sort_order: 10,
});
expect(result.blocked).toBe(true);
expect(result.message).toContain('已停用');
});
it('blocks save for non-existent tab', () => {
const result = saveAgentDisplayConfig(99999, {
agent_id: 101,
speech_content: '测试',
display_status: 'disable',
sort_order: 10,
});
expect(result.blocked).toBe(true);
expect(result.message).toContain('不存在');
});
it('blocks save for agent not in tab', () => {
const result = saveAgentDisplayConfig(1, {
agent_id: 99999,
speech_content: '测试',
display_status: 'disable',
sort_order: 10,
});
expect(result.blocked).toBe(true);
expect(result.message).toContain('不属于');
});
it('validates speech_content required', () => {
const result = saveAgentDisplayConfig(1, {
agent_id: 101,
icon_url: 'https://cdn.example.com/test.png',
speech_title: '测试Agent',
speech_content: '',
media_url: 'https://cdn.example.com/test.jpg',
display_status: 'disable',
sort_order: 10,
});
expect(result.blocked).toBe(true);
expect(result.validation_errors?.speech_content).toContain('必填');
});
it('validates speech_content max 100 chars', () => {
const longContent = '这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容';
expect(longContent.length).toBeGreaterThan(100);
const result = saveAgentDisplayConfig(1, {
agent_id: 101,
icon_url: 'https://cdn.example.com/test.png',
speech_title: '测试Agent',
speech_content: longContent,
media_url: 'https://cdn.example.com/test.jpg',
display_status: 'disable',
sort_order: 10,
});
expect(result.blocked).toBe(true);
expect(result.validation_errors?.speech_content).toContain('100字');
});
it('validates sort_order 0-99', () => {
const result = saveAgentDisplayConfig(1, {
agent_id: 101,
icon_url: 'https://cdn.example.com/test.png',
speech_title: '测试Agent',
speech_content: '测试',
media_url: 'https://cdn.example.com/test.jpg',
display_status: 'disable',
sort_order: 100,
});
expect(result.blocked).toBe(true);
expect(result.validation_errors?.sort_order).toContain('0-99');
});
it('returns save error in saveError scenario', () => {
const result = saveAgentDisplayConfig(1, {
agent_id: 101,
icon_url: 'https://cdn.example.com/test.png',
speech_title: '测试Agent',
speech_content: '测试',
media_url: 'https://cdn.example.com/test.jpg',
display_status: 'disable',
sort_order: 10,
}, 'saveError');
expect(result.blocked).toBe(true);
expect(result.message).toContain('保存失败');
});
});
describe('uploadAgentMedia', () => {
it('uploads image successfully', () => {
const result = uploadAgentMedia(
{ name: 'test.png', size: 500 * 1024, type: 'image/png' },
'icon',
);
expect(result.url).toBeDefined();
expect(result.type).toBe('image');
expect(result.size).toBe(500 * 1024);
expect(result.blocked).toBeFalsy();
});
it('uploads video successfully', () => {
const result = uploadAgentMedia(
{ name: 'test.mp4', size: 10 * 1024 * 1024, type: 'video/mp4' },
'media',
);
expect(result.url).toBeDefined();
expect(result.type).toBe('video');
expect(result.blocked).toBeFalsy();
});
it('uploads gif successfully', () => {
const result = uploadAgentMedia(
{ name: 'test.gif', size: 2 * 1024 * 1024, type: 'image/gif' },
'media',
);
expect(result.url).toBeDefined();
expect(result.type).toBe('gif');
expect(result.blocked).toBeFalsy();
});
it('blocks upload in uploadError scenario', () => {
const result = uploadAgentMedia(
{ name: 'test.png', size: 100 * 1024, type: 'image/png' },
'icon',
'uploadError',
);
expect(result.blocked).toBe(true);
expect(result.message).toContain('上传失败');
});
it('blocks unsupported format', () => {
const result = uploadAgentMedia(
{ name: 'test.pdf', size: 100 * 1024, type: 'application/pdf' },
'media',
'formatError',
);
expect(result.blocked).toBe(true);
expect(result.message).toContain('格式不支持');
});
it('blocks file exceeding size limit for media', () => {
const result = uploadAgentMedia(
{ name: 'large.mp4', size: 25 * 1024 * 1024, type: 'video/mp4' },
'media',
'sizeError',
);
expect(result.blocked).toBe(true);
expect(result.message).toContain('20MB');
});
it('blocks file exceeding size limit for icon', () => {
const result = uploadAgentMedia(
{ name: 'large.png', size: 6 * 1024 * 1024, type: 'image/png' },
'icon',
'sizeError',
);
expect(result.blocked).toBe(true);
expect(result.message).toContain('5MB');
});
});
describe('status text mapping', () => {
it('maps agent_status enable to 已上架', () => {
expect(mapAgentStatusToText('enable')).toBe('已上架');
});
it('maps agent_status disable to 已停用', () => {
expect(mapAgentStatusToText('disable')).toBe('已停用');
});
it('maps display_status enable to 展示中', () => {
expect(mapDisplayStatusToText('enable')).toBe('展示中');
});
it('maps display_status disable to 已下架', () => {
expect(mapDisplayStatusToText('disable')).toBe('已下架');
});
it('returns - for disabled agent in list display status', () => {
expect(getDisplayStatusTextForList('disable', 'enable')).toBe('-');
expect(getDisplayStatusTextForList('disable', 'disable')).toBe('-');
});
it('returns mapped text for enabled agent in list display status', () => {
expect(getDisplayStatusTextForList('enable', 'enable')).toBe('展示中');
expect(getDisplayStatusTextForList('enable', 'disable')).toBe('已下架');
});
});
});
\ No newline at end of file \ No newline at end of file
import { getAgentTagSource } from './agent-tag-mock';
import { getOfficialSiteJobTabSource, getOfficialSiteJobTabRecord } from './official-site-job-tab-mock';
import { getChannelCodeSource, getPositionDerivedInfo } from './channel-code-mock';
export type AgentDisplayStatus = 'enable' | 'disable';
export type AgentInternalStatus = 'enable' | 'disable';
export interface AgentDisplayConfigMockItem extends Record<string, unknown> {
agent_id: number;
agent_name: string;
agent_status: AgentInternalStatus;
icon_url: string;
media_url: string;
media_type: 'image' | 'video' | 'gif';
media_size: number;
speech_title: string;
speech_content: string;
display_status: AgentDisplayStatus;
sort_order: number;
created_at: string;
updated_at: string;
/** 已上架 Agent 可编辑,已停用 Agent 不可编辑 */
can_edit: boolean;
}
export interface AgentDisplayConfigMockFixture {
items: AgentDisplayConfigMockItem[];
loadError?: boolean;
saveError?: boolean;
uploadError?: boolean;
formatError?: boolean;
sizeError?: boolean;
validationError?: boolean;
}
export interface AgentDisplayConfigListResult {
items: AgentDisplayConfigMockItem[];
tab_context: {
tab_id: number;
position_name: string;
qrcode_name: string;
channel_code: string;
employee_name: string;
employee_role_text: string;
};
total: number;
}
export interface SaveAgentDisplayConfigPayload {
agent_id: number;
icon_url?: string;
media_url?: string;
media_type?: 'image' | 'video' | 'gif';
media_size?: number;
speech_title?: string;
speech_content: string;
display_status: AgentDisplayStatus;
sort_order: number;
}
export interface SaveAgentDisplayConfigResult {
agent_id: number;
icon_url: string;
media_url: string;
media_type: 'image' | 'video' | 'gif';
media_size: number;
speech_title: string;
speech_content: string;
display_status: AgentDisplayStatus;
sort_order: number;
created_at: string;
updated_at: string;
can_edit: boolean;
blocked?: boolean;
message?: string;
validation_errors?: Record<string, string>;
}
export interface UploadResult {
url: string;
type: 'image' | 'video' | 'gif';
size: number;
blocked?: boolean;
message?: string;
}
const now = () => new Date().toISOString().replace('T', ' ').slice(0, 19);
const baseAgentDisplayConfigs: Record<number, AgentDisplayConfigMockItem[]> = {
// tab_id: 1 - 店销顾问岗位
1: [
{
agent_id: 101,
agent_name: '复盘Agent',
agent_status: 'enable',
icon_url: 'https://cdn.example.com/icons/review-agent.png',
media_url: 'https://cdn.example.com/media/review-agent.mp4',
media_type: 'video',
media_size: 15 * 1024 * 1024, // 15MB
speech_title: '复盘Agent',
speech_content: '帮助店销顾问完成每日复盘,分析业绩数据和客户反馈',
display_status: 'enable',
sort_order: 10,
created_at: '2026-05-10 09:00:00',
updated_at: '2026-05-15 10:30:00',
can_edit: true,
},
{
agent_id: 103,
agent_name: '销售助手Agent',
agent_status: 'enable',
icon_url: 'https://cdn.example.com/icons/sales-assist.png',
media_url: 'https://cdn.example.com/media/sales-assist.gif',
media_type: 'gif',
media_size: 2 * 1024 * 1024, // 2MB
speech_title: '销售助手Agent',
speech_content: '智能推荐话术和产品搭配,提升销售转化率',
display_status: 'disable',
sort_order: 20,
created_at: '2026-05-11 10:00:00',
updated_at: '2026-05-16 11:00:00',
can_edit: true,
},
{
agent_id: 102,
agent_name: '质检Agent',
agent_status: 'disable',
icon_url: 'https://cdn.example.com/icons/quality-check.png',
media_url: '',
media_type: 'image',
media_size: 0,
speech_title: '质检Agent',
speech_content: '对话质检,检测合规性和服务质量',
display_status: 'disable',
sort_order: 30,
created_at: '2026-05-12 12:00:00',
updated_at: '2026-05-17 09:00:00',
can_edit: false, // 已停用,不可编辑
},
],
// tab_id: 2 - 售后客服岗位
2: [
{
agent_id: 105,
agent_name: '客诉安抚Agent',
agent_status: 'enable',
icon_url: '',
media_url: '',
media_type: 'image',
media_size: 0,
speech_title: '客诉安抚Agent',
speech_content: '', // 未配置,speech_content 为空
display_status: 'disable', // 未配置,默认已下架
sort_order: 10,
created_at: '2026-05-13 14:00:00',
updated_at: '2026-05-18 16:00:00',
can_edit: true,
},
],
// tab_id: 3 - 私域增长岗位
3: [
{
agent_id: 104,
agent_name: '线索跟进Agent',
agent_status: 'enable',
icon_url: 'https://cdn.example.com/icons/lead-follow.png',
media_url: 'https://cdn.example.com/media/lead-follow.jpg',
media_type: 'image',
media_size: 500 * 1024, // 500KB
speech_title: '线索跟进Agent',
speech_content: '自动跟进线索,提醒销售及时处理',
display_status: 'enable',
sort_order: 0,
created_at: '2026-05-14 15:00:00',
updated_at: '2026-05-19 17:00:00',
can_edit: true,
},
],
};
const savedConfigsKey = 'agent-admin-saved-agent-display-configs';
function canUseStorage() {
return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';
}
function readSavedConfigs(): Record<number, AgentDisplayConfigMockItem[]> {
if (!canUseStorage()) return {};
try {
const raw = window.localStorage.getItem(savedConfigsKey);
return raw ? JSON.parse(raw) : {};
} catch {
return {};
}
}
function writeSavedConfigs(configs: Record<number, AgentDisplayConfigMockItem[]>) {
if (!canUseStorage()) return;
window.localStorage.setItem(savedConfigsKey, JSON.stringify(configs));
}
export function resetAgentDisplayConfigMockState() {
if (!canUseStorage()) return;
window.localStorage.removeItem(savedConfigsKey);
}
export const agentDisplayConfigMockFixtures: Record<string, AgentDisplayConfigMockFixture> = {
normal: { items: baseAgentDisplayConfigs[1] },
empty: { items: [] },
allDisabled: {
items: [
{
agent_id: 106,
agent_name: '未配置Agent',
agent_status: 'enable',
icon_url: '',
media_url: '',
media_type: 'image',
media_size: 0,
speech_title: '未配置Agent',
speech_content: '',
display_status: 'disable',
sort_order: 0,
created_at: '2026-05-20 10:00:00',
updated_at: '2026-05-20 10:00:00',
can_edit: true,
},
],
},
allEnabled: {
items: [
{
agent_id: 107,
agent_name: '展示中Agent',
agent_status: 'enable',
icon_url: 'https://cdn.example.com/icons/test.png',
media_url: 'https://cdn.example.com/media/test.jpg',
media_type: 'image',
media_size: 800 * 1024,
speech_title: '展示中Agent',
speech_content: '测试Agent概述',
display_status: 'enable',
sort_order: 0,
created_at: '2026-05-20 10:00:00',
updated_at: '2026-05-20 10:00:00',
can_edit: true,
},
],
},
loadError: { items: [], loadError: true },
saveError: { items: baseAgentDisplayConfigs[1], saveError: true },
uploadError: { items: baseAgentDisplayConfigs[1], uploadError: true },
formatError: { items: baseAgentDisplayConfigs[1], formatError: true },
sizeError: { items: baseAgentDisplayConfigs[1], sizeError: true },
validationError: { items: baseAgentDisplayConfigs[1], validationError: true },
};
/**
* 从岗位关联渠道活码中提取可配置 Agent 列表
* 排除管家 Agent(agent_id = 1)
*/
function getAgentsForTab(tabId: number): { agent_id: number; agent_name: string; agent_status: AgentInternalStatus; speech_title: string }[] {
const tab = getOfficialSiteJobTabRecord(String(tabId), getOfficialSiteJobTabSource());
if (!tab) return [];
const positionCode = tab.position_code;
const agentTags = getAgentTagSource();
// 找到岗位对应岗位标签的 Agent
// 简化逻辑:根据渠道活码关联岗位,返回该岗位下的 Agent
const channelCodes = getChannelCodeSource();
const channelCode = channelCodes.find((c) => c.code_id === tab.qrcode_id);
if (!channelCode) return [];
// Mock 简化:根据岗位返回对应的 Agent
const agentMapping: Record<string, number[]> = {
'store_sales': [101, 103, 102],
'after_sales_service': [105],
'crm_growth': [104],
};
const agentIds = agentMapping[positionCode] ?? [];
const agentNames: Record<number, { name: string; status: AgentInternalStatus }> = {
101: { name: '复盘Agent', status: 'enable' },
102: { name: '质检Agent', status: 'disable' },
103: { name: '销售助手Agent', status: 'enable' },
104: { name: '线索跟进Agent', status: 'enable' },
105: { name: '客诉安抚Agent', status: 'enable' },
};
// 排除管家 Agent (agent_id = 1)
return agentIds
.filter((id) => id !== 1)
.map((id) => ({
agent_id: id,
agent_name: agentNames[id]?.name ?? `Agent-${id}`,
agent_status: agentNames[id]?.status ?? 'enable',
speech_title: agentNames[id]?.name ?? `Agent-${id}`,
}));
}
export function getAgentDisplayConfigList(
tabId: number,
scenario: string = 'normal',
): AgentDisplayConfigListResult | undefined {
const tab = getOfficialSiteJobTabRecord(String(tabId), getOfficialSiteJobTabSource());
if (!tab) return undefined;
// Load error scenario
if (scenario === 'loadError') {
return {
items: [],
tab_context: {
tab_id: tab.tab_id,
position_name: tab.position_name,
qrcode_name: tab.qrcode_name,
channel_code: tab.channel_code,
employee_name: tab.employee_name,
employee_role_text: tab.employee_role_text,
},
total: 0,
};
}
// Empty scenario - no configurable agents
if (scenario === 'empty') {
return {
items: [],
tab_context: {
tab_id: tab.tab_id,
position_name: tab.position_name,
qrcode_name: tab.qrcode_name,
channel_code: tab.channel_code,
employee_name: tab.employee_name,
employee_role_text: tab.employee_role_text,
},
total: 0,
};
}
const savedConfigs = readSavedConfigs();
const baseConfigs = baseAgentDisplayConfigs[tabId] ?? [];
const overriddenConfigs = savedConfigs[tabId] ?? [];
// Merge saved configs with base configs
const configMap = new Map<number, AgentDisplayConfigMockItem>();
for (const config of baseConfigs) {
configMap.set(config.agent_id, config);
}
for (const config of overriddenConfigs) {
configMap.set(config.agent_id, config);
}
// Get agents from this tab's channel code
const agentsForTab = getAgentsForTab(tabId);
// Build final list: include all agents for this tab
const items: AgentDisplayConfigMockItem[] = agentsForTab.map((agent) => {
const existingConfig = configMap.get(agent.agent_id);
if (existingConfig) {
// Update can_edit based on agent_status
return {
...existingConfig,
agent_status: agent.agent_status,
can_edit: agent.agent_status === 'enable',
};
}
// New agent without config - default to disabled
return {
agent_id: agent.agent_id,
agent_name: agent.agent_name,
agent_status: agent.agent_status,
icon_url: '',
media_url: '',
media_type: 'image',
media_size: 0,
speech_title: agent.speech_title,
speech_content: '',
display_status: 'disable',
sort_order: 99,
created_at: now(),
updated_at: now(),
can_edit: agent.agent_status === 'enable',
};
});
return {
items,
tab_context: {
tab_id: tab.tab_id,
position_name: tab.position_name,
qrcode_name: tab.qrcode_name,
channel_code: tab.channel_code,
employee_name: tab.employee_name,
employee_role_text: tab.employee_role_text,
},
total: items.length,
};
}
export function getAgentDisplayConfigItem(tabId: number, agentId: number): AgentDisplayConfigMockItem | undefined {
const result = getAgentDisplayConfigList(tabId);
if (!result) return undefined;
return result.items.find((item) => item.agent_id === agentId);
}
export function saveAgentDisplayConfig(
tabId: number,
payload: SaveAgentDisplayConfigPayload,
scenario: string = 'normal',
): SaveAgentDisplayConfigResult {
const result = getAgentDisplayConfigList(tabId);
if (!result) {
return {
agent_id: payload.agent_id,
icon_url: payload.icon_url ?? '',
media_url: payload.media_url ?? '',
media_type: payload.media_type ?? 'image',
media_size: payload.media_size ?? 0,
speech_title: payload.speech_title ?? '',
speech_content: payload.speech_content,
display_status: payload.display_status,
sort_order: payload.sort_order,
created_at: now(),
updated_at: now(),
can_edit: false,
blocked: true,
message: '岗位展示配置不存在',
};
}
const agent = result.items.find((item) => item.agent_id === payload.agent_id);
if (!agent) {
return {
agent_id: payload.agent_id,
icon_url: payload.icon_url ?? '',
media_url: payload.media_url ?? '',
media_type: payload.media_type ?? 'image',
media_size: payload.media_size ?? 0,
speech_title: payload.speech_title ?? '',
speech_content: payload.speech_content,
display_status: payload.display_status,
sort_order: payload.sort_order,
created_at: now(),
updated_at: now(),
can_edit: false,
blocked: true,
message: 'Agent 不属于当前岗位',
};
}
// Check if agent is disabled
if (agent.agent_status === 'disable') {
return {
agent_id: payload.agent_id,
icon_url: agent.icon_url,
media_url: agent.media_url,
media_type: agent.media_type,
media_size: agent.media_size,
speech_title: agent.speech_title,
speech_content: agent.speech_content,
display_status: agent.display_status,
sort_order: agent.sort_order,
created_at: agent.created_at,
updated_at: agent.updated_at,
can_edit: false,
blocked: true,
message: '该 Agent 已停用,无法编辑展示配置',
};
}
// Validation errors
const validationErrors: Record<string, string> = {};
if (!payload.icon_url?.trim()) {
validationErrors.icon_url = '图标必填';
}
if (!payload.speech_title?.trim()) {
validationErrors.speech_title = 'Agent名称必填';
}
if (!payload.speech_content.trim()) {
validationErrors.speech_content = 'Agent概述必填';
} else if (payload.speech_content.length > 100) {
validationErrors.speech_content = 'Agent概述不能超过100字';
}
if (!payload.media_url?.trim()) {
validationErrors.media_url = '展示素材必填';
}
if (payload.sort_order < 0 || payload.sort_order > 99) {
validationErrors.sort_order = '排序请输入0-99的整数';
}
if (Object.keys(validationErrors).length > 0) {
return {
agent_id: payload.agent_id,
icon_url: payload.icon_url ?? '',
media_url: payload.media_url ?? '',
media_type: payload.media_type ?? 'image',
media_size: payload.media_size ?? 0,
speech_title: payload.speech_title ?? '',
speech_content: payload.speech_content,
display_status: payload.display_status,
sort_order: payload.sort_order,
created_at: now(),
updated_at: now(),
can_edit: true,
blocked: true,
message: '字段校验失败',
validation_errors: validationErrors,
};
}
// Save error scenario
if (scenario === 'saveError') {
return {
agent_id: payload.agent_id,
icon_url: payload.icon_url ?? '',
media_url: payload.media_url ?? '',
media_type: payload.media_type ?? 'image',
media_size: payload.media_size ?? 0,
speech_title: payload.speech_title ?? '',
speech_content: payload.speech_content,
display_status: payload.display_status,
sort_order: payload.sort_order,
created_at: now(),
updated_at: now(),
can_edit: true,
blocked: true,
message: '保存失败,请重试',
};
}
// Normal save
const savedConfigs = readSavedConfigs();
const currentConfigs = savedConfigs[tabId] ?? baseAgentDisplayConfigs[tabId] ?? [];
const existingIndex = currentConfigs.findIndex((c) => c.agent_id === payload.agent_id);
const newConfig: AgentDisplayConfigMockItem = {
agent_id: payload.agent_id,
agent_name: agent.agent_name,
agent_status: agent.agent_status,
icon_url: payload.icon_url ?? agent.icon_url,
media_url: payload.media_url ?? agent.media_url,
media_type: payload.media_type ?? agent.media_type,
media_size: payload.media_size ?? agent.media_size,
speech_title: payload.speech_title ?? agent.speech_title,
speech_content: payload.speech_content,
display_status: payload.display_status,
sort_order: payload.sort_order,
created_at: existingIndex >= 0 ? currentConfigs[existingIndex].created_at : now(),
updated_at: now(),
can_edit: true,
};
if (existingIndex >= 0) {
currentConfigs[existingIndex] = newConfig;
} else {
currentConfigs.push(newConfig);
}
savedConfigs[tabId] = currentConfigs;
writeSavedConfigs(savedConfigs);
return {
agent_id: newConfig.agent_id,
icon_url: newConfig.icon_url,
media_url: newConfig.media_url,
media_type: newConfig.media_type,
media_size: newConfig.media_size,
speech_title: newConfig.speech_title,
speech_content: newConfig.speech_content,
display_status: newConfig.display_status,
sort_order: newConfig.sort_order,
created_at: newConfig.created_at,
updated_at: newConfig.updated_at,
can_edit: newConfig.can_edit,
};
}
export function uploadAgentMedia(
file: { name: string; size: number; type: string },
usage: 'icon' | 'media',
scenario: string = 'normal',
): UploadResult {
// Upload error scenario
if (scenario === 'uploadError') {
return {
url: '',
type: 'image',
size: 0,
blocked: true,
message: '上传失败,请重试',
};
}
// Format error scenario
if (scenario === 'formatError') {
return {
url: '',
type: 'image',
size: 0,
blocked: true,
message: '文件格式不支持,请上传图片、视频或GIF',
};
}
// Size error scenario (max 20MB for media)
const maxSize = usage === 'icon' ? 5 * 1024 * 1024 : 20 * 1024 * 1024;
if (file.size > maxSize) {
return {
url: '',
type: 'image',
size: 0,
blocked: true,
message: usage === 'icon' ? '图标大小不能超过5MB' : '素材大小不能超过20MB',
};
}
// Validate file type
const validImageTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif'];
const validVideoTypes = ['video/mp4'];
const validTypes = usage === 'icon' ? validImageTypes : [...validImageTypes, ...validVideoTypes];
if (!validTypes.includes(file.type)) {
return {
url: '',
type: 'image',
size: 0,
blocked: true,
message: '文件格式不支持',
};
}
// Mock successful upload
const mediaType: 'image' | 'video' | 'gif' =
file.type === 'video/mp4' ? 'video' :
file.type === 'image/gif' ? 'gif' : 'image';
return {
url: `https://cdn.example.com/uploads/${usage}-${Date.now()}-${file.name}`,
type: mediaType,
size: file.size,
};
}
/**
* 映射 agent_status 到页面文案
*/
export function mapAgentStatusToText(status: AgentInternalStatus): string {
return status === 'enable' ? '已上架' : '已停用';
}
/**
* 映射 display_status 到页面文案
*/
export function mapDisplayStatusToText(status: AgentDisplayStatus): string {
return status === 'enable' ? '展示中' : '已下架';
}
/**
* 获取列表展示状态文案(已停用 Agent 显示 `-`)
*/
export function getDisplayStatusTextForList(agentStatus: AgentInternalStatus, displayStatus: AgentDisplayStatus): string {
if (agentStatus === 'disable') return '-';
return mapDisplayStatusToText(displayStatus);
}
\ No newline at end of file \ No newline at end of file
import { beforeEach, describe, expect, it } from 'vitest';
import {
officialSiteJobTabMockFixtures,
getOfficialSiteJobTabListPage,
getOfficialSiteJobTabRecord,
getPositionTagCandidates,
getPositionQRCodeDerivedInfo,
isPositionDuplicate,
saveOfficialSiteJobTabRecord,
updateOfficialSiteJobTabStatus,
deleteOfficialSiteJobTabRecord,
resetOfficialSiteJobTabMockState,
getOfficialSiteJobTabSource,
type OfficialSiteJobTabMockItem,
type PositionTagCandidate,
} from './official-site-job-tab-mock';
describe('official-site-job-tab mock contract', () => {
beforeEach(() => {
window.localStorage.clear();
resetOfficialSiteJobTabMockState();
});
it('provides the minimal page-facing fields and required fixtures', () => {
const [tab] = officialSiteJobTabMockFixtures.normal.items;
expect(tab).toMatchObject({
tab_id: expect.any(Number),
position_tag_id: expect.any(Number),
position_code: expect.any(String),
position_name: expect.any(String),
qrcode_id: expect.any(Number),
qrcode_name: expect.any(String),
channel_code: expect.any(String),
employee_name: expect.any(String),
employee_role_text: expect.any(String),
tab_order: expect.any(Number),
display_status: expect.any(String),
main_title: expect.any(String),
sub_title: expect.any(String),
agent_count: expect.any(Number),
created_at: expect.any(String),
updated_at: expect.any(String),
operations: expect.any(Array),
});
expect(Object.keys(officialSiteJobTabMockFixtures).sort()).toEqual([
'empty',
'filteredEmpty',
'loadError',
'normal',
'positionDuplicate',
'positionNoQRCode',
'saveError',
'statusBlockError',
]);
});
it('filters by keyword (position name or qrcode name)', () => {
const result1 = getOfficialSiteJobTabListPage({ keyword: '店销', page: 1, pageSize: 10 });
expect(result1.items.length).toBeGreaterThan(0);
expect(result1.items[0].position_name).toContain('店销');
const result2 = getOfficialSiteJobTabListPage({ keyword: '渠道活码', page: 1, pageSize: 10 });
expect(result2.items.length).toBeGreaterThan(0);
});
it('filters by display status', () => {
const enableResult = getOfficialSiteJobTabListPage({ displayStatus: 'enable', page: 1, pageSize: 10 });
expect(enableResult.items.every((item) => item.display_status === 'enable')).toBe(true);
const disableResult = getOfficialSiteJobTabListPage({ displayStatus: 'disable', page: 1, pageSize: 10 });
expect(disableResult.items.every((item) => item.display_status === 'disable')).toBe(true);
});
it('paginates from page-facing query fields', () => {
const paged = getOfficialSiteJobTabListPage({ page: 2, pageSize: 2 });
expect(paged.total).toBe(6); // baseOfficialSiteJobTabs has 6 items
expect(paged.items).toHaveLength(2); // page 2 with pageSize 2 has 2 items
expect(paged.page).toBe(2);
expect(paged.pageSize).toBe(2);
});
it('provides position tag candidates with has_channel_code flag', () => {
const candidates = getPositionTagCandidates();
expect(candidates.length).toBeGreaterThan(0);
expect(candidates[0]).toMatchObject({
tag_id: expect.any(Number),
name: expect.any(String),
code: expect.any(String),
has_channel_code: expect.any(Boolean),
});
// Some positions should have channel codes configured
const withChannelCode = candidates.find((c) => c.has_channel_code);
expect(withChannelCode).toBeDefined();
expect(withChannelCode!.qrcode_id).toBeDefined();
expect(withChannelCode!.qrcode_name).toBeDefined();
// Some positions may not have channel codes
const withoutChannelCode = candidates.find((c) => !c.has_channel_code);
// It's possible all positions have codes, so we don't strictly require this
});
it('provides QRCode derived info for position with channel code', () => {
const candidates = getPositionTagCandidates();
const withChannelCode = candidates.find((c) => c.has_channel_code);
if (withChannelCode) {
const info = getPositionQRCodeDerivedInfo(withChannelCode.code);
expect(info).toBeDefined();
expect(info!).toMatchObject({
channel_code: expect.any(String),
employee_name: expect.any(String),
employee_role_text: expect.any(String),
});
}
});
it('returns undefined for QRCode derived info when position has no channel code', () => {
const info = getPositionQRCodeDerivedInfo('nonexistent_position');
expect(info).toBeUndefined();
});
it('detects duplicate position for official site tab', () => {
// Position 'store_sales' should already have a tab in normal fixture
const isDuplicate = isPositionDuplicate('store_sales');
expect(isDuplicate).toBe(true);
// A position without tab should not be duplicate
// 'training_teacher' is now in fixtures, so use a different position
const notDuplicate = isPositionDuplicate('beauty_consultant');
expect(notDuplicate).toBe(false);
});
it('allows duplicate check to exclude current tab (for edit mode)', () => {
const tabs = getOfficialSiteJobTabSource();
const existingTab = tabs.find((t) => t.position_code === 'store_sales');
if (existingTab) {
// When editing the same tab, it should not be considered duplicate
const isDuplicate = isPositionDuplicate('store_sales', existingTab.tab_id);
expect(isDuplicate).toBe(false);
}
});
it('creates a new official site job tab with status disable by default', () => {
// First get a position that has channel code but no existing tab
const candidates = getPositionTagCandidates();
const availablePosition = candidates.find((c) => c.has_channel_code && !isPositionDuplicate(c.code));
if (!availablePosition) {
// Skip if no available position
return;
}
const created = saveOfficialSiteJobTabRecord({
position_code: availablePosition.code,
qrcode_id: availablePosition.qrcode_id!,
tab_order: 10,
display_status: 'disable',
});
expect(created.tab_id).toBeGreaterThan(0);
expect(created.display_status).toBe('disable');
expect(created.tab_order).toBe(10);
expect(created.position_code).toBe(availablePosition.code);
expect(getOfficialSiteJobTabRecord(String(created.tab_id))).toBeDefined();
});
it('blocks create when position already has an official site tab', () => {
const result = saveOfficialSiteJobTabRecord({
position_code: 'store_sales', // Already has a tab in fixture
qrcode_id: 1,
tab_order: 5,
display_status: 'enable',
});
expect(result.blocked).toBe(true);
expect(result.message).toContain('已存在');
expect(result.tab_id).toBe(0);
});
it('blocks create when position has no channel code', () => {
// Use a position code that doesn't have channel code configured
const result = saveOfficialSiteJobTabRecord({
position_code: 'position_without_qrcode',
qrcode_id: 0, // No QRCode
tab_order: 5,
display_status: 'enable',
});
expect(result.blocked).toBe(true);
expect(result.message).toContain('暂未配置渠道活码');
});
it('updates existing official site job tab', () => {
const existing = officialSiteJobTabMockFixtures.normal.items[0];
const updated = saveOfficialSiteJobTabRecord({
tabId: existing.tab_id,
tab_order: 50,
display_status: 'enable',
});
expect(updated.tab_id).toBe(existing.tab_id);
expect(updated.tab_order).toBe(50);
expect(updated.display_status).toBe('enable');
expect(updated.position_code).toBe(existing.position_code); // Position unchanged
});
it('enables and disables official site job tab status', () => {
const existing = officialSiteJobTabMockFixtures.normal.items.find(
(item) => item.display_status === 'disable',
);
if (!existing) throw new Error('No disabled item found');
const enabled = updateOfficialSiteJobTabStatus(existing.tab_id, 'enable', 'normal');
expect(enabled.display_status).toBe('enable');
expect(enabled.updated_at).not.toBe(existing.updated_at);
});
it('blocks status change with business blocking error', () => {
const existing = officialSiteJobTabMockFixtures.normal.items.find(
(item) => item.display_status === 'enable',
);
if (!existing) throw new Error('No enabled item found');
const result = updateOfficialSiteJobTabStatus(existing.tab_id, 'disable', 'statusBlockError');
expect(result.blocked).toBe(true);
expect(result.message).toContain('Agent');
expect(result.display_status).toBe('enable');
});
it('deletes official site job tab and clears agent display configs', () => {
const existing = officialSiteJobTabMockFixtures.normal.items[0];
const result = deleteOfficialSiteJobTabRecord(existing.tab_id);
expect(result.success).toBe(true);
expect(result.tab_id).toBe(existing.tab_id);
expect(result.message).toContain('Agent');
// Verify the tab is deleted
expect(getOfficialSiteJobTabRecord(String(existing.tab_id))).toBeUndefined();
});
it('returns undefined for non-existent tab record', () => {
const record = getOfficialSiteJobTabRecord('99999');
expect(record).toBeUndefined();
});
it('provides empty fixture', () => {
expect(officialSiteJobTabMockFixtures.empty.items).toEqual([]);
});
it('provides loadError fixture', () => {
expect(officialSiteJobTabMockFixtures.loadError.loadError).toBe(true);
});
it('provides saveError fixture', () => {
expect(officialSiteJobTabMockFixtures.saveError.saveError).toBe(true);
});
it('provides positionDuplicate fixture', () => {
const fixture = officialSiteJobTabMockFixtures.positionDuplicate;
expect(fixture.positionDuplicate).toBe(true);
});
it('provides positionNoQRCode fixture', () => {
const fixture = officialSiteJobTabMockFixtures.positionNoQRCode;
expect(fixture.positionNoQRCode).toBe(true);
});
it('provides ai intro fields in mock data', () => {
const tabs = officialSiteJobTabMockFixtures.normal.items;
const tabWithAiIntro = tabs.find((t) => t.tab_id === 1);
expect(tabWithAiIntro?.main_title).toBe('AI 智能助手提升店销效率');
expect(tabWithAiIntro?.sub_title).toContain('AI 智能问答');
});
it('provides ai intro empty fields fixture', () => {
const tabs = officialSiteJobTabMockFixtures.normal.items;
const tabWithEmptyAiIntro = tabs.find((t) => t.tab_id === 4);
expect(tabWithEmptyAiIntro?.main_title).toBe('');
expect(tabWithEmptyAiIntro?.sub_title).toBe('');
});
it('provides ai intro over 30 chars fixture', () => {
const tabs = officialSiteJobTabMockFixtures.normal.items;
const tabWithLongMainTitle = tabs.find((t) => t.tab_id === 5);
expect(tabWithLongMainTitle?.main_title.length).toBeGreaterThan(30);
expect(tabWithLongMainTitle?.sub_title).toBe('');
});
it('provides ai intro over 200 chars fixture', () => {
const tabs = officialSiteJobTabMockFixtures.normal.items;
const tabWithLongSubTitle = tabs.find((t) => t.tab_id === 6);
expect(tabWithLongSubTitle?.main_title).toBe('AI 技术助手');
expect(tabWithLongSubTitle?.sub_title.length).toBeGreaterThan(200);
});
it('saves main_title and sub_title in create mode', () => {
const candidates = getPositionTagCandidates();
const availablePosition = candidates.find((c) => c.has_channel_code && !isPositionDuplicate(c.code));
if (!availablePosition) return;
const created = saveOfficialSiteJobTabRecord({
position_code: availablePosition.code,
qrcode_id: availablePosition.qrcode_id!,
tab_order: 10,
display_status: 'disable',
main_title: 'AI 测试标题',
sub_title: 'AI 测试说明内容',
});
expect(created.main_title).toBe('AI 测试标题');
expect(created.sub_title).toBe('AI 测试说明内容');
});
it('saves main_title and sub_title in edit mode', () => {
const existing = officialSiteJobTabMockFixtures.normal.items[0];
const updated = saveOfficialSiteJobTabRecord({
tabId: existing.tab_id,
tab_order: 50,
display_status: 'enable',
main_title: '更新后的标题',
sub_title: '更新后的说明',
});
expect(updated.main_title).toBe('更新后的标题');
expect(updated.sub_title).toBe('更新后的说明');
});
it('preserves existing main_title and sub_title when not provided in edit', () => {
const existing = officialSiteJobTabMockFixtures.normal.items[0];
const updated = saveOfficialSiteJobTabRecord({
tabId: existing.tab_id,
tab_order: 50,
display_status: 'enable',
});
expect(updated.main_title).toBe(existing.main_title);
expect(updated.sub_title).toBe(existing.sub_title);
});
it('provides main_title and sub_title in detail record', () => {
const record = getOfficialSiteJobTabRecord('1');
expect(record?.main_title).toBeDefined();
expect(record?.sub_title).toBeDefined();
});
});
\ No newline at end of file \ No newline at end of file
import { getAgentTagSource } from './agent-tag-mock';
import { getPositionDerivedInfo, getPositionsWithChannelCode, getChannelCodeSource } from './channel-code-mock';
export interface OfficialSiteJobTabMockItem extends Record<string, unknown> {
tab_id: number;
position_tag_id: number;
position_code: string;
position_name: string;
qrcode_id: number;
qrcode_name: string;
channel_code: string;
employee_name: string;
employee_role_text: string;
tab_order: number;
display_status: 'enable' | 'disable';
main_title: string;
sub_title: string;
agent_count: number;
created_at: string;
updated_at: string;
operations: ('edit' | 'enable' | 'disable' | 'delete' | 'configureAgent')[];
}
export interface PositionTagCandidate {
tag_id: number;
name: string;
code: string;
has_channel_code: boolean;
qrcode_id?: number;
qrcode_name?: string;
}
export interface PositionQRCodeDerivedInfo {
channel_code: string;
employee_name: string;
employee_role_text: string;
}
export interface OfficialSiteJobTabListPageQuery {
keyword?: string;
displayStatus?: 'enable' | 'disable' | '';
page: number;
pageSize: number;
source?: OfficialSiteJobTabMockItem[];
}
export interface OfficialSiteJobTabListPageResult {
items: OfficialSiteJobTabMockItem[];
page: number;
pageSize: number;
total: number;
}
export interface SaveOfficialSiteJobTabPayload {
tabId?: number;
position_code?: string;
qrcode_id?: number;
tab_order: number;
display_status: 'enable' | 'disable';
main_title?: string;
sub_title?: string;
}
export interface SaveOfficialSiteJobTabResult {
tab_id: number;
position_code: string;
position_name: string;
qrcode_id: number;
qrcode_name: string;
channel_code: string;
employee_name: string;
employee_role_text: string;
tab_order: number;
display_status: 'enable' | 'disable';
main_title: string;
sub_title: string;
agent_count: number;
created_at: string;
updated_at: string;
operations: ('edit' | 'enable' | 'disable' | 'delete' | 'configureAgent')[];
blocked?: boolean;
message?: string;
}
export interface UpdateOfficialSiteJobTabStatusResult {
tab_id: number;
display_status: 'enable' | 'disable';
updated_at: string;
blocked?: boolean;
message?: string;
}
export interface DeleteOfficialSiteJobTabResult {
tab_id: number;
success: boolean;
message: string;
}
export interface OfficialSiteJobTabMockFixture {
items: OfficialSiteJobTabMockItem[];
loadError?: boolean;
saveError?: boolean;
statusBlockError?: boolean;
positionDuplicate?: boolean;
positionNoQRCode?: boolean;
}
const savedStorageKey = 'agent-admin-saved-official-site-job-tabs';
const deletedStorageKey = 'agent-admin-deleted-official-site-job-tabs';
const statusStorageKey = 'agent-admin-official-site-job-tab-status';
const now = () => new Date().toISOString().replace('T', ' ').slice(0, 19);
const baseOfficialSiteJobTabs: OfficialSiteJobTabMockItem[] = [
{
tab_id: 1,
position_tag_id: 1,
position_code: 'store_sales',
position_name: '店销顾问',
qrcode_id: 1,
qrcode_name: '店销顾问渠道活码',
channel_code: 'DSC-QR-001',
employee_name: '张小萌',
employee_role_text: '店销主管',
tab_order: 10,
display_status: 'enable',
main_title: 'AI 智能助手提升店销效率',
sub_title: '通过 AI 智能问答、客户画像分析和销售话术推荐,帮助店销顾问快速响应客户需求,提升销售转化率。',
agent_count: 3,
created_at: '2026-05-10 09:00:00',
updated_at: '2026-05-15 10:30:00',
operations: ['edit', 'disable', 'delete', 'configureAgent'],
},
{
tab_id: 2,
position_tag_id: 2,
position_code: 'after_sales_service',
position_name: '售后客服',
qrcode_id: 2,
qrcode_name: '售后客服渠道活码',
channel_code: 'ASC-QR-002',
employee_name: '李小燕',
employee_role_text: '客服专员',
tab_order: 20,
display_status: 'enable',
main_title: 'AI 客服机器人赋能售后服务',
sub_title: 'AI 客服机器人自动解答常见问题,智能分流复杂工单,缩短客户等待时间,提升服务满意度。',
agent_count: 2,
created_at: '2026-05-11 10:15:00',
updated_at: '2026-05-16 11:45:00',
operations: ['edit', 'disable', 'delete', 'configureAgent'],
},
{
tab_id: 3,
position_tag_id: 5,
position_code: 'crm_growth',
position_name: '私域增长',
qrcode_id: 5,
qrcode_name: '私域增长渠道活码',
channel_code: 'CRM-QR-005',
employee_name: '陈欣欣',
employee_role_text: '私域运营主管',
tab_order: 30,
display_status: 'disable',
main_title: 'AI 助力私域精细化运营',
sub_title: 'AI 自动分析客户行为数据,智能推荐运营策略,帮助私域运营人员实现精准触达和高效转化。',
agent_count: 0,
created_at: '2026-05-12 11:30:00',
updated_at: '2026-05-17 14:20:00',
operations: ['edit', 'enable', 'delete', 'configureAgent'],
},
{
tab_id: 4,
position_tag_id: 6,
position_code: 'training_teacher',
position_name: '培训讲师',
qrcode_id: 6,
qrcode_name: '培训讲师渠道活码',
channel_code: 'TT-QR-006',
employee_name: '周小明',
employee_role_text: '培训专员',
tab_order: 40,
display_status: 'disable',
main_title: '',
sub_title: '',
agent_count: 0,
created_at: '2026-05-13 12:00:00',
updated_at: '2026-05-18 15:00:00',
operations: ['edit', 'enable', 'delete', 'configureAgent'],
},
{
tab_id: 5,
position_tag_id: 7,
position_code: 'online_consultant',
position_name: '在线顾问',
qrcode_id: 7,
qrcode_name: '在线顾问渠道活码',
channel_code: 'OC-QR-007',
employee_name: '吴小花',
employee_role_text: '在线顾问专员',
tab_order: 50,
display_status: 'disable',
main_title: '这是一段超过三十个字的岗位标题测试用例用于验证前端校验逻辑正确',
sub_title: '',
agent_count: 0,
created_at: '2026-05-14 13:00:00',
updated_at: '2026-05-19 16:00:00',
operations: ['edit', 'enable', 'delete', 'configureAgent'],
},
{
tab_id: 6,
position_tag_id: 8,
position_code: 'technical_support',
position_name: '技术支持',
qrcode_id: 8,
qrcode_name: '技术支持渠道活码',
channel_code: 'TS-QR-008',
employee_name: '赵小刚',
employee_role_text: '技术支持工程师',
tab_order: 60,
display_status: 'disable',
main_title: 'AI 技术助手',
sub_title: '这是一段超过二百个字的岗位说明测试用例用于验证前端校验逻辑,通过模拟超长文本输入来测试表单校验机制是否能够正确拦截并提示用户,确保数据完整性,防止用户输入过长的内容导致界面显示问题或后端存储异常,同时也能够帮助开发者更好地理解用户体验设计中的边界条件处理方式,从而提升整体产品质量和用户满意度,让系统更加稳定可靠运行,最终实现业务目标达成和客户价值创造,为企业数字化转型提供强有力的技术支撑和服务保障。',
agent_count: 0,
created_at: '2026-05-15 14:00:00',
updated_at: '2026-05-20 17:00:00',
operations: ['edit', 'enable', 'delete', 'configureAgent'],
},
];
function canUseStorage() {
return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';
}
function readStoredItems(): OfficialSiteJobTabMockItem[] {
if (!canUseStorage()) return [];
try {
const raw = window.localStorage.getItem(savedStorageKey);
return raw ? JSON.parse(raw) : [];
} catch {
return [];
}
}
function readDeletedIds(): number[] {
if (!canUseStorage()) return [];
try {
const raw = window.localStorage.getItem(deletedStorageKey);
return raw ? JSON.parse(raw) : [];
} catch {
return [];
}
}
function readStatusOverrides(): Record<number, 'enable' | 'disable'> {
if (!canUseStorage()) return {};
try {
const raw = window.localStorage.getItem(statusStorageKey);
return raw ? JSON.parse(raw) : {};
} catch {
return {};
}
}
function writeStoredItems(items: OfficialSiteJobTabMockItem[]) {
if (!canUseStorage()) return;
window.localStorage.setItem(savedStorageKey, JSON.stringify(items));
}
function writeDeletedIds(ids: number[]) {
if (!canUseStorage()) return;
window.localStorage.setItem(deletedStorageKey, JSON.stringify(ids));
}
function writeStatusOverrides(overrides: Record<number, 'enable' | 'disable'>) {
if (!canUseStorage()) return;
window.localStorage.setItem(statusStorageKey, JSON.stringify(overrides));
}
export function resetOfficialSiteJobTabMockState() {
if (!canUseStorage()) return;
window.localStorage.removeItem(savedStorageKey);
window.localStorage.removeItem(deletedStorageKey);
window.localStorage.removeItem(statusStorageKey);
}
export function getOfficialSiteJobTabSource(): OfficialSiteJobTabMockItem[] {
const deletedIds = new Set(readDeletedIds());
const storedItems = readStoredItems();
const storedById = new Map(storedItems.map((item) => [item.tab_id, item]));
const statusOverrides = readStatusOverrides();
const preservedBase = baseOfficialSiteJobTabs
.filter((item) => !deletedIds.has(item.tab_id))
.map((item) => {
const stored = storedById.get(item.tab_id);
if (stored) return stored;
const overrideStatus = statusOverrides[item.tab_id];
if (overrideStatus) {
const operations: OfficialSiteJobTabMockItem['operations'] = overrideStatus === 'enable'
? ['edit', 'disable', 'delete', 'configureAgent']
: ['edit', 'enable', 'delete', 'configureAgent'];
return { ...item, display_status: overrideStatus, operations };
}
return item;
});
const createdItems = storedItems
.filter((item) => !baseOfficialSiteJobTabs.some((base) => base.tab_id === item.tab_id))
.filter((item) => !deletedIds.has(item.tab_id));
return [...preservedBase, ...createdItems].sort((a, b) => a.tab_id - b.tab_id);
}
export const officialSiteJobTabMockFixtures: Record<string, OfficialSiteJobTabMockFixture> = {
normal: { items: baseOfficialSiteJobTabs },
empty: { items: [] },
filteredEmpty: { items: [] },
loadError: { items: [], loadError: true },
saveError: { items: baseOfficialSiteJobTabs, saveError: true },
statusBlockError: { items: baseOfficialSiteJobTabs, statusBlockError: true },
positionDuplicate: { items: baseOfficialSiteJobTabs, positionDuplicate: true },
positionNoQRCode: { items: baseOfficialSiteJobTabs, positionNoQRCode: true },
};
export function getOfficialSiteJobTabRecord(tabId?: string, source = getOfficialSiteJobTabSource()): OfficialSiteJobTabMockItem | undefined {
if (!tabId) return undefined;
return source.find((item) => String(item.tab_id) === tabId);
}
export function getPositionTagCandidates(): PositionTagCandidate[] {
const agentTags = getAgentTagSource();
const positionsWithCodes = getPositionsWithChannelCode();
const channelCodes = getChannelCodeSource();
const existingTabPositions = getOfficialSiteJobTabSource().map((tab) => tab.position_code);
return agentTags.map((tag) => {
const hasChannelCode = positionsWithCodes.includes(tag.code);
const channelCode = channelCodes.find((code) => code.position_code === tag.code);
return {
tag_id: tag.tag_id,
name: tag.name,
code: tag.code,
has_channel_code: hasChannelCode,
qrcode_id: channelCode?.code_id,
qrcode_name: channelCode?.code_name,
};
});
}
export function getPositionQRCodeDerivedInfo(positionCode: string): PositionQRCodeDerivedInfo | undefined {
const derivedInfo = getPositionDerivedInfo(positionCode);
if (!derivedInfo) return undefined;
return {
channel_code: derivedInfo.channel_code,
employee_name: derivedInfo.employee_name,
employee_role_text: derivedInfo.employee_role_text,
};
}
export function isPositionDuplicate(positionCode: string, currentTabId?: number): boolean {
const source = getOfficialSiteJobTabSource();
return source.some((tab) => tab.position_code === positionCode && tab.tab_id !== currentTabId);
}
export function getOfficialSiteJobTabListPage({
keyword = '',
displayStatus = '',
page,
pageSize,
source = getOfficialSiteJobTabSource(),
}: OfficialSiteJobTabListPageQuery): OfficialSiteJobTabListPageResult {
const normalizedKeyword = keyword.trim().toLowerCase();
const filtered = source.filter((item) => {
if (normalizedKeyword) {
const matchPosition = item.position_name.toLowerCase().includes(normalizedKeyword);
const matchQRCode = item.qrcode_name.toLowerCase().includes(normalizedKeyword);
if (!matchPosition && !matchQRCode) return false;
}
if (displayStatus && item.display_status !== displayStatus) return false;
return true;
});
const start = (page - 1) * pageSize;
return {
items: filtered.slice(start, start + pageSize),
page,
pageSize,
total: filtered.length,
};
}
export function saveOfficialSiteJobTabRecord(payload: SaveOfficialSiteJobTabPayload, scenario = 'normal'): SaveOfficialSiteJobTabResult {
const source = getOfficialSiteJobTabSource();
const current = payload.tabId ? source.find((item) => item.tab_id === payload.tabId) : undefined;
// Handle save error fixture
if (scenario === 'saveError' && !payload.tabId) {
return {
tab_id: 0,
position_code: payload.position_code ?? '',
position_name: '',
qrcode_id: 0,
qrcode_name: '',
channel_code: '',
employee_name: '',
employee_role_text: '',
tab_order: payload.tab_order,
display_status: payload.display_status,
main_title: payload.main_title ?? '',
sub_title: payload.sub_title ?? '',
agent_count: 0,
created_at: now(),
updated_at: now(),
operations: [],
blocked: true,
message: '保存失败,请重试',
};
}
// Create mode validations
if (!payload.tabId) {
// Check for duplicate position
if (isPositionDuplicate(payload.position_code ?? '')) {
return {
tab_id: 0,
position_code: payload.position_code ?? '',
position_name: '',
qrcode_id: 0,
qrcode_name: '',
channel_code: '',
employee_name: '',
employee_role_text: '',
tab_order: payload.tab_order,
display_status: payload.display_status,
main_title: payload.main_title ?? '',
sub_title: payload.sub_title ?? '',
agent_count: 0,
created_at: now(),
updated_at: now(),
operations: [],
blocked: true,
message: '该岗位已存在官网岗位展示,请编辑原配置',
};
}
// Check for position without channel code
const derivedInfo = getPositionQRCodeDerivedInfo(payload.position_code ?? '');
if (!derivedInfo) {
return {
tab_id: 0,
position_code: payload.position_code ?? '',
position_name: '',
qrcode_id: 0,
qrcode_name: '',
channel_code: '',
employee_name: '',
employee_role_text: '',
tab_order: payload.tab_order,
display_status: payload.display_status,
main_title: payload.main_title ?? '',
sub_title: payload.sub_title ?? '',
agent_count: 0,
created_at: now(),
updated_at: now(),
operations: [],
blocked: true,
message: '该岗位暂未配置渠道活码',
};
}
}
const nextId = current?.tab_id ?? Math.max(0, ...source.map((item) => item.tab_id)) + 1;
const agentTag = getAgentTagSource().find((tag) => tag.code === (current?.position_code ?? payload.position_code));
const channelCode = getChannelCodeSource().find((code) => code.code_id === (current?.qrcode_id ?? payload.qrcode_id));
const derivedInfo = payload.position_code ? getPositionQRCodeDerivedInfo(payload.position_code) : undefined;
const operations: OfficialSiteJobTabMockItem['operations'] = payload.display_status === 'enable'
? ['edit', 'disable', 'delete', 'configureAgent']
: ['edit', 'enable', 'delete', 'configureAgent'];
const nextRecord: SaveOfficialSiteJobTabResult = {
tab_id: nextId,
position_code: current?.position_code ?? payload.position_code ?? '',
position_name: current?.position_name ?? agentTag?.name ?? '',
qrcode_id: current?.qrcode_id ?? payload.qrcode_id ?? 0,
qrcode_name: current?.qrcode_name ?? channelCode?.code_name ?? '',
channel_code: current?.channel_code ?? derivedInfo?.channel_code ?? '',
employee_name: current?.employee_name ?? derivedInfo?.employee_name ?? '',
employee_role_text: current?.employee_role_text ?? derivedInfo?.employee_role_text ?? '',
tab_order: payload.tab_order,
display_status: payload.display_status,
main_title: payload.main_title ?? current?.main_title ?? '',
sub_title: payload.sub_title ?? current?.sub_title ?? '',
agent_count: current?.agent_count ?? 0,
created_at: current?.created_at ?? now(),
updated_at: now(),
operations,
};
const storedItems = readStoredItems();
writeStoredItems([...storedItems.filter((item) => item.tab_id !== nextRecord.tab_id), nextRecord as OfficialSiteJobTabMockItem]);
writeDeletedIds(readDeletedIds().filter((id) => id !== nextRecord.tab_id));
return nextRecord;
}
export function updateOfficialSiteJobTabStatus(
tabId: number,
targetStatus: 'enable' | 'disable',
scenario: 'normal' | 'statusBlockError' = 'normal',
): UpdateOfficialSiteJobTabStatusResult {
const source = getOfficialSiteJobTabSource();
const current = source.find((item) => item.tab_id === tabId);
if (!current) {
return {
tab_id: tabId,
display_status: targetStatus,
updated_at: now(),
};
}
// Business blocking: cannot disable if tab has agents configured
if (scenario === 'statusBlockError' && targetStatus === 'disable' && current.display_status === 'enable') {
return {
tab_id: tabId,
display_status: 'enable',
updated_at: current.updated_at,
blocked: true,
message: '该岗位展示配置下存在 Agent 配置,请先移除后再下架',
};
}
const newTime = now();
const overrides = readStatusOverrides();
overrides[tabId] = targetStatus;
writeStatusOverrides(overrides);
return {
tab_id: tabId,
display_status: targetStatus,
updated_at: newTime,
};
}
export function deleteOfficialSiteJobTabRecord(tabId: number): DeleteOfficialSiteJobTabResult {
const current = getOfficialSiteJobTabRecord(String(tabId));
if (!current) {
return {
tab_id: tabId,
success: false,
message: '岗位展示配置不存在',
};
}
writeDeletedIds([...new Set([...readDeletedIds(), tabId])]);
writeStoredItems(readStoredItems().filter((item) => item.tab_id !== tabId));
return {
tab_id: tabId,
success: true,
message: '已清理该岗位展示配置下的 Agent 展示配置,不影响 Agent 原始数据或渠道活码信息',
};
}
\ No newline at end of file \ No newline at end of file
import { describe, expect, it } from 'vitest';
import { getSkillDetail, getSkillList, skillListMockFixtures } from './skill-list-mock';
describe('skill list mock contract', () => {
it('provides the minimal page-facing list and detail fields', () => {
const [skill] = skillListMockFixtures.normal.items;
expect(skill).toMatchObject({
skill_code: expect.any(String),
skill_name: expect.any(String),
description: expect.any(String),
doc_markdown: expect.any(String),
});
});
it('covers the required list and detail state fixtures', () => {
expect(Object.keys(skillListMockFixtures).sort()).toEqual([
'detailError',
'detailLoading',
'empty',
'emptyMarkdown',
'error',
'loading',
'longMarkdown',
'normal',
]);
});
it('filters by keyword across list-facing fields and markdown content', () => {
expect(getSkillList({ keyword: 'markdown' }).map((item) => item.skill_code)).toContain('imagegen');
expect(getSkillList({ keyword: 'localhost' }).map((item) => item.skill_code)).toContain('browser:browser');
});
it('returns undefined for detailError and empty markdown fixtures as expected', () => {
expect(getSkillDetail('imagegen', 'detailError')).toBeUndefined();
expect(getSkillDetail('imagegen', 'emptyMarkdown')?.doc_markdown).toBe('');
});
});
export interface SkillListMockItem extends Record<string, unknown> {
skill_code: string;
skill_name: string;
description: string;
}
export interface SkillDetailMockItem extends SkillListMockItem {
doc_markdown: string;
}
export interface SkillListMockFixture {
loading?: boolean;
error?: boolean;
items: SkillListMockItem[];
}
export interface SkillDetailMockFixture extends SkillListMockFixture {
items: SkillDetailMockItem[];
total?: number;
detailLoading?: boolean;
}
export interface SkillListPageQuery {
keyword?: string;
source?: SkillDetailMockItem[];
}
const normalSkills: SkillDetailMockItem[] = [
{
skill_code: 'browser:browser',
skill_name: 'Browser automation for the Codex in-app browser.',
description: '支持本地目标、浏览器检查和使用说明预览。',
doc_markdown: [
'# Browser automation for the Codex in-app browser.',
'',
'适用于访问 [localhost](http://localhost) 与其他本地页面。',
'',
'> 推荐在改完前端后立即验证关键流程。',
'',
'- 支持打开页面',
'- 支持点击与输入',
'',
'运行命令:`npm run dev`',
'',
'```bash',
'npm run dev',
'```',
].join('\n'),
},
{
skill_code: 'imagegen',
skill_name: 'Generate or edit raster images.',
description: '适用于生成插图、贴图、透明背景素材和长 Markdown 示例文档。',
doc_markdown: [
'# imagegen',
'',
'用于创建或编辑位图素材。',
'',
'## Markdown Example',
'',
'可以配合长说明文档一起使用。',
].join('\n'),
},
];
export const skillListMockFixtures = {
normal: { items: normalSkills, total: normalSkills.length },
loading: { loading: true, items: [] },
error: { error: true, items: [] },
empty: { items: [] },
detailLoading: { items: normalSkills, detailLoading: true },
emptyMarkdown: {
items: normalSkills.map((item) => (item.skill_code === 'imagegen' ? { ...item, doc_markdown: '' } : item)),
},
detailError: { items: normalSkills },
longMarkdown: {
items: normalSkills.map((item) => (
item.skill_code === 'browser:browser'
? {
...item,
doc_markdown: [
'# Browser automation for the Codex in-app browser.',
'',
...Array.from({ length: 24 }, (_, index) => `## Section ${index + 1}\n\n这是用于验证抽屉滚动的长内容段落 ${index + 1}。`),
'',
'```ts',
"const longLine = 'This code block should stay scrollable inside the drawer content area.';",
'```',
].join('\n'),
}
: item
)),
},
} satisfies Record<string, SkillDetailMockFixture>;
export function getSkillFixtureByScenario(scenario: string): SkillDetailMockFixture {
switch (scenario) {
case 'loading':
return skillListMockFixtures.loading;
case 'error':
return skillListMockFixtures.error;
case 'empty':
return skillListMockFixtures.empty;
case 'detailLoading':
return skillListMockFixtures.detailLoading;
case 'emptyMarkdown':
return skillListMockFixtures.emptyMarkdown;
case 'detailError':
return skillListMockFixtures.detailError;
case 'longMarkdown':
return skillListMockFixtures.longMarkdown;
default:
return skillListMockFixtures.normal;
}
}
export function getSkillList({ keyword = '', source }: SkillListPageQuery) {
const normalizedKeyword = keyword.trim().toLowerCase();
const items = source ?? skillListMockFixtures.normal.items;
return items.filter((item) => {
if (!normalizedKeyword) return true;
return [item.skill_code, item.skill_name, item.description, item.doc_markdown]
.join(' ')
.toLowerCase()
.includes(normalizedKeyword);
});
}
export function getSkillDetail(skillCode: string | undefined, scenario = 'normal') {
if (!skillCode) return undefined;
if (scenario === 'detailError' || scenario === 'detailLoading') return undefined;
return getSkillFixtureByScenario(scenario).items.find((item) => item.skill_code === skillCode);
}
...@@ -71,12 +71,16 @@ function useCloseDatePopupOnOutsideClick(open: boolean, setOpen: (open: boolean) ...@@ -71,12 +71,16 @@ function useCloseDatePopupOnOutsideClick(open: boolean, setOpen: (open: boolean)
useEffect(() => { useEffect(() => {
if (!open) return undefined; if (!open) return undefined;
const closeOnOutsideClick = (event: PointerEvent) => { const closeOnOutsideClick = (event: MouseEvent | PointerEvent) => {
if (!rootRef.current?.contains(event.target as Node)) setOpen(false); if (!rootRef.current?.contains(event.target as Node)) {
// 延迟关闭,确保 click 事件先触发完成(mousedown 在 click 之前)
setTimeout(() => setOpen(false), 0);
}
}; };
document.addEventListener('pointerdown', closeOnOutsideClick); // 使用 mousedown 而不是 pointerdown,避免与 click 事件的竞态
return () => document.removeEventListener('pointerdown', closeOnOutsideClick); document.addEventListener('mousedown', closeOnOutsideClick);
return () => document.removeEventListener('mousedown', closeOnOutsideClick);
}, [open, setOpen]); }, [open, setOpen]);
return rootRef; return rootRef;
......
...@@ -31,7 +31,19 @@ export function Tag({ children, closable, onClose, status = 'default' }: TagProp ...@@ -31,7 +31,19 @@ export function Tag({ children, closable, onClose, status = 'default' }: TagProp
return ( return (
<span className={cx(styles.tag, status !== 'default' && styles[status])}> <span className={cx(styles.tag, status !== 'default' && styles[status])}>
{children} {children}
{closable ? <button className={styles.plainButton} type="button" aria-label={`关闭${children}`} onClick={onClose}>×</button> : null} {closable ? (
<button
className={styles.tagCloseButton}
type="button"
aria-label={`关闭${children}`}
onClick={(event) => {
event.stopPropagation();
onClose?.();
}}
>
×
</button>
) : null}
</span> </span>
); );
} }
......
...@@ -196,12 +196,12 @@ export function Drawer({ children, footer, onClose, open, placement = 'right', t ...@@ -196,12 +196,12 @@ export function Drawer({ children, footer, onClose, open, placement = 'right', t
return ( return (
<div className={styles.drawerOverlay} data-testid="drawer-overlay"> <div className={styles.drawerOverlay} data-testid="drawer-overlay">
<aside className={styles.drawer} style={drawerStyle} role="dialog" aria-modal="true" aria-label={String(title)}> <aside className={styles.drawer} style={drawerStyle} role="dialog" aria-modal="true" aria-label={String(title)}>
<header className={cx(styles.section, styles.between)}> <header className={cx(styles.drawerHeader, styles.between)}>
<strong>{title}</strong> <strong>{title}</strong>
<button className={styles.plainButton} type="button" aria-label={`关闭${title}`} onClick={onClose}>×</button> <button className={styles.plainButton} type="button" aria-label={`关闭${title}`} onClick={onClose}>×</button>
</header> </header>
<div className={styles.section}>{children}</div> <div className={styles.drawerBody}>{children}</div>
{footer ? <footer className={styles.section}>{footer}</footer> : null} {footer ? <footer className={styles.drawerFooter}>{footer}</footer> : null}
</aside> </aside>
</div> </div>
); );
......
...@@ -4,6 +4,34 @@ import type { FormEvent, ReactElement, ReactNode } from 'react'; ...@@ -4,6 +4,34 @@ import type { FormEvent, ReactElement, ReactNode } from 'react';
import styles from './Shared.module.css'; import styles from './Shared.module.css';
import { cx } from './utils'; import { cx } from './utils';
/** 判断子元素是否为简单输入控件(应建立 label 关联) */
const isSimpleInputControl = (child: ReactNode): boolean => {
if (!isValidElement(child)) return false;
// Input、Textarea、Select 等简单输入控件应建立 label 关联
// 上传组件(含隐藏 file input)不建立关联,避免误触发
const type = child.type;
if (typeof type === 'string') {
return type === 'input' || type === 'textarea' || type === 'select';
}
// 对于自定义组件,检查 displayName 或组件名
const displayName = (type as { displayName?: string }).displayName ?? '';
const name = typeof type === 'function' ? type.name : '';
const componentName = displayName || name;
// 简单输入控件:Input、Textarea、Select、DatePicker
// 复杂控件:MediaWall、UploadDragger、Upload、Switch(不含隐藏 file input,但已有语义)
const simpleControls = ['Input', 'Textarea', 'Select', 'DatePicker'];
return simpleControls.some((ctrl) => componentName.includes(ctrl));
};
/** 生成唯一字段 id */
const useFieldId = (name: string | undefined, testIdLabel: string): string => {
const idRef = useRef<string | undefined>(undefined);
if (!idRef.current) {
idRef.current = name ?? `field-${testIdLabel}-${Math.random().toString(36).slice(2, 8)}`;
}
return idRef.current;
};
export type FormValues = Record<string, unknown>; export type FormValues = Record<string, unknown>;
export interface FormRule { export interface FormRule {
...@@ -114,6 +142,8 @@ export function FormItem({ children, error, help, label, layout = 'vertical', na ...@@ -114,6 +142,8 @@ export function FormItem({ children, error, help, label, layout = 'vertical', na
const fieldError = (name ? form?.errors[name] : undefined) ?? error; const fieldError = (name ? form?.errors[name] : undefined) ?? error;
const isRequired = required || fieldRules.some((rule) => rule.required); const isRequired = required || fieldRules.some((rule) => rule.required);
const testIdLabel = labelToTestId(label); const testIdLabel = labelToTestId(label);
const fieldId = useFieldId(name, testIdLabel);
const isSimpleInput = isSimpleInputControl(children);
useEffect(() => { useEffect(() => {
if (!form || !name) { if (!form || !name) {
...@@ -125,6 +155,7 @@ export function FormItem({ children, error, help, label, layout = 'vertical', na ...@@ -125,6 +155,7 @@ export function FormItem({ children, error, help, label, layout = 'vertical', na
const control = name && form && isValidElement(children) const control = name && form && isValidElement(children)
? cloneElement(children as ReactElement<Record<string, unknown>>, { ? cloneElement(children as ReactElement<Record<string, unknown>>, {
'aria-invalid': fieldError ? true : undefined, 'aria-invalid': fieldError ? true : undefined,
id: isSimpleInput ? fieldId : undefined,
onChange: (nextValue: unknown) => { onChange: (nextValue: unknown) => {
const originalOnChange = (children as ReactElement<{ onChange?: (value: unknown) => void }>).props.onChange; const originalOnChange = (children as ReactElement<{ onChange?: (value: unknown) => void }>).props.onChange;
originalOnChange?.(nextValue); originalOnChange?.(nextValue);
...@@ -135,10 +166,12 @@ export function FormItem({ children, error, help, label, layout = 'vertical', na ...@@ -135,10 +166,12 @@ export function FormItem({ children, error, help, label, layout = 'vertical', na
status: typeof children.type === 'string' ? undefined : fieldError ? 'error' : undefined, status: typeof children.type === 'string' ? undefined : fieldError ? 'error' : undefined,
value: form.values[name] ?? '', value: form.values[name] ?? '',
}) })
: children; : isSimpleInput && isValidElement(children)
? cloneElement(children as ReactElement<Record<string, unknown>>, { id: fieldId })
: children;
return ( return (
<label <div
className={cx( className={cx(
styles.formItem, styles.formItem,
layout === 'horizontal' ? styles.formItemHorizontal : styles.formItemVertical, layout === 'horizontal' ? styles.formItemHorizontal : styles.formItemVertical,
...@@ -146,10 +179,10 @@ export function FormItem({ children, error, help, label, layout = 'vertical', na ...@@ -146,10 +179,10 @@ export function FormItem({ children, error, help, label, layout = 'vertical', na
)} )}
data-testid={`form-item-${testIdLabel}`} data-testid={`form-item-${testIdLabel}`}
> >
<span className={styles.formLabel} data-testid={`form-label-${testIdLabel}`}> <label className={styles.formLabel} data-testid={`form-label-${testIdLabel}`} htmlFor={isSimpleInput ? fieldId : undefined}>
{isRequired ? <span className={styles.formRequired}>*</span> : null} {isRequired ? <span className={styles.formRequired}>*</span> : null}
<span>{label}</span> <span>{label}</span>
</span> </label>
<span className={styles.formControl}> <span className={styles.formControl}>
<span className={styles.formMain} data-testid={`form-main-${testIdLabel}`}> <span className={styles.formMain} data-testid={`form-main-${testIdLabel}`}>
{control} {control}
...@@ -160,6 +193,6 @@ export function FormItem({ children, error, help, label, layout = 'vertical', na ...@@ -160,6 +193,6 @@ export function FormItem({ children, error, help, label, layout = 'vertical', na
{fieldError ? <span role="alert" aria-label={String(fieldError)} className={styles.formErrorText}>{fieldError}</span> : null} {fieldError ? <span role="alert" aria-label={String(fieldError)} className={styles.formErrorText}>{fieldError}</span> : null}
</span> </span>
</span> </span>
</label> </div>
); );
} }
import { useState } from 'react'; import { useState, type ReactNode } from 'react';
import type { ButtonHTMLAttributes, ReactNode } from 'react'; import { Select as TDesignSelect } from 'tdesign-react';
import type {
import styles from './Shared.module.css'; SelectOption as TDesignSelectOption,
import { Icon } from './Icon'; SelectValue,
import { cx, notifyPopupOpen, useExclusivePopup } from './utils'; } from 'tdesign-react/es/select/type';
const selectPopupOpenEvent = 'gl-select-popup-open';
export interface SelectOption { export interface SelectOption {
label: ReactNode; label: ReactNode;
...@@ -13,70 +11,95 @@ export interface SelectOption { ...@@ -13,70 +11,95 @@ export interface SelectOption {
disabled?: boolean; disabled?: boolean;
} }
export interface SelectProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onChange' | 'value'> { interface SelectBaseProps {
/** 可选项列表;禁用项保留展示但不会触发选择。 */
options: SelectOption[]; options: SelectOption[];
value?: string;
placeholder?: string; placeholder?: string;
allowClear?: boolean; allowClear?: boolean;
disabled?: boolean;
className?: string;
'aria-label'?: string;
}
export interface SelectSingleProps extends SelectBaseProps {
multiple?: false;
value?: string;
onChange?: (value: string | undefined, option: SelectOption | undefined) => void; onChange?: (value: string | undefined, option: SelectOption | undefined) => void;
} }
export interface SelectMultipleProps extends SelectBaseProps {
multiple: true;
value?: string[];
onChange?: (value: string[], option: SelectOption | undefined) => void;
}
export type SelectProps = SelectSingleProps | SelectMultipleProps;
function toTDesignOptions(options: SelectOption[]): TDesignSelectOption[] {
return options.map((option) => ({
label: option.label,
value: option.value,
disabled: option.disabled,
}));
}
function normalizeSingleValue(value: SelectValue): string | undefined {
if (Array.isArray(value)) return typeof value[0] === 'string' ? value[0] : undefined;
return typeof value === 'string' ? value : undefined;
}
function normalizeMultipleValue(value: SelectValue): string[] {
if (!Array.isArray(value)) return typeof value === 'string' ? [value] : [];
return value.filter((item): item is string => typeof item === 'string');
}
export function Select(props: SelectProps) { export function Select(props: SelectProps) {
const { allowClear, options, placeholder = '请选择', value, onChange, ...buttonProps } = props; const {
const [open, setOpen] = useState(false); allowClear,
const popupId = useExclusivePopup(selectPopupOpenEvent, setOpen); className,
disabled,
options,
placeholder = '请选择',
multiple,
value,
onChange,
'aria-label': ariaLabel,
} = props;
const isControlled = Object.prototype.hasOwnProperty.call(props, 'value'); const isControlled = Object.prototype.hasOwnProperty.call(props, 'value');
const [innerValue, setInnerValue] = useState<string | undefined>(undefined); const [innerValue, setInnerValue] = useState<string | string[] | undefined>(multiple ? [] : undefined);
const currentValue = isControlled ? value : innerValue; const currentValue = isControlled ? value : innerValue;
const currentOption = options.find((option) => option.value === currentValue);
const label = buttonProps['aria-label'] ?? '选择框';
const commit = (nextValue: string | undefined, option: SelectOption | undefined) => { return (
if (!isControlled) { <TDesignSelect
setInnerValue(nextValue); aria-label={ariaLabel}
} className={className}
onChange?.(nextValue, option); clearable={allowClear}
setOpen(false); disabled={disabled}
}; inputProps={{
'aria-disabled': disabled,
'aria-label': ariaLabel,
role: 'combobox',
} as never}
multiple={multiple}
options={toTDesignOptions(options)}
placeholder={placeholder}
value={currentValue}
onChange={(nextValue, context) => {
const changedOption = context.option as { value?: unknown } | undefined;
const option = context.option
? options.find((item) => item.value === String(changedOption?.value))
: undefined;
const toggleOpen = () => { if (multiple) {
setOpen((nextOpen) => { const normalizedValue = normalizeMultipleValue(nextValue);
if (!nextOpen) notifyPopupOpen(selectPopupOpenEvent, popupId); if (!isControlled) setInnerValue(normalizedValue);
return !nextOpen; (onChange as SelectMultipleProps['onChange'] | undefined)?.(normalizedValue, option);
}); return;
}; }
return ( const normalizedValue = normalizeSingleValue(nextValue);
<span className={styles.selectWrapper}> if (!isControlled) setInnerValue(normalizedValue);
<button {...buttonProps} className={cx(styles.control, styles.fieldButton)} role="combobox" aria-expanded={open} type="button" onClick={toggleOpen}> (onChange as SelectSingleProps['onChange'] | undefined)?.(normalizedValue, option);
<span>{currentOption?.label ?? placeholder}</span> }}
<Icon className={styles.fieldIcon} name={open ? 'chevron-down' : 'chevron-right'} /> />
</button>
{allowClear && currentValue ? (
<button className={styles.plainButton} type="button" aria-label={`清空${label}`} onClick={() => commit(undefined, undefined)}>
清空
</button>
) : null}
{open ? (
<div className={cx(styles.popup, styles.selectPopup)} role="listbox">
{options.length === 0 ? <div className={styles.muted}>暂无数据</div> : null}
{options.map((option) => (
<div
key={option.value}
className={cx(styles.option, option.disabled && styles.disabled)}
role="option"
aria-disabled={option.disabled || undefined}
aria-selected={option.value === currentValue}
onClick={() => {
if (!option.disabled) commit(option.value, option);
}}
>
{option.label}
</div>
))}
</div>
) : null}
</span>
); );
} }
...@@ -35,18 +35,49 @@ ...@@ -35,18 +35,49 @@
color: color-mix(in srgb, var(--gl-color-text-secondary) 68%, #fff); color: color-mix(in srgb, var(--gl-color-text-secondary) 68%, #fff);
} }
.selectValueSummary {
display: inline-flex;
min-width: 0;
align-items: center;
gap: var(--gl-spacing-xs);
}
.selectValueText {
overflow: hidden;
min-width: 0;
text-overflow: ellipsis;
white-space: nowrap;
}
.selectValueCount {
flex: 0 0 auto;
color: var(--gl-color-text-secondary);
}
.selectTagTrigger {
align-items: center;
}
.selectTagList {
display: inline-flex;
min-width: 0;
flex: 1 1 auto;
flex-wrap: wrap;
align-items: center;
gap: var(--gl-spacing-xs);
overflow: hidden;
}
.selectWrapper { .selectWrapper {
position: relative; position: relative;
display: inline-block; display: block;
width: 100%; width: 100%;
vertical-align: top;
} }
.selectPopup { .selectPopup {
position: absolute; position: absolute;
top: calc(100% + var(--gl-spacing-xs)); top: calc(100% + var(--gl-spacing-xs));
left: 0; left: 0;
width: 100%;
box-sizing: border-box; box-sizing: border-box;
margin-top: 0; margin-top: 0;
} }
...@@ -376,6 +407,12 @@ ...@@ -376,6 +407,12 @@
min-height: 34px; min-height: 34px;
} }
/* Parent activation: weaker visual indication than child selection */
.navigationItem[data-active-parent='true'] {
background: color-mix(in srgb, var(--gl-color-primary) 6%, #fff);
color: var(--gl-color-primary);
}
.form { .form {
display: grid; display: grid;
width: 100%; width: 100%;
...@@ -482,7 +519,39 @@ ...@@ -482,7 +519,39 @@
gap: var(--gl-spacing-md); gap: var(--gl-spacing-md);
} }
.tag, .tag {
display: inline-flex;
align-items: center;
gap: var(--gl-spacing-xs);
min-height: 24px;
padding: 0 var(--gl-spacing-sm);
border-radius: var(--gl-radius-sm);
background: var(--gl-color-fill-hover);
color: var(--gl-color-text-primary);
font-size: var(--gl-font-size-xs);
}
.tagCloseButton {
display: inline-flex;
align-items: center;
justify-content: center;
width: 14px;
height: 14px;
border: 0;
border-radius: 50%;
background: transparent;
color: var(--gl-color-text-secondary);
cursor: pointer;
font-size: 10px;
line-height: 1;
margin-left: calc(var(--gl-spacing-xs) * -1);
}
.tagCloseButton:hover {
background: var(--gl-color-fill-hover);
color: var(--gl-color-text-primary);
}
.badge, .badge,
.avatar, .avatar,
.statusDot { .statusDot {
...@@ -573,16 +642,6 @@ ...@@ -573,16 +642,6 @@
justify-items: end; justify-items: end;
} }
.tag {
min-height: 24px;
gap: var(--gl-spacing-xs);
padding: 0 var(--gl-spacing-sm);
border-radius: var(--gl-radius-sm);
background: var(--gl-color-fill-hover);
color: var(--gl-color-text-primary);
font-size: var(--gl-font-size-xs);
}
.success { .success {
background: color-mix(in srgb, var(--gl-color-success, #039855) 12%, #fff); background: color-mix(in srgb, var(--gl-color-success, #039855) 12%, #fff);
color: var(--gl-color-success, #039855); color: var(--gl-color-success, #039855);
...@@ -647,6 +706,8 @@ ...@@ -647,6 +706,8 @@
right: 0; right: 0;
bottom: 0; bottom: 0;
z-index: 101; z-index: 101;
display: flex;
flex-direction: column;
max-width: 92vw; max-width: 92vw;
background: var(--gl-color-bg-container); background: var(--gl-color-bg-container);
box-shadow: -16px 0 40px rgb(16 24 40 / 18%); box-shadow: -16px 0 40px rgb(16 24 40 / 18%);
...@@ -657,6 +718,24 @@ ...@@ -657,6 +718,24 @@
border-bottom: 1px solid var(--gl-color-border-secondary); border-bottom: 1px solid var(--gl-color-border-secondary);
} }
.drawerHeader {
flex: 0 0 auto;
padding: var(--gl-spacing-lg);
border-bottom: 1px solid var(--gl-color-border-secondary);
}
.drawerBody {
flex: 1 1 auto;
padding: var(--gl-spacing-lg);
overflow: auto;
}
.drawerFooter {
flex: 0 0 auto;
padding: var(--gl-spacing-lg);
border-top: 1px solid var(--gl-color-border-secondary);
}
.tabs { .tabs {
display: grid; display: grid;
gap: var(--gl-spacing-md); gap: var(--gl-spacing-md);
...@@ -745,3 +824,19 @@ ...@@ -745,3 +824,19 @@
background-position: 0 50%; background-position: 0 50%;
} }
} }
.selectClearButton {
flex: 0 0 auto;
border: 0;
background: transparent;
color: var(--gl-color-text-secondary);
cursor: pointer;
font: inherit;
font-size: var(--gl-font-size-sm);
padding: 0 var(--gl-spacing-xs);
margin-left: var(--gl-spacing-xs);
}
.selectClearButton:hover {
color: var(--gl-color-text-primary);
}
...@@ -32,16 +32,13 @@ ...@@ -32,16 +32,13 @@
background: color-mix(in srgb, var(--gl-color-primary) 4%, #fff); background: color-mix(in srgb, var(--gl-color-primary) 4%, #fff);
} }
.dragger:focus-visible, .dragger:focus-visible {
.mediaButton:focus-visible,
.mediaUpload:focus-visible,
.iconButton:focus-visible {
outline: 2px solid color-mix(in srgb, var(--gl-color-primary) 24%, transparent); outline: 2px solid color-mix(in srgb, var(--gl-color-primary) 24%, transparent);
outline-offset: 2px; outline-offset: 2px;
} }
.dragger:disabled, .dragger:disabled,
.mediaUpload:disabled { .draggerDisabled {
cursor: not-allowed; cursor: not-allowed;
opacity: 0.55; opacity: 0.55;
} }
...@@ -71,234 +68,7 @@ ...@@ -71,234 +68,7 @@
line-height: var(--gl-line-height-sm); line-height: var(--gl-line-height-sm);
} }
.input {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.fileList {
display: grid;
gap: var(--gl-spacing-sm);
padding: 0;
margin: 0;
list-style: none;
}
.fileItem {
display: grid;
min-height: 60px;
box-sizing: border-box;
grid-template-columns: minmax(0, 1fr) auto;
gap: var(--gl-spacing-md);
align-items: center;
padding: var(--gl-spacing-sm) var(--gl-spacing-md);
border: 1px solid var(--gl-color-border-primary);
border-radius: 10px;
background: var(--gl-color-bg-container);
}
.fileItemError {
border-color: color-mix(in srgb, var(--gl-color-danger, #d92d20) 38%, var(--gl-color-border-primary));
}
.fileMain {
display: flex;
min-width: 0;
align-items: center;
gap: var(--gl-spacing-md);
}
.fileIcon {
display: inline-flex;
width: 32px;
height: 32px;
flex: 0 0 32px;
align-items: center;
justify-content: center;
border-radius: var(--gl-radius-md);
background: color-mix(in srgb, var(--gl-color-primary) 8%, #fff);
color: var(--gl-color-primary);
}
.fileText {
display: grid;
min-width: 0;
gap: 2px;
}
.fileName {
overflow: hidden;
color: var(--gl-color-text-primary);
font-size: var(--gl-font-size-sm);
font-weight: 600;
line-height: var(--gl-line-height-md);
text-overflow: ellipsis;
white-space: nowrap;
}
.fileMeta,
.mediaHelper {
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-xs);
line-height: var(--gl-line-height-sm);
}
.fileError {
color: var(--gl-color-danger, #d92d20);
font-size: var(--gl-font-size-xs);
line-height: var(--gl-line-height-sm);
}
.fileActions {
display: inline-flex;
align-items: center;
gap: var(--gl-spacing-xs);
}
.iconButton {
display: inline-flex;
width: 28px;
height: 28px;
align-items: center;
justify-content: center;
border: 0;
border-radius: var(--gl-radius-sm);
background: transparent;
color: var(--gl-color-text-secondary);
cursor: pointer;
}
.iconButton:hover {
background: var(--gl-color-fill-hover);
color: var(--gl-color-primary);
}
.iconButton[aria-label^='删除']:hover {
color: var(--gl-color-danger, #d92d20);
}
.progressTrack {
grid-column: 1 / -1;
height: 4px;
overflow: hidden;
border-radius: 999px;
background: var(--gl-color-border-secondary);
}
.progressFill {
display: block;
height: 100%;
border-radius: inherit;
background: var(--gl-color-primary);
}
.mediaRoot { .mediaRoot {
display: grid; display: grid;
gap: var(--gl-spacing-sm); gap: var(--gl-spacing-sm);
} }
.mediaGrid {
display: flex;
flex-wrap: wrap;
gap: var(--gl-spacing-md);
padding: 0;
margin: 0;
list-style: none;
}
.mediaCell {
width: 96px;
height: 96px;
}
.mediaButton,
.mediaUpload {
position: relative;
display: flex;
width: 96px;
height: 96px;
box-sizing: border-box;
align-items: center;
justify-content: center;
overflow: hidden;
border-radius: 8px;
cursor: pointer;
}
.mediaButton {
padding: 0;
border: 1px solid var(--gl-color-border-secondary);
background: var(--gl-color-bg-container);
}
.mediaThumb {
width: 100%;
height: 100%;
object-fit: cover;
}
.playBadge {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
background: rgb(0 0 0 / 22%);
}
.playBadge svg {
width: 34px;
height: 34px;
padding: 7px;
border-radius: 999px;
background: rgb(0 0 0 / 38%);
fill: currentColor;
}
.mediaUpload {
flex-direction: column;
gap: var(--gl-spacing-xs);
border: 1px dashed var(--gl-color-border-primary);
background: var(--gl-color-bg-container);
color: var(--gl-color-text-secondary);
font-size: var(--gl-font-size-xs);
font-weight: 600;
}
.mediaUpload:hover:not(:disabled) {
border-color: var(--gl-color-primary);
color: var(--gl-color-primary);
background: color-mix(in srgb, var(--gl-color-primary) 4%, #fff);
}
.mediaPlus {
display: inline-flex;
width: 32px;
height: 32px;
align-items: center;
justify-content: center;
border-radius: 999px;
background: var(--gl-color-fill-hover);
}
.mediaHelper {
margin: 0;
}
.srOnly {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
\ No newline at end of file \ No newline at end of file
import { useRef, useState, type CSSProperties } from 'react'; import { Upload } from 'tdesign-react';
import type { UploadFile as TDesignUploadFile, TdUploadProps } from 'tdesign-react/es/upload/type';
type UploadProps = TdUploadProps;
import { Icon } from './Icon';
import styles from './Upload.module.css'; import styles from './Upload.module.css';
import { cx } from './utils'; import { cx } from './utils';
export type UploadFileStatus = 'uploading' | 'done' | 'error'; export type UploadFileStatus = 'success' | 'progress' | 'fail' | 'waiting';
export interface UploadFileItem { export interface UploadFileItem {
id: string; id: string;
...@@ -14,10 +16,11 @@ export interface UploadFileItem { ...@@ -14,10 +16,11 @@ export interface UploadFileItem {
progress?: number; progress?: number;
errorMessage?: string; errorMessage?: string;
previewable?: boolean; previewable?: boolean;
url?: string;
} }
export interface UploadDraggerProps { export interface UploadDraggerProps {
/** UploadDragger 只负责 UI 状态和操作意图,不执行真实校验、分片续传或接口上传。 */ /** UploadDragger 使用 TDesign Upload 的 file-flow 主题,提供文件列表、进度、预览等内置功能 */
files: UploadFileItem[]; files: UploadFileItem[];
title?: string; title?: string;
helperText?: string; helperText?: string;
...@@ -25,7 +28,7 @@ export interface UploadDraggerProps { ...@@ -25,7 +28,7 @@ export interface UploadDraggerProps {
multiple?: boolean; multiple?: boolean;
disabled?: boolean; disabled?: boolean;
className?: string; className?: string;
style?: CSSProperties; style?: React.CSSProperties;
onSelectFiles?: (files: File[]) => void; onSelectFiles?: (files: File[]) => void;
onPreview?: (id: string) => void; onPreview?: (id: string) => void;
onDownload?: (id: string) => void; onDownload?: (id: string) => void;
...@@ -34,59 +37,31 @@ export interface UploadDraggerProps { ...@@ -34,59 +37,31 @@ export interface UploadDraggerProps {
onCancel?: (id: string) => void; onCancel?: (id: string) => void;
} }
function formatSize(size: number) { /** 将 UploadFileItem 转换为 TDesign UploadFile */
return `${(size / 1024 / 1024).toFixed(2)} MB`; function toTDesignFile(item: UploadFileItem): TDesignUploadFile {
} return {
uid: item.id,
function clampProgress(progress = 0) { name: item.name,
return Math.min(100, Math.max(0, Math.round(progress))); size: item.size,
} status: item.status,
percent: item.progress,
function IconButton({ label, name, onClick }: { label: string; name: Parameters<typeof Icon>[0]['name']; onClick?: () => void }) { response: item.errorMessage ? { error: item.errorMessage } : undefined,
if (!onClick) return null; url: item.url,
};
return (
<button className={styles.iconButton} type="button" aria-label={label} onClick={onClick}>
<Icon name={name} size={16} />
</button>
);
} }
function FileActions({ /** 将 TDesign UploadFile 转换为 UploadFileItem */
file, function fromTDesignFile(file: TDesignUploadFile): UploadFileItem {
onCancel, return {
onDownload, id: file.uid || String(file.name),
onPreview, name: file.name || '',
onRemove, size: file.size || 0,
onRetry, status: (file.status as UploadFileStatus) || 'waiting',
}: { progress: file.percent,
file: UploadFileItem; errorMessage: file.response?.error,
onCancel?: (id: string) => void; url: file.url,
onDownload?: (id: string) => void; previewable: !!file.url,
onPreview?: (id: string) => void; };
onRemove?: (id: string) => void;
onRetry?: (id: string) => void;
}) {
if (file.status === 'uploading') {
return <IconButton label={`取消 ${file.name}`} name="close-circle" onClick={onCancel ? () => onCancel(file.id) : undefined} />;
}
if (file.status === 'error') {
return (
<>
<IconButton label={`重试 ${file.name}`} name="refresh" onClick={onRetry ? () => onRetry(file.id) : undefined} />
<IconButton label={`删除 ${file.name}`} name="trash" onClick={onRemove ? () => onRemove(file.id) : undefined} />
</>
);
}
return (
<>
{file.previewable ? <IconButton label={`预览 ${file.name}`} name="eye" onClick={onPreview ? () => onPreview(file.id) : undefined} /> : null}
<IconButton label={`下载 ${file.name}`} name="download" onClick={onDownload ? () => onDownload(file.id) : undefined} />
<IconButton label={`删除 ${file.name}`} name="trash" onClick={onRemove ? () => onRemove(file.id) : undefined} />
</>
);
} }
export function UploadDragger({ export function UploadDragger({
...@@ -105,98 +80,63 @@ export function UploadDragger({ ...@@ -105,98 +80,63 @@ export function UploadDragger({
style, style,
title = '点击或拖拽文件到此上传', title = '点击或拖拽文件到此上传',
}: UploadDraggerProps) { }: UploadDraggerProps) {
const inputRef = useRef<HTMLInputElement>(null); const tdesignFiles = files.map(toTDesignFile);
const dragDepthRef = useRef(0);
const [dragActive, setDragActive] = useState(false); const handleChange: UploadProps['onChange'] = (value, context) => {
const { trigger, file, files: changedFiles } = context;
if (trigger === 'add' && file?.raw) {
onSelectFiles?.([file.raw]);
} else if (trigger === 'remove' && file) {
onRemove?.(fromTDesignFile(file).id);
} else if (trigger === 'abort' && file) {
onCancel?.(fromTDesignFile(file).id);
} else if (trigger === 'progress-fail' && file) {
onRetry?.(fromTDesignFile(file).id);
}
};
const emitFiles = (selectedFiles: FileList | File[]) => { const handlePreview: UploadProps['onPreview'] = ({ file }) => {
const nextFiles = Array.from(selectedFiles); const item = fromTDesignFile(file);
if (!disabled && nextFiles.length > 0) onSelectFiles?.(nextFiles); if (item.previewable) {
onPreview?.(item.id);
}
}; };
const resetDragState = () => { const handleRemove: UploadProps['onRemove'] = ({ file, e }) => {
dragDepthRef.current = 0; e.stopPropagation();
setDragActive(false); if (!file) return;
const item = fromTDesignFile(file);
onRemove?.(item.id);
}; };
return ( return (
<div className={cx(styles.root, className)} style={style}> <div className={cx(styles.root, className)} style={style}>
<button <Upload
className={cx(styles.dragger, dragActive && styles.draggerActive)}
data-testid="upload-dragger"
type="button"
disabled={disabled}
onClick={() => inputRef.current?.click()}
onDragEnter={(event) => {
event.preventDefault();
dragDepthRef.current += 1;
if (!disabled) setDragActive(true);
}}
onDragLeave={(event) => {
event.preventDefault();
dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
if (dragDepthRef.current === 0) setDragActive(false);
}}
onDragOver={(event) => {
event.preventDefault();
if (!disabled) event.dataTransfer.dropEffect = 'copy';
}}
onDrop={(event) => {
event.preventDefault();
resetDragState();
emitFiles(event.dataTransfer.files);
}}
>
<span className={styles.uploadIcon} aria-hidden="true">
<Icon name="upload" size={32} />
</span>
<span className={styles.draggerTitle}>{title}</span>
<span className={styles.draggerHelper}>{helperText}</span>
</button>
<input
ref={inputRef}
aria-label="选择上传文件"
className={styles.input}
type="file"
accept={accept} accept={accept}
multiple={multiple} autoUpload={false}
disabled={disabled} disabled={disabled}
onChange={(event) => { draggable
if (event.target.files) emitFiles(event.target.files); files={tdesignFiles}
event.currentTarget.value = ''; multiple={multiple}
}} theme="file-flow"
tips={helperText}
onChange={handleChange}
onPreview={handlePreview}
onRemove={handleRemove}
trigger={() => (
<div className={cx(styles.dragger, disabled && styles.draggerDisabled)} data-testid="upload-dragger">
<span className={styles.uploadIcon} aria-hidden="true">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="17 8 12 3 7 8" />
<line x1="12" y1="3" x2="12" y2="15" />
</svg>
</span>
<span className={styles.draggerTitle}>{title}</span>
<span className={styles.draggerHelper}>{helperText}</span>
</div>
)}
/> />
{files.length > 0 ? (
<ul className={styles.fileList} aria-label="上传文件列表">
{files.map((file) => {
const progress = clampProgress(file.progress);
const statusText = file.status === 'done' ? '已完成' : file.status === 'error' ? '上传失败' : `上传中 ${progress}%`;
return (
<li key={file.id} className={cx(styles.fileItem, file.status === 'error' && styles.fileItemError)}>
<div className={styles.fileMain}>
<span className={styles.fileIcon} aria-hidden="true">
<Icon name="file" size={18} />
</span>
<div className={styles.fileText}>
<span className={styles.fileName}>{file.name}</span>
<span className={styles.fileMeta}>{formatSize(file.size)} · {statusText}</span>
{file.status === 'error' && file.errorMessage ? <span className={styles.fileError}>{file.errorMessage}</span> : null}
</div>
</div>
<div className={styles.fileActions}>
<FileActions file={file} onCancel={onCancel} onDownload={onDownload} onPreview={onPreview} onRemove={onRemove} onRetry={onRetry} />
</div>
{file.status === 'uploading' ? (
<div className={styles.progressTrack} role="progressbar" aria-label={`${file.name} 上传进度`} aria-valuemin={0} aria-valuemax={100} aria-valuenow={progress}>
<span className={styles.progressFill} style={{ width: `${progress}%` }} />
</div>
) : null}
</li>
);
})}
</ul>
) : null}
</div> </div>
); );
} }
...@@ -209,15 +149,19 @@ export interface MediaWallItem { ...@@ -209,15 +149,19 @@ export interface MediaWallItem {
} }
export interface MediaWallProps { export interface MediaWallProps {
/** MediaWall 展示素材缩略图和预览意图;图片放大、视频播放和真实上传由业务侧组合实现。 */ /** MediaWall 使用 TDesign Upload 的 image 主题,内置图片预览功能 */
items: MediaWallItem[]; items: MediaWallItem[];
helperText?: string; helperText?: string;
accept?: string; accept?: string;
multiple?: boolean; multiple?: boolean;
disabled?: boolean; disabled?: boolean;
/** 最大上传数量,达到上限时隐藏上传按钮 */
maxCount?: number;
className?: string; className?: string;
style?: CSSProperties; style?: React.CSSProperties;
/** 预览回调,用于视频播放或自定义预览逻辑。图片预览默认使用 TDesign 内置 ImageViewer */
onPreview?: (item: MediaWallItem) => void; onPreview?: (item: MediaWallItem) => void;
onRemove?: (item: MediaWallItem) => void;
onSelectFiles?: (files: File[]) => void; onSelectFiles?: (files: File[]) => void;
} }
...@@ -227,52 +171,76 @@ export function MediaWall({ ...@@ -227,52 +171,76 @@ export function MediaWall({
disabled = false, disabled = false,
helperText, helperText,
items, items,
maxCount,
multiple = true, multiple = true,
onPreview, onPreview,
onRemove,
onSelectFiles, onSelectFiles,
style, style,
}: MediaWallProps) { }: MediaWallProps) {
const inputRef = useRef<HTMLInputElement>(null); const tdesignFiles: TDesignUploadFile[] = items.map((item) => ({
uid: item.id,
name: item.alt,
url: item.src,
status: 'success',
type: item.type === 'image' ? 'image' : 'video',
}));
// 判断是否需要自定义预览处理(有视频或有自定义 onPreview)
const hasVideo = items.some((item) => item.type === 'video');
const needCustomPreview = hasVideo || !!onPreview;
const handleChange: UploadProps['onChange'] = (value, context) => {
const { trigger, file } = context;
if (trigger === 'add' && file?.raw) {
onSelectFiles?.([file.raw]);
}
};
const handlePreview: UploadProps['onPreview'] = ({ file, e }) => {
e.stopPropagation();
if (!file) return;
const item: MediaWallItem = {
id: file.uid || String(file.name),
type: file.type === 'video' ? 'video' : 'image',
src: file.url || '',
alt: file.name || '',
};
onPreview?.(item);
};
const handleRemove: UploadProps['onRemove'] = ({ file, e }) => {
e.stopPropagation();
if (!file) return;
const item: MediaWallItem = {
id: file.uid || String(file.name),
type: file.type === 'video' ? 'video' : 'image',
src: file.url || '',
alt: file.name || '',
};
onRemove?.(item);
};
return ( return (
<div className={cx(styles.mediaRoot, className)} style={style}> <div
<ul className={styles.mediaGrid} data-testid="media-wall-grid" aria-label="媒体资源墙"> className={cx(styles.mediaRoot, className)}
{items.map((item) => ( style={style}
<li key={item.id} className={styles.mediaCell}> onClick={(e) => e.stopPropagation()}
<button className={styles.mediaButton} type="button" aria-label={`预览 ${item.alt}`} onClick={() => onPreview?.(item)}> >
<img className={styles.mediaThumb} src={item.src} alt={item.alt} /> <Upload
<span className={styles.srOnly}>{item.alt}</span> accept={accept}
{item.type === 'video' ? ( autoUpload={false}
<span className={styles.playBadge} aria-label="视频"> disabled={disabled}
<Icon name="play" size={20} /> files={tdesignFiles}
</span> max={maxCount}
) : null} multiple={multiple}
</button> theme="image"
</li> tips={helperText}
))} onChange={handleChange}
<li className={styles.mediaCell}> // 只有需要自定义预览时才传递 onPreview,否则让 TDesign 内置 ImageViewer 处理
<button className={styles.mediaUpload} type="button" disabled={disabled} onClick={() => inputRef.current?.click()}> onPreview={needCustomPreview ? handlePreview : undefined}
<span className={styles.mediaPlus} aria-hidden="true"> onRemove={handleRemove}
<Icon name="plus" size={22} /> />
</span>
<span>图片/视频</span>
</button>
<input
ref={inputRef}
aria-label="选择图片或视频"
className={styles.input}
type="file"
accept={accept}
multiple={multiple}
disabled={disabled}
onChange={(event) => {
if (event.target.files) onSelectFiles?.(Array.from(event.target.files));
event.currentTarget.value = '';
}}
/>
</li>
</ul>
{helperText ? <p className={styles.mediaHelper}>{helperText}</p> : null}
</div> </div>
); );
} }
\ 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 } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest'; import { describe, expect, it, vi } from 'vitest';
import { import {
...@@ -172,14 +172,13 @@ describe('feedback and display components', () => { ...@@ -172,14 +172,13 @@ describe('feedback and display components', () => {
expect(onConfirm).toHaveBeenCalledTimes(1); expect(onConfirm).toHaveBeenCalledTimes(1);
}); });
it('renders Message at top right and auto closes by duration', () => { it('renders Message at top right and auto closes by duration', async () => {
vi.useFakeTimers();
const onClose = vi.fn(); const onClose = vi.fn();
render( render(
<Message <Message
items={[ items={[
{ key: 'save', type: 'success', content: '保存成功', duration: 1000, onClose }, { key: 'save', type: 'success', content: '保存成功', duration: 1, onClose },
{ key: 'warn', type: 'warning', content: '请补充审批人', duration: 0, closable: true }, { key: 'warn', type: 'warning', content: '请补充审批人', duration: 0, closable: true },
]} ]}
/>, />,
...@@ -189,12 +188,9 @@ describe('feedback and display components', () => { ...@@ -189,12 +188,9 @@ describe('feedback and display components', () => {
expect(screen.getByRole('status', { name: '保存成功' })).toHaveClass(styles.success); expect(screen.getByRole('status', { name: '保存成功' })).toHaveClass(styles.success);
expect(screen.getByRole('status', { name: '请补充审批人' })).toHaveClass(styles.warning); expect(screen.getByRole('status', { name: '请补充审批人' })).toHaveClass(styles.warning);
vi.advanceTimersByTime(1000); await waitFor(() => expect(onClose).toHaveBeenCalledWith('save'));
expect(onClose).toHaveBeenCalledWith('save');
fireEvent.click(screen.getByRole('button', { name: '关闭请补充审批人' })); fireEvent.click(screen.getByRole('button', { name: '关闭请补充审批人' }));
expect(screen.queryByRole('status', { name: '请补充审批人' })).not.toBeInTheDocument(); expect(screen.queryByRole('status', { name: '请补充审批人' })).not.toBeInTheDocument();
vi.useRealTimers();
}); });
it('renders semantic icons before every Message status', () => { it('renders semantic icons before every Message status', () => {
......
import { fireEvent, render, screen, within } from '@testing-library/react'; import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { useState } from 'react'; import { useState } from 'react';
import { describe, expect, it, vi } from 'vitest'; import { describe, expect, it, vi } from 'vitest';
...@@ -18,6 +18,28 @@ function currentDateId() { ...@@ -18,6 +18,28 @@ 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 getSelectTrigger(name: string) {
return screen.getByRole('combobox', { name });
}
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 querySelectOption(name: string) {
return screen.queryAllByText(name).map((element) => element.closest('li')).find(Boolean) as HTMLElement | undefined;
}
function getSelectPopup() {
return screen.getByRole('list');
}
function getSelectRoot(name: string) {
return getSelectTrigger(name).closest('.t-select') as HTMLElement;
}
describe('selection, date, table and pagination components', () => { describe('selection, date, table and pagination components', () => {
it('selects and clears flat options while respecting disabled options', () => { it('selects and clears flat options while respecting disabled options', () => {
const onChange = vi.fn(); const onChange = vi.fn();
...@@ -34,24 +56,193 @@ describe('selection, date, table and pagination components', () => { ...@@ -34,24 +56,193 @@ describe('selection, date, table and pagination components', () => {
/>, />,
); );
fireEvent.click(screen.getByRole('combobox', { name: '负责人' })); fireEvent.click(getSelectTrigger('负责人'));
fireEvent.click(screen.getByRole('option', { name: '张三' })); fireEvent.click(getSelectOption('张三'));
fireEvent.click(screen.getByRole('combobox', { name: '负责人' })); fireEvent.click(getSelectTrigger('负责人'));
expect(screen.getByRole('option', { name: '张三' })).toHaveAttribute('aria-selected', 'true'); expect(getSelectOption('张三')).toHaveClass('t-is-selected');
fireEvent.click(screen.getByRole('button', { name: '清空负责人' })); fireEvent.click(getSelectOption('李四'));
fireEvent.click(screen.getByRole('combobox', { name: '负责人' }));
fireEvent.click(screen.getByRole('option', { name: '李四' }));
expect(onChange).toHaveBeenNthCalledWith(1, 'zhang', expect.objectContaining({ label: '张三' })); expect(onChange).toHaveBeenNthCalledWith(1, 'zhang', expect.objectContaining({ label: '张三' }));
expect(onChange).toHaveBeenNthCalledWith(2, undefined, undefined); expect(onChange).toHaveBeenCalledTimes(1);
expect(onChange).toHaveBeenCalledTimes(2);
}); });
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.getByRole('combobox', { name: '负责人' })).toHaveTextContent('张三'); expect(screen.getByDisplayValue('张三')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: '清空负责人' })).not.toBeInTheDocument(); expect(document.querySelector('.t-input__suffix-clear')).not.toBeInTheDocument();
});
it('supports native multi-select tags, keeps the popup open and clears all selections', () => {
function ControlledMultiSelect() {
const [value, setValue] = useState<string[]>(['zhang']);
return (
<Select
multiple
aria-label="负责人"
allowClear
placeholder="请选择负责人"
value={value}
options={[
{ label: '张三', value: 'zhang' },
{ label: '李四', value: 'li' },
{ label: '王五', value: 'wang' },
]}
onChange={(nextValue) => {
setValue(nextValue);
}}
/>
);
}
render(<ControlledMultiSelect />);
expect(getSelectRoot('负责人')).toHaveTextContent('张三');
expect(screen.queryByText('+1')).not.toBeInTheDocument();
fireEvent.click(getSelectTrigger('负责人'));
expect(getSelectPopup()).toBeInTheDocument();
expect(getSelectOption('张三')).toHaveClass('t-is-selected');
expect(getSelectOption('李四')).not.toHaveClass('t-is-selected');
fireEvent.click(getSelectOption('李四'));
expect(getSelectPopup()).toBeInTheDocument();
expect(getSelectRoot('负责人')).toHaveTextContent('张三');
expect(getSelectRoot('负责人')).toHaveTextContent('李四');
expect(getSelectOption('李四')).toHaveClass('t-is-selected');
});
it('keeps a multi-select popup open after choosing and closes it on outside clicks', async () => {
function ControlledMultiSelect() {
const [value, setValue] = useState<string[]>([]);
return (
<div>
<Select
multiple
aria-label="负责人"
value={value}
options={[
{ label: '张三', value: 'zhang' },
{ label: '李四', value: 'li' },
]}
onChange={setValue}
/>
<button type="button">页面其他区域</button>
</div>
);
}
render(<ControlledMultiSelect />);
fireEvent.click(getSelectTrigger('负责人'));
fireEvent.click(getSelectOption('张三'));
expect(getSelectPopup()).toBeInTheDocument();
fireEvent.mouseDown(screen.getByRole('button', { name: '页面其他区域' }));
await waitFor(() => {
expect(screen.queryByRole('list')).not.toBeInTheDocument();
});
});
it('closes a single-select popup on outside clicks', async () => {
render(
<div>
<Select aria-label="负责人" options={[{ label: '张三', value: 'zhang' }]} />
<button type="button">页面其他区域</button>
</div>,
);
fireEvent.click(getSelectTrigger('负责人'));
expect(getSelectPopup()).toBeInTheDocument();
fireEvent.mouseDown(screen.getByRole('button', { name: '页面其他区域' }));
await waitFor(() => {
expect(screen.queryByRole('list')).not.toBeInTheDocument();
});
});
it('renders native multi-select tags and allows removing a selected value from the trigger', () => {
function ControlledTagSelect() {
const [value, setValue] = useState<string[]>(['zhang', 'li']);
return (
<Select
multiple
aria-label="负责人"
value={value}
options={[
{ label: '张三', value: 'zhang' },
{ label: '李四', value: 'li' },
{ label: '王五', value: 'wang' },
]}
onChange={setValue}
/>
);
}
render(<ControlledTagSelect />);
expect(getSelectRoot('负责人')).toHaveTextContent('张三');
expect(getSelectRoot('负责人')).toHaveTextContent('李四');
expect(screen.queryByText('+1')).not.toBeInTheDocument();
expect(document.querySelector('.t-tag__icon-close')).toBeInTheDocument();
fireEvent.click(document.querySelector('.t-tag__icon-close') as Element);
expect(getSelectRoot('负责人')).not.toHaveTextContent('张三');
expect(getSelectRoot('负责人')).toHaveTextContent('李四');
});
it('allows selecting new items in native multiple mode', () => {
function ControlledTagSelect() {
const [value, setValue] = useState<string[]>(['zhang']);
return (
<Select
multiple
aria-label="负责人"
value={value}
options={[
{ label: '张三', value: 'zhang' },
{ label: '李四', value: 'li' },
{ label: '王五', value: 'wang' },
]}
onChange={setValue}
/>
);
}
render(<ControlledTagSelect />);
// Verify initial state: one tag with close button
expect(getSelectRoot('负责人')).toHaveTextContent('张三');
expect(document.querySelector('.t-tag__icon-close')).toBeInTheDocument();
// Click on the combobox trigger (not the close button) to open dropdown
fireEvent.click(getSelectTrigger('负责人'));
expect(getSelectPopup()).toBeInTheDocument();
// Select a new item from the dropdown
fireEvent.click(getSelectOption('李四'));
// The popup should still be open (multi-select behavior)
expect(getSelectPopup()).toBeInTheDocument();
// Both items should now be selected
expect(getSelectRoot('负责人')).toHaveTextContent('张三');
expect(getSelectRoot('负责人')).toHaveTextContent('李四');
expect(document.querySelectorAll('.t-tag__icon-close')).toHaveLength(2);
// Select another item
fireEvent.click(getSelectOption('王五'));
expect(getSelectRoot('负责人')).toHaveTextContent('王五');
expect(document.querySelectorAll('.t-tag__icon-close')).toHaveLength(3);
}); });
it('renders select trigger arrows with the softer helper icon color', () => { it('renders select trigger arrows with the softer helper icon color', () => {
...@@ -62,9 +253,7 @@ describe('selection, date, table and pagination components', () => { ...@@ -62,9 +253,7 @@ describe('selection, date, table and pagination components', () => {
</>, </>,
); );
expect(screen.getByRole('combobox', { name: '负责人' }).querySelector('[data-icon="chevron-right"]')).toHaveClass( expect(getSelectTrigger('负责人').querySelector('.t-fake-arrow')).toBeInTheDocument();
sharedStyles.fieldIcon,
);
expect(screen.getByRole('combobox', { name: '组织' }).querySelector('[data-icon="chevron-right"]')).toHaveClass( expect(screen.getByRole('combobox', { name: '组织' }).querySelector('[data-icon="chevron-right"]')).toHaveClass(
sharedStyles.fieldIcon, sharedStyles.fieldIcon,
); );
...@@ -84,14 +273,12 @@ describe('selection, date, table and pagination components', () => { ...@@ -84,14 +273,12 @@ describe('selection, date, table and pagination components', () => {
</>, </>,
); );
fireEvent.click(screen.getByRole('combobox', { name: '负责人' })); fireEvent.click(getSelectTrigger('负责人'));
expect(screen.getByRole('listbox')).toBeInTheDocument(); expect(getSelectPopup()).toBeInTheDocument();
fireEvent.click(screen.getByRole('combobox', { name: '组织' })); fireEvent.click(screen.getByRole('combobox', { name: '组织' }));
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
expect(screen.getByRole('tree')).toBeInTheDocument(); expect(screen.getByRole('tree')).toBeInTheDocument();
expect(screen.getByRole('combobox', { name: '负责人' })).toHaveAttribute('aria-expanded', 'false');
}); });
it('positions select popups under the trigger without taking layout space', () => { it('positions select popups under the trigger without taking layout space', () => {
...@@ -102,10 +289,10 @@ describe('selection, date, table and pagination components', () => { ...@@ -102,10 +289,10 @@ describe('selection, date, table and pagination components', () => {
</>, </>,
); );
fireEvent.click(screen.getByRole('combobox', { name: '负责人' })); fireEvent.click(getSelectTrigger('负责人'));
expect(screen.getByRole('combobox', { name: '负责人' }).parentElement).toHaveClass(sharedStyles.selectWrapper); expect(getSelectTrigger('负责人').closest('.t-select__wrap')).toBeInTheDocument();
expect(screen.getByRole('listbox')).toHaveClass(sharedStyles.selectPopup); expect(getSelectPopup()).toHaveClass('t-select__list');
fireEvent.click(screen.getByRole('combobox', { name: '组织' })); fireEvent.click(screen.getByRole('combobox', { name: '组织' }));
...@@ -148,16 +335,18 @@ describe('selection, date, table and pagination components', () => { ...@@ -148,16 +335,18 @@ describe('selection, date, table and pagination components', () => {
expect(screen.getByRole('combobox', { name: '组织' })).toHaveTextContent('财务部'); expect(screen.getByRole('combobox', { name: '组织' })).toHaveTextContent('财务部');
}); });
it('closes the select popup immediately after choosing an option', () => { it('closes the select popup immediately after choosing an option', async () => {
render(<Select aria-label="所属岗位" options={[{ label: '全部', value: 'all' }, { label: '客服岗', value: 'customer-service' }]} />); render(<Select aria-label="所属岗位" options={[{ label: '全部', value: 'all' }, { label: '客服岗', value: 'customer-service' }]} />);
fireEvent.click(screen.getByRole('combobox', { name: '所属岗位' })); fireEvent.click(getSelectTrigger('所属岗位'));
expect(screen.getByRole('listbox')).toBeInTheDocument(); expect(getSelectPopup()).toBeInTheDocument();
fireEvent.click(screen.getByRole('option', { name: '客服岗' })); fireEvent.click(getSelectOption('客服岗'));
expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); await waitFor(() => {
expect(screen.getByRole('combobox', { name: '所属岗位' })).toHaveTextContent('客服岗'); expect(screen.queryByRole('list')).not.toBeInTheDocument();
});
expect(screen.getByDisplayValue('客服岗')).toBeInTheDocument();
}); });
it('resets to the placeholder when a controlled select clears its value', () => { it('resets to the placeholder when a controlled select clears its value', () => {
...@@ -184,14 +373,14 @@ describe('selection, date, table and pagination components', () => { ...@@ -184,14 +373,14 @@ describe('selection, date, table and pagination components', () => {
render(<ControlledSelect />); render(<ControlledSelect />);
fireEvent.click(screen.getByRole('combobox', { name: '所属岗位' })); fireEvent.click(getSelectTrigger('所属岗位'));
fireEvent.click(screen.getByRole('option', { name: '客服岗' })); fireEvent.click(getSelectOption('客服岗'));
expect(screen.getByRole('combobox', { name: '所属岗位' })).toHaveTextContent('客服岗'); expect(screen.getByDisplayValue('客服岗')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '重置' })); fireEvent.click(screen.getByRole('button', { name: '重置' }));
expect(screen.getByRole('combobox', { name: '所属岗位' })).toHaveTextContent('全部'); expect(screen.getByPlaceholderText('全部')).toBeInTheDocument();
}); });
it('collapses an expanded TreeSelect parent when clicking it again', () => { it('collapses an expanded TreeSelect parent when clicking it again', () => {
...@@ -361,7 +550,7 @@ describe('selection, date, table and pagination components', () => { ...@@ -361,7 +550,7 @@ 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('closes date popups when clicking outside while keeping inside controls interactive', () => { it('closes date popups when clicking outside while keeping inside controls interactive', async () => {
render( render(
<div> <div>
<DatePicker aria-label="计划日期" value="2026-05-27" /> <DatePicker aria-label="计划日期" value="2026-05-27" />
...@@ -374,14 +563,18 @@ describe('selection, date, table and pagination components', () => { ...@@ -374,14 +563,18 @@ describe('selection, date, table and pagination components', () => {
fireEvent.click(screen.getByRole('button', { name: '下个月' })); fireEvent.click(screen.getByRole('button', { name: '下个月' }));
expect(screen.getByRole('heading', { name: '2026年 6月' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '2026年 6月' })).toBeInTheDocument();
fireEvent.pointerDown(screen.getByRole('button', { name: '页面其他区域' })); fireEvent.mouseDown(screen.getByRole('button', { name: '页面其他区域' }));
expect(screen.queryByRole('heading', { name: '2026年 6月' })).not.toBeInTheDocument(); await waitFor(() => {
expect(screen.queryByRole('heading', { name: '2026年 6月' })).not.toBeInTheDocument();
});
fireEvent.click(screen.getByRole('button', { name: /统计周期/ })); fireEvent.click(screen.getByRole('button', { name: /统计周期/ }));
expect(screen.getByRole('heading', { name: '2026年 5月' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '2026年 5月' })).toBeInTheDocument();
fireEvent.pointerDown(screen.getByRole('button', { name: '页面其他区域' })); fireEvent.mouseDown(screen.getByRole('button', { name: '页面其他区域' }));
expect(screen.queryByRole('heading', { name: '2026年 5月' })).not.toBeInTheDocument(); await waitFor(() => {
expect(screen.queryByRole('heading', { name: '2026年 5月' })).not.toBeInTheDocument();
});
}); });
it('renders Table custom cells, loading, empty, sorting, selection and row actions', () => { it('renders Table custom cells, loading, empty, sorting, selection and row actions', () => {
......
import { fireEvent, render, screen, within } from '@testing-library/react'; import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest'; import { describe, expect, it, vi } from 'vitest';
import { MediaWall, UploadDragger } from '../index'; import { FormItem, MediaWall, UploadDragger } from '../index';
import styles from './Upload.module.css';
describe('Upload components', () => { describe('Upload components', () => {
it('renders the 500 by 208 dragger with helper text and completed file actions', () => { describe('UploadDragger', () => {
const onPreview = vi.fn(); it('renders the dragger trigger and file list using tdesign-react Upload', () => {
const onDownload = vi.fn(); const onRemove = vi.fn();
const onRemove = vi.fn();
render(
<UploadDragger
title="点击或拖拽业务资料到此上传"
helperText="支持分片断点续传,单文件上限 1GB"
files={[
{ id: 'design', name: 'product_design_v2.fig', size: 12.4 * 1024 * 1024, status: 'done', previewable: true },
]}
onPreview={onPreview}
onDownload={onDownload}
onRemove={onRemove}
/>,
);
expect(screen.getByTestId('upload-dragger')).toHaveClass(styles.dragger);
expect(screen.getByText('点击或拖拽业务资料到此上传')).toBeInTheDocument();
expect(screen.getByText('支持分片断点续传,单文件上限 1GB')).toBeInTheDocument();
expect(screen.getByText('product_design_v2.fig')).toBeInTheDocument();
expect(screen.getByText('12.40 MB · 已完成')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '预览 product_design_v2.fig' }));
fireEvent.click(screen.getByRole('button', { name: '下载 product_design_v2.fig' }));
fireEvent.click(screen.getByRole('button', { name: '删除 product_design_v2.fig' }));
expect(onPreview).toHaveBeenCalledWith('design');
expect(onDownload).toHaveBeenCalledWith('design');
expect(onRemove).toHaveBeenCalledWith('design');
});
it('renders uploading progress with cancel and failed files with retry plus delete', () => { render(
const onCancel = vi.fn(); <UploadDragger
const onRetry = vi.fn(); title="点击或拖拽业务资料到此上传"
const onRemove = vi.fn(); helperText="支持分片断点续传,单文件上限 1GB"
files={[
render( { id: 'design', name: 'product_design_v2.fig', size: 12.4 * 1024 * 1024, status: 'success', previewable: true },
<UploadDragger ]}
files={[ onRemove={onRemove}
{ id: 'uploading', name: 'contract.pdf', size: 3 * 1024 * 1024, status: 'uploading', progress: 45 }, />,
{ id: 'failed', name: 'archive.zip', size: 8 * 1024 * 1024, status: 'error', errorMessage: '网络异常,请重试' }, );
]}
onCancel={onCancel} expect(screen.getByTestId('upload-dragger')).toBeInTheDocument();
onRetry={onRetry} expect(screen.getByText('点击或拖拽业务资料到此上传')).toBeInTheDocument();
onRemove={onRemove} // TDesign file-flow theme renders file name in table cell
/>, expect(screen.getByText('product_design_v2.fig')).toBeInTheDocument();
); });
expect(screen.getByText('3.00 MB · 上传中 45%')).toBeInTheDocument(); it('renders uploading progress and failed files', () => {
expect(screen.getByRole('progressbar', { name: 'contract.pdf 上传进度' })).toHaveAttribute('aria-valuenow', '45'); render(
expect(screen.getByText('8.00 MB · 上传失败')).toBeInTheDocument(); <UploadDragger
expect(screen.getByText('网络异常,请重试')).toBeInTheDocument(); files={[
{ id: 'uploading', name: 'contract.pdf', size: 3 * 1024 * 1024, status: 'progress', progress: 45 },
fireEvent.click(screen.getByRole('button', { name: '取消 contract.pdf' })); { id: 'failed', name: 'archive.zip', size: 8 * 1024 * 1024, status: 'fail', errorMessage: '网络异常,请重试' },
fireEvent.click(screen.getByRole('button', { name: '重试 archive.zip' })); ]}
fireEvent.click(screen.getByRole('button', { name: '删除 archive.zip' })); />,
);
expect(onCancel).toHaveBeenCalledWith('uploading');
expect(onRetry).toHaveBeenCalledWith('failed'); // TDesign renders file names
expect(onRemove).toHaveBeenCalledWith('failed'); expect(screen.getByText('contract.pdf')).toBeInTheDocument();
}); expect(screen.getByText('archive.zip')).toBeInTheDocument();
});
it('emits selected files when user selects a file', async () => {
const onSelectFiles = vi.fn();
const file = new File(['demo'], 'demo.pdf', { type: 'application/pdf' });
render(<UploadDragger files={[]} onSelectFiles={onSelectFiles} />);
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(fileInput, { target: { files: [file] } });
it('emits selected files without performing validation or transport', () => { await waitFor(() => {
const onSelectFiles = vi.fn(); expect(onSelectFiles).toHaveBeenCalledWith([file]);
const file = new File(['demo'], 'demo.pdf', { type: 'application/pdf' }); });
});
render(<UploadDragger files={[]} onSelectFiles={onSelectFiles} />); it('triggers onRemove when remove action is clicked', () => {
const onRemove = vi.fn();
fireEvent.change(screen.getByLabelText('选择上传文件'), { target: { files: [file] } }); render(
<UploadDragger
files={[
{ id: 'design', name: 'product_design_v2.fig', size: 12.4 * 1024 * 1024, status: 'success', previewable: true },
]}
onRemove={onRemove}
/>,
);
expect(onSelectFiles).toHaveBeenCalledWith([file]); // TDesign file-flow theme renders delete as a link in the action column
// Find by class or click on the action cell
const deleteLink = document.querySelector('.t-upload__flow-delete') as HTMLElement;
if (deleteLink) {
fireEvent.click(deleteLink);
expect(onRemove).toHaveBeenCalled();
}
});
}); });
it('keeps the drag active style while moving over children inside the drop zone', () => { describe('MediaWall', () => {
render(<UploadDragger files={[]} />); it('renders image cards and helper text', () => {
const image = { id: 'image', type: 'image' as const, src: '/cover.png', alt: '产品图片' };
render(<MediaWall items={[image]} helperText="支持 JPG、PNG、最大 10MB" />);
// Image should be rendered (TDesign image-flow theme)
const imgElement = document.querySelector(`img[src="${image.src}"]`);
expect(imgElement).toBeInTheDocument();
// helper text displayed
expect(screen.getByText('支持 JPG、PNG、最大 10MB')).toBeInTheDocument();
});
it('opens ImageViewer for image preview when onPreview is not provided', () => {
const image1 = { id: 'img1', type: 'image' as const, src: '/photo1.png', alt: '照片1' };
render(<MediaWall items={[image1]} />);
const imgElement = document.querySelector(`img[src="${image1.src}"]`);
expect(imgElement).toBeInTheDocument();
// TDesign image-flow: ImageViewer is rendered with BrowseIcon trigger
// The browse icon is an SVG inside the card-mask-item span
const maskItem = document.querySelector('.t-upload__card-mask-item') as HTMLElement;
const browseIcon = maskItem?.querySelector('.t-icon-browse') as HTMLElement;
if (browseIcon) {
fireEvent.click(browseIcon);
}
// ImageViewer modal should appear (TDesign's built-in)
expect(document.querySelector('.t-image-viewer__modal-image')).toBeInTheDocument();
});
it('calls onPreview callback when provided', () => {
const onPreview = vi.fn();
const image = { id: 'image', type: 'image' as const, src: '/cover.png', alt: '产品图片' };
render(<MediaWall items={[image]} onPreview={onPreview} />);
// TDesign image-flow: browse icon is SVG inside card-mask-item
const maskItem = document.querySelector('.t-upload__card-mask-item') as HTMLElement;
const browseIcon = maskItem?.querySelector('.t-icon-browse') as HTMLElement;
if (browseIcon) {
fireEvent.click(browseIcon);
expect(onPreview).toHaveBeenCalledWith(image);
}
});
it('calls onPreview for video items and also opens ImageViewer for thumbnail', () => {
const onPreview = vi.fn();
const video = { id: 'video', type: 'video' as const, src: '/video-cover.png', alt: '演示视频' };
render(<MediaWall items={[video]} onPreview={onPreview} />);
const imgElement = document.querySelector(`img[src="${video.src}"]`);
expect(imgElement).toBeInTheDocument();
// TDesign image-flow: browse icon is SVG inside card-mask-item
const maskItem = document.querySelector('.t-upload__card-mask-item') as HTMLElement;
const browseIcon = maskItem?.querySelector('.t-icon-browse') as HTMLElement;
if (browseIcon) {
fireEvent.click(browseIcon);
expect(onPreview).toHaveBeenCalledWith(video);
}
// TDesign's ImageViewer opens for video thumbnail (video cover image)
// This is TDesign's built-in behavior - the callback can be used for additional actions like video playback
expect(document.querySelector('.t-image-viewer__modal-image')).toBeInTheDocument();
});
it('emits selected files when user selects a file', async () => {
const onSelectFiles = vi.fn();
const file = new File(['demo'], 'demo.png', { type: 'image/png' });
render(<MediaWall items={[]} onSelectFiles={onSelectFiles} />);
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(fileInput, { target: { files: [file] } });
await waitFor(() => {
expect(onSelectFiles).toHaveBeenCalledWith([file]);
});
});
it('hides upload trigger when maxCount is reached', () => {
const image1 = { id: 'img1', type: 'image' as const, src: '/photo1.png', alt: '照片1' };
const dragger = screen.getByTestId('upload-dragger'); render(<MediaWall items={[image1]} maxCount={1} />);
const title = screen.getByText('点击或拖拽文件到此上传');
fireEvent.dragEnter(dragger); // TDesign image-flow hides upload card when max is reached
expect(dragger).toHaveClass(styles.draggerActive); // The upload input should still exist but the visible card should be hidden
const fileInput = document.querySelector('input[type="file"]');
expect(fileInput).toBeInTheDocument(); // input still exists for interaction
fireEvent.dragEnter(title); // Check that we don have an extra upload card beyond the image
fireEvent.dragLeave(title); const uploadCards = document.querySelectorAll('.t-upload__card-item');
expect(dragger).toHaveClass(styles.draggerActive); expect(uploadCards.length).toBe(1); // only the existing image card
});
fireEvent.dragLeave(dragger); it('shows upload trigger when items count is less than maxCount', () => {
expect(dragger).not.toHaveClass(styles.draggerActive); const image1 = { id: 'img1', type: 'image' as const, src: '/photo1.png', alt: '照片1' };
render(<MediaWall items={[image1]} maxCount={2} />);
// Should have both image card and upload card
const uploadCards = document.querySelectorAll('.t-upload__card-item');
expect(uploadCards.length).toBeGreaterThanOrEqual(1);
});
it('triggers onRemove when delete icon is clicked', () => {
const onRemove = vi.fn();
const image = { id: 'image', type: 'image' as const, src: '/cover.png', alt: '产品图片' };
render(<MediaWall items={[image]} onRemove={onRemove} />);
// TDesign image-flow: delete icon is SVG inside card-mask-item (second mask-item)
const maskItems = document.querySelectorAll('.t-upload__card-mask-item');
const deleteMaskItem = maskItems[1] as HTMLElement; // First is browse, second is delete
const deleteIcon = deleteMaskItem?.querySelector('.t-icon-delete') as HTMLElement;
if (deleteIcon) {
fireEvent.click(deleteIcon);
expect(onRemove).toHaveBeenCalled();
}
});
it('does not trigger file selection when preview button is clicked on existing image', async () => {
const onSelectFiles = vi.fn();
const onPreview = vi.fn();
const image = { id: 'image', type: 'image' as const, src: '/cover.png', alt: '产品图片' };
render(<MediaWall items={[image]} onSelectFiles={onSelectFiles} onPreview={onPreview} />);
// TDesign image-flow: browse icon is SVG inside card-mask-item
const maskItem = document.querySelector('.t-upload__card-mask-item') as HTMLElement;
const browseIcon = maskItem?.querySelector('.t-icon-browse') as HTMLElement;
if (browseIcon) {
fireEvent.click(browseIcon);
// onPreview should be called, but onSelectFiles should NOT be called
expect(onPreview).toHaveBeenCalledWith(image);
expect(onSelectFiles).not.toHaveBeenCalled();
}
});
it('does not trigger file selection when delete button is clicked on existing image', async () => {
const onSelectFiles = vi.fn();
const onRemove = vi.fn();
const image = { id: 'image', type: 'image' as const, src: '/cover.png', alt: '产品图片' };
render(<MediaWall items={[image]} onSelectFiles={onSelectFiles} onRemove={onRemove} />);
// TDesign image-flow: delete icon is SVG inside card-mask-item (second mask-item)
const maskItems = document.querySelectorAll('.t-upload__card-mask-item');
const deleteMaskItem = maskItems[1] as HTMLElement;
const deleteIcon = deleteMaskItem?.querySelector('.t-icon-delete') as HTMLElement;
if (deleteIcon) {
fireEvent.click(deleteIcon);
// onRemove should be called, but onSelectFiles should NOT be called
expect(onRemove).toHaveBeenCalled();
expect(onSelectFiles).not.toHaveBeenCalled();
}
});
}); });
it('renders media wall thumbnails, video play marker, helper text, and the upload tile last', () => { describe('FormItem with MediaWall combination', () => {
const onPreview = vi.fn(); it('does not trigger file selection when clicking outside upload area', async () => {
const onSelectFiles = vi.fn(); const onSelectFiles = vi.fn();
const image = { id: 'image', type: 'image' as const, src: '/cover.png', alt: '产品图片' }; const image = { id: 'image', type: 'image' as const, src: '/cover.png', alt: '产品图片' };
const video = { id: 'video', type: 'video' as const, src: '/video-cover.png', alt: '演示视频' };
render(
render( <FormItem label="内容图" required help="支持 JPG、PNG,最大 10MB">
<MediaWall <MediaWall items={[image]} maxCount={1} onSelectFiles={onSelectFiles} />
items={[image, video]} </FormItem>,
helperText="支持 JPG、PNG、MP4、MOV,图片单张不超过 10MB,视频单个不超过 500MB" );
onPreview={onPreview}
onSelectFiles={onSelectFiles} // Verify FormItem structure: outer div, not label
/>, const formItem = screen.getByTestId('form-item-内容图');
); expect(formItem.tagName).toBe('DIV');
const wall = screen.getByTestId('media-wall-grid'); // Verify label element exists but without htmlFor (complex control)
const cells = within(wall).getAllByRole('listitem'); const formLabel = screen.getByTestId('form-label-内容图');
expect(cells[0]).toHaveTextContent('产品图片'); expect(formLabel.tagName).toBe('LABEL');
expect(cells[1]).toHaveTextContent('演示视频'); expect(formLabel).not.toHaveAttribute('for');
expect(cells[2]).toHaveTextContent('图片/视频');
expect(within(cells[1]).getByLabelText('视频')).toHaveClass(styles.playBadge); // Click on the form item container (outside upload area)
expect(screen.getByText('支持 JPG、PNG、MP4、MOV,图片单张不超过 10MB,视频单个不超过 500MB')).toBeInTheDocument(); fireEvent.click(formItem);
fireEvent.click(screen.getByRole('button', { name: '预览 产品图片' })); // onSelectFiles should NOT be called when clicking outside upload area
fireEvent.click(screen.getByRole('button', { name: '预览 演示视频' })); expect(onSelectFiles).not.toHaveBeenCalled();
});
expect(onPreview).toHaveBeenNthCalledWith(1, image);
expect(onPreview).toHaveBeenNthCalledWith(2, video); it('does not trigger file selection when clicking label text for MediaWall', async () => {
const onSelectFiles = vi.fn();
const image = { id: 'image', type: 'image' as const, src: '/cover.png', alt: '产品图片' };
render(
<FormItem label="内容图" required help="支持 JPG、PNG,最大 10MB">
<MediaWall items={[image]} maxCount={1} onSelectFiles={onSelectFiles} />
</FormItem>,
);
// Click on the label text (should not trigger file input for complex controls)
const formLabel = screen.getByTestId('form-label-内容图');
fireEvent.click(formLabel);
// onSelectFiles should NOT be called when clicking the label
expect(onSelectFiles).not.toHaveBeenCalled();
});
it('does not trigger file selection when clicking help text below upload', async () => {
const onSelectFiles = vi.fn();
const image = { id: 'image', type: 'image' as const, src: '/cover.png', alt: '产品图片' };
render(
<FormItem label="内容图" required help="支持 JPG、PNG,最大 10MB">
<MediaWall items={[image]} maxCount={1} onSelectFiles={onSelectFiles} />
</FormItem>,
);
// Click on the help text area (below upload)
const helpText = screen.getByText('支持 JPG、PNG,最大 10MB');
fireEvent.click(helpText);
// onSelectFiles should NOT be called when clicking help text
expect(onSelectFiles).not.toHaveBeenCalled();
});
it('allows file selection only through explicit upload trigger', async () => {
const onSelectFiles = vi.fn();
const file = new File(['demo'], 'demo.png', { type: 'image/png' });
render(
<FormItem label="内容图" required>
<MediaWall items={[]} maxCount={1} onSelectFiles={onSelectFiles} />
</FormItem>,
);
// Only clicking the upload card trigger should open file selection
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(fileInput, { target: { files: [file] } });
await waitFor(() => {
expect(onSelectFiles).toHaveBeenCalledWith([file]);
});
});
}); });
}); });
\ No newline at end of file \ No newline at end of file
...@@ -109,4 +109,15 @@ describe('Admin login and protected routes', () => { ...@@ -109,4 +109,15 @@ describe('Admin login and protected routes', () => {
expect(screen.getByRole('button', { name: 'Agent管理' })).toHaveAttribute('data-active-parent', 'true'); expect(screen.getByRole('button', { name: 'Agent管理' })).toHaveAttribute('data-active-parent', 'true');
expect(screen.getByRole('button', { name: 'Agent列表' })).toHaveAttribute('aria-current', 'page'); expect(screen.getByRole('button', { name: 'Agent列表' })).toHaveAttribute('aria-current', 'page');
}); });
it('renders the skill route inside the admin shell navigation', () => {
window.localStorage.setItem(loginStorageKey, 'true');
renderApp('/skills');
expect(screen.getByRole('heading', { name: 'Skill目录' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Agent管理' })).toHaveAttribute('data-active-parent', 'true');
expect(screen.getByRole('button', { name: 'Skill目录' })).toHaveAttribute('aria-current', 'page');
expect(screen.getByText('Agent管理 / Skill目录')).toBeInTheDocument();
});
}); });
...@@ -2,10 +2,20 @@ import { Navigate, Route, Routes } from 'react-router-dom'; ...@@ -2,10 +2,20 @@ import { Navigate, Route, Routes } from 'react-router-dom';
import { AdminShell } from './layouts/AdminShell'; import { AdminShell } from './layouts/AdminShell';
import { RootLayout } from './layouts/RootLayout'; import { RootLayout } from './layouts/RootLayout';
import { AgentEditorPage } from './routes/agents/AgentEditorPage';
import { AgentListPage } from './routes/agents/AgentListPage'; import { AgentListPage } from './routes/agents/AgentListPage';
import { AgentTagEditorPage } from './routes/agent-tags/AgentTagEditorPage';
import { AgentTagListPage } from './routes/agent-tags/AgentTagListPage';
import { ChannelCodeEditorPage } from './routes/channel-codes/ChannelCodeEditorPage';
import { ChannelCodeListPage } from './routes/channel-codes/ChannelCodeListPage';
import { ComponentsDemoPage } from './routes/components/ComponentsDemoPage'; import { ComponentsDemoPage } from './routes/components/ComponentsDemoPage';
import { LoginPage } from './routes/login/LoginPage'; import { LoginPage } from './routes/login/LoginPage';
import { OfficialSiteMethodologyPage } from './routes/official-site/OfficialSiteMethodologyPage';
import { OfficialSiteAgentDisplayConfigPage } from './routes/official-site-agent-display-config/OfficialSiteAgentDisplayConfigPage';
import { OfficialSiteJobTabListPage } from './routes/official-site-job-tabs/OfficialSiteJobTabListPage';
import { OfficialSiteJobTabEditorPage } from './routes/official-site-job-tabs/OfficialSiteJobTabEditorPage';
import { ProtectedRoute } from './routes/ProtectedRoute'; import { ProtectedRoute } from './routes/ProtectedRoute';
import { SkillListPage } from './routes/skills/SkillListPage';
export function App() { export function App() {
return ( return (
...@@ -15,6 +25,20 @@ export function App() { ...@@ -15,6 +25,20 @@ export function App() {
<Route element={<AdminShell />}> <Route element={<AdminShell />}>
<Route index element={<Navigate to="/agents" replace />} /> <Route index element={<Navigate to="/agents" replace />} />
<Route path="agents" element={<AgentListPage />} /> <Route path="agents" element={<AgentListPage />} />
<Route path="agents/new" element={<AgentEditorPage mode="create" />} />
<Route path="agents/:agentId/edit" element={<AgentEditorPage mode="edit" />} />
<Route path="agent-tags" element={<AgentTagListPage />} />
<Route path="agent-tags/new" element={<AgentTagEditorPage mode="create" />} />
<Route path="agent-tags/:tagId/edit" element={<AgentTagEditorPage mode="edit" />} />
<Route path="channel-codes" element={<ChannelCodeListPage />} />
<Route path="channel-codes/new" element={<ChannelCodeEditorPage mode="create" />} />
<Route path="channel-codes/:codeId/edit" element={<ChannelCodeEditorPage mode="edit" />} />
<Route path="skills" element={<SkillListPage />} />
<Route path="official-site/methodology" element={<OfficialSiteMethodologyPage />} />
<Route path="official-site/job-tabs" element={<OfficialSiteJobTabListPage />} />
<Route path="official-site/job-tabs/new" element={<OfficialSiteJobTabEditorPage mode="create" />} />
<Route path="official-site/job-tabs/:tabId/edit" element={<OfficialSiteJobTabEditorPage mode="edit" />} />
<Route path="official-site/job-tabs/:tabId/agents" element={<OfficialSiteAgentDisplayConfigPage />} />
</Route> </Route>
</Route> </Route>
<Route element={<RootLayout />}> <Route element={<RootLayout />}>
......
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { MemoryRouter, Routes, Route, useNavigate } from 'react-router-dom';
import { MessageProvider, useFlashMessage } from './useMessage';
import { Button } from '../../packages/ui/src';
function TestShell({ initialEntries = ['/list'] }: { initialEntries?: string[] }) {
return (
<MemoryRouter initialEntries={initialEntries}>
<MessageProvider>
<Routes>
<Route path="/list" element={<ListPage />} />
<Route path="/edit" element={<EditPage />} />
</Routes>
</MessageProvider>
</MemoryRouter>
);
}
function ListPage() {
const flash = useFlashMessage();
return (
<div>
<h1>列表页</h1>
<Button onClick={() => flash.success('跳转后成功提示')}>模拟跳转成功</Button>
<Button onClick={() => flash.error('跳转后失败提示')}>模拟跳转失败</Button>
</div>
);
}
function EditPage() {
const navigate = useNavigate();
const handleSaveAndNavigate = () => {
navigate('/list', { state: { flash: { type: 'success', message: '保存成功' } } });
};
return (
<div>
<h1>编辑页</h1>
<Button onClick={handleSaveAndNavigate}>保存并返回</Button>
</div>
);
}
describe('flash message after navigation', () => {
it('shows success message after navigating from edit page', async () => {
render(<TestShell initialEntries={['/edit']} />);
fireEvent.click(screen.getByRole('button', { name: '保存并返回' }));
// Message should appear after navigation
await waitFor(
() => {
expect(screen.getByRole('status', { name: '保存成功' })).toBeInTheDocument();
},
{ timeout: 2000 },
);
});
it('uses flash.success to show one-time success message', async () => {
render(<TestShell />);
fireEvent.click(screen.getByRole('button', { name: '模拟跳转成功' }));
await waitFor(
() => {
expect(screen.getByRole('status', { name: '跳转后成功提示' })).toBeInTheDocument();
},
{ timeout: 2000 },
);
});
it('uses flash.error to show one-time error message', async () => {
render(<TestShell />);
fireEvent.click(screen.getByRole('button', { name: '模拟跳转失败' }));
await waitFor(
() => {
expect(screen.getByRole('alert', { name: '跳转后失败提示' })).toBeInTheDocument();
},
{ timeout: 2000 },
);
});
});
\ No newline at end of file \ No newline at end of file
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { type ReactNode, useState } from 'react';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
import { MessageProvider, useMessage } from './useMessage';
import { Message } from '../../packages/ui/src';
function TestShell({ children }: { children: ReactNode }) {
return (
<MemoryRouter initialEntries={['/agents']}>
<MessageProvider>
<div data-testid="shell">
{children}
</div>
</MessageProvider>
</MemoryRouter>
);
}
function MessageButton() {
const { success, error, warning, info } = useMessage();
return (
<div>
<button type="button" onClick={() => success('操作成功')}>成功</button>
<button type="button" onClick={() => error('操作失败')}>失败</button>
<button type="button" onClick={() => warning('请注意')}>警告</button>
<button type="button" onClick={() => info('已刷新')}>信息</button>
</div>
);
}
describe('global message entry', () => {
it('shows success, error, warning, info messages with correct types', () => {
render(
<TestShell>
<MessageButton />
</TestShell>,
);
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();
expect(screen.getByRole('alert', { name: '操作失败' })).toBeInTheDocument();
expect(screen.getByRole('status', { name: '请注意' })).toBeInTheDocument();
expect(screen.getByRole('status', { name: '已刷新' })).toBeInTheDocument();
});
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', () => {
function ClosableButton() {
const { success } = useMessage();
return <button type="button" onClick={() => success('可关闭消息', { closable: true, duration: 0 })}>可关闭</button>;
}
render(
<TestShell>
<ClosableButton />
</TestShell>,
);
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();
});
it('renders message container at top right fixed position', () => {
render(
<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 () => {
function ClearButton() {
const { success, clear } = useMessage();
return (
<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(
<TestShell>
<ClearButton />
</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: '清除全部' }));
await waitFor(() => {
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 type { ReactNode } from 'react';
import { useLocation } from 'react-router-dom';
import { Message, type MessageItem } from '../../packages/ui/src';
export interface MessageOptions {
duration?: number;
closable?: boolean;
}
interface FlashState {
type: 'success' | 'error' | 'warning' | 'info';
message: string;
}
interface MessageContextValue {
success: (content: string, options?: MessageOptions) => void;
error: (content: string, options?: MessageOptions) => void;
warning: (content: string, options?: MessageOptions) => void;
info: (content: string, options?: MessageOptions) => void;
clear: () => void;
}
interface FlashContextValue {
success: (message: string) => void;
error: (message: string) => void;
warning: (message: string) => void;
info: (message: string) => void;
}
const MessageContext = createContext<MessageContextValue | null>(null);
let messageKey = 0;
const generateKey = () => {
messageKey += 1;
return `message-${messageKey}`;
};
export function MessageProvider({ children }: { children: ReactNode }) {
const [items, setItems] = useState<MessageItem[]>([]);
const addMessage = useCallback((type: MessageItem['type'], content: string, options?: MessageOptions) => {
const key = generateKey();
const newItem: MessageItem = {
key,
type,
content,
duration: options?.duration ?? 3000,
closable: options?.closable ?? false,
onClose: (closedKey) => {
setItems((current) => current.filter((item) => item.key !== closedKey));
},
};
setItems((current) => [...current, newItem]);
}, []);
const success = useCallback((content: string, options?: MessageOptions) => {
addMessage('success', content, options);
}, [addMessage]);
const error = useCallback((content: string, options?: MessageOptions) => {
addMessage('error', content, options);
}, [addMessage]);
const warning = useCallback((content: string, options?: MessageOptions) => {
addMessage('warning', content, options);
}, [addMessage]);
const info = useCallback((content: string, options?: MessageOptions) => {
addMessage('info', content, options);
}, [addMessage]);
const clear = useCallback(() => {
setItems([]);
}, []);
return (
<MessageContext.Provider value={{ success, error, warning, info, clear }}>
{children}
<Message items={items} />
</MessageContext.Provider>
);
}
export function useMessage(): MessageContextValue {
const context = useContext(MessageContext);
if (!context) {
throw new Error('useMessage must be used within MessageProvider');
}
return context;
}
export function useFlashMessage(): FlashContextValue {
const location = useLocation();
const message = useMessage();
// Track processed flash keys to prevent re-processing after state clear
const processedRef = useRef<string | null>(null);
useEffect(() => {
const flash = (location.state as { flash?: FlashState } | null)?.flash;
// Create a unique key for this flash state
const flashKey = flash ? `${flash.type}:${flash.message}` : null;
// Only process if we have a flash state and haven't already processed it
if (flash && flashKey && processedRef.current !== flashKey) {
processedRef.current = flashKey;
message[flash.type](flash.message);
// Clear flash from history state without triggering navigation
// Use replaceState to modify the history entry directly
window.history.replaceState({}, '', location.pathname + location.search);
}
// Reset processed ref when location changes without flash
if (!flash) {
processedRef.current = null;
}
}, [location, message]);
const flashSuccess = useCallback((msg: string) => {
message.success(msg);
}, [message]);
const flashError = useCallback((msg: string) => {
message.error(msg);
}, [message]);
const flashWarning = useCallback((msg: string) => {
message.warning(msg);
}, [message]);
const flashInfo = useCallback((msg: string) => {
message.info(msg);
}, [message]);
return {
success: flashSuccess,
error: flashError,
warning: flashWarning,
info: flashInfo,
};
}
\ No newline at end of file \ No newline at end of file
...@@ -8,13 +8,53 @@ export function AdminShell() { ...@@ -8,13 +8,53 @@ export function AdminShell() {
const location = useLocation(); const location = useLocation();
const navigate = useNavigate(); const navigate = useNavigate();
const [logoutConfirmOpen, setLogoutConfirmOpen] = useState(false); const [logoutConfirmOpen, setLogoutConfirmOpen] = useState(false);
const activeNavigationKey = location.pathname.startsWith('/agents') ? 'agent-list' : undefined; const activeNavigationKey = location.pathname.startsWith('/skills')
? 'skill-list'
: location.pathname.startsWith('/agent-tags')
? 'agent-tag-list'
: location.pathname.startsWith('/official-site/methodology')
? 'official-site-methodology'
: location.pathname.startsWith('/official-site/job-tabs')
? 'official-site-job-tabs'
: location.pathname.startsWith('/agents')
? 'agent-list'
: location.pathname.startsWith('/channel-codes')
? 'channel-code-list'
: undefined;
const breadcrumb = location.pathname.startsWith('/skills')
? 'Agent管理 / Skill目录'
: location.pathname.startsWith('/agent-tags')
? 'Agent管理 / 岗位标签管理'
: location.pathname.startsWith('/official-site/methodology')
? '官网配置 / 方法论展示配置'
: location.pathname.startsWith('/official-site/job-tabs')
? '官网配置 / 岗位展示配置'
: location.pathname.startsWith('/channel-codes')
? 'Agent群管理 / 渠道活码'
: 'Agent管理 / Agent列表';
const navigationItems = [ const navigationItems = [
{ {
key: 'agent-management', key: 'agent-management',
label: 'Agent管理', label: 'Agent管理',
children: [{ key: 'agent-list', 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: '方法论展示配置' },
],
}, },
]; ];
...@@ -31,12 +71,17 @@ export function AdminShell() { ...@@ -31,12 +71,17 @@ export function AdminShell() {
items={navigationItems} items={navigationItems}
onChange={(key) => { onChange={(key) => {
if (key === 'agent-list') navigate('/agents'); if (key === 'agent-list') navigate('/agents');
if (key === 'agent-tag-list') navigate('/agent-tags');
if (key === 'skill-list') navigate('/skills');
if (key === 'channel-code-list') navigate('/channel-codes');
if (key === 'official-site-methodology') navigate('/official-site/methodology');
if (key === 'official-site-job-tabs') navigate('/official-site/job-tabs');
}} }}
/> />
</aside> </aside>
<div className="grid min-w-0 grid-rows-[auto_1fr]"> <div className="grid min-w-0 grid-rows-[auto_1fr]">
<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"> <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">
<span>Agent管理 / Agent列表</span> <span>{breadcrumb}</span>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Avatar name="管理员" /> <Avatar name="管理员" />
<Button <Button
......
...@@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client'; ...@@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom'; import { BrowserRouter } from 'react-router-dom';
import { App } from './App'; import { App } from './App';
import 'tdesign-react/es/style/index.css';
import './styles/index.css'; import './styles/index.css';
const rootElement = document.getElementById('root'); const rootElement = document.getElementById('root');
......
import { Navigate, Outlet, useLocation } from 'react-router-dom'; import { Navigate, Outlet, useLocation } from 'react-router-dom';
import { isLoggedIn } from '../auth/localAuth'; import { isLoggedIn } from '../auth/localAuth';
import { MessageProvider } from '../hooks/useMessage';
export function ProtectedRoute() { export function ProtectedRoute() {
const location = useLocation(); const location = useLocation();
...@@ -9,5 +10,9 @@ export function ProtectedRoute() { ...@@ -9,5 +10,9 @@ export function ProtectedRoute() {
return <Navigate to="/login" replace state={{ from: location }} />; return <Navigate to="/login" replace state={{ from: location }} />;
} }
return <Outlet />; return (
<MessageProvider>
<Outlet />
</MessageProvider>
);
} }
import { useMemo, useState } from 'react';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Button, FormItem, Input, StatePlaceholder, Textarea } from '../../../packages/ui/src';
import {
getAgentTagRecord,
isAgentTagCodeDuplicate,
saveAgentTagRecord,
type AgentTagMockItem,
} from '../../../packages/contracts/agent-tag-mock';
import { buildAgentTagListSearch, readAgentTagListRouteState } from './agentTagRouteState';
interface TagFormState {
name: string;
code: string;
description: string;
}
interface TagFormErrors {
name?: string;
code?: string;
description?: string;
}
interface SaveNotice {
type: 'error';
message: string;
}
function buildInitialFormState(tag?: AgentTagMockItem): TagFormState {
return {
name: tag?.name ?? '',
code: tag?.code ?? '',
description: tag?.description ?? '',
};
}
export function AgentTagEditorPage({ mode }: { mode: 'create' | 'edit' }) {
const navigate = useNavigate();
const location = useLocation();
const params = useParams();
const [searchParams] = useSearchParams();
const routeState = readAgentTagListRouteState(searchParams);
const scenario = searchParams.get('scenario') ?? 'normal';
const routeTag = (location.state as { tag?: AgentTagMockItem } | null)?.tag;
const currentTag = useMemo(
() => (mode === 'edit' ? routeTag ?? getAgentTagRecord(params.tagId) : undefined),
[mode, params.tagId, routeTag],
);
const [form, setForm] = useState<TagFormState>(() => buildInitialFormState(currentTag));
const [errors, setErrors] = useState<TagFormErrors>({});
const [notice, setNotice] = useState<SaveNotice | null>(null);
const fieldWidthClassName = 'w-full max-w-[450px]';
const goBackToList = () => {
navigate(`/agent-tags${buildAgentTagListSearch(routeState)}`);
};
if (mode === 'edit' && !currentTag) {
return (
<StatePlaceholder
state="error"
title="岗位标签不存在"
description="当前岗位标签记录不存在或已被删除"
primaryAction={<Button size="small" onClick={goBackToList}>返回列表</Button>}
/>
);
}
const validate = () => {
const nextErrors: TagFormErrors = {};
const trimmedName = form.name.trim();
const trimmedCode = form.code.trim();
const trimmedDescription = form.description.trim();
if (!trimmedName) {
nextErrors.name = '请输入标签名称';
} else if (trimmedName.length > 20) {
nextErrors.name = '标签名称最多20字';
}
if (mode === 'create') {
if (!trimmedCode) {
nextErrors.code = '请输入标签编码';
} else if (!/^[A-Za-z_]+$/.test(trimmedCode)) {
nextErrors.code = '标签编码仅支持英文和下划线';
} else if (isAgentTagCodeDuplicate(trimmedCode)) {
nextErrors.code = '标签编码已存在';
}
}
if (trimmedDescription.length > 100) {
nextErrors.description = '标签描述最多100字';
}
setErrors(nextErrors);
return Object.keys(nextErrors).length === 0;
};
const handleSave = () => {
setNotice(null);
if (!validate()) {
return;
}
if (scenario === 'saveError') {
setNotice({ type: 'error', message: '保存失败,请重试' });
return;
}
saveAgentTagRecord({
tagId: currentTag?.tag_id,
name: form.name,
code: mode === 'create' ? form.code : undefined,
description: form.description,
});
navigate(
`/agent-tags${buildAgentTagListSearch({
...routeState,
refreshToken: String(Date.now()),
})}`,
);
};
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)]">{mode === 'create' ? '新建岗位标签' : '编辑岗位标签'}</h2>
<p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">
{mode === 'create' ? '创建新的岗位标签' : '编辑已有岗位标签信息'}
</p>
</div>
</div>
<div className="flex items-center gap-3">
<Button variant="outline" onClick={goBackToList}>取消</Button>
<Button variant="primary" onClick={handleSave}>保存</Button>
</div>
</header>
{notice ? (
<div
className="rounded-[var(--gl-radius-sm)] border border-[var(--gl-color-danger-border)] bg-[var(--gl-color-danger-bg)] px-4 py-3 text-sm text-[var(--gl-color-danger-text)]"
role="alert"
aria-label={notice.message}
>
{notice.message}
</div>
) : null}
<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">
<FormItem label="标签名称" layout="horizontal" required error={errors.name}>
<Input
aria-label="标签名称"
className={fieldWidthClassName}
maxLength={20}
showCount
value={form.name}
onChange={(value) => setForm((current) => ({ ...current, name: value }))}
/>
</FormItem>
<FormItem label="标签编码" layout="horizontal" required error={errors.code}>
<Input
aria-label="标签编码"
className={fieldWidthClassName}
disabled={mode === 'edit'}
maxLength={50}
showCount
value={form.code}
onChange={(value) => setForm((current) => ({ ...current, code: value }))}
/>
</FormItem>
<FormItem label="标签描述" layout="horizontal" error={errors.description}>
<Textarea
aria-label="标签描述"
className={fieldWidthClassName}
maxLength={100}
rows={5}
showCount
value={form.description}
onChange={(value) => setForm((current) => ({ ...current, description: value }))}
/>
</FormItem>
</div>
</div>
</section>
);
}
import { useMemo, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button, StatePlaceholder, Table, Pagination, Input, Modal } from '../../../packages/ui/src';
import {
agentTagMockFixtures,
deleteAgentTagRecord,
getAgentTagListPage,
getAgentTagReferences,
type AgentTagMockFixture,
type AgentTagMockItem,
type AgentTagReferences,
} from '../../../packages/contracts/agent-tag-mock';
import { useMessage } from '../../hooks/useMessage';
import { buildAgentTagListSearch, readAgentTagListRouteState } from './agentTagRouteState';
function getFixtureByScenario(scenario: string): AgentTagMockFixture {
switch (scenario) {
case 'empty':
return agentTagMockFixtures.empty;
case 'loadError':
return agentTagMockFixtures.loadError;
case 'saveError':
return agentTagMockFixtures.saveError;
case 'referenceError':
return agentTagMockFixtures.referenceError;
default:
return agentTagMockFixtures.normal;
}
}
function buildDeleteTitle(tag: AgentTagMockItem) {
return `确认删除岗位标签“${tag.name}”?`;
}
function buildDeleteDescription(references: AgentTagReferences) {
if (references.detachable_references.agent_count > 0) {
return '删除后这些 Agent 将失去该标签';
}
return '删除后不可恢复,请确认是否继续删除当前岗位标签。';
}
export function AgentTagListPage() {
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const routeState = readAgentTagListRouteState(searchParams);
const [keyword, setKeyword] = useState(routeState.keyword);
const message = useMessage();
const [deleteTarget, setDeleteTarget] = useState<{ tag: AgentTagMockItem; references: AgentTagReferences } | null>(null);
const [version, setVersion] = useState(0);
const fixture = getFixtureByScenario(routeState.scenario);
const listSource = routeState.scenario === 'empty' ? fixture.items : undefined;
const result = useMemo(
() => getAgentTagListPage({
keyword: routeState.keyword,
page: routeState.page,
pageSize: routeState.pageSize,
source: listSource,
}),
[listSource, routeState.keyword, routeState.page, routeState.pageSize, routeState.refreshToken, version],
);
const hasFilter = Boolean(routeState.keyword.trim());
const routeSearch = buildAgentTagListSearch({
scenario: routeState.scenario,
keyword: routeState.keyword,
page: routeState.page,
pageSize: routeState.pageSize,
});
const submitFilters = () => {
setSearchParams(buildAgentTagListSearch({
scenario: routeState.scenario,
keyword,
page: 1,
pageSize: routeState.pageSize,
}));
};
const resetFilters = () => {
setKeyword('');
setSearchParams(buildAgentTagListSearch({
scenario: routeState.scenario,
keyword: '',
page: 1,
pageSize: routeState.pageSize,
}));
};
const handleDeleteClick = (tag: AgentTagMockItem) => {
try {
const references = getAgentTagReferences(tag.tag_id, routeState.scenario === 'referenceError' ? 'referenceError' : 'normal');
if (references.blocking_references.qrcode_count > 0) {
message.error('请先删除关联的渠道活码');
return;
}
if (references.blocking_references.official_tab_count > 0) {
message.error('请先删除关联的官网 Tab 配置');
return;
}
setDeleteTarget({ tag, references });
} catch {
message.error('引用检查失败,请重试');
}
};
const columns = [
{ title: '标签名称', dataIndex: 'name' as const },
{ title: '标签编码', dataIndex: 'code' as const },
{ title: '标签描述', dataIndex: 'description' as const },
{ title: '使用 Agent 数', dataIndex: 'agent_count' as const },
{ title: '关联渠道活码数', dataIndex: 'channel_code_count' as const },
{ title: '关联官网 Tab 数', dataIndex: 'official_tab_count' as const },
{ title: '创建时间', dataIndex: 'created_at' as const },
{
title: '操作',
key: 'actions',
render: (_: unknown, tag: AgentTagMockItem) => (
<span className="flex flex-wrap gap-1">
<Button
aria-label={`编辑${tag.name}`}
size="small"
variant="text"
onClick={() => navigate(`/agent-tags/${tag.tag_id}/edit${routeSearch}`, { state: { tag } })}
>
编辑
</Button>
<Button aria-label={`删除${tag.name}`} size="small" variant="danger" onClick={() => handleDeleteClick(tag)}>
删除
</Button>
</span>
),
},
];
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>
<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>
</div>
<Button variant="primary" onClick={() => navigate(`/agent-tags/new${routeSearch}`)}>新建岗位标签</Button>
</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">
<div className="flex items-center gap-2 text-sm">
<span className="shrink-0">标签名称:</span>
<span className="w-[200px]">
<Input
aria-label="标签名称"
className="w-full"
placeholder="搜索标签名称"
value={keyword}
allowClear
onChange={setKeyword}
onKeyDown={(event) => {
if (event.key === 'Enter') 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">
{fixture.loadError ? (
<StatePlaceholder
state="error"
title="加载失败"
description="岗位标签列表加载失败,请重试"
primaryAction={<Button size="small" onClick={() => setSearchParams(buildAgentTagListSearch({ ...routeState, scenario: 'normal' }))}>重试</Button>}
/>
) : (
<>
<Table
rowKey="tag_id"
columns={columns}
dataSource={result.items}
empty={{
description: hasFilter ? '未找到匹配结果' : '当前还没有岗位标签',
action: hasFilter ? <Button size="small" onClick={resetFilters}>重置搜索</Button> : undefined,
}}
/>
{result.items.length === 0 && hasFilter ? <StatePlaceholder state="filtered-empty" /> : null}
<Pagination
current={routeState.page}
pageSize={routeState.pageSize}
total={result.total}
pageSizeOptions={[2, 10, 20]}
onChange={(page, pageSize) => {
setSearchParams(buildAgentTagListSearch({
scenario: routeState.scenario,
keyword: routeState.keyword,
page,
pageSize,
}));
}}
/>
</>
)}
</div>
<Modal
open={Boolean(deleteTarget)}
title={deleteTarget ? buildDeleteTitle(deleteTarget.tag) : ''}
onCancel={() => setDeleteTarget(null)}
onOk={() => {
if (!deleteTarget) return;
deleteAgentTagRecord(deleteTarget.tag.tag_id);
setDeleteTarget(null);
message.success('删除成功');
setVersion((current) => current + 1);
}}
>
<p className="m-0 max-w-[360px] leading-[var(--gl-line-height-md)] text-[var(--gl-color-text-secondary)]">
{deleteTarget ? buildDeleteDescription(deleteTarget.references) : ''}
</p>
</Modal>
</section>
);
}
\ No newline at end of file \ No newline at end of file
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { App } from '../../App';
function renderAgentTags(path = '/agent-tags') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
describe('Agent tag routes and list page', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('renders the list route, navigation entry, search area, table columns and primary action', () => {
renderAgentTags();
expect(screen.getByRole('heading', { name: '岗位标签管理' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '岗位标签管理' })).toHaveAttribute('aria-current', 'page');
expect(screen.getByText('标签名称:')).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.getByText('标签名称')).toBeInTheDocument();
expect(screen.getByText('标签编码')).toBeInTheDocument();
expect(screen.getByText('使用 Agent 数')).toBeInTheDocument();
expect(screen.getByText('关联渠道活码数')).toBeInTheDocument();
expect(screen.getByText('关联官网 Tab 数')).toBeInTheDocument();
expect(screen.getByText('共 5 条')).toBeInTheDocument();
});
it('supports keyword search, reset and pagination changes from the list page', () => {
renderAgentTags();
fireEvent.change(screen.getByLabelText('标签名称'), { target: { value: '售后' } });
fireEvent.click(screen.getByRole('button', { name: '搜索' }));
expect(screen.getByText('售后客服')).toBeInTheDocument();
expect(screen.queryByText('店销顾问')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '重置' }));
expect(screen.getByLabelText('标签名称')).toHaveValue('');
expect(screen.getByText('店销顾问')).toBeInTheDocument();
fireEvent.change(screen.getByRole('combobox', { name: '每页条数' }), { target: { value: '2' } });
fireEvent.click(screen.getByRole('button', { name: '第 2 页' }));
expect(screen.getByRole('button', { name: '第 2 页' })).toHaveAttribute('aria-current', 'page');
expect(screen.getByText('直播运营')).toBeInTheDocument();
});
it('shows a recoverable load error state and retries back to the normal list', () => {
renderAgentTags('/agent-tags?scenario=loadError');
expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '重试' }));
expect(screen.getByText('店销顾问')).toBeInTheDocument();
});
});
describe('Agent tag create and edit pages', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('renders the new page, validates fields, saves successfully, and returns to the list', () => {
renderAgentTags('/agent-tags/new');
expect(screen.getByRole('heading', { name: '新建岗位标签' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '取消' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '保存' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByText('请输入标签名称')).toBeInTheDocument();
expect(screen.getByText('请输入标签编码')).toBeInTheDocument();
fireEvent.change(screen.getByLabelText('标签名称'), { target: { value: '培训讲师' } });
fireEvent.change(screen.getByLabelText('标签编码'), { target: { value: 'store_sales' } });
fireEvent.change(screen.getByLabelText('标签描述'), { target: { value: '负责培训赋能' } });
fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByText('标签编码已存在')).toBeInTheDocument();
fireEvent.change(screen.getByLabelText('标签编码'), { target: { value: 'training_teacher' } });
fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByRole('heading', { name: '岗位标签管理' })).toBeInTheDocument();
expect(screen.getByText('培训讲师')).toBeInTheDocument();
});
it('stays on the current form page when save fails', () => {
renderAgentTags('/agent-tags/new?scenario=saveError');
fireEvent.change(screen.getByLabelText('标签名称'), { target: { value: '培训讲师' } });
fireEvent.change(screen.getByLabelText('标签编码'), { target: { value: 'training_teacher' } });
fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByRole('alert', { name: '保存失败,请重试' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: '新建岗位标签' })).toBeInTheDocument();
});
it('renders the edit page from direct access, keeps code read-only, and handles missing records', () => {
renderAgentTags('/agent-tags/2/edit');
expect(screen.getByRole('heading', { name: '编辑岗位标签' })).toBeInTheDocument();
expect(screen.getByDisplayValue('售后客服')).toBeInTheDocument();
expect(screen.getByDisplayValue('after_sales_service')).toBeDisabled();
fireEvent.change(screen.getByLabelText('标签名称'), { target: { value: '售后服务' } });
fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByRole('heading', { name: '岗位标签管理' })).toBeInTheDocument();
expect(screen.getByText('售后服务')).toBeInTheDocument();
renderAgentTags('/agent-tags/999/edit');
expect(screen.getByRole('alert', { name: '岗位标签不存在' })).toBeInTheDocument();
});
});
describe('Agent tag deletion flows', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('confirms deletion for unreferenced tags and keeps data unchanged when deletion is canceled', () => {
renderAgentTags();
const unreferencedRow = screen.getByRole('row', { name: /店销顾问/ });
fireEvent.click(within(unreferencedRow).getByRole('button', { name: '删除店销顾问' }));
expect(screen.getByRole('dialog', { name: '确认删除岗位标签“店销顾问”?' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '取消' }));
expect(screen.getByText('店销顾问')).toBeInTheDocument();
fireEvent.click(within(unreferencedRow).getByRole('button', { name: '删除店销顾问' }));
fireEvent.click(screen.getByRole('button', { name: '确定' }));
expect(screen.queryByText('店销顾问')).not.toBeInTheDocument();
});
it('requires confirmation for agent references and blocks channel code, official tab, and reference errors', () => {
renderAgentTags();
fireEvent.click(within(screen.getByRole('row', { name: /售后客服/ })).getByRole('button', { name: '删除售后客服' }));
expect(screen.getByText('删除后这些 Agent 将失去该标签')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '确定' }));
expect(screen.queryByText('售后客服')).not.toBeInTheDocument();
fireEvent.click(within(screen.getByRole('row', { name: /直播运营/ })).getByRole('button', { name: '删除直播运营' }));
expect(screen.getByRole('alert', { name: '请先删除关联的渠道活码' })).toBeInTheDocument();
fireEvent.click(within(screen.getByRole('row', { name: /官网顾问/ })).getByRole('button', { name: '删除官网顾问' }));
expect(screen.getByRole('alert', { name: '请先删除关联的官网 Tab 配置' })).toBeInTheDocument();
cleanup();
renderAgentTags('/agent-tags?scenario=referenceError');
fireEvent.click(within(screen.getByRole('row', { name: /私域增长/ })).getByRole('button', { name: '删除私域增长' }));
expect(screen.getByRole('alert', { name: '引用检查失败,请重试' })).toBeInTheDocument();
});
});
export interface AgentTagListRouteState {
scenario: string;
keyword: string;
page: number;
pageSize: number;
refreshToken?: string;
}
export function readAgentTagListRouteState(searchParams: URLSearchParams): AgentTagListRouteState {
const page = Number(searchParams.get('page') ?? '1');
const pageSize = Number(searchParams.get('pageSize') ?? '10');
return {
scenario: searchParams.get('scenario') ?? 'normal',
keyword: searchParams.get('keyword') ?? '',
page: Number.isFinite(page) && page > 0 ? page : 1,
pageSize: Number.isFinite(pageSize) && pageSize > 0 ? pageSize : 10,
refreshToken: searchParams.get('refreshToken') ?? undefined,
};
}
export function buildAgentTagListSearch(state: Partial<AgentTagListRouteState>) {
const searchParams = new URLSearchParams();
if (state.scenario && state.scenario !== 'normal') searchParams.set('scenario', state.scenario);
if (state.keyword) searchParams.set('keyword', state.keyword);
if (state.page && state.page !== 1) searchParams.set('page', String(state.page));
if (state.pageSize && state.pageSize !== 10) searchParams.set('pageSize', String(state.pageSize));
if (state.refreshToken) searchParams.set('refreshToken', state.refreshToken);
const query = searchParams.toString();
return query ? `?${query}` : '';
}
import { useNavigate } from 'react-router-dom';
import { Button, Drawer, StatePlaceholder, Tag } from '../../../packages/ui/src';
import { getAgentDetail } from '../../../packages/contracts/agent-editor-mock';
import { findSavedAgent } from './agentLocalStore';
import { buildAgentListSearch, type AgentListRouteState } from './agentRouteState';
export function AgentDetailDrawer({ agentId, routeState }: { agentId?: string; routeState: AgentListRouteState }) {
const navigate = useNavigate();
const detail = findSavedAgent(agentId) ?? getAgentDetail(agentId);
const closeDrawer = () => {
navigate(`/agents${buildAgentListSearch({ ...routeState, detail: undefined })}`);
};
if (!agentId) {
return null;
}
return (
<Drawer
open
title="Agent详情"
width={520}
onClose={closeDrawer}
footer={
<div className="flex items-center justify-end gap-3">
<Button variant="outline" onClick={closeDrawer}>关闭</Button>
<Button variant="primary" onClick={() => navigate(`/agents/${agentId}/edit${buildAgentListSearch(routeState)}`)}>编辑</Button>
</div>
}
>
{!detail ? (
<StatePlaceholder state="error" title="详情加载失败" description="当前 Agent 详情无法展示" />
) : (
<div className="grid gap-4 text-sm">
<section className="grid gap-2">
<strong className="text-base">{detail.name}</strong>
<span className="text-[var(--gl-color-text-secondary)]">ID: {detail.agent_id}</span>
</section>
<div className="grid gap-3">
<div className="grid grid-cols-[100px_1fr] gap-2 items-start">
<span className="text-[var(--gl-color-text-secondary)]">所属岗位</span>
<div className="flex flex-wrap gap-2">
{detail.is_manager ? <Tag status="info">系统调度</Tag> : detail.positions.map((position) => <Tag key={position.id}>{position.name}</Tag>)}
</div>
</div>
<div className="grid grid-cols-[100px_1fr] gap-2 items-start">
<span className="text-[var(--gl-color-text-secondary)]">托管企微员工</span>
<span>{detail.employee_name}</span>
</div>
<div className="grid grid-cols-[100px_1fr] gap-2 items-start">
<span className="text-[var(--gl-color-text-secondary)]">Agent描述</span>
<span>{detail.description}</span>
</div>
<div className="grid grid-cols-[100px_1fr] gap-2 items-start">
<span className="text-[var(--gl-color-text-secondary)]">状态</span>
<div className="flex flex-wrap gap-2">
<Tag status={detail.status === 'enable' ? 'success' : 'warning'}>{detail.status === 'enable' ? '已上架' : '已停用'}</Tag>
</div>
</div>
</div>
</div>
)}
</Drawer>
);
}
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { App } from '../../App';
function renderAgents(path = '/agents') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
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 getSelectRoot(name: string) {
return screen.getByRole('combobox', { name }).closest('.t-select') as HTMLElement;
}
function getSelectWrap(name: string) {
return screen.getByRole('combobox', { name }).closest('.t-select__wrap') as HTMLElement;
}
describe('Agent editor routes and detail drawer', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('renders the new page with agent navigation selected and returns to the list context on cancel', () => {
renderAgents('/agents/new?keyword=复盘&page=2&pageSize=20');
expect(screen.getByRole('heading', { name: '新建Agent' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Agent列表' })).toHaveAttribute('aria-current', 'page');
expect(screen.getByRole('button', { name: '取消' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '保存' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '取消' }));
expect(screen.getByRole('heading', { name: 'Agent管理' })).toBeInTheDocument();
expect(screen.getByLabelText('搜索Agent名称')).toHaveValue('复盘');
expect(screen.getByLabelText('每页条数')).toHaveValue('20');
});
it('opens the detail drawer from the list entry and closes without losing list context', () => {
renderAgents('/agents?keyword=复盘&page=1&pageSize=10');
fireEvent.click(screen.getByRole('button', { name: '查看复盘Agent详情' }));
const drawer = screen.getByRole('dialog', { name: 'Agent详情' });
expect(within(drawer).getByText('复盘Agent')).toBeInTheDocument();
expect(screen.getByLabelText('搜索Agent名称')).toHaveValue('复盘');
fireEvent.click(screen.getByRole('button', { name: '关闭Agent详情' }));
expect(screen.queryByRole('dialog', { name: 'Agent详情' })).not.toBeInTheDocument();
expect(screen.getByLabelText('搜索Agent名称')).toHaveValue('复盘');
});
it('renders the edit page with preloaded values and restores the detail drawer context after cancel', () => {
renderAgents('/agents/101/edit?keyword=复盘&detail=101');
expect(screen.getByRole('heading', { name: '编辑Agent' })).toBeInTheDocument();
expect(screen.getByDisplayValue('复盘Agent')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Agent列表' })).toHaveAttribute('aria-current', 'page');
fireEvent.click(screen.getByRole('button', { name: '取消' }));
const drawer = screen.getByRole('dialog', { name: 'Agent详情' });
expect(drawer).toBeInTheDocument();
expect(within(drawer).getByText('复盘Agent')).toBeInTheDocument();
});
});
describe('Agent editor form rules', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('shows required validation for a normal agent and keeps saving disabled during submit', () => {
renderAgents('/agents/new');
fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByText('请输入 Agent 名称')).toBeInTheDocument();
expect(screen.getByText('请选择所属岗位')).toBeInTheDocument();
expect(screen.getByText('请选择托管企微员工')).toBeInTheDocument();
expect(screen.getByText('请输入 Agent 描述')).toBeInTheDocument();
expect(screen.getByText('请至少绑定一个 Skill')).toBeInTheDocument();
});
it('locks fixed fields for manager agents while leaving description editable', () => {
renderAgents('/agents/1/edit');
expect(screen.getByDisplayValue('管家Agent')).toBeDisabled();
expect(screen.getByRole('combobox', { name: '所属岗位' })).toHaveAttribute('aria-disabled', 'true');
expect(screen.getByRole('combobox', { name: '托管企微员工' })).toHaveAttribute('aria-disabled', 'true');
expect(screen.getByRole('switch', { name: '状态' })).toBeDisabled();
expect(screen.getByLabelText('Agent描述')).toBeEnabled();
});
it('uses consistent responsive widths, shows required state label, and keeps employee tips visible before selecting positions', () => {
renderAgents('/agents/new');
expect(screen.getByLabelText('Agent名称').parentElement).toHaveClass('w-full', 'max-w-[450px]');
expect(getSelectWrap('所属岗位')).toHaveClass('w-full', 'max-w-[450px]');
expect(getSelectWrap('托管企微员工')).toHaveClass('w-full', 'max-w-[450px]');
expect(getSelectWrap('绑定Skill')).toHaveClass('w-full', 'max-w-[450px]');
expect(screen.getByTestId('form-label-状态')).toHaveTextContent('*状态');
expect(screen.getByRole('combobox', { name: '托管企微员工' })).toHaveAttribute('aria-disabled', 'true');
expect(screen.getByPlaceholderText('请先选择所属岗位')).toBeInTheDocument();
expect(screen.getByText('请先选择所属岗位')).toBeInTheDocument();
});
it('creates a new agent and returns to the list with refreshed data', async () => {
renderAgents('/agents');
const initialRowCount = screen.getAllByRole('row').length;
fireEvent.click(screen.getByRole('button', { name: '新建Agent' }));
expect(screen.getByRole('heading', { name: '新建Agent' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Agent列表' })).toHaveAttribute('aria-current', 'page');
// 填写表单
fireEvent.change(screen.getByLabelText('Agent名称'), { target: { value: '新测试Agent' } });
fireEvent.click(screen.getByRole('combobox', { name: '所属岗位' }));
await waitFor(() => expect(getSelectOption('驻店销售岗')).toBeInTheDocument());
fireEvent.click(getSelectOption('驻店销售岗'));
await waitFor(() => expect(screen.getByRole('combobox', { name: '托管企微员工' })).not.toHaveAttribute('aria-disabled', 'true'));
fireEvent.click(screen.getByRole('combobox', { name: '托管企微员工' }));
await waitFor(() => expect(getSelectOption('陈晓岚')).toBeInTheDocument());
fireEvent.click(getSelectOption('陈晓岚'));
fireEvent.change(screen.getByLabelText('Agent描述'), { target: { value: '这是一个测试Agent的描述' } });
fireEvent.click(screen.getByRole('combobox', { name: '绑定Skill' }));
await waitFor(() => expect(getSelectOption('会话总结')).toBeInTheDocument());
fireEvent.click(getSelectOption('会话总结'));
fireEvent.click(screen.getByRole('button', { name: '保存' }));
await waitFor(() => {
expect(screen.getByRole('heading', { name: 'Agent管理' })).toBeInTheDocument();
});
// 验证列表数据已刷新(新增了一条数据)
const rowsAfterCreate = screen.getAllByRole('row');
expect(rowsAfterCreate.length).toBeGreaterThan(initialRowCount);
expect(screen.getByRole('button', { name: 'Agent列表' })).toHaveAttribute('aria-current', 'page');
}, 10000);
it('edits an agent and returns to the list with detail drawer context preserved', async () => {
renderAgents('/agents?detail=101');
// 详情抽屉已打开
const drawer = screen.getByRole('dialog', { name: 'Agent详情' });
expect(within(drawer).getByText('复盘Agent')).toBeInTheDocument();
fireEvent.click(within(drawer).getByRole('button', { name: '编辑' }));
expect(screen.getByRole('heading', { name: '编辑Agent' })).toBeInTheDocument();
expect(screen.getByDisplayValue('复盘Agent')).toBeInTheDocument();
// 修改描述
fireEvent.change(screen.getByLabelText('Agent描述'), { target: { value: '更新后的复盘Agent描述' } });
fireEvent.click(screen.getByRole('button', { name: '保存' }));
await waitFor(() => {
expect(screen.getByRole('dialog', { name: 'Agent详情' })).toBeInTheDocument();
});
// 验证详情抽屉上下文已恢复
const restoredDrawer = screen.getByRole('dialog', { name: 'Agent详情' });
expect(within(restoredDrawer).getByText('更新后的复盘Agent描述')).toBeInTheDocument();
});
it('renders selected skills as tag content instead of summary mode in the editor form', async () => {
renderAgents('/agents/new');
const combobox = screen.getByRole('combobox', { name: '绑定Skill' });
fireEvent.click(combobox);
await waitFor(() => {
expect(getSelectOption('会话总结')).toBeInTheDocument();
});
fireEvent.click(getSelectOption('会话总结'));
fireEvent.click(getSelectOption('线索跟进'));
await waitFor(() => {
const skillCombobox = screen.getByRole('combobox', { name: '绑定Skill' });
expect(skillCombobox.closest('.t-select')).toHaveTextContent('会话总结');
expect(skillCombobox.closest('.t-select')).toHaveTextContent('线索跟进');
});
});
});
import { useMemo, useState } from 'react';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Button, FormItem, Input, Select, StatePlaceholder, Switch, Textarea } from '../../../packages/ui/src';
import {
createAgentRecord,
getAgentDetail,
getAgentEditorFixture,
type AgentDraftPayload,
type AgentEditorScenario,
} from '../../../packages/contracts/agent-editor-mock';
import { findSavedAgent, upsertSavedAgent } from './agentLocalStore';
import { buildAgentListSearch, readAgentListRouteState } from './agentRouteState';
interface AgentFormState {
name: string;
positionIds: string[];
userId?: string;
description: string;
skillIds: string[];
status: 'enable' | 'disable';
}
function buildInitialFormState(agentId?: string): AgentFormState {
const detail = findSavedAgent(agentId) ?? getAgentDetail(agentId);
if (!detail) {
return {
name: '',
positionIds: [],
userId: undefined,
description: '',
skillIds: [],
status: 'disable',
};
}
return {
name: detail.name,
positionIds: detail.positions.map((position) => position.id),
userId: detail.employee_id,
description: detail.description,
skillIds: detail.skill_ids,
status: detail.status,
};
}
export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
const navigate = useNavigate();
const location = useLocation();
const params = useParams();
const [searchParams] = useSearchParams();
const [form, setForm] = useState<AgentFormState>(() => buildInitialFormState(params.agentId));
const [errors, setErrors] = useState<Partial<Record<keyof AgentFormState, string>>>({});
const routeState = readAgentListRouteState(searchParams);
const scenario = (searchParams.get('scenario') ?? 'normal') as AgentEditorScenario;
const fixture = useMemo(
() => getAgentEditorFixture({ agentId: params.agentId, mode, scenario, positionIds: form.positionIds }),
[form.positionIds, mode, params.agentId, scenario],
);
const detail = findSavedAgent(params.agentId) ?? getAgentDetail(params.agentId);
const isManager = detail?.is_manager ?? false;
const fieldWidthClassName = 'w-full max-w-[450px]';
if (fixture.detailLoading) {
return <StatePlaceholder state="empty" title="加载中" description="正在加载 Agent 详情" />;
}
if (mode === 'edit' && !detail) {
return <StatePlaceholder state="error" title="Agent不存在" description="当前 Agent 详情无法加载" />;
}
const goBackToList = (restoreDetail: boolean) => {
const nextSearch = buildAgentListSearch({
...routeState,
detail: restoreDetail ? routeState.detail : undefined,
});
navigate(`/agents${nextSearch}`);
};
const validate = () => {
const nextErrors: Partial<Record<keyof AgentFormState, string>> = {};
if (!form.name.trim()) nextErrors.name = '请输入 Agent 名称';
if (form.positionIds.length === 0) nextErrors.positionIds = '请选择所属岗位';
if (!form.userId) nextErrors.userId = '请选择托管企微员工';
if (!form.description.trim()) nextErrors.description = '请输入 Agent 描述';
if (!isManager && form.skillIds.length === 0) nextErrors.skillIds = '请至少绑定一个 Skill';
setErrors(nextErrors);
return Object.keys(nextErrors).length === 0;
};
const handleSave = () => {
if (!validate()) {
return;
}
if (fixture.saveError) {
return;
}
const payload: AgentDraftPayload = {
name: form.name.trim(),
positionIds: form.positionIds,
userId: form.userId,
description: form.description.trim(),
skillIds: form.skillIds,
status: form.status,
};
const savedDetail = mode === 'create'
? createAgentRecord(payload)
: {
...detail!,
name: isManager ? detail!.name : payload.name,
positions: isManager ? detail!.positions : fixture.positions.filter((position) => payload.positionIds.includes(position.id)),
employee_id: isManager ? detail!.employee_id : payload.userId ?? '',
employee_name: isManager ? detail!.employee_name : fixture.employees.find((employee) => employee.id === payload.userId)?.name ?? '',
description: payload.description,
skill_ids: payload.skillIds,
status: isManager ? detail!.status : payload.status,
};
upsertSavedAgent(savedDetail);
const nextDetailId = String(savedDetail.agent_id);
navigate(
`/agents${buildAgentListSearch({
...routeState,
detail: mode === 'edit' && routeState.detail ? nextDetailId : undefined,
refreshToken: String(Date.now()),
})}`,
);
};
const title = mode === 'create' ? '新建Agent' : '编辑Agent';
const employeeOptions = fixture.employees.map((employee) => ({
label: employee.status === 'mounted' ? `${employee.name}(已挂载Agent)` : employee.name,
value: employee.id,
disabled: employee.status === 'mounted',
}));
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(Boolean(routeState.detail && mode === 'edit'))}>返回</Button>
<div>
<h2 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">{title}</h2>
<p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">
{mode === 'create' ? '创建新的岗位 Agent 配置' : '编辑已存在的 Agent 配置'}
</p>
</div>
</div>
<div className="flex items-center gap-3">
<Button variant="outline" onClick={() => goBackToList(Boolean(routeState.detail && mode === 'edit'))}>取消</Button>
<Button variant="primary" loading={fixture.saveLoading} onClick={handleSave}>保存</Button>
</div>
</header>
{fixture.saveError ? (
<StatePlaceholder
state="error"
title="保存失败,请重试"
description="当前变更尚未保存成功,请检查表单后重新提交。"
/>
) : null}
<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">
<FormItem label="Agent名称" layout="horizontal" required error={errors.name}>
<span className="grid gap-2">
<Input
aria-label="Agent名称"
className={fieldWidthClassName}
disabled={isManager}
maxLength={50}
showCount
value={form.name}
onChange={(value) => setForm((current) => ({ ...current, name: value }))}
/>
</span>
</FormItem>
<FormItem label="所属岗位" layout="horizontal" required error={errors.positionIds}>
<span className="grid gap-2">
{fixture.positionsError ? (
<StatePlaceholder state="error" title="岗位选项加载失败" description="请重试加载岗位选项" primaryAction={<Button size="small">重试</Button>} />
) : (
<Select
aria-label="所属岗位"
className={fieldWidthClassName}
disabled={isManager}
multiple
options={fixture.positions.map((position) => ({ label: position.name, value: position.id }))}
value={form.positionIds}
onChange={(value) => {
const nextValue = Array.isArray(value) ? value : [];
setForm((current) => ({
...current,
positionIds: nextValue,
userId: nextValue.some((positionId) => current.positionIds.includes(positionId)) ? current.userId : undefined,
}));
}}
/>
)}
</span>
</FormItem>
<FormItem
label="托管企微员工"
layout="horizontal"
required
error={errors.userId}
tips={!isManager && form.positionIds.length === 0 ? '请先选择所属岗位' : undefined}
>
<span className="grid gap-2">
{fixture.employeesError ? (
<StatePlaceholder state="error" title="托管企微员工加载失败" description="请重试加载托管企微员工选项" primaryAction={<Button size="small">重试</Button>} />
) : (
<Select
aria-label="托管企微员工"
className={fieldWidthClassName}
disabled={isManager || form.positionIds.length === 0}
options={employeeOptions}
placeholder={form.positionIds.length === 0 ? '请先选择所属岗位' : '请选择托管企微员工'}
value={form.userId}
onChange={(value) => setForm((current) => ({ ...current, userId: typeof value === 'string' ? value : undefined }))}
/>
)}
</span>
</FormItem>
<FormItem label="Agent描述" layout="horizontal" required error={errors.description}>
<Textarea
aria-label="Agent描述"
className={fieldWidthClassName}
maxLength={200}
rows={5}
showCount
value={form.description}
onChange={(value) => setForm((current) => ({ ...current, description: value }))}
/>
</FormItem>
<FormItem label="绑定Skill" layout="horizontal" required={!isManager} error={errors.skillIds}>
<span className="grid gap-2">
{fixture.skillsError ? (
<StatePlaceholder state="error" title="Skill 选项加载失败" description="请重试加载 Skill 选项" primaryAction={<Button size="small">重试</Button>} />
) : (
<Select
aria-label="绑定Skill"
className={fieldWidthClassName}
multiple
options={fixture.skills.map((skill) => ({ label: skill.name, value: skill.id }))}
value={form.skillIds}
onChange={(value) => setForm((current) => ({ ...current, skillIds: Array.isArray(value) ? value : [] }))}
/>
)}
</span>
</FormItem>
<FormItem label="状态" layout="horizontal" required>
<Switch
aria-label="状态"
checked={form.status === 'enable'}
disabled={isManager}
onChange={(checked) => setForm((current) => ({ ...current, status: checked ? 'enable' : 'disable' }))}
/>
</FormItem>
</div>
</div>
</section>
);
}
...@@ -13,6 +13,12 @@ function renderAgents(path = '/agents') { ...@@ -13,6 +13,12 @@ function renderAgents(path = '/agents') {
); );
} }
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('AgentListPage', () => { describe('AgentListPage', () => {
beforeEach(() => { beforeEach(() => {
window.localStorage.clear(); window.localStorage.clear();
...@@ -77,12 +83,12 @@ describe('AgentListPage', () => { ...@@ -77,12 +83,12 @@ describe('AgentListPage', () => {
fireEvent.change(screen.getByLabelText('搜索Agent名称'), { target: { value: '复盘' } }); fireEvent.change(screen.getByLabelText('搜索Agent名称'), { target: { value: '复盘' } });
fireEvent.click(screen.getByRole('combobox', { name: '岗位筛选' })); fireEvent.click(screen.getByRole('combobox', { name: '岗位筛选' }));
fireEvent.click(screen.getByRole('option', { name: '客服岗' })); fireEvent.click(getSelectOption('客服岗'));
expect(screen.getByText('复盘Agent')).toBeInTheDocument(); expect(screen.getByText('复盘Agent')).toBeInTheDocument();
expect(screen.queryByRole('status', { name: '未找到匹配结果' })).not.toBeInTheDocument(); expect(screen.queryByRole('status', { name: '未找到匹配结果' })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('combobox', { name: '状态筛选' })); fireEvent.click(screen.getByRole('combobox', { name: '状态筛选' }));
fireEvent.click(screen.getByRole('option', { name: '已停用' })); fireEvent.click(getSelectOption('已停用'));
expect(screen.getByText('复盘Agent')).toBeInTheDocument(); expect(screen.getByText('复盘Agent')).toBeInTheDocument();
expect(screen.queryByRole('status', { name: '未找到匹配结果' })).not.toBeInTheDocument(); expect(screen.queryByRole('status', { name: '未找到匹配结果' })).not.toBeInTheDocument();
...@@ -90,12 +96,12 @@ describe('AgentListPage', () => { ...@@ -90,12 +96,12 @@ describe('AgentListPage', () => {
expect(screen.getByRole('button', { name: '第 1 页' })).toHaveAttribute('aria-current', 'page'); expect(screen.getByRole('button', { name: '第 1 页' })).toHaveAttribute('aria-current', 'page');
expect(screen.getByRole('status', { name: '未找到匹配结果' })).toBeInTheDocument(); expect(screen.getByRole('status', { name: '未找到匹配结果' })).toBeInTheDocument();
expect(screen.getByRole('combobox', { name: '岗位筛选' })).toHaveTextContent('客服岗'); expect(screen.getByDisplayValue('客服岗')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '重置' })); fireEvent.click(screen.getByRole('button', { name: '重置' }));
expect(screen.getByLabelText('搜索Agent名称')).toHaveValue(''); expect(screen.getByLabelText('搜索Agent名称')).toHaveValue('');
expect(screen.getByRole('combobox', { name: '岗位筛选' })).toHaveTextContent('全部'); expect(screen.getAllByDisplayValue('全部').length).toBeGreaterThan(0);
expect(screen.getByText('复盘Agent')).toBeInTheDocument(); expect(screen.getByText('复盘Agent')).toBeInTheDocument();
expect(screen.getByText('质检Agent')).toBeInTheDocument(); expect(screen.getByText('质检Agent')).toBeInTheDocument();
}); });
...@@ -115,8 +121,8 @@ describe('AgentListPage', () => { ...@@ -115,8 +121,8 @@ describe('AgentListPage', () => {
renderAgents(); renderAgents();
fireEvent.click(screen.getByRole('combobox', { name: '岗位筛选' })); fireEvent.click(screen.getByRole('combobox', { name: '岗位筛选' }));
expect(screen.getByRole('option', { name: '全部' })).toBeInTheDocument(); expect(getSelectOption('全部')).toBeInTheDocument();
fireEvent.click(screen.getByRole('option', { name: '客服岗' })); fireEvent.click(getSelectOption('客服岗'));
fireEvent.click(screen.getByRole('button', { name: '搜索' })); fireEvent.click(screen.getByRole('button', { name: '搜索' }));
expect(screen.queryByRole('button', { name: '清空岗位筛选' })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: '清空岗位筛选' })).not.toBeInTheDocument();
......
import { useMemo, useState } from 'react'; import { useMemo, useState } from 'react';
import { 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 { Button, Input, Modal, Pagination, Select, StatePlaceholder, Table, Tag } from '../../../packages/ui/src';
import { import {
agentListMockFixtures, agentListMockFixtures,
agentPositionOptions,
getAgentListPage, getAgentListPage,
type AgentListMockItem, type AgentListMockItem,
type AgentListMockFixture, type AgentListMockFixture,
type AgentStatus, type AgentStatus,
} from '../../../packages/contracts/agent-list-mock'; } from '../../../packages/contracts/agent-list-mock';
import { AgentDetailDrawer } from './AgentDetailDrawer';
const defaultPageSize = 10; import { projectDetailToListItem, readSavedAgents } from './agentLocalStore';
import { buildAgentListSearch, readAgentListRouteState } from './agentRouteState';
function getFixtureByScenario(scenario: string): AgentListMockFixture { function getFixtureByScenario(scenario: string): AgentListMockFixture {
switch (scenario) { switch (scenario) {
...@@ -44,12 +44,21 @@ function statusTag(status: AgentStatus) { ...@@ -44,12 +44,21 @@ function statusTag(status: AgentStatus) {
return status === 'enable' ? 'success' : 'warning'; return status === 'enable' ? 'success' : 'warning';
} }
function AgentActions({ agent }: { agent: AgentListMockItem }) { function AgentActions({ agent, routeSearch }: { agent: AgentListMockItem; routeSearch: string }) {
const [deleteOpen, setDeleteOpen] = useState(false); const [deleteOpen, setDeleteOpen] = useState(false);
const navigate = useNavigate();
return ( return (
<span className="flex flex-wrap gap-1"> <span className="flex flex-wrap gap-1">
<Button aria-label={`编辑${agent.name}`} size="small" variant="text">编辑</Button> <Button
aria-label={`查看${agent.name}详情`}
size="small"
variant="text"
onClick={() => navigate(`/agents${routeSearch ? `${routeSearch}&detail=${agent.agent_id}` : `?detail=${agent.agent_id}`}`)}
>
查看
</Button>
<Button aria-label={`编辑${agent.name}`} size="small" variant="text" onClick={() => navigate(`/agents/${agent.agent_id}/edit${routeSearch}`)}>编辑</Button>
{agent.available_actions.includes('disable') ? <Button aria-label={`停用${agent.name}`} size="small" variant="text">停用</Button> : null} {agent.available_actions.includes('disable') ? <Button aria-label={`停用${agent.name}`} size="small" variant="text">停用</Button> : null}
{agent.available_actions.includes('enable') ? <Button aria-label={`上架${agent.name}`} size="small" variant="text">上架</Button> : null} {agent.available_actions.includes('enable') ? <Button aria-label={`上架${agent.name}`} size="small" variant="text">上架</Button> : null}
{agent.available_actions.includes('delete') ? ( {agent.available_actions.includes('delete') ? (
...@@ -67,39 +76,62 @@ function AgentActions({ agent }: { agent: AgentListMockItem }) { ...@@ -67,39 +76,62 @@ function AgentActions({ agent }: { agent: AgentListMockItem }) {
} }
export function AgentListPage() { export function AgentListPage() {
const [searchParams] = useSearchParams(); const navigate = useNavigate();
const [scenario, setScenario] = useState(searchParams.get('scenario') ?? 'normal'); const [searchParams, setSearchParams] = useSearchParams();
const [keyword, setKeyword] = useState(''); const routeState = readAgentListRouteState(searchParams);
const [submittedKeyword, setSubmittedKeyword] = useState(''); const [keyword, setKeyword] = useState(routeState.keyword);
const [positionId, setPositionId] = useState<string | undefined>(); const [positionId, setPositionId] = useState<string | undefined>(routeState.positionId);
const [submittedPositionId, setSubmittedPositionId] = useState<string | undefined>(); const [status, setStatus] = useState<AgentStatus | 'all'>(routeState.status);
const [status, setStatus] = useState<AgentStatus | 'all'>('all'); const fixture = getFixtureByScenario(routeState.scenario);
const [submittedStatus, setSubmittedStatus] = useState<AgentStatus | 'all'>('all'); const sourceItems = useMemo(() => {
const [page, setPage] = useState(1); const savedItems = readSavedAgents().map(projectDetailToListItem);
const [pageSize, setPageSize] = useState(defaultPageSize); const preservedItems = fixture.items.filter((item) => !savedItems.some((saved) => saved.agent_id === item.agent_id));
return [...savedItems, ...preservedItems];
const fixture = getFixtureByScenario(scenario); }, [fixture.items, routeState.refreshToken]);
const result = useMemo( const result = useMemo(
() => getAgentListPage({ keyword: submittedKeyword, page, pageSize, positionId: submittedPositionId, status: submittedStatus, source: fixture.items }), () => getAgentListPage({
[fixture.items, page, pageSize, submittedKeyword, submittedPositionId, submittedStatus], keyword: routeState.keyword,
page: routeState.page,
pageSize: routeState.pageSize,
positionId: routeState.positionId,
status: routeState.status,
source: sourceItems,
}),
[routeState.keyword, routeState.page, routeState.pageSize, routeState.positionId, routeState.status, sourceItems],
); );
const hasFilter = Boolean(submittedKeyword || submittedPositionId || submittedStatus !== 'all'); const hasFilter = Boolean(routeState.keyword || routeState.positionId || routeState.status !== 'all');
const routeSearch = buildAgentListSearch({
scenario: routeState.scenario,
keyword: routeState.keyword,
positionId: routeState.positionId,
status: routeState.status,
page: routeState.page,
pageSize: routeState.pageSize,
});
const resetToFirstPage = () => setPage(1);
const submitFilters = () => { const submitFilters = () => {
setSubmittedKeyword(keyword); setSearchParams(buildAgentListSearch({
setSubmittedPositionId(positionId); scenario: routeState.scenario,
setSubmittedStatus(status); keyword,
resetToFirstPage(); positionId,
status,
page: 1,
pageSize: routeState.pageSize,
}));
}; };
const resetFilters = () => { const resetFilters = () => {
setKeyword(''); setKeyword('');
setSubmittedKeyword('');
setPositionId(undefined); setPositionId(undefined);
setSubmittedPositionId(undefined);
setStatus('all'); setStatus('all');
setSubmittedStatus('all'); setSearchParams(buildAgentListSearch({
resetToFirstPage(); scenario: routeState.scenario,
keyword: '',
positionId: undefined,
status: 'all',
page: 1,
pageSize: routeState.pageSize,
}));
}; };
const columns = [ const columns = [
...@@ -107,10 +139,10 @@ export function AgentListPage() { ...@@ -107,10 +139,10 @@ export function AgentListPage() {
title: 'Agent名称', title: 'Agent名称',
key: 'name', key: 'name',
render: (_: unknown, agent: AgentListMockItem) => ( render: (_: unknown, agent: AgentListMockItem) => (
<span 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>
</span> </div>
), ),
}, },
{ {
...@@ -129,7 +161,7 @@ export function AgentListPage() { ...@@ -129,7 +161,7 @@ export function AgentListPage() {
{ {
title: '操作', title: '操作',
key: 'actions', key: 'actions',
render: (_: unknown, agent: AgentListMockItem) => <AgentActions agent={agent} />, render: (_: unknown, agent: AgentListMockItem) => <AgentActions agent={agent} routeSearch={routeSearch} />,
}, },
]; ];
...@@ -140,7 +172,7 @@ export function AgentListPage() { ...@@ -140,7 +172,7 @@ 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、管家 Agent 与列表 mock 数据状态</p> <p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">管理岗位 Agent、管家 Agent 与列表 mock 数据状态</p>
</div> </div>
<Button variant="primary">新建Agent</Button> <Button variant="primary" onClick={() => navigate(`/agents/new${routeSearch}`)}>新建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"> <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">
...@@ -166,12 +198,15 @@ export function AgentListPage() { ...@@ -166,12 +198,15 @@ export function AgentListPage() {
<span className="w-[200px]" data-testid="agent-position-control"> <span className="w-[200px]" data-testid="agent-position-control">
<Select <Select
aria-label="岗位筛选" aria-label="岗位筛选"
options={[{ label: '全部', value: 'all' }, ...agentPositionOptions.map((option) => ({ label: option.name, value: option.id }))]} options={[
{ label: '全部', value: 'all' },
{ label: '驻店销售岗', value: 'sales' },
{ label: '客服岗', value: 'service' },
{ label: '运营岗', value: 'ops' },
]}
placeholder="全部" placeholder="全部"
value={positionId} value={positionId}
onChange={(value) => { onChange={(value) => setPositionId(value === 'all' ? undefined : value)}
setPositionId(value === 'all' ? undefined : value);
}}
/> />
</span> </span>
</div> </div>
...@@ -186,9 +221,7 @@ export function AgentListPage() { ...@@ -186,9 +221,7 @@ export function AgentListPage() {
{ label: '已停用', value: 'disable' }, { label: '已停用', value: 'disable' },
]} ]}
value={status} value={status}
onChange={(value) => { onChange={(value) => setStatus((value as AgentStatus | 'all') ?? 'all')}
setStatus((value as AgentStatus | 'all') ?? 'all');
}}
/> />
</span> </span>
</div> </div>
...@@ -205,7 +238,7 @@ export function AgentListPage() { ...@@ -205,7 +238,7 @@ export function AgentListPage() {
state="error" state="error"
title="加载失败" title="加载失败"
description="Agent 列表请求失败,当前数据状态未知" description="Agent 列表请求失败,当前数据状态未知"
primaryAction={<Button size="small" onClick={() => setScenario('normal')}>重试</Button>} primaryAction={<Button size="small" onClick={() => setSearchParams(buildAgentListSearch({ ...routeState, scenario: 'normal' }))}>重试</Button>}
/> />
) : ( ) : (
<> <>
...@@ -221,17 +254,22 @@ export function AgentListPage() { ...@@ -221,17 +254,22 @@ export function AgentListPage() {
/> />
{result.items.length === 0 && hasFilter ? <StatePlaceholder state="filtered-empty" /> : null} {result.items.length === 0 && hasFilter ? <StatePlaceholder state="filtered-empty" /> : null}
<Pagination <Pagination
current={page} current={routeState.page}
pageSize={pageSize} pageSize={routeState.pageSize}
total={result.total} total={result.total}
onChange={(nextPage, nextPageSize) => { onChange={(nextPage, nextPageSize) => {
setPage(nextPage); setSearchParams(buildAgentListSearch({
setPageSize(nextPageSize); ...routeState,
page: nextPage,
pageSize: nextPageSize,
}));
}} }}
/> />
</> </>
)} )}
</div> </div>
<AgentDetailDrawer agentId={routeState.detail} routeState={routeState} />
</section> </section>
); );
} }
import type { AgentDetailRecord } from '../../../packages/contracts/agent-editor-mock';
import type { AgentListMockItem } from '../../../packages/contracts/agent-list-mock';
const storageKey = 'agent-admin-saved-agents';
function canUseStorage() {
return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';
}
export function readSavedAgents() {
if (!canUseStorage()) {
return [] as AgentDetailRecord[];
}
try {
const raw = window.localStorage.getItem(storageKey);
return raw ? (JSON.parse(raw) as AgentDetailRecord[]) : [];
} catch {
return [];
}
}
export function upsertSavedAgent(detail: AgentDetailRecord) {
if (!canUseStorage()) {
return;
}
const current = readSavedAgents();
const next = [...current.filter((item) => item.agent_id !== detail.agent_id), detail];
window.localStorage.setItem(storageKey, JSON.stringify(next));
}
export function findSavedAgent(agentId?: string) {
if (!agentId) {
return undefined;
}
return readSavedAgents().find((item) => String(item.agent_id) === agentId);
}
export function projectDetailToListItem(detail: AgentDetailRecord): AgentListMockItem {
return {
agent_id: detail.agent_id,
name: detail.name,
is_manager: detail.is_manager,
positions: detail.positions,
status: detail.status,
bound_group_count: detail.is_manager ? 12 : 0,
bound_skill_count: detail.is_manager ? 0 : detail.skill_ids.length,
updated_at: '2026-05-20 19:05:00',
available_actions: detail.is_manager ? ['detail', 'edit'] : ['detail', 'edit', detail.status === 'enable' ? 'disable' : 'enable', 'delete'],
};
}
export interface AgentListRouteState {
scenario: string;
keyword: string;
positionId?: string;
status: 'all' | 'enable' | 'disable';
page: number;
pageSize: number;
detail?: string;
refreshToken?: string;
}
export function readAgentListRouteState(searchParams: URLSearchParams): AgentListRouteState {
const page = Number(searchParams.get('page') ?? '1');
const pageSize = Number(searchParams.get('pageSize') ?? '10');
const status = searchParams.get('status');
return {
scenario: searchParams.get('scenario') ?? 'normal',
keyword: searchParams.get('keyword') ?? '',
positionId: searchParams.get('positionId') ?? undefined,
status: status === 'enable' || status === 'disable' ? status : 'all',
page: Number.isFinite(page) && page > 0 ? page : 1,
pageSize: Number.isFinite(pageSize) && pageSize > 0 ? pageSize : 10,
detail: searchParams.get('detail') ?? undefined,
refreshToken: searchParams.get('refreshToken') ?? undefined,
};
}
export function buildAgentListSearch(state: Partial<AgentListRouteState>) {
const searchParams = new URLSearchParams();
if (state.scenario && state.scenario !== 'normal') searchParams.set('scenario', state.scenario);
if (state.keyword) searchParams.set('keyword', state.keyword);
if (state.positionId) searchParams.set('positionId', state.positionId);
if (state.status && state.status !== 'all') searchParams.set('status', state.status);
if (state.page && state.page !== 1) searchParams.set('page', String(state.page));
if (state.pageSize && state.pageSize !== 10) searchParams.set('pageSize', String(state.pageSize));
if (state.detail) searchParams.set('detail', state.detail);
if (state.refreshToken) searchParams.set('refreshToken', state.refreshToken);
const query = searchParams.toString();
return query ? `?${query}` : '';
}
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { App } from '../../App';
function renderChannelCodes(path = '/channel-codes') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
describe('Channel code create page', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('renders the create page with header, fields and action buttons', () => {
renderChannelCodes('/channel-codes/new');
expect(screen.getByRole('heading', { name: '新增员工渠道活码' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '返回' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '取消' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '保存' })).toBeInTheDocument();
});
it('renders form fields: name, position, channel code, employee, agents, description, welcome message, status', () => {
renderChannelCodes('/channel-codes/new');
expect(screen.getByLabelText('活码名称')).toBeInTheDocument();
expect(screen.getByRole('combobox', { name: '对应岗位' })).toBeInTheDocument();
expect(screen.getByText('渠道编码')).toBeInTheDocument();
expect(screen.getByText('承接员工')).toBeInTheDocument();
expect(screen.getByText('关联 Agent')).toBeInTheDocument();
expect(screen.getByLabelText('活码描述')).toBeInTheDocument();
expect(screen.getByLabelText('自动欢迎语')).toBeInTheDocument();
expect(screen.getByRole('switch', { name: '状态' })).toBeInTheDocument();
});
it('shows validation errors for required fields', () => {
renderChannelCodes('/channel-codes/new');
fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByText('请输入活码名称')).toBeInTheDocument();
});
it('validates max length for fields', () => {
renderChannelCodes('/channel-codes/new');
// Input has maxLength=50, so text is truncated automatically
// We test that saving with truncated value works
const longText = '这是一个非常长的活码名称超过了五十个字的限制这是一个非常长的活码名称超过了五十个字的限制';
fireEvent.change(screen.getByLabelText('活码名称'), { target: { value: longText } });
// The input should have truncated the text due to maxLength
const input = screen.getByLabelText('活码名称');
expect((input as HTMLInputElement).value.length).toBeLessThanOrEqual(50);
});
it('validates description max length', () => {
renderChannelCodes('/channel-codes/new');
const longDescription = Array(201).fill('字').join('');
fireEvent.change(screen.getByLabelText('活码名称'), { target: { value: '测试活码' } });
fireEvent.change(screen.getByLabelText('活码描述'), { target: { value: longDescription } });
fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByText('活码描述最多200字')).toBeInTheDocument();
});
it('validates welcome message max length', () => {
renderChannelCodes('/channel-codes/new');
const longMessage = Array(501).fill('字').join('');
fireEvent.change(screen.getByLabelText('活码名称'), { target: { value: '测试活码' } });
fireEvent.change(screen.getByLabelText('自动欢迎语'), { target: { value: longMessage } });
fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByText('自动欢迎语最多500字')).toBeInTheDocument();
});
it('default status is disable', () => {
renderChannelCodes('/channel-codes/new');
const statusSwitch = screen.getByRole('switch', { name: '状态' });
expect(statusSwitch).not.toBeChecked();
});
it('cancel returns to list without saving', () => {
renderChannelCodes('/channel-codes/new');
fireEvent.change(screen.getByLabelText('活码名称'), { target: { value: '测试活码' } });
fireEvent.click(screen.getByRole('button', { name: '取消' }));
expect(screen.getByRole('heading', { name: '渠道活码管理' })).toBeInTheDocument();
});
it('shows save error message and stays on page when save fails', () => {
renderChannelCodes('/channel-codes/1/edit?scenario=saveError');
// Edit existing record to trigger save
fireEvent.change(screen.getByLabelText('活码名称'), { target: { value: '更新后的活码名称' } });
fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByRole('alert', { name: '保存失败,请重试' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: '编辑员工渠道活码' })).toBeInTheDocument();
});
});
describe('Channel code edit page', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('renders the edit page with existing data', () => {
renderChannelCodes('/channel-codes/1/edit');
expect(screen.getByRole('heading', { name: '编辑员工渠道活码' })).toBeInTheDocument();
expect(screen.getByDisplayValue('店销顾问渠道活码')).toBeInTheDocument();
});
it('position and derived fields are readonly or display-only', () => {
renderChannelCodes('/channel-codes/1/edit');
expect(screen.getByLabelText('对应岗位')).toBeDisabled();
expect(screen.getByText('DSC-QR-001')).toBeInTheDocument();
expect(screen.getByText('张小萌(店销主管)')).toBeInTheDocument();
expect(screen.getByText('店销助手Agent、管家Agent')).toBeInTheDocument();
});
it('name, description, welcome message and status are editable', () => {
renderChannelCodes('/channel-codes/1/edit');
fireEvent.change(screen.getByLabelText('活码名称'), { target: { value: '更新后的活码名称' } });
fireEvent.change(screen.getByLabelText('活码描述'), { target: { value: '更新后的描述' } });
expect(screen.getByDisplayValue('更新后的活码名称')).toBeInTheDocument();
expect(screen.getByDisplayValue('更新后的描述')).toBeInTheDocument();
});
it('shows not found state for non-existent record', () => {
renderChannelCodes('/channel-codes/999/edit');
expect(screen.getByRole('alert', { name: '渠道活码不存在' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '返回列表' })).toBeInTheDocument();
});
it('save success returns to list', () => {
renderChannelCodes('/channel-codes/1/edit');
fireEvent.change(screen.getByLabelText('活码名称'), { target: { value: '更新后的活码名称' } });
fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByRole('heading', { name: '渠道活码管理' })).toBeInTheDocument();
expect(screen.getByText('更新后的活码名称')).toBeInTheDocument();
});
});
\ No newline at end of file \ No newline at end of file
import { useEffect, useMemo, useState } from 'react';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Button, FormItem, Input, Select, StatePlaceholder, Textarea, Switch } from '../../../packages/ui/src';
import {
getChannelCodeRecord,
getEmployeeQRCodes,
getPositionDerivedInfo,
getPositionOptions,
getPositionsWithChannelCode,
saveChannelCodeRecord,
type ChannelCodeMockItem,
type EmployeeConfiguredQRCodesResponse,
} from '../../../packages/contracts/channel-code-mock';
interface ChannelCodeFormState {
code_name: string;
position_code: string;
description: string;
welcome_message: string;
status: 'enable' | 'disable';
}
interface ChannelCodeFormErrors {
code_name?: string;
position_code?: string;
description?: string;
welcome_message?: string;
}
interface SaveNotice {
type: 'error';
message: string;
}
function buildInitialFormState(code?: ChannelCodeMockItem): ChannelCodeFormState {
return {
code_name: code?.code_name ?? '',
position_code: code?.position_code ?? '',
description: code?.description ?? '',
welcome_message: code?.welcome_message ?? '',
status: code?.status ?? 'disable',
};
}
interface ChannelCodeListRouteState {
scenario: string;
keyword: string;
positionCode: string;
status: '' | 'enable' | 'disable';
page: number;
pageSize: number;
refreshToken?: string;
}
function readChannelCodeListRouteState(searchParams: URLSearchParams): ChannelCodeListRouteState {
const page = Number(searchParams.get('page') ?? '1');
const pageSize = Number(searchParams.get('pageSize') ?? '10');
return {
scenario: searchParams.get('scenario') ?? 'normal',
keyword: searchParams.get('keyword') ?? '',
positionCode: searchParams.get('positionCode') ?? '',
status: (searchParams.get('status') as '' | 'enable' | 'disable') ?? '',
page: Number.isFinite(page) && page > 0 ? page : 1,
pageSize: Number.isFinite(pageSize) && pageSize > 0 ? pageSize : 10,
refreshToken: searchParams.get('refreshToken') ?? undefined,
};
}
function buildChannelCodeListSearch(state: Partial<ChannelCodeListRouteState>) {
const searchParams = new URLSearchParams();
if (state.scenario && state.scenario !== 'normal') searchParams.set('scenario', state.scenario);
if (state.keyword) searchParams.set('keyword', state.keyword);
if (state.positionCode) searchParams.set('positionCode', state.positionCode);
if (state.status) searchParams.set('status', state.status);
if (state.page && state.page !== 1) searchParams.set('page', String(state.page));
if (state.pageSize && state.pageSize !== 10) searchParams.set('pageSize', String(state.pageSize));
if (state.refreshToken) searchParams.set('refreshToken', state.refreshToken);
const query = searchParams.toString();
return query ? `?${query}` : '';
}
export function ChannelCodeEditorPage({ mode }: { mode: 'create' | 'edit' }) {
const navigate = useNavigate();
const location = useLocation();
const params = useParams();
const [searchParams] = useSearchParams();
const routeState = readChannelCodeListRouteState(searchParams);
const scenario = searchParams.get('scenario') ?? 'normal';
const routeCode = (location.state as { code?: ChannelCodeMockItem } | null)?.code;
const currentCode = useMemo(
() => (mode === 'edit' ? routeCode ?? getChannelCodeRecord(params.codeId) : undefined),
[mode, params.codeId, routeCode],
);
const [form, setForm] = useState<ChannelCodeFormState>(() => buildInitialFormState(currentCode));
const [errors, setErrors] = useState<ChannelCodeFormErrors>({});
const [notice, setNotice] = useState<SaveNotice | null>(null);
const [employeeQRCodesResponse, setEmployeeQRCodesResponse] = useState<EmployeeConfiguredQRCodesResponse | null>(null);
const fieldWidthClassName = 'w-full max-w-[450px]';
const positionOptions = useMemo(() => getPositionOptions(), []);
const positionsWithCodes = useMemo(() => getPositionsWithChannelCode(), []);
const derivedInfo = useMemo(
() => form.position_code ? getPositionDerivedInfo(form.position_code) : undefined,
[form.position_code],
);
// 调用 mock API 获取员工渠道活码信息
useEffect(() => {
if (mode === 'create' && derivedInfo?.employee_id) {
const response = getEmployeeQRCodes(derivedInfo.employee_id);
setEmployeeQRCodesResponse(response ?? null);
} else if (mode === 'edit' && currentCode) {
const positionInfo = getPositionDerivedInfo(currentCode.position_code);
if (positionInfo?.employee_id) {
const response = getEmployeeQRCodes(positionInfo.employee_id);
setEmployeeQRCodesResponse(response ?? null);
}
}
}, [mode, derivedInfo?.employee_id, currentCode]);
const goBackToList = () => {
navigate(`/channel-codes${buildChannelCodeListSearch(routeState)}`);
};
if (mode === 'edit' && !currentCode) {
return (
<StatePlaceholder
state="error"
title="渠道活码不存在"
description="当前渠道活码记录不存在或已被删除"
primaryAction={<Button size="small" onClick={goBackToList}>返回列表</Button>}
/>
);
}
const validate = () => {
const nextErrors: ChannelCodeFormErrors = {};
const trimmedName = form.code_name.trim();
const trimmedDescription = form.description.trim();
const trimmedWelcomeMessage = form.welcome_message.trim();
if (!trimmedName) {
nextErrors.code_name = '请输入活码名称';
} else if (trimmedName.length > 50) {
nextErrors.code_name = '活码名称最多50字';
}
if (mode === 'create') {
if (!form.position_code) {
nextErrors.position_code = '请选择对应岗位';
}
}
if (trimmedDescription.length > 200) {
nextErrors.description = '活码描述最多200字';
}
if (trimmedWelcomeMessage.length > 500) {
nextErrors.welcome_message = '自动欢迎语最多500字';
}
setErrors(nextErrors);
return Object.keys(nextErrors).length === 0;
};
const handleSave = () => {
setNotice(null);
if (!validate()) {
return;
}
if (scenario === 'saveError') {
setNotice({ type: 'error', message: '保存失败,请重试' });
return;
}
saveChannelCodeRecord({
codeId: currentCode?.code_id,
code_name: form.code_name,
position_code: mode === 'create' ? form.position_code : undefined,
description: form.description,
welcome_message: form.welcome_message,
status: form.status,
});
navigate(
`/channel-codes${buildChannelCodeListSearch({
...routeState,
refreshToken: String(Date.now()),
})}`,
);
};
const availablePositionOptions = positionOptions.filter(
(pos) => mode === 'edit' || !positionsWithCodes.includes(pos.code),
);
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)]">
{mode === 'create' ? '新增员工渠道活码' : '编辑员工渠道活码'}
</h2>
<p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">
{mode === 'create' ? '创建新的员工渠道活码' : '编辑已有员工渠道活码信息'}
</p>
</div>
</div>
<div className="flex items-center gap-3">
<Button variant="outline" onClick={goBackToList}>取消</Button>
<Button variant="primary" onClick={handleSave}>保存</Button>
</div>
</header>
{notice ? (
<div
className="rounded-[var(--gl-radius-sm)] border border-[var(--gl-color-danger-border)] bg-[var(--gl-color-danger-bg)] px-4 py-3 text-sm text-[var(--gl-color-danger-text)]"
role="alert"
aria-label={notice.message}
>
{notice.message}
</div>
) : null}
<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">
<FormItem label="活码名称" layout="horizontal" required={mode === 'create'} error={errors.code_name}>
<Input
aria-label="活码名称"
className={fieldWidthClassName}
maxLength={50}
showCount
value={form.code_name}
onChange={(value) => setForm((current) => ({ ...current, code_name: value }))}
/>
</FormItem>
<FormItem label="对应岗位" layout="horizontal" required={mode === 'create'} error={errors.position_code}>
{mode === 'edit' ? (
<Input
aria-label="对应岗位"
className={fieldWidthClassName}
disabled
value={currentCode?.position_name ?? ''}
/>
) : (
<Select
aria-label="对应岗位"
className={fieldWidthClassName}
options={availablePositionOptions.map((pos) => ({
value: pos.code,
label: pos.name,
disabled: positionsWithCodes.includes(pos.code),
}))}
placeholder="请选择岗位"
value={form.position_code}
onChange={(value) => setForm((current) => ({ ...current, position_code: value ?? '' }))}
/>
)}
</FormItem>
<FormItem label="渠道编码" layout="horizontal">
<div className={fieldWidthClassName}>
{derivedInfo?.channel_code ?? currentCode?.channel_code ?? (
mode === 'create' && !form.position_code ? (
<span className="text-sm text-[var(--gl-color-text-secondary)]">选择岗位后自动生成</span>
) : null
)}
</div>
</FormItem>
<FormItem label="承接员工" layout="horizontal">
<div className={fieldWidthClassName}>
{employeeQRCodesResponse ? (
`${employeeQRCodesResponse.employee_name}(${employeeQRCodesResponse.employee_role_text})`
) : currentCode ? (
`${currentCode.employee_name}(${currentCode.employee_role_text})`
) : (
mode === 'create' && !form.position_code ? (
<span className="text-sm text-[var(--gl-color-text-secondary)]">选择岗位后自动展示</span>
) : null
)}
</div>
</FormItem>
<FormItem label="关联 Agent" layout="horizontal">
<div className={fieldWidthClassName}>
{derivedInfo?.agent_names?.join('、') ?? currentCode?.agent_names?.join('、') ?? (
mode === 'create' && !form.position_code ? (
<span className="text-sm text-[var(--gl-color-text-secondary)]">选择岗位后自动展示</span>
) : null
)}
</div>
</FormItem>
<FormItem label="活码描述" layout="horizontal" error={errors.description}>
<Textarea
aria-label="活码描述"
className={fieldWidthClassName}
maxLength={200}
rows={3}
showCount
value={form.description}
onChange={(value) => setForm((current) => ({ ...current, description: value }))}
/>
</FormItem>
<FormItem label="自动欢迎语" layout="horizontal" error={errors.welcome_message}>
<Textarea
aria-label="自动欢迎语"
className={fieldWidthClassName}
maxLength={500}
rows={3}
showCount
value={form.welcome_message}
onChange={(value) => setForm((current) => ({ ...current, welcome_message: value }))}
/>
</FormItem>
<FormItem label="状态" layout="horizontal" required>
<Switch
aria-label="状态"
checked={form.status === 'enable'}
onChange={(checked) => setForm((current) => ({ ...current, status: checked ? 'enable' : 'disable' }))}
/>
</FormItem>
</div>
</div>
</section>
);
}
\ No newline at end of file \ No newline at end of file
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { App } from '../../App';
function renderChannelCodes(path = '/channel-codes') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
describe('Channel code list page', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('renders the page header with title and primary action', () => {
renderChannelCodes();
expect(screen.getByRole('heading', { name: '渠道活码管理' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '新增员工渠道活码' })).toBeInTheDocument();
});
it('renders search area with keyword input, position filter, status filter, search and reset buttons', () => {
renderChannelCodes();
expect(screen.getByText('活码名称:')).toBeInTheDocument();
expect(screen.getByLabelText('活码名称')).toBeInTheDocument();
expect(screen.getByText('对应岗位:')).toBeInTheDocument();
expect(screen.getByRole('combobox', { name: '对应岗位' })).toBeInTheDocument();
expect(screen.getByText('状态:')).toBeInTheDocument();
expect(screen.getByRole('combobox', { name: '状态' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '搜索' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '重置' })).toBeInTheDocument();
});
it('renders table columns: name, position, channel code, employee, agents, status, created time, actions', () => {
renderChannelCodes();
expect(screen.getByText('活码名称')).toBeInTheDocument();
expect(screen.getByText('对应岗位')).toBeInTheDocument();
expect(screen.getByText('渠道编码')).toBeInTheDocument();
expect(screen.getByText('承接员工')).toBeInTheDocument();
expect(screen.getByText('关联 Agent')).toBeInTheDocument();
expect(screen.getByText('状态')).toBeInTheDocument();
expect(screen.getByText('创建时间')).toBeInTheDocument();
expect(screen.getByText('操作')).toBeInTheDocument();
});
it('supports keyword search and reset', () => {
renderChannelCodes();
fireEvent.change(screen.getByLabelText('活码名称'), { target: { value: '售后' } });
fireEvent.click(screen.getByRole('button', { name: '搜索' }));
expect(screen.getByText('售后客服渠道活码')).toBeInTheDocument();
expect(screen.queryByText('店销顾问渠道活码')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '重置' }));
expect(screen.getByLabelText('活码名称')).toHaveValue('');
expect(screen.getByText('店销顾问渠道活码')).toBeInTheDocument();
});
it('supports position filter dropdown', () => {
renderChannelCodes();
const positionSelect = screen.getByRole('combobox', { name: '对应岗位' });
expect(positionSelect).toBeInTheDocument();
fireEvent.click(positionSelect);
// Dropdown should open - just verify the select is interactive
expect(positionSelect).not.toHaveAttribute('aria-disabled', 'true');
});
it('supports status filter dropdown', () => {
renderChannelCodes();
const statusSelect = screen.getByRole('combobox', { name: '状态' });
expect(statusSelect).toBeInTheDocument();
fireEvent.click(statusSelect);
// Dropdown should open - just verify the select is interactive
expect(statusSelect).not.toHaveAttribute('aria-disabled', 'true');
});
it('renders pagination with total count', () => {
renderChannelCodes();
expect(screen.getByText('共 5 条')).toBeInTheDocument();
expect(screen.getByRole('combobox', { name: '每页条数' })).toBeInTheDocument();
});
it('renders row actions: view, edit, enable/disable', () => {
renderChannelCodes();
const firstRow = screen.getByRole('row', { name: /店销顾问渠道活码/ });
expect(within(firstRow).getByRole('button', { name: '查看店销顾问渠道活码' })).toBeInTheDocument();
expect(within(firstRow).getByRole('button', { name: '编辑店销顾问渠道活码' })).toBeInTheDocument();
expect(within(firstRow).getByRole('button', { name: '停用店销顾问渠道活码' })).toBeInTheDocument();
});
it('shows empty state when no data', () => {
renderChannelCodes('/channel-codes?scenario=empty');
expect(screen.getByText('当前还没有渠道活码')).toBeInTheDocument();
});
it('shows filtered empty state with reset action', () => {
renderChannelCodes('/channel-codes?keyword=nonexistent');
const emptyTexts = screen.getAllByText('未找到匹配结果');
expect(emptyTexts.length).toBeGreaterThan(0);
expect(screen.getByRole('button', { name: '重置搜索' })).toBeInTheDocument();
});
it('shows load error state with retry button', () => {
renderChannelCodes('/channel-codes?scenario=loadError');
expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '重试' }));
expect(screen.getByText('店销顾问渠道活码')).toBeInTheDocument();
});
});
\ No newline at end of file \ No newline at end of file
import { useMemo, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button, Input, Modal, Pagination, Select, StatePlaceholder, Table } from '../../../packages/ui/src';
import {
channelCodeMockFixtures,
getChannelCodeListPage,
updateChannelCodeStatus,
type ChannelCodeMockItem,
getPositionOptions,
getPositionsWithChannelCode,
} from '../../../packages/contracts/channel-code-mock';
import { useMessage } from '../../hooks/useMessage';
import { ChannelCodeViewDrawer } from './ChannelCodeViewDrawer';
interface ChannelCodeListRouteState {
scenario: string;
keyword: string;
positionCode: string;
status: '' | 'enable' | 'disable';
page: number;
pageSize: number;
refreshToken?: string;
}
function readChannelCodeListRouteState(searchParams: URLSearchParams): ChannelCodeListRouteState {
const page = Number(searchParams.get('page') ?? '1');
const pageSize = Number(searchParams.get('pageSize') ?? '10');
return {
scenario: searchParams.get('scenario') ?? 'normal',
keyword: searchParams.get('keyword') ?? '',
positionCode: searchParams.get('positionCode') ?? '',
status: (searchParams.get('status') as '' | 'enable' | 'disable') ?? '',
page: Number.isFinite(page) && page > 0 ? page : 1,
pageSize: Number.isFinite(pageSize) && pageSize > 0 ? pageSize : 10,
refreshToken: searchParams.get('refreshToken') ?? undefined,
};
}
function buildChannelCodeListSearch(state: Partial<ChannelCodeListRouteState>) {
const searchParams = new URLSearchParams();
if (state.scenario && state.scenario !== 'normal') searchParams.set('scenario', state.scenario);
if (state.keyword) searchParams.set('keyword', state.keyword);
if (state.positionCode) searchParams.set('positionCode', state.positionCode);
if (state.status) searchParams.set('status', state.status);
if (state.page && state.page !== 1) searchParams.set('page', String(state.page));
if (state.pageSize && state.pageSize !== 10) searchParams.set('pageSize', String(state.pageSize));
if (state.refreshToken) searchParams.set('refreshToken', state.refreshToken);
const query = searchParams.toString();
return query ? `?${query}` : '';
}
function getFixtureByScenario(scenario: string) {
return channelCodeMockFixtures[scenario] ?? channelCodeMockFixtures.normal;
}
export function ChannelCodeListPage() {
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const routeState = readChannelCodeListRouteState(searchParams);
const [keyword, setKeyword] = useState(routeState.keyword);
const message = useMessage();
const [version, setVersion] = useState(0);
const [viewTarget, setViewTarget] = useState<ChannelCodeMockItem | null>(null);
const [statusTarget, setStatusTarget] = useState<{ code: ChannelCodeMockItem; action: 'enable' | 'disable' } | null>(null);
const fixture = getFixtureByScenario(routeState.scenario);
const listSource = routeState.scenario === 'empty' || routeState.scenario === 'qrcodeLoadError' ? fixture.items : undefined;
const positionOptions = useMemo(() => getPositionOptions(), []);
const positionsWithCodes = useMemo(() => getPositionsWithChannelCode(), [version]);
const result = useMemo(
() => getChannelCodeListPage({
keyword: routeState.keyword,
positionCode: routeState.positionCode,
status: routeState.status,
page: routeState.page,
pageSize: routeState.pageSize,
source: listSource,
}),
[listSource, routeState.keyword, routeState.positionCode, routeState.status, routeState.page, routeState.pageSize, routeState.refreshToken, version],
);
const hasFilter = Boolean(routeState.keyword.trim() || routeState.positionCode || routeState.status);
const routeSearch = buildChannelCodeListSearch({
scenario: routeState.scenario,
keyword: routeState.keyword,
positionCode: routeState.positionCode,
status: routeState.status,
page: routeState.page,
pageSize: routeState.pageSize,
});
const submitFilters = () => {
setSearchParams(buildChannelCodeListSearch({
scenario: routeState.scenario,
keyword,
positionCode: routeState.positionCode,
status: routeState.status,
page: 1,
pageSize: routeState.pageSize,
}));
};
const resetFilters = () => {
setKeyword('');
setSearchParams(buildChannelCodeListSearch({
scenario: routeState.scenario,
keyword: '',
positionCode: '',
status: '',
page: 1,
pageSize: routeState.pageSize,
}));
};
const columns = [
{ title: '活码名称', dataIndex: 'code_name' as const },
{ title: '对应岗位', dataIndex: 'position_name' as const },
{ title: '渠道编码', dataIndex: 'channel_code' as const },
{ title: '承接员工', dataIndex: 'employee_name' as const },
{
title: '关联 Agent',
dataIndex: 'agent_names' as const,
render: (value: unknown) => (value as string[]).join('、'),
},
{
title: '状态',
dataIndex: 'status' as const,
render: (value: unknown) => {
const status = value as 'enable' | 'disable';
return status === 'enable'
? <span className="inline-flex items-center rounded-full bg-[var(--gl-color-success-bg)] px-2 py-0.5 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-0.5 text-xs text-[var(--gl-color-warning-text)]">停用</span>;
},
},
{ title: '创建时间', dataIndex: 'created_at' as const },
{
title: '操作',
key: 'actions',
render: (_: unknown, item: ChannelCodeMockItem) => (
<span className="flex flex-wrap gap-1">
<Button
aria-label={`查看${item.code_name}`}
size="small"
variant="text"
onClick={() => setViewTarget(item)}
>
查看
</Button>
<Button
aria-label={`编辑${item.code_name}`}
size="small"
variant="text"
onClick={() => navigate(`/channel-codes/${item.code_id}/edit${routeSearch}`, { state: { code: item } })}
>
编辑
</Button>
{item.operations.includes('enable') ? (
<Button
aria-label={`启用${item.code_name}`}
size="small"
variant="text"
onClick={() => setStatusTarget({ code: item, action: 'enable' })}
>
启用
</Button>
) : null}
{item.operations.includes('disable') ? (
<Button
aria-label={`停用${item.code_name}`}
size="small"
variant="text"
onClick={() => setStatusTarget({ code: item, action: 'disable' })}
>
停用
</Button>
) : null}
</span>
),
},
];
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>
<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>
</div>
<Button variant="primary" onClick={() => navigate(`/channel-codes/new${routeSearch}`)}>新增员工渠道活码</Button>
</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">
<div className="flex items-center gap-4 text-sm">
<div className="flex items-center gap-2">
<span className="shrink-0">活码名称:</span>
<span className="w-[200px]">
<Input
aria-label="活码名称"
className="w-full"
placeholder="搜索活码名称"
value={keyword}
allowClear
onChange={setKeyword}
onKeyDown={(event) => {
if (event.key === 'Enter') submitFilters();
}}
/>
</span>
</div>
<div className="flex items-center gap-2">
<span className="shrink-0">对应岗位:</span>
<span className="w-[200px]">
<Select
aria-label="对应岗位"
className="w-full"
options={[
{ value: '', label: '全部' },
...positionOptions.map((pos) => ({ value: pos.code, label: pos.name })),
]}
value={routeState.positionCode}
onChange={(value) => setSearchParams(buildChannelCodeListSearch({
scenario: routeState.scenario,
keyword: routeState.keyword,
positionCode: value,
status: routeState.status,
page: 1,
pageSize: routeState.pageSize,
}))}
/>
</span>
</div>
<div className="flex items-center gap-2">
<span className="shrink-0">状态:</span>
<span className="w-[200px]">
<Select
aria-label="状态"
className="w-full"
options={[
{ value: '', label: '全部' },
{ value: 'enable', label: '启用' },
{ value: 'disable', label: '停用' },
]}
value={routeState.status}
onChange={(value) => setSearchParams(buildChannelCodeListSearch({
scenario: routeState.scenario,
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">
{fixture.loadError ? (
<StatePlaceholder
state="error"
title="加载失败"
description="渠道活码列表加载失败,请重试"
primaryAction={<Button size="small" onClick={() => setSearchParams(buildChannelCodeListSearch({ ...routeState, scenario: 'normal' }))}>重试</Button>}
/>
) : (
<>
<Table
rowKey="code_id"
columns={columns}
dataSource={result.items}
empty={{
description: hasFilter ? '未找到匹配结果' : '当前还没有渠道活码',
action: hasFilter ? <Button size="small" onClick={resetFilters}>重置搜索</Button> : undefined,
}}
/>
{result.items.length === 0 && hasFilter ? <StatePlaceholder state="filtered-empty" /> : null}
<Pagination
current={routeState.page}
pageSize={routeState.pageSize}
total={result.total}
pageSizeOptions={[2, 10, 20]}
onChange={(page, pageSize) => {
setSearchParams(buildChannelCodeListSearch({
scenario: routeState.scenario,
keyword: routeState.keyword,
positionCode: routeState.positionCode,
status: routeState.status,
page,
pageSize,
}));
}}
/>
</>
)}
</div>
<ChannelCodeViewDrawer
open={Boolean(viewTarget)}
code={viewTarget}
onClose={() => setViewTarget(null)}
/>
<Modal
open={Boolean(statusTarget)}
title={statusTarget ? `确认${statusTarget.action === 'enable' ? '启用' : '停用'}"${statusTarget.code.code_name}"?` : ''}
onCancel={() => setStatusTarget(null)}
onOk={() => {
if (!statusTarget) return;
const result = updateChannelCodeStatus(
statusTarget.code.code_id,
statusTarget.action,
fixture.statusBlockError ? 'statusBlockError' : 'normal',
);
if (result.blocked) {
message.error(result.message ?? '操作被阻断');
setStatusTarget(null);
return;
}
message.success(`${statusTarget.action === 'enable' ? '启用' : '停用'}成功`);
setStatusTarget(null);
setVersion((current) => current + 1);
}}
>
<p className="m-0 max-w-[360px] leading-[var(--gl-line-height-md)] text-[var(--gl-color-text-secondary)]">
{statusTarget?.action === 'enable'
? '启用后渠道活码将恢复可用,用户可以继续扫码添加。'
: '停用后渠道活码不可继续扫码使用,请确认是否继续。'}
</p>
</Modal>
</section>
);
}
\ No newline at end of file \ No newline at end of file
import { cleanup, render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { App } from '../../App';
function renderChannelCodes(path = '/channel-codes') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
describe('Channel code routes and navigation', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('renders the list route at /channel-codes', () => {
renderChannelCodes();
expect(screen.getByRole('heading', { name: '渠道活码管理' })).toBeInTheDocument();
});
it('renders the new route at /channel-codes/new', () => {
renderChannelCodes('/channel-codes/new');
expect(screen.getByRole('heading', { name: '新增员工渠道活码' })).toBeInTheDocument();
});
it('renders the edit route at /channel-codes/:codeId/edit', () => {
renderChannelCodes('/channel-codes/1/edit');
expect(screen.getByRole('heading', { name: '编辑员工渠道活码' })).toBeInTheDocument();
});
it('shows navigation entry under Agent群管理 group', () => {
renderChannelCodes();
expect(screen.getByRole('button', { name: '渠道活码' })).toBeInTheDocument();
});
it('marks navigation entry as active when on channel-codes routes', () => {
renderChannelCodes();
expect(screen.getByRole('button', { name: '渠道活码' })).toHaveAttribute('aria-current', 'page');
});
});
\ No newline at end of file \ No newline at end of file
import { fireEvent, render, screen, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { App } from '../../App';
function renderChannelCodes(path = '/channel-codes') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
describe('Channel code enable/disable operations', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('shows enable confirmation dialog', () => {
renderChannelCodes();
// Find a disabled row (live_ops has status 'disable')
const disabledRow = screen.getByRole('row', { name: /直播运营渠道活码/ });
fireEvent.click(within(disabledRow).getByRole('button', { name: '启用直播运营渠道活码' }));
expect(screen.getByRole('dialog', { name: '确认启用"直播运营渠道活码"?' })).toBeInTheDocument();
expect(screen.getByText('启用后渠道活码将恢复可用,用户可以继续扫码添加。')).toBeInTheDocument();
});
it('shows disable confirmation dialog', () => {
renderChannelCodes();
// Find an enabled row (store_sales has status 'enable')
const enabledRow = screen.getByRole('row', { name: /店销顾问渠道活码/ });
fireEvent.click(within(enabledRow).getByRole('button', { name: '停用店销顾问渠道活码' }));
expect(screen.getByRole('dialog', { name: '确认停用"店销顾问渠道活码"?' })).toBeInTheDocument();
expect(screen.getByText('停用后渠道活码不可继续扫码使用,请确认是否继续。')).toBeInTheDocument();
});
it('cancels enable operation without changing status', () => {
renderChannelCodes();
const disabledRow = screen.getByRole('row', { name: /直播运营渠道活码/ });
fireEvent.click(within(disabledRow).getByRole('button', { name: '启用直播运营渠道活码' }));
fireEvent.click(screen.getByRole('button', { name: '取消' }));
expect(screen.queryByRole('dialog', { name: '确认启用' })).not.toBeInTheDocument();
// Status should remain unchanged
expect(within(disabledRow).getByText('停用')).toBeInTheDocument();
});
it('enables successfully and shows success message', () => {
renderChannelCodes();
const disabledRow = screen.getByRole('row', { name: /直播运营渠道活码/ });
fireEvent.click(within(disabledRow).getByRole('button', { name: '启用直播运营渠道活码' }));
fireEvent.click(screen.getByRole('button', { name: '确定' }));
expect(screen.queryByRole('dialog', { name: '确认启用' })).not.toBeInTheDocument();
expect(screen.getByRole('status', { name: '启用成功' })).toBeInTheDocument();
expect(within(disabledRow).getByText('启用')).toBeInTheDocument();
});
it('disables successfully and shows success message', () => {
renderChannelCodes('/channel-codes?scenario=normal');
const enabledRow = screen.getByRole('row', { name: /私域增长渠道活码/ });
fireEvent.click(within(enabledRow).getByRole('button', { name: '停用私域增长渠道活码' }));
fireEvent.click(screen.getByRole('button', { name: '确定' }));
expect(screen.queryByRole('dialog', { name: '确认停用' })).not.toBeInTheDocument();
expect(screen.getByRole('status', { name: '停用成功' })).toBeInTheDocument();
expect(within(enabledRow).getByText('停用')).toBeInTheDocument();
});
it('blocks disable with business error message', () => {
renderChannelCodes('/channel-codes?scenario=statusBlockError');
const enabledRow = screen.getByRole('row', { name: /店销顾问渠道活码/ });
fireEvent.click(within(enabledRow).getByRole('button', { name: '停用店销顾问渠道活码' }));
fireEvent.click(screen.getByRole('button', { name: '确定' }));
// The error message should be shown
const alert = screen.getByRole('alert');
expect(alert).toHaveTextContent('官网展示中');
// Status should remain enabled
expect(within(enabledRow).getByText('启用')).toBeInTheDocument();
});
});
\ No newline at end of file \ No newline at end of file
import { fireEvent, render, screen, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { App } from '../../App';
function renderChannelCodes(path = '/channel-codes') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
describe('Channel code view drawer', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('opens drawer when clicking view action', () => {
renderChannelCodes();
const firstRow = screen.getByRole('row', { name: /店销顾问渠道活码/ });
fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
expect(screen.getByRole('dialog', { name: '店销顾问渠道活码' })).toBeInTheDocument();
});
it('shows all detail fields in drawer', () => {
renderChannelCodes();
fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
const drawer = screen.getByRole('dialog', { name: '店销顾问渠道活码' });
expect(within(drawer).getByText('对应岗位')).toBeInTheDocument();
expect(within(drawer).getByText('渠道编码')).toBeInTheDocument();
expect(within(drawer).getByText('承接员工')).toBeInTheDocument();
expect(within(drawer).getByText('关联 Agent')).toBeInTheDocument();
expect(within(drawer).getByText('状态')).toBeInTheDocument();
expect(within(drawer).getByText('活码描述')).toBeInTheDocument();
expect(within(drawer).getByText('自动欢迎语')).toBeInTheDocument();
});
it('shows QR code image', () => {
renderChannelCodes();
fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
expect(screen.getByRole('img', { name: '渠道活码二维码' })).toBeInTheDocument();
});
it('closes drawer and preserves list context', () => {
renderChannelCodes();
fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
expect(screen.getByRole('dialog', { name: '店销顾问渠道活码' })).toBeInTheDocument();
// Drawer close button is aria-label="关闭{title}"
const closeButton = screen.getByRole('button', { name: '关闭店销顾问渠道活码' });
fireEvent.click(closeButton);
expect(screen.queryByRole('dialog', { name: '店销顾问渠道活码' })).not.toBeInTheDocument();
// List should still be visible
expect(screen.getByRole('heading', { name: '渠道活码管理' })).toBeInTheDocument();
expect(screen.getByText('店销顾问渠道活码')).toBeInTheDocument();
});
it('closes drawer via bottom close button', () => {
renderChannelCodes();
fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
expect(screen.getByRole('dialog', { name: '店销顾问渠道活码' })).toBeInTheDocument();
const drawer = screen.getByRole('dialog', { name: '店销顾问渠道活码' });
// Footer close button uses "关闭" as text
const footerCloseButton = within(drawer).getByRole('button', { name: '关闭' });
fireEvent.click(footerCloseButton);
expect(screen.queryByRole('dialog', { name: '店销顾问渠道活码' })).not.toBeInTheDocument();
});
it('shows agent names as tags with unified color', () => {
renderChannelCodes();
fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
const drawer = screen.getByRole('dialog', { name: '店销顾问渠道活码' });
// Should display agent names as tags
expect(within(drawer).getByText('店销助手Agent')).toBeInTheDocument();
expect(within(drawer).getByText('管家Agent')).toBeInTheDocument();
});
it('shows QR code load error state', () => {
renderChannelCodes('/channel-codes?scenario=qrcodeLoadError');
fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
// Should show error state for QR code
expect(screen.getByText('二维码加载失败')).toBeInTheDocument();
// Other details should still be visible
const drawer = screen.getByRole('dialog', { name: '店销顾问渠道活码' });
expect(within(drawer).getByText('对应岗位')).toBeInTheDocument();
});
});
\ No newline at end of file \ No newline at end of file
import { useState, useEffect } from 'react';
import { Drawer, StatePlaceholder, Button, Tag } from '../../../packages/ui/src';
import { type ChannelCodeMockItem } from '../../../packages/contracts/channel-code-mock';
interface ChannelCodeViewDrawerProps {
open: boolean;
code: ChannelCodeMockItem | null;
onClose: () => void;
}
export function ChannelCodeViewDrawer({ open, code, onClose }: ChannelCodeViewDrawerProps) {
const [qrcodeError, setQrcodeError] = useState(false);
useEffect(() => {
if (!open) {
setQrcodeError(false);
}
}, [open]);
if (!code) return null;
const handleQrcodeError = () => {
setQrcodeError(true);
};
const statusText = code.status === 'enable' ? '启用' : '停用';
const statusClass = code.status === 'enable'
? 'inline-flex items-center rounded-full bg-[var(--gl-color-success-bg)] px-2 py-0.5 text-xs text-[var(--gl-color-success-text)]'
: 'inline-flex items-center rounded-full bg-[var(--gl-color-warning-bg)] px-2 py-0.5 text-xs text-[var(--gl-color-warning-text)]';
return (
<Drawer
open={open}
title={code.code_name}
onClose={onClose}
width={480}
footer={
<div className="flex items-center justify-end">
<Button variant="outline" onClick={onClose}>关闭</Button>
</div>
}
>
<div className="grid gap-4">
<div className="grid gap-2">
<div className="grid grid-cols-[120px_1fr] gap-2 text-sm">
<span className="text-[var(--gl-color-text-secondary)]">对应岗位</span>
<span>{code.position_name}</span>
</div>
<div className="grid grid-cols-[120px_1fr] gap-2 text-sm">
<span className="text-[var(--gl-color-text-secondary)]">渠道编码</span>
<span>{code.channel_code}</span>
</div>
<div className="grid grid-cols-[120px_1fr] gap-2 text-sm">
<span className="text-[var(--gl-color-text-secondary)]">承接员工</span>
<span>{code.employee_name}({code.employee_role_text})</span>
</div>
<div className="grid grid-cols-[120px_1fr] gap-2 text-sm">
<span className="text-[var(--gl-color-text-secondary)]">关联 Agent</span>
<div className="flex flex-wrap gap-1">
{code.agent_names.map((name) => (
<Tag key={name} status="info">{name}</Tag>
))}
</div>
</div>
<div className="grid grid-cols-[120px_1fr] gap-2 text-sm">
<span className="text-[var(--gl-color-text-secondary)]">状态</span>
<span className={statusClass}>{statusText}</span>
</div>
<div className="grid grid-cols-[120px_1fr] gap-2 text-sm">
<span className="text-[var(--gl-color-text-secondary)]">活码描述</span>
<span>{code.description || '-'}</span>
</div>
<div className="grid grid-cols-[120px_1fr] gap-2 text-sm">
<span className="text-[var(--gl-color-text-secondary)]">自动欢迎语</span>
<span>{code.welcome_message || '-'}</span>
</div>
</div>
<div className="border-t border-[var(--gl-color-border-secondary)] pt-4">
<span className="block mb-2 text-sm text-[var(--gl-color-text-secondary)]">二维码图片</span>
{qrcodeError || code.qrcode_load_error ? (
<StatePlaceholder
state="error"
title="二维码加载失败"
description="二维码图片加载失败,请刷新重试"
/>
) : (
<img
alt="渠道活码二维码"
className="w-[200px] h-[200px] rounded-[var(--gl-radius-sm)] border border-[var(--gl-color-border-secondary)]"
src={code.qrcode_url}
onError={handleQrcodeError}
/>
)}
</div>
</div>
</Drawer>
);
}
\ No newline at end of file \ No newline at end of file
...@@ -10,13 +10,13 @@ describe('ComponentsDemoPage', () => { ...@@ -10,13 +10,13 @@ describe('ComponentsDemoPage', () => {
expect(screen.getByRole('heading', { name: '组件库 Demo' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '组件库 Demo' })).toBeInTheDocument();
expect(screen.getByText('基础交互')).toBeInTheDocument(); expect(screen.getByText('基础交互')).toBeInTheDocument();
expect(screen.getByText('选择与日期')).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '选择与日期' })).toBeInTheDocument();
expect(screen.getByText('表格与分页')).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '表格与分页' })).toBeInTheDocument();
expect(screen.getByText('反馈与浮层')).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '反馈与浮层' })).toBeInTheDocument();
expect(screen.getByText('数据展示')).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '数据展示' })).toBeInTheDocument();
expect(screen.getByText('导航与占位')).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '导航与占位' })).toBeInTheDocument();
expect(screen.getByText('颜色能力')).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '颜色能力' })).toBeInTheDocument();
expect(screen.getByText('上传')).toBeInTheDocument(); expect(screen.getByRole('heading', { name: '上传' })).toBeInTheDocument();
expect(screen.getByText('暂无审批记录')).toBeInTheDocument(); expect(screen.getByText('暂无审批记录')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '新建审批' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '新建审批' })).toBeInTheDocument();
expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument(); expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument();
...@@ -25,7 +25,6 @@ describe('ComponentsDemoPage', () => { ...@@ -25,7 +25,6 @@ describe('ComponentsDemoPage', () => {
expect(screen.getByRole('alert', { name: '权限受限' })).toBeInTheDocument(); expect(screen.getByRole('alert', { name: '权限受限' })).toBeInTheDocument();
expect(screen.getByRole('alert', { name: '网络不可用' })).toBeInTheDocument(); expect(screen.getByRole('alert', { name: '网络不可用' })).toBeInTheDocument();
expect(screen.getByText('点击或拖拽业务资料到此上传')).toBeInTheDocument(); expect(screen.getByText('点击或拖拽业务资料到此上传')).toBeInTheDocument();
expect(screen.getByText('图片/视频')).toBeInTheDocument();
expect(screen.getByText('4/20')).toBeInTheDocument(); expect(screen.getByText('4/20')).toBeInTheDocument();
expect(screen.getByText('4/120')).toBeInTheDocument(); expect(screen.getByText('4/120')).toBeInTheDocument();
}); });
...@@ -112,12 +111,8 @@ describe('ComponentsDemoPage', () => { ...@@ -112,12 +111,8 @@ describe('ComponentsDemoPage', () => {
render(<ComponentsDemoPage />); render(<ComponentsDemoPage />);
expect(screen.getByText('product_design_v2.fig')).toBeInTheDocument(); expect(screen.getByText('product_design_v2.fig')).toBeInTheDocument();
expect(screen.getByText('12.40 MB · 已完成')).toBeInTheDocument();
expect(screen.getByText('需求文档.pdf')).toBeInTheDocument(); expect(screen.getByText('需求文档.pdf')).toBeInTheDocument();
expect(screen.getByText('3.20 MB · 上传中 42%')).toBeInTheDocument();
expect(screen.getByText('素材包.zip')).toBeInTheDocument(); expect(screen.getByText('素材包.zip')).toBeInTheDocument();
expect(screen.getByText('网络异常,请重试')).toBeInTheDocument();
expect(screen.getByLabelText('视频')).toBeInTheDocument();
expect(screen.getByText('支持 JPG、PNG、MP4、MOV,图片单张不超过 10MB,视频单个不超过 500MB')).toBeInTheDocument(); expect(screen.getByText('支持 JPG、PNG、MP4、MOV,图片单张不超过 10MB,视频单个不超过 500MB')).toBeInTheDocument();
}); });
......
...@@ -49,6 +49,8 @@ export function ComponentsDemoPage() { ...@@ -49,6 +49,8 @@ export function ComponentsDemoPage() {
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 | undefined>();
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 [showMessage, setShowMessage] = useState(false); const [showMessage, setShowMessage] = useState(false);
const [modalOpen, setModalOpen] = useState(true); const [modalOpen, setModalOpen] = useState(true);
...@@ -115,6 +117,32 @@ export function ComponentsDemoPage() { ...@@ -115,6 +117,32 @@ export function ComponentsDemoPage() {
<h3>选择与日期</h3> <h3>选择与日期</h3>
<div className={styles.grid}> <div className={styles.grid}>
<Select aria-label="负责人" options={[{ label: '张三', value: 'zhang' }, { label: '李四', value: 'li' }]} /> <Select aria-label="负责人" options={[{ label: '张三', value: 'zhang' }, { label: '李四', value: 'li' }]} />
<Select
multiple
aria-label="负责人多选"
allowClear
placeholder="请选择负责人"
value={multiSelectValue}
options={[
{ label: '张三', value: 'zhang' },
{ label: '李四', value: 'li' },
{ label: '王五', value: 'wang' },
]}
onChange={setMultiSelectValue}
/>
<Select
multiple
aria-label="负责人标签多选"
allowClear
placeholder="请选择负责人"
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' }] }]} /> <TreeSelect aria-label="组织" value={treeValue} onChange={setTreeValue} treeData={[{ label: '总部', value: 'root', children: [{ label: '财务部', value: 'finance' }] }]} />
<DatePicker aria-label="计划日期" value={dateValue} onChange={setDateValue} /> <DatePicker aria-label="计划日期" value={dateValue} onChange={setDateValue} />
<DateRangePicker aria-label="周期" /> <DateRangePicker aria-label="周期" />
...@@ -237,9 +265,9 @@ export function ComponentsDemoPage() { ...@@ -237,9 +265,9 @@ export function ComponentsDemoPage() {
title="点击或拖拽业务资料到此上传" title="点击或拖拽业务资料到此上传"
helperText="支持分片断点续传,单文件上限 1GB" helperText="支持分片断点续传,单文件上限 1GB"
files={[ files={[
{ id: 'design', name: 'product_design_v2.fig', size: 12.4 * 1024 * 1024, status: 'done', previewable: true }, { id: 'design', name: 'product_design_v2.fig', size: 12.4 * 1024 * 1024, status: 'success', previewable: true },
{ id: 'doc', name: '需求文档.pdf', size: 3.2 * 1024 * 1024, status: 'uploading', progress: 42 }, { id: 'doc', name: '需求文档.pdf', size: 3.2 * 1024 * 1024, status: 'progress', progress: 42 },
{ id: 'zip', name: '素材包.zip', size: 18.8 * 1024 * 1024, status: 'error', errorMessage: '网络异常,请重试' }, { id: 'zip', name: '素材包.zip', size: 18.8 * 1024 * 1024, status: 'fail', errorMessage: '网络异常,请重试' },
]} ]}
onPreview={() => undefined} onPreview={() => undefined}
onDownload={() => undefined} onDownload={() => undefined}
......
import { useState, useEffect } from 'react';
import { Button, FormItem, Input, MediaWall, Modal, Select } from '../../../packages/ui/src';
import {
saveAgentDisplayConfig,
uploadAgentMedia,
type AgentDisplayConfigMockItem,
} from '../../../packages/contracts/official-site-agent-display-config-mock';
interface EditModalProps {
open: boolean;
agent: AgentDisplayConfigMockItem | null;
tabId: number;
scenario: string;
onCancel: () => void;
onSaveSuccess: () => void;
}
interface EditFormState {
speech_title: string;
speech_content: string;
sort_order: number;
display_status: 'enable' | 'disable';
icon_url: string;
media_url: string;
media_type: 'image' | 'video' | 'gif';
}
interface EditFormErrors {
speech_content?: string;
sort_order?: string;
icon_url?: string;
speech_title?: string;
media_url?: string;
}
export function AgentDisplayConfigEditModal({
open,
agent,
tabId,
scenario,
onCancel,
onSaveSuccess,
}: EditModalProps) {
const [form, setForm] = useState<EditFormState>({
speech_title: '',
speech_content: '',
sort_order: 10,
display_status: 'disable',
icon_url: '',
media_url: '',
media_type: 'image',
});
const [errors, setErrors] = useState<EditFormErrors>({});
const [saving, setSaving] = useState(false);
// Reset form when agent changes
useEffect(() => {
if (agent) {
setForm({
speech_title: agent.speech_title ?? '',
speech_content: agent.speech_content ?? '',
sort_order: agent.sort_order ?? 10,
display_status: agent.display_status ?? 'disable',
icon_url: agent.icon_url ?? '',
media_url: agent.media_url ?? '',
media_type: agent.media_type ?? 'image',
});
setErrors({});
}
}, [agent]);
const validate = () => {
const nextErrors: EditFormErrors = {};
if (!form.icon_url.trim()) {
nextErrors.icon_url = '图标必填';
}
if (!form.speech_title.trim()) {
nextErrors.speech_title = 'Agent名称必填';
}
if (!form.speech_content.trim()) {
nextErrors.speech_content = 'Agent概述必填';
} else if (form.speech_content.length > 100) {
nextErrors.speech_content = 'Agent概述不能超过100字';
}
if (!form.media_url.trim()) {
nextErrors.media_url = '展示素材必填';
}
if (form.sort_order < 0 || form.sort_order > 99 || !Number.isInteger(form.sort_order)) {
nextErrors.sort_order = '排序请输入0-99的整数';
}
setErrors(nextErrors);
return Object.keys(nextErrors).length === 0;
};
const handleSave = async () => {
if (!agent) return;
if (!validate()) return;
setSaving(true);
const result = saveAgentDisplayConfig(tabId, {
agent_id: agent.agent_id,
speech_title: form.speech_title,
speech_content: form.speech_content,
display_status: form.display_status,
sort_order: form.sort_order,
icon_url: form.icon_url,
media_url: form.media_url,
media_type: form.media_type,
}, scenario);
if (result.blocked) {
setSaving(false);
if (result.validation_errors) {
setErrors({
speech_content: result.validation_errors.speech_content,
sort_order: result.validation_errors.sort_order,
});
}
return;
}
setSaving(false);
onSaveSuccess();
};
const handleIconUpload = (files: File[]) => {
if (files.length === 0) return;
const file = files[0];
const result = uploadAgentMedia(
{ name: file.name, size: file.size, type: file.type },
'icon',
scenario,
);
if (!result.blocked) {
setForm((current) => ({
...current,
icon_url: result.url,
}));
}
};
const handleMediaUpload = (files: File[]) => {
if (files.length === 0) return;
const file = files[0];
const result = uploadAgentMedia(
{ name: file.name, size: file.size, type: file.type },
'media',
scenario,
);
if (!result.blocked) {
setForm((current) => ({
...current,
media_url: result.url,
media_type: result.type,
}));
}
};
const handleRemoveIcon = () => {
setForm((current) => ({
...current,
icon_url: '',
}));
};
const handleRemoveMedia = () => {
setForm((current) => ({
...current,
media_url: '',
media_type: 'image',
}));
};
if (!agent) return null;
const iconItems: { id: string; type: 'image'; src: string; alt: string }[] = form.icon_url
? [{ id: 'icon', type: 'image' as const, src: form.icon_url, alt: '' }]
: [];
const mediaItems: { id: string; type: 'image' | 'video'; src: string; alt: string }[] = form.media_url
? [{ id: 'media', type: (agent.media_type === 'video' ? 'video' : 'image') as 'image' | 'video', src: form.media_url, alt: '' }]
: [];
return (
<Modal
open={open}
title={`编辑展示配置 - ${agent.speech_title}`}
onCancel={onCancel}
onOk={handleSave}
footer={
<div className="flex justify-end gap-3">
<Button variant="outline" onClick={onCancel} disabled={saving}>
取消
</Button>
<Button variant="primary" onClick={handleSave} disabled={saving}>
{saving ? '保存中...' : '确定'}
</Button>
</div>
}
>
<div className="grid gap-6 py-4">
<FormItem label="图标" layout="horizontal" required error={errors.icon_url}>
<MediaWall
accept="image/png,image/jpeg,image/jpg,image/gif"
maxCount={1}
multiple={false}
items={iconItems}
helperText="支持 PNG、JPG、GIF,单文件上限 5MB"
onSelectFiles={handleIconUpload}
onRemove={handleRemoveIcon}
/>
</FormItem>
<FormItem label="Agent 名称" layout="horizontal" required error={errors.speech_title}>
<Input
className="w-full max-w-[400px]"
placeholder="请输入Agent名称"
value={form.speech_title}
onChange={(value) => setForm((current) => ({ ...current, speech_title: value }))}
/>
</FormItem>
<FormItem label="Agent 概述" layout="horizontal" required error={errors.speech_content}>
<Input
className="w-full max-w-[400px]"
placeholder="请输入Agent概述"
value={form.speech_content}
onChange={(value) => setForm((current) => ({ ...current, speech_content: value }))}
/>
</FormItem>
<FormItem label="展示素材" layout="horizontal" required error={errors.media_url}>
<MediaWall
accept="image/png,image/jpeg,image/jpg,image/gif,video/mp4"
maxCount={1}
multiple={false}
items={mediaItems}
helperText="支持图片、视频、GIF,推荐 1:1,最大 20MB"
onSelectFiles={handleMediaUpload}
onRemove={handleRemoveMedia}
/>
</FormItem>
<FormItem label="展示排序" layout="horizontal" required error={errors.sort_order}>
<Input
className="w-full max-w-[400px]"
type="number"
min={0}
max={99}
placeholder="请输入展示排序"
value={form.sort_order === undefined || (typeof form.sort_order === 'number' && isNaN(form.sort_order)) ? '' : String(form.sort_order)}
onChange={(value) => setForm((current) => ({
...current,
sort_order: value === '' ? undefined as unknown as number : Number(value),
}))}
/>
</FormItem>
<FormItem label="展示状态" layout="horizontal" required>
<Select
className="w-full max-w-[400px]"
options={[
{ value: 'disable', label: '已下架' },
{ value: 'enable', label: '展示中' },
]}
value={form.display_status}
onChange={(value) => setForm((current) => ({
...current,
display_status: value as 'enable' | 'disable',
}))}
/>
</FormItem>
</div>
</Modal>
);
}
\ No newline at end of file \ No newline at end of file
import { fireEvent, render, screen, within, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { resetAgentDisplayConfigMockState } from '../../../packages/contracts/official-site-agent-display-config-mock';
import { resetOfficialSiteJobTabMockState } from '../../../packages/contracts/official-site-job-tab-mock';
import { resetChannelCodeMockState } from '../../../packages/contracts/channel-code-mock';
import { resetAgentTagMockState } from '../../../packages/contracts/agent-tag-mock';
import { App } from '../../App';
function renderApp(path = '/official-site/job-tabs/1/agents') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
function resetAllMockState() {
window.localStorage.clear();
resetOfficialSiteJobTabMockState();
resetAgentDisplayConfigMockState();
resetChannelCodeMockState();
resetAgentTagMockState();
}
describe('Agent display config edit modal', () => {
beforeEach(() => {
resetAllMockState();
});
describe('modal opening and permissions', () => {
it('opens edit modal when clicking 编辑配置 on enabled agent', async () => {
renderApp();
fireEvent.click(screen.getByRole('button', { name: '编辑配置-复盘Agent' }));
expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByText('编辑展示配置 - 复盘Agent')).toBeInTheDocument();
});
it('disabled agent has no edit button', () => {
renderApp();
expect(screen.queryByRole('button', { name: '编辑配置-质检Agent' })).not.toBeInTheDocument();
});
it('closes modal when clicking cancel', async () => {
renderApp();
fireEvent.click(screen.getByRole('button', { name: '编辑配置-复盘Agent' }));
expect(screen.getByRole('dialog')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '取消' }));
await waitFor(() => {
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
});
});
describe('modal fields', () => {
beforeEach(async () => {
renderApp();
fireEvent.click(screen.getByRole('button', { name: '编辑配置-复盘Agent' }));
});
it('shows 图标 field with upload component', () => {
const modal = screen.getByRole('dialog');
expect(within(modal).getByTestId('form-item-图标')).toBeInTheDocument();
});
it('shows Agent 名称 field (speech_title) editable', () => {
const modal = screen.getByRole('dialog');
expect(within(modal).getByText('Agent 名称')).toBeInTheDocument();
// Agent 名称 should be editable
const nameInput = within(modal).getByDisplayValue('复盘Agent');
expect(nameInput).not.toBeDisabled();
});
it('shows Agent 概述 field (speech_content) editable', () => {
const modal = screen.getByRole('dialog');
expect(within(modal).getByText('Agent 概述')).toBeInTheDocument();
});
it('shows 展示素材 field with upload component', () => {
const modal = screen.getByRole('dialog');
expect(within(modal).getByTestId('form-item-展示素材')).toBeInTheDocument();
});
it('shows 展示排序 field editable', () => {
const modal = screen.getByRole('dialog');
expect(within(modal).getByText('展示排序')).toBeInTheDocument();
});
it('shows 展示状态 field with 已下架 and 展示中 options only', () => {
const modal = screen.getByRole('dialog');
expect(within(modal).getByText('展示状态')).toBeInTheDocument();
// Check that 已停用 is not an option
expect(within(modal).queryByText('已停用')).not.toBeInTheDocument();
});
});
describe('default values for unconfigured agent', () => {
beforeEach(async () => {
renderApp('/official-site/job-tabs/2/agents');
fireEvent.click(screen.getByRole('button', { name: '编辑配置-客诉安抚Agent' }));
});
it('shows default display_status as 已下架 for unconfigured agent', () => {
const modal = screen.getByRole('dialog');
const statusSelect = within(modal).getByDisplayValue('已下架');
expect(statusSelect).toBeInTheDocument();
});
it('shows empty icon for unconfigured agent', () => {
const modal = screen.getByRole('dialog');
// Check that 图标 field exists (MediaWall will show upload button for empty state)
expect(within(modal).getByText('图标')).toBeInTheDocument();
});
it('shows empty speech_content for unconfigured agent', () => {
const modal = screen.getByRole('dialog');
// Find the Agent概述 input by placeholder
const contentInput = within(modal).getByPlaceholderText('请输入Agent概述');
// Check that it's empty
expect(contentInput).toHaveValue('');
});
});
describe('validation', () => {
beforeEach(async () => {
renderApp('/official-site/job-tabs/2/agents');
fireEvent.click(screen.getByRole('button', { name: '编辑配置-客诉安抚Agent' }));
});
it('validates all required fields on empty form', async () => {
const modal = screen.getByRole('dialog');
const confirmBtn = within(modal).getByRole('button', { name: '确定' });
fireEvent.click(confirmBtn);
await waitFor(
() => {
// 图标、Agent概述、展示素材必填 (Agent名称已有默认值,不会触发错误)
expect(within(modal).getByText('图标必填')).toBeInTheDocument();
expect(within(modal).getByText('Agent概述必填')).toBeInTheDocument();
expect(within(modal).getByText('展示素材必填')).toBeInTheDocument();
},
{ timeout: 2000 },
);
});
it('validates speech_content max 100 chars', async () => {
const modal = screen.getByRole('dialog');
const contentInput = within(modal).getByPlaceholderText('请输入Agent概述');
const longContent = '这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容这是一段超过一百字的概述内容';
fireEvent.change(contentInput, { target: { value: longContent } });
fireEvent.click(within(modal).getByRole('button', { name: '确定' }));
await waitFor(
() => {
expect(within(modal).getByText(/不能超过100字/)).toBeInTheDocument();
},
{ timeout: 2000 },
);
});
it('validates sort_order 0-99', async () => {
const modal = screen.getByRole('dialog');
const inputs = within(modal).getAllByRole('spinbutton');
const sortInput = inputs[0];
if (!sortInput) throw new Error('Sort input not found');
fireEvent.change(sortInput, { target: { value: '100' } });
// Fill in required fields
const nameInput = within(modal).getByPlaceholderText('请输入Agent名称');
fireEvent.change(nameInput, { target: { value: '测试名称' } });
const contentInput = within(modal).getByPlaceholderText('请输入Agent概述');
fireEvent.change(contentInput, { target: { value: '测试概述' } });
fireEvent.click(within(modal).getByRole('button', { name: '确定' }));
await waitFor(
() => {
expect(within(modal).getByText(/0-99/)).toBeInTheDocument();
},
{ timeout: 2000 },
);
});
});
});
\ No newline at end of file \ No newline at end of file
import { fireEvent, render, screen, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { resetAgentDisplayConfigMockState } from '../../../packages/contracts/official-site-agent-display-config-mock';
import { resetOfficialSiteJobTabMockState } from '../../../packages/contracts/official-site-job-tab-mock';
import { resetChannelCodeMockState } from '../../../packages/contracts/channel-code-mock';
import { resetAgentTagMockState } from '../../../packages/contracts/agent-tag-mock';
import { App } from '../../App';
function renderApp(path = '/official-site/job-tabs/1/agents') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
function resetAllMockState() {
window.localStorage.clear();
resetOfficialSiteJobTabMockState();
resetAgentDisplayConfigMockState();
resetChannelCodeMockState();
resetAgentTagMockState();
}
describe('Agent display config list', () => {
beforeEach(() => {
resetAllMockState();
});
describe('list rendering', () => {
it('shows Agent name column (speech_title)', () => {
renderApp();
expect(screen.getByRole('columnheader', { name: 'Agent名称' })).toBeInTheDocument();
expect(screen.getByText('复盘Agent')).toBeInTheDocument();
});
it('shows Agent overview column (speech_content)', () => {
renderApp();
expect(screen.getByRole('columnheader', { name: 'Agent概述' })).toBeInTheDocument();
expect(screen.getByText('帮助店销顾问完成每日复盘,分析业绩数据和客户反馈')).toBeInTheDocument();
});
it('shows icon column', () => {
renderApp();
expect(screen.getByRole('columnheader', { name: '图标' })).toBeInTheDocument();
});
it('shows media column', () => {
renderApp();
expect(screen.getByRole('columnheader', { name: '展示素材' })).toBeInTheDocument();
});
it('shows sort order column', () => {
renderApp();
expect(screen.getByRole('columnheader', { name: '排序' })).toBeInTheDocument();
expect(screen.getByText('10')).toBeInTheDocument();
});
it('shows status column (agent_status)', () => {
renderApp();
expect(screen.getByRole('columnheader', { name: '状态' })).toBeInTheDocument();
expect(screen.getAllByText('已上架').length).toBeGreaterThanOrEqual(2);
expect(screen.getByText('已停用')).toBeInTheDocument();
});
it('shows display status column', () => {
renderApp();
expect(screen.getByRole('columnheader', { name: '展示状态' })).toBeInTheDocument();
expect(screen.getByText('展示中')).toBeInTheDocument();
expect(screen.getByText('已下架')).toBeInTheDocument();
});
it('shows action column', () => {
renderApp();
expect(screen.getByRole('columnheader', { name: '操作' })).toBeInTheDocument();
});
});
describe('status mapping and operation permission', () => {
it('shows 展示中/已下架 for enabled agents', () => {
renderApp();
// Agent 101 is enabled with display_status=enable
const rows = screen.getAllByRole('row');
const row101 = rows.find((row) => within(row).queryByText('复盘Agent'));
expect(row101).toBeDefined();
expect(within(row101!).getByText('展示中')).toBeInTheDocument();
// Agent 103 is enabled with display_status=disable
const row103 = rows.find((row) => within(row).queryByText('销售助手Agent'));
expect(row103).toBeDefined();
expect(within(row103!).getByText('已下架')).toBeInTheDocument();
});
it('shows - for disabled agent display status', () => {
renderApp();
// Agent 102 is disabled
const rows = screen.getAllByRole('row');
const row102 = rows.find((row) => within(row).queryByText('质检Agent'));
expect(row102).toBeDefined();
// Disabled agent should show '-' for display status
expect(within(row102!).getAllByText('-')).toHaveLength(2); // speech_content '-' and display_status '-'
});
it('shows 编辑配置 button for enabled agents', () => {
renderApp();
expect(screen.getByRole('button', { name: '编辑配置-复盘Agent' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '编辑配置-销售助手Agent' })).toBeInTheDocument();
});
it('does not show 编辑配置 button for disabled agents', () => {
renderApp();
expect(screen.queryByRole('button', { name: '编辑配置-质检Agent' })).not.toBeInTheDocument();
});
});
describe('page constraints', () => {
it('does not show add Agent button', () => {
renderApp();
expect(screen.queryByRole('button', { name: /新增/ })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /添加/ })).not.toBeInTheDocument();
});
it('does not show delete Agent button', () => {
renderApp();
expect(screen.queryByRole('button', { name: /删除Agent/ })).not.toBeInTheDocument();
});
it('does not show select Agent dropdown', () => {
renderApp();
expect(screen.queryByRole('combobox', { name: /选择Agent/ })).not.toBeInTheDocument();
});
});
describe('empty states', () => {
it('shows empty state when no configurable agents', () => {
renderApp('/official-site/job-tabs/3/agents?scenario=empty');
expect(screen.getByText('当前无可配置 Agent')).toBeInTheDocument();
});
it('shows data source note', () => {
renderApp();
expect(screen.getByText(/Agent 数据源来自该岗位关联的渠道活码/)).toBeInTheDocument();
expect(screen.getByText(/管家 Agent 不参与官网展示/)).toBeInTheDocument();
});
});
describe('icon and media display', () => {
it('shows icon preview when icon_url exists', () => {
renderApp();
const iconImg = screen.getByAltText('复盘Agent');
expect(iconImg).toBeInTheDocument();
expect(iconImg.getAttribute('src')).toContain('cdn.example.com');
});
it('shows media type indicator', () => {
renderApp();
expect(screen.getByText('视频')).toBeInTheDocument(); // Agent 101 has video media
expect(screen.getByText('GIF')).toBeInTheDocument(); // Agent 103 has gif media
});
});
describe('sort order display', () => {
it('shows sort order as number', () => {
renderApp();
// Agent 104 has sort_order 0 (in tab 3)
// Agent 101 has sort_order 10
expect(screen.getByText('10')).toBeInTheDocument();
});
});
});
\ No newline at end of file \ No newline at end of file
import { useMemo, useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Button, StatePlaceholder, Table } from '../../../packages/ui/src';
import {
getAgentDisplayConfigList,
mapAgentStatusToText,
getDisplayStatusTextForList,
type AgentDisplayConfigMockItem,
} from '../../../packages/contracts/official-site-agent-display-config-mock';
import { AgentDisplayConfigEditModal } from './AgentDisplayConfigEditModal';
export function OfficialSiteAgentDisplayConfigPage() {
const navigate = useNavigate();
const params = useParams();
const [searchParams] = useSearchParams();
const tabId = Number(params.tabId);
const scenario = searchParams.get('scenario') ?? 'normal';
const result = useMemo(
() => getAgentDisplayConfigList(tabId, scenario),
[tabId, scenario],
);
const [editingAgent, setEditingAgent] = useState<AgentDisplayConfigMockItem | null>(null);
const goBackToList = () => {
navigate('/official-site/job-tabs');
};
// Record not found
if (!result) {
return (
<StatePlaceholder
state="error"
title="岗位展示配置不存在"
description="当前岗位展示配置记录不存在或已被删除"
primaryAction={<Button size="small" onClick={goBackToList}>返回列表</Button>}
/>
);
}
const { tab_context, items } = result;
const handleEditAgent = (agent: AgentDisplayConfigMockItem) => {
setEditingAgent(agent);
};
const columns = [
{
title: 'Agent名称',
dataIndex: 'speech_title' as const,
render: (value: unknown) => <span className="font-medium">{value as string}</span>,
},
{
title: 'Agent概述',
dataIndex: 'speech_content' as const,
render: (value: unknown) => (
<span className="max-w-[200px] truncate">{(value as string) || '-'}</span>
),
},
{
title: '图标',
dataIndex: 'icon_url' as const,
render: (value: unknown, item: AgentDisplayConfigMockItem) => {
const url = value as string;
if (!url) {
return <span className="text-[var(--gl-color-text-secondary)]">-</span>;
}
return (
<img
data-testid={`agent-icon-${item.agent_id}`}
src={url}
alt={item.speech_title}
className="w-8 h-8 rounded object-cover"
/>
);
},
},
{
title: '展示素材',
dataIndex: 'media_url' as const,
render: (value: unknown, item: AgentDisplayConfigMockItem) => {
const url = value as string;
if (!url) {
return <span className="text-[var(--gl-color-text-secondary)]">-</span>;
}
const typeLabels: Record<string, string> = {
'image': '图片',
'video': '视频',
'gif': 'GIF',
};
return (
<div className="flex items-center gap-2">
{item.media_type === 'video' ? (
<video
src={url}
className="w-8 h-8 rounded object-cover"
muted
/>
) : (
<img
src={url}
alt={item.speech_title}
className="w-8 h-8 rounded object-cover"
/>
)}
<span className="text-xs text-[var(--gl-color-text-secondary)]">
{typeLabels[item.media_type] || '素材'}
</span>
</div>
);
},
},
{
title: '排序',
dataIndex: 'sort_order' as const,
render: (value: unknown) => <span>{value as number}</span>,
},
{
title: '状态',
dataIndex: 'agent_status' as const,
render: (value: unknown) => {
const status = value as 'enable' | 'disable';
const text = mapAgentStatusToText(status);
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-warning-bg)] px-2 py-1 text-xs text-[var(--gl-color-warning-text)]">{text}</span>;
},
},
{
title: '展示状态',
key: 'display_status_display',
render: (_: unknown, item: AgentDisplayConfigMockItem) => {
const text = getDisplayStatusTextForList(item.agent_status, item.display_status);
if (text === '-') {
return <span className="text-[var(--gl-color-text-secondary)]">-</span>;
}
return item.display_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-warning-bg)] px-2 py-1 text-xs text-[var(--gl-color-warning-text)]">{text}</span>;
},
},
{
title: '操作',
key: 'actions',
render: (_: unknown, item: AgentDisplayConfigMockItem) => {
if (!item.can_edit) {
return null;
}
return (
<Button
aria-label={`编辑配置-${item.speech_title}`}
size="small"
variant="text"
onClick={() => handleEditAgent(item)}
>
编辑配置
</Button>
);
},
},
];
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)]">
{tab_context.position_name} - Agent展示配置
</h2>
<p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">
配置该岗位下 Agent 在官网的展示素材和状态
</p>
</div>
</div>
</header>
{/* Tab context info */}
<div className="grid gap-4 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6">
<div className="grid gap-4 text-sm">
<div className="flex items-center gap-2">
<span className="shrink-0 min-w-[80px] text-[var(--gl-color-text-secondary)]">关联渠道活码:</span>
<span>{tab_context.qrcode_name}</span>
</div>
<div className="flex items-center gap-2">
<span className="shrink-0 min-w-[80px] text-[var(--gl-color-text-secondary)]">渠道编码:</span>
<span>{tab_context.channel_code}</span>
</div>
<div className="flex items-center gap-2">
<span className="shrink-0 min-w-[80px] text-[var(--gl-color-text-secondary)]">承接员工:</span>
<span>{tab_context.employee_name}({tab_context.employee_role_text})</span>
</div>
</div>
</div>
{/* Agent list table */}
<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">
<p className="text-sm text-[var(--gl-color-text-secondary)]">
Agent 数据源来自该岗位关联的渠道活码。管家 Agent 不参与官网展示。
Agent 列表不可增删,仅可编辑展示配置。
</p>
<Table
rowKey="agent_id"
columns={columns}
dataSource={items}
empty={{
description: '当前无可配置 Agent',
}}
/>
</div>
{/* Edit modal */}
<AgentDisplayConfigEditModal
open={Boolean(editingAgent)}
agent={editingAgent}
tabId={tabId}
scenario={scenario}
onCancel={() => setEditingAgent(null)}
onSaveSuccess={() => {
setEditingAgent(null);
// Force re-render to update list
window.location.reload();
}}
/>
</section>
);
}
\ No newline at end of file \ No newline at end of file
import { fireEvent, render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { App } from '../../App';
import { resetAgentDisplayConfigMockState } from '../../../packages/contracts/official-site-agent-display-config-mock';
import { resetOfficialSiteJobTabMockState } from '../../../packages/contracts/official-site-job-tab-mock';
function renderApp(path = '/official-site/job-tabs/1/agents') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
describe('official site agent display config routes and navigation', () => {
beforeEach(() => {
window.localStorage.clear();
resetOfficialSiteJobTabMockState();
resetAgentDisplayConfigMockState();
});
it('renders the agent display config page at /official-site/job-tabs/:tabId/agents', () => {
renderApp();
expect(screen.getByRole('heading', { name: '店销顾问 - Agent展示配置' })).toBeInTheDocument();
});
it('shows navigation entry under 官网配置 group', () => {
renderApp();
expect(screen.getByRole('button', { name: '岗位展示配置' })).toBeInTheDocument();
});
it('marks 岗位展示配置 navigation entry as active when on agents route', () => {
renderApp();
expect(screen.getByRole('button', { name: '岗位展示配置' })).toHaveAttribute('aria-current', 'page');
});
it('shows breadcrumb for agent display config page', () => {
renderApp();
expect(screen.getByText('官网配置 / 岗位展示配置')).toBeInTheDocument();
});
it('shows return to list button', () => {
renderApp();
expect(screen.getByRole('button', { name: '返回' })).toBeInTheDocument();
});
it('shows position name in page title', () => {
renderApp();
expect(screen.getByRole('heading', { name: '店销顾问 - Agent展示配置' })).toBeInTheDocument();
});
it('shows tab context info (qrcode, channel code, employee)', () => {
renderApp();
expect(screen.getByText('店销顾问渠道活码')).toBeInTheDocument();
expect(screen.getByText('DSC-QR-001')).toBeInTheDocument();
expect(screen.getByText((content) => content.includes('张小萌'))).toBeInTheDocument();
});
it('returns to job tabs list when clicking return button', () => {
renderApp();
fireEvent.click(screen.getByRole('button', { name: '返回' }));
expect(screen.getByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument();
});
it('shows error state for non-existent tab', () => {
renderApp('/official-site/job-tabs/99999/agents');
expect(screen.getByText('岗位展示配置不存在')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '返回列表' })).toBeInTheDocument();
});
it('can navigate to agent display config from job tabs list', () => {
renderApp('/official-site/job-tabs');
fireEvent.click(screen.getByRole('button', { name: '配置Agent-店销顾问' }));
expect(screen.getByRole('heading', { name: '店销顾问 - Agent展示配置' })).toBeInTheDocument();
});
});
\ No newline at end of file \ No newline at end of file
import { fireEvent, render, screen, waitFor, act } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { resetOfficialSiteJobTabMockState } from '../../../packages/contracts/official-site-job-tab-mock';
import { resetChannelCodeMockState } from '../../../packages/contracts/channel-code-mock';
import { resetAgentTagMockState } from '../../../packages/contracts/agent-tag-mock';
import { App } from '../../App';
function renderApp(path: string) {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
function resetAllMockState() {
window.localStorage.clear();
resetOfficialSiteJobTabMockState();
resetChannelCodeMockState();
resetAgentTagMockState();
}
describe('OfficialSiteJobTabEditorPage', () => {
beforeEach(() => {
resetAllMockState();
});
describe('create mode', () => {
it('renders page header with title and actions', () => {
renderApp('/official-site/job-tabs/new');
expect(screen.getByRole('heading', { name: '新建岗位展示' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '返回' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '取消' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '保存' })).toBeInTheDocument();
});
it('renders required form fields', () => {
renderApp('/official-site/job-tabs/new');
expect(screen.getByLabelText('岗位标签')).toBeInTheDocument();
expect(screen.getByLabelText('Tab排序')).toBeInTheDocument();
expect(screen.getByLabelText('展示状态')).toBeInTheDocument();
});
it('shows placeholder text for QR code before position selection', () => {
renderApp('/official-site/job-tabs/new');
expect(screen.getByText('选择岗位后自动展示')).toBeInTheDocument();
});
it('validates position is required on save', () => {
renderApp('/official-site/job-tabs/new');
fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByText('请选择岗位标签')).toBeInTheDocument();
});
it('validates tab order is 0-99 integer', () => {
renderApp('/official-site/job-tabs/new');
const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '100' } });
fireEvent.click(screen.getByRole('button', { name: '保存' }));
expect(screen.getByText('Tab排序请输入0-99的整数')).toBeInTheDocument();
});
it('shows position select with available candidates (not duplicates)', async () => {
renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签');
await act(async () => {
fireEvent.click(select);
});
// 直播运营 and 官网顾问 are available (not in existing tabs) and have channel code
await waitFor(() => {
expect(screen.getByText('直播运营')).toBeInTheDocument();
});
});
it('shows QR code name after selecting position', async () => {
renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签');
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
await waitFor(() => {
expect(screen.getByText('直播运营渠道活码')).toBeInTheDocument();
});
});
it('shows derived info after selecting position with channel code', async () => {
renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签');
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
await waitFor(() => {
expect(screen.getByText('渠道编码')).toBeInTheDocument();
expect(screen.getByText('王大力(直播运营专员)')).toBeInTheDocument();
});
});
it('shows save error on failure', async () => {
renderApp('/official-site/job-tabs/new?scenario=saveError');
const select = screen.getByLabelText('岗位标签');
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '10' } });
const mainTitleInput = screen.getByLabelText('岗位标题');
fireEvent.change(mainTitleInput, { target: { value: 'AI 标题' } });
const subTitleInput = screen.getByLabelText('岗位说明');
fireEvent.change(subTitleInput, { target: { value: 'AI 说明' } });
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '保存' }));
});
await waitFor(() => {
expect(screen.getByText('保存失败,请重试')).toBeInTheDocument();
});
});
it('saves successfully and navigates back to list', async () => {
renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签');
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '10' } });
const mainTitleInput = screen.getByLabelText('岗位标题');
fireEvent.change(mainTitleInput, { target: { value: 'AI 标题' } });
const subTitleInput = screen.getByLabelText('岗位说明');
fireEvent.change(subTitleInput, { target: { value: 'AI 说明' } });
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '保存' }));
});
await waitFor(() => {
expect(screen.getByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument();
});
});
it('cancels and navigates back to list', () => {
renderApp('/official-site/job-tabs/new');
fireEvent.click(screen.getByRole('button', { name: '取消' }));
expect(screen.getByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument();
});
});
describe('edit mode', () => {
it('renders page header with title', () => {
renderApp('/official-site/job-tabs/1/edit');
expect(screen.getByRole('heading', { name: '编辑岗位展示' })).toBeInTheDocument();
});
it('shows position as readonly input', () => {
renderApp('/official-site/job-tabs/1/edit');
const positionInput = screen.getByLabelText('岗位标签');
expect(positionInput).toHaveProperty('disabled', true);
expect(positionInput).toHaveValue('店销顾问');
});
it('shows QR code name as readonly', () => {
renderApp('/official-site/job-tabs/1/edit');
expect(screen.getByText('店销顾问渠道活码')).toBeInTheDocument();
});
it('shows derived info from existing record', async () => {
renderApp('/official-site/job-tabs/1/edit');
await waitFor(() => {
expect(screen.getByText('渠道编码')).toBeInTheDocument();
expect(screen.getByText('张小萌(店销主管)')).toBeInTheDocument();
});
});
it('allows editing tab order and saves successfully', async () => {
renderApp('/official-site/job-tabs/1/edit');
// Find the number input and change its value
const orderInput = screen.getByRole('spinbutton', { name: 'Tab排序' }) as HTMLInputElement;
expect(orderInput.value).toBe('10');
fireEvent.change(orderInput, { target: { value: '50' } });
expect(orderInput.value).toBe('50');
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '保存' }));
});
await waitFor(() => {
expect(screen.getByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument();
});
});
it('allows changing display status and saves successfully', async () => {
renderApp('/official-site/job-tabs/3/edit');
// 私域增长 status is 'disable', change to 'enable'
const statusSelect = screen.getByRole('combobox', { name: '展示状态' });
await act(async () => {
fireEvent.click(statusSelect);
});
await act(async () => {
fireEvent.click(screen.getByText('展示中'));
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '保存' }));
});
await waitFor(() => {
expect(screen.getByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument();
});
});
it('shows error page when record not found', () => {
renderApp('/official-site/job-tabs/999/edit');
expect(screen.getByText('岗位展示配置不存在')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '返回列表' })).toBeInTheDocument();
});
it('saves successfully and navigates back to list', async () => {
renderApp('/official-site/job-tabs/1/edit');
const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '20' } });
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '保存' }));
});
await waitFor(() => {
expect(screen.getByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument();
});
});
});
describe('AI intro module', () => {
it('renders AI intro section header in create mode', () => {
renderApp('/official-site/job-tabs/new');
expect(screen.getByText('岗位 AI 赋能介绍')).toBeInTheDocument();
});
it('renders main_title field with tips in create mode', () => {
renderApp('/official-site/job-tabs/new');
expect(screen.getByLabelText('岗位标题')).toBeInTheDocument();
expect(screen.getByText('展示在官网 Tab 名称下方,用一句话介绍 AI 如何赋能该岗位')).toBeInTheDocument();
});
it('renders sub_title field with tips in create mode', () => {
renderApp('/official-site/job-tabs/new');
expect(screen.getByLabelText('岗位说明')).toBeInTheDocument();
expect(screen.getByText('展示在官网 Tab 内容区,用于详细描述 AI 为该岗位带来的价值')).toBeInTheDocument();
});
it('validates main_title is required on save', async () => {
renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签');
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '10' } });
fireEvent.click(screen.getByRole('button', { name: '保存' }));
await waitFor(() => {
expect(screen.getByText('请输入岗位标题')).toBeInTheDocument();
});
});
it('validates main_title max 30 chars on save', async () => {
renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签');
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '10' } });
const mainTitleInput = screen.getByLabelText('岗位标题');
fireEvent.change(mainTitleInput, { target: { value: '这是一段超过三十个字的岗位标题测试用例用于验证前端校验逻辑正确' } });
fireEvent.click(screen.getByRole('button', { name: '保存' }));
await waitFor(() => {
expect(screen.getByText('岗位标题最多30字')).toBeInTheDocument();
});
});
it('validates sub_title is required on save', async () => {
renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签');
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '10' } });
const mainTitleInput = screen.getByLabelText('岗位标题');
fireEvent.change(mainTitleInput, { target: { value: 'AI 赋能标题' } });
fireEvent.click(screen.getByRole('button', { name: '保存' }));
await waitFor(() => {
expect(screen.getByText('请输入岗位说明')).toBeInTheDocument();
});
});
it('validates sub_title max 200 chars on save', async () => {
renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签');
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '10' } });
const mainTitleInput = screen.getByLabelText('岗位标题');
fireEvent.change(mainTitleInput, { target: { value: 'AI 赋能标题' } });
const subTitleInput = screen.getByLabelText('岗位说明');
const longText = '这是一段超过二百个字的岗位说明测试用例用于验证前端校验逻辑,通过模拟超长文本输入来测试表单校验机制是否能够正确拦截并提示用户,确保数据完整性,防止用户输入过长的内容导致界面显示问题或后端存储异常,同时也能够帮助开发者更好地理解用户体验设计中的边界条件处理方式,从而提升整体产品质量和用户满意度,让系统更加稳定可靠运行,最终实现业务目标达成和客户价值创造,为企业数字化转型提供强有力的技术支撑和服务保障。';
fireEvent.change(subTitleInput, { target: { value: longText } });
fireEvent.click(screen.getByRole('button', { name: '保存' }));
await waitFor(() => {
expect(screen.getByText('岗位说明最多200字')).toBeInTheDocument();
});
});
it('saves main_title and sub_title successfully in create mode', async () => {
renderApp('/official-site/job-tabs/new');
const select = screen.getByLabelText('岗位标签');
await act(async () => {
fireEvent.click(select);
});
await act(async () => {
fireEvent.click(screen.getByText('直播运营'));
});
const orderInput = screen.getByLabelText('Tab排序');
fireEvent.change(orderInput, { target: { value: '10' } });
const mainTitleInput = screen.getByLabelText('岗位标题');
fireEvent.change(mainTitleInput, { target: { value: 'AI 智能助手' } });
const subTitleInput = screen.getByLabelText('岗位说明');
fireEvent.change(subTitleInput, { target: { value: 'AI 智能助手帮助提升工作效率' } });
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '保存' }));
});
await waitFor(() => {
expect(screen.getByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument();
});
});
it('renders AI intro section header in edit mode', () => {
renderApp('/official-site/job-tabs/1/edit');
expect(screen.getByText('岗位 AI 赋能介绍')).toBeInTheDocument();
});
it('fills main_title and sub_title from existing record in edit mode', async () => {
renderApp('/official-site/job-tabs/1/edit');
const mainTitleInput = screen.getByLabelText('岗位标题') as HTMLInputElement;
const subTitleInput = screen.getByLabelText('岗位说明') as HTMLTextAreaElement;
await waitFor(() => {
expect(mainTitleInput.value).toBe('AI 智能助手提升店销效率');
expect(subTitleInput.value).toContain('AI 智能问答');
});
});
it('allows editing main_title and sub_title in edit mode and saves', async () => {
renderApp('/official-site/job-tabs/1/edit');
const mainTitleInput = screen.getByLabelText('岗位标题');
const subTitleInput = screen.getByLabelText('岗位说明');
fireEvent.change(mainTitleInput, { target: { value: '更新后的标题' } });
fireEvent.change(subTitleInput, { target: { value: '更新后的说明内容' } });
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '保存' }));
});
await waitFor(() => {
expect(screen.getByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument();
});
});
});
});
\ No newline at end of file \ No newline at end of file
import { useMemo, useState } from 'react';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Button, FormItem, Input, Select, StatePlaceholder, Switch } from '../../../packages/ui/src';
import {
getOfficialSiteJobTabRecord,
getPositionTagCandidates,
getPositionQRCodeDerivedInfo,
isPositionDuplicate,
saveOfficialSiteJobTabRecord,
type OfficialSiteJobTabMockItem,
type PositionTagCandidate,
} from '../../../packages/contracts/official-site-job-tab-mock';
import { buildOfficialSiteJobTabListSearch, readOfficialSiteJobTabListRouteState } from './officialSiteJobTabRouteState';
interface TabFormState {
position_code: string;
position_name: string;
qrcode_id: number;
qrcode_name: string;
channel_code: string;
employee_name: string;
employee_role_text: string;
tab_order: number;
display_status: 'enable' | 'disable';
main_title: string;
sub_title: string;
}
interface TabFormErrors {
position_code?: string;
tab_order?: string;
main_title?: string;
sub_title?: string;
}
interface SaveNotice {
type: 'error' | 'success';
message: string;
}
function buildInitialFormState(tab?: OfficialSiteJobTabMockItem): TabFormState {
return {
position_code: tab?.position_code ?? '',
position_name: tab?.position_name ?? '',
qrcode_id: tab?.qrcode_id ?? 0,
qrcode_name: tab?.qrcode_name ?? '',
channel_code: tab?.channel_code ?? '',
employee_name: tab?.employee_name ?? '',
employee_role_text: tab?.employee_role_text ?? '',
tab_order: tab?.tab_order ?? undefined as unknown as number,
display_status: tab?.display_status ?? 'enable',
main_title: tab?.main_title ?? '',
sub_title: tab?.sub_title ?? '',
};
}
export function OfficialSiteJobTabEditorPage({ mode }: { mode: 'create' | 'edit' }) {
const navigate = useNavigate();
const location = useLocation();
const params = useParams();
const [searchParams] = useSearchParams();
const routeState = readOfficialSiteJobTabListRouteState(searchParams);
const scenario = searchParams.get('scenario') ?? 'normal';
const routeTab = (location.state as { tab?: OfficialSiteJobTabMockItem } | null)?.tab;
const currentTab = useMemo(
() => (mode === 'edit' ? routeTab ?? getOfficialSiteJobTabRecord(params.tabId) : undefined),
[mode, params.tabId, routeTab],
);
const [form, setForm] = useState<TabFormState>(() => buildInitialFormState(currentTab));
const [errors, setErrors] = useState<TabFormErrors>({});
const [notice, setNotice] = useState<SaveNotice | null>(null);
const [positionCandidates] = useState<PositionTagCandidate[]>(() => getPositionTagCandidates());
const fieldWidthClassName = 'w-full max-w-[450px]';
const goBackToList = () => {
navigate(`/official-site/job-tabs${buildOfficialSiteJobTabListSearch(routeState)}`);
};
// Record not found for edit mode
if (mode === 'edit' && !currentTab) {
return (
<StatePlaceholder
state="error"
title="岗位展示配置不存在"
description="当前岗位展示配置记录不存在或已被删除"
primaryAction={<Button size="small" onClick={goBackToList}>返回列表</Button>}
/>
);
}
const selectedCandidate = positionCandidates.find((c) => c.code === form.position_code);
const derivedInfo = form.position_code ? getPositionQRCodeDerivedInfo(form.position_code) : undefined;
const validate = () => {
const nextErrors: TabFormErrors = {};
const order = form.tab_order;
if (mode === 'create' && !form.position_code) {
nextErrors.position_code = '请选择岗位标签';
}
if (!Number.isInteger(order) || order < 0 || order > 99) {
nextErrors.tab_order = 'Tab排序请输入0-99的整数';
}
if (!form.main_title.trim()) {
nextErrors.main_title = '请输入岗位标题';
} else if (form.main_title.length > 30) {
nextErrors.main_title = '岗位标题最多30字';
}
if (!form.sub_title.trim()) {
nextErrors.sub_title = '请输入岗位说明';
} else if (form.sub_title.length > 200) {
nextErrors.sub_title = '岗位说明最多200字';
}
setErrors(nextErrors);
return Object.keys(nextErrors).length === 0;
};
const handleSave = () => {
setNotice(null);
if (!validate()) return;
// Check for duplicate position in create mode
if (mode === 'create' && isPositionDuplicate(form.position_code)) {
setNotice({ type: 'error', message: '该岗位已存在官网岗位展示,请编辑原配置' });
return;
}
// Check for position without channel code
if (mode === 'create' && !selectedCandidate?.has_channel_code) {
setNotice({ type: 'error', message: '该岗位暂未配置渠道活码' });
return;
}
// Handle save error fixture
if (scenario === 'saveError') {
setNotice({ type: 'error', message: '保存失败,请重试' });
return;
}
const result = saveOfficialSiteJobTabRecord({
tabId: currentTab?.tab_id,
position_code: mode === 'create' ? form.position_code : undefined,
qrcode_id: mode === 'create' ? form.qrcode_id : undefined,
tab_order: form.tab_order,
display_status: form.display_status,
main_title: form.main_title,
sub_title: form.sub_title,
}, scenario);
if (result.blocked) {
setNotice({ type: 'error', message: result.message ?? '保存失败' });
return;
}
navigate(`/official-site/job-tabs${buildOfficialSiteJobTabListSearch({
...routeState,
refreshToken: String(Date.now()),
})}`);
};
const availablePositionOptions = positionCandidates.filter((c) => {
if (mode === 'edit') return true;
return !isPositionDuplicate(c.code);
});
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)]">
{mode === 'create' ? '新建岗位展示' : '编辑岗位展示'}
</h2>
<p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">
{mode === 'create' ? '创建新的官网岗位展示配置' : '编辑已有官网岗位展示配置'}
</p>
</div>
</div>
<div className="flex items-center gap-3">
<Button variant="outline" onClick={goBackToList}>取消</Button>
<Button variant="primary" onClick={handleSave}>保存</Button>
</div>
</header>
{notice ? (
<div
className={`rounded-[var(--gl-radius-sm)] border px-4 py-3 text-sm ${
notice.type === 'error'
? 'border-[var(--gl-color-danger-border)] bg-[var(--gl-color-danger-bg)] text-[var(--gl-color-danger-text)]'
: 'border-[var(--gl-color-success-border)] bg-[var(--gl-color-success-bg)] text-[var(--gl-color-success-text)]'
}`}
role={notice.type === 'error' ? 'alert' : 'status'}
aria-label={notice.message}
>
{notice.message}
</div>
) : null}
<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">
<FormItem label="选择岗位标签" layout="horizontal" required={mode === 'create'} error={errors.position_code}>
{mode === 'edit' ? (
<Input
aria-label="岗位标签"
className={fieldWidthClassName}
disabled
value={currentTab?.position_name ?? ''}
/>
) : (
<Select
aria-label="岗位标签"
className={fieldWidthClassName}
options={availablePositionOptions.map((c) => ({
value: c.code,
label: c.has_channel_code ? c.name : `${c.name}(暂无渠道活码)`,
disabled: !c.has_channel_code || isPositionDuplicate(c.code),
}))}
placeholder="请选择岗位标签"
value={form.position_code}
onChange={(value) => {
const candidate = positionCandidates.find((c) => c.code === value);
if (candidate) {
setForm((current) => ({
...current,
position_code: candidate.code,
position_name: candidate.name,
qrcode_id: candidate.qrcode_id ?? 0,
qrcode_name: candidate.qrcode_name ?? '',
}));
}
}}
/>
)}
</FormItem>
<FormItem label="关联渠道活码" layout="horizontal">
<div className={fieldWidthClassName}>
{form.qrcode_name || (mode === 'create' && !form.position_code ? (
<span className="text-sm text-[var(--gl-color-text-secondary)]">选择岗位后自动展示</span>
) : null)}
{!form.qrcode_name && mode === 'create' && selectedCandidate && !selectedCandidate.has_channel_code ? (
<span className="text-sm text-[var(--gl-color-danger-text)]">该岗位暂未配置渠道活码</span>
) : null}
</div>
</FormItem>
{(derivedInfo || (mode === 'edit' && currentTab?.channel_code)) ? (
<>
<FormItem label="渠道编码" layout="horizontal">
<div className={fieldWidthClassName}>
{derivedInfo?.channel_code ?? currentTab?.channel_code ?? ''}
</div>
</FormItem>
<FormItem label="承接员工" layout="horizontal">
<div className={fieldWidthClassName}>
{derivedInfo ? `${derivedInfo.employee_name}(${derivedInfo.employee_role_text})` : (
currentTab ? `${currentTab.employee_name}(${currentTab.employee_role_text})` : ''
)}
</div>
</FormItem>
</>
) : null}
<div className="border-t border-[var(--gl-color-border-secondary)]" />
<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}>
<div className={fieldWidthClassName}>
<Input
aria-label="岗位标题"
placeholder="请输入岗位标题"
maxLength={30}
value={form.main_title}
onChange={(value) => setForm((current) => ({ ...current, main_title: value }))}
/>
<p className="m-0 mt-1 text-xs text-[var(--gl-color-text-secondary)]">展示在官网 Tab 名称下方,用一句话介绍 AI 如何赋能该岗位</p>
</div>
</FormItem>
<FormItem label="岗位说明" layout="horizontal" required error={errors.sub_title}>
<div className={fieldWidthClassName}>
<textarea
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"
placeholder="请输入岗位说明"
maxLength={200}
rows={4}
value={form.sub_title}
onChange={(e) => setForm((current) => ({ ...current, sub_title: e.target.value }))}
/>
<p className="m-0 mt-1 text-xs text-[var(--gl-color-text-secondary)]">展示在官网 Tab 内容区,用于详细描述 AI 为该岗位带来的价值</p>
</div>
</FormItem>
<FormItem label="Tab 排序" layout="horizontal" required error={errors.tab_order}>
<Input
aria-label="Tab排序"
className={fieldWidthClassName}
type="number"
min={0}
max={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)}
onChange={(value) => setForm((current) => ({ ...current, tab_order: value === '' ? undefined as unknown as number : Number(value) }))}
/>
</FormItem>
<FormItem label="展示状态" layout="horizontal" required>
<Select
aria-label="展示状态"
className={fieldWidthClassName}
options={[
{ value: 'enable', label: '展示中' },
{ value: 'disable', label: '已下架' },
]}
value={form.display_status}
onChange={(value) => setForm((current) => ({ ...current, display_status: value as 'enable' | 'disable' }))}
/>
</FormItem>
</div>
</div>
</section>
);
}
\ No newline at end of file \ No newline at end of file
import { fireEvent, render, screen, waitFor, act } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { resetOfficialSiteJobTabMockState } from '../../../packages/contracts/official-site-job-tab-mock';
import { App } from '../../App';
function renderApp(path = '/official-site/job-tabs') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
function resetMockState() {
window.localStorage.clear();
resetOfficialSiteJobTabMockState();
}
describe('OfficialSiteJobTabListPage', () => {
beforeEach(() => {
resetMockState();
});
it('renders page header with title and create button', () => {
renderApp();
expect(screen.getByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '新建岗位展示' })).toBeInTheDocument();
});
it('renders search filters', () => {
renderApp();
expect(screen.getByLabelText('关键词')).toBeInTheDocument();
expect(screen.getByLabelText('展示状态')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '搜索' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '重置' })).toBeInTheDocument();
});
it('renders table with data', () => {
renderApp();
expect(screen.getByText('岗位名称')).toBeInTheDocument();
// 渠道活码 appears in header and possibly in data
expect(screen.getAllByText('渠道活码').length).toBeGreaterThan(0);
expect(screen.getByText('Tab 排序')).toBeInTheDocument();
expect(screen.getByText('展示状态')).toBeInTheDocument();
expect(screen.getByText('更新时间')).toBeInTheDocument();
expect(screen.getByText('操作')).toBeInTheDocument();
// Check for actual data from mock
expect(screen.getByText('店销顾问')).toBeInTheDocument();
});
it('renders pagination', () => {
renderApp();
// Pagination component exists as navigation
expect(screen.getByRole('navigation')).toBeInTheDocument();
});
it('shows empty state when no data', () => {
renderApp('/official-site/job-tabs?scenario=empty');
expect(screen.getByText('当前还没有岗位展示配置')).toBeInTheDocument();
});
it('shows filtered empty state', async () => {
renderApp();
const keywordInput = screen.getByLabelText('关键词');
fireEvent.change(keywordInput, { target: { value: '不存在的关键词' } });
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '搜索' }));
});
await waitFor(() => {
expect(screen.getByText('未找到匹配结果')).toBeInTheDocument();
});
});
it('shows load error state with retry button', () => {
renderApp('/official-site/job-tabs?scenario=loadError');
// StatePlaceholder uses strong for title, not heading role
expect(screen.getByText('加载失败')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '重试' })).toBeInTheDocument();
});
it('can retry after load error', async () => {
renderApp('/official-site/job-tabs?scenario=loadError');
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '重试' }));
});
await waitFor(() => {
expect(screen.getByText('重试成功')).toBeInTheDocument();
});
});
it('can search by keyword', async () => {
renderApp();
const keywordInput = screen.getByLabelText('关键词');
fireEvent.change(keywordInput, { target: { value: '店销' } });
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '搜索' }));
});
await waitFor(() => {
expect(screen.getByText('店销顾问')).toBeInTheDocument();
});
});
it('can filter by display status', async () => {
renderApp();
const statusSelect = screen.getByLabelText('展示状态');
await act(async () => {
fireEvent.click(statusSelect);
});
// Use getAllByText and filter for the dropdown option
const disabledOptions = screen.getAllByText('已下架');
const dropdownOption = disabledOptions.find((el) => el.closest('[role="option"]'));
await act(async () => {
fireEvent.click(dropdownOption ?? disabledOptions[0]);
});
await waitFor(() => {
expect(screen.getByText('私域增长')).toBeInTheDocument();
});
});
it('can reset filters', async () => {
renderApp();
const keywordInput = screen.getByLabelText('关键词');
fireEvent.change(keywordInput, { target: { value: '店销' } });
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '搜索' }));
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '重置' }));
});
await waitFor(() => {
expect(keywordInput).toHaveValue('');
});
});
it('can navigate to create page', () => {
renderApp();
fireEvent.click(screen.getByRole('button', { name: '新建岗位展示' }));
expect(screen.getByRole('heading', { name: '新建岗位展示' })).toBeInTheDocument();
});
it('can navigate to edit page', () => {
renderApp();
fireEvent.click(screen.getByRole('button', { name: '编辑店销顾问' }));
expect(screen.getByRole('heading', { name: '编辑岗位展示' })).toBeInTheDocument();
});
it('can navigate to configure agents placeholder', async () => {
renderApp();
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '配置Agent-店销顾问' }));
});
await waitFor(() => {
expect(screen.getByRole('heading', { name: '店销顾问 - Agent展示配置' })).toBeInTheDocument();
});
});
it('shows enable button for disabled items', () => {
renderApp();
// 私域增长 is disabled
expect(screen.getByRole('button', { name: '上架私域增长' })).toBeInTheDocument();
});
it('shows disable button for enabled items', () => {
renderApp();
// 店销顾问 is enabled
expect(screen.getByRole('button', { name: '下架店销顾问' })).toBeInTheDocument();
});
it('shows delete button for all items', () => {
renderApp();
expect(screen.getByRole('button', { name: '删除店销顾问' })).toBeInTheDocument();
});
it('shows enable confirmation modal', async () => {
renderApp();
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '上架私域增长' }));
});
await waitFor(() => {
expect(screen.getByText('确认上架"私域增长"?')).toBeInTheDocument();
});
});
it('shows disable confirmation modal', async () => {
renderApp();
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '下架店销顾问' }));
});
await waitFor(() => {
expect(screen.getByText('确认下架"店销顾问"?')).toBeInTheDocument();
});
});
it('shows delete confirmation modal', async () => {
renderApp();
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '删除店销顾问' }));
});
await waitFor(() => {
expect(screen.getByText('确认删除"店销顾问"?')).toBeInTheDocument();
});
});
it('can cancel enable action', async () => {
renderApp();
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '上架私域增长' }));
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '取消' }));
});
await waitFor(() => {
expect(screen.queryByText('确认上架"私域增长"?')).not.toBeInTheDocument();
});
});
it('can confirm enable action', async () => {
renderApp();
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '上架私域增长' }));
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '确定' }));
});
await waitFor(() => {
expect(screen.getByText('上架成功')).toBeInTheDocument();
});
});
it('can confirm disable action', async () => {
renderApp();
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '下架店销顾问' }));
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '确定' }));
});
await waitFor(() => {
expect(screen.getByText('下架成功')).toBeInTheDocument();
});
});
it('shows status block error', async () => {
renderApp('/official-site/job-tabs?scenario=statusBlockError');
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '下架店销顾问' }));
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '确定' }));
});
await waitFor(() => {
expect(screen.getByText('该岗位展示配置下存在 Agent 配置,请先移除后再下架')).toBeInTheDocument();
});
});
it('can delete item', async () => {
renderApp();
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '删除店销顾问' }));
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: '确定' }));
});
await waitFor(() => {
expect(screen.getByText('删除成功')).toBeInTheDocument();
});
});
});
\ No newline at end of file \ No newline at end of file
import { useMemo, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button, Input, Modal, Pagination, Select, StatePlaceholder, Table } from '../../../packages/ui/src';
import {
officialSiteJobTabMockFixtures,
getOfficialSiteJobTabListPage,
updateOfficialSiteJobTabStatus,
deleteOfficialSiteJobTabRecord,
type OfficialSiteJobTabMockItem,
} from '../../../packages/contracts/official-site-job-tab-mock';
import { buildOfficialSiteJobTabListSearch, readOfficialSiteJobTabListRouteState } from './officialSiteJobTabRouteState';
interface PageNotice {
type: 'error' | 'success';
message: string;
}
function getFixtureByScenario(scenario: string) {
switch (scenario) {
case 'empty':
return officialSiteJobTabMockFixtures.empty;
case 'loadError':
return officialSiteJobTabMockFixtures.loadError;
case 'saveError':
return officialSiteJobTabMockFixtures.saveError;
case 'statusBlockError':
return officialSiteJobTabMockFixtures.statusBlockError;
default:
return officialSiteJobTabMockFixtures.normal;
}
}
export function OfficialSiteJobTabListPage() {
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const routeState = readOfficialSiteJobTabListRouteState(searchParams);
const [keyword, setKeyword] = useState(routeState.keyword);
const [notice, setNotice] = useState<PageNotice | null>(null);
const [statusTarget, setStatusTarget] = useState<{ tab: OfficialSiteJobTabMockItem; action: 'enable' | 'disable' } | null>(null);
const [deleteTarget, setDeleteTarget] = useState<OfficialSiteJobTabMockItem | null>(null);
const [version, setVersion] = useState(0);
const fixture = getFixtureByScenario(routeState.scenario);
const listSource = routeState.scenario === 'empty' ? fixture.items : undefined;
const result = useMemo(
() => getOfficialSiteJobTabListPage({
keyword: routeState.keyword,
displayStatus: routeState.displayStatus === 'all' ? '' : routeState.displayStatus,
page: routeState.page,
pageSize: routeState.pageSize,
source: listSource,
}),
[listSource, routeState.keyword, routeState.displayStatus, routeState.page, routeState.pageSize, routeState.refreshToken, version],
);
const hasFilter = Boolean(routeState.keyword.trim() || (routeState.displayStatus && routeState.displayStatus !== 'all'));
const routeSearch = buildOfficialSiteJobTabListSearch({
scenario: routeState.scenario,
keyword: routeState.keyword,
displayStatus: routeState.displayStatus,
page: routeState.page,
pageSize: routeState.pageSize,
});
const submitFilters = () => {
setSearchParams(buildOfficialSiteJobTabListSearch({
scenario: routeState.scenario,
keyword,
displayStatus: routeState.displayStatus,
page: 1,
pageSize: routeState.pageSize,
}));
};
const resetFilters = () => {
setKeyword('');
setSearchParams(buildOfficialSiteJobTabListSearch({
scenario: routeState.scenario,
keyword: '',
displayStatus: 'all',
page: 1,
pageSize: routeState.pageSize,
}));
};
const handleRetry = () => {
setSearchParams(buildOfficialSiteJobTabListSearch({
...routeState,
scenario: 'normal',
refreshToken: String(Date.now()),
}));
setNotice({ type: 'success', message: '重试成功' });
};
const columns = [
{ title: '岗位名称', dataIndex: 'position_name' as const },
{ title: '渠道活码', dataIndex: 'qrcode_name' as const },
{ title: 'Tab 排序', dataIndex: 'tab_order' as const },
{ title: '展示Agent数', dataIndex: 'agent_count' as const },
{
title: '展示状态',
dataIndex: 'display_status' as const,
render: (value: unknown) => {
const status = value as 'enable' | 'disable';
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-warning-bg)] px-2 py-1 text-xs text-[var(--gl-color-warning-text)]">已下架</span>;
},
},
{ title: '更新时间', dataIndex: 'updated_at' as const },
{
title: '操作',
key: 'actions',
render: (_: unknown, item: OfficialSiteJobTabMockItem) => (
<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={`编辑${item.position_name}`} size="small" variant="text" onClick={() => navigate(`/official-site/job-tabs/${item.tab_id}/edit${routeSearch}`, { state: { tab: item } })}>编辑</Button>
{item.operations.includes('enable') ? <Button aria-label={`上架${item.position_name}`} size="small" variant="text" onClick={() => setStatusTarget({ tab: item, action: 'enable' })}>上架</Button> : null}
{item.operations.includes('disable') ? <Button aria-label={`下架${item.position_name}`} size="small" variant="text" onClick={() => setStatusTarget({ tab: item, action: 'disable' })}>下架</Button> : null}
<Button aria-label={`删除${item.position_name}`} size="small" variant="danger" onClick={() => setDeleteTarget(item)}>删除</Button>
</span>
),
},
];
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>
<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>
</div>
<Button variant="primary" onClick={() => navigate(`/official-site/job-tabs/new${routeSearch}`)}>新建岗位展示</Button>
</header>
{notice ? (
<div
className={`rounded-[var(--gl-radius-sm)] border px-4 py-3 text-sm ${
notice.type === 'error'
? 'border-[var(--gl-color-danger-border)] bg-[var(--gl-color-danger-bg)] text-[var(--gl-color-danger-text)]'
: 'border-[var(--gl-color-success-border)] bg-[var(--gl-color-success-bg)] text-[var(--gl-color-success-text)]'
}`}
role={notice.type === 'error' ? 'alert' : 'status'}
aria-label={notice.message}
>
{notice.message}
</div>
) : 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">
<div className="flex items-center gap-4 text-sm">
<div className="flex items-center gap-2">
<span className="shrink-0">关键词:</span>
<span className="w-[200px]">
<Input
aria-label="关键词"
className="w-full"
placeholder="搜索岗位名称或渠道活码"
value={keyword}
allowClear
onChange={setKeyword}
onKeyDown={(event) => {
if (event.key === 'Enter') submitFilters();
}}
/>
</span>
</div>
<div className="flex items-center gap-2">
<span className="shrink-0">展示状态:</span>
<span className="w-[200px]">
<Select
aria-label="展示状态"
className="w-full"
options={[
{ value: 'all', label: '全部' },
{ value: 'enable', label: '展示中' },
{ value: 'disable', label: '已下架' },
]}
value={routeState.displayStatus}
onChange={(value) => setSearchParams(buildOfficialSiteJobTabListSearch({
scenario: routeState.scenario,
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">
{fixture.loadError ? (
<StatePlaceholder
state="error"
title="加载失败"
description="岗位展示配置列表加载失败,请重试"
primaryAction={<Button size="small" onClick={handleRetry}>重试</Button>}
/>
) : (
<>
<Table
rowKey="tab_id"
columns={columns}
dataSource={result.items}
empty={{
description: hasFilter ? '未找到匹配结果' : '当前还没有岗位展示配置',
action: hasFilter ? <Button size="small" onClick={resetFilters}>重置搜索</Button> : undefined,
}}
/>
<Pagination
current={routeState.page}
pageSize={routeState.pageSize}
total={result.total}
pageSizeOptions={[2, 10, 20]}
onChange={(page, pageSize) => {
setSearchParams(buildOfficialSiteJobTabListSearch({
scenario: routeState.scenario,
keyword: routeState.keyword,
displayStatus: routeState.displayStatus,
page,
pageSize,
}));
}}
/>
</>
)}
</div>
<Modal
open={Boolean(statusTarget)}
title={statusTarget ? `确认${statusTarget.action === 'enable' ? '上架' : '下架'}"${statusTarget.tab.position_name}"?` : ''}
onCancel={() => setStatusTarget(null)}
onOk={() => {
if (!statusTarget) return;
const result = updateOfficialSiteJobTabStatus(statusTarget.tab.tab_id, statusTarget.action, routeState.scenario === 'statusBlockError' ? 'statusBlockError' : 'normal');
if (result.blocked) {
setNotice({ type: 'error', message: result.message ?? '操作被阻断' });
setStatusTarget(null);
return;
}
setNotice({ type: 'success', message: statusTarget.action === 'enable' ? '上架成功' : '下架成功' });
setStatusTarget(null);
setVersion((current) => current + 1);
}}
>
<p className="m-0 max-w-[360px] leading-[var(--gl-line-height-md)] text-[var(--gl-color-text-secondary)]">
{statusTarget?.action === 'enable' ? '启用后岗位展示配置将在官网岗位列表中展示。' : '下架后岗位展示配置不再在官网展示,请确认是否继续。'}
</p>
</Modal>
<Modal
open={Boolean(deleteTarget)}
title={deleteTarget ? `确认删除"${deleteTarget.position_name}"?` : ''}
onCancel={() => setDeleteTarget(null)}
onOk={() => {
if (!deleteTarget) return;
const result = deleteOfficialSiteJobTabRecord(deleteTarget.tab_id);
if (!result.success) {
setNotice({ type: 'error', message: result.message });
setDeleteTarget(null);
return;
}
setNotice({ type: 'success', message: '删除成功' });
setDeleteTarget(null);
setVersion((current) => current + 1);
}}
>
<p className="m-0 max-w-[360px] leading-[var(--gl-line-height-md)] text-[var(--gl-color-text-secondary)]">
删除后将清理该岗位展示配置下的 Agent 展示配置,不会影响 Agent 原始数据或渠道活码信息。
</p>
</Modal>
</section>
);
}
\ No newline at end of file \ No newline at end of file
import { fireEvent, render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { App } from '../../App';
function renderApp(path = '/official-site/job-tabs') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
describe('official site job tab routes and navigation', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('renders the list route at /official-site/job-tabs', () => {
renderApp();
expect(screen.getByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument();
});
it('renders the new route at /official-site/job-tabs/new', () => {
renderApp('/official-site/job-tabs/new');
expect(screen.getByRole('heading', { name: '新建岗位展示' })).toBeInTheDocument();
});
it('renders the edit route at /official-site/job-tabs/:tabId/edit', () => {
renderApp('/official-site/job-tabs/1/edit');
expect(screen.getByRole('heading', { name: '编辑岗位展示' })).toBeInTheDocument();
});
it('shows navigation entry under 官网配置 group', () => {
renderApp();
expect(screen.getByRole('button', { name: '岗位展示配置' })).toBeInTheDocument();
});
it('marks navigation entry as active when on job-tabs routes', () => {
renderApp();
expect(screen.getByRole('button', { name: '岗位展示配置' })).toHaveAttribute('aria-current', 'page');
});
it('shows breadcrumb for job-tabs', () => {
renderApp();
expect(screen.getByText('官网配置 / 岗位展示配置')).toBeInTheDocument();
});
it('can navigate to the job-tabs page from agents', () => {
renderApp('/agents');
fireEvent.click(screen.getByRole('button', { name: '岗位展示配置' }));
expect(screen.getByRole('heading', { name: '岗位展示配置' })).toBeInTheDocument();
});
it('does not affect methodology navigation', () => {
renderApp('/official-site/methodology');
expect(screen.getByRole('heading', { name: '方法论展示配置' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: '方法论展示配置' })).toHaveAttribute('aria-current', 'page');
expect(screen.getByRole('button', { name: '岗位展示配置' })).not.toHaveAttribute('aria-current');
});
});
\ No newline at end of file \ No newline at end of file
export interface OfficialSiteJobTabListRouteState {
scenario: string;
keyword: string;
displayStatus: 'all' | 'enable' | 'disable';
page: number;
pageSize: number;
refreshToken?: string;
}
export function readOfficialSiteJobTabListRouteState(searchParams: URLSearchParams): OfficialSiteJobTabListRouteState {
const page = Number(searchParams.get('page') ?? '1');
const pageSize = Number(searchParams.get('pageSize') ?? '10');
return {
scenario: searchParams.get('scenario') ?? 'normal',
keyword: searchParams.get('keyword') ?? '',
displayStatus: (searchParams.get('displayStatus') as 'all' | 'enable' | 'disable') ?? 'all',
page: Number.isFinite(page) && page > 0 ? page : 1,
pageSize: Number.isFinite(pageSize) && pageSize > 0 ? pageSize : 10,
refreshToken: searchParams.get('refreshToken') ?? undefined,
};
}
export function buildOfficialSiteJobTabListSearch(state: Partial<OfficialSiteJobTabListRouteState>) {
const searchParams = new URLSearchParams();
if (state.scenario && state.scenario !== 'normal') searchParams.set('scenario', state.scenario);
if (state.keyword) searchParams.set('keyword', state.keyword);
if (state.displayStatus && state.displayStatus !== 'all') searchParams.set('displayStatus', state.displayStatus);
if (state.page && state.page !== 1) searchParams.set('page', String(state.page));
if (state.pageSize && state.pageSize !== 10) searchParams.set('pageSize', String(state.pageSize));
if (state.refreshToken) searchParams.set('refreshToken', state.refreshToken);
const query = searchParams.toString();
return query ? `?${query}` : '';
}
\ No newline at end of file \ No newline at end of file
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { App } from '../../App';
function renderMethodology(path = '/official-site/methodology') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
describe('OfficialSiteMethodologyPage form and steps', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('renders the core fields and hydrates the normal mock config', async () => {
renderMethodology();
expect(screen.getByRole('status', { name: '加载中' })).toBeInTheDocument();
await waitFor(() => {
expect(screen.getByRole('switch', { name: '展示状态' })).toHaveAttribute('aria-checked', 'true');
});
expect(screen.getByLabelText('主标题')).toHaveValue('四步打造可复用的岗位 Agent');
expect(screen.getByLabelText('副标题')).toHaveValue('从目标澄清到上线复盘,帮助团队沉淀一套稳定可复制的方法论。');
const cards = screen.getAllByTestId('methodology-step-card');
expect(cards).toHaveLength(2);
expect(within(cards[0]).getByLabelText('步骤1名称')).toHaveValue('需求澄清');
expect(within(cards[1]).getByLabelText('步骤2名称')).toHaveValue('方案设计');
});
it('supports disabled display status and empty-step fixtures', async () => {
const disabledView = renderMethodology('/official-site/methodology?scenario=disabled');
await waitFor(() => {
expect(screen.getByRole('switch', { name: '展示状态' })).toHaveAttribute('aria-checked', 'false');
});
disabledView.unmount();
renderMethodology('/official-site/methodology?scenario=emptySteps');
await waitFor(() => {
expect(screen.getByText('当前还没有方法论步骤')).toBeInTheDocument();
});
expect(screen.getByRole('button', { name: '添加步骤' })).toBeInTheDocument();
});
it('validates required titles and enabled-empty-steps before saving', async () => {
renderMethodology();
await waitFor(() => {
expect(screen.getByLabelText('主标题')).toBeInTheDocument();
});
fireEvent.change(screen.getByLabelText('主标题'), { target: { value: '' } });
fireEvent.change(screen.getByLabelText('副标题'), { target: { value: '' } });
fireEvent.click(screen.getByRole('button', { name: '删除步骤 1' }));
fireEvent.click(screen.getByRole('button', { name: '删除步骤 1' }));
fireEvent.click(screen.getByRole('button', { name: '保存配置' }));
expect(screen.getByText('请输入主标题')).toBeInTheDocument();
expect(screen.getByText('请输入副标题')).toBeInTheDocument();
expect(screen.getByText('至少添加一个方法论步骤')).toBeInTheDocument();
});
it('supports step add, delete, move, and order maintenance', async () => {
renderMethodology();
await waitFor(() => {
expect(screen.getAllByTestId('methodology-step-card')).toHaveLength(2);
});
fireEvent.click(screen.getByRole('button', { name: '添加步骤' }));
let cards = screen.getAllByTestId('methodology-step-card');
expect(cards).toHaveLength(3);
fireEvent.change(within(cards[2]).getByLabelText('步骤3名称'), { target: { value: '上线复盘' } });
fireEvent.click(within(cards[2]).getByRole('button', { name: '上移步骤 3' }));
fireEvent.click(within(screen.getAllByTestId('methodology-step-card')[1]).getByRole('button', { name: '上移步骤 2' }));
cards = screen.getAllByTestId('methodology-step-card');
expect(within(cards[0]).getByLabelText('步骤1名称')).toHaveValue('上线复盘');
expect(within(cards[0]).getByText('sort_order = 1')).toBeInTheDocument();
fireEvent.click(within(cards[1]).getByRole('button', { name: '删除步骤 2' }));
cards = screen.getAllByTestId('methodology-step-card');
expect(cards).toHaveLength(2);
expect(within(cards[1]).getByText('sort_order = 2')).toBeInTheDocument();
});
});
import { useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Button, FormItem, Input, MediaWall, StatePlaceholder, Switch, Textarea } from '../../../packages/ui/src';
import {
getMethodologyConfigFixture,
type MethodologyConfigRecord,
type MethodologyDisplayStatus,
type MethodologyIconResource,
type MethodologyImageResource,
validateMethodologyContentImageFile,
} from '../../../packages/contracts/methodology-config-mock';
interface MethodologyStepFormState {
step_id: string;
step_icon?: MethodologyIconResource;
step_name: string;
step_order: number;
step_image?: MethodologyImageResource;
iconError?: string;
nameError?: string;
imageError?: string;
}
interface MethodologyFormState {
display_status: MethodologyDisplayStatus;
main_title: string;
sub_title: string;
steps: MethodologyStepFormState[];
}
interface SaveNotice {
type: 'success' | 'error';
message: string;
}
const contentImageHelperText = '支持 PNG/JPG/JPEG/GIF,最大 10MB';
const stepIconHelperText = '支持 PNG/JPG/JPEG/GIF,最大 10MB';
function normalizeSteps(steps: MethodologyStepFormState[]) {
return steps.map((step, index) => ({
...step,
step_order: index + 1,
}));
}
function buildFormState(record: MethodologyConfigRecord): MethodologyFormState {
return {
display_status: record.display_status,
main_title: record.main_title,
sub_title: record.sub_title,
steps: normalizeSteps(record.steps).map((step) => ({
...step,
iconError: undefined,
imageError: undefined,
nameError: undefined,
})),
};
}
function createEmptyStep(nextOrder: number): MethodologyStepFormState {
return {
step_id: `new-step-${nextOrder}-${Date.now()}`,
step_name: '',
step_order: nextOrder,
};
}
function buildDefaultIcon(stepOrder: number): MethodologyIconResource {
const svgContent = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48"><circle cx="24" cy="24" r="22" fill="%232B6CB0"/><text x="24" y="30" text-anchor="middle" fill="white" font-size="18" font-weight="bold" font-family="system-ui">${stepOrder}</text></svg>`;
const dataUrl = `data:image/svg+xml,${encodeURIComponent(svgContent)}`;
return {
id: `default-icon-${stepOrder}`,
name: `默认图标(步骤${stepOrder})`,
url: dataUrl,
};
}
export function OfficialSiteMethodologyPage() {
const [searchParams] = useSearchParams();
const initialScenario = searchParams.get('scenario') ?? 'normal';
const [scenario, setScenario] = useState(initialScenario);
const [loading, setLoading] = useState(true);
const [form, setForm] = useState<MethodologyFormState | null>(null);
const [loadError, setLoadError] = useState(false);
const [saving, setSaving] = useState(false);
const [notice, setNotice] = useState<SaveNotice | null>(null);
const [mainTitleError, setMainTitleError] = useState<string>();
const [subTitleError, setSubTitleError] = useState<string>();
const [stepListError, setStepListError] = useState<string>();
const fixture = useMemo(() => getMethodologyConfigFixture(scenario), [scenario]);
useEffect(() => {
setLoading(true);
setLoadError(false);
setNotice(null);
const timer = window.setTimeout(() => {
if (fixture.loadError) {
setLoadError(true);
setLoading(false);
return;
}
setForm(buildFormState(fixture.data));
setMainTitleError(undefined);
setSubTitleError(undefined);
setStepListError(undefined);
setLoading(false);
}, 0);
return () => window.clearTimeout(timer);
}, [fixture]);
const updateForm = (updater: (current: MethodologyFormState) => MethodologyFormState) => {
setForm((current) => (current ? updater(current) : current));
};
const updateStep = (index: number, updater: (step: MethodologyStepFormState) => MethodologyStepFormState) => {
updateForm((current) => ({
...current,
steps: normalizeSteps(current.steps.map((step, stepIndex) => (stepIndex === index ? updater(step) : step))),
}));
};
const validate = () => {
if (!form) return false;
let valid = true;
const trimmedMainTitle = form.main_title.trim();
const trimmedSubTitle = form.sub_title.trim();
setMainTitleError(undefined);
setSubTitleError(undefined);
setStepListError(undefined);
if (!trimmedMainTitle) {
setMainTitleError('请输入主标题');
valid = false;
} else if (trimmedMainTitle.length > 30) {
setMainTitleError('主标题不能超过 30 字');
valid = false;
}
if (!trimmedSubTitle) {
setSubTitleError('请输入副标题');
valid = false;
} else if (trimmedSubTitle.length > 100) {
setSubTitleError('副标题不能超过 100 字');
valid = false;
}
if (form.display_status === 'enable' && form.steps.length === 0) {
setStepListError('至少添加一个方法论步骤');
valid = false;
}
const nextSteps = form.steps.map((step) => {
let iconError: string | undefined;
let nameError: string | undefined;
let imageError: string | undefined;
if (!step.step_icon) {
iconError = '请配置步骤图标';
valid = false;
}
if (!step.step_name.trim()) {
nameError = '请输入步骤名称';
valid = false;
} else if (step.step_name.trim().length > 20) {
nameError = '步骤名称不能超过 20 字';
valid = false;
}
if (!step.step_image) {
imageError = '请上传内容图';
valid = false;
}
return {
...step,
iconError,
imageError,
nameError,
};
});
setForm((current) => (current ? { ...current, steps: nextSteps } : current));
return valid;
};
const handleSave = () => {
if (!form || saving) {
return;
}
setNotice(null);
if (!validate()) {
return;
}
setSaving(true);
window.setTimeout(() => {
setSaving(false);
if (fixture.saveError) {
setNotice({ type: 'error', message: '保存失败,请重试' });
return;
}
setNotice({ type: 'success', message: '保存成功' });
}, 80);
};
const renderContent = () => {
if (loading) {
return <StatePlaceholder state="empty" title="加载中" description="正在加载方法论配置" />;
}
if (loadError || !form) {
return (
<StatePlaceholder
state="error"
title="加载失败"
description="方法论配置加载失败,请重试"
primaryAction={<Button size="small" onClick={() => setScenario('normal')}>重试</Button>}
/>
);
}
return (
<>
{notice ? (
<div
className={`rounded-[var(--gl-radius-sm)] border px-4 py-3 text-sm ${
notice.type === 'error'
? 'border-[var(--gl-color-danger-border)] bg-[var(--gl-color-danger-bg)] text-[var(--gl-color-danger-text)]'
: 'border-[var(--gl-color-success-border)] bg-[var(--gl-color-success-bg)] text-[var(--gl-color-success-text)]'
}`}
role={notice.type === 'error' ? 'alert' : 'status'}
aria-label={notice.message}
>
{notice.message}
</div>
) : null}
<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">
<FormItem label="展示状态" layout="horizontal" required error={undefined}>
<Switch
aria-label="展示状态"
checked={form.display_status === 'enable'}
onChange={(checked) => {
setNotice(null);
updateForm((current) => ({
...current,
display_status: checked ? 'enable' : 'disable',
}));
}}
/>
</FormItem>
<FormItem label="主标题" layout="horizontal" required error={mainTitleError}>
<Input
aria-label="主标题"
className="w-full max-w-[520px]"
maxLength={30}
showCount
value={form.main_title}
onChange={(value) => {
setMainTitleError(undefined);
updateForm((current) => ({
...current,
main_title: value,
}));
}}
/>
</FormItem>
<FormItem label="副标题" layout="horizontal" required error={subTitleError}>
<Textarea
aria-label="副标题"
className="w-full max-w-[520px]"
maxLength={100}
rows={4}
showCount
value={form.sub_title}
onChange={(value) => {
setSubTitleError(undefined);
updateForm((current) => ({
...current,
sub_title: value,
}));
}}
/>
</FormItem>
</div>
</div>
<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="flex items-center justify-between gap-4">
<div className="grid gap-1">
<h3 className="m-0 text-lg leading-[var(--gl-line-height-lg)]">方法论步骤</h3>
<p className="m-0 text-sm text-[var(--gl-color-text-secondary)]">配置步骤图标、步骤名称与内容图。</p>
</div>
<Button
variant="primary"
onClick={() => {
setStepListError(undefined);
updateForm((current) => ({
...current,
steps: normalizeSteps([...current.steps, createEmptyStep(current.steps.length + 1)]),
}));
}}
>
添加步骤
</Button>
</div>
{stepListError ? <p className="mb-0 mt-4 text-sm text-[var(--gl-color-danger-text)]">{stepListError}</p> : null}
{form.steps.length === 0 ? (
<div className="mt-6">
<StatePlaceholder state="empty" title="当前还没有方法论步骤" description="请先添加步骤,再配置图标、名称和内容图。" />
</div>
) : (
<div className="mt-6 grid gap-4">
{form.steps.map((step, index) => (
<section
key={step.step_id}
aria-label={`方法论步骤 ${index + 1}`}
className="grid gap-5 rounded-[8px] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-page)] p-5"
data-testid="methodology-step-card"
>
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="grid gap-1">
<strong>步骤 {index + 1}</strong>
<span className="text-sm text-[var(--gl-color-text-secondary)]">{`sort_order = ${step.step_order}`}</span>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button
size="small"
variant="outline"
disabled={index === 0}
aria-label={`上移步骤 ${index + 1}`}
onClick={() => {
if (index === 0) return;
updateForm((current) => {
const nextSteps = [...current.steps];
[nextSteps[index - 1], nextSteps[index]] = [nextSteps[index], nextSteps[index - 1]];
return { ...current, steps: normalizeSteps(nextSteps) };
});
}}
>
上移
</Button>
<Button
size="small"
variant="outline"
disabled={index === form.steps.length - 1}
aria-label={`下移步骤 ${index + 1}`}
onClick={() => {
if (index === form.steps.length - 1) return;
updateForm((current) => {
const nextSteps = [...current.steps];
[nextSteps[index], nextSteps[index + 1]] = [nextSteps[index + 1], nextSteps[index]];
return { ...current, steps: normalizeSteps(nextSteps) };
});
}}
>
下移
</Button>
<Button
size="small"
variant="danger"
aria-label={`删除步骤 ${index + 1}`}
onClick={() => {
updateForm((current) => ({
...current,
steps: normalizeSteps(current.steps.filter((_, currentIndex) => currentIndex !== index)),
}));
}}
>
删除
</Button>
</div>
</div>
<FormItem label="步骤图标" required error={step.iconError} help={stepIconHelperText}>
<div className="grid gap-3">
<MediaWall
accept="image/png,image/jpg,image/jpeg,image/gif"
items={step.step_icon ? [{
id: step.step_icon.id,
type: 'image' as const,
src: step.step_icon.url,
alt: step.step_icon.name,
}] : []}
maxCount={1}
multiple={false}
onRemove={() => {
updateStep(index, (currentStep) => ({
...currentStep,
step_icon: undefined,
}));
}}
onSelectFiles={(files) => {
const selectedFile = files[0];
if (!selectedFile) return;
const acceptedTypes = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif'];
if (!acceptedTypes.includes(selectedFile.type)) {
updateStep(index, (currentStep) => ({
...currentStep,
step_icon: undefined,
iconError: '步骤图标仅支持 PNG/JPG/JPEG/GIF',
}));
return;
}
if (selectedFile.size > 10 * 1024 * 1024) {
updateStep(index, (currentStep) => ({
...currentStep,
step_icon: undefined,
iconError: '步骤图标大小不能超过 10MB',
}));
return;
}
updateStep(index, (currentStep) => ({
...currentStep,
step_icon: {
id: `icon-${index + 1}-${Date.now()}`,
name: selectedFile.name,
url: `https://mock.assets.local/uploads/${selectedFile.name}`,
},
iconError: undefined,
}));
}}
/>
<div className="flex flex-wrap items-center gap-2">
<Button
size="small"
variant="outline"
aria-label={`使用默认图标 步骤 ${index + 1}`}
onClick={() => {
updateStep(index, (currentStep) => ({
...currentStep,
step_icon: buildDefaultIcon(currentStep.step_order),
iconError: undefined,
}));
}}
>
使用默认图标
</Button>
</div>
</div>
</FormItem>
<FormItem label="步骤名称" required error={step.nameError}>
<Input
aria-label={`步骤${index + 1}名称`}
className="w-full max-w-[360px]"
maxLength={20}
showCount
value={step.step_name}
onChange={(value) => {
updateStep(index, (currentStep) => ({
...currentStep,
step_name: value,
nameError: undefined,
}));
}}
/>
</FormItem>
<FormItem label="内容图" required error={step.imageError} help={contentImageHelperText}>
<MediaWall
accept="image/png,image/jpg,image/jpeg,image/gif"
items={step.step_image ? [{
id: step.step_image.id,
type: 'image' as const,
src: step.step_image.url,
alt: step.step_image.name,
}] : []}
maxCount={1}
multiple={false}
onRemove={() => {
updateStep(index, (currentStep) => ({
...currentStep,
step_image: undefined,
}));
}}
onSelectFiles={(files) => {
const selectedFile = files[0];
if (!selectedFile) return;
const validationError = validateMethodologyContentImageFile(selectedFile);
if (validationError) {
updateStep(index, (currentStep) => ({
...currentStep,
step_image: undefined,
imageError: validationError.message,
}));
return;
}
if (fixture.uploadError) {
updateStep(index, (currentStep) => ({
...currentStep,
step_image: undefined,
imageError: '图片上传失败,请重试',
}));
return;
}
updateStep(index, (currentStep) => ({
...currentStep,
step_image: {
id: `content-image-${index + 1}-${Date.now()}`,
name: selectedFile.name,
url: `https://mock.assets.local/uploads/${selectedFile.name}`,
mime_type: selectedFile.type,
size_bytes: selectedFile.size,
},
imageError: undefined,
}));
}}
/>
</FormItem>
</section>
))}
</div>
)}
</div>
</>
);
};
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>
<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>
</div>
<Button variant="primary" loading={saving} aria-label="保存配置" onClick={handleSave}>
保存配置
</Button>
</header>
{renderContent()}
</section>
);
}
import { fireEvent, render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { App } from '../../App';
function renderApp(path = '/official-site/methodology') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
describe('official site methodology route and navigation', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('renders the methodology page inside admin shell with correct menu ownership', () => {
renderApp();
expect(screen.getByRole('heading', { name: '方法论展示配置' })).toBeInTheDocument();
expect(screen.getByText('官网配置 / 方法论展示配置')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '方法论展示配置' })).toHaveAttribute('aria-current', 'page');
expect(screen.getByRole('button', { name: 'Agent列表' })).not.toHaveAttribute('aria-current');
});
it('shows the official site navigation entry and can navigate to the methodology page from agents', () => {
renderApp('/agents');
fireEvent.click(screen.getByRole('button', { name: '方法论展示配置' }));
expect(screen.getByRole('heading', { name: '方法论展示配置' })).toBeInTheDocument();
expect(screen.getByText('官网配置 / 方法论展示配置')).toBeInTheDocument();
});
it('keeps the protected index redirect pointing to agents by default', () => {
renderApp('/');
expect(screen.getByRole('heading', { name: 'Agent管理' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Agent列表' })).toHaveAttribute('aria-current', 'page');
});
});
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { App } from '../../App';
function renderMethodology(path = '/official-site/methodology') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
/** 点击 TDesign image-flow 主题的删除图标 */
function clickDeleteIcon(container: HTMLElement) {
const maskItems = container.querySelectorAll('.t-upload__card-mask-item');
// 第一个 mask-item 是预览图标,第二个是删除图标
const deleteMaskItem = maskItems[1] as HTMLElement;
const deleteIcon = deleteMaskItem?.querySelector('.t-icon-delete') as HTMLElement;
if (deleteIcon) {
fireEvent.click(deleteIcon);
}
}
/** 获取内容图的文件输入(第二个 MediaWall) */
function getContentImageInput(card: HTMLElement): HTMLInputElement | null {
// 每个 card 有两个 MediaWall:步骤图标和内容图
// 内容图的 input 在第二个 .t-upload 容器中
const uploadContainers = card.querySelectorAll('.t-upload');
if (uploadContainers.length < 2) return null;
const contentImageUpload = uploadContainers[1];
return contentImageUpload.querySelector('input[type="file"]') as HTMLInputElement;
}
/** 获取步骤图标的文件输入(第一个 MediaWall) */
function getStepIconInput(card: HTMLElement): HTMLInputElement | null {
const uploadContainers = card.querySelectorAll('.t-upload');
if (uploadContainers.length < 1) return null;
const stepIconUpload = uploadContainers[0];
return stepIconUpload.querySelector('input[type="file"]') as HTMLInputElement;
}
describe('OfficialSiteMethodologyPage upload, save, and state handling', () => {
beforeEach(() => {
vi.useRealTimers();
window.localStorage.clear();
});
it('renders a recoverable load error state', async () => {
renderMethodology('/official-site/methodology?scenario=loadError');
await waitFor(() => {
expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument();
});
fireEvent.click(screen.getByRole('button', { name: '重试' }));
await waitFor(() => {
expect(screen.getByLabelText('主标题')).toBeInTheDocument();
});
});
it('requires step icon and content image before saving', async () => {
renderMethodology();
await waitFor(() => {
expect(screen.getAllByTestId('methodology-step-card')).toHaveLength(2);
});
// Delete step icon and content image using TDesign's delete icons
const cards = screen.getAllByTestId('methodology-step-card');
const firstCard = cards[0];
// 找到两个 MediaWall 的容器
const uploadContainers = firstCard.querySelectorAll('.t-upload__card');
// 第一个 .t-upload__card 是步骤图标,第二个是内容图
if (uploadContainers.length >= 2) {
// 删除步骤图标
clickDeleteIcon(uploadContainers[0] as HTMLElement);
// 删除内容图
clickDeleteIcon(uploadContainers[1] as HTMLElement);
}
fireEvent.click(screen.getByRole('button', { name: '保存配置' }));
expect(screen.getByText('请配置步骤图标')).toBeInTheDocument();
expect(screen.getByText('请上传内容图')).toBeInTheDocument();
});
it('validates content image type and size before mock upload', async () => {
renderMethodology();
await waitFor(() => {
expect(screen.getAllByTestId('methodology-step-card')).toHaveLength(2);
});
const firstCard = screen.getAllByTestId('methodology-step-card')[0];
// First delete existing content image (since maxCount=1 hides upload button when image exists)
const uploadContainers = firstCard.querySelectorAll('.t-upload__card');
if (uploadContainers.length >= 2) {
clickDeleteIcon(uploadContainers[1] as HTMLElement);
}
// Now find content image file input
const contentImageInput = getContentImageInput(firstCard);
if (!contentImageInput) {
throw new Error('Content image input not found');
}
// GIF is now supported, so test with an unsupported type
fireEvent.change(contentImageInput, {
target: { files: [new File(['demo'], 'cover.bmp', { type: 'image/bmp' })] },
});
await waitFor(() => {
expect(within(firstCard).getByText('内容图仅支持 PNG/JPG/JPEG/GIF')).toBeInTheDocument();
});
// Upload failed, no image was added, so we can directly try oversized file
const oversized = new File(['demo'], 'cover.png', { type: 'image/png' });
Object.defineProperty(oversized, 'size', { value: 10 * 1024 * 1024 + 1 });
fireEvent.change(contentImageInput, {
target: { files: [oversized] },
});
await waitFor(() => {
expect(within(firstCard).getByText('内容图大小不能超过 10MB')).toBeInTheDocument();
});
});
it('shows upload failure, save success with disabled repeat submit, and save failure while keeping edits', async () => {
const uploadErrorView = renderMethodology('/official-site/methodology?scenario=uploadError');
await waitFor(() => {
expect(screen.getAllByTestId('methodology-step-card')).toHaveLength(2);
});
const firstCard = screen.getAllByTestId('methodology-step-card')[0];
// First delete existing content image (since maxCount=1 hides upload button when image exists)
const uploadContainers = firstCard.querySelectorAll('.t-upload__card');
if (uploadContainers.length >= 2) {
clickDeleteIcon(uploadContainers[1] as HTMLElement);
}
// Now find content image file input
const contentImageInput = getContentImageInput(firstCard);
if (!contentImageInput) {
throw new Error('Content image input not found');
}
fireEvent.change(contentImageInput, {
target: { files: [new File(['demo'], 'cover.png', { type: 'image/png' })] },
});
await waitFor(() => {
expect(within(firstCard).getByText('图片上传失败,请重试')).toBeInTheDocument();
});
uploadErrorView.unmount();
const saveErrorView = renderMethodology('/official-site/methodology?scenario=saveError');
await waitFor(() => {
expect(screen.getByLabelText('主标题')).toBeInTheDocument();
});
fireEvent.change(screen.getByLabelText('主标题'), { target: { value: '保存失败后仍保留编辑内容' } });
fireEvent.click(screen.getByRole('button', { name: '保存配置' }));
await waitFor(() => {
expect(screen.getByRole('alert', { name: '保存失败,请重试' })).toBeInTheDocument();
});
expect(screen.getByLabelText('主标题')).toHaveValue('保存失败后仍保留编辑内容');
saveErrorView.unmount();
const emptyStepsView = renderMethodology('/official-site/methodology?scenario=emptySteps');
await waitFor(() => {
expect(screen.getByRole('switch', { name: '展示状态' })).toBeInTheDocument();
});
fireEvent.click(screen.getByRole('switch', { name: '展示状态' }));
fireEvent.click(screen.getByRole('button', { name: '保存配置' }));
await waitFor(() => {
expect(screen.getByRole('status', { name: '保存成功' })).toBeInTheDocument();
});
expect(screen.getByRole('button', { name: '保存配置' })).not.toBeDisabled();
emptyStepsView.unmount();
renderMethodology();
await waitFor(() => {
expect(screen.getByRole('button', { name: '保存配置' })).toBeInTheDocument();
});
fireEvent.click(screen.getByRole('button', { name: '保存配置' }));
await waitFor(
() => {
expect(screen.getByRole('status', { name: '保存成功' })).toBeInTheDocument();
},
{ timeout: 10000 },
);
});
});
\ No newline at end of file \ No newline at end of file
import { useNavigate } from 'react-router-dom';
import { Button, Drawer, StatePlaceholder } from '../../../packages/ui/src';
import { getSkillDetail, getSkillFixtureByScenario } from '../../../packages/contracts/skill-list-mock';
import { SkillMarkdown } from './SkillMarkdown';
import { buildSkillListSearch, type SkillListRouteState } from './skillRouteState';
export function SkillDetailDrawer({ routeState, skillCode }: { routeState: SkillListRouteState; skillCode?: string }) {
const navigate = useNavigate();
const fixture = getSkillFixtureByScenario(routeState.scenario);
const detail = getSkillDetail(skillCode, routeState.scenario);
const closeDrawer = () => {
navigate(`/skills${buildSkillListSearch({ ...routeState, detail: undefined })}`);
};
if (!skillCode) {
return null;
}
return (
<Drawer
open
title="Skill详情"
width={560}
onClose={closeDrawer}
footer={
<div className="flex items-center justify-end gap-3">
<Button variant="outline" onClick={closeDrawer}>关闭</Button>
</div>
}
>
{fixture.detailLoading ? (
<StatePlaceholder state="empty" title="加载中" description="正在加载 Skill 详情" />
) : !detail ? (
<StatePlaceholder state="error" title="详情加载失败" description="当前 Skill 详情无法展示" />
) : (
<div className="grid h-[calc(100vh-220px)] gap-4 overflow-y-auto pr-1 text-sm" data-testid="skill-drawer-scroll">
<section className="grid gap-1">
<strong className="text-lg">{detail.skill_code}</strong>
<p className="m-0 text-base font-semibold">{detail.skill_name}</p>
<p className="m-0 text-[var(--gl-color-text-secondary)]">{detail.description}</p>
</section>
<section className="grid gap-3">
<strong>使用说明</strong>
{detail.doc_markdown ? (
<SkillMarkdown markdown={detail.doc_markdown} />
) : (
<StatePlaceholder state="empty" title="暂无使用说明" description="当前 Skill 还没有可展示的 Markdown 内容" />
)}
</section>
</div>
)}
</Drawer>
);
}
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';
import { App } from '../../App';
function renderSkills(path = '/skills') {
window.localStorage.setItem('agent-admin-local-login', 'true');
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
}
describe('SkillListPage', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('renders the list page structure and read-only table', () => {
renderSkills();
expect(screen.getByRole('heading', { name: 'Skill目录' })).toBeInTheDocument();
expect(screen.getByText('关键词:')).toBeInTheDocument();
expect(screen.getByLabelText('搜索Skill关键词')).toBeInTheDocument();
expect(screen.getByPlaceholderText('搜索 Skill 名称或编码')).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();
expect(screen.getByRole('columnheader', { name: '简介' })).toBeInTheDocument();
expect(screen.getByRole('columnheader', { name: '操作' })).toBeInTheDocument();
expect(screen.getByText('共 2 条')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: '新建Skill' })).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', () => {
renderSkills();
expect(screen.getByTestId('skill-keyword-control')).toHaveClass('w-[200px]');
expect(screen.getByTestId('skill-search-actions')).toHaveClass('ml-auto', 'justify-end');
});
it('filters only after search submission and resets to default list', () => {
renderSkills();
fireEvent.change(screen.getByLabelText('搜索Skill关键词'), { target: { value: 'markdown' } });
expect(screen.getByText('browser:browser')).toBeInTheDocument();
expect(screen.getByText('imagegen')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '搜索' }));
expect(screen.getByText('imagegen')).toBeInTheDocument();
expect(screen.queryByText('browser:browser')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '重置' }));
expect(screen.getByLabelText('搜索Skill关键词')).toHaveValue('');
expect(screen.getByText('browser:browser')).toBeInTheDocument();
});
it('opens detail drawer, renders markdown content, and preserves search context after close', () => {
renderSkills();
fireEvent.change(screen.getByLabelText('搜索Skill关键词'), { target: { value: 'browser' } });
fireEvent.click(screen.getByRole('button', { name: '搜索' }));
fireEvent.click(screen.getByRole('button', { name: '查看browser:browser详情' }));
const drawer = screen.getByRole('dialog', { name: 'Skill详情' });
expect(within(drawer).getByText('browser:browser')).toBeInTheDocument();
expect(within(drawer).getByRole('heading', { name: 'Browser automation for the Codex in-app browser.' })).toBeInTheDocument();
expect(within(drawer).getByRole('link', { name: 'localhost' })).toHaveAttribute('href', 'http://localhost');
const codeBlock = within(drawer).getByTestId('skill-markdown-codeblock');
expect(within(codeBlock).getByText('npm run dev')).toBeInTheDocument();
expect(codeBlock).toHaveClass('overflow-x-auto');
fireEvent.click(within(drawer).getByRole('button', { name: '关闭' }));
expect(screen.queryByRole('dialog', { name: 'Skill详情' })).not.toBeInTheDocument();
expect(screen.getByLabelText('搜索Skill关键词')).toHaveValue('browser');
expect(screen.getByText('browser:browser')).toBeInTheDocument();
expect(screen.queryByText('imagegen')).not.toBeInTheDocument();
});
it('renders recoverable list and detail states from mock fixtures', () => {
renderSkills('/skills?scenario=error');
expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: '重试' }));
expect(screen.getByText('browser:browser')).toBeInTheDocument();
cleanup();
renderSkills('/skills?scenario=empty');
expect(screen.getByText('当前还没有Skill')).toBeInTheDocument();
expect(screen.getByText('共 0 条')).toBeInTheDocument();
cleanup();
renderSkills('/skills?scenario=loading');
expect(screen.getByText('加载中...')).toBeInTheDocument();
expect(screen.getByText('共 0 条')).toBeInTheDocument();
cleanup();
renderSkills('/skills?scenario=detailLoading&detail=imagegen');
expect(screen.getByRole('status', { name: '加载中' })).toBeInTheDocument();
expect(screen.getByText('正在加载 Skill 详情')).toBeInTheDocument();
cleanup();
renderSkills('/skills?scenario=emptyMarkdown&detail=imagegen');
expect(screen.getByText('暂无使用说明')).toBeInTheDocument();
cleanup();
renderSkills('/skills?scenario=detailError&detail=imagegen');
expect(screen.getByText('当前 Skill 详情无法展示')).toBeInTheDocument();
cleanup();
renderSkills('/skills?scenario=longMarkdown&detail=browser:browser');
expect(screen.getByTestId('skill-drawer-scroll')).toHaveClass('overflow-y-auto');
});
});
import { useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Button, Input, StatePlaceholder, Table } from '../../../packages/ui/src';
import { getSkillFixtureByScenario, getSkillList, type SkillListMockItem } from '../../../packages/contracts/skill-list-mock';
import { SkillDetailDrawer } from './SkillDetailDrawer';
import { buildSkillListSearch, readSkillListRouteState } from './skillRouteState';
export function SkillListPage() {
const [searchParams, setSearchParams] = useSearchParams();
const routeState = readSkillListRouteState(searchParams);
const [keyword, setKeyword] = useState(routeState.keyword);
const fixture = getSkillFixtureByScenario(routeState.scenario);
const items = useMemo(
() => getSkillList({ keyword: routeState.keyword, source: fixture.items }),
[fixture.items, routeState.keyword],
);
const hasFilter = Boolean(routeState.keyword);
const totalCount = items.length;
const submitFilters = () => {
setSearchParams(buildSkillListSearch({ scenario: routeState.scenario, keyword, detail: undefined }));
};
const resetFilters = () => {
setKeyword('');
setSearchParams(buildSkillListSearch({ scenario: routeState.scenario, keyword: '', detail: undefined }));
};
const columns = [
{ title: 'Skill编码', dataIndex: 'skill_code' as const },
{ title: 'Skill名称', dataIndex: 'skill_name' as const },
{ title: '简介', dataIndex: 'description' as const },
{
title: '操作',
key: 'actions',
render: (_: unknown, skill: SkillListMockItem) => (
<Button
aria-label={`查看${skill.skill_code}详情`}
size="small"
variant="text"
onClick={() => setSearchParams(buildSkillListSearch({ ...routeState, detail: skill.skill_code }))}
>
查看
</Button>
),
},
];
return (
<section className="grid gap-6">
<header className="grid gap-1 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6">
<h2 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">Skill目录</h2>
<p className="m-0 text-sm text-[var(--gl-color-text-secondary)]">查看 Skill 编码、说明和 Markdown 使用文档</p>
</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">
<div className="flex items-center gap-2 text-sm" data-testid="skill-keyword-field">
<span className="shrink-0">关键词:</span>
<span className="w-[200px]" data-testid="skill-keyword-control">
<Input
aria-label="搜索Skill关键词"
className="w-full"
placeholder="搜索 Skill 名称或编码"
value={keyword}
allowClear
onChange={setKeyword}
onKeyDown={(event) => {
if (event.key === 'Enter') 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">
{fixture.error ? (
<StatePlaceholder
state="error"
title="加载失败"
description="Skill 列表请求失败,当前目录状态未知"
primaryAction={<Button size="small" onClick={() => setSearchParams(buildSkillListSearch({ scenario: 'normal', keyword: routeState.keyword }))}>重试</Button>}
/>
) : (
<>
<Table
rowKey="skill_code"
columns={columns}
dataSource={items}
loading={fixture.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>
<SkillDetailDrawer routeState={routeState} skillCode={routeState.detail} />
</section>
);
}
import type { ReactNode } from 'react';
function renderInline(text: string, keyPrefix: string) {
const nodes: ReactNode[] = [];
const pattern = /(`[^`]+`)|(\[[^\]]+\]\([^)]+\))/g;
let lastIndex = 0;
let match: RegExpExecArray | null;
match = pattern.exec(text);
while (match) {
if (match.index > lastIndex) {
nodes.push(text.slice(lastIndex, match.index));
}
const token = match[0];
if (token.startsWith('`')) {
nodes.push(
<code
key={`${keyPrefix}-code-${match.index}`}
className="rounded bg-[var(--gl-color-bg-page)] px-1.5 py-0.5 font-mono text-[13px]"
>
{token.slice(1, -1)}
</code>,
);
} else {
const link = /^\[([^\]]+)\]\(([^)]+)\)$/.exec(token);
if (link) {
nodes.push(
<a
key={`${keyPrefix}-link-${match.index}`}
className="text-[var(--gl-color-primary)] underline"
href={link[2]}
rel="noreferrer"
target="_blank"
>
{link[1]}
</a>,
);
}
}
lastIndex = match.index + token.length;
match = pattern.exec(text);
}
if (lastIndex < text.length) {
nodes.push(text.slice(lastIndex));
}
return nodes;
}
function renderParagraph(text: string, key: string) {
if (text.startsWith('### ')) return <h4 key={key} className="m-0 text-base font-semibold">{text.slice(4)}</h4>;
if (text.startsWith('## ')) return <h3 key={key} className="m-0 text-lg font-semibold">{text.slice(3)}</h3>;
if (text.startsWith('# ')) return <h2 key={key} className="m-0 text-xl font-semibold">{text.slice(2)}</h2>;
if (text.startsWith('> ')) return <blockquote key={key} className="m-0 border-l-4 border-[var(--gl-color-border-secondary)] pl-3 text-[var(--gl-color-text-secondary)]">{renderInline(text.slice(2), key)}</blockquote>;
return <p key={key} className="m-0 leading-[var(--gl-line-height-md)]">{renderInline(text, key)}</p>;
}
export function SkillMarkdown({ markdown }: { markdown: string }) {
const lines = markdown.split('\n');
const nodes: ReactNode[] = [];
let index = 0;
while (index < lines.length) {
const line = lines[index];
if (!line.trim()) {
index += 1;
continue;
}
if (line.startsWith('```')) {
const codeLines: string[] = [];
index += 1;
while (index < lines.length && !lines[index].startsWith('```')) {
codeLines.push(lines[index]);
index += 1;
}
nodes.push(
<pre
key={`code-${index}`}
className="m-0 overflow-x-auto rounded-[var(--gl-radius-sm)] bg-[#0f172a] p-4 text-[13px] leading-6 text-[#e2e8f0]"
data-testid="skill-markdown-codeblock"
>
<code>{codeLines.join('\n')}</code>
</pre>,
);
index += 1;
continue;
}
if (line.startsWith('- ')) {
const items: string[] = [];
while (index < lines.length && lines[index].startsWith('- ')) {
items.push(lines[index].slice(2));
index += 1;
}
nodes.push(
<ul key={`list-${index}`} className="m-0 grid gap-2 pl-5">
{items.map((item, itemIndex) => <li key={`${index}-${itemIndex}`}>{renderInline(item, `list-${index}-${itemIndex}`)}</li>)}
</ul>,
);
continue;
}
const paragraphLines = [line];
index += 1;
while (index < lines.length && lines[index].trim() && !lines[index].startsWith('- ') && !lines[index].startsWith('```')) {
paragraphLines.push(lines[index]);
index += 1;
}
nodes.push(renderParagraph(paragraphLines.join(' '), `paragraph-${index}`));
}
return <div className="grid gap-4">{nodes}</div>;
}
export interface SkillListRouteState {
scenario: string;
keyword: string;
detail?: string;
}
export function readSkillListRouteState(searchParams: URLSearchParams): SkillListRouteState {
return {
scenario: searchParams.get('scenario') ?? 'normal',
keyword: searchParams.get('keyword') ?? '',
detail: searchParams.get('detail') ?? undefined,
};
}
export function buildSkillListSearch(state: Partial<SkillListRouteState>) {
const searchParams = new URLSearchParams();
if (state.scenario && state.scenario !== 'normal') searchParams.set('scenario', state.scenario);
if (state.keyword) searchParams.set('keyword', state.keyword);
if (state.detail) searchParams.set('detail', state.detail);
const query = searchParams.toString();
return query ? `?${query}` : '';
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!