Compare commits

..
Author SHA1 Message Date
que01 d923b8cea9 fix: 修复内存限流存储异步签名
CI / Static checks (pull_request) Successful in 6m32s
CI / Production build (pull_request) Successful in 5m53s
CI / API integration (pull_request) Has been cancelled
CI / Browser smoke (pull_request) Has been cancelled
2026-10-23 14:35:55 +08:00
que01 a1b29cedee fix: 忽略空图片并收紧预览警告断言 2026-10-23 14:32:01 +08:00
que01 34504c0b44 fix: 清理后台开发态 React 警告 2026-10-23 14:25:56 +08:00
que01 3af5611da5 fix: 收紧发布环境与任务文件边界 2026-10-23 12:57:15 +08:00
que01 2fe108d66a feat: 支持多实例客户端异常限流 2026-10-23 12:57:06 +08:00
que01 4cd3749806 refactor: 缓存后台请求级权限校验 2026-10-23 12:56:57 +08:00
que01 00aeaa3cb1 refactor: 拆分后台可视化编辑器 2026-10-23 12:56:48 +08:00
que01 b190f2758a docs: 记录后台客户端异常上报限流边界 2026-10-23 12:26:53 +08:00
que01 4d9c84defc fix: 生产环境拒绝占位 SESSION_SECRET 2026-10-23 12:26:45 +08:00
que01 b4e3e86dcd refactor: 拆分模板工作区服务并统一后台访问控制 2026-10-23 12:26:37 +08:00
que01 5051839986 Merge pull request 'test: 修复浏览器回归 fixture 契约漂移' (#2) from fix/browser-contract-fixtures into main
CI / Static checks (push) Successful in 5m45s
CI / API integration (push) Successful in 3m35s
CI / Production build (push) Successful in 5m41s
CI / Browser smoke (push) Has been skipped
Reviewed-on: #2
2026-10-21 08:42:41 +00:00
que01 84522a8908 test: 修复浏览器回归 fixture 契约漂移
CI / Static checks (pull_request) Successful in 5m52s
CI / Production build (pull_request) Successful in 5m35s
CI / Browser smoke (pull_request) Successful in 3m0s
CI / API integration (pull_request) Successful in 3m41s
- 补齐 trust content 与模板版本 fixture 的必填字段\n- mock template-operations/failures 的完整响应结构\n- 补全完整浏览器回归的启动步骤与 CORS 要求\n\n完整回归 32 个用例全部通过。
2026-10-21 16:37:31 +08:00
que01 18bcdbeb00 ci: 增加 PR 浏览器 smoke (#1)
CI / Static checks (push) Successful in 5m49s
CI / Production build (push) Successful in 5m44s
CI / Browser smoke (push) Has been skipped
CI / API integration (push) Successful in 3m36s
2026-10-21 07:49:43 +00:00
que01 040504774d fix: 补齐证据哈希与 runner 安装脚本边界
CI / Static checks (push) Successful in 5m44s
CI / Production build (push) Successful in 5m34s
CI / API integration (push) Successful in 3m44s
2026-10-21 14:43:16 +08:00
que01 1001c43af6 chore: 提供可复现的 CI runner 安装脚本
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Static checks (push) Has been cancelled
2026-10-21 14:41:47 +08:00
que01 121148f6cf fix: 修正 deploy:status 远程脚本执行并检查 runner 2026-10-21 14:41:39 +08:00
que01 a08a2f0f98 ci: 让 main 的必需检查始终上报 2026-10-21 14:41:31 +08:00
que01 669d4a7de6 chore: 收敛模板证据哈希并接入提交钩子 2026-10-21 14:41:23 +08:00
que01 ec0cf78d69 chore: 更新模板完成证据源码哈希
CI / Static checks (push) Successful in 5m41s
CI / Production build (push) Successful in 5m36s
CI / API integration (push) Successful in 3m40s
2026-10-21 14:14:04 +08:00
que01 658c94a4e9 docs: 修正 CI 缓存放行网段与日志级别说明 2026-10-21 14:14:04 +08:00
que01 261a33a5ca chore: 更新模板完成证据源码哈希
CI / Static checks (push) Successful in 11m39s
CI / API integration (push) Successful in 3m46s
CI / Production build (push) Successful in 7m38s
2026-10-21 13:40:47 +08:00
que01 f28332f49a docs: 记录 Gitea Actions 首次完整通过 2026-10-21 13:40:46 +08:00
que01 c33c9cbd63 chore: 更新模板完成证据源码哈希
CI / API integration (push) Successful in 9m44s
CI / Static checks (push) Successful in 11m48s
CI / Production build (push) Successful in 11m40s
2026-10-21 13:03:46 +08:00
que01 b742fc70b5 fix: API 集成测试先构建工作区依赖 2026-10-21 13:03:46 +08:00
que01 6bd91d5ee8 chore: 更新模板完成证据源码哈希
CI / Static checks (push) Successful in 12m18s
CI / Production build (push) Successful in 11m41s
CI / API integration (push) Failing after 4m38s
2026-10-21 12:30:46 +08:00
que01 cdc7b407bc fix: 补充 arm64 Prisma 查询引擎目标 2026-10-21 12:30:46 +08:00
que01 9bfa4bb736 chore: 更新模板完成证据源码哈希 2026-10-21 12:29:45 +08:00
que01 c04ab1ef60 fix: API lint 先构建本包以保证脚本类型可解析 2026-10-21 12:29:44 +08:00
que01 4a6bc42635 chore: 更新模板完成证据源码哈希
CI / Static checks (push) Failing after 6m29s
CI / Production build (push) Has been skipped
CI / API integration (push) Has been skipped
2026-10-21 12:17:12 +08:00
que01 b86c661af5 fix: 视觉夹具校验容忍缺失 npm 构建产物 2026-10-21 12:17:11 +08:00
que01 71c068966e chore: 更新模板完成证据源码哈希 2026-10-21 12:16:00 +08:00
que01 784b9cbac8 fix: 缺少 npm 构建产物时模板产物校验只告警 2026-10-21 12:16:00 +08:00
que01 2325214078 chore: 更新模板完成证据源码哈希 2026-10-21 12:11:19 +08:00
que01 e194e605f9 fix: 修复干净环境 lint 与类型检查依赖构建 2026-10-21 12:10:42 +08:00
que01 82381a5e93 chore: 落地 Gitea Actions CI 门禁
CI / Static checks (push) Failing after 5m7s
CI / Production build (push) Has been skipped
CI / API integration (push) Has been skipped
2026-10-21 12:01:40 +08:00
que01 ec6b0dee3e chore: 增加 Gitea Actions runner 冒烟工作流
CI / Runner smoke (push) Successful in 12s
2026-10-21 12:01:04 +08:00
que01 060bad2df0 docs: 更新生产发布状态
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been skipped
CI / API integration (push) Has been skipped
CI / Taro builds (acheng-campus-food) (push) Has been skipped
CI / Taro builds (atelier-solopreneur) (push) Has been skipped
CI / Taro builds (linjing-editorial) (push) Has been skipped
CI / Browser regression (push) Has been skipped
2026-10-21 11:49:40 +08:00
que01 adcaa12970 feat: 接通后台渲染异常上报与响应契约校验 2026-10-21 11:43:41 +08:00
que01 330d67adc1 docs: 更新生产发布状态
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Taro builds (acheng-campus-food) (push) Has been cancelled
CI / Taro builds (atelier-solopreneur) (push) Has been cancelled
CI / Taro builds (linjing-editorial) (push) Has been cancelled
CI / Browser regression (push) Has been cancelled
2026-10-21 11:06:23 +08:00
que01 737010ea03 fix: 后台外壳容忍异常品牌成员数据
CI / Taro builds (linjing-editorial) (push) Has been cancelled
CI / Browser regression (push) Has been cancelled
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Taro builds (acheng-campus-food) (push) Has been cancelled
CI / Taro builds (atelier-solopreneur) (push) Has been cancelled
2026-10-21 11:03:55 +08:00
que01 ec84988e57 docs: 更新生产发布状态
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Taro builds (acheng-campus-food) (push) Has been cancelled
CI / Taro builds (atelier-solopreneur) (push) Has been cancelled
CI / Taro builds (linjing-editorial) (push) Has been cancelled
CI / Browser regression (push) Has been cancelled
2026-10-21 11:00:37 +08:00
que01 f266bda3a9 test: 覆盖后台渲染异常页面
CI / Taro builds (linjing-editorial) (push) Has been cancelled
CI / Browser regression (push) Has been cancelled
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Taro builds (acheng-campus-food) (push) Has been cancelled
CI / Taro builds (atelier-solopreneur) (push) Has been cancelled
2026-10-21 10:56:51 +08:00
que01 88ab2561bd fix: 增加后台渲染错误边界 2026-10-21 10:56:51 +08:00
que01 98c7701ccd docs: 更新生产发布状态
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Taro builds (acheng-campus-food) (push) Has been cancelled
CI / Taro builds (atelier-solopreneur) (push) Has been cancelled
CI / Taro builds (linjing-editorial) (push) Has been cancelled
CI / Browser regression (push) Has been cancelled
2026-10-21 10:50:14 +08:00
que01 e752a3b7ed docs: 记录发布流程回归覆盖
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Taro builds (acheng-campus-food) (push) Has been cancelled
CI / Taro builds (atelier-solopreneur) (push) Has been cancelled
CI / Taro builds (linjing-editorial) (push) Has been cancelled
CI / Browser regression (push) Has been cancelled
2026-10-21 10:47:38 +08:00
que01 9389235a6c test: 补充发布流程浏览器回归 2026-10-21 10:47:30 +08:00
que01 a293591dba fix: 修正小程序配置表单实例归属 2026-10-21 10:47:30 +08:00
que01 8c5860699f docs: 更新生产发布状态
CI / Taro builds (atelier-solopreneur) (push) Has been cancelled
CI / Taro builds (linjing-editorial) (push) Has been cancelled
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Taro builds (acheng-campus-food) (push) Has been cancelled
CI / Browser regression (push) Has been cancelled
2026-10-21 10:37:36 +08:00
que01 06619a191f refactor: 提示与确认框改用 App 上下文实例
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Taro builds (acheng-campus-food) (push) Has been cancelled
CI / Taro builds (atelier-solopreneur) (push) Has been cancelled
CI / Taro builds (linjing-editorial) (push) Has been cancelled
CI / Browser regression (push) Has been cancelled
2026-10-21 10:34:34 +08:00
que01 3a0099e674 refactor: 迁移 Ant Design 6 弃用的 Alert 与 Space 属性 2026-10-21 10:30:03 +08:00
que01 ca1b873a50 docs: 更新生产发布状态
CI / Taro builds (linjing-editorial) (push) Has been cancelled
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Taro builds (acheng-campus-food) (push) Has been cancelled
CI / Taro builds (atelier-solopreneur) (push) Has been cancelled
CI / Browser regression (push) Has been cancelled
2026-10-21 10:28:25 +08:00
que01 c2bd956b07 docs: 更新项目状态与交付证据
CI / API integration (push) Has been cancelled
CI / Taro builds (acheng-campus-food) (push) Has been cancelled
CI / Taro builds (atelier-solopreneur) (push) Has been cancelled
CI / Taro builds (linjing-editorial) (push) Has been cancelled
CI / Browser regression (push) Has been cancelled
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
2026-10-21 10:22:44 +08:00
que01 b101d169c9 fix: 前置发布构建的 Node 版本门禁 2026-10-21 10:22:44 +08:00
que01 ab17f80607 fix: 修正品牌创建与页面方案交互 2026-10-21 10:22:44 +08:00
que01 6df4e1d72b docs: 补充模板契约发布快照刷新流程
CI / Taro builds (linjing-editorial) (push) Has been cancelled
CI / Browser regression (push) Has been cancelled
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Taro builds (acheng-campus-food) (push) Has been cancelled
CI / Taro builds (atelier-solopreneur) (push) Has been cancelled
2026-10-21 09:02:16 +08:00
que01 cb046a4c27 fix: 支持显式放行遗留字段删除的重发分类 2026-10-21 09:00:05 +08:00
que01 3738be884b chore: 更新模板完成证据源码哈希 2026-10-20 22:25:16 +08:00
que01 193858c727 fix: 增加模板契约发布快照重发工具 2026-10-20 22:14:55 +08:00
que01 ea81c754ed test: 增加发布包运行时预检 2026-10-20 21:24:21 +08:00
que01 16fd827634 fix: 收口发布包完整性与模板契约迁移 2026-10-20 17:59:11 +08:00
que01 38e9d59864 chore: 更新模板完成证据源码哈希 2026-10-20 17:37:34 +08:00
que01 fb072d844b fix: 补齐发布包补丁文件 2026-10-20 17:35:04 +08:00
135 changed files with 6131 additions and 1407 deletions

No files matched your search

@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"scope": "模板完成证据登记,保留命令、日志与产物哈希",
"generatedAt": "2026-10-20T09:00:52.740+00:00",
"generatedAt": "2026-10-23T06:35:59.337Z",
"templates": {
"acheng-campus-food": {
"real-manifest-interaction": {
@@ -256,5 +256,5 @@
}
}
},
"sourceTreeHash": "775950266c3ec796f5af6eafabedae91a1fa6c1d4c71b29ca8d5b589b4846473"
"sourceTreeHash": "f39e31a1959e24c07bf60776a0d3c5f28e5745962ca004301ff304daa1430041"
}
+2
View File
@@ -9,6 +9,8 @@ API_PREFIX=
CORS_ORIGINS=http://localhost:3000
ADMIN_PORT=3000
SESSION_SECRET=replace-with-a-long-random-value
# 单实例使用 memory;多实例部署改用 postgres 并先执行数据库迁移
CLIENT_ERROR_THROTTLE_STORE=memory
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
TEMPLATE_ARTIFACT_ROOT=/var/lib/personal-brand/template-artifacts
SEED_ADMIN_PASSWORD=change-me-now-123
+2
View File
@@ -6,6 +6,8 @@ POSTGRES_PORT=5432
DATABASE_URL=postgresql://personal_brand:replace-with-a-long-database-password@127.0.0.1:5432/personal_brand?schema=public
SESSION_SECRET=replace-with-at-least-32-random-characters
# 单实例使用 memory;多实例部署改用 postgres 并先执行数据库迁移
CLIENT_ERROR_THROTTLE_STORE=memory
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
SEED_ADMIN_PASSWORD=replace-with-a-one-time-initial-password
SEED_MODE=skip
+132
View File
@@ -0,0 +1,132 @@
name: CI
on:
push:
branches: [main]
# 纯文档提交不消耗 2 核 runner;需要状态时用 workflow_dispatch 手动触发。
paths-ignore:
- "**.md"
# PR 不设置 paths-ignore:branch protection 的 required checks 必须始终上报,
# 否则纯文档 PR 会永远等不到状态检查而无法合并。
pull_request:
workflow_dispatch:
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
env:
NODE_VERSION: "24"
PNPM_VERSION: "9.15.0"
jobs:
static:
name: Static checks
runs-on: ubuntu-latest
timeout-minutes: 40
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: ${{ env.PNPM_VERSION }}
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm check
- run: pnpm test:api-routes
- run: pnpm validate:templates
- run: pnpm template:compatibility
- run: pnpm --filter @personal-brand/api exec tsx --test test/template-preview-matrix.test.ts
- run: pnpm template:conformance
- run: pnpm template:doctor
build:
name: Production build
runs-on: ubuntu-latest
timeout-minutes: 60
needs: [static]
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: ${{ env.PNPM_VERSION }}
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm build
- run: pnpm build:admin:preview
- run: pnpm validate:template-release
browser-smoke:
name: Browser smoke
# 只在 PR 和手动触发时运行,避免 main 合并后重复消耗共享生产 runner。
if: github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 30
needs: [static]
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: ${{ env.PNPM_VERSION }}
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: pnpm
- run: pnpm install --frozen-lockfile
- name: Cache Playwright browsers
uses: actions/cache@v4
with:
path: ~/.cache/ms-playwright
key: playwright-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}
- name: Install Chromium
run: pnpm --filter @personal-brand/taro exec playwright install --with-deps chromium
- name: Run PR browser smoke
run: pnpm test:browser:smoke
api:
name: API integration
runs-on: ubuntu-latest
timeout-minutes: 45
needs: [static]
services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: personal_brand
options: >-
--health-cmd "pg_isready -U postgres -d personal_brand"
--health-interval 5s
--health-timeout 5s
--health-retries 12
env:
DATABASE_URL: postgresql://postgres:postgres@postgres:5432/personal_brand
DEFAULT_BRAND_ID: 00000000-0000-0000-0000-000000000001
SESSION_SECRET: ci-integration-session-secret-0123456789abcdef
SEED_ADMIN_PASSWORD: ci-integration-admin-password
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: ${{ env.PNPM_VERSION }}
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: pnpm
- run: pnpm install --frozen-lockfile
- name: Prepare API test env
working-directory: apps/api
run: |
cat > .env <<EOF
DATABASE_URL=$DATABASE_URL
DEFAULT_BRAND_ID=$DEFAULT_BRAND_ID
SESSION_SECRET=$SESSION_SECRET
SEED_ADMIN_PASSWORD=$SEED_ADMIN_PASSWORD
EOF
- run: pnpm --filter @personal-brand/api test:integration
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
# 提交前让模板完成证据的源码哈希跟随当前工作树,避免额外的 chore 提交。
set -e
[ -f scripts/template-evidence-refresh.mjs ] || exit 0
command -v node >/dev/null 2>&1 || exit 0
node scripts/template-evidence-refresh.mjs --stage
-198
View File
@@ -1,198 +0,0 @@
name: CI
on:
pull_request:
push:
branches: [main]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
static:
name: Static checks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9.15.0
- uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm check
- run: pnpm test:api-routes
- run: pnpm audit --prod --registry=https://registry.npmjs.org
- run: pnpm validate:templates
- run: pnpm template:compatibility
- run: pnpm --filter @personal-brand/api exec tsx --test test/template-preview-matrix.test.ts
- run: pnpm template:conformance
- run: pnpm template:doctor
build:
name: Production build
runs-on: ubuntu-latest
needs: [static]
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9.15.0
- uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm build
- run: pnpm build:admin:preview
- run: pnpm validate:template-release
- uses: actions/upload-artifact@v4
with:
name: admin-dist
path: apps/admin/dist
retention-days: 7
api:
name: API integration
runs-on: ubuntu-latest
needs: [static]
services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: personal_brand
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres -d personal_brand"
--health-interval 5s
--health-timeout 5s
--health-retries 12
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/personal_brand
DEFAULT_BRAND_ID: 00000000-0000-0000-0000-000000000001
SESSION_SECRET: ci-integration-session-secret-0123456789abcdef
SEED_ADMIN_PASSWORD: ci-integration-admin-password
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9.15.0
- uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- name: Prepare API test env
working-directory: apps/api
run: |
cat > .env <<EOF
DATABASE_URL=$DATABASE_URL
DEFAULT_BRAND_ID=$DEFAULT_BRAND_ID
SESSION_SECRET=$SESSION_SECRET
SEED_ADMIN_PASSWORD=$SEED_ADMIN_PASSWORD
EOF
- run: pnpm --filter @personal-brand/api test:integration
taro:
name: Taro builds
runs-on: ubuntu-latest
needs: [static]
strategy:
matrix:
template: [acheng-campus-food, atelier-solopreneur, linjing-editorial]
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9.15.0
- uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: TEMPLATE_KEY=acheng-campus-food pnpm --filter @personal-brand/taro build:h5
env:
TEMPLATE_KEY: ${{ matrix.template }}
- run: TEMPLATE_KEY=acheng-campus-food pnpm --filter @personal-brand/taro build:weapp
env:
TEMPLATE_KEY: ${{ matrix.template }}
browser:
name: Browser regression
runs-on: ubuntu-latest
needs: [build, taro]
services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: personal_brand
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres -d personal_brand"
--health-interval 5s
--health-timeout 5s
--health-retries 12
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/personal_brand
DEFAULT_BRAND_ID: 00000000-0000-0000-0000-000000000001
SESSION_SECRET: ci-integration-session-secret-0123456789abcdef
SEED_ADMIN_PASSWORD: ci-integration-admin-password
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9.15.0
- uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm --filter @personal-brand/taro exec playwright install --with-deps chromium
- name: Prepare API test env
working-directory: apps/api
run: |
cat > .env <<EOF
DATABASE_URL=$DATABASE_URL
DEFAULT_BRAND_ID=$DEFAULT_BRAND_ID
SESSION_SECRET=$SESSION_SECRET
SEED_ADMIN_PASSWORD=$SEED_ADMIN_PASSWORD
EOF
- run: pnpm --filter @personal-brand/api db:migrate:deploy
- run: pnpm --filter @personal-brand/api db:seed
- run: pnpm --filter @personal-brand/api test:integration
- name: Start API
run: pnpm --filter @personal-brand/api start > /tmp/api.log 2>&1 &
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/personal_brand
DEFAULT_BRAND_ID: 00000000-0000-0000-0000-000000000001
SESSION_SECRET: browser-ci-session-secret-0123456789abcdef
NODE_ENV: development
- name: Start mini program preview
run: pnpm --filter @personal-brand/taro dev:h5 > /tmp/taro.log 2>&1 &
env:
API_BASE_URL: http://localhost:3001
BRAND_SLUG: default-brand
TEMPLATE_KEY: acheng-campus-food
- name: Start admin
run: pnpm --filter @personal-brand/admin dev > /tmp/admin.log 2>&1 &
env:
VITE_API_BASE_URL: /api
VITE_DEV_API_TARGET: http://localhost:3001
VITE_TEMPLATE_PREVIEW_URL: http://localhost:3002
- name: Wait for services
run: |
curl --retry 30 --retry-delay 1 --retry-connrefused -fsS http://localhost:3001/health
curl --retry 30 --retry-delay 1 --retry-connrefused -fsS http://localhost:3002
curl --retry 30 --retry-delay 1 --retry-connrefused -fsS http://localhost:3000
- run: pnpm --filter @personal-brand/taro exec playwright test --config=playwright.config.ts --reporter=line
env:
ADMIN_URL: http://localhost:3000
+3
View File
@@ -24,6 +24,9 @@ media/
**/.swc/
.codex-tasks/
!.codex-tasks/template-audit-execution/
!.codex-tasks/template-audit-execution/raw/
!.codex-tasks/template-audit-execution/raw/completion-evidence.json
docker-compose.override.yml
.env.production
+106 -17
View File
@@ -1,26 +1,72 @@
# Project Status
最后更新:2026-10-20
最后更新:2026-10-21
## 当前阶段
系统已从“餐饮试点小程序”演进为多模板个人品牌平台。当前分支完成了统一模板契约收口、模板完成证据门禁、管理员登录态撤销和 release 版本一致性修复。
系统已从“餐饮试点小程序”演进为多模板个人品牌平台。当前已完成统一模板契约收口、模板完成证据门禁、品牌与页面方案拆分、管理员登录态撤销和 release 版本一致性修复。
ADR 0033 已落地:
- “表达方式”已从 Admin 源码移除。
- “业务类型”和“页面方案”是两个独立概念。
- 新增“创建品牌”和“页面方案”页面。
- 创建品牌不会自动导入示例内容。
- `linjing-editorial` 只兼容 `doors`,不再兼容 `personal`。
## 当前能力
- NestJS + Fastify API、Prisma PostgreSQL、全局 DTO 校验、统一错误响应和 `requestId`。
- 多品牌 Admin、品牌 membership、角色边界、品牌切换和品牌隔离。
- 创建品牌时按业务类型筛选兼容的页面方案;不兼容组合无法提交。
- 模板包发现、确定性打包、导入、校验、发布、预览、安装、升级和回滚。
- 三套已交付模板:
- `acheng-campus-food@1.0.3`
- `atelier-solopreneur@1.3.2`
- `linjing-editorial@1.0.7`
- 三套已交付模板及其业务类型:
- `acheng-campus-food@1.0.3`:`food`
- `atelier-solopreneur@1.3.2`:`personal`
- `linjing-editorial@1.0.7`:`doors`
- Taro Runtime、Admin 组件预览、真实 manifest 驱动编辑、草稿/发布隔离。
- 发布备注为可选字段;空备注不会写入数据库,也不影响发布、回滚和公开内容。
- 依赖 override 的运行时兼容性通过 `miniprogram-ci` / Jimp / image-size / uuid smoke test 守卫。
- Gitea Actions CI 已在 `oracle_arm` 自托管 runner 上落地,`static` / `build` / `api` 三个 job 已完整通过(run 21);详见 `docs/ci.md`。
- 小程序构建、上传任务状态机、attempt lease 和失败记录。
- Admin/Customer token version:修改 admin 密码或调用 logout 后旧 token 立即失效;无 membership 的账号不会自动获得 owner 权限。
- `visualPresentation` 已进入唯一 `template.json` 契约,旧手写 visual manifest 优先路径已删除。
## 生产状态
当前生产 release:
```text
20261021034700-adcaa12970af
```
该 release 由提交 `adcaa12` 构建,包含后台渲染异常上报(`POST /admin/client-errors`,含去重与限流)、Admin 列表接口运行时响应契约校验,以及前序 release 的创建品牌与页面方案交互修复、Admin 渲染错误边界和异常数据容忍。部署后已完成公开路由健康检查,并确认未登录调用异常上报接口返回 `401 HTTP_401`,说明新接口已进入生产路由。
生产健康检查:
```text
api=online
pm2-autostart=enabled
admin=active
database=running
backups=7
/admin/ 200
/template-preview/ 200
/api/health 200
/media/seed/food-package-02.jpg 200
/admin/client-errors(无登录态) 401
```
生产数据库已应用全部 48 个 Prisma migration,schema 为 up to date。
三个生产品牌的当前发布快照:
| 品牌 | 业务类型 | 页面方案 | 发布版本 |
| ---------------- | ---------- | --------------------------- | ------------ |
| `atelier-studio` | `personal` | `atelier-solopreneur@1.3.2` | `v2 current` |
| `default-brand` | `food` | `acheng-campus-food@1.0.3` | `v2 current` |
| `linjing-doors` | `doors` | `linjing-editorial@1.0.7` | `v3 current` |
## 完成证据
`.codex-tasks/template-audit-execution/raw/completion-evidence.json` 登记四类证据:
@@ -38,6 +84,50 @@ completionStatus=complete
unresolvedIssues=0
```
Admin 浏览器回归新增 `apps/taro/test/browser/brand-creation-and-page-scheme.spec.ts`,覆盖:
- 创建品牌时按业务类型筛选页面方案。
- `personal` 不出现林境页面方案。
- 切换业务类型后清除不兼容的页面方案选择,提交按钮禁用。
- 创建失败时保留用户输入并显示错误。
- 页面方案切换和升级提交正确版本、校验和与冲突保留参数。
- 操作成功后刷新工作区、页面方案选项和升级预览查询。
`apps/taro/test/browser/publication-release.spec.ts` 覆盖内容与发布流程:
- 发布按钮按 readiness 启用;空备注发布提交空 body,不写入 `note`。
- 备注提交前去除首尾空格。
- 发布失败时保留备注与确认弹窗,并显示服务端错误。
- 撤回当前版本、恢复历史版本分别提交正确路径与版本号。
- 小程序配置页从服务端回填设置,只提交用户新输入的私钥。
该回归同时发现并修复了 `MiniAppSettingsTab` 的 `Form` 实例归属问题:表单实例原本在父组件创建、子组件懒挂载,触发 antd `useForm` 未连接警告;现已下沉到配置页自身。
## Admin 渲染错误边界
后台此前没有任何 React error boundary:任一页面在渲染阶段抛错(例如接口返回了形状不符的数据)都会导致整页白屏,用户只能从控制台看到堆栈。现在按两级兜底:
- `Root` 上的整页边界:后台外壳自身渲染失败时显示错误页,提供「重新加载页面」和「返回概览」。
- `Dashboard` 内容区的页面边界:单个业务页面失败时保留侧边栏与顶部导航,提供「重试」和「重新加载页面」,切换路由后自动复位。
- 错误页展示可复制的错误编号,日志侧输出同一编号、堆栈与组件栈,便于把用户反馈和服务器日志对应起来。
- 开发环境额外显示原始错误信息;生产环境不暴露堆栈。
外壳数据不再直接信任接口形状:`apps/admin/src/lib/brand-switcher.ts` 只接受完整成员记录,跳过异常条目并对重复品牌、缺失名称和非字符串品牌名做稳定收敛,避免单条脏数据让整个后台外壳崩溃。错误边界只作为最后一道防线。
`apps/taro/test/browser/admin-error-boundary.spec.ts` 覆盖:
- 品牌成员与品牌名称返回异常结构时,后台外壳仍正常渲染。
- 业务页面数据异常时保留导航,重试仍失败保持错误页,重新加载后恢复。
`apps/admin/test/brand-switcher.test.mjs` 覆盖选项转换的异常条目、非数组、重复品牌、缺失名称与非字符串名称。
## Ant Design 6 弃用项
- `Alert` 统一使用 `title`,`Space` 统一使用 `orientation`。
- 提示与确认框改为 `App.useApp()` 实例,删除静态 `message` 转出口 `components/AdminMessage.ts`。
- `apps/admin/test/antd-deprecations.test.mjs` 作为静态门禁,阻止静态 `message`、`Modal.confirm`、`Alert.message`、`Space.direction` 回流。
- `List` 仍保留:`Listy` 是虚拟滚动组件,API 不兼容,当前仅用于小数据量场景;已记录在 `docs/adr/0034-antd6-static-api-and-list.md`,升级 Ant Design 7 前重新评估。
## 已验证门禁
- `pnpm check`
@@ -46,13 +136,21 @@ unresolvedIssues=0
- `pnpm --filter @personal-brand/api test:integration`
- `miniprogram-ci` override 兼容 smoke test
- `pnpm test:api-client`
- `pnpm test:deploy`
- `pnpm --filter @personal-brand/admin typecheck`
- `pnpm --filter @personal-brand/admin lint`
- `pnpm --filter @personal-brand/admin test`
- `pnpm --filter @personal-brand/admin build`
- `pnpm build`
- `pnpm template:doctor`
- Playwright:
- `brand-creation-and-page-scheme.spec.ts`
- `publication-release.spec.ts`
- `admin-error-boundary.spec.ts`
- `template-preview-media.spec.ts`
- `admin-editor.spec.ts`
本机数据库已应用全部 46 个 Prisma migration,`prisma migrate status` 为 up to date。
发布脚本的 Node 版本门禁已提前到所有构建之前。Node 22 下执行 `pnpm deploy:release` 会立即失败,并给出 Node.js 24 要求提示,不再先执行一轮无用构建。
## 安全审计
@@ -61,17 +159,8 @@ unresolvedIssues=0
- 剩余 8 条为 `miniprogram-ci@2.1.31` 无修复版本的上游 advisory,已在 `pnpm.auditConfig.ignoreGhsas` 和 `docs/security-audit.md` 中显式登记风险、控制措施与跟进条件。
- Taro 官方 peer 仍声明 Vite 4;当前使用 Vite 6.4.3,H5 与 Weapp 实际构建均通过,peer warning 记录在安全审计文档。
## 本机数据状态
- 本机数据库 schema 已 up to date。
- 当前三个新版本已通过模板导入服务导入并发布:
- `acheng-campus-food@1.0.3`
- `atelier-solopreneur@1.3.2`
- `linjing-editorial@1.0.7`
- 既有品牌安装仍锁定各自原版本,需通过 Admin 的显式升级流程升级,不在本任务中静默变更。
## 未决事项
- 生产发布仍需按 `docs/deployment.md` 配置真实环境变量并执行部署后健康检查。
- `miniprogram-ci` 上游发布修复版本后,需要移除对应的 audit ignore、风险登记和本地 patch。
- Gitea SSH 直连仍受 OCI 安全列表限制;当前本机通过 `oracle_arm` ProxyCommand 转发访问,不阻塞业务。
- CI 已加入 audit 和三套模板矩阵构建;后续可继续拆分更细粒度的 smoke/visual matrix。
+42 -38
View File
@@ -33,7 +33,7 @@ import {
} from "./routes.js";
import { LoadingStack } from "../components/LoadingStack.js";
import { AdminMenu } from "../components/AdminMenu.js";
import { adminMessage as message } from "../components/AdminMessage.js";
import { App } from "antd";
import { AdminButton } from "../components/AdminButton.js";
import { AdminSelect } from "../components/AdminSelect.js";
import { AdminLayout } from "../components/AdminLayout.js";
@@ -41,6 +41,8 @@ import { Route, Routes } from "react-router-dom";
import { AdminOverviewRedirect } from "./AdminRouter.js";
import { createBrandRouteElement } from "./route-access.js";
import { Suspense } from "react";
import { AdminErrorBoundary } from "../components/AdminErrorBoundary.js";
import { toBrandDisplayName, toBrandSwitcherOptions } from "../lib/brand-switcher.js";
export function Dashboard({
onLogout,
@@ -51,6 +53,7 @@ export function Dashboard({
role: string;
platformTemplateRole: "none" | "template_admin";
}) {
const { message } = App.useApp();
const navigate = useNavigate();
const location = useLocation();
const brand = useQuery({
@@ -70,6 +73,8 @@ export function Dashboard({
}
};
const page = location.pathname.split("/")[2] || "overview";
const brandName = toBrandDisplayName(brand.data?.name, "当前品牌");
const brandOptions = toBrandSwitcherOptions(memberships.data);
const items = [
{
type: "group" as const,
@@ -106,7 +111,7 @@ export function Dashboard({
<AdminLayout className="admin-shell">
<AdminLayout.Sider className="admin-sider" breakpoint="lg" collapsedWidth={0} width={232}>
<div className="admin-sider-brand">
<BrandMark name={brand.data?.name} />
<BrandMark name={toBrandDisplayName(brand.data?.name, "")} />
<span className="admin-sider-brand-name">品牌工作区</span>
</div>
<AdminMenu
@@ -118,7 +123,7 @@ export function Dashboard({
<AdminLayout className="admin-main">
<AdminLayout.Header className="admin-header">
<div className="admin-header-left">
<span className="admin-header-brand">{brand.data?.name || "当前品牌"}</span>
<span className="admin-header-brand">{brandName}</span>
<span className="admin-header-context">品牌工作区</span>
<StatusTag
tone={role === "owner" ? "info" : "neutral"}
@@ -133,10 +138,7 @@ export function Dashboard({
onChange={(value: string | undefined) => {
if (value) void switchBrand(value);
}}
options={(memberships.data ?? []).map((item) => ({
value: item.brand.id,
label: item.brand.name,
}))}
options={brandOptions}
/>
</div>
<AdminButton type="text" onClick={onLogout}>
@@ -145,37 +147,39 @@ export function Dashboard({
</AdminLayout.Header>
<AdminLayout.Content className="admin-content">
<div className="admin-content-inner">
<Suspense fallback={<LoadingStack />}>
<Routes>
<Route index element={<AdminOverviewRedirect />} />
<Route path="overview" element={<FeatureOverviewPage />} />
<Route path="publication" element={<FeaturePublicationPage />} />
<Route path="brand" element={<FeatureBrandPage />} />
<Route path="trust" element={<FeatureTrustContentPage />} />
<Route path="services" element={<FeatureServicesPage />} />
<Route path="inquiries" element={<FeatureInquiriesPage />} />
<Route path="workspace" element={<FeatureWorkspacePage />} />
{role === "editor" ? null : (
<>
<Route
path="brands"
element={<FeatureBrandsPage canCreate={role === "owner"} />}
/>
<Route
path="brands/new"
element={createBrandRouteElement(role, <FeatureCreateBrandPage />)}
/>
<Route path="page-scheme" element={<FeaturePageSchemePage />} />
<Route path="capabilities" element={<FeatureCapabilitiesPage />} />
<Route path="members" element={<FeatureMembersPage />} />
{platformTemplateRole === "template_admin" ? (
<Route path="templates" element={<FeatureTemplateManagementPage />} />
) : null}
</>
)}
<Route path="*" element={<AdminOverviewRedirect />} />
</Routes>
</Suspense>
<AdminErrorBoundary key={location.pathname}>
<Suspense fallback={<LoadingStack />}>
<Routes>
<Route index element={<AdminOverviewRedirect />} />
<Route path="overview" element={<FeatureOverviewPage />} />
<Route path="publication" element={<FeaturePublicationPage />} />
<Route path="brand" element={<FeatureBrandPage />} />
<Route path="trust" element={<FeatureTrustContentPage />} />
<Route path="services" element={<FeatureServicesPage />} />
<Route path="inquiries" element={<FeatureInquiriesPage />} />
<Route path="workspace" element={<FeatureWorkspacePage />} />
{role === "editor" ? null : (
<>
<Route
path="brands"
element={<FeatureBrandsPage canCreate={role === "owner"} />}
/>
<Route
path="brands/new"
element={createBrandRouteElement(role, <FeatureCreateBrandPage />)}
/>
<Route path="page-scheme" element={<FeaturePageSchemePage />} />
<Route path="capabilities" element={<FeatureCapabilitiesPage />} />
<Route path="members" element={<FeatureMembersPage />} />
{platformTemplateRole === "template_admin" ? (
<Route path="templates" element={<FeatureTemplateManagementPage />} />
) : null}
</>
)}
<Route path="*" element={<AdminOverviewRedirect />} />
</Routes>
</Suspense>
</AdminErrorBoundary>
</div>
</AdminLayout.Content>
</AdminLayout>
+12 -8
View File
@@ -3,13 +3,15 @@ import type { AdminSession } from "@personal-brand/api-client";
import { ChangePassword, Login } from "../features/auth/AuthPages.js";
import { Dashboard } from "./Dashboard.js";
import { AdminRouter } from "./AdminRouter.js";
import { adminMessage as message } from "../components/AdminMessage.js";
import { App } from "antd";
import { createApiClient } from "../lib/api.js";
import { LoadingStack } from "../components/LoadingStack.js";
import { AdminErrorBoundary } from "../components/AdminErrorBoundary.js";
type SessionState = Omit<AdminSession, "authenticated">;
export function Root() {
const { message } = App.useApp();
const [session, setSession] = useState<SessionState | null>(null);
const [loading, setLoading] = useState(true);
@@ -72,12 +74,14 @@ export function Root() {
/>
);
return (
<AdminRouter>
<Dashboard
onLogout={logout}
role={session.role}
platformTemplateRole={session.platformTemplateRole}
/>
</AdminRouter>
<AdminErrorBoundary variant="page">
<AdminRouter>
<Dashboard
onLogout={logout}
role={session.role}
platformTemplateRole={session.platformTemplateRole}
/>
</AdminRouter>
</AdminErrorBoundary>
);
}
@@ -0,0 +1,98 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
import { Button, Result, Space, Typography } from "antd";
import { createApiClient } from "../lib/api.js";
interface AdminErrorBoundaryProps {
children: ReactNode;
variant?: "page" | "content";
}
interface AdminErrorBoundaryState {
error: Error | null;
errorId: string | null;
}
function createErrorId(): string {
return `admin-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
/**
* 后台渲染错误边界:页面级兜底整页,内容级兜底单个业务页面且保留导航。
* React 只支持 class 组件捕获渲染异常,因此这里保留 class 实现。
*/
export class AdminErrorBoundary extends Component<
AdminErrorBoundaryProps,
AdminErrorBoundaryState
> {
override state: AdminErrorBoundaryState = { error: null, errorId: null };
private reportedErrorId: string | null = null;
static getDerivedStateFromError(error: Error): AdminErrorBoundaryState {
return { error, errorId: createErrorId() };
}
override componentDidCatch(error: Error, info: ErrorInfo) {
const errorId = this.state.errorId ?? createErrorId();
console.error("[admin] 页面渲染异常", errorId, error, info.componentStack);
if (this.reportedErrorId === errorId) return;
this.reportedErrorId = errorId;
// 上报失败不能影响错误页本身:只记录到控制台,不抛出、不改状态。
void createApiClient()
.reportAdminClientError({
errorId,
message: error.message.slice(0, 2000) || error.name,
route: `${window.location.pathname}${window.location.search}`.slice(0, 500),
...(info.componentStack ? { componentStack: info.componentStack.slice(0, 20000) } : {}),
})
.catch((reportError: unknown) => {
console.warn("[admin] 渲染异常上报失败", errorId, reportError);
});
}
private reset = () => {
this.setState({ error: null, errorId: null });
};
private reload = () => {
window.location.reload();
};
override render() {
const { error, errorId } = this.state;
if (!error) return this.props.children;
const isPage = this.props.variant === "page";
return (
<Result
status="error"
title="页面渲染出错"
subTitle={
isPage
? "后台页面无法显示。可以重新加载;如果问题持续,请把错误编号提供给管理员。"
: "这个页面无法显示,其他页面仍可正常使用。可以重试或重新加载页面。"
}
extra={
<Space wrap>
{isPage ? null : (
<Button type="primary" onClick={this.reset}>
重试
</Button>
)}
<Button type={isPage ? "primary" : "default"} onClick={this.reload}>
重新加载页面
</Button>
{isPage ? <Button href="/admin/overview">返回概览</Button> : null}
</Space>
}
>
<Typography.Paragraph type="secondary" copyable={{ text: errorId ?? "" }}>
错误编号:{errorId}
</Typography.Paragraph>
{import.meta.env.DEV ? (
<Typography.Paragraph type="secondary">
开发环境错误信息:{error.message}
</Typography.Paragraph>
) : null}
</Result>
);
}
}
@@ -1 +0,0 @@
export { message as adminMessage } from "antd";
+3 -2
View File
@@ -1,5 +1,5 @@
import { CloudUploadOutlined, DeleteOutlined, PictureOutlined } from "@ant-design/icons";
import { Alert, Button, Image, Popconfirm, Spin, Upload, message } from "antd";
import { Alert, App, Button, Image, Popconfirm, Spin, Upload } from "antd";
import { useEffect, useMemo, useState } from "react";
import { apiBaseUrl, authenticatedFetch, createApiClient } from "../lib/api.js";
@@ -12,6 +12,7 @@ interface ImageUrlFieldProps {
}
export function ImageUrlField({ id, value, onChange, placeholder, scope }: ImageUrlFieldProps) {
const { message } = App.useApp();
const imageUrl = typeof value === "string" ? value.trim() : "";
const [uploading, setUploading] = useState(false);
const [storageStatus, setStorageStatus] = useState<
@@ -74,7 +75,7 @@ export function ImageUrlField({ id, value, onChange, placeholder, scope }: Image
<Alert
type={storageStatus === "loading" ? "info" : "warning"}
showIcon
message={
title={
storageStatus === "loading"
? "正在检查媒体存储..."
: storageStatus === "unconfigured"
@@ -76,7 +76,7 @@ export function RecordContentEditor({
<Alert
type="info"
showIcon
message={
title={
source === "offering"
? `正在编辑业务提供项:${recordName}`
: `正在编辑信任内容:${recordName}`
@@ -1,4 +1,4 @@
import { Form, message } from "antd";
import { App, Form } from "antd";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useEffect, useMemo, useState } from "react";
import type { TemplateAdminSection } from "@personal-brand/api-client";
@@ -59,6 +59,7 @@ export function useRecordContentEditorState({
onDraft?: ((values: PresentationValues) => void) | undefined;
onSaved?: (() => void) | undefined;
}) {
const { message } = App.useApp();
const [form] = Form.useForm<PresentationValues>();
const queryClient = useQueryClient();
const [draftValues, setDraftValues] = useState<PresentationValues>(() =>
+3 -1
View File
@@ -1,13 +1,14 @@
import { useState } from "react";
import { App } from "antd";
import { createApiClient } from "../../lib/api.js";
import { BrandMark } from "../../components/BrandMark.js";
import { adminMessage as message } from "../../components/AdminMessage.js";
import { AdminButton } from "../../components/AdminButton.js";
import { AdminCard } from "../../components/AdminCard.js";
import { AdminForm, AdminInput } from "../../components/AdminForm.js";
import type { AdminLoginSession } from "@personal-brand/api-client";
export function Login({ onLogin }: { onLogin: (session: AdminLoginSession) => void }) {
const { message } = App.useApp();
const [form] = AdminForm.useForm();
const [loading, setLoading] = useState(false);
async function submit(values: { username: string; password: string }) {
@@ -52,6 +53,7 @@ export function Login({ onLogin }: { onLogin: (session: AdminLoginSession) => vo
}
export function ChangePassword({ onComplete }: { onComplete: () => void }) {
const { message } = App.useApp();
const [form] = AdminForm.useForm<{
currentPassword: string;
newPassword: string;
+3 -2
View File
@@ -1,4 +1,4 @@
import { Alert, Button, Col, Form, Input, Row, Segmented, message } from "antd";
import { Alert, App, Button, Col, Form, Input, Row, Segmented } from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { Link, useLocation } from "react-router-dom";
@@ -14,6 +14,7 @@ import "./BrandPage.css";
import { useEditorDraft } from "./use-editor-draft.js";
export function BrandPage() {
const { message } = App.useApp();
const location = useLocation();
const initialSelection = location.state as PreviewSelection | undefined;
const [panel, setPanel] = useState("pages");
@@ -219,7 +220,7 @@ export function BrandPage() {
className="brand-page__template-note"
type="info"
showIcon
message={`当前页面方案:${workspace.data?.templateContent?.displayName ?? template.data.name}`}
title={`当前页面方案:${workspace.data?.templateContent?.displayName ?? template.data.name}`}
description={`适用场景:${template.data.serviceCategories.join("、") || "通用品牌展示"}`}
/>
) : null}
@@ -205,7 +205,7 @@ export function ComponentTemplatePreview({
return () => window.removeEventListener("keydown", clear);
}, [onTargetSelected]);
if (!Renderer)
return <Alert type="warning" showIcon message="此模板尚无组件预览,请使用页面预览" />;
return <Alert type="warning" showIcon title="此模板尚无组件预览,请使用页面预览" />;
return (
<div className="component-template-preview-shell">
<div
@@ -1,4 +1,4 @@
import { Alert, Button, Form, Input, Select, Space, Switch, message } from "antd";
import { Alert, App, Button, Form, Input, Select, Space, Switch } from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import type { RuntimeWorkspace } from "@personal-brand/api-client";
@@ -18,6 +18,7 @@ export function InquiryPreviewEditor({
onDraft: (fields: RuntimeInquiryForm["fields"]) => void;
onSaved?: () => void;
}) {
const { message } = App.useApp();
const [form] = Form.useForm<Record<string, unknown>>();
const cache = useQueryClient();
const query = useQuery({
@@ -27,8 +28,9 @@ export function InquiryPreviewEditor({
const record = query.data?.find((item) => item.id === runtime.key);
const field = runtime.fields.find((item) => item.key === fieldKey);
useEffect(() => {
if (field) form.setFieldsValue({ ...field });
}, [fieldKey, runtime.key, form]);
if (!record || !field) return;
form.setFieldsValue({ ...field });
}, [field, fieldKey, form, record, runtime.key]);
const update = (values: Record<string, unknown>) =>
runtime.fields.map((item) => (item.key === fieldKey ? { ...item, ...values } : item));
const save = useMutation({
@@ -59,7 +61,7 @@ export function InquiryPreviewEditor({
return (
<Alert
type="error"
message="表单读取失败"
title="表单读取失败"
action={<Button onClick={() => void query.refetch()}>重试</Button>}
/>
);
@@ -67,10 +69,10 @@ export function InquiryPreviewEditor({
return (
<Alert
type="info"
message={query.isPending ? "正在读取表单" : "未找到对应表单,请刷新后重试"}
title={query.isPending ? "正在读取表单" : "未找到对应表单,请刷新后重试"}
/>
);
if (!field) return <Alert type="warning" message="字段已不存在" />;
if (!field) return <Alert type="warning" title="字段已不存在" />;
return (
<Form<Record<string, unknown>>
form={form}
@@ -1,34 +1,15 @@
import { Alert, Button, Grid, Select, Segmented, Space, Typography } from "antd";
import { useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import type { AdminTemplateContent, RuntimeWorkspace } from "@personal-brand/api-client";
import type { BrandProfile } from "@personal-brand/api-client";
import { Alert, Grid, Segmented, Select, Space } from "antd";
import type {
AdminTemplateContent,
BrandProfile,
RuntimeWorkspace,
} from "@personal-brand/api-client";
import { StatusTag } from "../../components/StatusTag.js";
import { RecordContentEditor } from "../../components/RecordContentEditor.js";
import { TemplatePreview } from "./TemplatePreview.js";
import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js";
import {
resolvePreviewSelection,
previewTrustRecordId,
type PreviewSelection,
type PreviewTarget,
} from "./preview-selection.js";
import { filterSectionsForPreviewTarget } from "../../lib/presentation/presentation-bindings.js";
import "./PresentationEditor.css";
import { useEditorDraft } from "./use-editor-draft.js";
import {
usePresentationRecordQueries,
useBrandPresentationSections,
useBrandSaveMutation,
useBrandPresentationForm,
useBrandPreviewDraft,
} from "./presentation-editor-state.js";
import { useRecordPreview } from "./presentation-editor-record-preview.js";
import type { RecordDraft } from "./presentation-editor-record-preview.js";
import { pageTitle, previewTargetSource, trustSection } from "./presentation-editor-helpers.js";
import { useDraftWorkspace } from "./use-draft-workspace.js";
import { PresentationFormPanel } from "./PresentationFormPanel.js";
import type { PreviewSelection } from "./preview-selection.js";
import { usePresentationEditorController } from "./presentation-editor-controller.js";
import { PresentationEditorInspector } from "./PresentationEditorInspector.js";
import { PresentationEditorPreview } from "./PresentationEditorPreview.js";
interface PresentationEditorProps {
templateContent: AdminTemplateContent | null | undefined;
@@ -49,254 +30,14 @@ export function PresentationEditor({
error,
initialSelection,
}: PresentationEditorProps) {
const queryClient = useQueryClient();
const navigate = useNavigate();
const breakpoints = Grid.useBreakpoint();
const [activePage, setActivePage] = useState<string>();
const [selection, setSelection] = useState<PreviewSelection | undefined>(initialSelection);
const [hasInitializedSelection, setHasInitializedSelection] = useState(Boolean(initialSelection));
const [detailOfferingId, setDetailOfferingId] = useState<string>();
const [recordDraft, setRecordDraft] = useState<RecordDraft>();
const [inquiryDraft, setInquiryDraft] =
useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>();
const [brandDirty, setBrandDirty] = useState(false);
const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft);
const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand");
const sections = useBrandPresentationSections(templateContent);
const pageOptions = useMemo(() => {
const pages = new Map<string, string>();
for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label);
for (const section of templateContent?.admin.sections ?? []) {
const navigation = templateContent?.navigation.find((item) => item.page === section.page);
if (!pages.has(section.page))
pages.set(section.page, navigation?.label ?? pageTitle(section.page));
}
return [...pages].map(([value, label]) => ({ value, label }));
}, [templateContent]);
const selectedPage = pageOptions.some((item) => item.value === activePage)
? activePage
: pageOptions[0]?.value;
const visibleSections = sections.filter((section) => section.page === selectedPage);
const recordSections = useMemo(
() =>
(templateContent?.trustContentTypes ?? [])
.filter((item) => item.pages?.includes(selectedPage ?? ""))
.map((item) => trustSection(item, selectedPage ?? "home")),
[templateContent, selectedPage],
);
const visibleTargets = useMemo<PreviewTarget[]>(
() =>
[...(templateContent?.admin.sections ?? []), ...recordSections]
.filter(
(section) =>
section.page === selectedPage &&
(selectedPage !== "detail" || section.target === "brand"),
)
.flatMap((section) =>
(section.previewTargets ?? []).map((target) => ({
...target,
page: section.page,
source: previewTargetSource(section, target.key),
...(section.key.startsWith("trust:") ? { trustType: section.key.slice(6) } : {}),
})),
)
.concat(
selectedPage === "inquiry" && inquiryRuntime
? inquiryRuntime.fields.map((field) => ({
key: `inquiry-field:${field.key}`,
label: field.label,
page: "inquiry",
source: "inquiry" as const,
}))
: [],
),
[templateContent, selectedPage, recordSections, inquiryRuntime],
);
const activeTarget = selection?.targetKey;
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
const selectedSection = [...(templateContent?.admin.sections ?? []), ...recordSections].find(
(section) =>
section.page === selectedPage &&
section.previewTargets?.some((target) => target.key === selectedTarget?.key),
);
const selectedRecordSource =
selectedTarget?.source === "offering" || selectedTarget?.source === "trust"
? selectedTarget.source
: undefined;
const { offeringsQuery, trustQuery, selectedRecord } = usePresentationRecordQueries(
selectedRecordSource,
selection?.recordId,
);
const editableSections = filterSectionsForPreviewTarget(
visibleSections.filter((section) =>
section.fields.some((field) => field.binding.startsWith("brand.")),
),
selectedTarget?.key,
);
const recordSection = useMemo(
() =>
selectedSection && selection?.targetKey
? {
...selectedSection,
fields: selectedSection.fields.filter(
(field) => field.previewTarget === selection.targetKey,
),
}
: undefined,
[selectedSection, selection?.targetKey],
);
const handleTargetSelected = useCallback(
(next?: PreviewSelection) => {
const select = () =>
setSelection(
next
? resolvePreviewSelection(
next.targetKey,
next.recordId,
visibleTargets,
selectedPage ?? "home",
)
: undefined,
);
if (recordDraft || inquiryDraft)
guardDraft(() => {
setInquiryDraft(undefined);
setRecordDraft(undefined);
select();
});
else select();
},
[visibleTargets, selectedPage, recordDraft, inquiryDraft, guardDraft],
);
const relatedTargets = [
...(templateContent?.admin.sections ?? [])
.filter((section) => section.page === selectedPage && section.target !== "brand")
.map((section) => section.target),
...((templateContent?.trustContentTypes ?? []).some((item) =>
item.pages?.includes(selectedPage ?? ""),
)
? ["trust"]
: []),
];
const pageLinks = [...new Set(relatedTargets)].flatMap((target) =>
target === "trust"
? (templateContent?.trustContentTypes ?? [])
.filter((item) => item.pages?.includes(selectedPage ?? ""))
.map((item) => ({
target: `trust:${item.type}`,
label: `编辑${item.label}`,
}))
: [
{
target,
label: (
{ offering: "管理此页展示的业务内容", inquiry: "管理此页的咨询表单" } as Record<
string,
string
>
)[target],
},
],
);
const relevantPageLinks = selectedSection
? pageLinks.filter((item) => {
if (item.target.startsWith("trust:")) return selectedSection.target === "trust";
return item.target === selectedSection.target;
})
: pageLinks;
const formState = useBrandPresentationForm({ brand, config, sections });
const { form, initialValues } = formState;
const save = useBrandSaveMutation({
...formState,
brand,
config,
sections,
queryClient,
onSaved: () => setBrandDirty(false),
});
useEffect(() => {
const initialPage =
typeof initialSelection === "object" && "page" in initialSelection
? String(initialSelection.page)
: undefined;
if (initialPage) {
setActivePage(
pageOptions.some((item) => item.value === initialPage)
? initialPage
: pageOptions[0]?.value,
);
return;
}
if (!activePage && pageOptions.length) setActivePage(pageOptions[0]?.value);
}, [activePage, initialSelection, pageOptions]);
useEffect(() => {
if (hasInitializedSelection) return;
if (!pageOptions.length) return;
if (!initialSelection) return;
const requestedPage =
typeof initialSelection === "object" && "page" in initialSelection
? String(initialSelection.page)
: undefined;
const resolvedPage =
requestedPage && pageOptions.some((item) => item.value === requestedPage)
? requestedPage
: (pageOptions[0]?.value ?? "home");
setSelection(
resolvePreviewSelection(
initialSelection.targetKey,
initialSelection.recordId,
visibleTargets,
resolvedPage,
),
);
setActivePage(resolvedPage);
setHasInitializedSelection(true);
}, [hasInitializedSelection, initialSelection, pageOptions, selectedPage, visibleTargets]);
useEffect(() => {
if (!initialSelection) setSelection(undefined);
}, [initialSelection, selectedPage, templateContent?.displayName]);
useEffect(() => {
if (!selection?.recordId) return;
const records =
selectedTarget?.source === "trust"
? previewWorkspace?.trustItems
: previewWorkspace?.offerings;
if (records && !records.some((item) => item.id === selection.recordId)) setSelection(undefined);
}, [
previewWorkspace?.offerings,
previewWorkspace?.trustItems,
selectedTarget?.source,
selection,
]);
useEffect(
() => setRecordDraft(undefined),
[selection?.targetKey, selection?.recordId, selectedPage],
);
const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({
brand,
config,
sections,
form,
onDirty: () => setBrandDirty(true),
});
const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection });
useEffect(() => resetPreview(), [config, initialValues, resetPreview]);
const draftWorkspace = useDraftWorkspace({
previewWorkspace,
previewBrand,
inquiryRuntime,
inquiryDraft,
recordDraft,
selectedRecord,
recordSection,
recordPreview,
const controller = usePresentationEditorController({
templateContent,
previewWorkspace,
config,
brand,
...(initialSelection ? { initialSelection } : {}),
});
const selectedDetailOfferingId =
detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId)
? detailOfferingId
: draftWorkspace?.offerings[0]?.id;
return (
<section className="presentation-editor" aria-labelledby="presentation-editor-title">
@@ -311,12 +52,12 @@ export function PresentationEditor({
</div>
{templateContent ? <StatusTag tone="info" label={templateContent.displayName} /> : null}
</div>
{loading ? <Alert type="info" showIcon message="正在读取当前页面方案的编辑项目" /> : null}
{loading ? <Alert type="info" showIcon title="正在读取当前页面方案的编辑项目" /> : null}
{error ? (
<Alert type="warning" showIcon message="页面方案编辑项目读取失败,请刷新后重试。" />
<Alert type="warning" showIcon title="页面方案编辑项目读取失败,请刷新后重试。" />
) : null}
{!loading && !error && !templateContent ? (
<Alert type="warning" showIcon message="当前页面方案暂未提供可编辑的页面内容。" />
<Alert type="warning" showIcon title="当前页面方案暂未提供可编辑的页面内容。" />
) : null}
{templateContent ? (
<>
@@ -324,306 +65,33 @@ export function PresentationEditor({
{breakpoints.xs ? (
<Select
aria-label="选择小程序页面"
value={selectedPage}
options={pageOptions}
onChange={(value) =>
guardDraft(() => {
setBrandDirty(false);
form.setFieldsValue(initialValues);
resetPreview();
setRecordDraft(undefined);
setInquiryDraft(undefined);
setActivePage(value);
})
}
value={controller.selectedPage ?? null}
options={controller.pageOptions}
onChange={controller.selectPage}
className="admin-field-w-2xl"
/>
) : (
<Segmented
value={selectedPage}
options={pageOptions}
onChange={(value) =>
guardDraft(() => {
setBrandDirty(false);
form.setFieldsValue(initialValues);
resetPreview();
setRecordDraft(undefined);
setInquiryDraft(undefined);
setActivePage(String(value));
})
}
value={controller.selectedPage ?? null}
options={controller.pageOptions}
onChange={(value) => controller.selectPage(String(value))}
/>
)}
</Space>
<div className="presentation-editor__workspace">
<div className="presentation-editor__preview">
<h3 className="admin-section-title admin-flush">页面预览</h3>
{selectedPage === "detail" && draftWorkspace?.offerings.length ? (
<Select
aria-label="选择详情页业务内容"
className="admin-block admin-offset-bottom-sm"
value={selectedDetailOfferingId}
options={draftWorkspace.offerings.map((item) => ({
value: item.id,
label: item.name,
}))}
onChange={(value) => {
setDetailOfferingId(value);
setSelection(undefined);
}}
/>
) : null}
<TemplatePreview
brand={previewBrand}
{...(draftWorkspace ? { workspace: draftWorkspace } : {})}
page={selectedPage ?? "home"}
{...(selectedPage === "detail" && selectedDetailOfferingId
? { offeringId: selectedDetailOfferingId }
: {})}
{...(activeTarget ? { targetKey: activeTarget } : {})}
{...(selection ? { selection } : {})}
targets={visibleTargets}
onTargetSelected={handleTargetSelected}
/>
</div>
<aside className="presentation-editor__outline" aria-label="页面区域">
<h3 className="admin-section-title admin-flush">页面区域</h3>
<p className="admin-section-description">选择区域,编辑对应内容</p>
{visibleTargets.length ? (
<Space className="presentation-editor__regions admin-offset-top" wrap>
{visibleTargets.map((target) => (
<Button
key={target.key}
className={
visibleTargets.some((parent) => parent.children?.includes(target.key))
? "is-child-region"
: ""
}
aria-pressed={activeTarget === target.key}
type={activeTarget === target.key ? "primary" : "default"}
onClick={() => {
const recordId =
target.source === "offering"
? selectedPage === "detail"
? selectedDetailOfferingId
: draftWorkspace?.offerings[0]?.id
: target.source === "trust"
? previewTrustRecordId(
draftWorkspace?.trustItems ?? [],
target.trustType,
)
: undefined;
handleTargetSelected({
targetKey: target.key,
...(recordId ? { recordId } : {}),
});
}}
>
{target.label}
</Button>
))}
</Space>
) : null}
{!visibleTargets.length ? (
<Typography.Text type="secondary">此页为动态预览</Typography.Text>
) : null}
</aside>
<div className="presentation-editor__inspector">
<h3 className="admin-section-title admin-flush">
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
</h3>
<StatusTag
tone={
save.isError
? "error"
: save.isPending || brandDirty || recordDraft || inquiryDraft
? "warning"
: "neutral"
}
label={
save.isPending
? "正在保存"
: save.isError
? "保存失败,请重试"
: brandDirty || recordDraft || inquiryDraft
? "有未保存修改"
: "草稿已同步"
}
/>
{selectedPage === "detail" && !selectedTarget ? (
<Alert
type="info"
showIcon
message="详情页由所选业务内容动态生成"
description="选择业务内容预览详情,记录内容在业务提供项中维护;公共标题和按钮文案可从左侧区域列表配置,对全部详情生效。"
action={
<Button
onClick={() => {
void navigate("/admin/services");
}}
>
管理业务内容
</Button>
}
/>
) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? (
<InquiryPreviewEditor
runtime={
draftWorkspace?.inquiryForms.find((item) => item.key === inquiryRuntime.key) ??
inquiryRuntime
}
fieldKey={activeTarget.slice("inquiry-field:".length)}
onDraft={setInquiryDraft}
onSaved={() => setInquiryDraft(undefined)}
/>
) : selectedTarget?.composite ? (
<Alert
type="info"
showIcon
message="这是一个组合区域"
description={
<Space wrap>
{(selectedTarget.children ?? []).map((childKey) => {
const child = visibleTargets.find((item) => item.key === childKey);
if (!child) return null;
return (
<Button
key={child.key}
onClick={() => {
const recordId =
child.source === "offering"
? selectedPage === "detail"
? selectedDetailOfferingId
: draftWorkspace?.offerings[0]?.id
: child.source === "trust"
? previewTrustRecordId(
draftWorkspace?.trustItems ?? [],
child.trustType,
)
: undefined;
handleTargetSelected({
targetKey: child.key,
...(recordId ? { recordId } : {}),
});
}}
>
编辑{child.label}
</Button>
);
})}
</Space>
}
/>
) : selectedRecordSource && selection?.recordId && selectedSection ? (
selectedRecord ? (
<RecordContentEditor
key={`${selectedRecordSource}:${selectedRecord.id}:${selectedSection.key}`}
source={selectedRecordSource}
record={selectedRecord}
section={recordSection!}
context="visual"
onDraft={(values) =>
setRecordDraft({
source: selectedRecordSource,
id: selectedRecord.id,
values,
})
}
onSaved={() => setRecordDraft(undefined)}
/>
) : (
<Alert
type={
(
selectedRecordSource === "offering"
? offeringsQuery.isError
: trustQuery.isError
)
? "error"
: "info"
}
message={
(
selectedRecordSource === "offering"
? offeringsQuery.isError
: trustQuery.isError
)
? "内容读取失败"
: (
selectedRecordSource === "offering"
? offeringsQuery.isSuccess
: trustQuery.isSuccess
)
? "对应内容已不存在,请重新选择页面中的区域"
: "正在读取对应内容"
}
{...((
selectedRecordSource === "offering"
? offeringsQuery.isError
: trustQuery.isError
)
? {
action: (
<Button
size="small"
onClick={() => {
if (selectedRecordSource === "offering")
void offeringsQuery.refetch();
else void trustQuery.refetch();
}}
>
重试
</Button>
),
}
: {})}
/>
)
) : selectedRecordSource ? (
<Alert
type="info"
showIcon
message="此区域尚未配置内容"
description="创建并启用对应内容后,即可在预览中点选编辑。"
action={
<Button
onClick={() =>
guardDraft(() => {
void navigate(
selectedRecordSource === "trust"
? `/admin/trust?type=${encodeURIComponent(selectedTarget?.trustType ?? "")}`
: "/admin/services",
);
})
}
>
配置此区域内容
</Button>
}
/>
) : !selectedTarget ? (
<div className="presentation-editor__empty">
<h3 className="admin-subhead">选择要编辑的区域</h3>
<p className="admin-section-description">
点击预览中的内容,或使用区域列表,查看并修改对应字段。
</p>
</div>
) : (
<PresentationFormPanel
form={form}
initialValues={initialValues}
editableSections={editableSections}
relevantPageLinks={relevantPageLinks}
selectedTarget={selectedTarget}
save={{
error: save.error,
isPending: save.isPending,
mutate: (values) => save.mutate(values),
}}
onValuesChange={handleValuesChange}
/>
)}
</div>
<PresentationEditorPreview
previewBrand={controller.previewBrand}
draftWorkspace={controller.draftWorkspace}
selectedPage={controller.selectedPage}
selectedDetailOfferingId={controller.selectedDetailOfferingId}
activeTarget={controller.activeTarget}
selection={controller.selection}
visibleTargets={controller.visibleTargets}
onSelectDetailOffering={controller.selectDetailOffering}
onTargetSelected={controller.handleTargetSelected}
onSelectPreviewTarget={controller.selectPreviewTarget}
/>
<PresentationEditorInspector controller={controller} />
</div>
</>
) : null}
@@ -0,0 +1,196 @@
import { Alert, Button, Space } from "antd";
import { StatusTag } from "../../components/StatusTag.js";
import { RecordContentEditor } from "../../components/RecordContentEditor.js";
import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js";
import { PresentationFormPanel } from "./PresentationFormPanel.js";
import { pageTitle } from "./presentation-editor-helpers.js";
import type { PresentationEditorController } from "./presentation-editor-controller.js";
export function PresentationEditorInspector({
controller,
}: {
controller: PresentationEditorController;
}) {
const {
selectedPage,
selectedTarget,
activeTarget,
selection,
selectedSection,
selectedRecordSource,
selectedRecord,
recordSection,
editableSections,
relevantPageLinks,
inquiryRuntime,
draftWorkspace,
form,
initialValues,
save,
offeringsQuery,
trustQuery,
recordDraft,
inquiryDraft,
brandDirty,
guardDraft,
} = controller;
const recordQuery = selectedRecordSource === "trust" ? trustQuery : offeringsQuery;
return (
<div className="presentation-editor__inspector">
<h3 className="admin-section-title admin-flush">
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
</h3>
<StatusTag
tone={
save.isError
? "error"
: save.isPending || brandDirty || recordDraft || inquiryDraft
? "warning"
: "neutral"
}
label={
save.isPending
? "正在保存"
: save.isError
? "保存失败,请重试"
: brandDirty || recordDraft || inquiryDraft
? "有未保存修改"
: "草稿已同步"
}
/>
{selectedPage === "detail" && !selectedTarget ? (
<Alert
type="info"
showIcon
title="详情页由所选业务内容动态生成"
description="选择业务内容预览详情,记录内容在业务提供项中维护;公共标题和按钮文案可从左侧区域列表配置,对全部详情生效。"
action={
<Button
onClick={() => {
void controller.navigate("/admin/services");
}}
>
管理业务内容
</Button>
}
/>
) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? (
<InquiryPreviewEditor
runtime={
draftWorkspace?.inquiryForms.find((item) => item.key === inquiryRuntime.key) ??
inquiryRuntime
}
fieldKey={activeTarget.slice("inquiry-field:".length)}
onDraft={controller.setInquiryDraft}
onSaved={() => controller.setInquiryDraft(undefined)}
/>
) : selectedTarget?.composite ? (
<Alert
type="info"
showIcon
title="这是一个组合区域"
description={
<Space wrap>
{(selectedTarget.children ?? []).map((childKey) => {
const child = visibleTarget(childKey, controller);
if (!child) return null;
return (
<Button key={child.key} onClick={() => controller.selectPreviewTarget(child)}>
编辑{child.label}
</Button>
);
})}
</Space>
}
/>
) : selectedRecordSource && selection?.recordId && selectedSection ? (
selectedRecord ? (
<RecordContentEditor
key={`${selectedRecordSource}:${selectedRecord.id}:${selectedSection.key}`}
source={selectedRecordSource}
record={selectedRecord}
section={recordSection!}
context="visual"
onDraft={(values) =>
controller.setRecordDraft({
source: selectedRecordSource,
id: selectedRecord.id,
values,
})
}
onSaved={() => controller.setRecordDraft(undefined)}
/>
) : (
<Alert
type={recordQuery.isError ? "error" : "info"}
title={
recordQuery.isError
? "内容读取失败"
: recordQuery.isSuccess
? "对应内容已不存在,请重新选择页面中的区域"
: "正在读取对应内容"
}
{...(recordQuery.isError
? {
action: (
<Button size="small" onClick={() => void recordQuery.refetch()}>
重试
</Button>
),
}
: {})}
/>
)
) : selectedRecordSource ? (
<Alert
type="info"
showIcon
title="此区域尚未配置内容"
description="创建并启用对应内容后,即可在预览中点选编辑。"
action={
<Button
onClick={() =>
guardDraft(() => {
void controller.navigate(
selectedRecordSource === "trust"
? `/admin/trust?type=${encodeURIComponent(selectedTarget?.trustType ?? "")}`
: "/admin/services",
);
})
}
>
配置此区域内容
</Button>
}
/>
) : !selectedTarget ? (
<div className="presentation-editor__empty">
<h3 className="admin-subhead">选择要编辑的区域</h3>
<p className="admin-section-description">
点击预览中的内容,或使用区域列表,查看并修改对应字段。
</p>
</div>
) : (
<PresentationFormPanel
key={`${selectedPage}:${selectedTarget.key}`}
form={form}
initialValues={initialValues}
editableSections={editableSections}
relevantPageLinks={relevantPageLinks}
selectedTarget={selectedTarget}
save={{
error: save.error,
isPending: save.isPending,
mutate: (values) => save.mutate(values),
}}
onValuesChange={controller.handleValuesChange}
/>
)}
</div>
);
}
function visibleTarget(key: string, controller: PresentationEditorController) {
return controller.visibleTargets.find((item) => item.key === key);
}
@@ -0,0 +1,88 @@
import { Button, Select, Space, Typography } from "antd";
import type { BrandProfile, RuntimeWorkspace } from "@personal-brand/api-client";
import { TemplatePreview } from "./TemplatePreview.js";
import type { PreviewSelection, PreviewTarget } from "./preview-selection.js";
interface PresentationEditorPreviewProps {
previewBrand: BrandProfile;
draftWorkspace?: RuntimeWorkspace | undefined;
selectedPage: string | undefined;
selectedDetailOfferingId: string | undefined;
activeTarget: string | undefined;
selection: PreviewSelection | undefined;
visibleTargets: PreviewTarget[];
onSelectDetailOffering: (id: string) => void;
onTargetSelected: (next?: PreviewSelection) => void;
onSelectPreviewTarget: (target: PreviewTarget) => void;
}
export function PresentationEditorPreview({
previewBrand,
draftWorkspace,
selectedPage,
selectedDetailOfferingId,
activeTarget,
selection,
visibleTargets,
onSelectDetailOffering,
onTargetSelected,
onSelectPreviewTarget,
}: PresentationEditorPreviewProps) {
return (
<>
<div className="presentation-editor__preview">
<h3 className="admin-section-title admin-flush">页面预览</h3>
{selectedPage === "detail" && draftWorkspace?.offerings.length ? (
<Select
aria-label="选择详情页业务内容"
className="admin-block admin-offset-bottom-sm"
value={selectedDetailOfferingId ?? null}
options={draftWorkspace.offerings.map((item) => ({
value: item.id,
label: item.name,
}))}
onChange={onSelectDetailOffering}
/>
) : null}
<TemplatePreview
brand={previewBrand}
{...(draftWorkspace ? { workspace: draftWorkspace } : {})}
page={selectedPage ?? "home"}
{...(selectedPage === "detail" && selectedDetailOfferingId
? { offeringId: selectedDetailOfferingId }
: {})}
{...(activeTarget ? { targetKey: activeTarget } : {})}
{...(selection ? { selection } : {})}
targets={visibleTargets}
onTargetSelected={onTargetSelected}
/>
</div>
<aside className="presentation-editor__outline" aria-label="页面区域">
<h3 className="admin-section-title admin-flush">页面区域</h3>
<p className="admin-section-description">选择区域,编辑对应内容</p>
{visibleTargets.length ? (
<Space className="presentation-editor__regions admin-offset-top" wrap>
{visibleTargets.map((target) => (
<Button
key={target.key}
className={
visibleTargets.some((parent) => parent.children?.includes(target.key))
? "is-child-region"
: ""
}
aria-pressed={activeTarget === target.key}
type={activeTarget === target.key ? "primary" : "default"}
onClick={() => onSelectPreviewTarget(target)}
>
{target.label}
</Button>
))}
</Space>
) : null}
{!visibleTargets.length ? (
<Typography.Text type="secondary">此页为动态预览</Typography.Text>
) : null}
</aside>
</>
);
}
@@ -89,7 +89,7 @@ export function PresentationFormPanel({
type="info"
showIcon
className="admin-offset-bottom-lg"
message="这个页面还有关联内容"
title="这个页面还有关联内容"
description={
<Space wrap>
{relevantPageLinks.map((item) => (
@@ -124,7 +124,7 @@ export function TemplatePreview({
<Alert
type="warning"
showIcon
message="页面预览暂不可用"
title="页面预览暂不可用"
description="请确认模板预览资源已构建并发布,或本地预览服务正在运行。"
/>
);
@@ -146,11 +146,11 @@ export function TemplatePreview({
<>
{!ready && !error ? (
<div className="template-preview__loading">
<Spin tip="正在加载页面预览" />
<Spin description="正在加载页面预览" />
</div>
) : null}
{error ? (
<Alert type="error" showIcon message="页面预览加载失败" description={error} />
<Alert type="error" showIcon title="页面预览加载失败" description={error} />
) : null}
<iframe
key={url}
@@ -0,0 +1,416 @@
import { useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate, type NavigateFunction } from "react-router-dom";
import type {
AdminTemplateContent,
BrandProfile,
Offering,
RuntimeWorkspace,
TemplateAdminSection,
TrustContent,
} from "@personal-brand/api-client";
import type { FormInstance } from "antd";
import { filterSectionsForPreviewTarget } from "../../lib/presentation/presentation-bindings.js";
import type { PresentationValues } from "../../lib/presentation/presentation-bindings.js";
import {
resolvePreviewSelection,
previewTrustRecordId,
type PreviewSelection,
type PreviewTarget,
} from "./preview-selection.js";
import { useEditorDraft } from "./use-editor-draft.js";
import {
useBrandPresentationForm,
useBrandPresentationSections,
useBrandPreviewDraft,
useBrandSaveMutation,
usePresentationRecordQueries,
} from "./presentation-editor-state.js";
import { useRecordPreview, type RecordDraft } from "./presentation-editor-record-preview.js";
import { pageTitle, previewTargetSource, trustSection } from "./presentation-editor-helpers.js";
import { useDraftWorkspace } from "./use-draft-workspace.js";
export interface PresentationEditorControllerInput {
templateContent: AdminTemplateContent | null | undefined;
previewWorkspace?: RuntimeWorkspace | undefined;
config: Record<string, unknown> | null | undefined;
brand: BrandProfile;
initialSelection?: PreviewSelection;
}
export interface PresentationRecordQuery {
isError: boolean;
isSuccess: boolean;
refetch: () => unknown;
}
export interface PresentationEditorController {
pageOptions: { value: string; label: string }[];
selectedPage: string | undefined;
visibleTargets: PreviewTarget[];
selectedTarget: PreviewTarget | undefined;
selectedSection: TemplateAdminSection | undefined;
selectedRecordSource: "offering" | "trust" | undefined;
selectedRecord: Offering | TrustContent | undefined;
recordSection: TemplateAdminSection | undefined;
editableSections: TemplateAdminSection[];
relevantPageLinks: { target: string; label: string | undefined }[];
inquiryRuntime: RuntimeWorkspace["inquiryForms"][number] | undefined;
draftWorkspace: RuntimeWorkspace | undefined;
previewBrand: BrandProfile;
selectedDetailOfferingId: string | undefined;
form: FormInstance<PresentationValues>;
initialValues: PresentationValues;
save: {
error: unknown;
isError: boolean;
isPending: boolean;
mutate: (values: PresentationValues) => void;
};
offeringsQuery: PresentationRecordQuery;
trustQuery: PresentationRecordQuery;
recordDraft: RecordDraft | undefined;
inquiryDraft: RuntimeWorkspace["inquiryForms"][number]["fields"] | undefined;
brandDirty: boolean;
selection: PreviewSelection | undefined;
activeTarget: string | undefined;
guardDraft: (action: () => void) => void;
selectPage: (page: string) => void;
selectDetailOffering: (id: string) => void;
selectPreviewTarget: (target: PreviewTarget) => void;
handleTargetSelected: (next?: PreviewSelection) => void;
setRecordDraft: (draft: RecordDraft | undefined) => void;
setInquiryDraft: (fields: RuntimeWorkspace["inquiryForms"][number]["fields"] | undefined) => void;
handleValuesChange: (changed: PresentationValues, allValues: PresentationValues) => void;
navigate: NavigateFunction;
}
/**
* PresentationEditor 的状态与派生数据集中在此处。
* 视图组件只负责渲染,避免页面组件继续膨胀。
*/
export function usePresentationEditorController({
templateContent,
previewWorkspace,
config,
brand,
initialSelection,
}: PresentationEditorControllerInput): PresentationEditorController {
const queryClient = useQueryClient();
const navigate = useNavigate();
const [activePage, setActivePage] = useState<string>();
const [selection, setSelection] = useState<PreviewSelection | undefined>(initialSelection);
const [hasInitializedSelection, setHasInitializedSelection] = useState(Boolean(initialSelection));
const [detailOfferingId, setDetailOfferingId] = useState<string>();
const [recordDraft, setRecordDraft] = useState<RecordDraft>();
const [inquiryDraft, setInquiryDraft] =
useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>();
const [brandDirty, setBrandDirty] = useState(false);
const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft);
const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand");
const sections = useBrandPresentationSections(templateContent);
const pageOptions = useMemo(() => {
const pages = new Map<string, string>();
for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label);
for (const section of templateContent?.admin.sections ?? []) {
const navigation = templateContent?.navigation.find((item) => item.page === section.page);
if (!pages.has(section.page))
pages.set(section.page, navigation?.label ?? pageTitle(section.page));
}
return [...pages].map(([value, label]) => ({ value, label }));
}, [templateContent]);
const selectedPage = pageOptions.some((item) => item.value === activePage)
? activePage
: pageOptions[0]?.value;
const visibleSections = sections.filter((section) => section.page === selectedPage);
const recordSections = useMemo(
() =>
(templateContent?.trustContentTypes ?? [])
.filter((item) => item.pages?.includes(selectedPage ?? ""))
.map((item) => trustSection(item, selectedPage ?? "home")),
[templateContent, selectedPage],
);
const visibleTargets = useMemo<PreviewTarget[]>(
() =>
[...(templateContent?.admin.sections ?? []), ...recordSections]
.filter(
(section) =>
section.page === selectedPage &&
(selectedPage !== "detail" || section.target === "brand"),
)
.flatMap((section) =>
(section.previewTargets ?? []).map((target) => ({
...target,
page: section.page,
source: previewTargetSource(section, target.key),
...(section.key.startsWith("trust:") ? { trustType: section.key.slice(6) } : {}),
})),
)
.concat(
selectedPage === "inquiry" && inquiryRuntime
? inquiryRuntime.fields.map((field) => ({
key: `inquiry-field:${field.key}`,
label: field.label,
page: "inquiry",
source: "inquiry" as const,
}))
: [],
),
[templateContent, selectedPage, recordSections, inquiryRuntime],
);
const activeTarget = selection?.targetKey;
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
const selectedSection = [...(templateContent?.admin.sections ?? []), ...recordSections].find(
(section) =>
section.page === selectedPage &&
section.previewTargets?.some((target) => target.key === selectedTarget?.key),
);
const selectedRecordSource =
selectedTarget?.source === "offering" || selectedTarget?.source === "trust"
? selectedTarget.source
: undefined;
const { offeringsQuery, trustQuery, selectedRecord } = usePresentationRecordQueries(
selectedRecordSource,
selection?.recordId,
);
const editableSections = filterSectionsForPreviewTarget(
visibleSections.filter((section) =>
section.fields.some((field) => field.binding.startsWith("brand.")),
),
selectedTarget?.key,
);
const recordSection = useMemo(
() =>
selectedSection && selection?.targetKey
? {
...selectedSection,
fields: selectedSection.fields.filter(
(field) => field.previewTarget === selection.targetKey,
),
}
: undefined,
[selectedSection, selection?.targetKey],
);
const handleTargetSelected = useCallback(
(next?: PreviewSelection) => {
const select = () =>
setSelection(
next
? resolvePreviewSelection(
next.targetKey,
next.recordId,
visibleTargets,
selectedPage ?? "home",
)
: undefined,
);
if (recordDraft || inquiryDraft)
guardDraft(() => {
setInquiryDraft(undefined);
setRecordDraft(undefined);
select();
});
else select();
},
[visibleTargets, selectedPage, recordDraft, inquiryDraft, guardDraft],
);
const relatedTargets = [
...(templateContent?.admin.sections ?? [])
.filter((section) => section.page === selectedPage && section.target !== "brand")
.map((section) => section.target),
...((templateContent?.trustContentTypes ?? []).some((item) =>
item.pages?.includes(selectedPage ?? ""),
)
? ["trust"]
: []),
];
const pageLinks = [...new Set(relatedTargets)].flatMap((target) =>
target === "trust"
? (templateContent?.trustContentTypes ?? [])
.filter((item) => item.pages?.includes(selectedPage ?? ""))
.map((item) => ({
target: `trust:${item.type}`,
label: `编辑${item.label}`,
}))
: [
{
target,
label: (
{ offering: "管理此页展示的业务内容", inquiry: "管理此页的咨询表单" } as Record<
string,
string
>
)[target],
},
],
);
const relevantPageLinks = selectedSection
? pageLinks.filter((item) => {
if (item.target.startsWith("trust:")) return selectedSection.target === "trust";
return item.target === selectedSection.target;
})
: pageLinks;
const formState = useBrandPresentationForm({ brand, config, sections });
const { form, initialValues } = formState;
const save = useBrandSaveMutation({
...formState,
brand,
config,
sections,
queryClient,
onSaved: () => setBrandDirty(false),
});
useEffect(() => {
const initialPage =
typeof initialSelection === "object" && "page" in initialSelection
? String(initialSelection.page)
: undefined;
if (initialPage) {
setActivePage(
pageOptions.some((item) => item.value === initialPage)
? initialPage
: pageOptions[0]?.value,
);
return;
}
if (!activePage && pageOptions.length) setActivePage(pageOptions[0]?.value);
}, [activePage, initialSelection, pageOptions]);
useEffect(() => {
if (hasInitializedSelection) return;
if (!pageOptions.length) return;
if (!initialSelection) return;
const requestedPage =
typeof initialSelection === "object" && "page" in initialSelection
? String(initialSelection.page)
: undefined;
const resolvedPage =
requestedPage && pageOptions.some((item) => item.value === requestedPage)
? requestedPage
: (pageOptions[0]?.value ?? "home");
setSelection(
resolvePreviewSelection(
initialSelection.targetKey,
initialSelection.recordId,
visibleTargets,
resolvedPage,
),
);
setActivePage(resolvedPage);
setHasInitializedSelection(true);
}, [hasInitializedSelection, initialSelection, pageOptions, selectedPage, visibleTargets]);
useEffect(() => {
if (!initialSelection) setSelection(undefined);
}, [initialSelection, selectedPage, templateContent?.displayName]);
useEffect(() => {
if (!selection?.recordId) return;
const records =
selectedTarget?.source === "trust"
? previewWorkspace?.trustItems
: previewWorkspace?.offerings;
if (records && !records.some((item) => item.id === selection.recordId)) setSelection(undefined);
}, [
previewWorkspace?.offerings,
previewWorkspace?.trustItems,
selectedTarget?.source,
selection,
]);
useEffect(
() => setRecordDraft(undefined),
[selection?.targetKey, selection?.recordId, selectedPage],
);
const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({
brand,
config,
sections,
form,
onDirty: () => setBrandDirty(true),
});
const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection });
useEffect(() => resetPreview(), [config, initialValues, resetPreview]);
const draftWorkspace = useDraftWorkspace({
previewWorkspace,
previewBrand,
inquiryRuntime,
inquiryDraft,
recordDraft,
selectedRecord,
recordSection,
recordPreview,
templateContent,
});
const selectedDetailOfferingId =
detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId)
? detailOfferingId
: draftWorkspace?.offerings[0]?.id;
const selectPage = useCallback(
(page: string) => {
guardDraft(() => {
setBrandDirty(false);
resetPreview();
setRecordDraft(undefined);
setInquiryDraft(undefined);
setActivePage(page);
});
},
[guardDraft, resetPreview],
);
const selectDetailOffering = useCallback((id: string) => {
setDetailOfferingId(id);
setSelection(undefined);
}, []);
const selectPreviewTarget = useCallback(
(target: PreviewTarget) => {
const recordId =
target.source === "offering"
? selectedPage === "detail"
? selectedDetailOfferingId
: draftWorkspace?.offerings[0]?.id
: target.source === "trust"
? previewTrustRecordId(draftWorkspace?.trustItems ?? [], target.trustType)
: undefined;
handleTargetSelected({
targetKey: target.key,
...(recordId ? { recordId } : {}),
});
},
[handleTargetSelected, selectedPage, selectedDetailOfferingId, draftWorkspace],
);
return {
pageOptions,
selectedPage,
visibleTargets,
selectedTarget,
selectedSection,
selectedRecordSource,
selectedRecord,
recordSection,
editableSections,
relevantPageLinks,
inquiryRuntime,
draftWorkspace,
previewBrand,
selectedDetailOfferingId,
form,
initialValues,
save,
offeringsQuery,
trustQuery,
recordDraft,
inquiryDraft,
brandDirty,
selection,
activeTarget,
guardDraft,
selectPage,
selectDetailOffering,
selectPreviewTarget,
handleTargetSelected,
setRecordDraft,
setInquiryDraft,
handleValuesChange,
navigate,
};
}
@@ -1,4 +1,4 @@
import { Form, message } from "antd";
import { App, Form } from "antd";
import { useMutation, useQuery } from "@tanstack/react-query";
import type { QueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
@@ -89,7 +89,6 @@ export function useBrandPresentationForm({
return values;
}, [brand, config, sections]);
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
return { form, initialValues };
}
@@ -108,6 +107,7 @@ export function useBrandSaveMutation({
queryClient,
onSaved,
}: BrandSaveMutationOptions) {
const { message } = App.useApp();
return useMutation({
mutationFn: (values: PresentationValues) => {
const nextConfig = applyPresentationValues(config, sections, values);
@@ -27,7 +27,21 @@ const element = (tag) =>
export const View = element("div");
export const Text = element("span");
export const Button = element("button");
export const Button = React.forwardRef(
({ children, className, style, onClick, loading, ...props }, ref) =>
React.createElement(
"button",
{
...props,
ref,
className,
style,
onClick,
...(loading ? { "aria-busy": "true" } : {}),
},
children,
),
);
export const Input = React.forwardRef(({ onInput, ...props }, ref) =>
React.createElement("input", {
...props,
@@ -101,16 +115,18 @@ export const Label = element("label");
export const Image = React.forwardRef(({ mode, src, style, ...props }, ref) => {
const key = React.useContext(TemplateAssetContext);
const assets = React.useContext(TemplatePreviewAssetsContext);
const normalizedSrc = typeof src === "string" ? src.trim() : "";
if (!normalizedSrc) return null;
return React.createElement("img", {
...props,
ref,
src:
assets && typeof src === "string" && src.startsWith("/assets/")
assets && normalizedSrc.startsWith("/assets/")
? // 导入包资源以 /assets 开头;本地多模板预览的 renderer 可能额外携带包 key 前缀。
(assets[src]?.dataUrl ??
assets[src.replace(`/assets/${key}/`, "/assets/")]?.dataUrl ??
src)
: resolveImageSource(src, key),
(assets[normalizedSrc]?.dataUrl ??
assets[normalizedSrc.replace(`/assets/${key}/`, "/assets/")]?.dataUrl ??
normalizedSrc)
: resolveImageSource(normalizedSrc, key),
style: { objectFit: mode === "aspectFit" ? "contain" : "cover", ...style },
});
});
@@ -1,8 +1,9 @@
import { useEffect } from "react";
import { Modal } from "antd";
import { App } from "antd";
import { useNavigate } from "react-router-dom";
export function useEditorDraft(dirty: boolean) {
const { modal } = App.useApp();
const navigate = useNavigate();
useEffect(() => {
if (!dirty) return;
@@ -22,7 +23,7 @@ export function useEditorDraft(dirty: boolean) {
return;
event.preventDefault();
event.stopImmediatePropagation();
Modal.confirm({
modal.confirm({
title: "有尚未保存的修改",
content: "离开工作台会丢失未保存内容。请先保存,或确认放弃修改。",
okText: "放弃修改并继续",
@@ -40,7 +41,7 @@ export function useEditorDraft(dirty: boolean) {
}, [dirty, navigate]);
return (action: () => void) => {
if (!dirty) return action();
Modal.confirm({
modal.confirm({
title: "有尚未保存的修改",
content: "切换后当前内容可能丢失。请先保存,或确认放弃修改。",
okText: "放弃修改并继续",
@@ -1,9 +1,8 @@
import { Alert, Button, Card, Col, Row, Space } from "antd";
import { Alert, App, Button, Card, Col, Row, Space } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { createApiClient } from "../../lib/api.js";
import { adminMessage as message } from "../../components/AdminMessage.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { EmptyState } from "../../components/EmptyState.js";
import { QueryState } from "../../components/QueryState.js";
@@ -12,6 +11,7 @@ import { StatusTag } from "../../components/StatusTag.js";
const client = createApiClient();
export function BrandsPage({ canCreate }: { canCreate: boolean }) {
const { message } = App.useApp();
const navigate = useNavigate();
const brands = useQuery({
queryKey: ["admin-brand-memberships"],
@@ -58,7 +58,7 @@ export function BrandsPage({ canCreate }: { canCreate: boolean }) {
className="admin-offset-bottom"
type="info"
showIcon
message="切换品牌会进入对应品牌的工作区"
title="切换品牌会进入对应品牌的工作区"
description="品牌之间的业务内容、成员、发布记录和页面方案相互隔离。"
/>
{brands.data?.length ? (
@@ -88,7 +88,7 @@ export function BrandsPage({ canCreate }: { canCreate: boolean }) {
</Button>,
]}
>
<Space direction="vertical" size={8}>
<Space orientation="vertical" size={8}>
<span className="admin-section-description">
小程序地址标识:{membership.brand.slug}
</span>
@@ -28,6 +28,7 @@ export function CreateBrandPage() {
const navigate = useNavigate();
const [form] = Form.useForm<CreateBrandInput>();
const businessType = Form.useWatch("businessType", form);
const selectedSchemeId = Form.useWatch("templatePackageVersionId", form);
const options = useQuery({
queryKey: ["admin-brand-creation-options"],
queryFn: () => client.getAdminBrandCreationOptions(),
@@ -121,12 +122,12 @@ export function CreateBrandPage() {
<Alert
type="warning"
showIcon
message="当前业务类型还没有可用的页面方案"
title="当前业务类型还没有可用的页面方案"
description="请先联系平台管理员发布兼容的页面方案。"
/>
)
) : (
<Alert type="info" showIcon message="选择业务类型后,将只显示兼容的页面方案" />
<Alert type="info" showIcon title="选择业务类型后,将只显示兼容的页面方案" />
)}
</AdminSection>
@@ -140,7 +141,7 @@ export function CreateBrandPage() {
rules={[{ required: true, message: "请选择页面方案" }]}
>
<Radio.Group className="admin-stack">
<Space direction="vertical" size={12} className="admin-full-width">
<Space orientation="vertical" size={12} className="admin-full-width">
{schemes.map((scheme) => (
<Radio.Button
key={scheme.templatePackageVersionId}
@@ -179,7 +180,7 @@ export function CreateBrandPage() {
<Alert
type="info"
showIcon
message="创建品牌不会自动导入示例内容"
title="创建品牌不会自动导入示例内容"
description="新品牌会从空白内容开始,避免把示例品牌、案例或联系方式误当成真实信息发布。"
/>
<MutationError error={create.error} />
@@ -190,7 +191,10 @@ export function CreateBrandPage() {
htmlType="submit"
size="large"
loading={create.isPending}
disabled={!businessType || schemes.length === 0}
disabled={
!businessType ||
!schemes.some((scheme) => scheme.templatePackageVersionId === selectedSchemeId)
}
>
创建并进入品牌
</Button>
@@ -1,5 +1,5 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { message } from "antd";
import { App } from "antd";
import { createApiClient } from "../../../lib/api.js";
import { readAdminCapability } from "../types.js";
import type { CapabilityValues } from "../types.js";
@@ -17,6 +17,7 @@ export function useCapabilityQuery() {
}
export function useCapabilityMutation() {
const { message } = App.useApp();
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ key, ...values }: { key: string } & CapabilityValues) =>
@@ -1,4 +1,4 @@
import { Badge, Button, Descriptions, Drawer, Select, Space, Table, message, Input } from "antd";
import { App, Badge, Button, Descriptions, Drawer, Select, Space, Table, Input } from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { AdminBooking, InquirySubmission } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
@@ -51,6 +51,7 @@ const statusTones: Record<string, StatusTone> = {
};
export function InquiriesPage() {
const { message } = App.useApp();
const client = createApiClient();
const queryClient = useQueryClient();
const [status, setStatus] = useState<string>();
@@ -1,8 +1,7 @@
import { useEffect, useState } from "react";
import { Alert, Button, Card, Collapse, Descriptions, Empty, List, Modal, Space, Tag } from "antd";
import { Alert, App, Button, Card, Collapse, Descriptions, Empty, List, Space, Tag } from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { createApiClient } from "../../lib/api.js";
import { adminMessage as message } from "../../components/AdminMessage.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { AdminSection } from "../../components/AdminSection.js";
import { MutationError, QueryState } from "../../components/QueryState.js";
@@ -11,6 +10,7 @@ import { StatusTag } from "../../components/StatusTag.js";
const client = createApiClient();
export function PageSchemePage() {
const { message, modal } = App.useApp();
const queryClient = useQueryClient();
const [selectedVersionId, setSelectedVersionId] = useState<string>();
const [samplePreview, setSamplePreview] = useState<Awaited<
@@ -43,6 +43,7 @@ export function PageSchemePage() {
const refresh = () => {
for (const queryKey of [
"page-scheme-workspace",
"admin-page-scheme-options",
"page-scheme-upgrade-preview",
"admin-workspace",
"admin-preview-workspace",
@@ -134,7 +135,7 @@ export function PageSchemePage() {
const target = compatibleSchemes.find(
(scheme) => scheme.templatePackageVersionId === templatePackageVersionId,
);
Modal.confirm({
modal.confirm({
title: "切换页面方案版本",
content: target
? `将当前品牌切换到「${target.name}」版本 ${target.version}。现有品牌内容会保留。`
@@ -146,7 +147,7 @@ export function PageSchemePage() {
};
const confirmUpgrade = () => {
const preview = upgradePreview.data;
Modal.confirm({
modal.confirm({
title: "升级页面方案",
content:
preview && preview.conflicts.length
@@ -158,7 +159,7 @@ export function PageSchemePage() {
});
};
const confirmRollback = () => {
Modal.confirm({
modal.confirm({
title: "恢复上一版配置基线",
content: "此操作只恢复上一版页面方案配置,不会删除品牌内容、业务提供项或咨询记录。",
okText: "确认恢复",
@@ -211,7 +212,7 @@ export function PageSchemePage() {
>
<Card>
{upgradePreview.data?.canUpgrade ? (
<Space direction="vertical" size={12} className="admin-full-width">
<Space orientation="vertical" size={12} className="admin-full-width">
<div className="admin-row-line">
<strong>可升级到版本 {upgradePreview.data.latestVersion}</strong>
<Tag color="blue">建议先预览</Tag>
@@ -234,11 +235,11 @@ export function PageSchemePage() {
<Alert
type="warning"
showIcon
message={`发现 ${upgradePreview.data.conflicts.length} 项自定义内容与新版布局存在差异`}
title={`发现 ${upgradePreview.data.conflicts.length} 项自定义内容与新版布局存在差异`}
description="升级时会全部保留现有内容,不会逐项覆盖。请确认后再执行升级。"
/>
) : (
<Alert type="success" showIcon message="未发现内容绑定冲突" />
<Alert type="success" showIcon title="未发现内容绑定冲突" />
)}
<Button type="primary" onClick={confirmUpgrade} loading={upgrade.isPending}>
升级到 {upgradePreview.data.latestVersion}
@@ -317,11 +318,11 @@ export function PageSchemePage() {
key: "sample-content",
label: "高级:导入示例内容",
children: (
<Space direction="vertical" size={12} className="admin-full-width">
<Space orientation="vertical" size={12} className="admin-full-width">
<Alert
type="warning"
showIcon
message="此操作会写入当前品牌内容"
title="此操作会写入当前品牌内容"
description="仅导入当前缺失的内容,不会覆盖已有品牌资料。创建品牌时不会自动执行。"
/>
<Space>
@@ -125,7 +125,7 @@ export function MiniAppReleaseCard({
return (
<Card size="small" styles={{ body: { padding: 16 } }}>
<Flex justify="space-between" align="flex-start" gap={12} wrap>
<Space direction="vertical" size={4}>
<Space orientation="vertical" size={4}>
<Space wrap size={8} align="center">
<Typography.Text strong>品牌内容 v{task.version}</Typography.Text>
<StatusTag label={status.label} tone={status.tone} />
@@ -1,5 +1,5 @@
import { useEffect } from "react";
import { Alert, Button, Form, Input, Space } from "antd";
import type { FormInstance } from "antd";
import type { MiniAppReleaseSettings } from "@personal-brand/api-client";
import { AdminSection } from "../../components/AdminSection.js";
import { MutationError } from "../../components/QueryState.js";
@@ -12,20 +12,24 @@ export type MiniAppSettingsValues = {
};
interface MiniAppSettingsTabProps {
form: FormInstance<MiniAppSettingsValues>;
settings: MiniAppReleaseSettings | undefined;
saving: boolean;
error?: unknown;
onSave: (values: MiniAppSettingsValues) => void;
}
export function MiniAppSettingsTab({
form,
settings,
saving,
error,
onSave,
}: MiniAppSettingsTabProps) {
export function MiniAppSettingsTab({ settings, saving, error, onSave }: MiniAppSettingsTabProps) {
const [form] = Form.useForm<MiniAppSettingsValues>();
useEffect(() => {
if (!settings) return;
form.setFieldsValue({
appId: settings.appId,
apiBaseUrl: settings.apiBaseUrl,
privateKey: "",
});
}, [form, settings]);
return (
<div className="admin-stack admin-stack-lg">
<AdminSection
@@ -37,7 +41,7 @@ export function MiniAppSettingsTab({
type="warning"
showIcon
className="admin-offset-bottom"
message="小程序构建参数未就绪"
title="小程序构建参数未就绪"
description={settings.buildError}
/>
) : (
@@ -45,7 +49,7 @@ export function MiniAppSettingsTab({
type="info"
showIcon
className="admin-offset-bottom"
message={`请求域名 ${settings?.requestDomain ?? "未确认"}`}
title={`请求域名 ${settings?.requestDomain ?? "未确认"}`}
description="该域名在构建时写入小程序包,必须与微信后台“开发设置 → 服务器域名 → request 合法域名”一致;不一致会导致小程序打开即加载失败。"
/>
)}
@@ -1,14 +1,14 @@
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { Alert, Button, Divider, Form, Input, Modal, Space, Tabs, Typography } from "antd";
import { Alert, Button, Divider, Input, Modal, Space, Tabs, Typography } from "antd";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { AdminSection } from "../../components/AdminSection.js";
import { EmptyState } from "../../components/EmptyState.js";
import { MutationError, QueryState } from "../../components/QueryState.js";
import { StatusTag, statusLabel } from "../../components/StatusTag.js";
import { MiniAppReleaseCard } from "./MiniAppReleaseCard.js";
import { MiniAppSettingsTab, type MiniAppSettingsValues } from "./MiniAppSettingsTab.js";
import { MiniAppSettingsTab } from "./MiniAppSettingsTab.js";
import { usePublicationQueries } from "./use-publication-queries.js";
import { usePublicationMutations } from "./use-publication-mutations.js";
@@ -29,8 +29,7 @@ export function PublicationPage() {
const [rollbackVersion, setRollbackVersion] = useState<number | null>(null);
const [note, setNote] = useState("");
const [activeTab, setActiveTab] = useState("content");
const [miniAppSettingsForm] = Form.useForm<MiniAppSettingsValues>();
const queries = usePublicationQueries(miniAppSettingsForm);
const queries = usePublicationQueries();
const {
workspace,
readiness,
@@ -255,7 +254,6 @@ export function PublicationPage() {
label: "小程序配置",
children: (
<MiniAppSettingsTab
form={miniAppSettingsForm}
settings={miniAppSettings.data}
saving={saveMiniAppSettings.isPending}
error={saveMiniAppSettings.error}
@@ -277,7 +275,7 @@ export function PublicationPage() {
{confirmAction === "revoke" ? (
<Alert
type="warning"
message="撤回后,小程序将显示品牌尚未发布,新的咨询和预约会停止受理。"
title="撤回后,小程序将显示品牌尚未发布,新的咨询和预约会停止受理。"
/>
) : (
<div className="admin-stack">
@@ -1,5 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { message } from "antd";
import { App } from "antd";
import { createApiClient } from "../../lib/api.js";
const client = createApiClient();
@@ -17,6 +17,7 @@ export function usePublicationMutations({
onNoteClear,
onRollbackClose,
}: MutationOptions) {
const { message } = App.useApp();
const queryClient = useQueryClient();
const publish = useMutation({
mutationFn: (note: string) => client.publishAdminRelease(note || undefined),
@@ -1,17 +1,10 @@
import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import type { FormInstance } from "antd";
import { createApiClient } from "../../lib/api.js";
const client = createApiClient();
export function usePublicationQueries(
miniAppSettingsForm: FormInstance<{
appId: string;
apiBaseUrl: string;
privateKey?: string;
}>,
) {
export function usePublicationQueries() {
const brand = useQuery<Awaited<ReturnType<typeof client.getAdminBrand>>>({
queryKey: ["publication-brand"],
queryFn: () => client.getAdminBrand(),
@@ -37,15 +30,6 @@ export function usePublicationQueries(
queryFn: () => client.getAdminMiniAppSettings(),
});
useEffect(() => {
if (!miniAppSettings.data) return;
miniAppSettingsForm.setFieldsValue({
appId: miniAppSettings.data.appId,
apiBaseUrl: miniAppSettings.data.apiBaseUrl,
privateKey: "",
});
}, [miniAppSettings.data, miniAppSettingsForm]);
useEffect(() => {
const building = miniAppReleases.data?.find(
(task) =>
@@ -75,7 +75,7 @@ export function OfferingEditorModal({
<Alert
type="info"
showIcon
message={previewPage === "offerings" ? "正在核对列表展示" : "正在核对详情展示"}
title={previewPage === "offerings" ? "正在核对列表展示" : "正在核对详情展示"}
description={
previewPage === "offerings"
? "右侧「列表展示」字段修改后,会实时反映在当前卡片。"
@@ -1,6 +1,6 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { Offering } from "@personal-brand/api-client";
import { message } from "antd";
import { App } from "antd";
import { useMemo } from "react";
import { createApiClient } from "../../lib/api.js";
import {
@@ -46,6 +46,7 @@ export function useOfferingMutations(options: {
templateFields: ReturnType<typeof offeringTemplateFields>;
onSuccess: () => void;
}) {
const { message } = App.useApp();
const client = createApiClient();
const queryClient = useQueryClient();
const invalidateAfterSave = () => {
+3 -2
View File
@@ -1,4 +1,4 @@
import { Alert, Button, Card, Form, Input, Modal, Select, Space, Table, message } from "antd";
import { Alert, App, Button, Card, Form, Input, Modal, Select, Space, Table } from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { AdminBrandMember } from "@personal-brand/api-client";
import { useState } from "react";
@@ -16,6 +16,7 @@ const roleLabels: Record<string, string> = {
};
export function MembersPage() {
const { message } = App.useApp();
const client = createApiClient();
const queryClient = useQueryClient();
const [addOpen, setAddOpen] = useState(false);
@@ -71,7 +72,7 @@ export function MembersPage() {
type="info"
showIcon
className="admin-offset-bottom"
message="请将初始账号和密码安全地交给成员"
title="请将初始账号和密码安全地交给成员"
description="当前采用负责人手动添加方式;系统不会再次显示成员初始密码。"
/>
<Table
@@ -1,6 +1,6 @@
import { useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Alert, Button, List, Modal, Table, Tag, Typography, message } from "antd";
import { Alert, App, Button, List, Modal, Table, Tag, Typography } from "antd";
import { EyeOutlined, ReloadOutlined, UploadOutlined } from "@ant-design/icons";
import type { TemplatePackageVersion } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
@@ -31,6 +31,7 @@ function formatBytes(value: unknown): string {
}
export function TemplateManagementPage() {
const { message } = App.useApp();
const inputRef = useRef<HTMLInputElement>(null);
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
@@ -110,7 +111,7 @@ export function TemplateManagementPage() {
<Alert
type="info"
showIcon
message="导入规则"
title="导入规则"
description="系统会校验文件路径、链接、文件数量、解压体积、template.json、package.json 和 checksums.json;包内脚本不会被执行。"
/>
{importing.isError ? <ErrorNote error={importing.error} /> : null}
@@ -118,7 +119,7 @@ export function TemplateManagementPage() {
<Alert
type="success"
showIcon
message={importing.data.idempotent ? "模板版本已存在,未重复写入" : "模板版本导入成功"}
title={importing.data.idempotent ? "模板版本已存在,未重复写入" : "模板版本导入成功"}
description={`${importing.data.version.packageKey}@${importing.data.version.version}`}
/>
) : null}
@@ -78,7 +78,7 @@ export function TemplatePackagePreviewModal({
<Alert
type="info"
showIcon
message="模板演示预览"
title="模板演示预览"
description="演示内容不属于真实品牌,咨询提交和客户记录读取已禁用。"
/>
{!industry ? (
@@ -92,12 +92,7 @@ export function TemplatePackagePreviewModal({
{data ? (
<>
{data.preview.diagnostics.map((diagnostic) => (
<Alert
key={diagnostic.code}
type="warning"
showIcon
message={diagnostic.message}
/>
<Alert key={diagnostic.code} type="warning" showIcon title={diagnostic.message} />
))}
<Typography.Text type="secondary">
演示数据:
@@ -1,5 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { message } from "antd";
import { App } from "antd";
import type { TrustContent, TrustContentInput } from "@personal-brand/api-client";
import { createApiClient } from "../../../lib/api.js";
@@ -10,6 +10,7 @@ export function useTrustContentMutations({
editing: TrustContent | null;
closeEditor: () => void;
}) {
const { message } = App.useApp();
const client = createApiClient();
const queryClient = useQueryClient();
@@ -1,4 +1,4 @@
import { message } from "antd";
import { App } from "antd";
import { useMutation } from "@tanstack/react-query";
import type { FormInstance } from "antd";
import type { BrandFieldDefinition, InquiryForm } from "@personal-brand/api-client";
@@ -19,6 +19,7 @@ export function useFieldMutations({
queryClient,
onClose,
}: FieldMutationOptions) {
const { message } = App.useApp();
const createField = useMutation({
mutationFn: (values: Omit<BrandFieldDefinition, "id" | "source">) =>
client.createAdminField(values),
@@ -49,6 +50,7 @@ export function useInquiryFormMutations({
};
onClose: () => void;
}) {
const { message } = App.useApp();
const createForm = useMutation({
mutationFn: (values: {
name: string;
+32
View File
@@ -0,0 +1,32 @@
export interface BrandSwitcherOption {
value: string;
label: string;
}
/**
* 品牌切换器只接受形状完整的成员记录。
* 接口返回异常条目时跳过该条,避免整个后台外壳渲染失败。
*/
export function toBrandSwitcherOptions(value: unknown): BrandSwitcherOption[] {
if (!Array.isArray(value)) return [];
const options: BrandSwitcherOption[] = [];
const seen = new Set<string>();
for (const item of value) {
const brand = (item as { brand?: { id?: unknown; name?: unknown } } | null | undefined)?.brand;
if (!brand || typeof brand.id !== "string" || brand.id.length === 0) continue;
if (seen.has(brand.id)) continue;
seen.add(brand.id);
options.push({
value: brand.id,
label: typeof brand.name === "string" && brand.name.length > 0 ? brand.name : brand.id,
});
}
return options;
}
/** 品牌名称必须是字符串,异常数据回退到给定文案。 */
export function toBrandDisplayName(value: unknown, fallback: string): string {
return typeof value === "string" && value.trim().length > 0 ? value : fallback;
}
@@ -0,0 +1,74 @@
import assert from "node:assert/strict";
import { readdir, readFile, access } from "node:fs/promises";
import path from "node:path";
import { test } from "node:test";
const sourceRoot = path.resolve(import.meta.dirname, "../src");
async function listSourceFiles(directory) {
const entries = await readdir(directory, { withFileTypes: true });
const files = await Promise.all(
entries.map(async (entry) => {
const absolute = path.join(directory, entry.name);
if (entry.isDirectory()) return listSourceFiles(absolute);
return /\.(?:ts|tsx)$/.test(entry.name) ? [absolute] : [];
}),
);
return files.flat();
}
function readTag(source, start) {
let index = start;
let quote = null;
while (index < source.length) {
const char = source[index];
if (quote) {
if (char === quote) quote = null;
} else if (char === '"' || char === "'" || char === "`") {
quote = char;
} else if (char === ">") {
return source.slice(start, index + 1);
}
index += 1;
}
return source.slice(start);
}
function tagsNamed(source, name) {
const tags = [];
for (const match of source.matchAll(new RegExp("<" + name + "\\b", "g"))) {
tags.push(readTag(source, match.index));
}
return tags;
}
test("Admin 源码不使用 Ant Design 6 已弃用的静态提示 API", async () => {
const files = await listSourceFiles(sourceRoot);
const violations = [];
for (const file of files) {
const source = await readFile(file, "utf8");
const relative = path.relative(sourceRoot, file);
if (/import\s*\{[^}]*\bmessage\b[^}]*\}\s*from\s*"antd"/.test(source)) {
violations.push(`${relative}: 仍从 antd 导入静态 message`);
}
if (/\bModal\.confirm\s*\(/.test(source)) {
violations.push(`${relative}: 仍调用静态 Modal.confirm`);
}
for (const tag of tagsNamed(source, "Alert")) {
if (/(?<![\w.])message\s*=/.test(tag)) {
violations.push(`${relative}: Alert 仍使用 message 属性`);
}
}
for (const tag of tagsNamed(source, "Space")) {
if (/(?<![\w.])direction\s*=/.test(tag)) {
violations.push(`${relative}: Space 仍使用 direction 属性`);
}
}
}
assert.deepEqual(violations, []);
});
test("Admin 不再保留静态 message 转出口", async () => {
const legacyBridge = path.resolve(sourceRoot, "components/AdminMessage.ts");
await assert.rejects(access(legacyBridge));
});
+57
View File
@@ -0,0 +1,57 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { toBrandDisplayName, toBrandSwitcherOptions } from "../src/lib/brand-switcher.ts";
test("完整成员记录转换为品牌切换选项", () => {
assert.deepEqual(
toBrandSwitcherOptions([
{ id: "membership-1", role: "owner", brand: { id: "brand-1", name: "独立工坊" } },
{ id: "membership-2", role: "editor", brand: { id: "brand-2", name: "林境门作" } },
]),
[
{ value: "brand-1", label: "独立工坊" },
{ value: "brand-2", label: "林境门作" },
],
);
});
test("异常成员条目被跳过而不是让外壳崩溃", () => {
assert.deepEqual(toBrandSwitcherOptions([{}, null, { brand: null }, { brand: { id: 1 } }]), []);
assert.deepEqual(
toBrandSwitcherOptions([
{},
null,
{ brand: { id: "brand-1", name: "独立工坊" } },
{ brand: { id: "" } },
]),
[{ value: "brand-1", label: "独立工坊" }],
);
});
test("非数组返回空选项集合", () => {
for (const value of [undefined, null, {}, "oops", 42]) {
assert.deepEqual(toBrandSwitcherOptions(value), []);
}
});
test("重复品牌与缺失名称按稳定规则收敛", () => {
assert.deepEqual(
toBrandSwitcherOptions([
{ brand: { id: "brand-1", name: "独立工坊" } },
{ brand: { id: "brand-1", name: "重复品牌" } },
{ brand: { id: "brand-2", name: 123 } },
]),
[
{ value: "brand-1", label: "独立工坊" },
{ value: "brand-2", label: "brand-2" },
],
);
});
test("品牌名称只接受非空字符串", () => {
assert.equal(toBrandDisplayName("独立工坊", "当前品牌"), "独立工坊");
assert.equal(toBrandDisplayName(" ", "当前品牌"), "当前品牌");
assert.equal(toBrandDisplayName({ name: "x" }, "当前品牌"), "当前品牌");
assert.equal(toBrandDisplayName(null, "当前品牌"), "当前品牌");
assert.equal(toBrandDisplayName(undefined, ""), "");
});
+2 -1
View File
@@ -4,11 +4,12 @@
"type": "module",
"scripts": {
"build": "tsc -p tsconfig.json",
"postinstall": "prisma generate",
"dev": "pnpm build && node --env-file=.env --watch dist/main.js",
"lint": "eslint .",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "tsx --test test/**/*.test.ts",
"test:integration": "pnpm build && node --env-file=.env test/template-contract-migration.integration.mjs && node --env-file=.env test/run-integration.cjs && pnpm --filter @personal-brand/api exec tsx --test test/http.upload.test.js",
"test:integration": "pnpm --workspace-root exec turbo run build --filter=@personal-brand/api... && node --env-file=.env test/template-contract-migration.integration.mjs && node --env-file=.env test/run-integration.cjs && pnpm --filter @personal-brand/api exec tsx --test test/http.upload.test.js",
"clean": "rimraf dist",
"start": "node dist/main.js",
"db:generate": "prisma generate",
@@ -0,0 +1,28 @@
-- CreateTable
CREATE TABLE "ClientErrorThrottleWindow" (
"subject" TEXT NOT NULL,
"windowStart" TIMESTAMP(3) NOT NULL,
"count" INTEGER NOT NULL,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "ClientErrorThrottleWindow_pkey" PRIMARY KEY ("subject")
);
-- CreateTable
CREATE TABLE "ClientErrorDedupe" (
"id" TEXT NOT NULL,
"subject" TEXT NOT NULL,
"errorId" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ClientErrorDedupe_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "ClientErrorThrottleWindow_windowStart_idx" ON "ClientErrorThrottleWindow"("windowStart");
-- CreateIndex
CREATE UNIQUE INDEX "ClientErrorDedupe_subject_errorId_key" ON "ClientErrorDedupe"("subject", "errorId");
-- CreateIndex
CREATE INDEX "ClientErrorDedupe_createdAt_idx" ON "ClientErrorDedupe"("createdAt");
+20 -1
View File
@@ -1,6 +1,6 @@
generator client {
provider = "prisma-client-js"
binaryTargets = ["linux-musl-openssl-3.0.x", "debian-openssl-3.0.x"]
binaryTargets = ["linux-musl-openssl-3.0.x", "debian-openssl-3.0.x", "linux-arm64-openssl-3.0.x"]
}
datasource db {
@@ -468,6 +468,25 @@ model AdminUser {
templateAuditLogs TemplatePackageAuditLog[] @relation("TemplatePackageAuditActor")
}
model ClientErrorThrottleWindow {
subject String @id
windowStart DateTime
count Int
updatedAt DateTime @updatedAt
@@index([windowStart])
}
model ClientErrorDedupe {
id String @id @default(uuid())
subject String
errorId String
createdAt DateTime @default(now())
@@unique([subject, errorId])
@@index([createdAt])
}
model TemplatePackage {
id String @id @default(uuid())
packageKey String @unique
+43 -15
View File
@@ -4,16 +4,36 @@ import { PrismaService } from "./prisma.service.js";
import { readAdminToken } from "./admin-access.identity.js";
import { readIdentity } from "./auth.js";
type TokenAccess = {
subject: string;
brandId: string;
mustChangePassword: boolean;
tokenVersion: number;
platformTemplateRole: string;
};
type BrandAccess = { subject: string; brandId: string; role: string };
@Injectable()
export class AdminAccessService {
/**
* 同一 HTTP 请求内 Guard 和 Controller 都会调用访问校验。
* 用 WeakMap 按请求缓存结果,既避免重复查询,也不会把权限状态跨请求缓存。
*/
private readonly tokenAccess = new WeakMap<FastifyRequest, Promise<TokenAccess>>();
private readonly brandAccess = new WeakMap<FastifyRequest, Promise<BrandAccess>>();
constructor(private readonly prisma: PrismaService) {}
async requireToken(request: FastifyRequest): Promise<{
subject: string;
brandId: string;
mustChangePassword: boolean;
tokenVersion: number;
}> {
requireToken(request: FastifyRequest): Promise<TokenAccess> {
const cached = this.tokenAccess.get(request);
if (cached) return cached;
const pending = this.resolveToken(request);
this.tokenAccess.set(request, pending);
return pending;
}
private async resolveToken(request: FastifyRequest): Promise<TokenAccess> {
const token = readAdminToken(request);
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
@@ -25,7 +45,12 @@ export class AdminAccessService {
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
const user = await this.prisma.adminUser.findUnique({
where: { id: identity.subject },
select: { isEnabled: true, mustChangePassword: true, tokenVersion: true },
select: {
isEnabled: true,
mustChangePassword: true,
tokenVersion: true,
platformTemplateRole: true,
},
});
if (!user || identity.tokenVersion !== user.tokenVersion)
throw new UnauthorizedException("管理员登录态已失效,请重新登录");
@@ -35,12 +60,19 @@ export class AdminAccessService {
brandId: identity.brandId,
mustChangePassword: user.mustChangePassword,
tokenVersion: user.tokenVersion,
platformTemplateRole: user.platformTemplateRole,
};
}
async requireBrand(
request: FastifyRequest,
): Promise<{ subject: string; brandId: string; role: string }> {
requireBrand(request: FastifyRequest): Promise<BrandAccess> {
const cached = this.brandAccess.get(request);
if (cached) return cached;
const pending = this.resolveBrand(request);
this.brandAccess.set(request, pending);
return pending;
}
private async resolveBrand(request: FastifyRequest): Promise<BrandAccess> {
const access = await this.requireToken(request);
if (access.mustChangePassword)
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
@@ -63,11 +95,7 @@ export class AdminAccessService {
const access = await this.requireToken(request);
if (access.mustChangePassword)
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
const user = await this.prisma.adminUser.findUniqueOrThrow({
where: { id: access.subject },
select: { platformTemplateRole: true },
});
if (user.platformTemplateRole !== "template_admin")
if (access.platformTemplateRole !== "template_admin")
throw new ForbiddenException("当前账号没有模板管理权限");
return { subject: access.subject };
}
+12
View File
@@ -1,5 +1,6 @@
import { UnauthorizedException } from "@nestjs/common";
import { createHmac, timingSafeEqual } from "node:crypto";
import { isPlaceholderSecret } from "./runtime-config.js";
type Identity = {
subject: string;
@@ -9,9 +10,20 @@ type Identity = {
exp: number;
};
let warnedAboutPlaceholderSecret = false;
function secret(): string {
const value = process.env.SESSION_SECRET;
if (!value || value.length < 32) throw new UnauthorizedException("服务端会话密钥未正确配置");
if (isPlaceholderSecret(value)) {
// 生产环境已在启动时 fail fast;这里保留二次防线,避免绕过 createApp 的调用方签发弱 token。
if (process.env.NODE_ENV === "production")
throw new UnauthorizedException("服务端会话密钥未正确配置");
if (!warnedAboutPlaceholderSecret) {
warnedAboutPlaceholderSecret = true;
console.warn("[api] SESSION_SECRET 仍是示例占位符,仅可用于本地开发");
}
}
return value;
}
+23
View File
@@ -0,0 +1,23 @@
import { IsOptional, IsString, Matches, MaxLength, MinLength } from "class-validator";
/** 后台渲染异常上报:只接受白名单字段,避免把任意浏览器数据写进日志。 */
export class CreateClientErrorDto {
@IsString()
@Matches(/^[A-Za-z0-9._-]{4,128}$/, { message: "errorId 格式不正确" })
errorId!: string;
@IsString()
@MinLength(1, { message: "message 不能为空" })
@MaxLength(2000, { message: "message 过长" })
message!: string;
@IsString()
@Matches(/^\//, { message: "route 必须以 / 开头" })
@MaxLength(500, { message: "route 过长" })
route!: string;
@IsOptional()
@IsString()
@MaxLength(20000, { message: "componentStack 过长" })
componentStack?: string;
}
+2
View File
@@ -6,8 +6,10 @@ import multipart from "@fastify/multipart";
import fastifyStatic from "@fastify/static";
import path from "node:path";
import { AppModule, configureApp } from "./app.module.js";
import { assertProductionSecret } from "./runtime-config.js";
export async function createApp(): Promise<NestFastifyApplication> {
assertProductionSecret(process.env.SESSION_SECRET);
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
app
.getHttpAdapter()
@@ -1,22 +1,12 @@
import { AdminBrand } from "../../admin-auth.decorators.js";
import {
Body,
Controller,
ForbiddenException,
Get,
Param,
Post,
Query,
Req,
UnauthorizedException,
} from "@nestjs/common";
import { Body, Controller, Get, Param, Post, Query, Req } from "@nestjs/common";
import { Transform } from "class-transformer";
import type { TransformFnParams } from "class-transformer";
import { BookingStatus } from "@prisma/client";
import { IsBoolean, IsEnum, IsOptional, IsString } from "class-validator";
import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "../../admin-access.service.js";
import { BookingService } from "../../booking.service.js";
import { readIdentity } from "../../auth.js";
import { UpdateBookingStatusDto, UpdateBookingTagsDto, CreateTagDto } from "../../admin.dto.js";
class AdminBookingQueryDto {
@@ -35,67 +25,67 @@ class AdminBookingQueryDto {
@AdminBrand()
@Controller("admin/bookings")
export class AdminBookingController {
constructor(private readonly bookings: BookingService) {}
constructor(
private readonly access: AdminAccessService,
private readonly bookings: BookingService,
) {}
@Get()
list(@Req() request: FastifyRequest, @Query() query: AdminBookingQueryDto): Promise<unknown> {
const brandId = this.requireAdmin(request);
async list(
@Req() request: FastifyRequest,
@Query() query: AdminBookingQueryDto,
): Promise<unknown> {
const { brandId } = await this.access.requireBrand(request);
return this.bookings.listForAdmin(brandId, query);
}
@Get("unread-count")
unreadCount(@Req() request: FastifyRequest): Promise<unknown> {
return this.bookings.unreadCountForAdmin(this.requireAdmin(request));
async unreadCount(@Req() request: FastifyRequest): Promise<unknown> {
const { brandId } = await this.access.requireBrand(request);
return this.bookings.unreadCountForAdmin(brandId);
}
@Get(":id")
detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
return this.bookings.getForAdmin(this.requireAdmin(request), id);
async detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
const { brandId } = await this.access.requireBrand(request);
return this.bookings.getForAdmin(brandId, id);
}
@Post(":id/status")
update(
async update(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateBookingStatusDto,
): Promise<unknown> {
return this.bookings.updateStatus(this.requireAdmin(request), id, body.status, body.adminNote);
const { brandId } = await this.access.requireBrand(request);
return this.bookings.updateStatus(brandId, id, body.status, body.adminNote);
}
@Post(":id/read")
markRead(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
return this.bookings.markRead(this.requireAdmin(request), id);
async markRead(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
const { brandId } = await this.access.requireBrand(request);
return this.bookings.markRead(brandId, id);
}
@Post(":id/tags")
updateTags(
async updateTags(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateBookingTagsDto,
): Promise<unknown> {
return this.bookings.updateTags(this.requireAdmin(request), id, body.tagIds);
const { brandId } = await this.access.requireBrand(request);
return this.bookings.updateTags(brandId, id, body.tagIds);
}
@Get("tags")
listTags(@Req() request: FastifyRequest): Promise<unknown> {
return this.bookings.listTags(this.requireAdmin(request));
async listTags(@Req() request: FastifyRequest): Promise<unknown> {
const { brandId } = await this.access.requireBrand(request);
return this.bookings.listTags(brandId);
}
@Post("tags")
createTag(@Req() request: FastifyRequest, @Body() body: CreateTagDto): Promise<unknown> {
return this.bookings.createTag(this.requireAdmin(request), body.name);
}
private requireAdmin(request: FastifyRequest): string {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
try {
identity = readIdentity(token);
} catch {
throw new UnauthorizedException("管理员登录态无效或已过期");
}
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
return identity.brandId;
async createTag(@Req() request: FastifyRequest, @Body() body: CreateTagDto): Promise<unknown> {
const { brandId } = await this.access.requireBrand(request);
return this.bookings.createTag(brandId, body.name);
}
}
@@ -0,0 +1,36 @@
import { AdminBrand } from "../../admin-auth.decorators.js";
import { Body, Controller, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "../../admin-access.service.js";
import { CreateClientErrorDto } from "../../client-error.dto.js";
import { AdminClientErrorService } from "./admin-client-error.service.js";
@AdminBrand()
@Controller("admin/client-errors")
export class AdminClientErrorController {
constructor(
private readonly access: AdminAccessService,
private readonly errors: AdminClientErrorService,
) {}
@Post()
async create(
@Req() request: FastifyRequest,
@Body() body: CreateClientErrorDto,
): Promise<{ received: true; duplicate: boolean }> {
const identity = await this.access.requireBrand(request);
return this.errors.record({
subject: identity.subject,
brandId: identity.brandId,
errorId: body.errorId,
message: body.message,
route: body.route,
componentStack: body.componentStack,
requestId:
(request as FastifyRequest & { requestId?: string }).requestId ??
request.headers["x-request-id"]?.toString() ??
null,
userAgent: request.headers["user-agent"]?.toString().slice(0, 300) ?? null,
});
}
}
@@ -0,0 +1,49 @@
import { Inject, Injectable } from "@nestjs/common";
import {
CLIENT_ERROR_THROTTLE_STORE,
type ClientErrorThrottleStore,
} from "./client-error-throttle.store.js";
const LOG_STACK_LIMIT = 4000;
export interface ClientErrorReport {
subject: string;
brandId: string;
errorId: string;
message: string;
route: string;
componentStack?: string | undefined;
requestId: string | null;
userAgent: string | null;
}
export interface ClientErrorReceipt {
received: true;
duplicate: boolean;
}
@Injectable()
export class AdminClientErrorService {
constructor(
@Inject(CLIENT_ERROR_THROTTLE_STORE)
private readonly throttle: ClientErrorThrottleStore,
) {}
async record(report: ClientErrorReport): Promise<ClientErrorReceipt> {
const result = await this.throttle.record(report);
if (result.duplicate) return { received: true, duplicate: true };
console.error("admin client error", {
errorId: report.errorId,
message: report.message,
route: report.route,
subject: report.subject,
brandId: report.brandId,
requestId: report.requestId,
userAgent: report.userAgent,
componentStack: report.componentStack?.slice(0, LOG_STACK_LIMIT) ?? null,
});
return { received: true, duplicate: false };
}
}
@@ -7,7 +7,7 @@ import {
UpdateBrandPresentationDto,
UpdateTrustContentDto,
} from "../../admin.dto.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { TrustContentService } from "../../template/trust-content.service.js";
import { requireAdminIdentity } from "../../admin-access.identity.js";
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
@@ -15,7 +15,7 @@ import { AdminBrandConfigService } from "./admin-brand-config.service.js";
@Controller("admin/config")
export class AdminConfigController {
constructor(
private readonly templateWorkspace: TemplateWorkspaceService,
private readonly trustContent: TrustContentService,
private readonly brandConfig: AdminBrandConfigService,
) {}
@Get("brand")
@@ -42,7 +42,7 @@ export class AdminConfigController {
@Get("trust-content")
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
const identity = requireAdminIdentity(request);
return this.templateWorkspace.listTrustContent(identity.brandId);
return this.trustContent.listTrustContent(identity.brandId);
}
@Post("trust-content")
createTrustContent(
@@ -50,7 +50,7 @@ export class AdminConfigController {
@Body() body: CreateTrustContentDto,
): Promise<unknown> {
const identity = requireAdminIdentity(request);
return this.templateWorkspace.createTrustContent(identity.brandId, body);
return this.trustContent.createTrustContent(identity.brandId, body);
}
@Patch("trust-content/:id")
updateTrustContent(
@@ -59,7 +59,7 @@ export class AdminConfigController {
@Body() body: UpdateTrustContentDto,
): Promise<unknown> {
const identity = requireAdminIdentity(request);
return this.templateWorkspace.updateTrustContent(identity.brandId, id, body);
return this.trustContent.updateTrustContent(identity.brandId, id, body);
}
@Delete("trust-content/:id")
async deleteTrustContent(
@@ -67,6 +67,6 @@ export class AdminConfigController {
@Param("id") id: string,
): Promise<unknown> {
const identity = requireAdminIdentity(request);
return this.templateWorkspace.deleteTrustContent(identity.brandId, id);
return this.trustContent.deleteTrustContent(identity.brandId, id);
}
}
@@ -2,6 +2,11 @@ import { Module } from "@nestjs/common";
import { BookingModule } from "../booking.module.js";
import { InfrastructureModule } from "../infrastructure.module.js";
import { AdminBookingController } from "./admin-booking.controller.js";
import { AdminClientErrorController } from "./admin-client-error.controller.js";
import { AdminClientErrorService } from "./admin-client-error.service.js";
import { createClientErrorThrottleStore } from "./client-error-throttle.factory.js";
import { CLIENT_ERROR_THROTTLE_STORE } from "./client-error-throttle.store.js";
import { PrismaService } from "../../prisma.service.js";
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
import { AdminConfigController } from "./admin-config.controller.js";
import { AdminLocalUploadController } from "./admin-local-upload.controller.js";
@@ -32,6 +37,7 @@ import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-asse
AdminBookingController,
AdminTemplatePackageController,
TemplateOperationMetricsController,
AdminClientErrorController,
],
providers: [
AdminBrandConfigService,
@@ -44,6 +50,12 @@ import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-asse
AdminTemplatePreviewService,
AdminTemplatePreviewAssetsService,
TemplateOperationMetricsService,
{
provide: CLIENT_ERROR_THROTTLE_STORE,
useFactory: (prisma: PrismaService) => createClientErrorThrottleStore(prisma),
inject: [PrismaService],
},
AdminClientErrorService,
],
})
export class AdminModule {}
@@ -0,0 +1,20 @@
import type { PrismaService } from "../../prisma.service.js";
import { PostgresClientErrorThrottleStore } from "./client-error-throttle.postgres.store.js";
import {
MemoryClientErrorThrottleStore,
type ClientErrorThrottleStore,
} from "./client-error-throttle.store.js";
export function createClientErrorThrottleStore(
prisma: PrismaService,
mode = process.env.CLIENT_ERROR_THROTTLE_STORE ?? "memory",
): ClientErrorThrottleStore {
switch (mode) {
case "memory":
return new MemoryClientErrorThrottleStore();
case "postgres":
return new PostgresClientErrorThrottleStore(prisma);
default:
throw new Error(`Unsupported CLIENT_ERROR_THROTTLE_STORE: ${mode}`);
}
}
@@ -0,0 +1,94 @@
import { randomUUID } from "node:crypto";
import { HttpException } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import type { PrismaService } from "../../prisma.service.js";
import {
CLIENT_ERROR_DEDUPE_TTL_MS,
CLIENT_ERROR_RATE_LIMIT,
CLIENT_ERROR_RATE_WINDOW_MS,
type ClientErrorThrottleReport,
type ClientErrorThrottleResult,
type ClientErrorThrottleStore,
} from "./client-error-throttle.store.js";
/**
* 多实例部署使用的共享存储实现。
* 去重与限流在同一事务中执行:限流拒绝时不会留下已去重标记。
*/
export class PostgresClientErrorThrottleStore implements ClientErrorThrottleStore {
private lastCleanupAt = 0;
constructor(private readonly prisma: PrismaService) {}
async record(
report: ClientErrorThrottleReport,
now = Date.now(),
): Promise<ClientErrorThrottleResult> {
const cutoff = new Date(now - CLIENT_ERROR_DEDUPE_TTL_MS);
const windowStart = new Date(
Math.floor(now / CLIENT_ERROR_RATE_WINDOW_MS) * CLIENT_ERROR_RATE_WINDOW_MS,
);
const recordedAt = new Date(now);
let duplicate = false;
await this.prisma.$transaction(async (transaction) => {
const inserted = await transaction.$queryRaw<Array<{ id: string }>>(Prisma.sql`
INSERT INTO "ClientErrorDedupe" ("id", "subject", "errorId", "createdAt")
VALUES (${randomUUID()}, ${report.subject}, ${report.errorId}, ${recordedAt})
ON CONFLICT ("subject", "errorId") DO UPDATE SET
"createdAt" = EXCLUDED."createdAt"
WHERE "ClientErrorDedupe"."createdAt" < ${cutoff}
RETURNING "id"
`);
if (!inserted.length) {
duplicate = true;
return;
}
const rows = await transaction.$queryRaw<Array<{ count: number }>>(Prisma.sql`
INSERT INTO "ClientErrorThrottleWindow" ("subject", "windowStart", "count", "updatedAt")
VALUES (${report.subject}, ${windowStart}, 1, ${recordedAt})
ON CONFLICT ("subject") DO UPDATE SET
"count" = CASE
WHEN EXCLUDED."windowStart" > "ClientErrorThrottleWindow"."windowStart"
THEN 1
WHEN EXCLUDED."windowStart" = "ClientErrorThrottleWindow"."windowStart"
THEN LEAST("ClientErrorThrottleWindow"."count" + 1, ${CLIENT_ERROR_RATE_LIMIT + 1})
ELSE "ClientErrorThrottleWindow"."count"
END,
"windowStart" = GREATEST(
"ClientErrorThrottleWindow"."windowStart",
EXCLUDED."windowStart"
),
"updatedAt" = EXCLUDED."updatedAt"
RETURNING "count"
`);
if (Number(rows[0]?.count ?? 1) > CLIENT_ERROR_RATE_LIMIT) {
throw new HttpException("客户端错误上报过于频繁,请稍后再试", 429);
}
});
await this.cleanupIfNeeded(cutoff, windowStart, now);
return { duplicate };
}
private async cleanupIfNeeded(cutoff: Date, windowStart: Date, now: number): Promise<void> {
if (now - this.lastCleanupAt < CLIENT_ERROR_RATE_WINDOW_MS) return;
this.lastCleanupAt = now;
try {
await Promise.all([
this.prisma.clientErrorDedupe.deleteMany({ where: { createdAt: { lt: cutoff } } }),
this.prisma.clientErrorThrottleWindow.deleteMany({
where: {
windowStart: {
lt: new Date(windowStart.getTime() - CLIENT_ERROR_RATE_WINDOW_MS),
},
},
}),
]);
} catch (error) {
// 清理失败不能影响诊断上报本身,下一分钟会再次尝试。
console.warn("[api] client error throttle cleanup failed", error);
}
}
}
@@ -0,0 +1,71 @@
import { HttpException } from "@nestjs/common";
export const CLIENT_ERROR_RATE_WINDOW_MS = 60_000;
export const CLIENT_ERROR_RATE_LIMIT = 10;
export const CLIENT_ERROR_DEDUPE_TTL_MS = 10 * 60_000;
export const CLIENT_ERROR_DEDUPE_CAPACITY = 500;
export const CLIENT_ERROR_THROTTLE_STORE = Symbol("CLIENT_ERROR_THROTTLE_STORE");
export interface ClientErrorThrottleReport {
subject: string;
errorId: string;
}
export interface ClientErrorThrottleResult {
duplicate: boolean;
}
export interface ClientErrorThrottleStore {
record(report: ClientErrorThrottleReport, now?: number): Promise<ClientErrorThrottleResult>;
}
/** 单实例部署使用的进程内实现;多实例必须切换为共享存储。 */
export class MemoryClientErrorThrottleStore implements ClientErrorThrottleStore {
private readonly recentErrorIds = new Map<string, number>();
private readonly windows = new Map<string, number[]>();
record(report: ClientErrorThrottleReport, now = Date.now()): Promise<ClientErrorThrottleResult> {
this.prune(now);
const dedupeKey = `${report.subject}:${report.errorId}`;
if (this.recentErrorIds.has(dedupeKey)) return Promise.resolve({ duplicate: true });
this.assertWithinRate(report.subject, now);
this.recentErrorIds.set(dedupeKey, now);
this.trimDedupe();
return Promise.resolve({ duplicate: false });
}
private assertWithinRate(subject: string, now: number): void {
const recent = (this.windows.get(subject) ?? []).filter(
(timestamp) => now - timestamp < CLIENT_ERROR_RATE_WINDOW_MS,
);
if (recent.length >= CLIENT_ERROR_RATE_LIMIT) {
this.windows.set(subject, recent);
throw new HttpException("客户端错误上报过于频繁,请稍后再试", 429);
}
recent.push(now);
this.windows.set(subject, recent);
}
private prune(now: number): void {
for (const [key, timestamp] of this.recentErrorIds) {
if (now - timestamp >= CLIENT_ERROR_DEDUPE_TTL_MS) this.recentErrorIds.delete(key);
}
for (const [subject, timestamps] of this.windows) {
const recent = timestamps.filter(
(timestamp) => now - timestamp < CLIENT_ERROR_RATE_WINDOW_MS,
);
if (recent.length === 0) this.windows.delete(subject);
else this.windows.set(subject, recent);
}
}
private trimDedupe(): void {
while (this.recentErrorIds.size > CLIENT_ERROR_DEDUPE_CAPACITY) {
const oldest = this.recentErrorIds.keys().next();
if (oldest.done) return;
this.recentErrorIds.delete(oldest.value);
}
}
}
@@ -4,7 +4,9 @@ import { AdminMembershipGuard } from "../admin-membership.guard.js";
import { BrandReleaseApiService } from "../brand-release-api.service.js";
import { BrandReleaseService } from "../brand-release.service.js";
import { PrismaService } from "../prisma.service.js";
import { TemplateWorkspaceService } from "../template-workspace.service.js";
import { PageSchemeService } from "../template/page-scheme.service.js";
import { TemplateInstallationService } from "../template/template-installation.service.js";
import { TrustContentService } from "../template/trust-content.service.js";
import { WechatAuthService } from "../wechat-auth.js";
@Module({
@@ -15,7 +17,9 @@ import { WechatAuthService } from "../wechat-auth.js";
AdminMembershipGuard,
BrandReleaseService,
BrandReleaseApiService,
TemplateWorkspaceService,
PageSchemeService,
TemplateInstallationService,
TrustContentService,
],
exports: [
PrismaService,
@@ -24,7 +28,9 @@ import { WechatAuthService } from "../wechat-auth.js";
AdminMembershipGuard,
BrandReleaseService,
BrandReleaseApiService,
TemplateWorkspaceService,
PageSchemeService,
TemplateInstallationService,
TrustContentService,
],
})
export class InfrastructureModule {}
@@ -14,7 +14,8 @@ import type {
CreateBrandMemberDto,
UpdateBrandMemberDto,
} from "../../admin.dto.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { PageSchemeService } from "../../template/page-scheme.service.js";
import { TemplateInstallationService } from "../../template/template-installation.service.js";
type AdminIdentity = { subject: string; brandId: string; tokenVersion?: number };
@@ -22,11 +23,12 @@ type AdminIdentity = { subject: string; brandId: string; tokenVersion?: number }
export class TenantService {
constructor(
private readonly prisma: PrismaService,
private readonly templateWorkspace: TemplateWorkspaceService,
private readonly pageSchemes: PageSchemeService,
private readonly templateInstallations: TemplateInstallationService,
) {}
async getCreationOptions() {
const catalog = await this.templateWorkspace.getPageSchemeCatalog();
const catalog = await this.pageSchemes.getPageSchemeCatalog();
// 创建品牌只应从每个页面方案的最新已发布版本开始;旧版本仍可在页面方案页显式切换。
return {
...catalog,
@@ -40,7 +42,7 @@ export class TenantService {
const name = body.name.trim();
const slug = body.slug.trim();
if (!name || !slug) throw new BadRequestException("品牌名称和小程序地址标识不能为空");
const packageVersion = await this.templateWorkspace.resolveInstallablePackageVersion(
const packageVersion = await this.templateInstallations.resolveInstallablePackageVersion(
body.businessType,
body.templatePackageVersionId,
);
@@ -2,24 +2,28 @@ import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { RollbackTemplateDto, UpgradeTemplateDto } from "../../admin.dto.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { PageSchemeService } from "../../template/page-scheme.service.js";
import { TemplateInstallationService } from "../../template/template-installation.service.js";
import { requireAdminIdentity } from "../../admin-access.identity.js";
@AdminBrand()
@Controller("admin/workspace")
class AdminTemplateController {
constructor(private readonly templateWorkspace: TemplateWorkspaceService) {}
constructor(
private readonly pageSchemes: PageSchemeService,
private readonly templateInstallations: TemplateInstallationService,
) {}
@AdminRoles(["owner", "admin", "platform-admin"])
@Get("template/options")
options(@Req() request: FastifyRequest): Promise<unknown> {
return this.templateWorkspace.getPageSchemeOptions(requireAdminIdentity(request).brandId);
return this.pageSchemes.getPageSchemeOptions(requireAdminIdentity(request).brandId);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@Get("template/preview")
preview(@Req() request: FastifyRequest): Promise<unknown> {
return this.templateWorkspace.preview(requireAdminIdentity(request).brandId);
return this.templateInstallations.preview(requireAdminIdentity(request).brandId);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@@ -30,7 +34,7 @@ class AdminTemplateController {
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
return this.templateWorkspace.upgrade(identity.brandId, body, identity.subject, requestId);
return this.templateInstallations.upgrade(identity.brandId, body, identity.subject, requestId);
}
@AdminRoles(["owner", "admin", "platform-admin"])
@@ -41,7 +45,7 @@ class AdminTemplateController {
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
return this.templateWorkspace.rollback(identity.brandId, identity.subject, body, requestId);
return this.templateInstallations.rollback(identity.brandId, identity.subject, body, requestId);
}
}
@@ -8,19 +8,19 @@ import {
validateCapabilityConfig,
} from "@personal-brand/config";
import { PrismaService } from "../../prisma.service.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { TemplateInstallationService } from "../../template/template-installation.service.js";
import type { UpdateCapabilityInstallationDto } from "../../admin.dto.js";
@Injectable()
export class AdminWorkspaceCapabilitiesService {
constructor(
private readonly prisma: PrismaService,
private readonly templateWorkspace: TemplateWorkspaceService,
private readonly templateInstallations: TemplateInstallationService,
) {}
async list(brandId: string) {
const [templateKey, installations] = await Promise.all([
this.templateWorkspace.getEffectiveTemplateKey(brandId),
this.templateInstallations.getEffectiveTemplateKey(brandId),
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
]);
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
@@ -54,7 +54,7 @@ export class AdminWorkspaceCapabilitiesService {
body: UpdateCapabilityInstallationDto,
) {
const template = getBrandTemplate(
await this.templateWorkspace.getEffectiveTemplateKey(brandId),
await this.templateInstallations.getEffectiveTemplateKey(brandId),
);
if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins))
throw new BadRequestException("能力未被当前模板声明");
@@ -2,7 +2,7 @@ import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
import { Controller, Get, Post, Body, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { InstallTemplateDto, SelectTemplateVersionDto } from "../../admin.dto.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { TemplateInstallationService } from "../../template/template-installation.service.js";
import { requireAdminIdentity } from "../../admin-access.identity.js";
import { AdminWorkspaceService } from "./admin-workspace.service.js";
@@ -11,7 +11,7 @@ import { AdminWorkspaceService } from "./admin-workspace.service.js";
class AdminWorkspacePreviewController {
constructor(
private readonly workspaceService: AdminWorkspaceService,
private readonly templateWorkspace: TemplateWorkspaceService,
private readonly templateInstallations: TemplateInstallationService,
) {}
@Get()
@@ -32,7 +32,7 @@ class AdminWorkspacePreviewController {
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
return this.templateWorkspace.install(
return this.templateInstallations.install(
identity.brandId,
body.templateKey,
body.templatePackageVersionId,
@@ -49,7 +49,7 @@ class AdminWorkspacePreviewController {
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
return this.templateWorkspace.selectVersion(
return this.templateInstallations.selectVersion(
identity.brandId,
body,
identity.subject,
+20
View File
@@ -0,0 +1,20 @@
const PLACEHOLDER_PATTERN = /(replace-with|change-me|changeme|^your[-_ ]|example|placeholder)/i;
/** 判断值是否仍是仓库示例中的占位符,而不是真实随机密钥。 */
export function isPlaceholderSecret(value: string): boolean {
return PLACEHOLDER_PATTERN.test(value.trim());
}
/**
* 生产环境启动前的快速失败校验。
* 本地开发允许占位符,避免示例 `.env` 阻塞调试;生产环境必须使用真实随机值。
*/
export function assertProductionSecret(
value: string | undefined,
nodeEnv: string | undefined = process.env.NODE_ENV,
): void {
if (nodeEnv !== "production") return;
const secret = value?.trim() ?? "";
if (secret.length < 32) throw new Error("SESSION_SECRET 必须是至少 32 位的随机值");
if (isPlaceholderSecret(secret)) throw new Error("SESSION_SECRET 不能使用示例占位符");
}
@@ -0,0 +1,114 @@
import type { TemplatePackageVersion } from "@prisma/client";
export function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
export function manifestRecords(value: unknown): Record<string, unknown>[] {
return Array.isArray(value)
? value.filter((item): item is Record<string, unknown> =>
Boolean(item && typeof item === "object" && !Array.isArray(item)),
)
: [];
}
export function stringList(value: unknown): string[] {
return Array.isArray(value)
? value.filter((item): item is string => typeof item === "string")
: [];
}
export function hasBindingValue(config: Record<string, unknown>, binding: unknown): boolean {
if (typeof binding !== "string" || !binding.startsWith("brand.config.")) return false;
const value = binding
.slice("brand.config.".length)
.split(".")
.reduce<unknown>((current, key) => record(current)[key], config);
return value !== undefined && value !== null && value !== "";
}
export function compareRecords(current: Record<string, unknown>, target: Record<string, unknown>) {
const currentKeys = Object.keys(current);
const targetKeys = Object.keys(target);
return {
added: targetKeys
.filter((key) => !(key in current))
.map((key) => ({ key, target: target[key] })),
removed: currentKeys
.filter((key) => !(key in target))
.map((key) => ({ key, current: current[key] })),
changed: targetKeys
.filter(
(key) => key in current && JSON.stringify(current[key]) !== JSON.stringify(target[key]),
)
.map((key) => ({ key, current: current[key], target: target[key] })),
};
}
export function compareKeyedRecords(
current: Record<string, unknown>[],
target: Record<string, unknown>[],
) {
const currentByKey = new Map(
current
.filter((item) => typeof item.key === "string")
.map((item) => [item.key as string, item]),
);
const targetByKey = new Map(
target.filter((item) => typeof item.key === "string").map((item) => [item.key as string, item]),
);
return {
added: [...targetByKey].filter(([key]) => !currentByKey.has(key)).map(([, item]) => item),
removed: [...currentByKey].filter(([key]) => !targetByKey.has(key)).map(([, item]) => item),
changed: [...targetByKey].flatMap(([key, item]) => {
const previous = currentByKey.get(key);
return previous && JSON.stringify(previous) !== JSON.stringify(item)
? [{ key, current: previous, target: item }]
: [];
}),
};
}
export function compareFiles(
current: Record<string, unknown>[],
target: Record<string, unknown>[],
) {
const currentByPath = new Map(
current
.filter((item) => typeof item.path === "string")
.map((item) => [item.path as string, item]),
);
const targetByPath = new Map(
target
.filter((item) => typeof item.path === "string")
.map((item) => [item.path as string, item]),
);
const available = currentByPath.size > 0 && targetByPath.size > 0;
return {
available,
...(available
? {
added: [...targetByPath]
.filter(([path]) => !currentByPath.has(path))
.map(([, item]) => item),
removed: [...currentByPath]
.filter(([path]) => !targetByPath.has(path))
.map(([, item]) => item),
changed: [...targetByPath].flatMap(([path, item]) => {
const previous = currentByPath.get(path);
return previous && previous.sha256 !== item.sha256
? [{ path, current: previous, target: item }]
: [];
}),
}
: { reason: "版本验证报告未包含完整文件清单" }),
};
}
export function readPackageFiles(
version: Pick<TemplatePackageVersion, "validationReport">,
): Record<string, unknown>[] {
return manifestRecords(record(version.validationReport).files);
}
@@ -0,0 +1,105 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import {
type BrandTemplateKey,
brandTemplateKeys,
getBrandTemplate,
getVisualTemplate,
getVisualTemplateManifest,
isVisualTemplateCompatible,
validateTemplatePackageManifest,
} from "@personal-brand/config";
import { PrismaService } from "../prisma.service.js";
import { compareTemplateVersions } from "../template-version-order.js";
import { record } from "./manifest-diff.helpers.js";
@Injectable()
export class PageSchemeService {
constructor(private readonly prisma: PrismaService) {}
async getPageSchemeCatalog() {
const versions = await this.prisma.templatePackageVersion.findMany({
where: { status: "published" },
orderBy: [{ importedAt: "desc" }, { createdAt: "desc" }],
});
const candidates = versions.flatMap((version) => {
const manifest = record(version.manifestSnapshot);
const visualTemplateKey = manifest.visualTemplateKey;
if (
manifest.packageKey !== version.packageKey ||
manifest.version !== version.version ||
typeof visualTemplateKey !== "string" ||
visualTemplateKey !== version.packageKey
)
return [];
const visualTemplate = getVisualTemplate(visualTemplateKey);
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
if (!visualTemplate || !visualManifest) return [];
const supportedBusinessTypes = Array.isArray(manifest.supportedIndustryTemplates)
? manifest.supportedIndustryTemplates.filter(
(value): value is BrandTemplateKey =>
typeof value === "string" &&
brandTemplateKeys.includes(value) &&
Boolean(getBrandTemplate(value)),
)
: [];
if (
supportedBusinessTypes.length === 0 ||
supportedBusinessTypes.some(
(businessType) => !isVisualTemplateCompatible(visualTemplate, businessType),
) ||
validateTemplatePackageManifest(manifest).length > 0
)
return [];
return [
{
templatePackageVersionId: version.id,
packageKey: version.packageKey,
name: version.displayName,
description: visualManifest.description,
version: version.version,
supportedBusinessTypes,
},
];
});
const latestByPackage = new Map<string, string>();
for (const candidate of candidates) {
const latestVersion = latestByPackage.get(candidate.packageKey);
if (!latestVersion || compareTemplateVersions(candidate.version, latestVersion) > 0) {
latestByPackage.set(candidate.packageKey, candidate.version);
}
}
const pageSchemes = candidates.map(({ packageKey, ...candidate }) => ({
...candidate,
isLatestForPackage: latestByPackage.get(packageKey) === candidate.version,
}));
return {
businesses: brandTemplateKeys.map((key) => {
const template = getBrandTemplate(key);
if (!template) throw new BadRequestException("业务类型配置不完整");
return { key, name: template.name, description: template.description };
}),
pageSchemes,
};
}
async getPageSchemeOptions(brandId: string) {
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true },
});
const template = brand ? getBrandTemplate(brand.templateKey) : undefined;
if (!brand || !template) throw new BadRequestException("品牌业务类型无效");
const catalog = await this.getPageSchemeCatalog();
return {
business: {
key: template.key,
name: template.name,
description: template.description,
},
pageSchemes: catalog.pageSchemes.filter((scheme) =>
scheme.supportedBusinessTypes.includes(template.key),
),
};
}
}
@@ -3,7 +3,6 @@ import type { TemplatePackageVersion } from "@prisma/client";
import { Prisma } from "@prisma/client";
import {
type BrandTemplateKey,
brandTemplateKeys,
getBrandTemplate,
getVisualTemplate,
getVisualTemplateManifest,
@@ -11,157 +10,25 @@ import {
validateTemplatePackageManifest,
} from "@personal-brand/config";
import type { TemplatePackageManifest } from "@personal-brand/config";
import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.js";
import type { RollbackTemplateDto, UpgradeTemplateDto } from "./admin.dto.js";
import { PrismaService } from "./prisma.service.js";
import { recordTemplateOperationFailure } from "./modules/admin/template-operation-failure.js";
import { compareTemplateVersions, latestTemplateVersion } from "./template-version-order.js";
import type { RollbackTemplateDto, UpgradeTemplateDto } from "../admin.dto.js";
import { PrismaService } from "../prisma.service.js";
import { recordTemplateOperationFailure } from "../modules/admin/template-operation-failure.js";
import { latestTemplateVersion } from "../template-version-order.js";
import {
compareFiles,
compareKeyedRecords,
compareRecords,
hasBindingValue,
manifestRecords,
readPackageFiles,
record,
stringList,
} from "./manifest-diff.helpers.js";
@Injectable()
export class TemplateWorkspaceService {
export class TemplateInstallationService {
constructor(private readonly prisma: PrismaService) {}
async getPageSchemeCatalog() {
const versions = await this.prisma.templatePackageVersion.findMany({
where: { status: "published" },
orderBy: [{ importedAt: "desc" }, { createdAt: "desc" }],
});
const candidates = versions.flatMap((version) => {
const manifest = record(version.manifestSnapshot);
const visualTemplateKey = manifest.visualTemplateKey;
if (
manifest.packageKey !== version.packageKey ||
manifest.version !== version.version ||
typeof visualTemplateKey !== "string" ||
visualTemplateKey !== version.packageKey
)
return [];
const visualTemplate = getVisualTemplate(visualTemplateKey);
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
if (!visualTemplate || !visualManifest) return [];
const supportedBusinessTypes = Array.isArray(manifest.supportedIndustryTemplates)
? manifest.supportedIndustryTemplates.filter(
(value): value is BrandTemplateKey =>
typeof value === "string" &&
brandTemplateKeys.includes(value) &&
Boolean(getBrandTemplate(value)),
)
: [];
if (
supportedBusinessTypes.length === 0 ||
supportedBusinessTypes.some(
(businessType) => !isVisualTemplateCompatible(visualTemplate, businessType),
) ||
validateTemplatePackageManifest(manifest).length > 0
)
return [];
return [
{
templatePackageVersionId: version.id,
packageKey: version.packageKey,
name: version.displayName,
description: visualManifest.description,
version: version.version,
supportedBusinessTypes,
},
];
});
const latestByPackage = new Map<string, string>();
for (const candidate of candidates) {
const latestVersion = latestByPackage.get(candidate.packageKey);
if (!latestVersion || compareTemplateVersions(candidate.version, latestVersion) > 0) {
latestByPackage.set(candidate.packageKey, candidate.version);
}
}
const pageSchemes = candidates.map(({ packageKey, ...candidate }) => ({
...candidate,
isLatestForPackage: latestByPackage.get(packageKey) === candidate.version,
}));
return {
businesses: brandTemplateKeys.map((key) => {
const template = getBrandTemplate(key);
if (!template) throw new BadRequestException("业务类型配置不完整");
return { key, name: template.name, description: template.description };
}),
pageSchemes,
};
}
async getPageSchemeOptions(brandId: string) {
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true },
});
const template = brand ? getBrandTemplate(brand.templateKey) : undefined;
if (!brand || !template) throw new BadRequestException("品牌业务类型无效");
const catalog = await this.getPageSchemeCatalog();
return {
business: {
key: template.key,
name: template.name,
description: template.description,
},
pageSchemes: catalog.pageSchemes.filter((scheme) =>
scheme.supportedBusinessTypes.includes(template.key),
),
};
}
async getTrustContentTypes(brandId: string): Promise<string[]> {
const installation = await this.prisma.brandTemplateInstallation.findUnique({
where: { brandId },
include: { templatePackageVersion: true },
});
if (!installation?.templatePackageVersion)
throw new BadRequestException("品牌没有锁定精确视觉模板包版本");
const manifest = record(
installation.templatePackageVersion.manifestSnapshot,
) as unknown as TemplatePackageManifest;
if (validateTemplatePackageManifest(manifest).length)
throw new BadRequestException("当前安装的模板包不符合统一模板契约");
return manifest.trustContentTypes?.map((item) => item.type) ?? [];
}
async createTrustContent(brandId: string, body: CreateTrustContentDto) {
if (!(await this.getTrustContentTypes(brandId)).includes(body.type))
throw new BadRequestException("当前模板不支持此信任内容类型");
const { config, ...fields } = body;
return this.prisma.trustContent.create({
data: {
...fields,
brandId,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
async updateTrustContent(brandId: string, id: string, body: UpdateTrustContentDto) {
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
if (!item) throw new BadRequestException("信任内容不存在");
if (body.type !== undefined && !(await this.getTrustContentTypes(brandId)).includes(body.type))
throw new BadRequestException("当前模板不支持此信任内容类型");
const { config, ...fields } = body;
return this.prisma.trustContent.update({
where: { id },
data: {
...fields,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
listTrustContent(brandId: string) {
return this.prisma.trustContent.findMany({
where: { brandId },
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
});
}
async deleteTrustContent(brandId: string, id: string) {
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
if (!item) throw new BadRequestException("信任内容不存在");
await this.prisma.trustContent.delete({ where: { id } });
return { deleted: true };
}
async getEffectiveTemplateKey(brandId: string): Promise<BrandTemplateKey> {
const [brand, installation] = await Promise.all([
this.prisma.brandProfile.findUnique({
@@ -759,113 +626,3 @@ export class TemplateWorkspaceService {
};
}
}
function readPackageFiles(
version: Pick<TemplatePackageVersion, "validationReport">,
): Record<string, unknown>[] {
return manifestRecords(record(version.validationReport).files);
}
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
function manifestRecords(value: unknown): Record<string, unknown>[] {
return Array.isArray(value)
? value.filter((item): item is Record<string, unknown> =>
Boolean(item && typeof item === "object" && !Array.isArray(item)),
)
: [];
}
function stringList(value: unknown): string[] {
return Array.isArray(value)
? value.filter((item): item is string => typeof item === "string")
: [];
}
function hasBindingValue(config: Record<string, unknown>, binding: unknown): boolean {
if (typeof binding !== "string" || !binding.startsWith("brand.config.")) return false;
const value = binding
.slice("brand.config.".length)
.split(".")
.reduce<unknown>((current, key) => record(current)[key], config);
return value !== undefined && value !== null && value !== "";
}
function compareRecords(current: Record<string, unknown>, target: Record<string, unknown>) {
const currentKeys = Object.keys(current);
const targetKeys = Object.keys(target);
return {
added: targetKeys
.filter((key) => !(key in current))
.map((key) => ({ key, target: target[key] })),
removed: currentKeys
.filter((key) => !(key in target))
.map((key) => ({ key, current: current[key] })),
changed: targetKeys
.filter(
(key) => key in current && JSON.stringify(current[key]) !== JSON.stringify(target[key]),
)
.map((key) => ({ key, current: current[key], target: target[key] })),
};
}
function compareKeyedRecords(
current: Record<string, unknown>[],
target: Record<string, unknown>[],
) {
const currentByKey = new Map(
current
.filter((item) => typeof item.key === "string")
.map((item) => [item.key as string, item]),
);
const targetByKey = new Map(
target.filter((item) => typeof item.key === "string").map((item) => [item.key as string, item]),
);
return {
added: [...targetByKey].filter(([key]) => !currentByKey.has(key)).map(([, item]) => item),
removed: [...currentByKey].filter(([key]) => !targetByKey.has(key)).map(([, item]) => item),
changed: [...targetByKey].flatMap(([key, item]) => {
const previous = currentByKey.get(key);
return previous && JSON.stringify(previous) !== JSON.stringify(item)
? [{ key, current: previous, target: item }]
: [];
}),
};
}
function compareFiles(current: Record<string, unknown>[], target: Record<string, unknown>[]) {
const currentByPath = new Map(
current
.filter((item) => typeof item.path === "string")
.map((item) => [item.path as string, item]),
);
const targetByPath = new Map(
target
.filter((item) => typeof item.path === "string")
.map((item) => [item.path as string, item]),
);
const available = currentByPath.size > 0 && targetByPath.size > 0;
return {
available,
...(available
? {
added: [...targetByPath]
.filter(([path]) => !currentByPath.has(path))
.map(([, item]) => item),
removed: [...currentByPath]
.filter(([path]) => !targetByPath.has(path))
.map(([, item]) => item),
changed: [...targetByPath].flatMap(([path, item]) => {
const previous = currentByPath.get(path);
return previous && previous.sha256 !== item.sha256
? [{ path, current: previous, target: item }]
: [];
}),
}
: { reason: "版本验证报告未包含完整文件清单" }),
};
}
@@ -0,0 +1,69 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { validateTemplatePackageManifest } from "@personal-brand/config";
import type { TemplatePackageManifest } from "@personal-brand/config";
import type { CreateTrustContentDto, UpdateTrustContentDto } from "../admin.dto.js";
import { PrismaService } from "../prisma.service.js";
import { record } from "./manifest-diff.helpers.js";
@Injectable()
export class TrustContentService {
constructor(private readonly prisma: PrismaService) {}
async getTrustContentTypes(brandId: string): Promise<string[]> {
const installation = await this.prisma.brandTemplateInstallation.findUnique({
where: { brandId },
include: { templatePackageVersion: true },
});
if (!installation?.templatePackageVersion)
throw new BadRequestException("品牌没有锁定精确视觉模板包版本");
const manifest = record(
installation.templatePackageVersion.manifestSnapshot,
) as unknown as TemplatePackageManifest;
if (validateTemplatePackageManifest(manifest).length)
throw new BadRequestException("当前安装的模板包不符合统一模板契约");
return manifest.trustContentTypes?.map((item) => item.type) ?? [];
}
async createTrustContent(brandId: string, body: CreateTrustContentDto) {
if (!(await this.getTrustContentTypes(brandId)).includes(body.type))
throw new BadRequestException("当前模板不支持此信任内容类型");
const { config, ...fields } = body;
return this.prisma.trustContent.create({
data: {
...fields,
brandId,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
async updateTrustContent(brandId: string, id: string, body: UpdateTrustContentDto) {
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
if (!item) throw new BadRequestException("信任内容不存在");
if (body.type !== undefined && !(await this.getTrustContentTypes(brandId)).includes(body.type))
throw new BadRequestException("当前模板不支持此信任内容类型");
const { config, ...fields } = body;
return this.prisma.trustContent.update({
where: { id },
data: {
...fields,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
listTrustContent(brandId: string) {
return this.prisma.trustContent.findMany({
where: { brandId },
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
});
}
async deleteTrustContent(brandId: string, id: string) {
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
if (!item) throw new BadRequestException("信任内容不存在");
await this.prisma.trustContent.delete({ where: { id } });
return { deleted: true };
}
}
@@ -0,0 +1,74 @@
import assert from "node:assert/strict";
import test from "node:test";
import { ForbiddenException } from "@nestjs/common";
import { AdminAccessService } from "../src/admin-access.service.js";
import { signIdentity } from "../src/auth.js";
process.env.SESSION_SECRET = "admin-access-service-test-secret-1234567890";
type RequestFixture = {
headers: { authorization: string };
};
function requestFixture(subject = "admin-1", brandId = "brand-1"): RequestFixture {
return {
headers: {
authorization: `Bearer ${signIdentity({ subject, brandId, role: "admin" })}`,
},
};
}
function accessFixture() {
const calls = { adminUser: 0, membership: 0 };
const prisma = {
adminUser: {
findUnique: async () => {
calls.adminUser += 1;
return {
isEnabled: true,
mustChangePassword: false,
tokenVersion: 0,
platformTemplateRole: "none",
};
},
},
brandMembership: {
findUnique: async () => {
calls.membership += 1;
return { role: "owner", isEnabled: true };
},
},
};
return { calls, prisma };
}
test("同一请求内 Guard 与 Controller 复用访问校验结果", async () => {
const { calls, prisma } = accessFixture();
const service = new AdminAccessService(prisma as never);
const request = requestFixture();
const [guardResult, controllerResult] = await Promise.all([
service.requireBrand(request as never),
service.requireBrand(request as never),
]);
assert.deepEqual(guardResult, controllerResult);
await service.requireRole(request as never, ["owner"]);
await assert.rejects(
service.requireTemplateAdmin(request as never),
(error: unknown) => error instanceof ForbiddenException,
);
assert.equal(calls.adminUser, 1);
assert.equal(calls.membership, 1);
});
test("不同请求之间不共享访问校验缓存", async () => {
const { calls, prisma } = accessFixture();
const service = new AdminAccessService(prisma as never);
await service.requireBrand(requestFixture("admin-1") as never);
await service.requireBrand(requestFixture("admin-2") as never);
assert.equal(calls.adminUser, 2);
assert.equal(calls.membership, 2);
});
@@ -0,0 +1,58 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { HttpException } from "@nestjs/common";
import { AdminClientErrorService } from "../src/modules/admin/admin-client-error.service.js";
import { MemoryClientErrorThrottleStore } from "../src/modules/admin/client-error-throttle.store.js";
function report(errorId: string, subject = "admin:user-1") {
return {
subject,
brandId: "brand-1",
errorId,
message: "boom",
route: "/admin/trust",
requestId: "req-1",
userAgent: "test-agent",
};
}
function service() {
return new AdminClientErrorService(new MemoryClientErrorThrottleStore());
}
test("首次上报记录,相同 errorId 在窗口内按管理员去重", async () => {
const errors = service();
assert.deepEqual(await errors.record(report("admin-error-1")), {
received: true,
duplicate: false,
});
assert.deepEqual(await errors.record(report("admin-error-1")), {
received: true,
duplicate: true,
});
// 不同管理员使用相同 errorId 时互不影响
assert.deepEqual(await errors.record(report("admin-error-1", "admin:user-2")), {
received: true,
duplicate: false,
});
});
test("同一管理员 60 秒内最多接受 10 条不同错误", async () => {
const errors = service();
for (let index = 0; index < 10; index += 1) {
assert.deepEqual(await errors.record(report(`admin-rate-${index}`)), {
received: true,
duplicate: false,
});
}
await assert.rejects(errors.record(report("admin-rate-overflow")), (error) => {
assert.ok(error instanceof HttpException);
assert.equal(error.getStatus(), 429);
return true;
});
// 另一个管理员不受影响
assert.deepEqual(await errors.record(report("admin-rate-other", "admin:user-2")), {
received: true,
duplicate: false,
});
});
@@ -0,0 +1,24 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { createClientErrorThrottleStore } from "../src/modules/admin/client-error-throttle.factory.js";
import { PostgresClientErrorThrottleStore } from "../src/modules/admin/client-error-throttle.postgres.store.js";
import { MemoryClientErrorThrottleStore } from "../src/modules/admin/client-error-throttle.store.js";
const prisma = {} as never;
test("默认使用进程内存储", () => {
const store = createClientErrorThrottleStore(prisma, "memory");
assert.ok(store instanceof MemoryClientErrorThrottleStore);
});
test("多实例可切换为 Postgres 共享存储", () => {
const store = createClientErrorThrottleStore(prisma, "postgres");
assert.ok(store instanceof PostgresClientErrorThrottleStore);
});
test("未知存储模式在启动时快速失败", () => {
assert.throws(
() => createClientErrorThrottleStore(prisma, "redis"),
/Unsupported CLIENT_ERROR_THROTTLE_STORE/,
);
});
+188
View File
@@ -12,6 +12,11 @@ import { createApp } from "../dist/main.js";
import { readIdentity, signIdentity } from "../dist/auth.js";
import { WechatAuthService } from "../dist/wechat-auth.js";
import { AdminMiniAppReleaseService } from "../dist/modules/admin/admin-miniapp-release.service.js";
import { PostgresClientErrorThrottleStore } from "../dist/modules/admin/client-error-throttle.postgres.store.js";
import {
CLIENT_ERROR_DEDUPE_TTL_MS,
CLIENT_ERROR_RATE_WINDOW_MS,
} from "../dist/modules/admin/client-error-throttle.store.js";
let app;
const prisma = new PrismaClient();
@@ -1892,6 +1897,124 @@ async function request(url, options = {}) {
});
}
test("admin client error reports are authenticated, validated, and deduplicated", async () => {
await assertProtectedRouteBoundary("/admin/client-errors", {
method: "POST",
payload: { errorId: "admin-boundary-check", message: "boom", route: "/admin/publication" },
});
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
assert.equal(login.statusCode, 201);
const headers = { authorization: `Bearer ${sessionToken(login)}` };
const errorId = `admin-it-${Date.now().toString(36)}`;
const payload = {
errorId,
message: "Cannot read properties of null (reading 'type')",
route: "/admin/trust?tab=1",
componentStack: "at TrustContentPage",
};
const first = await request("/admin/client-errors", { method: "POST", headers, payload });
assert.equal(first.statusCode, 201);
assert.deepEqual(JSON.parse(first.body), { received: true, duplicate: false });
const duplicate = await request("/admin/client-errors", { method: "POST", headers, payload });
assert.equal(duplicate.statusCode, 201);
assert.deepEqual(JSON.parse(duplicate.body), { received: true, duplicate: true });
const invalid = await request("/admin/client-errors", {
method: "POST",
headers,
payload: { errorId: "bad", message: "", route: "no-slash" },
});
assert.equal(invalid.statusCode, 400);
});
test("postgres client error store deduplicates and rate limits across instances", async () => {
const storeA = new PostgresClientErrorThrottleStore(prisma);
const storeB = new PostgresClientErrorThrottleStore(prisma);
const subjectPrefix = `pg-client-error-${randomUUID()}`;
const dedupeSubject = `${subjectPrefix}-dedupe`;
const concurrentSubject = `${subjectPrefix}-concurrent`;
const rateSubject = `${subjectPrefix}-rate`;
const lateSubject = `${subjectPrefix}-late`;
const now = Date.now();
try {
assert.deepEqual(await storeA.record({ subject: dedupeSubject, errorId: "same" }, now), {
duplicate: false,
});
assert.deepEqual(await storeB.record({ subject: dedupeSubject, errorId: "same" }, now), {
duplicate: true,
});
assert.deepEqual(
await storeB.record(
{ subject: dedupeSubject, errorId: "same" },
now + CLIENT_ERROR_DEDUPE_TTL_MS + 1_000,
),
{ duplicate: false },
);
const concurrent = await Promise.all(
Array.from({ length: 6 }, (_, index) =>
(index % 2 === 0 ? storeA : storeB).record(
{ subject: concurrentSubject, errorId: "concurrent-same" },
now,
),
),
);
assert.equal(concurrent.filter((result) => !result.duplicate).length, 1);
for (let index = 0; index < 10; index += 1) {
const store = index % 2 === 0 ? storeA : storeB;
assert.deepEqual(
await store.record({ subject: rateSubject, errorId: `rate-${index}` }, now),
{ duplicate: false },
);
}
await assert.rejects(
storeB.record({ subject: rateSubject, errorId: "rate-overflow" }, now),
(error) => error.getStatus?.() === 429,
);
assert.deepEqual(
await storeA.record(
{ subject: rateSubject, errorId: "rate-next-window" },
now + CLIENT_ERROR_RATE_WINDOW_MS,
),
{ duplicate: false },
);
// 旧窗口的迟到请求不得把窗口指针回拨,否则会额外放行一整窗口。
await storeA.record(
{ subject: lateSubject, errorId: "late-first" },
now + CLIENT_ERROR_RATE_WINDOW_MS,
);
await storeB.record({ subject: lateSubject, errorId: "late-old" }, now);
for (let index = 0; index < 9; index += 1) {
assert.deepEqual(
await storeA.record(
{ subject: lateSubject, errorId: `late-next-${index}` },
now + CLIENT_ERROR_RATE_WINDOW_MS,
),
{ duplicate: false },
);
}
await assert.rejects(
storeB.record(
{ subject: lateSubject, errorId: "late-overflow" },
now + CLIENT_ERROR_RATE_WINDOW_MS,
),
(error) => error.getStatus?.() === 429,
);
} finally {
const subjects = [dedupeSubject, concurrentSubject, rateSubject, lateSubject];
await prisma.clientErrorDedupe.deleteMany({ where: { subject: { in: subjects } } });
await prisma.clientErrorThrottleWindow.deleteMany({ where: { subject: { in: subjects } } });
}
});
async function assertProtectedRouteBoundary(url, options = {}) {
const { method = "GET", payload, forbiddenRole = "customer", headers = {} } = options;
const requestOptions = payload === undefined ? { method, headers } : { method, headers, payload };
@@ -5087,6 +5210,71 @@ test("disabled brand membership blocks existing admin token", async () => {
}
});
test("booking endpoints share the brand access policy", async () => {
const username = `booking-policy-${randomUUID()}`;
const password = "booking-policy-password-123";
const user = await prisma.adminUser.create({
data: {
username,
passwordHash: await bcrypt.hash(password, 12),
displayName: "预订策略测试管理员",
mustChangePassword: true,
},
});
const membership = await prisma.brandMembership.create({
data: { brandId, adminUserId: user.id, role: "admin", isEnabled: true },
});
try {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username, password },
});
assert.equal(login.statusCode, 201, login.body);
const headers = { authorization: `Bearer ${sessionToken(login)}` };
const routes = [
{ method: "GET", url: "/admin/bookings" },
{ method: "GET", url: "/admin/bookings/unread-count" },
{ method: "GET", url: "/admin/bookings/tags" },
{ method: "POST", url: "/admin/bookings/tags", payload: { name: "策略测试标签" } },
];
// 初始密码未修改时,预订路由必须与其他后台路由一样被拒绝。
for (const route of routes) {
const response = await request(route.url, {
method: route.method,
headers,
...(route.payload ? { payload: route.payload } : {}),
});
assert.equal(response.statusCode, 403, `${route.method} ${route.url}: ${response.body}`);
}
// 品牌成员被停用后,同一 token 也不能再访问预订数据。
await prisma.adminUser.update({ where: { id: user.id }, data: { mustChangePassword: false } });
const changed = await request("/admin/session/login", {
method: "POST",
payload: { username, password },
});
assert.equal(changed.statusCode, 201, changed.body);
const activeHeaders = { authorization: `Bearer ${sessionToken(changed)}` };
assert.equal((await request("/admin/bookings", { headers: activeHeaders })).statusCode, 200);
await prisma.brandMembership.update({
where: { id: membership.id },
data: { isEnabled: false },
});
for (const route of routes) {
const response = await request(route.url, {
method: route.method,
headers: activeHeaders,
...(route.payload ? { payload: route.payload } : {}),
});
assert.equal(response.statusCode, 403, `${route.method} ${route.url}: ${response.body}`);
}
} finally {
await prisma.adminUser.delete({ where: { id: user.id } });
}
});
test("admin can read and update brand and service configuration", async () => {
const login = await request("/admin/session/login", {
method: "POST",
+7
View File
@@ -657,6 +657,13 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
authorizationTest: null,
successTest: "wechat login creates a customer session for the requested brand",
},
{
method: "POST",
path: "/admin/client-errors",
auth: "brand",
authorizationTest: "admin client error reports are authenticated, validated, and deduplicated",
successTest: "admin client error reports are authenticated, validated, and deduplicated",
},
{
method: "PUT",
path: "/admin/uploads/local",
+37
View File
@@ -0,0 +1,37 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { assertProductionSecret, isPlaceholderSecret } from "../src/runtime-config.js";
test("production rejects missing or short session secrets", () => {
assert.throws(() => assertProductionSecret(undefined, "production"), /至少 32 位/);
assert.throws(() => assertProductionSecret("short-secret", "production"), /至少 32 位/);
});
test("production rejects example placeholder secrets", () => {
assert.throws(
() => assertProductionSecret("replace-with-at-least-32-random-characters", "production"),
/示例占位符/,
);
assert.throws(
() => assertProductionSecret("change-me-now-1234567890-abcdefghij", "production"),
/示例占位符/,
);
});
test("production accepts a strong random secret", () => {
assert.doesNotThrow(() =>
assertProductionSecret("s3cure-Random-Value-0123456789-abcdefghij", "production"),
);
});
test("development keeps working with the example placeholder", () => {
assert.doesNotThrow(() =>
assertProductionSecret("replace-with-a-long-random-value", "development"),
);
});
test("placeholder detection covers documented example values", () => {
assert.equal(isPlaceholderSecret("replace-with-a-long-random-value"), true);
assert.equal(isPlaceholderSecret(" YOur-secret-value "), true);
assert.equal(isPlaceholderSecret("s3cure-Random-Value-0123456789-abcdefghij"), false);
});
@@ -45,7 +45,6 @@ async function main() {
.filter((entry) => entry.isDirectory() && entry.name !== targetMigration)
.map((entry) => entry.name)
.sort();
assert.equal(migrationDirs.at(-1), "20261019100000_remove_brand_profile_defaults");
await admin.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
createdSchema = true;
+7
View File
@@ -0,0 +1,7 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"lint": { "dependsOn": ["build", "^build"] }
}
}
@@ -93,6 +93,7 @@ function validateManifestOutput(manifest, output, otherComponentNames) {
}
}
const hasNpm = fs.existsSync(path.join(output, "miniprogram_npm"));
for (const file of listFiles(output)) {
if (!/\.(js|json|wxml)$/.test(file)) continue;
const source = fs.readFileSync(path.join(output, file), "utf8");
@@ -106,11 +107,11 @@ function validateManifestOutput(manifest, output, otherComponentNames) {
}
for (const [name, reference] of Object.entries(definition.usingComponents || {})) {
if (reference.startsWith("plugin://")) continue;
if (
reference.startsWith("/miniprogram_npm/") &&
!fs.existsSync(path.join(output, "miniprogram_npm"))
)
continue;
// miniprogram_npm 由微信开发者工具生成且不入库;缺失时跳过 npm 组件解析检查。
const needsNpm =
reference.startsWith("/miniprogram_npm/") ||
(!reference.startsWith("/") && !reference.startsWith("."));
if (needsNpm && !hasNpm) continue;
if (!resolveComponent(output, file, reference))
failures.push(`${file}: component ${name} cannot be resolved (${reference})`);
}
+35 -1
View File
@@ -61,7 +61,41 @@ pnpm --filter @personal-brand/taro test
pnpm --filter @personal-brand/taro test:browser
```
浏览器测试需要先启动 API 和餐饮 H5 预览。`PREVIEW_URL` 指定预览地址,`CHROMIUM_PATH` 指定本机 Chromium;测试只读取开发库,模拟错误响应用于失败路径,不写入真实数据。
完整浏览器回归需要同时启动四类服务,缺一会产生误导性的失败:
```sh
# 1. API(3001)。CORS 必须放行 Admin 与两个 H5 预览来源,否则浏览器报 Failed to fetch。
CORS_ORIGINS=http://localhost:3002,http://localhost:3003,http://localhost:3005 \
pnpm --filter @personal-brand/api dev
# 2. Admin(3005)。dev server 会把 /api 代理到 3001;静态 preview 没有该代理。
ADMIN_PORT=3005 pnpm --filter @personal-brand/admin dev
# 3. 餐饮 H5(3002)
TEMPLATE_KEY=acheng-campus-food PREVIEW_PORT=3002 pnpm --filter @personal-brand/taro dev:h5
# 4. 林境 H5(3003)
TEMPLATE_KEY=linjing-editorial PREVIEW_PORT=3003 pnpm --filter @personal-brand/taro dev:h5
```
然后执行:
```sh
ADMIN_URL=http://127.0.0.1:3005 PREVIEW_URL=http://127.0.0.1:3002 \
pnpm --filter @personal-brand/taro test:browser
```
`PREVIEW_URL` 指定餐饮预览地址,林境用例固定访问 `http://localhost:3003`,`CHROMIUM_PATH` 可指定本机 Chromium。测试只读取开发库,模拟错误响应用于失败路径,不写入真实数据。
当前 Taro 4.3 的 `dev:h5` watch 模式在本地会持续增长直至 OOM,而一次性构建正常。遇到该问题时改用 `TEMPLATE_KEY=<key> pnpm --filter @personal-brand/taro build:h5`,再通过静态服务器托管 `dist/<key>/h5`;静态托管同样需要把对应来源加入 `CORS_ORIGINS`。
PR 和本地可用轻量 smoke 验证 Admin 会话与创建品牌流程:
```sh
pnpm test:browser:smoke
```
该命令会自动构建 Admin 并启动静态预览;完整浏览器回归仍使用 `pnpm --filter @personal-brand/taro test:browser`。
## 回滚与切换
+2 -1
View File
@@ -11,7 +11,8 @@
"typecheck": "tsc --noEmit",
"lint": "pnpm --workspace-root exec eslint apps/taro/src apps/taro/config \"packages/template-*/taro/**/*.{ts,tsx}\"",
"test": "node --experimental-strip-types --test test/*.test.mjs",
"test:browser": "playwright test"
"test:browser": "playwright test",
"test:browser:smoke": "playwright test -c playwright.smoke.config.ts"
},
"dependencies": {
"@personal-brand/types": "workspace:*",
+28
View File
@@ -0,0 +1,28 @@
import { defineConfig } from "@playwright/test";
const adminOrigin = process.env.ADMIN_URL || "http://127.0.0.1:3005";
export default defineConfig({
testDir: "./test/browser",
// PR smoke 只覆盖最容易影响所有后台操作的会话与品牌创建流程。
testMatch: ["admin-session.spec.ts", "brand-creation-and-page-scheme.spec.ts"],
timeout: 30000,
fullyParallel: false,
workers: 1,
use: {
viewport: { width: 1440, height: 1000 },
screenshot: "only-on-failure",
trace: "retain-on-failure",
launchOptions: { args: ["--no-sandbox"] },
},
reporter: [["list"]],
outputDir: "../../.codex-tasks/browser-smoke/raw",
webServer: {
// 使用已构建的 Admin 静态产物,避免在 CI 中额外启动 API 或 Vite 开发代理。
command:
"pnpm --dir ../../apps/admin exec vite preview --host 127.0.0.1 --port 3005 --strictPort",
url: `${adminOrigin}/admin/brands/new`,
reuseExistingServer: !process.env.CI,
timeout: 60000,
},
});
@@ -88,6 +88,27 @@ async function verifyCanvasTargets(page: Page, manifest: any, pageKey: string) {
}
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
const consoleWarnings = new WeakMap<Page, string[]>();
test.beforeEach(({ page }) => {
const warnings: string[] = [];
consoleWarnings.set(page, warnings);
page.on("console", (message) => {
const text = message.text();
const isWarning =
message.type() === "warning" ||
(message.type() === "error" &&
(text.startsWith("Warning:") ||
text.includes("non-boolean attribute") ||
text.includes("empty string")));
if (isWarning) warnings.push(text);
});
});
test.afterEach(({ page }) => {
expect(consoleWarnings.get(page) ?? []).toEqual([]);
});
const brand = {
id: "brand-fixture",
slug: "preview-fixture",
@@ -712,6 +733,9 @@ test("林境模板支持首页和主理人区域点选", async ({ page }) => {
title: "专业资历",
summary: "建筑与门系统经验",
content: "持续服务私宅项目",
sortOrder: 0,
isPublished: true,
coverUrl: null,
config: {
pillars: editorialPillars,
serviceFlow: editorialFlow,
@@ -0,0 +1,220 @@
import assert from "node:assert/strict";
import { test, expect, type Page, type Route } from "@playwright/test";
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
const pageErrors = new WeakMap<Page, string[]>();
test.beforeEach(({ page }) => {
const errors: string[] = [];
pageErrors.set(page, errors);
page.on("pageerror", (error) => errors.push(error.message));
});
test.afterEach(({ page }) => {
expect(pageErrors.get(page) ?? []).toEqual([]);
});
interface MockOptions {
/** 品牌成员列表的异常返回,用于触发整页渲染错误 */
memberships?: unknown;
/** 品牌名称的异常返回 */
brandName?: unknown;
/** 始终返回的异常信任内容,用于验证契约错误态 */
trustContent?: unknown;
/** 只在首次请求时返回的异常信任内容,重新加载后恢复 */
trustContentOnce?: unknown;
/** 只在首次请求时返回的异常工作区数据,用于触发渲染异常 */
workspaceOnce?: unknown;
/** 上报接口返回的状态码 */
clientErrorStatus?: number;
}
type ClientErrorReport = {
errorId?: string;
message?: string;
route?: string;
componentStack?: string;
};
async function mockAdminApi(page: Page, options: MockOptions = {}) {
let servedTrustContent = false;
let servedWorkspace = false;
const clientErrors: ClientErrorReport[] = [];
await page.route("**/api/**", async (route: Route) => {
const request = route.request();
const path = new URL(request.url()).pathname.replace(/^\/api/, "");
const method = request.method();
if (path === "/admin/session/current") {
return route.fulfill({
json: {
authenticated: true,
displayName: "品牌负责人",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "none",
},
});
}
if (path === "/admin/config/brand") {
return route.fulfill({
json: {
id: "brand-current",
name: options.brandName ?? "独立工坊",
slug: "atelier-studio",
tagline: "把耐心做进作品",
templateKey: "personal",
},
});
}
if (path === "/admin/brands" && method === "GET") {
return route.fulfill({
json: options.memberships ?? [
{
id: "membership-current",
role: "owner",
brand: {
id: "brand-current",
name: "独立工坊",
slug: "atelier-studio",
templateKey: "personal",
},
},
],
});
}
if (path === "/admin/config/trust-content" && method === "GET") {
if (options.trustContent !== undefined) {
return route.fulfill({ json: options.trustContent });
}
if (!servedTrustContent && options.trustContentOnce !== undefined) {
servedTrustContent = true;
return route.fulfill({ json: options.trustContentOnce });
}
return route.fulfill({ json: [] });
}
if (path === "/admin/client-errors" && method === "POST") {
clientErrors.push(JSON.parse(request.postData() ?? "{}") as ClientErrorReport);
return route.fulfill({
status: options.clientErrorStatus ?? 201,
...(options.clientErrorStatus && options.clientErrorStatus >= 400
? {
json: {
data: null,
error: { code: "HTTP_500", message: "上报失败" },
requestId: "req-client-error",
},
}
: { json: { received: true, duplicate: false } }),
});
}
if (path === "/admin/workspace") {
if (!servedWorkspace && options.workspaceOnce !== undefined) {
servedWorkspace = true;
return route.fulfill({ json: options.workspaceOnce });
}
return route.fulfill({
json: {
brand: { id: "brand-current", name: "独立工坊" },
installations: [],
templateContent: { displayName: "独立创作者画册" },
offerings: [],
forms: [],
},
});
}
if (path === "/admin/releases/readiness") {
return route.fulfill({ json: { ready: true, checks: [] } });
}
return route.fulfill({ json: [] });
});
return { clientErrors };
}
test("品牌成员与品牌名称异常时后台外壳仍可正常使用", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
await mockAdminApi(page, {
memberships: [{}, null, { brand: { id: "brand-current" } }],
brandName: { unexpected: true },
});
await page.goto(`${adminOrigin}/admin/publication`);
await expect(page.getByRole("heading", { name: "内容与发布" })).toBeVisible();
await expect(page.getByText("当前品牌", { exact: true }).first()).toBeVisible();
await expect(page.getByText("页面渲染出错")).toBeHidden();
await expect(page.getByRole("button", { name: "退出登录" })).toBeVisible();
});
test("内容区渲染出错时上报错误编号并保留导航,重新加载后恢复", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
const { clientErrors } = await mockAdminApi(page, {
workspaceOnce: {
brand: { id: "brand-current", name: "独立工坊" },
installations: [],
templateContent: { displayName: "独立创作者画册", trustContentTypes: [null] },
offerings: [],
forms: [],
},
});
await page.goto(`${adminOrigin}/admin/trust`);
await expect(page.getByText("页面渲染出错")).toBeVisible();
await expect(page.getByText(/错误编号:admin-/)).toBeVisible();
await expect.poll(() => clientErrors.length).toBe(1);
const report = clientErrors[0];
assert.match(report?.errorId ?? "", /^admin-/);
assert.equal(report?.route, "/admin/trust");
assert.ok(report?.message);
// 外壳导航仍然可用,不会因为单个页面崩溃而整站白屏
await expect(page.getByRole("button", { name: "退出登录" })).toBeVisible();
await expect(page.getByText("内容与发布")).toBeVisible();
// 重试仍失败时继续展示错误页,而不是变回白屏
await page.getByRole("button", { name: /重\s*试/ }).click();
await expect(page.getByText("页面渲染出错")).toBeVisible();
await page.getByRole("button", { name: "重新加载页面" }).click();
await expect(page.getByRole("heading", { name: "信任内容" })).toBeVisible();
await expect(page.getByText("页面渲染出错")).toBeHidden();
});
test("响应契约不符时展示可读错误,不进入渲染错误边界", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
const { clientErrors } = await mockAdminApi(page, { trustContent: [null] });
await page.goto(`${adminOrigin}/admin/trust`);
await expect(page.getByRole("alert")).toContainText("接口返回数据结构不符合契约");
await expect(page.getByRole("alert")).toContainText("/admin/config/trust-content");
await expect(page.getByText("页面渲染出错")).toBeHidden();
assert.equal(clientErrors.length, 0);
});
test("错误上报失败时错误页仍然可用", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
const { clientErrors } = await mockAdminApi(page, {
clientErrorStatus: 500,
workspaceOnce: {
brand: { id: "brand-current", name: "独立工坊" },
installations: [],
templateContent: { displayName: "独立创作者画册", trustContentTypes: [null] },
offerings: [],
forms: [],
},
});
await page.goto(`${adminOrigin}/admin/trust`);
await expect(page.getByText("页面渲染出错")).toBeVisible();
await expect(page.getByRole("button", { name: "重新加载页面" })).toBeVisible();
await expect.poll(() => clientErrors.length).toBe(1);
// 上报失败不会让错误页递归崩溃,也不会产生未捕获异常
await page.waitForTimeout(300);
await expect(page.getByText("页面渲染出错")).toBeVisible();
});
@@ -0,0 +1,315 @@
import { test, expect, type Page, type Route } from "@playwright/test";
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
const businesses = [
{ key: "personal", name: "个人品牌", description: "适合独立创作者与个人工作室" },
{ key: "doors", name: "门作品牌", description: "适合门作、木作与建筑空间业务" },
{ key: "food", name: "餐饮品牌", description: "适合餐饮与本地生活业务" },
];
const pageSchemes = [
{
templatePackageVersionId: "atelier-v132",
name: "独立创作者画册",
description: "个人品牌页面方案",
version: "1.3.2",
supportedBusinessTypes: ["personal"],
isLatestForPackage: true,
},
{
templatePackageVersionId: "linjing-v107",
name: "林境建筑画册",
description: "门作品牌页面方案",
version: "1.0.7",
supportedBusinessTypes: ["doors"],
isLatestForPackage: false,
},
{
templatePackageVersionId: "linjing-v108",
name: "林境建筑画册",
description: "门作品牌页面方案",
version: "1.0.8",
supportedBusinessTypes: ["doors"],
isLatestForPackage: true,
},
{
templatePackageVersionId: "food-v103",
name: "阿成校园餐饮",
description: "餐饮品牌页面方案",
version: "1.0.3",
supportedBusinessTypes: ["food"],
isLatestForPackage: true,
},
];
const currentBrand = {
id: "brand-current",
name: "独立工坊",
slug: "atelier-studio",
templateKey: "personal",
};
const memberships = [{ id: "membership-current", role: "owner", brand: currentBrand }];
interface ApiMockOptions {
createStatus?: number;
onCreate?: (body: Record<string, unknown>) => void;
onSelectVersion?: (body: Record<string, unknown>) => void;
onUpgrade?: (body: Record<string, unknown>) => void;
}
async function mockAdminApi(page: Page, options: ApiMockOptions = {}) {
let createStatus = options.createStatus ?? 200;
let currentVersion = "1.0.7";
let currentPackageVersionId = "linjing-v107";
await page.route("**/api/**", async (route: Route) => {
const request = route.request();
const url = new URL(request.url());
const path = url.pathname.replace(/^\/api/, "");
const method = request.method();
if (path === "/admin/session/current") {
return route.fulfill({
json: {
authenticated: true,
displayName: "品牌负责人",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "none",
},
});
}
if (path === "/admin/config/brand") return route.fulfill({ json: currentBrand });
if (path === "/admin/brands" && method === "GET") return route.fulfill({ json: memberships });
if (path === "/admin/brands/creation-options") {
return route.fulfill({ json: { businesses, pageSchemes } });
}
if (path === "/admin/brands" && method === "POST") {
const body = JSON.parse(request.postData() ?? "{}") as Record<string, unknown>;
options.onCreate?.(body);
if (createStatus !== 200) {
return route.fulfill({
status: createStatus,
json: {
error: { code: "BRAND_SLUG_TAKEN", message: "小程序地址标识已被使用" },
requestId: "browser-create-error",
},
});
}
return route.fulfill({
json: {
role: "owner",
brand: {
id: "brand-created",
name: body.name,
slug: body.slug,
templateKey: body.businessType,
},
},
});
}
if (path === "/admin/workspace/template/options") {
return route.fulfill({
json: {
business: businesses[1],
pageSchemes: pageSchemes.filter((scheme) =>
scheme.supportedBusinessTypes.includes("doors"),
),
},
});
}
if (path === "/admin/workspace/template/preview") {
return route.fulfill({
json: {
templateKey: "doors",
currentVersion: "1.0.7",
latestVersion: "1.0.8",
canUpgrade: true,
canRollback: false,
currentPackageVersionId: "linjing-v107",
currentContentChecksum: "current-checksum",
targetPackageVersionId: "linjing-v108",
targetContentChecksum: "target-checksum",
changes: {
brandFields: { available: false, reason: "不适用" },
templateBindings: { added: [], changed: [], removed: [] },
pages: { added: [], changed: [], removed: [] },
modules: {
available: true,
source: "platform_visual_manifest",
packageUpgradeChangesRenderer: false,
pages: [],
},
assets: {
slots: { added: [], changed: [], removed: [] },
files: { available: false, reason: "不适用" },
},
capabilities: { added: [], removed: [] },
renderer: {
available: true,
source: "platform_visual_manifest",
packageUpgradeChangesRenderer: false,
pages: [],
},
package: {
currentContentChecksum: "current-checksum",
targetContentChecksum: "target-checksum",
runtimeContract: { current: null, target: null },
},
},
conflicts: [{ key: "hero.title", binding: "brand.name", reason: "自定义标题" }],
},
});
}
if (path === "/admin/workspace/template/select-version" && method === "POST") {
options.onSelectVersion?.(JSON.parse(request.postData() ?? "{}") as Record<string, unknown>);
currentVersion = "1.0.8";
currentPackageVersionId = "linjing-v108";
return route.fulfill({ json: { selected: true } });
}
if (path === "/admin/workspace/template/upgrade" && method === "POST") {
options.onUpgrade?.(JSON.parse(request.postData() ?? "{}") as Record<string, unknown>);
currentVersion = "1.0.8";
currentPackageVersionId = "linjing-v108";
return route.fulfill({ json: { upgraded: true } });
}
if (path === "/admin/workspace") {
return route.fulfill({
json: {
brand: currentBrand,
installations: [
{
templateVersion: currentVersion,
templatePackageVersionId: currentPackageVersionId,
templateKey: "doors",
},
],
templateContent: { displayName: "林境建筑画册" },
offerings: [],
forms: [],
},
});
}
if (path === "/admin/releases/readiness") {
return route.fulfill({ json: { ready: true, checks: [] } });
}
if (
path === "/admin/config/trust-content" ||
path === "/admin/workspace/offerings" ||
path === "/admin/workspace/submissions"
) {
return route.fulfill({ json: [] });
}
return route.fulfill({ json: {} });
});
return {
failCreate: () => {
createStatus = 400;
},
};
}
test("创建品牌成功后进入新品牌工作区", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
let createdBody: Record<string, unknown> | undefined;
await mockAdminApi(page, { onCreate: (body) => (createdBody = body) });
await page.goto(`${adminOrigin}/admin/brands/new`);
await page.getByText("个人品牌", { exact: true }).click();
await page.getByText(/最新版 1\.3\.2/).click();
await page.getByLabel("品牌名称").fill("新的独立品牌");
await page.getByLabel("小程序地址标识").fill("new-atelier");
await page.getByRole("button", { name: "创建并进入品牌" }).click();
await expect
.poll(() => createdBody)
.toEqual({
name: "新的独立品牌",
slug: "new-atelier",
businessType: "personal",
templatePackageVersionId: "atelier-v132",
});
await page.waitForURL("**/admin/overview");
await expect(page.getByRole("heading", { name: "品牌概览" })).toBeVisible();
});
test("创建品牌按业务类型过滤页面方案,失败后保留输入", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
let createdBody: Record<string, unknown> | undefined;
const api = await mockAdminApi(page, { onCreate: (body) => (createdBody = body) });
await page.goto(`${adminOrigin}/admin/brands/new`);
await expect(page.getByRole("heading", { name: "创建品牌" })).toBeVisible();
await expect(page.getByText("先选择业务类型")).toBeVisible();
await page.getByText("个人品牌", { exact: true }).click();
await expect(page.getByText("独立创作者画册")).toBeVisible();
await expect(page.getByText("林境建筑画册")).toBeHidden();
await page.getByText("门作品牌", { exact: true }).click();
await expect(page.getByText("林境建筑画册").first()).toBeVisible();
await expect(page.getByText("独立创作者画册")).toBeHidden();
await page.getByText(/最新版 1\.0\.8/).click();
await page.getByText("个人品牌", { exact: true }).click();
await expect(page.getByRole("button", { name: "创建并进入品牌" })).toBeDisabled();
await page.getByText(/最新版 1\.3\.2/).click();
await page.getByLabel("品牌名称").fill("测试独立品牌");
await page.getByLabel("小程序地址标识").fill("test-atelier");
api.failCreate();
await page.getByRole("button", { name: "创建并进入品牌" }).click();
await expect(page.locator(".admin-error-note")).toContainText("小程序地址标识已被使用");
await expect(page.getByLabel("品牌名称")).toHaveValue("测试独立品牌");
await expect(page.getByLabel("小程序地址标识")).toHaveValue("test-atelier");
expect(createdBody).toEqual({
name: "测试独立品牌",
slug: "test-atelier",
businessType: "personal",
templatePackageVersionId: "atelier-v132",
});
});
test("页面方案切换和升级提交正确契约,并刷新查询缓存", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
let selectBody: Record<string, unknown> | undefined;
let upgradeBody: Record<string, unknown> | undefined;
await mockAdminApi(page, {
onSelectVersion: (body) => (selectBody = body),
onUpgrade: (body) => (upgradeBody = body),
});
await page.goto(`${adminOrigin}/admin/page-scheme`);
await expect(page.getByRole("heading", { name: "页面方案" })).toBeVisible();
await expect(page.getByText("门作品牌", { exact: true })).toBeVisible();
await expect(page.getByText("正在使用版本 1.0.7")).toBeVisible();
await expect(page.getByText("独立创作者画册")).toBeHidden();
await expect(page.getByRole("button", { name: "恢复上一版配置" })).toBeDisabled();
await page.getByRole("button", { name: "切换到此版本" }).click();
await page.getByRole("button", { name: "确认切换" }).click();
await expect.poll(() => selectBody).toBeTruthy();
expect(selectBody).toEqual({
templatePackageVersionId: "linjing-v108",
expectedCurrentPackageVersionId: "linjing-v107",
confirm: true,
});
await expect(page.getByText("页面方案版本已切换")).toBeVisible();
await expect(page.getByText("正在使用版本 1.0.8")).toBeVisible();
await page.getByRole("button", { name: "升级到 1.0.8" }).click();
await expect(page.getByText("将升级到版本 1.0.8,并全部保留 1 项现有内容。")).toBeVisible();
await page.getByRole("button", { name: "确认升级" }).click();
await expect.poll(() => upgradeBody).toBeTruthy();
expect(upgradeBody).toMatchObject({
templatePackageVersionId: "linjing-v108",
expectedContentChecksum: "target-checksum",
expectedCurrentVersion: "1.0.7",
expectedCurrentPackageVersionId: "linjing-v107",
confirm: true,
preservedBindings: [{ key: "hero.title", binding: "brand.name", action: "preserve" }],
});
await expect(page.getByText("页面方案已升级,现有内容已全部保留")).toBeVisible();
});
@@ -0,0 +1,310 @@
import { test, expect, type Page, type Route } from "@playwright/test";
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
const pageErrors = new WeakMap<Page, string[]>();
test.beforeEach(({ page }) => {
const errors: string[] = [];
pageErrors.set(page, errors);
page.on("pageerror", (error) => errors.push(error.message));
});
test.afterEach(({ page }) => {
expect(pageErrors.get(page) ?? []).toEqual([]);
});
interface ReleaseRow {
id: string;
version: number;
status: string;
note: string | null;
actorId: string;
createdAt: string;
revokedAt: string | null;
}
interface MockOptions {
ready?: boolean;
onPublish?: (body: Record<string, unknown>) => void;
onRollback?: (body: Record<string, unknown>, version: number) => void;
onRevoke?: () => void;
publishStatus?: number;
}
async function mockPublicationApi(page: Page, options: MockOptions = {}) {
const releases: ReleaseRow[] = [
{
id: "release-2",
version: 2,
status: "published",
note: "第二版",
actorId: "actor-1",
createdAt: "2026-10-20T02:00:00.000Z",
revokedAt: null,
},
{
id: "release-1",
version: 1,
status: "superseded",
note: null,
actorId: "actor-1",
createdAt: "2026-10-19T02:00:00.000Z",
revokedAt: null,
},
];
await page.route("**/api/**", async (route: Route) => {
const request = route.request();
const url = new URL(request.url());
const path = url.pathname.replace(/^\/api/, "");
const method = request.method();
if (path === "/admin/session/current") {
return route.fulfill({
json: {
authenticated: true,
displayName: "品牌负责人",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "none",
},
});
}
if (path === "/admin/config/brand") {
return route.fulfill({
json: {
id: "brand-current",
name: "独立工坊",
slug: "atelier-studio",
templateKey: "personal",
},
});
}
if (path === "/admin/brands" && method === "GET") {
return route.fulfill({
json: [
{
id: "membership-current",
role: "owner",
brand: {
id: "brand-current",
name: "独立工坊",
slug: "atelier-studio",
templateKey: "personal",
},
},
],
});
}
if (path === "/admin/workspace") {
return route.fulfill({
json: {
brand: { id: "brand-current", name: "独立工坊" },
installations: [],
templateContent: { displayName: "独立创作者画册" },
offerings: [],
forms: [],
},
});
}
if (path === "/admin/releases/readiness") {
return route.fulfill({
json: {
ready: options.ready ?? true,
checks: [
{ key: "brand", label: "品牌资料", passed: true },
{
key: "offerings",
label: "业务提供项",
passed: options.ready ?? true,
help: "至少添加一个业务提供项",
},
],
},
});
}
if (path === "/admin/releases" && method === "GET") {
return route.fulfill({ json: releases });
}
if (path === "/admin/releases/publish" && method === "POST") {
const body = JSON.parse(request.postData() ?? "{}") as Record<string, unknown>;
options.onPublish?.(body);
if (options.publishStatus && options.publishStatus !== 200) {
return route.fulfill({
status: options.publishStatus,
json: {
error: { code: "RELEASE_FAILED", message: "发布检查未通过" },
requestId: "browser-release-error",
},
});
}
for (const item of releases) item.status = "superseded";
const created: ReleaseRow = {
id: "release-3",
version: 3,
status: "published",
note: typeof body.note === "string" ? body.note : null,
actorId: "actor-1",
createdAt: "2026-10-21T02:00:00.000Z",
revokedAt: null,
};
releases.unshift(created);
return route.fulfill({ json: created });
}
if (path === "/admin/releases/revoke" && method === "POST") {
options.onRevoke?.();
return route.fulfill({ json: { revoked: true } });
}
const rollback = path.match(/^\/admin\/releases\/(\d+)\/rollback$/);
if (rollback && method === "POST") {
const body = JSON.parse(request.postData() ?? "{}") as Record<string, unknown>;
options.onRollback?.(body, Number(rollback[1]));
for (const item of releases) item.status = "superseded";
const created: ReleaseRow = {
id: "release-rollback",
version: 4,
status: "published",
note: null,
actorId: "actor-1",
createdAt: "2026-10-21T03:00:00.000Z",
revokedAt: null,
};
releases.unshift(created);
return route.fulfill({ json: created });
}
if (path === "/admin/miniapp-releases") return route.fulfill({ json: [] });
if (path === "/admin/miniapp-releases/settings") {
return route.fulfill({
json: {
appId: "wx0000000000000000",
apiBaseUrl: "https://wechat.app.que01.top/api",
hasStoredCredentials: false,
},
});
}
return route.fulfill({ json: {} });
});
}
test("发布按钮按就绪状态启用,空备注发布不写入 note", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
const bodies: Record<string, unknown>[] = [];
await mockPublicationApi(page, { onPublish: (body) => bodies.push(body) });
await page.goto(`${adminOrigin}/admin/publication`);
await expect(page.getByRole("heading", { name: "内容与发布" })).toBeVisible();
await page.getByRole("button", { name: "发布当前草稿" }).click();
await page.getByRole("button", { name: "确认发布" }).click();
await expect.poll(() => bodies).toEqual([{}]);
await expect(page.getByText("品牌已发布")).toBeVisible();
await expect(page.getByRole("button", { name: "确认发布" })).toBeHidden();
await expect(page.getByText("v3")).toBeVisible();
});
test("发布备注会去除首尾空格并随请求提交", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
const bodies: Record<string, unknown>[] = [];
await mockPublicationApi(page, { onPublish: (body) => bodies.push(body) });
await page.goto(`${adminOrigin}/admin/publication`);
await page.getByRole("button", { name: "发布当前草稿" }).click();
await page.getByPlaceholder("发布备注(可选)").fill(" 国庆版本 ");
await page.getByRole("button", { name: "确认发布" }).click();
await expect.poll(() => bodies).toEqual([{ note: "国庆版本" }]);
await expect(page.getByText("国庆版本")).toBeVisible();
});
test("发布失败时保留备注与确认弹窗", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
await mockPublicationApi(page, { publishStatus: 409 });
await page.goto(`${adminOrigin}/admin/publication`);
await page.getByRole("button", { name: "发布当前草稿" }).click();
await page.getByPlaceholder("发布备注(可选)").fill("待重试的版本");
await page.getByRole("button", { name: "确认发布" }).click();
await expect(page.getByText("发布检查未通过")).toBeVisible();
await expect(page.getByRole("button", { name: "确认发布" })).toBeVisible();
await expect(page.getByPlaceholder("发布备注(可选)")).toHaveValue("待重试的版本");
});
test("未通过发布检查时禁用发布按钮", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
await mockPublicationApi(page, { ready: false });
await page.goto(`${adminOrigin}/admin/publication`);
await expect(page.getByRole("button", { name: "发布当前草稿" })).toBeDisabled();
await expect(page.getByText("至少添加一个业务提供项")).toBeVisible();
});
test("撤回当前版本并刷新发布记录", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
let revoked = 0;
await mockPublicationApi(page, { onRevoke: () => (revoked += 1) });
await page.goto(`${adminOrigin}/admin/publication`);
await page.getByRole("button", { name: "撤回当前版本" }).click();
await page.getByRole("button", { name: "确认撤回" }).click();
await expect.poll(() => revoked).toBe(1);
await expect(page.getByText("品牌已撤回,小程序将显示未发布状态")).toBeVisible();
});
test("恢复历史版本会提交版本号并刷新发布记录", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
const requests: Array<{ body: Record<string, unknown>; version: number }> = [];
await mockPublicationApi(page, {
onRollback: (body, version) => requests.push({ body, version }),
});
await page.goto(`${adminOrigin}/admin/publication`);
await page.getByRole("button", { name: "恢复此版本" }).click();
await page.getByRole("button", { name: "确 定" }).click();
await expect.poll(() => requests).toEqual([{ body: {}, version: 1 }]);
await expect(page.getByText("历史版本已重新发布")).toBeVisible();
});
test("小程序配置页回填服务端设置并仅提交新私钥", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
const bodies: Record<string, unknown>[] = [];
await mockPublicationApi(page, {});
await page.route("**/api/admin/miniapp-releases/settings", async (route) => {
if (route.request().method() === "PATCH") {
const body = JSON.parse(route.request().postData() ?? "{}") as Record<string, unknown>;
bodies.push(body);
return route.fulfill({
json: {
appId: body.appId,
apiBaseUrl: body.apiBaseUrl,
hasStoredCredentials: true,
},
});
}
return route.fallback();
});
await page.goto(`${adminOrigin}/admin/publication`);
await page.getByRole("tab", { name: "小程序配置" }).click();
await expect(page.getByLabel("微信 AppID")).toHaveValue("wx0000000000000000");
await expect(page.getByLabel("小程序请求地址")).toHaveValue("https://wechat.app.que01.top/api");
await page
.getByLabel("上传私钥")
.fill("-----BEGIN PRIVATE KEY-----\nKEY\n-----END PRIVATE KEY-----");
await page.getByRole("button", { name: "保存上传配置" }).click();
await expect
.poll(() => bodies)
.toEqual([
{
appId: "wx0000000000000000",
apiBaseUrl: "https://wechat.app.que01.top/api",
privateKey: "-----BEGIN PRIVATE KEY-----\nKEY\n-----END PRIVATE KEY-----",
},
]);
await expect(page.getByText("小程序上传配置已保存")).toBeVisible();
});
+22 -1
View File
@@ -1,7 +1,28 @@
import fs from "node:fs";
import { test, expect } from "@playwright/test";
import { test, expect, type Page } from "@playwright/test";
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
const consoleWarnings = new WeakMap<Page, string[]>();
test.beforeEach(({ page }) => {
const warnings: string[] = [];
consoleWarnings.set(page, warnings);
page.on("console", (message) => {
const text = message.text();
const isWarning =
message.type() === "warning" ||
(message.type() === "error" &&
(text.startsWith("Warning:") ||
text.includes("non-boolean attribute") ||
text.includes("empty string")));
if (isWarning) warnings.push(text);
});
});
test.afterEach(({ page }) => {
expect(consoleWarnings.get(page) ?? []).toEqual([]);
});
const templateContent = JSON.parse(
fs.readFileSync("../../packages/template-acheng-campus-food/template.json", "utf8"),
);
@@ -11,13 +11,17 @@ const manifest = JSON.parse(
);
const version = {
id: "preview-browser-version",
templatePackageId: "preview-browser-package",
packageKey: manifest.packageKey,
version: manifest.version,
displayName: manifest.displayName,
status: "imported",
contentChecksum: "fixture-checksum",
archiveChecksum: "fixture-archive-checksum",
importedAt: "2026-10-21T00:00:00.000Z",
updatedAt: "2026-10-21T00:00:00.000Z",
manifestSnapshot: manifest,
importedBy: { displayName: "模板管理员" },
importedBy: { id: "template-admin", username: "admin", displayName: "模板管理员" },
validationReport: {},
manifestSummary: { supportedIndustryTemplates: manifest.supportedIndustryTemplates },
};
@@ -103,6 +107,16 @@ test("模板管理可重试预览,并切换我的、详情和禁止提交的
}
if (url.pathname.endsWith("/admin/templates"))
return route.fulfill({ json: { items: [version], page: 1, pageSize: 20, total: 1 } });
if (url.pathname.endsWith("/admin/template-operations/failures"))
return route.fulfill({
json: {
since: "2026-09-21T00:00:00.000Z",
until: "2026-10-21T00:00:00.000Z",
days: 30,
backfilled: true,
failures: [],
},
});
if (url.pathname.endsWith("/admin/brands")) return route.fulfill({ json: [] });
return route.fulfill({ json: { name: "测试工作区" } });
});
@@ -18,12 +18,15 @@ type PackedChecksums = {
type PreviewVersion = {
id: string;
templatePackageId: string;
packageKey: string;
version: string;
displayName: string;
status: "imported";
manifestSnapshot: PackedManifest;
importedBy: { displayName: string };
importedBy: { id: string; username: string; displayName: string };
importedAt: string;
updatedAt: string;
validationReport: Record<string, unknown>;
manifestSummary: { supportedIndustryTemplates: string[] };
artifactPath: string;
@@ -88,12 +91,15 @@ async function buildPreviewFixture(mediaCase: MediaCase) {
const archivePath = path.join(temporary, archive);
const version: PreviewVersion = {
id: `preview-media-${mediaCase.packageKey}-${mediaCase.industry}`,
templatePackageId: `preview-media-package-${mediaCase.packageKey}`,
packageKey: manifest.packageKey,
version: manifest.version,
displayName: manifest.displayName,
status: "imported",
manifestSnapshot: manifest,
importedBy: { displayName: "模板管理员" },
importedBy: { id: "template-admin", username: "admin", displayName: "模板管理员" },
importedAt: "2026-10-21T00:00:00.000Z",
updatedAt: "2026-10-21T00:00:00.000Z",
validationReport: {},
manifestSummary: { supportedIndustryTemplates: manifest.supportedIndustryTemplates },
artifactPath: archivePath,
@@ -216,6 +222,16 @@ test("导入包预览矩阵展示身份、资源和完整媒体槽位", async ({
total: 1,
},
});
if (url.pathname.endsWith("/admin/template-operations/failures"))
return route.fulfill({
json: {
since: "2026-09-21T00:00:00.000Z",
until: "2026-10-21T00:00:00.000Z",
days: 30,
backfilled: true,
failures: [],
},
});
if (url.pathname.endsWith("/admin/brands")) return route.fulfill({ json: [] });
return route.fulfill({ json: { name: "测试工作区" } });
});
+2
View File
@@ -6,6 +6,8 @@ module.exports = {
apps: [
{
name: "personal-brand-api",
instances: 1,
exec_mode: "fork",
cwd: path.join(root, "current/apps/api"),
script: "dist/main.js",
interpreter: process.execPath,
+13
View File
@@ -0,0 +1,13 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createRequire } from "node:module";
process.env.DEPLOY_ROOT = "/srv/personal-brand";
const require = createRequire(import.meta.url);
const config = require("./ecosystem.config.cjs");
test("异常上报使用进程内存储时 PM2 必须保持单实例", () => {
assert.equal(config.apps.length, 1);
assert.equal(config.apps[0].instances, 1);
assert.equal(config.apps[0].exec_mode, "fork");
});
+4 -14
View File
@@ -16,6 +16,7 @@ import {
import path from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { checkPackage } from "../scripts/deploy/check-package.mjs";
import { assertReleaseEnvironment } from "./release-environment.mjs";
const root = process.env.DEPLOY_ROOT;
if (!root || !path.isAbsolute(root)) throw new Error("DEPLOY_ROOT must be absolute");
@@ -28,20 +29,7 @@ if (!postgresContainer || !/^[a-zA-Z0-9_.-]+$/.test(postgresContainer)) {
throw new Error("POSTGRES_CONTAINER is required for the database backup");
}
if (Number(process.versions.node.split(".")[0]) !== 24) throw new Error("Node.js 24 is required");
if (
process.env.NODE_ENV !== "production" ||
!process.env.DATABASE_URL ||
!process.env.SESSION_SECRET ||
process.env.SESSION_SECRET.length < 32 ||
!process.env.DEFAULT_BRAND_ID ||
!process.env.LOCAL_MEDIA_ROOT
) {
throw new Error("Production environment is missing required values");
}
if (!path.isAbsolute(process.env.LOCAL_MEDIA_ROOT))
throw new Error("LOCAL_MEDIA_ROOT must be absolute");
if (process.env.API_PREFIX) throw new Error("API_PREFIX must be empty when Traefik strips /api");
const databaseUrl = new URL(process.env.DATABASE_URL);
const databaseUrl = assertReleaseEnvironment(process.env);
const privateDatabaseHost = /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[0-1])\.)/.test(
databaseUrl.hostname,
);
@@ -381,6 +369,8 @@ try {
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "generate"], release);
await backupDatabase(path.join(root, "shared/backups", manifest.version + ".dump"));
await pruneBackups(path.join(root, "shared/backups"));
// 旧数据的模板包声明必须先收敛,migration 才能安全地删除兼容字段。
run(process.execPath, ["deploy/prepare-template-contract.mjs", ".", "--apply"], release);
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "migrate", "deploy"], release);
const seedDirectory = path.join(process.env.LOCAL_MEDIA_ROOT, "seed");
await copyMissingFiles(path.join(release, "seed-media"), seedDirectory);
+479
View File
@@ -0,0 +1,479 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { copyFile, mkdir, readFile } from "node:fs/promises";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { spawnSync } from "node:child_process";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
const CONTRACT_MIGRATION = "20261018120000_enforce_single_template_contract";
const source = path.resolve(process.argv[2] ?? ".");
const apply = process.argv.includes("--apply");
const catalogPath = path.join(source, "template-catalog.json");
const apiRequire = createRequire(new URL("../apps/api/package.json", import.meta.url));
const { PrismaClient } = apiRequire("@prisma/client");
function object(value) {
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
}
function nonEmpty(value) {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function sha256(content) {
return createHash("sha256").update(content).digest("hex");
}
function supportsIndustry(version, industry) {
const manifest = object(version.manifestSnapshot) ?? object(version.manifest) ?? {};
const fixture = object(object(manifest.previewFixture)?.[industry]);
return (
version.status === "published" &&
manifest.packageKey === version.packageKey &&
manifest.visualTemplateKey === version.packageKey &&
manifest.version === version.version &&
manifest.runtimeContract === "1.0" &&
Array.isArray(manifest.supportedIndustryTemplates) &&
manifest.supportedIndustryTemplates.includes(industry) &&
fixture !== null
);
}
function versionShape(version) {
return {
id: version.id,
packageKey: version.packageKey,
version: version.version,
status: version.status,
contentChecksum: version.contentChecksum,
manifestSnapshot: version.manifestSnapshot ?? version.manifest,
};
}
/**
* 只规划旧数据到单一模板契约的转换。运行时不得复用此逻辑做兜底。
*/
export function buildTemplateContractPlan({ brands, versions, catalog }) {
const catalogPackages = catalog.packages ?? [];
const normalizedVersions = versions.map(versionShape);
const imports = new Map();
const installations = [];
for (const brand of brands) {
if (!Array.isArray(brand.installations) || brand.installations.length > 1)
throw new Error(`品牌 ${brand.slug} 存在多条模板安装记录,必须人工处理`);
const installation = brand.installations?.[0] ?? null;
const declarations = [
["installation.visualTemplateKey", nonEmpty(installation?.visualTemplateKey)],
["brand.config.visualTemplateKey", nonEmpty(brand.brandVisualTemplateKey)],
[
"installation.configSnapshot.visualTemplateKey",
nonEmpty(installation?.snapshotVisualTemplateKey),
],
["installation.configSnapshot.packageKey", nonEmpty(installation?.snapshotPackageKey)],
].filter(([, value]) => value);
const declaredKeys = [...new Set(declarations.map(([, value]) => value))];
if (declaredKeys.length > 1)
throw new Error(`品牌 ${brand.slug} 的模板包声明冲突:${declaredKeys.join("、")}`);
let selected;
const linkedId = nonEmpty(installation?.templatePackageVersionId);
if (linkedId) {
selected = normalizedVersions.find((version) => version.id === linkedId);
if (!selected || !supportsIndustry(selected, brand.templateKey))
throw new Error(`品牌 ${brand.slug} 已关联的模板包版本不符合契约`);
if (declaredKeys[0] && declaredKeys[0] !== selected.packageKey)
throw new Error(`品牌 ${brand.slug} 的模板包声明与已关联版本冲突`);
} else {
const packageKey = declaredKeys[0];
if (!packageKey) throw new Error(`品牌 ${brand.slug} 没有可审计的旧模板包声明`);
const candidates = normalizedVersions.filter(
(version) =>
version.packageKey === packageKey && supportsIndustry(version, brand.templateKey),
);
if (candidates.length > 1)
throw new Error(`品牌 ${brand.slug} 匹配到多个已发布模板包版本,必须人工处理`);
if (candidates.length === 1) {
selected = candidates[0];
} else {
const bundled = catalogPackages.filter(
(entry) =>
entry.packageKey === packageKey &&
supportsIndustry(
{
packageKey: entry.packageKey,
version: entry.version,
status: "published",
manifestSnapshot: entry.manifest,
},
brand.templateKey,
),
);
if (bundled.length !== 1)
throw new Error(
`品牌 ${brand.slug} 在发布包中匹配到 ${bundled.length} 个可用模板包,必须人工处理`,
);
selected = bundled[0];
imports.set(`${selected.packageKey}@${selected.version}`, selected);
}
}
installations.push({
brandId: brand.brandId,
slug: brand.slug,
installationId: installation?.id ?? null,
templateKey: brand.templateKey,
packageKey: selected.packageKey,
version: selected.version,
packageVersionId: selected.id ?? null,
catalogImport: !selected.id,
contentChecksum: selected.contentChecksum,
configSnapshot: selected.manifestSnapshot ?? selected.manifest,
});
}
return {
catalogImports: [...imports.values()],
installations,
};
}
async function loadInputs(prisma) {
const columns = await prisma.$queryRawUnsafe(`
SELECT table_name, column_name
FROM information_schema.columns
WHERE table_schema = current_schema()
AND table_name IN ('BrandTemplateInstallation', 'TemplatePackageVersion')
AND column_name IN ('visualTemplateKey', 'templatePackageVersionId')
`);
const installationVisual = columns.some(
(column) =>
column.table_name === "BrandTemplateInstallation" &&
column.column_name === "visualTemplateKey",
);
const versionVisual = columns.some(
(column) =>
column.table_name === "TemplatePackageVersion" && column.column_name === "visualTemplateKey",
);
if (!installationVisual && !versionVisual) return { alreadyApplied: true };
const tables = await prisma.$queryRawUnsafe(`
SELECT to_regclass('"TemplatePackage"')::text AS package_table,
to_regclass('"TemplatePackageVersion"')::text AS version_table,
to_regclass('"TemplatePackageAuditLog"')::text AS audit_table
`);
if (!tables[0]?.package_table || !tables[0]?.version_table || !tables[0]?.audit_table)
throw new Error("模板包目录表尚未创建,请先让 Prisma 应用目录类 migration");
const brands = await prisma.$queryRawUnsafe(`
SELECT
brand.id AS "brandId",
brand.slug,
brand."templateKey",
brand.config->>'visualTemplateKey' AS "brandVisualTemplateKey",
installation.id AS "installationId",
installation."templatePackageVersionId",
installation."visualTemplateKey" AS "installationVisualTemplateKey",
installation."configSnapshot"->>'visualTemplateKey' AS "snapshotVisualTemplateKey",
installation."configSnapshot"->>'packageKey' AS "snapshotPackageKey"
FROM "BrandProfile" brand
LEFT JOIN "BrandTemplateInstallation" installation ON installation."brandId" = brand.id
ORDER BY brand.slug, installation.id
`);
const grouped = new Map();
for (const row of brands) {
const entry = grouped.get(row.brandId) ?? {
brandId: row.brandId,
slug: row.slug,
templateKey: row.templateKey,
brandVisualTemplateKey: row.brandVisualTemplateKey,
installations: [],
};
if (row.installationId) {
entry.installations.push({
id: row.installationId,
templatePackageVersionId: row.templatePackageVersionId,
visualTemplateKey: row.installationVisualTemplateKey,
snapshotVisualTemplateKey: row.snapshotVisualTemplateKey,
snapshotPackageKey: row.snapshotPackageKey,
});
}
grouped.set(row.brandId, entry);
}
const versions = await prisma.$queryRawUnsafe(`
SELECT id, "packageKey", version, status, "contentChecksum", "manifestSnapshot"
FROM "TemplatePackageVersion"
ORDER BY "packageKey", version
`);
const catalog = JSON.parse(await readFile(catalogPath, "utf8"));
if (catalog.formatVersion !== "1" || !Array.isArray(catalog.packages))
throw new Error("发布包模板目录格式无效");
return { alreadyApplied: false, brands: [...grouped.values()], versions, catalog };
}
async function ensureArtifact(root, entry) {
const sourceArchive = path.join(source, entry.archivePath);
const content = await readFile(sourceArchive);
if (sha256(content) !== entry.archiveChecksum)
throw new Error(`发布包模板归档校验失败:${entry.packageKey}@${entry.version}`);
const target = path.join(
root,
"shared/template-artifacts",
entry.packageKey,
entry.version,
entry.archiveChecksum + ".tar.gz",
);
await mkdir(path.dirname(target), { recursive: true });
try {
const existing = await readFile(target);
if (sha256(existing) === entry.archiveChecksum) return target;
} catch {}
await copyFile(sourceArchive, target);
return target;
}
async function runApply(prisma, plan, deployRoot, actorId) {
const imported = new Map();
await prisma.$transaction(async (tx) => {
for (const entry of plan.catalogImports) {
const artifactPath = await ensureArtifact(deployRoot, entry);
const existingRows = await tx.$queryRawUnsafe(
`SELECT id, status, "contentChecksum", "manifestSnapshot"
FROM "TemplatePackageVersion"
WHERE "packageKey" = $1 AND version = $2`,
entry.packageKey,
entry.version,
);
let version = existingRows[0];
if (version) {
if (version.contentChecksum !== entry.contentChecksum)
throw new Error(`已存在不同内容的模板包版本:${entry.packageKey}@${entry.version}`);
if (version.status === "imported") {
await tx.$executeRawUnsafe(
`UPDATE "TemplatePackageVersion"
SET status = 'published', "updatedAt" = CURRENT_TIMESTAMP
WHERE id = $1`,
version.id,
);
await tx.$executeRawUnsafe(
`INSERT INTO "TemplatePackageAuditLog"
("id", "templatePackageVersionId", "actorId", action, "fromStatus", "toStatus", metadata)
VALUES ($1, $2, $3, 'published', 'imported', 'published', $4::jsonb)`,
randomUUID(),
version.id,
actorId,
JSON.stringify({ source: "legacy-template-contract-migration" }),
);
} else if (version.status !== "published") {
throw new Error(
`模板包版本 ${entry.packageKey}@${entry.version} 状态为 ${version.status},不能用于旧数据迁移`,
);
}
} else {
await tx.$executeRawUnsafe(
`INSERT INTO "TemplatePackage" (id, "packageKey", "createdAt", "updatedAt")
VALUES ($1, $2, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
ON CONFLICT ("packageKey") DO NOTHING`,
randomUUID(),
entry.packageKey,
);
const packageRows = await tx.$queryRawUnsafe(
`SELECT id FROM "TemplatePackage" WHERE "packageKey" = $1`,
entry.packageKey,
);
const templatePackageId = packageRows[0]?.id;
if (!templatePackageId) throw new Error(`无法创建模板包:${entry.packageKey}`);
const versionId = randomUUID();
await tx.$executeRawUnsafe(
`INSERT INTO "TemplatePackageVersion" (
id, "templatePackageId", "packageKey", version, "displayName", "visualTemplateKey",
status, "manifestSnapshot", "validationReport", "contentChecksum", "archiveChecksum",
"artifactPath", "importedById", "importedAt", "createdAt", "updatedAt"
) VALUES (
$1, $2, $3, $4, $5, $3, 'imported', $6::jsonb, $7::jsonb, $8, $9, $10, $11,
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
)`,
versionId,
templatePackageId,
entry.packageKey,
entry.version,
entry.displayName,
JSON.stringify(entry.manifest),
JSON.stringify(entry.validationReport),
entry.contentChecksum,
entry.archiveChecksum,
artifactPath,
actorId,
);
await tx.$executeRawUnsafe(
`INSERT INTO "TemplatePackageAuditLog"
("id", "templatePackageVersionId", "actorId", action, "toStatus", metadata)
VALUES ($1, $2, $3, 'imported', 'imported', $4::jsonb)`,
randomUUID(),
versionId,
actorId,
JSON.stringify({
source: "legacy-template-contract-migration",
contentChecksum: entry.contentChecksum,
archiveChecksum: entry.archiveChecksum,
}),
);
await tx.$executeRawUnsafe(
`UPDATE "TemplatePackageVersion"
SET status = 'published', "updatedAt" = CURRENT_TIMESTAMP
WHERE id = $1`,
versionId,
);
await tx.$executeRawUnsafe(
`INSERT INTO "TemplatePackageAuditLog"
("id", "templatePackageVersionId", "actorId", action, "fromStatus", "toStatus", metadata)
VALUES ($1, $2, $3, 'published', 'imported', 'published', $4::jsonb)`,
randomUUID(),
versionId,
actorId,
JSON.stringify({ source: "legacy-template-contract-migration" }),
);
version = {
id: versionId,
status: "published",
contentChecksum: entry.contentChecksum,
};
}
imported.set(`${entry.packageKey}@${entry.version}`, version.id);
}
for (const installation of plan.installations) {
const packageVersionId =
installation.packageVersionId ??
imported.get(`${installation.packageKey}@${installation.version}`);
if (!packageVersionId)
throw new Error(`模板包版本未导入:${installation.packageKey}@${installation.version}`);
if (installation.installationId) {
await tx.$executeRawUnsafe(
`UPDATE "BrandTemplateInstallation"
SET "templateKey" = $2,
"templateVersion" = $3,
"templatePackageVersionId" = $4,
"contentChecksum" = $5,
"configSnapshot" = $6::jsonb,
"visualTemplateKey" = $7,
"updatedAt" = CURRENT_TIMESTAMP
WHERE id = $1`,
installation.installationId,
installation.templateKey,
installation.version,
packageVersionId,
installation.contentChecksum,
JSON.stringify(installation.configSnapshot),
installation.packageKey,
);
} else {
await tx.$executeRawUnsafe(
`INSERT INTO "BrandTemplateInstallation" (
id, "brandId", "templateKey", "templateVersion", "templatePackageVersionId",
"contentChecksum", "configSnapshot", "previousSnapshots", "visualTemplateKey",
"installedAt", "updatedAt"
) VALUES (
$1, $2, $3, $4, $5, $6, $7::jsonb, '[]'::jsonb, $8,
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
)`,
randomUUID(),
installation.brandId,
installation.templateKey,
installation.version,
packageVersionId,
installation.contentChecksum,
JSON.stringify(installation.configSnapshot),
installation.packageKey,
);
}
}
});
}
async function resolveFailedMigration(root) {
const result = spawnSync(
"pnpm",
[
"--filter",
"@personal-brand/api",
"exec",
"prisma",
"migrate",
"resolve",
"--rolled-back",
CONTRACT_MIGRATION,
],
{ cwd: root, stdio: "inherit", env: process.env },
);
if (result.status !== 0) throw new Error("无法将失败的模板契约 migration 标记为 rolled-back");
}
async function main() {
const deployRoot = process.env.DEPLOY_ROOT;
if (!deployRoot || !path.isAbsolute(deployRoot))
throw new Error("DEPLOY_ROOT must be an absolute path");
const prisma = new PrismaClient();
try {
const inputs = await loadInputs(prisma);
if (inputs.alreadyApplied) {
console.log("template contract migration already applied; no legacy data to prepare");
return 0;
}
const plan = buildTemplateContractPlan(inputs);
console.log(
JSON.stringify(
{
apply,
catalogImports: plan.catalogImports.map((entry) => ({
packageKey: entry.packageKey,
version: entry.version,
contentChecksum: entry.contentChecksum,
})),
installations: plan.installations.map((entry) => ({
slug: entry.slug,
templateKey: entry.templateKey,
packageKey: entry.packageKey,
version: entry.version,
action: entry.installationId ? "update" : "create",
})),
},
null,
2,
),
);
if (!apply) return 0;
const actorUsername = process.env.TEMPLATE_CATALOG_ACTOR ?? "admin";
const actors = await prisma.$queryRawUnsafe(
`SELECT id FROM "AdminUser" WHERE username = $1 AND "isEnabled" = true`,
actorUsername,
);
if (!actors[0]) throw new Error(`找不到启用的模板迁移操作人:${actorUsername}`);
await runApply(prisma, plan, deployRoot, actors[0].id);
const failed = await prisma.$queryRawUnsafe(
`SELECT 1 FROM _prisma_migrations
WHERE migration_name = $1 AND finished_at IS NULL AND rolled_back_at IS NULL`,
CONTRACT_MIGRATION,
);
if (failed.length) await resolveFailedMigration(source);
console.log("legacy template contract data prepared");
return 0;
} finally {
await prisma.$disconnect();
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
main()
.then((code) => {
process.exitCode = code;
})
.catch((error) => {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
});
}
+99
View File
@@ -0,0 +1,99 @@
import assert from "node:assert/strict";
import test from "node:test";
import { buildTemplateContractPlan } from "./prepare-template-contract.mjs";
function manifest(packageKey, industry, version = "1.0.0") {
return {
packageKey,
version,
visualTemplateKey: packageKey,
runtimeContract: "1.0",
supportedIndustryTemplates: [industry],
previewFixture: { [industry]: { schemaVersion: "1" } },
};
}
function catalogEntry(packageKey, industry, version = "1.0.0") {
return {
packageKey,
version,
displayName: packageKey,
contentChecksum: "a".repeat(64),
validationReport: { errors: [] },
manifest: manifest(packageKey, industry, version),
archiveChecksum: "b".repeat(64),
archivePath: `template-artifacts/${packageKey}/${version}/${"b".repeat(64)}.tar.gz`,
};
}
test("template contract plan resolves legacy installations and imports missing packages", () => {
const existing = catalogEntry("atelier-solopreneur", "personal", "1.3.2");
const defaultBrand = catalogEntry("acheng-campus-food", "food", "1.0.3");
const plan = buildTemplateContractPlan({
catalog: { formatVersion: "1", packages: [existing, defaultBrand] },
versions: [],
brands: [
{
brandId: "brand-1",
slug: "atelier-studio",
templateKey: "personal",
brandVisualTemplateKey: "atelier-solopreneur",
installations: [
{
id: "installation-1",
templatePackageVersionId: null,
visualTemplateKey: null,
snapshotVisualTemplateKey: null,
snapshotPackageKey: null,
},
],
},
{
brandId: "brand-2",
slug: "default-brand",
templateKey: "food",
brandVisualTemplateKey: "acheng-campus-food",
installations: [],
},
],
});
assert.deepEqual(
plan.catalogImports.map((entry) => `${entry.packageKey}@${entry.version}`),
["atelier-solopreneur@1.3.2", "acheng-campus-food@1.0.3"],
);
assert.equal(plan.installations.length, 2);
assert.equal(plan.installations[0].installationId, "installation-1");
assert.equal(plan.installations[0].packageVersionId, null);
assert.equal(plan.installations[0].catalogImport, true);
assert.equal(plan.installations[1].installationId, null);
assert.equal(plan.installations[1].slug, "default-brand");
});
test("template contract plan rejects conflicting legacy package declarations", () => {
assert.throws(
() =>
buildTemplateContractPlan({
catalog: { formatVersion: "1", packages: [] },
versions: [],
brands: [
{
brandId: "brand-1",
slug: "conflicting-brand",
templateKey: "food",
brandVisualTemplateKey: "acheng-campus-food",
installations: [
{
id: "installation-1",
templatePackageVersionId: null,
visualTemplateKey: "linjing-editorial",
snapshotVisualTemplateKey: null,
snapshotPackageKey: null,
},
],
},
],
}),
/模板包声明冲突/,
);
});
+41
View File
@@ -0,0 +1,41 @@
import path from "node:path";
const PLACEHOLDER_PATTERN = /(replace-with|change-me|changeme|^your[-_ ]|example|placeholder)/i;
/** 判断值是否仍是示例占位符,而不是真实随机密钥。 */
export function isPlaceholderSecret(value) {
return PLACEHOLDER_PATTERN.test(value.trim());
}
/**
* 切流前校验共享生产环境文件。
* 除必填项外,必须拒绝示例密钥,避免上线后才在 API 启动时失败。
*/
export function assertReleaseEnvironment(environment) {
if (
environment.NODE_ENV !== "production" ||
!environment.DATABASE_URL ||
!environment.SESSION_SECRET ||
!environment.DEFAULT_BRAND_ID ||
!environment.LOCAL_MEDIA_ROOT
) {
throw new Error("Production environment is missing required values");
}
if (environment.SESSION_SECRET.trim().length < 32) {
throw new Error("SESSION_SECRET must contain at least 32 characters");
}
if (isPlaceholderSecret(environment.SESSION_SECRET)) {
throw new Error("SESSION_SECRET must not use an example placeholder");
}
if (!path.isAbsolute(environment.LOCAL_MEDIA_ROOT)) {
throw new Error("LOCAL_MEDIA_ROOT must be absolute");
}
if (environment.API_PREFIX) {
throw new Error("API_PREFIX must be empty when Traefik strips /api");
}
const throttleStore = environment.CLIENT_ERROR_THROTTLE_STORE ?? "memory";
if (!["memory", "postgres"].includes(throttleStore)) {
throw new Error("CLIENT_ERROR_THROTTLE_STORE must be memory or postgres");
}
return new URL(environment.DATABASE_URL);
}
+55
View File
@@ -0,0 +1,55 @@
import assert from "node:assert/strict";
import test from "node:test";
import { assertReleaseEnvironment } from "./release-environment.mjs";
const validEnvironment = {
NODE_ENV: "production",
DATABASE_URL: "postgresql://user:password@127.0.0.1:5432/personal_brand",
SESSION_SECRET: "Zx9vQ2mK7pL4rT8wY3nB6cF1hJ5sD0gA",
DEFAULT_BRAND_ID: "brand-1",
LOCAL_MEDIA_ROOT: "/srv/personal-brand/media",
};
test("生产环境校验接受真实随机密钥", () => {
const databaseUrl = assertReleaseEnvironment(validEnvironment);
assert.equal(databaseUrl.hostname, "127.0.0.1");
});
test("生产环境校验拒绝示例占位密钥", () => {
assert.throws(
() =>
assertReleaseEnvironment({
...validEnvironment,
SESSION_SECRET: "replace-with-at-least-32-random-characters",
}),
/must not use an example placeholder/,
);
});
test("生产环境校验拒绝过短密钥", () => {
assert.throws(
() => assertReleaseEnvironment({ ...validEnvironment, SESSION_SECRET: "short-secret" }),
/at least 32 characters/,
);
});
test("生产环境校验拒绝缺失的必填项", () => {
assert.throws(
() => assertReleaseEnvironment({ ...validEnvironment, DEFAULT_BRAND_ID: "" }),
/missing required values/,
);
});
test("生产环境校验拒绝 Traefik 之外的 API 前缀", () => {
assert.throws(
() => assertReleaseEnvironment({ ...validEnvironment, API_PREFIX: "/api" }),
/API_PREFIX must be empty/,
);
});
test("生产环境校验拒绝未知的异常限流存储", () => {
assert.throws(
() => assertReleaseEnvironment({ ...validEnvironment, CLIENT_ERROR_THROTTLE_STORE: "redis" }),
/CLIENT_ERROR_THROTTLE_STORE must be memory or postgres/,
);
});
@@ -0,0 +1,195 @@
#!/usr/bin/env node
import { isDeepStrictEqual } from "node:util";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createRequire } from "node:module";
const CONTRACT_KEYS = new Set([
"templateDefinition",
"visualTemplateDefinition",
"visualTemplateManifest",
"templatePackageManifest",
"installation",
"templateKey",
]);
const VOLATILE_KEYS = new Set(["generatedAt"]);
/** null 与缺失键都表示“没有值”,比较前统一剔除,避免旧快照缺列被误判为内容变更。 */
function normalizeNullish(value) {
if (Array.isArray(value)) return value.map(normalizeNullish);
if (value && typeof value === "object") {
const result = {};
for (const [key, item] of Object.entries(value)) {
if (item === null || item === undefined) continue;
result[key] = normalizeNullish(item);
}
return result;
}
return value;
}
function isPlainObject(value) {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
/** 返回递归差异路径,用于判断内容差异是否全部属于显式允许的遗留字段删除。 */
export function diffPaths(published, current, prefix = "") {
if (isPlainObject(published) && isPlainObject(current)) {
const keys = new Set([...Object.keys(published), ...Object.keys(current)]);
return [...keys].flatMap((key) =>
diffPaths(published[key], current[key], prefix ? prefix + "." + key : key),
);
}
return isDeepStrictEqual(published, current) ? [] : [{ path: prefix }];
}
/**
* 只允许自动重发“模板契约字段变化、品牌内容未变”的发布快照。
* 一旦草稿内容与已发布快照不同,必须由管理员显式审查后发布,避免误发草稿。
* allowedRemovedKeys 只能放行“旧值存在、新值缺失”的遗留字段删除,不能放行赋值变化。
*/
export function classifyContractRefresh(published, current, options = {}) {
if (!published || !current) throw new Error("发布快照不能为空");
const allowedRemovedKeys = new Set(options.allowedRemovedKeys ?? []);
const normalizedPublished = normalizeNullish(published);
const normalizedCurrent = normalizeNullish(current);
const keys = new Set([...Object.keys(normalizedPublished), ...Object.keys(normalizedCurrent)]);
const changedKeys = [...keys]
.filter((key) => !VOLATILE_KEYS.has(key))
.filter((key) => !isDeepStrictEqual(normalizedPublished[key], normalizedCurrent[key]));
const blockingKeys = [];
const allowedChanges = [];
for (const key of changedKeys) {
if (CONTRACT_KEYS.has(key)) continue;
const changes = diffPaths(normalizedPublished[key], normalizedCurrent[key], key);
const blocking = changes.filter(
(change) =>
!(allowedRemovedKeys.has(change.path) && isRemovedAtPath(normalizedCurrent, change.path)),
);
if (blocking.length) blockingKeys.push(key);
else allowedChanges.push(...changes.map((change) => change.path));
}
const status = blockingKeys.length
? "content-diverged"
: changedKeys.length
? "contract-stale"
: "current";
return { status, changedKeys, blockingKeys, allowedChanges };
}
function isRemovedAtPath(root, dotPath) {
let node = root;
const parts = dotPath.split(".");
for (const part of parts.slice(0, -1)) {
if (!isPlainObject(node) || !Object.hasOwn(node, part)) return false;
node = node[part];
}
return isPlainObject(node) && !Object.hasOwn(node, parts.at(-1));
}
async function loadServices() {
const apiRequire = createRequire(new URL("../apps/api/package.json", import.meta.url));
const { PrismaService } = await import("../apps/api/dist/prisma.service.js");
const { BrandReleaseService } = await import("../apps/api/dist/brand-release.service.js");
const { BrandReleaseApiService } = await import("../apps/api/dist/brand-release-api.service.js");
// 触发运行时依赖解析,避免发布脚本在错误的工作目录下才失败。
apiRequire("@prisma/client");
const prisma = new PrismaService();
const snapshots = new BrandReleaseService(prisma);
return {
prisma,
snapshots,
releases: new BrandReleaseApiService(prisma, snapshots),
};
}
function parseArgs(argv) {
const options = { apply: false, allowedRemovedKeys: [] };
for (const arg of argv) {
if (arg === "--apply") options.apply = true;
else if (arg.startsWith("--allow-removed-key=")) {
const key = arg.slice("--allow-removed-key=".length);
if (!key) throw new Error("--allow-removed-key 需要字段路径");
options.allowedRemovedKeys.push(key);
} else throw new Error(`未知参数:${arg}`);
}
return options;
}
async function main() {
const options = parseArgs(process.argv.slice(2));
const actorUsername = process.env.TEMPLATE_CATALOG_ACTOR ?? "admin";
const note =
process.env.TEMPLATE_CONTRACT_REPUBLISH_NOTE ?? "模板契约迁移:刷新已发布页面方案兼容性";
const { prisma, snapshots, releases } = await loadServices();
try {
const actor = await prisma.adminUser.findFirst({
where: { username: actorUsername, isEnabled: true },
select: { id: true },
});
if (!actor) throw new Error(`找不到启用的模板迁移操作人:${actorUsername}`);
const brands = await prisma.brandProfile.findMany({
select: { id: true, slug: true },
orderBy: { slug: "asc" },
});
const results = [];
for (const brand of brands) {
const release = await prisma.brandRelease.findFirst({
where: { brandId: brand.id, status: "published" },
orderBy: { version: "desc" },
select: { version: true, snapshot: true },
});
if (!release) {
results.push({ slug: brand.slug, status: "unpublished" });
continue;
}
const current = await snapshots.buildSnapshot(brand.id);
const classification = classifyContractRefresh(release.snapshot, current, options);
const result = {
slug: brand.slug,
releaseVersion: release.version,
...classification,
};
results.push(result);
if (!options.apply || classification.status !== "contract-stale") continue;
const readiness = await releases.readiness(brand.id);
if (!readiness.ready) {
result.status = "not-ready";
result.blockingKeys = readiness.checks
.filter((check) => !check.passed)
.map((check) => check.key);
continue;
}
const published = await releases.publish(brand.id, actor.id, note);
result.status = "republished";
result.newReleaseVersion = published.version;
}
console.log(
JSON.stringify(
{
apply: options.apply,
actor: actorUsername,
allowedRemovedKeys: options.allowedRemovedKeys,
results,
},
null,
2,
),
);
if (
options.apply &&
results.some((item) => ["content-diverged", "not-ready"].includes(item.status))
)
process.exitCode = 1;
} finally {
await prisma.$disconnect();
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
main().catch((error) => {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
});
}
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff. Show more