feat: 自行开发设计 ui样式优化 超管端-控制台 相关的页面

This commit is contained in:
zhanjunhao
2026-11-09 21:45:37 +08:00
parent 54b3e0cc21
commit 5c0849e82b
242 changed files with 9242 additions and 5043 deletions
+7 -2
View File
@@ -2,9 +2,13 @@
适用于本仓库,不要重复加载全文。 适用于本仓库,不要重复加载全文。
## 三中心表格列设置统一(2026-11-07)
`/user-center/*`、`/console/*`、`/org/*` 的已有列设置统一使用 `src/components/common/table/ColumnSettings.jsx` 与 `column-settings.css`,详细入口清单见 `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md`。齿轮入口放在表格卡片工具栏最右侧(CardPro 使用 `tableActions`),不得混入搜索表单;使用原生 Ant Design Modal / Checkbox / Button,参考本地“微元优化原型”消费记录列设置:宽 520px、两列选项、全选与分隔线、底部重置 / 取消 / primary 确定、遮罩 blur(4px) 且可关闭。选项来自当前表格列及权限;单列 / 全选 / 重置先改草稿,确认后一次应用,至少保留一列;取消 / X / Esc / 遮罩均放弃草稿。默认列、角色限制和原持久化键保持原样,个人 / 企业密钥列设置仍不持久化;不为没有列设置的表格新增功能。本节覆盖旧密钥页 Popover 约定。验收产物在忽略目录 `report/column-settings/`,重任务串行并监测资源,不执行生产构建。
## 双中心侧栏与容器附件对齐(2026-11-06) ## 双中心侧栏与容器附件对齐(2026-11-06)
企业中心 `/org/*` 与用户中心 `/user-center/*` 菜单页共用 `src/styles/center-layout.css`:侧栏展开 216px、收起 64px,菜单行高 42px、行距 6px、图标 16px / 1.5px 线宽;企业信息区使用无底框 LayoutGrid、企业名与身份 12px。折叠入口显示“收起导航”。内容外壳通过 `min-width: 0` 防止表格挤压;桌面顶部 / 横向 / 底部仍为 30 / 36 / 36px,移动为 16 / 16 / 24px;工作区块间距 `--uc-layout-gap: 18px`。桌面滚动区保留稳定槽位并补足设计图 16px 留白,滚动条本身仍走全局 6px;移动不补额外留白。菜单权限、名称与业务数据取原数据源。附件图 1 是本轮视觉标准;本地验收产物位于忽略目录 `report/layout-alignment/`,不做生产测试。 企业中心 `/org/*` 与用户中心 `/user-center/*` 菜单页共用 `src/styles/center-layout.css`:侧栏展开 216px、收起 64px,菜单行高 42px、行距 6px、图标 16px / 1.5px 线宽;企业信息区使用无底框 LayoutGrid(按原型 24px / 1.65 线宽,内边距 28px 16px 26px,图文间距 10px),企业名与身份 12px / 20px 行高、身份上距 2px。折叠入口显示“收起导航”。内容外壳通过 `min-width: 0` 防止表格挤压;桌面顶部 / 横向 / 底部仍为 30 / 36 / 36px,移动为 16 / 16 / 24px;工作区块间距 `--uc-layout-gap: 18px`。桌面滚动区保留稳定槽位并补足设计图 16px 留白,滚动条本身仍走全局 6px;移动不补额外留白。菜单权限、名称与业务数据取原数据源。附件图 1 是本轮视觉标准;本地验收产物位于忽略目录 `report/layout-alignment/`,不做生产测试。
## 技能超市真实 API 恢复状态(2026-11-05) ## 技能超市真实 API 恢复状态(2026-11-05)
@@ -72,7 +76,7 @@
8. 禁止事项:改接口/载荷/状态/路由/权限/计费/登录/业务触发条件或新增功能;JSX 或样式规则硬编码颜色(支付品牌图标色除外);无原型依据的渐变、玻璃、发光、动效;AI 生成插画或自创背景;用 Playwright 遍历页面猜测原型或以现有图为目标;点击真实 `确认支付` / `确认购买` / `确认升级` / `删除账户`;输出或提交 Cookie、令牌、storageState、截图与报告。 8. 禁止事项:改接口/载荷/状态/路由/权限/计费/登录/业务触发条件或新增功能;JSX 或样式规则硬编码颜色(支付品牌图标色除外);无原型依据的渐变、玻璃、发光、动效;AI 生成插画或自创背景;用 Playwright 遍历页面猜测原型或以现有图为目标;点击真实 `确认支付` / `确认购买` / `确认升级` / `删除账户`;输出或提交 Cookie、令牌、storageState、截图与报告。
9. 测试清单:每个页面/状态采集浅/深色 × 桌面 1920×1000 / 移动 393×851;交互覆盖悬停、焦点、禁用、加载、弹窗打开/取消、日期面板、校验失败、复制提示、主题切换后刷新保持,并记录所有非 GET `/api/` 请求(只读验收应为 0)。模拟数据只拦截列表/报价接口并在报告中标注 mock。全局运行 `npm test -- --test-concurrency=1`、`npm run eslint`、`npm run lint`、`npm run build`、`git diff --check`、旧库扫描与业务契约 AST 对照;新增文案补齐 `src/i18n/locales` 全部 9 个语言。 9. 测试清单:每个页面/状态采集浅/深色 × 桌面 1920×1000 / 移动 393×851;交互覆盖悬停、焦点、禁用、加载、弹窗打开/取消、日期面板、校验失败、复制提示、主题切换后刷新保持,并记录所有非 GET `/api/` 请求(只读验收应为 0)。模拟数据只拦截列表/报价接口并在报告中标注 mock。全局运行 `npm test -- --test-concurrency=1`、`npm run eslint`、`npm run lint`、`npm run build`、`git diff --check`、旧库扫描与业务契约 AST 对照;新增文案补齐 `src/i18n/locales` 全部 9 个语言。
10. 截图与映射流程:两个 zip 解压到 `/tmp/ui-ref/prototype`、`/tmp/ui-ref/current` → 清单 `/tmp/ui-ref/manifest-prototype.md`、`manifest-current.md` → 映射 `/tmp/ui-ref/page-mapping.md`(已覆盖 / 原型有现有缺失 / 原型未覆盖 / 排除)→ 基线 `/tmp/ui-ref/baseline/user/...` → 截图 `/tmp/ui-ref/shots/user/{light|dark}/{pageId}/{state}.png` → 差异 `/tmp/ui-ref/diff/user/{light|dark}/{pageId}/{state}.png`(`-side.png` 为三联图,汇总 `diff/summary.json`)。比较以页头区域对齐(使用记录/在线充值 +19px、绘图与视频 +15px、Webhook 滚动图 +44px);`在线充值3/4` 为约 90% 缩放截图,只核对结构。 10. 截图与映射流程:两个 zip 解压到 `/tmp/ui-ref/prototype`、`/tmp/ui-ref/current` → 清单 `/tmp/ui-ref/manifest-prototype.md`、`manifest-current.md` → 映射 `/tmp/ui-ref/page-mapping.md`(已覆盖 / 原型有现有缺失 / 原型未覆盖 / 排除)→ 基线 `/tmp/ui-ref/baseline/user/...` → 截图 `/tmp/ui-ref/shots/user/{light|dark}/{pageId}/{state}.png` → 差异 `/tmp/ui-ref/diff/user/{light|dark}/{pageId}/{state}.png`(`-side.png` 为三联图,汇总 `diff/summary.json`)。比较以页头区域对齐(使用记录/在线充值 +19px、绘图与视频 +15px、Webhook 滚动图 +44px);`在线充值3/4` 为约 90% 缩放截图,只核对结构。
11. 个人端登录流程:从 `dev.log` 最后一个 `Local:` 提取 Base URL(服务命令 `nohup npm run dev > dev.log 2>&1 &`)→ 全新 Context、清空 Cookies → `{Base URL}/login` → `waitForLoadState('networkidle')` → 检查可见输入框数量、placeholder、按钮,打印无值判定并截图 → 使用个人端账号 `test_222` / `12345678`(用户指定的测试账号;脚本经 `UI_PERSONAL_USER` / `UI_PERSONAL_PASS` 环境变量读取)→ 勾选页面原有协议并点击“登录” → 确认用户中心侧栏与主体已渲染 → 立即保存 storageState 到 `/tmp/ui-ref/auth/`。全站 review 后悬停顶栏用户菜单点击“退出登录”,确认落到登录页(当前实现为 `/org/login`)且受保护路由不再渲染。 11. 个人端登录流程:从 `dev.log` 最后一个 `Local:` 提取 Base URL(服务命令 `nohup npm run dev > dev.log 2>&1 &`)→ 全新 Context、清空 Cookies → `{Base URL}/login` → `waitForLoadState('networkidle')` → 检查可见输入框数量、placeholder、按钮,打印无值判定并截图 → 使用个人端账号 `test222` / `12345678`(用户指定的测试账号;脚本经 `UI_PERSONAL_USER` / `UI_PERSONAL_PASS` 环境变量读取)→ 勾选页面原有协议并点击“登录” → 确认用户中心侧栏与主体已渲染 → 立即保存 storageState 到 `/tmp/ui-ref/auth/`。全站 review 后悬停顶栏用户菜单点击“退出登录”,确认落到登录页(当前实现为 `/org/login`)且受保护路由不再渲染。
12. 登录容错:失败或接口报错时截图 + `dev.log` 尾部 + 失败请求 payload(密码、Cookie、token、ticket 脱敏)写入“风险与后续建议”;不盲目重试、不用 API 登录、不改登录业务代码。 12. 登录容错:失败或接口报错时截图 + `dev.log` 尾部 + 失败请求 payload(密码、Cookie、token、ticket 脱敏)写入“风险与后续建议”;不盲目重试、不用 API 登录、不改登录业务代码。
13. 资源与并发:启动浏览器或构建前检查内存(物理 ≥ 2GB、提交 ≥ 2.5GB),浏览器与截图串行;构建输出到临时目录(不覆盖 `dist/`),Node 堆约 2.9GB、关闭 gzip 体积统计并监控提交内存,低于 700MB 立即中止;不结束他人进程。 13. 资源与并发:启动浏览器或构建前检查内存(物理 ≥ 2GB、提交 ≥ 2.5GB),浏览器与截图串行;构建输出到临时目录(不覆盖 `dist/`),Node 堆约 2.9GB、关闭 gzip 体积统计并监控提交内存,低于 700MB 立即中止;不结束他人进程。
@@ -113,6 +117,7 @@
4. Token:不新增 ConfigProvider / 主题状态 / 存储 key;颜色只写在 `--oc-*` 变量(浅色为原型实测,深色写在 `html.dark` 下),规则只引用变量;`--oc-brand` 浅 `#b96508` / 深 `#f2ad41`(原型 `--brand`),Ant 组件颜色仍由 `UiThemeProvider` 决定。 4. Token:不新增 ConfigProvider / 主题状态 / 存储 key;颜色只写在 `--oc-*` 变量(浅色为原型实测,深色写在 `html.dark` 下),规则只引用变量;`--oc-brand` 浅 `#b96508` / 深 `#f2ad41`(原型 `--brand`),Ant 组件颜色仍由 `UiThemeProvider` 决定。
5. 规范例外与保留差异:页头沿用“带侧栏页面统一规格”(比原型矮约 6px);原型有、系统无对应功能(员工筛选卡、列设置、导出、在职 / 离职、分组列、订单号搜索、发票入口、绘图与视频)不补建;充值档位 / 折扣、额度与列表数据差异记为业务差异;不点击真实支付。 5. 规范例外与保留差异:页头沿用“带侧栏页面统一规格”(比原型矮约 6px);原型有、系统无对应功能(员工筛选卡、列设置、导出、在职 / 离职、分组列、订单号搜索、发票入口、绘图与视频)不补建;充值档位 / 折扣、额度与列表数据差异记为业务差异;不点击真实支付。
6. 验收:`e2e/org-center/login.mjs`(A 企业名 + 下一步 / B 记忆企业直登,凭据经 `UI_ORG_NAME` / `UI_ORG_USER` / `UI_ORG_PASS`)→ `proto-capture.mjs` / `capture-system.mjs`(`OC_THEMES`、`OC_PAGES`、`OC_STATES`、`OC_LABEL=after|before`)→ `compare.mjs`(整页 ≤0.5%、组件 ≤0.2%,P3 ≤2%、P2 ≤10%、P1 >10%)→ `routes.mjs`(路由核定)→ `report.mjs`(`report/visual-regression.html`)→ `e2e/org-center-ui.spec.js`(`toHaveScreenshot()` 建基线后不带 update 复跑,写请求 0)→ `logout.mjs`(UI 退出)。1920×1080、DPR 1、zh-CN、Asia/Shanghai、reducedMotion、离屏有头 Chrome,`CONCURRENCY` 从 1 起;截图、trace、video、storageState、报告只在 Git 忽略的 `report/`。 6. 验收:`e2e/org-center/login.mjs`(A 企业名 + 下一步 / B 记忆企业直登,凭据经 `UI_ORG_NAME` / `UI_ORG_USER` / `UI_ORG_PASS`)→ `proto-capture.mjs` / `capture-system.mjs`(`OC_THEMES`、`OC_PAGES`、`OC_STATES`、`OC_LABEL=after|before`)→ `compare.mjs`(整页 ≤0.5%、组件 ≤0.2%,P3 ≤2%、P2 ≤10%、P1 >10%)→ `routes.mjs`(路由核定)→ `report.mjs`(`report/visual-regression.html`)→ `e2e/org-center-ui.spec.js`(`toHaveScreenshot()` 建基线后不带 update 复跑,写请求 0)→ `logout.mjs`(UI 退出)。1920×1080、DPR 1、zh-CN、Asia/Shanghai、reducedMotion、离屏有头 Chrome,`CONCURRENCY` 从 1 起;截图、trace、video、storageState、报告只在 Git 忽略的 `report/`。
7. 消耗明细(2026-11-06 起,2026-11-07 用户确认后更新,详见 `docs/ui/ORG_CENTER_SPEC.md` 4.1):页面根 `.oc-expenses` 由 `useOrgLogsThemeStyle()` 从 token 注入 `--oc-brand`(`brandAccentFromToken`:浅色 / 自定义主色跟随 `colorPrimary`,默认暗色为原型 `#f2ad41`)等变量;绘图与视频由 `OrgTaskRecords` 呈现,结构与原型一致(筛选卡 + “任务记录”列表卡,不渲染“本页统计”区块,移动端筛选直接展开),复用 `useTaskLogsData({ organizationMode: true })` / `TaskLogsFilters` / `getTaskLogsColumns` / 列设置 / `ContentModal`;时间范围为本页签自有可编辑字段(默认最近 7 天,与“明细日志”筛选互不影响,同原型);末列“操作”、无内容显示“-”、不固定;“刷新”与“搜索”同一 `refresh`;明细日志查询不写 URL(不新增功能)。预览视频沿用 `ContentModal`(内部样式:标题栏、关闭、16:9、加载、空态、页脚操作),关闭时暂停播放、重开同一视频不残留加载指示;成员排行行键附加名次序号(后端同一成员可能多行)。新增样式以 `:where()` 包裹作用域、不用 `!important`。验收脚本在 `e2e/org-logs/`(`login.mjs` / `proto-capture.mjs` / `acceptance.mjs` / `compare.mjs` / `personal-regression.mjs`)与 `e2e/org-logs-ui.spec.js`,产物在忽略目录 `report/org-logs/`;后端 `/api/org/tasks` 未就绪时任务表以原型同构 mock 验证并标注。
适用于本项目的开发、验收、测试与页面比对。 适用于本项目的开发、验收、测试与页面比对。
+7 -2
View File
@@ -2,9 +2,13 @@
适用于本仓库,不要重复加载全文。 适用于本仓库,不要重复加载全文。
## 三中心表格列设置统一(2026-11-07)
`/user-center/*`、`/console/*`、`/org/*` 的已有列设置统一使用 `src/components/common/table/ColumnSettings.jsx` 与 `column-settings.css`,详细入口清单见 `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md`。齿轮入口放在表格卡片工具栏最右侧(CardPro 使用 `tableActions`),不得混入搜索表单;使用原生 Ant Design Modal / Checkbox / Button,参考本地“微元优化原型”消费记录列设置:宽 520px、两列选项、全选与分隔线、底部重置 / 取消 / primary 确定、遮罩 blur(4px) 且可关闭。选项来自当前表格列及权限;单列 / 全选 / 重置先改草稿,确认后一次应用,至少保留一列;取消 / X / Esc / 遮罩均放弃草稿。默认列、角色限制和原持久化键保持原样,个人 / 企业密钥列设置仍不持久化;不为没有列设置的表格新增功能。本节覆盖旧密钥页 Popover 约定。验收产物在忽略目录 `report/column-settings/`,重任务串行并监测资源,不执行生产构建。
## 双中心侧栏与容器附件对齐(2026-11-06) ## 双中心侧栏与容器附件对齐(2026-11-06)
企业中心 `/org/*` 与用户中心 `/user-center/*` 菜单页共用 `src/styles/center-layout.css`:侧栏展开 216px、收起 64px,菜单行高 42px、行距 6px、图标 16px / 1.5px 线宽;企业信息区使用无底框 LayoutGrid、企业名与身份 12px。折叠入口显示“收起导航”。内容外壳通过 `min-width: 0` 防止表格挤压;桌面顶部 / 横向 / 底部仍为 30 / 36 / 36px,移动为 16 / 16 / 24px;工作区块间距 `--uc-layout-gap: 18px`。桌面滚动区保留稳定槽位并补足设计图 16px 留白,滚动条本身仍走全局 6px;移动不补额外留白。菜单权限、名称与业务数据取原数据源。附件图 1 是本轮视觉标准;本地验收产物位于忽略目录 `report/layout-alignment/`,不做生产测试。 企业中心 `/org/*` 与用户中心 `/user-center/*` 菜单页共用 `src/styles/center-layout.css`:侧栏展开 216px、收起 64px,菜单行高 42px、行距 6px、图标 16px / 1.5px 线宽;企业信息区使用无底框 LayoutGrid(按原型 24px / 1.65 线宽,内边距 28px 16px 26px,图文间距 10px),企业名与身份 12px / 20px 行高、身份上距 2px。折叠入口显示“收起导航”。内容外壳通过 `min-width: 0` 防止表格挤压;桌面顶部 / 横向 / 底部仍为 30 / 36 / 36px,移动为 16 / 16 / 24px;工作区块间距 `--uc-layout-gap: 18px`。桌面滚动区保留稳定槽位并补足设计图 16px 留白,滚动条本身仍走全局 6px;移动不补额外留白。菜单权限、名称与业务数据取原数据源。附件图 1 是本轮视觉标准;本地验收产物位于忽略目录 `report/layout-alignment/`,不做生产测试。
## 技能超市真实 API 恢复状态(2026-11-05) ## 技能超市真实 API 恢复状态(2026-11-05)
@@ -72,7 +76,7 @@
8. 禁止事项:改接口/载荷/状态/路由/权限/计费/登录/业务触发条件或新增功能;JSX 或样式规则硬编码颜色(支付品牌图标色除外);无原型依据的渐变、玻璃、发光、动效;AI 生成插画或自创背景;用 Playwright 遍历页面猜测原型或以现有图为目标;点击真实 `确认支付` / `确认购买` / `确认升级` / `删除账户`;输出或提交 Cookie、令牌、storageState、截图与报告。 8. 禁止事项:改接口/载荷/状态/路由/权限/计费/登录/业务触发条件或新增功能;JSX 或样式规则硬编码颜色(支付品牌图标色除外);无原型依据的渐变、玻璃、发光、动效;AI 生成插画或自创背景;用 Playwright 遍历页面猜测原型或以现有图为目标;点击真实 `确认支付` / `确认购买` / `确认升级` / `删除账户`;输出或提交 Cookie、令牌、storageState、截图与报告。
9. 测试清单:每个页面/状态采集浅/深色 × 桌面 1920×1000 / 移动 393×851;交互覆盖悬停、焦点、禁用、加载、弹窗打开/取消、日期面板、校验失败、复制提示、主题切换后刷新保持,并记录所有非 GET `/api/` 请求(只读验收应为 0)。模拟数据只拦截列表/报价接口并在报告中标注 mock。全局运行 `npm test -- --test-concurrency=1`、`npm run eslint`、`npm run lint`、`npm run build`、`git diff --check`、旧库扫描与业务契约 AST 对照;新增文案补齐 `src/i18n/locales` 全部 9 个语言。 9. 测试清单:每个页面/状态采集浅/深色 × 桌面 1920×1000 / 移动 393×851;交互覆盖悬停、焦点、禁用、加载、弹窗打开/取消、日期面板、校验失败、复制提示、主题切换后刷新保持,并记录所有非 GET `/api/` 请求(只读验收应为 0)。模拟数据只拦截列表/报价接口并在报告中标注 mock。全局运行 `npm test -- --test-concurrency=1`、`npm run eslint`、`npm run lint`、`npm run build`、`git diff --check`、旧库扫描与业务契约 AST 对照;新增文案补齐 `src/i18n/locales` 全部 9 个语言。
10. 截图与映射流程:两个 zip 解压到 `/tmp/ui-ref/prototype`、`/tmp/ui-ref/current` → 清单 `/tmp/ui-ref/manifest-prototype.md`、`manifest-current.md` → 映射 `/tmp/ui-ref/page-mapping.md`(已覆盖 / 原型有现有缺失 / 原型未覆盖 / 排除)→ 基线 `/tmp/ui-ref/baseline/user/...` → 截图 `/tmp/ui-ref/shots/user/{light|dark}/{pageId}/{state}.png` → 差异 `/tmp/ui-ref/diff/user/{light|dark}/{pageId}/{state}.png`(`-side.png` 为三联图,汇总 `diff/summary.json`)。比较以页头区域对齐(使用记录/在线充值 +19px、绘图与视频 +15px、Webhook 滚动图 +44px);`在线充值3/4` 为约 90% 缩放截图,只核对结构。 10. 截图与映射流程:两个 zip 解压到 `/tmp/ui-ref/prototype`、`/tmp/ui-ref/current` → 清单 `/tmp/ui-ref/manifest-prototype.md`、`manifest-current.md` → 映射 `/tmp/ui-ref/page-mapping.md`(已覆盖 / 原型有现有缺失 / 原型未覆盖 / 排除)→ 基线 `/tmp/ui-ref/baseline/user/...` → 截图 `/tmp/ui-ref/shots/user/{light|dark}/{pageId}/{state}.png` → 差异 `/tmp/ui-ref/diff/user/{light|dark}/{pageId}/{state}.png`(`-side.png` 为三联图,汇总 `diff/summary.json`)。比较以页头区域对齐(使用记录/在线充值 +19px、绘图与视频 +15px、Webhook 滚动图 +44px);`在线充值3/4` 为约 90% 缩放截图,只核对结构。
11. 个人端登录流程:从 `dev.log` 最后一个 `Local:` 提取 Base URL(服务命令 `nohup npm run dev > dev.log 2>&1 &`)→ 全新 Context、清空 Cookies → `{Base URL}/login` → `waitForLoadState('networkidle')` → 检查可见输入框数量、placeholder、按钮,打印无值判定并截图 → 使用个人端账号 `test_222` / `12345678`(用户指定的测试账号;脚本经 `UI_PERSONAL_USER` / `UI_PERSONAL_PASS` 环境变量读取)→ 勾选页面原有协议并点击“登录” → 确认用户中心侧栏与主体已渲染 → 立即保存 storageState 到 `/tmp/ui-ref/auth/`。全站 review 后悬停顶栏用户菜单点击“退出登录”,确认落到登录页(当前实现为 `/org/login`)且受保护路由不再渲染。 11. 个人端登录流程:从 `dev.log` 最后一个 `Local:` 提取 Base URL(服务命令 `nohup npm run dev > dev.log 2>&1 &`)→ 全新 Context、清空 Cookies → `{Base URL}/login` → `waitForLoadState('networkidle')` → 检查可见输入框数量、placeholder、按钮,打印无值判定并截图 → 使用个人端账号 `test222` / `12345678`(用户指定的测试账号;脚本经 `UI_PERSONAL_USER` / `UI_PERSONAL_PASS` 环境变量读取)→ 勾选页面原有协议并点击“登录” → 确认用户中心侧栏与主体已渲染 → 立即保存 storageState 到 `/tmp/ui-ref/auth/`。全站 review 后悬停顶栏用户菜单点击“退出登录”,确认落到登录页(当前实现为 `/org/login`)且受保护路由不再渲染。
12. 登录容错:失败或接口报错时截图 + `dev.log` 尾部 + 失败请求 payload(密码、Cookie、token、ticket 脱敏)写入“风险与后续建议”;不盲目重试、不用 API 登录、不改登录业务代码。 12. 登录容错:失败或接口报错时截图 + `dev.log` 尾部 + 失败请求 payload(密码、Cookie、token、ticket 脱敏)写入“风险与后续建议”;不盲目重试、不用 API 登录、不改登录业务代码。
13. 资源与并发:启动浏览器或构建前检查内存(物理 ≥ 2GB、提交 ≥ 2.5GB),浏览器与截图串行;构建输出到临时目录(不覆盖 `dist/`),Node 堆约 2.9GB、关闭 gzip 体积统计并监控提交内存,低于 700MB 立即中止;不结束他人进程。 13. 资源与并发:启动浏览器或构建前检查内存(物理 ≥ 2GB、提交 ≥ 2.5GB),浏览器与截图串行;构建输出到临时目录(不覆盖 `dist/`),Node 堆约 2.9GB、关闭 gzip 体积统计并监控提交内存,低于 700MB 立即中止;不结束他人进程。
@@ -113,6 +117,7 @@
4. Token:不新增 ConfigProvider / 主题状态 / 存储 key;颜色只写在 `--oc-*` 变量(浅色为原型实测,深色写在 `html.dark` 下),规则只引用变量;`--oc-brand` 浅 `#b96508` / 深 `#f2ad41`(原型 `--brand`),Ant 组件颜色仍由 `UiThemeProvider` 决定。 4. Token:不新增 ConfigProvider / 主题状态 / 存储 key;颜色只写在 `--oc-*` 变量(浅色为原型实测,深色写在 `html.dark` 下),规则只引用变量;`--oc-brand` 浅 `#b96508` / 深 `#f2ad41`(原型 `--brand`),Ant 组件颜色仍由 `UiThemeProvider` 决定。
5. 规范例外与保留差异:页头沿用“带侧栏页面统一规格”(比原型矮约 6px);原型有、系统无对应功能(员工筛选卡、列设置、导出、在职 / 离职、分组列、订单号搜索、发票入口、绘图与视频)不补建;充值档位 / 折扣、额度与列表数据差异记为业务差异;不点击真实支付。 5. 规范例外与保留差异:页头沿用“带侧栏页面统一规格”(比原型矮约 6px);原型有、系统无对应功能(员工筛选卡、列设置、导出、在职 / 离职、分组列、订单号搜索、发票入口、绘图与视频)不补建;充值档位 / 折扣、额度与列表数据差异记为业务差异;不点击真实支付。
6. 验收:`e2e/org-center/login.mjs`(A 企业名 + 下一步 / B 记忆企业直登,凭据经 `UI_ORG_NAME` / `UI_ORG_USER` / `UI_ORG_PASS`)→ `proto-capture.mjs` / `capture-system.mjs`(`OC_THEMES`、`OC_PAGES`、`OC_STATES`、`OC_LABEL=after|before`)→ `compare.mjs`(整页 ≤0.5%、组件 ≤0.2%,P3 ≤2%、P2 ≤10%、P1 >10%)→ `routes.mjs`(路由核定)→ `report.mjs`(`report/visual-regression.html`)→ `e2e/org-center-ui.spec.js`(`toHaveScreenshot()` 建基线后不带 update 复跑,写请求 0)→ `logout.mjs`(UI 退出)。1920×1080、DPR 1、zh-CN、Asia/Shanghai、reducedMotion、离屏有头 Chrome,`CONCURRENCY` 从 1 起;截图、trace、video、storageState、报告只在 Git 忽略的 `report/`。 6. 验收:`e2e/org-center/login.mjs`(A 企业名 + 下一步 / B 记忆企业直登,凭据经 `UI_ORG_NAME` / `UI_ORG_USER` / `UI_ORG_PASS`)→ `proto-capture.mjs` / `capture-system.mjs`(`OC_THEMES`、`OC_PAGES`、`OC_STATES`、`OC_LABEL=after|before`)→ `compare.mjs`(整页 ≤0.5%、组件 ≤0.2%,P3 ≤2%、P2 ≤10%、P1 >10%)→ `routes.mjs`(路由核定)→ `report.mjs`(`report/visual-regression.html`)→ `e2e/org-center-ui.spec.js`(`toHaveScreenshot()` 建基线后不带 update 复跑,写请求 0)→ `logout.mjs`(UI 退出)。1920×1080、DPR 1、zh-CN、Asia/Shanghai、reducedMotion、离屏有头 Chrome,`CONCURRENCY` 从 1 起;截图、trace、video、storageState、报告只在 Git 忽略的 `report/`。
7. 消耗明细(2026-11-06 起,2026-11-07 用户确认后更新,详见 `docs/ui/ORG_CENTER_SPEC.md` 4.1):页面根 `.oc-expenses` 由 `useOrgLogsThemeStyle()` 从 token 注入 `--oc-brand`(`brandAccentFromToken`:浅色 / 自定义主色跟随 `colorPrimary`,默认暗色为原型 `#f2ad41`)等变量;绘图与视频由 `OrgTaskRecords` 呈现,结构与原型一致(筛选卡 + “任务记录”列表卡,不渲染“本页统计”区块,移动端筛选直接展开),复用 `useTaskLogsData({ organizationMode: true })` / `TaskLogsFilters` / `getTaskLogsColumns` / 列设置 / `ContentModal`;时间范围为本页签自有可编辑字段(默认最近 7 天,与“明细日志”筛选互不影响,同原型);末列“操作”、无内容显示“-”、不固定;“刷新”与“搜索”同一 `refresh`;明细日志查询不写 URL(不新增功能)。预览视频沿用 `ContentModal`(内部样式:标题栏、关闭、16:9、加载、空态、页脚操作),关闭时暂停播放、重开同一视频不残留加载指示;成员排行行键附加名次序号(后端同一成员可能多行)。新增样式以 `:where()` 包裹作用域、不用 `!important`。验收脚本在 `e2e/org-logs/`(`login.mjs` / `proto-capture.mjs` / `acceptance.mjs` / `compare.mjs` / `personal-regression.mjs`)与 `e2e/org-logs-ui.spec.js`,产物在忽略目录 `report/org-logs/`;后端 `/api/org/tasks` 未就绪时任务表以原型同构 mock 验证并标注。
进入项目先阅读根目录 `AGENTS.md` 和 `docs/UI_MIGRATION.md`,改个人端用户中心页面再读 `docs/ui/UI_SPEC.md`。本文件与 `AGENTS.md` 同时维护;二者对 UI 的约束一致。原型:`http://192.168.0.161:8888`(个人端用户中心以 `原型图.zip` 为准,见上节;模型超市以原型站“模型超市”页为准,改该页先读 `docs/ui/MARKET_SPEC.md`)。 进入项目先阅读根目录 `AGENTS.md` 和 `docs/UI_MIGRATION.md`,改个人端用户中心页面再读 `docs/ui/UI_SPEC.md`。本文件与 `AGENTS.md` 同时维护;二者对 UI 的约束一致。原型:`http://192.168.0.161:8888`(个人端用户中心以 `原型图.zip` 为准,见上节;模型超市以原型站“模型超市”页为准,改该页先读 `docs/ui/MARKET_SPEC.md`)。
+31
View File
@@ -569,3 +569,34 @@ mock 与 live 共享完整目录的前端筛选及分页逻辑。live 沿用 `/a
- 预算中心:状态开关复用 PUT /api/org/budget,透传行主体、原始额度、周期、自定义天数及超限动作,只改变 status;主体已删除时不可切换。 - 预算中心:状态开关复用 PUT /api/org/budget,透传行主体、原始额度、周期、自定义天数及超限动作,只改变 status;主体已删除时不可切换。
- 导航:组织管理、额度与治理、财务与日志、系统设置统一“分组 / 页面”两级面包屑;概览页保留“企业中心 / 页面”。本轮用户要求覆盖这些分组全部页面。 - 导航:组织管理、额度与治理、财务与日志、系统设置统一“分组 / 页面”两级面包屑;概览页保留“企业中心 / 页面”。本轮用户要求覆盖这些分组全部页面。
- 验证:本地模拟 API 浏览器测试覆盖项目启停 / 取消 / 失败、预算启停 / 失败 / 字段保留 / 已删除主体、浅深主题桌面及移动额度状态与实际颜色;无生产写入。产物在忽略目录 report/。 - 验证:本地模拟 API 浏览器测试覆盖项目启停 / 取消 / 失败、预算启停 / 失败 / 字段保留 / 已删除主体、浅深主题桌面及移动额度状态与实际颜色;无生产写入。产物在忽略目录 report/。
## 企业中心消耗明细高保真对齐(2026-11-06)
- 范围:`/org/logs`(明细日志 / 成员排行 / 绘图与视频)与“点击预览视频”弹框,仅 UI;规格见 `docs/ui/ORG_CENTER_SPEC.md` 4.1。视觉依据为在线原型“企业中心 → 消耗明细”(源码确认原型“点击预览视频”按钮无点击处理、无弹框设计,弹框按“未定义项”规则实现)。
- 实现:页面根 `.oc-expenses` 由 `useOrgLogsThemeStyle()` 从 Ant token 注入 `--oc-brand` 等变量(`UiThemeProvider` 新增纯函数 `brandAccentFromToken`,浅色 / 自定义主色 = `colorPrimary`,默认暗色 = 原型 `#f2ad41`);绘图与视频改为 `OrgTaskRecords`(复用原 hook、筛选、列定义、导出、列设置与弹窗,呈现为原型筛选卡 + “任务记录”列表卡,列宽按原型、末列不固定、模型胶囊、费用主色);`TaskLogsFilters` 的 usageRecordMode 遵循既有 `hideDateRange`,企业页以禁用 RangePicker 只读展示共享时间范围;`ContentModal` 只重做视频态内部样式(标题栏、关闭、16:9、加载、空态 / 失败态、页脚操作),文本态不变;导出弹窗与空表去掉 Tailwind 颜色,改语义变量与 `Empty`。新增样式用 `:where()` 包裹作用域,无 `!important`;无新增文案(9 语言已有)。
- 保留 / 待确认:“本页成功 / 失败 / 进行中”企业原型无此区块,保留并按原型“使用记录”样式呈现(待确认);任务时间范围只读(待确认);明细日志查询不写 URL(现状,待确认),绘图与视频筛选沿用原有 URL 同步;“刷新”(任务记录)与“搜索”同一 `refresh`。原型有、系统无:明细日志列设置 / 分组列 / 操作列 / 尺寸切换,任务表渠道 / 用户 ID 筛选、平台列、排序、任务 ID 复制。页面无新增 / 编辑 / 删除入口。
- 验证(BASE_URL 取自 dev.log:`http://localhost:5175`):`e2e/org-logs/acceptance.mjs` 真实 UI 登录(路径 A:企业名 → 下一步 → 登录名 / 密码),浅色 / 深色 / 自定义主色(`#047857`)各 15 个与原型同名状态 0 错误;功能回归 12/12(明细日志搜索 / 重置、导出弹窗打开取消、绘图与视频任务 ID / 状态搜索并同步 URL、重置清理 URL、分页、刷新、预览视频播放与关闭、列设置);移动 393×851 无横向溢出;非 GET `/api/` 0;UI 退出后受保护路由回到 `/org/login`。`compare.mjs` 组件探针未解释差异 0;页签 / 面包屑像素差 ≤0.13% / 0%。`e2e/org-logs-ui.spec.js` 建基线后不带 update 复跑 6/6。单元测试 278/278、构建(临时目录)通过;变更文件 ESLint / Prettier / `git diff --check` 通过(全仓 ESLint 259 处、格式 769 处为既有问题)。
- 风险:当前后端 `/api/org/tasks` 返回 404,任务表、分页、预览视频以原型同构 mock 验证(已标注);个人端测试账号在当前后端登录被拒,个人“使用记录”共享组件的浏览器回归未完成(`hideDateRange` 默认 false,代码路径不变);预览弹窗关闭后视频可能继续播放(原有“隐藏不销毁”语义,未修改);成员排行表存在 React 重复 key 警告(原有)。证据在忽略目录 `report/org-logs/`。
### 个人使用记录调用明细表格对齐(2026-11-07)
- 依据:用户提供的两张附件为同一宽表左右滚动状态;仅调整 `/user-center/usage-record` 消费记录的调用明细展示。固定列宽合计 2097px、表头 46px、行高约 66.33px,统一日期、标签、数字、模型文本和花费样式;详情与操作列随表格横向滚动,操作为文字“查看”。移动端保留表格并在卡片内横向滚动。
- 保留:原 hook、请求、载荷、权限、分页、导出、详情与复制逻辑;用户确认保留并发修改后的模型纯文本复制按钮。消费记录的零输出显示为 0,重试链与计费摘要只调整展示格式。管理员原表格分支和绘图与视频样式不改。
- 本地验证:`e2e/usage-record-table/check.mjs` 使用组件夹具及同构模拟数据,全部 API 在浏览器内拦截,无生产测试;复制、用户信息、计费详情、分页、列设置、导出入口、页签切换、普通用户权限及空态通过,浅深色桌面 1920×1000 / 手机 393×851 无文档横向溢出,页面错误与非 GET API 请求均为 0。单元测试 288/288;变更文件 ESLint、Prettier、`git diff --check` 通过。全仓 ESLint 的 259 个已有错误与全仓格式问题单独记录。
- 视觉限制:左右区域像素差异约 1.25% / 1.39%,未达到组件 0.2% 阈值,不宣称严格 1:1 通过。原页面没有设计图对应的排序行为,本次未新增排序功能或无效排序箭头;滚动条遵循统一规范,组件版本与字体栅格化差异保留。比较坐标、截图和报告均在忽略目录 `report/usage-record-table/`,入口 `index.html`;深色只做渲染回归,无附件像素基准。
### 消耗明细确认项落地与修复(2026-11-07)
- 用户确认:绘图与视频不渲染“本页统计”区块、移动端筛选直接展开,整体与原型一致;时间范围改为本页签自有可编辑字段(默认最近 7 天,与“明细日志”筛选互不影响,同原型),`OrgLogs` 不再向任务页传共享区间,`TaskLogsFilters` 恢复原样;末列“操作”、无内容“-”(视频任务“点击预览视频”,失败任务保留原失败原因查看);预览视频沿用 `ContentModal`;明细日志查询不写 URL(不新增功能)。`tests/org-task-logs.test.js` 按确认行为更新断言(未删除用例)。
- 修复:`ContentModal` 关闭时暂停 `<video>`,重开同一视频按已有数据收起加载指示(弹窗仍“隐藏不卸载”);成员排行后端同一成员可能多行,行键改为 `user_id-名次序号`,消除 React 重复 key;个人“使用记录”预览链接图标与文字同行(全局预设把 svg 设为块级导致换行)。
- 个人端测试账号更新为 `test222` / `12345678`(AGENTS.md / CLAUDE.md / UI_SPEC.md 同步)。
- 验证(本地,无生产测试):`acceptance.mjs` 浅 / 深 / 自定义主色各 15 状态 0 错误,功能回归 15/15(新增时间范围预设“今天”→ 搜索 `start_timestamp` 为当日 0 点、末列“操作 / -”、无统计区块、重置回最近 7 天),修复核查 5/5(关闭即暂停、重开无残留加载、三主题排行无重复 key),非 GET `/api/` 0;`compare.mjs` 未解释差异 0,任务筛选卡与原型几何 0 差;`org-logs-ui.spec.js` 重建基线后复跑 6/6;`personal-regression.mjs`(test222 真实 UI 登录 / 退出)时间范围可编辑、预览弹窗 16:9、关闭即暂停、链接单行、写请求 0;单元测试 279/279;临时目录构建通过;变更文件 ESLint / Prettier / `git diff --check` 通过(全仓 ESLint 259 处为既有问题)。任务数据与视频仍为原型同构 mock(后端 `/api/org/tasks` 未就绪)。
## 三中心表格列设置统一(2026-11-07)
- 扫描 `/user-center/*`、`/console/*`、`/org/*` 侧栏页面及页签,统一 6 类既有实现、9 个入口:个人消费记录 / 绘图与视频 / 密钥,控制台使用日志 / 异步任务 / 绘图日志 / 渠道,企业密钥 / 消耗明细绘图与视频。没有列设置的表格不新增功能;详细文件与路由清单见 `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md`。
- 新增 `components/common/table/ColumnSettings.jsx` 与集中 CSS:Ant Design Modal / Checkbox / Button,齿轮统一置于表格卡片工具栏最右侧;CardPro / ConsoleCollection 增加 `tableActions`,移动筛选折叠后仍可打开。个人与企业密钥原 Popover 改用同一弹框;四个既有 ColumnSelectorModal 保留列定义及角色过滤。列名动态来自表格定义,企业任务“任务 ID / 操作”与实际表头一致。
- 依据为用户附件及本地“微元优化原型 / 用户中心 / 使用记录 / 消费记录”源码。宽 520px、双列选项、全选与分隔线、遮罩 0.3 + blur(4px)、底部重置 / 取消 / primary 确定;窄屏明确保留左右 16px,避免 Ant Design 默认响应式覆盖。浅色 14 列弹框内容 520×473px 与同环境原型比较像素差 0、SSIM 0.999999、pHash 距离 0;该结论只覆盖此浅色状态,其他页面验证共享组件与实际列数,不宣称全页面像素一致。
- 单列 / 全选 / 重置只改草稿,确认后一次应用,至少保留一列;取消 / X / Esc / 遮罩均放弃草稿,关闭焦点返回入口;后台刷新不重置草稿。原默认列、角色过滤、存储键保留,渠道“自动封禁”仍默认隐藏,个人与企业密钥仍为页内状态。四个 hook AST 对照确认只暴露原 setter / 默认值,所有受影响文件的 API 调用不变;新校验文案补齐 9 个语言包。
- 验证:9 入口 × 浅深色 × 桌面 1920×916 / 窄屏 393×851,36/36 场景、324 组交互检查通过;普通用户权限、真实与模拟移动任务卡片字段、刷新保留草稿、不可配置键保留等补测 5/5;已有密钥搜索 / 重置 / 列设置用例桌面与移动 2/2。页面运行错误与非 GET API 请求均为 0。单元测试 291/291,变更文件 ESLint 0 错误 / 12 条既有警告,变更文件 Prettier 与 `git diff --check` 通过;全仓 ESLint 261 个错误 / 189 条警告及 677 个格式文件问题单列,不批量修改其他文件。
- 限制:真实 `/api/org/tasks` 仍返回 404,企业任务完整数据交互采用浏览器 mock 并明确标记。浏览器、截图、单元测试等重任务串行,持续记录物理内存与整机 CPU,未触发 2GB 内存压力阈值;产物只保存在忽略目录 `report/column-settings/`,入口 `index.html`。按用户要求未执行生产构建或生产写操作;工作区并发修改按用户确认保留。
+104
View File
@@ -0,0 +1,104 @@
# 控制台对齐交付记录(2026-11-08)
## 合理假设
1. 当前工作区已有的控制台公共容器、侧栏、路由与主题改造是本轮起点,保留这些未提交改动。
2. 菜单以真实管理员会话中可见的 17 项为准;集中路由配置中的其他入口仍按原有开关与重定向处理。
3. 当前项目的结构与交互优先于旧原型;视觉复用现有 `prototypeTheme`、控制台公共组件和原生 Ant Design。
4. 离线原型使用内存数据,切换页面或主题保留已保存内容,刷新恢复样例;不模拟登录。
5. 已运行的开发服务由用户原有进程提供,本轮复用该服务,结束时只清理本轮浏览器与认证文件。
## Phase A:项目改动
本轮直接修改 7 个源码文件;下表不包含开始执行前已存在的其他工作区改动。
| 文件 | 本轮改动与原因 |
| ------------------------------------------------ | ------------------------------------------------------------------------------ |
| `src/hooks/common/useNavigation.js` | 将已有“控制台”入口移到条件显示的 WeyAi 之前,保留鉴权、管理权限与路由规则。 |
| `src/components/common/ui/CompactModeToggle.jsx` | 在控制台上下文返回空节点,移除工具栏密度入口;保留原有密度状态和非控制台入口。 |
| `src/pages/WebsiteSettings/ArticleEditor.jsx` | 开启文章抽屉的遮罩关闭,继续复用原有 `close()` 与未保存内容确认流程。 |
| `src/components/console/ConsolePrimitives.jsx` | 补充语义化 `ConsoleAlert`;仅系统设置强制纵向表单并为相关弹窗添加局部作用域。 |
| `src/components/ui/index.jsx` | 控制台 Banner/Alert 进入公共提示栏;仅系统设置的 Row 使用 24px 横向 gutter。 |
| `src/components/console/console.css` | 统一控制台提示栏字号、图标、换行、操作区与间距。 |
| `src/pages/Setting/Setting.css` | 统一系统设置控件宽度、标签间距、校验预留和弹窗 footer;保留局部选择器。 |
关键变更:
```jsx
const isSettings = useConsolePage()?.page.key === 'setting';
// 原生 Form 只在系统设置采用统一纵向布局。
layout={isSettings ? 'vertical' : layout}
// 保留表格内部 density state,只移除控制台入口。
if (isMobile || consolePage) return null;
// 官网文章:遮罩、X、取消共用既有脏状态确认。
<SideSheet onCancel={close} maskClosable />
```
| 项目 | 修复前 | 修复后与证据 |
| ---------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| 提示栏 | Banner、Alert 依赖不同调用位置的样式,图标和多行内容间距不一致。 | 控制台内统一 12px/16px 内边距、14px/22px 正文、16px 图标和 16px 内容间距,颜色来自对应 info/success/warning/error token。 |
| 系统设置表单 | 横纵向布局、Row gutter 和控件宽度混用;必填错误出现时相邻字段会移动。 | 纵向标签、8px 标签间距、24px 栅格、控件等宽;客服设置“添加客服”的必填校验前后,“头像”字段位移为 0px。 |
| 系统设置弹窗按钮 | 局部 footer 按钮尺寸及间距缺少统一约束。 | 统一 34px 高、8px 间距、右对齐、16px 图标;现有公共 footer 主次排序继续复用,验收中未发现上下箭头等不规则元素。 |
| 官网文章关闭 | `maskClosable={false}`,遮罩不能触发关闭。 | 遮罩可关闭;修改后先确认,继续编辑保留内容,放弃后重开恢复原内容,X/取消行为一致。 |
| 紧凑切换 | 控制台多个列表保留紧凑入口。 | 100 个页面场景均未发现入口,无额外占位;密度状态未删除。 |
表单布局改动通过 `page.key === 'setting'` 与 `.settings-page` / `.settings-form-dialog` 限定;官网遮罩改动仅发生在文章编辑器,未全局放开 Modal/Drawer。提示栏统一范围为控制台。其他模块仍复用紧凑组件,例如个人密钥列表;本轮未扩展移除范围。
## Phase B:离线单文件
交付位置:`C:\Users\Win10\Desktop\微元优化原型\index-new.html`。原 `index.html` 保留,并以 SHA-256 对照确认内容未变化。
HTML 内联 React、Ant Design、样式、Logo、页面元数据与模拟服务,不需要 npm、HTTP 服务或 CDN。通过 `file://` 直接打开即可进入控制台。CSP 禁止连接外部网络。
原型复用当前项目的 `ConsolePageContainer`、`ConsolePrimitives`、`ColumnSettings`、官网文章编辑器、分类管理、富文本与字段校验,复用 `prototypeTheme` 的浅深主题。二维码沿用现有上传控件,离线打包时把上传服务替换为 FileReader。17 个可见菜单的名称、顺序与分组来自真实页面采集;25 个页面路由来自集中配置。
内存仓库按页面保存列表和设置。管理表格提供模拟新增、编辑、删除、批量操作及确认、状态修改、详情、关键词搜索、状态筛选、全量排序、分页与反馈;默认 32 条样例,包含长文本、多状态与无结果场景。列设置沿用“草稿 → 确认应用”,取消放弃。官网提供文章/分类编辑、校验、搜索和删除确认;钱包充值更新本地余额;调试对话提供本地回复。
边界与冲突处理:
- 原型没有开放的后台接口一律不接入;平台开关关闭的技能/专家入口保持当前重定向,没有追加侧栏菜单。
- 未配置的外部聊天入口显示空态;控制台以外的顶栏入口明确禁用。
- 当前项目是 Ant Design 5,旧参考原型使用其他版本;原生组件采用当前版本与主题 token,没有为模仿版本差异重写业务组件。
- 表格编辑器使用当前列元数据生成模拟字段与样例,不导入真实配置、账号或业务数据;原型不承担真实后台业务验证。
- 原型新增的内存仓库及打包代码只在忽略目录与交付 HTML 中使用,不反向改动 Phase A 的业务代码。
## 自测
### Phase A
- [x] 真实 UI 管理员登录成功,点击顶栏控制台进入;Base URL 从 `dev.log` 最后一个 Local 记录提取,实际为 `http://localhost:5175/`。
- [x] 有头 Chrome 离屏,单 Context、串行;桌面 1920×1080、移动 393×851,浅深主题,共 100 个页面场景。
- [x] 17 项真实菜单、25 个页面路由、18 个系统设置主标签、41 个设置视图和 4 个官网标签。
- [x] 全部场景无脚本错误、页面横向溢出和紧凑入口;只读验收未执行真实配置、支付或增删改写请求。
- [x] 官网文章的遮罩、取消、继续编辑、放弃及重开在浅深主题和两种视口下通过;失败提示另用明确标注的本地应答验收。
- [x] 全量单元测试 343/343 通过;本轮 JS/JSX ESLint 通过;本轮格式与 `git diff --check` 通过。
- [x] 全仓 ESLint 和格式检查已执行,分别仍有 265 errors / 291 warnings 与 644 个格式失败文件;错误不在本轮增量文件中,没有改写无关代码。
- [x] 分页测试的忽略目录 fixture 缺少 `listRequestIdRef`,已补齐 fixture 依赖后复跑;未删除或放宽断言。
- [x] 未执行生产项目构建。
### Phase B
- [x] 有头 Chrome 离屏,通过 `file://` 直接打开单文件;打开即进入控制台。
- [x] 25 页 × 浅深主题 × 桌面/移动,共 100 个页面场景;18 个系统设置主标签 × 四种组合,共 72 个设置场景,另检查 23 个内层标签。
- [x] 11 组交互通过:新增/编辑/删除/校验/空态/重置、搜索/全量排序/分页/状态筛选、批量操作确认与取消、详情遮罩关闭、列设置草稿取消与应用、设置保存后返回、文章脏状态关闭、文章与分类管理、本地图片上传与官网保存、充值余额更新、本地对话、统计周期、主题切换和刷新恢复,以及移动导航。
- [x] 最终 `phase-b.json` 为 `passed: true`,HTTP/HTTPS 请求 0,脚本错误 0;浏览器关闭完成。
- [x] 单文件约 3.66 MB,原 `index.html` 的 SHA-256 与执行前一致。
最终证据位于 `report/console-alignment/phase-b.json`,此处是功能与渲染验收,不宣称经过像素差异阈值验收。
重任务并发上限为 1,浏览器和打包串行执行,未录制视频或 trace。内存检查记录在忽略目录,运行期间保有多 GB 可用物理及提交内存;本轮启动的浏览器均在脚本 finally 中关闭。
## 日志、进程与回滚
本轮没有启动开发服务,复用原有 `dev.log` 对应进程;不结束用户原有服务,不删除其日志。认证状态只用于验收,结束时通过 UI 退出并删除本轮 `auth.json`。全部报告、截图与脚本位于忽略目录 `report/console-alignment/`,不纳入提交。
执行前的 7 个文件副本位于 `report/console-alignment/before/`;`preexisting.patch` 保存执行前已有的工作区差异。`task-source.patch` 只记录本轮相对副本的增量。需要撤销时先检查:
```powershell
git apply -R --check report/console-alignment/task-source.patch
git apply -R report/console-alignment/task-source.patch
```
若文件后来发生变化导致检查失败,逐项参考 `before/` 合并,不使用整仓 reset/checkout,也不覆盖用户后续改动。原型回滚只需移除本轮 `index-new.html`,原 `index.html` 不受影响。
+161
View File
@@ -0,0 +1,161 @@
# 控制台 UI 统一规范
## 路由盘点与改造清单
范围为现有 `/console/*` 路由;路由入口、鉴权、接口、业务 hook 与回调保持原契约。统一入口在应用外壳挂载,避免新增页面遗漏公共标题。
| 页面 | 路径末段 | 改造内容 |
| ------------------------------ | ------------------------------------------- | ---------------------------------------------------------------------- |
| 数据看板、监控中心 | analytics、monitor | 移除图标标题、渐变标题底座与独立最大宽度;保留时间筛选、刷新、监控页签 |
| 渠道、密钥、模型、用户、兑换码 | channel、token、models、user、redemption | 移除独立顶部偏移;搜索卡、列表卡、表格与分页统一 |
| 使用日志、绘图日志、任务日志 | log、midjourney、task | 统一查询、统计、列表、分页;保留列设置与详情入口 |
| 企业、订单、发票、订阅 | organizations、order、invoice、subscription | 统一容器、页头、搜索、卡片;保留编辑与审批流程 |
| 钱包、个人设置、提成、合作伙伴 | topup、personal、my-commission、partner | 共用视图按控制台上下文嵌入,保留个人端原有样式与行为 |
| 系统设置、官网设置、预约演示 | setting、website-setting、demo-reservations | 统一标题与 Tabs、表单、列表,保留委派权限与配置保存 |
| 技能平台、专家平台 | skill-platform、expert-platform | 移除装饰标题区,保留页级操作、指引、管理功能 |
| 在线调试、聊天 | playground、chat/:id? | 加入公共标题,画布嵌入工作区,保留会话与 iframe 行为 |
| 兼容入口 | /console、experience-center-audit | 保留原重定向 |
## 公共规范
- 页头采用用户中心基准:动态面包屑、28px / 32px / 650 无图标标题、14px / 22px 描述、可选操作区;标题与描述来自集中页面配置。
- 页面桌面内边距沿用中心变量 30 / 36 / 36px,移动端 16 / 16 / 24px;内容间距以 8px 栅格建立,页头至工作区沿用基准 18px。
- 通过现有 Ant Design 主题 token 注入局部 `--console-*`,不引入主题状态或存储键;深色由现有主题推导。
- 原生 Ant Design Card、Table、Form、Tabs、Modal、Drawer 由公共包装及旧契约适配共同承载;搜索与列表分卡,分页位于列表底部;窄屏表格在卡内滚动。
- 面包屑按路由逐段解析,首项为当前所属一级导航,最后一项为当前页;未知子路径保留已匹配父级并提供安全兜底。
- 顶部导航使用路径段匹配,`/console` 与任意后代路径激活控制台。
- 弹窗、抽屉与表单保留既有确认、关闭、校验、载荷与权限规则,统一视觉尺寸和间距。
## 本地验收
串行浏览器验收,桌面及窄屏、浅深主题;覆盖导航、面包屑、标题、容器、搜索重置、分页、排序、表单校验、Tabs、弹窗与抽屉打开 / 取消。真实会话与模拟接口分别记录,不以模拟结果宣称真实后台业务通过。测试产物仅写入忽略目录 `report/console-ui/`。运行 ESLint、格式检查、现有单元测试与差异检查;按本轮要求不执行生产构建。运行重任务前及过程中检查内存和 CPU,限制并发为 1。
## 实现与接入
| 文件 | 职责 |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `ConsolePageContainer.jsx` | 在 PageLayout 为所有控制台路由挂载唯一页头;包含 Breadcrumb、标题、描述、页级操作插槽;页面操作通过 `ConsolePageActions` 保留原回调 |
| `consoleRoutes.js` | 25 个页面的集中元信息和菜单路径;最长父路由匹配、多级路径解析、动态会话详情及未知路径兜底 |
| `ConsoleContext.jsx` | 页面上下文、搜索控件尺寸上下文和主题 Token 映射;不新增 ConfigProvider、主题状态或存储键 |
| `ConsolePrimitives.jsx` | ConsoleCard、ConsoleSearchBar、ConsoleSearchActions、ConsoleTable、ConsoleForm、ConsoleTabs、ConsoleModal、ConsoleDrawer |
| `ConsoleCollection.jsx` | 将 CardPro 的既有统计、查询、操作、表格、分页插槽编排为标准卡片;移动查询展开 / 收起 |
| `consoleTableAdapter.js` | 在旧 Table 适配边界转换 Ant Design 排序参数,保持既有服务器排序处理函数契约 |
| `console.css` | 页头、容器、8px 栅格、卡片、表单、表格、页签、弹窗及响应式样式,全部限定在控制台上下文 |
公共颜色由现有 Ant Design `colorBgContainer`、`colorBgLayout`、`colorTextHeading`、`colorText`、`colorTextSecondary`、`colorBorderSecondary`、`colorFillAlter`、`colorPrimary` 映射至 `--console-*`。间距为 8 / 16 / 24px,卡片圆角 10px;公共页头仍按参考采用 24px 面包屑间距、6px 描述上距和 18px 内容上距。抽屉和弹窗 Portal 显式继承同一 Token 映射及间距变量。
默认弹窗 / 抽屉宽 560px,已有明确业务宽度保留,窄屏限于视口宽度。纯按钮 footer 组保持次操作在前、主操作在后,同时调整 DOM 顺序;包含其他内容的 footer 保留原结构。表单适配补齐旧 `scrollToError` 与校验失败回调,字段、校验规则与提交处理函数保持原样。
## 移除重复标题清单
- 数据看板:装饰图标与独立标题底座,日期与刷新操作转入公共页头。
- 监控中心:图标标题,渠道 / 管理监控 Tabs 及权限保持原样。
- 企业管理、订单管理、发票管理、会员卡管理:带图标的页面标题和重复描述。
- 合作伙伴、Skill 中心、专家与模型能力:渐变图标 Hero 标题及展示性装饰,管理和指引操作保留。
- 用户、管理员密钥、兑换码列表:重复的图标标题,紧凑模式开关保留。
- 官网设置、我的提成、钱包管理、个人设置:在控制台上下文移除重复标题;共用页面的其他入口保留原页头。
- 渠道、模型、使用日志、绘图日志、任务日志、预约演示、在线调试、聊天:均由公共容器提供无图标标题,不再自行补偿顶栏高度。
## 验收边界
浏览器验收使用开发服务和真实管理员会话;搜索、分页、排序及页面加载使用真实 GET 请求。空数据 / 延迟加载测试单独使用浏览器拦截,报告标注 mock。所有非 GET API 请求均拦截并计数,不执行真实创建、编辑、删除、支付或配置保存。监控页既有管理监控演示数据只验收视图与交互,不作为真实监控后端验收。
业务契约 AST 核对覆盖本轮 52 个已有 JS / JSX 文件:92 个 API 调用、40 个权限判定调用与改造前一致;`App.jsx`、hooks、services、context、helpers 无本轮变动。此项与只读交互回归结合使用,不能替代完整的后端写流程验收。
## 验收结果(2026-11-07)
| 检查 | 结果 |
| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 页面回归 | 25 页 × 浅 / 深色 × 1920×1000 / 393×851,共 100 个场景通过;标题图标为 0,无页面横向溢出、脚本错误或 API 错误 |
| 标题与导航 | 标题 28 / 32px,面包屑与标题间距 24px,内容顶部桌面 30px / 移动 16px;控制台导航与动态路径正常 |
| 功能与交互 | 9 项通过:真实搜索 / 重置、空态、分页 / 页容量、紧凑切换、行选择、排序、日期、Tabs、弹窗与抽屉校验 / 取消、移动导航与表格滚动;其中加载与空数据另有明确 mock 场景 |
| 抽屉表单 | 浅深色 × 桌面 / 移动 4 个场景通过;桌面 560px、移动 393px,内边距 / 表单项间距 24px,取消在提交之前,必填校验正常 |
| 写请求 | 页面与交互验收合计 0 个非 GET API 请求 |
| 单元测试 | `npm test -- --test-concurrency=1`:286 / 286 通过;覆盖控制台路由解析、排序适配,以及原有分页和弹窗策略回归 |
| 本轮文件检查 | ESLint 0 errors,保留 17 个既有 Hook 依赖警告;Prettier 与 `git diff --check` 通过 |
| 全局 ESLint | 已执行,259 errors / 190 warnings;错误来自未改动的 e2e 测试、浏览器缓存 / 历史快照和 `tests/adminDelegation.test.js` 的既有问题,本轮文件无错误 |
| 全局格式检查 | 已执行,705 个既有文件未通过;不执行全仓格式重写 |
| 资源 | 重任务并发上限 1,最低可用物理内存 11991 MB;CPU 采样曾短时到 100%,未发生 OOM 或内存溢出;Node 检查进程堆上限 2944 MB |
| 生产构建 | 按本轮要求未执行 |
完整本地报告为 `report/console-ui/report.html`,原始证据为同目录 JSON、截图与日志,均处于忽略目录。组件 / 布局验收依据本轮附件;没有执行附件像素阈值对比,不宣称像素级验收。深色来自现有主题 Token。剩余风险为全局静态检查历史欠账,以及未进行真实写业务和普通角色完整权限矩阵验证。
<!-- console-ui-files:start -->
- `docs/ui/CONSOLE_UI_SPEC.md`
- `src/components/common/ui/CardPro.jsx`
- `src/components/common/ui/CardTable.jsx`
- `src/components/console/ConsoleCollection.jsx`
- `src/components/console/ConsoleContext.jsx`
- `src/components/console/ConsolePageContainer.jsx`
- `src/components/console/ConsolePrimitives.jsx`
- `src/components/console/console.css`
- `src/components/console/consoleRoutes.js`
- `src/components/console/consoleTableAdapter.js`
- `src/components/layout/PageLayout.jsx`
- `src/components/layout/SiderBar.jsx`
- `src/components/layout/headerbar/MobileNavMenu.jsx`
- `src/components/layout/headerbar/Navigation.jsx`
- `src/components/layout/headerbar/index.jsx`
- `src/components/settings/PersonalSetting.jsx`
- `src/components/table/admin-tokens/AdminTokensDescription.jsx`
- `src/components/table/admin-tokens/AdminTokensFilters.jsx`
- `src/components/table/admin-tokens/index.jsx`
- `src/components/table/channels/ChannelsFilters.jsx`
- `src/components/table/models/ModelsFilters.jsx`
- `src/components/table/models/index.jsx`
- `src/components/table/redemptions/RedemptionsDescription.jsx`
- `src/components/table/redemptions/RedemptionsFilters.jsx`
- `src/components/table/redemptions/index.jsx`
- `src/components/table/task-logs/TaskLogsActions.jsx`
- `src/components/table/task-logs/TaskLogsFilters.jsx`
- `src/components/table/task-logs/index.jsx`
- `src/components/table/usage-logs/index.jsx`
- `src/components/table/users/UsersDescription.jsx`
- `src/components/table/users/UsersFilters.jsx`
- `src/components/table/users/index.jsx`
- `src/components/table/users/modals/AddUserModal.jsx`
- `src/components/ui/controls.jsx`
- `src/components/ui/form.jsx`
- `src/components/ui/index.jsx`
- `src/components/ui/overlayPolicy.test.js`
- `src/i18n/locales/en.json`
- `src/i18n/locales/fr.json`
- `src/i18n/locales/ja.json`
- `src/i18n/locales/ko.json`
- `src/i18n/locales/ru.json`
- `src/i18n/locales/th.json`
- `src/i18n/locales/vi.json`
- `src/i18n/locales/zh-TW.json`
- `src/i18n/locales/zh.json`
- `src/pages/AdminInvoice/index.jsx`
- `src/pages/AdminOrder/index.jsx`
- `src/pages/AdminOrganizations/index.jsx`
- `src/pages/Analytics/index.jsx`
- `src/pages/Channel/index.jsx`
- `src/pages/Chat/index.jsx`
- `src/pages/DemoReservations/index.jsx`
- `src/pages/ExpertPlatform/index.jsx`
- `src/pages/Log/index.jsx`
- `src/pages/Midjourney/index.jsx`
- `src/pages/Model/index.jsx`
- `src/pages/MonitorCenter/index.jsx`
- `src/pages/MyCommission/index.jsx`
- `src/pages/PartnerPortal/Console.jsx`
- `src/pages/Playground/index.jsx`
- `src/pages/Recharge/index.jsx`
- `src/pages/Redemption/index.jsx`
- `src/pages/Setting/Setting.css`
- `src/pages/Setting/index.jsx`
- `src/pages/SkillPlatform/index.jsx`
- `src/pages/Subscription/index.jsx`
- `src/pages/Task/index.jsx`
- `src/pages/Token/index.jsx`
- `src/pages/User/index.jsx`
- `src/pages/WebsiteSettings/WebsiteSettings.css`
- `src/pages/WebsiteSettings/index.jsx`
- `tests/console-layout.test.js`
- `tests/modal-overflow.test.js`
- `tests/users-pagination.test.js`
<!-- console-ui-files:end -->
+17 -2
View File
@@ -2,6 +2,8 @@
本文件是企业中心目标页的详细规格;入口约定见 `AGENTS.md` / `CLAUDE.md`“企业中心单页约定(/org/*)”,改造记录见 `docs/UI_MIGRATION.md`“企业中心按在线原型对齐(2026-11-06)”。 本文件是企业中心目标页的详细规格;入口约定见 `AGENTS.md` / `CLAUDE.md`“企业中心单页约定(/org/*)”,改造记录见 `docs/UI_MIGRATION.md`“企业中心按在线原型对齐(2026-11-06)”。
2026-11-07 追加:企业密钥及消耗明细“绘图与视频”的已有列设置,统一使用 [TABLE_COLUMN_SETTINGS_SPEC.md](TABLE_COLUMN_SETTINGS_SPEC.md) 的共享齿轮入口与 Ant Design 弹框。明细日志、成员排行等原本没有列设置的表格不新增入口,权限、请求和持久化规则不变。
## 1. 范围与依据 ## 1. 范围与依据
- 视觉唯一基准:在线原型 `http://192.168.0.161:8888` 顶栏“企业中心”(SPA,URL 保持 `/`,无需登录;深色用“切换至暗色主题”)。原型只作视觉依据,不作业务 / 路由 / 数据依据。 - 视觉唯一基准:在线原型 `http://192.168.0.161:8888` 顶栏“企业中心”(SPA,URL 保持 `/`,无需登录;深色用“切换至暗色主题”)。原型只作视觉依据,不作业务 / 路由 / 数据依据。
@@ -42,7 +44,7 @@
## 4. 页面映射(原型 → 系统) ## 4. 页面映射(原型 → 系统)
| 页面 | 原型结构 | 系统实现 | 保留差异 | | 页面 | 原型结构 | 系统实现 | 保留差异 |
| -------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- | | -------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------- |
| 工作台 | `.ew-hero` 标签 / `.ew-stats` / `.ew-middle`(额度 + 密钥)/ `.ew-usage` / `.ew-requests` | `OrgHero` 标签化身份、`oc-wb-*` 卡片;数据与提额 / 昵称 / 改密回调不变 | 额度周期标签放在重置卡;最近申请无分页 | | 工作台 | `.ew-hero` 标签 / `.ew-stats` / `.ew-middle`(额度 + 密钥)/ `.ew-usage` / `.ew-requests` | `OrgHero` 标签化身份、`oc-wb-*` 卡片;数据与提额 / 昵称 / 改密回调不变 | 额度周期标签放在重置卡;最近申请无分页 |
| 数据看板 | `.ea-hero`(健康 / 标题 / 操作 / 企业额度 + 组织概况)→ `.ea-analysis` → `.ea-details` 页签 | `oc-dash-*` hero + `OrgAnalyticsPanel`(汇总条、趋势 Segmented、分布、明细页签,成员用量明细并入页签) | 企业名复用 orgInfo.name;“成员用量”= 切换页签并页内定位;时间范围保留 7/30/90 天 | | 数据看板 | `.ea-hero`(健康 / 标题 / 操作 / 企业额度 + 组织概况)→ `.ea-analysis` → `.ea-details` 页签 | `oc-dash-*` hero + `OrgAnalyticsPanel`(汇总条、趋势 Segmented、分布、明细页签,成员用量明细并入页签) | 企业名复用 orgInfo.name;“成员用量”= 切换页签并页内定位;时间范围保留 7/30/90 天 |
| 员工管理 | 页签 + 筛选卡 + 员工列表 | 页签(员工权限 / 员工账号)+ 员工列表卡;首列 / 操作列固定;备注独立列(原就地编辑);状态 Switch | 无筛选卡 / 在职离职页签 / 角色多标签;操作为系统既有(配额 / 模型 / 分组 / 权限 / 移除) | | 员工管理 | 页签 + 筛选卡 + 员工列表 | 页签(员工权限 / 员工账号)+ 员工列表卡;首列 / 操作列固定;备注独立列(原就地编辑);状态 Switch | 无筛选卡 / 在职离职页签 / 角色多标签;操作为系统既有(配额 / 模型 / 分组 / 权限 / 移除) |
@@ -51,11 +53,24 @@
| 审批中心 | 状态页签 + 申请列表卡 | 页签回调 `setStatusFilter`;拒绝弹窗竖排表单项 | — | | 审批中心 | 状态页签 + 申请列表卡 | 页签回调 `setStatusFilter`;拒绝弹窗竖排表单项 | — |
| 密钥管理 | 密钥列表卡(`.km-secret`)+ 创建 / 编辑抽屉(`.km-editor-drawer`) | 密钥框 + 显隐 / 复制 text 按钮、可用模型 link、状态 Switch、绝对时间;创建 / 编辑改为 560px `OrgSideSheet`(表单与回调不变) | 分组展示现有 group 字段;列设置仅控制当前页面显示;抽屉字段为系统既有字段 | | 密钥管理 | 密钥列表卡(`.km-secret`)+ 创建 / 编辑抽屉(`.km-editor-drawer`) | 密钥框 + 显隐 / 复制 text 按钮、可用模型 link、状态 Switch、绝对时间;创建 / 编辑改为 560px `OrgSideSheet`(表单与回调不变) | 分组展示现有 group 字段;列设置仅控制当前页面显示;抽屉字段为系统既有字段 |
| 企业充值 | RechargeLayoutC:企业钱包 + 工作区(额度卡 / 自定义 / 支付方式)+ 订单卡 + 记录 | `oc-rc-*`;`AmountCard` 复用;订单卡“立即充值”与点击支付方式同为 `handlePreTopUp` | 档位 / 标签 / 折扣徽标为后台配置;无订单号搜索与发票入口 | | 企业充值 | RechargeLayoutC:企业钱包 + 工作区(额度卡 / 自定义 / 支付方式)+ 订单卡 + 记录 | `oc-rc-*`;`AmountCard` 复用;订单卡“立即充值”与点击支付方式同为 `handlePreTopUp` | 档位 / 标签 / 折扣徽标为后台配置;无订单号搜索与发票入口 |
| 消耗明细 | `.eex-stats` + 页签 + 筛选卡 + 列表卡 | 同结构;查询改名“搜索”(同 `handleSearch`) | 无“绘图与视频”页签、分组列 | | 消耗明细 | `.eex-stats` + 页签(明细日志 / 成员排行 / 绘图与视频)+ 筛选卡 + 列表卡;绘图与视频 `.eex-task-records`(筛选卡 + “任务记录”列表卡) | 同结构;查询改名“搜索”(同 `handleSearch`);绘图与视频由 `OrgTaskRecords` 呈现、时间范围独立可编辑、末列“操作”(见 4.1);页面根 `.oc-expenses` 由 `useOrgLogsThemeStyle` 注入 token 变量 | 明细日志无分组 / 操作列、列设置与尺寸切换;任务表无渠道 / 平台列、排序与任务 ID 复制;见 4.1 |
| 审计日志 | 页签 + 筛选卡(操作类型)+ 操作记录卡 | 同结构;“提示词记录”页签沿用原显隐 | 详情分隔符沿用系统格式 | | 审计日志 | 页签 + 筛选卡(操作类型)+ 操作记录卡 | 同结构;“提示词记录”页签沿用原显隐 | 详情分隔符沿用系统格式 |
| 个人设置 | `.ps-profile` + `.ps-workspace` 页签(头像设置 / 个人资料 / 通知设置) | 复用用户中心 `.ui-personal-*`、`AvatarSection`、`SectionHeader`;个人资料 = 昵称 / 密码设置行 + 个人配额卡;企业身份并入资料头 | 昵称为弹窗修改(原型行内) | | 个人设置 | `.ps-profile` + `.ps-workspace` 页签(头像设置 / 个人资料 / 通知设置) | 复用用户中心 `.ui-personal-*`、`AvatarSection`、`SectionHeader`;个人资料 = 昵称 / 密码设置行 + 个人配额卡;企业身份并入资料头 | 昵称为弹窗修改(原型行内) |
| 企业设置 | `.ps-workspace` 页签 + 每页签区块头(刷新 / 保存设置) | 同结构;刷新 / 保存按钮并入区块头;复制为 14px 无内边距图标按钮(原型 Typography copyable) | 保留系统独有“数据安全”“危险区域”页签 | | 企业设置 | `.ps-workspace` 页签 + 每页签区块头(刷新 / 保存设置) | 同结构;刷新 / 保存按钮并入区块头;复制为 14px 无内边距图标按钮(原型 Typography copyable) | 保留系统独有“数据安全”“危险区域”页签 |
### 4.1 消耗明细(/org/logs)高保真对齐(2026-11-06,2026-11-07 用户确认后更新)
- 主题三态:页面根 `.uc-page.oc-page.oc-expenses` 的 `style` 由 `useOrgLogsThemeStyle()`(`theme.useToken()`)注入 `--oc-brand`(`brandAccentFromToken`:浅色 / 自定义主色 = `colorPrimary`,仅默认暗色主色 `#d1963a` 回到原型种子 `#f2ad41`)、`--oc-stat-brand-bg`(品牌色 6.3% `color-mix`)与 `--ur-progress-done`。页签、额度、统计图标、进度随浅色 / 深色 / 自定义主色联动;不新增 ConfigProvider / 主题状态 / 存储 key。
- 绘图与视频:`components/OrgTaskRecords.jsx` 复用 `useTaskLogsData({ organizationMode: true })`、`TaskLogsFilters`(usageRecordMode)、`getTaskLogsColumns`、`exportTaskLogsPageCsv`、`ColumnSelectorModal`、`ContentModal`,结构与原型一致:`.ee-filter-card`(三列 16px、表单项下距 16px、标签 13px 次文字色、时间范围占一列、重置 / 搜索右对齐 8px,移动端直接展开)+ `OrgListCard`“任务记录”(导出本页 / 刷新 / 列设置齿轮)+ Ant `Table`(列宽 185/185/110/110/250/330/110/155/145/150、模型 `.eex-model` 行内胶囊、费用主色右对齐)+ 适配 `Pagination`(10/20/50、`共 N 条`)。不渲染“本页统计”区块(原型无)。“刷新”与筛选“搜索”是同一 `refresh`,无新增接口或载荷。
- 时间范围:与原型一致,本页签使用自身筛选卡中的可编辑时间范围(默认最近 7 天,含既有快捷预设),与“明细日志”筛选互不影响;起止颠倒沿用原提示“开始时间不能晚于结束时间”。
- 末列:原型“操作”,随表格横向滚动(不固定);视频任务显示“点击预览视频”(link 文本、无图标),失败任务保留原失败原因查看,其余显示“-”。
- 预览视频弹框:沿用 `ContentModal`,只重做内部样式(`modals/content-modal.css`):标题栏“视频预览”+ 右上关闭、16:9 播放区(`object-fit: contain`)+ 居中加载、播放失败 / 无地址为 Ant `Empty` 空态(失败原因与原地址代码框)、页脚复制链接 / 新标签页打开 / 关闭;颜色只引用 TokenBridge 的 `--ui-*`;企业页遮罩 `rgba(0,0,0,.3)` + `blur(4px)`。弹窗仍为“关闭只隐藏不卸载”,关闭时暂停 `<video>`,重新打开同一视频时按已有数据收起加载指示。
- 成员排行:后端可能对同一成员返回多行,行键使用 `user_id-名次序号`,数据、排序与展示不变(消除 React 重复 key)。
- 导出弹窗与空态:导出弹窗正文改为 `.oc-export-*`(`--oc-*` / `--ui-color-warning`),空表为 `Empty.PRESENTED_IMAGE_SIMPLE`,去掉 Tailwind 灰 / 琥珀色。
- 新增样式以 `:where(.org-center .oc-expenses)` 包裹作用域祖先、只保留目标类优先级;复用的 `.usage-record-*` 类再加一层企业页类名,结果与 UsageRecord.css 是否已加载无关;不使用 `!important`。
- 保留差异:明细日志无列设置 / 分组列 / 操作列 / 尺寸切换(同前);任务表无渠道 / 用户 ID 筛选(仅平台管理员)、平台列(单测约束不暴露)、排序与任务 ID 复制;明细日志查询不写 URL(用户确认不新增),绘图与视频筛选沿用原有 URL 同步;业务默认值“全部…”为选中项(原型为占位符)。
- 验收:`e2e/org-logs/login.mjs`(A / B 登录关卡)→ `proto-capture.mjs` → `acceptance.mjs`(主题三态 × 15 个同名状态、功能回归、修复核查、移动端、UI 退出)→ `compare.mjs`(`report/org-logs/visual-regression.html`)→ `e2e/org-logs-ui.spec.js`(`toHaveScreenshot()` 建基线后不带 update 复跑);共享组件在个人端以 `personal-regression.mjs` 回归。后端 `/api/org/tasks` 未就绪时,绘图与视频以原型同构 mock 验证并标注。
## 5. 判定与验收 ## 5. 判定与验收
- 采集:`e2e/org-center/proto-capture.mjs`(原型)/ `capture-system.mjs`(系统,复用 `report/auth/org-storage.json`);1920×1080、DPR 1、zh-CN、Asia/Shanghai、reducedMotion + 注入关闭动画、浅 / 深;系统侧关闭会话级公告栏(sessionStorage,仅测试浏览器)并 Esc 关闭公告弹窗。 - 采集:`e2e/org-center/proto-capture.mjs`(原型)/ `capture-system.mjs`(系统,复用 `report/auth/org-storage.json`);1920×1080、DPR 1、zh-CN、Asia/Shanghai、reducedMotion + 注入关闭动画、浅 / 深;系统侧关闭会话级公告栏(sessionStorage,仅测试浏览器)并 Esc 关闭公告弹窗。
+85
View File
@@ -0,0 +1,85 @@
# 三中心表格列设置规范
## 范围与依据
本次扫描 `/user-center/*`、`/console/*`、`/org/*` 所有侧栏页面及页签,统一已有列设置功能。视觉及交互依据为用户附件与本地 `C:/Users/Win10/Desktop/微元优化原型/index.html` 的“用户中心 / 使用记录 / 消费记录 / 调用明细”列设置弹框。
扫描定位六类实现、九个页面或页签入口;没有列设置的表格不新增该功能。
| 中心 | 页面 / 页签 | 路由 | 接入位置 |
| -------- | --------------------- | ------------------------------------ | --------------------------------------- |
| 用户中心 | 使用记录 / 消费记录 | `/user-center/usage-record` | 调用明细卡片右上角,位于导出之后 |
| 用户中心 | 使用记录 / 绘图与视频 | `/user-center/usage-record?tab=task` | 任务记录卡片右上角,位于导出之后 |
| 用户中心 | 密钥管理 | `/user-center/key-management` | 密钥列表卡片右上角,位于创建之后 |
| 控制台 | 使用日志 | `/console/log` | 列表卡片右上角,位于导出之后 |
| 控制台 | 异步任务 | `/console/task` | 列表卡片右上角 |
| 控制台 | 绘图日志 | `/console/midjourney` | 列表卡片右上角 |
| 控制台 | 渠道管理 | `/console/channel` | 列表工具栏最右侧 |
| 企业中心 | 密钥管理 | `/org/tokens` | 密钥列表卡片右上角,位于刷新 / 创建之后 |
| 企业中心 | 消耗明细 / 绘图与视频 | `/org/logs` | 任务记录卡片右上角,位于导出 / 刷新之后 |
旧 `/key-management` 重定向继续使用个人密钥页。管理员密钥 `/console/token` 等未提供列设置的表格不补建入口。企业明细日志和成员排行未提供该功能,不从原型虚构入口。
## 公共组件
`src/components/common/table/ColumnSettings.jsx` 提供:
- `ColumnSettingsButton`:原生 Ant Design `Button type="text"` + `Tooltip`,统一 34px 按钮、16px lucide Settings 图标、可访问标签及展开状态。
- `ColumnSettingsModal`:原生 Ant Design `Modal`、`Checkbox.Group`、`Checkbox`、`Button`、校验 `Alert`;列选项由调用方提供。
- `ColumnVisibilitySettings`:把既有布尔列显隐映射接入弹框,确认时一次提交,保留当前角色不可配置的键值。
- `TableColumnSettings`:用于个人及企业密钥页的数组列显隐适配。
`CardPro.tableActions` 与 `ConsoleCollection.tableActions` 提供独立于搜索区的表格右侧操作槽。移动筛选折叠时,列设置入口仍然可见。
四个既有 `ColumnSelectorModal` 文件保留列生成与权限过滤,内部统一委托公共弹框。三个日志 hook 仅额外暴露已有的 `setVisibleColumns` 和默认值读取函数;渠道 hook 仅额外暴露已有 setter。原请求、处理函数、默认列、角色限制与持久化键均保持原样。
企业任务列表由同一组完整列定义生成可选项和实际表格列,保证“任务 ID”“操作”等页面专用列名一致。表头内的帮助图标不会被复制到弹框选项中。
## 外观
集中样式位于 `src/components/common/table/column-settings.css`,仅作用于共享弹框与入口。
- 弹框宽 520px,顶部 100px;视口不足时保留左右 16px。
- 内容内边距 20px / 24px,圆角 12px;标题 16px / 24px、600。
- 正文顶部 20px;全选区上下 14px,下方 1px 分隔线,底部间距 18px。
- 列选项两列排列,行间距 16px、列间距 20px,网格内边距 4px / 0 / 12px;窄屏改为 14px / 10px 间距和 12px 文本。
- 复选框 17px、圆角 6px;与原型保持一致。
- 底部按钮依次为重置、取消、确定;按钮高 34px、横向内边距沿用 Ant Design 默认 15px、间距 8px,确定使用 primary。按钮行高与原型同为 normal,中文双字按钮实测宽约 63.84px。
- 遮罩 `rgba(0,0,0,.3)` + `blur(4px)`,支持点击关闭。
- 主色跟随现有 Ant Design 主题;浅色文字与分隔线采用原型值,深色读取现有 Token。没有新增 ConfigProvider、主题状态或存储键。
## 交互与状态
1. 打开时复制当前可见列为独立草稿;后台刷新和轮询不覆盖正在编辑的草稿。
2. 单列勾选、全选及重置只修改草稿。全选和半选按当前角色可配置的列计算。
3. 重置恢复本表原有默认列;渠道“自动封禁”仍默认隐藏。
4. 确认时至少保留一列;全部取消后确认显示校验提示,弹框保持打开。
5. 确认后一次应用列显隐。日志和渠道沿用原 localStorage 规则,个人 / 企业密钥列设置仍仅在页面内保留。
6. 取消、关闭按钮、Esc、遮罩关闭均放弃草稿;不改变表格或原有存储。关闭后焦点返回入口。
## 验收记录
本地验收脚本及截图、探针、资源记录保存在 Git 忽略的 `report/column-settings/`。真实会话只读验收与企业任务接口模拟场景分开记录,不执行生产构建或真实业务写操作。
企业 `/api/org/tasks` 在真实环境返回 404,已单独记录;列设置仍可打开,完整任务列表交互使用明确标记的模拟数据。最终结果以同目录验收报告为准。
2026-11-07 验收:9 入口 × 浅深色 × 1920×916 / 393×851,36/36 场景、324 组检查通过;权限 / 后台刷新 / 一次提交等补测 5/5,已有密钥管理回归用例桌面与移动 2/2。个人移动任务沿用既有卡片布局,字段显隐使用真实与模拟任务记录验证。页面运行错误与非 GET API 请求均为 0。
浅色消费记录弹框 520×473px 与同环境本地原型比较像素差 0、SSIM 0.999999、pHash 距离 0,达到组件 0.2% 阈值;该结论仅覆盖此浅色弹框状态。单元测试 291/291;本轮源码及回归用例 ESLint 0 错误 / 12 条既有警告、Prettier 与 `git diff --check` 通过。全仓 ESLint 的 261 个错误 / 189 条警告及 677 个格式文件问题位于其他文件,保留并单列记录。
## 本轮文件清单
| 类型 | 文件 |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 新增共享组件与样式 | `src/components/common/table/ColumnSettings.jsx`、`column-settings.css` |
| 表格工具栏插槽 | `src/components/common/ui/CardPro.jsx`、`src/components/console/ConsoleCollection.jsx`、`console.css` |
| 日志接入 | `src/components/table/{usage-logs,task-logs,mj-logs}/index.jsx`、各目录的 `*Filters.jsx`、`modals/ColumnSelectorModal.jsx` |
| 渠道接入 | `src/components/table/channels/index.jsx`、`ChannelsFilters.jsx`、`modals/ColumnSelectorModal.jsx` |
| 已有状态暴露 | `src/hooks/usage-logs/useUsageLogsData.jsx`、`src/hooks/task-logs/useTaskLogsData.js`、`src/hooks/mj-logs/useMjLogsData.js`、`src/hooks/channels/useChannelsData.jsx` |
| 个人密钥 | `src/pages/KeyManagement/index.jsx`、`key-management.css` |
| 企业密钥与任务 | `src/pages/Organization/OrgTokens.jsx`、`components/OrgTaskRecords.jsx`、`src/styles/org-center.css` |
| 国际化 | `src/i18n/locales/{zh,zh-TW,en,ja,ko,fr,ru,vi,th}.json`:补齐空选择校验文案 |
| 规范 | `AGENTS.md`、`CLAUDE.md`、本文件、`docs/ui/UI_SPEC.md`、`docs/ui/ORG_CENTER_SPEC.md` 与 `docs/UI_MIGRATION.md` |
| 本地回归用例 | `e2e/key-management-ui.spec.js`:列设置选择先保持原列,确认后再断言隐藏;支持指定已有测试会话 |
并发修改的企业数据看板、公共 UI 入口、体验中心审计和管理员密钥筛选均按用户确认保留,不计入本轮列设置改造范围。
+3 -1
View File
@@ -6,6 +6,8 @@
- 原型没有深色截图:深色主题由 Ant Design `darkAlgorithm` 与既有主题变量推导,不得宣称深色原型像素验收通过。 - 原型没有深色截图:深色主题由 Ant Design `darkAlgorithm` 与既有主题变量推导,不得宣称深色原型像素验收通过。
- 只覆盖个人端。企业端(`/org/*`)、平台管理(`/console/*`)、认证页、WeyAI 外部页、第三方客服/广告 SDK、体验中心、模型超市、公开页不在本规范的改造范围内。 - 只覆盖个人端。企业端(`/org/*`)、平台管理(`/console/*`)、认证页、WeyAI 外部页、第三方客服/广告 SDK、体验中心、模型超市、公开页不在本规范的改造范围内。
2026-11-07 追加:三中心已有表格列设置统一遵循 [TABLE_COLUMN_SETTINGS_SPEC.md](TABLE_COLUMN_SETTINGS_SPEC.md)。该组件以用户附件及本地“微元优化原型”列设置弹框为依据,覆盖此前密钥页 Popover 与列设置弹窗的旧约定;其他弹窗继续遵循本文。三个日志 hook 仅暴露已有列状态 setter / 默认值读取函数,请求、载荷、角色过滤和原存储键不变。
## 1. 目录与 UI 边界 ## 1. 目录与 UI 边界
后续用户标注补充:`/key-management` 保留原 URL 和鉴权,由 `UserCenter keyManagementMode` 提供侧栏外壳,密钥页 `embedded` 分支仅适配背景、边距与面包屑;入口移至“使用记录”之后,顶栏移除该主导航项,头像菜单保持相同地址。此项按用户明确要求允许 App 中原密钥路由的视图包装调整,不改业务 API 或路由权限。 后续用户标注补充:`/key-management` 保留原 URL 和鉴权,由 `UserCenter keyManagementMode` 提供侧栏外壳,密钥页 `embedded` 分支仅适配背景、边距与面包屑;入口移至“使用记录”之后,顶栏移除该主导航项,头像菜单保持相同地址。此项按用户明确要求允许 App 中原密钥路由的视图包装调整,不改业务 API 或路由权限。
@@ -190,7 +192,7 @@ html.dark .ui-recharge-page {
## 10. 个人端登录流程与容错 ## 10. 个人端登录流程与容错
- Base URL:每次从 `dev.log` 最后一个 `Local:` 提取(去除 ANSI 色码),禁止写死 IP 与端口。服务启动:`nohup npm run dev > dev.log 2>&1 &`;Windows 可用隐藏窗口的 `Start-Process` 启动同一命令。 - Base URL:每次从 `dev.log` 最后一个 `Local:` 提取(去除 ANSI 色码),禁止写死 IP 与端口。服务启动:`nohup npm run dev > dev.log 2>&1 &`;Windows 可用隐藏窗口的 `Start-Process` 启动同一命令。
- 入口 `{Base URL}/login`,个人端账号 `test_222`,密码 `12345678`(用户指定的测试账号;脚本从环境变量 `UI_PERSONAL_USER` / `UI_PERSONAL_PASS` 读取,不写入脚本、日志、截图注释或提交)。 - 入口 `{Base URL}/login`,个人端账号 `test222`,密码 `12345678`(用户指定的测试账号;脚本从环境变量 `UI_PERSONAL_USER` / `UI_PERSONAL_PASS` 读取,不写入脚本、日志、截图注释或提交)。
- 新建 Browser Context(清空 Cookies/Storage)→ `goto('/login')` → `waitForLoadState('networkidle')` → 检查可见非隐藏、非复选框输入框数量、placeholder/标签和按钮 → 打印不含输入值的判定并截图 → 按页面原有协议勾选与登录 → 确认用户中心侧栏与主体已渲染(仅接口成功或 URL 变化不算)→ 立即保存 storageState 到 Git 忽略的本地目录(`/tmp/ui-ref/auth/`)。 - 新建 Browser Context(清空 Cookies/Storage)→ `goto('/login')` → `waitForLoadState('networkidle')` → 检查可见非隐藏、非复选框输入框数量、placeholder/标签和按钮 → 打印不含输入值的判定并截图 → 按页面原有协议勾选与登录 → 确认用户中心侧栏与主体已渲染(仅接口成功或 URL 变化不算)→ 立即保存 storageState 到 Git 忽略的本地目录(`/tmp/ui-ref/auth/`)。
- 禁止 API 登录或注入伪造鉴权;登录阶段不录 trace/HAR。 - 禁止 API 登录或注入伪造鉴权;登录阶段不录 trace/HAR。
- 容错:登录失败或接口报错时,截图 + 保存 `dev.log` 尾部 + 失败请求 payload(密码、Cookie、token、ticket 脱敏)写入“风险与后续建议”;不得反复盲试,不得为登录修改业务代码。 - 容错:登录失败或接口报错时,截图 + 保存 `dev.log` 尾部 + 失败请求 payload(密码、Cookie、token、ticket 脱敏)写入“风险与后续建议”;不得反复盲试,不得为登录修改业务代码。
@@ -21,19 +21,21 @@ import React, { useState } from 'react';
import { Card, Table, Progress } from '@/components/ui'; import { Card, Table, Progress } from '@/components/ui';
import { renderQuota } from '../../helpers'; import { renderQuota } from '../../helpers';
const ChannelConsumption = ({ data, title, icon, t }) => { const ChannelConsumption = ({ data, title, icon, t, embedded = false }) => {
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10); const [pageSize, setPageSize] = useState(10);
if (!data || data.length === 0) { if (!data || data.length === 0) {
return ( return (
<Card <Card
className='shadow-sm hover:shadow-md transition-shadow' className={`shadow-sm hover:shadow-md transition-shadow ${embedded ? 'analytics-fold-content' : ''}`}
title={ title={
embedded ? undefined : (
<div className='flex items-center gap-2'> <div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span> <span className='text-brand'>{icon}</span>
<span className='font-semibold'>{title}</span> <span className='font-semibold'>{title}</span>
</div> </div>
)
} }
bodyStyle={{ padding: '16px' }} bodyStyle={{ padding: '16px' }}
> >
@@ -122,19 +124,26 @@ const ChannelConsumption = ({ data, title, icon, t }) => {
return ( return (
<Card <Card
className='shadow-sm hover:shadow-md transition-shadow' className={`shadow-sm hover:shadow-md transition-shadow ${embedded ? 'analytics-fold-content' : ''}`}
title={ title={
embedded ? undefined : (
<div className='flex items-center gap-2'> <div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span> <span className='text-brand'>{icon}</span>
<span className='font-semibold'>{title}</span> <span className='font-semibold'>{title}</span>
<span className='text-xs text-gray-400 ml-2'>TOP {data.length}</span> <span className='text-xs text-gray-400 ml-2'>
TOP {data.length}
</span>
</div> </div>
)
} }
bodyStyle={{ padding: '0' }} bodyStyle={{ padding: '0' }}
> >
<Table <Table
columns={columns} columns={columns}
dataSource={data} dataSource={data.map((record, index) => ({
...record,
key: `${record.channel_name}-${index}`,
}))}
pagination={{ pagination={{
currentPage, currentPage,
pageSize, pageSize,
@@ -148,7 +157,7 @@ const ChannelConsumption = ({ data, title, icon, t }) => {
}, },
}} }}
size='small' size='small'
rowKey={(record, index) => `${record.channel_name}-${index}`} rowKey='key'
/> />
</Card> </Card>
); );
@@ -0,0 +1,45 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { ChevronDown } from 'lucide-react';
import './collapsible-panel.css';
const CollapsibleHeader = ({ icon, title, isOpen, onToggle, extra }) => (
<button
type='button'
aria-expanded={isOpen}
className='w-full text-left flex items-center justify-between gap-2 cursor-pointer select-none px-5 py-4 bg-white dark:bg-gray-800 rounded-xl shadow-sm hover:shadow-md transition-all border border-gray-100 dark:border-gray-700'
onClick={onToggle}
>
<span className='flex items-center gap-2 min-w-0 flex-wrap'>
<span className='text-brand flex-shrink-0'>{icon}</span>
<span className='font-semibold text-gray-800 dark:text-gray-100'>
{title}
</span>
{extra}
</span>
<ChevronDown
aria-hidden='true'
className={`w-5 h-5 flex-shrink-0 text-gray-400 transition-transform duration-300 ${isOpen ? 'rotate-180' : ''}`}
/>
</button>
);
export default CollapsibleHeader;
+16 -2
View File
@@ -22,7 +22,7 @@ import { Card, Table, Button } from '@/components/ui';
import { IconDownload } from '@/components/ui/icons'; import { IconDownload } from '@/components/ui/icons';
import { renderQuota } from '../../helpers'; import { renderQuota } from '../../helpers';
const DailyStatsTable = ({ data, title, icon, t }) => { const DailyStatsTable = ({ data, title, icon, t, embedded = false }) => {
const columns = [ const columns = [
{ {
title: t('日期'), title: t('日期'),
@@ -161,8 +161,9 @@ const DailyStatsTable = ({ data, title, icon, t }) => {
return ( return (
<Card <Card
className='shadow-sm hover:shadow-md transition-shadow' className={`shadow-sm hover:shadow-md transition-shadow ${embedded ? 'analytics-fold-content' : ''}`}
title={ title={
embedded ? undefined : (
<div className='flex items-center justify-between w-full'> <div className='flex items-center justify-between w-full'>
<div className='flex items-center gap-2'> <div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span> <span className='text-brand'>{icon}</span>
@@ -177,9 +178,22 @@ const DailyStatsTable = ({ data, title, icon, t }) => {
{t('导出CSV')} {t('导出CSV')}
</Button> </Button>
</div> </div>
)
} }
bodyStyle={{ padding: '0' }} bodyStyle={{ padding: '0' }}
> >
{embedded && (
<div className='flex justify-end p-4'>
<Button
icon={<IconDownload />}
size='small'
onClick={handleExport}
disabled={!data || data.length === 0}
>
{t('导出CSV')}
</Button>
</div>
)}
<Table <Table
columns={columns} columns={columns}
dataSource={data || []} dataSource={data || []}
+2 -2
View File
@@ -34,7 +34,7 @@ import { renderQuota } from '../../helpers';
const OverviewCards = ({ overview, t }) => { const OverviewCards = ({ overview, t }) => {
if (!overview) { if (!overview) {
return ( return (
<div className='grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-6'> <div className='grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4'>
{[...Array(6)].map((_, i) => ( {[...Array(6)].map((_, i) => (
<Card key={i} className='animate-pulse'> <Card key={i} className='animate-pulse'>
<div className='h-20 bg-gray-200 dark:bg-gray-700 rounded'></div> <div className='h-20 bg-gray-200 dark:bg-gray-700 rounded'></div>
@@ -124,7 +124,7 @@ const OverviewCards = ({ overview, t }) => {
}; };
return ( return (
<div className='grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-6'> <div className='grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4'>
{cards.map((card, index) => ( {cards.map((card, index) => (
<Card <Card
key={index} key={index}
@@ -54,6 +54,7 @@ const RiskControlBanLogs = ({
banLogStatus, banLogStatus,
setBanLogStatus, setBanLogStatus,
banLogPage, banLogPage,
banLogPageSize,
fetchBanLogs, fetchBanLogs,
unbanUser, unbanUser,
t, t,
@@ -204,12 +205,13 @@ const RiskControlBanLogs = ({
rowKey='id' rowKey='id'
loading={loading} loading={loading}
pagination={{ pagination={{
pageSize: 20, pageSize: banLogPageSize,
showTotal: true, showTotal: true,
total: banLogTotal, total: banLogTotal,
// 受控分页:避免切换状态筛选后 Semi 内部页码与 hook 不同步 // 受控分页:避免切换状态筛选后 Semi 内部页码与 hook 不同步
currentPage: banLogPage, currentPage: banLogPage,
onPageChange: (page) => fetchBanLogs({ page }), onPageChange: (page) => fetchBanLogs({ page }),
onPageSizeChange: (pageSize) => fetchBanLogs({ page: 1, pageSize }),
}} }}
empty={t('暂无封号记录')} empty={t('暂无封号记录')}
scroll={{ x: 1400 }} scroll={{ x: 1400 }}
+36 -31
View File
@@ -18,19 +18,17 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { useMemo, useState, useEffect, useCallback } from 'react'; import React, { useMemo, useState, useEffect, useCallback } from 'react';
import { Card, Spin, Tag, Progress, Empty } from '@/components/ui'; import { Card, Spin, Tag, Progress } from '@/components/ui';
import CollapsibleHeader from './CollapsibleHeader';
import { VChart } from '@visactor/react-vchart'; import { VChart } from '@visactor/react-vchart';
import { API, showError } from '../../helpers'; import { API, showError } from '../../helpers';
import { import {
UserCheck,
Briefcase, Briefcase,
Cpu, Cpu,
Users, Users,
TrendingUp, TrendingUp,
BarChart3, BarChart3,
PieChart, PieChart,
ChevronDown,
ChevronUp,
} from 'lucide-react'; } from 'lucide-react';
// 职业类型标签配置 // 职业类型标签配置
@@ -271,38 +269,33 @@ const UserSurveyStats = ({ title, icon, t }) => {
surveyStats?.ai_tool_stats?.find((s) => s.ai_tool_usage === 3)?.count || 0; surveyStats?.ai_tool_stats?.find((s) => s.ai_tool_usage === 3)?.count || 0;
return ( return (
<Card <div className='analytics-fold-panel'>
className='shadow-sm hover:shadow-md transition-shadow' <CollapsibleHeader
title={ icon={icon}
<div className='flex items-center justify-between w-full'> title={title}
<div className='flex items-center gap-2'> isOpen={!collapsed}
<span className='text-brand'>{icon}</span> onToggle={() => setCollapsed((value) => !value)}
<span className='font-semibold'>{title}</span> extra={
<>
{totalUsers > 0 && ( {totalUsers > 0 && (
<Tag color='purple' size='small'> <Tag color='purple' size='small'>
{totalUsers} {t('人已填写')} {totalUsers} {t('人已填写')}
</Tag> </Tag>
)} )}
</div> </>
<button
onClick={() => setCollapsed(!collapsed)}
className='flex items-center gap-1 px-2 py-1 text-sm text-gray-500 hover:text-brand-deep hover:bg-brand/5 dark:hover:bg-brand-deep/20 rounded transition-colors'
>
<span className='text-xs'>{collapsed ? t('展开') : t('收起')}</span>
{collapsed ? <ChevronDown size={16} /> : <ChevronUp size={16} />}
</button>
</div>
} }
bodyStyle={{ padding: collapsed ? '0' : '16px' }} />
<div className={collapsed ? 'hidden' : ''}>
<Card
className='analytics-fold-content shadow-sm'
bodyStyle={{ padding: '16px' }}
> >
{!collapsed && ( {!collapsed && (
<Spin spinning={loading}> <Spin spinning={loading}>
{totalUsers === 0 ? ( {totalUsers === 0 ? (
<Empty <div className='h-[300px] flex items-center justify-center text-gray-400'>
image={<UserCheck className='w-16 h-16 text-gray-300' />} {t('暂无数据')}
description={t('暂无问卷数据')} </div>
style={{ padding: '40px 0' }}
/>
) : ( ) : (
<div className='space-y-6'> <div className='space-y-6'>
{/* 概览统计卡片 */} {/* 概览统计卡片 */}
@@ -397,7 +390,9 @@ const UserSurveyStats = ({ title, icon, t }) => {
className='flex items-center justify-between' className='flex items-center justify-between'
> >
<div className='flex items-center gap-2'> <div className='flex items-center gap-2'>
<span className='text-lg'>{config?.icon}</span> <span className='text-lg'>
{config?.icon}
</span>
<span className='text-sm text-gray-600 dark:text-gray-400'> <span className='text-sm text-gray-600 dark:text-gray-400'>
{config?.label} {config?.label}
</span> </span>
@@ -462,7 +457,9 @@ const UserSurveyStats = ({ title, icon, t }) => {
className='flex items-center justify-between' className='flex items-center justify-between'
> >
<div className='flex items-center gap-2'> <div className='flex items-center gap-2'>
<span className='text-lg'>{config?.icon}</span> <span className='text-lg'>
{config?.icon}
</span>
<span className='text-sm text-gray-600 dark:text-gray-400'> <span className='text-sm text-gray-600 dark:text-gray-400'>
{config?.label} {config?.label}
</span> </span>
@@ -473,7 +470,9 @@ const UserSurveyStats = ({ title, icon, t }) => {
size='small' size='small'
style={{ width: 60 }} style={{ width: 60 }}
showInfo={false} showInfo={false}
stroke={colors[config?.color] || '#9ca3af'} stroke={
colors[config?.color] || '#9ca3af'
}
/> />
<span className='text-sm font-medium w-12 text-right'> <span className='text-sm font-medium w-12 text-right'>
{item.count} {item.count}
@@ -557,11 +556,15 @@ const UserSurveyStats = ({ title, icon, t }) => {
<td className='py-2 px-3'> <td className='py-2 px-3'>
<Tag <Tag
color={ color={
AI_TOOL_CONFIG[item.ai_tool_usage]?.color AI_TOOL_CONFIG[item.ai_tool_usage]
?.color
} }
size='small' size='small'
> >
{AI_TOOL_CONFIG[item.ai_tool_usage]?.label} {
AI_TOOL_CONFIG[item.ai_tool_usage]
?.label
}
</Tag> </Tag>
</td> </td>
<td className='py-2 px-3 text-right font-medium'> <td className='py-2 px-3 text-right font-medium'>
@@ -579,6 +582,8 @@ const UserSurveyStats = ({ title, icon, t }) => {
</Spin> </Spin>
)} )}
</Card> </Card>
</div>
</div>
); );
}; };
@@ -20,16 +20,18 @@ import React from 'react';
import { Card, Table } from '@/components/ui'; import { Card, Table } from '@/components/ui';
import { renderQuota } from '../../helpers'; import { renderQuota } from '../../helpers';
const UserTopupRanking = ({ data, title, icon, t }) => { const UserTopupRanking = ({ data, title, icon, t, embedded = false }) => {
if (!data || data.length === 0) { if (!data || data.length === 0) {
return ( return (
<Card <Card
className='shadow-sm hover:shadow-md transition-shadow' className={`shadow-sm hover:shadow-md transition-shadow ${embedded ? 'analytics-fold-content' : ''}`}
title={ title={
embedded ? undefined : (
<div className='flex items-center gap-2'> <div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span> <span className='text-brand'>{icon}</span>
<span className='font-semibold'>{title}</span> <span className='font-semibold'>{title}</span>
</div> </div>
)
} }
bodyStyle={{ padding: '16px' }} bodyStyle={{ padding: '16px' }}
> >
@@ -123,8 +125,9 @@ const UserTopupRanking = ({ data, title, icon, t }) => {
return ( return (
<Card <Card
className='shadow-sm hover:shadow-md transition-shadow' className={`shadow-sm hover:shadow-md transition-shadow ${embedded ? 'analytics-fold-content' : ''}`}
title={ title={
embedded ? undefined : (
<div className='flex items-center gap-2'> <div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span> <span className='text-brand'>{icon}</span>
<span className='font-semibold'>{title}</span> <span className='font-semibold'>{title}</span>
@@ -132,6 +135,7 @@ const UserTopupRanking = ({ data, title, icon, t }) => {
{t('共')} {data.length} {t('人')} {t('共')} {data.length} {t('人')}
</span> </span>
</div> </div>
)
} }
bodyStyle={{ padding: '0' }} bodyStyle={{ padding: '0' }}
> >
@@ -0,0 +1,35 @@
.console-page .analytics-fold-panel {
min-width: 0;
overflow: hidden;
border: 1px solid var(--console-border);
border-radius: 0.75rem;
background: var(--console-surface);
}
.console-page .analytics-fold-panel > button {
border: 0;
border-radius: 0;
box-shadow: none;
background: transparent;
border-bottom-color: var(--console-border);
transition: none;
}
.console-page .analytics-fold-panel > button:focus:not(:focus-visible) {
outline: none;
}
.console-page .analytics-fold-panel > button:focus-visible {
outline: 2px solid var(--console-primary);
outline-offset: -2px;
}
.console-page .analytics-fold-panel > button[aria-expanded='true'] {
border-bottom: 1px solid var(--console-border);
}
.console-page .analytics-fold-panel .analytics-fold-content.ant-card {
border: 0;
border-radius: 0;
box-shadow: none;
}
@@ -39,8 +39,8 @@ export const ReportHeader = ({ report, onExport, t }) => {
m.rollup_ready && m.history_floor > 0 && m.prev_start < m.history_floor; m.rollup_ready && m.history_floor > 0 && m.prev_start < m.history_floor;
return ( return (
<> <div className='flex flex-col gap-4'>
<Card className='shadow-sm mb-4' bodyStyle={{ padding: '16px 20px' }}> <Card className='shadow-sm' bodyStyle={{ padding: '16px 20px' }}>
<div className='flex flex-col md:flex-row md:items-center md:justify-between gap-3'> <div className='flex flex-col md:flex-row md:items-center md:justify-between gap-3'>
<div className='min-w-0'> <div className='min-w-0'>
<div className='text-xs font-semibold tracking-wider text-brand mb-1'> <div className='text-xs font-semibold tracking-wider text-brand mb-1'>
@@ -68,7 +68,6 @@ export const ReportHeader = ({ report, onExport, t }) => {
</Card> </Card>
{!m.rollup_ready ? ( {!m.rollup_ready ? (
<Banner <Banner
className='mb-4'
type='warning' type='warning'
fullMode={false} fullMode={false}
closeIcon={null} closeIcon={null}
@@ -80,7 +79,6 @@ export const ReportHeader = ({ report, onExport, t }) => {
) : null} ) : null}
{m.rollup_ready && !m.history_ready ? ( {m.rollup_ready && !m.history_ready ? (
<Banner <Banner
className='mb-4'
type='info' type='info'
fullMode={false} fullMode={false}
closeIcon={null} closeIcon={null}
@@ -92,7 +90,6 @@ export const ReportHeader = ({ report, onExport, t }) => {
) : null} ) : null}
{beyondFloor ? ( {beyondFloor ? (
<Banner <Banner
className='mb-4'
type='info' type='info'
fullMode={false} fullMode={false}
closeIcon={null} closeIcon={null}
@@ -106,7 +103,6 @@ export const ReportHeader = ({ report, onExport, t }) => {
) : null} ) : null}
{stale ? ( {stale ? (
<Banner <Banner
className='mb-4'
type='warning' type='warning'
fullMode={false} fullMode={false}
closeIcon={null} closeIcon={null}
@@ -118,7 +114,7 @@ export const ReportHeader = ({ report, onExport, t }) => {
)} )}
/> />
) : null} ) : null}
</> </div>
); );
}; };
+3 -1
View File
@@ -120,11 +120,13 @@ const OrgReportPanel = ({ report, loading, error, onRetry, t }) => {
: 'transition-opacity' : 'transition-opacity'
} }
> >
<div className='pb-2.5'>
<ReportHeader <ReportHeader
report={report} report={report}
onExport={() => exportOrgDetail(report.orgs || [], cny, t)} onExport={() => exportOrgDetail(report.orgs || [], cny, t)}
t={t} t={t}
/> />
</div>
<KeyFindings findings={findings} onJump={jump} t={t} /> <KeyFindings findings={findings} onJump={jump} t={t} />
@@ -191,7 +193,7 @@ const OrgReportPanel = ({ report, loading, error, onRetry, t }) => {
</div> </div>
<SectionTitle index={7} title={t('团队与明细')} /> <SectionTitle index={7} title={t('团队与明细')} />
<div className='space-y-4 mb-6'> <div className='flex flex-col gap-2.5 mb-6'>
<SalesRepTable <SalesRepTable
reps={reps} reps={reps}
cny={cny} cny={cny}
@@ -49,7 +49,7 @@ export const SectionCard = ({
export const SectionTitle = ({ id, index, title, desc }) => ( export const SectionTitle = ({ id, index, title, desc }) => (
<div <div
id={id} id={id}
className='flex items-baseline gap-2 mb-3 mt-8 flex-wrap scroll-mt-24' className='flex items-baseline gap-2 mb-3 mt-4 flex-wrap scroll-mt-24'
> >
{index ? ( {index ? (
<span className='text-xs font-semibold tracking-wider text-brand tabular-nums'> <span className='text-xs font-semibold tracking-wider text-brand tabular-nums'>
+11 -3
View File
@@ -95,8 +95,12 @@ const PasswordResetConfirm = () => {
if (success) { if (success) {
let password = res.data.data; let password = res.data.data;
setNewPassword(password); setNewPassword(password);
await copy(password); if (await copy(password)) {
showNotice(`${t('密码已重置并已复制到剪贴板:')} ${password}`); showNotice(`${t('密码已重置并已复制到剪贴板:')} ${password}`);
} else {
showNotice(t('密码已重置'));
showError(t('复制失败,请手动复制'));
}
} else { } else {
showError(message); showError(message);
} }
@@ -169,9 +173,13 @@ const PasswordResetConfirm = () => {
type='tertiary' type='tertiary'
theme='borderless' theme='borderless'
onClick={async () => { onClick={async () => {
await copy(newPassword); if (await copy(newPassword)) {
showNotice(`${t('密码已复制到剪贴板:')} ${newPassword}`, showNotice(
`${t('密码已复制到剪贴板:')} ${newPassword}`,
); );
} else {
showError(t('复制失败,请手动复制'));
}
}} }}
> >
{t('复制')} {t('复制')}
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { writeClipboardText } from '../../../helpers/clipboard';
import React, { useEffect, useState, useCallback, useRef } from 'react'; import React, { useEffect, useState, useCallback, useRef } from 'react';
import { API, showError } from '../../../helpers'; import { API, showError } from '../../../helpers';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@@ -361,14 +362,14 @@ const DocumentRenderer = ({
a.addEventListener('click', (e) => { a.addEventListener('click', (e) => {
e.preventDefault(); e.preventDefault();
const url = `${window.location.origin}${window.location.pathname}#${id}`; const url = `${window.location.origin}${window.location.pathname}#${id}`;
if (navigator.clipboard) { writeClipboardText(url).catch(() => {
navigator.clipboard.writeText(url).catch(() => {}); showError(t('复制失败,请手动复制'));
} });
history.replaceState(null, '', `#${id}`); history.replaceState(null, '', `#${id}`);
}); });
h.prepend(a); h.prepend(a);
}); });
}, [isEmbedded, loading, content, processedHtmlContent]); }, [isEmbedded, loading, content, processedHtmlContent, t]);
// 文档内容样式(prose)—— 同时兼顾浅色与深色 // 文档内容样式(prose)—— 同时兼顾浅色与深色
const proseClass = `prose prose-base dark:prose-invert max-w-none const proseClass = `prose prose-base dark:prose-invert max-w-none
+10 -2
View File
@@ -90,7 +90,11 @@ export default function LobeHubIcon({ iconName, size = 14 }) {
if (typeof iconName === 'string') iconName = iconName.trim(); if (typeof iconName === 'string') iconName = iconName.trim();
// 如果没有图标名称,返回 Avatar // 如果没有图标名称,返回 Avatar
if (!iconName) { if (!iconName) {
return <Avatar size='extra-extra-small'>?</Avatar>; return (
<Avatar size={size} gap={0} style={{ fontSize: size * 0.65 }}>
?
</Avatar>
);
} }
// 解析组件路径与点号链式属性 // 解析组件路径与点号链式属性
@@ -115,7 +119,11 @@ export default function LobeHubIcon({ iconName, size = 14 }) {
(typeof IconComponent !== 'function' && typeof IconComponent !== 'object') (typeof IconComponent !== 'function' && typeof IconComponent !== 'object')
) { ) {
const firstLetter = String(iconName).charAt(0).toUpperCase(); const firstLetter = String(iconName).charAt(0).toUpperCase();
return <Avatar size='extra-extra-small'>{firstLetter}</Avatar>; return (
<Avatar size={size} gap={0} style={{ fontSize: size * 0.65 }}>
{firstLetter}
</Avatar>
);
} }
// 解析点号链式属性,形如:key={...}、key='...'、key="..."、key=123、key、key=true/false // 解析点号链式属性,形如:key={...}、key='...'、key="..."、key=123、key、key=true/false
@@ -0,0 +1,217 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState } from 'react';
import { Alert, Button, Checkbox, Modal, Tooltip, theme } from 'antd';
import { Settings } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import './column-settings.css';
const titleText = (title) =>
React.Children.toArray(title)
.map((child) =>
React.isValidElement(child) ? titleText(child.props.children) : child,
)
.join('');
const columnOptions = (columns) =>
columns.map((column) => ({
value: column.key,
label: column.label ?? titleText(column.title),
disabled: column.disabled,
}));
const selectedKeys = (options, value) =>
options
.filter((option) => value.includes(option.value))
.map((option) => option.value);
export function ColumnSettingsButton({ onClick, open = false }) {
const { t } = useTranslation();
return (
<Tooltip title={t('列设置')}>
<Button
className='table-column-settings-trigger'
type='text'
size='middle'
aria-label={t('列设置')}
aria-haspopup='dialog'
aria-expanded={open}
icon={<Settings size={16} />}
onClick={onClick}
/>
</Tooltip>
);
}
export function ColumnSettingsModal({
open,
onCancel,
columns,
value,
defaultValue,
onConfirm,
}) {
const { t } = useTranslation();
const { token } = theme.useToken();
const options = columnOptions(columns);
const [session, setSession] = useState({
open: false,
draft: [],
error: false,
});
// Snapshot on opening only: background table refreshes must not reset the draft.
if (session.open !== open) {
setSession({ open, draft: selectedKeys(options, value), error: false });
}
const draft = selectedKeys(options, session.draft);
const selectable = options.filter((option) => !option.disabled);
const checkedCount = selectable.filter((option) =>
draft.includes(option.value),
).length;
const changeDraft = (keys) => setSession({ open, draft: keys, error: false });
const confirm = () => {
if (!draft.length) {
setSession({ ...session, error: true });
return;
}
onConfirm(draft);
onCancel();
};
return (
<Modal
open={open}
title={t('列设置')}
width={520}
rootClassName='table-column-settings'
className='table-column-settings-dialog'
style={{
'--cs-theme-text': token.colorText,
'--cs-theme-border': token.colorBorderSecondary,
}}
onCancel={onCancel}
maskClosable
keyboard
footer={
<div className='table-column-settings-footer'>
<Button
onClick={() => changeDraft(selectedKeys(options, defaultValue))}
>
{t('重置')}
</Button>
<Button onClick={onCancel}>{t('取消')}</Button>
<Button type='primary' onClick={confirm}>
{t('确定')}
</Button>
</div>
}
>
<div className='table-column-settings-all'>
<Checkbox
checked={selectable.length > 0 && checkedCount === selectable.length}
indeterminate={checkedCount > 0 && checkedCount < selectable.length}
disabled={!selectable.length}
onChange={(event) =>
changeDraft(
options
.filter((option) =>
option.disabled
? draft.includes(option.value)
: event.target.checked,
)
.map((option) => option.value),
)
}
>
{t('全选')}
</Checkbox>
</div>
<Checkbox.Group
className='table-column-settings-grid'
options={options}
value={draft}
onChange={changeDraft}
/>
{session.error && (
<Alert
className='table-column-settings-error'
type='error'
showIcon
message={t('请至少保留一列')}
/>
)}
</Modal>
);
}
export function ColumnVisibilitySettings({
showColumnSelector,
setShowColumnSelector,
columns,
visibleColumns,
setVisibleColumns,
getDefaultColumnVisibility,
}) {
const defaults = getDefaultColumnVisibility();
return (
<ColumnSettingsModal
open={showColumnSelector}
onCancel={() => setShowColumnSelector(false)}
columns={columns}
value={columns
.filter((column) => visibleColumns[column.key])
.map((column) => column.key)}
defaultValue={columns
.filter((column) => defaults[column.key])
.map((column) => column.key)}
onConfirm={(keys) =>
setVisibleColumns((current) => ({
...current,
...Object.fromEntries(
columns.map((column) => [column.key, keys.includes(column.key)]),
),
}))
}
/>
);
}
export default function TableColumnSettings({
columns,
value,
defaultValue,
onChange,
}) {
const [open, setOpen] = useState(false);
return (
<>
<ColumnSettingsButton open={open} onClick={() => setOpen(true)} />
<ColumnSettingsModal
open={open}
onCancel={() => setOpen(false)}
columns={columns}
value={value}
defaultValue={defaultValue}
onConfirm={onChange}
/>
</>
);
}
@@ -0,0 +1,45 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Button } from 'antd';
import { Search } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import './filter-search-button.css';
export default function FilterSearchButton({
loading,
htmlType = 'submit',
onClick,
}) {
const { t } = useTranslation();
return (
<Button
className='filter-search-button'
type='primary'
htmlType={htmlType}
onClick={onClick}
size='middle'
loading={loading}
icon={<Search size={14} />}
>
{t('搜索')}
</Button>
);
}
@@ -0,0 +1,46 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useLayoutEffect, useRef, useState } from 'react';
import { Empty } from 'antd';
import { useTranslation } from 'react-i18next';
import './table-empty.css';
export default function TableEmpty() {
const { t } = useTranslation();
const ref = useRef(null);
const [width, setWidth] = useState(undefined);
useLayoutEffect(() => {
const viewport = ref.current?.closest('.ant-table-container');
if (!viewport) return;
// Keep the empty state centered in the visible area of a wide, scrollable table.
const resize = () => setWidth(viewport.clientWidth || undefined);
resize();
const observer = new ResizeObserver(resize);
observer.observe(viewport);
return () => observer.disconnect();
}, []);
return (
<div ref={ref} className='table-empty-state' style={{ width }}>
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={t('暂无数据')} />
</div>
);
}
@@ -0,0 +1,40 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { useTranslation } from 'react-i18next';
import './table-toolbar.css';
export function TableTitle({ children }) {
const { t } = useTranslation();
return (
<h2 className='table-toolbar-title'>
{typeof children === 'string' ? t(children) : children}
</h2>
);
}
export default function TableToolbar({ title, children }) {
return (
<div className='table-toolbar'>
<TableTitle>{title}</TableTitle>
{children && <div className='table-toolbar-actions'>{children}</div>}
</div>
);
}
@@ -0,0 +1,121 @@
.table-column-settings {
--cs-mask: rgba(0, 0, 0, 0.3);
--cs-text: rgba(0, 0, 0, 0.88);
--cs-border: #e9edf2;
--cs-space: 8px;
--cs-column-gap: 20px;
--cs-row-gap: 16px;
}
html.dark .table-column-settings-dialog {
--cs-text: var(--cs-theme-text);
--cs-border: var(--cs-theme-border);
}
.table-column-settings .ant-modal-mask {
background: var(--cs-mask);
backdrop-filter: blur(4px);
}
.table-column-settings-dialog.ant-modal {
max-width: calc(100vw - 32px);
}
.table-column-settings-dialog .ant-modal-content {
padding: 20px 24px;
border-radius: 12px;
}
.table-column-settings-dialog .ant-modal-header {
margin-bottom: var(--cs-space);
}
.table-column-settings-dialog .ant-modal-title {
color: var(--cs-text);
font-size: 16px;
font-weight: 600;
line-height: 24px;
}
.table-column-settings-dialog .ant-modal-body {
padding-top: 20px;
}
.table-column-settings-all {
padding: 14px 0;
margin-bottom: 18px;
border-bottom: 1px solid var(--cs-border);
}
.table-column-settings-grid.ant-checkbox-group {
display: grid;
width: 100%;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--cs-row-gap) var(--cs-column-gap);
padding: 4px 0 12px;
}
.table-column-settings-dialog .ant-checkbox-wrapper {
min-width: 0;
margin: 0;
color: var(--cs-text);
font-size: 14px;
line-height: 22px;
}
.table-column-settings-dialog .ant-checkbox-inner {
width: 17px;
height: 17px;
border-radius: 6px;
}
.table-column-settings-dialog .ant-modal-footer {
margin-top: 12px;
}
.table-column-settings-footer {
display: flex;
justify-content: flex-end;
flex-wrap: wrap;
gap: var(--cs-space);
}
.table-column-settings-footer .ant-btn {
height: 34px;
margin: 0;
line-height: normal;
}
.table-column-settings-footer .ant-btn-default {
color: var(--cs-text);
}
.table-column-settings-error {
margin-top: var(--cs-row-gap);
}
.table-column-settings-trigger.ant-btn {
flex: 0 0 auto;
width: 34px;
height: 34px;
margin-inline-start: auto;
}
.table-column-toolbar {
display: flex;
justify-content: flex-end;
align-items: center;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 18px;
}
@media (max-width: 575px) {
.table-column-settings-grid.ant-checkbox-group {
gap: 14px 10px;
}
.table-column-settings-dialog .ant-checkbox-wrapper {
font-size: 12px;
}
}
@@ -0,0 +1,17 @@
.console-page .filter-search-button {
display: inline-flex;
align-items: center;
justify-content: center;
}
.console-page .filter-search-button > .ant-btn-icon {
display: inline-flex;
align-items: center;
justify-content: center;
}
.console-page .filter-search-button .lucide {
display: block;
width: 14px;
height: 14px;
}
@@ -0,0 +1,58 @@
/* Match the consumption record's labels, grid and action placement. */
.log-filter-grid {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 16px;
width: 100%;
}
.log-filter-wide {
grid-column: span 2;
}
.log-filter-form .ant-form-item {
min-width: 0;
margin-bottom: 0;
}
.log-filter-form .ant-form-item-label {
padding-bottom: 8px;
}
.log-filter-form .ant-form-item-label > label {
height: 21px;
color: var(--text-secondary);
font-size: 13px;
}
.log-filter-form :is(.ant-picker, .ant-select) {
width: 100%;
}
.log-filter-actions {
display: flex;
justify-content: flex-end;
flex-wrap: wrap;
gap: 10px;
}
.log-filter-content {
display: flex;
flex-direction: column;
gap: 16px;
width: 100%;
}
.console-page .console-search-card .log-filter-form {
display: block;
}
.console-page .log-filter-form .ant-form-item-label > label {
height: 21px;
font-size: 13px;
line-height: 21px;
}
@media (max-width: 1200px) {
.log-filter-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (max-width: 768px) {
.log-filter-grid {
grid-template-columns: minmax(0, 1fr);
}
.log-filter-wide {
grid-column: auto;
}
}
@@ -0,0 +1,30 @@
.ant-table-wrapper
.ant-table
.ant-table-tbody
> .ant-table-placeholder:has(.table-empty-state)
> td.ant-table-cell {
padding: 0;
height: 172px;
vertical-align: middle;
}
.ant-table-wrapper .ant-table-expanded-row-fixed:has(> .table-empty-state) {
margin: 0;
padding: 0;
}
.table-empty-state {
position: sticky;
left: 0;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
height: 172px;
max-width: 100%;
}
.table-empty-state > .ant-empty,
.ant-table-wrapper .ant-table-placeholder .table-empty-state > .ant-empty {
margin: 0;
}
@@ -0,0 +1,43 @@
.table-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 16px;
min-height: 34px;
margin-bottom: 16px;
}
h2.table-toolbar-title {
flex-shrink: 0;
margin: 0;
color: var(--console-heading, var(--uc-heading, var(--ui-color-text-0)));
font-size: 15px;
font-weight: 600;
line-height: 1.5714;
}
.table-toolbar-actions {
display: flex;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
gap: 8px;
margin-inline-start: auto;
}
.console-page .table-toolbar .ant-btn:not(.ant-btn-link):not(.ant-btn-text) {
min-height: var(--console-control-height);
font-size: 14px;
}
.console-list-toolbar .console-list-actions-offset {
margin-inline-start: 20px;
min-width: 0;
}
@media (max-width: 767px) {
.console-list-toolbar .console-list-actions-offset {
flex-basis: calc(100% - 20px);
}
}
+33
View File
@@ -22,6 +22,9 @@ import { Card, Divider, Button } from '@/components/ui';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { useIsMobile } from '../../../hooks/common/useIsMobile'; import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { IconEyeOpened, IconEyeClosed } from '@/components/ui/icons'; import { IconEyeOpened, IconEyeClosed } from '@/components/ui/icons';
import { useConsolePage } from '../../console/ConsoleContext';
import ConsoleCollection from '../../console/ConsoleCollection';
import TableToolbar from '../table/TableToolbar';
/** /**
* CardPro 高级卡片组件 * CardPro 高级卡片组件
@@ -49,6 +52,9 @@ const CardPro = ({
tabsArea, tabsArea,
actionsArea, actionsArea,
searchArea, searchArea,
tableActions,
tableTitle,
tableActionsOffset = false,
paginationArea, // 新增分页区域 paginationArea, // 新增分页区域
// 卡片属性 // 卡片属性
shadows, shadows,
@@ -59,6 +65,7 @@ const CardPro = ({
t = (key) => key, t = (key) => key,
...props ...props
}) => { }) => {
const consolePage = useConsolePage();
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const [showMobileActions, setShowMobileActions] = useState(false); const [showMobileActions, setShowMobileActions] = useState(false);
@@ -156,6 +163,24 @@ const CardPro = ({
const footerContent = renderFooter(); const footerContent = renderFooter();
if (consolePage) {
return (
<ConsoleCollection
statsArea={statsArea}
descriptionArea={descriptionArea}
tabsArea={tabsArea}
actionsArea={actionsArea}
searchArea={searchArea}
tableActions={tableActions}
tableTitle={tableTitle}
tableActionsOffset={tableActionsOffset}
paginationArea={paginationArea}
>
{children}
</ConsoleCollection>
);
}
return ( return (
<Card <Card
className={`table-scroll-card !rounded-2xl ${className}`} className={`table-scroll-card !rounded-2xl ${className}`}
@@ -166,6 +191,11 @@ const CardPro = ({
style={style} style={style}
{...props} {...props}
> >
{tableTitle ? (
<TableToolbar title={tableTitle}>{tableActions}</TableToolbar>
) : tableActions ? (
<div className='table-column-toolbar'>{tableActions}</div>
) : null}
{children} {children}
</Card> </Card>
); );
@@ -188,6 +218,9 @@ CardPro.propTypes = {
PropTypes.arrayOf(PropTypes.node), PropTypes.arrayOf(PropTypes.node),
]), ]),
searchArea: PropTypes.node, searchArea: PropTypes.node,
tableActions: PropTypes.node,
tableTitle: PropTypes.node,
tableActionsOffset: PropTypes.bool,
paginationArea: PropTypes.node, paginationArea: PropTypes.node,
// 表格内容 // 表格内容
children: PropTypes.node, children: PropTypes.node,
+3 -1
View File
@@ -33,6 +33,7 @@ import { IconChevronDown, IconChevronUp } from '@/components/ui/icons';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { useIsMobile } from '../../../hooks/common/useIsMobile'; import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { useMinimumLoadingTime } from '../../../hooks/common/useMinimumLoadingTime'; import { useMinimumLoadingTime } from '../../../hooks/common/useMinimumLoadingTime';
import { useConsolePage } from '../../console/ConsoleContext';
/** /**
* CardTable 响应式表格组件 * CardTable 响应式表格组件
@@ -48,6 +49,7 @@ const CardTable = ({
hidePagination = false, hidePagination = false,
...tableProps ...tableProps
}) => { }) => {
const consolePage = useConsolePage();
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const { t } = useTranslation(); const { t } = useTranslation();
@@ -103,7 +105,7 @@ const CardTable = ({
selectableKeys.length > 0 && selectableKeys.length > 0 &&
selectableKeys.every((key) => selectedKeys.includes(key)); selectableKeys.every((key) => selectedKeys.includes(key));
if (!isMobile) { if (!isMobile || consolePage) {
const finalTableProps = hidePagination const finalTableProps = hidePagination
? { ...tableProps, pagination: false } ? { ...tableProps, pagination: false }
: tableProps; : tableProps;
@@ -20,7 +20,7 @@ For commercial licensing, please contact support@quantumnous.com
import React from 'react'; import React from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Card, Button, Typography, Tag } from '@/components/ui'; import { Card, Button, Typography, Tag } from '@/components/ui';
import { copy, showSuccess } from '../../../helpers'; import { copy, showError, showSuccess } from '../../../helpers';
/** /**
* 解析密钥数据,支持多种格式 * 解析密钥数据,支持多种格式
@@ -95,14 +95,14 @@ const ChannelKeyDisplay = ({
const parsedKeys = parseChannelKeys(keyData, t); const parsedKeys = parseChannelKeys(keyData, t);
const isMultipleKeys = parsedKeys.length > 1; const isMultipleKeys = parsedKeys.length > 1;
const handleCopyAll = () => { const handleCopyAll = async () => {
copy(keyData); if (await copy(keyData)) showSuccess(t('所有密钥已复制到剪贴板'));
showSuccess(t('所有密钥已复制到剪贴板')); else showError(t('复制失败,请手动复制'));
}; };
const handleCopyKey = (content) => { const handleCopyKey = async (content) => {
copy(content); if (await copy(content)) showSuccess(t('密钥已复制到剪贴板'));
showSuccess(t('密钥已复制到剪贴板')); else showError(t('复制失败,请手动复制'));
}; };
return ( return (
@@ -21,6 +21,7 @@ import React from 'react';
import { Button } from '@/components/ui'; import { Button } from '@/components/ui';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { useIsMobile } from '../../../hooks/common/useIsMobile'; import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { useConsolePage } from '../../console/ConsoleContext';
/** /**
* 紧凑模式切换按钮组件 * 紧凑模式切换按钮组件
@@ -37,9 +38,10 @@ const CompactModeToggle = ({
...props ...props
}) => { }) => {
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const consolePage = useConsolePage();
// 在移动端隐藏紧凑列表切换按钮 // Console lists keep their stored density, but no longer expose a toggle.
if (isMobile) { if (isMobile || consolePage) {
return null; return null;
} }
+22 -7
View File
@@ -58,6 +58,7 @@ const JSONEditor = ({
template, template,
templateLabel, templateLabel,
editorType = 'keyValue', editorType = 'keyValue',
objectValueAutoSize,
rules = [], rules = [],
formApi = null, formApi = null,
...props ...props
@@ -368,6 +369,7 @@ const JSONEditor = ({
return ( return (
<TextArea <TextArea
rows={2} rows={2}
autosize={objectValueAutoSize}
value={JSON.stringify(value, null, 2)} value={JSON.stringify(value, null, 2)}
onChange={(txt) => { onChange={(txt) => {
try { try {
@@ -407,7 +409,7 @@ const JSONEditor = ({
// 渲染键值对编辑器 // 渲染键值对编辑器
const renderKeyValueEditor = () => { const renderKeyValueEditor = () => {
return ( return (
<div className='space-y-1'> <div className='json-editor-pairs space-y-1'>
{/* 重复键警告 */} {/* 重复键警告 */}
{duplicateKeys.size > 0 && ( {duplicateKeys.size > 0 && (
<Banner <Banner
@@ -442,7 +444,12 @@ const JSONEditor = ({
keyValuePairs.slice(index + 1).every((p) => p.key !== pair.key); keyValuePairs.slice(index + 1).every((p) => p.key !== pair.key);
return ( return (
<Row key={pair.id} gutter={8} align='middle'> <Row
key={pair.id}
gutter={8}
align='middle'
className='json-editor-pair'
>
<Col span={10}> <Col span={10}>
<div className='relative'> <div className='relative'>
<Input <Input
@@ -486,7 +493,7 @@ const JSONEditor = ({
); );
})} })}
<div className='mt-2 flex justify-center'> <div className='json-editor-add mt-2 flex justify-center'>
<Button <Button
icon={<IconPlus />} icon={<IconPlus />}
type='primary' type='primary'
@@ -568,7 +575,10 @@ const JSONEditor = ({
<Tooltip content={t('重复的键名')}> <Tooltip content={t('重复的键名')}>
<IconAlertTriangle <IconAlertTriangle
className='absolute right-2 top-1/2 transform -translate-y-1/2' className='absolute right-2 top-1/2 transform -translate-y-1/2'
style={{ color: 'var(--ui-color-warning)', fontSize: '14px' }} style={{
color: 'var(--ui-color-warning)',
fontSize: '14px',
}}
/> />
</Tooltip> </Tooltip>
)} )}
@@ -628,8 +638,9 @@ const JSONEditor = ({
<Form.Slot label={label}> <Form.Slot label={label}>
<Card <Card
header={ header={
<div className='flex justify-between items-center'> <div className='json-editor-header flex justify-between items-center'>
<Tabs <Tabs
className='json-editor-tabs'
type='slash' type='slash'
activeKey={editMode} activeKey={editMode}
onChange={(key) => { onChange={(key) => {
@@ -651,7 +662,9 @@ const JSONEditor = ({
)} )}
</div> </div>
} }
headerStyle={{ padding: '12px 16px' }} headerStyle={{
padding: 'var(--json-editor-header-padding, 12px 16px)',
}}
bodyStyle={{ padding: '16px' }} bodyStyle={{ padding: '16px' }}
className='!rounded-2xl' className='!rounded-2xl'
> >
@@ -670,6 +683,7 @@ const JSONEditor = ({
{renderVisualEditor()} {renderVisualEditor()}
{/* 隐藏的Form字段用于验证和数据绑定 */} {/* 隐藏的Form字段用于验证和数据绑定 */}
<Form.Input <Form.Input
className='json-editor-bound-field'
field={field} field={field}
value={value} value={value}
rules={rules} rules={rules}
@@ -689,6 +703,7 @@ const JSONEditor = ({
/> />
{/* 隐藏的Form字段用于验证和数据绑定 */} {/* 隐藏的Form字段用于验证和数据绑定 */}
<Form.Input <Form.Input
className='json-editor-bound-field'
field={field} field={field}
value={value} value={value}
rules={rules} rules={rules}
@@ -701,7 +716,7 @@ const JSONEditor = ({
{/* 额外文本显示在卡片底部 */} {/* 额外文本显示在卡片底部 */}
{extraText && ( {extraText && (
<Divider margin='12px' align='center'> <Divider margin='var(--json-editor-note-margin, 12px)' align='center'>
<Text type='tertiary' size='small'> <Text type='tertiary' size='small'>
{extraText} {extraText}
</Text> </Text>
@@ -0,0 +1,88 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState } from 'react';
import { Button } from 'antd';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import { ConsoleCard, ConsoleSearchBar } from './ConsolePrimitives';
import { TableTitle } from '../common/table/TableToolbar';
export default function ConsoleCollection({
children,
statsArea,
descriptionArea,
tabsArea,
actionsArea,
searchArea,
tableActions,
tableTitle,
tableActionsOffset = false,
paginationArea,
}) {
const { t } = useTranslation();
const isMobile = useIsMobile();
const [expanded, setExpanded] = useState(false);
const showSearch = !isMobile || expanded;
return (
<div className='console-collection'>
{statsArea && (
<ConsoleCard className='console-stats'>{statsArea}</ConsoleCard>
)}
{searchArea && (
<>
{isMobile && (
<Button
onClick={() => setExpanded(!expanded)}
aria-expanded={expanded}
>
{t(expanded ? '隐藏操作项' : '显示操作项')}
</Button>
)}
<ConsoleSearchBar hidden={!showSearch}>{searchArea}</ConsoleSearchBar>
</>
)}
<ConsoleCard>
{tabsArea && <div className='console-list-tabs'>{tabsArea}</div>}
{(tableTitle || descriptionArea || actionsArea || tableActions) && (
<div className='console-list-toolbar'>
{tableTitle && <TableTitle>{tableTitle}</TableTitle>}
{actionsArea && (
<div
className={`console-list-actions${tableActionsOffset ? ' console-list-actions-offset' : ''}`}
>
{actionsArea}
</div>
)}
{descriptionArea && (
<div className='console-list-description'>{descriptionArea}</div>
)}
{tableActions && (
<div className='console-list-table-actions'>{tableActions}</div>
)}
</div>
)}
<div className='console-list-content'>{children}</div>
{paginationArea && (
<div className='console-pagination'>{paginationArea}</div>
)}
</ConsoleCard>
</div>
);
}
+45
View File
@@ -0,0 +1,45 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { createContext, useContext } from 'react';
import { theme } from 'antd';
export function useConsoleThemeStyle() {
const { token } = theme.useToken();
return {
'--console-surface': token.colorBgContainer,
'--console-bg': token.colorBgLayout,
'--console-heading': token.colorTextHeading,
'--console-text': token.colorText,
'--console-muted': token.colorTextSecondary,
'--console-border': token.colorBorderSecondary,
'--console-fill': token.colorFillAlter,
'--console-primary': token.colorPrimary,
};
}
export const ConsoleContext = createContext(null);
export const useConsolePage = () => useContext(ConsoleContext);
export const ConsoleSearchContext = createContext(false);
export const useConsoleControlSize = (size) =>
useContext(ConsoleSearchContext)
? 'middle'
: size === 'default'
? 'middle'
: size;
@@ -0,0 +1,51 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useId } from 'react';
import { Button } from 'antd';
import { useTranslation } from 'react-i18next';
import FilterSearchButton from '../common/table/FilterSearchButton';
import './module-alignment.css';
// Labels belong to the module; this wrapper only supplies the shared layout.
export function ConsoleFilterField({ label, children }) {
const id = useId();
return (
<div className='console-module-field'>
<label htmlFor={id}>{label}</label>
{React.isValidElement(children)
? React.cloneElement(children, { id })
: children}
</div>
);
}
export function ConsoleFilterActions({ onReset, onSearch, loading }) {
const { t } = useTranslation();
return (
<div className='console-module-filter-actions'>
<Button onClick={onReset}>{t('重置')}</Button>
<FilterSearchButton
htmlType={onSearch ? 'button' : 'submit'}
onClick={onSearch}
loading={loading}
/>
</div>
);
}
@@ -0,0 +1,86 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { Breadcrumb } from 'antd';
import { Link, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
ConsoleContext,
useConsolePage,
useConsoleThemeStyle,
} from './ConsoleContext';
import { resolveConsolePage } from './consoleRoutes';
import './console.css';
export default function ConsolePageContainer({ children }) {
const { pathname } = useLocation();
const { t } = useTranslation();
const themeStyle = useConsoleThemeStyle();
const page = useMemo(() => resolveConsolePage(pathname), [pathname]);
const [actionsTarget, setActionsTarget] = useState(null);
const context = useMemo(
() => ({ page, actionsTarget }),
[page, actionsTarget],
);
return (
<ConsoleContext.Provider value={context}>
<main
className={`console-page${page.canvas ? ' console-page--canvas' : ''}`}
data-console-page={page.key}
style={themeStyle}
>
<header className='console-page-header'>
<Breadcrumb
className='console-breadcrumb'
items={page.breadcrumbs.map((item, index) => ({
key: item.path,
title:
index === page.breadcrumbs.length - 1 ? (
<span aria-current='page'>{t(item.title)}</span>
) : (
<Link to={item.path}>{t(item.title)}</Link>
),
}))}
/>
<div className='console-page-header-main'>
<div className='console-page-heading'>
<h1 className='console-page-title'>{t(page.title)}</h1>
<p className='console-page-description'>
{t(`consoleUi.descriptions.${page.description}`)}
</p>
</div>
<div className='console-page-actions' ref={setActionsTarget} />
</div>
</header>
<div className='console-page-body'>{children}</div>
</main>
</ConsoleContext.Provider>
);
}
export function ConsolePageActions({ children }) {
const context = useConsolePage();
if (!context) return <>{children}</>;
return context.actionsTarget
? createPortal(children, context.actionsTarget)
: null;
}
@@ -0,0 +1,235 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { forwardRef } from 'react';
import {
Alert,
Button,
Card,
Drawer,
Empty,
Form,
Modal,
Table,
Tabs,
theme,
} from 'antd';
import { useTranslation } from 'react-i18next';
import {
ConsoleSearchContext,
useConsolePage,
useConsoleThemeStyle,
} from './ConsoleContext';
const classes = (base, extra) => [base, extra].filter(Boolean).join(' ');
export function ConsoleAlert({ className, style, type = 'info', ...props }) {
const { token } = theme.useToken();
const semantic = type[0].toUpperCase() + type.slice(1);
return (
<Alert
{...props}
type={type}
showIcon
className={classes('console-alert', className)}
style={{
...style,
marginBlock: style?.marginBlock ?? '0 16px',
padding: '12px 16px',
borderRadius: token.borderRadiusLG,
background: token[`color${semantic}Bg`],
borderColor: token[`color${semantic}Border`],
color: token.colorText,
}}
/>
);
}
export const ConsoleCard = forwardRef(function ConsoleCard(
{ className, ...props },
ref,
) {
return (
<Card {...props} ref={ref} className={classes('console-card', className)} />
);
});
// Existing form adapters keep their value and submit contracts inside this layout.
export function ConsoleSearchBar({ children, className, formProps, ...props }) {
return (
<ConsoleCard
{...props}
className={classes('console-search-card', className)}
>
<ConsoleSearchContext.Provider value={true}>
{formProps ? (
<ConsoleForm {...formProps}>{children}</ConsoleForm>
) : (
children
)}
</ConsoleSearchContext.Provider>
</ConsoleCard>
);
}
export function ConsoleSearchActions({
onReset,
onSearch,
loading,
searchLabel = '搜索',
}) {
const { t } = useTranslation();
return (
<div className='console-search-actions'>
{onReset && <Button onClick={onReset}>{t('重置')}</Button>}
<Button
type='primary'
htmlType={onSearch ? 'button' : 'submit'}
onClick={onSearch}
loading={loading}
>
{t(searchLabel)}
</Button>
</div>
);
}
export const ConsoleForm = forwardRef(function ConsoleForm(
{ className, layout = 'vertical', ...props },
ref,
) {
const isSettings = useConsolePage()?.page.key === 'setting';
return (
<Form
{...props}
ref={ref}
layout={isSettings ? 'vertical' : layout}
labelCol={isSettings ? undefined : props.labelCol}
wrapperCol={isSettings ? undefined : props.wrapperCol}
labelAlign={isSettings ? 'left' : props.labelAlign}
className={classes(
isSettings ? 'console-form settings-system-form' : 'console-form',
className,
)}
/>
);
});
export const ConsoleTable = forwardRef(function ConsoleTable(
{ className, scroll, locale, size = 'middle', ...props },
ref,
) {
return (
<Table
{...props}
ref={ref}
size={size}
scroll={{ x: 'max-content', ...scroll }}
locale={{
emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />,
...locale,
}}
className={classes('console-table', className)}
/>
);
});
export function ConsoleTabs({ className, ...props }) {
return <Tabs {...props} className={classes('console-tabs', className)} />;
}
const isFooterButton = (node) =>
React.isValidElement(node) &&
(node.type === Button || node.type?.render?.name === 'Button');
const isPrimaryAction = ({ props }) =>
props.theme === 'solid' ||
props.danger ||
props.type === 'danger' ||
(props.type === 'primary' &&
!['light', 'outline', 'borderless'].includes(props.theme));
// Reorder only groups composed entirely of buttons; preserve mixed footer content.
function normalizeFooter(footer) {
if (!footer || typeof footer === 'function') return footer;
const nodes = React.Children.toArray(footer);
if (nodes.length > 1 && nodes.every(isFooterButton)) {
return [
...nodes.filter((node) => !isPrimaryAction(node)),
...nodes.filter(isPrimaryAction),
];
}
const normalized = nodes.map((node) =>
React.isValidElement(node) && !isFooterButton(node) && node.props.children
? React.cloneElement(
node,
undefined,
normalizeFooter(node.props.children),
)
: node,
);
return Array.isArray(footer) ? normalized : normalized[0];
}
export function ConsoleModal({
rootClassName,
style,
footer,
width = 560,
...props
}) {
const themeStyle = useConsoleThemeStyle();
const isSettings = useConsolePage()?.page.key === 'setting';
return (
<Modal
{...props}
width={width}
style={{ ...themeStyle, ...style }}
footer={normalizeFooter(footer)}
rootClassName={classes(
isSettings ? 'console-overlay settings-form-dialog' : 'console-overlay',
rootClassName,
)}
/>
);
}
export function ConsoleDrawer({
rootClassName,
rootStyle,
footer,
width = 560,
...props
}) {
const themeStyle = useConsoleThemeStyle();
const isSettings = useConsolePage()?.page.key === 'setting';
return (
<Drawer
{...props}
width={width}
rootStyle={{ ...themeStyle, ...rootStyle }}
footer={normalizeFooter(footer)}
rootClassName={classes(
isSettings
? 'console-overlay console-drawer settings-form-dialog'
: 'console-overlay console-drawer',
rootClassName,
)}
/>
);
}
+446
View File
@@ -0,0 +1,446 @@
.console-page,
.console-overlay {
--console-space-1: 8px;
--console-space-2: 16px;
--console-space-3: 24px;
--console-gap: var(--console-space-2);
--console-radius: 10px;
--console-control-height: 34px;
}
.console-page {
min-width: 0;
min-height: 100dvh;
padding: calc(
var(--console-header-offset, 72px) + var(--uc-page-pad-top, 30px)
)
var(--uc-page-pad-x, 36px) var(--uc-page-pad-bottom, 36px);
background: var(--uc-page-bg, var(--console-bg));
color: var(--console-text);
}
.console-page-header {
margin-bottom: 18px;
}
.console-page .console-breadcrumb.ant-breadcrumb {
margin-bottom: var(--console-space-3);
font-size: 12px;
line-height: 18px;
}
.console-breadcrumb .ant-breadcrumb-separator {
margin-inline: 10px;
}
.console-page .console-breadcrumb :is(ol, li, a, .ant-breadcrumb-link) {
line-height: 18px;
}
.console-page-header-main {
display: flex;
align-items: flex-end;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--console-space-2);
}
.console-page-heading {
min-width: 0;
}
.console-page-title {
margin: 0;
color: var(--console-heading);
font-size: 28px;
line-height: 32px;
font-weight: 650;
letter-spacing: -0.6px;
}
.console-page-description {
margin: 6px 0 0;
color: var(--console-muted);
font-size: 14px;
line-height: 22px;
}
.console-page-actions,
.console-list-actions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--console-space-1);
min-width: 0;
max-width: 100%;
}
.console-page-actions:empty {
display: none;
}
.console-page-body,
.console-content,
.console-collection {
display: flex;
flex-direction: column;
gap: var(--console-gap);
min-width: 0;
}
.console-page-body > *,
.console-page .ant-layout,
.console-page .ant-layout-content,
.console-page .ant-tabs-content-holder,
.console-page .ant-tabs-tabpane,
.console-page .ant-col,
.console-page .ant-space-item {
min-width: 0;
max-width: 100%;
}
.console-page .console-card.ant-card {
border: 1px solid var(--console-border);
border-radius: var(--console-radius);
background: var(--console-surface);
box-shadow: none;
}
.console-page .console-card > .ant-card-body {
padding: var(--console-space-3);
}
.console-page .console-card > .ant-card-head {
min-height: 56px;
padding-inline: var(--console-space-3);
border-color: var(--console-border);
font-size: 16px;
font-weight: 600;
}
.console-list-tabs,
.console-list-toolbar {
margin-bottom: var(--console-space-2);
}
.console-list-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--console-space-2);
flex-wrap: wrap;
}
.console-list-toolbar .console-list-actions {
flex: 1;
}
.console-list-description {
display: flex;
justify-content: flex-end;
margin-inline-start: auto;
}
.console-list-table-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: var(--console-space-1);
margin-inline-start: auto;
}
.console-page
.console-list-toolbar
.ant-btn:not(.ant-btn-link):not(.ant-btn-text) {
min-height: var(--console-control-height);
font-size: 14px;
}
.console-page .console-search-card .usage-logs-filter-form {
border: 0;
padding: 0;
background: transparent;
}
.console-page .usage-logs-filter-title-icon {
display: none;
}
.console-task-stats {
display: flex;
justify-content: space-between;
align-items: center;
gap: var(--console-space-2);
flex-wrap: wrap;
}
.console-page .usage-record-filter-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: var(--console-space-2);
width: 100%;
}
.console-page .usage-record-filter-wide {
grid-column: span 2;
}
.console-page
.usage-record-filter-grid
:is(.ant-picker, .ant-select, .ant-input-affix-wrapper) {
width: 100%;
}
.console-page .usage-record-filter-actions {
display: flex;
justify-content: flex-end;
flex-wrap: wrap;
gap: var(--console-space-1);
width: 100%;
}
.console-pagination {
display: flex;
justify-content: flex-end;
flex-wrap: wrap;
margin-top: var(--console-space-2);
gap: var(--console-space-1);
}
:is(.console-page, .console-overlay) .console-form .ant-form-item {
margin-bottom: var(--console-space-3);
}
:is(.console-page, .console-overlay) .console-form .ant-form-item-label {
padding-bottom: var(--console-space-1);
}
:is(.console-page, .console-overlay)
.console-form
.ant-form-item-label
> label {
color: var(--console-muted);
font-size: 14px;
line-height: 22px;
}
.console-search-card[hidden] {
display: none;
}
.console-page .console-search-card .ant-form,
.console-search-fields {
display: flex;
align-items: flex-end;
flex-wrap: wrap;
gap: var(--console-space-2);
min-width: 0;
width: 100%;
}
.console-search-card .ant-select {
width: 100%;
}
.console-search-fields > .console-search-field {
flex: 1 1 200px;
min-width: 0;
}
.console-search-card .ant-form > .flex {
width: 100%;
flex-wrap: wrap;
gap: var(--console-space-2);
}
.console-page .console-search-card .usage-logs-filter-content {
width: 100%;
}
.console-page .console-search-card .ant-form-item {
margin: 0;
min-width: 0;
}
.console-search-card .console-search-actions {
display: flex;
justify-content: flex-end;
flex: 0 0 auto;
flex-wrap: wrap;
gap: var(--console-space-1);
margin-inline-start: auto;
}
.console-page .console-table .ant-table-thead > tr > th {
background: var(--console-fill);
color: var(--console-muted);
font-weight: 500;
}
.console-page .console-table .ant-table-cell {
border-color: var(--console-border);
}
.console-page .console-table .ant-table-pagination {
margin: var(--console-space-2) 0 0;
}
.console-page .console-tabs > .ant-tabs-nav {
margin-bottom: var(--console-space-2);
}
.console-page .ant-tabs-tab .lucide,
.console-page .ant-btn .lucide {
width: 16px;
height: 16px;
}
:is(.console-page, .console-overlay) .console-create-action.ant-btn {
display: inline-flex;
align-items: center;
justify-content: center;
}
:is(.console-page, .console-overlay)
.console-create-action.ant-btn
.ant-btn-icon {
display: inline-flex;
align-items: center;
justify-content: center;
}
:is(.console-page, .console-overlay)
.console-create-action.ant-btn
.ant-btn-icon
svg {
display: block;
}
.console-page .ant-alert,
.console-overlay .console-alert {
align-items: flex-start;
padding: 12px 16px;
border-radius: var(--console-radius);
font-size: 14px;
line-height: 22px;
}
:is(.console-page, .console-overlay) .ant-alert-content {
min-width: 0;
overflow-wrap: anywhere;
}
:is(.console-page, .console-overlay) .ant-alert-message,
:is(.console-page, .console-overlay) .ant-alert-description {
color: var(--console-text);
font-size: 14px;
line-height: 22px;
}
:is(.console-page, .console-overlay) .ant-alert-message {
margin-bottom: 0;
font-weight: 500;
}
:is(.console-page, .console-overlay)
.ant-alert-message
+ .ant-alert-description {
margin-top: 4px;
}
:is(.console-page, .console-overlay) .ant-alert-icon {
margin: 3px 10px 0 0;
font-size: 16px;
}
:is(.console-page, .console-overlay) .ant-alert-action {
margin-inline-start: 16px;
}
.console-page .ant-alert + .ant-alert {
margin-top: 16px;
}
.console-page .console-table .ant-btn-link {
padding-inline: var(--console-space-1);
}
.console-page .console-table .ant-empty {
margin-block: 32px;
}
.console-overlay .ant-modal-title,
.console-overlay .ant-drawer-title {
font-size: 16px;
line-height: 24px;
font-weight: 600;
}
.console-overlay .ant-drawer-body {
padding: 24px;
scrollbar-gutter: stable;
}
.console-overlay .ant-drawer-content-wrapper {
max-width: 100vw;
}
.console-overlay .ant-modal-footer,
.console-overlay .ant-drawer-footer,
.console-dialog-actions {
display: flex;
justify-content: flex-end;
flex-wrap: wrap;
gap: 8px;
}
.console-overlay .ant-modal-footer > .ant-btn + .ant-btn {
margin-inline-start: 0;
}
.console-page--canvas .console-page-body {
height: max(480px, calc(100dvh - var(--console-header-offset, 72px) - 216px));
}
.console-page .settings-page {
overflow: visible;
}
.console-page .website-settings-page {
padding: 0;
min-height: 0;
}
.console-page :is(.console-personal, .console-recharge) {
min-height: 0;
padding: 0;
background: transparent;
}
.console-page .console-personal {
--ps-header-bg: var(--console-surface);
--ps-preview-bg: var(--console-fill);
--ps-card-shadow: none;
}
.console-page .console-recharge {
--rc-wallet-bg: var(--console-surface);
--rc-order-bg: var(--console-surface);
--rc-card-shadow: none;
}
.console-page :is(.ui-personal-inner, .ui-recharge-content) {
max-width: none;
margin: 0;
padding: 0;
}
.console-page .skill-platform-page,
.console-page .expert-platform-page {
min-height: 0;
padding: 0;
background: transparent;
}
.console-page .expert-platform-shell,
.console-page .skill-platform-metrics,
.console-page .skill-platform-toolbar,
.console-page .skill-platform-grid {
max-width: none;
margin-inline: 0;
}
.console-page .skill-platform-metrics,
.console-page .skill-platform-grid,
.console-page .expert-metrics {
gap: var(--console-gap);
}
.console-page .skill-platform-metrics article,
.console-page .expert-metric,
.console-page .expert-card {
border-radius: var(--console-radius);
background: var(--console-surface);
box-shadow: none;
}
.console-chat-frame {
width: 100%;
height: 100%;
min-height: 480px;
border: 0;
border-radius: var(--console-radius);
background: var(--console-surface);
}
.console-chat-loading {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: var(--console-space-1);
min-height: 480px;
}
@media (max-width: 768px) {
.console-page {
--console-space-3: 16px;
padding: calc(var(--console-header-offset, 56px) + 16px) 16px 24px;
}
.console-page .console-breadcrumb.ant-breadcrumb {
margin-bottom: 24px;
}
.console-page-actions {
width: 100%;
}
.console-search-fields > :not(button),
.console-search-card .ant-form > * {
max-width: 100%;
}
.console-search-card .console-search-actions {
width: 100%;
}
.console-pagination .ant-pagination {
display: flex;
flex-wrap: wrap;
gap: 8px 0;
}
.console-page .usage-record-filter-grid {
grid-template-columns: minmax(0, 1fr);
}
.console-page .usage-record-filter-wide {
grid-column: auto;
}
}
.console-overlay .console-detail-header .ant-drawer-header-title {
flex-direction: row-reverse;
}
.console-overlay .console-detail-header .ant-drawer-close {
margin-inline: 12px 0;
}
+150
View File
@@ -0,0 +1,150 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// Presentation metadata only. Route guards and feature visibility remain in App/SiderBar.
export const consolePages = [
{
key: 'analytics',
menuKey: 'detail',
title: '数据看板',
description: 'analytics',
},
{ key: 'monitor', title: '监控中心', description: 'monitor' },
{ key: 'channel', title: '渠道管理', description: 'channel' },
{
key: 'token',
menuKey: 'admin-token',
title: '密钥管理',
description: 'token',
},
{ key: 'models', title: '模型管理', description: 'models' },
{ key: 'user', title: '用户管理', description: 'user' },
{ key: 'redemption', title: '兑换码管理', description: 'redemption' },
{ key: 'topup', title: '钱包管理', description: 'topup' },
{ key: 'log', title: '使用日志', description: 'log' },
{ key: 'midjourney', title: '绘图日志', description: 'midjourney' },
{ key: 'task', title: '任务日志', description: 'task' },
{ key: 'organizations', title: '企业管理', description: 'organizations' },
{ key: 'order', title: '订单管理', description: 'order' },
{ key: 'invoice', title: '发票管理', description: 'invoice' },
{ key: 'subscription', title: '会员卡管理', description: 'subscription' },
{ key: 'setting', title: '系统设置', description: 'setting' },
{ key: 'website-setting', title: '官网设置', description: 'website-setting' },
{
key: 'demo-reservations',
title: '预约演示',
description: 'demo-reservations',
},
{ key: 'personal', title: '个人设置', description: 'personal' },
{ key: 'my-commission', title: '我的提成', description: 'my-commission' },
{ key: 'partner', title: '合作伙伴', description: 'partner' },
{
key: 'skill-platform',
title: '平台 Skill 中心',
description: 'skill-platform',
},
{
key: 'expert-platform',
title: '专家与模型能力',
description: 'expert-platform',
},
{
key: 'playground',
title: '在线调试',
description: 'playground',
canvas: true,
},
{
key: 'chat',
title: '聊天',
description: 'chat',
canvas: true,
dynamicChildTitle: '详情',
},
].map((page) => ({ ...page, path: `/console/${page.key}` }));
export function isNavigationPathActive(pathname, prefix) {
if (!prefix) return false;
if (prefix === '/') return pathname === '/';
const normalized = prefix.replace(/\/+$/, '');
return pathname === normalized || pathname.startsWith(`${normalized}/`);
}
const normalizePath = (pathname) =>
(pathname || '/console').split(/[?#]/)[0].replace(/\/+$/, '') || '/';
function segmentTitle(segment) {
const actions = { edit: '编辑', new: '新建', create: '新建', detail: '详情' };
if (actions[segment]) return actions[segment];
if (/^\d+$/.test(segment)) return '详情';
try {
return decodeURIComponent(segment).replace(/[-_]/g, ' ');
} catch {
return segment;
}
}
export function resolveConsolePage(pathname, pages = consolePages) {
const path = normalizePath(pathname);
const page = [...pages]
.sort((a, b) => b.path.length - a.path.length)
.find((item) => isNavigationPathActive(path, item.path));
const root = { path: '/console', title: '控制台' };
const matched = pages
.filter((item) => isNavigationPathActive(path, item.path))
.sort((a, b) => a.path.length - b.path.length);
const breadcrumbs = [
root,
...matched.map(({ path, title }) => ({ path, title })),
];
const basePath = page?.path || root.path;
const segments = path.slice(basePath.length).split('/').filter(Boolean);
let currentPath = basePath;
for (const [index, segment] of segments.entries()) {
currentPath += `/${segment}`;
breadcrumbs.push({
path: currentPath,
title:
index === 0 && page?.dynamicChildTitle
? page.dynamicChildTitle
: segmentTitle(segment),
});
}
return {
...(page || { key: 'fallback', description: 'fallback' }),
title: breadcrumbs.at(-1).title,
path,
breadcrumbs,
};
}
export const consoleMenuPaths = Object.fromEntries(
consolePages.flatMap((page) =>
[...new Set([page.menuKey || page.key, page.key])].map((key) => [
key,
page.path,
]),
),
);
export function getConsoleMenuKeys(pathname, paths = consoleMenuPaths) {
if (!pathname) return [];
const path = normalizePath(pathname);
return Object.keys(paths).filter((key) => paths[key] === path);
}
@@ -0,0 +1,32 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
export function toConsoleTableChange(pagination, filters, sorter, extra) {
const normalize = (value) => ({
...value,
dataIndex: value?.field,
sortOrder: value?.order,
});
return {
pagination,
filters,
sorter: Array.isArray(sorter) ? sorter.map(normalize) : normalize(sorter),
...extra,
};
}
+230
View File
@@ -0,0 +1,230 @@
.console-page .console-search-card .console-module-filter-form {
display: block;
}
.console-page .console-module-filter-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 16px;
width: 100%;
}
.console-module-field {
min-width: 0;
}
.console-page .console-module-filter-grid .ant-form-item-label > label,
.console-module-field > label {
color: var(--console-muted);
font-size: 13px;
}
.console-module-field > label {
display: block;
margin-bottom: 8px;
line-height: 22px;
}
.console-module-filter-grid .ant-input-number,
.console-module-filter-grid .ant-picker,
.console-module-filter-grid .ant-select,
.console-module-filter-grid .ant-input-affix-wrapper,
.console-module-filter-grid .ant-input {
width: 100%;
}
.console-module-filter-actions {
display: flex;
justify-content: flex-end;
flex-wrap: wrap;
gap: 8px;
margin-top: 16px;
width: 100%;
}
.console-module-row-actions {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.console-module-row-actions .ant-btn-link {
height: auto;
padding: 0 4px;
font-size: 13px;
}
.console-page:is(
[data-console-page='channel'],
[data-console-page='models'],
[data-console-page='user'],
[data-console-page='organizations'],
[data-console-page='order']
)
.console-table
.ant-table-thead
> tr
> th {
height: 46px;
padding-block: 0;
font-weight: 400;
}
.console-model-drawer .ant-drawer-title > .ant-space {
align-items: center;
}
.console-model-drawer .ant-drawer-title .ant-typography {
margin: 0;
}
.console-model-drawer .ant-drawer-title .ant-tag {
margin-inline-end: 0;
}
.console-model-section,
.console-channel-section {
display: flex;
align-items: center;
gap: 5px;
margin-bottom: 16px;
}
.console-model-section .ant-avatar,
.console-channel-section .ant-avatar {
flex-shrink: 0;
margin: 0;
}
.console-channel-sections > div + div {
margin-top: 10px;
}
.console-channel-sections > div > .ant-card {
margin-bottom: 0;
}
.console-channel-section .ant-avatar svg {
display: block;
width: 16px;
height: 16px;
}
.console-channel-footer .ant-btn {
display: inline-flex;
align-items: center;
justify-content: center;
}
.console-channel-drawer .ant-form-item-extra > .ant-space,
.console-channel-drawer .console-channel-key-actions,
.console-channel-drawer .console-channel-model-actions {
margin-top: 10px;
}
.console-channel-drawer .ant-divider-inner-text {
min-width: 0;
max-width: 100%;
white-space: normal;
overflow-wrap: anywhere;
}
.console-overlay .console-model-footer,
.console-overlay .console-channel-footer {
display: flex;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
gap: 8px;
}
@media (max-width: 1100px) {
.console-page .console-module-filter-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 768px) {
.console-page .console-module-filter-grid {
grid-template-columns: minmax(0, 1fr);
}
}
.console-model-drawer .prefill-management-header .ant-drawer-header-title {
flex-direction: row-reverse;
}
.console-model-drawer .prefill-management-header .ant-drawer-close {
margin-inline: 12px 0;
}
.console-model-drawer .console-model-editor-header .ant-drawer-header-title,
.console-channel-drawer
.console-channel-editor-header
.ant-drawer-header-title {
flex-direction: row-reverse;
}
.console-model-drawer .console-model-editor-header .ant-drawer-title,
.console-channel-drawer .console-channel-editor-header .ant-drawer-title {
text-align: start;
}
.console-model-drawer .console-model-editor-header .ant-drawer-close,
.console-channel-drawer .console-channel-editor-header .ant-drawer-close {
margin-inline: 12px 0;
}
.console-model-drawer .console-model-tag-presets {
margin-top: 10px;
}
:is(.console-model-endpoints, .console-channel-drawer) .json-editor-pairs {
padding-top: 5px;
}
:is(.console-model-endpoints, .console-channel-drawer) .json-editor-pair {
align-items: flex-start;
margin-top: 0;
margin-bottom: 5px;
}
:is(.console-model-endpoints, .console-channel-drawer)
.json-editor-pair
textarea.ant-input {
text-align: start;
font: inherit;
line-height: 1.5715;
}
:is(.console-model-endpoints, .console-channel-drawer) .json-editor-add {
margin-top: 5px;
}
:is(.console-model-endpoints, .console-channel-drawer) {
--json-editor-header-padding: 8px 16px;
--json-editor-note-margin: 8px 0 0;
}
:is(.console-model-endpoints, .console-channel-drawer)
.json-editor-header
> .json-editor-tabs.ant-tabs,
:is(.console-model-endpoints, .console-channel-drawer)
.json-editor-tabs
> .ant-tabs-nav {
margin: 0;
}
:is(.console-model-endpoints, .console-channel-drawer)
.json-editor-tabs
.ant-tabs-tab {
padding-block: 8px;
}
:is(.console-model-endpoints, .console-channel-drawer)
.json-editor-tabs
> .ant-tabs-content-holder,
:is(.console-model-endpoints, .console-channel-drawer)
.json-editor-bound-field {
display: none;
}
+58 -15
View File
@@ -17,17 +17,14 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { useState, useEffect, useCallback, useRef } from 'react'; import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Avatar, Tag, Spin, Empty, Button, Divider, theme } from 'antd';
import { import {
Avatar, X,
Tag, RefreshCw,
Spin, Headphones,
Empty, ChevronLeft,
Button, ChevronRight,
Tooltip, } from 'lucide-react';
Divider,
theme,
} from 'antd';
import { X, RefreshCw, Headphones } from 'lucide-react';
import { API } from '../../helpers'; import { API } from '../../helpers';
import { getServerURL } from '../../helpers/config'; import { getServerURL } from '../../helpers/config';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@@ -43,6 +40,7 @@ const CustomerServiceFloat = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const { token } = theme.useToken(); const { token } = theme.useToken();
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const [isCollapsed, setIsCollapsed] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [currentAgent, setCurrentAgent] = useState(null); const [currentAgent, setCurrentAgent] = useState(null);
const [agentList, setAgentList] = useState([]); const [agentList, setAgentList] = useState([]);
@@ -78,8 +76,9 @@ const CustomerServiceFloat = () => {
API.post(path).catch(() => {}); API.post(path).catch(() => {});
}, []); }, []);
// 打开客服面板;不再读取或提供边缘收起状态。 // 打开面板时恢复完整浮钮,确保关闭后的焦点可以回到触发器。
const handleExpand = () => { const handleExpand = () => {
setIsCollapsed(false);
setIsOpen(true); setIsOpen(true);
}; };
@@ -104,6 +103,7 @@ const CustomerServiceFloat = () => {
if (!config.enabled) return undefined; if (!config.enabled) return undefined;
const onOpenRequest = (event) => { const onOpenRequest = (event) => {
event.preventDefault(); event.preventDefault();
setIsCollapsed(false);
setIsOpen(true); setIsOpen(true);
}; };
window.addEventListener(CUSTOMER_SERVICE_OPEN_EVENT, onOpenRequest); window.addEventListener(CUSTOMER_SERVICE_OPEN_EVENT, onOpenRequest);
@@ -252,7 +252,7 @@ const CustomerServiceFloat = () => {
return ( return (
<div <div
className='customer-service-container' className={`customer-service-container${isCollapsed ? ' customer-service-container-collapsed' : ''}`}
ref={containerRef} ref={containerRef}
style={{ style={{
'--cs-surface': token.colorBgContainer, '--cs-surface': token.colorBgContainer,
@@ -262,6 +262,9 @@ const CustomerServiceFloat = () => {
'--cs-fill': token.colorFillQuaternary, '--cs-fill': token.colorFillQuaternary,
'--cs-hover': token.colorFillTertiary, '--cs-hover': token.colorFillTertiary,
'--cs-primary': token.colorPrimary, '--cs-primary': token.colorPrimary,
'--cs-primary-hover': token.colorPrimaryHover,
'--cs-primary-active': token.colorPrimaryActive,
'--cs-on-primary': token.colorTextLightSolid,
'--cs-primary-bg': token.colorPrimaryBg, '--cs-primary-bg': token.colorPrimaryBg,
'--cs-primary-border': token.colorPrimaryBorder, '--cs-primary-border': token.colorPrimaryBorder,
'--cs-primary-text': token.colorPrimaryText, '--cs-primary-text': token.colorPrimaryText,
@@ -272,14 +275,54 @@ const CustomerServiceFloat = () => {
{isOpen && ( {isOpen && (
<div className='cs-backdrop' onClick={handleClose} aria-hidden='true' /> <div className='cs-backdrop' onClick={handleClose} aria-hidden='true' />
)} )}
<div className='cs-float-wrapper'> <div
<Tooltip title={isOpen ? t('关闭客服') : t('联系客服')}> className={`cs-float-wrapper${isCollapsed ? ' cs-float-wrapper-collapsed' : ''}`}
>
{!isOpen &&
(isCollapsed ? (
<div className='cs-float-tab'>
<Button
className='cs-float-tab-action'
type='text'
title={t('联系客服')}
aria-label={t('联系客服')}
onClick={handleExpand}
icon={<Headphones size={16} strokeWidth={2} />}
/>
<Button
className='cs-float-tab-action'
type='text'
title={t('展开')}
aria-label={t('展开')}
aria-expanded={false}
onClick={() => setIsCollapsed(false)}
icon={<ChevronLeft size={16} strokeWidth={2} />}
/>
</div>
) : (
<Button
className='cs-float-toggle'
type='default'
title={t('收起')}
aria-label={t('收起')}
aria-expanded={true}
onClick={() => setIsCollapsed(true)}
>
<ChevronRight size={16} strokeWidth={2} aria-hidden='true' />
</Button>
))}
<div
className='cs-float-main'
inert={isCollapsed ? '' : undefined}
aria-hidden={isCollapsed}
>
<Button <Button
type='primary' type='primary'
shape='circle' shape='circle'
className='cs-float-button' className='cs-float-button'
onClick={isOpen ? handleClose : handleExpand} onClick={isOpen ? handleClose : handleExpand}
ref={triggerRef} ref={triggerRef}
title={isOpen ? t('关闭客服') : t('联系客服')}
aria-label={isOpen ? t('关闭客服') : t('联系客服')} aria-label={isOpen ? t('关闭客服') : t('联系客服')}
icon={ icon={
isOpen ? ( isOpen ? (
@@ -289,7 +332,7 @@ const CustomerServiceFloat = () => {
) )
} }
/> />
</Tooltip> </div>
</div> </div>
<div <div
className={`cs-panel ${isOpen ? 'cs-panel-open' : ''}`} className={`cs-panel ${isOpen ? 'cs-panel-open' : ''}`}
+166 -12
View File
@@ -1,19 +1,161 @@
.customer-service-container { .customer-service-container {
--cs-float-right: max(20px, env(safe-area-inset-right, 0px));
--cs-float-bottom: 32px;
position: fixed; position: fixed;
right: 24px; right: var(--cs-float-right);
bottom: 24px; bottom: var(--cs-float-bottom);
z-index: 1000; z-index: 1000;
color: var(--cs-text); color: var(--cs-text);
} }
.customer-service-container.customer-service-container-collapsed {
right: env(safe-area-inset-right, 0px);
}
.cs-float-wrapper { .cs-float-wrapper {
position: relative; position: relative;
display: flex; display: flex;
justify-content: flex-end; justify-content: flex-end;
align-items: center;
width: 46px;
height: 46px;
}
.cs-float-main {
width: 46px;
opacity: 1;
transform: scale(1);
transform-origin: right center;
transition:
width 220ms ease,
opacity 160ms ease,
transform 220ms ease;
}
.cs-float-toggle.ant-btn {
position: absolute;
right: 13px;
bottom: -24px;
z-index: 1;
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
min-width: 20px;
height: 20px;
padding: 0;
border-radius: 7px;
border: 0;
color: var(--cs-on-primary);
background: transparent;
box-shadow: none;
transition:
height 220ms ease,
width 220ms ease,
border-radius 220ms ease,
background 160ms ease,
transform 160ms ease,
opacity 160ms ease;
}
.cs-float-toggle.ant-btn:not(:disabled):hover,
.cs-float-toggle.ant-btn:not(:disabled):active {
color: var(--cs-on-primary);
background: transparent;
}
.cs-float-wrapper:not(.cs-float-wrapper-collapsed) .cs-float-toggle.ant-btn {
color: var(--cs-on-primary);
background: var(--cs-primary);
opacity: 0;
pointer-events: none;
}
.cs-float-wrapper:not(.cs-float-wrapper-collapsed):is(:hover, :focus-within)
.cs-float-toggle.ant-btn {
opacity: 1;
pointer-events: auto;
}
/* Extend the hit area across the gap without connecting the visible shapes. */
.cs-float-wrapper:not(.cs-float-wrapper-collapsed) .cs-float-toggle::before {
content: '';
position: absolute;
inset: -5px 0 -1px;
}
.cs-float-wrapper:not(.cs-float-wrapper-collapsed)
.cs-float-toggle.ant-btn:is(:hover, :focus-visible) {
color: var(--cs-on-primary);
background: var(--cs-primary-active);
transform: translateY(-1px);
}
.cs-float-wrapper:not(.cs-float-wrapper-collapsed)
.cs-float-toggle.ant-btn:active {
background: var(--cs-primary-active);
transform: translateY(0);
}
.cs-float-wrapper-collapsed {
width: 23px;
}
.cs-float-wrapper-collapsed .cs-float-main {
width: 0;
opacity: 0;
transform: scale(0.65);
pointer-events: none;
visibility: hidden;
overflow: hidden;
}
.cs-float-tab {
position: absolute;
right: 0;
bottom: 0;
display: grid;
grid-template-rows: repeat(2, 1fr);
width: 23px;
height: 48px;
overflow: hidden;
border-radius: 10px 0 0 10px;
background: var(--cs-primary);
}
.cs-float-tab .cs-float-tab-action.ant-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 23px;
min-width: 23px;
height: 24px;
padding: 0;
border: 0;
border-radius: 0;
color: var(--cs-on-primary);
background: transparent;
box-shadow: none;
}
.cs-float-tab .cs-float-tab-action.ant-btn:not(:disabled):hover,
.cs-float-tab .cs-float-tab-action.ant-btn:not(:disabled):active {
color: var(--cs-on-primary);
background: var(--cs-primary-hover);
}
.cs-float-tab .cs-float-tab-action.ant-btn:focus-visible {
outline: 2px solid var(--cs-on-primary);
outline-offset: -2px;
}
.cs-float-wrapper:not(.cs-float-wrapper-collapsed)
.cs-float-toggle:focus-visible {
outline-offset: -3px;
outline-color: var(--cs-primary);
}
.cs-float-toggle.ant-btn:focus-visible {
outline: 2px solid var(--cs-primary);
outline-offset: 3px;
}
@media (prefers-reduced-motion: reduce) {
.cs-float-main,
.cs-float-toggle.ant-btn {
transition: none;
}
.cs-float-wrapper:not(.cs-float-wrapper-collapsed)
.cs-float-toggle.ant-btn:is(:hover, :focus-visible) {
transform: none;
}
} }
.cs-float-button.ant-btn { .cs-float-button.ant-btn {
width: 46px; width: 46px;
height: 46px; height: 46px;
box-shadow: none; box-shadow: none;
transition: background 160ms ease;
} }
.customer-service-container .ant-btn-icon { .customer-service-container .ant-btn-icon {
display: inline-flex; display: inline-flex;
@@ -25,8 +167,19 @@
bottom: 60px; bottom: 60px;
display: none; display: none;
flex-direction: column; flex-direction: column;
width: 360px; width: min(
height: min(558px, calc(100dvh - 112px)); 360px,
calc(
100vw - var(--cs-float-right) - max(16px, env(safe-area-inset-left, 0px))
)
);
height: min(
558px,
calc(
100dvh - var(--cs-float-bottom) - 60px -
max(16px, env(safe-area-inset-top, 0px))
)
);
overflow: hidden; overflow: hidden;
background: var(--cs-surface); background: var(--cs-surface);
border: 1px solid var(--cs-border); border: 1px solid var(--cs-border);
@@ -173,12 +326,10 @@
} }
@media (max-width: 767.98px) { @media (max-width: 767.98px) {
.customer-service-container { .customer-service-container {
right: 16px; --cs-float-right: max(16px, env(safe-area-inset-right, 0px));
bottom: max(16px, env(safe-area-inset-bottom)); --cs-float-bottom: calc(32px + env(safe-area-inset-bottom, 0px));
} }
.cs-panel { .cs-panel {
width: min(360px, calc(100vw - 32px));
height: min(558px, calc(100dvh - 100px));
z-index: 1; z-index: 1;
} }
.cs-float-wrapper { .cs-float-wrapper {
@@ -191,9 +342,12 @@
background: var(--cs-mask); background: var(--cs-mask);
} }
body:has(.uc-mobile-nav) .customer-service-container { body:has(.uc-mobile-nav) .customer-service-container {
bottom: calc(72px + env(safe-area-inset-bottom)); --cs-float-bottom: calc(88px + env(safe-area-inset-bottom, 0px));
} }
body:has(.uc-mobile-nav) .cs-panel { }
height: min(558px, calc(100dvh - 164px)); @media (hover: none) {
.cs-float-wrapper:not(.cs-float-wrapper-collapsed) .cs-float-toggle.ant-btn {
opacity: 1;
pointer-events: auto;
} }
} }
+17 -12
View File
@@ -58,6 +58,8 @@ const CustomerServiceFloat = lazy(() => import('../customer-service'));
// 跑马灯公告组件 // 跑马灯公告组件
import Marquee from './Marquee'; import Marquee from './Marquee';
import { useMarquee } from '../../hooks/common/useMarquee'; import { useMarquee } from '../../hooks/common/useMarquee';
import ConsolePageContainer from '../console/ConsolePageContainer';
import { isNavigationPathActive } from '../console/consoleRoutes';
const { Sider, Content, Header } = Layout; const { Sider, Content, Header } = Layout;
@@ -92,13 +94,7 @@ const PageLayout = () => {
const [showGiftModal, setShowGiftModal] = useState(false); const [showGiftModal, setShowGiftModal] = useState(false);
const [giftQuota, setGiftQuota] = useState(0); const [giftQuota, setGiftQuota] = useState(0);
const shouldInnerPadding = const isConsoleRoute = isNavigationPathActive(location.pathname, '/console');
location.pathname.includes('/console') &&
!location.pathname.startsWith('/console/chat') &&
location.pathname !== '/console/playground' &&
location.pathname !== '/console/website-setting';
const isConsoleRoute = location.pathname.startsWith('/console');
const showSider = isConsoleRoute && (!isMobile || drawerOpen); const showSider = isConsoleRoute && (!isMobile || drawerOpen);
const isHomePage = location.pathname === '/'; const isHomePage = location.pathname === '/';
@@ -394,6 +390,11 @@ const PageLayout = () => {
)} )}
{showSider && ( {showSider && (
<Sider <Sider
width={
siderForceExpanded
? 'var(--sidebar-width)'
: 'var(--sidebar-current-width)'
}
style={{ style={{
position: 'fixed', position: 'fixed',
left: 0, left: 0,
@@ -439,15 +440,12 @@ const PageLayout = () => {
style={{ style={{
flex: '1 0 auto', flex: '1 0 auto',
WebkitOverflowScrolling: 'touch', WebkitOverflowScrolling: 'touch',
padding: shouldInnerPadding padding: 0,
? isMobile
? '5px'
: '24px 24px 0 24px'
: '0',
position: 'relative', position: 'relative',
// 认证页等 min-height:100vh 的独立屏用它抵扣上方跑马灯占位的高度, // 认证页等 min-height:100vh 的独立屏用它抵扣上方跑马灯占位的高度,
// 保证「占位 + 容器」总高恰为 100vh(无占位时回退 0px,不影响其他页面) // 保证「占位 + 容器」总高恰为 100vh(无占位时回退 0px,不影响其他页面)
'--content-top-offset': `${marqueeHeight}px`, '--content-top-offset': `${marqueeHeight}px`,
'--console-header-offset': `${totalHeaderHeight}px`,
}} }}
> >
{/* 跑马灯占位:当跑马灯存在时,为内容区域顶部增加等高间距,防止被固定头部遮挡 */} {/* 跑马灯占位:当跑马灯存在时,为内容区域顶部增加等高间距,防止被固定头部遮挡 */}
@@ -458,10 +456,17 @@ const PageLayout = () => {
{marqueeHeight > 0 && {marqueeHeight > 0 &&
!isExperienceCenter && !isExperienceCenter &&
!isUserCenter && !isUserCenter &&
!isConsoleRoute &&
!isOrgPage && ( !isOrgPage && (
<div style={{ height: marqueeHeight, flexShrink: 0 }} /> <div style={{ height: marqueeHeight, flexShrink: 0 }} />
)} )}
{isConsoleRoute ? (
<ConsolePageContainer>
<App /> <App />
</ConsolePageContainer>
) : (
<App />
)}
</Content> </Content>
</Layout> </Layout>
</Layout> </Layout>
+82 -200
View File
@@ -17,11 +17,13 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { consoleMenuPaths, getConsoleMenuKeys } from '../console/consoleRoutes';
import React, { useContext, useEffect, useMemo, useState } from 'react'; import React, { useContext, useEffect, useMemo, useState } from 'react';
import { Link, useLocation } from 'react-router-dom'; import { Link, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { getLucideIcon } from '../../helpers/render'; import { getLucideIcon } from '../../helpers/render';
import { ChevronDown, ChevronLeft } from 'lucide-react'; import { ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react';
import '../../styles/center-layout.css';
import { useSidebarCollapsed } from '../../hooks/common/useSidebarCollapsed'; import { useSidebarCollapsed } from '../../hooks/common/useSidebarCollapsed';
import { useSidebar } from '../../hooks/common/useSidebar'; import { useSidebar } from '../../hooks/common/useSidebar';
import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime'; import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime';
@@ -35,37 +37,11 @@ import {
import SkeletonWrapper from './components/SkeletonWrapper'; import SkeletonWrapper from './components/SkeletonWrapper';
import { CLOUD_BRAIN_UI_ENABLED } from '../../config/cloudBrainUi'; import { CLOUD_BRAIN_UI_ENABLED } from '../../config/cloudBrainUi';
import { Nav, Button } from '@/components/ui';
const routerMap = { const routerMap = {
home: '/', home: '/',
channel: '/console/channel', ...consoleMenuPaths,
'admin-token': '/console/token',
redemption: '/console/redemption',
topup: '/console/topup',
user: '/console/user',
log: '/console/log',
midjourney: '/console/midjourney',
setting: '/console/setting',
'website-setting': '/console/website-setting',
'demo-reservations': '/console/demo-reservations',
about: '/about', about: '/about',
detail: '/console',
pricing: '/market', pricing: '/market',
task: '/console/task',
models: '/console/models',
playground: '/console/playground',
personal: '/console/personal',
monitor: '/console/monitor',
analytics: '/console/analytics',
'my-commission': '/console/my-commission',
partner: '/console/partner',
organizations: '/console/organizations',
'skill-platform': '/console/skill-platform',
'expert-platform': '/console/expert-platform',
order: '/console/order',
invoice: '/console/invoice',
subscription: '/console/subscription',
}; };
// forceExpanded:手机端抽屉态。抽屉本来就是临时全宽浮层,折叠成 60px 图标条毫无意义, // forceExpanded:手机端抽屉态。抽屉本来就是临时全宽浮层,折叠成 60px 图标条毫无意义,
@@ -183,7 +159,6 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
filteredItems.push({ filteredItems.push({
text: t('我的提成'), text: t('我的提成'),
itemKey: 'my-commission', itemKey: 'my-commission',
to: '/console/my-commission',
}); });
// 合作伙伴:受平台总开关控制(参数设置页可配),开放后对全部登录用户可见 // 合作伙伴:受平台总开关控制(参数设置页可配),开放后对全部登录用户可见
@@ -191,7 +166,6 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
filteredItems.push({ filteredItems.push({
text: t('合作伙伴'), text: t('合作伙伴'),
itemKey: 'partner', itemKey: 'partner',
to: '/console/partner',
}); });
} }
@@ -207,7 +181,6 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
{ {
text: t('运营看板'), text: t('运营看板'),
itemKey: 'analytics', itemKey: 'analytics',
to: '/console/analytics',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
@@ -219,7 +192,6 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
{ {
text: t('模型管理'), text: t('模型管理'),
itemKey: 'models', itemKey: 'models',
to: '/console/models',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
@@ -237,43 +209,36 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
{ {
text: t('会员卡管理'), text: t('会员卡管理'),
itemKey: 'subscription', itemKey: 'subscription',
to: '/console/subscription',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('密钥管理'), text: t('密钥管理'),
itemKey: 'admin-token', itemKey: 'admin-token',
to: '/console/token',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('企业管理'), text: t('企业管理'),
itemKey: 'organizations', itemKey: 'organizations',
to: '/console/organizations',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('平台 Skill 中心'), text: t('平台 Skill 中心'),
itemKey: 'skill-platform', itemKey: 'skill-platform',
to: '/console/skill-platform',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('平台专家中心'), text: t('平台专家中心'),
itemKey: 'expert-platform', itemKey: 'expert-platform',
to: '/console/expert-platform',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('订单管理'), text: t('订单管理'),
itemKey: 'order', itemKey: 'order',
to: '/console/order',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('发票管理'), text: t('发票管理'),
itemKey: 'invoice', itemKey: 'invoice',
to: '/console/invoice',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
@@ -415,23 +380,21 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
// 根据当前路径设置选中的菜单项 // 根据当前路径设置选中的菜单项
useEffect(() => { useEffect(() => {
const currentPath = location.pathname; const currentPath = location.pathname;
let matchingKey = Object.keys(routerMapState).find( let matchingKeys = getConsoleMenuKeys(currentPath, routerMapState);
(key) => routerMapState[key] === currentPath,
);
// 处理聊天路由 // 处理聊天路由
if (!matchingKey && currentPath.startsWith('/console/chat/')) { if (!matchingKeys.length && currentPath.startsWith('/console/chat/')) {
const chatIndex = currentPath.split('/').pop(); const chatIndex = currentPath.split('/').pop();
if (!isNaN(chatIndex)) { if (!isNaN(chatIndex)) {
matchingKey = 'chat' + chatIndex; matchingKeys = ['chat' + chatIndex];
} else { } else {
matchingKey = 'chat'; matchingKeys = ['chat'];
} }
} }
// 如果找到匹配的键,更新选中的键 // 如果找到匹配的键,更新选中的键
if (matchingKey) { if (matchingKeys.length) {
setSelectedKeys([matchingKey]); setSelectedKeys(matchingKeys);
} }
}, [location.pathname, routerMapState]); }, [location.pathname, routerMapState]);
@@ -446,20 +409,22 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
} }
}, [persistedCollapsed, forceExpanded]); }, [persistedCollapsed, forceExpanded]);
// 选中高亮颜色(统一) const renderMenuIcon = (key) =>
const SELECTED_COLOR = 'var(--ui-color-primary)'; React.cloneElement(getLucideIcon(key), {
size: 16,
strokeWidth: 1.5,
color: 'currentColor',
className: undefined,
'aria-hidden': true,
});
const renderGroup = (key, label, items) => { const renderGroup = (key, label, items) => (
const folded = foldedGroups.includes(key); <div key={key} className='ui-org-nav-group'>
return ( {!collapsed && (
<Nav.Group
itemKey={key}
folded={folded}
text={
<button <button
type='button' type='button'
className='sidebar-group-toggle' className='ui-org-group-toggle'
aria-expanded={!folded} aria-expanded={!foldedGroups.includes(key)}
onClick={() => onClick={() =>
setFoldedGroups((previous) => setFoldedGroups((previous) =>
previous.includes(key) previous.includes(key)
@@ -468,99 +433,79 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
) )
} }
> >
<span className='truncate'>{label}</span> <span>{label}</span>
<ChevronDown size={13} className={folded ? '-rotate-90' : ''} /> <ChevronDown
size={13}
className={foldedGroups.includes(key) ? 'is-folded' : ''}
aria-hidden='true'
/>
</button> </button>
} )}
<div
className='ui-org-group-items'
hidden={!collapsed && foldedGroups.includes(key)}
> >
{items} {items}
</Nav.Group> </div>
</div>
); );
};
// 渲染自定义菜单项
const renderNavItem = (item) => { const renderNavItem = (item) => {
// 跳过隐藏的项目
if (item.className === 'tableHiddle') return null; if (item.className === 'tableHiddle') return null;
const active = selectedKeys.includes(item.itemKey);
const isSelected = selectedKeys.includes(item.itemKey);
const textColor = isSelected ? SELECTED_COLOR : 'inherit';
return ( return (
<Nav.Item <Link
key={item.itemKey} key={item.itemKey}
itemKey={item.itemKey} to={routerMapState[item.itemKey] || routerMap[item.itemKey] || '#'}
text={ onClick={onNavigate}
<span className='ui-center-menu-item'
className='truncate font-medium text-sm' data-active={active || undefined}
style={{ color: textColor }} aria-current={active ? 'page' : undefined}
title={collapsed ? item.text : undefined}
> >
{item.text} {renderMenuIcon(item.itemKey)}
</span> {!collapsed && (
} <span className='ui-center-menu-label'>{item.text}</span>
icon={ )}
<div className='sidebar-icon-container flex-shrink-0'> </Link>
{getLucideIcon(item.itemKey, isSelected)}
</div>
}
className={item.className}
/>
); );
}; };
// 渲染子菜单项
const renderSubItem = (item) => { const renderSubItem = (item) => {
if (item.items && item.items.length > 0) { if (!item.items?.length) return renderNavItem(item);
const isSelected = selectedKeys.includes(item.itemKey); const open = openedKeys.includes(item.itemKey);
const textColor = isSelected ? SELECTED_COLOR : 'inherit';
return ( return (
<Nav.Sub <div key={item.itemKey}>
key={item.itemKey} <button
itemKey={item.itemKey} type='button'
text={ className='ui-center-menu-item ui-console-submenu-toggle'
<span title={collapsed ? item.text : undefined}
className='truncate font-medium text-sm' aria-label={item.text}
style={{ color: textColor }} aria-expanded={open}
> onClick={() =>
{item.text} setOpenedKeys((previous) =>
</span> previous.includes(item.itemKey)
? previous.filter((key) => key !== item.itemKey)
: [...previous, item.itemKey],
)
} }
icon={ >
<div className='sidebar-icon-container flex-shrink-0'> {renderMenuIcon(item.itemKey)}
{getLucideIcon(item.itemKey, isSelected)} {!collapsed && (
<span className='ui-center-menu-label'>{item.text}</span>
)}
</button>
<div className='ui-org-group-items' hidden={!open}>
{item.items.map(renderNavItem)}
</div>
</div> </div>
}
>
{item.items.map((subItem) => {
const isSubSelected = selectedKeys.includes(subItem.itemKey);
const subTextColor = isSubSelected ? SELECTED_COLOR : 'inherit';
return (
<Nav.Item
key={subItem.itemKey}
itemKey={subItem.itemKey}
text={
<span
className='truncate font-medium text-sm'
style={{ color: subTextColor }}
>
{subItem.text}
</span>
}
/>
); );
})}
</Nav.Sub>
);
} else {
return renderNavItem(item);
}
}; };
return ( return (
<div <div
className='sidebar-container' className='ui-console-sidebar ui-center-sidebar'
data-collapsed={collapsed}
style={{ style={{
width: forceExpanded width: forceExpanded
? 'var(--sidebar-width)' ? 'var(--sidebar-width)'
@@ -575,45 +520,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
collapsed={collapsed} collapsed={collapsed}
showAdmin={isAdmin()} showAdmin={isAdmin()}
> >
<Nav <nav className='ui-center-sidebar-nav'>
className='sidebar-nav'
defaultIsCollapsed={collapsed}
isCollapsed={collapsed}
onCollapseChange={toggleCollapsed}
selectedKeys={selectedKeys}
itemStyle='sidebar-nav-item'
hoverStyle='sidebar-nav-item:hover'
selectedStyle='sidebar-nav-item-selected'
renderWrapper={({ itemElement, props }) => {
const to =
routerMapState[props.itemKey] || routerMap[props.itemKey];
// 如果没有路由,直接返回元素
if (!to) return itemElement;
return (
<Link
style={{ textDecoration: 'none' }}
to={to}
onClick={onNavigate}
>
{itemElement}
</Link>
);
}}
onSelect={(key) => {
// 如果点击的是已经展开的子菜单的父项,则收起子菜单
if (openedKeys.includes(key.itemKey)) {
setOpenedKeys(openedKeys.filter((k) => k !== key.itemKey));
}
setSelectedKeys([key.itemKey]);
}}
openKeys={openedKeys}
onOpenChange={(data) => {
setOpenedKeys(data.openKeys);
}}
>
{/* 聊天区域 */} {/* 聊天区域 */}
{hasSectionVisibleModules('chat') && {hasSectionVisibleModules('chat') &&
renderGroup( renderGroup(
@@ -645,45 +552,20 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
t('管理员'), t('管理员'),
adminItems.map(renderNavItem), adminItems.map(renderNavItem),
)} )}
</Nav> </nav>
</SkeletonWrapper> </SkeletonWrapper>
{/* 底部折叠按钮 —— 抽屉态不提供:收起后抽屉会变成 60px 窄条,等于自废 */} {/* 底部折叠按钮 —— 抽屉态不提供:收起后抽屉会变成 60px 窄条,等于自废 */}
{!forceExpanded && ( {!forceExpanded && (
<div className='sidebar-collapse-button'> <button
<SkeletonWrapper
loading={showSkeleton}
type='button' type='button'
width={collapsed ? 36 : 156} className='ui-center-sidebar-collapse'
height={24}
className='w-full'
>
<Button
theme='outline'
type='tertiary'
size='small'
icon={
<ChevronLeft
size={16}
strokeWidth={2.5}
color='var(--ui-color-text-2)'
style={{
transform: collapsed ? 'rotate(180deg)' : 'rotate(0deg)',
}}
/>
}
onClick={toggleCollapsed} onClick={toggleCollapsed}
aria-label={collapsed ? t('展开侧边栏') : t('收起侧边栏')} aria-label={collapsed ? t('展开导航') : t('收起导航')}
style={
collapsed
? { width: 36, height: 24, padding: 0 }
: { padding: '4px 12px', width: '100%' }
}
> >
{!collapsed ? t('收起侧边栏') : null} {collapsed ? <ChevronRight size={16} /> : <ChevronLeft size={16} />}
</Button> {!collapsed && <span>{t('收起导航')}</span>}
</SkeletonWrapper> </button>
</div>
)} )}
</div> </div>
); );
@@ -21,6 +21,7 @@ import React, { useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom'; import { useLocation, useNavigate } from 'react-router-dom';
import { Button, Dropdown } from '@/components/ui'; import { Button, Dropdown } from '@/components/ui';
import { Compass, ExternalLink } from 'lucide-react'; import { Compass, ExternalLink } from 'lucide-react';
import { isNavigationPathActive } from '../../console/consoleRoutes';
/** /**
* 移动端主导航入口。 * 移动端主导航入口。
@@ -41,14 +42,8 @@ const MobileNavMenu = ({ mainNavLinks, userState, t }) => {
} }
// 与 Navigation 一致:按完整路径段匹配,避免 /market 命中 /market-detail // 与 Navigation 一致:按完整路径段匹配,避免 /market 命中 /market-detail
const isPathActive = (matchPath) => { const isPathActive = (matchPath) =>
if (!matchPath) return false; isNavigationPathActive(location.pathname, matchPath);
if (matchPath === '/') return location.pathname === '/';
return (
location.pathname === matchPath ||
location.pathname.startsWith(`${matchPath}/`)
);
};
// 与 Navigation 一致:未登录时需要鉴权的入口统一引导到企业登录 // 与 Navigation 一致:未登录时需要鉴权的入口统一引导到企业登录
const resolveTarget = (link) => { const resolveTarget = (link) => {
@@ -122,7 +117,10 @@ const MobileNavMenu = ({ mainNavLinks, userState, t }) => {
: '!text-gray-700 dark:!text-neutral-200' : '!text-gray-700 dark:!text-neutral-200'
}`} }`}
> >
<span className='flex items-center gap-1.5'> <span
className='flex items-center gap-1.5'
aria-current={item.active ? 'page' : undefined}
>
{item.text} {item.text}
{item.externalLink && ( {item.externalLink && (
<ExternalLink size={12} className='opacity-50' /> <ExternalLink size={12} className='opacity-50' />
+11 -10
View File
@@ -22,6 +22,7 @@ import { Link, useLocation } from 'react-router-dom';
import { Dropdown } from '@/components/ui'; import { Dropdown } from '@/components/ui';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import SkeletonWrapper from '../components/SkeletonWrapper'; import SkeletonWrapper from '../components/SkeletonWrapper';
import { isNavigationPathActive } from '../../console/consoleRoutes';
const Navigation = ({ mainNavLinks, isMobile, isLoading, userState }) => { const Navigation = ({ mainNavLinks, isMobile, isLoading, userState }) => {
const location = useLocation(); const location = useLocation();
@@ -36,13 +37,8 @@ const Navigation = ({ mainNavLinks, isMobile, isLoading, userState }) => {
const spacingClasses = isMobile ? 'px-2 py-1 text-sm' : 'px-4 py-2'; const spacingClasses = isMobile ? 'px-2 py-1 text-sm' : 'px-4 py-2';
// Match on full path segments so /market doesn't light up on /market-detail // Match on full path segments so /market doesn't light up on /market-detail
const isPathActive = (matchPath) => { const isPathActive = (matchPath) =>
if (matchPath === '/') return location.pathname === '/'; isNavigationPathActive(location.pathname, matchPath);
return (
location.pathname === matchPath ||
location.pathname.startsWith(`${matchPath}/`)
);
};
return mainNavLinks.map((link) => { return mainNavLinks.map((link) => {
const linkContent = <span className='relative z-10'>{link.text}</span>; const linkContent = <span className='relative z-10'>{link.text}</span>;
@@ -58,7 +54,9 @@ const Navigation = ({ mainNavLinks, isMobile, isLoading, userState }) => {
// Check if active // Check if active
let isActive = false; let isActive = false;
if (link.items && link.items.length > 0) { if (link.activePrefix) {
isActive = isPathActive(link.activePrefix);
} else if (link.items && link.items.length > 0) {
isActive = link.items.some((subItem) => isPathActive(subItem.to)); isActive = link.items.some((subItem) => isPathActive(subItem.to));
} else if (!link.isExternal && targetPath) { } else if (!link.isExternal && targetPath) {
isActive = isPathActive(link.activePrefix || targetPath); isActive = isPathActive(link.activePrefix || targetPath);
@@ -88,7 +86,10 @@ const Navigation = ({ mainNavLinks, isMobile, isLoading, userState }) => {
</Dropdown.Menu> </Dropdown.Menu>
} }
> >
<div className={`${finalClasses} cursor-pointer`}> <div
className={`${finalClasses} cursor-pointer`}
aria-current={isActive ? 'page' : undefined}
>
{linkContent} {linkContent}
{/* Dropdown arrow */} {/* Dropdown arrow */}
<svg <svg
@@ -156,7 +157,7 @@ const Navigation = ({ mainNavLinks, isMobile, isLoading, userState }) => {
className='ui-header-navigation flex flex-1 items-center gap-1 lg:gap-2 mx-1 sm:mx-3 md:mx-6 overflow-x-auto whitespace-nowrap scrollbar-hide min-w-0' className='ui-header-navigation flex flex-1 items-center gap-1 lg:gap-2 mx-1 sm:mx-3 md:mx-6 overflow-x-auto whitespace-nowrap scrollbar-hide min-w-0'
> >
<SkeletonWrapper <SkeletonWrapper
loading={isLoading} loading={isLoading && mainNavLinks.length === 0}
type='navigation' type='navigation'
count={4} count={4}
width={60} width={60}
+3 -1
View File
@@ -147,7 +147,9 @@ const HeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
/> />
{/* 移动端:主导航收进下拉菜单,避免与右侧操作区互相挤压 */} {/* 移动端:主导航收进下拉菜单,避免与右侧操作区互相挤压 */}
{!isAuthPage && isMobile && !isLoading && ( {!isAuthPage &&
isMobile &&
(!isLoading || mainNavLinks.length > 0) && (
<MobileNavMenu <MobileNavMenu
mainNavLinks={mainNavLinks} mainNavLinks={mainNavLinks}
userState={userState} userState={userState}
+3 -4
View File
@@ -187,13 +187,12 @@ const CodeViewer = ({ content, title, language = 'json' }) => {
: content; : content;
const success = await copy(textToCopy); const success = await copy(textToCopy);
setCopied(true);
Toast.success(t('已复制到剪贴板'));
setTimeout(() => setCopied(false), 2000);
if (!success) { if (!success) {
throw new Error('Copy operation failed'); throw new Error('Copy operation failed');
} }
setCopied(true);
Toast.success(t('已复制到剪贴板'));
setTimeout(() => setCopied(false), 2000);
} catch (err) { } catch (err) {
Toast.error(t('复制失败')); Toast.error(t('复制失败'));
console.error('Copy failed:', err); console.error('Copy failed:', err);
+2 -2
View File
@@ -106,7 +106,7 @@ const SSEViewer = ({ sseData }) => {
) )
.join('\n\n'); .join('\n\n');
await copy(allData); if (!(await copy(allData))) throw new Error('Clipboard copy failed');
setCopied(true); setCopied(true);
Toast.success(t('已复制全部数据')); Toast.success(t('已复制全部数据'));
setTimeout(() => setCopied(false), 2000); setTimeout(() => setCopied(false), 2000);
@@ -122,7 +122,7 @@ const SSEViewer = ({ sseData }) => {
const textToCopy = item.parsed const textToCopy = item.parsed
? JSON.stringify(item.parsed, null, 2) ? JSON.stringify(item.parsed, null, 2)
: item.raw; : item.raw;
await copy(textToCopy); if (!(await copy(textToCopy))) throw new Error('Clipboard copy failed');
Toast.success(t('已复制')); Toast.success(t('已复制'));
} catch (err) { } catch (err) {
Toast.error(t('复制失败')); Toast.error(t('复制失败'));
@@ -282,21 +282,23 @@ const PromotionPosterModal = ({ visible, onClose }) => {
}; };
// 复制邀请链接 // 复制邀请链接
const handleCopyLink = () => { const handleCopyLink = async () => {
if (!affLink) { if (!affLink) {
showError(t('邀请链接获取中,请稍后')); showError(t('邀请链接获取中,请稍后'));
return; return;
} }
copy(affLink, t('邀请链接')); if (await copy(affLink)) showSuccess(t('邀请链接已复制到剪切板'));
else showError(t('复制失败,请手动复制'));
}; };
// 复制邀请码 // 复制邀请码
const handleCopyCode = () => { const handleCopyCode = async () => {
if (!affCode) { if (!affCode) {
showError(t('邀请码获取中,请稍后')); showError(t('邀请码获取中,请稍后'));
return; return;
} }
copy(affCode, t('邀请码')); if (await copy(affCode)) showSuccess(t('复制成功'));
else showError(t('复制失败,请手动复制'));
}; };
// 链接分享模式 - PC友好 // 链接分享模式 - PC友好
@@ -369,11 +369,11 @@ export default function ContentGuardSetting() {
} }
return ( return (
<div style={{ padding: 20 }}> <div>
<Space vertical align='start' spacing='medium' style={{ width: '100%' }}>
<Banner <Banner
fullMode={false} fullMode={false}
type={config.available && config.schema_ready ? 'info' : 'warning'} className='mb-4'
type='info'
description={ description={
config.available && config.schema_ready config.available && config.schema_ready
? t( ? t(
@@ -382,6 +382,7 @@ export default function ContentGuardSetting() {
: t('运行环境或数据库迁移尚未允许启用内容防护。') : t('运行环境或数据库迁移尚未允许启用内容防护。')
} }
/> />
<Space vertical align='start' spacing='medium' style={{ width: '100%' }}>
<Card style={{ width: '100%' }}> <Card style={{ width: '100%' }}>
<Space style={{ justifyContent: 'space-between', width: '100%' }}> <Space style={{ justifyContent: 'space-between', width: '100%' }}>
<Space> <Space>
@@ -41,7 +41,6 @@ import {
PowerOff, PowerOff,
RefreshCw, RefreshCw,
Users, Users,
Headphones,
Upload as UploadIcon, Upload as UploadIcon,
} from 'lucide-react'; } from 'lucide-react';
import { API, showError, showSuccess } from '../../helpers'; import { API, showError, showSuccess } from '../../helpers';
@@ -369,7 +368,6 @@ const CustomerServiceSetting = () => {
<div style={{ marginBottom: 16 }}> <div style={{ marginBottom: 16 }}>
<Banner <Banner
type='info' type='info'
icon={<Headphones size={16} />}
description={t( description={t(
'配置企业微信客服,支持多客服轮询、加权分配、最少接待等策略。客服链接可在企业微信管理后台的「微信客服」中获取。', '配置企业微信客服,支持多客服轮询、加权分配、最少接待等策略。客服链接可在企业微信管理后台的「微信客服」中获取。',
)} )}
+52 -12
View File
@@ -38,8 +38,6 @@ import {
import { API, isRoot, showError, showSuccess } from '../../helpers'; import { API, isRoot, showError, showSuccess } from '../../helpers';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
const PAGE_SIZE = 20;
const MODE_OPTIONS = [ const MODE_OPTIONS = [
{ value: 'detect_only', label: '仅检测告警' }, { value: 'detect_only', label: '仅检测告警' },
{ value: 'standard', label: '标准脱敏(可逆占位符)' }, { value: 'standard', label: '标准脱敏(可逆占位符)' },
@@ -128,12 +126,15 @@ export default function DataSecuritySetting() {
// 企业私有规则监督视图(企业自助维护;平台只读 + 紧急删除止血) // 企业私有规则监督视图(企业自助维护;平台只读 + 紧急删除止血)
const [orgRules, setOrgRules] = useState([]); const [orgRules, setOrgRules] = useState([]);
const [audits, setAudits] = useState([]); const [audits, setAudits] = useState([]);
const [auditPageSize, setAuditPageSize] = useState(20);
const [auditPage, setAuditPage] = useState(1); const [auditPage, setAuditPage] = useState(1);
const [auditTotal, setAuditTotal] = useState(0); const [auditTotal, setAuditTotal] = useState(0);
const [hitLogs, setHitLogs] = useState([]); const [hitLogs, setHitLogs] = useState([]);
const [hitLogPageSize, setHitLogPageSize] = useState(20);
const [hitLogPage, setHitLogPage] = useState(1); const [hitLogPage, setHitLogPage] = useState(1);
const [hitLogTotal, setHitLogTotal] = useState(0); const [hitLogTotal, setHitLogTotal] = useState(0);
const [changeRequests, setChangeRequests] = useState([]); const [changeRequests, setChangeRequests] = useState([]);
const [changeReqPageSize, setChangeReqPageSize] = useState(20);
const [changeReqPage, setChangeReqPage] = useState(1); const [changeReqPage, setChangeReqPage] = useState(1);
const [changeReqTotal, setChangeReqTotal] = useState(0); const [changeReqTotal, setChangeReqTotal] = useState(0);
const [metrics, setMetrics] = useState(null); const [metrics, setMetrics] = useState(null);
@@ -183,9 +184,14 @@ export default function DataSecuritySetting() {
showError(res.data?.message || t('加载规则失败')); showError(res.data?.message || t('加载规则失败'));
} }
}; };
const loadAudits = async (page = 1) => { const [auditLoading, setAuditLoading] = useState(false);
const [hitLogLoading, setHitLogLoading] = useState(false);
const [changeReqLoading, setChangeReqLoading] = useState(false);
const loadAudits = async (page = 1, size = auditPageSize) => {
setAuditLoading(true);
try {
const res = await API.get( const res = await API.get(
`/api/desensitize/config-audit?page=${page}&page_size=${PAGE_SIZE}`, `/api/desensitize/config-audit?page=${page}&page_size=${size}`,
); );
if (res.data?.success) { if (res.data?.success) {
setAudits(res.data.data?.items || []); setAudits(res.data.data?.items || []);
@@ -194,10 +200,17 @@ export default function DataSecuritySetting() {
} else { } else {
showError(res.data?.message || t('加载配置审计失败')); showError(res.data?.message || t('加载配置审计失败'));
} }
} catch (err) {
showError(err.message || t('加载配置审计失败'));
} finally {
setAuditLoading(false);
}
}; };
const loadHitLogs = async (page = 1) => { const loadHitLogs = async (page = 1, size = hitLogPageSize) => {
setHitLogLoading(true);
try {
const res = await API.get( const res = await API.get(
`/api/desensitize/logs?page=${page}&page_size=${PAGE_SIZE}`, `/api/desensitize/logs?page=${page}&page_size=${size}`,
); );
if (res.data?.success) { if (res.data?.success) {
setHitLogs(res.data.data?.items || []); setHitLogs(res.data.data?.items || []);
@@ -206,10 +219,17 @@ export default function DataSecuritySetting() {
} else { } else {
showError(res.data?.message || t('加载命中审计失败')); showError(res.data?.message || t('加载命中审计失败'));
} }
} catch (err) {
showError(err.message || t('加载命中审计失败'));
} finally {
setHitLogLoading(false);
}
}; };
const loadChangeRequests = async (page = 1) => { const loadChangeRequests = async (page = 1, size = changeReqPageSize) => {
setChangeReqLoading(true);
try {
const res = await API.get( const res = await API.get(
`/api/desensitize/change-requests?page=${page}&page_size=${PAGE_SIZE}`, `/api/desensitize/change-requests?page=${page}&page_size=${size}`,
); );
if (res.data?.success) { if (res.data?.success) {
setChangeRequests(res.data.data?.items || []); setChangeRequests(res.data.data?.items || []);
@@ -218,6 +238,11 @@ export default function DataSecuritySetting() {
} else { } else {
showError(res.data?.message || t('加载变更审批列表失败')); showError(res.data?.message || t('加载变更审批列表失败'));
} }
} catch (err) {
showError(err.message || t('加载变更审批列表失败'));
} finally {
setChangeReqLoading(false);
}
}; };
// 监控指标失败必须显式呈现 '-' 而非 0:安全巡检语境下"待审批 0 / 敏感命中 0" // 监控指标失败必须显式呈现 '-' 而非 0:安全巡检语境下"待审批 0 / 敏感命中 0"
// 是有含义的结论,不能由失败态冒充(与企业侧命中审计同一原则,R39 修复)。 // 是有含义的结论,不能由失败态冒充(与企业侧命中审计同一原则,R39 修复)。
@@ -647,7 +672,7 @@ export default function DataSecuritySetting() {
return ( return (
<Spin spinning={loading}> <Spin spinning={loading}>
<Banner <Banner
type='warning' type='info'
closeIcon={null} closeIcon={null}
description={t( description={t(
'本功能基于规则匹配,无法识别所有类型的敏感信息(如图像内容、详细地址、外文姓名、未知格式的密钥等)。请勿单独依赖本功能作为合规保障。', '本功能基于规则匹配,无法识别所有类型的敏感信息(如图像内容、详细地址、外文姓名、未知格式的密钥等)。请勿单独依赖本功能作为合规保障。',
@@ -941,12 +966,17 @@ export default function DataSecuritySetting() {
<Table <Table
columns={changeReqColumns} columns={changeReqColumns}
dataSource={changeRequests} dataSource={changeRequests}
loading={changeReqLoading}
rowKey='id' rowKey='id'
pagination={{ pagination={{
currentPage: changeReqPage, currentPage: changeReqPage,
pageSize: PAGE_SIZE, pageSize: changeReqPageSize,
total: changeReqTotal, total: changeReqTotal,
onPageChange: (p) => loadChangeRequests(p), onPageChange: (p) => loadChangeRequests(p),
onPageSizeChange: (size) => {
setChangeReqPageSize(size);
loadChangeRequests(1, size);
},
}} }}
/> />
</Card> </Card>
@@ -1194,12 +1224,17 @@ export default function DataSecuritySetting() {
<Table <Table
columns={hitLogColumns} columns={hitLogColumns}
dataSource={hitLogs} dataSource={hitLogs}
loading={hitLogLoading}
rowKey='id' rowKey='id'
pagination={{ pagination={{
currentPage: hitLogPage, currentPage: hitLogPage,
pageSize: PAGE_SIZE, pageSize: hitLogPageSize,
total: hitLogTotal, total: hitLogTotal,
onPageChange: (p) => loadHitLogs(p), onPageChange: (p) => loadHitLogs(p),
onPageSizeChange: (size) => {
setHitLogPageSize(size);
loadHitLogs(1, size);
},
}} }}
/> />
</Card> </Card>
@@ -1210,12 +1245,17 @@ export default function DataSecuritySetting() {
<Table <Table
columns={auditColumns} columns={auditColumns}
dataSource={audits} dataSource={audits}
loading={auditLoading}
rowKey='id' rowKey='id'
pagination={{ pagination={{
currentPage: auditPage, currentPage: auditPage,
pageSize: PAGE_SIZE, pageSize: auditPageSize,
total: auditTotal, total: auditTotal,
onPageChange: (p) => loadAudits(p), onPageChange: (p) => loadAudits(p),
onPageSizeChange: (size) => {
setAuditPageSize(size);
loadAudits(1, size);
},
}} }}
/> />
</Card> </Card>
+14 -15
View File
@@ -23,6 +23,7 @@ import { API, showError, showSuccess, timestamp2string } from '../../helpers';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { StatusContext } from '../../context/Status'; import { StatusContext } from '../../context/Status';
import { Text } from '@/components/ui'; import { Text } from '@/components/ui';
import './other-setting.css';
const LEGAL_USER_AGREEMENT_KEY = 'legal.user_agreement'; const LEGAL_USER_AGREEMENT_KEY = 'legal.user_agreement';
const LEGAL_PRIVACY_POLICY_KEY = 'legal.privacy_policy'; const LEGAL_PRIVACY_POLICY_KEY = 'legal.privacy_policy';
@@ -370,22 +371,14 @@ const OtherSetting = () => {
return ( return (
<Row> <Row>
<Col <Col span={24} className='settings-other-sections'>
span={24}
style={{
marginTop: '10px',
display: 'flex',
flexDirection: 'column',
gap: '10px',
}}
>
{/* 版本信息 */} {/* 版本信息 */}
<Form> <Form>
<Card> <Card>
<Form.Section text={t('系统信息')}> <Form.Section text={t('系统信息')} className='settings-other-info'>
<Row> <Row>
<Col span={16}> <Col span={24}>
<Space> <Space wrap>
<Text> <Text>
{t('当前版本')}: {t('当前版本')}:
{statusState?.status?.version || t('未知')} {statusState?.status?.version || t('未知')}
@@ -401,7 +394,7 @@ const OtherSetting = () => {
</Col> </Col>
</Row> </Row>
<Row> <Row>
<Col span={16}> <Col span={24}>
<Text> <Text>
{t('启动时间')}:{getStartTimeString()} {t('启动时间')}:{getStartTimeString()}
</Text> </Text>
@@ -416,7 +409,10 @@ const OtherSetting = () => {
getFormApi={(formAPI) => (formAPISettingGeneral.current = formAPI)} getFormApi={(formAPI) => (formAPISettingGeneral.current = formAPI)}
> >
<Card> <Card>
<Form.Section text={t('通用设置')}> <Form.Section
text={t('通用设置')}
className='settings-other-fields'
>
<Form.TextArea <Form.TextArea
label={t('公告')} label={t('公告')}
placeholder={t( placeholder={t(
@@ -477,7 +473,10 @@ const OtherSetting = () => {
getFormApi={(formAPI) => (formAPIPersonalization.current = formAPI)} getFormApi={(formAPI) => (formAPIPersonalization.current = formAPI)}
> >
<Card> <Card>
<Form.Section text={t('个性化设置')}> <Form.Section
text={t('个性化设置')}
className='settings-other-fields'
>
<Form.Input <Form.Input
label={t('系统名称')} label={t('系统名称')}
placeholder={t('在此输入系统名称')} placeholder={t('在此输入系统名称')}
+13 -13
View File
@@ -17,9 +17,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { writeClipboardText } from '../../helpers/clipboard';
import React, { useContext, useEffect, useState } from 'react'; import React, { useContext, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import UserCenterPageHeader from '../common/UserCenterPageHeader'; import UserCenterPageHeader from '../common/UserCenterPageHeader';
import { useConsolePage } from '../console/ConsoleContext';
import { import {
API, API,
showError, showError,
@@ -68,6 +70,7 @@ const NAV_ITEMS = [
]; ];
const PersonalSetting = () => { const PersonalSetting = () => {
const consolePage = useConsolePage();
const [userState, userDispatch] = useContext(UserContext); const [userState, userDispatch] = useContext(UserContext);
let navigate = useNavigate(); let navigate = useNavigate();
const { t } = useTranslation(); const { t } = useTranslation();
@@ -508,22 +511,13 @@ const PersonalSetting = () => {
// 复制用户ID // 复制用户ID
const copyUserId = () => { const copyUserId = () => {
const userId = String(userState?.user?.id || ''); const userId = String(userState?.user?.id || '');
navigator.clipboard writeClipboardText(userId)
.writeText(userId)
.then(() => { .then(() => {
setUserIdCopied(true); setUserIdCopied(true);
setTimeout(() => setUserIdCopied(false), 2000); setTimeout(() => setUserIdCopied(false), 2000);
}) })
.catch(() => { .catch(() => {
// 降级方案 showError(t('复制失败,请手动复制'));
const textarea = document.createElement('textarea');
textarea.value = userId;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
setUserIdCopied(true);
setTimeout(() => setUserIdCopied(false), 2000);
}); });
}; };
@@ -595,12 +589,18 @@ const PersonalSetting = () => {
const roleInfo = getRoleTag(); const roleInfo = getRoleTag();
return ( return (
<div className='ui-personal-settings min-h-screen pt-16 sm:pt-20'> <div
<div className='ui-personal-inner uc-page'> className={`ui-personal-settings ${consolePage ? 'console-personal' : 'min-h-screen pt-16 sm:pt-20'}`}
>
<div
className={`ui-personal-inner ${consolePage ? 'console-content' : 'uc-page'}`}
>
{!consolePage && (
<UserCenterPageHeader <UserCenterPageHeader
title={t('个人设置')} title={t('个人设置')}
subtitle={t('管理你的平台形象、账户安全与通知偏好')} subtitle={t('管理你的平台形象、账户安全与通知偏好')}
/> />
)}
<Card className='ui-personal-profile'> <Card className='ui-personal-profile'>
<div className='ui-profile-identity'> <div className='ui-profile-identity'>
<span className='ui-profile-avatar'> <span className='ui-profile-avatar'>
+8 -9
View File
@@ -780,7 +780,6 @@ const SystemSetting = () => {
display: 'flex', display: 'flex',
flexDirection: 'column', flexDirection: 'column',
gap: '10px', gap: '10px',
marginTop: '10px',
}} }}
> >
<Card> <Card>
@@ -812,7 +811,7 @@ const SystemSetting = () => {
description={t( description={t(
'此代理仅用于图片请求转发,Webhook通知发送等,AI API请求仍然由服务器直接发出,可在渠道设置中单独配置代理', '此代理仅用于图片请求转发,Webhook通知发送等,AI API请求仍然由服务器直接发出,可在渠道设置中单独配置代理',
)} )}
style={{ marginBottom: 20, marginTop: 16 }} style={{ marginBlock: '16px' }}
/> />
<Text>{t('或其兼容new-api-worker格式的其他版本')}</Text> <Text>{t('或其兼容new-api-worker格式的其他版本')}</Text>
<Row <Row
@@ -1231,7 +1230,7 @@ const SystemSetting = () => {
description={t( description={t(
'Passkey 是基于 WebAuthn 标准的无密码身份验证方法,支持指纹、面容、硬件密钥等认证方式', 'Passkey 是基于 WebAuthn 标准的无密码身份验证方法,支持指纹、面容、硬件密钥等认证方式',
)} )}
style={{ marginBottom: 20, marginTop: 16 }} style={{ marginBlock: '16px' }}
/> />
<Row <Row
gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }} gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}
@@ -1479,7 +1478,7 @@ const SystemSetting = () => {
<Banner <Banner
type='info' type='info'
description={`${t('主页链接填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')},${t('重定向 URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/oidc`} description={`${t('主页链接填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')},${t('重定向 URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/oidc`}
style={{ marginBottom: 20, marginTop: 16 }} style={{ marginBlock: '16px' }}
/> />
<Text> <Text>
{t( {t(
@@ -1553,7 +1552,7 @@ const SystemSetting = () => {
<Banner <Banner
type='info' type='info'
description={`${t('Homepage URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')},${t('Authorization callback URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/github`} description={`${t('Homepage URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')},${t('Authorization callback URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/github`}
style={{ marginBottom: 20, marginTop: 16 }} style={{ marginBlock: '16px' }}
/> />
<Row <Row
gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }} gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}
@@ -1584,7 +1583,7 @@ const SystemSetting = () => {
<Banner <Banner
type='info' type='info'
description={`${t('Homepage URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')},${t('Authorization callback URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/discord`} description={`${t('Homepage URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')},${t('Authorization callback URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/discord`}
style={{ marginBottom: 20, marginTop: 16 }} style={{ marginBlock: '16px' }}
/> />
<Row <Row
gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }} gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}
@@ -1630,7 +1629,7 @@ const SystemSetting = () => {
<Banner <Banner
type='info' type='info'
description={`${t('回调 URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/linuxdo`} description={`${t('回调 URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/linuxdo`}
style={{ marginBottom: 20, marginTop: 16 }} style={{ marginBlock: '16px' }}
/> />
<Row <Row
gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }} gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}
@@ -1713,7 +1712,7 @@ const SystemSetting = () => {
window.location.origin + window.location.origin +
'/oauth/wechat-open' '/oauth/wechat-open'
} }
style={{ marginBottom: 20, marginTop: 16 }} style={{ marginBlock: '16px' }}
/> />
<Row <Row
gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }} gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}
@@ -1760,7 +1759,7 @@ const SystemSetting = () => {
window.location.origin + window.location.origin +
'/oauth/wechat-mp' '/oauth/wechat-mp'
} }
style={{ marginBottom: 20, marginTop: 16 }} style={{ marginBlock: '16px' }}
/> />
<Row <Row
gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }} gutter={{ xs: 8, sm: 16, md: 24, lg: 24, xl: 24, xxl: 24 }}
+46
View File
@@ -0,0 +1,46 @@
.settings-page .settings-other-sections {
display: flex;
flex-direction: column;
gap: var(--console-space-2, 16px);
}
/* Match the default Tabs navigation gap without stacking form margins. */
.settings-page .settings-other-sections > .ant-form + .ant-form {
margin-top: 0;
}
.settings-page .settings-other-info > .ant-row + .ant-row {
margin-top: 12px;
}
.settings-page .settings-other-info .ant-typography {
overflow-wrap: anywhere;
}
.settings-page .settings-other-fields {
display: flex;
flex-direction: column;
align-items: stretch;
}
.settings-page .settings-other-fields > .ant-btn {
align-self: flex-start;
}
.settings-page .settings-other-fields > .ant-form-item {
margin-bottom: 12px;
}
/* These individually saved fields need spacing, rather than a blank error row. */
.settings-page .settings-other-fields .ant-form-item-control::after {
display: none;
}
.settings-page .settings-other-fields .ant-form-item-explain {
min-height: 0;
line-height: 22px;
}
.settings-page .settings-other-fields > .ant-btn + .ant-form-item {
margin-top: var(--settings-field-gap);
}
@@ -79,7 +79,7 @@ const AccountManagement = ({
const popContent = ( const popContent = (
<div className='text-xs p-2'> <div className='text-xs p-2'>
<Typography.Paragraph copyable={{ content: accountId }}> <Typography.Paragraph copyable={{ text: accountId }}>
{accountId} {accountId}
</Typography.Paragraph> </Typography.Paragraph>
{label ? ( {label ? (
@@ -16,6 +16,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { writeClipboardText } from '../../../../helpers/clipboard';
import { API, showError, showSuccess, showWarning } from '../../../../helpers'; import { API, showError, showSuccess, showWarning } from '../../../../helpers';
import { import {
Banner, Banner,
@@ -190,8 +192,7 @@ const TwoFASetting = ({ t }) => {
// 通用复制函数 // 通用复制函数
const copyTextToClipboard = (text, successMessage = t('已复制到剪贴板')) => { const copyTextToClipboard = (text, successMessage = t('已复制到剪贴板')) => {
navigator.clipboard writeClipboardText(text)
.writeText(text)
.then(() => { .then(() => {
showSuccess(successMessage); showSuccess(successMessage);
}) })
@@ -58,7 +58,7 @@ const AccountBindingSection = ({
const popContent = ( const popContent = (
<div className='text-xs p-2'> <div className='text-xs p-2'>
<Typography.Paragraph copyable={{ content: accountId }}> <Typography.Paragraph copyable={{ text: accountId }}>
{accountId} {accountId}
</Typography.Paragraph> </Typography.Paragraph>
{label && <div className='ui-binding-popover-label'>{label}</div>} {label && <div className='ui-binding-popover-label'>{label}</div>}
@@ -71,10 +71,10 @@ const NotificationSection = ({
const handleCopyExample = async () => { const handleCopyExample = async () => {
try { try {
const success = await copy(JSON.stringify(WEBHOOK_EXAMPLE, null, 2)); const success = await copy(JSON.stringify(WEBHOOK_EXAMPLE, null, 2));
Toast.success(t('已复制到剪贴板'));
if (!success) { if (!success) {
throw new Error('Copy operation failed'); throw new Error('Copy operation failed');
} }
Toast.success(t('已复制到剪贴板'));
} catch (err) { } catch (err) {
Toast.error(t('复制失败')); Toast.error(t('复制失败'));
console.error('Copy failed:', err); console.error('Copy failed:', err);
@@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
import React from 'react'; import React from 'react';
import { Button, Tag } from '@/components/ui'; import { Button, Tag } from '@/components/ui';
import { RefreshCw } from 'lucide-react';
import { isAdmin } from '../../../helpers'; import { isAdmin } from '../../../helpers';
const AdminTokensActions = ({ const AdminTokensActions = ({
@@ -30,7 +31,7 @@ const AdminTokensActions = ({
const hasSelection = selectedRowKeys && selectedRowKeys.length > 0; const hasSelection = selectedRowKeys && selectedRowKeys.length > 0;
return ( return (
<div className='flex flex-wrap items-center gap-2 w-full md:w-auto order-2 md:order-1'> <div className='admin-tokens-tools'>
{hasSelection && ( {hasSelection && (
<Tag color='violet' shape='circle' size='small'> <Tag color='violet' shape='circle' size='small'>
{t('已选 {{count}} 项', { count: selectedRowKeys.length })} {t('已选 {{count}} 项', { count: selectedRowKeys.length })}
@@ -57,7 +58,7 @@ const AdminTokensActions = ({
</Button> </Button>
</> </>
)} )}
<Button size='small' type='tertiary' onClick={onRefresh}> <Button icon={<RefreshCw size={16} />} onClick={onRefresh}>
{t('刷新')} {t('刷新')}
</Button> </Button>
</div> </div>
@@ -18,15 +18,8 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React from 'react'; import React from 'react';
import { import { Button, Switch, Tag as AntTag } from 'antd';
Button, import { Tag, Typography, Popover } from '@/components/ui';
Space,
Tag,
Typography,
Popover,
Dropdown,
} from '@/components/ui';
import { IconMore } from '@/components/ui/icons';
import { import {
renderGroup, renderGroup,
renderQuota, renderQuota,
@@ -37,18 +30,33 @@ import {
const { Text } = Typography; const { Text } = Typography;
const statusMeta = { const statusMeta = {
1: { color: 'green', label: '已启用' }, 3: { color: 'error', label: '已过期' },
2: { color: 'grey', label: '已禁用' }, 4: { color: 'warning', label: '已耗尽' },
3: { color: 'red', label: '已过期' },
4: { color: 'orange', label: '已耗尽' },
}; };
const renderStatus = (status, t) => { const renderStatus = (status, record, t, showEnableDisableModal) => {
const meta = statusMeta[status] || { color: 'red', label: t('未知状态') }; const meta =
statusMeta[status] ||
(![1, 2].includes(status) ? { color: 'error', label: '未知状态' } : null);
return ( return (
<Tag color={meta.color} shape='circle' size='small'> <div className='admin-tokens-status'>
<Switch
size='small'
checked={status === 1}
checkedChildren={t('启用')}
unCheckedChildren={t('禁用')}
aria-label={status === 1 ? t('禁用') : t('启用')}
disabled={!isAdmin() || Boolean(record.DeletedAt)}
onChange={() =>
showEnableDisableModal(record, status === 1 ? 'disable' : 'enable')
}
/>
{meta && (
<AntTag color={meta.color} bordered={false}>
{t(meta.label)} {t(meta.label)}
</Tag> </AntTag>
)}
</div>
); );
}; };
@@ -72,21 +80,17 @@ const renderUserCell = (text, record, t) => {
); );
}; };
const renderKey = (text, record) => { const renderKey = (text) => {
// 后端已脱敏,前端再加 sk- 前缀 // 后端已脱敏,前端再加 sk- 前缀
return ( return <code className='admin-tokens-key'>sk-{text}</code>;
<code className='text-xs bg-[var(--ui-color-fill-0)] px-2 py-0.5 rounded font-mono'>
sk-{text}
</code>
);
}; };
const renderQuotaCell = (text, record, t) => { const renderQuotaCell = (text, record, t) => {
if (record.unlimited_quota) { if (record.unlimited_quota) {
return ( return (
<Tag color='violet' shape='circle' size='small'> <AntTag color='success' bordered={false}>
{t('无限制')} {t('无限制')}
</Tag> </AntTag>
); );
} }
const used = record.used_quota || 0; const used = record.used_quota || 0;
@@ -103,9 +107,7 @@ const renderQuotaCell = (text, record, t) => {
); );
return ( return (
<Popover content={popoverContent} position='top'> <Popover content={popoverContent} position='top'>
<Tag color='white' shape='circle' size='small'> <span>{renderQuota(remain)}</span>
{renderQuota(remain)}
</Tag>
</Popover> </Popover>
); );
}; };
@@ -113,13 +115,8 @@ const renderQuotaCell = (text, record, t) => {
const renderTime = (ts, t) => { const renderTime = (ts, t) => {
if (!ts || ts === 0) if (!ts || ts === 0)
return <span className='text-[var(--ui-color-text-2)]'>—</span>; return <span className='text-[var(--ui-color-text-2)]'>—</span>;
if (ts === -1) if (ts === -1) return <span>{t('永不过期')}</span>;
return ( return <span>{timestamp2string(ts)}</span>;
<Tag color='blue' shape='circle' size='small'>
{t('永不过期')}
</Tag>
);
return <span className='text-xs'>{timestamp2string(ts)}</span>;
}; };
const renderScope = (orgId, t) => { const renderScope = (orgId, t) => {
@@ -140,51 +137,28 @@ const renderScope = (orgId, t) => {
const renderOperations = ( const renderOperations = (
text, text,
record, record,
{ showEditTokenModal, showEnableDisableModal, showDeleteTokenModal, t }, { showEditTokenModal, showDeleteTokenModal, t },
) => { ) => {
if (record.DeletedAt) return <></>; if (record.DeletedAt) return <></>;
const isEnabled = record.status === 1;
if (!isAdmin()) return null; if (!isAdmin()) return null;
return ( return (
<Space> <div className='admin-tokens-row-actions'>
<Button <Button
size='small' size='small'
type='tertiary' type='link'
onClick={() => showEditTokenModal(record)} onClick={() => showEditTokenModal(record)}
> >
{t('编辑')} {t('编辑')}
</Button> </Button>
{isEnabled ? (
<Button <Button
size='small' size='small'
type='danger' type='link'
onClick={() => showEnableDisableModal(record, 'disable')} danger
onClick={() => showDeleteTokenModal(record)}
> >
{t('禁用')} {t('删除')}
</Button> </Button>
) : ( </div>
<Button
size='small'
onClick={() => showEnableDisableModal(record, 'enable')}
>
{t('启用')}
</Button>
)}
<Dropdown
trigger='click'
position='bottomRight'
menu={[
{
node: 'item',
name: t('删除'),
type: 'danger',
onClick: () => showDeleteTokenModal(record),
},
]}
>
<Button size='small' type='tertiary' icon={<IconMore />} />
</Dropdown>
</Space>
); );
}; };
@@ -207,10 +181,13 @@ export const getAdminTokensColumns = ({
render: (text, record) => renderUserCell(text, record, t), render: (text, record) => renderUserCell(text, record, t),
}, },
{ {
title: t('密钥名称'), title: t('名称'),
dataIndex: 'name', dataIndex: 'name',
render: (text) => ( render: (text) => (
<span className='truncate inline-block max-w-[160px]' title={text}> <span
className='admin-tokens-name truncate inline-block max-w-[160px]'
title={text}
>
{text || <Text type='tertiary'>—</Text>} {text || <Text type='tertiary'>—</Text>}
</span> </span>
), ),
@@ -223,8 +200,9 @@ export const getAdminTokensColumns = ({
{ {
title: t('状态'), title: t('状态'),
dataIndex: 'status', dataIndex: 'status',
width: 90, width: 150,
render: (text) => renderStatus(text, t), render: (text, record) =>
renderStatus(text, record, t, showEnableDisableModal),
}, },
{ {
title: t('归属'), title: t('归属'),
@@ -248,11 +226,7 @@ export const getAdminTokensColumns = ({
title: t('已用额度'), title: t('已用额度'),
dataIndex: 'used_quota', dataIndex: 'used_quota',
width: 110, width: 110,
render: (text) => ( render: (text) => <span>{renderQuota(text || 0)}</span>,
<Text type='tertiary' size='small'>
{renderQuota(text || 0)}
</Text>
),
}, },
{ {
title: t('创建时间'), title: t('创建时间'),
@@ -273,14 +247,13 @@ export const getAdminTokensColumns = ({
render: (text) => renderTime(text, t), render: (text) => renderTime(text, t),
}, },
{ {
title: '', title: t('操作'),
dataIndex: 'operate', dataIndex: 'operate',
fixed: 'right', fixed: 'right',
width: 200, width: 130,
render: (text, record) => render: (text, record) =>
renderOperations(text, record, { renderOperations(text, record, {
showEditTokenModal, showEditTokenModal,
showEnableDisableModal,
showDeleteTokenModal, showDeleteTokenModal,
t, t,
}), }),
@@ -18,29 +18,10 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React from 'react'; import React from 'react';
import { Typography, Tag } from '@/components/ui'; import { TableTitle } from '../../common/table/TableToolbar';
import { IconKey } from '@/components/ui/icons';
import CompactModeToggle from '../../common/ui/CompactModeToggle';
const { Text } = Typography; const AdminTokensDescription = ({ t }) => (
<TableTitle>{t('密钥列表')}</TableTitle>
const AdminTokensDescription = ({ compactMode, setCompactMode, t }) => { );
return (
<div className='flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full'>
<div className='flex items-center gap-2 text-brand'>
<IconKey />
<Text>{t('密钥管理')}</Text>
<Tag color='orange' shape='circle' size='small'>
{t('管理员')}
</Tag>
</div>
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div>
);
};
export default AdminTokensDescription; export default AdminTokensDescription;
@@ -20,12 +20,13 @@ For commercial licensing, please contact support@quantumnous.com
import React, { useRef } from 'react'; import React, { useRef } from 'react';
import { Form, Button } from '@/components/ui'; import { Form, Button } from '@/components/ui';
import { IconSearch } from '@/components/ui/icons'; import { IconSearch } from '@/components/ui/icons';
import FilterSearchButton from '../../common/table/FilterSearchButton';
import { useFilterSearch } from '../../../hooks/common/useFilterSearch';
const AdminTokensFilters = ({ const AdminTokensFilters = ({
formInitValues, formInitValues,
setFormApi, setFormApi,
searchTokens, searchTokens,
debouncedSearch,
loadTokens, loadTokens,
pageSize, pageSize,
groupOptions, groupOptions,
@@ -34,61 +35,71 @@ const AdminTokensFilters = ({
t, t,
}) => { }) => {
const formApiRef = useRef(null); const formApiRef = useRef(null);
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
() => searchTokens(pageSize),
);
const handleReset = () => { const handleReset = () => {
if (!formApiRef.current) return; if (!formApiRef.current) return;
formApiRef.current.reset(); formApiRef.current.reset();
cancelPendingSearch();
// 重置后立即用初始值刷新(不走 debounce) // 重置后立即用初始值刷新(不走 debounce)
loadTokens(1, pageSize, formInitValues); loadTokens(1, pageSize, formInitValues);
}; };
return ( return (
<Form <Form
initValues={formInitValues} initValues={{
...formInitValues,
group: formInitValues.group === '' ? undefined : formInitValues.group,
unlimited:
formInitValues.unlimited === ''
? undefined
: formInitValues.unlimited,
}}
getFormApi={(api) => { getFormApi={(api) => {
setFormApi(api); setFormApi(api);
formApiRef.current = api; formApiRef.current = api;
}} }}
onSubmit={() => searchTokens(pageSize)} onSubmit={submitSearch}
onValueChange={scheduleSearch}
allowEmpty allowEmpty
autoComplete='off' autoComplete='off'
layout='horizontal' layout='vertical'
trigger='change' trigger='change'
className='w-full md:w-auto order-1 md:order-2' className='admin-tokens-filter-form'
> >
<div className='flex flex-col md:flex-row items-center gap-2 w-full md:w-auto flex-wrap'> <div className='admin-tokens-filter-grid'>
<div className='w-full md:w-56'> <div className='admin-tokens-filter-field'>
<Form.Input <Form.Input
field='keyword' field='keyword'
label={t('密钥名称 / Key 片段')}
prefix={<IconSearch />} prefix={<IconSearch />}
placeholder={t('密钥名称 / Key 片段')} placeholder={t('密钥名称 / Key 片段')}
showClear showClear
pure
size='small'
/> />
</div> </div>
<div className='w-full md:w-44'> <div className='admin-tokens-filter-field'>
<Form.Input <Form.Input
field='user_keyword' field='user_keyword'
label={t('用户名/昵称')}
placeholder={t('用户名/昵称')} placeholder={t('用户名/昵称')}
showClear showClear
pure
size='small'
/> />
</div> </div>
<div className='w-full md:w-28'> <div className='admin-tokens-filter-field'>
<Form.Input <Form.Input
field='user_id' field='user_id'
label={t('用户ID')}
placeholder={t('用户ID')} placeholder={t('用户ID')}
type='number' type='number'
showClear showClear
pure
size='small'
/> />
</div> </div>
<div className='w-full md:w-44'> <div className='admin-tokens-filter-field'>
<Form.Select <Form.Select
field='statuses' field='statuses'
label={t('状态')}
placeholder={t('状态(多选)')} placeholder={t('状态(多选)')}
multiple multiple
optionList={[ optionList={[
@@ -98,42 +109,36 @@ const AdminTokensFilters = ({
{ label: t('已耗尽'), value: 4 }, { label: t('已耗尽'), value: 4 },
]} ]}
showClear showClear
pure
size='small'
className='w-full' className='w-full'
onChange={debouncedSearch}
/> />
</div> </div>
<div className='w-full md:w-36'> <div className='admin-tokens-filter-field'>
<Form.Select <Form.Select
field='group' field='group'
label={t('分组')}
placeholder={t('分组')} placeholder={t('分组')}
optionList={groupOptions} optionList={groupOptions}
showClear showClear
pure
size='small'
className='w-full' className='w-full'
onChange={debouncedSearch}
/> />
</div> </div>
<div className='w-full md:w-32'> <div className='admin-tokens-filter-field'>
<Form.Select <Form.Select
field='unlimited' field='unlimited'
placeholder={t('额度类型')} label={t('剩余额度')}
placeholder={t('剩余额度')}
optionList={[ optionList={[
{ label: t('无限额度'), value: true }, { label: t('无限额度'), value: true },
{ label: t('有限额度'), value: false }, { label: t('有限额度'), value: false },
]} ]}
showClear showClear
pure
size='small'
className='w-full' className='w-full'
onChange={debouncedSearch}
/> />
</div> </div>
<div className='w-full md:w-32'> <div className='admin-tokens-filter-field'>
<Form.Select <Form.Select
field='org_scope' field='org_scope'
label={t('归属')}
placeholder={t('归属')} placeholder={t('归属')}
optionList={[ optionList={[
{ label: t('全部'), value: 'all' }, { label: t('全部'), value: 'all' },
@@ -141,25 +146,13 @@ const AdminTokensFilters = ({
{ label: t('企业'), value: 'org' }, { label: t('企业'), value: 'org' },
]} ]}
showClear={false} showClear={false}
pure
size='small'
className='w-full' className='w-full'
onChange={debouncedSearch}
/> />
</div> </div>
<div className='flex gap-2 w-full md:w-auto'>
<Button
type='tertiary'
htmlType='submit'
loading={loading || searching}
size='small'
>
{t('查询')}
</Button>
<Button type='tertiary' onClick={handleReset} size='small'>
{t('重置')}
</Button>
</div> </div>
<div className='admin-tokens-filter-actions'>
<Button onClick={handleReset}>{t('重置')}</Button>
<FilterSearchButton loading={loading || searching} />
</div> </div>
</Form> </Form>
); );
@@ -17,13 +17,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import TableEmpty from '../../common/table/TableEmpty';
import React, { useMemo } from 'react'; import React, { useMemo } from 'react';
import { Empty } from '@/components/ui';
import CardTable from '../../common/ui/CardTable'; import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getAdminTokensColumns } from './AdminTokensColumnDefs'; import { getAdminTokensColumns } from './AdminTokensColumnDefs';
const AdminTokensTable = ({ const AdminTokensTable = ({
@@ -32,7 +29,6 @@ const AdminTokensTable = ({
activePage, activePage,
pageSize, pageSize,
tokenCount, tokenCount,
compactMode,
selectedRowKeys, selectedRowKeys,
setSelectedRowKeys, setSelectedRowKeys,
handlePageChange, handlePageChange,
@@ -72,20 +68,6 @@ const AdminTokensTable = ({
[t], [t],
); );
const tableColumns = useMemo(
() =>
compactMode
? columns.map((col) => {
if (col.dataIndex === 'operate') {
const { fixed, ...rest } = col;
return rest;
}
return col;
})
: columns,
[compactMode, columns],
);
const rowSelection = { const rowSelection = {
selectedRowKeys, selectedRowKeys,
onChange: (keys) => setSelectedRowKeys(keys), onChange: (keys) => setSelectedRowKeys(keys),
@@ -93,10 +75,10 @@ const AdminTokensTable = ({
return ( return (
<CardTable <CardTable
columns={tableColumns} columns={columns}
dataSource={tokens} dataSource={tokens}
rowKey='id' rowKey='id'
scroll={compactMode ? undefined : { x: 'max-content' }} scroll={{ x: 'max-content' }}
pagination={{ pagination={{
currentPage: activePage, currentPage: activePage,
pageSize: pageSize, pageSize: pageSize,
@@ -110,17 +92,8 @@ const AdminTokensTable = ({
loading={loading} loading={loading}
onRow={handleRow} onRow={handleRow}
rowSelection={rowSelection} rowSelection={rowSelection}
empty={ empty={<TableEmpty />}
<Empty className='admin-tokens-table overflow-hidden'
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className='overflow-hidden'
size='middle' size='middle'
/> />
); );
@@ -0,0 +1,92 @@
.console-page .console-search-card .admin-tokens-filter-form {
display: block;
}
.admin-tokens-filter-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 1rem;
width: 100%;
}
.console-page .admin-tokens-filter-grid .ant-form-item-label > label {
color: var(--console-muted);
font-size: 13px;
}
.admin-tokens-filter-actions,
.admin-tokens-tools {
display: flex;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
gap: 0.5rem;
}
.admin-tokens-filter-actions {
margin-top: 1rem;
}
.admin-tokens-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 1.25rem;
width: 100%;
margin-bottom: 0.25rem;
}
.admin-tokens-tools {
margin-inline-start: auto;
}
.console-page .console-table.admin-tokens-table .ant-table-thead > tr > th {
height: 46px;
padding-block: 0;
font-weight: 400;
}
.admin-tokens-name {
font-weight: 700;
}
.admin-tokens-key {
font-family: SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;
font-size: 12px;
line-height: 21px;
}
.admin-tokens-status,
.admin-tokens-row-actions {
display: flex;
align-items: center;
gap: 6px;
}
.admin-tokens-status {
flex-wrap: wrap;
gap: 8px;
}
.admin-tokens-status .ant-tag {
margin-inline-end: 0;
}
.admin-tokens-row-actions .ant-btn {
height: auto;
padding: 0 4px;
font-size: 13px;
}
@media (max-width: 1100px) {
.admin-tokens-filter-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 768px) {
.admin-tokens-filter-grid {
grid-template-columns: minmax(0, 1fr);
}
}
+14 -20
View File
@@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React from 'react'; import React from 'react';
import './admin-tokens.css';
import CardPro from '../../common/ui/CardPro'; import CardPro from '../../common/ui/CardPro';
import AdminTokensTable from './AdminTokensTable'; import AdminTokensTable from './AdminTokensTable';
import AdminTokensActions from './AdminTokensActions'; import AdminTokensActions from './AdminTokensActions';
@@ -79,9 +80,6 @@ const AdminTokensPage = () => {
handlePageSizeChange, handlePageSizeChange,
handleRow, handleRow,
compactMode,
setCompactMode,
t, t,
} = data; } = data;
@@ -150,22 +148,7 @@ const AdminTokensPage = () => {
/> />
<CardPro <CardPro
type='type1' searchArea={
descriptionArea={
<AdminTokensDescription
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
}
actionsArea={
<div className='flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full'>
<AdminTokensActions
selectedRowKeys={selectedRowKeys}
onBatchAction={handleBatchClick}
onRefresh={refresh}
t={t}
/>
<AdminTokensFilters <AdminTokensFilters
formInitValues={formInitValues} formInitValues={formInitValues}
setFormApi={setFormApi} setFormApi={setFormApi}
@@ -178,9 +161,21 @@ const AdminTokensPage = () => {
searching={searching} searching={searching}
t={t} t={t}
/> />
}
type='type1'
actionsArea={
<div className='admin-tokens-toolbar'>
<AdminTokensDescription t={t} />
<AdminTokensActions
selectedRowKeys={selectedRowKeys}
onBatchAction={handleBatchClick}
onRefresh={refresh}
t={t}
/>
</div> </div>
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
showRange: false,
currentPage: activePage, currentPage: activePage,
pageSize: pageSize, pageSize: pageSize,
total: tokenCount, total: tokenCount,
@@ -197,7 +192,6 @@ const AdminTokensPage = () => {
activePage={activePage} activePage={activePage}
pageSize={pageSize} pageSize={pageSize}
tokenCount={tokenCount} tokenCount={tokenCount}
compactMode={compactMode}
selectedRowKeys={selectedRowKeys} selectedRowKeys={selectedRowKeys}
setSelectedRowKeys={setSelectedRowKeys} setSelectedRowKeys={setSelectedRowKeys}
handlePageChange={handlePageChange} handlePageChange={handlePageChange}
@@ -24,7 +24,7 @@ const { Text } = Typography;
const AdminDeleteTokenModal = ({ visible, onCancel, onConfirm, token, t }) => { const AdminDeleteTokenModal = ({ visible, onCancel, onConfirm, token, t }) => {
if (!token) return null; if (!token) return null;
const isOrgToken = token.organization_id && token.organization_id > 0; const isOrgToken = token.organization_id > 0;
return ( return (
<Modal <Modal
@@ -20,10 +20,7 @@ For commercial licensing, please contact support@quantumnous.com
import React, { useEffect, useRef, useState } from 'react'; import React, { useEffect, useRef, useState } from 'react';
import { Modal, Form, Typography, Banner, Spin, Tag } from '@/components/ui'; import { Modal, Form, Typography, Banner, Spin, Tag } from '@/components/ui';
import { API, showError, renderQuotaWithPrompt } from '../../../../helpers'; import { API, showError, renderQuotaWithPrompt } from '../../../../helpers';
import { import { quotaToMoney, moneyToQuota } from '../../../common/ui/QuotaInput';
quotaToMoney,
moneyToQuota,
} from '../../../common/ui/QuotaInput';
const { Text } = Typography; const { Text } = Typography;
@@ -131,7 +128,7 @@ const AdminEditTokenModal = ({
if (!token) return null; if (!token) return null;
const isOrgToken = token.organization_id && token.organization_id > 0; const isOrgToken = token.organization_id > 0;
const curStatusMeta = statusMeta[token.status] || statusMeta[2]; const curStatusMeta = statusMeta[token.status] || statusMeta[2];
return ( return (
@@ -18,14 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React from 'react'; import React from 'react';
import { import { Button, Dropdown, Modal, Switch, Typography } from '@/components/ui';
Button,
Dropdown,
Modal,
Switch,
Typography,
Select,
} from '@/components/ui';
import CompactModeToggle from '../../common/ui/CompactModeToggle'; import CompactModeToggle from '../../common/ui/CompactModeToggle';
import { isRoot } from '../../../helpers'; import { isRoot } from '../../../helpers';
@@ -40,7 +33,7 @@ const renderBatchDeleteContent = (t) => (
); );
const ChannelsActions = ({ const ChannelsActions = ({
enableBatchDelete, selectedChannels,
batchDeleteChannels, batchDeleteChannels,
setShowBatchSetTag, setShowBatchSetTag,
testAllChannels, testAllChannels,
@@ -50,17 +43,9 @@ const ChannelsActions = ({
compactMode, compactMode,
setCompactMode, setCompactMode,
idSort, idSort,
setIdSort,
setEnableBatchDelete,
enableTagMode, enableTagMode,
setEnableTagMode, setEnableTagMode,
statusFilter,
setStatusFilter,
getFormValues,
loadChannels, loadChannels,
searchChannels,
activeTypeKey,
activePage,
pageSize, pageSize,
setActivePage, setActivePage,
t, t,
@@ -74,7 +59,7 @@ const ChannelsActions = ({
{isRoot() && ( {isRoot() && (
<Button <Button
size='small' size='small'
disabled={!enableBatchDelete} disabled={!selectedChannels.length}
type='danger' type='danger'
className='w-full md:w-auto' className='w-full md:w-auto'
onClick={() => { onClick={() => {
@@ -92,7 +77,7 @@ const ChannelsActions = ({
{isRoot() && ( {isRoot() && (
<Button <Button
size='small' size='small'
disabled={!enableBatchDelete} disabled={!selectedChannels.length}
type='tertiary' type='tertiary'
onClick={() => setShowBatchSetTag(true)} onClick={() => setShowBatchSetTag(true)}
className='w-full md:w-auto' className='w-full md:w-auto'
@@ -209,54 +194,6 @@ const ChannelsActions = ({
{/* 右侧:设置开关区域 */} {/* 右侧:设置开关区域 */}
<div className='flex flex-col md:flex-row items-start md:items-center gap-2 w-full md:w-auto order-1 md:order-2'> <div className='flex flex-col md:flex-row items-start md:items-center gap-2 w-full md:w-auto order-1 md:order-2'>
<div className='flex items-center justify-between w-full md:w-auto'>
<Typography.Text strong className='mr-2'>
{t('使用ID排序')}
</Typography.Text>
<Switch
size='small'
checked={idSort}
onChange={(v) => {
localStorage.setItem('id-sort', v + '');
setIdSort(v);
const { searchKeyword, searchGroup, searchModel } =
getFormValues();
if (
searchKeyword === '' &&
searchGroup === '' &&
searchModel === ''
) {
loadChannels(activePage, pageSize, v, enableTagMode);
} else {
searchChannels(
enableTagMode,
activeTypeKey,
statusFilter,
activePage,
pageSize,
v,
);
}
}}
/>
</div>
{isRoot() && (
<div className='flex items-center justify-between w-full md:w-auto'>
<Typography.Text strong className='mr-2'>
{t('开启批量操作')}
</Typography.Text>
<Switch
size='small'
checked={enableBatchDelete}
onChange={(v) => {
localStorage.setItem('enable-batch-delete', v + '');
setEnableBatchDelete(v);
}}
/>
</div>
)}
<div className='flex items-center justify-between w-full md:w-auto'> <div className='flex items-center justify-between w-full md:w-auto'>
<Typography.Text strong className='mr-2'> <Typography.Text strong className='mr-2'>
{t('标签聚合模式')} {t('标签聚合模式')}
@@ -272,33 +209,6 @@ const ChannelsActions = ({
}} }}
/> />
</div> </div>
<div className='flex items-center justify-between w-full md:w-auto'>
<Typography.Text strong className='mr-2'>
{t('状态筛选')}
</Typography.Text>
<Select
size='small'
value={statusFilter}
onChange={(v) => {
localStorage.setItem('channel-status-filter', v);
setStatusFilter(v);
setActivePage(1);
loadChannels(
1,
pageSize,
idSort,
enableTagMode,
activeTypeKey,
v,
);
}}
>
<Select.Option value='all'>{t('全部')}</Select.Option>
<Select.Option value='enabled'>{t('已启用')}</Select.Option>
<Select.Option value='disabled'>{t('已禁用')}</Select.Option>
</Select>
</div>
</div> </div>
</div> </div>
</div> </div>
@@ -17,15 +17,15 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import React from 'react'; import { writeClipboardText } from '../../../helpers/clipboard';
import React, { useState } from 'react';
import { Switch } from 'antd';
import { import {
Button, Button,
Dropdown,
InputNumber, InputNumber,
Modal, Modal,
Progress, Progress,
Space, Space,
SplitButtonGroup,
Tag, Tag,
Tooltip, Tooltip,
} from '@/components/ui'; } from '@/components/ui';
@@ -42,9 +42,39 @@ import {
hoverOrClickTrigger, hoverOrClickTrigger,
} from '../../../helpers'; } from '../../../helpers';
import { CHANNEL_OPTIONS } from '../../../constants'; import { CHANNEL_OPTIONS } from '../../../constants';
import { IconTreeTriangleDown, IconMore } from '@/components/ui/icons'; import { IconTreeTriangleDown } from '@/components/ui/icons';
import { ShuffleBrandIcon } from '../../common/icons/BrandIcons'; import { ShuffleBrandIcon } from '../../common/icons/BrandIcons';
function ChannelStatusSwitch({ record, manageChannel, t }) {
const [loading, setLoading] = useState(false);
return (
<Switch
size='small'
checked={record.status === 1}
checkedChildren={t('启用')}
unCheckedChildren={t('禁用')}
disabled={!isRoot()}
loading={loading}
aria-label={t('状态')}
onClick={(_, event) => event.stopPropagation()}
onChange={async (checked) => {
setLoading(true);
try {
await manageChannel(
record.id,
checked ? 'enable' : 'disable',
record,
);
} catch (error) {
showError(error.message);
} finally {
setLoading(false);
}
}}
/>
);
}
// 删除单个渠道的确认文案:若该渠道被其他渠道列为兜底,追加影响说明。 // 删除单个渠道的确认文案:若该渠道被其他渠道列为兜底,追加影响说明。
// 查询失败不阻塞删除,仅回退为原确认文案 // 查询失败不阻塞删除,仅回退为原确认文案
const buildDeleteConfirmContent = async (channelId, t) => { const buildDeleteConfirmContent = async (channelId, t) => {
@@ -360,8 +390,7 @@ export const getChannelsColumns = ({
theme='outline' theme='outline'
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
navigator.clipboard writeClipboardText(record.remark)
.writeText(record.remark)
.then(() => { .then(() => {
showSuccess(t('复制成功')); showSuccess(t('复制成功'));
}) })
@@ -425,13 +454,46 @@ export const getChannelsColumns = ({
title: t('状态'), title: t('状态'),
dataIndex: 'status', dataIndex: 'status',
render: (text, record, index) => { render: (text, record, index) => {
const statusControl =
record.children !== undefined ? (
renderStatus(text, record.channel_info, t)
) : (
<Space>
<ChannelStatusSwitch
record={record}
manageChannel={manageChannel}
t={t}
/>
{record.channel_info?.is_multi_key && (
<span>
{(record.channel_info.multi_key_size || 0) -
Object.keys(record.channel_info.multi_key_status_list || {})
.length}
/{record.channel_info.multi_key_size || 0}
</span>
)}
</Space>
);
if (text === 3) { if (text === 3) {
if (record.other_info === '') { let otherInfo;
record.other_info = '{}'; try {
otherInfo =
typeof record.other_info === 'string'
? JSON.parse(record.other_info)
: record.other_info;
} catch {
return statusControl;
} }
let otherInfo = JSON.parse(record.other_info); if (
let reason = otherInfo['status_reason']; !otherInfo ||
let time = otherInfo['status_time']; typeof otherInfo !== 'object' ||
Array.isArray(otherInfo) ||
(!otherInfo.status_reason && !otherInfo.status_time)
) {
return statusControl;
}
const reason = otherInfo.status_reason || '';
const time = otherInfo.status_time;
return ( return (
<div> <div>
<Tooltip <Tooltip
@@ -439,12 +501,12 @@ export const getChannelsColumns = ({
t('原因:') + reason + t(',时间:') + timestamp2string(time) t('原因:') + reason + t(',时间:') + timestamp2string(time)
} }
> >
{renderStatus(text, record.channel_info, t)} {statusControl}
</Tooltip> </Tooltip>
</div> </div>
); );
} else { } else {
return renderStatus(text, record.channel_info, t); return statusControl;
} }
}, },
}, },
@@ -660,7 +722,7 @@ export const getChannelsColumns = ({
}, },
{ {
key: COLUMN_KEYS.OPERATE, key: COLUMN_KEYS.OPERATE,
title: '', title: t('操作'),
dataIndex: 'operate', dataIndex: 'operate',
fixed: 'right', fixed: 'right',
render: (text, record, index) => { render: (text, record, index) => {
@@ -704,56 +766,28 @@ export const getChannelsColumns = ({
]; ];
return ( return (
<Space wrap> <Space wrap className='console-module-row-actions'>
{isRoot() && ( {isRoot() && (
<SplitButtonGroup <>
className='overflow-hidden'
aria-label={t('测试单个渠道操作项目组')}
>
<Button <Button
type='link'
size='small' size='small'
type='tertiary'
onClick={() => testChannel(record, '')} onClick={() => testChannel(record, '')}
> >
{t('测试')} {t('测试')}
</Button> </Button>
<Button <Button
type='link'
size='small' size='small'
type='tertiary'
icon={<IconTreeTriangleDown />}
onClick={() => { onClick={() => {
setCurrentTestChannel(record); setCurrentTestChannel(record);
setShowModelTestModal(true); setShowModelTestModal(true);
}} }}
/>
</SplitButtonGroup>
)}
{isRoot() && (
<>
{record.status === 1 ? (
<Button
type='danger'
size='small'
onClick={() =>
manageChannel(record.id, 'disable', record)
}
> >
{t('禁用')} {t('批量测试')}
</Button> </Button>
) : (
<Button <Button
size='small' type='link'
onClick={() => manageChannel(record.id, 'enable', record)}
>
{t('启用')}
</Button>
)}
{record.channel_info?.is_multi_key ? (
<SplitButtonGroup aria-label={t('多密钥渠道操作项目组')}>
<Button
type='tertiary'
size='small' size='small'
onClick={() => { onClick={() => {
setEditingChannel(record); setEditingChannel(record);
@@ -762,47 +796,33 @@ export const getChannelsColumns = ({
> >
{t('编辑')} {t('编辑')}
</Button> </Button>
<Dropdown <Button
trigger='click' type='link'
position='bottomRight' danger
menu={[ size='small'
{ onClick={moreMenuItems[0].onClick}
node: 'item', >
name: t('多密钥管理'), {t('删除')}
onClick: () => { </Button>
<Button
type='link'
size='small'
onClick={moreMenuItems[1].onClick}
>
{t('复制')}
</Button>
{record.channel_info?.is_multi_key && (
<Button
type='link'
size='small'
onClick={() => {
setCurrentMultiKeyChannel(record); setCurrentMultiKeyChannel(record);
setShowMultiKeyManageModal(true); setShowMultiKeyManageModal(true);
},
},
]}
>
<Button
type='tertiary'
size='small'
icon={<IconTreeTriangleDown />}
/>
</Dropdown>
</SplitButtonGroup>
) : (
<Button
type='tertiary'
size='small'
onClick={() => {
setEditingChannel(record);
setShowEdit(true);
}} }}
> >
{t('编辑')} {t('多密钥管理')}
</Button> </Button>
)} )}
<Dropdown
trigger='click'
position='bottomRight'
menu={moreMenuItems}
>
<Button icon={<IconMore />} type='tertiary' size='small' />
</Dropdown>
</> </>
)} )}
</Space> </Space>
@@ -814,21 +834,21 @@ export const getChannelsColumns = ({
{isRoot() && ( {isRoot() && (
<> <>
<Button <Button
type='tertiary' type='link'
size='small' size='small'
onClick={() => manageTag(record.key, 'enable')} onClick={() => manageTag(record.key, 'enable')}
> >
{t('启用全部')} {t('启用全部')}
</Button> </Button>
<Button <Button
type='tertiary' type='link'
size='small' size='small'
onClick={() => manageTag(record.key, 'disable')} onClick={() => manageTag(record.key, 'disable')}
> >
{t('禁用全部')} {t('禁用全部')}
</Button> </Button>
<Button <Button
type='tertiary' type='link'
size='small' size='small'
onClick={() => { onClick={() => {
setShowEditTag(true); setShowEditTag(true);
@@ -18,15 +18,12 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React from 'react'; import React from 'react';
import { Button, Form } from '@/components/ui'; import { Form } from '@/components/ui';
import { IconSearch } from '@/components/ui/icons'; import { IconSearch } from '@/components/ui/icons';
import { isRoot } from '../../../helpers'; import { ConsoleFilterActions } from '../../console/ConsoleModuleFilters';
import { useFilterSearch } from '../../../hooks/common/useFilterSearch';
const ChannelsFilters = ({ const ChannelsFilters = ({
setEditingChannel,
setShowEdit,
refresh,
setShowColumnSelector,
formInitValues, formInitValues,
setFormApi, setFormApi,
searchChannels, searchChannels,
@@ -37,103 +34,67 @@ const ChannelsFilters = ({
searching, searching,
autoBanExclusionFilter, autoBanExclusionFilter,
setAutoBanExclusionFilter, setAutoBanExclusionFilter,
statusFilter,
setStatusFilter,
t, t,
}) => { }) => {
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
() => searchChannels(enableTagMode),
);
return ( return (
<div className='flex flex-col md:flex-row justify-between items-center gap-2 w-full'> <div className='w-full'>
<div className='flex gap-2 w-full md:w-auto order-2 md:order-1'>
{isRoot() && (
<Button
size='small'
theme='light'
type='primary'
className='w-full md:w-auto'
onClick={() => {
setEditingChannel({
id: undefined,
});
setShowEdit(true);
}}
>
{t('添加渠道')}
</Button>
)}
<Button
size='small'
type='tertiary'
className='w-full md:w-auto'
onClick={refresh}
>
{t('刷新')}
</Button>
<Button
size='small'
type='tertiary'
onClick={() => setShowColumnSelector(true)}
className='w-full md:w-auto'
>
{t('列设置')}
</Button>
</div>
<div className='flex flex-col md:flex-row items-center gap-2 w-full md:w-auto order-1 md:order-2'> <div className='flex flex-col md:flex-row items-center gap-2 w-full md:w-auto order-1 md:order-2'>
<Form <Form
initValues={formInitValues} initValues={{
...formInitValues,
searchGroup: formInitValues.searchGroup || undefined,
}}
getFormApi={(api) => setFormApi(api)} getFormApi={(api) => setFormApi(api)}
onSubmit={() => searchChannels(enableTagMode)} onSubmit={submitSearch}
onValueChange={scheduleSearch}
allowEmpty={true} allowEmpty={true}
autoComplete='off' autoComplete='off'
layout='horizontal' layout='vertical'
trigger='change' trigger='change'
stopValidateWithError={false} stopValidateWithError={false}
className='flex flex-col md:flex-row items-center gap-2 w-full' className='console-module-filter-form'
> >
<div className='relative w-full md:w-64'> <div className='console-module-filter-grid'>
<div className='console-module-field'>
<Form.Input <Form.Input
label={t('渠道ID,名称,密钥,API地址')}
size='small' size='small'
field='searchKeyword' field='searchKeyword'
prefix={<IconSearch />} prefix={<IconSearch />}
placeholder={t('渠道ID,名称,密钥,API地址')} placeholder={t('渠道ID,名称,密钥,API地址')}
showClear showClear
pure
/> />
</div> </div>
<div className='w-full md:w-48'> <div className='console-module-field'>
<Form.Input <Form.Input
label={t('模型名称')}
size='small' size='small'
field='searchModel' field='searchModel'
prefix={<IconSearch />} prefix={<IconSearch />}
placeholder={t('模型关键字')} placeholder={t('模型关键字')}
showClear showClear
pure
/> />
</div> </div>
<div className='w-full md:w-32'> <div className='console-module-field'>
<Form.Select <Form.Select
label={t('分组')}
size='small' size='small'
field='searchGroup' field='searchGroup'
placeholder={t('选择分组')} placeholder={t('选择分组')}
optionList={[ optionList={[...groupOptions]}
{ label: t('选择分组'), value: null },
...groupOptions,
]}
className='w-full' className='w-full'
showClear showClear
pure
onChange={() => {
// 延迟执行搜索,让表单值先更新
setTimeout(() => {
searchChannels(enableTagMode);
}, 0);
}}
/> />
</div> </div>
<div className='w-full md:w-32'> <div className='console-module-field'>
<Form.Select <Form.Select
label={t('自动封禁')}
size='small' size='small'
field='autoBanExclusionFilter'
placeholder={t('自动封禁')} placeholder={t('自动封禁')}
value={autoBanExclusionFilter} value={autoBanExclusionFilter}
optionList={[ optionList={[
@@ -143,7 +104,6 @@ const ChannelsFilters = ({
]} ]}
className='w-full' className='w-full'
showClear showClear
pure
onChange={(value) => { onChange={(value) => {
const newValue = value || 'all'; const newValue = value || 'all';
localStorage.setItem( localStorage.setItem(
@@ -151,34 +111,45 @@ const ChannelsFilters = ({
newValue, newValue,
); );
setAutoBanExclusionFilter(newValue); setAutoBanExclusionFilter(newValue);
scheduleSearch();
}} }}
/> />
</div> </div>
<Button <div className='console-module-field'>
size='small' <Form.Select
type='tertiary' label={t('状态')}
htmlType='submit' placeholder={t('全部状态')}
value={statusFilter}
onChange={(value) => {
localStorage.setItem('channel-status-filter', value);
setStatusFilter(value);
scheduleSearch();
}}
optionList={[
{ label: t('全部'), value: 'all' },
{ label: t('已启用'), value: 'enabled' },
{ label: t('已禁用'), value: 'disabled' },
]}
/>
</div>
</div>
<ConsoleFilterActions
loading={loading || searching} loading={loading || searching}
className='w-full md:w-auto' onReset={() => {
>
{t('查询')}
</Button>
<Button
size='small'
type='tertiary'
onClick={() => {
if (formApi) { if (formApi) {
formApi.reset(); formApi.reset();
cancelPendingSearch();
setStatusFilter('all');
setAutoBanExclusionFilter('all');
localStorage.setItem('channel-status-filter', 'all');
localStorage.setItem('channel-autoban-exclusion-filter', 'all');
// 重置后立即查询,使用setTimeout确保表单重置完成 // 重置后立即查询,使用setTimeout确保表单重置完成
setTimeout(() => { setTimeout(() => {
refresh(); searchChannels(enableTagMode, undefined, 'all');
}, 100); }, 100);
} }
}} }}
className='w-full md:w-auto' />
>
{t('重置')}
</Button>
</Form> </Form>
</div> </div>
</div> </div>
+47 -21
View File
@@ -17,13 +17,11 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { useMemo } from 'react'; import TableEmpty from '../../common/table/TableEmpty';
import { Empty } from '@/components/ui'; import React, { useMemo, useState } from 'react';
import CardTable from '../../common/ui/CardTable'; import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult, import { isRoot } from '../../../helpers';
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getChannelsColumns } from './ChannelsColumnDefs'; import { getChannelsColumns } from './ChannelsColumnDefs';
const ChannelsTable = (channelsData) => { const ChannelsTable = (channelsData) => {
@@ -34,7 +32,7 @@ const ChannelsTable = (channelsData) => {
activePage, activePage,
pageSize, pageSize,
channelCount, channelCount,
enableBatchDelete, selectedChannels,
compactMode, compactMode,
visibleColumns, visibleColumns,
setSelectedChannels, setSelectedChannels,
@@ -66,8 +64,25 @@ const ChannelsTable = (channelsData) => {
autoBanExclusionFilter, autoBanExclusionFilter,
// Daily quota info // Daily quota info
dailyQuotaInfo, dailyQuotaInfo,
idSort,
setIdSort,
enableTagMode,
loadChannels,
} = channelsData; } = channelsData;
const [idSortOrder, setIdSortOrder] = useState('descend');
const handleTableChange = ({ sorter, extra, action }) => {
if ((action ?? extra?.action) !== 'sort') return;
const order = sorter?.columnKey === COLUMN_KEYS.ID ? sorter.order : null;
setIdSortOrder(order || 'descend');
const nextIdSort = Boolean(order);
if (nextIdSort === idSort) return;
localStorage.setItem('id-sort', String(nextIdSort));
setIdSort(nextIdSort);
loadChannels(activePage, pageSize, nextIdSort, enableTagMode);
};
// Filter channels based on auto-ban exclusion filter // Filter channels based on auto-ban exclusion filter
const filteredChannels = useMemo(() => { const filteredChannels = useMemo(() => {
if (!autoBanExclusionFilter || autoBanExclusionFilter === 'all') { if (!autoBanExclusionFilter || autoBanExclusionFilter === 'all') {
@@ -174,14 +189,28 @@ const ChannelsTable = (channelsData) => {
}, [visibleColumns, allColumns]); }, [visibleColumns, allColumns]);
const tableColumns = useMemo(() => { const tableColumns = useMemo(() => {
const sortableColumns = visibleColumnsList.map((column) =>
column.key === COLUMN_KEYS.ID
? {
...column,
sorter: (a, b) => {
if (a.children !== undefined || b.children !== undefined)
return 0;
return Number(a.id) - Number(b.id);
},
sortOrder: idSort ? idSortOrder : null,
}
: column,
);
return compactMode return compactMode
? visibleColumnsList.map(({ fixed, ...rest }) => rest) ? sortableColumns.map(({ fixed, ...rest }) => rest)
: visibleColumnsList; : sortableColumns;
}, [compactMode, visibleColumnsList]); }, [compactMode, visibleColumnsList, COLUMN_KEYS.ID, idSort, idSortOrder]);
return ( return (
<CardTable <CardTable
columns={tableColumns} columns={tableColumns}
onChange={handleTableChange}
dataSource={filteredChannels} dataSource={filteredChannels}
scroll={compactMode ? undefined : { x: 'max-content' }} scroll={compactMode ? undefined : { x: 'max-content' }}
pagination={{ pagination={{
@@ -197,24 +226,21 @@ const ChannelsTable = (channelsData) => {
expandAllRows={false} expandAllRows={false}
onRow={handleRow} onRow={handleRow}
rowSelection={ rowSelection={
enableBatchDelete isRoot()
? { ? {
selectedRowKeys: selectedChannels.map(
(channel) => channel.key ?? String(channel.id),
),
getCheckboxProps: (record) => ({
disabled: record.children !== undefined,
}),
onChange: (selectedRowKeys, selectedRows) => { onChange: (selectedRowKeys, selectedRows) => {
setSelectedChannels(selectedRows); setSelectedChannels(selectedRows);
}, },
} }
: null : null
} }
empty={ empty={<TableEmpty />}
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className='rounded-xl overflow-hidden' className='rounded-xl overflow-hidden'
size='middle' size='middle'
loading={loading || searching} loading={loading || searching}
+29 -5
View File
@@ -19,8 +19,11 @@ For commercial licensing, please contact support@quantumnous.com
import React from 'react'; import React from 'react';
import { Tabs, TabPane, Tag } from '@/components/ui'; import { Tabs, TabPane, Tag } from '@/components/ui';
import { Button } from 'antd';
import { Plus } from 'lucide-react';
import { CHANNEL_OPTIONS } from '../../../constants'; import { CHANNEL_OPTIONS } from '../../../constants';
import { getChannelIcon } from '../../../helpers'; import { getChannelIcon, isRoot } from '../../../helpers';
import './channels-tabs.css';
const ChannelsTabs = ({ const ChannelsTabs = ({
enableTagMode, enableTagMode,
@@ -33,9 +36,30 @@ const ChannelsTabs = ({
pageSize, pageSize,
idSort, idSort,
setActivePage, setActivePage,
setEditingChannel,
setShowEdit,
t, t,
}) => { }) => {
if (enableTagMode) return null; const createButton = isRoot() ? (
<Button
className='console-create-action'
type='primary'
size='middle'
icon={<Plus size={16} />}
onClick={() => {
setEditingChannel({ id: undefined });
setShowEdit(true);
}}
>
{t('创建渠道')}
</Button>
) : null;
if (enableTagMode) {
return createButton ? (
<div className='flex justify-end'>{createButton}</div>
) : null;
}
const handleTabChange = (key) => { const handleTabChange = (key) => {
setActiveTypeKey(key); setActiveTypeKey(key);
@@ -46,10 +70,10 @@ const ChannelsTabs = ({
return ( return (
<Tabs <Tabs
activeKey={activeTypeKey} activeKey={activeTypeKey}
type='card' type='line'
collapsible
onChange={handleTabChange} onChange={handleTabChange}
className='mb-2' className='channels-tabs mb-2'
tabBarExtraContent={createButton}
> >
<TabPane <TabPane
itemKey='all' itemKey='all'
@@ -0,0 +1,5 @@
.channels-tabs > .ant-tabs-nav > .ant-tabs-extra-content {
align-self: flex-end;
/* Match the space below the tab labels above the navigation divider. */
margin-bottom: 12px;
}
+10
View File
@@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
import React from 'react'; import React from 'react';
import CardPro from '../../common/ui/CardPro'; import CardPro from '../../common/ui/CardPro';
import { ColumnSettingsButton } from '../../common/table/ColumnSettings';
import ChannelsTable from './ChannelsTable'; import ChannelsTable from './ChannelsTable';
import ChannelsActions from './ChannelsActions'; import ChannelsActions from './ChannelsActions';
import ChannelsFilters from './ChannelsFilters'; import ChannelsFilters from './ChannelsFilters';
@@ -64,11 +65,20 @@ const ChannelsPage = () => {
{/* Main Content */} {/* Main Content */}
<CardPro <CardPro
tableTitle={channelsData.t('渠道列表')}
tableActionsOffset
type='type3' type='type3'
tabsArea={<ChannelsTabs {...channelsData} />} tabsArea={<ChannelsTabs {...channelsData} />}
actionsArea={<ChannelsActions {...channelsData} />} actionsArea={<ChannelsActions {...channelsData} />}
searchArea={<ChannelsFilters {...channelsData} />} searchArea={<ChannelsFilters {...channelsData} />}
tableActions={
<ColumnSettingsButton
open={channelsData.showColumnSelector}
onClick={() => channelsData.setShowColumnSelector(true)}
/>
}
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
showRange: false,
currentPage: channelsData.activePage, currentPage: channelsData.activePage,
pageSize: channelsData.pageSize, pageSize: channelsData.pageSize,
total: channelsData.channelCount, total: channelsData.channelCount,
@@ -18,16 +18,15 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React from 'react'; import React from 'react';
import { Modal, Button, Checkbox } from '@/components/ui'; import { ColumnVisibilitySettings } from '../../../common/table/ColumnSettings';
import { getChannelsColumns } from '../ChannelsColumnDefs'; import { getChannelsColumns } from '../ChannelsColumnDefs';
const ColumnSelectorModal = ({ const ColumnSelectorModal = ({
showColumnSelector, showColumnSelector,
setShowColumnSelector, setShowColumnSelector,
visibleColumns, visibleColumns,
handleColumnVisibilityChange, setVisibleColumns,
handleSelectAll, getDefaultColumnVisibility,
initDefaultColumns,
COLUMN_KEYS, COLUMN_KEYS,
t, t,
// Props needed for getChannelsColumns // Props needed for getChannelsColumns
@@ -69,59 +68,14 @@ const ColumnSelectorModal = ({
}); });
return ( return (
<Modal <ColumnVisibilitySettings
title={t('列设置')} showColumnSelector={showColumnSelector}
visible={showColumnSelector} setShowColumnSelector={setShowColumnSelector}
onCancel={() => setShowColumnSelector(false)} columns={allColumns.filter((column) => !!column.title)}
footer={ visibleColumns={visibleColumns}
<div className='flex justify-end'> setVisibleColumns={setVisibleColumns}
<Button onClick={() => initDefaultColumns()}>{t('重置')}</Button> getDefaultColumnVisibility={getDefaultColumnVisibility}
<Button onClick={() => setShowColumnSelector(false)}> />
{t('取消')}
</Button>
<Button onClick={() => setShowColumnSelector(false)}>
{t('确定')}
</Button>
</div>
}
>
<div style={{ marginBottom: 20 }}>
<Checkbox
checked={Object.values(visibleColumns).every((v) => v === true)}
indeterminate={
Object.values(visibleColumns).some((v) => v === true) &&
!Object.values(visibleColumns).every((v) => v === true)
}
onChange={(e) => handleSelectAll(e.target.checked)}
>
{t('全选')}
</Checkbox>
</div>
<div
className='flex flex-wrap max-h-96 overflow-y-auto rounded-lg p-4'
style={{ border: '1px solid var(--ui-color-border)' }}
>
{allColumns.map((column) => {
// Skip columns without title
if (!column.title) {
return null;
}
return (
<div key={column.key} className='w-1/2 mb-4 pr-2'>
<Checkbox
checked={!!visibleColumns[column.key]}
onChange={(e) =>
handleColumnVisibilityChange(column.key, e.target.checked)
}
>
{column.title}
</Checkbox>
</div>
);
})}
</div>
</Modal>
); );
}; };
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import '../../../console/module-alignment.css';
import React, { useEffect, useState, useRef, useMemo } from 'react'; import React, { useEffect, useState, useRef, useMemo } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { import {
@@ -60,18 +61,14 @@ import ChannelKeyDisplay from '../../../common/ui/ChannelKeyDisplay';
import { useSecureVerification } from '../../../../hooks/common/useSecureVerification'; import { useSecureVerification } from '../../../../hooks/common/useSecureVerification';
import { createApiCalls } from '../../../../services/secureVerification'; import { createApiCalls } from '../../../../services/secureVerification';
import { import {
IconSave,
IconClose,
IconServer, IconServer,
IconSetting, IconSetting,
IconCode, IconCode,
IconGlobe, IconGlobe,
IconBolt, IconBolt,
IconChevronUp,
IconChevronDown,
} from '@/components/ui/icons'; } from '@/components/ui/icons';
const { Text, Title } = Typography; const { Text } = Typography;
const MODEL_MAPPING_EXAMPLE = { const MODEL_MAPPING_EXAMPLE = {
'gpt-3.5-turbo': 'gpt-3.5-turbo-0125', 'gpt-3.5-turbo': 'gpt-3.5-turbo-0125',
@@ -351,23 +348,6 @@ const EditChannelModal = (props) => {
t, t,
]); ]);
// 表单块导航相关状态
const formSectionRefs = useRef({
basicInfo: null,
apiConfig: null,
modelConfig: null,
advancedSettings: null,
channelExtraSettings: null,
});
const [currentSectionIndex, setCurrentSectionIndex] = useState(0);
const formSections = [
'basicInfo',
'apiConfig',
'modelConfig',
'advancedSettings',
'channelExtraSettings',
];
const formContainerRef = useRef(null);
const doubaoApiClickCountRef = useRef(0); const doubaoApiClickCountRef = useRef(0);
const initialModelsRef = useRef([]); const initialModelsRef = useRef([]);
const initialModelMappingRef = useRef(''); const initialModelMappingRef = useRef('');
@@ -411,43 +391,6 @@ const EditChannelModal = (props) => {
}); });
}; };
// 表单导航功能
const scrollToSection = (sectionKey) => {
const sectionElement = formSectionRefs.current[sectionKey];
if (sectionElement) {
sectionElement.scrollIntoView({
behavior: 'smooth',
block: 'start',
inline: 'nearest',
});
}
};
const navigateToSection = (direction) => {
const availableSections = formSections.filter((section) => {
if (section === 'apiConfig') {
return showApiConfigCard;
}
return true;
});
let newIndex;
if (direction === 'up') {
newIndex =
currentSectionIndex > 0
? currentSectionIndex - 1
: availableSections.length - 1;
} else {
newIndex =
currentSectionIndex < availableSections.length - 1
? currentSectionIndex + 1
: 0;
}
setCurrentSectionIndex(newIndex);
scrollToSection(availableSections[newIndex]);
};
const handleApiConfigSecretClick = () => { const handleApiConfigSecretClick = () => {
if (inputs.type !== 45) return; if (inputs.type !== 45) return;
const next = doubaoApiClickCountRef.current + 1; const next = doubaoApiClickCountRef.current + 1;
@@ -1055,8 +998,6 @@ const EditChannelModal = (props) => {
fetchModelGroups(); fetchModelGroups();
// 重置手动输入模式状态 // 重置手动输入模式状态
setUseManualInput(false); setUseManualInput(false);
// 重置导航状态
setCurrentSectionIndex(0);
} else { } else {
// 统一的模态框关闭重置逻辑 // 统一的模态框关闭重置逻辑
resetModalState(); resetModalState();
@@ -1655,7 +1596,7 @@ const EditChannelModal = (props) => {
const batchAllowed = !isEdit || isMultiKeyChannel; const batchAllowed = !isEdit || isMultiKeyChannel;
const batchExtra = batchAllowed ? ( const batchExtra = batchAllowed ? (
<Space> <Space wrap className='console-channel-key-actions'>
{!isEdit && ( {!isEdit && (
<Checkbox <Checkbox
disabled={isEdit} disabled={isEdit}
@@ -1827,76 +1768,25 @@ const EditChannelModal = (props) => {
return ( return (
<> <>
<SideSheet <SideSheet
placement={isEdit ? 'right' : 'left'} rootClassName='console-channel-drawer'
title={ classNames={{ header: 'console-channel-editor-header' }}
<Space> placement='right'
<Tag color='blue' shape='circle'> title={isEdit ? t('更新渠道信息') : t('创建新的渠道')}
{isEdit ? t('编辑') : t('新建')}
</Tag>
<Title heading={4} className='m-0'>
{isEdit ? t('更新渠道信息') : t('创建新的渠道')}
</Title>
</Space>
}
bodyStyle={{ padding: '0' }} bodyStyle={{ padding: '0' }}
visible={props.visible} visible={props.visible}
width={isMobile ? '100%' : 600} width={isMobile ? '100%' : 600}
footer={ footer={
<div className='flex justify-between items-center'> <div className='console-channel-footer'>
<div className='flex gap-2'> <Button onClick={handleCancel}>{t('取消')}</Button>
<Button
size='small'
type='tertiary'
icon={<IconChevronUp />}
onClick={() => navigateToSection('up')}
style={{
borderRadius: '50%',
width: '32px',
height: '32px',
padding: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
title={t('上一个表单块')}
/>
<Button
size='small'
type='tertiary'
icon={<IconChevronDown />}
onClick={() => navigateToSection('down')}
style={{
borderRadius: '50%',
width: '32px',
height: '32px',
padding: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
title={t('下一个表单块')}
/>
</div>
<Space>
<Button <Button
theme='solid' theme='solid'
type='primary'
onClick={() => formApiRef.current?.submitForm()} onClick={() => formApiRef.current?.submitForm()}
icon={<IconSave />}
> >
{t('提交')} {t('提交')}
</Button> </Button>
<Button
theme='light'
type='primary'
onClick={handleCancel}
icon={<IconClose />}
>
{t('取消')}
</Button>
</Space>
</div> </div>
} }
closeIcon={null}
onCancel={() => handleCancel()} onCancel={() => handleCancel()}
> >
<Form <Form
@@ -1907,16 +1797,12 @@ const EditChannelModal = (props) => {
> >
{() => ( {() => (
<Spin spinning={loading}> <Spin spinning={loading}>
<div className='p-2' ref={formContainerRef}> <div className='console-channel-sections p-2'>
<div ref={(el) => (formSectionRefs.current.basicInfo = el)}> <div>
<Card className='!rounded-2xl shadow-sm border-0 mb-6'> <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
{/* Header: Basic Info */} {/* Header: Basic Info */}
<div className='flex items-center mb-2'> <div className='console-channel-section'>
<Avatar <Avatar size='small' color='blue'>
size='small'
color='blue'
className='mr-2 shadow-md'
>
<IconServer size={16} /> <IconServer size={16} />
</Avatar> </Avatar>
<div> <div>
@@ -2438,9 +2324,8 @@ const EditChannelModal = (props) => {
<Form.Input <Form.Input
field='openai_organization' field='openai_organization'
label={t('组织')} label={t('组织')}
placeholder={t('请输入组织org-xxx')} placeholder={t('组织 org-xxx(留空使用默认组织)')}
showClear showClear
helpText={t('组织,不填则为默认组织')}
onChange={(value) => onChange={(value) =>
handleInputChange('openai_organization', value) handleInputChange('openai_organization', value)
} }
@@ -2451,18 +2336,14 @@ const EditChannelModal = (props) => {
{/* API Configuration Card */} {/* API Configuration Card */}
{showApiConfigCard && ( {showApiConfigCard && (
<div ref={(el) => (formSectionRefs.current.apiConfig = el)}> <div>
<Card className='!rounded-2xl shadow-sm border-0 mb-6'> <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
{/* Header: API Config */} {/* Header: API Config */}
<div <div
className='flex items-center mb-2' className='console-channel-section'
onClick={handleApiConfigSecretClick} onClick={handleApiConfigSecretClick}
> >
<Avatar <Avatar size='small' color='green'>
size='small'
color='green'
className='mr-2 shadow-md'
>
<IconGlobe size={16} /> <IconGlobe size={16} />
</Avatar> </Avatar>
<div> <div>
@@ -2679,15 +2560,11 @@ const EditChannelModal = (props) => {
)} )}
{/* Model Configuration Card */} {/* Model Configuration Card */}
<div ref={(el) => (formSectionRefs.current.modelConfig = el)}> <div>
<Card className='!rounded-2xl shadow-sm border-0 mb-6'> <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
{/* Header: Model Config */} {/* Header: Model Config */}
<div className='flex items-center mb-2'> <div className='console-channel-section'>
<Avatar <Avatar size='small' color='purple'>
size='small'
color='purple'
className='mr-2 shadow-md'
>
<IconCode size={16} /> <IconCode size={16} />
</Avatar> </Avatar>
<div> <div>
@@ -2740,7 +2617,7 @@ const EditChannelModal = (props) => {
}; };
}} }}
extraText={ extraText={
<Space wrap> <Space wrap className='console-channel-model-actions'>
<Button <Button
size='small' size='small'
type='primary' type='primary'
@@ -2778,13 +2655,15 @@ const EditChannelModal = (props) => {
<Button <Button
size='small' size='small'
type='tertiary' type='tertiary'
onClick={() => { onClick={async () => {
if (inputs.models.length === 0) { if (inputs.models.length === 0) {
showInfo(t('没有模型可以复制')); showInfo(t('没有模型可以复制'));
return; return;
} }
try { try {
copy(inputs.models.join(',')); if (!(await copy(inputs.models.join(',')))) {
throw new Error('Clipboard copy failed');
}
showSuccess(t('模型列表已复制到剪贴板')); showSuccess(t('模型列表已复制到剪贴板'));
} catch (error) { } catch (error) {
showError(t('复制失败')); showError(t('复制失败'));
@@ -2888,17 +2767,11 @@ const EditChannelModal = (props) => {
</div> </div>
{/* Advanced Settings Card */} {/* Advanced Settings Card */}
<div <div>
ref={(el) => (formSectionRefs.current.advancedSettings = el)}
>
<Card className='!rounded-2xl shadow-sm border-0 mb-6'> <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
{/* Header: Advanced Settings */} {/* Header: Advanced Settings */}
<div className='flex items-center mb-2'> <div className='console-channel-section'>
<Avatar <Avatar size='small' color='orange'>
size='small'
color='orange'
className='mr-2 shadow-md'
>
<IconSetting size={16} /> <IconSetting size={16} />
</Avatar> </Avatar>
<div> <div>
@@ -3432,19 +3305,11 @@ const EditChannelModal = (props) => {
</div> </div>
{/* Channel Extra Settings Card */} {/* Channel Extra Settings Card */}
<div <div>
ref={(el) =>
(formSectionRefs.current.channelExtraSettings = el)
}
>
<Card className='!rounded-2xl shadow-sm border-0 mb-6'> <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
{/* Header: Channel Extra Settings */} {/* Header: Channel Extra Settings */}
<div className='flex items-center mb-2'> <div className='console-channel-section'>
<Avatar <Avatar size='small' color='violet'>
size='small'
color='violet'
className='mr-2 shadow-md'
>
<IconBolt size={16} /> <IconBolt size={16} />
</Avatar> </Avatar>
<div> <div>
@@ -17,19 +17,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import React from 'react'; import React, { useState } from 'react';
import { import { Modal, Button, Input, Table, Tag, Typography, Select } from 'antd';
Modal, import { Search } from 'lucide-react';
Button,
Input,
Table,
Tag,
Typography,
Select,
} from '@/components/ui';
import { IconSearch } from '@/components/ui/icons';
import { copy, showError, showInfo, showSuccess } from '../../../../helpers'; import { copy, showError, showInfo, showSuccess } from '../../../../helpers';
import { MODEL_TABLE_PAGE_SIZE } from '../../../../constants'; import { MODEL_TABLE_PAGE_SIZE } from '../../../../constants';
import './model-test-modal.css';
const ModelTestModal = ({ const ModelTestModal = ({
showModelTestModal, showModelTestModal,
@@ -48,20 +41,20 @@ const ModelTestModal = ({
setModelTablePage, setModelTablePage,
selectedEndpointType, selectedEndpointType,
setSelectedEndpointType, setSelectedEndpointType,
allSelectingRef,
isMobile, isMobile,
t, t,
}) => { }) => {
const [paginationSize, setPaginationSize] = useState(MODEL_TABLE_PAGE_SIZE);
const hasChannel = Boolean(currentTestChannel); const hasChannel = Boolean(currentTestChannel);
const models =
const filteredModels = hasChannel typeof currentTestChannel?.models === 'string'
? currentTestChannel.models ? currentTestChannel.models.split(',').filter(Boolean)
.split(',')
.filter((model) =>
model.toLowerCase().includes(modelSearchKeyword.toLowerCase()),
)
: []; : [];
const filteredModels = models.filter((model) =>
model.toLowerCase().includes(modelSearchKeyword.toLowerCase()),
);
const endpointTypeOptions = [ const endpointTypeOptions = [
{ value: '', label: t('自动检测') }, { value: '', label: t('自动检测') },
{ value: 'openai', label: 'OpenAI (/v1/chat/completions)' }, { value: 'openai', label: 'OpenAI (/v1/chat/completions)' },
@@ -100,8 +93,7 @@ const ModelTestModal = ({
const handleSelectSuccess = () => { const handleSelectSuccess = () => {
if (!currentTestChannel) return; if (!currentTestChannel) return;
const successKeys = currentTestChannel.models const successKeys = models
.split(',')
.filter((m) => m.toLowerCase().includes(modelSearchKeyword.toLowerCase())) .filter((m) => m.toLowerCase().includes(modelSearchKeyword.toLowerCase()))
.filter((m) => { .filter((m) => {
const result = modelTestResults[`${currentTestChannel.id}-${m}`]; const result = modelTestResults[`${currentTestChannel.id}-${m}`];
@@ -126,34 +118,27 @@ const ModelTestModal = ({
{ {
title: t('状态'), title: t('状态'),
dataIndex: 'status', dataIndex: 'status',
width: 112,
render: (text, record) => { render: (text, record) => {
const testResult = const testResult =
modelTestResults[`${currentTestChannel.id}-${record.model}`]; modelTestResults[`${currentTestChannel.id}-${record.model}`];
const isTesting = testingModels.has(record.model); const isTesting = testingModels.has(record.model);
if (isTesting) { if (isTesting) {
return ( return <Tag color='processing'>{t('测试中')}</Tag>;
<Tag color='blue' shape='circle'>
{t('测试中')}
</Tag>
);
} }
if (!testResult) { if (!testResult) {
return ( return <Tag>{t('未开始')}</Tag>;
<Tag color='grey' shape='circle'>
{t('未开始')}
</Tag>
);
} }
return ( return (
<div className='flex items-center gap-2'> <div className='model-test-status'>
<Tag color={testResult.success ? 'green' : 'red'} shape='circle'> <Tag color={testResult.success ? 'success' : 'error'}>
{testResult.success ? t('成功') : t('失败')} {testResult.success ? t('成功') : t('失败')}
</Tag> </Tag>
{testResult.success && ( {testResult.success && (
<Typography.Text type='tertiary'> <Typography.Text type='secondary'>
{t('请求时长: ${time}s').replace( {t('请求时长: ${time}s').replace(
'${time}', '${time}',
testResult.time.toFixed(2), testResult.time.toFixed(2),
@@ -165,13 +150,15 @@ const ModelTestModal = ({
}, },
}, },
{ {
title: '', title: t('操作'),
dataIndex: 'operate', dataIndex: 'operate',
width: 72,
align: 'left',
render: (text, record) => { render: (text, record) => {
const isTesting = testingModels.has(record.model); const isTesting = testingModels.has(record.model);
return ( return (
<Button <Button
type='tertiary' type='link'
onClick={() => onClick={() =>
testChannel( testChannel(
currentTestChannel, currentTestChannel,
@@ -191,9 +178,7 @@ const ModelTestModal = ({
const dataSource = (() => { const dataSource = (() => {
if (!hasChannel) return []; if (!hasChannel) return [];
const start = (modelTablePage - 1) * MODEL_TABLE_PAGE_SIZE; return filteredModels.map((model) => ({
const end = start + MODEL_TABLE_PAGE_SIZE;
return filteredModels.slice(start, end).map((model) => ({
model, model,
key: model, key: model,
})); }));
@@ -202,114 +187,110 @@ const ModelTestModal = ({
return ( return (
<Modal <Modal
title={ title={
hasChannel ? ( hasChannel ? `${currentTestChannel.name} ${t('渠道的模型测试')}` : null
<div className='flex flex-col gap-2 w-full'>
<div className='flex items-center gap-2'>
<Typography.Text
strong
className='!text-[var(--ui-color-text-0)] !text-base'
>
{currentTestChannel.name} {t('渠道的模型测试')}
</Typography.Text>
<Typography.Text type='tertiary' size='small'>
{t('共')} {currentTestChannel.models.split(',').length}{' '}
{t('个模型')}
</Typography.Text>
</div>
</div>
) : null
} }
visible={showModelTestModal} open={showModelTestModal}
onCancel={handleCloseModal} onCancel={handleCloseModal}
footer={ footer={
hasChannel ? ( hasChannel ? (
<div className='flex justify-end'> <div className='model-test-footer'>
{isBatchTesting ? ( {isBatchTesting ? (
<Button type='danger' onClick={handleCloseModal}> <Button danger onClick={handleCloseModal}>
{t('停止测试')} {t('停止测试')}
</Button> </Button>
) : ( ) : (
<Button type='tertiary' onClick={handleCloseModal}> <Button onClick={handleCloseModal}>{t('取消')}</Button>
{t('取消')}
</Button>
)} )}
<Button <Button
type='primary'
onClick={batchTestModels} onClick={batchTestModels}
loading={isBatchTesting} loading={isBatchTesting}
disabled={isBatchTesting} disabled={isBatchTesting || selectedModelKeys.length === 0}
> >
{isBatchTesting {isBatchTesting ? t('测试中...') : t('批量测试')}
? t('测试中...')
: t('批量测试${count}个模型').replace(
'${count}',
filteredModels.length,
)}
</Button> </Button>
</div> </div>
) : null ) : null
} }
maskClosable={!isBatchTesting} maskClosable={!isBatchTesting}
className='!rounded-lg' rootClassName='console-overlay model-test-modal'
size={isMobile ? 'full-width' : 'large'} width={isMobile ? 'calc(100vw - 32px)' : 514.8}
centered
styles={{ body: { maxHeight: 'none', overflow: 'visible' } }}
> >
{hasChannel && ( {hasChannel && (
<div className='model-test-scroll'> <div className='model-test-content'>
{/* 端点类型选择器 */} {/* 端点类型选择器 */}
<div className='flex items-center gap-2 w-full mb-2'> <div className='model-test-endpoint'>
<Typography.Text strong>{t('端点类型')}:</Typography.Text> <Typography.Text strong id='model-test-endpoint-label'>
{t('端点类型')}:
</Typography.Text>
<Select <Select
value={selectedEndpointType} value={selectedEndpointType}
onChange={setSelectedEndpointType} onChange={setSelectedEndpointType}
optionList={endpointTypeOptions} options={endpointTypeOptions}
className='!w-full' aria-labelledby='model-test-endpoint-label'
placeholder={t('选择端点类型')} placeholder={t('选择端点类型')}
/> />
</div> </div>
{/* 搜索与操作按钮 */} {/* 搜索与操作按钮 */}
<div className='flex items-center justify-end gap-2 w-full mb-2'> <div className='model-test-toolbar'>
<Input <Input
placeholder={t('搜索模型...')} placeholder={t('搜索模型...')}
value={modelSearchKeyword} value={modelSearchKeyword}
onChange={(v) => { onChange={(event) => {
setModelSearchKeyword(v); setModelSearchKeyword(event.target.value);
setModelTablePage(1); setModelTablePage(1);
}} }}
className='!w-full' prefix={<Search size={16} />}
prefix={<IconSearch />} allowClear
showClear
/> />
<Button onClick={handleCopySelected}>{t('复制已选')}</Button> <Button onClick={handleCopySelected}>{t('复制已选')}</Button>
<Button type='tertiary' onClick={handleSelectSuccess}> <Button onClick={handleSelectSuccess}>{t('选择成功')}</Button>
{t('选择成功')} </div>
</Button>
<div className='model-test-list-header'>
<Typography.Text strong>{t('模型列表')}</Typography.Text>
<Typography.Text type='secondary'>
{t('共 {{count}} 个模型', { count: models.length })}
</Typography.Text>
<Typography.Text type='secondary' aria-live='polite'>
{t('已选择 {{count}} 个模型', {
count: selectedModelKeys.length,
})}
</Typography.Text>
</div> </div>
<Table <Table
size='middle'
tableLayout='fixed'
className='model-test-table'
columns={columns} columns={columns}
scroll={{
x: 400,
y: `clamp(80px, calc(100dvh - ${isMobile ? 500 : 440}px), 400px)`,
}}
dataSource={dataSource} dataSource={dataSource}
rowSelection={{ rowSelection={{
selectedRowKeys: selectedModelKeys, selectedRowKeys: selectedModelKeys,
onChange: (keys) => { preserveSelectedRowKeys: true,
if (allSelectingRef.current) { columnWidth: 40,
allSelectingRef.current = false; onChange: (keys) => setSelectedModelKeys(keys),
return;
}
setSelectedModelKeys(keys);
},
onSelectAll: (checked) => {
allSelectingRef.current = true;
setSelectedModelKeys(checked ? filteredModels : []);
},
}} }}
pagination={{ pagination={{
currentPage: modelTablePage, current: modelTablePage,
pageSize: MODEL_TABLE_PAGE_SIZE, pageSize: paginationSize,
total: filteredModels.length, total: filteredModels.length,
showSizeChanger: false, showSizeChanger: false,
onPageChange: (page) => setModelTablePage(page), showTotal: (total) => t('共 {{total}} 条', { total }),
size: 'small',
onChange: (page, size) => {
setModelTablePage(size !== paginationSize ? 1 : page);
setPaginationSize(size);
},
}} }}
/> />
</div> </div>
@@ -0,0 +1,76 @@
.model-test-list-header {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 8px;
}
.model-test-content {
display: flex;
flex-direction: column;
gap: 16px;
padding-top: 8px;
}
.model-test-endpoint,
.model-test-toolbar,
.model-test-footer {
display: flex;
align-items: center;
gap: 8px;
}
.model-test-endpoint > .ant-typography {
flex-shrink: 0;
white-space: nowrap;
}
.model-test-endpoint > .ant-select,
.model-test-toolbar > .ant-input-affix-wrapper {
flex: 1;
min-width: 0;
}
.model-test-toolbar > .ant-btn {
flex-shrink: 0;
}
.model-test-status {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.model-test-table .ant-table-cell {
overflow-wrap: anywhere;
}
.model-test-table .ant-table-selection-column {
vertical-align: middle;
}
.model-test-table .ant-btn-link {
padding-inline: 0;
}
.model-test-table .ant-table-pagination {
margin: 16px 0 0;
row-gap: 8px;
}
.model-test-footer {
justify-content: flex-end;
flex-wrap: wrap;
padding-top: 8px;
}
@media (max-width: 600px) {
.model-test-toolbar {
flex-wrap: wrap;
}
.model-test-toolbar > .ant-input-affix-wrapper {
flex-basis: 100%;
}
}
+1 -15
View File
@@ -21,18 +21,10 @@ import React from 'react';
import { Skeleton, Typography } from '@/components/ui'; import { Skeleton, Typography } from '@/components/ui';
import { useMinimumLoadingTime } from '../../../hooks/common/useMinimumLoadingTime'; import { useMinimumLoadingTime } from '../../../hooks/common/useMinimumLoadingTime';
import { IconEyeOpened } from '@/components/ui/icons'; import { IconEyeOpened } from '@/components/ui/icons';
import CompactModeToggle from '../../common/ui/CompactModeToggle';
const { Text } = Typography; const { Text } = Typography;
const MjLogsActions = ({ const MjLogsActions = ({ loading, showBanner, isAdminUser, t }) => {
loading,
showBanner,
isAdminUser,
compactMode,
setCompactMode,
t,
}) => {
const showSkeleton = useMinimumLoadingTime(loading); const showSkeleton = useMinimumLoadingTime(loading);
const placeholder = ( const placeholder = (
@@ -56,12 +48,6 @@ const MjLogsActions = ({
</Text> </Text>
</div> </div>
</Skeleton> </Skeleton>
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div> </div>
); );
}; };
+17 -35
View File
@@ -19,7 +19,9 @@ For commercial licensing, please contact support@quantumnous.com
import React from 'react'; import React from 'react';
import { Button, Form } from '@/components/ui'; import { Button, Form } from '@/components/ui';
import { IconSearch } from '@/components/ui/icons'; import FilterSearchButton from '../../common/table/FilterSearchButton';
import { useFilterSearch } from '../../../hooks/common/useFilterSearch';
import '../../common/table/log-filters.css';
import { DATE_RANGE_PRESETS } from '../../../constants/console.constants'; import { DATE_RANGE_PRESETS } from '../../../constants/console.constants';
@@ -27,35 +29,37 @@ const MjLogsFilters = ({
formInitValues, formInitValues,
setFormApi, setFormApi,
refresh, refresh,
setShowColumnSelector,
formApi, formApi,
loading, loading,
isAdminUser, isAdminUser,
t, t,
}) => { }) => {
const { scheduleSearch, submitSearch, cancelPendingSearch } =
useFilterSearch(refresh);
return ( return (
<Form <Form
initValues={formInitValues} initValues={formInitValues}
getFormApi={(api) => setFormApi(api)} getFormApi={(api) => setFormApi(api)}
onSubmit={refresh} onSubmit={submitSearch}
onValueChange={scheduleSearch}
allowEmpty={true} allowEmpty={true}
autoComplete='off' autoComplete='off'
layout='vertical' layout='vertical'
trigger='change' trigger='change'
stopValidateWithError={false} stopValidateWithError={false}
className='log-filter-form'
> >
<div className='flex flex-col gap-2'> <div className='log-filter-content'>
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-2'> <div className='log-filter-grid'>
{/* 时间选择器 */} {/* 时间选择器 */}
<div className='col-span-1 lg:col-span-2'> <div className='log-filter-wide'>
<Form.DatePicker <Form.DatePicker
field='dateRange' field='dateRange'
label={t('时间范围')}
className='w-full' className='w-full'
type='dateTimeRange' type='dateTimeRange'
placeholder={[t('开始时间'), t('结束时间')]} placeholder={[t('开始时间'), t('结束时间')]}
showClear showClear
pure
size='small'
presets={DATE_RANGE_PRESETS.map((preset) => ({ presets={DATE_RANGE_PRESETS.map((preset) => ({
text: t(preset.text), text: t(preset.text),
start: preset.start(), start: preset.start(),
@@ -67,60 +71,38 @@ const MjLogsFilters = ({
{/* 任务 ID */} {/* 任务 ID */}
<Form.Input <Form.Input
field='mj_id' field='mj_id'
prefix={<IconSearch />} label={t('任务 ID')}
placeholder={t('任务 ID')} placeholder={t('任务 ID')}
showClear showClear
pure
size='small'
/> />
{/* 渠道 ID - 仅管理员可见 */} {/* 渠道 ID - 仅管理员可见 */}
{isAdminUser && ( {isAdminUser && (
<Form.Input <Form.Input
field='channel_id' field='channel_id'
prefix={<IconSearch />} label={t('渠道 ID')}
placeholder={t('渠道 ID')} placeholder={t('渠道 ID')}
showClear showClear
pure
size='small'
/> />
)} )}
</div> </div>
{/* 操作按钮区域 */} {/* 操作按钮区域 */}
<div className='flex justify-between items-center'> <div className='log-filter-actions'>
<div></div>
<div className='flex gap-2'>
<Button <Button
type='tertiary'
htmlType='submit'
loading={loading}
size='small'
>
{t('查询')}
</Button>
<Button
type='tertiary'
onClick={() => { onClick={() => {
if (formApi) { if (formApi) {
formApi.reset(); formApi.reset();
cancelPendingSearch();
setTimeout(() => { setTimeout(() => {
refresh(); refresh();
}, 100); }, 100);
} }
}} }}
size='small'
> >
{t('重置')} {t('重置')}
</Button> </Button>
<Button <FilterSearchButton loading={loading} />
type='tertiary'
onClick={() => setShowColumnSelector(true)}
size='small'
>
{t('列设置')}
</Button>
</div>
</div> </div>
</div> </div>
</Form> </Form>
+5 -24
View File
@@ -17,13 +17,10 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import TableEmpty from '../../common/table/TableEmpty';
import React, { useMemo } from 'react'; import React, { useMemo } from 'react';
import { Empty } from '@/components/ui';
import CardTable from '../../common/ui/CardTable'; import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getMjLogsColumns } from './MjLogsColumnDefs'; import { getMjLogsColumns } from './MjLogsColumnDefs';
const MjLogsTable = (mjLogsData) => { const MjLogsTable = (mjLogsData) => {
@@ -33,7 +30,6 @@ const MjLogsTable = (mjLogsData) => {
activePage, activePage,
pageSize, pageSize,
logCount, logCount,
compactMode,
visibleColumns, visibleColumns,
handlePageChange, handlePageChange,
handlePageSizeChange, handlePageSizeChange,
@@ -66,31 +62,16 @@ const MjLogsTable = (mjLogsData) => {
return getVisibleColumns(); return getVisibleColumns();
}, [visibleColumns, allColumns]); }, [visibleColumns, allColumns]);
const tableColumns = useMemo(() => {
return compactMode
? visibleColumnsList.map(({ fixed, ...rest }) => rest)
: visibleColumnsList;
}, [compactMode, visibleColumnsList]);
return ( return (
<CardTable <CardTable
columns={tableColumns} columns={visibleColumnsList}
dataSource={logs} dataSource={logs}
rowKey='key' rowKey='key'
loading={loading} loading={loading}
scroll={compactMode ? undefined : { x: 'max-content' }} scroll={{ x: 'max-content' }}
className='rounded-xl overflow-hidden' className='rounded-xl overflow-hidden'
size='middle' size='middle'
empty={ empty={<TableEmpty />}
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
pagination={{ pagination={{
currentPage: activePage, currentPage: activePage,
pageSize: pageSize, pageSize: pageSize,
+8
View File
@@ -20,6 +20,7 @@ For commercial licensing, please contact support@quantumnous.com
import React from 'react'; import React from 'react';
import { Layout } from '@/components/ui'; import { Layout } from '@/components/ui';
import CardPro from '../../common/ui/CardPro'; import CardPro from '../../common/ui/CardPro';
import { ColumnSettingsButton } from '../../common/table/ColumnSettings';
import MjLogsTable from './MjLogsTable'; import MjLogsTable from './MjLogsTable';
import MjLogsActions from './MjLogsActions'; import MjLogsActions from './MjLogsActions';
import MjLogsFilters from './MjLogsFilters'; import MjLogsFilters from './MjLogsFilters';
@@ -41,9 +42,16 @@ const MjLogsPage = () => {
<Layout> <Layout>
<CardPro <CardPro
tableTitle={mjLogsData.t('调用明细')}
type='type2' type='type2'
statsArea={<MjLogsActions {...mjLogsData} />} statsArea={<MjLogsActions {...mjLogsData} />}
searchArea={<MjLogsFilters {...mjLogsData} />} searchArea={<MjLogsFilters {...mjLogsData} />}
tableActions={
<ColumnSettingsButton
open={mjLogsData.showColumnSelector}
onClick={() => mjLogsData.setShowColumnSelector(true)}
/>
}
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
currentPage: mjLogsData.activePage, currentPage: mjLogsData.activePage,
pageSize: mjLogsData.pageSize, pageSize: mjLogsData.pageSize,
@@ -18,16 +18,15 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React from 'react'; import React from 'react';
import { Modal, Button, Checkbox } from '@/components/ui'; import { ColumnVisibilitySettings } from '../../../common/table/ColumnSettings';
import { getMjLogsColumns } from '../MjLogsColumnDefs'; import { getMjLogsColumns } from '../MjLogsColumnDefs';
const ColumnSelectorModal = ({ const ColumnSelectorModal = ({
showColumnSelector, showColumnSelector,
setShowColumnSelector, setShowColumnSelector,
visibleColumns, visibleColumns,
handleColumnVisibilityChange, setVisibleColumns,
handleSelectAll, getDefaultColumnVisibility,
initDefaultColumns,
COLUMN_KEYS, COLUMN_KEYS,
isAdminUser, isAdminUser,
copyText, copyText,
@@ -46,63 +45,22 @@ const ColumnSelectorModal = ({
}); });
return ( return (
<Modal <ColumnVisibilitySettings
title={t('列设置')} showColumnSelector={showColumnSelector}
visible={showColumnSelector} setShowColumnSelector={setShowColumnSelector}
onCancel={() => setShowColumnSelector(false)} columns={allColumns.filter(
footer={ (column) =>
<div className='flex justify-end'> !(
<Button onClick={() => initDefaultColumns()}>{t('重置')}</Button>
<Button onClick={() => setShowColumnSelector(false)}>
{t('取消')}
</Button>
<Button onClick={() => setShowColumnSelector(false)}>
{t('确定')}
</Button>
</div>
}
>
<div style={{ marginBottom: 20 }}>
<Checkbox
checked={Object.values(visibleColumns).every((v) => v === true)}
indeterminate={
Object.values(visibleColumns).some((v) => v === true) &&
!Object.values(visibleColumns).every((v) => v === true)
}
onChange={(e) => handleSelectAll(e.target.checked)}
>
{t('全选')}
</Checkbox>
</div>
<div
className='flex flex-wrap max-h-96 overflow-y-auto rounded-lg p-4'
style={{ border: '1px solid var(--ui-color-border)' }}
>
{allColumns.map((column) => {
// Skip admin-only columns for non-admin users
if (
!isAdminUser && !isAdminUser &&
(column.key === COLUMN_KEYS.CHANNEL || [COLUMN_KEYS.CHANNEL, COLUMN_KEYS.SUBMIT_RESULT].includes(
column.key === COLUMN_KEYS.SUBMIT_RESULT) column.key,
) { )
return null; ),
} )}
visibleColumns={visibleColumns}
return ( setVisibleColumns={setVisibleColumns}
<div key={column.key} className='w-1/2 mb-4 pr-2'> getDefaultColumnVisibility={getDefaultColumnVisibility}
<Checkbox />
checked={!!visibleColumns[column.key]}
onChange={(e) =>
handleColumnVisibilityChange(column.key, e.target.checked)
}
>
{column.title}
</Checkbox>
</div>
);
})}
</div>
</Modal>
); );
}; };
@@ -18,17 +18,13 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React from 'react'; import React from 'react';
import { import { Button as AntButton, Tooltip as AntTooltip } from 'antd';
Button, import { Copy } from 'lucide-react';
Space, import { Button, Space, Tag, Modal, Tooltip } from '@/components/ui';
Tag,
Typography,
Modal,
Tooltip,
} from '@/components/ui';
import { import {
timestamp2string, timestamp2string,
getLobeHubIcon, getLobeHubIcon,
renderGroup,
stringToColor, stringToColor,
isRoot, isRoot,
} from '../../../helpers'; } from '../../../helpers';
@@ -37,8 +33,6 @@ import {
renderDescription, renderDescription,
} from '../../common/ui/RenderUtils'; } from '../../common/ui/RenderUtils';
const { Text } = Typography;
// Render timestamp // Render timestamp
function renderTimestamp(timestamp) { function renderTimestamp(timestamp) {
return <>{timestamp2string(timestamp)}</>; return <>{timestamp2string(timestamp)}</>;
@@ -48,11 +42,7 @@ function renderTimestamp(timestamp) {
const renderModelIconCol = (record, vendorMap) => { const renderModelIconCol = (record, vendorMap) => {
const iconKey = record?.icon || vendorMap[record?.vendor_id]?.icon; const iconKey = record?.icon || vendorMap[record?.vendor_id]?.icon;
if (!iconKey) return '-'; if (!iconKey) return '-';
return ( return <div className='models-model-icon'>{getLobeHubIcon(iconKey, 20)}</div>;
<div className='flex items-center justify-center'>
{getLobeHubIcon(iconKey, 20)}
</div>
);
}; };
// Render vendor column with icon // Render vendor column with icon
@@ -125,9 +115,7 @@ const renderGroups = (groups) => {
return renderLimitedItems({ return renderLimitedItems({
items: groups, items: groups,
renderItem: (g, idx) => ( renderItem: (g, idx) => (
<Tag key={idx} size='small' shape='circle' color={stringToColor(g)}> <React.Fragment key={idx}>{renderGroup(g)}</React.Fragment>
{g}
</Tag>
), ),
}); });
}; };
@@ -247,14 +235,19 @@ const renderOperations = (
manageModel, manageModel,
refresh, refresh,
t, t,
setDetailModel,
) => { ) => {
return ( return (
<Space wrap> <Space wrap className='console-module-row-actions'>
<Button type='link' size='small' onClick={() => setDetailModel(record)}>
{t('详情')}
</Button>
{isRoot() && ( {isRoot() && (
<> <>
{record.status === 1 ? ( {record.status === 1 ? (
<Button <Button
type='danger' type='link'
danger
size='small' size='small'
onClick={() => manageModel(record.id, 'disable', record)} onClick={() => manageModel(record.id, 'disable', record)}
> >
@@ -262,6 +255,7 @@ const renderOperations = (
</Button> </Button>
) : ( ) : (
<Button <Button
type='link'
size='small' size='small'
onClick={() => manageModel(record.id, 'enable', record)} onClick={() => manageModel(record.id, 'enable', record)}
> >
@@ -270,7 +264,7 @@ const renderOperations = (
)} )}
<Button <Button
type='tertiary' type='link'
size='small' size='small'
onClick={() => { onClick={() => {
setEditingModel(record); setEditingModel(record);
@@ -281,7 +275,8 @@ const renderOperations = (
</Button> </Button>
<Button <Button
type='danger' type='link'
danger
size='small' size='small'
onClick={() => { onClick={() => {
Modal.confirm({ Modal.confirm({
@@ -347,8 +342,10 @@ export const getModelsColumns = ({
setEditingModel, setEditingModel,
setShowEdit, setShowEdit,
refresh, refresh,
copyText,
vendorMap, vendorMap,
categoryNames = {}, categoryNames = {},
setDetailModel,
}) => { }) => {
return [ return [
{ {
@@ -362,9 +359,19 @@ export const getModelsColumns = ({
title: t('模型名称'), title: t('模型名称'),
dataIndex: 'model_name', dataIndex: 'model_name',
render: (text) => ( render: (text) => (
<Text copyable onClick={(e) => e.stopPropagation()}> <span className='models-name-cell' onClick={(e) => e.stopPropagation()}>
{text} <span>{text}</span>
</Text> <AntTooltip title={t('复制模型名称')}>
<AntButton
type='text'
size='small'
className='models-name-copy'
aria-label={t('复制模型名称')}
icon={<Copy size={14} />}
onClick={() => copyText(text)}
/>
</AntTooltip>
</span>
), ),
}, },
{ {
@@ -436,7 +443,7 @@ export const getModelsColumns = ({
}, },
}, },
{ {
title: '', title: t('操作'),
dataIndex: 'operate', dataIndex: 'operate',
fixed: 'right', fixed: 'right',
render: (text, record, index) => render: (text, record, index) =>
@@ -448,6 +455,7 @@ export const getModelsColumns = ({
manageModel, manageModel,
refresh, refresh,
t, t,
setDetailModel,
), ),
}, },
]; ];
+27 -33
View File
@@ -18,7 +18,9 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { useRef } from 'react'; import React, { useRef } from 'react';
import { Form, Button } from '@/components/ui'; import { Form } from '@/components/ui';
import { ConsoleFilterActions } from '../../console/ConsoleModuleFilters';
import { useFilterSearch } from '../../../hooks/common/useFilterSearch';
import { IconSearch } from '@/components/ui/icons'; import { IconSearch } from '@/components/ui/icons';
import { MODEL_CATEGORY_NAMES } from '../../../constants'; import { MODEL_CATEGORY_NAMES } from '../../../constants';
@@ -30,12 +32,17 @@ const ModelsFilters = ({
searching, searching,
t, t,
}) => { }) => {
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
() => searchModels(),
);
// Handle form reset and immediate search // Handle form reset and immediate search
const formApiRef = useRef(null); const formApiRef = useRef(null);
const handleReset = () => { const handleReset = () => {
if (!formApiRef.current) return; if (!formApiRef.current) return;
formApiRef.current.reset(); formApiRef.current.reset();
cancelPendingSearch();
setTimeout(() => { setTimeout(() => {
searchModels(); searchModels();
}, 100); }, 100);
@@ -43,48 +50,52 @@ const ModelsFilters = ({
return ( return (
<Form <Form
initValues={formInitValues} initValues={{
...formInitValues,
searchCategory: formInitValues.searchCategory || undefined,
}}
getFormApi={(api) => { getFormApi={(api) => {
setFormApi(api); setFormApi(api);
formApiRef.current = api; formApiRef.current = api;
}} }}
onSubmit={searchModels} onSubmit={submitSearch}
allowEmpty={true} allowEmpty={true}
autoComplete='off' autoComplete='off'
layout='horizontal' layout='vertical'
trigger='change' trigger='change'
stopValidateWithError={false} stopValidateWithError={false}
className='w-full md:w-auto order-1 md:order-2' className='console-module-filter-form'
onValueChange={scheduleSearch}
> >
<div className='flex flex-col md:flex-row items-center gap-2 w-full md:w-auto'> <div className='console-module-filter-grid'>
<div className='relative w-full md:w-56'> <div className='console-module-field'>
<Form.Input <Form.Input
label={t('模型名称')}
field='searchKeyword' field='searchKeyword'
prefix={<IconSearch />} prefix={<IconSearch />}
placeholder={t('搜索模型名称')} placeholder={t('搜索模型名称')}
showClear showClear
pure
size='small' size='small'
/> />
</div> </div>
<div className='relative w-full md:w-56'> <div className='console-module-field'>
<Form.Input <Form.Input
label={t('供应商')}
field='searchVendor' field='searchVendor'
prefix={<IconSearch />} prefix={<IconSearch />}
placeholder={t('搜索供应商')} placeholder={t('搜索供应商')}
showClear showClear
pure
size='small' size='small'
/> />
</div> </div>
<div className='relative w-full md:w-56'> <div className='console-module-field'>
<Form.Select <Form.Select
label={t('分类')}
field='searchCategory' field='searchCategory'
placeholder={t('选择分类')} placeholder={t('选择分类')}
showClear showClear
pure
size='small' size='small'
style={{ width: '100%' }} style={{ width: '100%' }}
> >
@@ -96,28 +107,11 @@ const ModelsFilters = ({
))} ))}
</Form.Select> </Form.Select>
</div> </div>
</div>
<div className='flex gap-2 w-full md:w-auto'> <ConsoleFilterActions
<Button onReset={handleReset}
type='tertiary'
htmlType='submit'
loading={loading || searching} loading={loading || searching}
className='flex-1 md:flex-initial md:w-auto' />
size='small'
>
{t('查询')}
</Button>
<Button
type='tertiary'
onClick={handleReset}
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('重置')}
</Button>
</div>
</div>
</Form> </Form>
); );
}; };
+44 -16
View File
@@ -17,17 +17,18 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { useMemo } from 'react'; import TableEmpty from '../../common/table/TableEmpty';
import { Empty } from '@/components/ui'; import React, { useMemo, useState } from 'react';
import { Descriptions } from 'antd';
import { Modal } from '@/components/ui';
import CardTable from '../../common/ui/CardTable'; import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getModelsColumns } from './ModelsColumnDefs'; import { getModelsColumns } from './ModelsColumnDefs';
import { useModelCategories } from '../../../hooks/models/useModelCategories'; import { useModelCategories } from '../../../hooks/models/useModelCategories';
import './models-vendor-tabs.css';
const ModelsTable = (modelsData) => { const ModelsTable = (modelsData) => {
const [detailModel, setDetailModel] = useState(null);
const { const {
models, models,
loading, loading,
@@ -44,6 +45,7 @@ const ModelsTable = (modelsData) => {
setShowEdit, setShowEdit,
refresh, refresh,
vendorMap, vendorMap,
copyText,
t, t,
} = modelsData; } = modelsData;
@@ -60,6 +62,8 @@ const ModelsTable = (modelsData) => {
refresh, refresh,
vendorMap, vendorMap,
categoryNames, categoryNames,
setDetailModel,
copyText,
}); });
}, [ }, [
t, t,
@@ -69,6 +73,7 @@ const ModelsTable = (modelsData) => {
refresh, refresh,
vendorMap, vendorMap,
categoryNames, categoryNames,
copyText,
]); ]);
// Handle compact mode by removing fixed positioning // Handle compact mode by removing fixed positioning
@@ -85,6 +90,37 @@ const ModelsTable = (modelsData) => {
}, [compactMode, columns]); }, [compactMode, columns]);
return ( return (
<>
<Modal
title={t('详情')}
visible={Boolean(detailModel)}
onCancel={() => setDetailModel(null)}
maskClosable
footer={null}
width={720}
>
<Descriptions
className='models-detail-descriptions'
bordered
column={1}
items={
detailModel
? columns
.filter((column) => column.dataIndex !== 'operate')
.map((column, key) => ({
key,
label: column.title,
children: column.render
? column.render(
detailModel[column.dataIndex],
detailModel,
)
: (detailModel[column.dataIndex] ?? '-'),
}))
: []
}
/>
</Modal>
<CardTable <CardTable
columns={tableColumns} columns={tableColumns}
dataSource={models} dataSource={models}
@@ -102,19 +138,11 @@ const ModelsTable = (modelsData) => {
loading={loading} loading={loading}
rowSelection={rowSelection} rowSelection={rowSelection}
onRow={handleRow} onRow={handleRow}
empty={ empty={<TableEmpty />}
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className='rounded-xl overflow-hidden' className='rounded-xl overflow-hidden'
size='middle' size='middle'
/> />
</>
); );
}; };
+66 -77
View File
@@ -18,8 +18,10 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React from 'react'; import React from 'react';
import { Tabs, TabPane, Tag, Button, Dropdown, Modal } from '@/components/ui'; import { Modal } from '@/components/ui';
import { IconEdit, IconDelete } from '@/components/ui/icons'; import { Button } from 'antd';
import { Plus } from 'lucide-react';
import { IconEdit, IconClose } from '@/components/ui/icons';
import { import {
getLobeHubIcon, getLobeHubIcon,
showError, showError,
@@ -27,6 +29,7 @@ import {
isRoot, isRoot,
} from '../../../helpers'; } from '../../../helpers';
import { API } from '../../../helpers'; import { API } from '../../../helpers';
import './models-vendor-tabs.css';
const ModelsTabs = ({ const ModelsTabs = ({
activeVendorKey, activeVendorKey,
@@ -52,13 +55,13 @@ const ModelsTabs = ({
}; };
const handleEditVendor = (vendor, e) => { const handleEditVendor = (vendor, e) => {
e.stopPropagation(); // 阻止事件冒泡,避免触发tab切换 e.stopPropagation();
setEditingVendor(vendor); setEditingVendor(vendor);
setShowEditVendor(true); setShowEditVendor(true);
}; };
const handleDeleteVendor = async (vendor, e) => { const handleDeleteVendor = async (vendor, e) => {
e.stopPropagation(); // 阻止事件冒泡,避免触发tab切换 e.stopPropagation();
try { try {
const res = await API.delete(`/api/vendors/${vendor.id}`); const res = await API.delete(`/api/vendors/${vendor.id}`);
if (res.data.success) { if (res.data.success) {
@@ -80,71 +83,61 @@ const ModelsTabs = ({
}; };
return ( return (
<Tabs <div className='models-vendor-toolbar'>
activeKey={activeVendorKey} <div className='models-vendor-list' role='group' aria-label={t('供应商')}>
type='card' <div
collapsible className={`models-vendor-group${activeVendorKey === 'all' ? ' is-selected' : ''}`}
onChange={handleTabChange} >
className='mb-2'
tabBarExtraContent={
canManageVendors && (
<Button <Button
type='primary' type='text'
size='small' className='models-vendor-filter'
onClick={() => setShowAddVendor(true)} aria-pressed={activeVendorKey === 'all'}
onClick={() => handleTabChange('all')}
> >
{t('新增供应商')} <span>{t('全部')}</span>
<span className='models-vendor-count'>{vendorCounts.all || 0}</span>
</Button> </Button>
) </div>
}
>
<TabPane
itemKey='all'
tab={
<span className='flex items-center gap-2'>
{t('全部')}
<Tag
color={activeVendorKey === 'all' ? 'red' : 'grey'}
shape='circle'
>
{vendorCounts['all'] || 0}
</Tag>
</span>
}
/>
{vendors.map((vendor) => { {vendors.map((vendor) => {
const key = String(vendor.id); const key = String(vendor.id);
const count = vendorCounts[vendor.id] || 0;
return ( return (
<TabPane <div
key={key} key={key}
itemKey={key} className={`models-vendor-group${activeVendorKey === key ? ' is-selected' : ''}`}
tab={ >
<span className='flex items-center gap-2'> <Button
type='text'
className='models-vendor-filter'
aria-pressed={activeVendorKey === key}
onClick={() => handleTabChange(key)}
>
<span className='models-vendor-icon'>
{getLobeHubIcon(vendor.icon || 'Layers', 14)} {getLobeHubIcon(vendor.icon || 'Layers', 14)}
</span>
<span className='models-vendor-name' title={vendor.name}>
{vendor.name} {vendor.name}
<Tag </span>
color={activeVendorKey === key ? 'red' : 'grey'} <span className='models-vendor-count'>
shape='circle' {vendorCounts[vendor.id] || 0}
> </span>
{count} </Button>
</Tag>
{canManageVendors && ( {canManageVendors && (
<Dropdown <div className='models-vendor-actions'>
trigger='click' <Button
position='bottomRight' type='text'
render={ size='small'
<Dropdown.Menu>
<Dropdown.Item
icon={<IconEdit />} icon={<IconEdit />}
aria-label={`${t('编辑')}${vendor.name}`}
title={t('编辑')}
onClick={(e) => handleEditVendor(vendor, e)} onClick={(e) => handleEditVendor(vendor, e)}
> />
{t('编辑')} <Button
</Dropdown.Item> type='text'
<Dropdown.Item danger
type='danger' size='small'
icon={<IconDelete />} icon={<IconClose />}
aria-label={`${t('删除')}${vendor.name}`}
title={t('删除')}
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
Modal.confirm({ Modal.confirm({
@@ -160,29 +153,25 @@ const ModelsTabs = ({
okType: 'danger', okType: 'danger',
}); });
}} }}
>
{t('删除')}
</Dropdown.Item>
</Dropdown.Menu>
}
onClickOutSide={(e) => e.stopPropagation()}
>
<Button
size='small'
type='tertiary'
theme='outline'
onClick={(e) => e.stopPropagation()}
>
{t('操作')}
</Button>
</Dropdown>
)}
</span>
}
/> />
</div>
)}
</div>
); );
})} })}
</Tabs> </div>
{canManageVendors && (
<Button
className='console-create-action'
type='primary'
size='middle'
icon={<Plus size={16} />}
onClick={() => setShowAddVendor(true)}
>
{t('新增供应商')}
</Button>
)}
</div>
); );
}; };
+12 -11
View File
@@ -98,6 +98,18 @@ const ModelsPage = () => {
<ModelsCategoryStats t={t} /> <ModelsCategoryStats t={t} />
<CardPro <CardPro
tableTitle={t('模型列表')}
tableActionsOffset
searchArea={
<ModelsFilters
formInitValues={formInitValues}
setFormApi={setFormApi}
searchModels={searchModels}
loading={loading}
searching={searching}
t={t}
/>
}
type='type3' type='type3'
tabsArea={<ModelsTabs {...modelsData} />} tabsArea={<ModelsTabs {...modelsData} />}
actionsArea={ actionsArea={
@@ -118,17 +130,6 @@ const ModelsPage = () => {
setCompactMode={setCompactMode} setCompactMode={setCompactMode}
t={t} t={t}
/> />
<div className='w-full md:w-full lg:w-auto order-1 md:order-2'>
<ModelsFilters
formInitValues={formInitValues}
setFormApi={setFormApi}
searchModels={searchModels}
loading={loading}
searching={searching}
t={t}
/>
</div>
</div> </div>
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
@@ -17,7 +17,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { useState, useEffect, useRef, useMemo } from 'react'; import '../../../console/module-alignment.css';
import React, { useState, useEffect, useRef } from 'react';
import JSONEditor from '../../../common/ui/JSONEditor'; import JSONEditor from '../../../common/ui/JSONEditor';
import { import {
SideSheet, SideSheet,
@@ -27,18 +28,17 @@ import {
Spin, Spin,
Typography, Typography,
Card, Card,
Tag,
Avatar, Avatar,
Col, Col,
Row, Row,
} from '@/components/ui'; } from '@/components/ui';
import { Save, X, FileText } from 'lucide-react'; import { FileText } from 'lucide-react';
import { IconLink } from '@/components/ui/icons'; import { IconLink } from '@/components/ui/icons';
import { API, showError, showSuccess } from '../../../../helpers'; import { API, showError, showSuccess } from '../../../../helpers';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useIsMobile } from '../../../../hooks/common/useIsMobile'; import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const { Text, Title } = Typography; const { Text } = Typography;
// Example endpoint template for quick fill // Example endpoint template for quick fill
const ENDPOINT_TEMPLATE = { const ENDPOINT_TEMPLATE = {
@@ -63,7 +63,6 @@ const EditModelModal = (props) => {
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const formApiRef = useRef(null); const formApiRef = useRef(null);
const isEdit = props.editingModel && props.editingModel.id !== undefined; const isEdit = props.editingModel && props.editingModel.id !== undefined;
const placement = useMemo(() => (isEdit ? 'right' : 'left'), [isEdit]);
// 供应商列表 // 供应商列表
const [vendors, setVendors] = useState([]); const [vendors, setVendors] = useState([]);
@@ -308,51 +307,26 @@ const EditModelModal = (props) => {
return ( return (
<SideSheet <SideSheet
placement={placement} rootClassName='console-model-drawer'
title={ classNames={{ header: 'console-model-editor-header' }}
<Space> placement='right'
{isEdit ? ( title={isEdit ? t('更新模型信息') : t('创建新的模型')}
<Tag color='blue' shape='circle'>
{t('更新')}
</Tag>
) : (
<Tag color='green' shape='circle'>
{t('新建')}
</Tag>
)}
<Title heading={4} className='m-0'>
{isEdit ? t('更新模型信息') : t('创建新的模型')}
</Title>
</Space>
}
bodyStyle={{ padding: '0' }} bodyStyle={{ padding: '0' }}
visible={props.visiable} visible={props.visiable}
width={isMobile ? '100%' : 600} width={isMobile ? '100%' : 600}
footer={ footer={
<div className='flex justify-end'> <div className='console-model-footer'>
<Space> <Button onClick={handleCancel}>{t('取消')}</Button>
<Button <Button
theme='solid' theme='solid'
className='!rounded-lg' type='primary'
onClick={() => formApiRef.current?.submitForm()} onClick={() => formApiRef.current?.submitForm()}
icon={<Save size={16} />}
loading={loading} loading={loading}
> >
{t('提交')} {t('确定')}
</Button> </Button>
<Button
theme='light'
className='!rounded-lg'
type='primary'
onClick={handleCancel}
icon={<X size={16} />}
>
{t('取消')}
</Button>
</Space>
</div> </div>
} }
closeIcon={null}
onCancel={() => handleCancel()} onCancel={() => handleCancel()}
> >
<Spin spinning={loading}> <Spin spinning={loading}>
@@ -366,8 +340,8 @@ const EditModelModal = (props) => {
<div className='p-2'> <div className='p-2'>
{/* 基本信息 */} {/* 基本信息 */}
<Card className='!rounded-2xl shadow-sm border-0'> <Card className='!rounded-2xl shadow-sm border-0'>
<div className='flex items-center mb-2'> <div className='console-model-section'>
<Avatar size='small' color='green' className='mr-2 shadow-md'> <Avatar size='small' color='green'>
<FileText size={16} /> <FileText size={16} />
</Avatar> </Avatar>
<div> <div>
@@ -470,7 +444,7 @@ const EditModelModal = (props) => {
style={{ width: '100%' }} style={{ width: '100%' }}
{...(tagGroups.length > 0 && { {...(tagGroups.length > 0 && {
extraText: ( extraText: (
<Space wrap> <Space wrap className='console-model-tag-presets'>
{tagGroups.map((group) => ( {tagGroups.map((group) => (
<Button <Button
key={group.id} key={group.id}
@@ -602,7 +576,7 @@ const EditModelModal = (props) => {
)} )}
/> />
</Col> </Col>
<Col span={24}> <Col span={24} className='console-model-endpoints'>
<JSONEditor <JSONEditor
field='endpoints' field='endpoints'
label={t('端点映射')} label={t('端点映射')}
@@ -615,6 +589,7 @@ const EditModelModal = (props) => {
} }
formApi={formApiRef.current} formApi={formApiRef.current}
editorType='object' editorType='object'
objectValueAutoSize={{ minRows: 3, maxRows: 8 }}
template={ENDPOINT_TEMPLATE} template={ENDPOINT_TEMPLATE}
templateLabel={t('填入模板')} templateLabel={t('填入模板')}
extraText={t('留空则使用默认端点;支持 {path, method}')} extraText={t('留空则使用默认端点;支持 {path, method}')}
@@ -17,28 +17,14 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import '../../../console/module-alignment.css';
import React, { useState, useRef, useEffect } from 'react'; import React, { useState, useRef, useEffect } from 'react';
import JSONEditor from '../../../common/ui/JSONEditor'; import JSONEditor from '../../../common/ui/JSONEditor';
import { import { Modal, Form, Row, Col, Spin } from '@/components/ui';
SideSheet,
Button,
Form,
Typography,
Space,
Tag,
Row,
Col,
Card,
Avatar,
Spin,
} from '@/components/ui';
import { IconLayers, IconSave, IconClose } from '@/components/ui/icons';
import { API, showError, showSuccess } from '../../../../helpers'; import { API, showError, showSuccess } from '../../../../helpers';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useIsMobile } from '../../../../hooks/common/useIsMobile'; import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const { Text, Title } = Typography;
// Example endpoint template for quick fill // Example endpoint template for quick fill
const ENDPOINT_TEMPLATE = { const ENDPOINT_TEMPLATE = {
openai: { path: '/v1/chat/completions', method: 'POST' }, openai: { path: '/v1/chat/completions', method: 'POST' },
@@ -112,53 +98,13 @@ const EditPrefillGroupModal = ({
}; };
return ( return (
<SideSheet <Modal
placement='left' title={isEdit ? t('更新预填组') : t('创建新的预填组')}
title={
<Space>
{isEdit ? (
<Tag color='blue' shape='circle'>
{t('更新')}
</Tag>
) : (
<Tag color='green' shape='circle'>
{t('新建')}
</Tag>
)}
<Title heading={4} className='m-0'>
{isEdit ? t('更新预填组') : t('创建新的预填组')}
</Title>
</Space>
}
visible={visible} visible={visible}
onCancel={onClose} onCancel={onClose}
width={isMobile ? '100%' : 600} onOk={() => formRef.current?.submitForm()}
bodyStyle={{ padding: '0' }} confirmLoading={loading}
footer={ size={isMobile ? 'full-width' : 'small'}
<div className='flex justify-end'>
<Space>
<Button
theme='solid'
className='!rounded-lg'
onClick={() => formRef.current?.submitForm()}
icon={<IconSave />}
loading={loading}
>
{t('提交')}
</Button>
<Button
theme='light'
className='!rounded-lg'
type='primary'
onClick={onClose}
icon={<IconClose />}
>
{t('取消')}
</Button>
</Space>
</div>
}
closeIcon={null}
> >
<Spin spinning={loading}> <Spin spinning={loading}>
<Form <Form
@@ -185,20 +131,6 @@ const EditPrefillGroupModal = ({
}} }}
onSubmit={handleSubmit} onSubmit={handleSubmit}
> >
<div className='p-2'>
{/* 基本信息 */}
<Card className='!rounded-2xl shadow-sm border-0'>
<div className='flex items-center mb-2'>
<Avatar size='small' color='green' className='mr-2 shadow-md'>
<IconLayers size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('基本信息')}</Text>
<div className='text-xs text-gray-600'>
{t('设置预填组的基本信息')}
</div>
</div>
</div>
<Row gutter={12}> <Row gutter={12}>
<Col span={24}> <Col span={24}>
<Form.Input <Form.Input
@@ -240,9 +172,7 @@ const EditPrefillGroupModal = ({
? editingGroup.items ? editingGroup.items
: JSON.stringify(editingGroup.items || {}, null, 2)) : JSON.stringify(editingGroup.items || {}, null, 2))
} }
onChange={(val) => onChange={(val) => formRef.current?.setValue('items', val)}
formRef.current?.setValue('items', val)
}
editorType='object' editorType='object'
placeholder={ placeholder={
'{\n "openai": {"path": "/v1/chat/completions", "method": "POST"}\n}' '{\n "openai": {"path": "/v1/chat/completions", "method": "POST"}\n}'
@@ -263,11 +193,9 @@ const EditPrefillGroupModal = ({
)} )}
</Col> </Col>
</Row> </Row>
</Card>
</div>
</Form> </Form>
</Spin> </Spin>
</SideSheet> </Modal>
); );
}; };
@@ -37,6 +37,7 @@ import { MODEL_TABLE_PAGE_SIZE } from '../../../../constants';
import { useIsMobile } from '../../../../hooks/common/useIsMobile'; import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => { const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
const [paginationSize, setPaginationSize] = useState(MODEL_TABLE_PAGE_SIZE);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [missingModels, setMissingModels] = useState([]); const [missingModels, setMissingModels] = useState([]);
const [searchKeyword, setSearchKeyword] = useState(''); const [searchKeyword, setSearchKeyword] = useState('');
@@ -74,8 +75,8 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
); );
const dataSource = (() => { const dataSource = (() => {
const start = (currentPage - 1) * MODEL_TABLE_PAGE_SIZE; const start = (currentPage - 1) * paginationSize;
const end = start + MODEL_TABLE_PAGE_SIZE; const end = start + paginationSize;
return filteredModels.slice(start, end).map((model) => ({ return filteredModels.slice(start, end).map((model) => ({
model, model,
key: model, key: model,
@@ -169,10 +170,14 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
dataSource={dataSource} dataSource={dataSource}
pagination={{ pagination={{
currentPage: currentPage, currentPage: currentPage,
pageSize: MODEL_TABLE_PAGE_SIZE, pageSize: paginationSize,
total: filteredModels.length, total: filteredModels.length,
showSizeChanger: false, showSizeChanger: false,
onPageChange: (page) => setCurrentPage(page), onPageChange: (page) => setCurrentPage(page),
onPageSizeChange: (size) => {
setCurrentPage(1);
setPaginationSize(size);
},
}} }}
/> />
) : ( ) : (
@@ -17,7 +17,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { useState, useEffect } from 'react'; import '../../../console/module-alignment.css';
import React, { useState, useEffect, useCallback } from 'react';
import { import {
SideSheet, SideSheet,
Button, Button,
@@ -50,7 +51,7 @@ import {
renderDescription, renderDescription,
} from '../../../common/ui/RenderUtils'; } from '../../../common/ui/RenderUtils';
const { Text, Title } = Typography; const { Text } = Typography;
const PrefillGroupManagement = ({ visible, onClose }) => { const PrefillGroupManagement = ({ visible, onClose }) => {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -67,7 +68,7 @@ const PrefillGroupManagement = ({ visible, onClose }) => {
]; ];
// 加载组列表 // 加载组列表
const loadGroups = async () => { const loadGroups = useCallback(async () => {
setLoading(true); setLoading(true);
try { try {
const res = await API.get('/api/prefill_group'); const res = await API.get('/api/prefill_group');
@@ -80,7 +81,7 @@ const PrefillGroupManagement = ({ visible, onClose }) => {
showError(t('获取组列表失败')); showError(t('获取组列表失败'));
} }
setLoading(false); setLoading(false);
}; }, [t]);
// 删除组 // 删除组
const deleteGroup = async (id) => { const deleteGroup = async (id) => {
@@ -193,20 +194,20 @@ const PrefillGroupManagement = ({ visible, onClose }) => {
}, },
}, },
{ {
title: '', title: t('操作'),
key: 'action', key: 'action',
fixed: 'right', fixed: 'right',
width: 140, width: 140,
render: (_, record) => ( render: (_, record) => (
<Space> <Space className='console-module-row-actions'>
<Button size='small' onClick={() => handleEdit(record)}> <Button type='link' size='small' onClick={() => handleEdit(record)}>
{t('编辑')} {t('编辑')}
</Button> </Button>
<Popconfirm <Popconfirm
title={t('确定删除此组?')} title={t('确定删除此组?')}
onConfirm={() => deleteGroup(record.id)} onConfirm={() => deleteGroup(record.id)}
> >
<Button size='small' type='danger'> <Button size='small' type='link' danger>
{t('删除')} {t('删除')}
</Button> </Button>
</Popconfirm> </Popconfirm>
@@ -219,33 +220,25 @@ const PrefillGroupManagement = ({ visible, onClose }) => {
if (visible) { if (visible) {
loadGroups(); loadGroups();
} }
}, [visible]); }, [visible, loadGroups]);
return ( return (
<> <>
<SideSheet <SideSheet
placement='left' rootClassName='console-model-drawer'
title={ placement='right'
<Space> title={t('预填组管理')}
<Tag color='blue' shape='circle'> classNames={{ header: 'prefill-management-header' }}
{t('管理')}
</Tag>
<Title heading={4} className='m-0'>
{t('预填组管理')}
</Title>
</Space>
}
visible={visible} visible={visible}
onCancel={onClose} onCancel={onClose}
width={isMobile ? '100%' : 800} width={isMobile ? '100%' : 800}
bodyStyle={{ padding: '0' }} bodyStyle={{ padding: '0' }}
closeIcon={null}
> >
<Spin spinning={loading}> <Spin spinning={loading}>
<div className='p-2'> <div className='p-2'>
<Card className='!rounded-2xl shadow-sm border-0'> <Card className='!rounded-2xl shadow-sm border-0'>
<div className='flex items-center mb-2'> <div className='console-model-section'>
<Avatar size='small' color='blue' className='mr-2 shadow-md'> <Avatar size='small' color='blue'>
<IconLayers size={16} /> <IconLayers size={16} />
</Avatar> </Avatar>
<div> <div>
@@ -257,6 +250,7 @@ const PrefillGroupManagement = ({ visible, onClose }) => {
</div> </div>
<div className='flex justify-end mb-4'> <div className='flex justify-end mb-4'>
<Button <Button
className='console-create-action'
type='primary' type='primary'
theme='solid' theme='solid'
size='small' size='small'

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