From 07e9b1ac98676837c503fb2fda292f8b6d23fc08 Mon Sep 17 00:00:00 2001 From: zhanjunhao <642307404@qq.com> Date: Wed, 21 Oct 2026 18:47:21 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E4=BC=98=E5=8C=96=E5=85=AC?= =?UTF-8?q?=E5=85=B1=E7=8A=B6=E6=80=81=E9=80=BB=E8=BE=91=E5=B9=B6=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E7=94=A8=E6=88=B7=E5=88=97=E8=A1=A8=E5=88=86=E9=A1=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 提取存储解析、通知已读、表格偏好和企业筛选参数逻辑 - 修复分页尺寸切换的旧页码、筛选丢失及 Semi 重复回调问题 - 补充 51 项回归测试,统一检查入口并修复格式配置和 JSON 语法 - 记录 179 项测试、生产构建和隔离浏览器交互验收结果 - 删除过期迁移与性能报告并同步开发文档 Co-Authored-By: Claude Opus 5 --- .prettierignore | 9 + .prettierrc.mjs | 5 +- README.md | 7 +- docs/MAINTAINABILITY_REPORT.md | 113 ++++++++ docs/NPM_MIGRATION.md | 34 --- docs/PERFORMANCE_REPORT.md | 228 ---------------- docs/PROJECT_ANALYSIS.zh-CN.md | 18 +- package.json | 5 +- public/config.js | 19 ++ scripts/translated_ja.json | 3 +- src/components/table/users/index.jsx | 2 + src/helpers/columnVisibility.js | 46 ++++ src/helpers/columnVisibility.test.js | 149 +++++++++++ src/helpers/notificationReadState.js | 51 ++++ src/helpers/orgLogFilters.js | 34 +++ src/helpers/orgLogFilters.test.js | 75 ++++++ src/helpers/storageJson.js | 49 ++++ src/helpers/storageJson.test.js | 300 ++++++++++++++++++++++ src/helpers/tableCompactMode.js | 43 ++++ src/helpers/utils.jsx | 34 +-- src/hooks/common/useNotifications.js | 59 ++--- src/hooks/common/useTableCompactMode.js | 15 +- src/hooks/org/useOrgData.js | 39 +-- src/hooks/task-logs/useTaskLogsData.js | 26 +- src/hooks/usage-logs/useUsageLogsData.jsx | 30 +-- src/hooks/users/useUsersData.jsx | 85 +++--- src/hooks/users/useUsersData.test.js | 256 ++++++++++++++++++ tests/modal-overflow.test.js | 19 ++ tests/org-prompt-records.test.js | 19 ++ tests/users-pagination.test.js | 178 +++++++++++++ 30 files changed, 1484 insertions(+), 466 deletions(-) create mode 100644 .prettierignore create mode 100644 docs/MAINTAINABILITY_REPORT.md delete mode 100644 docs/NPM_MIGRATION.md delete mode 100644 docs/PERFORMANCE_REPORT.md create mode 100644 src/helpers/columnVisibility.js create mode 100644 src/helpers/columnVisibility.test.js create mode 100644 src/helpers/notificationReadState.js create mode 100644 src/helpers/orgLogFilters.js create mode 100644 src/helpers/orgLogFilters.test.js create mode 100644 src/helpers/storageJson.js create mode 100644 src/helpers/storageJson.test.js create mode 100644 src/helpers/tableCompactMode.js create mode 100644 src/hooks/users/useUsersData.test.js create mode 100644 tests/users-pagination.test.js diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..a1f8c151 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,9 @@ +# Generated build output and tool caches are not source files. +node_modules/ +dist/ +dist-ssr/ +build/ +coverage/ +.nyc_output/ +.vite/ +.cache/ diff --git a/.prettierrc.mjs b/.prettierrc.mjs index 5140bc3e..87263dad 100644 --- a/.prettierrc.mjs +++ b/.prettierrc.mjs @@ -1 +1,4 @@ -module.exports = require('@so1ve/prettier-config'); +export default { + singleQuote: true, + jsxSingleQuote: true, +}; diff --git a/README.md b/README.md index 5c46ab6c..b6e22e2e 100644 --- a/README.md +++ b/README.md @@ -225,6 +225,7 @@ npm run i18n:lint | `npm run build` | Vite 生产构建,输出 `dist/` | | `npm run preview` | 预览构建结果,默认端口 4173 | | `npm run test` | 调用 `node --test` 执行现有测试 | +| `npm run check` | 依次执行 ESLint、测试和生产构建,任一步失败即停止 | | `npm run eslint` | JS / JSX 静态检查 | | `npm run eslint:fix` | 自动修复可修复的 ESLint 问题 | | `npm run lint` | Prettier 格式检查,并非 ESLint | @@ -237,10 +238,10 @@ npm run i18n:lint ### 当前交接注意点 -1. **格式化配置存在模块格式问题**:`.prettierrc.mjs` 使用了 `module.exports = require(...)`。按 Node ESM 加载会报 `require is not defined in ES module scope`;使用 Prettier 前需要将配置改为正确的 ESM 写法或调整为合适的 CommonJS 配置形式。本文未修改该配置。 +1. **格式化配置已统一**:`.prettierrc.mjs` 使用 ESM 导出,保留原有单引号规则;`.prettierignore` 排除构建产物与工具缓存。全仓仍有历史格式差异,修改时只格式化涉及的文件,不要为修复业务问题运行全仓 `lint:fix`。 2. **构建产物已忽略**:`dist/` 不提交,部署时使用 `npm run build` 生成。 3. **历史说明可能落后于代码**:部分子目录 README 仍写着 `web/src/...`,或把已经实现的功能描述成占位页。当前路径应去掉原来的 `web/` 前缀,行为以源码为准。原项目的后端、运维文档和部分注释引用的外部路径不在本仓库中。 -4. **npm 迁移验证**:干净安装、128 项测试及生产构建通过;静态检查和翻译存在历史问题,详见 [迁移验收记录](./docs/NPM_MIGRATION.md)。 +4. **验证记录**:维护性优化后,179 项测试和生产构建通过,ESLint 无错误但仍有 172 个历史警告,详见 [维护性优化报告](./docs/MAINTAINABILITY_REPORT.md)。 ## 7. 构建与部署 @@ -271,7 +272,7 @@ npm run preview | 云脑相关菜单找不到 | `VITE_CLOUD_BRAIN_UI_ENABLED`、后台模块开关和当前账号权限 | | 线上子页面刷新 404 | 静态服务器是否设置 SPA 回退,且接口路径没有误回退到 HTML | | 对话内容等到结束才一次性显示 | SSE 响应、反向代理缓冲和超时设置 | -| 格式检查报 `require` / `module` 未定义 | 上述 `.prettierrc.mjs` 模块格式问题 | +| 格式检查提示大量 Code style issues | 全仓仍有历史格式差异;保留统一配置,只格式化本次修改文件 | | 修改品牌后仍看到旧 Logo 或颜色 | 后端品牌设置、主题本地缓存以及 `config.js` / 静态资源缓存 | 首次联调建议依次确认:开发服务启动 → `/api/status` 正常 → 登录与 `/api/user/self` 正常 → 业务页面读取数据 → 选择已配置的测试模型验证对话。接口字段和业务权限问题需与后端负责人共同确认。 diff --git a/docs/MAINTAINABILITY_REPORT.md b/docs/MAINTAINABILITY_REPORT.md new file mode 100644 index 00000000..bed34ae8 --- /dev/null +++ b/docs/MAINTAINABILITY_REPORT.md @@ -0,0 +1,113 @@ +# 维护性优化报告 + +日期:2026-10-21 + +## 目标与边界 + +在保持现有页面、路由、接口和有效持久化数据兼容的前提下,提取重复规则、降低模块耦合、修复已确认的问题,并补充可执行回归测试。未升级依赖、迁移技术栈、调整 UI 或重写核心业务流程。 + +“无法优化”没有可客观证明的终点。本轮以已识别的低风险优化完成、相关测试与构建通过、独立复查未发现新增正确性问题为停止条件,不把缺少业务环境验证的重构视为安全优化。 + +## 已完成的改动 + +### 1. 通用存储解析与表格紧凑模式 + +- 新增 `src/helpers/storageJson.js`,统一处理 JSON 解析、数组/对象形状校验和存储读取失败;每次返回独立的默认容器,不共享可变状态。 +- 新增 `src/helpers/tableCompactMode.js`,将表格偏好从依赖 React/UI 的 `utils.jsx` 中分离,读取与跨标签页事件使用相同解析规则。 +- `utils.jsx` 保留原有导出,旧调用方无需迁移;存储键、每个表格的独立设置和有效值的真假判断保持兼容。 +- 紧凑模式写入失败仍为尽力保存,不阻止本页面切换。非法跨标签页值现在统一恢复为默认非紧凑模式,而不是保留过期状态。 + +### 2. 通知已读状态 + +- 新增 `src/helpers/notificationReadState.js`,集中公告标识、未读列表、已读合并和持久化规则。 +- `useNotifications` 的未读数量来自未读列表,避免两套独立筛选逻辑;稳定空公告数组和回调依赖,消除该处 Hooks 警告。 +- 保持“发布日期 + 内容前 30 字符”的既有公告标识、重复公告计数、已读历史和关闭通知的处理顺序。 +- 非法或非数组存储数据按未读处理;写入失败仍向上传播,不假装持久化成功。 + +### 3. 日志列偏好 + +- 新增 `src/helpers/columnVisibility.js`,由用量日志和任务日志共同使用,复用统一存储解析器。 +- 合并顺序为:当前默认列 → 已保存的合法布尔值 → 强制隐藏列。 +- 新增列获得默认值,显式 `false` 保留;未知列和非法字段值被忽略,非管理员不能通过本地偏好显示管理员专属列。 +- 保留两种日志各自的存储键、默认列、重置/全选行为和接口请求。 +- 未扩大为通用数据 Hook,避免把不同业务表格的请求与生命周期强行统一。 + +### 4. 企业用量筛选参数 + +- 新增 `src/helpers/orgLogFilters.js`,明细、汇总、排行复用用户、时间和模型筛选字段的接口映射。 +- 分页、排行数量和绕过缓存参数继续由具体接口管理,不混入共享筛选参数。 +- 保留原有空值/零值省略规则;没有修改请求代次控制、组织请求头或明细 `total=-1` 时保留已知总数的行为。 + +### 5. 用户管理分页与错误状态 + +- 修复修改每页条数时已将页面设为 1、却用旧页码发请求的问题;现在统一调用 `refresh(1, size)`。 +- 翻页、调整每页条数和刷新复用相同请求路径,保留当前表单筛选条件,不再在调整条数后丢失搜索。 +- 用户搜索通过 Axios `params` 编码,防止 `&`、`+`、`#` 等字符改变查询含义。 +- `loadUsers` / `searchUsers` 使用 `finally` 复位加载状态;翻页入口处理请求拒绝,避免一直显示加载或未处理的 Promise 拒绝。 +- 保留现有导出接口、首次请求的 page=0 约定及空筛选回退行为。 +- 浏览器验收发现 Semi 调整每页条数后还会自动触发页码回调,从第 3 页的 10 条改为 20 条时,会额外请求第 2 页的旧 10 条,覆盖正确结果。已在通用分页工厂增加默认关闭的 `preventPageChangeOnPageSizeChange` 选项,仅用户列表启用;由用户列表的条数处理函数负责重置第 1 页,其他表格行为不变。 + +### 6. 开发检查工具 + +- 将 `.prettierrc.mjs` 改为有效的 ESM,删除 `package.json` 中重复的 Prettier 配置,并保留原先实际生效的单引号选项。原先 package.json 配置优先命中,掩盖了 `.mjs` 的加载错误。 +- 新增 `.prettierignore`,排除构建产物、覆盖率和工具缓存,不屏蔽业务源码的历史格式问题。 +- 补齐 `public/config.js` 和两个既有测试文件的标准许可证头,清除 3 个 ESLint 错误,不禁用规则。 +- 修复 `scripts/translated_ja.json` 缺少结束括号导致的 JSON 语法错误,没有修改翻译内容或补造缺失翻译。 +- 新增 `npm run check`,依次执行 ESLint、测试和生产构建;任一步失败即停止。该命令不代表全仓格式检查、浏览器测试或类型检查通过。 +- 同步 README 和项目分析中的过期说明;依赖清单版本及锁文件保持不变。 + +## 验证结果 + +环境:Windows 10 / Git Bash,Node.js 22.23.3,npm 10.9.9。 + +| 检查 | 优化前 | 优化后 | +| --------------------------------- | ---------------------------------------- | ------------------------------------------- | +| `npm test` | 128 通过,0 失败 | 179 通过,0 失败;新增 51 项 | +| `npm run eslint` | 3 错误,173 警告;退出 1 | 0 错误,172 警告;退出 0 | +| `npm run build` | 通过,有大 chunk 告警 | 通过,仍有大 chunk 告警 | +| `npm run check` | 无统一入口 | 通过,包含上述三项 | +| `npm run lint` | 因 JSON 语法错误退出 2,另有历史格式差异 | 不再有解析/配置错误;仍因历史格式差异退出 1 | +| 已修改的 JS/JSX/MJS/JSON 格式检查 | — | 通过 | +| 仓库已跟踪及非忽略的 JSON 解析 | — | 33 个文件全部可解析 | +| `git diff --check` | — | 通过 | +| 独立 code review | — | 未发现本次改动新增的正确性问题 | + +新增测试分布: + +- `src/helpers/storageJson.test.js`:18 项,覆盖存储异常、通知标识/合并、紧凑模式独立设置和失败策略。 +- `src/helpers/columnVisibility.test.js`:12 项,覆盖默认值合并、非法值、角色限制及输入不变性。 +- `src/helpers/orgLogFilters.test.js`:4 项,覆盖字段映射、省略规则、端点隔离和输入不变性。 +- `src/hooks/users/useUsersData.test.js`:13 项,执行真实 Hook 导出的分页/搜索处理函数,并使用 Axios 实际序列化逻辑验证参数;React 状态与 effect 通过轻量测试替身驱动。 + +- `tests/users-pagination.test.js`:4 项,执行已安装 Semi 的真实分页 foundation,验证用户列表接线、桌面/移动端调整条数只触发一次回调、后续翻页可用,以及其他表格的默认行为保持不变。 + +上述 Node 测试不模拟完整 React 调度、StrictMode、DOM 或后端权限,不能替代浏览器和真实后端验收。 + +生产构建的 `/`、`/login`、`/org/login`、`/console/user`、`/config.js` 已通过 HTTP 冒烟:均返回 200,HTML 有 React root 和可访问的生产入口 JS。 + +### 提交前浏览器验收 + +使用 Chrome 155.0.8059.85 headless、独立浏览器上下文和生产预览的随机本地端口;桌面视口 1440×900,移动视口 390×844,DPR=1,语言 zh-CN。Playwright 工具安装在系统临时目录,不改项目依赖或锁文件。所有业务 API 由本地 fixture 拦截,外部请求阻断,没有接触真实用户会话或执行后端写入。 + +以下场景通过真实点击、输入和网络请求观察验收: + +1. 用户管理页加载,已查看桌面及移动端截图,列表和操作区正常渲染。 +2. 搜索 `alice & bob+#?=user`,翻到第 3 页后改为每页 20 条:只发出一次第 1 页、20 条的请求,搜索参数完整保留,显示 20 行。修复前实际复现了旧条数的第二次请求;修复后通过。 +3. 两个标签页之间双向切换紧凑模式,当前页立即更新,另一页通过真实 storage 事件同步。 +4. 非数组的通知已读存储可恢复,打开通知并点击“我知道了”后写入兼容格式的已读键。 +5. 移动端列表可见,点击“显示操作项”后可操作搜索控件。 +6. 分页接口主动返回 HTTP 503 后加载状态复位;恢复接口后点击查询成功。未出现未处理的 Promise 拒绝。 + +最终浏览器复验没有 pageerror 或非预期 console error;主动注入的 503 产生预期网络/Axios 错误日志。最初调试中的选择器不匹配、缺少 fixture 字段已在测试脚本中修正,没有为测试修改业务返回值。真实登录、权限与线上后端仍未验收。 + +本地浏览器验收脚本、结果和截图位于系统临时目录 `monkey-ai-acceptance-A0u9pq`,不纳入应用产物;防回归的 4 项 Semi 分页测试已纳入仓库。按用户要求删除不再保留的 npm 迁移和性能历史报告,并清理其失效引用。 + +## 保留的风险与后续工作 + +- 172 个历史 ESLint 警告仍需按具体场景处理。没有批量补 effect 依赖、禁用规则或修改告警级别,避免引入重复请求与循环渲染。 +- 全仓仍有数百个文件的历史格式差异。仅格式化涉及的代码,不用大面积格式变动掩盖业务差异。 +- 大 chunk 告警仍在;拆包、图标和可视化依赖优化需要浏览器加载与缓存证据,不能凭构建耗时宣称页面性能提升。 +- 真实登录、企业切换、后端权限及业务接口仍需在可用测试环境验收;本地 fixture 浏览器结果不代表真实后端联调通过。 +- 本轮没有实施全局异步请求竞态治理、统一所有数据 Hook、依赖升级或大型页面拆分。这些改变影响范围较大,需要明确业务契约和更完整的集成测试。 + +建议日常运行 `npm run check`;涉及页面改动时同时验证浏览器场景,对本次编辑的文件执行 `npx prettier <文件列表> --check`。不要将这份报告理解为整个项目已无缺陷或不存在进一步优化空间。 diff --git a/docs/NPM_MIGRATION.md b/docs/NPM_MIGRATION.md deleted file mode 100644 index f98eaa93..00000000 --- a/docs/NPM_MIGRATION.md +++ /dev/null @@ -1,34 +0,0 @@ -# npm 依赖迁移验收记录 - -日期:2026-10-21 - -## 迁移内容 - -- 以当前 `package.json` 为准,保留并纳入版本管理 `package-lock.json`(lockfileVersion 3)。 -- 删除与当前清单不一致的 Bun 锁文件 `bun.lock`。 -- 将 ESLint 和 i18next CLI 脚本从 `bunx` 改为直接调用项目本地命令,npm scripts 会自动使用 `node_modules/.bin`。 -- 在 `package.json` 增加 Node.js `>=22.13.0`、npm `>=10` 的 `engines`,并记录 `packageManager: npm@10.9.9`。 -- 从 `.gitignore` 移除 `package-lock.json`,避免 npm 锁文件再次被忽略。 -- 同步更新 README 和项目分析文档中的包管理、安装、命令及验证说明。 - -## 已执行验证 - -| 检查 | 结果 | -| --- | --- | -| `npm install --package-lock-only --ignore-scripts --no-audit --no-fund` | 通过 | -| `npm ci --no-audit --no-fund` | 通过;干净安装 1200 个包 | -| `npm test` | 通过;128 项通过,0 项失败 | -| `npm run build` | 通过;Vite 生产构建完成 | -| `npm ls --depth=0` | 通过;无顶层依赖缺失或无效 | -| `npm run i18n:status` | 命令可执行,但项目既有翻译未完成状态导致退出码 1 | -| `npm run eslint` | 命令可执行,但项目既有 3 个版权头错误和 173 个 Hooks 警告 | -| `npm run lint` | 命令可执行,但项目既有 `scripts/translated_ja.json` JSON/编码错误 | -| 生产预览 HTTP 冒烟 | `/`、`/org/login` 返回 200,`/config.js` 返回 JavaScript | -| Chrome headless 页面冒烟 | `/org/login` 的 React root 已挂载,DOM 出现 Semi 布局和输入控件;未进行完整页面交互或浏览器控制台错误采集 | -| `npm audit` | npm 镜像未实现 audit endpoint,返回 404;不是本次代码变更引入的漏洞结论 | - -## 验收边界 - -依赖迁移、Node 测试、生产构建和静态资源预览已验证。真实登录、后端接口、模型调用、SSE、企业权限和线上网关仍需要可用后端、测试账号及部署环境,不能仅凭本地构建代替业务验收。 - -干净安装曾因正在运行的 Vite/esbuild 进程占用 Windows 原生依赖文件而首次失败;停止占用进程后,`npm ci` 已成功完成。生产构建产生的 `dist/` 已被 `.gitignore` 忽略。 diff --git a/docs/PERFORMANCE_REPORT.md b/docs/PERFORMANCE_REPORT.md deleted file mode 100644 index 618d3431..00000000 --- a/docs/PERFORMANCE_REPORT.md +++ /dev/null @@ -1,228 +0,0 @@ -# 前端性能优化报告 - Weelink Monkey AI - -## ✅ 已完成的性能优化 (2026-02-12 更新) - -### 🎉 主要成就 - -#### 1. **react-icons (83MB) - ✅ 已完全移除** - -- **优化方案**: 创建自定义内联 SVG 图标组件 ([BrandIcons.jsx](src/components/common/icons/BrandIcons.jsx)) -- **替换的文件**: 全部7个文件已完成替换 - - ✅ `components/settings/personal/sections/AccountBindingSection.jsx` - - ✅ `components/topup/modals/PaymentConfirmModal.jsx` - - ✅ `pages/Recharge/RechargePanel.jsx` - - ✅ `components/topup/RechargeCard.jsx` - - ✅ `components/table/channels/ChannelsColumnDefs.jsx` - - ✅ `components/settings/personal/cards/AccountManagement.jsx` - - ✅ `components/settings/personal/modals/WeChatBindModal.jsx` -- **从 package.json 移除**: ✅ 完成 -- **节省空间**: **~83MB → 0MB** (100% 优化) -- **实际效果**: 构建产物减少约 2-3MB (gzip后) - -#### 2. **@lobehub/icons - 保留使用** - -- **使用文件**: 2个 - - `pages/Home/index.jsx` - - `helpers/render.jsx` -- **原因**: 这些是 AI 模型品牌图标(OpenAI, Claude, Gemini等),是项目核心功能 -- **优化**: 通过 tree-shaking 和具名导入已优化加载 -- **实际打包**: ~5MB → ~500KB (通过 tree-shaking) - -### 🟡 现有依赖(已优化) - -#### 3. **lucide-react** - -- **状态**: ✅ 正在使用,已通过 tree-shaking 优化 -- **导入方式**: 具名导入确保仅打包使用的图标 -- **用途**: 通用 UI 图标 (替代了大部分 react-icons) -- **实际打包**: ~40MB → ~50-100KB (通过 tree-shaking) - -#### 4. **mermaid (图表库)** - -- **状态**: ✅ 已懒加载 -- **文件**: `components/common/markdown/MarkdownRenderer.jsx` -- **优化**: 仅在需要时动态加载 - -#### 5. **katex (数学公式渲染)** - -- **状态**: ✅ 已通过 Vite chunk 分离 -- **优化**: 独立chunk,按需加载 - -#### 6. **@visactor (图表可视化)** - -- **状态**: ✅ 已通过 Vite chunk 分离 -- **包含**: react-vchart, vchart, vchart-semi-theme -- **优化**: 独立chunk,按需加载 - -### 🎯 新增优化项 - -✅ **Vite 构建配置优化** - -- 启用 esbuild 压缩 -- 移除生产环境的 console 和 debugger -- 优化 tree-shaking 配置 -- 细粒度的代码分割 (12+ chunks) -- Target ES2015 减少polyfill - -✅ **已完成的优化项目** - -- Google Fonts 依赖已移除 -- Telegram 登录组件已懒加载 -- MapleBackground 动画已优化 -- 首屏 loading 动画已优化 -- Mermaid 已懒加载 -- **react-icons 已完全移除** ⭐ NEW - ---- - -## 📊 优化前后对比 - -| 库名 | 优化前 | 优化后 | 节省 | 状态 | -| -------------- | ---------- | --------------------- | ----------- | ------------- | -| react-icons | 83MB | 0MB | **-83MB** | ✅ **已移除** | -| lucide-react | 40MB | ~100KB (tree-shaking) | **-39.9MB** | ✅ **已优化** | -| @lobehub/icons | 5MB | ~500KB (tree-shaking) | **-4.5MB** | ✅ **已优化** | -| @visactor | 10MB | 按需加载(独立chunk) | **懒加载** | ✅ **已优化** | -| mermaid | 3MB | 按需加载(独立chunk) | **懒加载** | ✅ **已优化** | -| katex | 2MB | 按需加载(独立chunk) | **懒加载** | ✅ **已优化** | -| **依赖总计** | **~143MB** | **~600KB + 懒加载** | **~99% ⬇️** | ✅ **完成** | - ---- - -## 🎯 优化技术细节 - -### ✅ 已实施的优化 - -1. **移除 react-icons (83MB)** - - 创建自定义 SVG 组件库 `BrandIcons.jsx` - - 包含品牌图标: Wechat, Alipay, Stripe, Telegram, Discord, Linux, Shuffle - - 所有7个文件已完成迁移 - - 从 package.json 移除依赖 - -2. **优化图标库使用** - - lucide-react: 使用具名导入 ✅ - - @lobehub/icons: 保留(AI模型图标必需) ✅ - - 自定义SVG: 零依赖,体积最小 ✅ - -3. **Vite 构建优化** - - ```javascript - // 压缩配置 - - esbuild 压缩 (速度+体积优化) - - 移除 console/debugger - - tree-shaking 优化 - - // 代码分割 (12+ chunks) - - react-core - - semi-ui / semi-icons - - vchart (图表) - - mermaid (流程图) - - markdown / katex - - lobe-icons / lucide-icons - - i18n / utils - - react-components - ``` - -### 📋 下一步可选优化 - -1. **CDN 加速 (可选)** - - 考虑使用国内CDN加速 Semi UI - - 使用CDN加速大型依赖(mermaid, vchart) - -2. **图片优化 (可选)** - - WebP 格式转换 - - 图片懒加载 - - 响应式图片 - ---- - -## 🚀 实际优化效果 - -### 打包体积对比 - -| 指标 | 优化前 | 优化后 | 提升 | -| --------------------- | ------ | ------- | ------------- | -| 初始JS依赖 | ~143MB | ~10MB\* | **93%** ⬇️ | -| 主chunk (预估) | ~2.5MB | ~800KB | **68%** ⬇️ | -| gzip 后 (预估) | ~8MB | ~2-3MB | **62-75%** ⬇️ | -| 首屏加载时间 (中国4G) | 4-8秒 | 1.5-3秒 | **50-75%** ⬇️ | - -\*通过 tree-shaking + 代码分割 + 懒加载实现 - -### 📈 预期用户体验提升 - -| 场景 | 优化前 | 优化后 | 改善 | -| ------------- | --------- | ----------- | ---------- | -| 🇨🇳 中国4G网络 | 6-8秒白屏 | 2-3秒可交互 | ⭐⭐⭐⭐⭐ | -| 🌐 国际网络 | 3-5秒 | 1-2秒 | ⭐⭐⭐⭐ | -| 📱 移动端 | 较慢 | 流畅 | ⭐⭐⭐⭐⭐ | -| 🔄 页面切换 | 卡顿 | 即时响应 | ⭐⭐⭐⭐⭐ | - ---- - -## ✅ 优化完成清单 - -### 🎉 已完成 (2026-02-12) - -- [x] 移除 react-icons (83MB → 0MB) - - [x] 创建自定义 SVG 图标组件 - - [x] 替换所有7个使用文件 - - [x] 从 package.json 移除 -- [x] 优化 Vite 构建配置 - - [x] 启用 esbuild 压缩 - - [x] 优化 tree-shaking - - [x] 细粒度代码分割 (12+ chunks) - - [x] 移除生产环境 console -- [x] 懒加载大型依赖 - - [x] Telegram 登录组件 - - [x] Mermaid 图表 - - [x] @visactor 图表库 - - [x] katex 数学公式 -- [x] 优化图标库 - - [x] lucide-react 具名导入 - - [x] @lobehub/icons tree-shaking - -### 📋 可选后续优化 - -- [ ] 配置 CDN 加速(Semi UI, 大型依赖) -- [ ] 图片优化 (WebP, 懒加载) -- [ ] 启用 Brotli 压缩 -- [ ] 添加性能监控 - -### 🧪 验证步骤 - -运行以下命令验证优化效果: - -```bash -cd web -npm install # 安装依赖(已移除 react-icons) -npm run build # 构建生产版本 -``` - -查看构建产物: - -```bash -ls -lh dist/assets/ # 查看打包后的文件大小 -``` - ---- - -## 📝 变更记录 - -**2026-02-12 (本次优化)** - -- ✅ 完全移除 react-icons (83MB) -- ✅ 创建自定义品牌图标组件 -- ✅ 优化 Vite 构建配置 -- ✅ 实现细粒度代码分割 -- ✅ 优化图标库 tree-shaking - -**预期收益**: - -- 依赖体积减少 ~93% -- 首屏加载时间减少 50-75% -- 中国用户体验显著提升 - ---- - -最后更新: 2026-02-12 diff --git a/docs/PROJECT_ANALYSIS.zh-CN.md b/docs/PROJECT_ANALYSIS.zh-CN.md index 5f2d0226..059ea61f 100644 --- a/docs/PROJECT_ANALYSIS.zh-CN.md +++ b/docs/PROJECT_ANALYSIS.zh-CN.md @@ -121,7 +121,7 @@ Monkey AI Web 是一个面向 AI 服务的 Web 前端,覆盖个人使用、企 ## 2. 技术栈:使用什么,分别解决什么问题 -下表列出 package.json 中声明的主要版本;精确安装版本以 package-lock.json 为准。项目已统一 npm,迁移验证及限制见 [npm 迁移验收记录](./NPM_MIGRATION.md)。 +下表列出 package.json 中声明的主要版本;精确安装版本以 package-lock.json 为准。项目统一使用 npm,当前验证结果见 [维护性优化报告](./MAINTAINABILITY_REPORT.md)。 | 领域 | 技术与声明版本 | 在项目中的作用 | | --- | --- | --- | @@ -386,7 +386,7 @@ npm run i18n:lint - 语言包按需加载,普通 GET 请求具有进行中请求去重。 - 全局有 Chunk 加载失败识别、有限重载和错误边界,处理部署更新后旧页面引用过期资源的情况。 -顶层懒加载不等于所有子页面都独立拆包;例如企业入口仍有多个静态导入。`PERFORMANCE_REPORT.md` 可以作为历史参考,其中的体积收益不能当作当前版本的实测结果。修改性能时应基于本次构建产物和浏览器数据判断。 +顶层懒加载不等于所有子页面都独立拆包;例如企业入口仍有多个静态导入。修改性能时应基于本次构建产物和浏览器数据判断,不把历史估算当作当前版本的实测结果。 ## 7. 快速搭建本地开发环境 @@ -557,11 +557,11 @@ npm run preview ## 11. 当前已确认的工程注意点 -以下事项来自本次代码检查或实际命令结果,便于接手时安排处理优先级。本次仅修订分析文档,没有修改这些配置。 +以下事项来自代码检查或实际命令结果,便于接手时安排处理优先级。后续优化结果见 [维护性优化报告](./MAINTAINABILITY_REPORT.md)。 | 事项 | 当前证据 | 对开发的影响与建议 | | --- | --- | --- | -| Prettier 配置无法按 ESM 正常加载 | `.prettierrc.mjs` 使用 `module.exports = require(...)`;Node 导入已复现 `require is not defined in ES module scope` | 运行格式检查前需统一为正确的 ESM 或 CJS 配置,避免格式检查成为阻塞项 | +| Prettier 配置已统一 | `.prettierrc.mjs` 使用 ESM 导出,移除 package.json 的重复配置;忽略构建产物和缓存 | 全仓仍有历史格式差异,按改动范围渐进处理,不做无关全仓格式化 | | 构建目录已被忽略 | `.gitignore` 包含 `/dist/`、`/dist-ssr/` 和 `/build` | 原文“dist 未忽略”已过时;提交前仍检查 Git 状态 | | 压缩选项位置需要复核 | `drop: ['console', 'debugger']` 写在 `build.esbuild` 中 | Vite 5 的 `esbuild` 通常是顶层配置;不能仅凭此处注释确认日志已被移除,应调整并检查产物。本次未构建验证 | | 开发代理已集中配置 | `vite.config.js` 的 `DEV_PROXY_TARGET` 统一供多个前缀使用,当前指向远程后端 | 仍是源码常量,不是代理环境变量;切换后重启开发服务 | @@ -578,11 +578,11 @@ npm run preview | --- | --- | | 源码与配置分析 | 已检查依赖、入口、路由、请求、状态、企业权限、对话、国际化、主题及检查规则 | | Node 环境 | `v22.23.3` | -| 现有测试 `node --test` | 128 项通过,0 项失败;包含之前因缺少 postcss 而加载失败的两个测试文件 | -| Prettier 配置导入 | 已复现 ESM 加载错误 | -| npm 迁移验证 | npm ci、128 项测试和生产构建通过;静态检查及真实业务验收限制见 NPM_MIGRATION.md | +| 现有测试 `node --test` | 优化与验收修复后 179 项通过,0 项失败;包含偏好解析、筛选参数、用户列表控制器和 Semi 分页回调回归测试 | +| Prettier 配置导入 | ESM 配置已修复;格式检查可执行,但全仓历史格式差异仍未统一 | +| 浏览器验收 | Chrome 隔离环境下的分页、搜索、通知、跨标签页同步、移动端和错误恢复通过;接口使用测试 fixture,不代表真实后端验收 | -Node 测试和生产构建通过不等于后端业务或线上发布验收通过;具体结果与未通过项见 [npm 迁移验收记录](./NPM_MIGRATION.md)。 +Node 测试和生产构建通过不等于后端业务或线上发布验收通过;具体结果与验证边界见 [维护性优化报告](./MAINTAINABILITY_REPORT.md)。 ## 12. 常见问题排查表 @@ -598,7 +598,7 @@ Node 测试和生产构建通过不等于后端业务或线上发布验收通过 | 流式回复在结束时一次性出现 | 检查 SSE 事件、网关缓冲、超时和后端输出方式 | | 线上刷新子页面 404 | 检查静态服务器的 SPA 路由回退 | | 模块资源加载失败 | 检查旧 HTML 与新资源是否版本不一致,确认发布和缓存策略 | -| `lint` 报 `require` 未定义 | 检查 `.prettierrc.mjs` 的 ESM/CJS 配置冲突 | +| `lint` 报 Code style issues | 历史格式差异仍存在,只格式化本次改动文件;当前 ESM 配置已修复 | | 测试报找不到 `postcss` | 先按锁文件安装依赖,再重跑对应测试 | ## 13. 建议的新成员学习路径 diff --git a/package.json b/package.json index 51b8a590..428d7122 100644 --- a/package.json +++ b/package.json @@ -55,6 +55,7 @@ "test": "node --test", "lint": "prettier . --check", "lint:fix": "prettier . --write", + "check": "npm run eslint && npm test && npm run build", "eslint": "eslint \"**/*.{js,jsx}\" --cache", "eslint:fix": "eslint \"**/*.{js,jsx}\" --fix --cache", "preview": "vite preview", @@ -91,10 +92,6 @@ "tailwindcss": "^3", "vite": "5.1.0" }, - "prettier": { - "singleQuote": true, - "jsxSingleQuote": true - }, "proxy": "http://localhost:3000", "engines": { "node": ">=22.13.0", diff --git a/public/config.js b/public/config.js index d3524ffc..9cd11d0d 100644 --- a/public/config.js +++ b/public/config.js @@ -1,3 +1,22 @@ +/* +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 +*/ + // Runtime configuration - modify per deployment environment. // Monolith mode: leave SERVER_URL empty. // Separated mode: set to backend URL, e.g. 'https://api.example.com' diff --git a/scripts/translated_ja.json b/scripts/translated_ja.json index 8d7f26ae..1d1aaced 100644 --- a/scripts/translated_ja.json +++ b/scripts/translated_ja.json @@ -496,4 +496,5 @@ "更多操作": "その他の操作", "自定义对话参数": "対話パラメータをカスタマイズ", "选择 AI 模型": "AI モデルを選択", - "实时显示AI回复内容": "AIの返信内容をリアルタイム表示" \ No newline at end of file + "实时显示AI回复内容": "AIの返信内容をリアルタイム表示" +} diff --git a/src/components/table/users/index.jsx b/src/components/table/users/index.jsx index 59e12a4e..86165f78 100644 --- a/src/components/table/users/index.jsx +++ b/src/components/table/users/index.jsx @@ -110,6 +110,8 @@ const UsersPage = () => { total: usersData.userCount, onPageChange: usersData.handlePageChange, onPageSizeChange: usersData.handlePageSizeChange, + // The size handler resets to page 1; skip Semi's automatic page callback. + preventPageChangeOnPageSizeChange: true, isMobile: isMobile, t: usersData.t, })} diff --git a/src/helpers/columnVisibility.js b/src/helpers/columnVisibility.js new file mode 100644 index 00000000..0e59a023 --- /dev/null +++ b/src/helpers/columnVisibility.js @@ -0,0 +1,46 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +import { parseStoredObject } from './storageJson.js'; + +// Resolve raw localStorage JSON without mutating defaults or performing I/O. +export const resolveColumnVisibility = ( + defaults, + savedColumns, + hiddenKeys = [], +) => { + const resolved = { ...defaults }; + const preferences = parseStoredObject(savedColumns); + + for (const key of Object.keys(defaults)) { + if ( + Object.prototype.hasOwnProperty.call(preferences, key) && + typeof preferences[key] === 'boolean' + ) { + resolved[key] = preferences[key]; + } + } + + // Role restrictions take precedence over saved preferences. + for (const key of hiddenKeys) { + resolved[key] = false; + } + + return resolved; +}; diff --git a/src/helpers/columnVisibility.test.js b/src/helpers/columnVisibility.test.js new file mode 100644 index 00000000..91a7dafd --- /dev/null +++ b/src/helpers/columnVisibility.test.js @@ -0,0 +1,149 @@ +/* +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 test from 'node:test'; +import assert from 'node:assert/strict'; +import { resolveColumnVisibility } from './columnVisibility.js'; + +const defaults = Object.freeze({ time: true, model: true, channel: false }); + +test('missing or malformed saved JSON falls back to a fresh copy of defaults', () => { + for (const saved of [ + undefined, + null, + '', + '{', + 'not-json', + '{"time":false,}', + ]) { + const resolved = resolveColumnVisibility(defaults, saved); + assert.deepEqual(resolved, defaults); + assert.notStrictEqual(resolved, defaults); + } +}); + +test('null, arrays, and primitive JSON values are not preference maps', () => { + for (const saved of [ + 'null', + '[]', + '[false]', + '"text"', + '0', + 'true', + 'false', + ]) { + assert.deepEqual(resolveColumnVisibility(defaults, saved), defaults); + } +}); + +test('non-string saved data is ignored without coercion or mutation', () => { + const saved = Object.freeze({ time: false }); + for (const value of [saved, [false], 1, true]) { + assert.deepEqual(resolveColumnVisibility(defaults, value), defaults); + } + assert.deepEqual(saved, { time: false }); +}); + +test('saved false and true values override defaults while new columns keep defaults', () => { + assert.deepEqual( + resolveColumnVisibility(defaults, '{"time":false,"channel":true}'), + { time: false, model: true, channel: true }, + ); + assert.deepEqual(resolveColumnVisibility(defaults, '{}'), defaults); +}); + +test('invalid individual preferences keep defaults without discarding valid booleans', () => { + for (const value of [null, 0, 1, '', 'false', [], {}]) { + assert.deepEqual( + resolveColumnVisibility( + defaults, + JSON.stringify({ time: value, channel: value, model: false }), + ), + { time: true, model: false, channel: false }, + ); + } +}); + +test('unknown and prototype-related saved keys do not enter the result', () => { + const resolved = resolveColumnVisibility( + defaults, + '{"time":false,"removedColumn":true,"__proto__":{"polluted":true},"constructor":false,"toString":false}', + ); + assert.deepEqual(resolved, { time: false, model: true, channel: false }); + assert.equal(Object.getPrototypeOf(resolved), Object.prototype); + assert.equal(Object.hasOwn(resolved, '__proto__'), false); +}); + +for (const [table, restrictedKeys] of [ + ['usage logs', ['channel', 'username', 'retry']], + ['task logs', ['channel']], +]) { + for (const isAdmin of [true, false]) { + test(`${table}: ${isAdmin ? 'admin' : 'non-admin'} preferences respect role restrictions`, () => { + const roleDefaults = { + model: true, + ...Object.fromEntries(restrictedKeys.map((key) => [key, isAdmin])), + }; + const hiddenKeys = isAdmin ? [] : restrictedKeys; + for (const checked of [true, false]) { + const preferences = { + model: false, + ...Object.fromEntries(restrictedKeys.map((key) => [key, checked])), + }; + const resolved = resolveColumnVisibility( + roleDefaults, + JSON.stringify(preferences), + hiddenKeys, + ); + assert.equal(resolved.model, false); + for (const key of restrictedKeys) { + assert.equal(resolved[key], isAdmin && checked); + } + } + assert.deepEqual( + resolveColumnVisibility(roleDefaults, null, hiddenKeys), + roleDefaults, + ); + }); + } +} + +test('forced-hidden keys apply even when saved preferences are missing or invalid', () => { + for (const saved of [null, '{', 'null', '[]', '{}', '{"time":true}']) { + assert.deepEqual(resolveColumnVisibility(defaults, saved, ['time']), { + time: false, + model: true, + channel: false, + }); + } +}); + +test('resolution never mutates defaults or hidden keys and returns independent results', () => { + const hiddenKeys = Object.freeze(['channel']); + const saved = '{"time":false,"channel":true}'; + const first = resolveColumnVisibility(defaults, saved, hiddenKeys); + const second = resolveColumnVisibility(defaults, saved, hiddenKeys); + + assert.notStrictEqual(first, second); + first.model = false; + assert.deepEqual(second, { time: false, model: true, channel: false }); + assert.deepEqual(defaults, { time: true, model: true, channel: false }); + assert.deepEqual(hiddenKeys, ['channel']); + assert.equal(saved, '{"time":false,"channel":true}'); +}); diff --git a/src/helpers/notificationReadState.js b/src/helpers/notificationReadState.js new file mode 100644 index 00000000..8c89632a --- /dev/null +++ b/src/helpers/notificationReadState.js @@ -0,0 +1,51 @@ +/* +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 { parseStoredArray, readStorageValue } from './storageJson.js'; + +export const NOTICE_READ_KEYS_KEY = 'notice_read_keys'; + +export const getAnnouncementKey = (announcement) => + `${announcement?.publishDate || ''}-${(announcement?.content || '').slice(0, 30)}`; + +export function getUnreadAnnouncementKeys(announcements, readKeys) { + const readSet = new Set(readKeys); + return announcements + .map(getAnnouncementKey) + .filter((key) => !readSet.has(key)); +} + +export function mergeAnnouncementReadKeys(announcements, readKeys) { + return Array.from( + new Set([...readKeys, ...announcements.map(getAnnouncementKey)]), + ); +} + +export function readNoticeReadKeys() { + return parseStoredArray(readStorageValue(NOTICE_READ_KEYS_KEY)); +} + +export function markAnnouncementsRead(announcements) { + const mergedKeys = mergeAnnouncementReadKeys( + announcements, + readNoticeReadKeys(), + ); + // Let write failures propagate so callers do not report unread items as saved. + localStorage.setItem(NOTICE_READ_KEYS_KEY, JSON.stringify(mergedKeys)); +} diff --git a/src/helpers/orgLogFilters.js b/src/helpers/orgLogFilters.js new file mode 100644 index 00000000..e4b6df05 --- /dev/null +++ b/src/helpers/orgLogFilters.js @@ -0,0 +1,34 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +/** Map the shared consumption filters without adding endpoint-specific options. */ +export function buildOrgLogFilters({ + userId, + startTimestamp, + endTimestamp, + modelName, +} = {}) { + const params = {}; + // Preserve the API callers' existing omission of empty values (including zero). + if (userId) params.user_id = userId; + if (startTimestamp) params.start_timestamp = startTimestamp; + if (endTimestamp) params.end_timestamp = endTimestamp; + if (modelName) params.model_name = modelName; + return params; +} diff --git a/src/helpers/orgLogFilters.test.js b/src/helpers/orgLogFilters.test.js new file mode 100644 index 00000000..aec5d428 --- /dev/null +++ b/src/helpers/orgLogFilters.test.js @@ -0,0 +1,75 @@ +/* +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 assert from 'node:assert/strict'; +import test from 'node:test'; +import { buildOrgLogFilters } from './orgLogFilters.js'; + +test('consumption filters map to the existing API field names', () => { + const filters = Object.freeze({ + userId: 42, + startTimestamp: 1700000000, + endTimestamp: 1700003600, + modelName: 'example/model + preview', + }); + assert.deepEqual(buildOrgLogFilters(filters), { + user_id: 42, + start_timestamp: 1700000000, + end_timestamp: 1700003600, + model_name: 'example/model + preview', + }); +}); + +test('empty filters and existing falsy values are omitted', () => { + assert.deepEqual(buildOrgLogFilters(), {}); + for (const value of [undefined, null, '', 0, false, NaN]) { + assert.deepEqual( + buildOrgLogFilters({ + userId: value, + startTimestamp: value, + endTimestamp: value, + modelName: value, + }), + {}, + ); + } +}); + +test('partial filters preserve values without coercion', () => { + assert.deepEqual(buildOrgLogFilters({ userId: '0', modelName: 'a&b' }), { + user_id: '0', + model_name: 'a&b', + }); +}); + +test('endpoint-specific parameters cannot leak into shared filters', () => { + const filters = Object.freeze({ + userId: 42, + limit: 10, + nocache: 1, + p: 5, + page_size: 20, + memberId: 7, + }); + const params = buildOrgLogFilters(filters); + assert.deepEqual(params, { user_id: 42 }); + params.limit = 15; + assert.deepEqual(buildOrgLogFilters(filters), { user_id: 42 }); + assert.equal(filters.limit, 10); +}); diff --git a/src/helpers/storageJson.js b/src/helpers/storageJson.js new file mode 100644 index 00000000..ed5f269f --- /dev/null +++ b/src/helpers/storageJson.js @@ -0,0 +1,49 @@ +/* +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 +*/ + +function parseStoredJson(json, isValid, fallback) { + if (typeof json !== 'string') return fallback; + try { + const value = JSON.parse(json); + return isValid(value) ? value : fallback; + } catch { + return fallback; + } +} + +export function parseStoredArray(json) { + return parseStoredJson(json, Array.isArray, []); +} + +export function parseStoredObject(json) { + return parseStoredJson( + json, + (value) => + value !== null && typeof value === 'object' && !Array.isArray(value), + {}, + ); +} + +export function readStorageValue(key) { + try { + return localStorage.getItem(key); + } catch { + return null; + } +} diff --git a/src/helpers/storageJson.test.js b/src/helpers/storageJson.test.js new file mode 100644 index 00000000..d0e7e732 --- /dev/null +++ b/src/helpers/storageJson.test.js @@ -0,0 +1,300 @@ +/* +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 test from 'node:test'; +import assert from 'node:assert/strict'; +import { + parseStoredArray, + parseStoredObject, + readStorageValue, +} from './storageJson.js'; + +import { + getAnnouncementKey, + getUnreadAnnouncementKeys, + markAnnouncementsRead, + mergeAnnouncementReadKeys, + NOTICE_READ_KEYS_KEY, + readNoticeReadKeys, +} from './notificationReadState.js'; +import { + getTableCompactMode, + parseTableCompactMode, + setTableCompactMode, +} from './tableCompactMode.js'; +import { TABLE_COMPACT_MODES_KEY } from '../constants/common.constant.js'; + +function mockStorage(t, storage) { + const descriptor = Object.getOwnPropertyDescriptor( + globalThis, + 'localStorage', + ); + Object.defineProperty(globalThis, 'localStorage', { + configurable: true, + value: storage, + }); + t.after(() => { + if (descriptor) { + Object.defineProperty(globalThis, 'localStorage', descriptor); + } else { + delete globalThis.localStorage; + } + }); +} + +const invalidJson = [ + null, + undefined, + '', + '{broken', + 'null', + 'true', + '42', + '"text"', +]; + +test('stored arrays reject malformed JSON and non-array values', () => { + for (const json of [...invalidJson, '{}', '{"0":"notice"}']) { + assert.deepEqual(parseStoredArray(json), [], String(json)); + } +}); + +test('stored objects reject malformed JSON and non-object values', () => { + for (const json of [...invalidJson, '[]', '[true]']) { + assert.deepEqual(parseStoredObject(json), {}, String(json)); + } +}); + +test('valid stored containers keep their values without coercion or filtering', () => { + const array = ['notice', 'notice', null, 1]; + const object = { global: true, tokens: false, other: 'yes' }; + assert.deepEqual(parseStoredArray(JSON.stringify(array)), array); + assert.deepEqual(parseStoredObject(JSON.stringify(object)), object); +}); + +test('fallback containers are fresh for each parse', () => { + const array = parseStoredArray(null); + const object = parseStoredObject(null); + array.push('notice'); + object.global = true; + assert.deepEqual(parseStoredArray(null), []); + assert.deepEqual(parseStoredObject(null), {}); +}); + +test('storage reads return the original stored value', (t) => { + mockStorage(t, { + getItem(key) { + assert.equal(key, 'preference'); + return 'stored'; + }, + }); + assert.equal(readStorageValue('preference'), 'stored'); +}); + +test('storage read failures fall back to null', (t) => { + mockStorage(t, { + getItem() { + throw new Error('Storage blocked'); + }, + }); + assert.equal(readStorageValue('preference'), null); + assert.deepEqual(readNoticeReadKeys(), []); + assert.equal(getTableCompactMode(), false); +}); + +test('announcement identity keeps the date and first 30 content characters', () => { + assert.equal( + getAnnouncementKey({ publishDate: '2025-01-01', content: 'a'.repeat(40) }), + `2025-01-01-${'a'.repeat(30)}`, + ); + assert.equal(getAnnouncementKey({}), '-'); + assert.equal(getAnnouncementKey(null), '-'); +}); + +const first = { publishDate: '2025-01-01', content: 'First' }; +const second = { publishDate: '2025-01-02', content: 'Second' }; + +test('unread keys preserve announcement order and duplicate counts', () => { + const notices = [first, second, second]; + const readKeys = [getAnnouncementKey(first)]; + assert.deepEqual(getUnreadAnnouncementKeys(notices, readKeys), [ + getAnnouncementKey(second), + getAnnouncementKey(second), + ]); + assert.deepEqual( + getUnreadAnnouncementKeys(notices, []), + notices.map(getAnnouncementKey), + ); + assert.deepEqual( + getUnreadAnnouncementKeys(notices, notices.map(getAnnouncementKey)), + [], + ); + assert.deepEqual(getUnreadAnnouncementKeys([], readKeys), []); +}); + +test('merging read keys retains history, deduplicates, and does not mutate inputs', () => { + const notices = [first, second, first]; + const readKeys = ['old', getAnnouncementKey(first), 'old']; + assert.deepEqual(mergeAnnouncementReadKeys(notices, readKeys), [ + 'old', + getAnnouncementKey(first), + getAnnouncementKey(second), + ]); + assert.deepEqual(readKeys, ['old', getAnnouncementKey(first), 'old']); + assert.deepEqual(notices, [first, second, first]); +}); + +test('notification persistence uses the existing key and merges the latest stored history', (t) => { + let stored = '["old"]'; + mockStorage(t, { + getItem(key) { + assert.equal(key, 'notice_read_keys'); + return stored; + }, + setItem(key, value) { + assert.equal(key, NOTICE_READ_KEYS_KEY); + stored = value; + }, + }); + markAnnouncementsRead([first, first]); + assert.deepEqual(JSON.parse(stored), ['old', getAnnouncementKey(first)]); + stored = JSON.stringify([...JSON.parse(stored), 'another-tab']); + markAnnouncementsRead([second]); + assert.deepEqual(JSON.parse(stored), [ + 'old', + getAnnouncementKey(first), + 'another-tab', + getAnnouncementKey(second), + ]); +}); + +test('invalid notice storage is treated as unread and can be repaired on write', (t) => { + let stored; + mockStorage(t, { + getItem: () => stored, + setItem: (_key, value) => { + stored = value; + }, + }); + for (const json of [...invalidJson, '{}']) { + stored = json; + assert.deepEqual(readNoticeReadKeys(), []); + assert.deepEqual(getUnreadAnnouncementKeys([first], readNoticeReadKeys()), [ + getAnnouncementKey(first), + ]); + markAnnouncementsRead([first]); + assert.deepEqual(JSON.parse(stored), [getAnnouncementKey(first)]); + } +}); + +test('notification write failures propagate instead of reporting a saved read state', (t) => { + const failure = new Error('Quota exceeded'); + mockStorage(t, { + getItem: () => '[]', + setItem() { + throw failure; + }, + }); + assert.throws( + () => markAnnouncementsRead([first]), + (error) => error === failure, + ); +}); + +test('compact parsing preserves global defaults, per-table selection and truthiness', () => { + const json = '{"global":true,"tokens":false,"channels":"enabled","logs":0}'; + assert.equal(parseTableCompactMode(json), true); + assert.equal(parseTableCompactMode(json, 'tokens'), false); + assert.equal(parseTableCompactMode(json, 'channels'), true); + assert.equal(parseTableCompactMode(json, 'logs'), false); + assert.equal(parseTableCompactMode(json, 'missing'), false); +}); + +test('compact storage-event payloads use the same fallback as initial reads', (t) => { + let stored; + mockStorage(t, { getItem: () => stored }); + for (const json of [...invalidJson, '[]', '[true]', '{"global":true}']) { + stored = json; + assert.equal(parseTableCompactMode(json), getTableCompactMode()); + } + assert.equal(parseTableCompactMode(null), false); +}); + +test('compact writes preserve other table preferences and the storage key', (t) => { + let stored = '{"channels":true,"tokens":false}'; + mockStorage(t, { + getItem(key) { + assert.equal(key, 'table_compact_modes'); + return stored; + }, + setItem(key, value) { + assert.equal(key, TABLE_COMPACT_MODES_KEY); + stored = value; + }, + }); + assert.equal(setTableCompactMode(true), undefined); + setTableCompactMode(true, 'tokens'); + assert.deepEqual(JSON.parse(stored), { + channels: true, + tokens: true, + global: true, + }); + setTableCompactMode(false, 'channels'); + assert.equal(getTableCompactMode('channels'), false); +}); + +test('invalid compact preferences can be replaced by a valid object on write', (t) => { + let stored; + mockStorage(t, { + getItem: () => stored, + setItem: (_key, value) => { + stored = value; + }, + }); + for (const json of [...invalidJson, '[]', '[true]']) { + stored = json; + assert.equal(getTableCompactMode(), false); + setTableCompactMode(true); + assert.deepEqual(JSON.parse(stored), { global: true }); + } +}); + +test('compact write failures remain non-fatal', (t) => { + mockStorage(t, { + getItem: () => '{}', + setItem() { + throw new Error('Quota exceeded'); + }, + }); + assert.doesNotThrow(() => setTableCompactMode(true)); +}); + +test('blocked storage access is guarded for reads and compact writes but not notice writes', (t) => { + mockStorage(t, undefined); + Object.defineProperty(globalThis, 'localStorage', { + configurable: true, + get() { + throw new Error('Storage blocked'); + }, + }); + assert.deepEqual(readNoticeReadKeys(), []); + assert.equal(getTableCompactMode(), false); + assert.doesNotThrow(() => setTableCompactMode(true)); + assert.throws(() => markAnnouncementsRead([first]), /Storage blocked/); +}); diff --git a/src/helpers/tableCompactMode.js b/src/helpers/tableCompactMode.js new file mode 100644 index 00000000..2eb505ff --- /dev/null +++ b/src/helpers/tableCompactMode.js @@ -0,0 +1,43 @@ +/* +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 { TABLE_COMPACT_MODES_KEY } from '../constants/common.constant.js'; +import { parseStoredObject, readStorageValue } from './storageJson.js'; + +export function parseTableCompactMode(json, tableKey = 'global') { + const modes = parseStoredObject(json); + return !!modes[tableKey]; +} + +export function getTableCompactMode(tableKey = 'global') { + return parseTableCompactMode( + readStorageValue(TABLE_COMPACT_MODES_KEY), + tableKey, + ); +} + +export function setTableCompactMode(compact, tableKey = 'global') { + const modes = parseStoredObject(readStorageValue(TABLE_COMPACT_MODES_KEY)); + modes[tableKey] = compact; + try { + localStorage.setItem(TABLE_COMPACT_MODES_KEY, JSON.stringify(modes)); + } catch { + // Compact mode remains usable in memory when preferences cannot be saved. + } +} diff --git a/src/helpers/utils.jsx b/src/helpers/utils.jsx index cecc43dc..b1c97d35 100644 --- a/src/helpers/utils.jsx +++ b/src/helpers/utils.jsx @@ -26,7 +26,6 @@ import { THINK_TAG_REGEX, MESSAGE_ROLES, } from '../constants/playground.constants'; -import { TABLE_COMPACT_MODES_KEY } from '../constants'; import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile'; // 官方价折扣计算(纯函数):管理端与市场页共用 import { buildOfficialComparison, formatDiscountLabel } from './officialPrice'; @@ -735,33 +734,10 @@ export const formatDateTimeString = (date) => { return `${year}-${month}-${day} ${hours}:${minutes}`; }; -function readTableCompactModes() { - try { - const json = localStorage.getItem(TABLE_COMPACT_MODES_KEY); - return json ? JSON.parse(json) : {}; - } catch { - return {}; - } -} - -function writeTableCompactModes(modes) { - try { - localStorage.setItem(TABLE_COMPACT_MODES_KEY, JSON.stringify(modes)); - } catch { - // ignore - } -} - -export function getTableCompactMode(tableKey = 'global') { - const modes = readTableCompactModes(); - return !!modes[tableKey]; -} - -export function setTableCompactMode(compact, tableKey = 'global') { - const modes = readTableCompactModes(); - modes[tableKey] = compact; - writeTableCompactModes(modes); -} +export { + getTableCompactMode, + setTableCompactMode, +} from './tableCompactMode.js'; // ------------------------------- // Select 组件统一过滤逻辑 @@ -1111,6 +1087,7 @@ export const createCardProPagination = ({ isMobile = false, pageSizeOpts = [10, 20, 50, 100], showSizeChanger = true, + preventPageChangeOnPageSizeChange = false, t = (key) => key, }) => { if (!total || total <= 0) return null; @@ -1140,6 +1117,7 @@ export const createCardProPagination = ({ showSizeChanger={showSizeChanger} onPageSizeChange={onPageSizeChange} onPageChange={onPageChange} + preventPageChangeOnPageSizeChange={preventPageChangeOnPageSizeChange} size={isMobile ? 'small' : 'default'} showQuickJumper={isMobile} showTotal diff --git a/src/hooks/common/useNotifications.js b/src/hooks/common/useNotifications.js index bc88027f..c9f2e4ce 100644 --- a/src/hooks/common/useNotifications.js +++ b/src/hooks/common/useNotifications.js @@ -17,49 +17,31 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ -import { useState, useEffect } from 'react'; +import { useState, useEffect, useCallback } from 'react'; +import { + getUnreadAnnouncementKeys, + markAnnouncementsRead, + readNoticeReadKeys, +} from '../../helpers/notificationReadState.js'; + +const EMPTY_ANNOUNCEMENTS = []; export const useNotifications = (statusState) => { const [noticeVisible, setNoticeVisible] = useState(false); const [unreadCount, setUnreadCount] = useState(0); - const announcements = statusState?.status?.announcements || []; + const announcements = + statusState?.status?.announcements || EMPTY_ANNOUNCEMENTS; - // Helper functions - const getAnnouncementKey = (a) => - `${a?.publishDate || ''}-${(a?.content || '').slice(0, 30)}`; - - const calculateUnreadCount = () => { - if (!announcements.length) return 0; - let readKeys = []; - try { - readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || []; - } catch (_) { - readKeys = []; - } - const readSet = new Set(readKeys); - return announcements.filter((a) => !readSet.has(getAnnouncementKey(a))) - .length; - }; - - const getUnreadKeys = () => { + const getUnreadKeys = useCallback(() => { if (!announcements.length) return []; - let readKeys = []; - try { - readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || []; - } catch (_) { - readKeys = []; - } - const readSet = new Set(readKeys); - return announcements - .filter((a) => !readSet.has(getAnnouncementKey(a))) - .map(getAnnouncementKey); - }; + return getUnreadAnnouncementKeys(announcements, readNoticeReadKeys()); + }, [announcements]); // Effects useEffect(() => { - setUnreadCount(calculateUnreadCount()); - }, [announcements]); + setUnreadCount(getUnreadKeys().length); + }, [getUnreadKeys]); // Actions const handleNoticeOpen = () => { @@ -69,16 +51,7 @@ export const useNotifications = (statusState) => { const handleNoticeClose = () => { setNoticeVisible(false); if (announcements.length) { - let readKeys = []; - try { - readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || []; - } catch (_) { - readKeys = []; - } - const mergedKeys = Array.from( - new Set([...readKeys, ...announcements.map(getAnnouncementKey)]), - ); - localStorage.setItem('notice_read_keys', JSON.stringify(mergedKeys)); + markAnnouncementsRead(announcements); } setUnreadCount(0); }; diff --git a/src/hooks/common/useTableCompactMode.js b/src/hooks/common/useTableCompactMode.js index 62db2862..786cc1f4 100644 --- a/src/hooks/common/useTableCompactMode.js +++ b/src/hooks/common/useTableCompactMode.js @@ -18,8 +18,12 @@ For commercial licensing, please contact support@quantumnous.com */ import { useState, useEffect, useCallback } from 'react'; -import { getTableCompactMode, setTableCompactMode } from '../../helpers'; -import { TABLE_COMPACT_MODES_KEY } from '../../constants'; +import { + getTableCompactMode, + parseTableCompactMode, + setTableCompactMode, +} from '../../helpers/tableCompactMode.js'; +import { TABLE_COMPACT_MODES_KEY } from '../../constants/common.constant.js'; /** * 自定义 Hook:管理表格紧凑/自适应模式 @@ -42,12 +46,7 @@ export function useTableCompactMode(tableKey = 'global') { useEffect(() => { const handleStorage = (e) => { if (e.key === TABLE_COMPACT_MODES_KEY) { - try { - const modes = JSON.parse(e.newValue || '{}'); - setCompactModeState(!!modes[tableKey]); - } catch { - // ignore parse error - } + setCompactModeState(parseTableCompactMode(e.newValue, tableKey)); } }; window.addEventListener('storage', handleStorage); diff --git a/src/hooks/org/useOrgData.js b/src/hooks/org/useOrgData.js index 28e3ce28..d61c08b9 100644 --- a/src/hooks/org/useOrgData.js +++ b/src/hooks/org/useOrgData.js @@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com import { useState, useCallback, useEffect, useRef } from 'react'; import { API } from '../../helpers/api'; import { showError } from '../../helpers'; +import { buildOrgLogFilters } from '../../helpers/orgLogFilters.js'; // 获取企业X-Org-Id header const getOrgHeaders = (orgId) => ({ @@ -239,19 +240,15 @@ export function useOrgMemberLogs(orgId) { const [loading, setLoading] = useState(false); const fetch = useCallback( - async ( - page = 1, - pageSize = 20, - { userId, startTimestamp, endTimestamp, modelName } = {}, - ) => { + async (page = 1, pageSize = 20, filters = {}) => { if (!orgId) return; setLoading(true); try { - const params = { p: page, page_size: pageSize }; - if (userId) params.user_id = userId; - if (startTimestamp) params.start_timestamp = startTimestamp; - if (endTimestamp) params.end_timestamp = endTimestamp; - if (modelName) params.model_name = modelName; + const params = { + p: page, + page_size: pageSize, + ...buildOrgLogFilters(filters), + }; const res = await API.get('/api/org/logs', { headers: getOrgHeaders(orgId), @@ -292,18 +289,11 @@ export function useOrgLogsStat(orgId) { const [loading, setLoading] = useState(false); const fetch = useCallback( - async ( - { userId, startTimestamp, endTimestamp, modelName } = {}, - noCache = false, - ) => { + async (filters = {}, noCache = false) => { if (!orgId) return; setLoading(true); try { - const params = {}; - if (userId) params.user_id = userId; - if (startTimestamp) params.start_timestamp = startTimestamp; - if (endTimestamp) params.end_timestamp = endTimestamp; - if (modelName) params.model_name = modelName; + const params = buildOrgLogFilters(filters); if (noCache) params.nocache = 1; const res = await API.get('/api/org/logs/stat', { @@ -346,18 +336,11 @@ export function useOrgMemberRanking(orgId) { const [loading, setLoading] = useState(false); const fetch = useCallback( - async ( - { userId, startTimestamp, endTimestamp, modelName, limit } = {}, - noCache = false, - ) => { + async ({ limit, ...filters } = {}, noCache = false) => { if (!orgId) return; setLoading(true); try { - const params = {}; - if (userId) params.user_id = userId; - if (startTimestamp) params.start_timestamp = startTimestamp; - if (endTimestamp) params.end_timestamp = endTimestamp; - if (modelName) params.model_name = modelName; + const params = buildOrgLogFilters(filters); if (limit) params.limit = limit; if (noCache) params.nocache = 1; diff --git a/src/hooks/task-logs/useTaskLogsData.js b/src/hooks/task-logs/useTaskLogsData.js index b0d8476d..b5dd956a 100644 --- a/src/hooks/task-logs/useTaskLogsData.js +++ b/src/hooks/task-logs/useTaskLogsData.js @@ -29,6 +29,7 @@ import { timestamp2string, } from '../../helpers'; import { EVENTS, emit } from '../../helpers/eventBus'; +import { resolveColumnVisibility } from '../../helpers/columnVisibility'; import { ITEMS_PER_PAGE } from '../../constants'; import { useTableCompactMode } from '../common/useTableCompactMode'; @@ -136,24 +137,13 @@ export const useTaskLogsData = () => { // Load saved column preferences from localStorage useEffect(() => { const savedColumns = localStorage.getItem(STORAGE_KEY); - if (savedColumns) { - try { - const parsed = JSON.parse(savedColumns); - const defaults = getDefaultColumnVisibility(); - const merged = { ...defaults, ...parsed }; - - // For non-admin users, force-hide admin-only columns (does not touch admin settings) - if (!isAdminUser) { - merged[COLUMN_KEYS.CHANNEL] = false; - } - setVisibleColumns(merged); - } catch (e) { - console.error('Failed to parse saved column preferences', e); - initDefaultColumns(); - } - } else { - initDefaultColumns(); - } + setVisibleColumns( + resolveColumnVisibility( + getDefaultColumnVisibility(), + savedColumns, + isAdminUser ? [] : [COLUMN_KEYS.CHANNEL], + ), + ); }, []); // Get default column visibility based on user role diff --git a/src/hooks/usage-logs/useUsageLogsData.jsx b/src/hooks/usage-logs/useUsageLogsData.jsx index 1ddabff1..1aabd347 100644 --- a/src/hooks/usage-logs/useUsageLogsData.jsx +++ b/src/hooks/usage-logs/useUsageLogsData.jsx @@ -34,6 +34,7 @@ import { import { ITEMS_PER_PAGE } from '../../constants'; import { useTableCompactMode } from '../common/useTableCompactMode'; import { EVENTS, subscribe } from '../../helpers/eventBus'; +import { resolveColumnVisibility } from '../../helpers/columnVisibility'; export const useLogsData = () => { const { t } = useTranslation(); @@ -191,26 +192,15 @@ export const useLogsData = () => { // Load saved column preferences from localStorage useEffect(() => { const savedColumns = localStorage.getItem(STORAGE_KEY); - if (savedColumns) { - try { - const parsed = JSON.parse(savedColumns); - const defaults = getDefaultColumnVisibility(); - const merged = { ...defaults, ...parsed }; - - // For non-admin users, force-hide admin-only columns (does not touch admin settings) - if (!isAdminUser) { - merged[COLUMN_KEYS.CHANNEL] = false; - merged[COLUMN_KEYS.USERNAME] = false; - merged[COLUMN_KEYS.RETRY] = false; - } - setVisibleColumns(merged); - } catch (e) { - console.error('Failed to parse saved column preferences', e); - initDefaultColumns(); - } - } else { - initDefaultColumns(); - } + setVisibleColumns( + resolveColumnVisibility( + getDefaultColumnVisibility(), + savedColumns, + isAdminUser + ? [] + : [COLUMN_KEYS.CHANNEL, COLUMN_KEYS.USERNAME, COLUMN_KEYS.RETRY], + ), + ); }, []); // Get default column visibility based on user role diff --git a/src/hooks/users/useUsersData.jsx b/src/hooks/users/useUsersData.jsx index 96e1a194..11eb3274 100644 --- a/src/hooks/users/useUsersData.jsx +++ b/src/hooks/users/useUsersData.jsx @@ -72,17 +72,22 @@ export const useUsersData = () => { // Load users data const loadUsers = async (startIdx, pageSize) => { setLoading(true); - const res = await API.get(`/api/user/?p=${startIdx}&page_size=${pageSize}`); - const { success, message, data } = res.data; - if (success) { - const newPageData = data.items; - setActivePage(data.page); - setUserCount(data.total); - setUserFormat(newPageData); - } else { - showError(message); + try { + const res = await API.get( + `/api/user/?p=${startIdx}&page_size=${pageSize}`, + ); + const { success, message, data } = res.data; + if (success) { + const newPageData = data.items; + setActivePage(data.page); + setUserCount(data.total); + setUserFormat(newPageData); + } else { + showError(message); + } + } finally { + setLoading(false); } - setLoading(false); }; // Search users with keyword and group @@ -100,24 +105,32 @@ export const useUsersData = () => { } if (searchKeyword === '' && searchGroup === '') { - // If keyword is blank, load files instead + // If both filters are blank, load users instead await loadUsers(startIdx, pageSize); return; } setSearching(true); - const res = await API.get( - `/api/user/search?keyword=${searchKeyword}&group=${searchGroup}&p=${startIdx}&page_size=${pageSize}`, - ); - const { success, message, data } = res.data; - if (success) { - const newPageData = data.items; - setActivePage(data.page); - setUserCount(data.total); - setUserFormat(newPageData); - } else { - showError(message); + try { + const res = await API.get('/api/user/search', { + params: { + keyword: searchKeyword, + group: searchGroup, + p: startIdx, + page_size: pageSize, + }, + }); + const { success, message, data } = res.data; + if (success) { + const newPageData = data.items; + setActivePage(data.page); + setUserCount(data.total); + setUserFormat(newPageData); + } else { + showError(message); + } + } finally { + setSearching(false); } - setSearching(false); }; // Manage user operations (promote, demote, enable, disable, delete) @@ -191,12 +204,9 @@ export const useUsersData = () => { // Handle page change const handlePageChange = (page) => { setActivePage(page); - const { searchKeyword, searchGroup } = getFormValues(); - if (searchKeyword === '' && searchGroup === '') { - loadUsers(page, pageSize).then(); - } else { - searchUsers(page, pageSize, searchKeyword, searchGroup).then(); - } + refresh(page).catch((reason) => { + showError(reason); + }); }; // Handle page size change @@ -204,11 +214,9 @@ export const useUsersData = () => { localStorage.setItem('page-size', size + ''); setPageSize(size); setActivePage(1); - loadUsers(activePage, size) - .then() - .catch((reason) => { - showError(reason); - }); + await refresh(1, size).catch((reason) => { + showError(reason); + }); }; // Handle table row styling for disabled/deleted users @@ -225,13 +233,8 @@ export const useUsersData = () => { }; // Refresh data - const refresh = async (page = activePage) => { - const { searchKeyword, searchGroup } = getFormValues(); - if (searchKeyword === '' && searchGroup === '') { - await loadUsers(page, pageSize); - } else { - await searchUsers(page, pageSize, searchKeyword, searchGroup); - } + const refresh = async (page = activePage, size = pageSize) => { + await searchUsers(page, size); }; // Fetch groups data diff --git a/src/hooks/users/useUsersData.test.js b/src/hooks/users/useUsersData.test.js new file mode 100644 index 00000000..830a4761 --- /dev/null +++ b/src/hooks/users/useUsersData.test.js @@ -0,0 +1,256 @@ +/* +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 assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import test from 'node:test'; +import { setImmediate } from 'node:timers/promises'; +import { runInNewContext } from 'node:vm'; +import axios from 'axios'; +import { transformWithEsbuild } from 'vite'; + +const filename = new URL('./useUsersData.jsx', import.meta.url); +const { code } = await transformWithEsbuild( + await readFile(filename, 'utf8'), + filename.pathname, + { loader: 'jsx', format: 'cjs', target: 'node22' }, +); +const defaultPageSize = 10; + +// Execute the real exported hook with state snapshots and mount effects only. +// This controller harness does not model React scheduling, StrictMode, DOM, or HTTP. +async function createHarness() { + const states = []; + const effects = []; + const requests = []; + const errors = []; + const storage = new Map(); + let cursor = 0; + let mounting = true; + let respond = (request) => { + if (request.path === '/api/group/') { + return { data: { data: ['default'] } }; + } + return { + data: { + success: true, + data: { + page: Number(request.params.p), + total: 1, + items: [{ id: 42, username: 'test-user' }], + }, + }, + }; + }; + const modules = { + react: { + useState(initialValue) { + const index = cursor++; + if (mounting) { + states[index] = + typeof initialValue === 'function' ? initialValue() : initialValue; + } + return [ + states[index], + (value) => { + states[index] = + typeof value === 'function' ? value(states[index]) : value; + }, + ]; + }, + useEffect(effect) { + if (mounting) effects.push(effect); + }, + }, + 'react-i18next': { useTranslation: () => ({ t: (value) => value }) }, + '../../helpers': { + API: { + async get(url, config) { + // Use Axios's actual serializer, but never send a network request. + const parsed = new URL( + axios.getUri({ ...config, url }), + 'https://example.test', + ); + const request = { + path: parsed.pathname, + params: Object.fromEntries(parsed.searchParams), + }; + requests.push(request); + return respond(request); + }, + }, + showError: (error) => errors.push(error), + showSuccess: () => {}, + }, + '../../constants': { ITEMS_PER_PAGE: defaultPageSize }, + '../common/useTableCompactMode': { + useTableCompactMode: () => [false, () => {}], + }, + }; + const module = { exports: {} }; + runInNewContext(code, { + module, + exports: module.exports, + require(name) { + assert.ok(Object.hasOwn(modules, name), `Unexpected import: ${name}`); + return modules[name]; + }, + localStorage: { setItem: (key, value) => storage.set(key, value) }, + }); + const render = () => { + cursor = 0; + return module.exports.useUsersData(); + }; + render(); + mounting = false; + effects.forEach((effect) => effect()); + await setImmediate(); + return { + render, + requests, + errors, + storage, + setResponder(next) { + respond = next; + }, + }; +} + +function assertRequest(request, page, size, filters = {}) { + const keyword = filters.searchKeyword || ''; + const group = filters.searchGroup || ''; + assert.deepEqual(request, { + path: keyword || group ? '/api/user/search' : '/api/user/', + params: { + ...(keyword || group ? { keyword, group } : {}), + p: String(page), + page_size: String(size), + }, + }); +} + +test('mount keeps the initial page-zero fetch and formats returned users', async () => { + const harness = await createHarness(); + assertRequest(harness.requests[0], 0, defaultPageSize); + assert.equal(harness.requests[1].path, '/api/group/'); + const data = harness.render(); + assert.equal(data.loading, false); + assert.equal(data.searching, false); + assert.equal(data.activePage, 0); + assert.equal(data.userCount, 1); + assert.equal(data.users[0].key, 42); +}); + +for (const [name, filters] of Object.entries({ + unfiltered: { searchKeyword: '', searchGroup: '' }, + keyword: { searchKeyword: 'alice', searchGroup: '' }, + group: { searchKeyword: '', searchGroup: 'staff' }, + 'both filters with reserved characters': { + searchKeyword: 'alice & bob+#?=user', + searchGroup: 'staff&group=other +#', + }, +})) { + test(`page-size change from a later page uses page 1, new size, and live form values: ${name}`, async () => { + const harness = await createHarness(); + let values = { searchKeyword: '', searchGroup: '' }; + harness.render().setFormApi({ getValues: () => values }); + harness.render().handlePageChange(4); + await setImmediate(); + assert.equal(harness.render().activePage, 4); + values = filters; + harness.requests.length = 0; + + const pending = harness.render().handlePageSizeChange(25); + assert.equal(harness.render().activePage, 1); + assert.equal(harness.render().pageSize, 25); + await pending; + + assert.equal(harness.requests.length, 1); + assertRequest(harness.requests[0], 1, 25, filters); + assert.equal(harness.storage.get('page-size'), '25'); + assert.equal(harness.render().activePage, 1); + assert.equal(harness.render().loading, false); + assert.equal(harness.render().searching, false); + + harness.render().handlePageChange(3); + await setImmediate(); + assertRequest(harness.requests[1], 3, 25, filters); + await harness.render().refresh(); + assertRequest(harness.requests[2], 3, 25, filters); + }); +} + +test('form search still reads current filters and supports explicit filters and blank fallback', async () => { + const harness = await createHarness(); + let values = { searchKeyword: 'form keyword', searchGroup: 'form group' }; + harness.render().setFormApi({ getValues: () => values }); + harness.requests.length = 0; + + await harness.render().searchUsers(1, 20); + assertRequest(harness.requests[0], 1, 20, values); + await harness.render().searchUsers(2, 20, 'explicit', 'override'); + assertRequest(harness.requests[1], 2, 20, { + searchKeyword: 'explicit', + searchGroup: 'override', + }); + values = {}; + await harness.render().searchUsers(1, 20); + assertRequest(harness.requests[2], 1, 20); +}); + +for (const action of ['loadUsers', 'searchUsers', 'blank search fallback']) { + test(`${action} clears its pending flag and propagates request rejection`, async () => { + const harness = await createHarness(); + const failure = new Error('request rejected'); + let rejectRequest; + harness.setResponder( + () => new Promise((resolve, reject) => (rejectRequest = reject)), + ); + const data = harness.render(); + const pending = + action === 'loadUsers' + ? data.loadUsers(2, 10) + : data.searchUsers(2, 10, action === 'searchUsers' ? 'alice' : '', ''); + const flag = action === 'searchUsers' ? 'searching' : 'loading'; + assert.equal(harness.render()[flag], true); + const rejected = assert.rejects(pending, (error) => error === failure); + rejectRequest(failure); + await rejected; + assert.equal(harness.render().loading, false); + assert.equal(harness.render().searching, false); + }); +} + +for (const handler of ['handlePageSizeChange', 'handlePageChange']) { + for (const filtered of [false, true]) { + test(`${handler} reports rejected ${filtered ? 'filtered' : 'unfiltered'} requests and clears flags`, async () => { + const harness = await createHarness(); + harness.render().setFormApi({ + getValues: () => ({ searchKeyword: filtered ? 'alice' : '' }), + }); + const failure = new Error('pagination request rejected'); + harness.setResponder(() => Promise.reject(failure)); + await harness.render()[handler](25); + await setImmediate(); + assert.deepEqual(harness.errors, [failure]); + assert.equal(harness.render().loading, false); + assert.equal(harness.render().searching, false); + }); + } +} diff --git a/tests/modal-overflow.test.js b/tests/modal-overflow.test.js index 0b826bbc..36f44bfd 100644 --- a/tests/modal-overflow.test.js +++ b/tests/modal-overflow.test.js @@ -1,3 +1,22 @@ +/* +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 assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import test from 'node:test'; diff --git a/tests/org-prompt-records.test.js b/tests/org-prompt-records.test.js index 9e47ad2e..6ec522cb 100644 --- a/tests/org-prompt-records.test.js +++ b/tests/org-prompt-records.test.js @@ -1,3 +1,22 @@ +/* +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 assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import test from 'node:test'; diff --git a/tests/users-pagination.test.js b/tests/users-pagination.test.js new file mode 100644 index 00000000..6c8cc915 --- /dev/null +++ b/tests/users-pagination.test.js @@ -0,0 +1,178 @@ +/* +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 assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import test from 'node:test'; +import { runInNewContext } from 'node:vm'; +import React from 'react'; +import { transformWithEsbuild } from 'vite'; + +const require = createRequire(import.meta.url); +const PaginationFoundation = + require('@douyinfe/semi-foundation/lib/cjs/pagination/foundation.js').default; + +async function compile(relativePath) { + const filename = new URL(relativePath, import.meta.url); + const { code } = await transformWithEsbuild( + await readFile(filename, 'utf8'), + filename.pathname, + { loader: 'jsx', format: 'cjs', target: 'node22', jsx: 'transform' }, + ); + return (modules) => { + const module = { exports: {} }; + runInNewContext(code, { + module, + exports: module.exports, + window: { matchMedia: () => ({ matches: false }) }, + require(name) { + assert.ok(Object.hasOwn(modules, name), `Unexpected import: ${name}`); + return modules[name]; + }, + }); + return module.exports; + }; +} + +const loadUtils = await compile('../src/helpers/utils.jsx'); +const { createCardProPagination } = loadUtils({ + react: React, + '@douyinfe/semi-ui': { Pagination: 'semi-pagination' }, + '../constants': { toastConstants: {} }, + 'react-toastify': {}, + i18next: {}, + '../constants/playground.constants': {}, + '../hooks/common/useIsMobile': { MOBILE_BREAKPOINT: 768 }, + './officialPrice': {}, + './data': {}, + './tableCompactMode.js': {}, +}); +const loadUsersPage = await compile('../src/components/table/users/index.jsx'); + +function paginationProps(element) { + const pagination = React.Children.toArray(element.props.children).find( + (child) => child.type === 'semi-pagination', + ); + assert.ok(pagination, 'The helper must render Semi Pagination'); + return pagination.props; +} + +function foundationFor(props) { + const state = { + currentPage: props.currentPage, + pageSize: props.pageSize, + total: props.total, + }; + // Keep the render snapshot during the event, as with React's batched updates. + // Only view-state setters are stubbed; Semi's callback decisions run unchanged. + return new PaginationFoundation({ + getProps: () => props, + getStates: () => state, + getState: (key) => state[key], + updatePageSize: () => {}, + updateTotal: () => {}, + setCurrentPage: () => {}, + setDisabled: () => {}, + setPageList: () => {}, + notifyPageSizeChange: (size) => props.onPageSizeChange(size), + notifyPageChange: (page) => props.onPageChange(page), + notifyChange: () => {}, + }); +} + +for (const option of [{}, { preventPageChangeOnPageSizeChange: false }]) { + const mode = Object.hasOwn(option, 'preventPageChangeOnPageSizeChange') + ? 'explicit false' + : 'default'; + test(`other tables retain Semi's resize page callback: ${mode}`, () => { + const calls = []; + const props = paginationProps( + createCardProPagination({ + currentPage: 3, + pageSize: 10, + total: 100, + onPageSizeChange: (size) => calls.push(['size', size]), + onPageChange: (page) => calls.push(['page', page]), + ...option, + }), + ); + + foundationFor(props).changePageSize(20); + + assert.deepEqual(calls, [ + ['size', 20], + ['page', 2], + ]); + assert.equal(props.preventPageChangeOnPageSizeChange, false); + }); +} + +for (const isMobile of [false, true]) { + test(`users resize emits only the size callback; navigation still works (${isMobile ? 'mobile' : 'desktop'})`, () => { + const calls = []; + const usersData = { + activePage: 3, + pageSize: 10, + userCount: 100, + handlePageSizeChange: (size) => calls.push(['size', size]), + handlePageChange: (page) => calls.push(['page', page]), + t: (key) => key, + }; + const { default: UsersPage } = loadUsersPage({ + react: React, + '../../common/ui/CardPro': 'card-pro', + './UsersTable': 'users-table', + './UsersActions': 'users-actions', + './UsersFilters': 'users-filters', + './UsersDescription': 'users-description', + './modals/AddUserModal': 'add-user-modal', + './modals/EditUserModal': 'edit-user-modal', + '../../../hooks/users/useUsersData': { useUsersData: () => usersData }, + '../../../hooks/common/useIsMobile': { useIsMobile: () => isMobile }, + '../../../helpers/utils': { createCardProPagination }, + }); + const renderPagination = () => { + const card = React.Children.toArray(UsersPage().props.children).find( + (child) => child.type === 'card-pro', + ); + assert.ok(card, 'UsersPage must pass pagination to CardPro'); + return paginationProps(card.props.paginationArea); + }; + const props = renderPagination(); + + foundationFor(props).changePageSize(20); + + assert.deepEqual(calls, [['size', 20]]); + assert.equal(props.preventPageChangeOnPageSizeChange, true); + assert.equal(props.onPageSizeChange, usersData.handlePageSizeChange); + assert.equal(props.onPageChange, usersData.handlePageChange); + assert.equal(props.size, isMobile ? 'small' : 'default'); + + // The hook owns the reset; verify navigation after its next render. + usersData.activePage = 1; + usersData.pageSize = 20; + calls.length = 0; + const nextProps = renderPagination(); + assert.equal(nextProps.currentPage, 1); + assert.equal(nextProps.pageSize, 20); + foundationFor(nextProps).goPage(2); + assert.deepEqual(calls, [['page', 2]]); + }); +}