Compare commits

..
Author SHA1 Message Date
que01 083a323c1f feat: 搭建设计生成工作台骨架 2026-10-15 15:54:21 +08:00
431 changed files with 10759 additions and 45361 deletions

No files matched your search

@@ -1,260 +0,0 @@
{
"schemaVersion": 1,
"scope": "模板完成证据登记,保留命令、日志与产物哈希",
"generatedAt": "2026-10-29T05:47:32.979Z",
"templates": {
"acheng-campus-food": {
"real-manifest-interaction": {
"status": "passed",
"commands": [
"pnpm --filter @personal-brand/api test:integration",
"ADMIN_URL=http://localhost:3000 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20-final/api-integration.log",
"sha256": "1efcc2e20c32dc9b42f960a6967a6e94a32aa9e49ca855c17d61b2bc7f6ab891"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20/admin-editor.log",
"sha256": "281c1bba68b5f6e30438d925ea58d8454bd98cf538fab8217710c7dc4402d103"
}
],
"exitCode": 0
},
"save-reload-publish-isolation": {
"status": "passed",
"commands": [
"pnpm --filter @personal-brand/api test:integration"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20-final/api-integration.log",
"sha256": "1efcc2e20c32dc9b42f960a6967a6e94a32aa9e49ca855c17d61b2bc7f6ab891"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20-final/api-unit.log",
"sha256": "8a7a4bbd46be04b7c89318b702886d75acdb3707d9035c789e1d0550fd052b6e"
}
],
"exitCode": 0
},
"visual-reference": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-final ADMIN_URL=http://localhost:3000 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20/template-preview-media.log",
"sha256": "3eb8132e3fae6c95e2820d2979422ab63ab93e52426de8bcd528fd16b36eba3c"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-final/01-acheng-campus-food-food-320.png",
"sha256": "3aa442379e6847eeda18b97df78fadb077f6b678ee09f99d692b8fd357d37422"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-final/01-acheng-campus-food-food-375.png",
"sha256": "a0cc26679391dc851056551dcd5b31f50603bfd0dc44a59bc5182ea377a2747f"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-final/01-acheng-campus-food-food-390.png",
"sha256": "f5d517380140ed62bb306a79fdbf818e1846c7ff58ebf229c2c8ed1142221537"
}
],
"exitCode": 0
},
"empty-error-branches": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-final ADMIN_URL=http://localhost:3000 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts",
"ADMIN_URL=http://localhost:3000 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20/template-preview-media.log",
"sha256": "3eb8132e3fae6c95e2820d2979422ab63ab93e52426de8bcd528fd16b36eba3c"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20/admin-editor.log",
"sha256": "281c1bba68b5f6e30438d925ea58d8454bd98cf538fab8217710c7dc4402d103"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-final/empty-01-acheng-campus-food-food.png",
"sha256": "2a8279db468ab65426f1cf5e13ff8dcffa6ef625bf9f3dd563165b8905a79043"
}
],
"exitCode": 0
}
},
"atelier-solopreneur": {
"real-manifest-interaction": {
"status": "passed",
"commands": [
"pnpm --filter @personal-brand/api test:integration",
"ADMIN_URL=http://localhost:3000 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20-final/api-integration.log",
"sha256": "1efcc2e20c32dc9b42f960a6967a6e94a32aa9e49ca855c17d61b2bc7f6ab891"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20/admin-editor.log",
"sha256": "281c1bba68b5f6e30438d925ea58d8454bd98cf538fab8217710c7dc4402d103"
}
],
"exitCode": 0
},
"save-reload-publish-isolation": {
"status": "passed",
"commands": [
"pnpm --filter @personal-brand/api test:integration"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20-final/api-integration.log",
"sha256": "1efcc2e20c32dc9b42f960a6967a6e94a32aa9e49ca855c17d61b2bc7f6ab891"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20-final/api-unit.log",
"sha256": "8a7a4bbd46be04b7c89318b702886d75acdb3707d9035c789e1d0550fd052b6e"
}
],
"exitCode": 0
},
"visual-reference": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-final ADMIN_URL=http://localhost:3000 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20/template-preview-media.log",
"sha256": "3eb8132e3fae6c95e2820d2979422ab63ab93e52426de8bcd528fd16b36eba3c"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-final/02-atelier-solopreneur-personal-320.png",
"sha256": "e55af9899393c7f9cfba9bb2b5c6ad6c447f90cf28dddd94da8feb6702fc8477"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-final/02-atelier-solopreneur-personal-375.png",
"sha256": "70d251ab829ebfc85dba7fd65ac423272af4af54b39f76d1bea9ebbe0f89bc2d"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-final/02-atelier-solopreneur-personal-390.png",
"sha256": "a430e7c72f794d62f9f0248c52307b6f644ea5b6099ba6c8b929f365504c3b07"
}
],
"exitCode": 0
},
"empty-error-branches": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-final ADMIN_URL=http://localhost:3000 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts",
"ADMIN_URL=http://localhost:3000 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20/template-preview-media.log",
"sha256": "3eb8132e3fae6c95e2820d2979422ab63ab93e52426de8bcd528fd16b36eba3c"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20/admin-editor.log",
"sha256": "281c1bba68b5f6e30438d925ea58d8454bd98cf538fab8217710c7dc4402d103"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-final/empty-02-atelier-solopreneur-personal.png",
"sha256": "78982dd7aa7a8751e29969de9f68c6c3eab0bcdb2403f1a5442f10cc03b9a843"
}
],
"exitCode": 0
}
},
"linjing-editorial": {
"real-manifest-interaction": {
"status": "passed",
"commands": [
"pnpm --filter @personal-brand/api test:integration",
"ADMIN_URL=http://localhost:3000 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20-final/api-integration.log",
"sha256": "1efcc2e20c32dc9b42f960a6967a6e94a32aa9e49ca855c17d61b2bc7f6ab891"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20/admin-editor.log",
"sha256": "281c1bba68b5f6e30438d925ea58d8454bd98cf538fab8217710c7dc4402d103"
}
],
"exitCode": 0
},
"save-reload-publish-isolation": {
"status": "passed",
"commands": [
"pnpm --filter @personal-brand/api test:integration"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20-final/api-integration.log",
"sha256": "1efcc2e20c32dc9b42f960a6967a6e94a32aa9e49ca855c17d61b2bc7f6ab891"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20-final/api-unit.log",
"sha256": "8a7a4bbd46be04b7c89318b702886d75acdb3707d9035c789e1d0550fd052b6e"
}
],
"exitCode": 0
},
"visual-reference": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-final ADMIN_URL=http://localhost:3000 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20/template-preview-media.log",
"sha256": "3eb8132e3fae6c95e2820d2979422ab63ab93e52426de8bcd528fd16b36eba3c"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-final/03-linjing-editorial-doors-320.png",
"sha256": "d1569323ca5514b2348338a4c6f37bc3078c2e827e17943437efe8f437dd1188"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-final/03-linjing-editorial-doors-375.png",
"sha256": "48960348d896631b6c0c788a5528a21e7eefe3339dfffdbff43330c062f7b983"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-final/03-linjing-editorial-doors-390.png",
"sha256": "dd893c5958c3f4165ae988fef7be6882b27ccb3260112676ae296f2e6fef6be6"
}
],
"exitCode": 0
},
"empty-error-branches": {
"status": "passed",
"commands": [
"TEMPLATE_PREVIEW_VISUAL_EVIDENCE=/home/que01/Project/persionalBrand/.codex-tasks/template-audit-execution/raw/visual-matrix-final ADMIN_URL=http://localhost:3000 pnpm --filter @personal-brand/taro exec playwright test test/browser/template-preview-media.spec.ts",
"ADMIN_URL=http://localhost:3000 pnpm --filter @personal-brand/taro exec playwright test test/browser/admin-editor.spec.ts"
],
"artifacts": [
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20/template-preview-media.log",
"sha256": "3eb8132e3fae6c95e2820d2979422ab63ab93e52426de8bcd528fd16b36eba3c"
},
{
"path": ".codex-tasks/template-audit-execution/raw/evidence-2026-10-20/admin-editor.log",
"sha256": "281c1bba68b5f6e30438d925ea58d8454bd98cf538fab8217710c7dc4402d103"
},
{
"path": ".codex-tasks/template-audit-execution/raw/visual-matrix-final/empty-03-linjing-editorial-doors.png",
"sha256": "d7b2b3197e426f1dd9b2ef99cd8682cb4c34531163b8ba5ebc90453438521970"
}
],
"exitCode": 0
}
}
},
"sourceTreeHash": "3f8f7d8b0063a1d21d4cf757d7c1b5ea83c3b3a162fd390183b1cb8e76879907"
}
@@ -1,11 +0,0 @@
Running 2 tests using 1 worker
(node:633537) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:633537) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
✓ 1 test/browser/admin-editor.spec.ts:235:5 › Admin 按通用预览目标筛选字段并同步品牌草稿 (26.4s)
✓ 2 test/browser/admin-editor.spec.ts:637:5 › 林境模板支持首页和主理人区域点选 (27.8s)
2 passed (55.7s)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,18 +0,0 @@
Running 1 test using 1 worker
(node:632552) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:632552) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:632689) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:632799) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:632867) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:632924) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
✓ 1 test/browser/template-preview-media.spec.ts:155:5 › 导入包预览矩阵展示身份、资源和完整媒体槽位 (12.7s)
1 passed (14.2s)
@@ -1,11 +0,0 @@
Running 2 tests using 1 worker
(node:12847) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12847) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
✓ 1 test/browser/admin-editor.spec.ts:235:5 › Admin 按通用预览目标筛选字段并同步品牌草稿 (21.0s)
✓ 2 test/browser/admin-editor.spec.ts:654:5 › 林境模板支持首页和主理人区域点选 (22.2s)
2 passed (44.1s)
File diff suppressed because it is too large. Load diff
@@ -1,18 +0,0 @@
Running 1 test using 1 worker
(node:12338) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12338) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12435) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12543) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12607) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12662) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
✓ 1 test/browser/template-preview-media.spec.ts:155:5 › 导入包预览矩阵展示身份、资源和完整媒体槽位 (9.1s)
1 passed (10.0s)
@@ -1,440 +0,0 @@
> @personal-brand/api@ test /home/que01/Project/persionalBrand/apps/api
> tsx --test test/**/*.test.ts
TAP version 13
# Subtest: 构建 worker 异常退出时返回明确非零结果
ok 1 - 构建 worker 异常退出时返回明确非零结果
---
duration_ms: 80.679734
type: 'test'
...
# Subtest: 构建 worker watchdog 超时会终止子进程并返回 timedOut
ok 2 - 构建 worker watchdog 超时会终止子进程并返回 timedOut
---
duration_ms: 36.587105
type: 'test'
...
# Subtest: 构建进度更新不触发发布状态机的顺序校验
ok 3 - 构建进度更新不触发发布状态机的顺序校验
---
duration_ms: 1.684099
type: 'test'
...
# Subtest: 构建进度更新按品牌隔离,任务不存在时抛出 404
ok 4 - 构建进度更新按品牌隔离,任务不存在时抛出 404
---
duration_ms: 0.989713
type: 'test'
...
# Subtest: 重新构建时可以清除上一次遗留的错误信息
ok 5 - 重新构建时可以清除上一次遗留的错误信息
---
duration_ms: 0.32377
type: 'test'
...
# Subtest: 发布状态机仍拒绝越级变更并允许合法上传流转
ok 6 - 发布状态机仍拒绝越级变更并允许合法上传流转
---
duration_ms: 0.879665
type: 'test'
...
# Subtest: 失败任务重试时可回到 built 并清除错误
ok 7 - 失败任务重试时可回到 built 并清除错误
---
duration_ms: 0.423466
type: 'test'
...
# Subtest: settings presentation never exposes plaintext credentials
ok 8 - settings presentation never exposes plaintext credentials
---
duration_ms: 2.507469
type: 'test'
...
# Subtest: update validates URL and private key before persistence
ok 9 - update validates URL and private key before persistence
---
duration_ms: 2.477873
type: 'test'
...
# Subtest: update encrypts a valid private key and preserves existing settings
ok 10 - update encrypts a valid private key and preserves existing settings
---
duration_ms: 2.609961
type: 'test'
...
# Subtest: upload blocks a currently building task before credentials are read
ok 11 - upload blocks a currently building task before credentials are read
---
duration_ms: 2.803565
type: 'test'
...
# Subtest: upload rejects invalid app configuration before building
ok 12 - upload rejects invalid app configuration before building
---
duration_ms: 0.739001
type: 'test'
...
# Subtest: failed build records logs and build failure state
ok 13 - failed build records logs and build failure state
---
duration_ms: 11.162244
type: 'test'
...
# Subtest: missing artifact records build failure without invoking upload
ok 14 - missing artifact records build failure without invoking upload
---
duration_ms: 1.657659
type: 'test'
...
# Subtest: upload rejects missing credentials before build
ok 15 - upload rejects missing credentials before build
---
duration_ms: 0.580422
type: 'test'
...
# Subtest: local mode reports configuration and returns a relative local upload URL
ok 16 - local mode reports configuration and returns a relative local upload URL
---
duration_ms: 19.254692
type: 'test'
...
# Subtest: upload service validates media type and traversal keys before persistence
ok 17 - upload service validates media type and traversal keys before persistence
---
duration_ms: 5.35153
type: 'test'
...
# Subtest: refactored admin controllers preserve their declared API routes
ok 18 - refactored admin controllers preserve their declared API routes
---
duration_ms: 2.171245
type: 'test'
...
# Subtest: root module composes bounded feature modules only
ok 19 - root module composes bounded feature modules only
---
duration_ms: 0.224672
type: 'test'
...
# Subtest: 创建普通套餐订单时保存价格快照和预计金额
ok 20 - 创建普通套餐订单时保存价格快照和预计金额
---
duration_ms: 3.15675
type: 'test'
...
# Subtest: 普通套餐不能在没有明细时创建
ok 21 - 普通套餐不能在没有明细时创建
---
duration_ms: 1.103406
type: 'test'
...
# Subtest: 客户只能取消自己的 received 订单
ok 22 - 客户只能取消自己的 received 订单
---
duration_ms: 0.528334
type: 'test'
...
# Subtest: 取消不存在或不属于当前客户的订单返回不存在
ok 23 - 取消不存在或不属于当前客户的订单返回不存在
---
duration_ms: 0.329831
type: 'test'
...
# Subtest: 订单状态只能按定义的状态机流转
ok 24 - 订单状态只能按定义的状态机流转
---
duration_ms: 0.789666
type: 'test'
...
# Subtest: 更新订单标签时拒绝其他品牌的标签
ok 25 - 更新订单标签时拒绝其他品牌的标签
---
duration_ms: 0.44106
type: 'test'
...
# Subtest: 开发 seed 引用的本地媒体都有随仓库分发的源文件
ok 26 - 开发 seed 引用的本地媒体都有随仓库分发的源文件
---
duration_ms: 1.65813
type: 'test'
...
# Subtest: 小程序产物根目录锚定仓库根目录,不随 API 进程工作目录变化
ok 27 - 小程序产物根目录锚定仓库根目录,不随 API 进程工作目录变化
---
duration_ms: 1.317639
type: 'test'
...
# Subtest: 按模板包 key 生成唯一的微信小程序产物目录
ok 28 - 按模板包 key 生成唯一的微信小程序产物目录
---
duration_ms: 0.275849
type: 'test'
...
# Subtest: 显式配置的产物根目录按仓库根目录解析相对路径
ok 29 - 显式配置的产物根目录按仓库根目录解析相对路径
---
duration_ms: 0.170942
type: 'test'
...
# Subtest: 发布产物路径隔离品牌、模板版本和 attempt
ok 30 - 发布产物路径隔离品牌、模板版本和 attempt
---
duration_ms: 0.400984
type: 'test'
...
# Subtest: 发布产物路径拒绝可能越界的品牌或模板字段
ok 31 - 发布产物路径拒绝可能越界的品牌或模板字段
---
duration_ms: 0.578859
type: 'test'
...
# Subtest: 后台配置的请求地址优先于环境变量,改域名不需要动服务端配置
ok 32 - 后台配置的请求地址优先于环境变量,改域名不需要动服务端配置
---
duration_ms: 1.515873
type: 'test'
...
# Subtest: 后台地址允许带路径前缀,保存前会去掉结尾斜杠
ok 33 - 后台地址允许带路径前缀,保存前会去掉结尾斜杠
---
duration_ms: 0.593416
type: 'test'
...
# Subtest: 优先使用 MINIAPP_API_BASE_URL,去掉结尾斜杠
ok 34 - 优先使用 MINIAPP_API_BASE_URL,去掉结尾斜杠
---
duration_ms: 0.192292
type: 'test'
...
# Subtest: 没有显式配置时由 PUBLIC_BASE_URL 加默认 /api 推导
ok 35 - 没有显式配置时由 PUBLIC_BASE_URL 加默认 /api 推导
---
duration_ms: 0.18611
type: 'test'
...
# Subtest: 非 https 的公网地址必须被拒绝,避免再次打出 localhost 包
ok 36 - 非 https 的公网地址必须被拒绝,避免再次打出 localhost 包
---
duration_ms: 0.437694
type: 'test'
...
# Subtest: 本地调试地址允许 http,方便开发环境构建
ok 37 - 本地调试地址允许 http,方便开发环境构建
---
duration_ms: 0.195187
type: 'test'
...
# Subtest: AppID 取品牌配置优先,回落 WEAPP_APP_ID,并拒绝占位值
ok 38 - AppID 取品牌配置优先,回落 WEAPP_APP_ID,并拒绝占位值
---
duration_ms: 0.381347
type: 'test'
...
# Subtest: 构建中的任务在超过阈值未更新时视为已中断
ok 39 - 构建中的任务在超过阈值未更新时视为已中断
---
duration_ms: 1.370659
type: 'test'
...
# Subtest: 非 building 状态永远不算中断,避免误伤正常流程
ok 40 - 非 building 状态永远不算中断,避免误伤正常流程
---
duration_ms: 0.278604
type: 'test'
...
# Subtest: 时间戳异常时按未中断处理,宁可挡住重试也不允许并发构建
ok 41 - 时间戳异常时按未中断处理,宁可挡住重试也不允许并发构建
---
duration_ms: 0.20209
type: 'test'
...
# Subtest: 阈值可通过环境变量覆盖,非法值回退到默认 30 分钟
ok 42 - 阈值可通过环境变量覆盖,非法值回退到默认 30 分钟
---
duration_ms: 0.285577
type: 'test'
...
# Subtest: 构建超时阈值支持环境变量并有独立默认值
ok 43 - 构建超时阈值支持环境变量并有独立默认值
---
duration_ms: 0.203984
type: 'test'
...
# Subtest: CommonJS 形态的 miniprogram-ci 从 default 上取 Project 与 upload
ok 44 - CommonJS 形态的 miniprogram-ci 从 default 上取 Project 与 upload
---
duration_ms: 1.180822
type: 'test'
...
# Subtest: 已是命名导出的模块可以直接使用
ok 45 - 已是命名导出的模块可以直接使用
---
duration_ms: 0.218942
type: 'test'
...
# Subtest: 缺少 Project 或 upload 时抛出明确错误,而不是 undefined is not a constructor
ok 46 - 缺少 Project 或 upload 时抛出明确错误,而不是 undefined is not a constructor
---
duration_ms: 0.67514
type: 'test'
...
# Subtest: 单行私钥(换行被输入框吞掉)可以还原为合法 PEM 并恢复签名能力
ok 47 - 单行私钥(换行被输入框吞掉)可以还原为合法 PEM 并恢复签名能力
---
duration_ms: 46.62352
type: 'test'
...
# Subtest: 字面量 \\n 转义的私钥同样可以还原
ok 48 - 字面量 \\n 转义的私钥同样可以还原
---
duration_ms: 35.171352
type: 'test'
...
# Subtest: 规范化是幂等的,不会反复改写已正确的 PEM
ok 49 - 规范化是幂等的,不会反复改写已正确的 PEM
---
duration_ms: 93.585148
type: 'test'
...
# Subtest: 损坏或非 PEM 内容会被判定为无效,而不是静默保存
ok 50 - 损坏或非 PEM 内容会被判定为无效,而不是静默保存
---
duration_ms: 45.896122
type: 'test'
...
# Subtest: 同一任务同一阶段的有效 lease 拒绝并发操作
ok 51 - 同一任务同一阶段的有效 lease 拒绝并发操作
---
duration_ms: 2.956083
type: 'test'
...
# Subtest: 过期 lease 会先收敛为 timed_out,再允许新的 attempt 接管
ok 52 - 过期 lease 会先收敛为 timed_out,再允许新的 attempt 接管
---
duration_ms: 0.652408
type: 'test'
...
# Subtest: 服务进程重建后从持久化记录恢复,并接管已过期的 build attempt
ok 53 - 服务进程重建后从持久化记录恢复,并接管已过期的 build attempt
---
duration_ms: 0.790237
type: 'test'
...
# Subtest: heartbeat 遇到过期上传 lease 时将任务阶段收敛为 timed_out
ok 54 - heartbeat 遇到过期上传 lease 时将任务阶段收敛为 timed_out
---
duration_ms: 0.830002
type: 'test'
...
# Subtest: 错误 lease 不能结束操作,正确 lease 结束上传后更新阶段状态
ok 55 - 错误 lease 不能结束操作,正确 lease 结束上传后更新阶段状态
---
duration_ms: 0.85031
type: 'test'
...
# Subtest: heartbeat 续租并更新日志,结束后的 attempt 拒绝迟到 heartbeat
ok 56 - heartbeat 续租并更新日志,结束后的 attempt 拒绝迟到 heartbeat
---
duration_ms: 1.451821
type: 'test'
...
# Subtest: 执行结束时 lease 已过期会持久化 timed_out,而不是回滚为 running
ok 57 - 执行结束时 lease 已过期会持久化 timed_out,而不是回滚为 running
---
duration_ms: 0.48344
type: 'test'
...
# Subtest: 上传工作目录位于系统临时目录,不会落在仓库内
ok 58 - 上传工作目录位于系统临时目录,不会落在仓库内
---
duration_ms: 1.278095
type: 'test'
...
# Subtest: miniprogram-ci 的相对路径缓存目录落在临时工作目录而不是仓库
ok 59 - miniprogram-ci 的相对路径缓存目录落在临时工作目录而不是仓库
---
duration_ms: 889.708804
type: 'test'
...
# Subtest: 上传会在临时工作目录下启动,失败也不会在仓库留下目录
ok 60 - 上传会在临时工作目录下启动,失败也不会在仓库留下目录
---
duration_ms: 35.854056
type: 'test'
...
# Subtest: 上传在独立进程执行,失败时返回可读错误且不抛出未捕获异常
ok 61 - 上传在独立进程执行,失败时返回可读错误且不抛出未捕获异常
---
duration_ms: 64.635283
type: 'test'
...
# Subtest: 上传超时会终止子进程并返回明确错误
ok 62 - 上传超时会终止子进程并返回明确错误
---
duration_ms: 5.145082
type: 'test'
...
# Subtest: miniprogram-ci compatibility patches keep overridden runtime APIs usable
ok 63 - miniprogram-ci compatibility patches keep overridden runtime APIs usable
---
duration_ms: 681.182262
type: 'test'
...
# Subtest: public default brand context fails fast when configuration is missing
ok 64 - public default brand context fails fast when configuration is missing
---
duration_ms: 2.103899
type: 'test'
...
# Subtest: every API route has an explicit authorization and success coverage contract
ok 65 - every API route has an explicit authorization and success coverage contract
---
duration_ms: 503.725354
type: 'test'
...
# Subtest: preview resources verify raster content and diagnose invalid or oversized assets
ok 66 - preview resources verify raster content and diagnose invalid or oversized assets
---
duration_ms: 84.808494
type: 'test'
...
# Subtest: preview resources reject image checksum drift and unavailable archives
ok 67 - preview resources reject image checksum drift and unavailable archives
---
duration_ms: 63.867568
type: 'test'
...
# Subtest: template preview matrix discovers newly added package manifests
ok 68 - template preview matrix discovers newly added package manifests
---
duration_ms: 14.07272
type: 'test'
...
# Subtest: template preview matrix keeps every deployed package, industry, and version isolated
ok 69 - template preview matrix keeps every deployed package, industry, and version isolated
---
duration_ms: 923.427842
type: 'test'
...
# Subtest: 模板版本按 SemVer 而不是导入时间判断最新版
ok 70 - 模板版本按 SemVer 而不是导入时间判断最新版
---
duration_ms: 1.899655
type: 'test'
...
# Subtest: 模板版本排序正确处理预发布版本和同版本稳定性
ok 71 - 模板版本排序正确处理预发布版本和同版本稳定性
---
duration_ms: 0.468962
type: 'test'
...
1..71
# tests 71
# suites 0
# pass 71
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 2561.461139
@@ -1,11 +0,0 @@
Running 2 tests using 1 worker
(node:297051) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:297051) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
✓ 1 test/browser/admin-editor.spec.ts:235:1 › Admin 按通用预览目标筛选字段并同步品牌草稿 (22.4s)
✓ 2 test/browser/admin-editor.spec.ts:654:1 › 林境模板支持首页和主理人区域点选 (22.9s)
2 passed (46.2s)
@@ -1,16 +0,0 @@
Running 1 test using 1 worker
(node:297457) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:297457) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:297554) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:297665) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:297714) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
(Use `node --trace-warnings ...` to show where the warning was created)
✓ 1 test/browser/template-preview-media.spec.ts:154:1 › 导入包预览矩阵展示身份、资源和完整媒体槽位 (7.0s)
1 passed (7.9s)
File diff suppressed because it is too large. Load diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

+4 -7
View File
@@ -6,31 +6,28 @@ POSTGRES_DB=personal_brand
POSTGRES_PORT=5432 POSTGRES_PORT=5432
API_PORT=3001 API_PORT=3001
API_PREFIX= API_PREFIX=
CORS_ORIGINS=http://localhost:3000
ADMIN_PORT=3000 ADMIN_PORT=3000
SESSION_SECRET=replace-with-a-long-random-value SESSION_SECRET=replace-with-a-long-random-value
# 单实例使用 memory;多实例部署改用 postgres 并先执行数据库迁移
CLIENT_ERROR_THROTTLE_STORE=memory
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001 DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
TEMPLATE_ARTIFACT_ROOT=/var/lib/personal-brand/template-artifacts
SEED_ADMIN_PASSWORD=change-me-now-123 SEED_ADMIN_PASSWORD=change-me-now-123
OBJECT_STORAGE_ENDPOINT=http://localhost:9000 OBJECT_STORAGE_ENDPOINT=http://localhost:9000
OBJECT_STORAGE_PUBLIC_URL=http://localhost:9000/personal-brand-media 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
# 微信 AppID 与 AppSecret 按品牌在后台「小程序配置」维护,不使用全局环境变量 WECHAT_APP_ID=
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
+3 -14
View File
@@ -6,24 +6,12 @@ POSTGRES_PORT=5432
DATABASE_URL=postgresql://personal_brand:replace-with-a-long-database-password@127.0.0.1:5432/personal_brand?schema=public DATABASE_URL=postgresql://personal_brand:replace-with-a-long-database-password@127.0.0.1:5432/personal_brand?schema=public
SESSION_SECRET=replace-with-at-least-32-random-characters SESSION_SECRET=replace-with-at-least-32-random-characters
# 建议单独配置并长期保持不变;未设置时回退 SESSION_SECRET。
# 轮换该密钥后,已保存的上传私钥和 AppSecret 都需要在后台重新填写。
# MINIAPP_CREDENTIAL_ENCRYPTION_KEY=replace-with-32-byte-random-secret
# 单实例使用 memory;多实例部署改用 postgres 并先执行数据库迁移
CLIENT_ERROR_THROTTLE_STORE=memory
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001 DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
SEED_ADMIN_PASSWORD=replace-with-a-one-time-initial-password SEED_ADMIN_PASSWORD=replace-with-a-one-time-initial-password
SEED_MODE=skip SEED_MODE=skip
API_PORT=3001 API_PORT=3001
API_PREFIX= API_PREFIX=
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
@@ -34,9 +22,10 @@ OBJECT_STORAGE_ACCESS_KEY=
OBJECT_STORAGE_SECRET_KEY= OBJECT_STORAGE_SECRET_KEY=
OBJECT_STORAGE_REGION=us-east-1 OBJECT_STORAGE_REGION=us-east-1
# 微信 AppID 与 AppSecret 按品牌在后台「小程序配置」维护,不使用全局环境变量 WECHAT_APP_ID=
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
-178
View File
@@ -1,178 +0,0 @@
name: CI
on:
push:
branches: [main]
# 纯文档提交不占用 runner;需要状态时用 workflow_dispatch 手动触发。
paths-ignore:
- "**.md"
# PR 不设置 paths-ignore:branch protection 的 required checks 必须始终上报,
# 否则纯文档 PR 会永远等不到状态检查而无法合并。
pull_request:
workflow_dispatch:
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
env:
NODE_VERSION: "24"
PNPM_VERSION: "9.15.0"
# runner 任务容器把该路径 bind mount 到宿主机共享 store,避免每个 job 重复下载依赖。
npm_config_store_dir: /workspace/.pnpm-store
jobs:
static:
name: Static checks
runs-on: ubuntu-latest
timeout-minutes: 40
steps:
- uses: actions/checkout@v4
- name: Verify preinstalled toolchain
# 任务镜像已内置 Node 与 pnpm;不在这里下载 Node,避免 nodejs.org 慢连接拖死整个 job。
run: |
actual_node="$(node -p 'process.versions.node')"
actual_pnpm="$(pnpm --version)"
test "${actual_node%%.*}" = "$NODE_VERSION" || { echo "expected Node $NODE_VERSION.x, got $actual_node" >&2; exit 1; }
test "$actual_pnpm" = "$PNPM_VERSION" || { echo "expected pnpm $PNPM_VERSION, got $actual_pnpm" >&2; exit 1; }
- name: Restore Prisma engine cache
uses: actions/cache@v4
with:
path: ~/.cache/prisma
key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
prisma-${{ runner.os }}-${{ runner.arch }}-
- name: Restore Turbo cache
uses: actions/cache@v4
with:
path: .turbo/cache
key: turbo-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }}
restore-keys: |
turbo-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}-
turbo-${{ runner.os }}-${{ runner.arch }}-
- run: pnpm install --frozen-lockfile
- run: pnpm check
- run: pnpm test:api-routes
- run: pnpm test:deploy
- run: pnpm validate:templates
- run: pnpm template:compatibility
- run: pnpm --filter @personal-brand/api exec tsx --test test/template-preview-matrix.test.ts
- run: pnpm template:conformance
- run: pnpm template:doctor
build:
name: Production build
runs-on: ubuntu-latest
timeout-minutes: 60
needs: [static]
steps:
- uses: actions/checkout@v4
- name: Verify preinstalled toolchain
# 任务镜像已内置 Node 与 pnpm;不在这里下载 Node,避免 nodejs.org 慢连接拖死整个 job。
run: |
actual_node="$(node -p 'process.versions.node')"
actual_pnpm="$(pnpm --version)"
test "${actual_node%%.*}" = "$NODE_VERSION" || { echo "expected Node $NODE_VERSION.x, got $actual_node" >&2; exit 1; }
test "$actual_pnpm" = "$PNPM_VERSION" || { echo "expected pnpm $PNPM_VERSION, got $actual_pnpm" >&2; exit 1; }
- name: Restore Prisma engine cache
uses: actions/cache@v4
with:
path: ~/.cache/prisma
key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
prisma-${{ runner.os }}-${{ runner.arch }}-
- name: Restore Turbo cache
uses: actions/cache@v4
with:
path: .turbo/cache
key: turbo-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }}
restore-keys: |
turbo-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}-
turbo-${{ runner.os }}-${{ runner.arch }}-
- run: pnpm install --frozen-lockfile
- run: pnpm build
- run: pnpm build:admin:preview
- run: pnpm validate:template-release
browser-smoke:
name: Browser smoke
# 只在 PR 和手动触发时运行,避免 main 合并后重复消耗共享生产 runner。
if: github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- name: Verify preinstalled toolchain
# 任务镜像已内置 Node 与 pnpm;不在这里下载 Node,避免 nodejs.org 慢连接拖死整个 job。
run: |
actual_node="$(node -p 'process.versions.node')"
actual_pnpm="$(pnpm --version)"
test "${actual_node%%.*}" = "$NODE_VERSION" || { echo "expected Node $NODE_VERSION.x, got $actual_node" >&2; exit 1; }
test "$actual_pnpm" = "$PNPM_VERSION" || { echo "expected pnpm $PNPM_VERSION, got $actual_pnpm" >&2; exit 1; }
- name: Restore Prisma engine cache
uses: actions/cache@v4
with:
path: ~/.cache/prisma
key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
prisma-${{ runner.os }}-${{ runner.arch }}-
- run: pnpm install --frozen-lockfile
- name: Cache Playwright browsers
uses: actions/cache@v4
with:
path: ~/.cache/ms-playwright
key: playwright-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
- name: Install Chromium
# 系统依赖与同版本 Chromium 已预装在 personal-brand-ci:node24 中;这里只做版本兜底。
run: pnpm --filter @personal-brand/taro exec playwright install chromium
- name: Run PR browser smoke
run: pnpm test:browser:smoke
api:
name: API integration
runs-on: ubuntu-latest
timeout-minutes: 45
services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: personal_brand
options: >-
--health-cmd "pg_isready -U postgres -d personal_brand"
--health-interval 5s
--health-timeout 5s
--health-retries 12
env:
DATABASE_URL: postgresql://postgres:postgres@postgres:5432/personal_brand
DEFAULT_BRAND_ID: 00000000-0000-0000-0000-000000000001
SESSION_SECRET: ci-integration-session-secret-0123456789abcdef
SEED_ADMIN_PASSWORD: ci-integration-admin-password
steps:
- uses: actions/checkout@v4
- name: Verify preinstalled toolchain
# 任务镜像已内置 Node 与 pnpm;不在这里下载 Node,避免 nodejs.org 慢连接拖死整个 job。
run: |
actual_node="$(node -p 'process.versions.node')"
actual_pnpm="$(pnpm --version)"
test "${actual_node%%.*}" = "$NODE_VERSION" || { echo "expected Node $NODE_VERSION.x, got $actual_node" >&2; exit 1; }
test "$actual_pnpm" = "$PNPM_VERSION" || { echo "expected pnpm $PNPM_VERSION, got $actual_pnpm" >&2; exit 1; }
- name: Restore Prisma engine cache
uses: actions/cache@v4
with:
path: ~/.cache/prisma
key: prisma-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
prisma-${{ runner.os }}-${{ runner.arch }}-
- run: pnpm install --frozen-lockfile
- name: Prepare API test env
working-directory: apps/api
run: |
cat > .env <<EOF
DATABASE_URL=$DATABASE_URL
DEFAULT_BRAND_ID=$DEFAULT_BRAND_ID
SESSION_SECRET=$SESSION_SECRET
SEED_ADMIN_PASSWORD=$SEED_ADMIN_PASSWORD
EOF
- run: pnpm --filter @personal-brand/api test:integration
-6
View File
@@ -1,6 +0,0 @@
#!/bin/sh
# 提交前让模板完成证据的源码哈希跟随当前工作树,避免额外的 chore 提交。
set -e
[ -f scripts/template-evidence-refresh.mjs ] || exit 0
command -v node >/dev/null 2>&1 || exit 0
node scripts/template-evidence-refresh.mjs --stage
+122
View File
@@ -0,0 +1,122 @@
name: CI
on:
pull_request:
push:
branches: [main]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
static:
name: Static checks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9.15.0
- uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm check
- run: pnpm template:doctor
build:
name: Production build
runs-on: ubuntu-latest
needs: [static]
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9.15.0
- uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm build:admin:preview
- uses: actions/upload-artifact@v4
with:
name: admin-dist
path: apps/admin/dist
retention-days: 7
api:
name: API integration
runs-on: ubuntu-latest
needs: [static]
services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: personal_brand
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres -d personal_brand"
--health-interval 5s
--health-timeout 5s
--health-retries 12
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/personal_brand
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9.15.0
- uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm --filter @personal-brand/api test:integration
browser:
name: Browser regression
runs-on: ubuntu-latest
needs: [build]
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9.15.0
- uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm --filter @personal-brand/taro exec playwright install --with-deps chromium
- run: pnpm --filter @personal-brand/api test:integration
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/personal_brand
- name: Start API
run: pnpm --filter @personal-brand/api start > /tmp/api.log 2>&1 &
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/personal_brand
NODE_ENV: development
- name: Start mini program preview
run: pnpm --filter @personal-brand/taro dev:h5 > /tmp/taro.log 2>&1 &
env:
API_BASE_URL: http://localhost:3001
BRAND_SLUG: default-brand
TEMPLATE_KEY: acheng-campus-food
- name: Start admin
run: pnpm --filter @personal-brand/admin dev > /tmp/admin.log 2>&1 &
env:
VITE_API_BASE_URL: /api
VITE_DEV_API_TARGET: http://localhost:3001
VITE_TEMPLATE_PREVIEW_URL: http://localhost:3002
- name: Wait for services
run: |
curl --retry 30 --retry-delay 1 --retry-connrefused -fsS http://localhost:3001/health
curl --retry 30 --retry-delay 1 --retry-connrefused -fsS http://localhost:3002
curl --retry 30 --retry-delay 1 --retry-connrefused -fsS http://localhost:3000
- run: pnpm --filter @personal-brand/taro exec playwright test --config=playwright.config.ts --reporter=line
-5
View File
@@ -24,10 +24,5 @@ media/
**/.swc/ **/.swc/
.codex-tasks/ .codex-tasks/
!.codex-tasks/template-audit-execution/
!.codex-tasks/template-audit-execution/raw/
!.codex-tasks/template-audit-execution/raw/completion-evidence.json
docker-compose.override.yml docker-compose.override.yml
.env.production .env.production
apps/api/storage/
-1
View File
@@ -8,7 +8,6 @@
- The food template is supported, but it is an example template rather than the product definition. - The food template is supported, but it is an example template rather than the product definition.
- Backend configuration is the source of truth for brand content, services, template selection, trust-building content, and industry-specific fields. The mini program only renders configuration and submits user input. - Backend configuration is the source of truth for brand content, services, template selection, trust-building content, and industry-specific fields. The mini program only renders configuration and submits user input.
- Template packages are the source of truth for template manifests, visual structure, default/sample content, field declarations, assets, and capabilities. Do not copy every template's sample data into Prisma seed or global database tables. A template's sample content may be copied into the database only when an administrator explicitly imports it for one specific brand; the resulting rows are brand content, not template registration. - Template packages are the source of truth for template manifests, visual structure, default/sample content, field declarations, assets, and capabilities. Do not copy every template's sample data into Prisma seed or global database tables. A template's sample content may be copied into the database only when an administrator explicitly imports it for one specific brand; the resulting rows are brand content, not template registration.
- Templates have exactly one active package manifest/runtime contract. Do not add legacy readers, dual-write paths, inferred defaults, aliases, or silent fallbacks. Convert existing persisted data with a one-time, auditable migration that fails on ambiguity, then remove the old representation.
- `apps/api/prisma/seed.ts` may contain a small, explicit development fixture for the seeded demo brands, but it must never become the catalog of all templates or require one seed block per production template. New templates must be discoverable and validated from their package manifest without editing global seed data. - `apps/api/prisma/seed.ts` may contain a small, explicit development fixture for the seeded demo brands, but it must never become the catalog of all templates or require one seed block per production template. New templates must be discoverable and validated from their package manifest without editing global seed data.
- Any delivered backend endpoint must have an automated test covering its authorization and successful behavior before it is considered complete. - Any delivered backend endpoint must have an automated test covering its authorization and successful behavior before it is considered complete.
- Keep personal-brand trust details explicit: biography, positioning, credentials, portfolio/proof, process, expectations, availability, contact methods, and clear follow-up status. - Keep personal-brand trust details explicit: biography, positioning, credentials, portfolio/proof, process, expectations, availability, contact methods, and clear follow-up status.
+84 -150
View File
@@ -1,170 +1,104 @@
# Project Status # Project Status
最后更新:2026-10-21 最后更新:2026-09-19
## 当前目标
先为餐饮摊主朋友交付一个真正能带来订单的个人品牌小程序,再根据真实使用把通用能力产品化。产品方的收益、运营和平台化目标不能牺牲朋友的实际使用效果。
## 当前阶段 ## 当前阶段
系统已从“餐饮试点小程序”演进为多模板个人品牌平台。当前已完成统一模板契约收口、模板完成证据门禁、品牌与页面方案拆分、管理员登录态撤销和 release 版本一致性修复。 后端基础、数据库环境和订单 API 已完成首轮验证,管理后台和小程序静态页面已接入首版结构,下一步进行真实资源与微信登录/预约联调。
ADR 0033 已落地: ## 已完成
- “表达方式”已从 Admin 源码移除。 - 产品 PRD、原型规格、架构决策、数据/API 设计和实施计划。
- “业务类型”和“页面方案”是两个独立概念。 - 餐饮试点画像与首轮需求访谈决策。
- 新增“创建品牌”和“页面方案”页面。 - 可点击低保真原型:`prototype/index.html`。
- 创建品牌不会自动导入示例内容。 - Git 仓库、`main` 分支和远程仓库。
- `linjing-editorial` 只兼容 `doors`,不再兼容 `personal`。 - pnpm workspace + Turborepo Monorepo。
- TypeScript 严格配置、ESLint、Prettier、EditorConfig、环境变量模板。
- NestJS + Fastify API 骨架。
- Prisma PostgreSQL schema:品牌、服务、客户身份、订单、订单明细、标签、管理员。
- 微信官方 `jscode2session` 登录交换边界。
- 客户登录 token、客户订单提交/查询/取消。
- 普通套餐价格快照和私厨需求人工报价模型。
- 管理员账号密码登录和角色 token。
- 管理员订单列表、状态、未读、标签和内部备忘能力。
- DTO 校验、全局异常响应、请求 ID和订单状态流转规则。
- Docker PostgreSQL Compose、seed 和 Prisma 脚本说明。
- 初始 Prisma migration,已在本地 PostgreSQL 应用并验证数据库 schema up to date。
- seed 已写入品牌、服务、标签和管理员数据,并完成数量核验。
- 管理员订单详情、状态/未读/标签筛选和未读数量接口。
- API 自动化业务规则测试:订单创建、客户取消、状态流转和标签品牌隔离,共 6 项通过。
- 修复 ESM 下 `bcryptjs` 导入和 Fastify 请求 ID middleware 的运行时问题。
- API 已通过真实 HTTP 验证:健康检查、公开品牌/服务读取和管理员登录。
- HTTP 集成测试:公开接口、管理员登录、错误密码、管理员权限边界、客户会话、预约 DTO 校验、创建/取消和状态流转,共 8 项通过。
- OpenAPI 3.1 契约:`docs/openapi.yaml`,覆盖当前公开、客户和管理员接口。
- 类型化 `@personal-brand/api-client`:支持公开内容、客户预约、管理员订单和统一错误处理,并有 2 项客户端测试。
- 已根据 `/home/que01/桌面/个人品牌设计图/` 确认 C 端页面视觉规范:暖白、米黄、砖红、深炭黑,16px 卡片圆角和大字号优先。
- 小程序已完成首页、服务列表、预约套餐和我的订单静态页面,页面标题使用微信原生导航栏。
- 已配置小程序 AppID:`wxd75d946d6978d183`。
- 服务分类、预约数量步进器、订单状态卡和底部导航已按设计图完成首版还原。
- 已执行多轮 Codex 代码审查并修复关键认证和权限问题。
## 当前能力 ## 最近提交
- NestJS + Fastify API、Prisma PostgreSQL、全局 DTO 校验、统一错误响应和 `requestId`。
- 多品牌 Admin、品牌 membership、角色边界、品牌切换和品牌隔离。
- 创建品牌时按业务类型筛选兼容的页面方案;不兼容组合无法提交。
- 模板包发现、确定性打包、导入、校验、发布、预览、安装、升级和回滚。
- 三套已交付模板及其业务类型:
- `acheng-campus-food@1.0.3`:`food`
- `atelier-solopreneur@1.3.2`:`personal`
- `linjing-editorial@1.0.7`:`doors`
- Taro Runtime、Admin 组件预览、真实 manifest 驱动编辑、草稿/发布隔离。
- 发布备注为可选字段;空备注不会写入数据库,也不影响发布、回滚和公开内容。
- 依赖 override 的运行时兼容性通过 `miniprogram-ci` / Jimp / image-size / uuid smoke test 守卫。
- Gitea Actions CI 已在 `oracle_arm` 自托管 runner 上落地,`static` / `build` / `api` 三个 job 已完整通过(run 21);详见 `docs/ci.md`。
- 小程序构建、上传任务状态机、attempt lease 和失败记录。
- Admin/Customer token version:修改 admin 密码或调用 logout 后旧 token 立即失效;无 membership 的账号不会自动获得 owner 权限。
- `visualPresentation` 已进入唯一 `template.json` 契约,旧手写 visual manifest 优先路径已删除。
## 生产状态
当前生产 release:
```text ```text
20261023100112-a2fa6c3c3140 fee3c77 fix: 按设计图优化预约套餐数量和商品卡
13ead2d fix: 对齐服务分类和订单视觉结构
255756c feat: 增加小程序品牌首页
本次工作:数据库初始化、订单管理接口、业务规则测试和运行时修复
f2687c5 chore: prepare portable postgres development environment
0e8b8e1 feat: add api http conventions and booking state rules
0d4caab feat: add admin order tags and read state
bb5ccb1 feat: add admin authentication
b89853b fix: harden api authentication and validation
``` ```
该 release 由提交 `a2fa6c3` 构建,新增生产数据库每日定时备份、备份可读性校验、发布/定时备份保留策略、`backup-timer` 与 `backup-age-hours` 部署状态门禁。部署后已手动触发一次 `personal-brand-backup.service`,生成 `scheduled-20261023T100426Z-1029929.dump`,并通过 `pg_restore -l` 校验可读。 远程:`https://git.app.que01.top/que01/persionalBrand.git`
生产健康检查: ## 下一步优先级
```text 1. 接入真实品牌图片、电话和微信配置,并替换当前图片占位区域。
api=online 2. 在微信开发者工具/真机完成 `wx.login`、预约提交、订单查询和取消联调。
pm2-autostart=enabled 3. 完善管理后台订单详情、筛选和状态处理视觉页面。
admin=active 4. 继续补充页面截图回归和真实素材下的移动端溢出检查。
database=running
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 - 微信小程序主体、AppID、服务类目和订阅消息模板是否可用。
/admin/ 200 - 生产部署使用哪家 PostgreSQL、对象存储和 API 托管服务。
/template-preview/ 200 - 当前 token 是开发阶段的签名 Bearer token;生产前应替换为带撤销能力的正式 session/Cookie 方案。
/api/health 200
/media/seed/food-package-02.jpg 200 ## 当前明确不做
/admin/client-errors(无登录态) 401
- 支付、退款、发票、财务对账。
- 复杂库存、自动配送判断和每日菜单编排。
- 多商户注册、套餐计费、会员和营销系统。
- 自动发布微信小程序。
## 跨电脑恢复
```bash
git clone https://git.app.que01.top/que01/persionalBrand.git
cd persionalBrand
cat PROJECT_STATUS.md
cat agent.md
cp .env.example .env
``` ```
生产数据库已应用全部 48 个 Prisma migration,schema 为 up to date。 有 Docker 的机器再执行:
三个生产品牌的当前发布快照: ```bash
docker compose up -d postgres
| 品牌 | 业务类型 | 页面方案 | 发布版本 | pnpm install
| ---------------- | ---------- | --------------------------- | ------------ | pnpm db:migrate
| `atelier-studio` | `personal` | `atelier-solopreneur@1.3.2` | `v2 current` | pnpm db:seed
| `default-brand` | `food` | `acheng-campus-food@1.0.3` | `v2 current` |
| `linjing-doors` | `doors` | `linjing-editorial@1.0.7` | `v3 current` |
## 完成证据
`.codex-tasks/template-audit-execution/raw/completion-evidence.json` 登记四类证据:
- `real-manifest-interaction`
- `save-reload-publish-isolation`
- `visual-reference`
- `empty-error-branches`
每条证据保留执行命令、日志和产物 SHA-256。`pnpm template:doctor` 会校验证据覆盖和哈希;当前三套模板均为:
```text
staticStatus=pass
completionStatus=complete
unresolvedIssues=0
``` ```
Admin 浏览器回归新增 `apps/taro/test/browser/brand-creation-and-page-scheme.spec.ts`,覆盖: ## 更新规则
- 创建品牌时按业务类型筛选页面方案。 每完成一个可验证的开发任务,更新“当前阶段”“已完成”“最近提交”和“下一步优先级”。只记录已经发生或已经确认的事实;未确认内容放入“未决问题”。
- `personal` 不出现林境页面方案。
- 切换业务类型后清除不兼容的页面方案选择,提交按钮禁用。
- 创建失败时保留用户输入并显示错误。
- 页面方案切换和升级提交正确版本、校验和与冲突保留参数。
- 操作成功后刷新工作区、页面方案选项和升级预览查询。
`apps/taro/test/browser/publication-release.spec.ts` 覆盖内容与发布流程:
- 发布按钮按 readiness 启用;空备注发布提交空 body,不写入 `note`。
- 备注提交前去除首尾空格。
- 发布失败时保留备注与确认弹窗,并显示服务端错误。
- 撤回当前版本、恢复历史版本分别提交正确路径与版本号。
- 小程序配置页从服务端回填设置,只提交用户新输入的私钥。
该回归同时发现并修复了 `MiniAppSettingsTab` 的 `Form` 实例归属问题:表单实例原本在父组件创建、子组件懒挂载,触发 antd `useForm` 未连接警告;现已下沉到配置页自身。
## Admin 渲染错误边界
后台此前没有任何 React error boundary:任一页面在渲染阶段抛错(例如接口返回了形状不符的数据)都会导致整页白屏,用户只能从控制台看到堆栈。现在按两级兜底:
- `Root` 上的整页边界:后台外壳自身渲染失败时显示错误页,提供「重新加载页面」和「返回概览」。
- `Dashboard` 内容区的页面边界:单个业务页面失败时保留侧边栏与顶部导航,提供「重试」和「重新加载页面」,切换路由后自动复位。
- 错误页展示可复制的错误编号,日志侧输出同一编号、堆栈与组件栈,便于把用户反馈和服务器日志对应起来。
- 开发环境额外显示原始错误信息;生产环境不暴露堆栈。
外壳数据不再直接信任接口形状:`apps/admin/src/lib/brand-switcher.ts` 只接受完整成员记录,跳过异常条目并对重复品牌、缺失名称和非字符串品牌名做稳定收敛,避免单条脏数据让整个后台外壳崩溃。错误边界只作为最后一道防线。
`apps/taro/test/browser/admin-error-boundary.spec.ts` 覆盖:
- 品牌成员与品牌名称返回异常结构时,后台外壳仍正常渲染。
- 业务页面数据异常时保留导航,重试仍失败保持错误页,重新加载后恢复。
`apps/admin/test/brand-switcher.test.mjs` 覆盖选项转换的异常条目、非数组、重复品牌、缺失名称与非字符串名称。
## Ant Design 6 弃用项
- `Alert` 统一使用 `title`,`Space` 统一使用 `orientation`。
- 提示与确认框改为 `App.useApp()` 实例,删除静态 `message` 转出口 `components/AdminMessage.ts`。
- `apps/admin/test/antd-deprecations.test.mjs` 作为静态门禁,阻止静态 `message`、`Modal.confirm`、`Alert.message`、`Space.direction` 回流。
- `List` 仍保留:`Listy` 是虚拟滚动组件,API 不兼容,当前仅用于小数据量场景;已记录在 `docs/adr/0034-antd6-static-api-and-list.md`,升级 Ant Design 7 前重新评估。
## 已验证门禁
- `pnpm check`
- `pnpm validate:template-release`
- `pnpm --filter @personal-brand/api test`
- `pnpm --filter @personal-brand/api test:integration`
- `miniprogram-ci` override 兼容 smoke test
- `pnpm test:api-client`
- `pnpm test:deploy`
- `pnpm --filter @personal-brand/admin typecheck`
- `pnpm --filter @personal-brand/admin lint`
- `pnpm --filter @personal-brand/admin test`
- `pnpm --filter @personal-brand/admin build`
- `pnpm build`
- `pnpm template:doctor`
- Playwright:
- `brand-creation-and-page-scheme.spec.ts`
- `publication-release.spec.ts`
- `admin-error-boundary.spec.ts`
- `template-preview-media.spec.ts`
- `admin-editor.spec.ts`
发布脚本的 Node 版本门禁已提前到所有构建之前。Node 22 下执行 `pnpm deploy:release` 会立即失败,并给出 Node.js 24 要求提示,不再先执行一轮无用构建。
## 安全审计
- `pnpm audit --prod --registry=https://registry.npmjs.org` 已完成。
- 可修复 advisory 已通过 `pnpm.overrides` 收敛;`request` 替换为 `@cypress/request@4.0.1`。
- 剩余 8 条为 `miniprogram-ci@2.1.31` 无修复版本的上游 advisory,已在 `pnpm.auditConfig.ignoreGhsas` 和 `docs/security-audit.md` 中显式登记风险、控制措施与跟进条件。
- Taro 官方 peer 仍声明 Vite 4;当前使用 Vite 6.4.3,H5 与 Weapp 实际构建均通过,peer warning 记录在安全审计文档。
## 未决事项
- `miniprogram-ci` 上游发布修复版本后,需要移除对应的 audit ignore、风险登记和本地 patch。
- Gitea SSH 直连仍受 OCI 安全列表限制;当前本机通过 `oracle_arm` ProxyCommand 转发访问,不阻塞业务。
- CI 已加入 audit 和三套模板矩阵构建;后续可继续拆分更细粒度的 smoke/visual matrix。
+13 -15
View File
@@ -270,21 +270,19 @@
以下为各页面的视觉结构约定,业务逻辑不变。 以下为各页面的视觉结构约定,业务逻辑不变。
| 页面 | 结构要点 | | 页面 | 结构要点 |
| -------------- | ---------------------------------------------------------------------------------------------------------------------- | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| 登录 | 居中 400px 卡片,标识 + 说明 + 表单 + 通栏主按钮;错误态展示在字段下方 | | 登录 | 居中 400px 卡片,标识 + 说明 + 表单 + 通栏主按钮;错误态展示在字段下方 |
| 首次改密 | 同登录卡片形态,说明文案 + 三个密码字段 + 「保存新密码」 | | 首次改密 | 同登录卡片形态,说明文案 + 三个密码字段 + 「保存新密码」 |
| 品牌概览 | 品牌卡 + 三张指标卡(等宽一行)+ 两栏(发布准备度 / 品牌内容检查) | | 品牌概览 | 品牌卡 + 三张指标卡(等宽一行)+ 两栏(发布准备度 / 品牌内容检查) |
| 内容与发布 | 内容发布 / 小程序发布 / 小程序配置三个分区;内容发布含发布状态卡、草稿卡和历史版本表,不承载业务类型或页面方案选择 | | 配置与发布 | 三 Tab(内容发布 / 小程序发布 / 小程序配置);内容发布含「选择表达方式」(行业模板 + 视觉模板 + 版本升级/回滚)+ 发布状态卡 + 草稿卡 + 历史版本表 |
| 页面方案 | 当前业务类型与页面方案 + 升级预览 + 版本选择 + 配置恢复 + 高级示例内容导入 | | 小程序页面 | 左右两栏:左 380px 编辑面板,右预览画布;预览内选中区域虚线高亮 + 区域名气泡 |
| 品牌管理 | 品牌列表与创建入口;创建品牌先选不可变的业务类型,再选兼容页面方案,创建时不导入示例内容 | | 信任内容 | 列表行(类型图标或配图 + 标题 + 发布状态标签 + 类型/展示位置说明 + 两行摘要 + 行内操作),按模板类型顺序排列,不用表格 |
| 小程序页面 | 左右两栏:左 380px 编辑面板,右预览画布;预览内选中区域虚线高亮 + 区域名气泡 | | 业务提供项 | 表格(名称 / 价格 / 状态开关 / 排序 / 操作)+ 新增弹窗 |
| 信任内容 | 列表行(类型图标或配图 + 标题 + 发布状态标签 + 类型/展示位置说明 + 两行摘要 + 行内操作),按模板类型顺序排列,不用表格 | | 咨询记录 | 顶部三指标 + 左 380px 列表 + 右详情的主从布局 |
| 业务提供项 | 表格(名称 / 价格 / 状态开关 / 排序 / 操作)+ 新增弹窗 | | 咨询表单与字段 | 咨询表单表(名称 / 版本 / 字段数 / 状态 / 操作)+ 新增与编辑弹窗(含选项编辑);高级自定义字段表 + 新增弹窗 |
| 咨询记录 | 顶部三指标 + 左 380px 列表 + 右详情的主从布局 | | 能力插件 | 插件卡片列表(图标 + 名称 + 说明 + 开关),停用态降低对比度 |
| 咨询表单与字段 | 咨询表单表(名称 / 版本 / 字段数 / 状态 / 操作)+ 新增与编辑弹窗(含选项编辑);高级自定义字段表 + 新增弹窗 | | 团队成员 | 表格(成员 / 角色 / 状态 / 最近登录 / 操作)+ 邀请弹窗 |
| 能力插件 | 插件卡片列表(图标 + 名称 + 说明 + 开关),停用态降低对比度 |
| 团队成员 | 表格(成员 / 角色 / 状态 / 最近登录 / 操作)+ 邀请弹窗 |
两栏页面在小屏下折叠为单列,编辑/预览改为上下排列。 两栏页面在小屏下折叠为单列,编辑/预览改为上下排列。
-4
View File
@@ -3,10 +3,6 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" /> <meta name="viewport" content="width=device-width,initial-scale=1" />
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; img-src 'self' data: blob:; media-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src 'self' ws: wss:; script-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'"
/>
<title>个人品牌后台</title> <title>个人品牌后台</title>
</head> </head>
<body> <body>
-15
View File
@@ -1,15 +0,0 @@
import { createElement, type ReactNode } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
export function AdminOverviewRedirect() {
return createElement(Navigate, { to: "/admin/overview", replace: true });
}
export function AdminRouter({ children }: { children: ReactNode }) {
return createElement(
Routes,
null,
createElement(Route, { path: "/admin/*", element: children }),
createElement(Route, { path: "*", element: createElement(AdminOverviewRedirect) }),
);
}
+36 -69
View File
@@ -4,11 +4,9 @@ import {
BarsOutlined, BarsOutlined,
CloudUploadOutlined, CloudUploadOutlined,
FormOutlined, FormOutlined,
LayoutOutlined,
MessageOutlined, MessageOutlined,
MobileOutlined, MobileOutlined,
SafetyCertificateOutlined, SafetyCertificateOutlined,
ShopOutlined,
TeamOutlined, TeamOutlined,
ThunderboltOutlined, ThunderboltOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
@@ -18,42 +16,25 @@ import { BrandMark } from "../components/BrandMark.js";
import { StatusTag } from "../components/StatusTag.js"; import { StatusTag } from "../components/StatusTag.js";
import { import {
FeatureBrandPage, FeatureBrandPage,
FeatureBrandsPage,
FeatureCapabilitiesPage, FeatureCapabilitiesPage,
FeatureCreateBrandPage,
FeatureInquiriesPage, FeatureInquiriesPage,
FeatureMembersPage, FeatureMembersPage,
FeatureOverviewPage, FeatureOverviewPage,
FeaturePageSchemePage,
FeaturePublicationPage, FeaturePublicationPage,
FeatureTemplateManagementPage,
FeatureServicesPage, FeatureServicesPage,
FeatureTrustContentPage, FeatureTrustContentPage,
FeatureWorkspacePage, FeatureWorkspacePage,
} from "./routes.js"; } from "./routes.js";
import { LoadingStack } from "../components/LoadingStack.js"; import { LoadingStack } from "../components/LoadingStack.js";
import { AdminMenu } from "../components/AdminMenu.js"; import { AdminMenu } from "../components/AdminMenu.js";
import { App } from "antd"; import { adminMessage as message } from "../components/AdminMessage.js";
import { AdminButton } from "../components/AdminButton.js"; import { AdminButton } from "../components/AdminButton.js";
import { AdminSelect } from "../components/AdminSelect.js"; import { AdminSelect } from "../components/AdminSelect.js";
import { AdminLayout } from "../components/AdminLayout.js"; import { AdminLayout } from "../components/AdminLayout.js";
import { Route, Routes } from "react-router-dom"; import { Navigate, Route, Routes } from "react-router-dom";
import { AdminOverviewRedirect } from "./AdminRouter.js";
import { createBrandRouteElement } from "./route-access.js";
import { Suspense } from "react"; import { Suspense } from "react";
import { AdminErrorBoundary } from "../components/AdminErrorBoundary.js";
import { toBrandDisplayName, toBrandSwitcherOptions } from "../lib/brand-switcher.js";
export function Dashboard({ export function Dashboard({ onLogout, role }: { onLogout: () => void; role: string }) {
onLogout,
role,
platformTemplateRole,
}: {
onLogout: () => void;
role: string;
platformTemplateRole: "none" | "template_admin";
}) {
const { message } = App.useApp();
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
const brand = useQuery({ const brand = useQuery({
@@ -66,22 +47,21 @@ export function Dashboard({
}); });
const switchBrand = async (brandId: string) => { const switchBrand = async (brandId: string) => {
try { try {
await createApiClient().switchAdminBrand(brandId); const result = await createApiClient().switchAdminBrand(brandId);
localStorage.setItem("adminToken", result.token);
window.location.reload(); window.location.reload();
} catch (error) { } catch (error) {
message.error(error instanceof Error ? error.message : "品牌切换失败"); message.error(error instanceof Error ? error.message : "品牌切换失败");
} }
}; };
const page = location.pathname.split("/")[2] || "overview"; const page = location.pathname.split("/")[2] || "overview";
const brandName = toBrandDisplayName(brand.data?.name, "当前品牌");
const brandOptions = toBrandSwitcherOptions(memberships.data);
const items = [ const items = [
{ {
type: "group" as const, type: "group" as const,
label: "日常经营", label: "日常经营",
children: [ children: [
{ key: "overview", label: "当前品牌概览", icon: <AppstoreOutlined /> }, { key: "overview", label: "当前品牌概览", icon: <AppstoreOutlined /> },
{ key: "publication", label: "内容与发布", icon: <CloudUploadOutlined /> }, { key: "publication", label: "配置与发布", icon: <CloudUploadOutlined /> },
{ key: "brand", label: "小程序页面", icon: <MobileOutlined /> }, { key: "brand", label: "小程序页面", icon: <MobileOutlined /> },
{ key: "trust", label: "信任内容", icon: <SafetyCertificateOutlined /> }, { key: "trust", label: "信任内容", icon: <SafetyCertificateOutlined /> },
{ key: "services", label: "业务提供项", icon: <BarsOutlined /> }, { key: "services", label: "业务提供项", icon: <BarsOutlined /> },
@@ -94,15 +74,10 @@ export function Dashboard({
: [ : [
{ {
type: "group" as const, type: "group" as const,
label: "品牌设置", label: "系统管理",
children: [ children: [
{ key: "brands", label: "品牌管理", icon: <ShopOutlined /> },
{ key: "page-scheme", label: "页面方案", icon: <LayoutOutlined /> },
{ key: "capabilities", label: "能力插件", icon: <ThunderboltOutlined /> }, { key: "capabilities", label: "能力插件", icon: <ThunderboltOutlined /> },
{ key: "members", label: "团队成员", icon: <TeamOutlined /> }, { key: "members", label: "团队成员", icon: <TeamOutlined /> },
...(platformTemplateRole === "template_admin"
? [{ key: "templates", label: "模板管理", icon: <AppstoreOutlined /> }]
: []),
], ],
}, },
]), ]),
@@ -111,7 +86,7 @@ export function Dashboard({
<AdminLayout className="admin-shell"> <AdminLayout className="admin-shell">
<AdminLayout.Sider className="admin-sider" breakpoint="lg" collapsedWidth={0} width={232}> <AdminLayout.Sider className="admin-sider" breakpoint="lg" collapsedWidth={0} width={232}>
<div className="admin-sider-brand"> <div className="admin-sider-brand">
<BrandMark name={toBrandDisplayName(brand.data?.name, "")} /> <BrandMark name={brand.data?.name} />
<span className="admin-sider-brand-name">品牌工作区</span> <span className="admin-sider-brand-name">品牌工作区</span>
</div> </div>
<AdminMenu <AdminMenu
@@ -123,7 +98,7 @@ export function Dashboard({
<AdminLayout className="admin-main"> <AdminLayout className="admin-main">
<AdminLayout.Header className="admin-header"> <AdminLayout.Header className="admin-header">
<div className="admin-header-left"> <div className="admin-header-left">
<span className="admin-header-brand">{brandName}</span> <span className="admin-header-brand">{brand.data?.name || "当前品牌"}</span>
<span className="admin-header-context">品牌工作区</span> <span className="admin-header-context">品牌工作区</span>
<StatusTag <StatusTag
tone={role === "owner" ? "info" : "neutral"} tone={role === "owner" ? "info" : "neutral"}
@@ -135,10 +110,13 @@ export function Dashboard({
className="admin-brand-switcher" className="admin-brand-switcher"
value={brand.data?.id} value={brand.data?.id}
loading={memberships.isLoading} loading={memberships.isLoading}
onChange={(value: string | undefined) => { onChange={(value) => {
if (value) void switchBrand(value); if (value) void switchBrand(value);
}} }}
options={brandOptions} options={(memberships.data ?? []).map((item) => ({
value: item.brand.id,
label: item.brand.name,
}))}
/> />
</div> </div>
<AdminButton type="text" onClick={onLogout}> <AdminButton type="text" onClick={onLogout}>
@@ -147,39 +125,28 @@ export function Dashboard({
</AdminLayout.Header> </AdminLayout.Header>
<AdminLayout.Content className="admin-content"> <AdminLayout.Content className="admin-content">
<div className="admin-content-inner"> <div className="admin-content-inner">
<AdminErrorBoundary key={location.pathname}> <Suspense fallback={<LoadingStack />}>
<Suspense fallback={<LoadingStack />}> <Routes>
<Routes> <Route path="/" element={<Navigate to="overview" replace />} />
<Route index element={<AdminOverviewRedirect />} /> <Route path="overview" element={<FeatureOverviewPage />} />
<Route path="overview" element={<FeatureOverviewPage />} /> <Route
<Route path="publication" element={<FeaturePublicationPage />} /> path="publication"
<Route path="brand" element={<FeatureBrandPage />} /> element={<FeaturePublicationPage canManageTemplate={role !== "editor"} />}
<Route path="trust" element={<FeatureTrustContentPage />} /> />
<Route path="services" element={<FeatureServicesPage />} /> <Route path="brand" element={<FeatureBrandPage />} />
<Route path="inquiries" element={<FeatureInquiriesPage />} /> <Route path="trust" element={<FeatureTrustContentPage />} />
<Route path="workspace" element={<FeatureWorkspacePage />} /> <Route path="services" element={<FeatureServicesPage />} />
{role === "editor" ? null : ( <Route path="inquiries" element={<FeatureInquiriesPage />} />
<> <Route path="workspace" element={<FeatureWorkspacePage />} />
<Route {role === "editor" ? null : (
path="brands" <>
element={<FeatureBrandsPage canCreate={role === "owner"} />} <Route path="capabilities" element={<FeatureCapabilitiesPage />} />
/> <Route path="members" element={<FeatureMembersPage />} />
<Route </>
path="brands/new" )}
element={createBrandRouteElement(role, <FeatureCreateBrandPage />)} <Route path="*" element={<Navigate to="overview" replace />} />
/> </Routes>
<Route path="page-scheme" element={<FeaturePageSchemePage />} /> </Suspense>
<Route path="capabilities" element={<FeatureCapabilitiesPage />} />
<Route path="members" element={<FeatureMembersPage />} />
{platformTemplateRole === "template_admin" ? (
<Route path="templates" element={<FeatureTemplateManagementPage />} />
) : null}
</>
)}
<Route path="*" element={<AdminOverviewRedirect />} />
</Routes>
</Suspense>
</AdminErrorBoundary>
</div> </div>
</AdminLayout.Content> </AdminLayout.Content>
</AdminLayout> </AdminLayout>
+19 -68
View File
@@ -1,87 +1,38 @@
import React, { useState } from "react"; import React, { useState } from "react";
import type { AdminSession } from "@personal-brand/api-client";
import { ChangePassword, Login } from "../features/auth/AuthPages.js"; import { ChangePassword, Login } from "../features/auth/AuthPages.js";
import { Dashboard } from "./Dashboard.js"; import { Dashboard } from "./Dashboard.js";
import { AdminRouter } from "./AdminRouter.js"; import { adminMessage as message } from "../components/AdminMessage.js";
import { App } from "antd";
import { createApiClient } from "../lib/api.js";
import { LoadingStack } from "../components/LoadingStack.js";
import { AdminErrorBoundary } from "../components/AdminErrorBoundary.js";
type SessionState = Omit<AdminSession, "authenticated">;
export function Root() { export function Root() {
const { message } = App.useApp(); const [loggedIn, setLoggedIn] = useState(Boolean(localStorage.getItem("adminToken")));
const [session, setSession] = useState<SessionState | null>(null); const [role, setRole] = useState(localStorage.getItem("adminRole") || "owner");
const [loading, setLoading] = useState(true); const [mustChangePassword, setMustChangePassword] = useState(
localStorage.getItem("adminMustChangePassword") === "true",
React.useEffect(() => { );
let active = true;
createApiClient()
.getAdminSession()
.then((current) => {
if (active) setSession(current);
})
.catch(() => {
if (active) setSession(null);
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, []);
React.useEffect(() => { React.useEffect(() => {
const expire = () => { const expire = () => {
message.warning("登录状态已失效,请重新登录"); message.warning("登录状态已失效,请重新登录");
setSession(null); setLoggedIn(false);
}; };
window.addEventListener("admin-auth-expired", expire); window.addEventListener("admin-auth-expired", expire);
return () => window.removeEventListener("admin-auth-expired", expire); return () => window.removeEventListener("admin-auth-expired", expire);
}, []); }, []);
const logout = () => {
const logout = async () => { localStorage.removeItem("adminToken");
try { localStorage.removeItem("adminRole");
await createApiClient().logoutAdmin(); localStorage.removeItem("adminMustChangePassword");
} catch { setLoggedIn(false);
message.warning("已退出本地会话;服务端撤销请求未完成");
} finally {
setSession(null);
}
}; };
if (!loggedIn)
if (loading) return <LoadingStack />;
if (!session)
return ( return (
<Login <Login
onLogin={(current) => { onLogin={(session) => {
setSession(current); setRole(session.role);
setMustChangePassword(session.mustChangePassword);
setLoggedIn(true);
}} }}
/> />
); );
if (session.mustChangePassword) if (mustChangePassword) return <ChangePassword onComplete={() => setMustChangePassword(false)} />;
return ( return <Dashboard onLogout={logout} role={role} />;
<ChangePassword
onComplete={async () => {
try {
setSession(await createApiClient().getAdminSession());
} catch {
setSession(null);
}
}}
/>
);
return (
<AdminErrorBoundary variant="page">
<AdminRouter>
<Dashboard
onLogout={logout}
role={session.role}
platformTemplateRole={session.platformTemplateRole}
/>
</AdminRouter>
</AdminErrorBoundary>
);
} }
-14
View File
@@ -1,14 +0,0 @@
import { createElement, type ReactNode } from "react";
import { Navigate } from "react-router-dom";
export const createBrandFallbackPath = "/admin/brands";
export function canCreateBrand(role: string) {
return role === "owner";
}
export function createBrandRouteElement(role: string, content: ReactNode) {
return canCreateBrand(role)
? content
: createElement(Navigate, { to: createBrandFallbackPath, replace: true });
}
-20
View File
@@ -43,23 +43,3 @@ export const FeaturePublicationPage = React.lazy(() =>
default: module.PublicationPage, default: module.PublicationPage,
})), })),
); );
export const FeatureTemplateManagementPage = React.lazy(() =>
import("../features/template-management/TemplateManagementPage.js").then((module) => ({
default: module.TemplateManagementPage,
})),
);
export const FeatureBrandsPage = React.lazy(() =>
import("../features/brands/BrandsPage.js").then((module) => ({
default: module.BrandsPage,
})),
);
export const FeatureCreateBrandPage = React.lazy(() =>
import("../features/brands/CreateBrandPage.js").then((module) => ({
default: module.CreateBrandPage,
})),
);
export const FeaturePageSchemePage = React.lazy(() =>
import("../features/page-scheme/PageSchemePage.js").then((module) => ({
default: module.PageSchemePage,
})),
);
@@ -1,98 +0,0 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
import { Button, Result, Space, Typography } from "antd";
import { createApiClient } from "../lib/api.js";
interface AdminErrorBoundaryProps {
children: ReactNode;
variant?: "page" | "content";
}
interface AdminErrorBoundaryState {
error: Error | null;
errorId: string | null;
}
function createErrorId(): string {
return `admin-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
/**
* 后台渲染错误边界:页面级兜底整页,内容级兜底单个业务页面且保留导航。
* React 只支持 class 组件捕获渲染异常,因此这里保留 class 实现。
*/
export class AdminErrorBoundary extends Component<
AdminErrorBoundaryProps,
AdminErrorBoundaryState
> {
override state: AdminErrorBoundaryState = { error: null, errorId: null };
private reportedErrorId: string | null = null;
static getDerivedStateFromError(error: Error): AdminErrorBoundaryState {
return { error, errorId: createErrorId() };
}
override componentDidCatch(error: Error, info: ErrorInfo) {
const errorId = this.state.errorId ?? createErrorId();
console.error("[admin] 页面渲染异常", errorId, error, info.componentStack);
if (this.reportedErrorId === errorId) return;
this.reportedErrorId = errorId;
// 上报失败不能影响错误页本身:只记录到控制台,不抛出、不改状态。
void createApiClient()
.reportAdminClientError({
errorId,
message: error.message.slice(0, 2000) || error.name,
route: `${window.location.pathname}${window.location.search}`.slice(0, 500),
...(info.componentStack ? { componentStack: info.componentStack.slice(0, 20000) } : {}),
})
.catch((reportError: unknown) => {
console.warn("[admin] 渲染异常上报失败", errorId, reportError);
});
}
private reset = () => {
this.setState({ error: null, errorId: null });
};
private reload = () => {
window.location.reload();
};
override render() {
const { error, errorId } = this.state;
if (!error) return this.props.children;
const isPage = this.props.variant === "page";
return (
<Result
status="error"
title="页面渲染出错"
subTitle={
isPage
? "后台页面无法显示。可以重新加载;如果问题持续,请把错误编号提供给管理员。"
: "这个页面无法显示,其他页面仍可正常使用。可以重试或重新加载页面。"
}
extra={
<Space wrap>
{isPage ? null : (
<Button type="primary" onClick={this.reset}>
重试
</Button>
)}
<Button type={isPage ? "primary" : "default"} onClick={this.reload}>
重新加载页面
</Button>
{isPage ? <Button href="/admin/overview">返回概览</Button> : null}
</Space>
}
>
<Typography.Paragraph type="secondary" copyable={{ text: errorId ?? "" }}>
错误编号:{errorId}
</Typography.Paragraph>
{import.meta.env.DEV ? (
<Typography.Paragraph type="secondary">
开发环境错误信息:{error.message}
</Typography.Paragraph>
) : null}
</Result>
);
}
}
@@ -0,0 +1 @@
export { message as adminMessage } from "antd";
+10 -6
View File
@@ -1,7 +1,7 @@
import { CloudUploadOutlined, DeleteOutlined, PictureOutlined } from "@ant-design/icons"; import { CloudUploadOutlined, DeleteOutlined, PictureOutlined } from "@ant-design/icons";
import { Alert, App, Button, Image, Popconfirm, Spin, Upload } from "antd"; import { Alert, Button, Image, Popconfirm, Spin, Upload, message } from "antd";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { apiBaseUrl, authenticatedFetch, createApiClient } from "../lib/api.js"; import { apiBaseUrl, createApiClient } from "../lib/api.js";
interface ImageUrlFieldProps { interface ImageUrlFieldProps {
id?: string; id?: string;
@@ -12,7 +12,6 @@ interface ImageUrlFieldProps {
} }
export function ImageUrlField({ id, value, onChange, placeholder, scope }: ImageUrlFieldProps) { export function ImageUrlField({ id, value, onChange, placeholder, scope }: ImageUrlFieldProps) {
const { message } = App.useApp();
const imageUrl = typeof value === "string" ? value.trim() : ""; const imageUrl = typeof value === "string" ? value.trim() : "";
const [uploading, setUploading] = useState(false); const [uploading, setUploading] = useState(false);
const [storageStatus, setStorageStatus] = useState< const [storageStatus, setStorageStatus] = useState<
@@ -55,9 +54,14 @@ export function ImageUrlField({ id, value, onChange, placeholder, scope }: Image
const uploadUrl = isLocalUpload const uploadUrl = isLocalUpload
? `${apiBaseUrl.replace(/\/$/, "")}${presign.uploadUrl}` ? `${apiBaseUrl.replace(/\/$/, "")}${presign.uploadUrl}`
: presign.uploadUrl; : presign.uploadUrl;
const response = await authenticatedFetch(uploadUrl, { const response = await fetch(uploadUrl, {
method: "PUT", method: "PUT",
headers: { "content-type": file.type }, headers: {
"content-type": file.type,
...(isLocalUpload
? { authorization: `Bearer ${localStorage.getItem("adminToken") ?? ""}` }
: {}),
},
body: file, body: file,
}); });
if (!response.ok) throw new Error(`upload failed: ${response.status}`); if (!response.ok) throw new Error(`upload failed: ${response.status}`);
@@ -75,7 +79,7 @@ export function ImageUrlField({ id, value, onChange, placeholder, scope }: Image
<Alert <Alert
type={storageStatus === "loading" ? "info" : "warning"} type={storageStatus === "loading" ? "info" : "warning"}
showIcon showIcon
title={ message={
storageStatus === "loading" storageStatus === "loading"
? "正在检查媒体存储..." ? "正在检查媒体存储..."
: storageStatus === "unconfigured" : storageStatus === "unconfigured"
@@ -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} data-presentation-binding={field.binding}> <Col key={field.key} xs={24} md={24}>
{field.input === "list" ? ( {field.input === "list" ? (
<TemplateListField field={field} name={presentationFieldName(sectionKey, field.key)} /> <TemplateListField field={field} name={presentationFieldName(sectionKey, field.key)} />
) : ( ) : (
@@ -76,7 +76,7 @@ export function RecordContentEditor({
<Alert <Alert
type="info" type="info"
showIcon showIcon
title={ message={
source === "offering" source === "offering"
? `正在编辑业务提供项:${recordName}` ? `正在编辑业务提供项:${recordName}`
: `正在编辑信任内容:${recordName}` : `正在编辑信任内容:${recordName}`
@@ -1,4 +1,4 @@
import { App, Form } from "antd"; import { Form, message } from "antd";
import { useMutation, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import type { TemplateAdminSection } from "@personal-brand/api-client"; import type { TemplateAdminSection } from "@personal-brand/api-client";
@@ -59,7 +59,6 @@ export function useRecordContentEditorState({
onDraft?: ((values: PresentationValues) => void) | undefined; onDraft?: ((values: PresentationValues) => void) | undefined;
onSaved?: (() => void) | undefined; onSaved?: (() => void) | undefined;
}) { }) {
const { message } = App.useApp();
const [form] = Form.useForm<PresentationValues>(); const [form] = Form.useForm<PresentationValues>();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const [draftValues, setDraftValues] = useState<PresentationValues>(() => const [draftValues, setDraftValues] = useState<PresentationValues>(() =>
+10 -5
View File
@@ -1,20 +1,25 @@
import { useState } from "react"; import { useState } from "react";
import { App } from "antd";
import { createApiClient } from "../../lib/api.js"; import { createApiClient } from "../../lib/api.js";
import { BrandMark } from "../../components/BrandMark.js"; import { BrandMark } from "../../components/BrandMark.js";
import { adminMessage as message } from "../../components/AdminMessage.js";
import { AdminButton } from "../../components/AdminButton.js"; import { AdminButton } from "../../components/AdminButton.js";
import { AdminCard } from "../../components/AdminCard.js"; import { AdminCard } from "../../components/AdminCard.js";
import { AdminForm, AdminInput } from "../../components/AdminForm.js"; import { AdminForm, AdminInput } from "../../components/AdminForm.js";
import type { AdminLoginSession } from "@personal-brand/api-client";
export function Login({ onLogin }: { onLogin: (session: AdminLoginSession) => void }) { export function Login({
const { message } = App.useApp(); onLogin,
}: {
onLogin: (session: { role: string; mustChangePassword: boolean }) => void;
}) {
const [form] = AdminForm.useForm(); const [form] = AdminForm.useForm();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
async function submit(values: { username: string; password: string }) { async function submit(values: { username: string; password: string }) {
setLoading(true); setLoading(true);
try { try {
const result = await createApiClient().loginAdmin(values.username, values.password); const result = await createApiClient().loginAdmin(values.username, values.password);
localStorage.setItem("adminToken", result.token);
localStorage.setItem("adminRole", result.role);
localStorage.setItem("adminMustChangePassword", String(result.mustChangePassword));
onLogin(result); onLogin(result);
} catch (error) { } catch (error) {
message.error(error instanceof Error ? error.message : "登录失败"); message.error(error instanceof Error ? error.message : "登录失败");
@@ -53,7 +58,6 @@ export function Login({ onLogin }: { onLogin: (session: AdminLoginSession) => vo
} }
export function ChangePassword({ onComplete }: { onComplete: () => void }) { export function ChangePassword({ onComplete }: { onComplete: () => void }) {
const { message } = App.useApp();
const [form] = AdminForm.useForm<{ const [form] = AdminForm.useForm<{
currentPassword: string; currentPassword: string;
newPassword: string; newPassword: string;
@@ -72,6 +76,7 @@ export function ChangePassword({ onComplete }: { onComplete: () => void }) {
setLoading(true); setLoading(true);
try { try {
await createApiClient().changeAdminPassword(values.currentPassword, values.newPassword); await createApiClient().changeAdminPassword(values.currentPassword, values.newPassword);
localStorage.setItem("adminMustChangePassword", "false");
message.success("密码已更新"); message.success("密码已更新");
onComplete(); onComplete();
} catch (error) { } catch (error) {
+21 -18
View File
@@ -1,4 +1,4 @@
import { Alert, App, Button, Col, Form, Input, Row, Segmented } from "antd"; import { Alert, Button, Col, Form, Input, Row, Select, Segmented, message } from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react"; import { useState } from "react";
import { Link, useLocation } from "react-router-dom"; import { Link, useLocation } from "react-router-dom";
@@ -14,7 +14,6 @@ import "./BrandPage.css";
import { useEditorDraft } from "./use-editor-draft.js"; import { useEditorDraft } from "./use-editor-draft.js";
export function BrandPage() { export function BrandPage() {
const { message } = App.useApp();
const location = useLocation(); const location = useLocation();
const initialSelection = location.state as PreviewSelection | undefined; const initialSelection = location.state as PreviewSelection | undefined;
const [panel, setPanel] = useState("pages"); const [panel, setPanel] = useState("pages");
@@ -37,6 +36,10 @@ export function BrandPage() {
queryFn: () => client.getPublicTemplate(brand.data!.templateKey), queryFn: () => client.getPublicTemplate(brand.data!.templateKey),
enabled: Boolean(brand.data?.templateKey), enabled: Boolean(brand.data?.templateKey),
}); });
const templateCatalog = useQuery({
queryKey: ["template-catalog"],
queryFn: () => client.listPublicTemplates(),
});
const save = useMutation({ const save = useMutation({
mutationFn: (values: Partial<BrandProfile>) => client.updateAdminBrand(values), mutationFn: (values: Partial<BrandProfile>) => client.updateAdminBrand(values),
onSuccess: () => { onSuccess: () => {
@@ -57,12 +60,7 @@ export function BrandPage() {
? `先让访客理解你是谁、服务谁,以及为什么值得信任。${template.data.description}` ? `先让访客理解你是谁、服务谁,以及为什么值得信任。${template.data.description}`
: "先让访客理解你是谁、服务谁,以及为什么值得信任。" : "先让访客理解你是谁、服务谁,以及为什么值得信任。"
} }
extra={ extra={<StatusTag tone="info" label={template.data?.name ?? "当前模板"} />}
<StatusTag
tone="info"
label={workspace.data?.templateContent?.displayName ?? "当前页面方案"}
/>
}
/> />
<div className="brand-page__toolbar"> <div className="brand-page__toolbar">
<Segmented <Segmented
@@ -171,20 +169,25 @@ export function BrandPage() {
<div className="admin-section-head"> <div className="admin-section-head">
<div> <div>
<h2 id="brand-visual-title" className="admin-section-title"> <h2 id="brand-visual-title" className="admin-section-title">
品牌视觉 模板与品牌视觉
</h2> </h2>
<p className="admin-section-description"> <p className="admin-section-description">
头像和封面会用于品牌身份展示;页面结构和资源位由页面方案统一管理。 模板负责业务表达,品牌信息仍由你统一维护。
</p> </p>
</div> </div>
</div> </div>
<Form.Item label="当前页面方案"> <Form.Item
<div> name="templateKey"
<strong>{workspace.data?.templateContent?.displayName ?? "尚未安装"}</strong> label="业务表达模板"
<p className="admin-section-description"> help="模板只改变业务表达,不改变个人品牌主线。"
页面方案的版本、升级和资源位由品牌负责人统一维护。 >
</p> <Select
</div> disabled
options={(templateCatalog.data?.industries ?? []).map((item) => ({
value: item.key,
label: item.name,
}))}
/>
</Form.Item> </Form.Item>
<Row gutter={16}> <Row gutter={16}>
<Col xs={24} md={12}> <Col xs={24} md={12}>
@@ -220,7 +223,7 @@ export function BrandPage() {
className="brand-page__template-note" className="brand-page__template-note"
type="info" type="info"
showIcon showIcon
title={`当前页面方案:${workspace.data?.templateContent?.displayName ?? template.data.name}`} message={`当前使用:${template.data.name}`}
description={`适用场景:${template.data.serviceCategories.join("、") || "通用品牌展示"}`} description={`适用场景:${template.data.serviceCategories.join("、") || "通用品牌展示"}`}
/> />
) : null} ) : null}
@@ -168,6 +168,6 @@
display: block; display: block;
} }
.component-template-preview__overlay-host > .component-template-preview__composite-select { .component-template-preview__overlay-host > * {
pointer-events: auto; pointer-events: auto;
} }
@@ -3,19 +3,15 @@ import type { RuntimeWorkspace } from "@personal-brand/api-client";
import { Alert } from "antd"; import { Alert } from "antd";
import { resolveTemplateRenderer } from "./component-renderers.jsx"; import { resolveTemplateRenderer } from "./component-renderers.jsx";
import type { PreviewSelection, PreviewTarget } from "./preview-selection.js"; import type { PreviewSelection, PreviewTarget } from "./preview-selection.js";
import { TemplatePreviewAssetsContext } from "./preview-assets.js";
import "./ComponentTemplatePreview.css"; import "./ComponentTemplatePreview.css";
type PreviewProps = { type PreviewProps = {
workspace: RuntimeWorkspace; workspace: RuntimeWorkspace;
page: string; page: string;
offeringId?: string; offeringId?: string;
assetFiles?: Record<string, { sha256: string; dataUrl: string }>;
selection?: PreviewSelection; selection?: PreviewSelection;
targets: PreviewTarget[]; targets: PreviewTarget[];
onTargetSelected: (selection?: PreviewSelection) => void; onTargetSelected: (selection?: PreviewSelection) => void;
onPageSelected?: (page: string) => void;
onOfferingSelected?: (offeringId: string) => void;
}; };
type Outline = { top: number; left: number; width: number; height: number; label: string }; type Outline = { top: number; left: number; width: number; height: number; label: string };
@@ -25,12 +21,9 @@ export function ComponentTemplatePreview({
workspace, workspace,
page, page,
offeringId, offeringId,
assetFiles,
selection, selection,
targets, targets,
onTargetSelected, onTargetSelected,
onPageSelected = () => undefined,
onOfferingSelected = () => undefined,
}: PreviewProps) { }: PreviewProps) {
const Renderer = resolveTemplateRenderer(workspace); const Renderer = resolveTemplateRenderer(workspace);
const root = useRef<HTMLDivElement>(null); const root = useRef<HTMLDivElement>(null);
@@ -38,26 +31,6 @@ export function ComponentTemplatePreview({
const [mode, setMode] = useState<"edit" | "browse">("edit"); const [mode, setMode] = useState<"edit" | "browse">("edit");
const [hovered, setHovered] = useState<HTMLElement | null>(null); const [hovered, setHovered] = useState<HTMLElement | null>(null);
const overlay = useRef<HTMLDivElement>(null); const overlay = useRef<HTMLDivElement>(null);
// 将 renderer 里的 Taro CTA 导航转换为画布内页面/记录切换。
useEffect(() => {
const navigate = (event: Event) => {
const detail = (event as CustomEvent<{ method?: string; options?: { url?: string } }>).detail;
const url = detail?.options?.url;
if (typeof url !== "string") return;
const match = /^\/pages\/([a-z]+)\/index(?:\?(.*))?$/.exec(url);
if (!match) return;
const nextPage = match[1];
if (!nextPage) return;
const query = match[2];
if (nextPage === "detail") {
const id = new URLSearchParams(query ?? "").get("id");
if (id) onOfferingSelected(id);
}
onPageSelected(nextPage);
};
window.addEventListener("template-preview-navigate", navigate);
return () => window.removeEventListener("template-preview-navigate", navigate);
}, [onOfferingSelected, onPageSelected]);
const targetFor = useCallback( const targetFor = useCallback(
(element: Element | null): HTMLElement | null => { (element: Element | null): HTMLElement | null => {
let candidate = element?.closest<HTMLElement>("[data-editor-target]"); let candidate = element?.closest<HTMLElement>("[data-editor-target]");
@@ -205,7 +178,7 @@ export function ComponentTemplatePreview({
return () => window.removeEventListener("keydown", clear); return () => window.removeEventListener("keydown", clear);
}, [onTargetSelected]); }, [onTargetSelected]);
if (!Renderer) if (!Renderer)
return <Alert type="warning" showIcon title="此模板尚无组件预览,请使用页面预览" />; return <Alert type="warning" showIcon message="此模板尚无组件预览,请使用页面预览" />;
return ( return (
<div className="component-template-preview-shell"> <div className="component-template-preview-shell">
<div <div
@@ -259,9 +232,7 @@ export function ComponentTemplatePreview({
}} }}
> >
<div ref={canvas} className="component-template-preview__canvas"> <div ref={canvas} className="component-template-preview__canvas">
<TemplatePreviewAssetsContext.Provider value={assetFiles}> <Renderer workspace={workspace} page={page} {...(offeringId ? { offeringId } : {})} />
<Renderer workspace={workspace} page={page} {...(offeringId ? { offeringId } : {})} />
</TemplatePreviewAssetsContext.Provider>
<div <div
ref={overlay} ref={overlay}
className={`component-template-preview__overlay-host ${ className={`component-template-preview__overlay-host ${
@@ -1,4 +1,4 @@
import { Alert, App, Button, Form, Input, Select, Space, Switch } from "antd"; import { Alert, Button, Form, Input, Select, Space, Switch, message } from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react"; import { useEffect } from "react";
import type { RuntimeWorkspace } from "@personal-brand/api-client"; import type { RuntimeWorkspace } from "@personal-brand/api-client";
@@ -18,7 +18,6 @@ export function InquiryPreviewEditor({
onDraft: (fields: RuntimeInquiryForm["fields"]) => void; onDraft: (fields: RuntimeInquiryForm["fields"]) => void;
onSaved?: () => void; onSaved?: () => void;
}) { }) {
const { message } = App.useApp();
const [form] = Form.useForm<Record<string, unknown>>(); const [form] = Form.useForm<Record<string, unknown>>();
const cache = useQueryClient(); const cache = useQueryClient();
const query = useQuery({ const query = useQuery({
@@ -28,9 +27,8 @@ export function InquiryPreviewEditor({
const record = query.data?.find((item) => item.id === runtime.key); const record = query.data?.find((item) => item.id === runtime.key);
const field = runtime.fields.find((item) => item.key === fieldKey); const field = runtime.fields.find((item) => item.key === fieldKey);
useEffect(() => { useEffect(() => {
if (!record || !field) return; if (field) form.setFieldsValue({ ...field });
form.setFieldsValue({ ...field }); }, [fieldKey, runtime.key, form]);
}, [field, fieldKey, form, record, runtime.key]);
const update = (values: Record<string, unknown>) => const update = (values: Record<string, unknown>) =>
runtime.fields.map((item) => (item.key === fieldKey ? { ...item, ...values } : item)); runtime.fields.map((item) => (item.key === fieldKey ? { ...item, ...values } : item));
const save = useMutation({ const save = useMutation({
@@ -61,7 +59,7 @@ export function InquiryPreviewEditor({
return ( return (
<Alert <Alert
type="error" type="error"
title="表单读取失败" message="表单读取失败"
action={<Button onClick={() => void query.refetch()}>重试</Button>} action={<Button onClick={() => void query.refetch()}>重试</Button>}
/> />
); );
@@ -69,10 +67,10 @@ export function InquiryPreviewEditor({
return ( return (
<Alert <Alert
type="info" type="info"
title={query.isPending ? "正在读取表单" : "未找到对应表单,请刷新后重试"} message={query.isPending ? "正在读取表单" : "未找到对应表单,请刷新后重试"}
/> />
); );
if (!field) return <Alert type="warning" title="字段已不存在" />; if (!field) return <Alert type="warning" message="字段已不存在" />;
return ( return (
<Form<Record<string, unknown>> <Form<Record<string, unknown>>
form={form} form={form}
@@ -1,15 +1,41 @@
import { Alert, Grid, Segmented, Select, Space } from "antd"; import { Alert, Button, Grid, Select, Segmented, Space, Typography } from "antd";
import { useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import type { import type {
AdminTemplateContent, AdminTemplateContent,
BrandProfile,
RuntimeWorkspace, RuntimeWorkspace,
TemplateAdminSection,
} from "@personal-brand/api-client"; } from "@personal-brand/api-client";
import type { BrandProfile } from "@personal-brand/api-client";
import { StatusTag } from "../../components/StatusTag.js"; import { StatusTag } from "../../components/StatusTag.js";
import { RecordContentEditor } from "../../components/RecordContentEditor.js";
import { TemplatePreview } from "./TemplatePreview.js";
import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js";
import {
resolvePreviewSelection,
previewTrustRecordId,
type PreviewSelection,
type PreviewTarget,
} from "./preview-selection.js";
import {
filterSectionsForPreviewTarget,
type PresentationValues,
} from "../../lib/presentation/presentation-bindings.js";
import "./PresentationEditor.css"; import "./PresentationEditor.css";
import type { PreviewSelection } from "./preview-selection.js"; import { useEditorDraft } from "./use-editor-draft.js";
import { usePresentationEditorController } from "./presentation-editor-controller.js"; import {
import { PresentationEditorInspector } from "./PresentationEditorInspector.js"; usePresentationRecordQueries,
import { PresentationEditorPreview } from "./PresentationEditorPreview.js"; useBrandPresentationSections,
useBrandSaveMutation,
useBrandPresentationForm,
useBrandPreviewDraft,
} from "./presentation-editor-state.js";
import { useRecordPreview } from "./presentation-editor-record-preview.js";
import type { RecordDraft } from "./presentation-editor-record-preview.js";
import { pageTitle, previewTargetSource, trustSection } from "./presentation-editor-helpers.js";
import { useDraftWorkspace } from "./use-draft-workspace.js";
import { PresentationFormPanel } from "./PresentationFormPanel.js";
interface PresentationEditorProps { interface PresentationEditorProps {
templateContent: AdminTemplateContent | null | undefined; templateContent: AdminTemplateContent | null | undefined;
@@ -30,14 +56,247 @@ export function PresentationEditor({
error, error,
initialSelection, initialSelection,
}: PresentationEditorProps) { }: PresentationEditorProps) {
const queryClient = useQueryClient();
const navigate = useNavigate();
const breakpoints = Grid.useBreakpoint(); const breakpoints = Grid.useBreakpoint();
const controller = usePresentationEditorController({ const [activePage, setActivePage] = useState<string>();
templateContent, const [selection, setSelection] = useState<PreviewSelection | undefined>(initialSelection);
previewWorkspace, const [hasInitializedSelection, setHasInitializedSelection] = useState(Boolean(initialSelection));
config, const [detailOfferingId, setDetailOfferingId] = useState<string>();
const [recordDraft, setRecordDraft] = useState<RecordDraft>();
const [inquiryDraft, setInquiryDraft] =
useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>();
const [brandDirty, setBrandDirty] = useState(false);
const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft);
const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand");
const sections = useBrandPresentationSections(templateContent);
const pageOptions = useMemo(() => {
const pages = new Map<string, string>();
for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label);
for (const section of templateContent?.admin.sections ?? []) {
const navigation = templateContent?.navigation.find((item) => item.page === section.page);
if (!pages.has(section.page))
pages.set(section.page, navigation?.label ?? pageTitle(section.page));
}
return [...pages].map(([value, label]) => ({ value, label }));
}, [templateContent]);
const selectedPage = pageOptions.some((item) => item.value === activePage)
? activePage
: pageOptions[0]?.value;
const visibleSections = sections.filter((section) => section.page === selectedPage);
const recordSections = useMemo(
() =>
(templateContent?.trustContentTypes ?? [])
.filter((item) => item.pages?.includes(selectedPage ?? ""))
.map((item) => trustSection(item, selectedPage ?? "home")),
[templateContent, selectedPage],
);
const visibleTargets = useMemo<PreviewTarget[]>(
() =>
[...(templateContent?.admin.sections ?? []), ...recordSections]
.filter(
(section) =>
section.page === selectedPage &&
(selectedPage !== "detail" || section.target === "brand"),
)
.flatMap((section) =>
(section.previewTargets ?? []).map((target) => ({
...target,
page: section.page,
source: previewTargetSource(section, target.key),
...(section.key.startsWith("trust:") ? { trustType: section.key.slice(6) } : {}),
})),
)
.concat(
selectedPage === "inquiry" && inquiryRuntime
? inquiryRuntime.fields.map((field) => ({
key: `inquiry-field:${field.key}`,
label: field.label,
page: "inquiry",
source: "inquiry" as const,
}))
: [],
),
[templateContent, selectedPage, recordSections, inquiryRuntime],
);
const activeTarget = selection?.targetKey;
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
const selectedSection = [...(templateContent?.admin.sections ?? []), ...recordSections].find(
(section) =>
section.page === selectedPage &&
section.previewTargets?.some((target) => target.key === selectedTarget?.key),
);
const selectedRecordSource =
selectedTarget?.source === "offering" || selectedTarget?.source === "trust"
? selectedTarget.source
: undefined;
const { offeringsQuery, trustQuery, selectedRecord } = usePresentationRecordQueries(
selectedRecordSource,
selection?.recordId,
);
const editableSections = filterSectionsForPreviewTarget(
visibleSections.filter((section) =>
section.fields.some((field) => field.binding.startsWith("brand.")),
),
selectedTarget?.key,
);
const recordSection = useMemo(
() =>
selectedSection && selection?.targetKey
? {
...selectedSection,
fields: selectedSection.fields.filter(
(field) => field.previewTarget === selection.targetKey,
),
}
: undefined,
[selectedSection, selection?.targetKey],
);
const handleTargetSelected = useCallback(
(next?: PreviewSelection) => {
const select = () =>
setSelection(
next
? resolvePreviewSelection(
next.targetKey,
next.recordId,
visibleTargets,
selectedPage ?? "home",
)
: undefined,
);
if (recordDraft || inquiryDraft)
guardDraft(() => {
setInquiryDraft(undefined);
setRecordDraft(undefined);
select();
});
else select();
},
[visibleTargets, selectedPage, recordDraft, inquiryDraft, guardDraft],
);
const relatedTargets = [
...(templateContent?.admin.sections ?? [])
.filter((section) => section.page === selectedPage && section.target !== "brand")
.map((section) => section.target),
...((templateContent?.trustContentTypes ?? []).some((item) =>
item.pages?.includes(selectedPage ?? ""),
)
? ["trust"]
: []),
];
const pageLinks = [...new Set(relatedTargets)].flatMap((target) =>
target === "trust"
? (templateContent?.trustContentTypes ?? [])
.filter((item) => item.pages?.includes(selectedPage ?? ""))
.map((item) => ({
target: `trust:${item.type}`,
label: `编辑${item.label}`,
}))
: [
{
target,
label: (
{ offering: "管理此页展示的业务内容", inquiry: "管理此页的咨询表单" } as Record<
string,
string
>
)[target],
},
],
);
const relevantPageLinks = selectedSection
? pageLinks.filter((item) => {
if (item.target.startsWith("trust:")) return selectedSection.target === "trust";
return item.target === selectedSection.target;
})
: pageLinks;
const formState = useBrandPresentationForm({ brand, config, sections });
const { form, initialValues } = formState;
const save = useBrandSaveMutation({ ...formState, brand, config, sections, queryClient });
useEffect(() => {
const initialPage =
typeof initialSelection === "object" && "page" in initialSelection
? String(initialSelection.page)
: undefined;
if (initialPage) {
setActivePage(
pageOptions.some((item) => item.value === initialPage)
? initialPage
: pageOptions[0]?.value,
);
return;
}
if (!activePage && pageOptions.length) setActivePage(pageOptions[0]?.value);
}, [activePage, initialSelection, pageOptions]);
useEffect(() => {
if (hasInitializedSelection) return;
if (!pageOptions.length) return;
if (!initialSelection) return;
const requestedPage =
typeof initialSelection === "object" && "page" in initialSelection
? String(initialSelection.page)
: undefined;
const resolvedPage =
requestedPage && pageOptions.some((item) => item.value === requestedPage)
? requestedPage
: (pageOptions[0]?.value ?? "home");
setSelection(
resolvePreviewSelection(
initialSelection.targetKey,
initialSelection.recordId,
visibleTargets,
resolvedPage,
),
);
setActivePage(resolvedPage);
setHasInitializedSelection(true);
}, [hasInitializedSelection, initialSelection, pageOptions, selectedPage, visibleTargets]);
useEffect(() => {
if (!initialSelection) setSelection(undefined);
}, [initialSelection, selectedPage, templateContent?.displayName]);
useEffect(() => {
if (!selection?.recordId) return;
const records =
selectedTarget?.source === "trust"
? previewWorkspace?.trustItems
: previewWorkspace?.offerings;
if (records && !records.some((item) => item.id === selection.recordId)) setSelection(undefined);
}, [
previewWorkspace?.offerings,
previewWorkspace?.trustItems,
selectedTarget?.source,
selection,
]);
useEffect(
() => setRecordDraft(undefined),
[selection?.targetKey, selection?.recordId, selectedPage],
);
const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({
brand, brand,
...(initialSelection ? { initialSelection } : {}), config,
sections,
form,
onDirty: () => setBrandDirty(true),
}); });
const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection });
useEffect(() => resetPreview(), [config, initialValues, resetPreview]);
const draftWorkspace = useDraftWorkspace({
previewWorkspace,
previewBrand,
inquiryRuntime,
inquiryDraft,
recordDraft,
selectedRecord,
recordSection,
recordPreview,
templateContent,
});
const selectedDetailOfferingId =
detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId)
? detailOfferingId
: draftWorkspace?.offerings[0]?.id;
return ( return (
<section className="presentation-editor" aria-labelledby="presentation-editor-title"> <section className="presentation-editor" aria-labelledby="presentation-editor-title">
@@ -52,12 +311,12 @@ export function PresentationEditor({
</div> </div>
{templateContent ? <StatusTag tone="info" label={templateContent.displayName} /> : null} {templateContent ? <StatusTag tone="info" label={templateContent.displayName} /> : null}
</div> </div>
{loading ? <Alert type="info" showIcon title="正在读取当前页面方案的编辑项目" /> : null} {loading ? <Alert type="info" showIcon message="正在读取当前模板的编辑项目" /> : null}
{error ? ( {error ? (
<Alert type="warning" showIcon title="页面方案编辑项目读取失败,请刷新后重试。" /> <Alert type="warning" showIcon message="模板编辑项目读取失败,请刷新后重试。" />
) : null} ) : null}
{!loading && !error && !templateContent ? ( {!loading && !error && !templateContent ? (
<Alert type="warning" showIcon title="当前页面方案暂未提供可编辑的页面内容。" /> <Alert type="warning" showIcon message="当前模板暂未提供可编辑的页面内容。" />
) : null} ) : null}
{templateContent ? ( {templateContent ? (
<> <>
@@ -65,33 +324,306 @@ export function PresentationEditor({
{breakpoints.xs ? ( {breakpoints.xs ? (
<Select <Select
aria-label="选择小程序页面" aria-label="选择小程序页面"
value={controller.selectedPage ?? null} value={selectedPage}
options={controller.pageOptions} options={pageOptions}
onChange={controller.selectPage} onChange={(value) =>
guardDraft(() => {
setBrandDirty(false);
form.setFieldsValue(initialValues);
resetPreview();
setRecordDraft(undefined);
setInquiryDraft(undefined);
setActivePage(value);
})
}
className="admin-field-w-2xl" className="admin-field-w-2xl"
/> />
) : ( ) : (
<Segmented <Segmented
value={controller.selectedPage ?? null} value={selectedPage}
options={controller.pageOptions} options={pageOptions}
onChange={(value) => controller.selectPage(String(value))} onChange={(value) =>
guardDraft(() => {
setBrandDirty(false);
form.setFieldsValue(initialValues);
resetPreview();
setRecordDraft(undefined);
setInquiryDraft(undefined);
setActivePage(String(value));
})
}
/> />
)} )}
</Space> </Space>
<div className="presentation-editor__workspace"> <div className="presentation-editor__workspace">
<PresentationEditorPreview <div className="presentation-editor__preview">
previewBrand={controller.previewBrand} <h3 className="admin-section-title admin-flush">页面预览</h3>
draftWorkspace={controller.draftWorkspace} {selectedPage === "detail" && draftWorkspace?.offerings.length ? (
selectedPage={controller.selectedPage} <Select
selectedDetailOfferingId={controller.selectedDetailOfferingId} aria-label="选择详情页业务内容"
activeTarget={controller.activeTarget} className="admin-block admin-offset-bottom-sm"
selection={controller.selection} value={selectedDetailOfferingId}
visibleTargets={controller.visibleTargets} options={draftWorkspace.offerings.map((item) => ({
onSelectDetailOffering={controller.selectDetailOffering} value: item.id,
onTargetSelected={controller.handleTargetSelected} label: item.name,
onSelectPreviewTarget={controller.selectPreviewTarget} }))}
/> onChange={(value) => {
<PresentationEditorInspector controller={controller} /> setDetailOfferingId(value);
setSelection(undefined);
}}
/>
) : null}
<TemplatePreview
brand={previewBrand}
{...(draftWorkspace ? { workspace: draftWorkspace } : {})}
page={selectedPage ?? "home"}
{...(selectedPage === "detail" && selectedDetailOfferingId
? { offeringId: selectedDetailOfferingId }
: {})}
{...(activeTarget ? { targetKey: activeTarget } : {})}
{...(selection ? { selection } : {})}
targets={visibleTargets}
onTargetSelected={handleTargetSelected}
/>
</div>
<aside className="presentation-editor__outline" aria-label="页面区域">
<h3 className="admin-section-title admin-flush">页面区域</h3>
<p className="admin-section-description">选择区域,编辑对应内容</p>
{visibleTargets.length ? (
<Space className="presentation-editor__regions admin-offset-top" wrap>
{visibleTargets.map((target) => (
<Button
key={target.key}
className={
visibleTargets.some((parent) => parent.children?.includes(target.key))
? "is-child-region"
: ""
}
aria-pressed={activeTarget === target.key}
type={activeTarget === target.key ? "primary" : "default"}
onClick={() => {
const recordId =
target.source === "offering"
? selectedPage === "detail"
? selectedDetailOfferingId
: draftWorkspace?.offerings[0]?.id
: target.source === "trust"
? previewTrustRecordId(
draftWorkspace?.trustItems ?? [],
target.trustType,
)
: undefined;
handleTargetSelected({
targetKey: target.key,
...(recordId ? { recordId } : {}),
});
}}
>
{target.label}
</Button>
))}
</Space>
) : null}
{!visibleTargets.length ? (
<Typography.Text type="secondary">此页为动态预览</Typography.Text>
) : null}
</aside>
<div className="presentation-editor__inspector">
<h3 className="admin-section-title admin-flush">
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
</h3>
<StatusTag
tone={
save.isError
? "error"
: save.isPending || brandDirty || recordDraft || inquiryDraft
? "warning"
: "neutral"
}
label={
save.isPending
? "正在保存"
: save.isError
? "保存失败,请重试"
: brandDirty || recordDraft || inquiryDraft
? "有未保存修改"
: "草稿已同步"
}
/>
{selectedPage === "detail" && !selectedTarget ? (
<Alert
type="info"
showIcon
message="详情页由所选业务内容动态生成"
description="选择业务内容预览详情,记录内容在业务提供项中维护;公共标题和按钮文案可从左侧区域列表配置,对全部详情生效。"
action={
<Button
onClick={() => {
void navigate("/admin/services");
}}
>
管理业务内容
</Button>
}
/>
) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? (
<InquiryPreviewEditor
runtime={
draftWorkspace?.inquiryForms.find((item) => item.key === inquiryRuntime.key) ??
inquiryRuntime
}
fieldKey={activeTarget.slice("inquiry-field:".length)}
onDraft={setInquiryDraft}
onSaved={() => setInquiryDraft(undefined)}
/>
) : selectedTarget?.composite ? (
<Alert
type="info"
showIcon
message="这是一个组合区域"
description={
<Space wrap>
{(selectedTarget.children ?? []).map((childKey) => {
const child = visibleTargets.find((item) => item.key === childKey);
if (!child) return null;
return (
<Button
key={child.key}
onClick={() => {
const recordId =
child.source === "offering"
? selectedPage === "detail"
? selectedDetailOfferingId
: draftWorkspace?.offerings[0]?.id
: child.source === "trust"
? previewTrustRecordId(
draftWorkspace?.trustItems ?? [],
child.trustType,
)
: undefined;
handleTargetSelected({
targetKey: child.key,
...(recordId ? { recordId } : {}),
});
}}
>
编辑{child.label}
</Button>
);
})}
</Space>
}
/>
) : selectedRecordSource && selection?.recordId && selectedSection ? (
selectedRecord ? (
<RecordContentEditor
key={`${selectedRecordSource}:${selectedRecord.id}:${selectedSection.key}`}
source={selectedRecordSource}
record={selectedRecord}
section={recordSection!}
context="visual"
onDraft={(values) =>
setRecordDraft({
source: selectedRecordSource,
id: selectedRecord.id,
values,
})
}
onSaved={() => setRecordDraft(undefined)}
/>
) : (
<Alert
type={
(
selectedRecordSource === "offering"
? offeringsQuery.isError
: trustQuery.isError
)
? "error"
: "info"
}
message={
(
selectedRecordSource === "offering"
? offeringsQuery.isError
: trustQuery.isError
)
? "内容读取失败"
: (
selectedRecordSource === "offering"
? offeringsQuery.isSuccess
: trustQuery.isSuccess
)
? "对应内容已不存在,请重新选择页面中的区域"
: "正在读取对应内容"
}
{...((
selectedRecordSource === "offering"
? offeringsQuery.isError
: trustQuery.isError
)
? {
action: (
<Button
size="small"
onClick={() => {
if (selectedRecordSource === "offering")
void offeringsQuery.refetch();
else void trustQuery.refetch();
}}
>
重试
</Button>
),
}
: {})}
/>
)
) : selectedRecordSource ? (
<Alert
type="info"
showIcon
message="此区域尚未配置内容"
description="创建并启用对应内容后,即可在预览中点选编辑。"
action={
<Button
onClick={() =>
guardDraft(() => {
void navigate(
selectedRecordSource === "trust"
? `/admin/trust?type=${encodeURIComponent(selectedTarget?.trustType ?? "")}`
: "/admin/services",
);
})
}
>
配置此区域内容
</Button>
}
/>
) : !selectedTarget ? (
<div className="presentation-editor__empty">
<h3 className="admin-subhead">选择要编辑的区域</h3>
<p className="admin-section-description">
点击预览中的内容,或使用区域列表,查看并修改对应字段。
</p>
</div>
) : (
<PresentationFormPanel
form={form}
initialValues={initialValues}
editableSections={editableSections}
relevantPageLinks={relevantPageLinks}
selectedTarget={selectedTarget}
save={{
error: save.error,
isPending: save.isPending,
mutate: (values) => save.mutate(values),
}}
onValuesChange={handleValuesChange}
/>
)}
</div>
</div> </div>
</> </>
) : null} ) : null}
@@ -1,196 +0,0 @@
import { Alert, Button, Space } from "antd";
import { StatusTag } from "../../components/StatusTag.js";
import { RecordContentEditor } from "../../components/RecordContentEditor.js";
import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js";
import { PresentationFormPanel } from "./PresentationFormPanel.js";
import { pageTitle } from "./presentation-editor-helpers.js";
import type { PresentationEditorController } from "./presentation-editor-controller.js";
export function PresentationEditorInspector({
controller,
}: {
controller: PresentationEditorController;
}) {
const {
selectedPage,
selectedTarget,
activeTarget,
selection,
selectedSection,
selectedRecordSource,
selectedRecord,
recordSection,
editableSections,
relevantPageLinks,
inquiryRuntime,
draftWorkspace,
form,
initialValues,
save,
offeringsQuery,
trustQuery,
recordDraft,
inquiryDraft,
brandDirty,
guardDraft,
} = controller;
const recordQuery = selectedRecordSource === "trust" ? trustQuery : offeringsQuery;
return (
<div className="presentation-editor__inspector">
<h3 className="admin-section-title admin-flush">
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
</h3>
<StatusTag
tone={
save.isError
? "error"
: save.isPending || brandDirty || recordDraft || inquiryDraft
? "warning"
: "neutral"
}
label={
save.isPending
? "正在保存"
: save.isError
? "保存失败,请重试"
: brandDirty || recordDraft || inquiryDraft
? "有未保存修改"
: "草稿已同步"
}
/>
{selectedPage === "detail" && !selectedTarget ? (
<Alert
type="info"
showIcon
title="详情页由所选业务内容动态生成"
description="选择业务内容预览详情,记录内容在业务提供项中维护;公共标题和按钮文案可从左侧区域列表配置,对全部详情生效。"
action={
<Button
onClick={() => {
void controller.navigate("/admin/services");
}}
>
管理业务内容
</Button>
}
/>
) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? (
<InquiryPreviewEditor
runtime={
draftWorkspace?.inquiryForms.find((item) => item.key === inquiryRuntime.key) ??
inquiryRuntime
}
fieldKey={activeTarget.slice("inquiry-field:".length)}
onDraft={controller.setInquiryDraft}
onSaved={() => controller.setInquiryDraft(undefined)}
/>
) : selectedTarget?.composite ? (
<Alert
type="info"
showIcon
title="这是一个组合区域"
description={
<Space wrap>
{(selectedTarget.children ?? []).map((childKey) => {
const child = visibleTarget(childKey, controller);
if (!child) return null;
return (
<Button key={child.key} onClick={() => controller.selectPreviewTarget(child)}>
编辑{child.label}
</Button>
);
})}
</Space>
}
/>
) : selectedRecordSource && selection?.recordId && selectedSection ? (
selectedRecord ? (
<RecordContentEditor
key={`${selectedRecordSource}:${selectedRecord.id}:${selectedSection.key}`}
source={selectedRecordSource}
record={selectedRecord}
section={recordSection!}
context="visual"
onDraft={(values) =>
controller.setRecordDraft({
source: selectedRecordSource,
id: selectedRecord.id,
values,
})
}
onSaved={() => controller.setRecordDraft(undefined)}
/>
) : (
<Alert
type={recordQuery.isError ? "error" : "info"}
title={
recordQuery.isError
? "内容读取失败"
: recordQuery.isSuccess
? "对应内容已不存在,请重新选择页面中的区域"
: "正在读取对应内容"
}
{...(recordQuery.isError
? {
action: (
<Button size="small" onClick={() => void recordQuery.refetch()}>
重试
</Button>
),
}
: {})}
/>
)
) : selectedRecordSource ? (
<Alert
type="info"
showIcon
title="此区域尚未配置内容"
description="创建并启用对应内容后,即可在预览中点选编辑。"
action={
<Button
onClick={() =>
guardDraft(() => {
void controller.navigate(
selectedRecordSource === "trust"
? `/admin/trust?type=${encodeURIComponent(selectedTarget?.trustType ?? "")}`
: "/admin/services",
);
})
}
>
配置此区域内容
</Button>
}
/>
) : !selectedTarget ? (
<div className="presentation-editor__empty">
<h3 className="admin-subhead">选择要编辑的区域</h3>
<p className="admin-section-description">
点击预览中的内容,或使用区域列表,查看并修改对应字段。
</p>
</div>
) : (
<PresentationFormPanel
key={`${selectedPage}:${selectedTarget.key}`}
form={form}
initialValues={initialValues}
editableSections={editableSections}
relevantPageLinks={relevantPageLinks}
selectedTarget={selectedTarget}
save={{
error: save.error,
isPending: save.isPending,
mutate: (values) => save.mutate(values),
}}
onValuesChange={controller.handleValuesChange}
/>
)}
</div>
);
}
function visibleTarget(key: string, controller: PresentationEditorController) {
return controller.visibleTargets.find((item) => item.key === key);
}
@@ -1,88 +0,0 @@
import { Button, Select, Space, Typography } from "antd";
import type { BrandProfile, RuntimeWorkspace } from "@personal-brand/api-client";
import { TemplatePreview } from "./TemplatePreview.js";
import type { PreviewSelection, PreviewTarget } from "./preview-selection.js";
interface PresentationEditorPreviewProps {
previewBrand: BrandProfile;
draftWorkspace?: RuntimeWorkspace | undefined;
selectedPage: string | undefined;
selectedDetailOfferingId: string | undefined;
activeTarget: string | undefined;
selection: PreviewSelection | undefined;
visibleTargets: PreviewTarget[];
onSelectDetailOffering: (id: string) => void;
onTargetSelected: (next?: PreviewSelection) => void;
onSelectPreviewTarget: (target: PreviewTarget) => void;
}
export function PresentationEditorPreview({
previewBrand,
draftWorkspace,
selectedPage,
selectedDetailOfferingId,
activeTarget,
selection,
visibleTargets,
onSelectDetailOffering,
onTargetSelected,
onSelectPreviewTarget,
}: PresentationEditorPreviewProps) {
return (
<>
<div className="presentation-editor__preview">
<h3 className="admin-section-title admin-flush">页面预览</h3>
{selectedPage === "detail" && draftWorkspace?.offerings.length ? (
<Select
aria-label="选择详情页业务内容"
className="admin-block admin-offset-bottom-sm"
value={selectedDetailOfferingId ?? null}
options={draftWorkspace.offerings.map((item) => ({
value: item.id,
label: item.name,
}))}
onChange={onSelectDetailOffering}
/>
) : null}
<TemplatePreview
brand={previewBrand}
{...(draftWorkspace ? { workspace: draftWorkspace } : {})}
page={selectedPage ?? "home"}
{...(selectedPage === "detail" && selectedDetailOfferingId
? { offeringId: selectedDetailOfferingId }
: {})}
{...(activeTarget ? { targetKey: activeTarget } : {})}
{...(selection ? { selection } : {})}
targets={visibleTargets}
onTargetSelected={onTargetSelected}
/>
</div>
<aside className="presentation-editor__outline" aria-label="页面区域">
<h3 className="admin-section-title admin-flush">页面区域</h3>
<p className="admin-section-description">选择区域,编辑对应内容</p>
{visibleTargets.length ? (
<Space className="presentation-editor__regions admin-offset-top" wrap>
{visibleTargets.map((target) => (
<Button
key={target.key}
className={
visibleTargets.some((parent) => parent.children?.includes(target.key))
? "is-child-region"
: ""
}
aria-pressed={activeTarget === target.key}
type={activeTarget === target.key ? "primary" : "default"}
onClick={() => onSelectPreviewTarget(target)}
>
{target.label}
</Button>
))}
</Space>
) : null}
{!visibleTargets.length ? (
<Typography.Text type="secondary">此页为动态预览</Typography.Text>
) : null}
</aside>
</>
);
}
@@ -89,7 +89,7 @@ export function PresentationFormPanel({
type="info" type="info"
showIcon showIcon
className="admin-offset-bottom-lg" className="admin-offset-bottom-lg"
title="这个页面还有关联内容" message="这个页面还有关联内容"
description={ description={
<Space wrap> <Space wrap>
{relevantPageLinks.map((item) => ( {relevantPageLinks.map((item) => (
@@ -124,7 +124,7 @@ export function TemplatePreview({
<Alert <Alert
type="warning" type="warning"
showIcon showIcon
title="页面预览暂不可用" message="页面预览暂不可用"
description="请确认模板预览资源已构建并发布,或本地预览服务正在运行。" description="请确认模板预览资源已构建并发布,或本地预览服务正在运行。"
/> />
); );
@@ -146,11 +146,11 @@ export function TemplatePreview({
<> <>
{!ready && !error ? ( {!ready && !error ? (
<div className="template-preview__loading"> <div className="template-preview__loading">
<Spin description="正在加载页面预览" /> <Spin tip="正在加载页面预览" />
</div> </div>
) : null} ) : null}
{error ? ( {error ? (
<Alert type="error" showIcon title="页面预览加载失败" description={error} /> <Alert type="error" showIcon message="页面预览加载失败" description={error} />
) : null} ) : null}
<iframe <iframe
key={url} key={url}
@@ -7,7 +7,6 @@ import { TemplateAssetContext } from "./taro-web-components.jsx";
const templateRenderers = import.meta.glob("../../../../../packages/template-*/taro/index.tsx", { const templateRenderers = import.meta.glob("../../../../../packages/template-*/taro/index.tsx", {
eager: true, eager: true,
}); });
const resolvedRenderers = new Map();
function pageContent({ workspace, page }) { function pageContent({ workspace, page }) {
if (page === "inquiry") return <Inquiry workspace={workspace} preview />; if (page === "inquiry") return <Inquiry workspace={workspace} preview />;
@@ -17,20 +16,21 @@ function pageContent({ workspace, page }) {
} }
export function resolveTemplateRenderer(workspace) { export function resolveTemplateRenderer(workspace) {
const key = workspace?.visualTemplate?.key; const config = workspace?.brand?.config;
const key =
config && typeof config === "object" && !Array.isArray(config)
? config.visualTemplateKey
: undefined;
if (typeof key !== "string") return null; if (typeof key !== "string") return null;
if (resolvedRenderers.has(key)) return resolvedRenderers.get(key);
const suffix = `/template-${key}/taro/index.tsx`; const suffix = `/template-${key}/taro/index.tsx`;
const entry = Object.entries(templateRenderers).find(([path]) => path.endsWith(suffix)); const entry = Object.entries(templateRenderers).find(([path]) => path.endsWith(suffix));
const TemplatePage = entry?.[1]?.TemplatePage; const TemplatePage = entry?.[1]?.TemplatePage;
if (!TemplatePage) return null; if (!TemplatePage) return null;
function TemplatePreview(props) { return function TemplatePreview(props) {
return ( return (
<TemplateAssetContext.Provider value={key}> <TemplateAssetContext.Provider value={key}>
<TemplatePage {...props}>{pageContent(props)}</TemplatePage> <TemplatePage {...props}>{pageContent(props)}</TemplatePage>
</TemplateAssetContext.Provider> </TemplateAssetContext.Provider>
); );
} };
resolvedRenderers.set(key, TemplatePreview);
return TemplatePreview;
} }
@@ -1,416 +0,0 @@
import { useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate, type NavigateFunction } from "react-router-dom";
import type {
AdminTemplateContent,
BrandProfile,
Offering,
RuntimeWorkspace,
TemplateAdminSection,
TrustContent,
} from "@personal-brand/api-client";
import type { FormInstance } from "antd";
import { filterSectionsForPreviewTarget } from "../../lib/presentation/presentation-bindings.js";
import type { PresentationValues } from "../../lib/presentation/presentation-bindings.js";
import {
resolvePreviewSelection,
previewTrustRecordId,
type PreviewSelection,
type PreviewTarget,
} from "./preview-selection.js";
import { useEditorDraft } from "./use-editor-draft.js";
import {
useBrandPresentationForm,
useBrandPresentationSections,
useBrandPreviewDraft,
useBrandSaveMutation,
usePresentationRecordQueries,
} from "./presentation-editor-state.js";
import { useRecordPreview, type RecordDraft } from "./presentation-editor-record-preview.js";
import { pageTitle, previewTargetSource, trustSection } from "./presentation-editor-helpers.js";
import { useDraftWorkspace } from "./use-draft-workspace.js";
export interface PresentationEditorControllerInput {
templateContent: AdminTemplateContent | null | undefined;
previewWorkspace?: RuntimeWorkspace | undefined;
config: Record<string, unknown> | null | undefined;
brand: BrandProfile;
initialSelection?: PreviewSelection;
}
export interface PresentationRecordQuery {
isError: boolean;
isSuccess: boolean;
refetch: () => unknown;
}
export interface PresentationEditorController {
pageOptions: { value: string; label: string }[];
selectedPage: string | undefined;
visibleTargets: PreviewTarget[];
selectedTarget: PreviewTarget | undefined;
selectedSection: TemplateAdminSection | undefined;
selectedRecordSource: "offering" | "trust" | undefined;
selectedRecord: Offering | TrustContent | undefined;
recordSection: TemplateAdminSection | undefined;
editableSections: TemplateAdminSection[];
relevantPageLinks: { target: string; label: string | undefined }[];
inquiryRuntime: RuntimeWorkspace["inquiryForms"][number] | undefined;
draftWorkspace: RuntimeWorkspace | undefined;
previewBrand: BrandProfile;
selectedDetailOfferingId: string | undefined;
form: FormInstance<PresentationValues>;
initialValues: PresentationValues;
save: {
error: unknown;
isError: boolean;
isPending: boolean;
mutate: (values: PresentationValues) => void;
};
offeringsQuery: PresentationRecordQuery;
trustQuery: PresentationRecordQuery;
recordDraft: RecordDraft | undefined;
inquiryDraft: RuntimeWorkspace["inquiryForms"][number]["fields"] | undefined;
brandDirty: boolean;
selection: PreviewSelection | undefined;
activeTarget: string | undefined;
guardDraft: (action: () => void) => void;
selectPage: (page: string) => void;
selectDetailOffering: (id: string) => void;
selectPreviewTarget: (target: PreviewTarget) => void;
handleTargetSelected: (next?: PreviewSelection) => void;
setRecordDraft: (draft: RecordDraft | undefined) => void;
setInquiryDraft: (fields: RuntimeWorkspace["inquiryForms"][number]["fields"] | undefined) => void;
handleValuesChange: (changed: PresentationValues, allValues: PresentationValues) => void;
navigate: NavigateFunction;
}
/**
* PresentationEditor 的状态与派生数据集中在此处。
* 视图组件只负责渲染,避免页面组件继续膨胀。
*/
export function usePresentationEditorController({
templateContent,
previewWorkspace,
config,
brand,
initialSelection,
}: PresentationEditorControllerInput): PresentationEditorController {
const queryClient = useQueryClient();
const navigate = useNavigate();
const [activePage, setActivePage] = useState<string>();
const [selection, setSelection] = useState<PreviewSelection | undefined>(initialSelection);
const [hasInitializedSelection, setHasInitializedSelection] = useState(Boolean(initialSelection));
const [detailOfferingId, setDetailOfferingId] = useState<string>();
const [recordDraft, setRecordDraft] = useState<RecordDraft>();
const [inquiryDraft, setInquiryDraft] =
useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>();
const [brandDirty, setBrandDirty] = useState(false);
const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft);
const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand");
const sections = useBrandPresentationSections(templateContent);
const pageOptions = useMemo(() => {
const pages = new Map<string, string>();
for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label);
for (const section of templateContent?.admin.sections ?? []) {
const navigation = templateContent?.navigation.find((item) => item.page === section.page);
if (!pages.has(section.page))
pages.set(section.page, navigation?.label ?? pageTitle(section.page));
}
return [...pages].map(([value, label]) => ({ value, label }));
}, [templateContent]);
const selectedPage = pageOptions.some((item) => item.value === activePage)
? activePage
: pageOptions[0]?.value;
const visibleSections = sections.filter((section) => section.page === selectedPage);
const recordSections = useMemo(
() =>
(templateContent?.trustContentTypes ?? [])
.filter((item) => item.pages?.includes(selectedPage ?? ""))
.map((item) => trustSection(item, selectedPage ?? "home")),
[templateContent, selectedPage],
);
const visibleTargets = useMemo<PreviewTarget[]>(
() =>
[...(templateContent?.admin.sections ?? []), ...recordSections]
.filter(
(section) =>
section.page === selectedPage &&
(selectedPage !== "detail" || section.target === "brand"),
)
.flatMap((section) =>
(section.previewTargets ?? []).map((target) => ({
...target,
page: section.page,
source: previewTargetSource(section, target.key),
...(section.key.startsWith("trust:") ? { trustType: section.key.slice(6) } : {}),
})),
)
.concat(
selectedPage === "inquiry" && inquiryRuntime
? inquiryRuntime.fields.map((field) => ({
key: `inquiry-field:${field.key}`,
label: field.label,
page: "inquiry",
source: "inquiry" as const,
}))
: [],
),
[templateContent, selectedPage, recordSections, inquiryRuntime],
);
const activeTarget = selection?.targetKey;
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
const selectedSection = [...(templateContent?.admin.sections ?? []), ...recordSections].find(
(section) =>
section.page === selectedPage &&
section.previewTargets?.some((target) => target.key === selectedTarget?.key),
);
const selectedRecordSource =
selectedTarget?.source === "offering" || selectedTarget?.source === "trust"
? selectedTarget.source
: undefined;
const { offeringsQuery, trustQuery, selectedRecord } = usePresentationRecordQueries(
selectedRecordSource,
selection?.recordId,
);
const editableSections = filterSectionsForPreviewTarget(
visibleSections.filter((section) =>
section.fields.some((field) => field.binding.startsWith("brand.")),
),
selectedTarget?.key,
);
const recordSection = useMemo(
() =>
selectedSection && selection?.targetKey
? {
...selectedSection,
fields: selectedSection.fields.filter(
(field) => field.previewTarget === selection.targetKey,
),
}
: undefined,
[selectedSection, selection?.targetKey],
);
const handleTargetSelected = useCallback(
(next?: PreviewSelection) => {
const select = () =>
setSelection(
next
? resolvePreviewSelection(
next.targetKey,
next.recordId,
visibleTargets,
selectedPage ?? "home",
)
: undefined,
);
if (recordDraft || inquiryDraft)
guardDraft(() => {
setInquiryDraft(undefined);
setRecordDraft(undefined);
select();
});
else select();
},
[visibleTargets, selectedPage, recordDraft, inquiryDraft, guardDraft],
);
const relatedTargets = [
...(templateContent?.admin.sections ?? [])
.filter((section) => section.page === selectedPage && section.target !== "brand")
.map((section) => section.target),
...((templateContent?.trustContentTypes ?? []).some((item) =>
item.pages?.includes(selectedPage ?? ""),
)
? ["trust"]
: []),
];
const pageLinks = [...new Set(relatedTargets)].flatMap((target) =>
target === "trust"
? (templateContent?.trustContentTypes ?? [])
.filter((item) => item.pages?.includes(selectedPage ?? ""))
.map((item) => ({
target: `trust:${item.type}`,
label: `编辑${item.label}`,
}))
: [
{
target,
label: (
{ offering: "管理此页展示的业务内容", inquiry: "管理此页的咨询表单" } as Record<
string,
string
>
)[target],
},
],
);
const relevantPageLinks = selectedSection
? pageLinks.filter((item) => {
if (item.target.startsWith("trust:")) return selectedSection.target === "trust";
return item.target === selectedSection.target;
})
: pageLinks;
const formState = useBrandPresentationForm({ brand, config, sections });
const { form, initialValues } = formState;
const save = useBrandSaveMutation({
...formState,
brand,
config,
sections,
queryClient,
onSaved: () => setBrandDirty(false),
});
useEffect(() => {
const initialPage =
typeof initialSelection === "object" && "page" in initialSelection
? String(initialSelection.page)
: undefined;
if (initialPage) {
setActivePage(
pageOptions.some((item) => item.value === initialPage)
? initialPage
: pageOptions[0]?.value,
);
return;
}
if (!activePage && pageOptions.length) setActivePage(pageOptions[0]?.value);
}, [activePage, initialSelection, pageOptions]);
useEffect(() => {
if (hasInitializedSelection) return;
if (!pageOptions.length) return;
if (!initialSelection) return;
const requestedPage =
typeof initialSelection === "object" && "page" in initialSelection
? String(initialSelection.page)
: undefined;
const resolvedPage =
requestedPage && pageOptions.some((item) => item.value === requestedPage)
? requestedPage
: (pageOptions[0]?.value ?? "home");
setSelection(
resolvePreviewSelection(
initialSelection.targetKey,
initialSelection.recordId,
visibleTargets,
resolvedPage,
),
);
setActivePage(resolvedPage);
setHasInitializedSelection(true);
}, [hasInitializedSelection, initialSelection, pageOptions, selectedPage, visibleTargets]);
useEffect(() => {
if (!initialSelection) setSelection(undefined);
}, [initialSelection, selectedPage, templateContent?.displayName]);
useEffect(() => {
if (!selection?.recordId) return;
const records =
selectedTarget?.source === "trust"
? previewWorkspace?.trustItems
: previewWorkspace?.offerings;
if (records && !records.some((item) => item.id === selection.recordId)) setSelection(undefined);
}, [
previewWorkspace?.offerings,
previewWorkspace?.trustItems,
selectedTarget?.source,
selection,
]);
useEffect(
() => setRecordDraft(undefined),
[selection?.targetKey, selection?.recordId, selectedPage],
);
const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({
brand,
config,
sections,
form,
onDirty: () => setBrandDirty(true),
});
const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection });
useEffect(() => resetPreview(), [config, initialValues, resetPreview]);
const draftWorkspace = useDraftWorkspace({
previewWorkspace,
previewBrand,
inquiryRuntime,
inquiryDraft,
recordDraft,
selectedRecord,
recordSection,
recordPreview,
templateContent,
});
const selectedDetailOfferingId =
detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId)
? detailOfferingId
: draftWorkspace?.offerings[0]?.id;
const selectPage = useCallback(
(page: string) => {
guardDraft(() => {
setBrandDirty(false);
resetPreview();
setRecordDraft(undefined);
setInquiryDraft(undefined);
setActivePage(page);
});
},
[guardDraft, resetPreview],
);
const selectDetailOffering = useCallback((id: string) => {
setDetailOfferingId(id);
setSelection(undefined);
}, []);
const selectPreviewTarget = useCallback(
(target: PreviewTarget) => {
const recordId =
target.source === "offering"
? selectedPage === "detail"
? selectedDetailOfferingId
: draftWorkspace?.offerings[0]?.id
: target.source === "trust"
? previewTrustRecordId(draftWorkspace?.trustItems ?? [], target.trustType)
: undefined;
handleTargetSelected({
targetKey: target.key,
...(recordId ? { recordId } : {}),
});
},
[handleTargetSelected, selectedPage, selectedDetailOfferingId, draftWorkspace],
);
return {
pageOptions,
selectedPage,
visibleTargets,
selectedTarget,
selectedSection,
selectedRecordSource,
selectedRecord,
recordSection,
editableSections,
relevantPageLinks,
inquiryRuntime,
draftWorkspace,
previewBrand,
selectedDetailOfferingId,
form,
initialValues,
save,
offeringsQuery,
trustQuery,
recordDraft,
inquiryDraft,
brandDirty,
selection,
activeTarget,
guardDraft,
selectPage,
selectDetailOffering,
selectPreviewTarget,
handleTargetSelected,
setRecordDraft,
setInquiryDraft,
handleValuesChange,
navigate,
};
}
@@ -1,4 +1,4 @@
import { App, Form } from "antd"; import { Form, message } from "antd";
import { useMutation, useQuery } from "@tanstack/react-query"; import { useMutation, useQuery } from "@tanstack/react-query";
import type { QueryClient } from "@tanstack/react-query"; import type { QueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
@@ -46,8 +46,8 @@ export function useBrandPresentationSections(
return [ return [
...[...new Set(declaredTemplateFields.map((field) => field.page ?? "home"))].map((page) => ({ ...[...new Set(declaredTemplateFields.map((field) => field.page ?? "home"))].map((page) => ({
key: `template-data:${page}`, key: `template-data:${page}`,
title: "页面方案专属内容", title: "模板专属内容",
description: "这些字段由当前页面方案定义,保存后发布才会对外展示。", description: "这些字段由当前小程序模板定义,保存后发布才会对外展示。",
page, page,
target: "brand" as const, target: "brand" as const,
fields: declaredTemplateFields.filter((field) => (field.page ?? "home") === page), fields: declaredTemplateFields.filter((field) => (field.page ?? "home") === page),
@@ -89,6 +89,7 @@ export function useBrandPresentationForm({
return values; return values;
}, [brand, config, sections]); }, [brand, config, sections]);
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
return { form, initialValues }; return { form, initialValues };
} }
@@ -97,7 +98,6 @@ interface BrandSaveMutationOptions extends BrandPresentationFormState {
config: Record<string, unknown> | null | undefined; config: Record<string, unknown> | null | undefined;
sections: TemplateAdminSection[]; sections: TemplateAdminSection[];
queryClient: QueryClient; queryClient: QueryClient;
onSaved: () => void;
} }
export function useBrandSaveMutation({ export function useBrandSaveMutation({
@@ -105,12 +105,12 @@ export function useBrandSaveMutation({
config, config,
sections, sections,
queryClient, queryClient,
onSaved,
}: BrandSaveMutationOptions) { }: BrandSaveMutationOptions) {
const { message } = App.useApp();
return useMutation({ return useMutation({
mutationFn: (values: PresentationValues) => { mutationFn: (values: PresentationValues) => {
const nextConfig = applyPresentationValues(config, sections, values); const nextConfig = applyPresentationValues(config, sections, values);
const contentConfig = { ...nextConfig };
delete contentConfig.visualTemplateKey;
const standard = applyStandardBrandValues( const standard = applyStandardBrandValues(
brand as unknown as Record<string, unknown>, brand as unknown as Record<string, unknown>,
sections, sections,
@@ -122,10 +122,9 @@ export function useBrandSaveMutation({
key !== "config" && value !== (brand as unknown as Record<string, unknown>)[key], key !== "config" && value !== (brand as unknown as Record<string, unknown>)[key],
), ),
); );
return createApiClient().updateAdminBrand({ ...changed, config: nextConfig }); return createApiClient().updateAdminBrand({ ...changed, config: contentConfig });
}, },
onSuccess: () => { onSuccess: () => {
onSaved();
message.success("页面内容已保存为草稿,发布后小程序才会更新"); message.success("页面内容已保存为草稿,发布后小程序才会更新");
window.dispatchEvent(new Event("template-preview-refresh")); window.dispatchEvent(new Event("template-preview-refresh"));
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] }); void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
@@ -1,5 +0,0 @@
import { createContext } from "react";
export const TemplatePreviewAssetsContext = createContext<
Record<string, { sha256: string; dataUrl: string }> | undefined
>(undefined);
@@ -1,5 +1,4 @@
import React from "react"; import React from "react";
import { TemplatePreviewAssetsContext } from "./preview-assets.js";
export const TemplateAssetContext = React.createContext(""); export const TemplateAssetContext = React.createContext("");
const templateAssets = import.meta.glob("../../../../../packages/template-*/miniapp/assets/**/*", { const templateAssets = import.meta.glob("../../../../../packages/template-*/miniapp/assets/**/*", {
@@ -27,21 +26,7 @@ const element = (tag) =>
export const View = element("div"); export const View = element("div");
export const Text = element("span"); export const Text = element("span");
export const Button = React.forwardRef( export const Button = element("button");
({ children, className, style, onClick, loading, ...props }, ref) =>
React.createElement(
"button",
{
...props,
ref,
className,
style,
onClick,
...(loading ? { "aria-busy": "true" } : {}),
},
children,
),
);
export const Input = React.forwardRef(({ onInput, ...props }, ref) => export const Input = React.forwardRef(({ onInput, ...props }, ref) =>
React.createElement("input", { React.createElement("input", {
...props, ...props,
@@ -114,19 +99,10 @@ export function Checkbox({ value, checked }) {
export const Label = element("label"); export const Label = element("label");
export const Image = React.forwardRef(({ mode, src, style, ...props }, ref) => { export const Image = React.forwardRef(({ mode, src, style, ...props }, ref) => {
const key = React.useContext(TemplateAssetContext); const key = React.useContext(TemplateAssetContext);
const assets = React.useContext(TemplatePreviewAssetsContext);
const normalizedSrc = typeof src === "string" ? src.trim() : "";
if (!normalizedSrc) return null;
return React.createElement("img", { return React.createElement("img", {
...props, ...props,
ref, ref,
src: src: resolveImageSource(src, key),
assets && normalizedSrc.startsWith("/assets/")
? // 导入包资源以 /assets 开头;本地多模板预览的 renderer 可能额外携带包 key 前缀。
(assets[normalizedSrc]?.dataUrl ??
assets[normalizedSrc.replace(`/assets/${key}/`, "/assets/")]?.dataUrl ??
normalizedSrc)
: resolveImageSource(normalizedSrc, key),
style: { objectFit: mode === "aspectFit" ? "contain" : "cover", ...style }, style: { objectFit: mode === "aspectFit" ? "contain" : "cover", ...style },
}); });
}); });
@@ -2,27 +2,13 @@ import React from "react";
const noop = () => Promise.resolve(); const noop = () => Promise.resolve();
export const useRouter = () => ({ params: {} }); export const useRouter = () => ({ params: {} });
export const useDidShow = (callback) => React.useEffect(callback, []); export const useDidShow = (callback) => React.useEffect(callback, []);
// Admin 画布监听该事件完成画布内路由;真实 Taro 端仍使用原始 API。
const emitPreviewNavigation = (method, options) => {
if (typeof window === "undefined") return;
window.dispatchEvent(
new CustomEvent("template-preview-navigate", { detail: { method, options } }),
);
};
const Taro = { const Taro = {
setStorageSync() {}, setStorageSync() {},
getStorageSync() { getStorageSync() {
return undefined; return undefined;
}, },
removeStorageSync() {}, removeStorageSync() {},
switchTab(options) { switchTab: noop,
emitPreviewNavigation("switchTab", options); navigateTo: noop,
return Promise.resolve();
},
navigateTo(options) {
emitPreviewNavigation("navigateTo", options);
return Promise.resolve();
},
}; };
export default Taro; export default Taro;
@@ -8,7 +8,10 @@ import type {
TrustContent, TrustContent,
} from "@personal-brand/api-client"; } from "@personal-brand/api-client";
import { projectBrandAliases, projectTrustPresentation } from "@personal-brand/api-client"; import { projectBrandAliases, projectTrustPresentation } from "@personal-brand/api-client";
import { presentationFieldName } from "../../lib/presentation/presentation-bindings.js"; import {
presentationFieldName,
type PresentationValues,
} from "../../lib/presentation/presentation-bindings.js";
import type { RecordDraft } from "./presentation-editor-record-preview.js"; import type { RecordDraft } from "./presentation-editor-record-preview.js";
interface DraftWorkspaceInput { interface DraftWorkspaceInput {
@@ -1,9 +1,8 @@
import { useEffect } from "react"; import { useEffect } from "react";
import { App } from "antd"; import { Modal } from "antd";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
export function useEditorDraft(dirty: boolean) { export function useEditorDraft(dirty: boolean) {
const { modal } = App.useApp();
const navigate = useNavigate(); const navigate = useNavigate();
useEffect(() => { useEffect(() => {
if (!dirty) return; if (!dirty) return;
@@ -23,7 +22,7 @@ export function useEditorDraft(dirty: boolean) {
return; return;
event.preventDefault(); event.preventDefault();
event.stopImmediatePropagation(); event.stopImmediatePropagation();
modal.confirm({ Modal.confirm({
title: "有尚未保存的修改", title: "有尚未保存的修改",
content: "离开工作台会丢失未保存内容。请先保存,或确认放弃修改。", content: "离开工作台会丢失未保存内容。请先保存,或确认放弃修改。",
okText: "放弃修改并继续", okText: "放弃修改并继续",
@@ -41,7 +40,7 @@ export function useEditorDraft(dirty: boolean) {
}, [dirty, navigate]); }, [dirty, navigate]);
return (action: () => void) => { return (action: () => void) => {
if (!dirty) return action(); if (!dirty) return action();
modal.confirm({ Modal.confirm({
title: "有尚未保存的修改", title: "有尚未保存的修改",
content: "切换后当前内容可能丢失。请先保存,或确认放弃修改。", content: "切换后当前内容可能丢失。请先保存,或确认放弃修改。",
okText: "放弃修改并继续", okText: "放弃修改并继续",
@@ -1,129 +0,0 @@
import { Alert, App, Button, Card, Col, Row, Space } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { EmptyState } from "../../components/EmptyState.js";
import { QueryState } from "../../components/QueryState.js";
import { StatusTag } from "../../components/StatusTag.js";
const client = createApiClient();
export function BrandsPage({ canCreate }: { canCreate: boolean }) {
const { message } = App.useApp();
const navigate = useNavigate();
const brands = useQuery({
queryKey: ["admin-brand-memberships"],
queryFn: () => client.listAdminBrands(),
});
const current = useQuery({
queryKey: ["admin-shell-brand"],
queryFn: () => client.getAdminBrand(),
});
const switchBrand = async (brandId: string) => {
try {
await client.switchAdminBrand(brandId);
window.location.assign("/admin/overview");
} catch (error) {
message.error(error instanceof Error ? error.message : "品牌切换失败,请重试");
}
};
return (
<QueryState
loading={brands.isLoading || current.isLoading}
error={brands.error || current.error}
onRetry={() => {
void brands.refetch();
void current.refetch();
}}
>
<AdminPageHeader
title="品牌管理"
description="每个品牌拥有独立的业务类型、页面方案、内容与发布记录。"
extra={
canCreate ? (
<Button
type="primary"
icon={<PlusOutlined />}
onClick={() => navigate("/admin/brands/new")}
>
创建品牌
</Button>
) : null
}
/>
<Alert
className="admin-offset-bottom"
type="info"
showIcon
title="切换品牌会进入对应品牌的工作区"
description="品牌之间的业务内容、成员、发布记录和页面方案相互隔离。"
/>
{brands.data?.length ? (
<Row gutter={[16, 16]} className="admin-equal-height">
{brands.data.map((membership) => {
const isCurrent = membership.brand.id === current.data?.id;
return (
<Col key={membership.brand.id} xs={24} lg={12}>
<Card
title={membership.brand.name}
extra={
<StatusTag
tone={isCurrent ? "success" : "neutral"}
label={
isCurrent ? "当前品牌" : membership.role === "owner" ? "负责人" : "编辑"
}
/>
}
actions={[
<Button
key="switch"
type={isCurrent ? "default" : "primary"}
disabled={isCurrent}
onClick={() => void switchBrand(membership.brand.id)}
>
{isCurrent ? "正在使用" : "进入此品牌"}
</Button>,
]}
>
<Space orientation="vertical" size={8}>
<span className="admin-section-description">
小程序地址标识:{membership.brand.slug}
</span>
{membership.role === "owner" ? (
<span className="admin-section-description">
你可以在该品牌中管理页面方案、成员和发布。
</span>
) : (
<span className="admin-section-description">
你在该品牌中的角色是内容编辑,不能管理页面方案或成员。
</span>
)}
</Space>
</Card>
</Col>
);
})}
</Row>
) : (
<Card>
<EmptyState
title="还没有可管理的品牌"
description={
canCreate ? "创建第一个品牌后即可开始配置内容。" : "请联系品牌负责人邀请你加入。"
}
action={
canCreate ? (
<Button type="primary" onClick={() => navigate("/admin/brands/new")}>
创建品牌
</Button>
) : undefined
}
/>
</Card>
)}
</QueryState>
);
}
@@ -1,206 +0,0 @@
import { Alert, Button, Col, Form, Input, Radio, Row, Space } from "antd";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import type {
BrandCreationOptionBusiness,
BrandCreationOptionPageScheme,
CreateBrandInput,
} from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { AdminSection } from "../../components/AdminSection.js";
import { EmptyState } from "../../components/EmptyState.js";
import { MutationError, QueryState } from "../../components/QueryState.js";
import { StatusTag } from "../../components/StatusTag.js";
const client = createApiClient();
function compatibleSchemes(
schemes: BrandCreationOptionPageScheme[],
businessType?: CreateBrandInput["businessType"],
) {
return businessType
? schemes.filter((scheme) => scheme.supportedBusinessTypes.includes(businessType))
: [];
}
export function CreateBrandPage() {
const navigate = useNavigate();
const [form] = Form.useForm<CreateBrandInput>();
const businessType = Form.useWatch("businessType", form);
const selectedSchemeId = Form.useWatch("templatePackageVersionId", form);
const options = useQuery({
queryKey: ["admin-brand-creation-options"],
queryFn: () => client.getAdminBrandCreationOptions(),
});
const create = useMutation({
mutationFn: (values: CreateBrandInput) => client.createAdminBrand(values),
onSuccess: () => {
// 创建接口会切换品牌会话;完整导航确保所有查询重新绑定到新品牌。
window.location.assign("/admin/overview");
},
});
const schemes = compatibleSchemes(options.data?.pageSchemes ?? [], businessType);
return (
<QueryState
loading={options.isLoading}
error={options.error}
onRetry={() => void options.refetch()}
>
<AdminPageHeader
title="创建品牌"
description="先确定业务类型,再选择与该业务兼容的页面方案。业务类型创建后不可更改。"
/>
<Form
form={form}
layout="vertical"
onFinish={(values) => create.mutate(values)}
onValuesChange={(changed: Partial<CreateBrandInput>) => {
if (!changed.businessType) return;
const nextSchemes = compatibleSchemes(
options.data?.pageSchemes ?? [],
changed.businessType,
);
const selected = form.getFieldValue("templatePackageVersionId") as unknown;
if (!nextSchemes.some((scheme) => scheme.templatePackageVersionId === selected)) {
form.setFieldValue("templatePackageVersionId", undefined);
}
}}
>
<div className="admin-stack">
<AdminSection title="品牌身份" description="这些信息会展示给访客,之后仍可继续完善。">
<Row gutter={16}>
<Col xs={24} md={12}>
<Form.Item
name="name"
label="品牌名称"
rules={[{ required: true, message: "请输入品牌名称" }]}
>
<Input size="large" maxLength={80} placeholder="例如:林境建筑" />
</Form.Item>
</Col>
<Col xs={24} md={12}>
<Form.Item
name="slug"
label="小程序地址标识"
help="用于生成和识别公开品牌地址,只能使用小写字母、数字和连字符。"
rules={[
{ required: true, message: "请输入小程序地址标识" },
{
pattern: /^[a-z0-9]+(?:-[a-z0-9]+)*$/,
message: "只能使用小写字母、数字和连字符",
},
]}
>
<Input size="large" maxLength={80} placeholder="例如:linjing-architecture" />
</Form.Item>
</Col>
</Row>
</AdminSection>
<AdminSection
title="业务类型"
description="业务类型决定品牌需要填写哪些内容。不同业务类型的字段和能力不同,创建后不能修改。"
>
<Form.Item name="businessType" rules={[{ required: true, message: "请选择业务类型" }]}>
<Radio.Group className="admin-stack">
<Row gutter={[12, 12]}>
{(options.data?.businesses ?? []).map((business: BrandCreationOptionBusiness) => (
<Col key={business.key} xs={24} lg={8}>
<Radio.Button value={business.key} className="admin-choice-card">
<strong>{business.name}</strong>
<span>{business.description}</span>
</Radio.Button>
</Col>
))}
</Row>
</Radio.Group>
</Form.Item>
{businessType ? (
schemes.length ? null : (
<Alert
type="warning"
showIcon
title="当前业务类型还没有可用的页面方案"
description="请先联系平台管理员发布兼容的页面方案。"
/>
)
) : (
<Alert type="info" showIcon title="选择业务类型后,将只显示兼容的页面方案" />
)}
</AdminSection>
<AdminSection
title="页面方案"
description="页面方案决定页面结构、视觉和资源位。版本可在创建后继续升级或切换。"
>
{schemes.length ? (
<Form.Item
name="templatePackageVersionId"
rules={[{ required: true, message: "请选择页面方案" }]}
>
<Radio.Group className="admin-stack">
<Space orientation="vertical" size={12} className="admin-full-width">
{schemes.map((scheme) => (
<Radio.Button
key={scheme.templatePackageVersionId}
value={scheme.templatePackageVersionId}
className="admin-choice-card admin-choice-card--wide"
>
<span className="admin-row-line">
<strong>{scheme.name}</strong>
<StatusTag
tone={scheme.isLatestForPackage ? "success" : "neutral"}
label={
scheme.isLatestForPackage
? `最新版 ${scheme.version}`
: `版本 ${scheme.version}`
}
/>
</span>
<span>{scheme.description}</span>
</Radio.Button>
))}
</Space>
</Radio.Group>
</Form.Item>
) : (
<EmptyState
title={businessType ? "没有兼容的页面方案" : "先选择业务类型"}
description={
businessType
? "平台尚未发布适配该业务类型的页面方案。"
: "选择业务类型后,这里会列出可用的页面结构和视觉方案。"
}
/>
)}
</AdminSection>
<Alert
type="info"
showIcon
title="创建品牌不会自动导入示例内容"
description="新品牌会从空白内容开始,避免把示例品牌、案例或联系方式误当成真实信息发布。"
/>
<MutationError error={create.error} />
<Space>
<Button onClick={() => navigate("/admin/brands")}>取消</Button>
<Button
type="primary"
htmlType="submit"
size="large"
loading={create.isPending}
disabled={
!businessType ||
!schemes.some((scheme) => scheme.templatePackageVersionId === selectedSchemeId)
}
>
创建并进入品牌
</Button>
</Space>
</div>
</Form>
</QueryState>
);
}
@@ -15,7 +15,7 @@ export function CapabilitiesPage() {
<QueryState loading={query.isLoading} error={query.error} onRetry={() => void query.refetch()}> <QueryState loading={query.isLoading} error={query.error} onRetry={() => void query.refetch()}>
<AdminPageHeader <AdminPageHeader
title="能力插件" title="能力插件"
description="以经营者视角调整当前页面方案提供的业务能力;保存后进入草稿,发布后生效。" description="以经营者视角调整模板能力的开关与展示设置;保存后进入草稿,发布后生效。"
/> />
{query.data?.length ? ( {query.data?.length ? (
<Row gutter={[16, 16]} className="admin-equal-height"> <Row gutter={[16, 16]} className="admin-equal-height">
@@ -29,9 +29,9 @@ export function CapabilitiesPage() {
<Card> <Card>
<EmptyState <EmptyState
icon={<AppstoreOutlined />} icon={<AppstoreOutlined />}
title="当前页面方案没有可配置能力" title="当前模板没有可配置能力"
description="能力由品牌当前使用的业务类型和页面方案决定。" description="能力的开关由品牌当前使用的行业模板决定;更换行业模板不在本版本范围内。"
action={<Button onClick={() => navigate("/admin/page-scheme")}>查看页面方案</Button>} action={<Button onClick={() => navigate("/admin/publication")}>查看模板与发布</Button>}
/> />
</Card> </Card>
)} )}
@@ -8,12 +8,12 @@ import { CapabilityStatusControl, CapabilityStatusTag } from "./CapabilityStatus
const sourceLabels = { const sourceLabels = {
brand: "品牌覆盖", brand: "品牌覆盖",
template: "方案默认", template: "模板默认",
} as const; } as const;
const disablePolicyLabels = { const disablePolicyLabels = {
allowed: "该能力允许停用,保存后进入草稿。", allowed: "该能力允许停用,保存后进入草稿。",
disabled: "该能力为页面方案必需项,保存后进入草稿。", disabled: "该能力为模板必需项,保存后进入草稿。",
} as const; } as const;
const updatedTimeFormatter = new Intl.DateTimeFormat("zh-CN", { const updatedTimeFormatter = new Intl.DateTimeFormat("zh-CN", {
@@ -143,7 +143,7 @@ export function CapabilityCard({ capability }: { capability: AdminCapability })
) : null} ) : null}
<Typography.Text type="secondary"> <Typography.Text type="secondary">
{capability.source === "template" {capability.source === "template"
? "当前使用页面方案默认设置;修改后保存会创建品牌覆盖。" ? "当前使用模板默认设置;修改后保存会创建品牌覆盖。"
: "当前已创建品牌覆盖;修改后保存会更新草稿。"} : "当前已创建品牌覆盖;修改后保存会更新草稿。"}
{capability.updatedAt {capability.updatedAt
? ` 最近更新:${updatedTimeFormatter.format(new Date(capability.updatedAt))}` ? ` 最近更新:${updatedTimeFormatter.format(new Date(capability.updatedAt))}`
@@ -1,5 +1,5 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { App } from "antd"; import { message } from "antd";
import { createApiClient } from "../../../lib/api.js"; import { createApiClient } from "../../../lib/api.js";
import { readAdminCapability } from "../types.js"; import { readAdminCapability } from "../types.js";
import type { CapabilityValues } from "../types.js"; import type { CapabilityValues } from "../types.js";
@@ -17,7 +17,6 @@ export function useCapabilityQuery() {
} }
export function useCapabilityMutation() { export function useCapabilityMutation() {
const { message } = App.useApp();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: ({ key, ...values }: { key: string } & CapabilityValues) => mutationFn: ({ key, ...values }: { key: string } & CapabilityValues) =>
Loaded 100 of 431 files, more files were not shown because too many files have changed in this diff. Show more