Compare commits
69
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
45a5e4d666 | ||
|
|
b0265f3be3 | ||
|
|
aa2b6f35b0 | ||
|
|
29116678aa | ||
|
|
b6fedd9f63 | ||
|
|
abf4e1b1c9 | ||
|
|
03460d5ab0 | ||
|
|
8f252d088a | ||
|
|
61f216ae0e | ||
|
|
96c3d3292d | ||
|
|
cbbf122280 | ||
|
|
64b6f5c27c | ||
|
|
a3730ee8fc | ||
|
|
d0a0eeea8c | ||
|
|
e75c524343 | ||
|
|
1a4f71996a | ||
|
|
a2fa6c3c31 | ||
|
|
015947f8fb | ||
|
|
072a1037ac | ||
|
|
447c224fce | ||
|
|
f2fc1e0810 | ||
|
|
12a3bf2f3b | ||
|
|
ca6d1712bd | ||
|
|
e7ef0b3ce5 | ||
|
|
b82aa12875 | ||
|
|
b43b6f2785 | ||
|
|
965dd10219 | ||
|
|
371689484e | ||
|
|
d923b8cea9 | ||
|
|
a1b29cedee | ||
|
|
34504c0b44 | ||
|
|
3af5611da5 | ||
|
|
2fe108d66a | ||
|
|
4cd3749806 | ||
|
|
00aeaa3cb1 | ||
|
|
b190f2758a | ||
|
|
4d9c84defc | ||
|
|
b4e3e86dcd | ||
|
|
5051839986 | ||
|
|
84522a8908 | ||
|
|
18bcdbeb00 | ||
|
|
040504774d | ||
|
|
1001c43af6 | ||
|
|
121148f6cf | ||
|
|
a08a2f0f98 | ||
|
|
669d4a7de6 | ||
|
|
ec0cf78d69 | ||
|
|
658c94a4e9 | ||
|
|
261a33a5ca | ||
|
|
f28332f49a | ||
|
|
c33c9cbd63 | ||
|
|
b742fc70b5 | ||
|
|
6bd91d5ee8 | ||
|
|
cdc7b407bc | ||
|
|
9bfa4bb736 | ||
|
|
c04ab1ef60 | ||
|
|
4a6bc42635 | ||
|
|
b86c661af5 | ||
|
|
71c068966e | ||
|
|
784b9cbac8 | ||
|
|
2325214078 | ||
|
|
e194e605f9 | ||
|
|
82381a5e93 | ||
|
|
ec6b0dee3e | ||
|
|
060bad2df0 | ||
|
|
adcaa12970 | ||
|
|
330d67adc1 | ||
|
|
737010ea03 | ||
|
|
ec84988e57 |
No files matched your search
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"schemaVersion": 1,
|
"schemaVersion": 1,
|
||||||
"scope": "模板完成证据登记,保留命令、日志与产物哈希",
|
"scope": "模板完成证据登记,保留命令、日志与产物哈希",
|
||||||
"generatedAt": "2026-10-20T13:23:08.179Z",
|
"generatedAt": "2026-10-29T07:09:56.748Z",
|
||||||
"templates": {
|
"templates": {
|
||||||
"acheng-campus-food": {
|
"acheng-campus-food": {
|
||||||
"real-manifest-interaction": {
|
"real-manifest-interaction": {
|
||||||
@@ -256,5 +256,5 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"sourceTreeHash": "7db7647772c54d29bcff2211b59bc3a1c261988b543046ba3b078d5945d3a599"
|
"sourceTreeHash": "6c984c7a56aeef55ed6af2b9f95ec5a8fb2073405b14846fdc79e056c8fe2a65"
|
||||||
}
|
}
|
||||||
@@ -1212,7 +1212,7 @@
|
|||||||
"code": "CONDITIONAL_RENDER_REVIEW",
|
"code": "CONDITIONAL_RENDER_REVIEW",
|
||||||
"severity": "review",
|
"severity": "review",
|
||||||
"file": "packages/template-atelier-solopreneur/taro/index.tsx",
|
"file": "packages/template-atelier-solopreneur/taro/index.tsx",
|
||||||
"target": "atelier-solopreneur.detail.projectDetail",
|
"target": "atelier-solopreneur.detail.projectHero",
|
||||||
"line": 310,
|
"line": 310,
|
||||||
"message": "条件显示需验证全部分支与空数据入口。",
|
"message": "条件显示需验证全部分支与空数据入口。",
|
||||||
"reviewStatus": "source-reviewed",
|
"reviewStatus": "source-reviewed",
|
||||||
@@ -1229,7 +1229,7 @@
|
|||||||
"code": "UNRESOLVED_RENDER_VALUE",
|
"code": "UNRESOLVED_RENDER_VALUE",
|
||||||
"severity": "review",
|
"severity": "review",
|
||||||
"file": "packages/template-atelier-solopreneur/taro/index.tsx",
|
"file": "packages/template-atelier-solopreneur/taro/index.tsx",
|
||||||
"target": "atelier-solopreneur.detail.projectDetail",
|
"target": "atelier-solopreneur.detail.projectFacts",
|
||||||
"page": "detail",
|
"page": "detail",
|
||||||
"expression": "[item.category, item.area, item.series].filter",
|
"expression": "[item.category, item.area, item.series].filter",
|
||||||
"line": 340,
|
"line": 340,
|
||||||
@@ -1248,7 +1248,7 @@
|
|||||||
"code": "DYNAMIC_TARGET_REVIEW",
|
"code": "DYNAMIC_TARGET_REVIEW",
|
||||||
"severity": "review",
|
"severity": "review",
|
||||||
"file": "packages/template-atelier-solopreneur/taro/index.tsx",
|
"file": "packages/template-atelier-solopreneur/taro/index.tsx",
|
||||||
"line": 433,
|
"line": 453,
|
||||||
"message": "动态目标需用真实 manifest 和实际记录验证分支。",
|
"message": "动态目标需用真实 manifest 和实际记录验证分支。",
|
||||||
"reviewStatus": "source-reviewed",
|
"reviewStatus": "source-reviewed",
|
||||||
"decision": "formTargets 为固定映射,模板只对 inquiry 注入 chips 和隐私区,其余共享页面保持原 children;没有动态业务 binding。",
|
"decision": "formTargets 为固定映射,模板只对 inquiry 注入 chips 和隐私区,其余共享页面保持原 children;没有动态业务 binding。",
|
||||||
@@ -1860,7 +1860,7 @@
|
|||||||
"severity": "review",
|
"severity": "review",
|
||||||
"file": "packages/template-atelier-solopreneur/taro/index.tsx",
|
"file": "packages/template-atelier-solopreneur/taro/index.tsx",
|
||||||
"page": "detail",
|
"page": "detail",
|
||||||
"target": "atelier-solopreneur.detail.projectDetail",
|
"target": "atelier-solopreneur.detail.projectFacts",
|
||||||
"expression": "[item.category, item.area, item.series].filter(Boolean).map",
|
"expression": "[item.category, item.area, item.series].filter(Boolean).map",
|
||||||
"line": 340,
|
"line": 340,
|
||||||
"message": "需要核对循环项或间接映射,不能视为已覆盖。",
|
"message": "需要核对循环项或间接映射,不能视为已覆盖。",
|
||||||
|
|||||||
+5
-4
@@ -9,6 +9,8 @@ API_PREFIX=
|
|||||||
CORS_ORIGINS=http://localhost:3000
|
CORS_ORIGINS=http://localhost:3000
|
||||||
ADMIN_PORT=3000
|
ADMIN_PORT=3000
|
||||||
SESSION_SECRET=replace-with-a-long-random-value
|
SESSION_SECRET=replace-with-a-long-random-value
|
||||||
|
# 单实例使用 memory;多实例部署改用 postgres 并先执行数据库迁移
|
||||||
|
CLIENT_ERROR_THROTTLE_STORE=memory
|
||||||
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
||||||
TEMPLATE_ARTIFACT_ROOT=/var/lib/personal-brand/template-artifacts
|
TEMPLATE_ARTIFACT_ROOT=/var/lib/personal-brand/template-artifacts
|
||||||
SEED_ADMIN_PASSWORD=change-me-now-123
|
SEED_ADMIN_PASSWORD=change-me-now-123
|
||||||
@@ -17,19 +19,18 @@ OBJECT_STORAGE_PUBLIC_URL=http://localhost:9000/personal-brand-media
|
|||||||
OBJECT_STORAGE_BUCKET=personal-brand-media
|
OBJECT_STORAGE_BUCKET=personal-brand-media
|
||||||
OBJECT_STORAGE_ACCESS_KEY=minioadmin
|
OBJECT_STORAGE_ACCESS_KEY=minioadmin
|
||||||
OBJECT_STORAGE_SECRET_KEY=minioadmin
|
OBJECT_STORAGE_SECRET_KEY=minioadmin
|
||||||
WECHAT_APP_ID=
|
# 微信 AppID 与 AppSecret 按品牌在后台「小程序配置」维护,不使用全局环境变量
|
||||||
WECHAT_APP_SECRET=
|
|
||||||
WECHAT_UPLOAD_PRIVATE_KEY=
|
WECHAT_UPLOAD_PRIVATE_KEY=
|
||||||
MINIAPP_CREDENTIAL_ENCRYPTION_KEY=replace-with-32-byte-random-secret
|
MINIAPP_CREDENTIAL_ENCRYPTION_KEY=replace-with-32-byte-random-secret
|
||||||
# 小程序代码构建产物根目录,相对路径按仓库根目录解析;默认 apps/taro/dist
|
# 小程序代码构建产物根目录,相对路径按仓库根目录解析;默认 apps/taro/dist
|
||||||
# MINIAPP_ARTIFACT_ROOT=apps/taro/dist
|
# MINIAPP_ARTIFACT_ROOT=apps/taro/dist
|
||||||
# 构建超过该毫秒数没有进度更新即视为中断,允许重新上传;默认 15 分钟
|
# 构建超过该毫秒数没有进度更新即视为中断,允许重新上传;默认 15 分钟
|
||||||
# MINIAPP_BUILD_STALE_MS=900000
|
# MINIAPP_BUILD_STALE_MS=900000
|
||||||
# 小程序请求地址在后台「小程序上传配置」维护,这里仅为回落值;
|
# 小程序请求地址在后台「小程序配置」维护,这里仅为回落值;
|
||||||
# 未设置时由 PUBLIC_BASE_URL + MINIAPP_API_PATH 推导
|
# 未设置时由 PUBLIC_BASE_URL + MINIAPP_API_PATH 推导
|
||||||
# MINIAPP_API_BASE_URL=https://wechat.app.que01.top/api
|
# MINIAPP_API_BASE_URL=https://wechat.app.que01.top/api
|
||||||
# MINIAPP_API_PATH=/api
|
# MINIAPP_API_PATH=/api
|
||||||
# 单个品牌的 AppID 在后台“小程序上传配置”维护,这里只作为回落值
|
# 单个品牌的 AppID 在后台“小程序配置”维护,这里只作为回落值
|
||||||
# WEAPP_APP_ID=
|
# WEAPP_APP_ID=
|
||||||
# 上传子进程工作目录;miniprogram-ci 的编译缓存放这里,默认系统临时目录
|
# 上传子进程工作目录;miniprogram-ci 的编译缓存放这里,默认系统临时目录
|
||||||
# MINIAPP_UPLOAD_WORKSPACE=/tmp/personal-brand-miniapp-upload
|
# MINIAPP_UPLOAD_WORKSPACE=/tmp/personal-brand-miniapp-upload
|
||||||
+13
-3
@@ -6,6 +6,11 @@ POSTGRES_PORT=5432
|
|||||||
|
|
||||||
DATABASE_URL=postgresql://personal_brand:replace-with-a-long-database-password@127.0.0.1:5432/personal_brand?schema=public
|
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
|
SESSION_SECRET=replace-with-at-least-32-random-characters
|
||||||
|
# 建议单独配置并长期保持不变;未设置时回退 SESSION_SECRET。
|
||||||
|
# 轮换该密钥后,已保存的上传私钥和 AppSecret 都需要在后台重新填写。
|
||||||
|
# MINIAPP_CREDENTIAL_ENCRYPTION_KEY=replace-with-32-byte-random-secret
|
||||||
|
# 单实例使用 memory;多实例部署改用 postgres 并先执行数据库迁移
|
||||||
|
CLIENT_ERROR_THROTTLE_STORE=memory
|
||||||
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
||||||
SEED_ADMIN_PASSWORD=replace-with-a-one-time-initial-password
|
SEED_ADMIN_PASSWORD=replace-with-a-one-time-initial-password
|
||||||
SEED_MODE=skip
|
SEED_MODE=skip
|
||||||
@@ -14,6 +19,12 @@ API_PORT=3001
|
|||||||
API_PREFIX=
|
API_PREFIX=
|
||||||
CORS_ORIGINS=
|
CORS_ORIGINS=
|
||||||
|
|
||||||
|
# 发布备份保留 7 份;定时备份默认保留 14 天
|
||||||
|
BACKUP_RETENTION_DAYS=14
|
||||||
|
# 可选:配置 rsync 目标后,每次定时备份会额外复制一份到异地
|
||||||
|
# 需要预先为 ubuntu 用户配置 SSH key;未配置时备份只保留在本机
|
||||||
|
# BACKUP_OFFSITE_TARGET=backup@example-host:/srv/personal-brand-backups/
|
||||||
|
|
||||||
LOCAL_MEDIA_ROOT=/home/ubuntu/persional-brand/media
|
LOCAL_MEDIA_ROOT=/home/ubuntu/persional-brand/media
|
||||||
LOCAL_MEDIA_BASE_URL=/media
|
LOCAL_MEDIA_BASE_URL=/media
|
||||||
OBJECT_STORAGE_ENDPOINT=
|
OBJECT_STORAGE_ENDPOINT=
|
||||||
@@ -23,10 +34,9 @@ OBJECT_STORAGE_ACCESS_KEY=
|
|||||||
OBJECT_STORAGE_SECRET_KEY=
|
OBJECT_STORAGE_SECRET_KEY=
|
||||||
OBJECT_STORAGE_REGION=us-east-1
|
OBJECT_STORAGE_REGION=us-east-1
|
||||||
|
|
||||||
WECHAT_APP_ID=
|
# 微信 AppID 与 AppSecret 按品牌在后台「小程序配置」维护,不使用全局环境变量
|
||||||
WECHAT_APP_SECRET=
|
|
||||||
|
|
||||||
# 小程序请求地址正常情况下在后台「小程序上传配置」维护;
|
# 小程序请求地址正常情况下在后台「小程序配置」维护;
|
||||||
# 这里仅作为后台未配置时的回落值(否则由 PUBLIC_BASE_URL + /api 推导)
|
# 这里仅作为后台未配置时的回落值(否则由 PUBLIC_BASE_URL + /api 推导)
|
||||||
# MINIAPP_API_BASE_URL=https://wechat.app.que01.top/api
|
# MINIAPP_API_BASE_URL=https://wechat.app.que01.top/api
|
||||||
# MINIAPP_BUILD_STALE_MS=900000
|
# MINIAPP_BUILD_STALE_MS=900000
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
# 纯文档提交不占用 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"
|
||||||
|
# runner 任务容器把该路径 bind mount 到宿主机共享 store,避免每个 job 重复下载依赖。
|
||||||
|
npm_config_store_dir: /workspace/.pnpm-store
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
static:
|
||||||
|
name: Static checks
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 40
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Verify preinstalled toolchain
|
||||||
|
# 任务镜像已内置 Node 与 pnpm;不在这里下载 Node,避免 nodejs.org 慢连接拖死整个 job。
|
||||||
|
run: |
|
||||||
|
actual_node="$(node -p 'process.versions.node')"
|
||||||
|
actual_pnpm="$(pnpm --version)"
|
||||||
|
test "${actual_node%%.*}" = "$NODE_VERSION" || { echo "expected Node $NODE_VERSION.x, got $actual_node" >&2; exit 1; }
|
||||||
|
test "$actual_pnpm" = "$PNPM_VERSION" || { echo "expected pnpm $PNPM_VERSION, got $actual_pnpm" >&2; exit 1; }
|
||||||
|
- name: Restore Prisma engine cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ~/.cache/prisma
|
||||||
|
key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||||
|
restore-keys: |
|
||||||
|
prisma-${{ runner.os }}-${{ runner.arch }}-
|
||||||
|
- name: Restore Turbo cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: .turbo/cache
|
||||||
|
key: turbo-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }}
|
||||||
|
restore-keys: |
|
||||||
|
turbo-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}-
|
||||||
|
turbo-${{ runner.os }}-${{ runner.arch }}-
|
||||||
|
- run: pnpm install --frozen-lockfile
|
||||||
|
- run: pnpm check
|
||||||
|
- run: pnpm test:api-routes
|
||||||
|
- run: pnpm test:deploy
|
||||||
|
- 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
|
||||||
|
- name: Verify preinstalled toolchain
|
||||||
|
# 任务镜像已内置 Node 与 pnpm;不在这里下载 Node,避免 nodejs.org 慢连接拖死整个 job。
|
||||||
|
run: |
|
||||||
|
actual_node="$(node -p 'process.versions.node')"
|
||||||
|
actual_pnpm="$(pnpm --version)"
|
||||||
|
test "${actual_node%%.*}" = "$NODE_VERSION" || { echo "expected Node $NODE_VERSION.x, got $actual_node" >&2; exit 1; }
|
||||||
|
test "$actual_pnpm" = "$PNPM_VERSION" || { echo "expected pnpm $PNPM_VERSION, got $actual_pnpm" >&2; exit 1; }
|
||||||
|
- name: Restore Prisma engine cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ~/.cache/prisma
|
||||||
|
key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||||
|
restore-keys: |
|
||||||
|
prisma-${{ runner.os }}-${{ runner.arch }}-
|
||||||
|
- name: Restore Turbo cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: .turbo/cache
|
||||||
|
key: turbo-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }}
|
||||||
|
restore-keys: |
|
||||||
|
turbo-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}-
|
||||||
|
turbo-${{ runner.os }}-${{ runner.arch }}-
|
||||||
|
- 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
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Verify preinstalled toolchain
|
||||||
|
# 任务镜像已内置 Node 与 pnpm;不在这里下载 Node,避免 nodejs.org 慢连接拖死整个 job。
|
||||||
|
run: |
|
||||||
|
actual_node="$(node -p 'process.versions.node')"
|
||||||
|
actual_pnpm="$(pnpm --version)"
|
||||||
|
test "${actual_node%%.*}" = "$NODE_VERSION" || { echo "expected Node $NODE_VERSION.x, got $actual_node" >&2; exit 1; }
|
||||||
|
test "$actual_pnpm" = "$PNPM_VERSION" || { echo "expected pnpm $PNPM_VERSION, got $actual_pnpm" >&2; exit 1; }
|
||||||
|
- name: Restore Prisma engine cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ~/.cache/prisma
|
||||||
|
key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||||
|
restore-keys: |
|
||||||
|
prisma-${{ runner.os }}-${{ runner.arch }}-
|
||||||
|
- run: pnpm install --frozen-lockfile
|
||||||
|
- name: Cache Playwright browsers
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ~/.cache/ms-playwright
|
||||||
|
key: playwright-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||||
|
- name: Install Chromium
|
||||||
|
# 系统依赖与同版本 Chromium 已预装在 personal-brand-ci:node24 中;这里只做版本兜底。
|
||||||
|
run: pnpm --filter @personal-brand/taro exec playwright install chromium
|
||||||
|
- name: Run PR browser smoke
|
||||||
|
run: pnpm test:browser:smoke
|
||||||
|
|
||||||
|
api:
|
||||||
|
name: API integration
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 45
|
||||||
|
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
|
||||||
|
- name: Verify preinstalled toolchain
|
||||||
|
# 任务镜像已内置 Node 与 pnpm;不在这里下载 Node,避免 nodejs.org 慢连接拖死整个 job。
|
||||||
|
run: |
|
||||||
|
actual_node="$(node -p 'process.versions.node')"
|
||||||
|
actual_pnpm="$(pnpm --version)"
|
||||||
|
test "${actual_node%%.*}" = "$NODE_VERSION" || { echo "expected Node $NODE_VERSION.x, got $actual_node" >&2; exit 1; }
|
||||||
|
test "$actual_pnpm" = "$PNPM_VERSION" || { echo "expected pnpm $PNPM_VERSION, got $actual_pnpm" >&2; exit 1; }
|
||||||
|
- name: Restore Prisma engine cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ~/.cache/prisma
|
||||||
|
key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||||
|
restore-keys: |
|
||||||
|
prisma-${{ runner.os }}-${{ runner.arch }}-
|
||||||
|
- 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
|
||||||
Executable
+6
@@ -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
|
||||||
@@ -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
|
|
||||||
@@ -24,6 +24,9 @@ media/
|
|||||||
|
|
||||||
**/.swc/
|
**/.swc/
|
||||||
.codex-tasks/
|
.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
|
docker-compose.override.yml
|
||||||
.env.production
|
.env.production
|
||||||
|
|
||||||
|
|||||||
+29
-4
@@ -27,6 +27,7 @@ ADR 0033 已落地:
|
|||||||
- Taro Runtime、Admin 组件预览、真实 manifest 驱动编辑、草稿/发布隔离。
|
- Taro Runtime、Admin 组件预览、真实 manifest 驱动编辑、草稿/发布隔离。
|
||||||
- 发布备注为可选字段;空备注不会写入数据库,也不影响发布、回滚和公开内容。
|
- 发布备注为可选字段;空备注不会写入数据库,也不影响发布、回滚和公开内容。
|
||||||
- 依赖 override 的运行时兼容性通过 `miniprogram-ci` / Jimp / image-size / uuid smoke test 守卫。
|
- 依赖 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 和失败记录。
|
- 小程序构建、上传任务状态机、attempt lease 和失败记录。
|
||||||
- Admin/Customer token version:修改 admin 密码或调用 logout 后旧 token 立即失效;无 membership 的账号不会自动获得 owner 权限。
|
- Admin/Customer token version:修改 admin 密码或调用 logout 后旧 token 立即失效;无 membership 的账号不会自动获得 owner 权限。
|
||||||
- `visualPresentation` 已进入唯一 `template.json` 契约,旧手写 visual manifest 优先路径已删除。
|
- `visualPresentation` 已进入唯一 `template.json` 契约,旧手写 visual manifest 优先路径已删除。
|
||||||
@@ -36,10 +37,10 @@ ADR 0033 已落地:
|
|||||||
当前生产 release:
|
当前生产 release:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
20261021024748-e752a3b7edb6
|
20261023100112-a2fa6c3c3140
|
||||||
```
|
```
|
||||||
|
|
||||||
该 release 由提交 `e752a3b` 构建,包含创建品牌与页面方案的交互修复、发布流程浏览器回归、小程序配置表单实例修复、前置的 Node 24 版本门禁,以及 Ant Design 6 弃用项收口。部署后已完成公开路由健康检查、三个品牌公开接口和发布快照核对。
|
该 release 由提交 `a2fa6c3` 构建,新增生产数据库每日定时备份、备份可读性校验、发布/定时备份保留策略、`backup-timer` 与 `backup-age-hours` 部署状态门禁。部署后已手动触发一次 `personal-brand-backup.service`,生成 `scheduled-20261023T100426Z-1029929.dump`,并通过 `pg_restore -l` 校验可读。
|
||||||
|
|
||||||
生产健康检查:
|
生产健康检查:
|
||||||
|
|
||||||
@@ -48,11 +49,16 @@ api=online
|
|||||||
pm2-autostart=enabled
|
pm2-autostart=enabled
|
||||||
admin=active
|
admin=active
|
||||||
database=running
|
database=running
|
||||||
backups=7
|
backups=8
|
||||||
|
latest-backup=2026-10-23 10:04:27 +0000 scheduled-20261023T100426Z-1029929.dump
|
||||||
|
backup-timer=active
|
||||||
|
backup-age-hours=0
|
||||||
|
backup-temp-files=0
|
||||||
/admin/ 200
|
/admin/ 200
|
||||||
/template-preview/ 200
|
/template-preview/ 200
|
||||||
/api/health 200
|
/api/health 200
|
||||||
/media/seed/food-package-02.jpg 200
|
/media/seed/food-package-02.jpg 200
|
||||||
|
/admin/client-errors(无登录态) 401
|
||||||
```
|
```
|
||||||
|
|
||||||
生产数据库已应用全部 48 个 Prisma migration,schema 为 up to date。
|
生产数据库已应用全部 48 个 Prisma migration,schema 为 up to date。
|
||||||
@@ -101,6 +107,24 @@ Admin 浏览器回归新增 `apps/taro/test/browser/brand-creation-and-page-sche
|
|||||||
|
|
||||||
该回归同时发现并修复了 `MiniAppSettingsTab` 的 `Form` 实例归属问题:表单实例原本在父组件创建、子组件懒挂载,触发 antd `useForm` 未连接警告;现已下沉到配置页自身。
|
该回归同时发现并修复了 `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 弃用项
|
## Ant Design 6 弃用项
|
||||||
|
|
||||||
- `Alert` 统一使用 `title`,`Space` 统一使用 `orientation`。
|
- `Alert` 统一使用 `title`,`Space` 统一使用 `orientation`。
|
||||||
@@ -125,6 +149,8 @@ Admin 浏览器回归新增 `apps/taro/test/browser/brand-creation-and-page-sche
|
|||||||
- `pnpm template:doctor`
|
- `pnpm template:doctor`
|
||||||
- Playwright:
|
- Playwright:
|
||||||
- `brand-creation-and-page-scheme.spec.ts`
|
- `brand-creation-and-page-scheme.spec.ts`
|
||||||
|
- `publication-release.spec.ts`
|
||||||
|
- `admin-error-boundary.spec.ts`
|
||||||
- `template-preview-media.spec.ts`
|
- `template-preview-media.spec.ts`
|
||||||
- `admin-editor.spec.ts`
|
- `admin-editor.spec.ts`
|
||||||
|
|
||||||
@@ -139,7 +165,6 @@ Admin 浏览器回归新增 `apps/taro/test/browser/brand-creation-and-page-sche
|
|||||||
|
|
||||||
## 未决事项
|
## 未决事项
|
||||||
|
|
||||||
- 本次源码新增的 Admin 浏览器回归、页面方案查询缓存修复和 Node 门禁修复尚未部署到生产;部署后需更新本节的生产 release 和验证结果。
|
|
||||||
- `miniprogram-ci` 上游发布修复版本后,需要移除对应的 audit ignore、风险登记和本地 patch。
|
- `miniprogram-ci` 上游发布修复版本后,需要移除对应的 audit ignore、风险登记和本地 patch。
|
||||||
- Gitea SSH 直连仍受 OCI 安全列表限制;当前本机通过 `oracle_arm` ProxyCommand 转发访问,不阻塞业务。
|
- Gitea SSH 直连仍受 OCI 安全列表限制;当前本机通过 `oracle_arm` ProxyCommand 转发访问,不阻塞业务。
|
||||||
- CI 已加入 audit 和三套模板矩阵构建;后续可继续拆分更细粒度的 smoke/visual matrix。
|
- CI 已加入 audit 和三套模板矩阵构建;后续可继续拆分更细粒度的 smoke/visual matrix。
|
||||||
@@ -42,6 +42,7 @@ import { AdminOverviewRedirect } from "./AdminRouter.js";
|
|||||||
import { createBrandRouteElement } from "./route-access.js";
|
import { createBrandRouteElement } from "./route-access.js";
|
||||||
import { Suspense } from "react";
|
import { Suspense } from "react";
|
||||||
import { AdminErrorBoundary } from "../components/AdminErrorBoundary.js";
|
import { AdminErrorBoundary } from "../components/AdminErrorBoundary.js";
|
||||||
|
import { toBrandDisplayName, toBrandSwitcherOptions } from "../lib/brand-switcher.js";
|
||||||
|
|
||||||
export function Dashboard({
|
export function Dashboard({
|
||||||
onLogout,
|
onLogout,
|
||||||
@@ -72,6 +73,8 @@ export function Dashboard({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
const page = location.pathname.split("/")[2] || "overview";
|
const page = location.pathname.split("/")[2] || "overview";
|
||||||
|
const brandName = toBrandDisplayName(brand.data?.name, "当前品牌");
|
||||||
|
const brandOptions = toBrandSwitcherOptions(memberships.data);
|
||||||
const items = [
|
const items = [
|
||||||
{
|
{
|
||||||
type: "group" as const,
|
type: "group" as const,
|
||||||
@@ -108,7 +111,7 @@ export function Dashboard({
|
|||||||
<AdminLayout className="admin-shell">
|
<AdminLayout className="admin-shell">
|
||||||
<AdminLayout.Sider className="admin-sider" breakpoint="lg" collapsedWidth={0} width={232}>
|
<AdminLayout.Sider className="admin-sider" breakpoint="lg" collapsedWidth={0} width={232}>
|
||||||
<div className="admin-sider-brand">
|
<div className="admin-sider-brand">
|
||||||
<BrandMark name={brand.data?.name} />
|
<BrandMark name={toBrandDisplayName(brand.data?.name, "")} />
|
||||||
<span className="admin-sider-brand-name">品牌工作区</span>
|
<span className="admin-sider-brand-name">品牌工作区</span>
|
||||||
</div>
|
</div>
|
||||||
<AdminMenu
|
<AdminMenu
|
||||||
@@ -120,7 +123,7 @@ export function Dashboard({
|
|||||||
<AdminLayout className="admin-main">
|
<AdminLayout className="admin-main">
|
||||||
<AdminLayout.Header className="admin-header">
|
<AdminLayout.Header className="admin-header">
|
||||||
<div className="admin-header-left">
|
<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>
|
<span className="admin-header-context">品牌工作区</span>
|
||||||
<StatusTag
|
<StatusTag
|
||||||
tone={role === "owner" ? "info" : "neutral"}
|
tone={role === "owner" ? "info" : "neutral"}
|
||||||
@@ -135,10 +138,7 @@ export function Dashboard({
|
|||||||
onChange={(value: string | undefined) => {
|
onChange={(value: string | undefined) => {
|
||||||
if (value) void switchBrand(value);
|
if (value) void switchBrand(value);
|
||||||
}}
|
}}
|
||||||
options={(memberships.data ?? []).map((item) => ({
|
options={brandOptions}
|
||||||
value: item.brand.id,
|
|
||||||
label: item.brand.name,
|
|
||||||
}))}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<AdminButton type="text" onClick={onLogout}>
|
<AdminButton type="text" onClick={onLogout}>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Component, type ErrorInfo, type ReactNode } from "react";
|
import { Component, type ErrorInfo, type ReactNode } from "react";
|
||||||
import { Button, Result, Space, Typography } from "antd";
|
import { Button, Result, Space, Typography } from "antd";
|
||||||
|
import { createApiClient } from "../lib/api.js";
|
||||||
|
|
||||||
interface AdminErrorBoundaryProps {
|
interface AdminErrorBoundaryProps {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
@@ -24,13 +25,28 @@ export class AdminErrorBoundary extends Component<
|
|||||||
AdminErrorBoundaryState
|
AdminErrorBoundaryState
|
||||||
> {
|
> {
|
||||||
override state: AdminErrorBoundaryState = { error: null, errorId: null };
|
override state: AdminErrorBoundaryState = { error: null, errorId: null };
|
||||||
|
private reportedErrorId: string | null = null;
|
||||||
|
|
||||||
static getDerivedStateFromError(error: Error): AdminErrorBoundaryState {
|
static getDerivedStateFromError(error: Error): AdminErrorBoundaryState {
|
||||||
return { error, errorId: createErrorId() };
|
return { error, errorId: createErrorId() };
|
||||||
}
|
}
|
||||||
|
|
||||||
override componentDidCatch(error: Error, info: ErrorInfo) {
|
override componentDidCatch(error: Error, info: ErrorInfo) {
|
||||||
console.error("[admin] 页面渲染异常", this.state.errorId, error, info.componentStack);
|
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 = () => {
|
private reset = () => {
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ export function RecordContentFields({
|
|||||||
return (
|
return (
|
||||||
<Row gutter={16}>
|
<Row gutter={16}>
|
||||||
{section.fields.map((field) => (
|
{section.fields.map((field) => (
|
||||||
<Col key={field.key} xs={24} md={24}>
|
<Col key={field.key} xs={24} md={24} data-presentation-binding={field.binding}>
|
||||||
{field.input === "list" ? (
|
{field.input === "list" ? (
|
||||||
<TemplateListField field={field} name={presentationFieldName(sectionKey, field.key)} />
|
<TemplateListField field={field} name={presentationFieldName(sectionKey, field.key)} />
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
type PresentationValues,
|
type PresentationValues,
|
||||||
} from "../../lib/presentation/presentation-bindings.js";
|
} from "../../lib/presentation/presentation-bindings.js";
|
||||||
import type { RecordContentSource } from "./types.js";
|
import type { RecordContentSource } from "./types.js";
|
||||||
|
import { getFullFormValues } from "../../lib/form-values.js";
|
||||||
|
|
||||||
function createInitialValues(
|
function createInitialValues(
|
||||||
record: Offering | TrustContent,
|
record: Offering | TrustContent,
|
||||||
@@ -96,12 +97,12 @@ export function useRecordContentEditorState({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const submit = (values: PresentationValues) => {
|
const submit = (values: PresentationValues) => {
|
||||||
const currentValues = form.getFieldsValue(true) as PresentationValues;
|
const currentValues = getFullFormValues<PresentationValues>(form);
|
||||||
save.mutate({ ...draftValues, ...values, ...currentValues });
|
save.mutate({ ...draftValues, ...values, ...currentValues });
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleValuesChange = (_values: PresentationValues) => {
|
const handleValuesChange = (_values: PresentationValues) => {
|
||||||
const currentValues = form.getFieldsValue(true) as PresentationValues;
|
const currentValues = getFullFormValues<PresentationValues>(form);
|
||||||
const next = { ...draftValues, ..._values, ...currentValues };
|
const next = { ...draftValues, ..._values, ...currentValues };
|
||||||
setDraftValues(next);
|
setDraftValues(next);
|
||||||
onDraft?.(next);
|
onDraft?.(next);
|
||||||
|
|||||||
@@ -28,8 +28,9 @@ export function InquiryPreviewEditor({
|
|||||||
const record = query.data?.find((item) => item.id === runtime.key);
|
const record = query.data?.find((item) => item.id === runtime.key);
|
||||||
const field = runtime.fields.find((item) => item.key === fieldKey);
|
const field = runtime.fields.find((item) => item.key === fieldKey);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (field) form.setFieldsValue({ ...field });
|
if (!record || !field) return;
|
||||||
}, [fieldKey, runtime.key, form]);
|
form.setFieldsValue({ ...field });
|
||||||
|
}, [field, fieldKey, form, record, runtime.key]);
|
||||||
const update = (values: Record<string, unknown>) =>
|
const update = (values: Record<string, unknown>) =>
|
||||||
runtime.fields.map((item) => (item.key === fieldKey ? { ...item, ...values } : item));
|
runtime.fields.map((item) => (item.key === fieldKey ? { ...item, ...values } : item));
|
||||||
const save = useMutation({
|
const save = useMutation({
|
||||||
|
|||||||
@@ -1,34 +1,15 @@
|
|||||||
import { Alert, Button, Grid, Select, Segmented, Space, Typography } from "antd";
|
import { Alert, Grid, Segmented, Select, Space } from "antd";
|
||||||
import { useQueryClient } from "@tanstack/react-query";
|
import type {
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
AdminTemplateContent,
|
||||||
import { useNavigate } from "react-router-dom";
|
BrandProfile,
|
||||||
import type { AdminTemplateContent, RuntimeWorkspace } from "@personal-brand/api-client";
|
RuntimeWorkspace,
|
||||||
import type { BrandProfile } from "@personal-brand/api-client";
|
} from "@personal-brand/api-client";
|
||||||
import { StatusTag } from "../../components/StatusTag.js";
|
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 "./PresentationEditor.css";
|
||||||
import { useEditorDraft } from "./use-editor-draft.js";
|
import type { PreviewSelection } from "./preview-selection.js";
|
||||||
import {
|
import { usePresentationEditorController } from "./presentation-editor-controller.js";
|
||||||
usePresentationRecordQueries,
|
import { PresentationEditorInspector } from "./PresentationEditorInspector.js";
|
||||||
useBrandPresentationSections,
|
import { PresentationEditorPreview } from "./PresentationEditorPreview.js";
|
||||||
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";
|
|
||||||
|
|
||||||
interface PresentationEditorProps {
|
interface PresentationEditorProps {
|
||||||
templateContent: AdminTemplateContent | null | undefined;
|
templateContent: AdminTemplateContent | null | undefined;
|
||||||
@@ -49,254 +30,14 @@ export function PresentationEditor({
|
|||||||
error,
|
error,
|
||||||
initialSelection,
|
initialSelection,
|
||||||
}: PresentationEditorProps) {
|
}: PresentationEditorProps) {
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const navigate = useNavigate();
|
|
||||||
const breakpoints = Grid.useBreakpoint();
|
const breakpoints = Grid.useBreakpoint();
|
||||||
const [activePage, setActivePage] = useState<string>();
|
const controller = usePresentationEditorController({
|
||||||
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,
|
templateContent,
|
||||||
|
previewWorkspace,
|
||||||
|
config,
|
||||||
|
brand,
|
||||||
|
...(initialSelection ? { initialSelection } : {}),
|
||||||
});
|
});
|
||||||
const selectedDetailOfferingId =
|
|
||||||
detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId)
|
|
||||||
? detailOfferingId
|
|
||||||
: draftWorkspace?.offerings[0]?.id;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="presentation-editor" aria-labelledby="presentation-editor-title">
|
<section className="presentation-editor" aria-labelledby="presentation-editor-title">
|
||||||
@@ -324,306 +65,33 @@ export function PresentationEditor({
|
|||||||
{breakpoints.xs ? (
|
{breakpoints.xs ? (
|
||||||
<Select
|
<Select
|
||||||
aria-label="选择小程序页面"
|
aria-label="选择小程序页面"
|
||||||
value={selectedPage}
|
value={controller.selectedPage ?? null}
|
||||||
options={pageOptions}
|
options={controller.pageOptions}
|
||||||
onChange={(value) =>
|
onChange={controller.selectPage}
|
||||||
guardDraft(() => {
|
|
||||||
setBrandDirty(false);
|
|
||||||
form.setFieldsValue(initialValues);
|
|
||||||
resetPreview();
|
|
||||||
setRecordDraft(undefined);
|
|
||||||
setInquiryDraft(undefined);
|
|
||||||
setActivePage(value);
|
|
||||||
})
|
|
||||||
}
|
|
||||||
className="admin-field-w-2xl"
|
className="admin-field-w-2xl"
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<Segmented
|
<Segmented
|
||||||
value={selectedPage}
|
value={controller.selectedPage ?? null}
|
||||||
options={pageOptions}
|
options={controller.pageOptions}
|
||||||
onChange={(value) =>
|
onChange={(value) => controller.selectPage(String(value))}
|
||||||
guardDraft(() => {
|
|
||||||
setBrandDirty(false);
|
|
||||||
form.setFieldsValue(initialValues);
|
|
||||||
resetPreview();
|
|
||||||
setRecordDraft(undefined);
|
|
||||||
setInquiryDraft(undefined);
|
|
||||||
setActivePage(String(value));
|
|
||||||
})
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Space>
|
</Space>
|
||||||
<div className="presentation-editor__workspace">
|
<div className="presentation-editor__workspace">
|
||||||
<div className="presentation-editor__preview">
|
<PresentationEditorPreview
|
||||||
<h3 className="admin-section-title admin-flush">页面预览</h3>
|
previewBrand={controller.previewBrand}
|
||||||
{selectedPage === "detail" && draftWorkspace?.offerings.length ? (
|
draftWorkspace={controller.draftWorkspace}
|
||||||
<Select
|
selectedPage={controller.selectedPage}
|
||||||
aria-label="选择详情页业务内容"
|
selectedDetailOfferingId={controller.selectedDetailOfferingId}
|
||||||
className="admin-block admin-offset-bottom-sm"
|
activeTarget={controller.activeTarget}
|
||||||
value={selectedDetailOfferingId}
|
selection={controller.selection}
|
||||||
options={draftWorkspace.offerings.map((item) => ({
|
visibleTargets={controller.visibleTargets}
|
||||||
value: item.id,
|
onSelectDetailOffering={controller.selectDetailOffering}
|
||||||
label: item.name,
|
onTargetSelected={controller.handleTargetSelected}
|
||||||
}))}
|
onSelectPreviewTarget={controller.selectPreviewTarget}
|
||||||
onChange={(value) => {
|
/>
|
||||||
setDetailOfferingId(value);
|
<PresentationEditorInspector controller={controller} />
|
||||||
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
|
|
||||||
title="详情页由所选业务内容动态生成"
|
|
||||||
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
|
|
||||||
title="这是一个组合区域"
|
|
||||||
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"
|
|
||||||
}
|
|
||||||
title={
|
|
||||||
(
|
|
||||||
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
|
|
||||||
title="此区域尚未配置内容"
|
|
||||||
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>
|
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : 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>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
} from "../../lib/presentation/presentation-bindings.js";
|
} from "../../lib/presentation/presentation-bindings.js";
|
||||||
import { fieldTargetTitle } from "./presentation-editor-helpers.js";
|
import { fieldTargetTitle } from "./presentation-editor-helpers.js";
|
||||||
import type { PreviewTarget } from "./preview-selection.js";
|
import type { PreviewTarget } from "./preview-selection.js";
|
||||||
|
import { getFullFormValues } from "../../lib/form-values.js";
|
||||||
|
|
||||||
interface PresentationFormPanelProps {
|
interface PresentationFormPanelProps {
|
||||||
form: FormInstance<PresentationValues>;
|
form: FormInstance<PresentationValues>;
|
||||||
@@ -44,7 +45,7 @@ export function PresentationFormPanel({
|
|||||||
layout="vertical"
|
layout="vertical"
|
||||||
initialValues={initialValues}
|
initialValues={initialValues}
|
||||||
onValuesChange={onValuesChange}
|
onValuesChange={onValuesChange}
|
||||||
onFinish={() => save.mutate(form.getFieldsValue(true) as PresentationValues)}
|
onFinish={() => save.mutate(getFullFormValues<PresentationValues>(form))}
|
||||||
className="presentation-editor__form"
|
className="presentation-editor__form"
|
||||||
>
|
>
|
||||||
<div className="presentation-editor__form-body">
|
<div className="presentation-editor__form-body">
|
||||||
|
|||||||
@@ -146,7 +146,7 @@ export function TemplatePreview({
|
|||||||
<>
|
<>
|
||||||
{!ready && !error ? (
|
{!ready && !error ? (
|
||||||
<div className="template-preview__loading">
|
<div className="template-preview__loading">
|
||||||
<Spin tip="正在加载页面预览" />
|
<Spin description="正在加载页面预览" />
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
{error ? (
|
{error ? (
|
||||||
|
|||||||
@@ -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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import type {
|
|||||||
TrustContent,
|
TrustContent,
|
||||||
} from "@personal-brand/api-client";
|
} from "@personal-brand/api-client";
|
||||||
import { createApiClient } from "../../lib/api.js";
|
import { createApiClient } from "../../lib/api.js";
|
||||||
|
import { getFullFormValues } from "../../lib/form-values.js";
|
||||||
import {
|
import {
|
||||||
applyBrandPreviewValues,
|
applyBrandPreviewValues,
|
||||||
applyPresentationValues,
|
applyPresentationValues,
|
||||||
@@ -89,7 +90,6 @@ export function useBrandPresentationForm({
|
|||||||
return values;
|
return values;
|
||||||
}, [brand, config, sections]);
|
}, [brand, config, sections]);
|
||||||
|
|
||||||
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
|
|
||||||
return { form, initialValues };
|
return { form, initialValues };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -162,7 +162,7 @@ export function useBrandPreviewDraft({
|
|||||||
const handleValuesChange = (changed: PresentationValues, allValues: PresentationValues) => {
|
const handleValuesChange = (changed: PresentationValues, allValues: PresentationValues) => {
|
||||||
onDirty();
|
onDirty();
|
||||||
const synchronized: PresentationValues = {
|
const synchronized: PresentationValues = {
|
||||||
...(form.getFieldsValue(true) as PresentationValues),
|
...getFullFormValues<PresentationValues>(form),
|
||||||
...allValues,
|
...allValues,
|
||||||
};
|
};
|
||||||
for (const section of sections) {
|
for (const section of sections) {
|
||||||
|
|||||||
@@ -27,7 +27,21 @@ const element = (tag) =>
|
|||||||
|
|
||||||
export const View = element("div");
|
export const View = element("div");
|
||||||
export const Text = element("span");
|
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) =>
|
export const Input = React.forwardRef(({ onInput, ...props }, ref) =>
|
||||||
React.createElement("input", {
|
React.createElement("input", {
|
||||||
...props,
|
...props,
|
||||||
@@ -101,16 +115,18 @@ export const Label = element("label");
|
|||||||
export const Image = React.forwardRef(({ mode, src, style, ...props }, ref) => {
|
export const Image = React.forwardRef(({ mode, src, style, ...props }, ref) => {
|
||||||
const key = React.useContext(TemplateAssetContext);
|
const key = React.useContext(TemplateAssetContext);
|
||||||
const assets = React.useContext(TemplatePreviewAssetsContext);
|
const assets = React.useContext(TemplatePreviewAssetsContext);
|
||||||
|
const normalizedSrc = typeof src === "string" ? src.trim() : "";
|
||||||
|
if (!normalizedSrc) return null;
|
||||||
return React.createElement("img", {
|
return React.createElement("img", {
|
||||||
...props,
|
...props,
|
||||||
ref,
|
ref,
|
||||||
src:
|
src:
|
||||||
assets && typeof src === "string" && src.startsWith("/assets/")
|
assets && normalizedSrc.startsWith("/assets/")
|
||||||
? // 导入包资源以 /assets 开头;本地多模板预览的 renderer 可能额外携带包 key 前缀。
|
? // 导入包资源以 /assets 开头;本地多模板预览的 renderer 可能额外携带包 key 前缀。
|
||||||
(assets[src]?.dataUrl ??
|
(assets[normalizedSrc]?.dataUrl ??
|
||||||
assets[src.replace(`/assets/${key}/`, "/assets/")]?.dataUrl ??
|
assets[normalizedSrc.replace(`/assets/${key}/`, "/assets/")]?.dataUrl ??
|
||||||
src)
|
normalizedSrc)
|
||||||
: resolveImageSource(src, key),
|
: resolveImageSource(normalizedSrc, key),
|
||||||
style: { objectFit: mode === "aspectFit" ? "contain" : "cover", ...style },
|
style: { objectFit: mode === "aspectFit" ? "contain" : "cover", ...style },
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -9,6 +9,7 @@ export type MiniAppSettingsValues = {
|
|||||||
appId: string;
|
appId: string;
|
||||||
apiBaseUrl: string;
|
apiBaseUrl: string;
|
||||||
privateKey?: string;
|
privateKey?: string;
|
||||||
|
appSecret?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
interface MiniAppSettingsTabProps {
|
interface MiniAppSettingsTabProps {
|
||||||
@@ -27,14 +28,15 @@ export function MiniAppSettingsTab({ settings, saving, error, onSave }: MiniAppS
|
|||||||
appId: settings.appId,
|
appId: settings.appId,
|
||||||
apiBaseUrl: settings.apiBaseUrl,
|
apiBaseUrl: settings.apiBaseUrl,
|
||||||
privateKey: "",
|
privateKey: "",
|
||||||
|
appSecret: "",
|
||||||
});
|
});
|
||||||
}, [form, settings]);
|
}, [form, settings]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="admin-stack admin-stack-lg">
|
<div className="admin-stack admin-stack-lg">
|
||||||
<AdminSection
|
<AdminSection
|
||||||
title="小程序上传配置"
|
title="小程序配置"
|
||||||
description="AppID 用于服务端调用微信官方上传工具;上传私钥保存前会使用 AES-256-GCM 加密。"
|
description="AppID 同时用于代码上传和小程序登录;AppSecret 只用于 wx.login 换取 OpenID;上传私钥和 AppSecret 均使用 AES-256-GCM 加密保存。"
|
||||||
>
|
>
|
||||||
{settings?.buildError ? (
|
{settings?.buildError ? (
|
||||||
<Alert
|
<Alert
|
||||||
@@ -59,7 +61,32 @@ export function MiniAppSettingsTab({ settings, saving, error, onSave }: MiniAppS
|
|||||||
label="微信 AppID"
|
label="微信 AppID"
|
||||||
rules={[{ required: true, message: "请输入微信 AppID" }]}
|
rules={[{ required: true, message: "请输入微信 AppID" }]}
|
||||||
>
|
>
|
||||||
<Input maxLength={100} />
|
<Input maxLength={100} autoComplete="off" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="appSecret"
|
||||||
|
label="微信登录 AppSecret"
|
||||||
|
help={
|
||||||
|
settings?.hasStoredAppSecret
|
||||||
|
? "已加密保存。留空保持现有 AppSecret;修改 AppID 时必须同时填写新 AppID 对应的 AppSecret。"
|
||||||
|
: "从微信公众平台“开发管理 → 开发设置”复制。保存后立即生效,不需要重新上传小程序代码。"
|
||||||
|
}
|
||||||
|
rules={[
|
||||||
|
{
|
||||||
|
validator: (_rule, value: string) =>
|
||||||
|
!value || /^[A-Za-z0-9]{16,64}$/.test(value.trim())
|
||||||
|
? Promise.resolve()
|
||||||
|
: Promise.reject(new Error("AppSecret 应为 16-64 位字母或数字,请复制完整值")),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<Input.Password
|
||||||
|
maxLength={64}
|
||||||
|
autoComplete="new-password"
|
||||||
|
placeholder={
|
||||||
|
settings?.hasStoredAppSecret ? "留空保持现有 AppSecret" : "填写该小程序的 AppSecret"
|
||||||
|
}
|
||||||
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name="apiBaseUrl"
|
name="apiBaseUrl"
|
||||||
@@ -98,15 +125,29 @@ export function MiniAppSettingsTab({ settings, saving, error, onSave }: MiniAppS
|
|||||||
className="admin-code-input"
|
className="admin-code-input"
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Space>
|
{!settings?.loginConfigured ? (
|
||||||
|
<Alert
|
||||||
|
type="warning"
|
||||||
|
showIcon
|
||||||
|
className="admin-offset-bottom"
|
||||||
|
title="微信登录尚不可用"
|
||||||
|
description="该品牌需要同时保存微信 AppID 和 AppSecret,体验版才能通过 wx.login 换取 OpenID。"
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
<Space wrap>
|
||||||
<Button type="primary" loading={saving} htmlType="submit">
|
<Button type="primary" loading={saving} htmlType="submit">
|
||||||
保存上传配置
|
保存小程序配置
|
||||||
</Button>
|
</Button>
|
||||||
{settings?.hasStoredCredentials ? (
|
{settings?.hasStoredCredentials ? (
|
||||||
<StatusTag tone="success" label="已加密保存上传凭据" />
|
<StatusTag tone="success" label="已加密保存上传凭据" />
|
||||||
) : (
|
) : (
|
||||||
<StatusTag tone="warning" label="未配置上传私钥" />
|
<StatusTag tone="warning" label="未配置上传私钥" />
|
||||||
)}
|
)}
|
||||||
|
{settings?.hasStoredAppSecret ? (
|
||||||
|
<StatusTag tone="success" label="已加密保存登录凭据" />
|
||||||
|
) : (
|
||||||
|
<StatusTag tone="warning" label="未配置登录 AppSecret" />
|
||||||
|
)}
|
||||||
</Space>
|
</Space>
|
||||||
<MutationError error={error} />
|
<MutationError error={error} />
|
||||||
</Form>
|
</Form>
|
||||||
|
|||||||
@@ -56,14 +56,20 @@ export function usePublicationMutations({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
const saveMiniAppSettings = useMutation({
|
const saveMiniAppSettings = useMutation({
|
||||||
mutationFn: (values: { appId: string; apiBaseUrl: string; privateKey?: string }) =>
|
mutationFn: (values: {
|
||||||
|
appId: string;
|
||||||
|
apiBaseUrl: string;
|
||||||
|
privateKey?: string;
|
||||||
|
appSecret?: string;
|
||||||
|
}) =>
|
||||||
client.updateAdminMiniAppSettings({
|
client.updateAdminMiniAppSettings({
|
||||||
appId: values.appId,
|
appId: values.appId,
|
||||||
apiBaseUrl: values.apiBaseUrl,
|
apiBaseUrl: values.apiBaseUrl,
|
||||||
...(values.privateKey ? { privateKey: values.privateKey } : {}),
|
...(values.privateKey ? { privateKey: values.privateKey } : {}),
|
||||||
|
...(values.appSecret ? { appSecret: values.appSecret } : {}),
|
||||||
}),
|
}),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
message.success("小程序上传配置已保存");
|
message.success("小程序配置已保存");
|
||||||
void queryClient.invalidateQueries({ queryKey: ["publication-miniapp-settings"] });
|
void queryClient.invalidateQueries({ queryKey: ["publication-miniapp-settings"] });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Alert, Button, Form, Input, Modal, Segmented, Select } from "antd";
|
import { Alert, Button, Form, Input, Modal, Segmented, Select } from "antd";
|
||||||
|
import { useEffect, useRef } from "react";
|
||||||
import type {
|
import type {
|
||||||
Offering,
|
Offering,
|
||||||
RuntimeWorkspace,
|
RuntimeWorkspace,
|
||||||
@@ -8,9 +9,10 @@ import type {
|
|||||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
||||||
import { RecordContentFields } from "../../components/RecordContentEditor.js";
|
import { RecordContentFields } from "../../components/RecordContentEditor.js";
|
||||||
import { ComponentTemplatePreview } from "../brand/ComponentTemplatePreview.js";
|
import { ComponentTemplatePreview } from "../brand/ComponentTemplatePreview.js";
|
||||||
import type { PreviewTarget } from "../brand/preview-selection.js";
|
import type { PreviewSelection, PreviewTarget } from "../brand/preview-selection.js";
|
||||||
import type { FormInstance } from "antd";
|
import type { FormInstance } from "antd";
|
||||||
import "./ServicesPage.css";
|
import "./ServicesPage.css";
|
||||||
|
import { getFullFormValues } from "../../lib/form-values.js";
|
||||||
|
|
||||||
type OfferingEditorModalProps = {
|
type OfferingEditorModalProps = {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
@@ -20,13 +22,16 @@ type OfferingEditorModalProps = {
|
|||||||
previewWorkspace: RuntimeWorkspace | undefined;
|
previewWorkspace: RuntimeWorkspace | undefined;
|
||||||
previewTargets: Record<"offerings" | "detail", PreviewTarget[]>;
|
previewTargets: Record<"offerings" | "detail", PreviewTarget[]>;
|
||||||
activeTemplateFields: TemplateAdminField[];
|
activeTemplateFields: TemplateAdminField[];
|
||||||
|
activePreviewBindings: string[];
|
||||||
|
selectedTarget: PreviewTarget | undefined;
|
||||||
templateFieldSection: TemplateAdminSection;
|
templateFieldSection: TemplateAdminSection;
|
||||||
hasTemplateDetailCopy: boolean;
|
hasTemplateDetailCopy: boolean;
|
||||||
listTarget: PreviewTarget;
|
listTarget: PreviewTarget | undefined;
|
||||||
detailTarget: PreviewTarget | undefined;
|
detailTarget: PreviewTarget | undefined;
|
||||||
saving: boolean;
|
saving: boolean;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onPreviewPageChange: (page: "offerings" | "detail") => void;
|
onPreviewPageChange: (page: "offerings" | "detail") => void;
|
||||||
|
onPreviewTargetSelected: (selection?: PreviewSelection) => void;
|
||||||
onValuesChange: (values: Record<string, unknown>) => void;
|
onValuesChange: (values: Record<string, unknown>) => void;
|
||||||
onFinish: (values: Record<string, unknown>) => void;
|
onFinish: (values: Record<string, unknown>) => void;
|
||||||
onEditInBrand: () => void;
|
onEditInBrand: () => void;
|
||||||
@@ -40,6 +45,8 @@ export function OfferingEditorModal({
|
|||||||
previewWorkspace,
|
previewWorkspace,
|
||||||
previewTargets,
|
previewTargets,
|
||||||
activeTemplateFields,
|
activeTemplateFields,
|
||||||
|
activePreviewBindings,
|
||||||
|
selectedTarget,
|
||||||
templateFieldSection,
|
templateFieldSection,
|
||||||
hasTemplateDetailCopy,
|
hasTemplateDetailCopy,
|
||||||
listTarget,
|
listTarget,
|
||||||
@@ -47,10 +54,46 @@ export function OfferingEditorModal({
|
|||||||
saving,
|
saving,
|
||||||
onClose,
|
onClose,
|
||||||
onPreviewPageChange,
|
onPreviewPageChange,
|
||||||
|
onPreviewTargetSelected,
|
||||||
onValuesChange,
|
onValuesChange,
|
||||||
onFinish,
|
onFinish,
|
||||||
onEditInBrand,
|
onEditInBrand,
|
||||||
}: OfferingEditorModalProps) {
|
}: OfferingEditorModalProps) {
|
||||||
|
const formScroll = useRef<HTMLDivElement>(null);
|
||||||
|
const previewPageTarget = previewPage === "offerings" ? listTarget : detailTarget;
|
||||||
|
const previewSelectionTarget = selectedTarget ?? previewPageTarget;
|
||||||
|
const viewOptions = [
|
||||||
|
...(listTarget ? [{ value: "offerings" as const, label: "列表卡片" }] : []),
|
||||||
|
...(detailTarget ? [{ value: "detail" as const, label: "详情内容" }] : []),
|
||||||
|
];
|
||||||
|
const previewSelection: PreviewSelection | undefined = previewSelectionTarget
|
||||||
|
? previewSelectionTarget.source === "offering" && editingOffering
|
||||||
|
? { targetKey: previewSelectionTarget.key, recordId: editingOffering.id }
|
||||||
|
: { targetKey: previewSelectionTarget.key }
|
||||||
|
: undefined;
|
||||||
|
// 标准字段与模板字段使用同一份 manifest binding;点选后只显示当前区域真正声明的字段。
|
||||||
|
const activeBindingSet = new Set(activePreviewBindings);
|
||||||
|
const isBaseFieldVisible = (name: string) =>
|
||||||
|
!selectedTarget || activeBindingSet.has(`offering.${name}`);
|
||||||
|
const showDescriptionField = !hasTemplateDetailCopy && isBaseFieldVisible("description");
|
||||||
|
const hasVisibleBaseFields =
|
||||||
|
["kind", "name", "summary", "priceText", "coverUrl", "sortOrder", "isEnabled"].some((name) =>
|
||||||
|
isBaseFieldVisible(name),
|
||||||
|
) || showDescriptionField;
|
||||||
|
|
||||||
|
// 点选区块后,在右侧滚动到并高亮对应的输入项;品牌通用区块没有对应输入项时只保留提示。
|
||||||
|
useEffect(() => {
|
||||||
|
const host = formScroll.current;
|
||||||
|
if (!host || !selectedTarget || activePreviewBindings.length === 0) return;
|
||||||
|
const bindings = new Set(activePreviewBindings);
|
||||||
|
const nodes = Array.from(
|
||||||
|
host.querySelectorAll<HTMLElement>("[data-presentation-binding]"),
|
||||||
|
).filter((node) => bindings.has(node.dataset.presentationBinding ?? ""));
|
||||||
|
nodes.forEach((node) => node.classList.add("is-preview-active"));
|
||||||
|
nodes[0]?.scrollIntoView({ block: "center", behavior: "smooth" });
|
||||||
|
return () => nodes.forEach((node) => node.classList.remove("is-preview-active"));
|
||||||
|
}, [selectedTarget, activePreviewBindings]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
open={open}
|
open={open}
|
||||||
@@ -66,10 +109,7 @@ export function OfferingEditorModal({
|
|||||||
<Segmented
|
<Segmented
|
||||||
className="service-offering-editor__view"
|
className="service-offering-editor__view"
|
||||||
value={previewPage}
|
value={previewPage}
|
||||||
options={[
|
options={viewOptions}
|
||||||
{ value: "offerings", label: "列表卡片" },
|
|
||||||
{ value: "detail", label: "详情内容" },
|
|
||||||
]}
|
|
||||||
onChange={onPreviewPageChange}
|
onChange={onPreviewPageChange}
|
||||||
/>
|
/>
|
||||||
<Alert
|
<Alert
|
||||||
@@ -77,21 +117,20 @@ export function OfferingEditorModal({
|
|||||||
showIcon
|
showIcon
|
||||||
title={previewPage === "offerings" ? "正在核对列表展示" : "正在核对详情展示"}
|
title={previewPage === "offerings" ? "正在核对列表展示" : "正在核对详情展示"}
|
||||||
description={
|
description={
|
||||||
previewPage === "offerings"
|
selectedTarget
|
||||||
? "右侧「列表展示」字段修改后,会实时反映在当前卡片。"
|
? `右侧只显示「${selectedTarget.label}」对应的字段,修改会实时反映在左侧预览;点击预览空白处或「查看全部字段」可恢复。`
|
||||||
: "右侧「详情展示」字段修改后,会实时反映在当前详情内容。"
|
: previewPage === "offerings"
|
||||||
|
? "点击左侧区块后,右侧只显示该区块对应的字段;未点选时显示全部列表展示字段。"
|
||||||
|
: "点击左侧区块后,右侧只显示该区块对应的字段;未点选时显示全部详情展示字段。"
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<ComponentTemplatePreview
|
<ComponentTemplatePreview
|
||||||
workspace={previewWorkspace}
|
workspace={previewWorkspace}
|
||||||
page={previewPage}
|
page={previewPageTarget?.page ?? previewPage}
|
||||||
offeringId={editingOffering.id}
|
offeringId={editingOffering.id}
|
||||||
targets={previewTargets[previewPage]}
|
targets={previewTargets[previewPage]}
|
||||||
selection={{
|
{...(previewSelection ? { selection: previewSelection } : {})}
|
||||||
targetKey: previewPage === "offerings" ? listTarget.key : (detailTarget?.key ?? ""),
|
onTargetSelected={onPreviewTargetSelected}
|
||||||
recordId: editingOffering.id,
|
|
||||||
}}
|
|
||||||
onTargetSelected={() => {}}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -100,64 +139,130 @@ export function OfferingEditorModal({
|
|||||||
form={form}
|
form={form}
|
||||||
layout="vertical"
|
layout="vertical"
|
||||||
onValuesChange={(_, allValues) => onValuesChange(allValues)}
|
onValuesChange={(_, allValues) => onValuesChange(allValues)}
|
||||||
onFinish={onFinish}
|
// 动态隐藏的字段会被卸载,onFinish 默认只返回仍挂载的字段。
|
||||||
|
// 提交时读取完整表单存储,避免切换区块后隐藏字段的修改丢失。
|
||||||
|
onFinish={() => onFinish(getFullFormValues(form))}
|
||||||
>
|
>
|
||||||
<div className="service-offering-editor__form-scroll">
|
<div ref={formScroll} className="service-offering-editor__form-scroll">
|
||||||
<h4 className="admin-subhead">基础信息</h4>
|
{selectedTarget ? (
|
||||||
<Form.Item name="kind" label="类型" rules={[{ required: true }]}>
|
<div className="service-offering-editor__selection">
|
||||||
<Select
|
<div>
|
||||||
options={[
|
<strong>正在编辑「{selectedTarget.label}」</strong>
|
||||||
{ value: "service", label: "服务" },
|
<p className="admin-section-description">
|
||||||
{ value: "product", label: "定制产品" },
|
只显示这个区块对应的字段,其他字段已临时隐藏。
|
||||||
{ value: "package", label: "套餐" },
|
</p>
|
||||||
{ value: "subscription", label: "订阅" },
|
</div>
|
||||||
]}
|
<Button
|
||||||
/>
|
size="small"
|
||||||
</Form.Item>
|
htmlType="button"
|
||||||
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
|
onClick={() => onPreviewTargetSelected(undefined)}
|
||||||
<Input />
|
>
|
||||||
</Form.Item>
|
查看全部字段
|
||||||
<Form.Item name="summary" label="一句话说明">
|
</Button>
|
||||||
<Input />
|
</div>
|
||||||
</Form.Item>
|
) : null}
|
||||||
{!hasTemplateDetailCopy ? (
|
{hasVisibleBaseFields ? <h4 className="admin-subhead">基础信息</h4> : null}
|
||||||
<Form.Item name="description" label="详细介绍">
|
{isBaseFieldVisible("kind") ? (
|
||||||
|
<Form.Item name="kind" label="类型" rules={[{ required: true }]}>
|
||||||
|
<Select
|
||||||
|
options={[
|
||||||
|
{ value: "service", label: "服务" },
|
||||||
|
{ value: "product", label: "定制产品" },
|
||||||
|
{ value: "package", label: "套餐" },
|
||||||
|
{ value: "subscription", label: "订阅" },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
) : null}
|
||||||
|
{isBaseFieldVisible("name") ? (
|
||||||
|
<Form.Item
|
||||||
|
name="name"
|
||||||
|
label="名称"
|
||||||
|
data-presentation-binding="offering.name"
|
||||||
|
rules={[{ required: true }]}
|
||||||
|
>
|
||||||
|
<Input />
|
||||||
|
</Form.Item>
|
||||||
|
) : null}
|
||||||
|
{isBaseFieldVisible("summary") ? (
|
||||||
|
<Form.Item
|
||||||
|
name="summary"
|
||||||
|
label="一句话说明"
|
||||||
|
data-presentation-binding="offering.summary"
|
||||||
|
>
|
||||||
|
<Input />
|
||||||
|
</Form.Item>
|
||||||
|
) : null}
|
||||||
|
{showDescriptionField ? (
|
||||||
|
<Form.Item
|
||||||
|
name="description"
|
||||||
|
label="详细介绍"
|
||||||
|
data-presentation-binding="offering.description"
|
||||||
|
>
|
||||||
<Input.TextArea rows={5} />
|
<Input.TextArea rows={5} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
) : null}
|
) : null}
|
||||||
<Form.Item name="priceText" label="价格展示">
|
{isBaseFieldVisible("priceText") ? (
|
||||||
<Input placeholder="例如:按现场评估报价 / ¥ 2,800 起" />
|
<Form.Item
|
||||||
</Form.Item>
|
name="priceText"
|
||||||
<Form.Item
|
label="价格展示"
|
||||||
name="coverUrl"
|
data-presentation-binding="offering.priceText"
|
||||||
label="封面图片地址"
|
>
|
||||||
help="点击上传,或粘贴服务/产品封面图片地址。"
|
<Input placeholder="例如:按现场评估报价 / ¥ 2,800 起" />
|
||||||
>
|
</Form.Item>
|
||||||
<ImageUrlField placeholder="粘贴服务或产品封面图片地址" scope="offering" />
|
) : null}
|
||||||
</Form.Item>
|
{isBaseFieldVisible("coverUrl") ? (
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name="sortOrder"
|
name="coverUrl"
|
||||||
label="展示顺序"
|
label="封面图片地址"
|
||||||
help="数字越小越靠前,不确定时填写 0。"
|
help="点击上传,或粘贴服务/产品封面图片地址。"
|
||||||
rules={[{ type: "number", min: 0, max: 9999 }]}
|
data-presentation-binding="offering.coverUrl"
|
||||||
>
|
>
|
||||||
<Input type="number" min={0} max={9999} />
|
<ImageUrlField placeholder="粘贴服务或产品封面图片地址" scope="offering" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="isEnabled" label="公开状态">
|
) : null}
|
||||||
<Select
|
{isBaseFieldVisible("sortOrder") ? (
|
||||||
options={[
|
<Form.Item
|
||||||
{ value: true, label: "已启用" },
|
name="sortOrder"
|
||||||
{ value: false, label: "已停用" },
|
label="展示顺序"
|
||||||
]}
|
help="数字越小越靠前,不确定时填写 0。"
|
||||||
|
rules={[{ type: "number", min: 0, max: 9999 }]}
|
||||||
|
>
|
||||||
|
<Input type="number" min={0} max={9999} />
|
||||||
|
</Form.Item>
|
||||||
|
) : null}
|
||||||
|
{isBaseFieldVisible("isEnabled") ? (
|
||||||
|
<Form.Item name="isEnabled" label="公开状态">
|
||||||
|
<Select
|
||||||
|
options={[
|
||||||
|
{ value: true, label: "已启用" },
|
||||||
|
{ value: false, label: "已停用" },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
) : null}
|
||||||
|
{selectedTarget && selectedTarget.source !== "offering" ? (
|
||||||
|
<Alert
|
||||||
|
type="warning"
|
||||||
|
showIcon
|
||||||
|
className="admin-offset-bottom"
|
||||||
|
title={`「${selectedTarget.label}」属于页面通用内容`}
|
||||||
|
description="这项内容不在业务提供项里维护。可点击下方「在小程序页面编辑」到对应区块修改。"
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
) : null}
|
||||||
{activeTemplateFields.length ? (
|
{activeTemplateFields.length ? (
|
||||||
<div>
|
<div>
|
||||||
<h4 className="admin-subhead">
|
<h4 className="admin-subhead">
|
||||||
{previewPage === "offerings" ? "列表展示字段" : "详情展示字段"}
|
{selectedTarget
|
||||||
|
? `${selectedTarget.label}对应字段`
|
||||||
|
: previewPage === "offerings"
|
||||||
|
? "列表展示字段"
|
||||||
|
: "详情展示字段"}
|
||||||
</h4>
|
</h4>
|
||||||
<p className="admin-section-description admin-offset-bottom">
|
<p className="admin-section-description admin-offset-bottom">
|
||||||
这里只编辑左侧预览对应的字段;它们与小程序页面编辑的是同一份业务数据。
|
{selectedTarget
|
||||||
|
? "右侧已定位到该区块使用的字段,修改会实时反映在左侧预览。"
|
||||||
|
: "这里只编辑左侧预览对应的字段;它们与小程序页面编辑的是同一份业务数据。"}
|
||||||
</p>
|
</p>
|
||||||
<RecordContentFields
|
<RecordContentFields
|
||||||
section={{
|
section={{
|
||||||
@@ -167,6 +272,14 @@ export function OfferingEditorModal({
|
|||||||
sectionKey="offering"
|
sectionKey="offering"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
) : selectedTarget?.source === "offering" ? (
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
className="admin-offset-bottom"
|
||||||
|
title={`「${selectedTarget.label}」只包含基础信息`}
|
||||||
|
description="请修改上方基础信息,左侧预览会实时同步。"
|
||||||
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
{editingOffering ? (
|
{editingOffering ? (
|
||||||
<Button htmlType="button" onClick={onEditInBrand}>
|
<Button htmlType="button" onClick={onEditInBrand}>
|
||||||
|
|||||||
@@ -55,10 +55,39 @@
|
|||||||
margin-top: 0;
|
margin-top: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.service-offering-editor__selection {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border: 1px solid rgba(22, 119, 255, 0.28);
|
||||||
|
border-radius: 10px;
|
||||||
|
background-color: rgba(22, 119, 255, 0.06);
|
||||||
|
}
|
||||||
|
|
||||||
|
.service-offering-editor__selection p {
|
||||||
|
margin: 4px 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
.service-offering-editor__form-scroll .ant-form-item {
|
.service-offering-editor__form-scroll .ant-form-item {
|
||||||
margin-bottom: 20px;
|
margin-bottom: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.service-offering-editor__form-scroll [data-presentation-binding] {
|
||||||
|
scroll-margin-block: 24px;
|
||||||
|
border-radius: 8px;
|
||||||
|
transition:
|
||||||
|
background-color 180ms ease,
|
||||||
|
box-shadow 180ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.service-offering-editor__form-scroll [data-presentation-binding].is-preview-active {
|
||||||
|
background-color: rgba(22, 119, 255, 0.07);
|
||||||
|
box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.24);
|
||||||
|
}
|
||||||
|
|
||||||
.service-offering-editor__form-scroll .ant-typography h5.ant-typography {
|
.service-offering-editor__form-scroll .ant-typography h5.ant-typography {
|
||||||
margin: 28px 0 4px;
|
margin: 28px 0 4px;
|
||||||
padding-bottom: 8px;
|
padding-bottom: 8px;
|
||||||
|
|||||||
@@ -7,9 +7,15 @@ import { QueryState } from "../../components/QueryState.js";
|
|||||||
import { OfferingEditorModal } from "./OfferingEditorModal.js";
|
import { OfferingEditorModal } from "./OfferingEditorModal.js";
|
||||||
import { OfferingsTable } from "./OfferingsTable.js";
|
import { OfferingsTable } from "./OfferingsTable.js";
|
||||||
import { detailPageLabel, hasTemplateDetailCopy, offeringPageLabel } from "./offering-model.js";
|
import { detailPageLabel, hasTemplateDetailCopy, offeringPageLabel } from "./offering-model.js";
|
||||||
import { buildOfferingPreviewWorkspace, previewTargetsByPage } from "./offering-preview.js";
|
import {
|
||||||
|
buildOfferingPreviewWorkspace,
|
||||||
|
pageTemplateFields as collectPageTemplateFields,
|
||||||
|
previewFieldsByTarget,
|
||||||
|
previewTargetsByPage,
|
||||||
|
} from "./offering-preview.js";
|
||||||
import { useOfferingEditor } from "./use-offering-editor.js";
|
import { useOfferingEditor } from "./use-offering-editor.js";
|
||||||
import { useOfferingMutations, useOfferingQueries } from "./use-offering-data.js";
|
import { useOfferingMutations, useOfferingQueries } from "./use-offering-data.js";
|
||||||
|
import type { PreviewSelection } from "../brand/preview-selection.js";
|
||||||
|
|
||||||
type PreviewPage = "offerings" | "detail";
|
type PreviewPage = "offerings" | "detail";
|
||||||
|
|
||||||
@@ -28,34 +34,50 @@ export function ServicesPage() {
|
|||||||
|
|
||||||
const sections = workspace.data?.templateContent?.admin.sections ?? [];
|
const sections = workspace.data?.templateContent?.admin.sections ?? [];
|
||||||
const previewTargets = useMemo(() => previewTargetsByPage(sections), [sections]);
|
const previewTargets = useMemo(() => previewTargetsByPage(sections), [sections]);
|
||||||
const listTarget = previewTargets.offerings.find((target) =>
|
const fieldsByTarget = useMemo(() => previewFieldsByTarget(sections), [sections]);
|
||||||
templateFields.some((field) => field.previewTarget === target.key),
|
// 只使用 manifest 中真实存在的业务卡片区域;模板没有对应区域时不显示列表预览。
|
||||||
) ?? {
|
const listTarget = useMemo(
|
||||||
key: "offering.list.item",
|
() => previewTargets.offerings.find((target) => target.source === "offering"),
|
||||||
label: "业务卡片",
|
[previewTargets],
|
||||||
page: "offerings",
|
|
||||||
source: "offering",
|
|
||||||
};
|
|
||||||
const detailTarget = previewTargets.detail.find((target) => target.source === "offering");
|
|
||||||
const listFields = useMemo(
|
|
||||||
() => templateFields.filter((field) => field.previewTarget === listTarget.key),
|
|
||||||
[templateFields, listTarget.key],
|
|
||||||
);
|
);
|
||||||
const detailFields = useMemo(
|
const detailTarget = useMemo(
|
||||||
() => templateFields.filter((field) => field.previewTarget === detailTarget?.key),
|
() => previewTargets.detail.find((target) => target.source === "offering"),
|
||||||
[templateFields, detailTarget?.key],
|
[previewTargets],
|
||||||
);
|
);
|
||||||
const otherFields = useMemo(
|
// 页面级字段必须按该页所有真实预览区域收集,不能只取列表/详情首个区域,
|
||||||
|
// 否则模板把详情拆成多个区域后,未点选的“全部字段”会漏掉后续区域。
|
||||||
|
const pageTemplateFields = useMemo<TemplateAdminField[]>(
|
||||||
() =>
|
() =>
|
||||||
templateFields.filter(
|
collectPageTemplateFields({
|
||||||
(field) => !listFields.includes(field) && !detailFields.includes(field),
|
previewPage: editor.previewPage,
|
||||||
),
|
previewTargets,
|
||||||
[templateFields, listFields, detailFields],
|
templateFields,
|
||||||
|
listPage: listTarget?.page,
|
||||||
|
}),
|
||||||
|
[editor.previewPage, listTarget?.page, previewTargets, templateFields],
|
||||||
|
);
|
||||||
|
// 点选预览区块后,右侧只保留该区块对应的字段,与小程序页面点选编辑保持一致。
|
||||||
|
const selectedTarget = useMemo(() => {
|
||||||
|
if (!editor.previewTargetKey) return undefined;
|
||||||
|
return previewTargets[editor.previewPage].find(
|
||||||
|
(target) => target.key === editor.previewTargetKey,
|
||||||
|
);
|
||||||
|
}, [editor.previewPage, editor.previewTargetKey, previewTargets]);
|
||||||
|
const activeTemplateFields = useMemo<TemplateAdminField[]>(
|
||||||
|
() =>
|
||||||
|
selectedTarget
|
||||||
|
? pageTemplateFields.filter((field) => field.previewTarget === selectedTarget.key)
|
||||||
|
: pageTemplateFields,
|
||||||
|
[pageTemplateFields, selectedTarget],
|
||||||
|
);
|
||||||
|
// 区块字段的 binding 用于在右侧表单中滚动并高亮同一份数据。
|
||||||
|
const activePreviewBindings = useMemo(
|
||||||
|
() =>
|
||||||
|
selectedTarget
|
||||||
|
? (fieldsByTarget[selectedTarget.key] ?? []).map((field) => field.binding)
|
||||||
|
: [],
|
||||||
|
[fieldsByTarget, selectedTarget],
|
||||||
);
|
);
|
||||||
const activeTemplateFields: TemplateAdminField[] =
|
|
||||||
editor.previewPage === "offerings"
|
|
||||||
? [...listFields, ...otherFields.filter((field) => field.page === "offerings")]
|
|
||||||
: [...detailFields, ...otherFields.filter((field) => field.page === "detail")];
|
|
||||||
const previewWorkspaceDraft = useMemo(() => {
|
const previewWorkspaceDraft = useMemo(() => {
|
||||||
if (!previewWorkspace.data || !editor.editingOffering) return undefined;
|
if (!previewWorkspace.data || !editor.editingOffering) return undefined;
|
||||||
return buildOfferingPreviewWorkspace({
|
return buildOfferingPreviewWorkspace({
|
||||||
@@ -74,12 +96,13 @@ export function ServicesPage() {
|
|||||||
|
|
||||||
const navigateToBrand = () => {
|
const navigateToBrand = () => {
|
||||||
if (!editor.editingOffering) return;
|
if (!editor.editingOffering) return;
|
||||||
|
const target =
|
||||||
|
selectedTarget ?? (editor.previewPage === "offerings" ? listTarget : detailTarget);
|
||||||
|
if (!target) return;
|
||||||
void navigate("/admin/brand", {
|
void navigate("/admin/brand", {
|
||||||
state: {
|
state: {
|
||||||
targetKey:
|
page: target.page,
|
||||||
editor.previewPage === "offerings"
|
targetKey: target.key,
|
||||||
? listTarget.key
|
|
||||||
: (detailTarget?.key ?? listTarget.key),
|
|
||||||
recordId: editor.editingOffering.id,
|
recordId: editor.editingOffering.id,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -120,13 +143,18 @@ export function ServicesPage() {
|
|||||||
previewWorkspace={previewWorkspaceDraft}
|
previewWorkspace={previewWorkspaceDraft}
|
||||||
previewTargets={previewTargets}
|
previewTargets={previewTargets}
|
||||||
activeTemplateFields={activeTemplateFields}
|
activeTemplateFields={activeTemplateFields}
|
||||||
|
activePreviewBindings={activePreviewBindings}
|
||||||
|
selectedTarget={selectedTarget}
|
||||||
templateFieldSection={editor.templateFieldSection}
|
templateFieldSection={editor.templateFieldSection}
|
||||||
hasTemplateDetailCopy={hasTemplateDetailCopy(templateFields)}
|
hasTemplateDetailCopy={hasTemplateDetailCopy(templateFields)}
|
||||||
listTarget={listTarget}
|
listTarget={listTarget}
|
||||||
detailTarget={detailTarget}
|
detailTarget={detailTarget}
|
||||||
saving={mutations.saveOffering.isPending}
|
saving={mutations.saveOffering.isPending}
|
||||||
onClose={editor.closeOffering}
|
onClose={editor.closeOffering}
|
||||||
onPreviewPageChange={(page: PreviewPage) => editor.setPreviewPage(page)}
|
onPreviewPageChange={(page: PreviewPage) => editor.changePreviewPage(page)}
|
||||||
|
onPreviewTargetSelected={(selection?: PreviewSelection) =>
|
||||||
|
editor.selectPreviewTarget(selection?.targetKey)
|
||||||
|
}
|
||||||
onValuesChange={(values) => editor.handleValuesChange(null, values)}
|
onValuesChange={(values) => editor.handleValuesChange(null, values)}
|
||||||
onFinish={(values) => mutations.saveOffering.mutate(values)}
|
onFinish={(values) => mutations.saveOffering.mutate(values)}
|
||||||
onEditInBrand={navigateToBrand}
|
onEditInBrand={navigateToBrand}
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import type { RuntimeOffering } from "@personal-brand/api-client";
|
||||||
|
|
||||||
|
type RuntimePresentation = RuntimeOffering["presentation"];
|
||||||
|
|
||||||
|
function isFilledString(value: unknown): value is string {
|
||||||
|
return typeof value === "string" && value.trim() !== "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把表单草稿投影到单条 Runtime Offering 上。
|
||||||
|
* 该函数是 buildOfferingPreviewWorkspace 的核心合并规则:
|
||||||
|
* - name/coverUrl 等展示字段为空时保留原值,避免输入中间态清空预览;
|
||||||
|
* - summary/priceText 允许清空为空字符串;
|
||||||
|
* - presentation 由原值、模板 config、config.presentation 与事实字段逐层合并;
|
||||||
|
* - detailHero 优先于 coverUrl,两者都为空时保留原 heroImage。
|
||||||
|
*/
|
||||||
|
export function projectOfferingPreviewFields(options: {
|
||||||
|
item: Pick<RuntimeOffering, "name" | "summary" | "priceText" | "coverUrl" | "presentation">;
|
||||||
|
config: Record<string, unknown>;
|
||||||
|
formValues: Record<string, unknown>;
|
||||||
|
}): {
|
||||||
|
name: string;
|
||||||
|
summary: string;
|
||||||
|
priceText: string | null;
|
||||||
|
coverUrl: string | null;
|
||||||
|
presentation: RuntimePresentation;
|
||||||
|
} {
|
||||||
|
const { item, config, formValues } = options;
|
||||||
|
const nestedPresentation =
|
||||||
|
config.presentation && typeof config.presentation === "object"
|
||||||
|
? (config.presentation as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
const configDetails =
|
||||||
|
config.details && typeof config.details === "object"
|
||||||
|
? (config.details as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
|
||||||
|
const presentation: RuntimePresentation = {
|
||||||
|
...item.presentation,
|
||||||
|
...config,
|
||||||
|
...nestedPresentation,
|
||||||
|
...(typeof config.area === "string" ? { area: config.area } : {}),
|
||||||
|
...(typeof config.series === "string" ? { series: config.series } : {}),
|
||||||
|
...(typeof config.spaceType === "string" ? { spaceType: config.spaceType } : {}),
|
||||||
|
heroImage: isFilledString(config.detailHero)
|
||||||
|
? config.detailHero
|
||||||
|
: isFilledString(formValues.coverUrl)
|
||||||
|
? formValues.coverUrl
|
||||||
|
: (item.coverUrl ?? null),
|
||||||
|
details: {
|
||||||
|
...item.presentation.details,
|
||||||
|
...configDetails,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: isFilledString(formValues.name) ? formValues.name : item.name,
|
||||||
|
summary: typeof formValues.summary === "string" ? formValues.summary : item.summary,
|
||||||
|
priceText: typeof formValues.priceText === "string" ? formValues.priceText : item.priceText,
|
||||||
|
coverUrl: isFilledString(formValues.coverUrl) ? formValues.coverUrl : item.coverUrl,
|
||||||
|
presentation,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import type { AdminTemplateContent, TemplateAdminField } from "@personal-brand/api-client";
|
||||||
|
import type { PreviewTarget } from "../brand/preview-selection.js";
|
||||||
|
|
||||||
|
export function previewTargetsByPage(
|
||||||
|
sections: AdminTemplateContent["admin"]["sections"],
|
||||||
|
): Record<"offerings" | "detail", PreviewTarget[]> {
|
||||||
|
const targets = sections.flatMap((section) =>
|
||||||
|
(section.previewTargets ?? []).map((target) => ({
|
||||||
|
...target,
|
||||||
|
page: section.page,
|
||||||
|
source: section.fields.some(
|
||||||
|
(field) => field.binding.startsWith("offering.") && field.previewTarget === target.key,
|
||||||
|
)
|
||||||
|
? ("offering" as const)
|
||||||
|
: section.target,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
const pages = [...new Set(sections.map((section) => section.page))];
|
||||||
|
const offeringPages = pages.filter(
|
||||||
|
(page) =>
|
||||||
|
page !== "detail" &&
|
||||||
|
targets.some((target) => target.page === page && target.source === "offering"),
|
||||||
|
);
|
||||||
|
// 业务卡片不一定在“服务页”:独立工坊把案例卡片放在首页。优先使用专门的
|
||||||
|
// offerings 页,没有时退回第一个包含业务记录的页面。
|
||||||
|
const listPage = offeringPages.find((page) => page === "offerings") ?? offeringPages[0];
|
||||||
|
return {
|
||||||
|
offerings: listPage ? targets.filter((target) => target.page === listPage) : [],
|
||||||
|
detail: targets.filter((target) => target.page === "detail"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pageTemplateFields(options: {
|
||||||
|
previewPage: "offerings" | "detail";
|
||||||
|
previewTargets: Record<"offerings" | "detail", PreviewTarget[]>;
|
||||||
|
templateFields: TemplateAdminField[];
|
||||||
|
listPage?: string | undefined;
|
||||||
|
}): TemplateAdminField[] {
|
||||||
|
const { previewPage, previewTargets, templateFields, listPage } = options;
|
||||||
|
const targets = previewPage === "offerings" ? previewTargets.offerings : previewTargets.detail;
|
||||||
|
const targetKeys = new Set(targets.map((target) => target.key));
|
||||||
|
return templateFields.filter(
|
||||||
|
(field) =>
|
||||||
|
(field.previewTarget && targetKeys.has(field.previewTarget)) ||
|
||||||
|
(!field.previewTarget && field.page === (previewPage === "offerings" ? listPage : "detail")),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,33 +1,23 @@
|
|||||||
|
export { pageTemplateFields, previewTargetsByPage } from "./offering-preview-targets.js";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
AdminTemplateContent,
|
AdminTemplateContent,
|
||||||
Offering,
|
Offering,
|
||||||
RuntimeWorkspace,
|
RuntimeWorkspace,
|
||||||
TemplateAdminField,
|
TemplateAdminField,
|
||||||
} from "@personal-brand/api-client";
|
} from "@personal-brand/api-client";
|
||||||
import type { PreviewTarget } from "../brand/preview-selection.js";
|
|
||||||
import { applyPresentationValues } from "../../lib/presentation/presentation-bindings.js";
|
import { applyPresentationValues } from "../../lib/presentation/presentation-bindings.js";
|
||||||
|
import { projectOfferingPreviewFields } from "./offering-preview-projection.js";
|
||||||
|
|
||||||
export function previewTargetsByPage(
|
export function previewFieldsByTarget(
|
||||||
sections: AdminTemplateContent["admin"]["sections"],
|
sections: AdminTemplateContent["admin"]["sections"],
|
||||||
): Record<"offerings" | "detail", PreviewTarget[]> {
|
): Record<string, TemplateAdminField[]> {
|
||||||
const result: Record<"offerings" | "detail", PreviewTarget[]> = {
|
const result: Record<string, TemplateAdminField[]> = {};
|
||||||
offerings: [],
|
for (const section of sections) {
|
||||||
detail: [],
|
for (const field of section.fields) {
|
||||||
};
|
if (!field.previewTarget) continue;
|
||||||
for (const page of ["offerings", "detail"] as const) {
|
(result[field.previewTarget] ??= []).push(field);
|
||||||
result[page] = sections
|
}
|
||||||
.filter((section) => section.page === page)
|
|
||||||
.flatMap((section) =>
|
|
||||||
(section.previewTargets ?? []).map((target) => ({
|
|
||||||
...target,
|
|
||||||
page: section.page,
|
|
||||||
source: section.fields.some(
|
|
||||||
(field) => field.binding.startsWith("offering.") && field.previewTarget === target.key,
|
|
||||||
)
|
|
||||||
? "offering"
|
|
||||||
: section.target,
|
|
||||||
})),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -44,60 +34,11 @@ export function buildOfferingPreviewWorkspace(options: {
|
|||||||
[{ key: "offering", fields: templateFields }],
|
[{ key: "offering", fields: templateFields }],
|
||||||
formValues,
|
formValues,
|
||||||
);
|
);
|
||||||
const offeringValues = {
|
|
||||||
name: formValues.name,
|
|
||||||
summary: formValues.summary,
|
|
||||||
description: formValues.description,
|
|
||||||
priceText: formValues.priceText,
|
|
||||||
coverUrl: formValues.coverUrl,
|
|
||||||
};
|
|
||||||
return {
|
return {
|
||||||
...previewWorkspace,
|
...previewWorkspace,
|
||||||
offerings: previewWorkspace.offerings.map((item) =>
|
offerings: previewWorkspace.offerings.map((item) =>
|
||||||
item.id === editingOffering.id
|
item.id === editingOffering.id
|
||||||
? {
|
? { ...item, ...projectOfferingPreviewFields({ item, config, formValues }) }
|
||||||
...item,
|
|
||||||
name:
|
|
||||||
typeof offeringValues.name === "string" && offeringValues.name.trim()
|
|
||||||
? offeringValues.name
|
|
||||||
: item.name,
|
|
||||||
summary:
|
|
||||||
typeof offeringValues.summary === "string" ? offeringValues.summary : item.summary,
|
|
||||||
priceText:
|
|
||||||
typeof offeringValues.priceText === "string"
|
|
||||||
? offeringValues.priceText
|
|
||||||
: item.priceText,
|
|
||||||
coverUrl:
|
|
||||||
typeof offeringValues.coverUrl === "string" && offeringValues.coverUrl.trim()
|
|
||||||
? offeringValues.coverUrl
|
|
||||||
: item.coverUrl,
|
|
||||||
config,
|
|
||||||
presentation: {
|
|
||||||
...item.presentation,
|
|
||||||
...config,
|
|
||||||
...(config.presentation && typeof config.presentation === "object"
|
|
||||||
? (config.presentation as Record<string, unknown>)
|
|
||||||
: {}),
|
|
||||||
...(typeof config.area === "string" ? { area: config.area } : {}),
|
|
||||||
...(typeof config.series === "string" ? { series: config.series } : {}),
|
|
||||||
...(typeof config.spaceType === "string" ? { spaceType: config.spaceType } : {}),
|
|
||||||
heroImage:
|
|
||||||
typeof config.detailHero === "string"
|
|
||||||
? config.detailHero
|
|
||||||
: typeof offeringValues.coverUrl === "string" && offeringValues.coverUrl.trim()
|
|
||||||
? offeringValues.coverUrl
|
|
||||||
: (item.coverUrl ?? null),
|
|
||||||
details: {
|
|
||||||
...item.presentation.details,
|
|
||||||
...(config.details && typeof config.details === "object"
|
|
||||||
? {
|
|
||||||
...item.presentation.details,
|
|
||||||
...(config.details as Record<string, unknown>),
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
: item,
|
: item,
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import type {
|
|||||||
TemplateAdminSection,
|
TemplateAdminSection,
|
||||||
} from "@personal-brand/api-client";
|
} from "@personal-brand/api-client";
|
||||||
import { offeringDefaultFormValues, offeringEditFormValues } from "./offering-form.js";
|
import { offeringDefaultFormValues, offeringEditFormValues } from "./offering-form.js";
|
||||||
|
import { getFullFormValues } from "../../lib/form-values.js";
|
||||||
|
|
||||||
export type OfferingPreviewPage = "offerings" | "detail";
|
export type OfferingPreviewPage = "offerings" | "detail";
|
||||||
|
|
||||||
@@ -15,6 +16,7 @@ export function useOfferingEditor(templateFields: TemplateAdminField[]) {
|
|||||||
const [editingOffering, setEditingOffering] = useState<Offering | null>(null);
|
const [editingOffering, setEditingOffering] = useState<Offering | null>(null);
|
||||||
const [offeringDraftVersion, setOfferingDraftVersion] = useState(0);
|
const [offeringDraftVersion, setOfferingDraftVersion] = useState(0);
|
||||||
const [previewPage, setPreviewPage] = useState<OfferingPreviewPage>("detail");
|
const [previewPage, setPreviewPage] = useState<OfferingPreviewPage>("detail");
|
||||||
|
const [previewTargetKey, setPreviewTargetKey] = useState<string>();
|
||||||
const [formValues, setFormValues] = useState<Record<string, unknown>>({});
|
const [formValues, setFormValues] = useState<Record<string, unknown>>({});
|
||||||
|
|
||||||
const templateFieldSection = useMemo<TemplateAdminSection>(
|
const templateFieldSection = useMemo<TemplateAdminSection>(
|
||||||
@@ -32,21 +34,32 @@ export function useOfferingEditor(templateFields: TemplateAdminField[]) {
|
|||||||
const beginOffering = (item?: Offering) => {
|
const beginOffering = (item?: Offering) => {
|
||||||
setEditingOffering(item ?? null);
|
setEditingOffering(item ?? null);
|
||||||
setPreviewPage("detail");
|
setPreviewPage("detail");
|
||||||
|
setPreviewTargetKey(undefined);
|
||||||
setOfferingOpen(true);
|
setOfferingOpen(true);
|
||||||
offeringForm.setFieldsValue(
|
offeringForm.setFieldsValue(
|
||||||
item
|
item
|
||||||
? offeringEditFormValues(item, templateFields)
|
? offeringEditFormValues(item, templateFields)
|
||||||
: offeringDefaultFormValues(templateFields),
|
: offeringDefaultFormValues(templateFields),
|
||||||
);
|
);
|
||||||
setFormValues(offeringForm.getFieldsValue(true) as Record<string, unknown>);
|
setFormValues(getFullFormValues(offeringForm));
|
||||||
};
|
};
|
||||||
|
|
||||||
const closeOffering = () => {
|
const closeOffering = () => {
|
||||||
setOfferingOpen(false);
|
setOfferingOpen(false);
|
||||||
setEditingOffering(null);
|
setEditingOffering(null);
|
||||||
|
setPreviewTargetKey(undefined);
|
||||||
offeringForm.resetFields();
|
offeringForm.resetFields();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 预览与右侧表单共用同一份选中状态:点选区块即定位到对应字段。
|
||||||
|
const selectPreviewTarget = (targetKey?: string) => setPreviewTargetKey(targetKey);
|
||||||
|
|
||||||
|
// 列表与详情是两张不同的页面,切换时清空区块选中,避免沿用另一页的 key。
|
||||||
|
const changePreviewPage = (page: OfferingPreviewPage) => {
|
||||||
|
setPreviewPage(page);
|
||||||
|
setPreviewTargetKey(undefined);
|
||||||
|
};
|
||||||
|
|
||||||
const handleValuesChange = (_: unknown, allValues: Record<string, unknown>) => {
|
const handleValuesChange = (_: unknown, allValues: Record<string, unknown>) => {
|
||||||
setFormValues(allValues);
|
setFormValues(allValues);
|
||||||
setOfferingDraftVersion((version) => version + 1);
|
setOfferingDraftVersion((version) => version + 1);
|
||||||
@@ -60,7 +73,9 @@ export function useOfferingEditor(templateFields: TemplateAdminField[]) {
|
|||||||
templateFieldSection,
|
templateFieldSection,
|
||||||
formValues,
|
formValues,
|
||||||
offeringDraftVersion,
|
offeringDraftVersion,
|
||||||
setPreviewPage,
|
previewTargetKey,
|
||||||
|
changePreviewPage,
|
||||||
|
selectPreviewTarget,
|
||||||
beginOffering,
|
beginOffering,
|
||||||
closeOffering,
|
closeOffering,
|
||||||
handleValuesChange,
|
handleValuesChange,
|
||||||
|
|||||||
@@ -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,7 @@
|
|||||||
|
import type { FormInstance } from "antd";
|
||||||
|
|
||||||
|
// 动态隐藏的字段会被 Ant Design Form 卸载,onFinish 默认只返回仍挂载的字段。
|
||||||
|
// 提交时读取完整表单存储,避免切换区块后隐藏字段的修改丢失。
|
||||||
|
export function getFullFormValues<T = Record<string, unknown>>(form: FormInstance): T {
|
||||||
|
return form.getFieldsValue(true) as T;
|
||||||
|
}
|
||||||
@@ -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, ""), "");
|
||||||
|
});
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import { projectOfferingPreviewFields } from "../src/features/services/offering-preview-projection.ts";
|
||||||
|
|
||||||
|
const baseItem = {
|
||||||
|
name: "原名称",
|
||||||
|
summary: "原简介",
|
||||||
|
priceText: "原价格",
|
||||||
|
coverUrl: "/media/original-cover.jpg",
|
||||||
|
presentation: {
|
||||||
|
categoryKey: "portfolio",
|
||||||
|
categoryLabel: "品牌视觉",
|
||||||
|
heroImage: "/media/original-hero.jpg",
|
||||||
|
keywords: ["原始"],
|
||||||
|
media: [],
|
||||||
|
details: {
|
||||||
|
background: "原始背景",
|
||||||
|
designConcept: "",
|
||||||
|
crafts: [],
|
||||||
|
materialsList: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
test("filled name and coverUrl override originals", () => {
|
||||||
|
const result = projectOfferingPreviewFields({
|
||||||
|
item: baseItem,
|
||||||
|
config: {},
|
||||||
|
formValues: {
|
||||||
|
name: "新名称",
|
||||||
|
coverUrl: "/media/new-cover.jpg",
|
||||||
|
summary: "",
|
||||||
|
priceText: "",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.name, "新名称");
|
||||||
|
assert.equal(result.coverUrl, "/media/new-cover.jpg");
|
||||||
|
// summary/priceText 空字符串应覆盖原值(允许清空)。
|
||||||
|
assert.equal(result.summary, "");
|
||||||
|
assert.equal(result.priceText, "");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("empty name and coverUrl preserve originals", () => {
|
||||||
|
const result = projectOfferingPreviewFields({
|
||||||
|
item: baseItem,
|
||||||
|
config: {},
|
||||||
|
formValues: {
|
||||||
|
name: " ",
|
||||||
|
coverUrl: "",
|
||||||
|
summary: "新简介",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.name, "原名称");
|
||||||
|
assert.equal(result.coverUrl, "/media/original-cover.jpg");
|
||||||
|
assert.equal(result.summary, "新简介");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("presentation merges base config and nested presentation", () => {
|
||||||
|
const result = projectOfferingPreviewFields({
|
||||||
|
item: baseItem,
|
||||||
|
config: {
|
||||||
|
area: "杭州",
|
||||||
|
series: "品牌焕新",
|
||||||
|
spaceType: "线上与线下",
|
||||||
|
presentation: { categoryLabel: "新分类" },
|
||||||
|
keywords: ["新关键词"],
|
||||||
|
},
|
||||||
|
formValues: {},
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.presentation.area, "杭州");
|
||||||
|
assert.equal(result.presentation.series, "品牌焕新");
|
||||||
|
assert.equal(result.presentation.spaceType, "线上与线下");
|
||||||
|
assert.equal(result.presentation.categoryLabel, "新分类");
|
||||||
|
assert.deepEqual(result.presentation.keywords, ["新关键词"]);
|
||||||
|
// categoryKey 不被覆盖时保留原值。
|
||||||
|
assert.equal(result.presentation.categoryKey, "portfolio");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("heroImage follows detailHero, then coverUrl, then original", () => {
|
||||||
|
const hero = projectOfferingPreviewFields({
|
||||||
|
item: baseItem,
|
||||||
|
config: { detailHero: "/media/detail-hero.jpg" },
|
||||||
|
formValues: { coverUrl: "/media/new-cover.jpg" },
|
||||||
|
});
|
||||||
|
assert.equal(hero.presentation.heroImage, "/media/detail-hero.jpg");
|
||||||
|
|
||||||
|
const fallbackCover = projectOfferingPreviewFields({
|
||||||
|
item: baseItem,
|
||||||
|
config: { detailHero: "" },
|
||||||
|
formValues: { coverUrl: "/media/new-cover.jpg" },
|
||||||
|
});
|
||||||
|
assert.equal(fallbackCover.presentation.heroImage, "/media/new-cover.jpg");
|
||||||
|
|
||||||
|
const fallbackOriginal = projectOfferingPreviewFields({
|
||||||
|
item: baseItem,
|
||||||
|
config: { detailHero: "" },
|
||||||
|
formValues: { coverUrl: "" },
|
||||||
|
});
|
||||||
|
assert.equal(fallbackOriginal.presentation.heroImage, "/media/original-cover.jpg");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("details merge preserves originals and applies updates", () => {
|
||||||
|
const result = projectOfferingPreviewFields({
|
||||||
|
item: baseItem,
|
||||||
|
config: {
|
||||||
|
details: {
|
||||||
|
background: "更新后的背景",
|
||||||
|
designConcept: "新的设计理念",
|
||||||
|
crafts: ["新交付"],
|
||||||
|
materialsList: [{ name: "策略", spec: "定位" }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
formValues: {},
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.presentation.details.background, "更新后的背景");
|
||||||
|
assert.equal(result.presentation.details.designConcept, "新的设计理念");
|
||||||
|
assert.deepEqual(result.presentation.details.crafts, ["新交付"]);
|
||||||
|
assert.deepEqual(result.presentation.details.materialsList, [{ name: "策略", spec: "定位" }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("non-object config.presentation and details are ignored safely", () => {
|
||||||
|
const result = projectOfferingPreviewFields({
|
||||||
|
item: baseItem,
|
||||||
|
config: {
|
||||||
|
presentation: "invalid",
|
||||||
|
details: 42,
|
||||||
|
},
|
||||||
|
formValues: {},
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(result.presentation.keywords, ["原始"]);
|
||||||
|
assert.equal(result.presentation.details.background, "原始背景");
|
||||||
|
assert.deepEqual(result.presentation.details.crafts, []);
|
||||||
|
});
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import {
|
||||||
|
pageTemplateFields,
|
||||||
|
previewTargetsByPage,
|
||||||
|
} from "../src/features/services/offering-preview-targets.ts";
|
||||||
|
|
||||||
|
function section(page, target, fields) {
|
||||||
|
return {
|
||||||
|
key: `${page}-${target}`,
|
||||||
|
title: target,
|
||||||
|
description: "",
|
||||||
|
page,
|
||||||
|
target,
|
||||||
|
fields,
|
||||||
|
previewTargets: [{ key: `${page}.${target}`, label: target }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test("previewTargetsByPage prefers the offerings page for list targets", () => {
|
||||||
|
const sections = [
|
||||||
|
section("home", "homeCard", [{ binding: "offering.name", previewTarget: "home.homeCard" }]),
|
||||||
|
section("offerings", "offeringCard", [
|
||||||
|
{ binding: "offering.name", previewTarget: "offerings.offeringCard" },
|
||||||
|
]),
|
||||||
|
section("detail", "projectHero", [
|
||||||
|
{ binding: "offering.name", previewTarget: "detail.projectHero" },
|
||||||
|
]),
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = previewTargetsByPage(sections);
|
||||||
|
assert.deepEqual(
|
||||||
|
result.offerings.map((target) => target.key),
|
||||||
|
["offerings.offeringCard"],
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
result.detail.map((target) => target.key),
|
||||||
|
["detail.projectHero"],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("previewTargetsByPage falls back to the first non-detail page with offering records", () => {
|
||||||
|
const sections = [
|
||||||
|
section("home", "homeCard", [{ binding: "offering.name", previewTarget: "home.homeCard" }]),
|
||||||
|
section("detail", "projectHero", []),
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = previewTargetsByPage(sections);
|
||||||
|
assert.equal(result.offerings.length, 1);
|
||||||
|
assert.equal(result.offerings[0].key, "home.homeCard");
|
||||||
|
assert.equal(result.offerings[0].source, "offering");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("previewTargetsByPage returns no list targets without offering-backed pages", () => {
|
||||||
|
const sections = [
|
||||||
|
section("detail", "projectHero", [
|
||||||
|
{ binding: "brand.name", previewTarget: "detail.projectHero" },
|
||||||
|
]),
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = previewTargetsByPage(sections);
|
||||||
|
assert.deepEqual(result.offerings, []);
|
||||||
|
assert.deepEqual(
|
||||||
|
result.detail.map((target) => target.key),
|
||||||
|
["detail.projectHero"],
|
||||||
|
);
|
||||||
|
assert.notEqual(result.detail[0].source, "offering");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pageTemplateFields collects every detail target field", () => {
|
||||||
|
const previewTargets = previewTargetsByPage([
|
||||||
|
section("detail", "projectHero", [
|
||||||
|
{ binding: "offering.name", previewTarget: "detail.projectHero" },
|
||||||
|
]),
|
||||||
|
section("detail", "projectFacts", [
|
||||||
|
{ binding: "offering.priceText", previewTarget: "detail.projectFacts" },
|
||||||
|
]),
|
||||||
|
section("home", "homeCard", [{ binding: "offering.summary", previewTarget: "home.homeCard" }]),
|
||||||
|
]);
|
||||||
|
const templateFields = [
|
||||||
|
{ key: "name", binding: "offering.name", previewTarget: "detail.projectHero" },
|
||||||
|
{ key: "priceText", binding: "offering.priceText", previewTarget: "detail.projectFacts" },
|
||||||
|
{ key: "summary", binding: "offering.summary", previewTarget: "home.homeCard" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = pageTemplateFields({
|
||||||
|
previewPage: "detail",
|
||||||
|
previewTargets,
|
||||||
|
templateFields,
|
||||||
|
});
|
||||||
|
assert.deepEqual(
|
||||||
|
result.map((field) => field.key),
|
||||||
|
["name", "priceText"],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pageTemplateFields falls back to page fields without previewTarget", () => {
|
||||||
|
const previewTargets = previewTargetsByPage([
|
||||||
|
section("detail", "projectHero", [
|
||||||
|
{ binding: "offering.name", previewTarget: "detail.projectHero" },
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
const templateFields = [
|
||||||
|
{ key: "name", binding: "offering.name", previewTarget: "detail.projectHero" },
|
||||||
|
{ key: "legacy", binding: "offering.config.legacy", page: "detail" },
|
||||||
|
{ key: "other", binding: "offering.config.other", previewTarget: "unknown.target" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = pageTemplateFields({
|
||||||
|
previewPage: "detail",
|
||||||
|
previewTargets,
|
||||||
|
templateFields,
|
||||||
|
});
|
||||||
|
assert.deepEqual(
|
||||||
|
result.map((field) => field.key),
|
||||||
|
["name", "legacy"],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pageTemplateFields uses the inferred list page for offerings", () => {
|
||||||
|
const previewTargets = previewTargetsByPage([
|
||||||
|
section("home", "homeCard", [{ binding: "offering.name", previewTarget: "home.homeCard" }]),
|
||||||
|
section("detail", "projectHero", []),
|
||||||
|
]);
|
||||||
|
const templateFields = [
|
||||||
|
{ key: "name", binding: "offering.name", previewTarget: "home.homeCard" },
|
||||||
|
{ key: "legacy", binding: "offering.config.legacy", page: "home" },
|
||||||
|
{ key: "detail", binding: "offering.config.detail", previewTarget: "detail.projectHero" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = pageTemplateFields({
|
||||||
|
previewPage: "offerings",
|
||||||
|
previewTargets,
|
||||||
|
templateFields,
|
||||||
|
listPage: previewTargets.offerings[0]?.page,
|
||||||
|
});
|
||||||
|
assert.deepEqual(
|
||||||
|
result.map((field) => field.key),
|
||||||
|
["name", "legacy"],
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -4,11 +4,12 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc -p tsconfig.json",
|
"build": "tsc -p tsconfig.json",
|
||||||
|
"postinstall": "prisma generate",
|
||||||
"dev": "pnpm build && node --env-file=.env --watch dist/main.js",
|
"dev": "pnpm build && node --env-file=.env --watch dist/main.js",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||||
"test": "tsx --test test/**/*.test.ts",
|
"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",
|
"clean": "rimraf dist",
|
||||||
"start": "node dist/main.js",
|
"start": "node dist/main.js",
|
||||||
"db:generate": "prisma generate",
|
"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");
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
generator client {
|
generator client {
|
||||||
provider = "prisma-client-js"
|
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 {
|
datasource db {
|
||||||
@@ -468,6 +468,25 @@ model AdminUser {
|
|||||||
templateAuditLogs TemplatePackageAuditLog[] @relation("TemplatePackageAuditActor")
|
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 {
|
model TemplatePackage {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
packageKey String @unique
|
packageKey String @unique
|
||||||
|
|||||||
@@ -4,16 +4,36 @@ import { PrismaService } from "./prisma.service.js";
|
|||||||
import { readAdminToken } from "./admin-access.identity.js";
|
import { readAdminToken } from "./admin-access.identity.js";
|
||||||
import { readIdentity } from "./auth.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()
|
@Injectable()
|
||||||
export class AdminAccessService {
|
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) {}
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
async requireToken(request: FastifyRequest): Promise<{
|
requireToken(request: FastifyRequest): Promise<TokenAccess> {
|
||||||
subject: string;
|
const cached = this.tokenAccess.get(request);
|
||||||
brandId: string;
|
if (cached) return cached;
|
||||||
mustChangePassword: boolean;
|
const pending = this.resolveToken(request);
|
||||||
tokenVersion: number;
|
this.tokenAccess.set(request, pending);
|
||||||
}> {
|
return pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resolveToken(request: FastifyRequest): Promise<TokenAccess> {
|
||||||
const token = readAdminToken(request);
|
const token = readAdminToken(request);
|
||||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||||
let identity;
|
let identity;
|
||||||
@@ -25,7 +45,12 @@ export class AdminAccessService {
|
|||||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||||
const user = await this.prisma.adminUser.findUnique({
|
const user = await this.prisma.adminUser.findUnique({
|
||||||
where: { id: identity.subject },
|
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)
|
if (!user || identity.tokenVersion !== user.tokenVersion)
|
||||||
throw new UnauthorizedException("管理员登录态已失效,请重新登录");
|
throw new UnauthorizedException("管理员登录态已失效,请重新登录");
|
||||||
@@ -35,12 +60,19 @@ export class AdminAccessService {
|
|||||||
brandId: identity.brandId,
|
brandId: identity.brandId,
|
||||||
mustChangePassword: user.mustChangePassword,
|
mustChangePassword: user.mustChangePassword,
|
||||||
tokenVersion: user.tokenVersion,
|
tokenVersion: user.tokenVersion,
|
||||||
|
platformTemplateRole: user.platformTemplateRole,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async requireBrand(
|
requireBrand(request: FastifyRequest): Promise<BrandAccess> {
|
||||||
request: FastifyRequest,
|
const cached = this.brandAccess.get(request);
|
||||||
): Promise<{ subject: string; brandId: string; role: string }> {
|
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);
|
const access = await this.requireToken(request);
|
||||||
if (access.mustChangePassword)
|
if (access.mustChangePassword)
|
||||||
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
||||||
@@ -63,11 +95,7 @@ export class AdminAccessService {
|
|||||||
const access = await this.requireToken(request);
|
const access = await this.requireToken(request);
|
||||||
if (access.mustChangePassword)
|
if (access.mustChangePassword)
|
||||||
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
||||||
const user = await this.prisma.adminUser.findUniqueOrThrow({
|
if (access.platformTemplateRole !== "template_admin")
|
||||||
where: { id: access.subject },
|
|
||||||
select: { platformTemplateRole: true },
|
|
||||||
});
|
|
||||||
if (user.platformTemplateRole !== "template_admin")
|
|
||||||
throw new ForbiddenException("当前账号没有模板管理权限");
|
throw new ForbiddenException("当前账号没有模板管理权限");
|
||||||
return { subject: access.subject };
|
return { subject: access.subject };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { UnauthorizedException } from "@nestjs/common";
|
import { UnauthorizedException } from "@nestjs/common";
|
||||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||||
|
import { isPlaceholderSecret } from "./runtime-config.js";
|
||||||
|
|
||||||
type Identity = {
|
type Identity = {
|
||||||
subject: string;
|
subject: string;
|
||||||
@@ -9,9 +10,20 @@ type Identity = {
|
|||||||
exp: number;
|
exp: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let warnedAboutPlaceholderSecret = false;
|
||||||
|
|
||||||
function secret(): string {
|
function secret(): string {
|
||||||
const value = process.env.SESSION_SECRET;
|
const value = process.env.SESSION_SECRET;
|
||||||
if (!value || value.length < 32) throw new UnauthorizedException("服务端会话密钥未正确配置");
|
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;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -6,8 +6,10 @@ import multipart from "@fastify/multipart";
|
|||||||
import fastifyStatic from "@fastify/static";
|
import fastifyStatic from "@fastify/static";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { AppModule, configureApp } from "./app.module.js";
|
import { AppModule, configureApp } from "./app.module.js";
|
||||||
|
import { assertProductionSecret } from "./runtime-config.js";
|
||||||
|
|
||||||
export async function createApp(): Promise<NestFastifyApplication> {
|
export async function createApp(): Promise<NestFastifyApplication> {
|
||||||
|
assertProductionSecret(process.env.SESSION_SECRET);
|
||||||
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
|
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
|
||||||
app
|
app
|
||||||
.getHttpAdapter()
|
.getHttpAdapter()
|
||||||
|
|||||||
+1
-1
@@ -38,7 +38,7 @@ export function decryptMiniAppCredential(value: unknown): string {
|
|||||||
typeof payload.iv !== "string" ||
|
typeof payload.iv !== "string" ||
|
||||||
typeof payload.authTag !== "string"
|
typeof payload.authTag !== "string"
|
||||||
)
|
)
|
||||||
throw new UnauthorizedException("小程序上传凭据不可用");
|
throw new UnauthorizedException("小程序凭据不可用");
|
||||||
const decipher = createDecipheriv(ALGORITHM, encryptionKey(), Buffer.from(payload.iv, "base64"));
|
const decipher = createDecipheriv(ALGORITHM, encryptionKey(), Buffer.from(payload.iv, "base64"));
|
||||||
decipher.setAuthTag(Buffer.from(payload.authTag, "base64"));
|
decipher.setAuthTag(Buffer.from(payload.authTag, "base64"));
|
||||||
return Buffer.concat([
|
return Buffer.concat([
|
||||||
@@ -1,22 +1,12 @@
|
|||||||
import { AdminBrand } from "../../admin-auth.decorators.js";
|
import { AdminBrand } from "../../admin-auth.decorators.js";
|
||||||
import {
|
import { Body, Controller, Get, Param, Post, Query, Req } from "@nestjs/common";
|
||||||
Body,
|
|
||||||
Controller,
|
|
||||||
ForbiddenException,
|
|
||||||
Get,
|
|
||||||
Param,
|
|
||||||
Post,
|
|
||||||
Query,
|
|
||||||
Req,
|
|
||||||
UnauthorizedException,
|
|
||||||
} from "@nestjs/common";
|
|
||||||
import { Transform } from "class-transformer";
|
import { Transform } from "class-transformer";
|
||||||
import type { TransformFnParams } from "class-transformer";
|
import type { TransformFnParams } from "class-transformer";
|
||||||
import { BookingStatus } from "@prisma/client";
|
import { BookingStatus } from "@prisma/client";
|
||||||
import { IsBoolean, IsEnum, IsOptional, IsString } from "class-validator";
|
import { IsBoolean, IsEnum, IsOptional, IsString } from "class-validator";
|
||||||
import type { FastifyRequest } from "fastify";
|
import type { FastifyRequest } from "fastify";
|
||||||
|
import { AdminAccessService } from "../../admin-access.service.js";
|
||||||
import { BookingService } from "../../booking.service.js";
|
import { BookingService } from "../../booking.service.js";
|
||||||
import { readIdentity } from "../../auth.js";
|
|
||||||
import { UpdateBookingStatusDto, UpdateBookingTagsDto, CreateTagDto } from "../../admin.dto.js";
|
import { UpdateBookingStatusDto, UpdateBookingTagsDto, CreateTagDto } from "../../admin.dto.js";
|
||||||
|
|
||||||
class AdminBookingQueryDto {
|
class AdminBookingQueryDto {
|
||||||
@@ -35,67 +25,67 @@ class AdminBookingQueryDto {
|
|||||||
@AdminBrand()
|
@AdminBrand()
|
||||||
@Controller("admin/bookings")
|
@Controller("admin/bookings")
|
||||||
export class AdminBookingController {
|
export class AdminBookingController {
|
||||||
constructor(private readonly bookings: BookingService) {}
|
constructor(
|
||||||
|
private readonly access: AdminAccessService,
|
||||||
|
private readonly bookings: BookingService,
|
||||||
|
) {}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
list(@Req() request: FastifyRequest, @Query() query: AdminBookingQueryDto): Promise<unknown> {
|
async list(
|
||||||
const brandId = this.requireAdmin(request);
|
@Req() request: FastifyRequest,
|
||||||
|
@Query() query: AdminBookingQueryDto,
|
||||||
|
): Promise<unknown> {
|
||||||
|
const { brandId } = await this.access.requireBrand(request);
|
||||||
return this.bookings.listForAdmin(brandId, query);
|
return this.bookings.listForAdmin(brandId, query);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get("unread-count")
|
@Get("unread-count")
|
||||||
unreadCount(@Req() request: FastifyRequest): Promise<unknown> {
|
async unreadCount(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
return this.bookings.unreadCountForAdmin(this.requireAdmin(request));
|
const { brandId } = await this.access.requireBrand(request);
|
||||||
|
return this.bookings.unreadCountForAdmin(brandId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(":id")
|
@Get(":id")
|
||||||
detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
async detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||||
return this.bookings.getForAdmin(this.requireAdmin(request), id);
|
const { brandId } = await this.access.requireBrand(request);
|
||||||
|
return this.bookings.getForAdmin(brandId, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post(":id/status")
|
@Post(":id/status")
|
||||||
update(
|
async update(
|
||||||
@Req() request: FastifyRequest,
|
@Req() request: FastifyRequest,
|
||||||
@Param("id") id: string,
|
@Param("id") id: string,
|
||||||
@Body() body: UpdateBookingStatusDto,
|
@Body() body: UpdateBookingStatusDto,
|
||||||
): Promise<unknown> {
|
): 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")
|
@Post(":id/read")
|
||||||
markRead(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
async markRead(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||||
return this.bookings.markRead(this.requireAdmin(request), id);
|
const { brandId } = await this.access.requireBrand(request);
|
||||||
|
return this.bookings.markRead(brandId, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post(":id/tags")
|
@Post(":id/tags")
|
||||||
updateTags(
|
async updateTags(
|
||||||
@Req() request: FastifyRequest,
|
@Req() request: FastifyRequest,
|
||||||
@Param("id") id: string,
|
@Param("id") id: string,
|
||||||
@Body() body: UpdateBookingTagsDto,
|
@Body() body: UpdateBookingTagsDto,
|
||||||
): Promise<unknown> {
|
): 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")
|
@Get("tags")
|
||||||
listTags(@Req() request: FastifyRequest): Promise<unknown> {
|
async listTags(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
return this.bookings.listTags(this.requireAdmin(request));
|
const { brandId } = await this.access.requireBrand(request);
|
||||||
|
return this.bookings.listTags(brandId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post("tags")
|
@Post("tags")
|
||||||
createTag(@Req() request: FastifyRequest, @Body() body: CreateTagDto): Promise<unknown> {
|
async createTag(@Req() request: FastifyRequest, @Body() body: CreateTagDto): Promise<unknown> {
|
||||||
return this.bookings.createTag(this.requireAdmin(request), body.name);
|
const { brandId } = await this.access.requireBrand(request);
|
||||||
}
|
return this.bookings.createTag(brandId, 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;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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,
|
UpdateBrandPresentationDto,
|
||||||
UpdateTrustContentDto,
|
UpdateTrustContentDto,
|
||||||
} from "../../admin.dto.js";
|
} 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 { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||||
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
|
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@ import { AdminBrandConfigService } from "./admin-brand-config.service.js";
|
|||||||
@Controller("admin/config")
|
@Controller("admin/config")
|
||||||
export class AdminConfigController {
|
export class AdminConfigController {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
private readonly trustContent: TrustContentService,
|
||||||
private readonly brandConfig: AdminBrandConfigService,
|
private readonly brandConfig: AdminBrandConfigService,
|
||||||
) {}
|
) {}
|
||||||
@Get("brand")
|
@Get("brand")
|
||||||
@@ -42,7 +42,7 @@ export class AdminConfigController {
|
|||||||
@Get("trust-content")
|
@Get("trust-content")
|
||||||
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
|
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
return this.templateWorkspace.listTrustContent(identity.brandId);
|
return this.trustContent.listTrustContent(identity.brandId);
|
||||||
}
|
}
|
||||||
@Post("trust-content")
|
@Post("trust-content")
|
||||||
createTrustContent(
|
createTrustContent(
|
||||||
@@ -50,7 +50,7 @@ export class AdminConfigController {
|
|||||||
@Body() body: CreateTrustContentDto,
|
@Body() body: CreateTrustContentDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
return this.templateWorkspace.createTrustContent(identity.brandId, body);
|
return this.trustContent.createTrustContent(identity.brandId, body);
|
||||||
}
|
}
|
||||||
@Patch("trust-content/:id")
|
@Patch("trust-content/:id")
|
||||||
updateTrustContent(
|
updateTrustContent(
|
||||||
@@ -59,7 +59,7 @@ export class AdminConfigController {
|
|||||||
@Body() body: UpdateTrustContentDto,
|
@Body() body: UpdateTrustContentDto,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
return this.templateWorkspace.updateTrustContent(identity.brandId, id, body);
|
return this.trustContent.updateTrustContent(identity.brandId, id, body);
|
||||||
}
|
}
|
||||||
@Delete("trust-content/:id")
|
@Delete("trust-content/:id")
|
||||||
async deleteTrustContent(
|
async deleteTrustContent(
|
||||||
@@ -67,6 +67,6 @@ export class AdminConfigController {
|
|||||||
@Param("id") id: string,
|
@Param("id") id: string,
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
return this.templateWorkspace.deleteTrustContent(identity.brandId, id);
|
return this.trustContent.deleteTrustContent(identity.brandId, id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -18,4 +18,9 @@ export class UpdateMiniAppSettingsDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
privateKey?: string;
|
privateKey?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(128)
|
||||||
|
appSecret?: string;
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,7 @@ import { Prisma } from "@prisma/client";
|
|||||||
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
|
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
|
||||||
import { miniappArtifactRoot } from "./miniapp-artifact.js";
|
import { miniappArtifactRoot } from "./miniapp-artifact.js";
|
||||||
import { miniappApiBaseUrl, validateApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
|
import { miniappApiBaseUrl, validateApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
|
||||||
import { encryptMiniAppCredential } from "./miniapp-credential-crypto.js";
|
import { encryptMiniAppCredential } from "../../miniapp-credential-crypto.js";
|
||||||
import { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js";
|
import { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js";
|
||||||
import type { UpdateMiniAppSettingsDto } from "./admin-miniapp-settings.dto.js";
|
import type { UpdateMiniAppSettingsDto } from "./admin-miniapp-settings.dto.js";
|
||||||
|
|
||||||
@@ -18,10 +18,17 @@ export class AdminMiniAppSettingsService {
|
|||||||
|
|
||||||
async update(brandId: string, body: UpdateMiniAppSettingsDto & { privateKey?: string }) {
|
async update(brandId: string, body: UpdateMiniAppSettingsDto & { privateKey?: string }) {
|
||||||
if (body.privateKey !== undefined) this.validatePrivateKey(body.privateKey);
|
if (body.privateKey !== undefined) this.validatePrivateKey(body.privateKey);
|
||||||
|
if (body.appSecret !== undefined) this.validateAppSecret(body.appSecret);
|
||||||
const current = this.jsonObject(await this.releases.settings(brandId));
|
const current = this.jsonObject(await this.releases.settings(brandId));
|
||||||
|
const currentAppId = typeof current.appId === "string" ? current.appId : "";
|
||||||
|
const nextAppId = body.appId === undefined ? currentAppId : body.appId.trim();
|
||||||
|
if (currentAppId && nextAppId !== currentAppId && body.appSecret === undefined)
|
||||||
|
throw new BadRequestException(
|
||||||
|
"修改微信 AppID 时必须同时填写该 AppID 对应的 AppSecret,避免登录凭据与小程序不匹配",
|
||||||
|
);
|
||||||
const settings = {
|
const settings = {
|
||||||
...current,
|
...current,
|
||||||
appId: body.appId ?? current.appId ?? "",
|
appId: nextAppId,
|
||||||
apiBaseUrl:
|
apiBaseUrl:
|
||||||
body.apiBaseUrl === undefined ? (current.apiBaseUrl ?? "") : this.apiBaseUrl(body),
|
body.apiBaseUrl === undefined ? (current.apiBaseUrl ?? "") : this.apiBaseUrl(body),
|
||||||
build: {
|
build: {
|
||||||
@@ -31,6 +38,9 @@ export class AdminMiniAppSettingsService {
|
|||||||
...(body.privateKey === undefined
|
...(body.privateKey === undefined
|
||||||
? {}
|
? {}
|
||||||
: { credential: encryptMiniAppCredential(normalizePrivateKey(body.privateKey)) }),
|
: { credential: encryptMiniAppCredential(normalizePrivateKey(body.privateKey)) }),
|
||||||
|
...(body.appSecret === undefined
|
||||||
|
? {}
|
||||||
|
: { appSecretCredential: encryptMiniAppCredential(body.appSecret.trim()) }),
|
||||||
templateKey: current.templateKey ?? null,
|
templateKey: current.templateKey ?? null,
|
||||||
} satisfies Prisma.InputJsonObject;
|
} satisfies Prisma.InputJsonObject;
|
||||||
await this.releases.saveSettings(brandId, settings);
|
await this.releases.saveSettings(brandId, settings);
|
||||||
@@ -47,6 +57,14 @@ export class AdminMiniAppSettingsService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private validateAppSecret(appSecret: string) {
|
||||||
|
const trimmed = appSecret.trim();
|
||||||
|
if (!/^[A-Za-z0-9]{16,64}$/.test(trimmed))
|
||||||
|
throw new BadRequestException(
|
||||||
|
"微信登录 AppSecret 格式无效:应为 16-64 位字母或数字,请从微信公众平台复制完整值",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private apiBaseUrl(body: UpdateMiniAppSettingsDto) {
|
private apiBaseUrl(body: UpdateMiniAppSettingsDto) {
|
||||||
const trimmed = body.apiBaseUrl?.trim();
|
const trimmed = body.apiBaseUrl?.trim();
|
||||||
if (!trimmed) throw new BadRequestException("小程序请求地址不能为空");
|
if (!trimmed) throw new BadRequestException("小程序请求地址不能为空");
|
||||||
@@ -58,16 +76,21 @@ export class AdminMiniAppSettingsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private present(settings: Record<string, unknown>) {
|
private present(settings: Record<string, unknown>) {
|
||||||
|
const { credential, appSecretCredential, ...rest } = settings;
|
||||||
|
delete rest.appSecret;
|
||||||
|
const appId = typeof rest.appId === "string" ? rest.appId : "";
|
||||||
return {
|
return {
|
||||||
appId: "",
|
appId: "",
|
||||||
artifactPath: miniappArtifactRoot(),
|
artifactPath: miniappArtifactRoot(),
|
||||||
build: {},
|
build: {},
|
||||||
...settings,
|
...rest,
|
||||||
apiBaseUrl: this.effectiveApiBaseUrl(settings.apiBaseUrl),
|
apiBaseUrl: this.effectiveApiBaseUrl(rest.apiBaseUrl),
|
||||||
privateKey: undefined,
|
privateKey: undefined,
|
||||||
credential: settings.credential ? { algorithm: "aes-256-gcm" } : null,
|
credential: credential ? { algorithm: "aes-256-gcm" } : null,
|
||||||
hasStoredCredentials: Boolean(settings.credential),
|
hasStoredCredentials: Boolean(credential),
|
||||||
...this.buildConfigSummary(settings.apiBaseUrl, settings.appId),
|
hasStoredAppSecret: Boolean(appSecretCredential),
|
||||||
|
loginConfigured: Boolean(appId && appSecretCredential),
|
||||||
|
...this.buildConfigSummary(rest.apiBaseUrl, rest.appId),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import {
|
|||||||
import { miniappReleaseProjectPath, miniappTaroOutputRoot } from "./miniapp-artifact.js";
|
import { miniappReleaseProjectPath, miniappTaroOutputRoot } from "./miniapp-artifact.js";
|
||||||
import { miniappApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
|
import { miniappApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
|
||||||
import { buildingStaleMs, isStaleBuilding } from "./miniapp-build-status.js";
|
import { buildingStaleMs, isStaleBuilding } from "./miniapp-build-status.js";
|
||||||
import { decryptMiniAppCredential } from "./miniapp-credential-crypto.js";
|
import { decryptMiniAppCredential } from "../../miniapp-credential-crypto.js";
|
||||||
import { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js";
|
import { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js";
|
||||||
import { runMiniAppUpload } from "./miniapp-upload.js";
|
import { runMiniAppUpload } from "./miniapp-upload.js";
|
||||||
|
|
||||||
@@ -68,7 +68,7 @@ export class AdminMiniAppUploadService {
|
|||||||
const keyInspection = inspectPrivateKey(normalizedPrivateKey);
|
const keyInspection = inspectPrivateKey(normalizedPrivateKey);
|
||||||
if (!keyInspection.valid)
|
if (!keyInspection.valid)
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
`上传私钥无法解析(${keyInspection.reason ?? "PEM 格式错误"})。请在“小程序上传配置”里重新粘贴完整私钥。`,
|
`上传私钥无法解析(${keyInspection.reason ?? "PEM 格式错误"})。请在“小程序配置”里重新粘贴完整私钥。`,
|
||||||
);
|
);
|
||||||
|
|
||||||
const templateManifest = miniAppTemplateManifest(brand.templateKey);
|
const templateManifest = miniAppTemplateManifest(brand.templateKey);
|
||||||
|
|||||||
@@ -2,6 +2,11 @@ import { Module } from "@nestjs/common";
|
|||||||
import { BookingModule } from "../booking.module.js";
|
import { BookingModule } from "../booking.module.js";
|
||||||
import { InfrastructureModule } from "../infrastructure.module.js";
|
import { InfrastructureModule } from "../infrastructure.module.js";
|
||||||
import { AdminBookingController } from "./admin-booking.controller.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 { AdminBrandConfigService } from "./admin-brand-config.service.js";
|
||||||
import { AdminConfigController } from "./admin-config.controller.js";
|
import { AdminConfigController } from "./admin-config.controller.js";
|
||||||
import { AdminLocalUploadController } from "./admin-local-upload.controller.js";
|
import { AdminLocalUploadController } from "./admin-local-upload.controller.js";
|
||||||
@@ -32,6 +37,7 @@ import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-asse
|
|||||||
AdminBookingController,
|
AdminBookingController,
|
||||||
AdminTemplatePackageController,
|
AdminTemplatePackageController,
|
||||||
TemplateOperationMetricsController,
|
TemplateOperationMetricsController,
|
||||||
|
AdminClientErrorController,
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
AdminBrandConfigService,
|
AdminBrandConfigService,
|
||||||
@@ -44,6 +50,12 @@ import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-asse
|
|||||||
AdminTemplatePreviewService,
|
AdminTemplatePreviewService,
|
||||||
AdminTemplatePreviewAssetsService,
|
AdminTemplatePreviewAssetsService,
|
||||||
TemplateOperationMetricsService,
|
TemplateOperationMetricsService,
|
||||||
|
{
|
||||||
|
provide: CLIENT_ERROR_THROTTLE_STORE,
|
||||||
|
useFactory: (prisma: PrismaService) => createClientErrorThrottleStore(prisma),
|
||||||
|
inject: [PrismaService],
|
||||||
|
},
|
||||||
|
AdminClientErrorService,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class AdminModule {}
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,7 +26,7 @@ export function miniappApiBaseUrl(
|
|||||||
normalizeBaseUrl(`${normalizeBaseUrl(publicBase)}${env.MINIAPP_API_PATH ?? "/api"}`),
|
normalizeBaseUrl(`${normalizeBaseUrl(publicBase)}${env.MINIAPP_API_PATH ?? "/api"}`),
|
||||||
);
|
);
|
||||||
throw new Error(
|
throw new Error(
|
||||||
"未配置小程序请求地址:请在“配置与发布 → 小程序上传配置”里填写“小程序请求地址”,例如 https://wechat.app.que01.top/api",
|
"未配置小程序请求地址:请在“配置与发布 → 小程序配置”里填写“小程序请求地址”,例如 https://wechat.app.que01.top/api",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,6 +53,6 @@ export function weappAppId(storedAppId: unknown, env: NodeJS.ProcessEnv = proces
|
|||||||
? storedAppId.trim()
|
? storedAppId.trim()
|
||||||
: (env.WEAPP_APP_ID?.trim() ?? "");
|
: (env.WEAPP_APP_ID?.trim() ?? "");
|
||||||
if (!candidate || candidate === "undefined" || candidate === "touristappid")
|
if (!candidate || candidate === "undefined" || candidate === "touristappid")
|
||||||
throw new Error("未配置微信 AppID:请在“小程序上传配置”里填写或设置 WEAPP_APP_ID");
|
throw new Error("未配置微信 AppID:请在“小程序配置”里填写或设置 WEAPP_APP_ID");
|
||||||
return candidate;
|
return candidate;
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,9 @@ import { AdminMembershipGuard } from "../admin-membership.guard.js";
|
|||||||
import { BrandReleaseApiService } from "../brand-release-api.service.js";
|
import { BrandReleaseApiService } from "../brand-release-api.service.js";
|
||||||
import { BrandReleaseService } from "../brand-release.service.js";
|
import { BrandReleaseService } from "../brand-release.service.js";
|
||||||
import { PrismaService } from "../prisma.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";
|
import { WechatAuthService } from "../wechat-auth.js";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
@@ -15,7 +17,9 @@ import { WechatAuthService } from "../wechat-auth.js";
|
|||||||
AdminMembershipGuard,
|
AdminMembershipGuard,
|
||||||
BrandReleaseService,
|
BrandReleaseService,
|
||||||
BrandReleaseApiService,
|
BrandReleaseApiService,
|
||||||
TemplateWorkspaceService,
|
PageSchemeService,
|
||||||
|
TemplateInstallationService,
|
||||||
|
TrustContentService,
|
||||||
],
|
],
|
||||||
exports: [
|
exports: [
|
||||||
PrismaService,
|
PrismaService,
|
||||||
@@ -24,7 +28,9 @@ import { WechatAuthService } from "../wechat-auth.js";
|
|||||||
AdminMembershipGuard,
|
AdminMembershipGuard,
|
||||||
BrandReleaseService,
|
BrandReleaseService,
|
||||||
BrandReleaseApiService,
|
BrandReleaseApiService,
|
||||||
TemplateWorkspaceService,
|
PageSchemeService,
|
||||||
|
TemplateInstallationService,
|
||||||
|
TrustContentService,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class InfrastructureModule {}
|
export class InfrastructureModule {}
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||||
import { PrismaService } from "../../prisma.service.js";
|
import { PrismaService } from "../../prisma.service.js";
|
||||||
import { signIdentity } from "../../auth.js";
|
import { signIdentity } from "../../auth.js";
|
||||||
import type { WechatSession } from "../../wechat-auth.js";
|
import {
|
||||||
|
WechatAuthService,
|
||||||
|
resolveWechatLoginCredentials,
|
||||||
|
type WechatSession,
|
||||||
|
} from "../../wechat-auth.js";
|
||||||
import { PublicBrandContextService } from "../public/public-brand-context.service.js";
|
import { PublicBrandContextService } from "../public/public-brand-context.service.js";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -9,15 +13,18 @@ export class CustomerSessionService {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly brandContext: PublicBrandContextService,
|
private readonly brandContext: PublicBrandContextService,
|
||||||
|
private readonly wechatAuth: WechatAuthService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async loginWithWechat(session: WechatSession, brandSlug?: string): Promise<{ token: string }> {
|
async loginWithWechat(code: string, brandSlug?: string): Promise<{ token: string }> {
|
||||||
const brandId = await this.brandContext.resolveId(brandSlug);
|
const brandId = await this.brandContext.resolveId(brandSlug);
|
||||||
const brand = await this.prisma.brandProfile.findUnique({
|
const brand = await this.prisma.brandProfile.findUnique({
|
||||||
where: { id: brandId },
|
where: { id: brandId },
|
||||||
select: { id: true },
|
select: { id: true, miniAppSettings: true },
|
||||||
});
|
});
|
||||||
if (!brand) throw new BadRequestException("品牌尚未初始化");
|
if (!brand) throw new BadRequestException("品牌尚未初始化");
|
||||||
|
const credentials = resolveWechatLoginCredentials(brand.miniAppSettings);
|
||||||
|
const session: WechatSession = await this.wechatAuth.exchangeCode(code, credentials);
|
||||||
const customer = await this.prisma.customerUser.upsert({
|
const customer = await this.prisma.customerUser.upsert({
|
||||||
where: { brandId_openid: { brandId: brand.id, openid: session.openid } },
|
where: { brandId_openid: { brandId: brand.id, openid: session.openid } },
|
||||||
update: { lastLoginAt: new Date() },
|
update: { lastLoginAt: new Date() },
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { Body, Controller, Get, Post, Query, Req, Res } from "@nestjs/common";
|
import { Body, Controller, Get, Post, Query, Req, Res } from "@nestjs/common";
|
||||||
import type { FastifyReply, FastifyRequest } from "fastify";
|
import type { FastifyReply, FastifyRequest } from "fastify";
|
||||||
import { WechatAuthService } from "../../wechat-auth.js";
|
|
||||||
import { AdminPublic, AdminTokenOnly } from "../../admin-auth.decorators.js";
|
import { AdminPublic, AdminTokenOnly } from "../../admin-auth.decorators.js";
|
||||||
import { clearAdminSessionCookie, setAdminSessionCookie } from "../../admin-session-cookie.js";
|
import { clearAdminSessionCookie, setAdminSessionCookie } from "../../admin-session-cookie.js";
|
||||||
import { AdminAuthService } from "../../admin-auth.service.js";
|
import { AdminAuthService } from "../../admin-auth.service.js";
|
||||||
@@ -11,18 +10,14 @@ import { ChangeAdminPasswordDto } from "../../admin.dto.js";
|
|||||||
|
|
||||||
@Controller("customer/session")
|
@Controller("customer/session")
|
||||||
export class CustomerSessionController {
|
export class CustomerSessionController {
|
||||||
constructor(
|
constructor(private readonly sessions: CustomerSessionService) {}
|
||||||
private readonly wechatAuth: WechatAuthService,
|
|
||||||
private readonly sessions: CustomerSessionService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
@Post("wechat")
|
@Post("wechat")
|
||||||
async wechatLogin(
|
async wechatLogin(
|
||||||
@Body() body: WechatLoginDto,
|
@Body() body: WechatLoginDto,
|
||||||
@Query("brandSlug") brandSlug?: string,
|
@Query("brandSlug") brandSlug?: string,
|
||||||
): Promise<{ token: string }> {
|
): Promise<{ token: string }> {
|
||||||
const session = await this.wechatAuth.exchangeCode(body.code);
|
return this.sessions.loginWithWechat(body.code, brandSlug);
|
||||||
return this.sessions.loginWithWechat(session, brandSlug);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,8 @@ import type {
|
|||||||
CreateBrandMemberDto,
|
CreateBrandMemberDto,
|
||||||
UpdateBrandMemberDto,
|
UpdateBrandMemberDto,
|
||||||
} from "../../admin.dto.js";
|
} 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 };
|
type AdminIdentity = { subject: string; brandId: string; tokenVersion?: number };
|
||||||
|
|
||||||
@@ -22,11 +23,12 @@ type AdminIdentity = { subject: string; brandId: string; tokenVersion?: number }
|
|||||||
export class TenantService {
|
export class TenantService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
private readonly pageSchemes: PageSchemeService,
|
||||||
|
private readonly templateInstallations: TemplateInstallationService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async getCreationOptions() {
|
async getCreationOptions() {
|
||||||
const catalog = await this.templateWorkspace.getPageSchemeCatalog();
|
const catalog = await this.pageSchemes.getPageSchemeCatalog();
|
||||||
// 创建品牌只应从每个页面方案的最新已发布版本开始;旧版本仍可在页面方案页显式切换。
|
// 创建品牌只应从每个页面方案的最新已发布版本开始;旧版本仍可在页面方案页显式切换。
|
||||||
return {
|
return {
|
||||||
...catalog,
|
...catalog,
|
||||||
@@ -40,7 +42,7 @@ export class TenantService {
|
|||||||
const name = body.name.trim();
|
const name = body.name.trim();
|
||||||
const slug = body.slug.trim();
|
const slug = body.slug.trim();
|
||||||
if (!name || !slug) throw new BadRequestException("品牌名称和小程序地址标识不能为空");
|
if (!name || !slug) throw new BadRequestException("品牌名称和小程序地址标识不能为空");
|
||||||
const packageVersion = await this.templateWorkspace.resolveInstallablePackageVersion(
|
const packageVersion = await this.templateInstallations.resolveInstallablePackageVersion(
|
||||||
body.businessType,
|
body.businessType,
|
||||||
body.templatePackageVersionId,
|
body.templatePackageVersionId,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,24 +2,28 @@ import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
|||||||
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
|
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
|
||||||
import type { FastifyRequest } from "fastify";
|
import type { FastifyRequest } from "fastify";
|
||||||
import { RollbackTemplateDto, UpgradeTemplateDto } from "../../admin.dto.js";
|
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";
|
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||||
|
|
||||||
@AdminBrand()
|
@AdminBrand()
|
||||||
@Controller("admin/workspace")
|
@Controller("admin/workspace")
|
||||||
class AdminTemplateController {
|
class AdminTemplateController {
|
||||||
constructor(private readonly templateWorkspace: TemplateWorkspaceService) {}
|
constructor(
|
||||||
|
private readonly pageSchemes: PageSchemeService,
|
||||||
|
private readonly templateInstallations: TemplateInstallationService,
|
||||||
|
) {}
|
||||||
|
|
||||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||||
@Get("template/options")
|
@Get("template/options")
|
||||||
options(@Req() request: FastifyRequest): Promise<unknown> {
|
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"])
|
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||||
@Get("template/preview")
|
@Get("template/preview")
|
||||||
preview(@Req() request: FastifyRequest): Promise<unknown> {
|
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"])
|
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||||
@@ -30,7 +34,7 @@ class AdminTemplateController {
|
|||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
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"])
|
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||||
@@ -41,7 +45,7 @@ class AdminTemplateController {
|
|||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
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,
|
validateCapabilityConfig,
|
||||||
} from "@personal-brand/config";
|
} from "@personal-brand/config";
|
||||||
import { PrismaService } from "../../prisma.service.js";
|
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";
|
import type { UpdateCapabilityInstallationDto } from "../../admin.dto.js";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AdminWorkspaceCapabilitiesService {
|
export class AdminWorkspaceCapabilitiesService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
private readonly templateInstallations: TemplateInstallationService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async list(brandId: string) {
|
async list(brandId: string) {
|
||||||
const [templateKey, installations] = await Promise.all([
|
const [templateKey, installations] = await Promise.all([
|
||||||
this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
this.templateInstallations.getEffectiveTemplateKey(brandId),
|
||||||
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
|
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
|
||||||
]);
|
]);
|
||||||
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
|
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
|
||||||
@@ -54,7 +54,7 @@ export class AdminWorkspaceCapabilitiesService {
|
|||||||
body: UpdateCapabilityInstallationDto,
|
body: UpdateCapabilityInstallationDto,
|
||||||
) {
|
) {
|
||||||
const template = getBrandTemplate(
|
const template = getBrandTemplate(
|
||||||
await this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
await this.templateInstallations.getEffectiveTemplateKey(brandId),
|
||||||
);
|
);
|
||||||
if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins))
|
if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins))
|
||||||
throw new BadRequestException("能力未被当前模板声明");
|
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 { Controller, Get, Post, Body, Req } from "@nestjs/common";
|
||||||
import type { FastifyRequest } from "fastify";
|
import type { FastifyRequest } from "fastify";
|
||||||
import { InstallTemplateDto, SelectTemplateVersionDto } from "../../admin.dto.js";
|
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 { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||||
import { AdminWorkspaceService } from "./admin-workspace.service.js";
|
import { AdminWorkspaceService } from "./admin-workspace.service.js";
|
||||||
|
|
||||||
@@ -11,7 +11,7 @@ import { AdminWorkspaceService } from "./admin-workspace.service.js";
|
|||||||
class AdminWorkspacePreviewController {
|
class AdminWorkspacePreviewController {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly workspaceService: AdminWorkspaceService,
|
private readonly workspaceService: AdminWorkspaceService,
|
||||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
private readonly templateInstallations: TemplateInstallationService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@@ -32,7 +32,7 @@ class AdminWorkspacePreviewController {
|
|||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||||
return this.templateWorkspace.install(
|
return this.templateInstallations.install(
|
||||||
identity.brandId,
|
identity.brandId,
|
||||||
body.templateKey,
|
body.templateKey,
|
||||||
body.templatePackageVersionId,
|
body.templatePackageVersionId,
|
||||||
@@ -49,7 +49,7 @@ class AdminWorkspacePreviewController {
|
|||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
const identity = requireAdminIdentity(request);
|
const identity = requireAdminIdentity(request);
|
||||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||||
return this.templateWorkspace.selectVersion(
|
return this.templateInstallations.selectVersion(
|
||||||
identity.brandId,
|
identity.brandId,
|
||||||
body,
|
body,
|
||||||
identity.subject,
|
identity.subject,
|
||||||
|
|||||||
@@ -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),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+15
-258
@@ -3,7 +3,6 @@ import type { TemplatePackageVersion } from "@prisma/client";
|
|||||||
import { Prisma } from "@prisma/client";
|
import { Prisma } from "@prisma/client";
|
||||||
import {
|
import {
|
||||||
type BrandTemplateKey,
|
type BrandTemplateKey,
|
||||||
brandTemplateKeys,
|
|
||||||
getBrandTemplate,
|
getBrandTemplate,
|
||||||
getVisualTemplate,
|
getVisualTemplate,
|
||||||
getVisualTemplateManifest,
|
getVisualTemplateManifest,
|
||||||
@@ -11,157 +10,25 @@ import {
|
|||||||
validateTemplatePackageManifest,
|
validateTemplatePackageManifest,
|
||||||
} from "@personal-brand/config";
|
} from "@personal-brand/config";
|
||||||
import type { TemplatePackageManifest } 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 type { RollbackTemplateDto, UpgradeTemplateDto } from "./admin.dto.js";
|
import { PrismaService } from "../prisma.service.js";
|
||||||
import { PrismaService } from "./prisma.service.js";
|
import { recordTemplateOperationFailure } from "../modules/admin/template-operation-failure.js";
|
||||||
import { recordTemplateOperationFailure } from "./modules/admin/template-operation-failure.js";
|
import { latestTemplateVersion } from "../template-version-order.js";
|
||||||
import { compareTemplateVersions, latestTemplateVersion } from "./template-version-order.js";
|
import {
|
||||||
|
compareFiles,
|
||||||
|
compareKeyedRecords,
|
||||||
|
compareRecords,
|
||||||
|
hasBindingValue,
|
||||||
|
manifestRecords,
|
||||||
|
readPackageFiles,
|
||||||
|
record,
|
||||||
|
stringList,
|
||||||
|
} from "./manifest-diff.helpers.js";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TemplateWorkspaceService {
|
export class TemplateInstallationService {
|
||||||
constructor(private readonly prisma: PrismaService) {}
|
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> {
|
async getEffectiveTemplateKey(brandId: string): Promise<BrandTemplateKey> {
|
||||||
const [brand, installation] = await Promise.all([
|
const [brand, installation] = await Promise.all([
|
||||||
this.prisma.brandProfile.findUnique({
|
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 };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Injectable, ServiceUnavailableException, UnauthorizedException } from "@nestjs/common";
|
import { Injectable, ServiceUnavailableException, UnauthorizedException } from "@nestjs/common";
|
||||||
|
import { decryptMiniAppCredential } from "./miniapp-credential-crypto.js";
|
||||||
|
|
||||||
interface WechatSessionResponse {
|
interface WechatSessionResponse {
|
||||||
openid?: string;
|
openid?: string;
|
||||||
@@ -14,17 +15,45 @@ export interface WechatSession {
|
|||||||
unionid?: string;
|
unionid?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface WechatLoginCredentials {
|
||||||
|
appId: string;
|
||||||
|
appSecret: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每个品牌对应自己的小程序,登录凭据必须来自该品牌的后台上传配置。
|
||||||
|
* 不使用全局环境变量或跨品牌回退,避免把 A 品牌的 OpenID 登录到 B 品牌。
|
||||||
|
*/
|
||||||
|
export function resolveWechatLoginCredentials(settings: unknown): WechatLoginCredentials {
|
||||||
|
const payload =
|
||||||
|
settings && typeof settings === "object" && !Array.isArray(settings)
|
||||||
|
? (settings as Record<string, unknown>)
|
||||||
|
: {};
|
||||||
|
const appId = typeof payload.appId === "string" ? payload.appId.trim() : "";
|
||||||
|
if (!appId) throw new ServiceUnavailableException("该品牌尚未配置微信 AppID");
|
||||||
|
if (!payload.appSecretCredential)
|
||||||
|
throw new ServiceUnavailableException("该品牌尚未配置微信登录 AppSecret");
|
||||||
|
let appSecret: string;
|
||||||
|
try {
|
||||||
|
appSecret = decryptMiniAppCredential(payload.appSecretCredential);
|
||||||
|
} catch {
|
||||||
|
throw new ServiceUnavailableException("该品牌微信登录凭据不可用,请重新保存 AppSecret");
|
||||||
|
}
|
||||||
|
if (!appSecret)
|
||||||
|
throw new ServiceUnavailableException("该品牌微信登录 AppSecret 为空,请重新保存");
|
||||||
|
return { appId, appSecret };
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class WechatAuthService {
|
export class WechatAuthService {
|
||||||
async exchangeCode(code: string): Promise<WechatSession> {
|
async exchangeCode(code: string, credentials: WechatLoginCredentials): Promise<WechatSession> {
|
||||||
if (!code.trim()) throw new UnauthorizedException("微信登录 code 不能为空");
|
if (!code.trim()) throw new UnauthorizedException("微信登录 code 不能为空");
|
||||||
const appId = process.env.WECHAT_APP_ID;
|
if (!credentials.appId || !credentials.appSecret)
|
||||||
const appSecret = process.env.WECHAT_APP_SECRET;
|
throw new ServiceUnavailableException("微信登录尚未配置");
|
||||||
if (!appId || !appSecret) throw new ServiceUnavailableException("微信登录尚未配置");
|
|
||||||
|
|
||||||
const query = new URLSearchParams({
|
const query = new URLSearchParams({
|
||||||
appid: appId,
|
appid: credentials.appId,
|
||||||
secret: appSecret,
|
secret: credentials.appSecret,
|
||||||
js_code: code,
|
js_code: code,
|
||||||
grant_type: "authorization_code",
|
grant_type: "authorization_code",
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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,
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,7 +4,10 @@ import { BadRequestException } from "@nestjs/common";
|
|||||||
import { generateKeyPairSync } from "node:crypto";
|
import { generateKeyPairSync } from "node:crypto";
|
||||||
import { AdminMiniAppSettingsService } from "../src/modules/admin/admin-miniapp-settings.service.js";
|
import { AdminMiniAppSettingsService } from "../src/modules/admin/admin-miniapp-settings.service.js";
|
||||||
import type { AdminMiniAppReleaseService } from "../src/modules/admin/admin-miniapp-release.service.js";
|
import type { AdminMiniAppReleaseService } from "../src/modules/admin/admin-miniapp-release.service.js";
|
||||||
import { decryptMiniAppCredential } from "../src/modules/admin/miniapp-credential-crypto.js";
|
import {
|
||||||
|
decryptMiniAppCredential,
|
||||||
|
encryptMiniAppCredential,
|
||||||
|
} from "../src/miniapp-credential-crypto.js";
|
||||||
|
|
||||||
process.env.SESSION_SECRET = "settings-service-test-secret-1234567890";
|
process.env.SESSION_SECRET = "settings-service-test-secret-1234567890";
|
||||||
|
|
||||||
@@ -25,12 +28,19 @@ function createService(settings: Record<string, unknown> = {}) {
|
|||||||
return { service: new AdminMiniAppSettingsService(releases), saved };
|
return { service: new AdminMiniAppSettingsService(releases), saved };
|
||||||
}
|
}
|
||||||
|
|
||||||
test("settings presentation never exposes plaintext credentials", async () => {
|
test("settings presentation never exposes encrypted credential payloads", async () => {
|
||||||
const credential = { algorithm: "aes-256-gcm" };
|
const credential = { algorithm: "aes-256-gcm" };
|
||||||
|
const appSecretCredential = {
|
||||||
|
algorithm: "aes-256-gcm",
|
||||||
|
ciphertext: "encrypted-secret",
|
||||||
|
iv: "iv",
|
||||||
|
authTag: "tag",
|
||||||
|
};
|
||||||
const { service } = createService({
|
const { service } = createService({
|
||||||
appId: "wxtestsettings",
|
appId: "wxtestsettings",
|
||||||
apiBaseUrl: "https://wechat.example.com/api",
|
apiBaseUrl: "https://wechat.example.com/api",
|
||||||
credential,
|
credential,
|
||||||
|
appSecretCredential,
|
||||||
build: { keep: true },
|
build: { keep: true },
|
||||||
});
|
});
|
||||||
const result = (await service.get("brand-1")) as Record<string, unknown>;
|
const result = (await service.get("brand-1")) as Record<string, unknown>;
|
||||||
@@ -38,8 +48,12 @@ test("settings presentation never exposes plaintext credentials", async () => {
|
|||||||
assert.equal(result.apiBaseUrl, "https://wechat.example.com/api");
|
assert.equal(result.apiBaseUrl, "https://wechat.example.com/api");
|
||||||
assert.equal(result.requestDomain, "wechat.example.com");
|
assert.equal(result.requestDomain, "wechat.example.com");
|
||||||
assert.equal(result.hasStoredCredentials, true);
|
assert.equal(result.hasStoredCredentials, true);
|
||||||
|
assert.equal(result.hasStoredAppSecret, true);
|
||||||
|
assert.equal(result.loginConfigured, true);
|
||||||
assert.deepEqual(result.credential, { algorithm: "aes-256-gcm" });
|
assert.deepEqual(result.credential, { algorithm: "aes-256-gcm" });
|
||||||
assert.equal(result.privateKey, undefined);
|
assert.equal(result.privateKey, undefined);
|
||||||
|
assert.equal("appSecretCredential" in result, false);
|
||||||
|
assert.equal(JSON.stringify(result).includes("encrypted-secret"), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("update validates URL and private key before persistence", async () => {
|
test("update validates URL and private key before persistence", async () => {
|
||||||
@@ -67,6 +81,7 @@ test("update encrypts a valid private key and preserves existing settings", asyn
|
|||||||
appId: "wxnew",
|
appId: "wxnew",
|
||||||
apiBaseUrl: "https://new.example.com/api/",
|
apiBaseUrl: "https://new.example.com/api/",
|
||||||
privateKey,
|
privateKey,
|
||||||
|
appSecret: "0123456789abcdef0123456789abcdef",
|
||||||
build: { extra: true },
|
build: { extra: true },
|
||||||
})) as Record<string, unknown>;
|
})) as Record<string, unknown>;
|
||||||
assert.equal(saved.length, 1);
|
assert.equal(saved.length, 1);
|
||||||
@@ -82,3 +97,54 @@ test("update encrypts a valid private key and preserves existing settings", asyn
|
|||||||
assert.ok(!JSON.stringify(saved[0]).includes(privateKey));
|
assert.ok(!JSON.stringify(saved[0]).includes(privateKey));
|
||||||
assert.equal(result.hasStoredCredentials, true);
|
assert.equal(result.hasStoredCredentials, true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("update encrypts the WeChat login AppSecret without exposing it", async () => {
|
||||||
|
const appSecret = "0123456789abcdef0123456789abcdef";
|
||||||
|
const { service, saved } = createService({
|
||||||
|
appId: "wxtestsettings",
|
||||||
|
apiBaseUrl: "https://wechat.example.com/api",
|
||||||
|
});
|
||||||
|
const result = (await service.update("brand-1", { appSecret })) as Record<string, unknown>;
|
||||||
|
assert.equal(saved.length, 1);
|
||||||
|
const appSecretCredential = saved[0]?.appSecretCredential as Record<string, string>;
|
||||||
|
assert.equal(appSecretCredential.algorithm, "aes-256-gcm");
|
||||||
|
assert.equal(decryptMiniAppCredential(appSecretCredential), appSecret);
|
||||||
|
assert.equal(JSON.stringify(saved[0]).includes(appSecret), false);
|
||||||
|
assert.equal(result.hasStoredAppSecret, true);
|
||||||
|
assert.equal(result.loginConfigured, true);
|
||||||
|
assert.equal("appSecretCredential" in result, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("update rejects malformed WeChat login AppSecret", async () => {
|
||||||
|
const { service, saved } = createService();
|
||||||
|
await assert.rejects(
|
||||||
|
() => service.update("brand-1", { appSecret: "not-a-valid-secret!" }),
|
||||||
|
BadRequestException,
|
||||||
|
);
|
||||||
|
assert.equal(saved.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("changing AppID requires the matching AppSecret", async () => {
|
||||||
|
const appSecret = "0123456789abcdef0123456789abcdef";
|
||||||
|
const { service, saved } = createService({
|
||||||
|
appId: "wxold",
|
||||||
|
appSecretCredential: encryptMiniAppCredential(appSecret),
|
||||||
|
});
|
||||||
|
await assert.rejects(
|
||||||
|
() => service.update("brand-1", { appId: "wxnew" }),
|
||||||
|
/必须同时填写该 AppID 对应的 AppSecret/,
|
||||||
|
);
|
||||||
|
assert.equal(saved.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("leaving AppSecret empty preserves the stored credential", async () => {
|
||||||
|
const appSecret = "0123456789abcdef0123456789abcdef";
|
||||||
|
const storedCredential = encryptMiniAppCredential(appSecret);
|
||||||
|
const { service, saved } = createService({
|
||||||
|
appId: "wxtestsettings",
|
||||||
|
appSecretCredential: storedCredential,
|
||||||
|
});
|
||||||
|
await service.update("brand-1", { appId: "wxtestsettings" });
|
||||||
|
assert.equal(saved.length, 1);
|
||||||
|
assert.deepEqual(saved[0]?.appSecretCredential, storedCredential);
|
||||||
|
});
|
||||||
@@ -8,7 +8,7 @@ import { tmpdir } from "node:os";
|
|||||||
import { join, resolve } from "node:path";
|
import { join, resolve } from "node:path";
|
||||||
import { AdminMiniAppUploadService } from "../src/modules/admin/admin-miniapp-upload.service.js";
|
import { AdminMiniAppUploadService } from "../src/modules/admin/admin-miniapp-upload.service.js";
|
||||||
import type { AdminMiniAppReleaseService } from "../src/modules/admin/admin-miniapp-release.service.js";
|
import type { AdminMiniAppReleaseService } from "../src/modules/admin/admin-miniapp-release.service.js";
|
||||||
import { encryptMiniAppCredential } from "../src/modules/admin/miniapp-credential-crypto.js";
|
import { encryptMiniAppCredential } from "../src/miniapp-credential-crypto.js";
|
||||||
|
|
||||||
process.env.SESSION_SECRET = "upload-service-test-secret-1234567890";
|
process.env.SESSION_SECRET = "upload-service-test-secret-1234567890";
|
||||||
|
|
||||||
|
|||||||
@@ -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/,
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -11,7 +11,13 @@ import { getTemplatePackageManifest, getVisualTemplateManifest } from "@personal
|
|||||||
import { createApp } from "../dist/main.js";
|
import { createApp } from "../dist/main.js";
|
||||||
import { readIdentity, signIdentity } from "../dist/auth.js";
|
import { readIdentity, signIdentity } from "../dist/auth.js";
|
||||||
import { WechatAuthService } from "../dist/wechat-auth.js";
|
import { WechatAuthService } from "../dist/wechat-auth.js";
|
||||||
|
import { encryptMiniAppCredential } from "../dist/miniapp-credential-crypto.js";
|
||||||
import { AdminMiniAppReleaseService } from "../dist/modules/admin/admin-miniapp-release.service.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;
|
let app;
|
||||||
const prisma = new PrismaClient();
|
const prisma = new PrismaClient();
|
||||||
@@ -384,7 +390,7 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
|
|||||||
// 预览只允许使用平台当前已部署的精确 renderer 版本;复用 prepare 阶段导入的基线版本,
|
// 预览只允许使用平台当前已部署的精确 renderer 版本;复用 prepare 阶段导入的基线版本,
|
||||||
// 避免测试自造一个 renderer 尚未部署的新版本。
|
// 避免测试自造一个 renderer 尚未部署的新版本。
|
||||||
const baselineVersion = await prisma.templatePackageVersion.findFirstOrThrow({
|
const baselineVersion = await prisma.templatePackageVersion.findFirstOrThrow({
|
||||||
where: { packageKey: "atelier-solopreneur", version: "1.3.2", status: "published" },
|
where: { packageKey: "atelier-solopreneur", version: "1.3.3", status: "published" },
|
||||||
});
|
});
|
||||||
const versionId = baselineVersion.id;
|
const versionId = baselineVersion.id;
|
||||||
|
|
||||||
@@ -861,7 +867,7 @@ test("API restart recovers an expired persisted miniapp build attempt", async ()
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test("miniapp release settings never expose or persist plaintext private keys", async () => {
|
test("miniapp release settings never expose or persist plaintext credentials", async () => {
|
||||||
const login = await request("/admin/session/login", {
|
const login = await request("/admin/session/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||||
@@ -892,6 +898,13 @@ test("miniapp release settings never expose or persist plaintext private keys",
|
|||||||
payload: { appId: "wxtestsettings", apiBaseUrl: "http://wechat.example.com/api" },
|
payload: { appId: "wxtestsettings", apiBaseUrl: "http://wechat.example.com/api" },
|
||||||
});
|
});
|
||||||
assert.equal(rejected.statusCode, 400);
|
assert.equal(rejected.statusCode, 400);
|
||||||
|
const invalidSecret = await request("/admin/miniapp-releases/settings", {
|
||||||
|
method: "PATCH",
|
||||||
|
headers,
|
||||||
|
payload: { appSecret: "invalid secret!" },
|
||||||
|
});
|
||||||
|
assert.equal(invalidSecret.statusCode, 400);
|
||||||
|
const appSecret = "0123456789abcdef0123456789abcdef";
|
||||||
const saved = await request("/admin/miniapp-releases/settings", {
|
const saved = await request("/admin/miniapp-releases/settings", {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
headers,
|
headers,
|
||||||
@@ -899,6 +912,7 @@ test("miniapp release settings never expose or persist plaintext private keys",
|
|||||||
appId: "wxtestsettings",
|
appId: "wxtestsettings",
|
||||||
apiBaseUrl: "https://wechat.example.com/api/",
|
apiBaseUrl: "https://wechat.example.com/api/",
|
||||||
privateKey,
|
privateKey,
|
||||||
|
appSecret,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
assert.equal(saved.statusCode, 200);
|
assert.equal(saved.statusCode, 200);
|
||||||
@@ -907,17 +921,24 @@ test("miniapp release settings never expose or persist plaintext private keys",
|
|||||||
assert.equal(body.apiBaseUrl, "https://wechat.example.com/api");
|
assert.equal(body.apiBaseUrl, "https://wechat.example.com/api");
|
||||||
assert.equal(body.requestDomain, "wechat.example.com");
|
assert.equal(body.requestDomain, "wechat.example.com");
|
||||||
assert.equal(body.hasStoredCredentials, true);
|
assert.equal(body.hasStoredCredentials, true);
|
||||||
|
assert.equal(body.hasStoredAppSecret, true);
|
||||||
|
assert.equal(body.loginConfigured, true);
|
||||||
assert.equal(body.privateKey, undefined);
|
assert.equal(body.privateKey, undefined);
|
||||||
assert.equal(body.credential?.algorithm, "aes-256-gcm");
|
assert.equal(body.credential?.algorithm, "aes-256-gcm");
|
||||||
|
assert.equal("appSecretCredential" in body, false);
|
||||||
assert.ok(body.requestDomain === null || typeof body.requestDomain === "string");
|
assert.ok(body.requestDomain === null || typeof body.requestDomain === "string");
|
||||||
assert.ok(body.buildError === null || typeof body.buildError === "string");
|
assert.ok(body.buildError === null || typeof body.buildError === "string");
|
||||||
if (typeof body.requestDomain === "string") assert.ok(!body.requestDomain.includes("localhost"));
|
if (typeof body.requestDomain === "string") assert.ok(!body.requestDomain.includes("localhost"));
|
||||||
const brand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
|
const brand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
|
||||||
const credential = brand.miniAppSettings?.credential;
|
const credential = brand.miniAppSettings?.credential;
|
||||||
|
const appSecretCredential = brand.miniAppSettings?.appSecretCredential;
|
||||||
assert.ok(credential);
|
assert.ok(credential);
|
||||||
|
assert.ok(appSecretCredential);
|
||||||
assert.equal(brand.miniAppSettings.apiBaseUrl, "https://wechat.example.com/api");
|
assert.equal(brand.miniAppSettings.apiBaseUrl, "https://wechat.example.com/api");
|
||||||
assert.equal(typeof credential.ciphertext, "string");
|
assert.equal(typeof credential.ciphertext, "string");
|
||||||
|
assert.equal(typeof appSecretCredential.ciphertext, "string");
|
||||||
assert.ok(!JSON.stringify(brand.miniAppSettings).includes(privateKey));
|
assert.ok(!JSON.stringify(brand.miniAppSettings).includes(privateKey));
|
||||||
|
assert.ok(!JSON.stringify(brand.miniAppSettings).includes(appSecret));
|
||||||
const missing = await request("/admin/miniapp-releases/settings");
|
const missing = await request("/admin/miniapp-releases/settings");
|
||||||
assert.equal(missing.statusCode, 401);
|
assert.equal(missing.statusCode, 401);
|
||||||
const forbidden = await request("/admin/miniapp-releases/settings", {
|
const forbidden = await request("/admin/miniapp-releases/settings", {
|
||||||
@@ -1892,6 +1913,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 = {}) {
|
async function assertProtectedRouteBoundary(url, options = {}) {
|
||||||
const { method = "GET", payload, forbiddenRole = "customer", headers = {} } = options;
|
const { method = "GET", payload, forbiddenRole = "customer", headers = {} } = options;
|
||||||
const requestOptions = payload === undefined ? { method, headers } : { method, headers, payload };
|
const requestOptions = payload === undefined ? { method, headers } : { method, headers, payload };
|
||||||
@@ -2199,7 +2338,7 @@ test("brand creation options are owner-scoped", async () => {
|
|||||||
assert.equal(linjingScheme.isLatestForPackage, true);
|
assert.equal(linjingScheme.isLatestForPackage, true);
|
||||||
const atelierScheme = options.pageSchemes.find((scheme) => scheme.name.includes("工坊"));
|
const atelierScheme = options.pageSchemes.find((scheme) => scheme.name.includes("工坊"));
|
||||||
assert.ok(atelierScheme);
|
assert.ok(atelierScheme);
|
||||||
assert.equal(atelierScheme.version, "1.3.2");
|
assert.equal(atelierScheme.version, "1.3.3");
|
||||||
assert.deepEqual(atelierScheme.supportedBusinessTypes, ["personal"]);
|
assert.deepEqual(atelierScheme.supportedBusinessTypes, ["personal"]);
|
||||||
assert.equal(
|
assert.equal(
|
||||||
options.pageSchemes.some(
|
options.pageSchemes.some(
|
||||||
@@ -2227,7 +2366,7 @@ test("owner can create an isolated brand", async () => {
|
|||||||
const atelier = await prisma.templatePackageVersion.findFirstOrThrow({
|
const atelier = await prisma.templatePackageVersion.findFirstOrThrow({
|
||||||
where: {
|
where: {
|
||||||
packageKey: "atelier-solopreneur",
|
packageKey: "atelier-solopreneur",
|
||||||
version: "1.3.2",
|
version: "1.3.3",
|
||||||
status: "published",
|
status: "published",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -5087,6 +5226,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 () => {
|
test("admin can read and update brand and service configuration", async () => {
|
||||||
const login = await request("/admin/session/login", {
|
const login = await request("/admin/session/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -5409,13 +5613,30 @@ test("wechat login validates the request DTO before exchanging the code", async
|
|||||||
assert.equal(response.statusCode, 400);
|
assert.equal(response.statusCode, 400);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("wechat login creates a customer session for the requested brand", async () => {
|
test("wechat login creates a customer session using the requested brand credentials", async () => {
|
||||||
const doorsBrand = await prisma.brandProfile.findUnique({ where: { slug: "linjing-doors" } });
|
const doorsBrand = await prisma.brandProfile.findUnique({ where: { slug: "linjing-doors" } });
|
||||||
assert.ok(doorsBrand);
|
assert.ok(doorsBrand);
|
||||||
const sessionOpenid = `doors-login-${Date.now()}`;
|
const sessionOpenid = `doors-login-${Date.now()}`;
|
||||||
|
const appId = "wxintegrationdoors";
|
||||||
|
const appSecret = "0123456789abcdef0123456789abcdef";
|
||||||
|
const originalSettings = doorsBrand.miniAppSettings;
|
||||||
|
await prisma.brandProfile.update({
|
||||||
|
where: { id: doorsBrand.id },
|
||||||
|
data: {
|
||||||
|
miniAppSettings: {
|
||||||
|
...(originalSettings && typeof originalSettings === "object" ? originalSettings : {}),
|
||||||
|
appId,
|
||||||
|
appSecretCredential: encryptMiniAppCredential(appSecret),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
const wechatAuth = app.get(WechatAuthService);
|
const wechatAuth = app.get(WechatAuthService);
|
||||||
const originalExchangeCode = wechatAuth.exchangeCode;
|
const originalExchangeCode = wechatAuth.exchangeCode;
|
||||||
wechatAuth.exchangeCode = async () => ({ openid: sessionOpenid });
|
wechatAuth.exchangeCode = async (code, credentials) => {
|
||||||
|
assert.equal(code, "test-code");
|
||||||
|
assert.deepEqual(credentials, { appId, appSecret });
|
||||||
|
return { openid: sessionOpenid };
|
||||||
|
};
|
||||||
try {
|
try {
|
||||||
const response = await request("/customer/session/wechat?brandSlug=linjing-doors", {
|
const response = await request("/customer/session/wechat?brandSlug=linjing-doors", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -5433,6 +5654,49 @@ test("wechat login creates a customer session for the requested brand", async ()
|
|||||||
} finally {
|
} finally {
|
||||||
wechatAuth.exchangeCode = originalExchangeCode;
|
wechatAuth.exchangeCode = originalExchangeCode;
|
||||||
await prisma.customerUser.deleteMany({ where: { openid: sessionOpenid } });
|
await prisma.customerUser.deleteMany({ where: { openid: sessionOpenid } });
|
||||||
|
await prisma.brandProfile.update({
|
||||||
|
where: { id: doorsBrand.id },
|
||||||
|
data: { miniAppSettings: originalSettings },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("wechat login fails closed when a brand has no login AppSecret", async () => {
|
||||||
|
const brand = await prisma.brandProfile.findUnique({ where: { slug: "default-brand" } });
|
||||||
|
assert.ok(brand);
|
||||||
|
const originalSettings = brand.miniAppSettings;
|
||||||
|
const { appSecretCredential: _ignoredAppSecretCredential, ...settingsWithoutAppSecret } =
|
||||||
|
originalSettings && typeof originalSettings === "object" ? originalSettings : {};
|
||||||
|
await prisma.brandProfile.update({
|
||||||
|
where: { id: brand.id },
|
||||||
|
data: {
|
||||||
|
miniAppSettings: {
|
||||||
|
...settingsWithoutAppSecret,
|
||||||
|
appId: "wxmissingsessionsecret",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const wechatAuth = app.get(WechatAuthService);
|
||||||
|
const originalExchangeCode = wechatAuth.exchangeCode;
|
||||||
|
let exchanged = false;
|
||||||
|
wechatAuth.exchangeCode = async () => {
|
||||||
|
exchanged = true;
|
||||||
|
return { openid: `must-not-login-${Date.now()}` };
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const response = await request("/customer/session/wechat?brandSlug=default-brand", {
|
||||||
|
method: "POST",
|
||||||
|
payload: { code: "test-code" },
|
||||||
|
});
|
||||||
|
assert.equal(response.statusCode, 503);
|
||||||
|
assert.equal(JSON.parse(response.body).error.message, "该品牌尚未配置微信登录 AppSecret");
|
||||||
|
assert.equal(exchanged, false);
|
||||||
|
} finally {
|
||||||
|
wechatAuth.exchangeCode = originalExchangeCode;
|
||||||
|
await prisma.brandProfile.update({
|
||||||
|
where: { id: brand.id },
|
||||||
|
data: { miniAppSettings: originalSettings },
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -117,8 +117,8 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
|
|||||||
method: "GET",
|
method: "GET",
|
||||||
path: "/admin/miniapp-releases/settings",
|
path: "/admin/miniapp-releases/settings",
|
||||||
auth: "brand",
|
auth: "brand",
|
||||||
authorizationTest: "miniapp release settings never expose or persist plaintext private keys",
|
authorizationTest: "miniapp release settings never expose or persist plaintext credentials",
|
||||||
successTest: "miniapp release settings never expose or persist plaintext private keys",
|
successTest: "miniapp release settings never expose or persist plaintext credentials",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
method: "GET",
|
method: "GET",
|
||||||
@@ -378,8 +378,8 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
|
|||||||
path: "/admin/miniapp-releases/settings",
|
path: "/admin/miniapp-releases/settings",
|
||||||
auth: "roles",
|
auth: "roles",
|
||||||
roles: ["owner", "admin", "platform-admin"],
|
roles: ["owner", "admin", "platform-admin"],
|
||||||
authorizationTest: "miniapp release settings never expose or persist plaintext private keys",
|
authorizationTest: "miniapp release settings never expose or persist plaintext credentials",
|
||||||
successTest: "miniapp release settings never expose or persist plaintext private keys",
|
successTest: "miniapp release settings never expose or persist plaintext credentials",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
@@ -655,7 +655,14 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
|
|||||||
path: "/customer/session/wechat",
|
path: "/customer/session/wechat",
|
||||||
auth: "public",
|
auth: "public",
|
||||||
authorizationTest: null,
|
authorizationTest: null,
|
||||||
successTest: "wechat login creates a customer session for the requested brand",
|
successTest: "wechat login creates a customer session using the requested brand credentials",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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",
|
method: "PUT",
|
||||||
|
|||||||
@@ -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)
|
.filter((entry) => entry.isDirectory() && entry.name !== targetMigration)
|
||||||
.map((entry) => entry.name)
|
.map((entry) => entry.name)
|
||||||
.sort();
|
.sort();
|
||||||
assert.equal(migrationDirs.at(-1), "20261019100000_remove_brand_profile_defaults");
|
|
||||||
await admin.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
|
await admin.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
|
||||||
createdSchema = true;
|
createdSchema = true;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { test } from "node:test";
|
||||||
|
import { ServiceUnavailableException, UnauthorizedException } from "@nestjs/common";
|
||||||
|
import { encryptMiniAppCredential } from "../src/miniapp-credential-crypto.js";
|
||||||
|
import {
|
||||||
|
WechatAuthService,
|
||||||
|
resolveWechatLoginCredentials,
|
||||||
|
type WechatLoginCredentials,
|
||||||
|
} from "../src/wechat-auth.js";
|
||||||
|
|
||||||
|
process.env.SESSION_SECRET = "wechat-auth-test-secret-1234567890";
|
||||||
|
|
||||||
|
const credentials: WechatLoginCredentials = {
|
||||||
|
appId: "wxbranchappid",
|
||||||
|
appSecret: "0123456789abcdef0123456789abcdef",
|
||||||
|
};
|
||||||
|
|
||||||
|
test("resolveWechatLoginCredentials requires a brand AppID", () => {
|
||||||
|
assert.throws(
|
||||||
|
() => resolveWechatLoginCredentials({}),
|
||||||
|
(error: unknown) =>
|
||||||
|
error instanceof ServiceUnavailableException && error.message.includes("AppID"),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("resolveWechatLoginCredentials requires a brand AppSecret", () => {
|
||||||
|
assert.throws(
|
||||||
|
() => resolveWechatLoginCredentials({ appId: credentials.appId }),
|
||||||
|
(error: unknown) =>
|
||||||
|
error instanceof ServiceUnavailableException && error.message.includes("AppSecret"),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("resolveWechatLoginCredentials decrypts the brand AppSecret", () => {
|
||||||
|
const resolved = resolveWechatLoginCredentials({
|
||||||
|
appId: credentials.appId,
|
||||||
|
appSecretCredential: encryptMiniAppCredential(credentials.appSecret),
|
||||||
|
});
|
||||||
|
assert.deepEqual(resolved, credentials);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("resolveWechatLoginCredentials reports unusable encrypted credentials as unavailable", () => {
|
||||||
|
assert.throws(
|
||||||
|
() =>
|
||||||
|
resolveWechatLoginCredentials({
|
||||||
|
appId: credentials.appId,
|
||||||
|
appSecretCredential: { algorithm: "aes-256-gcm", ciphertext: "broken" },
|
||||||
|
}),
|
||||||
|
(error: unknown) =>
|
||||||
|
error instanceof ServiceUnavailableException && error.message.includes("凭据不可用"),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("exchangeCode uses the credentials supplied for the requested brand", async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
let requestedUrl = "";
|
||||||
|
globalThis.fetch = async (input: string | URL | Request) => {
|
||||||
|
requestedUrl =
|
||||||
|
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
openid: "openid-1",
|
||||||
|
session_key: "session-key-1",
|
||||||
|
unionid: "unionid-1",
|
||||||
|
}),
|
||||||
|
{ status: 200, headers: { "content-type": "application/json" } },
|
||||||
|
);
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const session = await new WechatAuthService().exchangeCode("login-code", credentials);
|
||||||
|
const url = new URL(requestedUrl);
|
||||||
|
assert.equal(url.origin + url.pathname, "https://api.weixin.qq.com/sns/jscode2session");
|
||||||
|
assert.equal(url.searchParams.get("appid"), credentials.appId);
|
||||||
|
assert.equal(url.searchParams.get("secret"), credentials.appSecret);
|
||||||
|
assert.equal(url.searchParams.get("js_code"), "login-code");
|
||||||
|
assert.equal(url.searchParams.get("grant_type"), "authorization_code");
|
||||||
|
assert.deepEqual(session, {
|
||||||
|
openid: "openid-1",
|
||||||
|
sessionKey: "session-key-1",
|
||||||
|
unionid: "unionid-1",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("exchangeCode surfaces WeChat rejection details without treating them as success", async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
globalThis.fetch = async () =>
|
||||||
|
new Response(JSON.stringify({ errcode: 40029, errmsg: "invalid code" }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { "content-type": "application/json" },
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await assert.rejects(
|
||||||
|
() => new WechatAuthService().exchangeCode("bad-code", credentials),
|
||||||
|
(error: unknown) =>
|
||||||
|
error instanceof UnauthorizedException && error.message === "invalid code",
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("exchangeCode reports network and HTTP failures as service unavailable", async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
try {
|
||||||
|
globalThis.fetch = async () => {
|
||||||
|
throw new Error("network down");
|
||||||
|
};
|
||||||
|
await assert.rejects(
|
||||||
|
() => new WechatAuthService().exchangeCode("login-code", credentials),
|
||||||
|
ServiceUnavailableException,
|
||||||
|
);
|
||||||
|
|
||||||
|
globalThis.fetch = async () => new Response("upstream error", { status: 502 });
|
||||||
|
await assert.rejects(
|
||||||
|
() => new WechatAuthService().exchangeCode("login-code", credentials),
|
||||||
|
ServiceUnavailableException,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("exchangeCode rejects empty codes and incomplete credentials", async () => {
|
||||||
|
const service = new WechatAuthService();
|
||||||
|
await assert.rejects(() => service.exchangeCode(" ", credentials), UnauthorizedException);
|
||||||
|
await assert.rejects(
|
||||||
|
() => service.exchangeCode("login-code", { appId: "", appSecret: "" }),
|
||||||
|
ServiceUnavailableException,
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -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)) {
|
for (const file of listFiles(output)) {
|
||||||
if (!/\.(js|json|wxml)$/.test(file)) continue;
|
if (!/\.(js|json|wxml)$/.test(file)) continue;
|
||||||
const source = fs.readFileSync(path.join(output, file), "utf8");
|
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 || {})) {
|
for (const [name, reference] of Object.entries(definition.usingComponents || {})) {
|
||||||
if (reference.startsWith("plugin://")) continue;
|
if (reference.startsWith("plugin://")) continue;
|
||||||
if (
|
// miniprogram_npm 由微信开发者工具生成且不入库;缺失时跳过 npm 组件解析检查。
|
||||||
reference.startsWith("/miniprogram_npm/") &&
|
const needsNpm =
|
||||||
!fs.existsSync(path.join(output, "miniprogram_npm"))
|
reference.startsWith("/miniprogram_npm/") ||
|
||||||
)
|
(!reference.startsWith("/") && !reference.startsWith("."));
|
||||||
continue;
|
if (needsNpm && !hasNpm) continue;
|
||||||
if (!resolveComponent(output, file, reference))
|
if (!resolveComponent(output, file, reference))
|
||||||
failures.push(`${file}: component ${name} cannot be resolved (${reference})`);
|
failures.push(`${file}: component ${name} cannot be resolved (${reference})`);
|
||||||
}
|
}
|
||||||
|
|||||||
+35
-1
@@ -61,7 +61,41 @@ pnpm --filter @personal-brand/taro test
|
|||||||
pnpm --filter @personal-brand/taro test:browser
|
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`。
|
||||||
|
|
||||||
## 回滚与切换
|
## 回滚与切换
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,8 @@
|
|||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"lint": "pnpm --workspace-root exec eslint apps/taro/src apps/taro/config \"packages/template-*/taro/**/*.{ts,tsx}\"",
|
"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": "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": {
|
"dependencies": {
|
||||||
"@personal-brand/types": "workspace:*",
|
"@personal-brand/types": "workspace:*",
|
||||||
|
|||||||
@@ -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 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 = {
|
const brand = {
|
||||||
id: "brand-fixture",
|
id: "brand-fixture",
|
||||||
slug: "preview-fixture",
|
slug: "preview-fixture",
|
||||||
@@ -712,6 +733,9 @@ test("林境模板支持首页和主理人区域点选", async ({ page }) => {
|
|||||||
title: "专业资历",
|
title: "专业资历",
|
||||||
summary: "建筑与门系统经验",
|
summary: "建筑与门系统经验",
|
||||||
content: "持续服务私宅项目",
|
content: "持续服务私宅项目",
|
||||||
|
sortOrder: 0,
|
||||||
|
isPublished: true,
|
||||||
|
coverUrl: null,
|
||||||
config: {
|
config: {
|
||||||
pillars: editorialPillars,
|
pillars: editorialPillars,
|
||||||
serviceFlow: editorialFlow,
|
serviceFlow: editorialFlow,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
import { test, expect, type Page, type Route } from "@playwright/test";
|
import { test, expect, type Page, type Route } from "@playwright/test";
|
||||||
|
|
||||||
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
|
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
|
||||||
@@ -17,12 +18,29 @@ test.afterEach(({ page }) => {
|
|||||||
interface MockOptions {
|
interface MockOptions {
|
||||||
/** 品牌成员列表的异常返回,用于触发整页渲染错误 */
|
/** 品牌成员列表的异常返回,用于触发整页渲染错误 */
|
||||||
memberships?: unknown;
|
memberships?: unknown;
|
||||||
|
/** 品牌名称的异常返回 */
|
||||||
|
brandName?: unknown;
|
||||||
|
/** 始终返回的异常信任内容,用于验证契约错误态 */
|
||||||
|
trustContent?: unknown;
|
||||||
/** 只在首次请求时返回的异常信任内容,重新加载后恢复 */
|
/** 只在首次请求时返回的异常信任内容,重新加载后恢复 */
|
||||||
trustContentOnce?: unknown;
|
trustContentOnce?: unknown;
|
||||||
|
/** 只在首次请求时返回的异常工作区数据,用于触发渲染异常 */
|
||||||
|
workspaceOnce?: unknown;
|
||||||
|
/** 上报接口返回的状态码 */
|
||||||
|
clientErrorStatus?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ClientErrorReport = {
|
||||||
|
errorId?: string;
|
||||||
|
message?: string;
|
||||||
|
route?: string;
|
||||||
|
componentStack?: string;
|
||||||
|
};
|
||||||
|
|
||||||
async function mockAdminApi(page: Page, options: MockOptions = {}) {
|
async function mockAdminApi(page: Page, options: MockOptions = {}) {
|
||||||
let servedTrustContent = false;
|
let servedTrustContent = false;
|
||||||
|
let servedWorkspace = false;
|
||||||
|
const clientErrors: ClientErrorReport[] = [];
|
||||||
|
|
||||||
await page.route("**/api/**", async (route: Route) => {
|
await page.route("**/api/**", async (route: Route) => {
|
||||||
const request = route.request();
|
const request = route.request();
|
||||||
@@ -44,7 +62,7 @@ async function mockAdminApi(page: Page, options: MockOptions = {}) {
|
|||||||
return route.fulfill({
|
return route.fulfill({
|
||||||
json: {
|
json: {
|
||||||
id: "brand-current",
|
id: "brand-current",
|
||||||
name: "独立工坊",
|
name: options.brandName ?? "独立工坊",
|
||||||
slug: "atelier-studio",
|
slug: "atelier-studio",
|
||||||
tagline: "把耐心做进作品",
|
tagline: "把耐心做进作品",
|
||||||
templateKey: "personal",
|
templateKey: "personal",
|
||||||
@@ -68,13 +86,35 @@ async function mockAdminApi(page: Page, options: MockOptions = {}) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (path === "/admin/config/trust-content" && method === "GET") {
|
if (path === "/admin/config/trust-content" && method === "GET") {
|
||||||
|
if (options.trustContent !== undefined) {
|
||||||
|
return route.fulfill({ json: options.trustContent });
|
||||||
|
}
|
||||||
if (!servedTrustContent && options.trustContentOnce !== undefined) {
|
if (!servedTrustContent && options.trustContentOnce !== undefined) {
|
||||||
servedTrustContent = true;
|
servedTrustContent = true;
|
||||||
return route.fulfill({ json: options.trustContentOnce });
|
return route.fulfill({ json: options.trustContentOnce });
|
||||||
}
|
}
|
||||||
return route.fulfill({ json: [] });
|
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 (path === "/admin/workspace") {
|
||||||
|
if (!servedWorkspace && options.workspaceOnce !== undefined) {
|
||||||
|
servedWorkspace = true;
|
||||||
|
return route.fulfill({ json: options.workspaceOnce });
|
||||||
|
}
|
||||||
return route.fulfill({
|
return route.fulfill({
|
||||||
json: {
|
json: {
|
||||||
brand: { id: "brand-current", name: "独立工坊" },
|
brand: { id: "brand-current", name: "独立工坊" },
|
||||||
@@ -90,31 +130,46 @@ async function mockAdminApi(page: Page, options: MockOptions = {}) {
|
|||||||
}
|
}
|
||||||
return route.fulfill({ json: [] });
|
return route.fulfill({ json: [] });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return { clientErrors };
|
||||||
}
|
}
|
||||||
|
|
||||||
test("品牌成员接口返回异常结构时显示整页错误而不是白屏", async ({ page }) => {
|
test("品牌成员与品牌名称异常时后台外壳仍可正常使用", async ({ page }) => {
|
||||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||||
await mockAdminApi(page, { memberships: [{}] });
|
await mockAdminApi(page, {
|
||||||
|
memberships: [{}, null, { brand: { id: "brand-current" } }],
|
||||||
|
brandName: { unexpected: true },
|
||||||
|
});
|
||||||
|
|
||||||
await page.goto(`${adminOrigin}/admin/publication`);
|
await page.goto(`${adminOrigin}/admin/publication`);
|
||||||
|
|
||||||
await expect(page.getByText("页面渲染出错")).toBeVisible();
|
await expect(page.getByRole("heading", { name: "内容与发布" })).toBeVisible();
|
||||||
await expect(page.getByText(/错误编号:admin-/)).toBeVisible();
|
await expect(page.getByText("当前品牌", { exact: true }).first()).toBeVisible();
|
||||||
await expect(page.getByRole("button", { name: "重新加载页面" })).toBeVisible();
|
await expect(page.getByText("页面渲染出错")).toBeHidden();
|
||||||
await expect(page.getByRole("link", { name: "返回概览" })).toBeVisible();
|
await expect(page.getByRole("button", { name: "退出登录" })).toBeVisible();
|
||||||
|
|
||||||
const bodyText = await page.locator("body").innerText();
|
|
||||||
expect(bodyText.trim().length).toBeGreaterThan(0);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("内容区渲染出错时保留导航,重新加载后恢复", async ({ page }) => {
|
test("内容区渲染出错时上报错误编号并保留导航,重新加载后恢复", async ({ page }) => {
|
||||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||||
await mockAdminApi(page, { trustContentOnce: [null] });
|
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 page.goto(`${adminOrigin}/admin/trust`);
|
||||||
|
|
||||||
await expect(page.getByText("页面渲染出错")).toBeVisible();
|
await expect(page.getByText("页面渲染出错")).toBeVisible();
|
||||||
await expect(page.getByText(/错误编号:admin-/)).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.getByRole("button", { name: "退出登录" })).toBeVisible();
|
||||||
@@ -128,3 +183,38 @@ test("内容区渲染出错时保留导航,重新加载后恢复", async ({ pa
|
|||||||
await expect(page.getByRole("heading", { name: "信任内容" })).toBeVisible();
|
await expect(page.getByRole("heading", { name: "信任内容" })).toBeVisible();
|
||||||
await expect(page.getByText("页面渲染出错")).toBeHidden();
|
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,370 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
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-atelier-solopreneur/template.json", "utf8"),
|
||||||
|
);
|
||||||
|
const brand = {
|
||||||
|
id: "atelier-brand-fixture",
|
||||||
|
slug: "atelier-preview-fixture",
|
||||||
|
name: "独立工坊",
|
||||||
|
templateKey: "personal",
|
||||||
|
tagline: "为独立创作者建立可信的个人品牌",
|
||||||
|
description: "品牌策略、视觉叙事与长期陪伴。",
|
||||||
|
avatarUrl: "",
|
||||||
|
coverUrl: "",
|
||||||
|
hours: "工作日 10:00-18:00",
|
||||||
|
address: "杭州",
|
||||||
|
deliveryNote: "",
|
||||||
|
contactPhone: "13800138000",
|
||||||
|
contactWechat: "atelier-example",
|
||||||
|
config: {
|
||||||
|
founder: "林予",
|
||||||
|
title: "品牌顾问",
|
||||||
|
atelier: {
|
||||||
|
identity: { status: "可预约", experience: "8 年经验", tags: [] },
|
||||||
|
badges: [{ title: "真实案例" }],
|
||||||
|
features: [],
|
||||||
|
audiences: [],
|
||||||
|
deliverables: [],
|
||||||
|
process: [],
|
||||||
|
proofs: [],
|
||||||
|
faqs: [],
|
||||||
|
},
|
||||||
|
visualPresentation: {
|
||||||
|
home: {
|
||||||
|
eyebrow: "PERSONAL BRAND",
|
||||||
|
title: "让专业被看见",
|
||||||
|
subtitle: "从定位到表达",
|
||||||
|
primaryAction: "预约沟通",
|
||||||
|
secondaryAction: "查看案例",
|
||||||
|
casesTitle: "试点案例",
|
||||||
|
casesSubtitle: "真实项目",
|
||||||
|
caseAction: "全部案例",
|
||||||
|
featuresTitle: "合作方式",
|
||||||
|
featuresEnglish: "METHOD",
|
||||||
|
audienceTitle: "适合谁",
|
||||||
|
audienceEnglish: "AUDIENCE",
|
||||||
|
ctaTitle: "一起梳理品牌",
|
||||||
|
ctaSubtitle: "先聊清楚目标",
|
||||||
|
ctaAction: "发起咨询",
|
||||||
|
},
|
||||||
|
detail: {
|
||||||
|
priceLabel: "合作方式",
|
||||||
|
spaceLabel: "适用场景",
|
||||||
|
backgroundTitle: "项目背景",
|
||||||
|
conceptTitle: "设计理念",
|
||||||
|
craftsTitle: "交付要点",
|
||||||
|
materialsTitle: "能力构成",
|
||||||
|
inquiryAction: "咨询这个案例",
|
||||||
|
inquiryHint: "提交后会在工作台跟进",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const adminOffering = {
|
||||||
|
id: "atelier-project-fixture",
|
||||||
|
kind: "service",
|
||||||
|
name: "山野茶品牌焕新",
|
||||||
|
summary: "为在地茶品牌建立清晰、可信的视觉与叙事体系。",
|
||||||
|
description: "案例详情说明",
|
||||||
|
priceText: "¥ 30,000 起",
|
||||||
|
coverUrl: "",
|
||||||
|
isEnabled: true,
|
||||||
|
sortOrder: 0,
|
||||||
|
config: {
|
||||||
|
categoryKey: "portfolio",
|
||||||
|
categoryLabel: "品牌视觉",
|
||||||
|
area: "杭州",
|
||||||
|
series: "品牌焕新",
|
||||||
|
spaceType: "线上与线下",
|
||||||
|
keywords: ["个人品牌", "视觉叙事"],
|
||||||
|
details: {
|
||||||
|
background: "品牌已有稳定客群,但表达缺少统一线索。",
|
||||||
|
designConcept: "以山野节气为线索,建立克制的视觉秩序。",
|
||||||
|
crafts: ["品牌定位梳理", "视觉系统交付", "落地陪跑"],
|
||||||
|
materialsList: [
|
||||||
|
{ name: "品牌策略", spec: "定位、叙事与内容框架" },
|
||||||
|
{ name: "视觉系统", spec: "标志、字体、色彩与版式" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
detailHero: "",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const runtimeWorkspace = {
|
||||||
|
schemaVersion: "1.0.0",
|
||||||
|
publication: { status: "published", version: 1 },
|
||||||
|
brand: {
|
||||||
|
...brand,
|
||||||
|
...brand.config,
|
||||||
|
visualPresentation: brand.config.visualPresentation,
|
||||||
|
atelier: brand.config.atelier,
|
||||||
|
},
|
||||||
|
visualTemplate: {
|
||||||
|
key: "atelier-solopreneur",
|
||||||
|
version: templateContent.version,
|
||||||
|
name: templateContent.displayName,
|
||||||
|
},
|
||||||
|
templateData: {},
|
||||||
|
navigation: { tabs: [] },
|
||||||
|
offerings: [
|
||||||
|
{
|
||||||
|
id: adminOffering.id,
|
||||||
|
name: adminOffering.name,
|
||||||
|
summary: adminOffering.summary,
|
||||||
|
priceText: adminOffering.priceText,
|
||||||
|
coverUrl: adminOffering.coverUrl,
|
||||||
|
enabled: true,
|
||||||
|
kind: adminOffering.kind,
|
||||||
|
priceAmount: null,
|
||||||
|
schemaKey: "personal-offering",
|
||||||
|
schemaVersion: "1.0.0",
|
||||||
|
presentation: {
|
||||||
|
categoryKey: adminOffering.config.categoryKey,
|
||||||
|
categoryLabel: adminOffering.config.categoryLabel,
|
||||||
|
heroImage: adminOffering.config.detailHero,
|
||||||
|
keywords: adminOffering.config.keywords,
|
||||||
|
media: [],
|
||||||
|
details: structuredClone(adminOffering.config.details),
|
||||||
|
area: adminOffering.config.area,
|
||||||
|
series: adminOffering.config.series,
|
||||||
|
spaceType: adminOffering.config.spaceType,
|
||||||
|
},
|
||||||
|
sections: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
inquiryForms: [],
|
||||||
|
trustItems: [],
|
||||||
|
trustPresentation: {},
|
||||||
|
capabilities: [],
|
||||||
|
theme: { colors: {} },
|
||||||
|
};
|
||||||
|
|
||||||
|
test("独立工坊业务编辑按真实 manifest 区块过滤字段", async ({ page }) => {
|
||||||
|
test.setTimeout(90000);
|
||||||
|
let savedBody: any;
|
||||||
|
await page.setViewportSize({ width: 1920, height: 1000 });
|
||||||
|
await page.route("**/api/**", async (route) => {
|
||||||
|
const url = new URL(route.request().url());
|
||||||
|
const path = url.pathname.replace(/^\/api/, "");
|
||||||
|
if (path === "/admin/session/current")
|
||||||
|
return route.fulfill({ status: 401, json: { error: { message: "未登录" } } });
|
||||||
|
if (path === "/admin/session/login")
|
||||||
|
return route.fulfill({
|
||||||
|
json: {
|
||||||
|
displayName: "测试管理员",
|
||||||
|
role: "owner",
|
||||||
|
mustChangePassword: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (path === "/admin/brands")
|
||||||
|
return route.fulfill({ json: [{ id: brand.id, role: "owner", brand }] });
|
||||||
|
if (path === "/admin/workspace/offerings")
|
||||||
|
return route.fulfill({
|
||||||
|
json: [{ ...adminOffering, config: structuredClone(adminOffering.config) }],
|
||||||
|
});
|
||||||
|
if (path === "/admin/workspace/forms") return route.fulfill({ json: [] });
|
||||||
|
if (
|
||||||
|
path === `/admin/workspace/offerings/${adminOffering.id}` &&
|
||||||
|
route.request().method() === "PATCH"
|
||||||
|
) {
|
||||||
|
savedBody = route.request().postDataJSON();
|
||||||
|
Object.assign(adminOffering, structuredClone(savedBody));
|
||||||
|
runtimeWorkspace.offerings[0] = {
|
||||||
|
...runtimeWorkspace.offerings[0],
|
||||||
|
name: adminOffering.name,
|
||||||
|
summary: adminOffering.summary,
|
||||||
|
priceText: adminOffering.priceText,
|
||||||
|
coverUrl: adminOffering.coverUrl,
|
||||||
|
presentation: {
|
||||||
|
...runtimeWorkspace.offerings[0].presentation,
|
||||||
|
...structuredClone(adminOffering.config),
|
||||||
|
details: structuredClone(adminOffering.config.details),
|
||||||
|
heroImage: adminOffering.config.detailHero,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return route.fulfill({ json: structuredClone(adminOffering) });
|
||||||
|
}
|
||||||
|
if (path === "/admin/workspace")
|
||||||
|
return route.fulfill({
|
||||||
|
json: {
|
||||||
|
brand,
|
||||||
|
installations: [],
|
||||||
|
fields: [],
|
||||||
|
offerings: [{ ...adminOffering, config: structuredClone(adminOffering.config) }],
|
||||||
|
forms: [],
|
||||||
|
templateContent,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (path === "/admin/config/brand") return route.fulfill({ json: brand });
|
||||||
|
if (path === "/admin/workspace/preview")
|
||||||
|
return route.fulfill({ json: structuredClone(runtimeWorkspace) });
|
||||||
|
if (path === "/public/workspace")
|
||||||
|
return route.fulfill({ json: structuredClone(runtimeWorkspace) });
|
||||||
|
return route.fulfill({ json: {} });
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.goto(`${adminOrigin}/admin/services`);
|
||||||
|
await page.getByLabel("账号").fill("admin");
|
||||||
|
await page.getByLabel("密码").fill("fixture-password");
|
||||||
|
await page.locator('button[type="submit"]').click();
|
||||||
|
await page.getByRole("button", { name: "编辑详情" }).click();
|
||||||
|
|
||||||
|
const editor = page.locator(".service-offering-editor");
|
||||||
|
const preview = editor.locator(".component-template-preview");
|
||||||
|
await expect(preview.locator(".atelier-page")).toBeVisible();
|
||||||
|
await expect(preview).toHaveAttribute(
|
||||||
|
"data-active-target",
|
||||||
|
"atelier-solopreneur.detail.projectHero",
|
||||||
|
);
|
||||||
|
await expect(preview).toHaveAttribute("data-active-record-id", adminOffering.id);
|
||||||
|
|
||||||
|
// 头图与标题:只出现名称、简介、封面和详情主图,不出现案例信息或正文区块字段。
|
||||||
|
await preview.locator(".atelier-title").click();
|
||||||
|
await expect(preview).toHaveAttribute(
|
||||||
|
"data-active-target",
|
||||||
|
"atelier-solopreneur.detail.projectHero",
|
||||||
|
);
|
||||||
|
await expect(page.getByText("正在编辑「案例头图与标题」", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByLabel("名称", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByLabel("一句话说明", { exact: true })).toBeVisible();
|
||||||
|
await expect(editor.locator('[data-presentation-binding="offering.coverUrl"]')).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
editor.locator('[data-presentation-binding="offering.config.detailHero"]'),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(page.getByLabel("价格展示", { exact: true })).toHaveCount(0);
|
||||||
|
await expect(page.getByLabel("项目背景", { exact: true })).toHaveCount(0);
|
||||||
|
await expect(page.getByLabel("交付要点", { exact: true })).toHaveCount(0);
|
||||||
|
|
||||||
|
// 案例信息:只出现报价与事实字段,标题、封面、详情主图消失。
|
||||||
|
await preview.locator(".atelier-detail-facts .atelier-detail-value").first().click();
|
||||||
|
await expect(preview).toHaveAttribute(
|
||||||
|
"data-active-target",
|
||||||
|
"atelier-solopreneur.detail.projectFacts",
|
||||||
|
);
|
||||||
|
await expect(page.getByText("正在编辑「案例信息」", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByLabel("价格展示", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByLabel("案例类别", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByLabel("项目地点", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByLabel("方案名称", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByLabel("适用场景", { exact: true })).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
editor.locator('[data-presentation-binding="offering.config.keywords"]'),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(page.getByLabel("名称", { exact: true })).toHaveCount(0);
|
||||||
|
await expect(page.getByLabel("一句话说明", { exact: true })).toHaveCount(0);
|
||||||
|
await expect(page.getByLabel("详情主图", { exact: true })).toHaveCount(0);
|
||||||
|
|
||||||
|
// 背景、理念、交付要点、能力构成分别只保留一个区块字段。
|
||||||
|
await preview.getByText("品牌已有稳定客群,但表达缺少统一线索。").click();
|
||||||
|
await expect(preview).toHaveAttribute(
|
||||||
|
"data-active-target",
|
||||||
|
"atelier-solopreneur.detail.projectBackground",
|
||||||
|
);
|
||||||
|
await expect(
|
||||||
|
editor.locator('[data-presentation-binding="offering.config.details.background"]'),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
editor.locator('[data-presentation-binding="offering.config.details.designConcept"]'),
|
||||||
|
).toHaveCount(0);
|
||||||
|
await expect(page.getByLabel("价格展示", { exact: true })).toHaveCount(0);
|
||||||
|
|
||||||
|
await preview.getByText("以山野节气为线索,建立克制的视觉秩序。").click();
|
||||||
|
await expect(preview).toHaveAttribute(
|
||||||
|
"data-active-target",
|
||||||
|
"atelier-solopreneur.detail.projectConcept",
|
||||||
|
);
|
||||||
|
await expect(
|
||||||
|
editor.locator('[data-presentation-binding="offering.config.details.designConcept"]'),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
editor.locator('[data-presentation-binding="offering.config.details.background"]'),
|
||||||
|
).toHaveCount(0);
|
||||||
|
|
||||||
|
await preview.getByText("品牌定位梳理").click();
|
||||||
|
await expect(preview).toHaveAttribute(
|
||||||
|
"data-active-target",
|
||||||
|
"atelier-solopreneur.detail.projectCrafts",
|
||||||
|
);
|
||||||
|
await expect(
|
||||||
|
editor.locator('[data-presentation-binding="offering.config.details.crafts"]'),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
editor.locator('[data-presentation-binding="offering.config.details.materialsList"]'),
|
||||||
|
).toHaveCount(0);
|
||||||
|
|
||||||
|
await preview.getByText("品牌策略 定位、叙事与内容框架", { exact: true }).click();
|
||||||
|
await expect(preview).toHaveAttribute(
|
||||||
|
"data-active-target",
|
||||||
|
"atelier-solopreneur.detail.projectMaterials",
|
||||||
|
);
|
||||||
|
await expect(
|
||||||
|
editor.locator('[data-presentation-binding="offering.config.details.materialsList"]'),
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
editor.locator('[data-presentation-binding="offering.config.details.crafts"]'),
|
||||||
|
).toHaveCount(0);
|
||||||
|
|
||||||
|
await preview.getByText("品牌已有稳定客群,但表达缺少统一线索。").click();
|
||||||
|
await page.getByLabel("项目背景", { exact: true }).fill("弹窗里更新后的项目背景");
|
||||||
|
await expect(preview.getByText("弹窗里更新后的项目背景", { exact: true })).toBeVisible();
|
||||||
|
|
||||||
|
// “查看全部字段”恢复完整表单。
|
||||||
|
await page.getByRole("button", { name: "查看全部字段" }).click();
|
||||||
|
await expect(page.getByLabel("名称", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByLabel("价格展示", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByLabel("项目背景", { exact: true })).toBeVisible();
|
||||||
|
|
||||||
|
// 列表卡片来自真实首页案例区域;右侧只显示名称、简介和封面。
|
||||||
|
await page.getByText("列表卡片", { exact: true }).click();
|
||||||
|
await expect(preview).toHaveAttribute("data-active-target", "atelier.home.case");
|
||||||
|
await expect(preview).toHaveAttribute("data-active-record-id", adminOffering.id);
|
||||||
|
await expect(editor.locator(".service-offering-editor__view")).toContainText("列表卡片");
|
||||||
|
await expect(preview.locator(".atelier-case")).toContainText(adminOffering.name);
|
||||||
|
await preview.locator(".atelier-case .atelier-card-title").click();
|
||||||
|
await expect(page.getByText("正在编辑「试点案例卡片」", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByLabel("名称", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByLabel("一句话说明", { exact: true })).toBeVisible();
|
||||||
|
await expect(editor.locator('[data-presentation-binding="offering.coverUrl"]')).toBeVisible();
|
||||||
|
await expect(page.getByLabel("价格展示", { exact: true })).toHaveCount(0);
|
||||||
|
await expect(
|
||||||
|
editor.locator('[data-presentation-binding="offering.config.detailHero"]'),
|
||||||
|
).toHaveCount(0);
|
||||||
|
await expect(page.getByLabel("项目背景", { exact: true })).toHaveCount(0);
|
||||||
|
|
||||||
|
await page
|
||||||
|
.locator(".ant-modal-footer")
|
||||||
|
.getByRole("button", { name: "确 定", exact: true })
|
||||||
|
.click();
|
||||||
|
await expect(page.getByText("业务提供项已保存")).toBeVisible();
|
||||||
|
expect(savedBody.name).toBe(adminOffering.name);
|
||||||
|
expect(savedBody.config.details.background).toBe("弹窗里更新后的项目背景");
|
||||||
|
expect(savedBody.config.details.designConcept).toBe("以山野节气为线索,建立克制的视觉秩序。");
|
||||||
|
expect(savedBody.config.details.crafts).toEqual(["品牌定位梳理", "视觉系统交付", "落地陪跑"]);
|
||||||
|
expect(savedBody.config.details.materialsList).toEqual([
|
||||||
|
{ name: "品牌策略", spec: "定位、叙事与内容框架" },
|
||||||
|
{ name: "视觉系统", spec: "标志、字体、色彩与版式" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
@@ -10,10 +10,10 @@ const businesses = [
|
|||||||
|
|
||||||
const pageSchemes = [
|
const pageSchemes = [
|
||||||
{
|
{
|
||||||
templatePackageVersionId: "atelier-v132",
|
templatePackageVersionId: "atelier-v133",
|
||||||
name: "独立创作者画册",
|
name: "独立创作者画册",
|
||||||
description: "个人品牌页面方案",
|
description: "个人品牌页面方案",
|
||||||
version: "1.3.2",
|
version: "1.3.3",
|
||||||
supportedBusinessTypes: ["personal"],
|
supportedBusinessTypes: ["personal"],
|
||||||
isLatestForPackage: true,
|
isLatestForPackage: true,
|
||||||
},
|
},
|
||||||
@@ -217,7 +217,7 @@ test("创建品牌成功后进入新品牌工作区", async ({ page }) => {
|
|||||||
|
|
||||||
await page.goto(`${adminOrigin}/admin/brands/new`);
|
await page.goto(`${adminOrigin}/admin/brands/new`);
|
||||||
await page.getByText("个人品牌", { exact: true }).click();
|
await page.getByText("个人品牌", { exact: true }).click();
|
||||||
await page.getByText(/最新版 1\.3\.2/).click();
|
await page.getByText(/最新版 1\.3\.3/).click();
|
||||||
await page.getByLabel("品牌名称").fill("新的独立品牌");
|
await page.getByLabel("品牌名称").fill("新的独立品牌");
|
||||||
await page.getByLabel("小程序地址标识").fill("new-atelier");
|
await page.getByLabel("小程序地址标识").fill("new-atelier");
|
||||||
await page.getByRole("button", { name: "创建并进入品牌" }).click();
|
await page.getByRole("button", { name: "创建并进入品牌" }).click();
|
||||||
@@ -228,7 +228,7 @@ test("创建品牌成功后进入新品牌工作区", async ({ page }) => {
|
|||||||
name: "新的独立品牌",
|
name: "新的独立品牌",
|
||||||
slug: "new-atelier",
|
slug: "new-atelier",
|
||||||
businessType: "personal",
|
businessType: "personal",
|
||||||
templatePackageVersionId: "atelier-v132",
|
templatePackageVersionId: "atelier-v133",
|
||||||
});
|
});
|
||||||
await page.waitForURL("**/admin/overview");
|
await page.waitForURL("**/admin/overview");
|
||||||
await expect(page.getByRole("heading", { name: "品牌概览" })).toBeVisible();
|
await expect(page.getByRole("heading", { name: "品牌概览" })).toBeVisible();
|
||||||
@@ -254,7 +254,7 @@ test("创建品牌按业务类型过滤页面方案,失败后保留输入", as
|
|||||||
|
|
||||||
await page.getByText("个人品牌", { exact: true }).click();
|
await page.getByText("个人品牌", { exact: true }).click();
|
||||||
await expect(page.getByRole("button", { name: "创建并进入品牌" })).toBeDisabled();
|
await expect(page.getByRole("button", { name: "创建并进入品牌" })).toBeDisabled();
|
||||||
await page.getByText(/最新版 1\.3\.2/).click();
|
await page.getByText(/最新版 1\.3\.3/).click();
|
||||||
|
|
||||||
await page.getByLabel("品牌名称").fill("测试独立品牌");
|
await page.getByLabel("品牌名称").fill("测试独立品牌");
|
||||||
await page.getByLabel("小程序地址标识").fill("test-atelier");
|
await page.getByLabel("小程序地址标识").fill("test-atelier");
|
||||||
@@ -268,7 +268,7 @@ test("创建品牌按业务类型过滤页面方案,失败后保留输入", as
|
|||||||
name: "测试独立品牌",
|
name: "测试独立品牌",
|
||||||
slug: "test-atelier",
|
slug: "test-atelier",
|
||||||
businessType: "personal",
|
businessType: "personal",
|
||||||
templatePackageVersionId: "atelier-v132",
|
templatePackageVersionId: "atelier-v133",
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -180,6 +180,8 @@ async function mockPublicationApi(page: Page, options: MockOptions = {}) {
|
|||||||
appId: "wx0000000000000000",
|
appId: "wx0000000000000000",
|
||||||
apiBaseUrl: "https://wechat.app.que01.top/api",
|
apiBaseUrl: "https://wechat.app.que01.top/api",
|
||||||
hasStoredCredentials: false,
|
hasStoredCredentials: false,
|
||||||
|
hasStoredAppSecret: false,
|
||||||
|
loginConfigured: false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -268,7 +270,7 @@ test("恢复历史版本会提交版本号并刷新发布记录", async ({ page
|
|||||||
await expect(page.getByText("历史版本已重新发布")).toBeVisible();
|
await expect(page.getByText("历史版本已重新发布")).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("小程序配置页回填服务端设置并仅提交新私钥", async ({ page }) => {
|
test("小程序配置页回填服务端设置并提交新的登录凭据与私钥", async ({ page }) => {
|
||||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||||
const bodies: Record<string, unknown>[] = [];
|
const bodies: Record<string, unknown>[] = [];
|
||||||
await mockPublicationApi(page, {});
|
await mockPublicationApi(page, {});
|
||||||
@@ -281,6 +283,8 @@ test("小程序配置页回填服务端设置并仅提交新私钥", async ({ pa
|
|||||||
appId: body.appId,
|
appId: body.appId,
|
||||||
apiBaseUrl: body.apiBaseUrl,
|
apiBaseUrl: body.apiBaseUrl,
|
||||||
hasStoredCredentials: true,
|
hasStoredCredentials: true,
|
||||||
|
hasStoredAppSecret: true,
|
||||||
|
loginConfigured: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -292,10 +296,12 @@ test("小程序配置页回填服务端设置并仅提交新私钥", async ({ pa
|
|||||||
await expect(page.getByLabel("微信 AppID")).toHaveValue("wx0000000000000000");
|
await expect(page.getByLabel("微信 AppID")).toHaveValue("wx0000000000000000");
|
||||||
await expect(page.getByLabel("小程序请求地址")).toHaveValue("https://wechat.app.que01.top/api");
|
await expect(page.getByLabel("小程序请求地址")).toHaveValue("https://wechat.app.que01.top/api");
|
||||||
|
|
||||||
|
const appSecret = "0123456789abcdef0123456789abcdef";
|
||||||
|
await page.getByLabel("微信登录 AppSecret").fill(appSecret);
|
||||||
await page
|
await page
|
||||||
.getByLabel("上传私钥")
|
.getByLabel("上传私钥")
|
||||||
.fill("-----BEGIN PRIVATE KEY-----\nKEY\n-----END PRIVATE KEY-----");
|
.fill("-----BEGIN PRIVATE KEY-----\nKEY\n-----END PRIVATE KEY-----");
|
||||||
await page.getByRole("button", { name: "保存上传配置" }).click();
|
await page.getByRole("button", { name: "保存小程序配置" }).click();
|
||||||
|
|
||||||
await expect
|
await expect
|
||||||
.poll(() => bodies)
|
.poll(() => bodies)
|
||||||
@@ -303,8 +309,9 @@ test("小程序配置页回填服务端设置并仅提交新私钥", async ({ pa
|
|||||||
{
|
{
|
||||||
appId: "wx0000000000000000",
|
appId: "wx0000000000000000",
|
||||||
apiBaseUrl: "https://wechat.app.que01.top/api",
|
apiBaseUrl: "https://wechat.app.que01.top/api",
|
||||||
|
appSecret,
|
||||||
privateKey: "-----BEGIN PRIVATE KEY-----\nKEY\n-----END PRIVATE KEY-----",
|
privateKey: "-----BEGIN PRIVATE KEY-----\nKEY\n-----END PRIVATE KEY-----",
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
await expect(page.getByText("小程序上传配置已保存")).toBeVisible();
|
await expect(page.getByText("小程序配置已保存")).toBeVisible();
|
||||||
});
|
});
|
||||||
@@ -1,7 +1,28 @@
|
|||||||
import fs from "node:fs";
|
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 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(
|
const templateContent = JSON.parse(
|
||||||
fs.readFileSync("../../packages/template-acheng-campus-food/template.json", "utf8"),
|
fs.readFileSync("../../packages/template-acheng-campus-food/template.json", "utf8"),
|
||||||
);
|
);
|
||||||
@@ -168,6 +189,19 @@ test("业务编辑弹窗预览列表与详情详情同一份内容", async ({ pa
|
|||||||
await expect(editor.locator(".service-offering-editor__view")).toContainText("详情内容");
|
await expect(editor.locator(".service-offering-editor__view")).toContainText("详情内容");
|
||||||
await expect(page.getByText("正在核对详情展示")).toBeVisible();
|
await expect(page.getByText("正在核对详情展示")).toBeVisible();
|
||||||
|
|
||||||
|
await preview.locator(".food-detail .hero-copy").click();
|
||||||
|
await expect(preview).toHaveAttribute(
|
||||||
|
"data-active-target",
|
||||||
|
"acheng-campus-food.detail.dishDetail",
|
||||||
|
);
|
||||||
|
await expect(page.getByText("餐品与服务详情对应字段", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByText("正在编辑「餐品与服务详情」", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByLabel("名称", { exact: true })).toHaveCount(0);
|
||||||
|
await expect(page.getByLabel("类型", { exact: true })).toHaveCount(0);
|
||||||
|
await expect(
|
||||||
|
editor.locator('[data-presentation-binding="offering.config.details.background"]'),
|
||||||
|
).toHaveClass(/is-preview-active/);
|
||||||
|
|
||||||
await page.getByLabel("餐品介绍").fill("弹窗编辑后的餐品介绍");
|
await page.getByLabel("餐品介绍").fill("弹窗编辑后的餐品介绍");
|
||||||
await expect(preview.locator(".food-detail .body")).toContainText("弹窗编辑后的餐品介绍");
|
await expect(preview.locator(".food-detail .body")).toContainText("弹窗编辑后的餐品介绍");
|
||||||
|
|
||||||
@@ -176,6 +210,32 @@ test("业务编辑弹窗预览列表与详情详情同一份内容", async ({ pa
|
|||||||
await expect(preview).toHaveAttribute("data-active-target", "acheng-campus-food.offerings.item");
|
await expect(preview).toHaveAttribute("data-active-target", "acheng-campus-food.offerings.item");
|
||||||
await expect(page.getByText("正在核对列表展示")).toBeVisible();
|
await expect(page.getByText("正在核对列表展示")).toBeVisible();
|
||||||
|
|
||||||
|
await preview.locator(".offering-card .dish-name").click();
|
||||||
|
await expect(page.getByText("业务卡片对应字段", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByText("正在编辑「业务卡片」", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByLabel("类型", { exact: true })).toHaveCount(0);
|
||||||
|
await expect(page.getByLabel("展示顺序", { exact: true })).toHaveCount(0);
|
||||||
|
await expect(editor.locator('[data-presentation-binding="offering.name"]')).toHaveClass(
|
||||||
|
/is-preview-active/,
|
||||||
|
);
|
||||||
|
await expect(
|
||||||
|
editor.locator('[data-presentation-binding="offering.config.details.background"]'),
|
||||||
|
).toHaveCount(0);
|
||||||
|
|
||||||
|
await preview.locator(".menu-head").click();
|
||||||
|
await expect(preview).toHaveAttribute("data-active-target", "acheng-campus-food.offerings.menu");
|
||||||
|
await expect(page.getByText("「菜单页说明」属于页面通用内容", { exact: true })).toBeVisible();
|
||||||
|
await expect(editor.locator('[data-presentation-binding="offering.name"]')).toHaveCount(0);
|
||||||
|
await expect(editor.getByText("详情主图", { exact: true })).toHaveCount(0);
|
||||||
|
await expect(page.getByLabel("名称", { exact: true })).toHaveCount(0);
|
||||||
|
await expect(page.getByLabel("类型", { exact: true })).toHaveCount(0);
|
||||||
|
|
||||||
|
await page.getByRole("button", { name: "查看全部字段" }).click();
|
||||||
|
await expect(page.getByLabel("名称", { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByLabel("类型", { exact: true })).toBeVisible();
|
||||||
|
|
||||||
|
await preview.locator(".offering-card .dish-name").click();
|
||||||
|
await expect(page.getByText("业务卡片对应字段", { exact: true })).toBeVisible();
|
||||||
await page.getByLabel("名称", { exact: true }).fill("列表实时预览餐品");
|
await page.getByLabel("名称", { exact: true }).fill("列表实时预览餐品");
|
||||||
await expect(preview.locator(".offering-card")).toContainText("列表实时预览餐品");
|
await expect(preview.locator(".offering-card")).toContainText("列表实时预览餐品");
|
||||||
|
|
||||||
@@ -193,9 +253,14 @@ test("业务编辑弹窗预览列表与详情详情同一份内容", async ({ pa
|
|||||||
await page.getByRole("button", { name: "编辑详情" }).first().click();
|
await page.getByRole("button", { name: "编辑详情" }).first().click();
|
||||||
await expect(page.locator(".component-template-preview")).toBeVisible();
|
await expect(page.locator(".component-template-preview")).toBeVisible();
|
||||||
|
|
||||||
|
// 弹窗默认定位在详情页;跨入口编辑列表卡片前先切到列表并点选卡片,
|
||||||
|
// 确保“在小程序页面编辑”携带的是首页列表区域而不是详情区域。
|
||||||
|
await page.getByText("列表卡片", { exact: true }).click();
|
||||||
|
await preview.locator(".offering-card .dish-name").click();
|
||||||
|
await expect(page.getByText("业务卡片对应字段", { exact: true })).toBeVisible();
|
||||||
await page.getByRole("button", { name: "在小程序页面编辑" }).click();
|
await page.getByRole("button", { name: "在小程序页面编辑" }).click();
|
||||||
await expect(page.getByText("页面预览", { exact: true })).toBeVisible({ timeout: 15000 });
|
await expect(page.getByText("页面预览", { exact: true })).toBeVisible({ timeout: 15000 });
|
||||||
await page.getByText("首页业务卡片", { exact: true }).click();
|
// 跳转时已按 targetKey 自动选中列表卡片区域,无需再手动点选页面区域。
|
||||||
await expect(
|
await expect(
|
||||||
page.getByText("正在编辑业务提供项:列表实时预览餐品", { exact: true }),
|
page.getByText("正在编辑业务提供项:列表实时预览餐品", { exact: true }),
|
||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
@@ -214,7 +279,7 @@ test("业务编辑弹窗预览列表与详情详情同一份内容", async ({ pa
|
|||||||
.locator(".ant-modal-footer")
|
.locator(".ant-modal-footer")
|
||||||
.getByRole("button", { name: "确 定", exact: true })
|
.getByRole("button", { name: "确 定", exact: true })
|
||||||
.click();
|
.click();
|
||||||
await expect(page.getByText("业务提供项已保存")).toBeVisible();
|
await expect(page.getByText("业务提供项已保存").last()).toBeVisible();
|
||||||
expect(savedBody.name).toBe("小程序页保存后的餐品");
|
expect(savedBody.name).toBe("小程序页保存后的餐品");
|
||||||
expect(savedBody.summary).toBe("跨入口保存后的业务简介");
|
expect(savedBody.summary).toBe("跨入口保存后的业务简介");
|
||||||
expect(savedBody.config.details.background).toBe("弹窗编辑后的餐品介绍");
|
expect(savedBody.config.details.background).toBe("弹窗编辑后的餐品介绍");
|
||||||
|
|||||||
@@ -11,13 +11,17 @@ const manifest = JSON.parse(
|
|||||||
);
|
);
|
||||||
const version = {
|
const version = {
|
||||||
id: "preview-browser-version",
|
id: "preview-browser-version",
|
||||||
|
templatePackageId: "preview-browser-package",
|
||||||
packageKey: manifest.packageKey,
|
packageKey: manifest.packageKey,
|
||||||
version: manifest.version,
|
version: manifest.version,
|
||||||
displayName: manifest.displayName,
|
displayName: manifest.displayName,
|
||||||
status: "imported",
|
status: "imported",
|
||||||
contentChecksum: "fixture-checksum",
|
contentChecksum: "fixture-checksum",
|
||||||
|
archiveChecksum: "fixture-archive-checksum",
|
||||||
|
importedAt: "2026-10-21T00:00:00.000Z",
|
||||||
|
updatedAt: "2026-10-21T00:00:00.000Z",
|
||||||
manifestSnapshot: manifest,
|
manifestSnapshot: manifest,
|
||||||
importedBy: { displayName: "模板管理员" },
|
importedBy: { id: "template-admin", username: "admin", displayName: "模板管理员" },
|
||||||
validationReport: {},
|
validationReport: {},
|
||||||
manifestSummary: { supportedIndustryTemplates: manifest.supportedIndustryTemplates },
|
manifestSummary: { supportedIndustryTemplates: manifest.supportedIndustryTemplates },
|
||||||
};
|
};
|
||||||
@@ -103,6 +107,16 @@ test("模板管理可重试预览,并切换我的、详情和禁止提交的
|
|||||||
}
|
}
|
||||||
if (url.pathname.endsWith("/admin/templates"))
|
if (url.pathname.endsWith("/admin/templates"))
|
||||||
return route.fulfill({ json: { items: [version], page: 1, pageSize: 20, total: 1 } });
|
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: [] });
|
if (url.pathname.endsWith("/admin/brands")) return route.fulfill({ json: [] });
|
||||||
return route.fulfill({ json: { name: "测试工作区" } });
|
return route.fulfill({ json: { name: "测试工作区" } });
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -18,12 +18,15 @@ type PackedChecksums = {
|
|||||||
|
|
||||||
type PreviewVersion = {
|
type PreviewVersion = {
|
||||||
id: string;
|
id: string;
|
||||||
|
templatePackageId: string;
|
||||||
packageKey: string;
|
packageKey: string;
|
||||||
version: string;
|
version: string;
|
||||||
displayName: string;
|
displayName: string;
|
||||||
status: "imported";
|
status: "imported";
|
||||||
manifestSnapshot: PackedManifest;
|
manifestSnapshot: PackedManifest;
|
||||||
importedBy: { displayName: string };
|
importedBy: { id: string; username: string; displayName: string };
|
||||||
|
importedAt: string;
|
||||||
|
updatedAt: string;
|
||||||
validationReport: Record<string, unknown>;
|
validationReport: Record<string, unknown>;
|
||||||
manifestSummary: { supportedIndustryTemplates: string[] };
|
manifestSummary: { supportedIndustryTemplates: string[] };
|
||||||
artifactPath: string;
|
artifactPath: string;
|
||||||
@@ -88,12 +91,15 @@ async function buildPreviewFixture(mediaCase: MediaCase) {
|
|||||||
const archivePath = path.join(temporary, archive);
|
const archivePath = path.join(temporary, archive);
|
||||||
const version: PreviewVersion = {
|
const version: PreviewVersion = {
|
||||||
id: `preview-media-${mediaCase.packageKey}-${mediaCase.industry}`,
|
id: `preview-media-${mediaCase.packageKey}-${mediaCase.industry}`,
|
||||||
|
templatePackageId: `preview-media-package-${mediaCase.packageKey}`,
|
||||||
packageKey: manifest.packageKey,
|
packageKey: manifest.packageKey,
|
||||||
version: manifest.version,
|
version: manifest.version,
|
||||||
displayName: manifest.displayName,
|
displayName: manifest.displayName,
|
||||||
status: "imported",
|
status: "imported",
|
||||||
manifestSnapshot: manifest,
|
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: {},
|
validationReport: {},
|
||||||
manifestSummary: { supportedIndustryTemplates: manifest.supportedIndustryTemplates },
|
manifestSummary: { supportedIndustryTemplates: manifest.supportedIndustryTemplates },
|
||||||
artifactPath: archivePath,
|
artifactPath: archivePath,
|
||||||
@@ -216,6 +222,16 @@ test("导入包预览矩阵展示身份、资源和完整媒体槽位", async ({
|
|||||||
total: 1,
|
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: [] });
|
if (url.pathname.endsWith("/admin/brands")) return route.fulfill({ json: [] });
|
||||||
return route.fulfill({ json: { name: "测试工作区" } });
|
return route.fulfill({ json: { name: "测试工作区" } });
|
||||||
});
|
});
|
||||||
|
|||||||
+6
-1
@@ -18,7 +18,12 @@ RUN pnpm --filter @personal-brand/config build
|
|||||||
RUN pnpm --filter @personal-brand/types build
|
RUN pnpm --filter @personal-brand/types build
|
||||||
RUN pnpm --filter @personal-brand/validation build
|
RUN pnpm --filter @personal-brand/validation build
|
||||||
RUN pnpm --filter @personal-brand/api-client build
|
RUN pnpm --filter @personal-brand/api-client build
|
||||||
RUN pnpm add -w @tarojs/binding-linux-arm64-gnu@4.3.0
|
ARG TARGETARCH
|
||||||
|
RUN case "${TARGETARCH:-$(uname -m)}" in \
|
||||||
|
arm64 | aarch64) pnpm add -w @tarojs/binding-linux-arm64-gnu@4.3.0 ;; \
|
||||||
|
amd64 | x86_64) pnpm add -w @tarojs/binding-linux-x64-gnu@4.3.0 ;; \
|
||||||
|
*) echo "unsupported TARGETARCH: ${TARGETARCH:-$(uname -m)}" >&2; exit 1 ;; \
|
||||||
|
esac
|
||||||
RUN pnpm build:admin:preview
|
RUN pnpm build:admin:preview
|
||||||
|
|
||||||
FROM alpine:latest AS runtime
|
FROM alpine:latest AS runtime
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
{
|
{
|
||||||
"packageKey": "atelier-solopreneur",
|
"packageKey": "atelier-solopreneur",
|
||||||
"packageName": "@personal-brand/template-atelier-solopreneur",
|
"packageName": "@personal-brand/template-atelier-solopreneur",
|
||||||
"version": "1.3.2"
|
"version": "1.3.3"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { mkdir, rm } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import { spawnSync } from "node:child_process";
|
||||||
|
import {
|
||||||
|
backupPostgresDatabase,
|
||||||
|
pruneBackups,
|
||||||
|
scheduledBackupName,
|
||||||
|
verifyPostgresBackup,
|
||||||
|
} from "./database-backup.mjs";
|
||||||
|
|
||||||
|
const root = process.env.DEPLOY_ROOT;
|
||||||
|
if (!root || !path.isAbsolute(root)) throw new Error("DEPLOY_ROOT must be absolute");
|
||||||
|
process.loadEnvFile(path.join(root, "shared/.env.production"));
|
||||||
|
|
||||||
|
const container = process.env.POSTGRES_CONTAINER;
|
||||||
|
if (!container || !/^[a-zA-Z0-9_.-]+$/.test(container)) {
|
||||||
|
throw new Error("POSTGRES_CONTAINER is required");
|
||||||
|
}
|
||||||
|
const retentionDays = Number(process.env.BACKUP_RETENTION_DAYS ?? "14");
|
||||||
|
if (!Number.isInteger(retentionDays) || retentionDays < 1) {
|
||||||
|
throw new Error("BACKUP_RETENTION_DAYS must be a positive integer");
|
||||||
|
}
|
||||||
|
|
||||||
|
const directory = path.join(root, "shared/backups");
|
||||||
|
await mkdir(directory, { recursive: true });
|
||||||
|
const destination = path.join(directory, scheduledBackupName());
|
||||||
|
|
||||||
|
await backupPostgresDatabase({ container, destination });
|
||||||
|
try {
|
||||||
|
await verifyPostgresBackup({ container, file: destination });
|
||||||
|
} catch (error) {
|
||||||
|
await rm(destination, { force: true });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
await pruneBackups(directory, { retentionDays });
|
||||||
|
|
||||||
|
const offsiteTarget = process.env.BACKUP_OFFSITE_TARGET?.trim();
|
||||||
|
if (offsiteTarget) {
|
||||||
|
if (
|
||||||
|
!/^[a-zA-Z0-9_.@:/-]+$/.test(offsiteTarget) ||
|
||||||
|
offsiteTarget.startsWith("-") ||
|
||||||
|
offsiteTarget.includes("..")
|
||||||
|
) {
|
||||||
|
throw new Error("BACKUP_OFFSITE_TARGET contains unsupported characters");
|
||||||
|
}
|
||||||
|
const result = spawnSync("rsync", ["-a", "--partial", destination, offsiteTarget], {
|
||||||
|
stdio: "inherit",
|
||||||
|
env: process.env,
|
||||||
|
});
|
||||||
|
if (result.status !== 0) throw new Error("Offsite backup copy failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`scheduled backup written: ${destination}`);
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import { createReadStream, createWriteStream } from "node:fs";
|
||||||
|
import { readdir, rename, rm, stat } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import { spawn, spawnSync } from "node:child_process";
|
||||||
|
|
||||||
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||||
|
const SCHEDULED_BACKUP = /^scheduled-\d{8}T\d{6}Z-\d+\.dump$/;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 定时备份文件名包含 UTC 秒级时间和进程号,避免同一秒内重复执行时覆盖已有备份。
|
||||||
|
*/
|
||||||
|
export function scheduledBackupName(date = new Date(), pid = process.pid) {
|
||||||
|
const stamp = date
|
||||||
|
.toISOString()
|
||||||
|
.replace(/[-:]/g, "")
|
||||||
|
.replace(/\.\d{3}Z$/, "Z");
|
||||||
|
if (!/^\d{8}T\d{6}Z$/.test(stamp)) throw new Error("Invalid backup timestamp");
|
||||||
|
return `scheduled-${stamp}-${pid}.dump`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保留策略:
|
||||||
|
* - 发布前备份按文件名保留最近 7 份,保持原有发布回滚能力;
|
||||||
|
* - 定时备份按修改时间保留最近 retentionDays 天;
|
||||||
|
* - 同名临时文件由 pruneBackups 统一清理。
|
||||||
|
*/
|
||||||
|
export function selectExpiredBackups(
|
||||||
|
entries,
|
||||||
|
{ now = Date.now(), retentionDays = 14, keepReleaseBackups = 7 } = {},
|
||||||
|
) {
|
||||||
|
if (!Number.isInteger(retentionDays) || retentionDays < 1) {
|
||||||
|
throw new Error("retentionDays must be a positive integer");
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(keepReleaseBackups) || keepReleaseBackups < 1) {
|
||||||
|
throw new Error("keepReleaseBackups must be a positive integer");
|
||||||
|
}
|
||||||
|
|
||||||
|
const cutoff = now - retentionDays * DAY_MS;
|
||||||
|
const expired = [];
|
||||||
|
const releaseBackups = entries
|
||||||
|
.filter((entry) => entry.name.endsWith(".dump") && !SCHEDULED_BACKUP.test(entry.name))
|
||||||
|
.sort((left, right) => right.name.localeCompare(left.name));
|
||||||
|
|
||||||
|
for (const entry of releaseBackups.slice(keepReleaseBackups)) expired.push(entry.name);
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (SCHEDULED_BACKUP.test(entry.name) && entry.mtimeMs < cutoff) expired.push(entry.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...new Set(expired)];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function backupPostgresDatabase({
|
||||||
|
container,
|
||||||
|
destination,
|
||||||
|
docker = "docker",
|
||||||
|
env = process.env,
|
||||||
|
}) {
|
||||||
|
const temporary = destination + ".tmp";
|
||||||
|
const child = spawn(
|
||||||
|
docker,
|
||||||
|
["exec", container, "sh", "-c", 'exec pg_dump -Fc -U "$POSTGRES_USER" -d "$POSTGRES_DB"'],
|
||||||
|
{ stdio: ["ignore", "pipe", "inherit"], env },
|
||||||
|
);
|
||||||
|
const output = createWriteStream(temporary, { flags: "wx", mode: 0o600 });
|
||||||
|
child.stdout.pipe(output);
|
||||||
|
try {
|
||||||
|
await Promise.all([
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
|
child.on("error", reject);
|
||||||
|
child.on("exit", (code) =>
|
||||||
|
code === 0 ? resolve() : reject(new Error("Database backup failed")),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
|
output.on("finish", resolve);
|
||||||
|
output.on("error", reject);
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
await rename(temporary, destination);
|
||||||
|
} catch (error) {
|
||||||
|
child.kill("SIGTERM");
|
||||||
|
output.destroy();
|
||||||
|
await rm(temporary, { force: true });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function verifyPostgresBackup({
|
||||||
|
container,
|
||||||
|
file,
|
||||||
|
docker = "docker",
|
||||||
|
env = process.env,
|
||||||
|
}) {
|
||||||
|
const child = spawn(docker, ["exec", "-i", container, "pg_restore", "-l"], {
|
||||||
|
stdio: ["pipe", "ignore", "pipe"],
|
||||||
|
env,
|
||||||
|
});
|
||||||
|
const input = createReadStream(file);
|
||||||
|
let stderr = "";
|
||||||
|
child.stderr.setEncoding("utf8");
|
||||||
|
child.stderr.on("data", (chunk) => {
|
||||||
|
stderr += chunk;
|
||||||
|
});
|
||||||
|
input.pipe(child.stdin);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
child.on("error", reject);
|
||||||
|
input.on("error", reject);
|
||||||
|
child.stdin.on("error", (error) => {
|
||||||
|
if (error.code !== "EPIPE") reject(error);
|
||||||
|
});
|
||||||
|
child.on("exit", (code) => {
|
||||||
|
if (code === 0) resolve();
|
||||||
|
else reject(new Error(`Backup is not readable: ${stderr.trim() || "pg_restore failed"}`));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
input.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function pruneBackups(directory, options = {}) {
|
||||||
|
const entries = await readdir(directory);
|
||||||
|
const withStats = [];
|
||||||
|
for (const name of entries) {
|
||||||
|
const info = await stat(path.join(directory, name));
|
||||||
|
if (!info.isFile()) continue;
|
||||||
|
withStats.push({ name, mtimeMs: info.mtimeMs });
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const name of selectExpiredBackups(withStats, options)) {
|
||||||
|
await rm(path.join(directory, name));
|
||||||
|
}
|
||||||
|
for (const name of entries) {
|
||||||
|
if (name.endsWith(".dump.tmp")) await rm(path.join(directory, name), { force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { chmod, mkdtemp, readFile, rm, stat, utimes, writeFile } from "node:fs/promises";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import test from "node:test";
|
||||||
|
import {
|
||||||
|
backupPostgresDatabase,
|
||||||
|
pruneBackups,
|
||||||
|
scheduledBackupName,
|
||||||
|
selectExpiredBackups,
|
||||||
|
verifyPostgresBackup,
|
||||||
|
} from "./database-backup.mjs";
|
||||||
|
|
||||||
|
test("定时备份文件名使用 UTC 时间和进程号", () => {
|
||||||
|
assert.equal(
|
||||||
|
scheduledBackupName(new Date("2026-10-23T09:45:00.123Z"), 42),
|
||||||
|
"scheduled-20261023T094500Z-42.dump",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("发布备份只保留最近 7 份,定时备份按保留天数清理", () => {
|
||||||
|
const now = Date.parse("2026-10-23T12:00:00Z");
|
||||||
|
const day = 24 * 60 * 60 * 1000;
|
||||||
|
const entries = [
|
||||||
|
...Array.from({ length: 8 }, (_, index) => ({
|
||||||
|
name: `2026100${index + 1}000000-release${index}.dump`,
|
||||||
|
mtimeMs: now,
|
||||||
|
})),
|
||||||
|
{ name: "scheduled-20261001T000000Z-1.dump", mtimeMs: now - 30 * day },
|
||||||
|
{ name: "scheduled-20261020T000000Z-2.dump", mtimeMs: now - 3 * day },
|
||||||
|
];
|
||||||
|
|
||||||
|
assert.deepEqual(selectExpiredBackups(entries, { now, retentionDays: 14 }), [
|
||||||
|
"20261001000000-release0.dump",
|
||||||
|
"scheduled-20261001T000000Z-1.dump",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("非法保留天数会被拒绝", () => {
|
||||||
|
assert.throws(() => selectExpiredBackups([], { retentionDays: 0 }), /positive integer/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pruneBackups 删除过期备份和残留临时文件", async () => {
|
||||||
|
const directory = await mkdtemp(path.join(os.tmpdir(), "personal-brand-backup-"));
|
||||||
|
const old = path.join(directory, "scheduled-20260101T000000Z-1.dump");
|
||||||
|
const current = path.join(directory, "scheduled-20261023T000000Z-2.dump");
|
||||||
|
const temporary = path.join(directory, "scheduled-20261023T000000Z-3.dump.tmp");
|
||||||
|
try {
|
||||||
|
await writeFile(old, "old");
|
||||||
|
await writeFile(current, "current");
|
||||||
|
await writeFile(temporary, "partial");
|
||||||
|
const oldTime = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
||||||
|
await utimes(old, oldTime, oldTime);
|
||||||
|
|
||||||
|
await pruneBackups(directory, { retentionDays: 14 });
|
||||||
|
|
||||||
|
await assert.rejects(stat(old), { code: "ENOENT" });
|
||||||
|
await assert.rejects(stat(temporary), { code: "ENOENT" });
|
||||||
|
assert.equal((await stat(current)).size, 7);
|
||||||
|
} finally {
|
||||||
|
await rm(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
async function writeFakeDocker(directory, body) {
|
||||||
|
const file = path.join(directory, "docker");
|
||||||
|
await writeFile(file, "#!/bin/sh\n" + body, { mode: 0o755 });
|
||||||
|
await chmod(file, 0o755);
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
test("备份写入权限受限的 dump 文件并清理临时文件", async () => {
|
||||||
|
const directory = await mkdtemp(path.join(os.tmpdir(), "personal-brand-dump-"));
|
||||||
|
const destination = path.join(directory, "release.dump");
|
||||||
|
try {
|
||||||
|
const docker = await writeFakeDocker(directory, "printf 'dump-bytes'\n");
|
||||||
|
await backupPostgresDatabase({ container: "postgres", destination, docker });
|
||||||
|
|
||||||
|
assert.equal(await readFile(destination, "utf8"), "dump-bytes");
|
||||||
|
assert.equal((await stat(destination)).mode & 0o777, 0o600);
|
||||||
|
await assert.rejects(stat(destination + ".tmp"), { code: "ENOENT" });
|
||||||
|
} finally {
|
||||||
|
await rm(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pg_dump 失败时删除半成品备份", async () => {
|
||||||
|
const directory = await mkdtemp(path.join(os.tmpdir(), "personal-brand-dump-"));
|
||||||
|
const destination = path.join(directory, "release.dump");
|
||||||
|
try {
|
||||||
|
const docker = await writeFakeDocker(directory, "printf 'partial'; exit 1\n");
|
||||||
|
await assert.rejects(
|
||||||
|
backupPostgresDatabase({ container: "postgres", destination, docker }),
|
||||||
|
/Database backup failed/,
|
||||||
|
);
|
||||||
|
|
||||||
|
await assert.rejects(stat(destination), { code: "ENOENT" });
|
||||||
|
await assert.rejects(stat(destination + ".tmp"), { code: "ENOENT" });
|
||||||
|
} finally {
|
||||||
|
await rm(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("备份可被 pg_restore 读取校验", async () => {
|
||||||
|
const directory = await mkdtemp(path.join(os.tmpdir(), "personal-brand-verify-"));
|
||||||
|
const file = path.join(directory, "release.dump");
|
||||||
|
try {
|
||||||
|
await writeFile(file, "dump-bytes");
|
||||||
|
const docker = await writeFakeDocker(directory, "cat >/dev/null; exit 0\n");
|
||||||
|
await verifyPostgresBackup({ container: "postgres", file, docker });
|
||||||
|
} finally {
|
||||||
|
await rm(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pg_restore 校验失败时报告不可读", async () => {
|
||||||
|
const directory = await mkdtemp(path.join(os.tmpdir(), "personal-brand-verify-"));
|
||||||
|
const file = path.join(directory, "release.dump");
|
||||||
|
try {
|
||||||
|
await writeFile(file, "broken");
|
||||||
|
const docker = await writeFakeDocker(
|
||||||
|
directory,
|
||||||
|
"cat >/dev/null; echo 'invalid header' >&2; exit 1\n",
|
||||||
|
);
|
||||||
|
await assert.rejects(
|
||||||
|
verifyPostgresBackup({ container: "postgres", file, docker }),
|
||||||
|
/invalid header/,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await rm(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -6,6 +6,8 @@ module.exports = {
|
|||||||
apps: [
|
apps: [
|
||||||
{
|
{
|
||||||
name: "personal-brand-api",
|
name: "personal-brand-api",
|
||||||
|
instances: 1,
|
||||||
|
exec_mode: "fork",
|
||||||
cwd: path.join(root, "current/apps/api"),
|
cwd: path.join(root, "current/apps/api"),
|
||||||
script: "dist/main.js",
|
script: "dist/main.js",
|
||||||
interpreter: process.execPath,
|
interpreter: process.execPath,
|
||||||
|
|||||||
@@ -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");
|
||||||
|
});
|
||||||
+41
-65
@@ -1,4 +1,3 @@
|
|||||||
import { createWriteStream } from "node:fs";
|
|
||||||
import {
|
import {
|
||||||
copyFile,
|
copyFile,
|
||||||
cp,
|
cp,
|
||||||
@@ -14,8 +13,10 @@ import {
|
|||||||
writeFile,
|
writeFile,
|
||||||
} from "node:fs/promises";
|
} from "node:fs/promises";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { spawn, spawnSync } from "node:child_process";
|
import { spawnSync } from "node:child_process";
|
||||||
import { checkPackage } from "../scripts/deploy/check-package.mjs";
|
import { checkPackage } from "../scripts/deploy/check-package.mjs";
|
||||||
|
import { assertReleaseEnvironment } from "./release-environment.mjs";
|
||||||
|
import { backupPostgresDatabase, pruneBackups, verifyPostgresBackup } from "./database-backup.mjs";
|
||||||
|
|
||||||
const root = process.env.DEPLOY_ROOT;
|
const root = process.env.DEPLOY_ROOT;
|
||||||
if (!root || !path.isAbsolute(root)) throw new Error("DEPLOY_ROOT must be absolute");
|
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");
|
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 (Number(process.versions.node.split(".")[0]) !== 24) throw new Error("Node.js 24 is required");
|
||||||
if (
|
const databaseUrl = assertReleaseEnvironment(process.env);
|
||||||
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 privateDatabaseHost = /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[0-1])\.)/.test(
|
const privateDatabaseHost = /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[0-1])\.)/.test(
|
||||||
databaseUrl.hostname,
|
databaseUrl.hostname,
|
||||||
);
|
);
|
||||||
@@ -110,6 +98,37 @@ async function installPm2Service() {
|
|||||||
run("systemctl", ["--user", "enable", pm2ServiceName]);
|
run("systemctl", ["--user", "enable", pm2ServiceName]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const backupTimerName = "personal-brand-backup.timer";
|
||||||
|
|
||||||
|
async function installBackupTimer(release) {
|
||||||
|
const directory = path.dirname(adminServiceFile);
|
||||||
|
const serviceFile = path.join(directory, "personal-brand-backup.service");
|
||||||
|
const timerFile = path.join(directory, backupTimerName);
|
||||||
|
await mkdir(directory, { recursive: true });
|
||||||
|
// 定时任务从 shared 读取稳定副本;发布回滚后 current 变了,备份任务仍然可用。
|
||||||
|
await copyFile(
|
||||||
|
path.join(release, "deploy/backup-db.mjs"),
|
||||||
|
path.join(root, "shared/backup-db.mjs"),
|
||||||
|
);
|
||||||
|
await copyFile(
|
||||||
|
path.join(release, "deploy/database-backup.mjs"),
|
||||||
|
path.join(root, "shared/database-backup.mjs"),
|
||||||
|
);
|
||||||
|
await writeFile(
|
||||||
|
serviceFile,
|
||||||
|
`[Unit]\nDescription=Personal Brand daily database backup\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=oneshot\nEnvironment=DEPLOY_ROOT=${root}\nEnvironment=HOME=${process.env.HOME ?? "/home/ubuntu"}\nEnvironment=PATH=${process.env.PATH}\nExecStart=${process.execPath} ${root}/shared/backup-db.mjs\n`,
|
||||||
|
{ mode: 0o644 },
|
||||||
|
);
|
||||||
|
await writeFile(
|
||||||
|
timerFile,
|
||||||
|
`[Unit]\nDescription=Daily Personal Brand database backup\n\n[Timer]\nOnCalendar=*-*-* 03:30:00\nPersistent=true\nRandomizedDelaySec=10m\n\n[Install]\nWantedBy=timers.target\n`,
|
||||||
|
{ mode: 0o644 },
|
||||||
|
);
|
||||||
|
run("systemctl", ["--user", "daemon-reload"]);
|
||||||
|
run("systemctl", ["--user", "enable", "--now", backupTimerName]);
|
||||||
|
run("systemctl", ["--user", "restart", backupTimerName]);
|
||||||
|
}
|
||||||
|
|
||||||
async function waitForAdminHealth() {
|
async function waitForAdminHealth() {
|
||||||
const url = "http://127.0.0.1:" + (process.env.ADMIN_STATIC_PORT ?? "3010") + "/admin/";
|
const url = "http://127.0.0.1:" + (process.env.ADMIN_STATIC_PORT ?? "3010") + "/admin/";
|
||||||
for (let attempt = 0; attempt < 20; attempt++) {
|
for (let attempt = 0; attempt < 20; attempt++) {
|
||||||
@@ -146,53 +165,6 @@ async function switchCurrent(target) {
|
|||||||
await rename(temporary, current);
|
await rename(temporary, current);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function backupDatabase(destination) {
|
|
||||||
const temporary = destination + ".tmp";
|
|
||||||
const child = spawn(
|
|
||||||
"docker",
|
|
||||||
[
|
|
||||||
"exec",
|
|
||||||
postgresContainer,
|
|
||||||
"sh",
|
|
||||||
"-c",
|
|
||||||
'exec pg_dump -Fc -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
|
|
||||||
],
|
|
||||||
{ stdio: ["ignore", "pipe", "inherit"] },
|
|
||||||
);
|
|
||||||
const output = createWriteStream(temporary, { flags: "wx", mode: 0o600 });
|
|
||||||
child.stdout.pipe(output);
|
|
||||||
try {
|
|
||||||
await Promise.all([
|
|
||||||
new Promise((resolve, reject) => {
|
|
||||||
child.on("error", reject);
|
|
||||||
child.on("exit", (code) =>
|
|
||||||
code === 0 ? resolve() : reject(new Error("Database backup failed")),
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
new Promise((resolve, reject) => {
|
|
||||||
output.on("finish", resolve);
|
|
||||||
output.on("error", reject);
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
await rename(temporary, destination);
|
|
||||||
} catch (error) {
|
|
||||||
await rm(temporary, { force: true });
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pruneBackups(directory) {
|
|
||||||
const backups = (await readdir(directory, { withFileTypes: true }))
|
|
||||||
.filter((entry) => entry.isFile() && entry.name.endsWith(".dump"))
|
|
||||||
.map((entry) => entry.name)
|
|
||||||
.sort()
|
|
||||||
.reverse();
|
|
||||||
for (const backup of backups.slice(7)) await rm(path.join(directory, backup));
|
|
||||||
for (const entry of await readdir(directory)) {
|
|
||||||
if (entry.endsWith(".dump.tmp")) await rm(path.join(directory, entry), { force: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pruneReleases(directory, currentRelease, previousRelease) {
|
async function pruneReleases(directory, currentRelease, previousRelease) {
|
||||||
const releases = (await readdir(directory, { withFileTypes: true }))
|
const releases = (await readdir(directory, { withFileTypes: true }))
|
||||||
.filter((entry) => entry.isDirectory())
|
.filter((entry) => entry.isDirectory())
|
||||||
@@ -379,8 +351,11 @@ try {
|
|||||||
release,
|
release,
|
||||||
);
|
);
|
||||||
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "generate"], release);
|
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "generate"], release);
|
||||||
await backupDatabase(path.join(root, "shared/backups", manifest.version + ".dump"));
|
const backupDirectory = path.join(root, "shared/backups");
|
||||||
await pruneBackups(path.join(root, "shared/backups"));
|
const releaseBackup = path.join(backupDirectory, manifest.version + ".dump");
|
||||||
|
await backupPostgresDatabase({ container: postgresContainer, destination: releaseBackup });
|
||||||
|
await verifyPostgresBackup({ container: postgresContainer, file: releaseBackup });
|
||||||
|
await pruneBackups(backupDirectory);
|
||||||
// 旧数据的模板包声明必须先收敛,migration 才能安全地删除兼容字段。
|
// 旧数据的模板包声明必须先收敛,migration 才能安全地删除兼容字段。
|
||||||
run(process.execPath, ["deploy/prepare-template-contract.mjs", ".", "--apply"], release);
|
run(process.execPath, ["deploy/prepare-template-contract.mjs", ".", "--apply"], release);
|
||||||
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "migrate", "deploy"], release);
|
run("pnpm", ["--filter", "@personal-brand/api", "exec", "prisma", "migrate", "deploy"], release);
|
||||||
@@ -402,6 +377,7 @@ try {
|
|||||||
await writeFile(path.join(root, "shared/previous-release"), previous + "\n");
|
await writeFile(path.join(root, "shared/previous-release"), previous + "\n");
|
||||||
run("pm2", ["save"]);
|
run("pm2", ["save"]);
|
||||||
await pruneReleases(path.join(root, "releases"), release, previous);
|
await pruneReleases(path.join(root, "releases"), release, previous);
|
||||||
|
await installBackupTimer(release);
|
||||||
console.log("release installed: " + manifest.version);
|
console.log("release installed: " + manifest.version);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (routeUpdated) {
|
if (routeUpdated) {
|
||||||
|
|||||||
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user