Compare commits
8 Commits
dfa5c1edd6
...
ae7f773627
| Author | SHA1 | Date | |
|---|---|---|---|
| ae7f773627 | |||
| 381751a28d | |||
| be2b670ab3 | |||
| b416b21bda | |||
| 926e26b397 | |||
| 628fa323a8 | |||
| f9daeacaf9 | |||
| a57aae3043 |
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"permissions": {
|
||||||
|
"allow": ["Bash(go build:*)"]
|
||||||
|
},
|
||||||
|
"$schema": "https://json.schemastore.org/claude-code-settings.json",
|
||||||
|
"promptCacheTtl": "1h"
|
||||||
|
}
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
# Loaded by npm run dev. Override locally in .env.development.local.
|
# Loaded by npm run dev. Override locally in .env.development.local.
|
||||||
# Public configuration only; VITE_* values are exposed to the browser.
|
# Public configuration only; VITE_* values are exposed to the browser.
|
||||||
VITE_REACT_APP_SERVER_URL=
|
VITE_REACT_APP_SERVER_URL=
|
||||||
VITE_CLOUD_BRAIN_UI_ENABLED=false
|
VITE_CLOUD_BRAIN_UI_ENABLED=true
|
||||||
|
|
||||||
# Vite development proxy only. Keep the browser URL empty to use this proxy.
|
# Vite development proxy only. Keep the browser URL empty to use this proxy.
|
||||||
DEV_PROXY_TARGET=http://134.175.227.134:13000
|
DEV_PROXY_TARGET=http://134.175.227.134:13000
|
||||||
|
|||||||
@@ -62,6 +62,7 @@ yarn-debug.log*
|
|||||||
yarn-error.log*
|
yarn-error.log*
|
||||||
.idea
|
.idea
|
||||||
yarn.lock
|
yarn.lock
|
||||||
|
|
||||||
# i18n 批次中间产物(可由 scripts/i18n_kt_batches.cjs 重新生成,勿入库)
|
# i18n 批次中间产物(可由 scripts/i18n_kt_batches.cjs 重新生成,勿入库)
|
||||||
scripts/kt_batches/
|
scripts/kt_batches/
|
||||||
scripts/kt_out/
|
scripts/kt_out/
|
||||||
@@ -28,7 +28,7 @@
|
|||||||
|
|
||||||
- **技术栈**:React 18.3、react-router-dom 6.30、Vite 5.4,JS / JSX(未启用 TypeScript);antd 6.7.0 + @ant-design/icons 6.3.4(精确锁定);axios、i18next、Tailwind 3、lucide-react;专用组件 VChart、XYFlow、Quill、Joyride。
|
- **技术栈**:React 18.3、react-router-dom 6.30、Vite 5.4,JS / JSX(未启用 TypeScript);antd 6.7.0 + @ant-design/icons 6.3.4(精确锁定);axios、i18next、Tailwind 3、lucide-react;专用组件 VChart、XYFlow、Quill、Joyride。
|
||||||
- **环境**:`package.json` 要求 Node ≥ 22.13.0、npm ≥ 10,`packageManager` 指定 npm 10.9.9;依赖范围以 `package.json`、解析版本以 `package-lock.json` 为准,安装使用 `npm ci`,升级依赖时同步 lock。
|
- **环境**:`package.json` 要求 Node ≥ 22.13.0、npm ≥ 10,`packageManager` 指定 npm 10.9.9;依赖范围以 `package.json`、解析版本以 `package-lock.json` 为准,安装使用 `npm ci`,升级依赖时同步 lock。
|
||||||
- **入口与别名**:`@` → `src`;`index.html` → `src/index.jsx` → `src/components/layout/PageLayout.jsx` → `src/App.jsx`(路由、懒加载、守卫)。开发地址以 `dev.log` 最后一个 `Local:` 为准。
|
- **入口与别名**:`@` → `src`;`index.html` → `src/index.jsx` → `src/components/layout/PageLayout.jsx` → `src/App.jsx`(路由、懒加载、守卫)。开发服务按全局基线第 7.1 节结合项目目录、启动日志和监听进程发现,优先复用已有服务。
|
||||||
- **三个中心**:控制台 `/console/*`;企业中心 `/org/*`(子路由在 `src/pages/Organization/index.jsx`);用户中心 `/user-center/*`。
|
- **三个中心**:控制台 `/console/*`;企业中心 `/org/*`(子路由在 `src/pages/Organization/index.jsx`);用户中心 `/user-center/*`。
|
||||||
- **请求**:`src/helpers/api.js` 的 `API`(统一报错、GET 去重、`/api/org/*` 自动带 `X-Org-Id`),响应 `{ success, message, data }`。
|
- **请求**:`src/helpers/api.js` 的 `API`(统一报错、GET 去重、`/api/org/*` 自动带 `X-Org-Id`),响应 `{ success, message, data }`。
|
||||||
- **状态**:页面状态放模块 hook;全局只用 `src/context/{User,Status,Theme,Org,Playground}`。
|
- **状态**:页面状态放模块 hook;全局只用 `src/context/{User,Status,Theme,Org,Playground}`。
|
||||||
@@ -102,7 +102,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd
|
|||||||
## 7. 开发、验收与交付
|
## 7. 开发、验收与交付
|
||||||
|
|
||||||
1. **改前**:读相关代码;UI 任务先按 `GLOBAL_UI_BASELINE.md` 第 6 节真实 UI 登录;通用测试指令按该节自动判断验收范围、企业 / 普通个人 / 超管账号并加载现有本地配置,无需用户重复指定登录类型。
|
1. **改前**:读相关代码;UI 任务先按 `GLOBAL_UI_BASELINE.md` 第 6 节真实 UI 登录;通用测试指令按该节自动判断验收范围、企业 / 普通个人 / 超管账号并加载现有本地配置,无需用户重复指定登录类型。
|
||||||
2. **服务与浏览器**:复用已运行服务,Base URL 只取 `dev.log` 最后一个 `Local:`;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;正常、空数据、失败、校验、重复提交;只读验收的非 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`。
|
||||||
@@ -113,7 +113,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd
|
|||||||
- 无设计依据的渐变、玻璃、发光、浮起与动效;生成插画。
|
- 无设计依据的渐变、玻璃、发光、浮起与动效;生成插画。
|
||||||
- 伪造线上数据、开放隐藏菜单、绕过真实 UI 登录;点击真实支付、购买、升级、删除账户的确认按钮。
|
- 伪造线上数据、开放隐藏菜单、绕过真实 UI 登录;点击真实支付、购买、升级、删除账户的确认按钮。
|
||||||
- 删除或跳过已受跟踪的测试;隐藏失败;把模拟结果或本地截图基线写成真实通过或像素一致。
|
- 删除或跳过已受跟踪的测试;隐藏失败;把模拟结果或本地截图基线写成真实通过或像素一致。
|
||||||
- 对外输出凭据值,或将凭据、storageState、截图与报告提交到 Git;本地脱敏报告按第 7 节交付。
|
- 对外输出凭据值,或将凭据、storageState、截图与报告提交到 Git(仅 `.env.playwright.local` 中的测试账号按用户约定允许入库);本地脱敏报告按第 7 节交付。
|
||||||
|
|
||||||
## 9. 维护
|
## 9. 维护
|
||||||
|
|
||||||
@@ -122,7 +122,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd
|
|||||||
- 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。
|
- 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。
|
||||||
- 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。
|
- 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。
|
||||||
|
|
||||||
> 规范版本:v3.4 · 更新:2026-11-17
|
> 规范版本:v3.5 · 更新:2026-11-18
|
||||||
|
|
||||||
## 10. 工具差异(本节允许不同)
|
## 10. 工具差异(本节允许不同)
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,7 @@
|
|||||||
|
|
||||||
- **技术栈**:React 18.3、react-router-dom 6.30、Vite 5.4,JS / JSX(未启用 TypeScript);antd 6.7.0 + @ant-design/icons 6.3.4(精确锁定);axios、i18next、Tailwind 3、lucide-react;专用组件 VChart、XYFlow、Quill、Joyride。
|
- **技术栈**:React 18.3、react-router-dom 6.30、Vite 5.4,JS / JSX(未启用 TypeScript);antd 6.7.0 + @ant-design/icons 6.3.4(精确锁定);axios、i18next、Tailwind 3、lucide-react;专用组件 VChart、XYFlow、Quill、Joyride。
|
||||||
- **环境**:`package.json` 要求 Node ≥ 22.13.0、npm ≥ 10,`packageManager` 指定 npm 10.9.9;依赖范围以 `package.json`、解析版本以 `package-lock.json` 为准,安装使用 `npm ci`,升级依赖时同步 lock。
|
- **环境**:`package.json` 要求 Node ≥ 22.13.0、npm ≥ 10,`packageManager` 指定 npm 10.9.9;依赖范围以 `package.json`、解析版本以 `package-lock.json` 为准,安装使用 `npm ci`,升级依赖时同步 lock。
|
||||||
- **入口与别名**:`@` → `src`;`index.html` → `src/index.jsx` → `src/components/layout/PageLayout.jsx` → `src/App.jsx`(路由、懒加载、守卫)。开发地址以 `dev.log` 最后一个 `Local:` 为准。
|
- **入口与别名**:`@` → `src`;`index.html` → `src/index.jsx` → `src/components/layout/PageLayout.jsx` → `src/App.jsx`(路由、懒加载、守卫)。开发服务按全局基线第 7.1 节结合项目目录、启动日志和监听进程发现,优先复用已有服务。
|
||||||
- **三个中心**:控制台 `/console/*`;企业中心 `/org/*`(子路由在 `src/pages/Organization/index.jsx`);用户中心 `/user-center/*`。
|
- **三个中心**:控制台 `/console/*`;企业中心 `/org/*`(子路由在 `src/pages/Organization/index.jsx`);用户中心 `/user-center/*`。
|
||||||
- **请求**:`src/helpers/api.js` 的 `API`(统一报错、GET 去重、`/api/org/*` 自动带 `X-Org-Id`),响应 `{ success, message, data }`。
|
- **请求**:`src/helpers/api.js` 的 `API`(统一报错、GET 去重、`/api/org/*` 自动带 `X-Org-Id`),响应 `{ success, message, data }`。
|
||||||
- **状态**:页面状态放模块 hook;全局只用 `src/context/{User,Status,Theme,Org,Playground}`。
|
- **状态**:页面状态放模块 hook;全局只用 `src/context/{User,Status,Theme,Org,Playground}`。
|
||||||
@@ -102,7 +102,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd
|
|||||||
## 7. 开发、验收与交付
|
## 7. 开发、验收与交付
|
||||||
|
|
||||||
1. **改前**:读相关代码;UI 任务先按 `GLOBAL_UI_BASELINE.md` 第 6 节真实 UI 登录;通用测试指令按该节自动判断验收范围、企业 / 普通个人 / 超管账号并加载现有本地配置,无需用户重复指定登录类型。
|
1. **改前**:读相关代码;UI 任务先按 `GLOBAL_UI_BASELINE.md` 第 6 节真实 UI 登录;通用测试指令按该节自动判断验收范围、企业 / 普通个人 / 超管账号并加载现有本地配置,无需用户重复指定登录类型。
|
||||||
2. **服务与浏览器**:复用已运行服务,Base URL 只取 `dev.log` 最后一个 `Local:`;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;正常、空数据、失败、校验、重复提交;只读验收的非 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`。
|
||||||
@@ -113,7 +113,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd
|
|||||||
- 无设计依据的渐变、玻璃、发光、浮起与动效;生成插画。
|
- 无设计依据的渐变、玻璃、发光、浮起与动效;生成插画。
|
||||||
- 伪造线上数据、开放隐藏菜单、绕过真实 UI 登录;点击真实支付、购买、升级、删除账户的确认按钮。
|
- 伪造线上数据、开放隐藏菜单、绕过真实 UI 登录;点击真实支付、购买、升级、删除账户的确认按钮。
|
||||||
- 删除或跳过已受跟踪的测试;隐藏失败;把模拟结果或本地截图基线写成真实通过或像素一致。
|
- 删除或跳过已受跟踪的测试;隐藏失败;把模拟结果或本地截图基线写成真实通过或像素一致。
|
||||||
- 对外输出凭据值,或将凭据、storageState、截图与报告提交到 Git;本地脱敏报告按第 7 节交付。
|
- 对外输出凭据值,或将凭据、storageState、截图与报告提交到 Git(仅 `.env.playwright.local` 中的测试账号按用户约定允许入库);本地脱敏报告按第 7 节交付。
|
||||||
|
|
||||||
## 9. 维护
|
## 9. 维护
|
||||||
|
|
||||||
@@ -122,7 +122,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd
|
|||||||
- 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。
|
- 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。
|
||||||
- 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。
|
- 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。
|
||||||
|
|
||||||
> 规范版本:v3.4 · 更新:2026-11-17
|
> 规范版本:v3.5 · 更新:2026-11-18
|
||||||
|
|
||||||
## 10. 工具差异(本节允许不同)
|
## 10. 工具差异(本节允许不同)
|
||||||
|
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ 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 安装与构建命令。
|
||||||
|
|
||||||
```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
|
||||||
cd monkey-ai-web
|
cd monkey-ai-web
|
||||||
@@ -65,7 +67,7 @@ npm run dev
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `DEV_PROXY_TARGET` | 开发代理的后端地址(仅 Vite 使用) |
|
| `DEV_PROXY_TARGET` | 开发代理的后端地址(仅 Vite 使用) |
|
||||||
| `VITE_REACT_APP_SERVER_URL` | 浏览器直连的后端根地址,留空为同源 |
|
| `VITE_REACT_APP_SERVER_URL` | 浏览器直连的后端根地址,留空为同源 |
|
||||||
| `VITE_CLOUD_BRAIN_UI_ENABLED` | 云脑入口与路由开关,默认关闭 |
|
| `VITE_CLOUD_BRAIN_UI_ENABLED` | 云脑入口与路由开关,开发环境默认开启,生产环境默认关闭 |
|
||||||
| `VITE_SKILL_MARKET_MOCK` | 设为 `true` 时技能超市进入本地演示模式;默认不设置 |
|
| `VITE_SKILL_MARKET_MOCK` | 设为 `true` 时技能超市进入本地演示模式;默认不设置 |
|
||||||
| `VITE_UMAMI_WEBSITE_ID`、`VITE_UMAMI_SCRIPT_URL` | Umami 统计,ID 留空则不注入脚本 |
|
| `VITE_UMAMI_WEBSITE_ID`、`VITE_UMAMI_SCRIPT_URL` | Umami 统计,ID 留空则不注入脚本 |
|
||||||
| `VITE_GOOGLE_ANALYTICS_ID` | Google Analytics,留空则不注入 |
|
| `VITE_GOOGLE_ANALYTICS_ID` | Google Analytics,留空则不注入 |
|
||||||
@@ -79,6 +81,7 @@ monkey-ai-web/
|
|||||||
├── docs/ # 开发与组件规范、页面 UI 规范、变更记录(入口 docs/README.md)
|
├── docs/ # 开发与组件规范、页面 UI 规范、变更记录(入口 docs/README.md)
|
||||||
├── public/ # 原样复制到产物的静态资源
|
├── public/ # 原样复制到产物的静态资源
|
||||||
├── scripts/ # 开发启动、单测发现、UI 依赖审计、品牌图标生成、i18n 辅助脚本
|
├── scripts/ # 开发启动、单测发现、UI 依赖审计、品牌图标生成、i18n 辅助脚本
|
||||||
|
│ └── vite/ # 自定义 Vite 插件:legacy-css-layers.js 提供旧浏览器 @layer 样式兜底
|
||||||
├── src/
|
├── src/
|
||||||
│ ├── index.jsx # React 挂载、语言初始化、全局 Provider
|
│ ├── index.jsx # React 挂载、语言初始化、全局 Provider
|
||||||
│ ├── App.jsx # 路由、懒加载、访问守卫
|
│ ├── App.jsx # 路由、懒加载、访问守卫
|
||||||
@@ -156,7 +159,7 @@ monkey-ai-web/
|
|||||||
|
|
||||||
### 本地 Playwright 登录配置
|
### 本地 Playwright 登录配置
|
||||||
|
|
||||||
本机自动化登录入口为 `e2e/auth-login/run.mjs`(本地验收脚本,Git 忽略)。在 `.env.playwright.local` 中配置 `UI_ORG_NAME`、`UI_ORG_USER`、`UI_ORG_PASS`、`UI_PERSONAL_USER`、`UI_PERSONAL_PASS`;写入真实凭据前,用 `git ls-files -- .env.playwright.local` 确认未跟踪(应无输出),再用 `git check-ignore -- .env.playwright.local` 确认已忽略(应输出路径)。已跟踪文件不会因新增忽略规则而解除跟踪;检查不满足时先记录风险,跟踪与历史处置另行授权,不向该文件写入真实凭据。账号密码不写入脚本或提交。运行时由 Node 加载到环境变量:
|
本机自动化登录入口为 `e2e/auth-login/run.mjs`(本地验收脚本,Git 忽略)。在 `.env.playwright.local` 中配置 `UI_ORG_NAME`、`UI_ORG_USER`、`UI_ORG_PASS`、`UI_PERSONAL_USER`、`UI_PERSONAL_PASS`。该文件只保存测试账号,按用户约定不作 Git 忽略,允许提交;不得把值写入脚本、日志、截图注释或报告。其他凭据与 storageState 仍不入库。运行时由 Node 加载到环境变量:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
node --env-file=.env.playwright.local e2e/auth-login/run.mjs
|
node --env-file=.env.playwright.local e2e/auth-login/run.mjs
|
||||||
@@ -164,9 +167,9 @@ node --env-file=.env.playwright.local e2e/auth-login/run.mjs
|
|||||||
|
|
||||||
收到通用测试指令时,代理按 `docs/ui/GLOBAL_UI_BASELINE.md` 第 6 节自动判断受影响页面与账号类型,选择登录流程和脚本参数,无需用户重复说明个人或企业登录。手工运行脚本时,超管个人登录单独使用 `UI_ADMIN_USER` / `UI_ADMIN_PASS`,添加 `--admin` 选择超管账号,默认使用普通个人账号。仅执行个人端阶段可添加 `--personal-only`,例如 `node --env-file=.env.playwright.local e2e/auth-login/run.mjs --personal-only --admin`。超管同样通过 `/login` 的真实 UI 登录,不绕过权限校验。
|
收到通用测试指令时,代理按 `docs/ui/GLOBAL_UI_BASELINE.md` 第 6 节自动判断受影响页面与账号类型,选择登录流程和脚本参数,无需用户重复说明个人或企业登录。手工运行脚本时,超管个人登录单独使用 `UI_ADMIN_USER` / `UI_ADMIN_PASS`,添加 `--admin` 选择超管账号,默认使用普通个人账号。仅执行个人端阶段可添加 `--personal-only`,例如 `node --env-file=.env.playwright.local e2e/auth-login/run.mjs --personal-only --admin`。超管同样通过 `/login` 的真实 UI 登录,不绕过权限校验。
|
||||||
|
|
||||||
脚本从 `dev.log` 最后一个 `Local:` 提取并验证系统地址,使用本机 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 与 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-工具)。
|
||||||
|
|
||||||
| 命令 / 参数 | 用途与默认值 |
|
| 命令 / 参数 | 用途与默认值 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
@@ -177,7 +180,7 @@ Playwright 与 weelink 共用设备环境约定,依赖精确锁定 1.64.1;
|
|||||||
| `npm run test:e2e:environment` | 隔离验证 8 视口、手机 UA/触摸/DPR、CSS 截图;不代表业务验收 |
|
| `npm run test:e2e:environment` | 隔离验证 8 视口、手机 UA/触摸/DPR、CSS 截图;不代表业务验收 |
|
||||||
| `npm run test:e2e:report` | 打开最新完整 HTML 报告;仅人工使用 |
|
| `npm run test:e2e:report` | 打开最新完整 HTML 报告;仅人工使用 |
|
||||||
| `PW_WORKERS` | 默认 1,只接受正安全整数;保留串行优先策略 |
|
| `PW_WORKERS` | 默认 1,只接受正安全整数;保留串行优先策略 |
|
||||||
| `PW_TARGET` / `PW_BASE_URL` | 默认 local-dev / `http://127.0.0.1:4176/`;remote 必填 URL |
|
| `PW_TARGET` / `PW_BASE_URL` | 未指定时优先自动发现并复用开发服务,确认不存在后默认 local-dev / `http://127.0.0.1:4176/`;remote 必填 URL |
|
||||||
| `PW_VIDEO` / `PW_REQUIRE_ALL` | 默认 0;开启失败保留视频 / 全部通过约束 |
|
| `PW_VIDEO` / `PW_REQUIRE_ALL` | 默认 0;开启失败保留视频 / 全部通过约束 |
|
||||||
|
|
||||||
`UI_VISUAL_OFFSCREEN=0` 仅限人工本地可视化调试时临时使用。Agent、CI、无头/自动化环境禁止设置该值,必须保持默认离屏模式(或 `UI_VISUAL_OFFSCREEN=1`),避免弹出 UI 或依赖显示环境。配置会拦截 CI、无头及已识别的 Codex/Claude Agent 标记;其他自动化调用方也必须遵守此约定。
|
`UI_VISUAL_OFFSCREEN=0` 仅限人工本地可视化调试时临时使用。Agent、CI、无头/自动化环境禁止设置该值,必须保持默认离屏模式(或 `UI_VISUAL_OFFSCREEN=1`),避免弹出 UI 或依赖显示环境。配置会拦截 CI、无头及已识别的 Codex/Claude Agent 标记;其他自动化调用方也必须遵守此约定。
|
||||||
|
|||||||
+211
-1
@@ -1,6 +1,6 @@
|
|||||||
# 变更记录(CHANGELOG)
|
# 变更记录(CHANGELOG)
|
||||||
|
|
||||||
> 状态:有效(持续追加) · 更新:2026-11-17 · 版本:v3.2
|
> 状态:有效(持续追加) · 更新:2026-11-18 · 版本:v3.5
|
||||||
|
|
||||||
对现状仍有影响的功能与修复记录,按日期倒序。改造、迁移、优化等一次性过程不在此记录。
|
对现状仍有影响的功能与修复记录,按日期倒序。改造、迁移、优化等一次性过程不在此记录。
|
||||||
|
|
||||||
@@ -8,6 +8,216 @@
|
|||||||
|
|
||||||
**记录规则**:每条写“范围、变更、影响、回滚、关联”五项;回滚优先 `git revert <提交>`,提交含多项改动时按文件还原(`git checkout <提交>^ -- <文件>`),不整仓 reset。本文不作为规则依据。
|
**记录规则**:每条写“范围、变更、影响、回滚、关联”五项;回滚优先 `git revert <提交>`,提交含多项改动时按文件还原(`git checkout <提交>^ -- <文件>`),不整仓 reset。本文不作为规则依据。
|
||||||
|
|
||||||
|
## 2026-11-18
|
||||||
|
|
||||||
|
### 调整 · 认证页表单必填标识、就地校验与间距统一
|
||||||
|
|
||||||
|
- **范围**:`/login`、`/org/login`(第 1–3 步)、`/register`、`/org/register`、`/reset` 及微信验证码、两步验证弹窗。
|
||||||
|
- **变更**:必填项统一显示 `*`,为空时就地提示“请输入 + label”;注册密码 8-20 位、确认密码一致、邮箱格式沿用原判断就地提示;注册、找回密码改为前端校验通过后再调用原提交函数;获取验证码、微信验证码确定前先校验;企业登录第 1 步失焦为空时提示;label 与输入框间距 7px,表单项无下边距并预留 22px 报错位;新增 8 条提示文案并补齐 9 个语言包。
|
||||||
|
- **影响**:请求地址、载荷、原处理函数内判断与按钮禁用条件不变;非法输入改为就地提示后不再发出请求。
|
||||||
|
- **回滚**:按文件还原本条涉及的 `src/components/auth/`、`src/pages/OrgLogin/index.jsx`、`src/pages/OrgRegister/index.jsx`、`src/styles/prototype.css` 表单项段落与 `src/i18n/locales/` 新增键。
|
||||||
|
- **关联**:`docs/ui/GLOBAL_UI_BASELINE.md` 第 4.5 节。
|
||||||
|
|
||||||
|
### 调整 · 开发环境默认开启云脑入口
|
||||||
|
|
||||||
|
- **范围**:开发环境配置、环境回归测试与 README。
|
||||||
|
- **变更**:开发环境默认开启云脑入口,测试分别校验开发开启与生产关闭。
|
||||||
|
- **影响**:生产默认值保持关闭,入口仍受后台模块开关与账号权限约束。
|
||||||
|
- **回滚**:将开发环境开关与测试预期恢复为关闭,并还原本条文档差异。
|
||||||
|
- **关联**:`.env.development`、`tests/environment.test.js`、`README.md`。
|
||||||
|
|
||||||
|
### 修复 · 控制台侧栏自动定位当前菜单
|
||||||
|
|
||||||
|
- **范围**:控制台侧栏与移动端导航抽屉。
|
||||||
|
- **变更**:菜单完成加载、当前菜单变化、侧栏展开或尺寸变化时,自动滚动菜单区域,使超出视口的选中项完整可见;已可见时保留当前位置。
|
||||||
|
- **影响**:不滚动正文、不抢焦点、不改变权限和路由,不强制展开手动收起的分组;异步菜单变化后重新检查,卸载时回收观察器和动画帧。
|
||||||
|
- **回滚**:仅还原 `SiderBar.jsx` 的定位逻辑与 `helpers/sidebarScroll.js`、对应测试和本条规范变更。
|
||||||
|
- **关联**:`docs/ui/GLOBAL_UI_BASELINE.md` 第 4.3 节。
|
||||||
|
|
||||||
|
### 修复 · 平台 Skill 审核抽屉滚动与固定操作栏
|
||||||
|
|
||||||
|
- **范围**:`/console/skill-platform` 技能详情审核工作台。
|
||||||
|
- **变更**:技能原文随抽屉正文统一滚动,长文本自动换行;审核按钮移入固定页脚并靠右排列,版本页签隐藏审核操作,每次打开详情回到审核页签。
|
||||||
|
- **影响**:保留扫描、模型实测、审核、发布的原有条件、请求与回调;窄屏按钮按原行为换行。
|
||||||
|
- **回滚**:仅还原 `SkillPlatform/index.jsx`、`skill-platform.css`、`components/skill/index.jsx` 的样式类透传与控制台规范中本条相关差异。
|
||||||
|
- **关联**:`docs/standards/UI_COMPONENT_STANDARDS.md` 第 9 节。
|
||||||
|
|
||||||
|
### 修复 · 复制回归测试与 Hook 依赖检查
|
||||||
|
|
||||||
|
- **范围**:企业密钥复制回归用例、伙伴工作台入口与企业中心请求清理。
|
||||||
|
- **变更**:复制测试按当前公共复制函数及密钥、模型回调验证成功和失败反馈,同时校验成功标记与定时器;用例纳入 `test/unit/`;伙伴作用域按用户与企业身份保持稳定,企业请求清理捕获本次使用的引用。
|
||||||
|
- **影响**:修复过期测试及两处 Hook 检查警告,保留现有复制、权限探测与过期请求失效逻辑。
|
||||||
|
- **回滚**:仅还原本条相关 Hook 差异、复制测试与本记录,保留其他工作区修改。
|
||||||
|
- **关联**:`test/unit/clipboard.test.js`、`src/hooks/common/usePartnerWorkspaceEntry.js`、`src/pages/Organization/index.jsx`。
|
||||||
|
|
||||||
|
### 修复 · 技能许可证徽标兼容深浅主题
|
||||||
|
|
||||||
|
- **范围**:技能超市卡片与详情,以及复用 `LicenseBadge` 的技能平台、企业技能库。
|
||||||
|
- **变更**:许可证待审核状态由非 antd 预设色名 `amber` 改为 `gold`,统一由现有主题算法生成背景与描边,文字使用对应调色板第 9 档 token 提高可读性;通过与阻止保留绿色、红色。
|
||||||
|
- **影响**:修复暗色主题的浅底浅字问题,支持运行时主题切换;保留许可证表达式、审核决策及权限、接口逻辑。
|
||||||
|
- **回滚**:仅还原 `src/components/skill/` 中的待审核颜色映射、许可证文字 token 与局部样式,以及相关规范差异。
|
||||||
|
- **关联**:`src/components/skill/tokens.js`、`docs/ui/SKILL_MARKET_SPEC.md` 第 4 节。
|
||||||
|
|
||||||
|
### 调整 · 认证页输入框 36px 与视觉统一
|
||||||
|
|
||||||
|
- **范围**:`/login`、`/org/login`、`/org/:slug/login`、`/register`、`/org/register`、`/reset`、`/user/reset`,以及两步验证、微信验证码弹窗。
|
||||||
|
- **变更**:输入框、下拉、整行按钮统一 36px / 8px 圆角,字段节奏 24px;隐藏卡片外发光、角落光晕、漂移光斑与 Logo 光环 / 星标;第三方登录与注册提交按钮去掉渐变、扫光和上浮动效;新增 `AuthDivider` 统一分隔线;找回密码两页改用登录页同款背景、卡片与头部;六个认证页统一使用登录顶栏;两步验证链接色改用品牌色。
|
||||||
|
- **影响**:仅视图层,保留请求、载荷、校验规则、提交触发与禁用条件;`OrgCredentialResult` 和 `/client/authorize` 不变。
|
||||||
|
- **回滚**:按文件还原 `src/components/auth/`(含删除新增的 `AuthDivider.jsx`)、`src/pages/OrgLogin/index.jsx`、`src/pages/OrgRegister/index.jsx`、`src/components/layout/PageLayout.jsx`、`src/styles/prototype.css` 中的 `.auth-login-page` 段及 `GLOBAL_UI_BASELINE.md` 第 4.5 节。
|
||||||
|
- **关联**:`docs/ui/GLOBAL_UI_BASELINE.md` 第 4.5 节。
|
||||||
|
|
||||||
|
### 修复 · 平台 Skill 分类标签与搜索栏左对齐
|
||||||
|
|
||||||
|
- **范围**:`/console/skill-platform` 分类速览标签区域。
|
||||||
|
- **变更**:将分类区域纳入控制台全宽布局规则,移除其独立最大宽度与水平自动居中,使首个标签与上方搜索框左边缘对齐。
|
||||||
|
- **影响**:仅调整控制台样式,保留标签间距、自然换行、分类选择、请求和业务回调。
|
||||||
|
- **回滚**:移除 `console.css` 全宽规则中的 `.skill-platform-tag-chips` 选择器,按本条差异还原控制台规范。
|
||||||
|
- **关联**:`src/components/console/console.css`、`docs/ui/CONSOLE_SPEC.md` 第 3 节。
|
||||||
|
|
||||||
|
### 调整 · 移除全站顶栏登录注册按钮
|
||||||
|
|
||||||
|
- **范围**:共享顶部导航的桌面与移动端未登录状态。
|
||||||
|
- **变更**:移除 `UserArea` 的登录 / 注册按钮分支、专用样式拼接及无用依赖,并清理该分支专用参数传递。
|
||||||
|
- **影响**:已登录头像菜单、主题等工具、登录 / 注册页面和受保护导航的鉴权跳转保持原有行为。
|
||||||
|
- **回滚**:仅还原本条涉及 `UserArea.jsx`、`ActionButtons.jsx`、`headerbar/index.jsx` 与顶栏规范的差异,保留工作区其他修改。
|
||||||
|
- **关联**:`src/components/layout/headerbar/`、`docs/ui/GLOBAL_UI_BASELINE.md` 第 4.1 节。
|
||||||
|
|
||||||
|
### 调整 · 模型超市隐藏分组与标签筛选
|
||||||
|
|
||||||
|
- **范围**:`/market` 顶部模型筛选卡。
|
||||||
|
- **变更**:隐藏“用户分组”和“模型标签”两行筛选项,保留厂商、计费类型与端点类型;卡头说明同步列出当前可见的筛选维度,复用已有翻译。
|
||||||
|
- **影响**:仅调整筛选入口展示,保留原有请求、筛选状态、重置、计价、模型卡片与详情中的分组信息。
|
||||||
|
- **回滚**:仅还原 `MarketFilterSidebar.jsx`、`ModelMarketPage.jsx` 与模型超市规范中本条对应差异,保留其他工作区修改。
|
||||||
|
- **关联**:`docs/ui/MODEL_MARKET_SPEC.md` 第 3、8 节。
|
||||||
|
|
||||||
|
### 修复 · 等级弹窗模型数量入口使用操作主色
|
||||||
|
|
||||||
|
- **范围**:`/console/setting?tab=level_policy` 的个人与企业等级弹窗。
|
||||||
|
- **变更**:分组策略中模型数量大于 0 时,数量入口改用与表格操作列一致的 `link` 按钮,仅数量文字使用橙色主色,展开箭头保留中性文字色,自动适配浅深主题。
|
||||||
|
- **影响**:无模型时保留“配置”的原有样式;展开、收起、模型折扣、接口与保存逻辑不变。
|
||||||
|
- **回滚**:仅还原本条在 `LevelPolicySetting.jsx` 中的按钮属性与 `LevelPolicySetting.css` 中的图标样式差异。
|
||||||
|
- **关联**:`src/components/settings/LevelPolicySetting.jsx`。
|
||||||
|
|
||||||
|
### 修复 · 渠道自定义模型填入后清空
|
||||||
|
|
||||||
|
- **范围**:`/console/channel` 创建渠道与更新渠道信息表单。
|
||||||
|
- **变更**:点击自定义模型名称的“填入”后,同步清空组件状态与表单字段值,避免输入框保留已处理的名称。
|
||||||
|
- **影响**:保留模型合并、逗号分隔、去重、提示与原有渠道保存逻辑。
|
||||||
|
- **回滚**:仅还原 `EditChannelModal.jsx` 中本条新增的字段清空调用与本记录。
|
||||||
|
- **关联**:`src/components/table/channels/modals/EditChannelModal.jsx`。
|
||||||
|
|
||||||
|
### 修复 · 充值档位编辑弹窗回填当前行
|
||||||
|
|
||||||
|
- **范围**:`/console/setting?tab=amount-options`、`/console/setting?tab=org-amount-options`。
|
||||||
|
- **变更**:编辑与新增弹窗关闭后销毁内部表单,确保每次打开按当前档位初始化;移除未使用的表单 API 状态。
|
||||||
|
- **影响**:切换编辑行、取消后重开及编辑与新增切换时,不再保留首次打开或未保存的表单数据;保留原有接口、载荷与保存逻辑。
|
||||||
|
- **回滚**:仅还原 `AmountOptionsManager.jsx` 本条相关差异与本记录,保留其他工作区修改。
|
||||||
|
- **关联**:`src/pages/Setting/AmountOptionsManager.jsx`。
|
||||||
|
|
||||||
|
### 调整 · 消费记录耗时分档标签
|
||||||
|
|
||||||
|
- **范围**:`/user-center/usage-record` 消费记录的“用时 / 首字”列。
|
||||||
|
- **变更**:总用时与首字耗时按阈值分别呈现 antd 带描边彩色标签,流式状态使用蓝色标签,非流式使用中性标签;加宽该列,支持深浅主题,零值正常展示,缺失与无效耗时显示破折号。
|
||||||
|
- **影响**:仅调整用户中心表格展示;首字耗时先保留一位小数再判色,保留接口、筛选、权限与控制台原有渲染。
|
||||||
|
- **回滚**:仅还原本条在列定义、使用记录 CSS 与页面规范中的差异,保留工作区其他修改。
|
||||||
|
- **关联**:`src/components/table/usage-logs/UsageLogsColumnDefs.jsx`、`src/pages/UserCenter/UsageRecord.css`、`docs/ui/USER_CENTER_SPEC.md` 第 4.2 节。
|
||||||
|
|
||||||
|
### 调整 · 分佣工作台对齐本地原型
|
||||||
|
|
||||||
|
- **范围**:`/console/commission?view=overview`。
|
||||||
|
- **变更**:参照本地原型的工作台视图,调整概览指标图标、数字与单位、卡片内边距、待办摘要和数据健康区块;待办标题优先展示已有伙伴与账期;趋势图补齐纵轴刻度、统一柱宽与悬浮 / 键盘提示,保留加载失败和重试反馈。
|
||||||
|
- **影响**:保留月份选择与刷新区域、真实数据计算、历史请求、权限、待办过滤及原有跳转目标;不引入原型的示例业务数据。
|
||||||
|
- **回滚**:仅还原本条在 `Dashboard.jsx` 与 `dashboard.css` 的差异,保留此前工作区修改。
|
||||||
|
- **关联**:`src/pages/CommissionV2/Dashboard.jsx`、`src/pages/CommissionV2/dashboard.css`。
|
||||||
|
|
||||||
|
### 调整 · 分佣与智能路由统一 UI
|
||||||
|
|
||||||
|
- **范围**:`/console/commission`、`/org/commission`、`/console/my-commission`、`/console/smart-router` 及复用的列表、账单、表单与浮层。
|
||||||
|
- **变更**:分佣颜色映射到主题语义 token,统一控件高度、圆角、卡片、筛选区、页签与金额对齐;表格接入三中心公共组件;企业分佣复用企业页头,补齐无权限态布局;智能路由移除重复标题,统一抽屉、提示、表单栅格和移动端布局;分页尊重调用方显式关闭容量选择的设置。
|
||||||
|
- **影响**:保留接口、权限、请求载荷与业务回调;固定接口分页容量的页面不开放无效的容量切换。
|
||||||
|
- **回滚**:按本条涉及文件的差异还原,保留工作区其他改动。
|
||||||
|
- **关联**:`src/pages/CommissionV2/`、`src/components/smart-router/`、`src/pages/SmartRouter/index.jsx`、`src/components/ui/index.jsx`。
|
||||||
|
|
||||||
|
### 工具 · 本地验收优先复用开发服务
|
||||||
|
|
||||||
|
- **范围**:项目 Playwright 配置、开发服务发现脚本、Agent 入口、README 与全局 UI 基线。
|
||||||
|
- **变更**:结合项目日志与 Node 监听端口查找开发服务,通过 Vite 源码映射验证当前项目;兼容 UTF-8 / UTF-16LE 日志,历史地址失效时继续发现,仅未找到服务时才允许新启。按用户约定允许测试账号文件 `.env.playwright.local` 入库。
|
||||||
|
- **影响**:未显式指定目标时自动复用已有服务;显式指定测试目标的行为保留。验收产物与 storageState 仍不入库。
|
||||||
|
- **回滚**:移除 `playwright.config.js` 的自动发现调用与 `scripts/dev-service.mjs`,按差异还原相关文档;测试账号文件的入库约定单独维护。
|
||||||
|
- **关联**:`docs/ui/GLOBAL_UI_BASELINE.md` 第 6、7.1 节,`test/unit/dev-service.test.js`。
|
||||||
|
|
||||||
|
### 调整 · 智能路由卡片首部页签间距
|
||||||
|
|
||||||
|
- **范围**:`/console/smart-router` 的选项卡卡片,以及 UI 公共规范第 10 节。
|
||||||
|
- **变更**:参照官网设置页,将页签卡片主体顶部内边距从 24px 调整为 8px,减少 16px 多余留白;规范明确卡片首部页签的顶部间距、默认高度与适用条件。
|
||||||
|
- **影响**:仅调整该卡片顶部间距,保留页签高度、文字、切换逻辑、权限、请求和其他方向内边距;企业中心的智能路由组件不受影响。
|
||||||
|
- **回滚**:移除 `SmartRouter/index.jsx` 的 `smart-router-tabs-card` 类及对应 CSS 规则,按差异还原规范条目。
|
||||||
|
- **关联**:`docs/standards/UI_COMPONENT_STANDARDS.md` 第 10 节。
|
||||||
|
|
||||||
|
### 工具 · 集中管理 Vite 样式兼容插件
|
||||||
|
|
||||||
|
- **范围**:旧浏览器 CSS 级联层兼容插件、Vite 配置、相关测试与 README。
|
||||||
|
- **变更**:将根目录 `vite-plugin-legacy-css-layers.js` 迁至 `scripts/vite/legacy-css-layers.js`;同步导入、测试夹具目录与错误提示路径。
|
||||||
|
- **影响**:仅调整文件组织,保留插件的构建期处理、能力检测与样式兜底行为。
|
||||||
|
- **回滚**:将插件移回原路径,同时恢复 Vite、测试引用与 README 目录说明,保留其他工作区修改。
|
||||||
|
- **关联**:`vite.config.js`、`tests/{legacy-css-layers,environment}.test.js`、`README.md`。
|
||||||
|
|
||||||
|
### 修复 · 控制台设置表单警告与重复布局测量
|
||||||
|
|
||||||
|
- **范围**:`/console/setting` 的共享表单、运营、支付、WeyAi、模型定价、系统与内容防护设置,以及共享表格宽度测量。
|
||||||
|
- **变更**:迁移 `labelAlign` 的旧值并保留适配映射;静态表单依靠字段订阅更新,减少整表刷新;单选组标签关联到真实输入框,补齐运营汇率组合控件的标签关联;WeyAi 密码框归入表单,设置页输入补齐稳定标识与自动填充用途;模型定价表格使用模型名称作为行键;系统说明改用原生 `title`;表格复用 ResizeObserver 的尺寸结果,避免重复读取操作按钮宽度。
|
||||||
|
- **影响**:保留设置项、权限、保存回调、请求与载荷;减少应用侧重复渲染及同步布局读取,开发模式下第三方组件首次测量仍可能触发浏览器性能提示。
|
||||||
|
- **回滚**:仅还原本条涉及的表单、控件、表格和设置页差异,保留工作区其他修改。
|
||||||
|
- **关联**:`src/components/ui/{form,controls,CenterActionTable}.jsx`、`src/components/console/ConsolePrimitives.jsx`、`test/unit/{form-labels,antd-v6-contracts}.test.js`。
|
||||||
|
|
||||||
|
### 调整 · 顶部企业中心与控制台互换位置
|
||||||
|
|
||||||
|
- **范围**:桌面顶部导航与移动端主导航菜单。
|
||||||
|
- **变更**:公共导航顺序由“用户中心 → 控制台 → WeyAi → 企业中心”调整为“用户中心 → 企业中心 → WeyAi → 控制台”;未显示的入口按原条件过滤。
|
||||||
|
- **影响**:只交换两项的位置,保留权限、企业归属、模块开关、目标链接与激活态规则。
|
||||||
|
- **回滚**:仅还原 `src/hooks/common/useNavigation.js` 中企业中心与控制台的数组位置。
|
||||||
|
- **关联**:`Navigation.jsx`、`MobileNavMenu.jsx` 共用 `mainNavLinks`。
|
||||||
|
|
||||||
|
### 工具 · 统一 npm 安装与构建
|
||||||
|
|
||||||
|
- **范围**:Bun 锁文件、锁文件忽略规则、Vercel 配置与 README。
|
||||||
|
- **变更**:移除 `bun.lock`,忽略 Bun 两种锁文件;Vercel 显式使用 `npm ci` 安装、`npm run build` 构建。
|
||||||
|
- **影响**:项目依赖与脚本已使用 Node.js + npm,无 Bun 专属依赖需要卸载;保留现有 `package-lock.json` 与依赖版本。
|
||||||
|
- **回滚**:从改动前版本恢复 `bun.lock`,并仅还原本条涉及的忽略规则、部署配置与 README 段落。
|
||||||
|
- **关联**:`package.json`、`package-lock.json`、`vercel.json`。
|
||||||
|
|
||||||
|
### 修复 · WeyAi 下载页与顶部菜单统一主题
|
||||||
|
|
||||||
|
- **范围**:`/weyai/download`、用户中心内嵌下载页,以及共享顶栏的账户、语言与主导航菜单。
|
||||||
|
- **变更**:本站下载页进入系统样式作用域,修复头像浮层缺少背景与颜色变量;下载页复用公共页头与原生 antd 按钮、标签、骨架,对齐浅深主题、卡片、间距、图标和响应式布局,移除旧装饰渐变与悬浮动效。顶部菜单使用原生 antd 菜单与可聚焦触发器,账户和语言菜单支持点击,下载页锚点跟随实际顶栏高度并遵守减少动态效果偏好。
|
||||||
|
- **影响**:仅调整展示与菜单操作方式,保留下载地址、开放范围、权限判断、请求、语言与主题持久化;其他 WeyAI 外部页仍使用原作用域。
|
||||||
|
- **回滚**:按本条涉及的下载页、`UiThemeProvider.jsx` 与顶栏菜单组件差异还原,保留其他工作区修改。
|
||||||
|
- **关联**:`docs/ui/GLOBAL_UI_BASELINE.md` 第 1、4 节;`docs/standards/UI_COMPONENT_STANDARDS.md`。
|
||||||
|
|
||||||
|
### 修复 · 企业员工顶栏提示栏上下间距
|
||||||
|
|
||||||
|
- **范围**:`/console/setting?tab=operation` 的“企业员工顶栏”说明提示栏。
|
||||||
|
- **变更**:上下外边距统一为 16px,避免提示栏紧贴上方说明文字;内边距、正文与图标继续使用控制台公共提示栏样式。
|
||||||
|
- **影响**:仅调整该提示栏的展示间距,配置开关、保存逻辑和请求保持原样。
|
||||||
|
- **回滚**:将 `SettingsOrgUserNavModules.jsx` 中该提示栏的 `marginBlock` 恢复为原 `marginBottom`。
|
||||||
|
- **关联**:`docs/ui/CONSOLE_SPEC.md` 第 3 节。
|
||||||
|
|
||||||
|
### 规范 · 适配层日期契约、标签写法与控制台页头
|
||||||
|
|
||||||
|
- **范围**:`src/components/ui/controls.jsx`;`docs/standards/{DEV_STANDARDS,UI_COMPONENT_STANDARDS}.md`、`docs/ui/{ORG_CENTER_SPEC,CONSOLE_SPEC}.md`。
|
||||||
|
- **变更**:适配层 `DatePicker` / `TimePicker` 的 `onChange` 改回 Semi 契约 `(Date, 文本)` 并转换 date-fns `format`;标签无边框写法改为 `variant='filled'`;控制台页头新增 `hideHeading`。
|
||||||
|
- **影响**:修复按旧契约把首参当 `Date` 的十余处日期筛选与表单(企业密钥自定义过期、订单、消耗明细、数据看板等);`ArticleEditor`、WeyAi 内容与发布说明三处改取对应参数。
|
||||||
|
- **回滚**:`controls.jsx` 与上述三处调用方需一起还原;文档按文件还原。
|
||||||
|
- **关联**:`docs/standards/DEV_STANDARDS.md` 2.3
|
||||||
|
|
||||||
|
### 调整 · 隐藏用户中心服务监控
|
||||||
|
|
||||||
|
- **范围**:用户中心桌面侧栏、移动端底栏、服务监控路由与面包屑。
|
||||||
|
- **变更**:移除服务监控菜单,原页面地址与旧 `/service-dashboard` 地址均跳转到用户中心首个已开放页面;默认页候选排除服务监控,无可用页面时回到首页。
|
||||||
|
- **影响**:服务监控不再挂载,不触发该页面的监控请求;保留页面源码与后台配置,其他菜单沿用原有配置。
|
||||||
|
- **回滚**:仅还原本条涉及的用户中心入口、侧栏、面包屑及服务监控规范差异。
|
||||||
|
- **关联**:`docs/ui/SERVICE_DASHBOARD_SPEC.md`。
|
||||||
|
|
||||||
## 2026-11-17
|
## 2026-11-17
|
||||||
|
|
||||||
### 调整 · 官网设置指标只填数字并实时预览官网展示
|
### 调整 · 官网设置指标只填数字并实时预览官网展示
|
||||||
|
|||||||
@@ -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-17 · 版本:v2.2
|
> 状态:有效 · 适用:React 18.3、antd 6.7.0、Vite 5.4、Node ≥ 22.13 · 更新:2026-11-18 · 版本:v2.3
|
||||||
|
|
||||||
新增与重构 CRUD 的编码规范:目录与命名、组件选择、请求、React 组件与状态、表单与弹层、权限、i18n,以及可直接复制的页面模板。外观取值见 `UI_COMPONENT_STANDARDS.md`。
|
新增与重构 CRUD 的编码规范:目录与命名、组件选择、请求、React 组件与状态、表单与弹层、权限、i18n,以及可直接复制的页面模板。外观取值见 `UI_COMPONENT_STANDARDS.md`。
|
||||||
|
|
||||||
@@ -100,7 +100,7 @@ ESLint 规则 `header/header` 要求每个 `.js/.jsx` 顶部带 AGPL 许可证
|
|||||||
| `Tag` | 旧 `white` / `grey` → antd `default` | 用白底自定义样式模拟普通标签 |
|
| `Tag` | 旧 `white` / `grey` → antd `default` | 用白底自定义样式模拟普通标签 |
|
||||||
| `Dropdown` | 桌面默认 hover、触屏默认 click,显式 `trigger` 优先 | 强行统一触发方式 |
|
| `Dropdown` | 桌面默认 hover、触屏默认 click,显式 `trigger` 优先 | 强行统一触发方式 |
|
||||||
| `Card` | 存量 `bordered` 由适配层映射为 `variant` | 新代码继续写 `bordered` |
|
| `Card` | 存量 `bordered` 由适配层映射为 `variant` | 新代码继续写 `bordered` |
|
||||||
| `DatePicker` | 适配层保留字符串与 `Date` 的边界转换;新代码直接用 dayjs | 混用两种值类型 |
|
| `DatePicker` / `TimePicker` | 与 Semi 一致:`onChange(Date \| Date[] \| null, 文本 \| 文本[])`,`Form.DatePicker` 字段值为 `Date`;`format` 可写 date-fns 记法(自动转 dayjs);新代码直接用 antd + dayjs | 把首参当文本或对文本调用 `.getTime()`;需要文本时取第二个参数 |
|
||||||
| `Upload` | 手动上传在 `beforeUpload` 返回 `false`,保留文件实例、校验与列表 | 手动上传时自动发请求;`autoRemove` 的文件仍显示 |
|
| `Upload` | 手动上传在 `beforeUpload` 返回 `false`,保留文件实例、校验与列表 | 手动上传时自动发请求;`autoRemove` 的文件仍显示 |
|
||||||
| `Layout` | 侧栏布局显式控制 `hasSider` | 自动 `hasSider` 把内容列压成零宽 |
|
| `Layout` | 侧栏布局显式控制 `hasSider` | 自动 `hasSider` 把内容列压成零宽 |
|
||||||
| `CardPro` | 多行筛选区完整显示,正文独立滚动 | 筛选区被收缩或截断、与正文重叠 |
|
| `CardPro` | 多行筛选区完整显示,正文独立滚动 | 筛选区被收缩或截断、与正文重叠 |
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# UI 公共组件与样式规范
|
# UI 公共组件与样式规范
|
||||||
|
|
||||||
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-17 · 版本:v2.3
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v2.5
|
||||||
|
|
||||||
所有后台页面共用的主题与组件标准。页面规范只记录与本文不同的部分;编码约定见 `DEV_STANDARDS.md`,外壳与布局见 `GLOBAL_UI_BASELINE.md`。
|
所有后台页面共用的主题与组件标准。页面规范只记录与本文不同的部分;编码约定见 `DEV_STANDARDS.md`,外壳与布局见 `GLOBAL_UI_BASELINE.md`。
|
||||||
|
|
||||||
@@ -208,6 +208,7 @@ html.dark .km-page {
|
|||||||
| 类型 | 用法 |
|
| 类型 | 用法 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 列表页签 | antd `Tabs`;导航与下方内容间距 20px(控制台 16px);页签间距 28px;文字 14 / 22px;选中与悬停为品牌色,2px 下划线 |
|
| 列表页签 | antd `Tabs`;导航与下方内容间距 20px(控制台 16px);页签间距 28px;文字 14 / 22px;选中与悬停为品牌色,2px 下划线 |
|
||||||
|
| 卡片首部页签 | 控制台卡片主体以 `Tabs` 开始、页签上方没有标题或提示时,主体顶部内边距 8px,参考 `/console/website-setting`、`/console/smart-router`;保留页签默认上下内边距 12px、导航高 46px、与下方内容间距 16px,不叠加空白占位或顶部外边距。卡片其余内边距不变;页签前有错误提示或说明块时按对应容器规则处理。浅深主题、桌面与移动端一致。 |
|
||||||
| 筛选页签 | 只切换筛选条件时隐藏内容区(企业中心 `.oc-tabs-nav-only`),筛选结果由下方列表卡展示 |
|
| 筛选页签 | 只切换筛选条件时隐藏内容区(企业中心 `.oc-tabs-nav-only`),筛选结果由下方列表卡展示 |
|
||||||
| 分段控件 | 2–4 个互斥选项(如趋势维度、充值类型、头像类型)用 `Segmented`,`onChange(value)` 直接接值处理函数 |
|
| 分段控件 | 2–4 个互斥选项(如趋势维度、充值类型、头像类型)用 `Segmented`,`onChange(value)` 直接接值处理函数 |
|
||||||
| 预渲染 | 原先预渲染全部页签的页面保留 `forceRender`,不改变请求时机 |
|
| 预渲染 | 原先预渲染全部页签的页面保留 `forceRender`,不改变请求时机 |
|
||||||
@@ -216,7 +217,7 @@ 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 预设),不用非预设色名。
|
||||||
- 全局默认描边;卡片内的分类标签与企业中心表格标签用 `bordered={false}`。标签间距 8px,表格内标签不留右外边距。
|
- 全局默认描边;卡片内的分类标签与企业中心表格标签用无边框样式,新代码写 `variant='filled'`(antd 6 已弃用 `bordered={false}`,二者视觉等价;存量写法可在修改时顺带收敛)。标签间距 8px,表格内标签不留右外边距。
|
||||||
- 可启停的记录用 `Switch size='small'`,`onChange` 调原处理函数;无启停接口的列表保留只读 `Tag`。
|
- 可启停的记录用 `Switch size='small'`,`onChange` 调原处理函数;无启停接口的列表保留只读 `Tag`。
|
||||||
|
|
||||||
## 12. 按钮与图标
|
## 12. 按钮与图标
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# 控制台 UI 规范(/console/\*)
|
# 控制台 UI 规范(/console/\*)
|
||||||
|
|
||||||
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-11 · 版本:v2.2
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v2.4
|
||||||
|
|
||||||
管理控制台 `/console/*` 的规范:统一页头、控制台原语与差异样式。
|
管理控制台 `/console/*` 的规范:统一页头、控制台原语与差异样式。
|
||||||
|
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
|
|
||||||
| 关注点 | 规则 |
|
| 关注点 | 规则 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 页头 | `ConsolePageContainer` 统一挂载;元信息登记在 `consoleRoutes.js` |
|
| 页头 | `ConsolePageContainer` 统一挂载;元信息登记在 `consoleRoutes.js`;页面自带随子视图变化的标题时设 `hideHeading`,外壳只保留面包屑 |
|
||||||
| 原语 | `ConsolePrimitives.jsx`:Alert、Card、SearchBar、SearchActions、Form、Table、Tabs、Modal、Drawer |
|
| 原语 | `ConsolePrimitives.jsx`:Alert、Card、SearchBar、SearchActions、Form、Table、Tabs、Modal、Drawer |
|
||||||
| 样式差异 | 卡头 56px / 16px;筛选 4 列;表头底色 `colorFillAlter`;弹层默认 560px |
|
| 样式差异 | 卡头 56px / 16px;筛选 4 列;表头底色 `colorFillAlter`;弹层默认 560px |
|
||||||
| 系统设置 | 统一纵向表单;控制台不显示紧凑模式切换 |
|
| 系统设置 | 统一纵向表单;控制台不显示紧凑模式切换 |
|
||||||
@@ -39,7 +39,7 @@
|
|||||||
| 文件 | 职责 |
|
| 文件 | 职责 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `ConsolePageContainer.jsx` | 唯一页头:面包屑、标题、描述、页级操作插槽;页面操作经 `ConsolePageActions` 保留原回调 |
|
| `ConsolePageContainer.jsx` | 唯一页头:面包屑、标题、描述、页级操作插槽;页面操作经 `ConsolePageActions` 保留原回调 |
|
||||||
| `consoleRoutes.js` | `consolePages` 元信息(`key`、`title`、`description`)、菜单路径;最长父路由匹配、动态详情与未知路径兜底 |
|
| `consoleRoutes.js` | `consolePages` 元信息(`key`、`title`、`description`、可选 `hideHeading`)、菜单路径;最长父路由匹配、动态详情与未知路径兜底 |
|
||||||
| `ConsoleContext.jsx` | 页面上下文、搜索控件尺寸上下文、主题 token 到 `--console-*` 的映射;不新增 ConfigProvider 或存储 key |
|
| `ConsoleContext.jsx` | 页面上下文、搜索控件尺寸上下文、主题 token 到 `--console-*` 的映射;不新增 ConfigProvider 或存储 key |
|
||||||
| `ConsolePrimitives.jsx` | `ConsoleAlert`、`ConsoleCard`、`ConsoleSearchBar`、`ConsoleSearchActions`、`ConsoleForm`、`ConsoleTable`、`ConsoleTabs`、`ConsoleModal`、`ConsoleDrawer` |
|
| `ConsolePrimitives.jsx` | `ConsoleAlert`、`ConsoleCard`、`ConsoleSearchBar`、`ConsoleSearchActions`、`ConsoleForm`、`ConsoleTable`、`ConsoleTabs`、`ConsoleModal`、`ConsoleDrawer` |
|
||||||
| `ConsoleCollection.jsx` | 把 `CardPro` 的统计、查询、操作、表格、分页插槽编排为标准卡片;移动端查询可展开 / 收起 |
|
| `ConsoleCollection.jsx` | 把 `CardPro` 的统计、查询、操作、表格、分页插槽编排为标准卡片;移动端查询可展开 / 收起 |
|
||||||
@@ -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 详情的审核工作台仅由抽屉正文纵向滚动,技能原文不设置独立滚动区;审核操作进入抽屉固定页脚,按钮右对齐、间距 8px,仅在审核页签展示。
|
||||||
- 官网文章抽屉允许点击遮罩关闭,X、取消、遮罩共用同一未保存内容确认流程。
|
- 官网文章抽屉允许点击遮罩关闭,X、取消、遮罩共用同一未保存内容确认流程。
|
||||||
|
|
||||||
## 4. 验收要点
|
## 4. 验收要点
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# 后台 UI 全局基线
|
# 后台 UI 全局基线
|
||||||
|
|
||||||
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-17 · 版本:v3.6
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v3.11
|
||||||
|
|
||||||
后台外壳与布局基线:顶栏、侧栏、公告、页头与内容边距、登录页,以及原型未定义场景、登录关卡与验收流程。主题与组件样式见 `UI_COMPONENT_STANDARDS.md`。
|
后台外壳与布局基线:顶栏、侧栏、公告、页头与内容边距、登录页,以及原型未定义场景、登录关卡与验收流程。主题与组件样式见 `UI_COMPONENT_STANDARDS.md`。
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
|
|
||||||
- 原型定义的颜色、尺寸、样式、状态与视觉交互优先;原型只作视觉依据,不作业务、数据、状态、接口、路由依据。
|
- 原型定义的颜色、尺寸、样式、状态与视觉交互优先;原型只作视觉依据,不作业务、数据、状态、接口、路由依据。
|
||||||
- 专项规范见 `docs/README.md` 索引;专项未覆盖的部分按本文执行。
|
- 专项规范见 `docs/README.md` 索引;专项未覆盖的部分按本文执行。
|
||||||
- 不重做:WeyAI 外部页与第三方 SDK 的内部视觉;体验中心只检查宿主布局。图表、流程画布、编辑器与新手引导保留专用组件。
|
- 不重做:WeyAI 外部页与第三方 SDK 的内部视觉;本站托管的 `/weyai/download` 属于系统页面,沿用统一主题、顶栏与浮层 token。体验中心只检查宿主布局。图表、流程画布、编辑器与新手引导保留专用组件。
|
||||||
- 改造前先列出已覆盖、未覆盖、排除的页面;配置隐藏、权限重定向和原型失效入口单独列出。
|
- 改造前先列出已覆盖、未覆盖、排除的页面;配置隐藏、权限重定向和原型失效入口单独列出。
|
||||||
|
|
||||||
## 2. 目录职责
|
## 2. 目录职责
|
||||||
@@ -52,6 +52,7 @@
|
|||||||
- 桌面高 72px、移动 56px,另含 1px 底部分隔线;背景、文字、分隔线跟随双主题变量。
|
- 桌面高 72px、移动 56px,另含 1px 底部分隔线;背景、文字、分隔线跟随双主题变量。
|
||||||
- 主导航:导航项撑满顶栏,左右内边距 24px;2px 主色下划线两端内缩 16px;选中项主色文字,普通项悬停保留正常文字色,键盘焦点可见。不改链接与权限条件。
|
- 主导航:导航项撑满顶栏,左右内边距 24px;2px 主色下划线两端内缩 16px;选中项主色文字,普通项悬停保留正常文字色,键盘焦点可见。不改链接与权限条件。
|
||||||
- 右侧按钮:主题、公告、语言等图标 16px,工具按钮点击区 34px,账户下拉箭头 10px;`.ui-header-actions` 内图标容器为 inline-flex,使图标与文字垂直居中。
|
- 右侧按钮:主题、公告、语言等图标 16px,工具按钮点击区 34px,账户下拉箭头 10px;`.ui-header-actions` 内图标容器为 inline-flex,使图标与文字垂直居中。
|
||||||
|
- 全站共享顶栏不展示未登录用户的“登录 / 注册”按钮,桌面与移动端一致;已登录用户保留头像与账户菜单,登录 / 注册页面及受保护导航的原有鉴权跳转保持不变。
|
||||||
- 主题按钮为 `Button` + `Tooltip`,点击在浅色与深色之间直接切换,不提供下拉或“跟随系统”;沿用现有主题 setter 与持久化,覆盖 `/org/login`、`/login` 与共享顶栏。
|
- 主题按钮为 `Button` + `Tooltip`,点击在浅色与深色之间直接切换,不提供下拉或“跟随系统”;沿用现有主题 setter 与持久化,覆盖 `/org/login`、`/login` 与共享顶栏。
|
||||||
- WeyAi 下载按钮复用现有下载配置与权限判定,跳转 `/weyai/download`;使用 antd text 按钮默认悬停背景与 `Tooltip`,不硬编码外部地址。
|
- WeyAi 下载按钮复用现有下载配置与权限判定,跳转 `/weyai/download`;使用 antd text 按钮默认悬停背景与 `Tooltip`,不硬编码外部地址。
|
||||||
|
|
||||||
@@ -63,6 +64,7 @@
|
|||||||
|
|
||||||
### 4.3 侧栏
|
### 4.3 侧栏
|
||||||
|
|
||||||
|
- 控制台侧栏显示、路由选中项变化或滚动区尺寸变化后,当前菜单超出可视范围时,仅滚动菜单区域使其完整可见;已可见时不移动,不滚动正文、不抢焦点,也不强制展开用户手动收起的分组。
|
||||||
- 企业中心与用户中心共用 `src/styles/center-layout.css`:展开 216px、收起 64px;菜单行高 42px、行距 6px,图标 16px / 1.5px 线宽;折叠入口文案“收起导航”。
|
- 企业中心与用户中心共用 `src/styles/center-layout.css`:展开 216px、收起 64px;菜单行高 42px、行距 6px,图标 16px / 1.5px 线宽;折叠入口文案“收起导航”。
|
||||||
- 企业信息区为无底框网格图标(24px / 1.65 线宽),内边距 28px 16px 26px,图文间距 10px;企业名与身份 12px / 20px 行高,身份上距 2px。
|
- 企业信息区为无底框网格图标(24px / 1.65 线宽),内边距 28px 16px 26px,图文间距 10px;企业名与身份 12px / 20px 行高,身份上距 2px。
|
||||||
- 个人侧栏只保留容器外侧分隔线,内层 Menu 不叠加 `border-inline-end`;企业侧栏不提供菜单搜索。
|
- 个人侧栏只保留容器外侧分隔线,内层 Menu 不叠加 `border-inline-end`;企业侧栏不提供菜单搜索。
|
||||||
@@ -80,9 +82,9 @@
|
|||||||
|
|
||||||
### 4.5 登录页与认证顶栏
|
### 4.5 登录页与认证顶栏
|
||||||
|
|
||||||
- `/org/login` 与 `/login` 顶栏采用后台标准样式,无品牌条、玻璃渐变与反光层。登录页局部布局 `.auth-login-page`;其他认证顶栏 `.auth-layout-header` 透出既有背景;登录顶栏 `.login-layout-header`。
|
- 认证页(`/login`、`/org/login`、`/org/:slug/login`、`/register`、`/org/register`、`/reset`、`/user/reset`)统一使用登录顶栏 `.login-layout-header` 与局部布局 `.auth-login-page`,顶栏采用后台标准样式,无品牌条、玻璃渐变与反光层;仅客户端授权页 `/client/authorize` 保留 `.auth-layout-header` 透出背景。
|
||||||
- 登录卡片无顶部装饰线与反光;企业 / 个人切换用 antd `Button`;输入框 34px 高、8px 圆角,必填标识经 `Form.Item` 呈现;凭据字段只预留必要的错误提示高度,正常、报错、修正三态布局稳定。
|
- 登录卡片无顶部装饰线、反光、外发光、角落光晕与 Logo 光环 / 星标;企业 / 个人切换用 antd `Button`;输入框、下拉、整行按钮与认证弹窗(`.auth-login-modal`)控件统一 36px 高、8px 圆角(`--auth-control-height`),必填标识经 `Form.Item` 呈现;表单项无下边距,label 12px、与输入框间距 7px,输入框下方固定预留 22px 报错位(`--auth-error-line`),必填与非必填项间距一致,正常、报错、修正三态布局稳定。第三方登录用描边整行按钮,无位移与扫光;分隔线用 `AuthDivider`。规则集中在 `src/styles/prototype.css` 的 `.auth-login-page` 段。
|
||||||
- 副标题、“记住登录名”、管理员重置提示与“忘记密码”使用加深 20% 的次文字色,无悬停底色,“忘记密码”悬停再加深;“切换企业”与“登录”同为主按钮样式。个人登录必填校验用 `rules`,通过后调用原登录处理函数。样式调整不得改变登录校验、回调与载荷。
|
- 副标题、“记住登录名”、管理员重置提示与“忘记密码”使用加深 20% 的次文字色,无悬停底色,“忘记密码”悬停再加深;“切换企业”与“登录”同为主按钮样式。认证表单必填项显示 `*` 并就地提示:输入框“请输入 + label”,选择框“请选择 + label”;邮箱等格式校验沿用原判断与文案;校验用 `rules` / `validate`,通过后调用原处理函数,页面自管的受控输入(企业登录第 1 步)失焦为空时提示且不改按钮禁用条件。样式与校验调整不得改变登录校验、回调与载荷。
|
||||||
|
|
||||||
### 4.6 导航入口
|
### 4.6 导航入口
|
||||||
|
|
||||||
@@ -106,12 +108,12 @@
|
|||||||
- `/console/*` 控制台:超管账号,经 `/login` 登录;不先用普通账号试探控制台权限。
|
- `/console/*` 控制台:超管账号,经 `/login` 登录;不先用普通账号试探控制台权限。
|
||||||
- 共享组件或跨中心改动:追踪实际引用,在受影响的中心分别验收;不同账号使用独立 Context,避免企业、个人与超管会话混用。不因一句泛化测试指令执行无关页面的全量验收。
|
- 共享组件或跨中心改动:追踪实际引用,在受影响的中心分别验收;不同账号使用独立 Context,避免企业、个人与超管会话混用。不因一句泛化测试指令执行无关页面的全量验收。
|
||||||
- 执行前用简短进度说明告知已判断的范围与账号类型,直接继续。先使用现有本地配置;仅在范围经代码分析仍不明确、必要凭据缺失或实际权限不足时询问。用户明确“无需测试”“无需生产测试”等限制优先,普通测试指令不自动授权生产构建或生产环境操作。
|
- 执行前用简短进度说明告知已判断的范围与账号类型,直接继续。先使用现有本地配置;仅在范围经代码分析仍不明确、必要凭据缺失或实际权限不足时询问。用户明确“无需测试”“无需生产测试”等限制优先,普通测试指令不自动授权生产构建或生产环境操作。
|
||||||
2. Base URL 只取 `dev.log` 最后一个 `Local:`(去除 ANSI 色码),禁止写死 IP / 端口;服务可用即复用。Windows 用 `Start-Process -WindowStyle Hidden` 启动并写入 `dev.log`,支持 nohup 的 shell 用 `nohup npm run dev > dev.log 2>&1 &`。
|
2. Base URL 按第 7.1 节通过项目目录、启动日志与监听进程查找并核验,服务可用即复用;日志中的失效地址不能作为新启服务的依据。仅确认不存在时,Windows 用 `Start-Process -WindowStyle Hidden` 启动并写入 `dev.log`,支持 nohup 的 shell 用 `nohup npm run dev > dev.log 2>&1 &`。
|
||||||
3. 企业入口 `{Base URL}/org/login`,`waitForLoadState('networkidle')` 后检查可见非隐藏、非复选框输入框的数量、placeholder / 标签与按钮,打印不含输入值的判定并截图。
|
3. 企业入口 `{Base URL}/org/login`,`waitForLoadState('networkidle')` 后检查可见非隐藏、非复选框输入框的数量、placeholder / 标签与按钮,打印不含输入值的判定并截图。
|
||||||
- 状态 A:一个企业输入框 +“下一步”。先填企业名称,点击“下一步”,等“企业内登录名”“密码”“登录”出现后再填凭据;不得把登录名当企业名,不得跳过企业查询。
|
- 状态 A:一个企业输入框 +“下一步”。先填企业名称,点击“下一步”,等“企业内登录名”“密码”“登录”出现后再填凭据;不得把登录名当企业名,不得跳过企业查询。
|
||||||
- 状态 B:已出现登录名、密码与“登录”。直接填写凭据,保留已解析的企业上下文。
|
- 状态 B:已出现登录名、密码与“登录”。直接填写凭据,保留已解析的企业上下文。
|
||||||
4. 个人端:新建无企业 Cookies / Storage 的 Context,进入 `{Base URL}/login`,按页面原有协议勾选与登录,确认用户中心侧栏与主体渲染后保存 storageState。
|
4. 个人端:新建无企业 Cookies / Storage 的 Context,进入 `{Base URL}/login`,按页面原有协议勾选与登录,确认用户中心侧栏与主体渲染后保存 storageState。
|
||||||
5. 凭据只经环境变量传入:企业 `UI_ORG_NAME` / `UI_ORG_USER` / `UI_ORG_PASS`,普通个人 `UI_PERSONAL_USER` / `UI_PERSONAL_PASS`,超管 `UI_ADMIN_USER` / `UI_ADMIN_PASS`。本机可通过确认未跟踪且已忽略的 `.env.playwright.local` 加载,不要求用户在每次任务中重新提供;不得输出其值,不写入脚本、日志、截图注释、报告或提交;登录阶段不录 trace / HAR。本地入口、跟踪 / 忽略检查和账号选择参数见 `README.md` 的“本地 Playwright 登录配置”。
|
5. 凭据只经环境变量传入:企业 `UI_ORG_NAME` / `UI_ORG_USER` / `UI_ORG_PASS`,普通个人 `UI_PERSONAL_USER` / `UI_PERSONAL_PASS`,超管 `UI_ADMIN_USER` / `UI_ADMIN_PASS`。本机通过 `.env.playwright.local` 加载,不要求用户每次重新提供;该文件仅保存测试账号,按用户约定不作 Git 忽略,允许入库。值仍不得回显或写入脚本、日志、截图注释、报告;登录阶段不录 trace / HAR,其他凭据与 storageState 不入库。本地入口和账号选择参数见 `README.md` 的“本地 Playwright 登录配置”。
|
||||||
6. 失败时截图,记录 `dev.log` 尾部与失败请求(密码、Cookie、token、ticket 脱敏),写入风险;不盲目重试,不改登录业务代码。
|
6. 失败时截图,记录 `dev.log` 尾部与失败请求(密码、Cookie、token、ticket 脱敏),写入风险;不盲目重试,不改登录业务代码。
|
||||||
7. 结束时通过顶栏用户菜单“退出登录”,确认回到登录页(当前为 `/org/login`)且受保护路由不再渲染。
|
7. 结束时通过顶栏用户菜单“退出登录”,确认回到登录页(当前为 `/org/login`)且受保护路由不再渲染。
|
||||||
|
|
||||||
@@ -120,7 +122,7 @@
|
|||||||
### 7.1 工具
|
### 7.1 工具
|
||||||
|
|
||||||
- 优先使用项目 Playwright 配置(`playwright.config.js`:`testDir: ./e2e`、`workers` 默认 1,可由正整数 `PW_WORKERS` 覆盖)与本机 Chrome(`channel: 'chrome'`)。默认离屏,保留 `UI_VISUAL_OFFSCREEN=1`(只降低可见干扰,不保证没有瞬时焦点激活);要求不启动有头窗口时可用无头模式并在报告注明。
|
- 优先使用项目 Playwright 配置(`playwright.config.js`:`testDir: ./e2e`、`workers` 默认 1,可由正整数 `PW_WORKERS` 覆盖)与本机 Chrome(`channel: 'chrome'`)。默认离屏,保留 `UI_VISUAL_OFFSCREEN=1`(只降低可见干扰,不保证没有瞬时焦点激活);要求不启动有头窗口时可用无头模式并在报告注明。
|
||||||
- 运行前从 `dev.log` 最后一个 `Local:` 提取地址;runner 复用服务时设 `PW_TARGET=remote` + `PW_BASE_URL`,不会启动或关闭已有服务。专项脚本是否接收 `PLAYWRIGHT_BASE_URL` 以其实现为准,不能用它替代 runner 的 `PW_BASE_URL`。Playwright 失败先排查服务地址、元素定位、等待条件、浏览器环境与登录状态。
|
- 测试优先复用用户已启动的本项目开发服务:结合项目目录、启动日志(优先 `dev.log`,兼容 UTF-8 / UTF-16LE)、进程和监听端口查找候选地址,验证响应属于当前项目。历史日志地址失效时继续查找,不得直接启动新服务;仅确认本项目服务不存在时才启动,并记录、清理本次进程,不结束用户进程。项目 Playwright 配置通过 `scripts/dev-service.mjs` 自动发现服务并以 `PW_TARGET=remote` + `PW_BASE_URL` 复用;显式指定目标时保留调用方配置。专项脚本是否接收 `PLAYWRIGHT_BASE_URL` 以其实现为准,不能用它替代 runner 的 `PW_BASE_URL`。Playwright 失败先排查服务地址、元素定位、等待条件、浏览器环境与登录状态。
|
||||||
- 默认 runner 为浅色、1920×1080 / 360×800,本地有头、CI 无头,`webServer.reuseExistingServer=false`;默认执行不等于完成第 7.3 节浅深主题与规范视口矩阵,须在用例或专项脚本补足。严格有头焦点约束见第 7.1.1 节。
|
- 默认 runner 为浅色、1920×1080 / 360×800,本地有头、CI 无头,`webServer.reuseExistingServer=false`;默认执行不等于完成第 7.3 节浅深主题与规范视口矩阵,须在用例或专项脚本补足。严格有头焦点约束见第 7.1.1 节。
|
||||||
- `e2e/` 为本地忽略目录,验收脚本不随仓库分发;新增脚本同样放在该目录。
|
- `e2e/` 为本地忽略目录,验收脚本不随仓库分发;新增脚本同样放在该目录。
|
||||||
|
|
||||||
@@ -150,7 +152,7 @@
|
|||||||
| 设备源 | `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;扩展增加 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;viewport 覆盖为 360×800,screen 沿用模板;平板仅为桌面设备的平板尺寸 |
|
||||||
| 本地目标 | `PW_TARGET=local-dev` 默认启动 `http://127.0.0.1:4176/`,weelink 使用 4175;开发和预览均严格占用指定端口,禁止静默回退 |
|
| 本地目标 | 未指定目标时自动发现并复用已有开发服务,确认不存在后才启动 `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 强制无头;隐藏滚动条并禁用后台降频 |
|
||||||
| 并发 | 默认单 worker、文件内不拆分;`PW_WORKERS` 只接受正安全整数,不代表动态内存调度 |
|
| 并发 | 默认单 worker、文件内不拆分;`PW_WORKERS` 只接受正安全整数,不代表动态内存调度 |
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# 模型超市 UI 规范(/market)
|
# 模型超市 UI 规范(/market)
|
||||||
|
|
||||||
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-16 · 版本:v2.4
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v2.5
|
||||||
|
|
||||||
个人端模型超市 `/market` 的规范。本页为独立视觉页面,组件映射优先于公共规范。
|
个人端模型超市 `/market` 的规范。本页为独立视觉页面,组件映射优先于公共规范。
|
||||||
|
|
||||||
@@ -47,7 +47,7 @@
|
|||||||
| 区域 | 写法 |
|
| 区域 | 写法 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 搜索 | `Input`(`allowClear`、前缀图标)+ `Button`(重置 / 搜索 primary) |
|
| 搜索 | `Input`(`allowClear`、前缀图标)+ `Button`(重置 / 搜索 primary) |
|
||||||
| 筛选 | `Card` 位于结果栏下方、厂商分区上方;厂商、计费、分组、标签、端点五组可换行 `Button`(`aria-pressed`);不显示计数;“disabled 或计数为 0”时禁用 |
|
| 筛选 | `Card` 位于结果栏下方、厂商分区上方;仅展示厂商、计费、端点三组可换行 `Button`(`aria-pressed`),隐藏用户分组与模型标签筛选行;不显示计数;“disabled 或计数为 0”时禁用 |
|
||||||
| 筛选展开 | 默认仅显示厂商行;卡头保留重置与“展开更多 / 收起筛选”`Button`,同步 `aria-expanded` / `aria-controls`,收起不清空条件;装饰品牌图标设 `aria-hidden` |
|
| 筛选展开 | 默认仅显示厂商行;卡头保留重置与“展开更多 / 收起筛选”`Button`,同步 `aria-expanded` / `aria-controls`,收起不清空条件;装饰品牌图标设 `aria-hidden` |
|
||||||
| 分区标题 | `.mm-section-title`:图标框 + h2 + “N 款模型” |
|
| 分区标题 | `.mm-section-title`:图标框 + h2 + “N 款模型” |
|
||||||
| 卡片 | `Card`(`role=button`,Enter / Space 打开);价格格、缓存行、页脚分组与折扣 `Tag`、复制 `Button` + `Tooltip` |
|
| 卡片 | `Card`(`role=button`,Enter / Space 打开);价格格、缓存行、页脚分组与折扣 `Tag`、复制 `Button` + `Tooltip` |
|
||||||
@@ -110,7 +110,7 @@
|
|||||||
## 8. 验收要点
|
## 8. 验收要点
|
||||||
|
|
||||||
- 搜索仅对 `model_name` 做不区分大小写的子串匹配,忽略关键词首尾空格;描述、标签、厂商名称不参与关键词匹配,其他筛选条件仍取交集;保留原前端防抖,不新增搜索请求。
|
- 搜索仅对 `model_name` 做不区分大小写的子串匹配,忽略关键词首尾空格;描述、标签、厂商名称不参与关键词匹配,其他筛选条件仍取交集;保留原前端防抖,不新增搜索请求。
|
||||||
- 视口 1920×1000 与 393×851,浅深主题;交互序列:默认厂商行 → 展开五组条件 → 选择分组 → 收起仍保持筛选与价格 → 重置 → 悬停卡片 → 键盘聚焦卡片 → 关键词搜索 → 选择厂商 → 空结果 → 整页滚动到底与厂商懒渲染 → 打开详情。
|
- 视口 1920×1000 与 393×851,浅深主题;交互序列:默认厂商行 → 展开三组条件,确认用户分组与模型标签不显示 → 选择计费或端点 → 收起仍保持筛选与价格 → 重置 → 悬停卡片 → 键盘聚焦卡片 → 关键词搜索 → 选择厂商 → 空结果 → 整页滚动到底与厂商懒渲染 → 打开详情。
|
||||||
- 响应式补充 3840×2160、2560×1440、1920×1080、中屏及断点两侧、360×800;检查两侧留白、卡片宽度、正文换行、无横向溢出,以及筛选展开和详情在窄屏上的可达性。
|
- 响应式补充 3840×2160、2560×1440、1920×1080、中屏及断点两侧、360×800;检查两侧留白、卡片宽度、正文换行、无横向溢出,以及筛选展开和详情在窄屏上的可达性。
|
||||||
- 与原型比较时使用同构模拟目录并标注;真实后端另行验证;整页 ≤ 0.5%、组件 ≤ 0.2%。
|
- 与原型比较时使用同构模拟目录并标注;真实后端另行验证;整页 ≤ 0.5%、组件 ≤ 0.2%。
|
||||||
- 本地截图回归断言非 GET `/api/` 请求为 0。
|
- 本地截图回归断言非 GET `/api/` 请求为 0。
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# 企业中心 UI 规范(/org/\*)
|
# 企业中心 UI 规范(/org/\*)
|
||||||
|
|
||||||
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-11 · 版本:v2.2
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v2.3
|
||||||
|
|
||||||
企业中心 12 个目标页的规范:企业中心变量、通用组件的企业中心变体与各页面规则。
|
企业中心 12 个目标页的规范:企业中心变量、通用组件的企业中心变体与各页面规则。
|
||||||
|
|
||||||
@@ -40,7 +40,7 @@
|
|||||||
| `--oc-page-bg` | `#f8fafc` | `--surface-bg-base` | 页面底 |
|
| `--oc-page-bg` | `#f8fafc` | `--surface-bg-base` | 页面底 |
|
||||||
| `--oc-card-shadow` | `0 3px 18px #25354a03` | 同左 | 列表卡阴影 |
|
| `--oc-card-shadow` | `0 3px 18px #25354a03` | 同左 | 列表卡阴影 |
|
||||||
|
|
||||||
- 标签统一 `bordered={false}`;非 antd 预设色(如 `amber`、`violet`)改用 `gold` / `purple`。
|
- 标签统一无边框(新代码 `variant='filled'`,等价于已弃用的 `bordered={false}`);非 antd 预设色(如 `amber`、`violet`)改用 `gold` / `purple`。
|
||||||
- 消耗明细页根节点由 `useOrgLogsThemeStyle()` 注入 `--oc-brand`(浅色与自定义主色跟随 `colorPrimary`,默认暗色为 `#f2ad41`)、`--oc-stat-brand-bg`(品牌色 6.3% `color-mix`)与 `--ur-progress-done`。
|
- 消耗明细页根节点由 `useOrgLogsThemeStyle()` 注入 `--oc-brand`(浅色与自定义主色跟随 `colorPrimary`,默认暗色为 `#f2ad41`)、`--oc-stat-brand-bg`(品牌色 6.3% `color-mix`)与 `--ur-progress-done`。
|
||||||
- 新增样式用 `:where()` 包裹作用域祖先,不使用 `!important`。
|
- 新增样式用 `:where()` 包裹作用域祖先,不使用 `!important`。
|
||||||
|
|
||||||
@@ -53,7 +53,7 @@
|
|||||||
- **筛选卡 `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`。
|
||||||
- **标签**:表格与卡片内标签统一 `bordered={false}`;非 antd 预设色改用 `gold` / `purple`。
|
- **标签**:表格与卡片内标签统一无边框(`variant='filled'`);非 antd 预设色改用 `gold` / `purple`。
|
||||||
- **启停开关**:密钥、员工调原处理函数;项目禁用沿用确认 + DELETE、启用复用编辑 PUT;预算复用编辑 PUT 并透传主体、原始额度、周期、自定义天数与超限动作,主体已删除时禁用开关。
|
- **启停开关**:密钥、员工调原处理函数;项目禁用沿用确认 + DELETE、启用复用编辑 PUT;预算复用编辑 PUT 并透传主体、原始额度、周期、自定义天数与超限动作,主体已删除时禁用开关。
|
||||||
- **弹层**:`OrgModal` / `OrgSideSheet` 使用原型风格遮罩(`--oc-mask-bg` `rgba(0,0,0,.3)` + `--oc-mask-blur` 4px),只作用于企业中心目标页;表单竖排、`requiredMark={false}`,字段说明用 `extra`。
|
- **弹层**:`OrgModal` / `OrgSideSheet` 使用原型风格遮罩(`--oc-mask-bg` `rgba(0,0,0,.3)` + `--oc-mask-blur` 4px),只作用于企业中心目标页;表单竖排、`requiredMark={false}`,字段说明用 `extra`。
|
||||||
- **企业密钥抽屉 `OrgKeyForm`**:560px;字段为名称、归属项目、密钥分组、过期时间(`Radio.Group.oc-key-expiry`:间距 6px、圆角 6px、描边 `#d9dfe6`,仅“自定义”显示日期选择)与 `Collapse` 高级设置(额度设置 + `Divider` + 访问限制);`expiryPreset` 只用于视图,取值仍走 `setExpiredTime`。
|
- **企业密钥抽屉 `OrgKeyForm`**:560px;字段为名称、归属项目、密钥分组、过期时间(`Radio.Group.oc-key-expiry`:间距 6px、圆角 6px、描边 `#d9dfe6`,仅“自定义”显示日期选择)与 `Collapse` 高级设置(额度设置 + `Divider` + 访问限制);`expiryPreset` 只用于视图,取值仍走 `setExpiredTime`。
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# 服务监控 UI 规范(/user-center/service-dashboard)
|
# 服务监控 UI 规范(/user-center/service-dashboard)
|
||||||
|
|
||||||
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-11 · 版本:v2.1
|
> 状态:有效(页面暂不开放) · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v2.2
|
||||||
|
|
||||||
服务监控页的规范:分组可用性、历史条与详情弹窗。
|
服务监控页的规范:分组可用性、历史条与详情弹窗。
|
||||||
|
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
|
|
||||||
| 关注点 | 规则 |
|
| 关注点 | 规则 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 路由 | `/user-center/service-dashboard`,旧 `/service-dashboard` 重定向 |
|
| 路由 | 桌面侧栏与移动底栏隐藏服务监控;`/user-center/service-dashboard` 及旧 `/service-dashboard` 均回到用户中心首个已开放页面,无可用页面时回到首页;保留页面源码,以下视觉与验收规则供恢复时使用 |
|
||||||
| 组件 | `Card`、`Button`、详情 `Modal` + `Statistic` + `Table`、`Tooltip`、`Spin` / `Empty` |
|
| 组件 | `Card`、`Button`、详情 `Modal` + `Statistic` + `Table`、`Tooltip`、`Spin` / `Empty` |
|
||||||
| 主题 | `theme.useToken()` 注入 `--service-*`;正常态跟随 `colorPrimary`,告警 / 异常用 `colorWarning` / `colorError` |
|
| 主题 | `theme.useToken()` 注入 `--service-*`;正常态跟随 `colorPrimary`,告警 / 异常用 `colorWarning` / `colorError` |
|
||||||
| 业务 | 60 秒自动刷新、逐秒倒计时、分组权限、模型测试与请求不变 |
|
| 业务 | 60 秒自动刷新、逐秒倒计时、分组权限、模型测试与请求不变 |
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# 技能超市 UI 规范(/skill-market)
|
# 技能超市 UI 规范(/skill-market)
|
||||||
|
|
||||||
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-13 · 版本:v2.2
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v2.3
|
||||||
|
|
||||||
个人端技能超市 `/skill-market` 的规范,含真实接口与本地演示两种数据模式。本页为独立视觉页面。
|
个人端技能超市 `/skill-market` 的规范,含真实接口与本地演示两种数据模式。本页为独立视觉页面。
|
||||||
|
|
||||||
@@ -60,6 +60,7 @@
|
|||||||
## 4. 主题与样式
|
## 4. 主题与样式
|
||||||
|
|
||||||
- 不新增 ConfigProvider、主题状态或存储 key;`--sm-brand = colorPrimary`、`--sm-text = colorText`,页面根与详情 Portal(`rootStyle`)共用。
|
- 不新增 ConfigProvider、主题状态或存储 key;`--sm-brand = colorPrimary`、`--sm-text = colorText`,页面根与详情 Portal(`rootStyle`)共用。
|
||||||
|
- 许可证徽标使用 antd 预设调色板色:待审核 / 未知决策用 `gold`、通过用 `green`、阻止用 `red`;背景与描边使用默认预设,文字取对应主题调色板第 9 档 token,提高小字号可读性;不使用非预设色名 `amber` 或固定浅色背景。卡片与详情复用同一 `LicenseBadge`。
|
||||||
- `.sm-theme` / `html.dark .sm-theme` 变量(浅 / 深):页面底 `#f4f6f9` / `#111720`,面板 `#fff` / `#1b232e`,次要字 `#626f80` / `#aab6c5`,边线 `#e0e5ec` / `#344151`,浅金底 `#fff2dc` / `#3c2f1f`,卡片悬停边 `#c39343`;深色文字型主色 `--sm-accent: #f2ad41`。样式规则只引用变量,无 `!important`。
|
- `.sm-theme` / `html.dark .sm-theme` 变量(浅 / 深):页面底 `#f4f6f9` / `#111720`,面板 `#fff` / `#1b232e`,次要字 `#626f80` / `#aab6c5`,边线 `#e0e5ec` / `#344151`,浅金底 `#fff2dc` / `#3c2f1f`,卡片悬停边 `#c39343`;深色文字型主色 `--sm-accent: #f2ad41`。样式规则只引用变量,无 `!important`。
|
||||||
- 侧栏滚动条 6px,悬停或聚焦时显示;卡片列表隐藏滚动条,不写 `scrollbar-width` / `scrollbar-color`。
|
- 侧栏滚动条 6px,悬停或聚焦时显示;卡片列表隐藏滚动条,不写 `scrollbar-width` / `scrollbar-color`。
|
||||||
- 动效:卡片悬停上浮 3px + 光晕;Hero 线路 15s 线性循环,模块 10s 漂浮 7px(延时 0 / -5 / -3 / -7s);仅精确指针设备悬停生效,`prefers-reduced-motion` 时全部停用。
|
- 动效:卡片悬停上浮 3px + 光晕;Hero 线路 15s 线性循环,模块 10s 漂浮 7px(延时 0 / -5 / -3 / -7s);仅精确指针设备悬停生效,`prefers-reduced-motion` 时全部停用。
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# 用户中心 UI 规范(/user-center/\*)
|
# 用户中心 UI 规范(/user-center/\*)
|
||||||
|
|
||||||
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-16 · 版本:v2.3
|
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v2.4
|
||||||
|
|
||||||
个人登录后用户中心页面的规范,只记录与公共规范不同的部分;密钥管理、服务监控见各自规范。
|
个人登录后用户中心页面的规范,只记录与公共规范不同的部分;密钥管理、服务监控见各自规范。
|
||||||
|
|
||||||
@@ -79,6 +79,7 @@
|
|||||||
- 筛选卡: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),操作列文字“查看”,固定在右侧;横向滚动条保留 Ant Design 官方固定列表格行为,固定列兼容规则遵循公共规范第 5.2 节。
|
||||||
|
- 消费记录“用时 / 首字”列宽 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'>` +“复制”链接,复制提示沿用原文案。
|
||||||
|
|
||||||
|
|||||||
+98
@@ -2,6 +2,104 @@
|
|||||||
<html lang="zh">
|
<html lang="zh">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
|
<script id="wl-legacy-polyfills">
|
||||||
|
// 旧内核补丁,针对 Chromium 88~98(停更的 Edge、Win10 LTSC 自带 Edge、国产壳浏览器)。
|
||||||
|
// 打包产物里用到、而这批内核缺失的 JS API 只有下面三个;其中 mermaid 分包在加载时
|
||||||
|
// 就调用 structuredClone,登录/注册等页面静态依赖它,缺了整页报错。
|
||||||
|
// 88 以下不在兜底范围:那些内核连 :is() 选择器都不认,暗色变体等样式本身就会失效。
|
||||||
|
// 每项都只在缺失时才定义,对新浏览器没有任何影响。内联脚本不经过转译,语法须停留在
|
||||||
|
// ES5;且必须排在所有脚本之前。
|
||||||
|
// 样式侧对应的兜底见 vite-plugin-legacy-css-layers.js。
|
||||||
|
(function () {
|
||||||
|
var define = function (target, name, value) {
|
||||||
|
if (typeof target[name] === 'function') return;
|
||||||
|
Object.defineProperty(target, name, {
|
||||||
|
value: value,
|
||||||
|
writable: true,
|
||||||
|
configurable: true,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Chromium 92
|
||||||
|
var at = function (index) {
|
||||||
|
var i = Math.trunc(index) || 0;
|
||||||
|
if (i < 0) i += this.length;
|
||||||
|
return i < 0 || i >= this.length ? undefined : this[i];
|
||||||
|
};
|
||||||
|
define(Array.prototype, 'at', at);
|
||||||
|
define(String.prototype, 'at', at);
|
||||||
|
define(Object.getPrototypeOf(Int8Array).prototype, 'at', at);
|
||||||
|
|
||||||
|
// Chromium 93
|
||||||
|
define(Object, 'hasOwn', function (object, key) {
|
||||||
|
return Object.prototype.hasOwnProperty.call(object, key);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Chromium 98。按调用方实际传入的数据形态实现:普通对象/数组/Date/RegExp/Map/Set/
|
||||||
|
// 二进制缓冲,循环引用与共享引用在克隆结果里保持原有关系;函数与 symbol 按规范抛
|
||||||
|
// DataCloneError。Error、Blob 等宿主对象和 transfer 参数未实现(会被当成普通对象)。
|
||||||
|
define(window, 'structuredClone', function (value) {
|
||||||
|
var seen = new Map();
|
||||||
|
var Shared = window.SharedArrayBuffer;
|
||||||
|
var remember = function (source, copy) {
|
||||||
|
seen.set(source, copy);
|
||||||
|
return copy;
|
||||||
|
};
|
||||||
|
var clone = function (v) {
|
||||||
|
if (typeof v === 'function' || typeof v === 'symbol') {
|
||||||
|
throw new DOMException('uncloneable value', 'DataCloneError');
|
||||||
|
}
|
||||||
|
if (v === null || typeof v !== 'object') return v;
|
||||||
|
if (seen.has(v)) return seen.get(v);
|
||||||
|
if (v instanceof Date) return remember(v, new Date(v.getTime()));
|
||||||
|
if (v instanceof RegExp) {
|
||||||
|
return remember(v, new RegExp(v.source, v.flags));
|
||||||
|
}
|
||||||
|
if (v instanceof ArrayBuffer) return remember(v, v.slice(0));
|
||||||
|
// 共享内存按规范是共享而非复制;不单列的话它会落进普通对象分支变成 {}
|
||||||
|
if (Shared && v instanceof Shared) return v;
|
||||||
|
if (ArrayBuffer.isView(v)) {
|
||||||
|
// 缓冲区也走 clone:多个视图共享的缓冲区克隆后仍是同一份
|
||||||
|
var buf = clone(v.buffer);
|
||||||
|
var size = v instanceof DataView ? v.byteLength : v.length;
|
||||||
|
return remember(v, new v.constructor(buf, v.byteOffset, size));
|
||||||
|
}
|
||||||
|
var out;
|
||||||
|
if (v instanceof Map) {
|
||||||
|
out = remember(v, new Map());
|
||||||
|
v.forEach(function (item, key) {
|
||||||
|
out.set(clone(key), clone(item));
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (v instanceof Set) {
|
||||||
|
out = remember(v, new Set());
|
||||||
|
v.forEach(function (item) {
|
||||||
|
out.add(clone(item));
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
out = remember(v, Array.isArray(v) ? new Array(v.length) : {});
|
||||||
|
Object.keys(v).forEach(function (key) {
|
||||||
|
var copy = clone(v[key]);
|
||||||
|
if (key !== '__proto__') {
|
||||||
|
out[key] = copy;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 唯独这个键不能赋值:赋值改写的是原型,而不是落成自有属性
|
||||||
|
Object.defineProperty(out, key, {
|
||||||
|
value: copy,
|
||||||
|
writable: true,
|
||||||
|
enumerable: true,
|
||||||
|
configurable: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
return clone(value);
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
<!-- favicon: 后端启动时把 __WL_BRAND_FAVICON__ 替换为 common.Logo(未配置时为 /logo.svg);
|
<!-- favicon: 后端启动时把 __WL_BRAND_FAVICON__ 替换为 common.Logo(未配置时为 /logo.svg);
|
||||||
dev 模式占位符未替换时,下面的内联脚本会重写 href 为 /logo.svg。 -->
|
dev 模式占位符未替换时,下面的内联脚本会重写 href 为 /logo.svg。 -->
|
||||||
<link id="wl-favicon" rel="icon" href="__WL_BRAND_FAVICON__" />
|
<link id="wl-favicon" rel="icon" href="__WL_BRAND_FAVICON__" />
|
||||||
|
|||||||
@@ -24,6 +24,19 @@ import {
|
|||||||
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';
|
||||||
|
import { findDevService } from './scripts/dev-service.mjs';
|
||||||
|
|
||||||
|
if (
|
||||||
|
!process.argv.includes('--list') &&
|
||||||
|
!process.env.PW_TARGET &&
|
||||||
|
!process.env.PW_BASE_URL
|
||||||
|
) {
|
||||||
|
const existing = await findDevService();
|
||||||
|
if (existing) {
|
||||||
|
process.env.PW_TARGET = 'remote';
|
||||||
|
process.env.PW_BASE_URL = existing;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const runtime = runtimeOptions({ defaultPort: 4176, defaultWorkers: 1 });
|
const runtime = runtimeOptions({ defaultPort: 4176, defaultWorkers: 1 });
|
||||||
const { target, baseURL, isCI, headless, workers, outputDir, reportDir } =
|
const { target, baseURL, isCI, headless, workers, outputDir, reportDir } =
|
||||||
|
|||||||
@@ -0,0 +1,941 @@
|
|||||||
|
/** Actual commission UI regression, isolated API fixtures and no remote traffic.
|
||||||
|
* PLAYWRIGHT_MODULE: existing playwright/index.mjs; COMMISSION_QA_OUTPUT: artifacts.
|
||||||
|
* Browser plugin is unavailable; uses existing Playwright/Chromium, no installation.
|
||||||
|
*/
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import os from 'node:os';
|
||||||
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||||
|
|
||||||
|
const webRoot = path.resolve(
|
||||||
|
path.dirname(fileURLToPath(import.meta.url)),
|
||||||
|
'..',
|
||||||
|
);
|
||||||
|
process.chdir(webRoot);
|
||||||
|
const out =
|
||||||
|
process.env.COMMISSION_QA_OUTPUT ||
|
||||||
|
fs.mkdtempSync(path.join(os.tmpdir(), 'commission-qa-'));
|
||||||
|
fs.mkdirSync(out, { recursive: true });
|
||||||
|
const { chromium } = await import(
|
||||||
|
process.env.PLAYWRIGHT_MODULE
|
||||||
|
? pathToFileURL(path.resolve(process.env.PLAYWRIGHT_MODULE)).href
|
||||||
|
: 'playwright'
|
||||||
|
);
|
||||||
|
const { createServer, loadConfigFromFile } = await import(
|
||||||
|
pathToFileURL(path.join(webRoot, 'node_modules/vite/dist/node/index.js')).href
|
||||||
|
);
|
||||||
|
const { config: base } = await loadConfigFromFile(
|
||||||
|
{ command: 'serve', mode: 'development' },
|
||||||
|
path.join(webRoot, 'vite.config.js'),
|
||||||
|
);
|
||||||
|
const entry = path
|
||||||
|
.join(webRoot, 'src/__commission-qa.jsx')
|
||||||
|
.replaceAll('\\', '/');
|
||||||
|
const server = await createServer({
|
||||||
|
...base,
|
||||||
|
configFile: false,
|
||||||
|
root: webRoot,
|
||||||
|
cacheDir: path.join(out, 'vite-cache'),
|
||||||
|
optimizeDeps: { ...base.optimizeDeps, force: false },
|
||||||
|
server: { host: '127.0.0.1', port: 0, strictPort: false, proxy: {} },
|
||||||
|
plugins: [
|
||||||
|
...base.plugins,
|
||||||
|
{
|
||||||
|
name: 'commission-adjustment-qa',
|
||||||
|
configureServer(vite) {
|
||||||
|
vite.middlewares.use('/api/', (_req, res) => {
|
||||||
|
res.statusCode = 503;
|
||||||
|
res.end('QA requires intercepted API');
|
||||||
|
});
|
||||||
|
vite.middlewares.use('/__commission-qa.html', async (_req, res) => {
|
||||||
|
res.setHeader('Content-Type', 'text/html');
|
||||||
|
res.end(
|
||||||
|
await vite.transformIndexHtml(
|
||||||
|
'/__commission-qa.html',
|
||||||
|
'<html><head><title>Commission adjustment QA</title></head><body><div id="root"></div><script type="module" src="/__commission-qa.jsx"></script></body></html>',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
resolveId(id) {
|
||||||
|
if (id === '/__commission-qa.jsx') return entry;
|
||||||
|
},
|
||||||
|
load(id) {
|
||||||
|
if (id === entry)
|
||||||
|
return `
|
||||||
|
import '/src/styles/tokens.css';import '/src/index.css';import '/src/styles/org.css';
|
||||||
|
import React from 'react';import {createRoot} from 'react-dom/client';
|
||||||
|
import i18n from 'i18next';import {initReactI18next} from 'react-i18next';
|
||||||
|
import {MemoryRouter, Routes, Route, useLocation, useNavigate} from 'react-router-dom';
|
||||||
|
import {StatusContext} from '/src/context/Status/index.jsx';import {UserContext} from '/src/context/User/index.jsx';
|
||||||
|
import CommissionV2 from '/src/pages/CommissionV2/index.jsx';
|
||||||
|
import Organization from '/src/pages/Organization/index.jsx';
|
||||||
|
import {OrgProvider} from '/src/context/Org/index.jsx';
|
||||||
|
import {SettlementDialog} from '/src/pages/CommissionV2/operations.jsx';
|
||||||
|
i18n.use(initReactI18next).init({lng:'zh',fallbackLng:'zh',resources:{zh:{translation:{}}},interpolation:{escapeValue:false}});
|
||||||
|
const user={id:1,role:100,username:'qa'};
|
||||||
|
const view=new URLSearchParams(location.search).get('view');
|
||||||
|
const section=new URLSearchParams(location.search).get('section');
|
||||||
|
function RouteProbe(){const route=useLocation();window.__qaNavigate=useNavigate();return <output hidden data-qa-route={route.pathname+route.search}/>;}
|
||||||
|
function SettlementTest(){const [operation,setOperation]=React.useState(null);return <><button onClick={()=>setOperation({kind:'fee'})}>打开测试结算</button><SettlementDialog operation={operation} statement={{id:1,fee_uyuan:0}} items={[]} mutateJSON={async()=>{}} onClose={()=>setOperation(null)} onSaved={()=>{}}/></>}
|
||||||
|
createRoot(document.getElementById('root')).render(<MemoryRouter initialEntries={[view==='org'?'/org/commission'+(section?'?view='+section:''):view==='personal'?'/console/my-commission':'/console/commission'+location.search]}><RouteProbe/><StatusContext.Provider value={[{status:{commission_partner_portal_enabled:true}},()=>{}]}><UserContext.Provider value={[{user,authChecking:false},()=>{}]}><OrgProvider>{view==='org'?<Routes><Route path='/org/*' element={<Organization/>}/></Routes>:view==='settlement'?<SettlementTest/>:<CommissionV2/>}</OrgProvider></UserContext.Provider></StatusContext.Provider></MemoryRouter>);
|
||||||
|
`;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await server.listen();
|
||||||
|
const origin = `http://127.0.0.1:${server.httpServer.address().port}`;
|
||||||
|
console.log('QA origin:', origin, 'Artifacts:', out);
|
||||||
|
let browser;
|
||||||
|
try {
|
||||||
|
browser = await chromium.launch({ headless: true });
|
||||||
|
} catch (error) {
|
||||||
|
await server.close();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
const results = [];
|
||||||
|
let activeState;
|
||||||
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
function deferred() {
|
||||||
|
let resolve;
|
||||||
|
const promise = new Promise((done) => {
|
||||||
|
resolve = done;
|
||||||
|
});
|
||||||
|
return { promise, resolve };
|
||||||
|
}
|
||||||
|
async function until(check, message) {
|
||||||
|
const end = Date.now() + 12000;
|
||||||
|
while (!(await check())) {
|
||||||
|
if (Date.now() > end) throw new Error(message || 'Timed out');
|
||||||
|
await sleep(30);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
const tiers = [
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
config_id: 1,
|
||||||
|
name: '企业专用最新档',
|
||||||
|
source_type: 'channel',
|
||||||
|
source_id: 10,
|
||||||
|
channel_ids: [10],
|
||||||
|
model_names: [],
|
||||||
|
tier_key: 'G1',
|
||||||
|
rate_bps: 1000,
|
||||||
|
effective_from: now - 30,
|
||||||
|
effective_to: 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 3,
|
||||||
|
config_id: 3,
|
||||||
|
name: '真正停用档',
|
||||||
|
source_type: 'channel',
|
||||||
|
source_id: 11,
|
||||||
|
channel_ids: [11],
|
||||||
|
model_names: [],
|
||||||
|
tier_key: 'G2',
|
||||||
|
rate_bps: 500,
|
||||||
|
effective_from: now - 100,
|
||||||
|
effective_to: now - 10,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 4,
|
||||||
|
config_id: 4,
|
||||||
|
name: '明日生效档',
|
||||||
|
source_type: 'model',
|
||||||
|
source_id: 0,
|
||||||
|
channel_ids: [],
|
||||||
|
model_names: ['future-model'],
|
||||||
|
tier_key: 'G3',
|
||||||
|
rate_bps: 700,
|
||||||
|
effective_from: now + 86400,
|
||||||
|
effective_to: 0,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const oldTier = {
|
||||||
|
...tiers[0],
|
||||||
|
id: 1,
|
||||||
|
name: '不应显示的历史档',
|
||||||
|
effective_from: now - 200,
|
||||||
|
effective_to: now - 30,
|
||||||
|
};
|
||||||
|
async function setup(view = 'partners', width = 1500, section = '') {
|
||||||
|
const context = await browser.newContext({
|
||||||
|
viewport: { width, height: 1050 },
|
||||||
|
});
|
||||||
|
await context.addInitScript(() => {
|
||||||
|
localStorage.setItem('current_org_id', '101');
|
||||||
|
localStorage.setItem(
|
||||||
|
'user',
|
||||||
|
JSON.stringify({ id: 1, role: 100, username: 'qa' }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
const page = await context.newPage();
|
||||||
|
page.setDefaultTimeout(12000);
|
||||||
|
page.setDefaultNavigationTimeout(120000);
|
||||||
|
const state = {
|
||||||
|
context,
|
||||||
|
page,
|
||||||
|
requests: [],
|
||||||
|
writes: [],
|
||||||
|
errors: [],
|
||||||
|
mode: '',
|
||||||
|
delays: {},
|
||||||
|
orgDelays: {},
|
||||||
|
};
|
||||||
|
activeState = state;
|
||||||
|
page.on('pageerror', (error) => state.errors.push(error.message));
|
||||||
|
page.on('dialog', (dialog) => dialog.accept());
|
||||||
|
await page.route('**/*', async (route) => {
|
||||||
|
const req = route.request();
|
||||||
|
const url = new URL(req.url());
|
||||||
|
if (url.origin !== origin) {
|
||||||
|
await route.abort();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!url.pathname.startsWith('/api/')) {
|
||||||
|
await route.continue();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state.requests.push({
|
||||||
|
path: url.pathname,
|
||||||
|
query: Object.fromEntries(url.searchParams),
|
||||||
|
method: req.method(),
|
||||||
|
headers: req.headers(),
|
||||||
|
});
|
||||||
|
let data = [];
|
||||||
|
if (req.method() !== 'GET') {
|
||||||
|
state.writes.push({
|
||||||
|
path: url.pathname,
|
||||||
|
body: req.postDataJSON(),
|
||||||
|
headers: req.headers(),
|
||||||
|
});
|
||||||
|
data = { id: 91 };
|
||||||
|
} else if (url.pathname.startsWith('/api/org/commission/')) {
|
||||||
|
const id = Number(req.headers()['x-org-id']);
|
||||||
|
if (state.orgDelays[id]) await state.orgDelays[id];
|
||||||
|
if (/\/statements\/\d+$/.test(url.pathname) && state.detailDelay)
|
||||||
|
await state.detailDelay;
|
||||||
|
const statement = {
|
||||||
|
id: id * 10,
|
||||||
|
partner_id: id,
|
||||||
|
statement_month: '2026-11',
|
||||||
|
status: 'pending_confirmation',
|
||||||
|
payable_uyuan: 1000000,
|
||||||
|
commission_uyuan: 1000000,
|
||||||
|
};
|
||||||
|
if (url.pathname.endsWith('/summary'))
|
||||||
|
data = {
|
||||||
|
partner_status: 'active',
|
||||||
|
agreement_expires_at: now + 86400 * 60,
|
||||||
|
};
|
||||||
|
else if (url.pathname.endsWith('/statements')) data = [statement];
|
||||||
|
else if (/\/statements\/\d+$/.test(url.pathname)) data = statement;
|
||||||
|
else if (url.pathname.endsWith('/assignments'))
|
||||||
|
data = [
|
||||||
|
{
|
||||||
|
id,
|
||||||
|
status: 'formal',
|
||||||
|
customer_name: `企业${id}客户`,
|
||||||
|
subject_type: 'organization',
|
||||||
|
subject_id: id,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
} else if (url.pathname === '/api/org/info') {
|
||||||
|
const id = Number(req.headers()['x-org-id']);
|
||||||
|
if (state.pendingOrg === id) {
|
||||||
|
await route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({
|
||||||
|
success: false,
|
||||||
|
code: 'org_pending_activation',
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
data = {
|
||||||
|
organization: { id, name: `企业${id}`, status: 1, feature_flags: {} },
|
||||||
|
member: { role: 'admin', is_member_actor: true },
|
||||||
|
};
|
||||||
|
} else if (url.pathname === '/api/org/list') {
|
||||||
|
data = [101, 102].map((id) => ({
|
||||||
|
id,
|
||||||
|
name: `企业${id}`,
|
||||||
|
status: 1,
|
||||||
|
role: 'admin',
|
||||||
|
}));
|
||||||
|
} else if (
|
||||||
|
url.pathname.endsWith('/options/users') ||
|
||||||
|
url.pathname.endsWith('/options/organizations')
|
||||||
|
) {
|
||||||
|
const q = url.searchParams.get('q') || '';
|
||||||
|
if (state.delays[q]) await state.delays[q];
|
||||||
|
if (state.mode === 'search-error' && q) {
|
||||||
|
await route.fulfill({
|
||||||
|
status: 503,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ success: false, message: '选项查询暂不可用' }),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const user = {
|
||||||
|
id: 7,
|
||||||
|
username: 'redstar',
|
||||||
|
display_name: '红星',
|
||||||
|
disabled: false,
|
||||||
|
disabled_reason: '',
|
||||||
|
};
|
||||||
|
const org = {
|
||||||
|
id: 8,
|
||||||
|
name: '测试企业',
|
||||||
|
code: 'qa-company',
|
||||||
|
disabled: false,
|
||||||
|
disabled_reason: '',
|
||||||
|
};
|
||||||
|
const isUser = url.pathname.endsWith('/users');
|
||||||
|
const items = isUser
|
||||||
|
? ['7', '#7', '红星', 'redstar', 'slow'].includes(q)
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
...user,
|
||||||
|
...(q === 'slow'
|
||||||
|
? { id: 99, display_name: '迟到的旧结果' }
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []
|
||||||
|
: [org];
|
||||||
|
data = { items, total: items.length, p: 1, page_size: 20 };
|
||||||
|
} else if (url.pathname.endsWith('/options')) {
|
||||||
|
data = {
|
||||||
|
users: [{ id: 900, username: 'recent-only', display_name: '最近用户' }],
|
||||||
|
organizations: [],
|
||||||
|
channels: [
|
||||||
|
{ id: 10, name: '测试渠道' },
|
||||||
|
{ id: 11, name: '旧渠道' },
|
||||||
|
],
|
||||||
|
models: [{ id: 'future-model', name: 'future-model' }],
|
||||||
|
levels: [],
|
||||||
|
};
|
||||||
|
} else if (url.pathname.endsWith('/tiers')) {
|
||||||
|
if (url.searchParams.get('view') === 'latest') {
|
||||||
|
let items = state.tierRows || tiers;
|
||||||
|
const pageNumber = Number(url.searchParams.get('p') || 1);
|
||||||
|
const pageSize = Number(url.searchParams.get('page_size') || 20);
|
||||||
|
if (state.exportConflict && pageNumber > 1) {
|
||||||
|
await route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({
|
||||||
|
success: false,
|
||||||
|
message: '档位配置已变化,请重新加载或重新导出',
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const q = url.searchParams.get('q');
|
||||||
|
const source = url.searchParams.get('source_type');
|
||||||
|
const status = url.searchParams.get('status');
|
||||||
|
if (q) items = items.filter((row) => row.name.includes(q));
|
||||||
|
if (source) items = items.filter((row) => row.source_type === source);
|
||||||
|
const stateOf = (row) =>
|
||||||
|
row.effective_to
|
||||||
|
? 'disabled'
|
||||||
|
: row.effective_from > now
|
||||||
|
? 'pending'
|
||||||
|
: 'active';
|
||||||
|
const counts = {
|
||||||
|
all: items.length,
|
||||||
|
active: items.filter((r) => stateOf(r) === 'active').length,
|
||||||
|
pending: items.filter((r) => stateOf(r) === 'pending').length,
|
||||||
|
disabled: items.filter((r) => stateOf(r) === 'disabled').length,
|
||||||
|
};
|
||||||
|
if (status && status !== 'all')
|
||||||
|
items = items.filter((row) => stateOf(row) === status);
|
||||||
|
data = {
|
||||||
|
items: items.slice(
|
||||||
|
(pageNumber - 1) * pageSize,
|
||||||
|
pageNumber * pageSize,
|
||||||
|
),
|
||||||
|
total: items.length,
|
||||||
|
counts,
|
||||||
|
p: Number(url.searchParams.get('p') || 1),
|
||||||
|
page_size: Number(url.searchParams.get('page_size') || 20),
|
||||||
|
as_of: now,
|
||||||
|
revision: 3,
|
||||||
|
};
|
||||||
|
} else data = [...tiers, oldTier];
|
||||||
|
}
|
||||||
|
await route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ success: true, data }),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await page.goto(
|
||||||
|
`${origin}/__commission-qa.html?view=${view}§ion=${section}`,
|
||||||
|
);
|
||||||
|
if (view === 'org')
|
||||||
|
await page.locator('[data-partner-scope="1:101"]').waitFor();
|
||||||
|
else if (view === 'personal')
|
||||||
|
await page
|
||||||
|
.getByRole('heading', { name: '分佣概览', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
else if (view === 'settlement')
|
||||||
|
await page
|
||||||
|
.getByRole('button', { name: '打开测试结算', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
else
|
||||||
|
await page
|
||||||
|
.getByText(
|
||||||
|
view === 'tiers'
|
||||||
|
? '维护统一分佣比例与状态,支持按等级、模型及渠道关联档位'
|
||||||
|
: '已完成线下准入和协议签署的外部合作伙伴档案',
|
||||||
|
{ exact: true },
|
||||||
|
)
|
||||||
|
.waitFor();
|
||||||
|
assert.equal(await page.title(), 'Commission adjustment QA');
|
||||||
|
assert.equal(await page.locator('vite-error-overlay').count(), 0);
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
const field = (page, label) =>
|
||||||
|
page
|
||||||
|
.locator('.commission-form-field')
|
||||||
|
.filter({ has: page.locator('span').filter({ hasText: label }) });
|
||||||
|
async function openPartner(s) {
|
||||||
|
await s.page.getByRole('button', { name: /新建伙伴档案/ }).click();
|
||||||
|
await s.page.getByRole('button', { name: '保存草稿', exact: true }).waitFor();
|
||||||
|
}
|
||||||
|
async function searchUser(s, q) {
|
||||||
|
const control = field(s.page, '关联个人用户');
|
||||||
|
await control.locator('.semi-select').click();
|
||||||
|
await control.locator('input').fill(q);
|
||||||
|
}
|
||||||
|
async function test(name, run) {
|
||||||
|
if (process.env.QA_FILTER && !name.includes(process.env.QA_FILTER)) return;
|
||||||
|
let s;
|
||||||
|
try {
|
||||||
|
s = await run();
|
||||||
|
assert.deepEqual(s.errors, []);
|
||||||
|
await s.page.screenshot({
|
||||||
|
path: path.join(out, `${name}.png`),
|
||||||
|
fullPage: false,
|
||||||
|
animations: 'disabled',
|
||||||
|
});
|
||||||
|
results.push({ name, passed: true });
|
||||||
|
console.log('PASS', name);
|
||||||
|
} catch (error) {
|
||||||
|
results.push({ name, passed: false, error: error.stack });
|
||||||
|
console.log('FAIL', name, error.message);
|
||||||
|
if (activeState) {
|
||||||
|
await activeState.page.screenshot({
|
||||||
|
path: path.join(out, `${name}-failed.png`),
|
||||||
|
});
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(out, `${name}-failed.txt`),
|
||||||
|
await activeState.page.locator('body').innerText(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (s || activeState) await (s || activeState).context.close();
|
||||||
|
activeState = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await test('organization-secondary-history-and-details', async () => {
|
||||||
|
const s = await setup('org', 1500, 'customers');
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).waitFor();
|
||||||
|
await s.page.reload();
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).waitFor();
|
||||||
|
await s.page.getByRole('link', { name: '分佣概览', exact: true }).click();
|
||||||
|
await s.page.locator('.partner-portal-reminder').first().click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '提成账单详情', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
assert.equal(
|
||||||
|
await s.page
|
||||||
|
.getByRole('link', { name: '我的提成', exact: true })
|
||||||
|
.getAttribute('aria-current'),
|
||||||
|
'page',
|
||||||
|
);
|
||||||
|
await s.page.getByRole('button', { name: '确认账单', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.locator('.semi-modal-footer button')
|
||||||
|
.filter({ hasText: '确认无误' })
|
||||||
|
.waitFor();
|
||||||
|
// Browser back dismisses an unsubmitted confirmation and invalidates detail loads.
|
||||||
|
await s.page.evaluate(() => window.__qaNavigate(-1));
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '分佣概览', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
await s.page
|
||||||
|
.locator('.semi-modal-footer button')
|
||||||
|
.filter({ hasText: '确认无误' })
|
||||||
|
.waitFor({ state: 'hidden' });
|
||||||
|
await s.page.evaluate(() => window.__qaNavigate(1));
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '我的提成', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
await s.page.evaluate(() =>
|
||||||
|
window.__qaNavigate('/org/commission?view=invalid'),
|
||||||
|
);
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '分佣概览', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
assert.equal(s.writes.length, 0);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('organization-secondary-collapse-and-search', async () => {
|
||||||
|
const s = await setup('org');
|
||||||
|
const menu = s.page.getByRole('button', { name: '企业分佣', exact: true });
|
||||||
|
await menu.click();
|
||||||
|
assert.equal(await menu.getAttribute('aria-expanded'), 'false');
|
||||||
|
await s.page
|
||||||
|
.getByRole('textbox', { name: '搜索菜单', exact: true })
|
||||||
|
.fill('提成');
|
||||||
|
await s.page.getByRole('link', { name: '我的提成', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '我的提成', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
await s.page.getByRole('button', { name: '清空搜索', exact: true }).click();
|
||||||
|
await s.page.getByRole('button', { name: '收起', exact: true }).click();
|
||||||
|
assert.equal(await menu.getAttribute('aria-expanded'), 'false');
|
||||||
|
await menu.click();
|
||||||
|
await s.page.getByRole('link', { name: '我的客户', exact: true }).click();
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).waitFor();
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('organization-secondary-mobile', async () => {
|
||||||
|
const s = await setup('org', 390);
|
||||||
|
await s.page.getByRole('button', { name: '打开菜单', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('link', { name: '我的客户', exact: true })
|
||||||
|
.last()
|
||||||
|
.click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '我的客户', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
await until(
|
||||||
|
async () => !(await s.page.locator('.semi-sidesheet').isVisible()),
|
||||||
|
'Mobile drawer did not close',
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
await s.page.locator('.partner-portal .commission-v2-sider').count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert.ok(
|
||||||
|
await s.page.evaluate(
|
||||||
|
() => document.documentElement.scrollWidth <= innerWidth + 1,
|
||||||
|
),
|
||||||
|
'Page overflowed mobile viewport',
|
||||||
|
);
|
||||||
|
await s.page.screenshot({
|
||||||
|
path: path.join(out, 'organization-mobile-content.png'),
|
||||||
|
});
|
||||||
|
await s.page.getByRole('button', { name: '打开菜单', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('link', { name: '我的客户', exact: true })
|
||||||
|
.last()
|
||||||
|
.waitFor();
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('organization-secondary-navigation', async () => {
|
||||||
|
const s = await setup('org');
|
||||||
|
const menu = s.page.getByRole('button', { name: '企业分佣', exact: true });
|
||||||
|
await menu.waitFor();
|
||||||
|
assert.equal(await menu.getAttribute('aria-expanded'), 'true');
|
||||||
|
assert.equal(
|
||||||
|
await s.page.locator('.partner-portal .commission-v2-sider').count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
await s.page.getByRole('link', { name: '我的客户', exact: true }).click();
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).waitFor();
|
||||||
|
assert.equal(
|
||||||
|
await s.page
|
||||||
|
.getByRole('link', { name: '我的客户', exact: true })
|
||||||
|
.getAttribute('aria-current'),
|
||||||
|
'page',
|
||||||
|
);
|
||||||
|
await s.page.getByRole('link', { name: '本月预估', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '本月预估', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
await s.page.getByRole('link', { name: '分佣规则', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '分佣规则', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('personal-navigation-preserved', async () => {
|
||||||
|
const s = await setup('personal');
|
||||||
|
await s.page.getByRole('navigation', { name: '伙伴分佣导航' }).waitFor();
|
||||||
|
await s.page.getByRole('button', { name: '我的客户', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '我的客户', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
assert.ok(
|
||||||
|
!s.requests.some((r) => r.path.startsWith('/api/org/commission/')),
|
||||||
|
);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('user-id-remote-search', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await openPartner(s);
|
||||||
|
await searchUser(s, '7');
|
||||||
|
await until(
|
||||||
|
() =>
|
||||||
|
s.requests.some(
|
||||||
|
(r) => r.path.endsWith('/options/users') && r.query.q === '7',
|
||||||
|
),
|
||||||
|
'No remote user-ID search request',
|
||||||
|
);
|
||||||
|
await s.page
|
||||||
|
.getByText(/红星.*redstar.*#7/)
|
||||||
|
.last()
|
||||||
|
.click();
|
||||||
|
await field(s.page, '伙伴名称').locator('input').fill('红星伙伴');
|
||||||
|
await s.page.getByRole('button', { name: '保存草稿', exact: true }).click();
|
||||||
|
await until(() => s.writes.length === 1, 'Partner was not saved');
|
||||||
|
assert.equal(s.writes[0].body.user_id, 7);
|
||||||
|
assert.equal(s.writes[0].body.type, 'individual');
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('company-without-user', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await openPartner(s);
|
||||||
|
await s.page.getByText('企业伙伴', { exact: true }).click();
|
||||||
|
assert.equal(
|
||||||
|
await s.page.getByText('企业管理员登录身份', { exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
const org = field(s.page, '关联企业');
|
||||||
|
await org.locator('.semi-select').click();
|
||||||
|
await s.page
|
||||||
|
.getByText(/测试企业.*#8/)
|
||||||
|
.last()
|
||||||
|
.click();
|
||||||
|
await field(s.page, '伙伴名称').locator('input').fill('企业伙伴测试');
|
||||||
|
await s.page.getByRole('button', { name: '保存草稿', exact: true }).click();
|
||||||
|
await until(
|
||||||
|
() => s.writes.length === 1,
|
||||||
|
'Company requires an obsolete user identity',
|
||||||
|
);
|
||||||
|
assert.equal(s.writes[0].body.organization_id, 8);
|
||||||
|
assert.ok(!s.writes[0].body.user_id);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('search-race-keeps-new-results', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
const slow = deferred();
|
||||||
|
s.delays.slow = slow.promise;
|
||||||
|
await openPartner(s);
|
||||||
|
await searchUser(s, 'slow');
|
||||||
|
await until(
|
||||||
|
() => s.requests.some((r) => r.query.q === 'slow'),
|
||||||
|
'Slow request not sent',
|
||||||
|
);
|
||||||
|
await field(s.page, '关联个人用户').locator('input').fill('红星');
|
||||||
|
await s.page
|
||||||
|
.getByText(/红星.*redstar.*#7/)
|
||||||
|
.last()
|
||||||
|
.waitFor();
|
||||||
|
slow.resolve();
|
||||||
|
await sleep(150);
|
||||||
|
assert.equal(await s.page.getByText(/迟到的旧结果/).count(), 0);
|
||||||
|
await s.page
|
||||||
|
.getByText(/红星.*redstar.*#7/)
|
||||||
|
.last()
|
||||||
|
.click();
|
||||||
|
await field(s.page, '伙伴名称').locator('input').fill('保留选择');
|
||||||
|
await s.page.getByRole('button', { name: '保存草稿', exact: true }).click();
|
||||||
|
await until(() => s.writes.length === 1);
|
||||||
|
assert.equal(s.writes[0].body.user_id, 7);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('type-switch-discards-pending-user', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
const slow = deferred();
|
||||||
|
s.delays.slow = slow.promise;
|
||||||
|
await openPartner(s);
|
||||||
|
await searchUser(s, 'slow');
|
||||||
|
await until(() => s.requests.some((r) => r.query.q === 'slow'));
|
||||||
|
await s.page.getByText('企业伙伴', { exact: true }).click();
|
||||||
|
slow.resolve();
|
||||||
|
await sleep(150);
|
||||||
|
assert.equal(await s.page.getByText(/迟到的旧结果/).count(), 0);
|
||||||
|
assert.equal(
|
||||||
|
await s.page.getByText('关联个人用户', { exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
await field(s.page, '关联企业').locator('.semi-select').click();
|
||||||
|
await s.page
|
||||||
|
.getByText(/测试企业.*#8/)
|
||||||
|
.last()
|
||||||
|
.waitFor();
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('close-reopen-discards-old-search', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
const slow = deferred();
|
||||||
|
s.delays.slow = slow.promise;
|
||||||
|
await openPartner(s);
|
||||||
|
await searchUser(s, 'slow');
|
||||||
|
await until(() => s.requests.some((r) => r.query.q === 'slow'));
|
||||||
|
await s.page.getByRole('button', { name: '取消', exact: true }).click();
|
||||||
|
await openPartner(s);
|
||||||
|
await searchUser(s, '7');
|
||||||
|
await s.page
|
||||||
|
.getByText(/红星.*redstar.*#7/)
|
||||||
|
.last()
|
||||||
|
.waitFor();
|
||||||
|
slow.resolve();
|
||||||
|
await sleep(150);
|
||||||
|
assert.equal(await s.page.getByText(/迟到的旧结果/).count(), 0);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('latest-tiers-only', async () => {
|
||||||
|
const s = await setup('tiers');
|
||||||
|
await s.page.getByText('企业专用最新档', { exact: true }).waitFor();
|
||||||
|
assert.equal(
|
||||||
|
await s.page.getByText('不应显示的历史档', { exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert.ok(
|
||||||
|
s.requests.some(
|
||||||
|
(r) => r.path.endsWith('/tiers') && r.query.view === 'latest',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await s.page.getByText('真正停用档', { exact: true }).waitFor();
|
||||||
|
const future = s.page.locator('tr').filter({ hasText: '明日生效档' });
|
||||||
|
assert.equal(
|
||||||
|
await future.getByRole('button', { name: '停用', exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert.equal(await s.page.locator('.semi-datepicker').count(), 0);
|
||||||
|
await s.page
|
||||||
|
.getByRole('button', { name: '绑定历史', exact: true })
|
||||||
|
.waitFor();
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('latest-status-filter-is-server-side', async () => {
|
||||||
|
const s = await setup('tiers');
|
||||||
|
await s.page.getByText('企业专用最新档', { exact: true }).waitFor();
|
||||||
|
await s.page.getByRole('tab', { name: /已停用/ }).click();
|
||||||
|
await until(
|
||||||
|
() =>
|
||||||
|
s.requests.some(
|
||||||
|
(r) => r.path.endsWith('/tiers') && r.query.status === 'disabled',
|
||||||
|
),
|
||||||
|
'Status filter only ran locally',
|
||||||
|
);
|
||||||
|
await s.page.getByText('真正停用档', { exact: true }).waitFor();
|
||||||
|
await until(
|
||||||
|
async () =>
|
||||||
|
(await s.page.getByText('企业专用最新档', { exact: true }).count()) ===
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
await s.page.getByText('不应显示的历史档', { exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('settlement-cancel-and-close', async () => {
|
||||||
|
const s = await setup('settlement');
|
||||||
|
await s.page
|
||||||
|
.getByRole('button', { name: '打开测试结算', exact: true })
|
||||||
|
.click();
|
||||||
|
await s.page.getByText('录入手续费', { exact: true }).waitFor();
|
||||||
|
await s.page
|
||||||
|
.locator('.semi-modal-footer button')
|
||||||
|
.filter({ hasText: '取消' })
|
||||||
|
.click();
|
||||||
|
await until(
|
||||||
|
async () =>
|
||||||
|
!(await s.page.getByText('录入手续费', { exact: true }).isVisible()),
|
||||||
|
);
|
||||||
|
await s.page
|
||||||
|
.getByRole('button', { name: '打开测试结算', exact: true })
|
||||||
|
.click();
|
||||||
|
await s.page.getByText('录入手续费', { exact: true }).waitFor();
|
||||||
|
await s.page.locator('.semi-modal-close').click();
|
||||||
|
await until(
|
||||||
|
async () =>
|
||||||
|
!(await s.page.getByText('录入手续费', { exact: true }).isVisible()),
|
||||||
|
);
|
||||||
|
assert.equal(s.page.isClosed(), false);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('latest-export-fetches-all-pages', async () => {
|
||||||
|
const s = await setup('tiers');
|
||||||
|
s.tierRows = Array.from({ length: 105 }, (_, index) => ({
|
||||||
|
...tiers[0],
|
||||||
|
id: 1000 + index,
|
||||||
|
config_id: 1000 + index,
|
||||||
|
name: `导出配置${index}`,
|
||||||
|
}));
|
||||||
|
await s.page.getByRole('button', { name: /刷新/ }).click();
|
||||||
|
await s.page.getByText('导出配置0', { exact: true }).waitFor();
|
||||||
|
const download = s.page.waitForEvent('download');
|
||||||
|
await s.page.getByRole('button', { name: '导出', exact: true }).click();
|
||||||
|
const file = await download;
|
||||||
|
const exportPath = path.join(out, 'latest-all-pages.xlsx');
|
||||||
|
await file.saveAs(exportPath);
|
||||||
|
const XLSX = await import(
|
||||||
|
pathToFileURL(path.join(webRoot, 'node_modules/xlsx/xlsx.mjs')).href
|
||||||
|
);
|
||||||
|
const workbook = XLSX.read(fs.readFileSync(exportPath), { type: 'buffer' });
|
||||||
|
const rows = XLSX.utils.sheet_to_json(
|
||||||
|
workbook.Sheets[workbook.SheetNames[0]],
|
||||||
|
);
|
||||||
|
assert.equal(rows.length, 105);
|
||||||
|
assert.ok(
|
||||||
|
s.requests.some(
|
||||||
|
(r) =>
|
||||||
|
r.path.endsWith('/tiers') &&
|
||||||
|
r.query.p === '2' &&
|
||||||
|
r.query.revision === '3' &&
|
||||||
|
r.query.as_of === String(now),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('latest-export-refuses-changed-revision', async () => {
|
||||||
|
const s = await setup('tiers');
|
||||||
|
s.tierRows = Array.from({ length: 105 }, (_, index) => ({
|
||||||
|
...tiers[0],
|
||||||
|
id: 1000 + index,
|
||||||
|
config_id: 1000 + index,
|
||||||
|
name: `变更配置${index}`,
|
||||||
|
}));
|
||||||
|
s.exportConflict = true;
|
||||||
|
let downloads = 0;
|
||||||
|
s.page.on('download', () => downloads++);
|
||||||
|
await s.page.getByRole('button', { name: /刷新/ }).click();
|
||||||
|
await s.page.getByText('变更配置0', { exact: true }).waitFor();
|
||||||
|
await s.page.getByRole('button', { name: '导出', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.locator('.semi-banner')
|
||||||
|
.filter({ hasText: '档位配置已变化,请重新加载或重新导出' })
|
||||||
|
.waitFor();
|
||||||
|
assert.equal(downloads, 0);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('organization-navigation-discards-slow-detail', async () => {
|
||||||
|
const s = await setup('org');
|
||||||
|
const delayed = deferred();
|
||||||
|
s.detailDelay = delayed.promise;
|
||||||
|
await s.page.locator('.partner-portal-reminder').first().click();
|
||||||
|
await until(
|
||||||
|
() => s.requests.some((r) => /\/statements\/\d+$/.test(r.path)),
|
||||||
|
'No detail request',
|
||||||
|
);
|
||||||
|
await s.page.getByRole('link', { name: '我的客户', exact: true }).click();
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).waitFor();
|
||||||
|
const response = s.page.waitForResponse((r) =>
|
||||||
|
/\/statements\/\d+$/.test(new URL(r.url()).pathname),
|
||||||
|
);
|
||||||
|
delayed.resolve();
|
||||||
|
await (await response).finished();
|
||||||
|
await s.page.evaluate(
|
||||||
|
() =>
|
||||||
|
new Promise((done) =>
|
||||||
|
requestAnimationFrame(() => requestAnimationFrame(done)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '提成账单详情', exact: true })
|
||||||
|
.count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
await s.page
|
||||||
|
.getByRole('heading', { name: '我的客户', exact: true })
|
||||||
|
.count(),
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
assert.equal(s.writes.length, 0);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('organization-pending-activation-switch', async () => {
|
||||||
|
const s = await setup('org');
|
||||||
|
await s.page.getByRole('link', { name: '我的客户', exact: true }).click();
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).waitFor();
|
||||||
|
s.pendingOrg = 102;
|
||||||
|
await s.page
|
||||||
|
.locator('select[aria-label="切换企业"]')
|
||||||
|
.first()
|
||||||
|
.selectOption('102');
|
||||||
|
await s.page.getByText('企业待激活', { exact: true }).waitFor();
|
||||||
|
assert.equal(await s.page.locator('[data-partner-scope]').count(), 0);
|
||||||
|
assert.equal(
|
||||||
|
await s.page.evaluate(() => localStorage.getItem('current_org_id')),
|
||||||
|
'102',
|
||||||
|
);
|
||||||
|
s.pendingOrg = null;
|
||||||
|
await s.page.getByRole('button', { name: '刷新状态', exact: true }).click();
|
||||||
|
await s.page.getByText('企业102客户', { exact: true }).waitFor();
|
||||||
|
assert.equal(
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('organization-switch-clears-confirmation', async () => {
|
||||||
|
const s = await setup('org');
|
||||||
|
await s.page.locator('.partner-portal-reminder').first().click();
|
||||||
|
await s.page.getByRole('button', { name: '确认账单', exact: true }).click();
|
||||||
|
await s.page
|
||||||
|
.locator('.semi-modal-footer button')
|
||||||
|
.filter({ hasText: '确认无误' })
|
||||||
|
.waitFor();
|
||||||
|
// The real sidebar switch must unmount the old confirmation and pin all subsequent requests.
|
||||||
|
await s.page
|
||||||
|
.locator('select[aria-label="切换企业"]')
|
||||||
|
.first()
|
||||||
|
.selectOption('102');
|
||||||
|
await s.page.locator('[data-partner-scope="1:102"]').waitFor();
|
||||||
|
assert.equal(
|
||||||
|
await s.page.locator('[data-partner-scope="1:101"]').count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
await s.page
|
||||||
|
.locator('.semi-modal-footer button')
|
||||||
|
.filter({ hasText: '确认无误' })
|
||||||
|
.count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert.equal(s.writes.length, 0);
|
||||||
|
assert.ok(
|
||||||
|
s.requests.some(
|
||||||
|
(r) =>
|
||||||
|
r.path === '/api/org/commission/statements' &&
|
||||||
|
r.headers['x-org-id'] === '102',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
assert.ok(!s.requests.some((r) => r.path.startsWith('/api/partner/v2/')));
|
||||||
|
await s.page.getByRole('link', { name: '我的客户', exact: true }).click();
|
||||||
|
await s.page.getByText('企业102客户', { exact: true }).waitFor();
|
||||||
|
assert.equal(
|
||||||
|
await s.page.getByText('企业101客户', { exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await browser.close();
|
||||||
|
await server.close();
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(out, 'results.json'),
|
||||||
|
JSON.stringify(results, null, 2),
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`${results.filter((r) => r.passed).length}/${results.length} passed`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (results.some((r) => !r.passed)) process.exitCode = 1;
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
/*
|
||||||
|
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 { readFile, readdir } from 'node:fs/promises';
|
||||||
|
import { execFile } from 'node:child_process';
|
||||||
|
import { promisify } from 'node:util';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const exec = promisify(execFile);
|
||||||
|
const projectRoot = fileURLToPath(new URL('../', import.meta.url));
|
||||||
|
|
||||||
|
export function logAddresses(bytes, encoding) {
|
||||||
|
const text = bytes.toString(
|
||||||
|
encoding || (bytes[0] === 255 && bytes[1] === 254 ? 'utf16le' : 'utf8'),
|
||||||
|
);
|
||||||
|
return [
|
||||||
|
...text
|
||||||
|
.replace(/\x1b\[[0-9;]*m/g, '')
|
||||||
|
.matchAll(/(?:Local:|Network:)\s*(https?:\/\/[^\s]+)/g),
|
||||||
|
]
|
||||||
|
.map((match) => match[1])
|
||||||
|
.reverse();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function matchesProject(address, root) {
|
||||||
|
try {
|
||||||
|
const url = new URL(address);
|
||||||
|
if (
|
||||||
|
!['http:', 'https:'].includes(url.protocol) ||
|
||||||
|
url.username ||
|
||||||
|
url.password
|
||||||
|
)
|
||||||
|
return false;
|
||||||
|
const source = await readFile(path.join(root, 'src/index.jsx'), 'utf8');
|
||||||
|
const response = await fetch(new URL('src/index.jsx', url), {
|
||||||
|
signal: AbortSignal.timeout(2500),
|
||||||
|
});
|
||||||
|
if (!response.ok) return false;
|
||||||
|
const text = await response.text();
|
||||||
|
const map = text.match(
|
||||||
|
/sourceMappingURL=data:application\/json;base64,([^\s]+)/,
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
!!map &&
|
||||||
|
JSON.parse(
|
||||||
|
Buffer.from(map[1], 'base64').toString(),
|
||||||
|
).sourcesContent?.includes(source)
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function nodePorts() {
|
||||||
|
if (process.platform !== 'win32') return [];
|
||||||
|
const command =
|
||||||
|
'[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8; ' +
|
||||||
|
'$ids = @(Get-CimInstance Win32_Process -Filter "Name=\'node.exe\'" | Select-Object -ExpandProperty ProcessId); ' +
|
||||||
|
'Get-NetTCPConnection -State Listen -ErrorAction Stop | Where-Object { $_.OwningProcess -in $ids } | Select-Object -ExpandProperty LocalPort -Unique | ConvertTo-Json -Compress';
|
||||||
|
const { stdout } = await exec(
|
||||||
|
'powershell.exe',
|
||||||
|
['-NoProfile', '-Command', command],
|
||||||
|
{ timeout: 15000, windowsHide: true },
|
||||||
|
);
|
||||||
|
const parsed = JSON.parse(stdout.trim() || '[]');
|
||||||
|
return [parsed].flat().filter((port) => Number.isInteger(port) && port > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function findDevService({
|
||||||
|
root = projectRoot,
|
||||||
|
getPorts = nodePorts,
|
||||||
|
} = {}) {
|
||||||
|
const candidates = [];
|
||||||
|
const entries = await readdir(root, { withFileTypes: true });
|
||||||
|
const logs = entries.filter(
|
||||||
|
(entry) => entry.isFile() && /\.log$/i.test(entry.name),
|
||||||
|
);
|
||||||
|
logs.sort(
|
||||||
|
(a, b) => Number(b.name === 'dev.log') - Number(a.name === 'dev.log'),
|
||||||
|
);
|
||||||
|
for (const entry of logs.slice(0, 8)) {
|
||||||
|
const bytes = await readFile(path.join(root, entry.name));
|
||||||
|
candidates.push(
|
||||||
|
...logAddresses(
|
||||||
|
bytes.subarray(Math.max(0, bytes.length - 262144)),
|
||||||
|
bytes[0] === 255 && bytes[1] === 254 ? 'utf16le' : 'utf8',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Only Node listeners are probed; the source map must match this checkout.
|
||||||
|
for (const address of new Set(candidates)) {
|
||||||
|
if (await matchesProject(address, root))
|
||||||
|
return new URL(address).origin + '/';
|
||||||
|
}
|
||||||
|
const ports = await getPorts();
|
||||||
|
for (const address of new Set(
|
||||||
|
ports.map((port) => 'http://127.0.0.1:' + port + '/'),
|
||||||
|
)) {
|
||||||
|
if (await matchesProject(address, root))
|
||||||
|
return new URL(address).origin + '/';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,724 @@
|
|||||||
|
/**
|
||||||
|
* Isolated browser regression for the real model-cost settings components.
|
||||||
|
* No backend is started: every /api/ request is mocked; off-origin traffic is blocked.
|
||||||
|
* Requires existing web/node_modules and an externally available Playwright + Chromium.
|
||||||
|
* PowerShell example:
|
||||||
|
* $env:PLAYWRIGHT_MODULE='C:/path/to/node_modules/playwright/index.mjs'
|
||||||
|
* node web/scripts/model-cost-qa.mjs
|
||||||
|
* Optional: COST_QA_OUTPUT (artifact directory), QA_FILTER (case-name substring).
|
||||||
|
* Browser plugin not available in the authoring environment; regular Playwright used.
|
||||||
|
*/
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import os from 'node:os';
|
||||||
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||||
|
const webRoot = path.resolve(
|
||||||
|
path.dirname(fileURLToPath(import.meta.url)),
|
||||||
|
'..',
|
||||||
|
);
|
||||||
|
const out =
|
||||||
|
process.env.COST_QA_OUTPUT ||
|
||||||
|
fs.mkdtempSync(path.join(os.tmpdir(), 'model-cost-qa-'));
|
||||||
|
fs.mkdirSync(out, { recursive: true });
|
||||||
|
const playwrightModule = process.env.PLAYWRIGHT_MODULE;
|
||||||
|
const { chromium } = await import(
|
||||||
|
playwrightModule
|
||||||
|
? pathToFileURL(path.resolve(playwrightModule)).href
|
||||||
|
: 'playwright'
|
||||||
|
);
|
||||||
|
const { createServer, loadConfigFromFile } = await import(
|
||||||
|
pathToFileURL(path.join(webRoot, 'node_modules/vite/dist/node/index.js')).href
|
||||||
|
);
|
||||||
|
const loadedConfig = await loadConfigFromFile(
|
||||||
|
{ command: 'serve', mode: 'development' },
|
||||||
|
path.join(webRoot, 'vite.config.js'),
|
||||||
|
);
|
||||||
|
const base = loadedConfig.config;
|
||||||
|
const entry = path.join(webRoot, 'src/__cost-test.jsx').replaceAll('\\', '/');
|
||||||
|
const server = await createServer({
|
||||||
|
...base,
|
||||||
|
configFile: false,
|
||||||
|
root: webRoot,
|
||||||
|
cacheDir: path.join(out, 'vite-cache'),
|
||||||
|
optimizeDeps: { ...base.optimizeDeps, force: false },
|
||||||
|
server: { host: '127.0.0.1', port: 0, strictPort: false, proxy: {} },
|
||||||
|
plugins: [
|
||||||
|
...base.plugins,
|
||||||
|
{
|
||||||
|
name: 'isolated-model-cost-qa',
|
||||||
|
configureServer(vite) {
|
||||||
|
vite.middlewares.use('/api/', (_req, res) => {
|
||||||
|
res.statusCode = 503;
|
||||||
|
res.end('QA requires browser request interception');
|
||||||
|
});
|
||||||
|
vite.middlewares.use('/__cost-test.html', async (_req, res) => {
|
||||||
|
res.setHeader('Content-Type', 'text/html');
|
||||||
|
res.end(
|
||||||
|
await vite.transformIndexHtml(
|
||||||
|
'/__cost-test.html',
|
||||||
|
'<html><head><title>Cost settings QA</title></head><body><div id="root"></div><script type="module" src="/__cost-test.jsx"></script></body></html>',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
resolveId(id) {
|
||||||
|
if (id === '/__cost-test.jsx') return entry;
|
||||||
|
},
|
||||||
|
load(id) {
|
||||||
|
if (id === entry)
|
||||||
|
return `
|
||||||
|
import '/src/styles/tokens.css';import '/src/index.css';import '/src/styles/org.css';
|
||||||
|
import React from 'react';import {createRoot} from 'react-dom/client';
|
||||||
|
import i18n from 'i18next';import {initReactI18next} from 'react-i18next';
|
||||||
|
import {MemoryRouter} from 'react-router-dom';
|
||||||
|
import {StatusProvider} from '/src/context/Status/index.jsx';import {UserProvider} from '/src/context/User/index.jsx';
|
||||||
|
import RatioSetting from '/src/components/settings/RatioSetting.jsx';
|
||||||
|
import ModelCostSettings from '/src/pages/Setting/Ratio/ModelCostSettings.jsx';
|
||||||
|
i18n.use(initReactI18next).init({lng:'zh',fallbackLng:'zh',resources:{zh:{translation:{}}},interpolation:{escapeValue:false}});
|
||||||
|
createRoot(document.getElementById('root')).render(<MemoryRouter><StatusProvider><UserProvider><div style={{padding:20}}>{location.search.includes('direct')?<ModelCostSettings/>:<RatioSetting/>}</div></UserProvider></StatusProvider></MemoryRouter>);
|
||||||
|
`;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await server.listen();
|
||||||
|
const origin = 'http://127.0.0.1:' + server.httpServer.address().port;
|
||||||
|
console.log('QA origin:', origin, 'Artifacts:', out);
|
||||||
|
let browser;
|
||||||
|
try {
|
||||||
|
browser = await chromium.launch({ headless: true });
|
||||||
|
} catch (error) {
|
||||||
|
await server.close();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
const results = [];
|
||||||
|
const allRequests = [];
|
||||||
|
const allErrors = [];
|
||||||
|
let active;
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
async function until(predicate) {
|
||||||
|
const deadline = Date.now() + 12000;
|
||||||
|
while (!predicate()) {
|
||||||
|
if (Date.now() > deadline)
|
||||||
|
throw new Error('Timed out waiting for intercepted request');
|
||||||
|
await sleep(20);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function deferred() {
|
||||||
|
let resolve;
|
||||||
|
const promise = new Promise((r) => (resolve = r));
|
||||||
|
return { promise, resolve };
|
||||||
|
}
|
||||||
|
async function setup({
|
||||||
|
direct = true,
|
||||||
|
role = 100,
|
||||||
|
channels = true,
|
||||||
|
viewport = { width: 1500, height: 1000 },
|
||||||
|
} = {}) {
|
||||||
|
const ctx = await browser.newContext({ viewport });
|
||||||
|
await ctx.addInitScript(
|
||||||
|
(role) =>
|
||||||
|
localStorage.setItem(
|
||||||
|
'user',
|
||||||
|
JSON.stringify({ id: 1, role, username: 'qa' }),
|
||||||
|
),
|
||||||
|
role,
|
||||||
|
);
|
||||||
|
const p = await ctx.newPage();
|
||||||
|
p.setDefaultTimeout(12000);
|
||||||
|
p.setDefaultNavigationTimeout(120000);
|
||||||
|
p.on('dialog', (d) => d.accept());
|
||||||
|
const s = {
|
||||||
|
p,
|
||||||
|
ctx,
|
||||||
|
requests: [],
|
||||||
|
writes: [],
|
||||||
|
errors: [],
|
||||||
|
readMode: 'normal',
|
||||||
|
writeMode: 'normal',
|
||||||
|
readGates: {},
|
||||||
|
writeGate: null,
|
||||||
|
channels,
|
||||||
|
};
|
||||||
|
active = s;
|
||||||
|
p.on('pageerror', (e) => s.errors.push(e.message));
|
||||||
|
p.on('console', (m) => {
|
||||||
|
if (m.type() === 'error' && !m.text().startsWith('Warning:'))
|
||||||
|
allErrors.push(m.text());
|
||||||
|
});
|
||||||
|
await p.route('**/*', async (route) => {
|
||||||
|
const r = route.request(),
|
||||||
|
u = new URL(r.url());
|
||||||
|
if (u.origin !== origin) {
|
||||||
|
await route.abort();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!u.pathname.startsWith('/api/')) return route.continue();
|
||||||
|
const event = {
|
||||||
|
method: r.method(),
|
||||||
|
path: u.pathname,
|
||||||
|
key: u.searchParams.get('scope_key'),
|
||||||
|
body: r.postDataJSON(),
|
||||||
|
};
|
||||||
|
s.requests.push(event);
|
||||||
|
allRequests.push(event);
|
||||||
|
const ok = (data) => route.fulfill({ json: { success: true, data } });
|
||||||
|
const path = u.pathname,
|
||||||
|
k = event.key || '1';
|
||||||
|
if (r.method() !== 'GET') {
|
||||||
|
s.writes.push(event);
|
||||||
|
if (s.writeGate) await s.writeGate.promise;
|
||||||
|
if (s.writeMode === 'network') return route.abort('failed');
|
||||||
|
if (s.writeMode === 'business-reject')
|
||||||
|
return route.fulfill({
|
||||||
|
json: { success: false, message: 'mock rejected write' },
|
||||||
|
});
|
||||||
|
if (s.writeMode === 'reject')
|
||||||
|
return route.fulfill({
|
||||||
|
status: 500,
|
||||||
|
json: { success: false, message: 'mock write failure' },
|
||||||
|
});
|
||||||
|
return ok({ created: 1, updated: 1, closed: 1, deleted: 1 });
|
||||||
|
}
|
||||||
|
if (path === '/api/channel/')
|
||||||
|
return ok({
|
||||||
|
items: channels
|
||||||
|
? [
|
||||||
|
{ id: 1, name: 'Channel A', status: 1 },
|
||||||
|
{ id: 2, name: 'Channel B', status: 1 },
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
total: channels ? 2 : 0,
|
||||||
|
});
|
||||||
|
if (path === '/api/option/') return ok([]);
|
||||||
|
if (path.endsWith('/uncovered')) return ok({ total: 0, items: [] });
|
||||||
|
if (path.includes('/commission/costs/')) {
|
||||||
|
const capturedMode = s.readMode;
|
||||||
|
const gate = s.readGates[k];
|
||||||
|
if (gate) await gate.promise;
|
||||||
|
if (capturedMode === 'network') return route.abort('failed');
|
||||||
|
if (capturedMode === '500' || (capturedMode === 'failB' && k === '2'))
|
||||||
|
return route.fulfill({
|
||||||
|
status: 500,
|
||||||
|
json: { message: 'internal stack not for display' },
|
||||||
|
});
|
||||||
|
if (capturedMode.startsWith('410'))
|
||||||
|
return route.fulfill({
|
||||||
|
status: 410,
|
||||||
|
json: {
|
||||||
|
success: false,
|
||||||
|
message:
|
||||||
|
capturedMode === '410-valid'
|
||||||
|
? '旧版分佣已停用:测试说明'
|
||||||
|
: capturedMode === '410-object'
|
||||||
|
? { bad: true }
|
||||||
|
: '',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (path.endsWith('scope_models'))
|
||||||
|
return ok({
|
||||||
|
models: [
|
||||||
|
{
|
||||||
|
model_name: `model-${k === '1' ? 'A' : 'B'}`,
|
||||||
|
units: [{ unit: 'input_1m', tier_key: '' }],
|
||||||
|
enabled_channels: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
official: { [`model-${k === '1' ? 'A' : 'B'}`]: { input: 10 } },
|
||||||
|
});
|
||||||
|
return ok([
|
||||||
|
{
|
||||||
|
id: Number(k) * 100 + 1,
|
||||||
|
scope: 'channel',
|
||||||
|
scope_key: k,
|
||||||
|
model_name: `model-${k === '1' ? 'A' : 'B'}`,
|
||||||
|
unit: 'input_1m',
|
||||||
|
tier_key: '',
|
||||||
|
cost_uyuan_per_unit: Number(k) * 1000000,
|
||||||
|
effective_from: 1,
|
||||||
|
effective_to: 0,
|
||||||
|
note: 'original',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
return ok([]);
|
||||||
|
});
|
||||||
|
s.goto = async () => {
|
||||||
|
await p.goto(origin + '/__cost-test.html' + (direct ? '?direct' : ''), {
|
||||||
|
waitUntil: 'domcontentloaded',
|
||||||
|
});
|
||||||
|
await p
|
||||||
|
.getByText(direct ? '渠道' : '模型倍率设置', { exact: true })
|
||||||
|
.first()
|
||||||
|
.waitFor();
|
||||||
|
};
|
||||||
|
s.close = async () => {
|
||||||
|
assert.deepEqual(s.errors, [], 'no page runtime errors');
|
||||||
|
await ctx.close();
|
||||||
|
};
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
async function loaded(s, model = 'A') {
|
||||||
|
await s.p.getByPlaceholder('成本单价').first().waitFor();
|
||||||
|
await s.p
|
||||||
|
.getByText('model-' + model, { exact: true })
|
||||||
|
.first()
|
||||||
|
.waitFor();
|
||||||
|
}
|
||||||
|
const button = (p, name) =>
|
||||||
|
p
|
||||||
|
.locator('button')
|
||||||
|
.filter({ hasText: new RegExp('^' + name + '$') })
|
||||||
|
.first();
|
||||||
|
const modal = (p) =>
|
||||||
|
p.locator('.semi-modal-content').filter({ visible: true }).last();
|
||||||
|
async function confirm(p, label) {
|
||||||
|
await p.getByText(label, { exact: true }).last().click();
|
||||||
|
}
|
||||||
|
async function choose(s, id) {
|
||||||
|
await s.p.locator('.semi-select').first().click();
|
||||||
|
await s.p
|
||||||
|
.getByText(`#${id} Channel ${id === 1 ? 'A' : 'B'}`, { exact: true })
|
||||||
|
.click();
|
||||||
|
}
|
||||||
|
async function refresh(s) {
|
||||||
|
await button(s.p, '刷新').click();
|
||||||
|
}
|
||||||
|
async function noWrites(s) {
|
||||||
|
await sleep(100);
|
||||||
|
assert.equal(s.writes.length, 0);
|
||||||
|
}
|
||||||
|
async function history(s) {
|
||||||
|
await button(s.p, '版本(1)').click();
|
||||||
|
}
|
||||||
|
async function advanced(s) {
|
||||||
|
await history(s);
|
||||||
|
await button(s.p, '编辑').click();
|
||||||
|
await s.p.getByText('编辑价格版本', { exact: true }).waitFor();
|
||||||
|
}
|
||||||
|
async function modalOk(s) {
|
||||||
|
await modal(s.p).locator('.semi-modal-footer button').last().click();
|
||||||
|
}
|
||||||
|
async function test(name, fn) {
|
||||||
|
if (process.env.QA_FILTER && !name.includes(process.env.QA_FILTER)) return;
|
||||||
|
let s;
|
||||||
|
try {
|
||||||
|
s = await fn();
|
||||||
|
if (s) await s.close();
|
||||||
|
results.push({ name, pass: true });
|
||||||
|
console.log('PASS', name);
|
||||||
|
} catch (e) {
|
||||||
|
results.push({ name, pass: false, error: e.stack });
|
||||||
|
console.error('FAIL', name, e.message);
|
||||||
|
console.error('BODY', await active.p.locator('body').innerText());
|
||||||
|
await active.p.screenshot({
|
||||||
|
path: out + '/failure-' + results.length + '.png',
|
||||||
|
});
|
||||||
|
await active.ctx.close();
|
||||||
|
}
|
||||||
|
fs.writeFileSync(
|
||||||
|
out + '/fixed-results.json',
|
||||||
|
JSON.stringify(results, null, 2),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await test('lazy mounting, first cost load, tab draft persistence', async () => {
|
||||||
|
const s = await setup({ direct: false });
|
||||||
|
await s.goto();
|
||||||
|
await sleep(300);
|
||||||
|
assert.equal(
|
||||||
|
s.requests.filter((r) => r.path.includes('/commission/costs')).length,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
await s.p.getByText('模型成本价格', { exact: true }).click();
|
||||||
|
await loaded(s);
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('7');
|
||||||
|
await s.p.getByText('模型倍率设置', { exact: true }).first().click();
|
||||||
|
await s.p.getByText('模型成本价格', { exact: true }).click();
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '7');
|
||||||
|
await sleep(350);
|
||||||
|
await s.p.screenshot({ path: out + '/fixed-tabs.png' });
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('non Root has no cost tab', async () => {
|
||||||
|
const s = await setup({ direct: false, role: 10 });
|
||||||
|
await s.goto();
|
||||||
|
assert.equal(
|
||||||
|
await s.p.getByText('模型成本价格', { exact: true }).count(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('A dirty -> B 500 clears A and prevents all writes', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('7');
|
||||||
|
s.readMode = 'failB';
|
||||||
|
await choose(s, 2);
|
||||||
|
await confirm(s.p, '放弃修改并切换');
|
||||||
|
await s.p
|
||||||
|
.getByText('错误:加载成本配置失败,请重试', { exact: true })
|
||||||
|
.waitFor();
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').count(), 0);
|
||||||
|
assert(await button(s.p, '保存成本价').isDisabled());
|
||||||
|
assert(await button(s.p, '按官方价折扣批量定价').isDisabled());
|
||||||
|
await sleep(350);
|
||||||
|
await s.p.screenshot({ path: out + '/fixed-cross-channel.png' });
|
||||||
|
await noWrites(s);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('A slow B fast keeps B snapshot after A completes', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
const gate = deferred();
|
||||||
|
s.readGates['1'] = gate;
|
||||||
|
await s.goto();
|
||||||
|
await choose(s, 2);
|
||||||
|
await loaded(s, 'B');
|
||||||
|
gate.resolve();
|
||||||
|
await sleep(200);
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '2');
|
||||||
|
assert.equal(await s.p.getByText('model-A', { exact: true }).count(), 0);
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('8');
|
||||||
|
await button(s.p, '保存成本价').click();
|
||||||
|
await sleep(200);
|
||||||
|
assert.equal(s.writes[0].body.scope_key, '2');
|
||||||
|
assert.equal(s.writes[0].body.items[0].model_name, 'model-B');
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('old failed request cannot toast or unlock newer B pending read', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
const a = deferred(),
|
||||||
|
b = deferred();
|
||||||
|
s.readMode = '500';
|
||||||
|
s.readGates['1'] = a;
|
||||||
|
await s.goto();
|
||||||
|
await sleep(100);
|
||||||
|
s.readMode = 'normal';
|
||||||
|
s.readGates['2'] = b;
|
||||||
|
await choose(s, 2);
|
||||||
|
await until(() => s.requests.filter((r) => r.key === '2').length === 2);
|
||||||
|
a.resolve();
|
||||||
|
await sleep(100);
|
||||||
|
assert.equal(await s.p.locator('.semi-toast-content').count(), 0);
|
||||||
|
assert(await button(s.p, '按官方价折扣批量定价').isDisabled());
|
||||||
|
b.resolve();
|
||||||
|
await loaded(s, 'B');
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('invalid draft switch cancel preserves; confirm discards', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('-2');
|
||||||
|
await choose(s, 2);
|
||||||
|
await confirm(s.p, '留在当前渠道');
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '-2');
|
||||||
|
await choose(s, 2);
|
||||||
|
await confirm(s.p, '放弃修改并切换');
|
||||||
|
await loaded(s, 'B');
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '2');
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('same-channel failed refresh retains readonly draft then confirms recovery', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('7');
|
||||||
|
s.readMode = '500';
|
||||||
|
await refresh(s);
|
||||||
|
await confirm(s.p, '放弃修改并刷新');
|
||||||
|
await s.p
|
||||||
|
.getByText('错误:加载成本配置失败,请重试', { exact: true })
|
||||||
|
.waitFor();
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '7');
|
||||||
|
assert(await s.p.getByPlaceholder('成本单价').isDisabled());
|
||||||
|
assert(await button(s.p, '保存成本价').isDisabled());
|
||||||
|
assert(await button(s.p, '按官方价折扣批量定价').isDisabled());
|
||||||
|
s.readMode = 'normal';
|
||||||
|
await refresh(s);
|
||||||
|
await confirm(s.p, '放弃修改并刷新');
|
||||||
|
await sleep(200);
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '1');
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('clear selection confirms dirty draft, disables writes, no empty scope GET', async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('7');
|
||||||
|
await s.p.locator('.semi-select').first().hover();
|
||||||
|
await s.p.locator('.semi-select-clear').first().click();
|
||||||
|
await confirm(s.p, '放弃修改并切换');
|
||||||
|
await sleep(100);
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').count(), 0);
|
||||||
|
assert(await button(s.p, '保存成本价').isDisabled());
|
||||||
|
assert(await button(s.p, '按官方价折扣批量定价').isDisabled());
|
||||||
|
assert(
|
||||||
|
!s.requests.some(
|
||||||
|
(r) =>
|
||||||
|
r.path.includes('/commission/costs/') &&
|
||||||
|
!r.path.endsWith('uncovered') &&
|
||||||
|
r.key === '',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('no channel defaults has no scoped requests or writes', async () => {
|
||||||
|
const s = await setup({ channels: false });
|
||||||
|
await s.goto();
|
||||||
|
await sleep(100);
|
||||||
|
assert(!s.requests.some((r) => r.path.endsWith('scope_models')));
|
||||||
|
assert(await button(s.p, '保存成本价').isDisabled());
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
for (const mode of ['410-valid', '410-empty', '410-object', '500', 'network'])
|
||||||
|
await test('error presentation ' + mode, async () => {
|
||||||
|
const s = await setup();
|
||||||
|
s.readMode = mode;
|
||||||
|
await s.goto();
|
||||||
|
const expected =
|
||||||
|
mode === '410-valid'
|
||||||
|
? '错误:旧版分佣已停用:测试说明'
|
||||||
|
: '错误:加载成本配置失败,请重试';
|
||||||
|
await s.p.getByText(expected, { exact: true }).waitFor();
|
||||||
|
assert.equal(await s.p.locator('.semi-toast-content').count(), 1);
|
||||||
|
assert(await button(s.p, '保存成本价').isDisabled());
|
||||||
|
await noWrites(s);
|
||||||
|
if (mode === '410-valid') await sleep(350);
|
||||||
|
await s.p.screenshot({ path: out + '/fixed-410.png' });
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
for (const kind of ['save', 'save-delete', 'discount', 'advanced', 'delete'])
|
||||||
|
await test('write lock and payload ' + kind, async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
s.writeGate = deferred();
|
||||||
|
let submit;
|
||||||
|
if (kind === 'save') {
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('7');
|
||||||
|
submit = button(s.p, '保存成本价');
|
||||||
|
}
|
||||||
|
if (kind === 'save-delete') {
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('');
|
||||||
|
await button(s.p, '保存成本价').click();
|
||||||
|
submit = s.p.getByText('确认保存', { exact: true });
|
||||||
|
}
|
||||||
|
if (kind === 'discount') {
|
||||||
|
await button(s.p, '按官方价折扣批量定价').click();
|
||||||
|
await s.p.getByText('覆盖(新开一版价格)', { exact: true }).click();
|
||||||
|
submit = modal(s.p).locator('.semi-modal-footer button').last();
|
||||||
|
}
|
||||||
|
if (kind === 'advanced') {
|
||||||
|
await advanced(s);
|
||||||
|
await modal(s.p).locator('input').first().fill('9');
|
||||||
|
submit = modal(s.p).locator('.semi-modal-footer button').last();
|
||||||
|
}
|
||||||
|
if (kind === 'delete') {
|
||||||
|
await history(s);
|
||||||
|
await button(s.p, '删除').click();
|
||||||
|
submit = modal(s.p).locator('.semi-modal-footer button').last();
|
||||||
|
}
|
||||||
|
await submit.evaluate((el) => {
|
||||||
|
el.click();
|
||||||
|
el.click();
|
||||||
|
});
|
||||||
|
await sleep(100);
|
||||||
|
assert.equal(s.writes.length, 1);
|
||||||
|
assert(await button(s.p, '刷新').isDisabled());
|
||||||
|
assert(await button(s.p, '按官方价折扣批量定价').isDisabled());
|
||||||
|
assert(
|
||||||
|
await s.p
|
||||||
|
.locator('.semi-select')
|
||||||
|
.first()
|
||||||
|
.getAttribute('class')
|
||||||
|
.then((v) => v.includes('disabled')),
|
||||||
|
);
|
||||||
|
const w = s.writes[0];
|
||||||
|
if (['save', 'discount'].includes(kind)) {
|
||||||
|
assert.equal(w.body.scope, 'channel');
|
||||||
|
assert.equal(w.body.scope_key, '1');
|
||||||
|
if (kind === 'save') {
|
||||||
|
assert.equal(w.body.items[0].model_name, 'model-A');
|
||||||
|
assert.equal(w.body.items[0].cost_uyuan_per_unit, 7000000);
|
||||||
|
} else {
|
||||||
|
assert.deepEqual(w.body.model_names, ['model-A']);
|
||||||
|
assert.equal(w.body.discount, 0.2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (kind === 'advanced') {
|
||||||
|
assert.equal(w.body[0].scope_key, '1');
|
||||||
|
assert.equal(w.body[0].model_name, 'model-A');
|
||||||
|
assert.equal(w.body[0].id, 101);
|
||||||
|
assert.equal(w.body[0].cost_uyuan_per_unit, 9000000);
|
||||||
|
}
|
||||||
|
if (kind === 'save-delete') assert.deepEqual(w.body.ids, [101]);
|
||||||
|
if (kind === 'delete') assert(w.path.endsWith('/101'));
|
||||||
|
s.writeGate.resolve();
|
||||||
|
await sleep(250);
|
||||||
|
assert.equal(s.writes.length, 1);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
for (const mode of ['reject', 'business-reject', 'network'])
|
||||||
|
await test('failed delete retains inline draft ' + mode, async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('7');
|
||||||
|
await history(s);
|
||||||
|
await button(s.p, '删除').click();
|
||||||
|
s.writeMode = mode;
|
||||||
|
await modalOk(s);
|
||||||
|
await until(
|
||||||
|
() =>
|
||||||
|
s.requests.filter(
|
||||||
|
(r) => r.method === 'GET' && r.path.endsWith('scope_models'),
|
||||||
|
).length === 2,
|
||||||
|
);
|
||||||
|
await s.p.waitForFunction(() => {
|
||||||
|
const input = document.querySelector('input[placeholder="成本单价"]');
|
||||||
|
return input && !input.disabled;
|
||||||
|
});
|
||||||
|
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '7');
|
||||||
|
assert.equal(await button(s.p, '保存成本价').isEnabled(), true);
|
||||||
|
assert.equal(s.writes.length, 1, 'failed deletion must not auto-retry');
|
||||||
|
assert.equal(s.writes[0].method, 'DELETE');
|
||||||
|
assert.equal(s.writes[0].path, '/api/commission/costs/101');
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
for (const failRead of [false, true])
|
||||||
|
await test(
|
||||||
|
'failed advanced write retains draft, read ' +
|
||||||
|
(failRead ? 'fails' : 'succeeds'),
|
||||||
|
async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await advanced(s);
|
||||||
|
await modal(s.p).locator('input').first().fill('9');
|
||||||
|
await modal(s.p).locator('input').last().fill('keep draft');
|
||||||
|
s.writeMode = 'reject';
|
||||||
|
if (failRead) s.readMode = '500';
|
||||||
|
await modalOk(s);
|
||||||
|
await sleep(350);
|
||||||
|
assert.equal(
|
||||||
|
await modal(s.p).locator('input').first().inputValue(),
|
||||||
|
'9',
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
await modal(s.p).locator('input').last().inputValue(),
|
||||||
|
'keep draft',
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
await modal(s.p)
|
||||||
|
.locator('.semi-modal-footer button')
|
||||||
|
.last()
|
||||||
|
.isDisabled(),
|
||||||
|
failRead,
|
||||||
|
);
|
||||||
|
assert.equal(s.writes.length, 1);
|
||||||
|
if (!failRead) {
|
||||||
|
s.writeMode = 'normal';
|
||||||
|
await modalOk(s);
|
||||||
|
await sleep(200);
|
||||||
|
assert.equal(s.writes.length, 2);
|
||||||
|
assert.equal(s.writes[1].body[0].cost_uyuan_per_unit, 9000000);
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
for (const kind of ['save-delete', 'discount', 'advanced', 'delete'])
|
||||||
|
await test('stale confirmation after reload rejects ' + kind, async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
if (kind === 'save-delete') {
|
||||||
|
await s.p.getByPlaceholder('成本单价').fill('');
|
||||||
|
await button(s.p, '保存成本价').click();
|
||||||
|
}
|
||||||
|
if (kind === 'discount')
|
||||||
|
await button(s.p, '按官方价折扣批量定价').click();
|
||||||
|
if (kind === 'advanced') await advanced(s);
|
||||||
|
if (kind === 'delete') {
|
||||||
|
await history(s);
|
||||||
|
await button(s.p, '删除').click();
|
||||||
|
}
|
||||||
|
// Native DOM click exercises the underlying refresh handler while an old modal remains mounted.
|
||||||
|
await button(s.p, '刷新').evaluate((el) => el.click());
|
||||||
|
if (kind === 'save-delete') {
|
||||||
|
await confirm(s.p, '放弃修改并刷新');
|
||||||
|
}
|
||||||
|
await sleep(150);
|
||||||
|
const old =
|
||||||
|
kind === 'save-delete'
|
||||||
|
? s.p.getByText('确认保存', { exact: true })
|
||||||
|
: kind === 'delete'
|
||||||
|
? modal(s.p).locator('.semi-modal-footer button').last()
|
||||||
|
: modal(s.p).locator('.semi-modal-footer button').last();
|
||||||
|
// The refresh may unmount the dialog between count and click; inspect
|
||||||
|
// and click any surviving controls atomically without locator retries.
|
||||||
|
await old.evaluateAll((elements) => elements.forEach((el) => el.click()));
|
||||||
|
await noWrites(s);
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const action of ['edit', 'cancel'])
|
||||||
|
await test('pending failed advanced PUT ' + action, async () => {
|
||||||
|
const s = await setup();
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await advanced(s);
|
||||||
|
await modal(s.p).locator('input').first().fill('9');
|
||||||
|
s.writeMode = 'reject';
|
||||||
|
s.writeGate = deferred();
|
||||||
|
await modalOk(s);
|
||||||
|
await sleep(100);
|
||||||
|
if (action === 'edit')
|
||||||
|
await modal(s.p).locator('input').last().fill('typed while pending');
|
||||||
|
else
|
||||||
|
await modal(s.p).locator('.semi-modal-footer button').first().click();
|
||||||
|
s.writeGate.resolve();
|
||||||
|
await sleep(300);
|
||||||
|
assert.equal(s.writes.length, 1);
|
||||||
|
if (action === 'edit')
|
||||||
|
assert.equal(
|
||||||
|
await modal(s.p).locator('input').last().inputValue(),
|
||||||
|
'typed while pending',
|
||||||
|
);
|
||||||
|
else
|
||||||
|
await s.p
|
||||||
|
.getByText('编辑价格版本', { exact: true })
|
||||||
|
.waitFor({ state: 'detached' });
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
await test('mobile meaningful cost view', async () => {
|
||||||
|
const s = await setup({ viewport: { width: 390, height: 844 } });
|
||||||
|
await s.goto();
|
||||||
|
await loaded(s);
|
||||||
|
await sleep(350);
|
||||||
|
await s.p.screenshot({ path: out + '/fixed-mobile.png' });
|
||||||
|
assert.equal(await s.p.locator('vite-error-overlay').count(), 0);
|
||||||
|
assert.equal(await s.p.title(), 'Cost settings QA');
|
||||||
|
return s;
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
fs.writeFileSync(
|
||||||
|
out + '/fixed-requests.json',
|
||||||
|
JSON.stringify(allRequests, null, 2),
|
||||||
|
);
|
||||||
|
fs.writeFileSync(
|
||||||
|
out + '/fixed-console.json',
|
||||||
|
JSON.stringify(allErrors, null, 2),
|
||||||
|
);
|
||||||
|
await browser.close();
|
||||||
|
await server.close();
|
||||||
|
console.log(
|
||||||
|
JSON.stringify({
|
||||||
|
passed: results.filter((r) => r.pass).length,
|
||||||
|
total: results.length,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
if (results.some((r) => !r.pass)) process.exitCode = 1;
|
||||||
|
}
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
/*
|
||||||
|
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 postcss from 'postcss';
|
||||||
|
|
||||||
|
// 旧浏览器的级联层(@layer)兜底。
|
||||||
|
//
|
||||||
|
// index.css 把 Tailwind 的 base / components / utilities 整体包在原生 @layer 里,
|
||||||
|
// Semi 的按需样式也由 vitePluginSemi({ cssLayer: true }) 包进 @layer semi。
|
||||||
|
// @layer 自 Chromium 99 / Firefox 97 / Safari 15.4 才支持;更老的内核(停更的
|
||||||
|
// Edge、Win10 LTSC 自带 Edge、各类国产壳浏览器)把它当未知 at-rule 连同块内
|
||||||
|
// 全部规则一起丢弃 —— Tailwind 整体失效,页面只剩无尺寸约束的原图 logo。
|
||||||
|
//
|
||||||
|
// 这里在构建期把入口样式表里各层的内容按层序压平成一份不含 @layer 的样式表,
|
||||||
|
// index.html 里的内联探测脚本只在浏览器不认识 @layer 时才加载它。支持 @layer 的
|
||||||
|
// 浏览器不会请求这个文件,原有样式与层叠关系一个字节都不变。
|
||||||
|
//
|
||||||
|
// 压平只是近似,目标是页面可用而非像素一致。兜底表排在所有入口样式表之前,
|
||||||
|
// 因此「同特异性的普通声明,层外胜」得以保持;以下两点与原生级联层不同,
|
||||||
|
// 旧浏览器里会表现为局部外观差异(07 号文档 §95 有实例):
|
||||||
|
// - 层内 !important 本应无条件压过层外 !important,压平后改按特异性与先后;
|
||||||
|
// - 层内选择器特异性高于层外时会反超,原生层叠里层外恒胜。
|
||||||
|
|
||||||
|
// at 关键字大小写不敏感(@LAYER 也是合法写法),PostCSS 保留原始大小写,比较前统一
|
||||||
|
const isAtRule = (node, name) =>
|
||||||
|
node.type === 'atrule' && node.name.toLowerCase() === name;
|
||||||
|
const isLayer = (node) => isAtRule(node, 'layer');
|
||||||
|
|
||||||
|
// 文本里出现 @layer 不等于真有层规则(注释、字符串里也可能有这几个字),
|
||||||
|
// 先粗筛再解析确认,免得把没分层的样式表算进「必须兜底」的名单
|
||||||
|
const hasLayerRule = (css) => {
|
||||||
|
if (!/@layer/i.test(css)) return false;
|
||||||
|
let found = false;
|
||||||
|
postcss.parse(css).walkAtRules(/^layer$/i, () => {
|
||||||
|
found = true;
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
return found;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 只认「顶层的具名/匿名层块 + 层序声明」这一种形态(当前产物仅此一种)。
|
||||||
|
// 嵌套层、点号层名、条件块里的层、@import layer() 的优先级规则各不相同,
|
||||||
|
// 近似处理会悄悄排错顺序或漏收样式,而这类错误在新浏览器上完全看不出来 ——
|
||||||
|
// 所以遇到就让构建失败,由人来决定怎么扩展。
|
||||||
|
const assertSupportedShape = (root) => {
|
||||||
|
const reject = (what) => {
|
||||||
|
throw new Error(
|
||||||
|
`[legacy-css-layers] 入口样式表出现了 ${what},旧浏览器兜底尚不支持这种写法。` +
|
||||||
|
'请先扩展 scripts/vite/legacy-css-layers.js 的 flattenCssLayers 再构建。',
|
||||||
|
);
|
||||||
|
};
|
||||||
|
root.walkAtRules((rule) => {
|
||||||
|
if (isLayer(rule) && rule.parent !== root) {
|
||||||
|
reject(`非顶层的 @layer ${rule.params}`);
|
||||||
|
}
|
||||||
|
if (isLayer(rule) && rule.params.includes('.')) {
|
||||||
|
reject(`带点号的层名 @layer ${rule.params}`);
|
||||||
|
}
|
||||||
|
if (isAtRule(rule, 'import')) {
|
||||||
|
// 先去掉 url() 与字符串,免得文件名里的 layer 字样被当成关键字
|
||||||
|
const flags = rule.params.replace(/url\([^)]*\)|"[^"]*"|'[^']*'/gi, '');
|
||||||
|
if (/\blayer\b/i.test(flags)) reject(`@import ${rule.params}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从一组按文档顺序排列的 CSS 源码中取出所有级联层,按层序拼成不含 @layer 的 CSS。
|
||||||
|
* 层序与浏览器一致:按层名首次出现的先后(`@layer a, b;` 声明与 `@layer a {}` 块
|
||||||
|
* 都算出现),先出现的优先级低,因此排在前面。不在任何层里的规则不收录 ——
|
||||||
|
* 它们在旧浏览器里本来就生效。
|
||||||
|
*/
|
||||||
|
export function flattenCssLayers(sources) {
|
||||||
|
const roots = sources.map((css) => postcss.parse(css));
|
||||||
|
roots.forEach(assertSupportedShape);
|
||||||
|
|
||||||
|
// 层外已有逐字相同的规则时,层内那份不必收:选择器与声明都一样、层外的又加载
|
||||||
|
// 在后,它在旧浏览器里必然被覆盖。Semi 的 @layer 副本整份属于这种情况
|
||||||
|
// (index.jsx 另行全量引入了层外的 semi.css),剔掉后兜底表只剩约五分之一。
|
||||||
|
const unlayered = new Set();
|
||||||
|
for (const root of roots) {
|
||||||
|
root.each((node) => {
|
||||||
|
if (!isLayer(node) && node.type !== 'comment') {
|
||||||
|
unlayered.add(node.toString());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const layers = new Map();
|
||||||
|
const layerOf = (name) => {
|
||||||
|
if (!layers.has(name)) layers.set(name, []);
|
||||||
|
return layers.get(name);
|
||||||
|
};
|
||||||
|
for (const root of roots) {
|
||||||
|
root.each((node) => {
|
||||||
|
if (!isLayer(node)) return;
|
||||||
|
if (!node.nodes) {
|
||||||
|
postcss.list.comma(node.params).forEach(layerOf);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 匿名层各自独立,用块对象本身当 key 避免互相合并
|
||||||
|
layerOf(node.params.trim() || node).push(
|
||||||
|
node.nodes.filter((child) => !unlayered.has(child.toString())),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const flattened = postcss.root();
|
||||||
|
for (const blocks of layers.values()) {
|
||||||
|
for (const nodes of blocks) flattened.append(nodes);
|
||||||
|
}
|
||||||
|
return flattened.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 内联探测脚本:不经过转译,语法须停留在 ES5,且同步执行。
|
||||||
|
// 用 document.write 而非 createElement 插入 <link>:解析器创建的样式表与其余
|
||||||
|
// 入口样式表一样阻塞首帧,不会先闪一下无样式页面。
|
||||||
|
const buildLoader = (href) =>
|
||||||
|
`<script>
|
||||||
|
(function () {
|
||||||
|
try {
|
||||||
|
var probe = document.createElement('style');
|
||||||
|
probe.textContent = '@layer wl-probe{}';
|
||||||
|
document.head.appendChild(probe);
|
||||||
|
var supported = probe.sheet.cssRules.length > 0;
|
||||||
|
document.head.removeChild(probe);
|
||||||
|
if (supported) return;
|
||||||
|
} catch (e) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
document.write('<link rel="stylesheet" href="${href}">');
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
`;
|
||||||
|
|
||||||
|
const STYLESHEET_LINK = /<link\b[^>]*\brel="stylesheet"[^>]*>/g;
|
||||||
|
const CONDITIONAL_LINK = /\s(?:media|disabled)(?=[\s=>/])/i;
|
||||||
|
|
||||||
|
// Rollup 的 asset.source 可能是 string 或 Uint8Array
|
||||||
|
const sourceText = (asset) =>
|
||||||
|
typeof asset.source === 'string'
|
||||||
|
? asset.source
|
||||||
|
: Buffer.from(asset.source).toString('utf8');
|
||||||
|
|
||||||
|
export default function legacyCssLayers() {
|
||||||
|
let base = '/';
|
||||||
|
return {
|
||||||
|
name: 'legacy-css-layers',
|
||||||
|
apply: 'build',
|
||||||
|
// 排在 vite:build-html 之后:此时 index.html 已带上最终的样式表 <link>
|
||||||
|
enforce: 'post',
|
||||||
|
configResolved(config) {
|
||||||
|
base = config.base;
|
||||||
|
},
|
||||||
|
generateBundle(_, bundle) {
|
||||||
|
const layered = Object.keys(bundle).filter(
|
||||||
|
(name) =>
|
||||||
|
name.endsWith('.css') &&
|
||||||
|
bundle[name].type === 'asset' &&
|
||||||
|
hasLayerRule(sourceText(bundle[name])),
|
||||||
|
);
|
||||||
|
if (!layered.length) return;
|
||||||
|
|
||||||
|
// 走到这里说明产物确实依赖 @layer。注入所依赖的 index.html 或入口 <link>
|
||||||
|
// 找不到时,旧浏览器拿不到兜底而新浏览器上毫无征兆 —— 让构建失败,不静默跳过。
|
||||||
|
const page = bundle['index.html'];
|
||||||
|
if (page?.type !== 'asset') {
|
||||||
|
this.error('样式表用到了 @layer,但产物里没有 index.html 可供注入兜底');
|
||||||
|
}
|
||||||
|
const html = sourceText(page);
|
||||||
|
|
||||||
|
// 入口样式表:能对应到产物文件、且无条件加载的 <link>,按文档顺序(层序取决于它)。
|
||||||
|
// 只认解析得出产物文件的标签,注释或脚本字符串里的同形文本不会被当成锚点;
|
||||||
|
// 带 media / disabled 的标签只在特定条件下生效,它的规则既不能无条件收进兜底表,
|
||||||
|
// 也不能拿来给别的样式表剔重,所以不算入口。
|
||||||
|
const entry = [...html.matchAll(STYLESHEET_LINK)]
|
||||||
|
.filter(([tag]) => !CONDITIONAL_LINK.test(tag))
|
||||||
|
.map((match) => ({
|
||||||
|
at: match.index,
|
||||||
|
href: /\bhref="([^"]+)"/.exec(match[0])?.[1],
|
||||||
|
}))
|
||||||
|
.filter(({ href }) => href?.startsWith(base))
|
||||||
|
.map(({ at, href }) => ({ at, name: href.slice(base.length) }))
|
||||||
|
.filter(({ name }) => bundle[name]?.type === 'asset');
|
||||||
|
if (!entry.length) {
|
||||||
|
this.error(
|
||||||
|
'样式表用到了 @layer,但没能从 index.html 里解析出任何入口样式表 <link>,无法注入兜底',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const entryNames = entry.map(({ name }) => name);
|
||||||
|
|
||||||
|
// 不经过入口 <link> 的样式表(懒加载分包、条件加载的表)兜底覆盖不到:
|
||||||
|
// 旧浏览器会丢掉它们层内的那部分样式。
|
||||||
|
for (const name of layered) {
|
||||||
|
if (entryNames.includes(name)) continue;
|
||||||
|
this.warn(`${name} 含 @layer 但不是入口样式表,旧浏览器兜底覆盖不到它`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const css = flattenCssLayers(
|
||||||
|
entryNames.map((name) => sourceText(bundle[name])),
|
||||||
|
);
|
||||||
|
// 层内规则在层外全都有逐字副本:旧浏览器什么也不缺
|
||||||
|
if (!css) return;
|
||||||
|
|
||||||
|
const fileName = this.getFileName(
|
||||||
|
this.emitFile({
|
||||||
|
type: 'asset',
|
||||||
|
name: 'legacy-layers.css',
|
||||||
|
source: css,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
// 插在第一个入口样式表之前,兜底表才排在所有入口样式表前面
|
||||||
|
const { at } = entry[0];
|
||||||
|
page.source =
|
||||||
|
html.slice(0, at) + buildLoader(base + fileName) + html.slice(at);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
+45
-8
@@ -24,7 +24,7 @@ import {
|
|||||||
isMiniProgramWebView,
|
isMiniProgramWebView,
|
||||||
} from './helpers/miniProgram';
|
} from './helpers/miniProgram';
|
||||||
import Loading from './components/common/ui/Loading';
|
import Loading from './components/common/ui/Loading';
|
||||||
import { AuthRedirect, PrivateRoute, AdminRoute } from './helpers';
|
import { AuthRedirect, PrivateRoute, AdminRoute, RootRoute } from './helpers';
|
||||||
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';
|
||||||
@@ -58,8 +58,7 @@ const Docs = lazy(() => import('./pages/Docs'));
|
|||||||
const LoginForm = lazy(() => import('./components/auth/LoginForm'));
|
const LoginForm = lazy(() => import('./components/auth/LoginForm'));
|
||||||
const OrgLogin = lazy(() => import('./pages/OrgLogin'));
|
const OrgLogin = lazy(() => import('./pages/OrgLogin'));
|
||||||
const PartnerPortal = lazy(() => import('./pages/PartnerPortal'));
|
const PartnerPortal = lazy(() => import('./pages/PartnerPortal'));
|
||||||
const PartnerConsole = lazy(() => import('./pages/PartnerPortal/Console'));
|
const CommissionV2 = lazy(() => import('./pages/CommissionV2'));
|
||||||
const MyCommission = lazy(() => import('./pages/MyCommission'));
|
|
||||||
const OrgRegister = lazy(() => import('./pages/OrgRegister'));
|
const OrgRegister = lazy(() => import('./pages/OrgRegister'));
|
||||||
const RegisterForm = lazy(() => import('./components/auth/RegisterForm'));
|
const RegisterForm = lazy(() => import('./components/auth/RegisterForm'));
|
||||||
const PasswordResetForm = lazy(
|
const PasswordResetForm = lazy(
|
||||||
@@ -94,6 +93,7 @@ const PersonalSetting = lazy(
|
|||||||
);
|
);
|
||||||
const Setup = lazy(() => import('./pages/Setup'));
|
const Setup = lazy(() => import('./pages/Setup'));
|
||||||
const Analytics = lazy(() => import('./pages/Analytics'));
|
const Analytics = lazy(() => import('./pages/Analytics'));
|
||||||
|
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 AdminOrder = lazy(() => import('./pages/AdminOrder'));
|
const AdminOrder = lazy(() => import('./pages/AdminOrder'));
|
||||||
@@ -147,6 +147,22 @@ const PricingLegacyRedirect = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 密钥管理旧路径 /key-management → /user-center/key-management,同样保留 query/hash
|
||||||
|
// (如创作台 ?from=creation_studio 埋点来源、旧书签与登录回跳带参)
|
||||||
|
const KeyManagementLegacyRedirect = () => {
|
||||||
|
const location = useLocation();
|
||||||
|
return (
|
||||||
|
<Navigate
|
||||||
|
to={{
|
||||||
|
pathname: '/user-center/key-management',
|
||||||
|
search: location.search,
|
||||||
|
hash: location.hash,
|
||||||
|
}}
|
||||||
|
replace
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const [statusState] = useContext(StatusContext);
|
const [statusState] = useContext(StatusContext);
|
||||||
@@ -312,6 +328,16 @@ function App() {
|
|||||||
</AdminRoute>
|
</AdminRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
<Route
|
||||||
|
path='/console/smart-router'
|
||||||
|
element={
|
||||||
|
<PrivateRoute>
|
||||||
|
<Suspense fallback={<Loading />}>
|
||||||
|
<SmartRouter />
|
||||||
|
</Suspense>
|
||||||
|
</PrivateRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/console/analytics'
|
path='/console/analytics'
|
||||||
element={
|
element={
|
||||||
@@ -327,7 +353,7 @@ function App() {
|
|||||||
element={
|
element={
|
||||||
<PrivateRoute>
|
<PrivateRoute>
|
||||||
<Suspense fallback={<Loading />}>
|
<Suspense fallback={<Loading />}>
|
||||||
<MyCommission />
|
<CommissionV2 />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</PrivateRoute>
|
</PrivateRoute>
|
||||||
}
|
}
|
||||||
@@ -336,12 +362,23 @@ function App() {
|
|||||||
path='/console/partner'
|
path='/console/partner'
|
||||||
element={
|
element={
|
||||||
<PrivateRoute>
|
<PrivateRoute>
|
||||||
<Suspense fallback={<Loading />}>
|
<Navigate to='/console/my-commission' replace />
|
||||||
<PartnerConsole />
|
|
||||||
</Suspense>
|
|
||||||
</PrivateRoute>
|
</PrivateRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
<Route
|
||||||
|
path='/console/commission'
|
||||||
|
element={
|
||||||
|
/* 分佣管理为 Root 专属:侧边栏一直用 isRoot() 隐藏该入口,后端结算/销售/成本/
|
||||||
|
伙伴管理各路由组也已全部 Root 收口。这里把路由守卫对齐,避免 role=10 直接
|
||||||
|
输 URL 进到一个读得到、写按钮全 403 的半残页面。 */
|
||||||
|
<RootRoute>
|
||||||
|
<Suspense fallback={<Loading />}>
|
||||||
|
<CommissionV2 />
|
||||||
|
</Suspense>
|
||||||
|
</RootRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/console/experience-center-audit'
|
path='/console/experience-center-audit'
|
||||||
element={
|
element={
|
||||||
@@ -726,7 +763,7 @@ function App() {
|
|||||||
{/* 密钥管理归入用户中心路径;旧地址保留为重定向(旧链接、登录回跳、书签) */}
|
{/* 密钥管理归入用户中心路径;旧地址保留为重定向(旧链接、登录回跳、书签) */}
|
||||||
<Route
|
<Route
|
||||||
path='/key-management'
|
path='/key-management'
|
||||||
element={<Navigate to='/user-center/key-management' replace />}
|
element={<KeyManagementLegacyRedirect />}
|
||||||
/>
|
/>
|
||||||
<Route
|
<Route
|
||||||
path='/user-center/key-management'
|
path='/user-center/key-management'
|
||||||
|
|||||||
@@ -0,0 +1,379 @@
|
|||||||
|
/*
|
||||||
|
Copyright (C) 2025 QuantumNous
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as
|
||||||
|
published by the Free Software Foundation, either version 3 of the
|
||||||
|
License, or (at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
For commercial licensing, please contact support@quantumnous.com
|
||||||
|
*/
|
||||||
|
|
||||||
|
import React, { useMemo, useState, useEffect } from 'react';
|
||||||
|
import { Button, Empty, Segmented, Skeleton, theme } from 'antd';
|
||||||
|
import { VChart } from '@visactor/react-vchart';
|
||||||
|
import { Info } from 'lucide-react';
|
||||||
|
import { RefreshCw } from '@/components/common/icons/ActionIcons';
|
||||||
|
import { ConsoleDrawer } from '@/components/console/ConsolePrimitives';
|
||||||
|
import useOrgCacheHourly from '../../hooks/analytics/useOrgCacheHourly';
|
||||||
|
import { useIsMobile } from '../../hooks/common/useIsMobile';
|
||||||
|
|
||||||
|
// 图表序列色属于专用图表(VChart)配色,统计块沿用同色以便与图例对应。
|
||||||
|
// 千分位缩写。线上单小时 cache_read 能到十亿量级,不缩写轴标签会糊成一片。
|
||||||
|
const abbr = (n) => {
|
||||||
|
const v = Number(n) || 0;
|
||||||
|
const abs = Math.abs(v);
|
||||||
|
if (abs >= 1e9) return `${(v / 1e9).toFixed(2)}B`;
|
||||||
|
if (abs >= 1e6) return `${(v / 1e6).toFixed(2)}M`;
|
||||||
|
if (abs >= 1e3) return `${(v / 1e3).toFixed(2)}K`;
|
||||||
|
return `${v}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const money = (n) => {
|
||||||
|
const v = Number(n) || 0;
|
||||||
|
if (Math.abs(v) >= 1000) return `$${(v / 1000).toFixed(2)}K`;
|
||||||
|
return `$${v.toFixed(2)}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
// unix 秒 → 本地「MM-DD HH:00」。后端返回的是小时桶起点,整点整分,不做四舍五入。
|
||||||
|
const hourLabel = (unixSec) => {
|
||||||
|
const d = new Date((Number(unixSec) || 0) * 1000);
|
||||||
|
const p = (x) => String(x).padStart(2, '0');
|
||||||
|
return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:00`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const SERIES_COLORS = {
|
||||||
|
input: '#3b82f6',
|
||||||
|
output: '#10b981',
|
||||||
|
cacheCreation: '#f59e0b',
|
||||||
|
cacheRead: '#8b5cf6',
|
||||||
|
hitRate: '#ef4444',
|
||||||
|
};
|
||||||
|
|
||||||
|
const StatBlock = ({ label, value, sub, color }) => (
|
||||||
|
<div className='flex-1 min-w-[110px]'>
|
||||||
|
<div className='text-xs text-[var(--text-secondary)] mb-1'>{label}</div>
|
||||||
|
<div
|
||||||
|
className='text-lg font-semibold'
|
||||||
|
style={color ? { color } : undefined}
|
||||||
|
>
|
||||||
|
{value}
|
||||||
|
</div>
|
||||||
|
{sub ? (
|
||||||
|
<div className='text-xs text-[var(--text-secondary)] mt-0.5'>{sub}</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单企业逐小时缓存命中率报表抽屉。
|
||||||
|
*
|
||||||
|
* 数据源是企业小时聚合表,不是 logs —— 口径与成本理由见
|
||||||
|
* model/analytics_org_cache.go 顶部注释。
|
||||||
|
*/
|
||||||
|
const OrgCacheHourlySheet = ({ visible, org, onClose, t }) => {
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
const { token } = theme.useToken();
|
||||||
|
const [hours, setHours] = useState(24);
|
||||||
|
// 关闭后重开默认回到 24h:上次选了 7d 不该粘到下一家企业上。
|
||||||
|
useEffect(() => {
|
||||||
|
if (!visible) setHours(24);
|
||||||
|
}, [visible]);
|
||||||
|
|
||||||
|
const orgId = visible ? org?.org_id : null;
|
||||||
|
const { data, loading, error, refresh } = useOrgCacheHourly(orgId, hours);
|
||||||
|
|
||||||
|
const points = useMemo(() => data?.points || [], [data]);
|
||||||
|
const totals = data?.totals || null;
|
||||||
|
// 全窗口零流量:补出来的点都是 0,画出来是一条贴底的直线,不如直接给空态。
|
||||||
|
const hasTraffic = points.some((p) => (p.requests || 0) > 0);
|
||||||
|
|
||||||
|
const spec = useMemo(() => {
|
||||||
|
if (!points.length || !hasTraffic) return null;
|
||||||
|
|
||||||
|
const inputKey = t('输入');
|
||||||
|
const outputKey = t('输出');
|
||||||
|
const creationKey = t('写缓存');
|
||||||
|
const readKey = t('读缓存');
|
||||||
|
|
||||||
|
const stacked = [];
|
||||||
|
const rateRows = [];
|
||||||
|
points.forEach((p) => {
|
||||||
|
const label = hourLabel(p.hour);
|
||||||
|
stacked.push(
|
||||||
|
{ hour: label, kind: inputKey, value: p.input || 0 },
|
||||||
|
{ hour: label, kind: outputKey, value: p.output || 0 },
|
||||||
|
{ hour: label, kind: creationKey, value: p.cache_creation || 0 },
|
||||||
|
{ hour: label, kind: readKey, value: p.cache_read || 0 },
|
||||||
|
);
|
||||||
|
rateRows.push({
|
||||||
|
hour: label,
|
||||||
|
// 该小时无流量时后端给 null;这里原样传下去并让序列 invalidType='break',
|
||||||
|
// 折线在空洞处断开,而不是掉到 0% 被误读成命中率暴跌。
|
||||||
|
hit_rate:
|
||||||
|
p.hit_rate === null || p.hit_rate === undefined ? null : p.hit_rate,
|
||||||
|
actual_cost: p.actual_cost || 0,
|
||||||
|
requests: p.requests || 0,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const rateKey = t('缓存命中率');
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: 'common',
|
||||||
|
data: [
|
||||||
|
{ id: 'tokens', values: stacked },
|
||||||
|
{ id: 'rate', values: rateRows },
|
||||||
|
],
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
type: 'bar',
|
||||||
|
id: 'tokens',
|
||||||
|
dataIndex: 0,
|
||||||
|
xField: 'hour',
|
||||||
|
yField: 'value',
|
||||||
|
seriesField: 'kind',
|
||||||
|
stack: true,
|
||||||
|
bar: { style: { cornerRadius: [0, 0, 0, 0] } },
|
||||||
|
tooltip: {
|
||||||
|
visible: true,
|
||||||
|
mark: {
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
key: (datum) => datum?.kind,
|
||||||
|
value: (datum) => `${abbr(datum?.value)} tokens`,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'line',
|
||||||
|
id: 'rate',
|
||||||
|
name: rateKey,
|
||||||
|
dataIndex: 1,
|
||||||
|
xField: 'hour',
|
||||||
|
yField: 'hit_rate',
|
||||||
|
// 空洞断线,不要 connectNulls 把两段无关的曲线连起来
|
||||||
|
invalidType: 'break',
|
||||||
|
point: {
|
||||||
|
visible: true,
|
||||||
|
size: 3,
|
||||||
|
style: { fill: SERIES_COLORS.hitRate },
|
||||||
|
},
|
||||||
|
line: { style: { stroke: SERIES_COLORS.hitRate, lineWidth: 2 } },
|
||||||
|
tooltip: {
|
||||||
|
visible: true,
|
||||||
|
mark: {
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
key: () => rateKey,
|
||||||
|
value: (datum) =>
|
||||||
|
datum?.hit_rate === null || datum?.hit_rate === undefined
|
||||||
|
? t('无流量')
|
||||||
|
: `${Number(datum.hit_rate).toFixed(1)}%`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: () => t('实际消费'),
|
||||||
|
value: (datum) => money(datum?.actual_cost),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: () => t('请求数'),
|
||||||
|
value: (datum) => (datum?.requests || 0).toLocaleString(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
color: [
|
||||||
|
SERIES_COLORS.input,
|
||||||
|
SERIES_COLORS.output,
|
||||||
|
SERIES_COLORS.cacheCreation,
|
||||||
|
SERIES_COLORS.cacheRead,
|
||||||
|
],
|
||||||
|
legends: {
|
||||||
|
visible: true,
|
||||||
|
orient: 'top',
|
||||||
|
position: 'middle',
|
||||||
|
padding: { top: 0, bottom: 12, left: 0, right: 0 },
|
||||||
|
layoutType: 'normal',
|
||||||
|
},
|
||||||
|
tooltip: { visible: true, dimension: { visible: true } },
|
||||||
|
crosshair: { xField: { visible: true, line: { visible: true } } },
|
||||||
|
axes: [
|
||||||
|
{
|
||||||
|
orient: 'bottom',
|
||||||
|
// 7d = 168 个桶,标签必须自动抽稀,否则重叠成黑条
|
||||||
|
label: { style: { angle: -45 }, autoLimit: true, autoHide: true },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
orient: 'left',
|
||||||
|
title: { visible: true, text: t('Token 数') },
|
||||||
|
label: { formatMethod: (v) => abbr(v) },
|
||||||
|
seriesIndex: [0],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
orient: 'right',
|
||||||
|
title: { visible: true, text: t('命中率 (%)') },
|
||||||
|
// 固定 0~100:让曲线的高低在不同企业、不同窗口之间可比。
|
||||||
|
// 自适应量程会把 76%~87% 的波动拉成满屏振荡,像出了故障。
|
||||||
|
min: 0,
|
||||||
|
max: 100,
|
||||||
|
label: { formatMethod: (v) => `${Math.round(v)}%` },
|
||||||
|
seriesIndex: [1],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}, [points, hasTraffic, t]);
|
||||||
|
|
||||||
|
const orgTitle = org?.org_name || (org ? `${t('企业')} ${org.org_id}` : '');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ConsoleDrawer
|
||||||
|
open={visible}
|
||||||
|
onClose={onClose}
|
||||||
|
size={isMobile ? '100%' : 820}
|
||||||
|
title={
|
||||||
|
<div className='flex items-center gap-2 flex-wrap'>
|
||||||
|
<span className='font-semibold'>{t('缓存命中率明细')}</span>
|
||||||
|
<span className='text-sm font-normal text-[var(--text-secondary)]'>
|
||||||
|
{orgTitle}
|
||||||
|
</span>
|
||||||
|
{org?.org_id ? (
|
||||||
|
<span className='text-xs font-normal text-[var(--text-secondary)]'>
|
||||||
|
#{org.org_id}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className='flex items-center justify-between gap-3 flex-wrap mb-4'>
|
||||||
|
<Segmented
|
||||||
|
value={hours}
|
||||||
|
onChange={setHours}
|
||||||
|
options={[
|
||||||
|
{ label: t('近 24 小时'), value: 24 },
|
||||||
|
{ label: t('近 7 天'), value: 24 * 7 },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
icon={<RefreshCw size={16} />}
|
||||||
|
onClick={refresh}
|
||||||
|
loading={loading}
|
||||||
|
>
|
||||||
|
{t('刷新')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{totals ? (
|
||||||
|
<div
|
||||||
|
className='flex flex-wrap gap-4 px-4 py-3 mb-4 rounded-lg'
|
||||||
|
style={{ background: token.colorFillAlter }}
|
||||||
|
>
|
||||||
|
<StatBlock
|
||||||
|
label={t('缓存命中率')}
|
||||||
|
value={
|
||||||
|
totals.hit_rate === null || totals.hit_rate === undefined
|
||||||
|
? '--'
|
||||||
|
: `${Number(totals.hit_rate).toFixed(2)}%`
|
||||||
|
}
|
||||||
|
sub={t('按 token 加权')}
|
||||||
|
color={SERIES_COLORS.hitRate}
|
||||||
|
/>
|
||||||
|
<StatBlock label={t('输入')} value={abbr(totals.input)} />
|
||||||
|
<StatBlock label={t('输出')} value={abbr(totals.output)} />
|
||||||
|
<StatBlock
|
||||||
|
label={t('写缓存')}
|
||||||
|
value={abbr(totals.cache_creation)}
|
||||||
|
color={SERIES_COLORS.cacheCreation}
|
||||||
|
/>
|
||||||
|
<StatBlock
|
||||||
|
label={t('读缓存')}
|
||||||
|
value={abbr(totals.cache_read)}
|
||||||
|
color={SERIES_COLORS.cacheRead}
|
||||||
|
/>
|
||||||
|
<StatBlock
|
||||||
|
label={t('实际消费')}
|
||||||
|
value={money(totals.actual_cost)}
|
||||||
|
sub={t('{{n}} 次请求', {
|
||||||
|
n: (totals.requests || 0).toLocaleString(),
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{loading && !points.length ? (
|
||||||
|
<Skeleton active title={false} paragraph={{ rows: 8 }} />
|
||||||
|
) : error ? (
|
||||||
|
<Empty
|
||||||
|
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||||
|
className='py-12'
|
||||||
|
description={
|
||||||
|
<>
|
||||||
|
<div className='text-[var(--text-primary)]'>{t('加载失败')}</div>
|
||||||
|
<div>{error}</div>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
) : spec ? (
|
||||||
|
<VChart
|
||||||
|
spec={spec}
|
||||||
|
option={{ mode: 'desktop-browser' }}
|
||||||
|
style={{ height: 360 }}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Empty
|
||||||
|
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||||
|
className='py-12'
|
||||||
|
description={
|
||||||
|
<>
|
||||||
|
<div className='text-[var(--text-primary)]'>
|
||||||
|
{t('该时间段内没有流量')}
|
||||||
|
</div>
|
||||||
|
<div>{t('所选窗口内这家企业没有产生可统计的请求')}</div>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 口径脚注:不写清楚的话,运营会拿这张图去对账单,然后发现对不上。 */}
|
||||||
|
<div
|
||||||
|
className='mt-4 px-3 py-2.5 text-xs text-[var(--text-secondary)] leading-relaxed rounded-md'
|
||||||
|
style={{ background: token.colorFillAlter }}
|
||||||
|
>
|
||||||
|
<div className='flex items-start gap-1.5'>
|
||||||
|
<Info aria-hidden className='w-3.5 h-3.5 mt-0.5 flex-shrink-0' />
|
||||||
|
<div>
|
||||||
|
<div>
|
||||||
|
{t(
|
||||||
|
'命中率 = 读缓存 ÷(输入 + 写缓存 + 读缓存)。输出 token 与缓存无关,不计入分母。',
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
{t(
|
||||||
|
'数据来自企业小时聚合表,按自然小时切桶;最后一个小时尚未走完,数字仍在累加。',
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
{t(
|
||||||
|
'「实际消费」为本平台实际计费金额;标准价对比待官方价目表配置完成后再上。',
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</ConsoleDrawer>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export { abbr as formatTokenAbbr, money as formatUsd, hourLabel };
|
||||||
|
export default OrgCacheHourlySheet;
|
||||||
@@ -0,0 +1,407 @@
|
|||||||
|
/*
|
||||||
|
Copyright (C) 2025 QuantumNous
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as
|
||||||
|
published by the Free Software Foundation, either version 3 of the
|
||||||
|
License, or (at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
For commercial licensing, please contact support@quantumnous.com
|
||||||
|
*/
|
||||||
|
|
||||||
|
import React, { useState, useCallback } from 'react';
|
||||||
|
import { Badge, Empty, Progress, Skeleton, Tag, Tooltip, theme } from 'antd';
|
||||||
|
import { ArrowDown } from 'lucide-react';
|
||||||
|
import {
|
||||||
|
ConsoleCard,
|
||||||
|
ConsoleTable,
|
||||||
|
} from '@/components/console/ConsolePrimitives';
|
||||||
|
import OrgCacheHourlySheet from './OrgCacheHourlySheet';
|
||||||
|
|
||||||
|
// 并发占用比对应的色阶:接近上限提前变黄,打满变红。
|
||||||
|
const WARN_RATIO = 0.8;
|
||||||
|
|
||||||
|
// 缓存命中率色阶。90% 是与客户约定的 KPI 线(严格口径),所以绿/黄的分界放在这里;
|
||||||
|
// 70% 以下基本意味着会话结构出了问题(深轮首触、子代理扇出),标红提示排查。
|
||||||
|
const CACHE_GOOD = 90;
|
||||||
|
const CACHE_WARN = 70;
|
||||||
|
|
||||||
|
// 色阶取主题语义 token(成功 / 警告 / 错误 / 主色),阈值不变
|
||||||
|
const cacheRateColor = (rate, token) => {
|
||||||
|
if (rate >= CACHE_GOOD) return token.colorSuccess;
|
||||||
|
if (rate >= CACHE_WARN) return token.colorWarning;
|
||||||
|
return token.colorError;
|
||||||
|
};
|
||||||
|
|
||||||
|
const concurrencyColor = (ratio, token) => {
|
||||||
|
if (ratio >= 1) return token.colorError;
|
||||||
|
if (ratio >= WARN_RATIO) return token.colorWarning;
|
||||||
|
return token.colorPrimary;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 可点击的表头:点一下换排序维度,始终降序(后端只支持降序 TOP-N)。
|
||||||
|
const SortableTitle = ({ label, field, sortBy, onSort }) => {
|
||||||
|
const active = sortBy === field;
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
role='button'
|
||||||
|
tabIndex={0}
|
||||||
|
aria-pressed={active}
|
||||||
|
className={`inline-flex items-center gap-1 cursor-pointer select-none transition-colors ${
|
||||||
|
active
|
||||||
|
? 'text-brand font-semibold'
|
||||||
|
: 'text-[var(--text-secondary)] hover:text-brand'
|
||||||
|
}`}
|
||||||
|
onClick={() => onSort(field)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter' || e.key === ' ') {
|
||||||
|
e.preventDefault();
|
||||||
|
onSort(field);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
<ArrowDown
|
||||||
|
aria-hidden
|
||||||
|
className={`w-3 h-3 ${active ? 'opacity-100' : 'opacity-25'}`}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const OrgRealtimeUsage = ({
|
||||||
|
data,
|
||||||
|
loading,
|
||||||
|
sortBy,
|
||||||
|
onSortChange,
|
||||||
|
limit = 10,
|
||||||
|
title,
|
||||||
|
icon,
|
||||||
|
t,
|
||||||
|
}) => {
|
||||||
|
const { token } = theme.useToken();
|
||||||
|
const items = data?.items || [];
|
||||||
|
const windowSeconds = data?.window_seconds || 60;
|
||||||
|
|
||||||
|
// 抽屉状态放在这里而不是提到页面级:它完全由本表的行点击驱动,
|
||||||
|
// 页面不需要知道它的存在。
|
||||||
|
const [detailOrg, setDetailOrg] = useState(null);
|
||||||
|
const closeDetail = useCallback(() => setDetailOrg(null), []);
|
||||||
|
|
||||||
|
const columns = [
|
||||||
|
{
|
||||||
|
title: t('企业'),
|
||||||
|
dataIndex: 'org_name',
|
||||||
|
key: 'org_name',
|
||||||
|
width: 220,
|
||||||
|
fixed: 'left',
|
||||||
|
render: (text, record) => (
|
||||||
|
<div className='flex items-center gap-2 min-w-0'>
|
||||||
|
<span className='text-sm font-medium truncate' title={text || ''}>
|
||||||
|
{text || `${t('企业')} ${record.org_id}`}
|
||||||
|
</span>
|
||||||
|
<span className='text-xs text-[var(--text-secondary)] flex-shrink-0'>
|
||||||
|
#{record.org_id}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: (
|
||||||
|
<SortableTitle
|
||||||
|
label={t('并发占用')}
|
||||||
|
field='concurrency'
|
||||||
|
sortBy={sortBy}
|
||||||
|
onSort={onSortChange}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
dataIndex: 'concurrency',
|
||||||
|
key: 'concurrency',
|
||||||
|
width: 220,
|
||||||
|
render: (val, record) => {
|
||||||
|
const current = val || 0;
|
||||||
|
const limit = record.max_concurrency || 0;
|
||||||
|
// 0 表示未配置上限:不画进度条(没有分母,画出来就是误导)。
|
||||||
|
if (limit <= 0) {
|
||||||
|
return (
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<span className='text-sm font-semibold text-[var(--text-primary)]'>
|
||||||
|
{current.toLocaleString()}
|
||||||
|
</span>
|
||||||
|
<span className='text-xs text-[var(--text-secondary)]'>
|
||||||
|
/ {t('不限制')}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const ratio = current / limit;
|
||||||
|
const color = concurrencyColor(ratio, token);
|
||||||
|
return (
|
||||||
|
<div className='min-w-0'>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<span className='text-sm font-semibold' style={{ color }}>
|
||||||
|
{current.toLocaleString()}
|
||||||
|
</span>
|
||||||
|
<span className='text-xs text-[var(--text-secondary)]'>
|
||||||
|
/ {limit.toLocaleString()}
|
||||||
|
</span>
|
||||||
|
{record.rejected > 0 && (
|
||||||
|
<Tooltip
|
||||||
|
title={t(
|
||||||
|
'近 {{seconds}} 秒内有 {{times}} 次请求因超过并发上限被限流(429)',
|
||||||
|
{
|
||||||
|
seconds: windowSeconds,
|
||||||
|
times: record.rejected,
|
||||||
|
},
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Tag color='error' variant='filled'>
|
||||||
|
{t('限流中')}
|
||||||
|
</Tag>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Progress
|
||||||
|
percent={Math.min(ratio * 100, 100)}
|
||||||
|
showInfo={false}
|
||||||
|
size='small'
|
||||||
|
className='mt-1'
|
||||||
|
strokeColor={color}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: (
|
||||||
|
<SortableTitle
|
||||||
|
label='RPM'
|
||||||
|
field='rpm'
|
||||||
|
sortBy={sortBy}
|
||||||
|
onSort={onSortChange}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
dataIndex: 'rpm',
|
||||||
|
key: 'rpm',
|
||||||
|
width: 140,
|
||||||
|
align: 'right',
|
||||||
|
render: (val) => (
|
||||||
|
<span className='text-sm font-semibold text-[var(--text-primary)]'>
|
||||||
|
{(val || 0).toLocaleString()}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: (
|
||||||
|
<SortableTitle
|
||||||
|
label='TPM'
|
||||||
|
field='tpm'
|
||||||
|
sortBy={sortBy}
|
||||||
|
onSort={onSortChange}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
dataIndex: 'tpm',
|
||||||
|
key: 'tpm',
|
||||||
|
width: 180,
|
||||||
|
align: 'right',
|
||||||
|
render: (val) => (
|
||||||
|
<span className='text-sm font-semibold text-brand-deep'>
|
||||||
|
{(val || 0).toLocaleString()}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// 这一列不可排序:后端的 TOP-N 是按内存计数器(并发/RPM/TPM)排的,
|
||||||
|
// 命中率是取完 TOP-N 之后再补的落库数据,没有「按命中率取前 N 名」这回事。
|
||||||
|
title: (
|
||||||
|
<Tooltip
|
||||||
|
title={t(
|
||||||
|
'近 1 小时的缓存命中率 = 读缓存 ÷(输入 + 写缓存 + 读缓存)。与左侧 RPM/TPM 的 60 秒窗口不同:命中率在分钟级噪声很大,按 60 秒算每次刷新都会跳。点击数字查看逐小时明细。',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span className='inline-flex items-center gap-1 text-[var(--text-secondary)] border-b border-dashed border-[var(--border-subtle)]'>
|
||||||
|
{t('1h 缓存命中率')}
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
),
|
||||||
|
dataIndex: 'cache_hit_rate',
|
||||||
|
key: 'cache_hit_rate',
|
||||||
|
width: 170,
|
||||||
|
align: 'right',
|
||||||
|
render: (val, record) => {
|
||||||
|
// 分母为 0 = 这一小时没有可统计的 token,不是「命中率 0%」。
|
||||||
|
// 两者混为一谈会让刚接入的企业看起来像缓存全丢。
|
||||||
|
if (!record.cache_tokens) {
|
||||||
|
return (
|
||||||
|
<Tooltip
|
||||||
|
title={
|
||||||
|
data?.cache_degraded
|
||||||
|
? t('缓存数据暂时不可用(小时聚合表查询失败)')
|
||||||
|
: t('近 1 小时没有可统计的 token')
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className='text-sm'
|
||||||
|
style={{ color: token.colorTextQuaternary }}
|
||||||
|
>
|
||||||
|
--
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const rate = val || 0;
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
role='button'
|
||||||
|
tabIndex={0}
|
||||||
|
className='inline-flex items-center justify-end gap-1 cursor-pointer select-none group'
|
||||||
|
onClick={() => setDetailOrg(record)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter' || e.key === ' ') {
|
||||||
|
e.preventDefault();
|
||||||
|
setDetailOrg(record);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className='text-sm font-semibold group-hover:underline'
|
||||||
|
style={{ color: cacheRateColor(rate, token) }}
|
||||||
|
>
|
||||||
|
{rate.toFixed(1)}%
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
aria-hidden
|
||||||
|
className='text-xs text-[var(--text-secondary)] group-hover:text-brand'
|
||||||
|
>
|
||||||
|
›
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ConsoleCard
|
||||||
|
title={
|
||||||
|
<div className='flex items-center justify-between w-full flex-wrap gap-2'>
|
||||||
|
<div className='flex items-center gap-2'>
|
||||||
|
<span className='text-brand'>{icon}</span>
|
||||||
|
<span className='font-semibold'>{title}</span>
|
||||||
|
<span className='text-xs font-normal text-[var(--text-secondary)] ml-2'>
|
||||||
|
{t('取前 {{limit}} 名', { limit })}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className='flex items-center gap-3'>
|
||||||
|
{data && data.enforced === false && (
|
||||||
|
<Tooltip
|
||||||
|
title={t(
|
||||||
|
'当前只计量不拦截(ORG_CONCURRENCY_LIMIT_ENABLED=false):即使占满上限也不会返回 429',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Tag color='default' variant='filled'>
|
||||||
|
{t('仅观测')}
|
||||||
|
</Tag>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
{data?.degraded ? (
|
||||||
|
<Tooltip
|
||||||
|
title={t(
|
||||||
|
'未启用 Redis 或心跳异常,当前仅统计本实例的数据,多节点部署时会偏小',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Badge
|
||||||
|
status='warning'
|
||||||
|
text={
|
||||||
|
<span className='text-xs font-normal'>
|
||||||
|
{t('单实例口径')}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Tooltip>
|
||||||
|
) : (
|
||||||
|
<Tooltip
|
||||||
|
title={t(
|
||||||
|
'统计 {{instances}} 个实例,窗口为近 {{seconds}} 秒滚动',
|
||||||
|
{
|
||||||
|
instances: data?.instances || 1,
|
||||||
|
seconds: windowSeconds,
|
||||||
|
},
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Badge
|
||||||
|
status='processing'
|
||||||
|
color={token.colorSuccess}
|
||||||
|
text={
|
||||||
|
<span className='text-xs font-normal'>
|
||||||
|
{t('实时 · 近 {{seconds}} 秒滚动', {
|
||||||
|
seconds: windowSeconds,
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
styles={{ body: { padding: 0 } }}
|
||||||
|
>
|
||||||
|
{loading && items.length === 0 ? (
|
||||||
|
<div className='px-4 py-6'>
|
||||||
|
<Skeleton active title={false} paragraph={{ rows: 5 }} />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<ConsoleTable
|
||||||
|
columns={columns}
|
||||||
|
dataSource={items}
|
||||||
|
pagination={false}
|
||||||
|
scroll={{ x: 930 }}
|
||||||
|
size='small'
|
||||||
|
rowKey='org_id'
|
||||||
|
locale={{
|
||||||
|
emptyText: (
|
||||||
|
<Empty
|
||||||
|
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||||
|
description={t('近 {{seconds}} 秒内没有企业产生请求', {
|
||||||
|
seconds: windowSeconds,
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{/* 口径脚注:并发/RPM 只盖同步转发,TPM 还滞后一个请求时长。
|
||||||
|
不写出来的话,运营会拿这张表去对账单,然后发现对不上。 */}
|
||||||
|
<div className='px-4 py-2.5 text-xs text-[var(--text-secondary)] leading-relaxed border-t border-[var(--border-subtle)]'>
|
||||||
|
{t(
|
||||||
|
'口径:仅统计 /v1、/v1beta 同步转发接口;Midjourney、Suno、视频与异步图片任务提交后在后台执行,不计入本表。',
|
||||||
|
)}{' '}
|
||||||
|
{t(
|
||||||
|
'RPM 含被限流拒绝的请求;TPM 在请求结束时才计入,长流式请求会在结束的那一秒形成毛刺。',
|
||||||
|
)}{' '}
|
||||||
|
{t(
|
||||||
|
'缓存命中率的窗口是近 1 小时(读企业小时聚合表),与左侧 60 秒窗口的指标不同步。',
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<OrgCacheHourlySheet
|
||||||
|
visible={!!detailOrg}
|
||||||
|
org={detailOrg}
|
||||||
|
onClose={closeDetail}
|
||||||
|
t={t}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</ConsoleCard>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default OrgRealtimeUsage;
|
||||||
@@ -42,12 +42,12 @@ const AuthCardHeader = ({
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={`flex flex-col items-center justify-center ${wrapperClassName}`}
|
className={`auth-card-header flex flex-col items-center justify-center ${wrapperClassName}`}
|
||||||
>
|
>
|
||||||
<div className={`relative ${logoWrapperClassName}`}>
|
<div className={`auth-card-logo relative ${logoWrapperClassName}`}>
|
||||||
{/* Logo 光环 */}
|
{/* Logo 光环(.auth-login-page 认证页内隐藏,保持克制) */}
|
||||||
<div className='absolute -inset-1.5 bg-gradient-to-r from-brand-from/30 to-brand-to/30 rounded-xl blur-md opacity-60' />
|
<div className='auth-card-logo-halo absolute -inset-1.5 bg-gradient-to-r from-brand-from/30 to-brand-to/30 rounded-xl blur-md opacity-60' />
|
||||||
<div className='relative p-2 bg-white dark:bg-neutral-800 rounded-xl shadow-md'>
|
<div className='auth-card-logo-box relative p-2 bg-white dark:bg-neutral-800 rounded-xl shadow-md'>
|
||||||
{logoNode || (
|
{logoNode || (
|
||||||
<img
|
<img
|
||||||
src={logo}
|
src={logo}
|
||||||
@@ -58,10 +58,10 @@ const AuthCardHeader = ({
|
|||||||
</div>
|
</div>
|
||||||
<Sparkles
|
<Sparkles
|
||||||
size={14}
|
size={14}
|
||||||
className='absolute -top-0.5 -right-0.5 text-amber-400 motion-safe:animate-pulse'
|
className='auth-card-sparkle absolute -top-0.5 -right-0.5 text-amber-400 motion-safe:animate-pulse'
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<h4 className='text-xl font-bold text-gray-800 dark:text-white tracking-tight mb-0.5'>
|
<h4 className='auth-card-title text-xl font-bold text-gray-800 dark:text-white tracking-tight mb-0.5'>
|
||||||
{title}
|
{title}
|
||||||
</h4>
|
</h4>
|
||||||
<p className='auth-card-subtitle text-gray-500 dark:text-gray-400 text-xs'>
|
<p className='auth-card-subtitle text-gray-500 dark:text-gray-400 text-xs'>
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
/*
|
||||||
|
Copyright (C) 2025 QuantumNous
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as
|
||||||
|
published by the Free Software Foundation, either version 3 of the
|
||||||
|
License, or (at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
For commercial licensing, please contact support@quantumnous.com
|
||||||
|
*/
|
||||||
|
|
||||||
|
import React from 'react';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 认证页统一的「— 文案 —」分隔线(如「或」「还没有企业?」)。
|
||||||
|
* 两侧细线 + 居中弱化文字,不依赖底色遮挡,玻璃卡片与深色模式下都干净。
|
||||||
|
* 样式见 src/styles/prototype.css 的 .auth-divider。
|
||||||
|
*/
|
||||||
|
const AuthDivider = ({ children, className = '' }) => (
|
||||||
|
<div className={`auth-divider ${className}`} role='separator'>
|
||||||
|
<span className='auth-divider-line' aria-hidden='true' />
|
||||||
|
<span className='auth-divider-text'>{children}</span>
|
||||||
|
<span className='auth-divider-line' aria-hidden='true' />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
export default AuthDivider;
|
||||||
@@ -201,14 +201,14 @@ const GlassCard = ({
|
|||||||
return (
|
return (
|
||||||
<div className={`w-full max-w-sm relative login-card-float ${className}`}>
|
<div className={`w-full max-w-sm relative login-card-float ${className}`}>
|
||||||
<GlassCardStyles />
|
<GlassCardStyles />
|
||||||
{/* 外环柔光晕 */}
|
{/* 外环柔光晕(.auth-login-page 认证页内隐藏) */}
|
||||||
<div className='absolute -inset-6 bg-gradient-to-br from-brand-from/15 via-brand-via/10 to-brand-to/15 rounded-[2rem] blur-2xl opacity-80 pointer-events-none' />
|
<div className='login-card-glow absolute -inset-6 bg-gradient-to-br from-brand-from/15 via-brand-via/10 to-brand-to/15 rounded-[2rem] blur-2xl opacity-80 pointer-events-none' />
|
||||||
|
|
||||||
{/* 左上 / 右下脉动光晕 */}
|
{/* 左上 / 右下脉动光晕 */}
|
||||||
{withCornerHalos && (
|
{withCornerHalos && (
|
||||||
<>
|
<>
|
||||||
<div className='absolute -top-20 -left-20 w-44 h-44 bg-brand-from/25 dark:bg-brand-from/20 rounded-full blur-3xl pointer-events-none login-halo-pulse' />
|
<div className='login-card-halo absolute -top-20 -left-20 w-44 h-44 bg-brand-from/25 dark:bg-brand-from/20 rounded-full blur-3xl pointer-events-none login-halo-pulse' />
|
||||||
<div className='absolute -bottom-20 -right-20 w-44 h-44 bg-brand-to/25 dark:bg-brand-to/15 rounded-full blur-3xl pointer-events-none login-halo-pulse-delayed' />
|
<div className='login-card-halo absolute -bottom-20 -right-20 w-44 h-44 bg-brand-to/25 dark:bg-brand-to/15 rounded-full blur-3xl pointer-events-none login-halo-pulse-delayed' />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -71,6 +71,7 @@ import { Shield, Smartphone, QrCode } from 'lucide-react';
|
|||||||
import GlassCard from './GlassCard';
|
import GlassCard from './GlassCard';
|
||||||
import AuthCardHeader from './AuthCardHeader';
|
import AuthCardHeader from './AuthCardHeader';
|
||||||
import AuthLoginTabs from './AuthLoginTabs';
|
import AuthLoginTabs from './AuthLoginTabs';
|
||||||
|
import AuthDivider from './AuthDivider';
|
||||||
import AgreementModal from '../common/DocumentRenderer/AgreementModal';
|
import AgreementModal from '../common/DocumentRenderer/AgreementModal';
|
||||||
import {
|
import {
|
||||||
isMiniProgramWebView,
|
isMiniProgramWebView,
|
||||||
@@ -93,38 +94,26 @@ const IS_MOBILE_DEVICE =
|
|||||||
);
|
);
|
||||||
|
|
||||||
// 提取OAuthButton到组件外部,避免每次渲染都重建
|
// 提取OAuthButton到组件外部,避免每次渲染都重建
|
||||||
|
// 第三方登录按钮:统一为 36px 描边按钮,无位移 / 扫光动效(尺寸见 prototype.css .auth-login-page)
|
||||||
const OAuthButton = React.memo(
|
const OAuthButton = React.memo(
|
||||||
({ icon, children, onClick, loading, disabled, iconColor, t }) => (
|
({ icon, children, onClick, loading, disabled, iconColor }) => (
|
||||||
<button
|
<Button
|
||||||
|
block
|
||||||
|
className='auth-oauth-button'
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
disabled={loading || disabled}
|
loading={loading}
|
||||||
className={`
|
disabled={disabled}
|
||||||
group relative w-full h-10 flex items-center justify-center gap-2
|
icon={
|
||||||
bg-white/80 dark:bg-white/[0.08] backdrop-blur-sm
|
<span
|
||||||
border border-gray-200/80 dark:border-white/[0.12]
|
className='auth-oauth-icon'
|
||||||
rounded-xl shadow-sm
|
style={iconColor ? { color: iconColor } : undefined}
|
||||||
hover:bg-white dark:hover:bg-white/[0.12]
|
>
|
||||||
hover:shadow-md hover:shadow-gray-200/50 dark:hover:shadow-black/30
|
{icon}
|
||||||
hover:-translate-y-0.5 hover:border-gray-300 dark:hover:border-white/20
|
</span>
|
||||||
active:translate-y-0
|
}
|
||||||
transition-all duration-200 ease-out
|
|
||||||
disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:translate-y-0
|
|
||||||
overflow-hidden
|
|
||||||
`}
|
|
||||||
>
|
>
|
||||||
{/* 悬停光效 */}
|
{children}
|
||||||
<div className='absolute inset-0 bg-gradient-to-r from-transparent via-white/30 dark:via-white/10 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-500' />
|
</Button>
|
||||||
|
|
||||||
<span
|
|
||||||
style={iconColor ? { color: iconColor } : undefined}
|
|
||||||
className='relative z-10 flex items-center justify-center w-4 h-4 text-gray-700 dark:text-gray-200'
|
|
||||||
>
|
|
||||||
{icon}
|
|
||||||
</span>
|
|
||||||
<span className='relative z-10 font-medium text-sm text-gray-700 dark:text-gray-200'>
|
|
||||||
{loading ? (t ? t('加载中...') : '加载中...') : children}
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -177,6 +166,16 @@ const LoginForm = () => {
|
|||||||
const [githubButtonText, setGithubButtonText] = useState('');
|
const [githubButtonText, setGithubButtonText] = useState('');
|
||||||
const [githubButtonDisabled, setGithubButtonDisabled] = useState(false);
|
const [githubButtonDisabled, setGithubButtonDisabled] = useState(false);
|
||||||
const githubTimeoutRef = useRef(null);
|
const githubTimeoutRef = useRef(null);
|
||||||
|
// 微信验证码弹窗表单:确定前先做前端必填校验,通过后再走原提交逻辑
|
||||||
|
const wechatFormApi = useRef(null);
|
||||||
|
const submitWeChatCodeWithValidation = async () => {
|
||||||
|
try {
|
||||||
|
await wechatFormApi.current?.validate();
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await onSubmitWeChatVerificationCode();
|
||||||
|
};
|
||||||
|
|
||||||
const logo = getLogo();
|
const logo = getLogo();
|
||||||
const systemName = getSystemName();
|
const systemName = getSystemName();
|
||||||
@@ -286,6 +285,9 @@ const LoginForm = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function handleSubmit(e) {
|
async function handleSubmit(e) {
|
||||||
|
// Semi Form 里的按钮同时具备原生 submit 行为;先阻止浏览器
|
||||||
|
// 刷新/跳转,确保登录请求和 finishLogin 流程完整执行。
|
||||||
|
e?.preventDefault?.();
|
||||||
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
|
if ((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms) {
|
||||||
showInfo(t('请先阅读并同意用户协议和隐私政策'));
|
showInfo(t('请先阅读并同意用户协议和隐私政策'));
|
||||||
return;
|
return;
|
||||||
@@ -626,7 +628,7 @@ const LoginForm = () => {
|
|||||||
subtitle={t('请选择登录方式')}
|
subtitle={t('请选择登录方式')}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className='space-y-2'>
|
<div className='auth-option-list'>
|
||||||
{status.wechat_login && (
|
{status.wechat_login && (
|
||||||
<OAuthButton
|
<OAuthButton
|
||||||
icon={<Icon svg={<WeChatIcon />} />}
|
icon={<Icon svg={<WeChatIcon />} />}
|
||||||
@@ -727,39 +729,22 @@ const LoginForm = () => {
|
|||||||
</OAuthButton>
|
</OAuthButton>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* 分隔线 */}
|
<AuthDivider>{t('或')}</AuthDivider>
|
||||||
<div className='relative py-3'>
|
|
||||||
<div className='absolute inset-0 flex items-center'>
|
|
||||||
<div className='w-full border-t border-gray-200/80 dark:border-white/[0.08]'></div>
|
|
||||||
</div>
|
|
||||||
<div className='relative flex justify-center'>
|
|
||||||
<span className='px-3 text-xs text-gray-400 dark:text-gray-500 bg-white/60 dark:bg-neutral-900/70 backdrop-blur-md rounded-full'>
|
|
||||||
{t('或')}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 邮箱登录按钮 */}
|
{/* 邮箱登录按钮 */}
|
||||||
<button
|
<Button
|
||||||
|
theme='solid'
|
||||||
|
block
|
||||||
|
className='auth-login-submit'
|
||||||
|
icon={<IconMail />}
|
||||||
onClick={handleEmailLoginClick}
|
onClick={handleEmailLoginClick}
|
||||||
className='app-action-button group relative w-full h-10 flex items-center justify-center gap-2 bg-gradient-to-r from-brand-from to-brand-to hover:from-brand-from hover:to-brand-to text-white rounded-xl shadow-md shadow-brand/25 dark:shadow-brand/15 hover:shadow-lg hover:shadow-brand/30 hover:-translate-y-0.5 active:translate-y-0 transition-all duration-200 overflow-hidden'
|
|
||||||
>
|
>
|
||||||
{/* 闪光效果 */}
|
{t('邮箱/用户名 登录')}
|
||||||
<div className='absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-500' />
|
</Button>
|
||||||
|
|
||||||
<IconMail className='relative z-10' />
|
|
||||||
<span className='relative z-10 font-medium text-sm'>
|
|
||||||
{t('邮箱/用户名 登录')}
|
|
||||||
</span>
|
|
||||||
<ActionArrowRight
|
|
||||||
size={16}
|
|
||||||
className='relative z-10 group-hover:translate-x-1 transition-transform'
|
|
||||||
/>
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{(hasUserAgreement || hasPrivacyPolicy) && (
|
{(hasUserAgreement || hasPrivacyPolicy) && (
|
||||||
<div className='mt-4 flex justify-center'>
|
<div className='auth-login-agreement flex justify-center'>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={agreedToTerms}
|
checked={agreedToTerms}
|
||||||
onChange={(e) => setAgreedToTerms(e.target.checked)}
|
onChange={(e) => setAgreedToTerms(e.target.checked)}
|
||||||
@@ -798,7 +783,7 @@ const LoginForm = () => {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{!status.self_use_mode_enabled && (
|
{!status.self_use_mode_enabled && (
|
||||||
<div className='mt-4 text-center'>
|
<div className='auth-login-register text-center'>
|
||||||
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
|
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
|
||||||
{t('没有账户?')}{' '}
|
{t('没有账户?')}{' '}
|
||||||
<Link
|
<Link
|
||||||
@@ -812,7 +797,7 @@ const LoginForm = () => {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* 安全提示 */}
|
{/* 安全提示 */}
|
||||||
<div className='mt-4 flex items-center justify-center gap-1.5 text-[10px] text-gray-400 dark:text-gray-500'>
|
<div className='auth-login-security'>
|
||||||
<Shield size={12} />
|
<Shield size={12} />
|
||||||
<span>{t('安全登录')}</span>
|
<span>{t('安全登录')}</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -844,30 +829,17 @@ const LoginForm = () => {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{status.passkey_login && passkeySupported && (
|
{status.passkey_login && passkeySupported && (
|
||||||
<div className='relative py-2'>
|
<AuthDivider>{t('或')}</AuthDivider>
|
||||||
<div className='absolute inset-0 flex items-center'>
|
|
||||||
<div className='w-full border-t border-gray-200/80 dark:border-white/[0.08]'></div>
|
|
||||||
</div>
|
|
||||||
<div className='relative flex justify-center'>
|
|
||||||
<span className='px-3 text-xs text-gray-400 dark:text-gray-500 bg-white/60 dark:bg-neutral-900/70 backdrop-blur-md rounded-full'>
|
|
||||||
{t('或')}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Form className='auth-login-form' onSubmit={handleSubmit}>
|
<Form className='auth-login-form' onSubmit={handleSubmit}>
|
||||||
<Form.Input
|
<Form.Input
|
||||||
field='username'
|
field='username'
|
||||||
className='auth-login-required-field'
|
className='auth-login-required-field'
|
||||||
rules={[{ required: true, message: t('请输入用户名或邮箱') }]}
|
rules={[{ required: true, message: t('请输入用户名/邮箱') }]}
|
||||||
required
|
required
|
||||||
aria-required='true'
|
aria-required='true'
|
||||||
label={
|
label={t('用户名/邮箱')}
|
||||||
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
|
|
||||||
{t('用户名/邮箱')}
|
|
||||||
</span>
|
|
||||||
}
|
|
||||||
placeholder={t('请输入用户名或邮箱')}
|
placeholder={t('请输入用户名或邮箱')}
|
||||||
name='username'
|
name='username'
|
||||||
size='default'
|
size='default'
|
||||||
@@ -883,11 +855,7 @@ const LoginForm = () => {
|
|||||||
rules={[{ required: true, message: t('请输入密码') }]}
|
rules={[{ required: true, message: t('请输入密码') }]}
|
||||||
required
|
required
|
||||||
aria-required='true'
|
aria-required='true'
|
||||||
label={
|
label={t('密码')}
|
||||||
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
|
|
||||||
{t('密码')}
|
|
||||||
</span>
|
|
||||||
}
|
|
||||||
placeholder={t('请输入密码')}
|
placeholder={t('请输入密码')}
|
||||||
name='password'
|
name='password'
|
||||||
mode='password'
|
mode='password'
|
||||||
@@ -898,7 +866,7 @@ const LoginForm = () => {
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
{(hasUserAgreement || hasPrivacyPolicy) && (
|
{(hasUserAgreement || hasPrivacyPolicy) && (
|
||||||
<div className='flex items-center'>
|
<div className='auth-login-agree-row flex items-center'>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={agreedToTerms}
|
checked={agreedToTerms}
|
||||||
onChange={(e) => setAgreedToTerms(e.target.checked)}
|
onChange={(e) => setAgreedToTerms(e.target.checked)}
|
||||||
@@ -969,24 +937,15 @@ const LoginForm = () => {
|
|||||||
status.wechat_open_oauth ||
|
status.wechat_open_oauth ||
|
||||||
status.linuxdo_oauth ||
|
status.linuxdo_oauth ||
|
||||||
status.telegram_oauth) && (
|
status.telegram_oauth) && (
|
||||||
<div className='mt-1'>
|
<div>
|
||||||
<div className='relative py-2'>
|
<AuthDivider>{t('或')}</AuthDivider>
|
||||||
<div className='absolute inset-0 flex items-center'>
|
<Button
|
||||||
<div className='w-full border-t border-gray-200/80 dark:border-white/[0.08]'></div>
|
block
|
||||||
</div>
|
className='auth-oauth-button'
|
||||||
<div className='relative flex justify-center'>
|
|
||||||
<span className='px-3 text-xs text-gray-400 dark:text-gray-500 bg-white/60 dark:bg-neutral-900/70 backdrop-blur-md rounded-full'>
|
|
||||||
{t('或')}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={handleOtherLoginOptionsClick}
|
onClick={handleOtherLoginOptionsClick}
|
||||||
className='w-full h-9 flex items-center justify-center gap-2 text-sm text-gray-600 dark:text-gray-300 border border-gray-200/80 dark:border-white/[0.12] rounded-lg hover:bg-gray-50 dark:hover:bg-white/[0.06] hover:border-gray-300 dark:hover:border-white/20 transition-all'
|
|
||||||
>
|
>
|
||||||
{t('其他登录选项')}
|
{t('其他登录选项')}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -1005,7 +964,7 @@ const LoginForm = () => {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* 安全提示 */}
|
{/* 安全提示 */}
|
||||||
<div className='mt-3 flex items-center justify-center gap-1.5 text-[10px] text-gray-400 dark:text-gray-500'>
|
<div className='auth-login-security'>
|
||||||
<Shield size={12} />
|
<Shield size={12} />
|
||||||
<span>{t('安全登录')}</span>
|
<span>{t('安全登录')}</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -1030,14 +989,14 @@ const LoginForm = () => {
|
|||||||
}
|
}
|
||||||
visible={showWeChatLoginModal}
|
visible={showWeChatLoginModal}
|
||||||
maskClosable={true}
|
maskClosable={true}
|
||||||
onOk={onSubmitWeChatVerificationCode}
|
onOk={submitWeChatCodeWithValidation}
|
||||||
onCancel={() => setShowWeChatLoginModal(false)}
|
onCancel={() => setShowWeChatLoginModal(false)}
|
||||||
okText={t('登录')}
|
okText={t('登录')}
|
||||||
centered={true}
|
centered={true}
|
||||||
okButtonProps={{
|
okButtonProps={{
|
||||||
loading: wechatCodeSubmitLoading,
|
loading: wechatCodeSubmitLoading,
|
||||||
}}
|
}}
|
||||||
className='wechat-login-modal'
|
className='wechat-login-modal auth-login-modal'
|
||||||
>
|
>
|
||||||
{/* 移动端提示 */}
|
{/* 移动端提示 */}
|
||||||
{isMobileView && !isInWeChat && (
|
{isMobileView && !isInWeChat && (
|
||||||
@@ -1091,16 +1050,16 @@ const LoginForm = () => {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Form>
|
<Form getFormApi={(api) => (wechatFormApi.current = api)}>
|
||||||
<Form.Input
|
<Form.Input
|
||||||
field='wechat_verification_code'
|
field='wechat_verification_code'
|
||||||
placeholder={t('请输入验证码')}
|
placeholder={t('请输入验证码')}
|
||||||
label={t('验证码')}
|
label={t('验证码')}
|
||||||
|
rules={[{ required: true, message: t('请输入验证码') }]}
|
||||||
value={inputs.wechat_verification_code}
|
value={inputs.wechat_verification_code}
|
||||||
onChange={(value) =>
|
onChange={(value) =>
|
||||||
handleChange('wechat_verification_code', value)
|
handleChange('wechat_verification_code', value)
|
||||||
}
|
}
|
||||||
className='!rounded-xl'
|
|
||||||
/>
|
/>
|
||||||
</Form>
|
</Form>
|
||||||
</Modal>
|
</Modal>
|
||||||
@@ -1189,11 +1148,11 @@ const LoginForm = () => {
|
|||||||
<Modal
|
<Modal
|
||||||
title={
|
title={
|
||||||
<div className='flex items-center gap-3'>
|
<div className='flex items-center gap-3'>
|
||||||
<div className='w-10 h-10 rounded-xl bg-gradient-to-br from-green-400 to-emerald-500 flex items-center justify-center shadow-lg shadow-green-500/30'>
|
<div className='auth-modal-title-icon'>
|
||||||
<Shield size={20} className='text-white' />
|
<Shield size={18} />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div className='font-bold'>{t('两步验证')}</div>
|
<div className='font-semibold'>{t('两步验证')}</div>
|
||||||
<div className='text-xs text-gray-500 dark:text-gray-400 font-normal'>
|
<div className='text-xs text-gray-500 dark:text-gray-400 font-normal'>
|
||||||
{t('请输入验证码完成登录')}
|
{t('请输入验证码完成登录')}
|
||||||
</div>
|
</div>
|
||||||
@@ -1205,6 +1164,7 @@ const LoginForm = () => {
|
|||||||
footer={null}
|
footer={null}
|
||||||
width={450}
|
width={450}
|
||||||
centered
|
centered
|
||||||
|
className='auth-login-modal'
|
||||||
>
|
>
|
||||||
<TwoFAVerification
|
<TwoFAVerification
|
||||||
onSuccess={handle2FASuccess}
|
onSuccess={handle2FASuccess}
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ const OrgCredentialResult = ({ creds, onLogin }) => {
|
|||||||
|
|
||||||
const isPending = creds.status === 'pending';
|
const isPending = creds.status === 'pending';
|
||||||
|
|
||||||
|
// 走公共 copy:HTTP 部署下 navigator.clipboard 为 undefined,直接调用会同步抛错、点了无反应
|
||||||
const copy = async (val) => {
|
const copy = async (val) => {
|
||||||
if (await copyText(val)) {
|
if (await copyText(val)) {
|
||||||
Toast.success(t('已复制到剪贴板'));
|
Toast.success(t('已复制到剪贴板'));
|
||||||
|
|||||||
@@ -27,11 +27,14 @@ import {
|
|||||||
getSystemName,
|
getSystemName,
|
||||||
} from '../../helpers';
|
} from '../../helpers';
|
||||||
import { useSearchParams, Link } from 'react-router-dom';
|
import { useSearchParams, Link } from 'react-router-dom';
|
||||||
import { Button, Card, Form, Typography, Banner } from '@/components/ui';
|
import { Button, Form, Typography, Banner } from '@/components/ui';
|
||||||
import { IconMail, IconLock, IconCopy } from '@/components/ui/icons';
|
import { IconMail, IconLock, IconCopy } from '@/components/ui/icons';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import AuthBackground from '../common/AuthBackground';
|
||||||
|
import GlassCard from './GlassCard';
|
||||||
|
import AuthCardHeader from './AuthCardHeader';
|
||||||
|
|
||||||
const { Text, Title } = Typography;
|
const { Text } = Typography;
|
||||||
|
|
||||||
const PasswordResetConfirm = () => {
|
const PasswordResetConfirm = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -95,11 +98,11 @@ const PasswordResetConfirm = () => {
|
|||||||
if (success) {
|
if (success) {
|
||||||
let password = res.data.data;
|
let password = res.data.data;
|
||||||
setNewPassword(password);
|
setNewPassword(password);
|
||||||
|
// 复制发生在异步请求之后,已脱离用户点击手势,降级复制可能失败;失败时只展示密码
|
||||||
if (await copy(password)) {
|
if (await copy(password)) {
|
||||||
showNotice(`${t('密码已重置并已复制到剪贴板:')} ${password}`);
|
showNotice(`${t('密码已重置并已复制到剪贴板:')} ${password}`);
|
||||||
} else {
|
} else {
|
||||||
showNotice(t('密码已重置'));
|
showNotice(`${t('密码已重置')}:${password}`);
|
||||||
showError(t('复制失败,请手动复制'));
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
showError(message);
|
showError(message);
|
||||||
@@ -108,121 +111,100 @@ const PasswordResetConfirm = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='relative overflow-hidden bg-gray-100 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8'>
|
<div
|
||||||
{/* 背景模糊晕染球 */}
|
className='auth-login-page relative overflow-hidden flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8'
|
||||||
<div
|
// 与登录页一致:抵扣 PageLayout 跑马灯占位高度,避免幽灵滚动
|
||||||
className='blur-ball blur-ball-indigo'
|
style={{ minHeight: 'calc(100vh - var(--content-top-offset, 0px))' }}
|
||||||
style={{ top: '-80px', right: '-80px', transform: 'none' }}
|
>
|
||||||
/>
|
<AuthBackground />
|
||||||
<div
|
<div className='w-full max-w-md z-10 flex flex-col items-center'>
|
||||||
className='blur-ball blur-ball-teal'
|
<GlassCard>
|
||||||
style={{ top: '50%', left: '-120px' }}
|
<AuthCardHeader
|
||||||
/>
|
logo={logo}
|
||||||
<div className='w-full max-w-sm mt-[60px]'>
|
title={systemName}
|
||||||
<div className='flex flex-col items-center'>
|
subtitle={t('密码重置确认')}
|
||||||
<div className='w-full max-w-md'>
|
/>
|
||||||
<div className='flex items-center justify-center mb-6 gap-2'>
|
|
||||||
<img
|
{!isValidResetLink && (
|
||||||
src={logo}
|
<Banner
|
||||||
alt={t('网站标志')}
|
type='danger'
|
||||||
className='h-10 rounded-full'
|
description={t('无效的重置链接,请重新发起密码重置请求')}
|
||||||
|
className='auth-login-banner'
|
||||||
|
closeIcon={null}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Form
|
||||||
|
className='auth-login-form'
|
||||||
|
getFormApi={(api) => setFormApi(api)}
|
||||||
|
initValues={{
|
||||||
|
email: email || '',
|
||||||
|
newPassword: newPassword || '',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Form.Input
|
||||||
|
field='email'
|
||||||
|
label={t('邮箱')}
|
||||||
|
name='email'
|
||||||
|
disabled={true}
|
||||||
|
prefix={<IconMail />}
|
||||||
|
placeholder={email ? '' : t('等待获取邮箱信息...')}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{newPassword && (
|
||||||
|
<Form.Input
|
||||||
|
field='newPassword'
|
||||||
|
label={t('新密码')}
|
||||||
|
name='newPassword'
|
||||||
|
disabled={true}
|
||||||
|
prefix={<IconLock />}
|
||||||
|
suffix={
|
||||||
|
<Button
|
||||||
|
icon={<IconCopy />}
|
||||||
|
type='tertiary'
|
||||||
|
theme='borderless'
|
||||||
|
size='small'
|
||||||
|
onClick={async () => {
|
||||||
|
if (await copy(newPassword)) {
|
||||||
|
showNotice(
|
||||||
|
`${t('密码已复制到剪贴板:')} ${newPassword}`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
showError(t('复制失败,请手动复制'));
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t('复制')}
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
<Title heading={3} className='!text-gray-800'>
|
)}
|
||||||
{systemName}
|
|
||||||
</Title>
|
<div className='auth-login-actions'>
|
||||||
|
<Button
|
||||||
|
theme='solid'
|
||||||
|
block
|
||||||
|
className='auth-login-submit'
|
||||||
|
htmlType='submit'
|
||||||
|
onClick={handleSubmit}
|
||||||
|
loading={loading}
|
||||||
|
disabled={disableButton || newPassword || !isValidResetLink}
|
||||||
|
>
|
||||||
|
{newPassword ? t('密码重置完成') : t('确认重置密码')}
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
</Form>
|
||||||
|
|
||||||
<Card className='border-0 !rounded-2xl overflow-hidden'>
|
<div className='auth-login-register text-center'>
|
||||||
<div className='flex justify-center pt-6 pb-2'>
|
<Text className='text-xs'>
|
||||||
<Title heading={3} className='text-gray-800 dark:text-gray-200'>
|
<Link
|
||||||
{t('密码重置确认')}
|
to='/login'
|
||||||
</Title>
|
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from font-semibold transition-colors'
|
||||||
</div>
|
>
|
||||||
<div className='px-2 py-8'>
|
{t('返回登录')}
|
||||||
{!isValidResetLink && (
|
</Link>
|
||||||
<Banner
|
</Text>
|
||||||
type='danger'
|
|
||||||
description={t('无效的重置链接,请重新发起密码重置请求')}
|
|
||||||
className='mb-4 !rounded-lg'
|
|
||||||
closeIcon={null}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
<Form
|
|
||||||
getFormApi={(api) => setFormApi(api)}
|
|
||||||
initValues={{
|
|
||||||
email: email || '',
|
|
||||||
newPassword: newPassword || '',
|
|
||||||
}}
|
|
||||||
className='space-y-4'
|
|
||||||
>
|
|
||||||
<Form.Input
|
|
||||||
field='email'
|
|
||||||
label={t('邮箱')}
|
|
||||||
name='email'
|
|
||||||
disabled={true}
|
|
||||||
prefix={<IconMail />}
|
|
||||||
placeholder={email ? '' : t('等待获取邮箱信息...')}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{newPassword && (
|
|
||||||
<Form.Input
|
|
||||||
field='newPassword'
|
|
||||||
label={t('新密码')}
|
|
||||||
name='newPassword'
|
|
||||||
disabled={true}
|
|
||||||
prefix={<IconLock />}
|
|
||||||
suffix={
|
|
||||||
<Button
|
|
||||||
icon={<IconCopy />}
|
|
||||||
type='tertiary'
|
|
||||||
theme='borderless'
|
|
||||||
onClick={async () => {
|
|
||||||
if (await copy(newPassword)) {
|
|
||||||
showNotice(
|
|
||||||
`${t('密码已复制到剪贴板:')} ${newPassword}`,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
showError(t('复制失败,请手动复制'));
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{t('复制')}
|
|
||||||
</Button>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className='space-y-2 pt-2'>
|
|
||||||
<Button
|
|
||||||
theme='solid'
|
|
||||||
className='w-full !rounded-full'
|
|
||||||
type='primary'
|
|
||||||
htmlType='submit'
|
|
||||||
onClick={handleSubmit}
|
|
||||||
loading={loading}
|
|
||||||
disabled={
|
|
||||||
disableButton || newPassword || !isValidResetLink
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{newPassword ? t('密码重置完成') : t('确认重置密码')}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</Form>
|
|
||||||
|
|
||||||
<div className='mt-6 text-center text-sm'>
|
|
||||||
<Text>
|
|
||||||
<Link
|
|
||||||
to='/login'
|
|
||||||
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from font-medium transition-colors'
|
|
||||||
>
|
|
||||||
{t('返回登录')}
|
|
||||||
</Link>
|
|
||||||
</Text>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</GlassCard>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -27,12 +27,15 @@ import {
|
|||||||
getSystemName,
|
getSystemName,
|
||||||
} from '../../helpers';
|
} from '../../helpers';
|
||||||
import Turnstile from 'react-turnstile';
|
import Turnstile from 'react-turnstile';
|
||||||
import { Button, Card, Form, Typography } from '@/components/ui';
|
import { Button, Form, Typography } from '@/components/ui';
|
||||||
import { IconMail } from '@/components/ui/icons';
|
import { IconMail } from '@/components/ui/icons';
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import AuthBackground from '../common/AuthBackground';
|
||||||
|
import GlassCard from './GlassCard';
|
||||||
|
import AuthCardHeader from './AuthCardHeader';
|
||||||
|
|
||||||
const { Text, Title } = Typography;
|
const { Text } = Typography;
|
||||||
|
|
||||||
const PasswordResetForm = () => {
|
const PasswordResetForm = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -104,91 +107,78 @@ const PasswordResetForm = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className='relative overflow-hidden bg-gray-100 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8'>
|
<div
|
||||||
{/* 背景模糊晕染球 */}
|
className='auth-login-page relative overflow-hidden flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8'
|
||||||
<div
|
// 与登录页一致:抵扣 PageLayout 跑马灯占位高度,避免幽灵滚动
|
||||||
className='blur-ball blur-ball-indigo'
|
style={{ minHeight: 'calc(100vh - var(--content-top-offset, 0px))' }}
|
||||||
style={{ top: '-80px', right: '-80px', transform: 'none' }}
|
>
|
||||||
/>
|
<AuthBackground />
|
||||||
<div
|
<div className='w-full max-w-md z-10 flex flex-col items-center'>
|
||||||
className='blur-ball blur-ball-teal'
|
<GlassCard>
|
||||||
style={{ top: '50%', left: '-120px' }}
|
<AuthCardHeader
|
||||||
/>
|
logo={logo}
|
||||||
<div className='w-full max-w-sm mt-[60px]'>
|
title={systemName}
|
||||||
<div className='flex flex-col items-center'>
|
subtitle={t('密码重置')}
|
||||||
<div className='w-full max-w-md'>
|
/>
|
||||||
<div className='flex items-center justify-center mb-6 gap-2'>
|
|
||||||
<img
|
{/* 前端校验(必填 + 邮箱格式)通过后才调用原 handleSubmit */}
|
||||||
src={logo}
|
<Form className='auth-login-form' onSubmit={() => handleSubmit()}>
|
||||||
alt={t('网站标志')}
|
<Form.Input
|
||||||
className='h-10 rounded-full'
|
field='email'
|
||||||
/>
|
label={t('邮箱')}
|
||||||
<Title heading={3} className='!text-gray-800'>
|
rules={[
|
||||||
{systemName}
|
{ required: true, message: t('请输入邮箱') },
|
||||||
</Title>
|
{
|
||||||
|
type: 'email',
|
||||||
|
transform: (v) => v?.trim(),
|
||||||
|
message: t('邮箱格式不正确'),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
trigger='blur'
|
||||||
|
placeholder={t('请输入您的邮箱地址')}
|
||||||
|
name='email'
|
||||||
|
value={email}
|
||||||
|
onChange={handleChange}
|
||||||
|
prefix={<IconMail />}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className='auth-login-actions'>
|
||||||
|
<Button
|
||||||
|
theme='solid'
|
||||||
|
block
|
||||||
|
className='auth-login-submit'
|
||||||
|
htmlType='submit'
|
||||||
|
loading={loading}
|
||||||
|
disabled={disableButton}
|
||||||
|
>
|
||||||
|
{disableButton ? `${t('重试')} (${countdown})` : t('提交')}
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
</Form>
|
||||||
|
|
||||||
<Card className='border-0 !rounded-2xl overflow-hidden'>
|
<div className='auth-login-register text-center'>
|
||||||
<div className='flex justify-center pt-6 pb-2'>
|
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
|
||||||
<Title heading={3} className='text-gray-800 dark:text-gray-200'>
|
{t('想起来了?')}{' '}
|
||||||
{t('密码重置')}
|
<Link
|
||||||
</Title>
|
to='/login'
|
||||||
</div>
|
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from font-semibold transition-colors'
|
||||||
<div className='px-2 py-8'>
|
>
|
||||||
<Form className='space-y-3'>
|
{t('登录')}
|
||||||
<Form.Input
|
</Link>
|
||||||
field='email'
|
</Text>
|
||||||
label={t('邮箱')}
|
|
||||||
placeholder={t('请输入您的邮箱地址')}
|
|
||||||
name='email'
|
|
||||||
value={email}
|
|
||||||
onChange={handleChange}
|
|
||||||
prefix={<IconMail />}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className='space-y-2 pt-2'>
|
|
||||||
<Button
|
|
||||||
theme='solid'
|
|
||||||
className='w-full !rounded-full'
|
|
||||||
type='primary'
|
|
||||||
htmlType='submit'
|
|
||||||
onClick={handleSubmit}
|
|
||||||
loading={loading}
|
|
||||||
disabled={disableButton}
|
|
||||||
>
|
|
||||||
{disableButton
|
|
||||||
? `${t('重试')} (${countdown})`
|
|
||||||
: t('提交')}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</Form>
|
|
||||||
|
|
||||||
<div className='mt-6 text-center text-sm'>
|
|
||||||
<Text>
|
|
||||||
{t('想起来了?')}{' '}
|
|
||||||
<Link
|
|
||||||
to='/login'
|
|
||||||
className='!text-brand-deep dark:!text-brand-from hover:!text-brand dark:hover:!text-brand-from font-medium transition-colors'
|
|
||||||
>
|
|
||||||
{t('登录')}
|
|
||||||
</Link>
|
|
||||||
</Text>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{turnstileEnabled && (
|
|
||||||
<div className='flex justify-center mt-6'>
|
|
||||||
<Turnstile
|
|
||||||
sitekey={turnstileSiteKey}
|
|
||||||
onVerify={(token) => {
|
|
||||||
setTurnstileToken(token);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</GlassCard>
|
||||||
|
|
||||||
|
{turnstileEnabled && (
|
||||||
|
<div className='flex justify-center mt-6'>
|
||||||
|
<Turnstile
|
||||||
|
sitekey={turnstileSiteKey}
|
||||||
|
onVerify={(token) => {
|
||||||
|
setTurnstileToken(token);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -65,6 +65,7 @@ import AuthBackground from '../common/AuthBackground';
|
|||||||
import GlassCard from './GlassCard';
|
import GlassCard from './GlassCard';
|
||||||
import AuthCardHeader from './AuthCardHeader';
|
import AuthCardHeader from './AuthCardHeader';
|
||||||
import AuthLoginTabs from './AuthLoginTabs';
|
import AuthLoginTabs from './AuthLoginTabs';
|
||||||
|
import AuthDivider from './AuthDivider';
|
||||||
import { Shield, Smartphone, QrCode } from 'lucide-react';
|
import { Shield, Smartphone, QrCode } from 'lucide-react';
|
||||||
import AgreementModal from '../common/DocumentRenderer/AgreementModal';
|
import AgreementModal from '../common/DocumentRenderer/AgreementModal';
|
||||||
import {
|
import {
|
||||||
@@ -143,6 +144,26 @@ const RegisterForm = () => {
|
|||||||
const [githubButtonDisabled, setGithubButtonDisabled] = useState(false);
|
const [githubButtonDisabled, setGithubButtonDisabled] = useState(false);
|
||||||
const [showWeChatOpenTipModal, setShowWeChatOpenTipModal] = useState(false);
|
const [showWeChatOpenTipModal, setShowWeChatOpenTipModal] = useState(false);
|
||||||
const githubTimeoutRef = useRef(null);
|
const githubTimeoutRef = useRef(null);
|
||||||
|
// 注册表单 / 微信验证码弹窗的表单实例:用于在原逻辑执行前做前端校验
|
||||||
|
const registerFormApi = useRef(null);
|
||||||
|
const wechatFormApi = useRef(null);
|
||||||
|
// 获取验证码前先校验邮箱必填与格式,通过后走原发送逻辑
|
||||||
|
const sendVerificationCodeWithValidation = async () => {
|
||||||
|
try {
|
||||||
|
await registerFormApi.current?.validate(['email']);
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await sendVerificationCode();
|
||||||
|
};
|
||||||
|
const submitWeChatCodeWithValidation = async () => {
|
||||||
|
try {
|
||||||
|
await wechatFormApi.current?.validate();
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await onSubmitWeChatVerificationCode();
|
||||||
|
};
|
||||||
|
|
||||||
const logo = getLogo();
|
const logo = getLogo();
|
||||||
const systemName = getSystemName();
|
const systemName = getSystemName();
|
||||||
@@ -459,7 +480,7 @@ const RegisterForm = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 注册按钮样式组件
|
// 第三方注册按钮:与登录页一致的 36px 描边按钮,无位移 / 扫光动效
|
||||||
const OAuthButton = ({
|
const OAuthButton = ({
|
||||||
icon,
|
icon,
|
||||||
children,
|
children,
|
||||||
@@ -468,36 +489,23 @@ const RegisterForm = () => {
|
|||||||
disabled,
|
disabled,
|
||||||
iconColor,
|
iconColor,
|
||||||
}) => (
|
}) => (
|
||||||
<button
|
<Button
|
||||||
|
block
|
||||||
|
className='auth-oauth-button'
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
disabled={loading || disabled}
|
loading={loading}
|
||||||
className={`
|
disabled={disabled}
|
||||||
group relative w-full h-10 flex items-center justify-center gap-2
|
icon={
|
||||||
bg-white/80 dark:bg-white/[0.08] backdrop-blur-sm
|
<span
|
||||||
border border-gray-200/80 dark:border-white/[0.12]
|
className='auth-oauth-icon'
|
||||||
rounded-xl shadow-sm
|
style={iconColor ? { color: iconColor } : undefined}
|
||||||
hover:bg-white dark:hover:bg-white/[0.12]
|
>
|
||||||
hover:shadow-md hover:shadow-gray-200/50 dark:hover:shadow-black/30
|
{icon}
|
||||||
hover:-translate-y-0.5 hover:border-gray-300 dark:hover:border-white/20
|
</span>
|
||||||
active:translate-y-0
|
}
|
||||||
transition-all duration-200 ease-out
|
|
||||||
disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:translate-y-0
|
|
||||||
overflow-hidden
|
|
||||||
`}
|
|
||||||
>
|
>
|
||||||
{/* 悬停光效 */}
|
{children}
|
||||||
<div className='absolute inset-0 bg-gradient-to-r from-transparent via-white/30 dark:via-white/10 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-500' />
|
</Button>
|
||||||
|
|
||||||
<span
|
|
||||||
style={iconColor ? { color: iconColor } : undefined}
|
|
||||||
className='relative z-10 flex items-center justify-center w-4 h-4 text-gray-700 dark:text-gray-200'
|
|
||||||
>
|
|
||||||
{icon}
|
|
||||||
</span>
|
|
||||||
<span className='relative z-10 font-medium text-sm text-gray-700 dark:text-gray-200'>
|
|
||||||
{loading ? t('加载中...') : children}
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const renderOAuthOptions = () => {
|
const renderOAuthOptions = () => {
|
||||||
@@ -509,7 +517,7 @@ const RegisterForm = () => {
|
|||||||
subtitle={t('创建您的账户')}
|
subtitle={t('创建您的账户')}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className='space-y-2'>
|
<div className='auth-option-list'>
|
||||||
{status.wechat_login && (
|
{status.wechat_login && (
|
||||||
<OAuthButton
|
<OAuthButton
|
||||||
icon={<Icon svg={<WeChatIcon />} />}
|
icon={<Icon svg={<WeChatIcon />} />}
|
||||||
@@ -591,40 +599,23 @@ const RegisterForm = () => {
|
|||||||
</Suspense>
|
</Suspense>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* 分隔线 */}
|
<AuthDivider>{t('或')}</AuthDivider>
|
||||||
<div className='relative py-3'>
|
|
||||||
<div className='absolute inset-0 flex items-center'>
|
|
||||||
<div className='w-full border-t border-gray-200/80 dark:border-white/[0.08]'></div>
|
|
||||||
</div>
|
|
||||||
<div className='relative flex justify-center'>
|
|
||||||
<span className='px-3 text-xs text-gray-400 dark:text-gray-500 bg-white/60 dark:bg-neutral-900/70 backdrop-blur-md rounded-full'>
|
|
||||||
{t('或')}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 用户名注册按钮 */}
|
{/* 用户名注册按钮 */}
|
||||||
<button
|
<Button
|
||||||
|
theme='solid'
|
||||||
|
block
|
||||||
|
className='auth-login-submit'
|
||||||
|
icon={<IconMail />}
|
||||||
onClick={handleEmailRegisterClick}
|
onClick={handleEmailRegisterClick}
|
||||||
disabled={emailRegisterLoading}
|
disabled={emailRegisterLoading}
|
||||||
className='app-action-button group relative w-full h-10 flex items-center justify-center gap-2 bg-gradient-to-r from-brand-from to-brand-to hover:from-brand-from hover:to-brand-to text-white rounded-xl shadow-md shadow-brand/25 dark:shadow-brand/15 hover:shadow-lg hover:shadow-brand/30 hover:-translate-y-0.5 active:translate-y-0 transition-all duration-200 overflow-hidden'
|
|
||||||
>
|
>
|
||||||
{/* 闪光效果 */}
|
{t('使用 用户名 注册')}
|
||||||
<div className='absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-500' />
|
</Button>
|
||||||
|
|
||||||
<IconMail className='relative z-10' />
|
|
||||||
<span className='relative z-10 font-medium text-sm'>
|
|
||||||
{t('使用 用户名 注册')}
|
|
||||||
</span>
|
|
||||||
<ActionArrowRight
|
|
||||||
size={16}
|
|
||||||
className='relative z-10 group-hover:translate-x-1 transition-transform'
|
|
||||||
/>
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{(hasUserAgreement || hasPrivacyPolicy) && (
|
{(hasUserAgreement || hasPrivacyPolicy) && (
|
||||||
<div className='mt-4 flex justify-center'>
|
<div className='auth-login-agreement flex justify-center'>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={agreedToTerms}
|
checked={agreedToTerms}
|
||||||
onChange={(e) => setAgreedToTerms(e.target.checked)}
|
onChange={(e) => setAgreedToTerms(e.target.checked)}
|
||||||
@@ -662,7 +653,7 @@ const RegisterForm = () => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className='mt-4 text-center'>
|
<div className='auth-login-register text-center'>
|
||||||
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
|
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
|
||||||
{t('已有账户?')}{' '}
|
{t('已有账户?')}{' '}
|
||||||
<Link
|
<Link
|
||||||
@@ -675,7 +666,7 @@ const RegisterForm = () => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 安全提示 */}
|
{/* 安全提示 */}
|
||||||
<div className='mt-4 flex items-center justify-center gap-1.5 text-[10px] text-gray-400 dark:text-gray-500'>
|
<div className='auth-login-security'>
|
||||||
<Shield size={12} />
|
<Shield size={12} />
|
||||||
<span>{t('安全注册')}</span>
|
<span>{t('安全注册')}</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -694,35 +685,35 @@ const RegisterForm = () => {
|
|||||||
logoWrapperClassName='mb-2'
|
logoWrapperClassName='mb-2'
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Form className='register-compact-form auth-glass-form'>
|
{/* 前端校验通过后才调用原 handleSubmit;其内协议 / 长度 / 一致性判断原样保留 */}
|
||||||
{/* 用户名输入框 —— 玻璃观感统一由 .auth-glass-form(GlassCard 内置样式)驱动 */}
|
<Form
|
||||||
|
className='auth-login-form'
|
||||||
|
getFormApi={(api) => (registerFormApi.current = api)}
|
||||||
|
onSubmit={() => handleSubmit()}
|
||||||
|
>
|
||||||
<Form.Input
|
<Form.Input
|
||||||
field='username'
|
field='username'
|
||||||
label={
|
label={t('用户名')}
|
||||||
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
|
rules={[{ required: true, message: t('请输入用户名') }]}
|
||||||
{t('用户名')}
|
|
||||||
</span>
|
|
||||||
}
|
|
||||||
placeholder={t('请输入用户名')}
|
placeholder={t('请输入用户名')}
|
||||||
name='username'
|
name='username'
|
||||||
size='large'
|
|
||||||
autoComplete='username'
|
autoComplete='username'
|
||||||
onChange={(value) => handleChange('username', value)}
|
onChange={(value) => handleChange('username', value)}
|
||||||
prefix={<IconUser size='small' />}
|
prefix={<IconUser size='small' />}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* 密码输入框 */}
|
{/* 密码输入框:长度 8-20 与占位提示、后端约束一致 */}
|
||||||
<Form.Input
|
<Form.Input
|
||||||
field='password'
|
field='password'
|
||||||
label={
|
label={t('密码')}
|
||||||
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
|
rules={[
|
||||||
{t('密码')}
|
{ required: true, message: t('请输入密码') },
|
||||||
</span>
|
{ min: 8, max: 20, message: t('密码长度需为 8-20 位') },
|
||||||
}
|
]}
|
||||||
|
trigger='blur'
|
||||||
placeholder={t('输入密码,最短 8 位,最长 20 位')}
|
placeholder={t('输入密码,最短 8 位,最长 20 位')}
|
||||||
name='password'
|
name='password'
|
||||||
mode='password'
|
mode='password'
|
||||||
size='large'
|
|
||||||
autoComplete='new-password'
|
autoComplete='new-password'
|
||||||
onChange={(value) => handleChange('password', value)}
|
onChange={(value) => handleChange('password', value)}
|
||||||
prefix={<IconLock size='small' />}
|
prefix={<IconLock size='small' />}
|
||||||
@@ -731,15 +722,17 @@ const RegisterForm = () => {
|
|||||||
{/* 确认密码输入框 */}
|
{/* 确认密码输入框 */}
|
||||||
<Form.Input
|
<Form.Input
|
||||||
field='password2'
|
field='password2'
|
||||||
label={
|
label={t('确认密码')}
|
||||||
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
|
required
|
||||||
{t('确认密码')}
|
validate={(value, values) => {
|
||||||
</span>
|
if (!value) return t('请输入确认密码');
|
||||||
}
|
if (value !== values.password) return t('两次输入的密码不一致');
|
||||||
|
return '';
|
||||||
|
}}
|
||||||
|
trigger='blur'
|
||||||
placeholder={t('确认密码')}
|
placeholder={t('确认密码')}
|
||||||
name='password2'
|
name='password2'
|
||||||
mode='password'
|
mode='password'
|
||||||
size='large'
|
|
||||||
autoComplete='new-password'
|
autoComplete='new-password'
|
||||||
onChange={(value) => handleChange('password2', value)}
|
onChange={(value) => handleChange('password2', value)}
|
||||||
prefix={<IconLock size='small' />}
|
prefix={<IconLock size='small' />}
|
||||||
@@ -749,22 +742,26 @@ const RegisterForm = () => {
|
|||||||
<>
|
<>
|
||||||
<Form.Input
|
<Form.Input
|
||||||
field='email'
|
field='email'
|
||||||
label={
|
label={t('邮箱')}
|
||||||
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
|
rules={[
|
||||||
{t('邮箱')}
|
{ required: true, message: t('请输入邮箱') },
|
||||||
</span>
|
{
|
||||||
}
|
type: 'email',
|
||||||
|
transform: (v) => v?.trim(),
|
||||||
|
message: t('邮箱格式不正确'),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
trigger='blur'
|
||||||
placeholder={t('输入邮箱地址')}
|
placeholder={t('输入邮箱地址')}
|
||||||
name='email'
|
name='email'
|
||||||
type='email'
|
type='email'
|
||||||
size='large'
|
|
||||||
autoComplete='email'
|
autoComplete='email'
|
||||||
onChange={(value) => handleChange('email', value)}
|
onChange={(value) => handleChange('email', value)}
|
||||||
prefix={<IconMail size='small' />}
|
prefix={<IconMail size='small' />}
|
||||||
suffix={
|
suffix={
|
||||||
<Button
|
<Button
|
||||||
size='small'
|
size='small'
|
||||||
onClick={sendVerificationCode}
|
onClick={sendVerificationCodeWithValidation}
|
||||||
loading={verificationCodeLoading}
|
loading={verificationCodeLoading}
|
||||||
disabled={disableButton || verificationCodeLoading}
|
disabled={disableButton || verificationCodeLoading}
|
||||||
className='!rounded-lg'
|
className='!rounded-lg'
|
||||||
@@ -777,14 +774,10 @@ const RegisterForm = () => {
|
|||||||
/>
|
/>
|
||||||
<Form.Input
|
<Form.Input
|
||||||
field='verification_code'
|
field='verification_code'
|
||||||
label={
|
label={t('验证码')}
|
||||||
<span className='text-xs font-medium text-gray-600 dark:text-gray-300'>
|
rules={[{ required: true, message: t('请输入验证码') }]}
|
||||||
{t('验证码')}
|
|
||||||
</span>
|
|
||||||
}
|
|
||||||
placeholder={t('输入验证码')}
|
placeholder={t('输入验证码')}
|
||||||
name='verification_code'
|
name='verification_code'
|
||||||
size='large'
|
|
||||||
onChange={(value) => handleChange('verification_code', value)}
|
onChange={(value) => handleChange('verification_code', value)}
|
||||||
prefix={<IconKey size='small' />}
|
prefix={<IconKey size='small' />}
|
||||||
/>
|
/>
|
||||||
@@ -792,7 +785,7 @@ const RegisterForm = () => {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{(hasUserAgreement || hasPrivacyPolicy) && (
|
{(hasUserAgreement || hasPrivacyPolicy) && (
|
||||||
<div className='flex items-center mt-3'>
|
<div className='auth-login-agree-row flex items-center'>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
checked={agreedToTerms}
|
checked={agreedToTerms}
|
||||||
onChange={(e) => setAgreedToTerms(e.target.checked)}
|
onChange={(e) => setAgreedToTerms(e.target.checked)}
|
||||||
@@ -827,34 +820,22 @@ const RegisterForm = () => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className='space-y-2 mt-3'>
|
<div className='auth-login-actions'>
|
||||||
{/* 注册按钮 */}
|
{/* 注册按钮:提交经表单校验后调用原 handleSubmit,禁用条件不变 */}
|
||||||
<button
|
<Button
|
||||||
type='submit'
|
theme='solid'
|
||||||
onClick={handleSubmit}
|
htmlType='submit'
|
||||||
|
block
|
||||||
|
className='auth-login-submit'
|
||||||
|
loading={registerLoading}
|
||||||
disabled={
|
disabled={
|
||||||
registerLoading ||
|
registerLoading ||
|
||||||
((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms)
|
((hasUserAgreement || hasPrivacyPolicy) && !agreedToTerms)
|
||||||
}
|
}
|
||||||
className='app-action-button group relative w-full h-10 flex items-center justify-center gap-2 bg-gradient-to-r from-brand-from to-brand-to hover:from-brand-from hover:to-brand-to disabled:from-gray-400 disabled:to-gray-500 text-white rounded-xl shadow-md shadow-brand/25 dark:shadow-brand/15 hover:shadow-lg hover:shadow-brand/30 hover:-translate-y-0.5 active:translate-y-0 transition-all duration-200 disabled:cursor-not-allowed disabled:hover:translate-y-0 overflow-hidden'
|
|
||||||
>
|
>
|
||||||
{/* 闪光效果 */}
|
<span className='font-semibold'>{t('注 册')}</span>
|
||||||
<div className='absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-500' />
|
<ActionArrowRight size={16} />
|
||||||
|
</Button>
|
||||||
{registerLoading ? (
|
|
||||||
<div className='w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin' />
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<span className='relative z-10 font-semibold'>
|
|
||||||
{t('注 册')}
|
|
||||||
</span>
|
|
||||||
<ActionArrowRight
|
|
||||||
size={16}
|
|
||||||
className='relative z-10 group-hover:translate-x-1 transition-transform'
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</Form>
|
</Form>
|
||||||
|
|
||||||
@@ -865,29 +846,20 @@ const RegisterForm = () => {
|
|||||||
status.wechat_open_oauth ||
|
status.wechat_open_oauth ||
|
||||||
status.linuxdo_oauth ||
|
status.linuxdo_oauth ||
|
||||||
status.telegram_oauth) && (
|
status.telegram_oauth) && (
|
||||||
<div className='mt-2'>
|
<div>
|
||||||
<div className='relative py-3'>
|
<AuthDivider>{t('或')}</AuthDivider>
|
||||||
<div className='absolute inset-0 flex items-center'>
|
<Button
|
||||||
<div className='w-full border-t border-gray-200/80 dark:border-white/[0.08]'></div>
|
block
|
||||||
</div>
|
className='auth-oauth-button'
|
||||||
<div className='relative flex justify-center'>
|
|
||||||
<span className='px-3 text-xs text-gray-400 dark:text-gray-500 bg-white/60 dark:bg-neutral-900/70 backdrop-blur-md rounded-full'>
|
|
||||||
{t('或')}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={handleOtherRegisterOptionsClick}
|
onClick={handleOtherRegisterOptionsClick}
|
||||||
disabled={otherRegisterOptionsLoading}
|
disabled={otherRegisterOptionsLoading}
|
||||||
className='w-full h-9 flex items-center justify-center gap-2 text-sm text-gray-600 dark:text-gray-300 border border-gray-200/80 dark:border-white/[0.12] rounded-lg hover:bg-gray-50 dark:hover:bg-white/[0.06] hover:border-gray-300 dark:hover:border-white/20 transition-all'
|
|
||||||
>
|
>
|
||||||
{t('其他注册选项')}
|
{t('其他注册选项')}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className='mt-4 text-center'>
|
<div className='auth-login-register text-center'>
|
||||||
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
|
<Text className='text-gray-500 dark:text-gray-400 text-xs'>
|
||||||
{t('已有账户?')}{' '}
|
{t('已有账户?')}{' '}
|
||||||
<Link
|
<Link
|
||||||
@@ -900,7 +872,7 @@ const RegisterForm = () => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 安全提示 */}
|
{/* 安全提示 */}
|
||||||
<div className='mt-4 flex items-center justify-center gap-1.5 text-[10px] text-gray-400 dark:text-gray-500'>
|
<div className='auth-login-security'>
|
||||||
<Shield size={12} />
|
<Shield size={12} />
|
||||||
<span>{t('安全注册')}</span>
|
<span>{t('安全注册')}</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -925,14 +897,14 @@ const RegisterForm = () => {
|
|||||||
}
|
}
|
||||||
visible={showWeChatLoginModal}
|
visible={showWeChatLoginModal}
|
||||||
maskClosable={true}
|
maskClosable={true}
|
||||||
onOk={onSubmitWeChatVerificationCode}
|
onOk={submitWeChatCodeWithValidation}
|
||||||
onCancel={() => setShowWeChatLoginModal(false)}
|
onCancel={() => setShowWeChatLoginModal(false)}
|
||||||
okText={t('登录')}
|
okText={t('登录')}
|
||||||
centered={true}
|
centered={true}
|
||||||
okButtonProps={{
|
okButtonProps={{
|
||||||
loading: wechatCodeSubmitLoading,
|
loading: wechatCodeSubmitLoading,
|
||||||
}}
|
}}
|
||||||
className='wechat-login-modal'
|
className='wechat-login-modal auth-login-modal'
|
||||||
>
|
>
|
||||||
{/* 移动端提示 */}
|
{/* 移动端提示 */}
|
||||||
{isMobileView && !isInWeChat && (
|
{isMobileView && !isInWeChat && (
|
||||||
@@ -986,16 +958,16 @@ const RegisterForm = () => {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Form>
|
<Form getFormApi={(api) => (wechatFormApi.current = api)}>
|
||||||
<Form.Input
|
<Form.Input
|
||||||
field='wechat_verification_code'
|
field='wechat_verification_code'
|
||||||
placeholder={t('请输入验证码')}
|
placeholder={t('请输入验证码')}
|
||||||
label={t('验证码')}
|
label={t('验证码')}
|
||||||
|
rules={[{ required: true, message: t('请输入验证码') }]}
|
||||||
value={inputs.wechat_verification_code}
|
value={inputs.wechat_verification_code}
|
||||||
onChange={(value) =>
|
onChange={(value) =>
|
||||||
handleChange('wechat_verification_code', value)
|
handleChange('wechat_verification_code', value)
|
||||||
}
|
}
|
||||||
className='!rounded-xl'
|
|
||||||
/>
|
/>
|
||||||
</Form>
|
</Form>
|
||||||
</Modal>
|
</Modal>
|
||||||
@@ -1089,7 +1061,7 @@ const RegisterForm = () => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className='relative overflow-hidden flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8'
|
className='auth-login-page relative overflow-hidden flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8'
|
||||||
// 抵扣 PageLayout 跑马灯占位高度,保证占位+容器恰为一屏,避免幽灵滚动
|
// 抵扣 PageLayout 跑马灯占位高度,保证占位+容器恰为一屏,避免幽灵滚动
|
||||||
style={{ minHeight: 'calc(100vh - var(--content-top-offset, 0px))' }}
|
style={{ minHeight: 'calc(100vh - var(--content-top-offset, 0px))' }}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -71,6 +71,21 @@ const TwoFAVerification = ({ onSuccess, onBack, isModal = false }) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 前端校验:与 handleSubmit 内原有判断一致,改为在输入框下方就地提示
|
||||||
|
const codeRules = [
|
||||||
|
{
|
||||||
|
required: true,
|
||||||
|
message: useBackupCode ? t('请输入备用码') : t('请输入验证码'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
validator: (_, value) => {
|
||||||
|
if (!value) return true;
|
||||||
|
if (useBackupCode) return value.length === 8 || t('备用码必须是8位');
|
||||||
|
return /^\d{6}$/.test(value) || t('验证码必须是6位数字');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
if (isModal) {
|
if (isModal) {
|
||||||
return (
|
return (
|
||||||
<div className='space-y-4'>
|
<div className='space-y-4'>
|
||||||
@@ -88,7 +103,8 @@ const TwoFAVerification = ({ onSuccess, onBack, isModal = false }) => {
|
|||||||
value={verificationCode}
|
value={verificationCode}
|
||||||
onChange={setVerificationCode}
|
onChange={setVerificationCode}
|
||||||
onKeyPress={handleKeyPress}
|
onKeyPress={handleKeyPress}
|
||||||
size='large'
|
rules={codeRules}
|
||||||
|
trigger='blur'
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
autoFocus
|
autoFocus
|
||||||
/>
|
/>
|
||||||
@@ -98,7 +114,6 @@ const TwoFAVerification = ({ onSuccess, onBack, isModal = false }) => {
|
|||||||
type='primary'
|
type='primary'
|
||||||
loading={loading}
|
loading={loading}
|
||||||
block
|
block
|
||||||
size='large'
|
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
>
|
>
|
||||||
{t('验证并登录')}
|
{t('验证并登录')}
|
||||||
@@ -115,7 +130,8 @@ const TwoFAVerification = ({ onSuccess, onBack, isModal = false }) => {
|
|||||||
setUseBackupCode(!useBackupCode);
|
setUseBackupCode(!useBackupCode);
|
||||||
setVerificationCode('');
|
setVerificationCode('');
|
||||||
}}
|
}}
|
||||||
style={{ marginRight: 16, color: '#1890ff', padding: 0 }}
|
style={{ marginRight: 16, padding: 0 }}
|
||||||
|
className='!text-brand'
|
||||||
>
|
>
|
||||||
{useBackupCode ? t('使用认证器验证码') : t('使用备用码')}
|
{useBackupCode ? t('使用认证器验证码') : t('使用备用码')}
|
||||||
</Button>
|
</Button>
|
||||||
@@ -125,7 +141,8 @@ const TwoFAVerification = ({ onSuccess, onBack, isModal = false }) => {
|
|||||||
theme='borderless'
|
theme='borderless'
|
||||||
type='tertiary'
|
type='tertiary'
|
||||||
onClick={onBack}
|
onClick={onBack}
|
||||||
style={{ color: '#1890ff', padding: 0 }}
|
style={{ padding: 0 }}
|
||||||
|
className='!text-brand'
|
||||||
>
|
>
|
||||||
{t('返回登录')}
|
{t('返回登录')}
|
||||||
</Button>
|
</Button>
|
||||||
@@ -177,7 +194,8 @@ const TwoFAVerification = ({ onSuccess, onBack, isModal = false }) => {
|
|||||||
value={verificationCode}
|
value={verificationCode}
|
||||||
onChange={setVerificationCode}
|
onChange={setVerificationCode}
|
||||||
onKeyPress={handleKeyPress}
|
onKeyPress={handleKeyPress}
|
||||||
size='large'
|
rules={codeRules}
|
||||||
|
trigger='blur'
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
autoFocus
|
autoFocus
|
||||||
/>
|
/>
|
||||||
@@ -187,7 +205,6 @@ const TwoFAVerification = ({ onSuccess, onBack, isModal = false }) => {
|
|||||||
type='primary'
|
type='primary'
|
||||||
loading={loading}
|
loading={loading}
|
||||||
block
|
block
|
||||||
size='large'
|
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
>
|
>
|
||||||
{t('验证并登录')}
|
{t('验证并登录')}
|
||||||
@@ -204,7 +221,8 @@ const TwoFAVerification = ({ onSuccess, onBack, isModal = false }) => {
|
|||||||
setUseBackupCode(!useBackupCode);
|
setUseBackupCode(!useBackupCode);
|
||||||
setVerificationCode('');
|
setVerificationCode('');
|
||||||
}}
|
}}
|
||||||
style={{ marginRight: 16, color: '#1890ff', padding: 0 }}
|
style={{ marginRight: 16, padding: 0 }}
|
||||||
|
className='!text-brand'
|
||||||
>
|
>
|
||||||
{useBackupCode ? t('使用认证器验证码') : t('使用备用码')}
|
{useBackupCode ? t('使用认证器验证码') : t('使用备用码')}
|
||||||
</Button>
|
</Button>
|
||||||
@@ -214,7 +232,8 @@ const TwoFAVerification = ({ onSuccess, onBack, isModal = false }) => {
|
|||||||
theme='borderless'
|
theme='borderless'
|
||||||
type='tertiary'
|
type='tertiary'
|
||||||
onClick={onBack}
|
onClick={onBack}
|
||||||
style={{ color: '#1890ff', padding: 0 }}
|
style={{ padding: 0 }}
|
||||||
|
className='!text-brand'
|
||||||
>
|
>
|
||||||
{t('返回登录')}
|
{t('返回登录')}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ 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': '邀请有奖',
|
||||||
|
|||||||
@@ -48,7 +48,9 @@ export default function ConsolePageContainer({ children }) {
|
|||||||
data-console-page={page.key}
|
data-console-page={page.key}
|
||||||
style={themeStyle}
|
style={themeStyle}
|
||||||
>
|
>
|
||||||
<header className='console-page-header'>
|
<header
|
||||||
|
className={`console-page-header${page.hideHeading ? ' console-page-header--crumb-only' : ''}`}
|
||||||
|
>
|
||||||
<Breadcrumb
|
<Breadcrumb
|
||||||
className='console-breadcrumb'
|
className='console-breadcrumb'
|
||||||
items={page.breadcrumbs.map((item, index) => ({
|
items={page.breadcrumbs.map((item, index) => ({
|
||||||
@@ -61,15 +63,17 @@ export default function ConsolePageContainer({ children }) {
|
|||||||
),
|
),
|
||||||
}))}
|
}))}
|
||||||
/>
|
/>
|
||||||
<div className='console-page-header-main'>
|
{!page.hideHeading && (
|
||||||
<div className='console-page-heading'>
|
<div className='console-page-header-main'>
|
||||||
<h1 className='console-page-title'>{t(page.title)}</h1>
|
<div className='console-page-heading'>
|
||||||
<p className='console-page-description'>
|
<h1 className='console-page-title'>{t(page.title)}</h1>
|
||||||
{t(`consoleUi.descriptions.${page.description}`)}
|
<p className='console-page-description'>
|
||||||
</p>
|
{t(`consoleUi.descriptions.${page.description}`)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className='console-page-actions' ref={setActionsTarget} />
|
||||||
</div>
|
</div>
|
||||||
<div className='console-page-actions' ref={setActionsTarget} />
|
)}
|
||||||
</div>
|
|
||||||
</header>
|
</header>
|
||||||
<div className='console-page-body'>{children}</div>
|
<div className='console-page-body'>{children}</div>
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -130,7 +130,10 @@ export const ConsoleForm = forwardRef(function ConsoleForm(
|
|||||||
layout={isSettings ? 'vertical' : layout}
|
layout={isSettings ? 'vertical' : layout}
|
||||||
labelCol={isSettings ? undefined : props.labelCol}
|
labelCol={isSettings ? undefined : props.labelCol}
|
||||||
wrapperCol={isSettings ? undefined : props.wrapperCol}
|
wrapperCol={isSettings ? undefined : props.wrapperCol}
|
||||||
labelAlign={isSettings ? 'left' : props.labelAlign}
|
labelAlign={isSettings ? 'start' : props.labelAlign}
|
||||||
|
autoComplete={
|
||||||
|
isSettings ? (props.autoComplete ?? 'off') : props.autoComplete
|
||||||
|
}
|
||||||
className={classes(
|
className={classes(
|
||||||
isSettings ? 'console-form settings-system-form' : 'console-form',
|
isSettings ? 'console-form settings-system-form' : 'console-form',
|
||||||
className,
|
className,
|
||||||
|
|||||||
@@ -20,6 +20,10 @@
|
|||||||
.console-page-header {
|
.console-page-header {
|
||||||
margin-bottom: 18px;
|
margin-bottom: 18px;
|
||||||
}
|
}
|
||||||
|
/* 页面自带标题时外壳只保留面包屑:面包屑到页面标题的 24px 由面包屑下边距提供 */
|
||||||
|
.console-page-header--crumb-only {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
.console-page .console-breadcrumb.ant-breadcrumb {
|
.console-page .console-breadcrumb.ant-breadcrumb {
|
||||||
margin-bottom: var(--console-space-3);
|
margin-bottom: var(--console-space-3);
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
@@ -373,6 +377,7 @@
|
|||||||
.console-page .expert-platform-shell,
|
.console-page .expert-platform-shell,
|
||||||
.console-page .skill-platform-metrics,
|
.console-page .skill-platform-metrics,
|
||||||
.console-page .skill-platform-toolbar,
|
.console-page .skill-platform-toolbar,
|
||||||
|
.console-page .skill-platform-tag-chips,
|
||||||
.console-page .skill-platform-grid {
|
.console-page .skill-platform-grid {
|
||||||
max-width: none;
|
max-width: none;
|
||||||
margin-inline: 0;
|
margin-inline: 0;
|
||||||
|
|||||||
@@ -52,7 +52,21 @@ export const consolePages = [
|
|||||||
description: 'demo-reservations',
|
description: 'demo-reservations',
|
||||||
},
|
},
|
||||||
{ key: 'personal', title: '个人设置', description: 'personal' },
|
{ key: 'personal', title: '个人设置', description: 'personal' },
|
||||||
{ key: 'my-commission', title: '我的提成', description: 'my-commission' },
|
{
|
||||||
|
key: 'my-commission',
|
||||||
|
title: '我的提成',
|
||||||
|
description: 'my-commission',
|
||||||
|
// 伙伴工作台自带随子视图切换的标题与左侧导航,外壳只保留面包屑
|
||||||
|
hideHeading: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'commission',
|
||||||
|
title: '分佣管理',
|
||||||
|
description: 'commission',
|
||||||
|
// 页面自带随子视图切换的标题(合作伙伴 / 分佣档位…),外壳只保留面包屑
|
||||||
|
hideHeading: true,
|
||||||
|
},
|
||||||
|
{ key: 'smart-router', title: '智能路由', description: 'smart-router' },
|
||||||
{ key: 'partner', title: '合作伙伴', description: 'partner' },
|
{ key: 'partner', title: '合作伙伴', description: 'partner' },
|
||||||
{
|
{
|
||||||
key: 'skill-platform',
|
key: 'skill-platform',
|
||||||
|
|||||||
@@ -96,7 +96,14 @@ const PageLayout = () => {
|
|||||||
const [giftQuota, setGiftQuota] = useState(0);
|
const [giftQuota, setGiftQuota] = useState(0);
|
||||||
|
|
||||||
const isConsoleRoute = isNavigationPathActive(location.pathname, '/console');
|
const isConsoleRoute = isNavigationPathActive(location.pathname, '/console');
|
||||||
const showSider = isConsoleRoute && (!isMobile || drawerOpen);
|
// 伙伴端保留原型中的独立伙伴工作台侧栏:桌面端隐藏重复的平台侧栏,移动端仍使用平台抽屉。
|
||||||
|
// (管理端分佣 /console/commission 使用控制台主侧栏子菜单,内边距由 ConsolePageContainer 统一。)
|
||||||
|
const isPartnerCommissionWorkspace =
|
||||||
|
location.pathname === '/console/my-commission';
|
||||||
|
const showSider =
|
||||||
|
isConsoleRoute &&
|
||||||
|
(!isPartnerCommissionWorkspace || isMobile) &&
|
||||||
|
(!isMobile || drawerOpen);
|
||||||
const isHomePage = location.pathname === '/';
|
const isHomePage = location.pathname === '/';
|
||||||
|
|
||||||
// 隐私政策和用户协议页面需要隐藏顶部工具栏
|
// 隐私政策和用户协议页面需要隐藏顶部工具栏
|
||||||
@@ -339,9 +346,10 @@ const PageLayout = () => {
|
|||||||
<Header
|
<Header
|
||||||
className={
|
className={
|
||||||
isAuthPage
|
isAuthPage
|
||||||
? ['/org/login', '/login'].includes(location.pathname)
|
? // 登录 / 注册 / 找回密码统一使用登录页同款标准顶栏;仅客户端授权页保留透明顶栏
|
||||||
? 'login-layout-header'
|
location.pathname.toLowerCase() === '/client/authorize'
|
||||||
: 'auth-layout-header'
|
? 'auth-layout-header'
|
||||||
|
: 'login-layout-header'
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
style={{
|
style={{
|
||||||
|
|||||||
@@ -23,13 +23,15 @@ import {
|
|||||||
ChevronLeft as ActionChevronLeft,
|
ChevronLeft as ActionChevronLeft,
|
||||||
} from '@/components/common/icons/ActionIcons';
|
} from '@/components/common/icons/ActionIcons';
|
||||||
import { consoleMenuPaths, getConsoleMenuKeys } from '../console/consoleRoutes';
|
import { consoleMenuPaths, getConsoleMenuKeys } from '../console/consoleRoutes';
|
||||||
import React, { useContext, useEffect, useMemo, useState } from 'react';
|
import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import { revealActiveSidebarItem } from '../../helpers/sidebarScroll';
|
||||||
import { Link, useLocation } from 'react-router-dom';
|
import { Link, useLocation } from 'react-router-dom';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { getLucideIcon } from '../../helpers/render';
|
import { getLucideIcon } from '../../helpers/render';
|
||||||
import '../../styles/center-layout.css';
|
import '../../styles/center-layout.css';
|
||||||
import { useSidebarCollapsed } from '../../hooks/common/useSidebarCollapsed';
|
import { useSidebarCollapsed } from '../../hooks/common/useSidebarCollapsed';
|
||||||
import { useSidebar } from '../../hooks/common/useSidebar';
|
import { useSidebar } from '../../hooks/common/useSidebar';
|
||||||
|
import { usePartnerWorkspaceEntry } from '../../hooks/common/usePartnerWorkspaceEntry';
|
||||||
import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime';
|
import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime';
|
||||||
import { isAdmin, isRoot, showError } from '../../helpers';
|
import { isAdmin, isRoot, showError } from '../../helpers';
|
||||||
import {
|
import {
|
||||||
@@ -42,6 +44,10 @@ import {
|
|||||||
canAccessDelegatedAdminPage,
|
canAccessDelegatedAdminPage,
|
||||||
getDelegatedSettingTabs,
|
getDelegatedSettingTabs,
|
||||||
} from '../../helpers/adminDelegation';
|
} from '../../helpers/adminDelegation';
|
||||||
|
import {
|
||||||
|
loadPersonalConsentGranted,
|
||||||
|
readPersonalConsentCache,
|
||||||
|
} 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';
|
||||||
|
|
||||||
@@ -50,6 +56,18 @@ const routerMap = {
|
|||||||
...consoleMenuPaths,
|
...consoleMenuPaths,
|
||||||
about: '/about',
|
about: '/about',
|
||||||
pricing: '/market',
|
pricing: '/market',
|
||||||
|
// weiyuan 新增入口:consoleRoutes 未登记的路由在此补齐(智能路由、分佣管理子菜单)
|
||||||
|
'smart-router': '/console/smart-router',
|
||||||
|
commission: '/console/commission',
|
||||||
|
// 新版分佣使用控制台主侧栏展开子菜单,子项沿用现有 view 路由。
|
||||||
|
'commission-overview': '/console/commission?view=overview',
|
||||||
|
'commission-partners': '/console/commission?view=partners',
|
||||||
|
'commission-assignments': '/console/commission?view=assignments',
|
||||||
|
'commission-tiers': '/console/commission?view=tiers',
|
||||||
|
'commission-adjustments': '/console/commission?view=adjustments',
|
||||||
|
'commission-bills': '/console/commission?view=bills',
|
||||||
|
'commission-exceptions': '/console/commission?view=exceptions',
|
||||||
|
'commission-audit': '/console/commission?view=audit',
|
||||||
};
|
};
|
||||||
|
|
||||||
// forceExpanded:手机端抽屉态。抽屉本来就是临时全宽浮层,折叠成 60px 图标条毫无意义,
|
// forceExpanded:手机端抽屉态。抽屉本来就是临时全宽浮层,折叠成 60px 图标条毫无意义,
|
||||||
@@ -65,6 +83,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
|||||||
} = useSidebar();
|
} = useSidebar();
|
||||||
|
|
||||||
const [statusState] = useContext(StatusContext);
|
const [statusState] = useContext(StatusContext);
|
||||||
|
const showPartnerWorkspace = usePartnerWorkspaceEntry();
|
||||||
const [userState] = useContext(UserContext);
|
const [userState] = useContext(UserContext);
|
||||||
const delegatedPermissions = statusState?.status?.AdminDelegatedSettingTabs;
|
const delegatedPermissions = statusState?.status?.AdminDelegatedSettingTabs;
|
||||||
// 系统设置 tab 权限下放:普通管理员在被下放了至少一个 tab 时,才显示「系统设置」入口
|
// 系统设置 tab 权限下放:普通管理员在被下放了至少一个 tab 时,才显示「系统设置」入口
|
||||||
@@ -74,10 +93,31 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
|||||||
);
|
);
|
||||||
const canAccessSetting =
|
const canAccessSetting =
|
||||||
isRoot() || (isAdmin() && delegatedSettingTabs.length > 0);
|
isRoot() || (isAdmin() && delegatedSettingTabs.length > 0);
|
||||||
|
const commissionEnabled = statusState?.status?.commission_enabled !== false;
|
||||||
|
|
||||||
const showSkeleton = useMinimumLoadingTime(sidebarLoading, 200);
|
const showSkeleton = useMinimumLoadingTime(sidebarLoading, 200);
|
||||||
|
|
||||||
const [selectedKeys, setSelectedKeys] = useState(['home']);
|
const [selectedKeys, setSelectedKeys] = useState(['home']);
|
||||||
|
const navigationRef = useRef(null);
|
||||||
|
// 平台关闭智能路由后,仍有生效中出境同意的普通用户保留入口以便撤回(§9.5,与企业"仅授权模式"同口径)
|
||||||
|
const [routerConsentGranted, setRouterConsentGranted] = useState(
|
||||||
|
() => readPersonalConsentCache() === '1',
|
||||||
|
);
|
||||||
|
const smartRouterEnabled = statusState?.status?.smart_router_enabled;
|
||||||
|
useEffect(() => {
|
||||||
|
if (smartRouterEnabled !== false || isAdmin()) return;
|
||||||
|
if (!localStorage.getItem('user')) return; // 未登录不请求,避免 401 跳转
|
||||||
|
if (readPersonalConsentCache() !== null) return;
|
||||||
|
let alive = true;
|
||||||
|
loadPersonalConsentGranted()
|
||||||
|
.then((granted) => {
|
||||||
|
if (alive) setRouterConsentGranted(granted);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
};
|
||||||
|
}, [smartRouterEnabled]);
|
||||||
const [chatItems, setChatItems] = useState([]);
|
const [chatItems, setChatItems] = useState([]);
|
||||||
const [openedKeys, setOpenedKeys] = useState([]);
|
const [openedKeys, setOpenedKeys] = useState([]);
|
||||||
const [foldedGroups, setFoldedGroups] = useState([]);
|
const [foldedGroups, setFoldedGroups] = useState([]);
|
||||||
@@ -122,16 +162,39 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
|||||||
itemKey: 'monitor',
|
itemKey: 'monitor',
|
||||||
to: '/monitor',
|
to: '/monitor',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
// 智能路由:已登记在 sidebarModules 注册表(console.smart-router),管理员可隐藏
|
||||||
|
text: t('智能路由'),
|
||||||
|
itemKey: 'smart-router',
|
||||||
|
to: '/console/smart-router',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
// 根据配置过滤项目
|
// 根据配置过滤项目
|
||||||
const filteredItems = items.filter((item) => {
|
const filteredItems = items.filter((item) => {
|
||||||
|
// 智能路由:管理员始终可见(全局设置在该页),普通用户在平台开启后才显示,
|
||||||
|
// 避免升级后所有用户突然多出一个尚未启用的入口
|
||||||
|
if (
|
||||||
|
item.itemKey === 'smart-router' &&
|
||||||
|
!isAdmin() &&
|
||||||
|
smartRouterEnabled !== true &&
|
||||||
|
!routerConsentGranted
|
||||||
|
)
|
||||||
|
return false;
|
||||||
const configVisible = isModuleVisible('console', item.itemKey);
|
const configVisible = isModuleVisible('console', item.itemKey);
|
||||||
return configVisible;
|
return configVisible;
|
||||||
});
|
});
|
||||||
|
|
||||||
return filteredItems;
|
return filteredItems;
|
||||||
}, [dataExportFlag, drawingFlag, taskFlag, t, isModuleVisible]);
|
}, [
|
||||||
|
smartRouterEnabled,
|
||||||
|
routerConsentGranted,
|
||||||
|
dataExportFlag,
|
||||||
|
drawingFlag,
|
||||||
|
taskFlag,
|
||||||
|
t,
|
||||||
|
isModuleVisible,
|
||||||
|
]);
|
||||||
|
|
||||||
const financeItems = useMemo(() => {
|
const financeItems = useMemo(() => {
|
||||||
const items = [
|
const items = [
|
||||||
@@ -157,26 +220,16 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
|||||||
return configVisible;
|
return configVisible;
|
||||||
});
|
});
|
||||||
|
|
||||||
// 我的提成:新模块不在 sidebar 配置注册表内,直接追加(非销售用户页面为空态)
|
// 与顶栏和伙伴页面共用新版伙伴权限判断,避免无权限账号误入。
|
||||||
filteredItems.push({
|
if (showPartnerWorkspace) {
|
||||||
text: t('我的提成'),
|
|
||||||
itemKey: 'my-commission',
|
|
||||||
});
|
|
||||||
|
|
||||||
// 合作伙伴:受平台总开关控制(参数设置页可配),开放后对全部登录用户可见
|
|
||||||
if (statusState?.status?.commission_partner_portal_enabled === true) {
|
|
||||||
filteredItems.push({
|
filteredItems.push({
|
||||||
text: t('合作伙伴'),
|
text: t('我的提成'),
|
||||||
itemKey: 'partner',
|
itemKey: 'my-commission',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return filteredItems;
|
return filteredItems;
|
||||||
}, [
|
}, [t, isModuleVisible, showPartnerWorkspace]);
|
||||||
t,
|
|
||||||
isModuleVisible,
|
|
||||||
statusState?.status?.commission_partner_portal_enabled,
|
|
||||||
]);
|
|
||||||
|
|
||||||
const adminItems = useMemo(() => {
|
const adminItems = useMemo(() => {
|
||||||
const items = [
|
const items = [
|
||||||
@@ -185,6 +238,21 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
|||||||
itemKey: 'analytics',
|
itemKey: 'analytics',
|
||||||
className: isAdmin() ? '' : 'tableHiddle',
|
className: isAdmin() ? '' : 'tableHiddle',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
text: t('分佣管理'),
|
||||||
|
itemKey: 'commission',
|
||||||
|
items: [
|
||||||
|
{ text: t('分佣工作台'), itemKey: 'commission-overview' },
|
||||||
|
{ text: t('合作伙伴'), itemKey: 'commission-partners' },
|
||||||
|
{ text: t('客户归属'), itemKey: 'commission-assignments' },
|
||||||
|
{ text: t('分佣档位'), itemKey: 'commission-tiers' },
|
||||||
|
{ text: t('调整单'), itemKey: 'commission-adjustments' },
|
||||||
|
{ text: t('销售提成'), itemKey: 'commission-bills' },
|
||||||
|
{ text: t('异常中心'), itemKey: 'commission-exceptions' },
|
||||||
|
{ text: t('分佣审计日志'), itemKey: 'commission-audit' },
|
||||||
|
],
|
||||||
|
className: isRoot() ? '' : 'tableHiddle',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
text: t('渠道管理'),
|
text: t('渠道管理'),
|
||||||
itemKey: 'channel',
|
itemKey: 'channel',
|
||||||
@@ -281,6 +349,12 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
|||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
// 分佣管理:新增模块不在 sidebar 配置注册表内,绕过 isModuleVisible(Root 硬门控)。
|
||||||
|
// 分佣总开关关闭时整组隐藏(接口已被后端闸门拦截);旧后端不返回该字段,视为开启。
|
||||||
|
// 合并恢复:weiyuan 原逻辑(5e67eff82),合并 SiderBar 时被 ui 过滤函数覆盖丢失
|
||||||
|
if (item.itemKey === 'commission') {
|
||||||
|
return isRoot() && commissionEnabled;
|
||||||
|
}
|
||||||
// 系统设置入口:被下放了至少一个 tab 的普通管理员强制可见
|
// 系统设置入口:被下放了至少一个 tab 的普通管理员强制可见
|
||||||
// (需绕过 isModuleVisible,因为 GetSelf 默认对普通管理员置 admin.setting=false)。
|
// (需绕过 isModuleVisible,因为 GetSelf 默认对普通管理员置 admin.setting=false)。
|
||||||
// root 及其它情况仍走原有 isModuleVisible 逻辑,保留 root 自行隐藏该入口的能力。
|
// root 及其它情况仍走原有 isModuleVisible 逻辑,保留 root 自行隐藏该入口的能力。
|
||||||
@@ -304,6 +378,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
|||||||
delegatedSettingTabs,
|
delegatedSettingTabs,
|
||||||
delegatedPermissions,
|
delegatedPermissions,
|
||||||
userState?.user?.role,
|
userState?.user?.role,
|
||||||
|
commissionEnabled,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const chatMenuItems = useMemo(() => {
|
const chatMenuItems = useMemo(() => {
|
||||||
@@ -380,6 +455,28 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
|||||||
// 根据当前路径设置选中的菜单项
|
// 根据当前路径设置选中的菜单项
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const currentPath = location.pathname;
|
const currentPath = location.pathname;
|
||||||
|
if (currentPath === '/console/commission') {
|
||||||
|
const view =
|
||||||
|
new URLSearchParams(location.search).get('view') || 'overview';
|
||||||
|
const childKey = `commission-${view}`;
|
||||||
|
const validChildKeys = [
|
||||||
|
'commission-overview',
|
||||||
|
'commission-partners',
|
||||||
|
'commission-assignments',
|
||||||
|
'commission-tiers',
|
||||||
|
'commission-adjustments',
|
||||||
|
'commission-bills',
|
||||||
|
'commission-exceptions',
|
||||||
|
'commission-audit',
|
||||||
|
];
|
||||||
|
setSelectedKeys([
|
||||||
|
validChildKeys.includes(childKey) ? childKey : 'commission-overview',
|
||||||
|
]);
|
||||||
|
setOpenedKeys((keys) =>
|
||||||
|
keys.includes('commission') ? keys : [...keys, 'commission'],
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
let matchingKeys = getConsoleMenuKeys(currentPath, routerMapState);
|
let matchingKeys = getConsoleMenuKeys(currentPath, routerMapState);
|
||||||
|
|
||||||
// 处理聊天路由
|
// 处理聊天路由
|
||||||
@@ -396,7 +493,39 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
|||||||
if (matchingKeys.length) {
|
if (matchingKeys.length) {
|
||||||
setSelectedKeys(matchingKeys);
|
setSelectedKeys(matchingKeys);
|
||||||
}
|
}
|
||||||
}, [location.pathname, routerMapState]);
|
}, [location.pathname, location.search, routerMapState]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const navigation = navigationRef.current;
|
||||||
|
if (!navigation || showSkeleton) return;
|
||||||
|
let frame;
|
||||||
|
const scheduleReveal = () => {
|
||||||
|
cancelAnimationFrame(frame);
|
||||||
|
frame = requestAnimationFrame(() => revealActiveSidebarItem(navigation));
|
||||||
|
};
|
||||||
|
scheduleReveal();
|
||||||
|
const resizeObserver = new ResizeObserver(scheduleReveal);
|
||||||
|
resizeObserver.observe(navigation);
|
||||||
|
const mutationObserver = new MutationObserver(scheduleReveal);
|
||||||
|
mutationObserver.observe(navigation, {
|
||||||
|
childList: true,
|
||||||
|
subtree: true,
|
||||||
|
attributes: true,
|
||||||
|
attributeFilter: ['hidden'],
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelAnimationFrame(frame);
|
||||||
|
resizeObserver.disconnect();
|
||||||
|
mutationObserver.disconnect();
|
||||||
|
};
|
||||||
|
}, [
|
||||||
|
showSkeleton,
|
||||||
|
selectedKeys,
|
||||||
|
collapsed,
|
||||||
|
forceExpanded,
|
||||||
|
openedKeys,
|
||||||
|
foldedGroups,
|
||||||
|
]);
|
||||||
|
|
||||||
// 监控折叠状态变化以更新 body class(--sidebar-current-width 由它驱动)。
|
// 监控折叠状态变化以更新 body class(--sidebar-current-width 由它驱动)。
|
||||||
// 抽屉态下跳过:body class 是全局的,抽屉临时展开不该顺手把桌面侧栏宽度也改掉。
|
// 抽屉态下跳过:body class 是全局的,抽屉临时展开不该顺手把桌面侧栏宽度也改掉。
|
||||||
@@ -450,20 +579,24 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
||||||
const renderNavItem = (item) => {
|
// nested:二级菜单项(无图标,靠缩进与引导线表达层级);forceActive:收起态父项代表任一子项选中
|
||||||
|
const renderNavItem = (
|
||||||
|
item,
|
||||||
|
{ nested = false, forceActive = false } = {},
|
||||||
|
) => {
|
||||||
if (item.className === 'tableHiddle') return null;
|
if (item.className === 'tableHiddle') return null;
|
||||||
const active = selectedKeys.includes(item.itemKey);
|
const active = forceActive || selectedKeys.includes(item.itemKey);
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
key={item.itemKey}
|
key={item.itemKey}
|
||||||
to={routerMapState[item.itemKey] || routerMap[item.itemKey] || '#'}
|
to={routerMapState[item.itemKey] || routerMap[item.itemKey] || '#'}
|
||||||
onClick={onNavigate}
|
onClick={onNavigate}
|
||||||
className='ui-center-menu-item'
|
className={`ui-center-menu-item${nested ? ' ui-console-submenu-item' : ''}`}
|
||||||
data-active={active || undefined}
|
data-active={active || undefined}
|
||||||
aria-current={active ? 'page' : undefined}
|
aria-current={active ? 'page' : undefined}
|
||||||
title={collapsed ? item.text : undefined}
|
title={collapsed ? item.text : undefined}
|
||||||
>
|
>
|
||||||
{renderMenuIcon(item.itemKey)}
|
{!nested && renderMenuIcon(item.itemKey)}
|
||||||
{!collapsed && (
|
{!collapsed && (
|
||||||
<span className='ui-center-menu-label'>{item.text}</span>
|
<span className='ui-center-menu-label'>{item.text}</span>
|
||||||
)}
|
)}
|
||||||
@@ -474,14 +607,25 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
|||||||
const renderSubItem = (item) => {
|
const renderSubItem = (item) => {
|
||||||
if (!item.items?.length) return renderNavItem(item);
|
if (!item.items?.length) return renderNavItem(item);
|
||||||
const open = openedKeys.includes(item.itemKey);
|
const open = openedKeys.includes(item.itemKey);
|
||||||
|
const childActive = item.items.some((child) =>
|
||||||
|
selectedKeys.includes(child.itemKey),
|
||||||
|
);
|
||||||
|
// 收起态没有展开空间:父项作为入口直达模块首页,任一子项选中时父项高亮
|
||||||
|
if (collapsed) {
|
||||||
|
return renderNavItem(
|
||||||
|
{ ...item, items: undefined },
|
||||||
|
{ forceActive: childActive },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const groupId = `ui-console-submenu-${item.itemKey}`;
|
||||||
return (
|
return (
|
||||||
<div key={item.itemKey}>
|
<div key={item.itemKey} className='ui-console-submenu'>
|
||||||
<button
|
<button
|
||||||
type='button'
|
type='button'
|
||||||
className='ui-center-menu-item ui-console-submenu-toggle'
|
className='ui-center-menu-item ui-console-submenu-toggle'
|
||||||
title={collapsed ? item.text : undefined}
|
data-child-active={childActive || undefined}
|
||||||
aria-label={item.text}
|
|
||||||
aria-expanded={open}
|
aria-expanded={open}
|
||||||
|
aria-controls={groupId}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
setOpenedKeys((previous) =>
|
setOpenedKeys((previous) =>
|
||||||
previous.includes(item.itemKey)
|
previous.includes(item.itemKey)
|
||||||
@@ -491,12 +635,21 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
{renderMenuIcon(item.itemKey)}
|
{renderMenuIcon(item.itemKey)}
|
||||||
{!collapsed && (
|
<span className='ui-center-menu-label'>{item.text}</span>
|
||||||
<span className='ui-center-menu-label'>{item.text}</span>
|
<ActionChevronDown
|
||||||
)}
|
size={14}
|
||||||
|
className='ui-console-submenu-arrow'
|
||||||
|
aria-hidden
|
||||||
|
/>
|
||||||
</button>
|
</button>
|
||||||
<div className='ui-org-group-items' hidden={!open}>
|
<div
|
||||||
{item.items.map(renderNavItem)}
|
id={groupId}
|
||||||
|
role='group'
|
||||||
|
aria-label={item.text}
|
||||||
|
className='ui-org-group-items ui-console-submenu-items'
|
||||||
|
hidden={!open}
|
||||||
|
>
|
||||||
|
{item.items.map((child) => renderNavItem(child, { nested: true }))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -520,7 +673,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
|||||||
collapsed={collapsed}
|
collapsed={collapsed}
|
||||||
showAdmin={isAdmin()}
|
showAdmin={isAdmin()}
|
||||||
>
|
>
|
||||||
<nav className='ui-center-sidebar-nav'>
|
<nav ref={navigationRef} className='ui-center-sidebar-nav'>
|
||||||
{/* 聊天区域 */}
|
{/* 聊天区域 */}
|
||||||
{hasSectionVisibleModules('chat') &&
|
{hasSectionVisibleModules('chat') &&
|
||||||
renderGroup(
|
renderGroup(
|
||||||
@@ -534,7 +687,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
|||||||
renderGroup(
|
renderGroup(
|
||||||
'console-group',
|
'console-group',
|
||||||
t('控制台'),
|
t('控制台'),
|
||||||
workspaceItems.map(renderNavItem),
|
workspaceItems.map((item) => renderNavItem(item)),
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* 个人中心区域 */}
|
{/* 个人中心区域 */}
|
||||||
@@ -542,15 +695,17 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
|
|||||||
renderGroup(
|
renderGroup(
|
||||||
'personal-group',
|
'personal-group',
|
||||||
t('个人中心'),
|
t('个人中心'),
|
||||||
financeItems.map(renderNavItem),
|
financeItems.map((item) => renderNavItem(item)),
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* 管理员区域:按角色、权限下放及菜单配置过滤。 */}
|
{/* 管理员区域:按角色、权限下放及菜单配置过滤。分佣管理为子菜单,走 renderSubItem。 */}
|
||||||
{isAdmin() &&
|
{isAdmin() &&
|
||||||
renderGroup(
|
renderGroup(
|
||||||
'admin-group',
|
'admin-group',
|
||||||
t('管理员'),
|
t('管理员'),
|
||||||
adminItems.map(renderNavItem),
|
adminItems
|
||||||
|
.filter((item) => item.className !== 'tableHiddle')
|
||||||
|
.map(renderSubItem),
|
||||||
)}
|
)}
|
||||||
</nav>
|
</nav>
|
||||||
</SkeletonWrapper>
|
</SkeletonWrapper>
|
||||||
|
|||||||
@@ -44,7 +44,6 @@ const ActionButtons = ({
|
|||||||
userState,
|
userState,
|
||||||
isLoading,
|
isLoading,
|
||||||
isMobile,
|
isMobile,
|
||||||
isSelfUseMode,
|
|
||||||
headerNavModules,
|
headerNavModules,
|
||||||
sidebarModulesAdmin,
|
sidebarModulesAdmin,
|
||||||
isOrgUser,
|
isOrgUser,
|
||||||
@@ -235,7 +234,6 @@ const ActionButtons = ({
|
|||||||
userState={userState}
|
userState={userState}
|
||||||
isLoading={isLoading}
|
isLoading={isLoading}
|
||||||
isMobile={isMobile}
|
isMobile={isMobile}
|
||||||
isSelfUseMode={isSelfUseMode}
|
|
||||||
headerNavModules={headerNavModules}
|
headerNavModules={headerNavModules}
|
||||||
rightActions={headerNavModules?.rightActions}
|
rightActions={headerNavModules?.rightActions}
|
||||||
sidebarModulesAdmin={sidebarModulesAdmin}
|
sidebarModulesAdmin={sidebarModulesAdmin}
|
||||||
|
|||||||
@@ -19,8 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
|
|||||||
|
|
||||||
import { Globe as ActionGlobe } from '@/components/common/icons/ActionIcons';
|
import { Globe as ActionGlobe } from '@/components/common/icons/ActionIcons';
|
||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { Button as AntButton } from 'antd';
|
import { Button as AntButton, Dropdown } from 'antd';
|
||||||
import { Dropdown } from '@/components/ui';
|
|
||||||
import { CN, GB, JP, KR, TH, VN } from 'country-flag-icons/react/3x2';
|
import { CN, GB, JP, KR, TH, VN } from 'country-flag-icons/react/3x2';
|
||||||
import { normalizeLanguage } from '../../../i18n/language';
|
import { normalizeLanguage } from '../../../i18n/language';
|
||||||
import { orderEnabledLanguages } from '../../../i18n/catalog';
|
import { orderEnabledLanguages } from '../../../i18n/catalog';
|
||||||
@@ -47,41 +46,32 @@ const LanguageSelector = ({ currentLang, onLanguageChange, t }) => {
|
|||||||
window.removeEventListener(LANG_BOOT_UPDATED_EVENT, handleBootUpdated);
|
window.removeEventListener(LANG_BOOT_UPDATED_EVENT, handleBootUpdated);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const getItemClassName = (isSelected) =>
|
|
||||||
`!flex !items-center !gap-2 !px-3 !py-1.5 !text-sm ${
|
|
||||||
isSelected
|
|
||||||
? '!bg-ui-color-primary-light-default !font-semibold'
|
|
||||||
: 'hover:!bg-ui-color-fill-1'
|
|
||||||
}`;
|
|
||||||
|
|
||||||
// 展示哪些语言、按什么顺序由后台「语言与地区」配置决定(经 /api/i18n/locale 缓存下发)
|
// 展示哪些语言、按什么顺序由后台「语言与地区」配置决定(经 /api/i18n/locale 缓存下发)
|
||||||
const languages = orderEnabledLanguages(getBootConfig()?.enabled_languages);
|
const languages = orderEnabledLanguages(getBootConfig()?.enabled_languages);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dropdown
|
<Dropdown
|
||||||
position='bottomRight'
|
trigger={['hover', 'click']}
|
||||||
render={
|
placement='bottomRight'
|
||||||
<Dropdown.Menu>
|
menu={{
|
||||||
{languages.map(({ code, endonym, flag }) => {
|
selectable: true,
|
||||||
const Flag = FLAGS[flag];
|
selectedKeys: [lang],
|
||||||
return (
|
onClick: ({ key }) => onLanguageChange(key),
|
||||||
<Dropdown.Item
|
items: languages.map(({ code, endonym, flag }) => {
|
||||||
key={code}
|
const Flag = FLAGS[flag];
|
||||||
onClick={() => onLanguageChange(code)}
|
return {
|
||||||
className={getItemClassName(lang === code)}
|
key: code,
|
||||||
>
|
icon: Flag ? <Flag title={endonym} className='w-5 h-auto' /> : null,
|
||||||
{Flag && <Flag title={endonym} className='!w-5 !h-auto' />}
|
label: endonym,
|
||||||
<span>{endonym}</span>
|
};
|
||||||
</Dropdown.Item>
|
}),
|
||||||
);
|
}}
|
||||||
})}
|
|
||||||
</Dropdown.Menu>
|
|
||||||
}
|
|
||||||
>
|
>
|
||||||
<AntButton
|
<AntButton
|
||||||
type='text'
|
type='text'
|
||||||
icon={<ActionGlobe size={16} strokeWidth={1.5} aria-hidden />}
|
icon={<ActionGlobe size={16} strokeWidth={1.5} aria-hidden />}
|
||||||
aria-label={t('common.changeLanguage')}
|
aria-label={t('common.changeLanguage')}
|
||||||
|
aria-haspopup='menu'
|
||||||
className='ui-header-icon-action'
|
className='ui-header-icon-action'
|
||||||
/>
|
/>
|
||||||
</Dropdown>
|
</Dropdown>
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ For commercial licensing, please contact support@quantumnous.com
|
|||||||
import { Compass as ActionCompass } from '@/components/common/icons/ActionIcons';
|
import { Compass as ActionCompass } from '@/components/common/icons/ActionIcons';
|
||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { useLocation, useNavigate } from 'react-router-dom';
|
import { useLocation, useNavigate } from 'react-router-dom';
|
||||||
import { Button, Dropdown } from '@/components/ui';
|
import { Button, Dropdown } from 'antd';
|
||||||
import { ExternalLink } from 'lucide-react';
|
import { ExternalLink } from 'lucide-react';
|
||||||
import { isNavigationPathActive } from '../../console/consoleRoutes';
|
import { isNavigationPathActive } from '../../console/consoleRoutes';
|
||||||
|
|
||||||
@@ -82,6 +82,7 @@ const MobileNavMenu = ({ mainNavLinks, userState, t }) => {
|
|||||||
menuItems.push({
|
menuItems.push({
|
||||||
key: link.itemKey,
|
key: link.itemKey,
|
||||||
text: link.text,
|
text: link.text,
|
||||||
|
mobileText: link.mobileText,
|
||||||
to: targetPath,
|
to: targetPath,
|
||||||
active: isPathActive(link.activePrefix || targetPath),
|
active: isPathActive(link.activePrefix || targetPath),
|
||||||
});
|
});
|
||||||
@@ -91,62 +92,51 @@ const MobileNavMenu = ({ mainNavLinks, userState, t }) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Dropdown
|
<Dropdown
|
||||||
trigger='click'
|
trigger={['click']}
|
||||||
position='bottomLeft'
|
placement='bottomLeft'
|
||||||
visible={visible}
|
open={visible}
|
||||||
onVisibleChange={setVisible}
|
onOpenChange={setVisible}
|
||||||
render={
|
menu={{
|
||||||
<Dropdown.Menu className='!min-w-[168px] !p-1.5 !rounded-xl !border !border-gray-100 dark:!border-neutral-800 !shadow-xl !shadow-gray-200/50 dark:!shadow-black/30 !backdrop-blur-xl !bg-white/95 dark:!bg-neutral-900/95'>
|
selectedKeys: menuItems
|
||||||
{menuItems.map((item) => (
|
.filter((item) => item.active)
|
||||||
<Dropdown.Item
|
.map((item) => item.key),
|
||||||
key={item.key}
|
items: menuItems.map((item) => ({
|
||||||
onClick={() => {
|
key: item.key,
|
||||||
setVisible(false);
|
onClick: () => {
|
||||||
if (item.externalLink) {
|
setVisible(false);
|
||||||
window.open(
|
if (item.externalLink) {
|
||||||
item.externalLink,
|
window.open(item.externalLink, '_blank', 'noopener,noreferrer');
|
||||||
'_blank',
|
} else if (item.to) {
|
||||||
'noopener,noreferrer',
|
navigate(item.to);
|
||||||
);
|
}
|
||||||
} else if (item.to) {
|
},
|
||||||
navigate(item.to);
|
label: (
|
||||||
}
|
<span
|
||||||
}}
|
className='flex items-center gap-1.5'
|
||||||
className={`!rounded-lg !my-0.5 !px-3 !py-2 !text-sm !transition-colors ${
|
aria-current={item.active ? 'page' : undefined}
|
||||||
item.active
|
|
||||||
? '!bg-brand/10 dark:!bg-brand-deep/40 !text-brand-deep dark:!text-brand-from !font-semibold'
|
|
||||||
: '!text-gray-700 dark:!text-neutral-200'
|
|
||||||
}`}
|
|
||||||
>
|
>
|
||||||
<span
|
{item.text}
|
||||||
className='flex items-center gap-1.5'
|
{item.externalLink && (
|
||||||
aria-current={item.active ? 'page' : undefined}
|
<ExternalLink size={12} className='opacity-50' />
|
||||||
>
|
)}
|
||||||
{item.text}
|
</span>
|
||||||
{item.externalLink && (
|
),
|
||||||
<ExternalLink size={12} className='opacity-50' />
|
})),
|
||||||
)}
|
}}
|
||||||
</span>
|
|
||||||
</Dropdown.Item>
|
|
||||||
))}
|
|
||||||
</Dropdown.Menu>
|
|
||||||
}
|
|
||||||
>
|
>
|
||||||
<span className='inline-flex'>
|
<Button
|
||||||
<Button
|
type='text'
|
||||||
theme='borderless'
|
aria-label={t('主导航')}
|
||||||
type='tertiary'
|
title={activeItem?.text}
|
||||||
aria-label={t('主导航')}
|
aria-haspopup='menu'
|
||||||
aria-haspopup='menu'
|
aria-expanded={visible}
|
||||||
aria-expanded={visible}
|
icon={<ActionCompass size={16} />}
|
||||||
icon={<ActionCompass size={16} />}
|
className='ml-1 px-2 max-w-[9rem] [&_.ant-btn-content]:min-w-0'
|
||||||
className='!ml-1 !px-2 !h-8 max-w-[9rem] !rounded-xl !text-current hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !transition-all !duration-200 active:!scale-95 [&_.ant-btn-content]:min-w-0'
|
>
|
||||||
>
|
<span className='ml-1 text-[13px] font-semibold truncate'>
|
||||||
<span className='ml-1 text-[13px] font-semibold truncate'>
|
{activeItem?.mobileText || activeItem?.text || t('导航')}
|
||||||
{activeItem ? activeItem.text : t('导航')}
|
</span>
|
||||||
</span>
|
</Button>
|
||||||
</Button>
|
|
||||||
</span>
|
|
||||||
</Dropdown>
|
</Dropdown>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -19,7 +19,11 @@ For commercial licensing, please contact support@quantumnous.com
|
|||||||
|
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Link, useLocation } from 'react-router-dom';
|
import { Link, useLocation } from 'react-router-dom';
|
||||||
import { Dropdown } from '@/components/ui';
|
import { Dropdown } from 'antd';
|
||||||
|
import {
|
||||||
|
ChevronDown,
|
||||||
|
ExternalLink,
|
||||||
|
} from '@/components/common/icons/ActionIcons';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import SkeletonWrapper from '../components/SkeletonWrapper';
|
import SkeletonWrapper from '../components/SkeletonWrapper';
|
||||||
import { isNavigationPathActive } from '../../console/consoleRoutes';
|
import { isNavigationPathActive } from '../../console/consoleRoutes';
|
||||||
@@ -68,44 +72,27 @@ const Navigation = ({ mainNavLinks, isMobile, isLoading, userState }) => {
|
|||||||
return (
|
return (
|
||||||
<Dropdown
|
<Dropdown
|
||||||
key={link.itemKey}
|
key={link.itemKey}
|
||||||
trigger={'hover'}
|
trigger={['hover', 'click']}
|
||||||
position={'bottomLeft'}
|
placement='bottomLeft'
|
||||||
render={
|
menu={{
|
||||||
<Dropdown.Menu>
|
selectedKeys: link.items
|
||||||
{link.items.map((subItem) => (
|
.filter((item) => isPathActive(item.to))
|
||||||
<Dropdown.Item key={subItem.itemKey}>
|
.map((item) => item.itemKey),
|
||||||
<Link
|
items: link.items.map((subItem) => ({
|
||||||
to={subItem.to}
|
key: subItem.itemKey,
|
||||||
className='block w-full py-0.5 text-gray-700 dark:text-neutral-200 hover:text-brand-deep dark:hover:text-brand-from transition-colors'
|
label: <Link to={subItem.to}>{subItem.text}</Link>,
|
||||||
style={{ textDecoration: 'none' }}
|
})),
|
||||||
>
|
}}
|
||||||
{subItem.text}
|
|
||||||
</Link>
|
|
||||||
</Dropdown.Item>
|
|
||||||
))}
|
|
||||||
</Dropdown.Menu>
|
|
||||||
}
|
|
||||||
>
|
>
|
||||||
<div
|
<button
|
||||||
|
type='button'
|
||||||
className={`${finalClasses} cursor-pointer`}
|
className={`${finalClasses} cursor-pointer`}
|
||||||
|
aria-haspopup='menu'
|
||||||
aria-current={isActive ? 'page' : undefined}
|
aria-current={isActive ? 'page' : undefined}
|
||||||
>
|
>
|
||||||
{linkContent}
|
{linkContent}
|
||||||
{/* Dropdown arrow */}
|
<ChevronDown size={14} aria-hidden />
|
||||||
<svg
|
</button>
|
||||||
className='w-3.5 h-3.5 opacity-50 group-hover:opacity-100 transition-all duration-300 group-hover:rotate-180'
|
|
||||||
fill='none'
|
|
||||||
viewBox='0 0 24 24'
|
|
||||||
stroke='currentColor'
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
strokeLinecap='round'
|
|
||||||
strokeLinejoin='round'
|
|
||||||
strokeWidth={2}
|
|
||||||
d='M19 9l-7 7-7-7'
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
</div>
|
|
||||||
</Dropdown>
|
</Dropdown>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -120,20 +107,7 @@ const Navigation = ({ mainNavLinks, isMobile, isLoading, userState }) => {
|
|||||||
className={`${baseClasses} ${spacingClasses} ${defaultClasses} ${hoverClasses}`}
|
className={`${baseClasses} ${spacingClasses} ${defaultClasses} ${hoverClasses}`}
|
||||||
>
|
>
|
||||||
{linkContent}
|
{linkContent}
|
||||||
{/* External link icon */}
|
<ExternalLink size={12} aria-hidden />
|
||||||
<svg
|
|
||||||
className='w-3 h-3 opacity-50 group-hover:opacity-100 transition-opacity'
|
|
||||||
fill='none'
|
|
||||||
viewBox='0 0 24 24'
|
|
||||||
stroke='currentColor'
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
strokeLinecap='round'
|
|
||||||
strokeLinejoin='round'
|
|
||||||
strokeWidth={2}
|
|
||||||
d='M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14'
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
</a>
|
</a>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,11 +19,9 @@ For commercial licensing, please contact support@quantumnous.com
|
|||||||
|
|
||||||
import { ChevronDown as ActionChevronDown } from '@/components/common/icons/ActionIcons';
|
import { ChevronDown as ActionChevronDown } from '@/components/common/icons/ActionIcons';
|
||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { Link, useLocation } from 'react-router-dom';
|
|
||||||
import { Avatar, Button as AntButton, Dropdown as AntDropdown } from 'antd';
|
import { Avatar, Button as AntButton, Dropdown as AntDropdown } from 'antd';
|
||||||
import { Button } from '@/components/ui';
|
|
||||||
import { UserRound, KeyRound, LogOut } from 'lucide-react';
|
import { UserRound, KeyRound, LogOut } from 'lucide-react';
|
||||||
import { getUserAvatarUrl, isAuthPagePath } from '../../../helpers';
|
import { getUserAvatarUrl } from '../../../helpers';
|
||||||
import SkeletonWrapper from '../components/SkeletonWrapper';
|
import SkeletonWrapper from '../components/SkeletonWrapper';
|
||||||
import { isHeaderModuleEnabled } from '../../../constants/headerNavModules';
|
import { isHeaderModuleEnabled } from '../../../constants/headerNavModules';
|
||||||
|
|
||||||
@@ -46,7 +44,6 @@ const UserArea = ({
|
|||||||
userState,
|
userState,
|
||||||
isLoading,
|
isLoading,
|
||||||
isMobile,
|
isMobile,
|
||||||
isSelfUseMode,
|
|
||||||
headerNavModules,
|
headerNavModules,
|
||||||
rightActions = {},
|
rightActions = {},
|
||||||
sidebarModulesAdmin = {},
|
sidebarModulesAdmin = {},
|
||||||
@@ -55,7 +52,6 @@ const UserArea = ({
|
|||||||
navigate,
|
navigate,
|
||||||
t,
|
t,
|
||||||
}) => {
|
}) => {
|
||||||
const location = useLocation();
|
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const isActionVisible = (key) => rightActions?.[key] !== false;
|
const isActionVisible = (key) => rightActions?.[key] !== false;
|
||||||
const hasHeaderModuleConfig =
|
const hasHeaderModuleConfig =
|
||||||
@@ -68,9 +64,6 @@ const UserArea = ({
|
|||||||
return section.enabled !== false && section[moduleKey] !== false;
|
return section.enabled !== false && section[moduleKey] !== false;
|
||||||
};
|
};
|
||||||
|
|
||||||
// 在登录/注册/重置密码/企业登录页面时,未登录用户不显示登录注册按钮,避免重复
|
|
||||||
const isAuthPage = isAuthPagePath(location.pathname);
|
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
<SkeletonWrapper
|
<SkeletonWrapper
|
||||||
@@ -143,7 +136,7 @@ const UserArea = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<AntDropdown
|
<AntDropdown
|
||||||
trigger={['hover']}
|
trigger={['hover', 'click']}
|
||||||
placement='bottomRight'
|
placement='bottomRight'
|
||||||
open={open}
|
open={open}
|
||||||
onOpenChange={setOpen}
|
onOpenChange={setOpen}
|
||||||
@@ -193,64 +186,9 @@ const UserArea = ({
|
|||||||
</AntButton>
|
</AntButton>
|
||||||
</AntDropdown>
|
</AntDropdown>
|
||||||
);
|
);
|
||||||
} else {
|
|
||||||
if (isAuthPage) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const showRegisterButton = !isSelfUseMode;
|
|
||||||
|
|
||||||
const commonSizingAndLayoutClass =
|
|
||||||
'flex items-center justify-center !py-[10px] !px-1.5';
|
|
||||||
|
|
||||||
const loginButtonSpecificStyling =
|
|
||||||
'!bg-transparent hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep !transition-all !duration-200';
|
|
||||||
let loginButtonClasses = `${commonSizingAndLayoutClass} ${loginButtonSpecificStyling}`;
|
|
||||||
|
|
||||||
let registerButtonClasses = `${commonSizingAndLayoutClass}`;
|
|
||||||
|
|
||||||
const loginButtonTextSpanClass =
|
|
||||||
'!text-xs !text-ui-color-text-1 dark:!text-gray-300 !p-1.5';
|
|
||||||
const registerButtonTextSpanClass = '!text-xs !text-white !p-1.5';
|
|
||||||
|
|
||||||
if (showRegisterButton) {
|
|
||||||
if (isMobile) {
|
|
||||||
loginButtonClasses += ' !rounded-full';
|
|
||||||
} else {
|
|
||||||
loginButtonClasses += ' !rounded-l-full !rounded-r-none';
|
|
||||||
}
|
|
||||||
registerButtonClasses += ' !rounded-r-full !rounded-l-none';
|
|
||||||
} else {
|
|
||||||
loginButtonClasses += ' !rounded-full';
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className='flex items-center'>
|
|
||||||
<Link to='/org/login' className='flex'>
|
|
||||||
<Button
|
|
||||||
theme='borderless'
|
|
||||||
type='tertiary'
|
|
||||||
className={loginButtonClasses}
|
|
||||||
>
|
|
||||||
<span className={loginButtonTextSpanClass}>{t('登录')}</span>
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
{showRegisterButton && (
|
|
||||||
<div className='hidden md:block'>
|
|
||||||
<Link to='/register' className='flex -ml-px'>
|
|
||||||
<Button
|
|
||||||
theme='solid'
|
|
||||||
type='primary'
|
|
||||||
className={registerButtonClasses}
|
|
||||||
>
|
|
||||||
<span className={registerButtonTextSpanClass}>{t('注册')}</span>
|
|
||||||
</Button>
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default UserArea;
|
export default UserArea;
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ import { isAuthPagePath } from '../../../helpers';
|
|||||||
import { useHeaderBar } from '../../../hooks/common/useHeaderBar';
|
import { useHeaderBar } from '../../../hooks/common/useHeaderBar';
|
||||||
import { useNotifications } from '../../../hooks/common/useNotifications';
|
import { useNotifications } from '../../../hooks/common/useNotifications';
|
||||||
import { useNavigation } from '../../../hooks/common/useNavigation';
|
import { useNavigation } from '../../../hooks/common/useNavigation';
|
||||||
|
import { usePartnerWorkspaceEntry } from '../../../hooks/common/usePartnerWorkspaceEntry';
|
||||||
import NoticeModal from '../NoticeModal';
|
import NoticeModal from '../NoticeModal';
|
||||||
import MobileMenuButton from './MobileMenuButton';
|
import MobileMenuButton from './MobileMenuButton';
|
||||||
import HeaderLogo from './HeaderLogo';
|
import HeaderLogo from './HeaderLogo';
|
||||||
@@ -74,13 +75,14 @@ const HeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
|
|||||||
|
|
||||||
const userRole = userState?.user?.role || 0;
|
const userRole = userState?.user?.role || 0;
|
||||||
const userGroup = userState?.user?.group || 'default';
|
const userGroup = userState?.user?.group || 'default';
|
||||||
|
const showPartnerEntry = usePartnerWorkspaceEntry();
|
||||||
const { mainNavLinks: configuredNavLinks } = useNavigation(
|
const { mainNavLinks: configuredNavLinks } = useNavigation(
|
||||||
t,
|
t,
|
||||||
docsLink,
|
docsLink,
|
||||||
headerNavModules,
|
headerNavModules,
|
||||||
userRole,
|
userRole,
|
||||||
userGroup,
|
userGroup,
|
||||||
{ showOrgEntry, orgEntryPath },
|
{ showOrgEntry, orgEntryPath, showPartnerEntry },
|
||||||
);
|
);
|
||||||
const mainNavLinks = configuredNavLinks.filter(
|
const mainNavLinks = configuredNavLinks.filter(
|
||||||
(link) => link.itemKey !== 'keyManagement',
|
(link) => link.itemKey !== 'keyManagement',
|
||||||
@@ -179,7 +181,6 @@ const HeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
|
|||||||
userState={userState}
|
userState={userState}
|
||||||
isLoading={isLoading}
|
isLoading={isLoading}
|
||||||
isMobile={isMobile}
|
isMobile={isMobile}
|
||||||
isSelfUseMode={isSelfUseMode}
|
|
||||||
headerNavModules={headerNavModules}
|
headerNavModules={headerNavModules}
|
||||||
sidebarModulesAdmin={sidebarModulesAdmin}
|
sidebarModulesAdmin={sidebarModulesAdmin}
|
||||||
isOrgUser={isOrgUser}
|
isOrgUser={isOrgUser}
|
||||||
|
|||||||
@@ -105,7 +105,8 @@ const SSEViewer = ({ sseData }) => {
|
|||||||
)
|
)
|
||||||
.join('\n\n');
|
.join('\n\n');
|
||||||
|
|
||||||
if (!(await copy(allData))) throw new Error('Clipboard copy failed');
|
// copy 失败返回 false 而不抛错,交给下方 catch 统一提示
|
||||||
|
if (!(await copy(allData))) throw new Error('copy failed');
|
||||||
setCopied(true);
|
setCopied(true);
|
||||||
Toast.success(t('已复制全部数据'));
|
Toast.success(t('已复制全部数据'));
|
||||||
setTimeout(() => setCopied(false), 2000);
|
setTimeout(() => setCopied(false), 2000);
|
||||||
@@ -121,7 +122,7 @@ const SSEViewer = ({ sseData }) => {
|
|||||||
const textToCopy = item.parsed
|
const textToCopy = item.parsed
|
||||||
? JSON.stringify(item.parsed, null, 2)
|
? JSON.stringify(item.parsed, null, 2)
|
||||||
: item.raw;
|
: item.raw;
|
||||||
if (!(await copy(textToCopy))) throw new Error('Clipboard copy failed');
|
if (!(await copy(textToCopy))) throw new Error('copy failed');
|
||||||
Toast.success(t('已复制'));
|
Toast.success(t('已复制'));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
Toast.error(t('复制失败'));
|
Toast.error(t('复制失败'));
|
||||||
|
|||||||
@@ -284,14 +284,22 @@ const PromotionPosterModal = ({ visible, onClose }) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 复制并按实际结果提示(此前调用未处理结果,点击后无任何反馈)
|
||||||
|
const copyWithFeedback = async (text, name) => {
|
||||||
|
if (await copy(text)) {
|
||||||
|
showSuccess(t('已复制:{{name}}', { name }));
|
||||||
|
} else {
|
||||||
|
showError(t('复制失败,请手动复制'));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// 复制邀请链接
|
// 复制邀请链接
|
||||||
const handleCopyLink = async () => {
|
const handleCopyLink = async () => {
|
||||||
if (!affLink) {
|
if (!affLink) {
|
||||||
showError(t('邀请链接获取中,请稍后'));
|
showError(t('邀请链接获取中,请稍后'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (await copy(affLink)) showSuccess(t('邀请链接已复制到剪切板'));
|
copyWithFeedback(affLink, t('邀请链接'));
|
||||||
else showError(t('复制失败,请手动复制'));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// 复制邀请码
|
// 复制邀请码
|
||||||
@@ -300,8 +308,7 @@ const PromotionPosterModal = ({ visible, onClose }) => {
|
|||||||
showError(t('邀请码获取中,请稍后'));
|
showError(t('邀请码获取中,请稍后'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (await copy(affCode)) showSuccess(t('复制成功'));
|
copyWithFeedback(affCode, t('邀请码'));
|
||||||
else showError(t('复制失败,请手动复制'));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// 链接分享模式 - PC友好
|
// 链接分享模式 - PC友好
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
/* 等级与模型访问(level_policy)局部布局覆盖,全部只改尺寸不改配色 */
|
/* 等级与模型访问(level_policy)局部布局与图标样式 */
|
||||||
|
|
||||||
|
.level-policy-model-toggle.ant-btn .ant-btn-icon {
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
/* 默认访问态 pureCard 单选:两张卡等分弹窗整行宽,避免随文案长短一宽一窄 */
|
/* 默认访问态 pureCard 单选:两张卡等分弹窗整行宽,避免随文案长短一宽一窄 */
|
||||||
|
|||||||
@@ -1638,8 +1638,9 @@ const LevelPolicySetting = () => {
|
|||||||
const button = (
|
const button = (
|
||||||
<Button
|
<Button
|
||||||
size='small'
|
size='small'
|
||||||
theme='borderless'
|
className='level-policy-model-toggle'
|
||||||
type={r.modelDiscountCount > 0 ? 'primary' : 'tertiary'}
|
theme={r.modelDiscountCount > 0 ? undefined : 'borderless'}
|
||||||
|
type={r.modelDiscountCount > 0 ? 'link' : 'tertiary'}
|
||||||
icon={
|
icon={
|
||||||
expanded ? (
|
expanded ? (
|
||||||
<ActionChevronDown size={14} />
|
<ActionChevronDown size={14} />
|
||||||
|
|||||||
@@ -42,6 +42,7 @@ const ModelSetting = () => {
|
|||||||
'claude.thinking_adapter_budget_tokens_percentage': 0.8,
|
'claude.thinking_adapter_budget_tokens_percentage': 0.8,
|
||||||
'claude.cache_creation_5m_ratio': 1.25,
|
'claude.cache_creation_5m_ratio': 1.25,
|
||||||
'claude.cache_creation_1h_ratio': 2,
|
'claude.cache_creation_1h_ratio': 2,
|
||||||
|
'claude.cache_creation_default_ttl': '1h',
|
||||||
'claude.cache_ttl_override': 'off',
|
'claude.cache_ttl_override': 'off',
|
||||||
'global.pass_through_request_enabled': false,
|
'global.pass_through_request_enabled': false,
|
||||||
'global.thinking_model_blacklist': '[]',
|
'global.thinking_model_blacklist': '[]',
|
||||||
|
|||||||
@@ -89,6 +89,8 @@ const OperationSetting = () => {
|
|||||||
DefaultCollapseSidebar: false,
|
DefaultCollapseSidebar: false,
|
||||||
DemoSiteEnabled: false,
|
DemoSiteEnabled: false,
|
||||||
SelfUseModeEnabled: false,
|
SelfUseModeEnabled: false,
|
||||||
|
/* 分佣总开关:布尔必须在此声明,getOptions 才会 toBoolean */
|
||||||
|
CommissionEnabled: true,
|
||||||
|
|
||||||
/* 语言与地区(JSON,按 IP 国家自动选择界面语言) */
|
/* 语言与地区(JSON,按 IP 国家自动选择界面语言) */
|
||||||
LanguageSetting: '',
|
LanguageSetting: '',
|
||||||
|
|||||||
@@ -515,8 +515,9 @@ const PersonalSetting = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 复制用户ID
|
// 复制用户ID:走公共 copy,HTTP 部署下 navigator.clipboard 为 undefined,
|
||||||
const copyUserId = () => {
|
// 直接调用 writeText 会同步抛错,.catch 降级永远走不到。
|
||||||
|
const copyUserId = async () => {
|
||||||
const userId = String(userState?.user?.id || '');
|
const userId = String(userState?.user?.id || '');
|
||||||
writeClipboardText(userId)
|
writeClipboardText(userId)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ const RatioSetting = () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [costVisited, setCostVisited] = useState(false);
|
||||||
|
|
||||||
const getOptions = async () => {
|
const getOptions = async () => {
|
||||||
const res = await API.get('/api/option/');
|
const res = await API.get('/api/option/');
|
||||||
@@ -99,7 +100,12 @@ const RatioSetting = () => {
|
|||||||
<Spin spinning={loading} size='large'>
|
<Spin spinning={loading} size='large'>
|
||||||
{/* 模型倍率设置以及可视化编辑器 */}
|
{/* 模型倍率设置以及可视化编辑器 */}
|
||||||
<Card className='settings-section'>
|
<Card className='settings-section'>
|
||||||
<Tabs type='card'>
|
<Tabs
|
||||||
|
type='card'
|
||||||
|
onChange={(key) => {
|
||||||
|
if (key === 'model_cost') setCostVisited(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
<Tabs.TabPane tab={t('模型倍率设置')} itemKey='model'>
|
<Tabs.TabPane tab={t('模型倍率设置')} itemKey='model'>
|
||||||
<ModelRatioSettings options={inputs} refresh={onRefresh} />
|
<ModelRatioSettings options={inputs} refresh={onRefresh} />
|
||||||
</Tabs.TabPane>
|
</Tabs.TabPane>
|
||||||
@@ -122,7 +128,7 @@ const RatioSetting = () => {
|
|||||||
)}
|
)}
|
||||||
{isRoot() && (
|
{isRoot() && (
|
||||||
<Tabs.TabPane tab={t('模型成本价格')} itemKey='model_cost'>
|
<Tabs.TabPane tab={t('模型成本价格')} itemKey='model_cost'>
|
||||||
<ModelCostSettings />
|
{costVisited && <ModelCostSettings />}
|
||||||
</Tabs.TabPane>
|
</Tabs.TabPane>
|
||||||
)}
|
)}
|
||||||
<Tabs.TabPane tab={t('未设置倍率模型')} itemKey='unset_models'>
|
<Tabs.TabPane tab={t('未设置倍率模型')} itemKey='unset_models'>
|
||||||
|
|||||||
@@ -849,7 +849,7 @@ const SystemSetting = () => {
|
|||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<Form.Section text={t('SSRF防护设置')}>
|
<Form.Section text={t('SSRF防护设置')}>
|
||||||
<Text extraText={t('SSRF防护详细说明')}>
|
<Text title={t('SSRF防护详细说明')}>
|
||||||
{t('配置服务器端请求伪造(SSRF)防护,用于保护内网资源安全')}
|
{t('配置服务器端请求伪造(SSRF)防护,用于保护内网资源安全')}
|
||||||
</Text>
|
</Text>
|
||||||
<Row
|
<Row
|
||||||
|
|||||||
@@ -193,7 +193,7 @@ const TwoFASetting = ({ t }) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 通用复制函数
|
// 通用复制函数:走公共剪贴板封装(HTTP 部署下 navigator.clipboard 为 undefined 时降级 execCommand)
|
||||||
const copyTextToClipboard = (text, successMessage = t('已复制到剪贴板')) => {
|
const copyTextToClipboard = (text, successMessage = t('已复制到剪贴板')) => {
|
||||||
writeClipboardText(text)
|
writeClipboardText(text)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
import { theme } from 'antd';
|
||||||
import { Button, Progress, Tag, Timeline, Typography } from '@/components/ui';
|
import { Button, Progress, Tag, Timeline, Typography } from '@/components/ui';
|
||||||
import {
|
import {
|
||||||
IconAlertTriangle,
|
IconAlertTriangle,
|
||||||
@@ -35,13 +36,14 @@ import './skill-components.css';
|
|||||||
|
|
||||||
const { Text, Title, Paragraph } = Typography;
|
const { Text, Title, Paragraph } = Typography;
|
||||||
|
|
||||||
const SemanticTag = ({ value, fallback, className = '' }) => {
|
const SemanticTag = ({ value, fallback, className = '', style }) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const token = getSkillTagToken(value);
|
const token = getSkillTagToken(value);
|
||||||
return (
|
return (
|
||||||
<Tag
|
<Tag
|
||||||
color={token.color}
|
color={token.color}
|
||||||
className={className}
|
className={className}
|
||||||
|
style={style}
|
||||||
aria-label={t(fallback || token.label)}
|
aria-label={t(fallback || token.label)}
|
||||||
>
|
>
|
||||||
{t(fallback || token.label)}
|
{t(fallback || token.label)}
|
||||||
@@ -62,20 +64,26 @@ export const ScopeSourceBadge = ({ source, detail }) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const LicenseBadge = ({ expression, decision }) => (
|
export const LicenseBadge = ({ expression, decision }) => {
|
||||||
<span className='skill-license-badge'>
|
const { token } = theme.useToken();
|
||||||
<SemanticTag
|
const value =
|
||||||
value={
|
decision === 'blocked'
|
||||||
decision === 'blocked'
|
? 'deny'
|
||||||
? 'deny'
|
: decision === 'approved'
|
||||||
: decision === 'approved'
|
? 'allow'
|
||||||
? 'allow'
|
: 'license_pending';
|
||||||
: 'license_pending'
|
const { color } = getSkillTagToken(value);
|
||||||
}
|
return (
|
||||||
fallback={expression || '许可证未知'}
|
<span className='skill-license-badge'>
|
||||||
/>
|
<SemanticTag
|
||||||
</span>
|
value={value}
|
||||||
);
|
fallback={expression || '许可证未知'}
|
||||||
|
// 第 9 档在浅色下更深、暗色下更亮,保证小字号许可证的对比度。
|
||||||
|
style={{ color: token[`${color}-9`] }}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
export const RiskBadge = ({ conclusion }) => (
|
export const RiskBadge = ({ conclusion }) => (
|
||||||
<SemanticTag
|
<SemanticTag
|
||||||
@@ -168,6 +176,7 @@ export const GrayscaleProgress = ({ percent = 0, label }) => (
|
|||||||
);
|
);
|
||||||
|
|
||||||
export const SkillDetailSideSheet = ({
|
export const SkillDetailSideSheet = ({
|
||||||
|
className,
|
||||||
visible,
|
visible,
|
||||||
onCancel,
|
onCancel,
|
||||||
title,
|
title,
|
||||||
@@ -175,6 +184,7 @@ export const SkillDetailSideSheet = ({
|
|||||||
footer,
|
footer,
|
||||||
}) => (
|
}) => (
|
||||||
<OrgSideSheet
|
<OrgSideSheet
|
||||||
|
className={className}
|
||||||
visible={visible}
|
visible={visible}
|
||||||
onCancel={onCancel}
|
onCancel={onCancel}
|
||||||
title={title}
|
title={title}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
|
|||||||
|
|
||||||
export const SKILL_TAG_TOKENS = Object.freeze({
|
export const SKILL_TAG_TOKENS = Object.freeze({
|
||||||
pending_import: { color: 'grey', label: '待导入' },
|
pending_import: { color: 'grey', label: '待导入' },
|
||||||
license_pending: { color: 'amber', label: '许可证待审核' },
|
license_pending: { color: 'gold', label: '许可证待审核' },
|
||||||
scan_pending: { color: 'orange', label: '待云端化改写' },
|
scan_pending: { color: 'orange', label: '待云端化改写' },
|
||||||
review_pending: { color: 'blue', label: '待审核' },
|
review_pending: { color: 'blue', label: '待审核' },
|
||||||
published: { color: 'green', label: '已发布' },
|
published: { color: 'green', label: '已发布' },
|
||||||
|
|||||||
@@ -0,0 +1,201 @@
|
|||||||
|
/*
|
||||||
|
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, { useCallback, useEffect, useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
Button,
|
||||||
|
Empty,
|
||||||
|
Modal,
|
||||||
|
Spin,
|
||||||
|
Switch,
|
||||||
|
Tag,
|
||||||
|
Typography,
|
||||||
|
} from 'antd';
|
||||||
|
import { showError, showSuccess } from '../../helpers';
|
||||||
|
import { getConsents, updateConsent } from './api';
|
||||||
|
|
||||||
|
const { Text } = Typography;
|
||||||
|
|
||||||
|
const kindText = (t, kind) =>
|
||||||
|
({
|
||||||
|
judge: {
|
||||||
|
title: t('智能判定'),
|
||||||
|
desc: t(
|
||||||
|
'把脱敏、截断后的请求片段发送给境外判定服务(Jev),用于选择合适的模型。',
|
||||||
|
),
|
||||||
|
},
|
||||||
|
eval: {
|
||||||
|
title: t('质量打分'),
|
||||||
|
desc: t(
|
||||||
|
'把脱敏、截断后的请求与回答片段发送给境外判定服务,用于质量评估。',
|
||||||
|
),
|
||||||
|
},
|
||||||
|
shadow: {
|
||||||
|
title: t('影子评审'),
|
||||||
|
desc: t('把正式脱敏后的请求发送给基线模型和评审模型,用于对比质量。'),
|
||||||
|
},
|
||||||
|
replay: {
|
||||||
|
title: t('回放留存'),
|
||||||
|
desc: t('把脱敏后的请求加密留存最多 90 天,用于离线评估。'),
|
||||||
|
},
|
||||||
|
})[kind] || { title: kind, desc: '' };
|
||||||
|
|
||||||
|
// 同意记录(§9.5)。企业同意只能由真实的企业所有者操作。
|
||||||
|
// onChange:授权状态变化后回调最新列表(企业中心"仅授权模式"据此刷新入口)
|
||||||
|
const ConsentPanel = ({ mode, orgId, canWrite = true, onChange }) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [rows, setRows] = useState([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError('');
|
||||||
|
try {
|
||||||
|
setRows((await getConsents(mode, orgId)) || []);
|
||||||
|
} catch (e) {
|
||||||
|
setError(e?.message || t('加载失败'));
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [mode, orgId, t]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
const toggle = (row, granted) => {
|
||||||
|
const text = kindText(t, row.kind);
|
||||||
|
const doIt = async () => {
|
||||||
|
try {
|
||||||
|
const next = await updateConsent(mode, orgId, row.kind, granted);
|
||||||
|
setRows(next);
|
||||||
|
onChange?.(next);
|
||||||
|
showSuccess(granted ? t('已授权') : t('已撤回'));
|
||||||
|
} catch (e) {
|
||||||
|
if (e?.message) showError(e.message);
|
||||||
|
load(); // 写入可能已成功、只是回读失败:重新拉取,避免开关停在旧状态
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if (!granted) return doIt();
|
||||||
|
Modal.confirm({
|
||||||
|
title: `${t('确认授权')} · ${text.title}`,
|
||||||
|
content: (
|
||||||
|
<div className='flex flex-col gap-2'>
|
||||||
|
<Text>{text.desc}</Text>
|
||||||
|
{row.overseas && (
|
||||||
|
<Alert
|
||||||
|
type='warning'
|
||||||
|
showIcon
|
||||||
|
title={t(
|
||||||
|
'该项涉及数据出境(发送到境外服务),可随时撤回,撤回后立即生效。',
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{mode === 'org' && (
|
||||||
|
<Text type='secondary' className='smart-router-sub'>
|
||||||
|
{t('授权后会覆盖企业「数据安全」「不用于训练」功能的默认保护。')}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
onOk: doIt,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading)
|
||||||
|
return (
|
||||||
|
<div className='smart-router-state'>
|
||||||
|
<Spin />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
if (error)
|
||||||
|
return (
|
||||||
|
<Alert
|
||||||
|
type='error'
|
||||||
|
showIcon
|
||||||
|
title={error}
|
||||||
|
action={
|
||||||
|
<Button size='small' onClick={load}>
|
||||||
|
{t('重试')}
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
const available = rows.filter((r) => r.available);
|
||||||
|
if (available.length === 0)
|
||||||
|
return (
|
||||||
|
<Empty
|
||||||
|
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||||
|
description={t('平台暂未开放需要授权的智能路由功能')}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='smart-router-stack'>
|
||||||
|
{!canWrite && (
|
||||||
|
<Alert
|
||||||
|
type='info'
|
||||||
|
showIcon
|
||||||
|
title={t('企业出境同意只能由企业所有者操作。')}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{available.map((r) => {
|
||||||
|
const text = kindText(t, r.kind);
|
||||||
|
return (
|
||||||
|
<div key={r.kind} className='smart-router-consent-row'>
|
||||||
|
<div className='min-w-0'>
|
||||||
|
<div className='smart-router-consent-head'>
|
||||||
|
<Text strong>{text.title}</Text>
|
||||||
|
{r.overseas && (
|
||||||
|
<Tag color='warning' variant='filled'>
|
||||||
|
{t('境外处理')}
|
||||||
|
</Tag>
|
||||||
|
)}
|
||||||
|
{r.valid ? (
|
||||||
|
<Tag color='success' variant='filled'>
|
||||||
|
{t('已生效')}
|
||||||
|
</Tag>
|
||||||
|
) : r.granted ? (
|
||||||
|
<Tag color='default' variant='filled'>
|
||||||
|
{t('文案已更新,需要重新授权')}
|
||||||
|
</Tag>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<Text type='secondary' className='smart-router-sub'>
|
||||||
|
{text.desc}
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
size='small'
|
||||||
|
checked={r.valid}
|
||||||
|
disabled={!canWrite}
|
||||||
|
onChange={(v) => toggle(r, v)}
|
||||||
|
aria-label={text.title}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ConsentPanel;
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
/*
|
||||||
|
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, { useCallback, useEffect, useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Button, Empty, Tag } from 'antd';
|
||||||
|
import { Table } from '@/components/ui';
|
||||||
|
import { ConsoleAlert as Alert } from '../console/ConsolePrimitives';
|
||||||
|
import { listDecisions } from './api';
|
||||||
|
import { gateText, jevReasonText, srcText } from './labels';
|
||||||
|
|
||||||
|
// 判定明细:只读 router_eval_records(§12.3)
|
||||||
|
const DecisionTable = ({ mode, orgId }) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [data, setData] = useState({ items: [], total: 0 });
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError('');
|
||||||
|
try {
|
||||||
|
setData(
|
||||||
|
(await listDecisions(mode, orgId, { p: page, page_size: 20 })) || {
|
||||||
|
items: [],
|
||||||
|
total: 0,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
setError(e?.message || t('加载失败'));
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [mode, orgId, page, t]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
const columns = [
|
||||||
|
{
|
||||||
|
title: t('时间'),
|
||||||
|
dataIndex: 'created_at',
|
||||||
|
width: 180,
|
||||||
|
render: (v) => (
|
||||||
|
<span className='smart-router-num'>
|
||||||
|
{new Date(v * 1000).toLocaleString()}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: t('虚拟模型'),
|
||||||
|
dataIndex: 'virtual_model',
|
||||||
|
width: 180,
|
||||||
|
render: (v) => <span className='smart-router-mono'>{v}</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: t('实际模型'),
|
||||||
|
dataIndex: 'actual_model',
|
||||||
|
width: 200,
|
||||||
|
render: (v) => <span className='smart-router-mono'>{v || '-'}</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: t('判定来源'),
|
||||||
|
dataIndex: 'src',
|
||||||
|
width: 200,
|
||||||
|
render: (v, r) => (
|
||||||
|
<Tag variant='filled' color={v === 'error' ? 'error' : 'blue'}>
|
||||||
|
{srcText(t, v)}
|
||||||
|
{r.reason ? ` · ${jevReasonText(t, r.reason)}` : ''}
|
||||||
|
</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: t('任务 / 难度档'),
|
||||||
|
key: 'task',
|
||||||
|
width: 140,
|
||||||
|
render: (_, r) => `${r.task || '-'} / ${r.difficulty_tier}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: t('合规闸门'),
|
||||||
|
dataIndex: 'gate',
|
||||||
|
width: 140,
|
||||||
|
render: (v) => gateText(t, v),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: t('状态码'),
|
||||||
|
dataIndex: 'status_code',
|
||||||
|
width: 90,
|
||||||
|
align: 'right',
|
||||||
|
render: (v) => <span className='smart-router-num'>{v}</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: t('判定耗时'),
|
||||||
|
dataIndex: 'judge_ms',
|
||||||
|
width: 110,
|
||||||
|
align: 'right',
|
||||||
|
render: (v) => (
|
||||||
|
<span className='smart-router-num'>{v ? `${v} ms` : '-'}</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
if (error)
|
||||||
|
return (
|
||||||
|
<Alert
|
||||||
|
type='error'
|
||||||
|
showIcon
|
||||||
|
title={error}
|
||||||
|
action={
|
||||||
|
<Button size='small' onClick={load}>
|
||||||
|
{t('重试')}
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Table
|
||||||
|
rowKey='id'
|
||||||
|
size='middle'
|
||||||
|
loading={loading}
|
||||||
|
columns={columns}
|
||||||
|
dataSource={data.items || []}
|
||||||
|
scroll={{ x: 'max-content' }}
|
||||||
|
empty={
|
||||||
|
<Empty
|
||||||
|
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||||
|
description={t('还没有智能路由请求')}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
pagination={{
|
||||||
|
// 接口固定 page_size=20,不提供每页条数切换
|
||||||
|
current: page,
|
||||||
|
pageSize: 20,
|
||||||
|
total: data.total || 0,
|
||||||
|
size: 'small',
|
||||||
|
showSizeChanger: false,
|
||||||
|
showTotal: (total) => t('共 {{total}} 条', { total }),
|
||||||
|
onChange: setPage,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default DecisionTable;
|
||||||
@@ -0,0 +1,547 @@
|
|||||||
|
/*
|
||||||
|
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, { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
InputNumber,
|
||||||
|
Modal,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Spin,
|
||||||
|
Switch,
|
||||||
|
Tag,
|
||||||
|
Typography,
|
||||||
|
} from 'antd';
|
||||||
|
import { ConsoleAlert as Alert } from '../console/ConsolePrimitives';
|
||||||
|
import { showError, showSuccess } from '../../helpers';
|
||||||
|
import { getAdminStatus, loadOptions, saveOption, setJevKey } from './api';
|
||||||
|
|
||||||
|
const { Text } = Typography;
|
||||||
|
const { TextArea } = Input;
|
||||||
|
const PREFIX = 'smart_router_setting.';
|
||||||
|
|
||||||
|
// 字段定义:type 决定编辑控件;compliance=true 的是合规相关(只有 root 能改,后端 rootOnlyOptionKeys)
|
||||||
|
const FIELDS = [
|
||||||
|
{ key: 'enabled', type: 'bool', label: '总开关', section: 'main' },
|
||||||
|
{
|
||||||
|
key: 'rollout_percent',
|
||||||
|
type: 'int',
|
||||||
|
label: '灰度比例(%)',
|
||||||
|
min: 0,
|
||||||
|
max: 100,
|
||||||
|
section: 'main',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'single_node_ack',
|
||||||
|
type: 'bool',
|
||||||
|
label: '确认为单节点部署(Redis 未启用时必填)',
|
||||||
|
section: 'main',
|
||||||
|
compliance: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'max_profiles_per_user',
|
||||||
|
type: 'int',
|
||||||
|
label: '每人最多个人集合数',
|
||||||
|
min: 0,
|
||||||
|
max: 100,
|
||||||
|
section: 'main',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'jev_egress_allowed',
|
||||||
|
type: 'bool',
|
||||||
|
label: '允许调用 Jev(数据出境,合规评估通过后开启)',
|
||||||
|
section: 'jev',
|
||||||
|
compliance: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'jev_primary',
|
||||||
|
type: 'select',
|
||||||
|
label: '主通道',
|
||||||
|
options: ['typesafe', 'openrouter'],
|
||||||
|
section: 'jev',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'jev_model_typesafe',
|
||||||
|
type: 'str',
|
||||||
|
label: 'TypeSafe 模型版本',
|
||||||
|
section: 'jev',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'jev_model_openrouter',
|
||||||
|
type: 'str',
|
||||||
|
label: 'OpenRouter 模型版本',
|
||||||
|
section: 'jev',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'judge_budget_ms',
|
||||||
|
type: 'int',
|
||||||
|
label: '判定总预算(毫秒,以国内压测 P95 为准)',
|
||||||
|
min: 20,
|
||||||
|
max: 5000,
|
||||||
|
section: 'jev',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'judge_hedge_enabled',
|
||||||
|
type: 'bool',
|
||||||
|
label: '主备对冲',
|
||||||
|
section: 'jev',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'judge_hedge_after_ms',
|
||||||
|
type: 'int',
|
||||||
|
label: '对冲触发(毫秒,取压测 P80)',
|
||||||
|
min: 1,
|
||||||
|
max: 5000,
|
||||||
|
section: 'jev',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'state_max_bytes',
|
||||||
|
type: 'int',
|
||||||
|
label: '发给 Jev 的内容上限(字节)',
|
||||||
|
min: 1000,
|
||||||
|
max: 30000,
|
||||||
|
section: 'jev',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'default_tau_quality',
|
||||||
|
type: 'str',
|
||||||
|
label: '质量优先 τ1,τ2,τ3',
|
||||||
|
section: 'judge',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'default_tau_balanced',
|
||||||
|
type: 'str',
|
||||||
|
label: '平衡 τ1,τ2,τ3',
|
||||||
|
section: 'judge',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'default_tau_cost',
|
||||||
|
type: 'str',
|
||||||
|
label: '成本优先 τ1,τ2,τ3',
|
||||||
|
section: 'judge',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'skill_injection_token_reserve',
|
||||||
|
type: 'int',
|
||||||
|
label: 'skill 注入预留 token',
|
||||||
|
min: 0,
|
||||||
|
max: 100000,
|
||||||
|
section: 'judge',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'strip_incompatible_channel_types',
|
||||||
|
type: 'str',
|
||||||
|
label: '未通过剥离兼容性验证的渠道类型(逗号分隔)',
|
||||||
|
section: 'judge',
|
||||||
|
compliance: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'rules_judge_config',
|
||||||
|
type: 'json',
|
||||||
|
label: '规则判定器关键词与分数(JSON,留空使用内置)',
|
||||||
|
section: 'judge',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'consent_text_versions',
|
||||||
|
type: 'json',
|
||||||
|
label: '同意文案版本(JSON,如 {"judge":{"v":1,"overseas":true}})',
|
||||||
|
section: 'consent',
|
||||||
|
compliance: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'router_eval_retention_days',
|
||||||
|
type: 'int',
|
||||||
|
label: '判定明细保留天数',
|
||||||
|
min: 1,
|
||||||
|
max: 365,
|
||||||
|
section: 'retention',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'simulate_daily_cap_per_user',
|
||||||
|
type: 'int',
|
||||||
|
label: '试路由每人每日上限',
|
||||||
|
min: 0,
|
||||||
|
max: 100000,
|
||||||
|
section: 'retention',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'simulate_daily_cap_per_org',
|
||||||
|
type: 'int',
|
||||||
|
label: '试路由每企业每日上限',
|
||||||
|
min: 0,
|
||||||
|
max: 1000000,
|
||||||
|
section: 'retention',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'max_profiles_per_org',
|
||||||
|
type: 'int',
|
||||||
|
label: '每个企业最多集合数',
|
||||||
|
min: 0,
|
||||||
|
max: 1000,
|
||||||
|
section: 'retention',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'jev_daily_cap_per_user',
|
||||||
|
type: 'int',
|
||||||
|
label: 'Jev 判定每人每日上限(0 不限)',
|
||||||
|
min: 0,
|
||||||
|
max: 10000000,
|
||||||
|
section: 'retention',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'jev_daily_cap_per_org',
|
||||||
|
type: 'int',
|
||||||
|
label: 'Jev 判定每企业每日上限(0 不限)',
|
||||||
|
min: 0,
|
||||||
|
max: 100000000,
|
||||||
|
section: 'retention',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const SECTIONS = [
|
||||||
|
['main', '总控'],
|
||||||
|
['jev', 'Jev 判定'],
|
||||||
|
['judge', '判定参数'],
|
||||||
|
['consent', '同意文案'],
|
||||||
|
['retention', '保留与限流'],
|
||||||
|
];
|
||||||
|
|
||||||
|
// 保存顺序:前置条件(single_node_ack)必须先于依赖它的总开关保存
|
||||||
|
const SAVE_ORDER = ['single_node_ack', 'consent_text_versions'];
|
||||||
|
|
||||||
|
const GlobalSettings = () => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [values, setValues] = useState({});
|
||||||
|
const [original, setOriginal] = useState({});
|
||||||
|
const [status, setStatus] = useState(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [loadError, setLoadError] = useState('');
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [keys, setKeys] = useState({ typesafe: '', openrouter: '' });
|
||||||
|
const tRef = useRef(t);
|
||||||
|
tRef.current = t;
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setLoadError('');
|
||||||
|
try {
|
||||||
|
const data = await loadOptions();
|
||||||
|
const v = {};
|
||||||
|
(data || []).forEach((item) => {
|
||||||
|
if (item.key.startsWith(PREFIX))
|
||||||
|
v[item.key.slice(PREFIX.length)] = item.value;
|
||||||
|
});
|
||||||
|
setValues(v);
|
||||||
|
setOriginal(v);
|
||||||
|
setStatus(await getAdminStatus());
|
||||||
|
} catch (e) {
|
||||||
|
setLoadError(e?.message || tRef.current('加载失败'));
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []); // 不依赖 t:切换语言不能重新加载并丢掉未保存的编辑
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
const save = async () => {
|
||||||
|
const changed = FIELDS.filter(
|
||||||
|
(f) => String(values[f.key] ?? '') !== String(original[f.key] ?? ''),
|
||||||
|
).sort((a, b) => {
|
||||||
|
const ia = SAVE_ORDER.indexOf(a.key);
|
||||||
|
const ib = SAVE_ORDER.indexOf(b.key);
|
||||||
|
return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib);
|
||||||
|
});
|
||||||
|
if (changed.length === 0) {
|
||||||
|
showSuccess(t('配置未修改'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSaving(true);
|
||||||
|
const saved = {};
|
||||||
|
try {
|
||||||
|
for (const f of changed) {
|
||||||
|
try {
|
||||||
|
await saveOption(PREFIX + f.key, String(values[f.key] ?? ''));
|
||||||
|
saved[f.key] = values[f.key];
|
||||||
|
} catch (e) {
|
||||||
|
showError(`${t(f.label)} · ${e?.message || ''}`);
|
||||||
|
// 已保存的项更新基线,未保存的编辑保留在表单里,便于修改后重试
|
||||||
|
setOriginal((o) => ({ ...o, ...saved }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
showSuccess(t('已保存'));
|
||||||
|
await load();
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveKey = async (provider, clear = false) => {
|
||||||
|
const run = async () => {
|
||||||
|
try {
|
||||||
|
await setJevKey(provider, keys[provider], clear);
|
||||||
|
setKeys((k) => ({ ...k, [provider]: '' }));
|
||||||
|
showSuccess(clear ? t('已清除') : t('已保存'));
|
||||||
|
setStatus(await getAdminStatus());
|
||||||
|
} catch (e) {
|
||||||
|
showError(e?.message || t('保存失败,请稍后重试'));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if (!clear) return run();
|
||||||
|
Modal.confirm({
|
||||||
|
title: t('确认清除密钥?'),
|
||||||
|
content: t('清除后该通道无法调用 Jev,判定会降级为规则判定。'),
|
||||||
|
okButtonProps: { danger: true },
|
||||||
|
onOk: run,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderField = (f) => {
|
||||||
|
const v = values[f.key];
|
||||||
|
const set = (nv) => setValues((s) => ({ ...s, [f.key]: nv }));
|
||||||
|
switch (f.type) {
|
||||||
|
case 'bool':
|
||||||
|
return (
|
||||||
|
<Switch
|
||||||
|
checked={v === 'true'}
|
||||||
|
onChange={(c) => set(c ? 'true' : 'false')}
|
||||||
|
aria-label={t(f.label)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
case 'int':
|
||||||
|
return (
|
||||||
|
<InputNumber
|
||||||
|
className='smart-router-setting-control'
|
||||||
|
min={f.min}
|
||||||
|
max={f.max}
|
||||||
|
value={Number(v) || 0}
|
||||||
|
onChange={(raw) => {
|
||||||
|
// antd 清空时回调 null,按原 Semi 的空串语义回落到最小值
|
||||||
|
const n = raw ?? '';
|
||||||
|
set(
|
||||||
|
String(
|
||||||
|
Number.isFinite(Number(n)) && n !== ''
|
||||||
|
? Number(n)
|
||||||
|
: (f.min ?? 0),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
case 'select':
|
||||||
|
return (
|
||||||
|
<Select
|
||||||
|
className='smart-router-setting-control'
|
||||||
|
value={v}
|
||||||
|
options={f.options.map((o) => ({ label: o, value: o }))}
|
||||||
|
onChange={set}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
case 'json':
|
||||||
|
return (
|
||||||
|
<TextArea
|
||||||
|
className='smart-router-mono'
|
||||||
|
autoSize={{ minRows: 2, maxRows: 10 }}
|
||||||
|
value={v}
|
||||||
|
onChange={(e) => set(e.target.value)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return (
|
||||||
|
<Input
|
||||||
|
className='smart-router-setting-control'
|
||||||
|
value={v}
|
||||||
|
onChange={(e) => set(e.target.value)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading)
|
||||||
|
return (
|
||||||
|
<div className='smart-router-state'>
|
||||||
|
<Spin />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
if (loadError)
|
||||||
|
return (
|
||||||
|
<Alert
|
||||||
|
type='error'
|
||||||
|
showIcon
|
||||||
|
title={loadError}
|
||||||
|
action={
|
||||||
|
<Button size='small' onClick={load}>
|
||||||
|
{t('重试')}
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='smart-router-stack'>
|
||||||
|
{status && (
|
||||||
|
<div className='smart-router-card'>
|
||||||
|
<div className='smart-router-card-title'>{t('运行状态')}</div>
|
||||||
|
<Space size={8} wrap>
|
||||||
|
<Tag color={status.session_store_ready ? 'success' : 'error'}>
|
||||||
|
{status.session_store_ready
|
||||||
|
? t('共享会话存储就绪')
|
||||||
|
: t('共享会话存储未就绪')}
|
||||||
|
</Tag>
|
||||||
|
<Tag color={status.redis_enabled ? 'success' : 'default'}>
|
||||||
|
Redis {status.redis_enabled ? t('已启用') : t('未启用')}
|
||||||
|
</Tag>
|
||||||
|
<Tag color={status.typesafe_key_set ? 'success' : 'default'}>
|
||||||
|
TypeSafe{' '}
|
||||||
|
{status.typesafe_key_set ? t('密钥已设置') : t('未设置密钥')}
|
||||||
|
</Tag>
|
||||||
|
<Tag color={status.openrouter_key_set ? 'success' : 'default'}>
|
||||||
|
OpenRouter{' '}
|
||||||
|
{status.openrouter_key_set ? t('密钥已设置') : t('未设置密钥')}
|
||||||
|
</Tag>
|
||||||
|
{status.typesafe_breaker && (
|
||||||
|
<Tag color='error'>{t('TypeSafe 熔断中')}</Tag>
|
||||||
|
)}
|
||||||
|
{status.openrouter_breaker && (
|
||||||
|
<Tag color='error'>{t('OpenRouter 熔断中')}</Tag>
|
||||||
|
)}
|
||||||
|
<Tag>
|
||||||
|
{t('会话写入失败')}{' '}
|
||||||
|
<span className='smart-router-num'>
|
||||||
|
{status.session_write_fail}
|
||||||
|
</span>
|
||||||
|
</Tag>
|
||||||
|
<Tag>
|
||||||
|
{t('评估记录丢弃')}{' '}
|
||||||
|
<span className='smart-router-num'>{status.eval_dropped}</span>
|
||||||
|
</Tag>
|
||||||
|
<Tag>
|
||||||
|
{t('会话读取失败')}{' '}
|
||||||
|
<span className='smart-router-num'>
|
||||||
|
{status.session_read_fail}
|
||||||
|
</span>
|
||||||
|
</Tag>
|
||||||
|
<Tag>
|
||||||
|
{t('Jev 降级次数')}{' '}
|
||||||
|
<span className='smart-router-num'>{status.jev_fallback}</span>
|
||||||
|
</Tag>
|
||||||
|
<Tag color={status.not_ready ? 'warning' : 'default'}>
|
||||||
|
{t('存储未就绪拒绝')}{' '}
|
||||||
|
<span className='smart-router-num'>{status.not_ready}</span>
|
||||||
|
</Tag>
|
||||||
|
</Space>
|
||||||
|
<div className='smart-router-section'>
|
||||||
|
<Text type='secondary' className='smart-router-sub'>
|
||||||
|
{t('以上计数为当前节点进程内累计值,进程重启后清零')}
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<Alert
|
||||||
|
type='warning'
|
||||||
|
showIcon
|
||||||
|
title={t(
|
||||||
|
'标注「合规」的配置项只有超级管理员可以修改。开启 Jev 出境前须完成合规评估。',
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{SECTIONS.map(([sec, title]) => (
|
||||||
|
<div key={sec} className='smart-router-card'>
|
||||||
|
<div className='smart-router-card-title'>{t(title)}</div>
|
||||||
|
{/* 受控字段沿用 values 状态,Form 只提供竖排标签布局,不接管取值与提交 */}
|
||||||
|
<Form
|
||||||
|
layout='vertical'
|
||||||
|
component='div'
|
||||||
|
requiredMark={false}
|
||||||
|
className='smart-router-settings-form'
|
||||||
|
>
|
||||||
|
{FIELDS.filter((f) => f.section === sec).map((f) => (
|
||||||
|
<Form.Item
|
||||||
|
key={f.key}
|
||||||
|
label={
|
||||||
|
<span className='smart-router-field-label'>
|
||||||
|
{t(f.label)}
|
||||||
|
{f.compliance && (
|
||||||
|
<Tag color='warning' variant='filled'>
|
||||||
|
{t('合规')}
|
||||||
|
</Tag>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{renderField(f)}
|
||||||
|
</Form.Item>
|
||||||
|
))}
|
||||||
|
{sec === 'jev' &&
|
||||||
|
['typesafe', 'openrouter'].map((p) => (
|
||||||
|
<Form.Item
|
||||||
|
key={p}
|
||||||
|
label={
|
||||||
|
<span className='smart-router-field-label'>
|
||||||
|
{p === 'typesafe'
|
||||||
|
? t('TypeSafe 密钥')
|
||||||
|
: t('OpenRouter 密钥')}
|
||||||
|
({t('加密存储,只有超级管理员可修改')})
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Space size={8} wrap className='smart-router-key-tools'>
|
||||||
|
<Input.Password
|
||||||
|
className='smart-router-key-input'
|
||||||
|
placeholder={t('输入新密钥;留空表示不修改')}
|
||||||
|
value={keys[p]}
|
||||||
|
onChange={(e) =>
|
||||||
|
setKeys((k) => ({ ...k, [p]: e.target.value }))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Button onClick={() => saveKey(p)} disabled={!keys[p]}>
|
||||||
|
{t('保存密钥')}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
danger
|
||||||
|
disabled={
|
||||||
|
!(p === 'typesafe'
|
||||||
|
? status?.typesafe_key_set
|
||||||
|
: status?.openrouter_key_set)
|
||||||
|
}
|
||||||
|
onClick={() => saveKey(p, true)}
|
||||||
|
>
|
||||||
|
{t('清除')}
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
</Form.Item>
|
||||||
|
))}
|
||||||
|
</Form>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div>
|
||||||
|
<Button type='primary' loading={saving} onClick={save}>
|
||||||
|
{t('保存设置')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default GlobalSettings;
|
||||||
@@ -0,0 +1,954 @@
|
|||||||
|
/*
|
||||||
|
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, { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
Button,
|
||||||
|
Checkbox,
|
||||||
|
Collapse,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
InputNumber,
|
||||||
|
Modal,
|
||||||
|
Select,
|
||||||
|
Switch,
|
||||||
|
Typography,
|
||||||
|
} from 'antd';
|
||||||
|
import { ConsoleDrawer as Drawer } from '../console/ConsolePrimitives';
|
||||||
|
import { Plus, Trash2 } from '../common/icons/ActionIcons';
|
||||||
|
import { showError, showSuccess } from '../../helpers';
|
||||||
|
import { saveProfile } from './api';
|
||||||
|
|
||||||
|
const { TextArea } = Input;
|
||||||
|
|
||||||
|
// 等价 Semi Select 的 filter + allowCreate:可搜索,输入的新模型名作为临时选项出现,
|
||||||
|
// 只有选中后才回调 onChange(与原行为一致,不在每次键入时写值)。
|
||||||
|
const CreatableSelect = ({ options, value, onChange, ...props }) => {
|
||||||
|
const [search, setSearch] = useState('');
|
||||||
|
const keyword = search.trim();
|
||||||
|
const merged =
|
||||||
|
keyword && !options.some((o) => o.value === keyword)
|
||||||
|
? [...options, { label: keyword, value: keyword }]
|
||||||
|
: options;
|
||||||
|
return (
|
||||||
|
<Select
|
||||||
|
{...props}
|
||||||
|
showSearch
|
||||||
|
optionFilterProp='label'
|
||||||
|
value={value}
|
||||||
|
options={merged}
|
||||||
|
onSearch={setSearch}
|
||||||
|
onChange={(v) => {
|
||||||
|
setSearch('');
|
||||||
|
onChange(v);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const { Text } = Typography;
|
||||||
|
|
||||||
|
const RULES_LABELS = [
|
||||||
|
'coding',
|
||||||
|
'math',
|
||||||
|
'translate',
|
||||||
|
'extract',
|
||||||
|
'analysis',
|
||||||
|
'writing',
|
||||||
|
'chat',
|
||||||
|
'general',
|
||||||
|
];
|
||||||
|
|
||||||
|
const LABEL_PATTERN = /^[a-z0-9_]{1,32}$/;
|
||||||
|
|
||||||
|
let uidSeq = 0;
|
||||||
|
const uid = () => `l${Date.now().toString(36)}${(uidSeq += 1)}`;
|
||||||
|
|
||||||
|
const defaultLabels = (t) =>
|
||||||
|
[
|
||||||
|
['coding', '编写、修改、调试、解释代码'],
|
||||||
|
['math', '数学计算、推导、证明'],
|
||||||
|
['writing', '创作、改写、润色长文本'],
|
||||||
|
['analysis', '数据分析、方案对比、专业问答'],
|
||||||
|
['extract', '信息抽取、格式转换、分类'],
|
||||||
|
['translate', '翻译'],
|
||||||
|
['chat', '闲聊、简单查询'],
|
||||||
|
['general', '无法归入以上类别的请求'],
|
||||||
|
].map(([name, desc]) => ({
|
||||||
|
id: uid(),
|
||||||
|
name,
|
||||||
|
desc: t(desc),
|
||||||
|
rules_label: '',
|
||||||
|
}));
|
||||||
|
|
||||||
|
const emptyCaps = {
|
||||||
|
vision: false,
|
||||||
|
tools: false,
|
||||||
|
json_mode: false,
|
||||||
|
reasoning: false,
|
||||||
|
max_context: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseCaps = (raw) => {
|
||||||
|
if (!raw) return { ...emptyCaps };
|
||||||
|
try {
|
||||||
|
return {
|
||||||
|
...emptyCaps,
|
||||||
|
...(typeof raw === 'string' ? JSON.parse(raw) : raw),
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
return { ...emptyCaps };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const emptyRow = () => ['', '', '', ''];
|
||||||
|
|
||||||
|
// 矩阵按标签的稳定 id 存储:改名时不搬动行,保存时再按名字重建(避免改名到已有名字时覆盖别的行)
|
||||||
|
const toState = (profile, t) => {
|
||||||
|
if (!profile) {
|
||||||
|
const labels = defaultLabels(t);
|
||||||
|
return {
|
||||||
|
slug: '',
|
||||||
|
name: '',
|
||||||
|
description: '',
|
||||||
|
strategy: 'balanced',
|
||||||
|
tier_thresholds: '',
|
||||||
|
min_task_conf: 0,
|
||||||
|
reasoning_threshold: 0,
|
||||||
|
reasoning_model: '',
|
||||||
|
default_model: '',
|
||||||
|
baseline_model: '',
|
||||||
|
sticky_enabled: true,
|
||||||
|
sticky_ttl_sec: 1800,
|
||||||
|
jev_allowed: false,
|
||||||
|
status: 1,
|
||||||
|
labels,
|
||||||
|
matrix: Object.fromEntries(labels.map((l) => [l.id, emptyRow()])),
|
||||||
|
rules: '[]',
|
||||||
|
models: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const labels = (profile.task_labels_obj || []).map((l) => ({
|
||||||
|
id: uid(),
|
||||||
|
name: l.name,
|
||||||
|
desc: l.desc || '',
|
||||||
|
rules_label: l.rules_label || '',
|
||||||
|
}));
|
||||||
|
const matrix = {};
|
||||||
|
labels.forEach((l) => {
|
||||||
|
const row = (profile.matrix_obj || {})[l.name] || [];
|
||||||
|
matrix[l.id] = [0, 1, 2, 3].map((i) => row[i] || '');
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
id: profile.id,
|
||||||
|
slug: profile.slug,
|
||||||
|
name: profile.name,
|
||||||
|
description: profile.description,
|
||||||
|
strategy: profile.strategy,
|
||||||
|
tier_thresholds: profile.tier_thresholds || '',
|
||||||
|
min_task_conf: profile.min_task_conf || 0,
|
||||||
|
reasoning_threshold: profile.reasoning_threshold || 0,
|
||||||
|
reasoning_model: profile.reasoning_model || '',
|
||||||
|
default_model: profile.default_model,
|
||||||
|
baseline_model: profile.baseline_model,
|
||||||
|
sticky_enabled: profile.sticky_enabled,
|
||||||
|
sticky_ttl_sec: profile.sticky_ttl_sec || 1800,
|
||||||
|
jev_allowed: profile.jev_allowed,
|
||||||
|
status: profile.status,
|
||||||
|
labels,
|
||||||
|
matrix,
|
||||||
|
rules: JSON.stringify(profile.rules_obj || [], null, 2),
|
||||||
|
models: (profile.models || []).map((m) => ({
|
||||||
|
model_name: m.model_name,
|
||||||
|
model_tier: m.model_tier,
|
||||||
|
description: m.description || '',
|
||||||
|
enabled: m.enabled,
|
||||||
|
caps: parseCaps(m.capabilities),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// 一键生成:按能力档把候选分配到 4 列(只作为初始值,§8.6)
|
||||||
|
const autoMatrix = (labels, models) => {
|
||||||
|
const enabled = models.filter((m) => m.model_name && m.enabled);
|
||||||
|
if (enabled.length === 0) return null;
|
||||||
|
const sorted = [...enabled].sort((a, b) => a.model_tier - b.model_tier);
|
||||||
|
const col = (k) => {
|
||||||
|
const hit = sorted.find((m) => m.model_tier >= k);
|
||||||
|
return (hit || sorted[sorted.length - 1]).model_name;
|
||||||
|
};
|
||||||
|
const row = [col(0), col(1), col(2), col(3)];
|
||||||
|
return Object.fromEntries(labels.map((l) => [l.id, [...row]]));
|
||||||
|
};
|
||||||
|
|
||||||
|
// 替换矩阵与角色字段中对某个候选名的引用
|
||||||
|
const replaceModelRefs = (s, from, to) => {
|
||||||
|
if (!from) return s;
|
||||||
|
const matrix = {};
|
||||||
|
Object.entries(s.matrix).forEach(([k, row]) => {
|
||||||
|
matrix[k] = row.map((c) => (c === from ? to : c));
|
||||||
|
});
|
||||||
|
const swap = (v) => (v === from ? to : v);
|
||||||
|
return {
|
||||||
|
...s,
|
||||||
|
matrix,
|
||||||
|
default_model: swap(s.default_model),
|
||||||
|
baseline_model: swap(s.baseline_model),
|
||||||
|
reasoning_model: swap(s.reasoning_model),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const ProfileEditor = ({
|
||||||
|
visible,
|
||||||
|
mode,
|
||||||
|
orgId,
|
||||||
|
profile,
|
||||||
|
candidateModels,
|
||||||
|
onClose,
|
||||||
|
onSaved,
|
||||||
|
}) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [state, setState] = useState(() => toState(profile, t));
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [activePanels, setActivePanels] = useState([
|
||||||
|
'basic',
|
||||||
|
'models',
|
||||||
|
'matrix',
|
||||||
|
'roles',
|
||||||
|
]);
|
||||||
|
// 进入编辑时 general 行的标签 id:只锁定这一行,避免改名成 general 后整行被锁死
|
||||||
|
const generalIdRef = useRef(null);
|
||||||
|
|
||||||
|
// 只在打开抽屉(或换了要编辑的集合)时重置;切换语言不能清掉未保存的编辑
|
||||||
|
const tRef = useRef(t);
|
||||||
|
tRef.current = t;
|
||||||
|
useEffect(() => {
|
||||||
|
if (visible) {
|
||||||
|
const next = toState(profile, tRef.current);
|
||||||
|
generalIdRef.current =
|
||||||
|
next.labels.find((l) => l.name === 'general')?.id || null;
|
||||||
|
setState(next);
|
||||||
|
setActivePanels(['basic', 'models', 'matrix', 'roles']);
|
||||||
|
}
|
||||||
|
}, [visible, profile]);
|
||||||
|
|
||||||
|
const set = (k, v) => setState((s) => ({ ...s, [k]: v }));
|
||||||
|
const candidateNames = useMemo(
|
||||||
|
() => state.models.map((m) => m.model_name).filter(Boolean),
|
||||||
|
[state.models],
|
||||||
|
);
|
||||||
|
const candidateOptions = candidateNames.map((m) => ({ label: m, value: m }));
|
||||||
|
const modelOptions = useMemo(
|
||||||
|
() => (candidateModels || []).map((m) => ({ label: m, value: m })),
|
||||||
|
[candidateModels],
|
||||||
|
);
|
||||||
|
const duplicateLabels = useMemo(() => {
|
||||||
|
const seen = new Set();
|
||||||
|
const dup = new Set();
|
||||||
|
state.labels.forEach((l) => {
|
||||||
|
if (seen.has(l.name)) dup.add(l.name);
|
||||||
|
seen.add(l.name);
|
||||||
|
});
|
||||||
|
return dup;
|
||||||
|
}, [state.labels]);
|
||||||
|
|
||||||
|
const updateModel = (idx, patch) =>
|
||||||
|
setState((s) => {
|
||||||
|
let next = s;
|
||||||
|
if (patch.model_name !== undefined) {
|
||||||
|
const from = s.models[idx].model_name;
|
||||||
|
const usedElsewhere = (name) =>
|
||||||
|
s.models.some((m, i) => i !== idx && m.model_name === name);
|
||||||
|
// 改名时同步替换矩阵与角色字段中的引用;新旧名字被其他行占用时不级联,避免误改别的候选的引用
|
||||||
|
if (from && !usedElsewhere(from) && !usedElsewhere(patch.model_name)) {
|
||||||
|
next = replaceModelRefs(s, from, patch.model_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const models = next.models.map((m, i) =>
|
||||||
|
i === idx ? { ...m, ...patch } : m,
|
||||||
|
);
|
||||||
|
return { ...next, models };
|
||||||
|
});
|
||||||
|
const updateCaps = (idx, patch) =>
|
||||||
|
setState((s) => ({
|
||||||
|
...s,
|
||||||
|
models: s.models.map((m, i) =>
|
||||||
|
i === idx ? { ...m, caps: { ...m.caps, ...patch } } : m,
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
const removeModel = (idx) => {
|
||||||
|
const removed = state.models[idx]?.model_name;
|
||||||
|
const general = state.matrix[generalIdRef.current] || [];
|
||||||
|
if (removed && general.includes(removed)) {
|
||||||
|
showError(t('该模型在 general 行中被引用,请先替换 general 行的单元格'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState((s) => {
|
||||||
|
const stillUsed = s.models.some(
|
||||||
|
(m, i) => i !== idx && m.model_name === removed,
|
||||||
|
);
|
||||||
|
const next = stillUsed ? s : replaceModelRefs(s, removed, '');
|
||||||
|
return { ...next, models: next.models.filter((_, i) => i !== idx) };
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateLabel = (id, patch) =>
|
||||||
|
setState((s) => ({
|
||||||
|
...s,
|
||||||
|
labels: s.labels.map((l) => (l.id === id ? { ...l, ...patch } : l)),
|
||||||
|
}));
|
||||||
|
const removeLabel = (id) =>
|
||||||
|
setState((s) => {
|
||||||
|
const matrix = { ...s.matrix };
|
||||||
|
delete matrix[id];
|
||||||
|
return { ...s, labels: s.labels.filter((l) => l.id !== id), matrix };
|
||||||
|
});
|
||||||
|
const addLabel = () =>
|
||||||
|
setState((s) => {
|
||||||
|
const names = new Set(s.labels.map((l) => l.name));
|
||||||
|
let n = s.labels.length + 1;
|
||||||
|
while (names.has(`label_${n}`)) n += 1;
|
||||||
|
const id = uid();
|
||||||
|
return {
|
||||||
|
...s,
|
||||||
|
labels: [
|
||||||
|
...s.labels,
|
||||||
|
{ id, name: `label_${n}`, desc: '', rules_label: '' },
|
||||||
|
],
|
||||||
|
matrix: { ...s.matrix, [id]: emptyRow() },
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const setCell = (id, col, value) =>
|
||||||
|
setState((s) => {
|
||||||
|
const row = [...(s.matrix[id] || emptyRow())];
|
||||||
|
row[col] = value || '';
|
||||||
|
return { ...s, matrix: { ...s.matrix, [id]: row } };
|
||||||
|
});
|
||||||
|
|
||||||
|
const applyAutoMatrix = () => {
|
||||||
|
const next = autoMatrix(state.labels, state.models);
|
||||||
|
if (!next) {
|
||||||
|
showError(t('请先添加并启用候选模型'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Modal.confirm({
|
||||||
|
title: t('一键生成(仅作为初始值)'),
|
||||||
|
content: t('会覆盖当前矩阵中的全部单元格,是否继续?'),
|
||||||
|
onOk: () => set('matrix', next),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 保存前的客户端检查:把必填项问题指向对应面板,避免只看到后端报错
|
||||||
|
const precheck = () => {
|
||||||
|
if (!state.id && !/^[a-z0-9][a-z0-9-]{0,47}$/.test(state.slug.trim())) {
|
||||||
|
return ['basic', t('短名只允许小写字母、数字和连字符,最长 48 个字符')];
|
||||||
|
}
|
||||||
|
if (state.models.some((m) => !m.model_name)) {
|
||||||
|
return ['models', t('有候选模型还没有选择模型名')];
|
||||||
|
}
|
||||||
|
if (candidateNames.length === 0)
|
||||||
|
return ['models', t('至少需要一个候选模型')];
|
||||||
|
if (new Set(candidateNames).size !== candidateNames.length) {
|
||||||
|
return ['models', t('候选模型不能重复')];
|
||||||
|
}
|
||||||
|
for (const l of state.labels) {
|
||||||
|
if (!LABEL_PATTERN.test(l.name)) {
|
||||||
|
return [
|
||||||
|
'labels',
|
||||||
|
t('任务标签只允许小写字母、数字和下划线,最长 32 个字符'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (duplicateLabels.size > 0) return ['labels', t('任务标签不能重名')];
|
||||||
|
if (!state.labels.some((l) => l.name === 'general')) {
|
||||||
|
return ['labels', t('任务标签必须包含 general')];
|
||||||
|
}
|
||||||
|
const general = state.labels.find((l) => l.name === 'general');
|
||||||
|
if ((state.matrix[general.id] || []).some((c) => !c)) {
|
||||||
|
return ['matrix', t('general 行的 4 个单元格必须全部填写')];
|
||||||
|
}
|
||||||
|
if (!state.default_model) return ['roles', t('请选择默认模型')];
|
||||||
|
if (!state.baseline_model) return ['roles', t('请选择基线模型')];
|
||||||
|
// 自定义规则引用的模型 / 行必须仍然存在(改名、删除后容易遗漏)
|
||||||
|
try {
|
||||||
|
const rules = JSON.parse(state.rules || '[]');
|
||||||
|
const labelNames = new Set(state.labels.map((l) => l.name));
|
||||||
|
for (let i = 0; i < (Array.isArray(rules) ? rules.length : 0); i += 1) {
|
||||||
|
const th = rules[i]?.then || {};
|
||||||
|
if (
|
||||||
|
(th.model && !candidateNames.includes(th.model)) ||
|
||||||
|
(th.row && !labelNames.has(th.row))
|
||||||
|
) {
|
||||||
|
return [
|
||||||
|
'rules',
|
||||||
|
`${t('自定义规则引用了不存在的模型或行')} #${i + 1}`,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// JSON 格式错误在保存时单独提示
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
const problem = precheck();
|
||||||
|
if (problem) {
|
||||||
|
setActivePanels((p) => (p.includes(problem[0]) ? p : [...p, problem[0]]));
|
||||||
|
showError(problem[1]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let rules;
|
||||||
|
try {
|
||||||
|
rules = JSON.parse(state.rules || '[]');
|
||||||
|
if (!Array.isArray(rules)) throw new Error('not array');
|
||||||
|
} catch (e) {
|
||||||
|
setActivePanels((p) => (p.includes('rules') ? p : [...p, 'rules']));
|
||||||
|
showError(t('自定义规则必须是合法的 JSON 数组'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const matrix = {};
|
||||||
|
state.labels.forEach((l) => {
|
||||||
|
matrix[l.name] = [...(state.matrix[l.id] || emptyRow())].slice(0, 4);
|
||||||
|
});
|
||||||
|
const payload = {
|
||||||
|
id: state.id,
|
||||||
|
slug: state.slug.trim(),
|
||||||
|
name: state.name,
|
||||||
|
description: state.description,
|
||||||
|
mode: 'matrix',
|
||||||
|
strategy: state.strategy,
|
||||||
|
tier_thresholds: state.tier_thresholds,
|
||||||
|
min_task_conf: Number(state.min_task_conf) || 0,
|
||||||
|
reasoning_threshold: Number(state.reasoning_threshold) || 0,
|
||||||
|
reasoning_model: state.reasoning_model || '',
|
||||||
|
default_model: state.default_model || '',
|
||||||
|
baseline_model: state.baseline_model || '',
|
||||||
|
sticky_enabled: state.sticky_enabled,
|
||||||
|
sticky_ttl_sec: Number(state.sticky_ttl_sec) || 1800,
|
||||||
|
jev_allowed: state.jev_allowed,
|
||||||
|
status: state.status,
|
||||||
|
task_labels: state.labels.map((l) => ({
|
||||||
|
name: l.name.trim(),
|
||||||
|
desc: l.desc,
|
||||||
|
...(l.rules_label ? { rules_label: l.rules_label } : {}),
|
||||||
|
})),
|
||||||
|
difficulty_levels: profile?.difficulty_levels_obj || undefined,
|
||||||
|
matrix,
|
||||||
|
rules,
|
||||||
|
models: state.models.map((m) => ({
|
||||||
|
model_name: m.model_name,
|
||||||
|
model_tier: Number(m.model_tier) || 0,
|
||||||
|
description: m.description,
|
||||||
|
enabled: m.enabled,
|
||||||
|
capabilities: {
|
||||||
|
...m.caps,
|
||||||
|
max_context: Number(m.caps.max_context) || 0,
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
await saveProfile(mode, orgId, payload);
|
||||||
|
showSuccess(t('已保存'));
|
||||||
|
onSaved?.();
|
||||||
|
} catch (e) {
|
||||||
|
showError(e?.message || t('保存失败,请稍后重试'));
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const tierOptions = [0, 1, 2, 3, 4].map((v) => ({
|
||||||
|
label: `${t('能力档')} ${v}`,
|
||||||
|
value: v,
|
||||||
|
}));
|
||||||
|
const strategyOptions = [
|
||||||
|
{ label: t('质量优先'), value: 'quality' },
|
||||||
|
{ label: t('平衡'), value: 'balanced' },
|
||||||
|
{ label: t('成本优先'), value: 'cost' },
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Drawer
|
||||||
|
rootClassName='smart-router-sheet'
|
||||||
|
open={visible}
|
||||||
|
onClose={onClose}
|
||||||
|
size={Math.min(
|
||||||
|
820,
|
||||||
|
typeof window !== 'undefined' ? window.innerWidth : 820,
|
||||||
|
)}
|
||||||
|
title={profile ? t('编辑智能路由集合') : t('新建智能路由集合')}
|
||||||
|
footer={
|
||||||
|
<div className='smart-router-sheet-footer'>
|
||||||
|
<Button onClick={onClose}>{t('取消')}</Button>
|
||||||
|
<Button type='primary' loading={saving} onClick={handleSave}>
|
||||||
|
{t('保存')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{/* 字段均为受控 state;Form 只提供竖排标签与间距,不接管取值、校验与提交 */}
|
||||||
|
<Form layout='vertical' component='div' requiredMark={false}>
|
||||||
|
<Collapse
|
||||||
|
activeKey={activePanels}
|
||||||
|
onChange={(keys) => setActivePanels(keys || [])}
|
||||||
|
items={[
|
||||||
|
{
|
||||||
|
key: 'basic',
|
||||||
|
label: t('基本信息'),
|
||||||
|
children: (
|
||||||
|
<div className='smart-router-grid'>
|
||||||
|
<Form.Item
|
||||||
|
label={t(
|
||||||
|
'短名(虚拟模型名为 router/短名,创建后不可修改)',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
value={state.slug}
|
||||||
|
disabled={!!state.id}
|
||||||
|
prefix='router/'
|
||||||
|
onChange={(e) =>
|
||||||
|
set('slug', e.target.value.toLowerCase())
|
||||||
|
}
|
||||||
|
placeholder='coding'
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label={t('名称')}>
|
||||||
|
<Input
|
||||||
|
value={state.name}
|
||||||
|
onChange={(e) => set('name', e.target.value)}
|
||||||
|
maxLength={64}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
className='smart-router-grid-full'
|
||||||
|
label={t('说明')}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
value={state.description}
|
||||||
|
onChange={(e) => set('description', e.target.value)}
|
||||||
|
maxLength={255}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label={t('策略')}>
|
||||||
|
<Select
|
||||||
|
value={state.strategy}
|
||||||
|
options={strategyOptions}
|
||||||
|
onChange={(v) => set('strategy', v)}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
label={t('高级:难度档阈值 τ1,τ2,τ3(留空使用策略默认值)')}
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
value={state.tier_thresholds}
|
||||||
|
onChange={(e) => set('tier_thresholds', e.target.value)}
|
||||||
|
placeholder='0.45,0.50,0.55'
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<div className='smart-router-inline'>
|
||||||
|
<Switch
|
||||||
|
size='small'
|
||||||
|
checked={state.status === 1}
|
||||||
|
onChange={(v) => set('status', v ? 1 : 2)}
|
||||||
|
aria-label={t('启用')}
|
||||||
|
/>
|
||||||
|
<Text>{t('启用')}</Text>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'models',
|
||||||
|
label: t('候选模型'),
|
||||||
|
children: (
|
||||||
|
<div className='smart-router-stack'>
|
||||||
|
<Text type='secondary' className='smart-router-sub'>
|
||||||
|
{t(
|
||||||
|
'能力档 0~4:数值越大能力越强;推理模型通常配为 4。能力标签用于按请求过滤候选。',
|
||||||
|
)}
|
||||||
|
</Text>
|
||||||
|
{state.models.map((m, idx) => (
|
||||||
|
<div
|
||||||
|
key={idx}
|
||||||
|
className='smart-router-card smart-router-card--compact'
|
||||||
|
>
|
||||||
|
<div className='smart-router-inline'>
|
||||||
|
<CreatableSelect
|
||||||
|
className='smart-router-model-select'
|
||||||
|
value={m.model_name || undefined}
|
||||||
|
options={modelOptions.filter(
|
||||||
|
(o) =>
|
||||||
|
o.value === m.model_name ||
|
||||||
|
!state.models.some(
|
||||||
|
(x, i) => i !== idx && x.model_name === o.value,
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
placeholder={t('选择模型')}
|
||||||
|
aria-label={t('选择模型')}
|
||||||
|
onChange={(v) =>
|
||||||
|
updateModel(idx, { model_name: v || '' })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
style={{ width: 150 }}
|
||||||
|
value={m.model_tier}
|
||||||
|
options={tierOptions}
|
||||||
|
aria-label={t('能力档')}
|
||||||
|
onChange={(v) => updateModel(idx, { model_tier: v })}
|
||||||
|
/>
|
||||||
|
<Switch
|
||||||
|
size='small'
|
||||||
|
checked={m.enabled}
|
||||||
|
onChange={(v) => updateModel(idx, { enabled: v })}
|
||||||
|
aria-label={t('启用')}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type='text'
|
||||||
|
danger
|
||||||
|
icon={<Trash2 size={16} />}
|
||||||
|
aria-label={t('删除')}
|
||||||
|
onClick={() => removeModel(idx)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className='smart-router-inline smart-router-section'>
|
||||||
|
<Checkbox
|
||||||
|
checked={m.caps.vision}
|
||||||
|
onChange={(e) =>
|
||||||
|
updateCaps(idx, { vision: e.target.checked })
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{t('图片输入')}
|
||||||
|
</Checkbox>
|
||||||
|
<Checkbox
|
||||||
|
checked={m.caps.tools}
|
||||||
|
onChange={(e) =>
|
||||||
|
updateCaps(idx, { tools: e.target.checked })
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{t('工具调用')}
|
||||||
|
</Checkbox>
|
||||||
|
<Checkbox
|
||||||
|
checked={m.caps.json_mode}
|
||||||
|
onChange={(e) =>
|
||||||
|
updateCaps(idx, { json_mode: e.target.checked })
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{t('JSON 输出')}
|
||||||
|
</Checkbox>
|
||||||
|
<Checkbox
|
||||||
|
checked={m.caps.reasoning}
|
||||||
|
onChange={(e) =>
|
||||||
|
updateCaps(idx, { reasoning: e.target.checked })
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{t('推理模型')}
|
||||||
|
</Checkbox>
|
||||||
|
<InputNumber
|
||||||
|
style={{ width: 200 }}
|
||||||
|
prefix={t('上下文')}
|
||||||
|
min={0}
|
||||||
|
value={m.caps.max_context}
|
||||||
|
onChange={(v) =>
|
||||||
|
updateCaps(idx, { max_context: Number(v) || 0 })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div>
|
||||||
|
<Button
|
||||||
|
icon={<Plus size={16} />}
|
||||||
|
onClick={() =>
|
||||||
|
set('models', [
|
||||||
|
...state.models,
|
||||||
|
{
|
||||||
|
model_name: '',
|
||||||
|
model_tier: 1,
|
||||||
|
description: '',
|
||||||
|
enabled: true,
|
||||||
|
caps: { ...emptyCaps },
|
||||||
|
},
|
||||||
|
])
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{t('添加候选模型')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'labels',
|
||||||
|
label: t('任务标签'),
|
||||||
|
children: (
|
||||||
|
<div className='smart-router-stack'>
|
||||||
|
<Text type='secondary' className='smart-router-sub'>
|
||||||
|
{t(
|
||||||
|
'标签修改后,任务置信度阈值建议观察 7 天后再调整。必须包含 general。',
|
||||||
|
)}
|
||||||
|
</Text>
|
||||||
|
{state.labels.map((l) => {
|
||||||
|
const locked = l.id === generalIdRef.current;
|
||||||
|
const invalid =
|
||||||
|
duplicateLabels.has(l.name) ||
|
||||||
|
!LABEL_PATTERN.test(l.name);
|
||||||
|
return (
|
||||||
|
<div key={l.id} className='smart-router-inline'>
|
||||||
|
<Input
|
||||||
|
style={{ width: 160 }}
|
||||||
|
value={l.name}
|
||||||
|
disabled={locked}
|
||||||
|
status={invalid ? 'error' : undefined}
|
||||||
|
aria-label={t('任务类型')}
|
||||||
|
onChange={(e) =>
|
||||||
|
updateLabel(l.id, {
|
||||||
|
name: e.target.value.toLowerCase(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
style={{ flex: 1, minWidth: 200 }}
|
||||||
|
value={l.desc}
|
||||||
|
aria-label={t('说明')}
|
||||||
|
onChange={(e) =>
|
||||||
|
updateLabel(l.id, { desc: e.target.value })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
style={{ width: 170 }}
|
||||||
|
placeholder={t('对应规则判定器标签')}
|
||||||
|
allowClear
|
||||||
|
value={l.rules_label || undefined}
|
||||||
|
options={RULES_LABELS.map((x) => ({
|
||||||
|
label: x,
|
||||||
|
value: x,
|
||||||
|
}))}
|
||||||
|
onChange={(v) =>
|
||||||
|
updateLabel(l.id, { rules_label: v || '' })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type='text'
|
||||||
|
danger
|
||||||
|
icon={<Trash2 size={16} />}
|
||||||
|
disabled={locked}
|
||||||
|
aria-label={t('删除')}
|
||||||
|
onClick={() => removeLabel(l.id)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{duplicateLabels.size > 0 && (
|
||||||
|
<Text type='danger' className='smart-router-sub'>
|
||||||
|
{t('任务标签不能重名')}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
<div>
|
||||||
|
<Button
|
||||||
|
icon={<Plus size={16} />}
|
||||||
|
disabled={state.labels.length >= 32}
|
||||||
|
onClick={addLabel}
|
||||||
|
>
|
||||||
|
{t('添加标签')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'matrix',
|
||||||
|
label: t('路由矩阵'),
|
||||||
|
children: (
|
||||||
|
<div className='smart-router-stack'>
|
||||||
|
<div className='smart-router-toolbar'>
|
||||||
|
<Text type='secondary' className='smart-router-sub'>
|
||||||
|
{t('行是任务类型,列是难度档;general 行必须全部填写。')}
|
||||||
|
</Text>
|
||||||
|
<Button onClick={applyAutoMatrix}>
|
||||||
|
{t('一键生成(仅作为初始值)')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className='smart-router-matrix'>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>{t('任务类型')}</th>
|
||||||
|
<th>{t('0 简单')}</th>
|
||||||
|
<th>{t('1 常规')}</th>
|
||||||
|
<th>{t('2 较难')}</th>
|
||||||
|
<th>{t('3 困难')}</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{state.labels.map((l) => (
|
||||||
|
<tr key={l.id}>
|
||||||
|
<td className='smart-router-mono smart-router-sub'>
|
||||||
|
{l.name}
|
||||||
|
</td>
|
||||||
|
{[0, 1, 2, 3].map((col) => (
|
||||||
|
<td key={col}>
|
||||||
|
<Select
|
||||||
|
style={{ width: 150 }}
|
||||||
|
size='small'
|
||||||
|
allowClear={l.name !== 'general'}
|
||||||
|
value={
|
||||||
|
(state.matrix[l.id] || [])[col] || undefined
|
||||||
|
}
|
||||||
|
options={candidateOptions}
|
||||||
|
aria-label={`${l.name} · ${col}`}
|
||||||
|
onChange={(v) => setCell(l.id, col, v)}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'roles',
|
||||||
|
label: t('模型角色与阈值'),
|
||||||
|
children: (
|
||||||
|
<div className='smart-router-grid'>
|
||||||
|
<Form.Item label={t('默认模型(判定失败时使用)')}>
|
||||||
|
<Select
|
||||||
|
value={state.default_model || undefined}
|
||||||
|
options={candidateOptions}
|
||||||
|
onChange={(v) => set('default_model', v || '')}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
label={t('基线模型(用于节省率,必须出现在矩阵中)')}
|
||||||
|
>
|
||||||
|
<Select
|
||||||
|
value={state.baseline_model || undefined}
|
||||||
|
options={candidateOptions}
|
||||||
|
onChange={(v) => set('baseline_model', v || '')}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label={t('推理模型(可选)')}>
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
value={state.reasoning_model || undefined}
|
||||||
|
options={candidateOptions}
|
||||||
|
onChange={(v) => set('reasoning_model', v || '')}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label={t('推理阈值(0 表示默认 0.7)')}>
|
||||||
|
<InputNumber
|
||||||
|
className='w-full'
|
||||||
|
min={0}
|
||||||
|
max={1}
|
||||||
|
step={0.05}
|
||||||
|
value={state.reasoning_threshold}
|
||||||
|
onChange={(v) =>
|
||||||
|
set('reasoning_threshold', Number(v) || 0)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label={t('任务置信度下限(0 表示默认)')}>
|
||||||
|
<InputNumber
|
||||||
|
className='w-full'
|
||||||
|
min={0}
|
||||||
|
max={1}
|
||||||
|
step={0.05}
|
||||||
|
value={state.min_task_conf}
|
||||||
|
onChange={(v) => set('min_task_conf', Number(v) || 0)}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'session',
|
||||||
|
label: t('会话与判定'),
|
||||||
|
children: (
|
||||||
|
<div className='smart-router-stack'>
|
||||||
|
<div className='smart-router-inline'>
|
||||||
|
<Switch
|
||||||
|
size='small'
|
||||||
|
checked={state.sticky_enabled}
|
||||||
|
onChange={(v) => set('sticky_enabled', v)}
|
||||||
|
aria-label={t('会话粘性(只升档不降档)')}
|
||||||
|
/>
|
||||||
|
<Text>{t('会话粘性(只升档不降档)')}</Text>
|
||||||
|
<InputNumber
|
||||||
|
style={{ width: 220 }}
|
||||||
|
prefix={t('有效期(秒)')}
|
||||||
|
min={60}
|
||||||
|
max={86400}
|
||||||
|
value={state.sticky_ttl_sec}
|
||||||
|
onChange={(v) => set('sticky_ttl_sec', Number(v) || 1800)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className='smart-router-inline'>
|
||||||
|
<Switch
|
||||||
|
size='small'
|
||||||
|
checked={state.jev_allowed}
|
||||||
|
onChange={(v) => set('jev_allowed', v)}
|
||||||
|
aria-label={t(
|
||||||
|
'允许使用 Jev 判定(还需平台开启与出境同意)',
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Text>
|
||||||
|
{t('允许使用 Jev 判定(还需平台开启与出境同意)')}
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'rules',
|
||||||
|
label: t('自定义规则(高级)'),
|
||||||
|
children: (
|
||||||
|
<div className='smart-router-stack'>
|
||||||
|
<Alert
|
||||||
|
type='info'
|
||||||
|
showIcon
|
||||||
|
title={t(
|
||||||
|
'JSON 数组,按顺序第一条命中即生效。动作:model 直接指定模型;tier(可带 row)强制难度档;tier_min / tier_max 约束区间。',
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<TextArea
|
||||||
|
className='smart-router-mono'
|
||||||
|
autoSize={{ minRows: 6, maxRows: 16 }}
|
||||||
|
value={state.rules}
|
||||||
|
aria-label={t('自定义规则(高级)')}
|
||||||
|
onChange={(e) => set('rules', e.target.value)}
|
||||||
|
placeholder='[{"if":{"user_contains":"review"},"then":{"tier":3,"row":"coding"}}]'
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form>
|
||||||
|
</Drawer>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ProfileEditor;
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
/*
|
||||||
|
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, { useCallback, useEffect, useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Button, Empty, Popconfirm, Space, Tag, Typography } from 'antd';
|
||||||
|
import { Table } from '@/components/ui';
|
||||||
|
import { ConsoleAlert as Alert } from '../console/ConsolePrimitives';
|
||||||
|
import { Plus } from '../common/icons/ActionIcons';
|
||||||
|
import { copy, showError, showSuccess } from '../../helpers';
|
||||||
|
import { deleteProfile, listCandidateModels, listProfiles } from './api';
|
||||||
|
import ProfileEditor from './ProfileEditor';
|
||||||
|
import SimulateModal from './SimulateModal';
|
||||||
|
|
||||||
|
const { Text } = Typography;
|
||||||
|
|
||||||
|
const ProfileTable = ({ mode, orgId, canWrite = true, emptyHint }) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [list, setList] = useState([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
const [editing, setEditing] = useState(null); // null 关闭;{} 新建;profile 编辑
|
||||||
|
const [simulating, setSimulating] = useState(null);
|
||||||
|
const [models, setModels] = useState([]);
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError('');
|
||||||
|
try {
|
||||||
|
setList((await listProfiles(mode, orgId)) || []);
|
||||||
|
} catch (e) {
|
||||||
|
setError(e?.message || t('加载失败'));
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [mode, orgId, t]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!canWrite) return;
|
||||||
|
listCandidateModels(mode, orgId)
|
||||||
|
.then(setModels)
|
||||||
|
.catch(() => setModels([]));
|
||||||
|
}, [mode, orgId, canWrite]);
|
||||||
|
|
||||||
|
const strategyText = (s) =>
|
||||||
|
({ quality: t('质量优先'), balanced: t('平衡'), cost: t('成本优先') })[s] ||
|
||||||
|
s;
|
||||||
|
|
||||||
|
const columns = [
|
||||||
|
{
|
||||||
|
title: t('虚拟模型'),
|
||||||
|
dataIndex: 'virtual_model',
|
||||||
|
width: 280,
|
||||||
|
render: (v, r) => (
|
||||||
|
<div className='min-w-0'>
|
||||||
|
<Button
|
||||||
|
type='link'
|
||||||
|
size='small'
|
||||||
|
className='smart-router-mono smart-router-copy'
|
||||||
|
aria-label={`${t('复制')} ${v}`}
|
||||||
|
onClick={async () => {
|
||||||
|
if (await copy(v)) showSuccess(t('已复制'));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{v}
|
||||||
|
</Button>
|
||||||
|
<div>
|
||||||
|
<Text
|
||||||
|
type='secondary'
|
||||||
|
className='smart-router-sub smart-router-name'
|
||||||
|
ellipsis={{ tooltip: r.name }}
|
||||||
|
>
|
||||||
|
{r.name}
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: t('策略'),
|
||||||
|
dataIndex: 'strategy',
|
||||||
|
width: 110,
|
||||||
|
render: strategyText,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: t('候选模型'),
|
||||||
|
dataIndex: 'models',
|
||||||
|
width: 100,
|
||||||
|
align: 'right',
|
||||||
|
render: (ms) => (
|
||||||
|
<span className='smart-router-num'>
|
||||||
|
{(ms || []).filter((m) => m.enabled).length}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: t('默认模型'),
|
||||||
|
dataIndex: 'default_model',
|
||||||
|
width: 220,
|
||||||
|
render: (v) => <span className='smart-router-mono'>{v}</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: t('状态'),
|
||||||
|
dataIndex: 'status',
|
||||||
|
width: 140,
|
||||||
|
render: (v, r) => (
|
||||||
|
<Space size={8}>
|
||||||
|
{v === 1 ? (
|
||||||
|
<Tag color='success' variant='filled'>
|
||||||
|
{t('启用')}
|
||||||
|
</Tag>
|
||||||
|
) : (
|
||||||
|
<Tag color='default' variant='filled'>
|
||||||
|
{t('停用')}
|
||||||
|
</Tag>
|
||||||
|
)}
|
||||||
|
{r.jev_allowed && (
|
||||||
|
<Tag color='blue' variant='filled'>
|
||||||
|
Jev
|
||||||
|
</Tag>
|
||||||
|
)}
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: t('操作'),
|
||||||
|
key: 'actions',
|
||||||
|
fixed: 'right',
|
||||||
|
width: 180,
|
||||||
|
render: (_, r) => (
|
||||||
|
<Space size={8} wrap>
|
||||||
|
<Button
|
||||||
|
type='link'
|
||||||
|
size='small'
|
||||||
|
onClick={() => setSimulating(r)}
|
||||||
|
disabled={!canWrite}
|
||||||
|
>
|
||||||
|
{t('试路由')}
|
||||||
|
</Button>
|
||||||
|
{canWrite && (
|
||||||
|
<>
|
||||||
|
<Button type='link' size='small' onClick={() => setEditing(r)}>
|
||||||
|
{t('编辑')}
|
||||||
|
</Button>
|
||||||
|
<Popconfirm
|
||||||
|
title={t('确认删除该集合?')}
|
||||||
|
description={t('使用该虚拟模型名的请求将返回"模型不存在"。')}
|
||||||
|
okButtonProps={{ danger: true }}
|
||||||
|
onConfirm={async () => {
|
||||||
|
try {
|
||||||
|
await deleteProfile(mode, orgId, r.id);
|
||||||
|
showSuccess(t('已删除'));
|
||||||
|
load();
|
||||||
|
} catch (e) {
|
||||||
|
if (e?.message) showError(e.message);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Button type='link' size='small' danger>
|
||||||
|
{t('删除')}
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className='smart-router-stack'>
|
||||||
|
<div className='smart-router-toolbar'>
|
||||||
|
<Text type='secondary' className='smart-router-sub'>
|
||||||
|
{emptyHint}
|
||||||
|
</Text>
|
||||||
|
{canWrite && (
|
||||||
|
<Button
|
||||||
|
type='primary'
|
||||||
|
icon={<Plus size={16} />}
|
||||||
|
onClick={() => setEditing({})}
|
||||||
|
>
|
||||||
|
{t('新建集合')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{error ? (
|
||||||
|
<Alert
|
||||||
|
type='error'
|
||||||
|
showIcon
|
||||||
|
title={error}
|
||||||
|
action={
|
||||||
|
<Button size='small' onClick={load}>
|
||||||
|
{t('重试')}
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Table
|
||||||
|
rowKey='id'
|
||||||
|
size='middle'
|
||||||
|
loading={loading}
|
||||||
|
columns={columns}
|
||||||
|
dataSource={list}
|
||||||
|
pagination={false}
|
||||||
|
scroll={{ x: 'max-content' }}
|
||||||
|
empty={
|
||||||
|
<Empty
|
||||||
|
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||||
|
description={t('还没有智能路由集合')}
|
||||||
|
>
|
||||||
|
{canWrite && (
|
||||||
|
<Button type='primary' onClick={() => setEditing({})}>
|
||||||
|
{t('新建集合')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</Empty>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<ProfileEditor
|
||||||
|
visible={editing !== null}
|
||||||
|
mode={mode}
|
||||||
|
orgId={orgId}
|
||||||
|
profile={editing && editing.id ? editing : null}
|
||||||
|
candidateModels={models}
|
||||||
|
onClose={() => setEditing(null)}
|
||||||
|
onSaved={() => {
|
||||||
|
setEditing(null);
|
||||||
|
load();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<SimulateModal
|
||||||
|
visible={!!simulating}
|
||||||
|
mode={mode}
|
||||||
|
orgId={orgId}
|
||||||
|
profile={simulating}
|
||||||
|
onClose={() => setSimulating(null)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ProfileTable;
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
/*
|
||||||
|
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, { useEffect, useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Button, Input, Progress, Tag, Typography } from 'antd';
|
||||||
|
import {
|
||||||
|
ConsoleAlert as Alert,
|
||||||
|
ConsoleModal as Modal,
|
||||||
|
} from '../console/ConsolePrimitives';
|
||||||
|
import { simulateProfile } from './api';
|
||||||
|
import { gateText, reasonText, srcText } from './labels';
|
||||||
|
|
||||||
|
const { Text } = Typography;
|
||||||
|
const { TextArea } = Input;
|
||||||
|
|
||||||
|
const ProbBars = ({ probs }) => {
|
||||||
|
if (!probs) return null;
|
||||||
|
const entries = Array.isArray(probs)
|
||||||
|
? probs.map((v, i) => [String(i), v])
|
||||||
|
: Object.entries(probs).sort((a, b) => b[1] - a[1]);
|
||||||
|
return (
|
||||||
|
<div className='smart-router-prob-list'>
|
||||||
|
{entries.map(([k, v]) => (
|
||||||
|
<div key={k} className='smart-router-prob'>
|
||||||
|
<span className='smart-router-mono smart-router-prob-label'>{k}</span>
|
||||||
|
<Progress
|
||||||
|
className='smart-router-prob-bar'
|
||||||
|
percent={Math.round((v || 0) * 100)}
|
||||||
|
showInfo={false}
|
||||||
|
size='small'
|
||||||
|
/>
|
||||||
|
<span className='smart-router-num smart-router-prob-value'>
|
||||||
|
{Math.round((v || 0) * 100)}%
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const SimulateModal = ({ visible, mode, orgId, profile, onClose }) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [prompt, setPrompt] = useState('');
|
||||||
|
const [system, setSystem] = useState('');
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [result, setResult] = useState(null);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (visible) {
|
||||||
|
setResult(null);
|
||||||
|
setError('');
|
||||||
|
}
|
||||||
|
}, [visible]);
|
||||||
|
|
||||||
|
// 换了集合就清空上一次的输入
|
||||||
|
useEffect(() => {
|
||||||
|
setPrompt('');
|
||||||
|
setSystem('');
|
||||||
|
}, [profile?.id]);
|
||||||
|
|
||||||
|
const run = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError('');
|
||||||
|
try {
|
||||||
|
setResult(
|
||||||
|
await simulateProfile(mode, orgId, profile.id, { prompt, system }),
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
setError(e?.message || t('试路由失败,请稍后重试'));
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
rootClassName='smart-router-sheet'
|
||||||
|
open={visible}
|
||||||
|
title={`${t('试路由')} · router/${profile?.slug || ''}`}
|
||||||
|
onCancel={onClose}
|
||||||
|
footer={null}
|
||||||
|
width={760}
|
||||||
|
>
|
||||||
|
<div className='smart-router-stack'>
|
||||||
|
<TextArea
|
||||||
|
autoSize={{ minRows: 2, maxRows: 4 }}
|
||||||
|
placeholder={t('可选:system 提示词')}
|
||||||
|
aria-label={t('可选:system 提示词')}
|
||||||
|
value={system}
|
||||||
|
onChange={(e) => setSystem(e.target.value)}
|
||||||
|
/>
|
||||||
|
<TextArea
|
||||||
|
autoSize={{ minRows: 4, maxRows: 10 }}
|
||||||
|
placeholder={t('粘贴一段要路由的用户请求')}
|
||||||
|
aria-label={t('粘贴一段要路由的用户请求')}
|
||||||
|
value={prompt}
|
||||||
|
onChange={(e) => setPrompt(e.target.value)}
|
||||||
|
/>
|
||||||
|
<div>
|
||||||
|
<Button
|
||||||
|
type='primary'
|
||||||
|
loading={loading}
|
||||||
|
disabled={!prompt.trim()}
|
||||||
|
onClick={run}
|
||||||
|
>
|
||||||
|
{t('试路由')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{error && <Alert type='error' showIcon title={error} />}
|
||||||
|
{result && (
|
||||||
|
<div className='smart-router-card'>
|
||||||
|
{result.error ? (
|
||||||
|
<Alert type='warning' showIcon title={result.error} />
|
||||||
|
) : (
|
||||||
|
<dl className='smart-router-kv'>
|
||||||
|
<dt>{t('实际模型')}</dt>
|
||||||
|
<dd>
|
||||||
|
<span className='smart-router-mono'>{result.model}</span>{' '}
|
||||||
|
<Tag variant='filled'>
|
||||||
|
{t('能力档')} {result.model_tier}
|
||||||
|
</Tag>
|
||||||
|
</dd>
|
||||||
|
<dt>{t('判定来源')}</dt>
|
||||||
|
<dd>
|
||||||
|
<Tag variant='filled' color='blue'>
|
||||||
|
{srcText(t, result.src)}
|
||||||
|
</Tag>{' '}
|
||||||
|
<span className='smart-router-mono'>{result.why}</span>
|
||||||
|
</dd>
|
||||||
|
<dt>{t('合规闸门')}</dt>
|
||||||
|
<dd>{gateText(t, result.gate)}</dd>
|
||||||
|
<dt>{t('任务 / 难度档')}</dt>
|
||||||
|
<dd>
|
||||||
|
{result.task} /{' '}
|
||||||
|
<span className='smart-router-num'>
|
||||||
|
{result.difficulty_tier}
|
||||||
|
</span>
|
||||||
|
</dd>
|
||||||
|
<dt>{t('规则判定器')}</dt>
|
||||||
|
<dd>
|
||||||
|
{result.rules_task} /{' '}
|
||||||
|
<span className='smart-router-num'>{result.rules_tier}</span>
|
||||||
|
</dd>
|
||||||
|
{result.judge_ms > 0 && (
|
||||||
|
<>
|
||||||
|
<dt>{t('判定耗时')}</dt>
|
||||||
|
<dd className='smart-router-num'>{result.judge_ms} ms</dd>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<dt>{t('基线模型')}</dt>
|
||||||
|
<dd className='smart-router-mono'>{result.baseline_model}</dd>
|
||||||
|
{result.features && (
|
||||||
|
<>
|
||||||
|
<dt>{t('请求特征')}</dt>
|
||||||
|
<dd className='smart-router-num'>
|
||||||
|
{t('预估 token')} {result.features.est_tokens} ·{' '}
|
||||||
|
{t('对话 token')} {result.features.conv_tokens} ·{' '}
|
||||||
|
{t('用户轮次')} {result.features.user_turns}
|
||||||
|
</dd>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</dl>
|
||||||
|
)}
|
||||||
|
{result.task_probs && Object.keys(result.task_probs).length > 0 && (
|
||||||
|
<div className='smart-router-section'>
|
||||||
|
<Text strong>{t('任务类型概率')}</Text>
|
||||||
|
<ProbBars probs={result.task_probs} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{result.difficulty_probs && result.difficulty_probs.length > 0 && (
|
||||||
|
<div className='smart-router-section'>
|
||||||
|
<Text strong>{t('难度概率')}</Text>
|
||||||
|
<ProbBars probs={result.difficulty_probs} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{result.filtered && Object.keys(result.filtered).length > 0 && (
|
||||||
|
<div className='smart-router-section'>
|
||||||
|
<Text strong>{t('被过滤的候选')}</Text>
|
||||||
|
<div className='smart-router-tags'>
|
||||||
|
{Object.entries(result.filtered).map(([m, r]) => (
|
||||||
|
<Tag key={m} variant='filled' color='default'>
|
||||||
|
{m} · {reasonText(t, r)}
|
||||||
|
</Tag>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default SimulateModal;
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
/*
|
||||||
|
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 { API, showError } from '../../helpers';
|
||||||
|
import i18n from '../../i18n/i18n';
|
||||||
|
|
||||||
|
// 智能模型路由接口(后端 router/smart-router.go)。
|
||||||
|
// mode: personal(个人)/ admin(平台 system 集合)/ org(企业,X-Org-Id 由 API 拦截器注入)
|
||||||
|
// 所有请求都跳过全局错误提示(skipErrorHandler),由调用方只弹一次业务文案,避免英文报错与重复提示。
|
||||||
|
export const routerBase = (mode) => {
|
||||||
|
if (mode === 'admin') return '/api/router/admin';
|
||||||
|
if (mode === 'org') return '/api/org/router';
|
||||||
|
return '/api/router';
|
||||||
|
};
|
||||||
|
|
||||||
|
const opts = (orgId, extra = {}) => ({
|
||||||
|
skipErrorHandler: true,
|
||||||
|
...(orgId ? { headers: { 'X-Org-Id': String(orgId) } } : {}),
|
||||||
|
...extra,
|
||||||
|
});
|
||||||
|
|
||||||
|
const friendly = (e) => {
|
||||||
|
const msg = e?.response?.data?.message;
|
||||||
|
if (msg) return msg;
|
||||||
|
const status = e?.response?.status;
|
||||||
|
if (status === 429) return i18n.t('操作过于频繁,请稍后再试');
|
||||||
|
if (status === 401 || status === 403) return i18n.t('没有权限执行该操作');
|
||||||
|
return i18n.t('请求失败,请稍后重试');
|
||||||
|
};
|
||||||
|
|
||||||
|
const call = async (fn) => {
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = await fn();
|
||||||
|
} catch (e) {
|
||||||
|
// 401 交给全局处理:清理登录态并跳转登录页(skipErrorHandler 会跳过它)。
|
||||||
|
// 之后不再抛出,调用方也就不会再弹一次"没有权限"——页面马上会跳走
|
||||||
|
if (e?.response?.status === 401) {
|
||||||
|
showError(e);
|
||||||
|
return new Promise(() => {});
|
||||||
|
}
|
||||||
|
throw new Error(friendly(e));
|
||||||
|
}
|
||||||
|
const { success, message, data } = res?.data || {};
|
||||||
|
if (!success) throw new Error(message || i18n.t('请求失败,请稍后重试'));
|
||||||
|
return data;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const listProfiles = (mode, orgId) =>
|
||||||
|
call(() => API.get(`${routerBase(mode)}/profiles`, opts(orgId)));
|
||||||
|
|
||||||
|
export const saveProfile = (mode, orgId, profile) => {
|
||||||
|
const base = routerBase(mode);
|
||||||
|
return call(() =>
|
||||||
|
profile.id
|
||||||
|
? API.put(`${base}/profiles/${profile.id}`, profile, opts(orgId))
|
||||||
|
: API.post(`${base}/profiles`, profile, opts(orgId)),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteProfile = (mode, orgId, id) =>
|
||||||
|
call(() => API.delete(`${routerBase(mode)}/profiles/${id}`, opts(orgId)));
|
||||||
|
|
||||||
|
export const simulateProfile = (mode, orgId, id, payload) =>
|
||||||
|
call(() =>
|
||||||
|
API.post(
|
||||||
|
`${routerBase(mode)}/profiles/${id}/simulate`,
|
||||||
|
payload,
|
||||||
|
opts(orgId),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const listDecisions = (mode, orgId, params) =>
|
||||||
|
call(() => API.get(`${routerBase(mode)}/decisions`, opts(orgId, { params })));
|
||||||
|
|
||||||
|
export const getConsents = (mode, orgId) =>
|
||||||
|
call(() => API.get(`${routerBase(mode)}/consents`, opts(orgId)));
|
||||||
|
|
||||||
|
// 个人是否仍有生效中的出境同意:平台关闭智能路由后,侧边栏据此保留入口供撤回(会话内缓存,避免每次进页面都请求)
|
||||||
|
const CONSENT_CACHE_KEY = 'smart_router_personal_consent_granted';
|
||||||
|
|
||||||
|
export const readPersonalConsentCache = () => {
|
||||||
|
try {
|
||||||
|
return sessionStorage.getItem(CONSENT_CACHE_KEY);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const writePersonalConsentCache = (rows) => {
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(
|
||||||
|
CONSENT_CACHE_KEY,
|
||||||
|
(rows || []).some((x) => x && x.granted === true) ? '1' : '0',
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
// 无痕模式等场景下 sessionStorage 不可用:不缓存即可
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const loadPersonalConsentGranted = async () => {
|
||||||
|
const rows = await getConsents('personal');
|
||||||
|
writePersonalConsentCache(rows);
|
||||||
|
return (rows || []).some((x) => x && x.granted === true);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const updateConsent = async (mode, orgId, kind, granted) => {
|
||||||
|
const rows = await call(() =>
|
||||||
|
API.put(`${routerBase(mode)}/consents`, { kind, granted }, opts(orgId)),
|
||||||
|
);
|
||||||
|
if (mode !== 'org' && mode !== 'admin') writePersonalConsentCache(rows);
|
||||||
|
return rows;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 候选模型下拉的数据来源:个人=自己分组可用模型;平台=全部启用模型;企业=企业可用模型
|
||||||
|
export const listCandidateModels = async (mode, orgId) => {
|
||||||
|
let url = '/api/user/models';
|
||||||
|
if (mode === 'admin') url = '/api/channel/models_enabled';
|
||||||
|
if (mode === 'org') url = '/api/org/models';
|
||||||
|
const data = await call(() => API.get(url, opts(orgId)));
|
||||||
|
return (data || []).filter(
|
||||||
|
(m) => typeof m === 'string' && !m.startsWith('router/'),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getAdminStatus = () =>
|
||||||
|
call(() => API.get('/api/router/admin/status', opts()));
|
||||||
|
|
||||||
|
export const setJevKey = (provider, key, clear = false) =>
|
||||||
|
call(() =>
|
||||||
|
API.put('/api/router/admin/jev-key', { provider, key, clear }, opts()),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const loadOptions = () => call(() => API.get('/api/option/', opts()));
|
||||||
|
|
||||||
|
export const saveOption = (key, value) =>
|
||||||
|
call(() => API.put('/api/option/', { key, value }, opts()));
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
/*
|
||||||
|
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
|
||||||
|
*/
|
||||||
|
|
||||||
|
// 判定来源 / 闸门 / 过滤原因的展示文案(与后端 decide.go、gate.go、filter.go 的代码一一对应)
|
||||||
|
export const reasonText = (t, code) =>
|
||||||
|
({
|
||||||
|
disabled: t('已停用'),
|
||||||
|
level: t('等级不可用'),
|
||||||
|
scope: t('不在企业作用域白名单'),
|
||||||
|
experience_center: t('不在体验中心白名单'),
|
||||||
|
no_channel: t('分组内没有可用渠道'),
|
||||||
|
channel_query_failed: t('渠道查询失败'),
|
||||||
|
protocol: t('渠道不支持该入口格式'),
|
||||||
|
vision: t('不支持图片输入'),
|
||||||
|
tools: t('不支持工具调用'),
|
||||||
|
json_mode: t('不支持 JSON 输出'),
|
||||||
|
context: t('超出上下文长度'),
|
||||||
|
tool_id_format: t('工具调用 ID 格式不兼容'),
|
||||||
|
strip_incompatible: t('不兼容历史剥离'),
|
||||||
|
reasoning: t('不支持推理 / 思考'),
|
||||||
|
})[code] || code;
|
||||||
|
|
||||||
|
// Jev 调用失败原因(jev.FailureReason);http_xxx 为上游状态码
|
||||||
|
export const jevReasonText = (t, code) => {
|
||||||
|
if (!code) return '';
|
||||||
|
if (/^http_\d+$/.test(code))
|
||||||
|
return t('上游返回 {{code}}', { code: code.slice(5) });
|
||||||
|
return (
|
||||||
|
{
|
||||||
|
timeout: t('判定超时'),
|
||||||
|
breaker: t('通道熔断中'),
|
||||||
|
no_key: t('未配置密钥'),
|
||||||
|
parse: t('返回格式异常'),
|
||||||
|
error: t('调用失败'),
|
||||||
|
}[code] || code
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const gateText = (t, code) =>
|
||||||
|
({
|
||||||
|
jev: t('已调用 Jev'),
|
||||||
|
platform_off: t('平台未开启 Jev 出境'),
|
||||||
|
sensitive: t('命中敏感词'),
|
||||||
|
desens_off: t('脱敏未启用'),
|
||||||
|
desens_block: t('脱敏策略会拦截'),
|
||||||
|
guard_input: t('内容审核输入审查生效'),
|
||||||
|
org_no_consent: t('企业未授权'),
|
||||||
|
user_no_consent: t('个人未授权'),
|
||||||
|
profile_off: t('集合未允许使用 Jev'),
|
||||||
|
no_quota: t('余额不足,未调用 Jev'),
|
||||||
|
jev_cap: t('今日 Jev 判定次数已达上限'),
|
||||||
|
desens_residual: t('脱敏后仍有敏感信息'),
|
||||||
|
'n/a': t('未经过闸门'),
|
||||||
|
})[code] ||
|
||||||
|
(code && code.startsWith('rules:') ? gateText(t, code.slice(6)) : code) ||
|
||||||
|
'-';
|
||||||
|
|
||||||
|
export const srcText = (t, code) =>
|
||||||
|
({
|
||||||
|
jev: t('Jev 判定'),
|
||||||
|
cache: t('判定缓存'),
|
||||||
|
rules: t('规则判定器'),
|
||||||
|
rules_fallback: t('Jev 失败,规则判定'),
|
||||||
|
rule: t('自定义规则'),
|
||||||
|
rule_tier: t('自定义规则强制档位'),
|
||||||
|
forced: t('请求指定档位'),
|
||||||
|
single: t('唯一候选'),
|
||||||
|
sticky: t('会话粘性'),
|
||||||
|
continuation: t('工具调用续写'),
|
||||||
|
default: t('默认模型'),
|
||||||
|
cheapest: t('最便宜的候选'),
|
||||||
|
disabled: t('未启用,使用默认模型'),
|
||||||
|
error: t('路由失败'),
|
||||||
|
})[code] || code;
|
||||||
@@ -0,0 +1,344 @@
|
|||||||
|
/* 智能模型路由:配色只引用语义变量(tokens.css),同时用于控制台与企业中心,保持中性 */
|
||||||
|
.smart-router-page,
|
||||||
|
.smart-router-scope,
|
||||||
|
.smart-router-sheet {
|
||||||
|
--sr-ink: var(--text-primary);
|
||||||
|
--sr-muted: var(--text-secondary);
|
||||||
|
--sr-line: var(--border-subtle);
|
||||||
|
--sr-accent: var(--brand-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-page {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 18px;
|
||||||
|
color: var(--sr-ink);
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-page .smart-router-intro.console-alert {
|
||||||
|
margin-block: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-alert {
|
||||||
|
margin-bottom: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Match the tab-first card spacing used by WebsiteSettings. */
|
||||||
|
.console-page .smart-router-tabs-card.ant-card > .ant-card-body {
|
||||||
|
padding-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 控制台介绍区:无图标、无渐变的说明块;标题与内边距由公共页头 / 容器统一 */
|
||||||
|
.smart-router-hero {
|
||||||
|
padding: 16px 24px;
|
||||||
|
border: 1px solid var(--sr-line);
|
||||||
|
border-radius: 10px;
|
||||||
|
background: var(--surface-card);
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-eyebrow {
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.08em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: var(--sr-accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-hero h1 {
|
||||||
|
margin: 4px 0 0;
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 24px;
|
||||||
|
color: var(--sr-ink);
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-hero p {
|
||||||
|
margin: 4px 0 0;
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 22px;
|
||||||
|
color: var(--sr-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 区块卡:控制台 / 企业中心页内的子卡与弹层内结果卡 */
|
||||||
|
.smart-router-card {
|
||||||
|
border: 1px solid var(--sr-line);
|
||||||
|
border-radius: 10px;
|
||||||
|
background: var(--surface-card);
|
||||||
|
padding: 16px 24px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-card--compact {
|
||||||
|
padding: 12px 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-card-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-stack {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-toolbar {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-inline {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-section {
|
||||||
|
margin-top: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-state {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 24px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-sub {
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-tags {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 数据出境授权行 */
|
||||||
|
.smart-router-consent-row {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 16px;
|
||||||
|
padding: 16px 24px;
|
||||||
|
border: 1px solid var(--sr-line);
|
||||||
|
border-radius: 10px;
|
||||||
|
background: var(--surface-card);
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-consent-head {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-consent-head .ant-tag {
|
||||||
|
margin-inline-end: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 集合表:可点击复制的虚拟模型名 */
|
||||||
|
.smart-router-copy.ant-btn {
|
||||||
|
height: auto;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-name {
|
||||||
|
max-width: 260px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-field-label {
|
||||||
|
display: inline-flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-field-label .ant-tag {
|
||||||
|
margin-inline-end: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 编辑抽屉 */
|
||||||
|
.smart-router-sheet-footer {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 0 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-grid-full {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.smart-router-grid {
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-model-select {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 220px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-mono {
|
||||||
|
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-num {
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-matrix {
|
||||||
|
width: 100%;
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-matrix table {
|
||||||
|
border-collapse: separate;
|
||||||
|
border-spacing: 8px 8px;
|
||||||
|
min-width: 640px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-matrix th {
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--sr-muted);
|
||||||
|
text-align: left;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 试路由概率条:antd Progress,颜色沿用主题主色 */
|
||||||
|
.smart-router-prob-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-prob {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-prob-label {
|
||||||
|
width: 80px;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-prob-bar.ant-progress {
|
||||||
|
flex: 1;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-prob-value {
|
||||||
|
width: 40px;
|
||||||
|
flex: none;
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-kv {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: max-content 1fr;
|
||||||
|
gap: 8px 16px;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-kv dt {
|
||||||
|
color: var(--sr-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-kv dd {
|
||||||
|
margin: 0;
|
||||||
|
min-width: 0;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-settings-form {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
column-gap: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-setting-control.ant-input-number,
|
||||||
|
.smart-router-setting-control.ant-select,
|
||||||
|
.smart-router-setting-control.ant-input {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-key-tools {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-key-input {
|
||||||
|
width: min(320px, 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-sheet .ant-drawer-body {
|
||||||
|
padding: 24px;
|
||||||
|
scrollbar-gutter: stable;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-sheet .ant-modal {
|
||||||
|
max-width: calc(100vw - 32px);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.smart-router-card,
|
||||||
|
.smart-router-consent-row {
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-settings-form {
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-sheet .smart-router-inline > .ant-select,
|
||||||
|
.smart-router-sheet .smart-router-inline > .ant-input-number {
|
||||||
|
max-width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-sheet .smart-router-model-select {
|
||||||
|
flex-basis: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-key-tools > .ant-space-item,
|
||||||
|
.smart-router-key-input {
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-kv {
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.smart-router-kv dd {
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -390,7 +390,7 @@ export const getChannelsColumns = ({
|
|||||||
size='small'
|
size='small'
|
||||||
type='primary'
|
type='primary'
|
||||||
theme='outline'
|
theme='outline'
|
||||||
onClick={(e) => {
|
onClick={async (e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
writeClipboardText(record.remark)
|
writeClipboardText(record.remark)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
|
|||||||
@@ -180,6 +180,7 @@ const originInputs = {
|
|||||||
chat_image_to_images_enabled: false,
|
chat_image_to_images_enabled: false,
|
||||||
system_prompt: '',
|
system_prompt: '',
|
||||||
system_prompt_override: false,
|
system_prompt_override: false,
|
||||||
|
responses_system_prompt_mode: 'native',
|
||||||
client_only: false, // 只接受 Claude Code 客户端请求
|
client_only: false, // 只接受 Claude Code 客户端请求
|
||||||
bound_user_ids: '', // 绑定用户ID列表
|
bound_user_ids: '', // 绑定用户ID列表
|
||||||
os_restriction: [], // 操作系统白名单,仅 Claude 原生渠道(type=14)生效,空数组=无限制
|
os_restriction: [], // 操作系统白名单,仅 Claude 原生渠道(type=14)生效,空数组=无限制
|
||||||
@@ -190,6 +191,7 @@ const originInputs = {
|
|||||||
sticky_user_id_mode: 'native', // 注入形态:native(仿 Claude Code 原生)/ opaque
|
sticky_user_id_mode: 'native', // 注入形态:native(仿 Claude Code 原生)/ opaque
|
||||||
cache_breakpoint_fill: false, // 给完全没有 cache_control 的大上下文请求补一个缓存断点
|
cache_breakpoint_fill: false, // 给完全没有 cache_control 的大上下文请求补一个缓存断点
|
||||||
cache_breakpoint_min_tokens: 0, // 注入门限(估算 prompt token),0=用后端默认 10000
|
cache_breakpoint_min_tokens: 0, // 注入门限(估算 prompt token),0=用后端默认 10000
|
||||||
|
cache_creation_default_ttl: '', // 未分档缓存创建按哪档计费,''=跟随全局,可选 5m/1h
|
||||||
settings: '',
|
settings: '',
|
||||||
// 仅 Vertex: 密钥格式(存入 settings.vertex_key_type)
|
// 仅 Vertex: 密钥格式(存入 settings.vertex_key_type)
|
||||||
vertex_key_type: 'json',
|
vertex_key_type: 'json',
|
||||||
@@ -423,6 +425,8 @@ const EditChannelModal = (props) => {
|
|||||||
pass_through_body_enabled: false,
|
pass_through_body_enabled: false,
|
||||||
chat_image_to_images_enabled: false,
|
chat_image_to_images_enabled: false,
|
||||||
system_prompt: '',
|
system_prompt: '',
|
||||||
|
system_prompt_override: false,
|
||||||
|
responses_system_prompt_mode: 'native',
|
||||||
client_only: false,
|
client_only: false,
|
||||||
bound_user_ids: '',
|
bound_user_ids: '',
|
||||||
os_restriction: [],
|
os_restriction: [],
|
||||||
@@ -433,6 +437,7 @@ const EditChannelModal = (props) => {
|
|||||||
sticky_user_id_mode: 'native',
|
sticky_user_id_mode: 'native',
|
||||||
cache_breakpoint_fill: false,
|
cache_breakpoint_fill: false,
|
||||||
cache_breakpoint_min_tokens: 0,
|
cache_breakpoint_min_tokens: 0,
|
||||||
|
cache_creation_default_ttl: '',
|
||||||
});
|
});
|
||||||
const showApiConfigCard = true; // 控制是否显示 API 配置卡片
|
const showApiConfigCard = true; // 控制是否显示 API 配置卡片
|
||||||
const getInitValues = () => ({
|
const getInitValues = () => ({
|
||||||
@@ -626,6 +631,10 @@ const EditChannelModal = (props) => {
|
|||||||
data.system_prompt = parsedSettings.system_prompt || '';
|
data.system_prompt = parsedSettings.system_prompt || '';
|
||||||
data.system_prompt_override =
|
data.system_prompt_override =
|
||||||
parsedSettings.system_prompt_override || false;
|
parsedSettings.system_prompt_override || false;
|
||||||
|
data.responses_system_prompt_mode =
|
||||||
|
parsedSettings.responses_system_prompt_mode === 'input_user_message'
|
||||||
|
? 'input_user_message'
|
||||||
|
: 'native';
|
||||||
data.client_only = parsedSettings.client_only || false;
|
data.client_only = parsedSettings.client_only || false;
|
||||||
data.bound_user_ids = parsedSettings.bound_user_ids || '';
|
data.bound_user_ids = parsedSettings.bound_user_ids || '';
|
||||||
data.os_restriction = Array.isArray(parsedSettings.os_restriction)
|
data.os_restriction = Array.isArray(parsedSettings.os_restriction)
|
||||||
@@ -646,6 +655,11 @@ const EditChannelModal = (props) => {
|
|||||||
parsedSettings.cache_breakpoint_fill || false;
|
parsedSettings.cache_breakpoint_fill || false;
|
||||||
data.cache_breakpoint_min_tokens =
|
data.cache_breakpoint_min_tokens =
|
||||||
parsedSettings.cache_breakpoint_min_tokens || 0;
|
parsedSettings.cache_breakpoint_min_tokens || 0;
|
||||||
|
data.cache_creation_default_ttl = ['5m', '1h'].includes(
|
||||||
|
parsedSettings.cache_creation_default_ttl,
|
||||||
|
)
|
||||||
|
? parsedSettings.cache_creation_default_ttl
|
||||||
|
: '';
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('解析渠道设置失败:', error);
|
console.error('解析渠道设置失败:', error);
|
||||||
data.force_format = false;
|
data.force_format = false;
|
||||||
@@ -656,6 +670,7 @@ const EditChannelModal = (props) => {
|
|||||||
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;
|
||||||
|
data.responses_system_prompt_mode = 'native';
|
||||||
data.client_only = false;
|
data.client_only = false;
|
||||||
data.bound_user_ids = '';
|
data.bound_user_ids = '';
|
||||||
data.os_restriction = [];
|
data.os_restriction = [];
|
||||||
@@ -666,6 +681,7 @@ const EditChannelModal = (props) => {
|
|||||||
data.sticky_user_id_mode = 'native';
|
data.sticky_user_id_mode = 'native';
|
||||||
data.cache_breakpoint_fill = false;
|
data.cache_breakpoint_fill = false;
|
||||||
data.cache_breakpoint_min_tokens = 0;
|
data.cache_breakpoint_min_tokens = 0;
|
||||||
|
data.cache_creation_default_ttl = '';
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
data.force_format = false;
|
data.force_format = false;
|
||||||
@@ -676,6 +692,7 @@ const EditChannelModal = (props) => {
|
|||||||
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;
|
||||||
|
data.responses_system_prompt_mode = 'native';
|
||||||
data.client_only = false;
|
data.client_only = false;
|
||||||
data.bound_user_ids = '';
|
data.bound_user_ids = '';
|
||||||
data.os_restriction = [];
|
data.os_restriction = [];
|
||||||
@@ -686,6 +703,7 @@ const EditChannelModal = (props) => {
|
|||||||
data.sticky_user_id_mode = 'native';
|
data.sticky_user_id_mode = 'native';
|
||||||
data.cache_breakpoint_fill = false;
|
data.cache_breakpoint_fill = false;
|
||||||
data.cache_breakpoint_min_tokens = 0;
|
data.cache_breakpoint_min_tokens = 0;
|
||||||
|
data.cache_creation_default_ttl = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.settings) {
|
if (data.settings) {
|
||||||
@@ -792,6 +810,8 @@ const EditChannelModal = (props) => {
|
|||||||
data.chat_image_to_images_enabled || false,
|
data.chat_image_to_images_enabled || false,
|
||||||
system_prompt: data.system_prompt,
|
system_prompt: data.system_prompt,
|
||||||
system_prompt_override: data.system_prompt_override || false,
|
system_prompt_override: data.system_prompt_override || false,
|
||||||
|
responses_system_prompt_mode:
|
||||||
|
data.responses_system_prompt_mode || 'native',
|
||||||
client_only: data.client_only || false,
|
client_only: data.client_only || false,
|
||||||
bound_user_ids: data.bound_user_ids || '',
|
bound_user_ids: data.bound_user_ids || '',
|
||||||
os_restriction: Array.isArray(data.os_restriction)
|
os_restriction: Array.isArray(data.os_restriction)
|
||||||
@@ -806,6 +826,7 @@ const EditChannelModal = (props) => {
|
|||||||
sticky_user_id_mode: data.sticky_user_id_mode || 'native',
|
sticky_user_id_mode: data.sticky_user_id_mode || 'native',
|
||||||
cache_breakpoint_fill: data.cache_breakpoint_fill || false,
|
cache_breakpoint_fill: data.cache_breakpoint_fill || false,
|
||||||
cache_breakpoint_min_tokens: data.cache_breakpoint_min_tokens || 0,
|
cache_breakpoint_min_tokens: data.cache_breakpoint_min_tokens || 0,
|
||||||
|
cache_creation_default_ttl: data.cache_creation_default_ttl || '',
|
||||||
});
|
});
|
||||||
initialModelsRef.current = (data.models || [])
|
initialModelsRef.current = (data.models || [])
|
||||||
.map((model) => (model || '').trim())
|
.map((model) => (model || '').trim())
|
||||||
@@ -1075,6 +1096,7 @@ const EditChannelModal = (props) => {
|
|||||||
chat_image_to_images_enabled: false,
|
chat_image_to_images_enabled: false,
|
||||||
system_prompt: '',
|
system_prompt: '',
|
||||||
system_prompt_override: false,
|
system_prompt_override: false,
|
||||||
|
responses_system_prompt_mode: 'native',
|
||||||
client_only: false,
|
client_only: false,
|
||||||
bound_user_ids: '',
|
bound_user_ids: '',
|
||||||
os_restriction: [],
|
os_restriction: [],
|
||||||
@@ -1085,6 +1107,7 @@ const EditChannelModal = (props) => {
|
|||||||
sticky_user_id_mode: 'native',
|
sticky_user_id_mode: 'native',
|
||||||
cache_breakpoint_fill: false,
|
cache_breakpoint_fill: false,
|
||||||
cache_breakpoint_min_tokens: 0,
|
cache_breakpoint_min_tokens: 0,
|
||||||
|
cache_creation_default_ttl: '',
|
||||||
});
|
});
|
||||||
// 重置密钥模式状态
|
// 重置密钥模式状态
|
||||||
setKeyMode('append');
|
setKeyMode('append');
|
||||||
@@ -1403,6 +1426,11 @@ const EditChannelModal = (props) => {
|
|||||||
localInputs.chat_image_to_images_enabled || false,
|
localInputs.chat_image_to_images_enabled || false,
|
||||||
system_prompt: localInputs.system_prompt || '',
|
system_prompt: localInputs.system_prompt || '',
|
||||||
system_prompt_override: localInputs.system_prompt_override || false,
|
system_prompt_override: localInputs.system_prompt_override || false,
|
||||||
|
responses_system_prompt_mode: ['native', 'input_user_message'].includes(
|
||||||
|
localInputs.responses_system_prompt_mode,
|
||||||
|
)
|
||||||
|
? localInputs.responses_system_prompt_mode
|
||||||
|
: 'native',
|
||||||
client_only: localInputs.client_only || false,
|
client_only: localInputs.client_only || false,
|
||||||
bound_user_ids: localInputs.bound_user_ids || '',
|
bound_user_ids: localInputs.bound_user_ids || '',
|
||||||
os_restriction: Array.isArray(localInputs.os_restriction)
|
os_restriction: Array.isArray(localInputs.os_restriction)
|
||||||
@@ -1432,6 +1460,13 @@ const EditChannelModal = (props) => {
|
|||||||
0,
|
0,
|
||||||
parseInt(localInputs.cache_breakpoint_min_tokens, 10) || 0,
|
parseInt(localInputs.cache_breakpoint_min_tokens, 10) || 0,
|
||||||
),
|
),
|
||||||
|
// '' = 跟随全局「Claude设置」里的未分档缓存创建默认档位。
|
||||||
|
// 枚举外的值一律落回 '',后端 ValidateSettings 也会拒绝脏值。
|
||||||
|
cache_creation_default_ttl: ['5m', '1h'].includes(
|
||||||
|
localInputs.cache_creation_default_ttl,
|
||||||
|
)
|
||||||
|
? localInputs.cache_creation_default_ttl
|
||||||
|
: '',
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
localInputs.setting = mergeChannelSettings(
|
localInputs.setting = mergeChannelSettings(
|
||||||
@@ -1502,8 +1537,10 @@ const EditChannelModal = (props) => {
|
|||||||
delete localInputs.sticky_user_id_mode;
|
delete localInputs.sticky_user_id_mode;
|
||||||
delete localInputs.cache_breakpoint_fill;
|
delete localInputs.cache_breakpoint_fill;
|
||||||
delete localInputs.cache_breakpoint_min_tokens;
|
delete localInputs.cache_breakpoint_min_tokens;
|
||||||
|
delete localInputs.cache_creation_default_ttl;
|
||||||
delete localInputs.system_prompt;
|
delete localInputs.system_prompt;
|
||||||
delete localInputs.system_prompt_override;
|
delete localInputs.system_prompt_override;
|
||||||
|
delete localInputs.responses_system_prompt_mode;
|
||||||
delete localInputs.is_enterprise_account;
|
delete localInputs.is_enterprise_account;
|
||||||
// 顶层的 vertex_key_type 不应发送给后端
|
// 顶层的 vertex_key_type 不应发送给后端
|
||||||
delete localInputs.vertex_key_type;
|
delete localInputs.vertex_key_type;
|
||||||
@@ -1671,6 +1708,7 @@ const EditChannelModal = (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) {
|
||||||
@@ -2753,12 +2791,10 @@ const EditChannelModal = (props) => {
|
|||||||
showInfo(t('没有模型可以复制'));
|
showInfo(t('没有模型可以复制'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
// copy 失败返回 false 而不抛错,以返回值为准
|
||||||
if (!(await copy(inputs.models.join(',')))) {
|
if (await copy(inputs.models.join(','))) {
|
||||||
throw new Error('Clipboard copy failed');
|
|
||||||
}
|
|
||||||
showSuccess(t('模型列表已复制到剪贴板'));
|
showSuccess(t('模型列表已复制到剪贴板'));
|
||||||
} catch (error) {
|
} else {
|
||||||
showError(t('复制失败'));
|
showError(t('复制失败'));
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
@@ -3756,6 +3792,26 @@ const EditChannelModal = (props) => {
|
|||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<Form.Select
|
||||||
|
field='cache_creation_default_ttl'
|
||||||
|
label={t('未分档缓存创建默认档位')}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
optionList={[
|
||||||
|
{ label: t('跟随全局'), value: '' },
|
||||||
|
{ label: t('按 5 分钟档计费'), value: '5m' },
|
||||||
|
{ label: t('按 1 小时档计费'), value: '1h' },
|
||||||
|
]}
|
||||||
|
onChange={(value) =>
|
||||||
|
handleChannelSettingsChange(
|
||||||
|
'cache_creation_default_ttl',
|
||||||
|
value,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
extraText={t(
|
||||||
|
'本渠道上游只返回缓存创建总量、未给出 5m/1h 拆分时,这部分按哪一档倍率计费,优先级高于「模型设置 → Claude设置」里的全局默认档位。上游已明确分档的 token 永远按实际返回结算,与此项无关。号池确定「不带 ttl 参数即落 5 分钟」的渠道才需要改成 5m。',
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
<Form.Input
|
<Form.Input
|
||||||
field='proxy'
|
field='proxy'
|
||||||
label={t('代理地址')}
|
label={t('代理地址')}
|
||||||
@@ -3797,6 +3853,29 @@ const EditChannelModal = (props) => {
|
|||||||
'如果用户请求中包含系统提示词,则使用此设置拼接到用户的系统提示词前面',
|
'如果用户请求中包含系统提示词,则使用此设置拼接到用户的系统提示词前面',
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
<Form.Select
|
||||||
|
field='responses_system_prompt_mode'
|
||||||
|
label={t('Responses 系统提示词兼容模式')}
|
||||||
|
optionList={[
|
||||||
|
{
|
||||||
|
label: t('原生模式(默认)'),
|
||||||
|
value: 'native',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: t('号池兼容:放入 input 用户消息'),
|
||||||
|
value: 'input_user_message',
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
onChange={(value) =>
|
||||||
|
handleChannelSettingsChange(
|
||||||
|
'responses_system_prompt_mode',
|
||||||
|
value,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
extraText={t(
|
||||||
|
'仅对命中 ForceResponsesModels 的 Chat→Responses 桥接请求生效;直接 Responses 请求和图片接口不转换。',
|
||||||
|
)}
|
||||||
|
/>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -20,10 +20,8 @@ For commercial licensing, please contact support@quantumnous.com
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Button, Card } from 'antd';
|
import { Button, Card } from 'antd';
|
||||||
import { ChevronDown, ChevronUp } from '@/components/common/icons/ActionIcons';
|
import { ChevronDown, ChevronUp } from '@/components/common/icons/ActionIcons';
|
||||||
import PricingGroups from '../filter/PricingGroups';
|
|
||||||
import PricingVendors from '../filter/PricingVendors';
|
import PricingVendors from '../filter/PricingVendors';
|
||||||
import PricingQuotaTypes from '../filter/PricingQuotaTypes';
|
import PricingQuotaTypes from '../filter/PricingQuotaTypes';
|
||||||
import PricingTags from '../filter/PricingTags';
|
|
||||||
import PricingEndpointTypes from '../filter/PricingEndpointTypes';
|
import PricingEndpointTypes from '../filter/PricingEndpointTypes';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -37,29 +35,20 @@ const MarketFilterSidebar = ({
|
|||||||
vendorsMap,
|
vendorsMap,
|
||||||
filterVendor,
|
filterVendor,
|
||||||
setFilterVendor,
|
setFilterVendor,
|
||||||
filterGroup,
|
|
||||||
setFilterGroup,
|
|
||||||
usableGroup,
|
|
||||||
groupRatio,
|
|
||||||
showRatio,
|
|
||||||
filterQuotaType,
|
filterQuotaType,
|
||||||
setFilterQuotaType,
|
setFilterQuotaType,
|
||||||
filterTag,
|
|
||||||
setFilterTag,
|
|
||||||
filterEndpointType,
|
filterEndpointType,
|
||||||
setFilterEndpointType,
|
setFilterEndpointType,
|
||||||
endpointMap,
|
endpointMap,
|
||||||
allModels,
|
allModels,
|
||||||
tagModels,
|
|
||||||
quotaTypeModels,
|
quotaTypeModels,
|
||||||
endpointTypeModels,
|
endpointTypeModels,
|
||||||
groupCountModels,
|
|
||||||
}) => (
|
}) => (
|
||||||
<Card className='mm-filter-panel' aria-label={t('模型筛选')}>
|
<Card className='mm-filter-panel' aria-label={t('模型筛选')}>
|
||||||
<div className='mm-filter-title'>
|
<div className='mm-filter-title'>
|
||||||
<div>
|
<div>
|
||||||
<h2>{t('筛选模型')}</h2>
|
<h2>{t('筛选模型')}</h2>
|
||||||
<span>{t('按分组、厂商和计费方式快速定位')}</span>
|
<span>{[t('模型厂商'), t('计费类型'), t('端点类型')].join(' / ')}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className='mm-filter-actions'>
|
<div className='mm-filter-actions'>
|
||||||
<Button type='text' onClick={onReset}>
|
<Button type='text' onClick={onReset}>
|
||||||
@@ -95,24 +84,6 @@ const MarketFilterSidebar = ({
|
|||||||
models={quotaTypeModels}
|
models={quotaTypeModels}
|
||||||
title={t('计费类型')}
|
title={t('计费类型')}
|
||||||
/>
|
/>
|
||||||
<PricingGroups
|
|
||||||
filterGroup={filterGroup}
|
|
||||||
setFilterGroup={setFilterGroup}
|
|
||||||
groupRatio={groupRatio}
|
|
||||||
usableGroup={usableGroup}
|
|
||||||
showRatio={showRatio}
|
|
||||||
t={t}
|
|
||||||
models={groupCountModels}
|
|
||||||
title={t('用户分组')}
|
|
||||||
/>
|
|
||||||
<PricingTags
|
|
||||||
filterTag={filterTag}
|
|
||||||
setFilterTag={setFilterTag}
|
|
||||||
t={t}
|
|
||||||
models={tagModels}
|
|
||||||
allModels={allModels}
|
|
||||||
title={t('模型标签')}
|
|
||||||
/>
|
|
||||||
<PricingEndpointTypes
|
<PricingEndpointTypes
|
||||||
filterEndpointType={filterEndpointType}
|
filterEndpointType={filterEndpointType}
|
||||||
setFilterEndpointType={setFilterEndpointType}
|
setFilterEndpointType={setFilterEndpointType}
|
||||||
|
|||||||
@@ -82,16 +82,15 @@ const ModelMarketPage = () => {
|
|||||||
models,
|
models,
|
||||||
} = pricingData;
|
} = pricingData;
|
||||||
|
|
||||||
const { quotaTypeModels, endpointTypeModels, tagModels, groupCountModels } =
|
const { quotaTypeModels, endpointTypeModels } = usePricingFilterCounts({
|
||||||
usePricingFilterCounts({
|
models,
|
||||||
models,
|
filterGroup,
|
||||||
filterGroup,
|
filterQuotaType,
|
||||||
filterQuotaType,
|
filterEndpointType,
|
||||||
filterEndpointType,
|
filterVendor,
|
||||||
filterVendor,
|
filterTag,
|
||||||
filterTag,
|
searchValue,
|
||||||
searchValue,
|
});
|
||||||
});
|
|
||||||
|
|
||||||
// 复用原侧栏的 resetPricingFilters:清空搜索词与五类筛选。
|
// 复用原侧栏的 resetPricingFilters:清空搜索词与五类筛选。
|
||||||
// 不传货币 / 单位 / 视图 setter,避免改动页面既有的计价展示口径。
|
// 不传货币 / 单位 / 视图 setter,避免改动页面既有的计价展示口径。
|
||||||
@@ -141,23 +140,14 @@ const ModelMarketPage = () => {
|
|||||||
vendorsMap={vendorsMap}
|
vendorsMap={vendorsMap}
|
||||||
filterVendor={filterVendor}
|
filterVendor={filterVendor}
|
||||||
setFilterVendor={setFilterVendor}
|
setFilterVendor={setFilterVendor}
|
||||||
filterGroup={filterGroup}
|
|
||||||
setFilterGroup={setFilterGroup}
|
|
||||||
usableGroup={usableGroup}
|
|
||||||
groupRatio={groupRatio}
|
|
||||||
showRatio={showRatio}
|
|
||||||
filterQuotaType={filterQuotaType}
|
filterQuotaType={filterQuotaType}
|
||||||
setFilterQuotaType={setFilterQuotaType}
|
setFilterQuotaType={setFilterQuotaType}
|
||||||
filterTag={filterTag}
|
|
||||||
setFilterTag={setFilterTag}
|
|
||||||
filterEndpointType={filterEndpointType}
|
filterEndpointType={filterEndpointType}
|
||||||
setFilterEndpointType={setFilterEndpointType}
|
setFilterEndpointType={setFilterEndpointType}
|
||||||
endpointMap={endpointMap}
|
endpointMap={endpointMap}
|
||||||
allModels={models}
|
allModels={models}
|
||||||
tagModels={tagModels}
|
|
||||||
quotaTypeModels={quotaTypeModels}
|
quotaTypeModels={quotaTypeModels}
|
||||||
endpointTypeModels={endpointTypeModels}
|
endpointTypeModels={endpointTypeModels}
|
||||||
groupCountModels={groupCountModels}
|
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ For commercial licensing, please contact support@quantumnous.com
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Tag as AntTag } from 'antd';
|
import { Tag as AntTag } from 'antd';
|
||||||
import { Progress, Tooltip, Typography } from '@/components/ui';
|
import { Progress, Tooltip, Typography } from '@/components/ui';
|
||||||
|
import { fundAccountDisplay } from '../../../pages/Organization/fund/fundFormat';
|
||||||
import {
|
import {
|
||||||
Music,
|
Music,
|
||||||
FileText,
|
FileText,
|
||||||
@@ -570,6 +571,33 @@ export const getTaskLogsColumns = ({
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
...(COLUMN_KEYS.FUND_DEPT
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
key: COLUMN_KEYS.FUND_DEPT,
|
||||||
|
title: t('归属部门'),
|
||||||
|
dataIndex: 'fund_dept_name',
|
||||||
|
render: (v) => (
|
||||||
|
<span className='block max-w-[140px] truncate' title={v || ''}>
|
||||||
|
{v === undefined || v === null ? '—' : v || t('未归属部门')}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: COLUMN_KEYS.FUND_ACCOUNT,
|
||||||
|
title: t('扣费账户'),
|
||||||
|
dataIndex: 'fund_account_type',
|
||||||
|
render: (v, record) =>
|
||||||
|
v === undefined || v === null ? (
|
||||||
|
'—'
|
||||||
|
) : (
|
||||||
|
<span className='block max-w-[180px] truncate'>
|
||||||
|
{fundAccountDisplay(t, v, record.fund_dept_name)}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
{
|
{
|
||||||
key: COLUMN_KEYS.FAIL_REASON,
|
key: COLUMN_KEYS.FAIL_REASON,
|
||||||
title: t('详情'),
|
title: t('详情'),
|
||||||
|
|||||||
@@ -72,6 +72,7 @@ const ContentModal = ({
|
|||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 走公共 copy:HTTP 部署下 navigator.clipboard 为 undefined,裸调会同步抛错、点了无反应
|
||||||
const handleCopyUrl = () => {
|
const handleCopyUrl = () => {
|
||||||
writeClipboardText(shareUrl)
|
writeClipboardText(shareUrl)
|
||||||
.then(() => showSuccess(t('链接已复制')))
|
.then(() => showSuccess(t('链接已复制')))
|
||||||
|
|||||||
@@ -283,7 +283,7 @@ function renderModelName(record, copyText, t, isRootUser) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- 使用记录(个人端)呈现:原型为 Ant Design 预设无边框标签与纯文本,不含渐变点、脉冲与悬停缩放 ----
|
// ---- 使用记录(个人端)呈现 ----
|
||||||
const RECORD_TYPE_COLORS = {
|
const RECORD_TYPE_COLORS = {
|
||||||
1: 'cyan',
|
1: 'cyan',
|
||||||
2: 'green',
|
2: 'green',
|
||||||
@@ -312,19 +312,39 @@ function renderRecordType(type, t) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function renderRecordUseTime(record, t) {
|
function renderRecordUseTime(record, t) {
|
||||||
const useTime = `${parseInt(record.use_time)}s`;
|
const useTime = parseInt(record.use_time, 10);
|
||||||
|
const validUseTime = Number.isFinite(useTime) && useTime >= 0;
|
||||||
const other = getLogOther(record.other);
|
const other = getLogOther(record.other);
|
||||||
const firstTime =
|
const firstMilliseconds = parseFloat(other?.frt);
|
||||||
record.is_stream && other?.frt
|
const validFirstTime =
|
||||||
? ` / ${(parseFloat(other.frt) / 1000.0).toFixed(1)}s`
|
Number.isFinite(firstMilliseconds) && firstMilliseconds >= 0;
|
||||||
: '';
|
// 首字耗时按实际显示的一位小数判色,避免显示 3.0s / 10.0s 却仍落在上一档。
|
||||||
|
const firstTime = validFirstTime
|
||||||
|
? (firstMilliseconds / 1000).toFixed(1)
|
||||||
|
: null;
|
||||||
|
const useTimeColor = !validUseTime
|
||||||
|
? undefined
|
||||||
|
: useTime < 101
|
||||||
|
? 'green'
|
||||||
|
: useTime < 300
|
||||||
|
? 'gold'
|
||||||
|
: 'magenta';
|
||||||
|
const firstTimeColor = !validFirstTime
|
||||||
|
? undefined
|
||||||
|
: Number(firstTime) < 3
|
||||||
|
? 'cyan'
|
||||||
|
: Number(firstTime) < 10
|
||||||
|
? 'orange'
|
||||||
|
: 'red';
|
||||||
return (
|
return (
|
||||||
<span className='usage-record-use-time'>
|
<span className='usage-record-use-time' aria-label={t('用时/首字')}>
|
||||||
<span>
|
<AntTag color={useTimeColor}>{validUseTime ? `${useTime}s` : '—'}</AntTag>
|
||||||
{useTime}
|
{record.is_stream && (
|
||||||
{firstTime && <em>{firstTime}</em>}
|
<AntTag color={firstTimeColor}>
|
||||||
</span>
|
{validFirstTime ? `${firstTime}s` : '—'}
|
||||||
<AntTag variant='filled' color={record.is_stream ? 'cyan' : undefined}>
|
</AntTag>
|
||||||
|
)}
|
||||||
|
<AntTag color={record.is_stream ? 'blue' : undefined}>
|
||||||
{record.is_stream ? t('流') : t('非流')}
|
{record.is_stream ? t('流') : t('非流')}
|
||||||
</AntTag>
|
</AntTag>
|
||||||
</span>
|
</span>
|
||||||
@@ -336,7 +356,7 @@ const formatRecordNumber = (value) => {
|
|||||||
return Number.isFinite(number) ? number.toLocaleString('en-US') : value;
|
return Number.isFinite(number) ? number.toLocaleString('en-US') : value;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Both reference images show the same 2097px table at opposite scroll positions.
|
// 固定列宽保持横向滚动时的对齐,耗时列预留三枚标签的空间。
|
||||||
const RECORD_COLUMN_WIDTHS = {
|
const RECORD_COLUMN_WIDTHS = {
|
||||||
time: 152,
|
time: 152,
|
||||||
channel: 85,
|
channel: 85,
|
||||||
@@ -345,7 +365,7 @@ const RECORD_COLUMN_WIDTHS = {
|
|||||||
group: 148,
|
group: 148,
|
||||||
type: 110,
|
type: 110,
|
||||||
model: 225,
|
model: 225,
|
||||||
use_time: 126,
|
use_time: 190,
|
||||||
prompt: 110,
|
prompt: 110,
|
||||||
completion: 110,
|
completion: 110,
|
||||||
cost: 136,
|
cost: 136,
|
||||||
@@ -844,6 +864,10 @@ export const getLogsColumns = ({
|
|||||||
other.cache_creation_ratio_1h ||
|
other.cache_creation_ratio_1h ||
|
||||||
other.cache_creation_ratio ||
|
other.cache_creation_ratio ||
|
||||||
1.0,
|
1.0,
|
||||||
|
other.cache_creation_tokens_unlabeled || 0,
|
||||||
|
other.cache_creation_ratio_unlabeled ||
|
||||||
|
other.cache_creation_ratio ||
|
||||||
|
1.0,
|
||||||
false,
|
false,
|
||||||
1.0,
|
1.0,
|
||||||
other?.is_system_prompt_overwritten,
|
other?.is_system_prompt_overwritten,
|
||||||
@@ -862,6 +886,8 @@ export const getLogsColumns = ({
|
|||||||
1.0,
|
1.0,
|
||||||
0,
|
0,
|
||||||
1.0,
|
1.0,
|
||||||
|
0,
|
||||||
|
1.0,
|
||||||
false,
|
false,
|
||||||
1.0,
|
1.0,
|
||||||
other?.is_system_prompt_overwritten,
|
other?.is_system_prompt_overwritten,
|
||||||
|
|||||||
@@ -116,15 +116,18 @@ const UsageBillingDetail = ({
|
|||||||
const other = getLogOther(record.other) || {};
|
const other = getLogOther(record.other) || {};
|
||||||
const inputTokens = Number(record.prompt_tokens || 0);
|
const inputTokens = Number(record.prompt_tokens || 0);
|
||||||
const outputTokens = Number(record.completion_tokens || 0);
|
const outputTokens = Number(record.completion_tokens || 0);
|
||||||
const cacheTokens =
|
|
||||||
Number(other.cache_tokens || 0) +
|
|
||||||
Number(other.cache_creation_tokens || 0) +
|
|
||||||
Number(other.cache_creation_tokens_5m || 0) +
|
|
||||||
Number(other.cache_creation_tokens_1h || 0);
|
|
||||||
const textTokens = inputTokens + outputTokens;
|
const textTokens = inputTokens + outputTokens;
|
||||||
// 有 5m/1h 分档时只展示分档,不再重复展示未分档的总量与倍率
|
// 缓存创建按上游实际返回分三桶:明确的 5m / 1h,以及上游只给了总量没给分档的「未分档」。
|
||||||
|
// 三桶按各自倍率结算,所以三桶都得露出来——少露一桶,用户拿界面上的 token × 倍率就加不出账单金额。
|
||||||
const hasSplitCacheCreation =
|
const hasSplitCacheCreation =
|
||||||
other.cache_creation_tokens_5m > 0 || other.cache_creation_tokens_1h > 0;
|
other.cache_creation_tokens_5m > 0 || other.cache_creation_tokens_1h > 0;
|
||||||
|
// 未分档桶只在与分档并存时单独成行;没有分档时,下面的「缓存创建 / 缓存创建倍率」
|
||||||
|
// 本身说的就是这一桶,再列一遍是重复
|
||||||
|
const unlabeledCacheCreation = Number(
|
||||||
|
other.cache_creation_tokens_unlabeled || 0,
|
||||||
|
);
|
||||||
|
const showUnlabeledCacheCreation =
|
||||||
|
hasSplitCacheCreation && unlabeledCacheCreation > 0;
|
||||||
const effectiveGroupRatio =
|
const effectiveGroupRatio =
|
||||||
Number.isFinite(Number(other.user_group_ratio)) &&
|
Number.isFinite(Number(other.user_group_ratio)) &&
|
||||||
Number(other.user_group_ratio) !== -1
|
Number(other.user_group_ratio) !== -1
|
||||||
@@ -151,6 +154,10 @@ const UsageBillingDetail = ({
|
|||||||
label: t('1h 缓存创建'),
|
label: t('1h 缓存创建'),
|
||||||
value: formatCount(other.cache_creation_tokens_1h),
|
value: formatCount(other.cache_creation_tokens_1h),
|
||||||
},
|
},
|
||||||
|
showUnlabeledCacheCreation && {
|
||||||
|
label: t('未分档缓存创建'),
|
||||||
|
value: formatCount(unlabeledCacheCreation),
|
||||||
|
},
|
||||||
other.model_ratio != null && {
|
other.model_ratio != null && {
|
||||||
label: t('模型倍率'),
|
label: t('模型倍率'),
|
||||||
value: formatRatio(other.model_ratio),
|
value: formatRatio(other.model_ratio),
|
||||||
@@ -160,7 +167,10 @@ const UsageBillingDetail = ({
|
|||||||
value: formatRatio(other.completion_ratio),
|
value: formatRatio(other.completion_ratio),
|
||||||
},
|
},
|
||||||
other.cache_ratio != null &&
|
other.cache_ratio != null &&
|
||||||
cacheTokens > 0 && {
|
other.cache_tokens > 0 && {
|
||||||
|
// cache_ratio 是缓存命中(读)的倍率,与缓存创建(写)无关。
|
||||||
|
// 过去这里的闸门把写入 token 也算进来,于是只写不读的请求也会挂一个
|
||||||
|
// 没有对应 token 的「缓存倍率 0.1x」,看着像漏算了一笔钱。
|
||||||
label: t('缓存倍率'),
|
label: t('缓存倍率'),
|
||||||
value: formatRatio(other.cache_ratio),
|
value: formatRatio(other.cache_ratio),
|
||||||
},
|
},
|
||||||
@@ -180,6 +190,11 @@ const UsageBillingDetail = ({
|
|||||||
label: t('1h 缓存倍率'),
|
label: t('1h 缓存倍率'),
|
||||||
value: formatRatio(other.cache_creation_ratio_1h),
|
value: formatRatio(other.cache_creation_ratio_1h),
|
||||||
},
|
},
|
||||||
|
showUnlabeledCacheCreation &&
|
||||||
|
other.cache_creation_ratio_unlabeled != null && {
|
||||||
|
label: t('未分档缓存倍率'),
|
||||||
|
value: formatRatio(other.cache_creation_ratio_unlabeled),
|
||||||
|
},
|
||||||
effectiveGroupRatio != null && {
|
effectiveGroupRatio != null && {
|
||||||
label: t('分组倍率'),
|
label: t('分组倍率'),
|
||||||
value: formatRatio(effectiveGroupRatio),
|
value: formatRatio(effectiveGroupRatio),
|
||||||
|
|||||||
@@ -246,8 +246,10 @@ const renderOperations = (
|
|||||||
|
|
||||||
const currentRole = Number(getUserData()?.role || 0);
|
const currentRole = Number(getUserData()?.role || 0);
|
||||||
const recordRole = Number(record.role || 0);
|
const recordRole = Number(record.role || 0);
|
||||||
const canManage = isAdmin() && (currentRole >= 100 || recordRole < 100);
|
// 与后端 canManageUserOfRole 一致:非超级管理员只能管理角色低于自己的用户;提升/降级仅超级管理员
|
||||||
const canChangeRole = canManage && recordRole < 100;
|
const canManage =
|
||||||
|
isAdmin() && (currentRole >= 100 || recordRole < currentRole);
|
||||||
|
const canChangeRole = canManage && currentRole >= 100 && recordRole < 100;
|
||||||
|
|
||||||
// 低频动作全部收进「更多」下拉,操作列稳定为一行三个控件,避免跨行撑高行高
|
// 低频动作全部收进「更多」下拉,操作列稳定为一行三个控件,避免跨行撑高行高
|
||||||
const moreMenu = [];
|
const moreMenu = [];
|
||||||
|
|||||||
@@ -17,7 +17,13 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|||||||
For commercial licensing, please contact support@quantumnous.com
|
For commercial licensing, please contact support@quantumnous.com
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import React, { forwardRef, useLayoutEffect, useRef, useState } from 'react';
|
import React, {
|
||||||
|
forwardRef,
|
||||||
|
useEffect,
|
||||||
|
useLayoutEffect,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
} from 'react';
|
||||||
import { Table, theme } from 'antd';
|
import { Table, theme } from 'antd';
|
||||||
import { colord } from 'colord';
|
import { colord } from 'colord';
|
||||||
import { isCenterTableScope, prepareCenterColumns } from './centerTablePolicy';
|
import { isCenterTableScope, prepareCenterColumns } from './centerTablePolicy';
|
||||||
@@ -56,8 +62,21 @@ const CenterTable = forwardRef(function CenterTable(
|
|||||||
const scroller = root.querySelector('.ant-table-content,.ant-table-body');
|
const scroller = root.querySelector('.ant-table-content,.ant-table-body');
|
||||||
const previousTabIndex = scroller?.getAttribute('tabindex');
|
const previousTabIndex = scroller?.getAttribute('tabindex');
|
||||||
if (scroller && previousTabIndex === null) scroller.tabIndex = 0;
|
if (scroller && previousTabIndex === null) scroller.tabIndex = 0;
|
||||||
const update = () => setWidth(root.clientWidth);
|
const observer = new ResizeObserver(([entry]) => {
|
||||||
update();
|
// ResizeObserver already measured the box; avoid a synchronous layout read.
|
||||||
|
setWidth(entry.contentRect.width);
|
||||||
|
});
|
||||||
|
observer.observe(root);
|
||||||
|
return () => {
|
||||||
|
observer.disconnect();
|
||||||
|
if (scroller && previousTabIndex === null)
|
||||||
|
scroller.removeAttribute('tabindex');
|
||||||
|
};
|
||||||
|
}, [enabled]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!enabled) return;
|
||||||
|
const root = tableRef.current?.nativeElement;
|
||||||
|
if (!root) return;
|
||||||
const measureActionWidths = () => {
|
const measureActionWidths = () => {
|
||||||
const next = {};
|
const next = {};
|
||||||
root.querySelectorAll('th.center-action-cell').forEach((header) => {
|
root.querySelectorAll('th.center-action-cell').forEach((header) => {
|
||||||
@@ -69,9 +88,15 @@ const CenterTable = forwardRef(function CenterTable(
|
|||||||
(element) => element.getBoundingClientRect().width > 0,
|
(element) => element.getBoundingClientRect().width > 0,
|
||||||
);
|
);
|
||||||
const widths = cells.map((cell) => {
|
const widths = cells.map((cell) => {
|
||||||
const controls = [
|
const controlsWithWidths = [
|
||||||
...cell.querySelectorAll('button, a, [role="button"]'),
|
...cell.querySelectorAll('button, a, [role="button"]'),
|
||||||
].filter((element) => element.getBoundingClientRect().width > 0);
|
]
|
||||||
|
.map((element) => ({
|
||||||
|
element,
|
||||||
|
width: element.getBoundingClientRect().width,
|
||||||
|
}))
|
||||||
|
.filter(({ width }) => width > 0);
|
||||||
|
const controls = controlsWithWidths.map(({ element }) => element);
|
||||||
if (!controls.length) return 0;
|
if (!controls.length) return 0;
|
||||||
let group = controls[0].parentElement;
|
let group = controls[0].parentElement;
|
||||||
while (
|
while (
|
||||||
@@ -85,10 +110,7 @@ const CenterTable = forwardRef(function CenterTable(
|
|||||||
(Number.parseFloat(cellStyle.paddingRight) || 0);
|
(Number.parseFloat(cellStyle.paddingRight) || 0);
|
||||||
const gap = Number.parseFloat(getComputedStyle(group).columnGap) || 8;
|
const gap = Number.parseFloat(getComputedStyle(group).columnGap) || 8;
|
||||||
return (
|
return (
|
||||||
controls.reduce(
|
controlsWithWidths.reduce((total, { width }) => total + width, 0) +
|
||||||
(total, element) => total + element.getBoundingClientRect().width,
|
|
||||||
0,
|
|
||||||
) +
|
|
||||||
gap * Math.max(0, controls.length - 1) +
|
gap * Math.max(0, controls.length - 1) +
|
||||||
padding
|
padding
|
||||||
);
|
);
|
||||||
@@ -107,13 +129,8 @@ const CenterTable = forwardRef(function CenterTable(
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
const frame = requestAnimationFrame(measureActionWidths);
|
const frame = requestAnimationFrame(measureActionWidths);
|
||||||
const observer = new ResizeObserver(update);
|
|
||||||
observer.observe(root);
|
|
||||||
return () => {
|
return () => {
|
||||||
observer.disconnect();
|
|
||||||
cancelAnimationFrame(frame);
|
cancelAnimationFrame(frame);
|
||||||
if (scroller && previousTabIndex === null)
|
|
||||||
scroller.removeAttribute('tabindex');
|
|
||||||
};
|
};
|
||||||
}, [enabled, width, columns, props.dataSource]);
|
}, [enabled, width, columns, props.dataSource]);
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -261,8 +261,11 @@ export default function UiThemeProvider({ children }) {
|
|||||||
// 日期面板的星期、月份名称来自 dayjs 全局语言,需与 Ant Design locale 保持一致。
|
// 日期面板的星期、月份名称来自 dayjs 全局语言,需与 Ant Design locale 保持一致。
|
||||||
dayjs.locale(DAYJS_LOCALES[language] || 'zh-cn');
|
dayjs.locale(DAYJS_LOCALES[language] || 'zh-cn');
|
||||||
useLayoutEffect(() => {
|
useLayoutEffect(() => {
|
||||||
|
// The hosted download page shares the system shell and its popup tokens.
|
||||||
|
const isDownloadPage = /^\/weyai\/download\/?$/.test(pathname);
|
||||||
document.body.dataset.uiScope =
|
document.body.dataset.uiScope =
|
||||||
pathname.startsWith('/weyai/') || pathname.startsWith('/client/authorize')
|
(pathname.startsWith('/weyai/') && !isDownloadPage) ||
|
||||||
|
pathname.startsWith('/client/authorize')
|
||||||
? 'external'
|
? 'external'
|
||||||
: 'admin';
|
: 'admin';
|
||||||
}, [pathname]);
|
}, [pathname]);
|
||||||
|
|||||||
@@ -36,7 +36,10 @@ import {
|
|||||||
Space as AntSpace,
|
Space as AntSpace,
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import { useConsoleControlSize } from '../console/ConsoleContext';
|
import {
|
||||||
|
useConsoleControlSize,
|
||||||
|
useConsolePage,
|
||||||
|
} from '../console/ConsoleContext';
|
||||||
|
|
||||||
export const controlSize = (size) => (size === 'default' ? 'middle' : size);
|
export const controlSize = (size) => (size === 'default' ? 'middle' : size);
|
||||||
export const placement = (position) =>
|
export const placement = (position) =>
|
||||||
@@ -53,6 +56,12 @@ export const placement = (position) =>
|
|||||||
const statusOf = (status) =>
|
const statusOf = (status) =>
|
||||||
['error', 'warning'].includes(status) ? status : undefined;
|
['error', 'warning'].includes(status) ? status : undefined;
|
||||||
|
|
||||||
|
function useSettingsInputId(id) {
|
||||||
|
const generatedId = React.useId();
|
||||||
|
const isSettings = useConsolePage()?.page.key === 'setting';
|
||||||
|
return id ?? (isSettings ? generatedId : undefined);
|
||||||
|
}
|
||||||
|
|
||||||
// Existing screens consume values; DOM events stay inside this view boundary.
|
// Existing screens consume values; DOM events stay inside this view boundary.
|
||||||
export const Input = forwardRef(function Input(
|
export const Input = forwardRef(function Input(
|
||||||
{
|
{
|
||||||
@@ -69,10 +78,20 @@ export const Input = forwardRef(function Input(
|
|||||||
},
|
},
|
||||||
ref,
|
ref,
|
||||||
) {
|
) {
|
||||||
|
const isSettings = useConsolePage()?.page.key === 'setting';
|
||||||
const Component = mode === 'password' ? AntInput.Password : AntInput;
|
const Component = mode === 'password' ? AntInput.Password : AntInput;
|
||||||
return (
|
return (
|
||||||
<Component
|
<Component
|
||||||
{...props}
|
{...props}
|
||||||
|
id={useSettingsInputId(props.id)}
|
||||||
|
autoComplete={
|
||||||
|
props.autoComplete ??
|
||||||
|
(isSettings
|
||||||
|
? mode === 'password' || props.type === 'password'
|
||||||
|
? 'new-password'
|
||||||
|
: 'off'
|
||||||
|
: undefined)
|
||||||
|
}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
size={useConsoleControlSize(size)}
|
size={useConsoleControlSize(size)}
|
||||||
readOnly={readonly ?? props.readOnly}
|
readOnly={readonly ?? props.readOnly}
|
||||||
@@ -91,6 +110,7 @@ export const TextArea = forwardRef(function TextArea(
|
|||||||
return (
|
return (
|
||||||
<AntInput.TextArea
|
<AntInput.TextArea
|
||||||
{...props}
|
{...props}
|
||||||
|
id={useSettingsInputId(props.id)}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
autoSize={autosize}
|
autoSize={autosize}
|
||||||
maxLength={props.maxLength ?? maxCount}
|
maxLength={props.maxLength ?? maxCount}
|
||||||
@@ -152,6 +172,7 @@ export const InputNumber = forwardRef(function InputNumber(
|
|||||||
return (
|
return (
|
||||||
<AntInputNumber
|
<AntInputNumber
|
||||||
{...props}
|
{...props}
|
||||||
|
id={useSettingsInputId(props.id)}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
size={useConsoleControlSize(size)}
|
size={useConsoleControlSize(size)}
|
||||||
controls={!hideButtons}
|
controls={!hideButtons}
|
||||||
@@ -373,6 +394,13 @@ const toDate = (value) =>
|
|||||||
Array.isArray(value)
|
Array.isArray(value)
|
||||||
? value.map((v) => v?.toDate() ?? null)
|
? value.map((v) => v?.toDate() ?? null)
|
||||||
: (value?.toDate() ?? null);
|
: (value?.toDate() ?? null);
|
||||||
|
// Semi 契约:DatePicker / TimePicker 的 onChange 为 (Date | Date[], 文本 | 文本[])(onChangeWithDateFirst
|
||||||
|
// 默认 true),存量页面与 Form.DatePicker(取第一个参数为字段值)都按此编写;清空时 Date 为 null、文本为 ''。
|
||||||
|
// format 沿用 Semi 的 date-fns 记法(yyyy-MM-dd),在此转换为 dayjs 记法(YYYY-MM-DD)。
|
||||||
|
const toDayjsFormat = (format) =>
|
||||||
|
typeof format === 'string'
|
||||||
|
? format.replace(/y/g, 'Y').replace(/d/g, 'D')
|
||||||
|
: format;
|
||||||
export function DatePicker({
|
export function DatePicker({
|
||||||
type,
|
type,
|
||||||
value,
|
value,
|
||||||
@@ -386,6 +414,7 @@ export function DatePicker({
|
|||||||
inputReadOnly,
|
inputReadOnly,
|
||||||
dropdownClassName,
|
dropdownClassName,
|
||||||
dropdownStyle,
|
dropdownStyle,
|
||||||
|
format,
|
||||||
...props
|
...props
|
||||||
}) {
|
}) {
|
||||||
const range = type?.toLowerCase().includes('range');
|
const range = type?.toLowerCase().includes('range');
|
||||||
@@ -394,6 +423,7 @@ export function DatePicker({
|
|||||||
return (
|
return (
|
||||||
<Component
|
<Component
|
||||||
{...props}
|
{...props}
|
||||||
|
{...(format !== undefined ? { format: toDayjsFormat(format) } : {})}
|
||||||
classNames={{
|
classNames={{
|
||||||
...props.classNames,
|
...props.classNames,
|
||||||
popup: {
|
popup: {
|
||||||
@@ -422,17 +452,20 @@ export function DatePicker({
|
|||||||
value: convert(p.value || (p.start && [p.start, p.end])),
|
value: convert(p.value || (p.start && [p.start, p.end])),
|
||||||
}))}
|
}))}
|
||||||
onChange={(dates, strings) =>
|
onChange={(dates, strings) =>
|
||||||
onChange?.(dates ? (range ? strings : strings) : '', toDate(dates))
|
onChange?.(dates ? toDate(dates) : null, dates ? strings : '')
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function TimePicker({ value, onChange, ...props }) {
|
export function TimePicker({ value, onChange, format, ...props }) {
|
||||||
return (
|
return (
|
||||||
<AntTimePicker
|
<AntTimePicker
|
||||||
{...props}
|
{...props}
|
||||||
|
{...(format !== undefined ? { format: toDayjsFormat(format) } : {})}
|
||||||
value={toDay(value)}
|
value={toDay(value)}
|
||||||
onChange={(date, string) => onChange?.(string, date?.toDate())}
|
onChange={(date, string) =>
|
||||||
|
onChange?.(date ? date.toDate() : null, date ? string : '')
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+62
-14
@@ -82,8 +82,12 @@ export const Form = forwardRef(function Form(
|
|||||||
const FormComponent = consolePage ? ConsoleForm : AntForm;
|
const FormComponent = consolePage ? ConsoleForm : AntForm;
|
||||||
const [form] = AntForm.useForm();
|
const [form] = AntForm.useForm();
|
||||||
const [, renderValues] = useReducer((value) => value + 1, 0);
|
const [, renderValues] = useReducer((value) => value + 1, 0);
|
||||||
const callbacks = useRef({ getFormApi, onValueChange });
|
const callbacks = useRef({});
|
||||||
callbacks.current = { getFormApi, onValueChange };
|
callbacks.current = {
|
||||||
|
getFormApi,
|
||||||
|
onValueChange,
|
||||||
|
renderValues: typeof children === 'function' ? renderValues : () => {},
|
||||||
|
};
|
||||||
const api = useMemo(
|
const api = useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
getValues: () => form.getFieldsValue(true),
|
getValues: () => form.getFieldsValue(true),
|
||||||
@@ -94,17 +98,17 @@ export const Form = forwardRef(function Form(
|
|||||||
callbacks.current.onValueChange?.(form.getFieldsValue(true), {
|
callbacks.current.onValueChange?.(form.getFieldsValue(true), {
|
||||||
[field]: value,
|
[field]: value,
|
||||||
});
|
});
|
||||||
renderValues();
|
callbacks.current.renderValues();
|
||||||
},
|
},
|
||||||
setValues: (next) => {
|
setValues: (next) => {
|
||||||
form.setFieldsValue(next);
|
form.setFieldsValue(next);
|
||||||
callbacks.current.onValueChange?.(form.getFieldsValue(true), next);
|
callbacks.current.onValueChange?.(form.getFieldsValue(true), next);
|
||||||
renderValues();
|
callbacks.current.renderValues();
|
||||||
},
|
},
|
||||||
reset: (fields) => {
|
reset: (fields) => {
|
||||||
form.resetFields(fields?.map?.(fieldPath));
|
form.resetFields(fields?.map?.(fieldPath));
|
||||||
callbacks.current.onValueChange?.(form.getFieldsValue(true));
|
callbacks.current.onValueChange?.(form.getFieldsValue(true));
|
||||||
renderValues();
|
callbacks.current.renderValues();
|
||||||
},
|
},
|
||||||
validate: (fields) => form.validateFields(fields?.map?.(fieldPath)),
|
validate: (fields) => form.validateFields(fields?.map?.(fieldPath)),
|
||||||
submitForm: () => form.submit(),
|
submitForm: () => form.submit(),
|
||||||
@@ -122,10 +126,13 @@ export const Form = forwardRef(function Form(
|
|||||||
useImperativeHandle(ref, () => ({ formApi: api, ...api }), [api]);
|
useImperativeHandle(ref, () => ({ formApi: api, ...api }), [api]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
callbacks.current.getFormApi?.(api);
|
callbacks.current.getFormApi?.(api);
|
||||||
renderValues();
|
callbacks.current.renderValues();
|
||||||
}, [api]);
|
}, [api]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (values) form.setFieldsValue(values);
|
if (values) {
|
||||||
|
form.setFieldsValue(values);
|
||||||
|
callbacks.current.renderValues();
|
||||||
|
}
|
||||||
}, [form, values]);
|
}, [form, values]);
|
||||||
return (
|
return (
|
||||||
<FormContext.Provider value={form}>
|
<FormContext.Provider value={form}>
|
||||||
@@ -151,7 +158,13 @@ export const Form = forwardRef(function Form(
|
|||||||
wrapperCol={
|
wrapperCol={
|
||||||
props.wrapperCol ?? (labelWidth ? { flex: '1 1 0' } : undefined)
|
props.wrapperCol ?? (labelWidth ? { flex: '1 1 0' } : undefined)
|
||||||
}
|
}
|
||||||
labelAlign={labelAlign}
|
labelAlign={
|
||||||
|
labelAlign === 'left'
|
||||||
|
? 'start'
|
||||||
|
: labelAlign === 'right'
|
||||||
|
? 'end'
|
||||||
|
: labelAlign
|
||||||
|
}
|
||||||
onFinish={onSubmit}
|
onFinish={onSubmit}
|
||||||
onFinishFailed={
|
onFinishFailed={
|
||||||
consolePage && onSubmitFail
|
consolePage && onSubmitFail
|
||||||
@@ -168,7 +181,7 @@ export const Form = forwardRef(function Form(
|
|||||||
}
|
}
|
||||||
onValuesChange={(_, all) => {
|
onValuesChange={(_, all) => {
|
||||||
callbacks.current.onValueChange?.(all);
|
callbacks.current.onValueChange?.(all);
|
||||||
renderValues();
|
callbacks.current.renderValues();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{typeof children === 'function' ? (
|
{typeof children === 'function' ? (
|
||||||
@@ -198,15 +211,41 @@ function labelProps(label) {
|
|||||||
|
|
||||||
// Legacy Form.RadioGroup reports the selected value; standalone RadioGroup reports an event.
|
// Legacy Form.RadioGroup reports the selected value; standalone RadioGroup reports an event.
|
||||||
const FieldRadioGroup = forwardRef(function FieldRadioGroup(
|
const FieldRadioGroup = forwardRef(function FieldRadioGroup(
|
||||||
{ onChange, ...props },
|
{ onChange, id, options, children, ...props },
|
||||||
ref,
|
ref,
|
||||||
) {
|
) {
|
||||||
|
// A label must target a radio input, rather than the group's non-labelable div.
|
||||||
|
const optionIndex = options?.findIndex((option) => !option?.disabled);
|
||||||
|
let childLabeled = false;
|
||||||
return (
|
return (
|
||||||
<Controls.RadioGroup
|
<Controls.RadioGroup
|
||||||
{...props}
|
{...props}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
|
id={id ? `${id}-group` : undefined}
|
||||||
|
options={options?.map((option, index) =>
|
||||||
|
index === optionIndex && id
|
||||||
|
? {
|
||||||
|
...(typeof option === 'object'
|
||||||
|
? option
|
||||||
|
: { label: option, value: option }),
|
||||||
|
id,
|
||||||
|
}
|
||||||
|
: option,
|
||||||
|
)}
|
||||||
onChange={(event) => onChange?.(event.target.value, event)}
|
onChange={(event) => onChange?.(event.target.value, event)}
|
||||||
/>
|
>
|
||||||
|
{React.Children.map(children, (child) => {
|
||||||
|
if (
|
||||||
|
!id ||
|
||||||
|
childLabeled ||
|
||||||
|
!React.isValidElement(child) ||
|
||||||
|
child.props.disabled
|
||||||
|
)
|
||||||
|
return child;
|
||||||
|
childLabeled = true;
|
||||||
|
return React.cloneElement(child, { id });
|
||||||
|
})}
|
||||||
|
</Controls.RadioGroup>
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -284,6 +323,9 @@ export function withField(
|
|||||||
) : (
|
) : (
|
||||||
<Component
|
<Component
|
||||||
{...props}
|
{...props}
|
||||||
|
{...(Component === FieldRadioGroup && fieldLabel.label
|
||||||
|
? { 'aria-label': props['aria-label'] ?? fieldLabel.label }
|
||||||
|
: {})}
|
||||||
id={props.id ?? fieldLabel.htmlFor}
|
id={props.id ?? fieldLabel.htmlFor}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
style={style}
|
style={style}
|
||||||
@@ -370,13 +412,19 @@ Form.Slot = function Slot({ label, error, children, ...props }) {
|
|||||||
</AntForm.Item>
|
</AntForm.Item>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
Form.Section = function Section({ text, extraText, children, ...props }) {
|
Form.Section = function Section({
|
||||||
|
text,
|
||||||
|
extraText,
|
||||||
|
children,
|
||||||
|
component: Component = 'section',
|
||||||
|
...props
|
||||||
|
}) {
|
||||||
return (
|
return (
|
||||||
<section {...props}>
|
<Component {...props}>
|
||||||
<h3 className='ui-form-section'>{text}</h3>
|
<h3 className='ui-form-section'>{text}</h3>
|
||||||
{extraText && <p className='ui-field-help'>{extraText}</p>}
|
{extraText && <p className='ui-field-help'>{extraText}</p>}
|
||||||
{children}
|
{children}
|
||||||
</section>
|
</Component>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
Form.Label = function Label({ required, children, ...props }) {
|
Form.Label = function Label({ required, children, ...props }) {
|
||||||
|
|||||||
@@ -383,12 +383,14 @@ function CenterPaginatedTable({
|
|||||||
{...props}
|
{...props}
|
||||||
pagination={{
|
pagination={{
|
||||||
...centerPaginationOptions(config, isMobile),
|
...centerPaginationOptions(config, isMobile),
|
||||||
showSizeChanger: Boolean(
|
showSizeChanger:
|
||||||
local ||
|
config.showSizeChanger ??
|
||||||
config.onPageSizeChange ||
|
Boolean(
|
||||||
config.onShowSizeChange ||
|
local ||
|
||||||
config.onChange,
|
config.onPageSizeChange ||
|
||||||
),
|
config.onShowSizeChange ||
|
||||||
|
config.onChange,
|
||||||
|
),
|
||||||
current,
|
current,
|
||||||
pageSize,
|
pageSize,
|
||||||
onShowSizeChange: undefined,
|
onShowSizeChange: undefined,
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ export const getDefaultSidebarModulesAdmin = () => ({
|
|||||||
midjourney: true,
|
midjourney: true,
|
||||||
task: true,
|
task: true,
|
||||||
monitor: true,
|
monitor: true,
|
||||||
|
'smart-router': true,
|
||||||
},
|
},
|
||||||
personal: {
|
personal: {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
|
|||||||
+25
-9
@@ -17,8 +17,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|||||||
For commercial licensing, please contact support@quantumnous.com
|
For commercial licensing, please contact support@quantumnous.com
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import React, { useContext } from 'react';
|
import React, { useContext, useEffect, useRef } from 'react';
|
||||||
import { Navigate, useLocation } from 'react-router-dom';
|
import { Navigate, useLocation, useNavigate } from 'react-router-dom';
|
||||||
import { history } from './history';
|
import { history } from './history';
|
||||||
import { UserContext } from '../context/User';
|
import { UserContext } from '../context/User';
|
||||||
import { StatusContext } from '../context/Status';
|
import { StatusContext } from '../context/Status';
|
||||||
@@ -26,11 +26,11 @@ import { canAccessDelegatedAdminPage } from './adminDelegation';
|
|||||||
import { ADMIN_DELEGATION_OPTION_KEY } from '../constants/settingTabs';
|
import { ADMIN_DELEGATION_OPTION_KEY } from '../constants/settingTabs';
|
||||||
import Loading from '../components/common/ui/Loading';
|
import Loading from '../components/common/ui/Loading';
|
||||||
import {
|
import {
|
||||||
DEFAULT_LOGIN_REDIRECT,
|
|
||||||
getUserData,
|
getUserData,
|
||||||
isSafePostLoginRedirect,
|
isSafePostLoginRedirect,
|
||||||
savePostLoginRedirect,
|
savePostLoginRedirect,
|
||||||
} from './data';
|
} from './data';
|
||||||
|
import { authRedirectTarget } from './authRedirect';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 判断是否处于认证类页面(登录/注册/重置密码/企业登录/企业注册)。
|
* 判断是否处于认证类页面(登录/注册/重置密码/企业登录/企业注册)。
|
||||||
@@ -62,14 +62,30 @@ const getLoginTarget = (location) => {
|
|||||||
export const AuthRedirect = ({ children }) => {
|
export const AuthRedirect = ({ children }) => {
|
||||||
const [userState] = useContext(UserContext);
|
const [userState] = useContext(UserContext);
|
||||||
const cachedUser = getUserData();
|
const cachedUser = getUserData();
|
||||||
|
const location = useLocation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const initiallyAuthenticated = useRef(Boolean(userState?.user || cachedUser));
|
||||||
|
|
||||||
|
// LoginForm publishes the user before it navigates to the saved deep link.
|
||||||
|
// Schedule the default guard redirect in an effect so the explicit deep
|
||||||
|
// link navigation wins the same login transition.
|
||||||
|
useEffect(() => {
|
||||||
|
if (
|
||||||
|
!initiallyAuthenticated.current ||
|
||||||
|
!userState?.user ||
|
||||||
|
location.pathname !== '/login'
|
||||||
|
)
|
||||||
|
return;
|
||||||
|
const target = authRedirectTarget({
|
||||||
|
authenticated: true,
|
||||||
|
redirectReady: true,
|
||||||
|
orgOnly: userState.user.org_only_mode === true,
|
||||||
|
});
|
||||||
|
if (target) navigate(target, { replace: true });
|
||||||
|
}, [location.pathname, navigate, userState?.user]);
|
||||||
|
|
||||||
if (userState?.user) {
|
if (userState?.user) {
|
||||||
// org_only(仅企业资源)员工登录后直接进入企业空间
|
return children;
|
||||||
if (userState.user.org_only_mode === true) {
|
|
||||||
return <Navigate to='/org' replace />;
|
|
||||||
}
|
|
||||||
// 已登录用户统一跳转到默认登录落地页,而不是控制台(控制台需要管理员权限)
|
|
||||||
return <Navigate to={DEFAULT_LOGIN_REDIRECT} replace />;
|
|
||||||
}
|
}
|
||||||
if (!userState?.authChecked && cachedUser) {
|
if (!userState?.authChecked && cachedUser) {
|
||||||
return <Loading />;
|
return <Loading />;
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
/*
|
||||||
|
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 { DEFAULT_LOGIN_REDIRECT } from './data.js';
|
||||||
|
|
||||||
|
export function authRedirectTarget({
|
||||||
|
authenticated,
|
||||||
|
redirectReady,
|
||||||
|
orgOnly = false,
|
||||||
|
}) {
|
||||||
|
if (!authenticated || !redirectReady) return null;
|
||||||
|
return orgOnly ? '/org' : DEFAULT_LOGIN_REDIRECT;
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
/*
|
||||||
|
Copyright (C) 2025 QuantumNous
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as
|
||||||
|
published by the Free Software Foundation, either version 3 of the
|
||||||
|
License, or (at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
For commercial licensing, please contact support@quantumnous.com
|
||||||
|
*/
|
||||||
|
|
||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
|
||||||
|
import { authRedirectTarget } from './authRedirect.js';
|
||||||
|
|
||||||
|
test('认证状态刚切换时等待回跳目标完成,避免覆盖深链', () => {
|
||||||
|
assert.equal(
|
||||||
|
authRedirectTarget({ authenticated: true, redirectReady: false }),
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
authRedirectTarget({ authenticated: true, redirectReady: true }),
|
||||||
|
// ui 基线:密钥管理迁至 /user-center/key-management(旧路径重定向)
|
||||||
|
'/user-center/key-management',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('仅企业账号稳定登录后仍进入企业空间', () => {
|
||||||
|
assert.equal(
|
||||||
|
authRedirectTarget({
|
||||||
|
authenticated: true,
|
||||||
|
redirectReady: true,
|
||||||
|
orgOnly: true,
|
||||||
|
}),
|
||||||
|
'/org',
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -123,6 +123,12 @@ export function setUserData(data) {
|
|||||||
export function clearUserData() {
|
export function clearUserData() {
|
||||||
localStorage.removeItem(USER_STORAGE_KEY);
|
localStorage.removeItem(USER_STORAGE_KEY);
|
||||||
localStorage.removeItem('current_org_id');
|
localStorage.removeItem('current_org_id');
|
||||||
|
// 智能路由侧边栏的个人授权缓存属于当前用户:同一标签页换账号登录时不能沿用
|
||||||
|
try {
|
||||||
|
sessionStorage.removeItem('smart_router_personal_consent_granted');
|
||||||
|
} catch {
|
||||||
|
// sessionStorage 不可用时无需清理
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isSafePostLoginRedirect(path) {
|
export function isSafePostLoginRedirect(path) {
|
||||||
|
|||||||
@@ -77,8 +77,10 @@ import {
|
|||||||
Package,
|
Package,
|
||||||
Activity,
|
Activity,
|
||||||
PieChart,
|
PieChart,
|
||||||
|
HandCoins,
|
||||||
Building2,
|
Building2,
|
||||||
Handshake,
|
Handshake,
|
||||||
|
Route,
|
||||||
Globe,
|
Globe,
|
||||||
CalendarDays,
|
CalendarDays,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
@@ -125,8 +127,12 @@ export function getLucideIcon(key, selected = false) {
|
|||||||
return <Package {...commonProps} color={iconColor} />;
|
return <Package {...commonProps} color={iconColor} />;
|
||||||
case 'monitor':
|
case 'monitor':
|
||||||
return <Activity {...commonProps} color={iconColor} />;
|
return <Activity {...commonProps} color={iconColor} />;
|
||||||
|
case 'commission':
|
||||||
|
return <HandCoins {...commonProps} color={iconColor} />;
|
||||||
case 'analytics':
|
case 'analytics':
|
||||||
return <PieChart {...commonProps} color={iconColor} />;
|
return <PieChart {...commonProps} color={iconColor} />;
|
||||||
|
case 'smart-router':
|
||||||
|
return <Route {...commonProps} color={iconColor} />;
|
||||||
case 'organizations':
|
case 'organizations':
|
||||||
return <Building2 {...commonProps} color={iconColor} />;
|
return <Building2 {...commonProps} color={iconColor} />;
|
||||||
case 'partner':
|
case 'partner':
|
||||||
@@ -985,6 +991,8 @@ function renderPriceSimpleCore({
|
|||||||
cacheCreationRatio5m = 1.0,
|
cacheCreationRatio5m = 1.0,
|
||||||
cacheCreationTokens1h = 0,
|
cacheCreationTokens1h = 0,
|
||||||
cacheCreationRatio1h = 1.0,
|
cacheCreationRatio1h = 1.0,
|
||||||
|
cacheCreationTokensUnlabeled = 0,
|
||||||
|
cacheCreationRatioUnlabeled = 1.0,
|
||||||
image = false,
|
image = false,
|
||||||
imageRatio = 1.0,
|
imageRatio = 1.0,
|
||||||
isSystemPromptOverride = false,
|
isSystemPromptOverride = false,
|
||||||
@@ -1016,6 +1024,10 @@ function renderPriceSimpleCore({
|
|||||||
hasSplitCacheCreation && cacheCreationTokens5m > 0;
|
hasSplitCacheCreation && cacheCreationTokens5m > 0;
|
||||||
const shouldShowCacheCreation1h =
|
const shouldShowCacheCreation1h =
|
||||||
hasSplitCacheCreation && cacheCreationTokens1h > 0;
|
hasSplitCacheCreation && cacheCreationTokens1h > 0;
|
||||||
|
// 上游给了总量却没给分档的那部分按「默认档位」计价,倍率可能既不等于 5m 也不等于 1h。
|
||||||
|
// 与分档并存时它是独立的一项,漏掉这一项用户就对不出总价。
|
||||||
|
const shouldShowCacheCreationUnlabeled =
|
||||||
|
hasSplitCacheCreation && cacheCreationTokensUnlabeled > 0;
|
||||||
|
|
||||||
const parts = [];
|
const parts = [];
|
||||||
// base: model ratio
|
// base: model ratio
|
||||||
@@ -1047,6 +1059,13 @@ function renderPriceSimpleCore({
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if (shouldShowCacheCreationUnlabeled) {
|
||||||
|
parts.push(
|
||||||
|
i18next.t('未分档缓存创建: {{cacheCreationRatioUnlabeled}}', {
|
||||||
|
cacheCreationRatioUnlabeled,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
} else if (shouldShowLegacyCacheCreation) {
|
} else if (shouldShowLegacyCacheCreation) {
|
||||||
parts.push(
|
parts.push(
|
||||||
i18next.t('缓存创建: {{cacheCreationRatio}}', { cacheCreationRatio }),
|
i18next.t('缓存创建: {{cacheCreationRatio}}', { cacheCreationRatio }),
|
||||||
@@ -1451,6 +1470,8 @@ export function renderModelPriceSimple(
|
|||||||
cacheCreationRatio5m = 1.0,
|
cacheCreationRatio5m = 1.0,
|
||||||
cacheCreationTokens1h = 0,
|
cacheCreationTokens1h = 0,
|
||||||
cacheCreationRatio1h = 1.0,
|
cacheCreationRatio1h = 1.0,
|
||||||
|
cacheCreationTokensUnlabeled = 0,
|
||||||
|
cacheCreationRatioUnlabeled = 1.0,
|
||||||
image = false,
|
image = false,
|
||||||
imageRatio = 1.0,
|
imageRatio = 1.0,
|
||||||
isSystemPromptOverride = false,
|
isSystemPromptOverride = false,
|
||||||
@@ -1469,6 +1490,8 @@ export function renderModelPriceSimple(
|
|||||||
cacheCreationRatio5m,
|
cacheCreationRatio5m,
|
||||||
cacheCreationTokens1h,
|
cacheCreationTokens1h,
|
||||||
cacheCreationRatio1h,
|
cacheCreationRatio1h,
|
||||||
|
cacheCreationTokensUnlabeled,
|
||||||
|
cacheCreationRatioUnlabeled,
|
||||||
image,
|
image,
|
||||||
imageRatio,
|
imageRatio,
|
||||||
isSystemPromptOverride,
|
isSystemPromptOverride,
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
/*
|
||||||
|
Copyright (C) 2025 QuantumNous
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as
|
||||||
|
published by the Free Software Foundation, either version 3 of the
|
||||||
|
License, or (at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
For commercial licensing, please contact support@quantumnous.com
|
||||||
|
*/
|
||||||
|
|
||||||
|
export function revealActiveSidebarItem(container) {
|
||||||
|
if (!container || container.scrollHeight <= container.clientHeight) return;
|
||||||
|
const active = container.querySelector('[aria-current="page"]');
|
||||||
|
if (!active || !active.getClientRects().length) return;
|
||||||
|
const viewport = container.getBoundingClientRect();
|
||||||
|
const item = active.getBoundingClientRect();
|
||||||
|
const top = viewport.top + container.clientTop;
|
||||||
|
const bottom = top + container.clientHeight;
|
||||||
|
// 只移动菜单自身的滚动区,避免 scrollIntoView 连带滚动正文或页面外壳。
|
||||||
|
const offset =
|
||||||
|
item.top < top
|
||||||
|
? item.top - top
|
||||||
|
: item.bottom > bottom
|
||||||
|
? item.bottom - bottom
|
||||||
|
: 0;
|
||||||
|
if (offset) container.scrollTop += offset;
|
||||||
|
}
|
||||||
@@ -35,7 +35,6 @@ export const useAnalyticsData = (active = true) => {
|
|||||||
const [financeTrend, setFinanceTrend] = useState([]);
|
const [financeTrend, setFinanceTrend] = useState([]);
|
||||||
const [channelConsumption, setChannelConsumption] = useState([]);
|
const [channelConsumption, setChannelConsumption] = useState([]);
|
||||||
const [userRanking, setUserRanking] = useState([]);
|
const [userRanking, setUserRanking] = useState([]);
|
||||||
const [topupChannel, setTopupChannel] = useState([]);
|
|
||||||
const [dailyStats, setDailyStats] = useState([]);
|
const [dailyStats, setDailyStats] = useState([]);
|
||||||
const [userTopupRanking, setUserTopupRanking] = useState([]);
|
const [userTopupRanking, setUserTopupRanking] = useState([]);
|
||||||
const [period, setPeriod] = useState('today'); // today, week, month, quarter, custom
|
const [period, setPeriod] = useState('today'); // today, week, month, quarter, custom
|
||||||
@@ -173,23 +172,8 @@ export const useAnalyticsData = (active = true) => {
|
|||||||
[buildQueryParams],
|
[buildQueryParams],
|
||||||
);
|
);
|
||||||
|
|
||||||
// 获取充值渠道分布
|
// 充值渠道分布面板已于 2026-11 从运营看板撤下(位置让给「企业用量分析」)。
|
||||||
const fetchTopupChannel = useCallback(
|
// 组件 TopupChannelChart 与后端 /api/analytics/topup-channel 都保留,这里只是不再拉取。
|
||||||
async (currentPeriod, currentDateRange) => {
|
|
||||||
try {
|
|
||||||
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
|
|
||||||
const res = await API.get(
|
|
||||||
`/api/analytics/topup-channel?${queryParams}`,
|
|
||||||
);
|
|
||||||
if (res.data.success) {
|
|
||||||
setTopupChannel(res.data.data || []);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('获取充值渠道分布失败:', error);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[buildQueryParams],
|
|
||||||
);
|
|
||||||
|
|
||||||
// 获取每日统计
|
// 获取每日统计
|
||||||
const fetchDailyStats = useCallback(
|
const fetchDailyStats = useCallback(
|
||||||
@@ -229,7 +213,7 @@ export const useAnalyticsData = (active = true) => {
|
|||||||
// 刷新所有数据。
|
// 刷新所有数据。
|
||||||
// 概览不参与全页 loading:它只影响顶部 6 张卡片(卡片自己有骨架屏),
|
// 概览不参与全页 loading:它只影响顶部 6 张卡片(卡片自己有骨架屏),
|
||||||
// 却是耗时最长的一个请求,纳入遮罩会让下面的图表白白陪等。
|
// 却是耗时最长的一个请求,纳入遮罩会让下面的图表白白陪等。
|
||||||
// 返回的 Promise 仍然等齐全部 8 个请求,刷新按钮据此显示完整进度。
|
// 返回的 Promise 仍然等齐全部 7 个请求,刷新按钮据此显示完整进度。
|
||||||
const refreshAll = useCallback(
|
const refreshAll = useCallback(
|
||||||
async (currentPeriod, currentDateRange, force = false) => {
|
async (currentPeriod, currentDateRange, force = false) => {
|
||||||
const overviewTask = fetchOverview(force);
|
const overviewTask = fetchOverview(force);
|
||||||
@@ -240,7 +224,6 @@ export const useAnalyticsData = (active = true) => {
|
|||||||
fetchFinanceTrend(currentPeriod, currentDateRange),
|
fetchFinanceTrend(currentPeriod, currentDateRange),
|
||||||
fetchChannelConsumption(currentPeriod, currentDateRange),
|
fetchChannelConsumption(currentPeriod, currentDateRange),
|
||||||
fetchUserRanking(currentPeriod, currentDateRange),
|
fetchUserRanking(currentPeriod, currentDateRange),
|
||||||
fetchTopupChannel(currentPeriod, currentDateRange),
|
|
||||||
fetchDailyStats(currentPeriod, currentDateRange),
|
fetchDailyStats(currentPeriod, currentDateRange),
|
||||||
fetchUserTopupRanking(currentPeriod, currentDateRange),
|
fetchUserTopupRanking(currentPeriod, currentDateRange),
|
||||||
]);
|
]);
|
||||||
@@ -255,7 +238,6 @@ export const useAnalyticsData = (active = true) => {
|
|||||||
fetchFinanceTrend,
|
fetchFinanceTrend,
|
||||||
fetchChannelConsumption,
|
fetchChannelConsumption,
|
||||||
fetchUserRanking,
|
fetchUserRanking,
|
||||||
fetchTopupChannel,
|
|
||||||
fetchDailyStats,
|
fetchDailyStats,
|
||||||
fetchUserTopupRanking,
|
fetchUserTopupRanking,
|
||||||
],
|
],
|
||||||
@@ -303,7 +285,6 @@ export const useAnalyticsData = (active = true) => {
|
|||||||
financeTrend,
|
financeTrend,
|
||||||
channelConsumption,
|
channelConsumption,
|
||||||
userRanking,
|
userRanking,
|
||||||
topupChannel,
|
|
||||||
dailyStats,
|
dailyStats,
|
||||||
userTopupRanking,
|
userTopupRanking,
|
||||||
period,
|
period,
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
/*
|
||||||
|
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 { useState, useCallback, useEffect, useRef } from 'react';
|
||||||
|
import { API } from '../../helpers';
|
||||||
|
|
||||||
|
// 可选窗口。默认 24h;7d 用于看跨天的周期性(工作日/夜间的命中率差异)。
|
||||||
|
export const ORG_CACHE_WINDOWS = [
|
||||||
|
{ key: '24h', hours: 24 },
|
||||||
|
{ key: '7d', hours: 24 * 7 },
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单企业逐小时缓存报表 Hook(看板点击某行后的抽屉)。
|
||||||
|
*
|
||||||
|
* 与 useOrgRealtimeUsage 不同,这里**不轮询**:抽屉是用户主动点开看的,
|
||||||
|
* 数据又是按小时聚合的,轮询除了重复打同一份 60 秒服务端缓存没有任何收益。
|
||||||
|
* orgId 为空(抽屉关着)时一个请求都不发。
|
||||||
|
*/
|
||||||
|
export const useOrgCacheHourly = (orgId, hours = 24) => {
|
||||||
|
const [data, setData] = useState(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState(null);
|
||||||
|
|
||||||
|
const mountedRef = useRef(true);
|
||||||
|
// 请求序号:切窗口(24h↔7d)时两个请求会同时在飞,7d 慢一点就会后到并覆盖 24h 的结果。
|
||||||
|
// 只认最后一次发出的请求,丢弃过期响应。
|
||||||
|
const seqRef = useRef(0);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
mountedRef.current = true;
|
||||||
|
return () => {
|
||||||
|
mountedRef.current = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const fetchOnce = useCallback(
|
||||||
|
async (refresh = false) => {
|
||||||
|
if (!orgId) return;
|
||||||
|
const seq = ++seqRef.current;
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const res = await API.get(
|
||||||
|
`/api/analytics/org-cache-hourly?org_id=${orgId}&hours=${hours}${
|
||||||
|
refresh ? '&refresh=true' : ''
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
if (!mountedRef.current || seq !== seqRef.current) return;
|
||||||
|
if (res.data.success) {
|
||||||
|
setData(res.data.data || null);
|
||||||
|
} else {
|
||||||
|
setError(res.data.message || '');
|
||||||
|
setData(null);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (!mountedRef.current || seq !== seqRef.current) return;
|
||||||
|
setError(e?.message || '');
|
||||||
|
setData(null);
|
||||||
|
} finally {
|
||||||
|
if (mountedRef.current && seq === seqRef.current) setLoading(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[orgId, hours],
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!orgId) {
|
||||||
|
// 关抽屉时清掉旧数据:否则下次点开别的企业会先闪一帧上一家的曲线。
|
||||||
|
seqRef.current++;
|
||||||
|
setData(null);
|
||||||
|
setError(null);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fetchOnce(false);
|
||||||
|
}, [orgId, hours, fetchOnce]);
|
||||||
|
|
||||||
|
return { data, loading, error, refresh: () => fetchOnce(true) };
|
||||||
|
};
|
||||||
|
|
||||||
|
export default useOrgCacheHourly;
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
/*
|
||||||
|
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 { useState, useCallback, useEffect, useRef } from 'react';
|
||||||
|
import { API } from '../../helpers';
|
||||||
|
|
||||||
|
// 轮询间隔与服务端缓存 TTL 对齐(后端 orgRealtimeCacheTTL = 3s)。
|
||||||
|
// 调小没有意义:多出来的请求只会读到同一份缓存。
|
||||||
|
const POLL_INTERVAL_MS = 3000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 企业实时用量(并发 / RPM / TPM)轮询 Hook。
|
||||||
|
*
|
||||||
|
* 参数 active:是否激活。false 时停表且不发任何请求(用于 Tab 懒加载)。
|
||||||
|
*
|
||||||
|
* 三道闸门避免无谓请求堆积:
|
||||||
|
* 1. active 为 false —— 用户不在运营看板 Tab;
|
||||||
|
* 2. 页面不可见(切到别的标签页 / 最小化)—— 没人看的数据不必拉;
|
||||||
|
* 3. 上一轮还在飞 —— 后端慢时不叠加请求,否则会越积越多。
|
||||||
|
*/
|
||||||
|
export const useOrgRealtimeUsage = (active = true, { limit = 10 } = {}) => {
|
||||||
|
const [data, setData] = useState(null);
|
||||||
|
// 仅首次加载显示骨架;后续 3 秒一次的刷新静默进行,否则表格会一直闪。
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [sortBy, setSortBy] = useState('tpm');
|
||||||
|
|
||||||
|
const inFlightRef = useRef(false);
|
||||||
|
const mountedRef = useRef(true);
|
||||||
|
const loadedRef = useRef(false);
|
||||||
|
// 用 ref 读排序维度:轮询定时器只建一次,不应因为换排序就重建。
|
||||||
|
const sortByRef = useRef(sortBy);
|
||||||
|
sortByRef.current = sortBy;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
mountedRef.current = true;
|
||||||
|
return () => {
|
||||||
|
mountedRef.current = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const fetchOnce = useCallback(
|
||||||
|
async (silent = true) => {
|
||||||
|
if (inFlightRef.current) return;
|
||||||
|
inFlightRef.current = true;
|
||||||
|
if (!silent) setLoading(true);
|
||||||
|
try {
|
||||||
|
const res = await API.get(
|
||||||
|
`/api/analytics/org-realtime?limit=${limit}&sort_by=${sortByRef.current}`,
|
||||||
|
);
|
||||||
|
if (!mountedRef.current) return;
|
||||||
|
if (res.data.success) {
|
||||||
|
setData(res.data.data || null);
|
||||||
|
loadedRef.current = true;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// 轮询接口不弹 toast:3 秒一次的报错提示会把页面淹掉。
|
||||||
|
console.error('获取企业实时用量失败:', error);
|
||||||
|
} finally {
|
||||||
|
inFlightRef.current = false;
|
||||||
|
if (!silent && mountedRef.current) setLoading(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[limit],
|
||||||
|
);
|
||||||
|
|
||||||
|
// 切换排序维度立即重拉一次,不等下一个轮询周期。
|
||||||
|
const changeSortBy = useCallback(
|
||||||
|
(next) => {
|
||||||
|
if (!next || next === sortByRef.current) return;
|
||||||
|
sortByRef.current = next;
|
||||||
|
setSortBy(next);
|
||||||
|
fetchOnce(true);
|
||||||
|
},
|
||||||
|
[fetchOnce],
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active) return undefined;
|
||||||
|
|
||||||
|
// 首次进入显示骨架,之后(切走再切回)静默刷新。
|
||||||
|
fetchOnce(!loadedRef.current ? false : true);
|
||||||
|
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
if (
|
||||||
|
typeof document !== 'undefined' &&
|
||||||
|
document.visibilityState !== 'visible'
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fetchOnce(true);
|
||||||
|
}, POLL_INTERVAL_MS);
|
||||||
|
|
||||||
|
// 从后台切回前台时立刻补一次,避免盯着一屏最多 3 秒前的旧数据。
|
||||||
|
const onVisibilityChange = () => {
|
||||||
|
if (document.visibilityState === 'visible') fetchOnce(true);
|
||||||
|
};
|
||||||
|
document.addEventListener('visibilitychange', onVisibilityChange);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
clearInterval(timer);
|
||||||
|
document.removeEventListener('visibilitychange', onVisibilityChange);
|
||||||
|
};
|
||||||
|
}, [active, fetchOnce]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
loading,
|
||||||
|
sortBy,
|
||||||
|
setSortBy: changeSortBy,
|
||||||
|
refresh: () => fetchOnce(true),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export default useOrgRealtimeUsage;
|
||||||
@@ -35,7 +35,11 @@ export const useNavigation = (
|
|||||||
orgEntry = {},
|
orgEntry = {},
|
||||||
) => {
|
) => {
|
||||||
// 解构成基础类型,避免父组件每次渲染传入新对象字面量导致 useMemo 失效
|
// 解构成基础类型,避免父组件每次渲染传入新对象字面量导致 useMemo 失效
|
||||||
const { showOrgEntry = false, orgEntryPath = '/org' } = orgEntry;
|
const {
|
||||||
|
showOrgEntry = false,
|
||||||
|
orgEntryPath = '/org',
|
||||||
|
showPartnerEntry = false,
|
||||||
|
} = orgEntry;
|
||||||
// WeyAi 网页端入口:按 /api/status 开关与 /api/client/v1/web/access 决定是否显示
|
// WeyAi 网页端入口:按 /api/status 开关与 /api/client/v1/web/access 决定是否显示
|
||||||
const { visible: weyaiVisible, url: weyaiUrl } = useWeyAiWebEntry();
|
const { visible: weyaiVisible, url: weyaiUrl } = useWeyAiWebEntry();
|
||||||
const mainNavLinks = useMemo(() => {
|
const mainNavLinks = useMemo(() => {
|
||||||
@@ -106,6 +110,19 @@ export const useNavigation = (
|
|||||||
};
|
};
|
||||||
|
|
||||||
const allLinks = [
|
const allLinks = [
|
||||||
|
// 平台开放且具备新版伙伴权限时展示;放在前面,窄屏也容易找到。
|
||||||
|
...(showPartnerEntry
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
text: t('伙伴工作台'),
|
||||||
|
itemKey: 'partnerWorkspace',
|
||||||
|
mobileText: t('导航'),
|
||||||
|
to: '/console/my-commission',
|
||||||
|
requireAuth: true,
|
||||||
|
alwaysShow: true,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
{
|
{
|
||||||
text: t('密钥管理'),
|
text: t('密钥管理'),
|
||||||
itemKey: 'keyManagement',
|
itemKey: 'keyManagement',
|
||||||
@@ -137,27 +154,6 @@ export const useNavigation = (
|
|||||||
to: '/user-center',
|
to: '/user-center',
|
||||||
requireAuth: getHeaderModuleRequireAuth(modules, 'userCenter'),
|
requireAuth: getHeaderModuleRequireAuth(modules, 'userCenter'),
|
||||||
},
|
},
|
||||||
{
|
|
||||||
text: t('控制台'),
|
|
||||||
itemKey: 'console',
|
|
||||||
to: '/console/analytics',
|
|
||||||
activePrefix: '/console',
|
|
||||||
adminOnly: true,
|
|
||||||
requireAuth: true,
|
|
||||||
},
|
|
||||||
// WeyAi 网页端:外链到网关的 /sso/start(每次点击都重新走一遍免登录授权),
|
|
||||||
// 需要登录;管理员可在「顶栏管理」里关闭
|
|
||||||
...(weyaiVisible
|
|
||||||
? [
|
|
||||||
{
|
|
||||||
text: t('WeyAi'),
|
|
||||||
itemKey: 'weyai',
|
|
||||||
isExternal: true,
|
|
||||||
externalLink: weyaiUrl,
|
|
||||||
requireAuth: true,
|
|
||||||
},
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
// 企业中心:仅当用户属于某个企业时作为一级入口展示(不跟随 headerNavModules 配置,
|
// 企业中心:仅当用户属于某个企业时作为一级入口展示(不跟随 headerNavModules 配置,
|
||||||
// 由 showOrgEntry 统一控制可见性,故标记 alwaysShow 跳过模块开关过滤)
|
// 由 showOrgEntry 统一控制可见性,故标记 alwaysShow 跳过模块开关过滤)
|
||||||
...(showOrgEntry
|
...(showOrgEntry
|
||||||
@@ -172,6 +168,27 @@ export const useNavigation = (
|
|||||||
},
|
},
|
||||||
]
|
]
|
||||||
: []),
|
: []),
|
||||||
|
// WeyAi 网页端:外链到网关的 /sso/start(每次点击都重新走一遍免登录授权),
|
||||||
|
// 需要登录;管理员可在「顶栏管理」里关闭
|
||||||
|
...(weyaiVisible
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
text: t('WeyAi'),
|
||||||
|
itemKey: 'weyai',
|
||||||
|
isExternal: true,
|
||||||
|
externalLink: weyaiUrl,
|
||||||
|
requireAuth: true,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
{
|
||||||
|
text: t('控制台'),
|
||||||
|
itemKey: 'console',
|
||||||
|
to: '/console/analytics',
|
||||||
|
activePrefix: '/console',
|
||||||
|
adminOnly: true,
|
||||||
|
requireAuth: true,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
return allLinks.filter((link) => {
|
return allLinks.filter((link) => {
|
||||||
@@ -191,6 +208,7 @@ export const useNavigation = (
|
|||||||
userGroup,
|
userGroup,
|
||||||
showOrgEntry,
|
showOrgEntry,
|
||||||
orgEntryPath,
|
orgEntryPath,
|
||||||
|
showPartnerEntry,
|
||||||
weyaiVisible,
|
weyaiVisible,
|
||||||
weyaiUrl,
|
weyaiUrl,
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
/*
|
||||||
|
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, useMemo, useState } from 'react';
|
||||||
|
import { API } from '../../helpers/api';
|
||||||
|
import { UserContext } from '../../context/User';
|
||||||
|
import { StatusContext } from '../../context/Status';
|
||||||
|
import { resolvePartnerWorkspaceIdentity } from '../../pages/PartnerPortal/redirect';
|
||||||
|
import { partnerScope } from '../../pages/CommissionV2/partnerScope';
|
||||||
|
|
||||||
|
// 顶栏入口与工作台使用同一套服务端鉴权,不根据平台角色或旧版伙伴记录推断。
|
||||||
|
export function usePartnerWorkspaceAccess(organizationId = null) {
|
||||||
|
const [userState] = useContext(UserContext);
|
||||||
|
const [statusState] = useContext(StatusContext);
|
||||||
|
const user = userState?.user;
|
||||||
|
const scope = useMemo(
|
||||||
|
() => partnerScope(user?.id, organizationId),
|
||||||
|
[user?.id, organizationId],
|
||||||
|
);
|
||||||
|
const portalEnabled = statusState?.status?.commission_partner_portal_enabled;
|
||||||
|
// 分佣总开关关闭时不发起伙伴身份探测;旧后端不返回该字段,视为开启。
|
||||||
|
const commissionEnabled = statusState?.status?.commission_enabled !== false;
|
||||||
|
const enabled =
|
||||||
|
commissionEnabled &&
|
||||||
|
(portalEnabled === true || portalEnabled === 'true') &&
|
||||||
|
scope.valid &&
|
||||||
|
!userState?.authChecking;
|
||||||
|
const [access, setAccess] = useState(null);
|
||||||
|
const [attempt, setAttempt] = useState(0);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
setAccess(null);
|
||||||
|
if (!enabled) return undefined;
|
||||||
|
|
||||||
|
resolvePartnerWorkspaceIdentity((url, config) =>
|
||||||
|
API.get(scope.url(url), {
|
||||||
|
...config,
|
||||||
|
headers: scope.headers,
|
||||||
|
}),
|
||||||
|
).then(({ status, partnerType }) => {
|
||||||
|
if (!cancelled)
|
||||||
|
setAccess({ user, status, partnerType, attempt, scopeKey: scope.key });
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [enabled, user, attempt, scope]);
|
||||||
|
|
||||||
|
// 绑定本次登录的用户快照,切换账号时在 effect 执行前就隐藏旧入口。
|
||||||
|
let status = 'loading';
|
||||||
|
let partnerType = '';
|
||||||
|
if (statusState?.status !== undefined && !userState?.authChecking) {
|
||||||
|
if (!enabled) status = 'denied';
|
||||||
|
else if (
|
||||||
|
access?.user === user &&
|
||||||
|
access?.attempt === attempt &&
|
||||||
|
access?.scopeKey === scope.key
|
||||||
|
) {
|
||||||
|
status = access.status;
|
||||||
|
partnerType = access.partnerType || '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
status,
|
||||||
|
partnerType,
|
||||||
|
retry: () => setAttempt((value) => value + 1),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 顶栏「伙伴工作台」与控制台侧栏「我的提成」只给个人伙伴:
|
||||||
|
// 企业伙伴(含企业登录与管理企业的个人会话)统一从企业中心「企业分佣」进入,避免两处入口。
|
||||||
|
export function usePartnerWorkspaceEntry() {
|
||||||
|
const { status, partnerType } = usePartnerWorkspaceAccess();
|
||||||
|
return status === 'allowed' && partnerType === 'individual';
|
||||||
|
}
|
||||||
@@ -63,6 +63,12 @@ export const useImageTaskManagement = () => {
|
|||||||
// 上次轮询到的状态签名(status|progress),无变化时逐步退避
|
// 上次轮询到的状态签名(status|progress),无变化时逐步退避
|
||||||
const lastSeenRef = useRef(new Map());
|
const lastSeenRef = useRef(new Map());
|
||||||
|
|
||||||
|
// 图片链接刷新:同一任务同一类型的请求进行中时复用(图片 onError 与批量刷新会同时触发);
|
||||||
|
// refreshedUrlKeysRef 记录本次挂载已刷新过的链接,批量刷新跳过它们
|
||||||
|
const urlRefreshInFlightRef = useRef(new Map());
|
||||||
|
const refreshedUrlKeysRef = useRef(new Set());
|
||||||
|
const urlRefreshTimerRef = useRef(null);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 将后端任务数据转换为前端格式
|
* 将后端任务数据转换为前端格式
|
||||||
*/
|
*/
|
||||||
@@ -339,6 +345,47 @@ export const useImageTaskManagement = () => {
|
|||||||
);
|
);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// 调用 refresh-url 并写回任务;返回新 URL(失败返回 null,请求异常向上抛出)。
|
||||||
|
// 不走全局错误提示:后台刷新静默,手动刷新由调用方给出提示。
|
||||||
|
const requestTaskUrlRefresh = useCallback(
|
||||||
|
(taskId, type, urlToRefresh) => {
|
||||||
|
const key = `${taskId}|${type}`;
|
||||||
|
const inFlight = urlRefreshInFlightRef.current.get(key);
|
||||||
|
if (inFlight) return inFlight;
|
||||||
|
|
||||||
|
const params = { task_id: taskId, type };
|
||||||
|
// 有有效 COS URL(不是 base64)时传给后端刷新;为空或 base64 时不传,后端从数据库读取 base64 并上传
|
||||||
|
if (urlToRefresh && !urlToRefresh.startsWith('data:')) {
|
||||||
|
params.url = urlToRefresh;
|
||||||
|
}
|
||||||
|
const request = API.get('/api/images/refresh-url', {
|
||||||
|
params,
|
||||||
|
skipErrorHandler: true,
|
||||||
|
})
|
||||||
|
.then((response) => {
|
||||||
|
const newUrl = response.data?.success ? response.data?.data?.url : '';
|
||||||
|
if (!newUrl) return null;
|
||||||
|
refreshedUrlKeysRef.current.add(key);
|
||||||
|
if (mountedRef.current) {
|
||||||
|
// 根据类型更新对应的URL,并清除base64数据(因为已上传到COS)
|
||||||
|
updateTask(
|
||||||
|
taskId,
|
||||||
|
type === 'source'
|
||||||
|
? { sourceImageUrl: newUrl, sourceImageBase64: null }
|
||||||
|
: { imageUrl: newUrl, imageBase64: null },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return newUrl;
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
urlRefreshInFlightRef.current.delete(key);
|
||||||
|
});
|
||||||
|
urlRefreshInFlightRef.current.set(key, request);
|
||||||
|
return request;
|
||||||
|
},
|
||||||
|
[updateTask],
|
||||||
|
);
|
||||||
|
|
||||||
// 刷新任务图片URL
|
// 刷新任务图片URL
|
||||||
// type: 'generated'(生成图,默认)或 'source'(原图,图生图模式)
|
// type: 'generated'(生成图,默认)或 'source'(原图,图生图模式)
|
||||||
// 支持两种场景:
|
// 支持两种场景:
|
||||||
@@ -358,45 +405,14 @@ export const useImageTaskManagement = () => {
|
|||||||
const urlToRefresh =
|
const urlToRefresh =
|
||||||
type === 'source' ? task.sourceImageUrl : task.imageUrl;
|
type === 'source' ? task.sourceImageUrl : task.imageUrl;
|
||||||
|
|
||||||
// 如果URL是base64格式(data: 开头),说明前端保存了base64但还没上传到COS
|
|
||||||
// 这种情况需要上传到COS
|
|
||||||
const isBase64Url = urlToRefresh && urlToRefresh.startsWith('data:');
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 构建请求参数
|
const newUrl = await requestTaskUrlRefresh(taskId, type, urlToRefresh);
|
||||||
let apiUrl = `/api/images/refresh-url?task_id=${encodeURIComponent(taskId)}&type=${type}`;
|
if (newUrl) {
|
||||||
|
|
||||||
// 如果有有效的COS URL(不是base64),传递给后端刷新
|
|
||||||
if (urlToRefresh && !isBase64Url) {
|
|
||||||
apiUrl += `&url=${encodeURIComponent(urlToRefresh)}`;
|
|
||||||
}
|
|
||||||
// 如果URL是空的或者是base64格式,不传url参数,后端会从数据库读取base64并上传
|
|
||||||
|
|
||||||
const response = await API.get(apiUrl);
|
|
||||||
|
|
||||||
if (response.data?.success && response.data?.data?.url) {
|
|
||||||
const newUrl = response.data.data.url;
|
|
||||||
console.log(
|
|
||||||
`${type === 'source' ? '原图' : '生成图'}URL刷新成功,新URL:`,
|
|
||||||
newUrl,
|
|
||||||
);
|
|
||||||
|
|
||||||
// 根据类型更新对应的URL,并清除base64数据(因为已上传到COS)
|
|
||||||
if (type === 'source') {
|
|
||||||
updateTask(taskId, {
|
|
||||||
sourceImageUrl: newUrl,
|
|
||||||
sourceImageBase64: null,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
updateTask(taskId, { imageUrl: newUrl, imageBase64: null });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!silent) showSuccess(i18next.t('链接已刷新'));
|
if (!silent) showSuccess(i18next.t('链接已刷新'));
|
||||||
return true;
|
return true;
|
||||||
} else {
|
|
||||||
if (!silent) showError(i18next.t('刷新链接失败'));
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
if (!silent) showError(i18next.t('刷新链接失败'));
|
||||||
|
return false;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('刷新URL失败:', error);
|
console.error('刷新URL失败:', error);
|
||||||
if (!silent)
|
if (!silent)
|
||||||
@@ -408,64 +424,43 @@ export const useImageTaskManagement = () => {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[tasks, updateTask],
|
[tasks, requestTaskUrlRefresh],
|
||||||
);
|
);
|
||||||
|
|
||||||
// 批量刷新所有成功状态任务的图片链接(静默模式,用于页面加载时自动刷新)
|
// 批量刷新所有成功状态任务的图片链接(静默模式,用于页面加载时自动刷新)
|
||||||
|
// 跳过本次挂载已刷新过的任务(如图片 onError 已先刷新);页面卸载后停止
|
||||||
const refreshAllSuccessUrls = useCallback(
|
const refreshAllSuccessUrls = useCallback(
|
||||||
async (taskList) => {
|
async (taskList) => {
|
||||||
// 筛选出成功状态的任务
|
const successTasks = taskList.filter(
|
||||||
const successTasks = taskList.filter((task) => task.status === 'success');
|
(task) =>
|
||||||
|
task.status === 'success' &&
|
||||||
if (successTasks.length === 0) {
|
!refreshedUrlKeysRef.current.has(`${task.id}|generated`),
|
||||||
return;
|
);
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`开始批量刷新 ${successTasks.length} 个任务的图片链接...`);
|
|
||||||
|
|
||||||
// 并发刷新,但限制并发数避免请求过多
|
// 并发刷新,但限制并发数避免请求过多
|
||||||
const BATCH_SIZE = 5;
|
const BATCH_SIZE = 5;
|
||||||
let refreshedCount = 0;
|
|
||||||
|
|
||||||
for (let i = 0; i < successTasks.length; i += BATCH_SIZE) {
|
for (let i = 0; i < successTasks.length; i += BATCH_SIZE) {
|
||||||
const batch = successTasks.slice(i, i + BATCH_SIZE);
|
if (!mountedRef.current) return;
|
||||||
|
const batch = successTasks
|
||||||
|
.slice(i, i + BATCH_SIZE)
|
||||||
|
.filter(
|
||||||
|
(task) => !refreshedUrlKeysRef.current.has(`${task.id}|generated`),
|
||||||
|
);
|
||||||
|
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
batch.map(async (task) => {
|
batch.map((task) =>
|
||||||
try {
|
requestTaskUrlRefresh(task.id, 'generated', task.imageUrl).catch(
|
||||||
// 构建请求参数
|
(error) => {
|
||||||
let apiUrl = `/api/images/refresh-url?task_id=${encodeURIComponent(task.id)}&type=generated`;
|
// 静默失败,不影响其他任务
|
||||||
|
console.warn(`刷新任务 ${task.id} 链接失败:`, error.message);
|
||||||
const urlToRefresh = task.imageUrl;
|
},
|
||||||
const isBase64Url =
|
),
|
||||||
urlToRefresh && urlToRefresh.startsWith('data:');
|
),
|
||||||
|
|
||||||
if (urlToRefresh && !isBase64Url) {
|
|
||||||
apiUrl += `&url=${encodeURIComponent(urlToRefresh)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await API.get(apiUrl);
|
|
||||||
|
|
||||||
if (response.data?.success && response.data?.data?.url) {
|
|
||||||
const newUrl = response.data.data.url;
|
|
||||||
updateTask(task.id, { imageUrl: newUrl, imageBase64: null });
|
|
||||||
refreshedCount++;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
// 静默失败,不影响其他任务
|
|
||||||
console.warn(`刷新任务 ${task.id} 链接失败:`, error.message);
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (refreshedCount > 0) {
|
|
||||||
console.log(
|
|
||||||
`批量刷新完成,成功刷新 ${refreshedCount} 个任务的图片链接`,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[updateTask],
|
[requestTaskUrlRefresh],
|
||||||
);
|
);
|
||||||
|
|
||||||
// 取消/删除任务
|
// 取消/删除任务
|
||||||
@@ -546,7 +541,8 @@ export const useImageTaskManagement = () => {
|
|||||||
// 自动刷新成功任务的图片链接(在后台静默执行,不阻塞页面)
|
// 自动刷新成功任务的图片链接(在后台静默执行,不阻塞页面)
|
||||||
if (autoRefreshUrls) {
|
if (autoRefreshUrls) {
|
||||||
// 使用 setTimeout 确保不阻塞 UI 渲染
|
// 使用 setTimeout 确保不阻塞 UI 渲染
|
||||||
setTimeout(() => {
|
clearTimeout(urlRefreshTimerRef.current);
|
||||||
|
urlRefreshTimerRef.current = setTimeout(() => {
|
||||||
refreshAllSuccessUrls(convertedTasks);
|
refreshAllSuccessUrls(convertedTasks);
|
||||||
}, 500);
|
}, 500);
|
||||||
}
|
}
|
||||||
@@ -655,6 +651,7 @@ export const useImageTaskManagement = () => {
|
|||||||
return () => {
|
return () => {
|
||||||
mountedRef.current = false;
|
mountedRef.current = false;
|
||||||
clearTimeout(pollingTimerRef.current);
|
clearTimeout(pollingTimerRef.current);
|
||||||
|
clearTimeout(urlRefreshTimerRef.current);
|
||||||
document.removeEventListener('visibilitychange', onVisibility);
|
document.removeEventListener('visibilitychange', onVisibility);
|
||||||
};
|
};
|
||||||
}, [refreshTasks, schedulePoll]);
|
}, [refreshTasks, schedulePoll]);
|
||||||
|
|||||||
@@ -58,7 +58,8 @@ export const useModelPricingData = () => {
|
|||||||
const [groupRatio, setGroupRatio] = useState({});
|
const [groupRatio, setGroupRatio] = useState({});
|
||||||
// 模型级等级折扣修正系数(四期):{分组: {模型: 系数}},有效倍率 = groupRatio[g] × (系数 ?? 1)
|
// 模型级等级折扣修正系数(四期):{分组: {模型: 系数}},有效倍率 = groupRatio[g] × (系数 ?? 1)
|
||||||
const [groupModelDiscount, setGroupModelDiscount] = useState({});
|
const [groupModelDiscount, setGroupModelDiscount] = useState({});
|
||||||
// 折扣展示口径:enterprise=企业作用域按企业等级折扣展示(个人密钥调用仍按个人等级计费)
|
// 折扣展示口径:enterprise=按企业等级折扣展示——用户只要属于可用企业(含个人会话、个人密钥、
|
||||||
|
// 体验中心),标价与扣费都按所属企业等级;personal=不属于任何企业,按个人等级。
|
||||||
const [discountScope, setDiscountScope] = useState('personal');
|
const [discountScope, setDiscountScope] = useState('personal');
|
||||||
const [usableGroup, setUsableGroup] = useState({});
|
const [usableGroup, setUsableGroup] = useState({});
|
||||||
const [endpointMap, setEndpointMap] = useState({});
|
const [endpointMap, setEndpointMap] = useState({});
|
||||||
|
|||||||
@@ -18,10 +18,9 @@ For commercial licensing, please contact support@quantumnous.com
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { useEffectEvent } from '../common/useEffectEvent';
|
import { useEffectEvent } from '../common/useEffectEvent';
|
||||||
import { writeClipboardText } from '../../helpers/clipboard';
|
|
||||||
import { useState, useEffect, useMemo, useRef } from 'react';
|
import { useState, useEffect, useMemo, useRef } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { API, showError, showSuccess } from '../../helpers';
|
import { API, copy, showError, showSuccess } from '../../helpers';
|
||||||
import { ITEMS_PER_PAGE } from '../../constants';
|
import { ITEMS_PER_PAGE } from '../../constants';
|
||||||
import { useTableCompactMode } from '../common/useTableCompactMode';
|
import { useTableCompactMode } from '../common/useTableCompactMode';
|
||||||
|
|
||||||
@@ -464,13 +463,12 @@ export const useModelsData = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Copy text helper
|
// Copy text helper:走公共 copy,HTTP 部署下 navigator.clipboard 为 undefined,
|
||||||
|
// 裸调只会报错而复制不到,公共 copy 带 execCommand 降级
|
||||||
const copyText = async (text) => {
|
const copyText = async (text) => {
|
||||||
try {
|
if (await copy(text)) {
|
||||||
await writeClipboardText(text);
|
|
||||||
showSuccess(t('复制成功'));
|
showSuccess(t('复制成功'));
|
||||||
} catch (error) {
|
} else {
|
||||||
console.error('Copy failed:', error);
|
|
||||||
showError(t('复制失败'));
|
showError(t('复制失败'));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -372,6 +372,9 @@ export function useOrgTokens(orgId) {
|
|||||||
const [tokens, setTokens] = useState([]);
|
const [tokens, setTokens] = useState([]);
|
||||||
const [total, setTotal] = useState(0);
|
const [total, setTotal] = useState(0);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
// 列表加载失败:业务文案字符串,或无文案时为 true;空串表示无错误。
|
||||||
|
// 页面据此展示错误态+重试,而不是误显示"暂无令牌"
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
const fetch = useCallback(
|
const fetch = useCallback(
|
||||||
async (page = 1, pageSize = 20) => {
|
async (page = 1, pageSize = 20) => {
|
||||||
@@ -385,8 +388,14 @@ export function useOrgTokens(orgId) {
|
|||||||
if (res.data.success) {
|
if (res.data.success) {
|
||||||
setTokens(res.data.data?.items || []);
|
setTokens(res.data.data?.items || []);
|
||||||
setTotal(res.data.data?.total || 0);
|
setTotal(res.data.data?.total || 0);
|
||||||
|
setError('');
|
||||||
|
} else {
|
||||||
|
// 无文案时用 true 兜底,保证页面仍进入错误态
|
||||||
|
setError(res.data.message || true);
|
||||||
|
showError(res.data.message);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
setError(err.message || true);
|
||||||
showError(err.message);
|
showError(err.message);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
@@ -423,7 +432,8 @@ export function useOrgTokens(orgId) {
|
|||||||
headers: getOrgHeaders(orgId),
|
headers: getOrgHeaders(orgId),
|
||||||
});
|
});
|
||||||
if (res.data.success) {
|
if (res.data.success) {
|
||||||
return true;
|
// 返回后端保存后的令牌(分组可能被后端回落改写),无数据时退化为 true
|
||||||
|
return res.data.data || true;
|
||||||
}
|
}
|
||||||
showError(res.data.message);
|
showError(res.data.message);
|
||||||
return false;
|
return false;
|
||||||
@@ -435,6 +445,27 @@ export function useOrgTokens(orgId) {
|
|||||||
[orgId],
|
[orgId],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const getTokenEditOptions = useCallback(
|
||||||
|
async (tokenId, projectId) => {
|
||||||
|
if (!orgId) return null;
|
||||||
|
try {
|
||||||
|
const params = {};
|
||||||
|
if (projectId != null) params.project_id = projectId;
|
||||||
|
const res = await API.get(`/api/org/tokens/${tokenId}/edit-options`, {
|
||||||
|
headers: getOrgHeaders(orgId),
|
||||||
|
params,
|
||||||
|
});
|
||||||
|
if (res.data.success) return res.data.data || null;
|
||||||
|
showError(res.data.message);
|
||||||
|
return null;
|
||||||
|
} catch (err) {
|
||||||
|
showError(err.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[orgId],
|
||||||
|
);
|
||||||
|
|
||||||
const deleteToken = useCallback(
|
const deleteToken = useCallback(
|
||||||
async (tokenId) => {
|
async (tokenId) => {
|
||||||
if (!orgId) return false;
|
if (!orgId) return false;
|
||||||
@@ -455,13 +486,37 @@ export function useOrgTokens(orgId) {
|
|||||||
[orgId],
|
[orgId],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// 列表只下发脱敏密钥;显示/复制时按需取完整密钥(后端留痕),失败返回 null
|
||||||
|
const fetchTokenKey = useCallback(
|
||||||
|
async (tokenId) => {
|
||||||
|
if (!orgId) return null;
|
||||||
|
try {
|
||||||
|
const res = await API.post(`/api/org/tokens/${tokenId}/key`, null, {
|
||||||
|
headers: getOrgHeaders(orgId),
|
||||||
|
});
|
||||||
|
if (res.data.success) {
|
||||||
|
return res.data.data?.key || null;
|
||||||
|
}
|
||||||
|
showError(res.data.message);
|
||||||
|
return null;
|
||||||
|
} catch (err) {
|
||||||
|
showError(err.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[orgId],
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
tokens,
|
tokens,
|
||||||
total,
|
total,
|
||||||
loading,
|
loading,
|
||||||
|
error,
|
||||||
fetch,
|
fetch,
|
||||||
createToken,
|
createToken,
|
||||||
updateToken,
|
updateToken,
|
||||||
|
getTokenEditOptions,
|
||||||
deleteToken,
|
deleteToken,
|
||||||
|
fetchTokenKey,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
/*
|
||||||
|
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 assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import vm from 'node:vm';
|
||||||
|
import React from 'react';
|
||||||
|
import { renderToString } from 'react-dom/server';
|
||||||
|
import { build } from 'esbuild';
|
||||||
|
|
||||||
|
// Execute the actual hook with React. Only its HTTP/error boundary is replaced.
|
||||||
|
const bundled = await build({
|
||||||
|
entryPoints: [fileURLToPath(new URL('./useOrgData.js', import.meta.url))],
|
||||||
|
bundle: true,
|
||||||
|
write: false,
|
||||||
|
platform: 'node',
|
||||||
|
format: 'cjs',
|
||||||
|
external: ['react', 'i18next'],
|
||||||
|
plugins: [
|
||||||
|
{
|
||||||
|
name: 'http-boundary',
|
||||||
|
setup(builder) {
|
||||||
|
builder.onResolve(
|
||||||
|
{ filter: /^\.\.\/\.\.\/helpers(?:\/api)?$/ },
|
||||||
|
() => ({
|
||||||
|
path: 'test-http-boundary',
|
||||||
|
external: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
function renderTokensHook(orgId) {
|
||||||
|
const calls = [];
|
||||||
|
const errors = [];
|
||||||
|
const transport = {
|
||||||
|
API: {
|
||||||
|
async get(url, config) {
|
||||||
|
calls.push({ url, ...config });
|
||||||
|
return {
|
||||||
|
data: { success: true, data: { groups: ['default', 'vip'] } },
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
showError: (message) => errors.push(message),
|
||||||
|
};
|
||||||
|
const module = { exports: {} };
|
||||||
|
vm.runInNewContext(bundled.outputFiles[0].text, {
|
||||||
|
module,
|
||||||
|
exports: module.exports,
|
||||||
|
require: (name) =>
|
||||||
|
name === 'test-http-boundary' ? transport : require(name),
|
||||||
|
});
|
||||||
|
let hook;
|
||||||
|
function Probe() {
|
||||||
|
hook = module.exports.useOrgTokens(orgId);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
renderToString(React.createElement(Probe));
|
||||||
|
return { hook, calls, errors, transport };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('token edit options explicitly send zero when unbinding a project', async () => {
|
||||||
|
const { hook, calls } = renderTokensHook(12);
|
||||||
|
const data = await hook.getTokenEditOptions(7, 0);
|
||||||
|
assert.equal(calls[0].url, '/api/org/tokens/7/edit-options');
|
||||||
|
assert.equal(calls[0].headers['X-Org-Id'], '12');
|
||||||
|
assert.equal(calls[0].params.project_id, 0);
|
||||||
|
assert.deepEqual(data.groups, ['default', 'vip']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('token edit options distinguish omitted project from an explicit project', async () => {
|
||||||
|
const { hook, calls } = renderTokensHook(12);
|
||||||
|
await hook.getTokenEditOptions(7);
|
||||||
|
await hook.getTokenEditOptions(7, 35);
|
||||||
|
assert.equal(Object.hasOwn(calls[0].params, 'project_id'), false);
|
||||||
|
assert.equal(calls[1].params.project_id, 35);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('token edit options fail closed on HTTP and business errors', async () => {
|
||||||
|
const { hook, transport, errors } = renderTokensHook(12);
|
||||||
|
transport.API.get = async () => ({
|
||||||
|
data: { success: false, message: 'denied' },
|
||||||
|
});
|
||||||
|
assert.equal(await hook.getTokenEditOptions(7, 0), null);
|
||||||
|
transport.API.get = async () => {
|
||||||
|
throw new Error('offline');
|
||||||
|
};
|
||||||
|
assert.equal(await hook.getTokenEditOptions(7, 0), null);
|
||||||
|
assert.deepEqual(errors, ['denied', 'offline']);
|
||||||
|
});
|
||||||
@@ -71,6 +71,10 @@ export const useTaskLogsData = ({
|
|||||||
PROGRESS: 'progress',
|
PROGRESS: 'progress',
|
||||||
QUOTA: 'quota',
|
QUOTA: 'quota',
|
||||||
FAIL_REASON: 'fail_reason',
|
FAIL_REASON: 'fail_reason',
|
||||||
|
// 企业消费明细「绘图与视频」:部门资金归属快照两列(F-36),仅企业模式
|
||||||
|
...(organizationMode
|
||||||
|
? { FUND_DEPT: 'fund_dept', FUND_ACCOUNT: 'fund_account' }
|
||||||
|
: {}),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Basic state
|
// Basic state
|
||||||
@@ -189,6 +193,9 @@ export const useTaskLogsData = ({
|
|||||||
[COLUMN_KEYS.PROGRESS]: true,
|
[COLUMN_KEYS.PROGRESS]: true,
|
||||||
[COLUMN_KEYS.QUOTA]: true,
|
[COLUMN_KEYS.QUOTA]: true,
|
||||||
[COLUMN_KEYS.FAIL_REASON]: true,
|
[COLUMN_KEYS.FAIL_REASON]: true,
|
||||||
|
...(organizationMode
|
||||||
|
? { [COLUMN_KEYS.FUND_DEPT]: true, [COLUMN_KEYS.FUND_ACCOUNT]: true }
|
||||||
|
: {}),
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user