feat: 完善官网配置、预约管理与文章编辑

This commit is contained in:
zhanjunhao
2026-10-31 19:02:58 +08:00
parent 7b80c3bbb3
commit 1bf13bc226
54 changed files with 4898 additions and 203 deletions
+11
View File
@@ -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/
+28
View File
@@ -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、令牌等敏感信息。
- 测试失败时检查错误与报告,修复后重跑受影响用例;未执行或受环境限制的项目如实说明。
- 交付时简要说明完成内容、实际验证结果和待验收项,不将未完成验证的功能描述为验收通过。
+566
View File
@@ -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 上传配置和长期图片地址。
+60
View File
@@ -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,修复后重跑受影响用例。未执行或受环境限制的项目必须明确记录,不能计为通过。
+108
View File
@@ -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",
+6
View File
@@ -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",
+66
View File
@@ -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 <https://www.gnu.org/licenses/>.
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: '' },
},
});
+22
View File
@@ -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() {
</AdminRoute>
}
/>
<Route
path='/console/website-setting'
element={
<AdminRoute permission='website-setting'>
<Suspense fallback={<Loading />}>
<WebsiteSettings />
</Suspense>
</AdminRoute>
}
/>
<Route
path='/console/demo-reservations'
element={
<AdminRoute permission='demo-reservations'>
<Suspense fallback={<Loading />}>
<DemoReservations />
</Suspense>
</AdminRoute>
}
/>
<Route
path='/console/personal'
element={
+1 -1
View File
@@ -51,7 +51,7 @@ const CardPro = ({
searchArea,
paginationArea, // 新增分页区域
// 卡片属性
shadows = '',
shadows,
bordered = true,
// 自定义样式
style,
+2 -3
View File
@@ -134,7 +134,7 @@ const CardTable = ({
if (!col.title) {
return (
<div key={idx} className='mt-2 flex justify-end'>
<Skeleton.Title active style={{ width: 100, height: 24 }} />
<Skeleton.Title style={{ width: 100, height: 24 }} />
</div>
);
}
@@ -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)' }}
>
<Skeleton.Title active style={{ width: 80, height: 14 }} />
<Skeleton.Title style={{ width: 80, height: 14 }} />
<Skeleton.Title
active
style={{
width: `${50 + (idx % 3) * 10}%`,
maxWidth: 180,
+125
View File
@@ -0,0 +1,125 @@
.rich-text-editor {
border: 1px solid var(--semi-color-border);
border-radius: 4px;
overflow: hidden;
background: var(--semi-color-bg-2);
}
.rich-text-editor.is-invalid {
border-color: var(--semi-color-danger);
}
.rich-text-editor:focus-within {
border-color: var(--semi-color-primary);
}
.rich-text-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
padding: 8px;
border-bottom: 1px solid var(--semi-color-border);
background: var(--semi-color-fill-0);
}
.rich-text-toolbar button,
.rich-text-toolbar select {
display: inline-flex;
align-items: center;
justify-content: center;
height: 30px;
min-width: 30px;
padding: 4px 6px;
border: 0;
border-radius: 4px;
background: transparent;
color: var(--semi-color-text-1);
cursor: pointer;
}
.rich-text-toolbar select {
width: 112px;
margin-right: 4px;
}
.rich-text-toolbar button:hover,
.rich-text-toolbar button[aria-pressed='true'] {
background: var(--semi-color-primary-light-default);
color: var(--semi-color-primary);
}
.rich-text-toolbar button:focus-visible,
.rich-text-toolbar select:focus-visible {
outline: 2px solid var(--semi-color-primary);
outline-offset: 1px;
}
.rich-text-toolbar button:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.rich-text-content .ql-editor {
min-height: 300px;
padding: 16px;
outline: none;
line-height: 1.9;
color: var(--semi-color-text-0);
overflow-wrap: anywhere;
}
.rich-text-content .ql-editor > * + * {
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;
}
+509
View File
@@ -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 <https://www.gnu.org/licenses/>.
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 (
<div
className={`rich-text-editor ${invalid ? 'is-invalid' : ''}`}
aria-busy={busy}
>
<div
className='rich-text-toolbar'
role='toolbar'
aria-label='富文本工具栏'
>
<select
aria-label='段落格式'
disabled={disabled || busy}
value={format.header || ''}
onChange={(event) =>
run((q) =>
q.format('header', Number(event.target.value) || false, 'user'),
)
}
>
<option value=''>正文段落</option>
<option value='2'>二级标题</option>
<option value='3'>三级标题</option>
</select>
{tools.map(([name, Icon, command, selected = false]) => (
<button
key={name}
type='button'
title={name}
aria-label={name}
aria-pressed={Boolean(selected)}
disabled={disabled || busy}
onMouseDown={(event) => event.preventDefault()}
onClick={() => run(command)}
>
<Icon size={16} />
</button>
))}
<button
type='button'
title='插入正文图片(单张不超过 2 MB)'
aria-label='插入正文图片'
disabled={disabled || busy}
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
picker.current.value = '';
picker.current.click();
}}
>
<ImagePlus size={16} />
</button>
<input
ref={picker}
type='file'
accept={ARTICLE_IMAGE_TYPES.join(',')}
hidden
multiple
onChange={(event) =>
insertFiles.current?.(Array.from(event.target.files || []))
}
/>
</div>
<div ref={host} className='rich-text-content' />
{imageError && (
<div className='rich-text-image-error' role='alert'>
{imageError}
</div>
)}
<div className='rich-text-count'>
{busy
? '图片处理中…'
: `${count}${maxLength ? ` / ${maxLength}` : ''} 字`}
</div>
</div>
);
}
@@ -153,10 +153,9 @@ const SelectableButtonGroup = ({
}}
>
{withCheckbox && (
<Skeleton.Title active style={{ width: 14, height: 14 }} />
<Skeleton.Title style={{ width: 14, height: 14 }} />
)}
<Skeleton.Title
active
style={{
width: `${60 + (index % 3) * 20}px`,
height: 14,
@@ -264,7 +263,7 @@ const SelectableButtonGroup = ({
{title && (
<Divider margin='12px' align='left'>
{showSkeleton ? (
<Skeleton.Title active style={{ width: 80, height: 14 }} />
<Skeleton.Title style={{ width: 80, height: 14 }} />
) : (
title
)}
@@ -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 <https://www.gnu.org/licenses/>.
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;
}
@@ -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 <https://www.gnu.org/licenses/>.
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);
});
}
@@ -0,0 +1,59 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { 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;
}
+2 -5
View File
@@ -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');
+47 -13
View File
@@ -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() && (
<>
<Divider className='sidebar-divider' />
<div>
@@ -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 }
@@ -52,7 +52,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Title
active
style={{ width: isMobile ? 40 : width, height }}
/>
}
@@ -71,7 +70,7 @@ const SkeletonWrapper = ({
loading={true}
active
placeholder={
<Skeleton.Avatar active size='extra-small' className='shadow-sm' />
<Skeleton.Avatar size='extra-small' className='shadow-sm' />
}
/>
<div className='ml-1.5 mr-1'>
@@ -80,7 +79,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Title
active
style={{ width: isMobile ? 15 : width, height: 12 }}
/>
}
@@ -98,7 +96,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Image
active
className={`absolute inset-0 !rounded-full ${className}`}
style={{ width: '100%', height: '100%' }}
/>
@@ -113,7 +110,7 @@ const SkeletonWrapper = ({
<Skeleton
loading={true}
active
placeholder={<Skeleton.Title active style={{ width, height: 24 }} />}
placeholder={<Skeleton.Title style={{ width, height: 24 }} />}
/>
);
};
@@ -125,7 +122,7 @@ const SkeletonWrapper = ({
<Skeleton
loading={true}
active
placeholder={<Skeleton.Title active style={{ width, height }} />}
placeholder={<Skeleton.Title style={{ width, height }} />}
/>
</div>
);
@@ -139,10 +136,7 @@ const SkeletonWrapper = ({
loading={true}
active
placeholder={
<Skeleton.Title
active
style={{ width, height, borderRadius: 9999 }}
/>
<Skeleton.Title style={{ width, height, borderRadius: 9999 }} />
}
/>
</div>
@@ -164,7 +158,7 @@ const SkeletonWrapper = ({
loading={true}
active
placeholder={
<Skeleton.Avatar active size='extra-small' shape='square' />
<Skeleton.Avatar size='extra-small' shape='square' />
}
/>
</div>
@@ -174,7 +168,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Title
active
style={{ width: width || 80, height: height || 14 }}
/>
}
@@ -192,7 +185,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Title
active
style={{ width: width || 60, height: height || 12 }}
/>
}
@@ -217,7 +209,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Avatar
active
shape='square'
style={{ width: ICON_SIZE, height: ICON_SIZE }}
/>
@@ -230,10 +221,7 @@ const SkeletonWrapper = ({
loading={true}
active
placeholder={
<Skeleton.Title
active
style={{ width: labelWidth, height: TEXT_HEIGHT }}
/>
<Skeleton.Title style={{ width: labelWidth, height: TEXT_HEIGHT }} />
}
/>
);
@@ -269,7 +257,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Avatar
active
shape='square'
style={{ width: ICON_SIZE, height: ICON_SIZE }}
/>
@@ -284,22 +271,22 @@ const SkeletonWrapper = ({
{Array(2)
.fill(null)
.map((_, i) => (
<CollapsedRow keyPrefix='c-chat' index={i} />
<CollapsedRow key={i} keyPrefix='c-chat' index={i} />
))}
{Array(5)
.fill(null)
.map((_, i) => (
<CollapsedRow keyPrefix='c-console' index={i} />
<CollapsedRow key={i} keyPrefix='c-console' index={i} />
))}
{Array(2)
.fill(null)
.map((_, i) => (
<CollapsedRow keyPrefix='c-personal' index={i} />
<CollapsedRow key={i} keyPrefix='c-personal' index={i} />
))}
{Array(5)
.fill(null)
.map((_, i) => (
<CollapsedRow keyPrefix='c-admin' index={i} />
<CollapsedRow key={i} keyPrefix='c-admin' index={i} />
))}
</div>
);
@@ -329,7 +316,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Title
active
style={{ width: sec.titleWidth, height: TITLE_HEIGHT }}
/>
}
@@ -350,7 +336,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Title
active
style={{ width: sec.titleWidth, height: TITLE_HEIGHT }}
/>
}
@@ -82,19 +82,21 @@ const LanguageSelector = ({ currentLang, onLanguageChange, t }) => {
</Dropdown.Menu>
}
>
<Button
icon={<Globe size={20} />}
aria-label={t('common.changeLanguage')}
theme='borderless'
type='tertiary'
className='!w-8 !h-8 sm:!w-9 sm:!h-9 !flex !items-center !justify-center hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !rounded-full !transition-all !duration-200 hover:!scale-[1.08] active:!scale-95'
style={{
color:
actualTheme === 'dark'
? 'rgba(243,244,246,0.9)'
: 'rgba(75,85,99,1)',
}}
/>
<span className='inline-flex'>
<Button
icon={<Globe size={20} />}
aria-label={t('common.changeLanguage')}
theme='borderless'
type='tertiary'
className='!w-8 !h-8 sm:!w-9 sm:!h-9 !flex !items-center !justify-center hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !rounded-full !transition-all !duration-200 hover:!scale-[1.08] active:!scale-95'
style={{
color:
actualTheme === 'dark'
? 'rgba(243,244,246,0.9)'
: 'rgba(75,85,99,1)',
}}
/>
</span>
</Dropdown>
);
};
@@ -133,19 +133,21 @@ const MobileNavMenu = ({ mainNavLinks, userState, t }) => {
</Dropdown.Menu>
}
>
<Button
theme='borderless'
type='tertiary'
aria-label={t('主导航')}
aria-haspopup='menu'
aria-expanded={visible}
icon={<Compass size={16} />}
className='!ml-1 !px-2 !h-8 max-w-[9rem] !rounded-xl !text-current hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !transition-all !duration-200 active:!scale-95 [&_.semi-button-content]:min-w-0'
>
<span className='ml-1 text-[13px] font-semibold truncate'>
{activeItem ? activeItem.text : t('导航')}
</span>
</Button>
<span className='inline-flex'>
<Button
theme='borderless'
type='tertiary'
aria-label={t('主导航')}
aria-haspopup='menu'
aria-expanded={visible}
icon={<Compass size={16} />}
className='!ml-1 !px-2 !h-8 max-w-[9rem] !rounded-xl !text-current hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !transition-all !duration-200 active:!scale-95 [&_.semi-button-content]:min-w-0'
>
<span className='ml-1 text-[13px] font-semibold truncate'>
{activeItem ? activeItem.text : t('导航')}
</span>
</Button>
</span>
</Dropdown>
);
};
+16 -13
View File
@@ -251,19 +251,22 @@ const ThemeToggle = ({ theme, onThemeToggle, t }) => {
</Dropdown.Menu>
}
>
<Button
icon={currentButtonIcon}
aria-label={t('切换主题')}
theme='borderless'
type='tertiary'
className='!w-8 !h-8 sm:!w-9 sm:!h-9 !flex !items-center !justify-center hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !rounded-full !transition-all !duration-200 hover:!scale-[1.08] active:!scale-95'
style={{
color:
actualTheme === 'dark'
? 'rgba(243,244,246,0.9)'
: 'rgba(75,85,99,1)',
}}
/>
{/* Semi can resolve a DOM trigger directly without findDOMNode. */}
<span className='inline-flex'>
<Button
icon={currentButtonIcon}
aria-label={t('切换主题')}
theme='borderless'
type='tertiary'
className='!w-8 !h-8 sm:!w-9 sm:!h-9 !flex !items-center !justify-center hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !rounded-full !transition-all !duration-200 hover:!scale-[1.08] active:!scale-95'
style={{
color:
actualTheme === 'dark'
? 'rgba(243,244,246,0.9)'
: 'rgba(75,85,99,1)',
}}
/>
</span>
</Dropdown>
);
};
+35 -33
View File
@@ -300,41 +300,43 @@ const UserArea = ({
</Dropdown.Menu>
}
>
<Button
theme='borderless'
type='tertiary'
className='flex items-center gap-2 !pl-1.5 !pr-2.5 !py-1.5 !h-10 !rounded-full hover:!bg-brand/10 dark:hover:!bg-brand/15 !bg-transparent !transition-all !duration-200 hover:!-translate-y-0.5 group'
>
<div className='relative'>
<Avatar
size='small'
src={avatarUrl}
color={stringToColor(displayName)}
className='!w-7 !h-7 !text-xs ring-2 ring-white dark:ring-gray-800 group-hover:!ring-brand/40 dark:group-hover:!ring-brand/50 transition-all'
>
{displayName[0].toUpperCase()}
</Avatar>
{/* 在线状态点 */}
<span className='absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 bg-emerald-500 border-2 border-white dark:border-gray-800 rounded-full' />
</div>
<span className='hidden md:flex flex-col items-start'>
<Typography.Text
className='!text-sm !font-medium !leading-none'
<span className='inline-flex'>
<Button
theme='borderless'
type='tertiary'
className='flex items-center gap-2 !pl-1.5 !pr-2.5 !py-1.5 !h-10 !rounded-full hover:!bg-brand/10 dark:hover:!bg-brand/15 !bg-transparent !transition-all !duration-200 hover:!-translate-y-0.5 group'
>
<div className='relative'>
<Avatar
size='small'
src={avatarUrl}
color={stringToColor(displayName)}
className='!w-7 !h-7 !text-xs ring-2 ring-white dark:ring-gray-800 group-hover:!ring-brand/40 dark:group-hover:!ring-brand/50 transition-all'
>
{displayName[0].toUpperCase()}
</Avatar>
{/* 在线状态点 */}
<span className='absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 bg-emerald-500 border-2 border-white dark:border-gray-800 rounded-full' />
</div>
<span className='hidden md:flex flex-col items-start'>
<Typography.Text
className='!text-sm !font-medium !leading-none'
style={{
color: isDark ? 'rgba(243,244,246,0.9)' : 'rgba(55,65,81,1)',
}}
>
{displayName}
</Typography.Text>
</span>
<ChevronDown
size={14}
style={{
color: isDark ? 'rgba(243,244,246,0.9)' : 'rgba(55,65,81,1)',
color: isDark ? 'rgba(209,213,219,1)' : 'rgba(156,163,175,1)',
}}
>
{displayName}
</Typography.Text>
</span>
<ChevronDown
size={14}
style={{
color: isDark ? 'rgba(209,213,219,1)' : 'rgba(156,163,175,1)',
}}
className='group-hover:!opacity-80 transition-colors'
/>
</Button>
className='group-hover:!opacity-80 transition-colors'
/>
</Button>
</span>
</Dropdown>
);
} else {
+63 -9
View File
@@ -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 (
<Spin spinning={loading} size='large'>
{sections.slice(0, visibleCount)}
{visibleCount < sections.length && (
<div
role='status'
aria-busy='true'
className='flex justify-center py-6'
>
<Spin spinning />
</div>
)}
</Spin>
);
};
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 && (
<Banner type='danger' closeIcon={null} description={loadError}>
<Button onClick={onRefresh} disabled={loading}>
重新加载运营设置
</Button>
</Banner>
);
// Never mount editable defaults when the initial request fails.
if (!optionsLoaded) {
if (loadError) return errorBanner;
return (
<Spin spinning size='large' style={{ minHeight: 200, width: '100%' }} />
);
}
return (
<>
<Spin spinning={loading} size='large'>
{errorBanner}
<ProgressiveSettingsSections loading={loading}>
{/* 通用设置 */}
<Card style={{ marginTop: '10px' }}>
<SettingsGeneral options={inputs} refresh={onRefresh} />
@@ -235,7 +289,7 @@ const OperationSetting = () => {
<SettingsExperienceCenter options={inputs} refresh={onRefresh} />
{/* 普通管理员可见的系统设置页(权限下放) */}
<SettingsAdminDelegation options={inputs} refresh={onRefresh} />
</Spin>
</ProgressiveSettingsSections>
</>
);
};
+13
View File
@@ -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';
+2
View File
@@ -67,6 +67,8 @@ export const getDefaultSidebarModulesAdmin = () => ({
order: true,
invoice: true,
setting: true,
'website-setting': true,
'demo-reservations': true,
},
analytics: {
enabled: true,
+50
View File
@@ -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 <https://www.gnu.org/licenses/>.
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);
}
+20 -1
View File
@@ -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 <Loading />;
}
if (
!canAccessDelegatedAdminPage(
userState.user.role,
statusState?.status?.[ADMIN_DELEGATION_OPTION_KEY],
permission,
)
) {
return <Navigate to='/forbidden' replace />;
}
}
return children;
}
return <Navigate to='/forbidden' replace />;
+6
View File
@@ -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 <Handshake {...commonProps} color={iconColor} />;
case 'setting':
return <Settings {...commonProps} color={iconColor} />;
case 'website-setting':
return <Globe {...commonProps} color={iconColor} />;
case 'demo-reservations':
return <CalendarDays {...commonProps} color={iconColor} />;
default:
return <CircleUser {...commonProps} color={iconColor} />;
}
+48
View File
@@ -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 <https://www.gnu.org/licenses/>.
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;
}
+88
View File
@@ -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 <https://www.gnu.org/licenses/>.
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 (
<div className='mt-[60px] px-2 pb-6 md:px-4'>
<div className='mb-6 flex flex-wrap items-center gap-3'>
<Icon size={28} className='text-blue-500' />
<Typography.Title heading={3} style={{ margin: 0 }}>
{title}
</Typography.Title>
<Tag color='blue'>{t('功能预览')}</Tag>
</div>
<Typography.Paragraph type='tertiary'>
{t('当前为示例内容,仅用于预览页面,暂未接入数据保存。')}
</Typography.Paragraph>
{isWebsite ? (
<Card title={t('官网基础信息')}>
<div className='grid max-w-3xl gap-5 md:grid-cols-2'>
{[
[t('网站名称'), t('Monkey AI 官网')],
[t('官网地址'), 'https://www.example.com'],
[t('首页标题'), t('让 AI 为业务创造更多价值')],
[t('联系邮箱'), 'contact@example.com'],
].map(([label, value]) => (
<label key={label} className='flex flex-col gap-2'>
<span>{label}</span>
<Input value={value} readOnly />
</label>
))}
</div>
</Card>
) : (
<Card title={t('预约演示列表')}>
<div className='overflow-x-auto'>
<table className='w-full min-w-[560px] text-left text-sm'>
<thead>
<tr className='border-b border-[var(--semi-color-border)]'>
{['联系人', '企业名称', '演示需求', '状态'].map((label) => (
<th key={label} className='px-3 py-3 font-medium'>
{t(label)}
</th>
))}
</tr>
</thead>
<tbody>
<tr>
<td className='px-3 py-4'>{t('示例联系人')}</td>
<td className='px-3 py-4'>{t('示例科技有限公司')}</td>
<td className='px-3 py-4'>{t('企业 AI 应用演示')}</td>
<td className='px-3 py-4'>
<Tag color='orange'>{t('待联系')}</Tag>
</td>
</tr>
</tbody>
</table>
</div>
</Card>
)}
</div>
);
}
+26
View File
@@ -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,模拟接口验收与真实服务验收分别记录。
+294
View File
@@ -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 <https://www.gnu.org/licenses/>.
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 ? (
<div>
<span
style={{
display: '-webkit-box',
WebkitLineClamp: 3,
WebkitBoxOrient: 'vertical',
overflow: 'hidden',
overflowWrap: 'anywhere',
whiteSpace: 'pre-wrap',
}}
>
{value}
</span>
</div>
) : (
<span style={{ overflowWrap: 'anywhere', whiteSpace: 'pre-wrap' }}>
{value || '—'}
</span>
),
})),
[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 (
<div className='mt-[60px] px-2' aria-busy={loading}>
<Spin
spinning={loading}
size='large'
style={{ minHeight: 200, width: '100%' }}
data-testid='demo-reservations-loading'
>
<CardPro
type='type1'
t={t}
descriptionArea={
<div className='flex w-full flex-col items-start justify-between gap-2 md:flex-row md:items-center'>
<div>
<Typography.Title heading={4} style={{ marginBottom: 8 }}>
{t('预约演示')}
</Typography.Title>
<Typography.Text type='tertiary' size='small'>
{t('查看官网访客提交的预约信息,支持模糊查询与分页。')}
</Typography.Text>
</div>
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div>
}
actionsArea={
<div className='flex w-full justify-start'>
<Form
initValues={EMPTY_FILTERS}
getFormApi={(api) => (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'
>
<div className='flex w-full flex-col items-center gap-2 md:w-auto md:flex-row'>
{[
['name', '请输入姓名'],
['contact', '请输入联系方式'],
['companyName', '请输入公司名称'],
].map(([field, placeholder]) => (
<div key={field} className='w-full md:w-44'>
<Form.Input
field={field}
aria-label={t(placeholder)}
placeholder={t(placeholder)}
showClear
pure
size='small'
maxLength={254}
/>
</div>
))}
<div className='flex w-full gap-2 md:w-auto'>
<Button
type='tertiary'
htmlType='submit'
loading={loading}
size='small'
className='flex-1 md:flex-initial'
>
{t('查询')}
</Button>
<Button
type='tertiary'
onClick={reset}
size='small'
className='flex-1 md:flex-initial'
>
{t('重置')}
</Button>
</div>
</div>
</Form>
</div>
}
paginationArea={
isMobile && result.total > 0 ? (
<div className='flex w-full flex-col items-center gap-3'>
<div className='flex items-center gap-3'>
<Typography.Text type='tertiary'>
{t('共')} {result.total} {t('条')}
</Typography.Text>
<Select
aria-label={t('每页条数')}
size='small'
value={result.page_size ?? query.pageSize}
onChange={changePageSize}
optionList={[10, 20, 50, 100].map((value) => ({
value,
label: `${value} ${t('条/页')}`,
}))}
/>
</div>
{pagination}
</div>
) : (
pagination
)
}
>
{error && (
<Banner
type='danger'
closeIcon={null}
description={t(error)}
className='mb-4'
/>
)}
<CardTable
rowKey='id'
columns={columns}
dataSource={result.items}
scroll={compactMode ? undefined : { x: 'max-content' }}
hidePagination
className='overflow-hidden'
size='middle'
empty={
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
darkModeImage={
<IllustrationNoResultDark
style={{ width: 150, height: 150 }}
/>
}
description={t(
error ? '预约信息加载失败' : '暂无符合条件的预约信息',
)}
style={{ padding: 30 }}
/>
}
/>
</CardPro>
</Spin>
</div>
);
}
@@ -0,0 +1,54 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { requestWebsite } from '../../helpers/websiteApi';
export async function fetchDemoReservations({
name = '',
contact = '',
companyName = '',
page = 1,
pageSize = 10,
} = {}) {
const params = new URLSearchParams({
name: name.trim(),
contact: contact.trim(),
companyName: companyName.trim(),
p: String(page),
page_size: String(pageSize),
});
const data = await requestWebsite(
'get',
`/api/website/demo-requests?${params}`,
undefined,
'预约信息加载失败,请重新查询',
);
if (
!data ||
!Array.isArray(data.items) ||
!Number.isInteger(data.total) ||
data.total < 0 ||
!Number.isInteger(data.page) ||
data.page < 1 ||
!Number.isInteger(data.page_size) ||
data.page_size < 1
)
throw new Error('预约列表响应格式不正确,请联系管理员检查');
return data;
}
@@ -16,26 +16,20 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useState, useRef } from 'react';
import React, { useContext, useEffect, useState, useRef } from 'react';
import { Banner, Button, Card, Checkbox, Form, Spin } from '@douyinfe/semi-ui';
import { API, isRoot, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';
import { DELEGATABLE_SETTING_TABS } from '../../../constants/settingTabs';
const OPTION_KEY = 'AdminDelegatedSettingTabs';
function parseTabs(raw) {
if (!raw) return [];
try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : [];
} catch (e) {
return [];
}
}
import {
ADMIN_DELEGATION_OPTIONS,
ADMIN_DELEGATION_OPTION_KEY as OPTION_KEY,
} from '../../../constants/settingTabs';
import { parseAdminDelegation } from '../../../helpers/adminDelegation';
import { StatusContext } from '../../../context/Status';
export default function SettingsAdminDelegation(props) {
const { t } = useTranslation();
const [statusState, statusDispatch] = useContext(StatusContext);
const [loading, setLoading] = useState(false);
const [selected, setSelected] = useState([]);
const [savedRaw, setSavedRaw] = useState('');
@@ -44,7 +38,7 @@ export default function SettingsAdminDelegation(props) {
useEffect(() => {
const raw = props.options?.[OPTION_KEY] ?? '';
setSavedRaw(raw);
const tabs = parseTabs(raw);
const tabs = parseAdminDelegation(raw);
setSelected(tabs);
refForm.current?.setValues({ [OPTION_KEY]: tabs });
}, [props.options]);
@@ -56,7 +50,7 @@ export default function SettingsAdminDelegation(props) {
function onSubmit() {
const value = JSON.stringify(selected);
if (value === JSON.stringify(parseTabs(savedRaw))) {
if (value === JSON.stringify(parseAdminDelegation(savedRaw))) {
showSuccess(t('保存成功'));
return;
}
@@ -65,6 +59,11 @@ export default function SettingsAdminDelegation(props) {
.then((res) => {
const { success, message } = res.data;
if (success) {
setSavedRaw(value);
statusDispatch({
type: 'set',
payload: { ...statusState?.status, [OPTION_KEY]: value },
});
showSuccess(t('保存成功'));
props.refresh?.();
} else {
@@ -91,7 +90,7 @@ export default function SettingsAdminDelegation(props) {
<Banner
type='warning'
description={t(
'勾选后,普通管理员(非超级管理员)将能够看到并编辑这些系统设置 Tab。请谨慎下放含密钥的页面(如系统设置、支付设置、数据安全)。未勾选的 Tab 仍仅超级管理员可见。',
'勾选后,普通管理员(非超级管理员)将能够访问对应的系统设置 Tab 或管理页面,菜单同步按权限显示。请谨慎下放含密钥的页面(如系统设置、支付设置、数据安全)。未勾选的项目仍仅超级管理员可访问。',
)}
bordered
fullMode={false}
@@ -102,9 +101,15 @@ export default function SettingsAdminDelegation(props) {
field={OPTION_KEY}
noLabel
direction='horizontal'
onChange={(value) => setSelected(value)}
onChange={(value) => {
const unknown = parseAdminDelegation(savedRaw).filter(
(key) =>
!ADMIN_DELEGATION_OPTIONS.some((item) => item.key === key),
);
setSelected([...new Set([...unknown, ...value])]);
}}
>
{DELEGATABLE_SETTING_TABS.map((tab) => (
{ADMIN_DELEGATION_OPTIONS.map((tab) => (
<Checkbox key={tab.key} value={tab.key}>
{t(tab.labelKey)}
</Checkbox>
@@ -404,7 +404,7 @@ export default function SettingsHeaderNavModules(props) {
minHeight: '80px',
}}
bodyStyle={{ padding: '16px' }}
hoverable
shadows='hover'
>
<div
style={{
@@ -558,7 +558,7 @@ export default function SettingsHeaderNavModules(props) {
minHeight: '80px',
}}
bodyStyle={{ padding: '16px' }}
hoverable
shadows='hover'
>
<div
style={{
@@ -636,7 +636,7 @@ export default function SettingsHeaderNavModules(props) {
minHeight: '80px',
}}
bodyStyle={{ padding: '16px' }}
hoverable
shadows='hover'
>
<div
style={{
@@ -168,7 +168,7 @@ export default function SettingsOrgUserNavModules(props) {
minHeight: '64px',
}}
bodyStyle={{ padding: '16px' }}
hoverable
shadows='hover'
>
<div
style={{
@@ -695,7 +695,7 @@ export default function SettingsSidebarModulesAdmin(props) {
<Col key={module.key} xs={24} sm={12} md={8} lg={6} xl={6}>
<Card
bodyStyle={{ padding: '16px' }}
hoverable
shadows='hover'
style={{
opacity: sectionConfig.enabled ? 1 : 0.5,
transition: 'opacity 0.2s',
@@ -26,6 +26,7 @@ import {
showError,
showSuccess,
showWarning,
toBoolean,
} from '../../../helpers';
// InputNumber 清空时 onChange 会收到 ''/null,parseInt 得到 NaN,
@@ -76,12 +77,11 @@ export default function SettingsSkillInject(props) {
useEffect(() => {
const currentInputs = {};
for (const key in DEFAULTS) {
currentInputs[key] = Object.prototype.hasOwnProperty.call(
props.options,
key,
)
const value = Object.prototype.hasOwnProperty.call(props.options, key)
? props.options[key]
: DEFAULTS[key];
currentInputs[key] =
typeof DEFAULTS[key] === 'boolean' ? toBoolean(value) : value;
}
setInputs(currentInputs);
setInputsRow(structuredClone(currentInputs));
+52 -36
View File
@@ -17,13 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, {
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import {
Button,
Card,
@@ -136,7 +130,8 @@ const TOKEN_GROUPS = [
{
key: 'bg',
labelKey: '页面背景晕染(大面积底色 / 光晕)',
descKey: '影响 user-center、experience 等页面的整页背景渲染与动态光晕,不影响按钮气泡',
descKey:
'影响 user-center、experience 等页面的整页背景渲染与动态光晕,不影响按钮气泡',
},
{
key: 'accent',
@@ -286,7 +281,8 @@ export default function SettingsTheme(props) {
() => ({ ...getEffectivePreset(selectedPreset).dark, ...customDark }),
[selectedPreset, customDark, presetOverridesState],
);
const effectivePalette = colorMode === 'light' ? effectiveLight : effectiveDark;
const effectivePalette =
colorMode === 'light' ? effectiveLight : effectiveDark;
// 任何编辑都即时前端预览(不写 cache)。
// 注意:必须等首次 props 解析完成再开启预览,否则挂载瞬间会用 default state
@@ -553,10 +549,9 @@ export default function SettingsTheme(props) {
setPresetOverrides(payload);
setPresetOverridesState(nextOverrides);
setPresetDraft({});
applyTheme(
JSON.stringify({ preset: editingPresetKey }),
{ persist: false },
);
applyTheme(JSON.stringify({ preset: editingPresetKey }), {
persist: false,
});
statusDispatch({
type: 'set',
payload: { ...(statusState?.status || {}), theme_presets: payload },
@@ -624,9 +619,11 @@ export default function SettingsTheme(props) {
const cleanLight = sanitizeImportedTokens(cfg.lightTokens);
const cleanDark = sanitizeImportedTokens(cfg.darkTokens);
const droppedLight =
Object.keys(cfg.lightTokens || {}).length - Object.keys(cleanLight).length;
Object.keys(cfg.lightTokens || {}).length -
Object.keys(cleanLight).length;
const droppedDark =
Object.keys(cfg.darkTokens || {}).length - Object.keys(cleanDark).length;
Object.keys(cfg.darkTokens || {}).length -
Object.keys(cleanDark).length;
setSelectedPreset(presetKey);
setCustomLight(cleanLight);
setCustomDark(cleanDark);
@@ -769,9 +766,7 @@ export default function SettingsTheme(props) {
colorMode={colorMode}
setColorMode={setColorMode}
palette={effectivePalette}
customOverrides={
colorMode === 'light' ? customLight : customDark
}
customOverrides={colorMode === 'light' ? customLight : customDark}
onChange={handleTokenChange}
onResetToken={handleTokenReset}
onCopyToOther={handleCopyToOther}
@@ -863,7 +858,7 @@ function PresetGrid({
return (
<Col key={key} xs={24} sm={12} md={8}>
<Card
hoverable
shadows='hover'
onClick={() => onSelect(key)}
style={{
cursor: 'pointer',
@@ -926,7 +921,10 @@ function PresetGrid({
)}
</Title>
{isSaved && (
<Text size='small' style={{ color: 'var(--semi-color-primary)' }}>
<Text
size='small'
style={{ color: 'var(--semi-color-primary)' }}
>
{t('已应用')}
</Text>
)}
@@ -1015,19 +1013,13 @@ function PresetTemplateEditor({
/>
</div>
<div style={{ display: 'flex', gap: 8, marginTop: 16, alignItems: 'center' }}>
<Button
type='primary'
theme='solid'
loading={saving}
onClick={onSave}
>
<div
style={{ display: 'flex', gap: 8, marginTop: 16, alignItems: 'center' }}
>
<Button type='primary' theme='solid' loading={saving} onClick={onSave}>
{t('保存预设模板')}
</Button>
<Button
disabled={!isEdited || saving}
onClick={onRestore}
>
<Button disabled={!isEdited || saving} onClick={onRestore}>
{t('恢复此预设出厂')}
</Button>
</div>
@@ -1053,7 +1045,14 @@ function CustomEditor({
return (
<>
{/* 基础预设选择(决定未覆盖 token 的兜底值) */}
<div style={{ marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8 }}>
<div
style={{
marginBottom: 12,
display: 'flex',
alignItems: 'center',
gap: 8,
}}
>
<Text type='secondary' size='small'>
{t('基础预设:')}
</Text>
@@ -1115,7 +1114,9 @@ function CustomEditor({
<Button
size='small'
onClick={onDeriveToDark}
title={t('按 deriveDarkTokens 规则自动调亮,与编辑预设模板的派生逻辑一致')}
title={t(
'按 deriveDarkTokens 规则自动调亮,与编辑预设模板的派生逻辑一致',
)}
>
{t('派生到深色(自动调亮)')}
</Button>
@@ -1148,7 +1149,13 @@ function GroupedTokenList({ palette, isCustomOf, onChange, onReset, t }) {
}}
>
<div style={{ marginBottom: 6, padding: '0 4px' }}>
<div style={{ fontSize: 12, fontWeight: 600, color: 'var(--semi-color-text-1)' }}>
<div
style={{
fontSize: 12,
fontWeight: 600,
color: 'var(--semi-color-text-1)',
}}
>
{t(g.labelKey)}
</div>
<Text type='tertiary' size='small' style={{ fontSize: 11 }}>
@@ -1186,7 +1193,12 @@ function TokenRow({ label, desc, value, isCustom, onChange, onReset }) {
const alphaPct = valid ? Math.round(c.alpha() * 100) : 100;
// colord.toHex():alpha=1 → 6 位,alpha<1 → 8 位,天然兼容存储格式
const emit = (hex, pct) => onChange(colord(hex).alpha(pct / 100).toHex());
const emit = (hex, pct) =>
onChange(
colord(hex)
.alpha(pct / 100)
.toHex(),
);
return (
<div
@@ -1259,7 +1271,11 @@ function TokenRow({ label, desc, value, isCustom, onChange, onReset }) {
step={1}
value={alphaPct}
onChange={(e) => emit(rgbHex, Number(e.target.value))}
style={{ flex: 1, accentColor: 'var(--brand-primary)', cursor: 'pointer' }}
style={{
flex: 1,
accentColor: 'var(--brand-primary)',
cursor: 'pointer',
}}
aria-label={`${label} alpha`}
/>
<span
+4 -7
View File
@@ -22,6 +22,7 @@ import { Layout, TabPane, Tabs } from '@douyinfe/semi-ui';
import { useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { StatusContext } from '../../context/Status';
import { getDelegatedSettingTabs } from '../../helpers/adminDelegation';
import {
ALWAYS_ADMIN_VISIBLE_TABS,
ROOT_ONLY_SETTING_TABS,
@@ -264,13 +265,9 @@ const Setting = () => {
}
// 解析 root 配置的「下放给普通管理员」tab 列表
let delegatedTabs = [];
try {
const raw = statusState?.status?.AdminDelegatedSettingTabs;
if (raw) delegatedTabs = JSON.parse(raw);
} catch (e) {
delegatedTabs = [];
}
const delegatedTabs = getDelegatedSettingTabs(
statusState?.status?.AdminDelegatedSettingTabs,
);
// 可见性过滤:root 看全部;普通管理员看「会员管理 + 被下放的 tab」;其余看不到。
if (!isRoot()) {
+297
View File
@@ -0,0 +1,297 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useState } from 'react';
import {
Button,
Card,
Checkbox,
Form,
Input,
Modal,
Select,
SideSheet,
TextArea,
Typography,
} from '@douyinfe/semi-ui';
import { articleErrors } from './insightsModel';
import { articleContentInfo, sanitizeArticleHtml } from './insightsContent';
import ArticleRichEditor from './ArticleRichEditor';
export default function ArticleEditor({ initial, insights, onApply, onClose }) {
const [draft, setDraft] = useState(initial);
const [errors, setErrors] = useState({});
const [processingImage, setProcessingImage] = useState(false);
const hasDraftChanges = JSON.stringify(draft) !== JSON.stringify(initial);
useEffect(() => {
if (!hasDraftChanges && !processingImage) return;
const warn = (event) => {
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [hasDraftChanges, processingImage]);
const change = (name, value) => {
setDraft((previous) => ({ ...previous, [name]: value }));
setErrors((previous) => ({ ...previous, [name]: '' }));
};
const close = () => {
if (JSON.stringify(draft) === JSON.stringify(initial) && !processingImage)
onClose();
else
Modal.confirm({
title: '放弃本次编辑?',
content: '当前文章的修改尚未应用,关闭后将丢失本次编辑内容。',
okText: '放弃修改',
cancelText: '继续编辑',
onOk: onClose,
});
};
const apply = () => {
if (processingImage) return;
const article = { ...draft, body: sanitizeArticleHtml(draft.body) };
for (const key of ['title', 'summary', 'subtitle', 'tag'])
article[key] = article[key].trim();
const nextErrors = articleErrors(article, insights);
setErrors(nextErrors);
if (Object.keys(nextErrors).length) return;
onApply(article);
};
const field = (name, label, children, required = false) => (
<Form.Slot
className='website-insights-editor-field'
label={{ text: label, required }}
error={{ error: errors[name] || undefined }}
>
{children}
</Form.Slot>
);
const info = articleContentInfo(draft.body);
return (
<SideSheet
visible
title={initial.id ? '编辑文章' : '新增文章'}
width='min(1100px, 100vw)'
onCancel={close}
maskClosable={false}
footer={
<div className='website-insights-editor-footer'>
<div className='flex gap-2'>
<Button onClick={close}>取消</Button>
<Button theme='solid' disabled={processingImage} onClick={apply}>
{processingImage ? '图片处理中' : '保存'}
</Button>
</div>
</div>
}
>
<div className='website-insights-editor-layout'>
<div className='website-insights-editor-main'>
<Typography.Title
heading={5}
className='website-insights-section-title'
>
基础信息
</Typography.Title>
{field(
'title',
'文章标题',
<Input
aria-label='文章标题'
validateStatus={errors.title ? 'error' : 'default'}
aria-invalid={Boolean(errors.title)}
value={draft.title}
placeholder='请输入文章标题'
maxLength={80}
showClear
suffix={`${draft.title.length} / 80`}
onChange={(value) => change('title', value)}
/>,
true,
)}
<div className='grid grid-cols-1 gap-x-6 md:grid-cols-2'>
{field(
'category',
'所属分类',
<Select
aria-label='所属分类'
validateStatus={errors.category ? 'error' : 'default'}
aria-invalid={Boolean(errors.category)}
value={draft.category || undefined}
placeholder='请选择文章分类'
style={{ width: '100%' }}
optionList={[
{ label: '全部内容', value: 'all' },
...insights.categories.map((c) => ({
label: c.name,
value: c.id,
})),
]}
onChange={(value) => change('category', value)}
/>,
true,
)}
{field(
'date',
'发布日期',
<Input
aria-label='发布日期'
validateStatus={errors.date ? 'error' : 'default'}
aria-invalid={Boolean(errors.date)}
type='date'
value={draft.date}
onChange={(value) => change('date', value)}
/>,
true,
)}
</div>
{field(
'subtitle',
'详情副标题',
<Input
aria-label='详情副标题'
validateStatus={errors.subtitle ? 'error' : 'default'}
aria-invalid={Boolean(errors.subtitle)}
value={draft.subtitle}
maxLength={160}
placeholder='留空时使用卡片摘要作为副标题'
onChange={(value) => change('subtitle', value)}
/>,
)}
{field(
'summary',
'卡片摘要',
<TextArea
aria-label='卡片摘要'
validateStatus={errors.summary ? 'error' : 'default'}
aria-invalid={Boolean(errors.summary)}
value={draft.summary}
placeholder='请输入卡片摘要'
maxCount={200}
rows={3}
onChange={(value) => change('summary', value)}
/>,
true,
)}
{field(
'tag',
'角标标签',
<Input
aria-label='角标标签'
validateStatus={errors.tag ? 'error' : 'default'}
aria-invalid={Boolean(errors.tag)}
value={draft.tag}
maxLength={12}
placeholder='例如 NEW、推荐'
onChange={(value) => change('tag', value)}
/>,
)}
<Typography.Title
heading={5}
className='website-insights-section-title website-insights-detail-title'
>
详情内容
</Typography.Title>
{field(
'body',
'文章正文',
<ArticleRichEditor
value={draft.body}
invalid={Boolean(errors.body)}
onChange={(value) => change('body', value)}
onBusyChange={setProcessingImage}
/>,
true,
)}
</div>
<aside className='website-insights-aside'>
<Card title='文章目录'>
<Checkbox
checked={draft.toc}
onChange={(e) => change('toc', e.target.checked)}
>
根据正文标题自动生成
</Checkbox>
<div className='website-insights-toc'>
{!draft.toc ? (
<Typography.Text type='tertiary'>
已关闭目录展示
</Typography.Text>
) : info.headings.length ? (
info.headings.map((h, i) => (
<div
key={i}
style={{ paddingLeft: h.level === 'H3' ? 12 : 0 }}
>
{h.text}
</div>
))
) : (
<Typography.Text type='tertiary'>
添加 H2 / H3 标题后自动生成目录
</Typography.Text>
)}
</div>
</Card>
<Card title={`相关推荐(${draft.related.length} / 3)`}>
<div className='website-insights-related'>
{insights.articles
.filter((a) => a.id !== draft.id)
.map((a) => (
<Checkbox
key={a.id}
checked={draft.related.includes(a.id)}
disabled={
!draft.related.includes(a.id) && draft.related.length >= 3
}
onChange={(e) =>
change(
'related',
e.target.checked
? [...draft.related, a.id]
: draft.related.filter((id) => id !== a.id),
)
}
>
{a.title}
</Checkbox>
))}
</div>
{!insights.articles.some((a) => a.id !== draft.id) && (
<Typography.Text type='tertiary'>
暂无可推荐的其他文章
</Typography.Text>
)}
{errors.related && (
<Typography.Text type='danger'>{errors.related}</Typography.Text>
)}
</Card>
<Card title='展示说明'>
<Typography.Paragraph type='tertiary'>
列表页:标题、摘要、分类、日期、角标。
</Typography.Paragraph>
<Typography.Text type='tertiary'>
详情页:副标题(留空时使用摘要)、正文、目录和推荐。
</Typography.Text>
</Card>
</aside>
</div>
</SideSheet>
);
}
@@ -0,0 +1,33 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import RichTextEditor from '../../components/common/ui/RichTextEditor';
import { ARTICLE_BODY_LIMIT } from '../../components/common/ui/richTextLength';
export default function ArticleRichEditor(props) {
return (
<RichTextEditor
{...props}
maxLength={ARTICLE_BODY_LIMIT}
label='文章正文'
placeholder='请输入文章正文,支持文本、图片及复制粘贴'
/>
);
}
+417
View File
@@ -0,0 +1,417 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState } from 'react';
import {
Button,
Card,
Empty,
Input,
Modal,
Select,
Typography,
} from '@douyinfe/semi-ui';
import {
IconPlus,
IconSearch,
IconEdit,
IconClose,
} from '@douyinfe/semi-icons';
import CardTable from '../../components/common/ui/CardTable';
import { showError, showInfo } from '../../helpers';
import {
categoryError,
createContentId,
filterArticles,
newArticle,
removeArticle,
} from './insightsModel';
import ArticleEditor from './ArticleEditor';
export default function InsightsPanel({ value, onChange, disabled, error }) {
const [keyword, setKeyword] = useState('');
const [category, setCategory] = useState('all');
const [managing, setManaging] = useState(false);
const [categoryDraft, setCategoryDraft] = useState(null);
const [categoryMessage, setCategoryMessage] = useState('');
const [article, setArticle] = useState(null);
const activeCategory = value.categories.some((c) => c.id === category)
? category
: 'all';
const rows = filterArticles(value, keyword, activeCategory);
const count = (id) =>
id === 'all'
? value.articles.length
: value.articles.filter((a) => a.category === id).length;
const selectCategory = (id) => {
setCategory(id);
};
const editCategory = (item = { id: '', name: '' }) => {
setCategoryMessage('');
setCategoryDraft({ ...item });
};
const saveCategory = () => {
const message = categoryError(
categoryDraft.name,
value.categories,
categoryDraft.id,
);
if (message) {
setCategoryMessage(message);
return;
}
const item = {
id: categoryDraft.id || createContentId(),
name: categoryDraft.name.trim(),
};
onChange({
...value,
categories: categoryDraft.id
? value.categories.map((c) => (c.id === item.id ? item : c))
: [...value.categories, item],
});
setCategoryDraft(null);
};
const deleteCategory = (item) => {
if (count(item.id)) {
showError('该分类下仍有文章,请先调整文章所属分类,再删除分类。');
return;
}
Modal.confirm({
title: '删除分类',
content: `确定删除“${item.name}”分类吗?点击页面底部“保存”后统一提交。`,
okText: '确定删除',
cancelText: '取消',
onOk: () => {
onChange({
...value,
categories: value.categories.filter((c) => c.id !== item.id),
});
if (category === item.id) selectCategory('all');
},
});
};
const deleteArticle = (item) =>
Modal.confirm({
title: '删除文章',
content: `确定删除“${item.title}”吗?删除后将同步清理其他文章中的推荐引用。点击页面底部“保存”后统一提交。`,
okText: '确定删除',
cancelText: '取消',
onOk: () => onChange(removeArticle(value, item.id)),
});
const applyArticle = (draft) => {
const next = { ...draft, id: draft.id || createContentId() };
onChange({
...value,
articles: draft.id
? value.articles.map((a) => (a.id === draft.id ? next : a))
: [next, ...value.articles],
});
setArticle(null);
showInfo('文章已应用到当前配置,请点击页面底部“保存”统一提交。');
};
const columns = [
{
title: '文章标题',
dataIndex: 'title',
width: 420,
render: (_, item) => (
<div className='website-insights-article-meta'>
<button
type='button'
className='website-insights-title'
title={item.title}
disabled={disabled}
onClick={() => setArticle({ ...item, related: [...item.related] })}
>
{item.title}
</button>
<Typography.Paragraph
type='tertiary'
className='truncate'
title={item.summary}
style={{ marginBottom: 0 }}
>
{item.summary}
</Typography.Paragraph>
</div>
),
},
{
title: '所属分类',
dataIndex: 'category',
width: 140,
render: (id) =>
id === 'all'
? '全部内容'
: value.categories.find((c) => c.id === id)?.name || '未分类',
},
{ title: '发布日期', dataIndex: 'date', width: 140 },
{
title: '操作',
key: 'actions',
width: 160,
render: (_, item) => (
<div className='flex gap-2'>
<Button
type='tertiary'
theme='borderless'
disabled={disabled}
onClick={() => setArticle({ ...item, related: [...item.related] })}
>
编辑
</Button>
<Button
theme='borderless'
type='danger'
disabled={disabled}
onClick={() => deleteArticle(item)}
>
删除
</Button>
</div>
),
},
];
return (
<div className='website-insights'>
{error && (
<Typography.Paragraph type='danger' role='alert'>
{error}
</Typography.Paragraph>
)}
<Card
className='website-insights-categories'
title={
<Typography.Title heading={6} className='truncate' title='内容分类'>
内容分类
</Typography.Title>
}
headerExtraContent={
<Button
type='tertiary'
theme='borderless'
disabled={disabled}
onClick={() => setManaging(true)}
>
管理分类
</Button>
}
>
<div className='website-insights-category-list'>
{[{ id: 'all', name: '全部内容' }, ...value.categories].map((c) => (
<div
key={c.id}
className={`website-insights-category ${activeCategory === c.id ? 'is-selected' : ''}`}
>
<Button
type='tertiary'
theme='borderless'
aria-pressed={activeCategory === c.id}
onClick={() => selectCategory(c.id)}
>
<span>{c.name}</span>
<span className='website-insights-category-count'>
{count(c.id)}
</span>
</Button>
{c.id !== 'all' && (
<div className='website-insights-category-actions'>
<Button
type='tertiary'
icon={<IconEdit />}
size='small'
theme='borderless'
aria-label={`编辑${c.name}`}
disabled={disabled}
onClick={() => editCategory(c)}
/>
<Button
icon={<IconClose />}
size='small'
theme='borderless'
type='danger'
aria-label={`删除${c.name}`}
disabled={disabled}
onClick={() => deleteCategory(c)}
/>
</div>
)}
</div>
))}
<Button
type='tertiary'
icon={<IconPlus />}
theme='borderless'
disabled={disabled}
onClick={() => editCategory()}
>
新增分类
</Button>
</div>
</Card>
<div className='website-insights-toolbar'>
<Input
prefix={<IconSearch />}
aria-label='搜索文章标题或摘要'
placeholder='搜索文章标题或摘要'
value={keyword}
showClear
onEnterPress={(event) => event.preventDefault()}
onChange={(text) => {
setKeyword(text);
}}
/>
<Select
aria-label='筛选文章分类'
value={activeCategory}
optionList={[
{ label: '全部分类', value: 'all' },
...value.categories.map((c) => ({ label: c.name, value: c.id })),
]}
onChange={selectCategory}
/>
<Button
icon={<IconPlus />}
theme='solid'
disabled={disabled}
onClick={() => {
setArticle(newArticle(activeCategory));
}}
>
新增文章
</Button>
</div>
<CardTable
rowKey='id'
columns={columns}
dataSource={rows}
scroll={{ x: 860 }}
empty={<Empty description='暂无匹配的文章,请调整筛选条件或新增文章' />}
hidePagination
/>
<Modal
visible={managing}
title='管理分类'
onCancel={() => setManaging(false)}
footer={
<Button
icon={<IconPlus />}
theme='solid'
disabled={disabled}
onClick={() => editCategory()}
>
新增分类
</Button>
}
>
<Typography.Paragraph type='tertiary'>
“全部内容”为默认分类,也汇总展示全部文章;已有文章的自定义分类需先迁移文章再删除。
</Typography.Paragraph>
<div className='website-insights-manage-row'>
<span>全部内容</span>
<Typography.Text type='tertiary'>
默认分类(不可删除)
</Typography.Text>
</div>
{value.categories.map((c) => (
<div className='website-insights-manage-row' key={c.id}>
<span>
{c.name}({count(c.id)} 篇)
</span>
<Button
type='tertiary'
theme='borderless'
disabled={disabled}
onClick={() => editCategory(c)}
>
编辑
</Button>
<Button
theme='borderless'
type='danger'
disabled={disabled}
onClick={() => deleteCategory(c)}
>
删除
</Button>
</div>
))}
</Modal>
<Modal
visible={Boolean(categoryDraft)}
title={categoryDraft?.id ? '编辑分类' : '新增分类'}
onCancel={() => setCategoryDraft(null)}
onOk={saveCategory}
okText='确定'
cancelText='取消'
okButtonProps={{ disabled }}
>
<Typography.Paragraph
className='website-category-dialog-description'
type='tertiary'
>
分类名称将用于官网导航与文章分类标签。
</Typography.Paragraph>
<div className='website-category-dialog-field'>
<label
htmlFor='website-category-name'
className='website-category-dialog-label'
>
分类名称 <span aria-hidden='true'>*</span>
</label>
<Input
id='website-category-name'
aria-required='true'
aria-invalid={Boolean(categoryMessage)}
aria-describedby={
categoryMessage ? 'website-category-name-error' : undefined
}
aria-label='分类名称'
value={categoryDraft?.name || ''}
maxLength={12}
placeholder='请输入分类名称,最多 12 个字符'
validateStatus={categoryMessage ? 'error' : 'default'}
onChange={(name) => {
setCategoryDraft((previous) => ({ ...previous, name }));
setCategoryMessage('');
}}
onEnterPress={saveCategory}
/>
{categoryMessage && (
<Typography.Text
id='website-category-name-error'
type='danger'
role='alert'
>
{categoryMessage}
</Typography.Text>
)}
</div>
</Modal>
{article && (
<ArticleEditor
initial={article}
insights={value}
onApply={applyArticle}
onClose={() => setArticle(null)}
/>
)}
</div>
);
}
+138
View File
@@ -0,0 +1,138 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useRef, useState } from 'react';
import { Button, Image, Typography } from '@douyinfe/semi-ui';
import { Upload } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { showError } from '../../helpers';
import { validateImageFile } from './model';
import { uploadWebsiteQrCode } from './settingsApi';
export default function QrCodeUpload({
value,
onChange,
busy,
onBusyChange,
resetVersion,
invalid,
}) {
const { t } = useTranslation();
const inputRef = useRef(null);
const requestVersion = useRef(0);
const [uploading, setUploading] = useState(false);
useEffect(() => {
requestVersion.current += 1;
setUploading(false);
onBusyChange(false);
if (inputRef.current) inputRef.current.value = '';
return () => {
requestVersion.current += 1;
onBusyChange(false);
};
}, [resetVersion, onBusyChange]);
const upload = async (event) => {
const file = event.target.files?.[0];
event.target.value = '';
if (!file) return;
const error = validateImageFile(file);
if (error) {
showError(t(error));
return;
}
const version = ++requestVersion.current;
setUploading(true);
onBusyChange(true);
try {
// Verify the content is decodable, rather than trusting the filename or MIME alone.
try {
const bitmap = await createImageBitmap(file);
bitmap.close();
} catch {
throw new Error(
'无法读取二维码图片,请选择有效的 JPG、PNG 或 WebP 图片',
);
}
if (version !== requestVersion.current) return;
const url = await uploadWebsiteQrCode(file);
if (version === requestVersion.current) onChange(url);
} catch (err) {
if (version === requestVersion.current)
showError(t(err.message || '二维码上传失败,请选择有效图片后重试'));
} finally {
if (version === requestVersion.current) {
setUploading(false);
onBusyChange(false);
}
}
};
return (
<div
className='flex flex-wrap items-center gap-4 rounded-lg border border-dashed p-4'
style={{
borderColor: invalid
? 'var(--semi-color-danger)'
: 'var(--semi-color-border)',
background: 'var(--semi-color-fill-0)',
}}
>
{value ? (
<div className='relative inline-flex'>
<Image
src={value}
width={100}
height={100}
style={{ objectFit: 'contain' }}
alt={t('企业微信二维码')}
/>
</div>
) : (
<Upload size={28} className='m-4 text-[var(--semi-color-text-2)]' />
)}
<div className='flex flex-col gap-2'>
<input
ref={inputRef}
type='file'
accept='image/jpeg,image/png,image/webp'
onChange={upload}
hidden
/>
<Button
icon={<Upload size={14} />}
loading={uploading}
disabled={busy || uploading}
onClick={() => inputRef.current?.click()}
>
{t(value ? '重新上传' : '上传二维码')}
</Button>
<Typography.Text type='tertiary' size='small'>
{t('支持 JPG、PNG、WebP,单张不超过 2 MB')}
</Typography.Text>
{value && (
<Typography.Text type='tertiary' size='small'>
{t('点击图片可放大预览')}
</Typography.Text>
)}
</div>
</div>
);
}
+106
View File
@@ -0,0 +1,106 @@
# 官网设置接入说明
二维码使用后端上传与 HTTP(S) 绝对地址校验,缩略图支持放大预览和替换。
## 单一表单数据
首页、关于微词元、预约演示、动态与洞察共用一个配置对象,切换页签保留输入。
teamMembers 在两个页签共用,不生成不同的副本。原有 11 个字段均必填。
动态与洞察绑定 insights 对象,包含 categories 和 articles,不按页签拆分保存。
model.js 定义字段、页签、初始化、标准化和校验规则。
保存按首页、关于微词元、预约演示、动态与洞察顺序校验全部字段,错误保存在各表单项内。
空输入框提示“请输入中文字段名”,选择框提示“请选择中文字段名”,二维码提示“请上传企业微信二维码”。
每个非当前页签有错误时只显示一条“请完善某页签的配置”警告,不列出全部字段,不自动切换页签。
当前页签只显示表单项错误;切换页签后,其他页签的错误状态仍会显示。
清空会清除全部字段、二维码、错误状态,同时让尚未完成的上传结果失效。
## 读取与保存接口
进入页面 GET /api/website/page-config,解析 data 字符串并回填所有页签。
data 为 null 时回填空表单。读取失败可重试,成功前禁止编辑和保存,避免覆盖原配置。
保存 POST /api/website/page-config,请求为 { config: JSON.stringify(完整配置) }。
config 内部按 home/about/demo 分组;动态与洞察保存在 insights 扩展字段。
paidCustomers/dailyTokens/costReduction 分别映射 home.payingCustomers/dailyTokenCalls/monthlyAiCostReduction。
teamMembers/researchRatio 映射 about.teamMembers/researchStaffRatio;首页和关于页共用这两个值。
其余总部、服务网络和商务字段依联调文档映射。保存保留后端返回的未知字段。
严格检查 success === true 后才提示成功,失败保留当前编辑。提交期间防止重复请求。
完整配置按 UTF-8 字节限制为 60 KiB,超限时提示精简内容。
客户数和人数支持正整数及末尾 +;Token 支持正数、万/亿单位及末尾 +。
百分比支持 0~100,最多两位小数,% 可选。上述展示值以字符串提交。
## 二维码上传
复用客服模块 POST /api/customer-service/upload,multipart 字段 file。
期望响应 { success: true, data: { url: "https://公共资源域名/图片路径" } }。
前端限制 JPG/PNG/WebP、0~2 MB(不含 0),并在上传前尝试解码图片。
上传返回 HTTP(S) 绝对 URL 后才写入表单,可预览和替换。
切换页签或清空会使旧上传回调失效。
如果接口返回 /uploads/...,配置 VITE_WEBSITE_ASSET_BASE_URL 为公开资源域名;
禁止用开发代理地址、blob: 或 data: 地址作为提交资源路径。
绝对 URL 只保证地址形式正确,后端还需要保证图片无需后台登录即可被官网访问,
并在 HTTPS 官网部署时提供 HTTPS 图片地址。需在联调时通过未登录环境验证。
清空只移除配置引用,不删除服务器文件,文件回收由后端确定。
管理接口复用项目 API 实例的登录 Cookie 和 New-Api-User,401 沿用重新登录流程。
## 验证
```sh
node --test src/pages/WebsiteSettings/*.test.js src/components/common/ui/richTextImages.test.js
```
## 动态与洞察
InsightsPanel.jsx 承载分类管理、文章列表、标题/摘要即时搜索和分类筛选。
搜索为纯前端模糊匹配,不请求后端;不设分页,展示当前筛选后的全部文章。
ArticleEditor.jsx 承载文章新增/编辑抽屉,ArticleRichEditor.jsx 复用公共 RichTextEditor。
公共组件位于 src/components/common/ui/RichTextEditor.jsx,基于 Quill 2.0.3 core 封装,按需注册所用格式。
上游项目:https://github.com/slab/quill,BSD-3-Clause 许可;直接封装核心,不额外依赖 React 适配包。
支持 H2/H3、加粗、斜体、下划线、无序/有序列表、引用、撤销/重做、清除格式和图片。
工具栏采用独立的中性样式,避免项目 primary 按钮全局渐变影响编辑工具和选中状态。
默认保留公司动态、产品更新、行业洞察三个分类,文章为空,不向官网注入原型示例文章。
单篇文章结构:
```json
{
"id": "由前端生成的 UUID,后续可替换为后端 ID",
"title": "文章标题",
"category": "all",
"date": "2026-10-31",
"subtitle": "详情副标题,空值时由官网使用 summary",
"summary": "卡片摘要",
"tag": "NEW",
"body": "<h2>章节标题</h2><p>文章正文</p>",
"toc": true,
"related": []
}
```
必填:title(最多 80 字)、category、date、summary(最多 200 字)、body。
subtitle 最多 160 字,tag 最多 12 字,推荐最多 3 篇且不能选择自己。
正文 H2/H3 自动生成目录预览;toc 为是否展示目录,官网可从 body 提取标题。
“全部内容”是内置默认归属(category 为 all),也汇总展示所有分类的文章,不存入自定义 categories 数组。
新增文章默认归属当前分类,从全部内容新增时直接归属 all;自定义分类为空时也可新增文章。
分类名称最多 12 字,禁止空白、重名和系统保留名称;已有文章的自定义分类不能直接删除,可先迁移到全部内容。
删除文章同步清理其他文章的 related 引用。列表按发布日期倒序排列。
文章抽屉“保存”、分类编辑与文章删除只更新当前内存配置,不请求后端保存接口。
页面底部“保存”统一校验四个页签后,将整个配置序列化为 JSON 字符串调用 saveWebsiteSettings。
保存成功后刷新会从后端回填;文章抽屉内保存仅更新本地,仍需点击页面底部保存。
文章抽屉必填项错误只在字段内提示,不弹出汇总错误 Toast;不提供封面字段。
正文支持复制/粘贴 HTML 图文、剪贴板图片文件,以及工具栏选择本地图片。
HTTP(S) 图片保留绝对地址;JPG/PNG/WebP/GIF 内嵌图片每张限制 2 MB,
本地文件先解码校验,编辑期间使用 Base64 data URI;页面最终保存前上传到图片接口,将 body 中的图片替换为公开 URL。
相同内嵌图片在一次保存中仅上传一次;上传失败终止配置保存并保留本地内容。
二维码仍走原后端上传接口并强制 HTTP(S) 绝对地址,与文章内嵌图片分开处理。
HTML 在粘贴、编辑输出、应用文章时均进行白名单清理,不保留事件属性、脚本或 SVG 图片。
使用 getSemanticHTML 导出标准 HTML 列表,无需官网额外依赖 Quill 的 CSS 或 Delta 数据结构。
不可访问的外链图片会在编辑器内提示,需换为可公开访问的地址或插入本地文件。
不抓取第三方图片,无法自动绕过防盗链、登录权限及浏览器的混合内容限制。
后端正式接入时仍应进行服务端 HTML 清理(允许受限的图片 data URI)与权限校验,
官网 CSP 如有 img-src 白名单,需允许 data: 和所用图片域名。
@@ -0,0 +1,63 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Form, Input } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { FIELDS } from './model';
export default function WebsiteField({
name,
value,
error,
onChange,
onBlur,
disabled,
children,
}) {
const { t } = useTranslation();
const field = FIELDS[name];
return (
<Form.Slot
label={{ text: t(field.label), required: true, name: `website-${name}` }}
error={{
error: error ? t(error) : undefined,
errorMessageId: `website-${name}-error`,
}}
>
{children || (
<Input
id={`website-${name}`}
aria-label={t(field.label)}
aria-required={true}
aria-invalid={Boolean(error)}
aria-describedby={error ? `website-${name}-error` : undefined}
value={value}
onChange={onChange}
onBlur={onBlur}
disabled={disabled}
placeholder={t(field.placeholder)}
validateStatus={error ? 'error' : 'default'}
maxLength={name === 'businessEmail' ? 254 : 200}
showClear
/>
)}
</Form.Slot>
);
}
@@ -0,0 +1,264 @@
.website-settings-page {
display: flex;
flex-direction: column;
box-sizing: border-box;
/* Match Settings: 24px layout padding + 8px page padding on each side. */
padding-inline: 32px;
min-height: calc(100vh - var(--content-top-offset, 0px));
min-height: calc(100dvh - var(--content-top-offset, 0px));
/* PageLayout already inserts the marquee spacer above this page. */
padding-top: calc(
var(--app-header-height, 64px) - var(--content-top-offset, 0px) + 20px
);
padding-bottom: 20px;
}
.website-settings-page .website-settings-card {
flex: 1;
min-height: 100%;
}
.website-settings-page .website-settings-notice .semi-banner-icon {
margin-right: 4px;
}
.website-insights {
min-width: 0;
}
.website-settings-page .website-settings-tab-description {
margin-bottom: 16px;
line-height: 22px;
}
.website-category-dialog-description {
margin: 0 0 18px;
line-height: 22px;
}
.website-category-dialog-field {
display: flex;
flex-direction: column;
gap: 8px;
padding-bottom: 8px;
}
.website-category-dialog-label {
color: var(--semi-color-text-0);
font-weight: 600;
line-height: 20px;
}
.website-category-dialog-label > span {
color: var(--semi-color-danger);
}
.website-insights-categories {
margin-bottom: 20px;
}
.website-insights-category-list,
.website-insights-category,
.website-insights-toolbar,
.website-insights-manage-row,
.website-insights-editor-footer,
.website-rich-tools {
display: flex;
align-items: center;
gap: 8px;
}
.website-insights-category-list,
.website-rich-tools,
.website-insights-editor-footer {
flex-wrap: wrap;
}
.website-insights-category {
border: 1px solid var(--semi-color-border);
border-radius: var(--semi-border-radius-small);
gap: 0;
background: var(--semi-color-fill-0);
min-height: 34px;
padding-inline: 2px;
}
.website-insights-category.is-selected {
border-color: var(--semi-color-primary-light-active);
background: var(--semi-color-primary-light-default);
}
.website-insights-category .semi-button {
background: transparent !important;
border: 0 !important;
border-radius: 3px !important;
box-shadow: none !important;
}
.website-insights-category > .semi-button .semi-button-content {
display: flex;
align-items: center;
gap: 10px;
color: var(--semi-color-text-1);
font-weight: 400;
}
.website-insights-category.is-selected > .semi-button .semi-button-content {
color: var(--semi-color-primary);
}
.website-insights-category-count {
font-size: 12px;
opacity: 0.65;
}
.website-insights-category-actions {
display: flex;
visibility: hidden;
}
.website-insights-category-actions .semi-button {
width: 24px;
height: 24px;
padding: 4px;
}
.website-insights-category .semi-button:hover {
background: var(--semi-color-fill-1) !important;
}
.website-insights-category:hover .website-insights-category-actions,
.website-insights-category:focus-within .website-insights-category-actions {
visibility: visible;
}
.website-insights-toolbar {
flex-wrap: wrap;
margin-bottom: 16px;
}
.website-insights-toolbar > .semi-input-wrapper {
width: 290px;
max-width: 100%;
}
.website-insights-toolbar > .semi-select {
width: 160px;
}
.website-insights-toolbar > .semi-button {
margin-left: auto;
}
.website-insights-article-meta {
display: grid;
gap: 4px;
min-width: 0;
}
.website-insights .website-insights-title {
display: block;
width: 100%;
padding: 0;
border: 0;
border-radius: 0;
background: transparent;
color: var(--semi-color-text-0);
font-weight: 500;
line-height: 1.6;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: left;
cursor: pointer;
}
.website-insights .website-insights-title:hover {
color: var(--semi-color-primary);
}
.website-insights .website-insights-title:focus-visible {
outline: 2px solid var(--semi-color-primary);
outline-offset: 2px;
}
.website-insights-manage-row {
padding-block: 10px;
border-bottom: 1px solid var(--semi-color-border);
}
.website-insights-manage-row > span:first-child {
flex: 1;
}
.website-insights-editor-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) 250px;
gap: 24px;
}
.website-insights-editor-main {
min-width: 0;
}
.website-insights-editor-main .website-insights-section-title {
margin: 0 0 14px;
line-height: 24px;
}
.website-insights-editor-main .website-insights-detail-title {
margin-top: 10px;
}
/* SideSheet renders outside Form, so its slots need their own field spacing. */
.website-insights-editor-main .website-insights-editor-field {
min-width: 0;
margin: 0 0 18px;
padding: 0;
}
.website-insights-editor-field > .semi-form-field-label {
margin-bottom: 8px;
}
.website-insights-aside,
.website-insights-related {
display: flex;
flex-direction: column;
gap: 16px;
}
.website-insights-related {
max-height: 260px;
overflow-y: auto;
}
.website-insights-toc {
margin-top: 12px;
line-height: 1.8;
overflow-wrap: anywhere;
}
.website-insights-editor-footer {
justify-content: flex-end;
}
@media (max-width: 767px) {
.website-settings-page {
/* Match the shared mobile layout's 5px plus the page's 8px. */
padding-inline: 13px;
}
.website-insights-editor-layout {
grid-template-columns: minmax(0, 1fr);
}
.website-insights-category-actions {
visibility: visible;
}
.website-insights-toolbar > .semi-input-wrapper {
width: 100%;
}
}
+285
View File
@@ -0,0 +1,285 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useRef, useState } from 'react';
import {
Banner,
Button,
Card,
Form,
Spin,
Tabs,
Typography,
} from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { showError, showSuccess, showWarning } from '../../helpers';
import {
TABS,
emptySettings,
settingsFromConfig,
serializeSettings,
validateField,
validateSettings,
} from './model';
import { getWebsiteSettings, saveWebsiteSettings } from './settingsApi';
import WebsiteField from './WebsiteField';
import QrCodeUpload from './QrCodeUpload';
import InsightsPanel from './InsightsPanel';
import './WebsiteSettings.css';
export default function WebsiteSettings() {
const { t } = useTranslation();
const [activeTab, setActiveTab] = useState('home');
const [values, setValues] = useState(emptySettings);
const [errors, setErrors] = useState({});
const [saving, setSaving] = useState(false);
const [uploading, setUploading] = useState(false);
const [resetVersion, setResetVersion] = useState(0);
const [dirty, setDirty] = useState(false);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState('');
const [loadVersion, setLoadVersion] = useState(0);
const originalConfig = useRef({});
const savePending = useRef(false);
useEffect(() => {
let active = true;
setLoading(true);
setLoadError('');
getWebsiteSettings()
.then((config) => {
if (!active) return;
originalConfig.current = config ?? {};
setValues(settingsFromConfig(config));
setDirty(false);
setErrors({});
})
.catch((error) => {
if (active)
setLoadError(error.message || '官网配置读取失败,请稍后重试');
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, [loadVersion]);
const disabled = saving || loading || Boolean(loadError);
useEffect(() => {
if (!dirty) return;
const warn = (event) => {
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [dirty]);
const tab = TABS.find((item) => item.key === activeTab);
const change = (name, value) => {
setDirty(true);
setValues((previous) => ({ ...previous, [name]: value }));
setErrors((previous) =>
previous[name]
? { ...previous, [name]: validateField(name, value) }
: previous,
);
};
const clear = () => {
setDirty(true);
setResetVersion((version) => version + 1);
setValues(emptySettings());
setErrors({});
setUploading(false);
};
const save = async () => {
if (savePending.current || disabled || uploading) return;
const nextErrors = validateSettings(values);
setErrors(nextErrors);
if (Object.keys(nextErrors).length) {
// Keep field errors for every tab; report each hidden invalid tab only once.
for (const item of TABS) {
if (
item.key !== activeTab &&
item.fields.some((name) => nextErrors[name])
) {
showWarning(t(`请完善${item.label}的配置`));
}
}
return;
}
savePending.current = true;
setSaving(true);
try {
const configurationJson = serializeSettings(
values,
originalConfig.current,
);
const result = await saveWebsiteSettings(configurationJson);
originalConfig.current = result.config ?? JSON.parse(configurationJson);
setValues(settingsFromConfig(originalConfig.current));
setDirty(false);
showSuccess(t('官网设置已保存'));
} catch (error) {
showError(t(error.message || '保存失败,请稍后重试'));
} finally {
setSaving(false);
savePending.current = false;
}
};
return (
<div className='website-settings-page' aria-busy={loading || saving}>
<Spin
spinning={loading || saving}
size='large'
style={{
minHeight: 200,
width: '100%',
flex: 1,
display: 'flex',
flexDirection: 'column',
}}
childStyle={{ flex: 1, display: 'flex', flexDirection: 'column' }}
data-testid='website-settings-loading'
>
<Card className='website-settings-card'>
<Typography.Title heading={4} style={{ marginBottom: 8 }}>
{t('官网设置')}
</Typography.Title>
<Typography.Paragraph type='tertiary'>
{t('配置官网展示内容与商务联系信息')}
</Typography.Paragraph>
{loadError ? (
<Banner
type='danger'
closeIcon={null}
description={t(loadError)}
fullMode={false}
>
<Button onClick={() => setLoadVersion((version) => version + 1)}>
{t('重新加载')}
</Button>
</Banner>
) : null}
<Tabs type='line' activeKey={activeTab} onChange={setActiveTab}>
{TABS.map((item) => (
<Tabs.TabPane
key={item.key}
itemKey={item.key}
tab={t(item.label)}
/>
))}
</Tabs>
<Form
onSubmit={save}
className={activeTab === 'insights' ? 'py-5' : 'max-w-4xl py-5'}
autoComplete='off'
>
<Typography.Paragraph
type='tertiary'
className='website-settings-tab-description'
>
{t(tab.description)}
</Typography.Paragraph>
{activeTab === 'insights' ? (
<InsightsPanel
key={resetVersion}
value={values.insights}
onChange={(value) => change('insights', value)}
disabled={disabled}
error={errors.insights}
/>
) : (
<div className='grid grid-cols-1 gap-x-7 md:grid-cols-2'>
{tab.fields.map((name) => (
<div
key={name}
className={name === 'address' ? 'md:col-span-2' : ''}
>
<WebsiteField
name={name}
value={values[name]}
error={errors[name]}
disabled={disabled}
onChange={(value) => change(name, value)}
onBlur={() =>
setErrors((previous) => ({
...previous,
[name]: validateField(name, values[name]),
}))
}
>
{name === 'wechatQrCode' && (
<QrCodeUpload
value={values.wechatQrCode}
onChange={(url) => change(name, url)}
busy={disabled}
onBusyChange={setUploading}
resetVersion={resetVersion}
invalid={Boolean(errors[name])}
/>
)}
</WebsiteField>
{activeTab === 'home' && name === 'teamMembers' && (
<Typography.Text type='tertiary' size='small'>
{t('研发人员占比')}:
{values.researchRatio || t('未配置')}
</Typography.Text>
)}
</div>
))}
</div>
)}
<Banner
type='info'
closeIcon={null}
className='website-settings-notice !rounded-lg'
style={{
marginTop: 10,
marginBottom: 2,
paddingTop: 2,
paddingBottom: 2,
}}
description={t('四个页签共用一份配置,保存时将统一校验并提交。')}
/>
<div
className='flex justify-center gap-2'
style={{ marginTop: 18 }}
>
<Button onClick={clear} disabled={disabled}>
{t('清空')}
</Button>
<Button
theme='solid'
htmlType='submit'
loading={saving}
disabled={disabled || uploading}
>
{t('保存')}
</Button>
</div>
</Form>
</Card>
</Spin>
</div>
);
}
@@ -0,0 +1,32 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { sanitizeArticleHtml } from '../../components/common/ui/richTextContent.js';
import { countRichText } from '../../components/common/ui/richTextLength.js';
export { sanitizeArticleHtml };
export function articleContentInfo(html) {
const template = document.createElement('template');
template.innerHTML = sanitizeArticleHtml(html);
return {
count: countRichText(template.content.textContent),
headings: [...template.content.querySelectorAll('h2,h3')]
.map((h) => ({ level: h.tagName, text: h.textContent.trim() }))
.filter((h) => h.text),
};
}
+201
View File
@@ -0,0 +1,201 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { articleImageSource } from '../../components/common/ui/richTextImages.js';
import {
ARTICLE_BODY_LIMIT,
countArticleHtml,
} from '../../components/common/ui/richTextLength.js';
export const emptyInsights = () => ({
categories: [
{ id: 'company', name: '公司动态' },
{ id: 'product', name: '产品更新' },
{ id: 'industry', name: '行业洞察' },
],
articles: [],
});
export function createContentId() {
// randomUUID requires HTTPS; getRandomValues also works on HTTP admin sites.
return (
globalThis.crypto.randomUUID?.() ??
Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)), (byte) =>
byte.toString(16).padStart(2, '0'),
).join('')
);
}
export function categoryError(name, categories, id) {
const value = String(name ?? '').trim();
if (!value) return '请输入分类名称';
if (value.length > 12) return '分类名称不能超过 12 个字符';
if (
['全部内容', '全部分类'].includes(value) ||
categories.some((c) => c.id !== id && c.name === value)
)
return '分类名称已存在,请使用其他名称';
return '';
}
export function newArticle(category = 'all') {
const now = new Date();
const date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
return {
id: '',
title: '',
category,
date,
subtitle: '',
summary: '',
tag: '',
body: '',
toc: true,
related: [],
};
}
export function articleErrors(article, insights) {
const errors = {};
for (const [key, label, limit, required] of [
['title', '文章标题', 80, true],
['summary', '卡片摘要', 200, true],
['subtitle', '详情副标题', 160, false],
['tag', '角标标签', 12, false],
]) {
const text = String(article[key] ?? '').trim();
if (required && !text) errors[key] = `请输入${label}`;
else if (text.length > limit)
errors[key] = `${label}不能超过 ${limit} 个字符`;
}
if (
article.category !== 'all' &&
!insights.categories.some((c) => c.id === article.category)
)
errors.category = '请选择所属分类';
const date = String(article.date ?? '');
if (
!/^\d{4}-\d{2}-\d{2}$/.test(date) ||
!Number.isFinite(Date.parse(date)) ||
new Date(date).toISOString().slice(0, 10) !== date
)
errors.date = date ? '请选择有效的发布日期' : '请选择发布日期';
const body = String(article.body ?? '');
if (
!body.replace(/<[^>]*>/g, '').replace(/&nbsp;|&#160;|\s/g, '') &&
!/<img\s/i.test(body)
)
errors.body = '请输入文章正文';
else if (countArticleHtml(body) > ARTICLE_BODY_LIMIT)
errors.body = `文章正文不能超过 ${ARTICLE_BODY_LIMIT} 字`;
if (
/<(?:script|style|iframe|object|svg|math)\b|\son\w+\s*=|(?:javascript|blob):/i.test(
body,
) ||
[...body.matchAll(/<img\b[^>]*\bsrc\s*=\s*["']([^"']*)["'][^>]*>/gi)].some(
(match) => !articleImageSource(match[1]),
)
)
errors.body = '正文包含不支持的内容,请清除格式后重试';
if (
!Array.isArray(article.related) ||
article.related.length > 3 ||
new Set(article.related).size !== article.related.length ||
article.related.some(
(id) => id === article.id || !insights.articles.some((a) => a.id === id),
)
)
errors.related = '最多选择 3 篇有效的其他文章';
return errors;
}
export function normalizeInsights(value) {
const data = value ?? emptyInsights();
return {
...data,
categories: (data.categories || []).map((c) => ({
...c,
id: String(c.id),
name: String(c.name ?? '').trim(),
})),
articles: (data.articles || []).map((a) => ({
...a,
...Object.fromEntries(
[
'id',
'title',
'category',
'date',
'subtitle',
'summary',
'tag',
'body',
].map((key) => [key, String(a[key] ?? '').trim()]),
),
toc: a.toc !== false,
related: [...(a.related || [])],
})),
};
}
export function validateInsights(value) {
if (!value) return '';
if (!Array.isArray(value.categories) || !Array.isArray(value.articles))
return '动态与洞察配置格式不正确';
const { categories, articles } = value;
if (
categories.some(
(c) =>
!c?.id || c.id === 'all' || categoryError(c.name, categories, c.id),
) ||
new Set(categories.map((c) => c.id)).size !== categories.length
)
return '请检查内容分类配置';
if (new Set(articles.map((a) => a?.id)).size !== articles.length)
return '文章标识不能重复';
for (const article of articles) {
if (!article?.id) return '文章标识不能为空';
const errors = articleErrors(article, value);
if (Object.keys(errors).length)
return `${article.title || '未命名文章'}:${Object.values(errors)[0]}`;
}
return '';
}
export function removeArticle(insights, id) {
return {
...insights,
articles: insights.articles
.filter((a) => a.id !== id)
.map((a) => ({
...a,
related: a.related.filter((other) => other !== id),
})),
};
}
export function filterArticles(insights, keyword, category) {
const query = keyword.trim().toLocaleLowerCase();
return insights.articles
.filter(
(a) =>
(category === 'all' || a.category === category) &&
`${a.title} ${a.summary}`.toLocaleLowerCase().includes(query),
)
.sort((a, b) => b.date.localeCompare(a.date));
}
+291
View File
@@ -0,0 +1,291 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { isLocalQrPreview } from './qrPreview.js';
import {
emptyInsights,
normalizeInsights,
validateInsights,
} from './insightsModel.js';
export const TABS = [
{
key: 'home',
label: '首页',
description: '配置官网首页展示的核心指标。',
fields: ['paidCustomers', 'dailyTokens', 'costReduction', 'teamMembers'],
},
{
key: 'about',
label: '关于微词元',
description: '配置官网关于微词元区域展示的团队与服务信息。',
fields: ['teamMembers', 'researchRatio', 'headquarters', 'serviceNetwork'],
},
{
key: 'demo',
label: '预约演示',
description: '配置官网预约演示区域的联系信息,便于客户直接联系商务团队。',
fields: ['businessPhone', 'businessEmail', 'wechatQrCode', 'address'],
},
{
key: 'insights',
label: '动态与洞察',
description: '管理官网文章与内容分类,让每一次更新清晰可见。',
fields: ['insights'],
},
];
export const FIELDS = {
paidCustomers: {
label: '付费企业客户',
placeholder: '请输入付费企业客户数量,例如 300+',
help: '正整数,可带 +。',
},
dailyTokens: {
label: '平台日均 Token 调用',
placeholder: '请输入平台日均 Token 调用量,例如 500亿+',
help: '支持正数及万、亿单位,可带 +。',
},
costReduction: {
label: '客户月度 AI 调用成本',
placeholder: '请输入成本降幅,例如 20%',
help: '填写 0~100 的百分比,官网可展示为 ↓20%。',
},
teamMembers: {
label: '团队成员',
placeholder: '请输入团队成员数量,例如 50+',
help: '首页与关于微词元共用此字段,正整数,可带 +。',
},
researchRatio: {
label: '研发人员占比',
placeholder: '请输入研发人员占比,例如 60%',
help: '填写 0~100 的百分比。',
},
headquarters: {
label: '总部',
placeholder: '请输入总部所在地,例如 珠海 / 广州',
},
serviceNetwork: {
label: '服务网络',
placeholder: '请输入服务网络覆盖范围,例如 辐射全国',
},
businessPhone: {
label: '商务电话',
placeholder: '请输入手机号、固定电话或 400 电话',
help: '例如 13800138000、020-88888888、400-123-4567。',
},
businessEmail: {
label: '商务邮箱',
placeholder: '请输入商务联系邮箱,例如 business@example.com',
},
wechatQrCode: { label: '企业微信' },
address: { label: '联系地址', placeholder: '请输入详细联系地址' },
insights: { label: '动态与洞察' },
};
export const emptySettings = () =>
Object.fromEntries(
Object.keys(FIELDS).map((key) => [
key,
key === 'insights' ? emptyInsights() : '',
]),
);
const PHONE =
/^(?:(?:\+?86[- ]?)?1[3-9]\d{9}|0\d{2,3}-?\d{7,8}(?:[-转]\d{1,6})?|400-?\d{3}-?\d{4})$/;
const EMAIL =
/^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+$/;
export function isAbsoluteImageUrl(value) {
try {
const url = new URL(value);
return (
['http:', 'https:'].includes(url.protocol) &&
!url.username &&
!url.password
);
} catch {
return false;
}
}
export function validateField(key, rawValue) {
if (key === 'insights') return validateInsights(rawValue);
const value = String(rawValue ?? '').trim();
if (!value)
return key === 'wechatQrCode'
? '请上传企业微信二维码'
: `请输入${FIELDS[key].label}`;
if (
['paidCustomers', 'teamMembers'].includes(key) &&
!/^[1-9]\d*\+?$/.test(value)
)
return '请输入正整数,可在末尾添加 +';
if (
key === 'dailyTokens' &&
(!/^\d+(?:\.\d+)?[万亿]?\+?$/.test(value) || parseFloat(value) <= 0)
)
return '请输入大于 0 的调用量,例如 500亿+';
if (
['costReduction', 'researchRatio'].includes(key) &&
(!/^\d+(?:\.\d{1,2})?%?$/.test(value) || parseFloat(value) > 100)
)
return '请输入 0~100 的百分比,最多两位小数';
if (key === 'businessPhone' && !PHONE.test(value))
return '请输入有效的手机号、固定电话或 400 电话';
if (
key === 'businessEmail' &&
(value.length > 254 ||
!EMAIL.test(value) ||
value.split('@')[0].includes('..') ||
/^\.|\.$/.test(value.split('@')[0]))
)
return '请输入有效的商务邮箱';
if (
key === 'wechatQrCode' &&
!isAbsoluteImageUrl(value) &&
!isLocalQrPreview(value)
)
return '请上传二维码并获取有效的 HTTP(S) 绝对地址';
if (value.length > 200 && key !== 'wechatQrCode' && key !== 'businessEmail')
return '内容不能超过 200 个字符';
return '';
}
export function validateSettings(values) {
return Object.fromEntries(
[...new Set(TABS.flatMap((tab) => tab.fields))]
.map((key) => [key, validateField(key, values[key])])
.filter(([, error]) => error),
);
}
export function normalizeSettings(values) {
return Object.fromEntries(
Object.keys(FIELDS).map((key) => [
key,
key === 'insights'
? normalizeInsights(values[key])
: String(values[key] ?? '').trim(),
]),
);
}
export function serializeSettings(values, original = {}) {
return JSON.stringify(settingsToConfig(values, original));
}
const CONFIG_FIELDS = {
home: {
paidCustomers: 'payingCustomers',
dailyTokens: 'dailyTokenCalls',
costReduction: 'monthlyAiCostReduction',
},
about: {
teamMembers: 'teamMembers',
researchRatio: 'researchStaffRatio',
headquarters: 'headquarters',
serviceNetwork: 'serviceNetwork',
},
demo: {
businessPhone: 'businessPhone',
businessEmail: 'businessEmail',
wechatQrCode: 'wechatQrCode',
address: 'address',
},
};
export function settingsFromConfig(config) {
const values = emptySettings();
if (config === null) return values;
if (!config || typeof config !== 'object' || Array.isArray(config))
throw new Error('官网配置格式不正确,请联系管理员检查');
for (const [group, fields] of Object.entries(CONFIG_FIELDS)) {
if (
config[group] !== undefined &&
(!config[group] ||
typeof config[group] !== 'object' ||
Array.isArray(config[group]))
)
throw new Error('官网配置分组格式不正确,请联系管理员检查');
for (const [field, apiField] of Object.entries(fields)) {
const value = config[group]?.[apiField];
if (value !== undefined && typeof value !== 'string')
throw new Error('官网配置字段格式不正确,请联系管理员检查');
values[field] = value ?? '';
}
}
if (config.insights !== undefined) {
if (
!config.insights ||
!Array.isArray(config.insights.categories) ||
!Array.isArray(config.insights.articles)
)
throw new Error('动态与洞察配置格式不正确,请联系管理员检查');
try {
values.insights = normalizeInsights(config.insights);
} catch {
throw new Error('动态与洞察配置格式不正确,请联系管理员检查');
}
}
return values;
}
export function settingsToConfig(values, original = {}) {
const normalized = normalizeSettings(values);
const config = { ...original };
for (const [group, fields] of Object.entries(CONFIG_FIELDS)) {
config[group] = {
...original?.[group],
...Object.fromEntries(
Object.entries(fields).map(([field, apiField]) => [
apiField,
normalized[field],
]),
),
};
}
config.insights = normalized.insights;
return config;
}
export function validateImageFile(file) {
if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type))
return '仅支持 JPG、PNG、WebP 图片';
if (!file.size || file.size > 2 * 1024 * 1024)
return '图片大小需大于 0 且不能超过 2 MB';
return '';
}
export function resolveImageUrl(value, publicBaseUrl = '') {
if (isAbsoluteImageUrl(value)) return new URL(value).href;
// A dev proxy origin is not a public asset host. Only use an explicitly configured base.
if (
publicBaseUrl &&
isAbsoluteImageUrl(publicBaseUrl) &&
typeof value === 'string' &&
value.startsWith('/') &&
!value.startsWith('//')
) {
return new URL(value, publicBaseUrl).href;
}
throw new Error(
'上传接口未返回可供官网使用的绝对图片地址,请配置公共资源域名或联系后端。',
);
}
+40
View File
@@ -0,0 +1,40 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// Local preview is disabled; uploads use the backend resource endpoint.
export const LOCAL_QR_PREVIEW_ENABLED = false;
export function isLocalQrPreview(value) {
return (
LOCAL_QR_PREVIEW_ENABLED &&
/^data:image\/(?:jpeg|png|webp);base64,(?:[A-Za-z0-9+/]{4})+(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(
value,
)
);
}
export function readLocalQrPreview(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(new Error('图片读取失败,请重新选择'));
reader.onabort = () => reject(new Error('图片读取已取消,请重新选择'));
reader.readAsDataURL(file);
});
}
+119
View File
@@ -0,0 +1,119 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { requestWebsite } from '../../helpers/websiteApi';
import { articleImageSource } from '../../components/common/ui/richTextImages';
import {
resolveImageUrl,
settingsFromConfig,
validateImageFile,
validateSettings,
} from './model';
export async function uploadWebsiteQrCode(file) {
return uploadWebsiteImage(file);
}
export async function uploadWebsiteImage(file) {
const error = validateImageFile(file);
if (error) throw new Error(error);
return uploadImage(file);
}
async function uploadImage(file) {
const body = new FormData();
body.append('file', file);
const data = await requestWebsite(
'post',
'/api/customer-service/upload',
body,
'图片上传失败,请重试',
);
if (!data?.url) throw new Error('上传接口未返回图片地址,请重试');
return resolveImageUrl(
data.url,
import.meta.env.VITE_WEBSITE_ASSET_BASE_URL || '',
);
}
export async function saveWebsiteSettings(configurationJson) {
if (typeof configurationJson !== 'string')
throw new Error('官网设置需序列化为 JSON 字符串后提交');
const payload = JSON.parse(configurationJson);
if (Object.keys(validateSettings(settingsFromConfig(payload))).length)
throw new Error('请完整填写并检查官网设置');
// Existing article editors keep local images in memory; persist URLs in the public config.
const uploaded = new Map();
for (const article of payload.insights?.articles || []) {
const images = [
...article.body.matchAll(
/<img\b[^>]*\bsrc\s*=\s*["'](data:image\/[^"']+)["'][^>]*>/gi,
),
];
for (const [, source] of images) {
if (!articleImageSource(source))
throw new Error('文章中包含无效图片,请重新插入');
if (!uploaded.has(source)) {
const [meta, encoded] = source.split(',');
const type = meta.slice(5).split(';')[0];
const bytes = Uint8Array.from(atob(encoded), (char) =>
char.charCodeAt(0),
);
const file = new File([bytes], `article.${type.split('/')[1]}`, {
type,
});
uploaded.set(source, await uploadImage(file));
}
article.body = article.body.replaceAll(
source,
uploaded.get(source).replaceAll('&', '&amp;'),
);
}
}
configurationJson = JSON.stringify(payload);
if (new TextEncoder().encode(configurationJson).byteLength > 60 * 1024)
throw new Error('官网配置不能超过 60 KiB,请精简内容或减少图片');
await requestWebsite(
'post',
'/api/website/page-config',
{ config: configurationJson },
'官网设置保存失败,请稍后重试',
);
return { saved: true, config: payload };
}
export async function getWebsiteSettings() {
const data = await requestWebsite(
'get',
'/api/website/page-config',
undefined,
'官网配置读取失败,请稍后重试',
);
if (data === null) return null;
if (typeof data !== 'string') throw new Error('官网配置响应格式不正确');
let config;
try {
config = JSON.parse(data);
} catch {
throw new Error('官网配置不是有效的 JSON,请联系管理员检查');
}
if (config === null) throw new Error('官网配置格式不正确');
settingsFromConfig(config);
return config;
}