From 2e6fe7393932c4860d54fb8f1cf796cbbb154e30 Mon Sep 17 00:00:00 2001 From: zhanjunhao <642307404@qq.com> Date: Sat, 31 Oct 2026 19:02:58 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=8C=E5=96=84=E5=AE=98=E7=BD=91?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E3=80=81=E9=A2=84=E7=BA=A6=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E4=B8=8E=E6=96=87=E7=AB=A0=E7=BC=96=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 11 + AGENTS.md | 28 + docs/api-integration-frontend-20261031.md | 566 ++++++++++++++++++ docs/website-api-acceptance.md | 60 ++ package-lock.json | 108 ++++ package.json | 6 + playwright.config.js | 66 ++ src/App.jsx | 22 + src/components/common/ui/CardPro.jsx | 2 +- src/components/common/ui/CardTable.jsx | 5 +- src/components/common/ui/RichTextEditor.css | 125 ++++ src/components/common/ui/RichTextEditor.jsx | 509 ++++++++++++++++ .../common/ui/SelectableButtonGroup.jsx | 5 +- src/components/common/ui/richTextContent.js | 86 +++ src/components/common/ui/richTextImages.js | 68 +++ src/components/common/ui/richTextLength.js | 59 ++ src/components/layout/PageLayout.jsx | 7 +- src/components/layout/SiderBar.jsx | 60 +- .../layout/components/SkeletonWrapper.jsx | 35 +- .../layout/headerbar/LanguageSelector.jsx | 28 +- .../layout/headerbar/MobileNavMenu.jsx | 28 +- .../layout/headerbar/ThemeToggle.jsx | 29 +- src/components/layout/headerbar/UserArea.jsx | 68 ++- src/components/settings/OperationSetting.jsx | 72 ++- src/constants/settingTabs.js | 13 + src/constants/sidebarModules.js | 2 + src/helpers/adminDelegation.js | 50 ++ src/helpers/auth.jsx | 21 +- src/helpers/render.jsx | 6 + src/helpers/websiteApi.js | 48 ++ src/pages/AdminMenuPreview/index.jsx | 88 +++ src/pages/DemoReservations/README.md | 26 + src/pages/DemoReservations/index.jsx | 294 +++++++++ src/pages/DemoReservations/reservationsApi.js | 54 ++ .../Operation/SettingsAdminDelegation.jsx | 43 +- .../Operation/SettingsHeaderNavModules.jsx | 6 +- .../Operation/SettingsOrgUserNavModules.jsx | 2 +- .../Operation/SettingsSidebarModulesAdmin.jsx | 2 +- .../Setting/Operation/SettingsSkillInject.jsx | 8 +- src/pages/Setting/Operation/SettingsTheme.jsx | 88 +-- src/pages/Setting/index.jsx | 11 +- src/pages/WebsiteSettings/ArticleEditor.jsx | 297 +++++++++ .../WebsiteSettings/ArticleRichEditor.jsx | 33 + src/pages/WebsiteSettings/InsightsPanel.jsx | 417 +++++++++++++ src/pages/WebsiteSettings/QrCodeUpload.jsx | 138 +++++ src/pages/WebsiteSettings/README.md | 106 ++++ src/pages/WebsiteSettings/WebsiteField.jsx | 63 ++ src/pages/WebsiteSettings/WebsiteSettings.css | 264 ++++++++ src/pages/WebsiteSettings/index.jsx | 285 +++++++++ src/pages/WebsiteSettings/insightsContent.js | 32 + src/pages/WebsiteSettings/insightsModel.js | 201 +++++++ src/pages/WebsiteSettings/model.js | 291 +++++++++ src/pages/WebsiteSettings/qrPreview.js | 40 ++ src/pages/WebsiteSettings/settingsApi.js | 119 ++++ 54 files changed, 4898 insertions(+), 203 deletions(-) create mode 100644 AGENTS.md create mode 100644 docs/api-integration-frontend-20261031.md create mode 100644 docs/website-api-acceptance.md create mode 100644 playwright.config.js create mode 100644 src/components/common/ui/RichTextEditor.css create mode 100644 src/components/common/ui/RichTextEditor.jsx create mode 100644 src/components/common/ui/richTextContent.js create mode 100644 src/components/common/ui/richTextImages.js create mode 100644 src/components/common/ui/richTextLength.js create mode 100644 src/helpers/adminDelegation.js create mode 100644 src/helpers/websiteApi.js create mode 100644 src/pages/AdminMenuPreview/index.jsx create mode 100644 src/pages/DemoReservations/README.md create mode 100644 src/pages/DemoReservations/index.jsx create mode 100644 src/pages/DemoReservations/reservationsApi.js create mode 100644 src/pages/WebsiteSettings/ArticleEditor.jsx create mode 100644 src/pages/WebsiteSettings/ArticleRichEditor.jsx create mode 100644 src/pages/WebsiteSettings/InsightsPanel.jsx create mode 100644 src/pages/WebsiteSettings/QrCodeUpload.jsx create mode 100644 src/pages/WebsiteSettings/README.md create mode 100644 src/pages/WebsiteSettings/WebsiteField.jsx create mode 100644 src/pages/WebsiteSettings/WebsiteSettings.css create mode 100644 src/pages/WebsiteSettings/index.jsx create mode 100644 src/pages/WebsiteSettings/insightsContent.js create mode 100644 src/pages/WebsiteSettings/insightsModel.js create mode 100644 src/pages/WebsiteSettings/model.js create mode 100644 src/pages/WebsiteSettings/qrPreview.js create mode 100644 src/pages/WebsiteSettings/settingsApi.js diff --git a/.gitignore b/.gitignore index 0da56ec3..094f2a59 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,17 @@ node_modules/ /.nyc_output/ *.lcov +# Local acceptance tests, browser sessions, and reports +/e2e/ +/tests/ +*.test.* +*.spec.* +/playwright/.auth/ +/playwright-report/ +/test-results/ +/blob-report/ +/scripts/seed-demo-requests.mjs + # production /build /dist/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..ad8044c0 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,28 @@ +# Codex 项目协作规范 + +适用于本项目的开发、验收、测试与页面比对。 + +## 工具选择 + +- 网页操作、功能验收、截图和页面比对,优先使用项目中的 Playwright 配置与测试脚本。 +- 浏览器优先使用本机 Google Chrome,通过 Playwright 的 `channel: 'chrome'` 启动独立测试会话;需要复用已有会话时,使用已授权且可连接的浏览器会话。 +- 代码检索、文件编辑、接口检查和构建验证,使用对应的命令行工具或 API。 +- 不将 computer-use 作为网页任务的默认工具。仅在 Playwright 无法覆盖的原生桌面操作,或用户明确要求时使用。 +- Playwright 执行失败时,先排查服务地址、元素定位、等待条件、浏览器环境和登录状态;不要直接切换到 computer-use。 + +## 开发与验收 + +- 修改前阅读相关代码与接口文档,保留用户已有修改,控制变更范围。 +- 完成开发后,根据变更运行必要的逻辑测试、Playwright 验收及构建检查;纯文档修改检查内容与格式即可。 +- 页面交互使用稳定的角色、标签或测试标识定位元素,使用条件等待,避免依赖固定延时和屏幕坐标。 +- 功能验收覆盖正常流程及相关的空数据、失败提示、校验和重复提交场景;涉及响应式布局时检查桌面端和移动端。 +- 页面比对使用一致的视口、数据、主题和页面状态,结合截图与实际交互确认差异。 +- 模拟接口测试与真实后端联调分别记录;模拟通过不等同于真实保存、上传或鉴权通过。 + +## 测试与交付 + +- 复用 `playwright.config.js`:`npm run test:e2e` 运行验收,`npm run test:e2e:headed` 显示浏览器,`npm run test:e2e:report` 查看报告。 +- 新增测试文件、截图、报告、trace 和浏览器会话文件应加入 Git 忽略规则,不提交到仓库;已有受 Git 跟踪的文件不擅自移除。 +- 不在代码、日志或报告中输出密码、Cookie、令牌等敏感信息。 +- 测试失败时检查错误与报告,修复后重跑受影响用例;未执行或受环境限制的项目如实说明。 +- 交付时简要说明完成内容、实际验证结果和待验收项,不将未完成验证的功能描述为验收通过。 diff --git a/docs/api-integration-frontend-20261031.md b/docs/api-integration-frontend-20261031.md new file mode 100644 index 00000000..43693b0d --- /dev/null +++ b/docs/api-integration-frontend-20261031.md @@ -0,0 +1,566 @@ +# 官网及管理后台新增接口联调文档 + +版本:2026-10-31 + +适用范围:官网预约演示表单、管理后台预约需求列表、管理后台官网设置,以及官网配置展示读取。 + +## 1. 联调环境与接口总览 + +**后端地址:`http://134.175.227.134:13000`** + +| 编号 | 功能 | 方法 | 路径 | 调用方 | 权限 | +| ------ | --------------------------------- | ---- | ---------------------------- | -------------- | ---------- | +| API-01 | 提交预约演示表单 | POST | `/api/website/demo-requests` | 官网 | 无需登录 | +| API-02 | 查询预约需求列表 | GET | `/api/website/demo-requests` | 管理后台 | 平台管理员 | +| API-03 | 保存官网完整配置(setPageConfig) | POST | `/api/website/page-config` | 管理后台 | 平台管理员 | +| API-04 | 获取官网完整配置(getPageConfig) | GET | `/api/website/page-config` | 官网、管理后台 | 无需登录 | + +平台管理员和超级管理员均可调用受保护接口。普通用户、仅有企业管理员身份的用户无权调用。新增接口均没有结尾 `/`。 + +本次交付为后端接口;管理后台“预约演示”(原型名为“预约需求”)和“官网设置”页面按下表对应接口接入。 + +### 后台页面与接口对应 + +| 页面名称 | 参考地址 | 对应接口与用途 | +| ------------------------------------ | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | +| 预约演示(交付原型中名为“预约需求”) | [预约演示列表](http://192.168.0.161:5174/console/demo-reservations) | API-02:查询预约记录、筛选和分页;数据来自官网 API-01 提交 | +| 官网设置 | [官网设置](http://192.168.0.161:5174/console/website-setting) | API-04:读取并回填配置;API-03:保存三个页签的完整配置;企业微信二维码复用第 9 节上传接口 | + +下文字段名称与位置依据交付原型图及现有接口约定整理,在线页面尚未完成逐项核对。列表菜单“预约演示”和官网设置内的“预约演示”页签是两个功能:前者查询访客预约记录,后者配置官网商务联系信息。 + +## 2. 前端接入方式:先看这里 + +### 2.1 本地开发 + +当前联调服务通过 HTTP IP 访问。**管理后台本地调试使用 Vite 的 `/api` 代理**,浏览器向本地相对路径发请求,由 Vite 转发到上述后端。 + +在已有 `vite.config.js/ts` 的 `server.proxy` 中合并以下配置,不要覆盖其他项目配置: + +```js +server: { + proxy: { + '/api': { + target: 'http://134.175.227.134:13000', + changeOrigin: true, + }, + }, +} +``` + +管理后台的登录、用户信息和新增管理接口都走同一个 `/api` 代理。不要一部分请求走公网绝对地址、另一部分走本地代理。 + +本仓库 `web` 前端已经配置该代理,启动命令: + +```powershell +cd D:\project\liantiao\web +bun install +bun run dev +``` + +打开终端显示的本地地址,通常为 `http://localhost:5173`。例如访问 `http://localhost:5173/api/status` 可验证代理。 + +当前项目的 `VITE_REACT_APP_SERVER_URL` 应保持未设置或空字符串,避免绕过同源代理。以上本地目录是当前后端仓库的路径;其他前端项目在各自目录启动即可。 + +### 2.2 官网匿名直连与跨域状态 + +官网公开提交/读取可直接请求 `http://134.175.227.134:13000`,请求应使用 `credentials: 'omit'`;Axios 不要开启 `withCredentials`。 + +当前环境允许公开跨域请求,响应 `Access-Control-Allow-Origin: *`,**不允许跨域携带 Cookie**。管理后台使用同源代理即可携带登录会话。HTTPS 页面不能直接请求这个 HTTP 地址,应走自己的同源代理或后续 HTTPS API 地址,避免混合内容被浏览器拦截。 + +正式官网/后台域名确定后,请提供完整 origin(协议、主机、端口),由后端配置白名单。跨站 Cookie 登录还需要 HTTPS、相应 Cookie 配置及浏览器策略支持。 + +## 3. 公共响应、错误与鉴权 + +### 3.1 响应格式 + +成功示例(HTTP 200): + +```json +{ + "success": true, + "message": "", + "data": null +} +``` + +业务失败示例(沿用后台规范,可能仍为 HTTP 200): + +```json +{ + "success": false, + "message": "name 不能为空" +} +``` + +**不能仅通过 HTTP 200 判断成功,必须检查 `success === true`。** 成功数据在 `data`;失败时展示 `message`,不要假设失败响应也包含 `data`。 + +| 响应字段 | 中文名称 | 类型 | 页面用途 | +| --------- | ------------ | ---------- | ------------------------------------------------------------------------------ | +| `success` | 业务是否成功 | boolean | 判断提交、查询、读取、保存或上传是否成功 | +| `message` | 结果提示信息 | string | 失败时用于错误提示;成功时可能为空字符串 | +| `data` | 业务数据 | 按接口定义 | 预约提交结果、预约列表、官网配置或上传结果;具体含义见各接口,失败时可能不存在 | + +本文响应字段路径均从 JSON 响应正文开始计算;使用 Axios 时,先从 `response.data` 取得响应正文,再读取正文中的 `success`、`message`、`data`。 + +| 情况 | HTTP / 响应 | 前端处理 | +| -------------------------------- | -------------------------- | ------------ | +| 成功 | 200,`success:true` | 读取 data | +| 参数错误、保存/查询失败 | 通常 200,`success:false` | 提示 message | +| 未登录、缺少/不匹配 New-Api-User | 401,`success:false` | 重新登录 | +| 已登录但角色权限不足 | 沿用 200,`success:false` | 提示无权限 | +| 请求过频 | 429,可能无 JSON 正文 | 提示稍后重试 | +| 网络/网关异常 | 其他状态,可能无 JSON 正文 | 通用错误提示 | + +业务错误没有新增独立 `code` 字段,不要通过固定中文文案推断业务流程。 + +### 3.2 管理员鉴权 + +复用现有个人登录接口:`POST /api/user/login`。 + +请求头:`Content-Type: application/json`。 + +```json +{ + "username": "<管理员账号>", + "password": "<管理员密码>" +} +``` + +登录成功后,浏览器保存 Cookie,从响应 `data.id` 取得用户 ID。后续调用预约列表、配置保存、上传接口时同时携带: + +```http +Cookie: <浏览器自动携带的登录会话> +New-Api-User: <登录响应 data.id> +``` + +Cookie 由浏览器管理,前端无需手工设置 Cookie 请求头。`New-Api-User` 只是当前登录用户标识,不能单独用作身份认证。已有请求封装通常已经处理这两项,优先复用。 + +管理员账号密码单独提供,不包含在这份可转发文档中。模型调用的 `sk-...` Key 无法代替管理员登录会话。启用二次验证的账号沿用现有完整登录流程。 + +## 4. API-01:提交预约演示表单 + +**POST `/api/website/demo-requests`** + +权限:公开。请求类型:`application/json`。 + +### 请求字段 + +以下按图 1“聊聊你的需求”表单的展示顺序,列出页面字段与接口字段的对应关系;“接口必填”沿用现有接口约定。 + +| 接口字段 | 页面字段(图 1) | 类型 | 接口必填 | 限制与说明 | +| ------------------- | ------------------ | ------- | -------- | ------------------------------------------------------------------------------------- | +| `name` | 姓名 | string | 是 | 去除首尾空白后 1–80 字符 | +| `contact` | 联系方式 | string | 是 | 电话或邮箱,对应输入提示“手机号或邮箱”,最多 254 字符 | +| `companyName` | 公司名称 | string | 是 | 去除首尾空白后 1–200 字符 | +| `position` | 职位 | string | 否 | 页面标为选填;最多 100 字符;省略存空字符串 | +| `industry` | 行业 | string | 否 | 页面标为选填;最多 100 字符;保存实际选中值;“请选择行业”是占位提示,不作为行业值提交 | +| `interest` | 关注方向 | string | 否 | 最多 200 字符;图示选中“企业 AI 运营与治理”,前端有默认选项时也应传实际值 | +| `requirement` | 需求 | string | 是 | 业务场景或希望了解的内容;去除首尾空白后 1–5000 字符;保留内部换行 | +| `agreementAccepted` | 同意协议(勾选框) | boolean | 是 | 对应“我已阅读并同意《用户服务协议》和《隐私政策》”;必须为 true | + +图 1 中,姓名、联系方式、公司名称、需求标有必填星号。协议勾选框虽未标星,提交时仍须勾选,传布尔值 `true`,不能传字符串 `"true"`。点击“体验提交”时提交上述字段;按钮文案不对应额外的请求字段。 + +所有文本裁剪首尾空白,长度按 Unicode 码点计算。空白必填值不通过校验。请求体最大 64 KiB。`id`、`created_at` 由后端生成。 + +联系方式当前约定: + +- 邮箱:纯邮箱地址,如 `person+demo@example.com`,不接受 `姓名 <邮箱>`。 +- 电话:包含 7–15 位数字;可在开头带 `+`,内部允许空格、`-`、`(`、`)`,首尾为数字(开头 `+` 除外)。 +- 示例:`13800000001`、`+86 13800000001`、`00123456789`。 +- 不接受微信号、电话分机文本等格式。前导零和 `+` 原样保存,请使用字符串输入。 +- 行业、关注方向目前不设后端枚举,前端维护实际选项,按长度限制提交即可。 + +### 请求示例 + +```json +{ + "name": "张晨", + "contact": "+86 13800000001", + "companyName": "示例科技有限公司", + "position": "技术负责人", + "industry": "软件和信息服务", + "interest": "企业 AI 运营与治理", + "requirement": "希望了解企业 AI 使用管理和成本治理方案。", + "agreementAccepted": true +} +``` + +### 成功响应示例 + +```json +{ + "success": true, + "message": "", + "data": { + "id": 4, + "created_at": 1793404800 + } +} +``` + +| 响应字段 | 中文名称 | 类型 | 页面用途 | +| ----------------- | ------------ | ------- | ------------------------------------------------------------------------------- | +| `data.id` | 预约记录编号 | integer | 标识本次保存的预约记录,可与管理员列表中的记录对应 | +| `data.created_at` | 提交时间 | integer | Unix 秒时间戳;如需格式化为 JavaScript 日期,使用 `new Date(created_at * 1000)` | + +数值仅为示例。ID 不保证连续,也不保证从 1 开始。 + +只有持久化成功才返回成功。保存失败返回 `success:false`,例如 `预约保存失败,请稍后重试`。 + +目前没有业务去重/幂等键;每次有效提交均新增一条记录。提交中禁用按钮,失败或超时后由用户决定重试。公开提交有 IP 限流,默认每 IP 20 次 / 20 分钟,并受全局 API 限流约束。 + +## 5. API-02:查询预约需求列表 + +**GET `/api/website/demo-requests`** + +权限:平台管理员。携带登录 Cookie 和 `New-Api-User`。 + +### 查询参数 + +| 查询参数 | 页面名称 / 位置 | 类型 | 必填 | 说明 | +| ------------- | ----------------------------- | ------- | ---- | --------------------------------------------------------- | +| `name` | 姓名(筛选框) | string | 否 | 输入提示“请输入姓名”;姓名包含匹配,最多 254 字符 | +| `contact` | 联系方式(筛选框) | string | 否 | 输入提示“请输入联系方式”;联系方式包含匹配,最多 254 字符 | +| `companyName` | 公司名称(筛选框) | string | 否 | 输入提示“请输入公司名称”;公司名称包含匹配,最多 254 字符 | +| `p` | 当前页码(底部分页器) | integer | 否 | 从 1 开始,默认 1;翻页时提交目标页码 | +| `page_size` | 每页条数(底部“条/页”选择器) | integer | 否 | 默认 10,最大 100;对应页面的每页显示数量 | + +**请求分页使用 `p`、`page_size`;响应列表使用 `data.items`。不要使用原需求示例中的 `pageNum`、`pageSize`、`records`。** + +使用 `URLSearchParams` 或现有 HTTP 库编码查询参数,避免 `+`、`%`、`&`、中文等被误解析。三个过滤条件以 AND 组合;裁剪首尾空白后为空则不筛选。ASCII 大小写不敏感,非 ASCII 大小写/重音规则取决于数据库。`%`、`_`、`!` 按字面字符查询。 + +```text +GET /api/website/demo-requests?name=%E5%BC%A0&contact=138&companyName=%E7%A7%91%E6%8A%80&p=1&page_size=10 +``` + +### 响应字段与列表列名 + +分页数据从响应正文的 `data` 读取,每条预约记录从 `data.items` 读取。 + +| 响应字段 | 中文名称 / 页面位置 | 类型 | 对应说明 | +| ---------------- | -------------------------- | ------- | ---------------------------------------- | +| `data.page` | 当前页码(底部分页器) | integer | 对应查询参数 `p`;请求与响应的字段名不同 | +| `data.page_size` | 每页条数(底部分页器) | integer | 对应查询参数 `page_size` | +| `data.total` | 总记录数(底部“共 N 条”) | integer | 当前筛选条件下的总记录数,用于计算分页 | +| `data.items` | 预约记录列表(表格数据源) | array | 每个元素是一条预约记录;无匹配时为空数组 | + +下表前七项按原型表格从左到右排列;后三项为接口返回的辅助信息,原型未设对应展示列,无需据此新增列。 + +| 响应字段 | 中文名称 / 列名 | 类型 | 页面展示与使用说明 | +| -------------------------------- | ------------------------ | ------- | ----------------------------------------------------------- | +| `data.items[].name` | 姓名 | string | 预约人的姓名,与官网表单“姓名”对应 | +| `data.items[].contact` | 联系方式 | string | 预约人提交的电话或邮箱,按原始字符串展示,保留 `+` 和前导零 | +| `data.items[].companyName` | 公司名称 | string | 预约人填写的公司名称 | +| `data.items[].position` | 职位 | string | 预约人填写的职位;空字符串按原型展示为“—” | +| `data.items[].industry` | 行业 | string | 官网表单实际选中的行业;空字符串按原型展示为“—” | +| `data.items[].interest` | 关注方向 | string | 官网表单实际选中的关注方向,如“企业 AI 运营与治理” | +| `data.items[].requirement` | 需求 | string | 完整需求文本;列表可截断,完整查看时保留原始内容及换行 | +| `data.items[].id` | 预约记录编号(辅助字段) | integer | 可用作表格行的唯一标识;不是分页中的行序号 | +| `data.items[].agreementAccepted` | 协议同意状态(辅助字段) | boolean | 表示提交时是否同意用户服务协议和隐私政策 | +| `data.items[].created_at` | 提交时间(辅助字段) | integer | Unix 秒时间戳;格式化时先乘以 1000 转为毫秒 | + +### 成功响应示例 + +```json +{ + "success": true, + "message": "", + "data": { + "page": 1, + "page_size": 10, + "total": 1, + "items": [ + { + "id": 4, + "name": "张晨", + "contact": "+86 13800000001", + "companyName": "示例科技有限公司", + "position": "技术负责人", + "industry": "软件和信息服务", + "interest": "企业 AI 运营与治理", + "requirement": "希望了解企业 AI 使用管理和成本治理方案。", + "agreementAccepted": true, + "created_at": 1793404800 + } + ] + } +} +``` + +列表按提交时间倒序、同时间按 ID 倒序。`total` 是筛选后的总记录数。无匹配时 `items:[]`、`total:0`;超出末页时 `items:[]`、保留实际 total。需求返回完整内容,页面自行截断显示,并提供完整查看方式。 + +查询/重置筛选时建议回到第 1 页。页码和页大小应提交正整数;超过 100 的页大小截为 100,负值和 offset 溢出返回业务失败。默认值供省略参数使用。 + +页面“查询”按钮使用三个筛选框的当前值调用本接口;“重置”按钮清空三个筛选条件并回到第 1 页重新查询。两个按钮均为页面操作,不对应额外的请求字段或接口。原型中的演示联系方式仅用于展示,不替代第 4 节的正式提交校验规则。 + +当前仅提供列表查询,没有新增删除、编辑、跟进状态或导出接口。 + +## 6. API-03:保存官网完整配置(setPageConfig) + +**POST `/api/website/page-config`** + +权限:平台管理员。请求类型:`application/json`。携带登录 Cookie 和 `New-Api-User`。 + +### 请求字段 + +| 接口字段 | 中文名称 / 页面范围 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------------------- | ------ | ---- | ------------------------------------------------------------ | +| `config` | 官网完整配置(首页、关于微词元、预约演示三个页签) | string | 是 | 整份官网配置序列化后的合法 JSON 字符串;不是某一个输入框的值 | + +实际传输形态: + +```json +{ + "config": "{\"home\":{},\"about\":{},\"demo\":{}}" +} +``` + +上例是缩略示例,正式请求应提交三个页签的完整内容。**config 必须为字符串,不能直接提交对象。** + +### 配置对象字段约定 + +配置按以下三个分组组织,前端维护完整配置对象后再调用 `JSON.stringify`: + +| 配置分组 | 页签名称 | 包含内容 | +| -------- | ---------- | -------------------------------------------------------------- | +| `home` | 首页 | 付费企业客户、平台日均 Token 调用、客户月度 AI 调用成本 | +| `about` | 关于微词元 | 团队成员、研发人员占比、总部、服务网络;团队成员同时供首页使用 | +| `demo` | 预约演示 | 商务电话、商务邮箱、企业微信、联系地址 | + +以下字段路径相对于序列化前的配置对象;读取时先解析响应正文的 `data` 字符串,再按相同路径回填。三个分组用于组织配置,不作为额外的请求参数或查询参数。 + +```json +{ + "home": { + "payingCustomers": "200+", + "dailyTokenCalls": "10亿+", + "monthlyAiCostReduction": "30%" + }, + "about": { + "teamMembers": "100+", + "researchStaffRatio": "70%", + "headquarters": "深圳", + "serviceNetwork": "全国" + }, + "demo": { + "businessPhone": "0755-12345678", + "businessEmail": "contact@example.com", + "wechatQrCode": "https://cdn.example.com/qr.png", + "address": "示例联系地址" + } +} +``` + +| 字段路径 | 所属页签 / 位置 | 页面字段名称 | 类型 | 原型页面必填 | 输入提示与取值约定 | +| ----------------------------- | ------------------------ | -------------------- | ------ | ------------------ | -------------------------------------------------------------------------------- | +| `home.payingCustomers` | 首页 | 付费企业客户 | string | 是 | 提示“请输入付费企业客户数量”;展示字符串,可包含单位/后缀 | +| `home.dailyTokenCalls` | 首页 | 平台日均 Token 调用 | string | 是 | 提示“请输入平台日均 Token 调用量”;保存完整展示字符串 | +| `home.monthlyAiCostReduction` | 首页 | 客户月度 AI 调用成本 | string | 是 | 提示“请输入客户月度 AI 调用成本降幅”;实际含义为成本降幅,如 `30%`,不是费用金额 | +| `about.teamMembers` | 首页 | 团队成员 | string | 是 | 提示“请输入团队成员数量”;与“关于微词元”共用同一值,勿另建 `home.teamMembers` | +| `about.teamMembers` | 关于微词元 | 团队成员 | string | 是 | 与首页共用;在任一页签修改均更新同一份配置 | +| `about.researchStaffRatio` | 关于微词元;首页辅助提示 | 研发人员占比 | string | 是(关于页输入框) | 提示“请输入研发人员占比”;首页辅助提示读取同一值,无需重复配置 | +| `about.headquarters` | 关于微词元 | 总部 | string | 是 | 提示“请输入总部所在地”;保存总部所在地的展示字符串 | +| `about.serviceNetwork` | 关于微词元 | 服务网络 | string | 是 | 提示“请输入服务网络覆盖范围”;保存覆盖范围的展示字符串 | +| `demo.businessPhone` | 预约演示 | 商务电话 | string | 是 | 提示“请输入商务联系电话”;官网对外展示的商务电话,与预约人的 `contact` 不同 | +| `demo.businessEmail` | 预约演示 | 商务邮箱 | string | 是 | 提示“请输入商务联系邮箱”;官网对外展示的商务邮箱 | +| `demo.wechatQrCode` | 预约演示 | 企业微信 | string | 是 | 通过“上传二维码”选择图片;保存上传返回的可访问 URL,用于二维码预览和官网展示 | +| `demo.address` | 预约演示 | 联系地址 | string | 是 | 提示“请输入详细联系地址”;保存对外展示的详细地址 | + +“原型页面必填”指后台保存前的前端表单校验,后端仍按下文保存规则校验 `config`;不会因本表新增独立的后端字段校验。表中 `about.teamMembers` 出现两次是为了对应两个输入位置,序列化时只保存一份,共 11 个配置值。 + +示例值仅用于说明,不是联调环境默认数据。配置对匿名访客公开,只存对外展示内容。 + +### 保存规则 + +1. 任意页签点击保存,提交 home、about、demo 三个页签的完整当前配置。 +2. 首次保存创建,后续整体覆盖,不做字段级合并;只提交一个页签会丢失未提交的其他页签内容。 +3. 编辑、清空先改变本地表单,点击保存才持久化;切换页签不应丢失未保存内容。 +4. 后端仅校验字符串类型、合法 JSON 和大小,页面必填、完整结构和展示值格式由前端校验。 +5. config 内容最多 60 KiB(UTF-8 字节);外层请求最多 512 KiB。图片传 URL,不要把图片 Base64 放进配置。 +6. 后端完整保存原字符串,包括未知字段;保存前如编辑已存在配置,前端也应保留不认识的字段。 +7. 保存失败保留上一份成功配置;并发保存以最后写入为准,当前没有版本冲突校验。 + +### 成功响应 + +```json +{ + "success": true, + "message": "", + "data": null +} +``` + +失败示例: + +```json +{ + "success": false, + "message": "config 必须是合法 JSON,字符串内容不能超过 60 KiB" +} +``` + +## 7. API-04:获取官网完整配置(getPageConfig) + +**GET `/api/website/page-config`** + +权限:公开。不需要分页、页签参数或登录。 + +### 响应字段与页面回填 + +| 响应字段 / 解析结果 | 中文名称 | 类型 | 页面用途 | +| ------------------- | ---------------- | -------------- | ------------------------------------------------------------------------ | +| `data` | 官网完整配置 | string 或 null | 为 null 时按未配置处理;为字符串时先 `JSON.parse`,再读取三个分组 | +| 解析结果 `home` | 首页配置 | object | 回填“首页”的三个独立指标;团队成员从 `about.teamMembers` 回填 | +| 解析结果 `about` | 关于微词元配置 | object | 回填团队成员、研发人员占比、总部、服务网络,并同步首页的共享值及辅助提示 | +| 解析结果 `demo` | 预约演示联系配置 | object | 回填商务电话、商务邮箱、企业微信二维码和联系地址 | + +每个输入框的字段路径和页面名称与第 6 节相同。此处的 `demo` 是官网联系配置,不是 API-02 返回的预约记录列表。 + +### 尚未配置 + +```json +{ + "success": true, + "message": "", + "data": null +} +``` + +此时官网采用约定的默认展示,后台展示未配置状态。`null` 是 JSON null,不是字符串 `"null"`。 + +### 已配置 + +```json +{ + "success": true, + "message": "", + "data": "{\"home\":{},\"about\":{},\"demo\":{}}" +} +``` + +正式返回最近一次保存的完整字符串,上例仅缩略展示返回类型。 + +前端处理: + +```js +if (result.success !== true) { + throw new Error(result.message || '配置读取失败'); +} +const config = result.data === null ? null : JSON.parse(result.data); +``` + +读取失败返回 `success:false`,不能当成未配置。GET 返回 `Cache-Control: no-store`,前端保存成功后重新读取可拿到最新值;如前端另有缓存需同步失效。 + +## 8. 接入代码示例 + +以下示例在本地 Vite `/api` 代理下使用,推荐现有后台继续复用已封装的请求实例。 + +```js +// 相对路径走 Vite /api 代理。userId 来自现有登录态。 +async function api(path, { method = 'GET', body, userId } = {}) { + const response = await fetch(path, { + method, + credentials: 'same-origin', + headers: { + ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), + ...(userId !== undefined ? { 'New-Api-User': String(userId) } : {}), + }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + if (!response.ok) throw new Error(`请求失败:HTTP ${response.status}`); + const result = await response.json(); + if (result.success !== true) throw new Error(result.message || '请求失败'); + return result.data; +} + +// 预约查询:过滤值通过 URLSearchParams 编码。 +async function getDemoRequests(userId, filters, page = 1, pageSize = 10) { + const query = new URLSearchParams({ + name: filters.name || '', + contact: filters.contact || '', + companyName: filters.companyName || '', + p: String(page), + page_size: String(pageSize), + }); + return api(`/api/website/demo-requests?${query}`, { userId }); +} + +// 读取:返回 null 或解析后的完整配置对象。 +async function getPageConfig() { + const value = await api('/api/website/page-config'); + return value === null ? null : JSON.parse(value); +} + +// 保存:外层 JSON 编码一次,config 内部对象也要先序列化为字符串。 +async function setPageConfig(userId, completeConfig) { + return api('/api/website/page-config', { + method: 'POST', + userId, + body: { config: JSON.stringify(completeConfig) }, + }); +} + +// 官网表单:先按第 4 节规则校验,然后传入全部表单字段。 +async function submitDemoRequest(form) { + return api('/api/website/demo-requests', { method: 'POST', body: form }); +} +``` + +如官网匿名请求绕过代理直连,URL 改为后端绝对地址,同时将 `credentials` 改为 `omit`。上例没有处理登录跳转或全局消息,可并入项目已有错误处理。 + +## 9. 二维码上传:复用既有接口 + +**POST `/api/customer-service/upload`**,此接口为既有能力,不计入四个新增接口。 + +- 权限:平台管理员会话;且为超级管理员,或已获下放的 customer-service 配置权限。 +- 请求类型:`multipart/form-data`,文件字段名 `file`。 +- 请求同样需要 Cookie 和 `New-Api-User`。 +- 使用 `FormData` 时不要手工设置 Content-Type,让浏览器生成 multipart boundary。 + +| 方向 | 字段 | 中文名称 / 页面位置 | 类型 | 对应关系 | +| -------- | ---------- | -------------------------------------- | ------ | ------------------------------------------------------------------------------ | +| 上传请求 | `file` | 企业微信二维码文件(“上传二维码”按钮) | File | “官网设置 → 预约演示 → 企业微信”选择的图片,放入 FormData | +| 成功响应 | `data.url` | 企业微信二维码图片地址 | string | 用于预览,并写入完整配置中的 `demo.wechatQrCode`;不是直接把 File 对象写入配置 | + +成功响应示例: + +```json +{ + "success": true, + "message": "", + "data": { + "url": "https://cdn.example.com/customer-service/example.png" + } +} +``` + +上传后使用 `data.url` 预览,并写入 `demo.wechatQrCode`;最后点击配置保存才保存该引用。 + +官网设置页面按原型限制 JPG/JPEG、PNG、WebP,单张最大 2 MiB;前端先校验。既有上传接口服务端支持更多格式、最大 5 MiB,因此 2 MiB 目前是页面限制。 + +**上传依赖可用的 COS 对象存储,当前联调环境的 COS 配置与上传成功链路尚未验收。** 四个新接口不依赖 COS,可以先联调;二维码上传需后端补齐或确认存储配置后再测,也可暂用已可访问的测试图片 URL 验证配置显示。长期官网展示须使用实际可长期访问的图片地址。 + +## 10. 前端联调验收清单 + +| 项目 | 预期 | +| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 图 1 表单字段映射 | 姓名、联系方式、公司名称、职位、行业、关注方向、需求及协议勾选框分别对应第 4 节字段;关注方向提交实际选中值,行业占位提示不作为值提交,协议传布尔值 true | +| 预约列表字段映射 | 三个筛选项、七个业务列和底部分页器分别对应第 5 节字段;请求页码用 p,响应页码用 data.page;辅助字段不强制新增展示列 | +| 官网设置字段映射 | 按第 6 节对应三个页签、12 个输入/上传位置与 11 个唯一配置值;首页研发占比提示复用共享值,成本字段表示降幅,企业微信字段保存二维码 URL | +| 官网配置读取回填 | 按第 7 节解析 data 字符串,回填三个页签并同步共享值;预约记录与商务联系配置分别读取 | +| 有效预约提交 | success:true;管理员列表可见完整字段 | +| 必填为空 / 未勾协议 / 联系方式无效 | success:false;不新增有效记录 | +| 三个条件分别及组合查询 | 包含匹配;多条件 AND | +| 查询、重置、翻页和改变页大小 | page/page_size/total/items 对应正确 | +| 无结果 / 页码超过末页 | items 为 [];total 保持真实筛选总数 | +| 首次读取未配置数据 | data 为 null,显示默认/未配置状态 | +| 任一页签保存 | 提交三个页签完整配置,重新读取可回填 | +| 共享字段 | 首页、关于页读取同一份 teamMembers/researchStaffRatio | +| 清空但未保存 | 不修改服务端数据 | +| 非法 config 保存 | 失败,旧配置保持完整 | +| 未登录或普通账号访问管理接口 | 被拦截;管理员可访问 | +| 二维码上传 | 待 COS 确认可用后,验证上传、预览、保存和刷新回显 | + +与最初需求示例的接入差异:分页用 `p/page_size`,列表在 `data.items`;配置请求为 `{config: JSON.stringify(完整配置)}`,读取的 `data` 是字符串或 null;管理接口依赖现有登录会话和 `New-Api-User`。 + +还需双方确认的事项:正式官网/后台访问 origin、是否调整联系方式规则、行业/关注方向最终选项,以及 COS 上传配置和长期图片地址。 diff --git a/docs/website-api-acceptance.md b/docs/website-api-acceptance.md new file mode 100644 index 00000000..d9554397 --- /dev/null +++ b/docs/website-api-acceptance.md @@ -0,0 +1,60 @@ +# 官网接口与页面验收规范 + +接口基准:`docs/api-integration-frontend-20261031.md`。 + +## 运行方式 + +- `npm test`:运行现有单元测试及接口适配器、表单逻辑测试。 +- `npm run test:e2e`:使用本机已安装的 Google Chrome,在独立浏览器会话中运行桌面和移动端验收。 +- `npm run test:e2e:headed -- --project=chrome`:显示 Chrome 窗口,观察验收过程。 +- `npm run test:e2e:report`:查看本地 HTML 报告。 +- 默认启动专用 Vite 服务 `http://127.0.0.1:4175`;设置 `PLAYWRIGHT_BASE_URL` 可指定已有服务。 +- `playwright.config.js` 为公共运行配置。`e2e/`、`tests/`、新增 `*.test.*` / `*.spec.*`、测试结果和 `playwright/.auth/` 均被 Git 忽略。本来已受 Git 跟踪的测试不因忽略规则自动移除。 + +## 官网设置 + +| 验收项 | 通过标准 | +| ---------- | ------------------------------------------------------------------------------------------------------------------------- | +| 初始化读取 | 请求 GET `/api/website/page-config`,将 `data` 字符串解析后回填;`data:null` 回填空表单 | +| 读取失败 | 展示服务端错误或通用错误,可重试;读取成功前禁止编辑、清空和保存 | +| 页签共享 | 切换页签保留编辑内容;两个团队成员输入共用 `about.teamMembers`,首页研发占比提示读取 `about.researchStaffRatio` | +| 完整保存 | 任一页签保存均 POST `{config: JSON.stringify(完整配置)}`;包含 `home/about/demo`,保留扩展字段和已有动态与洞察 | +| 校验 | 所有必填项与格式检查通过后才发请求;按 UTF-8 字节限制配置不超过 60 KiB | +| 保存结果 | 严格检查 `success === true`;成功后提示保存,失败保留输入;连续点击只产生一次待完成请求 | +| 本地清空 | 清空所有页签内容、二维码和错误,不发保存请求;刷新后读取最后成功保存的数据 | +| 二维码 | JPG/JPEG、PNG、WebP,大小大于 0 且不超过 2 MiB;multipart 字段为 `file`,不手动设置 Content-Type;使用返回 URL 预览和保存 | + +## 预约演示 + +| 验收项 | 通过标准 | +| ---------- | ------------------------------------------------------------------------------------------------- | +| 真实字段 | 使用 `companyName/requirement`;七个业务列显示正确,可选空值显示破折号;联系方式保留 `+` 和前导零 | +| 模糊查询 | 姓名、联系方式、公司名称分别及组合发送后端;去除首尾空格,通过 URLSearchParams 编码;多条件为 AND | +| 翻页 | 请求参数为 `p/page_size`;数据读取 `page/page_size/total/items`,翻页保留已提交筛选条件 | +| 查询与重置 | 查询、重置、改变每页条数均回第一页;重置清空三个输入并重新请求 | +| 空数据 | 无匹配时显示空状态,不能用本地演示数据补位 | +| 请求竞态 | 旧请求迟到不能覆盖最近查询结果 | +| 需求展示 | 列表最多显示三行并保留换行;桌面端和移动端均不显示查看完整需求按钮或弹窗 | +| 失败处理 | `success:false`、网络错误、非 JSON 网关错误及 429 均有可理解提示;401 沿用项目重新登录流程 | + +## 管理页面权限 + +- 在「系统设置 → 运营设置 → 普通管理员可见的系统设置页」末尾追加「官网设置」「预约演示」,沿用现有复选框样式,仅超级管理员可修改权限下放。 +- 复用 `AdminDelegatedSettingTabs` 配置,新增值分别为 `website-setting`、`demo-reservations`;保存时保留其他已有权限项。 +- 超级管理员默认可访问两页;普通平台管理员按两个选项分别授权;普通用户即使配置中存在授权也不能访问。 +- 未授权时隐藏菜单,直接访问对应 `/console/` 路由进入无权限页,且不发起该页业务请求;权限尚未加载时等待,格式错误时不授予权限。 +- 菜单继续遵循平台侧栏配置、用户隐藏配置和分组限制。侧栏显示配置沿用现有用途,页面访问权限由角色及下放配置决定。 +- 单独下放这两个独立页面不视为下放系统设置 Tab,不因此开放「系统设置」菜单。 +- 验证保存成功后刷新回填、取消授权、保存失败保留已存权限,以及桌面与移动端菜单行为。 +- 本地验收命令:`npm run test:e2e -- e2e/admin-delegation.spec.js`。用例及截图保持 Git 忽略;模拟接口验收不代表真实后端权限校验已通过。 + +## 验收层次与发布门槛 + +1. 单元测试验证序列化、字段映射、业务失败与异常响应,全部通过。 +2. Playwright 使用隔离的管理员模拟会话及按接口文档实现的响应,验证真实 React 页面、搜索、分页、保存及移动端交互;不得将模拟通过描述成真实后端持久化通过。 +3. `npm run build` 通过;修改的业务文件通过 ESLint 与格式检查。 +4. 真实环境验证公开 GET、预约 POST,以及未登录受保护接口返回 401。模拟提交脚本为本地忽略文件 `scripts/seed-demo-requests.mjs`,默认仅预览;显式添加 `--submit` 才新增三条标注“联调测试”的记录。禁止在页面挂载时自动提交。 +5. 有管理员会话后,人工或使用本地会话文件验证:模拟预约出现在列表、真实筛选分页、配置保存后刷新回填。账号、Cookie、storageState 不得入库。 +6. COS 可用后验证真实上传、匿名预览和保存后回显。文档说明存储尚未验收,因此模拟上传通过不能替代 COS 验收。 + +测试失败需保留报告与 trace,修复后重跑受影响用例。未执行或受环境限制的项目必须明确记录,不能计为通过。 diff --git a/package-lock.json b/package-lock.json index 9a2c0fca..fd80cb01 100644 --- a/package-lock.json +++ b/package-lock.json @@ -23,6 +23,7 @@ "country-flag-icons": "^1.5.19", "dayjs": "^1.11.11", "docx": "^9.6.1", + "entities": "^6.0.1", "highlight.js": "^11.11.1", "history": "^5.3.0", "i18next": "^23.16.8", @@ -33,6 +34,7 @@ "prop-types": "^15.8.1", "qrcode": "^1.5.4", "qrcode.react": "^4.2.0", + "quill": "^2.0.3", "react": "^18.2.0", "react-dom": "^18.2.0", "react-fireworks": "^1.0.4", @@ -55,6 +57,7 @@ }, "devDependencies": { "@douyinfe/vite-plugin-semi": "^2.74.0-alpha.6", + "@playwright/test": "^1.64.1", "@vitejs/plugin-react": "^4.2.1", "autoprefixer": "^10.4.21", "eslint": "8.57.0", @@ -2513,6 +2516,22 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/@playwright/test": { + "version": "1.64.1", + "resolved": "https://registry.npmmirror.com/@playwright/test/-/test-1.64.1.tgz", + "integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@radix-ui/primitive": { "version": "1.2.0", "resolved": "https://registry.npmmirror.com/@radix-ui/primitive/-/primitive-1.2.0.tgz", @@ -8643,6 +8662,12 @@ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "license": "MIT" }, + "node_modules/fast-diff": { + "version": "1.3.0", + "resolved": "https://registry.npmmirror.com/fast-diff/-/fast-diff-1.3.0.tgz", + "integrity": "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==", + "license": "Apache-2.0" + }, "node_modules/fast-equals": { "version": "5.4.5", "resolved": "https://registry.npmmirror.com/fast-equals/-/fast-equals-5.4.5.tgz", @@ -11235,12 +11260,25 @@ "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==", "license": "MIT" }, + "node_modules/lodash.clonedeep": { + "version": "4.5.0", + "resolved": "https://registry.npmmirror.com/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", + "integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==", + "license": "MIT" + }, "node_modules/lodash.debounce": { "version": "4.0.8", "resolved": "https://registry.npmmirror.com/lodash.debounce/-/lodash.debounce-4.0.8.tgz", "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==", "license": "MIT" }, + "node_modules/lodash.isequal": { + "version": "4.5.0", + "resolved": "https://registry.npmmirror.com/lodash.isequal/-/lodash.isequal-4.5.0.tgz", + "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==", + "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.", + "license": "MIT" + }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmmirror.com/lodash.merge/-/lodash.merge-4.6.2.tgz", @@ -13130,6 +13168,12 @@ "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", "license": "(MIT AND Zlib)" }, + "node_modules/parchment": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/parchment/-/parchment-3.0.0.tgz", + "integrity": "sha512-HUrJFQ/StvgmXRcQ1ftY6VEZUq3jA2t9ncFN4F84J/vN0/FPpQF+8FKXb3l6fLces6q0uOHj6NJn+2xvZnxO6A==", + "license": "BSD-3-Clause" + }, "node_modules/parent-module": { "version": "1.0.1", "resolved": "https://registry.npmmirror.com/parent-module/-/parent-module-1.0.1.tgz", @@ -13351,6 +13395,35 @@ "node": ">= 6" } }, + "node_modules/playwright": { + "version": "1.64.1", + "resolved": "https://registry.npmmirror.com/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.64.1", + "resolved": "https://registry.npmmirror.com/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/pngjs": { "version": "5.0.0", "resolved": "https://registry.npmmirror.com/pngjs/-/pngjs-5.0.0.tgz", @@ -13871,6 +13944,41 @@ ], "license": "MIT" }, + "node_modules/quill": { + "version": "2.0.3", + "resolved": "https://registry.npmmirror.com/quill/-/quill-2.0.3.tgz", + "integrity": "sha512-xEYQBqfYx/sfb33VJiKnSJp8ehloavImQ2A6564GAbqG55PGw1dAWUn1MUbQB62t0azawUS2CZZhWCjO8gRvTw==", + "license": "BSD-3-Clause", + "dependencies": { + "eventemitter3": "^5.0.1", + "lodash-es": "^4.17.21", + "parchment": "^3.0.0", + "quill-delta": "^5.1.0" + }, + "engines": { + "npm": ">=8.2.3" + } + }, + "node_modules/quill-delta": { + "version": "5.1.0", + "resolved": "https://registry.npmmirror.com/quill-delta/-/quill-delta-5.1.0.tgz", + "integrity": "sha512-X74oCeRI4/p0ucjb5Ma8adTXd9Scumz367kkMK5V/IatcX6A0vlgLgKbzXWy5nZmCGeNJm2oQX0d2Eqj+ZIlCA==", + "license": "MIT", + "dependencies": { + "fast-diff": "^1.3.0", + "lodash.clonedeep": "^4.5.0", + "lodash.isequal": "^4.5.0" + }, + "engines": { + "node": ">= 12.0.0" + } + }, + "node_modules/quill/node_modules/eventemitter3": { + "version": "5.0.4", + "resolved": "https://registry.npmmirror.com/eventemitter3/-/eventemitter3-5.0.4.tgz", + "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", + "license": "MIT" + }, "node_modules/rc-cascader": { "version": "3.34.0", "resolved": "https://registry.npmmirror.com/rc-cascader/-/rc-cascader-3.34.0.tgz", diff --git a/package.json b/package.json index e8c3da83..b22e1603 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "country-flag-icons": "^1.5.19", "dayjs": "^1.11.11", "docx": "^9.6.1", + "entities": "^6.0.1", "highlight.js": "^11.11.1", "history": "^5.3.0", "i18next": "^23.16.8", @@ -29,6 +30,7 @@ "prop-types": "^15.8.1", "qrcode": "^1.5.4", "qrcode.react": "^4.2.0", + "quill": "^2.0.3", "react": "^18.2.0", "react-dom": "^18.2.0", "react-fireworks": "^1.0.4", @@ -53,6 +55,9 @@ "dev": "vite", "build": "vite build", "test": "node --test", + "test:e2e": "playwright test", + "test:e2e:headed": "playwright test --headed", + "test:e2e:report": "playwright show-report", "lint": "prettier . --check", "lint:fix": "prettier . --write", "check": "npm run eslint && npm test && npm run build", @@ -78,6 +83,7 @@ }, "devDependencies": { "@douyinfe/vite-plugin-semi": "^2.74.0-alpha.6", + "@playwright/test": "^1.64.1", "@vitejs/plugin-react": "^4.2.1", "autoprefixer": "^10.4.21", "eslint": "8.57.0", diff --git a/playwright.config.js b/playwright.config.js new file mode 100644 index 00000000..01384c6d --- /dev/null +++ b/playwright.config.js @@ -0,0 +1,66 @@ +/* +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 { defineConfig, devices } from '@playwright/test'; + +const baseURL = process.env.PLAYWRIGHT_BASE_URL || 'http://127.0.0.1:4175'; + +export default defineConfig({ + testDir: './e2e', + testMatch: '**/*.spec.js', + fullyParallel: false, + forbidOnly: Boolean(process.env.CI), + retries: 0, + workers: 1, + timeout: 45000, + expect: { timeout: 10000 }, + reporter: [ + ['list'], + ['html', { outputFolder: 'playwright-report', open: 'never' }], + ], + outputDir: 'test-results', + use: { + baseURL, + locale: 'zh-CN', + timezoneId: 'Asia/Shanghai', + trace: 'retain-on-failure', + screenshot: 'only-on-failure', + video: 'off', + serviceWorkers: 'block', + }, + projects: [ + { + name: 'chrome', + use: { ...devices['Desktop Chrome'], channel: 'chrome' }, + }, + { + name: 'mobile-chrome', + use: { ...devices['Pixel 5'], channel: 'chrome' }, + }, + ], + webServer: process.env.PLAYWRIGHT_BASE_URL + ? undefined + : { + command: 'npm run dev -- --host 127.0.0.1 --port 4175 --strictPort', + url: baseURL, + reuseExistingServer: !process.env.CI, + timeout: 120000, + env: { VITE_REACT_APP_SERVER_URL: '' }, + }, +}); diff --git a/src/App.jsx b/src/App.jsx index 60a8dbb8..02ace745 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -71,6 +71,8 @@ const OAuth2Callback = lazy(() => import('./components/auth/OAuth2Callback')); // 控制台页面懒加载 const User = lazy(() => import('./pages/User')); const Setting = lazy(() => import('./pages/Setting')); +const WebsiteSettings = lazy(() => import('./pages/WebsiteSettings')); +const DemoReservations = lazy(() => import('./pages/DemoReservations')); const Channel = lazy(() => import('./pages/Channel')); const Token = lazy(() => import('./pages/Token')); const Redemption = lazy(() => import('./pages/Redemption')); @@ -607,6 +609,26 @@ function App() { } /> + + }> + + + + } + /> + + }> + + + + } + /> - + ); } @@ -145,9 +145,8 @@ const CardTable = ({ className='flex justify-between items-center py-1 border-b last:border-b-0 border-dashed' style={{ borderColor: 'var(--semi-color-border)' }} > - + * + * { + margin-top: 12px; +} +.rich-text-content .ql-editor.ql-blank::before { + color: var(--semi-color-text-2); + font-style: normal; + pointer-events: none; + white-space: pre-wrap; +} +.rich-text-content h2 { + font-size: 22px; + font-weight: 600; +} +.rich-text-content h3 { + font-size: 18px; + font-weight: 600; +} +.rich-text-content ul { + list-style: disc; + padding-left: 24px; +} +.rich-text-content .ql-editor ol { + padding-left: 0; +} +.rich-text-content blockquote { + border-left: 3px solid var(--semi-color-border); + padding-left: 16px; + color: var(--semi-color-text-2); +} +.rich-text-content img { + max-width: 100%; + height: auto; +} +.rich-text-count { + border-top: 1px solid var(--semi-color-border); + padding: 4px 12px; + text-align: right; + font-size: 12px; + color: var(--semi-color-text-2); +} + +.rich-text-content.ql-container, +.rich-text-content .ql-container { + font-family: inherit; + font-size: 14px; +} +.rich-text-editor.is-invalid:focus-within { + border-color: var(--semi-color-danger); +} +.rich-text-toolbar select option { + background: var(--semi-color-bg-2); + color: var(--semi-color-text-0); +} +.rich-text-content .ql-editor img { + display: inline-block; + vertical-align: middle; +} +.rich-text-image-error { + padding: 8px 12px; + font-size: 12px; + color: var(--semi-color-danger); + border-top: 1px solid var(--semi-color-border); + line-height: 1.6; +} diff --git a/src/components/common/ui/RichTextEditor.jsx b/src/components/common/ui/RichTextEditor.jsx new file mode 100644 index 00000000..2adf6400 --- /dev/null +++ b/src/components/common/ui/RichTextEditor.jsx @@ -0,0 +1,509 @@ +/* +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 React, { useEffect, useRef, useState } from 'react'; +import Quill, { Delta } from 'quill/core'; +import BoldFormat from 'quill/formats/bold'; +import ItalicFormat from 'quill/formats/italic'; +import UnderlineFormat from 'quill/formats/underline'; +import HeaderFormat from 'quill/formats/header'; +import ListFormat from 'quill/formats/list'; +import QuoteFormat from 'quill/formats/blockquote'; +import ImageFormat from 'quill/formats/image'; +import { + Bold, + Italic, + Underline, + List, + ListOrdered, + Quote, + Undo2, + Redo2, + Eraser, + ImagePlus, +} from 'lucide-react'; +import { + articleImageSource, + ARTICLE_IMAGE_TYPES, + readArticleImage, +} from './richTextImages'; +import { sanitizeArticleHtml } from './richTextContent'; +import { countRichText, limitRichTextChange } from './richTextLength'; +import 'quill/dist/quill.core.css'; +import './RichTextEditor.css'; + +Quill.register( + { + 'formats/bold': BoldFormat, + 'formats/italic': ItalicFormat, + 'formats/underline': UnderlineFormat, + 'formats/header': HeaderFormat, + 'formats/list': ListFormat, + 'formats/blockquote': QuoteFormat, + 'formats/image': ImageFormat, + }, + true, +); + +export default function RichTextEditor({ + value = '', + onChange, + disabled = false, + invalid = false, + onBusyChange, + label = '富文本正文', + placeholder = '', + maxLength, +}) { + const host = useRef(null); + const picker = useRef(null); + const instance = useRef(null); + const selection = useRef({ index: 0, length: 0 }); + const callbacks = useRef({ + value, + onChange, + onBusyChange, + disabled, + label, + placeholder, + maxLength, + }); + const insertFiles = useRef(null); + const lastHtml = useRef(''); + const [format, setFormat] = useState({}); + const [count, setCount] = useState(0); + const [busy, setBusy] = useState(false); + const [imageError, setImageError] = useState(''); + + useEffect(() => { + callbacks.current = { + value, + onChange, + onBusyChange, + disabled, + label, + placeholder, + maxLength, + }; + }, [value, onChange, onBusyChange, disabled, label, placeholder, maxLength]); + + useEffect(() => { + // A separate mount node keeps Quill DOM mutations outside React's tree. + const mount = document.createElement('div'); + const container = host.current; + container.append(mount); + let active = true; + let processing = false; + let compositionStart = null; + const quill = new Quill(mount, { + readOnly: callbacks.current.disabled, + placeholder: callbacks.current.placeholder, + formats: [ + 'bold', + 'italic', + 'underline', + 'header', + 'list', + 'blockquote', + 'image', + ], + modules: { history: { userOnly: false }, toolbar: false }, + }); + instance.current = quill; + const root = quill.root; + root.setAttribute('role', 'textbox'); + root.setAttribute('aria-multiline', 'true'); + root.setAttribute('aria-required', 'true'); + root.setAttribute('aria-label', callbacks.current.label); + + const update = (change, old) => { + if (compositionStart) return; + const limit = callbacks.current.maxLength; + if (Number.isFinite(limit) && old && change) { + const bounded = old.compose( + new Delta(limitRichTextChange(old, change, limit)), + ); + const correction = quill.getContents().diff(bounded); + if (correction.length()) quill.updateContents(correction, 'silent'); + } + const html = sanitizeArticleHtml(quill.getSemanticHTML()); + const next = + !quill.getText().trim() && !root.querySelector('img') ? '' : html; + lastHtml.current = next; + setCount(countRichText(quill.getText())); + callbacks.current.onChange?.(next); + }; + const updateSelection = (range) => { + if (range) + selection.current = { index: range.index, length: range.length }; + setFormat(quill.getFormat(range || selection.current)); + }; + quill.setContents( + quill.clipboard.convert({ + html: sanitizeArticleHtml(callbacks.current.value), + }), + 'silent', + ); + lastHtml.current = callbacks.current.value; + setCount(countRichText(quill.getText())); + quill.history.clear(); + quill.on('text-change', update); + quill.on('editor-change', updateSelectionFromEditor); + function updateSelectionFromEditor(name, range) { + updateSelection( + name === 'selection-change' ? range : quill.getSelection(), + ); + } + + const begin = () => { + if (!active || processing || callbacks.current.disabled) return false; + processing = true; + setBusy(true); + setImageError(''); + callbacks.current.onBusyChange?.(true); + quill.enable(false); + return true; + }; + const finish = () => { + processing = false; + if (!active) return; + setBusy(false); + callbacks.current.onBusyChange?.(false); + quill.enable(!callbacks.current.disabled); + if (!callbacks.current.disabled) { + const range = { ...selection.current }; + quill.focus(); + quill.setSelection(range, 'silent'); + } + }; + const insert = (delta, range) => { + if (!active) return; + let change = new Delta() + .retain(range.index) + .delete(range.length) + .concat(delta); + if (Number.isFinite(callbacks.current.maxLength)) { + change = new Delta( + limitRichTextChange( + quill.getContents(), + change, + callbacks.current.maxLength, + ), + ); + } + quill.history.cutoff(); + quill.updateContents(change, 'api'); + quill.history.cutoff(); + selection.current = { + index: change.transformPosition(range.index, false), + length: 0, + }; + }; + const readFiles = async (files) => { + const sources = []; + for (const file of files) { + try { + sources.push(await readArticleImage(file)); + } catch (error) { + if (active) setImageError(error.message); + sources.push(''); + } + } + return sources; + }; + insertFiles.current = async (files) => { + if (!begin()) return; + const range = { ...selection.current }; + try { + const sources = await readFiles(files); + const delta = sources + .filter(Boolean) + .reduce( + (result, source) => result.insert({ image: source }), + new Delta(), + ); + if (delta.length()) insert(delta, range); + } finally { + finish(); + } + }; + const paste = async (event) => { + event.preventDefault(); + event.stopImmediatePropagation(); + if (!begin()) return; + const range = quill.getSelection() || selection.current; + const html = event.clipboardData?.getData('text/html') || ''; + const text = event.clipboardData?.getData('text/plain') || ''; + const files = Array.from(event.clipboardData?.files || []); + try { + let delta; + if (html) { + const template = document.createElement('template'); + template.innerHTML = html; + let fileIndex = 0; + let sources; + for (const img of template.content.querySelectorAll('img')) { + const original = img.getAttribute('src') || ''; + let source = + articleImageSource(original) || + articleImageSource(img.getAttribute('data-src')); + if ( + !source && + /^(?:file:|blob:|cid:|$)/i.test(original) && + files.length + ) { + sources ??= await readFiles(files); + source = sources[fileIndex++]; + } + if (source) img.setAttribute('src', source); + else { + img.remove(); + if (active) + setImageError( + '部分图片无法粘贴,请使用可公开访问的图片地址,或粘贴不超过 2 MB 的 JPG、PNG、WebP、GIF 图片。', + ); + } + } + delta = quill.clipboard.convert({ + html: sanitizeArticleHtml(template.innerHTML), + text, + }); + } else if (files.length) { + const sources = await readFiles(files); + delta = sources + .filter(Boolean) + .reduce( + (result, source) => result.insert({ image: source }), + new Delta(), + ); + } else + delta = quill.clipboard.convert( + { text }, + quill.getFormat(range.index), + ); + if (delta.length()) insert(delta, range); + } catch { + if (active) setImageError('粘贴失败,请重试或使用纯文本粘贴'); + } finally { + finish(); + } + }; + const imageFailed = (event) => { + if (event.target.tagName === 'IMG') + setImageError( + '部分图片加载失败,请确认原图地址可公开访问,或下载图片后重新插入。', + ); + }; + // Capture before Quill's default clipboard/uploader to validate every image path. + root.addEventListener('paste', paste, true); + root.addEventListener('error', imageFailed, true); + const drop = (event) => { + event.preventDefault(); + event.stopImmediatePropagation(); + insertFiles.current?.(Array.from(event.dataTransfer?.files || [])); + }; + root.addEventListener('drop', drop, true); + const startComposition = () => { + compositionStart = quill.getContents(); + }; + const endComposition = () => { + queueMicrotask(() => { + if (!active || !compositionStart) return; + const old = compositionStart; + compositionStart = null; + quill.update(); + update(old.diff(quill.getContents()), old); + }); + }; + root.addEventListener('compositionstart', startComposition); + root.addEventListener('compositionend', endComposition); + return () => { + active = false; + callbacks.current.onBusyChange?.(false); + quill.off('text-change', update); + quill.off('editor-change', updateSelectionFromEditor); + root.removeEventListener('paste', paste, true); + root.removeEventListener('error', imageFailed, true); + root.removeEventListener('drop', drop, true); + root.removeEventListener('compositionstart', startComposition); + root.removeEventListener('compositionend', endComposition); + quill.enable(false); + instance.current = null; + insertFiles.current = null; + mount.remove(); + container.classList.remove('ql-container'); + }; + }, []); + + useEffect(() => { + const quill = instance.current; + if (!quill) return; + quill.enable(!disabled && !busy); + quill.root.setAttribute('aria-invalid', String(invalid)); + quill.root.setAttribute('aria-label', label); + // Quill renders placeholder text via CSS, keeping it outside saved HTML. + quill.root.setAttribute('data-placeholder', placeholder); + quill.root.setAttribute('aria-placeholder', placeholder); + }, [disabled, busy, invalid, label, placeholder]); + + useEffect(() => { + const quill = instance.current; + if (!quill || value === lastHtml.current) return; + quill.setContents( + quill.clipboard.convert({ html: sanitizeArticleHtml(value) }), + 'silent', + ); + quill.history.clear(); + lastHtml.current = value; + selection.current = { index: 0, length: 0 }; + setCount(countRichText(quill.getText())); + setFormat({}); + }, [value]); + + const run = (command) => { + const quill = instance.current; + if (!quill || disabled || busy) return; + const range = { ...selection.current }; + quill.focus(); + quill.setSelection(range, 'silent'); + command(quill); + setFormat(quill.getFormat()); + }; + const tools = [ + ['加粗', Bold, (q) => q.format('bold', !format.bold, 'user'), format.bold], + [ + '斜体', + Italic, + (q) => q.format('italic', !format.italic, 'user'), + format.italic, + ], + [ + '下划线', + Underline, + (q) => q.format('underline', !format.underline, 'user'), + format.underline, + ], + [ + '项目列表', + List, + (q) => + q.format('list', format.list === 'bullet' ? false : 'bullet', 'user'), + format.list === 'bullet', + ], + [ + '有序列表', + ListOrdered, + (q) => + q.format('list', format.list === 'ordered' ? false : 'ordered', 'user'), + format.list === 'ordered', + ], + [ + '引用', + Quote, + (q) => q.format('blockquote', !format.blockquote, 'user'), + format.blockquote, + ], + ['撤销', Undo2, (q) => q.history.undo()], + ['重做', Redo2, (q) => q.history.redo()], + [ + '清除格式', + Eraser, + (q) => + q.removeFormat( + selection.current.index, + selection.current.length || 1, + 'user', + ), + ], + ]; + return ( +
+
+ + {tools.map(([name, Icon, command, selected = false]) => ( + + ))} + + + insertFiles.current?.(Array.from(event.target.files || [])) + } + /> +
+
+ {imageError && ( +
+ {imageError} +
+ )} +
+ {busy + ? '图片处理中…' + : `${count}${maxLength ? ` / ${maxLength}` : ''} 字`} +
+
+ ); +} diff --git a/src/components/common/ui/SelectableButtonGroup.jsx b/src/components/common/ui/SelectableButtonGroup.jsx index 3fe24908..6d88b1a4 100644 --- a/src/components/common/ui/SelectableButtonGroup.jsx +++ b/src/components/common/ui/SelectableButtonGroup.jsx @@ -153,10 +153,9 @@ const SelectableButtonGroup = ({ }} > {withCheckbox && ( - + )} {showSkeleton ? ( - + ) : ( title )} diff --git a/src/components/common/ui/richTextContent.js b/src/components/common/ui/richTextContent.js new file mode 100644 index 00000000..f0f889b5 --- /dev/null +++ b/src/components/common/ui/richTextContent.js @@ -0,0 +1,86 @@ +/* +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 { articleImageSource } from './richTextImages.js'; + +const TAGS = new Set([ + 'P', + 'DIV', + 'H2', + 'H3', + 'BR', + 'B', + 'STRONG', + 'I', + 'EM', + 'U', + 'UL', + 'OL', + 'LI', + 'IMG', + 'SPAN', + 'BLOCKQUOTE', +]); + +export function sanitizeArticleHtml(html) { + const template = document.createElement('template'); + template.innerHTML = String(html || ''); + const clean = (node) => { + for (const child of [...node.children]) { + if ( + [ + 'SCRIPT', + 'STYLE', + 'IFRAME', + 'OBJECT', + 'SVG', + 'MATH', + 'LINK', + 'META', + ].includes(child.tagName) + ) { + child.remove(); + continue; + } + clean(child); + if (!TAGS.has(child.tagName)) { + child.replaceWith(...child.childNodes); + continue; + } + const src = child.getAttribute('src'); + for (const attribute of [...child.attributes]) + child.removeAttribute(attribute.name); + if (child.tagName === 'IMG') { + const source = articleImageSource(src); + if (source) { + child.setAttribute('src', source); + child.setAttribute('alt', '文章配图'); + } else child.remove(); + } + } + }; + clean(template.content); + // Quill images are inline embeds; standalone images need their own paragraph. + for (const child of [...template.content.children]) { + if (child.tagName !== 'IMG') continue; + const paragraph = document.createElement('p'); + child.replaceWith(paragraph); + paragraph.append(child); + } + return template.innerHTML; +} diff --git a/src/components/common/ui/richTextImages.js b/src/components/common/ui/richTextImages.js new file mode 100644 index 00000000..837e02a3 --- /dev/null +++ b/src/components/common/ui/richTextImages.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 ARTICLE_IMAGE_LIMIT = 2 * 1024 * 1024; +export const ARTICLE_IMAGE_TYPES = [ + 'image/jpeg', + 'image/png', + 'image/webp', + 'image/gif', +]; + +export function articleImageSource(value) { + const source = String(value || '').trim(); + if (source.startsWith('data:')) { + const match = + /^data:(image\/(?:png|jpeg|webp|gif));base64,([A-Za-z0-9+/]+={0,2})$/i.exec( + source, + ); + if (!match || match[2].length % 4) return ''; + const bytes = + (match[2].length * 3) / 4 - (match[2].match(/=+$/)?.[0].length || 0); + return bytes > 0 && bytes <= ARTICLE_IMAGE_LIMIT ? source : ''; + } + try { + const url = new URL(source); + return ['http:', 'https:'].includes(url.protocol) && + !url.username && + !url.password + ? url.href + : ''; + } catch { + return ''; + } +} + +export async function readArticleImage(file) { + if (!ARTICLE_IMAGE_TYPES.includes(file.type)) + throw new Error('正文图片仅支持 JPG、PNG、WebP、GIF 格式'); + if (!file.size || file.size > ARTICLE_IMAGE_LIMIT) + throw new Error('单张正文图片大小不能超过 2 MB,且不能为空'); + try { + const bitmap = await createImageBitmap(file); + bitmap.close(); + } catch { + throw new Error('无法读取图片,请选择有效的图片文件'); + } + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(String(reader.result)); + reader.onerror = () => reject(new Error('图片读取失败,请重新选择或粘贴')); + reader.readAsDataURL(file); + }); +} diff --git a/src/components/common/ui/richTextLength.js b/src/components/common/ui/richTextLength.js new file mode 100644 index 00000000..437200ab --- /dev/null +++ b/src/components/common/ui/richTextLength.js @@ -0,0 +1,59 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { decodeHTML } from 'entities'; + +export const ARTICLE_BODY_LIMIT = 20000; + +export const countRichText = (text) => + Array.from(text.replace(/\s/g, '')).length; + +export const countArticleHtml = (html) => + countRichText(decodeHTML(String(html || '').replace(/<[^>]*>/g, ''))); + +const countDelta = (delta) => + delta.ops.reduce( + (total, op) => + total + (typeof op.insert === 'string' ? countRichText(op.insert) : 0), + 0, + ); + +// Budget only newly inserted text, keeping the original text after the caret intact. +export function limitRichTextChange(old, change, limit) { + let oldIndex = 0; + let remaining = limit - countDelta(old); + for (const op of change.ops) { + if (op.delete) + remaining += countDelta(old.slice(oldIndex, oldIndex + op.delete)); + oldIndex += op.retain || op.delete || 0; + } + remaining = Math.max(0, remaining); + const ops = change.ops.flatMap((op) => { + if (typeof op.insert !== 'string') return [op]; + const text = Array.from(op.insert) + .filter((char) => { + if (/\s/.test(char)) return true; + if (!remaining) return false; + remaining--; + return true; + }) + .join(''); + return text ? [{ ...op, insert: text }] : []; + }); + return ops; +} diff --git a/src/components/layout/PageLayout.jsx b/src/components/layout/PageLayout.jsx index ddcd375b..c361527d 100644 --- a/src/components/layout/PageLayout.jsx +++ b/src/components/layout/PageLayout.jsx @@ -77,7 +77,6 @@ const printConsoleWelcome = (status) => { }; const PageLayout = () => { - console.log('[PageLayout] Component rendering...'); const [userState, userDispatch] = useContext(UserContext); const [statusState, statusDispatch] = useContext(StatusContext); const isMobile = useIsMobile(); @@ -96,7 +95,8 @@ const PageLayout = () => { const shouldInnerPadding = location.pathname.includes('/console') && !location.pathname.startsWith('/console/chat') && - location.pathname !== '/console/playground'; + location.pathname !== '/console/playground' && + location.pathname !== '/console/website-setting'; const isConsoleRoute = location.pathname.startsWith('/console'); const showSider = isConsoleRoute && (!isMobile || drawerOpen); @@ -226,10 +226,8 @@ const PageLayout = () => { }; const loadStatus = async () => { - console.log('[PageLayout] Loading status from API...'); try { const res = await API.get('/api/status'); - console.log('[PageLayout] API response received:', res.data); const { success, data } = res.data; if (success) { statusDispatch({ type: 'set', payload: data }); @@ -243,7 +241,6 @@ const PageLayout = () => { if (data.theme_config !== undefined) { applyTheme(data.theme_config); } - console.log('[PageLayout] Status loaded successfully'); } else { console.error('[PageLayout] API returned success=false'); showError('Unable to connect to server'); diff --git a/src/components/layout/SiderBar.jsx b/src/components/layout/SiderBar.jsx index 75e78743..b8ebc5ce 100644 --- a/src/components/layout/SiderBar.jsx +++ b/src/components/layout/SiderBar.jsx @@ -27,6 +27,11 @@ import { useSidebar } from '../../hooks/common/useSidebar'; import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime'; import { isAdmin, isRoot, showError } from '../../helpers'; import { StatusContext } from '../../context/Status'; +import { UserContext } from '../../context/User'; +import { + canAccessDelegatedAdminPage, + getDelegatedSettingTabs, +} from '../../helpers/adminDelegation'; import SkeletonWrapper from './components/SkeletonWrapper'; import { CLOUD_BRAIN_UI_ENABLED } from '../../config/cloudBrainUi'; @@ -42,6 +47,8 @@ const routerMap = { log: '/console/log', midjourney: '/console/midjourney', setting: '/console/setting', + 'website-setting': '/console/website-setting', + 'demo-reservations': '/console/demo-reservations', about: '/about', detail: '/console', pricing: '/market', @@ -75,16 +82,13 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => { } = useSidebar(); const [statusState] = useContext(StatusContext); + const [userState] = useContext(UserContext); + const delegatedPermissions = statusState?.status?.AdminDelegatedSettingTabs; // 系统设置 tab 权限下放:普通管理员在被下放了至少一个 tab 时,才显示「系统设置」入口 - const delegatedSettingTabs = useMemo(() => { - try { - const raw = statusState?.status?.AdminDelegatedSettingTabs; - const parsed = raw ? JSON.parse(raw) : []; - return Array.isArray(parsed) ? parsed : []; - } catch (e) { - return []; - } - }, [statusState?.status?.AdminDelegatedSettingTabs]); + const delegatedSettingTabs = useMemo( + () => getDelegatedSettingTabs(delegatedPermissions), + [delegatedPermissions], + ); const canAccessSetting = isRoot() || (isAdmin() && delegatedSettingTabs.length > 0); @@ -284,10 +288,31 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => { to: '/setting', className: canAccessSetting ? '' : 'tableHiddle', }, + { + text: t('官网设置'), + itemKey: 'website-setting', + className: isAdmin() ? '' : 'tableHiddle', + }, + { + text: t('预约演示'), + itemKey: 'demo-reservations', + className: isAdmin() ? '' : 'tableHiddle', + }, ]; // 根据配置过滤项目 const filteredItems = items.filter((item) => { + if ( + (item.itemKey === 'website-setting' || + item.itemKey === 'demo-reservations') && + !canAccessDelegatedAdminPage( + userState?.user?.role, + delegatedPermissions, + item.itemKey, + ) + ) { + return false; + } if ( !CLOUD_BRAIN_UI_ENABLED && (item.itemKey === 'skill-platform' || @@ -315,7 +340,16 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => { }); return filteredItems; - }, [isAdmin(), isRoot(), t, isModuleVisible, canAccessSetting]); + }, [ + isAdmin(), + isRoot(), + t, + isModuleVisible, + canAccessSetting, + delegatedSettingTabs, + delegatedPermissions, + userState?.user?.role, + ]); const chatMenuItems = useMemo(() => { const items = [ @@ -597,8 +631,8 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => { )} - {/* 管理员区域 - 只在管理员时显示且配置允许时显示 */} - {isAdmin() && hasSectionVisibleModules('admin') && ( + {/* 管理员区域:按角色、权限下放及菜单配置过滤。 */} + {isAdmin() && ( <>
@@ -637,7 +671,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => { /> } onClick={toggleCollapsed} - icononly={collapsed} + aria-label={collapsed ? t('展开侧边栏') : t('收起侧边栏')} style={ collapsed ? { width: 36, height: 24, padding: 0 } diff --git a/src/components/layout/components/SkeletonWrapper.jsx b/src/components/layout/components/SkeletonWrapper.jsx index 7fbd588c..a78f9f06 100644 --- a/src/components/layout/components/SkeletonWrapper.jsx +++ b/src/components/layout/components/SkeletonWrapper.jsx @@ -52,7 +52,6 @@ const SkeletonWrapper = ({ active placeholder={ } @@ -71,7 +70,7 @@ const SkeletonWrapper = ({ loading={true} active placeholder={ - + } />
@@ -80,7 +79,6 @@ const SkeletonWrapper = ({ active placeholder={ } @@ -98,7 +96,6 @@ const SkeletonWrapper = ({ active placeholder={ @@ -113,7 +110,7 @@ const SkeletonWrapper = ({ } + placeholder={} /> ); }; @@ -125,7 +122,7 @@ const SkeletonWrapper = ({ } + placeholder={} />
); @@ -139,10 +136,7 @@ const SkeletonWrapper = ({ loading={true} active placeholder={ - + } />
@@ -164,7 +158,7 @@ const SkeletonWrapper = ({ loading={true} active placeholder={ - + } />
@@ -174,7 +168,6 @@ const SkeletonWrapper = ({ active placeholder={ } @@ -192,7 +185,6 @@ const SkeletonWrapper = ({ active placeholder={ } @@ -217,7 +209,6 @@ const SkeletonWrapper = ({ active placeholder={ @@ -230,10 +221,7 @@ const SkeletonWrapper = ({ loading={true} active placeholder={ - + } /> ); @@ -269,7 +257,6 @@ const SkeletonWrapper = ({ active placeholder={ @@ -284,22 +271,22 @@ const SkeletonWrapper = ({ {Array(2) .fill(null) .map((_, i) => ( - + ))} {Array(5) .fill(null) .map((_, i) => ( - + ))} {Array(2) .fill(null) .map((_, i) => ( - + ))} {Array(5) .fill(null) .map((_, i) => ( - + ))} ); @@ -329,7 +316,6 @@ const SkeletonWrapper = ({ active placeholder={ } @@ -350,7 +336,6 @@ const SkeletonWrapper = ({ active placeholder={ } diff --git a/src/components/layout/headerbar/LanguageSelector.jsx b/src/components/layout/headerbar/LanguageSelector.jsx index c7943154..7e1a334f 100644 --- a/src/components/layout/headerbar/LanguageSelector.jsx +++ b/src/components/layout/headerbar/LanguageSelector.jsx @@ -82,19 +82,21 @@ const LanguageSelector = ({ currentLang, onLanguageChange, t }) => { } > - + + + ); }; diff --git a/src/components/layout/headerbar/ThemeToggle.jsx b/src/components/layout/headerbar/ThemeToggle.jsx index d4771be9..4439fa47 100644 --- a/src/components/layout/headerbar/ThemeToggle.jsx +++ b/src/components/layout/headerbar/ThemeToggle.jsx @@ -251,19 +251,22 @@ const ThemeToggle = ({ theme, onThemeToggle, t }) => { } > - + className='group-hover:!opacity-80 transition-colors' + /> + + ); } else { diff --git a/src/components/settings/OperationSetting.jsx b/src/components/settings/OperationSetting.jsx index 20690d3c..1936357f 100644 --- a/src/components/settings/OperationSetting.jsx +++ b/src/components/settings/OperationSetting.jsx @@ -18,7 +18,7 @@ For commercial licensing, please contact support@quantumnous.com */ import React, { useCallback, useEffect, useRef, useState } from 'react'; -import { Card, Spin } from '@douyinfe/semi-ui'; +import { Banner, Button, Card, Spin } from '@douyinfe/semi-ui'; import SettingsGeneral from '../../pages/Setting/Operation/SettingsGeneral'; import SettingsLanguage from '../../pages/Setting/Operation/SettingsLanguage'; import SettingsHeaderNavModules from '../../pages/Setting/Operation/SettingsHeaderNavModules'; @@ -35,7 +35,34 @@ import SettingsFallback from '../../pages/Setting/Operation/SettingsFallback'; import SettingsTheme from '../../pages/Setting/Operation/SettingsTheme'; import SettingsAdminDelegation from '../../pages/Setting/Operation/SettingsAdminDelegation'; import SettingsSkillInject from '../../pages/Setting/Operation/SettingsSkillInject'; -import { API, showError, toBoolean } from '../../helpers'; +import { API, toBoolean } from '../../helpers'; + +const ProgressiveSettingsSections = ({ children, loading }) => { + const sections = React.Children.toArray(children); + const [visibleCount, setVisibleCount] = useState(1); + + useEffect(() => { + if (visibleCount >= sections.length) return; + // Yield between sections so mounting all forms cannot block one task. + const timer = setTimeout(() => setVisibleCount((count) => count + 1), 0); + return () => clearTimeout(timer); + }, [visibleCount, sections.length]); + + return ( + + {sections.slice(0, visibleCount)} + {visibleCount < sections.length && ( +
+ +
+ )} +
+ ); +}; const OperationSetting = () => { let [inputs, setInputs] = useState({ @@ -98,6 +125,13 @@ const OperationSetting = () => { /* 提示词采集(实验性,方案 §35 一期) */ GlobalPromptArchiveEnabled: false, + /* Skill switches arrive as strings from the options API. */ + SkillMarketRequireAuth: false, + SkillInjectEnabled: false, + SkillInjectMaxSkills: '5', + SkillInjectMaxRunes: '3000', + SkillInjectCacheTTLSeconds: '60', + /* 监控设置 */ ChannelDisableThreshold: 0, QuotaRemindThreshold: 0, @@ -135,13 +169,15 @@ const OperationSetting = () => { 'fallback_setting.max_attempts_per_request': 10, }); - let [loading, setLoading] = useState(false); + const [loading, setLoading] = useState(true); + const [optionsLoaded, setOptionsLoaded] = useState(false); + const [loadError, setLoadError] = useState(''); const inputTypes = useRef(inputs); const getOptions = useCallback(async () => { const res = await API.get('/api/option/'); const { success, message, data } = res.data; - if (success) { + if (success && Array.isArray(data)) { let newInputs = {}; data.forEach((item) => { if (typeof inputTypes.current[item.key] === 'boolean') { @@ -153,16 +189,17 @@ const OperationSetting = () => { setInputs(newInputs); } else { - showError(message); + throw new Error(message || '运营设置读取失败,请重试'); } }, []); const onRefresh = useCallback(async () => { try { setLoading(true); + setLoadError(''); await getOptions(); - // showSuccess('刷新成功'); + setOptionsLoaded(true); } catch (error) { - showError('刷新失败'); + setLoadError(error.message || '运营设置读取失败,请重试'); } finally { setLoading(false); } @@ -172,9 +209,26 @@ const OperationSetting = () => { onRefresh(); }, [onRefresh]); + const errorBanner = loadError && ( + + + + ); + + // Never mount editable defaults when the initial request fails. + if (!optionsLoaded) { + if (loadError) return errorBanner; + return ( + + ); + } + return ( <> - + {errorBanner} + {/* 通用设置 */} @@ -235,7 +289,7 @@ const OperationSetting = () => { {/* 普通管理员可见的系统设置页(权限下放) */} - + ); }; diff --git a/src/constants/settingTabs.js b/src/constants/settingTabs.js index 2f8cac05..1e633590 100644 --- a/src/constants/settingTabs.js +++ b/src/constants/settingTabs.js @@ -54,3 +54,16 @@ export const DELEGATABLE_SETTING_TABS = SETTING_TABS.filter( !ALWAYS_ADMIN_VISIBLE_TABS.includes(t.key) && !ROOT_ONLY_SETTING_TABS.includes(t.key), ); + +// Standalone admin pages share delegation settings, but are not settings tabs. +export const DELEGATABLE_ADMIN_PAGES = [ + { key: 'website-setting', labelKey: '官网设置' }, + { key: 'demo-reservations', labelKey: '预约演示' }, +]; + +export const ADMIN_DELEGATION_OPTIONS = [ + ...DELEGATABLE_SETTING_TABS, + ...DELEGATABLE_ADMIN_PAGES, +]; + +export const ADMIN_DELEGATION_OPTION_KEY = 'AdminDelegatedSettingTabs'; diff --git a/src/constants/sidebarModules.js b/src/constants/sidebarModules.js index cbe8c924..f10505f9 100644 --- a/src/constants/sidebarModules.js +++ b/src/constants/sidebarModules.js @@ -67,6 +67,8 @@ export const getDefaultSidebarModulesAdmin = () => ({ order: true, invoice: true, setting: true, + 'website-setting': true, + 'demo-reservations': true, }, analytics: { enabled: true, diff --git a/src/helpers/adminDelegation.js b/src/helpers/adminDelegation.js new file mode 100644 index 00000000..30b07f85 --- /dev/null +++ b/src/helpers/adminDelegation.js @@ -0,0 +1,50 @@ +/* +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 { + DELEGATABLE_ADMIN_PAGES, + DELEGATABLE_SETTING_TABS, +} from '../constants/settingTabs.js'; + +export function parseAdminDelegation(raw) { + try { + const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw; + return Array.isArray(parsed) + ? [...new Set(parsed.filter((key) => typeof key === 'string'))] + : []; + } catch { + return []; + } +} + +export function getDelegatedSettingTabs(raw) { + return parseAdminDelegation(raw).filter((key) => + DELEGATABLE_SETTING_TABS.some((tab) => tab.key === key), + ); +} + +export function canAccessDelegatedAdminPage(role, raw, permission) { + if (typeof role !== 'number' || !Number.isFinite(role) || role < 10) { + return false; + } + if (!DELEGATABLE_ADMIN_PAGES.some((page) => page.key === permission)) { + return false; + } + return role >= 100 || parseAdminDelegation(raw).includes(permission); +} diff --git a/src/helpers/auth.jsx b/src/helpers/auth.jsx index 24557fc3..ef60f616 100644 --- a/src/helpers/auth.jsx +++ b/src/helpers/auth.jsx @@ -21,6 +21,9 @@ import React, { useContext } from 'react'; import { Navigate, useLocation } from 'react-router-dom'; import { history } from './history'; import { UserContext } from '../context/User'; +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 { DEFAULT_LOGIN_REDIRECT, @@ -95,8 +98,9 @@ function PrivateRoute({ children }) { ); } -export function AdminRoute({ children }) { +export function AdminRoute({ children, permission }) { const [userState] = useContext(UserContext); + const [statusState] = useContext(StatusContext); const location = useLocation(); const cachedUser = getUserData(); @@ -113,6 +117,21 @@ export function AdminRoute({ children }) { ); } if (typeof userState.user.role === 'number' && userState.user.role >= 10) { + if (permission) { + // Wait for server permissions before deciding access for delegated admins. + if (userState.user.role < 100 && !statusState?.status) { + return ; + } + if ( + !canAccessDelegatedAdminPage( + userState.user.role, + statusState?.status?.[ADMIN_DELEGATION_OPTION_KEY], + permission, + ) + ) { + return ; + } + } return children; } return ; diff --git a/src/helpers/render.jsx b/src/helpers/render.jsx index e278c25c..3918fd97 100644 --- a/src/helpers/render.jsx +++ b/src/helpers/render.jsx @@ -77,6 +77,8 @@ import { PieChart, Building2, Handshake, + Globe, + CalendarDays, } from 'lucide-react'; // 获取侧边栏Lucide图标组件 @@ -128,6 +130,10 @@ export function getLucideIcon(key, selected = false) { return ; case 'setting': return ; + case 'website-setting': + return ; + case 'demo-reservations': + return ; default: return ; } diff --git a/src/helpers/websiteApi.js b/src/helpers/websiteApi.js new file mode 100644 index 00000000..dcfed486 --- /dev/null +++ b/src/helpers/websiteApi.js @@ -0,0 +1,48 @@ +/* +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 { API } from './api'; +import { showError } from './utils'; + +export async function requestWebsite( + method, + url, + body, + fallback = '请求失败,请稍后重试', +) { + let response; + try { + const options = { skipErrorHandler: true, timeout: 20000 }; + response = + method === 'get' + ? await API.get(url, options) + : await API.post(url, body, options); + } catch (error) { + if (error.response?.status === 401) { + showError(error); + throw new Error('登录状态已失效,请重新登录'); + } + if (error.response?.status === 429) + throw new Error('请求过于频繁,请稍后重试'); + throw new Error(error.response?.data?.message || fallback); + } + if (response.data?.success !== true) + throw new Error(response.data?.message || fallback); + return response.data.data; +} diff --git a/src/pages/AdminMenuPreview/index.jsx b/src/pages/AdminMenuPreview/index.jsx new file mode 100644 index 00000000..2f013a45 --- /dev/null +++ b/src/pages/AdminMenuPreview/index.jsx @@ -0,0 +1,88 @@ +/* +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 React from 'react'; +import { Card, Input, Tag, Typography } from '@douyinfe/semi-ui'; +import { CalendarDays, Globe } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; + +export default function AdminMenuPreview({ type }) { + const { t } = useTranslation(); + const isWebsite = type === 'website'; + const Icon = isWebsite ? Globe : CalendarDays; + const title = isWebsite ? t('官网设置') : t('预约演示'); + + return ( +
+
+ + + {title} + + {t('功能预览')} +
+ + {t('当前为示例内容,仅用于预览页面,暂未接入数据保存。')} + + {isWebsite ? ( + +
+ {[ + [t('网站名称'), t('Monkey AI 官网')], + [t('官网地址'), 'https://www.example.com'], + [t('首页标题'), t('让 AI 为业务创造更多价值')], + [t('联系邮箱'), 'contact@example.com'], + ].map(([label, value]) => ( + + ))} +
+
+ ) : ( + +
+ + + + {['联系人', '企业名称', '演示需求', '状态'].map((label) => ( + + ))} + + + + + + + + + + +
+ {t(label)} +
{t('示例联系人')}{t('示例科技有限公司')}{t('企业 AI 应用演示')} + {t('待联系')} +
+
+
+ )} +
+ ); +} diff --git a/src/pages/DemoReservations/README.md b/src/pages/DemoReservations/README.md new file mode 100644 index 00000000..5c984378 --- /dev/null +++ b/src/pages/DemoReservations/README.md @@ -0,0 +1,26 @@ +# 预约演示列表 + +页面复用 CardPro、CardTable、CompactModeToggle 和 createCardProPagination。 +桌面端搜索栏靠左,移动端沿用系统的操作区展开和卡片展示方式。 + +## 已接入接口 + +GET /api/website/demo-requests,通过项目共享 API 实例发送 Cookie 和 New-Api-User。 +不再使用本地演示列表。业务 success 必须严格为 true,否则显示后端 message 或错误提示。 + +筛选字段:name、contact、companyName,去除首尾空白并以 URLSearchParams 编码。 +模糊搜索由后端执行,三个条件为 AND。请求分页为 p 和 page_size; +响应读取 data.items、data.total、data.page 和 data.page_size。 + +查询、重置和切换每页条数回到第一页;翻页保留已提交的筛选条件。 +页面忽略过期请求结果,错误时清空表格并显示错误原因。 +公司名称与需求分别使用 companyName 和 requirement,不使用原型字段 company/requirements。 +需求列表最多显示三行,保留内部换行,不提供查看完整需求按钮或弹窗。 + +## 模拟提交与验收 + +本地脚本 scripts/seed-demo-requests.mjs 默认仅预览,添加 --submit 才真实新增三条联调测试预约。 +页面初始化不会新增数据。脚本和测试文件已加入 Git 忽略规则。 + +运行 npm run test:e2e 验证桌面与移动端交互;npm run test:e2e:report 查看本地报告。 +完整验收要求见 docs/website-api-acceptance.md,模拟接口验收与真实服务验收分别记录。 diff --git a/src/pages/DemoReservations/index.jsx b/src/pages/DemoReservations/index.jsx new file mode 100644 index 00000000..88052bbc --- /dev/null +++ b/src/pages/DemoReservations/index.jsx @@ -0,0 +1,294 @@ +/* +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 React, { useEffect, useMemo, useRef, useState } from 'react'; +import { + Banner, + Button, + Empty, + Form, + Select, + Spin, + Typography, +} from '@douyinfe/semi-ui'; +import { useTranslation } from 'react-i18next'; +import CardPro from '../../components/common/ui/CardPro'; +import CardTable from '../../components/common/ui/CardTable'; +import CompactModeToggle from '../../components/common/ui/CompactModeToggle'; +import { + IllustrationNoResult, + IllustrationNoResultDark, +} from '../../components/common/illustrations'; +import { createCardProPagination } from '../../helpers/utils'; +import { useIsMobile } from '../../hooks/common/useIsMobile'; +import { useTableCompactMode } from '../../hooks/common/useTableCompactMode'; +import { fetchDemoReservations } from './reservationsApi'; + +const EMPTY_FILTERS = { name: '', contact: '', companyName: '' }; + +export default function DemoReservations() { + const { t } = useTranslation(); + const isMobile = useIsMobile(); + const [compactMode, setCompactMode] = + useTableCompactMode('demo-reservations'); + const formRef = useRef(null); + const [query, setQuery] = useState({ + ...EMPTY_FILTERS, + page: 1, + pageSize: 10, + }); + const [result, setResult] = useState({ items: [], total: 0 }); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(''); + + useEffect(() => { + let active = true; + setLoading(true); + setError(''); + fetchDemoReservations(query) + .then((data) => { + if (active) setResult(data); + }) + .catch((error) => { + if (active) { + setError(error.message || '预约信息加载失败,请重新查询'); + setResult({ items: [], total: 0 }); + } + }) + .finally(() => { + if (active) setLoading(false); + }); + return () => { + active = false; + }; + }, [query]); + + const columns = useMemo( + () => + [ + ['name', '姓名', 100], + ['contact', '联系方式', 210], + ['companyName', '公司名称', 180], + ['position', '职位', 140], + ['industry', '行业', 160], + ['interest', '关注方向', 190], + ['requirement', '需求', 360], + ].map(([dataIndex, title, width]) => ({ + title: t(title), + dataIndex, + key: dataIndex, + ...(compactMode ? {} : { width }), + render: (value) => + dataIndex === 'requirement' && value ? ( +
+ + {value} + +
+ ) : ( + + {value || '—'} + + ), + })), + [t, compactMode], + ); + + const reset = () => { + formRef.current?.reset(); + setQuery((previous) => ({ + ...EMPTY_FILTERS, + page: 1, + pageSize: previous.pageSize, + })); + }; + + const changePageSize = (pageSize) => + setQuery((previous) => ({ ...previous, page: 1, pageSize })); + const pagination = createCardProPagination({ + currentPage: result.page ?? query.page, + pageSize: result.page_size ?? query.pageSize, + total: result.total, + onPageChange: (page) => setQuery((previous) => ({ ...previous, page })), + onPageSizeChange: changePageSize, + preventPageChangeOnPageSizeChange: true, + isMobile, + t, + }); + + return ( +
+ + +
+ + {t('预约演示')} + + + {t('查看官网访客提交的预约信息,支持模糊查询与分页。')} + +
+ +
+ } + actionsArea={ +
+
(formRef.current = api)} + onSubmit={(values) => + setQuery((previous) => ({ + name: (values.name || '').trim(), + contact: (values.contact || '').trim(), + companyName: (values.companyName || '').trim(), + page: 1, + pageSize: previous.pageSize, + })) + } + allowEmpty + autoComplete='off' + layout='horizontal' + className='w-full md:w-auto' + > +
+ {[ + ['name', '请输入姓名'], + ['contact', '请输入联系方式'], + ['companyName', '请输入公司名称'], + ].map(([field, placeholder]) => ( +
+ +
+ ))} +
+ + +
+
+
+
+ } + paginationArea={ + isMobile && result.total > 0 ? ( +
+
+ + {t('共')} {result.total} {t('条')} + + change('title', value)} + />, + true, + )} +
+ {field( + 'category', + '所属分类', + change('date', value)} + />, + true, + )} +
+ {field( + 'subtitle', + '详情副标题', + change('subtitle', value)} + />, + )} + {field( + 'summary', + '卡片摘要', +