fix(ui): 修复登录与并发请求并统一表格、主题和页面展示

验证:868 项单测、ESLint、Prettier、UI 依赖审计和差异检查通过。
This commit is contained in:
zhanjunhao
2026-11-19 18:58:46 +08:00
parent 9f5e0cddfb
commit e70e0d2224
128 changed files with 4672 additions and 5391 deletions
+2 -1
View File
@@ -89,6 +89,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd
| 企业中心 / 控制台 | `docs/ui/ORG_CENTER_SPEC.md` / `docs/ui/CONSOLE_SPEC.md` | | 企业中心 / 控制台 | `docs/ui/ORG_CENTER_SPEC.md` / `docs/ui/CONSOLE_SPEC.md` |
| 模型超市 / 技能超市 | `docs/ui/MODEL_MARKET_SPEC.md` / `docs/ui/SKILL_MARKET_SPEC.md` | | 模型超市 / 技能超市 | `docs/ui/MODEL_MARKET_SPEC.md` / `docs/ui/SKILL_MARKET_SPEC.md` |
| 表格列设置 | `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md` | | 表格列设置 | `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md` |
| UI 审查清单 | `docs/ui-review-checklist.md` |
| 历史改动与回滚 | `docs/CHANGELOG.md` | | 历史改动与回滚 | `docs/CHANGELOG.md` |
| Windows 命令、代码风格与提交规范 | `docs/standards/DEV_STANDARDS.md` 第 12 节 | | Windows 命令、代码风格与提交规范 | `docs/standards/DEV_STANDARDS.md` 第 12 节 |
@@ -122,7 +123,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd
- 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。 - 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。
- 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。 - 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。
> 规范版本:v3.5 · 更新:2026-11-18 > 规范版本:v3.6 · 更新:2026-11-19
## 10. 工具差异(本节允许不同) ## 10. 工具差异(本节允许不同)
+2 -1
View File
@@ -89,6 +89,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd
| 企业中心 / 控制台 | `docs/ui/ORG_CENTER_SPEC.md` / `docs/ui/CONSOLE_SPEC.md` | | 企业中心 / 控制台 | `docs/ui/ORG_CENTER_SPEC.md` / `docs/ui/CONSOLE_SPEC.md` |
| 模型超市 / 技能超市 | `docs/ui/MODEL_MARKET_SPEC.md` / `docs/ui/SKILL_MARKET_SPEC.md` | | 模型超市 / 技能超市 | `docs/ui/MODEL_MARKET_SPEC.md` / `docs/ui/SKILL_MARKET_SPEC.md` |
| 表格列设置 | `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md` | | 表格列设置 | `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md` |
| UI 审查清单 | `docs/ui-review-checklist.md` |
| 历史改动与回滚 | `docs/CHANGELOG.md` | | 历史改动与回滚 | `docs/CHANGELOG.md` |
| Windows 命令、代码风格与提交规范 | `docs/standards/DEV_STANDARDS.md` 第 12 节 | | Windows 命令、代码风格与提交规范 | `docs/standards/DEV_STANDARDS.md` 第 12 节 |
@@ -122,7 +123,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd
- 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。 - 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。
- 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。 - 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。
> 规范版本:v3.5 · 更新:2026-11-18 > 规范版本:v3.6 · 更新:2026-11-19
## 10. 工具差异(本节允许不同) ## 10. 工具差异(本节允许不同)
+2
View File
@@ -159,6 +159,8 @@ monkey-ai-web/
### 本地 Playwright 登录配置 ### 本地 Playwright 登录配置
全流程 UI 审查使用 [UI 审查清单](docs/ui-review-checklist.md)。`e2e/` 保存本地用例,`.e2e/` 保存分阶段状态、截图、验收报告与会话缓存;均由 Git 忽略。会话缓存不上传、不提交。
本机自动化登录入口为 `e2e/auth-login/run.mjs`(本地验收脚本,Git 忽略)。在 `.env.playwright.local` 中配置 `UI_ORG_NAME`、`UI_ORG_USER`、`UI_ORG_PASS`、`UI_PERSONAL_USER`、`UI_PERSONAL_PASS`。该文件只保存测试账号,按用户约定不作 Git 忽略,允许提交;不得把值写入脚本、日志、截图注释或报告。其他凭据与 storageState 仍不入库。运行时由 Node 加载到环境变量: 本机自动化登录入口为 `e2e/auth-login/run.mjs`(本地验收脚本,Git 忽略)。在 `.env.playwright.local` 中配置 `UI_ORG_NAME`、`UI_ORG_USER`、`UI_ORG_PASS`、`UI_PERSONAL_USER`、`UI_PERSONAL_PASS`。该文件只保存测试账号,按用户约定不作 Git 忽略,允许提交;不得把值写入脚本、日志、截图注释或报告。其他凭据与 storageState 仍不入库。运行时由 Node 加载到环境变量:
```powershell ```powershell
+95
View File
@@ -10,6 +10,101 @@
## 2026-11-19 ## 2026-11-19
### 修复 · 并发请求失败与会话过期提示
- **范围**:统一请求工具、登录入口及企业预算的关联查询。
- **变更**:会话 401 单次处理并取消旧会话的未完成读取;支持按组取消关联读取;合并重复 HTTP 错误和过期提示。
- **影响**:正常并发与公开请求不受限制;单个权限或服务错误不取消无关请求,也不会批量中断已发出的写入。
- **回滚**:仅还原本条的请求生命周期、提示和关联查询改动。
- **关联**:`src/helpers/api.js`、`src/helpers/requestLifecycle.js`、`src/pages/Organization/OrgBudgets.jsx`。
### 调整 · 登录与退出不再弹出成功提示
- **范围**:个人登录、企业登录、两步验证及顶栏退出登录。
- **变更**:移除登录成功和退出成功弹窗。
- **影响**:会话校验、页面跳转、失败提示及密码修改提示保持不变。
- **回滚**:仅还原本条的成功提示改动。
- **关联**:`src/helpers/loginFlow.js`、`src/components/auth/TwoFAVerification.jsx`、`src/hooks/common/useHeaderBar.js`。
### 修复 · 个人与企业登录回跳错位
- **范围**:个人登录、企业登录及同一浏览器切换账号。
- **变更**:直接登录不再读取旧回跳地址;验证会话账号后才完成登录,拒绝明显不匹配的落点;旧会话的迟到响应不再覆盖新会话;企业账号跳转时不再短暂挂载受限的个人页面并误弹权限提示。
- **影响**:保留适用的深链参数、锚点和原有权限校验;无有效落点时回到对应入口的默认页面。
- **回滚**:仅还原本条对应的登录、回跳逻辑和测试。
- **关联**:`src/App.jsx`、`src/helpers/loginFlow.js`、`src/helpers/data.js`、`src/components/layout/PageLayout.jsx`、`test/unit/post-login-redirect.test.js`。
### 调整 · 控制台列表与行操作统一
- **范围**:控制台兑换码、会员卡、发票管理,以及控制台、企业中心、用户中心和视频任务队列的多操作列表。
- **变更**:筛选栅格、列表工具栏、表头、分页与空态按密钥管理收敛;低频行操作统一进入带箭头的“更多”菜单。
- **影响**:不改变接口、载荷、权限、状态限制及危险操作确认;筛选与菜单适配移动端和亮暗主题;修复兑换码抽屉关闭后快速重新编辑时记录被延时清空的问题。
- **回滚**:仅还原本条关联的列表、行操作和公共样式改动,不还原其他主题改动。
- **关联**:`src/components/common/table/TableToolbar.jsx`、`src/components/console/ConsolePrimitives.jsx`、`docs/standards/UI_COMPONENT_STANDARDS.md`。
### 修复 · 云端大脑撰写态左侧对齐
- **范围**:`/experience-center/cloud-brain` 专家列表与撰写区布局。
- **变更**:撰写态由固定宽度居中改为从内容区左侧对齐,编辑区填充剩余空间,消除宽屏左侧与右侧的大块空白。
- **影响**:仅调整布局样式,保留专家选择、任务填写和主题切换行为;窄屏单列布局不变。
- **回滚**:还原 `src/pages/CloudBrain/cloud-brain.css` 中 `.brain-expert-layout.is-composing` 规则。
### 修复 · 图片生成底部操作区固定布局
- **范围**:`/experience-center/image-generation` 参数表单与生成操作区。
- **变更**:将生成按钮及估价移出参数滚动容器,通过独立 flex 区域贴住表单底边;移除固定 124px 底部占位,操作区使用完整主题表面背景,并兼顾移动端安全区。
- **影响**:桌面参数独立滚动,末尾参数可完整滚入可视区域;移动端保留自然堆叠与展开、收起行为,生成及估价逻辑不变。
- **回滚**:仅还原本条涉及的表单滚动结构与操作区 CSS,保留其他主题适配改动。
- **关联**:`src/pages/ExperienceCenter/components/AICreation/ImageGenerationForm.jsx`、`src/pages/ExperienceCenter/components/AICreation/Image/ImageGenerationForm.css`。
### 修复 · 图片生成表单背景与圆角主题适配
- **范围**:`/experience-center/image-generation` 图片生成表单外层、分区与底部生成操作区。
- **变更**:统一使用主题卡片表面色与边框 token,补齐整块白色背景、连续圆角和底部 sticky 操作区的顶部边界;深色模式自动映射深色表面。
- **影响**:仅调整视觉层,保留模型选择、提示词、参数、估价和生成逻辑;禁用按钮继续保持不可提交状态。
- **回滚**:按文件还原 `ImageGenerationForm.jsx`、`ImageGenerationForm.css` 及本条记录。
- **关联**:`src/pages/ExperienceCenter/components/AICreation/ImageGenerationForm.jsx`、`src/pages/ExperienceCenter/components/AICreation/Image/ImageGenerationForm.css`。
### 调整 · 推广分享弹窗布局与交互
- **范围**:顶栏推广入口的链接分享、海报分享及奖励规则入口。
- **变更**:采用 800px Ant Design 弹窗;链接分享以扫码区与复制区双栏展示,奖励规则收为底部轻量入口;海报预览与模板、导出操作分栏,模板使用带名称的单选控件并支持键盘选择;移动端堆叠,短视口正文限高滚动。
- **影响**:弹窗主体跟随系统主题色与亮暗模式,保留已有海报模板、分享接口、邀请地址、奖励页路由和 PNG 导出逻辑;邀请码不可用时不展示占位二维码。
- **回滚**:按文件还原 `src/components/promotion/PromotionPosterModal.jsx` 与 `src/components/promotion/promotion-poster.css`。
- **关联**:`docs/standards/UI_COMPONENT_STANDARDS.md` 第 8、10、15 节。
### 修复 · 系统主题色在亮暗模式下的交互对比度
- **范围**:共享主题入口、双端侧栏与公告、实底控件及系统设置主题色预览。
- **变更**:由当前主题色分别派生实底、文字和选中浅底;亮暗模式分别控制亮度与饱和度。同步企业强调色、个人深色页签和设置预览;预览链接示意即时切色,气泡按渐变亮度选用可读文字。
- **影响**:暗色原型侧栏保持琥珀选中态;默认浅色选中文字微调以达对比度要求。保留原始配置及持久化,成功、警告、错误仍独立配色。
- **回滚**:按文件回退本条涉及的主题解析、样式桥、消费者和配色单测,不改系统设置数据。
- **关联**:`docs/standards/UI_COMPONENT_STANDARDS.md`、`docs/ui-review-checklist.md`。
### 调整 · 新手教程阅读布局与主题适配
- **范围**:`/tutorial` 图文、视频教程及关闭入口。
- **变更**:去除固定阅读高度和嵌套纵向滚动,桌面采用步骤目录与正文双栏、移动目录换行;目录支持滚动同步与焦点定位,代码自动折行;视频列表支持键盘选择;关闭入口使用 Ant Design 文本图标按钮与提示,修复视频空态标题。
- **影响**:颜色跟随系统主题配置和亮暗主题;保留教程内容、请求、链接、返回逻辑和小程序充值步骤隐藏规则。
- **回滚**:按文件还原 `src/pages/Tutorial/` 本次修改。
- **关联**:`docs/ui/GLOBAL_UI_BASELINE.md`、`docs/standards/UI_COMPONENT_STANDARDS.md`。
### 调整 · 顶栏右侧工具与账户对齐
- **范围**:共享顶栏右侧教程、推广、下载、充值、主题、公告、语言和账户入口。
- **变更**:统一按钮高度、图标与文字行高和间距;消除链接与公告徽标包装层的行内基线偏移;调整头像、箭头与分隔线居中,桌面专属按钮按移动断点隐藏。
- **影响**:保留既有权限、配置和操作回调,样式随亮暗主题切换。
- **回滚**:按文件还原 `src/components/layout/headerbar/ActionButtons.jsx` 与 `src/styles/prototype.css` 顶栏相关段落。
- **关联**:`docs/ui/GLOBAL_UI_BASELINE.md` 第 4.1 节。
### 文档 · 补充双端 UI 审查清单
- **范围**:企业端与个人端的 UI 审查、真实操作验收与证据归档。
- **变更**:登记可复用审查清单,忽略 `.e2e/` 的分阶段本地产物。
- **影响**:不改变业务、路由、接口或 Playwright 默认配置;验收证据与会话缓存不入库。
- **回滚**:按文件还原本条涉及的清单、索引与忽略规则;保留既有本地验收证据。
- **关联**:`docs/ui-review-checklist.md`、`README.md`、`.gitignore`。
### 功能 · 恢复服务监控入口并接入超管开关 ### 功能 · 恢复服务监控入口并接入超管开关
- **范围**:用户中心桌面侧栏、移动底栏、服务监控路由与面包屑。 - **范围**:用户中心桌面侧栏、移动底栏、服务监控路由与面包屑。
+2 -1
View File
@@ -18,7 +18,7 @@
| 修改企业中心 / 控制台 | `ui/ORG_CENTER_SPEC.md` / `ui/CONSOLE_SPEC.md` | — | | 修改企业中心 / 控制台 | `ui/ORG_CENTER_SPEC.md` / `ui/CONSOLE_SPEC.md` | — |
| 修改模型超市 / 技能超市 | `ui/MODEL_MARKET_SPEC.md` / `ui/SKILL_MARKET_SPEC.md` | — | | 修改模型超市 / 技能超市 | `ui/MODEL_MARKET_SPEC.md` / `ui/SKILL_MARKET_SPEC.md` | — |
| 修改任一表格的列设置 | `ui/TABLE_COLUMN_SETTINGS_SPEC.md` | — | | 修改任一表格的列设置 | `ui/TABLE_COLUMN_SETTINGS_SPEC.md` | — |
| 做 UI 验收 | `ui/GLOBAL_UI_BASELINE.md` 第 6、7 节 | 对应页面规范的“验收要点” | | 做 UI 验收 | `ui/GLOBAL_UI_BASELINE.md` 第 6、7 节 | `ui-review-checklist.md`、对应页面规范的“验收要点” |
| 查改动范围或回滚方式 | `CHANGELOG.md` | — | | 查改动范围或回滚方式 | `CHANGELOG.md` | — |
每份规范开头都有“何时阅读”和“速查”表,先看速查,需要细节再按章节号读取。 每份规范开头都有“何时阅读”和“速查”表,先看速查,需要细节再按章节号读取。
@@ -38,6 +38,7 @@
| `ui/MODEL_MARKET_SPEC.md` | 模型超市 | 约 8KB | | `ui/MODEL_MARKET_SPEC.md` | 模型超市 | 约 8KB |
| `ui/SKILL_MARKET_SPEC.md` | 技能超市与数据模式 | 约 8KB | | `ui/SKILL_MARKET_SPEC.md` | 技能超市与数据模式 | 约 8KB |
| `ui/TABLE_COLUMN_SETTINGS_SPEC.md` | 表格列设置 | 约 4KB | | `ui/TABLE_COLUMN_SETTINGS_SPEC.md` | 表格列设置 | 约 4KB |
| `ui-review-checklist.md` | 双端 UI 审查、交互与证据记录清单 | 约 3KB |
| `CHANGELOG.md` | 对现状仍有影响的功能与修复记录 | 约 6KB | | `CHANGELOG.md` | 对现状仍有影响的功能与修复记录 | 约 6KB |
## 规则优先级 ## 规则优先级
+2 -1
View File
@@ -118,7 +118,8 @@ ESLint 规则 `header/header` 要求每个 `.js/.jsx` 顶部带 AGPL 许可证
### 3.1 规则 ### 3.1 规则
- 只用 `import { API } from '@/helpers'`;禁止新建 axios 实例或用 `fetch` 调 `/api`(流式对话 `src/hooks/playground/useApiRequest.jsx` 除外)。 - 只用 `import { API } from '@/helpers'`;禁止新建 axios 实例或用 `fetch` 调 `/api`(流式对话 `src/hooks/playground/useApiRequest.jsx` 除外)。
- `API` 已提供:`New-API-User` 请求头;`/api/org/*` 自动注入 `X-Org-Id`(显式传入优先);并发相同 GET 去重(`disableDuplicate: true` 关闭);HTTP 错误统一提示(`skipErrorHandler: true` 跳过并由页面自行提示);401 清理会话并跳转 `/org/login?expired=true`。 - `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` 对象,不手拼查询字符串(手拼不会编码 `&`、`#`、中文)。 - 查询参数用 `params` 对象,不手拼查询字符串(手拼不会编码 `&`、`#`、中文)。
- 响应按 `{ success, message, data }` 处理,先判断 `success`;具体字段以接口契约为准。 - 响应按 `{ success, message, data }` 处理,先判断 `success`;具体字段以接口契约为准。
- 分页参数 `p` 从 1 开始,`page_size` 默认 `ITEMS_PER_PAGE`(10,须与后端一致);后端对 `page_size > 100` 静默截断为 100,需要全量数据时用 `collectPagedItems(fetchPage)`(`src/helpers/paging.js`)。 - 分页参数 `p` 从 1 开始,`page_size` 默认 `ITEMS_PER_PAGE`(10,须与后端一致);后端对 `page_size > 100` 静默截断为 100,需要全量数据时用 `collectPagedItems(fetchPage)`(`src/helpers/paging.js`)。
+5 -4
View File
@@ -53,9 +53,9 @@
品牌主题预设在 `src/styles/presets.js`,主题配置与持久化在 `src/helpers/theme.js` 与 `src/context/Theme`;预设 key 不改名。 品牌主题预设在 `src/styles/presets.js`,主题配置与持久化在 `src/helpers/theme.js` 与 `src/context/Theme`;预设 key 不改名。
组件级配置:`Menu`(项高 42px,选中底 `#fff3df` / `#382b1b`,选中文字 `#a95d07` / `#f2ad41`);`Card` 标题 15px;`Modal` 圆角 12px;`Tag` 默认描边样式;弹窗与抽屉遮罩默认不模糊。 组件级配置:`Menu` 项高 42px,原型选中底 `#fff3df` / `#382b1b`,选中文字 `#a45a07` / `#f2ad41`;`Card` 标题 15px;`Modal` 圆角 12px;`Tag` 默认描边样式;弹窗与抽屉遮罩默认不模糊。
暗色主色:antd 暗色算法由种子 `#f2ad41` 推导出 `#d1963a`。系统以 `#d1963a` 作为 `colorPrimary`,其余衍生 token 仍按种子推导;页面需要“品牌强调色”时用 `brandAccentFromToken(colorPrimary, dark)`,浅色与自定义主色返回 `colorPrimary`,默认暗色返回 `#f2ad41`。 暗色原型:antd 暗色算法由种子 `#f2ad41` 推导出 `#d1963a`;保留该全局主色及原型选中态。系统配置的主题色保留为原始种子,交互色根据当前明暗模式派生:选中背景低浓度着色,选中文字与强调色保证可读;实底按钮的默认、悬停和按压态共享同一前景色。页面复用 `--brand-accent`、`--brand-selection-bg`、`--brand-selection-text`,不自行写固定品牌色;成功、警告、错误继续独立于主色。
### 2.2 取色方式 ### 2.2 取色方式
@@ -132,6 +132,7 @@ html.dark .km-page {
- 行为:搜索与重置都回到第 1 页;重置 = 清空表单 + 以默认条件重新查询;只切换筛选的页签放在筛选卡上方。 - 行为:搜索与重置都回到第 1 页;重置 = 清空表单 + 以默认条件重新查询;只切换筛选的页签放在筛选卡上方。
- 移动端:用户中心与控制台默认收起,通过“显示 / 隐藏操作项”或“筛选”按钮展开;列设置入口不随筛选收起。 - 移动端:用户中心与控制台默认收起,通过“显示 / 隐藏操作项”或“筛选”按钮展开;列设置入口不随筛选收起。
- 控制台使用 `ConsoleSearchBar` + `ConsoleSearchActions`,企业中心使用 `OrgFilterCard`,不要另写网格。 - 控制台使用 `ConsoleSearchBar` + `ConsoleSearchActions`,企业中心使用 `OrgFilterCard`,不要另写网格。
- 控制台标准列表以 `/console/token` 为参考:使用 `ConsoleCollection`(或通过 `CardPro` 接入),控件走共享筛选栅格(三列、≤ 1100px 两列、≤ 768px 单列),在列表卡内单列工具栏;快捷筛选在左,批量、刷新、新建等列表动作在右。不要把列表动作插进搜索字段区,也不要为了对齐而新增无业务语义的按钮。
## 5. 表格 ## 5. 表格
@@ -149,7 +150,7 @@ html.dark .km-page {
- 每列显式 `width`,长文本 `ellipsis` 并配 `Tooltip`;金额与数量右对齐;时间统一格式,必要时日期与时间分两行。 - 每列显式 `width`,长文本 `ellipsis` 并配 `Tooltip`;金额与数量右对齐;时间统一格式,必要时日期与时间分两行。
- 状态列用 `Tag` 或 `Switch`(见第 11 节);启停开关请求中禁用,失败恢复原状态。 - 状态列用 `Tag` 或 `Switch`(见第 11 节);启停开关请求中禁用,失败恢复原状态。
- 操作列放在最后,按钮为 `type='link' size='small'`,危险操作加 `danger`,同一行操作间距 8–10px;用户中心、企业中心、控制台(含系统设置)的操作列统一 `fixed: 'right'`;操作较多时折叠到“更多”下拉。 - 操作列放在最后,标题固定为“操作”,按钮为 `type='link' size='small'`,同一行操作间距 8px;用户中心、企业中心、控制台(含系统设置)的操作列统一 `fixed: 'right'`。多操作列表以 `/console/commission?view=partners` 为参考:使用 `TableRowActions`,直出 1–2 个高频动作(如“详情”“编辑”),其余放进带下箭头的文字“更多”菜单。菜单点击打开、右对齐,无有效菜单项时不渲染入口;危险项置末、标记 `danger` 并保留业务确认。现有权限、状态限制、禁用项和回调不得因收纳而改变,方向键、Enter、Escape 可操作菜单。
- 三中心表格通过 `CenterActionTable` 统一处理,最后一列存在创建、查看、编辑、测试、详情、删除、添加、设置、配置、弹窗 / 抽屉或请求交互时,列头统一显示“操作”并固定右侧,宽度按按钮 / 交互数量计算。没有操作列但估算列宽超出容器时,从右侧固定末 4 列,列数不足时降为 3、2、1 列。固定列使用不透明底色并保持表头层级;横向滚动条遵循 Ant Design 官方固定列表格行为,允许鼠标、触控板、触屏和键盘滚动,不隐藏滚动条。 - 三中心表格通过 `CenterActionTable` 统一处理,最后一列存在创建、查看、编辑、测试、详情、删除、添加、设置、配置、弹窗 / 抽屉或请求交互时,列头统一显示“操作”并固定右侧,宽度按按钮 / 交互数量计算。没有操作列但估算列宽超出容器时,从右侧固定末 4 列,列数不足时降为 3、2、1 列。固定列使用不透明底色并保持表头层级;横向滚动条遵循 Ant Design 官方固定列表格行为,允许鼠标、触控板、触屏和键盘滚动,不隐藏滚动条。
- 列显隐只在已有列设置的表格中提供,统一使用 `ColumnSettings`(见 `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md`)。 - 列显隐只在已有列设置的表格中提供,统一使用 `ColumnSettings`(见 `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md`)。
- 三中心表头背景统一由 `center-table.css` 绘制:页面通过 `--center-table-head-bg` 提供色调,公共层在不透明的容器底色上叠加同色填充,普通列与固定列保持一致;页面不再直接覆盖表头 `background`。固定列使用 antd 6 的 `.ant-table-cell-fix` 与原生动态层级,不写死 `z-index`,不使用旧版 `fix-left` / `fix-right` 类名补丁;表头不换行,表头与正文沿用同一列宽和对齐方式。 - 三中心表头背景统一由 `center-table.css` 绘制:页面通过 `--center-table-head-bg` 提供色调,公共层在不透明的容器底色上叠加同色填充,普通列与固定列保持一致;页面不再直接覆盖表头 `background`。固定列使用 antd 6 的 `.ant-table-cell-fix` 与原生动态层级,不写死 `z-index`,不使用旧版 `fix-left` / `fix-right` 类名补丁;表头不换行,表头与正文沿用同一列宽和对齐方式。
@@ -160,7 +161,7 @@ html.dark .km-page {
| 状态 | 写法 | | 状态 | 写法 |
| --- | --- | | --- | --- |
| 加载 | `Table loading` | | 加载 | `Table loading` |
| 空数据 | `Empty image={Empty.PRESENTED_IMAGE_SIMPLE}`,文案沿用页面原有 | | 空数据 | 标准列表使用 `TableEmpty`(`ConsoleListTable` 默认接入):保留表头,简单插图 + “暂无数据”在当前可见宽度内居中;加载中不把空态当作查询结果,失败继续走错误提示 |
| 批量操作 | `rowSelection={{ selectedRowKeys, onChange }}`,未选中时批量按钮禁用 | | 批量操作 | `rowSelection={{ selectedRowKeys, onChange }}`,未选中时批量按钮禁用 |
## 6. 分页 ## 6. 分页
+29
View File
@@ -0,0 +1,29 @@
# UI 审查清单
> 状态:有效 · 更新:2026-11-19 · 版本:v1.0
**何时阅读**:执行双端 UI 审查、视觉回归与真实操作验收时。项目设置、全局基线与对应页面规范优先,本清单不定义新增功能。
## 速查
- 环境、登录、视口与像素阈值:`ui/GLOBAL_UI_BASELINE.md` 第 6、7 节。
- 组件与主题判定:`standards/UI_COMPONENT_STANDARDS.md` 与对应页面规范。
- 只勾选实际验证项;无此控件写“不适用”,权限、数据或环境不足写“未覆盖”并留证,不视为通过。
## 检查顺序
- [ ] **导航布局**:侧栏展开、折叠、层级、悬停、选中与图标;顶栏 Logo、搜索、通知、头像、主题、语言、环境标识;面包屑;多页签关闭、固定、右键、滚动与回到顶部。
- [ ] **全局视觉**:背景、渐变、蒙层与其他叠加;边距、栅格、对齐、响应折行;主题与语义色、透明度、深浅映射;字号、字重、行高、截断、等宽数字和脱敏;SVG 基线、线面、尺寸、间距、圆角、边框、分割线与阴影。
- [ ] **容器**:卡片头、主体与分区,标签页的选中态、下划线、胶囊与位置,折叠面板与分隔线。
- [ ] **数据区**:表头、单元格、固定列、斑马纹、空态、虚拟滚动、列设置、密度、批量、编辑和拖拽;分页条数、位置、跳转、总数;操作对齐、权限、折叠和危险态;下拉菜单分组、图标及禁用态;标签、徽标、头像、进度、描述、统计、时间线、步骤、结果、JSON、高亮、复制与二维码。
- [ ] **输入与筛选**:文本、数字、自动补全、搜索、富文本、代码、单复选、组合框、开关、分段、日期时间、级联、树、穿梭、上传、滑块和评分;尺寸、前后缀、清除、计数、下拉空态、多选标签、远程搜索及错误、只读、禁用;标签、必填、校验、栅格、查询重置、展开收起和条件计数。
- [ ] **操作按钮**:主、次、默认、虚线、文本、链接、图标、危险、幽灵、下拉、分裂;大小、形状、块级、图标间距、点击热区、加载和禁用;按钮组、长文案与多语言折行、工具栏及弹层主操作、权限隐藏和禁用提示;危险二次确认、防重入、键盘焦点、语义色及深浅映射。复用组件和 token。
- [ ] **浮层与反馈**:弹窗和抽屉的尺寸、位置、结构、遮罩、关闭与二次确认;提示与气泡的定位、箭头、背景、阴影和触发;警告、消息、通知、无权占位及关闭反馈。
- [ ] **图形**:图表、拓扑、流程的 Canvas、WebGL 或 SVG;容器、DPR、清晰度、坐标轴、网格、图例、标注、配色、提示和动画终态。
- [ ] **状态**:骨架、加载、空态、失败、禁用、校验、选中;文字与图标能传达状态,空态操作不越权。
- [ ] **交互**:悬停、键盘焦点、按压、展开收起、表单、弹层、搜索分页、主题语言、导航与多页签;过渡时长、缓动、关键帧、进出场与减少动态效果。真实 CRUD 按基线、创建、复查、编辑、复查、删除、复查执行。
## 记录口径
- 每项差异记录页面、组件、属性、期望、实际、严重级、截图与建议;只读、真实写入与模拟场景分别记账。
- 视觉证据注明主题、视口、DPR、语言、字体和数据模式;跨主题像素变化不等于缺陷,只有同条件基线比较可按视觉阈值判定。
+2 -2
View File
@@ -1,6 +1,6 @@
# 后台 UI 全局基线 # 后台 UI 全局基线
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v3.11 > 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-19 · 版本:v3.12
后台外壳与布局基线:顶栏、侧栏、公告、页头与内容边距、登录页,以及原型未定义场景、登录关卡与验收流程。主题与组件样式见 `UI_COMPONENT_STANDARDS.md`。 后台外壳与布局基线:顶栏、侧栏、公告、页头与内容边距、登录页,以及原型未定义场景、登录关卡与验收流程。主题与组件样式见 `UI_COMPONENT_STANDARDS.md`。
@@ -51,7 +51,7 @@
- 桌面高 72px、移动 56px,另含 1px 底部分隔线;背景、文字、分隔线跟随双主题变量。 - 桌面高 72px、移动 56px,另含 1px 底部分隔线;背景、文字、分隔线跟随双主题变量。
- 主导航:导航项撑满顶栏,左右内边距 24px;2px 主色下划线两端内缩 16px;选中项主色文字,普通项悬停保留正常文字色,键盘焦点可见。不改链接与权限条件。 - 主导航:导航项撑满顶栏,左右内边距 24px;2px 主色下划线两端内缩 16px;选中项主色文字,普通项悬停保留正常文字色,键盘焦点可见。不改链接与权限条件。
- 右侧按钮:主题、公告、语言等图标 16px,工具按钮点击区 34px,账户下拉箭头 10px;`.ui-header-actions` 内图标容器为 inline-flex,使图标与文字垂直居中。 - 右侧按钮:主题、公告、语言等图标 16px,按钮高度与工具按钮点击区 34px、文字行高 20px,账户头像 32px、下拉箭头 10px;`.ui-header-actions` 内链接、徽标和图标容器为 inline-flex,图标、文字、头像与分隔线垂直居中;桌面专属操作在 768px 以下隐藏。
- 全站共享顶栏不展示未登录用户的“登录 / 注册”按钮,桌面与移动端一致;已登录用户保留头像与账户菜单,登录 / 注册页面及受保护导航的原有鉴权跳转保持不变。 - 全站共享顶栏不展示未登录用户的“登录 / 注册”按钮,桌面与移动端一致;已登录用户保留头像与账户菜单,登录 / 注册页面及受保护导航的原有鉴权跳转保持不变。
- 主题按钮为 `Button` + `Tooltip`,点击在浅色与深色之间直接切换,不提供下拉或“跟随系统”;沿用现有主题 setter 与持久化,覆盖 `/org/login`、`/login` 与共享顶栏。 - 主题按钮为 `Button` + `Tooltip`,点击在浅色与深色之间直接切换,不提供下拉或“跟随系统”;沿用现有主题 setter 与持久化,覆盖 `/org/login`、`/login` 与共享顶栏。
- WeyAi 下载按钮复用现有下载配置与权限判定,跳转 `/weyai/download`;使用 antd text 按钮默认悬停背景与 `Tooltip`,不硬编码外部地址。 - WeyAi 下载按钮复用现有下载配置与权限判定,跳转 `/weyai/download`;使用 antd text 按钮默认悬停背景与 `Tooltip`,不硬编码外部地址。
+22 -9
View File
@@ -130,9 +130,11 @@ const ORG_USER_NAV_PATHS = {
keyManagement: ['/key-management', '/user-center/key-management'], keyManagement: ['/key-management', '/user-center/key-management'],
userCenter: ['/user-center'], userCenter: ['/user-center'],
}; };
const matchesPathPrefix = (pathname, prefix) =>
pathname === prefix || pathname.startsWith(`${prefix}/`);
const isOrgAllowedPath = (pathname, extraPrefixes = []) => const isOrgAllowedPath = (pathname, extraPrefixes = []) =>
[...ORG_ALLOWED_PREFIXES, ...extraPrefixes].some( [...ORG_ALLOWED_PREFIXES, ...extraPrefixes].some((prefix) =>
(p) => pathname === p || pathname.startsWith(p + '/'), matchesPathPrefix(pathname, prefix),
); );
// 模型超市旧路径 /pricing → /market。用组件而非静态 <Navigate>, // 模型超市旧路径 /pricing → /market。用组件而非静态 <Navigate>,
@@ -220,27 +222,38 @@ function App() {
// /org,从此无任何路径把平台技能加入企业技能库——技能库与分发页永远为空。 // /org,从此无任何路径把平台技能加入企业技能库——技能库与分发页永远为空。
// 顶栏开关的本意是收敛"员工浏览目录",不应连带阉割企业治理能力,故对 // 顶栏开关的本意是收敛"员工浏览目录",不应连带阉割企业治理能力,故对
// 管理员无条件放行该路由(页面内部仍按 skill_manage 决定是否出现启用按钮)。 // 管理员无条件放行该路由(页面内部仍按 skill_manage 决定是否出现启用按钮)。
if (isOrgAdmin && !prefixes.includes('/skill-market')) { if (
orgMembershipLoaded &&
isOrgAdmin &&
!prefixes.includes('/skill-market')
) {
prefixes.push('/skill-market'); prefixes.push('/skill-market');
} }
return prefixes; return prefixes;
}, [statusState?.status?.HeaderNavModulesOrgUser, isOrgAdmin]); }, [
statusState?.status?.HeaderNavModulesOrgUser,
orgMembershipLoaded,
isOrgAdmin,
]);
// 路由级封锁:org_only 员工访问非企业路由一律回到企业空间。 // 路由级封锁:org_only 员工访问非企业路由一律回到企业空间。
// 仅在企业中心可用时启用,避免企业中心被全局关闭时与其内部回退跳转形成重定向死循环。 // 仅在企业中心可用时启用,避免企业中心被全局关闭时与其内部回退跳转形成重定向死循环。
// 企业列表未到位前不做封锁判定:isOrgAdmin 首帧恒 false,此时若直接重定向, // 只有技能超市的企业管理员特例需要等待企业列表;等待时也不挂载受限页面。
// 硬刷新/收藏夹直达 /skill-market 的 org_only 管理员会在放行判据还没算出来时 const routePath = location.pathname.toLowerCase();
// 就被弹回 /org,而重定向不可逆——之后 isOrgAdmin 变 true 也回不去。
const orgConfined = const orgConfined =
userState?.user?.org_only_mode === true && userState?.user?.org_only_mode === true &&
orgMembershipLoaded &&
isOrgCenterAvailable && isOrgCenterAvailable &&
!isOrgAllowedPath(location.pathname, orgUserAllowedPrefixes); !isOrgAllowedPath(routePath, orgUserAllowedPrefixes);
if (orgConfined) { if (orgConfined) {
return ( return (
<SetupCheck> <SetupCheck>
{!orgMembershipLoaded &&
matchesPathPrefix(routePath, '/skill-market') ? (
<Loading />
) : (
<Navigate to='/org' replace /> <Navigate to='/org' replace />
)}
</SetupCheck> </SetupCheck>
); );
} }
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatPercent } from '../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import React, { useState } from 'react'; import React, { useState } from 'react';
@@ -118,7 +119,7 @@ const ChannelConsumption = ({ data, title, icon, t, embedded = false }) => {
width: 80, width: 80,
align: 'right', align: 'right',
render: (val) => ( render: (val) => (
<span className='text-gray-500'>{(val || 0).toFixed(1)}%</span> <span className='text-gray-500'>{formatPercent(val || 0, 1)}</span>
), ),
}, },
]; ];
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatUserReference } from '../../helpers/safeDisplay';
import React, { useMemo, useState } from 'react'; import React, { useMemo, useState } from 'react';
import { import {
@@ -113,7 +114,9 @@ const HighFreqLowCostUsers = ({
width: 160, width: 160,
render: (v, row) => ( render: (v, row) => (
<div className='flex flex-col'> <div className='flex flex-col'>
<Text strong>{v || row.username || `user_${row.user_id}`}</Text> <Text strong>
{formatUserReference(v || row.username, row.user_id, t('未知用户'))}
</Text>
{row.username && v && row.username !== v && ( {row.username && v && row.username !== v && (
<Text type='tertiary' size='small'> <Text type='tertiary' size='small'>
@{row.username} @{row.username}
@@ -21,6 +21,7 @@ import React, { useMemo } from 'react';
import { Card } from '@/components/ui'; import { Card } from '@/components/ui';
import { VChart } from '@visactor/react-vchart'; import { VChart } from '@visactor/react-vchart';
import { renderQuota } from '../../helpers'; import { renderQuota } from '../../helpers';
import { formatPercent } from '../../helpers/safeDisplay';
const ModelDistribution = ({ data, title, icon, t }) => { const ModelDistribution = ({ data, title, icon, t }) => {
const pieSpec = useMemo(() => { const pieSpec = useMemo(() => {
@@ -119,12 +120,12 @@ const ModelDistribution = ({ data, title, icon, t }) => {
<span className='text-xs text-gray-500 w-4'>{index + 1}</span> <span className='text-xs text-gray-500 w-4'>{index + 1}</span>
<span <span
className='text-sm flex-1 truncate' className='text-sm flex-1 truncate'
title={item.model_name} title={item.model_name || t('未知')}
> >
{item.model_name} {item.model_name || t('未知')}
</span> </span>
<span className='text-xs text-gray-500'> <span className='text-xs text-gray-500'>
{item.percent?.toFixed(1)}% {formatPercent(item.percent, 1)}
</span> </span>
</div> </div>
))} ))}
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatPercent } from '../../helpers/safeDisplay';
import React, { useState, useCallback } from 'react'; import React, { useState, useCallback } from 'react';
import { Badge, Empty, Progress, Skeleton, Tag, Tooltip, theme } from 'antd'; import { Badge, Empty, Progress, Skeleton, Tag, Tooltip, theme } from 'antd';
import { ArrowDown } from 'lucide-react'; import { ArrowDown } from 'lucide-react';
@@ -275,7 +276,7 @@ const OrgRealtimeUsage = ({
className='text-sm font-semibold group-hover:underline' className='text-sm font-semibold group-hover:underline'
style={{ color: cacheRateColor(rate, token) }} style={{ color: cacheRateColor(rate, token) }}
> >
{rate.toFixed(1)}% {formatPercent(rate, 1)}
</span> </span>
<span <span
aria-hidden aria-hidden
+2 -1
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatPercent } from '../../helpers/safeDisplay';
import React from 'react'; import React from 'react';
import { Card } from '@/components/ui'; import { Card } from '@/components/ui';
@@ -117,7 +118,7 @@ const OverviewCards = ({ overview, loading = false, t }) => {
)} )}
<span> <span>
{isPositive ? '+' : ''} {isPositive ? '+' : ''}
{change.toFixed(1)}% {formatPercent(change, 1)}
</span> </span>
</div> </div>
); );
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatUserReference } from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import React, { useState } from 'react'; import React, { useState } from 'react';
@@ -246,7 +247,9 @@ const RiskControlBanLogs = ({
<div> <div>
<Text type='tertiary'>{t('用户:')}</Text> <Text type='tertiary'>{t('用户:')}</Text>
<Text strong> <Text strong>
{unbanRow.user_snapshot || `user_${unbanRow.user_id}`}(ID: {unbanRow.user_snapshot ||
formatUserReference('', unbanRow.user_id, t('未知用户'))}
(ID:
{unbanRow.user_id}) {unbanRow.user_id})
</Text> </Text>
</div> </div>
+7 -2
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatUserReference } from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
@@ -104,9 +105,13 @@ const UserRanking = ({ data, title, icon, t }) => {
<div className='flex items-center justify-between'> <div className='flex items-center justify-between'>
<span <span
className='text-sm font-medium truncate' className='text-sm font-medium truncate'
title={`${item.display_name || item.username || 'User'} (ID: ${item.user_id})`} title={`${formatUserReference(item.display_name || item.username, item.user_id, t('未知用户'))}`}
> >
{item.display_name || item.username || `User ${item.user_id}`} {formatUserReference(
item.display_name || item.username,
item.user_id,
t('未知用户'),
)}
<span className='text-xs text-gray-400 ml-1'> <span className='text-xs text-gray-400 ml-1'>
#{item.user_id} #{item.user_id}
</span> </span>
+3 -2
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatPercent } from '../../helpers/safeDisplay';
import React, { useMemo, useState, useEffect, useCallback } from 'react'; import React, { useMemo, useState, useEffect, useCallback } from 'react';
import { Card, Spin, Tag, Progress } from '@/components/ui'; import { Card, Spin, Tag, Progress } from '@/components/ui';
@@ -130,7 +131,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
}, },
{ {
key: () => t('占比'), key: () => t('占比'),
value: (datum) => `${(datum?.percentage || 0).toFixed(1)}%`, value: (datum) => formatPercent(datum?.percentage || 0, 1),
}, },
], ],
}, },
@@ -186,7 +187,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
}, },
{ {
key: () => t('占比'), key: () => t('占比'),
value: (datum) => `${(datum?.percentage || 0).toFixed(1)}%`, value: (datum) => formatPercent(datum?.percentage || 0, 1),
}, },
], ],
}, },
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatUserReference } from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
@@ -80,9 +81,9 @@ const UserTopupRanking = ({ data, title, icon, t, embedded = false }) => {
<div className='flex flex-col'> <div className='flex flex-col'>
<span <span
className='font-medium text-sm truncate' className='font-medium text-sm truncate'
title={text || `User ${record.user_id}`} title={formatUserReference(text, record.user_id, t('未知用户'))}
> >
{text || `User ${record.user_id}`} {formatUserReference(text, record.user_id, t('未知用户'))}
</span> </span>
<span className='text-xs text-gray-400 truncate'> <span className='text-xs text-gray-400 truncate'>
{I18N_TECHNICAL_TEXT.ID} {record.user_id} {I18N_TECHNICAL_TEXT.ID} {record.user_id}
@@ -30,6 +30,7 @@ import {
} from '@/components/ui'; } from '@/components/ui';
import { ClipboardList } from 'lucide-react'; import { ClipboardList } from 'lucide-react';
import { ChangeText, OrgNameCell, ReasonTags, SectionCard } from './shared'; import { ChangeText, OrgNameCell, ReasonTags, SectionCard } from './shared';
import { formatRatioPercent } from '../../../helpers/safeDisplay';
import { import {
daysSince, daysSince,
downloadCsv, downloadCsv,
@@ -284,7 +285,11 @@ const columnsFor = (tab, cny, t, atRisk) => {
{v}/{r.member_count} {v}/{r.member_count}
{r.member_count > 0 ? ( {r.member_count > 0 ? (
<span className='text-xs text-gray-400 ml-1'> <span className='text-xs text-gray-400 ml-1'>
{Math.min(100, (v / r.member_count) * 100).toFixed(0)}% {formatRatioPercent(
Math.min(100, Number(v) || 0),
r.member_count,
0,
)}
</span> </span>
) : null} ) : null}
</span> </span>
@@ -31,6 +31,10 @@ import {
} from 'lucide-react'; } from 'lucide-react';
import { ChangeText, KpiCard, SectionCard } from './shared'; import { ChangeText, KpiCard, SectionCard } from './shared';
import { formatCny, formatCst, pct, SEGMENTS } from './utils'; import { formatCny, formatCst, pct, SEGMENTS } from './utils';
import {
formatPercent,
formatRatioPercent,
} from '../../../helpers/safeDisplay';
// ─── 报表抬头:统计口径 + 数据状态 ───────────────────────────────── // ─── 报表抬头:统计口径 + 数据状态 ─────────────────────────────────
export const ReportHeader = ({ report, onExport, t }) => { export const ReportHeader = ({ report, onExport, t }) => {
@@ -209,7 +213,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => {
n: (k.active_orgs || 0).toLocaleString(), n: (k.active_orgs || 0).toLocaleString(),
count: k.active_orgs || 0, count: k.active_orgs || 0,
}), }),
sub: `${t('活跃率')} ${pct(k.active_orgs, servingOrgs).toFixed(1)}% · ${t('新增')} ${k.new_orgs || 0}`, sub: `${t('活跃率')} ${formatRatioPercent(k.active_orgs, servingOrgs)} · ${t('新增')} ${k.new_orgs || 0}`,
compare: ( compare: (
<ChangeText cur={k.active_orgs} prev={k.prev_active_orgs} t={t} /> <ChangeText cur={k.active_orgs} prev={k.prev_active_orgs} t={t} />
), ),
@@ -229,7 +233,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => {
n: (k.active_members || 0).toLocaleString(), n: (k.active_members || 0).toLocaleString(),
count: k.active_members || 0, count: k.active_members || 0,
}), }),
sub: `${t('渗透率')} ${Math.min(100, pct(k.active_members, k.total_members)).toFixed(1)}% · ${t('成员')} ${(k.total_members || 0).toLocaleString()}`, sub: `${t('渗透率')} ${formatPercent(Math.min(100, pct(k.active_members, k.total_members)))} · ${t('成员')} ${(k.total_members || 0).toLocaleString()}`,
tip: t('本期通过企业密钥产生调用的去重成员数(按自然日统计)'), tip: t('本期通过企业密钥产生调用的去重成员数(按自然日统计)'),
onClick: () => onJump('growth'), onClick: () => onJump('growth'),
}, },
@@ -277,7 +281,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => {
}, },
{ {
title: t('企业消耗占平台'), title: t('企业消耗占平台'),
value: `${share.toFixed(1)}%`, value: formatPercent(share),
sub: `${t('个人消耗')} ${formatCny(k.personal_quota, cny)}`, sub: `${t('个人消耗')} ${formatCny(k.personal_quota, cny)}`,
compare: compare:
shareDelta === null ? null : ( shareDelta === null ? null : (
@@ -341,7 +345,7 @@ export const HealthSegments = ({ report, cny, activeSegment, onSelect, t }) => {
{t(meta.label)} {t(meta.label)}
</Tag> </Tag>
<span className='text-xs text-gray-400 tabular-nums'> <span className='text-xs text-gray-400 tabular-nums'>
{pct(s.count, totalCount).toFixed(0)}% {formatPercent(pct(s.count, totalCount), 0)}
</span> </span>
</div> </div>
<div className='mt-2 text-lg font-bold text-gray-800 dark:text-gray-100 tabular-nums'> <div className='mt-2 text-lg font-bold text-gray-800 dark:text-gray-100 tabular-nums'>
@@ -30,6 +30,7 @@ import {
} from '@/components/ui'; } from '@/components/ui';
import { Search, Table2, UserCog } from 'lucide-react'; import { Search, Table2, UserCog } from 'lucide-react';
import { ChangeText, OrgNameCell, SectionCard } from './shared'; import { ChangeText, OrgNameCell, SectionCard } from './shared';
import { formatPercent } from '../../../helpers/safeDisplay';
import { import {
ALERT_LEVELS, ALERT_LEVELS,
ORG_STATUS, ORG_STATUS,
@@ -266,7 +267,7 @@ export const OrgDetailTable = ({ report, filter, setFilter, cny, t }) => {
align: 'right', align: 'right',
render: (v) => render: (v) =>
v > 0 ? ( v > 0 ? (
<span className='tabular-nums'>{v.toFixed(1)}%</span> <span className='tabular-nums'>{formatPercent(v, 1)}</span>
) : ( ) : (
<Text type='tertiary'>—</Text> <Text type='tertiary'>—</Text>
), ),
@@ -501,8 +502,8 @@ export const exportOrgDetail = (rows, cny, t) => {
SEGMENTS[o.segment] ? t(SEGMENTS[o.segment].label) : '', SEGMENTS[o.segment] ? t(SEGMENTS[o.segment].label) : '',
yuan(o.quota), yuan(o.quota),
yuan(o.prev_quota), yuan(o.prev_quota),
rate === null ? '' : `${rate.toFixed(1)}%`, rate === null ? '' : formatPercent(rate, 1),
o.share ? `${o.share.toFixed(2)}%` : '', o.share ? formatPercent(o.share, 2) : '',
o.requests, o.requests,
o.active_members, o.active_members,
o.member_count, o.member_count,
@@ -21,6 +21,7 @@ import React from 'react';
import { Card, Tag, Tooltip } from '@/components/ui'; import { Card, Tag, Tooltip } from '@/components/ui';
import { TrendingDown, TrendingUp } from 'lucide-react'; import { TrendingDown, TrendingUp } from 'lucide-react';
import { changeRate, ORG_STATUS, orgDisplayName, REASONS } from './utils'; import { changeRate, ORG_STATUS, orgDisplayName, REASONS } from './utils';
import { formatPercent } from '../../../helpers/safeDisplay';
export const SectionCard = ({ export const SectionCard = ({
id, id,
@@ -90,7 +91,7 @@ export const ChangeText = ({ cur, prev, t, size = 'xs', showNew = true }) => {
<TrendingDown className='w-3 h-3' /> <TrendingDown className='w-3 h-3' />
)} )}
{up ? '+' : ''} {up ? '+' : ''}
{rate.toFixed(1)}% {formatPercent(rate, 1)}
</span> </span>
); );
}; };
+17 -5
View File
@@ -16,6 +16,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../../helpers/safeDisplay';
import { formatPercent } from '../../../helpers/safeDisplay';
// 企业经营决策报表:口径常量、行动清单派生、要点生成、CSV 导出 // 企业经营决策报表:口径常量、行动清单派生、要点生成、CSV 导出
@@ -52,7 +54,15 @@ export const formatRate = (rate) =>
? '—' ? '—'
: `${rate >= 0 ? '+' : ''}${rate.toFixed(1)}%`; : `${rate >= 0 ? '+' : ''}${rate.toFixed(1)}%`;
export const pct = (part, total) => (total > 0 ? (part / total) * 100 : 0); export const pct = (part, total) => {
const numerator = Number(part);
const denominator = Number(total);
return Number.isFinite(numerator) &&
Number.isFinite(denominator) &&
denominator > 0
? (numerator / denominator) * 100
: 0;
};
// ─── 时间(报表口径统一为 UTC+8,与浏览器时区无关) ───────────────── // ─── 时间(报表口径统一为 UTC+8,与浏览器时区无关) ─────────────────
const pad = (n) => String(n).padStart(2, '0'); const pad = (n) => String(n).padStart(2, '0');
@@ -405,11 +415,11 @@ export const deriveFindings = (report, lists, cny, t) => {
? t( ? t(
'头部依赖较高:Top5 企业贡献 {{share}} 的企业消耗,需关注大客户稳定性', '头部依赖较高:Top5 企业贡献 {{share}} 的企业消耗,需关注大客户稳定性',
{ {
share: `${k.top5_share.toFixed(1)}%`, share: formatPercent(k.top5_share, 1),
}, },
) )
: t('客户结构较分散:Top5 企业贡献 {{share}} 的企业消耗', { : t('客户结构较分散:Top5 企业贡献 {{share}} 的企业消耗', {
share: `${k.top5_share.toFixed(1)}%`, share: formatPercent(k.top5_share, 1),
}), }),
target: 'tiers', target: 'tiers',
}); });
@@ -426,7 +436,7 @@ export const deriveFindings = (report, lists, cny, t) => {
text: t( text: t(
'企业成员渗透率 {{rate}},{{count}} 家企业成员活跃率低于 30%,存在增量空间', '企业成员渗透率 {{rate}},{{count}} 家企业成员活跃率低于 30%,存在增量空间',
{ {
rate: `${Math.min(100, penetration).toFixed(1)}%`, rate: formatPercent(Math.min(100, penetration), 1),
count: lowPen, count: lowPen,
}, },
), ),
@@ -467,4 +477,6 @@ export const downloadCsv = (filename, headers, rows) => {
}; };
export const orgDisplayName = (o, t) => export const orgDisplayName = (o, t) =>
o.deleted ? `${t('已删除企业')} #${o.org_id}` : o.name || `#${o.org_id}`; o.deleted
? `${t('已删除企业')} ${formatIdReference(o.org_id)}`
: o.name || formatIdReference(o.org_id);
+9 -2
View File
@@ -19,8 +19,9 @@ For commercial licensing, please contact support@quantumnous.com
import React from 'react'; import React from 'react';
import { Button } from 'antd'; import { Button } from 'antd';
import { useNavigate } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { isSafePostLoginRedirect } from '../../helpers/data';
/** /**
* 认证页「个人 / 企业」分段切换控件(登录与注册两种模式)。 * 认证页「个人 / 企业」分段切换控件(登录与注册两种模式)。
@@ -34,6 +35,12 @@ import { useTranslation } from 'react-i18next';
const AuthLoginTabs = ({ active = 'personal', mode = 'login' }) => { const AuthLoginTabs = ({ active = 'personal', mode = 'login' }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate(); const navigate = useNavigate();
const [searchParams] = useSearchParams();
const redirect = searchParams.get('redirect');
const loginSearch =
mode === 'login' && isSafePostLoginRedirect(redirect)
? `?${new URLSearchParams({ redirect })}`
: '';
// 企业入口置于左侧首位:本产品主推企业用户,企业登录/注册是默认入口 // 企业入口置于左侧首位:本产品主推企业用户,企业登录/注册是默认入口
const tabs = const tabs =
@@ -57,7 +64,7 @@ const AuthLoginTabs = ({ active = 'personal', mode = 'login' }) => {
type={isActive ? 'primary' : 'text'} type={isActive ? 'primary' : 'text'}
aria-pressed={isActive} aria-pressed={isActive}
onClick={() => { onClick={() => {
if (!isActive) navigate(tab.to); if (!isActive) navigate(`${tab.to}${loginSearch}`);
}} }}
className='flex-1 font-medium' className='flex-1 font-medium'
> >
+12 -7
View File
@@ -220,12 +220,17 @@ const LoginForm = () => {
}; };
}, []); }, []);
useEffect(() => {
const redirect = searchParams.get('redirect'); const redirect = searchParams.get('redirect');
if (redirect) { useEffect(() => {
savePostLoginRedirect(redirect); savePostLoginRedirect(redirect);
} }, [redirect]);
if (searchParams.get('expired')) {
const expiryShown = useRef(false);
useEffect(() => {
if (!searchParams.get('expired')) {
expiryShown.current = false;
} else if (!expiryShown.current) {
expiryShown.current = true;
showError(t('未登录或登录已过期,请重新登录')); showError(t('未登录或登录已过期,请重新登录'));
const nextParams = new URLSearchParams(searchParams); const nextParams = new URLSearchParams(searchParams);
nextParams.delete('expired'); nextParams.delete('expired');
@@ -234,15 +239,15 @@ const LoginForm = () => {
}, [searchParams, setSearchParams, t]); }, [searchParams, setSearchParams, t]);
const finishLogin = useCallback( const finishLogin = useCallback(
(data, successMessage) => (data) =>
runLoginFlow({ runLoginFlow({
data, data,
userDispatch, userDispatch,
navigate, navigate,
t, t,
successMessage, redirect,
}), }),
[navigate, t, userDispatch], [navigate, redirect, t, userDispatch],
); );
const onWeChatLoginClicked = () => { const onWeChatLoginClicked = () => {
+1 -2
View File
@@ -17,7 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { API, showError, showSuccess } from '../../helpers'; import { API, showError } from '../../helpers';
import { Button, Card, Divider, Form, Typography } from '@/components/ui'; import { Button, Card, Divider, Form, Typography } from '@/components/ui';
import React, { useState } from 'react'; import React, { useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@@ -51,7 +51,6 @@ const TwoFAVerification = ({ onSuccess, onBack, isModal = false }) => {
}); });
if (res.data.success) { if (res.data.success) {
showSuccess(t('登录成功'));
if (onSuccess) { if (onSuccess) {
onSuccess(res.data.data); onSuccess(res.data.data);
} }
@@ -18,9 +18,41 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React from 'react'; import React from 'react';
import { Button, Dropdown } from 'antd';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { ChevronDown } from '../icons/ActionIcons';
import './table-toolbar.css'; import './table-toolbar.css';
export function TableRowActions({ children, items = [] }) {
const { t } = useTranslation();
const menuItems = items.filter(Boolean);
if (!children && !menuItems.length) return null;
return (
<div className='table-row-actions'>
{children}
{menuItems.length > 0 && (
<Dropdown
autoFocus
trigger={['click']}
placement='bottomRight'
menu={{ items: menuItems }}
>
<Button
type='link'
size='small'
icon={<ChevronDown size={14} aria-hidden />}
iconPlacement='end'
aria-haspopup='menu'
>
{t('更多')}
</Button>
</Dropdown>
)}
</div>
);
}
export function TableTitle({ children }) { export function TableTitle({ children }) {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
@@ -1,3 +1,10 @@
.table-row-actions {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.table-toolbar { .table-toolbar {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -118,6 +118,28 @@ export function ConsoleSearchActions({
); );
} }
export function ConsoleFilterGrid({ children, onReset, onSearch, loading }) {
return (
<div className='console-filter-panel'>
<div className='console-filter-grid'>{children}</div>
<ConsoleSearchActions
onReset={onReset}
onSearch={onSearch}
loading={loading}
/>
</div>
);
}
export function ConsoleFilterField({ label, id, children }) {
return (
<div className='console-filter-field'>
<label htmlFor={id}>{label}</label>
{children}
</div>
);
}
export const ConsoleForm = forwardRef(function ConsoleForm( export const ConsoleForm = forwardRef(function ConsoleForm(
{ className, layout = 'vertical', ...props }, { className, layout = 'vertical', ...props },
ref, ref,
@@ -167,6 +189,16 @@ export function ConsoleTabs({ className, ...props }) {
return <Tabs {...props} className={classes('console-tabs', className)} />; return <Tabs {...props} className={classes('console-tabs', className)} />;
} }
export function ConsoleListTable({ locale, ...props }) {
return (
<ConsoleTable
{...props}
className={classes('console-list-table', props.className)}
locale={{ emptyText: <TableEmpty />, ...locale }}
/>
);
}
const isFooterButton = (node) => const isFooterButton = (node) =>
React.isValidElement(node) && React.isValidElement(node) &&
(node.type === Button || node.type?.render?.name === 'Button'); (node.type === Button || node.type?.render?.name === 'Button');
+61
View File
@@ -233,6 +233,67 @@
gap: var(--console-space-1); gap: var(--console-space-1);
margin-inline-start: auto; margin-inline-start: auto;
} }
.console-filter-panel {
width: 100%;
}
.console-page .console-search-card .console-filter-panel.ant-form {
display: block;
}
.console-filter-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 1rem;
width: 100%;
}
.console-filter-field {
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
}
.console-filter-field > label,
.console-page .console-filter-grid .ant-form-item-label > label {
color: var(--console-muted);
font-size: 13px;
}
.console-filter-field > :is(.ant-input-number, .ant-picker) {
width: 100%;
}
.console-filter-panel .console-search-actions {
margin-top: 1rem;
}
.console-table.console-list-table .ant-table-thead > tr > th {
height: 46px;
padding-block: 0;
font-weight: 400;
}
.console-list-tools,
.console-list-quick-filters,
.console-list-tool-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.console-list-tools {
width: 100%;
gap: 12px 20px;
justify-content: space-between;
}
.console-list-tool-actions {
justify-content: flex-end;
margin-inline-start: auto;
}
@media (max-width: 1100px) {
.console-filter-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 768px) {
.console-filter-grid {
grid-template-columns: minmax(0, 1fr);
}
}
.console-page .console-table .ant-table-thead > tr > th { .console-page .console-table .ant-table-thead > tr > th {
--center-table-head-bg: var(--console-fill); --center-table-head-bg: var(--console-fill);
color: var(--console-muted); color: var(--console-muted);
+10 -1
View File
@@ -198,12 +198,20 @@ const PageLayout = () => {
return; return;
} }
const sessionAPI = API;
const isCurrentSession = () => {
const currentUser = getUserData();
return (
sessionAPI === API && currentUser?.id === cachedUser.id && !!currentUser
);
};
userDispatch({ type: 'auth_start' }); userDispatch({ type: 'auth_start' });
try { try {
const res = await API.get('/api/user/self', { const res = await sessionAPI.get('/api/user/self', {
skipErrorHandler: true, skipErrorHandler: true,
disableDuplicate: true, disableDuplicate: true,
}); });
if (!isCurrentSession()) return;
const { success, data } = res.data; const { success, data } = res.data;
if (success && data) { if (success && data) {
setUserData(data); setUserData(data);
@@ -213,6 +221,7 @@ const PageLayout = () => {
userDispatch({ type: 'logout' }); userDispatch({ type: 'logout' });
} }
} catch (error) { } catch (error) {
if (!isCurrentSession()) return;
if (error?.response?.status === 401 || error?.response?.status === 403) { if (error?.response?.status === 401 || error?.response?.status === 403) {
clearUserData(); clearUserData();
userDispatch({ type: 'logout' }); userDispatch({ type: 'logout' });
@@ -146,7 +146,10 @@ const ActionButtons = ({
<div className='ui-header-actions flex items-center shrink-0'> <div className='ui-header-actions flex items-center shrink-0'>
{/* Tutorial Button - 新手教程按钮 (桌面端显示) */} {/* Tutorial Button - 新手教程按钮 (桌面端显示) */}
{isLoggedIn && isButtonVisible('tutorial') && ( {isLoggedIn && isButtonVisible('tutorial') && (
<Link to='/tutorial' className='hidden sm:block'> <Link
to='/tutorial'
className='ui-header-action-link ui-header-desktop-action'
>
<AntButton icon={actionIcon(BookOpen)}> <AntButton icon={actionIcon(BookOpen)}>
{!isMobile && t('新手教程')} {!isMobile && t('新手教程')}
</AntButton> </AntButton>
@@ -157,7 +160,7 @@ const ActionButtons = ({
{isLoggedIn && isButtonVisible('pricing') && ( {isLoggedIn && isButtonVisible('pricing') && (
<AntButton <AntButton
icon={actionIcon(Share2)} icon={actionIcon(Share2)}
className='hidden sm:!inline-flex' className='ui-header-desktop-action'
onClick={() => setPromotionVisible(true)} onClick={() => setPromotionVisible(true)}
> >
{!isMobile && t('推广')} {!isMobile && t('推广')}
@@ -169,7 +172,7 @@ const ActionButtons = ({
<Tooltip title={t('下载 WeyAi')}> <Tooltip title={t('下载 WeyAi')}>
<Link <Link
to='/weyai/download' to='/weyai/download'
className='hidden sm:block' className='ui-header-action-link ui-header-desktop-action'
aria-label={t('下载 WeyAi 桌面端')} aria-label={t('下载 WeyAi 桌面端')}
> >
<AntButton <AntButton
@@ -185,7 +188,7 @@ const ActionButtons = ({
{/* Recharge Button - 充值按钮 */} {/* Recharge Button - 充值按钮 */}
{isButtonVisible('recharge') && !isMiniProgramWebView() && ( {isButtonVisible('recharge') && !isMiniProgramWebView() && (
<Link to='/recharge'> <Link to='/recharge' className='ui-header-action-link'>
<AntButton <AntButton
icon={actionIcon(Wallet)} icon={actionIcon(Wallet)}
aria-label={isMobile ? t('充值') : undefined} aria-label={isMobile ? t('充值') : undefined}
+199 -385
View File
@@ -19,7 +19,6 @@ For commercial licensing, please contact support@quantumnous.com
import { import {
Copy as ActionCopy, Copy as ActionCopy,
CheckCircle as ActionCheckCircle,
Download as ActionDownload, Download as ActionDownload,
} from '@/components/common/icons/ActionIcons'; } from '@/components/common/icons/ActionIcons';
import React, { useState, useEffect, useRef, useCallback } from 'react'; import React, { useState, useEffect, useRef, useCallback } from 'react';
@@ -30,26 +29,17 @@ import {
Button, Button,
Typography, Typography,
Tabs, Tabs,
TabPane,
Input, Input,
Tag, Alert,
} from '@/components/ui'; Skeleton,
Radio,
} from 'antd';
import { QRCodeCanvas } from 'qrcode.react'; import { QRCodeCanvas } from 'qrcode.react';
import { import { Smartphone, Monitor, Gift, Users, ChevronRight } from 'lucide-react';
Share2, import './promotion-poster.css';
Smartphone,
Monitor,
Gift,
Users,
Sparkles,
ChevronRight,
CheckCircle,
Coins,
TrendingUp,
} from 'lucide-react';
import { API, showError, showSuccess, copy } from '../../helpers'; import { API, showError, showSuccess, copy } from '../../helpers';
const { Text } = Typography; const { Text, Title, Paragraph } = Typography;
// 默认海报模板配置 // 默认海报模板配置
const DEFAULT_TEMPLATES = [ const DEFAULT_TEMPLATES = [
@@ -311,409 +301,233 @@ const PromotionPosterModal = ({ visible, onClose }) => {
copyWithFeedback(affCode, t('邀请码')); copyWithFeedback(affCode, t('邀请码'));
}; };
// 链接分享模式 - PC友好
const renderLinkMode = () => ( const renderLinkMode = () => (
<div className='flex flex-col items-center w-full'> <div className='pm-link-layout'>
{/* 分享卡片 */} <section className='pm-invitation-card'>
<div <div className='pm-eyebrow'>{t('推广分享')}</div>
className='w-full rounded-2xl p-6 mb-6 relative overflow-hidden' <Title level={4}>{systemName}</Title>
style={{ background: selectedTemplate.bgGradient }} <Paragraph type='secondary'>
>
{/* 装饰元素 */}
<div className='absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full -translate-y-1/2 translate-x-1/2' />
<div className='absolute bottom-0 left-0 w-24 h-24 bg-white/10 rounded-full translate-y-1/2 -translate-x-1/2' />
<div className='absolute top-1/2 right-4 w-16 h-16 bg-white/5 rounded-full' />
<div className='relative z-10'>
{/* 平台信息 */}
<div className='flex items-center gap-3 mb-4'>
<div className='w-12 h-12 bg-white/20 backdrop-blur-sm rounded-xl flex items-center justify-center shadow-lg'>
<Sparkles size={24} className='text-white' />
</div>
<div>
<h3 className='text-white font-bold text-lg drop-shadow-sm'>
{systemName}
</h3>
<p className='text-white/80 text-sm'>
{posterConfig?.slogan || t('邀请好友,共享AI')} {posterConfig?.slogan || t('邀请好友,共享AI')}
</p> </Paragraph>
</div> <div className='pm-qrcode'>
</div>
{/* 福利说明 */}
<div className='flex gap-4 mb-5'>
<div className='flex items-center gap-2 text-white/90 text-sm bg-white/10 backdrop-blur-sm px-3 py-1.5 rounded-full'>
<Gift size={14} />
<span>{t('注册即送额度')}</span>
</div>
<div className='flex items-center gap-2 text-white/90 text-sm bg-white/10 backdrop-blur-sm px-3 py-1.5 rounded-full'>
<Users size={14} />
<span>{t('消费返佣')}</span>
</div>
</div>
{/* 二维码(小尺寸) */}
<div className='flex items-center gap-4'>
<div className='bg-white rounded-xl p-2.5 shadow-xl'>
<QRCodeCanvas <QRCodeCanvas
id='link-mode-qrcode' id='link-mode-qrcode'
value={affLink || 'https://example.com'}
size={80}
level='M'
includeMargin={false}
/>
</div>
<div className='flex-1'>
<p className='text-white/70 text-xs mb-1'>{t('手机扫码注册')}</p>
<p className='text-white font-mono text-sm'>
{t('邀请码')}:{' '}
<span className='font-bold bg-white/20 px-2 py-0.5 rounded'>
{affCode}
</span>
</p>
</div>
</div>
</div>
</div>
{/* 链接输入框 */}
<div className='w-full mb-4'>
<Text className='text-sm text-gray-500 dark:text-gray-400 mb-2 block font-medium'>
{t('邀请链接')}
</Text>
<div className='relative group'>
<div className='absolute -inset-0.5 bg-gradient-to-r from-brand-from/30 to-brand-to/30 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 blur-sm' />
<Input
value={affLink} value={affLink}
readOnly size={144}
size='large' level='M'
className='!rounded-xl' marginSize={2}
suffix={ />
</div>
<Text type='secondary'>{t('手机扫码注册')}</Text>
<div className='pm-benefits'>
<span>
<Gift size={14} aria-hidden />
{t('注册即送额度')}
</span>
<span>
<Users size={14} aria-hidden />
{t('消费返佣')}
</span>
</div>
</section>
<section className='pm-share-details'>
<div className='pm-field'>
<label htmlFor='promotion-link'>{t('邀请链接')}</label>
<Input id='promotion-link' value={affLink} readOnly size='large' />
<Button <Button
theme='solid'
type='primary' type='primary'
size='small' icon={<ActionCopy size={16} aria-hidden />}
icon={<ActionCopy size={14} />}
onClick={handleCopyLink} onClick={handleCopyLink}
className='!bg-gradient-to-r !from-brand-from !to-brand-to !border-0 !rounded-lg'
>
{t('复制')}
</Button>
}
/>
</div>
</div>
{/* 邀请码 */}
<div className='w-full mb-4'>
<Text className='text-sm text-gray-500 dark:text-gray-400 mb-2 block font-medium'>
{t('邀请码')}
</Text>
<div className='flex items-center gap-3'>
<div className='relative'>
<div className='absolute -inset-1 bg-gradient-to-r from-blue-500/20 to-brand-to/20 rounded-lg blur-sm' />
<Tag
size='large'
color='blue'
className='!text-lg !px-5 !py-2.5 !rounded-xl !font-bold relative'
>
{affCode}
</Tag>
</div>
<Button
theme='light'
type='tertiary'
icon={<ActionCopy size={14} />}
onClick={handleCopyCode}
className='!rounded-lg'
>
{t('复制')}
</Button>
</div>
</div>
{/* 使用说明 */}
<div className='w-full p-4 bg-gradient-to-r from-blue-50 to-brand-to/5 dark:from-blue-900/20 dark:to-brand-to/20 rounded-xl border border-blue-100 dark:border-blue-800/30'>
<div className='flex items-start gap-2'>
<CheckCircle
size={16}
className='text-blue-500 mt-0.5 flex-shrink-0'
/>
<Text className='text-sm text-blue-700 dark:text-blue-300'>
{t(
'将链接发送给好友,好友点击即可注册。支持微信、QQ、邮件等任意方式分享。',
)}
</Text>
</div>
</div>
</div>
);
// 海报模式 - 移动端友好
const renderPosterMode = () => (
<div className='flex flex-col items-center'>
{/* 模板选择 */}
<div className='w-full mb-4'>
<Text className='text-sm text-gray-500 dark:text-gray-400 mb-2 block font-medium'>
{t('选择模板')}
</Text>
<div className='flex gap-3 flex-wrap'>
{DEFAULT_TEMPLATES.map((template) => (
<button
key={template.id}
onClick={() => setSelectedTemplate(template)}
className={[
'app-action-button',
`relative w-14 h-14 rounded-xl border-2 transition-all duration-300 overflow-hidden ${
selectedTemplate.id === template.id
? 'border-brand scale-110 shadow-lg shadow-brand/30'
: 'border-transparent hover:border-gray-300 hover:scale-105'
}`,
]
.filter(Boolean)
.join(' ')}
style={{ background: template.bgGradient }}
title={t(template.name)}
>
{selectedTemplate.id === template.id && (
<div className='absolute inset-0 flex items-center justify-center bg-black/20'>
<ActionCheckCircle size={20} className='text-white' />
</div>
)}
</button>
))}
</div>
</div>
{/* 海报预览 */}
<div
className='relative rounded-2xl overflow-hidden shadow-2xl'
style={{
width: 280,
height: 497,
background: selectedTemplate.bgGradient,
}}
>
{/* 装饰元素 */}
<div className='absolute top-0 right-0 w-24 h-24 bg-white/10 rounded-full -translate-y-1/2 translate-x-1/2' />
<div className='absolute bottom-20 left-0 w-16 h-16 bg-white/10 rounded-full -translate-x-1/2' />
<div className='absolute inset-0 flex flex-col items-center pt-10 px-5'>
<h2
className='text-xl font-bold mb-2 text-center drop-shadow-sm'
style={{ color: selectedTemplate.textColor }}
>
{posterConfig?.slogan || t('邀请好友,共享AI')}
</h2>
<p
className='text-xs mb-5 opacity-90'
style={{ color: selectedTemplate.textColor }}
>
{posterConfig?.sub_slogan || t('注册即可获得免费额度')}
</p>
<h3
className='text-lg font-bold mb-6 drop-shadow-sm'
style={{ color: selectedTemplate.textColor }}
>
{systemName}
</h3>
<div className='bg-white rounded-xl p-3 shadow-2xl'>
<QRCodeCanvas
id='poster-qrcode'
value={affLink || 'https://example.com'}
size={130}
level='H'
includeMargin={false}
/>
</div>
<p
className='text-xs mt-3 opacity-90'
style={{ color: selectedTemplate.textColor }}
>
{t('扫码注册')}
</p>
<div
className='mt-2 px-4 py-1.5 rounded-full'
style={{ backgroundColor: 'rgba(255,255,255,0.2)' }}
>
<p
className='text-sm font-bold'
style={{ color: selectedTemplate.textColor }}
>
{t('邀请码')}: {affCode}
</p>
</div>
<div className='absolute bottom-6 left-0 right-0 text-center'>
<div
className='h-px mx-6 mb-3 opacity-30'
style={{ backgroundColor: selectedTemplate.textColor }}
/>
<p
className='text-xs opacity-80'
style={{ color: selectedTemplate.textColor }}
>
{posterConfig?.footer_text || t('长按识别二维码,立即体验AI')}
</p>
</div>
</div>
</div>
{/* 隐藏的 canvas 用于导出 */}
<canvas ref={canvasRef} style={{ display: 'none' }} />
{/* 操作按钮 */}
<div className='flex gap-3 mt-5 w-full'>
<Button
theme='solid'
type='primary'
icon={<ActionDownload size={16} />}
onClick={handleDownload}
loading={downloading}
className='flex-1 !bg-gradient-to-r !from-brand-from !to-brand-to !border-0 !rounded-xl !h-10'
>
{t('下载海报')}
</Button>
<Button
theme='light'
type='tertiary'
icon={<ActionCopy size={16} />}
onClick={handleCopyLink}
className='flex-1 !rounded-xl !h-10'
> >
{t('复制链接')} {t('复制链接')}
</Button> </Button>
</div> </div>
<div className='pm-field'>
<Text strong id='promotion-code-label'>
{t('邀请码')}
</Text>
<div
className='pm-code-row'
role='group'
aria-labelledby='promotion-code-label'
>
<Text id='promotion-code' className='pm-code'>
{affCode}
</Text>
<Button
icon={<ActionCopy size={16} aria-hidden />}
onClick={handleCopyCode}
>
{t('复制')}
</Button>
</div>
</div>
<Paragraph type='secondary' className='pm-share-hint'>
{t(
'将链接发送给好友,好友点击即可注册。支持微信、QQ、邮件等任意方式分享。',
)}
</Paragraph>
</section>
</div>
);
const renderPosterMode = () => (
<div className='pm-poster-layout'>
<div className='pm-preview-stage'>
<div
className='pm-poster'
style={{
'--pm-poster-background': selectedTemplate.bgGradient,
'--pm-poster-ink': selectedTemplate.textColor,
}}
>
<h2>{posterConfig?.slogan || t('邀请好友,共享AI')}</h2>
<p className='pm-poster-subtitle'>
{posterConfig?.sub_slogan || t('注册即可获得免费额度')}
</p>
<h3>{systemName}</h3>
<div className='pm-poster-qr'>
<QRCodeCanvas
id='poster-qrcode'
value={affLink}
size={130}
level='H'
marginSize={2}
/>
</div>
<p>{t('扫码注册')}</p>
<p className='pm-poster-code'>
{t('邀请码')}: {affCode}
</p>
<p className='pm-poster-footer'>
{posterConfig?.footer_text || t('长按识别二维码,立即体验AI')}
</p>
</div>
</div>
<section className='pm-poster-options'>
<div className='pm-field'>
<Text strong id='promotion-template-label'>
{t('选择模板')}
</Text>
<Radio.Group
className='pm-template-list'
aria-labelledby='promotion-template-label'
value={selectedTemplate.id}
onChange={(event) =>
setSelectedTemplate(
DEFAULT_TEMPLATES.find(
(item) => item.id === event.target.value,
),
)
}
>
{DEFAULT_TEMPLATES.map((template) => (
<Radio key={template.id} value={template.id}>
<span className='pm-template-label'>
<span
className='pm-template-swatch'
style={{ '--pm-template-background': template.bgGradient }}
/>
{t(template.name)}
</span>
</Radio>
))}
</Radio.Group>
</div>
<div className='pm-poster-actions'>
<Button
type='primary'
icon={<ActionDownload size={16} aria-hidden />}
onClick={handleDownload}
loading={downloading}
>
{t('下载海报')}
</Button>
<Button
icon={<ActionCopy size={16} aria-hidden />}
onClick={handleCopyLink}
>
{t('复制链接')}
</Button>
</div>
<Text type='secondary' className='pm-share-hint'>
{posterConfig?.footer_text || t('长按识别二维码,立即体验AI')}
</Text>
</section>
<canvas ref={canvasRef} hidden />
</div> </div>
); );
return ( return (
<Modal <Modal
title={ title={t('推广分享')}
<div className='flex items-center gap-2'> open={visible}
<div className='w-8 h-8 rounded-lg bg-gradient-to-br from-brand-from to-brand-to flex items-center justify-center shadow-lg shadow-brand/30'>
<Share2 size={16} className='text-white' />
</div>
<span className='font-bold text-lg'>{t('推广分享')}</span>
</div>
}
visible={visible}
onCancel={onClose} onCancel={onClose}
footer={null} footer={null}
width={520} width={800}
centered centered
className='promotion-modal' className='promotion-modal'
bodyStyle={{ padding: '0 24px 24px' }}
> >
<div style={{ minHeight: 540 }}>
{loading ? ( {loading ? (
<div <div className='pm-loading' aria-label={t('加载中...')}>
className='flex flex-col justify-center items-center' <Skeleton active paragraph={{ rows: 7 }} />
style={{ height: 540 }}
>
<div className='relative'>
<div className='w-16 h-16 rounded-full border-4 border-brand/10 dark:border-brand-deep' />
<div className='absolute inset-0 w-16 h-16 rounded-full border-4 border-brand border-t-transparent animate-spin' />
</div>
<span className='mt-4 text-gray-500 dark:text-gray-400'>
{t('加载中...')}
</span>
</div> </div>
) : ( ) : (
<> <>
{/* 查看邀请奖励规则 - 顶部显眼横幅 */} {affLink ? (
<div <Tabs
className='group mb-5 p-4 rounded-2xl cursor-pointer transition-all duration-300 hover:scale-[1.02] hover:shadow-xl relative overflow-hidden' activeKey={activeTab}
style={{ onChange={setActiveTab}
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', className='promotion-tabs'
}} items={[
{
key: 'link',
label: (
<span className='pm-tab-label'>
<Monitor size={16} aria-hidden />
{t('链接分享')}
</span>
),
children: renderLinkMode(),
},
{
key: 'poster',
label: (
<span className='pm-tab-label'>
<Smartphone size={16} aria-hidden />
{t('海报分享')}
</span>
),
children: renderPosterMode(),
},
]}
/>
) : (
<Alert
type='warning'
showIcon
title={t('邀请链接获取中,请稍后')}
/>
)}
<button
type='button'
className='pm-rewards'
onClick={() => { onClick={() => {
onClose(); onClose();
navigate('/user-center/invite'); navigate('/user-center/invite');
}} }}
> >
{/* 装饰元素 */} <span className='pm-rewards-icon'>
<div className='absolute top-0 right-0 w-20 h-20 bg-white/10 rounded-full -translate-y-1/2 translate-x-1/2' /> <Gift size={20} aria-hidden />
<div className='absolute bottom-0 left-1/2 w-32 h-32 bg-white/5 rounded-full translate-y-1/2' />
{/* 动态光效 */}
<div className='absolute inset-0 bg-gradient-to-r from-transparent via-white/10 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-1000' />
<div className='relative flex items-center justify-between'>
<div className='flex items-center gap-3'>
<div className='w-12 h-12 bg-white/20 backdrop-blur-sm rounded-xl flex items-center justify-center shadow-lg'>
<Gift size={22} className='text-white' />
</div>
<div>
<div className='text-white font-bold text-base flex items-center gap-2'>
{t('查看邀请奖励规则')}
<Sparkles
size={14}
className='text-amber-300 animate-pulse'
/>
</div>
<div className='text-white/80 text-sm mt-0.5'>
{t('了解返佣比例和奖励详情')}
</div>
</div>
</div>
<div className='flex items-center gap-1 text-white/90 group-hover:translate-x-1 transition-transform'>
<span className='text-xs font-medium hidden sm:block'>
{t('立即查看')}
</span> </span>
<ChevronRight size={20} /> <span className='pm-rewards-copy'>
</div> <strong>{t('查看邀请奖励规则')}</strong>
</div> <span>{t('了解返佣比例和奖励详情')}</span>
{/* 底部小标签 */}
<div className='flex gap-2 mt-3'>
<span className='text-xs bg-white/20 backdrop-blur-sm text-white px-2 py-1 rounded-full flex items-center gap-1'>
<Coins size={12} />
{t('消费返佣')}
</span> </span>
<span className='text-xs bg-white/20 backdrop-blur-sm text-white px-2 py-1 rounded-full flex items-center gap-1'> <ChevronRight size={18} aria-hidden />
<TrendingUp size={12} /> </button>
{t('额度奖励')}
</span>
</div>
</div>
{/* Tab 导航 */}
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
className='promotion-tabs'
>
<TabPane
tab={
<span className='flex items-center gap-2 px-2'>
<Monitor size={16} />
<span className='font-medium'>{t('链接分享')}</span>
</span>
}
itemKey='link'
>
<div className='pt-4'>{renderLinkMode()}</div>
</TabPane>
<TabPane
tab={
<span className='flex items-center gap-2 px-2'>
<Smartphone size={16} />
<span className='font-medium'>{t('海报分享')}</span>
</span>
}
itemKey='poster'
>
<div className='pt-4'>{renderPosterMode()}</div>
</TabPane>
</Tabs>
</> </>
)} )}
</div>
</Modal> </Modal>
); );
}; };
@@ -0,0 +1,352 @@
/* Copyright (C) 2025 QuantumNous */
.promotion-modal.ant-modal {
--pm-surface: var(--surface-card);
--pm-muted: var(--surface-bg-base);
--pm-text: var(--text-primary);
--pm-secondary: var(--text-secondary);
--pm-border: var(--border-subtle);
--pm-accent: var(--brand-primary);
--pm-soft: var(--brand-primary-soft);
--pm-qr-surface: #fff;
max-width: calc(100vw - 32px);
padding-block: 24px;
}
.promotion-modal .ant-modal-container {
padding: 28px 32px;
border-radius: 12px;
}
.promotion-modal .ant-modal-header {
margin-bottom: 12px;
}
.promotion-modal .ant-modal-title {
font-size: 20px;
line-height: 28px;
}
.promotion-modal .ant-modal-close {
top: 24px;
right: 24px;
}
.promotion-modal .ant-modal-body {
max-height: calc(100dvh - 160px);
overflow-y: auto;
overscroll-behavior: contain;
}
.promotion-tabs > .ant-tabs-nav {
margin-bottom: 24px;
}
.pm-tab-label {
display: inline-flex;
align-items: center;
gap: 8px;
}
.pm-link-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1.15fr);
gap: 32px;
align-items: stretch;
}
.pm-invitation-card {
display: flex;
flex-direction: column;
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;
}
.pm-eyebrow {
margin-bottom: 12px;
color: var(--pm-accent);
font-size: 12px;
letter-spacing: 0.08em;
}
.pm-invitation-card h4.ant-typography {
margin: 0 0 8px;
font-size: 20px;
overflow-wrap: anywhere;
}
.pm-invitation-card .ant-typography {
max-width: 100%;
}
.pm-qrcode {
padding: 12px;
background: var(--pm-qr-surface);
border-radius: 12px;
margin: 8px 0 16px;
}
.pm-qrcode canvas,
.pm-poster-qr canvas {
display: block;
max-width: 100%;
height: auto;
}
.pm-benefits {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 8px 16px;
margin-top: 24px;
color: var(--pm-secondary);
font-size: 12px;
}
.pm-benefits span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.pm-share-details {
display: flex;
flex-direction: column;
justify-content: center;
gap: 28px;
min-width: 0;
padding-block: 12px;
}
.pm-field {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 12px;
min-width: 0;
}
.pm-field label {
color: var(--pm-text);
font-size: 14px;
font-weight: 600;
}
.pm-field > .ant-btn {
align-self: flex-start;
}
.pm-code-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 16px;
}
.promotion-modal .pm-code {
padding: 10px 16px;
color: var(--pm-accent);
background: var(--pm-soft);
border-radius: 8px;
font:
600 20px/28px Consolas,
monospace;
letter-spacing: 0.06em;
overflow-wrap: anywhere;
min-width: 0;
}
.promotion-modal .pm-share-hint {
margin: 0;
font-size: 13px;
line-height: 1.8;
}
.pm-rewards {
display: flex;
align-items: center;
gap: 14px;
width: 100%;
margin-top: 24px;
padding: 16px;
background: var(--pm-surface);
color: var(--pm-text);
border: 1px solid var(--pm-border);
border-radius: 10px;
font: inherit;
text-align: left;
cursor: pointer;
}
.pm-rewards:hover {
border-color: var(--pm-accent);
background: var(--pm-soft);
}
.pm-rewards-icon {
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 40px;
height: 40px;
border-radius: 8px;
color: var(--pm-accent);
background: var(--pm-soft);
}
.pm-rewards-copy {
display: grid;
gap: 4px;
flex: 1;
min-width: 0;
}
.pm-rewards-copy strong {
font-size: 14px;
font-weight: 600;
}
.pm-rewards-copy > span {
color: var(--pm-secondary);
font-size: 12px;
}
.pm-rewards > svg {
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;
}
.pm-preview-stage {
display: flex;
justify-content: center;
padding: 20px;
border: 1px solid var(--pm-border);
border-radius: 12px;
background: var(--pm-muted);
min-width: 0;
}
.pm-poster {
display: flex;
flex-direction: column;
align-items: center;
width: 240px;
min-width: 0;
aspect-ratio: 375 / 667;
padding: 28px 16px 20px;
background: var(--pm-poster-background);
color: var(--pm-poster-ink);
border-radius: 8px;
text-align: center;
}
.pm-poster h2 {
margin: 0 0 8px;
font-size: 18px;
line-height: 1.5;
color: inherit;
}
.pm-poster p {
margin: 0;
font-size: 12px;
line-height: 1.6;
color: inherit;
}
.pm-poster h3 {
margin: 20px 0;
font-size: 16px;
line-height: 1.5;
color: inherit;
}
.pm-poster-qr {
padding: 8px;
background: var(--pm-qr-surface);
border-radius: 8px;
margin-bottom: 12px;
}
.pm-poster .pm-poster-code {
font-weight: 600;
margin-top: 8px;
overflow-wrap: anywhere;
}
.pm-poster .pm-poster-footer {
margin-top: auto;
padding-top: 20px;
font-size: 10px;
}
.pm-poster-options {
display: grid;
gap: 24px;
min-width: 0;
}
.pm-template-list {
display: grid;
gap: 8px;
}
.promotion-modal .pm-template-list .ant-radio-wrapper {
display: flex;
align-items: center;
margin: 0;
padding: 10px 12px;
border: 1px solid var(--pm-border);
border-radius: 8px;
}
.promotion-modal .pm-template-list .ant-radio-wrapper-checked {
border-color: var(--pm-accent);
background: var(--pm-soft);
}
.pm-template-label {
display: inline-flex;
align-items: center;
gap: 10px;
}
.pm-template-swatch {
display: block;
width: 24px;
height: 24px;
border-radius: 6px;
background: var(--pm-template-background);
}
.pm-poster-actions {
display: grid;
gap: 12px;
}
.pm-loading {
padding-block: 32px;
}
.promotion-modal :is(button, input):focus-visible {
outline: 2px solid var(--pm-accent);
outline-offset: 3px;
}
@media (max-width: 600px) {
.promotion-modal .ant-modal-container {
padding: 20px;
}
.promotion-modal .ant-modal-title {
font-size: 18px;
}
.promotion-modal .ant-modal-close {
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);
gap: 24px;
}
.pm-invitation-card {
padding: 20px 16px;
}
.pm-benefits {
margin-top: 16px;
}
.pm-share-details {
gap: 24px;
padding: 0;
}
.pm-field > .ant-btn {
width: 100%;
}
.pm-preview-stage {
padding: 16px;
}
.pm-template-list {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.promotion-modal .pm-template-list .ant-radio-wrapper {
padding: 8px;
}
.pm-template-label {
gap: 6px;
font-size: 12px;
}
.pm-template-swatch {
width: 18px;
height: 18px;
}
.pm-rewards {
padding: 12px;
}
}
+9 -5
View File
@@ -16,6 +16,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { formatUserReference } from '../../helpers/safeDisplay';
import React, { useCallback, useEffect, useRef, useState } from 'react'; import React, { useCallback, useEffect, useRef, useState } from 'react';
import { import {
@@ -82,7 +84,7 @@ export const HopChain = ({ hops, outcome, t }) => {
> >
<span className='font-medium truncate'> <span className='font-medium truncate'>
{t('第 {{n}} 跳', { n: i + 1 })} ·{' '} {t('第 {{n}} 跳', { n: i + 1 })} ·{' '}
{hop.channel_name || `#${hop.channel_id}`} {hop.channel_name || formatIdReference(hop.channel_id)}
</span> </span>
{failed ? ( {failed ? (
<span className='quality-mono'> <span className='quality-mono'>
@@ -199,7 +201,7 @@ const QualityDetail = ({ quality, t }) => {
width: 130, width: 130,
render: (v, row) => ( render: (v, row) => (
<span className='block truncate max-w-[130px]' title={v}> <span className='block truncate max-w-[130px]' title={v}>
{v || `#${row.user_id}`} {v || formatUserReference('', row.user_id)}
</span> </span>
), ),
}, },
@@ -212,7 +214,7 @@ const QualityDetail = ({ quality, t }) => {
render: (v, row) => render: (v, row) =>
row.organization_id ? ( row.organization_id ? (
<span className='block truncate max-w-[130px]' title={v}> <span className='block truncate max-w-[130px]' title={v}>
{v || `#${row.organization_id}`} {v || formatIdReference(row.organization_id)}
</span> </span>
) : ( ) : (
<span className='text-[var(--text-secondary)]'> <span className='text-[var(--text-secondary)]'>
@@ -240,7 +242,7 @@ const QualityDetail = ({ quality, t }) => {
width: 140, width: 140,
render: (v, row) => ( render: (v, row) => (
<span className='block truncate max-w-[140px]' title={v}> <span className='block truncate max-w-[140px]' title={v}>
{row.channel_id ? v || `#${row.channel_id}` : '-'} {row.channel_id ? v || formatIdReference(row.channel_id) : '-'}
</span> </span>
), ),
}, },
@@ -452,7 +454,9 @@ const QualityDetail = ({ quality, t }) => {
<OutcomeTag value={row.outcome} t={t} /> <OutcomeTag value={row.outcome} t={t} />
<span className='text-xs'> <span className='text-xs'>
{row.channel_name || {row.channel_name ||
(row.channel_id ? `#${row.channel_id}` : '')} (row.channel_id
? formatIdReference(row.channel_id)
: '')}
</span> </span>
{(row.status_code || row.error_code) && ( {(row.status_code || row.error_code) && (
<span className='quality-mono'> <span className='quality-mono'>
+4 -2
View File
@@ -16,6 +16,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { formatUserReference } from '../../helpers/safeDisplay';
import { import {
SlidersHorizontal as ActionSlidersHorizontal, SlidersHorizontal as ActionSlidersHorizontal,
@@ -110,7 +112,7 @@ const RemoteSelect = ({
const name = labels.current[String(value)]; const name = labels.current[String(value)];
opts.unshift({ opts.unshift({
value: String(value), value: String(value),
label: name ? `${name} (#${value})` : `#${value}`, label: name ? `${name} (#${value})` : formatIdReference(value),
}); });
} }
return opts; return opts;
@@ -193,7 +195,7 @@ const QualityFilterBar = ({ quality, t, onOpenDetail }) => {
if (filters.user_id) if (filters.user_id)
push( push(
'user_id', 'user_id',
`${isOrg ? t('成员') : t('用户')}: ${nameOf(options.members, filters.user_id) || '#' + filters.user_id}`, `${isOrg ? t('成员') : t('用户')}: ${nameOf(options.members, filters.user_id) || formatUserReference('', filters.user_id)}`,
); );
if (filters.token_id) if (filters.token_id)
push( push(
+4 -1
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
@@ -102,7 +103,9 @@ const QualityHeatmap = ({ quality, t }) => {
(row.cells || []).forEach((c) => { (row.cells || []).forEach((c) => {
byTs[c.ts] = c; byTs[c.ts] = c;
}); });
const name = names[row.channel_id] || `#${row.channel_id}`; const name =
names[row.channel_id] ||
formatIdReference(row.channel_id);
return ( return (
<tr key={row.channel_id}> <tr key={row.channel_id}>
<th title={name}> <th title={name}>
@@ -21,6 +21,7 @@ import {
Plus as ActionPlus, Plus as ActionPlus,
Upload as ActionUpload, Upload as ActionUpload,
} from '@/components/common/icons/ActionIcons'; } from '@/components/common/icons/ActionIcons';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React, { useState, useEffect, useCallback } from 'react'; import React, { useState, useEffect, useCallback } from 'react';
import { import {
Card, Card,
@@ -31,7 +32,6 @@ import {
Select, Select,
Tag, Tag,
Avatar, Avatar,
Popconfirm,
Typography, Typography,
Space, Space,
Banner, Banner,
@@ -307,28 +307,34 @@ const CustomerServiceSetting = () => {
title: t('操作'), title: t('操作'),
dataIndex: 'action', dataIndex: 'action',
render: (_, record) => ( render: (_, record) => (
<Space> <TableRowActions
<Button items={[
onClick={() => handleToggleStatus(record)} {
type='link' key: 'status',
size='small' label: record.status === 1 ? t('下线') : t('上线'),
danger={(record.status === 1 ? 'danger' : 'primary') === 'danger'} onClick: () => handleToggleStatus(record),
danger: (record.status === 1 ? 'danger' : 'primary') === 'danger',
},
{
key: 'delete',
label: t('删除'),
danger: true,
onClick: () =>
Modal.confirm({
title: t('确认删除'),
content: t('确定要删除这个客服吗?'),
okText: t('确认'),
cancelText: t('取消'),
okButtonProps: { danger: true },
onOk: () => handleDelete(record.id),
}),
},
]}
> >
{record.status === 1 ? t('下线') : t('上线')}
</Button>
<Button onClick={() => openModal(record)} type='link' size='small'> <Button onClick={() => openModal(record)} type='link' size='small'>
{t('编辑')} {t('编辑')}
</Button> </Button>
<Popconfirm </TableRowActions>
title={t('确认删除')}
content={t('确定要删除这个客服吗?')}
onConfirm={() => handleDelete(record.id)}
>
<Button type='link' size='small' danger>
{t('删除')}
</Button>
</Popconfirm>
</Space>
), ),
}, },
]; ];
+27 -25
View File
@@ -24,6 +24,7 @@ import {
ChevronDown as ActionChevronDown, ChevronDown as ActionChevronDown,
ChevronRight as ActionChevronRight, ChevronRight as ActionChevronRight,
} from '@/components/common/icons/ActionIcons'; } from '@/components/common/icons/ActionIcons';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React, { useState, useEffect, useCallback, useMemo } from 'react'; import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { import {
Card, Card,
@@ -989,7 +990,31 @@ const LevelPolicySetting = () => {
title: t('操作'), title: t('操作'),
width: 260, width: 260,
render: (_, r) => ( render: (_, r) => (
<Space> <TableRowActions
items={[
{
key: 'copy',
label: t('复制'),
onClick: () => duplicateLevel(type, r.code),
title: t('以该等级为模板新建'),
},
{
key: 'delete',
label: t('删除'),
disabled: deletingCode === `${type}/${r.code}`,
danger: true,
onClick: () =>
Modal.confirm({
title: t('确认删除该等级?'),
content: t('被用户/企业/默认等级引用时会被拒绝'),
okText: t('确认'),
cancelText: t('取消'),
okButtonProps: { danger: true },
onOk: () => deleteLevel(type, r.code),
}),
},
]}
>
<Button <Button
onClick={() => openEditor(type, r.code)} onClick={() => openEditor(type, r.code)}
type='link' type='link'
@@ -997,30 +1022,7 @@ const LevelPolicySetting = () => {
> >
{t('编辑')} {t('编辑')}
</Button> </Button>
<Tooltip content={t('以该等级为模板新建')}> </TableRowActions>
<Button
onClick={() => duplicateLevel(type, r.code)}
type='link'
size='small'
>
{t('复制')}
</Button>
</Tooltip>
<Popconfirm
title={t('确认删除该等级?')}
content={t('被用户/企业/默认等级引用时会被拒绝')}
onConfirm={() => deleteLevel(type, r.code)}
>
<Button
loading={deletingCode === `${type}/${r.code}`}
type='link'
size='small'
danger
>
{t('删除')}
</Button>
</Popconfirm>
</Space>
), ),
}, },
]; ];
@@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import { useEffectEvent } from '../../hooks/common/useEffectEvent'; import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { import {
@@ -27,7 +28,6 @@ import {
Modal, Modal,
Form, Form,
Toast, Toast,
Popconfirm,
Switch, Switch,
Tag, Tag,
Progress, Progress,
@@ -262,7 +262,29 @@ const TutorialVideoSetting = () => {
title: t('操作'), title: t('操作'),
width: 180, width: 180,
render: (_, record) => ( render: (_, record) => (
<div style={{ display: 'flex', gap: 8 }}> <TableRowActions
items={[
{
key: 'edit',
label: t('编辑'),
onClick: () => handleEdit(record),
},
{
key: 'delete',
label: t('删除'),
danger: true,
onClick: () =>
Modal.confirm({
title: t('确定删除这个视频吗?'),
content: t('删除后将无法恢复'),
okText: t('确认'),
cancelText: t('取消'),
okButtonProps: { danger: true },
onOk: () => handleDelete(record.id),
}),
},
]}
>
<Button <Button
onClick={() => handlePreview(record)} onClick={() => handlePreview(record)}
type='link' type='link'
@@ -270,19 +292,7 @@ const TutorialVideoSetting = () => {
> >
{t('预览')} {t('预览')}
</Button> </Button>
<Button onClick={() => handleEdit(record)} type='link' size='small'> </TableRowActions>
{t('编辑')}
</Button>
<Popconfirm
title={t('确定删除这个视频吗?')}
content={t('删除后将无法恢复')}
onConfirm={() => handleDelete(record.id)}
>
<Button type='link' size='small' danger>
{t('删除')}
</Button>
</Popconfirm>
</div>
), ),
}, },
]; ];
+34 -28
View File
@@ -19,7 +19,8 @@ For commercial licensing, please contact support@quantumnous.com
import React, { useCallback, useEffect, useState } from 'react'; import React, { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Button, Empty, Popconfirm, Space, Tag, Typography } from 'antd'; import { Button, Empty, Modal, Space, Tag, Typography } from 'antd';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import { Table } from '@/components/ui'; import { Table } from '@/components/ui';
import { ConsoleAlert as Alert } from '../console/ConsolePrimitives'; import { ConsoleAlert as Alert } from '../console/ConsolePrimitives';
import { Plus } from '../common/icons/ActionIcons'; import { Plus } from '../common/icons/ActionIcons';
@@ -148,7 +149,37 @@ const ProfileTable = ({ mode, orgId, canWrite = true, emptyHint }) => {
fixed: 'right', fixed: 'right',
width: 180, width: 180,
render: (_, r) => ( render: (_, r) => (
<Space size={8} wrap> <TableRowActions
items={[
canWrite && {
key: 'edit',
label: t('编辑'),
onClick: () => setEditing(r),
},
canWrite && {
key: 'delete',
label: t('删除'),
danger: true,
onClick: () =>
Modal.confirm({
title: t('确认删除该集合?'),
content: t('使用该虚拟模型名的请求将返回"模型不存在"。'),
okText: t('确认'),
cancelText: t('取消'),
okButtonProps: { danger: true },
onOk: async () => {
try {
await deleteProfile(mode, orgId, r.id);
showSuccess(t('已删除'));
load();
} catch (e) {
if (e?.message) showError(e.message);
}
},
}),
},
]}
>
<Button <Button
type='link' type='link'
size='small' size='small'
@@ -157,32 +188,7 @@ const ProfileTable = ({ mode, orgId, canWrite = true, emptyHint }) => {
> >
{t('试路由')} {t('试路由')}
</Button> </Button>
{canWrite && ( </TableRowActions>
<>
<Button type='link' size='small' onClick={() => setEditing(r)}>
{t('编辑')}
</Button>
<Popconfirm
title={t('确认删除该集合?')}
description={t('使用该虚拟模型名的请求将返回"模型不存在"。')}
okButtonProps={{ danger: true }}
onConfirm={async () => {
try {
await deleteProfile(mode, orgId, r.id);
showSuccess(t('已删除'));
load();
} catch (e) {
if (e?.message) showError(e.message);
}
}}
>
<Button type='link' size='small' danger>
{t('删除')}
</Button>
</Popconfirm>
</>
)}
</Space>
), ),
}, },
]; ];
@@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import { writeClipboardText } from '../../../helpers/clipboard'; import { writeClipboardText } from '../../../helpers/clipboard';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Switch } from 'antd'; import { Switch } from 'antd';
import { import {
@@ -729,12 +730,70 @@ export const getChannelsColumns = ({
dataIndex: 'operate', dataIndex: 'operate',
fixed: 'right', fixed: 'right',
render: (text, record, index) => { render: (text, record, index) => {
if (record.children === undefined) { if (!isRoot()) return null;
const moreMenuItems = [ if (record.children !== undefined) {
return (
<TableRowActions
items={[
{ {
node: 'item', key: 'enable',
name: t('删除'), label: t('启用全部'),
type: 'danger', onClick: () => manageTag(record.key, 'enable'),
},
{
key: 'disable',
label: t('禁用全部'),
onClick: () => manageTag(record.key, 'disable'),
},
]}
>
<Button
type='link'
size='small'
onClick={() => {
setShowEditTag(true);
setEditingTag(record.key);
}}
>
{t('编辑')}
</Button>
</TableRowActions>
);
}
return (
<TableRowActions
items={[
{
key: 'batch-test',
label: t('批量测试'),
onClick: () => {
setCurrentTestChannel(record);
setShowModelTestModal(true);
},
},
record.channel_info?.is_multi_key && {
key: 'multi-key',
label: t('多密钥管理'),
onClick: () => {
setCurrentMultiKeyChannel(record);
setShowMultiKeyManageModal(true);
},
},
{
key: 'copy',
label: t('复制'),
onClick: () => {
Modal.confirm({
title: t('确定是否要复制此渠道?'),
content: t('复制渠道的所有信息'),
onOk: () => copySelectedChannel(record),
});
},
},
{
key: 'delete',
label: t('删除'),
danger: true,
onClick: async () => { onClick: async () => {
const content = await buildDeleteConfirmContent(record.id, t); const content = await buildDeleteConfirmContent(record.id, t);
Modal.confirm({ Modal.confirm({
@@ -754,24 +813,8 @@ export const getChannelsColumns = ({
}); });
}, },
}, },
{ ]}
node: 'item', >
name: t('复制'),
type: 'tertiary',
onClick: () => {
Modal.confirm({
title: t('确定是否要复制此渠道?'),
content: t('复制渠道的所有信息'),
onOk: () => copySelectedChannel(record),
});
},
},
];
return (
<Space wrap className='console-module-row-actions'>
{isRoot() && (
<>
<Button <Button
type='link' type='link'
size='small' size='small'
@@ -779,16 +822,6 @@ export const getChannelsColumns = ({
> >
{t('测试')} {t('测试')}
</Button> </Button>
<Button
type='link'
size='small'
onClick={() => {
setCurrentTestChannel(record);
setShowModelTestModal(true);
}}
>
{t('批量测试')}
</Button>
<Button <Button
type='link' type='link'
size='small' size='small'
@@ -799,72 +832,8 @@ export const getChannelsColumns = ({
> >
{t('编辑')} {t('编辑')}
</Button> </Button>
<Button </TableRowActions>
type='link'
danger
size='small'
onClick={moreMenuItems[0].onClick}
>
{t('删除')}
</Button>
<Button
type='link'
size='small'
onClick={moreMenuItems[1].onClick}
>
{t('复制')}
</Button>
{record.channel_info?.is_multi_key && (
<Button
type='link'
size='small'
onClick={() => {
setCurrentMultiKeyChannel(record);
setShowMultiKeyManageModal(true);
}}
>
{t('多密钥管理')}
</Button>
)}
</>
)}
</Space>
); );
} else {
// 标签操作按钮
return (
<Space wrap>
{isRoot() && (
<>
<Button
type='link'
size='small'
onClick={() => manageTag(record.key, 'enable')}
>
{t('启用全部')}
</Button>
<Button
type='link'
size='small'
onClick={() => manageTag(record.key, 'disable')}
>
{t('禁用全部')}
</Button>
<Button
type='link'
size='small'
onClick={() => {
setShowEditTag(true);
setEditingTag(record.key);
}}
>
{t('编辑')}
</Button>
</>
)}
</Space>
);
}
}, },
}, },
]; ];
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../../../i18n/technicalText.js';
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent'; import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
@@ -290,11 +291,11 @@ const EditChannelModal = (props) => {
if (ch.status !== 1) { if (ch.status !== 1) {
return { return {
value: ch.id, value: ch.id,
label: `#${ch.id} ${ch.name}${t('(已禁用)')}`, label: `${formatIdReference(ch.id)} ${ch.name}${t('(已禁用)')}`,
disabled: true, disabled: true,
}; };
} }
const parts = [`#${ch.id} ${ch.name}`]; const parts = [`${formatIdReference(ch.id)} ${ch.name}`];
if (ch.group) parts.push(ch.group); if (ch.group) parts.push(ch.group);
if (ch.region) parts.push(ch.region); if (ch.region) parts.push(ch.region);
return { value: ch.id, label: parts.join(' · ') }; return { value: ch.id, label: parts.join(' · ') };
@@ -345,7 +346,7 @@ const EditChannelModal = (props) => {
.filter((id) => !known.has(id) && id !== channelId) .filter((id) => !known.has(id) && id !== channelId)
.map((id) => ({ .map((id) => ({
value: id, value: id,
label: `#${id}${t('(已删除)')}`, label: `${formatIdReference(id)}${t('(已删除)')}`,
disabled: true, disabled: true,
})); }));
return missing.length return missing.length
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../../../helpers/safeDisplay';
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent'; import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
@@ -359,7 +360,7 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => {
{ {
title: t('索引'), title: t('索引'),
dataIndex: 'index', dataIndex: 'index',
render: (text) => `#${text}`, render: (text) => formatIdReference(text),
}, },
// { // {
// title: t('密钥预览'), // title: t('密钥预览'),
@@ -18,9 +18,10 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import { Copy as ActionCopy } from '@/components/common/icons/ActionIcons'; import { Copy as ActionCopy } from '@/components/common/icons/ActionIcons';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React from 'react'; import React from 'react';
import { Button as AntButton, Tooltip as AntTooltip } from 'antd'; import { Button as AntButton, Tooltip as AntTooltip } from 'antd';
import { Button, Space, Tag, Modal, Tooltip } from '@/components/ui'; import { Button, Tag, Modal, Tooltip } from '@/components/ui';
import { import {
timestamp2string, timestamp2string,
getLobeHubIcon, getLobeHubIcon,
@@ -239,47 +240,25 @@ const renderOperations = (
setDetailModel, setDetailModel,
) => { ) => {
return ( return (
<Space wrap className='console-module-row-actions'> <TableRowActions
<Button type='link' size='small' onClick={() => setDetailModel(record)}> items={
{t('详情')} isRoot()
</Button> ? [
{isRoot() && ( {
<> key: 'toggle-status',
{record.status === 1 ? ( label: record.status === 1 ? t('禁用') : t('启用'),
<Button onClick: () =>
type='link' manageModel(
danger record.id,
size='small' record.status === 1 ? 'disable' : 'enable',
onClick={() => manageModel(record.id, 'disable', record)} record,
> ),
{t('禁用')} },
</Button> {
) : ( key: 'delete',
<Button label: t('删除'),
type='link' danger: true,
size='small' onClick: () => {
onClick={() => manageModel(record.id, 'enable', record)}
>
{t('启用')}
</Button>
)}
<Button
type='link'
size='small'
onClick={() => {
setEditingModel(record);
setShowEdit(true);
}}
>
{t('编辑')}
</Button>
<Button
type='link'
danger
size='small'
onClick={() => {
Modal.confirm({ Modal.confirm({
title: t('确定是否要删除此模型?'), title: t('确定是否要删除此模型?'),
content: t('此修改将不可逆'), content: t('此修改将不可逆'),
@@ -290,13 +269,28 @@ const renderOperations = (
})(); })();
}, },
}); });
},
},
]
: []
}
>
<Button type='link' size='small' onClick={() => setDetailModel(record)}>
{t('详情')}
</Button>
{isRoot() && (
<Button
type='link'
size='small'
onClick={() => {
setEditingModel(record);
setShowEdit(true);
}} }}
> >
{t('删除')} {t('编辑')}
</Button> </Button>
</>
)} )}
</Space> </TableRowActions>
); );
}; };
@@ -38,37 +38,21 @@ const RedemptionsActions = ({
}; };
return ( return (
<div className='flex flex-wrap gap-2 w-full md:w-auto order-2 md:order-1'> <div className='console-list-tool-actions'>
{isAdmin() && ( <Button onClick={batchCopyRedemptions}>
<Button
type='primary'
className='flex-1 md:flex-initial'
onClick={handleAddRedemption}
size='small'
>
{t('添加兑换码')}
</Button>
)}
<Button
type='tertiary'
className='flex-1 md:flex-initial'
onClick={batchCopyRedemptions}
size='small'
>
{t('复制所选兑换码到剪贴板')} {t('复制所选兑换码到剪贴板')}
</Button> </Button>
{isAdmin() && ( {isAdmin() && (
<Button <Button type='danger' onClick={batchDeleteRedemptions}>
type='danger'
className='w-full md:w-auto'
onClick={batchDeleteRedemptions}
size='small'
>
{t('清除失效兑换码')} {t('清除失效兑换码')}
</Button> </Button>
)} )}
{isAdmin() && (
<Button type='primary' onClick={handleAddRedemption}>
{t('添加兑换码')}
</Button>
)}
</div> </div>
); );
}; };
@@ -18,8 +18,8 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React from 'react'; import React from 'react';
import { Tag, Button, Space, Popover, Dropdown } from '@/components/ui'; import { Tag, Button, Popover } from '@/components/ui';
import { IconMore } from '@/components/ui/icons'; import { TableRowActions } from '@/components/common/table/TableToolbar';
import { import {
renderQuota, renderQuota,
timestamp2string, timestamp2string,
@@ -144,46 +144,42 @@ export const getRedemptionsColumns = ({
}, },
}, },
{ {
title: '', title: t('操作'),
dataIndex: 'operate', dataIndex: 'operate',
fixed: 'right', fixed: 'right',
width: 205, width: 215,
render: (text, record) => { render: (text, record) => {
// Create dropdown menu items for more operations const moreMenuItems = [];
const moreMenuItems = [ if (isAdmin() && !isExpired(record)) {
{ const unused = record.status === REDEMPTION_STATUS.UNUSED;
node: 'item',
name: t('删除'),
type: 'danger',
onClick: () => {
showDeleteRedemptionModal(record);
},
},
];
if (record.status === REDEMPTION_STATUS.UNUSED && !isExpired(record)) {
moreMenuItems.push({ moreMenuItems.push({
node: 'item', key: 'toggle-status',
name: t('禁用'), label: unused ? t('禁用') : 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, disabled: record.status === REDEMPTION_STATUS.USED,
onClick: () =>
manageRedemption(
record.id,
unused ? REDEMPTION_ACTIONS.DISABLE : REDEMPTION_ACTIONS.ENABLE,
record,
),
});
}
moreMenuItems.unshift({
key: 'copy',
label: t('复制'),
onClick: () => copyText(record.key),
});
if (isAdmin()) {
moreMenuItems.push({
key: 'delete',
label: t('删除'),
danger: true,
onClick: () => showDeleteRedemptionModal(record),
}); });
} }
return ( return (
<Space> <TableRowActions items={moreMenuItems}>
<Popover <Popover
// 触屏必须 click:这是查看兑换码明文的唯一入口 // 触屏必须 click:这是查看兑换码明文的唯一入口
trigger={hoverOrClickTrigger()} trigger={hoverOrClickTrigger()}
@@ -191,22 +187,13 @@ export const getRedemptionsColumns = ({
style={{ padding: 20 }} style={{ padding: 20 }}
position='top' position='top'
> >
<Button type='tertiary' size='small'> <Button type='link' size='small'>
{t('查看')} {t('查看')}
</Button> </Button>
</Popover> </Popover>
<Button
size='small'
onClick={async () => {
await copyText(record.key);
}}
>
{t('复制')}
</Button>
{isAdmin() && ( {isAdmin() && (
<>
<Button <Button
type='tertiary' type='link'
size='small' size='small'
onClick={() => { onClick={() => {
setEditingRedemption(record); setEditingRedemption(record);
@@ -216,16 +203,8 @@ export const getRedemptionsColumns = ({
> >
{t('编辑')} {t('编辑')}
</Button> </Button>
<Dropdown
trigger='click'
position='bottomRight'
menu={moreMenuItems}
>
<Button type='tertiary' size='small' icon={<IconMore />} />
</Dropdown>
</>
)} )}
</Space> </TableRowActions>
); );
}, },
}, },
@@ -51,28 +51,24 @@ const RedemptionsFilters = ({
onSubmit={searchRedemptions} onSubmit={searchRedemptions}
allowEmpty={true} allowEmpty={true}
autoComplete='off' autoComplete='off'
layout='horizontal' layout='vertical'
trigger='change' trigger='change'
stopValidateWithError={false} stopValidateWithError={false}
className='w-full' className='console-filter-panel'
> >
<div className='console-search-fields'> <div className='console-filter-grid'>
<div className='console-search-field'>
<Form.Input <Form.Input
field='searchKeyword' field='searchKeyword'
prefix={<IconSearch />} prefix={<IconSearch />}
label={t('搜索关键字')}
placeholder={t('关键字(id或者名称)')} placeholder={t('关键字(id或者名称)')}
showClear showClear
pure
size='small'
/> />
</div> </div>
<ConsoleSearchActions <ConsoleSearchActions
onReset={handleReset} onReset={handleReset}
loading={loading || searching} loading={loading || searching}
searchLabel='查询'
/> />
</div>
</Form> </Form>
); );
}; };
@@ -18,12 +18,8 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { useMemo, useState } from 'react'; import React, { useMemo, useState } from 'react';
import { Empty } from '@/components/ui'; import TableEmpty from '../../common/table/TableEmpty';
import CardTable from '../../common/ui/CardTable'; import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getRedemptionsColumns } from './RedemptionsColumnDefs'; import { getRedemptionsColumns } from './RedemptionsColumnDefs';
import DeleteRedemptionModal from './modals/DeleteRedemptionModal'; import DeleteRedemptionModal from './modals/DeleteRedemptionModal';
@@ -101,17 +97,8 @@ const RedemptionsTable = (redemptionsData) => {
loading={loading} loading={loading}
rowSelection={rowSelection} rowSelection={rowSelection}
onRow={handleRow} onRow={handleRow}
empty={ empty={<TableEmpty />}
<Empty className='console-list-table overflow-hidden'
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className='rounded-xl overflow-hidden'
size='middle' size='middle'
/> />
+2 -4
View File
@@ -82,15 +82,13 @@ const RedemptionsPage = () => {
/> />
} }
type='type1' type='type1'
descriptionArea={ actionsArea={
<div className='console-list-tools'>
<RedemptionsDescription <RedemptionsDescription
compactMode={compactMode} compactMode={compactMode}
setCompactMode={setCompactMode} setCompactMode={setCompactMode}
t={t} t={t}
/> />
}
actionsArea={
<div className='flex flex-col md:flex-row justify-between items-center gap-2 w-full'>
<RedemptionsActions <RedemptionsActions
selectedKeys={selectedKeys} selectedKeys={selectedKeys}
setEditingRedemption={setEditingRedemption} setEditingRedemption={setEditingRedemption}
@@ -18,11 +18,10 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
import React from 'react'; import React from 'react';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import { import {
Button, Button,
Dropdown,
Space, Space,
SplitButtonGroup,
Tag, Tag,
AvatarGroup, AvatarGroup,
Avatar, Avatar,
@@ -40,12 +39,7 @@ import {
getModelCategories, getModelCategories,
showError, showError,
} from '../../../helpers'; } from '../../../helpers';
import { import { IconCopy, IconEyeOpened, IconEyeClosed } from '@/components/ui/icons';
IconTreeTriangleDown,
IconCopy,
IconEyeOpened,
IconEyeClosed,
} from '@/components/ui/icons';
// progress color helper // progress color helper
const getProgressColor = (pct) => { const getProgressColor = (pct) => {
@@ -327,7 +321,6 @@ const renderOperations = (
const name = Object.keys(item)[0]; const name = Object.keys(item)[0];
if (!name) continue; if (!name) continue;
chatsArray.push({ chatsArray.push({
node: 'item',
key: i, key: i,
name, name,
value: item[name], value: item[name],
@@ -340,14 +333,58 @@ const renderOperations = (
} }
return ( return (
<Space wrap> <TableRowActions
<SplitButtonGroup items={[
className='overflow-hidden' chatsArray.length > 0 && {
aria-label={t('项目操作按钮组')} key: 'chat-links',
label: t('聊天链接'),
children: chatsArray.map((item) => ({
key: `chat-${item.key}`,
label: item.name,
onClick: item.onClick,
})),
},
{
key: 'status',
label: record.status === 1 ? t('禁用') : t('启用'),
danger: record.status === 1,
onClick: async () => {
await manageToken(
record.id,
record.status === 1 ? 'disable' : 'enable',
record,
);
await refresh();
},
},
{
key: 'edit',
label: t('编辑'),
onClick: () => {
setEditingToken(record);
setShowEdit(true);
},
},
{
key: 'delete',
label: t('删除'),
danger: true,
onClick: () =>
Modal.confirm({
title: t('确定是否要删除此密钥?'),
content: t('此修改将不可逆'),
okButtonProps: { danger: true },
onOk: async () => {
await manageToken(record.id, 'delete', record);
await refresh();
},
}),
},
]}
> >
<Button <Button
size='small' size='small'
type='tertiary' type='link'
onClick={() => { onClick={() => {
if (chatsArray.length === 0) { if (chatsArray.length === 0) {
showError(t('请联系管理员配置聊天链接')); showError(t('请联系管理员配置聊天链接'));
@@ -359,68 +396,7 @@ const renderOperations = (
> >
{t('聊天')} {t('聊天')}
</Button> </Button>
<Dropdown trigger='click' position='bottomRight' menu={chatsArray}> </TableRowActions>
<Button
type='tertiary'
icon={<IconTreeTriangleDown />}
size='small'
></Button>
</Dropdown>
</SplitButtonGroup>
{record.status === 1 ? (
<Button
type='danger'
size='small'
onClick={async () => {
await manageToken(record.id, 'disable', record);
await refresh();
}}
>
{t('禁用')}
</Button>
) : (
<Button
size='small'
onClick={async () => {
await manageToken(record.id, 'enable', record);
await refresh();
}}
>
{t('启用')}
</Button>
)}
<Button
type='tertiary'
size='small'
onClick={() => {
setEditingToken(record);
setShowEdit(true);
}}
>
{t('编辑')}
</Button>
<Button
type='danger'
size='small'
onClick={() => {
Modal.confirm({
title: t('确定是否要删除此密钥?'),
content: t('此修改将不可逆'),
onOk: () => {
(async () => {
await manageToken(record.id, 'delete', record);
await refresh();
})();
},
});
}}
>
{t('删除')}
</Button>
</Space>
); );
}; };
+20 -33
View File
@@ -26,10 +26,9 @@ import {
Progress, Progress,
Popover, Popover,
Typography, Typography,
Dropdown,
} from '@/components/ui'; } from '@/components/ui';
import { Switch } from 'antd'; import { Switch } from 'antd';
import { IconMore } from '@/components/ui/icons'; import { TableRowActions } from '@/components/common/table/TableToolbar';
import { import {
renderGroup, renderGroup,
renderNumber, renderNumber,
@@ -256,50 +255,48 @@ const renderOperations = (
if (canChangeRole) { if (canChangeRole) {
moreMenu.push( moreMenu.push(
{ {
node: 'item', key: 'promote',
name: t('提升'), label: t('提升'),
onClick: () => showPromoteModal(record), onClick: () => showPromoteModal(record),
}, },
{ {
node: 'item', key: 'demote',
name: t('降级'), label: t('降级'),
onClick: () => showDemoteModal(record), onClick: () => showDemoteModal(record),
}, },
{ node: 'divider' }, { type: 'divider' },
); );
} }
moreMenu.push({ moreMenu.push({
node: 'item', key: 'invitations',
name: t('邀请记录'), label: t('邀请记录'),
onClick: () => showInvitedUsersModal(record), onClick: () => showInvitedUsersModal(record),
}); });
if (canManage) { if (canManage) {
moreMenu.push( moreMenu.push(
{ node: 'divider' }, { type: 'divider' },
{ {
node: 'item', key: 'reset-passkey',
name: t('重置 Passkey'), label: t('重置 Passkey'),
onClick: () => showResetPasskeyModal(record), onClick: () => showResetPasskeyModal(record),
}, },
{ {
node: 'item', key: 'reset-2fa',
name: t('重置 2FA'), label: t('重置 2FA'),
onClick: () => showResetTwoFAModal(record), onClick: () => showResetTwoFAModal(record),
}, },
{ node: 'divider' }, { type: 'divider' },
{ {
node: 'item', key: 'delete',
name: t('注销'), label: t('注销'),
type: 'danger', danger: true,
onClick: () => showDeleteModal(record), onClick: () => showDeleteModal(record),
}, },
); );
} }
return ( return (
// wrap 保留:移动端 CardTable 把按钮放进 ~280px 的卡片行里,Semi Space 默认 <TableRowActions items={moreMenu}>
// wrap:false 时溢出会被 .ant-card{overflow:hidden} 裁掉(不是滚动,是永久看不到)
<Space wrap className='console-module-row-actions'>
{canManage && ( {canManage && (
<> <>
<Button <Button
@@ -314,15 +311,7 @@ const renderOperations = (
</Button> </Button>
</> </>
)} )}
<Dropdown menu={moreMenu} trigger='click' position='bottomRight'> </TableRowActions>
<Button
type='tertiary'
size='small'
icon={<IconMore />}
aria-label={t('更多操作')}
/>
</Dropdown>
</Space>
); );
}; };
@@ -394,9 +383,7 @@ export const getUsersColumns = ({
title: t('操作'), title: t('操作'),
dataIndex: 'operate', dataIndex: 'operate',
fixed: 'right', fixed: 'right',
// 200 而不是更窄:en 下「Edit + Disable + 更多」三控件 ≈ 190px, width: 135,
// 再窄会触发 Space wrap 折行,重新撑高行高(本次改版要消灭的问题)
width: 120,
render: (text, record, index) => render: (text, record, index) =>
renderOperations(text, record, { renderOperations(text, record, {
setEditingUser, setEditingUser,
+67 -23
View File
@@ -39,6 +39,12 @@ import { useLocation } from 'react-router-dom';
import { useActualTheme } from '../../context/Theme'; import { useActualTheme } from '../../context/Theme';
import { normalizeLanguage } from '../../i18n/language'; import { normalizeLanguage } from '../../i18n/language';
import { colord } from 'colord'; import { colord } from 'colord';
import {
PROTOTYPE_DARK_PRIMARY,
PROTOTYPE_DARK_SEED,
PROTOTYPE_LIGHT_PRIMARY,
resolveBrandPalette,
} from '../../helpers/brandPalette';
import './antd-v5-compat.css'; import './antd-v5-compat.css';
// 与下方 Ant Design locale 一一对应的 dayjs 语言(未覆盖语言与 Ant Design 一样回退中文)。 // 与下方 Ant Design locale 一一对应的 dayjs 语言(未覆盖语言与 Ant Design 一样回退中文)。
@@ -55,8 +61,8 @@ const DAYJS_LOCALES = {
// 在线原型暗色:种子 #f2ad41 经 Ant Design 暗色算法推导出主色 #d1963a(悬停 #e8ba65、 // 在线原型暗色:种子 #f2ad41 经 Ant Design 暗色算法推导出主色 #d1963a(悬停 #e8ba65、
// 选中背景 #574222 等)。系统以“最终主色”(--brand-primary) 作为 colorPrimary, // 选中背景 #574222 等)。系统以“最终主色”(--brand-primary) 作为 colorPrimary,
// 算法其余衍生令牌需仍按原型种子推导,否则会从 #d1963a 再推一次而整体偏暗。 // 算法其余衍生令牌需仍按原型种子推导,否则会从 #d1963a 再推一次而整体偏暗。
const PROTOTYPE_DARK_PRIMARY = '#d1963a'; const DARK_SURFACE = '#1b212b';
const PROTOTYPE_DARK_SEED = '#f2ad41'; const LIGHT_SURFACE = '#ffffff';
// v5 used these shadows in both themes; v6 derives white shadows in dark mode. // v5 used these shadows in both themes; v6 derives white shadows in dark mode.
const v5ShadowTokens = { const v5ShadowTokens = {
@@ -69,15 +75,7 @@ const v5ShadowTokens = {
'0 1px 2px 0 rgba(0,0,0,0.03), 0 1px 6px -1px rgba(0,0,0,0.02), 0 2px 4px 0 rgba(0,0,0,0.02)', '0 1px 2px 0 rgba(0,0,0,0.03), 0 1px 6px -1px rgba(0,0,0,0.02), 0 2px 4px 0 rgba(0,0,0,0.02)',
}; };
// 页面局部“品牌强调色”(原型 --brand):等于当前主题的种子色。 const prototypeTheme = (dark, palette) => ({
// 浅色与自定义主色时即 colorPrimary;仅默认暗色主色 #d1963a 时回到原型种子 #f2ad41,
// 保证浅色 / 深色 / 自定义主题色三态都只由主题 token 推导,不在页面里另写颜色。
export const brandAccentFromToken = (colorPrimary, dark) =>
dark && colorPrimary?.toLowerCase() === PROTOTYPE_DARK_PRIMARY
? PROTOTYPE_DARK_SEED
: colorPrimary;
export const prototypeTheme = (dark) => ({
algorithm: (seed, map) => { algorithm: (seed, map) => {
const derive = const derive =
dark && seed.colorPrimary?.toLowerCase() === PROTOTYPE_DARK_PRIMARY dark && seed.colorPrimary?.toLowerCase() === PROTOTYPE_DARK_PRIMARY
@@ -91,14 +89,30 @@ export const prototypeTheme = (dark) => ({
...(dark ? theme.darkAlgorithm : theme.defaultAlgorithm)(derive, map), ...(dark ? theme.darkAlgorithm : theme.defaultAlgorithm)(derive, map),
colorPrimary: seed.colorPrimary, colorPrimary: seed.colorPrimary,
colorInfo: seed.colorInfo, colorInfo: seed.colorInfo,
...(!palette.isPrototype && {
colorPrimaryHover: palette.hover,
colorPrimaryActive: palette.active,
colorPrimaryBg: palette.tint,
colorPrimaryBgHover: palette.tintHover,
colorPrimaryText: palette.accent,
colorPrimaryTextHover: palette.accent,
colorPrimaryTextActive: palette.accent,
colorLink: palette.accent,
colorLinkHover: palette.accent,
colorLinkActive: palette.accent,
}),
}; };
}, },
token: { token: {
...v5ShadowTokens, ...v5ShadowTokens,
colorPrimary: dark ? PROTOTYPE_DARK_PRIMARY : '#b96508', colorPrimary: palette.isPrototype
colorInfo: dark ? PROTOTYPE_DARK_PRIMARY : '#b96508', ? dark
? PROTOTYPE_DARK_PRIMARY
: PROTOTYPE_LIGHT_PRIMARY
: palette.normal,
colorInfo: dark ? PROTOTYPE_DARK_PRIMARY : PROTOTYPE_LIGHT_PRIMARY,
colorBgLayout: dark ? '#11151c' : '#f4f6f9', colorBgLayout: dark ? '#11151c' : '#f4f6f9',
colorBgContainer: dark ? '#1b212b' : '#ffffff', colorBgContainer: dark ? DARK_SURFACE : LIGHT_SURFACE,
colorText: dark ? '#e6ebf3' : '#263247', colorText: dark ? '#e6ebf3' : '#263247',
colorTextSecondary: dark ? '#8e9aaa' : '#7e8998', colorTextSecondary: dark ? '#8e9aaa' : '#7e8998',
colorBorderSecondary: dark ? '#2b333f' : '#e9edf2', colorBorderSecondary: dark ? '#2b333f' : '#e9edf2',
@@ -113,8 +127,22 @@ export const prototypeTheme = (dark) => ({
}, },
Menu: { Menu: {
itemHeight: 42, itemHeight: 42,
itemSelectedBg: dark ? '#382b1b' : '#fff3df', itemSelectedBg: palette.selectionBg,
itemSelectedColor: dark ? '#f2ad41' : '#a95d07', itemSelectedColor: palette.selectionText,
},
Button: {
colorPrimary: palette.normal,
colorPrimaryHover: palette.hover,
colorPrimaryActive: palette.active,
primaryColor: palette.onSolid,
},
Switch: {
colorPrimary: palette.normal,
colorPrimaryHover: palette.hover,
},
DatePicker: {
colorPrimary: palette.normal,
colorTextLightSolid: palette.onSolid,
}, },
Card: { headerFontSize: 15 }, Card: { headerFontSize: 15 },
Modal: { borderRadiusLG: 12 }, Modal: { borderRadiusLG: 12 },
@@ -128,10 +156,23 @@ const v5ComponentDefaults = {
drawer: { mask: { blur: false } }, drawer: { mask: { blur: false } },
}; };
function TokenBridge() { function TokenBridge({ palette }) {
const { token } = theme.useToken(); const { token } = theme.useToken();
useLayoutEffect(() => { useLayoutEffect(() => {
const values = { const values = {
'brand-accent': palette.accent,
'brand-selection-bg': palette.selectionBg,
'brand-selection-text': palette.selectionText,
'brand-on-primary': palette.onSolid,
'brand-notice-bg': palette.isPrototype
? 'var(--brand-notice-default-bg)'
: palette.tint,
'brand-notice-text': palette.isPrototype
? 'var(--brand-notice-default-text)'
: palette.selectionText,
'brand-notice-border': palette.isPrototype
? 'var(--brand-notice-default-border)'
: palette.tintHover,
'ui-color-white': '#fff', 'ui-color-white': '#fff',
'ui-color-black': '#000', 'ui-color-black': '#000',
...Object.fromEntries( ...Object.fromEntries(
@@ -216,7 +257,7 @@ function TokenBridge() {
} }
for (const [name, value] of Object.entries(values)) for (const [name, value] of Object.entries(values))
if (value != null) document.body.style.setProperty(`--${name}`, value); if (value != null) document.body.style.setProperty(`--${name}`, value);
}, [token]); }, [token, palette]);
return null; return null;
} }
@@ -237,14 +278,17 @@ export default function UiThemeProvider({ children }) {
return () => window.removeEventListener('theme-tokens-applied', update); return () => window.removeEventListener('theme-tokens-applied', update);
}, []); }, []);
// Re-read the computed brand when the existing CSS theme is applied. // Re-read the computed brand when the existing CSS theme is applied.
const config = useMemo(() => { const { config, palette } = useMemo(() => {
const result = prototypeTheme(dark);
// Keep existing configured brand previews and persistence in helpers/theme.js. // Keep existing configured brand previews and persistence in helpers/theme.js.
const brand = getComputedStyle(document.body) const brand = getComputedStyle(document.body)
.getPropertyValue('--brand-primary') .getPropertyValue('--brand-primary')
.trim(); .trim();
if (brand) result.token.colorPrimary = brand; const palette = resolveBrandPalette(
return result; brand,
dark,
dark ? DARK_SURFACE : LIGHT_SURFACE,
);
return { config: prototypeTheme(dark, palette), palette };
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [dark, revision]); }, [dark, revision]);
const language = normalizeLanguage(i18n.language); const language = normalizeLanguage(i18n.language);
@@ -281,7 +325,7 @@ export default function UiThemeProvider({ children }) {
return ( return (
<ConfigProvider {...v5ComponentDefaults} theme={config} locale={locale}> <ConfigProvider {...v5ComponentDefaults} theme={config} locale={locale}>
<App> <App>
<TokenBridge /> <TokenBridge palette={palette} />
{children} {children}
</App> </App>
</ConfigProvider> </ConfigProvider>
+4
View File
@@ -16,3 +16,7 @@ body[data-ui-scope='admin']
> label.ant-form-item-required::before { > label.ant-form-item-required::before {
font-family: SimSun, sans-serif; font-family: SimSun, sans-serif;
} }
.ant-switch.ant-switch-checked .ant-switch-inner-checked {
color: var(--brand-on-primary);
}
+24 -32
View File
@@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
import { import {
getUserIdFromLocalStorage, getUserIdFromLocalStorage,
redirectToExpiredLogin,
showError, showError,
formatMessageForAPI, formatMessageForAPI,
isValidMessage, isValidMessage,
@@ -29,6 +30,7 @@ import i18next from 'i18next';
import { MESSAGE_ROLES } from '../constants/playground.constants'; import { MESSAGE_ROLES } from '../constants/playground.constants';
import { getServerURL } from './config'; import { getServerURL } from './config';
import { buildGetRequestKey, getHeaderValue } from './requestDedupe'; import { buildGetRequestKey, getHeaderValue } from './requestDedupe';
import { installRequestLifecycle } from './requestLifecycle';
function createAPIInstance() { function createAPIInstance() {
const serverURL = getServerURL(); const serverURL = getServerURL();
@@ -41,14 +43,20 @@ function createAPIInstance() {
}); });
} }
export let API = createAPIInstance(); export let API;
let retireAPI;
function patchAPIInstance(instance) { function patchAPIInstance(instance) {
const originalGet = instance.get.bind(instance); const originalGet = instance.get.bind(instance);
const inFlightGetRequests = new Map(); const inFlightGetRequests = new Map();
instance.get = (url, config = {}) => { instance.get = (url, config = {}) => {
if (config?.disableDuplicate) { if (
config?.disableDuplicate ||
config?.signal ||
config?.cancelToken ||
config?.requestGroup
) {
return originalGet(url, config); return originalGet(url, config);
} }
@@ -56,12 +64,13 @@ function patchAPIInstance(instance) {
url.startsWith('/api/org/') && typeof localStorage !== 'undefined' url.startsWith('/api/org/') && typeof localStorage !== 'undefined'
? localStorage.getItem('current_org_id') || '' ? localStorage.getItem('current_org_id') || ''
: ''; : '';
const key = buildGetRequestKey( const requestKey = buildGetRequestKey(
url, url,
config, config,
fallbackOrgId, fallbackOrgId,
getUserIdFromLocalStorage(), getUserIdFromLocalStorage(),
); );
const key = `${requestKey}#error=${!config?.skipErrorHandler}#session=${config?.sessionBound !== false}`;
if (inFlightGetRequests.has(key)) { if (inFlightGetRequests.has(key)) {
return inFlightGetRequests.get(key); return inFlightGetRequests.get(key);
} }
@@ -75,23 +84,6 @@ function patchAPIInstance(instance) {
}; };
} }
patchAPIInstance(API);
// 添加 response interceptor 的函数
function addResponseInterceptor(instance) {
instance.interceptors.response.use(
(response) => response,
(error) => {
// 如果请求配置中显式要求跳过全局错误处理,则不弹出默认错误提示
if (error.config && error.config.skipErrorHandler) {
return Promise.reject(error);
}
showError(error);
return Promise.reject(error);
},
);
}
// 添加 request interceptor:自动为 /api/org/ 请求注入 X-Org-Id 头 // 添加 request interceptor:自动为 /api/org/ 请求注入 X-Org-Id 头
function addOrgHeaderInterceptor(instance) { function addOrgHeaderInterceptor(instance) {
instance.interceptors.request.use((config) => { instance.interceptors.request.use((config) => {
@@ -107,19 +99,21 @@ function addOrgHeaderInterceptor(instance) {
}); });
} }
// 初始化时添加 interceptor
addResponseInterceptor(API);
addOrgHeaderInterceptor(API);
export function updateAPI() { export function updateAPI() {
API = createAPIInstance(); const instance = createAPIInstance();
patchAPIInstance(instance);
patchAPIInstance(API); addOrgHeaderInterceptor(instance);
// 重新添加 interceptors const previous = retireAPI;
addResponseInterceptor(API); retireAPI = installRequestLifecycle(instance, {
addOrgHeaderInterceptor(API); onError: (error) => showError(error, { redirectOnUnauthorized: false }),
onSessionExpired: redirectToExpiredLogin,
});
API = instance;
previous?.();
} }
updateAPI();
// playground // playground
// 构建API请求负载 // 构建API请求负载
@@ -310,8 +304,6 @@ export const processGroupsData = (data, userGroup) => {
return groupOptions; return groupOptions;
}; };
// 原来components中的utils.js
export async function getOAuthState() { export async function getOAuthState() {
let path = '/api/oauth/state'; let path = '/api/oauth/state';
let affCode = localStorage.getItem('aff'); let affCode = localStorage.getItem('aff');
+1 -7
View File
@@ -25,11 +25,7 @@ import { StatusContext } from '../context/Status';
import { canAccessDelegatedAdminPage } from './adminDelegation'; import { canAccessDelegatedAdminPage } from './adminDelegation';
import { ADMIN_DELEGATION_OPTION_KEY } from '../constants/settingTabs'; import { ADMIN_DELEGATION_OPTION_KEY } from '../constants/settingTabs';
import Loading from '../components/common/ui/Loading'; import Loading from '../components/common/ui/Loading';
import { import { getUserData, isSafePostLoginRedirect } from './data';
getUserData,
isSafePostLoginRedirect,
savePostLoginRedirect,
} from './data';
import { authRedirectTarget } from './authRedirect'; import { authRedirectTarget } from './authRedirect';
/** /**
@@ -49,11 +45,9 @@ export const isAuthPagePath = (pathname) =>
/^\/org\/[^/]+\/login$/.test(pathname); /^\/org\/[^/]+\/login$/.test(pathname);
// 未登录统一引导到企业登录(本产品主推企业用户;个人用户可经页内切换回 /login)。 // 未登录统一引导到企业登录(本产品主推企业用户;个人用户可经页内切换回 /login)。
// 回跳地址已存本地(savePostLoginRedirect),切换到个人登录后仍可正常回跳。
const getLoginTarget = (location) => { const getLoginTarget = (location) => {
const target = `${location.pathname}${location.search}${location.hash}`; const target = `${location.pathname}${location.search}${location.hash}`;
if (isSafePostLoginRedirect(target)) { if (isSafePostLoginRedirect(target)) {
savePostLoginRedirect(target);
return `/org/login?redirect=${encodeURIComponent(target)}`; return `/org/login?redirect=${encodeURIComponent(target)}`;
} }
return '/org/login'; return '/org/login';
+126
View File
@@ -0,0 +1,126 @@
/*
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 { colord, extend } from 'colord';
import a11yPlugin from 'colord/plugins/a11y';
import mixPlugin from 'colord/plugins/mix';
extend([a11yPlugin, mixPlugin]);
export const PROTOTYPE_LIGHT_PRIMARY = '#b96508';
export const PROTOTYPE_DARK_PRIMARY = '#d1963a';
export const PROTOTYPE_DARK_SEED = '#f2ad41';
const clamp = (value, low, high) => Math.min(high, Math.max(low, value));
function toneAtContrast(color, surface, minimum, lighter) {
const { h: hue, s: saturation } = color.toHsl();
const tone = (lightness) => colord({ h: hue, s: saturation, l: lightness });
let low = 0;
let high = 100;
for (let step = 0; step < 12; step++) {
const middle = (low + high) / 2;
if (tone(middle).contrast(surface) >= minimum === lighter) high = middle;
else low = middle;
}
return tone(lighter ? high : low);
}
const readable = (color, surface, dark) =>
color.contrast(surface) >= 4.7
? color
: toneAtContrast(color, surface, 4.7, dark);
export function resolveBrandPalette(configured, dark, surface) {
const prototype = dark ? PROTOTYPE_DARK_PRIMARY : PROTOTYPE_LIGHT_PRIMARY;
const parsed = colord(configured);
const input = parsed.isValid() ? parsed.alpha(1) : colord(prototype);
const isPrototype = input.toHex() === prototype;
const hsl = input.toHsl();
const seed = isPrototype
? input
: colord({ ...hsl, s: Math.min(hsl.s, 68), l: clamp(hsl.l, 28, 70) });
const onSolid = dark ? '#11151c' : '#ffffff';
let normal;
let hover;
let active;
if (dark) {
const base = seed.contrast(onSolid);
const target = clamp(base, 5.3, isPrototype ? 7.2 : 6.45);
const fill = (ratio) => toneAtContrast(seed, onSolid, ratio, true);
normal = base === target ? seed : fill(target);
hover = fill(target + 0.5);
active = fill(target - 0.55);
} else {
normal = readable(seed, onSolid, false);
hover = normal.darken(0.035);
active = normal.darken(0.07);
}
const backdrop = colord(surface);
const tint = backdrop.mix(normal, dark ? 0.14 : 0.085);
const tintHover = backdrop.mix(normal, dark ? 0.2 : 0.135);
const ink = readable(normal, tintHover, dark).toHex();
return {
isPrototype,
onSolid,
normal: normal.toHex(),
hover: hover.toHex(),
active: active.toHex(),
accent: isPrototype ? (dark ? PROTOTYPE_DARK_SEED : prototype) : ink,
selectionBg: isPrototype ? (dark ? '#382b1b' : '#fff3df') : tint.toHex(),
selectionText: isPrototype ? (dark ? PROTOTYPE_DARK_SEED : '#a45a07') : ink,
tint: tint.toHex(),
tintHover: tintHover.toHex(),
};
}
export function resolveGradientLabel(stops, surface) {
const backdrop = colord(surface);
const base = backdrop.toRgb();
const colors = stops.map((stop) => {
const parsed = colord(stop);
return parsed.isValid() ? parsed.toRgb() : base;
});
const composite = (channel, from, to, progress) =>
from[channel] * from.a * (1 - progress) +
to[channel] * to.a * progress +
base[channel] * (1 - from.a * (1 - progress) - to.a * progress);
const samples = colors.flatMap((from, index) => {
const to = colors[index + 1] ?? from;
return [0, 0.25, 0.5, 0.75].map((progress) =>
colord({
r: composite('r', from, to, progress),
g: composite('g', from, to, progress),
b: composite('b', from, to, progress),
}),
);
});
const inks = ['#ffffff', '#11151c'];
const minimum = (ink) =>
Math.min(...samples.map((sample) => sample.contrast(ink)));
const chosen = minimum(inks[0]) >= minimum(inks[1]) ? inks[0] : inks[1];
if (samples.length > 0 && minimum(chosen) >= 4.5) return { color: chosen };
return {
color:
backdrop.contrast(inks[0]) >= backdrop.contrast(inks[1])
? inks[0]
: inks[1],
background: backdrop.toHex(),
};
}
+35 -3
View File
@@ -145,11 +145,43 @@ export function isSafePostLoginRedirect(path) {
export function savePostLoginRedirect(path) { export function savePostLoginRedirect(path) {
if (isSafePostLoginRedirect(path)) { if (isSafePostLoginRedirect(path)) {
sessionStorage.setItem(POST_LOGIN_REDIRECT_KEY, path); sessionStorage.setItem(POST_LOGIN_REDIRECT_KEY, path);
} else {
sessionStorage.removeItem(POST_LOGIN_REDIRECT_KEY);
} }
} }
export function consumePostLoginRedirect(defaultPath = DEFAULT_LOGIN_REDIRECT) { export function consumePostLoginRedirect({
const path = sessionStorage.getItem(POST_LOGIN_REDIRECT_KEY); redirect = sessionStorage.getItem(POST_LOGIN_REDIRECT_KEY),
enterprise = false,
orgOnly = false,
} = {}) {
sessionStorage.removeItem(POST_LOGIN_REDIRECT_KEY); sessionStorage.removeItem(POST_LOGIN_REDIRECT_KEY);
return isSafePostLoginRedirect(path) ? path : defaultPath; const fallback = enterprise
? '/org/workbench'
: orgOnly
? '/org'
: DEFAULT_LOGIN_REDIRECT;
if (!isSafePostLoginRedirect(redirect)) return fallback;
let normalizedPath;
try {
const base = 'https://login.invalid';
const target = new URL(redirect, base);
if (target.origin !== base) return fallback;
normalizedPath =
decodeURI(target.pathname).toLowerCase().replace(/\/+$/, '') || '/';
} catch {
return fallback;
}
if (
!isSafePostLoginRedirect(normalizedPath) ||
normalizedPath === '/forbidden' ||
normalizedPath === '/user/reset'
)
return fallback;
if (!enterprise && !orgOnly && /^\/org(?:\/|$)/.test(normalizedPath))
return fallback;
if ((enterprise || orgOnly) && /^\/console(?:\/|$)/.test(normalizedPath))
return fallback;
return redirect;
} }
+16 -17
View File
@@ -19,7 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
import { API, updateAPI } from './api'; import { API, updateAPI } from './api';
import { clearUserData, consumePostLoginRedirect, setUserData } from './data'; import { clearUserData, consumePostLoginRedirect, setUserData } from './data';
import { showError, showSuccess } from './utils'; import { showError } from './utils';
const SESSION_NOT_PERSISTED_MESSAGE = const SESSION_NOT_PERSISTED_MESSAGE =
'登录成功但浏览器未能保存登录会话,请确认 Cookie 未被拦截后重试'; '登录成功但浏览器未能保存登录会话,请确认 Cookie 未被拦截后重试';
@@ -35,8 +35,8 @@ export async function finishLogin({
userDispatch, userDispatch,
navigate, navigate,
t = (s) => s, t = (s) => s,
successMessage, redirect,
redirectOverride, enterprise = false,
}) { }) {
setUserData(data); setUserData(data);
// Recreate the axios instance so any in-flight request map from a prior // Recreate the axios instance so any in-flight request map from a prior
@@ -49,7 +49,11 @@ export async function finishLogin({
skipErrorHandler: true, skipErrorHandler: true,
disableDuplicate: true, disableDuplicate: true,
}); });
if (!res.data?.success || !res.data?.data) { if (
!res.data?.success ||
data?.id == null ||
String(res.data?.data?.id) !== String(data.id)
) {
throw new Error(res.data?.message || 'session verify failed'); throw new Error(res.data?.message || 'session verify failed');
} }
verifiedUser = res.data.data; verifiedUser = res.data.data;
@@ -64,18 +68,13 @@ export async function finishLogin({
setUserData(verifiedUser); setUserData(verifiedUser);
userDispatch({ type: 'login', payload: verifiedUser }); userDispatch({ type: 'login', payload: verifiedUser });
const message = navigate(
successMessage === undefined ? t('登录成功!') : successMessage; consumePostLoginRedirect({
if (message) { redirect,
showSuccess(message); enterprise,
} orgOnly: verifiedUser.org_only_mode === true,
// org_only(仅企业资源)用户默认落企业空间,与 AuthRedirect 一致:默认落地页 }),
// (密钥管理)挂载即调用被 BlockOrgOnlyMode 拦截的 /api/token,会先弹报错再被 { replace: true },
// orgConfined 踢回 /org;企业中心整体关闭时 orgConfined 不生效,会一直停在报错页 );
const defaultRedirect =
verifiedUser.org_only_mode === true ? '/org' : undefined;
navigate(redirectOverride ?? consumePostLoginRedirect(defaultRedirect), {
replace: true,
});
return true; return true;
} }
+109
View File
@@ -0,0 +1,109 @@
/*
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 { 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']);
function isSessionBound(config) {
const pathname = config?.url?.split(/[?#]/, 1)[0];
return (
config?.sessionBound !== false &&
pathname?.startsWith('/api/') &&
!PUBLIC_API_PATH.test(pathname)
);
}
function combineSignals(signals, config, cleanups) {
const inputs = [...new Set(signals.filter(Boolean))];
if (inputs.length < 2) return inputs[0];
if (typeof AbortSignal.any === 'function') return AbortSignal.any(inputs);
const controller = new AbortController();
const abort = () => controller.abort();
for (const input of inputs) {
if (input.aborted) abort();
else input.addEventListener('abort', abort, { once: true });
}
cleanups.set(config, () => {
for (const input of inputs) input.removeEventListener('abort', abort);
});
return controller.signal;
}
export function installRequestLifecycle(
instance,
{ onError, onSessionExpired },
) {
const session = new AbortController();
const cleanups = new WeakMap();
instance.interceptors.request.use((config) => {
const sessionBound = isSessionBound(config);
const read = READ_METHODS.has(config.method);
const groupSignal = read ? config.requestGroup?.signal : undefined;
if ((sessionBound && session.signal.aborted) || groupSignal?.aborted) {
throw new CanceledError(undefined, config);
}
config.signal = combineSignals(
[config.signal, read && sessionBound && session.signal, groupSignal],
config,
cleanups,
);
return config;
});
const cleanup = (config) => {
cleanups.get(config)?.();
cleanups.delete(config);
};
instance.interceptors.response.use(
(response) => {
cleanup(response.config);
return response;
},
(error) => {
const { config, response } = error;
cleanup(config);
const sessionBound = isSessionBound(config);
const read = READ_METHODS.has(config?.method);
if (isCancel(error)) throw error;
if (sessionBound && session.signal.aborted) {
if (read) throw new CanceledError(undefined, config);
throw error;
}
if (response?.status >= 400 && read) config.requestGroup?.abort();
if (!config?.skipErrorHandler) {
if (response?.status === 401 && sessionBound) {
session.abort();
onSessionExpired();
} else {
onError(error);
}
}
throw error;
},
);
return () => session.abort();
}
+52
View File
@@ -0,0 +1,52 @@
/*
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 const toFiniteNumber = (value) => {
if (value === null || value === undefined || value === '') return null;
const number = Number(value);
return Number.isFinite(number) ? number : null;
};
export const formatPercent = (value, digits = 1, fallback = '-') => {
const number = toFiniteNumber(value);
return number === null ? fallback : `${number.toFixed(digits)}%`;
};
export const formatRatioPercent = (part, total, digits = 1, fallback = '-') => {
const numerator = toFiniteNumber(part);
const denominator = toFiniteNumber(total);
if (numerator === null || denominator === null || denominator <= 0) {
return fallback;
}
return formatPercent((numerator / denominator) * 100, digits, fallback);
};
export const formatUserReference = (name, id, fallback = '-') => {
const displayName = typeof name === 'string' ? name.trim() : name;
if (displayName) return String(displayName);
const userId = toFiniteNumber(id);
return userId === null ? fallback : `User#${userId}`;
};
export const formatIdReference = (id, fallback = '-') => {
if (id === null || id === undefined || id === '') return fallback;
const value = String(id).trim();
return value ? `#${value}` : fallback;
};
+52 -49
View File
@@ -28,12 +28,7 @@ import {
import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile'; import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile';
// 官方价折扣计算(纯函数):管理端与市场页共用 // 官方价折扣计算(纯函数):管理端与市场页共用
import { buildOfficialComparison, formatDiscountLabel } from './officialPrice'; import { buildOfficialComparison, formatDiscountLabel } from './officialPrice';
import { import { clearUserData, getUserData, isSafePostLoginRedirect } from './data';
clearUserData,
getUserData,
isSafePostLoginRedirect,
savePostLoginRedirect,
} from './data';
const HTMLToastContent = ({ htmlContent }) => { const HTMLToastContent = ({ htmlContent }) => {
return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />; return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
@@ -128,56 +123,64 @@ if (isMobileScreen) {
// showNoticeOptions.transition = 'flip'; // showNoticeOptions.transition = 'flip';
} }
export function showError(error) { let redirectingToLogin = false;
console.error(error); const reportedRequestErrors = new WeakSet();
if (error.message) {
if (error.name === 'AxiosError') { export function redirectToExpiredLogin() {
// 检查 response 是否存在(网络错误时 response 为 undefined) if (redirectingToLogin) return;
if (!error.response) { redirectingToLogin = true;
Toast.error(i18next.t('错误:网络请求失败,请检查网络连接'));
return;
}
switch (error.response.status) {
case 401:
// 清除用户状态
clearUserData(); clearUserData();
const currentPath = `${window.location.pathname}${window.location.search}${window.location.hash}`; const { pathname, search, hash } = window.location;
const currentPath = `${pathname}${search}${hash}`;
const redirect = isSafePostLoginRedirect(currentPath) const redirect = isSafePostLoginRedirect(currentPath)
? `&redirect=${encodeURIComponent(currentPath)}` ? `&redirect=${encodeURIComponent(currentPath)}`
: ''; : '';
if (redirect) { window.location.replace(`/org/login?expired=true${redirect}`);
savePostLoginRedirect(currentPath); }
}
// toast.error('错误:未登录或登录已过期,请重新登录!', showErrorOptions); export function showError(error, { redirectOnUnauthorized = true } = {}) {
// 会话过期统一回企业登录(默认登录入口),OrgLogin 会识别 expired/redirect 参数 if (
window.location.href = `/org/login?expired=true${redirect}`; error?.code === 'ERR_CANCELED' ||
break; error === 'canceled' ||
case 429: (redirectingToLogin && error === 'Request failed with status code 401')
Toast.error(i18next.t('错误:请求次数过多,请稍后再试!')); )
break; return;
case 500:
Toast.error(i18next.t('错误:服务器内部错误,请联系管理员!')); if (error?.isAxiosError || error?.name === 'AxiosError') {
break; if (reportedRequestErrors.has(error)) return;
case 405: reportedRequestErrors.add(error);
Toast.info(i18next.t('本站仅作演示之用,无服务端!'));
break; const status = error.response?.status;
default: { if (status === 401 && redirectOnUnauthorized) {
// 后端业务错误(4xx/5xx)带有面向用户的 message 字段; redirectToExpiredLogin();
// 优先展示它,而不是 axios 的 "Request failed with status code XXX"。
const backendMessage = error.response?.data?.message;
Toast.error(
i18next.t('错误:{{message}}', {
message: backendMessage || error.message,
}),
);
}
}
return; return;
} }
Toast.error(i18next.t('错误:{{message}}', { message: error.message })); if (status === 405) {
} else { Toast.info({
Toast.error(i18next.t('错误:{{message}}', { message: error })); key: 'http-error:405',
content: i18next.t('本站仅作演示之用,无服务端!'),
});
return;
} }
let content;
if (!error.response) {
content = i18next.t('错误:网络请求失败,请检查网络连接');
} else if (status === 429) {
content = i18next.t('错误:请求次数过多,请稍后再试!');
} else if (status === 500) {
content = i18next.t('错误:服务器内部错误,请联系管理员!');
} else {
content = i18next.t('错误:{{message}}', {
message: error.response.data?.message || error.message,
});
}
Toast.error({ key: `http-error:${content}`, content });
return;
}
console.error(error);
Toast.error(
i18next.t('错误:{{message}}', { message: error?.message || error }),
);
} }
export function showWarning(message) { export function showWarning(message) {
+3 -3
View File
@@ -28,7 +28,7 @@ import {
getSystemName, getSystemName,
API, API,
clearUserData, clearUserData,
showSuccess, updateAPI,
} from '../../helpers'; } from '../../helpers';
import { rememberUserLanguage } from '../../i18n/bootstrap'; import { rememberUserLanguage } from '../../i18n/bootstrap';
import { useIsMobile } from './useIsMobile'; import { useIsMobile } from './useIsMobile';
@@ -163,11 +163,11 @@ export const useHeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
// Actions // Actions
const logout = useCallback(async () => { const logout = useCallback(async () => {
await API.get('/api/user/logout'); await API.get('/api/user/logout');
showSuccess(t('注销成功!'));
userDispatch({ type: 'logout' }); userDispatch({ type: 'logout' });
clearUserData(); clearUserData();
updateAPI();
navigate('/org/login'); navigate('/org/login');
}, [navigate, t, userDispatch]); }, [navigate, userDispatch]);
const handleLanguageChange = useCallback( const handleLanguageChange = useCallback(
(lang) => { (lang) => {
@@ -276,11 +276,6 @@ export const useRedemptionsData = () => {
// Close edit modal // Close edit modal
const closeEdit = () => { const closeEdit = () => {
setShowEdit(false); setShowEdit(false);
setTimeout(() => {
setEditingRedemption({
id: undefined,
});
}, 500);
}; };
// Remove record (for UI update after deletion) // Remove record (for UI update after deletion)
+85 -97
View File
@@ -16,24 +16,21 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatUserReference } from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { import {
Eye as ActionEye, ConsoleFilterField,
Check as ActionCheck, ConsoleFilterGrid,
X as ActionX, ConsoleListTable,
Ban as ActionBan,
RotateCw as ActionRotateCw,
} from '@/components/common/icons/ActionIcons';
import {
ConsoleCard,
ConsoleSearchBar,
ConsoleSearchActions,
} from '../../components/console/ConsolePrimitives'; } from '../../components/console/ConsolePrimitives';
import ConsoleCollection from '../../components/console/ConsoleCollection';
import { TableRowActions } from '../../components/common/table/TableToolbar';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../helpers/utils';
import React, { useEffect, useState, useCallback } from 'react'; import React, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { import {
Table,
Button, Button,
Input, Input,
Tag, Tag,
@@ -63,6 +60,7 @@ const paymentMethodMap = {
const AdminInvoice = () => { const AdminInvoice = () => {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const isMobile = useIsMobile();
const [invoices, setInvoices] = useState([]); const [invoices, setInvoices] = useState([]);
const [total, setTotal] = useState(0); const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -118,6 +116,13 @@ const AdminInvoice = () => {
setSearchKeyword(keyword); setSearchKeyword(keyword);
}; };
const handleReset = () => {
setPage(1);
setKeyword('');
setSearchKeyword('');
setStatusFilter('');
};
const handleStatusFilterChange = (value) => { const handleStatusFilterChange = (value) => {
setPage(1); setPage(1);
setStatusFilter(value || ''); setStatusFilter(value || '');
@@ -301,100 +306,83 @@ const AdminInvoice = () => {
}, },
{ {
title: t('操作'), title: t('操作'),
width: 200, key: 'actions',
width: 140,
fixed: 'right', fixed: 'right',
render: (_, record) => ( render: (_, record) => (
<div className='flex items-center gap-1 flex-wrap'> <TableRowActions
<Button items={[
size='small' record.status === INVOICE_STATUS.PENDING && {
theme='borderless' key: 'approve',
icon={<ActionEye size={14} />} label: t('通过'),
onClick={() => handleViewDetail(record.id)} onClick: () => {
/>
{record.status === INVOICE_STATUS.PENDING && (
<>
<Button
size='small'
theme='borderless'
type='primary'
icon={<ActionCheck size={14} />}
onClick={() => {
setApproveId(record.id); setApproveId(record.id);
setApproveVisible(true); setApproveVisible(true);
}} },
> },
{t('通过')} record.status === INVOICE_STATUS.PENDING && {
</Button> key: 'reject',
<Button label: t('拒绝'),
size='small' danger: true,
theme='borderless' onClick: () => {
type='danger'
icon={<ActionX size={14} />}
onClick={() => {
setRejectId(record.id); setRejectId(record.id);
setRejectVisible(true); setRejectVisible(true);
}} },
},
record.status === INVOICE_STATUS.FAILED && {
key: 'retry',
label: t('重试'),
onClick: () => handleRetry(record.id),
},
[
INVOICE_STATUS.APPROVED,
INVOICE_STATUS.INVOICING,
INVOICE_STATUS.FAILED,
].includes(record.status) && {
key: 'cancel',
label: t('取消'),
danger: true,
onClick: () => handleFailCancel(record.id),
},
]}
> >
{t('拒绝')}
</Button>
</>
)}
{(record.status === INVOICE_STATUS.APPROVED ||
record.status === INVOICE_STATUS.INVOICING) && (
<Button <Button
type='link'
size='small' size='small'
theme='borderless' onClick={() => handleViewDetail(record.id)}
type='danger'
icon={<ActionBan size={14} />}
onClick={() => handleFailCancel(record.id)}
> >
{t('取消')} {t('详情')}
</Button> </Button>
)} </TableRowActions>
{record.status === INVOICE_STATUS.FAILED && (
<>
<Button
size='small'
theme='borderless'
icon={<ActionRotateCw size={14} />}
onClick={() => handleRetry(record.id)}
>
{t('重试')}
</Button>
<Button
size='small'
theme='borderless'
type='danger'
icon={<ActionBan size={14} />}
onClick={() => handleFailCancel(record.id)}
>
{t('取消')}
</Button>
</>
)}
</div>
), ),
}, },
]; ];
return ( return (
<div className='console-content'> <div className='console-content'>
{/* 筛选区:标题与筛选项同行 */} <ConsoleCollection
<ConsoleSearchBar formProps={{ layout: 'inline' }}> searchArea={
<div className='console-search-fields'> <ConsoleFilterGrid
onReset={handleReset}
onSearch={handleSearch}
loading={loading}
>
<ConsoleFilterField label={t('搜索关键字')} id='invoice-keyword'>
<Input <Input
id='invoice-keyword'
prefix={<Search size={14} />} prefix={<Search size={14} />}
placeholder={t('搜索抬头/税号/订单号/用户')} placeholder={t('搜索抬头/税号/订单号/用户')}
value={keyword} value={keyword}
onChange={setKeyword} onChange={setKeyword}
onEnterPress={handleSearch} onEnterPress={handleSearch}
style={{ width: 240 }}
/> />
</ConsoleFilterField>
<ConsoleFilterField label={t('状态')} id='invoice-status'>
<Select <Select
id='invoice-status'
placeholder={t('状态')} placeholder={t('状态')}
value={statusFilter || undefined} value={statusFilter || undefined}
onChange={handleStatusFilterChange} onChange={handleStatusFilterChange}
style={{ width: 120 }}
allowClear allowClear
optionList={[ optionList={[
{ label: t('待审核'), value: '1' }, { label: t('待审核'), value: '1' },
@@ -406,33 +394,30 @@ const AdminInvoice = () => {
{ label: t('开票失败'), value: '7' }, { label: t('开票失败'), value: '7' },
]} ]}
/> />
<ConsoleSearchActions onSearch={handleSearch} loading={loading} /> </ConsoleFilterField>
</div> </ConsoleFilterGrid>
</ConsoleSearchBar> }
paginationArea={createCardProPagination({
{/* 表格 */}
<ConsoleCard>
<Table
columns={columns}
dataSource={invoices}
loading={loading}
rowKey='id'
pagination={{
currentPage: page, currentPage: page,
total,
pageSize, pageSize,
total,
onPageChange: setPage, onPageChange: setPage,
onPageSizeChange: (size) => { onPageSizeChange: (size) => {
setPage(1); setPage(1);
setPageSize(size); setPageSize(size);
}, },
showTotal: true, isMobile,
}} t,
scroll={{ x: 1100 }} })}
size='middle' >
empty={t('暂无发票数据')} <ConsoleListTable
columns={columns}
dataSource={invoices}
loading={loading}
rowKey='id'
pagination={false}
/> />
</ConsoleCard> </ConsoleCollection>
{/* 审核通过弹窗 */} {/* 审核通过弹窗 */}
<Modal <Modal
@@ -510,7 +495,10 @@ const AdminInvoice = () => {
<div> <div>
{detailData.display_name || {detailData.display_name ||
detailData.username || detailData.username ||
`User#${detailData.user_id}`} formatUserReference(
detailData.display_name || detailData.username,
detailData.user_id,
)}
</div> </div>
</div> </div>
<div> <div>
+59 -82
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { TableRowActions } from '@/components/common/table/TableToolbar';
import { import {
ExternalLink as ActionExternalLink, ExternalLink as ActionExternalLink,
BarChart3 as ActionBarChart3, BarChart3 as ActionBarChart3,
@@ -852,11 +853,62 @@ const AdminOrganizations = () => {
}, },
{ {
title: t('操作'), title: t('操作'),
width: 380, key: 'actions',
render: (_, record) => ( width: 140,
<div className='console-module-row-actions'> fixed: 'right',
{isAdmin() && ( render: (_, record) =>
<> isAdmin() ? (
<TableRowActions
items={[
{
key: 'quota',
label: t('调额'),
onClick: () => {
setQuotaOrgId(record.id);
setQuotaAmount(0);
setQuotaModalVisible(true);
},
},
{
key: 'features',
label: t('功能开关'),
onClick: () => openFeatureModal(record),
},
{
key: 'status',
label:
record.status === 4
? t('激活')
: record.status === 1
? t('冻结')
: t('解冻'),
onClick: () =>
record.status === 4
? handleActivate(record.id)
: handleStatusChange(
record.id,
record.status === 1 ? 2 : 1,
),
},
isRoot() && {
key: 'notifications',
disabled: alertToggleLoading === record.id,
label: alertExcludedIds.has(record.id)
? t('恢复通知')
: t('屏蔽通知'),
title: alertExcludedIds.has(record.id)
? t('已屏蔽预警,点击恢复')
: t('屏蔽该企业的预警通知'),
onClick: () => toggleAlertExclude(record),
},
{
key: 'delete',
label: t('删除'),
danger: true,
onClick: () => handleDelete(record.id),
},
]}
>
<Button <Button
type='link' type='link'
size='small' size='small'
@@ -864,83 +916,8 @@ const AdminOrganizations = () => {
> >
{t('编辑')} {t('编辑')}
</Button> </Button>
<Button </TableRowActions>
type='link' ) : null,
size='small'
onClick={() => {
setQuotaOrgId(record.id);
setQuotaAmount(0);
setQuotaModalVisible(true);
}}
>
{t('调额')}
</Button>
<Button
type='link'
size='small'
onClick={() => openFeatureModal(record)}
>
{t('功能开关')}
</Button>
{record.status === 4 ? (
<Button
size='small'
type='link'
onClick={() => handleActivate(record.id)}
>
{t('激活')}
</Button>
) : record.status === 1 ? (
<Button
size='small'
type='link'
onClick={() => handleStatusChange(record.id, 2)}
>
{t('冻结')}
</Button>
) : (
<Button
size='small'
type='link'
onClick={() => handleStatusChange(record.id, 1)}
>
{t('解冻')}
</Button>
)}
<Button
type='link'
size='small'
danger
onClick={() => handleDelete(record.id)}
>
{t('删除')}
</Button>
{isRoot() && (
<Button
size='small'
type='link'
loading={alertToggleLoading === record.id}
title={
alertExcludedIds.has(record.id)
? t('已屏蔽预警,点击恢复')
: t('屏蔽该企业的预警通知')
}
aria-label={
alertExcludedIds.has(record.id)
? t('恢复该企业的预警')
: t('屏蔽该企业的预警')
}
onClick={() => toggleAlertExclude(record)}
>
{alertExcludedIds.has(record.id)
? t('恢复通知')
: t('屏蔽通知')}
</Button>
)}
</>
)}
</div>
),
}, },
]; ];
+2 -2
View File
@@ -522,8 +522,8 @@
两列都给定上限并整体居中——否则宽屏下 1fr 撑满而 composer 自身 两列都给定上限并整体居中——否则宽屏下 1fr 撑满而 composer 自身
max-width 封顶,右侧会空出一大片(用户反馈:大面积空白)。 */ max-width 封顶,右侧会空出一大片(用户反馈:大面积空白)。 */
.brain-expert-layout.is-composing { .brain-expert-layout.is-composing {
grid-template-columns: minmax(220px, 280px) minmax(0, 860px); grid-template-columns: minmax(220px, 280px) minmax(0, 1fr);
justify-content: center; justify-content: start;
} }
.brain-expert-grid { .brain-expert-grid {
display: grid; display: grid;
+13 -6
View File
@@ -16,6 +16,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { formatPercent } from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
@@ -1611,7 +1613,7 @@ const CloudBrain = ({ organization = false, orgId = 0, canManage = false }) => {
} }
if (assignmentScope === 'member') { if (assignmentScope === 'member') {
return members.map((item) => ({ return members.map((item) => ({
label: item.display_name || item.username || `#${item.id}`, label: item.display_name || item.username || formatIdReference(item.id),
value: item.id, value: item.id,
})); }));
} }
@@ -1640,9 +1642,11 @@ const CloudBrain = ({ organization = false, orgId = 0, canManage = false }) => {
) )
.map((item) => ({ .map((item) => ({
...item, ...item,
expert_name: expertNameById.get(item.expert_id) || `#${item.expert_id}`, expert_name:
expertNameById.get(item.expert_id) ||
formatIdReference(item.expert_id),
scope_type_label: scopeTypeLabel[item.scope_type] || item.scope_type, scope_type_label: scopeTypeLabel[item.scope_type] || item.scope_type,
scope_label: item.scope_name || `#${item.scope_id}`, scope_label: item.scope_name || formatIdReference(item.scope_id),
})); }));
}, [assignments, expertCatalog, t]); }, [assignments, expertCatalog, t]);
@@ -1882,7 +1886,9 @@ const CloudBrain = ({ organization = false, orgId = 0, canManage = false }) => {
</div> </div>
<div> <div>
<span>{t('任务完成率')}</span> <span>{t('任务完成率')}</span>
<strong>{(metrics.completion_rate * 100).toFixed(1)}%</strong> <strong>
{formatPercent(Number(metrics.completion_rate) * 100, 1)}
</strong>
</div> </div>
<div> <div>
<span>{t('平均耗时')}</span> <span>{t('平均耗时')}</span>
@@ -1892,7 +1898,7 @@ const CloudBrain = ({ organization = false, orgId = 0, canManage = false }) => {
<span>{t('用户认可率')}</span> <span>{t('用户认可率')}</span>
<strong> <strong>
{metrics.feedback_count {metrics.feedback_count
? `${(metrics.useful_rate * 100).toFixed(1)}%` ? formatPercent(Number(metrics.useful_rate) * 100, 1)
: '—'} : '—'}
</strong> </strong>
</div> </div>
@@ -2702,7 +2708,8 @@ const CloudBrain = ({ organization = false, orgId = 0, canManage = false }) => {
<b>[{citation.citation_id}]</b> <b>[{citation.citation_id}]</b>
<span>{citation.source_label}</span> <span>{citation.source_label}</span>
<small> <small>
{t('相关度')} {(citation.score * 100).toFixed(1)}% {t('相关度')}{' '}
{formatPercent(Number(citation.score) * 100, 1)}
</small> </small>
</div> </div>
))} ))}
+4 -2
View File
@@ -16,6 +16,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { formatUserReference } from '../../helpers/safeDisplay';
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Button, Descriptions, Spin, Tag } from 'antd'; import { Button, Descriptions, Spin, Tag } from 'antd';
@@ -112,7 +114,7 @@ export default function PartnerDetail({
['主体类型', commissionLabel(t, 'partnerType', row.type)], ['主体类型', commissionLabel(t, 'partnerType', row.type)],
['状态', commissionLabel(t, 'status', row.status)], ['状态', commissionLabel(t, 'status', row.status)],
['伙伴名称', row.name], ['伙伴名称', row.name],
['登录主体', `#${row.user_id}`], ['登录主体', formatUserReference('', row.user_id, t('未知用户'))],
['证件号码', row.identity_no], ['证件号码', row.identity_no],
['联系人', row.contact_name], ['联系人', row.contact_name],
['联系电话', row.contact_phone], ['联系电话', row.contact_phone],
@@ -150,7 +152,7 @@ export default function PartnerDetail({
{ {
title: t('客户'), title: t('客户'),
render: (_, item) => render: (_, item) =>
item.customer_name || `#${item.subject_id}`, item.customer_name || formatIdReference(item.subject_id),
}, },
{ {
title: t('类型'), title: t('类型'),
+22 -24
View File
@@ -16,7 +16,9 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React, { import React, {
useCallback, useCallback,
useEffect, useEffect,
@@ -494,9 +496,25 @@ export default function PartnerPortal({
}, },
{ {
title: t('操作'), title: t('操作'),
width: 230, width: 175,
render: (_, row) => ( render: (_, row) => (
<div className='partner-portal-row-actions'> <TableRowActions
items={[
{
key: 'export',
label: t('导出'),
disabled: exportingId !== null || mutationLoading,
onClick: () => exportStatement(row),
},
row.status === 'pending_confirmation' && {
key: 'reject',
label: t('驳回'),
danger: true,
disabled: mutationLoading,
onClick: () => open(row, 'reject'),
},
]}
>
<Button <Button
type='link' type='link'
size='small' size='small'
@@ -506,7 +524,6 @@ export default function PartnerPortal({
{t('查看')} {t('查看')}
</Button> </Button>
{row.status === 'pending_confirmation' && ( {row.status === 'pending_confirmation' && (
<>
<Button <Button
type='link' type='link'
size='small' size='small'
@@ -515,27 +532,8 @@ export default function PartnerPortal({
> >
{t('确认')} {t('确认')}
</Button> </Button>
<Button
type='link'
size='small'
danger
disabled={mutationLoading}
onClick={() => open(row, 'reject')}
>
{t('驳回')}
</Button>
</>
)} )}
<Button </TableRowActions>
type='link'
size='small'
disabled={exportingId !== null || mutationLoading}
loading={exportingId === row.id}
onClick={() => exportStatement(row)}
>
{t('导出')}
</Button>
</div>
), ),
}, },
]; ];
@@ -887,7 +885,7 @@ export default function PartnerPortal({
<Users size={17} /> <Users size={17} />
</span> </span>
<span> <span>
{row.customer_name || `#${row.subject_id}`} ·{' '} {row.customer_name || formatIdReference(row.subject_id)} ·{' '}
{t('客户保护期临近到期')} {t('客户保护期临近到期')}
<small>{date(protectionUntil(row))}</small> <small>{date(protectionUntil(row))}</small>
</span> </span>
+66 -109
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import React, { import React, {
useCallback, useCallback,
@@ -56,7 +57,6 @@ import {
PencilLine, PencilLine,
ScrollText, ScrollText,
ShieldAlert, ShieldAlert,
ChevronDown,
} from 'lucide-react'; } from 'lucide-react';
import Dashboard from './Dashboard'; import Dashboard from './Dashboard';
import ListPanel from './ListPanel'; import ListPanel from './ListPanel';
@@ -65,20 +65,12 @@ import PartnerDetail from './PartnerDetail';
import PartnerPortal from './PartnerPortal'; import PartnerPortal from './PartnerPortal';
import { partnerScope, createPartnerTransport } from './partnerScope'; import { partnerScope, createPartnerTransport } from './partnerScope';
import { tierStatus } from './listFilters'; import { tierStatus } from './listFilters';
import { import { Button, DatePicker, Empty, Select, Spin, Tag, Typography } from 'antd';
Button,
DatePicker,
Dropdown,
Empty,
Select,
Spin,
Tag,
Typography,
} from 'antd';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { Plus, RefreshCw } from '../../components/common/icons/ActionIcons'; import { Plus, RefreshCw } from '../../components/common/icons/ActionIcons';
import { API } from '../../helpers'; import { API } from '../../helpers';
import * as XLSX from 'xlsx'; import * as XLSX from 'xlsx';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import './styles.css'; import './styles.css';
import { import {
OperationsDialog, OperationsDialog,
@@ -194,7 +186,7 @@ function TierSummary({ items }) {
const key = `${item.subject_type}:${item.subject_id}:${item.customer_name}:${item.tier_source}:${item.tier_key}:${item.group_name || item.group || ''}:${item.rate_bps}`; const key = `${item.subject_type}:${item.subject_id}:${item.customer_name}:${item.tier_source}:${item.tier_key}:${item.group_name || item.group || ''}:${item.rate_bps}`;
const value = groups.get(key) || { const value = groups.get(key) || {
id: key, id: key,
customer: item.customer_name || `#${item.subject_id || '—'}`, customer: item.customer_name || formatIdReference(item.subject_id, '—'),
tier: item.tier_name || item.tier_key || '—', tier: item.tier_name || item.tier_key || '—',
group: item.group_name || item.group || '—', group: item.group_name || item.group || '—',
rate_bps: item.rate_bps, rate_bps: item.rate_bps,
@@ -930,7 +922,9 @@ function AdminPage() {
dataIndex: 'user_id', dataIndex: 'user_id',
render: (value, row) => ( render: (value, row) => (
<EntityLabel <EntityLabel
name={entityNames.users.get(Number(value)) || `#${value}`} name={
entityNames.users.get(Number(value)) || formatIdReference(value)
}
reference={ reference={
row.organization_id row.organization_id
? entityNames.organizations.get(Number(row.organization_id)) ? entityNames.organizations.get(Number(row.organization_id))
@@ -990,26 +984,8 @@ function AdminPage() {
title: t('操作'), title: t('操作'),
width: 175, width: 175,
render: (_, row) => ( render: (_, row) => (
<div className='commission-row-actions'> <TableRowActions
<Button items={[
onClick={() => setPartnerDetail(row)}
type='link'
size='small'
>
{t('详情')}
</Button>
<Button
onClick={() => setOperation({ kind: 'partner-edit', row })}
type='link'
size='small'
>
{t('编辑')}
</Button>
<Dropdown
trigger={['click']}
placement='bottomRight'
menu={{
items: [
{ {
key: 'partner-agreement', key: 'partner-agreement',
label: t('登记或续签协议'), label: t('登记或续签协议'),
@@ -1020,9 +996,7 @@ function AdminPage() {
? [ ? [
{ {
key: 'partner-active', key: 'partner-active',
label: t( label: t(row.status === 'draft' ? '启用' : '恢复生效'),
row.status === 'draft' ? '启用' : '恢复生效',
),
onClick: () => onClick: () =>
setOperation({ setOperation({
kind: 'partner-status', kind: 'partner-status',
@@ -1061,19 +1035,23 @@ function AdminPage() {
}, },
] ]
: []), : []),
], ]}
}}
> >
<Button <Button
onClick={() => setPartnerDetail(row)}
type='link' type='link'
size='small' size='small'
icon={<ChevronDown size={14} aria-hidden />}
iconPlacement='end'
> >
{t('更多')} {t('详情')}
</Button> </Button>
</Dropdown> <Button
</div> onClick={() => setOperation({ kind: 'partner-edit', row })}
type='link'
size='small'
>
{t('编辑')}
</Button>
</TableRowActions>
), ),
}, },
], ],
@@ -1173,84 +1151,62 @@ function AdminPage() {
}, },
{ {
title: t('操作'), title: t('操作'),
width: 300, width: 155,
render: (_, row) => ( render: (_, row) => (
<div className='commission-row-actions'> <TableRowActions
<Button items={[
onClick={() => row.status === 'protected' && {
setOperation({ kind: 'assignment-history', row }) key: 'extend',
} label: t('延期'),
type='link' onClick: () =>
size='small' setOperation({ kind: 'assignment-extend', row }),
> },
{t('历史')} [
</Button>
{row.status === 'protected' && (
<Button
onClick={() =>
setOperation({ kind: 'assignment-extend', row })
}
type='link'
size='small'
>
{t('延期')}
</Button>
)}
{[
'protected', 'protected',
'protected_extended', 'protected_extended',
'pending_conversion', 'pending_conversion',
].includes(row.status) && ( ].includes(row.status) && {
<Button key: 'convert',
onClick={() => label: t('转正'),
setOperation({ kind: 'assignment-convert', row }) onClick: () =>
} setOperation({ kind: 'assignment-convert', row }),
type='link' },
size='small' row.status === 'pending_conversion' && {
> key: 'reject',
{t('转正')} label: t('驳回'),
</Button> onClick: () =>
)} setOperation({ kind: 'assignment-reject', row }),
{row.status === 'pending_conversion' && ( },
<Button row.status === 'formal' && {
onClick={() => key: 'transfer',
setOperation({ kind: 'assignment-reject', row }) label: t('转移'),
} onClick: () =>
type='link' setOperation({ kind: 'assignment-transfer', row }),
size='small' },
> [
{t('驳回')}
</Button>
)}
{row.status === 'formal' && (
<Button
onClick={() =>
setOperation({ kind: 'assignment-transfer', row })
}
type='link'
size='small'
>
{t('转移')}
</Button>
)}
{[
'formal', 'formal',
'protected', 'protected',
'protected_extended', 'protected_extended',
'pending_conversion', 'pending_conversion',
].includes(row.status) && ( ].includes(row.status) && {
key: 'terminate',
label: t('终止'),
danger: true,
onClick: () =>
setOperation({ kind: 'assignment-terminate', row }),
},
]}
>
<Button <Button
onClick={() =>
setOperation({ kind: 'assignment-terminate', row })
}
type='link' type='link'
size='small' size='small'
danger onClick={() =>
setOperation({ kind: 'assignment-history', row })
}
> >
{t('终止')} {t('历史')}
</Button> </Button>
)} </TableRowActions>
</div>
), ),
}, },
], ],
@@ -1284,7 +1240,8 @@ function AdminPage() {
) )
.map( .map(
(id) => (id) =>
entityNames.channels.get(Number(id)) || `#${id}`, entityNames.channels.get(Number(id)) ||
formatIdReference(id),
) )
.join('、') .join('、')
: row.source_type === 'model' : row.source_type === 'model'
@@ -6,11 +6,40 @@
--igf-ink: var(--text-primary); --igf-ink: var(--text-primary);
--igf-muted: var(--text-secondary); --igf-muted: var(--text-secondary);
--igf-line: var(--border-subtle); --igf-line: var(--border-subtle);
--igf-surface: var(--surface-card);
--igf-accent: var(--ui-color-primary); --igf-accent: var(--ui-color-primary);
--igf-fill: color-mix(in srgb, var(--text-primary) 4%, var(--surface-card)); --igf-fill: color-mix(in srgb, var(--text-primary) 4%, var(--surface-card));
--igf-danger: var(--ui-color-danger); --igf-danger: var(--ui-color-danger);
--igf-warning: var(--ui-color-warning); --igf-warning: var(--ui-color-warning);
--igf-ring: color-mix(in srgb, var(--ui-color-primary) 55%, transparent); --igf-ring: color-mix(in srgb, var(--ui-color-primary) 55%, transparent);
background: var(--igf-surface);
}
.igf-form-scroll {
flex: 1 1 auto;
min-height: 0;
overflow-x: hidden;
overflow-y: auto;
padding: 16px;
}
/* Keep disabled generation actions grounded in the same surface and border token. */
.image-generation-form .igf-generate .ant-btn:disabled,
.image-generation-form .igf-generate .ant-btn[disabled] {
border: 1px solid var(--igf-line);
background: var(--igf-fill);
box-shadow: none;
color: var(--igf-muted);
cursor: not-allowed;
opacity: 1;
}
.image-generation-form .igf-generate .ant-btn:disabled:hover,
.image-generation-form .igf-generate .ant-btn[disabled]:hover {
border-color: var(--igf-line);
background: var(--igf-fill);
box-shadow: none;
color: var(--igf-muted);
} }
.image-generation-form button:focus-visible, .image-generation-form button:focus-visible,
@@ -152,6 +181,13 @@
gap: 6px; gap: 6px;
} }
.igf-generate-wrap {
flex: 0 0 auto;
padding: 16px 16px max(16px, env(safe-area-inset-bottom));
border-top: 1px solid var(--igf-line);
background: var(--igf-surface);
}
.igf-quote { .igf-quote {
min-height: 18px; min-height: 18px;
color: var(--igf-muted); color: var(--igf-muted);
@@ -140,7 +140,7 @@ const hasImageTaskType = (dataTransfer) =>
const Section = ({ title, extra, children, className = '' }) => ( const Section = ({ title, extra, children, className = '' }) => (
<div <div
className={`mb-4 rounded-3xl border border-white/[0.45] bg-white/[0.28] p-3 backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.045] ${className}`} className={`mb-4 rounded-3xl border border-[var(--igf-line)] bg-white/[0.28] p-3 backdrop-blur-xl dark:bg-white/[0.045] ${className}`}
> >
{title || extra ? ( {title || extra ? (
<div className='flex items-center justify-between gap-2 mb-2'> <div className='flex items-center justify-between gap-2 mb-2'>
@@ -383,12 +383,14 @@ const ImageGenerationForm = ({ creation }) => {
loading={submitting} loading={submitting}
onClick={handleSubmit} onClick={handleSubmit}
disabled={isButtonDisabled} disabled={isButtonDisabled}
className='!rounded-2xl !shadow-lg !shadow-brand/20 hover:!shadow-xl hover:!shadow-brand/25 !transition-all' className='!rounded-2xl !transition-colors'
style={{ style={{
background: isButtonDisabled background: isButtonDisabled
? 'var(--ui-color-fill-1)' ? 'var(--ui-color-fill-1)'
: 'linear-gradient(135deg, var(--brand-gradient-from) 0%, var(--brand-primary) 52%, var(--brand-gradient-to) 100%)', : 'linear-gradient(135deg, var(--brand-gradient-from) 0%, var(--brand-primary) 52%, var(--brand-gradient-to) 100%)',
border: 'none', border: isButtonDisabled
? '1px solid var(--igf-line)'
: '1px solid transparent',
color: isButtonDisabled ? 'var(--ui-color-text-3)' : 'white', color: isButtonDisabled ? 'var(--ui-color-text-3)' : 'white',
height: '48px', height: '48px',
fontSize: '15px', fontSize: '15px',
@@ -538,12 +540,13 @@ const ImageGenerationForm = ({ creation }) => {
return ( return (
<div <div
className={`image-generation-form relative flex h-full flex-col overflow-y-auto overflow-x-hidden rounded-[28px] border border-white/[0.55] bg-white/[0.42] p-4 shadow-[0_24px_80px_rgba(15,23,42,0.10)] backdrop-blur-2xl backdrop-saturate-150 transition-colors app-scrollbar dark:border-white/10 dark:bg-neutral-950/[0.40] dark:shadow-[0_24px_80px_rgba(0,0,0,0.35)]${dropActive ? ' is-drop-active' : ''}`} className={`image-generation-form relative flex h-full min-h-0 flex-col overflow-hidden rounded-[28px] border border-[var(--igf-line)] bg-white/[0.42] shadow-[0_24px_80px_rgba(15,23,42,0.10)] backdrop-blur-2xl backdrop-saturate-150 transition-colors dark:bg-neutral-950/[0.40] dark:shadow-[0_24px_80px_rgba(0,0,0,0.35)]${dropActive ? ' is-drop-active' : ''}`}
onDragEnter={handleDragEnter} onDragEnter={handleDragEnter}
onDragOver={handleDragOver} onDragOver={handleDragOver}
onDragLeave={handleDragLeave} onDragLeave={handleDragLeave}
onDrop={handleDrop} onDrop={handleDrop}
> >
<div className='igf-form-scroll app-scrollbar'>
{/* 标题 */} {/* 标题 */}
<div className='mb-5 rounded-3xl border border-white/60 bg-white/[0.50] p-4 shadow-sm backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.05]'> <div className='mb-5 rounded-3xl border border-white/60 bg-white/[0.50] p-4 shadow-sm backdrop-blur-xl dark:border-white/10 dark:bg-white/[0.05]'>
<div className='flex items-center justify-between gap-2'> <div className='flex items-center justify-between gap-2'>
@@ -606,7 +609,11 @@ const ImageGenerationForm = ({ creation }) => {
{formBodyHidden && ( {formBodyHidden && (
<div className='mt-2'> <div className='mt-2'>
{renderGenerateArea()} {renderGenerateArea()}
<Text type='tertiary' size='small' className='block mt-2 text-center'> <Text
type='tertiary'
size='small'
className='block mt-2 text-center'
>
{prompt {prompt
? prompt.length > 50 ? prompt.length > 50
? prompt.slice(0, 50) + '...' ? prompt.slice(0, 50) + '...'
@@ -690,7 +697,10 @@ const ImageGenerationForm = ({ creation }) => {
render={ render={
<Dropdown.Menu style={{ maxWidth: 360 }}> <Dropdown.Menu style={{ maxWidth: 360 }}>
{promptHistory.map((p, idx) => ( {promptHistory.map((p, idx) => (
<Dropdown.Item key={idx} onClick={() => setPrompt(p)}> <Dropdown.Item
key={idx}
onClick={() => setPrompt(p)}
>
<div <div
style={{ style={{
maxWidth: 320, maxWidth: 320,
@@ -795,7 +805,9 @@ const ImageGenerationForm = ({ creation }) => {
</div> </div>
{hasUnusedImage ? ( {hasUnusedImage ? (
<div className='igf-muted igf-note' role='note'> <div className='igf-muted igf-note' role='note'>
{t('置灰的图片当前不会提交,切回支持的模型或模式后自动恢复')} {t(
'置灰的图片当前不会提交,切回支持的模型或模式后自动恢复',
)}
</div> </div>
) : null} ) : null}
</Section> </Section>
@@ -854,14 +866,13 @@ const ImageGenerationForm = ({ creation }) => {
</Collapsible> </Collapsible>
</Section> </Section>
) : null} ) : null}
{/* 生成按钮 + 估价 */}
<div className='sticky bottom-0 -mx-4 mt-auto bg-transparent px-4 pt-4 pb-1'>
{renderGenerateArea()}
</div>
</> </>
)} )}
</div> </div>
{!formBodyHidden && (
<div className='igf-generate-wrap'>{renderGenerateArea()}</div>
)}
</div>
); );
}; };
@@ -203,6 +203,22 @@
overflow: hidden; overflow: hidden;
} }
/* Override antd Collapse defaults so the advanced panel shares the input cards' line. */
.vip-advanced .ant-collapse {
border: 0;
border-radius: inherit;
background: transparent;
}
.vip-advanced .ant-collapse-item {
border-bottom: 0;
}
.vip-advanced .ant-collapse-header:focus-visible {
outline: 2px solid var(--vip-accent);
outline-offset: -2px;
}
.vip-advanced .ant-collapse-header { .vip-advanced .ant-collapse-header {
margin: 0; margin: 0;
padding: 12px 16px; padding: 12px 16px;
@@ -24,6 +24,7 @@ import {
Trash2 as ActionTrash2, Trash2 as ActionTrash2,
AlertCircle as ActionAlertCircle, AlertCircle as ActionAlertCircle,
} from '@/components/common/icons/ActionIcons'; } from '@/components/common/icons/ActionIcons';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { import {
Table, Table,
@@ -239,57 +240,39 @@ const VideoTaskQueue = ({
{ {
title: t('操作'), title: t('操作'),
dataIndex: 'operate', dataIndex: 'operate',
width: !isCompact ? 220 : 180, width: 168,
fixed: 'right', fixed: 'right',
render: (text, record) => { render: (text, record) => {
const normalizedStatus = normalizeVideoTaskStatus(record.status); const normalizedStatus = normalizeVideoTaskStatus(record.status);
return ( return (
<Space> <TableRowActions
{/* 播放和下载按钮:仅根据状态显示,视频URL在点击时才获取 */} items={[
{normalizedStatus === 'success' && ( normalizedStatus === 'success' && {
<> key: 'download',
<Button label: t('下载'),
size='small' onClick: () => onDownload(record),
type='tertiary' icon: <ActionDownload size={14} />,
icon={<ActionPlay size={14} />} },
onClick={() => onPlay && onPlay(record)} (normalizedStatus === 'success' ||
>
{!isCompact ? t('播放') : ''}
</Button>
<Button
size='small'
type='tertiary'
icon={<ActionDownload size={14} />}
onClick={() => onDownload(record)}
>
{!isCompact ? t('下载') : ''}
</Button>
</>
)}
{/* 再生成按钮 - 对所有已完成或失败的任务显示 */}
{(normalizedStatus === 'success' ||
normalizedStatus === 'failure') && normalizedStatus === 'failure') &&
canRegenerateVideoTask(record) && ( canRegenerateVideoTask(record) && {
<Button key: 'regenerate',
size='small' label: t('再生成'),
type='primary' onClick: () => onRegenerate && onRegenerate(record),
icon={<ActionRefreshCw size={14} />} icon: <ActionRefreshCw size={14} />,
onClick={() => onRegenerate && onRegenerate(record)} },
> {
{!isCompact ? t('再生成') : ''} key: 'delete',
</Button> label: t('删除'),
)} onClick: () => {
<Button
size='small'
type='danger'
icon={<ActionTrash2 size={14} />}
onClick={() => {
Modal.warning({ Modal.warning({
title: t('确定删除此任务?'), title: t('确定删除此任务?'),
content: t('删除后将无法恢复'), content: t('删除后将无法恢复'),
icon: ( icon: (
<ActionAlertCircle size={24} style={{ color: '#f59e0b' }} /> <ActionAlertCircle
size={24}
style={{ color: '#f59e0b' }}
/>
), ),
okText: t('确定'), okText: t('确定'),
cancelText: t('取消'), cancelText: t('取消'),
@@ -297,11 +280,23 @@ const VideoTaskQueue = ({
centered: true, centered: true,
okButtonProps: { type: 'danger' }, okButtonProps: { type: 'danger' },
}); });
}} },
icon: <ActionTrash2 size={14} />,
danger: true,
},
]}
> >
{!isCompact ? t('删除') : ''} {normalizedStatus === 'success' && (
<Button
size='small'
type='tertiary'
icon={<ActionPlay size={14} />}
onClick={() => onPlay && onPlay(record)}
>
{t('播放')}
</Button> </Button>
</Space> )}
</TableRowActions>
); );
}, },
}, },
+4 -3
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { import {
@@ -2340,8 +2341,8 @@ const ExpertPlatform = () => {
className={`expert-diagnose-model ${row.success ? 'is-ok' : 'is-blocked'}`} className={`expert-diagnose-model ${row.success ? 'is-ok' : 'is-blocked'}`}
> >
<strong> <strong>
{row.channel_name || `#${row.channel_id}`} {row.channel_name || formatIdReference(row.channel_id)}
<em>{`#${row.channel_id}`}</em> <em>{formatIdReference(row.channel_id)}</em>
</strong> </strong>
<small> <small>
{row.success {row.success
@@ -2392,7 +2393,7 @@ const ExpertPlatform = () => {
} }
optionList={channels.map((channel) => ({ optionList={channels.map((channel) => ({
value: channel.id, value: channel.id,
label: `#${channel.id} · ${channel.name}`, label: `${formatIdReference(channel.id)} · ${channel.name}`,
}))} }))}
placeholder={t('选择已启用渠道')} placeholder={t('选择已启用渠道')}
/> />
+2 -1
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatPercent } from '../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
@@ -455,7 +456,7 @@ const ChannelMonitor = () => {
: 'var(--ui-color-danger)', : 'var(--ui-color-danger)',
}} }}
> >
{channel.uptime.toFixed(2)}% {formatPercent(channel.uptime, 2)}
</span> </span>
</div> </div>
<div <div
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatPercent } from '../../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../../i18n/technicalText.js';
import React from 'react'; import React from 'react';
@@ -220,7 +221,10 @@ const ChannelMonitorView = ({ channelStatus, onRefresh }) => {
> >
{renderSparkline(channel.uptime || 0)} {renderSparkline(channel.uptime || 0)}
<Text type='success' strong> <Text type='success' strong>
{((channel.uptime || 0) * 100).toFixed(1)}% {formatPercent(
Number(channel.uptime || 0) * 100,
1,
)}
</Text> </Text>
</div> </div>
</div> </div>
+8 -18
View File
@@ -34,11 +34,7 @@ import {
} from '@/components/ui'; } from '@/components/ui';
import { API } from '../../helpers/api'; import { API } from '../../helpers/api';
import { showError, getLogo, getSystemName } from '../../helpers'; import { showError, getLogo, getSystemName } from '../../helpers';
import { import { setUserData } from '../../helpers/data';
setUserData,
savePostLoginRedirect,
consumePostLoginRedirect,
} from '../../helpers/data';
import { updateAPI } from '../../helpers/api'; import { updateAPI } from '../../helpers/api';
import { finishLogin } from '../../helpers/loginFlow'; import { finishLogin } from '../../helpers/loginFlow';
import { UserContext } from '../../context/User'; import { UserContext } from '../../context/User';
@@ -219,14 +215,10 @@ const OrgLogin = () => {
} }
}; };
// 与 /login 对齐的入口参数处理:?redirect= 写回本地存储(新标签页打开也能回跳), const expiryShown = useRef(false);
// ?expired=true 提示会话过期后从 URL 清除(避免刷新重复提示)。
useEffect(() => { useEffect(() => {
const redirect = searchParams.get('redirect'); if (searchParams.get('expired') && !expiryShown.current) {
if (redirect) { expiryShown.current = true;
savePostLoginRedirect(redirect);
}
if (searchParams.get('expired')) {
showError(t('未登录或登录已过期,请重新登录')); showError(t('未登录或登录已过期,请重新登录'));
const nextParams = new URLSearchParams(searchParams); const nextParams = new URLSearchParams(searchParams);
nextParams.delete('expired'); nextParams.delete('expired');
@@ -283,9 +275,8 @@ const OrgLogin = () => {
userDispatch, userDispatch,
navigate, navigate,
t, t,
// 消费被保护页跳来时保存的回跳地址(尊重深链意图,同时避免残留值 enterprise: true,
// 影响之后的个人登录);无保存值则进企业工作台 redirect: searchParams.get('redirect'),
redirectOverride: consumePostLoginRedirect('/org/workbench'),
}); });
} }
}; };
@@ -416,9 +407,8 @@ const OrgLogin = () => {
userDispatch, userDispatch,
navigate, navigate,
t, t,
successMessage: '', enterprise: true,
// 首登改密路径同样消费保存的回跳地址,默认进企业工作台 redirect: searchParams.get('redirect'),
redirectOverride: consumePostLoginRedirect('/org/workbench'),
}); });
} else { } else {
showError(res.data.message); showError(res.data.message);
+2 -1
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatUserReference } from '../../helpers/safeDisplay';
import { import {
Search as ActionSearch, Search as ActionSearch,
RefreshCw as ActionRefreshCw, RefreshCw as ActionRefreshCw,
@@ -306,7 +307,7 @@ const OrgAudit = ({ orgId }) => {
title: t('操作者'), title: t('操作者'),
dataIndex: 'operator_name', dataIndex: 'operator_name',
width: 130, width: 130,
render: (name, record) => name || `User#${record.operator_id}`, render: (name, record) => formatUserReference(name, record.operator_id),
}, },
{ {
title: t('操作类型'), title: t('操作类型'),
+17 -8
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { import {
RefreshCw as ActionRefreshCw, RefreshCw as ActionRefreshCw,
Plus as ActionPlus, Plus as ActionPlus,
@@ -106,10 +107,14 @@ const OrgBudgets = ({ orgId, featureFlags }) => {
if (!orgId) return; if (!orgId) return;
setLoading(true); setLoading(true);
try { try {
const options = {
headers: getOrgHeaders(orgId),
requestGroup: new AbortController(),
};
const [b, d, p] = await Promise.all([ const [b, d, p] = await Promise.all([
API.get('/api/org/budget', { headers: getOrgHeaders(orgId) }), API.get('/api/org/budget', options),
API.get('/api/org/dept', { headers: getOrgHeaders(orgId) }), API.get('/api/org/dept', options),
API.get('/api/org/project', { headers: getOrgHeaders(orgId) }), API.get('/api/org/project', options),
]); ]);
if (b.data.success) { if (b.data.success) {
// 新后端返回 {items, enforcement_enabled, engine_enabled};兼容旧后端直接返回数组。 // 新后端返回 {items, enforcement_enabled, engine_enabled};兼容旧后端直接返回数组。
@@ -122,7 +127,7 @@ const OrgBudgets = ({ orgId, featureFlags }) => {
if (d.data.success) setDepts(d.data.data || []); if (d.data.success) setDepts(d.data.data || []);
if (p.data.success) setProjects(p.data.data || []); if (p.data.success) setProjects(p.data.data || []);
} catch (err) { } catch (err) {
showError(err.message); if (!err?.isAxiosError) showError(err);
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -139,7 +144,7 @@ const OrgBudgets = ({ orgId, featureFlags }) => {
const st = r.subject_type; const st = r.subject_type;
if (r.subject_exists !== undefined) { if (r.subject_exists !== undefined) {
return { return {
name: r.subject_name || `#${r.subject_id}`, name: r.subject_name || formatIdReference(r.subject_id),
exists: !!r.subject_exists, exists: !!r.subject_exists,
disabled: r.subject_status === 2, disabled: r.subject_status === 2,
}; };
@@ -147,7 +152,7 @@ const OrgBudgets = ({ orgId, featureFlags }) => {
if (st === 'department') { if (st === 'department') {
const d = depts.find((x) => x.id === r.subject_id); const d = depts.find((x) => x.id === r.subject_id);
return { return {
name: d?.name || `#${r.subject_id}`, name: d?.name || formatIdReference(r.subject_id),
exists: !!d, exists: !!d,
disabled: d?.status === 2, disabled: d?.status === 2,
}; };
@@ -155,13 +160,17 @@ const OrgBudgets = ({ orgId, featureFlags }) => {
if (st === 'project') { if (st === 'project') {
const p = projects.find((x) => x.id === r.subject_id); const p = projects.find((x) => x.id === r.subject_id);
return { return {
name: p?.name || `#${r.subject_id}`, name: p?.name || formatIdReference(r.subject_id),
exists: !!p, exists: !!p,
disabled: p?.status === 2, disabled: p?.status === 2,
}; };
} }
// 旧后端下成员/密钥无从解析,按存在处理,避免误标「已删除」 // 旧后端下成员/密钥无从解析,按存在处理,避免误标「已删除」
return { name: `#${r.subject_id}`, exists: true, disabled: false }; return {
name: formatIdReference(r.subject_id),
exists: true,
disabled: false,
};
}, },
[depts, projects], [depts, projects],
); );
+4 -1
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { import {
RefreshCw as ActionRefreshCw, RefreshCw as ActionRefreshCw,
Plus as ActionPlus, Plus as ActionPlus,
@@ -186,7 +187,9 @@ const OrgDepartments = ({ orgId }) => {
const deptName = useCallback( const deptName = useCallback(
(id) => (id) =>
id ? list.find((d) => d.id === id)?.name || `#${id}` : t('顶级部门'), id
? list.find((d) => d.id === id)?.name || formatIdReference(id)
: t('顶级部门'),
[list, t], [list, t],
); );
+11 -5
View File
@@ -16,6 +16,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { formatUserReference } from '../../helpers/safeDisplay';
import { import {
RefreshCw as ActionRefreshCw, RefreshCw as ActionRefreshCw,
Check as ActionCheck, Check as ActionCheck,
@@ -213,7 +215,8 @@ const OrgDeptManage = ({ orgId, featureFlags }) => {
const nameMap = useMemo(() => { const nameMap = useMemo(() => {
const m = {}; const m = {};
members.forEach((x) => { members.forEach((x) => {
m[x.id] = x.remark || x.display_name || x.username || `#${x.id}`; m[x.id] =
x.remark || x.display_name || x.username || formatIdReference(x.id);
}); });
return m; return m;
}, [members]); }, [members]);
@@ -273,7 +276,7 @@ const OrgDeptManage = ({ orgId, featureFlags }) => {
{ {
title: t('成员'), title: t('成员'),
dataIndex: 'display_name', dataIndex: 'display_name',
render: (v, r) => r.remark || v || r.username || `#${r.id}`, render: (v, r) => r.remark || v || r.username || formatIdReference(r.id),
}, },
{ {
title: t('已用额度'), title: t('已用额度'),
@@ -299,7 +302,8 @@ const OrgDeptManage = ({ orgId, featureFlags }) => {
{ {
title: t('成员'), title: t('成员'),
dataIndex: 'display_name', dataIndex: 'display_name',
render: (v, r) => v || r.username || `#${r.user_id}`, render: (v, r) =>
formatUserReference(v || r.username, r.user_id, t('未知用户')),
}, },
{ {
title: t('消耗'), title: t('消耗'),
@@ -437,8 +441,10 @@ const OrgDeptManage = ({ orgId, featureFlags }) => {
> >
<div className='min-w-0'> <div className='min-w-0'>
<Text> <Text>
{nameMap[r.requester_id] || `#${r.requester_id}`} ·{' '} {nameMap[r.requester_id] ||
{t('提额')} {renderQuota(parseDelta(r.payload), 2)} formatIdReference(r.requester_id)}{' '}
· {t('提额')}{' '}
{renderQuota(parseDelta(r.payload), 2)}
</Text> </Text>
<div> <div>
<Text type='tertiary' size='small'> <Text type='tertiary' size='small'>
+16 -6
View File
@@ -16,6 +16,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { formatPercent } from '../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons'; import { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons';
@@ -414,13 +416,15 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => {
title: t('技能'), title: t('技能'),
dataIndex: 'name', dataIndex: 'name',
render: (name, record) => render: (name, record) =>
name || record.canonical_id || `#${record.skill_id}`, name ||
record.canonical_id ||
formatIdReference(record.skill_id),
}, },
{ title: t('调用次数'), dataIndex: 'request_count' }, { title: t('调用次数'), dataIndex: 'request_count' },
{ {
title: t('占比'), title: t('占比'),
dataIndex: 'share_percent', dataIndex: 'share_percent',
render: (share) => `${(share || 0).toFixed(1)}%`, render: (share) => formatPercent(share, 1),
}, },
{ {
title: t('提示词 token'), title: t('提示词 token'),
@@ -545,13 +549,16 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => {
<span> <span>
{t('首次交付通过率')}:{' '} {t('首次交付通过率')}:{' '}
{row.data_sufficient {row.data_sufficient
? `${(row.first_delivery_pass_rate * 100).toFixed(1)}%` ? formatPercent(
Number(row.first_delivery_pass_rate) * 100,
1,
)
: t('数据不足')} : t('数据不足')}
</span> </span>
<span> <span>
{t('退回率')}:{' '} {t('退回率')}:{' '}
{row.data_sufficient {row.data_sufficient
? `${(row.return_rate * 100).toFixed(1)}%` ? formatPercent(Number(row.return_rate) * 100, 1)
: t('数据不足')} : t('数据不足')}
</span> </span>
<span> <span>
@@ -574,14 +581,17 @@ const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => {
title: t('首次交付通过率'), title: t('首次交付通过率'),
render: (_, row) => render: (_, row) =>
row.data_sufficient row.data_sufficient
? `${(row.first_delivery_pass_rate * 100).toFixed(1)}%` ? formatPercent(
Number(row.first_delivery_pass_rate) * 100,
1,
)
: t('数据不足'), : t('数据不足'),
}, },
{ {
title: t('退回率'), title: t('退回率'),
render: (_, row) => render: (_, row) =>
row.data_sufficient row.data_sufficient
? `${(row.return_rate * 100).toFixed(1)}%` ? formatPercent(Number(row.return_rate) * 100, 1)
: t('数据不足'), : t('数据不足'),
}, },
{ {
+6 -2
View File
@@ -16,6 +16,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { formatPercent } from '../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { import {
@@ -1887,7 +1889,7 @@ const OrgKnowledge = ({ orgId, canAuditContent = false }) => {
label: label:
member.display_name || member.display_name ||
member.username || member.username ||
`#${member.id}`, formatIdReference(member.id),
}))} }))}
/> />
<Select <Select
@@ -1959,7 +1961,9 @@ const OrgKnowledge = ({ orgId, canAuditContent = false }) => {
<div className='knowledge-hit-body'> <div className='knowledge-hit-body'>
<div className='knowledge-hit-title'> <div className='knowledge-hit-title'>
<strong>{hit.source_label}</strong> <strong>{hit.source_label}</strong>
<span>{(hit.score * 100).toFixed(1)}%</span> <span>
{formatPercent(Number(hit.score) * 100, 1)}
</span>
</div> </div>
<div className='knowledge-hit-meta'> <div className='knowledge-hit-meta'>
{hit.base_name && <span>{hit.base_name}</span>} {hit.base_name && <span>{hit.base_name}</span>}
+10 -3
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatUserReference } from '../../helpers/safeDisplay';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { import {
@@ -486,7 +487,10 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
const key = log.user_id ?? 'unknown'; const key = log.user_id ?? 'unknown';
if (!groups.has(key)) { if (!groups.has(key)) {
groups.set(key, { groups.set(key, {
name: log.display_name || log.username || `User#${log.user_id}`, name: formatUserReference(
log.display_name || log.username,
log.user_id,
),
rows: [], rows: [],
}); });
} }
@@ -595,7 +599,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
members.forEach((m) => { members.forEach((m) => {
opts.push({ opts.push({
value: m.user_id, value: m.user_id,
label: m.display_name || m.username || `User#${m.user_id}`, label: formatUserReference(m.display_name || m.username, m.user_id),
}); });
}); });
return opts; return opts;
@@ -616,7 +620,10 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
: t('仅本人'); : t('仅本人');
if (canViewTeamUsage && af.userId) { if (canViewTeamUsage && af.userId) {
const m = members.find((x) => String(x.user_id) === String(af.userId)); const m = members.find((x) => String(x.user_id) === String(af.userId));
member = m ? m.display_name || m.username : `User#${af.userId}`; member = formatUserReference(
m?.display_name || m?.username,
m?.user_id ?? af.userId,
);
} }
const time = const time =
af.startTimestamp && af.endTimestamp af.startTimestamp && af.endTimestamp
+56 -47
View File
@@ -16,6 +16,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { formatUserReference } from '../../helpers/safeDisplay';
import { import {
RefreshCw as ActionRefreshCw, RefreshCw as ActionRefreshCw,
UserPlus as ActionUserPlus, UserPlus as ActionUserPlus,
@@ -30,7 +32,7 @@ import {
Form, Form,
Toast, Toast,
Tag, Tag,
Popconfirm, Modal,
Banner, Banner,
Typography, Typography,
Tooltip, Tooltip,
@@ -40,7 +42,8 @@ import { API } from '../../helpers/api';
import { showError, collectPagedItems } from '../../helpers'; import { showError, collectPagedItems } from '../../helpers';
import OrgPageHeader from './components/OrgPageHeader'; import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel'; import OrgPanel from './components/OrgPanel';
import { OrgListCard, OrgRowActions } from './components/OrgListCard'; import { TableRowActions } from '@/components/common/table/TableToolbar';
import { OrgListCard } from './components/OrgListCard';
import OrgModal from './components/OrgModal'; import OrgModal from './components/OrgModal';
import DeptTreeSelect from './components/DeptTreeSelect'; import DeptTreeSelect from './components/DeptTreeSelect';
import { import {
@@ -327,7 +330,13 @@ const OrgMemberAccounts = ({
title: t('成员'), title: t('成员'),
render: (_, r) => ( render: (_, r) => (
<div className='flex items-center gap-2'> <div className='flex items-center gap-2'>
<span>{r.display_name || r.username || `#${r.user_id}`}</span> <span>
{formatUserReference(
r.display_name || r.username,
r.user_id,
t('未知用户'),
)}
</span>
{r.created_by_org_id !== r.organization_id && ( {r.created_by_org_id !== r.organization_id && (
<Tooltip content={t('个人平台账号(非本企业托管)')}> <Tooltip content={t('个人平台账号(非本企业托管)')}>
<Tag size='small' color='blue'> <Tag size='small' color='blue'>
@@ -351,8 +360,8 @@ const OrgMemberAccounts = ({
width: 120, width: 120,
render: (v) => render: (v) =>
v ? ( v ? (
<Tooltip content={deptFullNameMap[v] || `#${v}`}> <Tooltip content={deptFullNameMap[v] || formatIdReference(v)}>
<span>{deptNameMap[v] || `#${v}`}</span> <span>{deptNameMap[v] || formatIdReference(v)}</span>
</Tooltip> </Tooltip>
) : ( ) : (
<span className='text-gray-400'>{t('未分配')}</span> <span className='text-gray-400'>{t('未分配')}</span>
@@ -382,7 +391,7 @@ const OrgMemberAccounts = ({
}, },
{ {
title: t('操作'), title: t('操作'),
width: 260, width: 110,
render: (_, r) => { render: (_, r) => {
const managed = r.created_by_org_id === r.organization_id; const managed = r.created_by_org_id === r.organization_id;
// 与后端 model.ResetManagedMemberPassword 的分级拦截保持一致 // 与后端 model.ResetManagedMemberPassword 的分级拦截保持一致
@@ -396,53 +405,53 @@ const OrgMemberAccounts = ({
} }
const canReset = !resetBlockedReason; const canReset = !resetBlockedReason;
return ( return (
<OrgRowActions> <TableRowActions
{deptEnabled && ( items={[
<Button deptEnabled && {
type='link' key: 'department',
onClick={() => { label: t('分配部门'),
onClick: () => {
setDeptAssignFor(r); setDeptAssignFor(r);
setDeptAssignVal(r.department_id || 0); setDeptAssignVal(r.department_id || 0);
}} },
> },
{t('分配部门')} {
</Button> key: 'reset-password',
)} label: t('重置密码'),
{canReset ? ( disabled: !canReset,
<Popconfirm title: resetBlockedReason || undefined,
title={t('重置该账号密码?')} onClick: () =>
content={ Modal.confirm({
managed title: t('重置该账号密码?'),
content: managed
? t('将生成一次性临时密码,并要求首次登录改密') ? t('将生成一次性临时密码,并要求首次登录改密')
: t( : t(
'该成员为个人平台账号,重置后其平台登录密码同步失效,请将临时密码安全告知本人', '该成员为个人平台账号,重置后其平台登录密码同步失效,请将临时密码安全告知本人',
) ),
} okText: t('确认'),
onConfirm={() => resetPassword(r)} cancelText: t('取消'),
> onOk: () => resetPassword(r),
<Button type='link'>{t('重置密码')}</Button> }),
</Popconfirm> },
) : ( r.status === 1 &&
<Tooltip content={resetBlockedReason}> r.role !== 'owner' && {
<Button type='link' disabled> key: 'offboard',
{t('重置密码')} label: t('离职回收'),
</Button> danger: true,
</Tooltip> onClick: () =>
)} Modal.confirm({
{r.status === 1 && r.role !== 'owner' && ( title: t('确认离职回收该成员?'),
<Popconfirm content: t(
title={t('确认离职回收该成员?')}
content={t(
'将禁用其企业成员身份与全部企业 Token,保留历史,不删除用户', '将禁用其企业成员身份与全部企业 Token,保留历史,不删除用户',
)} ),
onConfirm={() => offboard(r.id)} okText: t('确认'),
> cancelText: t('取消'),
<Button type='link' danger> okButtonProps: { danger: true },
{t('离职回收')} onOk: () => offboard(r.id),
</Button> }),
</Popconfirm> },
)} ]}
</OrgRowActions> />
); );
}, },
}, },
+54 -59
View File
@@ -30,7 +30,7 @@ import {
Input, Input,
Select, Select,
Tag, Tag,
Popconfirm, Modal,
Toast, Toast,
Tooltip, Tooltip,
Switch, Switch,
@@ -42,7 +42,8 @@ import QuotaInput from '../../components/common/ui/QuotaInput';
import OrgPageHeader from './components/OrgPageHeader'; import OrgPageHeader from './components/OrgPageHeader';
import OrgPanel from './components/OrgPanel'; import OrgPanel from './components/OrgPanel';
import { Alert as AntAlert, Tabs as AntTabs } from 'antd'; import { Alert as AntAlert, Tabs as AntTabs } from 'antd';
import { OrgListCard, OrgRowActions } from './components/OrgListCard'; import { TableRowActions } from '@/components/common/table/TableToolbar';
import { OrgListCard } from './components/OrgListCard';
import OrgModal from './components/OrgModal'; import OrgModal from './components/OrgModal';
import OrgMemberAccounts from './OrgMemberAccounts'; import OrgMemberAccounts from './OrgMemberAccounts';
@@ -572,7 +573,7 @@ const OrgMembers = ({
if (canWrite) { if (canWrite) {
memberColumns.push({ memberColumns.push({
title: t('操作'), title: t('操作'),
width: 260, width: 110,
fixed: 'right', fixed: 'right',
render: (_, record) => { render: (_, record) => {
if (record.role === 'owner') { if (record.role === 'owner') {
@@ -580,11 +581,13 @@ const OrgMembers = ({
} }
const isSelf = Number(record.user_id) === currentUserId; const isSelf = Number(record.user_id) === currentUserId;
return ( return (
<OrgRowActions> <TableRowActions
<Tooltip content={t('设置该成员的个人额度上限')}> items={[
<Button {
type='link' key: 'quota',
onClick={() => { label: t('配额'),
title: t('设置该成员的个人额度上限'),
onClick: () => {
setQuotaMemberId(record.id); setQuotaMemberId(record.id);
setQuotaMemberName( setQuotaMemberName(
record.display_name || record.username || '', record.display_name || record.username || '',
@@ -592,15 +595,13 @@ const OrgMembers = ({
setQuotaLimit(record.quota_limit || 0); setQuotaLimit(record.quota_limit || 0);
setQuotaPeriod(record.quota_period || 'none'); setQuotaPeriod(record.quota_period || 'none');
setQuotaModalVisible(true); setQuotaModalVisible(true);
}} },
> },
{t('配额')} {
</Button> key: 'models',
</Tooltip> label: t('模型'),
<Tooltip content={t('设置该成员可用的模型范围')}> title: t('设置该成员可用的模型范围'),
<Button onClick: async () => {
type='link'
onClick={async () => {
setModelLimitsMemberId(record.id); setModelLimitsMemberId(record.id);
setModelLimitsMemberName( setModelLimitsMemberName(
record.display_name || record.username || '', record.display_name || record.username || '',
@@ -629,22 +630,15 @@ const OrgMembers = ({
/* ignore */ /* ignore */
} }
setLoadingOrgModels(false); setLoadingOrgModels(false);
}} },
> },
{t('模型')} {
</Button> key: 'groups',
</Tooltip> label: t('分组'),
<Tooltip title: isSelf
content={
isSelf
? t('不能修改自己的可调用分组') ? t('不能修改自己的可调用分组')
: t('设置该成员可调用的分组') : t('设置该成员可调用的分组'),
} onClick: () => {
>
<Button
type='link'
disabled={isSelf}
onClick={() => {
if (isSelf) return; if (isSelf) return;
setGroupsMemberId(record.id); setGroupsMemberId(record.id);
setGroupsMemberName( setGroupsMemberName(
@@ -652,16 +646,15 @@ const OrgMembers = ({
); );
setSelectedMemberGroups(parseMemberGroups(record)); setSelectedMemberGroups(parseMemberGroups(record));
setGroupsModalVisible(true); setGroupsModalVisible(true);
}} },
> disabled: isSelf,
{t('分组')} },
</Button> orgRole === 'owner' &&
</Tooltip> record.role === 'admin' && {
{orgRole === 'owner' && record.role === 'admin' && ( key: 'permissions',
<Tooltip content={t('设置该管理员的细粒度权限')}> label: t('权限'),
<Button title: t('设置该管理员的细粒度权限'),
type='link' onClick: () => {
onClick={() => {
setPermMemberId(record.id); setPermMemberId(record.id);
setPermMemberName( setPermMemberName(
record.display_name || record.username || '', record.display_name || record.username || '',
@@ -685,23 +678,25 @@ const OrgMembers = ({
smart_router_manage: !!perms.smart_router_manage, smart_router_manage: !!perms.smart_router_manage,
}); });
setPermModalVisible(true); setPermModalVisible(true);
}} },
> },
{t('权限')} {
</Button> key: 'remove',
</Tooltip> label: t('移除'),
)} danger: true,
<Tooltip content={t('从企业中移除该成员')}> onClick: () =>
<Popconfirm Modal.confirm({
title={t('确定移除该成员?移除后该成员将失去企业访问权限。')} title: t(
onConfirm={() => handleRemove(record.id)} '确定移除该成员?移除后该成员将失去企业访问权限。',
> ),
<Button type='link' danger> okText: t('确认'),
{t('移除')} cancelText: t('取消'),
</Button> okButtonProps: { danger: true },
</Popconfirm> onOk: () => handleRemove(record.id),
</Tooltip> }),
</OrgRowActions> },
]}
/>
); );
}, },
}); });
+83 -85
View File
@@ -24,6 +24,7 @@ import {
OctagonX as ActionOctagonX, OctagonX as ActionOctagonX,
Code2 as ActionCode2, Code2 as ActionCode2,
} from '@/components/common/icons/ActionIcons'; } from '@/components/common/icons/ActionIcons';
import { TableRowActions } from '@/components/common/table/TableToolbar';
import React, { useCallback, useEffect, useMemo, useState } from 'react'; import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { import {
Button, Button,
@@ -217,118 +218,115 @@ const OrgPrivateSkills = ({ orgId }) => {
currentUserId > 0 && Number(row.version?.created_by) === currentUserId; currentUserId > 0 && Number(row.version?.created_by) === currentUserId;
const isReviewer = const isReviewer =
currentUserId > 0 && Number(row.review?.reviewer_id) === currentUserId; currentUserId > 0 && Number(row.review?.reviewer_id) === currentUserId;
return ( const [primaryAction, ...moreActions] = [
<div className='flex flex-wrap gap-2'> {
<Button key: 'new-version',
size='small' label: t('新版本'),
disabled={row.definition.emergency_stopped} onClick: () => {
onClick={() => {
setEditingSkill(row.definition); setEditingSkill(row.definition);
setForm({ setForm({
...blankSkill, ...blankSkill,
canonical_id: row.definition.canonical_id, canonical_id: row.definition.canonical_id,
}); });
setEditorVisible(true); setEditorVisible(true);
}} },
> disabled: row.definition.emergency_stopped,
{t('新版本')} },
</Button> {
<Button size='small' onClick={() => openHistory(row.definition)}> key: 'history',
{t('历史版本')} label: t('历史版本'),
</Button> onClick: () => openHistory(row.definition),
<Button },
size='small' {
disabled={!versionId} key: 'runtime',
onClick={() => { label: t('执行模型实测'),
onClick: () => {
// Clear residue from a previous version's test before reopening. // Clear residue from a previous version's test before reopening.
setEvidence({ model: '', input: '' }); setEvidence({ model: '', input: '' });
setEvidenceVersion(versionId); setEvidenceVersion(versionId);
}} },
> disabled: !versionId,
{t('执行模型实测')} },
</Button> {
<Button key: 'claim',
size='small' label:
disabled={!versionId || row.review?.status !== 'pending' || isAuthor} isAuthor && row.review?.status === 'pending'
onClick={() =>
action(`/api/org/skills/private/versions/${versionId}/review/start`)
}
>
{isAuthor && row.review?.status === 'pending'
? t('待他人审核') ? t('待他人审核')
: t('领取审核')} : t('领取审核'),
</Button> onClick: () =>
<Button action(`/api/org/skills/private/versions/${versionId}/review/start`),
size='small' disabled: !versionId || row.review?.status !== 'pending' || isAuthor,
icon={<ActionFileCheck2 size={14} />} },
disabled={ {
!versionId || row.review?.status !== 'reviewing' || !isReviewer key: 'approve',
} label: t('通过'),
onClick={() => onClick: () =>
action( action(
`/api/org/skills/private/versions/${versionId}/review/decision`, `/api/org/skills/private/versions/${versionId}/review/decision`,
{ approved: true, conclusion: { decision: 'approved' } }, { approved: true, conclusion: { decision: 'approved' } },
) ),
} disabled:
> !versionId || row.review?.status !== 'reviewing' || !isReviewer,
{t('通过')} icon: <ActionFileCheck2 size={14} />,
</Button> },
<Button {
size='small' key: 'reject',
type='danger' label: t('驳回'),
disabled={ onClick: () =>
!versionId || row.review?.status !== 'reviewing' || !isReviewer
}
onClick={() =>
action( action(
`/api/org/skills/private/versions/${versionId}/review/decision`, `/api/org/skills/private/versions/${versionId}/review/decision`,
{ approved: false, conclusion: { decision: 'rejected' } }, { approved: false, conclusion: { decision: 'rejected' } },
) ),
} disabled:
> !versionId || row.review?.status !== 'reviewing' || !isReviewer,
{t('驳回')} danger: true,
</Button> },
<Button {
size='small' key: 'publish',
disabled={!versionId || row.review?.status !== 'approved'} label: t('发布'),
onClick={() => onClick: () =>
action(`/api/org/skills/private/versions/${versionId}/publish`) action(`/api/org/skills/private/versions/${versionId}/publish`),
} disabled: !versionId || row.review?.status !== 'approved',
> },
{t('发布')} {
</Button> key: 'rollback',
<Button label: t('回滚'),
size='small' onClick: () =>
icon={<ActionRotateCcw size={14} />}
disabled={!versionId}
onClick={() =>
askReason(t('回滚到当前列表版本'), (reason) => askReason(t('回滚到当前列表版本'), (reason) =>
action( action(
`/api/org/skills/private/${row.definition.id}/versions/${versionId}/rollback`, `/api/org/skills/private/${row.definition.id}/versions/${versionId}/rollback`,
{ reason }, { reason },
), ),
) ),
} disabled: !versionId,
> icon: <ActionRotateCcw size={14} />,
{t('回滚')} },
</Button> {
<Button key: 'stop',
size='small' label: t('紧急停用'),
type='danger' onClick: () =>
icon={<ActionOctagonX size={14} />}
disabled={row.definition.emergency_stopped}
onClick={() =>
askReason(t('紧急停用 Skill'), (reason) => askReason(t('紧急停用 Skill'), (reason) =>
action( action(
`/api/org/skills/private/${row.definition.id}/emergency-stop`, `/api/org/skills/private/${row.definition.id}/emergency-stop`,
{ reason }, { reason },
), ),
) ),
} disabled: row.definition.emergency_stopped,
icon: <ActionOctagonX size={14} />,
danger: true,
},
];
return (
<TableRowActions items={moreActions}>
<Button
size='small'
type='link'
disabled={primaryAction.disabled}
onClick={primaryAction.onClick}
> >
{t('紧急停用')} {primaryAction.label}
</Button> </Button>
</div> </TableRowActions>
); );
}; };
const openCreateEditor = () => { const openCreateEditor = () => {
@@ -500,7 +498,7 @@ const OrgPrivateSkills = ({ orgId }) => {
}, },
{ {
title: t('操作'), title: t('操作'),
width: 430, width: 170,
render: (_, row) => renderSkillActions(row), render: (_, row) => renderSkillActions(row),
}, },
]} ]}
+5 -1
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { import {
RefreshCw as ActionRefreshCw, RefreshCw as ActionRefreshCw,
Pencil as ActionPencil, Pencil as ActionPencil,
@@ -44,7 +45,10 @@ const { Text } = Typography;
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) }); const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
const memberName = (m) => const memberName = (m) =>
m.remark || m.display_name || m.username || `#${m.org_member_id}`; m.remark ||
m.display_name ||
m.username ||
formatIdReference(m.org_member_id);
// 我的项目(阶段一):项目经理(项目负责人/项目管理员)自助管理项目成员与项目名。 // 我的项目(阶段一):项目经理(项目负责人/项目管理员)自助管理项目成员与项目名。
const OrgProjectManage = ({ orgId }) => { const OrgProjectManage = ({ orgId }) => {
+28 -18
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { import {
RefreshCw as ActionRefreshCw, RefreshCw as ActionRefreshCw,
Plus as ActionPlus, Plus as ActionPlus,
@@ -36,7 +37,8 @@ import {
import { API } from '../../helpers/api'; import { API } from '../../helpers/api';
import { showError, collectPagedItems } from '../../helpers'; import { showError, collectPagedItems } from '../../helpers';
import OrgPageHeader from './components/OrgPageHeader'; import OrgPageHeader from './components/OrgPageHeader';
import { OrgListCard, OrgRowActions } from './components/OrgListCard'; import { TableRowActions } from '@/components/common/table/TableToolbar';
import { OrgListCard } from './components/OrgListCard';
import OrgModal from './components/OrgModal'; import OrgModal from './components/OrgModal';
import OrgScopedLimitButtons from './components/OrgScopedLimitButtons'; import OrgScopedLimitButtons from './components/OrgScopedLimitButtons';
@@ -105,7 +107,7 @@ const OrgProjects = ({ orgId }) => {
const memberNameMap = useMemo(() => { const memberNameMap = useMemo(() => {
const m = {}; const m = {};
members.forEach((mem) => { members.forEach((mem) => {
m[mem.id] = mem.display_name || mem.username || `#${mem.id}`; m[mem.id] = mem.display_name || mem.username || formatIdReference(mem.id);
}); });
return m; return m;
}, [members]); }, [members]);
@@ -303,12 +305,11 @@ const OrgProjects = ({ orgId }) => {
return members return members
.filter((mem) => !inProject.has(mem.id)) .filter((mem) => !inProject.has(mem.id))
.map((mem) => ({ .map((mem) => ({
label: mem.display_name || mem.username || `#${mem.id}`, label: mem.display_name || mem.username || formatIdReference(mem.id),
value: mem.id, value: mem.id,
})); }));
}, [members, projectMembers]); }, [members, projectMembers]);
// 列宽与渲染对齐原型 EnterpriseProjects(150/350/120/140/300,scroll.x 1060);
const columns = [ const columns = [
{ {
title: t('项目编码'), title: t('项目编码'),
@@ -351,27 +352,36 @@ const OrgProjects = ({ orgId }) => {
}, },
{ {
title: t('操作'), title: t('操作'),
width: 300, width: 168,
render: (_, record) => ( render: (_, record) => (
<OrgRowActions>
<OrgScopedLimitButtons <OrgScopedLimitButtons
orgId={orgId} orgId={orgId}
record={record} record={record}
apiBase='/api/org/project' apiBase='/api/org/project'
scopeLabel='项目' scopeLabel='项目'
onSaved={fetchList} onSaved={fetchList}
variant='link' renderActions={(limitItems) => (
/> <TableRowActions
<Button type='link' onClick={() => openMembers(record)}> items={[
{t('成员')} ...limitItems,
</Button> {
<Button type='link' onClick={() => openTokens(record)}> key: 'members',
{t('密钥')} label: t('成员'),
</Button> onClick: () => openMembers(record),
<Button type='link' onClick={() => openEdit(record)}> },
{
key: 'tokens',
label: t('密钥'),
onClick: () => openTokens(record),
},
]}
>
<Button type='link' size='small' onClick={() => openEdit(record)}>
{t('编辑')} {t('编辑')}
</Button> </Button>
</OrgRowActions> </TableRowActions>
)}
/>
), ),
}, },
]; ];
@@ -491,7 +501,7 @@ const OrgProjects = ({ orgId }) => {
{ {
title: t('成员'), title: t('成员'),
dataIndex: 'org_member_id', dataIndex: 'org_member_id',
render: (v) => memberNameMap[v] || `#${v}`, render: (v) => memberNameMap[v] || formatIdReference(v),
}, },
{ {
title: t('角色'), title: t('角色'),
@@ -550,7 +560,7 @@ const OrgProjects = ({ orgId }) => {
</Tag> </Tag>
) : ( ) : (
<Tag color='blue' size='small'> <Tag color='blue' size='small'>
{projectNameMap[v] || `#${v}`} {projectNameMap[v] || formatIdReference(v)}
</Tag> </Tag>
), ),
}, },
+6 -2
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatUserReference } from '../../helpers/safeDisplay';
import { import {
Copy as ActionCopy, Copy as ActionCopy,
Search as ActionSearch, Search as ActionSearch,
@@ -250,7 +251,10 @@ const OrgPromptRecords = ({ orgId }) => {
() => [ () => [
{ value: '', label: t('全部成员') }, { value: '', label: t('全部成员') },
...members.map((member) => { ...members.map((member) => {
const name = member.name || member.username || `User#${member.user_id}`; const name = formatUserReference(
member.name || member.username,
member.user_id,
);
return { return {
value: member.member_id, value: member.member_id,
label: label:
@@ -271,7 +275,7 @@ const OrgPromptRecords = ({ orgId }) => {
member?.remark || member?.remark ||
member?.display_name || member?.display_name ||
record.username || record.username ||
`User#${record.user_id}` formatUserReference(record.name || record.username, record.user_id)
); );
}; };
+2 -1
View File
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatUserReference } from '../../helpers/safeDisplay';
import { import {
RefreshCw as ActionRefreshCw, RefreshCw as ActionRefreshCw,
@@ -1013,7 +1014,7 @@ const OrgSettings = ({ orgId, orgRole }) => {
value={transferTargetId} value={transferTargetId}
onChange={(v) => setTransferTargetId(v)} onChange={(v) => setTransferTargetId(v)}
optionList={members.map((m) => ({ optionList={members.map((m) => ({
label: `${m.user_name || m.username || 'User#' + m.user_id} (${m.role})`, label: `${formatUserReference(m.user_name || m.username, m.user_id, t('未知用户'))} (${m.role})`,
value: m.user_id, value: m.user_id,
}))} }))}
/> />
+6 -2
View File
@@ -16,6 +16,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatIdReference } from '../../helpers/safeDisplay';
import { formatUserReference } from '../../helpers/safeDisplay';
import { import {
EyeOff as ActionEyeOff, EyeOff as ActionEyeOff,
@@ -512,7 +514,7 @@ const OrgTokens = ({ orgId, orgRole }) => {
key: 'creator_name', key: 'creator_name',
dataIndex: 'creator_name', dataIndex: 'creator_name',
width: 140, width: 140,
render: (name, record) => name || `User#${record.user_id}`, render: (name, record) => formatUserReference(name, record.user_id),
}, },
] ]
: []), : []),
@@ -1348,7 +1350,9 @@ const EditTokenModal = ({
(libraryRes.data.data || []) (libraryRes.data.data || [])
.filter((policy) => policy.enabled) .filter((policy) => policy.enabled)
.map((policy) => ({ .map((policy) => ({
label: nameById.get(policy.skill_id) || `#${policy.skill_id}`, label:
nameById.get(policy.skill_id) ||
formatIdReference(policy.skill_id),
value: policy.skill_id, value: policy.skill_id,
})), })),
); );
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatUserReference } from '../../../helpers/safeDisplay';
import { Trans } from 'react-i18next'; import { Trans } from 'react-i18next';
import { import {
ChevronRight as ActionChevronRight, ChevronRight as ActionChevronRight,
@@ -774,7 +775,11 @@ const FlowInner = ({
) : ( ) : (
<div className='space-y-1'> <div className='space-y-1'>
{sheetMembers.map((m) => { {sheetMembers.map((m) => {
const name = m.display_name || m.username || `#${m.user_id}`; const name = formatUserReference(
m.display_name || m.username,
m.user_id,
t('未知用户'),
);
return ( return (
<div <div
key={m.user_id} key={m.user_id}
@@ -16,6 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import { formatPercent } from '../../../helpers/safeDisplay';
import { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons'; import { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons';
import React, { useCallback, useEffect, useMemo, useState } from 'react'; import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@@ -93,11 +94,16 @@ const DeltaBadge = ({ cur, prev, t }) => {
if (!prev || prev <= 0) { if (!prev || prev <= 0) {
return <small>{t('无上期对比')}</small>; return <small>{t('无上期对比')}</small>;
} }
const pct = ((cur - prev) / prev) * 100; const pct = Number.isFinite(Number(cur))
const up = pct >= 0; ? ((Number(cur) - Number(prev)) / Number(prev)) * 100
: null;
const up = pct !== null && pct >= 0;
return ( return (
<small className={up ? 'is-up' : 'is-down'}> <small className={up ? 'is-up' : 'is-down'}>
{up ? '↑' : '↓'} {Math.abs(pct).toFixed(1)}%<em>{t('较上期')}</em> {pct === null
? '-'
: `${up ? '↑' : '↓'} ${formatPercent(Math.abs(pct), 1)}`}
<em>{t('较上期')}</em>
</small> </small>
); );
}; };
@@ -432,12 +438,14 @@ const OrgAnalyticsPanel = ({
width: 300, width: 300,
render: (_, r) => { render: (_, r) => {
const pct = const pct =
breakdownTotal > 0 ? ((r.quota || 0) / breakdownTotal) * 100 : 0; breakdownTotal > 0
? ((Number(r.quota) || 0) / breakdownTotal) * 100
: null;
return ( return (
<div className='oc-ea-cost-share'> <div className='oc-ea-cost-share'>
<div> <div>
<strong>{renderQuota(r.quota || 0, 2)}</strong> <strong>{renderQuota(r.quota || 0, 2)}</strong>
<span>{pct.toFixed(1)}%</span> <span>{formatPercent(pct, 1)}</span>
</div> </div>
<Progress <Progress
percent={Math.round(pct)} percent={Math.round(pct)}
@@ -59,7 +59,7 @@ const OrgScopedLimitButtons = ({
apiBase, apiBase,
scopeLabel, scopeLabel,
onSaved, onSaved,
variant = 'default', renderActions,
}) => { }) => {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -170,6 +170,13 @@ const OrgScopedLimitButtons = ({
const groupConfigured = parseGroups(record?.groups).length > 0; const groupConfigured = parseGroups(record?.groups).length > 0;
return ( return (
<>
{renderActions ? (
renderActions([
{ key: 'models', label: t('模型'), onClick: openModelModal },
{ key: 'groups', label: t('分组'), onClick: openGroupsModal },
])
) : (
<> <>
<Tooltip <Tooltip
content={t( content={t(
@@ -178,14 +185,10 @@ const OrgScopedLimitButtons = ({
)} )}
> >
<Button <Button
{...(variant === 'link' size='small'
? { type: 'link' } theme='light'
: { type={modelConfigured ? 'primary' : 'tertiary'}
size: 'small', icon={<ActionLayers size={14} />}
theme: 'light',
type: modelConfigured ? 'primary' : 'tertiary',
icon: <ActionLayers size={14} />,
})}
onClick={openModelModal} onClick={openModelModal}
> >
{t('模型')} {t('模型')}
@@ -198,19 +201,17 @@ const OrgScopedLimitButtons = ({
)} )}
> >
<Button <Button
{...(variant === 'link' size='small'
? { type: 'link' } theme='light'
: { type={groupConfigured ? 'primary' : 'tertiary'}
size: 'small', icon={<ActionLayers size={14} />}
theme: 'light',
type: groupConfigured ? 'primary' : 'tertiary',
icon: <ActionLayers size={14} />,
})}
onClick={openGroupsModal} onClick={openGroupsModal}
> >
{t('分组')} {t('分组')}
</Button> </Button>
</Tooltip> </Tooltip>
</>
)}
{/* 模型限制 Modal */} {/* 模型限制 Modal */}
<OrgModal <OrgModal
@@ -19,12 +19,10 @@ For commercial licensing, please contact support@quantumnous.com
import { useMemo } from 'react'; import { useMemo } from 'react';
import { theme } from 'antd'; import { theme } from 'antd';
import { useActualTheme } from '../../../context/Theme';
import { brandAccentFromToken } from '../../../components/ui/UiThemeProvider';
/** /**
* 消耗明细页(/org/logs)主题桥:只从 Ant token 推导页面局部变量,挂在页面根节点 style 上。 * 消耗明细页(/org/logs)主题桥:只从 Ant token 推导页面局部变量,挂在页面根节点 style 上。
* - --oc-brand:原型 --brand(页签、额度、统计图标等强调色),浅色 / 深色 / 自定义主色三态跟随 token。 * - --oc-brand 继承页面作用域的品牌强调色。
* - --oc-stat-brand-bg:统计图标浅底(原型 #b9650810 = 品牌色 6.3% 透明度)。 * - --oc-stat-brand-bg:统计图标浅底(原型 #b9650810 = 品牌色 6.3% 透明度)。
* - --ur-progress-done:任务进度满格描边(原型 strokeColor = var(--brand))。 * - --ur-progress-done:任务进度满格描边(原型 strokeColor = var(--brand))。
* - --oc-task-{success|failure|pending}-{text|bg|border}:绘图与视频“本页统计”语义色(Ant success / error / warning)。 * - --oc-task-{success|failure|pending}-{text|bg|border}:绘图与视频“本页统计”语义色(Ant success / error / warning)。
@@ -32,10 +30,8 @@ import { brandAccentFromToken } from '../../../components/ui/UiThemeProvider';
*/ */
export function useOrgLogsThemeStyle() { export function useOrgLogsThemeStyle() {
const { token } = theme.useToken(); const { token } = theme.useToken();
const dark = useActualTheme() === 'dark';
return useMemo( return useMemo(
() => ({ () => ({
'--oc-brand': brandAccentFromToken(token.colorPrimary, dark),
'--oc-stat-brand-bg': '--oc-stat-brand-bg':
'color-mix(in srgb, var(--oc-brand) 6.3%, transparent)', 'color-mix(in srgb, var(--oc-brand) 6.3%, transparent)',
'--ur-progress-done': 'var(--oc-brand)', '--ur-progress-done': 'var(--oc-brand)',
@@ -49,7 +45,7 @@ export function useOrgLogsThemeStyle() {
'--oc-task-pending-bg': token.colorWarningBg, '--oc-task-pending-bg': token.colorWarningBg,
'--oc-task-pending-border': token.colorWarningBorder, '--oc-task-pending-border': token.colorWarningBorder,
}), }),
[token, dark], [token],
); );
} }
+23 -14
View File
@@ -38,7 +38,7 @@ import {
} from 'lucide-react'; } from 'lucide-react';
import OrgStatCard from '../components/OrgStatCard'; import OrgStatCard from '../components/OrgStatCard';
import OrgStateBlock from '../components/OrgStateBlock'; import OrgStateBlock from '../components/OrgStateBlock';
import { OrgRowActions } from '../components/OrgListCard'; import { TableRowActions } from '@/components/common/table/TableToolbar';
import { renderQuota } from '../../../helpers/render'; import { renderQuota } from '../../../helpers/render';
import { deptFundApi } from './fundApi'; import { deptFundApi } from './fundApi';
import { FUND_STATE, buildFundTree } from './fundFormat'; import { FUND_STATE, buildFundTree } from './fundFormat';
@@ -193,12 +193,29 @@ const DeptFundsPanel = ({ orgId, deptId, deptName, refreshKey }) => {
}, },
{ {
title: t('操作'), title: t('操作'),
width: 210, width: 168,
fixed: 'right', fixed: 'right',
render: (_, r) => ( render: (_, r) => (
<OrgRowActions> <TableRowActions
items={
canTransfer
? [
r.account && {
key: 'ledger',
label: t('流水'),
onClick: () =>
setLedgerAccount({ id: r.account.id, name: r.name }),
},
{
key: 'recall',
label: t('回收'),
onClick: () => setTransfer({ mode: 'recall', row: r }),
},
]
: []
}
>
{canTransfer && ( {canTransfer && (
<>
<Button <Button
size='small' size='small'
type='link' type='link'
@@ -207,16 +224,8 @@ const DeptFundsPanel = ({ orgId, deptId, deptName, refreshKey }) => {
> >
{t('分配')} {t('分配')}
</Button> </Button>
<Button
size='small'
type='link'
onClick={() => setTransfer({ mode: 'recall', row: r })}
>
{t('回收')}
</Button>
</>
)} )}
{r.account && ( {!canTransfer && r.account && (
<Button <Button
size='small' size='small'
type='link' type='link'
@@ -227,7 +236,7 @@ const DeptFundsPanel = ({ orgId, deptId, deptName, refreshKey }) => {
{t('流水')} {t('流水')}
</Button> </Button>
)} )}
</OrgRowActions> </TableRowActions>
), ),
}, },
]; ];

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