Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a62c80aea1 | |||
| 06ef5f3f77 | |||
| cd6eae5ed9 | |||
| 7e89edda5b | |||
| 2c43dd9cb1 | |||
| 6e41115d40 | |||
| 1e7780bdce | |||
| 5a9d6ae3cb | |||
| 3a0d9e15cd | |||
| 04cf3324a3 | |||
| a811793825 | |||
| 9576ba674a | |||
| 870b51d054 | |||
| ed693a450a | |||
| 49515f4ef3 | |||
| f896495048 | |||
| a532b860c8 |
@@ -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__/
|
||||
|
||||
@@ -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 与静态资源缓存 |
|
||||
|
||||
+246
-2
@@ -1,6 +1,6 @@
|
||||
# 变更记录(CHANGELOG)
|
||||
|
||||
> 状态:有效(持续追加) · 更新:2026-11-23 · 版本:v3.8
|
||||
> 状态:有效(持续追加) · 更新:2026-12-01 · 版本:v3.20
|
||||
|
||||
对现状仍有影响的功能与修复记录,按日期倒序。改造、迁移、优化等一次性过程不在此记录。
|
||||
|
||||
@@ -8,8 +8,244 @@
|
||||
|
||||
**记录规则**:每条写“范围、变更、影响、回滚、关联”五项;回滚优先 `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 的只读请求。
|
||||
- **变更**:看板首轮查询取消后可重新发起,作品详情的当前副作用接管加载状态。只读请求默认 60 秒超时,运营看板核心请求设置为 30 秒。
|
||||
- **影响**:两处首次加载可正常结束。只读接口持续无响应时返回超时错误,页面可按原有失败流程结束加载。
|
||||
- **回滚**:还原运营看板和作品详情的加载处理,以及公共 API 的只读超时。
|
||||
- **关联**:`src/hooks/analytics/useAnalyticsData.js`、`src/components/creation/WorkFeed/WorkDetailDrawer.jsx`、`src/helpers/api.js`。
|
||||
|
||||
## 2026-11-24
|
||||
|
||||
### 功能 · 计费详情弹窗增加费用明细与计算公式
|
||||
|
||||
- **范围**:使用记录 `/user-center/usage-record` 与控制台使用日志的「详情」弹窗(共用 `UsageLogsTable.jsx`)。
|
||||
- **变更**:新增「费用明细」:公式行(总金额 = 各计费项小计相加)与分项表(计费项、用量、单价、小计、合计),每行标注单价由哪些倍率构成;用量从「成本因子」移到分项表,成本因子只留倍率等补充信息。拆分逻辑在 `billingBreakdown.js`,口径对照后端结算公式;各行按展示精度四舍五入后与合计的差额归入「舍入与其他调整」一项,保证界面上的数字逐项相加恰好等于合计(`reconcileDisplayAmounts`);分项之和与实扣相差超过 1 个额度单位时视为口径未覆盖(如任务按时长 / 分辨率系数计价),token 兜底预扣与差额调整行同样不拆分,这些情况都不显示费用明细。已在费用明细里逐行列出的用量不再出现在成本因子区;按次 / 按秒计费的明细里没有 token 行,token 用量仍留在成本因子区。弹窗里的倍率由保留 3 位小数改为最多 6 位。超级管理员多一个「超管指标」区块,三项:官方价金额(1 倍率)= 同样用量按「模型原厂价格」计价 ÷ 原厂价登记汇率,整体倍率 = 实扣 ÷ 官方价金额,实际折扣 = 整体倍率 ÷ 登记汇率(汇率在 系统设置-倍率设置-模型原厂价格 页签顶部配置,option `OfficialPriceExchangeRate`,默认 7,仅超级管理员可读写),由后端只在超级管理员的日志响应里附加(`other.root_billing`,不落库),普通管理员与用户的接口不返回;未登记原厂价、或含音频 / 图片输入 / 工具调用等原厂价格表没有价目的计费项时不显示;按次计费但实扣含任务系数、出图接口、token 兜底预扣与差额调整行同样不显示。
|
||||
- **影响**:前端只改展示,不改请求。同批后端改动会改变扣费:Claude 联网搜索开始按次计费(此前算了价但未扣,流式与原生 Claude 格式此前也不记录次数;只对 Claude 模型收,其他走 Anthropic 协议的渠道即使上报搜索次数也不收;体验中心 / Playground 对 Claude 模型开启原生联网搜索时同样会多出这笔费用);扣费取整统一为四舍五入到 1 个额度单位(`common.QuotaFromFloat`,取整前先消除浮点噪声):Claude 原生结算、按次 / 按秒 / 任务类计费此前是向下取整,现在小数部分 ≥ 0.5 的每笔多 1 个额度单位(如 0.3 × 1.5 × 500000 由 224999 变为 225000);OpenAI 兼容路径原本就是四舍五入,不变。Claude 原生与音频 / 实时语音路径有费用时至少扣 1 个额度单位(此前不足 1 个单位扣 0)。邀请返佣仍向下取整(`common.QuotaFloorFromFloat`,只消除浮点噪声),保证返佣不超过「比例 × 消费」;token 预扣估算是准入闸门、不是最终扣费,保持原样。发布窗口内已提交未结算的视频任务,预扣(旧版向下取整)与结算(新版四舍五入)可能差 1 个额度单位:结算时重算结果与预扣只差 1 个单位的按预扣结清(`common.SettleRecomputedQuota`),不补扣不退款。缺少计费信息的日志不显示费用明细,弹窗与原来一致。后端结算公式变更时须同步 `billingBreakdown.js`。本条未做浏览器走查。
|
||||
- **回滚**:`git revert` 对应提交;`billingBreakdown.js` 与其单测为新增文件。
|
||||
- **关联**:`src/components/table/usage-logs/{UsageLogsTable.jsx,billingBreakdown.js,UsageLogs.css}`、`src/pages/Setting/Ratio/OfficialPriceExchangeRateSetting.jsx`、`test/unit/{usage-billing-breakdown,usage-billing-detail-render,official-price-exchange-rate-setting}.test.js`、后端 `common/quota.go`、`relay/compatible_handler.go`、`relay/channel/claude/relay-claude.go`、`service/quota.go`、`service/log_overall_ratio.go`、`controller/log.go`。
|
||||
|
||||
### 修复 · 企业登录接入人机验证
|
||||
|
||||
- **范围**:企业登录页 `/org/login`(企业标识登录与免企业标识直登)。
|
||||
- **变更**:系统开启 Turnstile 时,企业登录页显示人机验证,提交 `/api/org/login`、`/api/org/login/direct` 时带上 `turnstile` 参数;后端两条接口同步挂上 `TurnstileCheck`(未开启时自动放行)。
|
||||
- **影响**:未开启 Turnstile 的部署无变化。开启后,企业成员在通过人机验证前不能提交登录;两步验证、多企业选择两步不再重复验证。
|
||||
- **回滚**:`git revert` 对应提交(前后端须一起回滚,只回滚前端会导致开启 Turnstile 的部署无法企业登录)。
|
||||
- **关联**:`src/pages/OrgLogin/index.jsx`、`router/org-router.go`。
|
||||
|
||||
### 新增 · 渠道透传时应用模型映射
|
||||
|
||||
- **范围**:控制台渠道编辑框的「渠道额外设置」。
|
||||
- **变更**:「透传请求体」下方新增「透传时应用模型映射」,支持单独开启并保存。
|
||||
- **影响**:新建渠道和缺少该设置的历史渠道默认关闭。开启后,实际透传且命中渠道映射的请求使用映射后的上游模型名。
|
||||
- **回滚**:关闭该渠道的「透传时应用模型映射」并保存。
|
||||
- **关联**:`src/components/table/channels/modals/EditChannelModal.jsx`、`src/i18n/locales/`。
|
||||
|
||||
### 修复 · 控制台会员列表与弹窗
|
||||
|
||||
- **范围**:控制台 `/console/subscription` 的会员列表、新建与编辑会员卡弹窗。
|
||||
@@ -198,7 +434,7 @@
|
||||
### 修复 · 编辑用户分组提交格式
|
||||
|
||||
- **范围**:`/console/user` 编辑用户的分组字段。
|
||||
- **变更**:单个字符串、逗号分隔字符串和数组均可回填,保存时统一提交逗号分隔字符串。
|
||||
- **变更**:按后端的单分组权限契约回填和保存,历史名称中的逗号原样保留。
|
||||
- **影响**:保留已有分组选择及请求地址。
|
||||
- **回滚**:还原编辑用户表单的分组转换。
|
||||
- **关联**:`src/components/table/users/modals/EditUserModal.jsx`。
|
||||
@@ -309,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`。
|
||||
|
||||
### 修复 · 表格启停开关与分组样式统一
|
||||
|
||||
- **范围**:已有启停开关、调用或计费分组的表格,以及操作列删除确认规范。
|
||||
|
||||
@@ -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 组件边界
|
||||
|
||||
@@ -121,6 +121,7 @@
|
||||
- `API` 已提供:`New-API-User` 请求头;`/api/org/*` 自动注入 `X-Org-Id`(显式传入优先);并发相同 GET 去重(`disableDuplicate: true` 关闭,带取消信号或请求组的 GET 不共享);HTTP 错误统一提示(`skipErrorHandler: true` 跳过并由页面自行处理)。受会话约束的接口首次返回 401 时取消该会话未完成的只读请求,阻止该会话继续发请求,并仅清理、跳转 `/org/login?expired=true` 一次。公开接口或显式 `sessionBound: false` 的请求不参与会话联动。
|
||||
- 同一批必须全部成功的只读请求,可传入同一个 `requestGroup: new AbortController()`;首次拒绝的 HTTP 4xx/5xx 取消同组剩余读取。普通失败不取消无关请求,正常并发不限流;已发送的写入不由请求组批量取消。调用方仍须处理 Promise 拒绝,并在 `finally` 清理加载状态。
|
||||
- 查询参数用 `params` 对象,不手拼查询字符串(手拼不会编码 `&`、`#`、中文)。
|
||||
- `API` 的 GET、HEAD、OPTIONS 默认在 60 秒后超时,调用方可以通过 `timeout` 覆盖。保持在 `finally` 回收加载状态,并让过期请求与当前请求的状态互不干扰。
|
||||
- 响应按 `{ success, message, data }` 处理,先判断 `success`;具体字段以接口契约为准。
|
||||
- 分页参数 `p` 从 1 开始,`page_size` 默认 `ITEMS_PER_PAGE`(10,须与后端一致);后端对 `page_size > 100` 静默截断为 100,需要全量数据时用 `collectPagedItems(fetchPage)`(`src/helpers/paging.js`)。
|
||||
|
||||
|
||||
@@ -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、取消、遮罩共用同一未保存内容确认流程。
|
||||
|
||||
@@ -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,窄屏堆叠且操作可达;新增此类统一规则先写入本文。
|
||||
|
||||
@@ -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 复制。
|
||||
|
||||
|
||||
@@ -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
@@ -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 |
@@ -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>
|
||||
);
|
||||
};
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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';
|
||||
@@ -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('');
|
||||
}
|
||||
@@ -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'],
|
||||
);
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useNavigate } from 'react-router-dom';
|
||||
import { ERROR_ACTIONS } from '../../../helpers/creationError';
|
||||
import { copy, renderQuota, showSuccess } from '../../../helpers';
|
||||
import { useIsMobile } from '../../../hooks/common/useIsMobile';
|
||||
import { useEffectEvent } from '../../../hooks/common/useEffectEvent';
|
||||
import { adapterOf } from '../../../hooks/creation/creationForm';
|
||||
import {
|
||||
elapsedSeconds,
|
||||
@@ -101,24 +102,18 @@ const WorkDetailDrawer = ({
|
||||
}, [taskId]);
|
||||
|
||||
// 打开时拉取一次详情(快照 / 播放地址 / regenerate_supported)
|
||||
const fetchedRef = useRef('');
|
||||
const loadDetail = useEffectEvent(() => fetchDetail(task));
|
||||
useEffect(() => {
|
||||
if (!visible || !task || fetchedRef.current === task.id) return;
|
||||
fetchedRef.current = task.id;
|
||||
if (!visible || !taskId) return;
|
||||
let alive = true;
|
||||
setLoadingDetail(true);
|
||||
fetchDetail(task).finally(() => {
|
||||
loadDetail().finally(() => {
|
||||
if (alive) setLoadingDetail(false);
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
// 只按作品 id 触发
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [visible, taskId]);
|
||||
useEffect(() => {
|
||||
if (!visible) fetchedRef.current = '';
|
||||
}, [visible]);
|
||||
}, [visible, taskId, loadDetail]);
|
||||
|
||||
if (!task) return null;
|
||||
|
||||
|
||||
@@ -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
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -20,7 +20,7 @@ const kindText = (t, kind) =>
|
||||
judge: {
|
||||
title: t('智能判定'),
|
||||
desc: t(
|
||||
'把脱敏、截断后的请求片段发送给境外判定服务(Jev),用于选择合适的模型。',
|
||||
'将脱敏、截断后的请求片段发送至境外判定服务,用于选择合适的模型。',
|
||||
),
|
||||
},
|
||||
eval: {
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
),
|
||||
},
|
||||
|
||||
@@ -118,7 +118,7 @@ const ProfileTable = ({ mode, orgId, canWrite = true, emptyHint }) => {
|
||||
)}
|
||||
{r.jev_allowed && (
|
||||
<Tag color='blue' variant='filled'>
|
||||
Jev
|
||||
{t('允许模型判定')}
|
||||
</Tag>
|
||||
)}
|
||||
</Space>
|
||||
|
||||
@@ -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()));
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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 EditRedemptionModal = ({
|
||||
editingRedemption,
|
||||
visible,
|
||||
refresh,
|
||||
handleClose,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const { id } = editingRedemption;
|
||||
const isEdit = id !== undefined;
|
||||
const isMobile = useIsMobile();
|
||||
const formApi = useRef(null);
|
||||
const formId = useId();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loadedId, setLoadedId] = useState(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const pending = useRef(false);
|
||||
const formDisabled = loading || submitting || (isEdit && loadedId !== id);
|
||||
|
||||
useEffect(() => {
|
||||
if (!visible) return;
|
||||
|
||||
formApi.current?.reset();
|
||||
setLoadedId(null);
|
||||
setLoading(isEdit);
|
||||
if (!isEdit) return;
|
||||
|
||||
let active = true;
|
||||
async function loadRedemption() {
|
||||
try {
|
||||
const { data: result } = await API.get(`/api/redemption/${id}`);
|
||||
if (!active) return;
|
||||
if (result.success) {
|
||||
const { expired_time, ...data } = result.data;
|
||||
formApi.current?.setValues({
|
||||
...initialValues,
|
||||
...data,
|
||||
expired_time:
|
||||
expired_time === 0 ? null : new Date(expired_time * 1000),
|
||||
});
|
||||
|
||||
const handleCancel = () => {
|
||||
props.handleClose();
|
||||
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;
|
||||
};
|
||||
|
||||
const loadRedemption = async () => {
|
||||
setLoading(true);
|
||||
let res = await API.get(`/api/redemption/${props.editingRedemption.id}`);
|
||||
const { success, message, data } = res.data;
|
||||
if (success) {
|
||||
if (data.expired_time === 0) {
|
||||
data.expired_time = null;
|
||||
} else {
|
||||
data.expired_time = new Date(data.expired_time * 1000);
|
||||
}
|
||||
formApiRef.current?.setValues({ ...getInitValues(), ...data });
|
||||
} else {
|
||||
showError(message);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const onScopeChange = useEffectEvent(() => {
|
||||
if (formApiRef.current) {
|
||||
if (isEdit) {
|
||||
loadRedemption();
|
||||
} else {
|
||||
formApiRef.current.setValues(getInitValues());
|
||||
}
|
||||
}
|
||||
});
|
||||
useEffect(() => onScopeChange(), [onScopeChange, props.editingRedemption.id]);
|
||||
}, [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,
|
||||
};
|
||||
}
|
||||
@@ -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'
|
||||
|
||||
@@ -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,
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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: '已使用',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -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 (
|
||||
|
||||
+67
-8
@@ -11,13 +11,25 @@ import i18next from 'i18next';
|
||||
import { MESSAGE_ROLES } from '../constants/playground.constants';
|
||||
import { getServerURL } from './config';
|
||||
import { buildGetRequestKey, getHeaderValue } from './requestDedupe';
|
||||
import { installRequestLifecycle } from './requestLifecycle';
|
||||
import {
|
||||
DEFAULT_READ_TIMEOUT_MS,
|
||||
installRequestLifecycle,
|
||||
} from './requestLifecycle';
|
||||
import {
|
||||
getCurrentOrgId,
|
||||
getProxySession,
|
||||
clearProxySession,
|
||||
isProxyMode,
|
||||
markProxyExpired,
|
||||
} from './orgContext';
|
||||
|
||||
function createAPIInstance() {
|
||||
const serverURL = getServerURL();
|
||||
return axios.create({
|
||||
baseURL: serverURL,
|
||||
withCredentials: serverURL !== '',
|
||||
// Let the lifecycle apply a read default while preserving explicit timeouts.
|
||||
timeout: null,
|
||||
headers: {
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
@@ -41,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,
|
||||
@@ -51,7 +62,9 @@ function patchAPIInstance(instance) {
|
||||
fallbackOrgId,
|
||||
getUserIdFromLocalStorage(),
|
||||
);
|
||||
const key = `${requestKey}#error=${!config?.skipErrorHandler}#session=${config?.sessionBound !== false}`;
|
||||
const timeout =
|
||||
config?.timeout ?? instance.defaults.timeout ?? DEFAULT_READ_TIMEOUT_MS;
|
||||
const key = `${requestKey}#error=${!config?.skipErrorHandler}#session=${config?.sessionBound !== false}#timeout=${timeout}`;
|
||||
if (inFlightGetRequests.has(key)) {
|
||||
return inFlightGetRequests.get(key);
|
||||
}
|
||||
@@ -65,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;
|
||||
@@ -84,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
@@ -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');
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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} />;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { CanceledError, isCancel } from 'axios';
|
||||
const PUBLIC_API_PATH =
|
||||
/^\/api\/(?:status|setup|i18n|notice|about|privacy_policy|user_agreement|home_page_content|customer-service|verification|reset_password|oauth|user\/(?:login|register|reset|passkey\/login)|org\/(?:login|register))(?:\/|$)/;
|
||||
const READ_METHODS = new Set(['get', 'head', 'options']);
|
||||
export const DEFAULT_READ_TIMEOUT_MS = 60_000;
|
||||
|
||||
function isSessionBound(config) {
|
||||
const pathname = config?.url?.split(/[?#]/, 1)[0];
|
||||
@@ -40,6 +41,9 @@ export function installRequestLifecycle(
|
||||
instance.interceptors.request.use((config) => {
|
||||
const sessionBound = isSessionBound(config);
|
||||
const read = READ_METHODS.has(config.method);
|
||||
if (read && config.timeout == null) {
|
||||
config.timeout = DEFAULT_READ_TIMEOUT_MS;
|
||||
}
|
||||
const groupSignal = read ? config.requestGroup?.signal : undefined;
|
||||
if ((sessionBound && session.signal.aborted) || groupSignal?.aborted) {
|
||||
throw new CanceledError(undefined, config);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { useState, useCallback, useEffect, useRef } from 'react';
|
||||
import { API, showError } from '../../helpers';
|
||||
import { useEffectEvent } from '../common/useEffectEvent';
|
||||
import { useFilterSearch } from '../common/useFilterSearch';
|
||||
|
||||
const ANALYTICS_TIMEOUT_MS = 30_000;
|
||||
|
||||
/**
|
||||
* 运营看板数据获取Hook
|
||||
*
|
||||
@@ -24,7 +27,11 @@ export const useAnalyticsData = (active = true) => {
|
||||
const [dateRange, setDateRange] = useState([null, null]); // 自定义日期范围 [startDate, endDate]
|
||||
|
||||
const activeRequest = useRef(null);
|
||||
const cancelQuery = useCallback(() => activeRequest.current?.abort(), []);
|
||||
const loadedRef = useRef(false);
|
||||
const cancelQuery = useCallback(() => {
|
||||
activeRequest.current?.abort();
|
||||
activeRequest.current = null;
|
||||
}, []);
|
||||
useEffect(() => cancelQuery, [cancelQuery]);
|
||||
|
||||
// 将 DatePicker 选择的日期转换为 UTC+8 当天零点/末尾的 Unix 时间戳(秒)
|
||||
@@ -50,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],
|
||||
);
|
||||
@@ -72,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 },
|
||||
);
|
||||
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);
|
||||
@@ -93,9 +98,11 @@ 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,
|
||||
});
|
||||
if (signal.aborted) return;
|
||||
if (res.data.success) {
|
||||
@@ -112,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 },
|
||||
);
|
||||
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 || []);
|
||||
@@ -132,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 },
|
||||
);
|
||||
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 || []);
|
||||
@@ -153,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 },
|
||||
);
|
||||
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 || []);
|
||||
@@ -177,9 +185,11 @@ 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,
|
||||
});
|
||||
if (signal.aborted) return;
|
||||
if (res.data.success) {
|
||||
@@ -196,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 },
|
||||
);
|
||||
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 || []);
|
||||
@@ -238,6 +248,10 @@ export const useAnalyticsData = (active = true) => {
|
||||
if (!signal.aborted) setLoading(false);
|
||||
}
|
||||
await overviewTask;
|
||||
if (activeRequest.current === controller) {
|
||||
activeRequest.current = null;
|
||||
loadedRef.current = true;
|
||||
}
|
||||
},
|
||||
[
|
||||
cancelQuery,
|
||||
@@ -283,15 +297,16 @@ export const useAnalyticsData = (active = true) => {
|
||||
void refreshAll('today', [null, null]);
|
||||
};
|
||||
|
||||
// 懒加载:仅在 active 第一次为 true 时拉数据。
|
||||
// 由调用方传入 activeTab === 'operations',避免在 audit / risk Tab 时白白发起 8 个 API。
|
||||
const loadedRef = useRef(false);
|
||||
const loadInitialData = useEffectEvent(() => {
|
||||
if (!loadedRef.current && !activeRequest.current) {
|
||||
void refreshAll(period, dateRange);
|
||||
}
|
||||
});
|
||||
|
||||
// StrictMode 会取消首次副作用,只有完整结束的请求批次才算加载过。
|
||||
useEffect(() => {
|
||||
if (!active || loadedRef.current) return;
|
||||
loadedRef.current = true;
|
||||
refreshAll(period, dateRange);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [active]);
|
||||
if (active) loadInitialData();
|
||||
}, [active, loadInitialData]);
|
||||
|
||||
return {
|
||||
loading,
|
||||
|
||||
@@ -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 ||
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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);
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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;
|
||||
}, []);
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user