Compare commits

...
Author SHA1 Message Date
que01 45a5e4d666 refactor: 抽取业务预览投影规则并补充单测
CI / Browser smoke (pull_request) Successful in 47s
CI / Static checks (pull_request) Successful in 1m0s
CI / API integration (pull_request) Successful in 1m7s
CI / Production build (pull_request) Successful in 1m24s
2026-10-29 15:09:53 +08:00
que01 b0265f3be3 Merge pull request 'refactor: 抽取共享 getFullFormValues 表单读取工具' (#16) from refactor/form-values-helper into main
CI / Browser smoke (push) Has been skipped
CI / Static checks (push) Successful in 48s
CI / API integration (push) Successful in 1m9s
CI / Production build (push) Successful in 1m26s
Reviewed-on: #16
2026-10-29 06:32:31 +00:00
que01 aa2b6f35b0 refactor: 抽取共享 getFullFormValues 表单读取工具
CI / Browser smoke (pull_request) Successful in 47s
CI / Static checks (pull_request) Successful in 58s
CI / API integration (pull_request) Successful in 1m7s
CI / Production build (pull_request) Successful in 1m24s
2026-10-29 14:24:23 +08:00
que01 29116678aa Merge pull request 'test: 提取业务预览目标纯函数并补充单测' (#15) from test/offering-preview-unit into main
CI / Browser smoke (push) Has been skipped
CI / Static checks (push) Successful in 47s
CI / API integration (push) Successful in 1m7s
CI / Production build (push) Successful in 1m19s
Reviewed-on: #15
2026-10-29 06:08:37 +00:00
que01 b6fedd9f63 test: 提取业务预览目标纯函数并补充单测
CI / Browser smoke (pull_request) Successful in 46s
CI / Static checks (pull_request) Successful in 58s
CI / API integration (pull_request) Successful in 1m8s
CI / Production build (pull_request) Successful in 1m24s
2026-10-29 13:47:30 +08:00
que01 abf4e1b1c9 Merge pull request 'fix: 修复独立工坊业务详情区块字段过滤' (#14) from fix/atelier-detail-region-filter into main
CI / Browser smoke (push) Has been skipped
CI / Static checks (push) Successful in 49s
CI / API integration (push) Successful in 1m9s
CI / Production build (push) Successful in 1m25s
Reviewed-on: #14
2026-10-29 04:25:19 +00:00
que01 03460d5ab0 test: 更新品牌创建页面方案版本断言
CI / Browser smoke (pull_request) Successful in 47s
CI / Static checks (pull_request) Successful in 57s
CI / API integration (pull_request) Successful in 1m9s
CI / Production build (pull_request) Successful in 1m24s
2026-10-29 12:18:50 +08:00
que01 8f252d088a fix: 修复独立工坊业务详情区块字段过滤
CI / Static checks (pull_request) Successful in 1m10s
CI / Browser smoke (pull_request) Failing after 1m49s
CI / API integration (pull_request) Successful in 1m4s
CI / Production build (pull_request) Successful in 1m28s
2026-10-25 10:41:04 +08:00
que01 61f216ae0e Merge pull request 'fix: 业务提供项点选后仅显示当前区块字段' (#13) from fix/offering-editor-target-filter into main
CI / Browser smoke (push) Has been skipped
CI / Static checks (push) Successful in 1m0s
CI / API integration (push) Successful in 1m29s
CI / Production build (push) Failing after 14m10s
Merge pull request #13: fix: 业务提供项点选后仅显示当前区块字段
2026-10-24 02:45:42 +00:00
que01 96c3d3292d fix: 业务提供项点选后仅显示当前区块字段
CI / Browser smoke (pull_request) Successful in 51s
CI / Static checks (pull_request) Successful in 1m11s
CI / API integration (pull_request) Successful in 1m24s
CI / Production build (pull_request) Successful in 1m50s
2026-10-24 10:37:33 +08:00
que01 cbbf122280 Merge pull request #12: feat: 业务提供项编辑弹窗支持区块点选联动
CI / Browser smoke (push) Has been skipped
CI / Static checks (push) Successful in 55s
CI / API integration (push) Successful in 1m25s
CI / Production build (push) Successful in 1m55s
2026-10-24 02:07:28 +00:00
que01 64b6f5c27c feat: 业务提供项编辑弹窗支持区块点选联动
CI / Browser smoke (pull_request) Successful in 57s
CI / Static checks (pull_request) Successful in 1m20s
CI / API integration (pull_request) Successful in 1m26s
CI / Production build (pull_request) Successful in 1m51s
2026-10-24 10:02:04 +08:00
que01 a3730ee8fc Merge pull request 'feat: 支持按品牌配置微信登录凭据' (#11) from feat/brand-wechat-login-credentials into main
CI / Browser smoke (push) Has been skipped
CI / API integration (push) Successful in 1m29s
CI / Production build (push) Successful in 2m17s
CI / Static checks (push) Successful in 57s
2026-10-23 14:14:02 +00:00
que01 d0a0eeea8c feat: 支持按品牌配置微信登录凭据
CI / Browser smoke (pull_request) Successful in 58s
CI / Static checks (pull_request) Successful in 1m32s
CI / API integration (pull_request) Successful in 1m27s
CI / Production build (pull_request) Successful in 2m7s
2026-10-23 22:07:39 +08:00
que01 e75c524343 Merge pull request 'docs: 更新生产发布与备份状态' (#9) from docs/production-status-backup into main 2026-10-23 10:09:26 +00:00
que01 1a4f71996a docs: 更新生产发布与备份状态
CI / Browser smoke (pull_request) Successful in 51s
CI / Static checks (pull_request) Successful in 58s
CI / API integration (pull_request) Successful in 1m34s
CI / Production build (pull_request) Successful in 1m47s
2026-10-23 18:05:25 +08:00
que01 a2fa6c3c31 Merge pull request 'feat: 增加生产数据库每日备份与状态门禁' (#8) from feat/scheduled-db-backup into main
CI / Browser smoke (push) Has been skipped
CI / Static checks (push) Successful in 50s
CI / API integration (push) Successful in 1m22s
CI / Production build (push) Successful in 1m49s
2026-10-23 09:58:56 +00:00
que01 015947f8fb feat: 增加生产数据库每日备份与状态门禁
CI / Browser smoke (pull_request) Successful in 50s
CI / Static checks (pull_request) Successful in 52s
CI / API integration (pull_request) Successful in 1m23s
CI / Production build (pull_request) Successful in 1m48s
2026-10-23 17:54:27 +08:00
que01 072a1037ac Merge pull request 'ci: 预热 Prisma 并移除运行时 Node 下载' (#7) from ci/avoid-runtime-downloads into main
CI / Browser smoke (push) Has been skipped
CI / Static checks (push) Successful in 53s
CI / Production build (push) Successful in 1m49s
CI / API integration (push) Successful in 1m23s
2026-10-23 09:41:33 +00:00
que01 447c224fce ci: 预热 Prisma 并移除运行时 Node 下载
CI / Static checks (pull_request) Successful in 1m1s
CI / API integration (pull_request) Successful in 1m26s
CI / Production build (pull_request) Successful in 1m45s
CI / Browser smoke (pull_request) Successful in 50s
2026-10-23 17:37:48 +08:00
que01 f2fc1e0810 Merge pull request 'fix: 修复 runner 迁移后的部署状态检查' (#6) from fix/deploy-status-after-runner-migration into main
CI / Browser smoke (push) Has been skipped
CI / API integration (push) Failing after 5m0s
CI / Static checks (push) Failing after 8m4s
CI / Production build (push) Has been skipped
2026-10-23 09:16:08 +00:00
59 changed files with 2147 additions and 366 deletions

No files matched your search

@@ -1,7 +1,7 @@
{ {
"schemaVersion": 1, "schemaVersion": 1,
"scope": "模板完成证据登记,保留命令、日志与产物哈希", "scope": "模板完成证据登记,保留命令、日志与产物哈希",
"generatedAt": "2026-10-23T07:40:54.556Z", "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": "f0bb03d734cf303b75be41bbcab6eea15f5479ac197b16c82f78e1faad71b17e" "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": "需要核对循环项或间接映射,不能视为已覆盖。",
+3 -4
View File
@@ -19,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
+11 -3
View File
@@ -6,6 +6,9 @@ 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 并先执行数据库迁移 # 单实例使用 memory;多实例部署改用 postgres 并先执行数据库迁移
CLIENT_ERROR_THROTTLE_STORE=memory CLIENT_ERROR_THROTTLE_STORE=memory
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001 DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
@@ -16,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=
@@ -25,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
+52 -20
View File
@@ -28,12 +28,20 @@ jobs:
timeout-minutes: 40 timeout-minutes: 40
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: pnpm/action-setup@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: with:
version: ${{ env.PNPM_VERSION }} path: ~/.cache/prisma
- uses: actions/setup-node@v4 key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
with: restore-keys: |
node-version: ${{ env.NODE_VERSION }} prisma-${{ runner.os }}-${{ runner.arch }}-
- name: Restore Turbo cache - name: Restore Turbo cache
uses: actions/cache@v4 uses: actions/cache@v4
with: with:
@@ -59,12 +67,20 @@ jobs:
needs: [static] needs: [static]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: pnpm/action-setup@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: with:
version: ${{ env.PNPM_VERSION }} path: ~/.cache/prisma
- uses: actions/setup-node@v4 key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
with: restore-keys: |
node-version: ${{ env.NODE_VERSION }} prisma-${{ runner.os }}-${{ runner.arch }}-
- name: Restore Turbo cache - name: Restore Turbo cache
uses: actions/cache@v4 uses: actions/cache@v4
with: with:
@@ -86,12 +102,20 @@ jobs:
timeout-minutes: 30 timeout-minutes: 30
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: pnpm/action-setup@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: with:
version: ${{ env.PNPM_VERSION }} path: ~/.cache/prisma
- uses: actions/setup-node@v4 key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
with: restore-keys: |
node-version: ${{ env.NODE_VERSION }} prisma-${{ runner.os }}-${{ runner.arch }}-
- run: pnpm install --frozen-lockfile - run: pnpm install --frozen-lockfile
- name: Cache Playwright browsers - name: Cache Playwright browsers
uses: actions/cache@v4 uses: actions/cache@v4
@@ -127,12 +151,20 @@ jobs:
SEED_ADMIN_PASSWORD: ci-integration-admin-password SEED_ADMIN_PASSWORD: ci-integration-admin-password
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: pnpm/action-setup@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: with:
version: ${{ env.PNPM_VERSION }} path: ~/.cache/prisma
- uses: actions/setup-node@v4 key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
with: restore-keys: |
node-version: ${{ env.NODE_VERSION }} prisma-${{ runner.os }}-${{ runner.arch }}-
- run: pnpm install --frozen-lockfile - run: pnpm install --frozen-lockfile
- name: Prepare API test env - name: Prepare API test env
working-directory: apps/api working-directory: apps/api
+7 -3
View File
@@ -37,10 +37,10 @@ ADR 0033 已落地:
当前生产 release: 当前生产 release:
```text ```text
20261021034700-adcaa12970af 20261023100112-a2fa6c3c3140
``` ```
该 release 由提交 `adcaa12` 构建,包含后台渲染异常上报(`POST /admin/client-errors`,含去重与限流)、Admin 列表接口运行时响应契约校验,以及前序 release 的创建品牌与页面方案交互修复、Admin 渲染错误边界和异常数据容忍。部署后已完成公开路由健康检查,并确认未登录调用异常上报接口返回 `401 HTTP_401`,说明新接口已进入生产路由。 该 release 由提交 `a2fa6c3` 构建,新增生产数据库每日定时备份、备份可读性校验、发布/定时备份保留策略、`backup-timer` 与 `backup-age-hours` 部署状态门禁。部署后已手动触发一次 `personal-brand-backup.service`,生成 `scheduled-20261023T100426Z-1029929.dump`,并通过 `pg_restore -l` 校验可读。
生产健康检查: 生产健康检查:
@@ -49,7 +49,11 @@ 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
@@ -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);
@@ -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">
@@ -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,
@@ -161,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) {
@@ -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,
+7
View File
@@ -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,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, []);
});
+141
View File
@@ -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"],
);
});
@@ -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([
@@ -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);
@@ -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;
} }
@@ -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);
} }
} }
+35 -6
View File
@@ -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",
}); });
@@ -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";
+82 -6
View File
@@ -11,6 +11,7 @@ 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 { PostgresClientErrorThrottleStore } from "../dist/modules/admin/client-error-throttle.postgres.store.js";
import { import {
@@ -389,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;
@@ -866,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 },
@@ -897,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,
@@ -904,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);
@@ -912,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", {
@@ -2322,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(
@@ -2350,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",
}, },
}); });
@@ -5597,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",
@@ -5621,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 },
});
} }
}); });
+5 -5
View File
@@ -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,7 @@ 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", method: "POST",
+133
View File
@@ -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,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();
}); });
+46 -2
View File
@@ -189,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("弹窗编辑后的餐品介绍");
@@ -197,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("列表实时预览餐品");
@@ -214,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();
@@ -235,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("弹窗编辑后的餐品介绍");
+1 -1
View File
@@ -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"
} }
] ]
} }
+53
View File
@@ -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}`);
+138
View File
@@ -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 });
}
}
+132
View File
@@ -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 });
}
});
+39 -51
View File
@@ -1,4 +1,3 @@
import { createWriteStream } from "node:fs";
import { import {
copyFile, copyFile,
cp, cp,
@@ -14,9 +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 { 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");
@@ -98,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++) {
@@ -134,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())
@@ -367,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);
@@ -390,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) {
+10
View File
@@ -6,6 +6,8 @@ FROM node:24-bookworm
ARG PNPM_VERSION=9.15.0 ARG PNPM_VERSION=9.15.0
ARG PLAYWRIGHT_VERSION=1.58.2 ARG PLAYWRIGHT_VERSION=1.58.2
# 必须与 pnpm-lock.yaml 中解析出的 Prisma 版本一致;升级 Prisma 后同步修改并重建镜像。
ARG PRISMA_VERSION=6.19.3
ENV PNPM_HOME=/usr/local/share/pnpm ENV PNPM_HOME=/usr/local/share/pnpm
ENV PATH=${PNPM_HOME}:${PATH} ENV PATH=${PNPM_HOME}:${PATH}
@@ -22,4 +24,12 @@ RUN corepack enable \
RUN npx --yes playwright@${PLAYWRIGHT_VERSION} install --with-deps chromium \ RUN npx --yes playwright@${PLAYWRIGHT_VERSION} install --with-deps chromium \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
# 预热 Prisma engines 到 /root/.cache/prisma。CI job 每次都是新容器,若不预热,
# 每个 job 的 prisma generate 都会重新访问 binaries.prisma.sh,网络抖动会直接拖垮 CI。
COPY apps/api/prisma/schema.prisma /tmp/prisma-warmup/schema.prisma
RUN printf '%s\n' '{"name":"prisma-warmup","private":true}' > /tmp/prisma-warmup/package.json \
&& cd /tmp/prisma-warmup \
&& DATABASE_URL=postgresql://warmup:warmup@127.0.0.1:5432/warmup npx --yes prisma@${PRISMA_VERSION} generate --schema schema.prisma \
&& rm -rf /tmp/prisma-warmup /root/.npm
WORKDIR /workspace WORKDIR /workspace
+6
View File
@@ -33,6 +33,12 @@ journalctl --user -u gitea-runner -n 100 --no-pager
Runner 与本地开发工作共用 `Elitebook` 主机,不再与生产 API 共用资源。任务容器限制 4 CPU / 8 GB、并发 2;本地机器关机或休眠时 CI 会排队,required checks 不会自动完成。 Runner 与本地开发工作共用 `Elitebook` 主机,不再与生产 API 共用资源。任务容器限制 4 CPU / 8 GB、并发 2;本地机器关机或休眠时 CI 会排队,required checks 不会自动完成。
## 工具链与外部下载
任务镜像 `personal-brand-ci:node24` 已内置 Node 24 和 pnpm 9.15.0;workflow 不再调用 `actions/setup-node` 或 `pnpm/action-setup`,而是在每个 job 开头执行 `Verify preinstalled toolchain`。这样不会因为 nodejs.org 下载缓慢或中断而把 job 卡到超时。
Prisma engines 在构建镜像时预热到 `/root/.cache/prisma`,job 内 `pnpm install` 触发的 `prisma generate` 直接命中缓存,不再访问 `binaries.prisma.sh`。workflow 仍用 `actions/cache` 缓存该目录,作为更换镜像或镜像未预热时的兜底。升级 Prisma 后必须同步 `deploy/runner/Dockerfile` 的 `PRISMA_VERSION` 并重建镜像。
## 缓存 ## 缓存
Runner 内置 cache server(`cache.host=172.17.0.1`、`cache.port=8193`、`cache.dir=~/gitea-runner/cache-data`),供 `actions/cache` 使用(Turbo 缓存等)。 Runner 内置 cache server(`cache.host=172.17.0.1`、`cache.port=8193`、`cache.dir=~/gitea-runner/cache-data`),供 `actions/cache` 使用(Turbo 缓存等)。
+14 -5
View File
@@ -30,9 +30,16 @@ DEPLOY_TARGET=oracle_arm PUBLIC_BASE_URL=https://wechat.app.que01.top pnpm deplo
pnpm deploy:status pnpm deploy:status
``` ```
数据库备份自动保留最近 7 份;备份归档在状态检查中通过 `pg_restore -l` 校验可读性。备份失败会清理未完成的临时文件,不自动删除数据库数据。发布成功后保留当前版本、上一版本和最近 5 个发布目录。状态检查同时报告 PM2 自启、磁盘空间、备份时间/可读性及发布目录数量。 数据库备份分两类:
备份当前仍在同一台 VPS 上,不等同于灾难恢复副本。应将 `shared/backups/*.dump` 定期复制到独立主机或对象存储,并至少每季度在隔离数据库执行一次恢复演练;不得在生产数据库上测试恢复。整机重启演练需在维护窗口执行,确认 Admin、API、PostgreSQL 和公网路由恢复后再结束维护。 - 发布备份:每次 `pnpm deploy:release` 在 migration 前创建,按版本名保留最近 7 份。
- 定时备份:由 user-level `personal-brand-backup.timer` 每天 03:30(VPS 本地时区)执行,写入 `shared/backups/scheduled-*.dump`,默认保留 14 天。
定时任务的脚本副本位于 `shared/backup-db.mjs` 和 `shared/database-backup.mjs`,不依赖当前 release 目录,回滚后仍可运行。每次备份先用 `pg_dump -Fc` 写入临时文件,再用 `pg_restore -l` 校验;校验失败会删除损坏文件并让本次任务失败。备份失败会清理未完成的临时文件,不自动删除数据库数据。发布成功后保留当前版本、上一版本和最近 5 个发布目录。
状态检查会验证备份定时器处于 active、最新备份不超过 36 小时(可用 `BACKUP_MAX_AGE_HOURS` 调整),并通过 `pg_restore -l` 校验可读性。状态检查同时报告 PM2 自启、磁盘空间、备份时间和发布目录数量。
如需异地副本,在 `shared/.env.production` 配置 `BACKUP_OFFSITE_TARGET`(`rsync` 目标,例如 `backup@example-host:/srv/personal-brand-backups/`),并为 `ubuntu` 用户预先配置 SSH key。未配置时备份只保留在同一台 VPS 上,不等同于灾难恢复副本。至少每季度应在隔离数据库执行一次恢复演练,不得在生产数据库上测试恢复;整机重启演练需在维护窗口执行,确认 Admin、API、PostgreSQL 和公网路由恢复后再结束维护。
## Nginx 反向代理 ## Nginx 反向代理
@@ -204,9 +211,11 @@ curl -fsS "$API_BASE_URL/public/workspace?brandSlug=$BRAND_SLUG" |
`API_BASE_URL` 与 AppID 是**编译期常量**,构建时写入小程序包,无法在后台热改。上传前按以下顺序解析并校验,任一项不合法就直接拒绝构建,避免把指向 `localhost` 的包上传到微信: `API_BASE_URL` 与 AppID 是**编译期常量**,构建时写入小程序包,无法在后台热改。上传前按以下顺序解析并校验,任一项不合法就直接拒绝构建,避免把指向 `localhost` 的包上传到微信:
- 请求地址:后台「配置与发布 → 小程序上传配置」里的“小程序请求地址”优先;未配置时回落到 `MINIAPP_API_BASE_URL`,再回落到 `PUBLIC_BASE_URL` 加 `MINIAPP_API_PATH`(默认 `/api`)。非 `https` 的公网地址会被拒绝。因此换域名只需在后台改这一项并重新上传代码,不用改服务端环境变量。 - 请求地址:后台「配置与发布 → 小程序配置」里的“小程序请求地址”优先;未配置时回落到 `MINIAPP_API_BASE_URL`,再回落到 `PUBLIC_BASE_URL` 加 `MINIAPP_API_PATH`(默认 `/api`)。非 `https` 的公网地址会被拒绝。因此换域名只需在后台改这一项并重新上传代码,不用改服务端环境变量。
- AppID:同样以后台“小程序上传配置”里的 AppID 为准,回落 `WEAPP_APP_ID`;`undefined`、`touristappid` 等占位值会被拒绝。 - AppID:同样以后台“小程序配置”里的 AppID 为准,回落 `WEAPP_APP_ID`;`undefined`、`touristappid` 等占位值会被拒绝。
该域名必须与微信后台“开发设置 → 服务器域名 → request 合法域名”完全一致,否则小程序打开即报“加载失败,请重试”。后台“小程序上传配置”会直接展示当前生效的请求域名,便于上线前比对。 微信登录同样使用该品牌的 AppID,但 AppSecret 由后台“小程序配置”单独维护。服务端使用 `MINIAPP_CREDENTIAL_ENCRYPTION_KEY`(未配置时回退 `SESSION_SECRET`)加密保存 AppSecret,登录时按 `brandSlug` 读取对应品牌的凭据,不使用全局 `WECHAT_APP_SECRET`,也不会跨品牌回退。修改 AppSecret 后立即生效,不需要重新上传小程序代码;修改 AppID 时必须同时填写该 AppID 对应的 AppSecret。
该域名必须与微信后台“开发设置 → 服务器域名 → request 合法域名”完全一致,否则小程序打开即报“加载失败,请重试”。后台“小程序配置”会直接展示当前生效的请求域名,便于上线前比对。
小程序包内的 `/media/...` 按请求地址的 origin 解析(例如 `https://host/api` → `https://host/media/...`),与网关的 `/media` 路由保持一致,不依赖 `/api` 前缀的剥离行为。 小程序包内的 `/media/...` 按请求地址的 origin 解析(例如 `https://host/api` → `https://host/media/...`),与网关的 `/media` 路由保持一致,不依赖 `/api` 前缀的剥离行为。
+4 -2
View File
@@ -44,9 +44,11 @@ SKIP_LINGER=1 \
docker build -f deploy/runner/Dockerfile -t personal-brand-ci:node24 . docker build -f deploy/runner/Dockerfile -t personal-brand-ci:node24 .
``` ```
镜像包含 Node 24、pnpm 9.15.0、git/curl/jq/unzip,以及 Playwright 1.58.2 的 Chromium、headless shell、FFmpeg 和系统依赖。构建产物是本机 amd64 镜像(约 3 GB),不推送到 registry。 镜像包含 Node 24、pnpm 9.15.0、git/curl/jq/unzip,以及 Playwright 1.58.2 的 Chromium、headless shell、FFmpeg 和系统依赖;构建时还会预热 Prisma engines 到 `/root/.cache/prisma`。构建产物是本机 amd64 镜像(约 3 GB),不推送到 registry。
`apps/taro/package.json` 升级 Playwright 后,同步修改 `deploy/runner/Dockerfile` 的 `PLAYWRIGHT_VERSION`,重建镜像并重启 runner: workflow 不再使用 `actions/setup-node` 或 `pnpm/action-setup`,而是直接校验镜像内置的 Node/pnpm 版本。因此替换 `RUNNER_IMAGE` 时必须保证镜像内已有 Node 24 和 pnpm 9.15.0,否则 job 会在 `Verify preinstalled toolchain` 步骤失败。
`apps/taro/package.json` 升级 Playwright 后,同步修改 `deploy/runner/Dockerfile` 的 `PLAYWRIGHT_VERSION`;升级 Prisma 后,同步修改 `PRISMA_VERSION`。然后重建镜像并重启 runner:
```bash ```bash
docker build -f deploy/runner/Dockerfile -t personal-brand-ci:node24 . docker build -f deploy/runner/Dockerfile -t personal-brand-ci:node24 .
+1 -1
View File
@@ -16,7 +16,7 @@
- acheng-campus-food@1.0.3:餐饮场景,使用 food 行业能力。 - acheng-campus-food@1.0.3:餐饮场景,使用 food 行业能力。
- linjing-editorial@1.0.7:林境建筑画册,仅适配 doors 业务类型。 - linjing-editorial@1.0.7:林境建筑画册,仅适配 doors 业务类型。
- atelier-solopreneur@1.3.2:独立工坊方向,适配 personal 行业。 - atelier-solopreneur@1.3.3:独立工坊方向,适配 personal 行业。
以上是仓库盘点,不表示三个包都已经通过线上导入、预览、品牌安装和微信上传验收。生成目录当前位于 packages/config/src/generated-template-packages.ts,后续必须由导出和 conformance 流程生成并校验。 以上是仓库盘点,不表示三个包都已经通过线上导入、预览、品牌安装和微信上传验收。生成目录当前位于 packages/config/src/generated-template-packages.ts,后续必须由导出和 conformance 流程生成并校验。
+1
View File
@@ -68,6 +68,7 @@ export type { PublicOffering, BookingStatus, BrandTemplateKey } from "@personal-
export type { export type {
EditorPreviewFrameMessage, EditorPreviewFrameMessage,
EditorPreviewHostMessage, EditorPreviewHostMessage,
RuntimeOffering,
RuntimeWorkspace, RuntimeWorkspace,
} from "@personal-brand/types"; } from "@personal-brand/types";
export { isTrustContentComplete } from "@personal-brand/types"; export { isTrustContentComplete } from "@personal-brand/types";
@@ -80,6 +80,7 @@ export interface BrandMethods {
appId?: string; appId?: string;
apiBaseUrl?: string; apiBaseUrl?: string;
privateKey?: string; privateKey?: string;
appSecret?: string;
}): Promise<MiniAppReleaseSettings>; }): Promise<MiniAppReleaseSettings>;
} }
+4
View File
@@ -115,6 +115,10 @@ export interface MiniAppReleaseSettings {
build: Record<string, unknown>; build: Record<string, unknown>;
credential: { algorithm: string } | null; credential: { algorithm: string } | null;
hasStoredCredentials: boolean; hasStoredCredentials: boolean;
/** 微信登录 AppSecret 是否已加密保存 */
hasStoredAppSecret: boolean;
/** AppID 与 AppSecret 均已配置,小程序 wx.login 可换取 OpenID */
loginConfigured: boolean;
/** 小程序包内编译期写入的请求域名,需与微信后台 request 合法域名一致 */ /** 小程序包内编译期写入的请求域名,需与微信后台 request 合法域名一致 */
requestDomain?: string | null; requestDomain?: string | null;
/** 构建参数缺失时的原因,非空表示当前无法构建上传 */ /** 构建参数缺失时的原因,非空表示当前无法构建上传 */
+3 -1
View File
@@ -186,7 +186,7 @@ test("发布检查与发布操作使用当前品牌的管理接口", async () =>
]); ]);
}); });
test("小程序上传配置会提交请求地址", async () => { test("小程序配置会提交请求地址", async () => {
const calls: Array<{ url: string; method?: string; body?: string }> = []; const calls: Array<{ url: string; method?: string; body?: string }> = [];
const client = new ApiClient({ const client = new ApiClient({
baseUrl: "http://api.test", baseUrl: "http://api.test",
@@ -199,6 +199,7 @@ test("小程序上传配置会提交请求地址", async () => {
await client.updateAdminMiniAppSettings({ await client.updateAdminMiniAppSettings({
appId: "wx123", appId: "wx123",
apiBaseUrl: "https://wechat.example.com/api", apiBaseUrl: "https://wechat.example.com/api",
appSecret: "0123456789abcdef0123456789abcdef",
}); });
assert.deepEqual(calls, [ assert.deepEqual(calls, [
{ {
@@ -207,6 +208,7 @@ test("小程序上传配置会提交请求地址", async () => {
body: JSON.stringify({ body: JSON.stringify({
appId: "wx123", appId: "wx123",
apiBaseUrl: "https://wechat.example.com/api", apiBaseUrl: "https://wechat.example.com/api",
appSecret: "0123456789abcdef0123456789abcdef",
}), }),
}, },
]); ]);
@@ -2086,7 +2086,7 @@ export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[
}, },
{ {
"packageKey": "atelier-solopreneur", "packageKey": "atelier-solopreneur",
"version": "1.3.2", "version": "1.3.3",
"displayName": "独立工坊 · 品牌小程序", "displayName": "独立工坊 · 品牌小程序",
"defaultBrandSlug": "atelier-studio", "defaultBrandSlug": "atelier-studio",
"runtimeContract": "1.0", "runtimeContract": "1.0",
@@ -2974,28 +2974,28 @@ export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[
"binding": "offering.name", "binding": "offering.name",
"label": "案例名称", "label": "案例名称",
"input": "text", "input": "text",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectHero"
}, },
{ {
"key": "summary", "key": "summary",
"binding": "offering.summary", "binding": "offering.summary",
"label": "案例简介", "label": "案例简介",
"input": "textarea", "input": "textarea",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectHero"
}, },
{ {
"key": "priceText", "key": "priceText",
"binding": "offering.priceText", "binding": "offering.priceText",
"label": "合作方式 / 报价说明", "label": "合作方式 / 报价说明",
"input": "text", "input": "text",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectFacts"
}, },
{ {
"key": "coverUrl", "key": "coverUrl",
"binding": "offering.coverUrl", "binding": "offering.coverUrl",
"label": "案例封面", "label": "案例封面",
"input": "image", "input": "image",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectHero"
}, },
{ {
"key": "categoryLabel", "key": "categoryLabel",
@@ -3020,49 +3020,49 @@ export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[
"label": "其他服务" "label": "其他服务"
} }
], ],
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectFacts"
}, },
{ {
"key": "detailHero", "key": "detailHero",
"binding": "offering.config.detailHero", "binding": "offering.config.detailHero",
"label": "详情主图", "label": "详情主图",
"input": "image", "input": "image",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectHero"
}, },
{ {
"key": "area", "key": "area",
"binding": "offering.config.area", "binding": "offering.config.area",
"label": "项目地点", "label": "项目地点",
"input": "text", "input": "text",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectFacts"
}, },
{ {
"key": "series", "key": "series",
"binding": "offering.config.series", "binding": "offering.config.series",
"label": "方案名称", "label": "方案名称",
"input": "text", "input": "text",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectFacts"
}, },
{ {
"key": "spaceType", "key": "spaceType",
"binding": "offering.config.spaceType", "binding": "offering.config.spaceType",
"label": "适用场景", "label": "适用场景",
"input": "text", "input": "text",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectFacts"
}, },
{ {
"key": "background", "key": "background",
"binding": "offering.config.details.background", "binding": "offering.config.details.background",
"label": "项目背景", "label": "项目背景",
"input": "textarea", "input": "textarea",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectBackground"
}, },
{ {
"key": "designConcept", "key": "designConcept",
"binding": "offering.config.details.designConcept", "binding": "offering.config.details.designConcept",
"label": "设计理念", "label": "设计理念",
"input": "textarea", "input": "textarea",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectConcept"
}, },
{ {
"key": "keywords", "key": "keywords",
@@ -3076,7 +3076,7 @@ export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[
"label": "关键词" "label": "关键词"
} }
], ],
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectFacts"
}, },
{ {
"key": "crafts", "key": "crafts",
@@ -3090,7 +3090,7 @@ export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[
"label": "交付内容" "label": "交付内容"
} }
], ],
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectCrafts"
}, },
{ {
"key": "materialsList", "key": "materialsList",
@@ -3107,13 +3107,33 @@ export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[
"label": "能力说明" "label": "能力说明"
} }
], ],
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectMaterials"
} }
], ],
"previewTargets": [ "previewTargets": [
{ {
"key": "atelier-solopreneur.detail.projectDetail", "key": "atelier-solopreneur.detail.projectHero",
"label": "案例详情" "label": "案例头图与标题"
},
{
"key": "atelier-solopreneur.detail.projectFacts",
"label": "案例信息"
},
{
"key": "atelier-solopreneur.detail.projectBackground",
"label": "项目背景"
},
{
"key": "atelier-solopreneur.detail.projectConcept",
"label": "设计理念"
},
{
"key": "atelier-solopreneur.detail.projectCrafts",
"label": "交付要点"
},
{
"key": "atelier-solopreneur.detail.projectMaterials",
"label": "能力构成"
} }
] ]
}, },
@@ -6670,4 +6690,4 @@ export const generatedTemplatePackageRegistry: readonly TemplatePackageManifest[
} }
]; ];
export const generatedTemplatePackageRegistryHash = export const generatedTemplatePackageRegistryHash =
"06182e0005339404614b39e2051180d15bc6aa83f572194a7f4b7403650d3e8d"; "866a8ce5f3d22f1712de73d8cae0480a38a71c1949f541ee8b9955695be38f11";
@@ -1,6 +1,6 @@
{ {
"name": "@personal-brand/template-atelier-solopreneur", "name": "@personal-brand/template-atelier-solopreneur",
"version": "1.3.2", "version": "1.3.3",
"private": true, "private": true,
"type": "module", "type": "module",
"files": [ "files": [
@@ -304,7 +304,7 @@ function Detail({ workspace, id }: Props & { id?: string }) {
return ( return (
<View className="atelier-page"> <View className="atelier-page">
<View <View
data-editor-target="atelier-solopreneur.detail.projectDetail" data-editor-target="atelier-solopreneur.detail.projectHero"
data-editor-record-id={item.id} data-editor-record-id={item.id}
> >
{item.image && ( {item.image && (
@@ -314,7 +314,7 @@ function Detail({ workspace, id }: Props & { id?: string }) {
<Text className="atelier-body">{item.desc}</Text> <Text className="atelier-body">{item.desc}</Text>
</View> </View>
<View <View
data-editor-target="atelier-solopreneur.detail.projectDetail" data-editor-target="atelier-solopreneur.detail.projectFacts"
data-editor-record-id={item.id} data-editor-record-id={item.id}
> >
<View className="atelier-card atelier-detail-facts"> <View className="atelier-card atelier-detail-facts">
@@ -347,16 +347,31 @@ function Detail({ workspace, id }: Props & { id?: string }) {
{item.keywords.join(" · ")} {item.keywords.join(" · ")}
</Text> </Text>
</View> </View>
</View>
<View
data-editor-target="atelier-solopreneur.detail.projectBackground"
data-editor-record-id={item.id}
>
<Text className="atelier-heading"> <Text className="atelier-heading">
<Text data-editor-target="atelier-solopreneur.detail.detailCopy"> <Text data-editor-target="atelier-solopreneur.detail.detailCopy">
{p.backgroundTitle} {p.backgroundTitle}
</Text> </Text>
</Text> </Text>
<Text className="atelier-body">{item.details.background}</Text> <Text className="atelier-body">{item.details.background}</Text>
</View>
<View
data-editor-target="atelier-solopreneur.detail.projectConcept"
data-editor-record-id={item.id}
>
<Text className="atelier-heading"> <Text className="atelier-heading">
<Text data-editor-target="atelier-solopreneur.detail.detailCopy">{p.conceptTitle}</Text> <Text data-editor-target="atelier-solopreneur.detail.detailCopy">{p.conceptTitle}</Text>
</Text> </Text>
<Text className="atelier-body">{item.details.designConcept}</Text> <Text className="atelier-body">{item.details.designConcept}</Text>
</View>
<View
data-editor-target="atelier-solopreneur.detail.projectCrafts"
data-editor-record-id={item.id}
>
<Text className="atelier-heading"> <Text className="atelier-heading">
<Text data-editor-target="atelier-solopreneur.detail.detailCopy">{p.craftsTitle}</Text> <Text data-editor-target="atelier-solopreneur.detail.detailCopy">{p.craftsTitle}</Text>
</Text> </Text>
@@ -365,6 +380,11 @@ function Detail({ workspace, id }: Props & { id?: string }) {
{line} {line}
</Text> </Text>
))} ))}
</View>
<View
data-editor-target="atelier-solopreneur.detail.projectMaterials"
data-editor-record-id={item.id}
>
<Text className="atelier-heading"> <Text className="atelier-heading">
<Text data-editor-target="atelier-solopreneur.detail.detailCopy">{p.materialsTitle}</Text> <Text data-editor-target="atelier-solopreneur.detail.detailCopy">{p.materialsTitle}</Text>
</Text> </Text>
@@ -1,6 +1,6 @@
{ {
"packageKey": "atelier-solopreneur", "packageKey": "atelier-solopreneur",
"version": "1.3.2", "version": "1.3.3",
"displayName": "独立工坊 · 品牌小程序", "displayName": "独立工坊 · 品牌小程序",
"defaultBrandSlug": "atelier-studio", "defaultBrandSlug": "atelier-studio",
"runtimeContract": "1.0", "runtimeContract": "1.0",
@@ -883,28 +883,28 @@
"binding": "offering.name", "binding": "offering.name",
"label": "案例名称", "label": "案例名称",
"input": "text", "input": "text",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectHero"
}, },
{ {
"key": "summary", "key": "summary",
"binding": "offering.summary", "binding": "offering.summary",
"label": "案例简介", "label": "案例简介",
"input": "textarea", "input": "textarea",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectHero"
}, },
{ {
"key": "priceText", "key": "priceText",
"binding": "offering.priceText", "binding": "offering.priceText",
"label": "合作方式 / 报价说明", "label": "合作方式 / 报价说明",
"input": "text", "input": "text",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectFacts"
}, },
{ {
"key": "coverUrl", "key": "coverUrl",
"binding": "offering.coverUrl", "binding": "offering.coverUrl",
"label": "案例封面", "label": "案例封面",
"input": "image", "input": "image",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectHero"
}, },
{ {
"key": "categoryLabel", "key": "categoryLabel",
@@ -929,49 +929,49 @@
"label": "其他服务" "label": "其他服务"
} }
], ],
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectFacts"
}, },
{ {
"key": "detailHero", "key": "detailHero",
"binding": "offering.config.detailHero", "binding": "offering.config.detailHero",
"label": "详情主图", "label": "详情主图",
"input": "image", "input": "image",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectHero"
}, },
{ {
"key": "area", "key": "area",
"binding": "offering.config.area", "binding": "offering.config.area",
"label": "项目地点", "label": "项目地点",
"input": "text", "input": "text",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectFacts"
}, },
{ {
"key": "series", "key": "series",
"binding": "offering.config.series", "binding": "offering.config.series",
"label": "方案名称", "label": "方案名称",
"input": "text", "input": "text",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectFacts"
}, },
{ {
"key": "spaceType", "key": "spaceType",
"binding": "offering.config.spaceType", "binding": "offering.config.spaceType",
"label": "适用场景", "label": "适用场景",
"input": "text", "input": "text",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectFacts"
}, },
{ {
"key": "background", "key": "background",
"binding": "offering.config.details.background", "binding": "offering.config.details.background",
"label": "项目背景", "label": "项目背景",
"input": "textarea", "input": "textarea",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectBackground"
}, },
{ {
"key": "designConcept", "key": "designConcept",
"binding": "offering.config.details.designConcept", "binding": "offering.config.details.designConcept",
"label": "设计理念", "label": "设计理念",
"input": "textarea", "input": "textarea",
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectConcept"
}, },
{ {
"key": "keywords", "key": "keywords",
@@ -985,7 +985,7 @@
"label": "关键词" "label": "关键词"
} }
], ],
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectFacts"
}, },
{ {
"key": "crafts", "key": "crafts",
@@ -999,7 +999,7 @@
"label": "交付内容" "label": "交付内容"
} }
], ],
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectCrafts"
}, },
{ {
"key": "materialsList", "key": "materialsList",
@@ -1016,13 +1016,33 @@
"label": "能力说明" "label": "能力说明"
} }
], ],
"previewTarget": "atelier-solopreneur.detail.projectDetail" "previewTarget": "atelier-solopreneur.detail.projectMaterials"
} }
], ],
"previewTargets": [ "previewTargets": [
{ {
"key": "atelier-solopreneur.detail.projectDetail", "key": "atelier-solopreneur.detail.projectHero",
"label": "案例详情" "label": "案例头图与标题"
},
{
"key": "atelier-solopreneur.detail.projectFacts",
"label": "案例信息"
},
{
"key": "atelier-solopreneur.detail.projectBackground",
"label": "项目背景"
},
{
"key": "atelier-solopreneur.detail.projectConcept",
"label": "设计理念"
},
{
"key": "atelier-solopreneur.detail.projectCrafts",
"label": "交付要点"
},
{
"key": "atelier-solopreneur.detail.projectMaterials",
"label": "能力构成"
} }
] ]
}, },
+2
View File
@@ -40,6 +40,8 @@ export function buildRemoteStatusScript({ deployRoot: rootPath = deployRoot } =
'printf "database="; docker inspect -f "{{.State.Status}}" personal-brand-postgres-1', 'printf "database="; docker inspect -f "{{.State.Status}}" personal-brand-postgres-1',
'printf "backups="; find "$DEPLOY_ROOT/shared/backups" -maxdepth 1 -name "*.dump" | wc -l', 'printf "backups="; find "$DEPLOY_ROOT/shared/backups" -maxdepth 1 -name "*.dump" | wc -l',
'printf "latest-backup="; newest=$(find "$DEPLOY_ROOT/shared/backups" -maxdepth 1 -type f -name "*.dump" -printf "%T@ %p\\n" | sort -nr | head -1 | cut -d" " -f2-); test -n "$newest"; stat -c "%y %s bytes" "$newest"; docker exec -i personal-brand-postgres-1 pg_restore -l < "$newest" >/dev/null; echo readable', 'printf "latest-backup="; newest=$(find "$DEPLOY_ROOT/shared/backups" -maxdepth 1 -type f -name "*.dump" -printf "%T@ %p\\n" | sort -nr | head -1 | cut -d" " -f2-); test -n "$newest"; stat -c "%y %s bytes" "$newest"; docker exec -i personal-brand-postgres-1 pg_restore -l < "$newest" >/dev/null; echo readable',
'printf "backup-timer="; systemctl --user is-active personal-brand-backup.timer',
'printf "backup-age-hours="; newest=$(find "$DEPLOY_ROOT/shared/backups" -maxdepth 1 -type f -name "*.dump" -printf "%T@ %p\\n" | sort -nr | head -1 | cut -d" " -f2-); age=$(( ( $(date +%s) - $(stat -c %Y "$newest") ) / 3600 )); echo "$age"; test "$age" -le "${BACKUP_MAX_AGE_HOURS:-36}"',
'printf "backup-temp-files="; find "$DEPLOY_ROOT/shared/backups" -maxdepth 1 -type f -name "*.tmp" | wc -l', 'printf "backup-temp-files="; find "$DEPLOY_ROOT/shared/backups" -maxdepth 1 -type f -name "*.tmp" | wc -l',
'printf "disk="; df -h / | awk \'NR==2 {print $5 " used, " $4 " free"}\'', 'printf "disk="; df -h / | awk \'NR==2 {print $5 " used, " $4 " free"}\'',
'printf "release-count="; find "$DEPLOY_ROOT/releases" -mindepth 1 -maxdepth 1 -type d | wc -l', 'printf "release-count="; find "$DEPLOY_ROOT/releases" -mindepth 1 -maxdepth 1 -type d | wc -l',
+3
View File
@@ -9,6 +9,9 @@ test("生产状态脚本不再要求 VPS 上运行 CI runner", () => {
assert.doesNotMatch(script, /gitea-runner/); assert.doesNotMatch(script, /gitea-runner/);
assert.match(script, /pm2 pid personal-brand-api/); assert.match(script, /pm2 pid personal-brand-api/);
assert.match(script, /pg_restore -l/); assert.match(script, /pg_restore -l/);
assert.match(script, /personal-brand-backup\.timer/);
assert.match(script, /backup-age-hours/);
assert.match(script, /BACKUP_MAX_AGE_HOURS/);
}); });
test("生产状态脚本语法有效", () => { test("生产状态脚本语法有效", () => {