Compare commits

...

15 Commits

Author SHA1 Message Date
zhanjunhao a62c80aea1 fix(authz): 修复菜单搜索卡顿并为菜单和角色接入自动搜索 2026-12-01 17:53:34 +08:00
zhanjunhao 06ef5f3f77 feat: 企业中心-角色管理 警告栏 样式优化 2026-12-01 17:26:16 +08:00
zhanjunhao cd6eae5ed9 fix(auth/user-center): 修复个人登录回跳并兼容旧入口 2026-12-01 16:07:31 +08:00
zhanjunhao 7e89edda5b chore(repo): 更新验收手册与开发监听忽略目录 2026-12-01 11:10:58 +08:00
zhanjunhao 2c43dd9cb1 feat(download): weyai桌面端下载页对齐原型、修复顶部导航在768分辨率的遮挡问题 2026-11-28 13:03:41 +08:00
zhanjunhao 6e41115d40 fix: 修复顶部导航和侧边栏菜单连点bug,封装公共侧边栏菜单组件并统一ui样式与交互 2026-11-27 19:18:15 +08:00
zhanjunhao 1e7780bdce fix(header): 右侧快捷入口去重节流,稳定菜单和弹窗交互 2026-11-27 17:52:14 +08:00
zhanjunhao 5a9d6ae3cb fix(layout): 修复顶栏连点和头像菜单抖动,统一三中心侧栏加载态 2026-11-27 16:59:53 +08:00
zhanjunhao 3a0d9e15cd chore(repo): 合并推广分享与智能路由分支基线 2026-11-26 17:05:11 +08:00
zhanjunhao 04cf3324a3 feat(promotion/repo): 统一分享弹窗尺寸、暂隐藏奖励入口并清理仓库文件 2026-11-26 16:52:09 +08:00
qiubaishen a811793825 feat(router): 统一智能路由判定模型文案与多语言显示
同步全栈仓库 2e6865aa3 的 web/ 更新。
2026-11-26 16:25:40 +08:00
qiubaishen 9576ba674a feat(router): 同步 Jev 专用出站代理设置
同步全栈仓库 c3a1786c6 的 web/ 更新。
2026-11-26 15:34:33 +08:00
qiubaishen 870b51d054 feat: 同步权限管理、企业成员排行与消费计费明细
- 接入平台与企业角色权限,按权限展示菜单、页面及操作。
- 企业成员排行按需加载,翻页沿用同一榜单快照,保留连续名次与前三名样式。
- 更新消费日志的费用明细、超管指标和官方价格汇率设置,补齐翻译与回归测试。
2026-11-25 21:08:24 +08:00
zhanjunhao ed693a450a fix(org/vite): 修正成员排行跨页名次与配色,拦截开发服务的 .npmrc 请求 2026-11-25 16:29:05 +08:00
zhanjunhao 49515f4ef3 feat(*): 对齐兑换码与渠道表格,统一兑换码侧栏窗并固定消费记录首尾列 2026-11-25 16:27:09 +08:00
192 changed files with 23933 additions and 7149 deletions
+3
View File
@@ -4,6 +4,8 @@
node_modules/
/.pnp
.pnp.js
bun.lock
bun.lockb
# testing
/coverage
@@ -25,6 +27,7 @@ node_modules/
/build
/dist/
/dist-ssr/
vercel.json
# tool caches and temporary files
__pycache__/
+2 -4
View File
@@ -26,7 +26,7 @@ Monkey AI Web 是从总仓库 `weiyuan` 分支独立出来的前端工程,包
环境要求:Node.js ≥ 22.13.0,npm ≥ 10(`packageManager` 为 npm 10.9.9)。统一使用 npm,不要用 Bun 或 Yarn 生成其他锁文件。
仓库仅维护 `package-lock.json`,已移除 `bun.lock`,并忽略 `bun.lock` / `bun.lockb`。本地与 CI 使用 `npm ci` 安装依赖、`npm run dev` 启动开发服务、`npm run build` 构建;Vercel 已显式配置 npm 安装与构建命令。
仓库仅维护 `package-lock.json`,并忽略 `bun.lock` / `bun.lockb`。本地与 CI 使用 `npm ci` 安装依赖、`npm run dev` 启动开发服务、`npm run build` 构建。
```bash
git clone --branch weiyuan https://git.weytoken.com/qiubs/monkey-ai-web.git
@@ -135,7 +135,6 @@ monkey-ai-web/
- **路由与权限**:在 `src/App.jsx` 注册路由,用 `PrivateRoute`、`AdminRoute`(role ≥ 10)、`RootRoute`(role ≥ 100)守卫;企业中心子路由在 `src/pages/Organization/index.jsx`。部分模块的可见性来自 `/api/status`,不能只靠隐藏菜单控制权限。
- **UI**:通用组件用 Ant Design;存量页面经 `src/components/ui` 适配层保留原契约;主题只由 `UiThemeProvider` 提供,不新增 ConfigProvider;按钮图标从 `src/components/common/icons/ActionIcons.js` 导入。页面改动需检查浅色、深色与窄屏。
- **国际化**:文案写 `t('中文原文')`,新 key 补齐 `src/i18n/locales/` 下 9 个语言包;运行时开放语言以 `src/i18n/catalog.js` 为准(简中、繁中、英、日、韩、越、泰),`fr.json`、`ru.json` 尚未登记。
- **版权声明**:通用版权与许可声明见 [NOTICE.md](NOTICE.md),源码无需重复添加长文件头;保留独立的第三方声明。
## 6. 常用命令与提交检查
@@ -211,13 +210,12 @@ npm run preview
- **缓存**:`index.html` 应及时更新,带哈希的静态资源可长缓存;后端地址写在产物中,切换需重新构建并发布。
- **部署路径**:当前按域名根路径部署;部署到子目录需检查 Vite `base`、路由与静态资源地址。
仓库中的 `vercel.json` 只关闭了 GitHub 通知,未配置路由回退或代理,不能作为完整部署配置。
## 8. 常见问题
| 现象 | 优先检查 |
| --- | --- |
| 页面能打开但提示状态或接口加载失败 | 后端是否可用;Network 中 `/api/status` 的目标地址与响应;代理配置 |
| 共享测试站出现 Vite 红色遮罩 | 检查站点网关的前端上游。共享测试站应由网关提供构建后的静态文件,Vite 开发服务仅用于联调。开发服务对 `.npmrc` 请求直接返回 404。 |
| 登录后又回到登录页 | `/api/user/self` 响应、Cookie 是否发送、跨域凭证策略、账号状态 |
| 企业数据为空或串到其他企业 | 当前组织选择、`current_org_id` 与请求头 `X-Org-Id` |
| 修改环境变量后无变化 | 是否重启开发服务或重新构建发布;HTML 与静态资源缓存 |
+236 -2
View File
@@ -1,6 +1,6 @@
# 变更记录(CHANGELOG)
> 状态:有效(持续追加) · 更新:2026-11-23 · 版本:v3.8
> 状态:有效(持续追加) · 更新:2026-12-01 · 版本:v3.20
对现状仍有影响的功能与修复记录,按日期倒序。改造、迁移、优化等一次性过程不在此记录。
@@ -8,8 +8,210 @@
**记录规则**:每条写“范围、变更、影响、回滚、关联”五项;回滚优先 `git revert <提交>`,提交含多项改动时按文件还原(`git checkout <提交>^ -- <文件>`),不整仓 reset。本文不作为规则依据。
## 2026-12-01
### 修复平台菜单搜索卡顿并接入自动搜索
- **范围** 控制台菜单管理和平台角色。
- **变更** 筛选字段使用公共的 300ms 防抖搜索,搜索按钮和回车立即应用条件。菜单输入与树表渲染分离,角色筛选沿用当前分页。
- **影响** 连续输入只应用最后一次筛选,重置取消待执行搜索并恢复默认筛选和表格状态。
- **回滚** 按差异还原 `src/pages/Permission/MenuManage.jsx`、`src/pages/Permission/PlatformRoles.jsx` 和本条目。
- **关联** `docs/standards/UI_COMPONENT_STANDARDS.md` 第 4 节。
### 对齐企业角色管理迁移提示的区块间距
- **范围** 企业中心 `/org/roles`。
- **变更** 复用企业治理页的布局间距,页头、迁移提示和角色列表之间统一留出 18px。
- **影响** 迁移提示隐藏时,页头与角色列表仍保持一个标准区块间距。
- **回滚** 按差异还原 `src/pages/Organization/OrgRoles.jsx` 和本条目。
- **关联** `docs/ui/GLOBAL_UI_BASELINE.md` 第 4.4 节。
### 修复个人登录回跳旧版用户中心地址
- **范围** 个人登录回跳、旧版用户中心入口与个人设置。
- **变更** 第三方账号绑定成功或回调缺少授权码时统一返回 `/user/center`,由该入口在登录后进入用户中心首个可见页面。`/console/personal` 保留为旧个人设置链接,登录后转到 `/user-center/settings`。旧链接跳转保留查询参数和片段标识。
- **影响** 个人账号可从旧链接进入用户中心,页面可见性继续由用户中心配置决定,控制台管理页面继续使用原有权限守卫。
- **回滚** 按差异还原 `src/App.jsx`、`src/pages/UserCenter/index.jsx`、`src/components/auth/OAuth2Callback.jsx` 和本条目。
- **关联** `docs/ui/USER_CENTER_SPEC.md` 第 1 节。
## 2026-11-30
### 权限重构验收手册移除 E2、T 账号验收项
- **范围** `docs/权限重构产品功能验收与切换手册.md`。
- **变更** 删除账号 E2(个人账号加入企业,切换后登录名回填)与 T(企业登录两步验证)的账号说明、验收项(原 1.4.3、1.4.4、3.1.3、3.3.1、3.3.2 及 3.8.4 中 E2 部分)和客户通知中的两步验证说明;其余编号顺延,交叉引用同步更新。
- **影响** 自动化验收不再依赖个人账号加入企业与两步验证账号,避免阻塞;上述两类场景需另行人工验证。仅文档变更。
- **回滚** 按文件还原该手册与本条目。
- **关联** 无。
## 2026-11-28
### 顶栏主导航在中等宽度下不再被操作区遮挡
- **范围** 全站共享顶栏(768px 及以上)。
- **变更** 导航槽位按实际可用宽度切换:放不下时收为「主导航」下拉菜单,放得下时恢复平铺;折叠菜单复用移动端菜单的菜单项、选中态与跳转。品牌区可收缩截断,移动端菜单按钮补充最小宽度约束。
- **影响** 修复前个人账号在 768px 仅剩 33px 导航宽度、6 个入口被裁切,1024px 裁切 5 个;修复后 360–3840px 均无裁切与横向溢出,1920px 及以上外观不变。路由、权限与入口条件不变。
- **回滚** 按文件还原 `src/components/layout/headerbar/{Navigation,MobileNavMenu,index}.jsx` 与 `src/styles/prototype.css` 的导航段,以及基线第 4.1 节对应条目。
- **关联** 全站 UI 基线第 4.1 节。
### WeyAi 下载页交互与多分辨率对齐原型
- **范围** `/weyai/download` 与 `/user-center/weyai-download` 共用页面及顶栏下载入口。
- **变更** 系统页签和架构按钮改为原型的选择交互,安装卡和列表中的“当前选择”行同步切换。按原型重排首屏、安装卡、安装包卡片、工作台示意、功能和步骤。断点改为原型的 1180 / 850 / 520px,并按页面可用宽度计算。新增 5 条文案,并补齐 9 个语言包。
- **影响** 默认展示自动识别的推荐包,未识别系统时不预选。下载地址、接口请求和 `window.open(url, '_self')` 触发方式不变。颜色由主题 token 派生,跟随系统主题色和深浅模式。已覆盖 3840 至 360px 宽度。
- **回滚** 按文件还原 `src/pages/WeyAiDownload/{index.jsx,WorkbenchPreview.jsx,weyai-download.css}`、9 个语言包、`src/styles/prototype.css` 和基线第 4.1、5 节。
- **关联** 全站 UI 基线第 4.1 和第 5 节。
## 2026-11-27
### 对齐 WeyAi 下载页原型
- **范围** 公开下载页、用户中心下载页及其顶栏下载入口。
- **变更** 对齐原型的标题、版本、平台入口、推荐卡、工作台示意、安装包列表、产品能力和使用步骤,同时恢复首屏渐变与顶栏入口选中反馈。
- **影响** 推荐和下载沿用现有处理,平台入口交互已由 2026-11-28 条目更新。页面支持浅色、深色及窄屏排布。
- **回滚** 恢复本次下载页组件、示意资源、多语言文案、顶栏操作组件和对应样式。
- **关联** 全站 UI 基线第 4.1 和第 5 节。
### 统一页面级侧栏并修复高频连点
- **范围** 体验中心、用户中心、控制台、企业中心、文档和伙伴工作台。
- **变更** 页面链接去重与节流,统一侧栏外壳、菜单项、分组、折叠和加载占位。
- **影响** 当前项连点不再重复写入导航历史,桌面折叠偏好跨页面同步,移动抽屉与底栏保留各自的入口。
- **回滚** 恢复本次侧栏组件、样式和交互 hook。
- **关联** 全站 UI 基线第 4.3 节。
### 优化右侧顶栏快捷操作
- **范围** 顶栏教程、WeyAi 下载、充值、推广、主题、语言和头像菜单。
- **变更** 快捷入口复用主导航节流和当前路由去重。主题切换限制连续触发,语言和头像菜单共用展开与关闭逻辑。
- **影响** 高频点击减少重复路由和主题更新,推广遮罩短暂过滤连点,连续退出登录只执行一个请求。
- **回滚** 恢复本次变更涉及的顶栏操作组件和相关 hook。
- **关联** 全站 UI 基线第 4.1 节。
### 修复顶栏连点、侧栏加载和头像菜单交互
- **范围** 全站主导航、用户中心、控制台、企业中心和顶栏头像菜单。
- **变更** 当前目标跳过重复导航,快速切换保留最新目标。三个中心复用侧栏加载占位。头像菜单统一处理悬停、点击和关闭。
- **影响** 侧栏加载前后保持对应的宽度和底部位置,已在默认目标页时连点顶栏不再产生路由变更。
- **回滚** 恢复本次变更涉及的主导航、侧栏加载和头像菜单文件。
- **关联** 全站 UI 基线第 4 节。
## 2026-11-26
### 统一智能路由的判定模型文案
- **范围** 个人、平台和企业的判定明细、试路由、集合、授权和管理设置。
- **变更** 判定来源显示「智能路由」,合规闸门显示「已调用模型」或对应原因。集合开关说明使用判定模型所需的平台设置和出境授权。
- **影响** 历史判定记录按新文案展示,新增管理日志使用「判定模型」名称。
- **回滚** 恢复对应的状态标签、语言包与后端提示文案。
- **关联** [智能路由判定模型文案调整方案](../../docs/04-渠道与路由/22-智能路由判定模型文案调整方案.md)。
### 智能路由支持 Jev 专用出站代理
- **范围** 智能路由全局设置中的 Jev 判定请求。
- **变更** 超级管理员可以配置、测试和清除 HTTP、HTTPS 或 SOCKS5 系列代理。
- **影响** 测试展示 Google 连通性、耗时、出口 IP 和国家或地区。
- **回滚** 清除代理即可恢复 Jev 原有的服务器网络设置。
- **关联** 智能路由 Jev 设置和管理接口。
### 修复 · 稳定推广分享弹窗高度
- **范围**:顶栏「推广分享」弹窗的链接分享和海报分享页签。
- **变更**:两个页签共用等高的内容区,并按视口限制高度。邀请卡片和海报预览共用列宽、圆角和最小高度。
- **影响**:切换页签时弹窗位置保持稳定,两张卡片对齐,内容超出可用高度时在页签内滚动。
- **回滚**:恢复推广分享弹窗原有的页签高度、滚动和预览卡片样式。
- **关联**:`src/components/promotion/promotion-poster.css`。
### 清理 · 移除 Bun 锁文件、Vercel 配置和根目录声明文档
- **范围**:依赖锁文件、Vercel 配置、根目录声明文档和 Git 忽略规则。
- **变更**:移除 `bun.lock`、`vercel.json` 和 `NOTICE.md`,清理现行文档中的对应引用,忽略 `bun.lock`、`bun.lockb` 和 `vercel.json`。
- **影响**:npm 继续使用 `package-lock.json`。Vercel Git 部署改由 Vercel 项目设置提供安装和构建命令。
- **回滚**:还原本次文档和忽略规则改动,并从变更前的 Git 版本恢复三个文件。
- **关联**:`.gitignore`、`README.md`、`docs/standards/DEV_STANDARDS.md`。
### 调整 · 暂时隐藏推广分享中的邀请奖励规则入口
- **范围**:顶栏「推广 → 推广分享」弹窗。
- **变更**:暂停渲染弹窗底部「查看邀请奖励规则」入口。
- **影响**:用户仍可通过弹窗分享邀请链接、邀请码和海报。
- **回滚**:将 `SHOW_INVITATION_REWARD_RULES` 设为 `true`。
- **关联**:`src/components/promotion/PromotionPosterModal.jsx`。
## 2026-11-25
### 优化 · 成员排行按需加载并固定翻页结果
- **范围**:企业中心「消耗明细 → 成员排行」。
- **变更**:打开排行页签时按已应用的筛选查询,翻页和更改每页人数时沿用同一快照。刷新或重新筛选会获取当前榜单。
- **影响**:查看明细日志时省去排行请求。榜单更新期间翻页仍显示同一时点的名次;快照过期后自动回到第 1 页。
- **回滚**:恢复前端原有的排行加载与分页逻辑;分页响应兼容未传快照的客户端。
- **关联**:`src/pages/Organization/OrgLogs.jsx`、`src/hooks/org/useOrgData.js`、`docs/ui/ORG_CENTER_SPEC.md`。
### 优化 · 企业消耗明细成员排行支持服务端分页
- **范围**:企业中心「消耗明细 → 成员排行」及 `GET /api/org/logs/ranking`。
- **变更**:在权限和筛选范围内按成员汇总,消耗额度由高到低,同额按成员 ID 升序,返回当前页和总人数。
- **影响**:可以翻到第 50 名以后,跨页名次连续,前三名沿用主题强调色。
- **回滚**:先回退前端排行分页,再回退后端接口。旧前端仍可使用原有的 `limit` 查询。
- **关联**:`src/pages/Organization/OrgLogs.jsx`、`src/hooks/org/useOrgData.js`。
### 同步 · 三中心列表与本地权限适配
- **范围**:合入纯前端仓库 `weiyuan` 从 `574b6efa1` 至 `ed693a450` 的增量。
- **变更**:用户列表的自动搜索同时传递状态筛选和取消信号,企业日志在后续页重新筛选时同步刷新总数。企业内容页按操作权限显示创建、上传、分发与删除入口。兑换码按后端的查询、创建、编辑和删除权限显示操作,启停沿用编辑权限。个人密钥编辑表单在打开时加载模型、分组和技能选项。
- **影响**:角色分配、额度调整、模型映射、企业代理会话以及日志查询、排行、导出的独立权限继续使用全栈接口契约。
- **回滚**:按对应页面和共享依赖回退本次前端增量。
- **关联**:`src/components/table/users/`、`src/hooks/org/useOrgData.js`、`src/pages/Organization/`。
### 优化 · 消费记录固定首尾列
- **范围**:用户中心 `/user-center/usage-record` 的消费记录调用明细。
- **变更**:时间列固定在左侧,操作列显示时固定在右侧。
- **影响**:横向滚动中间字段时,仍可读取时间并打开账单详情。
- **回滚**:还原消费记录时间列和操作列的固定配置。
- **关联**:`src/components/table/usage-logs/`、`docs/ui/USER_CENTER_SPEC.md`。
### 优化 · 兑换码编辑侧栏窗
- **范围**:控制台 `/console/redemption` 编辑入口。
- **变更**:编辑兑换码信息与添加兑换码共用右侧侧栏窗。
- **影响**:两种表单使用相同的宽度、关闭方式和页脚,编辑继续回填当前记录。
- **回滚**:还原兑换码编辑表单的独立弹窗。
- **关联**:`src/components/table/redemptions/modals/EditRedemptionModal.jsx`、`docs/ui/CONSOLE_SPEC.md`。
### 优化 · 兑换码列表行内操作
- **范围**:控制台 `/console/redemption` 表格操作列。
- **变更**:「查看详情」入口简化为「查看」,启用、禁用和删除从更多菜单移至行内,按钮单行排列并随操作列固定在右侧。
- **影响**:桌面与窄屏均可直接使用行操作,启停权限和删除确认沿用原规则。
- **回滚**:还原兑换码操作列按钮、宽度和换行样式。
- **关联**:`src/components/table/redemptions/`、`docs/ui/CONSOLE_SPEC.md`。
### 优化 · 兑换码列表与表单
- **范围**:控制台 `/console/redemption` 与 `/console/channel` 的表头。
- **变更**:沿用渠道列表的表格与行内操作样式,提升两页表头文字对比度,固定兑换码操作列,新增同页详情弹窗,统一添加侧栏窗与编辑弹窗的表单及页脚。
- **影响**:可在详情弹窗查看与复制原码,批量复制随选中态启用,清除失效操作保留二次确认。
- **回滚**:还原兑换码列表、表单、详情弹窗和对应样式与文案。
- **关联**:`src/components/table/redemptions/`、`docs/ui/CONSOLE_SPEC.md`。
### 修复 · 企业成员排行的主题色与跨页名次
- **范围**:企业中心 `/org/logs` 的成员排行。
- **变更**:前三名使用主题派生的三档底色,其他名次使用中性色;在分页前生成全表名次。
- **影响**:切换系统主色或明暗模式时,排名徽章同步更新;翻页时继续显示全表名次。
- **回滚**:还原排名列的名次生成和徽章配色。
- **关联**:`src/pages/Organization/OrgLogs.jsx`、`src/styles/org-center.css`、`docs/ui/ORG_CENTER_SPEC.md`。
### 修复 · Vite 读取 npm 配置文件触发错误遮罩
- **范围**:Vite 开发服务的文件请求处理。
- **变更**:在资源转换前拦截 `.npmrc` 请求并返回 404,同时将 `.npmrc` 加入文件访问拒绝列表。
- **影响**:npm 配置文件请求不会启动资源转换或触发全站热更新错误遮罩。应用使用的文本资源导入继续由 Vite 转换。
- **回滚**:还原 Vite 的 npm 配置文件拦截和对应访问规则。
- **关联**:`vite.config.js`、`README.md`。
### 修复 · 控制台数据看板持续加载
- **范围**:控制台 `/console/analytics` 运营看板、创作作品详情抽屉及公共 API 的只读请求。
@@ -20,6 +222,30 @@
## 2026-11-24
### 功能 · 计费详情弹窗增加费用明细与计算公式
- **范围**:使用记录 `/user-center/usage-record` 与控制台使用日志的「详情」弹窗(共用 `UsageLogsTable.jsx`)。
- **变更**:新增「费用明细」:公式行(总金额 = 各计费项小计相加)与分项表(计费项、用量、单价、小计、合计),每行标注单价由哪些倍率构成;用量从「成本因子」移到分项表,成本因子只留倍率等补充信息。拆分逻辑在 `billingBreakdown.js`,口径对照后端结算公式;各行按展示精度四舍五入后与合计的差额归入「舍入与其他调整」一项,保证界面上的数字逐项相加恰好等于合计(`reconcileDisplayAmounts`);分项之和与实扣相差超过 1 个额度单位时视为口径未覆盖(如任务按时长 / 分辨率系数计价),token 兜底预扣与差额调整行同样不拆分,这些情况都不显示费用明细。已在费用明细里逐行列出的用量不再出现在成本因子区;按次 / 按秒计费的明细里没有 token 行,token 用量仍留在成本因子区。弹窗里的倍率由保留 3 位小数改为最多 6 位。超级管理员多一个「超管指标」区块,三项:官方价金额(1 倍率)= 同样用量按「模型原厂价格」计价 ÷ 原厂价登记汇率,整体倍率 = 实扣 ÷ 官方价金额,实际折扣 = 整体倍率 ÷ 登记汇率(汇率在 系统设置-倍率设置-模型原厂价格 页签顶部配置,option `OfficialPriceExchangeRate`,默认 7,仅超级管理员可读写),由后端只在超级管理员的日志响应里附加(`other.root_billing`,不落库),普通管理员与用户的接口不返回;未登记原厂价、或含音频 / 图片输入 / 工具调用等原厂价格表没有价目的计费项时不显示;按次计费但实扣含任务系数、出图接口、token 兜底预扣与差额调整行同样不显示。
- **影响**:前端只改展示,不改请求。同批后端改动会改变扣费:Claude 联网搜索开始按次计费(此前算了价但未扣,流式与原生 Claude 格式此前也不记录次数;只对 Claude 模型收,其他走 Anthropic 协议的渠道即使上报搜索次数也不收;体验中心 / Playground 对 Claude 模型开启原生联网搜索时同样会多出这笔费用);扣费取整统一为四舍五入到 1 个额度单位(`common.QuotaFromFloat`,取整前先消除浮点噪声):Claude 原生结算、按次 / 按秒 / 任务类计费此前是向下取整,现在小数部分 ≥ 0.5 的每笔多 1 个额度单位(如 0.3 × 1.5 × 500000 由 224999 变为 225000);OpenAI 兼容路径原本就是四舍五入,不变。Claude 原生与音频 / 实时语音路径有费用时至少扣 1 个额度单位(此前不足 1 个单位扣 0)。邀请返佣仍向下取整(`common.QuotaFloorFromFloat`,只消除浮点噪声),保证返佣不超过「比例 × 消费」;token 预扣估算是准入闸门、不是最终扣费,保持原样。发布窗口内已提交未结算的视频任务,预扣(旧版向下取整)与结算(新版四舍五入)可能差 1 个额度单位:结算时重算结果与预扣只差 1 个单位的按预扣结清(`common.SettleRecomputedQuota`),不补扣不退款。缺少计费信息的日志不显示费用明细,弹窗与原来一致。后端结算公式变更时须同步 `billingBreakdown.js`。本条未做浏览器走查。
- **回滚**:`git revert` 对应提交;`billingBreakdown.js` 与其单测为新增文件。
- **关联**:`src/components/table/usage-logs/{UsageLogsTable.jsx,billingBreakdown.js,UsageLogs.css}`、`src/pages/Setting/Ratio/OfficialPriceExchangeRateSetting.jsx`、`test/unit/{usage-billing-breakdown,usage-billing-detail-render,official-price-exchange-rate-setting}.test.js`、后端 `common/quota.go`、`relay/compatible_handler.go`、`relay/channel/claude/relay-claude.go`、`service/quota.go`、`service/log_overall_ratio.go`、`controller/log.go`。
### 修复 · 企业登录接入人机验证
- **范围**:企业登录页 `/org/login`(企业标识登录与免企业标识直登)。
- **变更**:系统开启 Turnstile 时,企业登录页显示人机验证,提交 `/api/org/login`、`/api/org/login/direct` 时带上 `turnstile` 参数;后端两条接口同步挂上 `TurnstileCheck`(未开启时自动放行)。
- **影响**:未开启 Turnstile 的部署无变化。开启后,企业成员在通过人机验证前不能提交登录;两步验证、多企业选择两步不再重复验证。
- **回滚**:`git revert` 对应提交(前后端须一起回滚,只回滚前端会导致开启 Turnstile 的部署无法企业登录)。
- **关联**:`src/pages/OrgLogin/index.jsx`、`router/org-router.go`。
### 新增 · 渠道透传时应用模型映射
- **范围**:控制台渠道编辑框的「渠道额外设置」。
- **变更**:「透传请求体」下方新增「透传时应用模型映射」,支持单独开启并保存。
- **影响**:新建渠道和缺少该设置的历史渠道默认关闭。开启后,实际透传且命中渠道映射的请求使用映射后的上游模型名。
- **回滚**:关闭该渠道的「透传时应用模型映射」并保存。
- **关联**:`src/components/table/channels/modals/EditChannelModal.jsx`、`src/i18n/locales/`。
### 修复 · 控制台会员列表与弹窗
- **范围**:控制台 `/console/subscription` 的会员列表、新建与编辑会员卡弹窗。
@@ -208,7 +434,7 @@
### 修复 · 编辑用户分组提交格式
- **范围**:`/console/user` 编辑用户的分组字段。
- **变更**:单个字符串、逗号分隔字符串和数组均可回填,保存时统一提交逗号分隔字符串。
- **变更**:按后端的单分组权限契约回填和保存,历史名称中的逗号原样保留。
- **影响**:保留已有分组选择及请求地址。
- **回滚**:还原编辑用户表单的分组转换。
- **关联**:`src/components/table/users/modals/EditUserModal.jsx`。
@@ -319,6 +545,14 @@
## 2026-11-23
### 功能 · 统一权限体系前端(合入 weiyuan 后按 antd 6 重做)
- **范围**:控制台路由守卫与侧栏、权限管理 5 页(菜单管理、平台角色、功能套餐、角色模板、运行模式)、用户管理、企业管理;企业中心入口与侧栏、角色管理(新增 `/org/roles`)、员工管理,以及其余企业中心页面的按钮显隐;企业登录页。
- **变更**:新增 `src/authz`(`usePerm` / `Perm` / `PermRoute` / `ConsoleRoute`),已切到新权限体系的模块按权限点判断,未切换的沿用原角色判断;超管"进入企业"改走代理会话(`X-Proxy-Session`,只存当前标签页);当前企业统一经 `helpers/orgContext.js` 读写;员工管理合并为一张表并改为服务端筛选分页,新增员工编辑;用户管理新增状态筛选、"添加额度"(按调整量)与"分配角色";企业管理新增所有者、功能套餐、预警通知列与"更换所有者";授权树支持父子联动、半选与全部展开 / 收起;企业登录支持两步验证与首登改密。
- **影响**:未切换时各入口的可见性与原来一致。员工管理不再有"员工权限 / 员工账号"页签;`OrgMemberAccounts.jsx` 只导出两个弹窗。接口变化见 `docs/10-数据安全与权限/10-权限体系重构改造方案.md` §13。本条所列页面均未做浏览器走查。
- **回滚**:`git revert` 对应提交;权限管理页、`src/authz`、`orgContext.js` 为新增文件。
- **关联**:`src/authz/*`、`src/pages/Permission/*`、`src/components/authz/PermTree.jsx`、`src/pages/Organization/{index,OrgSidebar,OrgRoles,OrgMembers,OrgMemberAccounts}.jsx`、`src/pages/Organization/orgMenuAccess.js`、`src/components/table/users/*`、`src/pages/AdminOrganizations/*`、`src/App.jsx`、`src/components/layout/SiderBar.jsx`。
### 修复 · 表格启停开关与分组样式统一
- **范围**:已有启停开关、调用或计费分组的表格,以及操作列删除确认规范。
+2 -2
View File
@@ -1,6 +1,6 @@
# 统一开发与 Ant Design CRUD 规范
> 状态:有效 · 适用:React 18.3、antd 6.7.0、Vite 5.4、Node ≥ 22.13 · 更新:2026-11-20 · 版本:v2.5
> 状态:有效 · 适用:React 18.3、antd 6.7.0、Vite 5.4、Node ≥ 22.13 · 更新:2026-11-26 · 版本:v2.6
新增与重构 CRUD 的编码规范:目录与命名、组件选择、请求、React 组件与状态、表单与弹层、权限、i18n,以及可直接复制的页面模板。外观取值见 `UI_COMPONENT_STANDARDS.md`。
@@ -55,7 +55,7 @@
### 1.3 版权声明
通用版权与许可声明集中保留在 [NOTICE.md](../../NOTICE.md)。源码不重复添加长版权文件头,不移除独立的第三方声明。
源码不重复添加通用长版权文件头,保留独立的第三方声明。
## 2. Ant Design 组件边界
+3 -1
View File
@@ -1,6 +1,6 @@
# 控制台 UI 规范(/console/\*)
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v2.4
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-25 · 版本:v2.7
管理控制台 `/console/*` 的规范:统一页头、控制台原语与差异样式。
@@ -58,6 +58,8 @@
- 提示栏:控制台内的 `Banner` / `Alert` 统一走 `ConsoleAlert`,内边距 12px 16px、正文 14 / 22px、图标 16px,颜色取对应语义 token。
- 系统设置(`page.key === 'setting'`):表单统一纵向布局、8px 标签间距、24px 栅格、控件等宽,校验信息预留高度;弹窗页脚按钮高 34px、间距 8px、右对齐。规则限定在 `.settings-page` / `.settings-form-dialog`。
- 控制台上下文中 `CompactModeToggle` 不渲染,表格密度状态保留;其他模块仍可使用紧凑模式。
- 兑换码列表沿用渠道列表的行内链接按钮、右侧固定操作列和底部分页。「查看、复制、编辑、禁用/启用、删除」在同一行直接显示,保留既有权限和状态限制,删除仍需确认。窄屏横向滚动时操作列不换行。批量复制在选中兑换码后可用,清除失效兑换码由独立的危险操作确认承载。
- 添加兑换码与编辑兑换码信息共用右侧侧栏窗、表单样式及页脚。查看详情使用弹窗,优先展示兑换码和状态,再列出额度、时间与兑换人信息。
- 平台 Skill 中心的分类标签区域与搜索工具栏同宽、左对齐,不保留独立的最大宽度和自动居中;窄屏按原间距自然换行。
- 平台 Skill 详情的审核工作台仅由抽屉正文纵向滚动,技能原文不设置独立滚动区;审核操作进入抽屉固定页脚,按钮右对齐、间距 8px,仅在审核页签展示。
- 官网文章抽屉允许点击遮罩关闭,X、取消、遮罩共用同一未保存内容确认流程。
+8 -5
View File
@@ -1,6 +1,6 @@
# 后台 UI 全局基线
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-23 · 版本:v3.14
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-28 · 版本:v3.15
后台外壳与布局基线:顶栏、侧栏、公告、页头与内容边距、登录页,以及原型未定义场景、登录关卡与验收流程。主题与组件样式见 `UI_COMPONENT_STANDARDS.md`。
@@ -51,10 +51,12 @@
- 桌面高 72px、移动 56px,另含 1px 底部分隔线;背景、文字、分隔线跟随双主题变量。
- 主导航:导航项撑满顶栏,左右内边距 24px;2px 主色下划线两端内缩 16px;选中项主色文字,普通项悬停保留正常文字色,键盘焦点可见。不改链接与权限条件。
- 768px 及以上,导航槽位按实际可用宽度判断:完整导航放不下时收为「主导航」下拉菜单,放得下时恢复平铺,不出现被操作区覆盖或隐藏横向滚动的导航项。菜单项、选中态、外链与鉴权跳转复用移动端菜单;槽位 ≥ 84px 显示当前页名称,更窄时为 34px 图标按钮;切换时焦点在导航内则移到菜单按钮。
- 右侧按钮:主题、公告、语言等图标 16px,按钮高度与工具按钮点击区 34px、文字行高 20px,账户头像 32px、下拉箭头 10px;`.ui-header-actions` 内链接、徽标和图标容器为 inline-flex,图标、文字、头像与分隔线垂直居中;桌面专属操作在 768px 以下隐藏。
- 全站共享顶栏不展示未登录用户的“登录 / 注册”按钮,桌面与移动端一致;已登录用户保留头像与账户菜单,登录 / 注册页面及受保护导航的原有鉴权跳转保持不变。
- 主题按钮为 `Button` + `Tooltip`,点击在浅色与深色之间直接切换,不提供下拉或“跟随系统”;沿用现有主题 setter 与持久化,覆盖 `/org/login`、`/login` 与共享顶栏。
- WeyAi 下载按钮复用现有下载配置与权限判定,跳转 `/weyai/download`;使用 antd text 按钮默认悬停背景与 `Tooltip`,不硬编码外部地址。
- WeyAi 下载按钮复用现有下载配置与权限判定,跳转 `/weyai/download`。在两个下载路由中显示品牌强调色文字和约 6% 的主题色底,并区分悬停、按压和键盘焦点。其他页面使用 antd text 按钮默认样式,保留 `Tooltip`。
- 右侧快捷链接复用主导航的当前路由去重与节流。主题切换即时响应首击,语言和头像菜单统一处理悬停、点击和键盘关闭。推广弹窗短暂过滤打开时落到遮罩上的连点。
### 4.2 公告栏与系统公告弹窗
@@ -64,8 +66,9 @@
### 4.3 侧栏
- 控制台侧栏显示、路由选中项变化或滚动区尺寸变化后,当前菜单超出可视范围时,仅滚动菜单区域使其完整可见;已可见时不移动,不滚动正文、不抢焦点,也不强制展开用户手动收起的分组。
- 企业中心与用户中心共用 `src/styles/center-layout.css`:展开 216px、收起 64px;菜单行高 42px、行距 6px,图标 16px / 1.5px 线宽;折叠入口文案“收起导航”。
- 页面级侧栏共用 `CenterSidebar` 和 `src/styles/center-layout.css`:展开 216px、收起 64px;菜单行高 42px、行距 6px,图标 16px / 1.5px 线宽;折叠入口文案“收起导航”。抽屉保留完整文字,窄屏的底部或横向导航沿用各页面的布局。
- 当前菜单超出可视范围时,仅滚动菜单区域使其完整可见;已可见时不移动。侧栏使用当前路由去重,快速切换保留最新目标。折叠按钮和分组操作过滤同一控件的连点。
- 体验、用户、控制台和企业中心的加载占位复用侧栏外壳,保持宽度、菜单起点及底部折叠条位置。企业身份和分组标题保留对应占位。
- 企业信息区为无底框网格图标(24px / 1.65 线宽),内边距 28px 16px 26px,图文间距 10px;企业名与身份 12px / 20px 行高,身份上距 2px。
- 个人侧栏只保留容器外侧分隔线,内层 Menu 不叠加 `border-inline-end`;企业侧栏不提供菜单搜索。
- 内容外壳设 `min-width: 0`,防止宽表格挤压;桌面滚动区保留稳定槽位并补足 16px 留白,移动端不补。
@@ -94,7 +97,7 @@
- 带侧栏页面按 4.4;控制台按 `CONSOLE_SPEC.md`;其余页面内容默认 24px 30px、移动 16px。筛选区自然换行,表格在自身容器横向滚动;不通过隐藏正文、裁剪校验信息或固定整页宽度迎合截图。
- 模型超市与技能超市的工作区居中,含内边距的最大宽度为 1760px;横向内边距为 `clamp(20px, 4vw, 80px)`,Hero 搜索区域沿用同一横向留白,600px 及以下为 20px。覆盖 3840 / 2560 / 1920 至 360px 宽度,目录按实际可用宽度减少列数,保留卡片正文和控件正常字号,不通过整体缩放压缩内容。
- WeyAi 两个下载路由共用页头、安装卡、工作台示意、平台安装包、功能和使用步骤。公开页的居中容器含内边距最大宽度为 1464px。首屏在页面可用宽度 960px 及以下上下排列,安装包分组在 1024px 及以上显示三列,在 768–1023px 显示两列,其余宽度显示一列,文件名可换行。用户中心内嵌页沿用第 4.4 节的面包屑和内容边距,下载页背景从面包屑区域开始覆盖内容区,面包屑与首屏标题区间隔 24px。
- WeyAi 两个下载路由共用页头、安装卡、工作台示意、平台安装包、功能和使用步骤,结构与测量值取自桌面原型 `微元优化原型/index.html` 的 WeyAIDownload。系统页签与架构按钮切换安装卡展示的安装包,并同步列表中的“当前选择”行,默认值是自动识别的推荐包,未识别系统时不预选。下载地址、请求与触发方式不变。颜色只用主题 token 派生,跟随系统主题色和深浅模式。公开页与内嵌页的居中容器含内边距最大宽度分别为 1480px 和 1760px。断点按页面可用宽度计算,阈值沿用原型的 1180 / 850 / 520px。850px 及以下首屏、安装包和步骤改为单列,520px 及以下系统页签等宽并使用 44px 热区,文件名可换行。用户中心内嵌页沿用第 4.4 节的面包屑、标题和内容边距,下载页背景从面包屑区域开始覆盖内容区,面包屑与首屏标题区间隔 24px。
- 背景图优先复用原型的原始 SVG / 图片,放入 `src/assets/prototype` 并注明来源;原型用 CSS 绘制的背景按测量值在页面作用域复现,不用生成插画替代。
- 企业工作台横幅 `.ew-hero` 的浅金 / 深棕背景与三层轮廓只用于 `.org-workbench`,不扩散到其他页面。
- 原型未定义、antd 有组件:用当前版本默认样式与主题 token。antd 无对应部件:语义背景 / 文字 / 边框,无装饰背景、阴影与动画,间距 8 / 16 / 24px,窄屏堆叠且操作可达;新增此类统一规则先写入本文。
+6 -5
View File
@@ -1,6 +1,6 @@
# 企业中心 UI 规范(/org/\*)
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-24 · 版本:v2.4
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-25 · 版本:v2.5
企业中心 12 个目标页的规范:企业中心变量、通用组件的企业中心变体与各页面规则。
@@ -10,7 +10,7 @@
| 关注点 | 规则 |
| --- | --- |
| 范围 | 工作台、数据看板、员工管理、项目管理、预算中心、审批中心、密钥管理、企业充值、消耗明细、审计日志、个人设置、企业设置;“我的 AI 能力”“组织架构”“角色管理”不改 |
| 范围 | 工作台、数据看板、员工管理、项目管理、预算中心、审批中心、令牌管理(原“密钥管理”)、企业充值、消耗明细、审计日志、个人设置、企业设置;“我的 AI 能力”不改;“组织架构”页面名称统一为“部门管理”(与权限目录一致,2026-11-23);“角色管理”为统一权限体系新增页面(2026-11-23) |
| 样式 | `org-center.css`,作用域 `.org-center .oc-page`,颜色只写 `--oc-*`(第 2 节) |
| 组件变体 | 紧凑表格、3 列筛选、无图标行操作、`.oc-list-tabs`、无边框标签(第 3 节) |
| 弹层 | `OrgModal` / `OrgSideSheet`,原型风格遮罩;密钥抽屉 560px |
@@ -23,7 +23,7 @@
- 视觉依据:在线原型 `http://192.168.0.161:8888` 顶栏“企业中心”(深色用“切换至暗色主题”),只作视觉依据,不作业务、路由、数据依据。
- 只对齐背景、字体、图标、表格、表单、卡片、页签、搜索条件、操作列、弹窗、按钮、颜色、文字、间距与已有交互反馈;不改请求、载荷、状态、路由、权限与触发条件。
- 原型有而系统无的功能不补建:员工筛选卡、CSV 导出、新建员工 / 分配角色 / 离职、角色管理、在职 / 离职筛选、订单号搜索、分组列、发票入口。例外:企业密钥管理的分组列与列设置已按需求实现。
- 原型有而系统无的功能不补建:CSV 导出、在职 / 离职页签、订单号搜索、分组列、发票入口。例外:企业密钥管理的分组列与列设置已按需求实现。
## 2. 作用域与变量
@@ -64,7 +64,7 @@
| --- | --- | --- |
| 工作台 | `OrgHero` 标签化身份与 `oc-wb-*` 卡片(额度、密钥、用量、最近申请);横幅 `.ew-hero` 背景只在 `.org-workbench` 作用域 | 额度周期标签放在重置卡;最近申请无分页 |
| 数据看板 | `oc-dash-*` hero(健康提示“企业运行正常”、企业名、企业额度、组织概况)+ `OrgAnalyticsPanel`(汇总条、趋势 `Segmented`、分布、明细页签) | 时间范围 7 / 30 / 90 天;企业名来自 `orgInfo.name`,无值时隐藏 |
| 员工管理 | 页签(员工权限 / 员工账号)+ 列表卡;首列与操作列固定;备注独立列;状态 `Switch` | 无筛选卡与在职 / 离职页签 |
| 员工管理 | 筛选卡(关键字、分组、组织、状态,服务端筛选)+ 单张列表卡,不分页签;备注独立列;状态 `Switch`;新建 / 编辑用抽屉 | 无在职 / 离职页签 |
| 项目管理 | `OrgListCard` + link 操作(模型 / 分组 / 成员 / 密钥 / 编辑);状态开关 | 操作列不再显示“停用” |
| 预算中心 | `.oc-policy` 固定说明条;列宽 300 / 110 / 260 / 120 / 120 / 130;状态开关 | 已加载数据前端分页 |
| 审批中心 | 状态页签(回调 `setStatusFilter`)+ 申请列表卡;拒绝弹窗竖排表单项 | — |
@@ -90,7 +90,8 @@
- 时间范围为本页签自有的可编辑字段(默认最近 7 天,含快捷预设),与“明细日志”筛选互不影响;起止颠倒沿用原提示。
- 末列“操作”不固定:视频任务显示“点击预览视频”,失败任务保留失败原因查看,其余显示“-”。
- 预览视频沿用 `ContentModal`:标题栏“视频预览”与关闭按钮、16:9 播放区、加载态、播放失败或无地址时 `Empty` 空态、页脚复制链接 / 新标签页打开 / 关闭;关闭时暂停视频,重开同一视频不残留加载指示。
- 成员排行行键使用 `user_id-名次序号`,避免后端同一成员多行时出现重复 key。
- 只有具备排行权限并打开「成员排行」时才查询榜单。首次打开使用已生效的成员、模型和时间范围,默认每页 10 人。翻页和更改每页人数均携带服务端返回的 `snapshot`。搜索、重置、刷新及切换企业会重新查询当前条件下的榜单。快照过期时自动按原筛选和页容量回到第 1 页重取一次。
- 服务端按成员汇总后按消耗额度降序排列,同额按成员 ID 升序。行键使用 `user_id`,名次按返回页码、页容量和行号连续计算。前三名使用当前主题的强调色及三档底色,其余名次使用中性色。
- 明细日志查询不写 URL;绘图与视频筛选沿用原有 URL 同步。
- 保留差异:明细日志无列设置、分组列、操作列;任务表无渠道 / 用户 ID 筛选、平台列、排序与任务 ID 复制。
+2 -2
View File
@@ -1,6 +1,6 @@
# 用户中心 UI 规范(/user-center/\*)
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v2.4
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-25 · 版本:v2.5
个人登录后用户中心页面的规范,只记录与公共规范不同的部分;密钥管理、服务监控见各自规范。
@@ -78,7 +78,7 @@
- 页签:纯文字页签(公共列表页签样式),与下方 20px,URL `?tab=` 同步并懒挂载。
- 筛选卡:5 列栅格,时间范围跨 2 列;背景使用 `--surface-card` 纯色(浅色为白色、深色为主题卡片色);操作“重置 / 搜索”右下。
- 列表卡:标题 15px / 600,导出、列设置位于卡头右侧;表头字重 400(公共标准为 500,待收敛)。
- 消费记录调用明细为固定列宽宽表,时间分两行(日期 11px、时间 15px / 600),操作列文字“查看”,固定在右侧;横向滚动条保留 Ant Design 官方固定列表格行为,固定列兼容规则遵循公共规范第 5.2 节。
- 消费记录调用明细为固定列宽宽表,横向滚动时“时间”列固定在左侧,“操作”列显示时固定在右侧,中间列可滚动。时间分两行(日期 11px、时间 15px / 600),固定列兼容规则遵循公共规范第 5.2 节。
- 消费记录“用时 / 首字”列宽 190px,总用时、首字耗时与流式状态分别用 antd 默认带描边 `Tag` 展示,保留主题算法生成的浅底 / 文字 / 边框。总用时对 `use_time` 取整数秒,`<101s` 用 `green`、`101–299s` 用 `gold`、`≥300s` 用 `magenta`;首字耗时取 `other.frt / 1000`,先保留一位小数再判色,`<3s` 用 `cyan`、`3–<10s` 用 `orange`、`≥10s` 用 `red`。流式显示三枚标签(状态为蓝色“流”),非流式仅显示总用时与中性“非流”;零值正常展示,缺失、非数值或负耗时显示中性破折号。
- 绘图与视频:三张统计卡(高 70px、间距 15px)+ 任务记录表。
- Webhook 示例为 `<pre class='ui-notify-code'>` +“复制”链接,复制提示沿用原文案。
@@ -0,0 +1,407 @@
# 权限重构 · 产品功能验收与切换手册
| 项 | 内容 |
| --- | --- |
| 对应需求 | 《MaaS平台用户菜单权限重构PRD-V1.2》(本目录 `V1.2/`) |
| 对应版本 | `weiyuan` 分支 `801eda5ff` 及之后 |
| 适用对象 | 产品验收、测试、运维(迁移命令、切换与回滚由运维执行) |
| 更新日期 | 2026-11-30(移除 E2 登录名回填、T 两步验证验收项;2026-11-24 已逐条对照代码核对) |
---
## 怎么用这份手册
验收和切换分五个阶段,**必须按顺序做,上一阶段全部通过再进入下一阶段**。每一项做完在「结果」列填 ✅ / ❌,❌ 的在「备注」写清现象并截图。
| 阶段 | 做什么 | 会不会改变线上权限 | 谁来做 |
| --- | --- | --- | --- |
| 一 | 升级后验收:确认原有功能没坏、新页面能用 | 不会 | 产品 / 测试 |
| 二 | 生成迁移角色,打开影子对比,观察新旧权限判断有没有差异 | 不会(只记录) | 产品 + 运维 |
| 三 | 选一家**内部测试企业**切到新权限体系,完整验收 | 只影响测试企业 | 产品 / 测试,运维配合 |
| 四 | 平台侧(控制台)分批切换 | 影响平台管理员 | 产品 + 运维 |
| 五 | 客户企业分批切换 | 影响客户企业 | 产品 + 运维 + 客户成功 |
**四个基本事实,验收时请记住:**
1. **升级后默认是「旧模式」**:所有权限判断和升级前一样。新的权限管理页面能打开,但在某个模块或企业被切换之前,配置不会影响实际权限。
2. **迁移角色不会随升级自动生成**:「平台管理员(迁移)」「管理员(迁移)」等角色和迁移套餐,要运维执行一次迁移对账命令(第二章 2.1)才会出现;不执行的话,切换企业时也会自动生成。
3. **新权限变化以「重新登录」生效**:已切换的模块或企业里,某人的权限一旦变化,他的页面会在 1 分钟内(或切回窗口时)弹出「权限已变更 · 你的权限已变更,请重新登录。」,点「重新登录」后看到新菜单。下文写「重新登录后」即指这一步。
4. **切换可以撤回**:把企业从切换名单里移除(或把平台模块移除),立即恢复旧逻辑。**移除之前**运维要先跑投影命令(第六章),顺序反了命令会报错。
---
## 0. 准备工作
### 0.1 环境
- [ ] 已按《01-常规升级操作卡》完成升级,`verify` 五项自动检查全绿(另有 4 项人工检查按操作卡执行)。
- [ ] 浏览器使用 Chrome 最新版,验收前 `Ctrl+F5` 强制刷新。
- [ ] 下文地址都是相对站点域名,例如 `https://<域名>/console/authz/menus`。
- [ ] 第三阶段建议在**预发环境**做;3.7.4 等全局配置项在生产上会影响所有已切换企业。
### 0.2 验收账号
至少准备以下账号(企业侧账号都建在一家**内部测试企业**里,不要用客户企业):
| 代号 | 身份 | 用途 |
| --- | --- | --- |
| R | 平台超级管理员(root) | 权限管理、代理进入企业、运行模式。**权限管理菜单只有 root 能看到** |
| A | 平台管理员(非 root) | 验证平台侧权限 |
| U | 普通个人用户 | 验证个人功能、模型调用、平台自定义角色 |
| O | 测试企业所有者 | 企业侧最高权限 |
| M | 测试企业管理员 | 迁移来的「管理员(迁移)」 |
| D | 测试企业部门负责人(某部门的负责人) | 「我管辖的部门」 |
| E | 测试企业普通员工(企业创建的托管账号),工号已填 | 企业登录、首登改密、角色授权 |
测试企业里准备至少两个一级部门(例如「研发部」「销售部」),研发部下再建一个二级部门(例如「研发一组」)。E 放在研发部,研发部、研发一组、销售部各至少再有 1 名员工。
---
## 一、阶段一:升级后验收(旧模式)
目标:原有功能不受影响,新增入口能正常打开。**本阶段不要修改任何角色、套餐、运行模式。**
### 1.1 原有功能回归(必做)
| 编号 | 账号 | 入口 | 操作 | 期望结果 | 结果 | 备注 |
| --- | --- | --- | --- | --- | --- | --- |
| 1.1.1 | U | 个人登录 `/login` | 登录,调用一次模型(操练场或 API) | 正常返回、正常扣费;「使用日志」里有记录 | | |
| 1.1.2 | U | 个人中心 | 修改一次密码,退出用新密码登录 | 改密成功、新密码可登录 | | |
| 1.1.3 | A | 控制台 | 打开平时使用的页面(渠道、日志、用户等) | 能看到的菜单和升级前一致;**看不到**「权限管理」分组(只有 root 可见) | | |
| 1.1.4 | O | 企业登录 `/org/login` | 登录 | 进入企业中心 | | |
| 1.1.5 | O | 企业中心各菜单 | 依次打开「数据看板」「员工管理」「令牌管理」「部门管理」「预算中心」「项目管理」 | 列表正常显示,无报错 | | |
| 1.1.6 | M | 企业中心 | 登录并打开员工管理、令牌管理 | 能看到的菜单与升级前一致 | | |
| 1.1.7 | D | 企业中心 →「我管辖的部门」`/org/dept-manage` | 打开 | 能看到自己负责的部门及成员(只有部门负责人或部门管理员才有这个菜单) | | |
| 1.1.8 | E | 企业登录 | 登录,在「令牌管理」新建一个令牌并调用模型 | 正常 | | |
| 1.1.9 | O | 「令牌管理」 | 编辑任意令牌并保存 | 保存成功 | | |
### 1.2 平台侧新页面(账号 R)
| 编号 | 入口 | 操作 | 期望结果 | 结果 | 备注 |
| --- | --- | --- | --- | --- | --- |
| 1.2.1 | 控制台侧栏 | 查看是否有「权限管理」分组 | 有,下含「菜单管理」「平台角色」「功能套餐」「角色模板」「运行模式」 | | |
| 1.2.2 | 「菜单管理」`/console/authz/menus` | 打开,切换「平台」/「企业」两个页签,全部展开 | 两棵权限树完整,按钮挂在对应菜单下,每行有「显示」「启用」开关 | | |
| 1.2.3 | 「平台角色」`/console/authz/roles` | 打开 | 页面正常。**此时还没有迁移角色**(第二章 2.1 执行后才出现),列表为空或只有内置角色属正常 | | |
| 1.2.4 | 「功能套餐」`/console/authz/packages` | 打开 | 页面正常(同上,迁移套餐在 2.1 之后出现) | | |
| 1.2.5 | 「角色模板」`/console/authz/templates` | 打开 | 页面正常 | | |
| 1.2.6 | 「运行模式」`/console/authz/mode` | 打开 | 「平台侧」的「已切换模块」、「企业侧」的「已切换企业 ID」「已切换模块」均为空;两侧「影子对比」均为关闭 | | |
| 1.2.7 | 「企业管理」`/console/organizations` | 查看列表 | 新增「企业所有者」「功能套餐」「企业预警通知」列;没有套餐的企业显示「跟随默认套餐」 | | |
| 1.2.8 | 「企业管理」 | 点击测试企业名称 | 进入该企业的「数据看板」,顶部出现黄色提示条「超管代理模式:正在代理操作企业「…」,所有操作都会记录审计」 | | |
| 1.2.9 | 代理状态下 | 打开员工管理,然后点提示条上的「退出代理」 | 员工列表正常;退出后回到「企业管理」列表 | | |
| 1.2.10 | 「用户管理」`/console/user` | 编辑一个用户 | 「剩余额度」只读,提示调整请用列表操作列的「添加额度」 | | |
| 1.2.11 | 「用户管理」 | 对一个测试用户点操作列「添加额度」:先 +100,再 -100;再试填 0、填一个超过剩余额度的负数 | 额度先加后减回到原值;填 0 提示「调整额度不能为 0」;减成负数提示「调整后的剩余额度不能小于 0」 | | |
| 1.2.12 | 「用户管理」 | 查看操作列 | 有「分配角色」入口(超级管理员行没有);切换前分配不改变该用户的管理员身份 | | |
### 1.3 企业侧新页面与改动(账号 O)
| 编号 | 入口 | 操作 | 期望结果 | 结果 | 备注 |
| --- | --- | --- | --- | --- | --- |
| 1.3.1 | 企业中心侧栏 | 核对菜单名称 | 「令牌管理」(原密钥管理)、「部门管理」(原组织架构);O 若是某部门负责人,还有「我管辖的部门」。**「角色管理」切换前不显示**,地址栏输入 `/org/roles` 会被送走,属正常 | | |
| 1.3.2 | 「员工管理」`/org/members` | 打开 | 合并为一张表(不再分「员工权限 / 员工账号」页签),筛选项有「关键字」「分组」「组织」(部门)「状态」 | | |
| 1.3.3 | 「员工管理」 | 新建员工,姓名留空提交 | 提示「请输入姓名」 | | |
| 1.3.4 | 「员工管理」 | 新建员工,邮箱填 `abc` | 提示「邮箱格式不正确」 | | |
| 1.3.5 | 「员工管理」 | 新建员工,工号填 E 的工号 | 提示「工号在企业内已存在」(已停用、离职成员的工号不占用) | | |
| 1.3.6 | 「员工管理」 | 编辑员工资料,修改工号、备注 | 保存成功 | | |
| 1.3.7 | 「员工管理」→ CSV 导入 | 导入一个含:正常行、姓名为空行、邮箱格式错误行的 CSV(Excel 另存的带 BOM 文件也要试;上限 500 行、5MB) | 正常行成功并给出初始密码;错误行逐行显示原因 | | |
| 1.3.8 | 「令牌管理」 | 对一个令牌点查看 / 复制密钥 | 正常显示 | | |
| 1.3.9 | 「部门管理」`/org/departments` | 新建部门,负责人选一个本企业员工 | 保存成功 | | |
### 1.4 企业登录(账号 E)
| 编号 | 账号 | 操作 | 期望结果 | 结果 | 备注 |
| --- | --- | --- | --- | --- | --- |
| 1.4.1 | O | 在「员工管理」给 E 重置密码(只能重置托管账号),E 用初始密码从 `/org/login` 登录 | 登录后进入「首次登录,请修改初始密码」步骤;改密前企业功能不可用 | | |
| 1.4.2 | E | 改密后 | 正常进入企业中心 | | |
| 1.4.3 | — | 若系统开启了 Turnstile | 企业登录页显示人机验证,验证通过才能提交 | | |
| 1.4.4 | E | 从个人入口 `/login` 登录 | 切换前仍可登录,并被送到企业中心(切换后会被拒绝,见 3.3.1) | | |
**阶段一通过标准**:1.1 全部通过;1.2–1.4 无阻断性问题。
---
## 二、阶段二:生成迁移角色与影子对比
目标:在不改变实际权限的情况下,让系统同时按新旧两套规则判断,记录两者不一致的地方。**建议在预发环境运行至少一周**,生产也可以开启(只记录、不拦截)。
### 2.1 生成迁移角色(运维执行,先于影子对比)
影子对比按库里的新角色计算。不先生成迁移角色,管理员、部门负责人的每次操作都会被记成「缩权」,结果没有参考价值。
在部署目录(`.env` 所在目录)、用新版本程序、单实例执行:
```bash
# ① 预演:只出报告,不写库,报告文件 authz-migrate-report.md
SERVICE_MODE=authz-migrate ./monkey-ai
# ② 产品审阅报告无误后,正式生成(旧模式 / 影子模式下不改变现有权限;报告有"扩大"项时拒绝执行)
SERVICE_MODE=authz-migrate AUTHZ_MIGRATE_APPLY=1 ./monkey-ai
```
| 编号 | 检查项 | 期望结果 | 结果 | 备注 |
| --- | --- | --- | --- | --- |
| 2.1.1 | 产品审阅预演报告 | 「扩大」一节为空,其他各节与实际情况相符 | | |
| 2.1.2 | R 打开「平台角色」 | 出现「平台管理员(迁移)」,旧管理员都已绑定 | | |
| 2.1.3 | R 打开「功能套餐」 | 有一个默认套餐;按企业原有功能开关组合可能还有「套餐(迁移)1」「套餐(迁移)2」… | | |
| 2.1.4 | R 代理进入测试企业,查看员工的角色 | 各成员已绑定管理员(迁移)、部门管理员(迁移)、部门负责人(迁移)、员工(迁移)等角色 | | |
### 2.2 开启(账号 R,运行模式页)
1. 打开「权限管理」→「运行模式」`/console/authz/mode`。
2. 「平台侧」打开「影子对比」,保存。
3. 「企业侧」打开「影子对比」,保存。
只改影子对比开关不会弹确认框,保存即生效。
### 2.3 观察
运行期间让各类账号正常使用系统。每天在运行模式页下方的「影子差异」表查看:
- 可按「域」(平台 / 企业 / 代理)和时间(最近 1 / 6 / 24 / 72 / 168 小时)筛选;点击一行可展开看是哪些人。
- 「方向」一列:
- **扩权**:旧规则拒绝、新规则放行。**必须为 0,或逐条找到原因并确认可以接受。**
- **缩权**:旧规则放行、新规则拒绝。逐条确认原因(通常是迁移角色缺了某个权限点)。
- 迁移角色在切换前只由对账命令维护:观察期内如果调整过旧身份(设管理员、换部门负责人),判断差异前请运维重跑一次 2.1 第②步,否则这些人会出现误报。
| 编号 | 检查项 | 期望结果 | 结果 | 备注 |
| --- | --- | --- | --- | --- |
| 2.3.1 | 运行满 7 天 | 已运行 ___ 天 | | |
| 2.3.2 | 平台域「扩权」差异 | 0 条,或已逐条说明 | | |
| 2.3.3 | 企业域「扩权」差异 | 0 条,或已逐条说明 | | |
| 2.3.4 | 「缩权」差异 | 已逐条说明,需要补权限的已在菜单管理 / 角色中补齐 | | |
**阶段二通过标准**:2.1 完成;2.3.2、2.3.3 无未解释的扩权差异。
---
## 三、阶段三:内部测试企业切换(企业侧)
目标:在一家内部测试企业上完整走一遍「切换 → 验收 → 回退 → 再切换」。**只用内部测试企业,不要用客户企业。**
### 3.1 切换前
| 编号 | 检查项 | 结果 | 备注 |
| --- | --- | --- | --- |
| 3.1.1 | 已记下测试企业 ID:______ | | |
| 3.1.2 | 已通知测试企业所有成员:切换后**只能从企业登录入口 `/org/login` 登录**;个人账号加入的成员用原用户名、原密码登录 | | |
| 3.1.3 | 测试企业的所有者有效(所有者是在职成员);否则先在「企业管理 → 编辑 → 更换所有者」处理 | | |
### 3.2 执行切换(账号 R,运行模式页)
1. 「企业侧」的「已切换模块」选「全部(*)」(建议企业侧一次切全)。
2. 「已切换企业 ID」输入框填测试企业 ID(多个用逗号分隔),保存,在「确认切换权限运行模式」框点「确认」。
3. 系统会先做**切换前对账**。报告里有「扩大」或「登录」项时,弹出「切换前对账未通过」:
- 顶部是各类条数(扩大 / 登录 / 冲突 / 缩小 / 未知),下面是完整报告;
- **扩大**:切换后谁会多出哪些权限;
- **登录**:切换后无法用密码从企业入口登录的成员(登录名已被他人占用、保留名、没有密码、成员的企业登录被关闭);
- **未知**:需要人工确认的情况(企业没有有效所有者、旧管理员可查看令牌密钥、未切换期间新建的普通角色);
- 企业原本没开「企业登录」的,对账会自动打开,在报告摘要里列出;
- 全部确认可以接受后,点「已逐条确认,继续切换」。没有扩大和登录项时不弹框,直接切换。
4. 切换立即生效。
| 编号 | 检查项 | 期望结果 | 结果 | 备注 |
| --- | --- | --- | --- | --- |
| 3.2.1 | 对账报告 | 内容与测试企业实际情况相符;记录扩大 ___ 条、登录 ___ 条 | | |
| 3.2.2 | 保存后刷新运行模式页 | 测试企业 ID 出现在「已切换企业 ID」中 | | |
### 3.3 登录与入口
| 编号 | 账号 | 操作 | 期望结果 | 结果 | 备注 |
| --- | --- | --- | --- | --- | --- |
| 3.3.1 | E | 从个人入口 `/login` 登录 | 被拒绝,提示「该账号为企业账号,请从企业登录入口登录」 | | |
| 3.3.2 | E | 从企业入口登录后,地址栏输入 `/console/token` | 被送回企业中心 `/org` | | |
| 3.3.3 | O、M、D、E | 分别从企业入口登录,查看侧栏菜单 | 各自能看到的菜单与切换前一致(迁移角色保证不变);O 新出现「角色管理」 | | |
| 3.3.4 | R | 「企业管理」点击测试企业名称,代理进入后修改一名员工的备注 | 代理进入,顶部有代理提示条;企业中心「审计日志」里能查到这次修改(进入 / 退出代理本身记在平台审计表,页面上不显示) | | |
### 3.4 角色管理(账号 O,`/org/roles`)
权限点名称以授权树为准,下文用到的:员工管理 →「查询」「编辑资料、模型限制与备注」「重置密码」;令牌管理 →「查询」「创建令牌」「编辑与启停」「删除」「查看与复制密钥」;消耗明细 →「查询」。
| 编号 | 操作 | 期望结果 | 结果 | 备注 |
| --- | --- | --- | --- | --- |
| 3.4.1 | 「新建角色」:名称「测试-只读」,数据范围「本部门及以下」,「菜单与按钮权限」只勾「员工管理 → 查询」 | 创建成功 | | |
| 3.4.2 | 行操作「分配员工」:把 E 分配到「测试-只读」 | 保存成功,成员数 +1 | | |
| 3.4.3 | E 等待「权限已变更」提示后重新登录 | 侧栏出现「员工管理」,只能看到研发部和研发一组的员工;没有新建、编辑等按钮 | | |
| 3.4.4 | 编辑「测试-只读」,再勾上「员工管理 → 编辑资料、模型限制与备注」 | E 重新登录后出现编辑按钮,能编辑本部门员工 | | |
| 3.4.5 | E 尝试编辑销售部员工(直接改地址或调接口) | 被拒绝 | | |
| 3.4.6 | 把「测试-只读」数据范围改为「仅本人」 | E 重新登录后员工列表只剩自己 | | |
| 3.4.7 | 在「状态」列尝试停用该角色(E 仍在角色中) | 被拒绝,提示「该角色仍分配给 1 个成员,请先移除后再停用/删除」 | | |
| 3.4.8 | 「分配员工」里移除 E,然后停用、再删除该角色 | E 重新登录后失去员工管理菜单;停用、删除均成功 | | |
| 3.4.9 | 授权树:勾选一个菜单 | 其下按钮全部勾上(父子联动);只勾部分按钮时菜单显示半选 | | |
| 3.4.10 | 新建一个只含「令牌管理 → 查询」的角色,点「设为默认」;在员工管理新建一个员工 | 提示「新建员工将自动分配该角色,已有员工角色保持不变。」;新员工自动获得该角色。**测完把默认改回原默认角色**(默认角色不能停用或删除) | | |
| 3.4.11 | 尝试给企业所有者分配角色 | 被拒绝,提示「不能对企业所有者执行该操作,所有者变更请走所有者移交」 | | |
| 3.4.12 | 编辑「管理员(迁移)」,移除「令牌管理 → 查看与复制密钥」 | 保存成功(切换后迁移角色可以修改);M 重新登录后看不到查看 / 复制密钥按钮,直接调接口也被拒 | | |
### 3.5 数据范围(六类)
给 E 绑定一个角色(授权含员工管理查询、令牌管理查询、消耗明细查询),依次把数据范围改成下表各项,E 每次重新登录后核对员工列表、令牌列表、消耗明细:
| 编号 | 数据范围 | E 所在部门 | 期望能看到 | 结果 | 备注 |
| --- | --- | --- | --- | --- | --- |
| 3.5.1 | 全部数据 | 研发部 | 全企业 | | |
| 3.5.2 | 本部门 | 研发部 | 只有研发部,**不含**研发一组 | | |
| 3.5.3 | 本部门及以下 | 研发部 | 研发部 + 研发一组 | | |
| 3.5.4 | 本部门及以下或本人 | 研发部 | 研发部 + 研发一组 + 本人 | | |
| 3.5.5 | 自定义部门(关闭「父子联动」,只勾销售部) | 研发部 | 只有销售部 | | |
| 3.5.6 | 仅本人 | 研发部 | 只有自己 | | |
### 3.6 员工管理与令牌(新体系下)
| 编号 | 账号 | 操作 | 期望结果 | 结果 | 备注 |
| --- | --- | --- | --- | --- | --- |
| 3.6.1 | O → M | 承接 3.4.12(M 已没有「查看与复制密钥」):给 E 的角色勾上「令牌管理 → 查看与复制密钥」,M 重新登录后给 E 重置密码 | 被拒绝,提示「该账号的权限超出你的权限范围,不能操作」 | | |
| 3.6.2 | M、R(代理) | 分别尝试修改所有者 O 的邮箱 | 都被拒绝,提示「不能对企业所有者执行该操作…」;切换后所有者邮箱只能本人改 | | |
| 3.6.3 | 持「令牌管理 → 查询 + 创建令牌」但无「编辑与启停 / 删除 / 查看与复制密钥」的员工 | 查看自己令牌的操作 | 不显示编辑、删除、查看 / 复制密钥;启停开关为灰色不可点 | | |
| 3.6.4 | 持「查看与复制密钥」的员工 | 1 分钟内反复「隐藏 → 显示」令牌密钥超过 20 次 | 第 21 次提示「查看密钥过于频繁,请稍后再试」。**本地测试环境关闭了限流,此项须在预发验证** | | |
| 3.6.5 | O | 停用一个部门 | 提示「停用后,该部门 N 名直属成员将被一并停用,其 API 令牌将被禁用;下级部门不受影响。」;确认后这些成员被停用、令牌被禁用(所有者不受影响) | | |
| 3.6.6 | O | 重新启用该部门 | 直属成员全部恢复(含此前被单独停用的);**令牌不会自动启用**,需手动启用;若某成员工号已被其他在职员工占用,该成员保持停用(审计日志里有记录) | | |
### 3.7 平台对已切换企业的管理(账号 R)
| 编号 | 入口 | 操作 | 期望结果 | 结果 | 备注 |
| --- | --- | --- | --- | --- | --- |
| 3.7.1 | 「企业管理」→ 功能套餐 | 给测试企业换一个套餐(先在「功能套餐」新建一个去掉「项目管理」的套餐) | 企业中心不再显示项目管理;角色授权树里也不再出现该菜单 | | |
| 3.7.2 | 同上 | 把套餐改回原套餐 | 菜单恢复;之前已有的授权自动恢复 | | |
| 3.7.3 | 「企业管理」→ 编辑 →「更换所有者」 | 把所有者换成 M | 新所有者获得全部权限;原所有者降为成员,保留原有普通角色并追加默认员工角色(未切换企业的原所有者则降为管理员) | | |
| 3.7.4 | 「菜单管理」→「企业」页签 | 把「数据看板」的「显示」关掉,验证后再打开 | 关掉后测试企业成员侧栏不显示数据看板、直接访问也被送走;打开后恢复。**这是全局设置,会影响所有已切换企业,生产上不要做** | | |
### 3.8 回退演练
| 编号 | 操作 | 期望结果 | 结果 | 备注 |
| --- | --- | --- | --- | --- |
| 3.8.1 | 运维执行投影命令并生成负责人报告(见第六章 6.2 第 1 步)。**必须在移出名单之前执行**;顺序反了命令会报错退出并列出已不在名单中的企业 | 生成报告文件 | | |
| 3.8.2 | 产品审阅报告中的两份名单:①回退后会获得部门管理权限的人、②回退后会失去部门管理权限的人 | 已逐一确认 | | |
| 3.8.3 | 运行模式页:从「已切换企业 ID」删掉测试企业,保存 | 立即生效 | | |
| 3.8.4 | O、M、D、E 各登录一次 | 菜单与切换前一致 | | |
| 3.8.5 | 再次把测试企业加入名单 | 对账报告把 3.4.12 撤掉的权限列为扩大项(「迁移角色「管理员(迁移)」将被对账校正为旧体系推导结果:…」),确认后切换成功;3.4 新建的普通角色若还在会重新生效 | | |
**阶段三通过标准**:3.2–3.8 全部通过,或不通过项已有结论并经产品确认。
---
## 四、阶段四:平台侧切换(控制台)
平台侧按三批切换,每批切换后用账号 A 和一名自定义角色用户验收。「已切换模块」下拉框里显示的是模块代号,对照如下:
| 批次 | 模块代号(菜单名) |
| --- | --- |
| P1a | `authz.menu`(菜单管理)、`authz.role`(平台角色)、`authz.package`(功能套餐)、`authz.template`(角色模板)、`user`(用户管理)、`redemption`(兑换码管理)、`admin_token`(秘钥管理)、`org`(企业管理) |
| P1b | `channel`(渠道管理)、`model`(模型管理)、`log`(使用日志)、`drawing_log`(绘图日志)、`task_log`(任务日志)、`monitor`(监控中心)、`topup`(充值记录)、`analytics`(运营看板)、`subscription`(会员卡管理)、`skill`(平台 Skill 中心)、`expert`(平台专家中心)、`router`(智能路由)、`order`(订单管理)、`invoice`(发票管理)、`commission`(分佣管理) |
| P1c | `setting`(系统设置) |
### 4.1 每批的操作(账号 R,运行模式页)
1. 「平台侧」的「已切换模块」**在原有基础上**加选本批模块,保存,在「确认切换权限运行模式」框点「确认」。
2. 平台侧第一次切换时会做对账;有扩大项时弹出「切换前对账未通过」,逐条确认后继续。
3. 运行模式只由一人修改,避免多人同时操作。
### 4.2 每批的验收
| 编号 | 账号 | 操作 | 期望结果 | 结果 | 备注 |
| --- | --- | --- | --- | --- | --- |
| 4.2.1 | A | 完成本批模块的日常操作 | 全部可用(A 已绑定「平台管理员(迁移)」) | | |
| 4.2.2 | R | 在「平台角色」新建角色,只授权本批某个页面的「查询」(选有「查询」按钮的页面,如用户管理、兑换码管理、渠道管理),分配给 U | U 重新登录后能进入该页面查看,不能修改 | | |
| 4.2.3 | U | 尝试该页面的修改操作 | 被拒绝 | | |
| 4.2.4 | R | 第一批起:在「平台角色」给 U 分配「平台管理员(迁移)」,再移除 | 分配后 U 成为管理员;移除后恢复普通用户 | | |
| 4.2.5 | R | P1a 起:查看用户管理操作列 | 不再出现「提升」「降级」,改用「分配角色」 | | |
| 4.2.6 | A | P1a 起:对一名在企业里是所有者、管理员或部门管理员的用户改密、停用 | 被拒绝,提示「该账号的权限超出你的权限范围,不能操作」(只能由 root 处理) | | |
**阶段四通过标准**:每批 4.2 全部通过后再切下一批。
---
## 五、阶段五:客户企业分批切换
### 5.1 每批切换前
| 编号 | 检查项 | 结果 | 备注 |
| --- | --- | --- | --- |
| 5.1.1 | 本批企业 ID 已确定,**每批新增不超过 50 家**(系统硬限制,超过会提示「一次最多新切换 50 家企业…」) | | |
| 5.1.2 | 已提前通知本批企业(建议至少提前 3 个工作日,通知要点见 5.3) | | |
| 5.1.3 | 用预演命令看过本批企业的报告(运维:`SERVICE_MODE=authz-migrate AUTHZ_MIGRATE_SCOPE=org AUTHZ_MIGRATE_ORG_IDS=<本批ID> ./monkey-ai`),「未知」里没有有效所有者的企业已先更换所有者 | | |
| 5.1.4 | 选在业务低峰执行 | | |
### 5.2 执行与观察
1. 运行模式页:在「已切换企业 ID」**追加**本批企业 ID(保留已切换的,逗号分隔),保存并确认。
2. 逐条阅读对账报告,重点看「登录」(无法从企业入口登录的成员,逐人处理或确认)、「未知」(普通角色会直接生效、旧管理员的令牌密钥权限),确认后继续。
3. 切换后抽查本批 3–5 家企业:所有者、管理员各登录一次,核对菜单。
4. 观察 1–2 天,收集客户反馈的登录失败、页面无权限问题,无异常再切下一批。
5. 全部企业切换完成后,「已切换企业 ID」改为 `*`。此后新建的企业自动按新体系运行(自动建好迁移角色、默认员工角色并打开企业登录)。
6. 运维执行一次存量消耗日志的部门回填:`SERVICE_MODE=authz-migrate AUTHZ_BACKFILL_LOG_DEPT=1 ./monkey-ai`(可中断、可重入)。
| 批次 | 企业数 | 切换时间 | 对账扩大 / 登录条数 | 抽查结果 | 执行人 |
| --- | --- | --- | --- | --- | --- |
| 第 1 批 | | | | | |
| 第 2 批 | | | | | |
| 第 3 批 | | | | | |
### 5.3 给企业客户的通知要点
- 切换后**只能从企业登录入口**登录,个人登录后切换企业的方式不再可用;已用个人账号登录的成员需要退出,改从企业入口重新登录。
- 企业创建的员工账号不能再从个人登录入口登录。
- 以个人账号加入企业的成员:用**原个人用户名和原密码**在企业登录入口登录。
- 从企业入口登录后只能使用企业功能;个人令牌、个人日志、充值与会员、发票、邀请、操练场与体验中心、伙伴门户等请从个人登录入口登录。本身是企业成员的合作伙伴,伙伴门户须从个人入口登录。
- 原「调整角色」「设置管理员权限」改为在「角色管理」页分配角色。
- 切换时在线的用户:权限有变化的会提示重新登录,没变化的刷新页面即可。
- 被重置过密码或首次登录的员工,要先修改初始密码才能使用企业功能。
---
## 六、回退
### 6.1 什么情况下回退
- 切换后出现大面积无法登录、无法使用核心功能,且无法在当天逐个处理;
- 发现扩权问题(有人能看到或操作不该看到的数据)。
### 6.2 企业侧回退(运维执行)
1. **先**生成投影与负责人报告(`12,15` 换成要回退的企业 ID;在部署目录、用新版本程序、单实例执行):
```bash
SERVICE_MODE=authz-migrate AUTHZ_PROJECT=1 AUTHZ_MIGRATE_SCOPE=org AUTHZ_MIGRATE_ORG_IDS=12,15 \
AUTHZ_MIGRATE_REPORT=rollback-12-15.md ./monkey-ai
```
2. 产品审阅报告中的两份名单并与企业确认。
3. **再**到运行模式页从「已切换企业 ID」删掉这些企业,保存,立即生效。
注意:
- 回退后在「角色管理」里新建的普通角色不再生效,只保留迁移角色对应的旧身份;这些角色和分配**不会被删除**,再次切换时重新生效。
- 再次切换时,切换后在迁移角色上撤掉的权限会被恢复(对账列为扩大项)。
- 切换后被分配了自定义范围「部门管理员(迁移)」、而主部门不在该范围内的成员,回退后会多出主部门的管理权,回退前人工核对。
### 6.3 平台侧回退(运维执行)
1. **先**生成投影:
```bash
SERVICE_MODE=authz-migrate AUTHZ_PROJECT=1 AUTHZ_MIGRATE_SCOPE=platform ./monkey-ai
```
2. **再**到运行模式页从平台侧「已切换模块」去掉要回退的模块,保存,立即生效。只回退部分模块时,自定义平台角色在其余已切换模块上仍然有效。
### 6.4 紧急兜底
新版本的路由兜底拦截出现误拦时,运维可临时设 `AUTHZ_GATE_MODE=log` 重启,退回只记录不拦截。
详细说明见代码仓库 `docs/01-部署运维/24-权限体系分批切换上线与回滚操作卡.md`。
---
## 七、问题记录
| 编号 | 对应验收项 | 现象 | 账号 | 截图 / 接口返回 | 严重程度 | 处理结论 |
| --- | --- | --- | --- | --- | --- | --- |
| | | | | | | |
反馈问题时请附:页面截图、浏览器开发者工具(F12 → Network)中出错接口的请求地址和返回内容、操作账号。
---
## 八、验收签字
| 阶段 | 结论(通过 / 有条件通过 / 不通过) | 验收人 | 日期 |
| --- | --- | --- | --- |
| 一、升级后验收 | | | |
| 二、迁移角色与影子对比 | | | |
| 三、测试企业切换 | | | |
| 四、平台侧切换 P1a | | | |
| 四、平台侧切换 P1b | | | |
| 四、平台侧切换 P1c | | | |
| 五、客户企业切换完成 | | | |
+153 -100
View File
@@ -5,12 +5,9 @@ import {
isMiniProgramWebView,
} from './helpers/miniProgram';
import Loading from './components/common/ui/Loading';
import {
AuthRedirect,
PrivateRoute,
AdminRoute,
RootRoute,
} from './helpers/auth';
import { CenterRouteLoading } from './components/layout/components/CenterSidebarLoading';
import { AuthRedirect, PrivateRoute, RootRoute } from './helpers/auth';
import { PermRoute, ConsoleRoute, ConsoleIndexRoute } from './authz';
import NotFound from './pages/NotFound';
import Forbidden from './pages/Forbidden';
import { StatusContext } from './context/Status';
@@ -74,14 +71,19 @@ const Task = lazy(() => import('./pages/Task'));
const ModelPage = lazy(() => import('./pages/Model'));
const Playground = lazy(() => import('./pages/Playground'));
const MonitorCenter = lazy(() => import('./pages/MonitorCenter'));
const PersonalSetting = lazy(
() => import('./components/settings/PersonalSetting'),
);
const Setup = lazy(() => import('./pages/Setup'));
const Analytics = lazy(() => import('./pages/Analytics'));
const SmartRouter = lazy(() => import('./pages/SmartRouter'));
const Organization = lazy(() => import('./pages/Organization'));
const AdminOrganizations = lazy(() => import('./pages/AdminOrganizations'));
// 平台侧权限管理(菜单管理 / 平台角色 / 功能套餐 / 角色模板 / 运行模式)
const AuthzMenuManage = lazy(() => import('./pages/Permission/MenuManage'));
const AuthzPlatformRoles = lazy(
() => import('./pages/Permission/PlatformRoles'),
);
const AuthzPackages = lazy(() => import('./pages/Permission/Packages'));
const AuthzTemplates = lazy(() => import('./pages/Permission/Templates'));
const AuthzRunMode = lazy(() => import('./pages/Permission/RunMode'));
const AdminOrder = lazy(() => import('./pages/AdminOrder'));
const AdminInvoice = lazy(() => import('./pages/AdminInvoice'));
const Subscription = lazy(() => import('./pages/Subscription'));
@@ -135,20 +137,10 @@ 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
/>
);
// 用户中心旧地址保留登录回跳、分享链接及书签中的参数。
const UserCenterLegacyRedirect = ({ to }) => {
const { search, hash } = useLocation();
return <Navigate to={{ pathname: to, search, hash }} replace />;
};
function App() {
@@ -280,51 +272,51 @@ function App() {
<Route
path='/console/models'
element={
<AdminRoute>
<ConsoleRoute code='platform.model'>
<Suspense fallback={<Loading />}>
<ModelPage />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
path='/console/channel'
element={
<AdminRoute>
<ConsoleRoute code='platform.channel'>
<Suspense fallback={<Loading />}>
<Channel />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
path='/console/token'
element={
<AdminRoute>
<ConsoleRoute code='platform.admin_token'>
<Suspense fallback={<Loading />}>
<Token />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
path='/console/playground'
element={
<AdminRoute>
<ConsoleRoute code='platform.playground'>
<Suspense fallback={<Loading />}>
<Playground />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
path='/console/monitor'
element={
<AdminRoute>
<ConsoleRoute code='platform.monitor'>
<Suspense fallback={<Loading />}>
<MonitorCenter />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
@@ -340,11 +332,11 @@ function App() {
<Route
path='/console/analytics'
element={
<AdminRoute>
<ConsoleRoute code='platform.analytics'>
<Suspense fallback={<Loading />}>
<Analytics />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
@@ -371,40 +363,91 @@ function App() {
/* 分佣管理为 Root 专属:侧边栏一直用 isRoot() 隐藏该入口,后端结算/销售/成本/
伙伴管理各路由组也已全部 Root 收口。这里把路由守卫对齐,避免 role=10 直接
输 URL 进到一个读得到、写按钮全 403 的半残页面。 */
<RootRoute>
<ConsoleRoute code='platform.commission' legacy='root'>
<Suspense fallback={<Loading />}>
<CommissionV2 />
</Suspense>
</RootRoute>
</ConsoleRoute>
}
/>
<Route
path='/console/experience-center-audit'
element={
<AdminRoute>
<ConsoleRoute code='platform.analytics'>
<Navigate to='/console/analytics?tab=audit' replace />
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
path='/console/organizations'
element={
<AdminRoute>
<ConsoleRoute code='platform.org'>
<Suspense fallback={<Loading />}>
<AdminOrganizations />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
{/* 平台侧权限管理:路由按与侧边栏相同的权限点守卫(PermRoute),接口权限由后端校验;运行模式仅 root */}
<Route
path='/console/authz/menus'
element={
<PermRoute code='platform.authz.menu.query'>
<Suspense fallback={<Loading />}>
<AuthzMenuManage />
</Suspense>
</PermRoute>
}
/>
<Route
path='/console/authz/roles'
element={
<PermRoute code='platform.authz.role.query'>
<Suspense fallback={<Loading />}>
<AuthzPlatformRoles />
</Suspense>
</PermRoute>
}
/>
<Route
path='/console/authz/packages'
element={
<PermRoute code='platform.authz.package.query'>
<Suspense fallback={<Loading />}>
<AuthzPackages />
</Suspense>
</PermRoute>
}
/>
<Route
path='/console/authz/templates'
element={
<PermRoute code='platform.authz.template.query'>
<Suspense fallback={<Loading />}>
<AuthzTemplates />
</Suspense>
</PermRoute>
}
/>
<Route
path='/console/authz/mode'
element={
<RootRoute>
<Suspense fallback={<Loading />}>
<AuthzRunMode />
</Suspense>
</RootRoute>
}
/>
<Route
path='/console/skill-platform'
element={
CLOUD_BRAIN_UI_ENABLED ? (
<AdminRoute>
<ConsoleRoute code='platform.skill'>
<Suspense fallback={<Loading />}>
<SkillPlatform />
</Suspense>
</AdminRoute>
</ConsoleRoute>
) : (
<Navigate to='/console' replace />
)
@@ -414,11 +457,11 @@ function App() {
path='/console/expert-platform'
element={
CLOUD_BRAIN_UI_ENABLED ? (
<AdminRoute>
<ConsoleRoute code='platform.expert'>
<Suspense fallback={<Loading />}>
<ExpertPlatform />
</Suspense>
</AdminRoute>
</ConsoleRoute>
) : (
<Navigate to='/console' replace />
)
@@ -427,21 +470,21 @@ function App() {
<Route
path='/console/order'
element={
<AdminRoute>
<ConsoleRoute code='platform.order'>
<Suspense fallback={<Loading />}>
<AdminOrder />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
path='/console/invoice'
element={
<AdminRoute>
<ConsoleRoute code='platform.invoice'>
<Suspense fallback={<Loading />}>
<AdminInvoice />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
{/* 旧路由重定向到用户中心内的服务监控 */}
@@ -454,7 +497,9 @@ function App() {
element={
CLOUD_BRAIN_UI_ENABLED ? (
<PrivateRoute>
<Suspense fallback={<Loading />} key={location.pathname}>
<Suspense
fallback={<CenterRouteLoading variant='experience' />}
>
<ExperienceCenter />
</Suspense>
</PrivateRoute>
@@ -469,14 +514,13 @@ function App() {
moduleAuthConfig.experienceCenter ? (
<PrivateRoute>
<Suspense
fallback={<Loading></Loading>}
key={location.pathname}
fallback={<CenterRouteLoading variant='experience' />}
>
<ExperienceCenter />
</Suspense>
</PrivateRoute>
) : (
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
<Suspense fallback={<CenterRouteLoading variant='experience' />}>
<ExperienceCenter />
</Suspense>
)
@@ -485,31 +529,31 @@ function App() {
<Route
path='/console/redemption'
element={
<AdminRoute>
<ConsoleRoute code='platform.redemption'>
<Suspense fallback={<Loading />}>
<Redemption />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
path='/console/user'
element={
<AdminRoute>
<ConsoleRoute code='platform.user'>
<Suspense fallback={<Loading />}>
<User />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
path='/console/subscription'
element={
<AdminRoute>
<ConsoleRoute code='platform.subscription'>
<Suspense fallback={<Loading />}>
<Subscription />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
@@ -631,89 +675,78 @@ function App() {
<Route
path='/console/setting'
element={
<AdminRoute>
<ConsoleRoute code='platform.setting'>
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
<Setting />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
path='/console/website-setting'
element={
<AdminRoute permission='website-setting'>
<ConsoleRoute
code='platform.setting.website_setting'
permission='website-setting'
>
<Suspense fallback={<Loading />}>
<WebsiteSettings />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
path='/console/demo-reservations'
element={
<AdminRoute permission='demo-reservations'>
<ConsoleRoute
code='platform.setting.demo_reservations'
permission='demo-reservations'
>
<Suspense fallback={<Loading />}>
<DemoReservations />
</Suspense>
</AdminRoute>
}
/>
<Route
path='/console/personal'
element={
<AdminRoute>
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
<PersonalSetting />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
path='/console/topup'
element={
<AdminRoute>
<ConsoleRoute code='platform.topup'>
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
<TopUp />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
path='/console/log'
element={
<AdminRoute>
<ConsoleRoute code='platform.log'>
<Suspense fallback={<Loading />}>
<Log />
</Suspense>
</AdminRoute>
}
/>
<Route
path='/console'
element={
<AdminRoute>
<Navigate to='/console/analytics' replace />
</AdminRoute>
</ConsoleRoute>
}
/>
<Route path='/console' element={<ConsoleIndexRoute />} />
<Route
path='/console/midjourney'
element={
<AdminRoute>
<ConsoleRoute code='platform.drawing_log'>
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
<Midjourney />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
path='/console/task'
element={
<AdminRoute>
<ConsoleRoute code='platform.task_log'>
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
<Task />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
<Route
@@ -759,10 +792,27 @@ function App() {
)
}
/>
{/* 密钥管理归入用户中心路径;旧地址保留为重定向(旧链接、登录回跳、书签) */}
<Route
path='/console/personal'
element={
<PrivateRoute>
<UserCenterLegacyRedirect to='/user-center/settings' />
</PrivateRoute>
}
/>
<Route
path='/user/center'
element={
<PrivateRoute>
<UserCenterLegacyRedirect to='/user-center' />
</PrivateRoute>
}
/>
<Route
path='/key-management'
element={<KeyManagementLegacyRedirect />}
element={
<UserCenterLegacyRedirect to='/user-center/key-management' />
}
/>
<Route
path='/user-center/key-management'
@@ -770,14 +820,17 @@ function App() {
moduleAuthConfig.keyManagement ? (
<PrivateRoute>
<Suspense
fallback={<Loading></Loading>}
fallback={<CenterRouteLoading />}
key={location.pathname}
>
<UserCenter keyManagementMode />
</Suspense>
</PrivateRoute>
) : (
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
<Suspense
fallback={<CenterRouteLoading />}
key={location.pathname}
>
<UserCenter keyManagementMode />
</Suspense>
)
@@ -788,12 +841,12 @@ function App() {
element={
moduleAuthConfig.userCenter ? (
<PrivateRoute>
<Suspense fallback={<Loading></Loading>}>
<Suspense fallback={<CenterRouteLoading />}>
<UserCenter />
</Suspense>
</PrivateRoute>
) : (
<Suspense fallback={<Loading></Loading>}>
<Suspense fallback={<CenterRouteLoading />}>
<UserCenter />
</Suspense>
)
@@ -865,11 +918,11 @@ function App() {
<Route
path='/console/chat/:id?'
element={
<AdminRoute>
<ConsoleRoute code='platform.chat'>
<Suspense fallback={<Loading></Loading>} key={location.pathname}>
<Chat />
</Suspense>
</AdminRoute>
</ConsoleRoute>
}
/>
{/* 方便使用chat2link直接跳转聊天... */}
@@ -897,7 +950,7 @@ function App() {
element={
<PrivateRoute>
{isOrgCenterAvailable ? (
<Suspense fallback={<Loading />}>
<Suspense fallback={<CenterRouteLoading variant='org' />}>
<Organization />
</Suspense>
) : (
Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

+393
View File
@@ -0,0 +1,393 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useLocation } from 'react-router-dom';
import { Modal } from 'antd';
import { useTranslation } from 'react-i18next';
import { API } from '../helpers/api';
import {
clearUserData,
isOrgLoginSession,
ORG_LOGIN_SESSION_KEY,
USER_STORAGE_KEY,
} from '../helpers/data';
import {
clearProxyExpired,
getCurrentOrgId,
getProxySession,
} from '../helpers/orgContext';
import { UserContext } from '../context/User';
import { normalizeView } from './permLogic';
// 权限上下文(权限重构 §9 GET /api/authz/me):同时持有平台视图与当前企业视图。
// 企业视图随当前企业(或代理会话)切换重新加载。有已切换模块、处于代理会话或上一次加载失败时,页面重新获得焦点
// (10 秒内不重复)、或每 60 秒刷新一次;否则(未切换,视图只用于判断是否已切换)每 10 分钟刷新一次、获得焦点时
// 2 分钟内不重复,不挤占按 IP 计数的全局限流,同时切换后用户切回窗口即可较快跟上。
// 当前视图的有效内容(权限点、菜单、数据范围)发生变化且涉及已切换模块时,按 Q12 要求重新登录。
export const AuthzContext = createContext({
platform: null,
org: null,
orgLoadedKey: null,
platformLoadedFor: 0,
platformLoadFailed: false,
reload: () => {},
});
const REFRESH_MS = 60 * 1000;
// 未切换时的刷新间隔
const IDLE_REFRESH_MS = 10 * 60 * 1000;
// 窗口 focus 触发刷新的节流间隔:频繁切换窗口时不重复拉取
const FOCUS_THROTTLE_MS = 10 * 1000;
// 未切换时 focus 触发刷新的节流间隔
const IDLE_FOCUS_THROTTLE_MS = 2 * 60 * 1000;
// 未登录(会话失效、其他标签页已登出):不算"加载失败",不因此转入高频刷新
const UNAUTHORIZED = Symbol('unauthorized');
// 拉取视图;接口 success:false 或网络错误返回 null(调用方按"加载失败"处理),401 返回 UNAUTHORIZED
const fetchView = async (headers) => {
try {
const res = await API.get('/api/authz/me', {
headers,
skipErrorHandler: true,
disableDuplicate: true,
});
return res.data?.success ? normalizeView(res.data.data) : null;
} catch (e) {
return e?.response?.status === 401 ? UNAUTHORIZED : null;
}
};
// 当前企业视图的标识(企业 ID + 代理会话):企业中心据此判断企业视图是否已按当前企业加载过
export const currentOrgViewKey = () =>
`${getCurrentOrgId()}:${getProxySession()?.id || ''}`;
const orgHeaders = () => {
const proxy = getProxySession();
const orgId = getCurrentOrgId();
if (!orgId) return null;
const h = { 'X-Org-Id': String(orgId) };
if (proxy) h['X-Proxy-Session'] = proxy.id;
return h;
};
// 视图有效内容的指纹:只取已切换模块(前后两次 enforced_modules 的并集)内的权限点、
// 菜单(code 与 visible)与数据范围类型(全部 / 部门 / 本人);未切换模块的变化不影响页面行为,不纳入。
// 部门个数不纳入:它是按部门树展开后的个数,新增子部门就会变化,而页面行为不变。
// 已切换模块列表本身不纳入:模块切换(或回退)只是把页面从旧判断改为按权限点判断,界面就地更新,
// 不属于 Q12 所说的撤权,不要求重新登录;切换前后权限点本身的变化仍会按上面的并集比较提示。
// 不用 version:它包含目录与企业版本,改任意菜单名、角色名都会变化,会误弹重新登录。
const viewSignature = (v, inScope) =>
JSON.stringify([
(v.perms || []).filter(inScope).sort(),
(v.menus || [])
.filter((m) => inScope(m.code))
.map((m) => `${m.code}:${m.visible ? 1 : 0}`)
.sort(),
Object.entries(v.scopes || {})
.filter(([code]) => inScope(code))
.map(
([code, sc]) =>
`${code}:${sc?.all ? 1 : 0}:${sc?.depts ? 1 : 0}:${sc?.self ? 1 : 0}`,
)
.sort(),
]);
// 有效内容变化且涉及已切换模块:权限确实影响到页面行为,需要重新登录
const changedUnderEnforce = (prev, next) => {
if (!prev || !next) return false;
// 用户、企业或登录域不同都是换了会话(如个人会话改用企业入口登录),不是权限变更
if (
prev.user_id !== next.user_id ||
prev.org_id !== next.org_id ||
prev.domain !== next.domain ||
(prev.session_domain || '') !== (next.session_domain || '')
) {
return false;
}
const modules = new Set([
...(prev.enforced_modules || []),
...(next.enforced_modules || []),
]);
if (modules.size === 0) return false;
const moduleOf = { ...(prev.module_of || {}), ...(next.module_of || {}) };
const inScope = (code) => modules.has(moduleOf[code]);
return viewSignature(prev, inScope) !== viewSignature(next, inScope);
};
// 视图是否涉及已切换模块(需要高频刷新以及时发现权限变更;代理会话另由调用方判断)
const isActiveView = (v) => !!v && (v.enforced_modules || []).length > 0;
// 内容相同的视图不重新写入状态,避免每次刷新都让订阅方(企业中心等)重渲染
const sameView = (a, b) => {
if (a === b) return true;
if (!a || !b) return false;
try {
return JSON.stringify(a) === JSON.stringify(b);
} catch {
return false;
}
};
export const AuthzProvider = ({ children }) => {
const { t } = useTranslation();
const [userState, userDispatch] = useContext(UserContext);
const userId = userState?.user?.id || 0;
const location = useLocation();
const [platform, setPlatform] = useState(null);
const [org, setOrg] = useState(null);
// 最近一次企业视图加载(无论成败)对应的 currentOrgViewKey;未加载过为 null
const [orgLoadedKey, setOrgLoadedKey] = useState(null);
// 平台视图已为哪个用户加载过(成败均算);路由守卫据此等待视图到达,避免先按旧判断误拦
const [platformLoadedFor, setPlatformLoadedFor] = useState(0);
// 最近一次平台视图加载是否失败(配合 platformLoadedFor 使用):路由守卫据此显示可重试提示
const [platformLoadFailed, setPlatformLoadFailed] = useState(false);
const prevRef = useRef({ platform: null, org: null });
const promptedRef = useRef(false);
// 已弹出的"权限已变更"提示实例:其他标签页换了会话时关闭它
const modalRef = useRef(null);
// 最近一次开始拉取视图的时间,用于 focus 刷新节流
const lastFetchRef = useRef(0);
// 最近一次加载是否有视图失败:失败后按高频刷新重试,否则已切换企业首次加载失败时会按旧判断渲染最长 10 分钟
const failedRef = useRef(false);
// 最新的 reload:storage 事件处理里主动重新加载(事件处理只注册一次)
const reloadRef = useRef(null);
// 企业会话(企业域登录、或仅企业资源账号)重新登录回 /org/login,否则回 /login
const orgOnlyRef = useRef(false);
orgOnlyRef.current = userState?.user?.org_only_mode === true;
const onOrgPage = location.pathname.startsWith('/org');
const orgKey = onOrgPage ? currentOrgViewKey() : '';
const promptRelogin = useCallback(() => {
if (promptedRef.current) return;
promptedRef.current = true;
// 只能点"重新登录":不提供关闭按钮,点遮罩与按 Esc 都不关闭
modalRef.current = Modal.warning({
title: t('权限已变更'),
content: t('你的权限已变更,请重新登录。'),
okText: t('重新登录'),
centered: true,
closable: false,
keyboard: false,
mask: { closable: false },
onOk: async () => {
modalRef.current = null;
// 先判断会话域,再登出清理(清理会移除企业登录标记)
// 以后端返回的登录域为准;老版本后端没有该字段时退回本地标记
const view = prevRef.current.org || prevRef.current.platform;
const orgSession = view?.session_domain
? view.session_domain === 'org'
: isOrgLoginSession() || orgOnlyRef.current;
const target = orgSession ? '/org/login' : '/login';
try {
await API.get('/api/user/logout', {
skipErrorHandler: true,
disableDuplicate: true,
});
} catch {
// 登出失败也继续清理本地数据并跳转登录页
}
clearUserData();
userDispatch({ type: 'logout' });
window.location.href = target;
},
});
}, [t, userDispatch]);
const reload = useCallback(async () => {
lastFetchRef.current = Date.now();
const loadingKey = currentOrgViewKey();
if (!userId) {
setPlatform(null);
setOrg(null);
prevRef.current = { platform: null, org: null };
setOrgLoadedKey(loadingKey);
setPlatformLoadedFor(0);
setPlatformLoadFailed(false);
return;
}
const headers = onOrgPage ? orgHeaders() : null;
const [pr, or] = await Promise.all([
fetchView(undefined),
headers ? fetchView(headers) : Promise.resolve(null),
]);
const unauthorized = pr === UNAUTHORIZED || or === UNAUTHORIZED;
const p = pr === UNAUTHORIZED ? null : pr;
const o = or === UNAUTHORIZED ? null : or;
if (p) {
if (changedUnderEnforce(prevRef.current.platform, p)) promptRelogin();
const same = sameView(prevRef.current.platform, p);
prevRef.current.platform = p;
if (!same) setPlatform(p);
} else {
// 加载失败:保留上一份视图作比较基准;不属于当前用户的旧视图不能再用
const kept = prevRef.current.platform;
if (kept && kept.user_id !== userId) {
prevRef.current.platform = null;
setPlatform(null);
}
}
setPlatformLoadFailed(!p);
setPlatformLoadedFor(userId);
failedRef.current = !unauthorized && (!p || (!!headers && !o));
if (!headers) {
prevRef.current.org = null;
setOrg(null);
// 不在企业页时并未加载企业视图,不能标记为已就绪(否则进入企业中心时会按旧判断先行守卫)
setOrgLoadedKey(onOrgPage ? loadingKey : null);
return;
}
if (o) {
if (changedUnderEnforce(prevRef.current.org, o)) promptRelogin();
const same = sameView(prevRef.current.org, o);
prevRef.current.org = o;
if (!same) setOrg(o);
} else {
// 加载失败:保留上一份视图作比较基准;只有仍属于当前用户与当前企业时才继续使用
const kept = prevRef.current.org;
if (
kept &&
(kept.user_id !== userId || kept.org_id !== getCurrentOrgId())
) {
prevRef.current.org = null;
setOrg(null);
}
}
setOrgLoadedKey(loadingKey);
}, [userId, onOrgPage, promptRelogin]);
// 换账号、换企业(含进入 / 退出代理)都要重新加载:企业键不参与 reload 本身的计算,单独作为触发条件
useEffect(() => {
reloadRef.current = reload;
}, [reload]);
useEffect(() => {
reload();
}, [reload, orgKey]);
// 换账号(含登出):允许对新账号重新提示
useEffect(() => {
promptedRef.current = false;
}, [userId]);
// 离开企业中心:清除本标签页的"代理已失效"标记,之后再进入 /org 按正常企业上下文解析
useEffect(() => {
if (!onOrgPage) clearProxyExpired();
}, [onOrgPage]);
// 多标签页:其他标签页重新登录或登出(localStorage 用户数据变化)时,关闭本页已弹出的提示,
// 避免在旧标签页点"重新登录"把新会话注销;同时丢弃旧的比较基准,下一次加载按新会话重新建立
useEffect(() => {
// 只看用户身份:登出(键被删)或换成另一个用户才算换会话;额度等字段刷新不算,
// 否则会关掉仍然有效的提示并丢弃比较基准,本标签页就再也不会提示了
const userIdOf = (raw) => {
try {
return raw ? JSON.parse(raw)?.id || 0 : 0;
} catch {
return 0;
}
};
const onStorage = (e) => {
if (
e.key !== USER_STORAGE_KEY &&
e.key !== ORG_LOGIN_SESSION_KEY &&
e.key !== null
) {
return;
}
// 企业登录标记变化:同一用户在其他标签页改用企业入口(或个人入口)登录,登录域变了,按换会话处理
if (
e.key === USER_STORAGE_KEY &&
e.newValue !== null &&
userIdOf(e.oldValue) === userIdOf(e.newValue)
) {
return;
}
if (modalRef.current) {
modalRef.current.destroy();
modalRef.current = null;
}
promptedRef.current = false;
prevRef.current = { platform: null, org: null };
// 立即按新会话重新加载:本标签页的 UserContext 不跨标签同步,不会自己触发加载;
// 清空基准后也不再算"有已切换模块",不主动加载就要等最长 10 分钟
if (reloadRef.current) reloadRef.current();
};
window.addEventListener('storage', onStorage);
return () => window.removeEventListener('storage', onStorage);
}, []);
useEffect(() => {
if (!userId) return undefined;
const active = () =>
failedRef.current ||
isActiveView(prevRef.current.platform) ||
isActiveView(prevRef.current.org) ||
!!getProxySession();
const timer = setInterval(() => {
if (
active() ||
Date.now() - lastFetchRef.current >= IDLE_REFRESH_MS - 1000
) {
reload();
}
}, REFRESH_MS);
const onFocus = () => {
const throttle = active() ? FOCUS_THROTTLE_MS : IDLE_FOCUS_THROTTLE_MS;
if (Date.now() - lastFetchRef.current < throttle) return;
reload();
};
window.addEventListener('focus', onFocus);
return () => {
clearInterval(timer);
window.removeEventListener('focus', onFocus);
};
}, [userId, reload]);
const value = useMemo(
() => ({
platform,
org,
orgLoadedKey,
platformLoadedFor,
platformLoadFailed,
reload,
}),
[
platform,
org,
orgLoadedKey,
platformLoadedFor,
platformLoadFailed,
reload,
],
);
return (
<AuthzContext.Provider value={value}>{children}</AuthzContext.Provider>
);
};
+13 -2
View File
@@ -1,5 +1,4 @@
# Copyright and License Notice
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
@@ -16,3 +15,15 @@ You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { usePerm } from './usePerm';
// <Perm code='org.member.edit' legacy={isAdmin} fallback={null}>…</Perm>
const Perm = ({ code, legacy, fallback = null, children }) => {
const allowed = usePerm(code, legacy);
return <>{allowed ? children : fallback}</>;
};
export default Perm;
+191
View File
@@ -0,0 +1,191 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useContext, useState } from 'react';
import { Navigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button, Result } from 'antd';
import Loading from '../components/common/ui/Loading';
import { AdminRoute, PrivateRoute, RootRoute } from '../helpers/auth';
import { isRoot } from '../helpers/utils';
import { UserContext } from '../context/User';
import { AuthzContext } from './AuthzProvider';
import { usePerm } from './usePerm';
// 平台视图加载失败:给出可重试的提示,而不是按旧判断直接跳 /forbidden
const LoadFailed = ({ reload }) => {
const { t } = useTranslation();
const [retrying, setRetrying] = useState(false);
const retry = async () => {
setRetrying(true);
try {
await reload();
} finally {
setRetrying(false);
}
};
return (
<Result
status='warning'
title={t('权限信息加载失败')}
subTitle={t('请检查网络后重试')}
extra={
<Button type='primary' loading={retrying} onClick={retry}>
{t('重试')}
</Button>
}
/>
);
};
// 会话已在其他标签页变更:刷新页面按新会话重新加载
const SessionChanged = () => {
const { t } = useTranslation();
return (
<Result
status='info'
title={t('登录状态已变化')}
subTitle={t('你已在其他页面切换了账号,请刷新页面')}
extra={
<Button type='primary' onClick={() => window.location.reload()}>
{t('刷新页面')}
</Button>
}
/>
);
};
// 平台视图是否已就绪。返回 null 表示就绪,否则返回等待期间应显示的内容。
// 就绪:已有属于当前用户的平台视图(之后的刷新失败不影响);否则本用户的加载已结束且失败时提示重试。
const useViewPending = () => {
const [userState] = useContext(UserContext);
const { platform, platformLoadedFor, platformLoadFailed, reload } =
useContext(AuthzContext);
const userId = userState?.user?.id || 0;
const viewReady = !!platform && platform.user_id === userId;
if (!userId || viewReady) return { pending: null, failed: false };
if (platformLoadedFor === userId && platformLoadFailed) {
return { pending: <LoadFailed reload={reload} />, failed: true };
}
// 视图已加载但属于另一个用户:其他标签页换了账号,本页的用户信息已过期,提示刷新而不是一直转圈
if (platformLoadedFor === userId && platform) {
return { pending: <SessionChanged />, failed: false };
}
return { pending: <Loading />, failed: false };
};
// 按平台权限点守卫的路由:判断与侧边栏一致(usePerm(code, isRoot())),
// 平台视图到达前显示加载中,加载失败显示可重试提示,无权限时与其它守卫一样跳 /forbidden。
const PermGate = ({ code, children }) => {
const allowed = usePerm(code, isRoot());
const { pending } = useViewPending();
if (pending) return pending;
if (!allowed) return <Navigate to='/forbidden' replace />;
return children;
};
const PermRoute = ({ code, children }) => (
<PrivateRoute>
<PermGate code={code}>{children}</PermGate>
</PrivateRoute>
);
// 原有守卫:legacy='root' 为 RootRoute,否则为 AdminRoute(permission 为系统设置页签委派校验)
const LegacyRoute = ({ legacy, permission, children }) =>
legacy === 'root' ? (
<RootRoute>{children}</RootRoute>
) : (
<AdminRoute permission={permission}>{children}</AdminRoute>
);
// 控制台路由守卫(新旧双路径):code 所属模块已切到新体系时按权限点判断(持有权限点的非管理员也能进入,
// 没有权限点的管理员进不去);未切换时完全沿用原有守卫(AdminRoute / RootRoute)。
// 用法:<ConsoleRoute code='platform.channel'>、<ConsoleRoute code='platform.commission' legacy='root'>、
// <ConsoleRoute code='platform.setting.website_setting' permission='website-setting'>
export const ConsoleRoute = ({
code,
legacy = 'admin',
permission,
children,
}) => {
const [userState] = useContext(UserContext);
const { platform } = useContext(AuthzContext);
const { pending, failed } = useViewPending();
const user = userState?.user;
const legacyRoute = (
<LegacyRoute legacy={legacy} permission={permission}>
{children}
</LegacyRoute>
);
// 未登录或登录态校验中:交给原有守卫(跳登录页或显示加载中)
if (!user) return legacyRoute;
if (pending) {
// 视图加载失败时无从得知模块是否已切换:原判断会放行的人仍按原有守卫进入(接口权限由后端校验),
// 避免权限接口故障把管理员挡在控制台外;其余人显示可重试提示
const legacyRole = legacy === 'root' ? 100 : 10;
if (failed && typeof user.role === 'number' && user.role >= legacyRole) {
return legacyRoute;
}
return pending;
}
const mod = platform.moduleOf[code];
if (!mod || !platform.enforcedSet.has(mod)) return legacyRoute;
if (!platform.permSet.has(code)) return <Navigate to='/forbidden' replace />;
return children;
};
// 控制台入口 /console:原行为是管理员进运营看板。运营看板模块已切换且当前用户没有该菜单时
// (含持有其他平台菜单的非管理员),改进第一个已切换且持有的控制台菜单;都没有时按原有守卫处理。
export const ConsoleIndexRoute = () => {
const [userState] = useContext(UserContext);
const { platform } = useContext(AuthzContext);
const { pending, failed } = useViewPending();
const user = userState?.user;
const legacyRoute = (
<AdminRoute>
<Navigate to='/console/analytics' replace />
</AdminRoute>
);
if (!user) return legacyRoute;
if (pending) {
if (failed && typeof user.role === 'number' && user.role >= 10) {
return legacyRoute;
}
return pending;
}
const enforced = (code) => platform.enforcedSet.has(platform.moduleOf[code]);
const analyticsEnforced = enforced('platform.analytics');
const canAnalytics = analyticsEnforced
? platform.permSet.has('platform.analytics')
: typeof user.role === 'number' && user.role >= 10;
if (canAnalytics) return <Navigate to='/console/analytics' replace />;
// view.menus 已按 sort 排好,且只含当前用户持有的节点
const first = (platform.menus || []).find(
(m) =>
m.type === 'menu' &&
m.visible &&
typeof m.route === 'string' &&
m.route.startsWith('/console/') &&
enforced(m.code),
);
if (first) return <Navigate to={first.route} replace />;
return legacyRoute;
};
export default PermRoute;
+34
View File
@@ -0,0 +1,34 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
export { AuthzContext, AuthzProvider } from './AuthzProvider';
export {
usePerm,
useAnyPerm,
useAuthzView,
useAuthzReload,
useOrgViewReady,
} from './usePerm';
export { default as Perm } from './Perm';
export {
default as PermRoute,
ConsoleRoute,
ConsoleIndexRoute,
} from './PermRoute';
export { checkPerm, checkAnyPerm, buildMenuTree } from './permLogic';
+70
View File
@@ -0,0 +1,70 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 权限判断的纯逻辑(权限重构 §7.1 新旧双路径),与 React 无关,便于单测。
// view 为 /api/authz/me 的返回;legacy 为旧判断(布尔或返回布尔的函数)。
export function normalizeView(data) {
if (!data) return null;
return {
...data,
permSet: new Set(data.perms || []),
enforcedSet: new Set(data.enforced_modules || []),
moduleOf: data.module_of || {},
};
}
const evalLegacy = (legacy) =>
typeof legacy === 'function' ? !!legacy() : !!legacy;
// 模块已切到新体系(enforced):以权限点为准;否则走旧判断。未提供旧判断时按权限点判断。
// view 尚未加载:有旧判断走旧判断,否则不放行。
export function checkPerm(view, code, legacy) {
if (!view) return legacy === undefined ? false : evalLegacy(legacy);
const mod = view.moduleOf[code];
if (mod && view.enforcedSet.has(mod)) return view.permSet.has(code);
if (legacy === undefined) return view.permSet.has(code);
return evalLegacy(legacy);
}
// 是否持有任一权限点(同样按模块逐个走新旧路径)。
export function checkAnyPerm(view, codes, legacy) {
return codes.some((c) => checkPerm(view, c, legacy));
}
// 视图对应的域:org.* 权限点看企业视图,其余看平台视图。
export function viewForCode(views, code) {
return code.startsWith('org.') ? views.org : views.platform;
}
// 菜单树:按 parent 组装,同级按 sort;只保留 visible 的节点。
export function buildMenuTree(menus) {
const byParent = new Map();
for (const m of menus || []) {
if (!m.visible) continue;
const list = byParent.get(m.parent || '') || [];
list.push(m);
byParent.set(m.parent || '', list);
}
const build = (parent) =>
(byParent.get(parent) || [])
.sort((a, b) => a.sort - b.sort || a.code.localeCompare(b.code))
.map((m) => ({ ...m, children: build(m.code) }));
return build('');
}
+82
View File
@@ -0,0 +1,82 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import test from 'node:test';
import assert from 'node:assert/strict';
import {
normalizeView,
checkPerm,
checkAnyPerm,
buildMenuTree,
} from './permLogic.js';
const view = normalizeView({
perms: ['org.member', 'org.member.query'],
enforced_modules: ['member'],
module_of: {
'org.member': 'member',
'org.member.query': 'member',
'org.member.edit': 'member',
'org.dept.query': 'dept',
},
});
test('enforced module follows perms, ignoring the legacy check', () => {
assert.equal(checkPerm(view, 'org.member.query', false), true);
assert.equal(checkPerm(view, 'org.member.edit', true), false);
});
test('non-enforced module follows the legacy check', () => {
assert.equal(checkPerm(view, 'org.dept.query', true), true);
assert.equal(
checkPerm(view, 'org.dept.query', () => false),
false,
);
assert.equal(checkPerm(view, 'org.dept.query'), false);
});
test('view not loaded yet', () => {
assert.equal(checkPerm(null, 'org.member.query'), false);
assert.equal(checkPerm(null, 'org.member.query', true), true);
});
test('any of several perms', () => {
assert.equal(
checkAnyPerm(view, ['org.member.edit', 'org.member.query']),
true,
);
assert.equal(checkAnyPerm(view, ['org.member.edit']), false);
});
test('menu tree keeps visible nodes ordered by sort', () => {
const tree = buildMenuTree([
{ code: 'b', parent: '', sort: 20, visible: true },
{ code: 'a', parent: '', sort: 10, visible: true },
{ code: 'a.x', parent: 'a', sort: 10, visible: true },
{ code: 'a.h', parent: 'a', sort: 5, visible: false },
]);
assert.deepEqual(
tree.map((n) => n.code),
['a', 'b'],
);
assert.deepEqual(
tree[0].children.map((n) => n.code),
['a.x'],
);
});
+59
View File
@@ -0,0 +1,59 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useContext, useEffect } from 'react';
import { AuthzContext, currentOrgViewKey } from './AuthzProvider';
import { checkPerm, checkAnyPerm, viewForCode } from './permLogic';
// usePerm(code, legacy):模块已切到新体系时按权限点判断,否则按 legacy(旧判断)判断。
export function usePerm(code, legacy) {
const ctx = useContext(AuthzContext);
return checkPerm(viewForCode(ctx, code), code, legacy);
}
// useAnyPerm(codes, legacy):持有其中任一权限点。
export function useAnyPerm(codes, legacy) {
const ctx = useContext(AuthzContext);
if (!codes.length) return false;
return checkAnyPerm(viewForCode(ctx, codes[0]), codes, legacy);
}
// useAuthzView(domain):'platform' | 'org' 的原始视图(菜单树渲染等)。
export function useAuthzView(domain) {
const ctx = useContext(AuthzContext);
return domain === 'org' ? ctx.org : ctx.platform;
}
export function useAuthzReload() {
return useContext(AuthzContext).reload;
}
// useOrgViewReady():企业视图是否已按当前企业(含代理会话)加载过(成败均算)。
// 企业中心在它就绪前不做路由守卫,避免新体系下持有菜单的人在视图到达前被旧判断重定向走。
// 当前企业刚由解析器写入、Provider 尚未感知时主动触发一次加载。
export function useOrgViewReady() {
const ctx = useContext(AuthzContext);
const key = currentOrgViewKey();
const ready = ctx.orgLoadedKey === key;
const { reload } = ctx;
useEffect(() => {
if (!ready) reload();
}, [ready, key, reload]);
return ready;
}
+2 -2
View File
@@ -36,7 +36,7 @@ const OAuth2Callback = (props) => {
if (message === 'bind') {
showSuccess(t('绑定成功!'));
navigate('/console/personal');
navigate('/user/center', { replace: true });
return;
}
@@ -74,7 +74,7 @@ const OAuth2Callback = (props) => {
// 参数缺失直接返回
if (!code) {
showError(t('未获取到授权码'));
navigate('/console/personal');
navigate('/user/center', { replace: true });
return;
}
+300
View File
@@ -0,0 +1,300 @@
import React, { useMemo, useState } from 'react';
import { Button, Empty, Input, Tag, Tree, theme } from 'antd';
import { useTranslation } from 'react-i18next';
import { Search } from '@/components/common/icons/ActionIcons';
// 权限授权树(平台角色、套餐、模板、企业角色共用)。nodes 为后端 GrantNode 列表:
// { code, parent, type: 'dir'|'menu'|'button', name, sort, sensitive, grantable }。
// value 为已勾选的权限编码数组,只会包含 grantable 的节点;grantable=false 的节点只作为祖先展示,不可勾选。
//
// 联动规则(PRD AC50 / AC62 / AC80):
// - 勾选一个节点 = 勾选它和它全部可选后代,并带上可选祖先(后端本来也会补齐祖先);
// - 取消一个节点 = 只取消它和它的后代,兄弟不受影响;祖先下已没有任何选中的后代时祖先一并取消;
// - 祖先的显示状态由"子树内可选节点是否全部选中"推导:全部选中为勾选,部分选中为半选。
// 半选的祖先只提交它自己的编码,不会把未选中的后代带上。
const TYPE_META = {
dir: { color: 'default', label: '目录' },
menu: { color: 'blue', label: '菜单' },
button: { color: 'green', label: '按钮' },
};
const bySort = (a, b) =>
(a.sort || 0) - (b.sort || 0) || a.code.localeCompare(b.code);
// 由扁平节点建索引:parent(父编码,根为 '')、children(已排序的子编码)、
// subtree(子树内可选的编码,含自身)、order(先序遍历的编码)。
export const buildPermIndex = (nodes) => {
const byCode = new Map();
for (const n of nodes || []) byCode.set(n.code, n);
const parent = new Map();
const childNodes = new Map();
for (const n of byCode.values()) {
// parent 不在列表里的节点当作根
const p =
n.parent && n.parent !== n.code && byCode.has(n.parent) ? n.parent : '';
parent.set(n.code, p);
const list = childNodes.get(p) || [];
list.push(n);
childNodes.set(p, list);
}
const children = new Map();
for (const [p, list] of childNodes) {
children.set(
p,
list.sort(bySort).map((n) => n.code),
);
}
const subtree = new Map();
const order = [];
const walk = (code) => {
order.push(code);
const own = byCode.get(code).grantable ? [code] : [];
for (const c of children.get(code) || []) own.push(...walk(c));
subtree.set(code, own);
return own;
};
for (const c of children.get('') || []) walk(c);
return { byCode, parent, children, subtree, order };
};
// 去掉树里不存在或不可授予的编码(提交它们会被后端拒绝)。
// 只认 subtree 里登记过的节点:父链成环而从根走不到的节点不参与勾选。
const selectableSet = (index, value) =>
new Set(
(value || []).filter(
(c) => index.subtree.has(c) && index.byCode.get(c).grantable === true,
),
);
// 可以提交给后端的勾选结果(已排序):保存前用它过一遍,避免带上树里没有的历史编码
export const selectablePerms = (index, value) =>
[...selectableSet(index, value)].sort();
// 各节点的显示状态:checked = 子树内可选节点全部选中;halfChecked = 部分选中
export const permCheckState = (index, value) => {
const set = selectableSet(index, value);
const checked = [];
const halfChecked = [];
for (const [code, list] of index.subtree) {
if (!list.length) continue;
let hit = 0;
for (const c of list) if (set.has(c)) hit += 1;
if (hit === list.length) checked.push(code);
else if (hit > 0) halfChecked.push(code);
}
return { checked, halfChecked };
};
// 点击一个节点后的新勾选结果(已排序)
export const togglePerm = (index, value, code) => {
const set = selectableSet(index, value);
const sub = index.subtree.get(code) || [];
if (!sub.length) return [...set].sort();
if (sub.every((c) => set.has(c))) {
for (const c of sub) set.delete(c);
for (let p = index.parent.get(code); p; p = index.parent.get(p)) {
if (index.subtree.get(p).some((c) => c !== p && set.has(c))) break;
set.delete(p);
}
} else {
for (const c of sub) set.add(c);
for (let p = index.parent.get(code); p; p = index.parent.get(p)) {
if (index.byCode.get(p).grantable) set.add(p);
}
}
return [...set].sort();
};
// 权限摘要:已选的菜单(附其下已选按钮数)与菜单、按钮总数。用于列表里的"权限摘要"列。
export const summarizePerms = (index, perms) => {
const set = selectableSet(index, perms);
const menus = [];
let buttonCount = 0;
for (const code of index.order) {
if (!set.has(code)) continue;
const n = index.byCode.get(code);
if (n.type === 'button') {
buttonCount += 1;
} else if (n.type === 'menu') {
const buttons = index.subtree
.get(code)
.filter(
(c) => set.has(c) && index.byCode.get(c).type === 'button',
).length;
menus.push({ code, name: n.name, buttons });
}
}
return { menus, menuCount: menus.length, buttonCount, total: set.size };
};
const expandableKeys = (index, keep) =>
index.order.filter(
(c) =>
(!keep || keep.has(c)) &&
(index.children.get(c) || []).some((k) => !keep || keep.has(k)),
);
// 搜索:保留命中的节点、它的祖先(定位用)和它的整棵子树(方便直接勾选下面的按钮)
const matchKeys = (index, keyword) => {
const kw = keyword.trim().toLowerCase();
if (!kw) return null;
const keep = new Set();
const addSubtree = (code) => {
keep.add(code);
for (const c of index.children.get(code) || []) addSubtree(c);
};
for (const code of index.order) {
const n = index.byCode.get(code);
if (
!(n.name || '').toLowerCase().includes(kw) &&
!code.toLowerCase().includes(kw)
)
continue;
addSubtree(code);
for (let p = index.parent.get(code); p; p = index.parent.get(p))
keep.add(p);
}
return keep;
};
/**
* @param {object} props
* @param {Array} props.nodes 后端 GrantNode 列表
* @param {string[]} [props.value] 已勾选的权限编码
* @param {(codes: string[]) => void} [props.onChange] 勾选变化,参数为排序后的编码数组
* @param {boolean} [props.disabled] 只读:不可勾选,仍可展开、收起与搜索
* @param {number|string} [props.height=480] 树区域的最大高度,超出滚动
* @param {boolean} [props.showToolbar=true] 是否显示搜索框与"全部展开 / 全部收起"
* @param {boolean} [props.defaultExpandAll=true] 初始是否全部展开(false 时只显示根级节点)
* @param {string} [props.className]
*/
const PermTree = ({
nodes,
value,
onChange,
disabled,
height = 480,
showToolbar = true,
defaultExpandAll = true,
className,
}) => {
const { t } = useTranslation();
const { token } = theme.useToken();
const index = useMemo(() => buildPermIndex(nodes), [nodes]);
const [keyword, setKeyword] = useState('');
// null = 尚未手动操作,按 defaultExpandAll 取初始值(节点异步到达后仍然生效)
const [expandedKeys, setExpandedKeys] = useState(null);
// 搜索期间单独记一份展开状态,清空搜索后回到原来的展开状态
const [searchExpandedKeys, setSearchExpandedKeys] = useState(null);
const keep = useMemo(() => matchKeys(index, keyword), [index, keyword]);
const allExpandable = useMemo(
() => expandableKeys(index, keep),
[index, keep],
);
const checkState = useMemo(
() => permCheckState(index, value),
[index, value],
);
const treeData = useMemo(() => {
const build = (parentCode) =>
(index.children.get(parentCode) || [])
.filter((code) => !keep || keep.has(code))
.map((code) => {
const n = index.byCode.get(code);
const meta = TYPE_META[n.type];
return {
key: code,
disableCheckbox: disabled || !n.grantable,
title: (
<span className='inline-flex flex-wrap items-center gap-1'>
<span>{n.name}</span>
{meta ? (
<Tag color={meta.color} style={{ marginInlineEnd: 0 }}>
{t(meta.label)}
</Tag>
) : null}
{n.sensitive ? (
<Tag color='error' style={{ marginInlineEnd: 0 }}>
{t('敏感')}
</Tag>
) : null}
</span>
),
children: build(code),
};
});
return build('');
}, [index, keep, disabled, t]);
const searching = keep !== null;
const currentExpanded = searching
? (searchExpandedKeys ?? allExpandable)
: (expandedKeys ?? (defaultExpandAll ? allExpandable : []));
const setCurrentExpanded = searching
? setSearchExpandedKeys
: setExpandedKeys;
return (
<div className={className}>
{showToolbar ? (
<div className='mb-2 flex flex-wrap items-center gap-2'>
<Input
allowClear
value={keyword}
prefix={<Search size={14} />}
placeholder={t('搜索权限')}
aria-label={t('搜索权限')}
style={{ flex: '1 1 180px', minWidth: 0 }}
onChange={(e) => {
setKeyword(e.target.value);
// 每次改关键字都重新展开全部命中路径
setSearchExpandedKeys(null);
}}
/>
<Button onClick={() => setCurrentExpanded(allExpandable)}>
{t('全部展开')}
</Button>
<Button onClick={() => setCurrentExpanded([])}>
{t('全部收起')}
</Button>
</div>
) : null}
<div
style={{
maxHeight: height,
overflow: 'auto',
padding: 8,
border: `1px solid ${token.colorBorderSecondary}`,
borderRadius: token.borderRadius,
}}
>
{treeData.length ? (
<Tree
checkable
// 联动与半选由本组件按"可选节点"自行计算;antd 自带的联动会把已保存的祖先当成全选
checkStrictly
selectable={false}
treeData={treeData}
checkedKeys={checkState}
expandedKeys={currentExpanded}
autoExpandParent={false}
onExpand={(keys) => setCurrentExpanded(keys)}
onCheck={(_, info) =>
onChange?.(togglePerm(index, value, info.node.key))
}
/>
) : (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={searching ? t('没有匹配的权限') : t('暂无数据')}
/>
)}
</div>
</div>
);
};
export default PermTree;
@@ -1,9 +1,3 @@
.usage-record-filter-card {
--usage-record-filter-label: #6b7789;
}
html.dark .usage-record-filter-card {
--usage-record-filter-label: var(--text-secondary);
}
.usage-record-filter-card.ant-card {
background: var(--surface-card);
}
@@ -39,7 +33,7 @@ html.dark .usage-record-filter-card {
.ant-form-item-label
> label {
height: 21px;
color: var(--usage-record-filter-label);
color: var(--text-secondary);
font-size: 13px;
}
:where(.usage-record-filter-card) .usage-record-filter-form .ant-picker,
+31
View File
@@ -48,6 +48,37 @@ export const consolePages = [
hideHeading: true,
},
{ key: 'smart-router', title: '智能路由', description: 'smart-router' },
// 权限管理(/console/authz/*):菜单 key 与侧栏、图标一致(authz-*)
{
key: 'authz/menus',
menuKey: 'authz-menus',
title: '菜单管理',
description: 'authz-menus',
},
{
key: 'authz/roles',
menuKey: 'authz-roles',
title: '平台角色',
description: 'authz-roles',
},
{
key: 'authz/packages',
menuKey: 'authz-packages',
title: '功能套餐',
description: 'authz-packages',
},
{
key: 'authz/templates',
menuKey: 'authz-templates',
title: '角色模板',
description: 'authz-templates',
},
{
key: 'authz/mode',
menuKey: 'authz-mode',
title: '运行模式',
description: 'authz-mode',
},
{ key: 'partner', title: '合作伙伴', description: 'partner' },
{
key: 'skill-platform',
@@ -59,6 +59,7 @@
.console-page:is(
[data-console-page='channel'],
[data-console-page='redemption'],
[data-console-page='models'],
[data-console-page='user'],
[data-console-page='organizations'],
@@ -73,6 +74,17 @@
font-weight: 400;
}
.console-page:is(
[data-console-page='channel'],
[data-console-page='redemption']
)
.console-table.ant-table-wrapper
.ant-table-thead
> tr
> th {
color: var(--console-text);
}
.console-model-drawer .ant-drawer-title > .ant-space {
align-items: center;
}
+22 -3
View File
@@ -4,12 +4,16 @@ import App from '../../App';
import React, {
useContext,
useEffect,
useLayoutEffect,
useState,
lazy,
Suspense,
useRef,
} from 'react';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import { useSidebarCollapsed } from '../../hooks/common/useSidebarCollapsed';
import { useSidebarToggleGuard } from '../../hooks/common/useSidebarToggleGuard';
import { CenterSidebarLoading } from './components/CenterSidebarLoading';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers/api';
import { isAuthPagePath } from '../../helpers/auth';
@@ -62,7 +66,9 @@ const PageLayout = () => {
const [userState, userDispatch] = useContext(UserContext);
const [, statusDispatch] = useContext(StatusContext);
const isMobile = useIsMobile();
const [collapsed] = useSidebarCollapsed();
const [drawerOpen, setDrawerOpen] = useState(false);
const canToggleSidebar = useSidebarToggleGuard();
const { i18n } = useTranslation();
const location = useLocation();
@@ -120,6 +126,10 @@ const PageLayout = () => {
const headerBarHeight = isMobile ? 56 : 72;
const totalHeaderHeight = headerBarHeight + marqueeHeight;
useLayoutEffect(() => {
document.body.classList.toggle('sidebar-collapsed', collapsed);
}, [collapsed]);
// 滚动容器引用
const scrollContainerRef = useRef(null);
const authBootstrappedRef = useRef(false);
@@ -155,7 +165,7 @@ const PageLayout = () => {
// 顶栏总高(顶栏 + 跑马灯)发布成全局 CSS 变量。
// 顶栏是 position:fixed,内容区从视口 0 开始流动,任何 `sticky top-0` 的页内元素
// 都会吸到顶栏底下被盖住。页面无从得知跑马灯开没开,只能由这里统一给出。
useEffect(() => {
useLayoutEffect(() => {
const root = document.documentElement;
root.style.setProperty('--app-header-height', `${totalHeaderHeight}px`);
}, [totalHeaderHeight]);
@@ -352,7 +362,9 @@ const PageLayout = () => {
>
<Suspense fallback={null}>
<HeaderBar
onMobileMenuToggle={() => setDrawerOpen((prev) => !prev)}
onMobileMenuToggle={() => {
if (canToggleSidebar('drawer')) setDrawerOpen((open) => !open);
}}
drawerOpen={drawerOpen}
/>
</Suspense>
@@ -408,7 +420,14 @@ const PageLayout = () => {
: undefined,
}}
>
<Suspense fallback={null}>
<Suspense
fallback={
<CenterSidebarLoading
variant='console'
forceExpanded={siderForceExpanded}
/>
}
>
<SiderBar
forceExpanded={siderForceExpanded}
onNavigate={() => {
+167 -192
View File
@@ -1,19 +1,14 @@
import {
ChevronDown as ActionChevronDown,
ChevronRight as ActionChevronRight,
ChevronLeft as ActionChevronLeft,
} from '@/components/common/icons/ActionIcons';
import { consoleMenuPaths, getConsoleMenuKeys } from '../console/consoleRoutes';
import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { revealActiveSidebarItem } from '../../helpers/sidebarScroll';
import { Link, useLocation } from 'react-router-dom';
import React, { useContext, useEffect, useMemo, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { getLucideIcon } from '../../helpers/render';
import '../../styles/center-layout.css';
import { useSidebarCollapsed } from '../../hooks/common/useSidebarCollapsed';
import { useSidebarNavigation } from '../../hooks/common/useTopNavigation';
import { useSidebarGroups } from '../../hooks/common/useSidebarGroups';
import { useSidebar } from '../../hooks/common/useSidebar';
import { usePartnerWorkspaceEntry } from '../../hooks/common/usePartnerWorkspaceEntry';
import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime';
import { isAdmin, isRoot, showError } from '../../helpers';
import {
isMiniProgramPaymentPath,
@@ -29,8 +24,15 @@ import {
loadPersonalConsentGranted,
readPersonalConsentCache,
} from '../smart-router/api';
import SkeletonWrapper from './components/SkeletonWrapper';
import {
CenterSidebar,
CenterSidebarGroup,
CenterSidebarItem,
CenterSidebarSubmenu,
} from './components/CenterSidebar';
import { CenterSidebarLoading } from './components/CenterSidebarLoading';
import { CLOUD_BRAIN_UI_ENABLED } from '../../config/cloudBrainUi';
import { useAuthzView, usePerm } from '../../authz';
const routerMap = {
home: '/',
@@ -57,6 +59,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
const { t } = useTranslation();
const [persistedCollapsed, toggleCollapsed] = useSidebarCollapsed();
const collapsed = forceExpanded ? false : persistedCollapsed;
const followSidebarLink = useSidebarNavigation(onNavigate);
const {
isModuleVisible,
hasSectionVisibleModules,
@@ -76,10 +79,29 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
isRoot() || (isAdmin() && delegatedSettingTabs.length > 0);
const commissionEnabled = statusState?.status?.commission_enabled !== false;
const showSkeleton = useMinimumLoadingTime(sidebarLoading, 200);
// 权限管理分组:模块切到新体系后按权限点判断,切换前只有 root 可见(legacy = isRoot())
const canAuthzMenu = usePerm('platform.authz.menu.query', isRoot());
const canAuthzRole = usePerm('platform.authz.role.query', isRoot());
const canAuthzPackage = usePerm('platform.authz.package.query', isRoot());
const canAuthzTemplate = usePerm('platform.authz.template.query', isRoot());
// 新旧双路径(与路由守卫 ConsoleRoute 同口径):菜单所属模块已切到新体系时按权限点决定是否显示,
// 返回 true / false;未切换(或权限视图未到达)返回 null,调用方沿用原判断。
// 菜单管理里把菜单设为不显示时(visible=false)同样隐藏。
const platformView = useAuthzView('platform');
const permVisible = useMemo(() => {
if (!platformView) return () => null;
const hidden = new Set(
(platformView.menus || []).filter((m) => !m.visible).map((m) => m.code),
);
return (code) => {
const mod = code ? platformView.moduleOf[code] : '';
if (!mod || !platformView.enforcedSet.has(mod)) return null;
return platformView.permSet.has(code) && !hidden.has(code);
};
}, [platformView]);
const [selectedKeys, setSelectedKeys] = useState(['home']);
const navigationRef = useRef(null);
// 平台关闭智能路由后,仍有生效中出境同意的普通用户保留入口以便撤回(§9.5,与企业"仅授权模式"同口径)
const [routerConsentGranted, setRouterConsentGranted] = useState(
() => readPersonalConsentCache() === '1',
@@ -100,8 +122,9 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
};
}, [smartRouterEnabled]);
const [chatItems, setChatItems] = useState([]);
const [openedKeys, setOpenedKeys] = useState([]);
const [foldedGroups, setFoldedGroups] = useState([]);
const submenus = useSidebarGroups();
const groups = useSidebarGroups();
const { setGroup: setSubmenu } = submenus;
const location = useLocation();
const [routerMapState, setRouterMapState] = useState(routerMap);
@@ -125,23 +148,27 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
text: t('使用日志'),
itemKey: 'log',
to: '/log',
perm: 'platform.log',
},
{
text: t('绘图日志'),
itemKey: 'midjourney',
to: '/midjourney',
perm: 'platform.drawing_log',
className: drawingFlag === 'true' ? '' : 'tableHiddle',
},
{
text: t('任务日志'),
itemKey: 'task',
to: '/task',
perm: 'platform.task_log',
className: taskFlag === 'true' ? '' : 'tableHiddle',
},
{
text: t('监控中心'),
itemKey: 'monitor',
to: '/monitor',
perm: 'platform.monitor',
},
{
// 智能路由:已登记在 sidebarModules 注册表(console.smart-router),管理员可隐藏
@@ -163,7 +190,8 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
)
return false;
const configVisible = isModuleVisible('console', item.itemKey);
return configVisible;
// 已切换模块:还须持有对应菜单权限点
return configVisible && permVisible(item.perm) !== false;
});
return filteredItems;
@@ -175,6 +203,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
taskFlag,
t,
isModuleVisible,
permVisible,
]);
const financeItems = useMemo(() => {
@@ -183,6 +212,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
text: t('钱包管理'),
itemKey: 'topup',
to: '/topup',
perm: 'platform.topup',
},
{
text: t('个人设置'),
@@ -198,7 +228,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
if (isMiniProgramWebView() && isMiniProgramPaymentPath(item.to)) {
return false;
}
return configVisible;
return configVisible && permVisible(item.perm) !== false;
});
// 与顶栏和伙伴页面共用新版伙伴权限判断,避免无权限账号误入。
@@ -210,18 +240,20 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
}
return filteredItems;
}, [t, isModuleVisible, showPartnerWorkspace]);
}, [t, isModuleVisible, showPartnerWorkspace, permVisible]);
const adminItems = useMemo(() => {
const items = [
{
text: t('运营看板'),
itemKey: 'analytics',
perm: 'platform.analytics',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('分佣管理'),
itemKey: 'commission',
perm: 'platform.commission',
items: [
{ text: t('分佣工作台'), itemKey: 'commission-overview' },
{ text: t('合作伙伴'), itemKey: 'commission-partners' },
@@ -237,81 +269,109 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
{
text: t('渠道管理'),
itemKey: 'channel',
perm: 'platform.channel',
to: '/channel',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('模型管理'),
itemKey: 'models',
perm: 'platform.model',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('兑换码管理'),
itemKey: 'redemption',
perm: 'platform.redemption',
to: '/redemption',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('用户管理'),
itemKey: 'user',
perm: 'platform.user',
to: '/user',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('会员卡管理'),
itemKey: 'subscription',
perm: 'platform.subscription',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('密钥管理'),
itemKey: 'admin-token',
perm: 'platform.admin_token',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('企业管理'),
itemKey: 'organizations',
perm: 'platform.org',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('平台 Skill 中心'),
itemKey: 'skill-platform',
perm: 'platform.skill',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('平台专家中心'),
itemKey: 'expert-platform',
perm: 'platform.expert',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('订单管理'),
itemKey: 'order',
perm: 'platform.order',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('发票管理'),
itemKey: 'invoice',
perm: 'platform.invoice',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('系统设置'),
itemKey: 'setting',
perm: 'platform.setting',
to: '/setting',
className: canAccessSetting ? '' : 'tableHiddle',
},
{
text: t('官网设置'),
itemKey: 'website-setting',
perm: 'platform.setting.website_setting',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('预约演示'),
itemKey: 'demo-reservations',
perm: 'platform.setting.demo_reservations',
className: isAdmin() ? '' : 'tableHiddle',
},
];
// 根据配置过滤项目
const filteredItems = items.filter((item) => {
// 已切换模块:只看权限点(及菜单管理的显示开关),不再看角色与侧栏模块配置——
// 持有菜单的非管理员也要能看到入口;功能总开关(云端大脑、分佣)仍然生效
const byPerm = permVisible(item.perm);
if (byPerm !== null) {
if (
!CLOUD_BRAIN_UI_ENABLED &&
(item.itemKey === 'skill-platform' ||
item.itemKey === 'expert-platform')
) {
return false;
}
if (item.itemKey === 'commission' && !commissionEnabled) return false;
return byPerm;
}
if (
(item.itemKey === 'website-setting' ||
item.itemKey === 'demo-reservations') &&
@@ -351,10 +411,14 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
return configVisible;
});
return filteredItems;
// 已切换模块的菜单按权限点放行,不受原有的角色隐藏(tableHiddle)影响
return filteredItems.map((item) =>
permVisible(item.perm) === true ? { ...item, className: '' } : item,
);
}, [
t,
isModuleVisible,
permVisible,
canAccessSetting,
delegatedSettingTabs,
delegatedPermissions,
@@ -362,28 +426,63 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
commissionEnabled,
]);
// 非管理员持有已切换模块的菜单时也显示管理员分组
const visibleAdminItems = adminItems.filter(
(item) => item.className !== 'tableHiddle',
);
// 权限管理分组:新模块不在 sidebar 配置注册表内,绕过 isModuleVisible,直接按权限点控制显示
const canAuthzMode = isRoot();
const authzItems = useMemo(() => {
const items = [
{ text: t('菜单管理'), itemKey: 'authz-menus', visible: canAuthzMenu },
{ text: t('平台角色'), itemKey: 'authz-roles', visible: canAuthzRole },
{
text: t('功能套餐'),
itemKey: 'authz-packages',
visible: canAuthzPackage,
},
{
text: t('角色模板'),
itemKey: 'authz-templates',
visible: canAuthzTemplate,
},
{ text: t('运行模式'), itemKey: 'authz-mode', visible: canAuthzMode },
];
return items.filter((item) => item.visible);
}, [
t,
canAuthzMenu,
canAuthzRole,
canAuthzPackage,
canAuthzTemplate,
canAuthzMode,
]);
const chatMenuItems = useMemo(() => {
const items = [
{
text: t('操练场'),
itemKey: 'playground',
to: '/playground',
perm: 'platform.playground',
},
{
text: t('聊天'),
itemKey: 'chat',
items: chatItems,
perm: 'platform.chat',
},
];
// 根据配置过滤项目
const filteredItems = items.filter((item) => {
const configVisible = isModuleVisible('chat', item.itemKey);
return configVisible;
return configVisible && permVisible(item.perm) !== false;
});
return filteredItems;
}, [chatItems, t, isModuleVisible]);
}, [chatItems, t, isModuleVisible, permVisible]);
// 更新路由映射,添加聊天路由
const updateRouterMapWithChats = (chats) => {
@@ -453,9 +552,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
setSelectedKeys([
validChildKeys.includes(childKey) ? childKey : 'commission-overview',
]);
setOpenedKeys((keys) =>
keys.includes('commission') ? keys : [...keys, 'commission'],
);
setSubmenu('commission', true);
return;
}
let matchingKeys = getConsoleMenuKeys(currentPath, routerMapState);
@@ -474,50 +571,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
if (matchingKeys.length) {
setSelectedKeys(matchingKeys);
}
}, [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 是全局的,抽屉临时展开不该顺手把桌面侧栏宽度也改掉。
useEffect(() => {
if (forceExpanded) return;
if (persistedCollapsed) {
document.body.classList.add('sidebar-collapsed');
} else {
document.body.classList.remove('sidebar-collapsed');
}
}, [persistedCollapsed, forceExpanded]);
}, [location.pathname, location.search, routerMapState, setSubmenu]);
const renderMenuIcon = (key) =>
React.cloneElement(getLucideIcon(key), {
@@ -529,139 +583,73 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
});
const renderGroup = (key, label, items) => (
<div key={key} className='ui-org-nav-group'>
{!collapsed && (
<button
type='button'
className='app-action-button ui-org-group-toggle'
aria-expanded={!foldedGroups.includes(key)}
onClick={() =>
setFoldedGroups((previous) =>
previous.includes(key)
? previous.filter((group) => group !== key)
: [...previous, key],
)
}
>
<span>{label}</span>
<ActionChevronDown
size={13}
className={foldedGroups.includes(key) ? 'is-folded' : ''}
aria-hidden='true'
/>
</button>
)}
<div
className='ui-org-group-items'
hidden={!collapsed && foldedGroups.includes(key)}
<CenterSidebarGroup
key={key}
label={label}
collapsed={collapsed}
folded={groups.keys.includes(key)}
onToggle={() => groups.toggle(key)}
>
{items}
</div>
</div>
</CenterSidebarGroup>
);
// nested:二级菜单项(无图标,靠缩进与引导线表达层级);forceActive:收起态父项代表任一子项选中
const renderNavItem = (
item,
{ nested = false, forceActive = false } = {},
) => {
if (item.className === 'tableHiddle') return null;
const active = forceActive || selectedKeys.includes(item.itemKey);
const to = routerMapState[item.itemKey] || routerMap[item.itemKey] || '#';
return (
<Link
<CenterSidebarItem
key={item.itemKey}
to={routerMapState[item.itemKey] || routerMap[item.itemKey] || '#'}
onClick={onNavigate}
className={`ui-center-menu-item${nested ? ' ui-console-submenu-item' : ''}`}
data-active={active || undefined}
aria-current={active ? 'page' : undefined}
title={collapsed ? item.text : undefined}
>
{!nested && renderMenuIcon(item.itemKey)}
{!collapsed && (
<span className='ui-center-menu-label'>{item.text}</span>
)}
</Link>
to={to}
label={item.text}
active={forceActive || selectedKeys.includes(item.itemKey)}
collapsed={collapsed}
nested={nested}
icon={!nested && renderMenuIcon(item.itemKey)}
onClick={(event) => followSidebarLink(to, event)}
/>
);
};
const renderSubItem = (item) => {
if (!item.items?.length) return renderNavItem(item);
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}`;
if (collapsed) return renderNavItem(item, { forceActive: childActive });
return (
<div key={item.itemKey} className='ui-console-submenu'>
<button
type='button'
className='ui-center-menu-item ui-console-submenu-toggle'
data-child-active={childActive || undefined}
aria-expanded={open}
aria-controls={groupId}
onClick={() =>
setOpenedKeys((previous) =>
previous.includes(item.itemKey)
? previous.filter((key) => key !== item.itemKey)
: [...previous, item.itemKey],
)
}
>
{renderMenuIcon(item.itemKey)}
<span className='ui-center-menu-label'>{item.text}</span>
<ActionChevronDown
size={14}
className='ui-console-submenu-arrow'
aria-hidden
/>
</button>
<div
id={groupId}
role='group'
aria-label={item.text}
className='ui-org-group-items ui-console-submenu-items'
hidden={!open}
<CenterSidebarSubmenu
key={item.itemKey}
label={item.text}
icon={renderMenuIcon(item.itemKey)}
open={submenus.keys.includes(item.itemKey)}
childActive={childActive}
onToggle={() => submenus.toggle(item.itemKey)}
>
{item.items.map((child) => renderNavItem(child, { nested: true }))}
</div>
</div>
</CenterSidebarSubmenu>
);
};
if (sidebarLoading)
return (
<div
className='ui-console-sidebar ui-center-sidebar'
data-collapsed={collapsed}
style={{
width: forceExpanded
? 'var(--sidebar-width)'
: 'var(--sidebar-current-width)',
background: 'var(--surface-sidebar)',
}}
>
<SkeletonWrapper
loading={showSkeleton}
type='sidebar'
className=''
<CenterSidebarLoading variant='console' forceExpanded={forceExpanded} />
);
return (
<CenterSidebar
className='ui-console-sidebar'
collapsed={collapsed}
showAdmin={isAdmin()}
mobile={forceExpanded}
onToggle={toggleCollapsed}
>
<nav ref={navigationRef} className='ui-center-sidebar-nav'>
{/* 聊天区域 */}
{hasSectionVisibleModules('chat') &&
renderGroup(
'chat-group',
t('聊天'),
chatMenuItems.map(renderSubItem),
)}
renderGroup('chat-group', t('聊天'), chatMenuItems.map(renderSubItem))}
{/* 控制台区域 */}
{hasSectionVisibleModules('console') &&
@@ -680,34 +668,21 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
)}
{/* 管理员区域:按角色、权限下放及菜单配置过滤。分佣管理为子菜单,走 renderSubItem。 */}
{isAdmin() &&
{(isAdmin() || visibleAdminItems.length > 0) &&
renderGroup(
'admin-group',
t('管理员'),
adminItems
.filter((item) => item.className !== 'tableHiddle')
.map(renderSubItem),
visibleAdminItems.map(renderSubItem),
)}
</nav>
</SkeletonWrapper>
{/* 底部折叠按钮 —— 抽屉态不提供:收起后抽屉会变成 60px 窄条,等于自废 */}
{!forceExpanded && (
<button
type='button'
className='app-action-button ui-center-sidebar-collapse'
onClick={toggleCollapsed}
aria-label={collapsed ? t('展开导航') : t('收起导航')}
>
{collapsed ? (
<ActionChevronRight size={16} />
) : (
<ActionChevronLeft size={16} />
{/* 权限管理区域:至少有一项可见时显示 */}
{authzItems.length > 0 &&
renderGroup(
'authz-group',
t('权限管理'),
authzItems.map((item) => renderNavItem(item)),
)}
{!collapsed && <span>{t('收起导航')}</span>}
</button>
)}
</div>
</CenterSidebar>
);
};
@@ -0,0 +1,192 @@
import React, { useEffect, useId, useRef } from 'react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
ChevronDown,
ChevronLeft,
ChevronRight,
} from '@/components/common/icons/ActionIcons';
import { revealActiveSidebarItem } from '../../../helpers/sidebarScroll';
export function CenterSidebar({
children,
className = '',
collapsed = false,
loading = false,
mobile = false,
header,
footer,
onToggle,
label,
navigationClassName = '',
}) {
const { t } = useTranslation();
const navigation = useRef(null);
const navId = useId();
useEffect(() => {
const node = navigation.current;
if (loading || !node) return;
let frame;
const schedule = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => revealActiveSidebarItem(node));
};
const resize = new ResizeObserver(schedule);
resize.observe(node);
const mutation = new MutationObserver(schedule);
mutation.observe(node, {
subtree: true,
childList: true,
attributes: true,
attributeFilter: ['aria-current', 'hidden'],
});
schedule();
return () => {
cancelAnimationFrame(frame);
resize.disconnect();
mutation.disconnect();
};
}, [collapsed, loading]);
const CollapseIcon = collapsed ? ChevronRight : ChevronLeft;
return (
<aside
className={`ui-center-sidebar ${className}`}
data-collapsed={collapsed}
data-mobile={mobile || undefined}
aria-busy={loading || undefined}
>
{header}
<nav
id={navId}
ref={navigation}
className={`ui-center-sidebar-nav ${navigationClassName}`}
aria-label={label || t('主导航')}
>
{children}
</nav>
{footer}
{onToggle && !mobile && (
<button
type='button'
className='app-action-button ui-center-sidebar-collapse'
onClick={onToggle}
aria-controls={navId}
aria-expanded={!collapsed}
aria-label={collapsed ? t('展开导航') : t('收起导航')}
>
<CollapseIcon size={16} aria-hidden='true' />
{!collapsed && <span>{t('收起导航')}</span>}
</button>
)}
</aside>
);
}
export function CenterSidebarItem({
to,
label,
icon,
active,
collapsed,
nested,
trailing,
className = '',
...props
}) {
const Element = to ? Link : 'button';
return (
<Element
{...(to ? { to } : { type: 'button' })}
className={`ui-center-menu-item${nested ? ' ui-console-submenu-item' : ''} ${className}`}
data-active={active || undefined}
aria-current={active ? 'page' : undefined}
aria-label={collapsed ? label : undefined}
title={collapsed ? label : undefined}
{...props}
>
{icon}
{!collapsed && <span className='ui-center-menu-label'>{label}</span>}
{trailing}
</Element>
);
}
export function CenterSidebarGroup({
children,
label,
collapsed,
folded,
onToggle,
}) {
const id = useId();
return (
<div className='ui-org-nav-group'>
{!collapsed && (
<button
type='button'
className='app-action-button ui-org-group-toggle'
aria-controls={id}
aria-expanded={!folded}
onClick={onToggle}
>
<span>{label}</span>
<ChevronDown
size={13}
className={folded ? 'is-folded' : ''}
aria-hidden='true'
/>
</button>
)}
<div id={id} className='ui-org-group-items' hidden={!collapsed && folded}>
{children}
</div>
</div>
);
}
export function CenterSidebarSubmenu({
children,
label,
icon,
collapsed,
open,
childActive,
onToggle,
className = '',
}) {
const id = useId();
return (
<div className={`ui-console-submenu ${className}`}>
<CenterSidebarItem
className='ui-console-submenu-toggle'
icon={icon}
label={label}
collapsed={collapsed}
data-child-active={childActive || undefined}
aria-expanded={open}
aria-controls={id}
onClick={onToggle}
trailing={
!collapsed && (
<ChevronDown
size={14}
className='ui-console-submenu-arrow'
aria-hidden='true'
/>
)
}
/>
<div
id={id}
role='group'
aria-label={label}
className='ui-org-group-items ui-console-submenu-items'
hidden={!open}
>
{children}
</div>
</div>
);
}
@@ -0,0 +1,76 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { useSidebarCollapsed } from '../../../hooks/common/useSidebarCollapsed';
import { CenterSidebar } from './CenterSidebar';
const rows = [0, 1, 2, 3, 4, 5];
export function CenterSidebarLoading({
forceExpanded = false,
variant = 'user',
}) {
const [persistedCollapsed] = useSidebarCollapsed();
const collapsed = !forceExpanded && persistedCollapsed;
const identity = variant === 'org' && !collapsed;
const grouped = !collapsed && (variant === 'org' || variant === 'console');
return (
<CenterSidebar
className={`ui-${variant}-sidebar ui-center-sidebar-placeholder`}
collapsed={collapsed}
mobile={forceExpanded}
loading
header={
identity && (
<div
className='ui-org-identity ui-center-sidebar-placeholder-identity'
aria-hidden='true'
>
<span />
<span />
</div>
)
}
footer={
!forceExpanded && (
<div
className='ui-center-sidebar-placeholder-footer'
aria-hidden='true'
>
<span />
</div>
)
}
>
<div
className='ui-org-group-items ui-center-sidebar-placeholder-rows'
aria-hidden='true'
>
{grouped && (
<div className='ui-center-sidebar-placeholder-group'>
<span />
</div>
)}
{rows.map((row) => (
<div key={row} className='ui-center-menu-item'>
<span />
<span />
</div>
))}
</div>
</CenterSidebar>
);
}
export function CenterRouteLoading({ variant }) {
const { t } = useTranslation();
return (
<div className='ui-center-route-loading' role='status'>
<div className='hidden md:block'>
<CenterSidebarLoading variant={variant} />
</div>
<div className='ui-center-route-loading-body'>{t('加载中...')}</div>
</div>
);
}
@@ -1,5 +1,5 @@
import React, { useState, useContext } from 'react';
import { Link } from 'react-router-dom';
import React, { useState, useContext, useRef } from 'react';
import { useHref, useMatch } from 'react-router-dom';
import { isMiniProgramWebView } from '../../../helpers/miniProgram';
import { Button as AntButton, Divider, Tooltip } from 'antd';
import { Share2, BookOpen, Download, Wallet } from 'lucide-react';
@@ -13,12 +13,14 @@ import { StatusContext } from '../../../context/Status';
import { isHeaderActionButtonVisible } from '../../../helpers/navigationVisibility';
import { useWeyAiDownloadEntry } from '../../../hooks/common/useWeyAiWebEntry';
const PROMOTION_MASK_INTERVAL = 240;
const WEYAI_DOWNLOAD_PATH = '/weyai/download';
const ActionButtons = ({
isAuthPage = false,
isNewYear,
unreadCount,
onNoticeOpen,
theme,
onThemeToggle,
currentLang,
onLanguageChange,
@@ -29,10 +31,18 @@ const ActionButtons = ({
sidebarModulesAdmin,
isOrgUser,
logout,
navigate,
followTopLink,
t,
}) => {
const [promotionVisible, setPromotionVisible] = useState(false);
const promotionOpenedAt = useRef(-Infinity);
const tutorialHref = useHref('/tutorial');
const downloadHref = useHref(WEYAI_DOWNLOAD_PATH);
const isWeyAiDownloadPage = Boolean(useMatch(WEYAI_DOWNLOAD_PATH));
const isEmbeddedWeyAiDownloadPage = Boolean(
useMatch('/user-center/weyai-download'),
);
const rechargeHref = useHref('/recharge');
const [statusState] = useContext(StatusContext);
const isLoggedIn = userState?.user?.username;
const userGroup = userState?.user?.group || 'default';
@@ -127,14 +137,14 @@ const ActionButtons = ({
<div className='ui-header-actions flex items-center shrink-0'>
{/* Tutorial Button - 新手教程按钮 (桌面端显示) */}
{isLoggedIn && isButtonVisible('tutorial') && (
<Link
to='/tutorial'
<AntButton
href={tutorialHref}
className='ui-header-action-link ui-header-desktop-action'
icon={actionIcon(BookOpen)}
onClick={(event) => followTopLink('/tutorial', event)}
>
<AntButton icon={actionIcon(BookOpen)}>
{!isMobile && t('新手教程')}
</AntButton>
</Link>
)}
{/* Promotion Button - 推广按钮 (桌面端显示) */}
@@ -142,7 +152,11 @@ const ActionButtons = ({
<AntButton
icon={actionIcon(Share2)}
className='ui-header-desktop-action'
onClick={() => setPromotionVisible(true)}
onClick={() => {
if (promotionVisible) return;
promotionOpenedAt.current = performance.now();
setPromotionVisible(true);
}}
>
{!isMobile && t('推广')}
</AntButton>
@@ -151,37 +165,49 @@ const ActionButtons = ({
{/* WeyAi 桌面端下载 - 有 WeyAi 访问权限且下载页已开放时显示 (桌面端显示) */}
{showWeyAiDownload && (
<Tooltip title={t('下载 WeyAi')}>
<Link
to='/weyai/download'
className='ui-header-action-link ui-header-desktop-action'
aria-label={t('下载 WeyAi 桌面端')}
>
<AntButton
href={downloadHref}
type='text'
className='ui-header-download'
className='ui-header-action-link ui-header-desktop-action ui-header-download'
data-active={isWeyAiDownloadPage || isEmbeddedWeyAiDownloadPage}
aria-current={isWeyAiDownloadPage ? 'page' : undefined}
aria-label={t('下载 WeyAi 桌面端')}
icon={actionIcon(Download)}
onClick={(event) => followTopLink(WEYAI_DOWNLOAD_PATH, event)}
>
{!isMobile && t('下载 WeyAi')}
</AntButton>
</Link>
</Tooltip>
)}
{/* Recharge Button - 充值按钮 */}
{isButtonVisible('recharge') && !isMiniProgramWebView() && (
<Link to='/recharge' className='ui-header-action-link'>
<AntButton
href={rechargeHref}
className='ui-header-action-link'
icon={actionIcon(Wallet)}
aria-label={isMobile ? t('充值') : undefined}
onClick={(event) => followTopLink('/recharge', event)}
>
{!isMobile && t('充值')}
</AntButton>
</Link>
)}
<PromotionPosterModal
visible={promotionVisible}
onClose={() => setPromotionVisible(false)}
onClose={(event) => {
// The remaining trigger clicks can land on the newly opened mask.
if (
event?.type === 'click' &&
event.target === event.currentTarget &&
event.currentTarget?.classList.contains('ant-modal-wrap') &&
performance.now() - promotionOpenedAt.current <
PROMOTION_MASK_INTERVAL
) {
return;
}
setPromotionVisible(false);
}}
/>
{/* Divider:原型仅在主操作与工具按钮之间保留一条竖线 */}
@@ -194,7 +220,7 @@ const ActionButtons = ({
)}
{isActionVisible('theme') && (
<ThemeToggle theme={theme} onThemeToggle={onThemeToggle} t={t} />
<ThemeToggle onThemeToggle={onThemeToggle} t={t} />
)}
{/* 系统公告:原型位于主题与语言之间 */}
@@ -210,6 +236,7 @@ const ActionButtons = ({
<LanguageSelector
currentLang={currentLang}
onLanguageChange={onLanguageChange}
isMobile={isMobile}
t={t}
/>
)}
@@ -223,7 +250,7 @@ const ActionButtons = ({
sidebarModulesAdmin={sidebarModulesAdmin}
isOrgUser={isOrgUser}
logout={logout}
navigate={navigate}
followTopLink={followTopLink}
t={t}
/>
</div>
@@ -4,6 +4,7 @@ import { Button as AntButton, Dropdown } from 'antd';
import { CN, GB, JP, KR, TH, VN } from 'country-flag-icons/react/3x2';
import { normalizeLanguage } from '../../../i18n/language';
import { orderEnabledLanguages } from '../../../i18n/catalog';
import { useHeaderDropdown } from './useHeaderDropdown';
import {
LANG_BOOT_UPDATED_EVENT,
getBootConfig,
@@ -12,7 +13,9 @@ import {
// 语言目录里的 flag 国家码 → 旗帜组件
const FLAGS = { CN, GB, JP, KR, TH, VN };
const LanguageSelector = ({ currentLang, onLanguageChange, t }) => {
const LanguageSelector = ({ currentLang, onLanguageChange, isMobile, t }) => {
const { close, dropdownProps, popupProps, triggerProps } =
useHeaderDropdown(isMobile);
// i18n.language 可能带地区码(如 zh-CN / en-US),高亮判断先归一化;
// 繁体靠地区码区分,不能简单取主语言
const lang = normalizeLanguage(currentLang);
@@ -32,12 +35,16 @@ const LanguageSelector = ({ currentLang, onLanguageChange, t }) => {
return (
<Dropdown
trigger={['hover', 'click']}
{...dropdownProps}
placement='bottomRight'
popupRender={(menu) => <div {...popupProps}>{menu}</div>}
menu={{
selectable: true,
selectedKeys: [lang],
onClick: ({ key }) => onLanguageChange(key),
onClick: ({ key }) => {
close();
onLanguageChange(key);
},
items: languages.map(({ code, endonym, flag }) => {
const Flag = FLAGS[flag];
return {
@@ -49,10 +56,10 @@ const LanguageSelector = ({ currentLang, onLanguageChange, t }) => {
}}
>
<AntButton
{...triggerProps}
type='text'
icon={<ActionGlobe size={16} strokeWidth={1.5} aria-hidden />}
aria-label={t('common.changeLanguage')}
aria-haspopup='menu'
className='ui-header-icon-action'
/>
</Dropdown>
@@ -1,22 +1,23 @@
import { Compass as ActionCompass } from '@/components/common/icons/ActionIcons';
import React, { useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useLocation } from 'react-router-dom';
import { Button, Dropdown } from 'antd';
import { ExternalLink } from 'lucide-react';
import { isNavigationPathActive } from '../../console/consoleRoutes';
/**
* 移动端主导航入口。
*
* 顶栏宽度在手机上只够放「logo + 主操作 + 工具图标 + 头像」,
* 主导航若继续内联平铺会把右侧按钮挤成一团(横向滚动条也不可见、不可发现)。
* 因此 <768px 时把 mainNavLinks 收进这个下拉菜单,跟主流控制台的做法保持一致。
* 窄空间主导航入口:手机直接使用,桌面顶栏在平铺项放不下时复用。
*
* 目标路径/外链的推导逻辑必须与桌面端 Navigation 保持一致,避免两端跳转不同。
*/
const MobileNavMenu = ({ mainNavLinks, userState, t }) => {
const MobileNavMenu = ({
mainNavLinks,
userState,
followTopLink,
t,
compact,
}) => {
const location = useLocation();
const navigate = useNavigate();
const [visible, setVisible] = useState(false);
if (!mainNavLinks || mainNavLinks.length === 0) {
@@ -88,7 +89,7 @@ const MobileNavMenu = ({ mainNavLinks, userState, t }) => {
if (item.externalLink) {
window.open(item.externalLink, '_blank', 'noopener,noreferrer');
} else if (item.to) {
navigate(item.to);
followTopLink(item.to);
}
},
label: (
@@ -108,13 +109,17 @@ const MobileNavMenu = ({ mainNavLinks, userState, t }) => {
<Button
type='text'
aria-label={t('主导航')}
title={activeItem?.text}
title={compact ? t('主导航') : activeItem?.text}
aria-haspopup='menu'
aria-expanded={visible}
icon={<ActionCompass size={16} />}
className='ml-1 px-2 max-w-[9rem] [&_.ant-btn-content]:min-w-0'
icon={<ActionCompass size={16} aria-hidden />}
className={
compact
? 'ui-header-compact-nav'
: 'ml-1 min-w-0 px-2 max-w-[9rem] [&_.ant-btn-content]:min-w-0'
}
>
<span className='ml-1 text-[13px] font-semibold truncate'>
<span className='ui-header-compact-label block text-[13px] font-semibold truncate'>
{activeItem?.mobileText || activeItem?.text || t('导航')}
</span>
</Button>
+63 -6
View File
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useLayoutEffect, useRef, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { Dropdown } from 'antd';
import {
@@ -7,11 +7,45 @@ import {
} from '@/components/common/icons/ActionIcons';
import { useTranslation } from 'react-i18next';
import SkeletonWrapper from '../components/SkeletonWrapper';
import MobileNavMenu from './MobileNavMenu';
import { isNavigationPathActive } from '../../console/consoleRoutes';
const Navigation = ({ mainNavLinks, isMobile, isLoading, userState }) => {
const Navigation = ({ mainNavLinks, isLoading, userState, followTopLink }) => {
const location = useLocation();
const { t } = useTranslation();
const slotRef = useRef(null);
const itemsRef = useRef(null);
const restoreFocus = useRef(false);
const [compact, setCompact] = useState(false);
useLayoutEffect(() => {
const slot = slotRef.current;
const items = itemsRef.current;
if (restoreFocus.current) {
const target = compact
? slot.querySelector('.ui-header-compact-nav')
: items.querySelector('[aria-current="page"]') ||
items.querySelector('a, button');
target?.focus({ preventScroll: true });
restoreFocus.current = false;
}
// 轨道保持自然宽度,收起后仍可测量,不会因按钮变窄而反复切换。
const measure = () => {
const next =
items.getBoundingClientRect().width >
slot.getBoundingClientRect().width;
if (next !== compact) {
restoreFocus.current = slot.contains(document.activeElement);
setCompact(next);
}
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(slot);
observer.observe(items);
return () => observer.disconnect();
}, [compact]);
const renderNavLinks = () => {
const baseClasses =
@@ -19,7 +53,7 @@ const Navigation = ({ mainNavLinks, isMobile, isLoading, userState }) => {
const defaultClasses = 'text-gray-600 dark:text-neutral-300';
const hoverClasses = 'hover:text-brand-deep dark:hover:text-brand-from';
const activeClasses = 'text-brand-deep dark:text-brand-from';
const spacingClasses = isMobile ? 'px-2 py-1 text-sm' : 'px-4 py-2';
const spacingClasses = 'px-4 py-2';
// Match on full path segments so /market doesn't light up on /market-detail
const isPathActive = (matchPath) =>
@@ -61,7 +95,14 @@ const Navigation = ({ mainNavLinks, isMobile, isLoading, userState }) => {
.map((item) => item.itemKey),
items: link.items.map((subItem) => ({
key: subItem.itemKey,
label: <Link to={subItem.to}>{subItem.text}</Link>,
label: (
<Link
to={subItem.to}
onClick={(event) => followTopLink(subItem.to, event)}
>
{subItem.text}
</Link>
),
})),
}}
>
@@ -97,6 +138,7 @@ const Navigation = ({ mainNavLinks, isMobile, isLoading, userState }) => {
<Link
key={link.itemKey}
to={targetPath}
onClick={(event) => followTopLink(targetPath, event)}
className={finalClasses}
aria-current={isActive ? 'page' : undefined}
>
@@ -107,21 +149,36 @@ const Navigation = ({ mainNavLinks, isMobile, isLoading, userState }) => {
};
return (
<div className='ui-header-navigation-slot' ref={slotRef}>
<nav
className='ui-header-navigation'
aria-label={t('主导航')}
className='ui-header-navigation flex flex-1 items-center gap-1 lg:gap-2 mx-1 sm:mx-3 md:mx-6 overflow-x-auto whitespace-nowrap scrollbar-hide min-w-0'
aria-hidden={compact || undefined}
inert={compact ? '' : undefined}
>
<div className='ui-header-navigation-items' ref={itemsRef}>
<SkeletonWrapper
key={compact ? 'measure' : 'navigate'}
loading={isLoading && mainNavLinks.length === 0}
type='navigation'
count={4}
width={60}
height={16}
isMobile={isMobile}
>
{renderNavLinks()}
</SkeletonWrapper>
</div>
</nav>
{compact && (
<MobileNavMenu
compact
mainNavLinks={mainNavLinks}
userState={userState}
followTopLink={followTopLink}
t={t}
/>
)}
</div>
);
};
@@ -1,9 +1,12 @@
import React from 'react';
import React, { useRef } from 'react';
import { Button, Tooltip } from 'antd';
import { Moon, Sun } from '../../common/icons/ActionIcons';
import { useActualTheme } from '../../../context/Theme';
const THEME_TOGGLE_INTERVAL = 350;
const ThemeToggle = ({ onThemeToggle, t }) => {
const lastToggle = useRef(-Infinity);
const isDark = useActualTheme() === 'dark';
const label = isDark ? t('切换至亮色主题') : t('切换至暗色主题');
const Icon = isDark ? Sun : Moon;
@@ -15,7 +18,12 @@ const ThemeToggle = ({ onThemeToggle, t }) => {
icon={<Icon size={16} strokeWidth={1.5} aria-hidden />}
aria-label={t('切换主题')}
className='ui-header-icon-action'
onClick={() => onThemeToggle(isDark ? 'light' : 'dark')}
onClick={() => {
const now = performance.now();
if (now - lastToggle.current < THEME_TOGGLE_INTERVAL) return;
lastToggle.current = now;
onThemeToggle(isDark ? 'light' : 'dark');
}}
/>
</Tooltip>
);
+11 -16
View File
@@ -1,10 +1,11 @@
import { ChevronDown as ActionChevronDown } from '@/components/common/icons/ActionIcons';
import React, { useState } from 'react';
import React from 'react';
import { Avatar, Button as AntButton, Dropdown as AntDropdown } from 'antd';
import { UserRound, KeyRound, LogOut } from 'lucide-react';
import { getUserAvatarUrl } from '../../../helpers';
import SkeletonWrapper from '../components/SkeletonWrapper';
import { isHeaderModuleEnabled } from '../../../constants/headerNavModules';
import { useHeaderDropdown } from './useHeaderDropdown';
// 头像菜单项:图标框 + 标题 + 说明(原型 account-menu-label)
const AccountMenuLabel = ({ icon, tone, title, description }) => (
@@ -30,10 +31,11 @@ const UserArea = ({
sidebarModulesAdmin = {},
isOrgUser = false,
logout,
navigate,
followTopLink,
t,
}) => {
const [open, setOpen] = useState(false);
const { open, close, dropdownProps, popupProps, triggerProps } =
useHeaderDropdown(isMobile);
const isActionVisible = (key) => rightActions?.[key] !== false;
const hasHeaderModuleConfig =
headerNavModules && Object.keys(headerNavModules).length > 0;
@@ -84,7 +86,7 @@ const UserArea = ({
description={t('管理账户信息')}
/>
),
onClick: () => navigate('/user-center/settings'),
onClick: () => followTopLink('/user-center/settings'),
});
}
if (showKeyManagement) {
@@ -98,7 +100,7 @@ const UserArea = ({
description={t('查看和管理 API 密钥')}
/>
),
onClick: () => navigate('/user-center/key-management'),
onClick: () => followTopLink('/user-center/key-management'),
});
}
items.push({ key: 'account-divider', type: 'divider' });
@@ -117,13 +119,11 @@ const UserArea = ({
return (
<AntDropdown
trigger={['hover', 'click']}
{...dropdownProps}
placement='bottomRight'
open={open}
onOpenChange={setOpen}
menu={{ items, onClick: () => setOpen(false) }}
menu={{ items, onClick: close }}
popupRender={(menu) => (
<div className='ui-account-panel'>
<div {...popupProps} className='ui-account-panel'>
<div className='ui-account-summary'>
<Avatar
shape='square'
@@ -143,12 +143,7 @@ const UserArea = ({
)}
classNames={{ root: 'ui-account-dropdown' }}
>
<AntButton
type='text'
className='ui-header-account'
aria-haspopup='menu'
aria-expanded={open}
>
<AntButton {...triggerProps} type='text' className='ui-header-account'>
<Avatar
shape='square'
size={38}
+5 -5
View File
@@ -4,6 +4,7 @@ import { isAuthPagePath } from '../../../helpers/auth';
import { useHeaderBar } from '../../../hooks/common/useHeaderBar';
import { useNotifications } from '../../../hooks/common/useNotifications';
import { useNavigation } from '../../../hooks/common/useNavigation';
import { useTopNavigation } from '../../../hooks/common/useTopNavigation';
import { usePartnerWorkspaceEntry } from '../../../hooks/common/usePartnerWorkspaceEntry';
import MobileMenuButton from './MobileMenuButton';
import HeaderLogo from './HeaderLogo';
@@ -33,7 +34,6 @@ const HeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
docsLink,
isDemoSiteMode,
isConsoleRoute,
theme,
headerNavModules,
sidebarModulesAdmin,
showOrgEntry,
@@ -43,7 +43,6 @@ const HeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
handleLanguageChange,
handleThemeToggle,
handleMobileMenuToggle,
navigate,
t,
} = useHeaderBar({ onMobileMenuToggle, drawerOpen });
@@ -69,6 +68,7 @@ const HeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
const mainNavLinks = configuredNavLinks.filter(
(link) => link.itemKey !== 'keyManagement',
);
const followTopLink = useTopNavigation();
const [hasOpenedNotice, setHasOpenedNotice] = useState(false);
useEffect(() => {
@@ -146,6 +146,7 @@ const HeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
<MobileNavMenu
mainNavLinks={mainNavLinks}
userState={userState}
followTopLink={followTopLink}
t={t}
/>
)}
@@ -154,9 +155,9 @@ const HeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
{!isAuthPage && !isMobile && (
<Navigation
mainNavLinks={mainNavLinks}
isMobile={isMobile}
isLoading={isLoading}
userState={userState}
followTopLink={followTopLink}
/>
)}
@@ -165,7 +166,6 @@ const HeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
isNewYear={isNewYear}
unreadCount={unreadCount}
onNoticeOpen={handleNoticeOpen}
theme={theme}
onThemeToggle={handleThemeToggle}
currentLang={currentLang}
onLanguageChange={handleLanguageChange}
@@ -176,7 +176,7 @@ const HeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
sidebarModulesAdmin={sidebarModulesAdmin}
isOrgUser={isOrgUser}
logout={logout}
navigate={navigate}
followTopLink={followTopLink}
t={t}
/>
</div>
@@ -0,0 +1,93 @@
import { useCallback, useEffect, useRef, useState } from 'react';
const HOVER_DELAY = 100;
const CLICK_INTERVAL = 240;
export function useHeaderDropdown(isMobile) {
const [mode, setMode] = useState(null);
const triggerRef = useRef(null);
const popupRef = useRef(null);
const hoverTimer = useRef();
const lastClick = useRef(-Infinity);
const open = mode !== null;
const close = useCallback(() => {
clearTimeout(hoverTimer.current);
lastClick.current = -Infinity;
setMode(null);
}, []);
useEffect(() => () => clearTimeout(hoverTimer.current), []);
useEffect(() => {
if (!open) return;
const handleOutsidePress = (event) => {
if (
!triggerRef.current?.contains(event.target) &&
!popupRef.current?.contains(event.target)
) {
close();
}
};
document.addEventListener('pointerdown', handleOutsidePress, true);
return () =>
document.removeEventListener('pointerdown', handleOutsidePress, true);
}, [close, open]);
const queueHoverChange = (event, opening) => {
if (isMobile || event.pointerType !== 'mouse') return;
clearTimeout(hoverTimer.current);
if (opening ? open : mode !== 'hover') return;
hoverTimer.current = setTimeout(() => {
setMode((current) => {
if (opening) return current ?? 'hover';
return current === 'hover' ? null : current;
});
}, HOVER_DELAY);
};
const handleEscape = (event) => {
if (event.key !== 'Escape' || !open) return;
event.stopPropagation();
close();
if (popupRef.current?.contains(event.target)) triggerRef.current?.focus();
};
const pointerEvents = {
onPointerEnter: (event) => queueHoverChange(event, true),
onPointerLeave: (event) => queueHoverChange(event, false),
};
return {
open,
close,
dropdownProps: {
trigger: [],
transitionName: '',
open,
autoFocus: mode === 'keyboard',
onOpenChange: (nextOpen) => {
if (!nextOpen) close();
},
},
popupProps: { ...pointerEvents, ref: popupRef, onKeyDown: handleEscape },
triggerProps: {
...pointerEvents,
ref: triggerRef,
'aria-haspopup': 'menu',
'aria-expanded': open,
onKeyDown: handleEscape,
onClick: (event) => {
const now = performance.now();
if (now - lastClick.current < CLICK_INTERVAL) return;
lastClick.current = now;
clearTimeout(hoverTimer.current);
const clickedMode = event.detail === 0 ? 'keyboard' : 'click';
setMode((current) =>
current === null || current === 'hover' ? clickedMode : null,
);
},
},
};
}
@@ -22,6 +22,9 @@ import { API, showError, showSuccess, copy } from '../../helpers';
const { Text, Title, Paragraph } = Typography;
// 暂时隐藏推广弹窗里的邀请奖励规则入口。
const SHOW_INVITATION_REWARD_RULES = false;
// 默认海报模板配置
const DEFAULT_TEMPLATES = [
{ id: 'blue', name: '科技蓝' },
@@ -449,6 +452,7 @@ const PromotionPosterModal = ({ visible, onClose }) => {
title={t('邀请链接获取中,请稍后')}
/>
)}
{SHOW_INVITATION_REWARD_RULES && (
<button
type='button'
className='pm-rewards'
@@ -466,6 +470,7 @@ const PromotionPosterModal = ({ visible, onClose }) => {
</span>
<ChevronRight size={18} aria-hidden />
</button>
)}
</>
)}
</Modal>
+35 -20
View File
@@ -8,8 +8,11 @@
--pm-border: var(--border-subtle);
--pm-accent: var(--brand-primary);
--pm-soft: var(--brand-primary-soft);
--pm-qr-surface: #fff;
--pm-poster-ink: #fff;
--pm-qr-surface: var(--ui-color-white);
--pm-poster-ink: var(--ui-color-white);
--pm-body-max-height: calc(100dvh - 200px);
--pm-tab-panel-height: 448px;
--pm-preview-min-height: 418px;
max-width: calc(100vw - 32px);
padding-block: 24px;
}
@@ -29,23 +32,44 @@
right: 24px;
}
.promotion-modal .ant-modal-body {
max-height: calc(100dvh - 160px);
max-height: var(--pm-body-max-height);
overflow-y: auto;
overscroll-behavior: contain;
}
.promotion-tabs {
max-block-size: var(--pm-body-max-height);
}
.promotion-tabs > .ant-tabs-nav {
flex-shrink: 0;
margin-bottom: 24px;
}
.promotion-tabs > .ant-tabs-body-holder {
flex: 0 1 var(--pm-tab-panel-height);
min-block-size: 0;
overflow-y: auto;
overscroll-behavior: contain;
scrollbar-gutter: stable;
}
.pm-tab-label {
display: inline-flex;
align-items: center;
gap: 8px;
}
.pm-link-layout {
.pm-link-layout,
.pm-poster-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1.15fr);
gap: 32px;
align-items: stretch;
align-items: start;
}
.pm-invitation-card,
.pm-preview-stage {
min-block-size: var(--pm-preview-min-height);
border-radius: 12px;
}
.pm-share-details,
.pm-poster-options {
align-self: center;
}
.pm-invitation-card {
display: flex;
@@ -53,7 +77,6 @@
align-items: center;
padding: 28px 20px;
border: 1px solid var(--pm-border);
border-radius: 12px;
background: var(--pm-muted);
text-align: center;
min-width: 0;
@@ -195,12 +218,6 @@
flex-shrink: 0;
color: var(--pm-secondary);
}
.pm-poster-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
gap: 32px;
align-items: center;
}
.promotion-modal [data-poster-template='blue'] {
--pm-template-background: #2455b8;
}
@@ -217,7 +234,6 @@
display: flex;
justify-content: center;
padding-inline: 16px;
border-radius: 12px;
background: var(--pm-template-background);
color: var(--pm-poster-ink);
min-width: 0;
@@ -228,8 +244,7 @@
align-items: center;
width: min(100%, 280px);
min-width: 0;
min-height: 448px;
padding: 32px 8px 24px;
padding: 28px 8px 20px;
text-align: center;
overflow-wrap: anywhere;
}
@@ -246,7 +261,7 @@
color: inherit;
}
.pm-poster h3 {
margin: 20px 0;
margin: 16px 0;
font-size: 16px;
line-height: 1.5;
color: inherit;
@@ -312,6 +327,10 @@
outline-offset: 3px;
}
@media (max-width: 600px) {
.promotion-modal.ant-modal {
--pm-tab-panel-height: 760px;
--pm-preview-min-height: 395px;
}
.promotion-modal .ant-modal-container {
padding: 20px;
}
@@ -322,9 +341,6 @@
top: 18px;
right: 16px;
}
.promotion-modal .ant-modal-body {
max-height: calc(100dvh - 136px);
}
.pm-link-layout,
.pm-poster-layout {
grid-template-columns: minmax(0, 1fr);
@@ -344,7 +360,6 @@
width: 100%;
}
.pm-poster {
min-height: 408px;
padding-block: 24px 20px;
}
.pm-template-list {
+6
View File
@@ -8,6 +8,7 @@ import ModelSettingsVisualEditor from '../../pages/Setting/Ratio/ModelSettingsVi
import ModelRatioNotSetEditor from '../../pages/Setting/Ratio/ModelRationNotSetEditor';
import UpstreamRatioSync from '../../pages/Setting/Ratio/UpstreamRatioSync';
import ModelOfficialPriceSettings from '../../pages/Setting/Ratio/ModelOfficialPriceSettings';
import OfficialPriceExchangeRateSetting from '../../pages/Setting/Ratio/OfficialPriceExchangeRateSetting';
import ModelCostSettings from '../../pages/Setting/Ratio/ModelCostSettings';
import { API, isRoot, showError, toBoolean } from '../../helpers';
@@ -23,6 +24,7 @@ const RatioSetting = () => {
GroupRatio: '',
GroupGroupRatio: '',
ModelOfficialPrice: '',
OfficialPriceExchangeRate: '',
ImageRatio: '',
AudioRatio: '',
AudioCompletionRatio: '',
@@ -101,6 +103,10 @@ const RatioSetting = () => {
入口——否则被下放 tab 的普通管理员会看到一个填了存不进去的页面。 */}
{isRoot() && (
<Tabs.TabPane tab={t('模型原厂价格')} itemKey='official_price'>
<OfficialPriceExchangeRateSetting
options={inputs}
refresh={onRefresh}
/>
<ModelOfficialPriceSettings
options={inputs}
refresh={onRefresh}
+1 -1
View File
@@ -20,7 +20,7 @@ const kindText = (t, kind) =>
judge: {
title: t('智能判定'),
desc: t(
'把脱敏、截断后的请求片段发送给境外判定服务(Jev),用于选择合适的模型。',
'将脱敏、截断后的请求片段发送至境外判定服务,用于选择合适的模型。',
),
},
eval: {
+20 -9
View File
@@ -16,6 +16,7 @@ import {
import { ConsoleAlert as Alert } from '../console/ConsolePrimitives';
import { showError, showSuccess } from '../../helpers';
import { getAdminStatus, loadOptions, saveOption, setJevKey } from './api';
import JevProxySettings from './JevProxySettings';
const { Text } = Typography;
const { TextArea } = Input;
@@ -50,7 +51,7 @@ const FIELDS = [
{
key: 'jev_egress_allowed',
type: 'bool',
label: '允许调用 Jev(数据出境,合规评估通过后开启)',
label: '允许调用境外判定模型(通过合规评估后开启)',
section: 'jev',
compliance: true,
},
@@ -98,7 +99,7 @@ const FIELDS = [
{
key: 'state_max_bytes',
type: 'int',
label: '发给 Jev 的内容上限(字节)',
label: '发送给判定模型的内容上限(字节)',
min: 1000,
max: 30000,
section: 'jev',
@@ -184,7 +185,7 @@ const FIELDS = [
{
key: 'jev_daily_cap_per_user',
type: 'int',
label: 'Jev 判定每人每日上限(0 不限)',
label: '每人每日模型判定次数上限(0 表示不限)',
min: 0,
max: 10000000,
section: 'retention',
@@ -192,7 +193,7 @@ const FIELDS = [
{
key: 'jev_daily_cap_per_org',
type: 'int',
label: 'Jev 判定每企业每日上限(0 不限)',
label: '每个企业每日模型判定次数上限(0 表示不限)',
min: 0,
max: 100000000,
section: 'retention',
@@ -201,7 +202,7 @@ const FIELDS = [
const SECTIONS = [
['main', '总控'],
['jev', 'Jev 判定'],
['jev', '判定模型'],
['judge', '判定参数'],
['consent', '同意文案'],
['retention', '保留与限流'],
@@ -266,7 +267,7 @@ const GlobalSettings = () => {
await saveOption(PREFIX + f.key, String(values[f.key] ?? ''));
saved[f.key] = values[f.key];
} catch (e) {
showError(`${t(f.label)} · ${e?.message || ''}`);
showError(`${t(f.label)} · ${e?.message ? t(e.message) : ''}`);
// 已保存的项更新基线,未保存的编辑保留在表单里,便于修改后重试
setOriginal((o) => ({ ...o, ...saved }));
return;
@@ -293,7 +294,9 @@ const GlobalSettings = () => {
if (!clear) return run();
Modal.confirm({
title: t('确认清除密钥?'),
content: t('清除后该通道无法调用 Jev,判定会降级为规则判定。'),
content: t(
'清除后,此通道将无法调用判定模型。所有通道均不可用时,将使用规则判定。',
),
okButtonProps: { danger: true },
onOk: run,
});
@@ -425,7 +428,7 @@ const GlobalSettings = () => {
</span>
</Tag>
<Tag>
{t('Jev 降级次数')}{' '}
{t('模型判定失败后使用规则的次数')}{' '}
<span className='smart-router-num'>{status.jev_fallback}</span>
</Tag>
<Tag color={status.not_ready ? 'warning' : 'default'}>
@@ -444,7 +447,7 @@ const GlobalSettings = () => {
type='warning'
showIcon
title={t(
'标注「合规」的配置项只有超级管理员可以修改。开启 Jev 出境前须完成合规评估。',
'标注「合规」的配置项仅限超级管理员修改。启用境外判定模型前须完成合规评估。',
)}
/>
{SECTIONS.map(([sec, title]) => (
@@ -474,6 +477,14 @@ const GlobalSettings = () => {
{renderField(f)}
</Form.Item>
))}
{sec === 'jev' && (
<JevProxySettings
saved={status?.jev_proxy}
onSaved={(jev_proxy) =>
setStatus((previous) => ({ ...previous, jev_proxy }))
}
/>
)}
{sec === 'jev' &&
['typesafe', 'openrouter'].map((p) => (
<Form.Item
@@ -0,0 +1,137 @@
import React, { useState } from 'react';
import {
Alert,
Button,
Form,
Input,
Popconfirm,
Space,
Typography,
} from 'antd';
import { useTranslation } from 'react-i18next';
import { getCountryName } from '@/constants/countries';
import { showSuccess } from '@/helpers';
import { clearJevProxy, saveJevProxy, testJevProxy } from './api';
export default function JevProxySettings({ saved, onSaved }) {
const { t, i18n } = useTranslation();
const [draft, setDraft] = useState('');
const [pending, setPending] = useState('');
const [result, setResult] = useState(null);
const [error, setError] = useState('');
const url = draft.trim();
const busy = Boolean(pending);
async function run(action) {
setPending(action);
setError('');
setResult(null);
try {
if (action === 'test') {
setResult(await testJevProxy(url));
} else {
const next =
action === 'save' ? await saveJevProxy(url) : await clearJevProxy();
onSaved(next);
setDraft('');
showSuccess(action === 'save' ? t('已保存') : t('已清除'));
}
} catch (e) {
setError(t(e.message));
} finally {
setPending('');
}
}
const google = result?.google;
const egress = result?.egress;
const reasons = {
timeout: t('连接超时'),
tls: t('TLS 证书校验失败'),
proxy_auth: t('代理认证失败'),
connection: t('代理连接失败'),
http_status: `HTTP ${google?.http_status}`,
};
return (
<Form.Item
label={t('判定模型专用代理')}
htmlFor='jev-proxy-url'
className='smart-router-proxy'
>
<Space orientation='vertical' size={8} className='smart-router-key-tools'>
<Typography.Text type='secondary'>
{t('仅用于调用判定模型。')}{' '}
{saved?.configured
? saved.address || t('已配置')
: t('跟随服务器网络设置')}
</Typography.Text>
<Input.Password
id='jev-proxy-url'
autoComplete='new-password'
placeholder='http:// · https:// · socks5:// · socks5h://'
value={draft}
disabled={busy}
onChange={(e) => {
setDraft(e.target.value);
setResult(null);
setError('');
}}
/>
<Space wrap>
<Button
onClick={() => run('test')}
loading={pending === 'test'}
disabled={busy || (!url && !saved?.configured)}
>
{t('测试代理')}
</Button>
<Button
onClick={() => run('save')}
loading={pending === 'save'}
disabled={busy || !url}
>
{t('保存代理')}
</Button>
<Popconfirm
title={t('确认清除判定模型代理?')}
onConfirm={() => run('clear')}
disabled={busy || !saved?.configured}
>
<Button
danger
loading={pending === 'clear'}
disabled={busy || !saved?.configured}
>
{t('清除代理')}
</Button>
</Popconfirm>
</Space>
{error && <Alert type='error' showIcon title={error} />}
{google && (
<Alert
showIcon
type={google.connected ? 'success' : 'error'}
title={
<span role='status'>
{google.connected ? t('Google 已连通') : t('Google 未连通')} ·{' '}
{google.elapsed_ms} ms
{google.error &&
` · ${reasons[google.error] || reasons.connection}`}
</span>
}
description={
egress?.ip
? t('出口 IP {{ip}} · {{region}}', {
ip: egress.ip,
region:
getCountryName(egress.country_code, i18n.language) ||
t('地区未知'),
})
: t('出口 IP 未获取')
}
/>
)}
</Space>
</Form.Item>
);
}
+12 -7
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import React, { useEffect, useId, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Alert,
@@ -207,6 +207,7 @@ const ProfileEditor = ({
onSaved,
}) => {
const { t } = useTranslation();
const judgeHelpId = useId();
const [state, setState] = useState(() => toState(profile, t));
const [saving, setSaving] = useState(false);
const [activePanels, setActivePanels] = useState([
@@ -891,14 +892,18 @@ const ProfileEditor = ({
size='small'
checked={state.jev_allowed}
onChange={(v) => set('jev_allowed', v)}
aria-label={t(
'允许使用 Jev 判定(还需平台开启与出境同意)',
)}
aria-label={t('允许使用判定模型')}
aria-describedby={judgeHelpId}
/>
<Text>
{t('允许使用 Jev 判定(还需平台开启与出境同意)')}
</Text>
<Text>{t('允许使用判定模型')}</Text>
</div>
<Text
id={judgeHelpId}
type='secondary'
className='smart-router-sub'
>
{t('需平台开启模型判定,并取得相应的数据出境授权。')}
</Text>
</div>
),
},
+1 -1
View File
@@ -118,7 +118,7 @@ const ProfileTable = ({ mode, orgId, canWrite = true, emptyHint }) => {
)}
{r.jev_allowed && (
<Tag color='blue' variant='filled'>
Jev
{t('允许模型判定')}
</Tag>
)}
</Space>
+13
View File
@@ -130,5 +130,18 @@ export const setJevKey = (provider, key, clear = false) =>
export const loadOptions = () => call(() => API.get('/api/option/', opts()));
const jevProxyPath = '/api/router/admin/jev-proxy';
export const saveJevProxy = (url) =>
call(() => API.put(jevProxyPath, { url }, opts()));
export const clearJevProxy = () => call(() => API.delete(jevProxyPath, opts()));
export const testJevProxy = (url) =>
call(() =>
API.post(
jevProxyPath + '/test',
url ? { source: 'draft', url } : { source: 'saved' },
opts(),
),
);
export const saveOption = (key, value) =>
call(() => API.put('/api/option/', { key, value }, opts()));
+7 -7
View File
@@ -35,17 +35,17 @@ export const jevReasonText = (t, code) => {
export const gateText = (t, code) =>
({
jev: t('已调用 Jev'),
platform_off: t('平台未开启 Jev 出境'),
jev: t('已调用模型'),
platform_off: t('平台未开启境外模型判定'),
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 判定次数已达上限'),
profile_off: t('此集合未开启模型判定'),
no_quota: t('余额不足,未调用模型'),
jev_cap: t('今日模型判定次数已达上限'),
desens_residual: t('脱敏后仍有敏感信息'),
'n/a': t('未经过闸门'),
})[code] ||
@@ -54,10 +54,10 @@ export const gateText = (t, code) =>
export const srcText = (t, code) =>
({
jev: t('Jev 判定'),
jev: t('智能路由'),
cache: t('判定缓存'),
rules: t('规则判定器'),
rules_fallback: t('Jev 失败,规则判定'),
rules_fallback: t('模型判定失败,已使用规则'),
rule: t('自定义规则'),
rule_tier: t('自定义规则强制档位'),
forced: t('请求指定档位'),
@@ -295,6 +295,12 @@
width: 100%;
}
.smart-router-proxy {
grid-column: 1 / -1;
min-width: 0;
overflow-wrap: anywhere;
}
.smart-router-key-input {
width: min(320px, 100%);
}
@@ -155,6 +155,7 @@ const originInputs = {
thinking_to_content: false,
proxy: '',
pass_through_body_enabled: false,
pass_through_model_mapping_enabled: false,
chat_image_to_images_enabled: false,
system_prompt: '',
system_prompt_override: false,
@@ -404,6 +405,7 @@ const EditChannelModal = (props) => {
thinking_to_content: false,
proxy: '',
pass_through_body_enabled: false,
pass_through_model_mapping_enabled: false,
chat_image_to_images_enabled: false,
system_prompt: '',
system_prompt_override: false,
@@ -602,6 +604,8 @@ const EditChannelModal = (props) => {
data.proxy = parsedSettings.proxy || '';
data.pass_through_body_enabled =
parsedSettings.pass_through_body_enabled || false;
data.pass_through_model_mapping_enabled =
parsedSettings.pass_through_model_mapping_enabled === true;
data.chat_image_to_images_enabled =
parsedSettings.chat_image_to_images_enabled || false;
data.system_prompt = parsedSettings.system_prompt || '';
@@ -643,6 +647,7 @@ const EditChannelModal = (props) => {
data.thinking_to_content = false;
data.proxy = '';
data.pass_through_body_enabled = false;
data.pass_through_model_mapping_enabled = false;
data.chat_image_to_images_enabled = false;
data.system_prompt = '';
data.system_prompt_override = false;
@@ -665,6 +670,7 @@ const EditChannelModal = (props) => {
data.thinking_to_content = false;
data.proxy = '';
data.pass_through_body_enabled = false;
data.pass_through_model_mapping_enabled = false;
data.chat_image_to_images_enabled = false;
data.system_prompt = '';
data.system_prompt_override = false;
@@ -778,6 +784,8 @@ const EditChannelModal = (props) => {
thinking_to_content: data.thinking_to_content,
proxy: data.proxy,
pass_through_body_enabled: data.pass_through_body_enabled,
pass_through_model_mapping_enabled:
data.pass_through_model_mapping_enabled,
chat_image_to_images_enabled:
data.chat_image_to_images_enabled || false,
system_prompt: data.system_prompt,
@@ -1065,6 +1073,7 @@ const EditChannelModal = (props) => {
thinking_to_content: false,
proxy: '',
pass_through_body_enabled: false,
pass_through_model_mapping_enabled: false,
chat_image_to_images_enabled: false,
system_prompt: '',
system_prompt_override: false,
@@ -1394,6 +1403,8 @@ const EditChannelModal = (props) => {
thinking_to_content: localInputs.thinking_to_content || false,
proxy: localInputs.proxy || '',
pass_through_body_enabled: localInputs.pass_through_body_enabled || false,
pass_through_model_mapping_enabled:
localInputs.pass_through_model_mapping_enabled === true,
chat_image_to_images_enabled:
localInputs.chat_image_to_images_enabled || false,
system_prompt: localInputs.system_prompt || '',
@@ -1499,6 +1510,7 @@ const EditChannelModal = (props) => {
delete localInputs.thinking_to_content;
delete localInputs.proxy;
delete localInputs.pass_through_body_enabled;
delete localInputs.pass_through_model_mapping_enabled;
delete localInputs.chat_image_to_images_enabled;
delete localInputs.client_only;
delete localInputs.os_restriction;
@@ -3514,6 +3526,22 @@ const EditChannelModal = (props) => {
extraText={t('启用请求体透传功能')}
/>
<Form.Switch
field='pass_through_model_mapping_enabled'
label={t('透传时应用模型映射')}
checkedText={t('开')}
uncheckedText={t('关')}
onChange={(value) =>
handleChannelSettingsChange(
'pass_through_model_mapping_enabled',
value,
)
}
extraText={t(
'请求体透传时,使用本渠道模型重定向后的模型名发送给上游,其余字段按原请求转发。',
)}
/>
{(inputs.type === 1 || inputs.type === 3) && (
<Form.Switch
field='chat_image_to_images_enabled'
@@ -46,7 +46,9 @@ function TagEditorSection({ icon, color, title, description, children }) {
</Avatar>
<div>
<Text className='text-lg font-medium'>{title}</Text>
<div className='text-xs text-gray-600'>{description}</div>
<Text type='secondary' className='block text-xs'>
{description}
</Text>
</div>
</div>
{children}
@@ -1,17 +1,30 @@
import React from 'react';
import React, { useState } from 'react';
import { Button } from 'antd';
import { Copy, Plus, Trash2 } from '@/components/common/icons/ActionIcons';
import { Button } from '@/components/ui';
import { isAdmin } from '../../../helpers';
const RedemptionsActions = ({
canQuery,
canCreate,
canDelete,
selectedKeys,
busy,
setEditingRedemption,
setShowEdit,
batchCopyRedemptions,
batchDeleteRedemptions,
t,
}) => {
// Add new redemption code
const [copying, setCopying] = useState(false);
const handleCopy = async () => {
setCopying(true);
try {
await batchCopyRedemptions();
} finally {
setCopying(false);
}
};
const handleAddRedemption = () => {
setEditingRedemption({
id: undefined,
@@ -21,23 +34,33 @@ const RedemptionsActions = ({
return (
<div className='console-list-tool-actions'>
<Button icon={<Copy size={16} />} onClick={batchCopyRedemptions}>
{canQuery && (
<Button
icon={<Copy size={16} aria-hidden />}
disabled={busy || selectedKeys.length === 0}
loading={copying}
onClick={handleCopy}
>
{t('复制所选兑换码到剪贴板')}
</Button>
)}
{isAdmin() && (
{canDelete && (
<Button
type='danger'
icon={<Trash2 size={16} />}
danger
className='redemption-invalid-action'
disabled={busy}
icon={<Trash2 size={16} aria-hidden />}
onClick={batchDeleteRedemptions}
>
{t('清除失效兑换码')}
</Button>
)}
{isAdmin() && (
{canCreate && (
<Button
type='primary'
icon={<Plus size={16} />}
className='console-create-action'
icon={<Plus size={16} aria-hidden />}
onClick={handleAddRedemption}
>
{t('添加兑换码')}
@@ -1,12 +1,6 @@
import React from 'react';
import { Tag, Button, Space, Popover, Dropdown } from '@/components/ui';
import { IconMore } from '@/components/ui/icons';
import {
renderQuota,
timestamp2string,
isAdmin,
hoverOrClickTrigger,
} from '../../../helpers';
import { Button, Tag, Tooltip } from 'antd';
import { renderQuota, timestamp2string } from '../../../helpers';
import {
REDEMPTION_STATUS,
REDEMPTION_STATUS_MAP,
@@ -27,156 +21,105 @@ export const isExpired = (record) => {
/**
* Render timestamp
*/
const renderTimestamp = (timestamp) => {
return <>{timestamp2string(timestamp)}</>;
};
export const formatRedemptionExpiry = (timestamp, t) =>
timestamp === 0 ? t('永不过期') : timestamp2string(timestamp);
/**
* Render redemption code status
*/
const renderStatus = (status, record, t) => {
export const renderRedemptionStatus = (status, record, t) => {
if (isExpired(record)) {
return (
<Tag color='orange' shape='circle'>
{t('已过期')}
</Tag>
);
return <Tag color='warning'>{t('已过期')}</Tag>;
}
const statusConfig = REDEMPTION_STATUS_MAP[status];
if (statusConfig) {
return (
<Tag color={statusConfig.color} shape='circle'>
{t(statusConfig.text)}
</Tag>
);
return <Tag color={statusConfig.color}>{t(statusConfig.text)}</Tag>;
}
return (
<Tag color='black' shape='circle'>
{t('未知状态')}
</Tag>
);
return <Tag>{t('未知状态')}</Tag>;
};
/**
* Get redemption code table column definitions
*/
export const getRedemptionsColumns = ({
canEdit,
canDelete,
t,
manageRedemption,
copyText,
setEditingRedemption,
setShowEdit,
refresh,
redemptions,
activePage,
showDetails,
showDeleteRedemptionModal,
}) => {
return [
{
title: t('ID'),
dataIndex: 'id',
width: 72,
},
{
title: t('名称'),
dataIndex: 'name',
width: 224,
ellipsis: { showTitle: false },
render: (name) => (
<Tooltip title={name}>
<span>{name}</span>
</Tooltip>
),
},
{
title: t('状态'),
dataIndex: 'status',
key: 'status',
render: (text, record) => {
return <div>{renderStatus(text, record, t)}</div>;
},
width: 120,
render: (status, record) => renderRedemptionStatus(status, record, t),
},
{
title: t('额度'),
dataIndex: 'quota',
render: (text) => {
return (
<div>
<Tag color='grey' shape='circle'>
{renderQuota(parseInt(text))}
</Tag>
</div>
);
},
width: 128,
align: 'right',
render: (quota) => renderQuota(parseInt(quota)),
},
{
title: t('创建时间'),
dataIndex: 'created_time',
render: (text) => {
return <div>{renderTimestamp(text)}</div>;
},
width: 180,
render: (timestamp) => timestamp2string(timestamp),
},
{
title: t('过期时间'),
dataIndex: 'expired_time',
render: (text) => {
return <div>{text === 0 ? t('永不过期') : renderTimestamp(text)}</div>;
},
width: 180,
render: (timestamp) => formatRedemptionExpiry(timestamp, t),
},
{
title: t('兑换人ID'),
dataIndex: 'used_user_id',
render: (text) => {
return <div>{text === 0 ? t('无') : text}</div>;
},
width: 128,
render: (id) => (id === 0 ? t('无') : id),
},
{
title: t('操作'),
dataIndex: 'operate',
fixed: 'right',
width: 205,
render: (text, record) => {
// Create dropdown menu items for more operations
const moreMenuItems = [
{
node: 'item',
name: t('删除'),
type: 'danger',
onClick: () => {
showDeleteRedemptionModal(record);
},
},
];
if (record.status === REDEMPTION_STATUS.UNUSED && !isExpired(record)) {
moreMenuItems.push({
node: 'item',
name: t('禁用'),
type: 'warning',
onClick: () => {
manageRedemption(record.id, REDEMPTION_ACTIONS.DISABLE, record);
},
});
} else if (!isExpired(record)) {
moreMenuItems.push({
node: 'item',
name: t('启用'),
type: 'secondary',
onClick: () => {
manageRedemption(record.id, REDEMPTION_ACTIONS.ENABLE, record);
},
disabled: record.status === REDEMPTION_STATUS.USED,
});
}
const isUnused = record.status === REDEMPTION_STATUS.UNUSED;
return (
<Space>
<Popover
// 触屏必须 click:这是查看兑换码明文的唯一入口
trigger={hoverOrClickTrigger()}
content={record.key}
style={{ padding: 20 }}
position='top'
<div className='console-module-row-actions redemption-row-actions'>
<Button
type='link'
size='small'
onClick={() => showDetails(record)}
>
<Button type='tertiary' size='small'>
{t('查看')}
</Button>
</Popover>
<Button
type='link'
size='small'
onClick={async () => {
await copyText(record.key);
@@ -184,29 +127,50 @@ export const getRedemptionsColumns = ({
>
{t('复制')}
</Button>
{isAdmin() && (
{canEdit && (
<>
<Button
type='tertiary'
type='link'
size='small'
onClick={() => {
setEditingRedemption(record);
setShowEdit(true);
}}
disabled={record.status !== REDEMPTION_STATUS.UNUSED}
disabled={!isUnused}
>
{t('编辑')}
</Button>
<Dropdown
trigger='click'
position='bottomRight'
menu={moreMenuItems}
{!isExpired(record) && (
<Button
type='link'
size='small'
disabled={record.status === REDEMPTION_STATUS.USED}
onClick={() =>
manageRedemption(
record.id,
isUnused
? REDEMPTION_ACTIONS.DISABLE
: REDEMPTION_ACTIONS.ENABLE,
record,
)
}
>
<Button type='tertiary' size='small' icon={<IconMore />} />
</Dropdown>
{isUnused ? t('禁用') : t('启用')}
</Button>
)}
</>
)}
</Space>
{canDelete && (
<Button
type='link'
size='small'
danger
onClick={() => showDeleteRedemptionModal(record)}
>
{t('删除')}
</Button>
)}
</div>
);
},
},
@@ -1,20 +1,21 @@
import React, { useMemo, useState } from 'react';
import React, { useState } from 'react';
import TableEmpty from '../../common/table/TableEmpty';
import CardTable from '../../common/ui/CardTable';
import { getRedemptionsColumns } from './RedemptionsColumnDefs';
import DeleteRedemptionModal from './modals/DeleteRedemptionModal';
import RedemptionDetailsModal from './modals/RedemptionDetailsModal';
const SELECTION_COLUMN_WIDTH = 34;
const RedemptionsTable = (redemptionsData) => {
const {
canEdit,
canDelete,
redemptions,
loading,
searching,
activePage,
pageSize,
tokenCount,
compactMode,
handlePageChange,
rowSelection,
handleRow,
manageRedemption,
copyText,
setEditingRedemption,
@@ -26,6 +27,7 @@ const RedemptionsTable = (redemptionsData) => {
// Modal states
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [deletingRecord, setDeletingRecord] = useState(null);
const [detailRecord, setDetailRecord] = useState(null);
// Handle show delete modal
const showDeleteRedemptionModal = (record) => {
@@ -35,56 +37,45 @@ const RedemptionsTable = (redemptionsData) => {
// Get all columns
const columns = getRedemptionsColumns({
canEdit,
canDelete,
t,
manageRedemption,
copyText,
setEditingRedemption,
setShowEdit,
refresh,
redemptions,
activePage,
showDetails: setDetailRecord,
showDeleteRedemptionModal,
});
// Handle compact mode by removing fixed positioning
const tableColumns = useMemo(() => {
return compactMode
? columns.map((col) => {
if (col.dataIndex === 'operate') {
const { fixed, ...rest } = col;
return rest;
}
return col;
})
: columns;
}, [compactMode, columns]);
return (
<>
<CardTable
columns={tableColumns}
columns={columns}
minScrollableWidth={SELECTION_COLUMN_WIDTH * 2}
dataSource={redemptions}
scroll={compactMode ? undefined : { x: 'max-content' }}
pagination={{
currentPage: activePage,
pageSize: pageSize,
total: tokenCount,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50, 100],
onPageSizeChange: redemptionsData.handlePageSizeChange,
onPageChange: handlePageChange,
}}
scroll={{ x: 'max-content' }}
hidePagination={true}
loading={loading}
rowSelection={rowSelection}
onRow={handleRow}
loading={loading || searching}
rowSelection={{
...rowSelection,
fixed: true,
columnWidth: SELECTION_COLUMN_WIDTH,
}}
empty={<TableEmpty />}
className='console-list-table overflow-hidden'
className='rounded-xl overflow-hidden'
size='middle'
/>
<RedemptionDetailsModal
record={detailRecord}
onClose={() => setDetailRecord(null)}
copyText={copyText}
t={t}
/>
<DeleteRedemptionModal
visible={showDeleteModal}
visible={canDelete && showDeleteModal}
onCancel={() => setShowDeleteModal(false)}
record={deletingRecord}
manageRedemption={manageRedemption}
+38 -8
View File
@@ -8,9 +8,17 @@ import EditRedemptionModal from './modals/EditRedemptionModal';
import { useRedemptionsData } from '../../../hooks/redemptions/useRedemptionsData';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../../helpers/utils';
import { isAdmin } from '@/helpers';
import { usePerm } from '@/authz';
import '../../console/module-alignment.css';
import './redemptions.css';
const RedemptionsPage = () => {
const redemptionsData = useRedemptionsData();
const canQuery = usePerm('platform.redemption.query', isAdmin);
const canCreate = usePerm('platform.redemption.create', isAdmin);
const canEdit = usePerm('platform.redemption.edit', isAdmin);
const canDelete = usePerm('platform.redemption.delete', isAdmin);
const redemptionsData = useRedemptionsData(canQuery);
const isMobile = useIsMobile();
const {
@@ -47,12 +55,17 @@ const RedemptionsPage = () => {
<EditRedemptionModal
refresh={refresh}
editingRedemption={editingRedemption}
visiable={showEdit}
visible={
showEdit &&
(editingRedemption.id === undefined ? canCreate : canQuery && canEdit)
}
handleClose={closeEdit}
/>
<CardPro
tableTitle={t('兑换码列表')}
searchArea={
canQuery && (
<RedemptionsFilters
formInitValues={formInitValues}
setFormApi={setFormApi}
@@ -63,27 +76,37 @@ const RedemptionsPage = () => {
searching={searching}
t={t}
/>
)
}
type='type1'
actionsArea={
<div className='console-list-tools'>
descriptionArea={
canQuery && (
<RedemptionsDescription
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
)
}
tableActions={
<RedemptionsActions
canQuery={canQuery}
canCreate={canCreate}
canDelete={canDelete}
selectedKeys={selectedKeys}
busy={loading || searching}
setEditingRedemption={setEditingRedemption}
setShowEdit={setShowEdit}
batchCopyRedemptions={batchCopyRedemptions}
batchDeleteRedemptions={batchDeleteRedemptions}
t={t}
/>
</div>
}
paginationArea={createCardProPagination({
paginationArea={
canQuery &&
createCardProPagination({
preservePage: true,
showRange: false,
currentPage: redemptionsData.activePage,
pageSize: redemptionsData.pageSize,
total: redemptionsData.tokenCount,
@@ -91,10 +114,17 @@ const RedemptionsPage = () => {
onPageSizeChange: redemptionsData.handlePageSizeChange,
isMobile: isMobile,
t: redemptionsData.t,
})}
})
}
t={redemptionsData.t}
>
<RedemptionsTable {...redemptionsData} />
{canQuery && (
<RedemptionsTable
{...redemptionsData}
canEdit={canEdit}
canDelete={canDelete}
/>
)}
</CardPro>
</>
);
@@ -1,5 +1,5 @@
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useEffect, useState, useRef } from 'react';
import React, { useEffect, useId, useRef, useState } from 'react';
import { Button, Card, Col, Row, Spin } from 'antd';
import { useTranslation } from 'react-i18next';
import {
API,
@@ -7,126 +7,105 @@ import {
showError,
showSuccess,
renderQuota,
} from '../../../../helpers';
} from '@/helpers';
import { FormQuotaInput } from '../../../common/ui/QuotaInput';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import {
Button,
Modal,
SideSheet,
Space,
Spin,
Typography,
Card,
Tag,
Form,
Avatar,
Row,
Col,
} from '@/components/ui';
import {
IconCreditCard,
IconSave,
IconClose,
IconGift,
} from '@/components/ui/icons';
import { Form, Modal, SideSheet } from '@/components/ui';
const { Text, Title } = Typography;
const EditRedemptionModal = (props) => {
const { t } = useTranslation();
const isEdit = props.editingRedemption.id !== undefined;
const [loading, setLoading] = useState(isEdit);
const isMobile = useIsMobile();
const formApiRef = useRef(null);
const getInitValues = () => ({
const initialValues = {
name: '',
quota: 100000,
count: 1,
expired_time: null,
is_gift: false,
});
const handleCancel = () => {
props.handleClose();
};
const loadRedemption = async () => {
setLoading(true);
let res = await API.get(`/api/redemption/${props.editingRedemption.id}`);
const { success, message, data } = res.data;
if (success) {
if (data.expired_time === 0) {
data.expired_time = null;
} else {
data.expired_time = new Date(data.expired_time * 1000);
}
formApiRef.current?.setValues({ ...getInitValues(), ...data });
} else {
showError(message);
}
setLoading(false);
};
const EditRedemptionModal = ({
editingRedemption,
visible,
refresh,
handleClose,
}) => {
const { t } = useTranslation();
const { id } = editingRedemption;
const isEdit = id !== undefined;
const isMobile = useIsMobile();
const formApi = useRef(null);
const formId = useId();
const [loading, setLoading] = useState(false);
const [loadedId, setLoadedId] = useState(null);
const [submitting, setSubmitting] = useState(false);
const pending = useRef(false);
const formDisabled = loading || submitting || (isEdit && loadedId !== id);
const onScopeChange = useEffectEvent(() => {
if (formApiRef.current) {
if (isEdit) {
loadRedemption();
} else {
formApiRef.current.setValues(getInitValues());
}
}
useEffect(() => {
if (!visible) return;
formApi.current?.reset();
setLoadedId(null);
setLoading(isEdit);
if (!isEdit) return;
let active = true;
async function loadRedemption() {
try {
const { data: result } = await API.get(`/api/redemption/${id}`);
if (!active) return;
if (result.success) {
const { expired_time, ...data } = result.data;
formApi.current?.setValues({
...initialValues,
...data,
expired_time:
expired_time === 0 ? null : new Date(expired_time * 1000),
});
useEffect(() => onScopeChange(), [onScopeChange, props.editingRedemption.id]);
setLoadedId(id);
} else {
showError(result.message);
}
} catch (error) {
if (active && !error.isAxiosError) showError(error.message);
} finally {
if (active) setLoading(false);
}
}
void loadRedemption();
return () => {
active = false;
};
}, [id, isEdit, visible]);
const submit = async (values) => {
let name = values.name;
if (!isEdit && (!name || name === '')) {
name = renderQuota(values.quota);
}
setLoading(true);
let localInputs = { ...values };
localInputs.count = parseInt(localInputs.count) || 0;
localInputs.quota = parseInt(localInputs.quota) || 0;
localInputs.name = name;
if (!localInputs.expired_time) {
localInputs.expired_time = 0;
} else {
localInputs.expired_time = Math.floor(
localInputs.expired_time.getTime() / 1000,
);
}
let res;
if (isEdit) {
res = await API.put(`/api/redemption/`, {
...localInputs,
id: parseInt(props.editingRedemption.id),
});
} else {
res = await API.post(`/api/redemption/`, {
...localInputs,
});
}
if (formDisabled || pending.current) return;
pending.current = true;
setSubmitting(true);
try {
const payload = {
...values,
name: !isEdit && !values.name ? renderQuota(values.quota) : values.name,
count: parseInt(values.count) || 0,
quota: parseInt(values.quota) || 0,
expired_time: values.expired_time
? Math.floor(values.expired_time.getTime() / 1000)
: 0,
};
const res = isEdit
? await API.put('/api/redemption/', { ...payload, id: parseInt(id) })
: await API.post('/api/redemption/', payload);
const { success, message, data } = res.data;
if (success) {
if (isEdit) {
showSuccess(t('兑换码更新成功!'));
props.refresh();
props.handleClose();
} else {
showSuccess(t('兑换码创建成功!'));
props.refresh();
formApiRef.current?.setValues(getInitValues());
props.handleClose();
}
showSuccess(isEdit ? t('兑换码更新成功!') : t('兑换码创建成功!'));
refresh();
handleClose();
} else {
showError(message);
}
if (!isEdit && data) {
let text = '';
for (let i = 0; i < data.length; i++) {
text += data[i] + '\n';
for (let index = 0; index < data.length; index++) {
text += data[index] + '\n';
}
Modal.confirm({
title: t('兑换码创建成功'),
@@ -136,176 +115,100 @@ const EditRedemptionModal = (props) => {
<p>{t('兑换码将以文本文件的形式下载,文件名为兑换码的名称。')}</p>
</div>
),
onOk: () => {
downloadTextAsFile(text, `${localInputs.name}.txt`);
},
onOk: () => downloadTextAsFile(text, `${payload.name}.txt`),
});
}
setLoading(false);
} catch (error) {
if (!error.isAxiosError) showError(error.message);
} finally {
pending.current = false;
setSubmitting(false);
}
};
return (
<>
<SideSheet
placement={isEdit ? 'right' : 'left'}
title={
<Space>
{isEdit ? (
<Tag color='blue' shape='circle'>
{t('更新')}
</Tag>
) : (
<Tag color='green' shape='circle'>
{t('新建')}
</Tag>
)}
<Title heading={4} className='m-0'>
{isEdit ? t('更新兑换码信息') : t('创建新的兑换码')}
</Title>
</Space>
}
bodyStyle={{ padding: '0' }}
visible={props.visiable}
width={isMobile ? '100%' : 600}
footer={
<div className='flex justify-end'>
<Space>
const handleCancel = () => {
if (!pending.current) handleClose();
};
const footer = (
<div className='console-dialog-actions redemption-form-actions'>
<Button disabled={submitting} onClick={handleCancel}>
{t('取消')}
</Button>
<Button
theme='solid'
onClick={() => formApiRef.current?.submitForm()}
icon={<IconSave />}
loading={loading}
type='primary'
htmlType='submit'
form={formId}
disabled={formDisabled}
loading={submitting}
>
{t('提交')}
</Button>
<Button
theme='light'
type='primary'
onClick={handleCancel}
icon={<IconClose />}
>
{t('取消')}
</Button>
</Space>
</div>
}
closeIcon={null}
onCancel={() => handleCancel()}
>
);
const form = (
<Spin spinning={loading}>
<Form
initValues={getInitValues()}
getFormApi={(api) => (formApiRef.current = api)}
id={formId}
name={formId}
ref={formApi}
className='redemption-form'
initValues={initialValues}
disabled={formDisabled}
onSubmit={submit}
onSubmitFail={() => formApi.current?.scrollToError()}
>
{({ values }) => (
<div className='p-2'>
<Card className='!rounded-2xl shadow-sm border-0 mb-6'>
{/* Header: Basic Info */}
<div className='flex items-center mb-2'>
<Avatar
size='small'
color='blue'
className='mr-2 shadow-md'
>
<IconGift size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>
{t('基本信息')}
</Text>
<div className='text-xs text-gray-600'>
{t('设置兑换码的基本信息')}
</div>
</div>
</div>
<Row gutter={12}>
<Col span={24}>
<Card size='small' title={t('基本信息')}>
<Form.Input
field='name'
label={t('名称')}
placeholder={t('请输入名称')}
style={{ width: '100%' }}
rules={
!isEdit
? []
: [{ required: true, message: t('请输入名称') }]
}
rules={isEdit ? [{ required: true, message: t('请输入名称') }] : []}
className={isEdit ? 'redemption-validated-field' : undefined}
showClear
/>
</Col>
<Col span={24}>
<Form.DatePicker
field='expired_time'
label={t('过期时间')}
type='dateTime'
placeholder={t('选择过期时间(可选,留空为永久)')}
style={{ width: '100%' }}
showClear
/>
</Col>
</Row>
</Card>
<Card className='!rounded-2xl shadow-sm border-0'>
{/* Header: Quota Settings */}
<div className='flex items-center mb-2'>
<Avatar
size='small'
color='green'
className='mr-2 shadow-md'
>
<IconCreditCard size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>
{t('额度设置')}
</Text>
<div className='text-xs text-gray-600'>
{t('设置兑换码的额度和数量')}
</div>
</div>
</div>
<Row gutter={12}>
<Col span={12}>
<Card size='small' title={t('额度设置')}>
<Row gutter={16}>
<Col xs={24} sm={isEdit ? 24 : 12}>
<FormQuotaInput
field='quota'
label={t('额度')}
style={{ width: '100%' }}
className='redemption-validated-field'
rules={[
{ required: true, message: t('请输入额度') },
{
validator: (rule, v) => {
const num = parseInt(v, 10);
return num > 0
validator: (rule, value) =>
parseInt(value, 10) > 0
? Promise.resolve()
: Promise.reject(t('额度必须大于0'));
},
: Promise.reject(t('额度必须大于0')),
},
]}
showClear
/>
</Col>
{!isEdit && (
<Col span={12}>
<Col xs={24} sm={12}>
<Form.InputNumber
field='count'
label={t('生成数量')}
className='redemption-validated-field'
min={1}
rules={[
{ required: true, message: t('请输入生成数量') },
{
validator: (rule, v) => {
const num = parseInt(v, 10);
return num > 0
validator: (rule, value) =>
parseInt(value, 10) > 0
? Promise.resolve()
: Promise.reject(t('生成数量必须大于0'));
},
: Promise.reject(t('生成数量必须大于0')),
},
]}
style={{ width: '100%' }}
showClear
/>
</Col>
@@ -319,12 +222,23 @@ const EditRedemptionModal = (props) => {
)}
/>
</Card>
</div>
)}
</Form>
</Spin>
);
return (
<SideSheet
placement='right'
forceRender
visible={visible}
width={isMobile ? '100%' : 560}
title={isEdit ? t('编辑兑换码信息') : t('添加兑换码')}
footer={footer}
onCancel={handleCancel}
closable={!submitting}
>
{form}
</SideSheet>
</>
);
};
@@ -0,0 +1,67 @@
import React from 'react';
import { Button } from 'antd';
import { Copy } from '@/components/common/icons/ActionIcons';
import { Modal } from '@/components/ui';
import { renderQuota, timestamp2string } from '@/helpers';
import {
formatRedemptionExpiry,
renderRedemptionStatus,
} from '../RedemptionsColumnDefs';
export default function RedemptionDetailsModal({
record,
onClose,
copyText,
t,
}) {
const fields = record
? [
[t('ID'), record.id],
[t('额度'), renderQuota(parseInt(record.quota))],
[t('创建时间'), timestamp2string(record.created_time)],
[t('过期时间'), formatRedemptionExpiry(record.expired_time, t)],
[t('兑换人ID'), record.used_user_id || t('无')],
]
: [];
return (
<Modal
centered
visible={Boolean(record)}
title={t('查看详情')}
onCancel={onClose}
footer={<Button onClick={onClose}>{t('关闭')}</Button>}
destroyOnHidden
>
{record && (
<div className='redemption-details'>
<div className='redemption-details-heading'>
<h3>{record.name}</h3>
{renderRedemptionStatus(record.status, record, t)}
</div>
<div className='redemption-code'>
<div className='redemption-code-header'>
<span>{t('兑换码')}</span>
<Button
icon={<Copy size={16} aria-hidden />}
size='small'
onClick={() => copyText(record.key)}
>
{t('复制')}
</Button>
</div>
<code>{record.key}</code>
</div>
<dl className='redemption-details-fields'>
{fields.map(([label, value]) => (
<div key={label}>
<dt>{label}</dt>
<dd>{value}</dd>
</div>
))}
</dl>
</div>
)}
</Modal>
);
}
@@ -0,0 +1,148 @@
.console-page[data-console-page='redemption']
.console-table
.ant-table-tbody
> .ant-table-row
> .ant-table-cell {
height: 51px;
}
.redemption-form {
display: grid;
gap: 16px;
}
.redemption-form .ant-card-small > .ant-card-head,
.redemption-form .ant-card-small > .ant-card-body {
padding-inline: 16px;
}
.redemption-form .ant-card-small > .ant-card-body {
padding-block: 16px;
}
.redemption-form.console-form .ant-form-item {
margin-bottom: 16px;
}
.redemption-form.console-form .ant-card-body > .ant-form-item:last-child {
margin-bottom: 0;
}
.redemption-form.console-form .ant-form-item-label > label {
color: var(--console-text, var(--ui-color-text-0));
}
.redemption-form,
.redemption-invalid-action {
--redemption-error-text: color-mix(
in srgb,
var(--ui-color-danger) 65%,
var(--console-text, var(--ui-color-text-0))
);
}
.redemption-form .ant-form-item .ant-form-item-explain-error,
.redemption-form .ant-form-item-label > .ant-form-item-required::before,
.console-page .redemption-invalid-action.ant-btn-dangerous:not(:disabled) {
color: var(--redemption-error-text);
}
.redemption-form :is(.ant-input-number, .ant-picker) {
width: 100%;
}
.redemption-validated-field .ant-form-item-control {
min-block-size: 56px;
}
.redemption-form-actions .ant-btn {
min-inline-size: 72px;
min-block-size: 34px;
}
.redemption-details {
display: grid;
gap: 16px;
padding-block: 8px;
color: var(--console-text, var(--ui-color-text-0));
}
.redemption-details-heading,
.redemption-code-header {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px 16px;
flex-wrap: wrap;
}
.redemption-details-heading h3 {
margin: 0;
font-size: 18px;
font-weight: 600;
color: var(--console-heading, var(--ui-color-text-0));
overflow-wrap: anywhere;
}
.redemption-details-heading .ant-tag {
margin-inline-end: 0;
}
.redemption-code {
display: grid;
gap: 8px;
padding: 12px 16px;
border: 1px solid var(--console-border, var(--ui-color-border));
border-radius: 8px;
background: var(--console-fill, var(--ui-color-fill-0));
}
.redemption-code code {
overflow-wrap: anywhere;
user-select: all;
font-size: 14px;
}
.redemption-details-fields {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px 20px;
margin: 0;
}
.redemption-details dt,
.redemption-code-header > span {
color: var(--console-text, var(--ui-color-text-0));
font-size: 13px;
}
.redemption-details dd {
margin: 4px 0 0;
overflow-wrap: anywhere;
font-variant-numeric: tabular-nums;
}
@media (max-width: 575px) {
.redemption-details-fields {
grid-template-columns: 1fr;
}
}
.center-action-table .center-action-cell .redemption-row-actions {
flex-wrap: nowrap;
vertical-align: middle;
overflow-x: auto;
}
.redemption-row-actions .ant-btn {
flex: none;
}
@media (max-width: 575px) {
.center-action-table .center-action-cell .redemption-row-actions {
gap: 4px;
}
.redemption-row-actions.console-module-row-actions .ant-btn-link {
padding-inline: 2px;
}
}
@@ -261,20 +261,11 @@ const EditTokenModal = (props) => {
setLoading(false);
};
const onScopeChange = useEffectEvent(() => {
if (formApiRef.current) {
if (!isEdit) {
formApiRef.current.setValues(getInitValues());
}
}
const onVisibilityChange = useEffectEvent(() => {
if (props.visiable) {
loadModels();
loadGroups();
loadSkillOptions();
});
useEffect(() => onScopeChange(), [onScopeChange, props.editingToken.id]);
const onVisibilityChange2 = useEffectEvent(() => {
if (props.visiable) {
if (isEdit) {
loadToken();
} else {
@@ -295,8 +286,8 @@ const EditTokenModal = (props) => {
}
});
useEffect(
() => onVisibilityChange2(),
[onVisibilityChange2, props.visiable, props.editingToken.id],
() => onVisibilityChange(),
[onVisibilityChange, props.visiable, props.editingToken.id],
);
const generateRandomSuffix = () => {
@@ -74,6 +74,7 @@
.usage-billing-detail .usage-billing-heading {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 5px;
line-height: 20px;
@@ -84,6 +85,127 @@
flex-shrink: 0;
}
/* 「仅超级管理员可见」提示:跟在区块标题后,不继承标题的大写与字距 */
.usage-billing-root-hint {
margin-left: 4px;
padding: 0 6px;
border: 1px solid var(--border-subtle);
border-radius: 6px;
color: var(--text-secondary);
font-size: 12px;
font-weight: 400;
letter-spacing: 0;
line-height: 18px;
text-transform: none;
}
/* 计费详情 · 费用明细:公式行 + 分项表(两处日志页共用,颜色只取语义变量) */
.usage-billing-formula {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
padding: 8px 12px;
border-radius: 8px;
background: var(--ui-color-fill-0);
color: var(--text-secondary);
font-size: 13px;
line-height: 22px;
}
.usage-billing-formula-label {
color: var(--text-primary);
font-weight: 600;
}
/* 一项 = 名称 + 金额。窄屏下名称可以折行,金额不拆开:整项不换行的话,较长的名称
(其他语言里更长)会撑出灰底,被弹窗的横向裁剪截掉末尾几位数字 */
.usage-billing-formula-term {
display: inline-flex;
flex-wrap: wrap;
align-items: baseline;
gap: 0 4px;
min-width: 0;
overflow-wrap: anywhere;
}
.usage-billing-formula-term strong {
color: var(--text-primary);
font-weight: 600;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.usage-billing-formula-total {
color: var(--brand-primary);
font-size: 15px;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.usage-billing-table-wrap {
margin-top: 8px;
overflow-x: auto;
}
.usage-billing-table {
width: 100%;
min-width: 480px;
border-collapse: collapse;
font-size: 13px;
line-height: 20px;
}
.usage-billing-table th,
.usage-billing-table td {
padding: 8px;
border-bottom: 1px solid var(--border-subtle);
color: var(--text-primary);
font-weight: 400;
text-align: right;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.usage-billing-table th:first-child {
text-align: left;
white-space: normal;
}
.usage-billing-table thead th {
color: var(--text-secondary);
font-size: 12px;
}
.usage-billing-table tbody td:last-child {
font-weight: 600;
}
.usage-billing-table-note {
display: block;
color: var(--text-secondary);
font-size: 12px;
line-height: 18px;
}
.usage-billing-table tfoot th,
.usage-billing-table tfoot td {
border-bottom: 0;
font-size: 14px;
font-weight: 600;
}
.usage-billing-table tfoot td {
color: var(--brand-primary);
}
.usage-billing-footnote {
margin-top: 4px;
color: var(--text-secondary);
font-size: 12px;
line-height: 18px;
}
.usage-logs-date-panel {
--usage-date-accent: var(--brand-gradient-via);
--usage-date-accent-strong: var(--brand-gradient-to);
@@ -265,7 +265,11 @@ const applyUsageRecordPresentation = (
};
switch (column.key) {
case COLUMN_KEYS.TIME:
return { ...column, render: (text) => renderRecordTime(text) };
return {
...column,
fixed: 'left',
render: (text) => renderRecordTime(text),
};
case COLUMN_KEYS.USERNAME:
return {
...column,
@@ -3,19 +3,34 @@ import React, { useMemo, useState } from 'react';
import AntTable from '../../ui/CenterActionTable';
import { Button as AntButton } from 'antd';
import { Modal, Typography } from '@/components/ui';
import i18next from 'i18next';
import {
Coins,
Cpu,
Gauge,
Landmark,
Layers3,
Percent,
ReceiptText,
RadioTower,
ShieldCheck,
Sparkles,
TrendingUp,
} from 'lucide-react';
import CardTable from '../../common/ui/CardTable';
import { getLogOther, renderQuota } from '../../../helpers';
import {
formatDiscountLabel,
getCurrencyConfig,
getLogOther,
getQuotaPerUnit,
renderQuota,
} from '../../../helpers';
import { getLogsColumns } from './UsageLogsColumnDefs';
import {
buildBillingBreakdown,
reconcileDisplayAmounts,
} from './billingBreakdown';
const { Text } = Typography;
@@ -28,7 +43,24 @@ const formatCount = (value) => {
const formatRatio = (value) => {
const num = Number(value);
if (!Number.isFinite(num)) return '-';
return `${Number.isInteger(num) ? num : num.toFixed(3).replace(/0+$/, '').replace(/\.$/, '')}x`;
// 保留到 6 位:倍率是费用明细里单价的构成因子,截到 3 位(0.7825 → 0.783)
// 用户照着界面上的数字就乘不出小计;toFixed 再转 Number 是为了去掉尾随 0 和浮点噪声
return `${Number(num.toFixed(6))}x`;
};
// 分项金额(额度单位,可带小数)→ 当前展示货币;trim 时去掉多余的尾随 0(用于单价)。
// 站点按额度展示时没有货币换算,小数位由 tokenDigits 单独控制
const formatAmount = (
quota,
{ digits = 6, tokenDigits = 2, trim = false } = {},
) => {
if (!Number.isFinite(quota)) return '-';
const { symbol, rate, type } = getCurrencyConfig();
const isToken = type === 'TOKENS';
const value = isToken ? quota : (quota / getQuotaPerUnit()) * rate;
let text = Math.abs(value).toFixed(isToken ? tokenDigits : digits);
if (trim) text = text.replace(/(\.\d{2}\d*?)0+$/, '$1');
return `${value < 0 ? '-' : ''}${isToken ? '' : symbol}${text}`;
};
const MetricCard = ({ icon: Icon, label, value, tone = 'brand', plain }) => {
@@ -67,6 +99,153 @@ const MetricCard = ({ icon: Icon, label, value, tone = 'brand', plain }) => {
);
};
const BillingBreakdown = ({ breakdown, t }) => {
const { symbol, rate, type } = getCurrencyConfig();
const isToken = type === 'TOKENS';
const digits = isToken ? 2 : 6;
const quotaPerUnit = getQuotaPerUnit();
// 各行与合计先换算成展示金额再对平:每行各自四舍五入后直接相加,常会和合计差最后一位
// (0.001315 + 0.001568 + 0.000550 = 0.003433,实扣 0.003432)。差额归入「舍入与其他
// 调整」一项,保证界面上的数字逐项相加恰好等于合计
const reconciled = reconcileDisplayAmounts(breakdown, {
digits,
// 与 renderQuota 是同一个表达式,合计才会和弹窗顶部的「本次花费」一致
toDisplay: (quota) => (isToken ? quota : (quota / quotaPerUnit) * rate),
});
const formatDisplayed = (amount) =>
`${amount < 0 ? '-' : ''}${isToken ? '' : symbol}${Math.abs(amount).toFixed(digits)}`;
const total = formatDisplayed(reconciled.total);
const itemLabels = {
input: t('输入'),
inputUncached: t('输入(未命中缓存)'),
cacheRead: t('缓存命中'),
cacheCreation: t('缓存创建'),
cacheCreation5m: t('5m 缓存创建'),
cacheCreation1h: t('1h 缓存创建'),
cacheCreationUnlabeled: t('未分档缓存创建'),
imageInput: t('图片输入'),
output: t('输出'),
textInput: t('文字输入'),
textOutput: t('文字输出'),
audioInput: t('音频输入'),
audioOutput: t('音频输出'),
webSearch: t('联网搜索'),
claudeWebSearch: t('Claude 联网搜索'),
fileSearch: t('文件搜索'),
imageGeneration: t('图片生成'),
perCall: t('按次计费'),
videoSecond: t('按秒计费'),
};
const ratioLabels = {
model: t('模型倍率'),
completion: t('输出倍率'),
cache: t('缓存倍率'),
cacheCreation: t('缓存创建倍率'),
image: t('图片倍率'),
audio: t('音频倍率'),
audioCompletion: t('音频输出倍率'),
group: t('分组倍率'),
};
const rows = reconciled.rows.map((item) => {
const isTokens = item.unit === 'tokens';
return {
key: item.key,
label: itemLabels[item.key] || item.key,
note: item.ratios
.map((ratio) => `${ratioLabels[ratio.key]} ${formatRatio(ratio.value)}`)
.join(' × '),
qty: isTokens
? `${formatCount(item.qty)} tokens`
: item.unit === 'seconds'
? t('{{n}} 秒', { n: formatCount(item.qty) })
: t('{{n}} 次', { n: formatCount(item.qty), count: item.qty }),
price: isTokens
? t('{{price}} / 1M tokens', {
price: formatAmount(item.unitQuota * 1000000, { trim: true }),
})
: item.unit === 'seconds'
? t('{{price}} / 秒', {
price: formatAmount(item.unitQuota, { trim: true }),
})
: t('{{price}} / 次', {
price: formatAmount(item.unitQuota, { trim: true }),
}),
amount: item.amount,
};
});
if (reconciled.adjustment !== 0) {
rows.push({
key: 'adjustment',
label: t('舍入与其他调整'),
amount: reconciled.adjustment,
});
}
return (
<>
<div className='usage-billing-formula' aria-label={t('计算公式')}>
<span className='usage-billing-formula-label'>{t('总金额')}</span>
{rows.map((row, index) => (
<React.Fragment key={row.key}>
<span className='usage-billing-formula-op'>
{index === 0 ? '=' : row.amount < 0 ? '−' : '+'}
</span>
<span className='usage-billing-formula-term'>
<span>{row.label}</span>
<strong>
{formatDisplayed(
index === 0 ? row.amount : Math.abs(row.amount),
)}
</strong>
</span>
</React.Fragment>
))}
<span className='usage-billing-formula-op'>=</span>
<strong className='usage-billing-formula-total'>{total}</strong>
</div>
<div className='usage-billing-table-wrap'>
<table className='usage-billing-table'>
<thead>
<tr>
<th scope='col'>{t('计费项')}</th>
<th scope='col'>{t('用量')}</th>
<th scope='col'>{t('单价')}</th>
<th scope='col'>{t('小计')}</th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={row.key}>
<th scope='row'>
<span>{row.label}</span>
{row.note && (
<span className='usage-billing-table-note'>{row.note}</span>
)}
</th>
<td>{row.qty || '-'}</td>
<td>{row.price || '-'}</td>
<td>{formatDisplayed(row.amount)}</td>
</tr>
))}
</tbody>
<tfoot>
<tr>
<th scope='row' colSpan={3}>
{t('合计')}
</th>
<td>{total}</td>
</tr>
</tfoot>
</table>
</div>
<div className='usage-billing-footnote'>
{t('各项小计为四舍五入后的近似值,合计以实际扣费为准')}
</div>
</>
);
};
const DetailPill = ({ label, value, plain }) => {
if (value === undefined || value === null || value === '' || value === '-')
return null;
@@ -116,27 +295,40 @@ const UsageBillingDetail = ({
: other.group_ratio;
const details = [
{ label: t('输入'), value: formatCount(inputTokens) },
outputTokens > 0 && { label: t('输出'), value: formatCount(outputTokens) },
inputTokens > 0 && {
label: t('输入'),
usage: 'tokens',
value: formatCount(inputTokens),
},
outputTokens > 0 && {
label: t('输出'),
usage: 'tokens',
value: formatCount(outputTokens),
},
other.cache_tokens > 0 && {
label: t('缓存命中'),
usage: 'tokens',
value: formatCount(other.cache_tokens),
},
!hasSplitCacheCreation &&
other.cache_creation_tokens > 0 && {
label: t('缓存创建'),
usage: 'tokens',
value: formatCount(other.cache_creation_tokens),
},
other.cache_creation_tokens_5m > 0 && {
label: t('5m 缓存创建'),
usage: 'tokens',
value: formatCount(other.cache_creation_tokens_5m),
},
other.cache_creation_tokens_1h > 0 && {
label: t('1h 缓存创建'),
usage: 'tokens',
value: formatCount(other.cache_creation_tokens_1h),
},
showUnlabeledCacheCreation && {
label: t('未分档缓存创建'),
usage: 'tokens',
value: formatCount(unlabeledCacheCreation),
},
other.model_ratio != null && {
@@ -182,14 +374,17 @@ const UsageBillingDetail = ({
},
other.audio_input > 0 && {
label: t('音频输入'),
usage: 'tokens',
value: formatCount(other.audio_input),
},
other.audio_output > 0 && {
label: t('音频输出'),
usage: 'tokens',
value: formatCount(other.audio_output),
},
other.audio_input_token_count > 0 && {
label: t('音频计费 Tokens'),
usage: 'tokens',
value: formatCount(other.audio_input_token_count),
},
other.audio_ratio != null &&
@@ -205,17 +400,29 @@ const UsageBillingDetail = ({
other.image &&
other.image_output > 0 && {
label: t('图片 Tokens'),
usage: 'tokens',
value: formatCount(other.image_output),
},
other.web_search && {
label: t('联网搜索'),
usage: 'webSearch',
value: t('{{n}} 次', {
n: formatCount(other.web_search_call_count || 0),
count: other.web_search_call_count || 0,
}),
},
// 模型名以 search-preview 结尾却由 Claude 渠道承接时,两种联网搜索各计一笔
other.claude_web_search_call_count > 0 && {
label: t('Claude 联网搜索'),
usage: 'claudeWebSearch',
value: t('{{n}} 次', {
n: formatCount(other.claude_web_search_call_count),
count: other.claude_web_search_call_count,
}),
},
other.file_search && {
label: t('文件搜索'),
usage: 'fileSearch',
value: t('{{n}} 次', {
n: formatCount(other.file_search_call_count || 0),
count: other.file_search_call_count || 0,
@@ -223,10 +430,28 @@ const UsageBillingDetail = ({
},
other.image_generation_call && {
label: t('图片生成'),
usage: 'imageGeneration',
value: t('已计费'),
},
].filter(Boolean);
const breakdown = buildBillingBreakdown(record, other, {
quotaPerUnit: getQuotaPerUnit(),
});
// 已经在费用明细里逐行列出的用量不在成本因子区重复。按次 / 按秒计费的明细里没有
// token 行,这类日志的 token 用量仍然留在这里,否则它在弹窗里就看不到了
const breakdownKeys = new Set(
(breakdown?.items || []).map((item) => item.key),
);
const hasTokenRows = (breakdown?.items || []).some(
(item) => item.unit === 'tokens',
);
const isItemised = (item) =>
item.usage === 'tokens' ? hasTokenRows : breakdownKeys.has(item.usage);
const sectionClass = plain
? 'usage-billing-factors'
: 'mt-3 rounded-2xl border border-white/55 bg-white/[0.35] p-3 backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.04]';
const mappedModel =
other?.is_model_mapped &&
other?.upstream_model_name &&
@@ -238,6 +463,19 @@ const UsageBillingDetail = ({
? t('本地计费')
: t('上游返回')
: '';
const factorPills = [
...details.filter((item) => !item.usage || !isItemised(item)),
mappedModel && { label: t('实际模型'), value: other.upstream_model_name },
billingMode && { label: t('计费源'), value: billingMode },
// 与 DetailPill 的判空同口径('-' 是倍率无法解析时的占位),否则整块可能只剩一个空框
].filter(
(item) =>
item &&
item.value !== undefined &&
item.value !== null &&
item.value !== '' &&
item.value !== '-',
);
const metrics = [
{
icon: Coins,
@@ -267,6 +505,45 @@ const UsageBillingDetail = ({
},
].filter(Boolean);
// 超管指标只在超级管理员的接口响应里存在(后端按角色附加),其余角色拿不到
const rootBilling =
Number(other.root_billing?.overall_ratio) > 0 ? other.root_billing : null;
const rootDiscount = Number(rootBilling?.discount);
// 接近 1 的比值不附折扣写法:0.999 会被四舍五入成「10折」
const rootDiscountLabel =
rootDiscount < 0.995
? formatDiscountLabel(rootDiscount, i18next.language)
: '';
const rootOfficialQuota = Number(rootBilling?.official_quota);
const rootMetrics = rootBilling
? [
{
icon: Landmark,
label: t('官方价金额(1 倍率)'),
// 不足 1 个额度单位的金额按默认位数会显示成 0,多给几位
value: formatAmount(
rootOfficialQuota,
rootOfficialQuota < 1 ? { digits: 8, tokenDigits: 6 } : undefined,
),
tone: 'cyan',
},
{
icon: TrendingUp,
label: t('整体倍率'),
value: formatRatio(rootBilling.overall_ratio),
tone: 'brand',
},
{
icon: Percent,
label: t('实际折扣'),
value: Number.isFinite(rootDiscount)
? `${Number(rootDiscount.toFixed(4))}${rootDiscountLabel ? ` · ${rootDiscountLabel}` : ''}`
: '-',
tone: 'emerald',
},
]
: [];
if (record.type !== 2) {
return (
<div className='usage-billing-detail'>
@@ -294,7 +571,9 @@ const UsageBillingDetail = ({
<span>{t('计费摘要')}</span>
</div>
<Text type='tertiary' size='small'>
{t('保留关键成本因子,省略冗长计算公式')}
{breakdown
? t('总金额 = 各计费项小计之和,小计 = 用量 × 单价')
: t('保留关键成本因子,省略冗长计算公式')}
</Text>
</div>
<div className='rounded-full border border-brand/20 bg-brand/10 px-3 py-1 text-sm font-semibold text-brand-deep dark:bg-brand/15 dark:text-brand-from'>
@@ -308,33 +587,60 @@ const UsageBillingDetail = ({
))}
</div>
<div
className={
plain
? 'usage-billing-factors'
: 'mt-3 rounded-2xl border border-white/55 bg-white/[0.35] p-3 backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.04]'
}
>
{rootBilling && (
<div className={sectionClass}>
<div className='usage-billing-heading mb-2 flex items-center text-xs font-medium uppercase tracking-[0.18em] text-gray-400'>
<ShieldCheck size={13} />
<span>{t('超管指标')}</span>
<span className='usage-billing-root-hint'>
{t('仅超级管理员可见')}
</span>
</div>
<div className='grid gap-3 sm:grid-cols-3'>
{rootMetrics.map((item) => (
<MetricCard key={item.label} {...item} plain={plain} />
))}
</div>
<div className='usage-billing-footnote'>
{t(
'整体倍率 = 实扣 ÷ 官方价金额;实际折扣 = 整体倍率 ÷ 登记汇率({{rate}})',
{ rate: rootBilling.exchange_rate },
)}
</div>
</div>
)}
{breakdown && (
<div className={sectionClass}>
<div className='usage-billing-heading mb-2 flex items-center text-xs font-medium uppercase tracking-[0.18em] text-gray-400'>
<ReceiptText size={13} />
<span>{t('费用明细')}</span>
</div>
<BillingBreakdown breakdown={breakdown} t={t} />
</div>
)}
{/* 没有任何可展示的因子时整块不渲染(如只带按秒计价字段的任务日志),免得留一个空框 */}
{factorPills.length > 0 && (
<div className={sectionClass}>
<div className='usage-billing-heading mb-2 flex items-center text-xs font-medium uppercase tracking-[0.18em] text-gray-400'>
<Layers3 size={13} />
<span>{t('成本因子')}</span>
</div>
<div className='flex flex-wrap gap-2'>
{details.map((item) => (
<DetailPill key={item.label} {...item} plain={plain} />
))}
{mappedModel && (
{/* 列表是静态的,用下标作 key:两个标签在某个语言里译成同一个词时,
按标签作 key 会重复 */}
{factorPills.map((item, index) => (
<DetailPill
label={t('实际模型')}
value={other.upstream_model_name}
key={index}
label={item.label}
value={item.value}
plain={plain}
/>
)}
{billingMode && (
<DetailPill label={t('计费源')} value={billingMode} plain={plain} />
)}
))}
</div>
</div>
)}
</div>
);
};
@@ -390,7 +696,8 @@ const LogsTable = (logsData) => {
);
const tableColumns = useMemo(() => {
const baseColumns = compactMode
const baseColumns =
compactMode && !usageRecordMode
? visibleColumnsList.map(({ fixed, ...rest }) => rest)
: visibleColumnsList;
if (!hasExpandableRows()) return baseColumns;
@@ -399,7 +706,7 @@ const LogsTable = (logsData) => {
{
title: usageRecordMode ? t('操作') : t('计费详情'),
key: 'billingDetailAction',
fixed: compactMode || usageRecordMode ? undefined : 'right',
fixed: usageRecordMode || !compactMode ? 'right' : undefined,
width: 120,
render: (_, record) => {
const canView =
@@ -452,7 +759,9 @@ const LogsTable = (logsData) => {
dataSource={logs}
rowKey='key'
loading={loading}
scroll={compactMode ? undefined : { x: 'max-content' }}
scroll={
usageRecordMode || !compactMode ? { x: 'max-content' } : undefined
}
className={
usageRecordMode
? 'usage-logs-table usage-record-table'
@@ -0,0 +1,261 @@
// 计费详情的「分项小计」:把一条消费日志拆成 用量 × 单价 的若干行,各行相加即本次扣费。
// 口径逐项对照后端结算(relay/compatible_handler.go postConsumeQuota、
// service/quota.go PostClaudeConsumeQuota / calculateAudioQuota),改后端公式时须同步这里。
// 纯函数、不依赖浏览器环境,单测见 test/unit/usage-billing-breakdown.test.js。
const num = (value) => {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
};
// 字段存在且是数字(null / undefined 视为缺失:Number(null) 是 0,会被当成有效值)
const hasNumber = (value) =>
value !== undefined && value !== null && Number.isFinite(Number(value));
// 实扣与分项之和最多允许差 1 个额度单位:结算四舍五入到 1 个单位、有费用至少扣 1 个单位,
// 历史日志是向下取整,这些差异都不超过 1 个单位。超过就说明这条日志的计费口径这里没覆盖
// (如任务按分辨率 / 时长系数计价),此时不展示拆分。不能按比例放宽:大额请求里
// 几千个额度单位的真实费用会被说成「舍入」
const MAX_UNEXPLAINED = 1;
const isReliable = (diff) => Math.abs(diff) <= MAX_UNEXPLAINED + 1e-6;
/**
* @param {object} record 日志行(prompt_tokens / completion_tokens / quota)
* @param {object} other getLogOther(record.other) 的结果
* @param {{ quotaPerUnit?: number }} options quotaPerUnit:1 美元对应的额度单位
* @returns {{ items: Array, estimated: number, actual: number } | null}
* items[].quota 为该项金额(额度单位,未取整);unitQuota 为每 1 个用量单位的金额;
* ratios 为单价的构成倍率;estimated 为各项之和,actual 为实扣。信息不足、或两者
* 对不上时返回 null。两者之间的取整差额由 reconcileDisplayAmounts 在展示层处理。
*/
export function buildBillingBreakdown(record, other, options = {}) {
if (!record || !other) return null;
// 差额调整行(实扣 = 实际 − 预扣)与 token 兜底预扣都不是「用量 × 单价」的完整一笔。
// 这两类日志同样会带按秒计价的字段(作为成本基准),不能当按秒计费来拆
if (other.quota_adjustment || other.video_token_fallback) return null;
const quotaPerUnit = num(options.quotaPerUnit) || 500000;
const actual = num(record.quota);
const group = hasNumber(other.group_ratio) ? num(other.group_ratio) : 1;
const groupRatio = { key: 'group', value: group };
const items = [];
const push = (key, qty, unit, unitQuota, ratios) => {
if (!(qty > 0)) return;
items.push({ key, qty, unit, unitQuota, ratios, quota: qty * unitQuota });
};
const finish = () => {
if (items.length === 0) return null;
const estimated = items.reduce((sum, item) => sum + item.quota, 0);
// 分项全是 0 元却有实扣:整笔钱都没解释,不能把它整个算作「舍入与其他调整」
if (estimated === 0 && actual !== 0) return null;
const diff = actual - estimated;
if (!isReliable(diff)) return null;
return { items, estimated, actual };
};
// 独立标价项(美元价 × 分组倍率),不乘模型倍率;按次计费的请求同样会叠加工具调用费
const pushExtras = (audioSeparateTokens = 0) => {
push(
'audioInput',
audioSeparateTokens,
'tokens',
(num(other.audio_input_price) / 1000000) * quotaPerUnit * group,
[groupRatio],
);
if (other.web_search) {
push(
'webSearch',
num(other.web_search_call_count),
'calls',
(num(other.web_search_price) / 1000) * quotaPerUnit * group,
[groupRatio],
);
}
// 模型名以 search-preview 结尾却由 Claude 渠道承接时,两种联网搜索各计一笔
push(
'claudeWebSearch',
num(other.claude_web_search_call_count),
'calls',
(num(other.claude_web_search_price) / 1000) * quotaPerUnit * group,
[groupRatio],
);
if (other.file_search) {
push(
'fileSearch',
num(other.file_search_call_count),
'calls',
(num(other.file_search_price) / 1000) * quotaPerUnit * group,
[groupRatio],
);
}
if (other.image_generation_call) {
push(
'imageGeneration',
1,
'calls',
num(other.image_generation_call_price) * quotaPerUnit * group,
[groupRatio],
);
}
};
// 视频按秒计费:单价 × 时长 × 分组倍率(此时 model_price 为 0,不是按次)
const videoSecondPrice = num(other.video_second_unit_price);
if (videoSecondPrice > 0) {
const videoGroup = hasNumber(other.video_second_group_ratio)
? num(other.video_second_group_ratio)
: group;
push(
'videoSecond',
num(other.video_second_duration),
'seconds',
videoSecondPrice * quotaPerUnit * videoGroup,
[{ key: 'group', value: videoGroup }],
);
return finish();
}
// 按次计费:模型价格 × 分组倍率。按倍率计费的日志 model_price 为 -1;
// 个别日志写的是 0 却带着有效的模型倍率,这类仍按 token 拆分
const modelPrice = hasNumber(other.model_price)
? Number(other.model_price)
: NaN;
const usesModelRatio = modelPrice === 0 && num(other.model_ratio) > 0;
if (Number.isFinite(modelPrice) && modelPrice !== -1 && !usesModelRatio) {
push('perCall', 1, 'calls', modelPrice * quotaPerUnit * group, [
groupRatio,
]);
pushExtras();
return finish();
}
if (!hasNumber(other.model_ratio)) return null;
const model = num(other.model_ratio);
const modelRatio = { key: 'model', value: model };
const completion = num(other.completion_ratio);
const completionRatio = { key: 'completion', value: completion };
// 按 token 计费的一行:用量 × 模型倍率 × 该项倍率 × 分组倍率
const pushTokens = (key, tokens, extraRatios = []) => {
const weight = extraRatios.reduce((acc, r) => acc * r.value, 1);
push(key, num(tokens), 'tokens', model * weight * group, [
modelRatio,
...extraRatios,
groupRatio,
]);
};
// 实时语音 / 音频:文字与音频各按自己的倍率
if (other.ws || other.audio) {
const audio = { key: 'audio', value: num(other.audio_ratio) };
const audioCompletion = {
key: 'audioCompletion',
value: num(other.audio_completion_ratio),
};
pushTokens('textInput', other.text_input);
pushTokens('textOutput', other.text_output, [completionRatio]);
pushTokens('audioInput', other.audio_input, [audio]);
pushTokens('audioOutput', other.audio_output, [audio, audioCompletion]);
return finish();
}
const cacheTokens = num(other.cache_tokens);
const tokens5m = num(other.cache_creation_tokens_5m);
const tokens1h = num(other.cache_creation_tokens_1h);
const hasSplit = tokens5m > 0 || tokens1h > 0;
// 与分档并存时未分档是独立一桶;没有分档时 cache_creation_tokens 整体就是这一桶
const tokensUnlabeled = hasSplit
? num(other.cache_creation_tokens_unlabeled)
: num(other.cache_creation_tokens);
const ratioUnlabeled = hasSplit
? num(other.cache_creation_ratio_unlabeled)
: num(other.cache_creation_ratio);
const creationTokens = tokens5m + tokens1h + tokensUnlabeled;
const imageTokens = other.image ? num(other.image_output) : 0;
const audioSeparateTokens = other.audio_input_seperate_price
? num(other.audio_input_token_count)
: 0;
// Claude 协议的 prompt_tokens 不含缓存;其余协议含缓存 / 图片 / 音频,须逐项剥离,
// 且与后端一致:不够减时不减(上游本就没把这部分算进 prompt_tokens)
let baseTokens = num(record.prompt_tokens);
if (!other.claude) {
for (const part of [
cacheTokens,
creationTokens,
imageTokens,
audioSeparateTokens,
]) {
if (part > 0 && baseTokens >= part) baseTokens -= part;
}
}
pushTokens(
cacheTokens > 0 || creationTokens > 0 ? 'inputUncached' : 'input',
baseTokens,
);
pushTokens('cacheRead', cacheTokens, [
{ key: 'cache', value: num(other.cache_ratio) },
]);
pushTokens('cacheCreation5m', tokens5m, [
{ key: 'cacheCreation', value: num(other.cache_creation_ratio_5m) },
]);
pushTokens('cacheCreation1h', tokens1h, [
{ key: 'cacheCreation', value: num(other.cache_creation_ratio_1h) },
]);
pushTokens(
hasSplit ? 'cacheCreationUnlabeled' : 'cacheCreation',
tokensUnlabeled,
[{ key: 'cacheCreation', value: ratioUnlabeled }],
);
pushTokens('imageInput', imageTokens, [
{ key: 'image', value: num(other.image_ratio) },
]);
pushTokens('output', record.completion_tokens, [completionRatio]);
pushExtras(audioSeparateTokens);
return finish();
}
/**
* 把分项与实扣换算成展示金额并对平。
*
* 各行先按展示精度四舍五入,再用一项「调整」吸收「展示合计 − 各行展示金额之和」,
* 保证界面上的数字逐项相加恰好等于合计——拿计算器把公式行加一遍就能对上。
* 调整项同时包含结算取整(四舍五入到 1 个额度单位、有费用至少扣 1 个单位)与
* 各行展示取整两部分误差。
*
* @param {{ items: Array, actual: number }} breakdown buildBillingBreakdown 的结果
* @param {{ toDisplay: (quota: number) => number, digits: number }} display
* toDisplay:额度单位 → 展示金额,须与页面其余位置的金额换算是同一个表达式;
* digits:展示保留的小数位
* @returns {{ rows: Array, adjustment: number, total: number }}
* rows[].amount、adjustment、total 都已按 digits 取整,且 Σ amount + adjustment 恰等于 total
*/
export function reconcileDisplayAmounts(breakdown, { toDisplay, digits }) {
const unit = 10 ** digits;
// 先 toFixed 再放大取整:toFixed 的舍入方向与页面上其余金额的展示一致;放大后的值
// 离整数只差浮点噪声,Math.round 不会再改变舍入方向。全程用整数个最小展示单位做加减,
// 避免 0.1 + 0.2 式的误差让「差额为 0」判断失准
const toUnits = (quota) =>
Math.round(Number(toDisplay(quota).toFixed(digits)) * unit);
let totalUnits = toUnits(breakdown.actual);
// 与 renderQuota 一致:实扣大于 0 却被舍成 0 时按最小展示单位显示
if (
totalUnits === 0 &&
breakdown.actual > 0 &&
toDisplay(breakdown.actual) > 0
)
totalUnits = 1;
let sumUnits = 0;
const rows = breakdown.items.map((item) => {
const amountUnits = toUnits(item.quota);
sumUnits += amountUnits;
return { ...item, amount: amountUnits / unit };
});
return {
rows,
adjustment: (totalUnits - sumUnits) / unit,
total: totalUnits / unit,
};
}
+4 -1
View File
@@ -2,8 +2,11 @@ import { Plus as ActionPlus } from '@/components/common/icons/ActionIcons';
import React from 'react';
import { Button } from 'antd';
import { isAdmin } from '../../../helpers';
import { usePerm } from '../../../authz';
const UsersActions = ({ setShowAddUser, t }) => {
// 已切换模块按权限点,未切换与原判断一致
const canCreate = usePerm('platform.user.create', isAdmin());
// Add new user
const handleAddUser = () => {
setShowAddUser(true);
@@ -11,7 +14,7 @@ const UsersActions = ({ setShowAddUser, t }) => {
return (
<div className='flex justify-end gap-2'>
{isAdmin() && (
{canCreate && (
<Button
className='console-create-action'
type='primary'
+93 -29
View File
@@ -16,9 +16,23 @@ import {
renderNumber,
renderQuota,
getUserData,
isAdmin,
} from '../../../helpers';
/**
* 当前登录人能否管理这一行(与后端 canManageUserOfRole 同口径,按钮权限另由 perms 决定)
* - 超级管理员:全部可管理
* - 用户管理已切到新体系:不能操作自己和超级管理员(目标权限是否被覆盖由后端校验)
* - 未切换:只能管理角色低于自己的用户
*/
const canManageRow = (record, enforced) => {
const me = getUserData();
const currentRole = Number(me?.role || 0);
const recordRole = Number(record.role || 0);
if (currentRole >= 100) return true;
if (enforced) return record.id !== me?.id && recordRole < 100;
return recordRole < currentRole;
};
/**
* Render user role
*/
@@ -98,19 +112,21 @@ const renderUsername = (text, record) => {
/**
* Render user statistics
*/
const renderStatistics = (text, record, showEnableDisableModal, t) => {
const renderStatistics = (text, record, showEnableDisableModal, perms, t) => {
const isDeleted = record.DeletedAt !== null;
const currentRole = Number(getUserData()?.role || 0);
const canManage =
isAdmin() && (currentRole >= 100 || Number(record.role || 0) < 100);
// 超级管理员是受保护对象,不可切换;其余按「禁用/启用」按钮权限与行级可管理性
const canToggle =
perms.canStatus &&
Number(record.role || 0) < 100 &&
canManageRow(record, perms.enforced);
const content = isDeleted ? (
<Tag color='red'>{t('已注销')}</Tag>
) : (
<TableStatusSwitch
checked={record.status === 1}
aria-label={t('状态')}
disabled={!canManage}
disabled={!canToggle}
onChange={(checked, event) => {
event.stopPropagation();
showEnableDisableModal(record, checked ? 'enable' : 'disable');
@@ -215,6 +231,9 @@ const renderOperations = (
showResetPasskeyModal,
showResetTwoFAModal,
showInvitedUsersModal,
showAssignRolesModal,
showAddQuotaModal,
perms,
t,
},
) => {
@@ -224,15 +243,23 @@ const renderOperations = (
const currentRole = Number(getUserData()?.role || 0);
const recordRole = Number(record.role || 0);
// 与后端 canManageUserOfRole 一致:非超级管理员只能管理角色低于自己的用户;提升/降级仅超级管理员
const canManage =
isAdmin() && (currentRole >= 100 || recordRole < currentRole);
const canChangeRole = canManage && currentRole >= 100 && recordRole < 100;
const manageable = canManageRow(record, perms.enforced);
// 提升/降级仅超级管理员;用户管理切到新体系后冻结,改用「分配角色」
const canChangeRole =
!perms.enforced &&
perms.canPromote &&
manageable &&
currentRole >= 100 &&
recordRole < 100;
const canEditRow = perms.canEdit && manageable;
// 分配平台角色:超级管理员本身不参与角色授权
const canAssignRow =
perms.canAssignRole && recordRole < 100 && !!showAssignRolesModal;
// 低频动作全部收进「更多」下拉,操作列稳定为一行三个控件,避免跨行撑高行高
const moreMenu = [];
// 低频动作收进「更多」下拉;分组之间用分割线
const groups = [];
if (canChangeRole) {
moreMenu.push(
groups.push([
{
key: 'promote',
label: t('提升'),
@@ -243,41 +270,53 @@ const renderOperations = (
label: t('降级'),
onClick: () => showDemoteModal(record),
},
{ type: 'divider' },
);
]);
}
moreMenu.push({
groups.push([
{
key: 'invitations',
label: t('邀请记录'),
onClick: () => showInvitedUsersModal(record),
});
if (canManage) {
moreMenu.push(
{ type: 'divider' },
{
},
]);
const resetItems = [];
if (perms.canResetPasskey && manageable) {
resetItems.push({
key: 'reset-passkey',
label: t('重置 Passkey'),
onClick: () => showResetPasskeyModal(record),
},
{
});
}
if (perms.canReset2FA && manageable) {
resetItems.push({
key: 'reset-2fa',
label: t('重置 2FA'),
onClick: () => showResetTwoFAModal(record),
},
{ type: 'divider' },
});
}
if (resetItems.length) groups.push(resetItems);
// 超级管理员不可注销(后端同样拒绝)
if (perms.canDelete && manageable && recordRole < 100) {
groups.push([
{
key: 'delete',
label: t('注销'),
danger: true,
onClick: () => showDeleteModal(record),
},
);
]);
}
const moreMenu = groups.flatMap((group, index) =>
index === 0
? group
: [{ type: 'divider', key: `divider-${index}` }, ...group],
);
return (
<TableRowActions items={moreMenu}>
{canManage && (
{(canEditRow || canAssignRow) && (
<>
{canEditRow && (
<Button
type='link'
size='small'
@@ -288,6 +327,25 @@ const renderOperations = (
>
{t('编辑')}
</Button>
)}
{canEditRow && (
<Button
type='link'
size='small'
onClick={() => showAddQuotaModal(record)}
>
{t('添加额度')}
</Button>
)}
{canAssignRow && (
<Button
type='link'
size='small'
onClick={() => showAssignRolesModal(record)}
>
{t('分配角色')}
</Button>
)}
</>
)}
</TableRowActions>
@@ -308,6 +366,9 @@ export const getUsersColumns = ({
showResetPasskeyModal,
showResetTwoFAModal,
showInvitedUsersModal,
showAssignRolesModal,
showAddQuotaModal,
perms,
}) => {
return [
{
@@ -332,7 +393,7 @@ export const getUsersColumns = ({
title: t('状态'),
dataIndex: 'info',
render: (text, record, index) =>
renderStatistics(text, record, showEnableDisableModal, t),
renderStatistics(text, record, showEnableDisableModal, perms, t),
},
{
title: t('剩余额度/总额度'),
@@ -363,7 +424,7 @@ export const getUsersColumns = ({
title: t('操作'),
dataIndex: 'operate',
fixed: 'right',
width: 135,
width: 290,
render: (text, record, index) =>
renderOperations(text, record, {
setEditingUser,
@@ -375,6 +436,9 @@ export const getUsersColumns = ({
showResetPasskeyModal,
showResetTwoFAModal,
showInvitedUsersModal,
showAssignRolesModal,
showAddQuotaModal,
perms,
t,
}),
},
+17 -3
View File
@@ -7,7 +7,7 @@ import { IconSearch } from '@/components/ui/icons';
const UsersFilters = ({
formInitValues,
setFormApi,
searchUsers,
refresh,
loadUsers,
activePage,
pageSize,
@@ -17,8 +17,7 @@ const UsersFilters = ({
t,
}) => {
const { scheduleSearch, submitSearch, cancelPendingSearch } = useFilterSearch(
(_, signal) =>
searchUsers(Math.max(1, activePage), pageSize, null, null, signal),
(_, signal) => refresh(activePage, pageSize, signal),
);
const formApiRef = useRef(null);
@@ -35,6 +34,7 @@ const UsersFilters = ({
initValues={{
...formInitValues,
searchGroup: formInitValues.searchGroup || undefined,
searchStatus: formInitValues.searchStatus || undefined,
}}
getFormApi={(api) => {
setFormApi(api);
@@ -71,6 +71,20 @@ const UsersFilters = ({
size='small'
/>
</div>
<div className='console-module-field'>
<Form.Select
label={t('状态')}
field='searchStatus'
placeholder={t('全部状态')}
optionList={[
{ value: 1, label: t('启用') },
{ value: 2, label: t('禁用') },
]}
className='w-full'
showClear
size='small'
/>
</div>
</div>
<ConsoleFilterActions
onReset={handleReset}
+65
View File
@@ -10,6 +10,10 @@ import DeleteUserModal from './modals/DeleteUserModal';
import ResetPasskeyModal from './modals/ResetPasskeyModal';
import ResetTwoFAModal from './modals/ResetTwoFAModal';
import InvitedUsersModal from './modals/InvitedUsersModal';
import AssignRolesModal from './modals/AssignRolesModal';
import AddUserQuotaModal from './modals/AddUserQuotaModal';
import { isAdmin, isRoot } from '../../../helpers';
import { usePerm, useAuthzView } from '../../../authz';
const UsersTable = (usersData) => {
const {
@@ -25,6 +29,7 @@ const UsersTable = (usersData) => {
setEditingUser,
setShowEditUser,
manageUser,
adjustUserQuota,
refresh,
resetUserPasskey,
resetUserTwoFA,
@@ -41,6 +46,33 @@ const UsersTable = (usersData) => {
const [showResetPasskeyModal, setShowResetPasskeyModal] = useState(false);
const [showResetTwoFAModal, setShowResetTwoFAModal] = useState(false);
const [showInvitedUsersModal, setShowInvitedUsersModal] = useState(false);
const [showAssignRolesModal, setShowAssignRolesModal] = useState(false);
const [showAddQuotaModal, setShowAddQuotaModal] = useState(false);
// 按钮权限:模块已切到新体系按权限点,未切换与原判断一致
const canEdit = usePerm('platform.user.edit', isAdmin());
const canStatus = usePerm('platform.user.status', isAdmin());
const canDelete = usePerm('platform.user.delete', isAdmin());
const canPromote = usePerm('platform.user.promote', isRoot());
const canResetPasskey = usePerm('platform.user.reset_passkey', isAdmin());
const canReset2FA = usePerm('platform.user.reset_2fa', isAdmin());
// 分配平台角色:模块切换前仅 root 可用;弹窗要拉取角色列表,须同时持有 platform.authz.role.query
const canAssignRoleOp = usePerm('platform.authz.role.assign', isRoot());
const canQueryRole = usePerm('platform.authz.role.query', isRoot());
// 用户管理模块是否已切到新体系:切换后提升/降级冻结,行级可管理性不再按 users.role 分层
const platformView = useAuthzView('platform');
const userModule = platformView?.moduleOf?.['platform.user.edit'];
const enforced = !!userModule && platformView.enforcedSet.has(userModule);
const perms = {
canEdit,
canStatus,
canDelete,
canPromote,
canResetPasskey,
canReset2FA,
canAssignRole: canAssignRoleOp && canQueryRole,
enforced,
};
// Modal handlers
const showPromoteUserModal = (user) => {
@@ -79,6 +111,16 @@ const UsersTable = (usersData) => {
setShowInvitedUsersModal(true);
};
const showAssignRolesUserModal = (user) => {
setModalUser(user);
setShowAssignRolesModal(true);
};
const showAddQuotaUserModal = (user) => {
setModalUser(user);
setShowAddQuotaModal(true);
};
// Modal confirm handlers
const handlePromoteConfirm = () => {
manageUser(modalUser.id, 'promote', modalUser);
@@ -90,6 +132,7 @@ const UsersTable = (usersData) => {
setShowDemoteModal(false);
};
// 状态 Switch 受控于 record.status:请求失败时 manageUser 已提示原因,列表保持原状态
const handleEnableDisableConfirm = () => {
manageUser(modalUser.id, enableDisableAction, modalUser);
setShowEnableDisableModal(false);
@@ -117,6 +160,9 @@ const UsersTable = (usersData) => {
showResetPasskeyModal: showResetPasskeyUserModal,
showResetTwoFAModal: showResetTwoFAUserModal,
showInvitedUsersModal: showInvitedUsersUserModal,
showAssignRolesModal: showAssignRolesUserModal,
showAddQuotaModal: showAddQuotaUserModal,
perms,
});
// Handle compact mode by removing fixed positioning
@@ -214,6 +260,25 @@ const UsersTable = (usersData) => {
user={modalUser}
t={t}
/>
<AssignRolesModal
visible={showAssignRolesModal}
onCancel={() => setShowAssignRolesModal(false)}
user={modalUser}
t={t}
/>
<AddUserQuotaModal
visible={showAddQuotaModal}
onCancel={() => setShowAddQuotaModal(false)}
onSubmit={adjustUserQuota}
user={
modalUser
? users.find((u) => u.id === modalUser.id) || modalUser
: null
}
t={t}
/>
</>
);
};
+1 -2
View File
@@ -27,7 +27,6 @@ const UsersPage = () => {
// Form state
formInitValues,
setFormApi,
searchUsers,
loadUsers,
activePage,
pageSize,
@@ -64,7 +63,7 @@ const UsersPage = () => {
<UsersFilters
formInitValues={formInitValues}
setFormApi={setFormApi}
searchUsers={searchUsers}
refresh={refresh}
loadUsers={loadUsers}
activePage={activePage}
pageSize={pageSize}
@@ -1,7 +1,15 @@
import React, { useState, useRef } from 'react';
import { API, showError, showSuccess } from '../../../../helpers';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import { Button, SideSheet, Spin, Form, Row, Col } from '@/components/ui';
import {
Button,
SideSheet,
Spin,
Form,
Row,
Col,
Typography,
} from '@/components/ui';
import { useTranslation } from 'react-i18next';
const AddUserModal = (props) => {
@@ -70,6 +78,19 @@ const AddUserModal = (props) => {
}}
>
<Row gutter={12}>
<Col span={24}>
{/* 账号类型用语统一为"个人账号"(PRD AC52);平台角色不在新建表单中选择(AC57) */}
<Form.Slot label={t('账号类型')}>
<Typography.Text>{t('个人账号')}</Typography.Text>
<div>
<Typography.Text type='secondary' className='text-xs'>
{t(
'创建后为启用状态;平台角色请在列表操作列通过「分配角色」设置',
)}
</Typography.Text>
</div>
</Form.Slot>
</Col>
<Col span={24}>
<Form.Input
field='username'
@@ -0,0 +1,93 @@
import React, { useEffect, useState } from 'react';
import { Typography } from 'antd';
import { ConsoleModal } from '../../../console/ConsolePrimitives';
import QuotaInput from '../../../common/ui/QuotaInput';
import { renderQuota } from '../../../../helpers';
const { Text } = Typography;
// 添加额度弹窗(PRD §4.1、AC59):输入调整量(可正可负,不能为 0),实时展示
// 「当前剩余额度 + 调整额度 = 新剩余额度」;新剩余额度不能小于 0。
// QuotaInput 的 value/onChange 始终是内部额度单位,金额换算由它完成。
const AddUserQuotaModal = ({ visible, onCancel, onSubmit, user, t }) => {
const [delta, setDelta] = useState(null);
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (visible) setDelta(null);
}, [visible, user?.id]);
const current = parseInt(user?.quota) || 0;
const amount = Number.isFinite(delta) ? delta : 0;
const next = current + amount;
const error =
delta === null
? ''
: amount === 0
? t('调整额度不能为 0')
: next < 0
? t('调整后的剩余额度不能小于 0')
: '';
const canSubmit = delta !== null && !error;
const handleOk = async () => {
if (!canSubmit || submitting || !user?.id) return;
setSubmitting(true);
try {
const ok = await onSubmit(user.id, amount);
if (ok) onCancel();
} finally {
setSubmitting(false);
}
};
return (
<ConsoleModal
title={`${t('添加额度')} - ${user?.display_name || user?.username || ''}`}
open={visible}
onOk={handleOk}
onCancel={onCancel}
okText={t('确定')}
cancelText={t('取消')}
confirmLoading={submitting}
okButtonProps={{ disabled: !canSubmit }}
centered
destroyOnHidden
>
<div className='flex flex-col gap-3'>
<div>
<div className='mb-2'>
<Text>{t('调整额度(正数增加,负数减少)')}</Text>
</div>
<QuotaInput
value={delta}
onChange={setDelta}
placeholder={t('需要添加的金额(支持负数)')}
style={{ width: '100%' }}
status={error ? 'error' : undefined}
aria-label={t('调整额度')}
/>
{error && (
<div className='mt-1'>
<Text type='danger' className='text-xs'>
{error}
</Text>
</div>
)}
</div>
<Text type='secondary' className='tabular-nums'>
{t(
'当前剩余额度 {{current}} + 调整额度 {{delta}} = 新剩余额度 {{next}}',
{
current: renderQuota(current),
delta: renderQuota(amount),
next: renderQuota(next),
},
)}
</Text>
</div>
</ConsoleModal>
);
};
export default AddUserQuotaModal;
@@ -0,0 +1,131 @@
/*
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 { Select, Spin, Tag, Typography } from 'antd';
import { ConsoleModal } from '../../../console/ConsolePrimitives';
import { API, showError, showSuccess } from '../../../../helpers';
// 分配平台角色弹窗:读写 /api/user/:id/roles(整体替换)。
// 角色列表来自 /api/authz/platform/roles,停用的角色仍可展示但标注"停用"。
const AssignRolesModal = ({ visible, onCancel, user, t }) => {
const [roles, setRoles] = useState([]);
const [selected, setSelected] = useState([]);
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
useEffect(() => {
if (!visible || !user?.id) return;
let alive = true;
const load = async () => {
setLoading(true);
try {
const [rolesRes, mineRes] = await Promise.all([
API.get('/api/authz/platform/roles'),
API.get(`/api/user/${user.id}/roles`),
]);
if (!alive) return;
if (rolesRes.data.success) {
setRoles(rolesRes.data.data || []);
} else {
showError(rolesRes.data.message);
}
if (mineRes.data.success) {
setSelected(mineRes.data.data || []);
} else {
showError(mineRes.data.message);
}
} catch (err) {
showError(err);
} finally {
if (alive) setLoading(false);
}
};
load();
return () => {
alive = false;
};
}, [visible, user?.id]);
const handleOk = async () => {
if (!user?.id || saving) return;
setSaving(true);
try {
const res = await API.put(`/api/user/${user.id}/roles`, {
ids: selected,
});
if (res.data.success) {
showSuccess(t('角色已更新'));
onCancel();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err);
} finally {
setSaving(false);
}
};
return (
<ConsoleModal
title={`${t('分配角色')} - ${user?.display_name || user?.username || ''}`}
open={visible}
onOk={handleOk}
onCancel={onCancel}
confirmLoading={saving}
okButtonProps={{ disabled: loading }}
okText={t('保存')}
cancelText={t('取消')}
centered
width='min(520px, calc(100vw - 32px))'
>
<Spin spinning={loading}>
<Typography.Text type='secondary' className='text-xs'>
{t('为该用户分配平台角色,保存后整体替换原有角色。')}
</Typography.Text>
<Select
className='mt-3'
style={{ width: '100%' }}
mode='multiple'
value={selected}
onChange={setSelected}
placeholder={t('选择平台角色')}
aria-label={t('选择平台角色')}
options={roles.map((r) => ({
value: r.id,
label: (
<span className='inline-flex items-center gap-1'>
<span>{r.name}</span>
{r.status !== 1 ? (
<Tag variant='filled'>{t('停用')}</Tag>
) : null}
</span>
),
searchText: `${r.name} ${r.code}`,
}))}
showSearch={{ optionFilterProp: 'searchText' }}
notFoundContent={t('暂无角色')}
/>
</Spin>
</ConsoleModal>
);
};
export default AssignRolesModal;
@@ -30,6 +30,7 @@ const DeleteUserModal = ({
onCancel={onCancel}
onOk={handleConfirm}
type='danger'
okType='danger'
>
{t('相当于删除用户,此修改将不可逆')}
</TableActionModal>
@@ -5,7 +5,6 @@ import { API, showError, showSuccess, renderQuota } from '../../../../helpers';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import {
Button,
Modal,
SideSheet,
Spin,
Typography,
@@ -15,27 +14,28 @@ import {
Row,
Col,
} from '@/components/ui';
import QuotaInput, { FormQuotaInput } from '../../../common/ui/QuotaInput';
import { FormQuotaInput } from '../../../common/ui/QuotaInput';
import {
User as ActionUser,
Link as ActionLink,
Users as ActionUsers,
Plus as ActionPlus,
} from '@/components/common/icons/ActionIcons';
import { toGroupList } from '@/helpers/groupList';
const { Text } = Typography;
// User.Group is a single lookup key. Preserve historical keys containing commas.
const userGroupKey = (group) =>
Array.isArray(group) ? group.join(',') : group;
const EditUserModal = (props) => {
const { t } = useTranslation();
const userId = props.editingUser.id;
const [loading, setLoading] = useState(true);
// 剩余额度只读展示(PRD AC56):调整额度走列表操作列的「添加额度」(按调整量累加)
const [loadedQuota, setLoadedQuota] = useState(0);
const [loadedUserId, setLoadedUserId] = useState(null);
const [submitting, setSubmitting] = useState(false);
const pending = useRef(false);
const [addQuotaModalOpen, setIsModalOpen] = useState(false);
const [addQuotaLocal, setAddQuotaLocal] = useState('');
const isMobile = useIsMobile();
const [groupOptions, setGroupOptions] = useState([]);
const [levelOptions, setLevelOptions] = useState([]);
@@ -63,7 +63,9 @@ const EditUserModal = (props) => {
const fetchGroups = async () => {
try {
let res = await API.get(`/api/group/`);
if (res.data.success && Array.isArray(res.data.data)) {
setGroupOptions(res.data.data.map((g) => ({ label: g, value: g })));
}
} catch (e) {
showError(e.message);
}
@@ -95,8 +97,6 @@ const EditUserModal = (props) => {
const handleCancel = () => {
if (pending.current) return;
setIsModalOpen(false);
setAddQuotaLocal('');
props.handleClose();
};
@@ -112,11 +112,14 @@ const EditUserModal = (props) => {
const { data: response } = await API.get(url);
if (!isCurrent()) return;
if (response.success) {
setLoadedQuota(Number(response.data.quota) || 0);
formApiRef.current?.setValues({
...getInitValues(),
...response.data,
...(userId && {
group: toGroupList(response.data.group ?? 'default'),
group: [userGroupKey(response.data.group) ?? 'default'].filter(
Boolean,
),
}),
password: '',
});
@@ -147,13 +150,13 @@ const EditUserModal = (props) => {
setSubmitting(true);
try {
const payload = { ...values };
if (typeof payload.quota === 'string')
payload.quota = parseInt(payload.quota) || 0;
// 额度通过列表按增量调整;编辑资料时省略该字段,保留服务端当前余额。
delete payload.quota;
if (typeof payload.gift_quota === 'string')
payload.gift_quota = parseInt(payload.gift_quota) || 0;
if (userId) {
payload.id = parseInt(userId);
payload.group = toGroupList(values.group).join(',');
payload.group = userGroupKey(values.group);
}
const url = userId ? '/api/user/' : '/api/user/self';
const { data } = await API.put(url, payload);
@@ -172,13 +175,6 @@ const EditUserModal = (props) => {
}
};
/* --------------------- quota helper -------------------- */
const addLocalQuota = () => {
const current = parseInt(formApiRef.current?.getValue('quota') || 0);
const delta = parseInt(addQuotaLocal) || 0;
formApiRef.current?.setValue('quota', current + delta);
};
/* --------------------------- UI --------------------------- */
return (
<>
@@ -298,6 +294,7 @@ const EditUserModal = (props) => {
placeholder={t('请选择分组')}
optionList={groupOptions}
allowAdditions
maxCount={1}
search
rules={[{ required: true, message: t('请选择分组') }]}
/>
@@ -318,12 +315,16 @@ const EditUserModal = (props) => {
</Col>
<Col xs={24} sm={12}>
<FormQuotaInput
field='quota'
label={t('剩余额度')}
rules={[{ required: true, message: t('请输入额度') }]}
style={{ width: '100%' }}
/>
<Form.Slot label={t('剩余额度')}>
<Text className='tabular-nums'>
{renderQuota(loadedQuota)}
</Text>
<div>
<Text type='secondary' className='text-xs'>
{t('只读;调整请使用列表操作列的「添加额度」')}
</Text>
</div>
</Form.Slot>
</Col>
<Col xs={24} sm={12}>
@@ -336,16 +337,6 @@ const EditUserModal = (props) => {
style={{ width: '100%' }}
/>
</Col>
<Col span={24}>
<Form.Slot label={t('添加额度')}>
<Button
icon={<ActionPlus size={16} />}
aria-label={t('添加额度')}
onClick={() => setIsModalOpen(true)}
/>
</Form.Slot>
</Col>
</Row>
</Card>
)}
@@ -395,42 +386,6 @@ const EditUserModal = (props) => {
)}
</Form>
</SideSheet>
{/* 添加额度模态框 */}
<Modal
centered
visible={addQuotaModalOpen}
onOk={() => {
addLocalQuota();
setIsModalOpen(false);
}}
onCancel={() => setIsModalOpen(false)}
closable={null}
title={
<div className='flex items-center'>
<ActionPlus size={16} className='mr-2' />
{t('添加额度')}
</div>
}
>
<div className='mb-4'>
{(() => {
const current = formApiRef.current?.getValue('quota') || 0;
return (
<Text type='secondary' className='block mb-2'>
{`${t('新额度:')}${renderQuota(current)} + ${renderQuota(addQuotaLocal || 0)} = ${renderQuota(current + parseInt(addQuotaLocal || 0))}`}
</Text>
);
})()}
</div>
<QuotaInput
placeholder={t('需要添加的金额(支持负数)')}
value={addQuotaLocal}
onChange={setAddQuotaLocal}
style={{ width: '100%' }}
showClear
/>
</Modal>
</>
);
};
+3 -3
View File
@@ -7,15 +7,15 @@ export const REDEMPTION_STATUS = {
// Redemption code status display mapping
export const REDEMPTION_STATUS_MAP = {
[REDEMPTION_STATUS.UNUSED]: {
color: 'green',
color: 'success',
text: '未使用',
},
[REDEMPTION_STATUS.DISABLED]: {
color: 'red',
color: 'error',
text: '已禁用',
},
[REDEMPTION_STATUS.USED]: {
color: 'grey',
color: 'default',
text: '已使用',
},
};
+4 -3
View File
@@ -1,6 +1,7 @@
import React, { createContext, useReducer, useCallback } from 'react';
import { reducer, initialState } from './reducer';
import { API } from '../../helpers/api';
import { setCurrentOrgId, clearCurrentOrgId } from '../../helpers/orgContext';
export const OrgContext = createContext([initialState, () => {}]);
@@ -24,15 +25,15 @@ export const OrgProvider = ({ children }) => {
const setCurrentOrg = useCallback((org, role) => {
dispatch({ type: 'set_current_org', payload: { org, role } });
if (org) {
localStorage.setItem('current_org_id', String(org.id));
setCurrentOrgId(org.id);
} else {
localStorage.removeItem('current_org_id');
clearCurrentOrgId();
}
}, []);
const clearOrg = useCallback(() => {
dispatch({ type: 'clear' });
localStorage.removeItem('current_org_id');
clearCurrentOrgId();
}, []);
return (
+58 -6
View File
@@ -15,6 +15,13 @@ import {
DEFAULT_READ_TIMEOUT_MS,
installRequestLifecycle,
} from './requestLifecycle';
import {
getCurrentOrgId,
getProxySession,
clearProxySession,
isProxyMode,
markProxyExpired,
} from './orgContext';
function createAPIInstance() {
const serverURL = getServerURL();
@@ -46,9 +53,8 @@ function patchAPIInstance(instance) {
return originalGet(url, config);
}
const fallbackOrgId =
url.startsWith('/api/org/') && typeof localStorage !== 'undefined'
? localStorage.getItem('current_org_id') || ''
const fallbackOrgId = url.startsWith('/api/org/')
? String(getCurrentOrgId() || '')
: '';
const requestKey = buildGetRequestKey(
url,
@@ -72,15 +78,60 @@ function patchAPIInstance(instance) {
};
}
// 添加 request interceptor:自动为 /api/org/ 请求注入 X-Org-Id 头
// 表示代理会话已失效、需清掉本标签页代理上下文的返回码
const PROXY_INVALID_CODES = new Set([
'proxy_invalid',
'proxy_timeout',
'proxy_org_mismatch',
]);
// 企业会话须先修改初始密码(服务端在改密前拒绝企业业务接口):回到企业登录页的改密步骤。
// 已在企业登录页时不再跳转(登录页自己处理),同一页面只跳一次。
let redirectingToChangePassword = false;
function redirectToChangeInitialPassword() {
if (redirectingToChangePassword || typeof window === 'undefined') return;
const { pathname, search, hash } = window.location;
if (/^\/org(?:\/[^/]+)?\/login\/?$/.test(pathname)) return;
redirectingToChangePassword = true;
const params = new URLSearchParams({ must_change: '1' });
if (pathname.startsWith('/org')) {
params.set('redirect', `${pathname}${search}${hash}`);
}
window.location.replace(`/org/login?${params.toString()}`);
}
// 添加 response interceptor:按业务返回码维护企业上下文(HTTP 200 + success:false)
function addOrgResponseInterceptor(instance) {
instance.interceptors.response.use((response) => {
const code = response?.data?.code;
// 代理会话失效(超时、重新登录、被结束、企业不一致):清掉本标签页的代理上下文,提示从企业管理重新进入。
// proxy_error 是服务端校验出错("稍后重试"),代理会话本身仍有效,不清理
if (PROXY_INVALID_CODES.has(code) && isProxyMode()) {
clearProxySession();
// 记下"本标签页代理已失效":企业中心据此固定显示失效提示,不回落到 localStorage 里的企业
markProxyExpired();
}
if (code === 'must_change_password' && response?.data?.success === false) {
redirectToChangeInitialPassword();
}
return response;
});
}
// 添加 request interceptor:自动为 /api/org/ 请求注入 X-Org-Id 头;超管代理标签页同时带上
// X-Proxy-Session(企业以代理会话为准,X-Org-Id 只做一致性校验)
function addOrgHeaderInterceptor(instance) {
instance.interceptors.request.use((config) => {
config.headers['New-API-User'] = getUserIdFromLocalStorage();
if (config.url && config.url.startsWith('/api/org/')) {
const explicitOrgId = getHeaderValue(config.headers, 'X-Org-Id');
const orgId = explicitOrgId || localStorage.getItem('current_org_id');
const orgId = explicitOrgId || getCurrentOrgId();
if (orgId && !explicitOrgId) {
config.headers['X-Org-Id'] = orgId;
config.headers['X-Org-Id'] = String(orgId);
}
const proxy = getProxySession();
if (proxy) {
config.headers['X-Proxy-Session'] = proxy.id;
}
}
return config;
@@ -91,6 +142,7 @@ export function updateAPI() {
const instance = createAPIInstance();
patchAPIInstance(instance);
addOrgHeaderInterceptor(instance);
addOrgResponseInterceptor(instance);
const previous = retireAPI;
retireAPI = installRequestLifecycle(instance, {
onError: (error) => showError(error, { redirectOnUnauthorized: false }),
+27 -2
View File
@@ -1,3 +1,5 @@
import { clearAllOrgContext } from './orgContext.js';
export function setStatusData(data) {
localStorage.setItem('status', JSON.stringify(data));
localStorage.setItem('system_name', data.system_name);
@@ -78,7 +80,8 @@ export function setStatusData(data) {
}
export const DEFAULT_LOGIN_REDIRECT = '/user-center/key-management';
const USER_STORAGE_KEY = 'user';
// 用户数据在 localStorage 的键;AuthzProvider 监听其变化感知其他标签页换会话
export const USER_STORAGE_KEY = 'user';
const POST_LOGIN_REDIRECT_KEY = 'post_login_redirect';
export function getUserData() {
@@ -101,9 +104,31 @@ export function setUserData(data) {
localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(data));
}
// 企业域登录标记:/org/login 登录成功时写入,个人登录与登出时清除。
// 后端 /api/user/self 不返回登录域,前端据此决定重新登录时回到 /org/login 还是 /login。
export const ORG_LOGIN_SESSION_KEY = 'org_login_session';
export function setOrgLoginSession(isOrg) {
try {
if (isOrg) localStorage.setItem(ORG_LOGIN_SESSION_KEY, '1');
else localStorage.removeItem(ORG_LOGIN_SESSION_KEY);
} catch {
// localStorage 不可用时忽略
}
}
export function isOrgLoginSession() {
try {
return localStorage.getItem(ORG_LOGIN_SESSION_KEY) === '1';
} catch {
return false;
}
}
export function clearUserData() {
localStorage.removeItem(USER_STORAGE_KEY);
localStorage.removeItem('current_org_id');
setOrgLoginSession(false);
clearAllOrgContext();
// 智能路由侧边栏的个人授权缓存属于当前用户:同一标签页换账号登录时不能沿用
try {
sessionStorage.removeItem('smart_router_personal_consent_granted');
+1
View File
@@ -8,6 +8,7 @@ export * from './log';
export * from './data';
export * from './token';
export * from './boolean';
export * from './orgContext';
export * from './dashboard';
export * from './experienceCenter';
export * from './playgroundCapability';
+8 -1
View File
@@ -1,5 +1,10 @@
import { API, updateAPI } from './api';
import { clearUserData, consumePostLoginRedirect, setUserData } from './data';
import {
clearUserData,
consumePostLoginRedirect,
setOrgLoginSession,
setUserData,
} from './data';
import { showError } from './utils';
const SESSION_NOT_PERSISTED_MESSAGE =
@@ -17,9 +22,11 @@ export async function finishLogin({
navigate,
t = (s) => s,
redirect,
// 是否为企业域登录(/org/login):决定默认落地页,并记下登录域供之后重新登录时回到对应的登录页
enterprise = false,
}) {
setUserData(data);
setOrgLoginSession(enterprise);
// Recreate the axios instance so any in-flight request map from a prior
// session is dropped before we issue the verification GET.
updateAPI();
+127
View File
@@ -0,0 +1,127 @@
/*
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
*/
// 当前企业上下文(权限重构 §5.5)。
// - 普通成员:企业 ID 存 localStorage 的 current_org_id(跨标签页共享,与现状一致)。
// - 超管代理:代理会话只存在当前标签页的 sessionStorage,企业 ID 以代理会话为准;
// 代理标签页不读写 current_org_id,否则会影响其他标签页。
const ORG_KEY = 'current_org_id';
const PROXY_KEY = 'authz_proxy_session';
// 本标签页的代理会话已失效(超时、被结束、企业不一致):存在时企业中心固定提示从企业管理重新进入,
// 不回落到 localStorage 里的企业(否则会静默切到别的企业)。离开 /org、重新进入代理或在本标签页
// 明确选择企业时清除。
const PROXY_EXPIRED_KEY = 'authz_proxy_expired';
// 标记写入时派发的事件:企业中心据此重新渲染出失效提示
export const PROXY_EXPIRED_EVENT = 'authz-proxy-expired';
const safeSession = () => {
try {
return typeof sessionStorage !== 'undefined' ? sessionStorage : null;
} catch {
return null;
}
};
const safeLocal = () => {
try {
return typeof localStorage !== 'undefined' ? localStorage : null;
} catch {
return null;
}
};
// 代理会话:{ id, org_id, org_name };没有时返回 null。
export function getProxySession() {
const raw = safeSession()?.getItem(PROXY_KEY);
if (!raw) return null;
try {
const v = JSON.parse(raw);
if (v && typeof v.id === 'string' && v.id && Number(v.org_id) > 0) {
return { id: v.id, org_id: Number(v.org_id), org_name: v.org_name || '' };
}
} catch {
// 损坏的值按没有代理处理
}
safeSession()?.removeItem(PROXY_KEY);
return null;
}
export function setProxySession(session) {
clearProxyExpired();
safeSession()?.setItem(PROXY_KEY, JSON.stringify(session));
}
// 标记本标签页的代理会话已失效(由响应拦截器在清除代理会话时调用)
export function markProxyExpired() {
safeSession()?.setItem(PROXY_EXPIRED_KEY, '1');
try {
window.dispatchEvent(new Event(PROXY_EXPIRED_EVENT));
} catch {
// 非浏览器环境忽略
}
}
export function isProxyExpired() {
return safeSession()?.getItem(PROXY_EXPIRED_KEY) === '1';
}
export function clearProxyExpired() {
safeSession()?.removeItem(PROXY_EXPIRED_KEY);
}
export function clearProxySession() {
safeSession()?.removeItem(PROXY_KEY);
}
export function isProxyMode() {
return getProxySession() !== null;
}
// 当前企业 ID(数字,没有时为 0);代理已失效的标签页固定为 0。
export function getCurrentOrgId() {
const proxy = getProxySession();
if (proxy) return proxy.org_id;
if (isProxyExpired()) return 0;
return parseInt(safeLocal()?.getItem(ORG_KEY) || '0', 10) || 0;
}
// 写入当前企业:代理标签页内企业由代理会话决定,忽略写入。
export function setCurrentOrgId(orgId) {
if (isProxyMode()) return;
// 本标签页明确选择了企业(如企业登录成功):不再处于代理失效状态
clearProxyExpired();
safeLocal()?.setItem(ORG_KEY, String(orgId));
}
// 清除当前企业:代理标签页内清除即结束本标签页的代理上下文。
export function clearCurrentOrgId() {
if (isProxyMode()) {
clearProxySession();
return;
}
safeLocal()?.removeItem(ORG_KEY);
}
// 登出:两处都清。
export function clearAllOrgContext() {
clearProxySession();
clearProxyExpired();
safeLocal()?.removeItem(ORG_KEY);
}
+10
View File
@@ -13,3 +13,13 @@ export function buildOrgLogFilters({
if (modelName) params.model_name = modelName;
return params;
}
export function sameOrgRankingFilters(applied, next, rollingRange) {
return (
applied.userId === next.userId &&
applied.modelName === next.modelName &&
(rollingRange ||
(applied.startTimestamp === next.startTimestamp &&
applied.endTimestamp === next.endTimestamp))
);
}
+16
View File
@@ -66,6 +66,11 @@ import {
Route,
Globe,
CalendarDays,
ListTree,
ShieldCheck,
PackageCheck,
LayoutTemplate,
ToggleRight,
} from 'lucide-react';
// 获取侧边栏Lucide图标组件
@@ -126,6 +131,17 @@ export function getLucideIcon(key, selected = false) {
return <Globe {...commonProps} color={iconColor} />;
case 'demo-reservations':
return <CalendarDays {...commonProps} color={iconColor} />;
// 权限管理分组
case 'authz-menus':
return <ListTree {...commonProps} color={iconColor} />;
case 'authz-roles':
return <ShieldCheck {...commonProps} color={iconColor} />;
case 'authz-packages':
return <PackageCheck {...commonProps} color={iconColor} />;
case 'authz-templates':
return <LayoutTemplate {...commonProps} color={iconColor} />;
case 'authz-mode':
return <ToggleRight {...commonProps} color={iconColor} />;
default:
return <CircleUser {...commonProps} color={iconColor} />;
}
+11 -13
View File
@@ -66,27 +66,25 @@ export const useAdminTokensData = () => {
}, [formApi]);
const buildQuery = (page, size, filters) => {
const params = new URLSearchParams();
params.set('p', page);
params.set('page_size', size);
if (filters.keyword) params.set('keyword', filters.keyword);
if (filters.user_keyword) params.set('user_keyword', filters.user_keyword);
if (filters.user_id) params.set('user_id', filters.user_id);
const params = { p: page, page_size: size };
if (filters.keyword) params.keyword = filters.keyword;
if (filters.user_keyword) params.user_keyword = filters.user_keyword;
if (filters.user_id) params.user_id = filters.user_id;
if (filters.statuses && filters.statuses.length > 0) {
params.set('statuses', filters.statuses.join(','));
params.statuses = filters.statuses.join(',');
}
if (filters.group) params.set('group', filters.group);
if (filters.group) params.group = filters.group;
if (
filters.unlimited !== '' &&
filters.unlimited !== undefined &&
filters.unlimited !== null
) {
params.set('unlimited', filters.unlimited);
params.unlimited = filters.unlimited;
}
if (filters.org_scope && filters.org_scope !== 'all') {
params.set('org_scope', filters.org_scope);
params.org_scope = filters.org_scope;
}
return params.toString();
return params;
};
const hasAnyFilter = (filters) =>
@@ -122,8 +120,8 @@ export const useAdminTokensData = () => {
}
try {
const qs = buildQuery(page, size, useFilters);
const res = await API.get(`/api/token/admin?${qs}`, { signal });
const params = buildQuery(page, size, useFilters);
const res = await API.get('/api/token/admin', { params, signal });
if (requestId !== listRequestIdRef.current || signal?.aborted) return;
const { success, message, data } = res.data;
if (success) {
+40 -39
View File
@@ -57,20 +57,17 @@ export const useAnalyticsData = (active = true) => {
// 构建查询参数
const buildQueryParams = useCallback(
(currentPeriod, currentDateRange) => {
const params = new URLSearchParams();
const usePeriod = currentPeriod || period;
const useRange = currentDateRange || dateRange;
if (usePeriod === 'custom' && useRange[0] && useRange[1]) {
// 自定义日期范围:统一使用 UTC+8 时区的天边界
const startTime = toCST(useRange[0], false);
const endTime = toCST(useRange[1], true);
params.append('start_time', startTime);
params.append('end_time', endTime);
} else if (usePeriod !== 'custom') {
params.append('period', usePeriod);
return {
start_time: toCST(useRange[0], false),
end_time: toCST(useRange[1], true),
};
}
return params.toString();
return usePeriod === 'custom' ? {} : { period: usePeriod };
},
[period, dateRange, toCST],
);
@@ -79,10 +76,11 @@ export const useAnalyticsData = (active = true) => {
const fetchOverview = useCallback(async (force, signal) => {
setOverviewLoading(true);
try {
const res = await API.get(
`/api/analytics/overview${force ? '?refresh=true' : ''}`,
{ signal, timeout: ANALYTICS_TIMEOUT_MS },
);
const res = await API.get('/api/analytics/overview', {
params: force ? { refresh: true } : {},
signal,
timeout: ANALYTICS_TIMEOUT_MS,
});
if (signal.aborted) return;
if (res.data.success) {
setOverview(res.data.data);
@@ -100,8 +98,9 @@ export const useAnalyticsData = (active = true) => {
const fetchUserTrend = useCallback(
async (currentPeriod, currentDateRange, signal) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get(`/api/analytics/user-trend?${queryParams}`, {
const params = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get('/api/analytics/user-trend', {
params,
signal,
timeout: ANALYTICS_TIMEOUT_MS,
});
@@ -120,11 +119,12 @@ export const useAnalyticsData = (active = true) => {
const fetchFinanceTrend = useCallback(
async (currentPeriod, currentDateRange, signal) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get(
`/api/analytics/finance-trend?${queryParams}`,
{ signal, timeout: ANALYTICS_TIMEOUT_MS },
);
const params = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get('/api/analytics/finance-trend', {
params,
signal,
timeout: ANALYTICS_TIMEOUT_MS,
});
if (signal.aborted) return;
if (res.data.success) {
setFinanceTrend(res.data.data || []);
@@ -140,12 +140,12 @@ export const useAnalyticsData = (active = true) => {
const fetchChannelConsumption = useCallback(
async (currentPeriod, currentDateRange, signal) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const separator = queryParams ? '&' : '';
const res = await API.get(
`/api/analytics/channel-consumption?${queryParams}${separator}limit=30`,
{ signal, timeout: ANALYTICS_TIMEOUT_MS },
);
const params = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get('/api/analytics/channel-consumption', {
params: { ...params, limit: 30 },
signal,
timeout: ANALYTICS_TIMEOUT_MS,
});
if (signal.aborted) return;
if (res.data.success) {
setChannelConsumption(res.data.data || []);
@@ -161,12 +161,12 @@ export const useAnalyticsData = (active = true) => {
const fetchUserRanking = useCallback(
async (currentPeriod, currentDateRange, signal) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const separator = queryParams ? '&' : '';
const res = await API.get(
`/api/analytics/user-ranking?${queryParams}${separator}limit=100`,
{ signal, timeout: ANALYTICS_TIMEOUT_MS },
);
const params = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get('/api/analytics/user-ranking', {
params: { ...params, limit: 100 },
signal,
timeout: ANALYTICS_TIMEOUT_MS,
});
if (signal.aborted) return;
if (res.data.success) {
setUserRanking(res.data.data || []);
@@ -185,8 +185,9 @@ export const useAnalyticsData = (active = true) => {
const fetchDailyStats = useCallback(
async (currentPeriod, currentDateRange, signal) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get(`/api/analytics/daily-stats?${queryParams}`, {
const params = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get('/api/analytics/daily-stats', {
params,
signal,
timeout: ANALYTICS_TIMEOUT_MS,
});
@@ -205,12 +206,12 @@ export const useAnalyticsData = (active = true) => {
const fetchUserTopupRanking = useCallback(
async (currentPeriod, currentDateRange, signal) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const separator = queryParams ? '&' : '';
const res = await API.get(
`/api/analytics/user-topup-ranking?${queryParams}${separator}limit=50`,
{ signal, timeout: ANALYTICS_TIMEOUT_MS },
);
const params = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get('/api/analytics/user-topup-ranking', {
params: { ...params, limit: 50 },
signal,
timeout: ANALYTICS_TIMEOUT_MS,
});
if (signal.aborted) return;
if (res.data.success) {
setUserTopupRanking(res.data.data || []);
+11 -8
View File
@@ -295,7 +295,6 @@ export const useChannelsData = () => {
const { searchKeyword, searchGroup, searchModel } = getFormValues();
if (searchKeyword !== '' || searchGroup !== '' || searchModel !== '') {
setLoading(true);
await searchChannels(
enableTagMode,
typeKey,
@@ -305,20 +304,24 @@ export const useChannelsData = () => {
idSort,
signal,
);
setLoading(false);
return;
}
const reqId = ++requestCounter.current;
setSearching(false);
setLoading(true);
const typeParam = typeKey !== 'all' ? `&type=${typeKey}` : '';
const statusParam = statusF !== 'all' ? `&status=${statusF}` : '';
try {
const res = await API.get(
`/api/channel/?p=${page}&page_size=${pageSize}&id_sort=${idSort}&tag_mode=${enableTagMode}${typeParam}${statusParam}`,
{ signal },
);
const res = await API.get('/api/channel/', {
signal,
params: {
p: page,
page_size: pageSize,
id_sort: idSort,
tag_mode: enableTagMode,
type: typeKey === 'all' ? undefined : typeKey,
status: statusF === 'all' ? undefined : statusF,
},
});
if (
res === undefined ||
+28 -8
View File
@@ -1,9 +1,16 @@
import { useState, useEffect, useContext, useCallback, useMemo } from 'react';
import {
useState,
useEffect,
useContext,
useCallback,
useMemo,
useRef,
} from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { UserContext } from '../../context/User';
import { StatusContext } from '../../context/Status';
import { useSetTheme, useTheme, useActualTheme } from '../../context/Theme';
import { useSetTheme, useActualTheme } from '../../context/Theme';
import {
getLogo,
getSystemName,
@@ -12,6 +19,7 @@ import {
updateAPI,
} from '../../helpers';
import { rememberUserLanguage } from '../../i18n/bootstrap';
import { normalizeLanguage } from '../../i18n/language';
import { useIsMobile } from './useIsMobile';
import { useSidebarCollapsed } from './useSidebarCollapsed';
import { useMinimumLoadingTime } from './useMinimumLoadingTime';
@@ -34,6 +42,8 @@ export const useHeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
const [logoLoaded, setLogoLoaded] = useState(false);
const navigate = useNavigate();
const [currentLang, setCurrentLang] = useState(i18n.language);
const languageChanging = useRef(false);
const loggingOut = useRef(false);
const location = useLocation();
const loading = statusState?.status === undefined || userState?.authChecking;
@@ -94,7 +104,6 @@ export const useHeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
const isConsoleRoute = location.pathname.startsWith('/console');
const theme = useTheme();
const actualTheme = useActualTheme();
const setTheme = useSetTheme();
@@ -143,18 +152,31 @@ export const useHeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
// Actions
const logout = useCallback(async () => {
if (loggingOut.current) return;
loggingOut.current = true;
try {
await API.get('/api/user/logout');
userDispatch({ type: 'logout' });
clearUserData();
updateAPI();
navigate('/org/login');
} finally {
loggingOut.current = false;
}
}, [navigate, userDispatch]);
const handleLanguageChange = useCallback(
(lang) => {
async (lang) => {
if (languageChanging.current) return;
// 记为显式选择:此后优先于 IP 国家判定(后台关闭顶栏切换时失效)
rememberUserLanguage(lang);
i18n.changeLanguage(lang);
const language = rememberUserLanguage(lang);
if (!language || language === normalizeLanguage(i18n.language)) return;
languageChanging.current = true;
try {
await i18n.changeLanguage(language);
} finally {
languageChanging.current = false;
}
},
[i18n],
);
@@ -197,7 +219,6 @@ export const useHeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
docsLink,
isDemoSiteMode,
isConsoleRoute,
theme,
drawerOpen,
headerNavModules,
sidebarModulesAdmin,
@@ -211,7 +232,6 @@ export const useHeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
handleLanguageChange,
handleThemeToggle,
handleMobileMenuToggle,
navigate,
t,
};
};
+28 -4
View File
@@ -6,6 +6,9 @@ import {
} from '../../helpers/navigationVisibility';
import { getHeaderModuleRequireAuth } from '../../constants/headerNavModules';
import { useWeyAiWebEntry } from './useWeyAiWebEntry';
import { useAuthzView } from '../../authz';
import { useExperienceModules } from '../../pages/ExperienceCenter/useExperienceModules';
import { useUserCenterRoutes } from '../../pages/UserCenter/useUserCenterRoutes';
export const useNavigation = (
t,
@@ -23,6 +26,20 @@ export const useNavigation = (
} = orgEntry;
// WeyAi 网页端入口:按 /api/status 开关与 /api/client/v1/web/access 决定是否显示
const { visible: weyaiVisible, url: weyaiUrl } = useWeyAiWebEntry();
const { ready: navigationReady, defaultPath: experienceEntry } =
useExperienceModules();
const { firstRoute: userCenterEntry } = useUserCenterRoutes();
// 新权限体系:持有已切换的控制台菜单的非管理员(自定义平台角色)同样要有"控制台"入口,
// 否则路由和侧栏都放行了,却只能手输地址进入
const platformView = useAuthzView('platform');
const hasConsoleMenu = (platformView?.menus || []).some(
(m) =>
m.type === 'menu' &&
m.visible &&
typeof m.route === 'string' &&
m.route.startsWith('/console/') &&
platformView.enforcedSet?.has(platformView.moduleOf?.[m.code]),
);
const mainNavLinks = useMemo(() => {
const isAdminUser = userRole >= 10;
// 默认配置,如果没有传入配置则显示所有模块
@@ -113,7 +130,8 @@ export const useNavigation = (
{
text: t('体验中心'),
itemKey: 'experienceCenter',
to: '/experience-center',
to: (navigationReady && experienceEntry) || '/experience-center',
activePrefix: '/experience-center',
requireAuth: getHeaderModuleRequireAuth(modules, 'experienceCenter'),
},
{
@@ -132,7 +150,8 @@ export const useNavigation = (
{
text: t('用户中心'),
itemKey: 'userCenter',
to: '/user-center',
to: (navigationReady && userCenterEntry) || '/user-center',
activePrefix: '/user-center',
requireAuth: getHeaderModuleRequireAuth(modules, 'userCenter'),
},
// 企业中心:仅当用户属于某个企业时作为一级入口展示(不跟随 headerNavModules 配置,
@@ -165,7 +184,8 @@ export const useNavigation = (
{
text: t('控制台'),
itemKey: 'console',
to: '/console/analytics',
// 非管理员从 /console 进入,由入口路由落到第一个持有的菜单
to: isAdminUser ? '/console/analytics' : '/console',
activePrefix: '/console',
adminOnly: true,
requireAuth: true,
@@ -173,7 +193,7 @@ export const useNavigation = (
];
return allLinks.filter((link) => {
if (link.adminOnly && !isAdminUser) {
if (link.adminOnly && !isAdminUser && !hasConsoleMenu) {
return false;
}
if (link.alwaysShow) {
@@ -192,6 +212,10 @@ export const useNavigation = (
showPartnerEntry,
weyaiVisible,
weyaiUrl,
hasConsoleMenu,
navigationReady,
experienceEntry,
userCenterEntry,
]);
return {
+2 -1
View File
@@ -1,5 +1,6 @@
import { useState, useEffect } from 'react';
import { API } from '../../helpers/api';
import { getCurrentOrgId } from '../../helpers/orgContext';
const ADMIN_ROLES = ['owner', 'admin', 'super_admin'];
@@ -56,7 +57,7 @@ export const useOrgMembership = (userId, enabled = true) => {
// 选取当前企业:优先 localStorage 记录的,否则取第一个
let activeOrg = null;
if (hasOrg) {
const savedId = parseInt(localStorage.getItem('current_org_id') || '0', 10);
const savedId = getCurrentOrgId();
activeOrg = orgs.find((o) => o.id === savedId) || orgs[0];
}
const role = activeOrg?.role || 'member';
+5
View File
@@ -1,6 +1,8 @@
import { useCallback, useSyncExternalStore } from 'react';
const KEY = 'default_collapse_sidebar';
const TOGGLE_INTERVAL = 180;
let lastToggleAt = -Infinity;
/*
* 侧栏折叠态是「一份跨组件共享的状态」,不能用 useState——
@@ -65,6 +67,9 @@ export const useSidebarCollapsed = () => {
);
const toggle = useCallback(() => {
const now = performance.now();
if (now - lastToggleAt < TOGGLE_INTERVAL) return;
lastToggleAt = now;
setCollapsedState(!collapsedState);
}, []);
+44
View File
@@ -0,0 +1,44 @@
import { useCallback, useRef, useState } from 'react';
import { useSidebarToggleGuard } from './useSidebarToggleGuard';
function readGroups(storageKey) {
if (!storageKey) return [];
try {
const saved = JSON.parse(localStorage.getItem(storageKey));
return Array.isArray(saved) ? saved : [];
} catch {
return [];
}
}
export function useSidebarGroups(storageKey) {
const [keys, setKeys] = useState(() => readGroups(storageKey));
const current = useRef(keys);
const canToggle = useSidebarToggleGuard();
const setGroup = useCallback(
(key, included, persist = false) => {
const previous = current.current;
if (!key || previous.includes(key) === included) return;
const next = included
? [...previous, key]
: previous.filter((item) => item !== key);
current.current = next;
setKeys(next);
if (persist && storageKey) {
try {
localStorage.setItem(storageKey, JSON.stringify(next));
} catch {
// Keep the in-memory preference if storage is unavailable.
}
}
},
[storageKey],
);
const toggle = (key) => {
if (canToggle(key)) setGroup(key, !current.current.includes(key), true);
};
return { keys, toggle, setGroup };
}
+16
View File
@@ -0,0 +1,16 @@
import { useCallback, useRef } from 'react';
const TOGGLE_INTERVAL = 180;
export function useSidebarToggleGuard() {
const lastToggle = useRef(new Map());
return useCallback((key) => {
const now = performance.now();
if (now - (lastToggle.current.get(key) ?? -Infinity) < TOGGLE_INTERVAL) {
return false;
}
lastToggle.current.set(key, now);
return true;
}, []);
}
+66
View File
@@ -0,0 +1,66 @@
import { useEffect, useRef } from 'react';
import { resolvePath, useLocation, useNavigate } from 'react-router-dom';
import { useEffectEvent } from './useEffectEvent';
const NAVIGATION_INTERVAL = 180;
const normalizePathname = (path) => path.replace(/\/+$/, '') || '/';
export function useTopNavigation() {
return useThrottledNavigation();
}
export function useSidebarNavigation(onNavigate) {
return useThrottledNavigation({ exact: true, onNavigate });
}
function useThrottledNavigation({ exact = false, onNavigate } = {}) {
const location = useLocation();
const navigate = useNavigate();
const timer = useRef();
const lastNavigationAt = useRef(-Infinity);
useEffect(() => () => clearTimeout(timer.current), []);
return useEffectEvent((to, event) => {
if (
!to ||
event?.defaultPrevented ||
(event &&
((event.button != null && event.button !== 0) ||
event.metaKey ||
event.altKey ||
event.ctrlKey ||
event.shiftKey))
) {
return;
}
event?.preventDefault();
clearTimeout(timer.current);
const target = resolvePath(to, location.pathname);
const current = window.location;
if (
normalizePathname(target.pathname) ===
normalizePathname(current.pathname) &&
(target.search === current.search || (!exact && !target.search)) &&
(target.hash === current.hash || (!exact && !target.hash))
) {
onNavigate?.();
return;
}
const originKey = window.history.state?.key;
const go = () => {
// Back/forward or a different control may have navigated during the wait.
if (window.history.state?.key !== originKey) return;
lastNavigationAt.current = performance.now();
navigate(to);
onNavigate?.();
};
const wait =
NAVIGATION_INTERVAL - (performance.now() - lastNavigationAt.current);
// Apply the first click immediately and keep only the newest queued click.
if (wait > 0) timer.current = setTimeout(go, wait);
else go();
});
}
+10 -6
View File
@@ -207,13 +207,17 @@ export const useMjLogsData = () => {
setLoading(true);
const { channel_id, mj_id, start_timestamp, end_timestamp } =
getFormValues();
let localStartTimestamp = Date.parse(start_timestamp);
let localEndTimestamp = Date.parse(end_timestamp);
const url = isAdminUser
? `/api/mj/?p=${page}&page_size=${size}&channel_id=${channel_id}&mj_id=${mj_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`
: `/api/mj/self/?p=${page}&page_size=${size}&mj_id=${mj_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`;
const url = isAdminUser ? '/api/mj/' : '/api/mj/self/';
const params = {
p: page,
page_size: size,
mj_id,
start_timestamp: Date.parse(start_timestamp),
end_timestamp: Date.parse(end_timestamp),
};
if (isAdminUser) params.channel_id = channel_id;
try {
const res = await API.get(url, { signal });
const res = await API.get(url, { params, signal });
if (requestId !== listRequestIdRef.current || signal?.aborted) return;
const { success, message, data } = res.data;
if (success) {
+95 -24
View File
@@ -225,6 +225,17 @@ export function useOrgPromptRecords(orgId) {
return { records, total, loading, error, fetch };
}
// 此接口只有首页会计算总数。保留当前页重新筛选时,用相同范围取一条首页记录以获取计数。
export async function fetchOrgLogTotal(options) {
const { data } = await API.get('/api/org/logs', {
...options,
params: { ...options.params, p: 1, page_size: 1 },
});
if (!data.success)
throw new Error(data.message || i18next.t('加载消耗明细失败'));
return data.data.total;
}
// 获取企业成员消耗日志
export function useOrgMemberLogs(orgId) {
const [logs, setLogs] = useState([]);
@@ -233,7 +244,13 @@ export function useOrgMemberLogs(orgId) {
const request = useRef(0);
const fetch = useCallback(
async (page = 1, pageSize = 20, filters = {}, signal) => {
async (
page = 1,
pageSize = 20,
filters = {},
signal,
refreshTotal = false,
) => {
if (!orgId) return;
const id = ++request.current;
setLoading(true);
@@ -244,16 +261,20 @@ export function useOrgMemberLogs(orgId) {
...buildOrgLogFilters(filters),
};
const res = await API.get('/api/org/logs', {
const options = {
headers: getOrgHeaders(orgId),
params,
signal,
});
};
const [res, filteredTotal] = await Promise.all([
API.get('/api/org/logs', options),
refreshTotal && page > 1 ? fetchOrgLogTotal(options) : null,
]);
if (signal?.aborted || id !== request.current) return;
if (res.data.success) {
setLogs(res.data.data?.items || []);
// 后端在翻页(page>1)时跳过 COUNT 并返回 total=-1,此处保留首页已知总数,避免分页器异常
const nextTotal = res.data.data?.total;
const nextTotal = filteredTotal ?? res.data.data?.total;
if (typeof nextTotal === 'number' && nextTotal >= 0) {
setTotal(nextTotal);
}
@@ -333,44 +354,89 @@ export function useOrgLogsStat(orgId) {
}
// 获取企业成员消耗排行榜
export function useOrgMemberRanking(orgId) {
const [ranking, setRanking] = useState([]);
const [loading, setLoading] = useState(false);
const emptyRankingPage = { items: [], total: 0, page: 1, page_size: 10 };
export function useOrgMemberRanking(orgId) {
const [rankingPage, setRankingPage] = useState(emptyRankingPage);
const [loading, setLoading] = useState(false);
const request = useRef(null);
const cancel = useCallback(() => {
request.current?.abort();
request.current = null;
}, []);
useEffect(() => {
setRankingPage(emptyRankingPage);
setLoading(false);
return cancel;
}, [orgId, cancel]);
const request = useRef(0);
const fetch = useCallback(
async ({ limit, ...filters } = {}, noCache = false, signal) => {
if (!orgId) return;
const id = ++request.current;
async function fetchPage(
filters,
{ page = 1, pageSize = 10, snapshot, noCache = false, signal } = {},
) {
if (!orgId || signal?.aborted) return;
request.current?.abort();
const requestGroup = new AbortController();
request.current = requestGroup;
setLoading(true);
// 新筛选加载期间收起旧分页,避免旧快照和新条件一起提交。
if (!snapshot)
setRankingPage({ ...emptyRankingPage, page_size: pageSize });
try {
const params = buildOrgLogFilters(filters);
if (limit) params.limit = limit;
if (noCache) params.nocache = 1;
const params = {
...buildOrgLogFilters(filters),
p: page,
page_size: pageSize,
};
if (snapshot) params.snapshot = snapshot;
else if (noCache) params.nocache = 1;
const res = await API.get('/api/org/logs/ranking', {
headers: getOrgHeaders(orgId),
params,
signal,
requestGroup,
});
if (signal?.aborted || id !== request.current) return;
if (res.data.success) {
setRanking(res.data.data || []);
} else {
setRanking([]);
showError(res.data.message || i18next.t('加载成员排行失败'));
if (signal?.aborted || requestGroup !== request.current) return;
const { success, data: result, message, code } = res.data;
if (!success) {
if (snapshot && code === 'ranking_snapshot_expired') {
return fetchPage(filters, { pageSize, signal });
}
setRankingPage({ ...emptyRankingPage, page_size: pageSize });
showError(message || i18next.t('加载成员排行失败'));
return;
}
const lastPage = Math.max(
1,
Math.ceil(result.total / result.page_size),
);
if (result.total > 0 && page > lastPage) {
return fetchPage(filters, {
page: lastPage,
pageSize,
snapshot: result.snapshot,
signal,
});
}
setRankingPage(result.total === 0 ? { ...result, page: 1 } : result);
} catch (err) {
if (!signal?.aborted && id === request.current && !err.isAxiosError)
showError(err.message);
if (signal?.aborted || requestGroup !== request.current) return;
setRankingPage({ ...emptyRankingPage, page_size: pageSize });
if (!err.isAxiosError) showError(err.message);
} finally {
if (id === request.current) setLoading(false);
if (requestGroup === request.current) {
request.current = null;
setLoading(false);
}
}
},
[orgId],
);
return { ranking, loading, fetch };
return { rankingPage, loading, fetch, cancel };
}
// 获取企业Token列表
@@ -506,7 +572,12 @@ export function useOrgTokens(orgId) {
showError(res.data.message);
return null;
} catch (err) {
// 取明文按操作人限流(每分钟 20 次),超出时返回 429
if (err?.response?.status === 429) {
showError(i18next.t('查看密钥过于频繁,请稍后再试'));
} else {
showError(err.message);
}
return null;
}
},
+141 -161
View File
@@ -1,4 +1,4 @@
import { useState, useCallback } from 'react';
import { useState, useCallback, useRef } from 'react';
import { API } from '../../helpers/api';
import { showError } from '../../helpers';
@@ -6,220 +6,194 @@ const getOrgHeaders = (orgId) => ({
'X-Org-Id': String(orgId),
});
/**
* 员工管理数据入口:服务端筛选 + 服务端分页的员工列表,以及员工的各项写操作。
* 写操作失败时已提示后端返回的原因,调用方只需按返回值决定是否关闭弹层、刷新列表。
*/
export function useOrgMembers(orgId) {
const [members, setMembers] = useState([]);
const [items, setItems] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
// 只采用最后一次查询的结果,避免快速切换筛选时旧响应覆盖新结果
const seqRef = useRef(0);
const fetch = useCallback(
async (page = 1, pageSize = 20) => {
async (page = 1, pageSize = 10, filters = {}) => {
if (!orgId) return;
const seq = ++seqRef.current;
// 筛选条件空值不传;department_id 传 -1 表示未分配部门
const params = { p: page, page_size: pageSize };
const keyword = (filters.keyword || '').trim();
if (keyword) params.keyword = keyword;
if (filters.group) params.group = filters.group;
if (filters.department_id) params.department_id = filters.department_id;
if (filters.status) params.status = filters.status;
setLoading(true);
try {
const res = await API.get('/api/org/members', {
headers: getOrgHeaders(orgId),
params: { p: page, page_size: pageSize },
params,
});
if (res.data.success) {
setMembers(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
if (seq !== seqRef.current) return;
const { success, message, data } = res.data;
if (!success) {
showError(message);
return;
}
} catch (err) {
showError(err.message);
setItems(data?.items || []);
setTotal(data?.total || 0);
} catch (error) {
if (seq === seqRef.current) showError(error);
} finally {
setLoading(false);
if (seq === seqRef.current) setLoading(false);
}
},
[orgId],
);
// 统一的写请求:成功返回 { data },失败(已提示原因)返回 null
const send = useCallback(
async (request) => {
if (!orgId) return null;
try {
const res = await request({ headers: getOrgHeaders(orgId) });
const { success, message, data } = res.data;
if (!success) {
showError(message);
return null;
}
return { data };
} catch (error) {
showError(error);
return null;
}
},
[orgId],
);
const put = useCallback(
async (path, body) => !!(await send((cfg) => API.put(path, body, cfg))),
[send],
);
const removeMember = useCallback(
async (memberId) => {
if (!orgId) return false;
try {
const res = await API.delete(`/api/org/members/${memberId}`, {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
async (memberId) =>
!!(await send((cfg) => API.delete(`/api/org/members/${memberId}`, cfg))),
[send],
);
const updateMemberRole = useCallback(
async (memberId, role) => {
if (!orgId) return false;
try {
const res = await API.put(
`/api/org/members/${memberId}/role`,
{ role },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
(memberId, role) => put(`/api/org/members/${memberId}/role`, { role }),
[put],
);
const updateMemberQuota = useCallback(
async (memberId, quotaLimit, quotaPeriod = 'none') => {
if (!orgId) return false;
try {
const res = await API.put(
`/api/org/members/${memberId}/quota`,
{ quota_limit: quotaLimit, quota_period: quotaPeriod },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
(memberId, quotaLimit, quotaPeriod = 'none') =>
put(`/api/org/members/${memberId}/quota`, {
quota_limit: quotaLimit,
quota_period: quotaPeriod,
}),
[put],
);
const updateMemberStatus = useCallback(
async (memberId, status) => {
if (!orgId) return false;
try {
const res = await API.put(
`/api/org/members/${memberId}/status`,
{ status },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
(memberId, status) =>
put(`/api/org/members/${memberId}/status`, { status }),
[put],
);
const updateMemberModelLimits = useCallback(
async (memberId, modelLimitsEnabled, modelLimits) => {
if (!orgId) return false;
try {
const res = await API.put(
`/api/org/members/${memberId}/models`,
{
(memberId, modelLimitsEnabled, modelLimits) =>
put(`/api/org/members/${memberId}/models`, {
model_limits_enabled: modelLimitsEnabled,
model_limits: modelLimits,
},
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
}),
[put],
);
const updateMemberGroups = useCallback(
async (memberId, groups) => {
if (!orgId) return false;
try {
const res = await API.put(
`/api/org/members/${memberId}/groups`,
{ groups },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
(memberId, groups) =>
put(`/api/org/members/${memberId}/groups`, { groups }),
[put],
);
// 更新管理员细粒度权限(owner-only)。permissions 为 {key: bool} 对象。
const updateMemberAdminPermissions = useCallback(
async (memberId, permissions) => {
if (!orgId) return false;
try {
const res = await API.put(
`/api/org/members/${memberId}/admin-permissions`,
{ permissions },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
(memberId, permissions) =>
put(`/api/org/members/${memberId}/admin-permissions`, { permissions }),
[put],
);
const updateMemberRemark = useCallback(
async (memberId, remark) => {
if (!orgId) return false;
try {
const res = await API.put(
`/api/org/members/${memberId}/remark`,
{ remark },
{ headers: getOrgHeaders(orgId) },
(memberId, remark) =>
put(`/api/org/members/${memberId}/remark`, { remark }),
[put],
);
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
// 修改员工资料:profile 只含要改的字段(display_name / email / employee_no / remark),同一事务保存
const updateMemberProfile = useCallback(
(memberId, profile) => put(`/api/org/members/${memberId}/profile`, profile),
[put],
);
// 分配主部门:departmentId 为 0 表示未分配
const assignMemberDept = useCallback(
(memberId, departmentId) =>
put(`/api/org/members/${memberId}/dept`, {
department_id: departmentId || 0,
}),
[put],
);
// 新建员工账号:成功返回 { username, login_name, initial_password, login_name_global_collision }
const createMemberAccount = useCallback(
async (payload) => {
const result = await send((cfg) =>
API.post('/api/org/members/create-account', payload, cfg),
);
return result ? result.data : null;
},
[orgId],
[send],
);
// 重置密码:成功返回一次性临时密码
const resetMemberPassword = useCallback(
async (memberId) => {
const result = await send((cfg) =>
API.put(`/api/org/members/${memberId}/reset-password`, {}, cfg),
);
return result ? result.data?.temp_password || '' : null;
},
[send],
);
const offboardMember = useCallback(
(memberId) => put(`/api/org/members/${memberId}/offboard`, {}),
[put],
);
// CSV 导入:成功返回 { total, success, failed, details }
const importMembers = useCallback(
async (file) => {
const body = new FormData();
body.append('file', file);
const result = await send((cfg) =>
API.post('/api/org/members/import', body, cfg),
);
return result ? result.data : null;
},
[send],
);
// 乐观更新:直接修改本地列表中某成员的字段,无需重新请求
const updateMemberInList = useCallback((memberId, updates) => {
setMembers((prev) =>
setItems((prev) =>
prev.map((m) => (m.id === memberId ? { ...m, ...updates } : m)),
);
}, []);
return {
members,
items,
total,
loading,
fetch,
@@ -230,7 +204,13 @@ export function useOrgMembers(orgId) {
updateMemberGroups,
updateMemberStatus,
updateMemberRemark,
updateMemberProfile,
updateMemberAdminPermissions,
assignMemberDept,
createMemberAccount,
resetMemberPassword,
offboardMember,
importMembers,
updateMemberInList,
};
}
+34 -43
View File
@@ -7,15 +7,16 @@ import {
REDEMPTION_STATUS,
} from '../../constants/redemption.constants';
import { Modal } from '@/components/ui';
import { confirmTableAction } from '@/components/common/table/confirmTableAction';
import { useTranslation } from 'react-i18next';
import { useTableCompactMode } from '../common/useTableCompactMode';
export const useRedemptionsData = () => {
export const useRedemptionsData = (canQuery) => {
const { t } = useTranslation();
// Basic state
const [redemptions, setRedemptions] = useState([]);
const [loading, setLoading] = useState(true);
const [loading, setLoading] = useState(canQuery);
const [searching, setSearching] = useState(false);
const [activePage, setActivePage] = useState(1);
const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
@@ -57,10 +58,10 @@ export const useRedemptionsData = () => {
const loadRedemptions = async (page = 1, pageSize, signal) => {
setLoading(true);
try {
const res = await API.get(
`/api/redemption/?p=${page}&page_size=${pageSize}`,
{ signal },
);
const res = await API.get('/api/redemption/', {
params: { p: page, page_size: pageSize },
signal,
});
if (signal?.aborted) return;
const { success, message, data } = res.data;
if (success) {
@@ -159,7 +160,9 @@ export const useRedemptionsData = () => {
};
// Refresh data
const refresh = (page = activePage) => loadPage(page, pageSize);
const refresh = (page = activePage) => {
if (canQuery) return loadPage(page, pageSize);
};
// Handle page change
const handlePageChange = (page) => {
@@ -185,28 +188,6 @@ export const useRedemptionsData = () => {
},
};
// Row style handling - using isExpired function
const handleRow = (record, index) => {
// Local isExpired function
const isExpired = (rec) => {
return (
rec.status === REDEMPTION_STATUS.UNUSED &&
rec.expired_time !== 0 &&
rec.expired_time < Math.floor(Date.now() / 1000)
);
};
if (record.status !== REDEMPTION_STATUS.UNUSED || isExpired(record)) {
return {
style: {
background: 'var(--ui-color-disabled-border)',
},
};
} else {
return {};
}
};
// Copy text
const copyText = async (text) => {
if (await copy(text)) {
@@ -235,21 +216,28 @@ export const useRedemptionsData = () => {
};
// Batch delete redemption codes (clear invalid)
const batchDeleteRedemptions = async () => {
Modal.confirm({
const batchDeleteRedemptions = () => {
confirmTableAction({
title: t('确定清除所有失效兑换码?'),
content: t('将删除已使用、已禁用及过期的兑换码,此操作不可撤销。'),
focusable: { autoFocusButton: 'cancel' },
onOk: async () => {
setLoading(true);
try {
const res = await API.delete('/api/redemption/invalid');
const { success, message, data } = res.data;
if (success) {
if (!success) {
showError(message);
return false;
}
showSuccess(t('已删除 {{count}} 条失效兑换码', { count: data }));
await refresh();
} else {
showError(message);
}
} catch (error) {
if (!error.isAxiosError) showError(error.message);
return false;
} finally {
setLoading(false);
}
},
});
};
@@ -272,14 +260,18 @@ export const useRedemptionsData = () => {
};
// Initialize data loading
const onScopeChange = useEffectEvent(() => {
loadRedemptions(1, pageSize)
.then()
.catch((reason) => {
showError(reason);
const onScopeChange = useEffectEvent((signal) => {
void loadRedemptions(1, pageSize, signal);
});
});
useEffect(() => onScopeChange(), [onScopeChange]);
useEffect(() => {
if (!canQuery) {
setSelectedKeys([]);
return;
}
const controller = new AbortController();
onScopeChange(controller.signal);
return () => controller.abort();
}, [canQuery, onScopeChange]);
return {
// Data state
@@ -324,7 +316,6 @@ export const useRedemptionsData = () => {
handlePageChange,
handlePageSizeChange,
rowSelection,
handleRow,
closeEdit,
getFormValues,
+10 -10
View File
@@ -335,28 +335,28 @@ export const useTaskLogsData = ({
}
return;
}
const params = new URLSearchParams({
const params = {
p: page,
page_size: size,
task_id,
start_timestamp: localStartTimestamp,
end_timestamp: localEndTimestamp,
});
};
// 空值不带到 URL,保持 query 简洁,也避免后端误把空串当作精确匹配
if (status) params.set('status', status);
if (action) params.set('action', action);
if (status) params.status = status;
if (action) params.action = action;
if (isAdminUser) {
params.set('channel_id', channel_id);
params.channel_id = channel_id;
// 与使用日志对齐:管理员可按 user_id 过滤任务日志
if (user_id) params.set('user_id', user_id);
if (user_id) params.user_id = user_id;
}
const url = organizationMode
? `/api/org/tasks?${params.toString()}`
? '/api/org/tasks'
: isAdminUser
? `/api/task/?${params.toString()}`
: `/api/task/self?${params.toString()}`;
? '/api/task/'
: '/api/task/self';
try {
const res = await API.get(url, { signal });
const res = await API.get(url, { params, signal });
// 过时响应直接丢弃:reqId 小于最新值说明更新的请求已经发出
if (reqId !== requestIdRef.current || signal?.aborted) return;
const { success, message, data } = res.data;
+8 -3
View File
@@ -73,7 +73,8 @@ export const useTokensData = (openFluentNotification) => {
const loadTokens = async (page = 1, size = pageSize, signal) => {
setLoading(true);
try {
const res = await API.get(`/api/token/?p=${page}&size=${size}`, {
const res = await API.get('/api/token/', {
params: { p: page, page_size: size },
signal,
});
if (signal?.aborted) return;
@@ -154,11 +155,15 @@ export const useTokensData = (openFluentNotification) => {
break;
case 'enable':
data.status = 1;
res = await API.put('/api/token/?status_only=true', data);
res = await API.put('/api/token/', data, {
params: { status_only: true },
});
break;
case 'disable':
data.status = 2;
res = await API.put('/api/token/?status_only=true', data);
res = await API.put('/api/token/', data, {
params: { status_only: true },
});
break;
}
const { success, message } = res.data;
+11 -30
View File
@@ -296,16 +296,15 @@ export const useLogsData = () => {
const currentLogType = formLogType || 0;
let localStartTimestamp = Date.parse(start_timestamp) / 1000;
let localEndTimestamp = Date.parse(end_timestamp) / 1000;
const params = new URLSearchParams({
const params = {
type: currentLogType,
token_name,
model_name,
start_timestamp: localStartTimestamp,
end_timestamp: localEndTimestamp,
group,
});
const url = `/api/log/self/stat?${params.toString()}`;
const res = await API.get(url, { signal });
};
const res = await API.get('/api/log/self/stat', { params, signal });
if (signal?.aborted || requestId !== statRequest.current) return;
const { success, message, data } = res.data;
if (success) {
@@ -331,7 +330,7 @@ export const useLogsData = () => {
const currentLogType = formLogType || 0;
let localStartTimestamp = Date.parse(start_timestamp) / 1000;
let localEndTimestamp = Date.parse(end_timestamp) / 1000;
const params = new URLSearchParams({
const params = {
type: currentLogType,
username,
token_name,
@@ -341,9 +340,8 @@ export const useLogsData = () => {
channel,
group,
user_id,
});
const url = `/api/log/stat?${params.toString()}`;
const res = await API.get(url, { signal });
};
const res = await API.get('/api/log/stat', { params, signal });
if (signal?.aborted || requestId !== statRequest.current) return;
const { success, message, data } = res.data;
if (success) {
@@ -499,7 +497,6 @@ export const useLogsData = () => {
const reqId = ++logsRequestIdRef.current;
setLoading(true);
let url = '';
const {
username,
token_name,
@@ -528,23 +525,8 @@ export const useLogsData = () => {
if (reqId === logsRequestIdRef.current) setLoading(false);
return;
}
if (isAdminUser) {
const params = new URLSearchParams({
p: startIdx,
page_size: pageSize,
type: currentLogType,
username,
token_name,
model_name,
start_timestamp: localStartTimestamp,
end_timestamp: localEndTimestamp,
channel,
group,
user_id,
});
url = `/api/log/?${params.toString()}`;
} else {
const params = new URLSearchParams({
const url = isAdminUser ? '/api/log/' : '/api/log/self';
const params = {
p: startIdx,
page_size: pageSize,
type: currentLogType,
@@ -553,11 +535,10 @@ export const useLogsData = () => {
start_timestamp: localStartTimestamp,
end_timestamp: localEndTimestamp,
group,
});
url = `/api/log/self?${params.toString()}`;
}
...(isAdminUser ? { username, channel, user_id } : {}),
};
try {
const res = await API.get(url, { signal });
const res = await API.get(url, { params, signal });
// 丢弃过期响应,只处理仍然是最新的请求
if (reqId !== logsRequestIdRef.current || signal?.aborted) return;
const { success, message, data } = res.data;
+52 -18
View File
@@ -29,6 +29,7 @@ export const useUsersData = () => {
const formInitValues = {
searchKeyword: '',
searchGroup: '',
searchStatus: '',
};
// Form API reference
@@ -40,6 +41,7 @@ export const useUsersData = () => {
return {
searchKeyword: formValues.searchKeyword || '',
searchGroup: formValues.searchGroup || '',
searchStatus: formValues.searchStatus || '',
};
};
@@ -58,10 +60,10 @@ export const useUsersData = () => {
setSearching(false);
setLoading(true);
try {
const res = await API.get(
`/api/user/?p=${startIdx}&page_size=${pageSize}`,
{ signal },
);
const res = await API.get('/api/user/', {
params: { p: startIdx, page_size: pageSize },
signal,
});
if (id !== listRequest.current || signal?.aborted) return;
const { success, message, data } = res.data;
if (success) {
@@ -77,12 +79,13 @@ export const useUsersData = () => {
}
};
// Search users with keyword and group
// Search users with keyword, group and status (1 启用 / 2 禁用)
const searchUsers = async (
startIdx,
pageSize,
searchKeyword = null,
searchGroup = null,
searchStatus = null,
signal,
) => {
// If no parameters passed, get values from form
@@ -90,10 +93,11 @@ export const useUsersData = () => {
const formValues = getFormValues();
searchKeyword = formValues.searchKeyword;
searchGroup = formValues.searchGroup;
if (searchStatus === null) searchStatus = formValues.searchStatus;
}
searchStatus = searchStatus || '';
if (searchKeyword === '' && searchGroup === '') {
// If both filters are blank, load users instead
if (searchKeyword === '' && searchGroup === '' && searchStatus === '') {
await loadUsers(startIdx, pageSize, signal);
return;
}
@@ -106,6 +110,8 @@ export const useUsersData = () => {
params: {
keyword: searchKeyword,
group: searchGroup,
// 未选状态时不带该参数(后端 0 = 不筛选)
status: searchStatus || undefined,
p: startIdx,
page_size: pageSize,
},
@@ -126,6 +132,7 @@ export const useUsersData = () => {
};
// Manage user operations (promote, demote, enable, disable, delete)
// 返回是否成功;失败时列表保持原状态(状态 Switch 受控于 record.status,自然回到原位)
const manageUser = async (userId, action, record) => {
// Trigger loading state to force table re-render
setLoading(true);
@@ -141,7 +148,8 @@ export const useUsersData = () => {
const user = res.data.data;
// Create a new array and new object to ensure React detects changes
const newUsers = users.map((u) => {
setUsers((current) =>
current.map((u) => {
if (u.id === userId) {
if (action === 'delete') {
return { ...u, DeletedAt: new Date() };
@@ -149,18 +157,44 @@ export const useUsersData = () => {
return { ...u, status: user.status, role: user.role };
}
return u;
});
setUsers(newUsers);
} else {
showError(message);
}),
);
return true;
}
return success;
showError(message);
return false;
} catch (error) {
showError(error);
return false;
} finally {
setLoading(false);
}
};
// 额度调整(PRD AC59):按调整量累加(内部额度单位,可正可负),成功后用返回的新额度同步列表
const adjustUserQuota = async (userId, delta) => {
try {
const res = await API.post('/api/user/manage', {
id: userId,
action: 'add_quota',
value: delta,
});
const { success, message, data } = res.data;
if (success) {
showSuccess(t('额度已调整'));
setUsers((prev) =>
prev.map((u) => (u.id === userId ? { ...u, quota: data.quota } : u)),
);
return true;
}
showError(message);
return false;
} catch (error) {
showError(error);
return false;
}
};
const resetUserPasskey = async (user) => {
if (!user) {
return;
@@ -227,9 +261,8 @@ export const useUsersData = () => {
};
// Refresh data
const refresh = async (page = activePage, size = pageSize) => {
await searchUsers(page, size);
};
const refresh = (page = activePage, size = pageSize, signal) =>
searchUsers(page, size, null, null, null, signal);
// Fetch groups data
const fetchGroups = async () => {
@@ -264,7 +297,7 @@ export const useUsersData = () => {
// Initialize data on component mount
const onMount = useEffectEvent(() => {
loadUsers(0, pageSize)
loadUsers(1, pageSize)
.then()
.catch((reason) => {
showError(reason);
@@ -304,6 +337,7 @@ export const useUsersData = () => {
loadUsers,
searchUsers,
manageUser,
adjustUserQuota,
resetUserPasskey,
resetUserTwoFA,
handlePageChange,
+46 -4
View File
@@ -78,7 +78,7 @@ async function createHarness() {
params: Object.fromEntries(parsed.searchParams),
};
requests.push(request);
return respond(request);
return respond(request, config);
},
},
showError: (error) => errors.push(error),
@@ -132,14 +132,14 @@ function assertRequest(request, page, size, filters = {}) {
});
}
test('mount keeps the initial page-zero fetch and formats returned users', async () => {
test('mount requests the first page and formats returned users', async () => {
const harness = await createHarness();
assertRequest(harness.requests[0], 0, defaultPageSize);
assertRequest(harness.requests[0], 1, defaultPageSize);
assert.equal(harness.requests[1].path, '/api/group/');
const data = harness.render();
assert.equal(data.loading, false);
assert.equal(data.searching, false);
assert.equal(data.activePage, 0);
assert.equal(data.activePage, 1);
assert.equal(data.userCount, 1);
assert.equal(data.users[0].key, 42);
});
@@ -201,6 +201,48 @@ test('form search still reads current filters and supports explicit filters and
assertRequest(harness.requests[2], 1, 20);
});
test('status filter alone uses the search endpoint and is omitted when unset', async () => {
const harness = await createHarness();
let values = { searchKeyword: '', searchGroup: '', searchStatus: 2 };
harness.render().setFormApi({ getValues: () => values });
harness.requests.length = 0;
await harness.render().searchUsers(1, 20);
assert.deepEqual(harness.requests[0], {
path: '/api/user/search',
params: { keyword: '', group: '', status: '2', p: '1', page_size: '20' },
});
values = { searchKeyword: 'alice', searchGroup: '', searchStatus: '' };
await harness.render().searchUsers(1, 20);
assertRequest(harness.requests[1], 1, 20, values);
});
test('live status filtering passes the abort signal separately and discards canceled results', async () => {
const harness = await createHarness();
const controller = new AbortController();
harness.render().setFormApi({ getValues: () => ({ searchStatus: 2 }) });
let resolveRequest;
harness.setResponder((request, config) => {
assert.equal(request.path, '/api/user/search');
assert.equal(request.params.status, '2');
assert.equal(request.params.p, '4');
assert.equal(config.signal, controller.signal);
return new Promise((resolve) => {
resolveRequest = resolve;
});
});
const pending = harness.render().refresh(4, 20, controller.signal);
controller.abort();
resolveRequest({
data: { success: true, data: { page: 4, total: 0, items: [] } },
});
await pending;
assert.equal(harness.render().users[0].id, 42);
assert.equal(harness.render().activePage, 1);
assert.equal(harness.render().searching, false);
});
for (const action of ['loadUsers', 'searchUsers', 'blank search fallback']) {
test(`${action} clears its pending flag and propagates request rejection`, async () => {
const harness = await createHarness();
+431 -18
View File
@@ -1,5 +1,53 @@
{
"translation": {
"允许模型判定": "Model decisions allowed",
"请在「智能路由 → 全局设置」中保存判定模型的密钥或代理": "Save the decision model key or proxy under Smart routing → Global settings",
"判定模型接口地址须为以 http:// 或 https:// 开头的完整地址": "Enter a complete decision model endpoint starting with http:// or https://",
"需平台开启模型判定,并取得相应的数据出境授权。": "The platform must enable model decisions and the relevant cross-border data transfer consent must be granted.",
"判定模型专用代理": "Dedicated proxy for the decision model",
"仅用于调用判定模型。": "Used only for calls to the decision model.",
"跟随服务器网络设置": "Use server network settings",
"测试代理": "Test proxy",
"保存代理": "Save proxy",
"确认清除判定模型代理?": "Clear the decision model proxy?",
"清除代理": "Clear proxy",
"Google 已连通": "Google is reachable",
"Google 未连通": "Google is unreachable",
"出口 IP {{ip}} · {{region}}": "Exit IP {{ip}} · {{region}}",
"地区未知": "Unknown region",
"出口 IP 未获取": "Exit IP unavailable",
"连接超时": "Connection timed out",
"TLS 证书校验失败": "TLS certificate verification failed",
"代理认证失败": "Proxy authentication failed",
"代理连接失败": "Proxy connection failed",
"代理地址无效,请使用 HTTP、HTTPS、SOCKS5 或 SOCKS5H 地址": "Enter a valid HTTP, HTTPS, SOCKS5 or SOCKS5H proxy URL",
"无法读取已保存的判定模型代理,请重新配置": "Unable to read the saved decision model proxy. Configure it again.",
"尚未设置判定模型代理": "No proxy is configured for the decision model",
"判定模型代理配置加密失败": "Failed to encrypt the decision model proxy configuration",
"Claude 联网搜索": "Claude web search",
"超管指标": "Root metrics",
"仅超级管理员可见": "Root admins only",
"官方价金额(1 倍率)": "Official amount (1x)",
"整体倍率": "Overall ratio",
"实际折扣": "Actual discount",
"整体倍率 = 实扣 ÷ 官方价金额;实际折扣 = 整体倍率 ÷ 登记汇率({{rate}})": "Overall ratio = charged ÷ official amount; actual discount = overall ratio ÷ exchange rate ({{rate}})",
"原厂价登记汇率": "Official price exchange rate",
"下方原厂价格表中的数值 = 官方实际价格 × 该汇率。仅用于超级管理员在使用日志详情里看到的「整体倍率」(实扣 ÷ 官方实际价格),不参与计费与成本核算。": "Values in the official price table below = actual official price × this rate. It is only used for the \"overall ratio\" (charged ÷ actual official price) shown to root admins in usage log details, and does not affect billing or cost accounting.",
"请输入大于 0 且不超过 1000 的数字": "Enter a number greater than 0 and at most 1000",
"{{price}} / 秒": "{{price}} / second",
"总金额 = 各计费项小计之和,小计 = 用量 × 单价": "Total = sum of all line subtotals; subtotal = usage × unit price",
"费用明细": "Cost breakdown",
"计费项": "Item",
"用量": "Usage",
"小计": "Subtotal",
"总金额": "Total",
"计算公式": "Formula",
"输入(未命中缓存)": "Input (uncached)",
"图片倍率": "Image ratio",
"舍入与其他调整": "Rounding & other adjustments",
"{{price}} / 1M tokens": "{{price}} / 1M tokens",
"{{price}} / 次": "{{price}} / call",
"各项小计为四舍五入后的近似值,合计以实际扣费为准": "Subtotals are rounded for display; the total reflects the actual charge",
"数据加载失败,请刷新重试": "Failed to load data. Please refresh and try again.",
"伙伴工作台": "Partner workspace",
"屏蔽通知": "Mute alerts",
@@ -1560,6 +1608,9 @@
"兑换": "Redeem",
"兑换成功!": "Redemption successful!",
"兑换额度": "Redeem",
"兑换码": "Redemption code",
"兑换码列表": "Redemption codes",
"编辑兑换码信息": "Edit redemption code",
"兑换码充值": "Redemption code recharge",
"兑换码创建成功": "Redemption Code Created",
"兑换码创建成功,是否下载兑换码?": "Redemption code created successfully. Do you want to download it?",
@@ -5916,6 +5967,8 @@
"投递健康": "Delivery health",
"投递通道": "Delivery channels",
"投递正常": "Delivery normal",
"透传时应用模型映射": "Apply model mapping during pass-through",
"请求体透传时,使用本渠道模型重定向后的模型名发送给上游,其余字段按原请求转发。": "When passing through the request body, send the model name from this channel’s model mapping to the upstream service. Forward all other fields as received.",
"透传请求体": "Pass through body",
"图标": "Icon",
"图标使用@lobehub/icons库,如:OpenAI、Claude.Color,支持链式参数:OpenAI.Avatar.type={'platform'}、OpenRouter.Avatar.shape={'square'},查询所有可用图标请 ": "The icon uses the @lobehub/icons library, such as: OpenAI, Claude.Color, supports chain parameters: OpenAI.Avatar.type={'platform'}, OpenRouter.Avatar.shape={'square'}, query all available icons please ",
@@ -9003,6 +9056,28 @@
"下载 WeyAi": "Download WeyAi",
"WeyAi 桌面端支持 Windows、macOS 和 Linux,请在电脑上打开此页面下载": "WeyAi Desktop supports Windows, macOS and Linux. Please open this page on a computer to download",
"未能识别你的系统,请在下方选择对应的安装包": "Could not detect your system. Please choose an installer below",
"把 AI 带到你的桌面": "Bring AI to your desktop",
"下载 {{os}} 版": "Download for {{os}}",
"{{count}} 个文件": "{{count}} files",
"当前选择": "Selected",
"选择操作系统": "Choose operating system",
"选择处理器架构": "Choose processor architecture",
"{{kind}} 安装包": "{{kind}} installer",
"一个账号,连接桌面与平台": "One account for desktop and platform",
"WeyAI 工作台": "WeyAI workspace",
"工具示意": "Tool preview",
"我的对话": "My chats",
"工具": "Tools",
"文档整理": "Organize documents",
"代码协作": "Code collaboration",
"平台账号": "Platform account",
"已连接": "Connected",
"让想法,在桌面展开": "Bring ideas to life on your desktop",
"对话、文件与工具,汇聚一处": "Chats, files, and tools in one place",
"今天想从哪里开始?": "What would you like to start with?",
"文件与知识": "Files and knowledge",
"随时整理,随时调用": "Organize and access anytime",
"连接日常任务": "Connect your daily tasks",
"下载 WeyAi 桌面端": "Download WeyAi Desktop",
"用你的账号登录,直接使用平台提供的模型和余额": "Sign in with your account and use the models and balance provided by the platform",
"最新版本 v{{version}}": "Latest version v{{version}}",
@@ -9956,7 +10031,7 @@
"3 困难": "3 Very hard",
"JSON 数组,按顺序第一条命中即生效。动作:model 直接指定模型;tier(可带 row)强制难度档;tier_min / tier_max 约束区间。": "A JSON array; the first matching rule wins. Actions: model picks a model directly; tier (optionally with row) forces a difficulty tier; tier_min / tier_max constrain the range.",
"JSON 输出": "JSON output",
"Jev 判定": "Jev judging",
"判定模型": "Decision model",
"OpenRouter 密钥": "OpenRouter key",
"OpenRouter 模型版本": "OpenRouter model version",
"OpenRouter 熔断中": "OpenRouter circuit open",
@@ -9992,8 +10067,8 @@
"保存密钥": "Save key",
"保留与限流": "Retention and limits",
"信息抽取、格式转换、分类": "Extraction, format conversion, classification",
"允许使用 Jev 判定(还需平台开启与出境同意)": "Allow Jev judging (also requires platform enablement and cross-border consent)",
"允许调用 Jev(数据出境,合规评估通过后开启)": "Allow calling Jev (data leaves the country; enable after compliance review)",
"允许使用判定模型": "Allow the decision model",
"允许调用境外判定模型(通过合规评估后开启)": "Allow calls to overseas decision models (enable after compliance review)",
"全部判定明细": "All routing decisions",
"共享会话存储就绪": "Shared session store ready",
"共享会话存储未就绪": "Shared session store not ready",
@@ -10007,7 +10082,7 @@
"判定来源": "Decision source",
"判定耗时": "Judging latency",
"加密存储,只有超级管理员可修改": "stored encrypted; root admins only",
"发给 Jev 的内容上限(字节)": "Max content sent to Jev (bytes)",
"发送给判定模型的内容上限(字节)": "Maximum content sent to the decision model (bytes)",
"可选:system 提示词": "Optional: system prompt",
"合规": "Compliance",
"合规闸门": "Compliance gate",
@@ -10027,9 +10102,9 @@
"工具调用 ID 格式不兼容": "Incompatible tool call ID format",
"已授权": "Authorized",
"已生效": "Applied",
"已调用 Jev": "Jev called",
"已调用模型": "Model called",
"平台暂未开放需要授权的智能路由功能": "The platform has not enabled any smart routing feature that needs consent",
"平台未开启 Jev 出境": "Jev egress disabled by platform",
"平台未开启境外模型判定": "Cross-border model decisions are disabled on the platform",
"平台集合": "Platform routers",
"平台集合对所有用户可用;修改候选会影响所有引用它的令牌,并写入审计日志。": "Platform routers are available to all users; changing candidates affects every token that uses them and is written to the audit log.",
"平衡 τ1,τ2,τ3": "Balanced τ1,τ2,τ3",
@@ -10041,7 +10116,7 @@
"我的集合": "My routers",
"把正式脱敏后的请求发送给基线模型和评审模型,用于对比质量。": "Send the redacted request to the baseline and judge models to compare quality.",
"把脱敏、截断后的请求与回答片段发送给境外判定服务,用于质量评估。": "Send redacted, truncated request and response snippets to an overseas judging service for quality scoring.",
"把脱敏、截断后的请求片段发送给境外判定服务(Jev),用于选择合适的模型。": "Send redacted, truncated request snippets to an overseas judging service (Jev) to choose a suitable model.",
"将脱敏、截断后的请求片段发送至境外判定服务,用于选择合适的模型。": "Redacted, truncated excerpts of requests are sent to an overseas decision service to select a suitable model.",
"把脱敏后的请求加密留存最多 90 天,用于离线评估。": "Keep redacted requests encrypted for up to 90 days for offline evaluation.",
"授权后会覆盖企业「数据安全」「不用于训练」功能的默认保护。": "Granting this overrides the default protection of the enterprise's Data Security and No Training features.",
"推理模型": "Reasoning model",
@@ -10055,14 +10130,14 @@
"新建集合": "New router",
"无法归入以上类别的请求": "Requests that fit none of the above",
"智能判定": "Smart judging",
"智能路由 · Jev 判定(可用)": "Smart Router · Jev judging (available)",
"智能路由 · 允许模型判定": "Smart routing · Allow model decisions",
"智能路由 · 质量评估(可用)": "Smart Router · quality evaluation (available)",
"有效期(秒)": "TTL (seconds)",
"未经过闸门": "Gate not applied",
"未设置密钥": "no key",
"未通过剥离兼容性验证的渠道类型(逗号分隔)": "Channel types that failed strip-compatibility validation (comma separated)",
"查看智能路由": "View smart routing",
"标注「合规」的配置项只有超级管理员可以修改。开启 Jev 出境前须完成合规评估。": "Settings marked Compliance can only be changed by root admins. Complete a compliance review before enabling Jev egress.",
"标注「合规」的配置项仅限超级管理员修改。启用境外判定模型前须完成合规评估。": "Only super administrators can change settings marked “Compliance”. Complete a compliance review before enabling an overseas decision model.",
"标签修改后,任务置信度阈值建议观察 7 天后再调整。必须包含 general。": "After changing labels, observe for 7 days before tuning the task confidence threshold. general is required.",
"模型角色与阈值": "Model roles and thresholds",
"每人最多个人集合数": "Max personal routers per user",
@@ -10104,15 +10179,15 @@
"调用失败": "Call failed",
"企业集合只对本企业令牌生效。候选模型同样受作用域模型白名单约束:使用作用域白名单时,需同时加入 router/ 虚拟名与它的候选模型,否则判定时候选会被过滤。": "Enterprise profiles apply only to this enterprise's tokens. Candidate models are also subject to the scoped model whitelist: when a scoped whitelist is used, add both the router/ virtual name and its candidate models, otherwise candidates are filtered out during routing.",
"平台已关闭本企业的智能路由。之前授予的数据出境同意仍然有效,功能重新开启后会自动生效;如不再需要,请在此撤回。": "Smart routing has been turned off for this enterprise by the platform. Previously granted data-transfer consent is still valid and takes effect again when the feature is turned back on. Revoke it here if you no longer need it.",
"余额不足,未调用 Jev": "Balance exhausted, Jev skipped",
"今日 Jev 判定次数已达上限": "Daily Jev judgement cap reached",
"Jev 判定每人每日上限(0 不限)": "Jev judgements per user per day (0 = unlimited)",
"Jev 判定每企业每日上限(0 不限)": "Jev judgements per enterprise per day (0 = unlimited)",
"余额不足,未调用模型": "Insufficient balance, model not called",
"今日模型判定次数已达上限": "Daily model decision limit reached",
"每人每日模型判定次数上限(0 表示不限)": "Daily model decision limit per user (0 = unlimited)",
"每个企业每日模型判定次数上限(0 表示不限)": "Daily model decision limit per organization (0 = unlimited)",
"每个企业最多集合数": "Max profiles per enterprise",
"以上计数为当前节点进程内累计值,进程重启后清零": "Counters are per node and reset when the process restarts",
"渠道查询失败": "Channel lookup failed",
"会话读取失败": "Session read failures",
"Jev 降级次数": "Jev fallbacks",
"模型判定失败后使用规则的次数": "Rule fallbacks after a model decision failed",
"存储未就绪拒绝": "Rejected (store not ready)",
"试路由": "Test routing",
"试路由失败,请稍后重试": "Test routing failed, please try again later",
@@ -10133,11 +10208,11 @@
"配置未修改": "No changes",
"闲聊、简单查询": "Small talk, simple lookups",
"难度概率": "Difficulty probabilities",
"集合未允许使用 Jev": "Router does not allow Jev",
"此集合未开启模型判定": "Model decisions are disabled for this collection",
"预估 token": "Estimated tokens",
"高级:难度档阈值 τ1,τ2,τ3(留空使用策略默认值)": "Advanced: difficulty thresholds τ1,τ2,τ3 (empty = strategy default)",
"默认模型(判定失败时使用)": "Default model (used when judging fails)",
"Jev 失败,规则判定": "Jev failed, rules judge used",
"模型判定失败,已使用规则": "Model decision failed, rules used",
"Smart Router": "Smart Router",
"general 行的 4 个单元格必须全部填写": "All 4 cells of the general row must be filled",
"任务标签不能重名": "Task labels must be unique",
@@ -10154,7 +10229,7 @@
"最便宜的候选": "Cheapest candidate",
"未启用,使用默认模型": "Not enabled, default model used",
"没有权限执行该操作": "You do not have permission to do this",
"清除后该通道无法调用 Jev,判定会降级为规则判定。": "After clearing, this channel cannot call Jev and judging falls back to the rules judge.",
"清除后,此通道将无法调用判定模型。所有通道均不可用时,将使用规则判定。": "Clearing this key disables calls to the decision model through this channel. Rules are used if all channels are unavailable.",
"短名只允许小写字母、数字和连字符,最长 48 个字符": "Short names may only contain lowercase letters, digits and hyphens (max 48 characters)",
"确认清除密钥?": "Clear this key?",
"自定义规则强制档位": "Tier forced by custom rule",
@@ -11416,6 +11491,344 @@
"共 {{count}} 个文件_other": "{{count}} files in total",
"{{count}} 个安装包_other": "{{count}} installation packages",
"consoleUi.descriptions.commission": "Manage partners, customer attribution, commission tiers and statements",
"consoleUi.descriptions.smart-router": "Configure candidate models and routing strategies for virtual models"
"consoleUi.descriptions.smart-router": "Configure candidate models and routing strategies for virtual models",
"超管代理模式:正在代理操作企业「{{name}}」,所有操作都会记录审计": "Admin proxy mode: you are operating organization \"{{name}}\" on its behalf. All actions are audited.",
"退出代理": "Exit proxy",
"权限已变更": "Permissions changed",
"你的权限已变更,请重新登录。": "Your permissions have changed. Please sign in again.",
"重新登录": "Sign in again",
"不可授予": "Not grantable",
"丢弃": "Dropped",
"为平台管理员配置角色、授权菜单与按钮,并分配给用户": "Configure roles for platform admins, grant menus and buttons, and assign them to users",
"为该用户分配平台角色,保存后整体替换原有角色。": "Assign platform roles to this user. Saving replaces all existing roles.",
"主体 ID": "Subject ID",
"主体数": "Subjects",
"企业侧": "Organization side",
"企业新建角色时可直接套用的预设权限与数据范围": "Preset permissions and data scope that organizations can apply when creating roles",
"全部(*)": "All (*)",
"全部域": "All domains",
"全部数据": "All data",
"分配用户": "Assign users",
"分配角色": "Assign roles",
"切换后对应模块将以新权限体系判定访问,旧判断不再生效,已登录用户的权限变化会要求重新登录。": "After switching, access to these modules is decided by the new permission system and the old checks no longer apply. Signed-in users whose permissions change will be asked to sign in again.",
"删除后不可恢复,确定删除该角色吗?": "This cannot be undone. Delete this role?",
"功能套餐": "Feature packages",
"功能套餐决定企业可授予给成员的权限范围。": "The feature package determines which permissions the organization can grant to its members.",
"功能套餐已更新": "Feature package updated",
"包含权限": "Included permissions",
"域": "Domain",
"墓碑": "Tombstone",
"套餐决定企业可授予给成员的权限范围;未单独绑定的企业跟随默认套餐": "A package determines which permissions an organization can grant to members; organizations without their own package follow the default package",
"套餐名称": "Package name",
"差异": "Differences",
"已从代码目录移除,保留记录以兼容历史授权": "Removed from the code catalog; the record is kept for compatibility with existing grants",
"已切换企业 ID": "Switched organization IDs",
"已切换模块": "Switched modules",
"已对比": "Compared",
"已设为默认套餐": "Set as default package",
"已选 {{count}} 项;勾选按钮会自动勾上所属菜单。": "{{count}} selected; checking a button also checks its menu.",
"平台侧": "Platform side",
"平台角色": "Platform roles",
"当前仍有 {{count}} 条扩权差异,请确认每条都已有解释。": "There are still {{count}} privilege-expanding differences. Make sure each one has an explanation.",
"影子对比": "Shadow comparison",
"影子对比计数(本节点自启动以来)": "Shadow comparison counters (this node, since startup)",
"影子差异": "Shadow differences",
"所有者专属": "Owner only",
"扩权": "Expands access",
"扩权项(旧拒新放)必须逐条有解释才能切换到新体系;缩权项(旧放新拒)请确认是否为预期收紧。": "Every access-expanding item (denied before, allowed now) must have an explanation before switching to the new system; for access-narrowing items (allowed before, denied now), confirm the restriction is intended.",
"授权已保存": "Permissions saved",
"控制各模块是否切换到新权限体系,以及影子对比的开关": "Control which modules use the new permission system and toggle shadow comparison",
"搜索名称、编码或路由": "Search name, code or route",
"搜索角色名称或编码": "Search role name or code",
"放行": "Allow",
"数据范围": "Data scope",
"新建套餐": "New package",
"新建模板": "New template",
"新建角色": "New role",
"旧 / 新": "Old / New",
"时间段": "Time slot",
"显示": "Visible",
"暂无主体明细": "No subject details",
"暂无套餐": "No packages",
"暂无差异": "No differences",
"暂无已分配用户": "No users assigned",
"暂无模板": "No templates",
"暂无角色": "No roles",
"最近 {{count}} 小时": "Last {{count}} hours",
"最近出现": "Last seen",
"未切换任何模块": "No modules switched",
"未单独绑定套餐的企业都将跟随默认套餐,确定把「{{name}}」设为默认吗?": "All organizations without their own package will follow the default package. Set \"{{name}}\" as the default?",
"未就绪": "not ready",
"本部门": "Own department",
"本部门及以下": "Own department and below",
"本部门及以下或本人": "Own department and below, or self",
"权限数": "Permissions",
"权限点": "Permission",
"权限管理": "Permissions",
"权限运行模式": "Permission run mode",
"查看用户": "View users",
"模板名称": "Template name",
"次数": "Count",
"点击一行查看涉及的主体明细。": "Click a row to see the subjects involved.",
"目录": "Directory",
"确定删除模板「{{name}}」吗?已用该模板创建的企业角色不受影响。": "Delete template \"{{name}}\"? Organization roles already created from it are not affected.",
"确认切换权限运行模式": "Confirm permission run mode change",
"绑定企业": "Organizations",
"绑定用户": "Users",
"维护平台与企业两侧菜单、按钮权限点的名称、排序与显隐": "Maintain names, order and visibility of menu and button permissions on both platform and organization sides",
"编辑套餐": "Edit package",
"编辑模板": "Edit template",
"编辑节点": "Edit node",
"编辑角色": "Edit role",
"缩权": "Narrows access",
"菜单": "Menu",
"菜单授权": "Grant menus",
"菜单管理": "Menu management",
"角色名称": "Role name",
"角色模板": "Role templates",
"角色编码": "Role code",
"设为默认": "Set as default",
"设为默认套餐": "Set as default package",
"该角色仍绑定 {{count}} 个用户,删除后这些用户将失去该角色的权限。": "This role is still bound to {{count}} users. After deletion they will lose its permissions.",
"请输入套餐名称": "Enter a package name",
"请输入模板名称": "Enter a template name",
"请输入角色名称": "Enter a role name",
"跟随默认套餐": "Follow default package",
"路由": "Route",
"输入关键字搜索用户": "Type a keyword to search users",
"输入用户名搜索并添加": "Search by username to add",
"迁移": "Migrated",
"运行模式已保存": "Run mode saved",
"选择平台角色": "Select platform roles",
"逗号分隔的企业 ID,* 表示全部": "Comma-separated organization IDs; * means all",
"锁定": "Locked",
"锁定节点及其上级不可停用": "Locked nodes and their ancestors cannot be disabled",
"从模板创建": "Create from template",
"分配员工": "Assign employees",
"删除后已分配该角色的员工将失去对应权限,此操作不可撤销。": "After deletion, employees assigned this role will lose its permissions. This action cannot be undone.",
"可选:选择模板预填权限与数据范围": "Optional: choose a template to prefill permissions and data scope",
"员工分配已保存": "Employee assignment saved",
"将带入 {{n}} 项权限,创建后可在「授权」中调整": "{{n}} permissions will be applied; you can adjust them under \"Grant\" after creation",
"已设为默认员工角色": "Set as default employee role",
"已选 {{n}} 项": "{{n}} selected",
"按角色配置员工可访问的菜单、按钮与数据范围": "Configure by role the menus, buttons and data scope employees can access",
"授权": "Grant",
"新成员加入企业时自动分配该角色": "New members are automatically assigned this role when they join",
"无匹配员工": "No matching employees",
"暂无员工": "No employees",
"未选择员工": "No employees selected",
"未选择部门": "No departments selected",
"标记为「迁移」的角色由旧角色迁移,切换到新权限体系前修改会被拒绝": "Roles marked \"Migrated\" were migrated from legacy roles; changes are rejected until the organization switches to the new permission system",
"由旧角色迁移,切换到新权限体系前修改会被拒绝": "Migrated from a legacy role; changes are rejected until the organization switches to the new permission system",
"确定删除该角色?": "Delete this role?",
"自定义部门": "Custom departments",
"自定义部门范围至少选择一个部门": "Select at least one department for the custom department scope",
"菜单与按钮权限": "Menu and button permissions",
"菜单与数据授权": "Menu and data permissions",
"角色已停用": "Role disabled",
"角色已创建": "Role created",
"角色已删除": "Role deleted",
"角色已启用": "Role enabled",
"角色管理": "Role management",
"设置该成员拥有的企业角色": "Set the organization roles this member has",
"选中的员工将拥有该角色,保存后整体替换原有分配;企业所有者无需分配角色。": "Selected employees will have this role. Saving replaces the existing assignment; the organization owner does not need roles.",
"选择可访问数据的部门": "Select departments whose data can be accessed",
"选择角色": "Select roles",
"选择该成员拥有的企业角色,保存后整体替换原有角色。": "Select the organization roles for this member. Saving replaces all existing roles.",
"({{m}} 项超出本企业套餐,已忽略)": "({{m}} outside this organization's plan, ignored)",
"我管辖的部门": "My Managed Departments",
"扩大": "Expanded",
"冲突": "Conflict",
"缩小": "Narrowed",
"切换前对账未通过": "Pre-switch reconciliation failed",
"已逐条确认扩大项,继续切换": "I have reviewed every expanded item, continue switching",
"报告中的扩大项会让部分人获得原来没有的访问权限,请逐条核对确认后再继续切换。": "Expanded items in the report grant some people access they did not have before. Review each one before continuing.",
"无报告内容": "No report content",
"请从企业登录入口登录": "Please sign in from the enterprise login",
"该企业已启用新权限体系,个人账号登录后不能直接进入企业中心,请使用企业账号从企业登录入口登录。": "This enterprise has switched to the new permission system. A personal sign-in cannot open the enterprise center directly; sign in with your enterprise account from the enterprise login.",
"企业登录状态不匹配": "Enterprise session mismatch",
"当前登录的是另一家企业,不能访问该企业。请重新从企业登录入口登录目标企业,或返回当前登录的企业。": "You are signed in to a different enterprise and cannot access this one. Sign in to the target enterprise from the enterprise login, or go back to the enterprise you are signed in to.",
"请从企业管理重新进入": "Please re-enter from Enterprise Management",
"超管代理只在发起代理的标签页内有效,新打开的标签页没有代理会话。请到企业管理列表中点击该企业名称重新进入。": "A super admin proxy session only works in the tab where it was started; this new tab has none. Go to the Enterprise Management list and click the enterprise name to enter again.",
"前往企业登录": "Go to enterprise login",
"返回当前登录的企业": "Back to my signed-in enterprise",
"前往企业管理": "Go to Enterprise Management",
"另有 {{n}} 名成员不在你的数据范围内,保持不变": "{{n}} more members are outside your data scope and will remain unchanged",
"迁移套餐的权限在其企业切换前由对账维护": "Permissions of a migrated package are maintained by reconciliation until its organizations are cut over",
"你没有查询用户的权限,只能查看与移除已分配用户": "You do not have permission to query users; you can only view and remove assigned users",
"代理会话已失效": "Proxy session expired",
"代理会话已失效,请从企业管理重新进入": "The proxy session has expired. Please re-enter from Organization Management",
"代理会话校验失败": "Proxy session verification failed",
"代理会话校验失败,请稍后刷新重试,或从企业管理重新进入": "Proxy session verification failed. Please refresh and try again later, or re-enter from Organization Management",
"对账报告已变化,请重新核对后再确认": "The reconciliation report has changed. Please review it again before confirming",
"代理": "Proxy",
"搜索权限": "Search permissions",
"该企业已启用新权限体系,请先从企业登录入口登录该企业后再授权": "This organization uses the new permission system. Sign in to it from the organization login page before authorizing.",
"已分配用户加载失败,请关闭后重试": "Failed to load assigned users. Please close and try again.",
"迁移套餐在其企业切换前由对账维护,修改权限可能被拒绝": "Migrated packages are maintained by reconciliation until their organizations switch over; permission changes may be rejected.",
"权限信息加载失败": "Failed to load permission information",
"成员列表加载不完整,请刷新后重试": "The member list was not fully loaded. Please refresh and try again.",
"你没有部门查询权限,无法修改自定义部门": "You do not have permission to query departments, so custom departments cannot be changed.",
"登录状态已变化": "Sign-in status changed",
"你已在其他页面切换了账号,请刷新页面": "You switched accounts in another tab. Please refresh the page.",
"你在该企业的登录已被管理员关闭,请联系企业管理员": "Your sign-in to this organization has been disabled by an administrator. Please contact your organization administrator.",
"当前是企业登录,个人范围请从个人登录入口登录后再授权": "You are signed in through the organization portal. To authorize the personal scope, sign in through the personal sign-in page first.",
"去企业登录": "Sign in to organization",
"去个人登录": "Personal sign-in",
"请输入初始密码": "Enter your initial password",
"consoleUi.descriptions.authz-menus": "Browse the menu and permission catalog and adjust names, order and visibility",
"consoleUi.descriptions.authz-roles": "Manage platform roles, menu grants and user assignments",
"consoleUi.descriptions.authz-packages": "Manage the feature packages available to organizations and the menus they include",
"consoleUi.descriptions.authz-templates": "Manage the role templates distributed to organizations",
"consoleUi.descriptions.authz-mode": "Switch modules between the legacy and new permission systems and review their status",
"{{field}}最多允许{{max}}个字符。": "{{field}} allows at most {{max}} characters.",
"{{field}}格式不正确。": "{{field}} has an invalid format.",
"请输入{{field}}。": "Please enter {{field}}.",
"修改尚未保存,确定离开吗?": "Your changes have not been saved. Leave anyway?",
"离开": "Leave",
"继续编辑": "Keep editing",
"员工": "Employee",
"新建员工": "New employee",
"编辑员工": "Edit employee",
"员工资料、账号、额度与角色统一在一个表格管理": "Manage employee profiles, accounts, quotas and roles in a single table",
"关键字": "Keyword",
"姓名 / 登录名 / 工号 / 备注": "Name / login name / employee no. / remark",
"全部组织": "All departments",
"企业角色": "Enterprise roles",
"未分配角色": "No role assigned",
"所有者不能直接停用,须先完成移交": "The owner cannot be disabled directly; transfer ownership first",
"停用员工“{{name}}”": "Disable employee \"{{name}}\"",
"停用后该企业身份将无法登录,已有会话立即失效,历史记录保留。是否继续?": "After disabling, this enterprise identity can no longer sign in, existing sessions end immediately, and history is kept. Continue?",
"确定删除员工“{{name}}”吗?": "Delete employee \"{{name}}\"?",
"删除后将移除该员工在当前企业的访问资格,已有会话立即失效;历史业务记录与审计标识保留,不会删除其个人账号。该操作不可恢复。": "Deleting removes this employee's access to the current enterprise and ends existing sessions immediately. Business history and audit identifiers are kept, and the personal account is not deleted. This cannot be undone.",
"员工已删除": "Employee deleted",
"员工账号已创建。": "Employee account created.",
"员工资料已更新": "Employee profile updated",
"创建后不可修改。": "Cannot be changed after creation.",
"用于企业登录,创建后不可修改。": "Used for enterprise sign-in; cannot be changed after creation.",
"个人账号,由本人在个人中心维护": "Personal account; maintained by the user in the personal center",
"填写时企业内唯一": "Must be unique within the enterprise when provided",
"可选任意启用的部门,不选即未分配": "Any enabled department can be selected; leave empty for unassigned",
"无分配部门权限,主部门不可调整": "You lack the assign-department permission; the primary department cannot be changed",
"部门调整将改变相对数据范围,自定义范围保持不变,请核查角色授权。": "Changing the department changes relative data scopes; custom scopes stay unchanged. Please review role authorizations.",
"该成员当前归属的部门已停用,建议调整到启用中的部门。": "This member's current department is disabled; consider moving them to an enabled department.",
"选择 CSV 文件": "Choose CSV file",
"暂无部门": "No departments",
"父子联动": "Link parent and children",
"已选 {{n}} 个部门": "{{n}} departments selected",
"数据范围按勾选的部门精确生效:开启联动时,勾选上级会同时勾选当前已有的全部下级;之后新增的下级部门不会自动加入。": "The data scope applies to exactly the departments checked. With linking on, checking a parent also checks all of its current sub-departments; sub-departments added later are not included automatically.",
"数据范围按勾选的部门精确生效:已关闭联动,只勾选节点本身,不包含其下级部门。": "The data scope applies to exactly the departments checked. Linking is off: only the node itself is checked, not its sub-departments.",
"另有 {{n}} 个已保存的部门不在当前部门列表中,保存时保持不变": "{{n}} saved departments are not in the current department list and will be kept unchanged on save",
"可授予的菜单加载失败,请刷新后重试": "Failed to load the grantable menus. Refresh and try again",
"角色已创建,请核对权限和数据范围。": "Role created. Please review its permissions and data scope.",
"授权成功,相关账号需重新登录。": "Authorization saved. The affected accounts need to sign in again.",
"角色已保存": "Role saved",
"确定停用角色“{{name}}”吗?": "Disable the role \"{{name}}\"?",
"停用后该角色的授权不再生效,可随时重新启用。": "Once disabled, the role's permissions no longer take effect. You can enable it again at any time.",
"确定删除角色“{{name}}”吗?": "Delete the role \"{{name}}\"?",
"删除后不可恢复。": "This cannot be undone.",
"新建员工将自动分配该角色,已有员工角色保持不变。": "New employees will be assigned this role automatically. Existing employees' roles stay unchanged.",
"新建员工时自动分配该角色": "Assigned automatically to newly created employees",
"请先更换默认员工角色。": "Change the default employee role first.",
"角色“{{name}}”状态": "Status of role \"{{name}}\"",
"菜单与数据授权 - {{name}}": "Menu and data authorization - {{name}}",
"编辑角色 - {{name}}": "Edit role - {{name}}",
"角色列表": "Roles",
"已带入 {{n}} 项权限,可在下方继续调整。": "{{n}} permissions were filled in from the template. You can adjust them below.",
"另有 {{m}} 项超出本企业套餐,已忽略。": "{{m}} more are outside this organization's plan and were ignored.",
"可选:选择模板预填权限与数据范围,也可以直接在下方配置": "Optional: pick a template to prefill permissions and data scope, or configure them directly below",
"不使用模板": "No template",
"请输入角色名称。": "Please enter the role name.",
"角色名称最多允许 {{n}} 个字符。": "The role name can be at most {{n}} characters.",
"角色标识": "Role key",
"小写字母开头,只能包含小写字母、数字、下划线,不能以 legacy_ 开头;留空自动生成": "Starts with a lowercase letter; lowercase letters, digits and underscores only; must not start with legacy_. Leave empty to generate automatically",
"角色标识格式不正确。": "The role key format is invalid.",
"排序不能为负数": "The sort order cannot be negative",
"默认员工角色不能直接停用,请先更换默认角色。": "The default employee role cannot be disabled directly. Change the default role first.",
"仍分配给员工的角色不能停用。": "A role that is still assigned to employees cannot be disabled.",
"你没有菜单与数据授权权限,将创建不含权限的空角色,数据范围为仅本人。": "You do not have the menu and data authorization permission. An empty role without permissions will be created, with the data scope set to self only.",
"请选择数据范围。": "Please select a data scope.",
"自定义数据范围至少选择一个部门": "Select at least one department for the custom data scope",
"只能授予本企业套餐内的菜单与按钮": "Only menus and buttons included in this organization's plan can be granted",
"分配员工 - {{name}}": "Assign employees - {{name}}",
"可选员工": "Available employees",
"已分配": "Assigned",
"搜索员工": "Search employees",
"暂无可用功能,请联系管理员。": "No features are available. Please contact your administrator.",
"{{menus}} 个菜单 · {{buttons}} 个按钮": "{{menus}} menus · {{buttons}} buttons",
"{{name}} · {{count}} 项按钮": "{{name}} · {{count}} buttons",
"停用角色": "Disable role",
"共 {{count}} 项": "{{count}} in total",
"内置角色不能停用": "Built-in roles cannot be disabled",
"套餐列表": "Packages",
"套餐至少包含一个可访问的菜单": "A package must include at least one accessible menu",
"已逐条确认,继续切换": "I have reviewed every item, continue switching",
"平台角色已保存。": "Platform role saved.",
"授权树加载失败,无法查看或修改授权": "Failed to load the permission tree; permissions cannot be viewed or changed",
"排序须为非负整数": "Sort order must be a non-negative integer",
"显示与启用在列表中直接切换;类型、编码、路由与上级由代码定义,不可修改。": "Toggle visibility and status directly in the list. Type, code, route and parent are defined in code and cannot be changed.",
"有 {{count}} 名成员的企业登录名回填不了或账号没有密码,切换后无法用密码从企业入口登录,请逐人处理或确认。": "{{count}} members have no enterprise login name that can be backfilled or have no password. After switching they cannot sign in with a password from the enterprise entry. Handle or confirm them one by one.",
"未授权": "No permissions",
"本次变更将影响{{count}}个企业,请确认。": "This change will affect {{count}} enterprises. Please confirm.",
"权限字符": "Role key",
"权限字符须以小写字母开头,只能包含小写字母、数字、下划线,且不能以 legacy_ 开头": "The role key must start with a lowercase letter, contain only lowercase letters, digits and underscores, and must not start with legacy_",
"权限摘要": "Permission summary",
"查看套餐": "View package",
"查看模板": "View template",
"模板列表": "Templates",
"没有匹配的权限": "No matching permissions",
"确认保存套餐": "Confirm package change",
"菜单列表": "Menus",
"菜单配置已保存。": "Menu settings saved.",
"角色分配成功。": "Role assigned successfully.",
"角色详情": "Role details",
"该角色仍分配给 {{count}} 个用户,需先移除后才能删除。": "This role is still assigned to {{count}} users. Remove them before deleting it.",
"迁移角色的权限字符由系统维护,不能修改": "The key of a migrated role is maintained by the system and cannot be changed",
"默认套餐不能停用,请先设置其他默认套餐": "The default package cannot be disabled. Set another default package first",
"账号类型": "Account type",
"创建后为启用状态;平台角色请在列表操作列通过「分配角色」设置": "The account is enabled once created. Assign platform roles from \"Assign roles\" in the list actions.",
"调整额度不能为 0": "The adjustment cannot be 0",
"调整后的剩余额度不能小于 0": "The remaining quota after adjustment cannot be less than 0",
"当前剩余额度 {{current}} + 调整额度 {{delta}} = 新剩余额度 {{next}}": "Current remaining {{current}} + adjustment {{delta}} = new remaining {{next}}",
"只读;调整请使用列表操作列的「添加额度」": "Read-only. Use \"Add quota\" in the list actions to adjust it.",
"企业所有者已更换": "Organization owner changed",
"更换后立即生效,是否继续?": "The change takes effect immediately. Continue?",
"确认更换": "Confirm change",
"更换企业所有者": "Change organization owner",
"仅用于原所有者停用、离开或数据异常时的兜底更换;接任人必须是该企业状态正常的成员。": "Use only as a fallback when the current owner is disabled, has left, or the data is inconsistent. The successor must be an active member of this organization.",
"更换原因": "Reason for change",
"请填写更换原因": "Enter the reason for the change",
"更换原因不能超过 {{max}} 个字": "The reason cannot exceed {{max}} characters",
"最大成员数和最大Token数必须为非负整数": "Max members and max tokens must be non-negative integers",
"企业所有者": "Organization owner",
"企业预警通知": "Alert notifications",
"更换所有者": "Change owner",
"调整套餐": "Change package",
"功能套餐只控制功能菜单及按钮,分组、额度、限额独立生效": "The feature package only controls menus and buttons; groups, quota and limits take effect independently.",
"须为非负整数;填 0 使用系统默认值": "Must be non-negative integers; enter 0 to use the system default.",
"须为非负整数;填 0 表示本次不修改": "Must be non-negative integers; enter 0 to leave the value unchanged.",
"搜索企业名称、代码、联系人": "Search by organization name, code or contact",
"该企业已切换到新权限体系:菜单类功能由功能套餐决定,这里只调整行为类开关。": "This organization has switched to the new permission system: menu features are determined by its feature package, so only behavior switches can be adjusted here.",
"企业「{{name}}」的所有者将更换为「{{member}}」,原所有者按移交规则降级。": "The owner of \"{{name}}\" will be changed to \"{{member}}\"; the previous owner is downgraded according to the transfer rules.",
"当前所有者": "Current owner",
"接任成员": "Successor",
"可按显示名称或登录名搜索,最多列出 100 名正常成员": "Search by display name or login name; up to 100 active members are listed.",
"请选择接任成员": "Select a successor",
"暂无可选成员": "No members available",
"令牌管理": "Token Management",
"管理令牌": "Manage tokens",
"个令牌": "tokens",
"请填写员工姓名": "Please enter the employee name",
"工号在企业内已存在": "This employee number already exists in the enterprise",
"表头需含 login_name,display_name,email,employee_no(login_name 与 display_name 必填;工号填写时须在企业内唯一)。单次最多 500 行。每个账号返回一次性初始密码。": "The header must include login_name,display_name,email,employee_no (login_name and display_name are required; employee numbers, if provided, must be unique within the enterprise). Up to 500 rows per import. A one-time initial password is returned for each account.",
"首次登录请先修改初始密码,再进行授权": "Please change your initial password before authorizing",
"查看密钥过于频繁,请稍后再试": "Too many key views. Please try again later.",
"未命名部门": "Unnamed department",
"未知主体": "Unknown subject",
"未知技能": "Unknown skill",
"以下模型在新分组下不可用,已自动移除:{{models}}": "These models are unavailable in the new group and were removed: {{models}}",
"分组加载失败,请刷新后重试": "Failed to load groups. Please refresh and try again.",
"员工姓名不能超过 {{max}} 个字符": "Employee name cannot exceed {{max}} characters",
"邮箱不能超过 {{max}} 个字符": "Email cannot exceed {{max}} characters"
}
}
+431 -18
View File
@@ -1,5 +1,53 @@
{
"translation": {
"允许模型判定": "Décisions par modèle autorisées",
"请在「智能路由 → 全局设置」中保存判定模型的密钥或代理": "Enregistrez la clé ou le proxy du modèle de décision dans Routage intelligent → Paramètres globaux",
"判定模型接口地址须为以 http:// 或 https:// 开头的完整地址": "Saisissez une URL complète commençant par http:// ou https:// pour le modèle de décision",
"需平台开启模型判定,并取得相应的数据出境授权。": "La plateforme doit activer les décisions par modèle et le transfert de données à l’étranger doit avoir été autorisé.",
"判定模型专用代理": "Proxy dédié au modèle de décision",
"仅用于调用判定模型。": "Utilisé uniquement pour les appels au modèle de décision.",
"跟随服务器网络设置": "Utiliser les paramètres réseau du serveur",
"测试代理": "Tester le proxy",
"保存代理": "Enregistrer le proxy",
"确认清除判定模型代理?": "Effacer le proxy du modèle de décision ?",
"清除代理": "Supprimer le proxy",
"Google 已连通": "Google est accessible",
"Google 未连通": "Google est inaccessible",
"出口 IP {{ip}} · {{region}}": "IP de sortie {{ip}} · {{region}}",
"地区未知": "Région inconnue",
"出口 IP 未获取": "IP de sortie indisponible",
"连接超时": "Délai de connexion dépassé",
"TLS 证书校验失败": "Échec de la vérification du certificat TLS",
"代理认证失败": "Échec de l’authentification du proxy",
"代理连接失败": "Échec de la connexion au proxy",
"代理地址无效,请使用 HTTP、HTTPS、SOCKS5 或 SOCKS5H 地址": "Saisissez une URL de proxy HTTP, HTTPS, SOCKS5 ou SOCKS5H valide",
"无法读取已保存的判定模型代理,请重新配置": "Impossible de lire le proxy enregistré pour le modèle de décision. Configurez-le à nouveau.",
"尚未设置判定模型代理": "Aucun proxy configuré pour le modèle de décision",
"判定模型代理配置加密失败": "Échec du chiffrement de la configuration du proxy du modèle de décision",
"Claude 联网搜索": "Recherche web Claude",
"超管指标": "Indicateurs super-admin",
"仅超级管理员可见": "Super-administrateurs uniquement",
"官方价金额(1 倍率)": "Montant officiel (1x)",
"整体倍率": "Ratio global",
"实际折扣": "Remise réelle",
"整体倍率 = 实扣 ÷ 官方价金额;实际折扣 = 整体倍率 ÷ 登记汇率({{rate}})": "Ratio global = débité ÷ montant officiel ; remise réelle = ratio global ÷ taux de change ({{rate}})",
"原厂价登记汇率": "Taux de change des prix officiels",
"下方原厂价格表中的数值 = 官方实际价格 × 该汇率。仅用于超级管理员在使用日志详情里看到的「整体倍率」(实扣 ÷ 官方实际价格),不参与计费与成本核算。": "Les valeurs du tableau des prix officiels ci-dessous = prix officiel réel × ce taux. Il sert uniquement au « ratio global » (débité ÷ prix officiel réel) affiché aux super-administrateurs dans le détail des journaux d'utilisation, sans effet sur la facturation ni sur le calcul des coûts.",
"请输入大于 0 且不超过 1000 的数字": "Saisissez un nombre supérieur à 0 et au plus égal à 1000",
"{{price}} / 秒": "{{price}} / seconde",
"总金额 = 各计费项小计之和,小计 = 用量 × 单价": "Total = somme des sous-totaux ; sous-total = usage × prix unitaire",
"费用明细": "Détail des coûts",
"计费项": "Poste",
"用量": "Usage",
"小计": "Sous-total",
"总金额": "Total",
"计算公式": "Formule",
"输入(未命中缓存)": "Entrée (hors cache)",
"图片倍率": "Ratio image",
"舍入与其他调整": "Arrondi et autres ajustements",
"{{price}} / 1M tokens": "{{price}} / 1M tokens",
"{{price}} / 次": "{{price}} / appel",
"各项小计为四舍五入后的近似值,合计以实际扣费为准": "Les sous-totaux sont arrondis ; le total correspond au montant réellement débité",
"并发占用": "Utilisation de la concurrence",
"限流中": "Limitation active",
"单实例口径": "Portée mono-instance",
@@ -1512,6 +1560,9 @@
"兑换": "échange",
"兑换成功!": "Échange réussi !",
"兑换额度": "Utiliser",
"兑换码": "Code d’échange",
"兑换码列表": "Codes d’échange",
"编辑兑换码信息": "Modifier les informations du code d’échange",
"兑换码充值": "Recharge par code d'échange",
"兑换码创建成功": "Code d'échange créé",
"兑换码创建成功,是否下载兑换码?": "Code d'échange créé avec succès. Voulez-vous le télécharger ?",
@@ -5674,6 +5725,8 @@
"投递健康": "Livraison santé",
"投递通道": "Canal de distribution",
"投递正常": "La livraison est OK",
"透传时应用模型映射": "Appliquer la correspondance des modèles lors de la transmission directe",
"请求体透传时,使用本渠道模型重定向后的模型名发送给上游,其余字段按原请求转发。": "Lors de la transmission directe du corps de la requête, envoyer au service amont le nom du modèle défini par la correspondance de ce canal. Transmettre les autres champs tels quels.",
"透传请求体": "Corps de transmission",
"图标": "Icône",
"图标使用@lobehub/icons库,如:OpenAI、Claude.Color,支持链式参数:OpenAI.Avatar.type={'platform'}、OpenRouter.Avatar.shape={'square'},查询所有可用图标请 ": "L'icône utilise la bibliothèque @lobehub/icons, telle que : OpenAI, Claude.Color, prend en charge les paramètres de chaîne : OpenAI.Avatar.type={'platform'}, OpenRouter.Avatar.shape={'square'}, interroger toutes les icônes disponibles s'il vous plaît ",
@@ -8560,6 +8613,28 @@
"下载 WeyAi": "Télécharger WeyAi",
"WeyAi 桌面端支持 Windows、macOS 和 Linux,请在电脑上打开此页面下载": "WeyAi Desktop prend en charge Windows, macOS et Linux. Ouvrez cette page sur un ordinateur pour télécharger",
"未能识别你的系统,请在下方选择对应的安装包": "Impossible de détecter votre système. Choisissez un installateur ci-dessous",
"把 AI 带到你的桌面": "L’IA sur votre bureau",
"下载 {{os}} 版": "Télécharger pour {{os}}",
"{{count}} 个文件": "{{count}} fichiers",
"当前选择": "Sélectionné",
"选择操作系统": "Choisir le système d'exploitation",
"选择处理器架构": "Choisir l'architecture du processeur",
"{{kind}} 安装包": "Programme d'installation {{kind}}",
"一个账号,连接桌面与平台": "Un compte pour l’application et la plateforme",
"WeyAI 工作台": "Espace de travail WeyAI",
"工具示意": "Aperçu des outils",
"我的对话": "Mes discussions",
"工具": "Outils",
"文档整理": "Organisation de documents",
"代码协作": "Collaboration sur le code",
"平台账号": "Compte de plateforme",
"已连接": "Connecté",
"让想法,在桌面展开": "Donnez vie à vos idées sur votre bureau",
"对话、文件与工具,汇聚一处": "Discussions, fichiers et outils au même endroit",
"今天想从哪里开始?": "Par quoi voulez-vous commencer ?",
"文件与知识": "Fichiers et connaissances",
"随时整理,随时调用": "Organisez et consultez à tout moment",
"连接日常任务": "Reliez vos tâches quotidiennes",
"下载 WeyAi 桌面端": "Télécharger WeyAi Desktop",
"用你的账号登录,直接使用平台提供的模型和余额": "Connectez-vous avec votre compte et utilisez les modèles et le solde fournis par la plateforme",
"最新版本 v{{version}}": "Dernière version v{{version}}",
@@ -9928,7 +10003,7 @@
"3 困难": "3 Difficultés",
"JSON 数组,按顺序第一条命中即生效。动作:model 直接指定模型;tier(可带 row)强制难度档;tier_min / tier_max 约束区间。": "Tableau JSON, qui prend effet lorsque la première frappe dans l'ordre. action: model spécifie directement le modèle;tier (peut être avec row) force le fichier de difficulté;tier_min / tier_max contraint l'intervalle.",
"JSON 输出": "Sortie de JSON",
"Jev 判定": "Jugement par Jev",
"判定模型": "Modèle de décision",
"OpenRouter 密钥": "La clé OpenRouter",
"OpenRouter 模型版本": "Version du modèle OpenRouter",
"OpenRouter 熔断中": "OpenRouter en fusion",
@@ -9964,8 +10039,8 @@
"保存密钥": "Sauver la clé",
"保留与限流": "Préservation et limitation du flux",
"信息抽取、格式转换、分类": "Extraction d'informations, conversion de format, classification",
"允许使用 Jev 判定(还需平台开启与出境同意)": "Autoriser l'utilisation du jugement Jev (nécessite également l'ouverture de la plateforme et le consentement de sortie)",
"允许调用 Jev(数据出境,合规评估通过后开启)": "Autoriser l'appel à Jev (sortie des données, ouverture après évaluation de la conformité)",
"允许使用判定模型": "Autoriser le modèle de décision",
"允许调用境外判定模型(通过合规评估后开启)": "Autoriser les appels à un modèle de décision à l’étranger (après évaluation de conformité)",
"全部判定明细": "Détails de toutes les décisions",
"共享会话存储就绪": "Session partagée Storage Ready",
"共享会话存储未就绪": "Stockage de session partagé non prêt",
@@ -9979,7 +10054,7 @@
"判定来源": "Source du jugement",
"判定耗时": "Temps de jugement",
"加密存储,只有超级管理员可修改": "Stockage crypté, modifiable uniquement par Super Admin",
"发给 Jev 的内容上限(字节)": "Limite de contenu (en octets) envoyée à Jev",
"发送给判定模型的内容上限(字节)": "Taille maximale du contenu envoyé au modèle de décision (octets)",
"可选:system 提示词": "Facultatif: system Indice Word",
"合规": "Conformité avec",
"合规闸门": "Conformité Gate",
@@ -9999,9 +10074,9 @@
"工具调用 ID 格式不兼容": "Le format d'appel d'outils ID est incompatible",
"已授权": "Autorisé à",
"已生效": "déjà en vigueur",
"已调用 Jev": "Jev a été appelé",
"已调用模型": "Modèle appelé",
"平台暂未开放需要授权的智能路由功能": "La plateforme n'est pas encore ouverte pour les fonctions de routage intelligent nécessitant une autorisation",
"平台未开启 Jev 出境": "La plateforme n'est pas ouverte Jev Sortie du pays",
"平台未开启境外模型判定": "Les décisions par un modèle à l’étranger sont désactivées sur la plateforme",
"平台集合": "Collection de plateformes",
"平台集合对所有用户可用;修改候选会影响所有引用它的令牌,并写入审计日志。": "La collection de plateformes est disponible pour tous les utilisateurs; le candidat à la modification affecte tous les jetons qui la référencent et est écrit dans le journal d'audit.",
"平衡 τ1,τ2,τ3": "Équilibre τ1,τ2,τ3",
@@ -10013,7 +10088,7 @@
"我的集合": "Ma collection",
"把正式脱敏后的请求发送给基线模型和评审模型,用于对比质量。": "Les demandes formellement désensibilisées sont envoyées au modèle de base et au modèle de révision pour comparer la qualité.",
"把脱敏、截断后的请求与回答片段发送给境外判定服务,用于质量评估。": "Les fragments de demande et de réponse désensibilisés et tronqués sont envoyés au service de jugement offshore pour une évaluation de la qualité.",
"把脱敏、截断后的请求片段发送给境外判定服务(Jev),用于选择合适的模型。": "Les fragments de demande tronqués et désensibilisés sont envoyés au service de décision offshore (Jev) pour sélection du modèle approprié.",
"将脱敏、截断后的请求片段发送至境外判定服务,用于选择合适的模型。": "Des extraits de la requête, expurgés et tronqués, sont envoyés à un service de décision à l’étranger pour sélectionner un modèle adapté.",
"把脱敏后的请求加密留存最多 90 天,用于离线评估。": "Conservez les demandes désensibilisées cryptées pendant 90 jours maximum pour une évaluation hors ligne.",
"授权后会覆盖企业「数据安全」「不用于训练」功能的默认保护。": "Une fois autorisé, la protection par défaut de la fonctionnalité de sécurité des données de l'entreprise « Non utilisé pour la formation » est remplacée.",
"推理模型": "Modèle de raisonnement",
@@ -10027,14 +10102,14 @@
"新建集合": "Nouvelle collection",
"无法归入以上类别的请求": "Demandes qui ne peuvent être classées dans les catégories ci-dessus",
"智能判定": "Décision intelligente",
"智能路由 · Jev 判定(可用)": "Routage intelligent·Décision Jev (disponible)",
"智能路由 · 允许模型判定": "Routage intelligent · Autoriser les décisions par modèle",
"智能路由 · 质量评估(可用)": "Routage intelligent·Evaluation de la qualité (disponible)",
"有效期(秒)": "Durée de validité en secondes",
"未经过闸门": "Ne pas passer la porte",
"未设置密钥": "La clé n'est pas définie",
"未通过剥离兼容性验证的渠道类型(逗号分隔)": "Types de canaux (séparés par des virgules) qui n'ont pas été vérifiés par la compatibilité de décapage",
"查看智能路由": "Voir le Smart Routing",
"标注「合规」的配置项只有超级管理员可以修改。开启 Jev 出境前须完成合规评估。": "Les éléments de configuration étiquetés « Conformité » ne peuvent être modifiés que par les super-administrateurs. une évaluation de la conformité doit être effectuée avant d'ouvrir Jev pour quitter le pays.",
"标注「合规」的配置项仅限超级管理员修改。启用境外判定模型前须完成合规评估。": "Seuls les superadministrateurs peuvent modifier les paramètres marqués « Conformité ». Une évaluation de conformité est requise avant d’activer un modèle de décision à l’étranger.",
"标签修改后,任务置信度阈值建议观察 7 天后再调整。必须包含 general。": "Après la modification de l'étiquette, le seuil de confiance de la tâche recommande 7 jours d'observation avant d'être ajusté. general doit être inclus.",
"模型角色与阈值": "Rôles modèles et seuils",
"每人最多个人集合数": "Nombre maximum de collections individuelles par personne",
@@ -10076,15 +10151,15 @@
"调用失败": "Appel échoué",
"企业集合只对本企业令牌生效。候选模型同样受作用域模型白名单约束:使用作用域白名单时,需同时加入 router/ 虚拟名与它的候选模型,否则判定时候选会被过滤。": "La collection d'entreprise n'est efficace que pour ce jeton d'entreprise. modèle candidat est également soumis à la liste blanche du modèle de portée: lors de l'utilisation de la liste blanche de portée, le nom virtuel router/ doit être ajouté avec son modèle candidat, sinon le temps de décision sera filtré.",
"平台已关闭本企业的智能路由。之前授予的数据出境同意仍然有效,功能重新开启后会自动生效;如不再需要,请在此撤回。": "La plateforme a désactivé le routage intelligent pour cette entreprise. le consentement de sortie de données précédemment accordé reste valide et prend effet automatiquement lorsque la fonctionnalité est réactivée; si elle n'est plus nécessaire, veuillez le retirer ici.",
"余额不足,未调用 Jev": "Solde insuffisant, Jev n'a pas été appelé",
"今日 Jev 判定次数已达上限": "Aujourd 'hui, le nombre de jugements Jev a atteint sa limite maximale",
"Jev 判定每人每日上限(0 不限)": "Jev détermine la limite quotidienne maximale par personne (0 illimité)",
"Jev 判定每企业每日上限(0 不限)": "Jev détermine le plafond journalier par entreprise (0 sans limite)",
"余额不足,未调用模型": "Solde insuffisant, modèle non appelé",
"今日模型判定次数已达上限": "Limite quotidienne de décisions par modèle atteinte",
"每人每日模型判定次数上限(0 表示不限)": "Limite quotidienne de décisions par modèle et par utilisateur (0 = illimité)",
"每个企业每日模型判定次数上限(0 表示不限)": "Limite quotidienne de décisions par modèle et par organisation (0 = illimité)",
"每个企业最多集合数": "Nombre maximum de collections par entreprise",
"以上计数为当前节点进程内累计值,进程重启后清零": "Le compte ci-dessus est la valeur cumulée dans le processus du nœud courant et est mis à zéro après le redémarrage du processus.",
"渠道查询失败": "Échec de la demande de canal",
"会话读取失败": "Session lecture échouée",
"Jev 降级次数": "Jev Nombre de relégations",
"模型判定失败后使用规则的次数": "Nombre de recours aux règles après un échec du modèle de décision",
"存储未就绪拒绝": "Stockage pas prêt Refusé",
"试路由": "Essayez le routage",
"试路由失败,请稍后重试": "La tentative de routage a échoué, veuillez réessayer plus tard",
@@ -10105,11 +10180,11 @@
"配置未修改": "Configuration non modifiée",
"闲聊、简单查询": "Petites discussions, demandes simples",
"难度概率": "Probabilité de difficulté",
"集合未允许使用 Jev": "La collection n'autorise pas Jev",
"此集合未开启模型判定": "Les décisions par modèle sont désactivées pour cette collection",
"预估 token": "token estimé",
"高级:难度档阈值 τ1,τ2,τ3(留空使用策略默认值)": "Avancé: seuil de difficulté τ1,τ2,τ3 (vide pour utiliser les valeurs par défaut de la stratégie)",
"默认模型(判定失败时使用)": "Modèle par défaut (utilisé en cas d'échec de la décision)",
"Jev 失败,规则判定": "Jev a échoué, la règle a décidé",
"模型判定失败,已使用规则": "Échec de la décision du modèle, règles appliquées",
"Smart Router": "Smart Router",
"general 行的 4 个单元格必须全部填写": "Les 4 cellules de la ligne general doivent toutes être remplies",
"任务标签不能重名": "Les étiquettes de tâches ne peuvent pas être renommées",
@@ -10126,7 +10201,7 @@
"最便宜的候选": "Le candidat le moins cher",
"未启用,使用默认模型": "Non activé, avec le modèle par défaut",
"没有权限执行该操作": "Ne pas avoir la permission de faire cette action",
"清除后该通道无法调用 Jev,判定会降级为规则判定。": "Le canal ne peut pas appeler Jev après le nettoyage, et la décision est rétrogradée à une décision de règle.",
"清除后,此通道将无法调用判定模型。所有通道均不可用时,将使用规则判定。": "Une fois la clé effacée, ce canal ne pourra plus appeler le modèle de décision. Si aucun canal n’est disponible, les règles seront appliquées.",
"短名只允许小写字母、数字和连字符,最长 48 个字符": "Seules les lettres minuscules, les chiffres et les tirets sont autorisés pour les noms courts, jusqu'à 48 caractères.",
"确认清除密钥?": "Confirmer la clé de nettoyage?",
"自定义规则强制档位": "Règles personnalisées Force Gear",
@@ -11426,7 +11501,345 @@
"consoleUi.descriptions.commission": "Gérez les partenaires, le rattachement des clients, les paliers de commission et les relevés",
"consoleUi.descriptions.smart-router": "Configurez les modèles candidats et les stratégies de routage des modèles virtuels",
"分佣功能未开启,可在「系统设置 → 运营设置 → 通用设置」中开启": "Les commissions sont désactivées. Activez-les dans « Paramètres système → Paramètres d'exploitation → Paramètres généraux »",
"关闭后停止全部分佣计提、后台任务与分佣/伙伴接口,不再产生任何分佣相关的数据库读写": "Une fois désactivé, le calcul des commissions, les tâches de fond et les API commissions/partenaires s'arrêtent ; plus aucune lecture ni écriture en base liée aux commissions n'est effectuée"
"关闭后停止全部分佣计提、后台任务与分佣/伙伴接口,不再产生任何分佣相关的数据库读写": "Une fois désactivé, le calcul des commissions, les tâches de fond et les API commissions/partenaires s'arrêtent ; plus aucune lecture ni écriture en base liée aux commissions n'est effectuée",
"超管代理模式:正在代理操作企业「{{name}}」,所有操作都会记录审计": "Mode proxy administrateur : vous opérez l’organisation « {{name}} » en son nom. Toutes les actions sont auditées.",
"退出代理": "Quitter le mode proxy",
"权限已变更": "Autorisations modifiées",
"你的权限已变更,请重新登录。": "Vos autorisations ont changé. Veuillez vous reconnecter.",
"重新登录": "Se reconnecter",
"不可授予": "Non attribuable",
"丢弃": "Ignorés",
"为平台管理员配置角色、授权菜单与按钮,并分配给用户": "Configurez les rôles des administrateurs de la plateforme, attribuez menus et boutons, puis affectez-les aux utilisateurs",
"为该用户分配平台角色,保存后整体替换原有角色。": "Attribuez des rôles de plateforme à cet utilisateur. L'enregistrement remplace tous les rôles existants.",
"主体 ID": "ID du sujet",
"主体数": "Sujets",
"企业侧": "Côté organisation",
"企业新建角色时可直接套用的预设权限与数据范围": "Permissions et périmètre de données prédéfinis que les organisations peuvent appliquer lors de la création de rôles",
"全部(*)": "Tous (*)",
"全部域": "Tous les domaines",
"全部数据": "Toutes les données",
"分配用户": "Affecter des utilisateurs",
"分配角色": "Attribuer des rôles",
"切换后对应模块将以新权限体系判定访问,旧判断不再生效,已登录用户的权限变化会要求重新登录。": "Après la bascule, l'accès à ces modules est déterminé par le nouveau système de permissions et les anciennes vérifications ne s'appliquent plus. Les utilisateurs connectés dont les droits changent devront se reconnecter.",
"删除后不可恢复,确定删除该角色吗?": "Cette action est irréversible. Supprimer ce rôle ?",
"功能套餐": "Forfaits de fonctionnalités",
"功能套餐决定企业可授予给成员的权限范围。": "Le forfait détermine les permissions que l'organisation peut attribuer à ses membres.",
"功能套餐已更新": "Forfait mis à jour",
"包含权限": "Permissions incluses",
"域": "Domaine",
"墓碑": "Supprimé",
"套餐决定企业可授予给成员的权限范围;未单独绑定的企业跟随默认套餐": "Le forfait détermine les permissions qu'une organisation peut attribuer ; les organisations sans forfait propre suivent le forfait par défaut",
"套餐名称": "Nom du forfait",
"差异": "Écarts",
"已从代码目录移除,保留记录以兼容历史授权": "Retiré du catalogue du code ; l'enregistrement est conservé pour la compatibilité avec les attributions existantes",
"已切换企业 ID": "ID des organisations basculées",
"已切换模块": "Modules basculés",
"已对比": "Comparés",
"已设为默认套餐": "Défini comme forfait par défaut",
"已选 {{count}} 项;勾选按钮会自动勾上所属菜单。": "{{count}} sélectionné(s) ; cocher un bouton coche aussi son menu.",
"平台侧": "Côté plateforme",
"平台角色": "Rôles de plateforme",
"当前仍有 {{count}} 条扩权差异,请确认每条都已有解释。": "Il reste {{count}} écarts d'élargissement de droits. Vérifiez que chacun est expliqué.",
"影子对比": "Comparaison fantôme",
"影子对比计数(本节点自启动以来)": "Compteurs de comparaison fantôme (ce nœud, depuis le démarrage)",
"影子差异": "Écarts fantômes",
"所有者专属": "Propriétaire uniquement",
"扩权": "Élargissement",
"扩权项(旧拒新放)必须逐条有解释才能切换到新体系;缩权项(旧放新拒)请确认是否为预期收紧。": "Chaque élément élargissant les droits (refusé avant, autorisé maintenant) doit être expliqué avant de basculer ; pour les éléments restreignant les droits (autorisé avant, refusé maintenant), confirmez que la restriction est voulue.",
"授权已保存": "Permissions enregistrées",
"控制各模块是否切换到新权限体系,以及影子对比的开关": "Contrôlez quels modules utilisent le nouveau système de permissions et activez la comparaison fantôme",
"搜索名称、编码或路由": "Rechercher par nom, code ou route",
"搜索角色名称或编码": "Rechercher un nom ou code de rôle",
"放行": "Autorisé",
"数据范围": "Périmètre des données",
"新建套餐": "Nouveau forfait",
"新建模板": "Nouveau modèle",
"新建角色": "Nouveau rôle",
"旧 / 新": "Ancien / Nouveau",
"时间段": "Créneau",
"显示": "Visible",
"暂无主体明细": "Aucun détail de sujet",
"暂无套餐": "Aucun forfait",
"暂无差异": "Aucun écart",
"暂无已分配用户": "Aucun utilisateur affecté",
"暂无模板": "Aucun modèle",
"暂无角色": "Aucun rôle",
"最近 {{count}} 小时": "{{count}} dernières heures",
"最近出现": "Dernière occurrence",
"未切换任何模块": "Aucun module basculé",
"未单独绑定套餐的企业都将跟随默认套餐,确定把「{{name}}」设为默认吗?": "Toutes les organisations sans forfait propre suivront le forfait par défaut. Définir « {{name}} » comme forfait par défaut ?",
"未就绪": "non prêt",
"本部门": "Son service",
"本部门及以下": "Son service et sous-services",
"本部门及以下或本人": "Son service et sous-services, ou soi-même",
"权限数": "Permissions",
"权限点": "Permission",
"权限管理": "Permissions",
"权限运行模式": "Mode d'exécution des permissions",
"查看用户": "Voir les utilisateurs",
"模板名称": "Nom du modèle",
"次数": "Occurrences",
"点击一行查看涉及的主体明细。": "Cliquez sur une ligne pour voir les sujets concernés.",
"目录": "Répertoire",
"确定删除模板「{{name}}」吗?已用该模板创建的企业角色不受影响。": "Supprimer le modèle « {{name}} » ? Les rôles d'organisation déjà créés à partir de celui-ci ne sont pas affectés.",
"确认切换权限运行模式": "Confirmer le changement de mode",
"绑定企业": "Organisations liées",
"绑定用户": "Utilisateurs liés",
"维护平台与企业两侧菜单、按钮权限点的名称、排序与显隐": "Gérez le nom, l'ordre et la visibilité des permissions de menus et boutons côté plateforme et côté organisation",
"编辑套餐": "Modifier le forfait",
"编辑模板": "Modifier le modèle",
"编辑节点": "Modifier le nœud",
"编辑角色": "Modifier le rôle",
"缩权": "Restriction",
"菜单": "Menu",
"菜单授权": "Attribuer les menus",
"菜单管理": "Gestion des menus",
"角色名称": "Nom du rôle",
"角色模板": "Modèles de rôle",
"角色编码": "Code du rôle",
"设为默认": "Définir par défaut",
"设为默认套餐": "Définir comme forfait par défaut",
"该角色仍绑定 {{count}} 个用户,删除后这些用户将失去该角色的权限。": "Ce rôle est encore lié à {{count}} utilisateur(s). Après suppression, ils perdront ses permissions.",
"请输入套餐名称": "Saisissez un nom de forfait",
"请输入模板名称": "Saisissez un nom de modèle",
"请输入角色名称": "Saisissez un nom de rôle",
"跟随默认套餐": "Suivre le forfait par défaut",
"路由": "Route",
"输入关键字搜索用户": "Saisissez un mot-clé pour rechercher des utilisateurs",
"输入用户名搜索并添加": "Rechercher un nom d'utilisateur à ajouter",
"迁移": "Migré",
"运行模式已保存": "Mode d'exécution enregistré",
"选择平台角色": "Sélectionner des rôles de plateforme",
"逗号分隔的企业 ID,* 表示全部": "ID d'organisations séparés par des virgules ; * = toutes",
"锁定": "Verrouillé",
"锁定节点及其上级不可停用": "Les nœuds verrouillés et leurs parents ne peuvent pas être désactivés",
"从模板创建": "Créer à partir d'un modèle",
"分配员工": "Attribuer des employés",
"删除后已分配该角色的员工将失去对应权限,此操作不可撤销。": "Après la suppression, les employés ayant ce rôle perdront les autorisations correspondantes. Cette action est irréversible.",
"可选:选择模板预填权限与数据范围": "Facultatif : choisissez un modèle pour préremplir les autorisations et la portée des données",
"员工分配已保存": "Attribution des employés enregistrée",
"将带入 {{n}} 项权限,创建后可在「授权」中调整": "{{n}} autorisations seront appliquées ; vous pourrez les ajuster dans « Autoriser » après la création",
"已设为默认员工角色": "Défini comme rôle par défaut des employés",
"已选 {{n}} 项": "{{n}} sélectionné(s)",
"按角色配置员工可访问的菜单、按钮与数据范围": "Configurez par rôle les menus, boutons et la portée des données accessibles aux employés",
"授权": "Autoriser",
"新成员加入企业时自动分配该角色": "Ce rôle est attribué automatiquement aux nouveaux membres de l'entreprise",
"无匹配员工": "Aucun employé correspondant",
"暂无员工": "Aucun employé",
"未选择员工": "Aucun employé sélectionné",
"未选择部门": "Aucun département sélectionné",
"标记为「迁移」的角色由旧角色迁移,切换到新权限体系前修改会被拒绝": "Les rôles marqués « Migré » proviennent des anciens rôles ; leurs modifications sont refusées tant que le nouveau système d'autorisations n'est pas activé",
"由旧角色迁移,切换到新权限体系前修改会被拒绝": "Migré depuis un ancien rôle ; les modifications sont refusées tant que le nouveau système d'autorisations n'est pas activé",
"确定删除该角色?": "Supprimer ce rôle ?",
"自定义部门": "Départements personnalisés",
"自定义部门范围至少选择一个部门": "Sélectionnez au moins un département pour la portée personnalisée",
"菜单与按钮权限": "Autorisations des menus et boutons",
"菜单与数据授权": "Autorisations des menus et des données",
"角色已停用": "Rôle désactivé",
"角色已创建": "Rôle créé",
"角色已删除": "Rôle supprimé",
"角色已启用": "Rôle activé",
"角色管理": "Gestion des rôles",
"设置该成员拥有的企业角色": "Définir les rôles d'entreprise de ce membre",
"选中的员工将拥有该角色,保存后整体替换原有分配;企业所有者无需分配角色。": "Les employés sélectionnés auront ce rôle. L'enregistrement remplace l'attribution existante ; le propriétaire de l'entreprise n'a pas besoin de rôle.",
"选择可访问数据的部门": "Sélectionnez les départements dont les données sont accessibles",
"选择角色": "Sélectionner des rôles",
"选择该成员拥有的企业角色,保存后整体替换原有角色。": "Sélectionnez les rôles d'entreprise de ce membre. L'enregistrement remplace tous les rôles existants.",
"({{m}} 项超出本企业套餐,已忽略)": "({{m}} hors de l'offre de l'entreprise, ignorées)",
"我管辖的部门": "Mes départements gérés",
"扩大": "Élargi",
"冲突": "Conflit",
"缩小": "Réduit",
"切换前对账未通过": "Échec du rapprochement avant bascule",
"已逐条确认扩大项,继续切换": "J'ai vérifié chaque élément élargi, poursuivre la bascule",
"报告中的扩大项会让部分人获得原来没有的访问权限,请逐条核对确认后再继续切换。": "Les éléments élargis du rapport donnent à certaines personnes des accès qu'elles n'avaient pas. Vérifiez-les un par un avant de poursuivre.",
"无报告内容": "Aucun contenu de rapport",
"请从企业登录入口登录": "Connectez-vous via la connexion entreprise",
"该企业已启用新权限体系,个人账号登录后不能直接进入企业中心,请使用企业账号从企业登录入口登录。": "Cette entreprise utilise le nouveau système d'autorisations. Une connexion personnelle ne permet pas d'ouvrir directement le centre entreprise ; connectez-vous avec votre compte entreprise via la connexion entreprise.",
"企业登录状态不匹配": "Session entreprise non concordante",
"当前登录的是另一家企业,不能访问该企业。请重新从企业登录入口登录目标企业,或返回当前登录的企业。": "Vous êtes connecté à une autre entreprise et ne pouvez pas accéder à celle-ci. Connectez-vous à l'entreprise cible via la connexion entreprise, ou revenez à l'entreprise à laquelle vous êtes connecté.",
"请从企业管理重新进入": "Veuillez revenir via la gestion des entreprises",
"超管代理只在发起代理的标签页内有效,新打开的标签页没有代理会话。请到企业管理列表中点击该企业名称重新进入。": "La session de délégation super admin n'est valable que dans l'onglet où elle a été ouverte ; ce nouvel onglet n'en a pas. Dans la liste de gestion des entreprises, cliquez sur le nom de l'entreprise pour y revenir.",
"前往企业登录": "Aller à la connexion entreprise",
"返回当前登录的企业": "Revenir à l'entreprise connectée",
"前往企业管理": "Aller à la gestion des entreprises",
"另有 {{n}} 名成员不在你的数据范围内,保持不变": "{{n}} autres membres sont hors de votre périmètre de données et resteront inchangés",
"迁移套餐的权限在其企业切换前由对账维护": "Les permissions d'un forfait migré sont maintenues par rapprochement jusqu'à la bascule de ses organisations",
"你没有查询用户的权限,只能查看与移除已分配用户": "Vous n'avez pas la permission de rechercher des utilisateurs ; vous pouvez seulement consulter et retirer les utilisateurs assignés",
"代理会话已失效": "Session de proxy expirée",
"代理会话已失效,请从企业管理重新进入": "La session de proxy a expiré. Veuillez y revenir depuis la gestion des organisations",
"代理会话校验失败": "Échec de la vérification de la session de proxy",
"代理会话校验失败,请稍后刷新重试,或从企业管理重新进入": "Échec de la vérification de la session de proxy. Actualisez la page plus tard ou revenez depuis la gestion des organisations",
"对账报告已变化,请重新核对后再确认": "Le rapport de rapprochement a changé. Veuillez le vérifier à nouveau avant de confirmer",
"代理": "Proxy",
"搜索权限": "Rechercher des permissions",
"该企业已启用新权限体系,请先从企业登录入口登录该企业后再授权": "Cette organisation utilise le nouveau système d’autorisations. Connectez-vous via la page de connexion de l’organisation avant d’autoriser.",
"已分配用户加载失败,请关闭后重试": "Échec du chargement des utilisateurs attribués. Fermez puis réessayez.",
"迁移套餐在其企业切换前由对账维护,修改权限可能被拒绝": "Les forfaits migrés sont maintenus par la réconciliation jusqu'à la bascule de leurs entreprises ; la modification des permissions peut être refusée.",
"权限信息加载失败": "Échec du chargement des informations d'autorisation",
"成员列表加载不完整,请刷新后重试": "La liste des membres n'a pas été entièrement chargée. Actualisez puis réessayez.",
"你没有部门查询权限,无法修改自定义部门": "Vous n'avez pas l'autorisation de consulter les départements ; les départements personnalisés ne peuvent pas être modifiés.",
"登录状态已变化": "Statut de connexion modifié",
"你已在其他页面切换了账号,请刷新页面": "Vous avez changé de compte dans un autre onglet. Veuillez actualiser la page.",
"你在该企业的登录已被管理员关闭,请联系企业管理员": "Votre connexion à cette organisation a été désactivée par un administrateur. Contactez l'administrateur de l'organisation.",
"当前是企业登录,个人范围请从个人登录入口登录后再授权": "Vous êtes connecté via le portail de l'organisation. Pour autoriser la portée personnelle, connectez-vous d'abord via la page de connexion personnelle.",
"去企业登录": "Se connecter à l'organisation",
"去个人登录": "Connexion personnelle",
"请输入初始密码": "Saisissez votre mot de passe initial",
"consoleUi.descriptions.authz-menus": "Consultez le catalogue des menus et des permissions, ajustez noms, ordre et visibilité",
"consoleUi.descriptions.authz-roles": "Gérez les rôles de la plateforme, les autorisations de menu et l'affectation des utilisateurs",
"consoleUi.descriptions.authz-packages": "Gérez les offres de fonctionnalités proposées aux entreprises et les menus qu'elles incluent",
"consoleUi.descriptions.authz-templates": "Gérez les modèles de rôles distribués aux entreprises",
"consoleUi.descriptions.authz-mode": "Basculez chaque module entre l'ancien et le nouveau système de permissions et consultez l'état",
"{{field}}最多允许{{max}}个字符。": "{{field}} : {{max}} caractères maximum.",
"{{field}}格式不正确。": "Le format de {{field}} est incorrect.",
"请输入{{field}}。": "Veuillez saisir {{field}}.",
"修改尚未保存,确定离开吗?": "Les modifications ne sont pas enregistrées. Voulez-vous vraiment quitter ?",
"离开": "Quitter",
"继续编辑": "Continuer la modification",
"员工": "Employé",
"新建员工": "Nouvel employé",
"编辑员工": "Modifier l'employé",
"员工资料、账号、额度与角色统一在一个表格管理": "Gérez les profils, comptes, quotas et rôles des employés dans un seul tableau",
"关键字": "Mot-clé",
"姓名 / 登录名 / 工号 / 备注": "Nom / identifiant / matricule / remarque",
"全部组织": "Tous les services",
"企业角色": "Rôles d'entreprise",
"未分配角色": "Aucun rôle attribué",
"所有者不能直接停用,须先完成移交": "Le propriétaire ne peut pas être désactivé directement ; transférez d'abord la propriété",
"停用员工“{{name}}”": "Désactiver l'employé « {{name}} »",
"停用后该企业身份将无法登录,已有会话立即失效,历史记录保留。是否继续?": "Après désactivation, cette identité d'entreprise ne pourra plus se connecter, les sessions en cours expirent immédiatement et l'historique est conservé. Continuer ?",
"确定删除员工“{{name}}”吗?": "Supprimer l'employé « {{name}} » ?",
"删除后将移除该员工在当前企业的访问资格,已有会话立即失效;历史业务记录与审计标识保留,不会删除其个人账号。该操作不可恢复。": "La suppression retire à cet employé l'accès à l'entreprise actuelle et met fin immédiatement aux sessions en cours. L'historique métier et les identifiants d'audit sont conservés, et le compte personnel n'est pas supprimé. Action irréversible.",
"员工已删除": "Employé supprimé",
"员工账号已创建。": "Compte employé créé.",
"员工资料已更新": "Profil de l'employé mis à jour",
"创建后不可修改。": "Non modifiable après la création.",
"用于企业登录,创建后不可修改。": "Utilisé pour la connexion entreprise ; non modifiable après la création.",
"个人账号,由本人在个人中心维护": "Compte personnel, géré par l'utilisateur dans son espace personnel",
"填写时企业内唯一": "Doit être unique dans l'entreprise s'il est renseigné",
"可选任意启用的部门,不选即未分配": "Tout service actif peut être sélectionné ; laisser vide pour non attribué",
"无分配部门权限,主部门不可调整": "Vous n'avez pas le droit d'attribuer un service ; le service principal ne peut pas être modifié",
"部门调整将改变相对数据范围,自定义范围保持不变,请核查角色授权。": "Le changement de service modifie les périmètres de données relatifs ; les périmètres personnalisés restent inchangés. Vérifiez les autorisations des rôles.",
"该成员当前归属的部门已停用,建议调整到启用中的部门。": "Le service actuel de ce membre est désactivé ; il est conseillé de le rattacher à un service actif.",
"选择 CSV 文件": "Choisir un fichier CSV",
"暂无部门": "Aucun département",
"父子联动": "Lier parents et enfants",
"已选 {{n}} 个部门": "{{n}} départements sélectionnés",
"数据范围按勾选的部门精确生效:开启联动时,勾选上级会同时勾选当前已有的全部下级;之后新增的下级部门不会自动加入。": "Le périmètre de données s'applique exactement aux départements cochés. Avec la liaison activée, cocher un parent coche aussi tous ses sous-départements actuels ; ceux ajoutés par la suite ne sont pas inclus automatiquement.",
"数据范围按勾选的部门精确生效:已关闭联动,只勾选节点本身,不包含其下级部门。": "Le périmètre de données s'applique exactement aux départements cochés. La liaison est désactivée : seul le nœud lui-même est coché, pas ses sous-départements.",
"另有 {{n}} 个已保存的部门不在当前部门列表中,保存时保持不变": "{{n}} départements enregistrés ne figurent pas dans la liste actuelle et seront conservés tels quels à l'enregistrement",
"可授予的菜单加载失败,请刷新后重试": "Échec du chargement des menus attribuables. Actualisez puis réessayez",
"角色已创建,请核对权限和数据范围。": "Rôle créé. Veuillez vérifier ses autorisations et son périmètre de données.",
"授权成功,相关账号需重新登录。": "Autorisation enregistrée. Les comptes concernés doivent se reconnecter.",
"角色已保存": "Rôle enregistré",
"确定停用角色“{{name}}”吗?": "Désactiver le rôle « {{name}} » ?",
"停用后该角色的授权不再生效,可随时重新启用。": "Une fois désactivé, les autorisations de ce rôle ne s'appliquent plus. Vous pouvez le réactiver à tout moment.",
"确定删除角色“{{name}}”吗?": "Supprimer le rôle « {{name}} » ?",
"删除后不可恢复。": "Cette action est irréversible.",
"新建员工将自动分配该角色,已有员工角色保持不变。": "Les nouveaux employés recevront automatiquement ce rôle. Les rôles des employés existants restent inchangés.",
"新建员工时自动分配该角色": "Attribué automatiquement aux nouveaux employés",
"请先更换默认员工角色。": "Changez d'abord le rôle d'employé par défaut.",
"角色“{{name}}”状态": "Statut du rôle « {{name}} »",
"菜单与数据授权 - {{name}}": "Autorisations de menus et de données - {{name}}",
"编辑角色 - {{name}}": "Modifier le rôle - {{name}}",
"角色列表": "Liste des rôles",
"已带入 {{n}} 项权限,可在下方继续调整。": "{{n}} autorisations ont été préremplies depuis le modèle. Vous pouvez les ajuster ci-dessous.",
"另有 {{m}} 项超出本企业套餐,已忽略。": "{{m}} autres sont hors du forfait de cette organisation et ont été ignorées.",
"可选:选择模板预填权限与数据范围,也可以直接在下方配置": "Facultatif : choisissez un modèle pour préremplir les autorisations et le périmètre de données, ou configurez-les directement ci-dessous",
"不使用模板": "Aucun modèle",
"请输入角色名称。": "Veuillez saisir le nom du rôle.",
"角色名称最多允许 {{n}} 个字符。": "Le nom du rôle ne peut pas dépasser {{n}} caractères.",
"角色标识": "Identifiant du rôle",
"小写字母开头,只能包含小写字母、数字、下划线,不能以 legacy_ 开头;留空自动生成": "Commence par une lettre minuscule ; uniquement minuscules, chiffres et tirets bas ; ne doit pas commencer par legacy_. Laissez vide pour une génération automatique",
"角色标识格式不正确。": "Le format de l'identifiant du rôle est incorrect.",
"排序不能为负数": "L'ordre de tri ne peut pas être négatif",
"默认员工角色不能直接停用,请先更换默认角色。": "Le rôle d'employé par défaut ne peut pas être désactivé directement. Changez d'abord le rôle par défaut.",
"仍分配给员工的角色不能停用。": "Un rôle encore attribué à des employés ne peut pas être désactivé.",
"你没有菜单与数据授权权限,将创建不含权限的空角色,数据范围为仅本人。": "Vous n'avez pas l'autorisation d'attribuer les menus et les données. Un rôle vide sans autorisations sera créé, avec un périmètre de données limité à soi-même.",
"请选择数据范围。": "Veuillez sélectionner un périmètre de données.",
"自定义数据范围至少选择一个部门": "Sélectionnez au moins un département pour le périmètre de données personnalisé",
"只能授予本企业套餐内的菜单与按钮": "Seuls les menus et boutons inclus dans le forfait de cette organisation peuvent être attribués",
"分配员工 - {{name}}": "Attribuer des employés - {{name}}",
"可选员工": "Employés disponibles",
"已分配": "Attribués",
"搜索员工": "Rechercher des employés",
"暂无可用功能,请联系管理员。": "Aucune fonctionnalité disponible. Veuillez contacter l'administrateur.",
"{{menus}} 个菜单 · {{buttons}} 个按钮": "{{menus}} menus · {{buttons}} boutons",
"{{name}} · {{count}} 项按钮": "{{name}} · {{count}} boutons",
"停用角色": "Désactiver le rôle",
"共 {{count}} 项": "{{count}} au total",
"内置角色不能停用": "Les rôles intégrés ne peuvent pas être désactivés",
"套餐列表": "Liste des forfaits",
"套餐至少包含一个可访问的菜单": "Un forfait doit inclure au moins un menu accessible",
"已逐条确认,继续切换": "Chaque élément a été vérifié, poursuivre la bascule",
"平台角色已保存。": "Rôle de plateforme enregistré.",
"授权树加载失败,无法查看或修改授权": "Échec du chargement de l'arborescence des permissions ; impossible de consulter ou de modifier les autorisations",
"排序须为非负整数": "L'ordre doit être un entier non négatif",
"显示与启用在列表中直接切换;类型、编码、路由与上级由代码定义,不可修改。": "La visibilité et l'activation se modifient directement dans la liste. Le type, le code, la route et le parent sont définis dans le code et ne peuvent pas être modifiés.",
"有 {{count}} 名成员的企业登录名回填不了或账号没有密码,切换后无法用密码从企业入口登录,请逐人处理或确认。": "{{count}} membres n'ont pas d'identifiant d'entreprise récupérable ou n'ont pas de mot de passe. Après la bascule, ils ne pourront pas se connecter par mot de passe depuis l'accès entreprise. Traitez ou confirmez chaque cas.",
"未授权": "Aucune autorisation",
"本次变更将影响{{count}}个企业,请确认。": "Cette modification affectera {{count}} entreprises. Veuillez confirmer.",
"权限字符": "Clé de rôle",
"权限字符须以小写字母开头,只能包含小写字母、数字、下划线,且不能以 legacy_ 开头": "La clé de rôle doit commencer par une minuscule, ne contenir que des minuscules, des chiffres et des tirets bas, et ne pas commencer par legacy_",
"权限摘要": "Résumé des permissions",
"查看套餐": "Voir le forfait",
"查看模板": "Voir le modèle",
"模板列表": "Liste des modèles",
"没有匹配的权限": "Aucune permission correspondante",
"确认保存套餐": "Confirmer la modification du forfait",
"菜单列表": "Liste des menus",
"菜单配置已保存。": "Configuration du menu enregistrée.",
"角色分配成功。": "Rôle attribué avec succès.",
"角色详情": "Détails du rôle",
"该角色仍分配给 {{count}} 个用户,需先移除后才能删除。": "Ce rôle est encore attribué à {{count}} utilisateurs. Retirez-les avant de le supprimer.",
"迁移角色的权限字符由系统维护,不能修改": "La clé d'un rôle migré est gérée par le système et ne peut pas être modifiée",
"默认套餐不能停用,请先设置其他默认套餐": "Le forfait par défaut ne peut pas être désactivé. Définissez d'abord un autre forfait par défaut",
"账号类型": "Type de compte",
"创建后为启用状态;平台角色请在列表操作列通过「分配角色」设置": "Le compte est activé dès sa création. Attribuez les rôles de plateforme via « Attribuer des rôles » dans les actions de la liste.",
"调整额度不能为 0": "L'ajustement ne peut pas être égal à 0",
"调整后的剩余额度不能小于 0": "Le quota restant après ajustement ne peut pas être inférieur à 0",
"当前剩余额度 {{current}} + 调整额度 {{delta}} = 新剩余额度 {{next}}": "Restant actuel {{current}} + ajustement {{delta}} = nouveau restant {{next}}",
"只读;调整请使用列表操作列的「添加额度」": "Lecture seule. Utilisez « Ajouter du quota » dans les actions de la liste pour l'ajuster.",
"企业所有者已更换": "Propriétaire de l'entreprise modifié",
"更换后立即生效,是否继续?": "Le changement prend effet immédiatement. Continuer ?",
"确认更换": "Confirmer le changement",
"更换企业所有者": "Changer le propriétaire de l'entreprise",
"仅用于原所有者停用、离开或数据异常时的兜底更换;接任人必须是该企业状态正常的成员。": "À utiliser uniquement en dernier recours lorsque le propriétaire actuel est désactivé, parti ou que les données sont incohérentes. Le successeur doit être un membre actif de cette entreprise.",
"更换原因": "Motif du changement",
"请填写更换原因": "Saisissez le motif du changement",
"更换原因不能超过 {{max}} 个字": "Le motif ne peut pas dépasser {{max}} caractères",
"最大成员数和最大Token数必须为非负整数": "Le nombre maximal de membres et de jetons doit être un entier non négatif",
"企业所有者": "Propriétaire de l'entreprise",
"企业预警通知": "Notifications d'alerte",
"更换所有者": "Changer de propriétaire",
"调整套餐": "Changer de forfait",
"功能套餐只控制功能菜单及按钮,分组、额度、限额独立生效": "Le forfait de fonctionnalités ne contrôle que les menus et les boutons ; les groupes, le quota et les limites s'appliquent indépendamment.",
"须为非负整数;填 0 使用系统默认值": "Doit être un entier non négatif ; saisissez 0 pour utiliser la valeur par défaut du système.",
"须为非负整数;填 0 表示本次不修改": "Doit être un entier non négatif ; saisissez 0 pour ne pas modifier la valeur cette fois.",
"搜索企业名称、代码、联系人": "Rechercher par nom d'entreprise, code ou contact",
"该企业已切换到新权限体系:菜单类功能由功能套餐决定,这里只调整行为类开关。": "Cette entreprise est passée au nouveau système d'autorisations : les fonctionnalités de menu dépendent du forfait de fonctionnalités, seuls les commutateurs de comportement sont réglables ici.",
"企业「{{name}}」的所有者将更换为「{{member}}」,原所有者按移交规则降级。": "Le propriétaire de « {{name}} » sera remplacé par « {{member}} » ; l'ancien propriétaire est rétrogradé selon les règles de transfert.",
"当前所有者": "Propriétaire actuel",
"接任成员": "Membre successeur",
"可按显示名称或登录名搜索,最多列出 100 名正常成员": "Recherche par nom d'affichage ou identifiant ; 100 membres actifs au maximum sont listés.",
"请选择接任成员": "Sélectionnez un membre successeur",
"暂无可选成员": "Aucun membre disponible",
"令牌管理": "Gestion des jetons",
"管理令牌": "Gérer les jetons",
"个令牌": "jetons",
"请填写员工姓名": "Veuillez saisir le nom de l’employé",
"工号在企业内已存在": "Ce matricule existe déjà dans l’entreprise",
"表头需含 login_name,display_name,email,employee_no(login_name 与 display_name 必填;工号填写时须在企业内唯一)。单次最多 500 行。每个账号返回一次性初始密码。": "L’en-tête doit contenir login_name,display_name,email,employee_no (login_name et display_name obligatoires ; le matricule, s’il est renseigné, doit être unique dans l’entreprise). 500 lignes maximum par import. Un mot de passe initial à usage unique est renvoyé pour chaque compte.",
"首次登录请先修改初始密码,再进行授权": "Veuillez modifier votre mot de passe initial avant d’autoriser",
"查看密钥过于频繁,请稍后再试": "Trop de consultations de clé, réessayez plus tard",
"未命名部门": "Département sans nom",
"未知主体": "Sujet inconnu",
"未知技能": "Compétence inconnue",
"以下模型在新分组下不可用,已自动移除:{{models}}": "Ces modèles ne sont pas disponibles dans le nouveau groupe et ont été retirés : {{models}}",
"分组加载失败,请刷新后重试": "Échec du chargement des groupes, actualisez puis réessayez",
"员工姓名不能超过 {{max}} 个字符": "Le nom de l’employé ne peut pas dépasser {{max}} caractères",
"邮箱不能超过 {{max}} 个字符": "L’e-mail ne peut pas dépasser {{max}} caractères"
},
"操作成功": "Opération réussie",
"状态": "Statut",

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