diff --git a/.eslintrc.cjs b/.eslintrc.cjs deleted file mode 100644 index b80a005f..00000000 --- a/.eslintrc.cjs +++ /dev/null @@ -1,106 +0,0 @@ -module.exports = { - root: true, - env: { browser: true, es2021: true, node: true }, - parserOptions: { - ecmaVersion: 2022, - sourceType: 'module', - ecmaFeatures: { jsx: true }, - }, - settings: { - react: { version: 'detect' }, - }, - plugins: ['header', 'react-hooks', 'react', 'unused-imports'], - ignorePatterns: [ - 'dist/**', - 'node_modules/**', - 'logs/**', - 'report/**', - 'playwright-report/**', - 'test-results/**', - 'blob-report/**', - 'src/assets/brand-icons/*.js', - ], - overrides: [ - { - files: ['**/*.{js,jsx}'], - rules: { - 'no-restricted-imports': [ - 'error', - { - patterns: [ - { - group: [ - '@radix-ui/*', - '@floating-ui/*', - '@lobehub/ui', - '@lobehub/ui/*', - '@lobehub/icons', - '@lobehub/icons/*', - '@douyinfe/semi-*', - '@headlessui/*', - '@mui/*', - '@chakra-ui/*', - 'leva', - 'leva/*', - 'antd-style', - 'react-layout-kit', - ], - message: - 'Use antd public APIs or the audited local brand SVG assets. Preserve legacy components/ui callback contracts.', - }, - ], - }, - ], - 'header/header': [ - 2, - 'block', - [ - '', - '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 .', - '', - 'For commercial licensing, please contact support@quantumnous.com', - '', - ], - ], - 'no-multiple-empty-lines': ['error', { max: 1 }], - - // ===== 防线:杜绝“用了未定义/未导入标识符”导致的运行时崩溃(本次线上事故根因)===== - // 让规则识别 JSX 中使用到的组件/React,避免误报。 - 'react/jsx-uses-vars': 'error', - 'react/jsx-uses-react': 'error', - // 未定义标识符 = 直接报错(构建/CI 即拦截)。 - 'no-undef': 'error', - // 未使用的 import = error 且可 --fix 自动移除(含 JSX/副作用识别); - // 未使用的变量 = warn(不阻断,下划线前缀豁免)。 - 'no-unused-vars': 'off', - 'unused-imports/no-unused-imports': 'error', - 'unused-imports/no-unused-vars': [ - 'warn', - { - vars: 'all', - varsIgnorePattern: '^_', - args: 'none', - argsIgnorePattern: '^_', - ignoreRestSiblings: true, - }, - ], - // React Hooks 规则。 - 'react-hooks/rules-of-hooks': 'error', - 'react-hooks/exhaustive-deps': 'warn', - }, - }, - ], -}; diff --git a/.gitignore b/.gitignore index 492d69da..f3d34641 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,7 @@ node_modules/ # Local acceptance tests, browser sessions, and reports /e2e/ +/.e2e/ /tests/ *.test.* *.spec.* @@ -65,4 +66,4 @@ yarn.lock # i18n 批次中间产物(可由 scripts/i18n_kt_batches.cjs 重新生成,勿入库) scripts/kt_batches/ -scripts/kt_out/ \ No newline at end of file +scripts/kt_out/ diff --git a/AGENTS.md b/AGENTS.md index 8e641cc3..2fc4dcf3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -89,6 +89,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd | 企业中心 / 控制台 | `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/TABLE_COLUMN_SETTINGS_SPEC.md` | +| UI 审查清单 | `docs/ui-review-checklist.md` | | 历史改动与回滚 | `docs/CHANGELOG.md` | | Windows 命令、代码风格与提交规范 | `docs/standards/DEV_STANDARDS.md` 第 12 节 | @@ -122,7 +123,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd - 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。 - 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。 -> 规范版本:v3.5 · 更新:2026-11-18 +> 规范版本:v3.6 · 更新:2026-11-19 ## 10. 工具差异(本节允许不同) diff --git a/CLAUDE.md b/CLAUDE.md index 5031e513..e32c4587 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -89,6 +89,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd | 企业中心 / 控制台 | `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/TABLE_COLUMN_SETTINGS_SPEC.md` | +| UI 审查清单 | `docs/ui-review-checklist.md` | | 历史改动与回滚 | `docs/CHANGELOG.md` | | Windows 命令、代码风格与提交规范 | `docs/standards/DEV_STANDARDS.md` 第 12 节 | @@ -122,7 +123,7 @@ Windows 执行命令前按开发规范第 12.3 节设置 UTF-8;使用 `npm.cmd - 新规则先写入对应 `docs/` 文档,再在第 6 节加索引;改动只动相关段落,更新本节版本与日期。 - 文档的新增、调整、删除按 `docs/README.md` 的“阅读与维护”执行;删除与重命名需用户确认清单。 -> 规范版本:v3.5 · 更新:2026-11-18 +> 规范版本:v3.6 · 更新:2026-11-19 ## 10. 工具差异(本节允许不同) diff --git a/README.md b/README.md index adff39ea..b0190b6b 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ npm run dev /api /v1 /v1beta /mj /pg /dashboard /kling /jimeng /suno ``` -切换联调后端时修改 `.env.development.local` 中的 `DEV_PROXY_TARGET` 并重启服务;该变量只供 Vite 代理使用,不会暴露给浏览器。生产环境需由 Nginx 或网关配置同源反向代理,`package.json` 中的 `proxy` 字段不生效。 +切换联调后端时修改 `.env.development.local` 中的 `DEV_PROXY_TARGET` 并重启服务;该变量只供 Vite 代理使用,不会暴露给浏览器。生产环境需由 Nginx 或网关配置同源反向代理,Vite 开发代理不会进入生产产物。 ### 可选:直接访问独立后端域名 @@ -159,6 +159,8 @@ monkey-ai-web/ ### 本地 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 加载到环境变量: ```powershell diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 4ce19ad6..2b208c3f 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,6 +1,6 @@ # 变更记录(CHANGELOG) -> 状态:有效(持续追加) · 更新:2026-11-18 · 版本:v3.5 +> 状态:有效(持续追加) · 更新:2026-11-19 · 版本:v3.6 对现状仍有影响的功能与修复记录,按日期倒序。改造、迁移、优化等一次性过程不在此记录。 @@ -8,6 +8,169 @@ **记录规则**:每条写“范围、变更、影响、回滚、关联”五项;回滚优先 `git revert <提交>`,提交含多项改动时按文件还原(`git checkout <提交>^ -- <文件>`),不整仓 reset。本文不作为规则依据。 +## 2026-11-20 + +### 修复 · 全量 undefined / NaN 展示防护与主题兼容回归 + +- **范围**:分析看板、组织/个人中心、充值/发票/订单/订阅、佣金、渠道模型测试、服务监控,以及亮色/暗色主题下的数字展示路径。 +- **变更**:新增并复用安全数字、金额、百分比与编号展示兜底;缺失或非法接口字段不再拼接为 `undefined`、`NaN%`、`xxundefined`;补齐 9 个语言包的未知档位文案与单元测试隔离 mock。 +- **影响**:只收敛用户可见展示和格式化健壮性,不改变请求载荷、权限、路由、计费或登录业务语义;主题色继续遵循现有 token 与亮暗主题派生规则。 +- **回滚**:按本条关联文件逐项回退;不使用整库 reset,保留其他会话的独立改动。 +- **关联**:`src/helpers/safeDisplay.js`、`src/helpers/render.jsx`、相关 `src/components/` 与 `src/pages/` 展示文件、`test/unit/safe-display.test.js`、`test/unit/market-name-search.test.js`、`.e2e/report/report.html`。 + +## 2026-11-19 + +### 更新 · ESLint 9 + +- **范围**:JavaScript / JSX 静态检查与 UI 依赖审计。 +- **变更**:升级至 ESLint 9.39.5 并迁移为扁平配置,保留原有检查规则。 +- **影响**:不改变应用运行时依赖。 +- **回滚**:同步还原配置、依赖锁文件和 UI 审计脚本的本条差异。 +- **关联**:`eslint.config.cjs`、`scripts/check-ui-dependencies.mjs`。 + +### 调整 · 对齐操作审计筛选栏 + +- **范围**:企业审计日志的「操作审计」页签。 +- **变更**:复用用户中心密钥管理的筛选表单布局、按钮与移动端折叠。 +- **影响**:保留操作类型、选择即筛选、重置、搜索和刷新逻辑;不影响「提示词记录」。 +- **回滚**:仅还原本条涉及的操作审计筛选栏改动。 +- **关联**:`src/pages/Organization/OrgAudit.jsx`。 + +### 调整 · 收窄表格「更多」菜单的使用范围 + +- **范围**:此前接入公共行操作菜单的表格。 +- **变更**:仅用户列表与合作伙伴列表保留新版「更多」,其他列表恢复原操作入口。 +- **影响**:保留现有权限、业务回调、筛选、分页及空态。 +- **回滚**:仅还原本条菜单差异,不覆盖其他页面改动。 +- **关联**:`src/components/common/table/TableToolbar.jsx`、`docs/standards/UI_COMPONENT_STANDARDS.md`。 + +### 调整 · 企业表格分页与用量明细对齐 + +- **范围**:企业中心表格、企业密钥列表、用户中心调用明细及控制台使用明细。 +- **变更**:企业表格统一底部分页;密钥表按可见列宽度滚动;两端共用「用时 / 首字」标签和居中样式,调用明细与使用明细的操作入口均显示「详情」。 +- **影响**:前端分页不追加请求,接口分页沿用原有查询,树形数据保留父子关系。 +- **回滚**:只还原本条涉及的企业列表、分页适配和用量明细改动。 +- **关联**:`docs/ui/ORG_CENTER_SPEC.md`、`src/components/table/usage-logs/UsageLogsColumnDefs.jsx`。 + +### 调整 · 列表筛选、工具栏及分页对齐密钥管理 + +- **范围**:平台、企业、个人分佣,兑换码、会员卡、发票和用户中心密钥管理,含页签及明细表格。 +- **变更**:共享搜索按钮、筛选栅格和工具栏布局,统一分页总数、每页条数与切换行为。 +- **影响**:保留现有权限、接口用途和即时筛选;分佣档位每页条数传入列表请求,导出仍读取完整结果。 +- **回滚**:只还原本条所列的组件、分页和规范改动。 +- **关联**:`docs/standards/UI_COMPONENT_STANDARDS.md`、`src/components/console/ConsoleCollection.jsx`。 + +### 清理 · 移除无效的旧代理配置 + +- **范围**:前端包配置与联调说明。 +- **变更**:删除 `package.json` 中 Vite 不读取的 `proxy` 字段。 +- **影响**:不改变依赖、锁文件、本地联调后端或生产网关。 +- **回滚**:仅还原本条涉及的包配置与文档。 +- **关联**:`package.json`、`vite.config.js`、`README.md`。 + +### 修复 · 并发请求失败与会话过期提示 + +- **范围**:统一请求工具、登录入口及企业预算的关联查询。 +- **变更**:会话 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`。 + +### 功能 · 恢复服务监控入口并接入超管开关 + +- **范围**:用户中心桌面侧栏、移动底栏、服务监控路由与面包屑。 +- **变更**:恢复服务监控菜单和页面,复用超管运营设置中的 `SidebarModulesAdmin.userCenter.serviceDashboard` 开关;桌面、移动和路由统一判断区域开关、功能开关及可见分组。 +- **影响**:未配置时默认开启;关闭或分组不允许时不挂载监控页面、不请求监控数据,直接访问新旧地址均回到首个可见页面,无可见页面时回到首页;服务监控接口与刷新逻辑保持原有行为。 +- **回滚**:通过超管开关关闭入口;需要代码回滚时还原本条相关导航、路由与可见性判断。 +- **关联**:`docs/ui/SERVICE_DASHBOARD_SPEC.md`、`src/helpers/navigationVisibility.js`、`src/pages/UserCenter/`。 + ## 2026-11-18 ### 调整 · 认证页表单必填标识、就地校验与间距统一 @@ -210,14 +373,6 @@ - **回滚**:`controls.jsx` 与上述三处调用方需一起还原;文档按文件还原。 - **关联**:`docs/standards/DEV_STANDARDS.md` 2.3 -### 调整 · 隐藏用户中心服务监控 - -- **范围**:用户中心桌面侧栏、移动端底栏、服务监控路由与面包屑。 -- **变更**:移除服务监控菜单,原页面地址与旧 `/service-dashboard` 地址均跳转到用户中心首个已开放页面;默认页候选排除服务监控,无可用页面时回到首页。 -- **影响**:服务监控不再挂载,不触发该页面的监控请求;保留页面源码与后台配置,其他菜单沿用原有配置。 -- **回滚**:仅还原本条涉及的用户中心入口、侧栏、面包屑及服务监控规范差异。 -- **关联**:`docs/ui/SERVICE_DASHBOARD_SPEC.md`。 - ## 2026-11-17 ### 调整 · 官网设置指标只填数字并实时预览官网展示 diff --git a/docs/README.md b/docs/README.md index 47f5ba07..b30f62a4 100644 --- a/docs/README.md +++ b/docs/README.md @@ -18,7 +18,7 @@ | 修改企业中心 / 控制台 | `ui/ORG_CENTER_SPEC.md` / `ui/CONSOLE_SPEC.md` | — | | 修改模型超市 / 技能超市 | `ui/MODEL_MARKET_SPEC.md` / `ui/SKILL_MARKET_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` | — | 每份规范开头都有“何时阅读”和“速查”表,先看速查,需要细节再按章节号读取。 @@ -38,6 +38,7 @@ | `ui/MODEL_MARKET_SPEC.md` | 模型超市 | 约 8KB | | `ui/SKILL_MARKET_SPEC.md` | 技能超市与数据模式 | 约 8KB | | `ui/TABLE_COLUMN_SETTINGS_SPEC.md` | 表格列设置 | 约 4KB | +| `ui-review-checklist.md` | 双端 UI 审查、交互与证据记录清单 | 约 3KB | | `CHANGELOG.md` | 对现状仍有影响的功能与修复记录 | 约 6KB | ## 规则优先级 diff --git a/docs/standards/DEV_STANDARDS.md b/docs/standards/DEV_STANDARDS.md index deda389b..f195f133 100644 --- a/docs/standards/DEV_STANDARDS.md +++ b/docs/standards/DEV_STANDARDS.md @@ -118,7 +118,8 @@ ESLint 规则 `header/header` 要求每个 `.js/.jsx` 顶部带 AGPL 许可证 ### 3.1 规则 - 只用 `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` 对象,不手拼查询字符串(手拼不会编码 `&`、`#`、中文)。 - 响应按 `{ success, message, data }` 处理,先判断 `success`;具体字段以接口契约为准。 - 分页参数 `p` 从 1 开始,`page_size` 默认 `ITEMS_PER_PAGE`(10,须与后端一致);后端对 `page_size > 100` 静默截断为 100,需要全量数据时用 `collectPagedItems(fetchPage)`(`src/helpers/paging.js`)。 diff --git a/docs/standards/UI_COMPONENT_STANDARDS.md b/docs/standards/UI_COMPONENT_STANDARDS.md index 51784eac..bdcc1a2f 100644 --- a/docs/standards/UI_COMPONENT_STANDARDS.md +++ b/docs/standards/UI_COMPONENT_STANDARDS.md @@ -53,9 +53,9 @@ 品牌主题预设在 `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 取色方式 @@ -132,6 +132,9 @@ html.dark .km-page { - 行为:搜索与重置都回到第 1 页;重置 = 清空表单 + 以默认条件重新查询;只切换筛选的页签放在筛选卡上方。 - 移动端:用户中心与控制台默认收起,通过“显示 / 隐藏操作项”或“筛选”按钮展开;列设置入口不随筛选收起。 - 控制台使用 `ConsoleSearchBar` + `ConsoleSearchActions`,企业中心使用 `OrgFilterCard`,不要另写网格。 +- 标准列表以 `/console/token` 为参考,覆盖控制台分佣、兑换码、会员卡和发票,企业及个人分佣,以及用户中心密钥管理(含各自子页、页签和详情列表)。使用 `ConsoleCollection`(或通过 `CardPro` 接入);独立列表可用 `ConsoleCollectionSearch` + `ConsoleFilterGrid`。筛选栅格为三列、≤ 1100px 两列、≤ 768px 单列。 +- 搜索操作在筛选卡右下,先默认样式“重置”(无图标),再带放大镜的主按钮“搜索”;点击和回车共用同一个提交入口。保留原有即时筛选及请求方式,移动端统一通过“显示/隐藏操作项”切换。 +- 工具栏在列表卡内、表格上方:列表标题、计数或快捷筛选在左;已有的批量、导出、刷新、列设置、新建等动作在右,主操作尽量靠右,使用公共操作图标和清晰文案。窗口变窄时自然换行。只读明细若没有筛选或业务动作,不新增占位按钮。 ## 5. 表格 @@ -149,7 +152,7 @@ html.dark .km-page { - 每列显式 `width`,长文本 `ellipsis` 并配 `Tooltip`;金额与数量右对齐;时间统一格式,必要时日期与时间分两行。 - 状态列用 `Tag` 或 `Switch`(见第 11 节);启停开关请求中禁用,失败恢复原状态。 -- 操作列放在最后,按钮为 `type='link' size='small'`,危险操作加 `danger`,同一行操作间距 8–10px;用户中心、企业中心、控制台(含系统设置)的操作列统一 `fixed: 'right'`;操作较多时折叠到“更多”下拉。 +- 操作列放在最后,标题固定为“操作”,按钮为 `type='link' size='small'`,同一行操作间距 8px;用户中心、企业中心、控制台(含系统设置)的操作列统一 `fixed: 'right'`。`/console/user` 的用户列表和 `/console/commission?view=partners` 的合作伙伴列表使用 `TableRowActions`:直出高频动作,其余放进带下箭头的文字“更多”菜单。其他列表沿用既有操作呈现方式,不批量套用此菜单。菜单点击打开、右对齐,无有效菜单项时不渲染入口;危险项置末、标记 `danger` 并保留业务确认。现有权限、状态限制、禁用项和回调不得因收纳而改变,方向键、Enter、Escape 可操作菜单。 - 三中心表格通过 `CenterActionTable` 统一处理,最后一列存在创建、查看、编辑、测试、详情、删除、添加、设置、配置、弹窗 / 抽屉或请求交互时,列头统一显示“操作”并固定右侧,宽度按按钮 / 交互数量计算。没有操作列但估算列宽超出容器时,从右侧固定末 4 列,列数不足时降为 3、2、1 列。固定列使用不透明底色并保持表头层级;横向滚动条遵循 Ant Design 官方固定列表格行为,允许鼠标、触控板、触屏和键盘滚动,不隐藏滚动条。 - 列显隐只在已有列设置的表格中提供,统一使用 `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` 类名补丁;表头不换行,表头与正文沿用同一列宽和对齐方式。 @@ -160,15 +163,15 @@ html.dark .km-page { | 状态 | 写法 | | --- | --- | | 加载 | `Table loading` | -| 空数据 | `Empty image={Empty.PRESENTED_IMAGE_SIMPLE}`,文案沿用页面原有 | +| 空数据 | 标准列表使用 `TableEmpty`(`ConsoleListTable` 默认接入):保留表头,简单插图 + “暂无数据”在当前可见宽度内居中;加载中不把空态当作查询结果,失败继续走错误提示 | | 批量操作 | `rowSelection={{ selectedRowKeys, onChange }}`,未选中时批量按钮禁用 | ## 6. 分页 - 位置:列表卡底部右对齐,上距 16px;移动端换行显示并提供快速跳页。 - 外观:小尺寸,可切换每页条数 `[10, 20, 50, 100]`,总数文案 `t('共 {{total}} 条', { total })`。 -- 用法:分页列表使用 `@/components/ui` 的 `Table` / `Pagination`,传 `currentPage`、`pageSize`、`total`、`onPageChange(page)`、`onPageSizeChange(size)`。`/console`、`/org` 下由封装自动统一外观与回调;其他路由需显式传 `showSizeChanger`、`pageSizeOpts`、`showTotal`,并设置 `preventPageChangeOnPageSizeChange: true`,避免改页容量时请求两次。 -- 删除当前页最后一条后回到上一页;前端分页的列表在筛选或数据变化时回到第 1 页。 +- 用法:分页列表使用 `@/components/ui` 的 `Table` / `Pagination`。第 4 节的标准列表及其明细分页均沿用密钥管理:表格底部右对齐、小尺寸,依次显示“共 N 条”、上一页/页码/下一页、每页条数(10、20、50、100),移动端保留跳页。已加载的明细可本地分页;服务端分页传 `currentPage`、`pageSize`、`total` 以及分页回调,切换每页条数回到第 1 页,只发一次请求。导出仍作用于原有结果范围,不受当前页条数影响。 +- 删除当前页最后一条后回到上一页;前端分页的列表在筛选或数据变化时回到第 1 页。`/org/*` 的独立表格、页签和下钻明细均用此分页规则;已加载的树形表格按根节点分页,子节点不拆散;接口已分页时沿用原查询与总数。 ## 7. 表单项 @@ -242,7 +245,7 @@ html.dark .km-page { 组件分层(antd 原生、中心封装、契约封装、专用组件)及选用方式见 `DEV_STANDARDS.md` 2.1、2.2 节。`src/components/ui/*` 只做视图映射,不放请求、权限与业务状态。 -- 禁止导入:`@lobehub/*`、Radix UI、Floating UI、Semi、MUI、Chakra、Headless UI、leva、antd-style、react-layout-kit(`.eslintrc.cjs` 的 `no-restricted-imports`)。 +- 禁止导入:`@lobehub/*`、Radix UI、Floating UI、Semi、MUI、Chakra、Headless UI、leva、antd-style、react-layout-kit(`eslint.config.cjs` 的 `no-restricted-imports`)。 - `npm run check:ui` 审计源码导入、完整 lock 图与品牌图标资产 hash,已包含在 `npm run check` 中。 - `antd` 与 `@ant-design/icons` 精确锁定版本;`src/components/ui/antd-v5-compat.css` 统一标签间距、分页选择器宽度与必填标记字体,页面样式可以覆盖。 - 当前版本 API 约定:Card 用 `variant`,Drawer 用 `size`,弹层遮罩用 `mask` 配置,Alert 标题用 `title`;样式选择器使用 `.ant-modal-container`、`.ant-alert-title`、`.ant-collapse-body`。聊天消息列表使用 `List`(antd 已标记弃用),替换前需先建立该区域的视觉基线。 diff --git a/docs/ui-review-checklist.md b/docs/ui-review-checklist.md new file mode 100644 index 00000000..47bdfe9a --- /dev/null +++ b/docs/ui-review-checklist.md @@ -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、语言、字体和数据模式;跨主题像素变化不等于缺陷,只有同条件基线比较可按视觉阈值判定。 diff --git a/docs/ui/GLOBAL_UI_BASELINE.md b/docs/ui/GLOBAL_UI_BASELINE.md index 1460e8bd..c3e3f362 100644 --- a/docs/ui/GLOBAL_UI_BASELINE.md +++ b/docs/ui/GLOBAL_UI_BASELINE.md @@ -1,6 +1,6 @@ # 后台 UI 全局基线 -> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v3.11 +> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-19 · 版本:v3.12 后台外壳与布局基线:顶栏、侧栏、公告、页头与内容边距、登录页,以及原型未定义场景、登录关卡与验收流程。主题与组件样式见 `UI_COMPONENT_STANDARDS.md`。 @@ -51,7 +51,7 @@ - 桌面高 72px、移动 56px,另含 1px 底部分隔线;背景、文字、分隔线跟随双主题变量。 - 主导航:导航项撑满顶栏,左右内边距 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` 与共享顶栏。 - WeyAi 下载按钮复用现有下载配置与权限判定,跳转 `/weyai/download`;使用 antd text 按钮默认悬停背景与 `Tooltip`,不硬编码外部地址。 diff --git a/docs/ui/ORG_CENTER_SPEC.md b/docs/ui/ORG_CENTER_SPEC.md index 99559b23..1a46da08 100644 --- a/docs/ui/ORG_CENTER_SPEC.md +++ b/docs/ui/ORG_CENTER_SPEC.md @@ -23,7 +23,7 @@ - 视觉依据:在线原型 `http://192.168.0.161:8888` 顶栏“企业中心”(深色用“切换至暗色主题”),只作视觉依据,不作业务、路由、数据依据。 - 只对齐背景、字体、图标、表格、表单、卡片、页签、搜索条件、操作列、弹窗、按钮、颜色、文字、间距与已有交互反馈;不改请求、载荷、状态、路由、权限与触发条件。 -- 原型有而系统无的功能不补建:员工筛选卡、CSV 导出、尺寸切换分页、新建员工 / 分配角色 / 离职、角色管理、在职 / 离职筛选、订单号搜索、分组列、发票入口。例外:企业密钥管理的分组列与列设置已按需求实现。 +- 原型有而系统无的功能不补建:员工筛选卡、CSV 导出、新建员工 / 分配角色 / 离职、角色管理、在职 / 离职筛选、订单号搜索、分组列、发票入口。例外:企业密钥管理的分组列与列设置已按需求实现。 ## 2. 作用域与变量 @@ -49,7 +49,7 @@ 通用卡片、筛选栏、表格、分页、弹层、页签、标签样式按 `UI_COMPONENT_STANDARDS.md`;企业中心的差异如下。 - **页头**:`OrgPageHeader`(内部复用 `UserCenterPageHeader`),规格见 `GLOBAL_UI_BASELINE.md` 4.4;页头不放操作按钮,操作移入列表卡头。面包屑分组见 4.4 第 3 条。 -- **列表卡 `OrgListCard`**:卡头与表格间距 20px;表格为紧凑变体(正文 13px,表头 12px / 500、底色 `--oc-soft`,行上下内边距 17px);分页不提供每页条数切换。 +- **列表卡 `OrgListCard`**:卡头与表格间距 20px;表格为紧凑变体(正文 13px,表头 12px / 500、底色 `--oc-soft`,行上下内边距 17px);分页按公共组件规范,覆盖页签及表格明细。 - **筛选卡 `OrgFilterCard`**:固定 3 列;筛选取值与生效时机沿用原页面(审计日志为“选择即筛选”,“搜索”以当前条件重新查询)。 - **行操作 `OrgRowActions`**:link 按钮 13 / 24px、无内边距、间距 10px,不带图标。 - **列表页签 `.oc-list-tabs`**:导航高 44px,页签内边距 12px 0,选中与悬停色为 `--oc-brand`;只切换筛选时加 `.oc-tabs-nav-only`。 @@ -66,9 +66,9 @@ | 数据看板 | `oc-dash-*` hero(健康提示“企业运行正常”、企业名、企业额度、组织概况)+ `OrgAnalyticsPanel`(汇总条、趋势 `Segmented`、分布、明细页签) | 时间范围 7 / 30 / 90 天;企业名来自 `orgInfo.name`,无值时隐藏 | | 员工管理 | 页签(员工权限 / 员工账号)+ 列表卡;首列与操作列固定;备注独立列;状态 `Switch` | 无筛选卡与在职 / 离职页签 | | 项目管理 | `OrgListCard` + link 操作(模型 / 分组 / 成员 / 密钥 / 编辑);状态开关 | 操作列不再显示“停用” | -| 预算中心 | `.oc-policy` 固定说明条;列宽 300 / 110 / 260 / 120 / 120 / 130;状态开关 | 无分页 | +| 预算中心 | `.oc-policy` 固定说明条;列宽 300 / 110 / 260 / 120 / 120 / 130;状态开关 | 已加载数据前端分页 | | 审批中心 | 状态页签(回调 `setStatusFilter`)+ 申请列表卡;拒绝弹窗竖排表单项 | — | -| 密钥管理 | 密钥框 + 显隐 / 复制、可用模型 link、分组列、状态开关、绝对时间;列设置用共享组件;创建 / 编辑为 560px `OrgSideSheet` | 列设置只在当前页面生效 | +| 密钥管理 | 密钥框 + 显隐 / 复制、可用模型 link、分组列、状态开关、绝对时间;列设置用共享组件;创建 / 编辑为 560px `OrgSideSheet` | 列设置只在当前页面生效;非操作列整体横向滚动,仅在可见列宽度超过容器时显示滚动条 | | 企业充值 | 企业钱包 + 充值工作区(额度卡 / 自定义 / 支付方式)+ 订单卡 + 记录;订单“立即充值”与支付方式点击同为 `handlePreTopUp` | 档位与折扣来自后台配置;无订单号搜索与发票入口 | | 消耗明细 | 统计卡 + 页签(明细日志 / 成员排行 / 绘图与视频)+ 三列筛选卡 + 列表卡;查询按钮为“搜索”(`handleSearch`) | 见第 5 节 | | 审计日志 | 页签 + 筛选卡(操作类型)+ 操作记录卡;“提示词记录”页签沿用原显隐 | — | @@ -79,18 +79,18 @@ - 剩余额度提示按未取整占比判定:> 20% 为“可用额度充足”(`#438568`),0 < 占比 ≤ 20% 为“可用额度偏低”(`#9c6b25`),≤ 0 为“可用额度已用尽”(`#b34c4c`);数据无效时隐藏,仅作提示,不影响计费或拦截。 - 多维用量分析工具组用原生 `Select` / `Button`:维度 132px、时间 86px、刷新 34px,高 34px、间距 8px。 -- 模型明细使用已加载数据做前端分页(每页 10 条),翻页不请求接口,维度、时间或数据变化时回到第一页;表格随页面自然展开,仅窄屏横向滚动。 +- 模型明细使用已加载数据做前端分页(默认每页 10 条),翻页不请求接口,维度、时间或数据变化时回到第一页;表格随页面自然展开,仅窄屏横向滚动。 ## 5. 消耗明细(/org/logs) - 绘图与视频由 `components/OrgTaskRecords.jsx` 呈现,复用 `useTaskLogsData({ organizationMode: true })`、`TaskLogsFilters`、`getTaskLogsColumns`、`exportTaskLogsPageCsv`、`ColumnSelectorModal`、`ContentModal`;结构为筛选卡 + “任务记录”列表卡(导出本页 / 刷新 / 列设置),不渲染“本页统计”区块,移动端筛选直接展开。 -- 任务表列宽 185 / 185 / 110 / 110 / 250 / 330 / 110 / 155 / 145 / 150;模型为行内胶囊,费用主色右对齐;分页 10 / 20 / 50,“共 N 条”。“刷新”与“搜索”调用同一 `refresh`。 +- 任务表列宽 185 / 185 / 110 / 110 / 250 / 330 / 110 / 155 / 145 / 150;模型为行内胶囊,费用主色右对齐;分页沿用公共规范。“刷新”与“搜索”调用同一 `refresh`。 - 时间范围为本页签自有的可编辑字段(默认最近 7 天,含快捷预设),与“明细日志”筛选互不影响;起止颠倒沿用原提示。 - 末列“操作”不固定:视频任务显示“点击预览视频”,失败任务保留失败原因查看,其余显示“-”。 - 预览视频沿用 `ContentModal`:标题栏“视频预览”与关闭按钮、16:9 播放区、加载态、播放失败或无地址时 `Empty` 空态、页脚复制链接 / 新标签页打开 / 关闭;关闭时暂停视频,重开同一视频不残留加载指示。 - 成员排行行键使用 `user_id-名次序号`,避免后端同一成员多行时出现重复 key。 - 明细日志查询不写 URL;绘图与视频筛选沿用原有 URL 同步。 -- 保留差异:明细日志无列设置、分组列、操作列与尺寸切换;任务表无渠道 / 用户 ID 筛选、平台列、排序与任务 ID 复制。 +- 保留差异:明细日志无列设置、分组列、操作列;任务表无渠道 / 用户 ID 筛选、平台列、排序与任务 ID 复制。 ## 6. 验收要点 diff --git a/docs/ui/SERVICE_DASHBOARD_SPEC.md b/docs/ui/SERVICE_DASHBOARD_SPEC.md index 65dffed2..a822465b 100644 --- a/docs/ui/SERVICE_DASHBOARD_SPEC.md +++ b/docs/ui/SERVICE_DASHBOARD_SPEC.md @@ -1,6 +1,6 @@ # 服务监控 UI 规范(/user-center/service-dashboard) -> 状态:有效(页面暂不开放) · 适用:antd 6.7.0 · 更新:2026-11-18 · 版本:v2.2 +> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-19 · 版本:v2.3 服务监控页的规范:分组可用性、历史条与详情弹窗。 @@ -10,7 +10,7 @@ | 关注点 | 规则 | | --- | --- | -| 路由 | 桌面侧栏与移动底栏隐藏服务监控;`/user-center/service-dashboard` 及旧 `/service-dashboard` 均回到用户中心首个已开放页面,无可用页面时回到首页;保留页面源码,以下视觉与验收规则供恢复时使用 | +| 路由 | `/user-center/service-dashboard`,旧 `/service-dashboard` 重定向;桌面侧栏、移动底栏和页面访问统一受超管“运营设置 → 左侧边栏模块管理 → 用户中心 → 服务监控”开关(`SidebarModulesAdmin.userCenter.serviceDashboard`)及区域 / 功能可见分组控制;关闭或无分组权限时不挂载页面,回到首个可见页面,无可用页面时回到首页;未配置时沿用默认开启 | | 组件 | `Card`、`Button`、详情 `Modal` + `Statistic` + `Table`、`Tooltip`、`Spin` / `Empty` | | 主题 | `theme.useToken()` 注入 `--service-*`;正常态跟随 `colorPrimary`,告警 / 异常用 `colorWarning` / `colorError` | | 业务 | 60 秒自动刷新、逐秒倒计时、分组权限、模型测试与请求不变 | diff --git a/eslint.config.cjs b/eslint.config.cjs new file mode 100644 index 00000000..066fef8d --- /dev/null +++ b/eslint.config.cjs @@ -0,0 +1,133 @@ +const globals = require('globals'); +const { rules: headerRules } = require('eslint-plugin-header'); +const react = require('eslint-plugin-react'); +const reactHooks = require('eslint-plugin-react-hooks'); +const unusedImports = require('eslint-plugin-unused-imports'); + +const headerRule = headerRules.header; +const header = { + rules: { + header: { + ...headerRule, + meta: { + ...headerRule.meta, + schema: [ + { enum: ['block', 'line'] }, + { type: 'array', items: { type: 'string' } }, + ], + }, + }, + }, +}; + +module.exports = [ + { + ignores: [ + '**/.*', + 'dist/**', + 'node_modules/**', + 'logs/**', + 'report/**', + 'playwright-report/**', + 'test-results/**', + 'blob-report/**', + 'src/assets/brand-icons/*.js', + ], + }, + { + files: ['**/*.{js,jsx}'], + linterOptions: { reportUnusedDisableDirectives: 'off' }, + languageOptions: { + ecmaVersion: 2022, + sourceType: 'module', + parserOptions: { ecmaFeatures: { jsx: true } }, + globals: { ...globals.browser, ...globals.node, ...globals.es2021 }, + }, + settings: { react: { version: 'detect' } }, + plugins: { + header, + react, + 'react-hooks': reactHooks, + 'unused-imports': unusedImports, + }, + rules: { + 'no-restricted-imports': [ + 'error', + { + patterns: [ + { + group: [ + '@radix-ui/*', + '@floating-ui/*', + '@lobehub/ui', + '@lobehub/ui/*', + '@lobehub/icons', + '@lobehub/icons/*', + '@douyinfe/semi-*', + '@headlessui/*', + '@mui/*', + '@chakra-ui/*', + 'leva', + 'leva/*', + 'antd-style', + 'react-layout-kit', + ], + message: + 'Use antd public APIs or the audited local brand SVG assets. Preserve legacy components/ui callback contracts.', + }, + ], + }, + ], + 'header/header': [ + 2, + 'block', + [ + '', + '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 .', + '', + 'For commercial licensing, please contact support@quantumnous.com', + '', + ], + ], + 'no-multiple-empty-lines': ['error', { max: 1 }], + + // ===== 防线:杜绝“用了未定义/未导入标识符”导致的运行时崩溃(本次线上事故根因)===== + // 让规则识别 JSX 中使用到的组件/React,避免误报。 + 'react/jsx-uses-vars': 'error', + 'react/jsx-uses-react': 'error', + // 未定义标识符 = 直接报错(构建/CI 即拦截)。 + 'no-undef': 'error', + // 未使用的 import = error 且可 --fix 自动移除(含 JSX/副作用识别); + // 未使用的变量 = warn(不阻断,下划线前缀豁免)。 + 'no-unused-vars': 'off', + 'unused-imports/no-unused-imports': 'error', + 'unused-imports/no-unused-vars': [ + 'warn', + { + vars: 'all', + varsIgnorePattern: '^_', + args: 'none', + caughtErrors: 'none', + argsIgnorePattern: '^_', + ignoreRestSiblings: true, + }, + ], + // React Hooks 规则。 + 'react-hooks/rules-of-hooks': 'error', + 'react-hooks/exhaustive-deps': 'warn', + }, + }, +]; diff --git a/package-lock.json b/package-lock.json index 1c9c18be..2f450034 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,11 +1,11 @@ { - "name": "react-template", + "name": "monkey-ai-web", "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "react-template", + "name": "monkey-ai-web", "version": "0.1.0", "dependencies": { "@ant-design/icons": "6.3.4", @@ -56,11 +56,12 @@ "@vitejs/plugin-react": "^4.2.1", "autoprefixer": "^10.4.21", "esbuild": "0.21.5", - "eslint": "8.57.0", + "eslint": "9.39.5", "eslint-plugin-header": "^3.1.1", "eslint-plugin-react": "^7.37.5", "eslint-plugin-react-hooks": "^5.2.0", - "eslint-plugin-unused-imports": "^3.2.0", + "eslint-plugin-unused-imports": "4.4.1", + "globals": "16.5.0", "i18next-cli": "^1.10.3", "postcss": "^8.5.3", "prettier": "^3.0.0", @@ -961,38 +962,119 @@ "node": "^12.0.0 || ^14.0.0 || >=16.0.0" } }, + "node_modules/@eslint/config-array": { + "version": "0.21.2", + "resolved": "https://registry.npmmirror.com/@eslint/config-array/-/config-array-0.21.2.tgz", + "integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.5" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.2", + "resolved": "https://registry.npmmirror.com/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", + "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmmirror.com/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, "node_modules/@eslint/eslintrc": { - "version": "2.1.4", - "resolved": "https://registry.npmmirror.com/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", - "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", + "version": "3.3.7", + "resolved": "https://registry.npmmirror.com/@eslint/eslintrc/-/eslintrc-3.3.7.tgz", + "integrity": "sha512-F42g89Qd5oAWtp0k0nnSrjziAKza7w8SVT4mStc18LZMaRb4J1HQAHLCalEtDCxrTuksx7NU9qsmeLwpOfPqWw==", "dev": true, "license": "MIT", "dependencies": { - "ajv": "^6.12.4", + "ajv": "^6.14.0", "debug": "^4.3.2", - "espree": "^9.6.0", - "globals": "^13.19.0", + "espree": "^10.0.1", + "globals": "^14.0.0", "ignore": "^5.2.0", "import-fresh": "^3.2.1", - "js-yaml": "^4.1.0", - "minimatch": "^3.1.2", + "js-yaml": "^4.3.2", + "minimatch": "^3.1.5", "strip-json-comments": "^3.1.1" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" } }, - "node_modules/@eslint/js": { - "version": "8.57.0", - "resolved": "https://registry.npmmirror.com/@eslint/js/-/js-8.57.0.tgz", - "integrity": "sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g==", + "node_modules/@eslint/eslintrc/node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmmirror.com/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", "dev": true, "license": "MIT", "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@eslint/js": { + "version": "9.39.5", + "resolved": "https://registry.npmmirror.com/@eslint/js/-/js-9.39.5.tgz", + "integrity": "sha512-QywQuszQh77pIXCsq998c8hbhSTI/azTty1Z6N53dmAudKHhy573j3yvRLsX2BSp8YpLtoCEG8E9DJe+8zUh4A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "resolved": "https://registry.npmmirror.com/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.1", + "resolved": "https://registry.npmmirror.com/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", + "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, "node_modules/@formatjs/icu-messageformat-parser": { @@ -1018,20 +1100,42 @@ "integrity": "sha512-I7xWjLs2YSVMc5gGx1Z3ZG1lgFpITPndpi8Ku55GeEIKpACCPQNS/OTqQbxgTCfq0Ncvcc+CrFov96itVh6Qvw==", "license": "MIT" }, - "node_modules/@humanwhocodes/config-array": { - "version": "0.11.14", - "resolved": "https://registry.npmmirror.com/@humanwhocodes/config-array/-/config-array-0.11.14.tgz", - "integrity": "sha512-3T8LkOmg45BV5FICb15QQMsyUSWrQ8AygVfC7ZG32zOalnqrilm018ZVCw0eapXux8FtA33q8PSRSstjee3jSg==", - "deprecated": "Use @eslint/config-array instead", + "node_modules/@humanfs/core": { + "version": "0.19.2", + "resolved": "https://registry.npmmirror.com/@humanfs/core/-/core-0.19.2.tgz", + "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@humanwhocodes/object-schema": "^2.0.2", - "debug": "^4.3.1", - "minimatch": "^3.0.5" + "@humanfs/types": "^0.15.0" }, "engines": { - "node": ">=10.10.0" + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.8", + "resolved": "https://registry.npmmirror.com/@humanfs/node/-/node-0.16.8.tgz", + "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.2", + "@humanfs/types": "^0.15.0", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/types": { + "version": "0.15.0", + "resolved": "https://registry.npmmirror.com/@humanfs/types/-/types-0.15.0.tgz", + "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" } }, "node_modules/@humanwhocodes/module-importer": { @@ -1048,13 +1152,19 @@ "url": "https://github.com/sponsors/nzakas" } }, - "node_modules/@humanwhocodes/object-schema": { - "version": "2.0.3", - "resolved": "https://registry.npmmirror.com/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", - "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", - "deprecated": "Use @eslint/object-schema instead", + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmmirror.com/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", "dev": true, - "license": "BSD-3-Clause" + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } }, "node_modules/@iconify/types": { "version": "2.0.0", @@ -3369,6 +3479,13 @@ "@types/unist": "*" } }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmmirror.com/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/katex": { "version": "0.16.8", "resolved": "https://registry.npmmirror.com/@types/katex/-/katex-0.16.8.tgz", @@ -5438,19 +5555,6 @@ "dev": true, "license": "MIT" }, - "node_modules/doctrine": { - "version": "3.0.0", - "resolved": "https://registry.npmmirror.com/doctrine/-/doctrine-3.0.0.tgz", - "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "esutils": "^2.0.2" - }, - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/docx": { "version": "9.15.3", "resolved": "https://registry.npmmirror.com/docx/-/docx-9.15.3.tgz", @@ -5783,60 +5887,64 @@ } }, "node_modules/eslint": { - "version": "8.57.0", - "resolved": "https://registry.npmmirror.com/eslint/-/eslint-8.57.0.tgz", - "integrity": "sha512-dZ6+mexnaTIbSBZWgou51U6OmzIhYM2VcNdtiTtI7qPNZm35Akpr0f6vtw3w1Kmn5PYo+tZVfh13WrhpS6oLqQ==", + "version": "9.39.5", + "resolved": "https://registry.npmmirror.com/eslint/-/eslint-9.39.5.tgz", + "integrity": "sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw==", "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", "dev": true, "license": "MIT", "dependencies": { - "@eslint-community/eslint-utils": "^4.2.0", - "@eslint-community/regexpp": "^4.6.1", - "@eslint/eslintrc": "^2.1.4", - "@eslint/js": "8.57.0", - "@humanwhocodes/config-array": "^0.11.14", + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.2", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.6", + "@eslint/js": "9.39.5", + "@eslint/plugin-kit": "^0.4.1", + "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", - "@nodelib/fs.walk": "^1.2.8", - "@ungap/structured-clone": "^1.2.0", - "ajv": "^6.12.4", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", "chalk": "^4.0.0", - "cross-spawn": "^7.0.2", + "cross-spawn": "^7.0.6", "debug": "^4.3.2", - "doctrine": "^3.0.0", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^7.2.2", - "eslint-visitor-keys": "^3.4.3", - "espree": "^9.6.1", - "esquery": "^1.4.2", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^6.0.1", + "file-entry-cache": "^8.0.0", "find-up": "^5.0.0", "glob-parent": "^6.0.2", - "globals": "^13.19.0", - "graphemer": "^1.4.0", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", - "is-path-inside": "^3.0.3", - "js-yaml": "^4.1.0", "json-stable-stringify-without-jsonify": "^1.0.1", - "levn": "^0.4.1", "lodash.merge": "^4.6.2", - "minimatch": "^3.1.2", + "minimatch": "^3.1.5", "natural-compare": "^1.4.0", - "optionator": "^0.9.3", - "strip-ansi": "^6.0.1", - "text-table": "^0.2.0" + "optionator": "^0.9.3" }, "bin": { "eslint": "bin/eslint.js" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { - "url": "https://opencollective.com/eslint" + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } } }, "node_modules/eslint-plugin-header": { @@ -5909,20 +6017,14 @@ } }, "node_modules/eslint-plugin-unused-imports": { - "version": "3.2.0", - "resolved": "https://registry.npmmirror.com/eslint-plugin-unused-imports/-/eslint-plugin-unused-imports-3.2.0.tgz", - "integrity": "sha512-6uXyn6xdINEpxE1MtDjxQsyXB37lfyO2yKGVVgtD7WEWQGORSOZjgrD6hBhvGv4/SO+TOlS+UnC6JppRqbuwGQ==", + "version": "4.4.1", + "resolved": "https://registry.npmmirror.com/eslint-plugin-unused-imports/-/eslint-plugin-unused-imports-4.4.1.tgz", + "integrity": "sha512-oZGYUz1X3sRMGUB+0cZyK2VcvRX5lm/vB56PgNNcU+7ficUCKm66oZWKUubXWnOuPjQ8PvmXtCViXBMONPe7tQ==", "dev": true, "license": "MIT", - "dependencies": { - "eslint-rule-composer": "^0.3.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, "peerDependencies": { - "@typescript-eslint/eslint-plugin": "6 - 7", - "eslint": "8" + "@typescript-eslint/eslint-plugin": "^8.0.0-0 || ^7.0.0 || ^6.0.0 || ^5.0.0", + "eslint": "^10.0.0 || ^9.0.0 || ^8.0.0" }, "peerDependenciesMeta": { "@typescript-eslint/eslint-plugin": { @@ -5930,20 +6032,10 @@ } } }, - "node_modules/eslint-rule-composer": { - "version": "0.3.0", - "resolved": "https://registry.npmmirror.com/eslint-rule-composer/-/eslint-rule-composer-0.3.0.tgz", - "integrity": "sha512-bt+Sh8CtDmn2OajxvNO+BX7Wn4CIWMpTRm3MaiKPCQcnnlm0CS2mhui6QaoeQugs+3Kj2ESKEEGJUdVafwhiCg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4.0.0" - } - }, "node_modules/eslint-scope": { - "version": "7.2.2", - "resolved": "https://registry.npmmirror.com/eslint-scope/-/eslint-scope-7.2.2.tgz", - "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", + "version": "8.4.0", + "resolved": "https://registry.npmmirror.com/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", "dev": true, "license": "BSD-2-Clause", "dependencies": { @@ -5951,7 +6043,7 @@ "estraverse": "^5.2.0" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" @@ -5970,19 +6062,45 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/eslint/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmmirror.com/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, "node_modules/espree": { - "version": "9.6.1", - "resolved": "https://registry.npmmirror.com/espree/-/espree-9.6.1.tgz", - "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", + "version": "10.4.0", + "resolved": "https://registry.npmmirror.com/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", "dev": true, "license": "BSD-2-Clause", "dependencies": { - "acorn": "^8.9.0", + "acorn": "^8.15.0", "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^3.4.1" + "eslint-visitor-keys": "^4.2.1" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmmirror.com/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" @@ -6166,16 +6284,16 @@ "license": "MIT" }, "node_modules/file-entry-cache": { - "version": "6.0.1", - "resolved": "https://registry.npmmirror.com/file-entry-cache/-/file-entry-cache-6.0.1.tgz", - "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", + "version": "8.0.0", + "resolved": "https://registry.npmmirror.com/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", "dev": true, "license": "MIT", "dependencies": { - "flat-cache": "^3.0.4" + "flat-cache": "^4.0.0" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": ">=16.0.0" } }, "node_modules/file-source": { @@ -6218,18 +6336,17 @@ } }, "node_modules/flat-cache": { - "version": "3.2.0", - "resolved": "https://registry.npmmirror.com/flat-cache/-/flat-cache-3.2.0.tgz", - "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", + "version": "4.0.1", + "resolved": "https://registry.npmmirror.com/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", "dev": true, "license": "MIT", "dependencies": { "flatted": "^3.2.9", - "keyv": "^4.5.3", - "rimraf": "^3.0.2" + "keyv": "^4.5.4" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": ">=16" } }, "node_modules/flatted": { @@ -6314,13 +6431,6 @@ "url": "https://github.com/sponsors/rawify" } }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmmirror.com/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true, - "license": "ISC" - }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.3.tgz", @@ -6598,16 +6708,13 @@ } }, "node_modules/globals": { - "version": "13.24.0", - "resolved": "https://registry.npmmirror.com/globals/-/globals-13.24.0.tgz", - "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", + "version": "16.5.0", + "resolved": "https://registry.npmmirror.com/globals/-/globals-16.5.0.tgz", + "integrity": "sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==", "dev": true, "license": "MIT", - "dependencies": { - "type-fest": "^0.20.2" - }, "engines": { - "node": ">=8" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -6642,13 +6749,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/graphemer": { - "version": "1.4.0", - "resolved": "https://registry.npmmirror.com/graphemer/-/graphemer-1.4.0.tgz", - "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", - "dev": true, - "license": "MIT" - }, "node_modules/hachure-fill": { "version": "0.5.2", "resolved": "https://registry.npmmirror.com/hachure-fill/-/hachure-fill-0.5.2.tgz", @@ -7221,18 +7321,6 @@ "node": ">=0.8.19" } }, - "node_modules/inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmmirror.com/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", - "dev": true, - "license": "ISC", - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" - } - }, "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmmirror.com/inherits/-/inherits-2.0.4.tgz", @@ -7610,16 +7698,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/is-path-inside": { - "version": "3.0.3", - "resolved": "https://registry.npmmirror.com/is-path-inside/-/is-path-inside-3.0.3.tgz", - "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/is-plain-obj": { "version": "4.1.0", "resolved": "https://registry.npmmirror.com/is-plain-obj/-/is-plain-obj-4.1.0.tgz", @@ -9436,16 +9514,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmmirror.com/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmmirror.com/optionator/-/optionator-0.9.4.tgz", @@ -9625,16 +9693,6 @@ "node": ">=8" } }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmmirror.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmmirror.com/path-key/-/path-key-3.1.1.tgz", @@ -10716,45 +10774,6 @@ "node": ">=0.10.0" } }, - "node_modules/rimraf": { - "version": "3.0.2", - "resolved": "https://registry.npmmirror.com/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "deprecated": "Rimraf versions prior to v4 are no longer supported", - "dev": true, - "license": "ISC", - "dependencies": { - "glob": "^7.1.3" - }, - "bin": { - "rimraf": "bin.js" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/rimraf/node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmmirror.com/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", - "dev": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/robust-predicates": { "version": "3.0.3", "resolved": "https://registry.npmmirror.com/robust-predicates/-/robust-predicates-3.0.3.tgz", @@ -11674,13 +11693,6 @@ "deprecated": "no longer maintained", "license": "Unlicense" }, - "node_modules/text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmmirror.com/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", - "dev": true, - "license": "MIT" - }, "node_modules/thenify": { "version": "3.3.1", "resolved": "https://registry.npmmirror.com/thenify/-/thenify-3.3.1.tgz", @@ -11868,19 +11880,6 @@ "node": ">= 0.8.0" } }, - "node_modules/type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmmirror.com/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "dev": true, - "license": "(MIT OR CC0-1.0)", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/typed-array-buffer": { "version": "1.0.3", "resolved": "https://registry.npmmirror.com/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", @@ -12452,13 +12451,6 @@ "node": ">=8" } }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmmirror.com/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true, - "license": "ISC" - }, "node_modules/xlsx": { "version": "0.18.5", "resolved": "https://registry.npmmirror.com/xlsx/-/xlsx-0.18.5.tgz", diff --git a/package.json b/package.json index 39d697aa..ba1ea6a3 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "react-template", + "name": "monkey-ai-web", "version": "0.1.0", "private": true, "type": "module", @@ -90,18 +90,18 @@ "@vitejs/plugin-react": "^4.2.1", "autoprefixer": "^10.4.21", "esbuild": "0.21.5", - "eslint": "8.57.0", + "eslint": "9.39.5", "eslint-plugin-header": "^3.1.1", "eslint-plugin-react": "^7.37.5", "eslint-plugin-react-hooks": "^5.2.0", - "eslint-plugin-unused-imports": "^3.2.0", + "eslint-plugin-unused-imports": "4.4.1", + "globals": "16.5.0", "i18next-cli": "^1.10.3", "postcss": "^8.5.3", "prettier": "^3.0.0", "tailwindcss": "^3", "vite": "5.4.21" }, - "proxy": "http://localhost:3000", "engines": { "node": ">=22.13.0", "npm": ">=10" diff --git a/scripts/check-ui-dependencies.mjs b/scripts/check-ui-dependencies.mjs index 1b1f24f4..61e033f7 100644 --- a/scripts/check-ui-dependencies.mjs +++ b/scripts/check-ui-dependencies.mjs @@ -42,7 +42,7 @@ export function auditManifest(manifest, lock) { } export function auditSource(source, filename) { - const linter = new Linter(); + const linter = new Linter({ configType: 'eslintrc' }); linter.defineRule('ui-dependencies', { create(context) { const inspect = (node) => { diff --git a/src/App.jsx b/src/App.jsx index 514ca131..b35713a0 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -130,9 +130,11 @@ const ORG_USER_NAV_PATHS = { keyManagement: ['/key-management', '/user-center/key-management'], userCenter: ['/user-center'], }; +const matchesPathPrefix = (pathname, prefix) => + pathname === prefix || pathname.startsWith(`${prefix}/`); const isOrgAllowedPath = (pathname, extraPrefixes = []) => - [...ORG_ALLOWED_PREFIXES, ...extraPrefixes].some( - (p) => pathname === p || pathname.startsWith(p + '/'), + [...ORG_ALLOWED_PREFIXES, ...extraPrefixes].some((prefix) => + matchesPathPrefix(pathname, prefix), ); // 模型超市旧路径 /pricing → /market。用组件而非静态 , @@ -220,27 +222,38 @@ function App() { // /org,从此无任何路径把平台技能加入企业技能库——技能库与分发页永远为空。 // 顶栏开关的本意是收敛"员工浏览目录",不应连带阉割企业治理能力,故对 // 管理员无条件放行该路由(页面内部仍按 skill_manage 决定是否出现启用按钮)。 - if (isOrgAdmin && !prefixes.includes('/skill-market')) { + if ( + orgMembershipLoaded && + isOrgAdmin && + !prefixes.includes('/skill-market') + ) { prefixes.push('/skill-market'); } return prefixes; - }, [statusState?.status?.HeaderNavModulesOrgUser, isOrgAdmin]); + }, [ + statusState?.status?.HeaderNavModulesOrgUser, + orgMembershipLoaded, + isOrgAdmin, + ]); // 路由级封锁:org_only 员工访问非企业路由一律回到企业空间。 // 仅在企业中心可用时启用,避免企业中心被全局关闭时与其内部回退跳转形成重定向死循环。 - // 企业列表未到位前不做封锁判定:isOrgAdmin 首帧恒 false,此时若直接重定向, - // 硬刷新/收藏夹直达 /skill-market 的 org_only 管理员会在放行判据还没算出来时 - // 就被弹回 /org,而重定向不可逆——之后 isOrgAdmin 变 true 也回不去。 + // 只有技能超市的企业管理员特例需要等待企业列表;等待时也不挂载受限页面。 + const routePath = location.pathname.toLowerCase(); const orgConfined = userState?.user?.org_only_mode === true && - orgMembershipLoaded && isOrgCenterAvailable && - !isOrgAllowedPath(location.pathname, orgUserAllowedPrefixes); + !isOrgAllowedPath(routePath, orgUserAllowedPrefixes); if (orgConfined) { return ( - + {!orgMembershipLoaded && + matchesPathPrefix(routePath, '/skill-market') ? ( + + ) : ( + + )} ); } diff --git a/src/components/analytics/ChannelConsumption.jsx b/src/components/analytics/ChannelConsumption.jsx index 7d44aea2..f0829beb 100644 --- a/src/components/analytics/ChannelConsumption.jsx +++ b/src/components/analytics/ChannelConsumption.jsx @@ -16,6 +16,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { formatPercent } from '../../helpers/safeDisplay'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import React, { useState } from 'react'; @@ -118,7 +119,7 @@ const ChannelConsumption = ({ data, title, icon, t, embedded = false }) => { width: 80, align: 'right', render: (val) => ( - {(val || 0).toFixed(1)}% + {formatPercent(val || 0, 1)} ), }, ]; diff --git a/src/components/analytics/DailyStatsTable.jsx b/src/components/analytics/DailyStatsTable.jsx index 8c479a8c..a224a038 100644 --- a/src/components/analytics/DailyStatsTable.jsx +++ b/src/components/analytics/DailyStatsTable.jsx @@ -21,6 +21,7 @@ import React from 'react'; import { Card, Table, Button } from '@/components/ui'; import { IconDownload } from '@/components/ui/icons'; import { renderQuota } from '../../helpers'; +import { formatNumber, toFiniteNumber } from '../../helpers/safeDisplay'; const DailyStatsTable = ({ data, title, icon, t, embedded = false }) => { const columns = [ @@ -68,7 +69,7 @@ const DailyStatsTable = ({ data, title, icon, t, embedded = false }) => { align: 'right', render: (val) => ( - ¥{(val || 0).toFixed(2)} + ¥{formatNumber(val, 2, '0.00')} ), }, @@ -99,7 +100,7 @@ const DailyStatsTable = ({ data, title, icon, t, embedded = false }) => { width: 120, align: 'right', render: (val) => { - const tokens = val || 0; + const tokens = toFiniteNumber(val) ?? 0; if (tokens >= 1000000) { return {(tokens / 1000000).toFixed(2)}M; } else if (tokens >= 1000) { diff --git a/src/components/analytics/HighFreqLowCostUsers.jsx b/src/components/analytics/HighFreqLowCostUsers.jsx index ea0eb042..b107dad1 100644 --- a/src/components/analytics/HighFreqLowCostUsers.jsx +++ b/src/components/analytics/HighFreqLowCostUsers.jsx @@ -16,6 +16,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { formatUserReference } from '../../helpers/safeDisplay'; import React, { useMemo, useState } from 'react'; import { @@ -113,7 +114,9 @@ const HighFreqLowCostUsers = ({ width: 160, render: (v, row) => (
- {v || row.username || `user_${row.user_id}`} + + {formatUserReference(v || row.username, row.user_id, t('未知用户'))} + {row.username && v && row.username !== v && ( @{row.username} diff --git a/src/components/analytics/ModelDistribution.jsx b/src/components/analytics/ModelDistribution.jsx index cad7ab91..d226685b 100644 --- a/src/components/analytics/ModelDistribution.jsx +++ b/src/components/analytics/ModelDistribution.jsx @@ -21,6 +21,7 @@ import React, { useMemo } from 'react'; import { Card } from '@/components/ui'; import { VChart } from '@visactor/react-vchart'; import { renderQuota } from '../../helpers'; +import { formatPercent } from '../../helpers/safeDisplay'; const ModelDistribution = ({ data, title, icon, t }) => { const pieSpec = useMemo(() => { @@ -119,12 +120,12 @@ const ModelDistribution = ({ data, title, icon, t }) => { {index + 1} - {item.model_name} + {item.model_name || t('未知')} - {item.percent?.toFixed(1)}% + {formatPercent(item.percent, 1)}
))} diff --git a/src/components/analytics/OrgCacheHourlySheet.jsx b/src/components/analytics/OrgCacheHourlySheet.jsx index 5215112b..8fefa144 100644 --- a/src/components/analytics/OrgCacheHourlySheet.jsx +++ b/src/components/analytics/OrgCacheHourlySheet.jsx @@ -25,6 +25,7 @@ import { RefreshCw } from '@/components/common/icons/ActionIcons'; import { ConsoleDrawer } from '@/components/console/ConsolePrimitives'; import useOrgCacheHourly from '../../hooks/analytics/useOrgCacheHourly'; import { useIsMobile } from '../../hooks/common/useIsMobile'; +import { formatIdReference, formatPercent } from '../../helpers/safeDisplay'; // 图表序列色属于专用图表(VChart)配色,统计块沿用同色以便与图例对应。 // 千分位缩写。线上单小时 cache_read 能到十亿量级,不缩写轴标签会糊成一片。 @@ -179,7 +180,7 @@ const OrgCacheHourlySheet = ({ visible, org, onClose, t }) => { value: (datum) => datum?.hit_rate === null || datum?.hit_rate === undefined ? t('无流量') - : `${Number(datum.hit_rate).toFixed(1)}%`, + : formatPercent(datum.hit_rate, 1), }, { key: () => t('实际消费'), @@ -228,14 +229,15 @@ const OrgCacheHourlySheet = ({ visible, org, onClose, t }) => { // 自适应量程会把 76%~87% 的波动拉成满屏振荡,像出了故障。 min: 0, max: 100, - label: { formatMethod: (v) => `${Math.round(v)}%` }, + label: { formatMethod: (v) => formatPercent(v, 0) }, seriesIndex: [1], }, ], }; }, [points, hasTraffic, t]); - const orgTitle = org?.org_name || (org ? `${t('企业')} ${org.org_id}` : ''); + const orgReference = formatIdReference(org?.org_id); + const orgTitle = org?.org_name || (org ? `${t('企业')} ${orgReference}` : ''); return ( { {org?.org_id ? ( - #{org.org_id} + {orgReference} ) : null} @@ -284,7 +286,7 @@ const OrgCacheHourlySheet = ({ visible, org, onClose, t }) => { value={ totals.hit_rate === null || totals.hit_rate === undefined ? '--' - : `${Number(totals.hit_rate).toFixed(2)}%` + : formatPercent(totals.hit_rate, 2) } sub={t('按 token 加权')} color={SERIES_COLORS.hitRate} diff --git a/src/components/analytics/OrgRealtimeUsage.jsx b/src/components/analytics/OrgRealtimeUsage.jsx index 9a7a151b..4443acba 100644 --- a/src/components/analytics/OrgRealtimeUsage.jsx +++ b/src/components/analytics/OrgRealtimeUsage.jsx @@ -17,6 +17,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { formatIdReference, formatPercent } from '../../helpers/safeDisplay'; import React, { useState, useCallback } from 'react'; import { Badge, Empty, Progress, Skeleton, Tag, Tooltip, theme } from 'antd'; import { ArrowDown } from 'lucide-react'; @@ -103,16 +104,19 @@ const OrgRealtimeUsage = ({ key: 'org_name', width: 220, fixed: 'left', - render: (text, record) => ( -
- - {text || `${t('企业')} ${record.org_id}`} - - - #{record.org_id} - -
- ), + render: (text, record) => { + const orgReference = formatIdReference(record.org_id); + return ( +
+ + {text || `${t('企业')} ${orgReference}`} + + + {orgReference} + +
+ ); + }, }, { title: ( @@ -275,7 +279,7 @@ const OrgRealtimeUsage = ({ className='text-sm font-semibold group-hover:underline' style={{ color: cacheRateColor(rate, token) }} > - {rate.toFixed(1)}% + {formatPercent(rate, 1)} . For commercial licensing, please contact support@quantumnous.com */ +import { formatNumber, formatPercent } from '../../helpers/safeDisplay'; import React from 'react'; import { Card } from '@/components/ui'; @@ -65,7 +66,7 @@ const OverviewCards = ({ overview, loading = false, t }) => { }, { title: t('今日充值'), - value: `¥${overview.today_topup?.toFixed(2) || '0.00'}`, + value: `¥${formatNumber(overview.today_topup, 2, '0.00')}`, change: overview.today_topup_change, icon: , color: 'yellow', @@ -92,7 +93,7 @@ const OverviewCards = ({ overview, loading = false, t }) => { }, { title: t('付费率'), - value: `${overview.pay_rate?.toFixed(1) || '0.0'}%`, + value: formatPercent(overview.pay_rate, 1, '0.0%'), change: null, icon: , color: 'pink', @@ -117,7 +118,7 @@ const OverviewCards = ({ overview, loading = false, t }) => { )} {isPositive ? '+' : ''} - {change.toFixed(1)}% + {formatPercent(change, 1)} ); diff --git a/src/components/analytics/RiskControlBanLogs.jsx b/src/components/analytics/RiskControlBanLogs.jsx index ae5ab0f9..9980f06f 100644 --- a/src/components/analytics/RiskControlBanLogs.jsx +++ b/src/components/analytics/RiskControlBanLogs.jsx @@ -16,6 +16,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { formatUserReference } from '../../helpers/safeDisplay'; import { Trans } from 'react-i18next'; import React, { useState } from 'react'; @@ -246,7 +247,9 @@ const RiskControlBanLogs = ({
{t('用户:')} - {unbanRow.user_snapshot || `user_${unbanRow.user_id}`}(ID: + {unbanRow.user_snapshot || + formatUserReference('', unbanRow.user_id, t('未知用户'))} + (ID: {unbanRow.user_id})
diff --git a/src/components/analytics/TopupChannelChart.jsx b/src/components/analytics/TopupChannelChart.jsx index cb8e121e..3b7adf13 100644 --- a/src/components/analytics/TopupChannelChart.jsx +++ b/src/components/analytics/TopupChannelChart.jsx @@ -18,6 +18,11 @@ For commercial licensing, please contact support@quantumnous.com */ import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; +import { + formatNumber, + formatPercent, + toFiniteNumber, +} from '../../helpers/safeDisplay'; import React, { useMemo } from 'react'; import { Card } from '@/components/ui'; import { VChart } from '@visactor/react-vchart'; @@ -48,8 +53,8 @@ const TopupChannelChart = ({ data, title, icon, t }) => { const chartData = data.map((item) => ({ name: item.payment_method ? t(item.payment_method) : t('未知'), rawName: item.payment_method, - value: item.amount || 0, - count: item.count || 0, + value: toFiniteNumber(item.amount) ?? 0, + count: toFiniteNumber(item.count) ?? 0, })); // 根据支付渠道名称生成颜色数组 @@ -78,7 +83,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => { content: [ { key: (datum) => datum?.name, - value: (datum) => `¥${(datum?.value || 0).toFixed(2)}`, + value: (datum) => `¥${formatNumber(datum?.value, 2, '0.00')}`, }, { key: () => t('笔数'), @@ -108,7 +113,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => { // 统计列表 const channelList = data || []; const totalAmount = channelList.reduce( - (sum, item) => sum + (item.amount || 0), + (sum, item) => sum + (toFiniteNumber(item.amount) ?? 0), 0, ); @@ -141,10 +146,10 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
- ¥{(item.amount || 0).toFixed(2)} + ¥{formatNumber(item.amount, 2, '0.00')} - ({item.percent?.toFixed(1)} + ({formatPercent(item.percent, 1).replace('%', '')} {I18N_TECHNICAL_TEXT.PERCENT_CLOSE}
@@ -152,7 +157,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => { ))}
{t('合计')} - ¥{totalAmount.toFixed(2)} + ¥{formatNumber(totalAmount, 2, '0.00')}
diff --git a/src/components/analytics/TrendCharts.jsx b/src/components/analytics/TrendCharts.jsx index f4be8377..4460c447 100644 --- a/src/components/analytics/TrendCharts.jsx +++ b/src/components/analytics/TrendCharts.jsx @@ -20,6 +20,7 @@ For commercial licensing, please contact support@quantumnous.com import React, { useMemo } from 'react'; import { Card } from '@/components/ui'; import { VChart } from '@visactor/react-vchart'; +import { formatCurrency } from '@/helpers/safeDisplay'; const TrendCharts = ({ title, icon, data, type, t }) => { const spec = useMemo(() => { @@ -142,7 +143,7 @@ const TrendCharts = ({ title, icon, data, type, t }) => { content: [ { key: () => topupKey, - value: (datum) => `¥${(datum?.[topupKey] || 0).toFixed(2)}`, + value: (datum) => formatCurrency(datum?.[topupKey]), }, ], }, @@ -174,8 +175,7 @@ const TrendCharts = ({ title, icon, data, type, t }) => { content: [ { key: () => consumeKey, - value: (datum) => - `¥${(datum?.[consumeKey] || 0).toFixed(2)}`, + value: (datum) => formatCurrency(datum?.[consumeKey]), }, ], }, diff --git a/src/components/analytics/UserRanking.jsx b/src/components/analytics/UserRanking.jsx index 34421ad9..06e7afe2 100644 --- a/src/components/analytics/UserRanking.jsx +++ b/src/components/analytics/UserRanking.jsx @@ -16,6 +16,10 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { + formatIdReference, + formatUserReference, +} from '../../helpers/safeDisplay'; import { Trans } from 'react-i18next'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; @@ -104,11 +108,15 @@ const UserRanking = ({ data, title, icon, t }) => {
- {item.display_name || item.username || `User ${item.user_id}`} + {formatUserReference( + item.display_name || item.username, + item.user_id, + t('未知用户'), + )} - #{item.user_id} + {formatIdReference(item.user_id)} diff --git a/src/components/analytics/UserSurveyStats.jsx b/src/components/analytics/UserSurveyStats.jsx index 68b27268..d5a34636 100644 --- a/src/components/analytics/UserSurveyStats.jsx +++ b/src/components/analytics/UserSurveyStats.jsx @@ -16,6 +16,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { formatPercent, formatRatioPercent } from '../../helpers/safeDisplay'; import React, { useMemo, useState, useEffect, useCallback } from 'react'; import { Card, Spin, Tag, Progress } from '@/components/ui'; @@ -130,7 +131,7 @@ const UserSurveyStats = ({ title, icon, 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('占比'), - value: (datum) => `${(datum?.percentage || 0).toFixed(1)}%`, + value: (datum) => formatPercent(datum?.percentage || 0, 1), }, ], }, @@ -334,10 +335,7 @@ const UserSurveyStats = ({ title, icon, t }) => { {techUsers}
- {totalUsers > 0 - ? ((techUsers / totalUsers) * 100).toFixed(1) - : 0} - % + {formatRatioPercent(techUsers, totalUsers, 1, '0.0%')}
@@ -351,10 +349,12 @@ const UserSurveyStats = ({ title, icon, t }) => { {activeAIUsers}
- {totalUsers > 0 - ? ((activeAIUsers / totalUsers) * 100).toFixed(1) - : 0} - % + {formatRatioPercent( + activeAIUsers, + totalUsers, + 1, + '0.0%', + )}
@@ -368,10 +368,12 @@ const UserSurveyStats = ({ title, icon, t }) => { {interestedUsers}
- {totalUsers > 0 - ? ((interestedUsers / totalUsers) * 100).toFixed(1) - : 0} - % + {formatRatioPercent( + interestedUsers, + totalUsers, + 1, + '0.0%', + )}
diff --git a/src/components/analytics/UserTopupRanking.jsx b/src/components/analytics/UserTopupRanking.jsx index 336e17f4..21521423 100644 --- a/src/components/analytics/UserTopupRanking.jsx +++ b/src/components/analytics/UserTopupRanking.jsx @@ -16,6 +16,11 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { + formatNumber, + formatIdReference, + formatUserReference, +} from '../../helpers/safeDisplay'; import { Trans } from 'react-i18next'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; @@ -80,12 +85,12 @@ const UserTopupRanking = ({ data, title, icon, t, embedded = false }) => {
- {text || `User ${record.user_id}`} + {formatUserReference(text, record.user_id, t('未知用户'))} - {I18N_TECHNICAL_TEXT.ID} {record.user_id} + {I18N_TECHNICAL_TEXT.ID} {formatIdReference(record.user_id)}
), @@ -98,7 +103,7 @@ const UserTopupRanking = ({ data, title, icon, t, embedded = false }) => { defaultSortOrder: 'descend', render: (value) => ( - ¥{(value || 0).toFixed(2)} + ¥{formatNumber(value, 2, '0.00')} ), }, diff --git a/src/components/analytics/orgReport/ActionCenter.jsx b/src/components/analytics/orgReport/ActionCenter.jsx index f1fabc1f..2a838a57 100644 --- a/src/components/analytics/orgReport/ActionCenter.jsx +++ b/src/components/analytics/orgReport/ActionCenter.jsx @@ -30,6 +30,7 @@ import { } from '@/components/ui'; import { ClipboardList } from 'lucide-react'; import { ChangeText, OrgNameCell, ReasonTags, SectionCard } from './shared'; +import { formatRatioPercent } from '../../../helpers/safeDisplay'; import { daysSince, downloadCsv, @@ -284,7 +285,11 @@ const columnsFor = (tab, cny, t, atRisk) => { {v}/{r.member_count} {r.member_count > 0 ? ( - {Math.min(100, (v / r.member_count) * 100).toFixed(0)}% + {formatRatioPercent( + Math.min(100, Number(v) || 0), + r.member_count, + 0, + )} ) : null} diff --git a/src/components/analytics/orgReport/Overview.jsx b/src/components/analytics/orgReport/Overview.jsx index 066821c5..1b146c19 100644 --- a/src/components/analytics/orgReport/Overview.jsx +++ b/src/components/analytics/orgReport/Overview.jsx @@ -31,6 +31,10 @@ import { } from 'lucide-react'; import { ChangeText, KpiCard, SectionCard } from './shared'; import { formatCny, formatCst, pct, SEGMENTS } from './utils'; +import { + formatPercent, + formatRatioPercent, +} from '../../../helpers/safeDisplay'; // ─── 报表抬头:统计口径 + 数据状态 ───────────────────────────────── export const ReportHeader = ({ report, onExport, t }) => { @@ -209,7 +213,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => { n: (k.active_orgs || 0).toLocaleString(), 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: ( ), @@ -229,7 +233,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => { n: (k.active_members || 0).toLocaleString(), 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('本期通过企业密钥产生调用的去重成员数(按自然日统计)'), onClick: () => onJump('growth'), }, @@ -277,7 +281,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => { }, { title: t('企业消耗占平台'), - value: `${share.toFixed(1)}%`, + value: formatPercent(share), sub: `${t('个人消耗')} ${formatCny(k.personal_quota, cny)}`, compare: shareDelta === null ? null : ( @@ -341,7 +345,7 @@ export const HealthSegments = ({ report, cny, activeSegment, onSelect, t }) => { {t(meta.label)} - {pct(s.count, totalCount).toFixed(0)}% + {formatPercent(pct(s.count, totalCount), 0)}
diff --git a/src/components/analytics/orgReport/Tables.jsx b/src/components/analytics/orgReport/Tables.jsx index 95bb1702..c786d5f9 100644 --- a/src/components/analytics/orgReport/Tables.jsx +++ b/src/components/analytics/orgReport/Tables.jsx @@ -30,6 +30,7 @@ import { } from '@/components/ui'; import { Search, Table2, UserCog } from 'lucide-react'; import { ChangeText, OrgNameCell, SectionCard } from './shared'; +import { formatPercent } from '../../../helpers/safeDisplay'; import { ALERT_LEVELS, ORG_STATUS, @@ -266,7 +267,7 @@ export const OrgDetailTable = ({ report, filter, setFilter, cny, t }) => { align: 'right', render: (v) => v > 0 ? ( - {v.toFixed(1)}% + {formatPercent(v, 1)} ) : ( — ), @@ -501,8 +502,8 @@ export const exportOrgDetail = (rows, cny, t) => { SEGMENTS[o.segment] ? t(SEGMENTS[o.segment].label) : '', yuan(o.quota), yuan(o.prev_quota), - rate === null ? '' : `${rate.toFixed(1)}%`, - o.share ? `${o.share.toFixed(2)}%` : '', + rate === null ? '' : formatPercent(rate, 1), + o.share ? formatPercent(o.share, 2) : '', o.requests, o.active_members, o.member_count, diff --git a/src/components/analytics/orgReport/shared.jsx b/src/components/analytics/orgReport/shared.jsx index dac50035..86b872e6 100644 --- a/src/components/analytics/orgReport/shared.jsx +++ b/src/components/analytics/orgReport/shared.jsx @@ -21,6 +21,7 @@ import React from 'react'; import { Card, Tag, Tooltip } from '@/components/ui'; import { TrendingDown, TrendingUp } from 'lucide-react'; import { changeRate, ORG_STATUS, orgDisplayName, REASONS } from './utils'; +import { formatPercent } from '../../../helpers/safeDisplay'; export const SectionCard = ({ id, @@ -90,7 +91,7 @@ export const ChangeText = ({ cur, prev, t, size = 'xs', showNew = true }) => { )} {up ? '+' : ''} - {rate.toFixed(1)}% + {formatPercent(rate, 1)} ); }; diff --git a/src/components/analytics/orgReport/utils.js b/src/components/analytics/orgReport/utils.js index 4de61618..ee45aa4e 100644 --- a/src/components/analytics/orgReport/utils.js +++ b/src/components/analytics/orgReport/utils.js @@ -16,6 +16,11 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { + formatIdReference, + formatPercent, + toFiniteNumber, +} from '../../../helpers/safeDisplay'; // 企业经营决策报表:口径常量、行动清单派生、要点生成、CSV 导出 @@ -27,7 +32,8 @@ export const getCnyParams = () => { let usdRate = 1; try { const s = JSON.parse(localStorage.getItem('status') || '{}'); - usdRate = s?.usd_exchange_rate || 1; + const parsedRate = toFiniteNumber(s?.usd_exchange_rate); + usdRate = parsedRate !== null && parsedRate > 0 ? parsedRate : 1; } catch (e) { usdRate = 1; } @@ -35,7 +41,7 @@ export const getCnyParams = () => { }; export const quotaToCny = (quota, { quotaPerUnit, usdRate }) => - ((quota || 0) / quotaPerUnit) * usdRate; + ((toFiniteNumber(quota) ?? 0) / quotaPerUnit) * usdRate; export const formatCny = (quota, params, digits = 2) => `¥${quotaToCny(quota, params).toLocaleString(undefined, { @@ -47,12 +53,22 @@ export const formatCny = (quota, params, digits = 2) => export const changeRate = (cur, prev) => prev > 0 ? (((cur || 0) - prev) / prev) * 100 : null; -export const formatRate = (rate) => - rate === null || rate === undefined +export const formatRate = (rate) => { + const number = Number(rate); + return rate === null || rate === undefined || !Number.isFinite(number) ? '—' - : `${rate >= 0 ? '+' : ''}${rate.toFixed(1)}%`; + : `${number >= 0 ? '+' : ''}${number.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,与浏览器时区无关) ───────────────── const pad = (n) => String(n).padStart(2, '0'); @@ -405,11 +421,11 @@ export const deriveFindings = (report, lists, cny, t) => { ? t( '头部依赖较高:Top5 企业贡献 {{share}} 的企业消耗,需关注大客户稳定性', { - share: `${k.top5_share.toFixed(1)}%`, + share: formatPercent(k.top5_share, 1), }, ) : t('客户结构较分散:Top5 企业贡献 {{share}} 的企业消耗', { - share: `${k.top5_share.toFixed(1)}%`, + share: formatPercent(k.top5_share, 1), }), target: 'tiers', }); @@ -426,7 +442,7 @@ export const deriveFindings = (report, lists, cny, t) => { text: t( '企业成员渗透率 {{rate}},{{count}} 家企业成员活跃率低于 30%,存在增量空间', { - rate: `${Math.min(100, penetration).toFixed(1)}%`, + rate: formatPercent(Math.min(100, penetration), 1), count: lowPen, }, ), @@ -467,4 +483,6 @@ export const downloadCsv = (filename, headers, rows) => { }; 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); diff --git a/src/components/auth/AuthLoginTabs.jsx b/src/components/auth/AuthLoginTabs.jsx index 07826d4c..077a247d 100644 --- a/src/components/auth/AuthLoginTabs.jsx +++ b/src/components/auth/AuthLoginTabs.jsx @@ -19,8 +19,9 @@ For commercial licensing, please contact support@quantumnous.com import React from 'react'; import { Button } from 'antd'; -import { useNavigate } from 'react-router-dom'; +import { useNavigate, useSearchParams } from 'react-router-dom'; 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 { t } = useTranslation(); const navigate = useNavigate(); + const [searchParams] = useSearchParams(); + const redirect = searchParams.get('redirect'); + const loginSearch = + mode === 'login' && isSafePostLoginRedirect(redirect) + ? `?${new URLSearchParams({ redirect })}` + : ''; // 企业入口置于左侧首位:本产品主推企业用户,企业登录/注册是默认入口 const tabs = @@ -57,7 +64,7 @@ const AuthLoginTabs = ({ active = 'personal', mode = 'login' }) => { type={isActive ? 'primary' : 'text'} aria-pressed={isActive} onClick={() => { - if (!isActive) navigate(tab.to); + if (!isActive) navigate(`${tab.to}${loginSearch}`); }} className='flex-1 font-medium' > diff --git a/src/components/auth/LoginForm.jsx b/src/components/auth/LoginForm.jsx index 28d86168..872b0621 100644 --- a/src/components/auth/LoginForm.jsx +++ b/src/components/auth/LoginForm.jsx @@ -220,12 +220,17 @@ const LoginForm = () => { }; }, []); + const redirect = searchParams.get('redirect'); useEffect(() => { - const redirect = searchParams.get('redirect'); - if (redirect) { - savePostLoginRedirect(redirect); - } - if (searchParams.get('expired')) { + savePostLoginRedirect(redirect); + }, [redirect]); + + const expiryShown = useRef(false); + useEffect(() => { + if (!searchParams.get('expired')) { + expiryShown.current = false; + } else if (!expiryShown.current) { + expiryShown.current = true; showError(t('未登录或登录已过期,请重新登录')); const nextParams = new URLSearchParams(searchParams); nextParams.delete('expired'); @@ -234,15 +239,15 @@ const LoginForm = () => { }, [searchParams, setSearchParams, t]); const finishLogin = useCallback( - (data, successMessage) => + (data) => runLoginFlow({ data, userDispatch, navigate, t, - successMessage, + redirect, }), - [navigate, t, userDispatch], + [navigate, redirect, t, userDispatch], ); const onWeChatLoginClicked = () => { diff --git a/src/components/auth/TwoFAVerification.jsx b/src/components/auth/TwoFAVerification.jsx index 58b18835..f792dec7 100644 --- a/src/components/auth/TwoFAVerification.jsx +++ b/src/components/auth/TwoFAVerification.jsx @@ -17,7 +17,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ 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 React, { useState } from 'react'; import { useTranslation } from 'react-i18next'; @@ -51,7 +51,6 @@ const TwoFAVerification = ({ onSuccess, onBack, isModal = false }) => { }); if (res.data.success) { - showSuccess(t('登录成功')); if (onSuccess) { onSuccess(res.data.data); } diff --git a/src/components/common/table/TableToolbar.jsx b/src/components/common/table/TableToolbar.jsx index 217ab56f..d6935ecf 100644 --- a/src/components/common/table/TableToolbar.jsx +++ b/src/components/common/table/TableToolbar.jsx @@ -18,9 +18,41 @@ For commercial licensing, please contact support@quantumnous.com */ import React from 'react'; +import { Button, Dropdown } from 'antd'; import { useTranslation } from 'react-i18next'; +import { ChevronDown } from '../icons/ActionIcons'; import './table-toolbar.css'; +export function TableRowActions({ children, items = [] }) { + const { t } = useTranslation(); + const menuItems = items.filter(Boolean); + if (!children && !menuItems.length) return null; + + return ( +
+ {children} + {menuItems.length > 0 && ( + + + + )} +
+ ); +} + export function TableTitle({ children }) { const { t } = useTranslation(); return ( diff --git a/src/components/common/table/table-toolbar.css b/src/components/common/table/table-toolbar.css index d89d4d83..db39c4c2 100644 --- a/src/components/common/table/table-toolbar.css +++ b/src/components/common/table/table-toolbar.css @@ -1,3 +1,10 @@ +.table-row-actions { + display: inline-flex; + align-items: center; + flex-wrap: wrap; + gap: 8px; +} + .table-toolbar { display: flex; align-items: center; diff --git a/src/components/console/ConsoleCollection.jsx b/src/components/console/ConsoleCollection.jsx index 11aee1a5..66b71dac 100644 --- a/src/components/console/ConsoleCollection.jsx +++ b/src/components/console/ConsoleCollection.jsx @@ -24,6 +24,27 @@ import { useIsMobile } from '../../hooks/common/useIsMobile'; import { ConsoleCard, ConsoleSearchBar } from './ConsolePrimitives'; import { TableTitle } from '../common/table/TableToolbar'; +export function ConsoleCollectionSearch({ children, className }) { + const { t } = useTranslation(); + const isMobile = useIsMobile(); + const [expanded, setExpanded] = useState(false); + return ( + <> + {isMobile && ( + + )} + + + ); +} + export default function ConsoleCollection({ children, statsArea, @@ -36,27 +57,13 @@ export default function ConsoleCollection({ tableActionsOffset = false, paginationArea, }) { - const { t } = useTranslation(); - const isMobile = useIsMobile(); - const [expanded, setExpanded] = useState(false); - const showSearch = !isMobile || expanded; return (
{statsArea && ( {statsArea} )} {searchArea && ( - <> - {isMobile && ( - - )} - - + {searchArea} )} {tabsArea &&
{tabsArea}
} diff --git a/src/components/console/ConsolePrimitives.jsx b/src/components/console/ConsolePrimitives.jsx index c1f32f8f..f3d67c51 100644 --- a/src/components/console/ConsolePrimitives.jsx +++ b/src/components/console/ConsolePrimitives.jsx @@ -32,6 +32,8 @@ import { } from 'antd'; import { useTranslation } from 'react-i18next'; import TableEmpty from '../common/table/TableEmpty'; +import FilterSearchButton from '../common/table/FilterSearchButton'; +import './console.css'; import { ConsoleSearchContext, useConsolePage, @@ -96,24 +98,40 @@ export function ConsoleSearchBar({ children, className, formProps, ...props }) { ); } -export function ConsoleSearchActions({ - onReset, - onSearch, - loading, - searchLabel = '搜索', -}) { +export function ConsoleSearchActions({ onReset, loading }) { const { t } = useTranslation(); return (
- {onReset && } - + {onReset && ( + + )} + +
+ ); +} + +export function ConsoleFilterGrid({ children, onReset, onSearch, loading }) { + return ( +
{ + event.preventDefault(); + onSearch(); + }} + > +
{children}
+ + + ); +} + +export function ConsoleFilterField({ label, id, children }) { + return ( +
+ + {children}
); } @@ -167,6 +185,16 @@ export function ConsoleTabs({ className, ...props }) { return ; } +export function ConsoleListTable({ locale, ...props }) { + return ( + , ...locale }} + /> + ); +} + const isFooterButton = (node) => React.isValidElement(node) && (node.type === Button || node.type?.render?.name === 'Button'); diff --git a/src/components/console/console.css b/src/components/console/console.css index 9dc7042f..1a668572 100644 --- a/src/components/console/console.css +++ b/src/components/console/console.css @@ -230,9 +230,70 @@ justify-content: flex-end; flex: 0 0 auto; flex-wrap: wrap; - gap: var(--console-space-1); + gap: var(--console-space-1, 8px); 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, var(--ui-color-text-2)); + 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 { --center-table-head-bg: var(--console-fill); color: var(--console-muted); diff --git a/src/components/layout/PageLayout.jsx b/src/components/layout/PageLayout.jsx index 24c1bd0e..4267d177 100644 --- a/src/components/layout/PageLayout.jsx +++ b/src/components/layout/PageLayout.jsx @@ -198,12 +198,20 @@ const PageLayout = () => { return; } + const sessionAPI = API; + const isCurrentSession = () => { + const currentUser = getUserData(); + return ( + sessionAPI === API && currentUser?.id === cachedUser.id && !!currentUser + ); + }; userDispatch({ type: 'auth_start' }); try { - const res = await API.get('/api/user/self', { + const res = await sessionAPI.get('/api/user/self', { skipErrorHandler: true, disableDuplicate: true, }); + if (!isCurrentSession()) return; const { success, data } = res.data; if (success && data) { setUserData(data); @@ -213,6 +221,7 @@ const PageLayout = () => { userDispatch({ type: 'logout' }); } } catch (error) { + if (!isCurrentSession()) return; if (error?.response?.status === 401 || error?.response?.status === 403) { clearUserData(); userDispatch({ type: 'logout' }); diff --git a/src/components/layout/headerbar/ActionButtons.jsx b/src/components/layout/headerbar/ActionButtons.jsx index 11caada1..ccb31c29 100644 --- a/src/components/layout/headerbar/ActionButtons.jsx +++ b/src/components/layout/headerbar/ActionButtons.jsx @@ -146,7 +146,10 @@ const ActionButtons = ({
{/* Tutorial Button - 新手教程按钮 (桌面端显示) */} {isLoggedIn && isButtonVisible('tutorial') && ( - + {!isMobile && t('新手教程')} @@ -157,7 +160,7 @@ const ActionButtons = ({ {isLoggedIn && isButtonVisible('pricing') && ( setPromotionVisible(true)} > {!isMobile && t('推广')} @@ -169,7 +172,7 @@ const ActionButtons = ({ + { dataIndex: 'price_paid', key: 'price_paid', width: 100, - render: (price) => `¥${price?.toFixed(2) || '0.00'}`, + render: (price) => formatCurrency(price, '¥', 2, '¥0.00'), }, { title: t('生效日期'), diff --git a/src/components/promotion/PromotionPosterModal.jsx b/src/components/promotion/PromotionPosterModal.jsx index ced9edf3..df2e69b6 100644 --- a/src/components/promotion/PromotionPosterModal.jsx +++ b/src/components/promotion/PromotionPosterModal.jsx @@ -19,7 +19,6 @@ For commercial licensing, please contact support@quantumnous.com import { Copy as ActionCopy, - CheckCircle as ActionCheckCircle, Download as ActionDownload, } from '@/components/common/icons/ActionIcons'; import React, { useState, useEffect, useRef, useCallback } from 'react'; @@ -30,26 +29,17 @@ import { Button, Typography, Tabs, - TabPane, Input, - Tag, -} from '@/components/ui'; + Alert, + Skeleton, + Radio, +} from 'antd'; import { QRCodeCanvas } from 'qrcode.react'; -import { - Share2, - Smartphone, - Monitor, - Gift, - Users, - Sparkles, - ChevronRight, - CheckCircle, - Coins, - TrendingUp, -} from 'lucide-react'; +import { Smartphone, Monitor, Gift, Users, ChevronRight } from 'lucide-react'; +import './promotion-poster.css'; import { API, showError, showSuccess, copy } from '../../helpers'; -const { Text } = Typography; +const { Text, Title, Paragraph } = Typography; // 默认海报模板配置 const DEFAULT_TEMPLATES = [ @@ -311,409 +301,233 @@ const PromotionPosterModal = ({ visible, onClose }) => { copyWithFeedback(affCode, t('邀请码')); }; - // 链接分享模式 - PC友好 const renderLinkMode = () => ( -
- {/* 分享卡片 */} -
- {/* 装饰元素 */} -
-
-
- -
- {/* 平台信息 */} -
-
- -
-
-

- {systemName} -

-

- {posterConfig?.slogan || t('邀请好友,共享AI')} -

-
-
- - {/* 福利说明 */} -
-
- - {t('注册即送额度')} -
-
- - {t('消费返佣')} -
-
- - {/* 二维码(小尺寸) */} -
-
- -
-
-

{t('手机扫码注册')}

-

- {t('邀请码')}:{' '} - - {affCode} - -

-
-
-
-
- - {/* 链接输入框 */} -
- - {t('邀请链接')} - -
-
- +
+
{t('推广分享')}
+ {systemName} + + {posterConfig?.slogan || t('邀请好友,共享AI')} + +
+ } - onClick={handleCopyLink} - className='!bg-gradient-to-r !from-brand-from !to-brand-to !border-0 !rounded-lg' - > - {t('复制')} - - } + size={144} + level='M' + marginSize={2} />
-
- - {/* 邀请码 */} -
- - {t('邀请码')} - -
-
-
- - {affCode} - -
+ {t('手机扫码注册')} +
+ + + {t('注册即送额度')} + + + + {t('消费返佣')} + +
+ +
+
+ +
-
- - {/* 使用说明 */} -
-
- - - {t( - '将链接发送给好友,好友点击即可注册。支持微信、QQ、邮件等任意方式分享。', - )} +
+ + {t('邀请码')} +
+ + {affCode} + + +
-
+ + {t( + '将链接发送给好友,好友点击即可注册。支持微信、QQ、邮件等任意方式分享。', + )} + +
); - // 海报模式 - 移动端友好 const renderPosterMode = () => ( -
- {/* 模板选择 */} -
- - {t('选择模板')} - -
- {DEFAULT_TEMPLATES.map((template) => ( - - ))} -
-
- - {/* 海报预览 */} -
- {/* 装饰元素 */} -
-
- -
-

- {posterConfig?.slogan || t('邀请好友,共享AI')} -

-

+

+
+
+

{posterConfig?.slogan || t('邀请好友,共享AI')}

+

{posterConfig?.sub_slogan || t('注册即可获得免费额度')}

- -

- {systemName} -

- -
+

{systemName}

+
- -

- {t('扫码注册')} +

{t('扫码注册')}

+

+ {t('邀请码')}: {affCode} +

+

+ {posterConfig?.footer_text || t('长按识别二维码,立即体验AI')}

- -
-

- {t('邀请码')}: {affCode} -

-
- -
-
-

- {posterConfig?.footer_text || t('长按识别二维码,立即体验AI')} -

-
- - {/* 隐藏的 canvas 用于导出 */} - - - {/* 操作按钮 */} -
- - -
+
+
+ + {t('选择模板')} + + + setSelectedTemplate( + DEFAULT_TEMPLATES.find( + (item) => item.id === event.target.value, + ), + ) + } + > + {DEFAULT_TEMPLATES.map((template) => ( + + + + {t(template.name)} + + + ))} + +
+
+ + +
+ + {posterConfig?.footer_text || t('长按识别二维码,立即体验AI')} + +
+
); return ( -
- -
- {t('推广分享')} -
- } - visible={visible} + title={t('推广分享')} + open={visible} onCancel={onClose} footer={null} - width={520} + width={800} centered className='promotion-modal' - bodyStyle={{ padding: '0 24px 24px' }} > -
- {loading ? ( -
-
-
-
-
- - {t('加载中...')} - -
- ) : ( - <> - {/* 查看邀请奖励规则 - 顶部显眼横幅 */} -
{ - onClose(); - navigate('/user-center/invite'); - }} - > - {/* 装饰元素 */} -
-
- - {/* 动态光效 */} -
- -
-
-
- -
-
-
- {t('查看邀请奖励规则')} - -
-
- {t('了解返佣比例和奖励详情')} -
-
-
-
- - {t('立即查看')} - - -
-
- - {/* 底部小标签 */} -
- - - {t('消费返佣')} - - - - {t('额度奖励')} - -
-
- - {/* Tab 导航 */} + {loading ? ( +
+ +
+ ) : ( + <> + {affLink ? ( - - - {t('链接分享')} - - } - itemKey='link' - > -
{renderLinkMode()}
-
- - - {t('海报分享')} - - } - itemKey='poster' - > -
{renderPosterMode()}
-
-
- - )} -
+ items={[ + { + key: 'link', + label: ( + + + {t('链接分享')} + + ), + children: renderLinkMode(), + }, + { + key: 'poster', + label: ( + + + {t('海报分享')} + + ), + children: renderPosterMode(), + }, + ]} + /> + ) : ( + + )} + + + )} ); }; diff --git a/src/components/promotion/promotion-poster.css b/src/components/promotion/promotion-poster.css new file mode 100644 index 00000000..26445b98 --- /dev/null +++ b/src/components/promotion/promotion-poster.css @@ -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; + } +} diff --git a/src/components/quality/QualityAlerts.jsx b/src/components/quality/QualityAlerts.jsx index d1e8dc70..2f3889d6 100644 --- a/src/components/quality/QualityAlerts.jsx +++ b/src/components/quality/QualityAlerts.jsx @@ -34,6 +34,7 @@ import { } from '@/components/ui'; import { BellRing } from 'lucide-react'; import { useIsMobile } from '../../hooks/common/useIsMobile'; +import { formatIdReference, formatNumber } from '../../helpers/safeDisplay'; import { ALERT_DIM_TYPES, ALERT_METRICS, @@ -265,7 +266,7 @@ const QualityAlerts = ({ quality, t }) => { width: 160, render: (v, r) => ( - {Number(v).toFixed(2)} / {r.threshold} + {formatNumber(v, 2)} / {formatNumber(r.threshold, 2)} ), }, @@ -311,7 +312,7 @@ const QualityAlerts = ({ quality, t }) => { placeholder={t('选择渠道')} optionList={(options.channels || []).map((c) => ({ value: String(c.id), - label: `${c.name} (#${c.id})`, + label: `${c.name || t('未知渠道')} (${formatIdReference(c.id)})`, }))} onChange={(v) => patch({ dim_key: v || '' })} style={{ width: '100%' }} @@ -529,7 +530,7 @@ const QualityAlerts = ({ quality, t }) => { { start: fmtTs(testResult.start), end: fmtTs(testResult.end), - value: Number(testResult.value).toFixed(2), + value: formatNumber(testResult.value, 2), samples: fmtInt(testResult.samples), }, )} diff --git a/src/components/quality/QualityDetail.jsx b/src/components/quality/QualityDetail.jsx index a631386d..d3620011 100644 --- a/src/components/quality/QualityDetail.jsx +++ b/src/components/quality/QualityDetail.jsx @@ -16,6 +16,8 @@ along with this program. If not, see . 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 { @@ -82,7 +84,7 @@ export const HopChain = ({ hops, outcome, t }) => { > {t('第 {{n}} 跳', { n: i + 1 })} ·{' '} - {hop.channel_name || `#${hop.channel_id}`} + {hop.channel_name || formatIdReference(hop.channel_id)} {failed ? ( @@ -199,7 +201,7 @@ const QualityDetail = ({ quality, t }) => { width: 130, render: (v, row) => ( - {v || `#${row.user_id}`} + {v || formatUserReference('', row.user_id)} ), }, @@ -212,7 +214,7 @@ const QualityDetail = ({ quality, t }) => { render: (v, row) => row.organization_id ? ( - {v || `#${row.organization_id}`} + {v || formatIdReference(row.organization_id)} ) : ( @@ -240,7 +242,7 @@ const QualityDetail = ({ quality, t }) => { width: 140, render: (v, row) => ( - {row.channel_id ? v || `#${row.channel_id}` : '-'} + {row.channel_id ? v || formatIdReference(row.channel_id) : '-'} ), }, @@ -452,7 +454,9 @@ const QualityDetail = ({ quality, t }) => { {row.channel_name || - (row.channel_id ? `#${row.channel_id}` : '')} + (row.channel_id + ? formatIdReference(row.channel_id) + : '')} {(row.status_code || row.error_code) && ( diff --git a/src/components/quality/QualityFilterBar.jsx b/src/components/quality/QualityFilterBar.jsx index f37e5742..9ff7d791 100644 --- a/src/components/quality/QualityFilterBar.jsx +++ b/src/components/quality/QualityFilterBar.jsx @@ -16,6 +16,8 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { formatIdReference } from '../../helpers/safeDisplay'; +import { formatUserReference } from '../../helpers/safeDisplay'; import { SlidersHorizontal as ActionSlidersHorizontal, @@ -102,15 +104,19 @@ const RemoteSelect = ({ useEffect(() => () => window.clearTimeout(timer.current), []); const optionList = useMemo(() => { - const opts = list.map((it) => ({ - value: String(it.id), - label: `${it.name || '-'} (#${it.id})`, - })); + const opts = list + .filter((it) => it?.id !== null && it?.id !== undefined) + .map((it) => ({ + value: String(it.id), + label: `${it.name || '-'} (${formatIdReference(it.id)})`, + })); if (value && !opts.some((o) => o.value === String(value))) { const name = labels.current[String(value)]; opts.unshift({ value: String(value), - label: name ? `${name} (#${value})` : `#${value}`, + label: name + ? `${name} (${formatIdReference(value)})` + : formatIdReference(value), }); } return opts; @@ -147,10 +153,12 @@ const QualityFilterBar = ({ quality, t, onOpenDetail }) => { const [moreOpen, setMoreOpen] = useState(false); const idOptions = (items) => - (items || []).map((it) => ({ - value: String(it.id), - label: `${it.name || '-'} (#${it.id})`, - })); + (items || []) + .filter((it) => it?.id !== null && it?.id !== undefined) + .map((it) => ({ + value: String(it.id), + label: `${it.name || '-'} (${formatIdReference(it.id)})`, + })); const strOptions = (items) => (items || []).map((v) => ({ value: v, label: v })); @@ -176,29 +184,30 @@ const QualityFilterBar = ({ quality, t, onOpenDetail }) => { if (filters.channel_id) push( 'channel_id', - `${t('渠道')}: ${nameOf(options.channels, filters.channel_id) || '#' + filters.channel_id}`, + `${t('渠道')}: ${nameOf(options.channels, filters.channel_id) || formatIdReference(filters.channel_id)}`, ); if (filters.group) push('group', `${t('分组')}: ${filters.group}`); - if (filters.org_id) push('org_id', `${t('企业')}: #${filters.org_id}`); + if (filters.org_id) + push('org_id', `${t('企业')}: ${formatIdReference(filters.org_id)}`); if (filters.dept_id) push( 'dept_id', - `${t('部门')}: ${nameOf(options.depts, filters.dept_id) || (filters.dept_id === '0' ? t('未分配部门') : '#' + filters.dept_id)}`, + `${t('部门')}: ${nameOf(options.depts, filters.dept_id) || (filters.dept_id === '0' ? t('未分配部门') : formatIdReference(filters.dept_id))}`, ); if (filters.project_id) push( 'project_id', - `${t('项目')}: ${nameOf(options.projects, filters.project_id) || (filters.project_id === '0' ? t('未绑定项目') : '#' + filters.project_id)}`, + `${t('项目')}: ${nameOf(options.projects, filters.project_id) || (filters.project_id === '0' ? t('未绑定项目') : formatIdReference(filters.project_id))}`, ); if (filters.user_id) push( '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) push( 'token_id', - `${t('密钥')}: ${nameOf(options.tokens, filters.token_id) || '#' + filters.token_id}`, + `${t('密钥')}: ${nameOf(options.tokens, filters.token_id) || formatIdReference(filters.token_id)}`, ); if (filters.path) push('path', `${t('接口')}: ${filters.path}`); if (filters.error_code) diff --git a/src/components/quality/QualityHeatmap.jsx b/src/components/quality/QualityHeatmap.jsx index e406afaf..8f5296ee 100644 --- a/src/components/quality/QualityHeatmap.jsx +++ b/src/components/quality/QualityHeatmap.jsx @@ -16,6 +16,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { formatIdReference } from '../../helpers/safeDisplay'; import { Trans } from 'react-i18next'; import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; @@ -102,7 +103,9 @@ const QualityHeatmap = ({ quality, t }) => { (row.cells || []).forEach((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 ( diff --git a/src/components/quality/QualityOverview.jsx b/src/components/quality/QualityOverview.jsx index 3663d567..58013ca6 100644 --- a/src/components/quality/QualityOverview.jsx +++ b/src/components/quality/QualityOverview.jsx @@ -22,6 +22,7 @@ import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; import React, { useMemo } from 'react'; import { Button, Skeleton, Tooltip } from '@/components/ui'; import { useActualTheme } from '../../context/Theme'; +import { formatPercent } from '../../helpers/safeDisplay'; import { VChart } from '@visactor/react-vchart'; import { Activity, AlertTriangle, Info, PieChart } from 'lucide-react'; import { @@ -372,7 +373,7 @@ export const QualityTrendChart = ({ trend, loading, onZoom, t }) => { min: 0, max: 100, grid: { visible: false }, - label: { formatMethod: (v) => `${v}%` }, + label: { formatMethod: (v) => formatPercent(v, 0) }, }, { orient: 'bottom', type: 'band' }, ], @@ -388,7 +389,7 @@ export const QualityTrendChart = ({ trend, loading, onZoom, t }) => { { seriesId: 'rateLine', key: t('成功率'), - value: (d) => (d?.rate === null ? '-' : `${d?.rate}%`), + value: (d) => formatPercent(d?.rate, 1), }, ], }, diff --git a/src/components/quality/qualityConstants.js b/src/components/quality/qualityConstants.js index b6845741..0a37e36e 100644 --- a/src/components/quality/qualityConstants.js +++ b/src/components/quality/qualityConstants.js @@ -183,10 +183,12 @@ export const outcomeTagColor = { 6: 'purple', }; -export const pct = (v, digits = 1) => - v === null || v === undefined || Number.isNaN(v) +export const pct = (v, digits = 1) => { + const number = Number(v); + return v === null || v === undefined || !Number.isFinite(number) ? '-' - : `${(v * 100).toFixed(digits)}%`; + : `${(number * 100).toFixed(digits)}%`; +}; export const fmtInt = (v) => Number(v || 0).toLocaleString(); diff --git a/src/components/settings/ContentGuardSetting.jsx b/src/components/settings/ContentGuardSetting.jsx index bc7cb5ca..3241456a 100644 --- a/src/components/settings/ContentGuardSetting.jsx +++ b/src/components/settings/ContentGuardSetting.jsx @@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com */ import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js'; +import { formatIdReference } from '../../helpers/safeDisplay'; import { TestTube2 as ActionTestTube2 } from '@/components/common/icons/ActionIcons'; import { RefreshCw as ActionRefreshCw, @@ -484,7 +485,7 @@ export default function ContentGuardSetting() { }} optionList={users.map((user) => ({ value: user.id, - label: `${user.display_name || user.username} (#${user.id})`, + label: `${user.display_name || user.username || t('未知用户')} (${formatIdReference(user.id)})`, }))} emptyContent={ userKeyword diff --git a/src/components/smart-router/DecisionTable.jsx b/src/components/smart-router/DecisionTable.jsx index ff3dfafc..e5c56539 100644 --- a/src/components/smart-router/DecisionTable.jsx +++ b/src/components/smart-router/DecisionTable.jsx @@ -30,6 +30,7 @@ const DecisionTable = ({ mode, orgId }) => { const { t } = useTranslation(); const [data, setData] = useState({ items: [], total: 0 }); const [page, setPage] = useState(1); + const [pageSize, setPageSize] = useState(20); const [loading, setLoading] = useState(true); const [error, setError] = useState(''); @@ -38,7 +39,10 @@ const DecisionTable = ({ mode, orgId }) => { setError(''); try { setData( - (await listDecisions(mode, orgId, { p: page, page_size: 20 })) || { + (await listDecisions(mode, orgId, { + p: page, + page_size: pageSize, + })) || { items: [], total: 0, }, @@ -48,7 +52,7 @@ const DecisionTable = ({ mode, orgId }) => { } finally { setLoading(false); } - }, [mode, orgId, page, t]); + }, [mode, orgId, page, pageSize, t]); useEffect(() => { load(); @@ -147,12 +151,18 @@ const DecisionTable = ({ mode, orgId }) => { /> } pagination={{ - // 接口固定 page_size=20,不提供每页条数切换 current: page, - pageSize: 20, + pageSize, total: data.total || 0, size: 'small', - showSizeChanger: false, + showSizeChanger: mode === 'org', + onPageSizeChange: + mode === 'org' + ? (size) => { + setPage(1); + setPageSize(size); + } + : undefined, showTotal: (total) => t('共 {{total}} 条', { total }), onChange: setPage, }} diff --git a/src/components/smart-router/ProfileTable.jsx b/src/components/smart-router/ProfileTable.jsx index ce69f107..15a1e9a6 100644 --- a/src/components/smart-router/ProfileTable.jsx +++ b/src/components/smart-router/ProfileTable.jsx @@ -221,7 +221,7 @@ const ProfileTable = ({ mode, orgId, canWrite = true, emptyHint }) => { loading={loading} columns={columns} dataSource={list} - pagination={false} + pagination={mode === 'org' ? { resetOnDataChange: true } : false} scroll={{ x: 'max-content' }} empty={ -
-
- } - placeholder={t('密钥名称 / Key 片段')} - showClear - /> -
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
-
- - +
+ } + placeholder={t('密钥名称 / Key 片段')} + showClear + /> + + + + + + + + + + + +
+ ); }; diff --git a/src/components/table/admin-tokens/admin-tokens.css b/src/components/table/admin-tokens/admin-tokens.css index a9575622..55517769 100644 --- a/src/components/table/admin-tokens/admin-tokens.css +++ b/src/components/table/admin-tokens/admin-tokens.css @@ -1,32 +1,3 @@ -.console-page .console-search-card .admin-tokens-filter-form { - display: block; -} - -.admin-tokens-filter-grid { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 1rem; - width: 100%; -} - -.console-page .admin-tokens-filter-grid .ant-form-item-label > label { - color: var(--console-muted); - font-size: 13px; -} - -.admin-tokens-filter-actions, -.admin-tokens-tools { - display: flex; - align-items: center; - justify-content: flex-end; - flex-wrap: wrap; - gap: 0.5rem; -} - -.admin-tokens-filter-actions { - margin-top: 1rem; -} - .admin-tokens-toolbar { display: flex; align-items: center; @@ -39,6 +10,11 @@ .admin-tokens-tools { margin-inline-start: auto; + display: flex; + align-items: center; + justify-content: flex-end; + flex-wrap: wrap; + gap: 8px; } .console-page .console-table.admin-tokens-table .ant-table-thead > tr > th { @@ -78,15 +54,3 @@ padding: 0 4px; font-size: 13px; } - -@media (max-width: 1100px) { - .admin-tokens-filter-grid { - grid-template-columns: repeat(2, minmax(0, 1fr)); - } -} - -@media (max-width: 768px) { - .admin-tokens-filter-grid { - grid-template-columns: minmax(0, 1fr); - } -} diff --git a/src/components/table/channels/ChannelsColumnDefs.jsx b/src/components/table/channels/ChannelsColumnDefs.jsx index 1d03871c..c426810c 100644 --- a/src/components/table/channels/ChannelsColumnDefs.jsx +++ b/src/components/table/channels/ChannelsColumnDefs.jsx @@ -45,6 +45,11 @@ import { CHANNEL_OPTIONS } from '../../../constants'; import { IconTreeTriangleDown } from '@/components/ui/icons'; import { ShuffleBrandIcon } from '../../common/icons/BrandIcons'; +const formatDisplayPercent = (value, digits = 0) => { + const number = Number(value); + return Number.isFinite(number) ? `${number.toFixed(digits)}%` : '-'; +}; + function ChannelStatusSwitch({ record, manageChannel, t }) { const [loading, setLoading] = useState(false); return ( @@ -311,7 +316,7 @@ const renderDailyQuota = (record, dailyQuotaInfo, t) => { {t('已使用')}: {formatQuotaCount(info.daily_quota)}
- {t('使用率')}: {percent}% + {t('使用率')}: {formatDisplayPercent(percent)}
{isExceeded && (
@@ -327,7 +332,7 @@ const renderDailyQuota = (record, dailyQuotaInfo, t) => { strokeColor={strokeColor} size='small' showInfo - format={(percent) => `${percent}%`} + format={(percent) => formatDisplayPercent(percent)} />
diff --git a/src/components/table/channels/modals/EditChannelModal.jsx b/src/components/table/channels/modals/EditChannelModal.jsx index 7fcf6d3d..d7860a0b 100644 --- a/src/components/table/channels/modals/EditChannelModal.jsx +++ b/src/components/table/channels/modals/EditChannelModal.jsx @@ -16,6 +16,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { formatIdReference } from '../../../../helpers/safeDisplay'; import { I18N_TECHNICAL_TEXT } from '../../../../i18n/technicalText.js'; import { useEffectEvent } from '../../../../hooks/common/useEffectEvent'; @@ -290,11 +291,11 @@ const EditChannelModal = (props) => { if (ch.status !== 1) { return { value: ch.id, - label: `#${ch.id} ${ch.name}${t('(已禁用)')}`, + label: `${formatIdReference(ch.id)} ${ch.name}${t('(已禁用)')}`, disabled: true, }; } - const parts = [`#${ch.id} ${ch.name}`]; + const parts = [`${formatIdReference(ch.id)} ${ch.name}`]; if (ch.group) parts.push(ch.group); if (ch.region) parts.push(ch.region); return { value: ch.id, label: parts.join(' · ') }; @@ -345,7 +346,7 @@ const EditChannelModal = (props) => { .filter((id) => !known.has(id) && id !== channelId) .map((id) => ({ value: id, - label: `#${id}${t('(已删除)')}`, + label: `${formatIdReference(id)}${t('(已删除)')}`, disabled: true, })); return missing.length diff --git a/src/components/table/channels/modals/ModelTestModal.jsx b/src/components/table/channels/modals/ModelTestModal.jsx index 10d7458d..de203b49 100644 --- a/src/components/table/channels/modals/ModelTestModal.jsx +++ b/src/components/table/channels/modals/ModelTestModal.jsx @@ -25,6 +25,11 @@ import { copy, showError, showInfo, showSuccess } from '../../../../helpers'; import { MODEL_TABLE_PAGE_SIZE } from '../../../../constants'; import './model-test-modal.css'; +const formatTestTime = (value) => { + const number = Number(value); + return Number.isFinite(number) ? number.toFixed(2) : '0.00'; +}; + const ModelTestModal = ({ showModelTestModal, currentTestChannel, @@ -141,7 +146,7 @@ const ModelTestModal = ({ {testResult.success && ( {t('请求时长: {{time}}s', { - time: testResult.time.toFixed(2), + time: formatTestTime(testResult.time), })} )} diff --git a/src/components/table/channels/modals/MultiKeyManageModal.jsx b/src/components/table/channels/modals/MultiKeyManageModal.jsx index f40fe001..55445cdd 100644 --- a/src/components/table/channels/modals/MultiKeyManageModal.jsx +++ b/src/components/table/channels/modals/MultiKeyManageModal.jsx @@ -16,6 +16,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { formatIdReference } from '../../../../helpers/safeDisplay'; import { useEffectEvent } from '../../../../hooks/common/useEffectEvent'; import React, { useState, useEffect } from 'react'; @@ -359,7 +360,7 @@ const MultiKeyManageModal = ({ visible, onCancel, channel, onRefresh }) => { { title: t('索引'), dataIndex: 'index', - render: (text) => `#${text}`, + render: (text) => formatIdReference(text), }, // { // title: t('密钥预览'), diff --git a/src/components/table/redemptions/RedemptionsActions.jsx b/src/components/table/redemptions/RedemptionsActions.jsx index 93847b68..0bd3a3b1 100644 --- a/src/components/table/redemptions/RedemptionsActions.jsx +++ b/src/components/table/redemptions/RedemptionsActions.jsx @@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com */ import React from 'react'; +import { Copy, Plus, Trash2 } from '@/components/common/icons/ActionIcons'; import { Button } from '@/components/ui'; import { isAdmin } from '../../../helpers'; @@ -38,37 +39,29 @@ const RedemptionsActions = ({ }; return ( -
- {isAdmin() && ( - - )} - - {isAdmin() && ( )} + {isAdmin() && ( + + )}
); }; diff --git a/src/components/table/redemptions/RedemptionsColumnDefs.jsx b/src/components/table/redemptions/RedemptionsColumnDefs.jsx index 39e60d70..ed350c38 100644 --- a/src/components/table/redemptions/RedemptionsColumnDefs.jsx +++ b/src/components/table/redemptions/RedemptionsColumnDefs.jsx @@ -144,7 +144,7 @@ export const getRedemptionsColumns = ({ }, }, { - title: '', + title: t('操作'), dataIndex: 'operate', fixed: 'right', width: 205, diff --git a/src/components/table/redemptions/RedemptionsFilters.jsx b/src/components/table/redemptions/RedemptionsFilters.jsx index e608771f..9aea445a 100644 --- a/src/components/table/redemptions/RedemptionsFilters.jsx +++ b/src/components/table/redemptions/RedemptionsFilters.jsx @@ -51,28 +51,24 @@ const RedemptionsFilters = ({ onSubmit={searchRedemptions} allowEmpty={true} autoComplete='off' - layout='horizontal' + layout='vertical' trigger='change' stopValidateWithError={false} - className='w-full' + className='console-filter-panel' > -
-
- } - placeholder={t('关键字(id或者名称)')} - showClear - pure - size='small' - /> -
- + } + label={t('搜索关键字')} + placeholder={t('关键字(id或者名称)')} + showClear />
+ ); }; diff --git a/src/components/table/redemptions/RedemptionsTable.jsx b/src/components/table/redemptions/RedemptionsTable.jsx index 963116ec..027fb30d 100644 --- a/src/components/table/redemptions/RedemptionsTable.jsx +++ b/src/components/table/redemptions/RedemptionsTable.jsx @@ -18,12 +18,8 @@ For commercial licensing, please contact support@quantumnous.com */ import React, { useMemo, useState } from 'react'; -import { Empty } from '@/components/ui'; +import TableEmpty from '../../common/table/TableEmpty'; import CardTable from '../../common/ui/CardTable'; -import { - IllustrationNoResult, - IllustrationNoResultDark, -} from '../../common/illustrations'; import { getRedemptionsColumns } from './RedemptionsColumnDefs'; import DeleteRedemptionModal from './modals/DeleteRedemptionModal'; @@ -101,17 +97,8 @@ const RedemptionsTable = (redemptionsData) => { loading={loading} rowSelection={rowSelection} onRow={handleRow} - empty={ - } - darkModeImage={ - - } - description={t('搜索无结果')} - style={{ padding: 30 }} - /> - } - className='rounded-xl overflow-hidden' + empty={} + className='console-list-table overflow-hidden' size='middle' /> diff --git a/src/components/table/redemptions/index.jsx b/src/components/table/redemptions/index.jsx index 33928f42..3b48ba9c 100644 --- a/src/components/table/redemptions/index.jsx +++ b/src/components/table/redemptions/index.jsx @@ -82,15 +82,13 @@ const RedemptionsPage = () => { /> } type='type1' - descriptionArea={ - - } actionsArea={ -
+
+ - - {t('流')} - - ); - } else { - return ( - - {t('非流')} - - ); - } -} - -function renderUseTime(type, t) { - const time = parseInt(type); - let colorConfig; - - if (time < 101) { - colorConfig = { - bg: 'bg-emerald-50 dark:bg-emerald-950/30', - text: 'text-emerald-600 dark:text-emerald-400', - border: 'border-emerald-200/50 dark:border-emerald-800/50', - dot: 'bg-emerald-500', - }; - } else if (time < 300) { - colorConfig = { - bg: 'bg-amber-50 dark:bg-amber-950/30', - text: 'text-amber-600 dark:text-amber-400', - border: 'border-amber-200/50 dark:border-amber-800/50', - dot: 'bg-amber-500', - }; - } else { - colorConfig = { - bg: 'bg-rose-50 dark:bg-rose-950/30', - text: 'text-rose-600 dark:text-rose-400', - border: 'border-rose-200/50 dark:border-rose-800/50', - dot: 'bg-rose-500', - }; - } - - return ( - - {time}s - - ); -} - -function renderFirstUseTime(type, t) { - let time = parseFloat(type) / 1000.0; - time = time.toFixed(1); - let colorConfig; - - if (time < 3) { - colorConfig = { - bg: 'bg-teal-50 dark:bg-teal-950/30', - text: 'text-teal-600 dark:text-teal-400', - border: 'border-teal-200/50 dark:border-teal-800/50', - }; - } else if (time < 10) { - colorConfig = { - bg: 'bg-orange-50 dark:bg-orange-950/30', - text: 'text-orange-600 dark:text-orange-400', - border: 'border-orange-200/50 dark:border-orange-800/50', - }; - } else { - colorConfig = { - bg: 'bg-red-50 dark:bg-red-950/30', - text: 'text-red-600 dark:text-red-400', - border: 'border-red-200/50 dark:border-red-800/50', - }; - } - - return ( - - {time}s - - ); -} - function renderModelName(record, copyText, t, isRootUser) { let other = getLogOther(record.other); let modelMapped = @@ -384,7 +297,7 @@ const applyUsageRecordPresentation = ( ...baseColumn, width: RECORD_COLUMN_WIDTHS[baseColumn.key], fixed: undefined, - className: `usage-record-cell-${baseColumn.key}`, + className: baseColumn.className ?? `usage-record-cell-${baseColumn.key}`, }; switch (column.key) { case COLUMN_KEYS.TIME: @@ -449,15 +362,6 @@ const applyUsageRecordPresentation = ( ) : null, }; - case COLUMN_KEYS.USE_TIME: - return { - ...column, - title: t('用时/首字').replace('/', ' / '), - render: (text, record) => - record.type === 2 || record.type === 5 - ? renderRecordUseTime(record, t) - : null, - }; case COLUMN_KEYS.PROMPT: case COLUMN_KEYS.COMPLETION: return { @@ -693,34 +597,14 @@ export const getLogsColumns = ({ }, { key: COLUMN_KEYS.USE_TIME, - title: t('用时/首字'), + title: t('用时/首字').replace('/', ' / '), dataIndex: 'use_time', - render: (text, record, index) => { - if (!(record.type === 2 || record.type === 5)) { - return <>; - } - if (record.is_stream) { - let other = getLogOther(record.other); - return ( - <> - - {renderUseTime(text, t)} - {renderFirstUseTime(other?.frt, t)} - {renderIsStream(record.is_stream, t)} - - - ); - } else { - return ( - <> - - {renderUseTime(text, t)} - {renderIsStream(record.is_stream, t)} - - - ); - } - }, + align: 'center', + className: 'usage-record-cell-use_time', + render: (_, record) => + record.type === 2 || record.type === 5 + ? renderRecordUseTime(record, t) + : null, }, { key: COLUMN_KEYS.PROMPT, diff --git a/src/components/table/usage-logs/UsageLogsTable.jsx b/src/components/table/usage-logs/UsageLogsTable.jsx index a4dfbc2e..6ebb31f6 100644 --- a/src/components/table/usage-logs/UsageLogsTable.jsx +++ b/src/components/table/usage-logs/UsageLogsTable.jsx @@ -435,7 +435,7 @@ const LogsTable = (logsData) => { if (canView) setDetailRecord(record); }} > - {t('查看')} + {t('详情')} ); } @@ -449,7 +449,7 @@ const LogsTable = (logsData) => { if (canView) setDetailRecord(record); }} > - {t('查看')} + {t('详情')} ); }, diff --git a/src/components/table/users/UsersColumnDefs.jsx b/src/components/table/users/UsersColumnDefs.jsx index 4ef9f422..36a3ff23 100644 --- a/src/components/table/users/UsersColumnDefs.jsx +++ b/src/components/table/users/UsersColumnDefs.jsx @@ -26,10 +26,9 @@ import { Progress, Popover, Typography, - Dropdown, } from '@/components/ui'; import { Switch } from 'antd'; -import { IconMore } from '@/components/ui/icons'; +import { TableRowActions } from '@/components/common/table/TableToolbar'; import { renderGroup, renderNumber, @@ -256,50 +255,48 @@ const renderOperations = ( if (canChangeRole) { moreMenu.push( { - node: 'item', - name: t('提升'), + key: 'promote', + label: t('提升'), onClick: () => showPromoteModal(record), }, { - node: 'item', - name: t('降级'), + key: 'demote', + label: t('降级'), onClick: () => showDemoteModal(record), }, - { node: 'divider' }, + { type: 'divider' }, ); } moreMenu.push({ - node: 'item', - name: t('邀请记录'), + key: 'invitations', + label: t('邀请记录'), onClick: () => showInvitedUsersModal(record), }); if (canManage) { moreMenu.push( - { node: 'divider' }, + { type: 'divider' }, { - node: 'item', - name: t('重置 Passkey'), + key: 'reset-passkey', + label: t('重置 Passkey'), onClick: () => showResetPasskeyModal(record), }, { - node: 'item', - name: t('重置 2FA'), + key: 'reset-2fa', + label: t('重置 2FA'), onClick: () => showResetTwoFAModal(record), }, - { node: 'divider' }, + { type: 'divider' }, { - node: 'item', - name: t('注销'), - type: 'danger', + key: 'delete', + label: t('注销'), + danger: true, onClick: () => showDeleteModal(record), }, ); } return ( - // wrap 保留:移动端 CardTable 把按钮放进 ~280px 的卡片行里,Semi Space 默认 - // wrap:false 时溢出会被 .ant-card{overflow:hidden} 裁掉(不是滚动,是永久看不到) - + {canManage && ( <>
diff --git a/src/components/topup/modals/TopupHistoryModal.jsx b/src/components/topup/modals/TopupHistoryModal.jsx index d7b5645f..dbf3058d 100644 --- a/src/components/topup/modals/TopupHistoryModal.jsx +++ b/src/components/topup/modals/TopupHistoryModal.jsx @@ -43,6 +43,7 @@ import { IconSearch } from '@/components/ui/icons'; import { API, timestamp2string } from '../../../helpers'; import { isAdmin } from '../../../helpers/utils'; import { useIsMobile } from '../../../hooks/common/useIsMobile'; +import { formatCurrency } from '../../../helpers/safeDisplay'; const { Text } = Typography; @@ -236,7 +237,7 @@ const TopupHistoryModal = ({ visible, onCancel, t }) => { key: 'money', render: (money) => ( - ¥{Number(money || 0).toFixed(2)} + {formatCurrency(money, '¥', 2, '¥0.00')} ), }, diff --git a/src/components/topup/modals/WechatQRModal.jsx b/src/components/topup/modals/WechatQRModal.jsx index 13b0a64b..85c71b16 100644 --- a/src/components/topup/modals/WechatQRModal.jsx +++ b/src/components/topup/modals/WechatQRModal.jsx @@ -24,6 +24,7 @@ import { IconRefresh, IconClose } from '@/components/ui/icons'; import { useTranslation } from 'react-i18next'; import QRCode from 'qrcode'; import { API, renderQuota } from '../../../helpers'; +import { formatCurrency } from '../../../helpers/safeDisplay'; const { Text } = Typography; @@ -228,7 +229,7 @@ const WechatQRModal = ({ visible, onClose, orderData, pollFn }) => {
{t('支付金额:')} - ¥{orderData.amount?.toFixed(2)} + {formatCurrency(orderData.amount)}
diff --git a/src/components/ui/UiThemeProvider.jsx b/src/components/ui/UiThemeProvider.jsx index 03f8cab6..9fe7899c 100644 --- a/src/components/ui/UiThemeProvider.jsx +++ b/src/components/ui/UiThemeProvider.jsx @@ -39,6 +39,12 @@ import { useLocation } from 'react-router-dom'; import { useActualTheme } from '../../context/Theme'; import { normalizeLanguage } from '../../i18n/language'; import { colord } from 'colord'; +import { + PROTOTYPE_DARK_PRIMARY, + PROTOTYPE_DARK_SEED, + PROTOTYPE_LIGHT_PRIMARY, + resolveBrandPalette, +} from '../../helpers/brandPalette'; import './antd-v5-compat.css'; // 与下方 Ant Design locale 一一对应的 dayjs 语言(未覆盖语言与 Ant Design 一样回退中文)。 @@ -55,8 +61,8 @@ const DAYJS_LOCALES = { // 在线原型暗色:种子 #f2ad41 经 Ant Design 暗色算法推导出主色 #d1963a(悬停 #e8ba65、 // 选中背景 #574222 等)。系统以“最终主色”(--brand-primary) 作为 colorPrimary, // 算法其余衍生令牌需仍按原型种子推导,否则会从 #d1963a 再推一次而整体偏暗。 -const PROTOTYPE_DARK_PRIMARY = '#d1963a'; -const PROTOTYPE_DARK_SEED = '#f2ad41'; +const DARK_SURFACE = '#1b212b'; +const LIGHT_SURFACE = '#ffffff'; // v5 used these shadows in both themes; v6 derives white shadows in dark mode. 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)', }; -// 页面局部“品牌强调色”(原型 --brand):等于当前主题的种子色。 -// 浅色与自定义主色时即 colorPrimary;仅默认暗色主色 #d1963a 时回到原型种子 #f2ad41, -// 保证浅色 / 深色 / 自定义主题色三态都只由主题 token 推导,不在页面里另写颜色。 -export const brandAccentFromToken = (colorPrimary, dark) => - dark && colorPrimary?.toLowerCase() === PROTOTYPE_DARK_PRIMARY - ? PROTOTYPE_DARK_SEED - : colorPrimary; - -export const prototypeTheme = (dark) => ({ +const prototypeTheme = (dark, palette) => ({ algorithm: (seed, map) => { const derive = dark && seed.colorPrimary?.toLowerCase() === PROTOTYPE_DARK_PRIMARY @@ -91,14 +89,30 @@ export const prototypeTheme = (dark) => ({ ...(dark ? theme.darkAlgorithm : theme.defaultAlgorithm)(derive, map), colorPrimary: seed.colorPrimary, 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: { ...v5ShadowTokens, - colorPrimary: dark ? PROTOTYPE_DARK_PRIMARY : '#b96508', - colorInfo: dark ? PROTOTYPE_DARK_PRIMARY : '#b96508', + colorPrimary: palette.isPrototype + ? dark + ? PROTOTYPE_DARK_PRIMARY + : PROTOTYPE_LIGHT_PRIMARY + : palette.normal, + colorInfo: dark ? PROTOTYPE_DARK_PRIMARY : PROTOTYPE_LIGHT_PRIMARY, colorBgLayout: dark ? '#11151c' : '#f4f6f9', - colorBgContainer: dark ? '#1b212b' : '#ffffff', + colorBgContainer: dark ? DARK_SURFACE : LIGHT_SURFACE, colorText: dark ? '#e6ebf3' : '#263247', colorTextSecondary: dark ? '#8e9aaa' : '#7e8998', colorBorderSecondary: dark ? '#2b333f' : '#e9edf2', @@ -113,8 +127,22 @@ export const prototypeTheme = (dark) => ({ }, Menu: { itemHeight: 42, - itemSelectedBg: dark ? '#382b1b' : '#fff3df', - itemSelectedColor: dark ? '#f2ad41' : '#a95d07', + itemSelectedBg: palette.selectionBg, + 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 }, Modal: { borderRadiusLG: 12 }, @@ -128,10 +156,23 @@ const v5ComponentDefaults = { drawer: { mask: { blur: false } }, }; -function TokenBridge() { +function TokenBridge({ palette }) { const { token } = theme.useToken(); useLayoutEffect(() => { 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-black': '#000', ...Object.fromEntries( @@ -216,7 +257,7 @@ function TokenBridge() { } for (const [name, value] of Object.entries(values)) if (value != null) document.body.style.setProperty(`--${name}`, value); - }, [token]); + }, [token, palette]); return null; } @@ -237,14 +278,17 @@ export default function UiThemeProvider({ children }) { return () => window.removeEventListener('theme-tokens-applied', update); }, []); // Re-read the computed brand when the existing CSS theme is applied. - const config = useMemo(() => { - const result = prototypeTheme(dark); + const { config, palette } = useMemo(() => { // Keep existing configured brand previews and persistence in helpers/theme.js. const brand = getComputedStyle(document.body) .getPropertyValue('--brand-primary') .trim(); - if (brand) result.token.colorPrimary = brand; - return result; + const palette = resolveBrandPalette( + brand, + dark, + dark ? DARK_SURFACE : LIGHT_SURFACE, + ); + return { config: prototypeTheme(dark, palette), palette }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [dark, revision]); const language = normalizeLanguage(i18n.language); @@ -281,7 +325,7 @@ export default function UiThemeProvider({ children }) { return ( - + {children} diff --git a/src/components/ui/antd-v5-compat.css b/src/components/ui/antd-v5-compat.css index e6d0bf83..0cfc4fec 100644 --- a/src/components/ui/antd-v5-compat.css +++ b/src/components/ui/antd-v5-compat.css @@ -16,3 +16,7 @@ body[data-ui-scope='admin'] > label.ant-form-item-required::before { font-family: SimSun, sans-serif; } + +.ant-switch.ant-switch-checked .ant-switch-inner-checked { + color: var(--brand-on-primary); +} diff --git a/src/components/ui/index.jsx b/src/components/ui/index.jsx index 5a16db55..ca4a3d44 100644 --- a/src/components/ui/index.jsx +++ b/src/components/ui/index.jsx @@ -288,6 +288,7 @@ export function Table({ expandedRowKeys, onExpand, expandRowByClick, + expandable: nativeExpandable, pagination, size, onChange, @@ -305,7 +306,7 @@ export function Table({ onExpand, expandRowByClick, } - : undefined; + : nativeExpandable; return ( { + if (resetLocalPage) setLocalPage(1); + }, [resetLocalPage, resetSource]); const pageSize = local && !config.onPageSizeChange ? localSize : (config.pageSize ?? 10); const total = config.total ?? props.dataSource?.length ?? 0; diff --git a/src/components/ui/pagination.js b/src/components/ui/pagination.js index 16aed87d..4060f385 100644 --- a/src/components/ui/pagination.js +++ b/src/components/ui/pagination.js @@ -21,7 +21,9 @@ import i18next from 'i18next'; export const isCenterPaginationScope = () => typeof window !== 'undefined' && - /^\/(console|org)(\/|$)/.test(window.location?.pathname || ''); + /^\/(?:console|org|user-center\/key-management)(?:\/|$)/.test( + window.location?.pathname || '', + ); export const centerPaginationOptions = (config, isMobile = false) => ({ ...config, diff --git a/src/helpers/api.js b/src/helpers/api.js index ab513ac2..ab13025c 100644 --- a/src/helpers/api.js +++ b/src/helpers/api.js @@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com import { getUserIdFromLocalStorage, + redirectToExpiredLogin, showError, formatMessageForAPI, isValidMessage, @@ -29,6 +30,7 @@ import i18next from 'i18next'; import { MESSAGE_ROLES } from '../constants/playground.constants'; import { getServerURL } from './config'; import { buildGetRequestKey, getHeaderValue } from './requestDedupe'; +import { installRequestLifecycle } from './requestLifecycle'; function createAPIInstance() { const serverURL = getServerURL(); @@ -41,14 +43,20 @@ function createAPIInstance() { }); } -export let API = createAPIInstance(); +export let API; +let retireAPI; function patchAPIInstance(instance) { const originalGet = instance.get.bind(instance); const inFlightGetRequests = new Map(); instance.get = (url, config = {}) => { - if (config?.disableDuplicate) { + if ( + config?.disableDuplicate || + config?.signal || + config?.cancelToken || + config?.requestGroup + ) { return originalGet(url, config); } @@ -56,12 +64,13 @@ function patchAPIInstance(instance) { url.startsWith('/api/org/') && typeof localStorage !== 'undefined' ? localStorage.getItem('current_org_id') || '' : ''; - const key = buildGetRequestKey( + const requestKey = buildGetRequestKey( url, config, fallbackOrgId, getUserIdFromLocalStorage(), ); + const key = `${requestKey}#error=${!config?.skipErrorHandler}#session=${config?.sessionBound !== false}`; if (inFlightGetRequests.has(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 头 function addOrgHeaderInterceptor(instance) { instance.interceptors.request.use((config) => { @@ -107,19 +99,21 @@ function addOrgHeaderInterceptor(instance) { }); } -// 初始化时添加 interceptor -addResponseInterceptor(API); -addOrgHeaderInterceptor(API); - export function updateAPI() { - API = createAPIInstance(); - - patchAPIInstance(API); - // 重新添加 interceptors - addResponseInterceptor(API); - addOrgHeaderInterceptor(API); + const instance = createAPIInstance(); + patchAPIInstance(instance); + addOrgHeaderInterceptor(instance); + const previous = retireAPI; + retireAPI = installRequestLifecycle(instance, { + onError: (error) => showError(error, { redirectOnUnauthorized: false }), + onSessionExpired: redirectToExpiredLogin, + }); + API = instance; + previous?.(); } +updateAPI(); + // playground // 构建API请求负载 @@ -310,8 +304,6 @@ export const processGroupsData = (data, userGroup) => { return groupOptions; }; -// 原来components中的utils.js - export async function getOAuthState() { let path = '/api/oauth/state'; let affCode = localStorage.getItem('aff'); diff --git a/src/helpers/auth.jsx b/src/helpers/auth.jsx index 8f6a358f..57d17278 100644 --- a/src/helpers/auth.jsx +++ b/src/helpers/auth.jsx @@ -25,11 +25,7 @@ import { StatusContext } from '../context/Status'; import { canAccessDelegatedAdminPage } from './adminDelegation'; import { ADMIN_DELEGATION_OPTION_KEY } from '../constants/settingTabs'; import Loading from '../components/common/ui/Loading'; -import { - getUserData, - isSafePostLoginRedirect, - savePostLoginRedirect, -} from './data'; +import { getUserData, isSafePostLoginRedirect } from './data'; import { authRedirectTarget } from './authRedirect'; /** @@ -49,11 +45,9 @@ export const isAuthPagePath = (pathname) => /^\/org\/[^/]+\/login$/.test(pathname); // 未登录统一引导到企业登录(本产品主推企业用户;个人用户可经页内切换回 /login)。 -// 回跳地址已存本地(savePostLoginRedirect),切换到个人登录后仍可正常回跳。 const getLoginTarget = (location) => { const target = `${location.pathname}${location.search}${location.hash}`; if (isSafePostLoginRedirect(target)) { - savePostLoginRedirect(target); return `/org/login?redirect=${encodeURIComponent(target)}`; } return '/org/login'; diff --git a/src/helpers/brandPalette.js b/src/helpers/brandPalette.js new file mode 100644 index 00000000..d1aac717 --- /dev/null +++ b/src/helpers/brandPalette.js @@ -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 . + +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(), + }; +} diff --git a/src/helpers/dashboard.jsx b/src/helpers/dashboard.jsx index a38afd67..67df7dfa 100644 --- a/src/helpers/dashboard.jsx +++ b/src/helpers/dashboard.jsx @@ -30,6 +30,7 @@ import { showSuccess, showError, } from './utils'; +import { formatPercent, toFiniteNumber } from './safeDisplay.js'; import { STORAGE_KEYS, DEFAULT_TIME_INTERVALS, @@ -217,37 +218,46 @@ export const renderMonitorList = ( grouped[g].push(m); }); - const renderItem = (monitor, idx) => ( -
-
-
-
- - {monitor.name} + const renderItem = (monitor, idx) => { + const uptime = Math.max( + 0, + Math.min(1, toFiniteNumber(monitor.uptime) ?? 0), + ); + return ( +
+
+
+
+ + {monitor.name} + +
+ + {formatPercent(uptime * 100, 2)}
- - {((monitor.uptime || 0) * 100).toFixed(2)}% - -
-
- - {getUptimeStatusText(monitor.status)} - -
- +
+ + {getUptimeStatusText(monitor.status)} + +
+ +
-
- ); + ); + }; return Object.entries(grouped).map(([gname, list]) => (
diff --git a/src/helpers/data.js b/src/helpers/data.js index 5c3648e9..4090a61f 100644 --- a/src/helpers/data.js +++ b/src/helpers/data.js @@ -145,11 +145,43 @@ export function isSafePostLoginRedirect(path) { export function savePostLoginRedirect(path) { if (isSafePostLoginRedirect(path)) { sessionStorage.setItem(POST_LOGIN_REDIRECT_KEY, path); + } else { + sessionStorage.removeItem(POST_LOGIN_REDIRECT_KEY); } } -export function consumePostLoginRedirect(defaultPath = DEFAULT_LOGIN_REDIRECT) { - const path = sessionStorage.getItem(POST_LOGIN_REDIRECT_KEY); +export function consumePostLoginRedirect({ + redirect = sessionStorage.getItem(POST_LOGIN_REDIRECT_KEY), + enterprise = false, + orgOnly = false, +} = {}) { 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; } diff --git a/src/helpers/loginFlow.js b/src/helpers/loginFlow.js index 2198f21a..1d8fd3ee 100644 --- a/src/helpers/loginFlow.js +++ b/src/helpers/loginFlow.js @@ -19,7 +19,7 @@ For commercial licensing, please contact support@quantumnous.com import { API, updateAPI } from './api'; import { clearUserData, consumePostLoginRedirect, setUserData } from './data'; -import { showError, showSuccess } from './utils'; +import { showError } from './utils'; const SESSION_NOT_PERSISTED_MESSAGE = '登录成功但浏览器未能保存登录会话,请确认 Cookie 未被拦截后重试'; @@ -35,8 +35,8 @@ export async function finishLogin({ userDispatch, navigate, t = (s) => s, - successMessage, - redirectOverride, + redirect, + enterprise = false, }) { setUserData(data); // Recreate the axios instance so any in-flight request map from a prior @@ -49,7 +49,11 @@ export async function finishLogin({ skipErrorHandler: 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'); } verifiedUser = res.data.data; @@ -64,18 +68,13 @@ export async function finishLogin({ setUserData(verifiedUser); userDispatch({ type: 'login', payload: verifiedUser }); - const message = - successMessage === undefined ? t('登录成功!') : successMessage; - if (message) { - showSuccess(message); - } - // org_only(仅企业资源)用户默认落企业空间,与 AuthRedirect 一致:默认落地页 - // (密钥管理)挂载即调用被 BlockOrgOnlyMode 拦截的 /api/token,会先弹报错再被 - // orgConfined 踢回 /org;企业中心整体关闭时 orgConfined 不生效,会一直停在报错页 - const defaultRedirect = - verifiedUser.org_only_mode === true ? '/org' : undefined; - navigate(redirectOverride ?? consumePostLoginRedirect(defaultRedirect), { - replace: true, - }); + navigate( + consumePostLoginRedirect({ + redirect, + enterprise, + orgOnly: verifiedUser.org_only_mode === true, + }), + { replace: true }, + ); return true; } diff --git a/src/helpers/navigationVisibility.js b/src/helpers/navigationVisibility.js index f9c79136..86a082db 100644 --- a/src/helpers/navigationVisibility.js +++ b/src/helpers/navigationVisibility.js @@ -29,6 +29,12 @@ export const isGroupAllowed = (groups, userGroup) => { return allowedGroups.includes(getEffectiveUserGroup(userGroup)); }; +export const isSidebarModuleVisible = (config, key, userGroup) => + config?.enabled !== false && + config?.[key] !== false && + isGroupAllowed(config?.groups, userGroup) && + isGroupAllowed(config?.moduleGroups?.[key], userGroup); + export const isHeaderActionButtonVisible = (config, key, userGroup) => { let buttons = config; diff --git a/src/helpers/render.jsx b/src/helpers/render.jsx index 7c470983..dece4a39 100644 --- a/src/helpers/render.jsx +++ b/src/helpers/render.jsx @@ -56,6 +56,7 @@ import { Lock, Bot as FastGPT, Image as Jimeng } from 'lucide-react'; import { Modal, Tag, Typography } from '@/components/ui'; import { copy, getCurrencySymbol, showSuccess } from './utils'; import { visit } from 'unist-util-visit'; +import { toFiniteNumber } from './safeDisplay'; // Full Avatar/Text/Combine variants are loaded only when configured icons render. const LobeHubIcon = lazy(() => import('../components/common/LobeHubIcon')); @@ -783,35 +784,30 @@ export function renderNumber(num) { } export function getQuotaPerUnit() { - let quotaPerUnit = localStorage.getItem('quota_per_unit'); - quotaPerUnit = parseFloat(quotaPerUnit); - return quotaPerUnit; + const quotaPerUnit = toFiniteNumber(localStorage.getItem('quota_per_unit')); + return quotaPerUnit !== null && quotaPerUnit > 0 ? quotaPerUnit : 500000; } export function renderUnitWithQuota(quota) { - let quotaPerUnit = localStorage.getItem('quota_per_unit'); - quotaPerUnit = parseFloat(quotaPerUnit); - quota = parseFloat(quota); - return quotaPerUnit * quota; + return getQuotaPerUnit() * (toFiniteNumber(quota) ?? 0); } export function getQuotaWithUnit(quota, digits = 6) { - let quotaPerUnit = localStorage.getItem('quota_per_unit'); - quotaPerUnit = parseFloat(quotaPerUnit); - return (quota / quotaPerUnit).toFixed(digits); + return ((toFiniteNumber(quota) ?? 0) / getQuotaPerUnit()).toFixed(digits); } export function renderQuotaWithAmount(amount) { + const normalizedAmount = toFiniteNumber(amount) ?? 0; const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD'; if (quotaDisplayType === 'TOKENS') { - return renderNumber(renderUnitWithQuota(amount)); + return renderNumber(renderUnitWithQuota(normalizedAmount)); } if (quotaDisplayType === 'CNY') { - return getCurrencySymbol('CNY') + amount; + return getCurrencySymbol('CNY') + normalizedAmount; } else if (quotaDisplayType === 'CUSTOM') { - return getCurrencySymbol('CUSTOM') + amount; + return getCurrencySymbol('CUSTOM') + normalizedAmount; } - return getCurrencySymbol('USD') + amount; + return getCurrencySymbol('USD') + normalizedAmount; } /** @@ -830,11 +826,8 @@ export function getCurrencyConfig() { try { if (statusStr) { const s = JSON.parse(statusStr); - // 注意:如果设置了汇率值(包括1),使用设置值;只有未设置(undefined/null)时才用默认值1 - rate = - s?.usd_exchange_rate !== undefined && s?.usd_exchange_rate !== null - ? s.usd_exchange_rate - : 1; + const parsedRate = toFiniteNumber(s?.usd_exchange_rate); + rate = parsedRate !== null && parsedRate > 0 ? parsedRate : 1; } } catch (e) {} } else if (quotaDisplayType === 'CUSTOM') { @@ -842,7 +835,8 @@ export function getCurrencyConfig() { if (statusStr) { const s = JSON.parse(statusStr); symbol = getCurrencySymbol('CUSTOM', s?.custom_currency_symbol); - rate = s?.custom_currency_exchange_rate || 1; + const parsedRate = toFiniteNumber(s?.custom_currency_exchange_rate); + rate = parsedRate !== null && parsedRate > 0 ? parsedRate : 1; } } catch (e) { symbol = getCurrencySymbol('CUSTOM'); @@ -860,18 +854,18 @@ export function getCurrencyConfig() { */ export function convertUSDToCurrency(usdAmount, digits = 2) { const { symbol, rate } = getCurrencyConfig(); - const convertedAmount = usdAmount * rate; + const convertedAmount = (toFiniteNumber(usdAmount) ?? 0) * rate; return symbol + convertedAmount.toFixed(digits); } export function renderQuota(quota, digits = 2) { - let quotaPerUnit = localStorage.getItem('quota_per_unit'); + const normalizedQuota = toFiniteNumber(quota) ?? 0; const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD'; - quotaPerUnit = parseFloat(quotaPerUnit); + const quotaPerUnit = getQuotaPerUnit(); if (quotaDisplayType === 'TOKENS') { - return renderNumber(quota); + return renderNumber(normalizedQuota); } - const resultUSD = quota / quotaPerUnit; + const resultUSD = normalizedQuota / quotaPerUnit; let symbol = getCurrencySymbol('USD'); let value = resultUSD; if (quotaDisplayType === 'CNY') { @@ -880,7 +874,8 @@ export function renderQuota(quota, digits = 2) { try { if (statusStr) { const s = JSON.parse(statusStr); - usdRate = s?.usd_exchange_rate || 1; + const parsedRate = toFiniteNumber(s?.usd_exchange_rate); + usdRate = parsedRate !== null && parsedRate > 0 ? parsedRate : 1; } } catch (e) {} value = resultUSD * usdRate; @@ -893,14 +888,15 @@ export function renderQuota(quota, digits = 2) { if (statusStr) { const s = JSON.parse(statusStr); symbolCustom = getCurrencySymbol('CUSTOM', s?.custom_currency_symbol); - rate = s?.custom_currency_exchange_rate || rate; + const parsedRate = toFiniteNumber(s?.custom_currency_exchange_rate); + rate = parsedRate !== null && parsedRate > 0 ? parsedRate : 1; } } catch (e) {} value = resultUSD * rate; symbol = symbolCustom; } const fixedResult = value.toFixed(digits); - if (parseFloat(fixedResult) === 0 && quota > 0 && value > 0) { + if (parseFloat(fixedResult) === 0 && normalizedQuota > 0 && value > 0) { const minValue = Math.pow(10, -digits); return symbol + minValue.toFixed(digits); } @@ -947,7 +943,10 @@ export function renderExportQuota(quota, digits = 6) { if (!Number.isFinite(quotaPerUnit) || quotaPerUnit <= 0) { quotaPerUnit = 500000; } - return getCurrencySymbol() + (quota / quotaPerUnit).toFixed(digits); + return ( + getCurrencySymbol() + + ((toFiniteNumber(quota) ?? 0) / quotaPerUnit).toFixed(digits) + ); } function isValidGroupRatio(ratio) { diff --git a/src/helpers/requestLifecycle.js b/src/helpers/requestLifecycle.js new file mode 100644 index 00000000..679e57bb --- /dev/null +++ b/src/helpers/requestLifecycle.js @@ -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 . + +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(); +} diff --git a/src/helpers/safeDisplay.js b/src/helpers/safeDisplay.js new file mode 100644 index 00000000..bd97d992 --- /dev/null +++ b/src/helpers/safeDisplay.js @@ -0,0 +1,68 @@ +/* +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 . + +For commercial licensing, please contact support@quantumnous.com +*/ + +export const toFiniteNumber = (value) => { + if (value === null || value === undefined) return null; + if (typeof value === 'string' && value.trim() === '') 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 formatNumber = (value, digits = 2, fallback = '-') => { + const number = toFiniteNumber(value); + return number === null ? fallback : number.toFixed(digits); +}; + +export const formatCurrency = ( + value, + symbol = '¥', + digits = 2, + fallback = '-', +) => { + const formatted = formatNumber(value, digits, null); + return formatted === null ? fallback : symbol + formatted; +}; + +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; +}; diff --git a/src/helpers/utils.jsx b/src/helpers/utils.jsx index f0ef9aeb..773a3a5a 100644 --- a/src/helpers/utils.jsx +++ b/src/helpers/utils.jsx @@ -28,12 +28,7 @@ import { import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile'; // 官方价折扣计算(纯函数):管理端与市场页共用 import { buildOfficialComparison, formatDiscountLabel } from './officialPrice'; -import { - clearUserData, - getUserData, - isSafePostLoginRedirect, - savePostLoginRedirect, -} from './data'; +import { clearUserData, getUserData, isSafePostLoginRedirect } from './data'; const HTMLToastContent = ({ htmlContent }) => { return
; @@ -128,56 +123,64 @@ if (isMobileScreen) { // showNoticeOptions.transition = 'flip'; } -export function showError(error) { - console.error(error); - if (error.message) { - if (error.name === 'AxiosError') { - // 检查 response 是否存在(网络错误时 response 为 undefined) - if (!error.response) { - Toast.error(i18next.t('错误:网络请求失败,请检查网络连接')); - return; - } - switch (error.response.status) { - case 401: - // 清除用户状态 - clearUserData(); - const currentPath = `${window.location.pathname}${window.location.search}${window.location.hash}`; - const redirect = isSafePostLoginRedirect(currentPath) - ? `&redirect=${encodeURIComponent(currentPath)}` - : ''; - if (redirect) { - savePostLoginRedirect(currentPath); - } - // toast.error('错误:未登录或登录已过期,请重新登录!', showErrorOptions); - // 会话过期统一回企业登录(默认登录入口),OrgLogin 会识别 expired/redirect 参数 - window.location.href = `/org/login?expired=true${redirect}`; - break; - case 429: - Toast.error(i18next.t('错误:请求次数过多,请稍后再试!')); - break; - case 500: - Toast.error(i18next.t('错误:服务器内部错误,请联系管理员!')); - break; - case 405: - Toast.info(i18next.t('本站仅作演示之用,无服务端!')); - break; - default: { - // 后端业务错误(4xx/5xx)带有面向用户的 message 字段; - // 优先展示它,而不是 axios 的 "Request failed with status code XXX"。 - const backendMessage = error.response?.data?.message; - Toast.error( - i18next.t('错误:{{message}}', { - message: backendMessage || error.message, - }), - ); - } - } +let redirectingToLogin = false; +const reportedRequestErrors = new WeakSet(); + +export function redirectToExpiredLogin() { + if (redirectingToLogin) return; + redirectingToLogin = true; + clearUserData(); + const { pathname, search, hash } = window.location; + const currentPath = `${pathname}${search}${hash}`; + const redirect = isSafePostLoginRedirect(currentPath) + ? `&redirect=${encodeURIComponent(currentPath)}` + : ''; + window.location.replace(`/org/login?expired=true${redirect}`); +} + +export function showError(error, { redirectOnUnauthorized = true } = {}) { + if ( + error?.code === 'ERR_CANCELED' || + error === 'canceled' || + (redirectingToLogin && error === 'Request failed with status code 401') + ) + return; + + if (error?.isAxiosError || error?.name === 'AxiosError') { + if (reportedRequestErrors.has(error)) return; + reportedRequestErrors.add(error); + + const status = error.response?.status; + if (status === 401 && redirectOnUnauthorized) { + redirectToExpiredLogin(); return; } - Toast.error(i18next.t('错误:{{message}}', { message: error.message })); - } else { - Toast.error(i18next.t('错误:{{message}}', { message: error })); + if (status === 405) { + Toast.info({ + 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) { diff --git a/src/hooks/common/useHeaderBar.js b/src/hooks/common/useHeaderBar.js index 6d6dd88c..42c874c2 100644 --- a/src/hooks/common/useHeaderBar.js +++ b/src/hooks/common/useHeaderBar.js @@ -28,7 +28,7 @@ import { getSystemName, API, clearUserData, - showSuccess, + updateAPI, } from '../../helpers'; import { rememberUserLanguage } from '../../i18n/bootstrap'; import { useIsMobile } from './useIsMobile'; @@ -163,11 +163,11 @@ export const useHeaderBar = ({ onMobileMenuToggle, drawerOpen }) => { // Actions const logout = useCallback(async () => { await API.get('/api/user/logout'); - showSuccess(t('注销成功!')); userDispatch({ type: 'logout' }); clearUserData(); + updateAPI(); navigate('/org/login'); - }, [navigate, t, userDispatch]); + }, [navigate, userDispatch]); const handleLanguageChange = useCallback( (lang) => { diff --git a/src/hooks/model-pricing/useModelPricingData.jsx b/src/hooks/model-pricing/useModelPricingData.jsx index 9059090f..4118f442 100644 --- a/src/hooks/model-pricing/useModelPricingData.jsx +++ b/src/hooks/model-pricing/useModelPricingData.jsx @@ -31,6 +31,7 @@ import { import { Modal } from '@/components/ui'; import { UserContext } from '../../context/User'; import { StatusContext } from '../../context/Status'; +import { formatNumber, toFiniteNumber } from '../../helpers/safeDisplay'; export const useModelPricingData = () => { const { t } = useTranslation(); @@ -189,17 +190,27 @@ export const useModelPricingData = () => { ); const displayPrice = (usdPrice) => { - let priceInUSD = usdPrice; + const basePrice = toFiniteNumber(usdPrice) ?? 0; + const rechargeRate = toFiniteNumber(priceRate) ?? 1; + const exchangeRate = toFiniteNumber(usdExchangeRate) ?? 1; + const customRate = toFiniteNumber(customExchangeRate) ?? 1; + let priceInUSD = basePrice; if (showWithRecharge) { - priceInUSD = (usdPrice * priceRate) / usdExchangeRate; + priceInUSD = (basePrice * rechargeRate) / exchangeRate; } if (currency === 'CNY') { - return `${getCurrencySymbol('CNY')}${(priceInUSD * usdExchangeRate).toFixed(3)}`; + return ( + getCurrencySymbol('CNY') + + formatNumber(priceInUSD * exchangeRate, 3, '0.000') + ); } else if (currency === 'CUSTOM') { - return `${getCurrencySymbol('CUSTOM', customCurrencySymbol)}${(priceInUSD * customExchangeRate).toFixed(3)}`; + return ( + getCurrencySymbol('CUSTOM', customCurrencySymbol) + + formatNumber(priceInUSD * customRate, 3, '0.000') + ); } - return `${getCurrencySymbol('USD')}${priceInUSD.toFixed(3)}`; + return getCurrencySymbol('USD') + formatNumber(priceInUSD, 3, '0.000'); }; const setModelsFormat = ( diff --git a/src/hooks/redemptions/useRedemptionsData.jsx b/src/hooks/redemptions/useRedemptionsData.jsx index c5e7403a..d1af47a6 100644 --- a/src/hooks/redemptions/useRedemptionsData.jsx +++ b/src/hooks/redemptions/useRedemptionsData.jsx @@ -276,11 +276,6 @@ export const useRedemptionsData = () => { // Close edit modal const closeEdit = () => { setShowEdit(false); - setTimeout(() => { - setEditingRedemption({ - id: undefined, - }); - }, 500); }; // Remove record (for UI update after deletion) diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index 48832b65..a84f2089 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -6118,6 +6118,7 @@ "未找到匹配会话": "No matching conversations", "未找到视频URL": "Video URL not found", "未知": "Unknown", + "未知档位": "Unknown tier", "未知错误": "Unknown error", "未知供应商": "Unknown", "未知计费类型,暂不支持配置官方价": "Unknown billing type; official price cannot be configured", diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 03ee4dc9..aaabbadc 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -5868,6 +5868,7 @@ "未找到匹配会话": "Aucune session match trouvée", "未找到视频URL": "Vidéo introuvable URL", "未知": "Inconnu", + "未知档位": "Niveau inconnu", "未知错误": "Erreur inconnue", "未知供应商": "Inconnu", "未知计费类型,暂不支持配置官方价": "Type de facturation inconnu, configuration du prix officiel non prise en charge temporairement", diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index ae3600e0..292ea889 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -6118,6 +6118,7 @@ "未找到匹配会话": "一致する会話が見つかりません", "未找到视频URL": "動画URLが見つかりません", "未知": "不明", + "未知档位": "不明なティア", "未知错误": "不明なエラー", "未知供应商": "不明なプロバイダー", "未知计费类型,暂不支持配置官方价": "不明な課金タイプのため、公式価格は設定できません", diff --git a/src/i18n/locales/ko.json b/src/i18n/locales/ko.json index ba72a2af..1bb7cd7f 100644 --- a/src/i18n/locales/ko.json +++ b/src/i18n/locales/ko.json @@ -6118,6 +6118,7 @@ "未找到匹配会话": "일치하는 대화가 없습니다", "未找到视频URL": "동영상 URL을 찾을 수 없습니다", "未知": "알 수 없음", + "未知档位": "알 수 없는 등급", "未知错误": "알 수 없는 오류", "未知供应商": "알 수 없음", "未知计费类型,暂不支持配置官方价": "알 수 없는 과금 유형이라 아직 정가를 설정할 수 없습니다", diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index b280593a..48de1189 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -5905,6 +5905,7 @@ "未找到匹配会话": "Нет совпадений разговоров", "未找到视频URL": "Видео URL не найден", "未知": "Неизвестно", + "未知档位": "Неизвестный уровень", "未知错误": "Неизвестная ошибка", "未知供应商": "Неизвестный поставщик", "未知计费类型,暂不支持配置官方价": "Неизвестный тип выставления счетов; официальная цена не может быть настроена", diff --git a/src/i18n/locales/th.json b/src/i18n/locales/th.json index 5d1cfeef..90ee0ae7 100644 --- a/src/i18n/locales/th.json +++ b/src/i18n/locales/th.json @@ -6118,6 +6118,7 @@ "未找到匹配会话": "ไม่พบบทสนทนาที่ตรงกัน", "未找到视频URL": "ไม่พบ URL ของวิดีโอ", "未知": "ไม่ทราบ", + "未知档位": "ระดับที่ไม่รู้จัก", "未知错误": "ข้อผิดพลาดที่ไม่ทราบสาเหตุ", "未知供应商": "ไม่ทราบ", "未知计费类型,暂不支持配置官方价": "ประเภทการคิดค่าบริการที่ไม่รู้จัก ยังไม่รองรับการตั้งราคาทางการ", diff --git a/src/i18n/locales/vi.json b/src/i18n/locales/vi.json index 0779f8a6..9cbc6746 100644 --- a/src/i18n/locales/vi.json +++ b/src/i18n/locales/vi.json @@ -6118,6 +6118,7 @@ "未找到匹配会话": "Không tìm thấy hội thoại phù hợp", "未找到视频URL": "Không tìm thấy URL video", "未知": "không xác định", + "未知档位": "Bậc không xác định", "未知错误": "Lỗi không xác định", "未知供应商": "Không xác định", "未知计费类型,暂不支持配置官方价": "Loại tính phí không xác định, tạm không hỗ trợ cấu hình giá chính thức", diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.json index e728d6bc..984233e7 100644 --- a/src/i18n/locales/zh-TW.json +++ b/src/i18n/locales/zh-TW.json @@ -6118,6 +6118,7 @@ "未找到匹配会话": "未找到匹配會話", "未找到视频URL": "未找到影片URL", "未知": "未知", + "未知档位": "未知檔位", "未知错误": "未知錯誤", "未知供应商": "未知供應商", "未知计费类型,暂不支持配置官方价": "未知計費類型,暫不支援配置官方價", diff --git a/src/i18n/locales/zh.json b/src/i18n/locales/zh.json index 41e99aa4..5e19ef1e 100644 --- a/src/i18n/locales/zh.json +++ b/src/i18n/locales/zh.json @@ -6057,6 +6057,7 @@ "未找到匹配会话": "未找到匹配会话", "未找到视频URL": "未找到视频URL", "未知": "未知", + "未知档位": "未知档位", "未知错误": "未知错误", "未知供应商": "未知供应商", "未知计费类型,暂不支持配置官方价": "未知计费类型,暂不支持配置官方价", diff --git a/src/pages/AdminInvoice/index.jsx b/src/pages/AdminInvoice/index.jsx index 52c120e8..83c7287d 100644 --- a/src/pages/AdminInvoice/index.jsx +++ b/src/pages/AdminInvoice/index.jsx @@ -16,24 +16,25 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { + formatCurrency, + formatNumber, + formatUserReference, + toFiniteNumber, +} from '../../helpers/safeDisplay'; import { Trans } from 'react-i18next'; import { - Eye as ActionEye, - Check as ActionCheck, - X as ActionX, - Ban as ActionBan, - RotateCw as ActionRotateCw, -} from '@/components/common/icons/ActionIcons'; -import { - ConsoleCard, - ConsoleSearchBar, - ConsoleSearchActions, + ConsoleFilterField, + ConsoleFilterGrid, + ConsoleListTable, } from '../../components/console/ConsolePrimitives'; +import ConsoleCollection from '../../components/console/ConsoleCollection'; +import { useIsMobile } from '../../hooks/common/useIsMobile'; +import { createCardProPagination } from '../../helpers/utils'; import React, { useEffect, useState, useCallback } from 'react'; import { useTranslation } from 'react-i18next'; import { - Table, Button, Input, Tag, @@ -43,7 +44,14 @@ import { Spin, Typography, } from '@/components/ui'; -import { Search } from 'lucide-react'; +import { + Search, + Eye as ActionEye, + Check as ActionCheck, + X as ActionX, + Ban as ActionBan, + RotateCw as ActionRotateCw, +} from '@/components/common/icons/ActionIcons'; import { API, showError, showSuccess } from '../../helpers'; import { INVOICE_STATUS, @@ -63,6 +71,7 @@ const paymentMethodMap = { const AdminInvoice = () => { const { t, i18n } = useTranslation(); + const isMobile = useIsMobile(); const [invoices, setInvoices] = useState([]); const [total, setTotal] = useState(0); const [loading, setLoading] = useState(false); @@ -118,6 +127,13 @@ const AdminInvoice = () => { setSearchKeyword(keyword); }; + const handleReset = () => { + setPage(1); + setKeyword(''); + setSearchKeyword(''); + setStatusFilter(''); + }; + const handleStatusFilterChange = (value) => { setPage(1); setStatusFilter(value || ''); @@ -258,7 +274,7 @@ const AdminInvoice = () => { displayName || username || ( - {t('用户 #{{id}}', { id: record.user_id })} + {formatUserReference(null, record.user_id)} ) ); @@ -281,7 +297,7 @@ const AdminInvoice = () => { title: t('金额'), dataIndex: 'amount', width: 90, - render: (v) => `¥${Number(v).toFixed(2)}`, + render: (v) => formatCurrency(v), }, { title: t('状态'), @@ -301,6 +317,7 @@ const AdminInvoice = () => { }, { title: t('操作'), + key: 'actions', width: 200, fixed: 'right', render: (_, record) => ( @@ -379,60 +396,63 @@ const AdminInvoice = () => { return (
- {/* 筛选区:标题与筛选项同行 */} - -
- } - placeholder={t('搜索抬头/税号/订单号/用户')} - value={keyword} - onChange={setKeyword} - onEnterPress={handleSearch} - style={{ width: 240 }} - /> - } + placeholder={t('搜索抬头/税号/订单号/用户')} + value={keyword} + onChange={setKeyword} + /> + + + } + value={draft.query} + onChange={(event) => set('query', event.target.value)} + allowClear + placeholder={t(placeholders[section])} + aria-label={t(placeholders[section])} + /> + + {typeOptions && ( - )} - {section === 'partners' && ( - - )} - {['assignments', 'bills', 'adjustments'].includes(section) && ( - + )} + + -
+
{t('共 {{count}} 条', { count: server ? server.total : filtered.length, })} - {onExport && ( - - )} +
+ {onExport && ( + + )} + {toolbarActions} +
{ - setPage(next); - server?.onChange({ ...filters, status, page: next }); - }, - showSizeChanger: false, - showTotal: (total) => t('共 {{total}} 条', { total }), - }} + pagination={ + (server ? server.total : filtered.length) + ? { + size: 'small', + pageSize: server ? server.pageSize : pageSize, + total: server ? server.total : filtered.length, + currentPage: server ? server.page : page, + onPageChange: (next) => { + setPage(next); + server?.onChange({ ...filters, status, page: next }); + }, + onPageSizeChange: (nextSize) => { + setPage(1); + setPageSize(nextSize); + server?.onChange({ + ...filters, + status, + page: 1, + pageSize: nextSize, + }); + }, + } + : false + } empty={ . 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 { Button, Descriptions, Spin, Tag } from 'antd'; @@ -112,7 +114,7 @@ export default function PartnerDetail({ ['主体类型', commissionLabel(t, 'partnerType', row.type)], ['状态', commissionLabel(t, 'status', row.status)], ['伙伴名称', row.name], - ['登录主体', `#${row.user_id}`], + ['登录主体', formatUserReference('', row.user_id, t('未知用户'))], ['证件号码', row.identity_no], ['联系人', row.contact_name], ['联系电话', row.contact_phone], @@ -145,12 +147,12 @@ export default function PartnerDetail({ dataSource={assignments.filter( (item) => item.partner_id === row.id, )} - pagination={{ pageSize: 5, size: 'small' }} + pagination={{ pageSize: 10 }} columns={[ { title: t('客户'), render: (_, item) => - item.customer_name || `#${item.subject_id}`, + item.customer_name || formatIdReference(item.subject_id), }, { title: t('类型'), diff --git a/src/pages/CommissionV2/PartnerPortal.jsx b/src/pages/CommissionV2/PartnerPortal.jsx index 2d949d06..679d9d71 100644 --- a/src/pages/CommissionV2/PartnerPortal.jsx +++ b/src/pages/CommissionV2/PartnerPortal.jsx @@ -16,7 +16,13 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { formatIdReference } from '../../helpers/safeDisplay'; +import { ConsoleCollectionSearch } from '@/components/console/ConsoleCollection'; +import { + ConsoleFilterField, + ConsoleFilterGrid, +} from '@/components/console/ConsolePrimitives'; import React, { useCallback, useEffect, @@ -42,6 +48,8 @@ import { } from '@/components/ui'; import { ArrowLeft as ActionArrowLeft, + Download, + Search, RefreshCw as ActionRefresh, } from '@/components/common/icons/ActionIcons'; import { @@ -146,6 +154,9 @@ export default function PartnerPortal({ const [customerStatus, setCustomerStatus] = useState('all'); const [billMonth, setBillMonth] = useState('all'); const [billStatus, setBillStatus] = useState('all'); + const [billPage, setBillPage] = useState(1); + const [customerPage, setCustomerPage] = useState(1); + const [detailPage, setDetailPage] = useState(1); const loadVersion = useRef(0); const detailVersion = useRef(0); const selectedId = useRef(null); @@ -250,6 +261,7 @@ export default function PartnerPortal({ setDetailLoading(true); setError(''); setQuery(''); + setDetailPage(1); setAction(null); setReason(''); setActionError(''); @@ -540,43 +552,85 @@ export default function PartnerPortal({ }, ]; + const refreshButton = ( + + ); + const renderBills = () => ( <> + + { + setBillMonth('all'); + setBillStatus('all'); + setBillPage(1); + }} + onSearch={() => setBillPage(1)} + > + + { + setBillStatus(value); + setBillPage(1); + }} + optionList={[ + { value: 'all', label: t('全部状态') }, + ...Array.from(new Set(rows.map((row) => row.status))).map( + (value) => ({ + value, + label: commissionLabel(t, 'status', value), + }), + ), + ]} + /> + + + -
- row.status))).map( - (value) => ({ - value, - label: commissionLabel(t, 'status', value), - }), - ), - ]} - /> +
{t('共 {{count}} 张账单', { count: visibleBills.length })} +
{refreshButton}
0 ? { pageSize: 10 } : false} + pagination={ + visibleBills.length > 0 + ? { pageSize: 10, current: billPage, onChange: setBillPage } + : false + } scroll={{ x: 1120 }} empty={ - + + { + setQuery(''); + setDetailPage(1); + }} + onSearch={() => setDetailPage(1)} + > + + } + value={query} + onChange={(value) => { + setQuery(value); + setDetailPage(1); + }} + placeholder={t('搜索客户、模型、计费记录或档位')} + showClear + /> + + +
0 ? { pageSize: 10 } : false} + pagination={ + detailItems.length > 0 + ? { + pageSize: 10, + current: detailPage, + onChange: setDetailPage, + } + : false + } empty={ - {row.customer_name || `#${row.subject_id}`} ·{' '} + {row.customer_name || formatIdReference(row.subject_id)} ·{' '} {t('客户保护期临近到期')} {date(protectionUntil(row))} @@ -924,96 +1005,136 @@ export default function PartnerPortal({ ); const renderCustomers = () => ( - - -
- + + - } + value={customerQuery} + onChange={(value) => { + setCustomerQuery(value); + setCustomerPage(1); + }} + showClear + placeholder={t('搜索客户名称或编号')} + /> + + +
0 + ? { + pageSize: 10, + current: customerPage, + onChange: setCustomerPage, + } + : false + } + scroll={{ x: 1100 }} + empty={ + + } + columns={[ + { + title: t('客户'), + render: (_, row) => ( + + {row.customer_name || + row.subject_name || + `${commissionLabel(t, 'subjectType', row.subject_type)} ${formatIdReference(row.subject_id)}`} + + ), + }, + { + title: t('类型'), + dataIndex: 'subject_type', + render: (value) => commissionLabel(t, 'subjectType', value), + }, + { title: t('归属状态'), dataIndex: 'status', render: tag }, + { + title: t('正式归属起点'), + dataIndex: 'formal_at', + render: formatDateTime, + }, + { title: t('保护期开始'), dataIndex: 'started_at', render: date }, + { + title: t('保护期至'), + render: (_, row) => date(protectionUntil(row)), + }, + { + title: t('保护期剩余天数'), + render: (_, row) => + PROTECTED.includes(row.status) + ? Math.max( + 0, + Math.ceil( + (protectionUntil(row) - Date.now() / 1000) / 86400, + ), + ) + : '—', + }, + { + title: t('归属结束'), + dataIndex: 'ended_at', + render: formatDateTime, + }, ]} /> - - {t('共 {{count}} 条归属记录', { count: visibleCustomers.length })} - - -
0 ? { pageSize: 10 } : false} - scroll={{ x: 1100 }} - empty={ - - } - columns={[ - { - title: t('客户'), - render: (_, row) => ( - - {row.customer_name || - row.subject_name || - `${commissionLabel(t, 'subjectType', row.subject_type)} #${row.subject_id}`} - - ), - }, - { - title: t('类型'), - dataIndex: 'subject_type', - render: (value) => commissionLabel(t, 'subjectType', value), - }, - { title: t('归属状态'), dataIndex: 'status', render: tag }, - { - title: t('正式归属起点'), - dataIndex: 'formal_at', - render: formatDateTime, - }, - { title: t('保护期开始'), dataIndex: 'started_at', render: date }, - { - title: t('保护期至'), - render: (_, row) => date(protectionUntil(row)), - }, - { - title: t('保护期剩余天数'), - render: (_, row) => - PROTECTED.includes(row.status) - ? Math.max( - 0, - Math.ceil( - (protectionUntil(row) - Date.now() / 1000) / 86400, - ), - ) - : '—', - }, - { - title: t('归属结束'), - dataIndex: 'ended_at', - render: formatDateTime, - }, - ]} - /> - + + ); const renderEstimate = () => ( @@ -1057,7 +1178,7 @@ export default function PartnerPortal({ className='partner-portal-estimate-table' rowKey='statement_month' dataSource={realtime} - pagination={false} + pagination={realtime.length ? { pageSize: 10 } : false} empty={ {t(subtitles[active])} @@ -1254,7 +1375,7 @@ export default function PartnerPortal({ {!embedded && ( {selected - ? `${t('账单号')} #${selected.id} · ${selected.statement_month}` + ? `${t('账单号')} ${formatIdReference(selected.id)} · ${selected.statement_month}` : t(subtitles[active])} {!selected && ['overview', 'estimate'].includes(active) && @@ -1268,6 +1389,7 @@ export default function PartnerPortal({ {selected && ( <> + {(selected || + !loaded || + !['bills', 'customers'].includes(active)) && + refreshButton} {error && } @@ -1347,7 +1462,7 @@ export default function PartnerPortal({ style={themeStyle} className='commission-modal partner-portal-modal' visible={!!action} - title={`${t(action === 'reject' ? '驳回账单' : '确认账单')} · #${selected?.id || ''}`} + title={`${t(action === 'reject' ? '驳回账单' : '确认账单')} · ${formatIdReference(selected?.id)}`} confirmLoading={mutationLoading} closeOnEsc={!mutationLoading} maskClosable={!mutationLoading} diff --git a/src/pages/CommissionV2/index.jsx b/src/pages/CommissionV2/index.jsx index 6a4f0e24..584737af 100644 --- a/src/pages/CommissionV2/index.jsx +++ b/src/pages/CommissionV2/index.jsx @@ -16,6 +16,12 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { + formatCurrency, + formatIdReference, + formatPercent, + toFiniteNumber, +} from '../../helpers/safeDisplay'; import React, { useCallback, @@ -56,7 +62,6 @@ import { PencilLine, ScrollText, ShieldAlert, - ChevronDown, } from 'lucide-react'; import Dashboard from './Dashboard'; import ListPanel from './ListPanel'; @@ -65,20 +70,18 @@ import PartnerDetail from './PartnerDetail'; import PartnerPortal from './PartnerPortal'; import { partnerScope, createPartnerTransport } from './partnerScope'; import { tierStatus } from './listFilters'; -import { - Button, - DatePicker, - Dropdown, - Empty, - Select, - Spin, - Tag, - Typography, -} from 'antd'; +import { Button, DatePicker, Empty, Select, Spin, Tag, Typography } from 'antd'; import dayjs from 'dayjs'; -import { Plus, RefreshCw } from '../../components/common/icons/ActionIcons'; +import { + Download, + History, + Link, + Plus, + RefreshCw, +} from '../../components/common/icons/ActionIcons'; import { API } from '../../helpers'; import * as XLSX from 'xlsx'; +import { TableRowActions } from '@/components/common/table/TableToolbar'; import './styles.css'; import { OperationsDialog, @@ -91,7 +94,8 @@ const { Title, Text } = Typography; const emptyState = (description) => ( ); -const money = (value) => `¥${(Number(value || 0) / 1e6).toFixed(2)}`; +const money = (value) => + formatCurrency((toFiniteNumber(value) ?? 0) / 1e6, '¥', 2, '¥0.00'); const protectionUntil = (row) => Number(row.extended_until || row.protected_until || 0); const date = (value) => @@ -194,7 +198,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 value = groups.get(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 || '—', group: item.group_name || item.group || '—', rate_bps: item.rate_bps, @@ -216,7 +220,7 @@ function TierSummary({ items }) { rowKey='id' size='small' dataSource={groups} - pagination={false} + pagination={groups.length ? { pageSize: 10 } : false} columns={[ { title: t('客户'), dataIndex: 'customer' }, { title: t('分佣档位'), dataIndex: 'tier' }, @@ -224,7 +228,7 @@ function TierSummary({ items }) { { title: t('比例'), dataIndex: 'rate_bps', - render: (value) => `${Number(value || 0) / 100}%`, + render: (value) => formatPercent(Number(value || 0) / 100, 2), }, { title: t('调用笔数'), dataIndex: 'count' }, { title: t('有效销售额'), dataIndex: 'sales', render: money }, @@ -240,7 +244,7 @@ function PaymentTable({ payments, admin = false }) {
{t('返回账单列表')} -
+
{(status === 'estimated' || status === 'checking') && ( )} - + {status === 'pending_confirmation' && ( )} @@ -448,9 +454,7 @@ function AdminStatementDetail({ rowKey='id' columns={itemColumns} dataSource={items} - pagination={{ - pageSize: 10, - }} + pagination={items.length ? { pageSize: 10 } : false} scroll={{ x: 1800 }} empty={emptyState(t('暂无计费明细'))} /> @@ -466,7 +470,7 @@ function AdminStatementDetail({
- {t('查看详情')} + {t('详情')} ), }, @@ -930,7 +934,9 @@ function AdminPage() { dataIndex: 'user_id', render: (value, row) => ( ( -
+ + setOperation({ kind: 'partner-agreement', row }), + }, + ...(['draft', 'suspended'].includes(row.status) + ? [ + { + key: 'partner-active', + label: t(row.status === 'draft' ? '启用' : '恢复生效'), + onClick: () => + setOperation({ + kind: 'partner-status', + row, + status: 'active', + }), + }, + ] + : []), + ...(row.status === 'active' + ? [ + { + key: 'partner-suspend', + label: t('暂停合作'), + onClick: () => + setOperation({ + kind: 'partner-status', + row, + status: 'suspended', + }), + }, + ] + : []), + ...(row.status !== 'terminated' + ? [ + { + key: 'partner-terminate', + label: t('终止合作'), + danger: true, + onClick: () => + setOperation({ + kind: 'partner-status', + row, + status: 'terminated', + }), + }, + ] + : []), + ]} + > - - setOperation({ kind: 'partner-agreement', row }), - }, - ...(['draft', 'suspended'].includes(row.status) - ? [ - { - key: 'partner-active', - label: t( - row.status === 'draft' ? '启用' : '恢复生效', - ), - onClick: () => - setOperation({ - kind: 'partner-status', - row, - status: 'active', - }), - }, - ] - : []), - ...(row.status === 'active' - ? [ - { - key: 'partner-suspend', - label: t('暂停合作'), - onClick: () => - setOperation({ - kind: 'partner-status', - row, - status: 'suspended', - }), - }, - ] - : []), - ...(row.status !== 'terminated' - ? [ - { - key: 'partner-terminate', - label: t('终止合作'), - danger: true, - onClick: () => - setOperation({ - kind: 'partner-status', - row, - status: 'terminated', - }), - }, - ] - : []), - ], - }} - > - - -
+ ), }, ], @@ -1092,7 +1082,7 @@ function AdminPage() { ? t('企业组织') : t('个人用户')) } - reference={`${commissionLabel(t, 'subjectType', row.subject_type)} #${row.subject_id}`} + reference={`${commissionLabel(t, 'subjectType', row.subject_type)} ${formatIdReference(row.subject_id)}`} /> ), }, @@ -1284,7 +1274,8 @@ function AdminPage() { ) .map( (id) => - entityNames.channels.get(Number(id)) || `#${id}`, + entityNames.channels.get(Number(id)) || + formatIdReference(id), ) .join('、') : row.source_type === 'model' @@ -1297,7 +1288,7 @@ function AdminPage() { { title: t('比例'), dataIndex: 'rate_bps', - render: (v) => `${(Number(v || 0) / 100).toFixed(2)}%`, + render: (v) => formatPercent(Number(v) / 100, 2), }, { title: t('生效时间'), @@ -1515,6 +1506,88 @@ function AdminPage() { ); XLSX.writeFile(workbook, `commission-${key}-${month}.xlsx`); }; + const listToolbarActions = ( + <> + + {active === 'partners' && ( + + )} + {active === 'assignments' && ( + + )} + {active === 'tiers' && ( + + )} + {active === 'adjustments' && ( + + )} + {active === 'tiers' && ( + <> + + + + )} + {active === 'bills' && ( + + )} + + ); const tableFor = (key) => key === 'tiers' ? ( exportRows('tiers', rows)} refreshToken={data} + toolbarActions={listToolbarActions} /> ) : ( exportRows(key, rows)} context={listContext} + toolbarActions={listToolbarActions} /> ); return ( @@ -1575,80 +1650,11 @@ function AdminPage() { }} /> )} - - {active === 'partners' && ( - )} - {active === 'assignments' && ( - - )} - {active === 'tiers' && ( - - )} - {active === 'adjustments' && ( - - )} - {active === 'tiers' && ( - <> - - - - )} - {active === 'bills' && !selectedStatement && ( - - )} {error && ( diff --git a/src/pages/CommissionV2/latestTiers.js b/src/pages/CommissionV2/latestTiers.js index 2ee44ccb..b7c9c465 100644 --- a/src/pages/CommissionV2/latestTiers.js +++ b/src/pages/CommissionV2/latestTiers.js @@ -16,11 +16,13 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ +import { formatIdReference } from '../../helpers/safeDisplay.js'; + export function latestTierURL(filters = {}, page = 1, snapshot = {}) { const params = new URLSearchParams({ view: 'latest', p: String(page), - page_size: '100', + page_size: String(filters.pageSize ?? 100), }); if (filters.query?.trim()) params.set('q', filters.query.trim()); if (filters.type) params.set('source_type', filters.type); @@ -39,7 +41,9 @@ export async function fetchAllLatestTiers(fetchJSON, filters = {}) { let snapshot; let total; for (let page = 1; ; page++) { - const result = await fetchJSON(latestTierURL(filters, page, snapshot)); + const result = await fetchJSON( + latestTierURL({ ...filters, pageSize: 100 }, page, snapshot), + ); if (!snapshot) { snapshot = { as_of: result.as_of, revision: result.revision }; total = result.total; @@ -81,5 +85,5 @@ export function identityOptionLabel(item) { const name = item.name || item.display_name || item.username || item.code || ''; const identifier = item.name ? item.code : item.username; - return `${name}${identifier && identifier !== name ? ` · ${identifier}` : ''} (#${item.id})${item.disabled_reason ? ` · ${item.disabled_reason}` : ''}`; + return `${name}${identifier && identifier !== name ? ` · ${identifier}` : ''} (${formatIdReference(item.id)})${item.disabled_reason ? ` · ${item.disabled_reason}` : ''}`; } diff --git a/src/pages/CommissionV2/latestTiers.test.js b/src/pages/CommissionV2/latestTiers.test.js index 2714ce6a..5b722ac7 100644 --- a/src/pages/CommissionV2/latestTiers.test.js +++ b/src/pages/CommissionV2/latestTiers.test.js @@ -57,6 +57,9 @@ test('latest all status is omitted and export pins server snapshot across all pa ), false, ); + const listURL = new URL(latestTierURL({ pageSize: 20 }, 2), 'http://local'); + assert.equal(listURL.searchParams.get('page_size'), '20'); + assert.equal(listURL.searchParams.get('p'), '2'); const urls = []; const rows = await fetchAllLatestTiers( async (url) => { @@ -69,9 +72,10 @@ test('latest all status is omitted and export pins server snapshot across all pa revision: 7, }; }, - { query: '中文', type: 'level' }, + { query: '中文', type: 'level', pageSize: 20 }, ); assert.equal(rows.length, 2); + assert.ok(urls.every((url) => /page_size=100/.test(url))); assert.match(urls[1], /as_of=123/); assert.match(urls[1], /revision=7/); }); diff --git a/src/pages/CommissionV2/operations.jsx b/src/pages/CommissionV2/operations.jsx index d2947a1b..bd039152 100644 --- a/src/pages/CommissionV2/operations.jsx +++ b/src/pages/CommissionV2/operations.jsx @@ -51,6 +51,12 @@ import { } from './operationForm'; import { pickerEpoch } from './datePicker'; import { API } from '../../helpers'; +import { + formatCurrency, + formatIdReference, + formatPercent, + toFiniteNumber, +} from '../../helpers/safeDisplay'; import RemoteIdentitySelect from './RemoteIdentitySelect'; import { fetchAllLatestTiers } from './latestTiers'; import './formSections.css'; @@ -340,7 +346,7 @@ export function OperationsDialog({ style={{ width: '100%' }} optionList={rows.map((item) => ({ value: item.id, - label: `${name(item)} (#${item.id})`, + label: `${name(item)} (${formatIdReference(item.id)})`, }))} /> @@ -848,7 +854,7 @@ export function OperationsDialog({ channel.id, { value: channel.id, - label: `${channel.name} (#${channel.id})`, + label: `${channel.name || t('未知渠道')} (${formatIdReference(channel.id)})`, }, ]), ]).values(), @@ -944,7 +950,7 @@ export function OperationsDialog({ '等级档位', bindingConfigs.map((item) => ({ ...item, id: item.config_id })), (item) => - `${item.name || item.tier_key} · 配置 #${item.config_id}`, + `${item.name || item.tier_key || t('未知档位')} · 配置 ${formatIdReference(item.config_id)}`, )} {dateField('effective_from', '绑定生效时间', true)} `${Number(value || 0) / 100}%`, + render: (value) => formatPercent(Number(value || 0) / 100, 2), }, { title: t('提成金额'), dataIndex: 'commission_uyuan', render: money }, ]; @@ -1358,11 +1364,16 @@ export function SettlementDialog({ @@ -1449,7 +1460,7 @@ export function SettlementDialog({ onChange={(value) => set('detail_id', value)} optionList={items.map((item) => ({ value: item.detail_id, - label: `${item.billing_record_id} · ${item.model_name || ''} · ${Number(item.rate_bps || 0) / 100}%`, + label: `${formatIdReference(item.billing_record_id)} · ${item.model_name || t('未知模型')} · ${formatPercent(Number(item.rate_bps) / 100, 2)}`, }))} /> diff --git a/src/pages/CommissionV2/styles.css b/src/pages/CommissionV2/styles.css index 54ac3bba..bec195a5 100644 --- a/src/pages/CommissionV2/styles.css +++ b/src/pages/CommissionV2/styles.css @@ -905,8 +905,7 @@ margin-top: 18px; } .commission-filter-end { - justify-content: flex-end; - margin-bottom: 18px; + margin-bottom: 16px; } .commission-search-field { display: flex; @@ -919,17 +918,6 @@ .commission-search-field .ant-select { width: 100%; } -.commission-filter-card .console-search-fields { - display: grid; - grid-template-columns: repeat(4, minmax(0, 1fr)); - gap: 16px; -} -.commission-filter-card .console-search-actions { - margin-top: 16px; -} -.commission-filter-toggle.ant-btn { - display: none; -} .commission-detail-tabs { margin-top: 18px; padding: 8px 24px 24px; @@ -948,19 +936,9 @@ outline-offset: 2px; } @media (max-width: 768px) { - .commission-filter-card .console-search-fields { - grid-template-columns: minmax(0, 1fr); - } .commission-card > .ant-card-body { padding: 16px; } - .commission-filter-toggle.ant-btn { - display: inline-flex; - margin-bottom: 16px; - } - .commission-filter-card:not(.is-open) { - display: none; - } .commission-page-header { flex-direction: column; align-items: stretch; diff --git a/src/pages/ExperienceCenter/components/AICreation/Image/ImageGenerationForm.css b/src/pages/ExperienceCenter/components/AICreation/Image/ImageGenerationForm.css index 5641b022..7703e01e 100644 --- a/src/pages/ExperienceCenter/components/AICreation/Image/ImageGenerationForm.css +++ b/src/pages/ExperienceCenter/components/AICreation/Image/ImageGenerationForm.css @@ -6,11 +6,40 @@ --igf-ink: var(--text-primary); --igf-muted: var(--text-secondary); --igf-line: var(--border-subtle); + --igf-surface: var(--surface-card); --igf-accent: var(--ui-color-primary); --igf-fill: color-mix(in srgb, var(--text-primary) 4%, var(--surface-card)); --igf-danger: var(--ui-color-danger); --igf-warning: var(--ui-color-warning); --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, @@ -152,6 +181,13 @@ 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 { min-height: 18px; color: var(--igf-muted); diff --git a/src/pages/ExperienceCenter/components/AICreation/ImageGenerationForm.jsx b/src/pages/ExperienceCenter/components/AICreation/ImageGenerationForm.jsx index 125e9e60..934c31c8 100644 --- a/src/pages/ExperienceCenter/components/AICreation/ImageGenerationForm.jsx +++ b/src/pages/ExperienceCenter/components/AICreation/ImageGenerationForm.jsx @@ -140,7 +140,7 @@ const hasImageTaskType = (dataTransfer) => const Section = ({ title, extra, children, className = '' }) => (
{title || extra ? (
@@ -383,12 +383,14 @@ const ImageGenerationForm = ({ creation }) => { loading={submitting} onClick={handleSubmit} 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={{ background: isButtonDisabled ? 'var(--ui-color-fill-1)' : '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', height: '48px', fontSize: '15px', @@ -538,328 +540,337 @@ const ImageGenerationForm = ({ creation }) => { return (
- {/* 标题 */} -
-
-
-
- - {t('AI 图片创作')} +
+ {/* 标题 */} +
+
+
+
+ + {t('AI 图片创作')} +
+ + {t('图片生成')} + + + {formBodyHidden && selectedModel + ? selectedModel.display_name || selectedModel.model + : t('输入描述即可生成图片')} +
- - {t('图片生成')} - +
+ {!formBodyHidden && ( + + )} + {isMobile && ( + + )} +
+
+
+ + {/* 移动端折叠时只显示生成按钮 + 简略 */} + {formBodyHidden && ( +
+ {renderGenerateArea()} - {formBodyHidden && selectedModel - ? selectedModel.display_name || selectedModel.model - : t('输入描述即可生成图片')} + {prompt + ? prompt.length > 50 + ? prompt.slice(0, 50) + '...' + : prompt + : t('点击展开编辑参数')}
-
- {!formBodyHidden && ( - - )} - {isMobile && ( - - )} -
-
-
+ )} - {/* 移动端折叠时只显示生成按钮 + 简略 */} - {formBodyHidden && ( -
- {renderGenerateArea()} - - {prompt - ? prompt.length > 50 - ? prompt.slice(0, 50) + '...' - : prompt - : t('点击展开编辑参数')} - -
- )} + {!formBodyHidden && ( + <> + {/* 模型选择 */} +
{renderModelSection()}
- {!formBodyHidden && ( - <> - {/* 模型选择 */} -
{renderModelSection()}
+ {/* 生成方式(来自 schema modes) */} + {selectedModel && modeOptions.length > 1 ? ( +
+ o.mode)} + value={formData.mode} + onChange={setMode} + ariaLabel={t('生成方式')} + optionDisabledReasons={Object.fromEntries( + modeOptions + .filter((o) => o.disabled) + .map((o) => [o.mode, t(o.reason || '当前不可用')]), + )} + renderOption={(mode) => { + const Icon = MODE_ICONS[mode] || Type; + return ( + + + ); + }} + /> +
+ ) : null} - {/* 生成方式(来自 schema modes) */} - {selectedModel && modeOptions.length > 1 ? ( -
- o.mode)} - value={formData.mode} - onChange={setMode} - ariaLabel={t('生成方式')} - optionDisabledReasons={Object.fromEntries( - modeOptions - .filter((o) => o.disabled) - .map((o) => [o.mode, t(o.reason || '当前不可用')]), - )} - renderOption={(mode) => { - const Icon = MODE_ICONS[mode] || Type; - return ( - - - ); - }} - /> -
- ) : null} - - {/* 提示词 + 模板 + 历史 */} -
- {/* AI 优化提示词 —— 按钮始终可点击,handler 内判断并 Toast 解释原因 */} - - - {promptHistory.length > 0 && ( - - {promptHistory.map((p, idx) => ( - setPrompt(p)}> -
- {p} -
-
- ))} - + {/* 提示词 + 模板 + 历史 */} +
+ {/* AI 优化提示词 —— 按钮始终可点击,handler 内判断并 Toast 解释原因 */} + + + {promptHistory.length > 0 && ( + + {promptHistory.map((p, idx) => ( + setPrompt(p)} + > +
+ {p} +
+
+ ))} + + } > - - {t('历史')} - -
- )} - - {IS_MAC ? ( - - ) : ( - {I18N_TECHNICAL_TEXT.CTRL} + + )} - + - {I18N_TECHNICAL_TEXT.ENTER} - {t('生成')} - -
- } - > -