Compare commits

..

19 Commits

Author SHA1 Message Date
zhanjunhao 3a0d9e15cd chore(repo): 合并推广分享与智能路由分支基线 2026-11-26 17:05:11 +08:00
zhanjunhao 04cf3324a3 feat(promotion/repo): 统一分享弹窗尺寸、暂隐藏奖励入口并清理仓库文件 2026-11-26 16:52:09 +08:00
qiubaishen a811793825 feat(router): 统一智能路由判定模型文案与多语言显示
同步全栈仓库 2e6865aa3 的 web/ 更新。
2026-11-26 16:25:40 +08:00
qiubaishen 9576ba674a feat(router): 同步 Jev 专用出站代理设置
同步全栈仓库 c3a1786c6 的 web/ 更新。
2026-11-26 15:34:33 +08:00
qiubaishen 870b51d054 feat: 同步权限管理、企业成员排行与消费计费明细
- 接入平台与企业角色权限,按权限展示菜单、页面及操作。
- 企业成员排行按需加载,翻页沿用同一榜单快照,保留连续名次与前三名样式。
- 更新消费日志的费用明细、超管指标和官方价格汇率设置,补齐翻译与回归测试。
2026-11-25 21:08:24 +08:00
zhanjunhao ed693a450a fix(org/vite): 修正成员排行跨页名次与配色,拦截开发服务的 .npmrc 请求 2026-11-25 16:29:05 +08:00
zhanjunhao 49515f4ef3 feat(*): 对齐兑换码与渠道表格,统一兑换码侧栏窗并固定消费记录首尾列 2026-11-25 16:27:09 +08:00
zhanjunhao f896495048 fix(console): 修复看板与作品详情加载并限制只读请求等待 2026-11-25 11:30:40 +08:00
zhanjunhao a532b860c8 fix(ui): 完善控制台列表并优化企业中心与个人操作 2026-11-25 10:05:30 +08:00
zhanjunhao dd4da99f1d fix(table): 统一筛选交互并补齐移动视口覆盖 2026-11-24 20:14:10 +08:00
zhanjunhao 437a0345e8 fix(ui): 统一三中心表格交互并优化企业及配套页面
- 公共表格:统一分组标签、状态开关和危险操作确认,支持防重复提交和失败重试,修复浮层触发组件的 ref 转发。
- 控制台:统一用户和渠道编辑抽屉,修正分组回填与提交格式,对齐系统设置操作区和预约列表。
- 企业中心:调整技能中心页签和窄屏布局,优化质量监控提示栏、效能分析及成本对账,统一消耗明细和审计日志筛选。
- 用户中心及公共页面:优化密钥和消费记录展示,对齐模型超市筛选,统一公开与内嵌客户端下载页。
- 同步多语言文案、组件规范与移动端视口要求。
2026-11-24 15:00:30 +08:00
zhanjunhao 9b9e98a6b4 feat(desktop-download): 优化下载页布局与主题表现 2026-11-23 19:51:04 +08:00
qiubaishen 574b6efa1e feat(web): 同步预约演示与兜底渠道优化 2026-11-23 17:54:37 +08:00
zhanjunhao 45979985fe fix(website-settings): 统一关于我们文案与翻译 2026-11-23 16:35:41 +08:00
zhanjunhao 4cd894b7ae fix(vite): 升级开发依赖并禁用 glob 转换 2026-11-23 16:07:24 +08:00
zhanjunhao 09e1d7cf7f feat(desktop-download): 优化下载页响应式布局与键盘导航 2026-11-23 12:53:58 +08:00
qiubaishen 2ae4a625b5 feat(weyai): 同步默认助手配置和译文
同步全栈仓库 weiyuan 分支的 WeyAi 默认助手配置页面、单测和九语言译文。
2026-11-23 10:27:02 +08:00
zhanjunhao 031e22ee49 fix: 视频生成任务队列分页 2026-11-21 15:20:52 +08:00
zhanjunhao ef67244aea feat(experience-center): 统一侧栏与页头,优化云端大脑、图片和视频生成界面 2026-11-20 21:38:32 +08:00
311 changed files with 27303 additions and 9145 deletions
+3
View File
@@ -4,6 +4,8 @@
node_modules/ node_modules/
/.pnp /.pnp
.pnp.js .pnp.js
bun.lock
bun.lockb
# testing # testing
/coverage /coverage
@@ -25,6 +27,7 @@ node_modules/
/build /build
/dist/ /dist/
/dist-ssr/ /dist-ssr/
vercel.json
# tool caches and temporary files # tool caches and temporary files
__pycache__/ __pycache__/
+2 -2
View File
@@ -104,7 +104,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd
1. **改前**:读相关代码;UI 任务先按 `GLOBAL_UI_BASELINE.md` 第 6 节真实 UI 登录;通用测试指令按该节自动判断验收范围、企业 / 普通个人 / 超管账号并加载现有本地配置,无需用户重复指定登录类型。 1. **改前**:读相关代码;UI 任务先按 `GLOBAL_UI_BASELINE.md` 第 6 节真实 UI 登录;通用测试指令按该节自动判断验收范围、企业 / 普通个人 / 超管账号并加载现有本地配置,无需用户重复指定登录类型。
2. **服务与浏览器**:优先通过项目目录、启动日志和监听进程查找并验证用户已运行的开发服务;仅确认不存在时才启动新服务,细节见全局基线第 7.1 节;Playwright + 本机 Chrome(`channel: 'chrome'`),无人值守设 `UI_VISUAL_OFFSCREEN=1`,单 Context 串行;有头运行遵守 `GLOBAL_UI_BASELINE.md` 7.1.1 焦点约束(唯一页面,不新建 / 切换标签页、不 `bringToFront`,用 `scripts/playwright-focus-guard.mjs` 检测前台)。 2. **服务与浏览器**:优先通过项目目录、启动日志和监听进程查找并验证用户已运行的开发服务;仅确认不存在时才启动新服务,细节见全局基线第 7.1 节;Playwright + 本机 Chrome(`channel: 'chrome'`),无人值守设 `UI_VISUAL_OFFSCREEN=1`,单 Context 串行;有头运行遵守 `GLOBAL_UI_BASELINE.md` 7.1.1 焦点约束(唯一页面,不新建 / 切换标签页、不 `bringToFront`,用 `scripts/playwright-focus-guard.mjs` 检测前台)。
3. **覆盖**:UI 规范验收为浅深主题 × 桌面 1920×1000 / 移动 393×851;正常、空数据、失败、校验、重复提交;只读验收的非 GET `/api/` 请求为 0;模拟与真实分开记录。配置默认值、服务复用与规范矩阵的差异见基线第 7.1 节,不能用默认 runner 结果替代完整验收。 3. **覆盖**:UI 规范验收为浅深主题 × 桌面 1920×1000 / 移动 393×851 与 360×800(最小必测视口);正常、空数据、失败、校验、重复提交;只读验收的非 GET `/api/` 请求为 0;模拟与真实分开记录。配置默认值、服务复用与规范矩阵的差异见基线第 7.1 节,不能用默认 runner 结果替代完整验收。
4. **检查**:`npm run eslint`、`npm run lint`、`npm test -- --test-concurrency=1`、`git diff --check`,涉及依赖或图标时加 `npm run check:ui`;纯文档改动只需 `npx prettier --check <文件>` 与 `git diff --check`。构建须先经用户同意,输出到系统临时目录(如 `npx vite build --outDir <临时目录> --emptyOutDir`),不覆盖 `dist/`。 4. **检查**:`npm run eslint`、`npm run lint`、`npm test -- --test-concurrency=1`、`git diff --check`,涉及依赖或图标时加 `npm run check:ui`;纯文档改动只需 `npx prettier --check <文件>` 与 `git diff --check`。构建须先经用户同意,输出到系统临时目录(如 `npx vite build --outDir <临时目录> --emptyOutDir`),不覆盖 `dist/`。
5. **证据与交付**:截图、trace、storageState、报告只写 Git 忽略目录;说明完成范围、实际验证结果与未覆盖项,未验证的不写成通过;在 `docs/CHANGELOG.md` 追加条目,改动脚本、环境变量或目录约定时同步更新 `README.md`。 5. **证据与交付**:截图、trace、storageState、报告只写 Git 忽略目录;说明完成范围、实际验证结果与未覆盖项,未验证的不写成通过;在 `docs/CHANGELOG.md` 追加条目,改动脚本、环境变量或目录约定时同步更新 `README.md`。
6. **提交**:授权按第 0 节,格式、检查与暂存边界见开发规范第 12.2 节。 6. **提交**:授权按第 0 节,格式、检查与暂存边界见开发规范第 12.2 节。
@@ -123,7 +123,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd
- 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。 - 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。
- 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。 - 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。
> 规范版本:v3.7 · 更新:2026-11-20 > 规范版本:v3.8 · 更新:2026-11-24
## 10. 工具差异(本节允许不同) ## 10. 工具差异(本节允许不同)
+2 -2
View File
@@ -104,7 +104,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd
1. **改前**:读相关代码;UI 任务先按 `GLOBAL_UI_BASELINE.md` 第 6 节真实 UI 登录;通用测试指令按该节自动判断验收范围、企业 / 普通个人 / 超管账号并加载现有本地配置,无需用户重复指定登录类型。 1. **改前**:读相关代码;UI 任务先按 `GLOBAL_UI_BASELINE.md` 第 6 节真实 UI 登录;通用测试指令按该节自动判断验收范围、企业 / 普通个人 / 超管账号并加载现有本地配置,无需用户重复指定登录类型。
2. **服务与浏览器**:优先通过项目目录、启动日志和监听进程查找并验证用户已运行的开发服务;仅确认不存在时才启动新服务,细节见全局基线第 7.1 节;Playwright + 本机 Chrome(`channel: 'chrome'`),无人值守设 `UI_VISUAL_OFFSCREEN=1`,单 Context 串行;有头运行遵守 `GLOBAL_UI_BASELINE.md` 7.1.1 焦点约束(唯一页面,不新建 / 切换标签页、不 `bringToFront`,用 `scripts/playwright-focus-guard.mjs` 检测前台)。 2. **服务与浏览器**:优先通过项目目录、启动日志和监听进程查找并验证用户已运行的开发服务;仅确认不存在时才启动新服务,细节见全局基线第 7.1 节;Playwright + 本机 Chrome(`channel: 'chrome'`),无人值守设 `UI_VISUAL_OFFSCREEN=1`,单 Context 串行;有头运行遵守 `GLOBAL_UI_BASELINE.md` 7.1.1 焦点约束(唯一页面,不新建 / 切换标签页、不 `bringToFront`,用 `scripts/playwright-focus-guard.mjs` 检测前台)。
3. **覆盖**:UI 规范验收为浅深主题 × 桌面 1920×1000 / 移动 393×851;正常、空数据、失败、校验、重复提交;只读验收的非 GET `/api/` 请求为 0;模拟与真实分开记录。配置默认值、服务复用与规范矩阵的差异见基线第 7.1 节,不能用默认 runner 结果替代完整验收。 3. **覆盖**:UI 规范验收为浅深主题 × 桌面 1920×1000 / 移动 393×851 与 360×800(最小必测视口);正常、空数据、失败、校验、重复提交;只读验收的非 GET `/api/` 请求为 0;模拟与真实分开记录。配置默认值、服务复用与规范矩阵的差异见基线第 7.1 节,不能用默认 runner 结果替代完整验收。
4. **检查**:`npm run eslint`、`npm run lint`、`npm test -- --test-concurrency=1`、`git diff --check`,涉及依赖或图标时加 `npm run check:ui`;纯文档改动只需 `npx prettier --check <文件>` 与 `git diff --check`。构建须先经用户同意,输出到系统临时目录(如 `npx vite build --outDir <临时目录> --emptyOutDir`),不覆盖 `dist/`。 4. **检查**:`npm run eslint`、`npm run lint`、`npm test -- --test-concurrency=1`、`git diff --check`,涉及依赖或图标时加 `npm run check:ui`;纯文档改动只需 `npx prettier --check <文件>` 与 `git diff --check`。构建须先经用户同意,输出到系统临时目录(如 `npx vite build --outDir <临时目录> --emptyOutDir`),不覆盖 `dist/`。
5. **证据与交付**:截图、trace、storageState、报告只写 Git 忽略目录;说明完成范围、实际验证结果与未覆盖项,未验证的不写成通过;在 `docs/CHANGELOG.md` 追加条目,改动脚本、环境变量或目录约定时同步更新 `README.md`。 5. **证据与交付**:截图、trace、storageState、报告只写 Git 忽略目录;说明完成范围、实际验证结果与未覆盖项,未验证的不写成通过;在 `docs/CHANGELOG.md` 追加条目,改动脚本、环境变量或目录约定时同步更新 `README.md`。
6. **提交**:授权按第 0 节,格式、检查与暂存边界见开发规范第 12.2 节。 6. **提交**:授权按第 0 节,格式、检查与暂存边界见开发规范第 12.2 节。
@@ -123,7 +123,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd
- 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。 - 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。
- 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。 - 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。
> 规范版本:v3.7 · 更新:2026-11-20 > 规范版本:v3.8 · 更新:2026-11-24
## 10. 工具差异(本节允许不同) ## 10. 工具差异(本节允许不同)
+6 -6
View File
@@ -26,7 +26,7 @@ Monkey AI Web 是从总仓库 `weiyuan` 分支独立出来的前端工程,包
环境要求:Node.js ≥ 22.13.0,npm ≥ 10(`packageManager` 为 npm 10.9.9)。统一使用 npm,不要用 Bun 或 Yarn 生成其他锁文件。 环境要求:Node.js ≥ 22.13.0,npm ≥ 10(`packageManager` 为 npm 10.9.9)。统一使用 npm,不要用 Bun 或 Yarn 生成其他锁文件。
仓库仅维护 `package-lock.json`,已移除 `bun.lock`,并忽略 `bun.lock` / `bun.lockb`。本地与 CI 使用 `npm ci` 安装依赖、`npm run dev` 启动开发服务、`npm run build` 构建;Vercel 已显式配置 npm 安装与构建命令。 仓库仅维护 `package-lock.json`,并忽略 `bun.lock` / `bun.lockb`。本地与 CI 使用 `npm ci` 安装依赖、`npm run dev` 启动开发服务、`npm run build` 构建。
```bash ```bash
git clone --branch weiyuan https://git.weytoken.com/qiubs/monkey-ai-web.git git clone --branch weiyuan https://git.weytoken.com/qiubs/monkey-ai-web.git
@@ -35,7 +35,7 @@ npm ci
npm run dev npm run dev
``` ```
开发服务监听 `0.0.0.0`,默认端口 5174,被占用时 Vite 自动顺延,以终端输出的 `Local:` 地址为准。需要供验收脚本读取地址时,把输出重定向到 `dev.log`(如 `nohup npm run dev > dev.log 2>&1 &`)。 开发服务默认监听 `0.0.0.0`,端口为 5174,支持访问本机地址和局域网 IP。端口被占用时 Vite 自动顺延,以终端输出的 `Local:` 和 `Network:` 地址为准。开发服务禁用项目未使用的 `import.meta.glob` 转换,普通动态导入和热更新照常使用。需要供验收脚本读取地址时,把输出重定向到 `dev.log`(如 `nohup npm run dev > dev.log 2>&1 &`)。
| 命令 | 模式 | 自动加载的配置文件 | | 命令 | 模式 | 自动加载的配置文件 |
| ----------------- | ----------- | ---------------------------------- | | ----------------- | ----------- | ---------------------------------- |
@@ -135,7 +135,6 @@ monkey-ai-web/
- **路由与权限**:在 `src/App.jsx` 注册路由,用 `PrivateRoute`、`AdminRoute`(role ≥ 10)、`RootRoute`(role ≥ 100)守卫;企业中心子路由在 `src/pages/Organization/index.jsx`。部分模块的可见性来自 `/api/status`,不能只靠隐藏菜单控制权限。 - **路由与权限**:在 `src/App.jsx` 注册路由,用 `PrivateRoute`、`AdminRoute`(role ≥ 10)、`RootRoute`(role ≥ 100)守卫;企业中心子路由在 `src/pages/Organization/index.jsx`。部分模块的可见性来自 `/api/status`,不能只靠隐藏菜单控制权限。
- **UI**:通用组件用 Ant Design;存量页面经 `src/components/ui` 适配层保留原契约;主题只由 `UiThemeProvider` 提供,不新增 ConfigProvider;按钮图标从 `src/components/common/icons/ActionIcons.js` 导入。页面改动需检查浅色、深色与窄屏。 - **UI**:通用组件用 Ant Design;存量页面经 `src/components/ui` 适配层保留原契约;主题只由 `UiThemeProvider` 提供,不新增 ConfigProvider;按钮图标从 `src/components/common/icons/ActionIcons.js` 导入。页面改动需检查浅色、深色与窄屏。
- **国际化**:文案写 `t('中文原文')`,新 key 补齐 `src/i18n/locales/` 下 9 个语言包;运行时开放语言以 `src/i18n/catalog.js` 为准(简中、繁中、英、日、韩、越、泰),`fr.json`、`ru.json` 尚未登记。 - **国际化**:文案写 `t('中文原文')`,新 key 补齐 `src/i18n/locales/` 下 9 个语言包;运行时开放语言以 `src/i18n/catalog.js` 为准(简中、繁中、英、日、韩、越、泰),`fr.json`、`ru.json` 尚未登记。
- **版权声明**:通用版权与许可声明见 [NOTICE.md](NOTICE.md),源码无需重复添加长文件头;保留独立的第三方声明。
## 6. 常用命令与提交检查 ## 6. 常用命令与提交检查
@@ -172,11 +171,12 @@ node --env-file=.env.playwright.local e2e/auth-login/run.mjs
测试先通过项目目录、启动日志与监听进程查找并验证已有开发服务;历史日志中的失效地址不能作为新启服务的依据。仅确认本项目服务不存在时才启动,结束时只清理本次启动的进程。项目 Playwright 配置和专项验收通过 `scripts/dev-service.mjs` 自动发现并复用服务(验证 Vite 源码映射属于当前项目,兼容 UTF-8 / UTF-16LE 日志);显式目标仍按调用方配置执行。本地登录脚本同样先发现已有服务,使用本机 Chrome 离屏串行执行企业 A/B 状态判定、真实 UI 登录、后台主体断言、个人端全新 Context 登录和 UI 退出。企业 A 路径先填写企业名称并点击“下一步”,B 路径直接填写登录名和密码;不可覆盖的路径单独记录。后续搜索按钮验收拦截非 GET 写请求;截图、脱敏失败记录与供后续用例复用的 storageState 保存在 `report/auth-login-<时间>/`,均为本地忽略产物。storageState 含会话凭据,不上传、不提交;登录规则见 `docs/ui/GLOBAL_UI_BASELINE.md` 第 6 节。 测试先通过项目目录、启动日志与监听进程查找并验证已有开发服务;历史日志中的失效地址不能作为新启服务的依据。仅确认本项目服务不存在时才启动,结束时只清理本次启动的进程。项目 Playwright 配置和专项验收通过 `scripts/dev-service.mjs` 自动发现并复用服务(验证 Vite 源码映射属于当前项目,兼容 UTF-8 / UTF-16LE 日志);显式目标仍按调用方配置执行。本地登录脚本同样先发现已有服务,使用本机 Chrome 离屏串行执行企业 A/B 状态判定、真实 UI 登录、后台主体断言、个人端全新 Context 登录和 UI 退出。企业 A 路径先填写企业名称并点击“下一步”,B 路径直接填写登录名和密码;不可覆盖的路径单独记录。后续搜索按钮验收拦截非 GET 写请求;截图、脱敏失败记录与供后续用例复用的 storageState 保存在 `report/auth-login-<时间>/`,均为本地忽略产物。storageState 含会话凭据,不上传、不提交;登录规则见 `docs/ui/GLOBAL_UI_BASELINE.md` 第 6 节。
Playwright 与 weelink 共用设备环境约定,依赖精确锁定 1.64.1;本项目 runner 优先复用已核验的现有开发服务,仅确认不存在时才使用 4176,避免与 weelink 的 4175 冲突。配置读取 `scripts/ui-review/config.json`,用例通过 `scripts/playwright-test.mjs` 的公共 fixture 后台建页并守护焦点。独立脚本使用 `scripts/playwright-focus-guard.mjs` 的 `launchFocusSafe()`,两类流程保留各自执行策略。前台激活或探测失败会记录并停止,离屏不保证绝无瞬时激活。环境变量和截图口径见 [全局基线第 7.1 节](docs/ui/GLOBAL_UI_BASELINE.md#71-工具)。 Playwright 默认运行桌面及两个移动项目:`chrome-mobile`(最小视口 360×800)与 `chrome-mobile-393`(393×851)。通用用例继承项目视口,专项用例可覆盖视口测试指定场景。Playwright 与 weelink 共用设备环境约定,依赖精确锁定 1.64.1;本项目 runner 优先复用已核验的现有开发服务,仅确认不存在时才使用 4176,避免与 weelink 的 4175 冲突。配置读取 `scripts/ui-review/config.json`,用例通过 `scripts/playwright-test.mjs` 的公共 fixture 后台建页并守护焦点。独立脚本使用 `scripts/playwright-focus-guard.mjs` 的 `launchFocusSafe()`,两类流程保留各自执行策略。前台激活或探测失败会记录并停止,离屏不保证绝无瞬时激活。环境变量和截图口径见 [全局基线第 7.1 节](docs/ui/GLOBAL_UI_BASELINE.md#71-工具)。
| 命令 / 参数 | 用途与默认值 | | 命令 / 参数 | 用途与默认值 |
| --- | --- | | --- | --- |
| `npm run test:e2e:headless` | 无头运行;本地默认有头离屏,CI 强制无头 | | `npm run test:e2e:headless` | 无头运行;本地默认有头离屏,CI 强制无头 |
| `npm run test:e2e -- --project=chrome-mobile` | 运行默认配置中的 360×800 手机项目。专项 UI 验收也须覆盖此最小视口 |
| `npm run test:e2e:extended` | 全部 8 视口;也可设置 `PW_EXTENDED_LAYOUT=1` | | `npm run test:e2e:extended` | 全部 8 视口;也可设置 `PW_EXTENDED_LAYOUT=1` |
| `npm run test:e2e:dist` | 验证已有静态产物并严格启动 4176;不自动构建 | | `npm run test:e2e:dist` | 验证已有静态产物并严格启动 4176;不自动构建 |
| `npm run test:acceptance -- <参数>` | 串行单测、临时目录构建、产物校验、强制 local-dist/4176 测试 | | `npm run test:acceptance -- <参数>` | 串行单测、临时目录构建、产物校验、强制 local-dist/4176 测试 |
@@ -203,19 +203,19 @@ npm run preview
将 `dist/` 作为静态站点发布,部署环境需处理: 将 `dist/` 作为静态站点发布,部署环境需处理:
- **共享测试环境**:局域网沿用现有域名或 IP 与端口。由网关提供构建后的静态文件和 SPA 路由回退,并继续转发测试后端接口。Vite 的源码转换与 HMR 只用于独立的开发服务。自动发布时,先完成构建与检查,再切换站点目录,避免访问到构建中的文件。
- **路由回退**:使用 BrowserRouter,直接访问 `/org/...` 等页面时静态服务器需回退到 `index.html`,否则刷新返回 404。 - **路由回退**:使用 BrowserRouter,直接访问 `/org/...` 等页面时静态服务器需回退到 `index.html`,否则刷新返回 404。
- **接口转发**:生产环境配置反向代理或独立后端地址;Vite 开发代理不会进入产物,`preview` 不能代替生产网关。 - **接口转发**:生产环境配置反向代理或独立后端地址;Vite 开发代理不会进入产物,`preview` 不能代替生产网关。
- **流式与长连接**:SSE 接口需关闭响应缓冲并设置合理超时;WebSocket 需配置连接升级。 - **流式与长连接**:SSE 接口需关闭响应缓冲并设置合理超时;WebSocket 需配置连接升级。
- **缓存**:`index.html` 应及时更新,带哈希的静态资源可长缓存;后端地址写在产物中,切换需重新构建并发布。 - **缓存**:`index.html` 应及时更新,带哈希的静态资源可长缓存;后端地址写在产物中,切换需重新构建并发布。
- **部署路径**:当前按域名根路径部署;部署到子目录需检查 Vite `base`、路由与静态资源地址。 - **部署路径**:当前按域名根路径部署;部署到子目录需检查 Vite `base`、路由与静态资源地址。
仓库中的 `vercel.json` 只关闭了 GitHub 通知,未配置路由回退或代理,不能作为完整部署配置。
## 8. 常见问题 ## 8. 常见问题
| 现象 | 优先检查 | | 现象 | 优先检查 |
| --- | --- | | --- | --- |
| 页面能打开但提示状态或接口加载失败 | 后端是否可用;Network 中 `/api/status` 的目标地址与响应;代理配置 | | 页面能打开但提示状态或接口加载失败 | 后端是否可用;Network 中 `/api/status` 的目标地址与响应;代理配置 |
| 共享测试站出现 Vite 红色遮罩 | 检查站点网关的前端上游。共享测试站应由网关提供构建后的静态文件,Vite 开发服务仅用于联调。开发服务对 `.npmrc` 请求直接返回 404。 |
| 登录后又回到登录页 | `/api/user/self` 响应、Cookie 是否发送、跨域凭证策略、账号状态 | | 登录后又回到登录页 | `/api/user/self` 响应、Cookie 是否发送、跨域凭证策略、账号状态 |
| 企业数据为空或串到其他企业 | 当前组织选择、`current_org_id` 与请求头 `X-Org-Id` | | 企业数据为空或串到其他企业 | 当前组织选择、`current_org_id` 与请求头 `X-Org-Id` |
| 修改环境变量后无变化 | 是否重启开发服务或重新构建发布;HTML 与静态资源缓存 | | 修改环境变量后无变化 | 是否重启开发服务或重新构建发布;HTML 与静态资源缓存 |
+546 -1
View File
@@ -1,6 +1,6 @@
# 变更记录(CHANGELOG) # 变更记录(CHANGELOG)
> 状态:有效(持续追加) · 更新:2026-11-21 · 版本:v3.7 > 状态:有效(持续追加) · 更新:2026-11-26 · 版本:v3.14
对现状仍有影响的功能与修复记录,按日期倒序。改造、迁移、优化等一次性过程不在此记录。 对现状仍有影响的功能与修复记录,按日期倒序。改造、迁移、优化等一次性过程不在此记录。
@@ -8,6 +8,551 @@
**记录规则**:每条写“范围、变更、影响、回滚、关联”五项;回滚优先 `git revert <提交>`,提交含多项改动时按文件还原(`git checkout <提交>^ -- <文件>`),不整仓 reset。本文不作为规则依据。 **记录规则**:每条写“范围、变更、影响、回滚、关联”五项;回滚优先 `git revert <提交>`,提交含多项改动时按文件还原(`git checkout <提交>^ -- <文件>`),不整仓 reset。本文不作为规则依据。
## 2026-11-26
### 统一智能路由的判定模型文案
- **范围** 个人、平台和企业的判定明细、试路由、集合、授权和管理设置。
- **变更** 判定来源显示「智能路由」,合规闸门显示「已调用模型」或对应原因。集合开关说明使用判定模型所需的平台设置和出境授权。
- **影响** 历史判定记录按新文案展示,新增管理日志使用「判定模型」名称。
- **回滚** 恢复对应的状态标签、语言包与后端提示文案。
- **关联** [智能路由判定模型文案调整方案](../../docs/04-渠道与路由/22-智能路由判定模型文案调整方案.md)。
### 智能路由支持 Jev 专用出站代理
- **范围** 智能路由全局设置中的 Jev 判定请求。
- **变更** 超级管理员可以配置、测试和清除 HTTP、HTTPS 或 SOCKS5 系列代理。
- **影响** 测试展示 Google 连通性、耗时、出口 IP 和国家或地区。
- **回滚** 清除代理即可恢复 Jev 原有的服务器网络设置。
- **关联** 智能路由 Jev 设置和管理接口。
### 修复 · 稳定推广分享弹窗高度
- **范围**:顶栏「推广分享」弹窗的链接分享和海报分享页签。
- **变更**:两个页签共用等高的内容区,并按视口限制高度。邀请卡片和海报预览共用列宽、圆角和最小高度。
- **影响**:切换页签时弹窗位置保持稳定,两张卡片对齐,内容超出可用高度时在页签内滚动。
- **回滚**:恢复推广分享弹窗原有的页签高度、滚动和预览卡片样式。
- **关联**:`src/components/promotion/promotion-poster.css`。
### 清理 · 移除 Bun 锁文件、Vercel 配置和根目录声明文档
- **范围**:依赖锁文件、Vercel 配置、根目录声明文档和 Git 忽略规则。
- **变更**:移除 `bun.lock`、`vercel.json` 和 `NOTICE.md`,清理现行文档中的对应引用,忽略 `bun.lock`、`bun.lockb` 和 `vercel.json`。
- **影响**:npm 继续使用 `package-lock.json`。Vercel Git 部署改由 Vercel 项目设置提供安装和构建命令。
- **回滚**:还原本次文档和忽略规则改动,并从变更前的 Git 版本恢复三个文件。
- **关联**:`.gitignore`、`README.md`、`docs/standards/DEV_STANDARDS.md`。
### 调整 · 暂时隐藏推广分享中的邀请奖励规则入口
- **范围**:顶栏「推广 → 推广分享」弹窗。
- **变更**:暂停渲染弹窗底部「查看邀请奖励规则」入口。
- **影响**:用户仍可通过弹窗分享邀请链接、邀请码和海报。
- **回滚**:将 `SHOW_INVITATION_REWARD_RULES` 设为 `true`。
- **关联**:`src/components/promotion/PromotionPosterModal.jsx`。
## 2026-11-25
### 优化 · 成员排行按需加载并固定翻页结果
- **范围**:企业中心「消耗明细 → 成员排行」。
- **变更**:打开排行页签时按已应用的筛选查询,翻页和更改每页人数时沿用同一快照。刷新或重新筛选会获取当前榜单。
- **影响**:查看明细日志时省去排行请求。榜单更新期间翻页仍显示同一时点的名次;快照过期后自动回到第 1 页。
- **回滚**:恢复前端原有的排行加载与分页逻辑;分页响应兼容未传快照的客户端。
- **关联**:`src/pages/Organization/OrgLogs.jsx`、`src/hooks/org/useOrgData.js`、`docs/ui/ORG_CENTER_SPEC.md`。
### 优化 · 企业消耗明细成员排行支持服务端分页
- **范围**:企业中心「消耗明细 → 成员排行」及 `GET /api/org/logs/ranking`。
- **变更**:在权限和筛选范围内按成员汇总,消耗额度由高到低,同额按成员 ID 升序,返回当前页和总人数。
- **影响**:可以翻到第 50 名以后,跨页名次连续,前三名沿用主题强调色。
- **回滚**:先回退前端排行分页,再回退后端接口。旧前端仍可使用原有的 `limit` 查询。
- **关联**:`src/pages/Organization/OrgLogs.jsx`、`src/hooks/org/useOrgData.js`。
### 同步 · 三中心列表与本地权限适配
- **范围**:合入纯前端仓库 `weiyuan` 从 `574b6efa1` 至 `ed693a450` 的增量。
- **变更**:用户列表的自动搜索同时传递状态筛选和取消信号,企业日志在后续页重新筛选时同步刷新总数。企业内容页按操作权限显示创建、上传、分发与删除入口。兑换码按后端的查询、创建、编辑和删除权限显示操作,启停沿用编辑权限。个人密钥编辑表单在打开时加载模型、分组和技能选项。
- **影响**:角色分配、额度调整、模型映射、企业代理会话以及日志查询、排行、导出的独立权限继续使用全栈接口契约。
- **回滚**:按对应页面和共享依赖回退本次前端增量。
- **关联**:`src/components/table/users/`、`src/hooks/org/useOrgData.js`、`src/pages/Organization/`。
### 优化 · 消费记录固定首尾列
- **范围**:用户中心 `/user-center/usage-record` 的消费记录调用明细。
- **变更**:时间列固定在左侧,操作列显示时固定在右侧。
- **影响**:横向滚动中间字段时,仍可读取时间并打开账单详情。
- **回滚**:还原消费记录时间列和操作列的固定配置。
- **关联**:`src/components/table/usage-logs/`、`docs/ui/USER_CENTER_SPEC.md`。
### 优化 · 兑换码编辑侧栏窗
- **范围**:控制台 `/console/redemption` 编辑入口。
- **变更**:编辑兑换码信息与添加兑换码共用右侧侧栏窗。
- **影响**:两种表单使用相同的宽度、关闭方式和页脚,编辑继续回填当前记录。
- **回滚**:还原兑换码编辑表单的独立弹窗。
- **关联**:`src/components/table/redemptions/modals/EditRedemptionModal.jsx`、`docs/ui/CONSOLE_SPEC.md`。
### 优化 · 兑换码列表行内操作
- **范围**:控制台 `/console/redemption` 表格操作列。
- **变更**:「查看详情」入口简化为「查看」,启用、禁用和删除从更多菜单移至行内,按钮单行排列并随操作列固定在右侧。
- **影响**:桌面与窄屏均可直接使用行操作,启停权限和删除确认沿用原规则。
- **回滚**:还原兑换码操作列按钮、宽度和换行样式。
- **关联**:`src/components/table/redemptions/`、`docs/ui/CONSOLE_SPEC.md`。
### 优化 · 兑换码列表与表单
- **范围**:控制台 `/console/redemption` 与 `/console/channel` 的表头。
- **变更**:沿用渠道列表的表格与行内操作样式,提升两页表头文字对比度,固定兑换码操作列,新增同页详情弹窗,统一添加侧栏窗与编辑弹窗的表单及页脚。
- **影响**:可在详情弹窗查看与复制原码,批量复制随选中态启用,清除失效操作保留二次确认。
- **回滚**:还原兑换码列表、表单、详情弹窗和对应样式与文案。
- **关联**:`src/components/table/redemptions/`、`docs/ui/CONSOLE_SPEC.md`。
### 修复 · 企业成员排行的主题色与跨页名次
- **范围**:企业中心 `/org/logs` 的成员排行。
- **变更**:前三名使用主题派生的三档底色,其他名次使用中性色;在分页前生成全表名次。
- **影响**:切换系统主色或明暗模式时,排名徽章同步更新;翻页时继续显示全表名次。
- **回滚**:还原排名列的名次生成和徽章配色。
- **关联**:`src/pages/Organization/OrgLogs.jsx`、`src/styles/org-center.css`、`docs/ui/ORG_CENTER_SPEC.md`。
### 修复 · Vite 读取 npm 配置文件触发错误遮罩
- **范围**:Vite 开发服务的文件请求处理。
- **变更**:在资源转换前拦截 `.npmrc` 请求并返回 404,同时将 `.npmrc` 加入文件访问拒绝列表。
- **影响**:npm 配置文件请求不会启动资源转换或触发全站热更新错误遮罩。应用使用的文本资源导入继续由 Vite 转换。
- **回滚**:还原 Vite 的 npm 配置文件拦截和对应访问规则。
- **关联**:`vite.config.js`、`README.md`。
### 修复 · 控制台数据看板持续加载
- **范围**:控制台 `/console/analytics` 运营看板、创作作品详情抽屉及公共 API 的只读请求。
- **变更**:看板首轮查询取消后可重新发起,作品详情的当前副作用接管加载状态。只读请求默认 60 秒超时,运营看板核心请求设置为 30 秒。
- **影响**:两处首次加载可正常结束。只读接口持续无响应时返回超时错误,页面可按原有失败流程结束加载。
- **回滚**:还原运营看板和作品详情的加载处理,以及公共 API 的只读超时。
- **关联**:`src/hooks/analytics/useAnalyticsData.js`、`src/components/creation/WorkFeed/WorkDetailDrawer.jsx`、`src/helpers/api.js`。
## 2026-11-24
### 功能 · 计费详情弹窗增加费用明细与计算公式
- **范围**:使用记录 `/user-center/usage-record` 与控制台使用日志的「详情」弹窗(共用 `UsageLogsTable.jsx`)。
- **变更**:新增「费用明细」:公式行(总金额 = 各计费项小计相加)与分项表(计费项、用量、单价、小计、合计),每行标注单价由哪些倍率构成;用量从「成本因子」移到分项表,成本因子只留倍率等补充信息。拆分逻辑在 `billingBreakdown.js`,口径对照后端结算公式;各行按展示精度四舍五入后与合计的差额归入「舍入与其他调整」一项,保证界面上的数字逐项相加恰好等于合计(`reconcileDisplayAmounts`);分项之和与实扣相差超过 1 个额度单位时视为口径未覆盖(如任务按时长 / 分辨率系数计价),token 兜底预扣与差额调整行同样不拆分,这些情况都不显示费用明细。已在费用明细里逐行列出的用量不再出现在成本因子区;按次 / 按秒计费的明细里没有 token 行,token 用量仍留在成本因子区。弹窗里的倍率由保留 3 位小数改为最多 6 位。超级管理员多一个「超管指标」区块,三项:官方价金额(1 倍率)= 同样用量按「模型原厂价格」计价 ÷ 原厂价登记汇率,整体倍率 = 实扣 ÷ 官方价金额,实际折扣 = 整体倍率 ÷ 登记汇率(汇率在 系统设置-倍率设置-模型原厂价格 页签顶部配置,option `OfficialPriceExchangeRate`,默认 7,仅超级管理员可读写),由后端只在超级管理员的日志响应里附加(`other.root_billing`,不落库),普通管理员与用户的接口不返回;未登记原厂价、或含音频 / 图片输入 / 工具调用等原厂价格表没有价目的计费项时不显示;按次计费但实扣含任务系数、出图接口、token 兜底预扣与差额调整行同样不显示。
- **影响**:前端只改展示,不改请求。同批后端改动会改变扣费:Claude 联网搜索开始按次计费(此前算了价但未扣,流式与原生 Claude 格式此前也不记录次数;只对 Claude 模型收,其他走 Anthropic 协议的渠道即使上报搜索次数也不收;体验中心 / Playground 对 Claude 模型开启原生联网搜索时同样会多出这笔费用);扣费取整统一为四舍五入到 1 个额度单位(`common.QuotaFromFloat`,取整前先消除浮点噪声):Claude 原生结算、按次 / 按秒 / 任务类计费此前是向下取整,现在小数部分 ≥ 0.5 的每笔多 1 个额度单位(如 0.3 × 1.5 × 500000 由 224999 变为 225000);OpenAI 兼容路径原本就是四舍五入,不变。Claude 原生与音频 / 实时语音路径有费用时至少扣 1 个额度单位(此前不足 1 个单位扣 0)。邀请返佣仍向下取整(`common.QuotaFloorFromFloat`,只消除浮点噪声),保证返佣不超过「比例 × 消费」;token 预扣估算是准入闸门、不是最终扣费,保持原样。发布窗口内已提交未结算的视频任务,预扣(旧版向下取整)与结算(新版四舍五入)可能差 1 个额度单位:结算时重算结果与预扣只差 1 个单位的按预扣结清(`common.SettleRecomputedQuota`),不补扣不退款。缺少计费信息的日志不显示费用明细,弹窗与原来一致。后端结算公式变更时须同步 `billingBreakdown.js`。本条未做浏览器走查。
- **回滚**:`git revert` 对应提交;`billingBreakdown.js` 与其单测为新增文件。
- **关联**:`src/components/table/usage-logs/{UsageLogsTable.jsx,billingBreakdown.js,UsageLogs.css}`、`src/pages/Setting/Ratio/OfficialPriceExchangeRateSetting.jsx`、`test/unit/{usage-billing-breakdown,usage-billing-detail-render,official-price-exchange-rate-setting}.test.js`、后端 `common/quota.go`、`relay/compatible_handler.go`、`relay/channel/claude/relay-claude.go`、`service/quota.go`、`service/log_overall_ratio.go`、`controller/log.go`。
### 修复 · 企业登录接入人机验证
- **范围**:企业登录页 `/org/login`(企业标识登录与免企业标识直登)。
- **变更**:系统开启 Turnstile 时,企业登录页显示人机验证,提交 `/api/org/login`、`/api/org/login/direct` 时带上 `turnstile` 参数;后端两条接口同步挂上 `TurnstileCheck`(未开启时自动放行)。
- **影响**:未开启 Turnstile 的部署无变化。开启后,企业成员在通过人机验证前不能提交登录;两步验证、多企业选择两步不再重复验证。
- **回滚**:`git revert` 对应提交(前后端须一起回滚,只回滚前端会导致开启 Turnstile 的部署无法企业登录)。
- **关联**:`src/pages/OrgLogin/index.jsx`、`router/org-router.go`。
### 新增 · 渠道透传时应用模型映射
- **范围**:控制台渠道编辑框的「渠道额外设置」。
- **变更**:「透传请求体」下方新增「透传时应用模型映射」,支持单独开启并保存。
- **影响**:新建渠道和缺少该设置的历史渠道默认关闭。开启后,实际透传且命中渠道映射的请求使用映射后的上游模型名。
- **回滚**:关闭该渠道的「透传时应用模型映射」并保存。
- **关联**:`src/components/table/channels/modals/EditChannelModal.jsx`、`src/i18n/locales/`。
### 修复 · 控制台会员列表与弹窗
- **范围**:控制台 `/console/subscription` 的会员列表、新建与编辑会员卡弹窗。
- **变更**:列表卡补充「会员列表」标题,快捷筛选移到标题之后。操作列沿用用户列表的「编辑」和「更多」,额度与金额右对齐。新建和编辑弹窗的主按钮统一为「确定」,桌面宽度调整为 575px。
- **影响**:有效会员行可正常渲染。补发额度从「更多」进入确认弹窗,原有筛选和会员操作仍使用原接口。
- **回滚**:还原会员页的工具栏、操作列、弹窗和对应翻译。
- **关联**:`src/pages/Subscription/index.jsx`、`src/i18n/locales/`、`docs/standards/UI_COMPONENT_STANDARDS.md`。
### 调整 · 顶栏推广海报预览
- **范围**:顶栏「推广分享」弹窗的「海报分享」页签。
- **变更**:模板色铺满海报预览区,色块、预览和 PNG 导出共用配色。通过 CSS 隐藏海报页签的奖励规则入口。
- **影响**:切换模板时整块预览同步换色,「链接分享」页签仍可打开奖励规则。
- **回滚**:还原推广弹窗的模板配色与奖励入口显隐样式。
- **关联**:`src/components/promotion/PromotionPosterModal.jsx`、`src/components/promotion/promotion-poster.css`。
### 调整 · Playwright 默认覆盖两档移动视口
- **范围**:项目 Playwright 配置与设备环境校验。
- **变更**:显式保留 `chrome-mobile` 的 360×800,新增默认项目 `chrome-mobile-393` 覆盖 393×851。
- **影响**:继承项目视口的用例默认在两档手机尺寸运行,设备环境检查校验实际尺寸、触摸和截图。
- **回滚**:从默认项目与设备配置移除 393×851 项目,并恢复对应断言。
- **关联**:`playwright.config.js`、`scripts/browser-environment.mjs`、`scripts/ui-review/config.json`。
### 修复 · 企业设置的数据库密码表单
- **范围**:企业设置「提示词采集」的数据库连接配置。
- **变更**:将数据库连接字段放入原生表单,为数据库用户名和密码指定自动填充属性。
- **影响**:消除 Chrome 对数据库凭据字段的表单和自动填充警告。
- **回滚**:还原数据库连接配置表单的 `component` 属性和两个凭据字段的 `autoComplete` 属性。
- **关联**:`src/pages/Organization/OrgSettings.jsx`。
### 修复 · 渠道自动禁用开关初始化
- **范围**:控制台渠道管理的新建和编辑渠道表单。
- **变更**:表单统一初始化「是否自动禁用」,详情返回的 0 和 1 转为开关使用的布尔值。
- **影响**:消除 `auto_ban` 重复初始化警告,提交仍使用 0 或 1。
- **回滚**:还原自动禁用开关的初始化配置。
- **关联**:`src/components/table/channels/modals/EditChannelModal.jsx`。
### 调整 · 企业设置数据安全页签间距
- **范围**:企业设置「数据安全」的子页签。
- **变更**:去掉子页签叠加的顶部内边距,沿用设置卡的 24px 内容间距。
- **影响**:子页签文字与「登录与安全」的内容标题从相同高度开始。
- **回滚**:移除企业设置对子页签顶部内边距的覆盖。
- **关联**:`src/styles/org-center.css`。
### 调整 · 编辑标签的请求头变量提示
- **范围**:控制台渠道管理的「编辑标签」抽屉。
- **变更**:将「支持变量」与渠道密钥占位符合并为一行,使用相同的字体和样式。
- **影响**:请求头模板仍使用 `{api_key}`,表单行为保持原样。
- **回滚**:还原请求头变量提示的布局。
- **关联**:`src/components/table/channels/modals/EditTagModal.jsx`。
### 调整 · 渠道列表复选框与创建入口
- **范围**:控制台 `/console/channel` 的普通列表和标签聚合模式。
- **变更**:多选复选框固定在表格左侧,「创建渠道」移到列表工具栏右侧、列设置按钮左边。
- **影响**:窄屏横向滚动时仍可选择渠道,标签分组行保持不可选。创建权限和弹窗沿用原流程。
- **回滚**:还原多选列的固定配置,并将创建按钮移回分类页签区域。
- **关联**:`src/components/table/channels/ChannelsTable.jsx`、`src/components/table/channels/index.jsx`、`src/components/table/channels/ChannelsTabs.jsx`。
### 调整 · 表格日期范围与自动搜索
- **范围**:控制台、企业中心、用户中心的表格筛选区。
- **变更**:日期范围共用快捷周期、格式和确认交互。接入公共 300ms 搜索调度,可取消过期查询。个人密钥的本地过滤按批处理。
- **影响**:搜索保留当前页与表格操作状态,重置恢复各页面默认条件及初始页。
- **回滚**:按受影响页面恢复筛选事件和列表请求,并还原表格日期和搜索公共入口。
- **关联**:`docs/standards/UI_COMPONENT_STANDARDS.md` 第 4、6 节,`src/hooks/common/useFilterSearch.js`。
### 调整 · 控制台预约、渠道与企业列表
- **范围**:控制台 `/console/demo-reservations`、`/console/channel`、`/console/organizations`。
- **变更**:预约列表将「状态」改为「是否已响应」,两态开关隐藏内部文字。开启时确认「是否进行响应」,关闭时确认「是否取消响应」。渠道列表固定 ID 和名称,企业列表固定 ID 和企业名称。
- **影响**:渠道及企业列表的操作列固定在右侧,多选框和其他未固定列在表格内横向滚动。窄屏空间不足时,左侧列参与滚动,为右侧操作和表格内容留出空间。预约开关沿用原确认流程。
- **回滚**:还原预约表头和开关配置,以及渠道、企业列表的固定列配置。
- **关联**:`src/pages/DemoReservations/index.jsx`、`src/components/table/channels/ChannelsTable.jsx`、`src/pages/AdminOrganizations/index.jsx`。
### 调整 · 业务系统授权标题
- **范围**:`/org/my-capabilities?tab=connectors`。
- **变更**:主标题改为「业务系统授权」,与页签共用文案。
- **影响**:两个页签的主标题都使用各自的页签名称。
- **回滚**:恢复主标题单独配置。
- **关联**:`src/pages/Organization/OrgMyCapabilities.jsx`。
### 调整 · 我的 AI 能力页签位置
- **范围**:企业中心 `/org/my-capabilities`。
- **变更**:将「我的技能」「业务系统授权」页签移到通用页头下方,统一页签和正文的左右边距。
- **影响**:切换后展示当前页签对应的标题、说明和使用指引,旧路由和模块开关沿用原逻辑。
- **回滚**:还原合并页的页头渲染方式和两个子页的页头。
- **关联**:`src/pages/Organization/OrgMyCapabilities.jsx`、`src/pages/Organization/OrgMySkills.jsx`、`src/pages/Organization/OrgMyConnectors.jsx`。
### 调整 · 企业云端大脑界面与导航
- **范围**:企业中心 `/org/cloud-brain` 的页头、页签和工作区布局。
- **变更**:与体验中心云端大脑共用页头与线型页签,统一内容边距、图标和操作区排布。页签支持方向键移动焦点和键盘确认。
- **影响**:保留企业专家管理、项目关联、专家卡片与任务流程。管理面板可通过「完成管理」或选择页签返回工作区。
- **回滚**:还原企业页头和页签分支及对应样式。
- **关联**:`src/pages/CloudBrain/index.jsx`、`src/pages/CloudBrain/cloud-brain.css`、`src/pages/ExperienceCenter/components/ExperiencePageHeader.jsx`。
### 调整 · 企业知识页页头、引导间距与保存文案
- **范围**:企业中心 `/org/knowledge`。
- **变更**:页头对齐体验中心云端大脑,移除「企业可信知识层」标签,将 BETA 徽标移至「企业知识」标题右侧。「快速上手」提示条上方增加 12px 留白,两个知识库弹窗的主按钮统一为「保存」。
- **影响**:页头使用统一的面包屑、标题和说明布局,两个弹窗沿用各自的提交逻辑。
- **回滚**:还原原页头、提示条外边距和两个弹窗的确认按钮文案。
- **关联**:`src/pages/Organization/OrgKnowledge.jsx`、`src/pages/Organization/org-knowledge.css`。
### 调整 · 企业调用质量页头
- **范围**:企业中心调用质量页。
- **变更**:移除主标题上方重复的「调用质量」标签,使用通用企业页头。
- **影响**:主标题和说明对齐企业中心规范,面包屑与使用指引保留原入口。
- **回滚**:还原调用质量页头及对应的局部样式。
- **关联**:`src/pages/Organization/OrgQuality.jsx`、`src/pages/Organization/org-quality.css`、`src/styles/org-page.css`。
### 修复 · 企业技能治理快速上手条
- **范围**:企业专家工坊、分发与锁定和业务系统连接器的快速上手条。
- **变更**:网格内容从顶部按自然高度排列,连接器的快速上手条到页签导航的间距缩为 8px。
- **影响**:内容较少时,页头、引导条与下方内容保持紧凑,引导条继续打开原有抽屉。
- **回滚**:移除共用网格的顶部对齐声明和连接器页签的间距覆盖。
- **关联**:`src/styles/org-page.css`、`src/pages/Organization/OrgConnectors.jsx`、`src/pages/Organization/org-connectors.css`。
### 调整 · 企业 Agent 任务审计
- **范围**:企业中心 `/org/agent-audit` 的任务元数据、待对账、安全策略及正文弹窗。
- **变更**:任务卡片区分运行与计费状态,补充页签计数、空状态、表单标签与保存反馈,支持窄屏读取长编号。
- **影响**:审计入口、筛选分页、策略保留和正文二次确认继续使用现有接口与权限。操作反馈沿用系统主题色,状态标签保留语义色。
- **回滚**:还原该页组件、页面样式、原专家样式中的审计规则和对应语言项。
- **关联**:`src/pages/Organization/OrgAgentAudit.jsx`、`src/pages/Organization/org-agent-audit.css`、`docs/ui/ORG_CENTER_SPEC.md`。
### 修复 · 个人密钥保存失败后保留表单
- **范围**:用户中心密钥管理的新建和编辑抽屉。
- **变更**:保存失败时保留分组及其他输入,结束提交时统一恢复按钮状态。
- **影响**:用户可以在原表单上修正信息或直接重试,继续沿用原有密钥接口。
- **回滚**:还原密钥表单提交结束时的重置逻辑。
- **关联**:`src/components/table/tokens/modals/EditTokenModal.jsx`。
### 调整 · 企业技能治理页面布局
- **范围**:分发与锁定、企业专家工坊、业务系统连接器。
- **变更**:统一页头、主操作、列表卡片和表单弹层。整理成员预览、专家版本与连接器卡片,补齐连接器页签空态。
- **影响**:页面权限、接口和已有治理操作沿用原流程。
- **回滚**:还原三个页面及相关样式的布局改动。
- **关联**:`src/pages/Organization/OrgSkillAssignments.jsx`、`src/pages/Organization/OrgExperts.jsx`、`src/pages/Organization/OrgConnectors.jsx`。
### 调整 · 企业技能中心布局
- **范围**:企业中心技能库与自研 Skill。
- **变更**:统一页头与页签顺序,整理技能操作区、引入目录与自研技能表单标签。
- **布局细节**:企业技能库与自研 Skill 的操作按钮统一放在当前页头右侧,与分发与锁定页一致。自研 Skill 的快速上手贴近页签。
- **影响**:两种页签继续使用原有路由参数、权限及技能治理操作。
- **回滚**:还原技能中心、两个子页与共用页签容器的对应布局改动。
- **关联**:`src/pages/Organization/OrgSkillCenter.jsx`、`src/pages/Organization/org-skills.css`。
### 修复 · 企业质量维度分布提示栏对齐
- **范围**:企业中心质量监控「维度分布」的六个页签。
- **变更**:图标和文案从提示栏左侧内边距起排,两者垂直居中对齐,间距为 6px。窄屏换行后文案各行左对齐。
- **影响**:仅调整企业端维度分布提示栏的布局,覆盖警告和信息提示。
- **回滚**:移除企业端维度分布提示栏的居中样式。
- **关联**:`src/components/quality/quality.css`。
### 修复 · 表格分组布局与渠道分组参数
- **范围**:用户、企业、渠道、模型、密钥等调用分组表格,以及渠道筛选和编辑表单。
- **变更**:分组标签统一单行紧凑显示。渠道筛选按查询参数编码,分组表单统一处理字符串和数组回填。
- **影响**:分组显示、复制和模型更多分组入口沿用原有行为。用户、渠道、企业及密钥接口各自沿用已有字段类型。
- **回滚**:还原分组布局、列宽配置及渠道分组转换与查询参数改动。
- **关联**:`src/components/common/table/TableGroupTags.jsx`、`src/helpers/groupList.js`、`src/hooks/channels/useChannelsData.jsx`。
### 调整 · 企业效能分析页面
- **范围**:企业中心效能分析。
- **变更**:统一页头、指标卡、列表卡、成本对账和移动端空态,版本下钻支持回车提交。
- **影响**:保留各区块的排列和数据逻辑,指标图标及主操作随系统主题色。
- **回滚**:还原效能分析页组件与页面样式。
- **关联**:`src/pages/Organization/OrgEffectiveness.jsx`、`src/pages/Organization/org-effectiveness.css`。
### 修复 · 编辑用户分组提交格式
- **范围**:`/console/user` 编辑用户的分组字段。
- **变更**:按后端的单分组权限契约回填和保存,历史名称中的逗号原样保留。
- **影响**:保留已有分组选择及请求地址。
- **回滚**:还原编辑用户表单的分组转换。
- **关联**:`src/components/table/users/modals/EditUserModal.jsx`。
### 调整 · 明确最小移动验收视口
- **范围**:Playwright 与专项 UI 验收。
- **变更**:明确 360×800 是必测的最小移动视口,保留 393×851 专项覆盖。
- **影响**:默认 `chrome-mobile` 项目已使用 360×800。
- **回滚**:还原本条对应的验收规范与 README 说明。
- **关联**:`docs/ui/GLOBAL_UI_BASELINE.md`、`scripts/ui-review/config.json`。
### 修复 · 编辑用户抽屉关闭时标题闪动
- **范围**:`/console/user` 的编辑用户抽屉。
- **变更**:关闭时保留当前用户,退出动画期间维持编辑标题和分区。
- **影响**:下次打开时按选中的行重新加载用户信息。
- **回滚**:恢复关闭抽屉时的选中用户清理逻辑。
- **关联**:`src/hooks/users/useUsersData.jsx`。
### 修复 · 企业调用质量维度分布提示栏间距
- **范围**:`/org/quality` 的维度分布卡片。
- **变更**:复用 18px 区块间距,统一提示栏与页签、结果区之间的留白。
- **影响**:有提示、无提示和查询失败时均沿用同一组间距。
- **回滚**:还原企业端维度分布的容器样式和表格上边距。
- **关联**:`src/components/quality/QualityBreakdown.jsx`、`src/components/quality/quality.css`。
### 修复 · 补齐运营设置保存按钮对齐
- **范围**:`/console/setting?tab=operation` 的额度、邀请消费返佣、监控、兜底渠道、日志、屏蔽词过滤、跑马灯、技能超市与技能注入。
- **变更**:9 个保存按钮复用运营设置操作区,与对应表单左边缘对齐。
- **影响**:覆盖桌面和移动端,沿用各区块的保存处理。
- **回滚**:还原本条涉及的保存按钮容器。
- **关联**:`src/pages/Setting/Operation/`、`src/pages/Setting/Setting.css`。
### 调整 · 用户编辑抽屉对齐渠道编辑
- **范围**:`/console/user` 表格操作列的编辑用户抽屉。
- **变更**:统一抽屉标题、分区标题、图标、面板间距和固定页脚,余额控件按视口切换单双列。
- **影响**:保留原有用户字段、校验、额度调整和更新接口,提交期间防止重复保存。
- **回滚**:还原用户编辑抽屉及对应的样式规则。
- **关联**:`src/components/table/users/modals/EditUserModal.jsx`、`src/components/console/module-alignment.css`。
### 修复 · 统一表格分组标签文字
- **范围**:企业列表及共用分组标签的表格。
- **变更**:分组列的 `default`、`vip`、`svip` 显示标准名称,移除企业列表追加的默认分组标记。
- **影响**:默认分组配置、访问权限和计费规则沿用原逻辑。
- **回滚**:还原分组列渲染与对应公共规范。
- **关联**:`src/components/common/table/TableGroupTags.jsx`、`docs/standards/UI_COMPONENT_STANDARDS.md`。
### 修复 · 运营设置操作区对齐
- **范围**:`/console/setting?tab=operation` 的通用、COS、提示词采集、语言与地区及管理员权限下放设置。
- **变更**:将操作按钮与表单内容左边缘对齐,统一按钮组及语言规则校验提示的间距,权限选项沿用横向排列并统一行列间距。
- **影响**:语言规则正常和校验失败时均保留操作区间距。
- **回滚**:还原运营设置操作区的布局与样式。
- **关联**:`src/pages/Setting/Operation/SettingsGeneral.jsx`、`src/pages/Setting/Operation/SettingsLanguage.jsx`、`src/pages/Setting/Setting.css`。
### 调整 · 企业日志筛选栏对齐消费记录
- **范围**:审计日志的提示词记录与操作审计卡片间距,消耗明细的明细日志、成员排行和绘图与视频筛选栏。
- **变更**:复用个人消费记录的筛选卡布局、操作区和移动端折叠,统一搜索提交入口。审计日志的说明条上下及筛选卡至列表卡采用 18px 公共间距。
- **影响**:沿用各页签的筛选条件、默认时间和请求逻辑。
- **回滚**:还原本条对应的页面筛选区、公共样式和组件。
- **关联**:`src/components/common/table/UsageRecordFilterCard.jsx`、`docs/standards/UI_COMPONENT_STANDARDS.md`、`docs/ui/ORG_CENTER_SPEC.md`。
### 修复 · 企业成员页浮层触发节点引用
- **范围**:企业成员列表的状态开关和移除确认。
- **变更**:表格状态开关和兼容层确认框将 `ref` 转发给 Ant Design 组件。
- **影响**:消除 React 18 的 `Trigger` 引用告警,提示框可定位到对应的开关和按钮。
- **回滚**:还原本条对应的组件引用转发及单测修改。
- **关联**:`src/components/common/table/TableStatusSwitch.jsx`、`src/components/ui/index.jsx`。
### 修复 · 表格危险操作失败后可重试
- **范围**:表格操作列的删除、注销和冻结。
- **变更**:业务回调回传提交结果。确认框在失败时保留当前记录,提交期间拦截重复确认。
- **影响**:继续使用原接口、提示文案、权限判断及成功后的列表更新逻辑。
- **回滚**:还原本条涉及的提交结果传递和确认框改动。
- **关联**:`src/components/common/table/confirmTableAction.js`、`docs/standards/UI_COMPONENT_STANDARDS.md`。
### 修复 · 模型超市筛选按钮对齐
- **范围**:`/market` 顶部筛选按钮。
- **变更**:统一按钮内容的对齐方式,厂商图标调整为 16px,图标右侧文字下移 1px 以改善视觉对齐。
- **影响**:带图标和纯文字的选项采用相同的对齐方式。
- **回滚**:还原筛选按钮及其图标的对齐样式。
- **关联**:`src/components/table/model-pricing/market/market.css`、`src/components/table/model-pricing/filter/PricingVendors.jsx`。
### 调整 · 统一 WeyAi 下载页
- **范围**:公开下载页与用户中心下载页。
- **变更**:共用下载页布局和样式,用户中心保留面包屑,下载背景延伸至导航区域。
- **影响**:两个入口使用相同的推荐卡、安装包列表与下载交互,布局按各自的可用宽度排列。
- **回滚**:还原本条对应的下载组件、样式和布局规范。
- **关联**:`src/pages/WeyAiDownload/`、`docs/ui/GLOBAL_UI_BASELINE.md`。
### 修复 · 表格危险操作确认交互
- **范围**:表格操作列的删除、注销和冻结。
- **变更**:统一危险操作入口和确认按钮,补齐直接执行入口的确认步骤;取消优先聚焦。
- **影响**:保留已有业务提示文案和提交逻辑。
- **回滚**:还原本条对应的行操作入口和公共确认组件。
- **关联**:`src/components/common/table/TableActionPopconfirm.jsx`、`src/components/common/table/TableActionModal.jsx`。
## 2026-11-23
### 功能 · 统一权限体系前端(合入 weiyuan 后按 antd 6 重做)
- **范围**:控制台路由守卫与侧栏、权限管理 5 页(菜单管理、平台角色、功能套餐、角色模板、运行模式)、用户管理、企业管理;企业中心入口与侧栏、角色管理(新增 `/org/roles`)、员工管理,以及其余企业中心页面的按钮显隐;企业登录页。
- **变更**:新增 `src/authz`(`usePerm` / `Perm` / `PermRoute` / `ConsoleRoute`),已切到新权限体系的模块按权限点判断,未切换的沿用原角色判断;超管"进入企业"改走代理会话(`X-Proxy-Session`,只存当前标签页);当前企业统一经 `helpers/orgContext.js` 读写;员工管理合并为一张表并改为服务端筛选分页,新增员工编辑;用户管理新增状态筛选、"添加额度"(按调整量)与"分配角色";企业管理新增所有者、功能套餐、预警通知列与"更换所有者";授权树支持父子联动、半选与全部展开 / 收起;企业登录支持两步验证与首登改密。
- **影响**:未切换时各入口的可见性与原来一致。员工管理不再有"员工权限 / 员工账号"页签;`OrgMemberAccounts.jsx` 只导出两个弹窗。接口变化见 `docs/10-数据安全与权限/10-权限体系重构改造方案.md` §13。本条所列页面均未做浏览器走查。
- **回滚**:`git revert` 对应提交;权限管理页、`src/authz`、`orgContext.js` 为新增文件。
- **关联**:`src/authz/*`、`src/pages/Permission/*`、`src/components/authz/PermTree.jsx`、`src/pages/Organization/{index,OrgSidebar,OrgRoles,OrgMembers,OrgMemberAccounts}.jsx`、`src/pages/Organization/orgMenuAccess.js`、`src/components/table/users/*`、`src/pages/AdminOrganizations/*`、`src/App.jsx`、`src/components/layout/SiderBar.jsx`。
### 修复 · 表格启停开关与分组样式统一
- **范围**:已有启停开关、调用或计费分组的表格,以及操作列删除确认规范。
- **变更**:复用密钥管理的小尺寸状态开关和企业列表的分组标签;规范删除确认、提交防重及失败处理,文案可自定义。
- **影响**:保持原接口、权限、确认及删除流程;单组与多组使用同一颜色映射。
- **回滚**:分别还原共享组件接入和对应规范差异。
- **关联**:`src/components/common/table/TableStatusSwitch.jsx`、`src/components/common/table/TableGroupTags.jsx`、`docs/standards/UI_COMPONENT_STANDARDS.md`。
### 调整 · 渠道聚合标签编辑抽屉
- **范围**:`/console/channel` 标签聚合模式下的编辑标签抽屉。
- **变更**:标签抽屉沿用编辑渠道的标题、面板和页脚,将标签名称与分组放入响应式栅格。创建渠道、编辑渠道和编辑标签的圆形图标均对齐模型编辑抽屉。
- **影响**:可通过关闭按钮或取消退出,提交继续使用标签批量覆盖接口及校验规则。
- **回滚**:还原标签编辑抽屉的布局、控件和页脚改动。
- **关联**:`src/components/table/channels/modals/EditTagModal.jsx`、`src/components/table/channels/modals/EditChannelModal.jsx`、`src/components/console/module-alignment.css`。
### 调整 · 预约列表导出和操作确认
- **范围**:`/console/demo-reservations` 预约列表。
- **变更**:复用日志页的导出按钮,水平居中表格列,加宽操作列左侧的状态列,启用、禁用与删除操作采用密钥管理页的确认弹窗样式。
- **影响**:启停和删除在确认后提交;导出继续下载当前选中预约的 CSV。
- **回滚**:还原预约列表的工具栏、列定义、确认弹窗与对应语言条目。
- **关联**:`src/pages/DemoReservations/index.jsx`、`src/i18n/locales/`。
### 修复 · 审计提示词记录模型列样式
- **范围**:`/org/audit` 提示词调用记录的模型列。
- **变更**:移除紫色标签,复用相邻提示词列的文字样式,保留长名称省略和悬浮提示。
- **影响**:文字随浅深主题切换,不受品牌色覆盖;查询、权限和调用明细不变。
- **回滚**:还原模型列渲染及共享文字类名提取。
- **关联**:`src/pages/Organization/OrgPromptRecords.jsx`。
### 修复 · 消费记录渠道标签可读性
- **范围**:`/user-center/usage-record` 消费记录和绘图与视频任务记录表格的渠道列。
- **变更**:调用明细采用与任务记录相同的默认填充标签,移除按渠道 ID 配色及井号图标,并修正点击复制的参数。
- **影响**:两张表的渠道标签随亮暗主题使用中性底色,保留渠道名称提示和调用明细的多密钥序号。
- **回滚**:按关联文件还原本条对应的标签渲染与样式。
- **关联**:`src/components/table/usage-logs/UsageLogsColumnDefs.jsx`、`src/components/table/task-logs/TaskLogsColumnDefs.jsx`、`src/pages/UserCenter/UsageRecord.css`。
### 优化 · WeyAi 独立下载页原型对齐
- **范围**:`/weyai/download` 独立下载页和此路由的顶栏下载入口。
- **变更**:首屏并排展示推荐安装区和工作台示意。安装包按系统分组,文件名和大小分行,指引区跟随可用宽度折行。
- **影响**:首屏光晕、推荐提示、焦点环和顶栏选中态随当前主题生效。
- **回滚**:按关联文件还原本条的布局与样式变更。
- **关联**:`src/pages/WeyAiDownload/{index.jsx,weyai-download.css}`、`docs/ui/GLOBAL_UI_BASELINE.md` 第 5 节。
### 调整 · 官网设置关于我们文案
- **范围**:控制台官网设置。
- **变更**:关于页签、页签说明、团队成员共用提示和跨页签校验文案统一使用“关于我们”,同步更新九个语言包。
- **影响**:文案随当前界面语言显示,已保存的官网配置继续按原结构读取。
- **回滚**:按关联文件还原对应文案。
- **关联**:`src/pages/WebsiteSettings/{model.js,README.md}`、`src/i18n/locales/`。
### 修复 · Vite 开发服务暴露面
- **范围**:本地开发服务与共享测试环境部署说明。
- **变更**:升级 Vite 和 esbuild,禁用开发服务中项目未使用的 `import.meta.glob` 转换。
- **影响**:本机和局域网可继续访问开发端口 5174,普通动态导入和热更新沿用现有流程,共享测试环境可使用静态构建产物。
- **回滚**:按关联文件还原配置和依赖锁定。
- **关联**:`vite.config.js`、`package.json`、`package-lock.json`、`README.md`。
### 优化 · WeyAi 桌面端下载页
- **范围**:独立下载页 `/weyai/download` 与用户中心内嵌下载页。
- **变更**:独立页扩大桌面内容区,整合版本信息、打开入口和推荐安装包。两处下载页均按系统分组展示安装包,按可用宽度切换列数,文件名完整换行,交互色跟随系统主题配置。
- **影响**:鼠标或键盘激活“其他平台与架构”后,焦点落在安装包分区标题,随后按 Tab 可进入第一个包的下载按钮。
- **回滚**:按关联文件还原本条对应的布局、样式和焦点处理。
- **关联**:`src/pages/WeyAiDownload/{index.jsx,weyai-download.css}`、`docs/ui/GLOBAL_UI_BASELINE.md` 第 5 节。
### 优化 · 兜底渠道选择器
- **范围** 控制台「渠道管理」的渠道编辑抽屉。
- **变更** 下拉项和已选标签显示渠道 ID 与名称,禁用状态以灰态和悬停提示表达。
- **影响** 可按 ID、名称、分组和地域搜索。写入兜底链时仍按选择顺序提交数字 ID。
- **回滚** 还原渠道编辑抽屉的选项标签和搜索字段。
- **关联** `src/components/table/channels/modals/EditChannelModal.jsx`。
### 功能 · 预约演示列表管理
- **范围** 控制台「预约演示」。
- **变更** 支持当前页多选、导出选中行的 CSV、逐条启停与确认删除。列宽按常见字段长度分配,表头字段居中,需求列随窗口加宽,窄屏下固定复选框和操作列。
- **影响** 历史和新提交记录默认启用,删除记录从预约列表中移除并保留在数据库中。
- **回滚** 还原本次前后端变更。旧版列表会重新显示软删除记录。
- **关联** `src/pages/DemoReservations/` 和 `website_demo_requests`。
## 2026-11-21 ## 2026-11-21
### 修复 · 视频生成任务队列分页 ### 修复 · 视频生成任务队列分页
+4 -3
View File
@@ -1,6 +1,6 @@
# 统一开发与 Ant Design CRUD 规范 # 统一开发与 Ant Design CRUD 规范
> 状态:有效 · 适用:React 18.3、antd 6.7.0、Vite 5.4、Node ≥ 22.13 · 更新:2026-11-20 · 版本:v2.5 > 状态:有效 · 适用:React 18.3、antd 6.7.0、Vite 5.4、Node ≥ 22.13 · 更新:2026-11-26 · 版本:v2.6
新增与重构 CRUD 的编码规范:目录与命名、组件选择、请求、React 组件与状态、表单与弹层、权限、i18n,以及可直接复制的页面模板。外观取值见 `UI_COMPONENT_STANDARDS.md`。 新增与重构 CRUD 的编码规范:目录与命名、组件选择、请求、React 组件与状态、表单与弹层、权限、i18n,以及可直接复制的页面模板。外观取值见 `UI_COMPONENT_STANDARDS.md`。
@@ -55,7 +55,7 @@
### 1.3 版权声明 ### 1.3 版权声明
通用版权与许可声明集中保留在 [NOTICE.md](../../NOTICE.md)。源码不重复添加长版权文件头,不移除独立的第三方声明。 源码不重复添加通用长版权文件头,保留独立的第三方声明。
## 2. Ant Design 组件边界 ## 2. Ant Design 组件边界
@@ -121,6 +121,7 @@
- `API` 已提供:`New-API-User` 请求头;`/api/org/*` 自动注入 `X-Org-Id`(显式传入优先);并发相同 GET 去重(`disableDuplicate: true` 关闭,带取消信号或请求组的 GET 不共享);HTTP 错误统一提示(`skipErrorHandler: true` 跳过并由页面自行处理)。受会话约束的接口首次返回 401 时取消该会话未完成的只读请求,阻止该会话继续发请求,并仅清理、跳转 `/org/login?expired=true` 一次。公开接口或显式 `sessionBound: false` 的请求不参与会话联动。 - `API` 已提供:`New-API-User` 请求头;`/api/org/*` 自动注入 `X-Org-Id`(显式传入优先);并发相同 GET 去重(`disableDuplicate: true` 关闭,带取消信号或请求组的 GET 不共享);HTTP 错误统一提示(`skipErrorHandler: true` 跳过并由页面自行处理)。受会话约束的接口首次返回 401 时取消该会话未完成的只读请求,阻止该会话继续发请求,并仅清理、跳转 `/org/login?expired=true` 一次。公开接口或显式 `sessionBound: false` 的请求不参与会话联动。
- 同一批必须全部成功的只读请求,可传入同一个 `requestGroup: new AbortController()`;首次拒绝的 HTTP 4xx/5xx 取消同组剩余读取。普通失败不取消无关请求,正常并发不限流;已发送的写入不由请求组批量取消。调用方仍须处理 Promise 拒绝,并在 `finally` 清理加载状态。 - 同一批必须全部成功的只读请求,可传入同一个 `requestGroup: new AbortController()`;首次拒绝的 HTTP 4xx/5xx 取消同组剩余读取。普通失败不取消无关请求,正常并发不限流;已发送的写入不由请求组批量取消。调用方仍须处理 Promise 拒绝,并在 `finally` 清理加载状态。
- 查询参数用 `params` 对象,不手拼查询字符串(手拼不会编码 `&`、`#`、中文)。 - 查询参数用 `params` 对象,不手拼查询字符串(手拼不会编码 `&`、`#`、中文)。
- `API` 的 GET、HEAD、OPTIONS 默认在 60 秒后超时,调用方可以通过 `timeout` 覆盖。保持在 `finally` 回收加载状态,并让过期请求与当前请求的状态互不干扰。
- 响应按 `{ success, message, data }` 处理,先判断 `success`;具体字段以接口契约为准。 - 响应按 `{ success, message, data }` 处理,先判断 `success`;具体字段以接口契约为准。
- 分页参数 `p` 从 1 开始,`page_size` 默认 `ITEMS_PER_PAGE`(10,须与后端一致);后端对 `page_size > 100` 静默截断为 100,需要全量数据时用 `collectPagedItems(fetchPage)`(`src/helpers/paging.js`)。 - 分页参数 `p` 从 1 开始,`page_size` 默认 `ITEMS_PER_PAGE`(10,须与后端一致);后端对 `page_size > 100` 静默截断为 100,需要全量数据时用 `collectPagedItems(fetchPage)`(`src/helpers/paging.js`)。
@@ -222,7 +223,7 @@ pagination={{
- 防重复:提交中按钮 `loading` 或 `confirmLoading`;hook 内 `submitting` 为真时直接返回。 - 防重复:提交中按钮 `loading` 或 `confirmLoading`;hook 内 `submitting` 为真时直接返回。
- 成功:`showSuccess` → 关闭 → 刷新当前页;失败:保留弹层与已填内容。 - 成功:`showSuccess` → 关闭 → 刷新当前页;失败:保留弹层与已填内容。
- 打开时重置:弹层加 `forceRender`,在 `useEffect([open, record])` 中先 `resetFields()` 再 `setFieldsValue(record)`。 - 打开时重置:弹层加 `forceRender`,在 `useEffect([open, record])` 中先 `resetFields()` 再 `setFieldsValue(record)`。
- 删除:`Popconfirm` 的 `onConfirm` 返回 Promise 以显示加载;批量或不可撤销操作用 `Modal.confirm`。 - 删除:确认回调返回 Promise 以显示加载;确认形态、危险按钮、失败保留与键盘交互见组件规范第 8 节。
- 日期提交前转换为后端格式(多为 Unix 秒);有未保存内容时沿用页面已有的关闭确认流程。 - 日期提交前转换为后端格式(多为 Unix 秒);有未保存内容时沿用页面已有的关闭确认流程。
## 7. 加载、空态与错误态 ## 7. 加载、空态与错误态
+25 -8
View File
@@ -125,17 +125,26 @@ html.dark .km-page {
## 4. 表格搜索栏(筛选卡) ## 4. 表格搜索栏(筛选卡)
- **筛选卡与列表卡间距**:从筛选卡底边到下方列表卡顶边统一为 18px,复用 `--uc-layout-gap`。同一对相邻区块只设置一次间距,优先由共同容器的 `gap` 控制。企业端以 `/org/logs` 为对齐基准,审计日志若在页签与筛选卡之间插入说明条,说明条上下也各留 18px。
- 背景:使用不透明的卡片纯色;浅色为白色,深色沿用主题卡片色,不使用渐变背景。 - 背景:使用不透明的卡片纯色;浅色为白色,深色沿用主题卡片色,不使用渐变背景。
- 字段竖排:标签在上(13px,次文字色,下距 8px),控件在下且宽度占满单元格。 - 字段竖排:标签在上(13px,次文字色,下距 8px),控件在下且宽度占满单元格。
- 栅格:列间距与行间距 16px;按页面宽度取 3–5 列(企业中心 3 列、控制台 4 列、用户中心 5 列,时间范围可跨 2 列);≤ 768px 单列。 - 栅格:列间距与行间距 16px;按页面宽度取 3–5 列(企业中心 3 列、控制台 4 列、用户中心 5 列,时间范围可跨 2 列);≤ 768px 单列。
- 操作:“重置”“搜索”位于右下,间距 8px;“搜索”为 primary 且 `htmlType='submit'`,回车提交。 - 操作:“重置”“搜索”位于右下,间距 8px;“搜索”为 primary 且 `htmlType='submit'`,回车提交。
- 行为:搜索与重置都回到第 1 页;重置 = 清空表单 + 以默认条件重新查询;只切换筛选的页签放在筛选卡上方。 - 搜索保留当前页码、每页条数、排序、勾选和展开等表格操作状态。点击“重置”时取消待执行搜索及在途筛选请求,恢复本页的默认筛选条件,回到第 1 页并初始化本页的表格操作状态。只切换筛选的页签放在筛选卡上方。
- 移动端:用户中心与控制台默认收起,通过“显示 / 隐藏操作项”或“筛选”按钮展开;列设置入口不随筛选收起。 - 移动端:用户中心与控制台默认收起,通过“显示 / 隐藏操作项”或“筛选”按钮展开;列设置入口不随筛选收起。
- 控制台使用 `ConsoleSearchBar` + `ConsoleSearchActions`,企业中心使用 `OrgFilterCard`,不要另写网格。 - 控制台使用 `ConsoleSearchBar` + `ConsoleSearchActions`,企业中心常规筛选使用 `OrgFilterCard`。消耗明细及提示词记录复用个人消费记录的筛选布局和移动端折叠。
- 标准列表以 `/console/token` 为参考,覆盖控制台分佣、兑换码、会员卡和发票,企业及个人分佣,以及用户中心密钥管理(含各自子页、页签和详情列表)。使用 `ConsoleCollection`(或通过 `CardPro` 接入);独立列表可用 `ConsoleCollectionSearch` + `ConsoleFilterGrid`。筛选栅格为三列、≤ 1100px 两列、≤ 768px 单列。 - 标准列表以 `/console/token` 为参考,覆盖控制台分佣、兑换码、会员卡和发票,企业及个人分佣,以及用户中心密钥管理(含各自子页、页签和详情列表)。使用 `ConsoleCollection`(或通过 `CardPro` 接入);独立列表可用 `ConsoleCollectionSearch` + `ConsoleFilterGrid`。筛选栅格为三列、≤ 1100px 两列、≤ 768px 单列。
- 搜索操作在筛选卡右下,先默认样式“重置”(无图标),再带放大镜的主按钮“搜索”;点击和回车共用同一个提交入口。保留原有即时筛选及请求方式,移动端统一通过“显示/隐藏操作项”切换。 - 搜索操作在筛选卡右下,先默认样式“重置”(无图标),再带放大镜的主按钮“搜索”;点击和回车共用同一个提交入口。移动端统一通过“显示/隐藏操作项”切换。
- 工具栏在列表卡内、表格上方:列表标题、计数或快捷筛选在左;已有的批量、导出、刷新、列设置、新建等动作在右,主操作尽量靠右,使用公共操作图标和清晰文案。窗口变窄时自然换行。只读明细若没有筛选或业务动作,不新增占位按钮。 - 工具栏在列表卡内、表格上方:列表标题、计数或快捷筛选在左;已有的批量、导出、刷新、列设置、新建等动作在右,主操作尽量靠右,使用公共操作图标和清晰文案。窗口变窄时自然换行。只读明细若没有筛选或业务动作,不新增占位按钮。
### 4.1 时间范围及自动搜索
- 表格筛选的范围控件使用 `DatePicker` 或 `Form.DatePicker` 的 `tableFilter`,开始和结束输入框共用一个控件,支持清除。仅日期使用 `YYYY-MM-DD`,含时间使用 `YYYY-MM-DD HH:mm:ss`。日期弹层使用当前主题;桌面快捷周期位于日历左侧,窄屏可换行。
- 快捷周期依次为今天、近 7 天、本周、近 30 天、本月,复用 `DATE_RANGE_PRESETS`。相对周期按选择时的本地日期计算,匹配已提交范围时显示选中态。页面沿用自身初始日期或空值。选择完整范围、确认时间、选择快捷周期或清除后,通过同一个值变更入口提交;临时选择、悬浮预览和下拉搜索词不触发列表查询。
- `useFilterSearch` 将字段变更合并为一次 300ms 防抖查询。兼容表单用 `onValueChange={scheduleSearch}`,原生 Ant Design Form 用 `onValuesChange` 传最终值;独立受控字段可用 `changeFilter(setValue)`。输入框、数字组件、选择器、开关、复选和异步选择组件均在实际筛选值变化时接入。搜索按钮和回车共用 `submitSearch`,立即执行待查询条件。
- 后端分页沿用现有查询接口,传当前页及条件,同时将 `AbortSignal` 传到 `API`。字段变化、重置和卸载取消在途查询,忽略过期响应。以页码或已应用条件驱动请求的页面可用 `useTableFilterQuery` 将取消操作传给 `useFilterSearch`。
- 本地分页先按条件处理完整数据集再切页。独立控件可用 `useLocalTableFilters` 分开显示值与已应用值,再用 `useFilteredTableRows` 计算结果。大数组过滤复用 `filterTableRows`,超出 500 行时分片让出主线程,并在每批检查取消状态。
## 5. 表格 ## 5. 表格
### 5.1 表头与行 ### 5.1 表头与行
@@ -151,12 +160,14 @@ html.dark .km-page {
### 5.2 列 ### 5.2 列
- 每列显式 `width`,长文本 `ellipsis` 并配 `Tooltip`;金额与数量右对齐;时间统一格式,必要时日期与时间分两行。 - 每列显式 `width`,长文本 `ellipsis` 并配 `Tooltip`;金额与数量右对齐;时间统一格式,必要时日期与时间分两行。
- 状态列用 `Tag` 或 `Switch`(见第 11 节);启停开关请求中禁用,失败恢复原状态。 - 状态列用只读 `Tag` 或 `TableStatusSwitch`(见第 11 节);启停开关请求中禁用,失败恢复原状态。
- 操作列放在最后,标题固定为“操作”,按钮为 `type='link' size='small'`,同一行操作间距 8px;用户中心、企业中心、控制台(含系统设置)的操作列统一 `fixed: 'right'`。`/console/user` 的用户列表和 `/console/commission?view=partners` 的合作伙伴列表使用 `TableRowActions`:直出高频动作,其余放进带下箭头的文字“更多”菜单。其他列表沿用既有操作呈现方式,不批量套用此菜单。菜单点击打开、右对齐,无有效菜单项时不渲染入口;危险项置末、标记 `danger` 并保留业务确认。现有权限、状态限制、禁用项和回调不得因收纳而改变,方向键、Enter、Escape 可操作菜单。 - 调用、计费和访问权限分组列使用 `TableGroupTags`,单组与多组按同一套颜色渲染(见第 11 节)。
- 操作列放在最后,标题固定为“操作”,按钮为 `type='link' size='small'`,同一行操作间距 8px;用户中心、企业中心、控制台(含系统设置)的操作列统一 `fixed: 'right'`。`/console/user` 的用户列表、`/console/subscription` 的会员列表和 `/console/commission?view=partners` 的合作伙伴列表使用 `TableRowActions`:直出高频动作,其余放进带下箭头的文字“更多”菜单。其他列表沿用既有操作呈现方式,不批量套用此菜单。菜单点击打开、右对齐,无有效菜单项时不渲染入口;危险项置末、标记 `danger` 并保留业务确认。现有权限、状态限制、禁用项和回调不得因收纳而改变,方向键、Enter、Escape 可操作菜单。
- 三中心表格通过 `CenterActionTable` 统一处理,最后一列存在创建、查看、编辑、测试、详情、删除、添加、设置、配置、弹窗 / 抽屉或请求交互时,列头统一显示“操作”并固定右侧,宽度按按钮 / 交互数量计算。没有操作列但估算列宽超出容器时,从右侧固定末 4 列,列数不足时降为 3、2、1 列。固定列使用不透明底色并保持表头层级;横向滚动条遵循 Ant Design 官方固定列表格行为,允许鼠标、触控板、触屏和键盘滚动,不隐藏滚动条。 - 三中心表格通过 `CenterActionTable` 统一处理,最后一列存在创建、查看、编辑、测试、详情、删除、添加、设置、配置、弹窗 / 抽屉或请求交互时,列头统一显示“操作”并固定右侧,宽度按按钮 / 交互数量计算。没有操作列但估算列宽超出容器时,从右侧固定末 4 列,列数不足时降为 3、2、1 列。固定列使用不透明底色并保持表头层级;横向滚动条遵循 Ant Design 官方固定列表格行为,允许鼠标、触控板、触屏和键盘滚动,不隐藏滚动条。
- 列显隐只在已有列设置的表格中提供,统一使用 `ColumnSettings`(见 `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md`)。 - 列显隐只在已有列设置的表格中提供,统一使用 `ColumnSettings`(见 `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md`)。
- 三中心表头背景统一由 `center-table.css` 绘制:页面通过 `--center-table-head-bg` 提供色调,公共层在不透明的容器底色上叠加同色填充,普通列与固定列保持一致;页面不再直接覆盖表头 `background`。固定列使用 antd 6 的 `.ant-table-cell-fix` 与原生动态层级,不写死 `z-index`,不使用旧版 `fix-left` / `fix-right` 类名补丁;表头不换行,表头与正文沿用同一列宽和对齐方式。 - 三中心表头背景统一由 `center-table.css` 绘制:页面通过 `--center-table-head-bg` 提供色调,公共层在不透明的容器底色上叠加同色填充,普通列与固定列保持一致;页面不再直接覆盖表头 `background`。固定列使用 antd 6 的 `.ant-table-cell-fix` 与原生动态层级,不写死 `z-index`,不使用旧版 `fix-left` / `fix-right` 类名补丁;表头不换行,表头与正文沿用同一列宽和对齐方式。
- 操作列在异步数据或列变化后重新测量可见行的按钮宽度,取最大值;列宽不超过表格容器,按钮组在空间不足时换行。左右固定区总宽超过容器时,保留右侧操作列,其余固定列参与横向滚动;容器恢复足够宽度后恢复原固定配置,避免窄屏相互遮挡。 - 操作列在异步数据或列变化后重新测量可见行的按钮宽度,取最大值;列宽不超过表格容器,按钮组在空间不足时换行。左右固定区总宽超过容器时,保留右侧操作列,其余固定列参与横向滚动;容器恢复足够宽度后恢复原固定配置,避免窄屏相互遮挡。
- 操作列的删除入口置末并用 `danger`;点击仅打开确认,确认后的提交与刷新按第 8 节执行。无权删除或当前状态不允许删除时,沿用业务的隐藏或禁用规则。
### 5.3 状态 ### 5.3 状态
@@ -171,8 +182,9 @@ html.dark .km-page {
- 位置:列表卡底部右对齐,上距 16px;移动端换行显示并提供快速跳页。 - 位置:列表卡底部右对齐,上距 16px;移动端换行显示并提供快速跳页。
- 外观:小尺寸,可切换每页条数 `[10, 20, 50, 100]`,总数文案 `t('共 {{total}} 条', { total })`。 - 外观:小尺寸,可切换每页条数 `[10, 20, 50, 100]`,总数文案 `t('共 {{total}} 条', { total })`。
- 用法:分页列表使用 `@/components/ui` 的 `Table` / `Pagination`。第 4 节的标准列表及其明细分页均沿用密钥管理:表格底部右对齐、小尺寸,依次显示“共 N 条”、上一页/页码/下一页、每页条数(10、20、50、100),移动端保留跳页。已加载的明细可本地分页;服务端分页传 `currentPage`、`pageSize`、`total` 以及分页回调,切换每页条数回到第 1 页,只发一次请求。导出仍作用于原有结果范围,不受当前页条数影响。 - 用法:分页列表使用 `@/components/ui` 的 `Table` / `Pagination`。第 4 节的标准列表及其明细分页均沿用密钥管理:表格底部右对齐、小尺寸,依次显示“共 N 条”、上一页/页码/下一页、每页条数(10、20、50、100),移动端保留跳页。已加载的明细可本地分页;服务端分页传 `currentPage`、`pageSize`、`total` 以及分页回调,切换每页条数回到第 1 页,只发一次请求。导出仍作用于原有结果范围,不受当前页条数影响。
- 删除当前页最后一条后回到上一页;前端分页的列表在筛选或数据变化时回到第 1 页。`/org/*` 的独立表格、页签和下钻明细均用此分页规则;已加载的树形表格按根节点分页,子节点不拆散;接口已分页时沿用原查询与总数。 - 删除当前页最后一条后回到上一页;筛选和搜索沿用当前页,重置回到第 1 页。`/org/*` 的独立表格、页签和下钻明细均用此分页规则;已加载的树形表格按根节点分页,子节点不拆散;接口已分页时沿用原查询与总数。
- 受控分页须实现条数回调(或兼容的统一变更回调)才显示条数选择,不用客户端切片模拟固定条数的服务端接口;分页启用且有结果时单页也显示分页栏。 - 受控分页须实现条数回调(或兼容的统一变更回调)才显示条数选择,不用客户端切片模拟固定条数的服务端接口;分页启用且有结果时单页也显示分页栏。
- 接入自动搜索的表格使用 `preservePage`。筛选后当前页没有结果时仍保留页码,分页栏显示实际结果总数并允许手动返回。删除后的页码调整由对应删除流程处理。
## 7. 表单项 ## 7. 表单项
@@ -192,7 +204,11 @@ html.dark .km-page {
| 外观 | 圆角 12px;标题 16px / 600;正文与页脚使用 antd 默认间距 | | 外观 | 圆角 12px;标题 16px / 600;正文与页脚使用 antd 默认间距 |
| 页脚 | 次操作(取消)在前、主操作(确定 / 保存)在后,按钮高 34px、间距 8px;危险确认用 `okButtonProps={{ danger: true }}` | | 页脚 | 次操作(取消)在前、主操作(确定 / 保存)在后,按钮高 34px、间距 8px;危险确认用 `okButtonProps={{ danger: true }}` |
| 行为 | 提交中 `confirmLoading`;校验或请求失败不关闭;X、取消、Esc、遮罩关闭行为一致 | | 行为 | 提交中 `confirmLoading`;校验或请求失败不关闭;X、取消、Esc、遮罩关闭行为一致 |
| 确认框 | 单条删除用 `Popconfirm`;批量或不可撤销操作用 `Modal.confirm`(企业中心用 `OrgModal.confirm`) | | 表格操作列危险确认 | 删除、注销和冻结使用小尺寸危险链接,更多菜单使用危险菜单项。普通单条操作用 `TableActionPopconfirm`,注销、企业冻结等影响较大的操作用确认弹窗。取消在前,危险确认在后;优先聚焦取消 |
- 保留业务定制的标题、正文和按钮文案,并接入国际化。确认信息明确操作对象和影响。
- 只有明确确认才发送请求;取消、Esc 或关闭不修改数据。确认回调返回 Promise,提交中显示加载并防止重复请求,失败保留确认及上下文并提示原因。成功后关闭确认并刷新列表,删除当前页最后一条时按分页规范回退。
- 表格危险操作的回调在 API 明确失败时返回 `false`。确认框保持打开,业务回调保留原有错误提示。受控弹窗由业务在成功后关闭。
## 9. 抽屉 ## 9. 抽屉
@@ -222,7 +238,8 @@ html.dark .km-page {
- **状态**用语义色:成功 `success`、失败 `error`、进行中 `processing`、等待 / 警告 `warning`、中性 `default`。 - **状态**用语义色:成功 `success`、失败 `error`、进行中 `processing`、等待 / 警告 `warning`、中性 `default`。
- **分类**(分组、类型、模型标签等)用调色板色(`blue`、`green`、`purple`、`gold`、`cyan` 等 antd 预设),不用非预设色名。 - **分类**(分组、类型、模型标签等)用调色板色(`blue`、`green`、`purple`、`gold`、`cyan` 等 antd 预设),不用非预设色名。
- 全局默认描边;卡片内的分类标签与企业中心表格标签用无边框样式,新代码写 `variant='filled'`(antd 6 已弃用 `bordered={false}`,二者视觉等价;存量写法可在修改时顺带收敛)。标签间距 8px,表格内标签不留右外边距。 - 全局默认描边;卡片内的分类标签与企业中心表格标签用无边框样式,新代码写 `variant='filled'`(antd 6 已弃用 `bordered={false}`,二者视觉等价;存量写法可在修改时顺带收敛)。标签间距 8px,表格内标签不留右外边距。
- 可启停的记录用 `Switch size='small'`,`onChange` 调原处理函数;无启停接口的列表保留只读 `Tag`。 - **表格启停开关**以 `/user-center/key-management` 为准,复用 `TableStatusSwitch`:小尺寸、开启显示「启用」并使用系统主题主色,关闭显示「禁用」并使用组件中性色。其他既有布尔含义可自定义两态文字。保留键盘焦点、可访问名称、原有确认和权限;关闭状态不等于控件不可操作。只读状态仍用 `Tag`,过期、耗尽等非二元状态的说明保留,表单与筛选区开关不套用本规则。
- **表格分组颜色与布局**以 `/console/organizations` 分组列为准,复用 `TableGroupTags`(单个标签也可用 `TableGroupTag`)。三种分组的标签文字固定为 `default`、`vip`、`svip`,颜色分别为蓝、黄、红。分组列禁止追加「(默认)」等说明,默认分组设置继续在表单中体现。`premium`、`pro` 沿用原名及红、黄配色,自定义分组用中性色。使用 antd 浅底描边标签并适配明暗主题。标签逐个着色、去重,按 4px 间距单行排列。纯分组列复用 `TABLE_GROUP_COLUMN_WIDTH`(148px),以完整容纳三枚标准标签为准。超出单元格的分组可横向滚动,已有的「+N」展开仍可使用。空值继承、智能熔断和非调用分组沿用各自的业务展示。
## 12. 按钮与图标 ## 12. 按钮与图标
+3 -1
View File
@@ -1,6 +1,6 @@
# 控制台 UI 规范(/console/\*) # 控制台 UI 规范(/console/\*)
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v2.4 > 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-25 · 版本:v2.7
管理控制台 `/console/*` 的规范:统一页头、控制台原语与差异样式。 管理控制台 `/console/*` 的规范:统一页头、控制台原语与差异样式。
@@ -58,6 +58,8 @@
- 提示栏:控制台内的 `Banner` / `Alert` 统一走 `ConsoleAlert`,内边距 12px 16px、正文 14 / 22px、图标 16px,颜色取对应语义 token。 - 提示栏:控制台内的 `Banner` / `Alert` 统一走 `ConsoleAlert`,内边距 12px 16px、正文 14 / 22px、图标 16px,颜色取对应语义 token。
- 系统设置(`page.key === 'setting'`):表单统一纵向布局、8px 标签间距、24px 栅格、控件等宽,校验信息预留高度;弹窗页脚按钮高 34px、间距 8px、右对齐。规则限定在 `.settings-page` / `.settings-form-dialog`。 - 系统设置(`page.key === 'setting'`):表单统一纵向布局、8px 标签间距、24px 栅格、控件等宽,校验信息预留高度;弹窗页脚按钮高 34px、间距 8px、右对齐。规则限定在 `.settings-page` / `.settings-form-dialog`。
- 控制台上下文中 `CompactModeToggle` 不渲染,表格密度状态保留;其他模块仍可使用紧凑模式。 - 控制台上下文中 `CompactModeToggle` 不渲染,表格密度状态保留;其他模块仍可使用紧凑模式。
- 兑换码列表沿用渠道列表的行内链接按钮、右侧固定操作列和底部分页。「查看、复制、编辑、禁用/启用、删除」在同一行直接显示,保留既有权限和状态限制,删除仍需确认。窄屏横向滚动时操作列不换行。批量复制在选中兑换码后可用,清除失效兑换码由独立的危险操作确认承载。
- 添加兑换码与编辑兑换码信息共用右侧侧栏窗、表单样式及页脚。查看详情使用弹窗,优先展示兑换码和状态,再列出额度、时间与兑换人信息。
- 平台 Skill 中心的分类标签区域与搜索工具栏同宽、左对齐,不保留独立的最大宽度和自动居中;窄屏按原间距自然换行。 - 平台 Skill 中心的分类标签区域与搜索工具栏同宽、左对齐,不保留独立的最大宽度和自动居中;窄屏按原间距自然换行。
- 平台 Skill 详情的审核工作台仅由抽屉正文纵向滚动,技能原文不设置独立滚动区;审核操作进入抽屉固定页脚,按钮右对齐、间距 8px,仅在审核页签展示。 - 平台 Skill 详情的审核工作台仅由抽屉正文纵向滚动,技能原文不设置独立滚动区;审核操作进入抽屉固定页脚,按钮右对齐、间距 8px,仅在审核页签展示。
- 官网文章抽屉允许点击遮罩关闭,X、取消、遮罩共用同一未保存内容确认流程。 - 官网文章抽屉允许点击遮罩关闭,X、取消、遮罩共用同一未保存内容确认流程。
+6 -5
View File
@@ -1,6 +1,6 @@
# 后台 UI 全局基线 # 后台 UI 全局基线
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-19 · 版本:v3.12 > 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-23 · 版本:v3.14
后台外壳与布局基线:顶栏、侧栏、公告、页头与内容边距、登录页,以及原型未定义场景、登录关卡与验收流程。主题与组件样式见 `UI_COMPONENT_STANDARDS.md`。 后台外壳与布局基线:顶栏、侧栏、公告、页头与内容边距、登录页,以及原型未定义场景、登录关卡与验收流程。主题与组件样式见 `UI_COMPONENT_STANDARDS.md`。
@@ -16,7 +16,7 @@
| 滚动条 | 全站 6px,`#8b8b8b`,悬停 `#636363`,页面不得单独设置 | | 滚动条 | 全站 6px,`#8b8b8b`,悬停 `#636363`,页面不得单独设置 |
| 装饰 | 无设计依据不加渐变、玻璃、发光、浮起与动效 | | 装饰 | 无设计依据不加渐变、玻璃、发光、浮起与动效 |
| 登录关卡 | 真实 UI 登录,企业先于个人,凭据只经环境变量(第 6 节) | | 登录关卡 | 真实 UI 登录,企业先于个人,凭据只经环境变量(第 6 节) |
| 验收 | 浅深主题 × 1920×1000 / 393×851,有头离屏串行,唯一页面不抢焦点,模拟与真实分开记录(第 7 节) | | 验收 | 浅深主题 × 1920×1000 / 393×851 / 360×800,有头离屏串行,唯一页面不抢焦点,模拟与真实分开记录(第 7 节) |
**相关代码**:`src/styles/{user-center,center-layout,org-page,prototype}.css`、`src/index.css`、`src/components/layout/` **相关代码**:`src/styles/{user-center,center-layout,org-page,prototype}.css`、`src/index.css`、`src/components/layout/`
@@ -94,6 +94,7 @@
- 带侧栏页面按 4.4;控制台按 `CONSOLE_SPEC.md`;其余页面内容默认 24px 30px、移动 16px。筛选区自然换行,表格在自身容器横向滚动;不通过隐藏正文、裁剪校验信息或固定整页宽度迎合截图。 - 带侧栏页面按 4.4;控制台按 `CONSOLE_SPEC.md`;其余页面内容默认 24px 30px、移动 16px。筛选区自然换行,表格在自身容器横向滚动;不通过隐藏正文、裁剪校验信息或固定整页宽度迎合截图。
- 模型超市与技能超市的工作区居中,含内边距的最大宽度为 1760px;横向内边距为 `clamp(20px, 4vw, 80px)`,Hero 搜索区域沿用同一横向留白,600px 及以下为 20px。覆盖 3840 / 2560 / 1920 至 360px 宽度,目录按实际可用宽度减少列数,保留卡片正文和控件正常字号,不通过整体缩放压缩内容。 - 模型超市与技能超市的工作区居中,含内边距的最大宽度为 1760px;横向内边距为 `clamp(20px, 4vw, 80px)`,Hero 搜索区域沿用同一横向留白,600px 及以下为 20px。覆盖 3840 / 2560 / 1920 至 360px 宽度,目录按实际可用宽度减少列数,保留卡片正文和控件正常字号,不通过整体缩放压缩内容。
- WeyAi 两个下载路由共用页头、安装卡、工作台示意、平台安装包、功能和使用步骤。公开页的居中容器含内边距最大宽度为 1464px。首屏在页面可用宽度 960px 及以下上下排列,安装包分组在 1024px 及以上显示三列,在 768–1023px 显示两列,其余宽度显示一列,文件名可换行。用户中心内嵌页沿用第 4.4 节的面包屑和内容边距,下载页背景从面包屑区域开始覆盖内容区,面包屑与首屏标题区间隔 24px。
- 背景图优先复用原型的原始 SVG / 图片,放入 `src/assets/prototype` 并注明来源;原型用 CSS 绘制的背景按测量值在页面作用域复现,不用生成插画替代。 - 背景图优先复用原型的原始 SVG / 图片,放入 `src/assets/prototype` 并注明来源;原型用 CSS 绘制的背景按测量值在页面作用域复现,不用生成插画替代。
- 企业工作台横幅 `.ew-hero` 的浅金 / 深棕背景与三层轮廓只用于 `.org-workbench`,不扩散到其他页面。 - 企业工作台横幅 `.ew-hero` 的浅金 / 深棕背景与三层轮廓只用于 `.org-workbench`,不扩散到其他页面。
- 原型未定义、antd 有组件:用当前版本默认样式与主题 token。antd 无对应部件:语义背景 / 文字 / 边框,无装饰背景、阴影与动画,间距 8 / 16 / 24px,窄屏堆叠且操作可达;新增此类统一规则先写入本文。 - 原型未定义、antd 有组件:用当前版本默认样式与主题 token。antd 无对应部件:语义背景 / 文字 / 边框,无装饰背景、阴影与动画,间距 8 / 16 / 24px,窄屏堆叠且操作可达;新增此类统一规则先写入本文。
@@ -150,8 +151,8 @@
| 配置 | 约定 | | 配置 | 约定 |
| --- | --- | | --- | --- |
| 设备源 | `scripts/ui-review/config.json` → `scripts/browser-environment.mjs`;与 weelink 的设备结构和 Playwright 1.64.1 保持一致,各项目独立保存 | | 设备源 | `scripts/ui-review/config.json` → `scripts/browser-environment.mjs`;与 weelink 的设备结构和 Playwright 1.64.1 保持一致,各项目独立保存 |
| 视口 | 默认 1920×1080、360×800;扩展增加 768×1024、1024×768、1366×768、1440×900、2560×1440、3840×2160 | | 视口 | 默认 1920×1080、360×800、393×851;扩展增加 768×1024、1024×768、1366×768、1440×900、2560×1440、3840×2160 |
| 手机 | Pixel 5 UA、触摸、移动模式和 DPR 2.75;viewport 覆盖为 360×800,screen 沿用模板;平板仅为桌面设备的平板尺寸 | | 手机 | Pixel 5 UA、触摸、移动模式和 DPR 2.75;默认项目覆盖 360×800(`chrome-mobile`)和 393×851(`chrome-mobile-393`),screen 沿用模板;平板仅为桌面设备的平板尺寸 |
| 本地目标 | 未指定目标时自动发现并复用已有开发服务,确认不存在后才启动 `http://127.0.0.1:4176/`;开发和预览均严格占用指定端口,禁止静默回退 | | 本地目标 | 未指定目标时自动发现并复用已有开发服务,确认不存在后才启动 `http://127.0.0.1:4176/`;开发和预览均严格占用指定端口,禁止静默回退 |
| 目标切换 | `local-dist` 先校验静态入口与引用资源,再启动 Vite preview;`remote` 必须提供 `PW_BASE_URL`,不启动服务 | | 目标切换 | `local-dist` 先校验静态入口与引用资源,再启动 Vite preview;`remote` 必须提供 `PW_BASE_URL`,不启动服务 |
| 窗口 | 本地默认有头离屏;`PW_HEADLESS=1` 无头,CI 强制无头;隐藏滚动条并禁用后台降频 | | 窗口 | 本地默认有头离屏;`PW_HEADLESS=1` 无头,CI 强制无头;隐藏滚动条并禁用后台降频 |
@@ -175,7 +176,7 @@
### 7.3 采集与判定 ### 7.3 采集与判定
- 固定视口(桌面 1920×1000 / 移动 393×851,专项另有规定从其规定)、DPR 1、`zh-CN`、`Asia/Shanghai`、`reducedMotion: reduce`、相同数据与状态;用角色、标签、测试标识定位,用条件等待,不依赖固定延时与坐标。 - 固定视口(桌面 1920×1000,移动 393×851 和 360×800。360×800 是必测的最小移动视口,专项可增加其他尺寸)、DPR 1、`zh-CN`、`Asia/Shanghai`、`reducedMotion: reduce`、相同数据与状态;用角色、标签、测试标识定位,用条件等待,不依赖固定延时与坐标。
- 等待懒加载、骨架屏、提交中状态结束;检查错误消息、控制台、实际路由与无效数值,不能只凭无 pageerror 判定通过。 - 等待懒加载、骨架屏、提交中状态结束;检查错误消息、控制台、实际路由与无效数值,不能只凭无 pageerror 判定通过。
- 只读验收记录所有非 GET `/api/` 请求(应为 0);模拟响应按接口真实结构提供并标注;真实写入只用可清理的测试数据;支付未启用不得写成支付通过。 - 只读验收记录所有非 GET `/api/` 请求(应为 0);模拟响应按接口真实结构提供并标注;真实写入只用可清理的测试数据;支付未启用不得写成支付通过。
- 定位双字按钮允许 antd 默认字间距,如 `getByRole('button', { name: /^(?:loadings+)?保s*存$/ })`;虚拟 Select 用可见选项或组合框键盘操作,不点击隐藏的辅助选项。 - 定位双字按钮允许 antd 默认字间距,如 `getByRole('button', { name: /^(?:loadings+)?保s*存$/ })`;虚拟 Select 用可见选项或组合框键盘操作,不点击隐藏的辅助选项。
+2 -2
View File
@@ -38,8 +38,8 @@
| 页头 | `UserCenterPageHeader`;“新手教程 / 查看操作指引”图标按钮保留在右侧 | | 页头 | `UserCenterPageHeader`;“新手教程 / 查看操作指引”图标按钮保留在右侧 |
| 查询卡 | 保留单输入框,匹配密钥名称、Key 或分组。输入防抖,点击搜索或按回车立即提交,重置取消待提交条件并回到普通列表第 1 页 | | 查询卡 | 保留单输入框,匹配密钥名称、Key 或分组。输入防抖,点击搜索或按回车立即提交,重置取消待提交条件并回到普通列表第 1 页 |
| 列表 | `Table size='middle' tableLayout='fixed'`,列宽 150 / 300 / 150 / 100 / 180 / 100 / 100 / 130;默认每页 10 条;列设置用 `ColumnSettings`,不持久化 | | 列表 | `Table size='middle' tableLayout='fixed'`,列宽 150 / 300 / 150 / 100 / 180 / 100 / 100 / 130;默认每页 10 条;列设置用 `ColumnSettings`,不持久化 |
| 状态 | `Switch`(`onChange` 仍走原 `Modal.confirm` → `manageToken`);已过期 / 已耗尽另显示语义 `Tag` | | 状态 | `TableStatusSwitch`(`onChange` 仍走原 `Modal.confirm` → `manageToken`);已过期 / 已耗尽另显示语义 `Tag` |
| 分组 | `Tag color='blue'` 无边框 + `Tooltip`;额度为 `Tag color='success'` | | 分组 | `TableGroupTags` + `Tooltip`,颜色按组件公共规范;额度为 `Tag color='success'` |
| 密钥 | `<code>` 密钥框(底 `#f4f6f9`、描边 `#e4e9ee`,深色引用 `--surface-bg-base` / `--border-subtle`)+ 显示、隐藏、复制图标按钮 + `Tooltip`;脱敏提示 `Alert type='success'` | | 密钥 | `<code>` 密钥框(底 `#f4f6f9`、描边 `#e4e9ee`,深色引用 `--surface-bg-base` / `--border-subtle`)+ 显示、隐藏、复制图标按钮 + `Tooltip`;脱敏提示 `Alert type='success'` |
| 模型抽屉 | 440px;正文 20px;卡片间 18px;信息卡 16px(标签 12 / 18px);分类头 45px(底 `#f6f8fa`);模型名高 28px(等宽 12px、底 `#fafafa`);行距 9.5px、列距 8px;面板描边 `#e4e9ef` | | 模型抽屉 | 440px;正文 20px;卡片间 18px;信息卡 16px(标签 12 / 18px);分类头 45px(底 `#f6f8fa`);模型名高 28px(等宽 12px、底 `#fafafa`);行距 9.5px、列距 8px;面板描边 `#e4e9ef` |
| 编辑抽屉 | 560px(移动 100%);适配 `Form requiredMark={false}`;过期快捷 `Button` 组(间距 5px、描边 `#d9dfe6`、无按钮阴影,`aria-pressed`);仅“自定义”显示 `DatePicker showTime`;高级设置 `Collapse`(`forceRender`)+ `Switch` + `Divider`;页脚按钮间距 10px | | 编辑抽屉 | 560px(移动 100%);适配 `Form requiredMark={false}`;过期快捷 `Button` 组(间距 5px、描边 `#d9dfe6`、无按钮阴影,`aria-pressed`);仅“自定义”显示 `DatePicker showTime`;高级设置 `Collapse`(`forceRender`)+ `Switch` + `Divider`;页脚按钮间距 10px |
+12 -9
View File
@@ -1,6 +1,6 @@
# 企业中心 UI 规范(/org/\*) # 企业中心 UI 规范(/org/\*)
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v2.3 > 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-25 · 版本:v2.5
企业中心 12 个目标页的规范:企业中心变量、通用组件的企业中心变体与各页面规则。 企业中心 12 个目标页的规范:企业中心变量、通用组件的企业中心变体与各页面规则。
@@ -10,7 +10,7 @@
| 关注点 | 规则 | | 关注点 | 规则 |
| --- | --- | | --- | --- |
| 范围 | 工作台、数据看板、员工管理、项目管理、预算中心、审批中心、密钥管理、企业充值、消耗明细、审计日志、个人设置、企业设置;“我的 AI 能力”“组织架构”“角色管理”不改 | | 范围 | 工作台、数据看板、员工管理、项目管理、预算中心、审批中心、令牌管理(原“密钥管理”)、企业充值、消耗明细、审计日志、个人设置、企业设置;“我的 AI 能力”不改;“组织架构”页面名称统一为“部门管理”(与权限目录一致,2026-11-23);“角色管理”为统一权限体系新增页面(2026-11-23) |
| 样式 | `org-center.css`,作用域 `.org-center .oc-page`,颜色只写 `--oc-*`(第 2 节) | | 样式 | `org-center.css`,作用域 `.org-center .oc-page`,颜色只写 `--oc-*`(第 2 节) |
| 组件变体 | 紧凑表格、3 列筛选、无图标行操作、`.oc-list-tabs`、无边框标签(第 3 节) | | 组件变体 | 紧凑表格、3 列筛选、无图标行操作、`.oc-list-tabs`、无边框标签(第 3 节) |
| 弹层 | `OrgModal` / `OrgSideSheet`,原型风格遮罩;密钥抽屉 560px | | 弹层 | `OrgModal` / `OrgSideSheet`,原型风格遮罩;密钥抽屉 560px |
@@ -23,7 +23,7 @@
- 视觉依据:在线原型 `http://192.168.0.161:8888` 顶栏“企业中心”(深色用“切换至暗色主题”),只作视觉依据,不作业务、路由、数据依据。 - 视觉依据:在线原型 `http://192.168.0.161:8888` 顶栏“企业中心”(深色用“切换至暗色主题”),只作视觉依据,不作业务、路由、数据依据。
- 只对齐背景、字体、图标、表格、表单、卡片、页签、搜索条件、操作列、弹窗、按钮、颜色、文字、间距与已有交互反馈;不改请求、载荷、状态、路由、权限与触发条件。 - 只对齐背景、字体、图标、表格、表单、卡片、页签、搜索条件、操作列、弹窗、按钮、颜色、文字、间距与已有交互反馈;不改请求、载荷、状态、路由、权限与触发条件。
- 原型有而系统无的功能不补建:员工筛选卡、CSV 导出、新建员工 / 分配角色 / 离职、角色管理、在职 / 离职筛选、订单号搜索、分组列、发票入口。例外:企业密钥管理的分组列与列设置已按需求实现。 - 原型有而系统无的功能不补建:CSV 导出、在职 / 离职页签、订单号搜索、分组列、发票入口。例外:企业密钥管理的分组列与列设置已按需求实现。
## 2. 作用域与变量 ## 2. 作用域与变量
@@ -50,7 +50,7 @@
- **页头**:`OrgPageHeader`(内部复用 `UserCenterPageHeader`),规格见 `GLOBAL_UI_BASELINE.md` 4.4;页头不放操作按钮,操作移入列表卡头。面包屑分组见 4.4 第 3 条。 - **页头**:`OrgPageHeader`(内部复用 `UserCenterPageHeader`),规格见 `GLOBAL_UI_BASELINE.md` 4.4;页头不放操作按钮,操作移入列表卡头。面包屑分组见 4.4 第 3 条。
- **列表卡 `OrgListCard`**:卡头与表格间距 20px;表格为紧凑变体(正文 13px,表头 12px / 500、底色 `--oc-soft`,行上下内边距 17px);分页按公共组件规范,覆盖页签及表格明细。 - **列表卡 `OrgListCard`**:卡头与表格间距 20px;表格为紧凑变体(正文 13px,表头 12px / 500、底色 `--oc-soft`,行上下内边距 17px);分页按公共组件规范,覆盖页签及表格明细。
- **筛选卡 `OrgFilterCard`**:固定 3 列;筛选取值与生效时机沿用原页面(审计日志为“选择即筛选”,“搜索”以当前条件重新查询)。 - **筛选卡 `OrgFilterCard`**:默认 3 列。提示词记录和消耗明细的筛选区沿用个人消费记录的布局。筛选取值与生效时机沿用原页面(审计日志为“选择即筛选”,“搜索”以当前条件重新查询)。
- **行操作 `OrgRowActions`**:link 按钮 13 / 24px、无内边距、间距 10px,不带图标。 - **行操作 `OrgRowActions`**:link 按钮 13 / 24px、无内边距、间距 10px,不带图标。
- **列表页签 `.oc-list-tabs`**:导航高 44px,页签内边距 12px 0,选中与悬停色为 `--oc-brand`;只切换筛选时加 `.oc-tabs-nav-only`。 - **列表页签 `.oc-list-tabs`**:导航高 44px,页签内边距 12px 0,选中与悬停色为 `--oc-brand`;只切换筛选时加 `.oc-tabs-nav-only`。
- **标签**:表格与卡片内标签统一无边框(`variant='filled'`);非 antd 预设色改用 `gold` / `purple`。 - **标签**:表格与卡片内标签统一无边框(`variant='filled'`);非 antd 预设色改用 `gold` / `purple`。
@@ -64,14 +64,15 @@
| --- | --- | --- | | --- | --- | --- |
| 工作台 | `OrgHero` 标签化身份与 `oc-wb-*` 卡片(额度、密钥、用量、最近申请);横幅 `.ew-hero` 背景只在 `.org-workbench` 作用域 | 额度周期标签放在重置卡;最近申请无分页 | | 工作台 | `OrgHero` 标签化身份与 `oc-wb-*` 卡片(额度、密钥、用量、最近申请);横幅 `.ew-hero` 背景只在 `.org-workbench` 作用域 | 额度周期标签放在重置卡;最近申请无分页 |
| 数据看板 | `oc-dash-*` hero(健康提示“企业运行正常”、企业名、企业额度、组织概况)+ `OrgAnalyticsPanel`(汇总条、趋势 `Segmented`、分布、明细页签) | 时间范围 7 / 30 / 90 天;企业名来自 `orgInfo.name`,无值时隐藏 | | 数据看板 | `oc-dash-*` hero(健康提示“企业运行正常”、企业名、企业额度、组织概况)+ `OrgAnalyticsPanel`(汇总条、趋势 `Segmented`、分布、明细页签) | 时间范围 7 / 30 / 90 天;企业名来自 `orgInfo.name`,无值时隐藏 |
| 员工管理 | 页签(员工权限 / 员工账号)+ 列表卡;首列与操作列固定;备注独立列;状态 `Switch` | 无筛选卡与在职 / 离职页签 | | 员工管理 | 筛选卡(关键字、分组、组织、状态,服务端筛选)+ 单张列表卡,不分页签;备注独立列;状态 `Switch`;新建 / 编辑用抽屉 | 无在职 / 离职页签 |
| 项目管理 | `OrgListCard` + link 操作(模型 / 分组 / 成员 / 密钥 / 编辑);状态开关 | 操作列不再显示“停用” | | 项目管理 | `OrgListCard` + link 操作(模型 / 分组 / 成员 / 密钥 / 编辑);状态开关 | 操作列不再显示“停用” |
| 预算中心 | `.oc-policy` 固定说明条;列宽 300 / 110 / 260 / 120 / 120 / 130;状态开关 | 已加载数据前端分页 | | 预算中心 | `.oc-policy` 固定说明条;列宽 300 / 110 / 260 / 120 / 120 / 130;状态开关 | 已加载数据前端分页 |
| 审批中心 | 状态页签(回调 `setStatusFilter`)+ 申请列表卡;拒绝弹窗竖排表单项 | — | | 审批中心 | 状态页签(回调 `setStatusFilter`)+ 申请列表卡;拒绝弹窗竖排表单项 | — |
| Agent 任务审计 | 保留页头状态筛选、任务元数据 / 待对账 / 安全策略三个页签。记录按卡片排列,任务状态和计费状态使用独立标签,弹窗使用 `OrgModal` | 正文必须填写有效审计原因并经二次确认。页签计数、操作和焦点使用系统品牌色,状态标签使用语义色。窄屏按单列排列卡片,长编号换行 |
| 密钥管理 | 密钥框 + 显隐 / 复制、可用模型 link、分组列、状态开关、绝对时间;列设置用共享组件;创建 / 编辑为 560px `OrgSideSheet` | 列设置只在当前页面生效;非操作列整体横向滚动,仅在可见列宽度超过容器时显示滚动条 | | 密钥管理 | 密钥框 + 显隐 / 复制、可用模型 link、分组列、状态开关、绝对时间;列设置用共享组件;创建 / 编辑为 560px `OrgSideSheet` | 列设置只在当前页面生效;非操作列整体横向滚动,仅在可见列宽度超过容器时显示滚动条 |
| 企业充值 | 企业钱包 + 充值工作区(额度卡 / 自定义 / 支付方式)+ 订单卡 + 记录;订单“立即充值”与支付方式点击同为 `handlePreTopUp` | 档位与折扣来自后台配置;无订单号搜索与发票入口 | | 企业充值 | 企业钱包 + 充值工作区(额度卡 / 自定义 / 支付方式)+ 订单卡 + 记录;订单“立即充值”与支付方式点击同为 `handlePreTopUp` | 档位与折扣来自后台配置;无订单号搜索与发票入口 |
| 消耗明细 | 统计卡 + 页签(明细日志 / 成员排行 / 绘图与视频)+ 三列筛选卡 + 列表卡;查询按钮为“搜索”(`handleSearch`) | 见第 5 节 | | 消耗明细 | 统计卡 + 页签(明细日志 / 成员排行 / 绘图与视频)+ 消费记录样式筛选卡 + 列表卡;查询按钮为“搜索”(`handleSearch`) | 见第 5 节 |
| 审计日志 | 页签 + 筛选卡(操作类型)+ 操作记录卡;“提示词记录”页签沿用原显隐 | — | | 审计日志 | 页签 + 筛选卡(操作类型)+ 操作记录卡;“提示词记录”页签沿用原显隐,筛选区参考消费记录;说明条上下与筛选卡至列表卡均间隔 18px | — |
| 个人设置 | 复用用户中心 `ui-personal-*`、`AvatarSection`、`SectionHeader`;三页签:头像设置 / 个人资料 / 通知设置;企业身份并入资料头 | 昵称在弹窗中修改 | | 个人设置 | 复用用户中心 `ui-personal-*`、`AvatarSection`、`SectionHeader`;三页签:头像设置 / 个人资料 / 通知设置;企业身份并入资料头 | 昵称在弹窗中修改 |
| 企业设置 | 设置卡内页签 + 区块头(刷新 / 保存设置);复制为 14px 无内边距图标按钮 | 保留“数据安全”“危险区域”页签 | | 企业设置 | 设置卡内页签 + 区块头(刷新 / 保存设置);复制为 14px 无内边距图标按钮 | 保留“数据安全”“危险区域”页签 |
@@ -83,12 +84,14 @@
## 5. 消耗明细(/org/logs) ## 5. 消耗明细(/org/logs)
- 绘图与视频由 `components/OrgTaskRecords.jsx` 呈现,复用 `useTaskLogsData({ organizationMode: true })`、`TaskLogsFilters`、`getTaskLogsColumns`、`exportTaskLogsPageCsv`、`ColumnSelectorModal`、`ContentModal`;结构为筛选卡 + “任务记录”列表卡(导出本页 / 刷新 / 列设置),不渲染“本页统计”区块,移动端筛选直接展开。 - 三个页签和审计日志下的提示词记录共用个人消费记录的筛选布局:桌面五列,时间范围跨两列;窄屏三列,移动端单列并默认收起。操作区位于右下,“重置”在前,“搜索”在后,点击和回车共用提交入口。
- 绘图与视频由 `components/OrgTaskRecords.jsx` 呈现,复用 `useTaskLogsData({ organizationMode: true })`、`TaskLogsFilters`、`getTaskLogsColumns`、`exportTaskLogsPageCsv`、`ColumnSelectorModal`、`ContentModal`;结构为筛选卡 + “任务记录”列表卡(导出本页 / 刷新 / 列设置),不渲染“本页统计”区块。
- 任务表列宽 185 / 185 / 110 / 110 / 250 / 330 / 110 / 155 / 145 / 150;模型为行内胶囊,费用主色右对齐;分页沿用公共规范。“刷新”与“搜索”调用同一 `refresh`。 - 任务表列宽 185 / 185 / 110 / 110 / 250 / 330 / 110 / 155 / 145 / 150;模型为行内胶囊,费用主色右对齐;分页沿用公共规范。“刷新”与“搜索”调用同一 `refresh`。
- 时间范围为本页签自有的可编辑字段(默认最近 7 天,含快捷预设),与“明细日志”筛选互不影响;起止颠倒沿用原提示。 - 时间范围为本页签自有的可编辑字段(默认最近 7 天,含快捷预设),与“明细日志”筛选互不影响;起止颠倒沿用原提示。
- 末列“操作”不固定:视频任务显示“点击预览视频”,失败任务保留失败原因查看,其余显示“-”。 - 末列“操作”不固定:视频任务显示“点击预览视频”,失败任务保留失败原因查看,其余显示“-”。
- 预览视频沿用 `ContentModal`:标题栏“视频预览”与关闭按钮、16:9 播放区、加载态、播放失败或无地址时 `Empty` 空态、页脚复制链接 / 新标签页打开 / 关闭;关闭时暂停视频,重开同一视频不残留加载指示。 - 预览视频沿用 `ContentModal`:标题栏“视频预览”与关闭按钮、16:9 播放区、加载态、播放失败或无地址时 `Empty` 空态、页脚复制链接 / 新标签页打开 / 关闭;关闭时暂停视频,重开同一视频不残留加载指示。
- 成员排行行键使用 `user_id-名次序号`,避免后端同一成员多行时出现重复 key。 - 只有具备排行权限并打开「成员排行」时才查询榜单。首次打开使用已生效的成员、模型和时间范围,默认每页 10 人。翻页和更改每页人数均携带服务端返回的 `snapshot`。搜索、重置、刷新及切换企业会重新查询当前条件下的榜单。快照过期时自动按原筛选和页容量回到第 1 页重取一次。
- 服务端按成员汇总后按消耗额度降序排列,同额按成员 ID 升序。行键使用 `user_id`,名次按返回页码、页容量和行号连续计算。前三名使用当前主题的强调色及三档底色,其余名次使用中性色。
- 明细日志查询不写 URL;绘图与视频筛选沿用原有 URL 同步。 - 明细日志查询不写 URL;绘图与视频筛选沿用原有 URL 同步。
- 保留差异:明细日志无列设置、分组列、操作列;任务表无渠道 / 用户 ID 筛选、平台列、排序与任务 ID 复制。 - 保留差异:明细日志无列设置、分组列、操作列;任务表无渠道 / 用户 ID 筛选、平台列、排序与任务 ID 复制。
+2 -2
View File
@@ -1,6 +1,6 @@
# 用户中心 UI 规范(/user-center/\*) # 用户中心 UI 规范(/user-center/\*)
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v2.4 > 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-25 · 版本:v2.5
个人登录后用户中心页面的规范,只记录与公共规范不同的部分;密钥管理、服务监控见各自规范。 个人登录后用户中心页面的规范,只记录与公共规范不同的部分;密钥管理、服务监控见各自规范。
@@ -78,7 +78,7 @@
- 页签:纯文字页签(公共列表页签样式),与下方 20px,URL `?tab=` 同步并懒挂载。 - 页签:纯文字页签(公共列表页签样式),与下方 20px,URL `?tab=` 同步并懒挂载。
- 筛选卡:5 列栅格,时间范围跨 2 列;背景使用 `--surface-card` 纯色(浅色为白色、深色为主题卡片色);操作“重置 / 搜索”右下。 - 筛选卡:5 列栅格,时间范围跨 2 列;背景使用 `--surface-card` 纯色(浅色为白色、深色为主题卡片色);操作“重置 / 搜索”右下。
- 列表卡:标题 15px / 600,导出、列设置位于卡头右侧;表头字重 400(公共标准为 500,待收敛)。 - 列表卡:标题 15px / 600,导出、列设置位于卡头右侧;表头字重 400(公共标准为 500,待收敛)。
- 消费记录调用明细为固定列宽宽表,时间分两行(日期 11px、时间 15px / 600),操作列文字“查看”,固定在右侧;横向滚动条保留 Ant Design 官方固定列表格行为,固定列兼容规则遵循公共规范第 5.2 节。 - 消费记录调用明细为固定列宽宽表,横向滚动时“时间”列固定在左侧,“操作”列显示时固定在右侧,中间列可滚动。时间分两行(日期 11px、时间 15px / 600),固定列兼容规则遵循公共规范第 5.2 节。
- 消费记录“用时 / 首字”列宽 190px,总用时、首字耗时与流式状态分别用 antd 默认带描边 `Tag` 展示,保留主题算法生成的浅底 / 文字 / 边框。总用时对 `use_time` 取整数秒,`<101s` 用 `green`、`101–299s` 用 `gold`、`≥300s` 用 `magenta`;首字耗时取 `other.frt / 1000`,先保留一位小数再判色,`<3s` 用 `cyan`、`3–<10s` 用 `orange`、`≥10s` 用 `red`。流式显示三枚标签(状态为蓝色“流”),非流式仅显示总用时与中性“非流”;零值正常展示,缺失、非数值或负耗时显示中性破折号。 - 消费记录“用时 / 首字”列宽 190px,总用时、首字耗时与流式状态分别用 antd 默认带描边 `Tag` 展示,保留主题算法生成的浅底 / 文字 / 边框。总用时对 `use_time` 取整数秒,`<101s` 用 `green`、`101–299s` 用 `gold`、`≥300s` 用 `magenta`;首字耗时取 `other.frt / 1000`,先保留一位小数再判色,`<3s` 用 `cyan`、`3–<10s` 用 `orange`、`≥10s` 用 `red`。流式显示三枚标签(状态为蓝色“流”),非流式仅显示总用时与中性“非流”;零值正常展示,缺失、非数值或负耗时显示中性破折号。
- 绘图与视频:三张统计卡(高 70px、间距 15px)+ 任务记录表。 - 绘图与视频:三张统计卡(高 70px、间距 15px)+ 任务记录表。
- Webhook 示例为 `<pre class='ui-notify-code'>` +“复制”链接,复制提示沿用原文案。 - Webhook 示例为 `<pre class='ui-notify-code'>` +“复制”链接,复制提示沿用原文案。
+230 -130
View File
@@ -55,7 +55,7 @@
"@playwright/test": "1.64.1", "@playwright/test": "1.64.1",
"@vitejs/plugin-react": "^4.2.1", "@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.21", "autoprefixer": "^10.4.21",
"esbuild": "0.21.5", "esbuild": "0.25.12",
"eslint": "9.39.5", "eslint": "9.39.5",
"eslint-plugin-react": "^7.37.5", "eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^5.2.0", "eslint-plugin-react-hooks": "^5.2.0",
@@ -65,7 +65,7 @@
"postcss": "^8.5.3", "postcss": "^8.5.3",
"prettier": "^3.0.0", "prettier": "^3.0.0",
"tailwindcss": "^3", "tailwindcss": "^3",
"vite": "5.4.21" "vite": "6.4.6"
}, },
"engines": { "engines": {
"node": ">=22.13.0", "node": ">=22.13.0",
@@ -542,9 +542,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@esbuild/aix-ppc64": { "node_modules/@esbuild/aix-ppc64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
"integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
"cpu": [ "cpu": [
"ppc64" "ppc64"
], ],
@@ -555,13 +555,13 @@
"aix" "aix"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/android-arm": { "node_modules/@esbuild/android-arm": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/android-arm/-/android-arm-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
"integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
"cpu": [ "cpu": [
"arm" "arm"
], ],
@@ -572,13 +572,13 @@
"android" "android"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/android-arm64": { "node_modules/@esbuild/android-arm64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
"integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -589,13 +589,13 @@
"android" "android"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/android-x64": { "node_modules/@esbuild/android-x64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/android-x64/-/android-x64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
"integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -606,13 +606,13 @@
"android" "android"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/darwin-arm64": { "node_modules/@esbuild/darwin-arm64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
"integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -623,13 +623,13 @@
"darwin" "darwin"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/darwin-x64": { "node_modules/@esbuild/darwin-x64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
"integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -640,13 +640,13 @@
"darwin" "darwin"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/freebsd-arm64": { "node_modules/@esbuild/freebsd-arm64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
"integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -657,13 +657,13 @@
"freebsd" "freebsd"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/freebsd-x64": { "node_modules/@esbuild/freebsd-x64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
"integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -674,13 +674,13 @@
"freebsd" "freebsd"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/linux-arm": { "node_modules/@esbuild/linux-arm": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
"integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
"cpu": [ "cpu": [
"arm" "arm"
], ],
@@ -691,13 +691,13 @@
"linux" "linux"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/linux-arm64": { "node_modules/@esbuild/linux-arm64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
"integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -708,13 +708,13 @@
"linux" "linux"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/linux-ia32": { "node_modules/@esbuild/linux-ia32": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
"integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
"cpu": [ "cpu": [
"ia32" "ia32"
], ],
@@ -725,13 +725,13 @@
"linux" "linux"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/linux-loong64": { "node_modules/@esbuild/linux-loong64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
"integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
"cpu": [ "cpu": [
"loong64" "loong64"
], ],
@@ -742,13 +742,13 @@
"linux" "linux"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/linux-mips64el": { "node_modules/@esbuild/linux-mips64el": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
"integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
"cpu": [ "cpu": [
"mips64el" "mips64el"
], ],
@@ -759,13 +759,13 @@
"linux" "linux"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/linux-ppc64": { "node_modules/@esbuild/linux-ppc64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
"integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
"cpu": [ "cpu": [
"ppc64" "ppc64"
], ],
@@ -776,13 +776,13 @@
"linux" "linux"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/linux-riscv64": { "node_modules/@esbuild/linux-riscv64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
"integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
"cpu": [ "cpu": [
"riscv64" "riscv64"
], ],
@@ -793,13 +793,13 @@
"linux" "linux"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/linux-s390x": { "node_modules/@esbuild/linux-s390x": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
"integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
"cpu": [ "cpu": [
"s390x" "s390x"
], ],
@@ -810,13 +810,13 @@
"linux" "linux"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/linux-x64": { "node_modules/@esbuild/linux-x64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
"integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -827,13 +827,30 @@
"linux" "linux"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
"integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
} }
}, },
"node_modules/@esbuild/netbsd-x64": { "node_modules/@esbuild/netbsd-x64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
"integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -844,13 +861,30 @@
"netbsd" "netbsd"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
"integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
} }
}, },
"node_modules/@esbuild/openbsd-x64": { "node_modules/@esbuild/openbsd-x64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
"integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -861,13 +895,30 @@
"openbsd" "openbsd"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
"integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
} }
}, },
"node_modules/@esbuild/sunos-x64": { "node_modules/@esbuild/sunos-x64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
"integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -878,13 +929,13 @@
"sunos" "sunos"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/win32-arm64": { "node_modules/@esbuild/win32-arm64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
"integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -895,13 +946,13 @@
"win32" "win32"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/win32-ia32": { "node_modules/@esbuild/win32-ia32": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
"integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
"cpu": [ "cpu": [
"ia32" "ia32"
], ],
@@ -912,13 +963,13 @@
"win32" "win32"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@esbuild/win32-x64": { "node_modules/@esbuild/win32-x64": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
"integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -929,7 +980,7 @@
"win32" "win32"
], ],
"engines": { "engines": {
"node": ">=12" "node": ">=18"
} }
}, },
"node_modules/@eslint-community/eslint-utils": { "node_modules/@eslint-community/eslint-utils": {
@@ -5824,9 +5875,9 @@
] ]
}, },
"node_modules/esbuild": { "node_modules/esbuild": {
"version": "0.21.5", "version": "0.25.12",
"resolved": "https://registry.npmmirror.com/esbuild/-/esbuild-0.21.5.tgz", "resolved": "https://registry.npmmirror.com/esbuild/-/esbuild-0.25.12.tgz",
"integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
"dev": true, "dev": true,
"hasInstallScript": true, "hasInstallScript": true,
"license": "MIT", "license": "MIT",
@@ -5834,32 +5885,35 @@
"esbuild": "bin/esbuild" "esbuild": "bin/esbuild"
}, },
"engines": { "engines": {
"node": ">=12" "node": ">=18"
}, },
"optionalDependencies": { "optionalDependencies": {
"@esbuild/aix-ppc64": "0.21.5", "@esbuild/aix-ppc64": "0.25.12",
"@esbuild/android-arm": "0.21.5", "@esbuild/android-arm": "0.25.12",
"@esbuild/android-arm64": "0.21.5", "@esbuild/android-arm64": "0.25.12",
"@esbuild/android-x64": "0.21.5", "@esbuild/android-x64": "0.25.12",
"@esbuild/darwin-arm64": "0.21.5", "@esbuild/darwin-arm64": "0.25.12",
"@esbuild/darwin-x64": "0.21.5", "@esbuild/darwin-x64": "0.25.12",
"@esbuild/freebsd-arm64": "0.21.5", "@esbuild/freebsd-arm64": "0.25.12",
"@esbuild/freebsd-x64": "0.21.5", "@esbuild/freebsd-x64": "0.25.12",
"@esbuild/linux-arm": "0.21.5", "@esbuild/linux-arm": "0.25.12",
"@esbuild/linux-arm64": "0.21.5", "@esbuild/linux-arm64": "0.25.12",
"@esbuild/linux-ia32": "0.21.5", "@esbuild/linux-ia32": "0.25.12",
"@esbuild/linux-loong64": "0.21.5", "@esbuild/linux-loong64": "0.25.12",
"@esbuild/linux-mips64el": "0.21.5", "@esbuild/linux-mips64el": "0.25.12",
"@esbuild/linux-ppc64": "0.21.5", "@esbuild/linux-ppc64": "0.25.12",
"@esbuild/linux-riscv64": "0.21.5", "@esbuild/linux-riscv64": "0.25.12",
"@esbuild/linux-s390x": "0.21.5", "@esbuild/linux-s390x": "0.25.12",
"@esbuild/linux-x64": "0.21.5", "@esbuild/linux-x64": "0.25.12",
"@esbuild/netbsd-x64": "0.21.5", "@esbuild/netbsd-arm64": "0.25.12",
"@esbuild/openbsd-x64": "0.21.5", "@esbuild/netbsd-x64": "0.25.12",
"@esbuild/sunos-x64": "0.21.5", "@esbuild/openbsd-arm64": "0.25.12",
"@esbuild/win32-arm64": "0.21.5", "@esbuild/openbsd-x64": "0.25.12",
"@esbuild/win32-ia32": "0.21.5", "@esbuild/openharmony-arm64": "0.25.12",
"@esbuild/win32-x64": "0.21.5" "@esbuild/sunos-x64": "0.25.12",
"@esbuild/win32-arm64": "0.25.12",
"@esbuild/win32-ia32": "0.25.12",
"@esbuild/win32-x64": "0.25.12"
} }
}, },
"node_modules/escalade": { "node_modules/escalade": {
@@ -12202,21 +12256,24 @@
} }
}, },
"node_modules/vite": { "node_modules/vite": {
"version": "5.4.21", "version": "6.4.6",
"resolved": "https://registry.npmmirror.com/vite/-/vite-5.4.21.tgz", "resolved": "https://registry.npmmirror.com/vite/-/vite-6.4.6.tgz",
"integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", "integrity": "sha512-RtsraAwEG68idOA6iUOoIpOlcSKROnf815aIq9qHTSrDNpLoBrBa12suyfcEd8qn0xwOVQI1Yhm1GbmTjF600A==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"esbuild": "^0.21.3", "esbuild": "^0.25.0",
"postcss": "^8.4.43", "fdir": "^6.4.4",
"rollup": "^4.20.0" "picomatch": "^4.0.2",
"postcss": "^8.5.3",
"rollup": "^4.34.9",
"tinyglobby": "^0.2.13"
}, },
"bin": { "bin": {
"vite": "bin/vite.js" "vite": "bin/vite.js"
}, },
"engines": { "engines": {
"node": "^18.0.0 || >=20.0.0" "node": "^18.0.0 || ^20.0.0 || >=22.0.0"
}, },
"funding": { "funding": {
"url": "https://github.com/vitejs/vite?sponsor=1" "url": "https://github.com/vitejs/vite?sponsor=1"
@@ -12225,19 +12282,25 @@
"fsevents": "~2.3.3" "fsevents": "~2.3.3"
}, },
"peerDependencies": { "peerDependencies": {
"@types/node": "^18.0.0 || >=20.0.0", "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
"jiti": ">=1.21.0",
"less": "*", "less": "*",
"lightningcss": "^1.21.0", "lightningcss": "^1.21.0",
"sass": "*", "sass": "*",
"sass-embedded": "*", "sass-embedded": "*",
"stylus": "*", "stylus": "*",
"sugarss": "*", "sugarss": "*",
"terser": "^5.4.0" "terser": "^5.16.0",
"tsx": "^4.8.1",
"yaml": "^2.4.2"
}, },
"peerDependenciesMeta": { "peerDependenciesMeta": {
"@types/node": { "@types/node": {
"optional": true "optional": true
}, },
"jiti": {
"optional": true
},
"less": { "less": {
"optional": true "optional": true
}, },
@@ -12258,9 +12321,46 @@
}, },
"terser": { "terser": {
"optional": true "optional": true
},
"tsx": {
"optional": true
},
"yaml": {
"optional": true
} }
} }
}, },
"node_modules/vite/node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmmirror.com/fdir/-/fdir-6.5.0.tgz",
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12.0.0"
},
"peerDependencies": {
"picomatch": "^3 || ^4"
},
"peerDependenciesMeta": {
"picomatch": {
"optional": true
}
}
},
"node_modules/vite/node_modules/picomatch": {
"version": "4.0.7",
"resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-4.0.7.tgz",
"integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/void-elements": { "node_modules/void-elements": {
"version": "3.1.0", "version": "3.1.0",
"resolved": "https://registry.npmmirror.com/void-elements/-/void-elements-3.1.0.tgz", "resolved": "https://registry.npmmirror.com/void-elements/-/void-elements-3.1.0.tgz",
+2 -2
View File
@@ -89,7 +89,7 @@
"@playwright/test": "1.64.1", "@playwright/test": "1.64.1",
"@vitejs/plugin-react": "^4.2.1", "@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.21", "autoprefixer": "^10.4.21",
"esbuild": "0.21.5", "esbuild": "0.25.12",
"eslint": "9.39.5", "eslint": "9.39.5",
"eslint-plugin-react": "^7.37.5", "eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^5.2.0", "eslint-plugin-react-hooks": "^5.2.0",
@@ -99,7 +99,7 @@
"postcss": "^8.5.3", "postcss": "^8.5.3",
"prettier": "^3.0.0", "prettier": "^3.0.0",
"tailwindcss": "^3", "tailwindcss": "^3",
"vite": "5.4.21" "vite": "6.4.6"
}, },
"engines": { "engines": {
"node": ">=22.13.0", "node": ">=22.13.0",
+2 -3
View File
@@ -2,6 +2,7 @@ import { defineConfig } from '@playwright/test';
import { import {
browserChannel, browserChannel,
contextOptions, contextOptions,
defaultProjectViewports,
projectViewports, projectViewports,
} from './scripts/browser-environment.mjs'; } from './scripts/browser-environment.mjs';
import { runtimeOptions } from './scripts/playwright-runtime.mjs'; import { runtimeOptions } from './scripts/playwright-runtime.mjs';
@@ -29,9 +30,7 @@ if (
) )
) )
throw new Error('CI requires headless non-interactive tests'); throw new Error('CI requires headless non-interactive tests');
const viewports = runtime.extended const viewports = runtime.extended ? projectViewports : defaultProjectViewports;
? projectViewports
: projectViewports.slice(0, 2);
// UI_VISUAL_OFFSCREEN=0 仅限人工本地可视化调试时临时使用。 // UI_VISUAL_OFFSCREEN=0 仅限人工本地可视化调试时临时使用。
// Agent、CI、无头/自动化环境禁止设置该值,必须保持默认离屏模式 // Agent、CI、无头/自动化环境禁止设置该值,必须保持默认离屏模式
+5 -3
View File
@@ -13,9 +13,9 @@ const aliases = {
'laptop-wxga': 'wxga', 'laptop-wxga': 'wxga',
}; };
export const browserChannel = config.browser.channel; export const browserChannel = config.browser.channel;
export const defaultProjectViewports = ['desktop', 'mobile', 'mobile-393'];
export const projectViewports = [ export const projectViewports = [
'desktop', ...defaultProjectViewports,
'mobile',
'tablet', 'tablet',
'desktop-boundary', 'desktop-boundary',
'laptop-hd', 'laptop-hd',
@@ -30,7 +30,9 @@ export function deviceOptions(name) {
if (!size) throw new Error(`Unknown viewport: ${name}`); if (!size) throw new Error(`Unknown viewport: ${name}`);
const descriptor = const descriptor =
devices[ devices[
config.browser[key === 'mobile' ? 'mobileDevice' : 'desktopDevice'] config.browser[
key.startsWith('mobile') ? 'mobileDevice' : 'desktopDevice'
]
]; ];
if (!descriptor) throw new Error(`Unknown device profile for ${name}`); if (!descriptor) throw new Error(`Unknown device profile for ${name}`);
const { defaultBrowserType, ...context } = descriptor; const { defaultBrowserType, ...context } = descriptor;
+1
View File
@@ -9,6 +9,7 @@
"viewports": { "viewports": {
"desktop": [1920, 1080], "desktop": [1920, 1080],
"mobile": [360, 800], "mobile": [360, 800],
"mobile-393": [393, 851],
"tablet": [768, 1024], "tablet": [768, 1024],
"laptop": [1024, 768], "laptop": [1024, 768],
"hd": [1366, 768], "hd": [1366, 768],
+115 -56
View File
@@ -11,6 +11,7 @@ import {
AdminRoute, AdminRoute,
RootRoute, RootRoute,
} from './helpers/auth'; } from './helpers/auth';
import { PermRoute, ConsoleRoute, ConsoleIndexRoute } from './authz';
import NotFound from './pages/NotFound'; import NotFound from './pages/NotFound';
import Forbidden from './pages/Forbidden'; import Forbidden from './pages/Forbidden';
import { StatusContext } from './context/Status'; import { StatusContext } from './context/Status';
@@ -82,6 +83,14 @@ const Analytics = lazy(() => import('./pages/Analytics'));
const SmartRouter = lazy(() => import('./pages/SmartRouter')); const SmartRouter = lazy(() => import('./pages/SmartRouter'));
const Organization = lazy(() => import('./pages/Organization')); const Organization = lazy(() => import('./pages/Organization'));
const AdminOrganizations = lazy(() => import('./pages/AdminOrganizations')); const AdminOrganizations = lazy(() => import('./pages/AdminOrganizations'));
// 平台侧权限管理(菜单管理 / 平台角色 / 功能套餐 / 角色模板 / 运行模式)
const AuthzMenuManage = lazy(() => import('./pages/Permission/MenuManage'));
const AuthzPlatformRoles = lazy(
() => import('./pages/Permission/PlatformRoles'),
);
const AuthzPackages = lazy(() => import('./pages/Permission/Packages'));
const AuthzTemplates = lazy(() => import('./pages/Permission/Templates'));
const AuthzRunMode = lazy(() => import('./pages/Permission/RunMode'));
const AdminOrder = lazy(() => import('./pages/AdminOrder')); const AdminOrder = lazy(() => import('./pages/AdminOrder'));
const AdminInvoice = lazy(() => import('./pages/AdminInvoice')); const AdminInvoice = lazy(() => import('./pages/AdminInvoice'));
const Subscription = lazy(() => import('./pages/Subscription')); const Subscription = lazy(() => import('./pages/Subscription'));
@@ -280,51 +289,51 @@ function App() {
<Route <Route
path='/console/models' path='/console/models'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.model'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<ModelPage /> <ModelPage />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
path='/console/channel' path='/console/channel'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.channel'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<Channel /> <Channel />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
path='/console/token' path='/console/token'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.admin_token'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<Token /> <Token />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
path='/console/playground' path='/console/playground'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.playground'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<Playground /> <Playground />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
path='/console/monitor' path='/console/monitor'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.monitor'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<MonitorCenter /> <MonitorCenter />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
@@ -340,11 +349,11 @@ function App() {
<Route <Route
path='/console/analytics' path='/console/analytics'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.analytics'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<Analytics /> <Analytics />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
@@ -371,40 +380,91 @@ function App() {
/* 分佣管理为 Root 专属:侧边栏一直用 isRoot() 隐藏该入口,后端结算/销售/成本/ /* 分佣管理为 Root 专属:侧边栏一直用 isRoot() 隐藏该入口,后端结算/销售/成本/
伙伴管理各路由组也已全部 Root 收口。这里把路由守卫对齐,避免 role=10 直接 伙伴管理各路由组也已全部 Root 收口。这里把路由守卫对齐,避免 role=10 直接
输 URL 进到一个读得到、写按钮全 403 的半残页面。 */ 输 URL 进到一个读得到、写按钮全 403 的半残页面。 */
<RootRoute> <ConsoleRoute code='platform.commission' legacy='root'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<CommissionV2 /> <CommissionV2 />
</Suspense> </Suspense>
</RootRoute> </ConsoleRoute>
} }
/> />
<Route <Route
path='/console/experience-center-audit' path='/console/experience-center-audit'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.analytics'>
<Navigate to='/console/analytics?tab=audit' replace /> <Navigate to='/console/analytics?tab=audit' replace />
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
path='/console/organizations' path='/console/organizations'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.org'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<AdminOrganizations /> <AdminOrganizations />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
}
/>
{/* 平台侧权限管理:路由按与侧边栏相同的权限点守卫(PermRoute),接口权限由后端校验;运行模式仅 root */}
<Route
path='/console/authz/menus'
element={
<PermRoute code='platform.authz.menu.query'>
<Suspense fallback={<Loading />}>
<AuthzMenuManage />
</Suspense>
</PermRoute>
}
/>
<Route
path='/console/authz/roles'
element={
<PermRoute code='platform.authz.role.query'>
<Suspense fallback={<Loading />}>
<AuthzPlatformRoles />
</Suspense>
</PermRoute>
}
/>
<Route
path='/console/authz/packages'
element={
<PermRoute code='platform.authz.package.query'>
<Suspense fallback={<Loading />}>
<AuthzPackages />
</Suspense>
</PermRoute>
}
/>
<Route
path='/console/authz/templates'
element={
<PermRoute code='platform.authz.template.query'>
<Suspense fallback={<Loading />}>
<AuthzTemplates />
</Suspense>
</PermRoute>
}
/>
<Route
path='/console/authz/mode'
element={
<RootRoute>
<Suspense fallback={<Loading />}>
<AuthzRunMode />
</Suspense>
</RootRoute>
} }
/> />
<Route <Route
path='/console/skill-platform' path='/console/skill-platform'
element={ element={
CLOUD_BRAIN_UI_ENABLED ? ( CLOUD_BRAIN_UI_ENABLED ? (
<AdminRoute> <ConsoleRoute code='platform.skill'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<SkillPlatform /> <SkillPlatform />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
) : ( ) : (
<Navigate to='/console' replace /> <Navigate to='/console' replace />
) )
@@ -414,11 +474,11 @@ function App() {
path='/console/expert-platform' path='/console/expert-platform'
element={ element={
CLOUD_BRAIN_UI_ENABLED ? ( CLOUD_BRAIN_UI_ENABLED ? (
<AdminRoute> <ConsoleRoute code='platform.expert'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<ExpertPlatform /> <ExpertPlatform />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
) : ( ) : (
<Navigate to='/console' replace /> <Navigate to='/console' replace />
) )
@@ -427,21 +487,21 @@ function App() {
<Route <Route
path='/console/order' path='/console/order'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.order'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<AdminOrder /> <AdminOrder />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
path='/console/invoice' path='/console/invoice'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.invoice'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<AdminInvoice /> <AdminInvoice />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
{/* 旧路由重定向到用户中心内的服务监控 */} {/* 旧路由重定向到用户中心内的服务监控 */}
@@ -485,31 +545,31 @@ function App() {
<Route <Route
path='/console/redemption' path='/console/redemption'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.redemption'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<Redemption /> <Redemption />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
path='/console/user' path='/console/user'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.user'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<User /> <User />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
path='/console/subscription' path='/console/subscription'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.subscription'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<Subscription /> <Subscription />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
@@ -631,31 +691,37 @@ function App() {
<Route <Route
path='/console/setting' path='/console/setting'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.setting'>
<Suspense fallback={<Loading></Loading>} key={location.pathname}> <Suspense fallback={<Loading></Loading>} key={location.pathname}>
<Setting /> <Setting />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
path='/console/website-setting' path='/console/website-setting'
element={ element={
<AdminRoute permission='website-setting'> <ConsoleRoute
code='platform.setting.website_setting'
permission='website-setting'
>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<WebsiteSettings /> <WebsiteSettings />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
path='/console/demo-reservations' path='/console/demo-reservations'
element={ element={
<AdminRoute permission='demo-reservations'> <ConsoleRoute
code='platform.setting.demo_reservations'
permission='demo-reservations'
>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<DemoReservations /> <DemoReservations />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
@@ -671,49 +737,42 @@ function App() {
<Route <Route
path='/console/topup' path='/console/topup'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.topup'>
<Suspense fallback={<Loading></Loading>} key={location.pathname}> <Suspense fallback={<Loading></Loading>} key={location.pathname}>
<TopUp /> <TopUp />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
path='/console/log' path='/console/log'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.log'>
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<Log /> <Log />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
}
/>
<Route
path='/console'
element={
<AdminRoute>
<Navigate to='/console/analytics' replace />
</AdminRoute>
} }
/> />
<Route path='/console' element={<ConsoleIndexRoute />} />
<Route <Route
path='/console/midjourney' path='/console/midjourney'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.drawing_log'>
<Suspense fallback={<Loading></Loading>} key={location.pathname}> <Suspense fallback={<Loading></Loading>} key={location.pathname}>
<Midjourney /> <Midjourney />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
path='/console/task' path='/console/task'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.task_log'>
<Suspense fallback={<Loading></Loading>} key={location.pathname}> <Suspense fallback={<Loading></Loading>} key={location.pathname}>
<Task /> <Task />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
<Route <Route
@@ -865,11 +924,11 @@ function App() {
<Route <Route
path='/console/chat/:id?' path='/console/chat/:id?'
element={ element={
<AdminRoute> <ConsoleRoute code='platform.chat'>
<Suspense fallback={<Loading></Loading>} key={location.pathname}> <Suspense fallback={<Loading></Loading>} key={location.pathname}>
<Chat /> <Chat />
</Suspense> </Suspense>
</AdminRoute> </ConsoleRoute>
} }
/> />
{/* 方便使用chat2link直接跳转聊天... */} {/* 方便使用chat2link直接跳转聊天... */}
+393
View File
@@ -0,0 +1,393 @@
/*
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, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useLocation } from 'react-router-dom';
import { Modal } from 'antd';
import { useTranslation } from 'react-i18next';
import { API } from '../helpers/api';
import {
clearUserData,
isOrgLoginSession,
ORG_LOGIN_SESSION_KEY,
USER_STORAGE_KEY,
} from '../helpers/data';
import {
clearProxyExpired,
getCurrentOrgId,
getProxySession,
} from '../helpers/orgContext';
import { UserContext } from '../context/User';
import { normalizeView } from './permLogic';
// 权限上下文(权限重构 §9 GET /api/authz/me):同时持有平台视图与当前企业视图。
// 企业视图随当前企业(或代理会话)切换重新加载。有已切换模块、处于代理会话或上一次加载失败时,页面重新获得焦点
// (10 秒内不重复)、或每 60 秒刷新一次;否则(未切换,视图只用于判断是否已切换)每 10 分钟刷新一次、获得焦点时
// 2 分钟内不重复,不挤占按 IP 计数的全局限流,同时切换后用户切回窗口即可较快跟上。
// 当前视图的有效内容(权限点、菜单、数据范围)发生变化且涉及已切换模块时,按 Q12 要求重新登录。
export const AuthzContext = createContext({
platform: null,
org: null,
orgLoadedKey: null,
platformLoadedFor: 0,
platformLoadFailed: false,
reload: () => {},
});
const REFRESH_MS = 60 * 1000;
// 未切换时的刷新间隔
const IDLE_REFRESH_MS = 10 * 60 * 1000;
// 窗口 focus 触发刷新的节流间隔:频繁切换窗口时不重复拉取
const FOCUS_THROTTLE_MS = 10 * 1000;
// 未切换时 focus 触发刷新的节流间隔
const IDLE_FOCUS_THROTTLE_MS = 2 * 60 * 1000;
// 未登录(会话失效、其他标签页已登出):不算"加载失败",不因此转入高频刷新
const UNAUTHORIZED = Symbol('unauthorized');
// 拉取视图;接口 success:false 或网络错误返回 null(调用方按"加载失败"处理),401 返回 UNAUTHORIZED
const fetchView = async (headers) => {
try {
const res = await API.get('/api/authz/me', {
headers,
skipErrorHandler: true,
disableDuplicate: true,
});
return res.data?.success ? normalizeView(res.data.data) : null;
} catch (e) {
return e?.response?.status === 401 ? UNAUTHORIZED : null;
}
};
// 当前企业视图的标识(企业 ID + 代理会话):企业中心据此判断企业视图是否已按当前企业加载过
export const currentOrgViewKey = () =>
`${getCurrentOrgId()}:${getProxySession()?.id || ''}`;
const orgHeaders = () => {
const proxy = getProxySession();
const orgId = getCurrentOrgId();
if (!orgId) return null;
const h = { 'X-Org-Id': String(orgId) };
if (proxy) h['X-Proxy-Session'] = proxy.id;
return h;
};
// 视图有效内容的指纹:只取已切换模块(前后两次 enforced_modules 的并集)内的权限点、
// 菜单(code 与 visible)与数据范围类型(全部 / 部门 / 本人);未切换模块的变化不影响页面行为,不纳入。
// 部门个数不纳入:它是按部门树展开后的个数,新增子部门就会变化,而页面行为不变。
// 已切换模块列表本身不纳入:模块切换(或回退)只是把页面从旧判断改为按权限点判断,界面就地更新,
// 不属于 Q12 所说的撤权,不要求重新登录;切换前后权限点本身的变化仍会按上面的并集比较提示。
// 不用 version:它包含目录与企业版本,改任意菜单名、角色名都会变化,会误弹重新登录。
const viewSignature = (v, inScope) =>
JSON.stringify([
(v.perms || []).filter(inScope).sort(),
(v.menus || [])
.filter((m) => inScope(m.code))
.map((m) => `${m.code}:${m.visible ? 1 : 0}`)
.sort(),
Object.entries(v.scopes || {})
.filter(([code]) => inScope(code))
.map(
([code, sc]) =>
`${code}:${sc?.all ? 1 : 0}:${sc?.depts ? 1 : 0}:${sc?.self ? 1 : 0}`,
)
.sort(),
]);
// 有效内容变化且涉及已切换模块:权限确实影响到页面行为,需要重新登录
const changedUnderEnforce = (prev, next) => {
if (!prev || !next) return false;
// 用户、企业或登录域不同都是换了会话(如个人会话改用企业入口登录),不是权限变更
if (
prev.user_id !== next.user_id ||
prev.org_id !== next.org_id ||
prev.domain !== next.domain ||
(prev.session_domain || '') !== (next.session_domain || '')
) {
return false;
}
const modules = new Set([
...(prev.enforced_modules || []),
...(next.enforced_modules || []),
]);
if (modules.size === 0) return false;
const moduleOf = { ...(prev.module_of || {}), ...(next.module_of || {}) };
const inScope = (code) => modules.has(moduleOf[code]);
return viewSignature(prev, inScope) !== viewSignature(next, inScope);
};
// 视图是否涉及已切换模块(需要高频刷新以及时发现权限变更;代理会话另由调用方判断)
const isActiveView = (v) => !!v && (v.enforced_modules || []).length > 0;
// 内容相同的视图不重新写入状态,避免每次刷新都让订阅方(企业中心等)重渲染
const sameView = (a, b) => {
if (a === b) return true;
if (!a || !b) return false;
try {
return JSON.stringify(a) === JSON.stringify(b);
} catch {
return false;
}
};
export const AuthzProvider = ({ children }) => {
const { t } = useTranslation();
const [userState, userDispatch] = useContext(UserContext);
const userId = userState?.user?.id || 0;
const location = useLocation();
const [platform, setPlatform] = useState(null);
const [org, setOrg] = useState(null);
// 最近一次企业视图加载(无论成败)对应的 currentOrgViewKey;未加载过为 null
const [orgLoadedKey, setOrgLoadedKey] = useState(null);
// 平台视图已为哪个用户加载过(成败均算);路由守卫据此等待视图到达,避免先按旧判断误拦
const [platformLoadedFor, setPlatformLoadedFor] = useState(0);
// 最近一次平台视图加载是否失败(配合 platformLoadedFor 使用):路由守卫据此显示可重试提示
const [platformLoadFailed, setPlatformLoadFailed] = useState(false);
const prevRef = useRef({ platform: null, org: null });
const promptedRef = useRef(false);
// 已弹出的"权限已变更"提示实例:其他标签页换了会话时关闭它
const modalRef = useRef(null);
// 最近一次开始拉取视图的时间,用于 focus 刷新节流
const lastFetchRef = useRef(0);
// 最近一次加载是否有视图失败:失败后按高频刷新重试,否则已切换企业首次加载失败时会按旧判断渲染最长 10 分钟
const failedRef = useRef(false);
// 最新的 reload:storage 事件处理里主动重新加载(事件处理只注册一次)
const reloadRef = useRef(null);
// 企业会话(企业域登录、或仅企业资源账号)重新登录回 /org/login,否则回 /login
const orgOnlyRef = useRef(false);
orgOnlyRef.current = userState?.user?.org_only_mode === true;
const onOrgPage = location.pathname.startsWith('/org');
const orgKey = onOrgPage ? currentOrgViewKey() : '';
const promptRelogin = useCallback(() => {
if (promptedRef.current) return;
promptedRef.current = true;
// 只能点"重新登录":不提供关闭按钮,点遮罩与按 Esc 都不关闭
modalRef.current = Modal.warning({
title: t('权限已变更'),
content: t('你的权限已变更,请重新登录。'),
okText: t('重新登录'),
centered: true,
closable: false,
keyboard: false,
mask: { closable: false },
onOk: async () => {
modalRef.current = null;
// 先判断会话域,再登出清理(清理会移除企业登录标记)
// 以后端返回的登录域为准;老版本后端没有该字段时退回本地标记
const view = prevRef.current.org || prevRef.current.platform;
const orgSession = view?.session_domain
? view.session_domain === 'org'
: isOrgLoginSession() || orgOnlyRef.current;
const target = orgSession ? '/org/login' : '/login';
try {
await API.get('/api/user/logout', {
skipErrorHandler: true,
disableDuplicate: true,
});
} catch {
// 登出失败也继续清理本地数据并跳转登录页
}
clearUserData();
userDispatch({ type: 'logout' });
window.location.href = target;
},
});
}, [t, userDispatch]);
const reload = useCallback(async () => {
lastFetchRef.current = Date.now();
const loadingKey = currentOrgViewKey();
if (!userId) {
setPlatform(null);
setOrg(null);
prevRef.current = { platform: null, org: null };
setOrgLoadedKey(loadingKey);
setPlatformLoadedFor(0);
setPlatformLoadFailed(false);
return;
}
const headers = onOrgPage ? orgHeaders() : null;
const [pr, or] = await Promise.all([
fetchView(undefined),
headers ? fetchView(headers) : Promise.resolve(null),
]);
const unauthorized = pr === UNAUTHORIZED || or === UNAUTHORIZED;
const p = pr === UNAUTHORIZED ? null : pr;
const o = or === UNAUTHORIZED ? null : or;
if (p) {
if (changedUnderEnforce(prevRef.current.platform, p)) promptRelogin();
const same = sameView(prevRef.current.platform, p);
prevRef.current.platform = p;
if (!same) setPlatform(p);
} else {
// 加载失败:保留上一份视图作比较基准;不属于当前用户的旧视图不能再用
const kept = prevRef.current.platform;
if (kept && kept.user_id !== userId) {
prevRef.current.platform = null;
setPlatform(null);
}
}
setPlatformLoadFailed(!p);
setPlatformLoadedFor(userId);
failedRef.current = !unauthorized && (!p || (!!headers && !o));
if (!headers) {
prevRef.current.org = null;
setOrg(null);
// 不在企业页时并未加载企业视图,不能标记为已就绪(否则进入企业中心时会按旧判断先行守卫)
setOrgLoadedKey(onOrgPage ? loadingKey : null);
return;
}
if (o) {
if (changedUnderEnforce(prevRef.current.org, o)) promptRelogin();
const same = sameView(prevRef.current.org, o);
prevRef.current.org = o;
if (!same) setOrg(o);
} else {
// 加载失败:保留上一份视图作比较基准;只有仍属于当前用户与当前企业时才继续使用
const kept = prevRef.current.org;
if (
kept &&
(kept.user_id !== userId || kept.org_id !== getCurrentOrgId())
) {
prevRef.current.org = null;
setOrg(null);
}
}
setOrgLoadedKey(loadingKey);
}, [userId, onOrgPage, promptRelogin]);
// 换账号、换企业(含进入 / 退出代理)都要重新加载:企业键不参与 reload 本身的计算,单独作为触发条件
useEffect(() => {
reloadRef.current = reload;
}, [reload]);
useEffect(() => {
reload();
}, [reload, orgKey]);
// 换账号(含登出):允许对新账号重新提示
useEffect(() => {
promptedRef.current = false;
}, [userId]);
// 离开企业中心:清除本标签页的"代理已失效"标记,之后再进入 /org 按正常企业上下文解析
useEffect(() => {
if (!onOrgPage) clearProxyExpired();
}, [onOrgPage]);
// 多标签页:其他标签页重新登录或登出(localStorage 用户数据变化)时,关闭本页已弹出的提示,
// 避免在旧标签页点"重新登录"把新会话注销;同时丢弃旧的比较基准,下一次加载按新会话重新建立
useEffect(() => {
// 只看用户身份:登出(键被删)或换成另一个用户才算换会话;额度等字段刷新不算,
// 否则会关掉仍然有效的提示并丢弃比较基准,本标签页就再也不会提示了
const userIdOf = (raw) => {
try {
return raw ? JSON.parse(raw)?.id || 0 : 0;
} catch {
return 0;
}
};
const onStorage = (e) => {
if (
e.key !== USER_STORAGE_KEY &&
e.key !== ORG_LOGIN_SESSION_KEY &&
e.key !== null
) {
return;
}
// 企业登录标记变化:同一用户在其他标签页改用企业入口(或个人入口)登录,登录域变了,按换会话处理
if (
e.key === USER_STORAGE_KEY &&
e.newValue !== null &&
userIdOf(e.oldValue) === userIdOf(e.newValue)
) {
return;
}
if (modalRef.current) {
modalRef.current.destroy();
modalRef.current = null;
}
promptedRef.current = false;
prevRef.current = { platform: null, org: null };
// 立即按新会话重新加载:本标签页的 UserContext 不跨标签同步,不会自己触发加载;
// 清空基准后也不再算"有已切换模块",不主动加载就要等最长 10 分钟
if (reloadRef.current) reloadRef.current();
};
window.addEventListener('storage', onStorage);
return () => window.removeEventListener('storage', onStorage);
}, []);
useEffect(() => {
if (!userId) return undefined;
const active = () =>
failedRef.current ||
isActiveView(prevRef.current.platform) ||
isActiveView(prevRef.current.org) ||
!!getProxySession();
const timer = setInterval(() => {
if (
active() ||
Date.now() - lastFetchRef.current >= IDLE_REFRESH_MS - 1000
) {
reload();
}
}, REFRESH_MS);
const onFocus = () => {
const throttle = active() ? FOCUS_THROTTLE_MS : IDLE_FOCUS_THROTTLE_MS;
if (Date.now() - lastFetchRef.current < throttle) return;
reload();
};
window.addEventListener('focus', onFocus);
return () => {
clearInterval(timer);
window.removeEventListener('focus', onFocus);
};
}, [userId, reload]);
const value = useMemo(
() => ({
platform,
org,
orgLoadedKey,
platformLoadedFor,
platformLoadFailed,
reload,
}),
[
platform,
org,
orgLoadedKey,
platformLoadedFor,
platformLoadFailed,
reload,
],
);
return (
<AuthzContext.Provider value={value}>{children}</AuthzContext.Provider>
);
};
+13 -2
View File
@@ -1,5 +1,4 @@
# Copyright and License Notice /*
Copyright (C) 2025 QuantumNous Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
@@ -16,3 +15,15 @@ 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/>. 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 { usePerm } from './usePerm';
// <Perm code='org.member.edit' legacy={isAdmin} fallback={null}>…</Perm>
const Perm = ({ code, legacy, fallback = null, children }) => {
const allowed = usePerm(code, legacy);
return <>{allowed ? children : fallback}</>;
};
export default Perm;
+191
View File
@@ -0,0 +1,191 @@
/*
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, { useContext, useState } from 'react';
import { Navigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button, Result } from 'antd';
import Loading from '../components/common/ui/Loading';
import { AdminRoute, PrivateRoute, RootRoute } from '../helpers/auth';
import { isRoot } from '../helpers/utils';
import { UserContext } from '../context/User';
import { AuthzContext } from './AuthzProvider';
import { usePerm } from './usePerm';
// 平台视图加载失败:给出可重试的提示,而不是按旧判断直接跳 /forbidden
const LoadFailed = ({ reload }) => {
const { t } = useTranslation();
const [retrying, setRetrying] = useState(false);
const retry = async () => {
setRetrying(true);
try {
await reload();
} finally {
setRetrying(false);
}
};
return (
<Result
status='warning'
title={t('权限信息加载失败')}
subTitle={t('请检查网络后重试')}
extra={
<Button type='primary' loading={retrying} onClick={retry}>
{t('重试')}
</Button>
}
/>
);
};
// 会话已在其他标签页变更:刷新页面按新会话重新加载
const SessionChanged = () => {
const { t } = useTranslation();
return (
<Result
status='info'
title={t('登录状态已变化')}
subTitle={t('你已在其他页面切换了账号,请刷新页面')}
extra={
<Button type='primary' onClick={() => window.location.reload()}>
{t('刷新页面')}
</Button>
}
/>
);
};
// 平台视图是否已就绪。返回 null 表示就绪,否则返回等待期间应显示的内容。
// 就绪:已有属于当前用户的平台视图(之后的刷新失败不影响);否则本用户的加载已结束且失败时提示重试。
const useViewPending = () => {
const [userState] = useContext(UserContext);
const { platform, platformLoadedFor, platformLoadFailed, reload } =
useContext(AuthzContext);
const userId = userState?.user?.id || 0;
const viewReady = !!platform && platform.user_id === userId;
if (!userId || viewReady) return { pending: null, failed: false };
if (platformLoadedFor === userId && platformLoadFailed) {
return { pending: <LoadFailed reload={reload} />, failed: true };
}
// 视图已加载但属于另一个用户:其他标签页换了账号,本页的用户信息已过期,提示刷新而不是一直转圈
if (platformLoadedFor === userId && platform) {
return { pending: <SessionChanged />, failed: false };
}
return { pending: <Loading />, failed: false };
};
// 按平台权限点守卫的路由:判断与侧边栏一致(usePerm(code, isRoot())),
// 平台视图到达前显示加载中,加载失败显示可重试提示,无权限时与其它守卫一样跳 /forbidden。
const PermGate = ({ code, children }) => {
const allowed = usePerm(code, isRoot());
const { pending } = useViewPending();
if (pending) return pending;
if (!allowed) return <Navigate to='/forbidden' replace />;
return children;
};
const PermRoute = ({ code, children }) => (
<PrivateRoute>
<PermGate code={code}>{children}</PermGate>
</PrivateRoute>
);
// 原有守卫:legacy='root' 为 RootRoute,否则为 AdminRoute(permission 为系统设置页签委派校验)
const LegacyRoute = ({ legacy, permission, children }) =>
legacy === 'root' ? (
<RootRoute>{children}</RootRoute>
) : (
<AdminRoute permission={permission}>{children}</AdminRoute>
);
// 控制台路由守卫(新旧双路径):code 所属模块已切到新体系时按权限点判断(持有权限点的非管理员也能进入,
// 没有权限点的管理员进不去);未切换时完全沿用原有守卫(AdminRoute / RootRoute)。
// 用法:<ConsoleRoute code='platform.channel'>、<ConsoleRoute code='platform.commission' legacy='root'>、
// <ConsoleRoute code='platform.setting.website_setting' permission='website-setting'>
export const ConsoleRoute = ({
code,
legacy = 'admin',
permission,
children,
}) => {
const [userState] = useContext(UserContext);
const { platform } = useContext(AuthzContext);
const { pending, failed } = useViewPending();
const user = userState?.user;
const legacyRoute = (
<LegacyRoute legacy={legacy} permission={permission}>
{children}
</LegacyRoute>
);
// 未登录或登录态校验中:交给原有守卫(跳登录页或显示加载中)
if (!user) return legacyRoute;
if (pending) {
// 视图加载失败时无从得知模块是否已切换:原判断会放行的人仍按原有守卫进入(接口权限由后端校验),
// 避免权限接口故障把管理员挡在控制台外;其余人显示可重试提示
const legacyRole = legacy === 'root' ? 100 : 10;
if (failed && typeof user.role === 'number' && user.role >= legacyRole) {
return legacyRoute;
}
return pending;
}
const mod = platform.moduleOf[code];
if (!mod || !platform.enforcedSet.has(mod)) return legacyRoute;
if (!platform.permSet.has(code)) return <Navigate to='/forbidden' replace />;
return children;
};
// 控制台入口 /console:原行为是管理员进运营看板。运营看板模块已切换且当前用户没有该菜单时
// (含持有其他平台菜单的非管理员),改进第一个已切换且持有的控制台菜单;都没有时按原有守卫处理。
export const ConsoleIndexRoute = () => {
const [userState] = useContext(UserContext);
const { platform } = useContext(AuthzContext);
const { pending, failed } = useViewPending();
const user = userState?.user;
const legacyRoute = (
<AdminRoute>
<Navigate to='/console/analytics' replace />
</AdminRoute>
);
if (!user) return legacyRoute;
if (pending) {
if (failed && typeof user.role === 'number' && user.role >= 10) {
return legacyRoute;
}
return pending;
}
const enforced = (code) => platform.enforcedSet.has(platform.moduleOf[code]);
const analyticsEnforced = enforced('platform.analytics');
const canAnalytics = analyticsEnforced
? platform.permSet.has('platform.analytics')
: typeof user.role === 'number' && user.role >= 10;
if (canAnalytics) return <Navigate to='/console/analytics' replace />;
// view.menus 已按 sort 排好,且只含当前用户持有的节点
const first = (platform.menus || []).find(
(m) =>
m.type === 'menu' &&
m.visible &&
typeof m.route === 'string' &&
m.route.startsWith('/console/') &&
enforced(m.code),
);
if (first) return <Navigate to={first.route} replace />;
return legacyRoute;
};
export default PermRoute;
+34
View File
@@ -0,0 +1,34 @@
/*
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 { AuthzContext, AuthzProvider } from './AuthzProvider';
export {
usePerm,
useAnyPerm,
useAuthzView,
useAuthzReload,
useOrgViewReady,
} from './usePerm';
export { default as Perm } from './Perm';
export {
default as PermRoute,
ConsoleRoute,
ConsoleIndexRoute,
} from './PermRoute';
export { checkPerm, checkAnyPerm, buildMenuTree } from './permLogic';
+70
View File
@@ -0,0 +1,70 @@
/*
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
*/
// 权限判断的纯逻辑(权限重构 §7.1 新旧双路径),与 React 无关,便于单测。
// view 为 /api/authz/me 的返回;legacy 为旧判断(布尔或返回布尔的函数)。
export function normalizeView(data) {
if (!data) return null;
return {
...data,
permSet: new Set(data.perms || []),
enforcedSet: new Set(data.enforced_modules || []),
moduleOf: data.module_of || {},
};
}
const evalLegacy = (legacy) =>
typeof legacy === 'function' ? !!legacy() : !!legacy;
// 模块已切到新体系(enforced):以权限点为准;否则走旧判断。未提供旧判断时按权限点判断。
// view 尚未加载:有旧判断走旧判断,否则不放行。
export function checkPerm(view, code, legacy) {
if (!view) return legacy === undefined ? false : evalLegacy(legacy);
const mod = view.moduleOf[code];
if (mod && view.enforcedSet.has(mod)) return view.permSet.has(code);
if (legacy === undefined) return view.permSet.has(code);
return evalLegacy(legacy);
}
// 是否持有任一权限点(同样按模块逐个走新旧路径)。
export function checkAnyPerm(view, codes, legacy) {
return codes.some((c) => checkPerm(view, c, legacy));
}
// 视图对应的域:org.* 权限点看企业视图,其余看平台视图。
export function viewForCode(views, code) {
return code.startsWith('org.') ? views.org : views.platform;
}
// 菜单树:按 parent 组装,同级按 sort;只保留 visible 的节点。
export function buildMenuTree(menus) {
const byParent = new Map();
for (const m of menus || []) {
if (!m.visible) continue;
const list = byParent.get(m.parent || '') || [];
list.push(m);
byParent.set(m.parent || '', list);
}
const build = (parent) =>
(byParent.get(parent) || [])
.sort((a, b) => a.sort - b.sort || a.code.localeCompare(b.code))
.map((m) => ({ ...m, children: build(m.code) }));
return build('');
}
+82
View File
@@ -0,0 +1,82 @@
/*
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 test from 'node:test';
import assert from 'node:assert/strict';
import {
normalizeView,
checkPerm,
checkAnyPerm,
buildMenuTree,
} from './permLogic.js';
const view = normalizeView({
perms: ['org.member', 'org.member.query'],
enforced_modules: ['member'],
module_of: {
'org.member': 'member',
'org.member.query': 'member',
'org.member.edit': 'member',
'org.dept.query': 'dept',
},
});
test('enforced module follows perms, ignoring the legacy check', () => {
assert.equal(checkPerm(view, 'org.member.query', false), true);
assert.equal(checkPerm(view, 'org.member.edit', true), false);
});
test('non-enforced module follows the legacy check', () => {
assert.equal(checkPerm(view, 'org.dept.query', true), true);
assert.equal(
checkPerm(view, 'org.dept.query', () => false),
false,
);
assert.equal(checkPerm(view, 'org.dept.query'), false);
});
test('view not loaded yet', () => {
assert.equal(checkPerm(null, 'org.member.query'), false);
assert.equal(checkPerm(null, 'org.member.query', true), true);
});
test('any of several perms', () => {
assert.equal(
checkAnyPerm(view, ['org.member.edit', 'org.member.query']),
true,
);
assert.equal(checkAnyPerm(view, ['org.member.edit']), false);
});
test('menu tree keeps visible nodes ordered by sort', () => {
const tree = buildMenuTree([
{ code: 'b', parent: '', sort: 20, visible: true },
{ code: 'a', parent: '', sort: 10, visible: true },
{ code: 'a.x', parent: 'a', sort: 10, visible: true },
{ code: 'a.h', parent: 'a', sort: 5, visible: false },
]);
assert.deepEqual(
tree.map((n) => n.code),
['a', 'b'],
);
assert.deepEqual(
tree[0].children.map((n) => n.code),
['a.x'],
);
});
+59
View File
@@ -0,0 +1,59 @@
/*
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 { useContext, useEffect } from 'react';
import { AuthzContext, currentOrgViewKey } from './AuthzProvider';
import { checkPerm, checkAnyPerm, viewForCode } from './permLogic';
// usePerm(code, legacy):模块已切到新体系时按权限点判断,否则按 legacy(旧判断)判断。
export function usePerm(code, legacy) {
const ctx = useContext(AuthzContext);
return checkPerm(viewForCode(ctx, code), code, legacy);
}
// useAnyPerm(codes, legacy):持有其中任一权限点。
export function useAnyPerm(codes, legacy) {
const ctx = useContext(AuthzContext);
if (!codes.length) return false;
return checkAnyPerm(viewForCode(ctx, codes[0]), codes, legacy);
}
// useAuthzView(domain):'platform' | 'org' 的原始视图(菜单树渲染等)。
export function useAuthzView(domain) {
const ctx = useContext(AuthzContext);
return domain === 'org' ? ctx.org : ctx.platform;
}
export function useAuthzReload() {
return useContext(AuthzContext).reload;
}
// useOrgViewReady():企业视图是否已按当前企业(含代理会话)加载过(成败均算)。
// 企业中心在它就绪前不做路由守卫,避免新体系下持有菜单的人在视图到达前被旧判断重定向走。
// 当前企业刚由解析器写入、Provider 尚未感知时主动触发一次加载。
export function useOrgViewReady() {
const ctx = useContext(AuthzContext);
const key = currentOrgViewKey();
const ready = ctx.orgLoadedKey === key;
const { reload } = ctx;
useEffect(() => {
if (!ready) reload();
}, [ready, key, reload]);
return ready;
}
@@ -180,6 +180,7 @@ const DailyStatsTable = ({ data, title, icon, t, embedded = false }) => {
columns={columns} columns={columns}
dataSource={data || []} dataSource={data || []}
pagination={{ pagination={{
preservePage: true,
pageSize: 10, pageSize: 10,
showSizeChanger: true, showSizeChanger: true,
showTotal: (total) => t('共 {{total}} 条', { total, count: total }), showTotal: (total) => t('共 {{total}} 条', { total, count: total }),
+300
View File
@@ -0,0 +1,300 @@
import React, { useMemo, useState } from 'react';
import { Button, Empty, Input, Tag, Tree, theme } from 'antd';
import { useTranslation } from 'react-i18next';
import { Search } from '@/components/common/icons/ActionIcons';
// 权限授权树(平台角色、套餐、模板、企业角色共用)。nodes 为后端 GrantNode 列表:
// { code, parent, type: 'dir'|'menu'|'button', name, sort, sensitive, grantable }。
// value 为已勾选的权限编码数组,只会包含 grantable 的节点;grantable=false 的节点只作为祖先展示,不可勾选。
//
// 联动规则(PRD AC50 / AC62 / AC80):
// - 勾选一个节点 = 勾选它和它全部可选后代,并带上可选祖先(后端本来也会补齐祖先);
// - 取消一个节点 = 只取消它和它的后代,兄弟不受影响;祖先下已没有任何选中的后代时祖先一并取消;
// - 祖先的显示状态由"子树内可选节点是否全部选中"推导:全部选中为勾选,部分选中为半选。
// 半选的祖先只提交它自己的编码,不会把未选中的后代带上。
const TYPE_META = {
dir: { color: 'default', label: '目录' },
menu: { color: 'blue', label: '菜单' },
button: { color: 'green', label: '按钮' },
};
const bySort = (a, b) =>
(a.sort || 0) - (b.sort || 0) || a.code.localeCompare(b.code);
// 由扁平节点建索引:parent(父编码,根为 '')、children(已排序的子编码)、
// subtree(子树内可选的编码,含自身)、order(先序遍历的编码)。
export const buildPermIndex = (nodes) => {
const byCode = new Map();
for (const n of nodes || []) byCode.set(n.code, n);
const parent = new Map();
const childNodes = new Map();
for (const n of byCode.values()) {
// parent 不在列表里的节点当作根
const p =
n.parent && n.parent !== n.code && byCode.has(n.parent) ? n.parent : '';
parent.set(n.code, p);
const list = childNodes.get(p) || [];
list.push(n);
childNodes.set(p, list);
}
const children = new Map();
for (const [p, list] of childNodes) {
children.set(
p,
list.sort(bySort).map((n) => n.code),
);
}
const subtree = new Map();
const order = [];
const walk = (code) => {
order.push(code);
const own = byCode.get(code).grantable ? [code] : [];
for (const c of children.get(code) || []) own.push(...walk(c));
subtree.set(code, own);
return own;
};
for (const c of children.get('') || []) walk(c);
return { byCode, parent, children, subtree, order };
};
// 去掉树里不存在或不可授予的编码(提交它们会被后端拒绝)。
// 只认 subtree 里登记过的节点:父链成环而从根走不到的节点不参与勾选。
const selectableSet = (index, value) =>
new Set(
(value || []).filter(
(c) => index.subtree.has(c) && index.byCode.get(c).grantable === true,
),
);
// 可以提交给后端的勾选结果(已排序):保存前用它过一遍,避免带上树里没有的历史编码
export const selectablePerms = (index, value) =>
[...selectableSet(index, value)].sort();
// 各节点的显示状态:checked = 子树内可选节点全部选中;halfChecked = 部分选中
export const permCheckState = (index, value) => {
const set = selectableSet(index, value);
const checked = [];
const halfChecked = [];
for (const [code, list] of index.subtree) {
if (!list.length) continue;
let hit = 0;
for (const c of list) if (set.has(c)) hit += 1;
if (hit === list.length) checked.push(code);
else if (hit > 0) halfChecked.push(code);
}
return { checked, halfChecked };
};
// 点击一个节点后的新勾选结果(已排序)
export const togglePerm = (index, value, code) => {
const set = selectableSet(index, value);
const sub = index.subtree.get(code) || [];
if (!sub.length) return [...set].sort();
if (sub.every((c) => set.has(c))) {
for (const c of sub) set.delete(c);
for (let p = index.parent.get(code); p; p = index.parent.get(p)) {
if (index.subtree.get(p).some((c) => c !== p && set.has(c))) break;
set.delete(p);
}
} else {
for (const c of sub) set.add(c);
for (let p = index.parent.get(code); p; p = index.parent.get(p)) {
if (index.byCode.get(p).grantable) set.add(p);
}
}
return [...set].sort();
};
// 权限摘要:已选的菜单(附其下已选按钮数)与菜单、按钮总数。用于列表里的"权限摘要"列。
export const summarizePerms = (index, perms) => {
const set = selectableSet(index, perms);
const menus = [];
let buttonCount = 0;
for (const code of index.order) {
if (!set.has(code)) continue;
const n = index.byCode.get(code);
if (n.type === 'button') {
buttonCount += 1;
} else if (n.type === 'menu') {
const buttons = index.subtree
.get(code)
.filter(
(c) => set.has(c) && index.byCode.get(c).type === 'button',
).length;
menus.push({ code, name: n.name, buttons });
}
}
return { menus, menuCount: menus.length, buttonCount, total: set.size };
};
const expandableKeys = (index, keep) =>
index.order.filter(
(c) =>
(!keep || keep.has(c)) &&
(index.children.get(c) || []).some((k) => !keep || keep.has(k)),
);
// 搜索:保留命中的节点、它的祖先(定位用)和它的整棵子树(方便直接勾选下面的按钮)
const matchKeys = (index, keyword) => {
const kw = keyword.trim().toLowerCase();
if (!kw) return null;
const keep = new Set();
const addSubtree = (code) => {
keep.add(code);
for (const c of index.children.get(code) || []) addSubtree(c);
};
for (const code of index.order) {
const n = index.byCode.get(code);
if (
!(n.name || '').toLowerCase().includes(kw) &&
!code.toLowerCase().includes(kw)
)
continue;
addSubtree(code);
for (let p = index.parent.get(code); p; p = index.parent.get(p))
keep.add(p);
}
return keep;
};
/**
* @param {object} props
* @param {Array} props.nodes 后端 GrantNode 列表
* @param {string[]} [props.value] 已勾选的权限编码
* @param {(codes: string[]) => void} [props.onChange] 勾选变化,参数为排序后的编码数组
* @param {boolean} [props.disabled] 只读:不可勾选,仍可展开、收起与搜索
* @param {number|string} [props.height=480] 树区域的最大高度,超出滚动
* @param {boolean} [props.showToolbar=true] 是否显示搜索框与"全部展开 / 全部收起"
* @param {boolean} [props.defaultExpandAll=true] 初始是否全部展开(false 时只显示根级节点)
* @param {string} [props.className]
*/
const PermTree = ({
nodes,
value,
onChange,
disabled,
height = 480,
showToolbar = true,
defaultExpandAll = true,
className,
}) => {
const { t } = useTranslation();
const { token } = theme.useToken();
const index = useMemo(() => buildPermIndex(nodes), [nodes]);
const [keyword, setKeyword] = useState('');
// null = 尚未手动操作,按 defaultExpandAll 取初始值(节点异步到达后仍然生效)
const [expandedKeys, setExpandedKeys] = useState(null);
// 搜索期间单独记一份展开状态,清空搜索后回到原来的展开状态
const [searchExpandedKeys, setSearchExpandedKeys] = useState(null);
const keep = useMemo(() => matchKeys(index, keyword), [index, keyword]);
const allExpandable = useMemo(
() => expandableKeys(index, keep),
[index, keep],
);
const checkState = useMemo(
() => permCheckState(index, value),
[index, value],
);
const treeData = useMemo(() => {
const build = (parentCode) =>
(index.children.get(parentCode) || [])
.filter((code) => !keep || keep.has(code))
.map((code) => {
const n = index.byCode.get(code);
const meta = TYPE_META[n.type];
return {
key: code,
disableCheckbox: disabled || !n.grantable,
title: (
<span className='inline-flex flex-wrap items-center gap-1'>
<span>{n.name}</span>
{meta ? (
<Tag color={meta.color} style={{ marginInlineEnd: 0 }}>
{t(meta.label)}
</Tag>
) : null}
{n.sensitive ? (
<Tag color='error' style={{ marginInlineEnd: 0 }}>
{t('敏感')}
</Tag>
) : null}
</span>
),
children: build(code),
};
});
return build('');
}, [index, keep, disabled, t]);
const searching = keep !== null;
const currentExpanded = searching
? (searchExpandedKeys ?? allExpandable)
: (expandedKeys ?? (defaultExpandAll ? allExpandable : []));
const setCurrentExpanded = searching
? setSearchExpandedKeys
: setExpandedKeys;
return (
<div className={className}>
{showToolbar ? (
<div className='mb-2 flex flex-wrap items-center gap-2'>
<Input
allowClear
value={keyword}
prefix={<Search size={14} />}
placeholder={t('搜索权限')}
aria-label={t('搜索权限')}
style={{ flex: '1 1 180px', minWidth: 0 }}
onChange={(e) => {
setKeyword(e.target.value);
// 每次改关键字都重新展开全部命中路径
setSearchExpandedKeys(null);
}}
/>
<Button onClick={() => setCurrentExpanded(allExpandable)}>
{t('全部展开')}
</Button>
<Button onClick={() => setCurrentExpanded([])}>
{t('全部收起')}
</Button>
</div>
) : null}
<div
style={{
maxHeight: height,
overflow: 'auto',
padding: 8,
border: `1px solid ${token.colorBorderSecondary}`,
borderRadius: token.borderRadius,
}}
>
{treeData.length ? (
<Tree
checkable
// 联动与半选由本组件按"可选节点"自行计算;antd 自带的联动会把已保存的祖先当成全选
checkStrictly
selectable={false}
treeData={treeData}
checkedKeys={checkState}
expandedKeys={currentExpanded}
autoExpandParent={false}
onExpand={(keys) => setCurrentExpanded(keys)}
onCheck={(_, info) =>
onChange?.(togglePerm(index, value, info.node.key))
}
/>
) : (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={searching ? t('没有匹配的权限') : t('暂无数据')}
/>
)}
</div>
</div>
);
};
export default PermTree;
@@ -7,6 +7,7 @@ const pageTitles = {
'/user-center/key-management': '密钥管理', '/user-center/key-management': '密钥管理',
'/user-center/dashboard': '数据看板', '/user-center/dashboard': '数据看板',
'/user-center/usage-record': '使用记录', '/user-center/usage-record': '使用记录',
'/user-center/service-dashboard': '服务监控',
'/user-center/topup': '在线充值', '/user-center/topup': '在线充值',
'/user-center/settings': '个人设置', '/user-center/settings': '个人设置',
'/user-center/invite': '邀请有奖', '/user-center/invite': '邀请有奖',
@@ -0,0 +1,38 @@
import React, { useRef, useState } from 'react';
import { Modal } from '@/components/ui';
export default function TableActionModal({ onOk, ...props }) {
const [submitting, setSubmitting] = useState(false);
const cancelButton = useRef(null);
const pending = useRef(false);
const confirm = async () => {
if (pending.current) return;
pending.current = true;
setSubmitting(true);
try {
await onOk();
} catch {
// The request or page already reports the error.
} finally {
pending.current = false;
setSubmitting(false);
}
};
return (
<Modal
{...props}
okType='danger'
confirmLoading={submitting}
onOk={confirm}
onCancel={(event) => {
if (!pending.current) props.onCancel(event);
}}
afterOpenChange={(visible) => {
if (visible) cancelButton.current?.focus();
}}
cancelButtonProps={{ ref: cancelButton }}
/>
);
}
@@ -0,0 +1,76 @@
import React, { useRef, useState } from 'react';
import { Popconfirm } from 'antd';
export default function TableActionPopconfirm({
children,
content,
position,
onConfirm,
...props
}) {
const [open, setOpen] = useState(false);
const cancelButton = useRef(null);
const trigger = useRef(null);
const pending = useRef(false);
const [submitting, setSubmitting] = useState(false);
const confirm = (event) => {
if (pending.current) return;
pending.current = true;
setSubmitting(true);
void (async () => {
try {
if ((await onConfirm(event)) !== false) setOpen(false);
} catch {
// The request or page already reports the error.
} finally {
pending.current = false;
setSubmitting(false);
}
})();
};
const cancel = () => {
if (pending.current) return;
setOpen(false);
trigger.current?.focus();
};
const handleKeyDown = (event) => {
if (event.key === 'Escape') {
event.stopPropagation();
cancel();
}
};
return (
<Popconfirm
{...props}
open={open}
description={content ?? props.description}
placement={position ?? props.placement}
onOpenChange={(nextOpen) => {
if (pending.current) return;
if (nextOpen) trigger.current = document.activeElement;
setOpen(nextOpen);
}}
afterOpenChange={(visible) => {
if (visible) cancelButton.current?.focus();
}}
onConfirm={confirm}
onCancel={cancel}
cancelButtonProps={{
ref: cancelButton,
disabled: submitting,
onKeyDown: handleKeyDown,
}}
okButtonProps={{
danger: true,
loading: submitting,
onKeyDown: handleKeyDown,
}}
>
{children}
</Popconfirm>
);
}
@@ -0,0 +1,80 @@
import React from 'react';
import { Tag } from 'antd';
import './table-group-tags.css';
export const TABLE_GROUP_COLUMN_WIDTH = 148;
const groupColors = new Map([
['default', 'blue'],
['svip', 'red'],
['vip', 'yellow'],
['premium', 'red'],
['pro', 'yellow'],
]);
const standardGroupNames = new Set(['default', 'vip', 'svip']);
function displayGroupName(group) {
const name = group?.trim().toLowerCase();
return standardGroupNames.has(name) ? name : group;
}
export function TableGroupTag({ group, children, onClick }) {
return (
<Tag
color={groupColors.get(group?.trim().toLowerCase()) ?? 'default'}
variant='outlined'
onClick={onClick}
role={onClick ? 'button' : undefined}
tabIndex={onClick ? 0 : undefined}
onKeyDown={
onClick
? (event) => {
if (event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
event.stopPropagation();
if (!event.repeat) onClick(event);
}
: undefined
}
className='m-0'
>
{children ?? displayGroupName(group)}
</Tag>
);
}
export default function TableGroupTags({
groups,
empty = '-',
renderLabel,
onGroupClick,
}) {
const names = [
...new Set(
(Array.isArray(groups) ? groups : [groups])
.flatMap((value) => (typeof value === 'string' ? value.split(',') : []))
.map((name) => name.trim())
.filter(Boolean),
),
];
if (!names.length) return empty;
return (
<span className='table-group-tags'>
{names.map((name) => (
<TableGroupTag
key={name}
group={name}
onClick={
onGroupClick ? (event) => onGroupClick(name, event) : undefined
}
>
{standardGroupNames.has(name.toLowerCase())
? displayGroupName(name)
: renderLabel?.(name)}
</TableGroupTag>
))}
</span>
);
}
@@ -0,0 +1,20 @@
import React, { forwardRef } from 'react';
import { Switch } from 'antd';
import { useTranslation } from 'react-i18next';
export default forwardRef(function TableStatusSwitch(
{ checkedChildren, unCheckedChildren, 'aria-label': ariaLabel, ...props },
ref,
) {
const { t } = useTranslation();
return (
<Switch
{...props}
ref={ref}
size='small'
aria-label={ariaLabel ?? t('启用状态')}
checkedChildren={checkedChildren ?? t('启用')}
unCheckedChildren={unCheckedChildren ?? t('禁用')}
/>
);
});
@@ -0,0 +1,44 @@
import React, { useId, useState } from 'react';
import { Card } from 'antd';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import './usage-record-filter.css';
export function UsageRecordFilterContent({ children }) {
const { t } = useTranslation();
const isMobile = useIsMobile();
const [expanded, setExpanded] = useState(false);
const id = useId();
return (
<>
{isMobile && (
<Button
block
className='usage-record-mobile-toggle'
aria-expanded={expanded}
aria-controls={id}
onClick={() => setExpanded((open) => !open)}
>
{expanded ? t('隐藏操作项') : t('显示操作项')}
</Button>
)}
<div
className='usage-record-filter-content'
id={id}
hidden={isMobile && !expanded}
>
{children}
</div>
</>
);
}
export default function UsageRecordFilterCard({ children, className }) {
return (
<Card className={`usage-record-filter-card ${className}`}>
<UsageRecordFilterContent>{children}</UsageRecordFilterContent>
</Card>
);
}
@@ -0,0 +1,30 @@
import { Modal } from '@/components/ui';
export function confirmTableAction({ onOk, ...config }) {
let submitting = false;
const okButtonProps = { danger: true, ...config.okButtonProps };
const dialog = Modal.confirm({
...config,
okButtonProps,
onOk: (close) => {
if (submitting) return;
submitting = true;
dialog.update({
okButtonProps: { ...okButtonProps, loading: true },
});
void (async () => {
try {
if ((await onOk()) !== false) close();
} catch {
// The request or page already reports the error.
} finally {
submitting = false;
dialog.update({
okButtonProps: { ...okButtonProps, loading: false },
});
}
})();
},
});
return dialog;
}
@@ -0,0 +1,15 @@
const CHUNK_SIZE = 500;
export async function filterTableRows(items, matches, signal) {
const result = [];
for (let start = 0; start < items.length; start += CHUNK_SIZE) {
if (start > 0) await new Promise((resolve) => setTimeout(resolve, 0));
signal?.throwIfAborted();
const end = Math.min(items.length, start + CHUNK_SIZE);
for (let index = start; index < end; index++) {
if (matches(items[index])) result.push(items[index]);
}
}
signal?.throwIfAborted();
return result;
}
@@ -0,0 +1,79 @@
.table-filter-range {
min-width: 0;
}
.table-filter-range-popup .ant-picker-panel-container .ant-picker-presets {
min-width: 118px;
}
.table-filter-range-popup .table-filter-period-active {
color: var(--ant-color-primary, var(--brand-primary));
font-weight: 600;
}
@media (hover: none) and (pointer: coarse) {
.table-filter-range.ant-picker .ant-picker-clear {
opacity: 1;
pointer-events: auto;
}
.table-filter-range.ant-picker .ant-picker-suffix:not(:last-child) {
opacity: 0;
}
}
@media (max-width: 640px) {
.table-filter-range-popup
.ant-picker-panel-container
.ant-picker-panel-layout {
flex-direction: column;
max-width: calc(100vw - 16px);
}
.table-filter-range-popup .ant-picker-panel-container .ant-picker-presets {
max-width: none;
}
.table-filter-range-popup .ant-picker-panel-container .ant-picker-presets ul {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
height: auto;
border-inline-end: 0;
border-block-end: 1px solid var(--ant-color-split, var(--ui-color-border));
}
.table-filter-range-popup .ant-picker-panel-container .ant-picker-presets li {
margin-block: 0;
}
.table-filter-range-popup .ant-picker-panel-container .ant-picker-panels {
display: flex;
max-width: calc(100vw - 16px);
overflow-x: auto;
}
.table-filter-range-popup .ant-picker-datetime-panel .ant-picker-date-panel {
width: min(64vw, 272px);
min-width: 0;
}
.table-filter-range-popup .ant-picker-datetime-panel .ant-picker-content th,
.table-filter-range-popup .ant-picker-datetime-panel .ant-picker-content td {
width: auto;
}
.table-filter-range-popup
.ant-picker-datetime-panel
.ant-picker-time-panel-column {
width: min(10vw, 48px);
}
.table-filter-range-popup
.ant-picker-datetime-panel
.ant-picker-time-panel-cell-inner {
width: auto;
padding-inline: 4px;
}
}
@@ -0,0 +1,27 @@
.table-group-tags {
display: inline-flex;
align-items: center;
gap: 4px;
inline-size: 132px;
max-inline-size: 100%;
overflow-x: auto;
vertical-align: middle;
white-space: nowrap;
}
.table-group-tags > * {
flex: none;
}
.table-group-tags .table-group-tags {
inline-size: auto;
overflow: visible;
}
.table-group-tags > .ant-tag {
margin-inline-end: 0;
}
.table-group-tags > .ant-tag:focus-visible {
outline-offset: -2px;
}
@@ -0,0 +1,76 @@
.usage-record-filter-card.ant-card {
background: var(--surface-card);
}
.usage-record-mobile-toggle {
margin-bottom: 0;
}
.usage-record-mobile-toggle[aria-expanded='true'] {
margin-bottom: 12px;
}
/* 筛选:五列竖排标签表单,日期跨两列;重置/搜索右下 */
:where(.usage-record-filter-card) .usage-record-filter-grid {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
column-gap: 16px;
row-gap: 16px;
}
:where(.usage-record-filter-card)
.usage-record-filter-grid
.usage-record-filter-wide {
grid-column: span 2;
}
:where(.usage-record-filter-card) .usage-record-filter-form .ant-form-item {
margin-bottom: 0;
}
:where(.usage-record-filter-card)
.usage-record-filter-form
.ant-form-item-label {
padding-bottom: 8px;
}
:where(.usage-record-filter-card)
.usage-record-filter-form
.ant-form-item-label
> label {
height: 21px;
color: var(--text-secondary);
font-size: 13px;
}
:where(.usage-record-filter-card) .usage-record-filter-form .ant-picker,
:where(.usage-record-filter-card) .usage-record-filter-form .ant-select {
width: 100%;
}
:where(.usage-record-filter-card) .usage-record-filter-actions {
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 16px;
}
@media (max-width: 1200px) {
:where(.usage-record-filter-card) .usage-record-filter-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (max-width: 768px) {
:where(.usage-record-filter-card) .usage-record-filter-grid {
grid-template-columns: minmax(0, 1fr);
}
:where(.usage-record-filter-card)
.usage-record-filter-grid
.usage-record-filter-wide {
grid-column: auto;
}
:where(.usage-record-filter-card) .ant-picker-range {
padding-inline: 8px;
}
:where(.usage-record-filter-card) .ant-picker-range-separator {
padding-inline: 4px;
}
:where(.usage-record-filter-card)
.ant-picker-range
.ant-picker-input
> input {
font-size: 12px;
}
}
+7 -2
View File
@@ -4,12 +4,17 @@ import { Space, Tag, Typography, Popover } from '@/components/ui';
const { Text } = Typography; const { Text } = Typography;
// 通用渲染函数:限制项目数量显示,支持popover展开 // 通用渲染函数:限制项目数量显示,支持popover展开
export function renderLimitedItems({ items, renderItem, maxDisplay = 3 }) { export function renderLimitedItems({
items,
renderItem,
maxDisplay = 3,
wrap = true,
}) {
if (!items || items.length === 0) return '-'; if (!items || items.length === 0) return '-';
const displayItems = items.slice(0, maxDisplay); const displayItems = items.slice(0, maxDisplay);
const remainingItems = items.slice(maxDisplay); const remainingItems = items.slice(maxDisplay);
return ( return (
<Space spacing={1} wrap> <Space spacing={wrap ? 1 : 4} wrap={wrap}>
{displayItems.map((item, idx) => renderItem(item, idx))} {displayItems.map((item, idx) => renderItem(item, idx))}
{remainingItems.length > 0 && ( {remainingItems.length > 0 && (
<Popover <Popover
+31
View File
@@ -48,6 +48,37 @@ export const consolePages = [
hideHeading: true, hideHeading: true,
}, },
{ key: 'smart-router', title: '智能路由', description: 'smart-router' }, { key: 'smart-router', title: '智能路由', description: 'smart-router' },
// 权限管理(/console/authz/*):菜单 key 与侧栏、图标一致(authz-*)
{
key: 'authz/menus',
menuKey: 'authz-menus',
title: '菜单管理',
description: 'authz-menus',
},
{
key: 'authz/roles',
menuKey: 'authz-roles',
title: '平台角色',
description: 'authz-roles',
},
{
key: 'authz/packages',
menuKey: 'authz-packages',
title: '功能套餐',
description: 'authz-packages',
},
{
key: 'authz/templates',
menuKey: 'authz-templates',
title: '角色模板',
description: 'authz-templates',
},
{
key: 'authz/mode',
menuKey: 'authz-mode',
title: '运行模式',
description: 'authz-mode',
},
{ key: 'partner', title: '合作伙伴', description: 'partner' }, { key: 'partner', title: '合作伙伴', description: 'partner' },
{ {
key: 'skill-platform', key: 'skill-platform',
+27 -10
View File
@@ -59,6 +59,7 @@
.console-page:is( .console-page:is(
[data-console-page='channel'], [data-console-page='channel'],
[data-console-page='redemption'],
[data-console-page='models'], [data-console-page='models'],
[data-console-page='user'], [data-console-page='user'],
[data-console-page='organizations'], [data-console-page='organizations'],
@@ -73,6 +74,17 @@
font-weight: 400; font-weight: 400;
} }
.console-page:is(
[data-console-page='channel'],
[data-console-page='redemption']
)
.console-table.ant-table-wrapper
.ant-table-thead
> tr
> th {
color: var(--console-text);
}
.console-model-drawer .ant-drawer-title > .ant-space { .console-model-drawer .ant-drawer-title > .ant-space {
align-items: center; align-items: center;
} }
@@ -86,7 +98,8 @@
} }
.console-model-section, .console-model-section,
.console-channel-section { .console-channel-section,
.console-user-section {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 5px; gap: 5px;
@@ -94,12 +107,14 @@
} }
.console-model-section .ant-avatar, .console-model-section .ant-avatar,
.console-channel-section .ant-avatar { .console-channel-section .ant-avatar,
.console-user-section .ant-avatar {
flex-shrink: 0; flex-shrink: 0;
margin: 0; margin: 0;
} }
.console-channel-sections > div + div { .console-channel-sections > div + div,
.console-user-sections > .ant-card + .ant-card {
margin-top: 10px; margin-top: 10px;
} }
@@ -107,13 +122,13 @@
margin-bottom: 0; margin-bottom: 0;
} }
.console-channel-section .ant-avatar svg { .console-user-section-description {
display: block; color: var(--console-muted);
width: 16px; font-size: 12px;
height: 16px;
} }
.console-channel-footer .ant-btn { .console-channel-footer .ant-btn,
.console-user-footer .ant-btn {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
@@ -133,7 +148,8 @@
} }
.console-overlay .console-model-footer, .console-overlay .console-model-footer,
.console-overlay .console-channel-footer { .console-overlay .console-channel-footer,
.console-overlay .console-user-footer {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: flex-end; justify-content: flex-end;
@@ -153,7 +169,8 @@
} }
} }
.console-model-drawer .console-model-editor-header .ant-drawer-title, .console-model-drawer .console-model-editor-header .ant-drawer-title,
.console-channel-drawer .console-channel-editor-header .ant-drawer-title { .console-channel-drawer .console-channel-editor-header .ant-drawer-title,
.console-user-drawer .console-user-editor-header .ant-drawer-title {
text-align: start; text-align: start;
} }
@@ -9,6 +9,7 @@ import { useNavigate } from 'react-router-dom';
import { ERROR_ACTIONS } from '../../../helpers/creationError'; import { ERROR_ACTIONS } from '../../../helpers/creationError';
import { copy, renderQuota, showSuccess } from '../../../helpers'; import { copy, renderQuota, showSuccess } from '../../../helpers';
import { useIsMobile } from '../../../hooks/common/useIsMobile'; import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { useEffectEvent } from '../../../hooks/common/useEffectEvent';
import { adapterOf } from '../../../hooks/creation/creationForm'; import { adapterOf } from '../../../hooks/creation/creationForm';
import { import {
elapsedSeconds, elapsedSeconds,
@@ -101,24 +102,18 @@ const WorkDetailDrawer = ({
}, [taskId]); }, [taskId]);
// 打开时拉取一次详情(快照 / 播放地址 / regenerate_supported) // 打开时拉取一次详情(快照 / 播放地址 / regenerate_supported)
const fetchedRef = useRef(''); const loadDetail = useEffectEvent(() => fetchDetail(task));
useEffect(() => { useEffect(() => {
if (!visible || !task || fetchedRef.current === task.id) return; if (!visible || !taskId) return;
fetchedRef.current = task.id;
let alive = true; let alive = true;
setLoadingDetail(true); setLoadingDetail(true);
fetchDetail(task).finally(() => { loadDetail().finally(() => {
if (alive) setLoadingDetail(false); if (alive) setLoadingDetail(false);
}); });
return () => { return () => {
alive = false; alive = false;
}; };
// 只按作品 id 触发 }, [visible, taskId, loadDetail]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [visible, taskId]);
useEffect(() => {
if (!visible) fetchedRef.current = '';
}, [visible]);
if (!task) return null; if (!task) return null;
+115 -10
View File
@@ -31,6 +31,7 @@ import {
} from '../smart-router/api'; } from '../smart-router/api';
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 { useAuthzView, usePerm } from '../../authz';
const routerMap = { const routerMap = {
home: '/', home: '/',
@@ -78,6 +79,28 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
const showSkeleton = useMinimumLoadingTime(sidebarLoading, 200); const showSkeleton = useMinimumLoadingTime(sidebarLoading, 200);
// 权限管理分组:模块切到新体系后按权限点判断,切换前只有 root 可见(legacy = isRoot())
const canAuthzMenu = usePerm('platform.authz.menu.query', isRoot());
const canAuthzRole = usePerm('platform.authz.role.query', isRoot());
const canAuthzPackage = usePerm('platform.authz.package.query', isRoot());
const canAuthzTemplate = usePerm('platform.authz.template.query', isRoot());
// 新旧双路径(与路由守卫 ConsoleRoute 同口径):菜单所属模块已切到新体系时按权限点决定是否显示,
// 返回 true / false;未切换(或权限视图未到达)返回 null,调用方沿用原判断。
// 菜单管理里把菜单设为不显示时(visible=false)同样隐藏。
const platformView = useAuthzView('platform');
const permVisible = useMemo(() => {
if (!platformView) return () => null;
const hidden = new Set(
(platformView.menus || []).filter((m) => !m.visible).map((m) => m.code),
);
return (code) => {
const mod = code ? platformView.moduleOf[code] : '';
if (!mod || !platformView.enforcedSet.has(mod)) return null;
return platformView.permSet.has(code) && !hidden.has(code);
};
}, [platformView]);
const [selectedKeys, setSelectedKeys] = useState(['home']); const [selectedKeys, setSelectedKeys] = useState(['home']);
const navigationRef = useRef(null); const navigationRef = useRef(null);
// 平台关闭智能路由后,仍有生效中出境同意的普通用户保留入口以便撤回(§9.5,与企业"仅授权模式"同口径) // 平台关闭智能路由后,仍有生效中出境同意的普通用户保留入口以便撤回(§9.5,与企业"仅授权模式"同口径)
@@ -125,23 +148,27 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
text: t('使用日志'), text: t('使用日志'),
itemKey: 'log', itemKey: 'log',
to: '/log', to: '/log',
perm: 'platform.log',
}, },
{ {
text: t('绘图日志'), text: t('绘图日志'),
itemKey: 'midjourney', itemKey: 'midjourney',
to: '/midjourney', to: '/midjourney',
perm: 'platform.drawing_log',
className: drawingFlag === 'true' ? '' : 'tableHiddle', className: drawingFlag === 'true' ? '' : 'tableHiddle',
}, },
{ {
text: t('任务日志'), text: t('任务日志'),
itemKey: 'task', itemKey: 'task',
to: '/task', to: '/task',
perm: 'platform.task_log',
className: taskFlag === 'true' ? '' : 'tableHiddle', className: taskFlag === 'true' ? '' : 'tableHiddle',
}, },
{ {
text: t('监控中心'), text: t('监控中心'),
itemKey: 'monitor', itemKey: 'monitor',
to: '/monitor', to: '/monitor',
perm: 'platform.monitor',
}, },
{ {
// 智能路由:已登记在 sidebarModules 注册表(console.smart-router),管理员可隐藏 // 智能路由:已登记在 sidebarModules 注册表(console.smart-router),管理员可隐藏
@@ -163,7 +190,8 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
) )
return false; return false;
const configVisible = isModuleVisible('console', item.itemKey); const configVisible = isModuleVisible('console', item.itemKey);
return configVisible; // 已切换模块:还须持有对应菜单权限点
return configVisible && permVisible(item.perm) !== false;
}); });
return filteredItems; return filteredItems;
@@ -175,6 +203,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
taskFlag, taskFlag,
t, t,
isModuleVisible, isModuleVisible,
permVisible,
]); ]);
const financeItems = useMemo(() => { const financeItems = useMemo(() => {
@@ -183,6 +212,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
text: t('钱包管理'), text: t('钱包管理'),
itemKey: 'topup', itemKey: 'topup',
to: '/topup', to: '/topup',
perm: 'platform.topup',
}, },
{ {
text: t('个人设置'), text: t('个人设置'),
@@ -198,7 +228,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
if (isMiniProgramWebView() && isMiniProgramPaymentPath(item.to)) { if (isMiniProgramWebView() && isMiniProgramPaymentPath(item.to)) {
return false; return false;
} }
return configVisible; return configVisible && permVisible(item.perm) !== false;
}); });
// 与顶栏和伙伴页面共用新版伙伴权限判断,避免无权限账号误入。 // 与顶栏和伙伴页面共用新版伙伴权限判断,避免无权限账号误入。
@@ -210,18 +240,20 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
} }
return filteredItems; return filteredItems;
}, [t, isModuleVisible, showPartnerWorkspace]); }, [t, isModuleVisible, showPartnerWorkspace, permVisible]);
const adminItems = useMemo(() => { const adminItems = useMemo(() => {
const items = [ const items = [
{ {
text: t('运营看板'), text: t('运营看板'),
itemKey: 'analytics', itemKey: 'analytics',
perm: 'platform.analytics',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('分佣管理'), text: t('分佣管理'),
itemKey: 'commission', itemKey: 'commission',
perm: 'platform.commission',
items: [ items: [
{ text: t('分佣工作台'), itemKey: 'commission-overview' }, { text: t('分佣工作台'), itemKey: 'commission-overview' },
{ text: t('合作伙伴'), itemKey: 'commission-partners' }, { text: t('合作伙伴'), itemKey: 'commission-partners' },
@@ -237,81 +269,109 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
{ {
text: t('渠道管理'), text: t('渠道管理'),
itemKey: 'channel', itemKey: 'channel',
perm: 'platform.channel',
to: '/channel', to: '/channel',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('模型管理'), text: t('模型管理'),
itemKey: 'models', itemKey: 'models',
perm: 'platform.model',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('兑换码管理'), text: t('兑换码管理'),
itemKey: 'redemption', itemKey: 'redemption',
perm: 'platform.redemption',
to: '/redemption', to: '/redemption',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('用户管理'), text: t('用户管理'),
itemKey: 'user', itemKey: 'user',
perm: 'platform.user',
to: '/user', to: '/user',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('会员卡管理'), text: t('会员卡管理'),
itemKey: 'subscription', itemKey: 'subscription',
perm: 'platform.subscription',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('密钥管理'), text: t('密钥管理'),
itemKey: 'admin-token', itemKey: 'admin-token',
perm: 'platform.admin_token',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('企业管理'), text: t('企业管理'),
itemKey: 'organizations', itemKey: 'organizations',
perm: 'platform.org',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('平台 Skill 中心'), text: t('平台 Skill 中心'),
itemKey: 'skill-platform', itemKey: 'skill-platform',
perm: 'platform.skill',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('平台专家中心'), text: t('平台专家中心'),
itemKey: 'expert-platform', itemKey: 'expert-platform',
perm: 'platform.expert',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('订单管理'), text: t('订单管理'),
itemKey: 'order', itemKey: 'order',
perm: 'platform.order',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('发票管理'), text: t('发票管理'),
itemKey: 'invoice', itemKey: 'invoice',
perm: 'platform.invoice',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('系统设置'), text: t('系统设置'),
itemKey: 'setting', itemKey: 'setting',
perm: 'platform.setting',
to: '/setting', to: '/setting',
className: canAccessSetting ? '' : 'tableHiddle', className: canAccessSetting ? '' : 'tableHiddle',
}, },
{ {
text: t('官网设置'), text: t('官网设置'),
itemKey: 'website-setting', itemKey: 'website-setting',
perm: 'platform.setting.website_setting',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
{ {
text: t('预约演示'), text: t('预约演示'),
itemKey: 'demo-reservations', itemKey: 'demo-reservations',
perm: 'platform.setting.demo_reservations',
className: isAdmin() ? '' : 'tableHiddle', className: isAdmin() ? '' : 'tableHiddle',
}, },
]; ];
// 根据配置过滤项目 // 根据配置过滤项目
const filteredItems = items.filter((item) => { const filteredItems = items.filter((item) => {
// 已切换模块:只看权限点(及菜单管理的显示开关),不再看角色与侧栏模块配置——
// 持有菜单的非管理员也要能看到入口;功能总开关(云端大脑、分佣)仍然生效
const byPerm = permVisible(item.perm);
if (byPerm !== null) {
if (
!CLOUD_BRAIN_UI_ENABLED &&
(item.itemKey === 'skill-platform' ||
item.itemKey === 'expert-platform')
) {
return false;
}
if (item.itemKey === 'commission' && !commissionEnabled) return false;
return byPerm;
}
if ( if (
(item.itemKey === 'website-setting' || (item.itemKey === 'website-setting' ||
item.itemKey === 'demo-reservations') && item.itemKey === 'demo-reservations') &&
@@ -351,10 +411,14 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
return configVisible; return configVisible;
}); });
return filteredItems; // 已切换模块的菜单按权限点放行,不受原有的角色隐藏(tableHiddle)影响
return filteredItems.map((item) =>
permVisible(item.perm) === true ? { ...item, className: '' } : item,
);
}, [ }, [
t, t,
isModuleVisible, isModuleVisible,
permVisible,
canAccessSetting, canAccessSetting,
delegatedSettingTabs, delegatedSettingTabs,
delegatedPermissions, delegatedPermissions,
@@ -362,28 +426,63 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
commissionEnabled, commissionEnabled,
]); ]);
// 非管理员持有已切换模块的菜单时也显示管理员分组
const visibleAdminItems = adminItems.filter(
(item) => item.className !== 'tableHiddle',
);
// 权限管理分组:新模块不在 sidebar 配置注册表内,绕过 isModuleVisible,直接按权限点控制显示
const canAuthzMode = isRoot();
const authzItems = useMemo(() => {
const items = [
{ text: t('菜单管理'), itemKey: 'authz-menus', visible: canAuthzMenu },
{ text: t('平台角色'), itemKey: 'authz-roles', visible: canAuthzRole },
{
text: t('功能套餐'),
itemKey: 'authz-packages',
visible: canAuthzPackage,
},
{
text: t('角色模板'),
itemKey: 'authz-templates',
visible: canAuthzTemplate,
},
{ text: t('运行模式'), itemKey: 'authz-mode', visible: canAuthzMode },
];
return items.filter((item) => item.visible);
}, [
t,
canAuthzMenu,
canAuthzRole,
canAuthzPackage,
canAuthzTemplate,
canAuthzMode,
]);
const chatMenuItems = useMemo(() => { const chatMenuItems = useMemo(() => {
const items = [ const items = [
{ {
text: t('操练场'), text: t('操练场'),
itemKey: 'playground', itemKey: 'playground',
to: '/playground', to: '/playground',
perm: 'platform.playground',
}, },
{ {
text: t('聊天'), text: t('聊天'),
itemKey: 'chat', itemKey: 'chat',
items: chatItems, items: chatItems,
perm: 'platform.chat',
}, },
]; ];
// 根据配置过滤项目 // 根据配置过滤项目
const filteredItems = items.filter((item) => { const filteredItems = items.filter((item) => {
const configVisible = isModuleVisible('chat', item.itemKey); const configVisible = isModuleVisible('chat', item.itemKey);
return configVisible; return configVisible && permVisible(item.perm) !== false;
}); });
return filteredItems; return filteredItems;
}, [chatItems, t, isModuleVisible]); }, [chatItems, t, isModuleVisible, permVisible]);
// 更新路由映射,添加聊天路由 // 更新路由映射,添加聊天路由
const updateRouterMapWithChats = (chats) => { const updateRouterMapWithChats = (chats) => {
@@ -680,13 +779,19 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
)} )}
{/* 管理员区域:按角色、权限下放及菜单配置过滤。分佣管理为子菜单,走 renderSubItem。 */} {/* 管理员区域:按角色、权限下放及菜单配置过滤。分佣管理为子菜单,走 renderSubItem。 */}
{isAdmin() && {(isAdmin() || visibleAdminItems.length > 0) &&
renderGroup( renderGroup(
'admin-group', 'admin-group',
t('管理员'), t('管理员'),
adminItems visibleAdminItems.map(renderSubItem),
.filter((item) => item.className !== 'tableHiddle') )}
.map(renderSubItem),
{/* 权限管理区域:至少有一项可见时显示 */}
{authzItems.length > 0 &&
renderGroup(
'authz-group',
t('权限管理'),
authzItems.map((item) => renderNavItem(item)),
)} )}
</nav> </nav>
</SkeletonWrapper> </SkeletonWrapper>
@@ -22,45 +22,29 @@ import { API, showError, showSuccess, copy } from '../../helpers';
const { Text, Title, Paragraph } = Typography; const { Text, Title, Paragraph } = Typography;
// 暂时隐藏推广弹窗里的邀请奖励规则入口。
const SHOW_INVITATION_REWARD_RULES = false;
// 默认海报模板配置 // 默认海报模板配置
const DEFAULT_TEMPLATES = [ const DEFAULT_TEMPLATES = [
{ { id: 'blue', name: '科技蓝' },
id: 'blue', { id: 'orange', name: '活力橙' },
name: '科技蓝', { id: 'green', name: '清新绿' },
bgGradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', { id: 'dark', name: '暗夜黑' },
textColor: '#ffffff',
},
{
id: 'orange',
name: '活力橙',
bgGradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
textColor: '#ffffff',
},
{
id: 'green',
name: '清新绿',
bgGradient: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
textColor: '#ffffff',
},
{
id: 'dark',
name: '暗夜黑',
bgGradient: 'linear-gradient(135deg, #232526 0%, #414345 100%)',
textColor: '#ffffff',
},
]; ];
const PromotionPosterModal = ({ visible, onClose }) => { const PromotionPosterModal = ({ visible, onClose }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate(); const navigate = useNavigate();
const canvasRef = useRef(null); const canvasRef = useRef(null);
const previewRef = useRef(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [affCode, setAffCode] = useState(''); const [affCode, setAffCode] = useState('');
const [affLink, setAffLink] = useState(''); const [affLink, setAffLink] = useState('');
const [systemName, setSystemName] = useState(''); const [systemName, setSystemName] = useState('');
const [selectedTemplate, setSelectedTemplate] = useState( const [selectedTemplate, setSelectedTemplate] = useState(
DEFAULT_TEMPLATES[0], DEFAULT_TEMPLATES[0].id,
); );
const [downloading, setDownloading] = useState(false); const [downloading, setDownloading] = useState(false);
const [posterConfig, setPosterConfig] = useState(null); const [posterConfig, setPosterConfig] = useState(null);
@@ -123,9 +107,7 @@ const PromotionPosterModal = ({ visible, onClose }) => {
// 绘制海报内容 // 绘制海报内容
const drawContent = useCallback( const drawContent = useCallback(
(ctx, width, height) => { (ctx, width, height, textColor) => {
const textColor = selectedTemplate.textColor;
ctx.fillStyle = textColor; ctx.fillStyle = textColor;
ctx.font = ctx.font =
'bold 28px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'; 'bold 28px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
@@ -187,15 +169,17 @@ const PromotionPosterModal = ({ visible, onClose }) => {
height - 45, height - 45,
); );
}, },
[selectedTemplate, posterConfig, systemName, affCode, t], [posterConfig, systemName, affCode, t],
); );
// 绘制海报到 Canvas // 绘制海报到 Canvas
const drawPoster = useCallback(() => { const drawPoster = useCallback(() => {
const canvas = canvasRef.current; const canvas = canvasRef.current;
if (!canvas || !affLink) return null; const preview = previewRef.current;
if (!canvas || !preview || !affLink) return null;
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
const { backgroundColor, color } = getComputedStyle(preview);
const width = 375; const width = 375;
const height = 667; const height = 667;
@@ -203,26 +187,12 @@ const PromotionPosterModal = ({ visible, onClose }) => {
canvas.height = height * 2; canvas.height = height * 2;
ctx.scale(2, 2); ctx.scale(2, 2);
const gradient = ctx.createLinearGradient(0, 0, width, height); ctx.fillStyle = backgroundColor;
if (selectedTemplate.id === 'blue') {
gradient.addColorStop(0, '#667eea');
gradient.addColorStop(1, '#764ba2');
} else if (selectedTemplate.id === 'orange') {
gradient.addColorStop(0, '#f093fb');
gradient.addColorStop(1, '#f5576c');
} else if (selectedTemplate.id === 'green') {
gradient.addColorStop(0, '#4facfe');
gradient.addColorStop(1, '#00f2fe');
} else {
gradient.addColorStop(0, '#232526');
gradient.addColorStop(1, '#414345');
}
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, width, height); ctx.fillRect(0, 0, width, height);
drawContent(ctx, width, height); drawContent(ctx, width, height, color);
return canvas; return canvas;
}, [affLink, selectedTemplate, drawContent]); }, [affLink, drawContent]);
// 下载海报 // 下载海报
const handleDownload = async () => { const handleDownload = async () => {
@@ -354,14 +324,12 @@ const PromotionPosterModal = ({ visible, onClose }) => {
const renderPosterMode = () => ( const renderPosterMode = () => (
<div className='pm-poster-layout'> <div className='pm-poster-layout'>
<div className='pm-preview-stage'>
<div <div
className='pm-poster' className='pm-preview-stage'
style={{ data-poster-template={selectedTemplate}
'--pm-poster-background': selectedTemplate.bgGradient, ref={previewRef}
'--pm-poster-ink': selectedTemplate.textColor,
}}
> >
<div className='pm-poster'>
<h2>{posterConfig?.slogan || t('邀请好友,共享AI')}</h2> <h2>{posterConfig?.slogan || t('邀请好友,共享AI')}</h2>
<p className='pm-poster-subtitle'> <p className='pm-poster-subtitle'>
{posterConfig?.sub_slogan || t('注册即可获得免费额度')} {posterConfig?.sub_slogan || t('注册即可获得免费额度')}
@@ -393,21 +361,15 @@ const PromotionPosterModal = ({ visible, onClose }) => {
<Radio.Group <Radio.Group
className='pm-template-list' className='pm-template-list'
aria-labelledby='promotion-template-label' aria-labelledby='promotion-template-label'
value={selectedTemplate.id} value={selectedTemplate}
onChange={(event) => onChange={(event) => setSelectedTemplate(event.target.value)}
setSelectedTemplate(
DEFAULT_TEMPLATES.find(
(item) => item.id === event.target.value,
),
)
}
> >
{DEFAULT_TEMPLATES.map((template) => ( {DEFAULT_TEMPLATES.map((template) => (
<Radio key={template.id} value={template.id}> <Radio key={template.id} value={template.id}>
<span className='pm-template-label'> <span className='pm-template-label'>
<span <span
className='pm-template-swatch' className='pm-template-swatch'
style={{ '--pm-template-background': template.bgGradient }} data-poster-template={template.id}
/> />
{t(template.name)} {t(template.name)}
</span> </span>
@@ -447,7 +409,7 @@ const PromotionPosterModal = ({ visible, onClose }) => {
footer={null} footer={null}
width={800} width={800}
centered centered
className='promotion-modal' className={`promotion-modal${activeTab === 'poster' ? ' promotion-modal--poster' : ''}`}
> >
{loading ? ( {loading ? (
<div className='pm-loading' aria-label={t('加载中...')}> <div className='pm-loading' aria-label={t('加载中...')}>
@@ -490,6 +452,7 @@ const PromotionPosterModal = ({ visible, onClose }) => {
title={t('邀请链接获取中,请稍后')} title={t('邀请链接获取中,请稍后')}
/> />
)} )}
{SHOW_INVITATION_REWARD_RULES && (
<button <button
type='button' type='button'
className='pm-rewards' className='pm-rewards'
@@ -507,6 +470,7 @@ const PromotionPosterModal = ({ visible, onClose }) => {
</span> </span>
<ChevronRight size={18} aria-hidden /> <ChevronRight size={18} aria-hidden />
</button> </button>
)}
</> </>
)} )}
</Modal> </Modal>
+56 -26
View File
@@ -8,7 +8,11 @@
--pm-border: var(--border-subtle); --pm-border: var(--border-subtle);
--pm-accent: var(--brand-primary); --pm-accent: var(--brand-primary);
--pm-soft: var(--brand-primary-soft); --pm-soft: var(--brand-primary-soft);
--pm-qr-surface: #fff; --pm-qr-surface: var(--ui-color-white);
--pm-poster-ink: var(--ui-color-white);
--pm-body-max-height: calc(100dvh - 200px);
--pm-tab-panel-height: 448px;
--pm-preview-min-height: 418px;
max-width: calc(100vw - 32px); max-width: calc(100vw - 32px);
padding-block: 24px; padding-block: 24px;
} }
@@ -28,23 +32,44 @@
right: 24px; right: 24px;
} }
.promotion-modal .ant-modal-body { .promotion-modal .ant-modal-body {
max-height: calc(100dvh - 160px); max-height: var(--pm-body-max-height);
overflow-y: auto; overflow-y: auto;
overscroll-behavior: contain; overscroll-behavior: contain;
} }
.promotion-tabs {
max-block-size: var(--pm-body-max-height);
}
.promotion-tabs > .ant-tabs-nav { .promotion-tabs > .ant-tabs-nav {
flex-shrink: 0;
margin-bottom: 24px; margin-bottom: 24px;
} }
.promotion-tabs > .ant-tabs-body-holder {
flex: 0 1 var(--pm-tab-panel-height);
min-block-size: 0;
overflow-y: auto;
overscroll-behavior: contain;
scrollbar-gutter: stable;
}
.pm-tab-label { .pm-tab-label {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
} }
.pm-link-layout { .pm-link-layout,
.pm-poster-layout {
display: grid; display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1.15fr); grid-template-columns: minmax(0, 1fr) minmax(0, 1.15fr);
gap: 32px; gap: 32px;
align-items: stretch; align-items: start;
}
.pm-invitation-card,
.pm-preview-stage {
min-block-size: var(--pm-preview-min-height);
border-radius: 12px;
}
.pm-share-details,
.pm-poster-options {
align-self: center;
} }
.pm-invitation-card { .pm-invitation-card {
display: flex; display: flex;
@@ -52,7 +77,6 @@
align-items: center; align-items: center;
padding: 28px 20px; padding: 28px 20px;
border: 1px solid var(--pm-border); border: 1px solid var(--pm-border);
border-radius: 12px;
background: var(--pm-muted); background: var(--pm-muted);
text-align: center; text-align: center;
min-width: 0; min-width: 0;
@@ -162,6 +186,9 @@
border-color: var(--pm-accent); border-color: var(--pm-accent);
background: var(--pm-soft); background: var(--pm-soft);
} }
.promotion-modal--poster .pm-rewards {
display: none;
}
.pm-rewards-icon { .pm-rewards-icon {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -191,33 +218,35 @@
flex-shrink: 0; flex-shrink: 0;
color: var(--pm-secondary); color: var(--pm-secondary);
} }
.pm-poster-layout { .promotion-modal [data-poster-template='blue'] {
display: grid; --pm-template-background: #2455b8;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }
gap: 32px; .promotion-modal [data-poster-template='orange'] {
align-items: center; --pm-template-background: #a94913;
}
.promotion-modal [data-poster-template='green'] {
--pm-template-background: #226b50;
}
.promotion-modal [data-poster-template='dark'] {
--pm-template-background: #272b33;
} }
.pm-preview-stage { .pm-preview-stage {
display: flex; display: flex;
justify-content: center; justify-content: center;
padding: 20px; padding-inline: 16px;
border: 1px solid var(--pm-border); background: var(--pm-template-background);
border-radius: 12px; color: var(--pm-poster-ink);
background: var(--pm-muted);
min-width: 0; min-width: 0;
} }
.pm-poster { .pm-poster {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
width: 240px; width: min(100%, 280px);
min-width: 0; min-width: 0;
aspect-ratio: 375 / 667; padding: 28px 8px 20px;
padding: 28px 16px 20px;
background: var(--pm-poster-background);
color: var(--pm-poster-ink);
border-radius: 8px;
text-align: center; text-align: center;
overflow-wrap: anywhere;
} }
.pm-poster h2 { .pm-poster h2 {
margin: 0 0 8px; margin: 0 0 8px;
@@ -232,7 +261,7 @@
color: inherit; color: inherit;
} }
.pm-poster h3 { .pm-poster h3 {
margin: 20px 0; margin: 16px 0;
font-size: 16px; font-size: 16px;
line-height: 1.5; line-height: 1.5;
color: inherit; color: inherit;
@@ -298,6 +327,10 @@
outline-offset: 3px; outline-offset: 3px;
} }
@media (max-width: 600px) { @media (max-width: 600px) {
.promotion-modal.ant-modal {
--pm-tab-panel-height: 760px;
--pm-preview-min-height: 395px;
}
.promotion-modal .ant-modal-container { .promotion-modal .ant-modal-container {
padding: 20px; padding: 20px;
} }
@@ -308,9 +341,6 @@
top: 18px; top: 18px;
right: 16px; right: 16px;
} }
.promotion-modal .ant-modal-body {
max-height: calc(100dvh - 136px);
}
.pm-link-layout, .pm-link-layout,
.pm-poster-layout { .pm-poster-layout {
grid-template-columns: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr);
@@ -329,8 +359,8 @@
.pm-field > .ant-btn { .pm-field > .ant-btn {
width: 100%; width: 100%;
} }
.pm-preview-stage { .pm-poster {
padding: 16px; padding-block: 24px 20px;
} }
.pm-template-list { .pm-template-list {
grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-columns: repeat(2, minmax(0, 1fr));
+7 -6
View File
@@ -1,3 +1,5 @@
import TableActionPopconfirm from '@/components/common/table/TableActionPopconfirm';
import TableStatusSwitch from '@/components/common/table/TableStatusSwitch';
import { Plus as ActionPlus } from '@/components/common/icons/ActionIcons'; import { Plus as ActionPlus } from '@/components/common/icons/ActionIcons';
import React, { useCallback, useEffect, useState } from 'react'; import React, { useCallback, useEffect, useState } from 'react';
import { import {
@@ -6,7 +8,6 @@ import {
Input, Input,
InputNumber, InputNumber,
Modal, Modal,
Popconfirm,
Select, Select,
Switch, Switch,
Table, Table,
@@ -146,6 +147,7 @@ const QualityAlerts = ({ quality, t }) => {
load(); load();
} catch (e) { } catch (e) {
Toast.error(saveErrorText(e)); Toast.error(saveErrorText(e));
return false;
} }
}; };
@@ -173,8 +175,7 @@ const QualityAlerts = ({ quality, t }) => {
dataIndex: 'enabled', dataIndex: 'enabled',
width: 70, width: 70,
render: (v, rule) => ( render: (v, rule) => (
<Switch <TableStatusSwitch
size='small'
checked={v} checked={v}
onChange={(checked) => toggle(rule, checked)} onChange={(checked) => toggle(rule, checked)}
/> />
@@ -220,14 +221,14 @@ const QualityAlerts = ({ quality, t }) => {
> >
{t('编辑')} {t('编辑')}
</Button> </Button>
<Popconfirm <TableActionPopconfirm
title={t('确定删除该告警规则?')} title={t('确定删除该告警规则?')}
onConfirm={() => remove(rule)} onConfirm={() => remove(rule)}
> >
<Button size='small' theme='borderless' type='danger'> <Button size='small' type='link' danger>
{t('删除')} {t('删除')}
</Button> </Button>
</Popconfirm> </TableActionPopconfirm>
</div> </div>
), ),
}, },
+2 -2
View File
@@ -196,7 +196,7 @@ const QualityBreakdown = ({ quality, t }) => {
/> />
</div> </div>
<div <div
className={`quality-card-body quality-nested-tabs${isPlatform ? ' quality-breakdown-body' : ''}`} className={`quality-card-body quality-nested-tabs ${isPlatform ? 'quality-breakdown-body' : 'quality-breakdown-org-body'}`}
> >
<Tabs type='button' size='small' activeKey={dim} onChange={setDim}> <Tabs type='button' size='small' activeKey={dim} onChange={setDim}>
{dims.map((d) => ( {dims.map((d) => (
@@ -215,7 +215,7 @@ const QualityBreakdown = ({ quality, t }) => {
className={ className={
isPlatform isPlatform
? 'quality-breakdown-result' ? 'quality-breakdown-result'
: 'overflow-x-auto app-scrollbar mt-2' : 'overflow-x-auto app-scrollbar'
} }
> >
<Table <Table
@@ -254,6 +254,7 @@ const QualityFilterBar = ({ quality, t, onOpenDetail }) => {
</Radio.Group> </Radio.Group>
{filters.range === 'custom' && ( {filters.range === 'custom' && (
<DatePicker <DatePicker
tableFilter
type='dateTimeRange' type='dateTimeRange'
value={customRange} value={customRange}
style={{ maxWidth: 380, width: '100%' }} style={{ maxWidth: 380, width: '100%' }}
+19 -1
View File
@@ -70,7 +70,14 @@
padding-block-start: 12px; padding-block-start: 12px;
} }
.quality-breakdown-body .ant-tabs > .ant-tabs-nav { .quality-breakdown-org-body {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: var(--uc-layout-gap);
}
.quality-breakdown-body .ant-tabs > .ant-tabs-nav,
.quality-breakdown-org-body .ant-tabs > .ant-tabs-nav {
margin-bottom: 0; margin-bottom: 0;
} }
@@ -214,6 +221,17 @@
border-color: color-mix(in srgb, var(--ui-color-primary) 22%, transparent); border-color: color-mix(in srgb, var(--ui-color-primary) 22%, transparent);
} }
.quality-breakdown-org-body .quality-notice {
align-items: center;
justify-content: flex-start;
gap: 6px;
text-align: left;
}
.quality-breakdown-org-body .quality-notice > svg {
margin-top: 0;
}
.quality-grid-2 { .quality-grid-2 {
display: grid; display: grid;
grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); grid-template-columns: minmax(0, 2fr) minmax(0, 1fr);
@@ -1,3 +1,6 @@
import TableGroupTags, {
TABLE_GROUP_COLUMN_WIDTH,
} from '@/components/common/table/TableGroupTags';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { formatIdReference } from '../../helpers/safeDisplay'; import { formatIdReference } from '../../helpers/safeDisplay';
import { TestTube2 as ActionTestTube2 } from '@/components/common/icons/ActionIcons'; import { TestTube2 as ActionTestTube2 } from '@/components/common/icons/ActionIcons';
@@ -327,7 +330,12 @@ export default function ContentGuardSetting() {
render: (v) => new Date(v).toLocaleString(), render: (v) => new Date(v).toLocaleString(),
}, },
{ title: t('用户'), dataIndex: 'user_id', width: 80 }, { title: t('用户'), dataIndex: 'user_id', width: 80 },
{ title: t('分组'), dataIndex: 'using_group' }, {
title: t('分组'),
dataIndex: 'using_group',
width: TABLE_GROUP_COLUMN_WIDTH,
render: (groups) => <TableGroupTags groups={groups} />,
},
{ title: t('模型'), dataIndex: 'model' }, { title: t('模型'), dataIndex: 'model' },
{ title: t('方向'), dataIndex: 'direction' }, { title: t('方向'), dataIndex: 'direction' },
{ title: t('类型'), dataIndex: 'content_type' }, { title: t('类型'), dataIndex: 'content_type' },
@@ -1,3 +1,4 @@
import TableActionPopconfirm from '@/components/common/table/TableActionPopconfirm';
import { import {
RefreshCw as ActionRefreshCw, RefreshCw as ActionRefreshCw,
Plus as ActionPlus, Plus as ActionPlus,
@@ -13,7 +14,6 @@ import {
Select, Select,
Tag, Tag,
Avatar, Avatar,
Popconfirm,
Typography, Typography,
Space, Space,
Banner, Banner,
@@ -178,12 +178,14 @@ const CustomerServiceSetting = () => {
if (res.data.success) { if (res.data.success) {
showSuccess(t('删除成功')); showSuccess(t('删除成功'));
fetchAgents(); fetchAgents();
return true;
} else { } else {
showError(res.data.message); showError(res.data.message);
} }
} catch (err) { } catch (err) {
showError(t('删除失败')); showError(t('删除失败'));
} }
return false;
}; };
// 切换状态 // 切换状态
@@ -301,7 +303,7 @@ const CustomerServiceSetting = () => {
<Button onClick={() => openModal(record)} type='link' size='small'> <Button onClick={() => openModal(record)} type='link' size='small'>
{t('编辑')} {t('编辑')}
</Button> </Button>
<Popconfirm <TableActionPopconfirm
title={t('确认删除')} title={t('确认删除')}
content={t('确定要删除这个客服吗?')} content={t('确定要删除这个客服吗?')}
onConfirm={() => handleDelete(record.id)} onConfirm={() => handleDelete(record.id)}
@@ -309,7 +311,7 @@ const CustomerServiceSetting = () => {
<Button type='link' size='small' danger> <Button type='link' size='small' danger>
{t('删除')} {t('删除')}
</Button> </Button>
</Popconfirm> </TableActionPopconfirm>
</Space> </Space>
), ),
}, },
@@ -1,3 +1,4 @@
import TableActionPopconfirm from '@/components/common/table/TableActionPopconfirm';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { useEffectEvent } from '../../hooks/common/useEffectEvent'; import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useEffect, useRef, useState } from 'react'; import React, { useEffect, useRef, useState } from 'react';
@@ -317,9 +318,11 @@ export default function DataSecuritySetting() {
showSuccess(res.data?.message || t('删除成功')); showSuccess(res.data?.message || t('删除成功'));
loadOrgConfigs(); loadOrgConfigs();
loadChangeRequests(); // 开启二级审批时会进入待审批队列 loadChangeRequests(); // 开启二级审批时会进入待审批队列
return true;
} else { } else {
showError(res.data?.message || t('删除失败')); showError(res.data?.message || t('删除失败'));
} }
return false;
}; };
const toggleKillSwitch = async (action) => { const toggleKillSwitch = async (action) => {
const res = await API.post('/api/desensitize/killswitch', { const res = await API.post('/api/desensitize/killswitch', {
@@ -438,9 +441,11 @@ export default function DataSecuritySetting() {
showSuccess(res.data?.message || t('删除成功')); showSuccess(res.data?.message || t('删除成功'));
loadRules(); loadRules();
loadChangeRequests(); loadChangeRequests();
return true;
} else { } else {
showError(res.data?.message || t('删除失败')); showError(res.data?.message || t('删除失败'));
} }
return false;
}; };
// ---- 审批 ---- // ---- 审批 ----
@@ -496,14 +501,14 @@ export default function DataSecuritySetting() {
<Button onClick={() => openEditRule(rule)} type='link' size='small'> <Button onClick={() => openEditRule(rule)} type='link' size='small'>
{t('编辑')} {t('编辑')}
</Button> </Button>
<Popconfirm <TableActionPopconfirm
title={t('确认删除该规则?')} title={t('确认删除该规则?')}
onConfirm={() => deleteRule(rule)} onConfirm={() => deleteRule(rule)}
> >
<Button type='link' size='small' danger> <Button type='link' size='small' danger>
{t('删除')} {t('删除')}
</Button> </Button>
</Popconfirm> </TableActionPopconfirm>
</Space> </Space>
), ),
}, },
@@ -859,7 +864,7 @@ export default function DataSecuritySetting() {
{ {
title: t('操作'), title: t('操作'),
render: (_, rule) => ( render: (_, rule) => (
<Popconfirm <TableActionPopconfirm
title={t( title={t(
'确认紧急删除该企业私有规则?将同步记入该企业的变更留痕。', '确认紧急删除该企业私有规则?将同步记入该企业的变更留痕。',
)} )}
@@ -868,7 +873,7 @@ export default function DataSecuritySetting() {
<Button type='link' size='small' danger> <Button type='link' size='small' danger>
{t('删除')} {t('删除')}
</Button> </Button>
</Popconfirm> </TableActionPopconfirm>
), ),
}, },
]} ]}
@@ -1181,14 +1186,14 @@ export default function DataSecuritySetting() {
> >
{t('编辑')} {t('编辑')}
</Button> </Button>
<Popconfirm <TableActionPopconfirm
title={t('确认删除该企业覆盖(回到继承全局)?')} title={t('确认删除该企业覆盖(回到继承全局)?')}
onConfirm={() => deleteOrgConfig(row.org_id)} onConfirm={() => deleteOrgConfig(row.org_id)}
> >
<Button type='link' size='small' danger> <Button type='link' size='small' danger>
{t('删除')} {t('删除')}
</Button> </Button>
</Popconfirm> </TableActionPopconfirm>
</Space> </Space>
), ),
}, },
+16 -12
View File
@@ -1,3 +1,6 @@
import TableActionPopconfirm from '@/components/common/table/TableActionPopconfirm';
import TableStatusSwitch from '@/components/common/table/TableStatusSwitch';
import { TableGroupTag } from '@/components/common/table/TableGroupTags';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { Eraser as ActionEraser } from '@/components/common/icons/ActionIcons'; import { Eraser as ActionEraser } from '@/components/common/icons/ActionIcons';
import { import {
@@ -25,7 +28,6 @@ import {
Tooltip, Tooltip,
Divider, Divider,
Empty, Empty,
Switch,
} from '@/components/ui'; } from '@/components/ui';
import { Search } from 'lucide-react'; import { Search } from 'lucide-react';
import { API, showError, showSuccess } from '../../helpers'; import { API, showError, showSuccess } from '../../helpers';
@@ -745,6 +747,7 @@ const LevelPolicySetting = () => {
showSuccess(t('删除成功')); showSuccess(t('删除成功'));
} }
await fetchAll(); await fetchAll();
return true;
} else { } else {
const d = res?.data?.data || {}; const d = res?.data?.data || {};
const refs = []; const refs = [];
@@ -770,6 +773,7 @@ const LevelPolicySetting = () => {
} finally { } finally {
setDeletingCode(''); setDeletingCode('');
} }
return false;
}; };
const saveDefaults = async () => { const saveDefaults = async () => {
@@ -859,9 +863,9 @@ const LevelPolicySetting = () => {
const tags = ( const tags = (
<Space> <Space>
{preview.map((g) => ( {preview.map((g) => (
<Tag key={g} color='light-blue'> <TableGroupTag key={g} group={g}>
{g} ×{d[g]} {g} ×{d[g]}
</Tag> </TableGroupTag>
))} ))}
{rest > 0 && ( {rest > 0 && (
<Tag color='light-blue' type='ghost'> <Tag color='light-blue' type='ghost'>
@@ -953,9 +957,7 @@ const LevelPolicySetting = () => {
> >
<Space> <Space>
{preview.map((g) => ( {preview.map((g) => (
<Tag key={g} color='red' type='ghost'> <TableGroupTag key={g} group={g} />
{g}
</Tag>
))} ))}
{rest > 0 && ( {rest > 0 && (
<Tag color='red' type='ghost'> <Tag color='red' type='ghost'>
@@ -988,7 +990,7 @@ const LevelPolicySetting = () => {
{t('复制')} {t('复制')}
</Button> </Button>
</Tooltip> </Tooltip>
<Popconfirm <TableActionPopconfirm
title={t('确认删除该等级?')} title={t('确认删除该等级?')}
content={t('被用户/企业/默认等级引用时会被拒绝')} content={t('被用户/企业/默认等级引用时会被拒绝')}
onConfirm={() => deleteLevel(type, r.code)} onConfirm={() => deleteLevel(type, r.code)}
@@ -1001,7 +1003,7 @@ const LevelPolicySetting = () => {
> >
{t('删除')} {t('删除')}
</Button> </Button>
</Popconfirm> </TableActionPopconfirm>
</Space> </Space>
), ),
}, },
@@ -1419,7 +1421,7 @@ const LevelPolicySetting = () => {
dataIndex: 'model', dataIndex: 'model',
render: (v, r) => ( render: (v, r) => (
<Space> <Space>
<span>{v}</span> <TableGroupTag group={v} />
{r.maybeDisabled && ( {r.maybeDisabled && (
<Tooltip <Tooltip
content={t( content={t(
@@ -1532,7 +1534,7 @@ const LevelPolicySetting = () => {
dataIndex: 'group', dataIndex: 'group',
render: (v, r) => ( render: (v, r) => (
<Space> <Space>
<span>{v}</span> <TableGroupTag group={v} />
{r.stale && ( {r.stale && (
<Tooltip <Tooltip
content={t( content={t(
@@ -1554,9 +1556,11 @@ const LevelPolicySetting = () => {
// 已废弃分组只允许关闭存量隐藏条目:后端对新增隐藏做存在性校验必拒, // 已废弃分组只允许关闭存量隐藏条目:后端对新增隐藏做存在性校验必拒,
// 放开开关会造成一次注定失败的保存。 // 放开开关会造成一次注定失败的保存。
render: (v, r) => ( render: (v, r) => (
<Switch <TableStatusSwitch
size='small'
checked={!!v} checked={!!v}
checkedChildren={t('是')}
unCheckedChildren={t('否')}
aria-label={t('对该等级隐藏')}
disabled={r.stale && !v} disabled={r.stale && !v}
onChange={(checked) => setGroupHidden(r.group, checked)} onChange={(checked) => setGroupHidden(r.group, checked)}
/> />
+6
View File
@@ -8,6 +8,7 @@ import ModelSettingsVisualEditor from '../../pages/Setting/Ratio/ModelSettingsVi
import ModelRatioNotSetEditor from '../../pages/Setting/Ratio/ModelRationNotSetEditor'; import ModelRatioNotSetEditor from '../../pages/Setting/Ratio/ModelRationNotSetEditor';
import UpstreamRatioSync from '../../pages/Setting/Ratio/UpstreamRatioSync'; import UpstreamRatioSync from '../../pages/Setting/Ratio/UpstreamRatioSync';
import ModelOfficialPriceSettings from '../../pages/Setting/Ratio/ModelOfficialPriceSettings'; import ModelOfficialPriceSettings from '../../pages/Setting/Ratio/ModelOfficialPriceSettings';
import OfficialPriceExchangeRateSetting from '../../pages/Setting/Ratio/OfficialPriceExchangeRateSetting';
import ModelCostSettings from '../../pages/Setting/Ratio/ModelCostSettings'; import ModelCostSettings from '../../pages/Setting/Ratio/ModelCostSettings';
import { API, isRoot, showError, toBoolean } from '../../helpers'; import { API, isRoot, showError, toBoolean } from '../../helpers';
@@ -23,6 +24,7 @@ const RatioSetting = () => {
GroupRatio: '', GroupRatio: '',
GroupGroupRatio: '', GroupGroupRatio: '',
ModelOfficialPrice: '', ModelOfficialPrice: '',
OfficialPriceExchangeRate: '',
ImageRatio: '', ImageRatio: '',
AudioRatio: '', AudioRatio: '',
AudioCompletionRatio: '', AudioCompletionRatio: '',
@@ -101,6 +103,10 @@ const RatioSetting = () => {
入口——否则被下放 tab 的普通管理员会看到一个填了存不进去的页面。 */} 入口——否则被下放 tab 的普通管理员会看到一个填了存不进去的页面。 */}
{isRoot() && ( {isRoot() && (
<Tabs.TabPane tab={t('模型原厂价格')} itemKey='official_price'> <Tabs.TabPane tab={t('模型原厂价格')} itemKey='official_price'>
<OfficialPriceExchangeRateSetting
options={inputs}
refresh={onRefresh}
/>
<ModelOfficialPriceSettings <ModelOfficialPriceSettings
options={inputs} options={inputs}
refresh={onRefresh} refresh={onRefresh}
@@ -1,3 +1,5 @@
import TableActionPopconfirm from '@/components/common/table/TableActionPopconfirm';
import TableStatusSwitch from '@/components/common/table/TableStatusSwitch';
import { useEffectEvent } from '../../hooks/common/useEffectEvent'; import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@@ -8,8 +10,6 @@ import {
Modal, Modal,
Form, Form,
Toast, Toast,
Popconfirm,
Switch,
Tag, Tag,
Progress, Progress,
Empty, Empty,
@@ -154,6 +154,7 @@ const TutorialVideoSetting = () => {
if (res.data.success) { if (res.data.success) {
Toast.success(t('删除成功')); Toast.success(t('删除成功'));
loadVideos(); loadVideos();
return true;
} else { } else {
Toast.error(res.data.message || t('删除失败')); Toast.error(res.data.message || t('删除失败'));
} }
@@ -161,6 +162,7 @@ const TutorialVideoSetting = () => {
console.error('Delete error:', error); console.error('Delete error:', error);
Toast.error(t('删除失败')); Toast.error(t('删除失败'));
} }
return false;
}; };
// 切换状态 // 切换状态
@@ -231,11 +233,9 @@ const TutorialVideoSetting = () => {
dataIndex: 'status', dataIndex: 'status',
width: 80, width: 80,
render: (status, record) => ( render: (status, record) => (
<Switch <TableStatusSwitch
checked={status === 1} checked={status === 1}
onChange={() => handleToggleStatus(record)} onChange={() => handleToggleStatus(record)}
checkedText={t('启用')}
uncheckedText={t('禁用')}
/> />
), ),
}, },
@@ -254,7 +254,7 @@ const TutorialVideoSetting = () => {
<Button onClick={() => handleEdit(record)} type='link' size='small'> <Button onClick={() => handleEdit(record)} type='link' size='small'>
{t('编辑')} {t('编辑')}
</Button> </Button>
<Popconfirm <TableActionPopconfirm
title={t('确定删除这个视频吗?')} title={t('确定删除这个视频吗?')}
content={t('删除后将无法恢复')} content={t('删除后将无法恢复')}
onConfirm={() => handleDelete(record.id)} onConfirm={() => handleDelete(record.id)}
@@ -262,7 +262,7 @@ const TutorialVideoSetting = () => {
<Button type='link' size='small' danger> <Button type='link' size='small' danger>
{t('删除')} {t('删除')}
</Button> </Button>
</Popconfirm> </TableActionPopconfirm>
</div> </div>
), ),
}, },
+1 -1
View File
@@ -20,7 +20,7 @@ const kindText = (t, kind) =>
judge: { judge: {
title: t('智能判定'), title: t('智能判定'),
desc: t( desc: t(
'把脱敏、截断后的请求片段发送给境外判定服务(Jev),用于选择合适的模型。', '将脱敏、截断后的请求片段发送至境外判定服务,用于选择合适的模型。',
), ),
}, },
eval: { eval: {
+20 -9
View File
@@ -16,6 +16,7 @@ import {
import { ConsoleAlert as Alert } from '../console/ConsolePrimitives'; import { ConsoleAlert as Alert } from '../console/ConsolePrimitives';
import { showError, showSuccess } from '../../helpers'; import { showError, showSuccess } from '../../helpers';
import { getAdminStatus, loadOptions, saveOption, setJevKey } from './api'; import { getAdminStatus, loadOptions, saveOption, setJevKey } from './api';
import JevProxySettings from './JevProxySettings';
const { Text } = Typography; const { Text } = Typography;
const { TextArea } = Input; const { TextArea } = Input;
@@ -50,7 +51,7 @@ const FIELDS = [
{ {
key: 'jev_egress_allowed', key: 'jev_egress_allowed',
type: 'bool', type: 'bool',
label: '允许调用 Jev(数据出境,合规评估通过后开启)', label: '允许调用境外判定模型(通过合规评估后开启)',
section: 'jev', section: 'jev',
compliance: true, compliance: true,
}, },
@@ -98,7 +99,7 @@ const FIELDS = [
{ {
key: 'state_max_bytes', key: 'state_max_bytes',
type: 'int', type: 'int',
label: '发给 Jev 的内容上限(字节)', label: '发送给判定模型的内容上限(字节)',
min: 1000, min: 1000,
max: 30000, max: 30000,
section: 'jev', section: 'jev',
@@ -184,7 +185,7 @@ const FIELDS = [
{ {
key: 'jev_daily_cap_per_user', key: 'jev_daily_cap_per_user',
type: 'int', type: 'int',
label: 'Jev 判定每人每日上限(0 不限)', label: '每人每日模型判定次数上限(0 表示不限)',
min: 0, min: 0,
max: 10000000, max: 10000000,
section: 'retention', section: 'retention',
@@ -192,7 +193,7 @@ const FIELDS = [
{ {
key: 'jev_daily_cap_per_org', key: 'jev_daily_cap_per_org',
type: 'int', type: 'int',
label: 'Jev 判定每企业每日上限(0 不限)', label: '每个企业每日模型判定次数上限(0 表示不限)',
min: 0, min: 0,
max: 100000000, max: 100000000,
section: 'retention', section: 'retention',
@@ -201,7 +202,7 @@ const FIELDS = [
const SECTIONS = [ const SECTIONS = [
['main', '总控'], ['main', '总控'],
['jev', 'Jev 判定'], ['jev', '判定模型'],
['judge', '判定参数'], ['judge', '判定参数'],
['consent', '同意文案'], ['consent', '同意文案'],
['retention', '保留与限流'], ['retention', '保留与限流'],
@@ -266,7 +267,7 @@ const GlobalSettings = () => {
await saveOption(PREFIX + f.key, String(values[f.key] ?? '')); await saveOption(PREFIX + f.key, String(values[f.key] ?? ''));
saved[f.key] = values[f.key]; saved[f.key] = values[f.key];
} catch (e) { } catch (e) {
showError(`${t(f.label)} · ${e?.message || ''}`); showError(`${t(f.label)} · ${e?.message ? t(e.message) : ''}`);
// 已保存的项更新基线,未保存的编辑保留在表单里,便于修改后重试 // 已保存的项更新基线,未保存的编辑保留在表单里,便于修改后重试
setOriginal((o) => ({ ...o, ...saved })); setOriginal((o) => ({ ...o, ...saved }));
return; return;
@@ -293,7 +294,9 @@ const GlobalSettings = () => {
if (!clear) return run(); if (!clear) return run();
Modal.confirm({ Modal.confirm({
title: t('确认清除密钥?'), title: t('确认清除密钥?'),
content: t('清除后该通道无法调用 Jev,判定会降级为规则判定。'), content: t(
'清除后,此通道将无法调用判定模型。所有通道均不可用时,将使用规则判定。',
),
okButtonProps: { danger: true }, okButtonProps: { danger: true },
onOk: run, onOk: run,
}); });
@@ -425,7 +428,7 @@ const GlobalSettings = () => {
</span> </span>
</Tag> </Tag>
<Tag> <Tag>
{t('Jev 降级次数')}{' '} {t('模型判定失败后使用规则的次数')}{' '}
<span className='smart-router-num'>{status.jev_fallback}</span> <span className='smart-router-num'>{status.jev_fallback}</span>
</Tag> </Tag>
<Tag color={status.not_ready ? 'warning' : 'default'}> <Tag color={status.not_ready ? 'warning' : 'default'}>
@@ -444,7 +447,7 @@ const GlobalSettings = () => {
type='warning' type='warning'
showIcon showIcon
title={t( title={t(
'标注「合规」的配置项只有超级管理员可以修改。开启 Jev 出境前须完成合规评估。', '标注「合规」的配置项仅限超级管理员修改。启用境外判定模型前须完成合规评估。',
)} )}
/> />
{SECTIONS.map(([sec, title]) => ( {SECTIONS.map(([sec, title]) => (
@@ -474,6 +477,14 @@ const GlobalSettings = () => {
{renderField(f)} {renderField(f)}
</Form.Item> </Form.Item>
))} ))}
{sec === 'jev' && (
<JevProxySettings
saved={status?.jev_proxy}
onSaved={(jev_proxy) =>
setStatus((previous) => ({ ...previous, jev_proxy }))
}
/>
)}
{sec === 'jev' && {sec === 'jev' &&
['typesafe', 'openrouter'].map((p) => ( ['typesafe', 'openrouter'].map((p) => (
<Form.Item <Form.Item
@@ -0,0 +1,137 @@
import React, { useState } from 'react';
import {
Alert,
Button,
Form,
Input,
Popconfirm,
Space,
Typography,
} from 'antd';
import { useTranslation } from 'react-i18next';
import { getCountryName } from '@/constants/countries';
import { showSuccess } from '@/helpers';
import { clearJevProxy, saveJevProxy, testJevProxy } from './api';
export default function JevProxySettings({ saved, onSaved }) {
const { t, i18n } = useTranslation();
const [draft, setDraft] = useState('');
const [pending, setPending] = useState('');
const [result, setResult] = useState(null);
const [error, setError] = useState('');
const url = draft.trim();
const busy = Boolean(pending);
async function run(action) {
setPending(action);
setError('');
setResult(null);
try {
if (action === 'test') {
setResult(await testJevProxy(url));
} else {
const next =
action === 'save' ? await saveJevProxy(url) : await clearJevProxy();
onSaved(next);
setDraft('');
showSuccess(action === 'save' ? t('已保存') : t('已清除'));
}
} catch (e) {
setError(t(e.message));
} finally {
setPending('');
}
}
const google = result?.google;
const egress = result?.egress;
const reasons = {
timeout: t('连接超时'),
tls: t('TLS 证书校验失败'),
proxy_auth: t('代理认证失败'),
connection: t('代理连接失败'),
http_status: `HTTP ${google?.http_status}`,
};
return (
<Form.Item
label={t('判定模型专用代理')}
htmlFor='jev-proxy-url'
className='smart-router-proxy'
>
<Space orientation='vertical' size={8} className='smart-router-key-tools'>
<Typography.Text type='secondary'>
{t('仅用于调用判定模型。')}{' '}
{saved?.configured
? saved.address || t('已配置')
: t('跟随服务器网络设置')}
</Typography.Text>
<Input.Password
id='jev-proxy-url'
autoComplete='new-password'
placeholder='http:// · https:// · socks5:// · socks5h://'
value={draft}
disabled={busy}
onChange={(e) => {
setDraft(e.target.value);
setResult(null);
setError('');
}}
/>
<Space wrap>
<Button
onClick={() => run('test')}
loading={pending === 'test'}
disabled={busy || (!url && !saved?.configured)}
>
{t('测试代理')}
</Button>
<Button
onClick={() => run('save')}
loading={pending === 'save'}
disabled={busy || !url}
>
{t('保存代理')}
</Button>
<Popconfirm
title={t('确认清除判定模型代理?')}
onConfirm={() => run('clear')}
disabled={busy || !saved?.configured}
>
<Button
danger
loading={pending === 'clear'}
disabled={busy || !saved?.configured}
>
{t('清除代理')}
</Button>
</Popconfirm>
</Space>
{error && <Alert type='error' showIcon title={error} />}
{google && (
<Alert
showIcon
type={google.connected ? 'success' : 'error'}
title={
<span role='status'>
{google.connected ? t('Google 已连通') : t('Google 未连通')} ·{' '}
{google.elapsed_ms} ms
{google.error &&
` · ${reasons[google.error] || reasons.connection}`}
</span>
}
description={
egress?.ip
? t('出口 IP {{ip}} · {{region}}', {
ip: egress.ip,
region:
getCountryName(egress.country_code, i18n.language) ||
t('地区未知'),
})
: t('出口 IP 未获取')
}
/>
)}
</Space>
</Form.Item>
);
}
+12 -7
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useMemo, useRef, useState } from 'react'; import React, { useEffect, useId, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { import {
Alert, Alert,
@@ -207,6 +207,7 @@ const ProfileEditor = ({
onSaved, onSaved,
}) => { }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const judgeHelpId = useId();
const [state, setState] = useState(() => toState(profile, t)); const [state, setState] = useState(() => toState(profile, t));
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [activePanels, setActivePanels] = useState([ const [activePanels, setActivePanels] = useState([
@@ -891,14 +892,18 @@ const ProfileEditor = ({
size='small' size='small'
checked={state.jev_allowed} checked={state.jev_allowed}
onChange={(v) => set('jev_allowed', v)} onChange={(v) => set('jev_allowed', v)}
aria-label={t( aria-label={t('允许使用判定模型')}
'允许使用 Jev 判定(还需平台开启与出境同意)', aria-describedby={judgeHelpId}
)}
/> />
<Text> <Text>{t('允许使用判定模型')}</Text>
{t('允许使用 Jev 判定(还需平台开启与出境同意)')}
</Text>
</div> </div>
<Text
id={judgeHelpId}
type='secondary'
className='smart-router-sub'
>
{t('需平台开启模型判定,并取得相应的数据出境授权。')}
</Text>
</div> </div>
), ),
}, },
+6 -5
View File
@@ -1,6 +1,7 @@
import TableActionPopconfirm from '@/components/common/table/TableActionPopconfirm';
import React, { useCallback, useEffect, useState } from 'react'; import React, { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Button, Empty, Popconfirm, Space, Tag, Typography } from 'antd'; import { Button, Empty, Space, Tag, Typography } from 'antd';
import { Table } from '@/components/ui'; import { Table } from '@/components/ui';
import { ConsoleAlert as Alert } from '../console/ConsolePrimitives'; import { ConsoleAlert as Alert } from '../console/ConsolePrimitives';
import { Plus } from '../common/icons/ActionIcons'; import { Plus } from '../common/icons/ActionIcons';
@@ -117,7 +118,7 @@ const ProfileTable = ({ mode, orgId, canWrite = true, emptyHint }) => {
)} )}
{r.jev_allowed && ( {r.jev_allowed && (
<Tag color='blue' variant='filled'> <Tag color='blue' variant='filled'>
Jev {t('允许模型判定')}
</Tag> </Tag>
)} )}
</Space> </Space>
@@ -143,10 +144,9 @@ const ProfileTable = ({ mode, orgId, canWrite = true, emptyHint }) => {
<Button type='link' size='small' onClick={() => setEditing(r)}> <Button type='link' size='small' onClick={() => setEditing(r)}>
{t('编辑')} {t('编辑')}
</Button> </Button>
<Popconfirm <TableActionPopconfirm
title={t('确认删除该集合?')} title={t('确认删除该集合?')}
description={t('使用该虚拟模型名的请求将返回"模型不存在"。')} description={t('使用该虚拟模型名的请求将返回"模型不存在"。')}
okButtonProps={{ danger: true }}
onConfirm={async () => { onConfirm={async () => {
try { try {
await deleteProfile(mode, orgId, r.id); await deleteProfile(mode, orgId, r.id);
@@ -154,13 +154,14 @@ const ProfileTable = ({ mode, orgId, canWrite = true, emptyHint }) => {
load(); load();
} catch (e) { } catch (e) {
if (e?.message) showError(e.message); if (e?.message) showError(e.message);
return false;
} }
}} }}
> >
<Button type='link' size='small' danger> <Button type='link' size='small' danger>
{t('删除')} {t('删除')}
</Button> </Button>
</Popconfirm> </TableActionPopconfirm>
</> </>
)} )}
</Space> </Space>
+13
View File
@@ -130,5 +130,18 @@ export const setJevKey = (provider, key, clear = false) =>
export const loadOptions = () => call(() => API.get('/api/option/', opts())); export const loadOptions = () => call(() => API.get('/api/option/', opts()));
const jevProxyPath = '/api/router/admin/jev-proxy';
export const saveJevProxy = (url) =>
call(() => API.put(jevProxyPath, { url }, opts()));
export const clearJevProxy = () => call(() => API.delete(jevProxyPath, opts()));
export const testJevProxy = (url) =>
call(() =>
API.post(
jevProxyPath + '/test',
url ? { source: 'draft', url } : { source: 'saved' },
opts(),
),
);
export const saveOption = (key, value) => export const saveOption = (key, value) =>
call(() => API.put('/api/option/', { key, value }, opts())); call(() => API.put('/api/option/', { key, value }, opts()));
+7 -7
View File
@@ -35,17 +35,17 @@ export const jevReasonText = (t, code) => {
export const gateText = (t, code) => export const gateText = (t, code) =>
({ ({
jev: t('已调用 Jev'), jev: t('已调用模型'),
platform_off: t('平台未开启 Jev 出境'), platform_off: t('平台未开启境外模型判定'),
sensitive: t('命中敏感词'), sensitive: t('命中敏感词'),
desens_off: t('脱敏未启用'), desens_off: t('脱敏未启用'),
desens_block: t('脱敏策略会拦截'), desens_block: t('脱敏策略会拦截'),
guard_input: t('内容审核输入审查生效'), guard_input: t('内容审核输入审查生效'),
org_no_consent: t('企业未授权'), org_no_consent: t('企业未授权'),
user_no_consent: t('个人未授权'), user_no_consent: t('个人未授权'),
profile_off: t('集合未允许使用 Jev'), profile_off: t('此集合未开启模型判定'),
no_quota: t('余额不足,未调用 Jev'), no_quota: t('余额不足,未调用模型'),
jev_cap: t('今日 Jev 判定次数已达上限'), jev_cap: t('今日模型判定次数已达上限'),
desens_residual: t('脱敏后仍有敏感信息'), desens_residual: t('脱敏后仍有敏感信息'),
'n/a': t('未经过闸门'), 'n/a': t('未经过闸门'),
})[code] || })[code] ||
@@ -54,10 +54,10 @@ export const gateText = (t, code) =>
export const srcText = (t, code) => export const srcText = (t, code) =>
({ ({
jev: t('Jev 判定'), jev: t('智能路由'),
cache: t('判定缓存'), cache: t('判定缓存'),
rules: t('规则判定器'), rules: t('规则判定器'),
rules_fallback: t('Jev 失败,规则判定'), rules_fallback: t('模型判定失败,已使用规则'),
rule: t('自定义规则'), rule: t('自定义规则'),
rule_tier: t('自定义规则强制档位'), rule_tier: t('自定义规则强制档位'),
forced: t('请求指定档位'), forced: t('请求指定档位'),
@@ -295,6 +295,12 @@
width: 100%; width: 100%;
} }
.smart-router-proxy {
grid-column: 1 / -1;
min-width: 0;
overflow-wrap: anywhere;
}
.smart-router-key-input { .smart-router-key-input {
width: min(320px, 100%); width: min(320px, 100%);
} }
@@ -1,5 +1,7 @@
import { TABLE_GROUP_COLUMN_WIDTH } from '@/components/common/table/TableGroupTags';
import TableStatusSwitch from '@/components/common/table/TableStatusSwitch';
import React from 'react'; import React from 'react';
import { Button, Switch, Tag as AntTag } from 'antd'; import { Button, Tag as AntTag } from 'antd';
import { Tag, Typography, Popover } from '@/components/ui'; import { Tag, Typography, Popover } from '@/components/ui';
import { import {
renderGroup, renderGroup,
@@ -21,11 +23,8 @@ const renderStatus = (status, record, t, showEnableDisableModal) => {
(![1, 2].includes(status) ? { color: 'error', label: '未知状态' } : null); (![1, 2].includes(status) ? { color: 'error', label: '未知状态' } : null);
return ( return (
<div className='admin-tokens-status'> <div className='admin-tokens-status'>
<Switch <TableStatusSwitch
size='small'
checked={status === 1} checked={status === 1}
checkedChildren={t('启用')}
unCheckedChildren={t('禁用')}
aria-label={status === 1 ? t('禁用') : t('启用')} aria-label={status === 1 ? t('禁用') : t('启用')}
disabled={!isAdmin() || Boolean(record.DeletedAt)} disabled={!isAdmin() || Boolean(record.DeletedAt)}
onChange={() => onChange={() =>
@@ -194,7 +193,7 @@ export const getAdminTokensColumns = ({
{ {
title: t('分组'), title: t('分组'),
dataIndex: 'group', dataIndex: 'group',
width: 110, width: TABLE_GROUP_COLUMN_WIDTH,
render: (text) => <div>{renderGroup(text)}</div>, render: (text) => <div>{renderGroup(text)}</div>,
}, },
{ {
@@ -7,7 +7,8 @@ import { useFilterSearch } from '../../../hooks/common/useFilterSearch';
const AdminTokensFilters = ({ const AdminTokensFilters = ({
formInitValues, formInitValues,
setFormApi, setFormApi,
searchTokens, activePage,
setSelectedRowKeys,
loadTokens, loadTokens,
pageSize, pageSize,
groupOptions, groupOptions,
@@ -17,7 +18,7 @@ const AdminTokensFilters = ({
}) => { }) => {
const formApiRef = useRef(null); const formApiRef = useRef(null);
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch( const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
() => searchTokens(pageSize), (_, signal) => loadTokens(activePage, pageSize, null, signal),
); );
const handleReset = () => { const handleReset = () => {
@@ -25,6 +26,7 @@ const AdminTokensFilters = ({
formApiRef.current.reset(); formApiRef.current.reset();
cancelPendingSearch(); cancelPendingSearch();
// 重置后立即用初始值刷新(不走 debounce) // 重置后立即用初始值刷新(不走 debounce)
setSelectedRowKeys([]);
loadTokens(1, pageSize, formInitValues); loadTokens(1, pageSize, formInitValues);
}; };
+4 -6
View File
@@ -52,8 +52,6 @@ const AdminTokensPage = () => {
setFormApi, setFormApi,
loadTokens, loadTokens,
searchTokens,
debouncedSearch,
refresh, refresh,
manageToken, manageToken,
batchManageTokens, batchManageTokens,
@@ -82,8 +80,7 @@ const AdminTokensPage = () => {
const handleDeleteConfirm = async () => { const handleDeleteConfirm = async () => {
if (!modalToken) return; if (!modalToken) return;
await manageToken(modalToken.id, 'delete'); if (await manageToken(modalToken.id, 'delete')) setShowDelete(false);
setShowDelete(false);
}; };
const handleEditConfirm = async () => { const handleEditConfirm = async () => {
@@ -133,8 +130,8 @@ const AdminTokensPage = () => {
<AdminTokensFilters <AdminTokensFilters
formInitValues={formInitValues} formInitValues={formInitValues}
setFormApi={setFormApi} setFormApi={setFormApi}
searchTokens={searchTokens} activePage={activePage}
debouncedSearch={debouncedSearch} setSelectedRowKeys={setSelectedRowKeys}
loadTokens={loadTokens} loadTokens={loadTokens}
pageSize={pageSize} pageSize={pageSize}
groupOptions={groupOptions} groupOptions={groupOptions}
@@ -156,6 +153,7 @@ const AdminTokensPage = () => {
</div> </div>
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
preservePage: true,
showRange: false, showRange: false,
currentPage: activePage, currentPage: activePage,
pageSize: pageSize, pageSize: pageSize,
@@ -1,5 +1,6 @@
import TableActionModal from '@/components/common/table/TableActionModal';
import React from 'react'; import React from 'react';
import { Modal, Typography, Banner } from '@/components/ui'; import { Typography, Banner } from '@/components/ui';
const { Text } = Typography; const { Text } = Typography;
@@ -8,7 +9,7 @@ const AdminDeleteTokenModal = ({ visible, onCancel, onConfirm, token, t }) => {
const isOrgToken = token.organization_id > 0; const isOrgToken = token.organization_id > 0;
return ( return (
<Modal <TableActionModal
title={t('确定要删除此密钥吗?')} title={t('确定要删除此密钥吗?')}
visible={visible} visible={visible}
onCancel={onCancel} onCancel={onCancel}
@@ -37,7 +38,7 @@ const AdminDeleteTokenModal = ({ visible, onCancel, onConfirm, token, t }) => {
{token.user_id}) {token.user_id})
</Text> </Text>
</div> </div>
</Modal> </TableActionModal>
); );
}; };
@@ -1,6 +1,9 @@
import { TABLE_GROUP_COLUMN_WIDTH } from '@/components/common/table/TableGroupTags';
import { toGroupList } from '@/helpers/groupList';
import { confirmTableAction } from '@/components/common/table/confirmTableAction';
import TableStatusSwitch from '@/components/common/table/TableStatusSwitch';
import { writeClipboardText } from '../../../helpers/clipboard'; import { writeClipboardText } from '../../../helpers/clipboard';
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Switch } from 'antd';
import { import {
Button, Button,
InputNumber, InputNumber,
@@ -34,11 +37,8 @@ const formatDisplayPercent = (value, digits = 0) => {
function ChannelStatusSwitch({ record, manageChannel, t }) { function ChannelStatusSwitch({ record, manageChannel, t }) {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
return ( return (
<Switch <TableStatusSwitch
size='small'
checked={record.status === 1} checked={record.status === 1}
checkedChildren={t('启用')}
unCheckedChildren={t('禁用')}
disabled={!isRoot()} disabled={!isRoot()}
loading={loading} loading={loading}
aria-label={t('状态')} aria-label={t('状态')}
@@ -360,11 +360,16 @@ export const getChannelsColumns = ({
key: COLUMN_KEYS.ID, key: COLUMN_KEYS.ID,
title: t('ID'), title: t('ID'),
dataIndex: 'id', dataIndex: 'id',
fixed: 'left',
width: 64,
}, },
{ {
key: COLUMN_KEYS.NAME, key: COLUMN_KEYS.NAME,
title: t('名称'), title: t('名称'),
dataIndex: 'name', dataIndex: 'name',
fixed: 'left',
width: 112,
ellipsis: { showTitle: false },
render: (text, record, index) => { render: (text, record, index) => {
if (record.remark && record.remark.trim() !== '') { if (record.remark && record.remark.trim() !== '') {
return ( return (
@@ -394,30 +399,26 @@ export const getChannelsColumns = ({
trigger={hoverOrClickTrigger()} trigger={hoverOrClickTrigger()}
position='topLeft' position='topLeft'
> >
<span>{text}</span> <span title={text}>{text}</span>
</Tooltip> </Tooltip>
); );
} }
return text; return <span title={text}>{text}</span>;
}, },
}, },
{ {
key: COLUMN_KEYS.GROUP, key: COLUMN_KEYS.GROUP,
title: t('分组'), title: t('分组'),
dataIndex: 'group', dataIndex: 'group',
render: (text, record, index) => ( width: TABLE_GROUP_COLUMN_WIDTH,
<div> render: (groups) =>
<Space spacing={2}> renderGroup(
{text toGroupList(groups).sort((left, right) => {
?.split(',') if (left === right) return 0;
.sort((a, b) => { if (left === 'default') return -1;
if (a === 'default') return -1; if (right === 'default') return 1;
if (b === 'default') return 1; return left.localeCompare(right);
return a.localeCompare(b); }),
})
.map((item, index) => renderGroup(item))}
</Space>
</div>
), ),
}, },
{ {
@@ -713,7 +714,6 @@ export const getChannelsColumns = ({
key: COLUMN_KEYS.OPERATE, key: COLUMN_KEYS.OPERATE,
title: t('操作'), title: t('操作'),
dataIndex: 'operate', dataIndex: 'operate',
fixed: 'right',
render: (text, record, index) => { render: (text, record, index) => {
if (record.children === undefined) { if (record.children === undefined) {
const moreMenuItems = [ const moreMenuItems = [
@@ -723,19 +723,20 @@ export const getChannelsColumns = ({
type: 'danger', type: 'danger',
onClick: async () => { onClick: async () => {
const content = await buildDeleteConfirmContent(record.id, t); const content = await buildDeleteConfirmContent(record.id, t);
Modal.confirm({ confirmTableAction({
title: t('确定是否要删除此渠道?'), title: t('确定是否要删除此渠道?'),
content, content,
onOk: () => { okType: 'danger',
(async () => { focusable: { autoFocusButton: 'cancel' },
await manageChannel(record.id, 'delete', record); onOk: async () => {
if (!(await manageChannel(record.id, 'delete', record)))
return false;
await refresh(); await refresh();
setTimeout(() => { setTimeout(() => {
if (channels.length === 0 && activePage > 1) { if (channels.length === 0 && activePage > 1) {
refresh(activePage - 1); refresh(activePage - 1);
} }
}, 100); }, 100);
})();
}, },
}); });
}, },
@@ -8,6 +8,9 @@ const ChannelsFilters = ({
formInitValues, formInitValues,
setFormApi, setFormApi,
searchChannels, searchChannels,
activePage,
setActivePage,
setSelectedChannels,
enableTagMode, enableTagMode,
formApi, formApi,
groupOptions, groupOptions,
@@ -20,7 +23,16 @@ const ChannelsFilters = ({
t, t,
}) => { }) => {
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch( const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
() => searchChannels(enableTagMode), (_, signal) =>
searchChannels(
enableTagMode,
undefined,
undefined,
activePage,
undefined,
undefined,
signal,
),
); );
return ( return (
<div className='w-full'> <div className='w-full'>
@@ -124,10 +136,9 @@ const ChannelsFilters = ({
setAutoBanExclusionFilter('all'); setAutoBanExclusionFilter('all');
localStorage.setItem('channel-status-filter', 'all'); localStorage.setItem('channel-status-filter', 'all');
localStorage.setItem('channel-autoban-exclusion-filter', 'all'); localStorage.setItem('channel-autoban-exclusion-filter', 'all');
// 重置后立即查询,使用setTimeout确保表单重置完成 setSelectedChannels([]);
setTimeout(() => { setActivePage(1);
searchChannels(enableTagMode, undefined, 'all'); searchChannels(enableTagMode, undefined, 'all').catch(() => {});
}, 100);
} }
}} }}
/> />
@@ -5,6 +5,8 @@ import CardTable from '../../common/ui/CardTable';
import { isRoot } from '../../../helpers'; import { isRoot } from '../../../helpers';
import { getChannelsColumns } from './ChannelsColumnDefs'; import { getChannelsColumns } from './ChannelsColumnDefs';
const SELECTION_COLUMN_WIDTH = 34;
const ChannelsTable = (channelsData) => { const ChannelsTable = (channelsData) => {
const { const {
channels, channels,
@@ -51,6 +53,7 @@ const ChannelsTable = (channelsData) => {
} = channelsData; } = channelsData;
const [idSortOrder, setIdSortOrder] = useState('descend'); const [idSortOrder, setIdSortOrder] = useState('descend');
const canSelect = isRoot();
const handleTableChange = ({ sorter, extra, action }) => { const handleTableChange = ({ sorter, extra, action }) => {
if ((action ?? extra?.action) !== 'sort') return; if ((action ?? extra?.action) !== 'sort') return;
@@ -166,7 +169,7 @@ const ChannelsTable = (channelsData) => {
const visibleColumnsList = getVisibleColumns(); const visibleColumnsList = getVisibleColumns();
const tableColumns = useMemo(() => { const tableColumns = useMemo(() => {
const sortableColumns = visibleColumnsList.map((column) => return visibleColumnsList.map((column) =>
column.key === COLUMN_KEYS.ID column.key === COLUMN_KEYS.ID
? { ? {
...column, ...column,
@@ -179,14 +182,12 @@ const ChannelsTable = (channelsData) => {
} }
: column, : column,
); );
return compactMode }, [visibleColumnsList, COLUMN_KEYS.ID, idSort, idSortOrder]);
? sortableColumns.map(({ fixed, ...rest }) => rest)
: sortableColumns;
}, [compactMode, visibleColumnsList, COLUMN_KEYS.ID, idSort, idSortOrder]);
return ( return (
<CardTable <CardTable
columns={tableColumns} columns={tableColumns}
minScrollableWidth={72 + (canSelect ? SELECTION_COLUMN_WIDTH : 0)}
onChange={handleTableChange} onChange={handleTableChange}
dataSource={filteredChannels} dataSource={filteredChannels}
scroll={compactMode ? undefined : { x: 'max-content' }} scroll={compactMode ? undefined : { x: 'max-content' }}
@@ -203,8 +204,10 @@ const ChannelsTable = (channelsData) => {
expandAllRows={false} expandAllRows={false}
onRow={handleRow} onRow={handleRow}
rowSelection={ rowSelection={
isRoot() canSelect
? { ? {
fixed: true,
columnWidth: SELECTION_COLUMN_WIDTH,
selectedRowKeys: selectedChannels.map( selectedRowKeys: selectedChannels.map(
(channel) => channel.key ?? String(channel.id), (channel) => channel.key ?? String(channel.id),
), ),
+1 -28
View File
@@ -1,9 +1,7 @@
import { Plus as ActionPlus } from '@/components/common/icons/ActionIcons';
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 { CHANNEL_OPTIONS } from '../../../constants'; import { CHANNEL_OPTIONS } from '../../../constants';
import { getChannelIcon, isRoot } from '../../../helpers'; import { getChannelIcon } from '../../../helpers';
import './channels-tabs.css'; import './channels-tabs.css';
const ChannelsTabs = ({ const ChannelsTabs = ({
@@ -13,35 +11,11 @@ const ChannelsTabs = ({
channelTypeCounts, channelTypeCounts,
availableTypeKeys, availableTypeKeys,
loadChannels, loadChannels,
activePage,
pageSize, pageSize,
idSort, idSort,
setActivePage, setActivePage,
setEditingChannel,
setShowEdit,
t, t,
}) => { }) => {
const createButton = isRoot() ? (
<Button
className='console-create-action'
type='primary'
size='middle'
icon={<ActionPlus 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);
setActivePage(1); setActivePage(1);
@@ -54,7 +28,6 @@ const ChannelsTabs = ({
type='line' type='line'
onChange={handleTabChange} onChange={handleTabChange}
className='channels-tabs mb-2' className='channels-tabs mb-2'
tabBarExtraContent={createButton}
> >
<TabPane <TabPane
itemKey='all' itemKey='all'
+23 -1
View File
@@ -1,4 +1,6 @@
import React from 'react'; import React from 'react';
import { Button } from 'antd';
import { Plus as ActionPlus } from '@/components/common/icons/ActionIcons';
import CardPro from '../../common/ui/CardPro'; import CardPro from '../../common/ui/CardPro';
import { ColumnSettingsButton } from '../../common/table/ColumnSettings'; import { ColumnSettingsButton } from '../../common/table/ColumnSettings';
import ChannelsTable from './ChannelsTable'; import ChannelsTable from './ChannelsTable';
@@ -14,6 +16,7 @@ import EditChannelModal from './modals/EditChannelModal';
import EditTagModal from './modals/EditTagModal'; import EditTagModal from './modals/EditTagModal';
import MultiKeyManageModal from './modals/MultiKeyManageModal'; import MultiKeyManageModal from './modals/MultiKeyManageModal';
import { createCardProPagination } from '../../../helpers/utils'; import { createCardProPagination } from '../../../helpers/utils';
import { isRoot } from '../../../helpers';
const ChannelsPage = () => { const ChannelsPage = () => {
const channelsData = useChannelsData(); const channelsData = useChannelsData();
@@ -49,16 +52,35 @@ const ChannelsPage = () => {
tableTitle={channelsData.t('渠道列表')} tableTitle={channelsData.t('渠道列表')}
tableActionsOffset tableActionsOffset
type='type3' type='type3'
tabsArea={<ChannelsTabs {...channelsData} />} tabsArea={
channelsData.enableTagMode ? null : <ChannelsTabs {...channelsData} />
}
actionsArea={<ChannelsActions {...channelsData} />} actionsArea={<ChannelsActions {...channelsData} />}
searchArea={<ChannelsFilters {...channelsData} />} searchArea={<ChannelsFilters {...channelsData} />}
tableActions={ tableActions={
<>
{isRoot() && (
<Button
className='console-create-action'
type='primary'
size='middle'
icon={<ActionPlus size={16} />}
onClick={() => {
channelsData.setEditingChannel({ id: undefined });
channelsData.setShowEdit(true);
}}
>
{channelsData.t('创建渠道')}
</Button>
)}
<ColumnSettingsButton <ColumnSettingsButton
open={channelsData.showColumnSelector} open={channelsData.showColumnSelector}
onClick={() => channelsData.setShowColumnSelector(true)} onClick={() => channelsData.setShowColumnSelector(true)}
/> />
</>
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
preservePage: true,
showRange: false, showRange: false,
currentPage: channelsData.activePage, currentPage: channelsData.activePage,
pageSize: channelsData.pageSize, pageSize: channelsData.pageSize,
@@ -1,3 +1,4 @@
import { toGroupList } from '@/helpers/groupList';
import { formatIdReference } from '../../../../helpers/safeDisplay'; import { formatIdReference } from '../../../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../../../i18n/technicalText.js';
@@ -46,13 +47,7 @@ import SecureVerificationModal from '../../../common/modals/SecureVerificationMo
import ChannelKeyDisplay from '../../../common/ui/ChannelKeyDisplay'; 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 { Code, Globe, Server, Settings, Zap } from 'lucide-react';
IconServer,
IconSetting,
IconCode,
IconGlobe,
IconBolt,
} from '@/components/ui/icons';
const { Text } = Typography; const { Text } = Typography;
@@ -138,7 +133,7 @@ const originInputs = {
model_mapping: '', model_mapping: '',
status_code_mapping: '', status_code_mapping: '',
models: [], models: [],
auto_ban: 1, auto_ban: true,
test_model: '', test_model: '',
groups: ['default'], groups: ['default'],
priority: 0, priority: 0,
@@ -160,6 +155,7 @@ const originInputs = {
thinking_to_content: false, thinking_to_content: false,
proxy: '', proxy: '',
pass_through_body_enabled: false, pass_through_body_enabled: false,
pass_through_model_mapping_enabled: false,
chat_image_to_images_enabled: false, chat_image_to_images_enabled: false,
system_prompt: '', system_prompt: '',
system_prompt_override: false, system_prompt_override: false,
@@ -200,7 +196,6 @@ const EditChannelModal = (props) => {
const [batch, setBatch] = useState(false); const [batch, setBatch] = useState(false);
const [multiToSingle, setMultiToSingle] = useState(false); const [multiToSingle, setMultiToSingle] = useState(false);
const [multiKeyMode, setMultiKeyMode] = useState('random'); const [multiKeyMode, setMultiKeyMode] = useState('random');
const [autoBan, setAutoBan] = useState(true);
const [inputs, setInputs] = useState(originInputs); const [inputs, setInputs] = useState(originInputs);
const [originModelOptions, setOriginModelOptions] = useState([]); const [originModelOptions, setOriginModelOptions] = useState([]);
const [modelOptions, setModelOptions] = useState([]); const [modelOptions, setModelOptions] = useState([]);
@@ -270,17 +265,21 @@ const EditChannelModal = (props) => {
res.data.data res.data.data
.filter((ch) => ch.id !== selfId) .filter((ch) => ch.id !== selfId)
.map((ch) => { .map((ch) => {
const label = `${formatIdReference(ch.id)} ${ch.name}`;
if (ch.status !== 1) { if (ch.status !== 1) {
const searchLabel = `${label}${t('(已禁用)')}`;
return { return {
value: ch.id, value: ch.id,
label: `${formatIdReference(ch.id)} ${ch.name}${t('(已禁用)')}`, label,
searchLabel,
title: searchLabel,
disabled: true, disabled: true,
}; };
} }
const parts = [`${formatIdReference(ch.id)} ${ch.name}`]; const searchLabel = [label, ch.group, ch.region]
if (ch.group) parts.push(ch.group); .filter(Boolean)
if (ch.region) parts.push(ch.region); .join(' · ');
return { value: ch.id, label: parts.join(' · ') }; return { value: ch.id, label, searchLabel };
}), }),
); );
setFallbackCandidatesLoaded(true); setFallbackCandidatesLoaded(true);
@@ -406,6 +405,7 @@ const EditChannelModal = (props) => {
thinking_to_content: false, thinking_to_content: false,
proxy: '', proxy: '',
pass_through_body_enabled: false, pass_through_body_enabled: false,
pass_through_model_mapping_enabled: false,
chat_image_to_images_enabled: false, chat_image_to_images_enabled: false,
system_prompt: '', system_prompt: '',
system_prompt_override: false, system_prompt_override: false,
@@ -553,7 +553,6 @@ const EditChannelModal = (props) => {
// 重置手动输入模式状态 // 重置手动输入模式状态
setUseManualInput(false); setUseManualInput(false);
} }
//setAutoBan
}; };
const loadChannel = async () => { const loadChannel = async () => {
@@ -569,11 +568,7 @@ const EditChannelModal = (props) => {
} else { } else {
data.models = data.models.split(','); data.models = data.models.split(',');
} }
if (data.group === '') { data.groups = toGroupList(data.group);
data.groups = [];
} else {
data.groups = data.group.split(',');
}
if (data.model_mapping !== '') { if (data.model_mapping !== '') {
data.model_mapping = JSON.stringify( data.model_mapping = JSON.stringify(
JSON.parse(data.model_mapping), JSON.parse(data.model_mapping),
@@ -609,6 +604,8 @@ const EditChannelModal = (props) => {
data.proxy = parsedSettings.proxy || ''; data.proxy = parsedSettings.proxy || '';
data.pass_through_body_enabled = data.pass_through_body_enabled =
parsedSettings.pass_through_body_enabled || false; parsedSettings.pass_through_body_enabled || false;
data.pass_through_model_mapping_enabled =
parsedSettings.pass_through_model_mapping_enabled === true;
data.chat_image_to_images_enabled = data.chat_image_to_images_enabled =
parsedSettings.chat_image_to_images_enabled || false; parsedSettings.chat_image_to_images_enabled || false;
data.system_prompt = parsedSettings.system_prompt || ''; data.system_prompt = parsedSettings.system_prompt || '';
@@ -650,6 +647,7 @@ const EditChannelModal = (props) => {
data.thinking_to_content = false; data.thinking_to_content = false;
data.proxy = ''; data.proxy = '';
data.pass_through_body_enabled = false; data.pass_through_body_enabled = false;
data.pass_through_model_mapping_enabled = false;
data.chat_image_to_images_enabled = false; data.chat_image_to_images_enabled = false;
data.system_prompt = ''; data.system_prompt = '';
data.system_prompt_override = false; data.system_prompt_override = false;
@@ -672,6 +670,7 @@ const EditChannelModal = (props) => {
data.thinking_to_content = false; data.thinking_to_content = false;
data.proxy = ''; data.proxy = '';
data.pass_through_body_enabled = false; data.pass_through_body_enabled = false;
data.pass_through_model_mapping_enabled = false;
data.chat_image_to_images_enabled = false; data.chat_image_to_images_enabled = false;
data.system_prompt = ''; data.system_prompt = '';
data.system_prompt_override = false; data.system_prompt_override = false;
@@ -762,6 +761,7 @@ const EditChannelModal = (props) => {
if (!data.fallback_primary_attempts) data.fallback_primary_attempts = 1; if (!data.fallback_primary_attempts) data.fallback_primary_attempts = 1;
if (!data.fallback_hop_attempts) data.fallback_hop_attempts = 1; if (!data.fallback_hop_attempts) data.fallback_hop_attempts = 1;
data.auto_ban = Boolean(data.auto_ban ?? originInputs.auto_ban);
setInputs(data); setInputs(data);
if (formApiRef.current) { if (formApiRef.current) {
formApiRef.current.setValues(data); formApiRef.current.setValues(data);
@@ -773,11 +773,6 @@ const EditChannelModal = (props) => {
data.work_hours_timezone || 'Asia/Shanghai', data.work_hours_timezone || 'Asia/Shanghai',
); );
} }
if (data.auto_ban === 0) {
setAutoBan(false);
} else {
setAutoBan(true);
}
// 同步企业账户状态 // 同步企业账户状态
setIsEnterpriseAccount(data.is_enterprise_account || false); setIsEnterpriseAccount(data.is_enterprise_account || false);
setBasicModels(getChannelModels(data.type)); setBasicModels(getChannelModels(data.type));
@@ -789,6 +784,8 @@ const EditChannelModal = (props) => {
thinking_to_content: data.thinking_to_content, thinking_to_content: data.thinking_to_content,
proxy: data.proxy, proxy: data.proxy,
pass_through_body_enabled: data.pass_through_body_enabled, pass_through_body_enabled: data.pass_through_body_enabled,
pass_through_model_mapping_enabled:
data.pass_through_model_mapping_enabled,
chat_image_to_images_enabled: chat_image_to_images_enabled:
data.chat_image_to_images_enabled || false, data.chat_image_to_images_enabled || false,
system_prompt: data.system_prompt, system_prompt: data.system_prompt,
@@ -1076,6 +1073,7 @@ const EditChannelModal = (props) => {
thinking_to_content: false, thinking_to_content: false,
proxy: '', proxy: '',
pass_through_body_enabled: false, pass_through_body_enabled: false,
pass_through_model_mapping_enabled: false,
chat_image_to_images_enabled: false, chat_image_to_images_enabled: false,
system_prompt: '', system_prompt: '',
system_prompt_override: false, system_prompt_override: false,
@@ -1405,6 +1403,8 @@ const EditChannelModal = (props) => {
thinking_to_content: localInputs.thinking_to_content || false, thinking_to_content: localInputs.thinking_to_content || false,
proxy: localInputs.proxy || '', proxy: localInputs.proxy || '',
pass_through_body_enabled: localInputs.pass_through_body_enabled || false, pass_through_body_enabled: localInputs.pass_through_body_enabled || false,
pass_through_model_mapping_enabled:
localInputs.pass_through_model_mapping_enabled === true,
chat_image_to_images_enabled: chat_image_to_images_enabled:
localInputs.chat_image_to_images_enabled || false, localInputs.chat_image_to_images_enabled || false,
system_prompt: localInputs.system_prompt || '', system_prompt: localInputs.system_prompt || '',
@@ -1510,6 +1510,7 @@ const EditChannelModal = (props) => {
delete localInputs.thinking_to_content; delete localInputs.thinking_to_content;
delete localInputs.proxy; delete localInputs.proxy;
delete localInputs.pass_through_body_enabled; delete localInputs.pass_through_body_enabled;
delete localInputs.pass_through_model_mapping_enabled;
delete localInputs.chat_image_to_images_enabled; delete localInputs.chat_image_to_images_enabled;
delete localInputs.client_only; delete localInputs.client_only;
delete localInputs.os_restriction; delete localInputs.os_restriction;
@@ -1571,7 +1572,7 @@ const EditChannelModal = (props) => {
let res; let res;
localInputs.auto_ban = localInputs.auto_ban ? 1 : 0; localInputs.auto_ban = localInputs.auto_ban ? 1 : 0;
localInputs.models = localInputs.models.join(','); localInputs.models = localInputs.models.join(',');
localInputs.group = (localInputs.groups || []).join(','); localInputs.group = toGroupList(localInputs.groups).join(',');
// 日消耗限额统一使用 token(quota)单位,确保为整数 // 日消耗限额统一使用 token(quota)单位,确保为整数
if (localInputs.daily_quota_limit && localInputs.daily_quota_limit > 0) { if (localInputs.daily_quota_limit && localInputs.daily_quota_limit > 0) {
@@ -1917,7 +1918,7 @@ const EditChannelModal = (props) => {
{/* Header: Basic Info */} {/* Header: Basic Info */}
<div className='console-channel-section'> <div className='console-channel-section'>
<Avatar size='small' color='blue'> <Avatar size='small' color='blue'>
<IconServer size={16} /> <Server size={16} />
</Avatar> </Avatar>
<div> <div>
<Text className='text-lg font-medium'> <Text className='text-lg font-medium'>
@@ -2458,7 +2459,7 @@ const EditChannelModal = (props) => {
onClick={handleApiConfigSecretClick} onClick={handleApiConfigSecretClick}
> >
<Avatar size='small' color='green'> <Avatar size='small' color='green'>
<IconGlobe size={16} /> <Globe size={16} />
</Avatar> </Avatar>
<div> <div>
<Text className='text-lg font-medium'> <Text className='text-lg font-medium'>
@@ -2679,7 +2680,7 @@ const EditChannelModal = (props) => {
{/* Header: Model Config */} {/* Header: Model Config */}
<div className='console-channel-section'> <div className='console-channel-section'>
<Avatar size='small' color='purple'> <Avatar size='small' color='purple'>
<IconCode size={16} /> <Code size={16} />
</Avatar> </Avatar>
<div> <div>
<Text className='text-lg font-medium'> <Text className='text-lg font-medium'>
@@ -2884,7 +2885,7 @@ const EditChannelModal = (props) => {
{/* Header: Advanced Settings */} {/* Header: Advanced Settings */}
<div className='console-channel-section'> <div className='console-channel-section'>
<Avatar size='small' color='orange'> <Avatar size='small' color='orange'>
<IconSetting size={16} /> <Settings size={16} />
</Avatar> </Avatar>
<div> <div>
<Text className='text-lg font-medium'> <Text className='text-lg font-medium'>
@@ -2993,6 +2994,9 @@ const EditChannelModal = (props) => {
filter filter
showClear showClear
max={20} max={20}
showSearch={{
optionFilterProp: ['searchLabel', 'label'],
}}
optionList={fallbackOptionList} optionList={fallbackOptionList}
// Semi 对 disabled option 的已选标签不给关闭按钮; // Semi 对 disabled option 的已选标签不给关闭按钮;
// 已禁用/已删除的渠道需要能从链中移除,故自绘可关闭标签 // 已禁用/已删除的渠道需要能从链中移除,故自绘可关闭标签
@@ -3004,9 +3008,20 @@ const EditChannelModal = (props) => {
color='white' color='white'
size='large' size='large'
onClose={onClose} onClose={onClose}
style={{ maxWidth: '100%' }} title={
option.disabled ? option.searchLabel : undefined
}
style={{
maxWidth: '100%',
color: option.disabled
? 'var(--text-secondary)'
: undefined,
}}
> >
{option.label} {option.label}
{option.disabled && option.searchLabel && (
<span className='sr-only'>{t('(已禁用)')}</span>
)}
</Tag> </Tag>
), ),
})} })}
@@ -3183,11 +3198,9 @@ const EditChannelModal = (props) => {
label={t('是否自动禁用')} label={t('是否自动禁用')}
checkedText={t('开')} checkedText={t('开')}
uncheckedText={t('关')} uncheckedText={t('关')}
onChange={(value) => setAutoBan(value)}
extraText={t( extraText={t(
'仅当自动禁用开启时有效,关闭后不会自动禁用该渠道', '仅当自动禁用开启时有效,关闭后不会自动禁用该渠道',
)} )}
initValue={autoBan}
/> />
<Form.TextArea <Form.TextArea
@@ -3415,7 +3428,7 @@ const EditChannelModal = (props) => {
{/* Header: Channel Extra Settings */} {/* Header: Channel Extra Settings */}
<div className='console-channel-section'> <div className='console-channel-section'>
<Avatar size='small' color='violet'> <Avatar size='small' color='violet'>
<IconBolt size={16} /> <Zap size={16} />
</Avatar> </Avatar>
<div> <div>
<Text className='text-lg font-medium'> <Text className='text-lg font-medium'>
@@ -3513,6 +3526,22 @@ const EditChannelModal = (props) => {
extraText={t('启用请求体透传功能')} extraText={t('启用请求体透传功能')}
/> />
<Form.Switch
field='pass_through_model_mapping_enabled'
label={t('透传时应用模型映射')}
checkedText={t('开')}
uncheckedText={t('关')}
onChange={(value) =>
handleChannelSettingsChange(
'pass_through_model_mapping_enabled',
value,
)
}
extraText={t(
'请求体透传时,使用本渠道模型重定向后的模型名发送给上游,其余字段按原请求转发。',
)}
/>
{(inputs.type === 1 || inputs.type === 3) && ( {(inputs.type === 1 || inputs.type === 3) && (
<Form.Switch <Form.Switch
field='chat_image_to_images_enabled' field='chat_image_to_images_enabled'
@@ -1,5 +1,8 @@
import { toGroupList } from '@/helpers/groupList';
import { I18N_TECHNICAL_TEXT } from '../../../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../../../i18n/technicalText.js';
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent'; import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import '../../../console/module-alignment.css';
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { import {
API, API,
@@ -18,29 +21,45 @@ import {
Spin, Spin,
Banner, Banner,
Card, Card,
Tag,
Avatar, Avatar,
Form, Form,
Row,
Col,
} from '@/components/ui'; } from '@/components/ui';
import { import { Bookmark, Code, Settings } from 'lucide-react';
IconSave,
IconClose,
IconBookmark,
IconUser,
IconCode,
IconSetting,
} from '@/components/ui/icons';
import { getChannelModels } from '../../../../helpers'; import { getChannelModels } from '../../../../helpers';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
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',
}; };
function TagEditorSection({ icon, color, title, description, children }) {
return (
<div>
<Card className='!rounded-2xl shadow-sm border-0 mb-6'>
<div className='console-channel-section'>
<Avatar size='small' color={color}>
{icon}
</Avatar>
<div>
<Text className='text-lg font-medium'>{title}</Text>
<Text type='secondary' className='block text-xs'>
{description}
</Text>
</div>
</div>
{children}
</Card>
</div>
);
}
const EditTagModal = (props) => { const EditTagModal = (props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const isMobile = useIsMobile();
const { visible, tag, handleClose, refresh } = props; const { visible, tag, handleClose, refresh } = props;
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [originModelOptions, setOriginModelOptions] = useState([]); const [originModelOptions, setOriginModelOptions] = useState([]);
@@ -159,6 +178,7 @@ const EditTagModal = (props) => {
}; };
const handleSave = async (values) => { const handleSave = async (values) => {
if (loading) return;
setLoading(true); setLoading(true);
const formVals = values || formApiRef.current?.getValues() || {}; const formVals = values || formApiRef.current?.getValues() || {};
let data = { tag }; let data = { tag };
@@ -170,8 +190,9 @@ const EditTagModal = (props) => {
} }
data.model_mapping = formVals.model_mapping; data.model_mapping = formVals.model_mapping;
} }
if (formVals.groups && formVals.groups.length > 0) { const groups = toGroupList(formVals.groups);
data.groups = formVals.groups.join(','); if (groups.length > 0) {
data.groups = groups.join(',');
} }
if (formVals.models && formVals.models.length > 0) { if (formVals.models && formVals.models.length > 0) {
data.models = formVals.models.join(','); data.models = formVals.models.join(',');
@@ -234,6 +255,8 @@ const EditTagModal = (props) => {
showSuccess(t('标签更新成功!')); showSuccess(t('标签更新成功!'));
refresh(); refresh();
handleClose(); handleClose();
} else if (res?.data) {
showError(res.data.message || t('操作失败'));
} }
} catch (error) { } catch (error) {
showError(error); showError(error);
@@ -254,6 +277,10 @@ const EditTagModal = (props) => {
}, [originModelOptions, inputs.models]); }, [originModelOptions, inputs.models]);
const onVisibilityChange = useEffectEvent(() => { const onVisibilityChange = useEffectEvent(() => {
if (visible) {
setCustomModel('');
formApiRef.current?.setValue('custom_model', '');
}
const fetchTagModels = async () => { const fetchTagModels = async () => {
if (!tag) return; if (!tag) return;
setLoading(true); setLoading(true);
@@ -319,6 +346,7 @@ const EditTagModal = (props) => {
setModelOptions(localModelOptions); setModelOptions(localModelOptions);
setCustomModel(''); setCustomModel('');
formApiRef.current?.setValue('custom_model', '');
handleInputChange('models', localModels); handleInputChange('models', localModels);
if (addedModels.length > 0) { if (addedModels.length > 0) {
@@ -335,44 +363,27 @@ const EditTagModal = (props) => {
return ( return (
<SideSheet <SideSheet
rootClassName='console-channel-drawer'
classNames={{ header: 'console-channel-editor-header' }}
placement='right' placement='right'
title={ title={t('编辑标签')}
<Space>
<Tag color='blue' shape='circle'>
{t('编辑')}
</Tag>
<Title heading={4} className='m-0'>
{t('编辑标签')}
</Title>
</Space>
}
bodyStyle={{ padding: '0' }} bodyStyle={{ padding: '0' }}
visible={visible} visible={visible}
width={600} width={isMobile ? '100%' : 600}
onCancel={handleClose} onCancel={handleClose}
footer={ footer={
<div className='flex justify-end'> <div className='console-channel-footer'>
<Space> <Button onClick={handleClose}>{t('取消')}</Button>
<Button <Button
theme='solid' theme='solid'
type='primary'
onClick={() => formApiRef.current?.submitForm()} onClick={() => formApiRef.current?.submitForm()}
loading={loading} loading={loading}
icon={<IconSave />}
> >
{t('保存')} {t('提交')}
</Button> </Button>
<Button
theme='light'
type='primary'
onClick={handleClose}
icon={<IconClose />}
>
{t('取消')}
</Button>
</Space>
</div> </div>
} }
closeIcon={null}
> >
<Form <Form
key={tag || 'edit'} key={tag || 'edit'}
@@ -382,56 +393,55 @@ const EditTagModal = (props) => {
> >
{() => ( {() => (
<Spin spinning={loading}> <Spin spinning={loading}>
<div className='p-2'> <div className='console-channel-sections p-2'>
<Card className='!rounded-2xl shadow-sm border-0 mb-6'> <TagEditorSection
{/* Header: Tag Info */} icon={<Bookmark size={16} />}
<div className='flex items-center mb-2'> color='blue'
<Avatar size='small' color='blue' className='mr-2 shadow-md'> title={t('标签信息')}
<IconBookmark size={16} /> description={t('标签的基本配置')}
</Avatar> >
<div>
<Text className='text-lg font-medium'>{t('标签信息')}</Text>
<div className='text-xs text-gray-600'>
{t('标签的基本配置')}
</div>
</div>
</div>
<Banner <Banner
type='warning' type='warning'
description={t('所有编辑均为覆盖操作,留空则不更改')} description={t('所有编辑均为覆盖操作,留空则不更改')}
className='!rounded-lg mb-4' className='!rounded-lg mb-4'
/> />
<div className='space-y-4'> <Row gutter={12}>
<Col xs={24} md={12}>
<Form.Input <Form.Input
field='new_tag' field='new_tag'
label={t('标签名称')} label={t('标签名称')}
placeholder={t('请输入新标签,留空则解散标签')} placeholder={t('请输入新标签,留空则解散标签')}
showClear
onChange={(value) => handleInputChange('new_tag', value)} onChange={(value) => handleInputChange('new_tag', value)}
/> />
</div> </Col>
</Card> <Col xs={24} md={12}>
<Form.Select
field='groups'
label={t('分组')}
placeholder={t(
'请选择可以使用该渠道的分组,留空则不更改',
)}
multiple
allowAdditions
additionLabel={t(
'请在系统设置页面编辑分组倍率以添加新的分组:',
)}
optionList={groupOptions}
style={{ width: '100%' }}
onChange={(value) => handleInputChange('groups', value)}
/>
</Col>
</Row>
</TagEditorSection>
<Card className='!rounded-2xl shadow-sm border-0 mb-6'> <TagEditorSection
{/* Header: Model Config */} icon={<Code size={16} />}
<div className='flex items-center mb-2'>
<Avatar
size='small'
color='purple' color='purple'
className='mr-2 shadow-md' title={t('模型配置')}
description={t('模型选择和映射设置')}
> >
<IconCode size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('模型配置')}</Text>
<div className='text-xs text-gray-600'>
{t('模型选择和映射设置')}
</div>
</div>
</div>
<div className='space-y-4'>
<Banner <Banner
type='info' type='info'
description={t( description={t(
@@ -457,6 +467,7 @@ const EditTagModal = (props) => {
label={t('自定义模型名称')} label={t('自定义模型名称')}
placeholder={t('输入自定义模型名称')} placeholder={t('输入自定义模型名称')}
onChange={(value) => setCustomModel(value.trim())} onChange={(value) => setCustomModel(value.trim())}
value={customModel}
suffix={ suffix={
<Button <Button
size='small' size='small'
@@ -511,28 +522,14 @@ const EditTagModal = (props) => {
</Space> </Space>
} }
/> />
</div> </TagEditorSection>
</Card>
<Card className='!rounded-2xl shadow-sm border-0 mb-6'> <TagEditorSection
{/* Header: Advanced Settings */} icon={<Settings size={16} />}
<div className='flex items-center mb-2'>
<Avatar
size='small'
color='orange' color='orange'
className='mr-2 shadow-md' title={t('高级设置')}
description={t('渠道的高级配置选项')}
> >
<IconSetting size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('高级设置')}</Text>
<div className='text-xs text-gray-600'>
{t('渠道的高级配置选项')}
</div>
</div>
</div>
<div className='space-y-4'>
<Form.TextArea <Form.TextArea
field='param_override' field='param_override'
label={t('参数覆盖')} label={t('参数覆盖')}
@@ -642,53 +639,14 @@ const EditTagModal = (props) => {
{t('不更改')} {t('不更改')}
</Text> </Text>
</div> </div>
<div>
<Text type='tertiary' size='small'> <Text type='tertiary' size='small'>
{t('支持变量:')} {t('支持变量:')} {t('渠道密钥')}:{' '}
</Text>
<div className='text-xs text-tertiary ml-2'>
<div>
{t('渠道密钥')}:{' '}
{I18N_TECHNICAL_TEXT.API_KEY_PLACEHOLDER} {I18N_TECHNICAL_TEXT.API_KEY_PLACEHOLDER}
</div> </Text>
</div>
</div>
</div> </div>
} }
/> />
</div> </TagEditorSection>
</Card>
<Card className='!rounded-2xl shadow-sm border-0'>
{/* Header: Group Settings */}
<div className='flex items-center mb-2'>
<Avatar size='small' color='green' className='mr-2 shadow-md'>
<IconUser size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('分组设置')}</Text>
<div className='text-xs text-gray-600'>
{t('用户分组配置')}
</div>
</div>
</div>
<div className='space-y-4'>
<Form.Select
field='groups'
label={t('分组')}
placeholder={t('请选择可以使用该渠道的分组,留空则不更改')}
multiple
allowAdditions
additionLabel={t(
'请在系统设置页面编辑分组倍率以添加新的分组:',
)}
optionList={groupOptions}
style={{ width: '100%' }}
onChange={(value) => handleInputChange('groups', value)}
/>
</div>
</Card>
</div> </div>
</Spin> </Spin>
)} )}
@@ -1,4 +1,7 @@
import React, { useState } from 'react'; import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useEffectEvent } from '@/hooks/common/useEffectEvent';
import { useLocalTableFilters } from '@/hooks/common/useLocalTableFilters';
import { useFilteredTableRows } from '@/hooks/common/useFilteredTableRows';
import { Table } from '@/components/ui'; import { Table } from '@/components/ui';
import { Modal, Button, Input, Tag, Typography, Select } from 'antd'; import { Modal, Button, Input, Tag, Typography, Select } from 'antd';
import { Search } from 'lucide-react'; import { Search } from 'lucide-react';
@@ -17,8 +20,6 @@ const ModelTestModal = ({
handleCloseModal, handleCloseModal,
isBatchTesting, isBatchTesting,
batchTestModels, batchTestModels,
modelSearchKeyword,
setModelSearchKeyword,
selectedModelKeys, selectedModelKeys,
setSelectedModelKeys, setSelectedModelKeys,
modelTestResults, modelTestResults,
@@ -33,14 +34,24 @@ const ModelTestModal = ({
}) => { }) => {
const [paginationSize, setPaginationSize] = useState(MODEL_TABLE_PAGE_SIZE); const [paginationSize, setPaginationSize] = useState(MODEL_TABLE_PAGE_SIZE);
const hasChannel = Boolean(currentTestChannel); const hasChannel = Boolean(currentTestChannel);
const models = const modelList = currentTestChannel?.models;
typeof currentTestChannel?.models === 'string' const models = useMemo(
? currentTestChannel.models.split(',').filter(Boolean) () =>
: []; typeof modelList === 'string' ? modelList.split(',').filter(Boolean) : [],
[modelList],
const filteredModels = models.filter((model) =>
model.toLowerCase().includes(modelSearchKeyword.toLowerCase()),
); );
const { draft, applied, changeFilters, submitSearch, resetFilters } =
useLocalTableFilters({ keyword: '' });
const resetOnClose = useEffectEvent(() => {
if (!showModelTestModal) resetFilters();
});
useEffect(() => resetOnClose(), [showModelTestModal, resetOnClose]);
const keyword = applied.keyword.toLowerCase();
const matches = useCallback(
(model) => model.toLowerCase().includes(keyword),
[keyword],
);
const filteredModels = useFilteredTableRows(models, matches);
const endpointTypeOptions = [ const endpointTypeOptions = [
{ value: '', label: t('自动检测') }, { value: '', label: t('自动检测') },
@@ -80,9 +91,7 @@ const ModelTestModal = ({
const handleSelectSuccess = () => { const handleSelectSuccess = () => {
if (!currentTestChannel) return; if (!currentTestChannel) return;
const successKeys = models const successKeys = filteredModels.filter((m) => {
.filter((m) => m.toLowerCase().includes(modelSearchKeyword.toLowerCase()))
.filter((m) => {
const result = modelTestResults[`${currentTestChannel.id}-${m}`]; const result = modelTestResults[`${currentTestChannel.id}-${m}`];
return result && result.success; return result && result.success;
}); });
@@ -224,11 +233,11 @@ const ModelTestModal = ({
<div className='model-test-toolbar'> <div className='model-test-toolbar'>
<Input <Input
placeholder={t('搜索模型...')} placeholder={t('搜索模型...')}
value={modelSearchKeyword} value={draft.keyword}
onChange={(event) => { onChange={(event) =>
setModelSearchKeyword(event.target.value); changeFilters({ keyword: event.target.value })
setModelTablePage(1); }
}} onPressEnter={submitSearch}
prefix={<Search size={16} />} prefix={<Search size={16} />}
allowClear allowClear
/> />
@@ -267,6 +276,7 @@ const ModelTestModal = ({
onChange: (keys) => setSelectedModelKeys(keys), onChange: (keys) => setSelectedModelKeys(keys),
}} }}
pagination={{ pagination={{
preservePage: true,
current: modelTablePage, current: modelTablePage,
pageSize: paginationSize, pageSize: paginationSize,
onChange: (page, size) => { onChange: (page, size) => {
@@ -1,7 +1,9 @@
import TableActionPopconfirm from '@/components/common/table/TableActionPopconfirm';
import { formatIdReference } from '../../../../helpers/safeDisplay'; import { formatIdReference } from '../../../../helpers/safeDisplay';
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent'; import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { useFilterSearch } from '@/hooks/common/useFilterSearch';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { import {
Modal, Modal,
@@ -54,14 +56,22 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
// Filter states // Filter states
const [statusFilter, setStatusFilter] = useState(null); // null=all, 1=enabled, 2=manual_disabled, 3=auto_disabled const [statusFilter, setStatusFilter] = useState(null); // null=all, 1=enabled, 2=manual_disabled, 3=auto_disabled
const appliedStatus = useRef(null);
const activeRequest = useRef(null);
const cancelQuery = () => activeRequest.current?.abort();
// Load key status data // Load key status data
const loadKeyStatus = async ( const loadKeyStatus = async (
page = currentPage, page = currentPage,
size = pageSize, size = pageSize,
status = statusFilter, status = appliedStatus.current,
) => { ) => {
if (!channel?.id) return; if (!channel?.id) return;
cancelQuery();
const controller = new AbortController();
activeRequest.current = controller;
const { signal } = controller;
setLoading(true); setLoading(true);
try { try {
const requestData = { const requestData = {
@@ -76,13 +86,16 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
requestData.status = status; requestData.status = status;
} }
const res = await API.post('/api/channel/multi_key/manage', requestData); const res = await API.post('/api/channel/multi_key/manage', requestData, {
signal,
});
if (signal.aborted) return;
if (res.data.success) { if (res.data.success) {
const data = res.data.data; const data = res.data.data;
setKeyStatusList(data.keys || []); setKeyStatusList(data.keys || []);
setTotal(data.total || 0); setTotal(data.total || 0);
setCurrentPage(data.page || 1); setCurrentPage(page);
setPageSize(data.page_size || 10); setPageSize(data.page_size || 10);
setTotalPages(data.total_pages || 0); setTotalPages(data.total_pages || 0);
@@ -94,13 +107,19 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
showError(res.data.message); showError(res.data.message);
} }
} catch (error) { } catch (error) {
if (signal.aborted) return;
console.error(error); console.error(error);
showError(t('获取密钥状态失败')); if (!error?.isAxiosError) showError(t('获取密钥状态失败'));
} finally { } finally {
setLoading(false); if (!signal.aborted) setLoading(false);
} }
}; };
const { scheduleSearch, cancelPendingSearch } = useFilterSearch((status) => {
appliedStatus.current = status;
return loadKeyStatus(currentPage, pageSize, status);
}, cancelQuery);
// Disable a specific key // Disable a specific key
const handleDisableKey = async (keyIndex) => { const handleDisableKey = async (keyIndex) => {
const operationId = `disable_${keyIndex}`; const operationId = `disable_${keyIndex}`;
@@ -247,6 +266,7 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
showSuccess(t('密钥已删除')); showSuccess(t('密钥已删除'));
await loadKeyStatus(currentPage, pageSize); // Reload current page await loadKeyStatus(currentPage, pageSize); // Reload current page
onRefresh && onRefresh(); // Refresh parent component onRefresh && onRefresh(); // Refresh parent component
return true;
} else { } else {
showError(res.data.message); showError(res.data.message);
} }
@@ -255,6 +275,7 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
} finally { } finally {
setOperationLoading((prev) => ({ ...prev, [operationId]: false })); setOperationLoading((prev) => ({ ...prev, [operationId]: false }));
} }
return false;
}; };
// Handle page size change // Handle page size change
@@ -266,9 +287,9 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
// Handle status filter change // Handle status filter change
const handleStatusFilterChange = (status) => { const handleStatusFilterChange = (status) => {
setStatusFilter(status); const value = status ?? null;
setCurrentPage(1); // Reset to first page when filter changes setStatusFilter(value);
loadKeyStatus(1, pageSize, status); scheduleSearch(value);
}; };
// Effect to load data when modal opens // Effect to load data when modal opens
@@ -277,6 +298,7 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
setCurrentPage(1); // Reset to first page when opening setCurrentPage(1); // Reset to first page when opening
loadKeyStatus(1, pageSize); loadKeyStatus(1, pageSize);
} }
return cancelPendingSearch;
}); });
useEffect( useEffect(
() => onVisibilityChange(), () => onVisibilityChange(),
@@ -293,6 +315,7 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
setEnabledCount(0); setEnabledCount(0);
setManualDisabledCount(0); setManualDisabledCount(0);
setAutoDisabledCount(0); setAutoDisabledCount(0);
appliedStatus.current = null;
setStatusFilter(null); // Reset filter setStatusFilter(null); // Reset filter
} }
}, [visible]); }, [visible]);
@@ -414,21 +437,21 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
{t('启用')} {t('启用')}
</Button> </Button>
)} )}
<Popconfirm <TableActionPopconfirm
title={t('确定要删除此密钥吗?')} title={t('确定要删除此密钥吗?')}
content={t('此操作不可撤销,将永久删除该密钥')} content={t('此操作不可撤销,将永久删除该密钥')}
onConfirm={() => handleDeleteKey(record.index)} onConfirm={() => handleDeleteKey(record.index)}
okType={'danger'}
position={'topRight'} position={'topRight'}
> >
<Button <Button
type='danger' type='link'
danger
size='small' size='small'
loading={operationLoading[`delete_${record.index}`]} loading={operationLoading[`delete_${record.index}`]}
> >
{t('删除')} {t('删除')}
</Button> </Button>
</Popconfirm> </TableActionPopconfirm>
</Space> </Space>
), ),
}, },
@@ -679,6 +702,7 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
columns={columns} columns={columns}
dataSource={keyStatusList} dataSource={keyStatusList}
pagination={{ pagination={{
preservePage: true,
currentPage: currentPage, currentPage: currentPage,
pageSize: pageSize, pageSize: pageSize,
total: total, total: total,
+5 -11
View File
@@ -4,19 +4,19 @@ import FilterSearchButton from '../../common/table/FilterSearchButton';
import { useFilterSearch } from '../../../hooks/common/useFilterSearch'; import { useFilterSearch } from '../../../hooks/common/useFilterSearch';
import '../../common/table/log-filters.css'; import '../../common/table/log-filters.css';
import { DATE_RANGE_PRESETS } from '../../../constants/console.constants';
const MjLogsFilters = ({ const MjLogsFilters = ({
formInitValues, formInitValues,
setFormApi, setFormApi,
refresh, refresh,
activePage,
formApi, formApi,
loading, loading,
isAdminUser, isAdminUser,
t, t,
}) => { }) => {
const { scheduleSearch, submitSearch, cancelPendingSearch } = const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
useFilterSearch(refresh); (_, signal) => refresh({ page: activePage, signal }),
);
return ( return (
<Form <Form
initValues={formInitValues} initValues={formInitValues}
@@ -38,14 +38,10 @@ const MjLogsFilters = ({
field='dateRange' field='dateRange'
label={t('时间范围')} label={t('时间范围')}
className='w-full' className='w-full'
tableFilter
type='dateTimeRange' type='dateTimeRange'
placeholder={[t('开始时间'), t('结束时间')]} placeholder={[t('开始时间'), t('结束时间')]}
showClear showClear
presets={DATE_RANGE_PRESETS.map((preset) => ({
text: t(preset.text),
start: preset.start(),
end: preset.end(),
}))}
/> />
</div> </div>
@@ -75,9 +71,7 @@ const MjLogsFilters = ({
if (formApi) { if (formApi) {
formApi.reset(); formApi.reset();
cancelPendingSearch(); cancelPendingSearch();
setTimeout(() => {
refresh(); refresh();
}, 100);
} }
}} }}
> >
+1
View File
@@ -34,6 +34,7 @@ const MjLogsPage = () => {
/> />
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
preservePage: true,
currentPage: mjLogsData.activePage, currentPage: mjLogsData.activePage,
pageSize: mjLogsData.pageSize, pageSize: mjLogsData.pageSize,
total: mjLogsData.logCount, total: mjLogsData.logCount,
@@ -39,7 +39,7 @@ const PricingVendors = ({
...vendorsList.map((vendor) => ({ ...vendorsList.map((vendor) => ({
value: vendor.name, value: vendor.name,
label: vendor.name, label: vendor.name,
icon: vendor.icon ? getLobeHubIcon(vendor.icon, 18) : null, icon: vendor.icon ? getLobeHubIcon(vendor.icon, 16) : null,
})), })),
]; ];
}, [vendorsMap, availableVendorNames, t]); }, [vendorsMap, availableVendorNames, t]);
@@ -338,6 +338,9 @@ html.dark .mm-theme {
} }
.mm-filter-group .ant-btn { .mm-filter-group .ant-btn {
display: inline-flex;
align-items: center;
justify-content: center;
height: auto; height: auto;
min-height: 28px; min-height: 28px;
padding: 3px 9px; padding: 3px 9px;
@@ -348,6 +351,7 @@ html.dark .mm-theme {
max-width: 100%; max-width: 100%;
box-shadow: none; box-shadow: none;
line-height: 1.45; line-height: 1.45;
text-align: center;
} }
.mm-filter-group .ant-btn.mm-selected { .mm-filter-group .ant-btn.mm-selected {
@@ -400,6 +404,17 @@ html.dark .mm-theme {
padding: var(--mm-filter-logo-padding); padding: var(--mm-filter-logo-padding);
} }
.mm-filter-group .mm-logo :is(svg, img) {
display: block;
max-width: 16px;
max-height: 16px;
}
.mm-filter-group .mm-logo + span {
position: relative;
top: 1px;
}
html.dark .mm-filter-group .mm-logo { html.dark .mm-filter-group .mm-logo {
color: var(--mm-filter-logo-ink); color: var(--mm-filter-logo-ink);
} }
@@ -1,4 +1,5 @@
import React from 'react'; import React from 'react';
import TableGroupTags from '@/components/common/table/TableGroupTags';
import { Empty, Table, Tag, Tooltip } from 'antd'; import { Empty, Table, Tag, Tooltip } from 'antd';
import { ChevronRight } from 'lucide-react'; import { ChevronRight } from 'lucide-react';
import { import {
@@ -111,7 +112,7 @@ const ModelPricingTable = ({
</span> </span>
) : ( ) : (
<span className='mm-detail-group'> <span className='mm-detail-group'>
{row.group} <TableGroupTags groups={row.group} />
{row.discountText && ( {row.discountText && (
<Tooltip <Tooltip
title={t( title={t(
@@ -1,7 +1,9 @@
import { TABLE_GROUP_COLUMN_WIDTH } from '@/components/common/table/TableGroupTags';
import { confirmTableAction } from '@/components/common/table/confirmTableAction';
import { Copy as ActionCopy } from '@/components/common/icons/ActionIcons'; import { Copy as ActionCopy } from '@/components/common/icons/ActionIcons';
import React from 'react'; import React from 'react';
import { Button as AntButton, Tooltip as AntTooltip } from 'antd'; import { Button as AntButton, Tooltip as AntTooltip } from 'antd';
import { Button, Space, Tag, Modal, Tooltip } from '@/components/ui'; import { Button, Space, Tag, Tooltip } from '@/components/ui';
import { import {
timestamp2string, timestamp2string,
getLobeHubIcon, getLobeHubIcon,
@@ -94,12 +96,17 @@ const renderCategories = (categories, t, categoryNames) => {
// Render groups (enable_groups) // Render groups (enable_groups)
const renderGroups = (groups) => { const renderGroups = (groups) => {
if (!groups || groups.length === 0) return '-'; if (!groups || groups.length === 0) return '-';
return renderLimitedItems({ return (
<span className='table-group-tags'>
{renderLimitedItems({
items: groups, items: groups,
renderItem: (g, idx) => ( renderItem: (group, index) => (
<React.Fragment key={idx}>{renderGroup(g)}</React.Fragment> <React.Fragment key={index}>{renderGroup(group)}</React.Fragment>
), ),
}); wrap: false,
})}
</span>
);
}; };
// Render tags // Render tags
@@ -261,14 +268,15 @@ const renderOperations = (
danger danger
size='small' size='small'
onClick={() => { onClick={() => {
Modal.confirm({ confirmTableAction({
title: t('确定是否要删除此模型?'), title: t('确定是否要删除此模型?'),
content: t('此修改将不可逆'), content: t('此修改将不可逆'),
onOk: () => { okType: 'danger',
(async () => { focusable: { autoFocusButton: 'cancel' },
await manageModel(record.id, 'delete', record); onOk: async () => {
if (!(await manageModel(record.id, 'delete', record)))
return false;
await refresh(); await refresh();
})();
}, },
}); });
}} }}
@@ -407,6 +415,7 @@ export const getModelsColumns = ({
{ {
title: t('可用分组'), title: t('可用分组'),
dataIndex: 'enable_groups', dataIndex: 'enable_groups',
width: TABLE_GROUP_COLUMN_WIDTH,
render: renderGroups, render: renderGroups,
}, },
{ {
@@ -9,12 +9,14 @@ const ModelsFilters = ({
formInitValues, formInitValues,
setFormApi, setFormApi,
searchModels, searchModels,
activePage,
setSelectedKeys,
loading, loading,
searching, searching,
t, t,
}) => { }) => {
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch( const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
() => searchModels(), (_, signal) => searchModels(activePage, undefined, signal),
); );
// Handle form reset and immediate search // Handle form reset and immediate search
@@ -24,9 +26,8 @@ const ModelsFilters = ({
if (!formApiRef.current) return; if (!formApiRef.current) return;
formApiRef.current.reset(); formApiRef.current.reset();
cancelPendingSearch(); cancelPendingSearch();
setTimeout(() => { setSelectedKeys([]);
searchModels(); searchModels(1);
}, 100);
}; };
return ( return (
+3
View File
@@ -86,6 +86,8 @@ const ModelsPage = () => {
formInitValues={formInitValues} formInitValues={formInitValues}
setFormApi={setFormApi} setFormApi={setFormApi}
searchModels={searchModels} searchModels={searchModels}
activePage={modelsData.activePage}
setSelectedKeys={setSelectedKeys}
loading={loading} loading={loading}
searching={searching} searching={searching}
t={t} t={t}
@@ -114,6 +116,7 @@ const ModelsPage = () => {
</div> </div>
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
preservePage: true,
currentPage: modelsData.activePage, currentPage: modelsData.activePage,
pageSize: modelsData.pageSize, pageSize: modelsData.pageSize,
total: modelsData.modelCount, total: modelsData.modelCount,
@@ -1,6 +1,8 @@
import { useLocalTableFilters } from '@/hooks/common/useLocalTableFilters';
import { useFilteredTableRows } from '@/hooks/common/useFilteredTableRows';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent'; import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useEffect, useState } from 'react'; import React, { useCallback, useEffect, useState } from 'react';
import { import {
Modal, Modal,
Table, Table,
@@ -23,7 +25,9 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
const [paginationSize, setPaginationSize] = useState(MODEL_TABLE_PAGE_SIZE); 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 { draft, applied, changeFilters, submitSearch, resetFilters } =
useLocalTableFilters({ searchKeyword: '' });
const keyword = applied.searchKeyword.toLowerCase();
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const isMobile = useIsMobile(); const isMobile = useIsMobile();
@@ -45,7 +49,7 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
const onVisibilityChange = useEffectEvent(() => { const onVisibilityChange = useEffectEvent(() => {
if (visible) { if (visible) {
fetchMissing(); fetchMissing();
setSearchKeyword(''); resetFilters();
setCurrentPage(1); setCurrentPage(1);
} else { } else {
setMissingModels([]); setMissingModels([]);
@@ -54,9 +58,11 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
useEffect(() => onVisibilityChange(), [onVisibilityChange, visible]); useEffect(() => onVisibilityChange(), [onVisibilityChange, visible]);
// 过滤和分页逻辑 // 过滤和分页逻辑
const filteredModels = missingModels.filter((model) => const matches = useCallback(
model.toLowerCase().includes(searchKeyword.toLowerCase()), (model) => model.toLowerCase().includes(keyword),
[keyword],
); );
const filteredModels = useFilteredTableRows(missingModels, matches);
const dataSource = (() => { const dataSource = (() => {
const start = (currentPage - 1) * paginationSize; const start = (currentPage - 1) * paginationSize;
@@ -137,11 +143,9 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
<div className='flex items-center justify-end gap-2 w-full mb-4'> <div className='flex items-center justify-end gap-2 w-full mb-4'>
<Input <Input
placeholder={t('搜索模型...')} placeholder={t('搜索模型...')}
value={searchKeyword} value={draft.searchKeyword}
onChange={(v) => { onChange={(searchKeyword) => changeFilters({ searchKeyword })}
setSearchKeyword(v); onEnterPress={submitSearch}
setCurrentPage(1);
}}
className='!w-full' className='!w-full'
prefix={<IconSearch />} prefix={<IconSearch />}
showClear showClear
@@ -149,7 +153,7 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
</div> </div>
{/* 表格 */} {/* 表格 */}
{filteredModels.length > 0 ? ( {filteredModels.length > 0 || currentPage > 1 ? (
<Table <Table
// 列宽合计远超窄屏视口;没有 scroll 时表格会压缩到 min-content 硬塞进去, // 列宽合计远超窄屏视口;没有 scroll 时表格会压缩到 min-content 硬塞进去,
// 末尾的操作列落在视口外,且 iOS 上滚动条不可见、毫无可拖动提示 // 末尾的操作列落在视口外,且 iOS 上滚动条不可见、毫无可拖动提示
@@ -157,6 +161,7 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
columns={columns} columns={columns}
dataSource={dataSource} dataSource={dataSource}
pagination={{ pagination={{
preservePage: true,
currentPage: currentPage, currentPage: currentPage,
pageSize: paginationSize, pageSize: paginationSize,
total: filteredModels.length, total: filteredModels.length,
@@ -178,7 +183,7 @@ const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
/> />
} }
description={ description={
searchKeyword ? t('未找到匹配的模型') : t('暂无缺失模型') keyword ? t('未找到匹配的模型') : t('暂无缺失模型')
} }
style={{ padding: 20 }} style={{ padding: 20 }}
/> />
@@ -1,3 +1,4 @@
import TableActionPopconfirm from '@/components/common/table/TableActionPopconfirm';
import '../../../console/module-alignment.css'; import '../../../console/module-alignment.css';
import React, { useState, useEffect, useCallback } from 'react'; import React, { useState, useEffect, useCallback } from 'react';
import { import {
@@ -6,7 +7,6 @@ import {
Typography, Typography,
Space, Space,
Tag, Tag,
Popconfirm,
Card, Card,
Avatar, Avatar,
Spin, Spin,
@@ -71,12 +71,14 @@ const PrefillGroupManagement = ({ visible, onClose }) => {
if (res.data.success) { if (res.data.success) {
showSuccess(t('删除成功')); showSuccess(t('删除成功'));
loadGroups(); loadGroups();
return true;
} else { } else {
showError(res.data.message || t('删除失败')); showError(res.data.message || t('删除失败'));
} }
} catch (error) { } catch (error) {
showError(t('删除失败')); showError(t('删除失败'));
} }
return false;
}; };
// 编辑组 // 编辑组
@@ -184,14 +186,14 @@ const PrefillGroupManagement = ({ visible, onClose }) => {
<Button type='link' size='small' onClick={() => handleEdit(record)}> <Button type='link' size='small' onClick={() => handleEdit(record)}>
{t('编辑')} {t('编辑')}
</Button> </Button>
<Popconfirm <TableActionPopconfirm
title={t('确定删除此组?')} title={t('确定删除此组?')}
onConfirm={() => deleteGroup(record.id)} onConfirm={() => deleteGroup(record.id)}
> >
<Button size='small' type='link' danger> <Button size='small' type='link' danger>
{t('删除')} {t('删除')}
</Button> </Button>
</Popconfirm> </TableActionPopconfirm>
</Space> </Space>
), ),
}, },
@@ -1,3 +1,6 @@
import { useLocalTableFilters } from '@/hooks/common/useLocalTableFilters';
import { useFilteredTableRows } from '@/hooks/common/useFilteredTableRows';
import { useEffectEvent } from '@/hooks/common/useEffectEvent';
import React, { useEffect, useMemo, useState, useCallback } from 'react'; import React, { useEffect, useMemo, useState, useCallback } from 'react';
import { import {
Modal, Modal,
@@ -39,7 +42,9 @@ const UpstreamConflictModal = ({
const [selections, setSelections] = useState({}); const [selections, setSelections] = useState({});
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const [searchKeyword, setSearchKeyword] = useState(''); const { draft, applied, changeFilters, submitSearch, resetFilters } =
useLocalTableFilters({ searchKeyword: '' });
const keyword = applied.searchKeyword.toLowerCase();
const formatValue = (v) => { const formatValue = (v) => {
if (v === null || v === undefined) return '-'; if (v === null || v === undefined) return '-';
@@ -51,6 +56,7 @@ const UpstreamConflictModal = ({
} }
}; };
const resetSearch = useEffectEvent(resetFilters);
useEffect(() => { useEffect(() => {
if (visible) { if (visible) {
const init = {}; const init = {};
@@ -59,11 +65,11 @@ const UpstreamConflictModal = ({
}); });
setSelections(init); setSelections(init);
setCurrentPage(1); setCurrentPage(1);
setSearchKeyword(''); resetSearch();
} else { } else {
setSelections({}); setSelections({});
} }
}, [visible, conflicts]); }, [visible, conflicts, resetSearch]);
const toggleField = useCallback((modelName, field, checked) => { const toggleField = useCallback((modelName, field, checked) => {
setSelections((prev) => { setSelections((prev) => {
@@ -87,13 +93,11 @@ const UpstreamConflictModal = ({
[conflicts], [conflicts],
); );
const filteredDataSource = useMemo(() => { const matches = useCallback(
const kw = (searchKeyword || '').toLowerCase(); (item) => (item.model_name || '').toLowerCase().includes(keyword),
if (!kw) return dataSource; [keyword],
return dataSource.filter((item) =>
(item.model_name || '').toLowerCase().includes(kw),
); );
}, [dataSource, searchKeyword]); const filteredDataSource = useFilteredTableRows(dataSource, matches);
// 列头工具:当前过滤范围内可操作的行集合/勾选状态/批量设置 // 列头工具:当前过滤范围内可操作的行集合/勾选状态/批量设置
const getPresentRowsForField = useCallback( const getPresentRowsForField = useCallback(
@@ -261,21 +265,20 @@ const UpstreamConflictModal = ({
<div className='flex items-center justify-end gap-2 w-full mb-4'> <div className='flex items-center justify-end gap-2 w-full mb-4'>
<Input <Input
placeholder={t('搜索模型...')} placeholder={t('搜索模型...')}
value={searchKeyword} value={draft.searchKeyword}
onChange={(v) => { onChange={(searchKeyword) => changeFilters({ searchKeyword })}
setSearchKeyword(v); onEnterPress={submitSearch}
setCurrentPage(1);
}}
className='!w-full' className='!w-full'
prefix={<IconSearch />} prefix={<IconSearch />}
showClear showClear
/> />
</div> </div>
{filteredDataSource.length > 0 ? ( {filteredDataSource.length > 0 || currentPage > 1 ? (
<Table <Table
columns={columns} columns={columns}
dataSource={pagedDataSource} dataSource={pagedDataSource}
pagination={{ pagination={{
preservePage: true,
currentPage: currentPage, currentPage: currentPage,
pageSize: paginationSize, pageSize: paginationSize,
total: filteredDataSource.length, total: filteredDataSource.length,
@@ -289,9 +292,7 @@ const UpstreamConflictModal = ({
/> />
) : ( ) : (
<Empty <Empty
description={ description={keyword ? t('未找到匹配的模型') : t('无冲突项')}
searchKeyword ? t('未找到匹配的模型') : t('无冲突项')
}
className='p-6' className='p-6'
/> />
)} )}
@@ -1,17 +1,30 @@
import React from 'react'; import React, { useState } from 'react';
import { Button } from 'antd';
import { Copy, Plus, Trash2 } from '@/components/common/icons/ActionIcons'; import { Copy, Plus, Trash2 } from '@/components/common/icons/ActionIcons';
import { Button } from '@/components/ui';
import { isAdmin } from '../../../helpers';
const RedemptionsActions = ({ const RedemptionsActions = ({
canQuery,
canCreate,
canDelete,
selectedKeys, selectedKeys,
busy,
setEditingRedemption, setEditingRedemption,
setShowEdit, setShowEdit,
batchCopyRedemptions, batchCopyRedemptions,
batchDeleteRedemptions, batchDeleteRedemptions,
t, t,
}) => { }) => {
// Add new redemption code const [copying, setCopying] = useState(false);
const handleCopy = async () => {
setCopying(true);
try {
await batchCopyRedemptions();
} finally {
setCopying(false);
}
};
const handleAddRedemption = () => { const handleAddRedemption = () => {
setEditingRedemption({ setEditingRedemption({
id: undefined, id: undefined,
@@ -21,23 +34,33 @@ const RedemptionsActions = ({
return ( return (
<div className='console-list-tool-actions'> <div className='console-list-tool-actions'>
<Button icon={<Copy size={16} />} onClick={batchCopyRedemptions}> {canQuery && (
<Button
icon={<Copy size={16} aria-hidden />}
disabled={busy || selectedKeys.length === 0}
loading={copying}
onClick={handleCopy}
>
{t('复制所选兑换码到剪贴板')} {t('复制所选兑换码到剪贴板')}
</Button> </Button>
)}
{isAdmin() && ( {canDelete && (
<Button <Button
type='danger' danger
icon={<Trash2 size={16} />} className='redemption-invalid-action'
disabled={busy}
icon={<Trash2 size={16} aria-hidden />}
onClick={batchDeleteRedemptions} onClick={batchDeleteRedemptions}
> >
{t('清除失效兑换码')} {t('清除失效兑换码')}
</Button> </Button>
)} )}
{isAdmin() && ( {canCreate && (
<Button <Button
type='primary' type='primary'
icon={<Plus size={16} />} className='console-create-action'
icon={<Plus size={16} aria-hidden />}
onClick={handleAddRedemption} onClick={handleAddRedemption}
> >
{t('添加兑换码')} {t('添加兑换码')}
@@ -1,12 +1,6 @@
import React from 'react'; import React from 'react';
import { Tag, Button, Space, Popover, Dropdown } from '@/components/ui'; import { Button, Tag, Tooltip } from 'antd';
import { IconMore } from '@/components/ui/icons'; import { renderQuota, timestamp2string } from '../../../helpers';
import {
renderQuota,
timestamp2string,
isAdmin,
hoverOrClickTrigger,
} from '../../../helpers';
import { import {
REDEMPTION_STATUS, REDEMPTION_STATUS,
REDEMPTION_STATUS_MAP, REDEMPTION_STATUS_MAP,
@@ -27,156 +21,105 @@ export const isExpired = (record) => {
/** /**
* Render timestamp * Render timestamp
*/ */
const renderTimestamp = (timestamp) => { export const formatRedemptionExpiry = (timestamp, t) =>
return <>{timestamp2string(timestamp)}</>; timestamp === 0 ? t('永不过期') : timestamp2string(timestamp);
};
/** /**
* Render redemption code status * Render redemption code status
*/ */
const renderStatus = (status, record, t) => { export const renderRedemptionStatus = (status, record, t) => {
if (isExpired(record)) { if (isExpired(record)) {
return ( return <Tag color='warning'>{t('已过期')}</Tag>;
<Tag color='orange' shape='circle'>
{t('已过期')}
</Tag>
);
} }
const statusConfig = REDEMPTION_STATUS_MAP[status]; const statusConfig = REDEMPTION_STATUS_MAP[status];
if (statusConfig) { if (statusConfig) {
return ( return <Tag color={statusConfig.color}>{t(statusConfig.text)}</Tag>;
<Tag color={statusConfig.color} shape='circle'>
{t(statusConfig.text)}
</Tag>
);
} }
return ( return <Tag>{t('未知状态')}</Tag>;
<Tag color='black' shape='circle'>
{t('未知状态')}
</Tag>
);
}; };
/** /**
* Get redemption code table column definitions * Get redemption code table column definitions
*/ */
export const getRedemptionsColumns = ({ export const getRedemptionsColumns = ({
canEdit,
canDelete,
t, t,
manageRedemption, manageRedemption,
copyText, copyText,
setEditingRedemption, setEditingRedemption,
setShowEdit, setShowEdit,
refresh, showDetails,
redemptions,
activePage,
showDeleteRedemptionModal, showDeleteRedemptionModal,
}) => { }) => {
return [ return [
{ {
title: t('ID'), title: t('ID'),
dataIndex: 'id', dataIndex: 'id',
width: 72,
}, },
{ {
title: t('名称'), title: t('名称'),
dataIndex: 'name', dataIndex: 'name',
width: 224,
ellipsis: { showTitle: false },
render: (name) => (
<Tooltip title={name}>
<span>{name}</span>
</Tooltip>
),
}, },
{ {
title: t('状态'), title: t('状态'),
dataIndex: 'status', dataIndex: 'status',
key: 'status', width: 120,
render: (text, record) => { render: (status, record) => renderRedemptionStatus(status, record, t),
return <div>{renderStatus(text, record, t)}</div>;
},
}, },
{ {
title: t('额度'), title: t('额度'),
dataIndex: 'quota', dataIndex: 'quota',
render: (text) => { width: 128,
return ( align: 'right',
<div> render: (quota) => renderQuota(parseInt(quota)),
<Tag color='grey' shape='circle'>
{renderQuota(parseInt(text))}
</Tag>
</div>
);
},
}, },
{ {
title: t('创建时间'), title: t('创建时间'),
dataIndex: 'created_time', dataIndex: 'created_time',
render: (text) => { width: 180,
return <div>{renderTimestamp(text)}</div>; render: (timestamp) => timestamp2string(timestamp),
},
}, },
{ {
title: t('过期时间'), title: t('过期时间'),
dataIndex: 'expired_time', dataIndex: 'expired_time',
render: (text) => { width: 180,
return <div>{text === 0 ? t('永不过期') : renderTimestamp(text)}</div>; render: (timestamp) => formatRedemptionExpiry(timestamp, t),
},
}, },
{ {
title: t('兑换人ID'), title: t('兑换人ID'),
dataIndex: 'used_user_id', dataIndex: 'used_user_id',
render: (text) => { width: 128,
return <div>{text === 0 ? t('无') : text}</div>; render: (id) => (id === 0 ? t('无') : id),
},
}, },
{ {
title: t('操作'), title: t('操作'),
dataIndex: 'operate', dataIndex: 'operate',
fixed: 'right', fixed: 'right',
width: 205,
render: (text, record) => { render: (text, record) => {
// Create dropdown menu items for more operations const isUnused = record.status === REDEMPTION_STATUS.UNUSED;
const moreMenuItems = [
{
node: 'item',
name: t('删除'),
type: 'danger',
onClick: () => {
showDeleteRedemptionModal(record);
},
},
];
if (record.status === REDEMPTION_STATUS.UNUSED && !isExpired(record)) {
moreMenuItems.push({
node: 'item',
name: t('禁用'),
type: 'warning',
onClick: () => {
manageRedemption(record.id, REDEMPTION_ACTIONS.DISABLE, record);
},
});
} else if (!isExpired(record)) {
moreMenuItems.push({
node: 'item',
name: t('启用'),
type: 'secondary',
onClick: () => {
manageRedemption(record.id, REDEMPTION_ACTIONS.ENABLE, record);
},
disabled: record.status === REDEMPTION_STATUS.USED,
});
}
return ( return (
<Space> <div className='console-module-row-actions redemption-row-actions'>
<Popover <Button
// 触屏必须 click:这是查看兑换码明文的唯一入口 type='link'
trigger={hoverOrClickTrigger()} size='small'
content={record.key} onClick={() => showDetails(record)}
style={{ padding: 20 }}
position='top'
> >
<Button type='tertiary' size='small'>
{t('查看')} {t('查看')}
</Button> </Button>
</Popover>
<Button <Button
type='link'
size='small' size='small'
onClick={async () => { onClick={async () => {
await copyText(record.key); await copyText(record.key);
@@ -184,29 +127,50 @@ export const getRedemptionsColumns = ({
> >
{t('复制')} {t('复制')}
</Button> </Button>
{isAdmin() && ( {canEdit && (
<> <>
<Button <Button
type='tertiary' type='link'
size='small' size='small'
onClick={() => { onClick={() => {
setEditingRedemption(record); setEditingRedemption(record);
setShowEdit(true); setShowEdit(true);
}} }}
disabled={record.status !== REDEMPTION_STATUS.UNUSED} disabled={!isUnused}
> >
{t('编辑')} {t('编辑')}
</Button> </Button>
<Dropdown {!isExpired(record) && (
trigger='click' <Button
position='bottomRight' type='link'
menu={moreMenuItems} size='small'
disabled={record.status === REDEMPTION_STATUS.USED}
onClick={() =>
manageRedemption(
record.id,
isUnused
? REDEMPTION_ACTIONS.DISABLE
: REDEMPTION_ACTIONS.ENABLE,
record,
)
}
> >
<Button type='tertiary' size='small' icon={<IconMore />} /> {isUnused ? t('禁用') : t('启用')}
</Dropdown> </Button>
)}
</> </>
)} )}
</Space> {canDelete && (
<Button
type='link'
size='small'
danger
onClick={() => showDeleteRedemptionModal(record)}
>
{t('删除')}
</Button>
)}
</div>
); );
}, },
}, },
@@ -1,4 +1,5 @@
import React, { useRef } from 'react'; import React, { useRef } from 'react';
import { useFilterSearch } from '../../../hooks/common/useFilterSearch';
import { Form } from '@/components/ui'; import { Form } from '@/components/ui';
import { ConsoleSearchActions } from '../../console/ConsolePrimitives'; import { ConsoleSearchActions } from '../../console/ConsolePrimitives';
import { IconSearch } from '@/components/ui/icons'; import { IconSearch } from '@/components/ui/icons';
@@ -7,19 +8,24 @@ const RedemptionsFilters = ({
formInitValues, formInitValues,
setFormApi, setFormApi,
searchRedemptions, searchRedemptions,
activePage,
setSelectedKeys,
loading, loading,
searching, searching,
t, t,
}) => { }) => {
// Handle form reset and immediate search // Handle form reset and immediate search
const formApiRef = useRef(null); const formApiRef = useRef(null);
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
(_, signal) => searchRedemptions(activePage, signal),
);
const handleReset = () => { const handleReset = () => {
if (!formApiRef.current) return; if (!formApiRef.current) return;
formApiRef.current.reset(); formApiRef.current.reset();
setTimeout(() => { cancelPendingSearch();
searchRedemptions(); setSelectedKeys([]);
}, 100); searchRedemptions(1);
}; };
return ( return (
@@ -29,7 +35,8 @@ const RedemptionsFilters = ({
setFormApi(api); setFormApi(api);
formApiRef.current = api; formApiRef.current = api;
}} }}
onSubmit={searchRedemptions} onSubmit={submitSearch}
onValueChange={scheduleSearch}
allowEmpty={true} allowEmpty={true}
autoComplete='off' autoComplete='off'
layout='vertical' layout='vertical'
@@ -1,20 +1,21 @@
import React, { useMemo, useState } from 'react'; import React, { useState } from 'react';
import TableEmpty from '../../common/table/TableEmpty'; import TableEmpty from '../../common/table/TableEmpty';
import CardTable from '../../common/ui/CardTable'; import CardTable from '../../common/ui/CardTable';
import { getRedemptionsColumns } from './RedemptionsColumnDefs'; import { getRedemptionsColumns } from './RedemptionsColumnDefs';
import DeleteRedemptionModal from './modals/DeleteRedemptionModal'; import DeleteRedemptionModal from './modals/DeleteRedemptionModal';
import RedemptionDetailsModal from './modals/RedemptionDetailsModal';
const SELECTION_COLUMN_WIDTH = 34;
const RedemptionsTable = (redemptionsData) => { const RedemptionsTable = (redemptionsData) => {
const { const {
canEdit,
canDelete,
redemptions, redemptions,
loading, loading,
searching,
activePage, activePage,
pageSize,
tokenCount,
compactMode,
handlePageChange,
rowSelection, rowSelection,
handleRow,
manageRedemption, manageRedemption,
copyText, copyText,
setEditingRedemption, setEditingRedemption,
@@ -26,6 +27,7 @@ const RedemptionsTable = (redemptionsData) => {
// Modal states // Modal states
const [showDeleteModal, setShowDeleteModal] = useState(false); const [showDeleteModal, setShowDeleteModal] = useState(false);
const [deletingRecord, setDeletingRecord] = useState(null); const [deletingRecord, setDeletingRecord] = useState(null);
const [detailRecord, setDetailRecord] = useState(null);
// Handle show delete modal // Handle show delete modal
const showDeleteRedemptionModal = (record) => { const showDeleteRedemptionModal = (record) => {
@@ -35,56 +37,45 @@ const RedemptionsTable = (redemptionsData) => {
// Get all columns // Get all columns
const columns = getRedemptionsColumns({ const columns = getRedemptionsColumns({
canEdit,
canDelete,
t, t,
manageRedemption, manageRedemption,
copyText, copyText,
setEditingRedemption, setEditingRedemption,
setShowEdit, setShowEdit,
refresh, showDetails: setDetailRecord,
redemptions,
activePage,
showDeleteRedemptionModal, showDeleteRedemptionModal,
}); });
// Handle compact mode by removing fixed positioning
const tableColumns = useMemo(() => {
return compactMode
? columns.map((col) => {
if (col.dataIndex === 'operate') {
const { fixed, ...rest } = col;
return rest;
}
return col;
})
: columns;
}, [compactMode, columns]);
return ( return (
<> <>
<CardTable <CardTable
columns={tableColumns} columns={columns}
minScrollableWidth={SELECTION_COLUMN_WIDTH * 2}
dataSource={redemptions} dataSource={redemptions}
scroll={compactMode ? undefined : { x: 'max-content' }} scroll={{ x: 'max-content' }}
pagination={{
currentPage: activePage,
pageSize: pageSize,
total: tokenCount,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50, 100],
onPageSizeChange: redemptionsData.handlePageSizeChange,
onPageChange: handlePageChange,
}}
hidePagination={true} hidePagination={true}
loading={loading} loading={loading || searching}
rowSelection={rowSelection} rowSelection={{
onRow={handleRow} ...rowSelection,
fixed: true,
columnWidth: SELECTION_COLUMN_WIDTH,
}}
empty={<TableEmpty />} empty={<TableEmpty />}
className='console-list-table overflow-hidden' className='rounded-xl overflow-hidden'
size='middle' size='middle'
/> />
<RedemptionDetailsModal
record={detailRecord}
onClose={() => setDetailRecord(null)}
copyText={copyText}
t={t}
/>
<DeleteRedemptionModal <DeleteRedemptionModal
visible={showDeleteModal} visible={canDelete && showDeleteModal}
onCancel={() => setShowDeleteModal(false)} onCancel={() => setShowDeleteModal(false)}
record={deletingRecord} record={deletingRecord}
manageRedemption={manageRedemption} manageRedemption={manageRedemption}
+41 -8
View File
@@ -8,9 +8,17 @@ import EditRedemptionModal from './modals/EditRedemptionModal';
import { useRedemptionsData } from '../../../hooks/redemptions/useRedemptionsData'; import { useRedemptionsData } from '../../../hooks/redemptions/useRedemptionsData';
import { useIsMobile } from '../../../hooks/common/useIsMobile'; import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../../helpers/utils'; import { createCardProPagination } from '../../../helpers/utils';
import { isAdmin } from '@/helpers';
import { usePerm } from '@/authz';
import '../../console/module-alignment.css';
import './redemptions.css';
const RedemptionsPage = () => { const RedemptionsPage = () => {
const redemptionsData = useRedemptionsData(); const canQuery = usePerm('platform.redemption.query', isAdmin);
const canCreate = usePerm('platform.redemption.create', isAdmin);
const canEdit = usePerm('platform.redemption.edit', isAdmin);
const canDelete = usePerm('platform.redemption.delete', isAdmin);
const redemptionsData = useRedemptionsData(canQuery);
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const { const {
@@ -47,40 +55,58 @@ const RedemptionsPage = () => {
<EditRedemptionModal <EditRedemptionModal
refresh={refresh} refresh={refresh}
editingRedemption={editingRedemption} editingRedemption={editingRedemption}
visiable={showEdit} visible={
showEdit &&
(editingRedemption.id === undefined ? canCreate : canQuery && canEdit)
}
handleClose={closeEdit} handleClose={closeEdit}
/> />
<CardPro <CardPro
tableTitle={t('兑换码列表')}
searchArea={ searchArea={
canQuery && (
<RedemptionsFilters <RedemptionsFilters
formInitValues={formInitValues} formInitValues={formInitValues}
setFormApi={setFormApi} setFormApi={setFormApi}
searchRedemptions={searchRedemptions} searchRedemptions={searchRedemptions}
activePage={redemptionsData.activePage}
setSelectedKeys={redemptionsData.setSelectedKeys}
loading={loading} loading={loading}
searching={searching} searching={searching}
t={t} t={t}
/> />
)
} }
type='type1' type='type1'
actionsArea={ descriptionArea={
<div className='console-list-tools'> canQuery && (
<RedemptionsDescription <RedemptionsDescription
compactMode={compactMode} compactMode={compactMode}
setCompactMode={setCompactMode} setCompactMode={setCompactMode}
t={t} t={t}
/> />
)
}
tableActions={
<RedemptionsActions <RedemptionsActions
canQuery={canQuery}
canCreate={canCreate}
canDelete={canDelete}
selectedKeys={selectedKeys} selectedKeys={selectedKeys}
busy={loading || searching}
setEditingRedemption={setEditingRedemption} setEditingRedemption={setEditingRedemption}
setShowEdit={setShowEdit} setShowEdit={setShowEdit}
batchCopyRedemptions={batchCopyRedemptions} batchCopyRedemptions={batchCopyRedemptions}
batchDeleteRedemptions={batchDeleteRedemptions} batchDeleteRedemptions={batchDeleteRedemptions}
t={t} t={t}
/> />
</div>
} }
paginationArea={createCardProPagination({ paginationArea={
canQuery &&
createCardProPagination({
preservePage: true,
showRange: false,
currentPage: redemptionsData.activePage, currentPage: redemptionsData.activePage,
pageSize: redemptionsData.pageSize, pageSize: redemptionsData.pageSize,
total: redemptionsData.tokenCount, total: redemptionsData.tokenCount,
@@ -88,10 +114,17 @@ const RedemptionsPage = () => {
onPageSizeChange: redemptionsData.handlePageSizeChange, onPageSizeChange: redemptionsData.handlePageSizeChange,
isMobile: isMobile, isMobile: isMobile,
t: redemptionsData.t, t: redemptionsData.t,
})} })
}
t={redemptionsData.t} t={redemptionsData.t}
> >
<RedemptionsTable {...redemptionsData} /> {canQuery && (
<RedemptionsTable
{...redemptionsData}
canEdit={canEdit}
canDelete={canDelete}
/>
)}
</CardPro> </CardPro>
</> </>
); );
@@ -1,5 +1,5 @@
import TableActionModal from '@/components/common/table/TableActionModal';
import React from 'react'; import React from 'react';
import { Modal } from '@/components/ui';
import { REDEMPTION_ACTIONS } from '../../../../constants/redemption.constants'; import { REDEMPTION_ACTIONS } from '../../../../constants/redemption.constants';
const DeleteRedemptionModal = ({ const DeleteRedemptionModal = ({
@@ -13,7 +13,8 @@ const DeleteRedemptionModal = ({
t, t,
}) => { }) => {
const handleConfirm = async () => { const handleConfirm = async () => {
await manageRedemption(record.id, REDEMPTION_ACTIONS.DELETE, record); if (!(await manageRedemption(record.id, REDEMPTION_ACTIONS.DELETE, record)))
return;
await refresh(); await refresh();
setTimeout(() => { setTimeout(() => {
if (redemptions.length === 0 && activePage > 1) { if (redemptions.length === 0 && activePage > 1) {
@@ -24,7 +25,7 @@ const DeleteRedemptionModal = ({
}; };
return ( return (
<Modal <TableActionModal
title={t('确定是否要删除此兑换码?')} title={t('确定是否要删除此兑换码?')}
visible={visible} visible={visible}
onCancel={onCancel} onCancel={onCancel}
@@ -32,7 +33,7 @@ const DeleteRedemptionModal = ({
type='warning' type='warning'
> >
{t('此修改将不可逆')} {t('此修改将不可逆')}
</Modal> </TableActionModal>
); );
}; };
@@ -1,5 +1,5 @@
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent'; import React, { useEffect, useId, useRef, useState } from 'react';
import React, { useEffect, useState, useRef } from 'react'; import { Button, Card, Col, Row, Spin } from 'antd';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { import {
API, API,
@@ -7,126 +7,105 @@ import {
showError, showError,
showSuccess, showSuccess,
renderQuota, renderQuota,
} from '../../../../helpers'; } from '@/helpers';
import { FormQuotaInput } from '../../../common/ui/QuotaInput'; import { FormQuotaInput } from '../../../common/ui/QuotaInput';
import { useIsMobile } from '../../../../hooks/common/useIsMobile'; import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import { import { Form, Modal, SideSheet } from '@/components/ui';
Button,
Modal,
SideSheet,
Space,
Spin,
Typography,
Card,
Tag,
Form,
Avatar,
Row,
Col,
} from '@/components/ui';
import {
IconCreditCard,
IconSave,
IconClose,
IconGift,
} from '@/components/ui/icons';
const { Text, Title } = Typography; const initialValues = {
const EditRedemptionModal = (props) => {
const { t } = useTranslation();
const isEdit = props.editingRedemption.id !== undefined;
const [loading, setLoading] = useState(isEdit);
const isMobile = useIsMobile();
const formApiRef = useRef(null);
const getInitValues = () => ({
name: '', name: '',
quota: 100000, quota: 100000,
count: 1, count: 1,
expired_time: null, expired_time: null,
is_gift: false, is_gift: false,
};
const EditRedemptionModal = ({
editingRedemption,
visible,
refresh,
handleClose,
}) => {
const { t } = useTranslation();
const { id } = editingRedemption;
const isEdit = id !== undefined;
const isMobile = useIsMobile();
const formApi = useRef(null);
const formId = useId();
const [loading, setLoading] = useState(false);
const [loadedId, setLoadedId] = useState(null);
const [submitting, setSubmitting] = useState(false);
const pending = useRef(false);
const formDisabled = loading || submitting || (isEdit && loadedId !== id);
useEffect(() => {
if (!visible) return;
formApi.current?.reset();
setLoadedId(null);
setLoading(isEdit);
if (!isEdit) return;
let active = true;
async function loadRedemption() {
try {
const { data: result } = await API.get(`/api/redemption/${id}`);
if (!active) return;
if (result.success) {
const { expired_time, ...data } = result.data;
formApi.current?.setValues({
...initialValues,
...data,
expired_time:
expired_time === 0 ? null : new Date(expired_time * 1000),
}); });
setLoadedId(id);
const handleCancel = () => { } else {
props.handleClose(); showError(result.message);
}
} catch (error) {
if (active && !error.isAxiosError) showError(error.message);
} finally {
if (active) setLoading(false);
}
}
void loadRedemption();
return () => {
active = false;
}; };
}, [id, isEdit, visible]);
const loadRedemption = async () => {
setLoading(true);
let res = await API.get(`/api/redemption/${props.editingRedemption.id}`);
const { success, message, data } = res.data;
if (success) {
if (data.expired_time === 0) {
data.expired_time = null;
} else {
data.expired_time = new Date(data.expired_time * 1000);
}
formApiRef.current?.setValues({ ...getInitValues(), ...data });
} else {
showError(message);
}
setLoading(false);
};
const onScopeChange = useEffectEvent(() => {
if (formApiRef.current) {
if (isEdit) {
loadRedemption();
} else {
formApiRef.current.setValues(getInitValues());
}
}
});
useEffect(() => onScopeChange(), [onScopeChange, props.editingRedemption.id]);
const submit = async (values) => { const submit = async (values) => {
let name = values.name; if (formDisabled || pending.current) return;
if (!isEdit && (!name || name === '')) { pending.current = true;
name = renderQuota(values.quota); setSubmitting(true);
} try {
setLoading(true); const payload = {
let localInputs = { ...values }; ...values,
localInputs.count = parseInt(localInputs.count) || 0; name: !isEdit && !values.name ? renderQuota(values.quota) : values.name,
localInputs.quota = parseInt(localInputs.quota) || 0; count: parseInt(values.count) || 0,
localInputs.name = name; quota: parseInt(values.quota) || 0,
if (!localInputs.expired_time) { expired_time: values.expired_time
localInputs.expired_time = 0; ? Math.floor(values.expired_time.getTime() / 1000)
} else { : 0,
localInputs.expired_time = Math.floor( };
localInputs.expired_time.getTime() / 1000, const res = isEdit
); ? await API.put('/api/redemption/', { ...payload, id: parseInt(id) })
} : await API.post('/api/redemption/', payload);
let res;
if (isEdit) {
res = await API.put(`/api/redemption/`, {
...localInputs,
id: parseInt(props.editingRedemption.id),
});
} else {
res = await API.post(`/api/redemption/`, {
...localInputs,
});
}
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
if (isEdit) { showSuccess(isEdit ? t('兑换码更新成功!') : t('兑换码创建成功!'));
showSuccess(t('兑换码更新成功!')); refresh();
props.refresh(); handleClose();
props.handleClose();
} else {
showSuccess(t('兑换码创建成功!'));
props.refresh();
formApiRef.current?.setValues(getInitValues());
props.handleClose();
}
} else { } else {
showError(message); showError(message);
} }
if (!isEdit && data) { if (!isEdit && data) {
let text = ''; let text = '';
for (let i = 0; i < data.length; i++) { for (let index = 0; index < data.length; index++) {
text += data[i] + '\n'; text += data[index] + '\n';
} }
Modal.confirm({ Modal.confirm({
title: t('兑换码创建成功'), title: t('兑换码创建成功'),
@@ -136,176 +115,100 @@ const EditRedemptionModal = (props) => {
<p>{t('兑换码将以文本文件的形式下载,文件名为兑换码的名称。')}</p> <p>{t('兑换码将以文本文件的形式下载,文件名为兑换码的名称。')}</p>
</div> </div>
), ),
onOk: () => { onOk: () => downloadTextAsFile(text, `${payload.name}.txt`),
downloadTextAsFile(text, `${localInputs.name}.txt`);
},
}); });
} }
setLoading(false); } catch (error) {
if (!error.isAxiosError) showError(error.message);
} finally {
pending.current = false;
setSubmitting(false);
}
}; };
return ( const handleCancel = () => {
<> if (!pending.current) handleClose();
<SideSheet };
placement={isEdit ? 'right' : 'left'} const footer = (
title={ <div className='console-dialog-actions redemption-form-actions'>
<Space> <Button disabled={submitting} onClick={handleCancel}>
{isEdit ? ( {t('取消')}
<Tag color='blue' shape='circle'> </Button>
{t('更新')}
</Tag>
) : (
<Tag color='green' shape='circle'>
{t('新建')}
</Tag>
)}
<Title heading={4} className='m-0'>
{isEdit ? t('更新兑换码信息') : t('创建新的兑换码')}
</Title>
</Space>
}
bodyStyle={{ padding: '0' }}
visible={props.visiable}
width={isMobile ? '100%' : 600}
footer={
<div className='flex justify-end'>
<Space>
<Button <Button
theme='solid' type='primary'
onClick={() => formApiRef.current?.submitForm()} htmlType='submit'
icon={<IconSave />} form={formId}
loading={loading} disabled={formDisabled}
loading={submitting}
> >
{t('提交')} {t('提交')}
</Button> </Button>
<Button
theme='light'
type='primary'
onClick={handleCancel}
icon={<IconClose />}
>
{t('取消')}
</Button>
</Space>
</div> </div>
} );
closeIcon={null} const form = (
onCancel={() => handleCancel()}
>
<Spin spinning={loading}> <Spin spinning={loading}>
<Form <Form
initValues={getInitValues()} id={formId}
getFormApi={(api) => (formApiRef.current = api)} name={formId}
ref={formApi}
className='redemption-form'
initValues={initialValues}
disabled={formDisabled}
onSubmit={submit} onSubmit={submit}
onSubmitFail={() => formApi.current?.scrollToError()}
> >
{({ values }) => ( <Card size='small' title={t('基本信息')}>
<div className='p-2'>
<Card className='!rounded-2xl shadow-sm border-0 mb-6'>
{/* Header: Basic Info */}
<div className='flex items-center mb-2'>
<Avatar
size='small'
color='blue'
className='mr-2 shadow-md'
>
<IconGift 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}>
<Col span={24}>
<Form.Input <Form.Input
field='name' field='name'
label={t('名称')} label={t('名称')}
placeholder={t('请输入名称')} placeholder={t('请输入名称')}
style={{ width: '100%' }} rules={isEdit ? [{ required: true, message: t('请输入名称') }] : []}
rules={ className={isEdit ? 'redemption-validated-field' : undefined}
!isEdit
? []
: [{ required: true, message: t('请输入名称') }]
}
showClear showClear
/> />
</Col>
<Col span={24}>
<Form.DatePicker <Form.DatePicker
field='expired_time' field='expired_time'
label={t('过期时间')} label={t('过期时间')}
type='dateTime' type='dateTime'
placeholder={t('选择过期时间(可选,留空为永久)')} placeholder={t('选择过期时间(可选,留空为永久)')}
style={{ width: '100%' }}
showClear showClear
/> />
</Col>
</Row>
</Card> </Card>
<Card size='small' title={t('额度设置')}>
<Card className='!rounded-2xl shadow-sm border-0'> <Row gutter={16}>
{/* Header: Quota Settings */} <Col xs={24} sm={isEdit ? 24 : 12}>
<div className='flex items-center mb-2'>
<Avatar
size='small'
color='green'
className='mr-2 shadow-md'
>
<IconCreditCard 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}>
<Col span={12}>
<FormQuotaInput <FormQuotaInput
field='quota' field='quota'
label={t('额度')} label={t('额度')}
style={{ width: '100%' }} className='redemption-validated-field'
rules={[ rules={[
{ required: true, message: t('请输入额度') }, { required: true, message: t('请输入额度') },
{ {
validator: (rule, v) => { validator: (rule, value) =>
const num = parseInt(v, 10); parseInt(value, 10) > 0
return num > 0
? Promise.resolve() ? Promise.resolve()
: Promise.reject(t('额度必须大于0')); : Promise.reject(t('额度必须大于0')),
},
}, },
]} ]}
showClear showClear
/> />
</Col> </Col>
{!isEdit && ( {!isEdit && (
<Col span={12}> <Col xs={24} sm={12}>
<Form.InputNumber <Form.InputNumber
field='count' field='count'
label={t('生成数量')} label={t('生成数量')}
className='redemption-validated-field'
min={1} min={1}
rules={[ rules={[
{ required: true, message: t('请输入生成数量') }, { required: true, message: t('请输入生成数量') },
{ {
validator: (rule, v) => { validator: (rule, value) =>
const num = parseInt(v, 10); parseInt(value, 10) > 0
return num > 0
? Promise.resolve() ? Promise.resolve()
: Promise.reject(t('生成数量必须大于0')); : Promise.reject(t('生成数量必须大于0')),
},
}, },
]} ]}
style={{ width: '100%' }}
showClear showClear
/> />
</Col> </Col>
@@ -319,12 +222,23 @@ const EditRedemptionModal = (props) => {
)} )}
/> />
</Card> </Card>
</div>
)}
</Form> </Form>
</Spin> </Spin>
);
return (
<SideSheet
placement='right'
forceRender
visible={visible}
width={isMobile ? '100%' : 560}
title={isEdit ? t('编辑兑换码信息') : t('添加兑换码')}
footer={footer}
onCancel={handleCancel}
closable={!submitting}
>
{form}
</SideSheet> </SideSheet>
</>
); );
}; };
@@ -0,0 +1,67 @@
import React from 'react';
import { Button } from 'antd';
import { Copy } from '@/components/common/icons/ActionIcons';
import { Modal } from '@/components/ui';
import { renderQuota, timestamp2string } from '@/helpers';
import {
formatRedemptionExpiry,
renderRedemptionStatus,
} from '../RedemptionsColumnDefs';
export default function RedemptionDetailsModal({
record,
onClose,
copyText,
t,
}) {
const fields = record
? [
[t('ID'), record.id],
[t('额度'), renderQuota(parseInt(record.quota))],
[t('创建时间'), timestamp2string(record.created_time)],
[t('过期时间'), formatRedemptionExpiry(record.expired_time, t)],
[t('兑换人ID'), record.used_user_id || t('无')],
]
: [];
return (
<Modal
centered
visible={Boolean(record)}
title={t('查看详情')}
onCancel={onClose}
footer={<Button onClick={onClose}>{t('关闭')}</Button>}
destroyOnHidden
>
{record && (
<div className='redemption-details'>
<div className='redemption-details-heading'>
<h3>{record.name}</h3>
{renderRedemptionStatus(record.status, record, t)}
</div>
<div className='redemption-code'>
<div className='redemption-code-header'>
<span>{t('兑换码')}</span>
<Button
icon={<Copy size={16} aria-hidden />}
size='small'
onClick={() => copyText(record.key)}
>
{t('复制')}
</Button>
</div>
<code>{record.key}</code>
</div>
<dl className='redemption-details-fields'>
{fields.map(([label, value]) => (
<div key={label}>
<dt>{label}</dt>
<dd>{value}</dd>
</div>
))}
</dl>
</div>
)}
</Modal>
);
}
@@ -0,0 +1,148 @@
.console-page[data-console-page='redemption']
.console-table
.ant-table-tbody
> .ant-table-row
> .ant-table-cell {
height: 51px;
}
.redemption-form {
display: grid;
gap: 16px;
}
.redemption-form .ant-card-small > .ant-card-head,
.redemption-form .ant-card-small > .ant-card-body {
padding-inline: 16px;
}
.redemption-form .ant-card-small > .ant-card-body {
padding-block: 16px;
}
.redemption-form.console-form .ant-form-item {
margin-bottom: 16px;
}
.redemption-form.console-form .ant-card-body > .ant-form-item:last-child {
margin-bottom: 0;
}
.redemption-form.console-form .ant-form-item-label > label {
color: var(--console-text, var(--ui-color-text-0));
}
.redemption-form,
.redemption-invalid-action {
--redemption-error-text: color-mix(
in srgb,
var(--ui-color-danger) 65%,
var(--console-text, var(--ui-color-text-0))
);
}
.redemption-form .ant-form-item .ant-form-item-explain-error,
.redemption-form .ant-form-item-label > .ant-form-item-required::before,
.console-page .redemption-invalid-action.ant-btn-dangerous:not(:disabled) {
color: var(--redemption-error-text);
}
.redemption-form :is(.ant-input-number, .ant-picker) {
width: 100%;
}
.redemption-validated-field .ant-form-item-control {
min-block-size: 56px;
}
.redemption-form-actions .ant-btn {
min-inline-size: 72px;
min-block-size: 34px;
}
.redemption-details {
display: grid;
gap: 16px;
padding-block: 8px;
color: var(--console-text, var(--ui-color-text-0));
}
.redemption-details-heading,
.redemption-code-header {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px 16px;
flex-wrap: wrap;
}
.redemption-details-heading h3 {
margin: 0;
font-size: 18px;
font-weight: 600;
color: var(--console-heading, var(--ui-color-text-0));
overflow-wrap: anywhere;
}
.redemption-details-heading .ant-tag {
margin-inline-end: 0;
}
.redemption-code {
display: grid;
gap: 8px;
padding: 12px 16px;
border: 1px solid var(--console-border, var(--ui-color-border));
border-radius: 8px;
background: var(--console-fill, var(--ui-color-fill-0));
}
.redemption-code code {
overflow-wrap: anywhere;
user-select: all;
font-size: 14px;
}
.redemption-details-fields {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px 20px;
margin: 0;
}
.redemption-details dt,
.redemption-code-header > span {
color: var(--console-text, var(--ui-color-text-0));
font-size: 13px;
}
.redemption-details dd {
margin: 4px 0 0;
overflow-wrap: anywhere;
font-variant-numeric: tabular-nums;
}
@media (max-width: 575px) {
.redemption-details-fields {
grid-template-columns: 1fr;
}
}
.center-action-table .center-action-cell .redemption-row-actions {
flex-wrap: nowrap;
vertical-align: middle;
overflow-x: auto;
}
.redemption-row-actions .ant-btn {
flex: none;
}
@media (max-width: 575px) {
.center-action-table .center-action-cell .redemption-row-actions {
gap: 4px;
}
.redemption-row-actions.console-module-row-actions .ant-btn-link {
padding-inline: 2px;
}
}
@@ -132,6 +132,14 @@ const CustomTag = ({
); );
}; };
const getTaskChannelColorKey = (value) => {
const idNum = parseInt(value);
const colorIndex = Number.isFinite(idNum)
? ((idNum % colors.length) + colors.length) % colors.length
: 0;
return colors[colorIndex];
};
// Render functions // Render functions
const renderTimestamp = (timestampInSeconds) => { const renderTimestamp = (timestampInSeconds) => {
const date = new Date(timestampInSeconds * 1000); const date = new Date(timestampInSeconds * 1000);
@@ -417,11 +425,7 @@ export const getTaskLogsColumns = ({
render: (text, record, index) => { render: (text, record, index) => {
if (!isAdminUser) return null; if (!isAdminUser) return null;
const idNum = parseInt(text); const colorKey = getTaskChannelColorKey(text);
const colorIndex = Number.isFinite(idNum)
? ((idNum % colors.length) + colors.length) % colors.length
: 0;
const colorKey = colors[colorIndex];
// 若后端返回 channel_name 则在 Tooltip 中显示名称,便于管理员快速识别;否则回落为 ID // 若后端返回 channel_name 则在 Tooltip 中显示名称,便于管理员快速识别;否则回落为 ID
const tooltipContent = record.channel_name || text; const tooltipContent = record.channel_name || text;
@@ -12,7 +12,6 @@ import {
Layers, Layers,
} from 'lucide-react'; } from 'lucide-react';
import { DATE_RANGE_PRESETS } from '../../../constants/console.constants';
import { useConsolePage } from '../../console/ConsoleContext'; import { useConsolePage } from '../../console/ConsoleContext';
import FilterSearchButton from '../../common/table/FilterSearchButton'; import FilterSearchButton from '../../common/table/FilterSearchButton';
import { useFilterSearch } from '../../../hooks/common/useFilterSearch'; import { useFilterSearch } from '../../../hooks/common/useFilterSearch';
@@ -29,6 +28,7 @@ const TaskLogsFilters = ({
formInitValues, formInitValues,
setFormApi, setFormApi,
refresh, refresh,
activePage,
formApi, formApi,
loading, loading,
isAdminUser, isAdminUser,
@@ -38,8 +38,9 @@ const TaskLogsFilters = ({
t, t,
}) => { }) => {
const consolePage = useConsolePage(); const consolePage = useConsolePage();
const { scheduleSearch, submitSearch, cancelPendingSearch } = const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
useFilterSearch(refresh); (_, signal) => refresh({ page: activePage, signal }),
);
const SearchIcon = Search; const SearchIcon = Search;
const ResetIcon = RotateCcw; const ResetIcon = RotateCcw;
const primaryButtonClass = const primaryButtonClass =
@@ -63,9 +64,7 @@ const TaskLogsFilters = ({
: formInitValues; : formInitValues;
formApi.setValues(fresh, { isOverride: true }); formApi.setValues(fresh, { isOverride: true });
cancelPendingSearch(); cancelPendingSearch();
setTimeout(() => {
refresh(); refresh();
}, 100);
} }
}; };
@@ -105,12 +104,6 @@ const TaskLogsFilters = ({
} }
}; };
const datePresets = DATE_RANGE_PRESETS.map((preset) => ({
text: t(preset.text),
start: preset.start(),
end: preset.end(),
}));
const statusOptions = ( const statusOptions = (
<> <>
<Form.Select.Option value=''>{t('全部状态')}</Form.Select.Option> <Form.Select.Option value=''>{t('全部状态')}</Form.Select.Option>
@@ -156,8 +149,8 @@ const TaskLogsFilters = ({
<Form <Form
initValues={formInitValues} initValues={formInitValues}
getFormApi={(api) => setFormApi(api)} getFormApi={(api) => setFormApi(api)}
onSubmit={consolePage ? submitSearch : refresh} onSubmit={submitSearch}
onValueChange={consolePage ? scheduleSearch : undefined} onValueChange={scheduleSearch}
allowEmpty={true} allowEmpty={true}
autoComplete='off' autoComplete='off'
layout='vertical' layout='vertical'
@@ -170,10 +163,10 @@ const TaskLogsFilters = ({
field='dateRange' field='dateRange'
label={t('时间范围')} label={t('时间范围')}
className='usage-record-filter-wide' className='usage-record-filter-wide'
tableFilter
type='dateTimeRange' type='dateTimeRange'
placeholder={[t('开始时间'), t('结束时间')]} placeholder={[t('开始时间'), t('结束时间')]}
showClear showClear
presets={datePresets}
/> />
<Form.Input <Form.Input
field='task_id' field='task_id'
@@ -240,7 +233,8 @@ const TaskLogsFilters = ({
<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'
@@ -269,13 +263,13 @@ const TaskLogsFilters = ({
<Form.DatePicker <Form.DatePicker
field='dateRange' field='dateRange'
className='w-full' className='w-full'
tableFilter
type='dateTimeRange' type='dateTimeRange'
placeholder={[t('开始时间'), t('结束时间')]} placeholder={[t('开始时间'), t('结束时间')]}
showClear showClear
pure pure
size='small' size='small'
prefix={<InputPrefix icon={Calendar} />} prefix={<InputPrefix icon={Calendar} />}
presets={datePresets}
/> />
</div> </div>
</div> </div>
+5 -16
View File
@@ -1,5 +1,6 @@
import { Download as ActionDownload } from '@/components/common/icons/ActionIcons'; import { Download as ActionDownload } from '@/components/common/icons/ActionIcons';
import React, { useState } from 'react'; import React from 'react';
import UsageRecordFilterCard from '../../common/table/UsageRecordFilterCard';
import { Card, Tag as AntTag } from 'antd'; import { Card, Tag as AntTag } from 'antd';
import { Clock } from 'lucide-react'; import { Clock } from 'lucide-react';
import { Button, Pagination } from '@/components/ui'; import { Button, Pagination } from '@/components/ui';
@@ -31,8 +32,6 @@ const TaskLogsPage = ({
sharedFilterRevision, sharedFilterRevision,
}); });
const isMobile = useIsMobile(); const isMobile = useIsMobile();
// 与 CardPro 一致:移动端默认收起筛选区,仅视图状态
const [showMobileFilters, setShowMobileFilters] = useState(false);
const pageStats = useTaskPageStats(taskLogsData.logs); const pageStats = useTaskPageStats(taskLogsData.logs);
if (usageRecordMode) { if (usageRecordMode) {
@@ -53,20 +52,9 @@ const TaskLogsPage = ({
<div className='usage-record-panels'> <div className='usage-record-panels'>
<TaskLogsActions {...taskLogsData} usageRecordMode /> <TaskLogsActions {...taskLogsData} usageRecordMode />
<Card className='usage-record-card usage-record-filter-card'> <UsageRecordFilterCard className='usage-record-card'>
{isMobile && (
<Button
block
className='usage-record-mobile-toggle'
onClick={() => setShowMobileFilters(!showMobileFilters)}
>
{showMobileFilters ? t('隐藏操作项') : t('显示操作项')}
</Button>
)}
<div hidden={isMobile && !showMobileFilters}>
<TaskLogsFilters {...taskLogsData} usageRecordMode /> <TaskLogsFilters {...taskLogsData} usageRecordMode />
</div> </UsageRecordFilterCard>
</Card>
<Card className='usage-record-card usage-record-table-card'> <Card className='usage-record-card usage-record-table-card'>
<div className='usage-record-table-head'> <div className='usage-record-table-head'>
@@ -161,6 +149,7 @@ const TaskLogsPage = ({
/> />
} }
paginationArea={createCardProPagination({ paginationArea={createCardProPagination({
preservePage: true,
showRange: false, showRange: false,
currentPage: taskLogsData.activePage, currentPage: taskLogsData.activePage,
pageSize: taskLogsData.pageSize, pageSize: taskLogsData.pageSize,
@@ -1,3 +1,5 @@
import { TABLE_GROUP_COLUMN_WIDTH } from '@/components/common/table/TableGroupTags';
import { confirmTableAction } from '@/components/common/table/confirmTableAction';
import React from 'react'; import React from 'react';
import { import {
Button, Button,
@@ -12,7 +14,6 @@ import {
Popover, Popover,
Typography, Typography,
Input, Input,
Modal,
} from '@/components/ui'; } from '@/components/ui';
import { import {
timestamp2string, timestamp2string,
@@ -387,14 +388,15 @@ const renderOperations = (
type='danger' type='danger'
size='small' size='small'
onClick={() => { onClick={() => {
Modal.confirm({ confirmTableAction({
title: t('确定是否要删除此密钥?'), title: t('确定是否要删除此密钥?'),
content: t('此修改将不可逆'), content: t('此修改将不可逆'),
onOk: () => { okType: 'danger',
(async () => { focusable: { autoFocusButton: 'cancel' },
await manageToken(record.id, 'delete', record); onOk: async () => {
if (!(await manageToken(record.id, 'delete', record)))
return false;
await refresh(); await refresh();
})();
}, },
}); });
}} }}
@@ -436,6 +438,7 @@ export const getTokensColumns = ({
title: t('分组'), title: t('分组'),
dataIndex: 'group', dataIndex: 'group',
key: 'group', key: 'group',
width: TABLE_GROUP_COLUMN_WIDTH,
render: (text) => renderGroupColumn(text, t), render: (text) => renderGroupColumn(text, t),
}, },
{ {

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