feat(doc): 首页登录分流 + 文档站(简易 CMS / 静态 HTML / sitemap)

- 首页:`/` 未登录原地显示登录页(不再跳 /login),已登录直接进 `/dashboard`;
  看板路由由 `/` 迁到 `/dashboard`,侧边栏「首页」与无权限回跳同步;
  桌面端「工具 → 打开配置页」的 `/?token=` 免登录仍然可用
- 文档站:`/doc/**` 由后端整站生成静态 HTML(顶部分类 tab 全局切换、左侧栏目 → 内容页、
  右侧本页目录);`/sitemap.txt` 新链接追加到末尾,下架 / 删除的会被清理
- 平台管理 · 文档管理(`/admin/doc`):分类 / 栏目 / 内容页(Markdown)简易 CMS,
  内容页有编辑表单与列表,保存后自动重生成目录与静态页面
- 登录页右下角、顶栏(登录后)、看板右上角新增进入文档站的链接
- 部署:nginx 模板为 `/doc`、`/doc/`、`/sitemap.txt` 增加反代(否则会落到 SPA 回退);
  Vite dev server 增加同名代理;`middleware/frontend.js` 排除这些路径
- 登录页插画改为内联 SVG(沿用工作区已有的未提交改动)
- 测试:新增 Markdown 渲染单测;后端 218 个用例通过,前端 typecheck / build 通过

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-11-07 20:33:46 +08:00
parent 0c59bede7e
commit 78cee0fe1a
25 changed files with 3059 additions and 118 deletions

View File

@ -78,6 +78,13 @@ packService/
- [x] **平台管理 · 套餐管理(2026-11-07)**:左侧「平台管理」新增**套餐管理**(`/admin/plans`):
新增 / 改价 / 改天数 / 上下架 / 删除续期套餐;续期下单只按库里的售价算钱,改完即生效、不用发版
(接口 `GET/POST/PUT/DELETE /api/web/admin/plans`,详见 [`backend/README.md`](backend/README.md))
- [x] **登录入口与文档站(2026-11-07)**:
- **`/` 就是入口**:已登录 → 自动进看板 `/dashboard`;未登录 → **原地**显示登录页(地址保持在 `/`,不再跳 `/login`);
看板路由从 `/` 挪到 `/dashboard`,侧边栏「首页」与各处「被拒绝」回跳同步改过去;
- **文档站** `/doc/**`:后端生成的**静态 HTML**(顶部 tab 切分类、左侧「栏目 → 内容页」、右侧本页目录),
页面保存后自动重生成,新链接追加到 `/sitemap.txt`;
- **平台管理 · 文档管理**(`/admin/doc`):分类 / 栏目 / 内容页(Markdown)的简易 CMS,保存即重生成;
- 登录页右下角、顶栏(登录后)与看板右上角都有进入文档站的链接
- [x] **待支付订单 2 小时自动失效(2026-10-29)**:下单后 2 小时(`PAY_ORDER_TTL`,默认 7200 秒)内未支付,
订单自动关闭(`status=2`);之后的支付回调 / 手工确认一律 409。与微信扫码支付二维码有效期对齐,
定时任务每分钟扫一次,详情 / 列表 / 回调读路径也会顺手收口(详见 [`backend/README.md`](backend/README.md))

View File

@ -39,6 +39,8 @@ packService/backend
│ │ │ ├── admin_order.js # /api/web/admin/orders[/:orderNo/confirm] 所有订单 + 确认订单
│ │ │ ├── admin_plan.js # /api/web/admin/plans[/:id] 续期套餐(改价 / 改天数 / 上下架)
│ │ │ ├── admin_extension.js # /api/web/admin/extension Chrome 插件集中配置(❗需平台管理员)
│ │ │ ├── admin_doc.js # /api/web/admin/doc/* 文档站 CMS(分类 / 栏目 / 内容页,❗需平台管理员)
│ │ │ ├── doc.js # GET /doc/**、/sitemap.txt 文档站(公开,直接回生成好的静态 HTML)
│ │ │ ├── extension.js # /api/web/extension/config 插件读取的配置(公开只读,无令牌)
│ │ │ └── test.js # /api/web/test/{device-login,scan} 前端测试页的模拟接口(仅非生产环境注册)
│ │ ├── internal/ # 运维/内部(❗需内部令牌,挂在 middleware.internalAuth() 后面)
@ -67,7 +69,10 @@ packService/backend
│ │ ├── sys_config.js # sys_config
│ │ ├── scanner.js # scanners
│ │ ├── scan_channel.js # scan_channels
│ │ └── scan_record.js # scan_records(去重)
│ │ ├── scan_record.js # scan_records(去重)
│ │ ├── doc_category.js # doc_categories(文档分类 = 顶部 tab)
│ │ ├── doc_section.js # doc_sections(分类下的一级栏目)
│ │ └── doc_article.js # doc_articles(内容页,Markdown 原文)
│ ├── service
│ │ ├── auth.js # 登录校验(bcrypt 密码比对)+ 自助注册
│ │ ├── admin_member.js # 平台管理员:名单维护 + isAdmin(admin_members / INTERNAL_ADMIN_IDS)
@ -82,7 +87,11 @@ packService/backend
│ │ ├── scan.js # 中控通道上报 / 扫码入库去重 / 扫码查询
│ │ ├── health.js # MySQL / Redis 连通性探测
│ │ ├── user.js # 用户数据访问(app.model.User)
│ │ └── wx_gateway.js # 微信登录网关:临时码 / 验签 / 会话长轮询 / 绑定关系
│ │ ├── wx_gateway.js # 微信登录网关:临时码 / 验签 / 会话长轮询 / 绑定关系
│ │ ├── doc.js # 文档站 CMS:分类 / 栏目 / 内容页的增删改查(写完自动重生成)
│ │ └── doc_site.js # 文档站生成:把库里的内容渲染成 /doc/** 静态 HTML + /sitemap.txt
│ ├── lib
│ │ └── markdown.js # 极简 Markdown → HTML(先转义再拼标签,附文章内目录)
│ └── router.js
├── config
│ ├── config.default.js # 统一配置(连接 / 端口 / 安全 / 前端入口 / 内部鉴权)
@ -975,7 +984,7 @@ await this.ctx.service.cache.remember('user:1', 60, () => loadFromMysql());
- 「查状态」→ `GET /api/wechat/status?code=…`(无需登录):`pending`(待扫码)/ `confirmed`(已被确认)/ `expired`(没这个码);
- 「请求登录」→ `POST /api/wechat/confirm`(`{ code }`):`data.status='confirmed'` 即授权成功,电脑端正在长轮询的请求会**立即**完成登录;已用过/不存在/格式错分别返回 `used` / `expired` / `bad_format`;
- **鉴权完全模仿小程序**:AJAX 把用户 JWT 放在 `Authorization: Bearer` 头里(`fetch` 不带 `credentials`),页面上也把这枚令牌显示出来方便贴到小程序里调试;
- **鉴权总览**:`/api/web/*`、`/api/wechat/confirm` 走 `app/middleware/api_auth.js`(**只认 header 里的用户令牌**),其中 `/api/web/admin/*` 再叠一层 `app/middleware/platform_admin.js`(平台管理员);`/api/users*`、`/api/configs*`、`/api/scanners*` 走 `app/middleware/internal_auth.js`(`X-Internal-Token` 或白名单账号的 user JWT);`/api/scanner/*`、`/api/scan/*` 走 `app/middleware/scanner_auth.js`(设备长期 JWT);公开接口只有 `/api/info`、`/health`、`/api/wechat/{status,qrcode.svg}`、`/api/wechat-gateway/notify`、`/api/device/login` 与 `/api/web/auth/*`;
- **鉴权总览**:`/api/web/*`、`/api/wechat/confirm` 走 `app/middleware/api_auth.js`(**只认 header 里的用户令牌**),其中 `/api/web/admin/*` 再叠一层 `app/middleware/platform_admin.js`(平台管理员);`/api/users*`、`/api/configs*`、`/api/scanners*` 走 `app/middleware/internal_auth.js`(`X-Internal-Token` 或白名单账号的 user JWT);`/api/scanner/*`、`/api/scan/*` 走 `app/middleware/scanner_auth.js`(设备长期 JWT);公开接口只有 `/api/info`、`/health`、`/api/wechat/{status,qrcode.svg}`、`/api/wechat-gateway/notify`、`/api/device/login` 与 `/api/web/auth/*`;另外 `/doc/**`、`/sitemap.txt` 是文档站的静态页面(公开,不走 SPA,见「文档站」一节);
- 密码等敏感信息放 `config/config.local.js`(已 gitignore)或环境变量,不要写进 `config.default.js`。
- 生产环境请修改 `config/config.default.js` 中的 `config.keys`。
@ -1049,6 +1058,36 @@ await this.ctx.service.cache.remember('user:1', 60, () => loadFromMysql());
(后台页面已不提供这个输入框;配置里的值只在 version.json 拉不到时兜底);
- 生产若配了 `CORS_ORIGINS` 白名单,记得把 `chrome-extension://<扩展ID>` 加进去(默认 `*` 不用管)。
## 文档站(简易 CMS,2026-11-07)
文档站是**静态 HTML**:内容存在库里,保存时由 `service/docSite` 整站渲染到 `run/doc-site/`(`run/` 被 gitignore),
`controller/web/doc.js` 只负责回文件(文件不存在时按需重新生成,部署后不用手工跑构建)。
- 层级:**分类**(文档站顶部 tab)→ **栏目**(侧边栏分组)→ **内容页**(Markdown,`lib/markdown.js` 渲染);
- 页面地址:`/doc/`、`/doc/<分类编码>/`、`/doc/<分类编码>/<文章 slug>.html`;
- 新链接按顺序追加到 `/sitemap.txt` 末尾(下架 / 删除的会被清掉);
- `middleware/frontend.js` 已把 `/doc/**`、`/sitemap.txt` 从 SPA 里排除;Vite dev server 也把它们反代给后端;
- 生成目录 / sitemap 的站点根地址:`config.docSite.baseUrl`(env `SITE_BASE_URL`),不配就用触发请求的 origin。
### 接口(`/api/web/admin/doc/*`,全部要求平台管理员)
| 方法 | 路径 | 说明 |
|---|---|---|
| GET | `/api/web/admin/doc/tree` | 分类 → 栏目 → 内容页(树;文章不带正文,带 `url` / `statusText`) |
| POST | `/api/web/admin/doc/categories` | 新增分类 `{ code?, name, description?, sort?, status? }`;`code` 留空自动 `cat1`、`cat2`… |
| PUT | `/api/web/admin/doc/categories/:id` | 修改分类(`code` 创建后不可改,其余只改传了的字段) |
| DELETE | `/api/web/admin/doc/categories/:id` | 删除分类(栏目与内容页一起软删,页面与 sitemap 一并移除) |
| POST | `/api/web/admin/doc/sections` | 新增栏目 `{ categoryId, name, sort?, status? }` |
| PUT | `/api/web/admin/doc/sections/:id` | 修改栏目(传 `categoryId` 可换分类,底下内容页跟着走) |
| DELETE | `/api/web/admin/doc/sections/:id` | 删除栏目(内容页一起软删) |
| GET | `/api/web/admin/doc/articles/:id` | 单篇(含 Markdown 正文) |
| POST | `/api/web/admin/doc/articles` | 新增内容页 `{ sectionId, title, slug?, summary?, content?, sort?, status? }`;`slug` 留空自动 `a1`、`a2`… |
| PUT | `/api/web/admin/doc/articles/:id` | 修改内容页(`slug` 创建后不可改;`status=0` 作草稿,不生成页面) |
| DELETE | `/api/web/admin/doc/articles/:id` | 删除内容页 |
| POST | `/api/web/admin/doc/rebuild` | 手动整站重生成(排查用,返回页面数与 sitemap 条数) |
公开读取(无令牌):`GET /doc/**`、`GET /sitemap.txt`。
### 前端(`frontend/`)
左侧菜单在**平台管理员**登录后会多出一组「平台管理」(`components/AppLayout.vue`):
@ -1060,6 +1099,7 @@ await this.ctx.service.cache.remember('user:1', 60, () => loadFromMysql());
| 套餐管理 | `/admin/plans` | `views/AdminPlansView.vue` | 续期套餐的新增 / 改价 / 改天数 / 上下架 / 删除(下单只按这里的售价算钱) |
| 管理员 | `/admin/members` | `views/AdminMembersView.vue` | 平台管理员列表 + 添加(按账号)+ 移除 |
| 插件配置 | `/admin/extension` | `views/AdminExtensionView.vue` | Chrome 插件的单号前缀 / 生效站点 / 跳转模板 |
| 文档管理 | `/admin/doc` | `views/AdminDocView.vue` | 文档站 CMS:分类(顶部 tab)→ 栏目 → 内容页(Markdown),保存即重生成静态页面 |
- 是否显示这组菜单靠 `GET /api/web/admin/me`(`composables/usePlatformAdmin.ts`;非管理员 403 静默当 false);
- 路由带 `meta.platformAdmin`,不是平台管理员会被守卫踢回首页(`?denied=1`);

View File

@ -0,0 +1,120 @@
'use strict';
const { Controller } = require('egg');
/** 路径参数转正整数,非法返回 null */
function toId(value) {
const id = Number(value);
return Number.isInteger(id) && id > 0 ? id : null;
}
/**
* web 平台管理员:文档站(简易 CMS)
*
* 鉴权:`middleware.apiAuth()` + `middleware.platformAdmin()`(能进来的都是平台管理员)。
*
* - `GET /api/web/admin/doc/tree` 分类 → 栏目 → 内容页(树,文章不带正文)
* - `POST /api/web/admin/doc/categories` 新增分类
* - `PUT /api/web/admin/doc/categories/:id` 修改分类(名称 / 排序 / 显隐;`code` 不可改)
* - `DELETE /api/web/admin/doc/categories/:id` 删除分类(栏目与内容页一起删)
* - `POST /api/web/admin/doc/sections` 新增栏目
* - `PUT /api/web/admin/doc/sections/:id` 修改栏目
* - `DELETE /api/web/admin/doc/sections/:id` 删除栏目(内容页一起删)
* - `GET /api/web/admin/doc/articles/:id` 单篇(含正文)
* - `POST /api/web/admin/doc/articles` 新增内容页
* - `PUT /api/web/admin/doc/articles/:id` 修改内容页
* - `DELETE /api/web/admin/doc/articles/:id` 删除内容页
* - `POST /api/web/admin/doc/rebuild` 手动整站重生成(排查用)
*
* 所有写操作都会重生成 `/doc/**` 静态页面与 `/sitemap.txt`(见 `service/doc.js`)。
*/
class WebAdminDocController extends Controller {
/** GET /api/web/admin/doc/tree */
async tree() {
const data = await this.ctx.service.doc.tree();
this.ctx.body = { ok: true, data };
}
/** POST /api/web/admin/doc/categories */
async createCategory() {
const data = await this.ctx.service.doc.createCategory(this.ctx.request.body || {});
this.ctx.status = 201;
this.ctx.body = { ok: true, data };
}
/** PUT /api/web/admin/doc/categories/:id */
async updateCategory() {
const id = this.requireId();
const data = await this.ctx.service.doc.updateCategory(id, this.ctx.request.body || {});
this.ctx.body = { ok: true, data };
}
/** DELETE /api/web/admin/doc/categories/:id */
async destroyCategory() {
const data = await this.ctx.service.doc.removeCategory(this.requireId());
this.ctx.body = { ok: true, data };
}
/** POST /api/web/admin/doc/sections */
async createSection() {
const data = await this.ctx.service.doc.createSection(this.ctx.request.body || {});
this.ctx.status = 201;
this.ctx.body = { ok: true, data };
}
/** PUT /api/web/admin/doc/sections/:id */
async updateSection() {
const id = this.requireId();
const data = await this.ctx.service.doc.updateSection(id, this.ctx.request.body || {});
this.ctx.body = { ok: true, data };
}
/** DELETE /api/web/admin/doc/sections/:id */
async destroySection() {
const data = await this.ctx.service.doc.removeSection(this.requireId());
this.ctx.body = { ok: true, data };
}
/** GET /api/web/admin/doc/articles/:id */
async showArticle() {
const data = await this.ctx.service.doc.findArticle(this.requireId());
this.ctx.body = { ok: true, data };
}
/** POST /api/web/admin/doc/articles */
async createArticle() {
const data = await this.ctx.service.doc.createArticle(this.ctx.request.body || {});
this.ctx.status = 201;
this.ctx.body = { ok: true, data };
}
/** PUT /api/web/admin/doc/articles/:id */
async updateArticle() {
const id = this.requireId();
const data = await this.ctx.service.doc.updateArticle(id, this.ctx.request.body || {});
this.ctx.body = { ok: true, data };
}
/** DELETE /api/web/admin/doc/articles/:id */
async destroyArticle() {
const data = await this.ctx.service.doc.removeArticle(this.requireId());
this.ctx.body = { ok: true, data };
}
/** POST /api/web/admin/doc/rebuild */
async rebuild() {
const { ctx } = this;
const files = await ctx.service.docSite.generate(ctx);
const model = await ctx.service.docSite.loadModel();
const urls = ctx.service.docSite.buildSitemapUrls(model, ctx.service.docSite.baseUrl(ctx));
ctx.body = { ok: true, data: { files: files.length, urls: urls.length } };
}
requireId() {
const id = toId(this.ctx.params.id);
if (!id) this.ctx.throw(400, 'id 必须是正整数');
return id;
}
}
module.exports = WebAdminDocController;

View File

@ -0,0 +1,73 @@
'use strict';
const fs = require('fs');
const { Controller } = require('egg');
/**
* 文档站(公开,静态 HTML)
*
* 后端**不参与渲染**:`service/docSite` 在内容保存时把页面生成到 `run/doc-site`,
* 这里只做「路径 → 文件」的映射与缓存头控制。文件被人删了 / 刚部署上来时按需重新生成。
*
* - `GET /doc` → 301 到 `/doc/`
* - `GET /doc/…` → 生成好的 HTML(分类首页 `index.html` / 内容页 `<slug>.html`)
* - `GET /sitemap.txt` → 全站 URL(页面顺序稳定,新增的追加在末尾)
*/
class WebDocController extends Controller {
/** GET /doc(`/doc/` 会被 koa-router 的 strict:false 归到同一条路由,这里区分处理) */
async redirect() {
const { ctx } = this;
if (ctx.path === '/doc') {
ctx.redirect('/doc/');
return;
}
await this.page();
}
/** GET /doc/** */
async page() {
const { ctx } = this;
await ctx.service.docSite.ensureSite(ctx);
const file = ctx.service.docSite.resolveFile(this.relativePath(ctx.path));
if (!file || !this.isfile(file)) {
// 页面已经下架 / 改名,文件被清掉了:整站重生成一次再试
await ctx.service.docSite.generate(ctx);
if (!file || !this.isfile(file)) ctx.throw(404, '文档页面不存在');
}
ctx.set('Cache-Control', 'no-cache');
ctx.type = 'html';
ctx.body = fs.createReadStream(file);
}
/** GET /sitemap.txt */
async sitemap() {
const { ctx } = this;
await ctx.service.docSite.ensureSite(ctx);
const file = ctx.service.docSite.sitemapPath;
if (!this.isfile(file)) await ctx.service.docSite.generate(ctx);
ctx.set('Cache-Control', 'no-cache');
ctx.type = 'text/plain; charset=utf-8';
ctx.body = fs.createReadStream(file);
}
/** `/doc/guide/welcome.html` → `guide/welcome.html`;`/doc/guide/` → `guide/index.html` */
relativePath(pathname) {
const clean = String(pathname || '').replace(/^\/doc\/?/, '');
if (!clean) return 'index.html';
return clean.endsWith('/') ? `${clean}index.html` : clean;
}
isfile(file) {
try {
return fs.statSync(file).isFile();
} catch {
return false;
}
}
}
module.exports = WebDocController;

175
backend/app/lib/markdown.js Normal file
View File

@ -0,0 +1,175 @@
'use strict';
/**
* 极简 Markdown → HTML(文档站专用)
*
* 只支持写文档够用的子集:标题 / 段落 / 列表 / 引用 / 代码块 / 行内代码 / 粗体 / 斜体 / 删除线 / 链接 / 分割线。
* **先转义再拼 HTML**:文档站是公开页面,后台输入的内容一律当纯文本处理,避免把 `<script>` 原样吐出去。
*
* `render()` 同时返回文章内目录(`toc`),供页面右侧的「本页目录」使用。
*/
const ESCAPE_MAP = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
'\'': '&#39;',
};
function escapeHtml(value) {
return String(value === undefined || value === null ? '' : value)
.replace(/[&<>"']/g, ch => ESCAPE_MAP[ch]);
}
/** 只要 http(s) / mailto / 站内绝对路径 / 锚点 / 相对路径,拒绝 javascript: 之类的协议 */
function safeHref(href) {
const raw = String(href || '').trim();
if (!raw) return '';
if (/^(https?:\/\/|mailto:)/i.test(raw)) return raw;
if (/^[/#]/.test(raw)) return raw;
// 相对路径里不能出现协议(`//evil.com` 或 `javascript:`)
if (/^[a-z][a-z0-9+.-]*:/i.test(raw)) return '';
if (raw.startsWith('//')) return '';
return raw;
}
/** 行内样式:先处理代码片段与链接,再处理强调(避免把链接文字里的 * 吃掉) */
function inline(text) {
const codeSpans = [];
let out = escapeHtml(text).replace(/`([^`]+)`/g, (match, code) => {
codeSpans.push(`<code>${code}</code>`);
return `\u0000${codeSpans.length - 1}\u0000`;
});
out = out.replace(/\[([^\]]*)\]\(([^)\s]+)\)/g, (match, label, href) => {
const target = safeHref(href);
if (!target) return label;
const external = /^https?:\/\//i.test(target);
return `<a href="${escapeHtml(target)}"${external ? ' target="_blank" rel="noopener"' : ''}>${label}</a>`;
});
out = out
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
.replace(/~~([^~]+)~~/g, '<del>$1</del>')
.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>');
return out.replace(/\u0000(\d+)\u0000/g, (match, index) => codeSpans[Number(index)] || '');
}
/**
* @param {string} markdown 原文
* @returns {{ html: string, toc: Array<{ id: string, text: string, level: number }> }}
*/
function render(markdown) {
const lines = String(markdown || '').replace(/\r\n?/g, '\n').split('\n');
const blocks = [];
const toc = [];
let headingIndex = 0;
let paragraph = [];
const flushParagraph = () => {
if (!paragraph.length) return;
const text = paragraph.join('\n').trim();
paragraph = [];
if (!text) return;
blocks.push(`<p>${inline(text).replace(/\n/g, '<br>')}</p>`);
};
let i = 0;
while (i < lines.length) {
const line = lines[i];
// 代码块:```lang ... ```
const fence = /^```\s*([\w+-]*)\s*$/.exec(line);
if (fence) {
flushParagraph();
const lang = fence[1];
const code = [];
i += 1;
while (i < lines.length && !/^```\s*$/.test(lines[i])) {
code.push(lines[i]);
i += 1;
}
i += 1; // 吃掉结尾的 ```
const cls = lang ? ` class="language-${escapeHtml(lang)}"` : '';
blocks.push(`<pre><code${cls}>${escapeHtml(code.join('\n'))}</code></pre>`);
continue;
}
if (!line.trim()) {
flushParagraph();
i += 1;
continue;
}
// 标题
const heading = /^(#{1,6})\s+(.*)$/.exec(line);
if (heading) {
flushParagraph();
const level = heading[1].length;
const text = heading[2].trim();
headingIndex += 1;
const id = `sec-${headingIndex}`;
toc.push({ id, text: text.replace(/[*`~]/g, ''), level });
blocks.push(`<h${level} id="${id}">${inline(text)}</h${level}>`);
i += 1;
continue;
}
// 分割线
if (/^\s*(---+|\*\*\*+|___+)\s*$/.test(line)) {
flushParagraph();
blocks.push('<hr>');
i += 1;
continue;
}
// 引用(整段连续 > 行)
if (/^\s*>\s?/.test(line)) {
flushParagraph();
const quote = [];
while (i < lines.length && /^\s*>\s?/.test(lines[i])) {
quote.push(lines[i].replace(/^\s*>\s?/, ''));
i += 1;
}
blocks.push(`<blockquote>${render(quote.join('\n')).html}</blockquote>`);
continue;
}
// 列表(有序 / 无序;只支持一层)
if (/^\s*(?:[-*+]|\d+\.)\s+/.test(line)) {
flushParagraph();
const ordered = /^\s*\d+\.\s+/.test(line);
const items = [];
while (i < lines.length) {
const item = /^\s*(?:[-*+]|\d+\.)\s+(.*)$/.exec(lines[i]);
if (!item) break;
items.push(item[1]);
i += 1;
}
const tag = ordered ? 'ol' : 'ul';
blocks.push(`<${tag}>${items.map(text => `<li>${inline(text)}</li>`).join('')}</${tag}>`);
continue;
}
paragraph.push(line);
i += 1;
}
flushParagraph();
return { html: blocks.join('\n'), toc };
}
/** 纯文本摘要:去掉 Markdown 记号,给列表 / meta description 用 */
function plainText(markdown, maxLength = 120) {
const text = String(markdown || '')
.replace(/```[\s\S]*?```/g, ' ')
.replace(/[#>*`~\-]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (text.length <= maxLength) return text;
return `${text.slice(0, maxLength)}…`;
}
module.exports = { render, plainText, escapeHtml };

View File

@ -71,6 +71,8 @@ module.exports = (options, app) => {
function isFrontendRequest(ctx) {
if (ctx.method !== 'GET' && ctx.method !== 'HEAD') return false;
if (ctx.path.startsWith('/download/')) return false;
// 文档站(/doc/**)与 sitemap 是后端生成并落盘的静态文件,不交给 SPA
if (ctx.path === '/sitemap.txt' || ctx.path === '/doc' || ctx.path.startsWith('/doc/')) return false;
return !ctx.path.startsWith('/api/') && ctx.path !== '/api' && ctx.path !== '/health';
}

View File

@ -0,0 +1,31 @@
'use strict';
/**
* 文档内容页(doc_articles)
*
* - `content`:Markdown 原文(保存后由 `service/docSite` 渲染成静态 HTML)
* - `slug`:URL 片段(`/doc/<categoryCode>/<slug>.html`),创建后不能改
* - `status`:1 发布 0 草稿(草稿不生成页面,也不进 sitemap)
* - `categoryId` 冗余一份:列表 / 生成文档站时不用每次都 join 栏目
*/
module.exports = (app) => {
const { BIGINT, STRING, TINYINT, INTEGER, TEXT } = app.Sequelize;
const DocArticle = app.model.define('doc_article', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
categoryId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属分类 doc_categories.id' },
sectionId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属栏目 doc_sections.id' },
title: { type: STRING(128), allowNull: false, comment: '标题' },
slug: { type: STRING(64), allowNull: false, comment: 'URL 片段(/doc/<分类>/<slug>.html)' },
summary: { type: STRING(255), allowNull: true, comment: '摘要(列表 / meta description)' },
content: { type: TEXT('medium'), allowNull: true, comment: '正文(Markdown)' },
sort: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '栏目内排序(小的在前)' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1 发布 0 草稿' },
}, {
tableName: 'doc_articles',
paranoid: true,
comment: '文档内容页表',
});
return DocArticle;
};

View File

@ -0,0 +1,28 @@
'use strict';
/**
* 文档分类(doc_categories)
*
* 一行 = 文档站顶部的一个 tab(「快速开始」「设备接入」「常见问题」…)。
* - `code`:URL 片段(`/doc/<code>/`),**创建后不能改**(改了旧链接就失效)
* - `status`:1 展示 0 隐藏(隐藏后不生成页面,也不再进 sitemap)
* - `sort`:tab 顺序(小的在前)
*/
module.exports = (app) => {
const { BIGINT, STRING, TINYINT, INTEGER } = app.Sequelize;
const DocCategory = app.model.define('doc_category', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
code: { type: STRING(32), allowNull: false, unique: true, comment: 'URL 片段(/doc/<code>/)' },
name: { type: STRING(64), allowNull: false, comment: '分类名称(tab 文案)' },
description: { type: STRING(255), allowNull: true, comment: '分类说明(可选)' },
sort: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '排序(小的在前)' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1 展示 0 隐藏' },
}, {
tableName: 'doc_categories',
paranoid: true,
comment: '文档分类表',
});
return DocCategory;
};

View File

@ -0,0 +1,25 @@
'use strict';
/**
* 文档栏目(doc_sections)
*
* 分类底下的**一级**列表(「安装部署」「扫码上报」…),栏目下面才是内容页。
* 层级只有两级:分类 → 栏目 → 内容页,够用且不会把侧边栏撑爆。
*/
module.exports = (app) => {
const { BIGINT, STRING, TINYINT, INTEGER } = app.Sequelize;
const DocSection = app.model.define('doc_section', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
categoryId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属分类 doc_categories.id' },
name: { type: STRING(64), allowNull: false, comment: '栏目名称(侧边栏分组标题)' },
sort: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '排序(小的在前)' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1 展示 0 隐藏' },
}, {
tableName: 'doc_sections',
paranoid: true,
comment: '文档栏目表',
});
return DocSection;
};

View File

@ -38,6 +38,12 @@ module.exports = (app) => {
// ---------- 协议(公开读取;同意记录在登录时落库) ----------
router.get('/api/agreements/current', controller.agreement.current);
// ---------- 文档站(公开):`service/docSite` 把内容生成成静态 HTML,这里只回文件 ----------
// `/doc/...` 与 `/sitemap.txt` 不是 SPA 页面,middleware/frontend.js 已把它们排除掉。
router.get('/doc', controller.web.doc.redirect);
router.get('/doc/*', controller.web.doc.page);
router.get('/sitemap.txt', controller.web.doc.sitemap);
// ---------- web 用户端(前端 SPA 调;登录/注册等公开,其余要令牌) ----------
router.post('/api/web/auth/login', controller.web.auth.login);
router.post('/api/web/auth/register/code', controller.web.auth.sendRegisterCode);
@ -86,6 +92,20 @@ module.exports = (app) => {
router.get('/api/web/admin/extension', apiAuth, platformAdmin, controller.web.adminExtension.show);
router.put('/api/web/admin/extension', apiAuth, platformAdmin, controller.web.adminExtension.update);
// 文档站(简易 CMS):分类 → 栏目 → 内容页;保存后自动重生成 /doc/** 与 /sitemap.txt
router.get('/api/web/admin/doc/tree', apiAuth, platformAdmin, controller.web.adminDoc.tree);
router.post('/api/web/admin/doc/categories', apiAuth, platformAdmin, controller.web.adminDoc.createCategory);
router.put('/api/web/admin/doc/categories/:id', apiAuth, platformAdmin, controller.web.adminDoc.updateCategory);
router.delete('/api/web/admin/doc/categories/:id', apiAuth, platformAdmin, controller.web.adminDoc.destroyCategory);
router.post('/api/web/admin/doc/sections', apiAuth, platformAdmin, controller.web.adminDoc.createSection);
router.put('/api/web/admin/doc/sections/:id', apiAuth, platformAdmin, controller.web.adminDoc.updateSection);
router.delete('/api/web/admin/doc/sections/:id', apiAuth, platformAdmin, controller.web.adminDoc.destroySection);
router.get('/api/web/admin/doc/articles/:id', apiAuth, platformAdmin, controller.web.adminDoc.showArticle);
router.post('/api/web/admin/doc/articles', apiAuth, platformAdmin, controller.web.adminDoc.createArticle);
router.put('/api/web/admin/doc/articles/:id', apiAuth, platformAdmin, controller.web.adminDoc.updateArticle);
router.delete('/api/web/admin/doc/articles/:id', apiAuth, platformAdmin, controller.web.adminDoc.destroyArticle);
router.post('/api/web/admin/doc/rebuild', apiAuth, platformAdmin, controller.web.adminDoc.rebuild);
// ---------- Chrome 插件读取(公开只读,无令牌) ----------
// 只下发:前缀 + 生成好的正则 + 生效站点 + 跳转模板 + 安装包地址;不含任何账号/业务数据。
// 生产若配了 CORS_ORIGINS,记得把 `chrome-extension://<扩展ID>` 加进去(默认 `*` 不用管)。

454
backend/app/service/doc.js Normal file
View File

@ -0,0 +1,454 @@
'use strict';
const { Service } = require('egg');
/** 分类 code:URL 片段,只用安全字符 */
const CATEGORY_CODE = /^[a-z0-9][a-z0-9-]{0,31}$/;
/** 文章 slug:URL 文件名 */
const ARTICLE_SLUG = /^[a-z0-9][a-z0-9_-]{0,63}$/;
const MAX_CONTENT = 200000;
function toId(value) {
const id = Number(value);
return Number.isInteger(id) && id > 0 ? id : 0;
}
/**
* 文档站(简易 CMS)的增删改查
*
* 层级固定两级:分类(顶部 tab)→ 栏目(侧边栏分组)→ 内容页(Markdown)。
* **每次写操作后都会整站重生成**(`service/docSite`),保证页面 / 目录 / sitemap 与库一致。
*/
class DocService extends Service {
get Category() {
return this.app.model.DocCategory;
}
get Section() {
return this.app.model.DocSection;
}
get Article() {
return this.app.model.DocArticle;
}
/** CMS 树:分类 → 栏目 → 文章(文章不带正文,点开再取) */
async tree() {
const order = [ [ 'sort', 'ASC' ], [ 'id', 'ASC' ] ];
const [ categories, sections, articles ] = await Promise.all([
this.Category.findAll({ order }),
this.Section.findAll({ order }),
this.Article.findAll({ order }),
]);
const articlesBySection = new Map();
for (const article of articles) {
const key = String(article.sectionId);
if (!articlesBySection.has(key)) articlesBySection.set(key, []);
articlesBySection.get(key).push(article);
}
const sectionsByCategory = new Map();
for (const section of sections) {
const key = String(section.categoryId);
if (!sectionsByCategory.has(key)) sectionsByCategory.set(key, []);
sectionsByCategory.get(key).push(section);
}
const list = categories.map(category => {
const code = category.code;
const ownSections = sectionsByCategory.get(String(category.id)) || [];
const groups = ownSections.map(section => ({
id: Number(section.id),
categoryId: Number(section.categoryId),
name: section.name,
sort: Number(section.sort),
status: Number(section.status),
statusText: Number(section.status) === 1 ? '展示' : '隐藏',
deleted: Boolean(section.deletedAt),
articles: (articlesBySection.get(String(section.id)) || []).map(article => this.presentArticle(article, code)),
}));
return {
id: Number(category.id),
code,
name: category.name,
description: category.description || '',
sort: Number(category.sort),
status: Number(category.status),
statusText: Number(category.status) === 1 ? '展示' : '隐藏',
deleted: Boolean(category.deletedAt),
sections: groups,
articleCount: groups.reduce((total, group) => total + group.articles.length, 0),
};
});
return { list, total: list.length };
}
/** 单篇文章(含正文),给编辑表单用 */
async findArticle(id) {
const articleId = toId(id);
if (!articleId) this.ctx.throw(400, 'id 必须是正整数');
const row = await this.Article.findByPk(articleId, { paranoid: false });
if (!row || row.deletedAt) this.ctx.throw(404, '内容页不存在');
const category = await this.Category.findByPk(row.categoryId, { paranoid: false });
return {
...this.presentArticle(row, category ? category.code : ''),
content: row.content || '',
categoryId: Number(row.categoryId),
sectionId: Number(row.sectionId),
};
}
// ---------------- 分类 ----------------
async createCategory(body = {}) {
const payload = await this.normalizeCategory(body, null);
if (!payload.code) payload.code = await this.uniqueCategoryCode();
const row = await this.Category.create(payload);
this.app.logger.info('[doc] 新增分类:id=%s code=%s', row.id, row.code);
await this.regenerate();
return this.presentCategory(row);
}
async updateCategory(id, body = {}) {
const row = await this.findCategory(id);
const payload = await this.normalizeCategory(body, row);
await row.update(payload);
this.app.logger.info('[doc] 修改分类:id=%s %s', row.id, JSON.stringify(payload));
await this.regenerate();
return this.presentCategory(row);
}
/** 删除分类:连同栏目 / 内容页一起软删(页面与 sitemap 一并清掉) */
async removeCategory(id) {
const row = await this.findCategory(id);
const sections = await this.Section.findAll({ where: { categoryId: row.id } });
const sectionIds = sections.map(section => section.id);
if (sectionIds.length) {
await this.Article.destroy({ where: { sectionId: sectionIds } });
await this.Section.destroy({ where: { id: sectionIds } });
}
await row.destroy();
this.app.logger.info('[doc] 删除分类:id=%s code=%s', row.id, row.code);
await this.regenerate();
return { id: Number(row.id) };
}
async findCategory(id) {
const categoryId = toId(id);
if (!categoryId) this.ctx.throw(400, 'id 必须是正整数');
const row = await this.Category.findByPk(categoryId);
if (!row) this.ctx.throw(404, '分类不存在');
return row;
}
// ---------------- 栏目 ----------------
async createSection(body = {}) {
const payload = this.normalizeSection(body, null);
payload.categoryId = await this.assertCategory(body.categoryId);
const row = await this.Section.create(payload);
this.app.logger.info('[doc] 新增栏目:id=%s category=%s', row.id, payload.categoryId);
await this.regenerate();
return this.presentSection(row);
}
async updateSection(id, body = {}) {
const row = await this.findSection(id);
const payload = this.normalizeSection(body, row);
if (body.categoryId !== undefined && Number(body.categoryId) !== Number(row.categoryId)) {
payload.categoryId = await this.assertCategory(body.categoryId);
// 栏目换分类时,底下的内容页跟着走(categoryId 冗余在文章上)
await this.Article.update({ categoryId: payload.categoryId }, { where: { sectionId: row.id } });
}
await row.update(payload);
this.app.logger.info('[doc] 修改栏目:id=%s %s', row.id, JSON.stringify(payload));
await this.regenerate();
return this.presentSection(row);
}
/** 删除栏目:底下的内容页一起软删 */
async removeSection(id) {
const row = await this.findSection(id);
await this.Article.destroy({ where: { sectionId: row.id } });
await row.destroy();
this.app.logger.info('[doc] 删除栏目:id=%s', row.id);
await this.regenerate();
return { id: Number(row.id) };
}
async findSection(id) {
const sectionId = toId(id);
if (!sectionId) this.ctx.throw(400, 'id 必须是正整数');
const row = await this.Section.findByPk(sectionId);
if (!row) this.ctx.throw(404, '栏目不存在');
return row;
}
// ---------------- 内容页 ----------------
async createArticle(body = {}) {
const payload = this.normalizeArticle(body, null);
const section = await this.findSection(body.sectionId);
payload.sectionId = Number(section.id);
payload.categoryId = Number(section.categoryId);
const customSlug = payload.slug;
if (customSlug) {
await this.assertSlugFree(payload.categoryId, customSlug, null);
} else {
// slug 是非空列:先插一个临时值,拿到 id 后再改成稳定的 `a12`
payload.slug = `tmp${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
}
const row = await this.Article.create(payload);
if (!customSlug) {
await row.update({ slug: `a${row.id}` });
}
this.app.logger.info('[doc] 新增内容页:id=%s %s/%s', row.id, payload.categoryId, row.slug);
await this.regenerate();
return this.findArticle(row.id);
}
async updateArticle(id, body = {}) {
const row = await this.Article.findByPk(toId(id));
if (!row) this.ctx.throw(404, '内容页不存在');
const payload = this.normalizeArticle(body, row);
if (body.sectionId !== undefined && Number(body.sectionId) !== Number(row.sectionId)) {
const section = await this.findSection(body.sectionId);
payload.sectionId = Number(section.id);
payload.categoryId = Number(section.categoryId);
}
if (payload.slug && payload.slug !== row.slug) {
// slug 改了旧链接就失效,所以创建后不允许改
this.ctx.throw(409, '内容页地址(slug)创建后不能修改');
}
if (payload.categoryId && Number(payload.categoryId) !== Number(row.categoryId)) {
// 换分类:目标分类下不能已有同名地址
await this.assertSlugFree(Number(payload.categoryId), row.slug, null);
}
await row.update(payload);
this.app.logger.info('[doc] 修改内容页:id=%s', row.id);
await this.regenerate();
return this.findArticle(row.id);
}
async removeArticle(id) {
const row = await this.Article.findByPk(toId(id));
if (!row) this.ctx.throw(404, '内容页不存在');
await row.destroy();
this.app.logger.info('[doc] 删除内容页:id=%s', row.id);
await this.regenerate();
return { id: Number(row.id) };
}
// ---------------- 校验 ----------------
async normalizeCategory(body = {}, base = null) {
const has = key => Object.prototype.hasOwnProperty.call(body, key);
const data = {};
if (!base) {
if (body.status === undefined || body.status === null) body.status = 1;
if (body.sort === undefined || body.sort === null) body.sort = 0;
if (body.description === undefined) body.description = null;
}
if (!base || has('code')) {
const code = body.code === undefined || body.code === null ? '' : String(body.code).trim().toLowerCase();
if (base) {
if (code && code !== String(base.code)) this.ctx.throw(409, '分类编码创建后不能修改');
} else if (code) {
if (!CATEGORY_CODE.test(code)) this.ctx.throw(422, '分类编码只能用小写字母 / 数字 / 短横线(1~32 位)');
const existing = await this.Category.findOne({ where: { code }, paranoid: false });
if (existing) this.ctx.throw(409, `分类编码「${code}」已存在`);
data.code = code;
}
}
if (!base || has('name')) {
const name = String(body.name === undefined || body.name === null ? '' : body.name).trim();
if (!name) this.ctx.throw(422, '请填写分类名称');
if (name.length > 64) this.ctx.throw(422, '分类名称不能超过 64 个字符');
data.name = name;
}
if (!base || has('description')) {
const description = String(body.description === undefined || body.description === null ? '' : body.description).trim();
if (description.length > 255) this.ctx.throw(422, '分类说明不能超过 255 个字符');
data.description = description || null;
}
if (!base || has('sort')) data.sort = this.normalizeSort(body.sort);
if (!base || has('status')) data.status = this.normalizeStatus(body.status);
return data;
}
normalizeSection(body = {}, base = null) {
const has = key => Object.prototype.hasOwnProperty.call(body, key);
const data = {};
if (!base) {
if (body.status === undefined || body.status === null) body.status = 1;
if (body.sort === undefined || body.sort === null) body.sort = 0;
}
if (!base || has('name')) {
const name = String(body.name === undefined || body.name === null ? '' : body.name).trim();
if (!name) this.ctx.throw(422, '请填写栏目名称');
if (name.length > 64) this.ctx.throw(422, '栏目名称不能超过 64 个字符');
data.name = name;
}
if (!base || has('sort')) data.sort = this.normalizeSort(body.sort);
if (!base || has('status')) data.status = this.normalizeStatus(body.status);
return data;
}
normalizeArticle(body = {}, base = null) {
const has = key => Object.prototype.hasOwnProperty.call(body, key);
const data = {};
if (!base) {
if (body.status === undefined || body.status === null) body.status = 1;
if (body.sort === undefined || body.sort === null) body.sort = 0;
if (body.summary === undefined) body.summary = null;
if (body.content === undefined) body.content = '';
if (body.slug === undefined) body.slug = '';
}
if (!base || has('title')) {
const title = String(body.title === undefined || body.title === null ? '' : body.title).trim();
if (!title) this.ctx.throw(422, '请填写标题');
if (title.length > 128) this.ctx.throw(422, '标题不能超过 128 个字符');
data.title = title;
}
if (!base || has('slug')) {
const slug = String(body.slug === undefined || body.slug === null ? '' : body.slug).trim().toLowerCase();
if (slug) {
if (!ARTICLE_SLUG.test(slug)) this.ctx.throw(422, '地址只能用小写字母 / 数字 / 下划线 / 短横线(1~64 位)');
data.slug = slug;
}
}
if (!base || has('summary')) {
const summary = String(body.summary === undefined || body.summary === null ? '' : body.summary).trim();
if (summary.length > 255) this.ctx.throw(422, '摘要不能超过 255 个字符');
data.summary = summary || null;
}
if (!base || has('content')) {
const content = String(body.content === undefined || body.content === null ? '' : body.content);
if (content.length > MAX_CONTENT) this.ctx.throw(422, `正文不能超过 ${MAX_CONTENT} 个字符`);
data.content = content;
}
if (!base || has('sort')) data.sort = this.normalizeSort(body.sort);
if (!base || has('status')) data.status = this.normalizeStatus(body.status);
return data;
}
normalizeSort(value) {
const sort = Number(value);
if (!Number.isInteger(sort) || sort < 0) this.ctx.throw(422, '排序必须是非负整数');
if (sort > 9999) this.ctx.throw(422, '排序不能超过 9999');
return sort;
}
normalizeStatus(value) {
const status = Number(value);
if (status !== 0 && status !== 1) this.ctx.throw(422, '状态只能是 1(展示)或 0(隐藏)');
return status;
}
async assertCategory(id) {
const row = await this.findCategory(id);
return Number(row.id);
}
/** 同一分类下 slug 不能重复(含已删除的行:唯一索引还在) */
async assertSlugFree(categoryId, slug, id) {
const existing = await this.Article.findOne({
where: { categoryId, slug },
paranoid: false,
});
if (existing && Number(existing.id) !== Number(id)) this.ctx.throw(409, `该分类下已有地址「${slug}」`);
}
/** 没填 code 时生成 `cat1`、`cat2`…(和已有 code 不冲突) */
async uniqueCategoryCode() {
for (let i = 1; i <= 999; i++) {
const code = `cat${i}`;
const existing = await this.Category.findOne({ where: { code }, paranoid: false });
if (!existing) return code;
}
this.ctx.throw(409, '分类过多,请手动填写分类编码');
}
// ---------------- 展示 ----------------
presentCategory(row) {
return {
id: Number(row.id),
code: row.code,
name: row.name,
description: row.description || '',
sort: Number(row.sort),
status: Number(row.status),
statusText: Number(row.status) === 1 ? '展示' : '隐藏',
createdAt: row.createdAt || null,
updatedAt: row.updatedAt || null,
};
}
presentSection(row) {
return {
id: Number(row.id),
categoryId: Number(row.categoryId),
name: row.name,
sort: Number(row.sort),
status: Number(row.status),
statusText: Number(row.status) === 1 ? '展示' : '隐藏',
};
}
presentArticle(row, categoryCode) {
return {
id: Number(row.id),
categoryId: Number(row.categoryId),
sectionId: Number(row.sectionId),
categoryCode: categoryCode || '',
title: row.title,
slug: row.slug,
summary: row.summary || '',
sort: Number(row.sort),
status: Number(row.status),
statusText: Number(row.status) === 1 ? '已发布' : '草稿',
deleted: Boolean(row.deletedAt),
url: categoryCode && row.slug ? `/doc/${categoryCode}/${row.slug}.html` : '',
updatedAt: row.updatedAt || null,
};
}
/** 内容变更后整站重生成(静态 HTML + sitemap) */
async regenerate() {
try {
await this.ctx.service.docSite.generate(this.ctx);
} catch (err) {
// 生成失败不该把保存操作回滚,但必须留下日志(下次访问会再试一次)
this.app.logger.error('[doc] 生成文档站失败:%s', err && err.message);
}
}
}
module.exports = DocService;

View File

@ -0,0 +1,523 @@
'use strict';
const fs = require('fs');
const path = require('path');
const { Service } = require('egg');
const markdown = require('../lib/markdown');
const SITE_NAME = '云仓视频溯源';
/** 目录 / 文件名只允许安全的 ASCII:分类 code、文章 slug 都按这个校验 */
const SAFE_SEGMENT = /^[a-z0-9][a-z0-9_-]{0,63}$/;
function ensureDir(dir) {
fs.mkdirSync(dir, { recursive: true });
}
function writeFile(file, content) {
ensureDir(path.dirname(file));
fs.writeFileSync(file, content, 'utf8');
}
function escape(value) {
return markdown.escapeHtml(value);
}
/** 日期只留 YYYY-MM-DD */
function dateOnly(value) {
if (!value) return '';
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.getTime())) return '';
return date.toISOString().slice(0, 10);
}
/**
* 文档站生成器(`/doc/**` 的静态 HTML + `/sitemap.txt`)
*
* 设计取舍:
* - **静态优先**:每次内容变更(增删改分类 / 栏目 / 文章)整站重写一遍,文章量级小(几十篇)足够快;
* - 首次访问 / 部署后文件不存在时 **按需生成**(`ensureSite`),不依赖启动钩子;
* - 生成目录放在 `run/doc-site`(不进仓库),由 `controller/web/doc.js` 直接读文件返回。
*/
class DocSiteService extends Service {
get siteDir() {
return this.app.config.docSite.dir;
}
get indexPath() {
return path.join(this.siteDir, 'index.html');
}
get sitemapPath() {
return path.join(this.siteDir, 'sitemap.txt');
}
/** 站点根地址(sitemap 用绝对地址):优先配置,其次当前请求的 origin */
baseUrl(ctx) {
const configured = (this.app.config.docSite && this.app.config.docSite.baseUrl) || '';
if (configured) return String(configured).replace(/\/+$/, '');
const origin = ctx && ctx.origin ? String(ctx.origin) : '';
return origin.replace(/\/+$/, '');
}
/** 已发布的分类 → 栏目 → 文章(仅 status=1,按 sort 排序) */
async loadModel() {
const { DocCategory, DocSection, DocArticle } = this.app.model;
const order = [ [ 'sort', 'ASC' ], [ 'id', 'ASC' ] ];
const [ categories, sections, articles ] = await Promise.all([
DocCategory.findAll({ where: { status: 1 }, order }),
DocSection.findAll({ where: { status: 1 }, order }),
DocArticle.findAll({ where: { status: 1 }, order }),
]);
const articlesBySection = new Map();
for (const article of articles) {
const key = String(article.sectionId);
if (!articlesBySection.has(key)) articlesBySection.set(key, []);
articlesBySection.get(key).push(article);
}
const sectionsByCategory = new Map();
for (const section of sections) {
const key = String(section.categoryId);
if (!sectionsByCategory.has(key)) sectionsByCategory.set(key, []);
sectionsByCategory.get(key).push(section);
}
return categories.map(category => {
const ownSections = sectionsByCategory.get(String(category.id)) || [];
const groups = ownSections.map(section => ({
id: Number(section.id),
name: section.name,
articles: articlesBySection.get(String(section.id)) || [],
})).filter(group => group.articles.length > 0);
return {
id: Number(category.id),
code: category.code,
name: category.name,
description: category.description || '',
groups,
articles: groups.reduce((all, group) => all.concat(group.articles), []),
};
}).filter(category => SAFE_SEGMENT.test(category.code));
}
/** 生成整站(页面 + sitemap),返回生成的文件相对路径列表 */
async generate(ctx) {
const model = await this.loadModel();
const base = this.baseUrl(ctx);
ensureDir(this.siteDir);
const written = [];
const firstCategory = model[0] || null;
// `/doc/`:默认展示第一个分类(没有分类就展示空态)
writeFile(this.indexPath, this.renderPage({ model, base, active: firstCategory, article: null }));
written.push('index.html');
for (const category of model) {
writeFile(
path.join(this.siteDir, category.code, 'index.html'),
this.renderPage({ model, base, active: category, article: null }),
);
written.push(`${category.code}/index.html`);
for (const article of category.articles) {
writeFile(
path.join(this.siteDir, category.code, `${article.slug}.html`),
this.renderPage({ model, base, active: category, article }),
);
written.push(`${category.code}/${article.slug}.html`);
}
}
this.prune(model);
this.writeSitemap(this.buildSitemapUrls(model, base));
return written;
}
/** 文件不存在就生成(部署后第一次访问 / 清缓存后) */
async ensureSite(ctx) {
if (fs.existsSync(this.indexPath)) return;
await this.generate(ctx);
}
/** 删掉已经不该存在的目录 / 页面(分类改名、文章下架后不留旧链接) */
prune(model) {
const codes = new Set(model.map(category => category.code));
const slugsByCode = new Map(model.map(category => [ category.code, new Set(category.articles.map(article => `${article.slug}.html`)) ]));
for (const entry of fs.readdirSync(this.siteDir, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
if (!codes.has(entry.name)) {
fs.rmSync(path.join(this.siteDir, entry.name), { recursive: true, force: true });
continue;
}
const allow = slugsByCode.get(entry.name) || new Set();
for (const file of fs.readdirSync(path.join(this.siteDir, entry.name))) {
if (file === 'index.html') continue;
if (!allow.has(file)) fs.rmSync(path.join(this.siteDir, entry.name, file), { force: true });
}
}
}
/** 全站 URL:站点首页 + 文档站各级页面(顺序稳定,新增的排在最后) */
buildSitemapUrls(model, base) {
const urls = [ `${base}/`, `${base}/doc/` ];
for (const category of model) {
urls.push(`${base}/doc/${category.code}/`);
for (const article of category.articles) {
urls.push(`${base}/doc/${category.code}/${article.slug}.html`);
}
}
return urls;
}
/**
* 写 sitemap.txt:**已有顺序保持不变,新链接追加到末尾**(文章新增即"在尾部加入")。
* 已经不存在的 URL 会被清掉(下架 / 删除的文章不给搜索引擎留着)。
*/
writeSitemap(urls) {
const wanted = new Set(urls);
let existing = [];
try {
existing = fs.readFileSync(this.sitemapPath, 'utf8')
.split(/\r?\n/)
.map(line => line.trim())
.filter(Boolean);
} catch {
existing = [];
}
const kept = [];
const keptSet = new Set();
for (const url of existing) {
if (!wanted.has(url) || keptSet.has(url)) continue;
kept.push(url);
keptSet.add(url);
}
const appended = urls.filter(url => !keptSet.has(url));
writeFile(this.sitemapPath, `${kept.concat(appended).join('\n')}\n`);
}
/** 单个文件在磁盘上的位置(拒绝 `..` 越界) */
resolveFile(relative) {
const clean = String(relative || '').replace(/^\/+/, '').replace(/\\/g, '/');
const target = path.resolve(this.siteDir, clean);
const root = path.resolve(this.siteDir);
if (target !== root && !target.startsWith(`${root}${path.sep}`)) return null;
return target;
}
// ---------------- 渲染 ----------------
/** 顶部 tab(分类全量展示,全局可切换) */
renderTabs(model, active) {
return model.map(category => {
const isActive = active && category.code === active.code;
return `<a class="tab${isActive ? ' is-active' : ''}" href="/doc/${escape(category.code)}/">${escape(category.name)}</a>`;
}).join('');
}
/** 侧边栏:当前分类下的「栏目 → 内容页」 */
renderSidebar(active, article) {
if (!active) return '<p class="side-empty">还没有文档分类。</p>';
if (!active.groups.length) return '<p class="side-empty">这个分类下还没有内容。</p>';
return active.groups.map(group => `
<div class="side-group">
<div class="side-group__title">${escape(group.name)}</div>
<ul>
${group.articles.map(item => {
const href = `/doc/${escape(active.code)}/${escape(item.slug)}.html`;
const isActive = article && Number(article.id) === Number(item.id);
return `<li><a class="side-link${isActive ? ' is-active' : ''}" href="${href}">${escape(item.title)}</a></li>`;
}).join('')}
</ul>
</div>`).join('');
}
/** 正文第一行如果就是文章标题(`# 标题`),去掉它:标题已经在页头渲染过了 */
stripLeadingTitle(content, title) {
const source = String(content || '');
const lines = source.split('\n');
const first = (lines[0] || '').trim();
if (first === `# ${String(title || '').trim()}`) return lines.slice(1).join('\n');
return source;
}
/** 文章正文(分类首页展示该分类第一篇文章) */
renderBody(active, article) {
if (!active) {
return `<div class="empty">
<h1>${SITE_NAME} · 文档</h1>
<p>文档站还没有内容。平台管理员可以在「平台管理 → 文档管理」里新建分类与内容页。</p>
</div>`;
}
const current = article || active.articles[0] || null;
if (!current) {
return `<div class="empty">
<h1>${escape(active.name)}</h1>
<p>${escape(active.description || '这个分类下还没有已发布的内容。')}</p>
</div>`;
}
const rendered = markdown.render(this.stripLeadingTitle(current.content, current.title));
const toc = rendered.toc.filter(item => item.level >= 2 && item.level <= 4);
const updated = dateOnly(current.updatedAt || current.updated_at);
const summary = current.summary || markdown.plainText(current.content, 140);
return `<article class="doc">
<header class="doc-head">
<h1>${escape(current.title)}</h1>
${summary ? `<p class="doc-summary">${escape(summary)}</p>` : ''}
${updated ? `<p class="doc-meta">最近更新:${updated}</p>` : ''}
</header>
<div class="doc-body">
${rendered.html}
</div>
${toc.length ? `<nav class="doc-toc">
<div class="doc-toc__title">本页目录</div>
<ul>${toc.map(item => `<li class="lv-${item.level}"><a href="#${item.id}">${escape(item.text)}</a></li>`).join('')}</ul>
</nav>` : ''}
</article>`;
}
renderPage({ model, base, active, article }) {
const current = article || (active && active.articles[0]) || null;
const pagePath = current && active
? `/doc/${active.code}/${current.slug}.html`
: active ? `/doc/${active.code}/` : '/doc/';
const title = current ? `${current.title} · ${active.name}` : active ? active.name : '文档';
const description = (current && current.summary)
|| (active && active.description)
|| `${SITE_NAME} 使用文档`;
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escape(title)} · ${SITE_NAME}</title>
<meta name="description" content="${escape(description)}">
<link rel="canonical" href="${escape(base)}${escape(pagePath)}">
<style>
${this.styles()}
</style>
</head>
<body>
<header class="topbar">
<a class="brand" href="/doc/">
<span class="brand-dot" aria-hidden="true"></span>
${SITE_NAME} · 文档
</a>
<nav class="tabs" aria-label="文档分类">${this.renderTabs(model, active)}</nav>
<a class="back" href="/">返回控制台 →</a>
</header>
<div class="layout">
<aside class="sidebar">
${active ? `<div class="side-head">${escape(active.name)}</div>` : ''}
${this.renderSidebar(active, current)}
</aside>
<main class="content">
${this.renderBody(active, current)}
</main>
</div>
<footer class="footer">
<span>${SITE_NAME} · 文档由「平台管理 → 文档管理」维护</span>
</footer>
</body>
</html>
`;
}
styles() {
return `
:root {
--brand: #2563eb;
--brand-soft: rgba(37, 99, 235, 0.08);
--text: #1f2937;
--text-muted: #64748b;
--border: #e5e7eb;
--side-bg: #f8fafc;
--code-bg: #0f172a;
}
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
color: var(--text);
background: #fff;
line-height: 1.75;
font-size: 15px;
}
a { color: var(--brand); text-decoration: none; }
a:hover { text-decoration: underline; }
.topbar {
position: sticky;
top: 0;
z-index: 10;
display: flex;
align-items: center;
gap: 16px;
padding: 0 20px;
height: 56px;
background: rgba(255, 255, 255, 0.94);
backdrop-filter: blur(8px);
border-bottom: 1px solid var(--border);
}
.brand {
display: inline-flex;
align-items: center;
gap: 8px;
font-weight: 700;
color: var(--text);
white-space: nowrap;
}
.brand-dot {
width: 10px; height: 10px; border-radius: 50%;
background: linear-gradient(135deg, #24bbcd, #2563eb);
box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.12);
}
.tabs {
display: flex;
align-items: center;
gap: 4px;
flex: 1 1 auto;
min-width: 0;
overflow-x: auto;
scrollbar-width: none;
}
.tabs::-webkit-scrollbar { display: none; }
.tab {
padding: 6px 12px;
border-radius: 999px;
color: #475569;
font-size: 13px;
white-space: nowrap;
}
.tab:hover { background: var(--brand-soft); text-decoration: none; }
.tab.is-active { background: var(--brand); color: #fff; }
.tab.is-active:hover { background: var(--brand); }
.back { font-size: 13px; color: var(--text-muted); white-space: nowrap; }
.layout {
display: grid;
grid-template-columns: 248px minmax(0, 1fr);
max-width: 1440px;
margin: 0 auto;
min-height: calc(100vh - 56px - 60px);
}
.sidebar {
padding: 24px 16px 40px;
background: var(--side-bg);
border-right: 1px solid var(--border);
}
.side-head {
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--text-muted);
margin: 0 6px 14px;
}
.side-group { margin-bottom: 18px; }
.side-group__title {
font-size: 12px;
font-weight: 700;
color: #334155;
margin: 0 6px 6px;
}
.sidebar ul { list-style: none; margin: 0; padding: 0; }
.side-link {
display: block;
padding: 5px 10px;
border-radius: 8px;
font-size: 13.5px;
color: #334155;
line-height: 1.5;
}
.side-link:hover { background: rgba(37, 99, 235, 0.08); text-decoration: none; }
.side-link.is-active { background: var(--brand); color: #fff; }
.side-empty { color: var(--text-muted); font-size: 13px; padding: 0 6px; }
.content { padding: 32px 40px 64px; min-width: 0; }
.doc { max-width: 820px; }
.doc-head h1 { font-size: 30px; line-height: 1.35; margin: 0 0 8px; }
.doc-summary { margin: 0 0 6px; color: var(--text-muted); }
.doc-meta { margin: 0 0 24px; font-size: 12.5px; color: #94a3b8; }
.doc-body h2 { font-size: 22px; margin: 36px 0 12px; padding-bottom: 6px; border-bottom: 1px solid var(--border); }
.doc-body h3 { font-size: 18px; margin: 28px 0 10px; }
.doc-body h4 { font-size: 16px; margin: 24px 0 8px; }
.doc-body p { margin: 0 0 14px; }
.doc-body ul, .doc-body ol { margin: 0 0 16px; padding-left: 22px; }
.doc-body li { margin: 4px 0; }
.doc-body code {
font-family: ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", monospace;
font-size: 0.9em;
background: #f1f5f9;
border: 1px solid var(--border);
border-radius: 4px;
padding: 1px 5px;
}
.doc-body pre {
background: var(--code-bg);
color: #e2e8f0;
border-radius: 10px;
padding: 16px 18px;
overflow-x: auto;
margin: 0 0 18px;
}
.doc-body pre code { background: transparent; border: 0; padding: 0; color: inherit; }
.doc-body blockquote {
margin: 0 0 18px;
padding: 10px 16px;
border-left: 3px solid var(--brand);
background: var(--brand-soft);
border-radius: 0 8px 8px 0;
color: #334155;
}
.doc-body hr { border: 0; border-top: 1px solid var(--border); margin: 28px 0; }
.doc-body a { word-break: break-word; }
.doc-toc {
margin-top: 40px;
padding: 16px 18px;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--side-bg);
max-width: 820px;
}
.doc-toc__title { font-size: 12px; letter-spacing: 0.08em; color: var(--text-muted); margin-bottom: 8px; }
.doc-toc ul { list-style: none; margin: 0; padding: 0; }
.doc-toc li { margin: 3px 0; font-size: 13.5px; }
.doc-toc .lv-3 { padding-left: 14px; }
.doc-toc .lv-4 { padding-left: 28px; }
.empty { max-width: 720px; }
.empty h1 { font-size: 26px; }
.empty p { color: var(--text-muted); }
.footer {
border-top: 1px solid var(--border);
padding: 20px;
text-align: center;
font-size: 12.5px;
color: #94a3b8;
}
@media (max-width: 900px) {
.layout { grid-template-columns: 1fr; }
.sidebar { border-right: 0; border-bottom: 1px solid var(--border); }
.content { padding: 24px 20px 48px; }
.doc-head h1 { font-size: 24px; }
}
`;
}
}
module.exports = DocSiteService;

View File

@ -75,6 +75,17 @@ module.exports = (appInfo) => {
distDir: env.FRONTEND_DIST || path.join(appInfo.baseDir, '../frontend/dist'),
};
// ==================== 文档站(简易 CMS 生成的静态页面)====================
// 内容存在 doc_categories / doc_sections / doc_articles,保存时由 service/docSite 整站生成:
// /doc/index.html、/doc/<分类>/index.html、/doc/<分类>/<文章>.html、/sitemap.txt
// - dir:生成目录(run/ 已被 .gitignore 忽略,部署后首次访问会按需生成)
// - baseUrl:sitemap 里的站点根地址;不配则用触发生成的那次请求的 origin
// (生产建议配 SITE_BASE_URL=https://your.domain,避免 sitemap 里混进内网地址)
config.docSite = {
dir: env.DOC_SITE_DIR || path.join(appInfo.baseDir, 'run/doc-site'),
baseUrl: String(env.SITE_BASE_URL || '').replace(/\/+$/, ''),
};
// ==================== 运维/内部接口鉴权 ====================
// 对应 app/middleware/internal_auth.js:
// - token:给运维脚本 / 后台系统用(header `X-Internal-Token`);**不配则一律不认**

View File

@ -0,0 +1,127 @@
'use strict';
/**
* 文档站(简易 CMS):doc_categories / doc_sections / doc_articles
*
* 层级:分类(顶部 tab)→ 栏目(侧边栏分组)→ 内容页(Markdown)。
* 内容保存后由 `service/docSite` 渲染成 `/doc/**` 下的**静态 HTML**,并维护 `/sitemap.txt`。
*
* 迁移里先放一页「欢迎使用」,保证文档站一上线就有内容(也方便部署后自测)。
*/
module.exports = {
async up(queryInterface, Sequelize) {
const { BIGINT, STRING, TINYINT, INTEGER, TEXT, DATE } = Sequelize;
await queryInterface.createTable('doc_categories', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
code: { type: STRING(32), allowNull: false, unique: true, comment: 'URL 片段(/doc/<code>/)' },
name: { type: STRING(64), allowNull: false, comment: '分类名称(tab 文案)' },
description: { type: STRING(255), allowNull: true, comment: '分类说明(可选)' },
sort: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '排序(小的在前)' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1 展示 0 隐藏' },
created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
updated_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
deleted_at: { type: DATE, allowNull: true },
}, { comment: '文档分类表' });
await queryInterface.addIndex('doc_categories', [ 'status', 'sort' ], { name: 'idx_doc_categories_status_sort' });
await queryInterface.createTable('doc_sections', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
category_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属分类 doc_categories.id' },
name: { type: STRING(64), allowNull: false, comment: '栏目名称(侧边栏分组标题)' },
sort: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '排序(小的在前)' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1 展示 0 隐藏' },
created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
updated_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
deleted_at: { type: DATE, allowNull: true },
}, { comment: '文档栏目表' });
await queryInterface.addIndex('doc_sections', [ 'category_id', 'sort' ], { name: 'idx_doc_sections_category_sort' });
await queryInterface.createTable('doc_articles', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
category_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属分类(冗余,列表用)' },
section_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属栏目 doc_sections.id' },
title: { type: STRING(128), allowNull: false, comment: '标题' },
slug: { type: STRING(64), allowNull: false, comment: 'URL 片段' },
summary: { type: STRING(255), allowNull: true, comment: '摘要' },
content: { type: TEXT('medium'), allowNull: true, comment: '正文(Markdown)' },
sort: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '栏目内排序(小的在前)' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1 发布 0 草稿' },
created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
updated_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
deleted_at: { type: DATE, allowNull: true },
}, { comment: '文档内容页表' });
await queryInterface.addIndex('doc_articles', [ 'category_id', 'section_id', 'sort' ], { name: 'idx_doc_articles_tree' });
await queryInterface.addIndex('doc_articles', [ 'category_id', 'slug' ], { name: 'idx_doc_articles_slug' });
const now = new Date();
await queryInterface.bulkInsert('doc_categories', [{
code: 'guide',
name: '使用指南',
description: '从创建主体到看板查看,一步步把系统跑起来',
sort: 10,
status: 1,
created_at: now,
updated_at: now,
}]);
const [ categories ] = await queryInterface.sequelize.query(
'SELECT id FROM doc_categories WHERE code = ? LIMIT 1',
{ replacements: [ 'guide' ] },
);
const categoryId = categories && categories[0] ? categories[0].id : null;
if (!categoryId) return;
await queryInterface.bulkInsert('doc_sections', [{
category_id: categoryId,
name: '快速开始',
sort: 10,
status: 1,
created_at: now,
updated_at: now,
}]);
const [ sections ] = await queryInterface.sequelize.query(
'SELECT id FROM doc_sections WHERE category_id = ? ORDER BY id ASC LIMIT 1',
{ replacements: [ categoryId ] },
);
const sectionId = sections && sections[0] ? sections[0].id : null;
if (!sectionId) return;
await queryInterface.bulkInsert('doc_articles', [{
category_id: categoryId,
section_id: sectionId,
title: '欢迎使用云仓视频溯源',
slug: 'welcome',
summary: '文档站已经跑起来了,这里的内容都能在「平台管理 → 文档管理」里维护。',
content: [
'# 欢迎使用云仓视频溯源',
'',
'这里是由**平台管理 → 文档管理**维护的静态文档站:',
'',
'- 顶部 tab 是「分类」,点一下就能切换;',
'- 左侧是分类下的「栏目 → 内容页」;',
'- 文章保存后会自动重新生成 HTML 与目录,并把新链接追加到 `/sitemap.txt`。',
'',
'## 下一步',
'',
'1. 在「文档管理」里新建分类 / 栏目 / 内容页;',
'2. 回到本站刷新,就能看到刚发布的内容;',
'3. 需要撤下某篇时,把状态改成「草稿」即可(页面和 sitemap 都会移除)。',
].join('\n'),
sort: 10,
status: 1,
created_at: now,
updated_at: now,
}]);
},
async down(queryInterface) {
await queryInterface.dropTable('doc_articles');
await queryInterface.dropTable('doc_sections');
await queryInterface.dropTable('doc_categories');
},
};

View File

@ -459,8 +459,16 @@ function buildFrontConf(config) {
proxyLocation('location ^~ /api/'),
'',
proxyLocation('location = /health'),
'',
'# 文档站:静态 HTML 由后端生成(run/doc-site),交给 Node 直接回文件;',
'# 不能落到下面的 location /(那是 SPA,找不到文件会回 index.html)',
proxyLocation('location = /doc'),
'',
proxyLocation('location ^~ /doc/'),
'',
proxyLocation('location = /sitemap.txt'),
]
: [ '# nginxUpstreamFile 未配置,跳过 /api、/health 反代' ]),
: [ '# nginxUpstreamFile 未配置,跳过 /api、/health、/doc、/sitemap.txt 反代' ]),
'',
'# 桌面端 / Android 安装包:由 nginx 直接托管 deployRoot/download',
'# download/desktop/*.exe、*.msi、download/android_client/*.apk 长缓存;',

View File

@ -0,0 +1,60 @@
'use strict';
const assert = require('assert');
const { render, plainText } = require('../../../app/lib/markdown');
describe('test/app/lib/markdown.test.js', () => {
it('标题 / 段落 / 行内样式 / 目录', () => {
const { html, toc } = render([
'# 一级标题',
'',
'这是 **粗体**、`代码` 和 [链接](https://example.com)。',
'',
'## 二级标题',
].join('\n'));
assert.ok(html.includes('<h1 id="sec-1">一级标题</h1>'));
assert.ok(html.includes('<strong>粗体</strong>'));
assert.ok(html.includes('<code>代码</code>'));
assert.ok(html.includes('target="_blank"'));
assert.ok(html.includes('<h2 id="sec-2">二级标题</h2>'));
assert.deepStrictEqual(toc.map(item => item.level), [ 1, 2 ]);
});
it('列表 / 引用 / 代码块', () => {
const { html } = render([
'- 一',
'- 二',
'',
'> 引用一行',
'',
'```js',
'console.log(1)',
'```',
].join('\n'));
assert.ok(html.includes('<ul><li>一</li><li>二</li></ul>'));
assert.ok(html.includes('<blockquote>'));
assert.ok(html.includes('class="language-js"'));
assert.ok(html.includes('console.log(1)'));
});
it('先转义再拼标签:脚本与 javascript: 链接不会漏出去', () => {
const html = render([
'<script>alert(1)</script>',
'',
'[点我](javascript:alert(1))',
'',
'![图](http://x.com/a.png)',
].join('\n')).html;
assert.ok(!html.includes('<script>'), 'HTML 必须被转义');
assert.ok(html.includes('&lt;script&gt;'));
assert.ok(!html.includes('javascript:'), 'javascript: 协议必须被拒绝');
});
it('plainText:去掉记号并截断', () => {
assert.strictEqual(plainText('# 标题\n\n正文 `code`'), '标题 正文 code');
assert.ok(plainText('a'.repeat(200), 10).endsWith('…'));
});
});

View File

@ -207,3 +207,133 @@ export function updateAdminPlan(id: number, body: AdminPlanInput): Promise<Admin
export function removeAdminPlan(id: number): Promise<{ id: number }> {
return api.del(`/api/web/admin/plans/${id}`);
}
// ==================== 文档站(简易 CMS)====================
// 层级:分类(顶部 tab)→ 栏目(侧边栏分组)→ 内容页(Markdown)。
// 每次保存都会让后端**整站重生成** `/doc/**` 的静态页面与 `/sitemap.txt`。
/** 内容页(列表里不带正文) */
export interface DocArticleNode {
id: number;
categoryId: number;
sectionId: number;
categoryCode: string;
title: string;
slug: string;
summary: string;
sort: number;
/** 1 已发布 0 草稿 */
status: number;
statusText: string;
/** 站点内地址(`/doc/<分类>/<文章>.html`) */
url: string;
updatedAt?: string | null;
}
/** 内容页(带正文,编辑表单用) */
export interface DocArticleDetail extends DocArticleNode {
content: string;
}
/** 栏目(分类下的一级列表) */
export interface DocSectionNode {
id: number;
categoryId: number;
name: string;
sort: number;
/** 1 展示 0 隐藏 */
status: number;
statusText: string;
articles: DocArticleNode[];
}
/** 分类(顶部 tab) */
export interface DocCategoryNode {
id: number;
code: string;
name: string;
description: string;
sort: number;
/** 1 展示 0 隐藏 */
status: number;
statusText: string;
articleCount: number;
sections: DocSectionNode[];
}
export interface DocCategoryInput {
code?: string;
name?: string;
description?: string | null;
sort?: number;
status?: number;
}
export interface DocSectionInput {
categoryId?: number;
name?: string;
sort?: number;
status?: number;
}
export interface DocArticleInput {
sectionId?: number;
title?: string;
slug?: string;
summary?: string | null;
content?: string;
sort?: number;
status?: number;
}
/** 整棵文档树(分类 → 栏目 → 内容页) */
export function fetchDocTree(): Promise<{ list: DocCategoryNode[]; total: number }> {
return api.get('/api/web/admin/doc/tree');
}
export function createDocCategory(body: DocCategoryInput): Promise<DocCategoryNode> {
return api.post('/api/web/admin/doc/categories', body);
}
export function updateDocCategory(id: number, body: DocCategoryInput): Promise<DocCategoryNode> {
return api.put(`/api/web/admin/doc/categories/${id}`, body);
}
/** 删除分类(栏目与内容页一起删) */
export function removeDocCategory(id: number): Promise<{ id: number }> {
return api.del(`/api/web/admin/doc/categories/${id}`);
}
export function createDocSection(body: DocSectionInput): Promise<DocSectionNode> {
return api.post('/api/web/admin/doc/sections', body);
}
export function updateDocSection(id: number, body: DocSectionInput): Promise<DocSectionNode> {
return api.put(`/api/web/admin/doc/sections/${id}`, body);
}
/** 删除栏目(内容页一起删) */
export function removeDocSection(id: number): Promise<{ id: number }> {
return api.del(`/api/web/admin/doc/sections/${id}`);
}
export function fetchDocArticle(id: number): Promise<DocArticleDetail> {
return api.get(`/api/web/admin/doc/articles/${id}`);
}
export function createDocArticle(body: DocArticleInput): Promise<DocArticleDetail> {
return api.post('/api/web/admin/doc/articles', body);
}
export function updateDocArticle(id: number, body: DocArticleInput): Promise<DocArticleDetail> {
return api.put(`/api/web/admin/doc/articles/${id}`, body);
}
export function removeDocArticle(id: number): Promise<{ id: number }> {
return api.del(`/api/web/admin/doc/articles/${id}`);
}
/** 手动整站重生成(排查用;正常保存后会自动生成) */
export function rebuildDocSite(): Promise<{ files: number; urls: number }> {
return api.post('/api/web/admin/doc/rebuild', {});
}

View File

@ -1,102 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 520" fill="none" role="img">
<defs>
<radialGradient id="floorGlow" cx="50%" cy="50%" r="50%">
<stop offset="0%" stop-color="#38bdf8" stop-opacity="0.30"/>
<stop offset="60%" stop-color="#2563eb" stop-opacity="0.10"/>
<stop offset="100%" stop-color="#0b1b3a" stop-opacity="0"/>
</radialGradient>
<linearGradient id="camBody" x1="0" y1="0" x2="0.3" y2="1">
<stop offset="0%" stop-color="#ffffff"/>
<stop offset="55%" stop-color="#eaf1ff"/>
<stop offset="100%" stop-color="#c7d8f6"/>
</linearGradient>
<linearGradient id="paper" x1="0" y1="0" x2="0.4" y2="1">
<stop offset="0%" stop-color="#ffffff"/>
<stop offset="100%" stop-color="#e3ecff"/>
</linearGradient>
<linearGradient id="gunBody" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#3b5480"/>
<stop offset="100%" stop-color="#16233c"/>
</linearGradient>
<linearGradient id="laser" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#5eead4" stop-opacity="0"/>
<stop offset="100%" stop-color="#34d399" stop-opacity="0.95"/>
</linearGradient>
<filter id="soft" x="-60%" y="-60%" width="220%" height="220%">
<feGaussianBlur stdDeviation="7"/>
</filter>
<filter id="dotGlow" x="-80%" y="-80%" width="260%" height="260%">
<feGaussianBlur stdDeviation="2.6" result="b"/>
<feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
</filter>
</defs>
<ellipse cx="336" cy="438" rx="215" ry="62" fill="url(#floorGlow)"/>
<ellipse cx="336" cy="452" rx="150" ry="30" fill="#1d4ed8" opacity="0.20" filter="url(#soft)"/>
<g stroke="#34d399" stroke-dasharray="5 7" stroke-linecap="round" fill="none">
<path d="M188 196 C 236 232, 254 268, 288 292" stroke-width="2" opacity="0.55"/>
<path d="M470 352 C 424 344, 396 322, 372 306" stroke-width="2" opacity="0.5"/>
<path d="M452 176 C 424 196, 406 214, 388 232" stroke-width="2" opacity="0.45"/>
</g>
<g fill="#34d399" filter="url(#dotGlow)">
<circle cx="188" cy="196" r="3.4"/><circle cx="372" cy="306" r="3.4"/><circle cx="452" cy="176" r="3.4"/>
<circle cx="262" cy="264" r="2.4" opacity="0.8"/><circle cx="404" cy="330" r="2.4" opacity="0.8"/>
</g>
<g>
<polygon points="336.00,264.00 341.33,267.08 336.00,270.16 330.67,267.08" fill="#6ea8ff"/><polygon points="341.33,267.08 336.00,270.16 336.00,438.16 341.33,435.08" fill="#3b78ec"/><polygon points="330.67,267.08 336.00,270.16 336.00,438.16 330.67,435.08" fill="#2a5cc9"/>
<polygon points="336.00,429.76 485.37,516.00 418.45,554.64 269.07,468.40" fill="#3f7cf6"/><polygon points="485.37,516.00 418.45,554.64 418.45,560.24 485.37,521.60" fill="#2b5dd6"/><polygon points="269.07,468.40 418.45,554.64 418.45,560.24 269.07,474.00" fill="#1f47ab"/><polygon points="336.97,391.12 399.05,426.96 348.61,456.08 286.53,420.24" fill="#f4c98f"/><polygon points="399.05,426.96 348.61,456.08 348.61,504.24 399.05,475.12" fill="#dda86a"/><polygon points="286.53,420.24 348.61,456.08 348.61,504.24 286.53,468.40" fill="#c88f4e"/><polygon points="363.64,406.52 372.37,411.56 321.94,440.68 313.21,435.64" fill="#fff4e2" opacity="0.85"/><polygon points="385.47,451.17 362.19,464.61 362.19,476.17 385.47,462.73" fill="#efdcbe"/>
<polygon points="336.00,373.76 485.37,460.00 418.45,498.64 269.07,412.40" fill="#3f7cf6"/><polygon points="485.37,460.00 418.45,498.64 418.45,504.24 485.37,465.60" fill="#2b5dd6"/><polygon points="269.07,412.40 418.45,498.64 418.45,504.24 269.07,418.00" fill="#1f47ab"/><polygon points="336.97,348.56 468.88,424.72 417.48,454.40 285.56,378.24" fill="#eec084"/><polygon points="468.88,424.72 417.48,454.40 417.48,489.12 468.88,459.44" fill="#d39c5c"/><polygon points="285.56,378.24 417.48,454.40 417.48,489.12 285.56,412.96" fill="#bb8043"/><polygon points="398.56,384.12 407.29,389.16 355.88,418.84 347.15,413.80" fill="#fff4e2" opacity="0.85"/><polygon points="455.30,444.36 431.05,458.36 431.05,466.70 455.30,452.70" fill="#efdcbe"/>
<polygon points="336.00,317.76 485.37,404.00 418.45,442.64 269.07,356.40" fill="#3f7cf6"/><polygon points="485.37,404.00 418.45,442.64 418.45,448.24 485.37,409.60" fill="#2b5dd6"/><polygon points="269.07,356.40 418.45,442.64 418.45,448.24 269.07,362.00" fill="#1f47ab"/><polygon points="336.97,282.48 393.23,314.96 341.82,344.64 285.56,312.16" fill="#f7d3a0"/><polygon points="393.23,314.96 341.82,344.64 341.82,389.44 393.23,359.76" fill="#e0af74"/><polygon points="285.56,312.16 341.82,344.64 341.82,389.44 285.56,356.96" fill="#c89355"/><polygon points="360.73,296.20 369.46,301.24 318.06,330.92 309.33,325.88" fill="#fff4e2" opacity="0.85"/><polygon points="379.65,338.03 355.40,352.03 355.40,362.78 379.65,348.78" fill="#efdcbe"/>
<polygon points="476.16,344.92 481.49,348.00 476.16,351.08 470.82,348.00" fill="#6ea8ff"/><polygon points="481.49,348.00 476.16,351.08 476.16,519.08 481.49,516.00" fill="#3b78ec"/><polygon points="470.82,348.00 476.16,351.08 476.16,519.08 470.82,516.00" fill="#2a5cc9"/>
<polygon points="278.29,297.32 283.62,300.40 278.29,303.48 272.95,300.40" fill="#6ea8ff"/><polygon points="283.62,300.40 278.29,303.48 278.29,471.48 283.62,468.40" fill="#3b78ec"/><polygon points="272.95,300.40 278.29,303.48 278.29,471.48 272.95,468.40" fill="#2a5cc9"/>
<polygon points="418.45,378.24 423.78,381.32 418.45,384.40 413.11,381.32" fill="#6ea8ff"/><polygon points="423.78,381.32 418.45,384.40 418.45,552.40 423.78,549.32" fill="#3b78ec"/><polygon points="413.11,381.32 418.45,384.40 418.45,552.40 413.11,549.32" fill="#2a5cc9"/>
<polygon points="336.00,261.76 485.37,348.00 418.45,386.64 269.07,300.40" fill="#3f7cf6"/><polygon points="485.37,348.00 418.45,386.64 418.45,392.24 485.37,353.60" fill="#2b5dd6"/><polygon points="269.07,300.40 418.45,386.64 418.45,392.24 269.07,306.00" fill="#1f47ab"/>
<polygon points="272.95,300.40 418.45,384.40 418.45,386.08 272.95,302.08" fill="#34d399" opacity="0.9"/>
<polygon points="418.45,384.40 481.49,348.00 481.49,349.68 418.45,386.08" fill="#34d399" opacity="0.55"/>
</g>
<g transform="translate(96 96)">
<ellipse cx="46" cy="42" rx="64" ry="58" fill="#1d4ed8" opacity="0.28" filter="url(#soft)"/>
<path d="M18 30 L58 12" stroke="#94b8f2" stroke-width="7" stroke-linecap="round"/>
<circle cx="18" cy="31" r="6" fill="#c7d8f6"/>
<g transform="rotate(-14 60 44)">
<rect x="26" y="24" width="76" height="42" rx="12" fill="url(#camBody)" stroke="#b9d0f4" stroke-width="1.2"/>
<circle cx="96" cy="45" r="17" fill="#22335a"/>
<circle cx="96" cy="45" r="12" fill="#0b1730"/>
<circle cx="96" cy="45" r="7" fill="#38bdf8" opacity="0.85"/>
<circle cx="91" cy="40" r="2.6" fill="#e0f2fe" opacity="0.9"/>
<circle cx="34" cy="45" r="3.2" fill="#34d399"/>
<rect x="38" y="34" width="16" height="3.4" rx="1.7" fill="#c2d4ef"/>
<rect x="38" y="42" width="10" height="3" rx="1.5" fill="#d7e3f7"/>
</g>
</g>
<g transform="translate(430 96) rotate(7)">
<rect x="4" y="10" width="112" height="132" rx="14" fill="#1d4ed8" opacity="0.22" filter="url(#soft)"/>
<rect x="0" y="0" width="112" height="132" rx="14" fill="url(#paper)" stroke="#cadbf7" stroke-width="1.2"/>
<rect x="16" y="18" width="34" height="6" rx="3" fill="#8fb0e8"/>
<rect x="16" y="34" width="80" height="5" rx="2.5" fill="#dbe6f8"/>
<rect x="16" y="46" width="62" height="5" rx="2.5" fill="#dbe6f8"/>
<rect x="16" y="64" width="80" height="34" rx="8" fill="#eef4ff"/>
<path d="M24 90 L38 74 L50 86 L66 66" stroke="#34d399" stroke-width="3.4" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
<rect x="16" y="108" width="48" height="5" rx="2.5" fill="#dbe6f8"/>
<circle cx="95" cy="112" r="11" fill="#34d399"/>
<path d="M89.5 112.5 L93.5 116.5 L101 108.5" stroke="#08381f" stroke-width="2.6" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
</g>
<g transform="translate(470 286) rotate(12)">
<ellipse cx="22" cy="52" rx="56" ry="44" fill="#0ea5e9" opacity="0.20" filter="url(#soft)"/>
<path d="M34 26 C 34 12, 46 4, 58 4 C 70 4, 82 12, 82 26 L 82 44 L 34 44 Z" fill="url(#gunBody)"/>
<rect x="34" y="40" width="52" height="16" rx="7" fill="#22314f"/>
<path d="M44 54 L 40 96 C 39 104, 45 108, 52 108 L 62 108 C 69 108, 74 103, 71 95 L 64 54 Z" fill="url(#gunBody)"/>
<rect x="48" y="62" width="12" height="22" rx="6" fill="#0f1b31"/>
<path d="M34 30 L 8 12" stroke="url(#laser)" stroke-width="3.6" stroke-linecap="round"/>
<circle cx="8" cy="12" r="4" fill="#5eead4" filter="url(#dotGlow)"/>
<rect x="78" y="16" width="10" height="4" rx="2" fill="#34d399"/>
<path d="M50 22 L 70 22" stroke="#8fa6cc" stroke-width="2.6" stroke-linecap="round" opacity="0.75"/>
</g>
<g fill="#7dd3fc" opacity="0.75">
<circle cx="232" cy="140" r="2.6"/>
<circle cx="300" cy="112" r="2.0"/>
<circle cx="556" cy="250" r="2.4"/>
<circle cx="100" cy="300" r="2.2"/>
<circle cx="588" cy="388" r="2.0"/>
<circle cx="206" cy="372" r="1.8"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 8.7 KiB

View File

@ -0,0 +1,279 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="128 66 848 540" width="848" height="540" fill="none" role="img" aria-label="打包工位示意图:物料架存纸箱、包裹封箱贴面单、工业相机拍摄面单、顶部球机监控">
<title>打包工位:封箱、贴面单、相机拍摄</title>
<desc>台面上物料架存放纸箱,包裹自动折盖封箱并贴上面单,工业相机拍摄面单,顶部球机监控整个工位。</desc>
<defs>
<linearGradient id="ps-lidTop" x1="0" y1="0" x2="0.55" y2="1">
<stop offset="0" stop-color="#fdeed8" />
<stop offset="1" stop-color="#eccb9e" />
</linearGradient>
<linearGradient id="ps-boxFront" x1="0" y1="0" x2="0.4" y2="1">
<stop offset="0" stop-color="#f0d3a6" />
<stop offset="1" stop-color="#d5a973" />
</linearGradient>
<linearGradient id="ps-boxSide" x1="0" y1="0" x2="0.6" y2="1">
<stop offset="0" stop-color="#dfb883" />
<stop offset="1" stop-color="#c4945c" />
</linearGradient>
<linearGradient id="ps-flapFill" x1="0" y1="0" x2="0.3" y2="1">
<stop offset="0" stop-color="#f8e2bd" />
<stop offset="1" stop-color="#e7c497" />
</linearGradient>
<linearGradient id="ps-metal" x1="0" y1="0" x2="0.35" y2="1">
<stop offset="0" stop-color="#eef5ff" />
<stop offset="1" stop-color="#b6cbe8" />
</linearGradient>
<radialGradient id="ps-groundGlow" cx="50%" cy="50%" r="50%">
<stop offset="0" stop-color="#38bdf8" stop-opacity="0.22" />
<stop offset="65%" stop-color="#2563eb" stop-opacity="0.08" />
<stop offset="100%" stop-color="#0b1b3a" stop-opacity="0" />
</radialGradient>
<linearGradient id="ps-coneGrad" x1="0" y1="0" x2="0.6" y2="1">
<stop offset="0" stop-color="#38bdf8" stop-opacity="0.22" />
<stop offset="1" stop-color="#38bdf8" stop-opacity="0" />
</linearGradient>
<linearGradient id="ps-scanGrad" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#5eead4" stop-opacity="0" />
<stop offset="45%" stop-color="#5eead4" stop-opacity="0.95" />
<stop offset="100%" stop-color="#38bdf8" stop-opacity="0" />
</linearGradient>
<filter id="ps-glow" x="-70%" y="-70%" width="240%" height="240%">
<feGaussianBlur stdDeviation="4" result="b" />
<feMerge>
<feMergeNode in="b" />
<feMergeNode in="SourceGraphic" />
</feMerge>
</filter>
<style>
.ps-ln { stroke: #a8c8f2; stroke-width: 2.8; stroke-linecap: round; stroke-linejoin: round; }
.ps-ln-soft { stroke: #7fa1cd; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.ps-surf { stroke: #a8c8f2; stroke-width: 2.8; stroke-linejoin: round; fill: #8fb8ee; fill-opacity: 0.12; }
.ps-surf--side { fill-opacity: 0.07; }
.ps-box-edge { stroke: #ffe0b0; stroke-width: 2.4; stroke-linejoin: round; }
.ps-tape { stroke: #38bdf8; stroke-width: 8; stroke-linecap: round; opacity: 0.85; }
.ps-paper { stroke: #cfe4ff; stroke-width: 1.6; }
.ps-ink-line { stroke: #7ea6d8; stroke-width: 1.4; stroke-linecap: round; }
.ps-fov { stroke: #38bdf8; stroke-width: 2; stroke-dasharray: 7 8; opacity: 0.75; }
.ps-anim { animation-duration: 7s; animation-timing-function: ease-in-out; animation-iteration-count: infinite; }
.ps-flap { transform-box: fill-box; transform-origin: 50% 100%; }
.ps-flap--back { animation-name: ps-foldBack; }
.ps-flap--front { animation-name: ps-foldFront; }
.ps-hole { animation-name: ps-holeFade; }
.ps-tape-run { animation-name: ps-tapeDraw; }
.ps-disp { animation-name: ps-dispRun; }
.ps-label { animation-name: ps-labelDrop; }
.ps-label-edge { animation-name: ps-labelFlash; }
.ps-scan { animation-name: ps-scanSweep; }
.ps-march { animation: ps-march 2.4s linear infinite; }
.ps-breathe { animation: ps-breathe 5.5s ease-in-out infinite; }
.ps-blink { animation: ps-blink 2.6s ease-in-out infinite; }
@keyframes ps-foldBack {
0%, 8% { transform: scaleY(1); }
23%, 92% { transform: scaleY(0.03); }
100% { transform: scaleY(1); }
}
@keyframes ps-foldFront {
0%, 8% { transform: scaleY(1); }
23%, 92% { transform: scaleY(0.03); }
100% { transform: scaleY(1); }
}
@keyframes ps-holeFade {
0%, 10% { opacity: 1; }
23%, 92% { opacity: 0; }
100% { opacity: 1; }
}
@keyframes ps-tapeDraw {
0%, 25% { stroke-dashoffset: 150; }
37%, 93% { stroke-dashoffset: 0; }
100% { stroke-dashoffset: 150; }
}
@keyframes ps-dispRun {
0%, 24% { transform: translateX(0); opacity: 0; }
26% { opacity: 1; }
36% { transform: translateX(158px); opacity: 1; }
42% { opacity: 0; }
100% { transform: translateX(158px); opacity: 0; }
}
@keyframes ps-labelDrop {
0%, 42% { transform: translate(46px, -34px); opacity: 0; }
50% { transform: translate(0, 3px); opacity: 1; }
54%, 94% { transform: translate(0, 0); opacity: 1; }
100% { transform: translate(46px, -34px); opacity: 0; }
}
@keyframes ps-labelFlash {
0%, 58% { stroke: #cfe4ff; }
66% { stroke: #34d399; }
84%, 100% { stroke: #cfe4ff; }
}
@keyframes ps-scanSweep {
0%, 55% { transform: translateX(-6px); opacity: 0; }
57% { opacity: 1; }
72% { transform: translateX(96px); opacity: 1; }
77%, 100% { transform: translateX(96px); opacity: 0; }
}
@keyframes ps-march {
to { stroke-dashoffset: -30; }
}
@keyframes ps-breathe {
0%, 100% { opacity: 0.32; }
50% { opacity: 0.62; }
}
@keyframes ps-blink {
0%, 100% { opacity: 0.35; }
50% { opacity: 0.9; }
}
@media (prefers-reduced-motion: reduce) {
.ps-anim, .ps-march, .ps-breathe, .ps-blink { animation: none !important; }
.ps-flap { transform: scaleY(0.03); }
.ps-hole { opacity: 0; }
.ps-tape-run { stroke-dashoffset: 0; }
.ps-disp, .ps-scan { opacity: 0; }
.ps-label { opacity: 1; }
}
</style>
</defs>
<!-- 地面光晕 -->
<ellipse cx="612" cy="566" rx="342" ry="36" fill="url(#ps-groundGlow)" />
<!-- 球机监控范围 -->
<g class="ps-breathe">
<path d="M216 152 L300 452 L880 442 Z" fill="url(#ps-coneGrad)" />
<path d="M216 152 L300 452 M216 152 L880 442" class="ps-fov ps-march" />
</g>
<!-- 球机 -->
<g>
<path class="ps-ln-soft" d="M148 88 H288" />
<path class="ps-ln-soft" d="M156 96 l10 -12 M182 96 l10 -12 M208 96 l10 -12 M234 96 l10 -12 M260 96 l10 -12" opacity="0.55" />
<rect x="208" y="88" width="16" height="26" rx="3" fill="url(#ps-metal)" stroke="#a8c8f2" stroke-width="2.4" />
<rect x="182" y="112" width="68" height="9" rx="4" fill="url(#ps-metal)" stroke="#a8c8f2" stroke-width="2.4" />
<path d="M184 121 A32 30 0 0 0 248 121 Z" fill="url(#ps-metal)" stroke="#a8c8f2" stroke-width="2.4" stroke-linejoin="round" />
<circle cx="216" cy="129" r="7" fill="#0b1b3a" stroke="#38bdf8" stroke-width="2" />
<circle class="ps-blink" cx="216" cy="129" r="3.5" fill="#5eead4" filter="url(#ps-glow)" />
</g>
<!-- 打包台 -->
<g>
<path class="ps-surf" d="M300 450 L860 450 L916 404 L356 404 Z" />
<path class="ps-surf ps-surf--side" d="M300 450 L860 450 L860 466 L300 466 Z" />
<path class="ps-surf ps-surf--side" d="M860 450 L916 404 L916 420 L860 466 Z" />
<rect class="ps-surf ps-surf--side" x="318" y="466" width="18" height="104" rx="2" />
<rect class="ps-surf ps-surf--side" x="310" y="562" width="34" height="8" rx="3" />
<rect class="ps-surf ps-surf--side" x="824" y="466" width="18" height="104" rx="2" />
<rect class="ps-surf ps-surf--side" x="816" y="562" width="34" height="8" rx="3" />
<rect class="ps-surf ps-surf--side" x="898" y="420" width="18" height="104" rx="2" />
<rect class="ps-surf ps-surf--side" x="890" y="516" width="34" height="8" rx="3" />
</g>
<!-- 物料架 -->
<g>
<path class="ps-surf" d="M356 382 L528 382 L563 354 L391 354 Z" />
<path class="ps-surf ps-surf--side" d="M356 382 L528 382 L528 389 L356 389 Z" />
<path class="ps-surf" d="M356 258 L528 258 L563 230 L391 230 Z" />
<path class="ps-surf ps-surf--side" d="M356 258 L528 258 L528 265 L356 265 Z" />
<!-- 平折纸箱 -->
<g stroke="#ffe0b0" stroke-width="2.2" stroke-linejoin="round">
<path d="M387 344 L495 344 L495 376 L387 376 Z" fill="url(#ps-boxFront)" />
<path d="M387 352 H495 M387 360 H495 M387 368 H495" stroke-width="1.6" opacity="0.55" />
<path d="M387 344 L495 344 L517 326 L409 326 Z" fill="url(#ps-lidTop)" />
<path d="M441 326 L453 344" stroke-width="1.6" opacity="0.55" />
</g>
<!-- 整箱 -->
<g stroke="#ffe0b0" stroke-width="2.2" stroke-linejoin="round">
<path d="M411 208 L473 208 L473 252 L411 252 Z" fill="url(#ps-boxFront)" />
<path d="M473 208 L495 190 L495 234 L473 252 Z" fill="url(#ps-boxSide)" />
<path d="M411 208 L473 208 L495 190 L433 190 Z" fill="url(#ps-lidTop)" />
<path d="M442 208 L464 190" stroke-width="1.6" opacity="0.55" />
</g>
<rect class="ps-surf ps-surf--side" x="391" y="230" width="16" height="186" rx="2" />
<rect class="ps-surf ps-surf--side" x="547" y="230" width="16" height="186" rx="2" />
<rect class="ps-surf ps-surf--side" x="356" y="258" width="16" height="186" rx="2" />
<rect class="ps-surf ps-surf--side" x="512" y="258" width="16" height="186" rx="2" />
</g>
<!-- 待打包包裹:开封 → 折盖 → 打胶带 → 贴面单 -->
<g>
<path d="M624 447 L774 447 L818 411 L668 411 Z" fill="#0b1b3a" opacity="0.35" />
<!-- 后盖板 -->
<g transform="translate(660 321)">
<g class="ps-anim ps-flap ps-flap--back">
<path d="M0 0 L150 0 L150 -26 L0 -26 Z" fill="url(#ps-flapFill)" class="ps-box-edge" />
</g>
</g>
<path d="M616 357 L766 357 L810 321 L660 321 Z" fill="url(#ps-lidTop)" class="ps-box-edge" />
<path d="M638 339 H788" stroke="#b98a55" stroke-width="1.6" opacity="0.75" stroke-linecap="round" />
<path d="M766 357 L810 321 L810 405 L766 441 Z" fill="url(#ps-boxSide)" class="ps-box-edge" />
<path d="M616 357 L766 357 L766 441 L616 441 Z" fill="url(#ps-boxFront)" class="ps-box-edge" />
<!-- 箱内腔(开封时可见) -->
<path class="ps-anim ps-hole" d="M638 347 L768 347 L788 331 L658 331 Z" fill="#7a5326" opacity="0.9" stroke="#c99a63" stroke-width="1.6" />
<!-- 前盖板 -->
<g transform="translate(616 357)">
<g class="ps-anim ps-flap ps-flap--front">
<path d="M0 0 L150 0 L150 -26 L0 -26 Z" fill="url(#ps-flapFill)" class="ps-box-edge" />
</g>
</g>
<!-- 封箱胶带 -->
<path class="ps-tape ps-anim ps-tape-run" d="M638 339 H788" stroke-dasharray="150" stroke-dashoffset="150" />
<path d="M641 337 H785" stroke="#e0f2fe" stroke-width="1.6" opacity="0.5" stroke-linecap="round" stroke-dasharray="150" stroke-dashoffset="150" class="ps-anim ps-tape-run" />
<!-- 面单 -->
<g class="ps-anim ps-label" opacity="0">
<path class="ps-paper ps-label-edge ps-anim" d="M627 355 L700 355 L718 340 L645 340 Z" fill="#f8fbff" />
<g class="ps-ink-line">
<path d="M635 353 l7 -6 M643 353 l7 -6 M651 353 l7 -6 M659 353 l7 -6" />
<path d="M674 352 l20 -16 M674 348 l14 -11" opacity="0.7" />
</g>
</g>
<!-- 相机扫描线 -->
<g class="ps-anim ps-scan" opacity="0">
<rect x="626" y="334" width="7" height="24" rx="3" fill="url(#ps-scanGrad)" />
<path d="M629.5 333 V359" stroke="#5eead4" stroke-width="1.6" filter="url(#ps-glow)" />
</g>
</g>
<!-- 工业相机 -->
<g>
<path d="M570 430 L602 430 L616 418 L584 418 Z" fill="url(#ps-metal)" stroke="#a8c8f2" stroke-width="2.4" stroke-linejoin="round" />
<rect x="580" y="200" width="16" height="218" rx="2" fill="url(#ps-metal)" stroke="#a8c8f2" stroke-width="2.4" />
<rect x="580" y="192" width="128" height="14" rx="4" fill="url(#ps-metal)" stroke="#a8c8f2" stroke-width="2.4" />
<rect x="638" y="206" width="60" height="38" rx="7" fill="url(#ps-metal)" stroke="#a8c8f2" stroke-width="2.4" />
<path d="M654 244 L682 244 L676 264 L660 264 Z" fill="url(#ps-metal)" stroke="#a8c8f2" stroke-width="2.4" stroke-linejoin="round" />
<ellipse cx="668" cy="266" rx="9" ry="4" fill="#0b1b3a" stroke="#38bdf8" stroke-width="2" />
<circle class="ps-blink" cx="668" cy="266" r="4" fill="#5eead4" filter="url(#ps-glow)" />
<path class="ps-fov ps-march" d="M668 268 L630 352 M668 268 L714 338" />
</g>
<!-- 封箱胶带器(沿箱缝移动) -->
<g class="ps-anim ps-disp" opacity="0">
<g transform="translate(624 330)">
<circle cx="0" cy="0" r="9" fill="#0b1b3a" stroke="#7dd3fc" stroke-width="2.2" />
<circle cx="0" cy="0" r="3.2" fill="#38bdf8" />
<path d="M9 0 H20" stroke="#7dd3fc" stroke-width="2.2" stroke-linecap="round" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 13 KiB

View File

@ -34,7 +34,7 @@ const router = useRouter();
* - `admin: true` → **只有主体管理员**能看(设备 / 录像机 / 摄像头 / 工作台 / 扫码记录)
*/
const allMenus = [
{ to: '/', label: '首页', subject: false, admin: false },
{ to: '/dashboard', label: '首页', subject: false, admin: false },
{ to: '/devices', label: '设备管理', subject: true, admin: true },
{ to: '/nvrs', label: 'NVR 录像机', subject: true, admin: true },
{ to: '/cameras', label: '摄像头', subject: true, admin: true },
@ -63,6 +63,7 @@ const platformMenus = [
{ to: '/admin/plans', label: '套餐管理' },
{ to: '/admin/members', label: '管理员' },
{ to: '/admin/extension', label: '插件配置' },
{ to: '/admin/doc', label: '文档管理' },
];
/** 当前主体(用于右上角展示 / 过期提示) */
@ -159,9 +160,21 @@ onMounted(() => {
</aside>
<div class="main">
<header class="topbar">
<slot name="title">控制台</slot>
<span class="topbar-title"><slot name="title">控制台</slot></span>
<div class="topbar-right">
<!-- 文档站入口:与权限无关(文档本身是公开页面),新窗口打开后端生成的静态页 -->
<a
class="download-btn doc-entry"
href="/doc/"
target="_blank"
rel="noopener"
title="打开使用文档(新窗口)"
>
<span class="download-icon" aria-hidden="true">📘</span>
<span class="download-text">文档</span>
</a>
<!-- 下载入口:**与权限无关,所有人都能看到**(桌面端 / Android 扫码台) -->
<div class="downloads">
<a
@ -251,16 +264,23 @@ onMounted(() => {
color: #64748b;
}
/* 标题与右上角一组:标题可以被压缩,右侧不折行 */
/* 标题与右上角一组:标题不折行(右上角元素多时优先压缩右侧的次要文字) */
.topbar {
gap: 12px;
}
.topbar-title {
flex: 0 0 auto;
white-space: nowrap;
font-weight: 600;
}
.topbar-right {
display: flex;
align-items: center;
gap: 10px;
flex: 0 0 auto;
min-width: 0;
}
/* 右上角的分隔线 */
@ -316,6 +336,13 @@ onMounted(() => {
font-size: 11px;
}
/* 顶栏元素多:窄屏先把「文档」按钮收成只留图标 */
@media (max-width: 1400px) {
.doc-entry .download-text {
display: none;
}
}
/* 窄屏:版本号先藏起来,保证主体切换与账号不被挤 */
@media (max-width: 1180px) {
.download-version {

View File

@ -15,6 +15,9 @@ import { ensurePlatformAdmin } from '@/composables/usePlatformAdmin';
* 不看主体、不需要选主体;不是平台管理员直接跳回首页(后端同名接口返回 403)。
*/
const routes: RouteRecordRaw[] = [
// 根路径就是入口:**未登录时原地显示登录页**(地址不会跳到 /login),
// 已登录由下面的路由守卫直接送去 /dashboard 看板。
{ path: '/', name: 'root', component: () => import('@/views/LoginView.vue'), meta: { public: true, bare: true } },
{ path: '/login', name: 'login', component: () => import('@/views/LoginView.vue'), meta: { public: true, bare: true } },
{ path: '/forgot', name: 'forgot', component: () => import('@/views/ForgotView.vue'), meta: { public: true, bare: true } },
{ path: '/reset', name: 'reset', component: () => import('@/views/ResetView.vue'), meta: { public: true, bare: true, alwaysShow: true } },
@ -31,7 +34,7 @@ const routes: RouteRecordRaw[] = [
meta: { public: true, bare: true },
},
{ path: '/', name: 'home', component: () => import('@/views/HomeView.vue'), meta: { allowNoSubject: true } },
{ path: '/dashboard', name: 'dashboard', component: () => import('@/views/HomeView.vue'), meta: { allowNoSubject: true } },
// 主体 / 成员:没有主体时只有这个入口(创建主体、切换主体、绑成员)
{ path: '/subjects', name: 'subjects', component: () => import('@/views/SubjectsView.vue'), meta: { allowNoSubject: true } },
{ path: '/devices', name: 'devices', component: () => import('@/views/DevicesView.vue'), meta: { adminOnly: true } },
@ -74,6 +77,13 @@ const routes: RouteRecordRaw[] = [
component: () => import('@/views/AdminExtensionView.vue'),
meta: { allowNoSubject: true, platformAdmin: true },
},
// 文档站(简易 CMS):分类 → 栏目 → 内容页;保存后自动生成 /doc/** 静态页面与 sitemap.txt
{
path: '/admin/doc',
name: 'admin-doc',
component: () => import('@/views/AdminDocView.vue'),
meta: { allowNoSubject: true, platformAdmin: true },
},
// 测试页只在开发构建里存在:生产包不包含该路由,也不会产出它的 chunk
...(import.meta.env.DEV
? [{ path: '/test', name: 'test', component: () => import('@/views/TestView.vue'), meta: { adminOnly: true } } as RouteRecordRaw]
@ -91,8 +101,9 @@ router.beforeEach(async (to) => {
const isPublic = Boolean(to.meta.public);
// 桌面端「工具 → 打开配置页」:`?token=<用户 JWT>` 直接登录,并把 token 从地址栏去掉
// ⚠️ 只对需要登录的页面生效:`/reset?token=…` 里的 token 是重置令牌,不是 SSO JWT
// ⚠️ 根路径现在是公开页(未登录显示登录表单),但桌面端正是用 `/?token=…` 免登录进来的,同样要吃 token
const ssoToken = typeof to.query.token === 'string' ? to.query.token : (typeof to.query.sso === 'string' ? to.query.sso : '');
if (!isPublic && ssoToken) {
if (ssoToken && (!isPublic || to.name === 'root')) {
localStorage.setItem('packs_token', ssoToken);
const query = { ...to.query };
delete query.token;
@ -101,6 +112,12 @@ router.beforeEach(async (to) => {
}
const logged = Boolean(getToken());
// 根路径:已登录直接进看板;未登录就**原地**渲染登录页(地址保持 `/`,不跳 /login)
if (to.name === 'root') {
return logged ? { name: 'dashboard' } : true;
}
if (!isPublic && !logged) {
return { name: 'login', query: { redirect: to.fullPath } };
}
@ -110,7 +127,7 @@ router.beforeEach(async (to) => {
|| to.name === 'wechat-confirm'
|| to.name === 'local-service';
if (isPublic && logged && !alwaysShow) {
return { name: 'home' };
return { name: 'dashboard' };
}
// 业务页都要主体:没拉过列表先拉一次,没有可用主体就去「主体 / 成员」页创建
@ -125,12 +142,12 @@ router.beforeEach(async (to) => {
}
// 业务数据(设备 / 录像机 / 摄像头 / 工作台 / 扫码记录)只有主体管理员能进
if (to.meta.adminOnly === true && !isSubjectAdmin.value) {
return { name: 'home', query: { denied: '1' } };
return { name: 'dashboard', query: { denied: '1' } };
}
// 平台管理页只有平台管理员能进(没权限按「被拒绝」处理,与主体管理员那种一致)
if (to.meta.platformAdmin === true) {
const allowed = await ensurePlatformAdmin();
if (!allowed) return { name: 'home', query: { denied: '1' } };
if (!allowed) return { name: 'dashboard', query: { denied: '1' } };
}
}
return true;

View File

@ -0,0 +1,839 @@
<script setup lang="ts">
/**
* 平台管理 · 文档管理(简易 CMS)
*
* 层级固定两级:**分类**(文档站顶部 tab)→ **栏目**(侧边栏分组)→ **内容页**(Markdown)。
* 保存后由后端整站重生成 `/doc/**` 静态页面与 `/sitemap.txt`(新链接追加在 sitemap 末尾)。
*
* 接口:`/api/web/admin/doc/*`(平台管理员)
*/
import { computed, onMounted, reactive, ref } from 'vue';
import AppLayout from '@/components/AppLayout.vue';
import ModalBox from '@/components/ModalBox.vue';
import { ApiError } from '@/api/client';
import {
createDocArticle,
createDocCategory,
createDocSection,
fetchDocArticle,
fetchDocTree,
rebuildDocSite,
removeDocArticle,
removeDocCategory,
removeDocSection,
updateDocArticle,
updateDocCategory,
updateDocSection,
type DocArticleInput,
type DocCategoryInput,
type DocCategoryNode,
type DocSectionInput,
type DocSectionNode,
} from '@/api/admin';
/** 文档站在站点里的入口(后端生成的静态 HTML) */
const DOC_SITE_URL = '/doc/';
const tree = ref<DocCategoryNode[]>([]);
const loading = ref(false);
const error = ref('');
const ok = ref('');
const activeCategoryId = ref(0);
const activeArticleId = ref(0);
const categories = computed(() => tree.value);
const activeCategory = computed(() => tree.value.find(item => item.id === activeCategoryId.value) || null);
const sections = computed(() => activeCategory.value?.sections || []);
async function load(keepSelection = true) {
loading.value = true;
error.value = '';
try {
const data = await fetchDocTree();
tree.value = data.list;
const exists = tree.value.some(item => item.id === activeCategoryId.value);
if (!keepSelection || !exists) {
activeCategoryId.value = tree.value.length ? tree.value[0].id : 0;
activeArticleId.value = 0;
resetArticle();
}
} catch (err) {
error.value = err instanceof ApiError ? err.message : '加载失败';
} finally {
loading.value = false;
}
}
/** 生成地址:`/doc/<分类编码>/<文章地址>.html` */
function articleUrl(slug: string): string {
if (!slug || !activeCategory.value) return '';
return `/doc/${activeCategory.value.code}/${slug}.html`;
}
// ==================== 内容页编辑 ====================
interface ArticleForm {
id: number;
sectionId: number | '';
title: string;
slug: string;
summary: string;
content: string;
sort: number | string;
status: number;
}
function blankArticle(): ArticleForm {
return { id: 0, sectionId: '', title: '', slug: '', summary: '', content: '', sort: 10, status: 1 };
}
const articleForm = reactive<ArticleForm>(blankArticle());
const articleLoading = ref(false);
const saving = ref(false);
const editing = computed(() => articleForm.id > 0);
function resetArticle() {
Object.assign(articleForm, blankArticle());
}
/** 点左侧某一篇:拉正文填表单 */
async function selectArticle(id: number) {
error.value = '';
ok.value = '';
articleLoading.value = true;
try {
const data = await fetchDocArticle(id);
activeArticleId.value = data.id;
Object.assign(articleForm, {
id: data.id,
sectionId: data.sectionId,
title: data.title,
slug: data.slug,
summary: data.summary || '',
content: data.content || '',
sort: data.sort,
status: data.status,
});
} catch (err) {
error.value = err instanceof ApiError ? err.message : '内容加载失败';
} finally {
articleLoading.value = false;
}
}
/** 新建内容页:默认落在某个栏目下,排序排到最后 */
function openArticleCreate(section: DocSectionNode) {
error.value = '';
ok.value = '';
activeArticleId.value = 0;
Object.assign(articleForm, blankArticle());
articleForm.sectionId = section.id;
articleForm.sort = section.articles.length
? Math.max(...section.articles.map(item => item.sort)) + 10
: 10;
}
/** 切分类:当前文章不在新分类里就换成该分类第一篇 */
function selectCategory(id: number) {
if (id === activeCategoryId.value) return;
activeCategoryId.value = id;
const all = sections.value.flatMap(section => section.articles);
if (all.some(item => item.id === activeArticleId.value)) return;
if (all.length) {
void selectArticle(all[0].id);
} else {
activeArticleId.value = 0;
resetArticle();
}
}
const canSaveArticle = computed(() => {
if (!articleForm.title.trim()) return false;
if (articleForm.sectionId === '') return false;
if (!Number.isInteger(Number(articleForm.sort)) || Number(articleForm.sort) < 0) return false;
return true;
});
async function saveArticle() {
if (!canSaveArticle.value) return;
const body: DocArticleInput = {
sectionId: Number(articleForm.sectionId),
title: articleForm.title.trim(),
summary: articleForm.summary.trim() || null,
content: articleForm.content,
sort: Number(articleForm.sort),
status: articleForm.status,
};
saving.value = true;
error.value = '';
ok.value = '';
try {
if (editing.value) {
const data = await updateDocArticle(articleForm.id, body);
ok.value = `已保存「${data.title}」,已重新生成文档页面与 sitemap`;
await load();
await selectArticle(data.id);
} else {
const slug = articleForm.slug.trim();
if (slug) body.slug = slug;
const data = await createDocArticle(body);
ok.value = `已新增「${data.title}」:${data.url || articleUrl(data.slug)}`;
await load();
await selectArticle(data.id);
}
} catch (err) {
error.value = err instanceof ApiError ? err.message : '保存失败';
} finally {
saving.value = false;
}
}
async function deleteArticle() {
if (!editing.value) return;
if (!window.confirm(`确认删除内容页「${articleForm.title}」?\n\n删除后文档页面与 sitemap 里的链接会一起移除,且不能恢复。`)) return;
saving.value = true;
error.value = '';
ok.value = '';
try {
await removeDocArticle(articleForm.id);
ok.value = `已删除「${articleForm.title}」`;
activeArticleId.value = 0;
resetArticle();
await load();
} catch (err) {
error.value = err instanceof ApiError ? err.message : '删除失败';
} finally {
saving.value = false;
}
}
// ==================== 分类 ====================
interface CategoryForm {
id: number;
code: string;
name: string;
description: string;
sort: number | string;
status: number;
}
const categoryOpen = ref(false);
const categorySaving = ref(false);
const categoryForm = reactive<CategoryForm>({ id: 0, code: '', name: '', description: '', sort: 10, status: 1 });
function openCategoryCreate() {
error.value = '';
ok.value = '';
Object.assign(categoryForm, {
id: 0,
code: '',
name: '',
description: '',
sort: categories.value.length
? Math.max(...categories.value.map(item => item.sort)) + 10
: 10,
status: 1,
});
categoryOpen.value = true;
}
function openCategoryEdit() {
const current = activeCategory.value;
if (!current) return;
error.value = '';
ok.value = '';
Object.assign(categoryForm, {
id: current.id,
code: current.code,
name: current.name,
description: current.description || '',
sort: current.sort,
status: current.status,
});
categoryOpen.value = true;
}
const canSaveCategory = computed(() => Boolean(categoryForm.name.trim()));
async function saveCategory() {
if (!canSaveCategory.value) return;
const body: DocCategoryInput = {
name: categoryForm.name.trim(),
description: categoryForm.description.trim() || null,
sort: Number(categoryForm.sort),
status: categoryForm.status,
};
categorySaving.value = true;
error.value = '';
ok.value = '';
try {
if (categoryForm.id) {
const data = await updateDocCategory(categoryForm.id, body);
ok.value = `分类「${data.name}」已保存`;
} else {
const code = categoryForm.code.trim().toLowerCase();
if (code) body.code = code;
const data = await createDocCategory(body);
ok.value = `分类「${data.name}」已新增(地址 /doc/${data.code}/ )`;
activeCategoryId.value = data.id;
}
categoryOpen.value = false;
await load();
} catch (err) {
error.value = err instanceof ApiError ? err.message : '保存失败';
} finally {
categorySaving.value = false;
}
}
async function deleteCategory() {
const current = activeCategory.value;
if (!current) return;
if (!window.confirm(`确认删除分类「${current.name}」?\n\n底下的 ${current.sections.length} 个栏目和 ${current.articleCount} 篇内容会一起删除。`)) return;
error.value = '';
ok.value = '';
try {
await removeDocCategory(current.id);
ok.value = `分类「${current.name}」已删除`;
activeCategoryId.value = 0;
activeArticleId.value = 0;
resetArticle();
await load(false);
} catch (err) {
error.value = err instanceof ApiError ? err.message : '删除失败';
}
}
// ==================== 栏目 ====================
interface SectionForm {
id: number;
name: string;
sort: number | string;
status: number;
}
const sectionOpen = ref(false);
const sectionSaving = ref(false);
const sectionForm = reactive<SectionForm>({ id: 0, name: '', sort: 10, status: 1 });
function openSectionCreate() {
if (!activeCategory.value) return;
error.value = '';
ok.value = '';
Object.assign(sectionForm, {
id: 0,
name: '',
sort: sections.value.length
? Math.max(...sections.value.map(item => item.sort)) + 10
: 10,
status: 1,
});
sectionOpen.value = true;
}
function openSectionEdit(section: DocSectionNode) {
error.value = '';
ok.value = '';
Object.assign(sectionForm, {
id: section.id,
name: section.name,
sort: section.sort,
status: section.status,
});
sectionOpen.value = true;
}
const canSaveSection = computed(() => Boolean(sectionForm.name.trim()));
async function saveSection() {
if (!canSaveSection.value) return;
const body: DocSectionInput = {
name: sectionForm.name.trim(),
sort: Number(sectionForm.sort),
status: sectionForm.status,
};
sectionSaving.value = true;
error.value = '';
ok.value = '';
try {
if (sectionForm.id) {
const data = await updateDocSection(sectionForm.id, body);
ok.value = `栏目「${data.name}」已保存`;
} else {
const data = await createDocSection({ ...body, categoryId: activeCategoryId.value });
ok.value = `栏目「${data.name}」已新增`;
}
sectionOpen.value = false;
await load();
} catch (err) {
error.value = err instanceof ApiError ? err.message : '保存失败';
} finally {
sectionSaving.value = false;
}
}
async function deleteSection(section: DocSectionNode) {
const tip = `确认删除栏目「${section.name}」?\n\n底下的 ${section.articles.length} 篇内容会一起删除。`;
if (!window.confirm(tip)) return;
error.value = '';
ok.value = '';
try {
await removeDocSection(section.id);
ok.value = `栏目「${section.name}」已删除`;
if (section.articles.some(item => item.id === activeArticleId.value)) {
activeArticleId.value = 0;
resetArticle();
}
await load();
} catch (err) {
error.value = err instanceof ApiError ? err.message : '删除失败';
}
}
// ==================== 其它 ====================
const rebuilding = ref(false);
async function rebuild() {
rebuilding.value = true;
error.value = '';
ok.value = '';
try {
const data = await rebuildDocSite();
ok.value = `文档站已重新生成:${data.files} 个页面,sitemap ${data.urls} 条链接`;
} catch (err) {
error.value = err instanceof ApiError ? err.message : '重新生成失败';
} finally {
rebuilding.value = false;
}
}
onMounted(() => load(false));
</script>
<template>
<AppLayout>
<template #title>文档管理</template>
<div v-if="error" class="alert alert-error">{{ error }}</div>
<div v-if="ok" class="alert alert-ok">{{ ok }}</div>
<div class="doc-admin">
<!-- 左:分类 tab + 栏目 / 内容页树 -->
<section class="card doc-nav">
<div class="toolbar toolbar-wrap">
<button class="btn btn-sm" @click="openCategoryCreate">新增分类</button>
<button class="btn btn-ghost btn-sm" :disabled="!activeCategory" @click="openCategoryEdit">编辑分类</button>
<button class="btn btn-danger btn-sm" :disabled="!activeCategory" @click="deleteCategory">删除分类</button>
</div>
<div class="cat-tabs">
<button
v-for="item in categories"
:key="item.id"
type="button"
class="cat-tab"
:class="{ 'is-active': item.id === activeCategoryId }"
@click="selectCategory(item.id)"
>
{{ item.name }}
<span class="cat-count">{{ item.articleCount }}</span>
<span v-if="item.status === 0" class="badge badge-off">隐藏</span>
</button>
</div>
<p v-if="loading" class="hint">加载中…</p>
<p v-else-if="!categories.length" class="hint">还没有分类,点「新增分类」开始。</p>
<div v-else class="tree">
<div v-for="section in sections" :key="section.id" class="tree-group">
<div class="tree-head">
<b>{{ section.name }}</b>
<span v-if="section.status === 0" class="badge badge-off">隐藏</span>
<span class="tree-ops">
<a href="#" @click.prevent="openArticleCreate(section)">+内容</a>
<a href="#" @click.prevent="openSectionEdit(section)">编辑</a>
<a href="#" class="is-danger" @click.prevent="deleteSection(section)">删除</a>
</span>
</div>
<ul>
<li
v-for="article in section.articles"
:key="article.id"
class="tree-item"
:class="{ 'is-active': article.id === activeArticleId }"
@click="selectArticle(article.id)"
>
<span class="tree-title">{{ article.title }}</span>
<span v-if="article.status === 0" class="badge badge-off">草稿</span>
</li>
<li v-if="!section.articles.length" class="tree-empty">这个栏目还没有内容</li>
</ul>
</div>
<div class="tree-foot">
<button class="btn btn-ghost btn-sm" :disabled="!activeCategory" @click="openSectionCreate">新增栏目</button>
<button class="btn btn-ghost btn-sm" :disabled="rebuilding" @click="rebuild">
{{ rebuilding ? '生成中…' : '重新生成文档站' }}
</button>
<a class="btn btn-ghost btn-sm" :href="DOC_SITE_URL" target="_blank" rel="noopener">打开文档站 ↗</a>
</div>
</div>
</section>
<!-- 右:内容页编辑 -->
<section class="card doc-editor">
<p v-if="!activeCategory" class="hint">先在左边选一个分类。</p>
<p v-else-if="!sections.length" class="hint">这个分类下还没有栏目,点「新增栏目」建一个,再往里面加内容页。</p>
<p v-else-if="!articleForm.id && articleForm.sectionId === ''" class="hint">
点左侧「+内容」新建内容页,或点某一篇开始编辑。
</p>
<template v-else>
<div class="editor-head">
<b>{{ editing ? '编辑内容页' : '新建内容页' }}</b>
<a v-if="editing && articleForm.slug" :href="articleUrl(articleForm.slug)" target="_blank" rel="noopener">
在文档站查看 ↗
</a>
</div>
<div class="form-grid">
<label class="field span-2">
<span>标题</span>
<input v-model="articleForm.title" maxlength="128" placeholder="如:设备扫码登录" />
</label>
<label class="field">
<span>所属栏目</span>
<select v-model.number="articleForm.sectionId">
<option v-for="section in sections" :key="section.id" :value="section.id">{{ section.name }}</option>
</select>
</label>
<label class="field">
<span>排序(栏目内,小的在前)</span>
<input v-model="articleForm.sort" type="number" min="0" max="9999" />
</label>
<label class="field">
<span>地址(可选,创建后不可改)</span>
<input
v-model="articleForm.slug"
maxlength="64"
:disabled="editing"
placeholder="如 welcome(留空自动生成 a1 / a2)"
/>
</label>
<label class="field">
<span>状态</span>
<select v-model.number="articleForm.status">
<option :value="1">已发布(生成页面)</option>
<option :value="0">草稿(不生成页面)</option>
</select>
</label>
<label class="field span-2">
<span>摘要(可选,列表与搜索引擎描述)</span>
<input v-model="articleForm.summary" maxlength="255" placeholder="一句话说明这篇讲什么" />
</label>
<label class="field span-2">
<span>正文(Markdown:标题 # / ##、列表、代码块、链接、粗体)</span>
<textarea v-model="articleForm.content" rows="18" spellcheck="false" placeholder="## 小标题&#10;&#10;正文内容…" />
</label>
</div>
<p v-if="editing && articleForm.slug" class="hint">
页面地址:<code>{{ articleUrl(articleForm.slug) }}</code>(保存后自动重新生成)
</p>
<div class="editor-foot">
<button class="btn" :disabled="saving || articleLoading || !canSaveArticle" @click="saveArticle">
{{ saving ? '保存中…' : '保存' }}
</button>
<button v-if="editing" class="btn btn-danger" :disabled="saving" @click="deleteArticle">删除</button>
<span class="hint">保存后自动生成目录与静态 HTML,并把新链接追加到 /sitemap.txt</span>
</div>
</template>
</section>
</div>
<!-- 分类弹窗 -->
<ModalBox
:open="categoryOpen"
:title="categoryForm.id ? '编辑分类' : '新增分类'"
width="520px"
@close="categoryOpen = false"
>
<div class="form-grid">
<label class="field span-2">
<span>分类名称(文档站顶部 tab)</span>
<input v-model="categoryForm.name" maxlength="64" placeholder="如:设备接入" />
</label>
<label v-if="!categoryForm.id" class="field span-2">
<span>分类编码(可选,留空自动生成 cat1)</span>
<input v-model="categoryForm.code" maxlength="32" placeholder="小写字母 / 数字 / 短横线,创建后不可改" />
</label>
<label class="field">
<span>排序(小的在前)</span>
<input v-model="categoryForm.sort" type="number" min="0" max="9999" />
</label>
<label class="field">
<span>状态</span>
<select v-model.number="categoryForm.status">
<option :value="1">展示</option>
<option :value="0">隐藏(不生成页面)</option>
</select>
</label>
<label class="field span-2">
<span>分类说明(可选)</span>
<input v-model="categoryForm.description" maxlength="255" placeholder="如:录像机 / 摄像头 / 工作台的接入步骤" />
</label>
</div>
<p v-if="categoryForm.id" class="hint">
分类编码 <code>{{ categoryForm.code }}</code> 决定地址 <code>/doc/{{ categoryForm.code }}/</code>,创建后不能修改。
</p>
<template #footer>
<button class="btn btn-ghost" :disabled="categorySaving" @click="categoryOpen = false">取消</button>
<button class="btn" :disabled="categorySaving || !canSaveCategory" @click="saveCategory">
{{ categorySaving ? '保存中…' : '保存' }}
</button>
</template>
</ModalBox>
<!-- 栏目弹窗 -->
<ModalBox
:open="sectionOpen"
:title="sectionForm.id ? '编辑栏目' : '新增栏目'"
width="440px"
@close="sectionOpen = false"
>
<div class="form-grid">
<label class="field span-2">
<span>栏目名称(侧边栏分组标题)</span>
<input v-model="sectionForm.name" maxlength="64" placeholder="如:安装部署" />
</label>
<label class="field">
<span>排序(小的在前)</span>
<input v-model="sectionForm.sort" type="number" min="0" max="9999" />
</label>
<label class="field">
<span>状态</span>
<select v-model.number="sectionForm.status">
<option :value="1">展示</option>
<option :value="0">隐藏(不生成页面)</option>
</select>
</label>
</div>
<template #footer>
<button class="btn btn-ghost" :disabled="sectionSaving" @click="sectionOpen = false">取消</button>
<button class="btn" :disabled="sectionSaving || !canSaveSection" @click="saveSection">
{{ sectionSaving ? '保存中…' : '保存' }}
</button>
</template>
</ModalBox>
</AppLayout>
</template>
<style scoped>
.doc-admin {
display: grid;
grid-template-columns: minmax(0, 320px) minmax(0, 1fr);
gap: 14px;
align-items: start;
}
/* 左侧导航:分类 tab 换行铺满,树列表可滚动 */
.doc-nav {
display: flex;
flex-direction: column;
gap: 12px;
}
.doc-nav .toolbar {
margin-bottom: 0;
}
.cat-tabs {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.cat-tab {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 10px;
border: 1px solid var(--border);
border-radius: 999px;
background: #fff;
color: #334155;
font-size: 12.5px;
cursor: pointer;
}
.cat-tab:hover {
border-color: var(--brand);
color: var(--brand);
}
.cat-tab.is-active {
background: var(--brand);
border-color: var(--brand);
color: #fff;
}
.cat-count {
font-size: 11px;
opacity: 0.75;
}
.tree-group {
margin-bottom: 14px;
}
.tree-head {
display: flex;
align-items: center;
gap: 6px;
padding: 4px 2px;
}
.tree-head b {
font-size: 13px;
}
.tree-ops {
margin-left: auto;
display: flex;
gap: 8px;
font-size: 12px;
}
.tree-ops .is-danger {
color: var(--danger);
}
.tree ul {
list-style: none;
margin: 4px 0 0;
padding: 0;
}
.tree-item {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 10px;
border-radius: 8px;
font-size: 13px;
color: #334155;
cursor: pointer;
}
.tree-item:hover {
background: rgba(37, 99, 235, 0.07);
}
.tree-item.is-active {
background: rgba(37, 99, 235, 0.12);
color: var(--brand);
font-weight: 600;
}
.tree-title {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tree-empty {
padding: 4px 10px;
font-size: 12.5px;
color: var(--text-muted);
}
.tree-foot {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 8px;
}
/* 右侧编辑器 */
.doc-editor {
min-width: 0;
}
.editor-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 12px;
font-size: 14px;
}
.form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0 12px;
}
.span-2 {
grid-column: span 2;
}
textarea {
border: 1px solid var(--border);
border-radius: 8px;
padding: 10px 12px;
font: inherit;
font-family: ui-monospace, SFMono-Regular, Consolas, 'Liberation Mono', monospace;
font-size: 13px;
line-height: 1.6;
outline: none;
resize: vertical;
min-height: 220px;
}
textarea:focus {
border-color: var(--brand);
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.12);
}
.editor-foot {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
margin-top: 4px;
}
@media (max-width: 1100px) {
.doc-admin {
grid-template-columns: 1fr;
}
}
@media (max-width: 640px) {
.form-grid {
grid-template-columns: 1fr;
}
.span-2 {
grid-column: span 1;
}
}
</style>

View File

@ -298,6 +298,7 @@ onBeforeUnmount(() => {
<b>{{ clockTime }}</b>
<span>{{ clockDate }}</span>
</div>
<a class="tech-btn" href="/doc/" target="_blank" rel="noopener">查看文档</a>
<button class="tech-btn" type="button" :disabled="busy" @click="manualRefresh">
{{ busy ? '刷新中…' : '刷新' }}
</button>
@ -562,6 +563,9 @@ onBeforeUnmount(() => {
}
.tech-btn {
display: inline-flex;
align-items: center;
justify-content: center;
height: 30px;
padding: 0 14px;
border: 1px solid var(--tech-border);
@ -570,6 +574,7 @@ onBeforeUnmount(() => {
color: var(--tech-accent-2);
font-size: 12px;
letter-spacing: 1px;
text-decoration: none;
cursor: pointer;
transition: background 0.15s ease, box-shadow 0.15s ease;
}

View File

@ -4,7 +4,7 @@
*
* 版面按既定风格:
* - 整页**深色科技背景**(海军蓝渐变 + 淡网格 + 光晕,`.login-bg` 只画背景、不接事件);
* - 左侧品牌区(标题 + 副标题 + 等距插画 `assets/login-hero.svg`),右侧白色登录卡(`.login-card`);
* - 左侧品牌区(标题 + 副标题 + 等距插画 `assets/packing-station-hero.svg`),右侧白色登录卡(`.login-card`);
* - 窄屏(≤960px)隐藏品牌区,卡片回到居中;
* - **扫码** 用右上角三角形 `.corner-toggle` 切换(挂在 `.panel-switch` 容器上,和输入框右边缘对齐);
* - 登录与扫码面板定成**同高**,来回切卡片高度/位置不变;扫码面板只留二维码 + 返回入口,不放多余说明;
@ -14,7 +14,7 @@
*/
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import heroUrl from '@/assets/login-hero.svg';
import heroSvg from '@/assets/packing-station-hero.svg?raw';
import { api, ApiError } from '@/api/client';
import { createWechatLoginQr, fetchWechatLoginStatus } from '@/api/web';
import { setSession, type CurrentUser } from '@/composables/useAuth';
@ -244,7 +244,8 @@ onBeforeUnmount(() => {
<section class="brand-pane">
<h1 class="brand-title">云仓视频溯源系统</h1>
<p class="brand-sub">全链路打包视频存证,订单扫码溯源</p>
<img class="brand-hero" :src="heroUrl" alt="仓库货架、摄像头与扫码设备示意图" />
<!-- 插画内联(不是 <img>):`<img>` 里的 SVG 在部分内嵌 Chromium 里不会跑 CSS 动画 -->
<div class="brand-hero" v-html="heroSvg" />
</section>
<section class="form-pane">
@ -342,6 +343,9 @@ onBeforeUnmount(() => {
</div>
</section>
</div>
<!-- 文档站入口:公开页面(后端生成的静态 HTML),未登录也能看 -->
<a class="doc-entry" href="/doc/" target="_blank" rel="noopener">查看看板使用文档 →</a>
</div>
</template>
@ -431,13 +435,19 @@ onBeforeUnmount(() => {
.brand-hero {
display: block;
width: 100%;
max-width: 560px;
max-width: 600px;
margin-top: 6px;
user-select: none;
pointer-events: none;
animation: hero-float 9s ease-in-out infinite;
}
.brand-hero :deep(svg) {
display: block;
width: 100%;
height: auto;
}
@keyframes hero-float {
0%,
100% {
@ -525,4 +535,33 @@ onBeforeUnmount(() => {
animation: none;
}
}
/* 文档站入口(公开,新窗口):固定在右下角,不抢登录卡的视觉 */
.doc-entry {
position: absolute;
right: 24px;
bottom: 20px;
z-index: 2;
padding: 6px 14px;
border: 1px solid rgba(148, 197, 255, 0.35);
border-radius: 999px;
background: rgba(15, 42, 84, 0.5);
color: #cfe1ff;
font-size: 12.5px;
text-decoration: none;
transition: border-color 0.15s ease, color 0.15s ease, background 0.15s ease;
}
.doc-entry:hover {
border-color: rgba(148, 197, 255, 0.7);
background: rgba(37, 99, 235, 0.28);
color: #fff;
}
@media (max-width: 640px) {
.doc-entry {
right: 12px;
bottom: 12px;
}
}
</style>

View File

@ -30,6 +30,9 @@ export default defineConfig({
'/api': { target: backend, changeOrigin: true },
'/health': { target: backend, changeOrigin: true },
'/download': { target: backend, changeOrigin: true },
// 文档站是后端生成并落盘的静态 HTML(/doc/**、/sitemap.txt),不走 SPA
'/doc': { target: backend, changeOrigin: true },
'/sitemap.txt': { target: backend, changeOrigin: true },
},
},
preview: {