Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47a24e0d53 | ||
|
|
c78deafee3 | ||
|
|
3330b536dc | ||
|
|
07629a4596 | ||
|
|
5c6ad02f46 | ||
|
|
048c42207c | ||
|
|
67735afd45 | ||
|
|
0574a85632 | ||
|
|
18ddf125be | ||
|
|
bb0709b8cc | ||
|
|
076c6124c8 | ||
|
|
89fdfd7d83 | ||
|
|
f87b26b201 | ||
|
|
466dc66907 | ||
|
|
357f271639 | ||
|
|
f3adf7bc15 | ||
|
|
4512d2601d | ||
|
|
d0902d6568 | ||
|
|
7e1dd543fb | ||
|
|
3003e7801d | ||
|
|
567921e726 | ||
|
|
03f947e9b8 | ||
|
|
6ac2d9421b | ||
|
|
aa42e7b866 | ||
|
|
e09b56e0f3 | ||
|
|
84956b8fe2 | ||
|
|
f57c0ca0ea | ||
|
|
9c15a822e9 | ||
|
|
85f37d2eae | ||
|
|
222055595c | ||
|
|
b1d5c2b4b0 | ||
|
|
787a50369f | ||
|
|
422162e580 | ||
|
|
26bcb2b66e | ||
|
|
91322fa9a0 | ||
|
|
bfbcee45bb | ||
|
|
46b1690f6c | ||
|
|
0e0ca201a7 | ||
|
|
569156c977 | ||
|
|
20e7e8bb81 | ||
|
|
20eb160abf | ||
|
|
d0ef25cfb3 | ||
|
|
d2ce2d2a84 | ||
|
|
f57e1b1336 | ||
|
|
22a82dbfba | ||
|
|
fa6b492bce | ||
|
|
860d9266fe | ||
|
|
a2932b1134 | ||
|
|
849ae5df05 | ||
|
|
df2b1f6031 | ||
|
|
66dbba5748 | ||
|
|
c5db30f817 | ||
|
|
541304a763 | ||
|
|
fd2e970d8b | ||
|
|
5b85fe769f | ||
|
|
0b14b5a814 | ||
|
|
c5af790554 |
No files matched your search
@@ -0,0 +1,30 @@
|
||||
# Admin 编辑工作区重构
|
||||
|
||||
## 目标
|
||||
|
||||
把 Admin 的品牌配置与小程序页面编辑整理成一个层级清晰、可持续扩展的工作区。用户能够明确区分品牌基础资料、模板内容、业务记录和页面预览;页面预览、区域选择和字段编辑保持统一行为。
|
||||
|
||||
## 交付边界
|
||||
|
||||
- 品牌资料页面减少 Card 堆叠,形成连续的配置分组。
|
||||
- 小程序页面配置成为主要编辑工作区,使用页面导航、预览画布和编辑面板的稳定布局。
|
||||
- 详情页只提供业务记录选择和动态预览,不出现品牌级详情编辑表单。
|
||||
- 预览选区、高亮、编辑状态、空状态和错误状态保持一致。
|
||||
- 不改变后端数据模型和小程序业务语义;模板仍通过 manifest 声明页面、区域和字段。
|
||||
|
||||
## 设计原则
|
||||
|
||||
- 基础品牌事实只提供一个编辑入口。
|
||||
- 模板专属字段由模板 manifest 驱动,不在共享页面中写行业逻辑。
|
||||
- 预览是编辑上下文的一部分,不单独启动每个模板服务。
|
||||
- 详情页数据来自选中的业务记录,视觉文案只能作为模板配置存在。
|
||||
- 页面区块使用平面分组和分隔线,只有真正需要独立操作的区域使用 Card。
|
||||
|
||||
## 验收标准
|
||||
|
||||
- 1920、1280、1024、768 和 390 宽度下布局无横向溢出。
|
||||
- 品牌资料、页面配置和发布状态的层级可以在首屏理解。
|
||||
- 首页、业务、服务、详情、咨询、成功和记录页面均可切换并保持稳定高度。
|
||||
- 点击模板区域后,选区高亮和右侧编辑面板始终同步。
|
||||
- 详情页只能选择业务记录并预览,不能出现品牌级详情字段编辑。
|
||||
- 通过 Admin/Taro typecheck、模板契约测试、生产构建和关键浏览器交互测试。
|
||||
@@ -0,0 +1,40 @@
|
||||
# Progress
|
||||
|
||||
## 保存体验收尾
|
||||
|
||||
- 品牌资料、页面字段、记录和咨询字段暴露未保存状态;保存成功清除对应状态,失败保留输入。
|
||||
- 切换页面/记录提供取消或放弃确认,刷新关闭窗口提供提醒,工作区内链接离开提供确认。
|
||||
- 保存操作区采用统一的面板底部样式;业务记录与品牌配置继续分别保存到原有接口。
|
||||
- 浏览器测试补充未保存取消切换与失败重试场景;测试采用独立接口 fixture,不冒充当前数据库的端到端验收。
|
||||
- 本轮没有重构品牌切换器或新增跨实体批量保存 API,这些不作为已验证能力。
|
||||
|
||||
## 工作台重构补充验收
|
||||
|
||||
- 上一轮将布局整理判为全部完成不准确,补充真正的工作台任务:视图分离、三栏布局和层级区域导航。
|
||||
- 默认显示页面编辑,品牌基础表单在“品牌资料”视图访问;两套组件保持挂载,切换不丢弃草稿。
|
||||
- 区域导航移至左栏,预览居中,属性编辑位于右栏;子区域缩进,选区与导航选中状态同步。
|
||||
- 顶部区分草稿工作区与检查发布入口,保存仍由各内容表单负责,避免错误承诺跨实体统一保存。
|
||||
- 已通过 2 项浏览器回归和五种宽度检查,并查看 1920 宽度实际截图。
|
||||
|
||||
## 2026-10-10
|
||||
|
||||
- 建立 Admin 编辑工作区重构 Epic。
|
||||
- 当前已知问题:品牌资料上方存在多个连续 Card;小程序页面配置仍是普通 Card;预览区和编辑面板层级不够明确;详情页需要保持动态只读预览;选区高亮需要继续验证真实鼠标路径。
|
||||
- 当前基线能力:模板 manifest、Taro renderer、RuntimeWorkspace 和 Admin 字段绑定已经形成契约;本 Epic 主要调整 Admin 信息架构与视觉层。
|
||||
- 第 1 项已完成:确认 `BrandPage` 的两列 Card 结构、页面配置固定最小高度、模板说明右栏和编辑器内部重复导航。
|
||||
- 第 2 项开始:先整理品牌资料页面层级,减少 Card 作为页面区块容器的使用。
|
||||
- 第 2 项阶段性完成:`BrandPage` 已将品牌身份、联系合作、模板视觉改为连续分组,模板说明改为右侧辅助 `Alert`,并增加移动端断点。
|
||||
- 验证:Admin typecheck 通过,`admin-editor.spec.ts` 2 项通过。
|
||||
- 第 2 项完成,第 3 项开始:`PresentationEditor` 已移除外层 Card 和固定最小高度,改为独立工作区标题区;下一步处理工作区内部布局和视觉状态。
|
||||
|
||||
- 工作区完成:品牌配置使用连续分组;模板辅助信息移入基础资料尾部;编辑器使用完整宽度两栏布局,窄屏上下排列。
|
||||
- 未选中时显示引导,详情页目标列表为空且不显示点选工具。
|
||||
- 新增 1920/1280/1024/768/390 宽度无溢出断言和截图,已人工查看 1280 与 390 截图。
|
||||
- 验证通过:Admin/Taro typecheck、Admin lint、全仓 format:check、19 项模板契约测试、Admin build、2 项浏览器测试。
|
||||
- lint 暴露已有 InquiryPreviewEditor 类型问题,已通过 Form 泛型和普通对象传入修复。
|
||||
- 保留已知构建 api chunk 超过 500 kB 提示,后续由 Admin 前端打包优化任务负责;记录在 ADR 0021。
|
||||
- 本轮不涉及新增 API 或数据迁移。
|
||||
|
||||
- 最终收尾完成:新增全局未保存离开提醒、切换确认、保存状态和失败保留输入;属性面板保存按钮固定在底部。
|
||||
- 验证通过:Admin/Taro typecheck、Admin lint、format:check、19 项模板契约、Admin build、浏览器 2 项(含未保存取消切换与失败重试)。
|
||||
- 构建仍有 api chunk 超过 500 kB 的提示,属于后续打包优化项,不影响构建结果。
|
||||
@@ -0,0 +1,6 @@
|
||||
id,title,status,task_type,depends_on,acceptance_criteria,validation_command,task_dir,notes
|
||||
1,建立现状基线与页面覆盖清单,DONE,single-full,,记录当前布局层级、Card 使用、响应式问题和关键交互,测试基线截图与 DOM 检查,.codex-tasks/admin-editor-workspace/tasks/01-baseline/,已完成代码结构基线与验证记录
|
||||
2,重构品牌配置的信息架构,DONE,single-full,1,品牌资料按身份联系模板视觉分组且减少卡片嵌套,Admin typecheck; browser brand page test,.codex-tasks/admin-editor-workspace/tasks/02-information-architecture/,已完成分组与模板说明层级调整
|
||||
3,重构小程序页面编辑工作区,DONE,single-full,1;2,页面导航预览画布编辑面板形成稳定三栏或响应式两栏布局,Admin build; browser editor test,.codex-tasks/admin-editor-workspace/tasks/03-workspace-ui/,完整宽度两栏工作区,窄屏堆叠;详情页只读;未选中显示引导
|
||||
4,统一编辑器视觉系统与状态样式,DONE,single-full,3,间距层级按钮选区空状态错误状态统一且无 Card 堆叠,Prettier; Admin build; screenshot review,.codex-tasks/admin-editor-workspace/tasks/04-visual-system/,统一导航工具条、画布边界、区域按钮和面板间距;已检查 1280 与 390 截图
|
||||
5,全页面回归与交付验收,DONE,single-full,2;3;4,关键页面交互和响应式检查通过并记录残余风险,validate:templates; typecheck; build; browser tests,.codex-tasks/admin-editor-workspace/tasks/05-regression/,5 种宽度无溢出;浏览器 2 项、契约 19 项、格式、lint、类型和构建通过
|
||||
|
@@ -0,0 +1,32 @@
|
||||
# 当前基线
|
||||
|
||||
## 页面结构
|
||||
|
||||
- `BrandPage` 使用两列布局:左侧 `xl=16`,右侧 `xl=8`。
|
||||
- 左侧依次渲染“我是谁”“如何联系与合作”“模板与品牌视觉”三个 `Card`。
|
||||
- 左侧表单之后渲染“小程序页面配置” `Card`。
|
||||
- 右侧单独渲染“模板说明” `Card`。
|
||||
- 页面配置内部还有页面导航、页面预览、详情业务选择器、预览目标按钮和右侧编辑表单。
|
||||
|
||||
## 已确认问题
|
||||
|
||||
- 配置 Card 与页面编辑 Card 在视觉上处于同一层级,用户难以判断基础资料和页面编辑的关系。
|
||||
- “模板说明”占据右侧固定列,但对编辑流程帮助有限,造成首屏空间浪费。
|
||||
- 页面配置使用 `minHeight: 760/620`,内容较少的页面会出现大面积空白。
|
||||
- 页面配置内部的预览目标按钮与画布选区重复表达同一件事。
|
||||
- 详情页已经改为动态预览提示,但页面整体仍沿用通用编辑器的表单布局。
|
||||
- 品牌资料表单保存按钮位于所有配置分组之后,长页面中不够容易发现。
|
||||
|
||||
## 现有可复用能力
|
||||
|
||||
- 模板 manifest 声明页面、区域、字段和 preview target。
|
||||
- `RuntimeWorkspace` 为组件预览提供品牌、业务记录、信任内容和咨询表单数据。
|
||||
- `ComponentTemplatePreview` 支持点选、高亮、组合区域和浏览模式。
|
||||
- `PresentationEditor` 已支持业务记录编辑、信任内容编辑和咨询字段编辑。
|
||||
|
||||
## 基线验证
|
||||
|
||||
- `pnpm --filter @personal-brand/admin typecheck`:通过。
|
||||
- `pnpm --filter @personal-brand/taro typecheck`:通过。
|
||||
- `pnpm validate:templates`:19 项模板契约测试通过。
|
||||
- 已有 `admin-editor.spec.ts` 覆盖页面切换、预览选区、业务记录、信任内容、咨询表单和详情页动态预览。
|
||||
@@ -0,0 +1,64 @@
|
||||
# 本轮执行进度
|
||||
|
||||
## 当前恢复点
|
||||
|
||||
- 任务:现有两模板按通用规则诊断、修复、验收。
|
||||
- 形态:single-full。
|
||||
- 进度:7/7;任务真源为 TODO.csv。
|
||||
- 当前:本轮审计修复和证据归档完成,详见 docs/template-audit-2026-10-10.md。
|
||||
- 验证:真实数据库集成 41 项通过,覆盖 193 个声明绑定;真实 manifest 浏览器逐页/320 与 390 宽布局、全部实际存在目标的画布内部点选、方法和流程子字段修改重载共 2 项通过(42.3 秒)。
|
||||
- 静态报告:两模板 blocker 均为 0,food review 55,linjing review 23;命令仍退出 1,保留原报告 completionStatus=unverified。
|
||||
- 动态审查:raw/manual-review.json 为每条 review 保存来源、只读理由和证据;条件组合未穷举,不将源码审查冒充浏览器全分支验证。
|
||||
- 数据:只在随机独立 schema 做 integration;没有生产 migration 或 seed 改写。
|
||||
- 下一步:当前无剩余实现任务;保持未提交 diff,后续模板按相同规则验收。静态 completionStatus 不自动改为完整通过。
|
||||
|
||||
## 本轮新增故障与修复
|
||||
|
||||
1. 新 config 被旧完整品牌对象覆盖:仅发送改变的标准字段和新 config,剔除模板选择字段。
|
||||
2. 保存后 Admin 预览读取旧发布快照:从当前品牌记录构建内存草稿,与公开投影共用服务;公开仍读取发布快照。
|
||||
3. 旧 config.avatarUrl 覆盖共享头像:标准列优先,主动清空后旧别名不得复活。
|
||||
4. templateFields 错页、templateData 未同步:按 page 分组并同步专属草稿。
|
||||
5. 列表只检查 binding:补逐个 itemFields 检查及排序;空区域提供内容管理入口。
|
||||
6. 详情正文与底部按钮共用目标:拆为两个公共编辑区,业务记录仍仅选择预览。
|
||||
|
||||
## 画布检查的失败记录
|
||||
|
||||
新增检查先后发现测试命中点不正确:圆角透明角落、父容器采样落在子区、装饰图片被遮罩覆盖。原始失败保留 raw/browser-*-failure.log;最终也发现林境 fixture 缺少所有介绍标题,使父区域没有显示文字,补真实结构的标题内容后验收通过。重新审查测试输入后,改为点击目标内有文字的叶子内容,并先确认浏览器真实 elementFromPoint 命中的最近目标。没有强制点击、删业务断言或改变模板视觉。
|
||||
|
||||
## 前轮历史(已被本轮验证补充)
|
||||
|
||||
# 本轮审计结果
|
||||
|
||||
本轮按 skill 完成诊断、修复、回归与剩余项归档;模板整体验收仍为 unverified。
|
||||
|
||||
## 静态结果
|
||||
|
||||
- acheng-campus-food:blocker 11 → 2;review 120
|
||||
- linjing-editorial:blocker 26 → 2;review 65
|
||||
|
||||
## 已验证
|
||||
|
||||
- 林境真实 manifest:主理人完整字段、最近选区、统计 2×2、数值编辑保存重载、共享简介保存重载、侧栏信任记录定位、主理人页不出现首页统计目标。
|
||||
- 餐饮现有浏览器回归通过,新增共享字段未逐一完成端到端验证。
|
||||
- 浏览器 2 项通过;模板契约 19 项、诊断器 15 项通过;Admin 单元测试、Admin/Taro 类型、Admin lint 与生产构建、全仓格式及 diff 检查通过。
|
||||
- 独立随机 schema 的 API 集成 40 项通过;不等于所有新模板字段发布流程逐项已验证。
|
||||
|
||||
## 未完成与限制
|
||||
|
||||
- 两模板详情页公共按钮文案仍由品牌配置读取,与只读详情预览边界需进一步明确,4 条静态 blocker 保留。
|
||||
- 动态循环、条件分支等 review 仍需逐项核对,不能用静态报告证明完整。
|
||||
- 林境截图验证 2×2,使用 fixture 主图且头像未加载,不能作为真实原型视觉一致性证明;原型全量对照未完成。
|
||||
- 未对每个新增共享字段执行真实数据库发布后公开读取;现有集成通过不能替代该覆盖。
|
||||
- Admin 构建仍有已有大于 500 kB chunk 提示。
|
||||
|
||||
## 经验沉淀
|
||||
|
||||
新增多入口绑定同步及未挂载字段保留规则,补入 skill 和回归。未提交 commit,未迁移生产数据。
|
||||
|
||||
## 最终门槛
|
||||
|
||||
- browser-current.log:2/2 通过,42.3 秒;实际画布目标检查没有使用 force 或 dispatchEvent。
|
||||
- integration-final.log:41/41 通过,193 个真实绑定保存/草稿/发布验证。
|
||||
- API Client 3/3、模板契约 19/19、诊断器 19/19;API/Admin/Taro 类型检查通过。
|
||||
- API/Admin lint、Admin 构建、两模板 H5 与 weapp 构建通过;格式和 diff 检查通过。
|
||||
- 完整范围、78 条动态映射 review 的源码审阅和视觉限制保留在最终文档及 raw/manual-review.json;没有将静态退出 1 隐藏为通过。
|
||||
@@ -0,0 +1,3 @@
|
||||
# 按 template-completion-audit 执行现有模板审计
|
||||
|
||||
范围:自动发现两个模板,修复共享字段入口、选区、信任页作用域与实际绑定,运行真实 manifest 浏览器及隔离数据库回归,记录未完成证据。没有生产数据迁移或自动提交。
|
||||
@@ -0,0 +1,8 @@
|
||||
id,task,status,acceptance_criteria,validation_command,completed_at,retry_count,notes
|
||||
1,采集真实基线,DONE,before 报告已存档,node scripts/template-doctor.mjs,2026-10-10,0,退出 1 保留实际问题
|
||||
2,修复公共编辑和字段绑定,DONE,真实 manifest 修改保存重载测试通过,playwright admin-editor.spec.ts,2026-10-10,1,修复共享字段未挂载覆盖
|
||||
3,执行审计验证并归档边界,DONE,保留未验证和失败项,pnpm format:check,2026-10-10,0,详情按钮与原型全量验收未完成
|
||||
4,补齐详情公共文案和真实卡片字段,DONE,所有展示字段有对应入口,pnpm validate:templates,2026-10-10,0,详情正文与底部按钮独立目标;真实卡片字段补齐;模板契约 19 项通过
|
||||
5,验证真实声明的浏览器编辑闭环,DONE,两个模板真实声明保存重载测试通过,playwright admin-editor.spec.ts,2026-10-10,0,2 项真实 manifest 浏览器通过;含逐页画布内部点击、字段面板、列表子项修改重载和多宽检查
|
||||
6,验证数据库保存发布隔离,DONE,新增字段真实持久化发布回归通过,pnpm --filter @personal-brand/api test:integration,2026-10-10,0,41 项集成通过;193 个真实绑定隔离数据库保存草稿发布验证
|
||||
7,归档动态映射和视觉验收,DONE,逐项证据与门槛验证完成,pnpm template:doctor,2026-10-10,4,78 条动态审查归档;最终画布检查通过;原型结构与视觉边界详见 docs/template-audit-2026-10-10.md
|
||||
|
@@ -0,0 +1,7 @@
|
||||
# 可视化编辑闭环
|
||||
|
||||
执行方案:docs/visual-editor-next-steps.md。
|
||||
基线:feat/admin-component-preview / 541304a。
|
||||
状态源:本目录 SUBTASKS.csv;旧 visual-editor 任务保留为历史。
|
||||
当前仅完成规划,实现未开始。各子任务开始前建立 tasks 对应目录的 SPEC.md、TODO.csv、PROGRESS.md,补充具体验证命令和证据。
|
||||
完成条件:全部子任务通过,业务内容有明确编辑入口,真实保存、发布隔离及生产部署验证完成。
|
||||
@@ -0,0 +1,13 @@
|
||||
# 进度记录
|
||||
|
||||
2026-10-09:与现有 ADR 0020、后续计划和交付清单对齐,制定四阶段实施计划。
|
||||
2026-10-09:完成任务 1。盘点两套模板页面与 manifest / renderer 目标,修复餐饮首页身份区点选、咨询页字段过滤和首页业务目标 key;`pnpm validate:templates` 19 项通过,浏览器测试 2 项通过。
|
||||
2026-10-09:完成任务 2、3、4。区域来源改为按 binding 推导;编辑面板改单列自适应;咨询表单字段可独立点选和编辑。Admin/Taro 类型检查与浏览器测试通过。
|
||||
|
||||
- 任务:可视化内容编辑闭环。
|
||||
- 形态:epic。
|
||||
- 进度:5/5 子任务完成。
|
||||
- 当前:本轮计划已完成;后续可继续做真实数据库持久化和发布隔离验收。
|
||||
- 验证:`pnpm validate:templates`、Admin/Taro typecheck、Admin build、`ADMIN_URL=http://localhost:3005 pnpm --filter @personal-brand/taro test:browser -- admin-editor.spec.ts` 均通过;计划 CSV 未纳入 Prettier 检查。
|
||||
- 文件:.codex-tasks/visual-editor-closure/SUBTASKS.csv。
|
||||
- 下一步:使用隔离品牌执行真实 API 保存、发布隔离和重载验证。
|
||||
@@ -0,0 +1,6 @@
|
||||
id,task,task_type,status,depends_on,task_dir,acceptance_criteria,validation_command,completed_at,retry_count,notes
|
||||
1,逐页建立覆盖清单,single-full,DONE,,tasks/coverage,所有页面内容与字段对应且缺陷可复现,pnpm validate:templates; pnpm --filter @personal-brand/taro test:browser -- admin-editor.spec.ts,2026-10-09,0,已盘点两套模板页面;首批缺口已复现并修复:首页身份区目标、咨询品牌字段过滤、餐饮首页目标 key;契约 19 项和浏览器 2 项通过
|
||||
2,修复通用选区绑定与模板发现,single-full,DONE,1,tasks/contract,混合来源及重复记录映射正确且契约测试通过,pnpm validate:templates; pnpm --filter @personal-brand/admin typecheck; 浏览器测试,2026-10-09,0,区域来源按 binding 推导;餐饮首页身份目标和业务卡片目标对齐;切页及记录失效选择已有清理逻辑
|
||||
3,整理选区面板与保存交互,single-full,DONE,2,tasks/inspector,布局及失败和未保存切换验证通过,pnpm --filter @personal-brand/admin typecheck; 浏览器测试,2026-10-09,0,选区字段改单列自适应并移除固定最小高度;保持保存失败输入不重置
|
||||
4,接通咨询字段编辑,single-full,DONE,2;3,tasks/inquiry,配置保存重载一致且历史提交不受损,pnpm --filter @personal-brand/admin typecheck; 浏览器测试,2026-10-09,0,咨询字段可独立点选并编辑标题、类型、必填、选项;预览草稿不提交真实咨询
|
||||
5,全页面回归与部署验收,single-full,DONE,1;2;3;4,tasks/delivery,覆盖清单及工程门槛和部署验收通过,pnpm validate:templates; pnpm --filter @personal-brand/admin build; pnpm --filter @personal-brand/admin typecheck; pnpm --filter @personal-brand/taro typecheck; 浏览器测试,2026-10-09,0,模板契约 19 项、浏览器 2 项、Admin build、Admin/Taro typecheck 通过;CSV 不交给 Prettier
|
||||
|
@@ -0,0 +1,13 @@
|
||||
template,page,visible_content,renderer_target,manifest_editor,source,status,evidence
|
||||
acheng-campus-food,home,主理人身份、地点、出摊图片、餐品标题、首页操作按钮、承诺、业务卡片,food.home.identity; food.home.location; food.home.hero; food.home.offerings-heading; food.home.actions; food.home.promise-heading; acheng-campus-food.home.offering,对应 sections 已声明并补齐身份与操作目标,brand; offering; trust,已覆盖,契约测试 + 浏览器点选
|
||||
acheng-campus-food,offerings,菜单说明、业务卡片,acheng-campus-food.offerings.menu; acheng-campus-food.offerings.item,对应 sections 已声明,brand; offering,已覆盖,契约测试 + 浏览器点选
|
||||
acheng-campus-food,service,出摊说明、日程、配送、流程,acheng-campus-food.service.service; trust:schedule; trust:coverage; trust:process,对应 sections / trust declarations 已声明,brand; trust,待第二阶段复核,已存在浏览器点选路径
|
||||
acheng-campus-food,profile,主理人与信任内容,acheng-campus-food.profile.identity; trust:credential; trust:case; trust:promise,对应 sections / trust declarations 已声明,brand; trust,待第二阶段复核,已存在 renderer target
|
||||
acheng-campus-food,detail,餐品详情、详情说明,acheng-campus-food.detail.dishDetail; acheng-campus-food.detail.detailCopy,对应 sections 已声明,offering; brand,已覆盖,浏览器已验证底栏与编辑入口
|
||||
acheng-campus-food,inquiry,页面文案、访客表单,acheng-campus-food.inquiry.booking,对应 section 已声明;Admin 已允许 inquiry section 编辑,brand; inquiry,首批已修复,浏览器已验证表单展示
|
||||
acheng-campus-food,success,提交结果文案,acheng-campus-food.success.successCopy,对应 section 已声明,brand,待第二阶段复核,已验证页面可切换
|
||||
acheng-campus-food,records,记录页文案,acheng-campus-food.records.recordsCopy,对应 section 已声明,brand; records,待第二阶段复核,已验证页面可切换
|
||||
linjing-editorial,home,身份、主视觉、证明、主张、案例,editorial.home.identity; editorial.home.hero; editorial.home.proof; editorial.home.manifesto; editorial.home.works; linjing-editorial.home.home,对应 sections 已声明,brand; trust; offering,已覆盖,契约测试 + 浏览器点选
|
||||
linjing-editorial,offerings,案例说明、业务卡片,linjing-editorial.offerings.cases; linjing-editorial.offerings.item,对应 sections 已声明,brand; offering,待第二阶段复核,已有 renderer target
|
||||
linjing-editorial,profile,身份、履约、联系方式、信任内容,linjing-editorial.profile.identity; linjing-editorial.profile.profileDetails; trust:*,对应 sections / trust declarations 已声明,brand; trust,已覆盖,契约测试 + 浏览器点选
|
||||
linjing-editorial,detail,案例详情、详情说明,linjing-editorial.detail.projectDetail; linjing-editorial.detail.detailCopy,对应 sections 已声明,offering; brand,待第二阶段复核,已有 renderer target
|
||||
|
@@ -0,0 +1,25 @@
|
||||
.agents
|
||||
.aws
|
||||
.claude
|
||||
.codex
|
||||
.codex-tasks
|
||||
.git
|
||||
.github
|
||||
.turbo
|
||||
.worktrees
|
||||
coverage
|
||||
dist
|
||||
pnpm-lock.yaml.bak
|
||||
docker-compose.override.yml
|
||||
docker-compose.prod.yml
|
||||
docs
|
||||
media
|
||||
node_modules
|
||||
prototype
|
||||
scripts/deploy/*.test.mjs
|
||||
.env
|
||||
.env.*
|
||||
!.env.production.example
|
||||
**/node_modules
|
||||
**/dist
|
||||
!apps/api/prisma/assets/**
|
||||
@@ -10,9 +10,10 @@ ADMIN_PORT=3000
|
||||
SESSION_SECRET=replace-with-a-long-random-value
|
||||
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
||||
SEED_ADMIN_PASSWORD=change-me-now-123
|
||||
OBJECT_STORAGE_ENDPOINT=
|
||||
OBJECT_STORAGE_BUCKET=
|
||||
OBJECT_STORAGE_ACCESS_KEY=
|
||||
OBJECT_STORAGE_SECRET_KEY=
|
||||
OBJECT_STORAGE_ENDPOINT=http://localhost:9000
|
||||
OBJECT_STORAGE_PUBLIC_URL=http://localhost:9000/personal-brand-media
|
||||
OBJECT_STORAGE_BUCKET=personal-brand-media
|
||||
OBJECT_STORAGE_ACCESS_KEY=minioadmin
|
||||
OBJECT_STORAGE_SECRET_KEY=minioadmin
|
||||
WECHAT_APP_ID=
|
||||
WECHAT_APP_SECRET=
|
||||
@@ -0,0 +1,26 @@
|
||||
NODE_ENV=production
|
||||
POSTGRES_USER=personal_brand
|
||||
POSTGRES_PASSWORD=replace-with-a-long-database-password
|
||||
POSTGRES_DB=personal_brand
|
||||
POSTGRES_PORT=5432
|
||||
|
||||
DATABASE_URL=postgresql://personal_brand:replace-with-a-long-database-password@127.0.0.1:5432/personal_brand?schema=public
|
||||
SESSION_SECRET=replace-with-at-least-32-random-characters
|
||||
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
||||
SEED_ADMIN_PASSWORD=replace-with-a-one-time-initial-password
|
||||
SEED_MODE=seed
|
||||
|
||||
API_PORT=3001
|
||||
API_PREFIX=
|
||||
|
||||
LOCAL_MEDIA_ROOT=/home/ubuntu/persional-brand/media
|
||||
LOCAL_MEDIA_BASE_URL=/media
|
||||
OBJECT_STORAGE_ENDPOINT=
|
||||
OBJECT_STORAGE_PUBLIC_URL=
|
||||
OBJECT_STORAGE_BUCKET=
|
||||
OBJECT_STORAGE_ACCESS_KEY=
|
||||
OBJECT_STORAGE_SECRET_KEY=
|
||||
OBJECT_STORAGE_REGION=us-east-1
|
||||
|
||||
WECHAT_APP_ID=
|
||||
WECHAT_APP_SECRET=
|
||||
@@ -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: 22
|
||||
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: 22
|
||||
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: 22
|
||||
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: 22
|
||||
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
|
||||
@@ -2,11 +2,13 @@ node_modules/
|
||||
.pnpm-store/
|
||||
.turbo/
|
||||
dist/
|
||||
packages/config/dist/
|
||||
.next/
|
||||
coverage/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.env.production
|
||||
!.env.production.example
|
||||
*.log
|
||||
.DS_Store
|
||||
apps/miniapp/miniprogram_npm/
|
||||
@@ -14,8 +16,13 @@ apps/miniapp/project.private.config.json
|
||||
|
||||
.worktrees/
|
||||
apps/taro/src/assets/
|
||||
apps/admin/public/template-preview/
|
||||
|
||||
apps/taro/test-results/
|
||||
apps/taro/playwright-report/
|
||||
media/
|
||||
|
||||
**/.swc/
|
||||
.codex-tasks/
|
||||
docker-compose.override.yml
|
||||
.env.production
|
||||
@@ -1,6 +1,7 @@
|
||||
node_modules
|
||||
.turbo
|
||||
dist
|
||||
apps/admin/public/template-preview
|
||||
.next
|
||||
prototype
|
||||
pnpm-lock.yaml
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# Product Direction
|
||||
|
||||
- 模板新增、绑定修改及宣称完成前,执行 pnpm template:doctor 并遵循 docs/template-completion-rules.md。静态校验、输入框出现、mock 成功不能单独证明完成;回归使用真实 manifest,按区域全部可见变量验收。
|
||||
|
||||
- The core product is a personal-brand platform whose primary goal is to build trust and convert that trust into qualified inquiries or collaborations.
|
||||
- Personal-brand identity, positioning, proof of work, communication expectations, and contact paths are higher priority than any single industry workflow.
|
||||
- Industry behavior is implemented as replaceable templates. Food, consulting, design, photography, and future industries must not hard-code their terminology or fields into the shared brand model or shared UI.
|
||||
|
||||
@@ -2,3 +2,5 @@ VITE_APP_BASE_PATH=/admin/
|
||||
VITE_API_BASE_URL=/api
|
||||
VITE_DEV_API_TARGET=http://localhost:3001
|
||||
ADMIN_PORT=3000
|
||||
VITE_TEMPLATE_PREVIEW_URL=http://localhost:3002
|
||||
VITE_MEDIA_PROXY_TARGET=http://localhost:9000
|
||||
@@ -3,6 +3,7 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^6.3.4",
|
||||
"@personal-brand/api-client": "workspace:*",
|
||||
"@tanstack/react-query": "^5.103.1",
|
||||
"antd": "^6.6.4",
|
||||
|
||||
@@ -1,33 +1,150 @@
|
||||
import { Image, Input, Space, Typography } from "antd";
|
||||
import { CloudUploadOutlined, DeleteOutlined, PictureOutlined } from "@ant-design/icons";
|
||||
import { Alert, Button, Image, Popconfirm, Space, Spin, Upload, message } from "antd";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { createApiClient } from "../lib/api.js";
|
||||
|
||||
interface ImageUrlFieldProps {
|
||||
id?: string;
|
||||
value?: string;
|
||||
onChange?: (value: string) => void;
|
||||
placeholder?: string;
|
||||
scope?: "brand" | "offering" | "trust";
|
||||
}
|
||||
|
||||
export function ImageUrlField({ value, onChange, placeholder }: ImageUrlFieldProps) {
|
||||
export function ImageUrlField({ id, value, onChange, placeholder, scope }: ImageUrlFieldProps) {
|
||||
const imageUrl = typeof value === "string" ? value.trim() : "";
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [storageStatus, setStorageStatus] = useState<
|
||||
"loading" | "ok" | "unavailable" | "unconfigured"
|
||||
>("loading");
|
||||
const client = useMemo(() => createApiClient(), []);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
client
|
||||
.getUploadConfig()
|
||||
.then((config) => {
|
||||
if (active) setStorageStatus(config.configured ? config.status : "unconfigured");
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) setStorageStatus("unavailable");
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [client]);
|
||||
|
||||
async function upload(file: File) {
|
||||
if (!file.type.startsWith("image/")) {
|
||||
message.error("仅支持图片文件");
|
||||
return;
|
||||
}
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
message.error("图片不能超过 10MB");
|
||||
return;
|
||||
}
|
||||
setUploading(true);
|
||||
try {
|
||||
const presign = await client.createPresignedUpload({
|
||||
fileName: file.name,
|
||||
contentType: file.type,
|
||||
...(scope ? { scope } : {}),
|
||||
});
|
||||
const response = await fetch(presign.uploadUrl, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": file.type },
|
||||
body: file,
|
||||
});
|
||||
if (!response.ok) throw new Error(`upload failed: ${response.status}`);
|
||||
onChange?.(presign.publicUrl);
|
||||
} catch {
|
||||
setStorageStatus("unavailable");
|
||||
message.error("图片上传失败,请检查对象存储后重试");
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Space direction="vertical" size={8} style={{ width: "100%" }}>
|
||||
<Input
|
||||
value={value}
|
||||
onChange={(event) => onChange?.(event.target.value)}
|
||||
placeholder={placeholder ?? "粘贴图片地址"}
|
||||
/>
|
||||
<Space direction="vertical" size={4} style={{ width: "100%" }}>
|
||||
{storageStatus !== "ok" ? (
|
||||
<Alert
|
||||
type={storageStatus === "loading" ? "info" : "warning"}
|
||||
showIcon
|
||||
message={
|
||||
storageStatus === "loading"
|
||||
? "正在检查媒体存储..."
|
||||
: storageStatus === "unconfigured"
|
||||
? "媒体存储未配置,请先设置对象存储"
|
||||
: "媒体存储不可用,请检查对象存储配置"
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{imageUrl ? (
|
||||
<Space align="start">
|
||||
<div
|
||||
style={{
|
||||
position: "relative",
|
||||
width: "100%",
|
||||
minHeight: 140,
|
||||
borderRadius: 8,
|
||||
overflow: "hidden",
|
||||
border: "1px solid #d9d9d9",
|
||||
background: "#f5f5f5",
|
||||
}}
|
||||
>
|
||||
<Image
|
||||
src={imageUrl}
|
||||
width={96}
|
||||
height={64}
|
||||
alt={placeholder ?? "图片预览"}
|
||||
width="100%"
|
||||
height={180}
|
||||
preview
|
||||
style={{ objectFit: "cover" }}
|
||||
fallback="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="
|
||||
style={{ objectFit: "cover", borderRadius: 8, background: "#f5f5f5" }}
|
||||
/>
|
||||
<Typography.Text type="secondary">预览图</Typography.Text>
|
||||
</Space>
|
||||
<Popconfirm title="移除这张图片?" onConfirm={() => onChange?.("")}>
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
icon={<DeleteOutlined />}
|
||||
style={{ position: "absolute", top: 8, right: 8 }}
|
||||
>
|
||||
移除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</div>
|
||||
) : (
|
||||
<Upload.Dragger
|
||||
accept="image/*"
|
||||
multiple={false}
|
||||
showUploadList={false}
|
||||
disabled={uploading || storageStatus !== "ok"}
|
||||
beforeUpload={(file) => {
|
||||
if (storageStatus === "ok") void upload(file);
|
||||
return false;
|
||||
}}
|
||||
>
|
||||
<p className="ant-upload-drag-icon">{uploading ? <Spin /> : <PictureOutlined />}</p>
|
||||
<p className="ant-upload-text">{uploading ? "上传中..." : "点击或拖拽上传图片"}</p>
|
||||
<p className="ant-upload-hint">JPG、PNG、WebP 或 AVIF,最大 10MB</p>
|
||||
</Upload.Dragger>
|
||||
)}
|
||||
{storageStatus === "unavailable" ? (
|
||||
<Button
|
||||
icon={<CloudUploadOutlined />}
|
||||
onClick={() => {
|
||||
setStorageStatus("loading");
|
||||
client
|
||||
.getUploadConfig()
|
||||
.then((config) =>
|
||||
setStorageStatus(config.configured ? config.status : "unconfigured"),
|
||||
)
|
||||
.catch(() => setStorageStatus("unavailable"));
|
||||
}}
|
||||
>
|
||||
重新检查存储
|
||||
</Button>
|
||||
) : null}
|
||||
<input {...(id ? { id } : {})} type="hidden" value={imageUrl} />
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { Alert, Button, Col, Form, Row, Space, Typography } from "antd";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import type { TemplateAdminSection } from "@personal-brand/api-client";
|
||||
import { TemplateListField } from "./TemplateListField.js";
|
||||
import { TemplateFieldRenderer } from "./TemplateFieldRenderer.js";
|
||||
import { MutationError } from "./QueryState.js";
|
||||
import { presentationFieldName } from "../features/brand/presentation-bindings.js";
|
||||
import { useRecordContentEditorState } from "./record-content/useRecordContentEditorState.js";
|
||||
import type { RecordContentEditorProps, RecordContentSource } from "./record-content/types.js";
|
||||
|
||||
export type { RecordContentEditorProps, RecordContentSource };
|
||||
|
||||
export function RecordContentFields({
|
||||
section,
|
||||
sectionKey = section.key,
|
||||
}: {
|
||||
section: TemplateAdminSection;
|
||||
sectionKey?: string;
|
||||
}) {
|
||||
return (
|
||||
<Row gutter={16}>
|
||||
{section.fields.map((field) => (
|
||||
<Col key={field.key} xs={24} md={24}>
|
||||
{field.input === "list" ? (
|
||||
<TemplateListField field={field} name={presentationFieldName(sectionKey, field.key)} />
|
||||
) : (
|
||||
<Form.Item
|
||||
name={presentationFieldName(sectionKey, field.key)}
|
||||
label={field.label}
|
||||
htmlFor={presentationFieldName(sectionKey, field.key)}
|
||||
{...(field.help ? { help: field.help } : {})}
|
||||
{...(field.required
|
||||
? { rules: [{ required: true, message: `请填写${field.label}` }] }
|
||||
: {})}
|
||||
>
|
||||
<TemplateFieldRenderer
|
||||
field={field}
|
||||
id={presentationFieldName(sectionKey, field.key)}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
</Col>
|
||||
))}
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
|
||||
export function RecordContentEditor({
|
||||
source,
|
||||
record,
|
||||
section,
|
||||
context,
|
||||
onDraft,
|
||||
onSaved,
|
||||
visualSelection,
|
||||
}: RecordContentEditorProps) {
|
||||
const navigate = useNavigate();
|
||||
const recordName = "name" in record ? record.name : record.title;
|
||||
const { form, handleValuesChange, initialValues, save, submit } = useRecordContentEditorState({
|
||||
source,
|
||||
record,
|
||||
section,
|
||||
...(onDraft ? { onDraft } : {}),
|
||||
...(onSaved ? { onSaved } : {}),
|
||||
});
|
||||
|
||||
return (
|
||||
<Form
|
||||
form={form}
|
||||
layout="vertical"
|
||||
initialValues={initialValues}
|
||||
onValuesChange={handleValuesChange}
|
||||
onFinish={submit}
|
||||
style={{ minHeight: 0, display: "flex", flexDirection: "column" }}
|
||||
>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
message={
|
||||
source === "offering"
|
||||
? `正在编辑业务提供项:${recordName}`
|
||||
: `正在编辑信任内容:${recordName}`
|
||||
}
|
||||
description={
|
||||
context === "visual"
|
||||
? "这里修改的是业务或信任记录本身;业务提供项列表中打开同一项目,看到并修改的是同一份数据。"
|
||||
: "这里修改的内容也会显示在小程序页面对应的卡片、列表或详情中;两处入口修改的是同一份数据。"
|
||||
}
|
||||
/>
|
||||
{save.isPending ? <Typography.Text type="secondary">正在保存内容…</Typography.Text> : null}
|
||||
<Typography.Paragraph type="secondary">{section.description}</Typography.Paragraph>
|
||||
<div style={{ flex: 1 }}>
|
||||
<RecordContentFields section={section} />
|
||||
</div>
|
||||
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
|
||||
<MutationError error={save.error} />
|
||||
<Space wrap>
|
||||
<Button type="primary" htmlType="submit" loading={save.isPending}>
|
||||
保存此项内容
|
||||
</Button>
|
||||
{source === "offering" ? (
|
||||
<Button
|
||||
htmlType="button"
|
||||
onClick={() =>
|
||||
navigate("/admin/brand", {
|
||||
state: {
|
||||
targetKey: visualSelection?.targetKey ?? "offering.list.item",
|
||||
recordId: record.id,
|
||||
},
|
||||
})
|
||||
}
|
||||
>
|
||||
在小程序页面编辑
|
||||
</Button>
|
||||
) : null}
|
||||
</Space>
|
||||
</Space>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { Input, InputNumber, Select, Switch } from "antd";
|
||||
import type { TemplateAdminField } from "@personal-brand/api-client";
|
||||
import { ImageUrlField } from "./ImageUrlField.js";
|
||||
|
||||
export function TemplateFieldRenderer({
|
||||
field,
|
||||
id,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
field: TemplateAdminField;
|
||||
id?: string;
|
||||
value?: unknown;
|
||||
onChange?: (value: unknown) => void;
|
||||
}) {
|
||||
if (field.input === "textarea")
|
||||
return (
|
||||
<Input.TextArea
|
||||
{...(id ? { id } : {})}
|
||||
value={typeof value === "string" ? value : ""}
|
||||
onChange={(event) => onChange?.(event.target.value)}
|
||||
rows={3}
|
||||
maxLength={field.maxLength}
|
||||
showCount={!!field.maxLength}
|
||||
placeholder={field.placeholder}
|
||||
/>
|
||||
);
|
||||
if (field.input === "image")
|
||||
return (
|
||||
<ImageUrlField
|
||||
{...(id ? { id } : {})}
|
||||
{...(field.placeholder ? { placeholder: field.placeholder } : {})}
|
||||
{...(typeof value === "string" ? { value } : {})}
|
||||
{...(onChange ? { onChange: (next: string) => onChange(next) } : {})}
|
||||
/>
|
||||
);
|
||||
if (field.input === "phone")
|
||||
return (
|
||||
<Input
|
||||
{...(id ? { id } : {})}
|
||||
type="tel"
|
||||
placeholder={field.placeholder}
|
||||
value={typeof value === "string" ? value : ""}
|
||||
onChange={(event) => onChange?.(event.target.value)}
|
||||
/>
|
||||
);
|
||||
if (field.input === "number")
|
||||
return (
|
||||
<InputNumber
|
||||
{...(id ? { id } : {})}
|
||||
value={typeof value === "number" ? value : null}
|
||||
onChange={(input) => onChange?.(input ?? undefined)}
|
||||
min={0}
|
||||
style={{ width: "100%" }}
|
||||
placeholder={field.placeholder}
|
||||
/>
|
||||
);
|
||||
if (field.input === "boolean")
|
||||
return (
|
||||
<Switch
|
||||
{...(id ? { id } : {})}
|
||||
checked={Boolean(value)}
|
||||
onChange={(checked) => onChange?.(checked)}
|
||||
/>
|
||||
);
|
||||
if (field.input === "select")
|
||||
return (
|
||||
<Select
|
||||
{...(id ? { id } : {})}
|
||||
options={(field.options ?? []).map((item) => ({ ...item }))}
|
||||
value={typeof value === "string" || typeof value === "number" ? value : undefined}
|
||||
onChange={(selected) => onChange?.(selected)}
|
||||
{...(field.placeholder ? { placeholder: field.placeholder } : {})}
|
||||
/>
|
||||
);
|
||||
if (field.input === "multi-select")
|
||||
return (
|
||||
<Select
|
||||
{...(id ? { id } : {})}
|
||||
mode="multiple"
|
||||
options={(field.options ?? []).map((item) => ({ ...item }))}
|
||||
value={Array.isArray(value) ? value.map(String) : []}
|
||||
onChange={(selected) => onChange?.(selected)}
|
||||
placeholder={field.placeholder}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<Input
|
||||
{...(id ? { id } : {})}
|
||||
value={typeof value === "string" ? value : ""}
|
||||
onChange={(event) => onChange?.(event.target.value)}
|
||||
maxLength={field.maxLength}
|
||||
placeholder={field.placeholder}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,10 @@
|
||||
import { Button, Form, Input, Space } from "antd";
|
||||
import { Button, Card, Collapse, Empty, Form, Input, Space, Typography } from "antd";
|
||||
import {
|
||||
CaretDownOutlined,
|
||||
CaretUpOutlined,
|
||||
DeleteOutlined,
|
||||
PlusOutlined,
|
||||
} from "@ant-design/icons";
|
||||
import type { TemplateAdminField } from "@personal-brand/api-client";
|
||||
|
||||
export function TemplateListField({
|
||||
@@ -21,29 +27,114 @@ export function TemplateListField({
|
||||
},
|
||||
]}
|
||||
>
|
||||
{(rows, { add, remove }, { errors }) => (
|
||||
<Space direction="vertical" style={{ width: "100%" }}>
|
||||
{rows.map((row, index) => (
|
||||
<Space key={row.key} align="start" wrap>
|
||||
{field.itemFields?.map((itemField) => (
|
||||
<Form.Item
|
||||
key={itemField.key}
|
||||
name={[row.name, itemField.key]}
|
||||
label={`${index + 1}. ${itemField.label}`}
|
||||
rules={
|
||||
itemField.required === false
|
||||
? []
|
||||
: [{ required: true, message: `请填写${itemField.label}` }]
|
||||
}
|
||||
>
|
||||
{itemField.input === "textarea" ? <Input.TextArea rows={2} /> : <Input />}
|
||||
</Form.Item>
|
||||
))}
|
||||
<Button onClick={() => remove(row.name)}>删除</Button>
|
||||
</Space>
|
||||
))}
|
||||
{(rows, { add, remove, move }, { errors }) => (
|
||||
<Space direction="vertical" size={12} style={{ width: "100%" }}>
|
||||
{rows.length === 0 ? (
|
||||
<Empty
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
description={`还没有${field.label}内容`}
|
||||
/>
|
||||
) : null}
|
||||
{rows.map((row, index) => {
|
||||
const titleField = field.itemFields?.[0];
|
||||
const primaryTitle = titleField ? (
|
||||
<Form.Item
|
||||
noStyle
|
||||
shouldUpdate={(prev: unknown, next: unknown) => {
|
||||
const previous = Array.isArray(prev)
|
||||
? (prev[row.name] as Record<string, unknown> | undefined)
|
||||
: undefined;
|
||||
const nextRow = Array.isArray(next)
|
||||
? (next[row.name] as Record<string, unknown> | undefined)
|
||||
: undefined;
|
||||
return previous?.[titleField.key] !== nextRow?.[titleField.key];
|
||||
}}
|
||||
>
|
||||
{({ getFieldValue }) => {
|
||||
const value = String(
|
||||
getFieldValue([...name, row.name, titleField.key] as const) ?? "",
|
||||
);
|
||||
return (
|
||||
<Typography.Text
|
||||
strong
|
||||
>{`${index + 1}. ${value || titleField.label}`}</Typography.Text>
|
||||
);
|
||||
}}
|
||||
</Form.Item>
|
||||
) : (
|
||||
<Typography.Text strong>{`${index + 1}. ${field.label}`}</Typography.Text>
|
||||
);
|
||||
return (
|
||||
<Card
|
||||
key={row.key}
|
||||
size="small"
|
||||
title={primaryTitle}
|
||||
extra={
|
||||
<Space size={0}>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
aria-label={`上移第 ${index + 1} 项`}
|
||||
icon={<CaretUpOutlined />}
|
||||
disabled={index === 0}
|
||||
onClick={() => move(index, index - 1)}
|
||||
/>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
aria-label={`下移第 ${index + 1} 项`}
|
||||
icon={<CaretDownOutlined />}
|
||||
disabled={index === rows.length - 1}
|
||||
onClick={() => move(index, index + 1)}
|
||||
/>
|
||||
<Button
|
||||
type="text"
|
||||
danger
|
||||
size="small"
|
||||
aria-label={`删除第 ${index + 1} 项`}
|
||||
icon={<DeleteOutlined />}
|
||||
onClick={() => remove(row.name)}
|
||||
/>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
{field.itemFields?.map((itemField) => (
|
||||
<Form.Item
|
||||
key={itemField.key}
|
||||
name={[row.name, itemField.key]}
|
||||
label={itemField.label}
|
||||
rules={
|
||||
itemField.required === false
|
||||
? []
|
||||
: [{ required: true, message: `请填写${itemField.label}` }]
|
||||
}
|
||||
>
|
||||
{itemField.input === "textarea" ? <Input.TextArea rows={2} /> : <Input />}
|
||||
</Form.Item>
|
||||
))}
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
{rows.length > 1 ? (
|
||||
<Collapse
|
||||
ghost
|
||||
items={[
|
||||
{
|
||||
key: "sort-help",
|
||||
label: "排序说明",
|
||||
children: (
|
||||
<Typography.Text type="secondary">
|
||||
使用每张卡片右上角的箭头调整顺序,保存后预览也会按当前顺序展示。
|
||||
</Typography.Text>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
) : null}
|
||||
<Form.ErrorList errors={errors} />
|
||||
<Button onClick={() => add()}>新增{field.label}</Button>
|
||||
<Button block icon={<PlusOutlined />} onClick={() => add()}>
|
||||
新增{field.label}
|
||||
</Button>
|
||||
</Space>
|
||||
)}
|
||||
</Form.List>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { Offering, TemplateAdminSection, TrustContent } from "@personal-brand/api-client";
|
||||
import type { PresentationValues } from "../../features/brand/presentation-bindings.js";
|
||||
|
||||
export type RecordContentSource = "offering" | "trust";
|
||||
|
||||
export interface RecordContentEditorProps {
|
||||
source: RecordContentSource;
|
||||
record: Offering | TrustContent;
|
||||
section: TemplateAdminSection;
|
||||
context: "visual" | "services";
|
||||
onDraft?: (values: PresentationValues) => void;
|
||||
onSaved?: () => void;
|
||||
visualSelection?: { targetKey: string; page: string };
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { Form, message } from "antd";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import type { TemplateAdminSection } from "@personal-brand/api-client";
|
||||
import type { Offering, TrustContent } from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import {
|
||||
applyPresentationValues,
|
||||
applyStandardEntityValues,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
type PresentationValues,
|
||||
} from "../../features/brand/presentation-bindings.js";
|
||||
import type { RecordContentSource } from "./types.js";
|
||||
|
||||
function createInitialValues(
|
||||
record: Offering | TrustContent,
|
||||
section: TemplateAdminSection,
|
||||
): PresentationValues {
|
||||
return Object.fromEntries(
|
||||
section.fields.map((field) => [
|
||||
presentationFieldName(section.key, field.key),
|
||||
readPresentationValue(
|
||||
record.config,
|
||||
field.binding,
|
||||
field,
|
||||
record as unknown as Record<string, unknown>,
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
function createChangedStandardValues(
|
||||
record: Offering | TrustContent,
|
||||
source: RecordContentSource,
|
||||
section: TemplateAdminSection,
|
||||
values: PresentationValues,
|
||||
) {
|
||||
const entity = record as unknown as Record<string, unknown>;
|
||||
const standard = applyStandardEntityValues(entity, source, [section], values);
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(standard).filter(
|
||||
([key, value]) => key !== "config" && (key in entity || value !== entity[key]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function useRecordContentEditorState({
|
||||
source,
|
||||
record,
|
||||
section,
|
||||
onDraft,
|
||||
onSaved,
|
||||
}: {
|
||||
source: RecordContentSource;
|
||||
record: Offering | TrustContent;
|
||||
section: TemplateAdminSection;
|
||||
onDraft?: ((values: PresentationValues) => void) | undefined;
|
||||
onSaved?: (() => void) | undefined;
|
||||
}) {
|
||||
const [form] = Form.useForm<PresentationValues>();
|
||||
const queryClient = useQueryClient();
|
||||
const [draftValues, setDraftValues] = useState<PresentationValues>(() =>
|
||||
createInitialValues(record, section),
|
||||
);
|
||||
const initialValues = useMemo(() => createInitialValues(record, section), [record, section]);
|
||||
|
||||
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: async (values: PresentationValues): Promise<void> => {
|
||||
const config = applyPresentationValues(record.config, [section], values);
|
||||
const changed = createChangedStandardValues(record, source, section, values);
|
||||
const client = createApiClient();
|
||||
|
||||
if (source === "offering") {
|
||||
await client.updateAdminOffering(record.id, { ...changed, config });
|
||||
} else {
|
||||
await client.updateAdminTrustContent(record.id, { ...changed, config });
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
message.success("已保存内容草稿,发布后访客才会看到更新");
|
||||
onSaved?.();
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: [source === "offering" ? "admin-offerings" : "trust-content"],
|
||||
});
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
|
||||
if (source === "offering") {
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace-offering-fields"] });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const submit = (values: PresentationValues) => {
|
||||
const currentValues = form.getFieldsValue(true) as PresentationValues;
|
||||
save.mutate({ ...draftValues, ...values, ...currentValues });
|
||||
};
|
||||
|
||||
const handleValuesChange = (_values: PresentationValues) => {
|
||||
const currentValues = form.getFieldsValue(true) as PresentationValues;
|
||||
const next = { ...draftValues, ..._values, ...currentValues };
|
||||
setDraftValues(next);
|
||||
onDraft?.(next);
|
||||
};
|
||||
|
||||
return {
|
||||
draftValues,
|
||||
form,
|
||||
handleValuesChange,
|
||||
initialValues,
|
||||
save,
|
||||
submit,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
.brand-page__content {
|
||||
max-width: 960px;
|
||||
}
|
||||
|
||||
.brand-page__content[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.brand-page__toolbar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
padding: 16px 0;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
@media (max-width: 575px) {
|
||||
.brand-page__toolbar {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
|
||||
.brand-page__settings {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.brand-settings-section {
|
||||
padding: 24px 0;
|
||||
border-top: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.brand-settings-section:first-child {
|
||||
padding-top: 8px;
|
||||
border-top: 0;
|
||||
}
|
||||
|
||||
.brand-settings-section__header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.brand-settings-section__header .ant-typography {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.brand-settings-section__header .ant-typography + .ant-typography {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.brand-page__template-note {
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
@media (max-width: 1199px) {
|
||||
.brand-page__content {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.brand-page__template-note {
|
||||
position: static;
|
||||
margin-top: 24px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 575px) {
|
||||
.brand-settings-section__header {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.brand-settings-section__header .ant-tag {
|
||||
display: inline-block;
|
||||
margin-top: 10px;
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,36 @@
|
||||
import { Button, Card, Col, Form, Input, Row, Select, Space, Tag, Typography, message } from "antd";
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Col,
|
||||
Form,
|
||||
Input,
|
||||
Row,
|
||||
Select,
|
||||
Segmented,
|
||||
Space,
|
||||
Tag,
|
||||
Typography,
|
||||
message,
|
||||
} from "antd";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
import { Link, useLocation } from "react-router-dom";
|
||||
import type { BrandProfile } from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
||||
import { MutationError, QueryState } from "../../components/QueryState.js";
|
||||
import { PresentationEditor } from "./PresentationEditor.js";
|
||||
import type { PreviewSelection } from "./preview-selection.js";
|
||||
import "./BrandPage.css";
|
||||
import { useEditorDraft } from "./use-editor-draft.js";
|
||||
|
||||
export function BrandPage() {
|
||||
const location = useLocation();
|
||||
const initialSelection = location.state as PreviewSelection | undefined;
|
||||
const [panel, setPanel] = useState("pages");
|
||||
const [dirty, setDirty] = useState(false);
|
||||
useEditorDraft(dirty);
|
||||
const client = createApiClient();
|
||||
const queryClient = useQueryClient();
|
||||
const [form] = Form.useForm<BrandProfile>();
|
||||
@@ -16,16 +39,26 @@ export function BrandPage() {
|
||||
queryKey: ["admin-workspace"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
});
|
||||
const previewWorkspace = useQuery({
|
||||
queryKey: ["admin-preview-workspace"],
|
||||
queryFn: () => client.getAdminPreviewWorkspace(),
|
||||
});
|
||||
const template = useQuery({
|
||||
queryKey: ["template", brand.data?.templateKey],
|
||||
queryFn: () => client.getPublicTemplate(brand.data!.templateKey),
|
||||
enabled: Boolean(brand.data?.templateKey),
|
||||
});
|
||||
const templateCatalog = useQuery({
|
||||
queryKey: ["template-catalog"],
|
||||
queryFn: () => client.listPublicTemplates(),
|
||||
});
|
||||
const save = useMutation({
|
||||
mutationFn: (values: Partial<BrandProfile>) => client.updateAdminBrand(values),
|
||||
onSuccess: () => {
|
||||
setDirty(false);
|
||||
message.success("品牌表达已保存");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
|
||||
},
|
||||
});
|
||||
return (
|
||||
@@ -33,29 +66,57 @@ export function BrandPage() {
|
||||
{!brand.data ? null : (
|
||||
<>
|
||||
<AdminPageHeader
|
||||
title="品牌资料"
|
||||
description="先让访客理解你是谁、服务谁,以及为什么值得信任。"
|
||||
title="小程序工作台"
|
||||
description={
|
||||
template.data?.description
|
||||
? `先让访客理解你是谁、服务谁,以及为什么值得信任。${template.data.description}`
|
||||
: "先让访客理解你是谁、服务谁,以及为什么值得信任。"
|
||||
}
|
||||
extra={<Tag color="blue">{template.data?.name ?? "当前模板"}</Tag>}
|
||||
/>
|
||||
<Row gutter={[24, 24]} align="top">
|
||||
<Col xs={24} xl={15}>
|
||||
<div className="brand-page__toolbar">
|
||||
<Segmented
|
||||
aria-label="工作台视图"
|
||||
value={panel}
|
||||
onChange={(value) => setPanel(String(value))}
|
||||
options={[
|
||||
{ value: "pages", label: "页面编辑" },
|
||||
{ value: "brand", label: "品牌资料" },
|
||||
]}
|
||||
/>
|
||||
<Space>
|
||||
<Tag color={dirty ? "orange" : "default"}>
|
||||
{dirty ? "品牌资料有未保存修改" : "草稿工作区"}
|
||||
</Tag>
|
||||
<Link to="/admin/publication">检查与发布 →</Link>
|
||||
</Space>
|
||||
</div>
|
||||
<div className="brand-page__content" hidden={panel !== "brand"}>
|
||||
<div className="brand-page__settings">
|
||||
<Form
|
||||
form={form}
|
||||
layout="vertical"
|
||||
initialValues={brand.data}
|
||||
onValuesChange={() => setDirty(true)}
|
||||
onFinish={(values) => save.mutate(values)}
|
||||
>
|
||||
<Card
|
||||
title="我是谁"
|
||||
extra={<Typography.Text type="secondary">公开展示</Typography.Text>}
|
||||
>
|
||||
<section className="brand-settings-section" aria-labelledby="brand-identity-title">
|
||||
<div className="brand-settings-section__header">
|
||||
<div>
|
||||
<Typography.Title id="brand-identity-title" level={4}>
|
||||
我是谁
|
||||
</Typography.Title>
|
||||
<Typography.Text type="secondary">公开展示的品牌身份和定位。</Typography.Text>
|
||||
</div>
|
||||
<Tag>品牌基础信息</Tag>
|
||||
</div>
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="品牌名称"
|
||||
help="可以是个人姓名、工作室名称或品牌名。"
|
||||
rules={[{ required: true, message: "请输入品牌名称" }]}
|
||||
>
|
||||
<Input size="large" placeholder="例如:林然|品牌顾问" />
|
||||
<Input size="large" placeholder="例如:品牌主理人|品牌顾问" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="tagline"
|
||||
@@ -73,8 +134,18 @@ export function BrandPage() {
|
||||
placeholder="让第一次认识你的人快速建立基本信任。"
|
||||
/>
|
||||
</Form.Item>
|
||||
</Card>
|
||||
<Card title="如何联系与合作" style={{ marginTop: 24 }}>
|
||||
</section>
|
||||
<section className="brand-settings-section" aria-labelledby="brand-contact-title">
|
||||
<div className="brand-settings-section__header">
|
||||
<div>
|
||||
<Typography.Title id="brand-contact-title" level={4}>
|
||||
如何联系与合作
|
||||
</Typography.Title>
|
||||
<Typography.Text type="secondary">
|
||||
让访客知道联系渠道、服务范围和响应预期。
|
||||
</Typography.Text>
|
||||
</div>
|
||||
</div>
|
||||
<Row gutter={16}>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name="hours" label="可联系时间">
|
||||
@@ -104,8 +175,18 @@ export function BrandPage() {
|
||||
>
|
||||
<Input.TextArea rows={3} placeholder="例如:收到咨询后 1 个工作日内回复。" />
|
||||
</Form.Item>
|
||||
</Card>
|
||||
<Card title="模板与品牌视觉" style={{ marginTop: 24 }}>
|
||||
</section>
|
||||
<section className="brand-settings-section" aria-labelledby="brand-visual-title">
|
||||
<div className="brand-settings-section__header">
|
||||
<div>
|
||||
<Typography.Title id="brand-visual-title" level={4}>
|
||||
模板与品牌视觉
|
||||
</Typography.Title>
|
||||
<Typography.Text type="secondary">
|
||||
模板负责业务表达,品牌信息仍由你统一维护。
|
||||
</Typography.Text>
|
||||
</div>
|
||||
</div>
|
||||
<Form.Item
|
||||
name="templateKey"
|
||||
label="业务表达模板"
|
||||
@@ -113,10 +194,10 @@ export function BrandPage() {
|
||||
>
|
||||
<Select
|
||||
disabled
|
||||
options={[
|
||||
{ value: "personal", label: "个人品牌" },
|
||||
{ value: "food", label: "餐饮模板" },
|
||||
]}
|
||||
options={(templateCatalog.data?.industries ?? []).map((item) => ({
|
||||
value: item.key,
|
||||
label: item.name,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Row gutter={16}>
|
||||
@@ -124,18 +205,22 @@ export function BrandPage() {
|
||||
<Form.Item
|
||||
name="avatarUrl"
|
||||
label="头像图片地址"
|
||||
help="粘贴一张可公开访问的图片地址。"
|
||||
help="点击上传或粘贴一张可公开访问的图片地址。"
|
||||
>
|
||||
<ImageUrlField />
|
||||
<ImageUrlField scope="brand" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name="coverUrl" label="品牌封面图片地址" help="建议使用横向图片。">
|
||||
<ImageUrlField />
|
||||
<Form.Item
|
||||
name="coverUrl"
|
||||
label="品牌封面图片地址"
|
||||
help="点击上传,或粘贴一张横向图片地址。"
|
||||
>
|
||||
<ImageUrlField scope="brand" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
</section>
|
||||
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
|
||||
<MutationError error={save.error} />
|
||||
<Button type="primary" htmlType="submit" loading={save.isPending} size="large">
|
||||
@@ -143,43 +228,28 @@ export function BrandPage() {
|
||||
</Button>
|
||||
</Space>
|
||||
</Form>
|
||||
<PresentationEditor
|
||||
templateContent={workspace.data?.templateContent}
|
||||
config={brand.data.config}
|
||||
loading={workspace.isLoading}
|
||||
error={workspace.error}
|
||||
</div>
|
||||
{template.data ? (
|
||||
<Alert
|
||||
className="brand-page__template-note"
|
||||
type="info"
|
||||
showIcon
|
||||
message={`当前使用:${template.data.name}`}
|
||||
description={`适用场景:${template.data.serviceCategories.join("、") || "通用品牌展示"}`}
|
||||
/>
|
||||
</Col>
|
||||
<Col xs={24} xl={9}>
|
||||
<Card title="公开表达预览" style={{ position: "sticky", top: 24 }}>
|
||||
<Typography.Text type="secondary">
|
||||
这些资料会用于小程序首页和联系区域
|
||||
</Typography.Text>
|
||||
<Typography.Title level={3}>{brand.data.name || "品牌名称"}</Typography.Title>
|
||||
<Typography.Title level={5}>{brand.data.tagline || "一句话定位"}</Typography.Title>
|
||||
<Typography.Paragraph>
|
||||
{brand.data.description || "品牌简介将在这里展示。"}
|
||||
</Typography.Paragraph>
|
||||
<Typography.Text strong>合作方式</Typography.Text>
|
||||
<Typography.Paragraph type="secondary">
|
||||
{brand.data.deliveryNote || "补充你的响应时间和合作预期。"}
|
||||
</Typography.Paragraph>
|
||||
<Space wrap>
|
||||
{brand.data.contactPhone && <Tag>电话:{brand.data.contactPhone}</Tag>}
|
||||
{brand.data.contactWechat && <Tag>微信:{brand.data.contactWechat}</Tag>}
|
||||
{brand.data.hours && <Tag>时间:{brand.data.hours}</Tag>}
|
||||
</Space>
|
||||
</Card>
|
||||
{template.data && (
|
||||
<Card title="模板说明" style={{ marginTop: 24 }}>
|
||||
<Typography.Paragraph>{template.data.description}</Typography.Paragraph>
|
||||
<Typography.Text type="secondary">
|
||||
服务分类:{template.data.serviceCategories.join("、")}
|
||||
</Typography.Text>
|
||||
</Card>
|
||||
)}
|
||||
</Col>
|
||||
</Row>
|
||||
) : null}
|
||||
</div>
|
||||
<div hidden={panel !== "pages"}>
|
||||
<PresentationEditor
|
||||
templateContent={workspace.data?.templateContent}
|
||||
previewWorkspace={previewWorkspace.data}
|
||||
config={brand.data.config}
|
||||
brand={brand.data}
|
||||
loading={workspace.isLoading}
|
||||
error={workspace.error}
|
||||
{...(initialSelection ? { initialSelection } : {})}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</QueryState>
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
.component-template-preview-shell {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.component-template-preview__tools {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
border-bottom: 1px solid #e8e8e8;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.component-template-preview__tools button {
|
||||
padding: 4px 12px;
|
||||
border: 1px solid #d9d9d9;
|
||||
border-radius: 6px;
|
||||
background: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.component-template-preview__tools button[aria-pressed="true"] {
|
||||
border-color: #1677ff;
|
||||
color: #1677ff;
|
||||
}
|
||||
|
||||
.component-template-preview {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: calc(100% - 49px);
|
||||
min-height: 510px;
|
||||
padding: 24px 16px;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
background: #f3f4f6;
|
||||
}
|
||||
|
||||
.component-template-preview__canvas {
|
||||
position: relative;
|
||||
container-type: inline-size;
|
||||
width: min(100%, 390px);
|
||||
min-height: calc(100% - 48px);
|
||||
margin: 0 auto;
|
||||
overflow: visible;
|
||||
border-radius: 14px;
|
||||
background: #fff;
|
||||
box-shadow:
|
||||
0 0 0 1px rgba(0, 0, 0, 0.04),
|
||||
0 10px 30px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
:where(.component-template-preview__canvas) {
|
||||
--taro-button-height: 11.7333333cqw;
|
||||
--taro-button-compact-height: 6.1333333cqw;
|
||||
}
|
||||
|
||||
.component-template-preview__canvas,
|
||||
.component-template-preview__canvas * {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.component-template-preview__canvas > * {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
:where(.component-template-preview__canvas) button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
min-height: var(--taro-button-height);
|
||||
appearance: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
line-height: 1.5;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
:where(.component-template-preview__canvas) input {
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.component-template-preview__canvas img {
|
||||
flex-shrink: 0;
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.component-template-preview[data-editor-mode="edit"] [data-editor-target] {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.component-template-preview__outline {
|
||||
position: absolute;
|
||||
z-index: 5;
|
||||
pointer-events: none;
|
||||
border: 2px solid #91caff;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.component-template-preview__outline.is-selected {
|
||||
z-index: 6;
|
||||
border-color: #1677ff;
|
||||
box-shadow: 0 0 0 3px rgba(22, 119, 255, 0.16);
|
||||
}
|
||||
|
||||
.component-template-preview__composite-select {
|
||||
position: absolute;
|
||||
z-index: 7;
|
||||
width: max-content !important;
|
||||
padding: 2px 8px !important;
|
||||
border: 1px solid #1677ff !important;
|
||||
border-radius: 4px !important;
|
||||
background: #fff !important;
|
||||
color: #0958d9 !important;
|
||||
font-size: 12px !important;
|
||||
line-height: 20px !important;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.component-template-preview__outline span {
|
||||
position: absolute;
|
||||
bottom: 100%;
|
||||
left: 0;
|
||||
max-width: 100%;
|
||||
padding: 2px 7px;
|
||||
overflow: hidden;
|
||||
border-radius: 4px 4px 0 0;
|
||||
background: #1677ff;
|
||||
color: #fff;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.component-template-preview__tools[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.component-template-preview-shell:has(.component-template-preview__tools[hidden])
|
||||
.component-template-preview {
|
||||
height: 100%;
|
||||
}
|
||||
.component-template-preview__overlay-host {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 5;
|
||||
pointer-events: none;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.component-template-preview__overlay-host.is-visible {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.component-template-preview__overlay-host > * {
|
||||
pointer-events: auto;
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import type { RuntimeWorkspace } from "@personal-brand/api-client";
|
||||
import { Alert } from "antd";
|
||||
import { resolveTemplateRenderer } from "./component-renderers.jsx";
|
||||
import type { PreviewSelection, PreviewTarget } from "./preview-selection.js";
|
||||
import "./ComponentTemplatePreview.css";
|
||||
|
||||
type PreviewProps = {
|
||||
workspace: RuntimeWorkspace;
|
||||
page: string;
|
||||
offeringId?: string;
|
||||
selection?: PreviewSelection;
|
||||
targets: PreviewTarget[];
|
||||
onTargetSelected: (selection?: PreviewSelection) => void;
|
||||
};
|
||||
|
||||
type Outline = { top: number; left: number; width: number; height: number; label: string };
|
||||
type CompositeOutline = Outline & { key: string };
|
||||
|
||||
export function ComponentTemplatePreview({
|
||||
workspace,
|
||||
page,
|
||||
offeringId,
|
||||
selection,
|
||||
targets,
|
||||
onTargetSelected,
|
||||
}: PreviewProps) {
|
||||
const Renderer = resolveTemplateRenderer(workspace);
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const canvas = useRef<HTMLDivElement>(null);
|
||||
const [mode, setMode] = useState<"edit" | "browse">("edit");
|
||||
const [hovered, setHovered] = useState<HTMLElement | null>(null);
|
||||
const overlay = useRef<HTMLDivElement>(null);
|
||||
const targetFor = useCallback(
|
||||
(element: Element | null): HTMLElement | null => {
|
||||
let candidate = element?.closest<HTMLElement>("[data-editor-target]");
|
||||
let deepest: HTMLElement | null = null;
|
||||
let composite: HTMLElement | null = null;
|
||||
while (candidate && root.current?.contains(candidate)) {
|
||||
const target = targets.find((item) => item.key === candidate?.dataset.editorTarget);
|
||||
if (target && !deepest) deepest = candidate;
|
||||
if (target?.composite) composite = candidate;
|
||||
candidate = candidate.parentElement?.closest<HTMLElement>("[data-editor-target]") ?? null;
|
||||
}
|
||||
return deepest ?? composite;
|
||||
},
|
||||
[targets],
|
||||
);
|
||||
const selectedElement = useCallback(() => {
|
||||
if (!selection) return null;
|
||||
return (
|
||||
Array.from(root.current?.querySelectorAll<HTMLElement>("[data-editor-target]") ?? []).find(
|
||||
(element) =>
|
||||
element.dataset.editorTarget === selection.targetKey &&
|
||||
(element.dataset.editorRecordId || undefined) === selection.recordId,
|
||||
) ?? null
|
||||
);
|
||||
}, [selection]);
|
||||
const renderOutlines = useCallback(
|
||||
(
|
||||
host: HTMLDivElement,
|
||||
outlines: {
|
||||
hover: Outline | null;
|
||||
selected: Outline | null;
|
||||
composite: CompositeOutline[];
|
||||
},
|
||||
) => {
|
||||
host.replaceChildren();
|
||||
const position = (node: HTMLElement, outline: Outline) => {
|
||||
node.style.top = `${outline.top}px`;
|
||||
node.style.left = `${outline.left}px`;
|
||||
node.style.width = `${outline.width}px`;
|
||||
node.style.height = `${outline.height}px`;
|
||||
};
|
||||
if (outlines.hover) {
|
||||
const node = document.createElement("div");
|
||||
node.className = "component-template-preview__outline is-hovered";
|
||||
position(node, outlines.hover);
|
||||
host.append(node);
|
||||
}
|
||||
if (outlines.selected) {
|
||||
const node = document.createElement("div");
|
||||
node.className = "component-template-preview__outline is-selected";
|
||||
node.dataset.selectedTarget = selection?.targetKey ?? "";
|
||||
node.dataset.selectedRecordId = selection?.recordId ?? "";
|
||||
const label = document.createElement("span");
|
||||
label.textContent = outlines.selected.label;
|
||||
node.append(label);
|
||||
position(node, outlines.selected);
|
||||
host.append(node);
|
||||
}
|
||||
for (const outline of outlines.composite) {
|
||||
const node = document.createElement("button");
|
||||
node.type = "button";
|
||||
node.className = "component-template-preview__composite-select";
|
||||
node.textContent = `选择${outline.label}`;
|
||||
node.setAttribute("aria-label", node.textContent);
|
||||
node.onclick = () => onTargetSelected({ targetKey: outline.key });
|
||||
node.style.top = `${outline.top + 4}px`;
|
||||
node.style.left = `${outline.left + 4}px`;
|
||||
host.append(node);
|
||||
}
|
||||
},
|
||||
[onTargetSelected, selection?.recordId, selection?.targetKey],
|
||||
);
|
||||
const measure = useCallback(
|
||||
(element: HTMLElement | null): Outline | null => {
|
||||
const host = canvas.current;
|
||||
if (!element || !host || !host.contains(element)) return null;
|
||||
const box = element.getBoundingClientRect();
|
||||
const parent = host.getBoundingClientRect();
|
||||
const target = targets.find((item) => item.key === element.dataset.editorTarget);
|
||||
if (!target || !box.width || !box.height) return null;
|
||||
return {
|
||||
top: box.top - parent.top,
|
||||
left: box.left - parent.left,
|
||||
width: box.width,
|
||||
height: box.height,
|
||||
label: target.label,
|
||||
};
|
||||
},
|
||||
[targets],
|
||||
);
|
||||
useLayoutEffect(() => {
|
||||
const viewport = root.current;
|
||||
const outlineHost = overlay.current;
|
||||
const host = canvas.current;
|
||||
if (!viewport || !outlineHost || !host) return;
|
||||
let frame = 0;
|
||||
const update = () => {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(() => {
|
||||
const nextHover = measure(hovered);
|
||||
const nextSelected = measure(selectedElement());
|
||||
const nextComposite = targets
|
||||
.filter((target) => target.composite)
|
||||
.flatMap((target) => {
|
||||
const element = host.querySelector<HTMLElement>(
|
||||
`[data-editor-target="${CSS.escape(target.key)}"]`,
|
||||
);
|
||||
const outline = measure(element);
|
||||
return outline ? [{ ...outline, key: target.key }] : [];
|
||||
});
|
||||
renderOutlines(outlineHost, {
|
||||
hover: nextHover,
|
||||
selected: nextSelected,
|
||||
composite: nextComposite,
|
||||
});
|
||||
});
|
||||
};
|
||||
update();
|
||||
const resize = new ResizeObserver(update);
|
||||
resize.observe(viewport);
|
||||
host
|
||||
.querySelectorAll<HTMLElement>("[data-editor-target]")
|
||||
.forEach((node) => resize.observe(node));
|
||||
window.addEventListener("resize", update);
|
||||
viewport.addEventListener("scroll", update);
|
||||
viewport.addEventListener("load", update, true);
|
||||
return () => {
|
||||
cancelAnimationFrame(frame);
|
||||
resize.disconnect();
|
||||
window.removeEventListener("resize", update);
|
||||
viewport.removeEventListener("scroll", update);
|
||||
viewport.removeEventListener("load", update, true);
|
||||
};
|
||||
}, [hovered, measure, selectedElement, workspace, page]);
|
||||
useEffect(() => {
|
||||
selectedElement()?.scrollIntoView({ block: "nearest", behavior: "smooth" });
|
||||
}, [selectedElement]);
|
||||
useEffect(() => {
|
||||
const clear = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") onTargetSelected(undefined);
|
||||
};
|
||||
window.addEventListener("keydown", clear);
|
||||
return () => window.removeEventListener("keydown", clear);
|
||||
}, [onTargetSelected]);
|
||||
if (!Renderer)
|
||||
return <Alert type="warning" showIcon message="此模板尚无组件预览,请使用页面预览" />;
|
||||
return (
|
||||
<div className="component-template-preview-shell">
|
||||
<div
|
||||
className="component-template-preview__tools"
|
||||
aria-label="预览操作模式"
|
||||
hidden={!targets.length}
|
||||
>
|
||||
<button type="button" aria-pressed={mode === "edit"} onClick={() => setMode("edit")}>
|
||||
点选编辑
|
||||
</button>
|
||||
<button type="button" aria-pressed={mode === "browse"} onClick={() => setMode("browse")}>
|
||||
浏览页面
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
ref={root}
|
||||
className="component-template-preview"
|
||||
data-active-target={selection?.targetKey}
|
||||
data-active-record-id={selection?.recordId}
|
||||
data-editor-mode={mode}
|
||||
onPointerMoveCapture={(event) => {
|
||||
if (mode !== "edit" || !targets.length) return;
|
||||
const next = targetFor(event.target instanceof Element ? event.target : null);
|
||||
if (next !== hovered) setHovered(next);
|
||||
}}
|
||||
onPointerLeave={() => setHovered(null)}
|
||||
onClickCapture={(event) => {
|
||||
if (mode !== "edit" || !targets.length) return;
|
||||
const canvas = root.current?.querySelector(".component-template-preview__canvas");
|
||||
if (!event.target || !(event.target instanceof Node) || !canvas?.contains(event.target))
|
||||
return;
|
||||
const pointTarget = document.elementFromPoint(event.clientX, event.clientY);
|
||||
const element = targetFor(
|
||||
pointTarget && canvas.contains(pointTarget) ? pointTarget : null,
|
||||
);
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onTargetSelected(
|
||||
element
|
||||
? {
|
||||
targetKey: element.dataset.editorTarget!,
|
||||
...(element.dataset.editorRecordId
|
||||
? { recordId: element.dataset.editorRecordId }
|
||||
: {}),
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<div ref={canvas} className="component-template-preview__canvas">
|
||||
<Renderer workspace={workspace} page={page} {...(offeringId ? { offeringId } : {})} />
|
||||
<div
|
||||
ref={overlay}
|
||||
className={`component-template-preview__overlay-host ${
|
||||
mode === "edit" ? "is-visible" : ""
|
||||
}`}
|
||||
data-editor-overlay=""
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// @ts-nocheck
|
||||
@@ -0,0 +1,136 @@
|
||||
import { Alert, Button, Form, Input, Select, Space, Switch, Typography, message } from "antd";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect } from "react";
|
||||
import type { RuntimeWorkspace } from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import { MutationError } from "../../components/QueryState.js";
|
||||
|
||||
type RuntimeInquiryForm = RuntimeWorkspace["inquiryForms"][number];
|
||||
|
||||
export function InquiryPreviewEditor({
|
||||
runtime,
|
||||
fieldKey,
|
||||
onDraft,
|
||||
onSaved,
|
||||
}: {
|
||||
runtime: RuntimeInquiryForm;
|
||||
fieldKey: string;
|
||||
onDraft: (fields: RuntimeInquiryForm["fields"]) => void;
|
||||
onSaved?: () => void;
|
||||
}) {
|
||||
const [form] = Form.useForm<Record<string, unknown>>();
|
||||
const cache = useQueryClient();
|
||||
const query = useQuery({
|
||||
queryKey: ["admin-inquiry-forms"],
|
||||
queryFn: () => createApiClient().listAdminInquiryForms(),
|
||||
});
|
||||
const record = query.data?.find((item) => item.id === runtime.key);
|
||||
const field = runtime.fields.find((item) => item.key === fieldKey);
|
||||
useEffect(() => {
|
||||
if (field) form.setFieldsValue({ ...field });
|
||||
}, [fieldKey, runtime.key, form]);
|
||||
const update = (values: Record<string, unknown>) =>
|
||||
runtime.fields.map((item) => (item.key === fieldKey ? { ...item, ...values } : item));
|
||||
const save = useMutation({
|
||||
mutationFn: async (values: Record<string, unknown>) => {
|
||||
if (!record || !field) throw new Error("表单已不存在,请刷新后重试");
|
||||
const fieldsSnapshot = record.fieldsSnapshot.map((item) => {
|
||||
if (!item || typeof item !== "object" || (item as { key?: string }).key !== fieldKey)
|
||||
return item;
|
||||
const type =
|
||||
values.type === "tel"
|
||||
? "phone"
|
||||
: values.type === "checkbox"
|
||||
? "multi-select"
|
||||
: values.type;
|
||||
return { ...item, ...values, type };
|
||||
});
|
||||
return createApiClient().updateAdminInquiryForm(record.id, { fieldsSnapshot });
|
||||
},
|
||||
onSuccess: () => {
|
||||
onSaved?.();
|
||||
message.success("表单字段已保存为草稿");
|
||||
void cache.invalidateQueries({ queryKey: ["admin-inquiry-forms"] });
|
||||
void cache.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
|
||||
void cache.invalidateQueries({ queryKey: ["publication-readiness"] });
|
||||
},
|
||||
});
|
||||
if (query.isError)
|
||||
return (
|
||||
<Alert
|
||||
type="error"
|
||||
message="表单读取失败"
|
||||
action={<Button onClick={() => void query.refetch()}>重试</Button>}
|
||||
/>
|
||||
);
|
||||
if (!record)
|
||||
return (
|
||||
<Alert
|
||||
type="info"
|
||||
message={query.isPending ? "正在读取表单" : "未找到对应表单,请刷新后重试"}
|
||||
/>
|
||||
);
|
||||
if (!field) return <Alert type="warning" message="字段已不存在" />;
|
||||
return (
|
||||
<Form<Record<string, unknown>>
|
||||
form={form}
|
||||
layout="vertical"
|
||||
initialValues={field}
|
||||
onValuesChange={(_, values) => onDraft(update(values))}
|
||||
onFinish={(values) => save.mutate(values)}
|
||||
>
|
||||
<Typography.Paragraph type="secondary">
|
||||
{record.name} · 编辑字段:{field.label}
|
||||
</Typography.Paragraph>
|
||||
<Form.Item
|
||||
name="label"
|
||||
label="字段标题"
|
||||
rules={[{ required: true, message: "请填写字段标题" }]}
|
||||
>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="type" label="输入方式">
|
||||
<Select
|
||||
options={[
|
||||
{ value: "text", label: "简短文字" },
|
||||
{ value: "textarea", label: "详细说明" },
|
||||
{ value: "tel", label: "联系电话" },
|
||||
{ value: "number", label: "数字" },
|
||||
{ value: "date", label: "日期" },
|
||||
{ value: "select", label: "单项选择" },
|
||||
{ value: "radio", label: "单选按钮" },
|
||||
{ value: "checkbox", label: "多项选择" },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="required" label="必填" valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
<Form.List name="options">
|
||||
{(fields, { add, remove }) => (
|
||||
<div>
|
||||
{fields.length ? <Typography.Title level={5}>选项</Typography.Title> : null}
|
||||
{fields.map(({ key, name }) => (
|
||||
<Space key={key} align="start">
|
||||
<Form.Item name={[name, "label"]} label="选项名称" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name={[name, "value"]} label="选项标识" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Button onClick={() => remove(name)}>删除</Button>
|
||||
</Space>
|
||||
))}
|
||||
<Button onClick={() => add({ label: "新选项", value: crypto.randomUUID() })}>
|
||||
添加选项
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Form.List>
|
||||
<MutationError error={save.error} />
|
||||
<Button style={{ marginTop: 24 }} type="primary" htmlType="submit" loading={save.isPending}>
|
||||
保存表单字段
|
||||
</Button>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
.presentation-editor {
|
||||
margin-top: 0;
|
||||
padding-top: 8px;
|
||||
}
|
||||
|
||||
.presentation-editor__header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.presentation-editor__header .ant-typography {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.presentation-editor__header .ant-typography + .ant-typography {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.presentation-editor > .ant-space {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
margin-bottom: 24px !important;
|
||||
padding: 6px;
|
||||
border: 1px solid #e8e8e8;
|
||||
border-radius: 10px;
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
@media (max-width: 575px) {
|
||||
.presentation-editor__header {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.presentation-editor__header .ant-tag {
|
||||
display: inline-block;
|
||||
margin-top: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.presentation-editor__workspace {
|
||||
display: grid;
|
||||
grid-template-columns: 200px minmax(300px, 1fr) minmax(280px, 360px);
|
||||
grid-template-areas: "outline preview inspector";
|
||||
margin: 0 !important;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.presentation-editor__preview {
|
||||
grid-area: preview;
|
||||
padding: 20px !important;
|
||||
background: #f8fafc;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.presentation-editor__inspector {
|
||||
grid-area: inspector;
|
||||
padding: 24px !important;
|
||||
min-width: 0;
|
||||
border-left: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.presentation-editor__outline {
|
||||
grid-area: outline;
|
||||
padding: 20px 12px;
|
||||
border-right: 1px solid #e5e7eb;
|
||||
}
|
||||
.presentation-editor__regions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
}
|
||||
.presentation-editor__regions .ant-space-item {
|
||||
width: 100%;
|
||||
}
|
||||
.presentation-editor__regions .ant-btn {
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.presentation-editor__regions .is-child-region {
|
||||
padding-left: 24px;
|
||||
}
|
||||
.presentation-editor__regions .ant-btn[aria-pressed="true"] {
|
||||
background: #e6f4ff;
|
||||
color: #0958d9;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.presentation-editor__preview .template-preview {
|
||||
height: 680px;
|
||||
min-height: 0;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.presentation-editor__regions .ant-btn {
|
||||
height: auto;
|
||||
padding: 5px 10px;
|
||||
font-size: 12px;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.presentation-editor__empty {
|
||||
padding: 56px 16px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.presentation-editor__inspector .ant-form-item {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.presentation-editor__inspector form > section {
|
||||
padding: 16px;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 12px;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.presentation-editor__inspector form > section + section {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.presentation-editor__inspector form > .ant-space:last-child {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
z-index: 2;
|
||||
padding: 16px 0 4px;
|
||||
border-top: 1px solid #e5e7eb;
|
||||
background: #fff;
|
||||
}
|
||||
.presentation-editor__inspector form > .ant-space:last-child .ant-btn-primary {
|
||||
min-width: 140px;
|
||||
}
|
||||
.presentation-editor__inspector > .ant-tag {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
@media (max-width: 1199px) {
|
||||
.presentation-editor__workspace {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-areas: "outline" "preview" "inspector";
|
||||
}
|
||||
.presentation-editor__outline {
|
||||
border-right: 0;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
.presentation-editor__inspector {
|
||||
border-left: 0;
|
||||
border-top: 1px solid #e5e7eb;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 575px) {
|
||||
.presentation-editor__preview,
|
||||
.presentation-editor__inspector {
|
||||
padding: 12px !important;
|
||||
}
|
||||
.presentation-editor__preview .template-preview {
|
||||
height: 600px;
|
||||
}
|
||||
.presentation-editor__navigation {
|
||||
max-width: 100%;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
.template-preview {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: min(72vh, 760px);
|
||||
min-height: 560px;
|
||||
overflow: hidden;
|
||||
border: 1px solid #e8e8e8;
|
||||
background: #f3f4f6;
|
||||
}
|
||||
|
||||
.template-preview iframe {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: 0;
|
||||
background: #fff;
|
||||
transition: opacity 120ms ease;
|
||||
}
|
||||
|
||||
.template-preview__loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: #fff;
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Alert, Spin } from "antd";
|
||||
import type {
|
||||
BrandProfile,
|
||||
EditorPreviewFrameMessage,
|
||||
EditorPreviewHostMessage,
|
||||
RuntimeWorkspace,
|
||||
} from "@personal-brand/api-client";
|
||||
import { templatePreviewUrl } from "../../lib/template-preview.js";
|
||||
import { ComponentTemplatePreview } from "./ComponentTemplatePreview.js";
|
||||
import { resolveTemplateRenderer } from "./component-renderers.jsx";
|
||||
import type { PreviewSelection, PreviewTarget } from "./preview-selection.js";
|
||||
import "./TemplatePreview.css";
|
||||
|
||||
export function TemplatePreview({
|
||||
brand,
|
||||
workspace,
|
||||
page,
|
||||
offeringId,
|
||||
targetKey,
|
||||
selection,
|
||||
targets,
|
||||
onTargetSelected,
|
||||
}: {
|
||||
brand: BrandProfile;
|
||||
workspace?: RuntimeWorkspace;
|
||||
page: string;
|
||||
offeringId?: string;
|
||||
targetKey?: string;
|
||||
selection?: PreviewSelection;
|
||||
targets: PreviewTarget[];
|
||||
onTargetSelected: (selection?: PreviewSelection) => void;
|
||||
}) {
|
||||
const frame = useRef<HTMLIFrameElement>(null);
|
||||
const useComponent = Boolean(workspace && resolveTemplateRenderer(workspace));
|
||||
const [ready, setReady] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const url = useMemo(() => {
|
||||
const value = templatePreviewUrl(
|
||||
brand.slug,
|
||||
page,
|
||||
import.meta.env.VITE_TEMPLATE_PREVIEW_URL || "/template-preview/index.html",
|
||||
window.location.origin,
|
||||
`/pages/${encodeURIComponent(page)}/index`,
|
||||
);
|
||||
if (!value) return undefined;
|
||||
const preview = new URL(value);
|
||||
preview.searchParams.set("refresh", String(reloadKey));
|
||||
return preview.toString();
|
||||
}, [brand.slug, page, reloadKey]);
|
||||
const origin = useMemo(() => (url ? new URL(url).origin : ""), [url]);
|
||||
const brandDraft = useMemo(
|
||||
() => ({
|
||||
name: brand.name,
|
||||
tagline: brand.tagline,
|
||||
description: brand.description,
|
||||
avatarUrl: brand.avatarUrl,
|
||||
coverUrl: brand.coverUrl,
|
||||
hours: brand.hours,
|
||||
address: brand.address,
|
||||
deliveryNote: brand.deliveryNote,
|
||||
contactPhone: brand.contactPhone,
|
||||
contactWechat: brand.contactWechat,
|
||||
config: brand.config,
|
||||
}),
|
||||
[brand],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setReady(false);
|
||||
setError("");
|
||||
}, [url]);
|
||||
|
||||
useEffect(() => {
|
||||
const onMessage = (event: MessageEvent<EditorPreviewFrameMessage>) => {
|
||||
if (event.source !== frame.current?.contentWindow || event.origin !== origin) return;
|
||||
const message = event.data;
|
||||
if (message?.protocol !== "personal-brand-editor-preview" || message.version !== 1) return;
|
||||
if (message.type === "ready") setReady(true);
|
||||
if (message.type === "targetSelected" && message.page === page)
|
||||
onTargetSelected({ targetKey: message.targetKey });
|
||||
};
|
||||
window.addEventListener("message", onMessage);
|
||||
return () => window.removeEventListener("message", onMessage);
|
||||
}, [onTargetSelected, origin, page]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready || !frame.current?.contentWindow || !origin) return;
|
||||
const send = (message: EditorPreviewHostMessage) =>
|
||||
frame.current?.contentWindow?.postMessage(message, origin);
|
||||
if (workspace) {
|
||||
send({
|
||||
protocol: "personal-brand-editor-preview",
|
||||
version: 1,
|
||||
type: "workspaceDraft",
|
||||
workspace,
|
||||
});
|
||||
} else {
|
||||
send({
|
||||
protocol: "personal-brand-editor-preview",
|
||||
version: 1,
|
||||
type: "brandDraft",
|
||||
brand: brandDraft,
|
||||
});
|
||||
}
|
||||
if (targetKey)
|
||||
send({
|
||||
protocol: "personal-brand-editor-preview",
|
||||
version: 1,
|
||||
type: "focusTarget",
|
||||
targetKey,
|
||||
});
|
||||
}, [brandDraft, origin, ready, targetKey, workspace]);
|
||||
|
||||
useEffect(() => {
|
||||
const refresh = () => setReloadKey((value) => value + 1);
|
||||
window.addEventListener("template-preview-refresh", refresh);
|
||||
return () => window.removeEventListener("template-preview-refresh", refresh);
|
||||
}, []);
|
||||
|
||||
if (!useComponent && !url)
|
||||
return (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
message="页面预览暂不可用"
|
||||
description="请确认模板预览资源已构建并发布,或本地预览服务正在运行。"
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="template-preview">
|
||||
{workspace && useComponent ? (
|
||||
<ComponentTemplatePreview
|
||||
workspace={workspace}
|
||||
page={page}
|
||||
{...(offeringId ? { offeringId } : {})}
|
||||
{...(targetKey ? { targetKey } : {})}
|
||||
{...(selection ? { selection } : {})}
|
||||
targets={targets}
|
||||
onTargetSelected={onTargetSelected}
|
||||
/>
|
||||
) : null}
|
||||
{!useComponent ? (
|
||||
<>
|
||||
{!ready && !error ? (
|
||||
<div className="template-preview__loading">
|
||||
<Spin tip="正在加载页面预览" />
|
||||
</div>
|
||||
) : null}
|
||||
{error ? (
|
||||
<Alert type="error" showIcon message="页面预览加载失败" description={error} />
|
||||
) : null}
|
||||
<iframe
|
||||
key={url}
|
||||
ref={frame}
|
||||
title="小程序页面预览"
|
||||
src={url}
|
||||
referrerPolicy="origin"
|
||||
onError={() => setError("请检查预览服务地址和网络连接。")}
|
||||
style={{ opacity: ready ? 1 : 0 }}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { ComponentType } from "react";
|
||||
import type { RuntimeWorkspace } from "@personal-brand/api-client";
|
||||
|
||||
declare module "./component-renderers.jsx" {
|
||||
export function resolveTemplateRenderer(workspace: RuntimeWorkspace): ComponentType<{
|
||||
workspace: RuntimeWorkspace;
|
||||
page: string;
|
||||
offeringId?: string;
|
||||
}> | null;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import React from "react";
|
||||
import { Inquiry } from "../../../../taro/src/components/Inquiry.tsx";
|
||||
import { Records } from "../../../../taro/src/components/Records.tsx";
|
||||
import { Success } from "../../../../taro/src/components/Success.tsx";
|
||||
import { TemplateAssetContext } from "./taro-web-components.jsx";
|
||||
|
||||
const templateRenderers = import.meta.glob("../../../../../packages/template-*/taro/index.tsx", {
|
||||
eager: true,
|
||||
});
|
||||
|
||||
function pageContent({ workspace, page }) {
|
||||
if (page === "inquiry") return <Inquiry workspace={workspace} preview />;
|
||||
if (page === "records") return <Records workspace={workspace} preview />;
|
||||
if (page === "success") return <Success workspace={workspace} preview />;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveTemplateRenderer(workspace) {
|
||||
const config = workspace?.brand?.config;
|
||||
const key =
|
||||
config && typeof config === "object" && !Array.isArray(config)
|
||||
? config.visualTemplateKey
|
||||
: undefined;
|
||||
if (typeof key !== "string") return null;
|
||||
const suffix = `/template-${key}/taro/index.tsx`;
|
||||
const entry = Object.entries(templateRenderers).find(([path]) => path.endsWith(suffix));
|
||||
const TemplatePage = entry?.[1]?.TemplatePage;
|
||||
if (!TemplatePage) return null;
|
||||
return function TemplatePreview(props) {
|
||||
return (
|
||||
<TemplateAssetContext.Provider value={key}>
|
||||
<TemplatePage {...props}>{pageContent(props)}</TemplatePage>
|
||||
</TemplateAssetContext.Provider>
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -12,6 +12,18 @@ export type PresentationSection = {
|
||||
|
||||
export type PresentationValues = Record<string, unknown>;
|
||||
|
||||
export function filterSectionsForPreviewTarget<
|
||||
T extends { fields: Array<{ previewTarget?: string }> },
|
||||
>(sections: T[], targetKey?: string): T[] {
|
||||
if (!targetKey) return sections;
|
||||
return sections
|
||||
.map((section) => ({
|
||||
...section,
|
||||
fields: section.fields.filter((field) => field.previewTarget === targetKey),
|
||||
}))
|
||||
.filter((section) => section.fields.length > 0);
|
||||
}
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
@@ -19,11 +31,14 @@ function asObject(value: unknown): Record<string, unknown> {
|
||||
}
|
||||
|
||||
function safePath(binding: string): string[] | null {
|
||||
const prefix = ["brand.config.", "offering.config.", "trust.config."].find((candidate) =>
|
||||
binding.startsWith(candidate),
|
||||
);
|
||||
if (!prefix) return null;
|
||||
const path = binding.slice(prefix.length).split(".");
|
||||
const prefixes = ["brand.config.", "offering.config.", "trust.config."];
|
||||
const prefix = prefixes.find((candidate) => binding.startsWith(candidate));
|
||||
const standardField =
|
||||
/^(brand\.(name|tagline|avatarUrl|description|contactPhone|contactWechat|address|hours|deliveryNote)|offering\.(name|summary|description|coverUrl|priceText)|trust\.(title|summary|content|coverUrl))$/.test(
|
||||
binding,
|
||||
);
|
||||
if (!prefix && !standardField) return null;
|
||||
const path = prefix ? binding.slice(prefix.length).split(".") : [binding.split(".")[1] ?? ""];
|
||||
if (path.some((part) => !part || ["__proto__", "prototype", "constructor"].includes(part)))
|
||||
return null;
|
||||
return path;
|
||||
@@ -37,10 +52,15 @@ export function readPresentationValue(
|
||||
config: Record<string, unknown> | null | undefined,
|
||||
binding: string,
|
||||
field?: PresentationField,
|
||||
brand?: Record<string, unknown>,
|
||||
): unknown {
|
||||
const path = safePath(binding);
|
||||
if (!path) return undefined;
|
||||
let value: unknown = asObject(config);
|
||||
const isConfigBinding =
|
||||
binding.startsWith("brand.config.") ||
|
||||
binding.startsWith("offering.config.") ||
|
||||
binding.startsWith("trust.config.");
|
||||
let value: unknown = isConfigBinding ? asObject(config) : asObject(brand);
|
||||
for (const part of path) value = asObject(value)[part];
|
||||
if (field?.input === "list") {
|
||||
if (!Array.isArray(value)) return [];
|
||||
@@ -76,9 +96,11 @@ export function applyPresentationValues(
|
||||
let nextConfig = { ...asObject(config) };
|
||||
for (const section of sections) {
|
||||
for (const field of section.fields) {
|
||||
if (!field.binding.includes(".config.")) continue;
|
||||
const path = safePath(field.binding);
|
||||
if (!path) continue;
|
||||
const raw = values[presentationFieldName(section.key, field.key)];
|
||||
if (raw === undefined) continue;
|
||||
const value =
|
||||
field.input === "list" && Array.isArray(raw)
|
||||
? field.itemValueKey
|
||||
@@ -92,3 +114,51 @@ export function applyPresentationValues(
|
||||
}
|
||||
return nextConfig;
|
||||
}
|
||||
|
||||
export function applyStandardBrandValues(
|
||||
brand: Record<string, unknown>,
|
||||
sections: PresentationSection[],
|
||||
values: PresentationValues,
|
||||
): Record<string, unknown> {
|
||||
const next = { ...brand };
|
||||
for (const section of sections) {
|
||||
for (const field of section.fields) {
|
||||
if (!field.binding.startsWith("brand.") || field.binding.startsWith("brand.config."))
|
||||
continue;
|
||||
const value = values[presentationFieldName(section.key, field.key)];
|
||||
if (value !== undefined) next[field.binding.slice("brand.".length)] = value;
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function applyStandardEntityValues(
|
||||
entity: Record<string, unknown>,
|
||||
entityType: "offering" | "trust",
|
||||
sections: PresentationSection[],
|
||||
values: PresentationValues,
|
||||
): Record<string, unknown> {
|
||||
const next = { ...entity };
|
||||
for (const section of sections) {
|
||||
for (const field of section.fields) {
|
||||
if (!field.binding.startsWith(`${entityType}.`) || field.binding.includes(".config."))
|
||||
continue;
|
||||
const value = values[presentationFieldName(section.key, field.key)];
|
||||
if (value !== undefined) next[field.binding.slice(entityType.length + 1)] = value;
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function applyBrandPreviewValues(
|
||||
brand: Record<string, unknown>,
|
||||
config: Record<string, unknown> | null | undefined,
|
||||
sections: PresentationSection[],
|
||||
values: PresentationValues,
|
||||
): Record<string, unknown> {
|
||||
const nextBrand = applyStandardBrandValues(brand, sections, values);
|
||||
return {
|
||||
...nextBrand,
|
||||
config: applyPresentationValues(config, sections, values),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useMemo } from "react";
|
||||
import type { Offering, TrustContent } from "@personal-brand/api-client";
|
||||
import type { TemplateAdminSection } from "@personal-brand/api-client";
|
||||
import { applyPresentationValues, applyStandardEntityValues } from "./presentation-bindings.js";
|
||||
import type { PresentationValues } from "./presentation-bindings.js";
|
||||
|
||||
export interface RecordDraft {
|
||||
source: "offering" | "trust";
|
||||
id: string;
|
||||
values: PresentationValues;
|
||||
}
|
||||
|
||||
export function useRecordPreview({
|
||||
recordDraft,
|
||||
selectedRecord,
|
||||
recordSection,
|
||||
}: {
|
||||
recordDraft?: RecordDraft | undefined;
|
||||
selectedRecord?: Offering | TrustContent | undefined;
|
||||
recordSection?: TemplateAdminSection | undefined;
|
||||
}) {
|
||||
return useMemo(() => {
|
||||
if (!recordDraft || !selectedRecord || !recordSection) return undefined;
|
||||
const config = applyPresentationValues(
|
||||
selectedRecord.config,
|
||||
[recordSection],
|
||||
recordDraft.values,
|
||||
);
|
||||
return {
|
||||
config,
|
||||
standard: applyStandardEntityValues(
|
||||
selectedRecord as unknown as Record<string, unknown>,
|
||||
recordDraft.source,
|
||||
[recordSection],
|
||||
recordDraft.values,
|
||||
),
|
||||
};
|
||||
}, [recordDraft, selectedRecord, recordSection]);
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import { Form, message } from "antd";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type { FormInstance } from "antd";
|
||||
import type {
|
||||
AdminTemplateContent,
|
||||
BrandProfile,
|
||||
Offering,
|
||||
TemplateAdminSection,
|
||||
TrustContent,
|
||||
} from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import {
|
||||
applyBrandPreviewValues,
|
||||
applyPresentationValues,
|
||||
applyStandardBrandValues,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
type PresentationValues,
|
||||
} from "./presentation-bindings.js";
|
||||
|
||||
const standardBrandBindings = [
|
||||
"brand.name",
|
||||
"brand.tagline",
|
||||
"brand.avatarUrl",
|
||||
"brand.description",
|
||||
"brand.contactPhone",
|
||||
"brand.contactWechat",
|
||||
"brand.address",
|
||||
] as const;
|
||||
|
||||
export interface BrandPresentationFormState {
|
||||
form: FormInstance<PresentationValues>;
|
||||
initialValues: PresentationValues;
|
||||
}
|
||||
|
||||
export function useBrandPresentationSections(
|
||||
templateContent: AdminTemplateContent | null | undefined,
|
||||
): TemplateAdminSection[] {
|
||||
return useMemo(() => {
|
||||
const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({
|
||||
...field,
|
||||
binding: field.binding ?? `brand.config.templateData.${field.key}`,
|
||||
}));
|
||||
return [
|
||||
...[...new Set(declaredTemplateFields.map((field) => field.page ?? "home"))].map((page) => ({
|
||||
key: `template-data:${page}`,
|
||||
title: "模板专属内容",
|
||||
description: "这些字段由当前小程序模板定义,保存后发布才会对外展示。",
|
||||
page,
|
||||
target: "brand" as const,
|
||||
fields: declaredTemplateFields.filter((field) => (field.page ?? "home") === page),
|
||||
})),
|
||||
...(templateContent?.admin.sections ?? []),
|
||||
].map((section) => ({
|
||||
...section,
|
||||
fields: section.fields.filter(
|
||||
(field) =>
|
||||
field.binding.startsWith("brand.config.") ||
|
||||
(standardBrandBindings as readonly string[]).includes(field.binding),
|
||||
),
|
||||
}));
|
||||
}, [templateContent]);
|
||||
}
|
||||
|
||||
export function useBrandPresentationForm({
|
||||
brand,
|
||||
config,
|
||||
sections,
|
||||
}: {
|
||||
brand: BrandProfile;
|
||||
config: Record<string, unknown> | null | undefined;
|
||||
sections: TemplateAdminSection[];
|
||||
}): BrandPresentationFormState {
|
||||
const [form] = Form.useForm<PresentationValues>();
|
||||
const initialValues = useMemo(() => {
|
||||
const values: PresentationValues = {};
|
||||
for (const section of sections) {
|
||||
for (const field of section.fields) {
|
||||
values[presentationFieldName(section.key, field.key)] = readPresentationValue(
|
||||
config,
|
||||
field.binding,
|
||||
field,
|
||||
brand as unknown as Record<string, unknown>,
|
||||
);
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}, [brand, config, sections]);
|
||||
|
||||
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
|
||||
return { form, initialValues };
|
||||
}
|
||||
|
||||
interface BrandSaveMutationOptions extends BrandPresentationFormState {
|
||||
brand: BrandProfile;
|
||||
config: Record<string, unknown> | null | undefined;
|
||||
sections: TemplateAdminSection[];
|
||||
queryClient: QueryClient;
|
||||
}
|
||||
|
||||
export function useBrandSaveMutation({
|
||||
brand,
|
||||
config,
|
||||
sections,
|
||||
queryClient,
|
||||
}: BrandSaveMutationOptions) {
|
||||
return useMutation({
|
||||
mutationFn: (values: PresentationValues) => {
|
||||
const nextConfig = applyPresentationValues(config, sections, values);
|
||||
const contentConfig = { ...nextConfig };
|
||||
delete contentConfig.visualTemplateKey;
|
||||
const standard = applyStandardBrandValues(
|
||||
brand as unknown as Record<string, unknown>,
|
||||
sections,
|
||||
values,
|
||||
);
|
||||
const changed = Object.fromEntries(
|
||||
Object.entries(standard).filter(
|
||||
([key, value]) =>
|
||||
key !== "config" && value !== (brand as unknown as Record<string, unknown>)[key],
|
||||
),
|
||||
);
|
||||
return createApiClient().updateAdminBrand({ ...changed, config: contentConfig });
|
||||
},
|
||||
onSuccess: () => {
|
||||
message.success("页面内容已保存为草稿,发布后小程序才会更新");
|
||||
window.dispatchEvent(new Event("template-preview-refresh"));
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["publication-readiness"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useBrandPreviewDraft({
|
||||
brand,
|
||||
config,
|
||||
sections,
|
||||
form,
|
||||
onDirty,
|
||||
}: {
|
||||
brand: BrandProfile;
|
||||
config: Record<string, unknown> | null | undefined;
|
||||
sections: TemplateAdminSection[];
|
||||
form: BrandPresentationFormState["form"];
|
||||
onDirty: () => void;
|
||||
}) {
|
||||
const [previewConfig, setPreviewConfig] = useState(config ?? {});
|
||||
const [previewBrandValues, setPreviewBrandValues] = useState<Record<string, unknown>>({});
|
||||
|
||||
useEffect(() => {
|
||||
setPreviewConfig(config ?? {});
|
||||
setPreviewBrandValues({});
|
||||
}, [config, form]);
|
||||
|
||||
const handleValuesChange = (changed: PresentationValues, allValues: PresentationValues) => {
|
||||
onDirty();
|
||||
const synchronized: PresentationValues = {
|
||||
...(form.getFieldsValue(true) as PresentationValues),
|
||||
...allValues,
|
||||
};
|
||||
for (const section of sections) {
|
||||
for (const field of section.fields) {
|
||||
const name = presentationFieldName(section.key, field.key);
|
||||
if (!Object.prototype.hasOwnProperty.call(changed, name)) continue;
|
||||
for (const peer of sections) {
|
||||
for (const item of peer.fields) {
|
||||
if (item.binding === field.binding)
|
||||
synchronized[presentationFieldName(peer.key, item.key)] = changed[name];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
form.setFieldsValue(synchronized);
|
||||
const next = applyBrandPreviewValues(
|
||||
brand as unknown as Record<string, unknown>,
|
||||
config,
|
||||
sections,
|
||||
synchronized,
|
||||
);
|
||||
setPreviewConfig((next.config as Record<string, unknown>) ?? {});
|
||||
setPreviewBrandValues(next);
|
||||
};
|
||||
|
||||
const previewBrand = useMemo(
|
||||
() => ({ ...brand, ...previewBrandValues, config: previewConfig }),
|
||||
[brand, previewBrandValues, previewConfig],
|
||||
);
|
||||
|
||||
const resetPreview = useCallback(() => {
|
||||
setPreviewConfig(config ?? {});
|
||||
setPreviewBrandValues({});
|
||||
}, [config]);
|
||||
|
||||
return {
|
||||
previewBrand,
|
||||
handleValuesChange,
|
||||
resetPreview,
|
||||
};
|
||||
}
|
||||
|
||||
export function usePresentationRecordQueries(
|
||||
source: "offering" | "trust" | undefined,
|
||||
recordId: string | undefined,
|
||||
) {
|
||||
const offeringsQuery = useQuery({
|
||||
queryKey: ["admin-offerings"],
|
||||
queryFn: () => createApiClient().listAdminOfferings(),
|
||||
enabled: source === "offering",
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
const trustQuery = useQuery({
|
||||
queryKey: ["trust-content"],
|
||||
queryFn: () => createApiClient().listAdminTrustContent(),
|
||||
enabled: source === "trust",
|
||||
});
|
||||
const selectedRecord =
|
||||
source === "offering"
|
||||
? offeringsQuery.data?.find((item: Offering) => item.id === recordId)
|
||||
: source === "trust"
|
||||
? trustQuery.data?.find((item: TrustContent) => item.id === recordId)
|
||||
: undefined;
|
||||
return { offeringsQuery, trustQuery, selectedRecord };
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
export type PreviewSelection = { targetKey: string; recordId?: string };
|
||||
|
||||
// 与模板 slot 一致,优先选择承载结构化内容的记录。
|
||||
export function previewTrustRecordId(
|
||||
items: { id?: string; type: string; config: Record<string, unknown> }[],
|
||||
type: string | undefined,
|
||||
): string | undefined {
|
||||
const matches = items.filter((item) => item.type === type);
|
||||
return (matches.find((item) => Object.keys(item.config).length > 0) ?? matches[0])?.id;
|
||||
}
|
||||
|
||||
export type PreviewTarget = {
|
||||
key: string;
|
||||
label: string;
|
||||
source: "brand" | "offering" | "trust" | "inquiry";
|
||||
page: string;
|
||||
composite?: boolean;
|
||||
trustType?: string;
|
||||
children?: string[];
|
||||
};
|
||||
|
||||
export function resolvePreviewSelection(
|
||||
targetKey: string,
|
||||
recordId: string | undefined,
|
||||
targets: PreviewTarget[],
|
||||
page: string,
|
||||
): PreviewSelection | undefined {
|
||||
const target = targets.find((item) => item.key === targetKey && item.page === page);
|
||||
if (!target) return undefined;
|
||||
if (recordId && target.source !== "offering" && target.source !== "trust") return undefined;
|
||||
// 空区域仍可选中,编辑面板提供创建内容的入口。
|
||||
return recordId ? { targetKey, recordId } : { targetKey };
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import React from "react";
|
||||
|
||||
export const TemplateAssetContext = React.createContext("");
|
||||
const templateAssets = import.meta.glob("../../../../../packages/template-*/miniapp/assets/**/*", {
|
||||
eager: true,
|
||||
query: "?url",
|
||||
import: "default",
|
||||
});
|
||||
|
||||
function resolveImageSource(src, templateKey) {
|
||||
if (typeof src !== "string" || !src.startsWith("/assets/")) return src;
|
||||
const relative = src.slice("/assets/".length);
|
||||
for (const [file, url] of Object.entries(templateAssets)) {
|
||||
const parts = file.split("/packages/template-")[1]?.split("/miniapp/assets/");
|
||||
if (!parts) continue;
|
||||
const [key, asset] = parts;
|
||||
if (relative === key + "/" + asset || (key === templateKey && relative === asset)) return url;
|
||||
}
|
||||
return src;
|
||||
}
|
||||
|
||||
const element = (tag) =>
|
||||
React.forwardRef(({ children, className, style, onClick, ...props }, ref) =>
|
||||
React.createElement(tag, { ...props, ref, className, style, onClick }, children),
|
||||
);
|
||||
|
||||
export const View = element("div");
|
||||
export const Text = element("span");
|
||||
export const Button = element("button");
|
||||
export const Input = React.forwardRef(({ onInput, ...props }, ref) =>
|
||||
React.createElement("input", {
|
||||
...props,
|
||||
ref,
|
||||
onInput: (event) => onInput?.({ detail: { value: event.currentTarget.value } }),
|
||||
}),
|
||||
);
|
||||
export const Textarea = React.forwardRef(({ onInput, maxlength, ...props }, ref) =>
|
||||
React.createElement("textarea", {
|
||||
...props,
|
||||
ref,
|
||||
maxLength: maxlength,
|
||||
onInput: (event) => onInput?.({ detail: { value: event.currentTarget.value } }),
|
||||
}),
|
||||
);
|
||||
export function Picker({ children, mode, range = [], value, onChange }) {
|
||||
return (
|
||||
<div style={{ position: "relative" }}>
|
||||
{children}
|
||||
{mode === "date" ? (
|
||||
<input
|
||||
aria-label="选择日期"
|
||||
type="date"
|
||||
value={value || ""}
|
||||
onChange={(event) => onChange?.({ detail: { value: event.currentTarget.value } })}
|
||||
style={{ position: "absolute", inset: 0, width: "100%", opacity: 0, cursor: "pointer" }}
|
||||
/>
|
||||
) : (
|
||||
<select
|
||||
aria-label="选择选项"
|
||||
value={value ?? 0}
|
||||
onChange={(event) => onChange?.({ detail: { value: event.currentTarget.value } })}
|
||||
style={{ position: "absolute", inset: 0, width: "100%", opacity: 0, cursor: "pointer" }}
|
||||
>
|
||||
{range.map((label, index) => (
|
||||
<option key={index} value={index}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const CheckboxContext = React.createContext(null);
|
||||
export function CheckboxGroup({ children, onChange }) {
|
||||
const [selected, setSelected] = React.useState([]);
|
||||
const update = (value, checked) => {
|
||||
const next = checked ? [...selected, value] : selected.filter((item) => item !== value);
|
||||
setSelected(next);
|
||||
onChange?.({ detail: { value: next } });
|
||||
};
|
||||
return (
|
||||
<CheckboxContext.Provider value={update}>
|
||||
<div>{children}</div>
|
||||
</CheckboxContext.Provider>
|
||||
);
|
||||
}
|
||||
export function Checkbox({ value, checked }) {
|
||||
const update = React.useContext(CheckboxContext);
|
||||
return (
|
||||
<input
|
||||
type="checkbox"
|
||||
value={value}
|
||||
checked={Boolean(checked)}
|
||||
onChange={(event) => update?.(value, event.currentTarget.checked)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
export const Label = element("label");
|
||||
export const Image = React.forwardRef(({ mode, src, style, ...props }, ref) => {
|
||||
const key = React.useContext(TemplateAssetContext);
|
||||
return React.createElement("img", {
|
||||
...props,
|
||||
ref,
|
||||
src: resolveImageSource(src, key),
|
||||
style: { objectFit: mode === "aspectFit" ? "contain" : "cover", ...style },
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import React from "react";
|
||||
const noop = () => Promise.resolve();
|
||||
export const useRouter = () => ({ params: {} });
|
||||
export const useDidShow = (callback) => React.useEffect(callback, []);
|
||||
const Taro = {
|
||||
setStorageSync() {},
|
||||
getStorageSync() {
|
||||
return undefined;
|
||||
},
|
||||
removeStorageSync() {},
|
||||
switchTab: noop,
|
||||
navigateTo: noop,
|
||||
};
|
||||
export default Taro;
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useEffect } from "react";
|
||||
import { Modal } from "antd";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
export function useEditorDraft(dirty: boolean) {
|
||||
const navigate = useNavigate();
|
||||
useEffect(() => {
|
||||
if (!dirty) return;
|
||||
const beforeUnload = (event: BeforeUnloadEvent) => {
|
||||
event.preventDefault();
|
||||
event.returnValue = "";
|
||||
};
|
||||
window.addEventListener("beforeunload", beforeUnload);
|
||||
const leave = (event: MouseEvent) => {
|
||||
if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey)
|
||||
return;
|
||||
const anchor =
|
||||
event.target instanceof Element ? event.target.closest<HTMLAnchorElement>("a[href]") : null;
|
||||
if (!anchor || anchor.target === "_blank" || anchor.hasAttribute("download")) return;
|
||||
const url = new URL(anchor.href, window.location.href);
|
||||
if (url.origin !== window.location.origin || url.pathname === window.location.pathname)
|
||||
return;
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
Modal.confirm({
|
||||
title: "有尚未保存的修改",
|
||||
content: "离开工作台会丢失未保存内容。请先保存,或确认放弃修改。",
|
||||
okText: "放弃修改并继续",
|
||||
cancelText: "继续编辑",
|
||||
onOk: () => {
|
||||
void navigate(`${url.pathname}${url.search}${url.hash}`);
|
||||
},
|
||||
});
|
||||
};
|
||||
document.addEventListener("click", leave, true);
|
||||
return () => {
|
||||
window.removeEventListener("beforeunload", beforeUnload);
|
||||
document.removeEventListener("click", leave, true);
|
||||
};
|
||||
}, [dirty, navigate]);
|
||||
return (action: () => void) => {
|
||||
if (!dirty) return action();
|
||||
Modal.confirm({
|
||||
title: "有尚未保存的修改",
|
||||
content: "切换后当前内容可能丢失。请先保存,或确认放弃修改。",
|
||||
okText: "放弃修改并继续",
|
||||
cancelText: "继续编辑",
|
||||
onOk: action,
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -1,148 +1,34 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Alert, Button, Card, Form, Input, Select, Table, Tag, message } from "antd";
|
||||
import type { CapabilityInstallation } from "@personal-brand/api-client";
|
||||
import { Card, Col, Empty, Row, Typography } from "antd";
|
||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||
import { QueryState } from "../../components/QueryState.js";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
|
||||
const statusLabels = { enabled: "已启用", disabled: "已停用", degraded: "降级" } as const;
|
||||
import { CapabilityCard } from "./components/CapabilityCard.js";
|
||||
import { useCapabilityQuery } from "./hooks/useCapabilityQueries.js";
|
||||
|
||||
export function CapabilitiesPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const query = useQuery({
|
||||
queryKey: ["admin", "capabilities"],
|
||||
queryFn: () => createApiClient().listAdminCapabilities(),
|
||||
});
|
||||
const mutation = useMutation({
|
||||
mutationFn: ({
|
||||
key,
|
||||
values,
|
||||
}: {
|
||||
key: string;
|
||||
values: {
|
||||
capabilityVersion: string;
|
||||
status: CapabilityInstallation["status"];
|
||||
configText?: string;
|
||||
};
|
||||
}) =>
|
||||
createApiClient().updateAdminCapability(key, {
|
||||
capabilityVersion: values.capabilityVersion,
|
||||
status: values.status,
|
||||
config: values.configText ? (JSON.parse(values.configText) as Record<string, unknown>) : {},
|
||||
}),
|
||||
onSuccess: () => {
|
||||
message.success("能力配置已更新");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin", "capabilities"] });
|
||||
},
|
||||
onError: (error) => message.error(error instanceof Error ? error.message : "更新失败"),
|
||||
});
|
||||
const sampleMutation = useMutation({
|
||||
mutationFn: () => createApiClient().importAdminSampleContent(),
|
||||
onSuccess: (result) => message.success(`已导入 ${result.counts.offerings} 项示例业务`),
|
||||
onError: (error) => message.error(error instanceof Error ? error.message : "导入失败"),
|
||||
});
|
||||
if (query.isLoading) return <QueryState loading />;
|
||||
if (query.isError) return <QueryState error={query.error} />;
|
||||
const items = query.data ?? [];
|
||||
return (
|
||||
<div>
|
||||
<AdminPageHeader title="能力插件" description="管理当前模板声明的业务能力及其运行状态。" />
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
message="能力状态会影响公开 Runtime Workspace;停用不会删除历史数据。"
|
||||
style={{ marginBottom: 16 }}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => sampleMutation.mutate()}
|
||||
loading={sampleMutation.isPending}
|
||||
style={{ marginBottom: 16 }}
|
||||
>
|
||||
导入门窗示例内容
|
||||
</Button>
|
||||
<Table
|
||||
rowKey="capabilityKey"
|
||||
dataSource={items}
|
||||
locale={{ emptyText: "当前还没有品牌级能力覆盖,系统将使用模板默认能力。" }}
|
||||
columns={[
|
||||
{ title: "能力", dataIndex: "capabilityKey" },
|
||||
{
|
||||
title: "来源",
|
||||
dataIndex: "source",
|
||||
render: (value: CapabilityInstallation["source"]) => (
|
||||
<Tag>{value === "brand" ? "品牌覆盖" : "模板默认"}</Tag>
|
||||
),
|
||||
},
|
||||
{ title: "版本", dataIndex: "capabilityVersion" },
|
||||
{
|
||||
title: "状态",
|
||||
dataIndex: "status",
|
||||
render: (value: CapabilityInstallation["status"]) => (
|
||||
<Tag
|
||||
color={value === "enabled" ? "green" : value === "degraded" ? "orange" : "default"}
|
||||
>
|
||||
{statusLabels[value]}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
render: (_: unknown, record: CapabilityInstallation) => (
|
||||
<CapabilityEditor
|
||||
record={record}
|
||||
loading={mutation.isPending}
|
||||
onSubmit={(values) => mutation.mutate({ key: record.capabilityKey, values })}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const query = useCapabilityQuery();
|
||||
|
||||
function CapabilityEditor({
|
||||
record,
|
||||
loading,
|
||||
onSubmit,
|
||||
}: {
|
||||
record: CapabilityInstallation;
|
||||
loading: boolean;
|
||||
onSubmit: (values: {
|
||||
capabilityVersion: string;
|
||||
status: CapabilityInstallation["status"];
|
||||
configText?: string;
|
||||
}) => void;
|
||||
}) {
|
||||
const [form] = Form.useForm();
|
||||
return (
|
||||
<Card size="small" style={{ maxWidth: 420 }}>
|
||||
<Form
|
||||
form={form}
|
||||
layout="inline"
|
||||
initialValues={{
|
||||
capabilityVersion: record.capabilityVersion,
|
||||
status: record.status,
|
||||
configText: record.config ? JSON.stringify(record.config) : "",
|
||||
}}
|
||||
onFinish={onSubmit}
|
||||
>
|
||||
<Form.Item name="capabilityVersion" rules={[{ required: true, message: "请输入版本" }]}>
|
||||
<Input placeholder="版本" style={{ width: 100 }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="status">
|
||||
<Select
|
||||
options={Object.entries(statusLabels).map(([value, label]) => ({ value, label }))}
|
||||
style={{ width: 100 }}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="configText">
|
||||
<Input placeholder="JSON 配置(可选)" style={{ width: 180 }} />
|
||||
</Form.Item>
|
||||
<Button type="primary" htmlType="submit" loading={loading}>
|
||||
保存
|
||||
</Button>
|
||||
</Form>
|
||||
</Card>
|
||||
<QueryState loading={query.isLoading} error={query.error} onRetry={() => void query.refetch()}>
|
||||
<AdminPageHeader
|
||||
title="能力管理"
|
||||
description="以经营者视角调整模板能力的开关与展示设置;保存后进入草稿,发布后生效。"
|
||||
/>
|
||||
{query.data?.length ? (
|
||||
<Row gutter={[16, 16]}>
|
||||
{query.data.map((capability) => (
|
||||
<Col key={capability.capabilityKey} xs={24} lg={12}>
|
||||
<CapabilityCard capability={capability} />
|
||||
</Col>
|
||||
))}
|
||||
</Row>
|
||||
) : (
|
||||
<Card>
|
||||
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前模板没有可配置能力。" />
|
||||
</Card>
|
||||
)}
|
||||
<Typography.Text type="secondary" style={{ display: "block", marginTop: 16 }}>
|
||||
技术信息仅用于排查问题,不作为运营判断依据。
|
||||
</Typography.Text>
|
||||
</QueryState>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import { Alert, Button, Card, Input, Switch, Tag, Typography } from "antd";
|
||||
import { useState } from "react";
|
||||
import { useCapabilityMutation } from "../hooks/useCapabilityQueries.js";
|
||||
import type { AdminCapability, CapabilityStatus } from "../types.js";
|
||||
import { CapabilityStatusControl, CapabilityStatusTag } from "./CapabilityStatusControl.js";
|
||||
|
||||
const sourceLabels = {
|
||||
brand: "品牌覆盖",
|
||||
template: "模板默认",
|
||||
} as const;
|
||||
|
||||
const disablePolicyLabels = {
|
||||
allowed: "该能力允许停用,保存后进入草稿。",
|
||||
disabled: "该能力为模板必需项,保存后进入草稿。",
|
||||
} as const;
|
||||
|
||||
const updatedTimeFormatter = new Intl.DateTimeFormat("zh-CN", {
|
||||
dateStyle: "short",
|
||||
timeStyle: "short",
|
||||
});
|
||||
|
||||
function readTextValue(value: unknown): string {
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
function readSwitchValue(value: unknown): boolean {
|
||||
return value === true;
|
||||
}
|
||||
|
||||
export function CapabilityCard({ capability }: { capability: AdminCapability }) {
|
||||
const [status, setStatus] = useState<CapabilityStatus>(capability.status);
|
||||
const [config, setConfig] = useState<Record<string, unknown>>(capability.config);
|
||||
const mutation = useCapabilityMutation();
|
||||
|
||||
const save = async () => {
|
||||
await mutation.mutateAsync({
|
||||
key: capability.capabilityKey,
|
||||
status,
|
||||
config,
|
||||
});
|
||||
};
|
||||
|
||||
const updateConfigValue = (key: string, value: unknown) =>
|
||||
setConfig((current) => ({ ...current, [key]: value }));
|
||||
|
||||
return (
|
||||
<Card
|
||||
title={
|
||||
<span>
|
||||
{capability.displayName ?? "未命名能力"}
|
||||
<Tag style={{ marginLeft: 8 }}>{sourceLabels[capability.source]}</Tag>
|
||||
<CapabilityStatusTag status={status} />
|
||||
</span>
|
||||
}
|
||||
extra={
|
||||
<Button type="primary" loading={mutation.isPending} onClick={() => void save()}>
|
||||
保存草稿
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{mutation.isError ? (
|
||||
<Alert
|
||||
type="error"
|
||||
showIcon
|
||||
message="保存失败,已保留当前输入"
|
||||
description={
|
||||
mutation.error instanceof Error ? mutation.error.message : "请检查网络或稍后重试"
|
||||
}
|
||||
style={{ marginBottom: 16 }}
|
||||
/>
|
||||
) : null}
|
||||
{capability.description ? (
|
||||
<Typography.Paragraph>{capability.description}</Typography.Paragraph>
|
||||
) : null}
|
||||
{capability.impact ? (
|
||||
<Typography.Paragraph type="secondary">影响:{capability.impact}</Typography.Paragraph>
|
||||
) : null}
|
||||
<div style={{ display: "grid", gap: 12 }}>
|
||||
<div>
|
||||
<Typography.Text strong>运行状态</Typography.Text>
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<CapabilityStatusControl
|
||||
status={status}
|
||||
onChange={setStatus}
|
||||
disabled={mutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
<Typography.Paragraph type="secondary" style={{ marginBottom: 0 }}>
|
||||
保存后进入草稿,发布后生效。
|
||||
</Typography.Paragraph>
|
||||
{status === "disabled" && capability.disablePolicy ? (
|
||||
<Typography.Paragraph type="warning" style={{ marginBottom: 0 }}>
|
||||
{disablePolicyLabels[capability.disablePolicy]}
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
</div>
|
||||
{capability.configFields?.length ? (
|
||||
<div>
|
||||
<Typography.Text strong>能力设置</Typography.Text>
|
||||
<div style={{ display: "grid", gap: 12, marginTop: 8 }}>
|
||||
{capability.configFields.map((field) => (
|
||||
<div key={field.key}>
|
||||
<Typography.Text>{field.label}</Typography.Text>
|
||||
{field.input === "switch" ? (
|
||||
<div>
|
||||
<Switch
|
||||
checked={readSwitchValue(config[field.key])}
|
||||
disabled={mutation.isPending}
|
||||
onChange={(checked) => updateConfigValue(field.key, checked)}
|
||||
/>
|
||||
</div>
|
||||
) : field.input === "textarea" ? (
|
||||
<Input.TextArea
|
||||
rows={3}
|
||||
value={readTextValue(config[field.key])}
|
||||
disabled={mutation.isPending}
|
||||
onChange={(event) => updateConfigValue(field.key, event.target.value)}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
value={readTextValue(config[field.key])}
|
||||
disabled={mutation.isPending}
|
||||
onChange={(event) => updateConfigValue(field.key, event.target.value)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<Typography.Text type="secondary">
|
||||
{capability.source === "template"
|
||||
? "当前使用模板默认设置;修改后保存会创建品牌覆盖。"
|
||||
: "当前已创建品牌覆盖;修改后保存会更新草稿。"}
|
||||
{capability.updatedAt
|
||||
? ` 最近更新:${updatedTimeFormatter.format(new Date(capability.updatedAt))}`
|
||||
: ""}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Segmented, Space, Switch, Tag, Typography } from "antd";
|
||||
import type { CapabilityStatus } from "../types.js";
|
||||
|
||||
const statusLabels: Record<CapabilityStatus, string> = {
|
||||
enabled: "启用",
|
||||
disabled: "停用",
|
||||
degraded: "降级",
|
||||
};
|
||||
|
||||
const statusColors: Record<CapabilityStatus, string> = {
|
||||
enabled: "green",
|
||||
disabled: "default",
|
||||
degraded: "orange",
|
||||
};
|
||||
|
||||
export function CapabilityStatusTag({ status }: { status: CapabilityStatus }) {
|
||||
return <Tag color={statusColors[status]}>{statusLabels[status]}</Tag>;
|
||||
}
|
||||
|
||||
export function CapabilityStatusControl({
|
||||
status,
|
||||
onChange,
|
||||
disabled,
|
||||
}: {
|
||||
status: CapabilityStatus;
|
||||
onChange: (status: CapabilityStatus) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const isDisabled = disabled === true;
|
||||
if (status === "degraded")
|
||||
return (
|
||||
<Segmented
|
||||
value={status}
|
||||
disabled={isDisabled}
|
||||
options={[
|
||||
{ value: "degraded", label: "降级" },
|
||||
{ value: "enabled", label: "启用" },
|
||||
{ value: "disabled", label: "停用" },
|
||||
]}
|
||||
onChange={(value) => onChange(value as CapabilityStatus)}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<Space>
|
||||
<Switch
|
||||
checked={status === "enabled"}
|
||||
disabled={isDisabled}
|
||||
onChange={(checked) => onChange(checked ? "enabled" : "disabled")}
|
||||
/>
|
||||
<Typography.Text type={status === "enabled" ? "success" : "secondary"}>
|
||||
{statusLabels[status]}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { message } from "antd";
|
||||
import { createApiClient } from "../../../lib/api.js";
|
||||
import { readAdminCapability } from "../types.js";
|
||||
import type { CapabilityValues } from "../types.js";
|
||||
|
||||
export const capabilitiesQueryKey = ["admin", "capabilities"] as const;
|
||||
|
||||
export function useCapabilityQuery() {
|
||||
return useQuery({
|
||||
queryKey: capabilitiesQueryKey,
|
||||
queryFn: async () => {
|
||||
const response = await createApiClient().listAdminCapabilities();
|
||||
return response.map(readAdminCapability);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useCapabilityMutation() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({ key, ...values }: { key: string } & CapabilityValues) =>
|
||||
createApiClient().updateAdminCapability(key, {
|
||||
...values,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
message.success("能力已保存,进入草稿;发布后生效");
|
||||
void queryClient.invalidateQueries({ queryKey: capabilitiesQueryKey });
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { CapabilityInstallation } from "@personal-brand/api-client";
|
||||
|
||||
export type CapabilityStatus = CapabilityInstallation["status"];
|
||||
|
||||
export type CapabilitySource = NonNullable<CapabilityInstallation["source"]>;
|
||||
|
||||
export interface CapabilityConfigField {
|
||||
key: string;
|
||||
label: string;
|
||||
input: string;
|
||||
required: boolean;
|
||||
}
|
||||
|
||||
export interface AdminCapability {
|
||||
capabilityKey: string;
|
||||
capabilityVersion: string;
|
||||
status: CapabilityStatus;
|
||||
config: Record<string, unknown>;
|
||||
source: CapabilitySource;
|
||||
updatedAt?: string | null;
|
||||
displayName?: string | undefined;
|
||||
description?: string | undefined;
|
||||
impact?: string | undefined;
|
||||
optional?: boolean | undefined;
|
||||
disablePolicy?: "allowed" | "disabled" | undefined;
|
||||
configFields?: CapabilityConfigField[] | undefined;
|
||||
}
|
||||
|
||||
export interface CapabilityValues {
|
||||
status: CapabilityStatus;
|
||||
config: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function isCapabilitySource(value: unknown): value is CapabilitySource {
|
||||
return value === "brand" || value === "template";
|
||||
}
|
||||
|
||||
export function readAdminCapability(value: CapabilityInstallation): AdminCapability {
|
||||
const { config, source, ...rest } = value;
|
||||
return {
|
||||
...rest,
|
||||
config: config ?? {},
|
||||
source: isCapabilitySource(source) ? source : "template",
|
||||
displayName: readOptionalString(value.displayName),
|
||||
description: readOptionalString(value.description),
|
||||
impact: readOptionalString(value.impact),
|
||||
optional: typeof value.optional === "boolean" ? value.optional : undefined,
|
||||
disablePolicy:
|
||||
value.disablePolicy === "allowed" || value.disablePolicy === "disabled"
|
||||
? value.disablePolicy
|
||||
: undefined,
|
||||
configFields: Array.isArray(value.configFields)
|
||||
? value.configFields.filter(isCapabilityConfigField)
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function readOptionalString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim() ? value : undefined;
|
||||
}
|
||||
|
||||
function isCapabilityConfigField(value: {
|
||||
key: string;
|
||||
label: string;
|
||||
input: string;
|
||||
required: boolean;
|
||||
}): value is CapabilityConfigField {
|
||||
const field = value;
|
||||
return (
|
||||
typeof field.key === "string" &&
|
||||
field.key.length > 0 &&
|
||||
typeof field.label === "string" &&
|
||||
field.label.length > 0 &&
|
||||
(field.input === "text" || field.input === "textarea" || field.input === "switch")
|
||||
);
|
||||
}
|
||||
@@ -147,14 +147,16 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
||||
workspace.data?.installations[0]?.templateKey ??
|
||||
workspace.data?.brand?.templateKey ??
|
||||
brand.data?.templateKey ??
|
||||
"personal";
|
||||
const visuals = (catalog.data?.visuals ?? []).filter((item) =>
|
||||
item.supportedIndustryTemplates.includes(industryKey),
|
||||
catalog.data?.industries[0]?.key ??
|
||||
null;
|
||||
const visuals = (catalog.data?.visuals ?? []).filter(
|
||||
(item) =>
|
||||
typeof industryKey === "string" && item.supportedIndustryTemplates.includes(industryKey),
|
||||
);
|
||||
const visualKey =
|
||||
typeof brand.data?.config?.visualTemplateKey === "string"
|
||||
? brand.data.config.visualTemplateKey
|
||||
: "linjing-editorial";
|
||||
: (visuals[0]?.key ?? null);
|
||||
const currentRelease = releases.data?.find((item) => item.status === "published");
|
||||
const publishedHistory = (releases.data ?? []).filter(
|
||||
(item) => item.status === "published" || item.status === "superseded",
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import { Alert, Button, Form, Input, Modal, Segmented, Select, Typography } from "antd";
|
||||
import type {
|
||||
Offering,
|
||||
RuntimeWorkspace,
|
||||
TemplateAdminField,
|
||||
TemplateAdminSection,
|
||||
} from "@personal-brand/api-client";
|
||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
||||
import { RecordContentFields } from "../../components/RecordContentEditor.js";
|
||||
import { ComponentTemplatePreview } from "../brand/ComponentTemplatePreview.js";
|
||||
import type { PreviewTarget } from "../brand/preview-selection.js";
|
||||
import type { FormInstance } from "antd";
|
||||
import "./ServicesPage.css";
|
||||
|
||||
type OfferingEditorModalProps = {
|
||||
open: boolean;
|
||||
editingOffering: Offering | null;
|
||||
form: FormInstance<Record<string, unknown>>;
|
||||
previewPage: "offerings" | "detail";
|
||||
previewWorkspace: RuntimeWorkspace | undefined;
|
||||
previewTargets: Record<"offerings" | "detail", PreviewTarget[]>;
|
||||
activeTemplateFields: TemplateAdminField[];
|
||||
templateFieldSection: TemplateAdminSection;
|
||||
hasTemplateDetailCopy: boolean;
|
||||
listTarget: PreviewTarget;
|
||||
detailTarget: PreviewTarget | undefined;
|
||||
saving: boolean;
|
||||
onClose: () => void;
|
||||
onPreviewPageChange: (page: "offerings" | "detail") => void;
|
||||
onValuesChange: (values: Record<string, unknown>) => void;
|
||||
onFinish: (values: Record<string, unknown>) => void;
|
||||
onEditInBrand: () => void;
|
||||
};
|
||||
|
||||
export function OfferingEditorModal({
|
||||
open,
|
||||
editingOffering,
|
||||
form,
|
||||
previewPage,
|
||||
previewWorkspace,
|
||||
previewTargets,
|
||||
activeTemplateFields,
|
||||
templateFieldSection,
|
||||
hasTemplateDetailCopy,
|
||||
listTarget,
|
||||
detailTarget,
|
||||
saving,
|
||||
onClose,
|
||||
onPreviewPageChange,
|
||||
onValuesChange,
|
||||
onFinish,
|
||||
onEditInBrand,
|
||||
}: OfferingEditorModalProps) {
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={editingOffering ? "编辑业务提供项" : "新增业务提供项"}
|
||||
width={960}
|
||||
onCancel={onClose}
|
||||
onOk={() => form.submit()}
|
||||
confirmLoading={saving}
|
||||
>
|
||||
<div className="service-offering-editor">
|
||||
{editingOffering && previewWorkspace ? (
|
||||
<div className="service-offering-editor__preview">
|
||||
<Segmented
|
||||
className="service-offering-editor__view"
|
||||
value={previewPage}
|
||||
options={[
|
||||
{ value: "offerings", label: "列表卡片" },
|
||||
{ value: "detail", label: "详情内容" },
|
||||
]}
|
||||
onChange={onPreviewPageChange}
|
||||
/>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
message={previewPage === "offerings" ? "正在核对列表展示" : "正在核对详情展示"}
|
||||
description={
|
||||
previewPage === "offerings"
|
||||
? "右侧「列表展示」字段修改后,会实时反映在当前卡片。"
|
||||
: "右侧「详情展示」字段修改后,会实时反映在当前详情内容。"
|
||||
}
|
||||
/>
|
||||
<ComponentTemplatePreview
|
||||
workspace={previewWorkspace}
|
||||
page={previewPage}
|
||||
offeringId={editingOffering.id}
|
||||
targets={previewTargets[previewPage]}
|
||||
selection={{
|
||||
targetKey: previewPage === "offerings" ? listTarget.key : (detailTarget?.key ?? ""),
|
||||
recordId: editingOffering.id,
|
||||
}}
|
||||
onTargetSelected={() => {}}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<Form
|
||||
className="service-offering-editor__form"
|
||||
form={form}
|
||||
layout="vertical"
|
||||
onValuesChange={(_, allValues) => onValuesChange(allValues)}
|
||||
onFinish={onFinish}
|
||||
>
|
||||
<div className="service-offering-editor__form-scroll">
|
||||
<Typography.Title level={5}>基础信息</Typography.Title>
|
||||
<Form.Item name="kind" label="类型" rules={[{ required: true }]}>
|
||||
<Select
|
||||
options={[
|
||||
{ value: "service", label: "服务" },
|
||||
{ value: "product", label: "定制产品" },
|
||||
{ value: "package", label: "套餐" },
|
||||
{ value: "subscription", label: "订阅" },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="summary" label="一句话说明">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
{!hasTemplateDetailCopy ? (
|
||||
<Form.Item name="description" label="详细介绍">
|
||||
<Input.TextArea rows={5} />
|
||||
</Form.Item>
|
||||
) : null}
|
||||
<Form.Item name="priceText" label="价格展示">
|
||||
<Input placeholder="例如:按现场评估报价 / ¥ 2,800 起" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="coverUrl"
|
||||
label="封面图片地址"
|
||||
help="点击上传,或粘贴服务/产品封面图片地址。"
|
||||
>
|
||||
<ImageUrlField placeholder="粘贴服务或产品封面图片地址" scope="offering" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="sortOrder"
|
||||
label="展示顺序"
|
||||
help="数字越小越靠前,不确定时填写 0。"
|
||||
rules={[{ type: "number", min: 0, max: 9999 }]}
|
||||
>
|
||||
<Input type="number" min={0} max={9999} />
|
||||
</Form.Item>
|
||||
<Form.Item name="isEnabled" label="公开状态">
|
||||
<Select
|
||||
options={[
|
||||
{ value: true, label: "已启用" },
|
||||
{ value: false, label: "已停用" },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
{activeTemplateFields.length ? (
|
||||
<div>
|
||||
<Typography.Title level={5}>
|
||||
{previewPage === "offerings" ? "列表展示字段" : "详情展示字段"}
|
||||
</Typography.Title>
|
||||
<Typography.Paragraph type="secondary">
|
||||
这里只编辑左侧预览对应的字段;它们与小程序页面编辑的是同一份业务数据。
|
||||
</Typography.Paragraph>
|
||||
<RecordContentFields
|
||||
section={{
|
||||
...templateFieldSection,
|
||||
fields: activeTemplateFields,
|
||||
}}
|
||||
sectionKey="offering"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{editingOffering ? (
|
||||
<Button htmlType="button" onClick={onEditInBrand}>
|
||||
在小程序页面编辑
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { Button, Popconfirm, Space, Table, Tag, Typography } from "antd";
|
||||
import type { Offering } from "@personal-brand/api-client";
|
||||
import { MutationError } from "../../components/QueryState.js";
|
||||
import type { useOfferingMutations } from "./use-offering-data.js";
|
||||
|
||||
type OfferingsTableProps = {
|
||||
pageLabel: string;
|
||||
detailSectionTitles: string[];
|
||||
items: Offering[];
|
||||
loading: boolean;
|
||||
saveError: unknown;
|
||||
toggleOffering: ReturnType<typeof useOfferingMutations>["toggleOffering"];
|
||||
deleteOffering: ReturnType<typeof useOfferingMutations>["deleteOffering"];
|
||||
onEdit: (item: Offering) => void;
|
||||
};
|
||||
|
||||
const offeringKindLabels: Record<string, string> = {
|
||||
service: "服务",
|
||||
product: "定制产品",
|
||||
package: "套餐",
|
||||
subscription: "订阅",
|
||||
};
|
||||
|
||||
export function OfferingsTable({
|
||||
pageLabel,
|
||||
detailSectionTitles,
|
||||
items,
|
||||
loading,
|
||||
saveError,
|
||||
toggleOffering,
|
||||
deleteOffering,
|
||||
onEdit,
|
||||
}: OfferingsTableProps) {
|
||||
const columns = [
|
||||
{ title: "名称", dataIndex: "name" },
|
||||
{
|
||||
title: "业务类型",
|
||||
dataIndex: "kind",
|
||||
render: (value: unknown) => <Tag>{offeringKindLabels[String(value)] ?? String(value)}</Tag>,
|
||||
},
|
||||
{ title: "价格", dataIndex: "priceText" },
|
||||
{
|
||||
title: "状态",
|
||||
dataIndex: "isEnabled",
|
||||
render: (value: boolean) => (value ? "已启用" : "已停用"),
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
render: (_: unknown, item: Offering) => (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => onEdit(item)}>
|
||||
编辑详情
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
loading={toggleOffering.isPending && toggleOffering.variables?.id === item.id}
|
||||
onClick={() => toggleOffering.mutate({ id: item.id, isEnabled: !item.isEnabled })}
|
||||
>
|
||||
{item.isEnabled ? "禁用" : "启用"}
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="确认删除这项业务提供项?"
|
||||
description="如果它已经关联咨询表单,系统会阻止删除。"
|
||||
onConfirm={() => deleteOffering.mutate(item.id)}
|
||||
okText="删除"
|
||||
cancelText="取消"
|
||||
>
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
loading={deleteOffering.isPending && deleteOffering.variables === item.id}
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<section aria-label="业务提供项列表">
|
||||
<Space wrap style={{ marginBottom: 16 }}>
|
||||
<Typography.Title level={5} style={{ margin: 0 }}>
|
||||
{pageLabel}中的内容
|
||||
</Typography.Title>
|
||||
<Tag color="blue">已启用的项目会公开展示</Tag>
|
||||
</Space>
|
||||
{detailSectionTitles.length ? (
|
||||
<Typography.Paragraph type="secondary">
|
||||
编辑单项详情时,附加字段将用于:
|
||||
{detailSectionTitles.join("、")}
|
||||
。列表中的名称、说明、价格和封面也会显示在业务展示页。
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
<Table
|
||||
scroll={{ x: 760 }}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
dataSource={items}
|
||||
columns={columns}
|
||||
/>
|
||||
{items.length === 0 && (
|
||||
<Typography.Paragraph type="secondary">
|
||||
还没有公开业务提供项。创建后,小程序服务页会优先读取这些内容。
|
||||
</Typography.Paragraph>
|
||||
)}
|
||||
<MutationError error={saveError} />
|
||||
<MutationError error={toggleOffering.error} />
|
||||
<MutationError error={deleteOffering.error} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
.service-offering-editor {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(320px, 1fr) minmax(340px, 440px);
|
||||
gap: 20px;
|
||||
max-height: 76vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.service-offering-editor__preview {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 72vh;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.service-offering-editor__preview > * {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.service-offering-editor__view {
|
||||
align-self: flex-start;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.service-offering-editor__preview > .component-template-preview-shell {
|
||||
flex: 1 1 0;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.service-offering-editor__preview .component-template-preview {
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.service-offering-editor__form {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding-right: 4px;
|
||||
}
|
||||
|
||||
.service-offering-editor__form-scroll {
|
||||
flex: none;
|
||||
max-height: 66vh;
|
||||
overflow-y: auto;
|
||||
padding: 20px 16px 24px;
|
||||
border-radius: 12px;
|
||||
background: #f8fafc;
|
||||
border: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.service-offering-editor__form-scroll > .ant-typography:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.service-offering-editor__form-scroll .ant-form-item {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.service-offering-editor__form-scroll .ant-typography h5.ant-typography {
|
||||
margin: 28px 0 4px;
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.service-offering-editor__form-scroll > .ant-typography-secondary {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.service-offering-editor__preview .ant-alert {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
@media (max-width: 860px) {
|
||||
.service-offering-editor {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
max-height: none;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.service-offering-editor__preview {
|
||||
height: 560px;
|
||||
}
|
||||
|
||||
.service-offering-editor__form {
|
||||
max-height: none;
|
||||
}
|
||||
}
|
||||
@@ -1,330 +1,136 @@
|
||||
import {
|
||||
Button,
|
||||
Form,
|
||||
Input,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Select,
|
||||
Space,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
message,
|
||||
} from "antd";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Button } from "antd";
|
||||
import type { Offering, TemplateAdminField } from "@personal-brand/api-client";
|
||||
import { useState } from "react";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import { useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
||||
import { TemplateListField } from "../../components/TemplateListField.js";
|
||||
import {
|
||||
applyPresentationValues,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
} from "../brand/presentation-bindings.js";
|
||||
import { MutationError, QueryState } from "../../components/QueryState.js";
|
||||
import { QueryState } from "../../components/QueryState.js";
|
||||
import { OfferingEditorModal } from "./OfferingEditorModal.js";
|
||||
import { OfferingsTable } from "./OfferingsTable.js";
|
||||
import { detailPageLabel, hasTemplateDetailCopy, offeringPageLabel } from "./offering-model.js";
|
||||
import { buildOfferingPreviewWorkspace, previewTargetsByPage } from "./offering-preview.js";
|
||||
import { useOfferingEditor } from "./use-offering-editor.js";
|
||||
import { useOfferingMutations, useOfferingQueries } from "./use-offering-data.js";
|
||||
|
||||
type PreviewPage = "offerings" | "detail";
|
||||
|
||||
export function ServicesPage() {
|
||||
const client = createApiClient();
|
||||
const queryClient = useQueryClient();
|
||||
const [offeringForm] = Form.useForm();
|
||||
const [offeringOpen, setOfferingOpen] = useState(false);
|
||||
const [editingOffering, setEditingOffering] = useState<Offering | null>(null);
|
||||
const offerings = useQuery({
|
||||
queryKey: ["admin-offerings"],
|
||||
queryFn: () => client.listAdminOfferings(),
|
||||
});
|
||||
const workspace = useQuery({
|
||||
queryKey: ["admin-workspace-offering-fields"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
});
|
||||
const templateFields: TemplateAdminField[] = (
|
||||
workspace.data?.templateContent?.admin.sections ?? []
|
||||
)
|
||||
.filter((section) => section.target === "offering")
|
||||
.flatMap((section) =>
|
||||
section.fields.filter((field) => field.binding.startsWith("offering.config.")),
|
||||
);
|
||||
const offeringPageLabel =
|
||||
workspace.data?.templateContent?.navigation.find((item) => item.page === "offerings")?.label ??
|
||||
"业务展示页";
|
||||
const detailPageLabel =
|
||||
workspace.data?.templateContent?.navigation.find((item) => item.page === "detail")?.label ??
|
||||
"详情页";
|
||||
const detailSections = (workspace.data?.templateContent?.admin.sections ?? []).filter(
|
||||
(section) => section.target === "offering" && section.page === "detail",
|
||||
);
|
||||
const hasTemplateDetailCopy = templateFields.some(
|
||||
(field) => field.binding === "offering.config.details.background",
|
||||
);
|
||||
const saveOffering = useMutation({
|
||||
mutationFn: (values: Record<string, unknown>) => {
|
||||
const fields = Object.fromEntries(
|
||||
Object.entries(values).filter(([key]) => key !== "config" && !key.startsWith("offering:")),
|
||||
);
|
||||
const config = applyPresentationValues(
|
||||
editingOffering?.config,
|
||||
[{ key: "offering", fields: templateFields }],
|
||||
values,
|
||||
);
|
||||
const body = { ...fields, config };
|
||||
return editingOffering
|
||||
? client.updateAdminOffering(editingOffering.id, body)
|
||||
: client.createAdminOffering(body as Omit<Offering, "id" | "brandId">);
|
||||
},
|
||||
const navigate = useNavigate();
|
||||
const { offerings, workspace, previewWorkspace, templateFields, retry } = useOfferingQueries();
|
||||
const editor = useOfferingEditor(templateFields);
|
||||
const mutations = useOfferingMutations({
|
||||
editingOffering: editor.editingOffering,
|
||||
templateFields,
|
||||
onSuccess: () => {
|
||||
message.success("业务提供项已保存");
|
||||
setOfferingOpen(false);
|
||||
setEditingOffering(null);
|
||||
offeringForm.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
||||
editor.closeOffering();
|
||||
editor.offeringForm.resetFields();
|
||||
},
|
||||
});
|
||||
const deleteOffering = useMutation({
|
||||
mutationFn: (id: string) => client.deleteAdminOffering(id),
|
||||
onSuccess: () => {
|
||||
message.success("业务提供项已删除");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
||||
},
|
||||
});
|
||||
const toggleOffering = useMutation({
|
||||
mutationFn: ({ id, isEnabled }: { id: string; isEnabled: boolean }) =>
|
||||
client.updateAdminOffering(id, { isEnabled }),
|
||||
onSuccess: () => {
|
||||
message.success("业务提供项状态已更新");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
||||
},
|
||||
});
|
||||
const beginOffering = (item?: Offering) => {
|
||||
setEditingOffering(item ?? null);
|
||||
setOfferingOpen(true);
|
||||
offeringForm.setFieldsValue(
|
||||
item
|
||||
? {
|
||||
kind: item.kind,
|
||||
name: item.name,
|
||||
summary: item.summary ?? "",
|
||||
description: item.description ?? "",
|
||||
priceText: item.priceText ?? "",
|
||||
coverUrl: item.coverUrl ?? "",
|
||||
sortOrder: item.sortOrder,
|
||||
isEnabled: item.isEnabled,
|
||||
...Object.fromEntries(
|
||||
templateFields.map((field) => [
|
||||
presentationFieldName("offering", field.key),
|
||||
readPresentationValue(item.config, field.binding, field),
|
||||
]),
|
||||
),
|
||||
}
|
||||
: {
|
||||
kind: "service",
|
||||
isEnabled: true,
|
||||
sortOrder: 0,
|
||||
...Object.fromEntries(
|
||||
templateFields.map((field) => [
|
||||
presentationFieldName("offering", field.key),
|
||||
field.input === "list" ? [] : undefined,
|
||||
]),
|
||||
),
|
||||
},
|
||||
);
|
||||
|
||||
const sections = workspace.data?.templateContent?.admin.sections ?? [];
|
||||
const previewTargets = useMemo(() => previewTargetsByPage(sections), [sections]);
|
||||
const listTarget = previewTargets.offerings.find((target) =>
|
||||
templateFields.some((field) => field.previewTarget === target.key),
|
||||
) ?? {
|
||||
key: "offering.list.item",
|
||||
label: "业务卡片",
|
||||
page: "offerings",
|
||||
source: "offering",
|
||||
};
|
||||
const detailTarget = previewTargets.detail.find((target) => target.source === "offering");
|
||||
const listFields = useMemo(
|
||||
() => templateFields.filter((field) => field.previewTarget === listTarget.key),
|
||||
[templateFields, listTarget.key],
|
||||
);
|
||||
const detailFields = useMemo(
|
||||
() => templateFields.filter((field) => field.previewTarget === detailTarget?.key),
|
||||
[templateFields, detailTarget?.key],
|
||||
);
|
||||
const otherFields = useMemo(
|
||||
() =>
|
||||
templateFields.filter(
|
||||
(field) => !listFields.includes(field) && !detailFields.includes(field),
|
||||
),
|
||||
[templateFields, listFields, detailFields],
|
||||
);
|
||||
const activeTemplateFields: TemplateAdminField[] =
|
||||
editor.previewPage === "offerings"
|
||||
? [...listFields, ...otherFields.filter((field) => field.page === "offerings")]
|
||||
: [...detailFields, ...otherFields.filter((field) => field.page === "detail")];
|
||||
const previewWorkspaceDraft = useMemo(() => {
|
||||
if (!previewWorkspace.data || !editor.editingOffering) return undefined;
|
||||
return buildOfferingPreviewWorkspace({
|
||||
previewWorkspace: previewWorkspace.data,
|
||||
editingOffering: editor.editingOffering,
|
||||
templateFields,
|
||||
formValues: editor.formValues,
|
||||
});
|
||||
}, [
|
||||
previewWorkspace.data,
|
||||
editor.editingOffering,
|
||||
templateFields,
|
||||
editor.formValues,
|
||||
editor.offeringDraftVersion,
|
||||
]);
|
||||
|
||||
const navigateToBrand = () => {
|
||||
if (!editor.editingOffering) return;
|
||||
void navigate("/admin/brand", {
|
||||
state: {
|
||||
targetKey:
|
||||
editor.previewPage === "offerings"
|
||||
? listTarget.key
|
||||
: (detailTarget?.key ?? listTarget.key),
|
||||
recordId: editor.editingOffering.id,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<QueryState
|
||||
loading={offerings.isLoading || workspace.isLoading}
|
||||
error={offerings.error || workspace.error}
|
||||
onRetry={() => {
|
||||
void offerings.refetch();
|
||||
void workspace.refetch();
|
||||
}}
|
||||
onRetry={retry}
|
||||
>
|
||||
<AdminPageHeader
|
||||
title="小程序内容:业务展示与详情"
|
||||
description={`在「${offeringPageLabel}」管理访客能选择的服务、产品或案例;每项内容的补充资料会显示在对应的「${detailPageLabel}」。`}
|
||||
description={`在「${offeringPageLabel(workspace.data?.templateContent ?? undefined)}」管理访客能选择的服务、产品或案例;每项内容的补充资料会显示在对应的「${detailPageLabel(workspace.data?.templateContent ?? undefined)}」。`}
|
||||
extra={
|
||||
<Button type="primary" onClick={() => beginOffering()}>
|
||||
<Button type="primary" onClick={() => editor.beginOffering()}>
|
||||
新增业务提供项
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<section aria-label="业务提供项列表">
|
||||
<Space wrap style={{ marginBottom: 16 }}>
|
||||
<Typography.Title level={5} style={{ margin: 0 }}>
|
||||
{offeringPageLabel}中的内容
|
||||
</Typography.Title>
|
||||
<Tag color="blue">已启用的项目会公开展示</Tag>
|
||||
</Space>
|
||||
{detailSections.length ? (
|
||||
<Typography.Paragraph type="secondary">
|
||||
编辑单项详情时,附加字段将用于:
|
||||
{detailSections.map((section) => section.title).join("、")}
|
||||
。列表中的名称、说明、价格和封面也会显示在业务展示页。
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
<Table
|
||||
scroll={{ x: 760 }}
|
||||
rowKey="id"
|
||||
loading={offerings.isLoading}
|
||||
dataSource={offerings.data ?? []}
|
||||
columns={[
|
||||
{ title: "名称", dataIndex: "name" },
|
||||
{
|
||||
title: "业务类型",
|
||||
dataIndex: "kind",
|
||||
render: (value) => (
|
||||
<Tag>
|
||||
{(
|
||||
{
|
||||
service: "服务",
|
||||
product: "定制产品",
|
||||
package: "套餐",
|
||||
subscription: "订阅",
|
||||
} as Record<string, string>
|
||||
)[String(value)] ?? String(value)}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{ title: "价格", dataIndex: "priceText" },
|
||||
{
|
||||
title: "状态",
|
||||
dataIndex: "isEnabled",
|
||||
render: (value) => (value ? "已启用" : "已停用"),
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
render: (_: unknown, item: Offering) => (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => beginOffering(item)}>
|
||||
编辑详情
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
loading={toggleOffering.isPending && toggleOffering.variables?.id === item.id}
|
||||
onClick={() =>
|
||||
toggleOffering.mutate({ id: item.id, isEnabled: !item.isEnabled })
|
||||
}
|
||||
>
|
||||
{item.isEnabled ? "禁用" : "启用"}
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="确认删除这项业务提供项?"
|
||||
description="如果它已经关联咨询表单,系统会阻止删除。"
|
||||
onConfirm={() => deleteOffering.mutate(item.id)}
|
||||
okText="删除"
|
||||
cancelText="取消"
|
||||
>
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
loading={deleteOffering.isPending && deleteOffering.variables === item.id}
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
{offerings.data?.length === 0 && (
|
||||
<Typography.Paragraph type="secondary">
|
||||
还没有公开业务提供项。创建后,小程序服务页会优先读取这些内容。
|
||||
</Typography.Paragraph>
|
||||
)}
|
||||
<MutationError error={saveOffering.error} />
|
||||
<MutationError error={toggleOffering.error} />
|
||||
<MutationError error={deleteOffering.error} />
|
||||
</section>
|
||||
<Modal
|
||||
open={offeringOpen}
|
||||
title={editingOffering ? "编辑业务提供项" : "新增业务提供项"}
|
||||
onCancel={() => {
|
||||
setOfferingOpen(false);
|
||||
setEditingOffering(null);
|
||||
offeringForm.resetFields();
|
||||
}}
|
||||
onOk={() => offeringForm.submit()}
|
||||
confirmLoading={saveOffering.isPending}
|
||||
>
|
||||
<Form
|
||||
form={offeringForm}
|
||||
layout="vertical"
|
||||
onFinish={(values) => saveOffering.mutate(values as Record<string, unknown>)}
|
||||
>
|
||||
<Form.Item name="kind" label="类型" rules={[{ required: true }]}>
|
||||
<Select
|
||||
options={[
|
||||
{ value: "service", label: "服务" },
|
||||
{ value: "product", label: "定制产品" },
|
||||
{ value: "package", label: "套餐" },
|
||||
{ value: "subscription", label: "订阅" },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="summary" label="一句话说明">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
{!hasTemplateDetailCopy ? (
|
||||
<Form.Item name="description" label="详细介绍">
|
||||
<Input.TextArea rows={5} />
|
||||
</Form.Item>
|
||||
) : null}
|
||||
<Form.Item name="priceText" label="价格展示">
|
||||
<Input placeholder="例如:按现场评估报价 / ¥ 2,800 起" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="coverUrl"
|
||||
label="封面图片地址"
|
||||
help="填写图片地址;图片上传能力将在后续媒体管理中提供。"
|
||||
>
|
||||
<ImageUrlField placeholder="粘贴服务或产品封面图片地址" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="sortOrder"
|
||||
label="展示顺序"
|
||||
help="数字越小越靠前,不确定时填写 0。"
|
||||
rules={[{ type: "number", min: 0, max: 9999 }]}
|
||||
>
|
||||
<Input type="number" min={0} max={9999} />
|
||||
</Form.Item>
|
||||
<Form.Item name="isEnabled" label="公开状态">
|
||||
<Select
|
||||
options={[
|
||||
{ value: true, label: "已启用" },
|
||||
{ value: false, label: "已停用" },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
{templateFields.map((field) =>
|
||||
field.input === "list" ? (
|
||||
<TemplateListField
|
||||
key={field.key}
|
||||
field={field}
|
||||
name={presentationFieldName("offering", field.key)}
|
||||
/>
|
||||
) : (
|
||||
<Form.Item
|
||||
key={field.key}
|
||||
name={presentationFieldName("offering", field.key)}
|
||||
label={field.label}
|
||||
help={field.help}
|
||||
>
|
||||
{field.input === "textarea" ? (
|
||||
<Input.TextArea rows={3} />
|
||||
) : field.input === "image" ? (
|
||||
<ImageUrlField />
|
||||
) : (
|
||||
<Input />
|
||||
)}
|
||||
</Form.Item>
|
||||
),
|
||||
)}
|
||||
</Form>
|
||||
</Modal>
|
||||
<OfferingsTable
|
||||
pageLabel={offeringPageLabel(workspace.data?.templateContent ?? undefined)}
|
||||
detailSectionTitles={sections
|
||||
.filter((section) => section.target === "offering" && section.page === "detail")
|
||||
.map((section) => section.title)}
|
||||
items={offerings.data ?? []}
|
||||
loading={offerings.isLoading}
|
||||
saveError={mutations.saveOffering.error}
|
||||
toggleOffering={mutations.toggleOffering}
|
||||
deleteOffering={mutations.deleteOffering}
|
||||
onEdit={(item: Offering) => editor.beginOffering(item)}
|
||||
/>
|
||||
<OfferingEditorModal
|
||||
open={editor.offeringOpen}
|
||||
editingOffering={editor.editingOffering}
|
||||
form={editor.offeringForm}
|
||||
previewPage={editor.previewPage}
|
||||
previewWorkspace={previewWorkspaceDraft}
|
||||
previewTargets={previewTargets}
|
||||
activeTemplateFields={activeTemplateFields}
|
||||
templateFieldSection={editor.templateFieldSection}
|
||||
hasTemplateDetailCopy={hasTemplateDetailCopy(templateFields)}
|
||||
listTarget={listTarget}
|
||||
detailTarget={detailTarget}
|
||||
saving={mutations.saveOffering.isPending}
|
||||
onClose={editor.closeOffering}
|
||||
onPreviewPageChange={(page: PreviewPage) => editor.setPreviewPage(page)}
|
||||
onValuesChange={(values) => editor.handleValuesChange(null, values)}
|
||||
onFinish={(values) => mutations.saveOffering.mutate(values)}
|
||||
onEditInBrand={navigateToBrand}
|
||||
/>
|
||||
</QueryState>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type {
|
||||
AdminTemplateContent,
|
||||
Offering,
|
||||
TemplateAdminField,
|
||||
} from "@personal-brand/api-client";
|
||||
import {
|
||||
applyPresentationValues,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
} from "../brand/presentation-bindings.js";
|
||||
|
||||
export type OfferingFormValues = Record<string, unknown>;
|
||||
|
||||
export function offeringTemplateFields(
|
||||
sections: AdminTemplateContent["admin"]["sections"],
|
||||
): TemplateAdminField[] {
|
||||
return sections
|
||||
.filter((section) => section.target === "offering")
|
||||
.flatMap((section) =>
|
||||
section.fields.filter((field) => field.binding.startsWith("offering.config.")),
|
||||
);
|
||||
}
|
||||
|
||||
export function offeringDefaultFormValues(
|
||||
templateFields: TemplateAdminField[],
|
||||
): OfferingFormValues {
|
||||
return {
|
||||
kind: "service",
|
||||
isEnabled: true,
|
||||
sortOrder: 0,
|
||||
...Object.fromEntries(
|
||||
templateFields.map((field) => [
|
||||
presentationFieldName("offering", field.key),
|
||||
field.input === "list" ? [] : undefined,
|
||||
]),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function offeringEditFormValues(
|
||||
item: Offering,
|
||||
templateFields: TemplateAdminField[],
|
||||
): OfferingFormValues {
|
||||
return {
|
||||
kind: item.kind,
|
||||
name: item.name,
|
||||
summary: item.summary ?? "",
|
||||
description: item.description ?? "",
|
||||
priceText: item.priceText ?? "",
|
||||
coverUrl: item.coverUrl ?? "",
|
||||
sortOrder: item.sortOrder,
|
||||
isEnabled: item.isEnabled,
|
||||
...Object.fromEntries(
|
||||
templateFields.map((field) => {
|
||||
const value = readPresentationValue(item.config, field.binding, field);
|
||||
return [
|
||||
presentationFieldName("offering", field.key),
|
||||
value === undefined || value === null || value === ""
|
||||
? field.input === "select"
|
||||
? field.options?.[0]?.value
|
||||
: field.input === "list"
|
||||
? []
|
||||
: undefined
|
||||
: value,
|
||||
];
|
||||
}),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildOfferingRequestBody(
|
||||
values: OfferingFormValues,
|
||||
editingOffering: Offering | null,
|
||||
templateFields: TemplateAdminField[],
|
||||
): Record<string, unknown> {
|
||||
const fields = Object.fromEntries(
|
||||
Object.entries(values).filter(([key]) => key !== "config" && !key.startsWith("offering:")),
|
||||
);
|
||||
return {
|
||||
...fields,
|
||||
config: applyPresentationValues(
|
||||
editingOffering?.config,
|
||||
[{ key: "offering", fields: templateFields }],
|
||||
values,
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { AdminTemplateContent, TemplateAdminField } from "@personal-brand/api-client";
|
||||
|
||||
export function offeringPageLabel(templateContent?: AdminTemplateContent): string {
|
||||
return (
|
||||
templateContent?.navigation.find((item) => item.page === "offerings")?.label ?? "业务展示页"
|
||||
);
|
||||
}
|
||||
|
||||
export function detailPageLabel(templateContent?: AdminTemplateContent): string {
|
||||
return templateContent?.navigation.find((item) => item.page === "detail")?.label ?? "详情页";
|
||||
}
|
||||
|
||||
export function hasTemplateDetailCopy(templateFields: TemplateAdminField[]): boolean {
|
||||
return templateFields.some((field) => field.binding === "offering.config.details.background");
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import type {
|
||||
AdminTemplateContent,
|
||||
Offering,
|
||||
RuntimeWorkspace,
|
||||
TemplateAdminField,
|
||||
} from "@personal-brand/api-client";
|
||||
import type { PreviewTarget } from "../brand/preview-selection.js";
|
||||
import { applyPresentationValues } from "../brand/presentation-bindings.js";
|
||||
|
||||
export function previewTargetsByPage(
|
||||
sections: AdminTemplateContent["admin"]["sections"],
|
||||
): Record<"offerings" | "detail", PreviewTarget[]> {
|
||||
const result: Record<"offerings" | "detail", PreviewTarget[]> = {
|
||||
offerings: [],
|
||||
detail: [],
|
||||
};
|
||||
for (const page of ["offerings", "detail"] as const) {
|
||||
result[page] = sections
|
||||
.filter((section) => section.page === page)
|
||||
.flatMap((section) =>
|
||||
(section.previewTargets ?? []).map((target) => ({
|
||||
...target,
|
||||
page: section.page,
|
||||
source: section.fields.some(
|
||||
(field) => field.binding.startsWith("offering.") && field.previewTarget === target.key,
|
||||
)
|
||||
? "offering"
|
||||
: section.target,
|
||||
})),
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function buildOfferingPreviewWorkspace(options: {
|
||||
previewWorkspace: RuntimeWorkspace;
|
||||
editingOffering: Offering;
|
||||
templateFields: TemplateAdminField[];
|
||||
formValues: Record<string, unknown>;
|
||||
}): RuntimeWorkspace {
|
||||
const { previewWorkspace, editingOffering, templateFields, formValues } = options;
|
||||
const config = applyPresentationValues(
|
||||
editingOffering.config,
|
||||
[{ key: "offering", fields: templateFields }],
|
||||
formValues,
|
||||
);
|
||||
const offeringValues = {
|
||||
name: formValues.name,
|
||||
summary: formValues.summary,
|
||||
description: formValues.description,
|
||||
priceText: formValues.priceText,
|
||||
coverUrl: formValues.coverUrl,
|
||||
};
|
||||
return {
|
||||
...previewWorkspace,
|
||||
offerings: previewWorkspace.offerings.map((item) =>
|
||||
item.id === editingOffering.id
|
||||
? {
|
||||
...item,
|
||||
name:
|
||||
typeof offeringValues.name === "string" && offeringValues.name.trim()
|
||||
? offeringValues.name
|
||||
: item.name,
|
||||
summary:
|
||||
typeof offeringValues.summary === "string" ? offeringValues.summary : item.summary,
|
||||
priceText:
|
||||
typeof offeringValues.priceText === "string"
|
||||
? offeringValues.priceText
|
||||
: item.priceText,
|
||||
coverUrl:
|
||||
typeof offeringValues.coverUrl === "string" && offeringValues.coverUrl.trim()
|
||||
? offeringValues.coverUrl
|
||||
: item.coverUrl,
|
||||
config,
|
||||
presentation: {
|
||||
...item.presentation,
|
||||
...config,
|
||||
...(config.presentation && typeof config.presentation === "object"
|
||||
? (config.presentation as Record<string, unknown>)
|
||||
: {}),
|
||||
...(typeof config.area === "string" ? { area: config.area } : {}),
|
||||
...(typeof config.series === "string" ? { series: config.series } : {}),
|
||||
...(typeof config.spaceType === "string" ? { spaceType: config.spaceType } : {}),
|
||||
heroImage:
|
||||
typeof config.detailHero === "string"
|
||||
? config.detailHero
|
||||
: typeof offeringValues.coverUrl === "string" && offeringValues.coverUrl.trim()
|
||||
? offeringValues.coverUrl
|
||||
: (item.coverUrl ?? null),
|
||||
details: {
|
||||
...item.presentation.details,
|
||||
...(config.details && typeof config.details === "object"
|
||||
? {
|
||||
...item.presentation.details,
|
||||
...(config.details as Record<string, unknown>),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
}
|
||||
: item,
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { Offering } from "@personal-brand/api-client";
|
||||
import { message } from "antd";
|
||||
import { useMemo } from "react";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import {
|
||||
buildOfferingRequestBody,
|
||||
offeringTemplateFields,
|
||||
type OfferingFormValues,
|
||||
} from "./offering-form.js";
|
||||
|
||||
export function useOfferingQueries() {
|
||||
const client = createApiClient();
|
||||
const offerings = useQuery({
|
||||
queryKey: ["admin-offerings"],
|
||||
queryFn: () => client.listAdminOfferings(),
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
const workspace = useQuery({
|
||||
queryKey: ["admin-workspace-offering-fields"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
});
|
||||
const previewWorkspace = useQuery({
|
||||
queryKey: ["admin-preview-workspace-services"],
|
||||
queryFn: () => client.getAdminPreviewWorkspace(),
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
const templateFields = useMemo(
|
||||
() => offeringTemplateFields(workspace.data?.templateContent?.admin.sections ?? []),
|
||||
[workspace.data?.templateContent?.admin.sections],
|
||||
);
|
||||
return {
|
||||
offerings,
|
||||
workspace,
|
||||
previewWorkspace,
|
||||
templateFields,
|
||||
retry: () => {
|
||||
void offerings.refetch();
|
||||
void workspace.refetch();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function useOfferingMutations(options: {
|
||||
editingOffering: Offering | null;
|
||||
templateFields: ReturnType<typeof offeringTemplateFields>;
|
||||
onSuccess: () => void;
|
||||
}) {
|
||||
const client = createApiClient();
|
||||
const queryClient = useQueryClient();
|
||||
const invalidateAfterSave = () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace-offering-fields"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace-services"] });
|
||||
};
|
||||
const saveOffering = useMutation({
|
||||
mutationFn: (values: OfferingFormValues) =>
|
||||
options.editingOffering
|
||||
? client.updateAdminOffering(
|
||||
options.editingOffering.id,
|
||||
buildOfferingRequestBody(values, options.editingOffering, options.templateFields),
|
||||
)
|
||||
: client.createAdminOffering(
|
||||
buildOfferingRequestBody(values, null, options.templateFields) as Omit<
|
||||
Offering,
|
||||
"id" | "brandId"
|
||||
>,
|
||||
),
|
||||
onSuccess: () => {
|
||||
message.success("业务提供项已保存");
|
||||
invalidateAfterSave();
|
||||
options.onSuccess();
|
||||
},
|
||||
});
|
||||
const deleteOffering = useMutation({
|
||||
mutationFn: (id: string) => client.deleteAdminOffering(id),
|
||||
onSuccess: () => {
|
||||
message.success("业务提供项已删除");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
||||
},
|
||||
});
|
||||
const toggleOffering = useMutation({
|
||||
mutationFn: ({ id, isEnabled }: { id: string; isEnabled: boolean }) =>
|
||||
client.updateAdminOffering(id, { isEnabled }),
|
||||
onSuccess: () => {
|
||||
message.success("业务提供项状态已更新");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
||||
},
|
||||
});
|
||||
return { saveOffering, deleteOffering, toggleOffering };
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Form } from "antd";
|
||||
import { useMemo, useState } from "react";
|
||||
import type {
|
||||
Offering,
|
||||
TemplateAdminField,
|
||||
TemplateAdminSection,
|
||||
} from "@personal-brand/api-client";
|
||||
import { offeringDefaultFormValues, offeringEditFormValues } from "./offering-form.js";
|
||||
|
||||
export type OfferingPreviewPage = "offerings" | "detail";
|
||||
|
||||
export function useOfferingEditor(templateFields: TemplateAdminField[]) {
|
||||
const [offeringForm] = Form.useForm();
|
||||
const [offeringOpen, setOfferingOpen] = useState(false);
|
||||
const [editingOffering, setEditingOffering] = useState<Offering | null>(null);
|
||||
const [offeringDraftVersion, setOfferingDraftVersion] = useState(0);
|
||||
const [previewPage, setPreviewPage] = useState<OfferingPreviewPage>("detail");
|
||||
const [formValues, setFormValues] = useState<Record<string, unknown>>({});
|
||||
|
||||
const templateFieldSection = useMemo<TemplateAdminSection>(
|
||||
() => ({
|
||||
key: "offering",
|
||||
title: "模板内容",
|
||||
description: "",
|
||||
page: "detail",
|
||||
target: "offering",
|
||||
fields: templateFields,
|
||||
}),
|
||||
[templateFields],
|
||||
);
|
||||
|
||||
const beginOffering = (item?: Offering) => {
|
||||
setEditingOffering(item ?? null);
|
||||
setPreviewPage("detail");
|
||||
setOfferingOpen(true);
|
||||
offeringForm.setFieldsValue(
|
||||
item
|
||||
? offeringEditFormValues(item, templateFields)
|
||||
: offeringDefaultFormValues(templateFields),
|
||||
);
|
||||
setFormValues(offeringForm.getFieldsValue(true) as Record<string, unknown>);
|
||||
};
|
||||
|
||||
const closeOffering = () => {
|
||||
setOfferingOpen(false);
|
||||
setEditingOffering(null);
|
||||
offeringForm.resetFields();
|
||||
};
|
||||
|
||||
const handleValuesChange = (_: unknown, allValues: Record<string, unknown>) => {
|
||||
setFormValues(allValues);
|
||||
setOfferingDraftVersion((version) => version + 1);
|
||||
};
|
||||
|
||||
return {
|
||||
offeringForm,
|
||||
offeringOpen,
|
||||
editingOffering,
|
||||
previewPage,
|
||||
templateFieldSection,
|
||||
formValues,
|
||||
offeringDraftVersion,
|
||||
setPreviewPage,
|
||||
beginOffering,
|
||||
closeOffering,
|
||||
handleValuesChange,
|
||||
};
|
||||
}
|
||||
@@ -169,14 +169,14 @@ export function MembersPage() {
|
||||
label="登录账号"
|
||||
rules={[{ required: true, message: "请输入登录账号" }]}
|
||||
>
|
||||
<Input placeholder="例如:linran" />
|
||||
<Input placeholder="例如:brand-owner" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="displayName"
|
||||
label="成员姓名"
|
||||
rules={[{ required: true, message: "请输入成员姓名" }]}
|
||||
>
|
||||
<Input placeholder="例如:林然" />
|
||||
<Input placeholder="例如:品牌主理人" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="password"
|
||||
|
||||
@@ -1,185 +1,51 @@
|
||||
import {
|
||||
Button,
|
||||
Divider,
|
||||
Form,
|
||||
Input,
|
||||
List,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Select,
|
||||
Space,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
message,
|
||||
} from "antd";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { isTrustContentComplete } from "@personal-brand/api-client";
|
||||
import type {
|
||||
TemplateAdminField,
|
||||
TrustContent,
|
||||
TrustContentInput,
|
||||
} from "@personal-brand/api-client";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import { Button, Divider, Form, Typography } from "antd";
|
||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
||||
import { TemplateListField } from "../../components/TemplateListField.js";
|
||||
import { MutationError, QueryState } from "../../components/QueryState.js";
|
||||
|
||||
const types = [
|
||||
{
|
||||
value: "schedule",
|
||||
label: "时间与服务安排",
|
||||
help: "说明你通常什么时候提供服务、接受预约或处理订单。多项内容可以分行填写。",
|
||||
},
|
||||
{
|
||||
value: "coverage",
|
||||
label: "服务范围与方式",
|
||||
help: "说明服务地点、覆盖范围、适用对象或承接边界。多项内容可以分行填写。",
|
||||
},
|
||||
{
|
||||
value: "process",
|
||||
label: "合作流程",
|
||||
help: "说明客户从提出需求到完成合作会经历哪些步骤,每行写一步。",
|
||||
},
|
||||
{
|
||||
value: "credential",
|
||||
label: "资质与专业证明",
|
||||
help: "说明资质、经验、制作标准或让客户放心的专业依据。",
|
||||
},
|
||||
{
|
||||
value: "case",
|
||||
label: "案例与客户反馈",
|
||||
help: "写代表性案例、服务结果或客户评价,多条内容可以分行填写。",
|
||||
},
|
||||
{
|
||||
value: "promise",
|
||||
label: "服务承诺与响应说明",
|
||||
help: "说明回复时间、交付承诺、售后方式或合作预期。",
|
||||
},
|
||||
];
|
||||
type TrustTypeOption = {
|
||||
type: string;
|
||||
label: string;
|
||||
adminFields: {
|
||||
title: string;
|
||||
summary: string;
|
||||
content: string;
|
||||
summaryHelp?: string;
|
||||
summaryPlaceholder?: string;
|
||||
};
|
||||
pages?: string[];
|
||||
help?: string;
|
||||
placeholder?: string;
|
||||
required?: boolean;
|
||||
configFields?: TemplateAdminField[];
|
||||
hideStandardFields?: Array<"summary" | "content">;
|
||||
maxPublishedItems?: number;
|
||||
};
|
||||
const fallbackTypes: TrustTypeOption[] = types.map(({ value, label, help }) => ({
|
||||
type: value,
|
||||
label,
|
||||
adminFields: { title: "标题", summary: "摘要", content: "详细内容" },
|
||||
help,
|
||||
}));
|
||||
import { QueryState } from "../../components/QueryState.js";
|
||||
import { TrustContentEditorModal } from "./components/TrustContentEditorModal.js";
|
||||
import { TrustContentTable } from "./components/TrustContentTable.js";
|
||||
import { TrustRequirementsList } from "./components/TrustRequirementsList.js";
|
||||
import type { TrustTypeOption } from "./domain/trust-content-domain.js";
|
||||
import {
|
||||
createTrustPageLabelResolver,
|
||||
groupTrustContentByType,
|
||||
selectTrustTypeOptions,
|
||||
} from "./domain/trust-content-domain.js";
|
||||
import { useTrustContentEditor } from "./hooks/useTrustContentEditor.js";
|
||||
import { useTrustContentQueries } from "./hooks/useTrustContentQueries.js";
|
||||
|
||||
export function TrustContentPage() {
|
||||
const client = createApiClient();
|
||||
const queryClient = useQueryClient();
|
||||
const [editing, setEditing] = useState<TrustContent | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [form] = Form.useForm<TrustContentInput>();
|
||||
const [searchParams] = useSearchParams();
|
||||
const selectedType = Form.useWatch("type", form);
|
||||
const query = useQuery({
|
||||
queryKey: ["trust-content"],
|
||||
queryFn: () => client.listAdminTrustContent(),
|
||||
const { query, workspace } = useTrustContentQueries();
|
||||
const availableTypes = selectTrustTypeOptions(workspace.data?.templateContent?.trustContentTypes);
|
||||
const pageLabel = createTrustPageLabelResolver(workspace.data?.templateContent?.navigation);
|
||||
const contentByType = groupTrustContentByType(query.data ?? []);
|
||||
const firstMissingRequiredType =
|
||||
availableTypes.find((item) => item.required && !contentByType.has(item.type))?.type ??
|
||||
availableTypes[0]?.type ??
|
||||
"credential";
|
||||
const {
|
||||
begin,
|
||||
closeEditor,
|
||||
editing,
|
||||
form: editorForm,
|
||||
open,
|
||||
remove,
|
||||
save,
|
||||
} = useTrustContentEditor({
|
||||
availableTypes,
|
||||
contentByType,
|
||||
firstMissingRequiredType,
|
||||
});
|
||||
const workspace = useQuery({
|
||||
queryKey: ["admin-workspace-trust-types"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
});
|
||||
const availableTypes: TrustTypeOption[] = workspace.data?.templateContent?.trustContentTypes
|
||||
?.length
|
||||
? workspace.data.templateContent.trustContentTypes
|
||||
: fallbackTypes;
|
||||
const pageLabel = (page: string) =>
|
||||
workspace.data?.templateContent?.navigation.find((item) => item.page === page)?.label ??
|
||||
(
|
||||
{ home: "首页", offerings: "业务展示页", detail: "详情页", profile: "主理人页" } as Record<
|
||||
string,
|
||||
string
|
||||
>
|
||||
)[page] ??
|
||||
page;
|
||||
const selectedType = Form.useWatch("type", editorForm);
|
||||
const selectedTypeMeta: TrustTypeOption | undefined = availableTypes.find(
|
||||
(item) => item.type === selectedType,
|
||||
);
|
||||
const trustPageLabels = [
|
||||
...new Set(availableTypes.flatMap((item) => item.pages ?? []).map(pageLabel)),
|
||||
];
|
||||
const trustPlacement = trustPageLabels.length
|
||||
? `小程序的${trustPageLabels.join("、")}中`
|
||||
: "小程序对应的信任展示区域中";
|
||||
const selectedTypeMeta = availableTypes.find((item) => item.type === selectedType);
|
||||
const contentByType = new Map<string, TrustContent>();
|
||||
for (const item of query.data ?? []) {
|
||||
const current = contentByType.get(item.type);
|
||||
const hasConfig = Object.keys(item.config ?? {}).length > 0;
|
||||
const currentHasConfig = Object.keys(current?.config ?? {}).length > 0;
|
||||
if (
|
||||
!current ||
|
||||
(item.isPublished && !current.isPublished) ||
|
||||
(item.isPublished === current.isPublished && hasConfig && !currentHasConfig)
|
||||
) {
|
||||
contentByType.set(item.type, item);
|
||||
}
|
||||
}
|
||||
const firstMissingRequiredType =
|
||||
availableTypes.find((item) => item.required && !contentByType.has(item.type))?.type ??
|
||||
availableTypes[0]?.type ??
|
||||
"credential";
|
||||
const requestedType = searchParams.get("type");
|
||||
const save = useMutation({
|
||||
mutationFn: (values: TrustContentInput) =>
|
||||
editing
|
||||
? client.updateAdminTrustContent(editing.id, values)
|
||||
: client.createAdminTrustContent(values),
|
||||
onSuccess: () => {
|
||||
message.success("品牌内容已保存为草稿,发布后小程序才会更新");
|
||||
setOpen(false);
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
|
||||
},
|
||||
});
|
||||
const remove = useMutation({
|
||||
mutationFn: (id: string) => client.deleteAdminTrustContent(id),
|
||||
onSuccess: () => {
|
||||
message.success("品牌内容已删除");
|
||||
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
|
||||
},
|
||||
});
|
||||
const begin = (item?: TrustContent, type?: string) => {
|
||||
setEditing(item ?? null);
|
||||
setOpen(true);
|
||||
form.setFieldsValue(
|
||||
item
|
||||
? {
|
||||
type: item.type,
|
||||
title: item.title,
|
||||
...(item.summary ? { summary: item.summary } : {}),
|
||||
content: item.content,
|
||||
config: item.config ?? {},
|
||||
...(item.coverUrl ? { coverUrl: item.coverUrl } : {}),
|
||||
isPublished: item.isPublished,
|
||||
}
|
||||
: { type: type ?? firstMissingRequiredType, isPublished: false, config: {} },
|
||||
);
|
||||
};
|
||||
useEffect(() => {
|
||||
if (!requestedType || !availableTypes.some((item) => item.type === requestedType)) return;
|
||||
begin(contentByType.get(requestedType), requestedType);
|
||||
}, [requestedType, availableTypes.length]);
|
||||
|
||||
return (
|
||||
<QueryState
|
||||
loading={query.isLoading || workspace.isLoading}
|
||||
@@ -202,213 +68,34 @@ export function TrustContentPage() {
|
||||
<Typography.Paragraph type="secondary">
|
||||
标记为“发布必填”的项目需要填写完整后,才能发布小程序。
|
||||
</Typography.Paragraph>
|
||||
<List
|
||||
size="small"
|
||||
dataSource={availableTypes}
|
||||
renderItem={(item) => {
|
||||
const content = contentByType.get(item.type);
|
||||
const publishedCount = (query.data ?? []).filter(
|
||||
(record) => record.type === item.type && record.isPublished,
|
||||
).length;
|
||||
const tooMany =
|
||||
item.maxPublishedItems !== undefined && publishedCount > item.maxPublishedItems;
|
||||
const complete = Boolean(content && isTrustContentComplete(content, item) && !tooMany);
|
||||
return (
|
||||
<List.Item
|
||||
actions={[
|
||||
<Button
|
||||
key={item.type}
|
||||
type="link"
|
||||
size="small"
|
||||
onClick={() => (content ? begin(content) : begin(undefined, item.type))}
|
||||
>
|
||||
{content ? "编辑" : "新增"}
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
<Space wrap>
|
||||
<Typography.Text strong>{item.label}</Typography.Text>
|
||||
{item.required && <Tag color="orange">发布必填</Tag>}
|
||||
{(item.pages ?? []).map((page) => (
|
||||
<Tag key={page}>{pageLabel(page)}</Tag>
|
||||
))}
|
||||
<Tag color={complete ? "success" : "default"}>
|
||||
{tooMany
|
||||
? `公开内容过多(${publishedCount} 条)`
|
||||
: complete
|
||||
? "内容完整"
|
||||
: content
|
||||
? "需要完善"
|
||||
: "尚未填写"}
|
||||
</Tag>
|
||||
{item.help && <Typography.Text type="secondary">{item.help}</Typography.Text>}
|
||||
</Space>
|
||||
</List.Item>
|
||||
);
|
||||
}}
|
||||
<TrustRequirementsList
|
||||
availableTypes={availableTypes}
|
||||
contentByType={contentByType}
|
||||
items={query.data ?? []}
|
||||
onEdit={begin}
|
||||
/>
|
||||
</section>
|
||||
<Divider />
|
||||
<section aria-label="已配置的品牌内容">
|
||||
<Table
|
||||
rowKey="id"
|
||||
dataSource={query.data ?? []}
|
||||
locale={{ emptyText: "还没有品牌内容,请先按上方模板要求添加。" }}
|
||||
columns={[
|
||||
{
|
||||
title: "内容类型",
|
||||
dataIndex: "type",
|
||||
render: (value) => (
|
||||
<Tag>{availableTypes.find((item) => item.type === value)?.label ?? value}</Tag>
|
||||
),
|
||||
},
|
||||
{ title: "标题", dataIndex: "title" },
|
||||
{
|
||||
title: "内容预览",
|
||||
ellipsis: { showTitle: true },
|
||||
render: (_value: unknown, item: TrustContent) => {
|
||||
const meta = availableTypes.find((type) => type.type === item.type);
|
||||
if (meta?.hideStandardFields?.includes("content")) {
|
||||
return (
|
||||
meta.configFields
|
||||
?.flatMap((field) => {
|
||||
const value = item.config?.[field.key];
|
||||
if (Array.isArray(value))
|
||||
return value.length ? [`${field.label}:${value.length} 项`] : [];
|
||||
return typeof value === "string" && value.trim()
|
||||
? [`${field.label}:${value}`]
|
||||
: [];
|
||||
})
|
||||
.join(";") || "尚未填写区块内容"
|
||||
);
|
||||
}
|
||||
return item.summary || item.content || "未填写";
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "发布状态",
|
||||
dataIndex: "isPublished",
|
||||
render: (value) => (
|
||||
<Tag color={value ? "success" : "default"}>{value ? "随发布展示" : "草稿"}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
render: (_: unknown, item: TrustContent) => (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => begin(item)}>
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="确认删除这条信任内容?"
|
||||
description="删除后需发布品牌,才会更新小程序展示。"
|
||||
onConfirm={() => remove.mutate(item.id)}
|
||||
>
|
||||
<Button size="small" danger loading={remove.isPending}>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<MutationError error={remove.error} />
|
||||
</section>
|
||||
<Modal
|
||||
<TrustContentTable
|
||||
availableTypes={availableTypes}
|
||||
items={query.data ?? []}
|
||||
removeError={remove.error}
|
||||
removePending={remove.isPending}
|
||||
onEdit={(item) => begin(item)}
|
||||
onDelete={(id) => remove.mutate(id)}
|
||||
/>
|
||||
<TrustContentEditorModal
|
||||
availableTypes={availableTypes}
|
||||
editing={editing}
|
||||
form={editorForm}
|
||||
open={open}
|
||||
title={editing ? "编辑品牌内容" : "添加品牌内容"}
|
||||
onCancel={() => {
|
||||
setOpen(false);
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
}}
|
||||
onOk={() => form.submit()}
|
||||
confirmLoading={save.isPending}
|
||||
destroyOnClose
|
||||
>
|
||||
<Form
|
||||
form={form}
|
||||
layout="vertical"
|
||||
onFinish={(values) => save.mutate({ ...values, content: values.content ?? "" })}
|
||||
>
|
||||
<Form.Item name="type" label="内容类型" rules={[{ required: true }]}>
|
||||
<Select
|
||||
options={availableTypes.map((item) => ({ value: item.type, label: item.label }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
{selectedTypeMeta?.pages?.length ? (
|
||||
<Typography.Paragraph type="secondary">
|
||||
这类内容会显示在:
|
||||
{selectedTypeMeta.pages.map(pageLabel).join("、")}
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
<Form.Item
|
||||
name="title"
|
||||
label={selectedTypeMeta?.adminFields.title ?? "标题"}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<Input placeholder="例如:服务过 30+ 位独立创作者" />
|
||||
</Form.Item>
|
||||
{!selectedTypeMeta?.hideStandardFields?.includes("summary") && (
|
||||
<Form.Item
|
||||
name="summary"
|
||||
label={selectedTypeMeta?.adminFields.summary ?? "摘要"}
|
||||
help={selectedTypeMeta?.adminFields.summaryHelp}
|
||||
>
|
||||
<Input placeholder={selectedTypeMeta?.adminFields.summaryPlaceholder} />
|
||||
</Form.Item>
|
||||
)}
|
||||
{!selectedTypeMeta?.hideStandardFields?.includes("content") && (
|
||||
<Form.Item
|
||||
name="content"
|
||||
label={selectedTypeMeta?.adminFields.content ?? "详细内容"}
|
||||
help={
|
||||
selectedTypeMeta?.help ?? "每行写一项,页面会按模板样式展示。不要填写 HTML 或代码。"
|
||||
}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<Input.TextArea
|
||||
rows={8}
|
||||
showCount
|
||||
maxLength={2000}
|
||||
placeholder={selectedTypeMeta?.placeholder ?? "例如:\n第一项内容\n第二项内容"}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
{selectedTypeMeta?.configFields?.map((field) =>
|
||||
field.input === "list" ? (
|
||||
<TemplateListField key={field.key} field={field} name={["config", field.key]} />
|
||||
) : (
|
||||
<Form.Item
|
||||
key={field.key}
|
||||
name={["config", field.key]}
|
||||
label={field.label}
|
||||
help={field.help}
|
||||
rules={[{ required: field.required === true }]}
|
||||
>
|
||||
{field.input === "textarea" ? <Input.TextArea rows={3} /> : <Input />}
|
||||
</Form.Item>
|
||||
),
|
||||
)}
|
||||
<Form.Item
|
||||
name="coverUrl"
|
||||
label="配图地址"
|
||||
help="粘贴一张可公开访问的图片地址,保存前会显示预览。"
|
||||
>
|
||||
<ImageUrlField placeholder="粘贴案例或经历配图地址" />
|
||||
</Form.Item>
|
||||
<Form.Item name="isPublished" label="公开状态">
|
||||
<Select
|
||||
options={[
|
||||
{ value: true, label: "随品牌发布展示" },
|
||||
{ value: false, label: "保存为草稿" },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<MutationError error={save.error} />
|
||||
</Form>
|
||||
</Modal>
|
||||
pageLabel={pageLabel}
|
||||
saveError={save.error}
|
||||
savePending={save.isPending}
|
||||
selectedTypeMeta={selectedTypeMeta}
|
||||
onCancel={closeEditor}
|
||||
onFinish={(values) => save.mutate(values)}
|
||||
/>
|
||||
</QueryState>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { Form, Input, Modal, Select, Typography } from "antd";
|
||||
import type { FormInstance } from "antd";
|
||||
import type { TrustContent, TrustContentInput } from "@personal-brand/api-client";
|
||||
import { ImageUrlField } from "../../../components/ImageUrlField.js";
|
||||
import { TemplateListField } from "../../../components/TemplateListField.js";
|
||||
import { MutationError } from "../../../components/QueryState.js";
|
||||
import type { TrustTypeOption } from "../domain/trust-content-domain.js";
|
||||
|
||||
export function TrustContentEditorModal({
|
||||
availableTypes,
|
||||
editing,
|
||||
form,
|
||||
open,
|
||||
pageLabel,
|
||||
saveError,
|
||||
savePending,
|
||||
selectedTypeMeta,
|
||||
onCancel,
|
||||
onFinish,
|
||||
}: {
|
||||
availableTypes: TrustTypeOption[];
|
||||
editing: TrustContent | null;
|
||||
form: FormInstance<TrustContentInput>;
|
||||
open: boolean;
|
||||
pageLabel: (page: string) => string;
|
||||
saveError: unknown;
|
||||
savePending: boolean;
|
||||
selectedTypeMeta?: TrustTypeOption | undefined;
|
||||
onCancel: () => void;
|
||||
onFinish: (values: TrustContentInput) => void;
|
||||
}) {
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={editing ? "编辑品牌内容" : "添加品牌内容"}
|
||||
onCancel={onCancel}
|
||||
onOk={() => form.submit()}
|
||||
confirmLoading={savePending}
|
||||
destroyOnClose
|
||||
>
|
||||
<Form
|
||||
form={form}
|
||||
layout="vertical"
|
||||
onFinish={(values) => onFinish({ ...values, content: values.content ?? "" })}
|
||||
>
|
||||
<Form.Item name="type" label="内容类型" rules={[{ required: true }]}>
|
||||
<Select
|
||||
options={availableTypes.map((item) => ({ value: item.type, label: item.label }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
{selectedTypeMeta?.pages?.length ? (
|
||||
<Typography.Paragraph type="secondary">
|
||||
这类内容会显示在:{selectedTypeMeta.pages.map(pageLabel).join("、")}
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
<Form.Item
|
||||
name="title"
|
||||
label={selectedTypeMeta?.adminFields.title ?? "标题"}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<Input placeholder="例如:服务过 30+ 位独立创作者" />
|
||||
</Form.Item>
|
||||
{!selectedTypeMeta?.hideStandardFields?.includes("summary") && (
|
||||
<Form.Item
|
||||
name="summary"
|
||||
label={selectedTypeMeta?.adminFields.summary ?? "摘要"}
|
||||
help={selectedTypeMeta?.adminFields.summaryHelp}
|
||||
>
|
||||
<Input placeholder={selectedTypeMeta?.adminFields.summaryPlaceholder} />
|
||||
</Form.Item>
|
||||
)}
|
||||
{!selectedTypeMeta?.hideStandardFields?.includes("content") && (
|
||||
<Form.Item
|
||||
name="content"
|
||||
label={selectedTypeMeta?.adminFields.content ?? "详细内容"}
|
||||
help={
|
||||
selectedTypeMeta?.help ?? "每行写一项,页面会按模板样式展示。不要填写 HTML 或代码。"
|
||||
}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<Input.TextArea
|
||||
rows={8}
|
||||
showCount
|
||||
maxLength={2000}
|
||||
placeholder={selectedTypeMeta?.placeholder ?? "例如:\n第一项内容\n第二项内容"}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
{selectedTypeMeta?.configFields?.map((field) =>
|
||||
field.input === "list" ? (
|
||||
<TemplateListField key={field.key} field={field} name={["config", field.key]} />
|
||||
) : (
|
||||
<Form.Item
|
||||
key={field.key}
|
||||
name={["config", field.key]}
|
||||
label={field.label}
|
||||
help={field.help}
|
||||
rules={[{ required: field.required === true }]}
|
||||
>
|
||||
{field.input === "textarea" ? <Input.TextArea rows={3} /> : <Input />}
|
||||
</Form.Item>
|
||||
),
|
||||
)}
|
||||
<Form.Item
|
||||
name="coverUrl"
|
||||
label="配图地址"
|
||||
help="粘贴一张可公开访问的图片地址,保存前会显示预览。"
|
||||
>
|
||||
<ImageUrlField placeholder="粘贴案例或经历配图地址" scope="trust" />
|
||||
</Form.Item>
|
||||
<Form.Item name="isPublished" label="公开状态">
|
||||
<Select
|
||||
options={[
|
||||
{ value: true, label: "随品牌发布展示" },
|
||||
{ value: false, label: "保存为草稿" },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<MutationError error={saveError} />
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Button, Popconfirm, Space, Table, Tag } from "antd";
|
||||
import type { TrustContent } from "@personal-brand/api-client";
|
||||
import type { TrustTypeOption } from "../domain/trust-content-domain.js";
|
||||
import { getTrustContentPreview } from "../domain/trust-content-domain.js";
|
||||
import { MutationError } from "../../../components/QueryState.js";
|
||||
|
||||
export function TrustContentTable({
|
||||
availableTypes,
|
||||
items,
|
||||
removeError,
|
||||
removePending,
|
||||
onEdit,
|
||||
onDelete,
|
||||
}: {
|
||||
availableTypes: TrustTypeOption[];
|
||||
items: TrustContent[];
|
||||
removeError: unknown;
|
||||
removePending: boolean;
|
||||
onEdit: (item: TrustContent) => void;
|
||||
onDelete: (id: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<section aria-label="已配置的品牌内容">
|
||||
<Table
|
||||
rowKey="id"
|
||||
dataSource={items}
|
||||
locale={{ emptyText: "还没有品牌内容,请先按上方模板要求添加。" }}
|
||||
columns={[
|
||||
{
|
||||
title: "内容类型",
|
||||
dataIndex: "type",
|
||||
render: (value) => (
|
||||
<Tag>{availableTypes.find((item) => item.type === value)?.label ?? value}</Tag>
|
||||
),
|
||||
},
|
||||
{ title: "标题", dataIndex: "title" },
|
||||
{
|
||||
title: "内容预览",
|
||||
ellipsis: { showTitle: true },
|
||||
render: (_value: unknown, item: TrustContent) =>
|
||||
getTrustContentPreview(
|
||||
item,
|
||||
availableTypes.find((type) => type.type === item.type),
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "发布状态",
|
||||
dataIndex: "isPublished",
|
||||
render: (value) => (
|
||||
<Tag color={value ? "success" : "default"}>{value ? "随发布展示" : "草稿"}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
render: (_: unknown, item: TrustContent) => (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => onEdit(item)}>
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="确认删除这条信任内容?"
|
||||
description="删除后需发布品牌,才会更新小程序展示。"
|
||||
onConfirm={() => onDelete(item.id)}
|
||||
>
|
||||
<Button size="small" danger loading={removePending}>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<MutationError error={removeError} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { Button, List, Space, Tag, Typography } from "antd";
|
||||
import { isTrustContentComplete } from "@personal-brand/api-client";
|
||||
import type { TrustContent } from "@personal-brand/api-client";
|
||||
import type { TrustTypeOption } from "../domain/trust-content-domain.js";
|
||||
|
||||
export function TrustRequirementsList({
|
||||
availableTypes,
|
||||
contentByType,
|
||||
items,
|
||||
onEdit,
|
||||
}: {
|
||||
availableTypes: TrustTypeOption[];
|
||||
contentByType: Map<string, TrustContent>;
|
||||
items: TrustContent[];
|
||||
onEdit: (item?: TrustContent, type?: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<List
|
||||
size="small"
|
||||
dataSource={availableTypes}
|
||||
renderItem={(item) => {
|
||||
const content = contentByType.get(item.type);
|
||||
const publishedCount = items.filter(
|
||||
(record) => record.type === item.type && record.isPublished,
|
||||
).length;
|
||||
const tooMany =
|
||||
item.maxPublishedItems !== undefined && publishedCount > item.maxPublishedItems;
|
||||
const complete = Boolean(content && isTrustContentComplete(content, item) && !tooMany);
|
||||
|
||||
return (
|
||||
<List.Item
|
||||
actions={[
|
||||
<Button
|
||||
key={item.type}
|
||||
type="link"
|
||||
size="small"
|
||||
onClick={() => (content ? onEdit(content) : onEdit(undefined, item.type))}
|
||||
>
|
||||
{content ? "编辑" : "新增"}
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
<Space wrap>
|
||||
<Typography.Text strong>{item.label}</Typography.Text>
|
||||
{item.required && <Tag color="orange">发布必填</Tag>}
|
||||
{(item.pages ?? []).map((page) => (
|
||||
<Tag key={page}>{page}</Tag>
|
||||
))}
|
||||
<Tag color={complete ? "success" : "default"}>
|
||||
{tooMany
|
||||
? `公开内容过多(${publishedCount} 条)`
|
||||
: complete
|
||||
? "内容完整"
|
||||
: content
|
||||
? "需要完善"
|
||||
: "尚未填写"}
|
||||
</Tag>
|
||||
{item.help && <Typography.Text type="secondary">{item.help}</Typography.Text>}
|
||||
</Space>
|
||||
</List.Item>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { TemplateAdminField } from "@personal-brand/api-client";
|
||||
import type { TrustContent } from "@personal-brand/api-client";
|
||||
|
||||
export type TrustTypeOption = {
|
||||
type: string;
|
||||
label: string;
|
||||
adminFields: {
|
||||
title: string;
|
||||
summary: string;
|
||||
content: string;
|
||||
summaryHelp?: string;
|
||||
summaryPlaceholder?: string;
|
||||
};
|
||||
pages?: string[];
|
||||
help?: string;
|
||||
placeholder?: string;
|
||||
required?: boolean;
|
||||
configFields?: TemplateAdminField[];
|
||||
hideStandardFields?: Array<"summary" | "content">;
|
||||
maxPublishedItems?: number;
|
||||
};
|
||||
|
||||
const fallbackTypeSeeds = [
|
||||
{
|
||||
value: "schedule",
|
||||
label: "时间与服务安排",
|
||||
help: "说明你通常什么时候提供服务、接受预约或处理订单。多项内容可以分行填写。",
|
||||
},
|
||||
{
|
||||
value: "coverage",
|
||||
label: "服务范围与方式",
|
||||
help: "说明服务地点、覆盖范围、适用对象或承接边界。多项内容可以分行填写。",
|
||||
},
|
||||
{
|
||||
value: "process",
|
||||
label: "合作流程",
|
||||
help: "说明客户从提出需求到完成合作会经历哪些步骤,每行写一步。",
|
||||
},
|
||||
{
|
||||
value: "credential",
|
||||
label: "资质与专业证明",
|
||||
help: "说明资质、经验、制作标准或让客户放心的专业依据。",
|
||||
},
|
||||
{
|
||||
value: "case",
|
||||
label: "案例与客户反馈",
|
||||
help: "写代表性案例、服务结果或客户评价,多条内容可以分行填写。",
|
||||
},
|
||||
{
|
||||
value: "promise",
|
||||
label: "服务承诺与响应说明",
|
||||
help: "说明回复时间、交付承诺、售后方式或合作预期。",
|
||||
},
|
||||
];
|
||||
|
||||
export const fallbackTrustTypes: TrustTypeOption[] = fallbackTypeSeeds.map(
|
||||
({ value, label, help }) => ({
|
||||
type: value,
|
||||
label,
|
||||
adminFields: { title: "标题", summary: "摘要", content: "详细内容" },
|
||||
help,
|
||||
}),
|
||||
);
|
||||
|
||||
const pageLabels: Record<string, string> = {
|
||||
home: "首页",
|
||||
offerings: "业务展示页",
|
||||
detail: "详情页",
|
||||
profile: "主理人页",
|
||||
};
|
||||
|
||||
export function createTrustPageLabelResolver(navigation?: Array<{ page: string; label: string }>) {
|
||||
return (page: string) =>
|
||||
navigation?.find((item) => item.page === page)?.label ?? pageLabels[page] ?? page;
|
||||
}
|
||||
|
||||
export function selectTrustTypeOptions(workspaceTypes?: TrustTypeOption[]): TrustTypeOption[] {
|
||||
return workspaceTypes?.length ? workspaceTypes : fallbackTrustTypes;
|
||||
}
|
||||
|
||||
export function groupTrustContentByType(items: TrustContent[]) {
|
||||
const contentByType = new Map<string, TrustContent>();
|
||||
|
||||
for (const item of items) {
|
||||
const current = contentByType.get(item.type);
|
||||
const hasConfig = Object.keys(item.config ?? {}).length > 0;
|
||||
const currentHasConfig = Object.keys(current?.config ?? {}).length > 0;
|
||||
|
||||
if (
|
||||
!current ||
|
||||
(item.isPublished && !current.isPublished) ||
|
||||
(item.isPublished === current.isPublished && hasConfig && !currentHasConfig)
|
||||
) {
|
||||
contentByType.set(item.type, item);
|
||||
}
|
||||
}
|
||||
|
||||
return contentByType;
|
||||
}
|
||||
|
||||
export function getTrustContentPreview(item: TrustContent, typeMeta?: TrustTypeOption): string {
|
||||
if (typeMeta?.hideStandardFields?.includes("content")) {
|
||||
return (
|
||||
typeMeta.configFields
|
||||
?.flatMap((field) => {
|
||||
const value = item.config?.[field.key];
|
||||
if (Array.isArray(value)) {
|
||||
return value.length ? [`${field.label}:${value.length} 项`] : [];
|
||||
}
|
||||
return typeof value === "string" && value.trim() ? [`${field.label}:${value}`] : [];
|
||||
})
|
||||
.join(";") || "尚未填写区块内容"
|
||||
);
|
||||
}
|
||||
|
||||
return item.summary || item.content || "未填写";
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { Form } from "antd";
|
||||
import type { TrustContent, TrustContentInput } from "@personal-brand/api-client";
|
||||
import type { TrustTypeOption } from "../domain/trust-content-domain.js";
|
||||
import { useTrustContentMutations } from "./useTrustContentMutations.js";
|
||||
|
||||
export function useTrustContentEditor({
|
||||
availableTypes,
|
||||
contentByType,
|
||||
firstMissingRequiredType,
|
||||
}: {
|
||||
availableTypes: TrustTypeOption[];
|
||||
contentByType: Map<string, TrustContent>;
|
||||
firstMissingRequiredType: string;
|
||||
}) {
|
||||
const [editing, setEditing] = useState<TrustContent | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [form] = Form.useForm<TrustContentInput>();
|
||||
const [searchParams] = useSearchParams();
|
||||
|
||||
const closeEditor = () => {
|
||||
setOpen(false);
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
};
|
||||
|
||||
const { save, remove } = useTrustContentMutations({ editing, closeEditor });
|
||||
|
||||
const begin = (item?: TrustContent, type?: string) => {
|
||||
setEditing(item ?? null);
|
||||
setOpen(true);
|
||||
form.setFieldsValue(
|
||||
item
|
||||
? {
|
||||
type: item.type,
|
||||
title: item.title,
|
||||
...(item.summary ? { summary: item.summary } : {}),
|
||||
content: item.content,
|
||||
config: item.config ?? {},
|
||||
...(item.coverUrl ? { coverUrl: item.coverUrl } : {}),
|
||||
isPublished: item.isPublished,
|
||||
}
|
||||
: { type: type ?? firstMissingRequiredType, isPublished: false, config: {} },
|
||||
);
|
||||
};
|
||||
|
||||
const requestedType = searchParams.get("type");
|
||||
|
||||
useEffect(() => {
|
||||
if (!requestedType || !availableTypes.some((item) => item.type === requestedType)) return;
|
||||
begin(contentByType.get(requestedType), requestedType);
|
||||
}, [requestedType, availableTypes.length]);
|
||||
|
||||
return { begin, closeEditor, editing, form, open, remove, save };
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { message } from "antd";
|
||||
import type { TrustContent, TrustContentInput } from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../../lib/api.js";
|
||||
|
||||
export function useTrustContentMutations({
|
||||
editing,
|
||||
closeEditor,
|
||||
}: {
|
||||
editing: TrustContent | null;
|
||||
closeEditor: () => void;
|
||||
}) {
|
||||
const client = createApiClient();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: (values: TrustContentInput) =>
|
||||
editing
|
||||
? client.updateAdminTrustContent(editing.id, values)
|
||||
: client.createAdminTrustContent(values),
|
||||
onSuccess: () => {
|
||||
message.success("品牌内容已保存为草稿,发布后小程序才会更新");
|
||||
closeEditor();
|
||||
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
|
||||
},
|
||||
});
|
||||
|
||||
const remove = useMutation({
|
||||
mutationFn: (id: string) => client.deleteAdminTrustContent(id),
|
||||
onSuccess: () => {
|
||||
message.success("品牌内容已删除");
|
||||
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
|
||||
},
|
||||
});
|
||||
|
||||
return { save, remove };
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { createApiClient } from "../../../lib/api.js";
|
||||
|
||||
export function useTrustContentQueries() {
|
||||
const client = createApiClient();
|
||||
|
||||
return {
|
||||
query: useQuery({
|
||||
queryKey: ["trust-content"],
|
||||
queryFn: () => client.listAdminTrustContent(),
|
||||
}),
|
||||
workspace: useQuery({
|
||||
queryKey: ["admin-workspace-trust-types"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,30 +1,25 @@
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
Form,
|
||||
Input,
|
||||
Modal,
|
||||
Select,
|
||||
Space,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
message,
|
||||
} from "antd";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Button, Card, Form, Input, Modal, Select, Space, Table, Tag, Typography } from "antd";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import { ApiClientError } from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import type {
|
||||
BrandFieldDefinition,
|
||||
BrandTemplateKey,
|
||||
InquiryForm,
|
||||
} from "@personal-brand/api-client";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
import {
|
||||
useWorkspaceQueries,
|
||||
useTemplateMutations,
|
||||
useFieldMutations,
|
||||
useInquiryFormMutations,
|
||||
} from "./workspace-mutations.js";
|
||||
import { supportsIndustry, type IndustryTarget } from "./workspace-templates.js";
|
||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||
import { MutationError } from "../../components/QueryState.js";
|
||||
|
||||
const inquiryFieldTypes = [
|
||||
export const inquiryFieldTypes = [
|
||||
{ value: "text", label: "简短文字" },
|
||||
{ value: "textarea", label: "详细说明" },
|
||||
{ value: "phone", label: "联系电话" },
|
||||
@@ -36,53 +31,28 @@ const inquiryFieldTypes = [
|
||||
{ value: "multi-select", label: "多项选择" },
|
||||
];
|
||||
|
||||
function optionsToText(options: unknown): string {
|
||||
if (!Array.isArray(options)) return "";
|
||||
return options
|
||||
.map((option) => {
|
||||
if (!option || typeof option !== "object") return "";
|
||||
const label = (option as { label?: unknown }).label;
|
||||
return typeof label === "string" ? label : "";
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
export function readOptionLabel(option: unknown): string {
|
||||
const value = option as { label?: unknown } | null | undefined;
|
||||
return typeof value?.label === "string" ? value.label : "";
|
||||
}
|
||||
|
||||
function optionsFromText(value: unknown): Array<{ label: string; value: string }> {
|
||||
if (typeof value !== "string") return [];
|
||||
return value
|
||||
.split(/\r?\n|、|,/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean)
|
||||
.map((item) => ({ label: item, value: item }));
|
||||
}
|
||||
|
||||
function supportsIndustry(
|
||||
visual: { supportedIndustryTemplates?: unknown },
|
||||
industry: string,
|
||||
): boolean {
|
||||
return (
|
||||
Array.isArray(visual.supportedIndustryTemplates) &&
|
||||
visual.supportedIndustryTemplates.includes(industry)
|
||||
);
|
||||
export function normalizeOptionLabels(options: unknown): Array<{ label: string; value: string }> {
|
||||
return (Array.isArray(options) ? options : [])
|
||||
.map(readOptionLabel)
|
||||
.filter((label) => label.trim())
|
||||
.map((label) => ({ label, value: label }));
|
||||
}
|
||||
|
||||
export function WorkspacePage() {
|
||||
const navigate = useNavigate();
|
||||
const client = createApiClient();
|
||||
const queryClient = useQueryClient();
|
||||
const [fieldOpen, setFieldOpen] = useState(false);
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [editingForm, setEditingForm] = useState<InquiryForm | null>(null);
|
||||
const [visualTarget, setVisualTarget] = useState<string | null>(null);
|
||||
const [industryTarget, setIndustryTarget] = useState<{
|
||||
key: "personal" | "food" | "doors";
|
||||
name: string;
|
||||
description: string;
|
||||
capabilities: string[];
|
||||
} | null>(null);
|
||||
const [previewIndustry, setPreviewIndustry] = useState<BrandTemplateKey>("personal");
|
||||
const [previewVisual, setPreviewVisual] = useState("linjing-editorial");
|
||||
const [industryTarget, setIndustryTarget] = useState<IndustryTarget | null>(null);
|
||||
const [previewIndustry, setPreviewIndustry] = useState<BrandTemplateKey | null>(null);
|
||||
const [previewVisual, setPreviewVisual] = useState<string | null>(null);
|
||||
const [form] = Form.useForm<Record<string, unknown>>();
|
||||
const [inquiryForm] = Form.useForm<Record<string, unknown>>();
|
||||
const openNewInquiryForm = () => {
|
||||
@@ -98,126 +68,49 @@ export function WorkspacePage() {
|
||||
});
|
||||
setFormOpen(true);
|
||||
};
|
||||
const query = useQuery({
|
||||
queryKey: ["admin-workspace"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
});
|
||||
const runtimeQuery = useQuery({
|
||||
queryKey: ["public-runtime-workspace"],
|
||||
queryFn: () => client.getPublicWorkspace(),
|
||||
});
|
||||
const templateCatalog = useQuery({
|
||||
queryKey: ["template-catalog"],
|
||||
queryFn: () => client.listPublicTemplates(),
|
||||
});
|
||||
const { query, runtimeQuery, templateCatalog, forms, templatePreview } = useWorkspaceQueries();
|
||||
const previewIndustryKey =
|
||||
previewIndustry ??
|
||||
query.data?.brand.templateKey ??
|
||||
query.data?.installations[0]?.templateKey ??
|
||||
templateCatalog.data?.industries[0]?.key;
|
||||
const previewVisualKey =
|
||||
previewVisual ??
|
||||
runtimeQuery.data?.visualTemplate?.key ??
|
||||
(templateCatalog.data?.visuals ?? []).find((visual) =>
|
||||
supportsIndustry(visual, previewIndustryKey ?? ""),
|
||||
)?.key;
|
||||
const combinationPreview = useQuery({
|
||||
queryKey: ["template-combination-preview", previewIndustry, previewVisual],
|
||||
queryFn: () => client.previewPublicTemplateCombination(previewIndustry, previewVisual),
|
||||
enabled: Boolean(templateCatalog.data),
|
||||
queryKey: ["template-combination-preview", previewIndustryKey, previewVisualKey],
|
||||
queryFn: () =>
|
||||
createApiClient().previewPublicTemplateCombination(
|
||||
previewIndustryKey ?? "",
|
||||
previewVisualKey ?? "",
|
||||
),
|
||||
enabled: Boolean(templateCatalog.data && previewIndustryKey && previewVisualKey),
|
||||
});
|
||||
const compatibleVisuals = (templateCatalog.data?.visuals ?? []).filter((visual) =>
|
||||
supportsIndustry(visual, query.data?.brand?.templateKey ?? "personal"),
|
||||
supportsIndustry(visual, query.data?.brand?.templateKey ?? ""),
|
||||
);
|
||||
const visualTemplate = useMutation({
|
||||
mutationFn: (key: string) =>
|
||||
client.updateAdminBrand({
|
||||
config: { ...(runtimeQuery.data?.brand?.config ?? {}), visualTemplateKey: key },
|
||||
}),
|
||||
onSuccess: () => {
|
||||
message.success("视觉模板已切换");
|
||||
void runtimeQuery.refetch();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
|
||||
},
|
||||
const { visualTemplate, rollbackVisual, install, upgrade, rollback } = useTemplateMutations({
|
||||
runtimeConfig: runtimeQuery.data?.brand?.config ?? undefined,
|
||||
queryClient,
|
||||
});
|
||||
const visualHistory = useQuery({
|
||||
queryKey: ["visual-template-history"],
|
||||
queryFn: () => client.getAdminVisualTemplateHistory(),
|
||||
queryFn: () => createApiClient().getAdminVisualTemplateHistory(),
|
||||
});
|
||||
const rollbackVisual = useMutation({
|
||||
mutationFn: () => client.rollbackAdminVisualTemplate(),
|
||||
onSuccess: () => {
|
||||
message.success("视觉模板已回滚");
|
||||
void runtimeQuery.refetch();
|
||||
void visualHistory.refetch();
|
||||
},
|
||||
const { createField, removeField } = useFieldMutations({
|
||||
form,
|
||||
queryClient,
|
||||
onClose: () => setFieldOpen(false),
|
||||
});
|
||||
const install = useMutation({
|
||||
mutationFn: (key: "personal" | "food" | "doors") => client.installAdminTemplate(key),
|
||||
onSuccess: () => {
|
||||
message.success("模板已安装");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
},
|
||||
});
|
||||
const createField = useMutation({
|
||||
mutationFn: (values: Omit<BrandFieldDefinition, "id" | "source">) =>
|
||||
client.createAdminField(values),
|
||||
onSuccess: () => {
|
||||
message.success("字段已创建");
|
||||
setFieldOpen(false);
|
||||
form.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
},
|
||||
});
|
||||
const removeField = useMutation({
|
||||
mutationFn: (id: string) => client.deleteAdminField(id),
|
||||
onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }),
|
||||
});
|
||||
const forms = useQuery({
|
||||
queryKey: ["admin-inquiry-forms"],
|
||||
queryFn: () => client.listAdminInquiryForms(),
|
||||
});
|
||||
const templatePreview = useQuery({
|
||||
queryKey: ["admin-template-preview"],
|
||||
queryFn: () => client.getAdminTemplateUpgradePreview(),
|
||||
enabled: Boolean(query.data?.installations?.length),
|
||||
});
|
||||
const upgrade = useMutation({
|
||||
mutationFn: () => client.upgradeAdminTemplate(),
|
||||
onSuccess: () => {
|
||||
message.success("模板已升级,已有内容未被覆盖");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] });
|
||||
},
|
||||
});
|
||||
const rollback = useMutation({
|
||||
mutationFn: () => client.rollbackAdminTemplate(),
|
||||
onSuccess: () => {
|
||||
message.success("模板版本已回滚,现有内容未删除");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] });
|
||||
},
|
||||
});
|
||||
const createForm = useMutation({
|
||||
mutationFn: (values: {
|
||||
name: string;
|
||||
offeringId?: string;
|
||||
purpose?: InquiryForm["purpose"];
|
||||
targetType?: InquiryForm["targetType"];
|
||||
submissionAction?: InquiryForm["submissionAction"];
|
||||
fieldsSnapshot: unknown[];
|
||||
}) => client.createAdminInquiryForm(values),
|
||||
onSuccess: () => {
|
||||
message.success("咨询表单已创建");
|
||||
setFormOpen(false);
|
||||
inquiryForm.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-forms"] });
|
||||
},
|
||||
});
|
||||
const updateForm = useMutation({
|
||||
mutationFn: ({ id, body }: { id: string; body: Partial<InquiryForm> }) =>
|
||||
client.updateAdminInquiryForm(id, {
|
||||
...(body.name === undefined ? {} : { name: body.name }),
|
||||
...(body.offeringId == null ? {} : { offeringId: body.offeringId }),
|
||||
...(body.fieldsSnapshot === undefined ? {} : { fieldsSnapshot: body.fieldsSnapshot }),
|
||||
...(body.isEnabled === undefined ? {} : { isEnabled: body.isEnabled }),
|
||||
}),
|
||||
onSuccess: () => {
|
||||
message.success("咨询表单已更新");
|
||||
const { createForm, updateForm } = useInquiryFormMutations({
|
||||
form: inquiryForm,
|
||||
queryClient,
|
||||
onClose: () => {
|
||||
setFormOpen(false);
|
||||
setEditingForm(null);
|
||||
inquiryForm.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-forms"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
|
||||
},
|
||||
});
|
||||
if (query.isLoading) return <Card loading />;
|
||||
@@ -306,9 +199,9 @@ export function WorkspacePage() {
|
||||
<Space wrap>
|
||||
<Typography.Text strong>视觉模板</Typography.Text>
|
||||
<Select
|
||||
value={runtimeQuery.data?.visualTemplate?.key ?? "linjing-editorial"}
|
||||
value={runtimeQuery.data?.visualTemplate?.key}
|
||||
loading={visualTemplate.isPending}
|
||||
onChange={(key) => setVisualTarget(key)}
|
||||
onChange={(key) => setVisualTarget(key ?? null)}
|
||||
options={[
|
||||
...compatibleVisuals.map((visual) => ({ value: visual.key, label: visual.name })),
|
||||
]}
|
||||
@@ -475,18 +368,18 @@ export function WorkspacePage() {
|
||||
</Typography.Paragraph>
|
||||
<Space wrap>
|
||||
<Select
|
||||
value={previewIndustry}
|
||||
onChange={setPreviewIndustry}
|
||||
value={previewIndustryKey ?? null}
|
||||
onChange={(key) => setPreviewIndustry(key)}
|
||||
options={(templateCatalog.data?.industries ?? []).map((item) => ({
|
||||
value: item.key,
|
||||
label: item.name,
|
||||
}))}
|
||||
/>
|
||||
<Select
|
||||
value={previewVisual}
|
||||
onChange={setPreviewVisual}
|
||||
value={previewVisualKey ?? null}
|
||||
onChange={(key) => setPreviewVisual(key)}
|
||||
options={(templateCatalog.data?.visuals ?? [])
|
||||
.filter((item) => supportsIndustry(item, previewIndustry))
|
||||
.filter((item) => supportsIndustry(item, previewIndustryKey ?? ""))
|
||||
.map((item) => ({ value: item.key, label: item.name }))}
|
||||
/>
|
||||
</Space>
|
||||
@@ -541,11 +434,11 @@ export function WorkspacePage() {
|
||||
name: item.name,
|
||||
purpose: item.purpose,
|
||||
offeringId: item.offeringId ?? undefined,
|
||||
fieldsSnapshot: item.fieldsSnapshot.map((field) => {
|
||||
fieldsSnapshot: item.fieldsSnapshot.map((field: unknown) => {
|
||||
const value = field as Record<string, unknown>;
|
||||
return {
|
||||
...value,
|
||||
optionsText: optionsToText(value.options),
|
||||
options: normalizeOptionLabels(value.options),
|
||||
};
|
||||
}),
|
||||
});
|
||||
@@ -719,12 +612,15 @@ export function WorkspacePage() {
|
||||
fieldsSnapshot: (Array.isArray(values.fieldsSnapshot)
|
||||
? values.fieldsSnapshot
|
||||
: []
|
||||
).map((field) => {
|
||||
).map((field: unknown) => {
|
||||
const item = field as Record<string, unknown>;
|
||||
const { optionsText, ...rest } = item;
|
||||
const { options, ...rest } = item;
|
||||
const type = typeof rest.type === "string" ? rest.type : "text";
|
||||
return ["select", "radio", "multi-select"].includes(type)
|
||||
? { ...rest, options: optionsFromText(optionsText) }
|
||||
? {
|
||||
...rest,
|
||||
options: normalizeOptionLabels(options),
|
||||
}
|
||||
: rest;
|
||||
}),
|
||||
};
|
||||
@@ -824,18 +720,54 @@ export function WorkspacePage() {
|
||||
["select", "radio", "multi-select"].includes(
|
||||
String(getFieldValue(["fieldsSnapshot", name, "type"])),
|
||||
) ? (
|
||||
<Form.Item
|
||||
{...restField}
|
||||
name={[name, "optionsText"]}
|
||||
label="可选内容"
|
||||
help="每行填写一个选项,也可以用顿号分隔。"
|
||||
rules={[{ required: true, message: "请至少填写一个选项" }]}
|
||||
<Form.List
|
||||
name={[name, "options"]}
|
||||
rules={[
|
||||
{
|
||||
validator: (_, value: unknown) =>
|
||||
Array.isArray(value) &&
|
||||
value.some((option: unknown) => readOptionLabel(option).trim())
|
||||
? Promise.resolve()
|
||||
: Promise.reject(new Error("请至少添加一个选项")),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
placeholder="例如:预算内、需要沟通、暂不确定"
|
||||
/>
|
||||
</Form.Item>
|
||||
{(optionFields, { add, remove }, { errors }) => (
|
||||
<>
|
||||
{optionFields.map((optionField) => (
|
||||
<Space
|
||||
key={optionField.key}
|
||||
align="center"
|
||||
style={{ display: "flex" }}
|
||||
>
|
||||
<Form.Item
|
||||
{...optionField}
|
||||
name={[optionField.name, "label"]}
|
||||
initialValue=""
|
||||
rules={[{ required: true, message: "请填写选项内容" }]}
|
||||
style={{ flex: 1, minWidth: 240, marginBottom: 8 }}
|
||||
>
|
||||
<Input placeholder="例如:预算内" />
|
||||
</Form.Item>
|
||||
<Button
|
||||
danger
|
||||
onClick={() => remove(optionField.name)}
|
||||
style={{ marginBottom: 8 }}
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
</Space>
|
||||
))}
|
||||
<Button
|
||||
onClick={() => add({ label: "", value: "" })}
|
||||
style={{ marginBottom: 8 }}
|
||||
>
|
||||
新增选项
|
||||
</Button>
|
||||
<Form.ErrorList errors={errors} />
|
||||
</>
|
||||
)}
|
||||
</Form.List>
|
||||
) : null
|
||||
}
|
||||
</Form.Item>
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { message } from "antd";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import type { FormInstance } from "antd";
|
||||
import type {
|
||||
BrandFieldDefinition,
|
||||
BrandTemplateKey,
|
||||
InquiryForm,
|
||||
} from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
|
||||
export function useWorkspaceQueries(client = createApiClient()) {
|
||||
const query = useQuery({
|
||||
queryKey: ["admin-workspace"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
});
|
||||
const runtimeQuery = useQuery({
|
||||
queryKey: ["public-runtime-workspace"],
|
||||
queryFn: () => client.getPublicWorkspace(),
|
||||
});
|
||||
const templateCatalog = useQuery({
|
||||
queryKey: ["template-catalog"],
|
||||
queryFn: () => client.listPublicTemplates(),
|
||||
});
|
||||
const forms = useQuery({
|
||||
queryKey: ["admin-inquiry-forms"],
|
||||
queryFn: () => client.listAdminInquiryForms(),
|
||||
});
|
||||
const templatePreview = useQuery({
|
||||
queryKey: ["admin-template-preview"],
|
||||
queryFn: () => client.getAdminTemplateUpgradePreview(),
|
||||
enabled: Boolean(query.data?.installations?.length),
|
||||
});
|
||||
return { query, runtimeQuery, templateCatalog, forms, templatePreview };
|
||||
}
|
||||
|
||||
interface TemplateMutationOptions {
|
||||
client?: ReturnType<typeof createApiClient>;
|
||||
runtimeConfig: Record<string, unknown> | undefined;
|
||||
queryClient: {
|
||||
invalidateQueries: (options: { queryKey: readonly unknown[] }) => Promise<void>;
|
||||
};
|
||||
}
|
||||
|
||||
export function useTemplateMutations({
|
||||
client = createApiClient(),
|
||||
runtimeConfig,
|
||||
queryClient,
|
||||
}: TemplateMutationOptions) {
|
||||
const visualTemplate = useMutation({
|
||||
mutationFn: (key: string) =>
|
||||
client.updateAdminBrand({ config: { ...(runtimeConfig ?? {}), visualTemplateKey: key } }),
|
||||
onSuccess: () => {
|
||||
message.success("视觉模板已切换");
|
||||
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
|
||||
},
|
||||
});
|
||||
const rollbackVisual = useMutation({
|
||||
mutationFn: () => client.rollbackAdminVisualTemplate(),
|
||||
onSuccess: () => {
|
||||
message.success("视觉模板已回滚");
|
||||
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["visual-template-history"] });
|
||||
},
|
||||
});
|
||||
const install = useMutation({
|
||||
mutationFn: (key: BrandTemplateKey) => client.installAdminTemplate(key),
|
||||
onSuccess: () => {
|
||||
message.success("模板已安装");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
},
|
||||
});
|
||||
const upgrade = useMutation({
|
||||
mutationFn: () => client.upgradeAdminTemplate(),
|
||||
onSuccess: () => {
|
||||
message.success("模板已升级,已有内容未被覆盖");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] });
|
||||
},
|
||||
});
|
||||
const rollback = useMutation({
|
||||
mutationFn: () => client.rollbackAdminTemplate(),
|
||||
onSuccess: () => {
|
||||
message.success("模板版本已回滚,现有内容未删除");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] });
|
||||
},
|
||||
});
|
||||
return { visualTemplate, rollbackVisual, install, upgrade, rollback };
|
||||
}
|
||||
|
||||
interface FieldMutationOptions {
|
||||
client?: ReturnType<typeof createApiClient>;
|
||||
form: FormInstance<Record<string, unknown>>;
|
||||
queryClient: {
|
||||
invalidateQueries: (options: { queryKey: readonly unknown[] }) => Promise<void>;
|
||||
};
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function useFieldMutations({
|
||||
client = createApiClient(),
|
||||
form,
|
||||
queryClient,
|
||||
onClose,
|
||||
}: FieldMutationOptions) {
|
||||
const createField = useMutation({
|
||||
mutationFn: (values: Omit<BrandFieldDefinition, "id" | "source">) =>
|
||||
client.createAdminField(values),
|
||||
onSuccess: () => {
|
||||
message.success("字段已创建");
|
||||
onClose();
|
||||
form.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
},
|
||||
});
|
||||
const removeField = useMutation({
|
||||
mutationFn: (id: string) => client.deleteAdminField(id),
|
||||
onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }),
|
||||
});
|
||||
return { createField, removeField };
|
||||
}
|
||||
|
||||
export function useInquiryFormMutations({
|
||||
client = createApiClient(),
|
||||
form,
|
||||
queryClient,
|
||||
onClose,
|
||||
}: {
|
||||
client?: ReturnType<typeof createApiClient>;
|
||||
form: FormInstance<Record<string, unknown>>;
|
||||
queryClient: {
|
||||
invalidateQueries: (options: { queryKey: readonly unknown[] }) => Promise<void>;
|
||||
};
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const createForm = useMutation({
|
||||
mutationFn: (values: {
|
||||
name: string;
|
||||
offeringId?: string;
|
||||
purpose?: InquiryForm["purpose"];
|
||||
targetType?: InquiryForm["targetType"];
|
||||
submissionAction?: InquiryForm["submissionAction"];
|
||||
fieldsSnapshot: unknown[];
|
||||
}) => client.createAdminInquiryForm(values),
|
||||
onSuccess: () => {
|
||||
message.success("咨询表单已创建");
|
||||
onClose();
|
||||
form.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-forms"] });
|
||||
},
|
||||
});
|
||||
const updateForm = useMutation({
|
||||
mutationFn: ({ id, body }: { id: string; body: Partial<InquiryForm> }) =>
|
||||
client.updateAdminInquiryForm(id, {
|
||||
...(body.name === undefined ? {} : { name: body.name }),
|
||||
...(body.offeringId == null ? {} : { offeringId: body.offeringId }),
|
||||
...(body.fieldsSnapshot === undefined ? {} : { fieldsSnapshot: body.fieldsSnapshot }),
|
||||
...(body.isEnabled === undefined ? {} : { isEnabled: body.isEnabled }),
|
||||
}),
|
||||
onSuccess: () => {
|
||||
message.success("咨询表单已更新");
|
||||
onClose();
|
||||
form.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-forms"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
|
||||
},
|
||||
});
|
||||
return { createForm, updateForm };
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { BrandTemplateKey } from "@personal-brand/api-client";
|
||||
|
||||
export interface IndustryTarget {
|
||||
key: BrandTemplateKey;
|
||||
name: string;
|
||||
description: string;
|
||||
capabilities: string[];
|
||||
}
|
||||
|
||||
export function supportsIndustry(
|
||||
visual: { supportedIndustryTemplates?: unknown },
|
||||
industry: string,
|
||||
): boolean {
|
||||
return (
|
||||
Array.isArray(visual.supportedIndustryTemplates) &&
|
||||
visual.supportedIndustryTemplates.includes(industry)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export function templatePreviewUrl(
|
||||
brandSlug: string | undefined,
|
||||
page: string,
|
||||
configured: string | undefined,
|
||||
parentOrigin?: string,
|
||||
route?: string,
|
||||
): string | undefined {
|
||||
const raw = configured || "http://localhost:3002";
|
||||
try {
|
||||
const url = new URL(raw, parentOrigin);
|
||||
url.searchParams.set("editor", "1");
|
||||
if (parentOrigin) url.searchParams.set("parentOrigin", parentOrigin);
|
||||
if (brandSlug) url.searchParams.set("brand", brandSlug);
|
||||
url.hash = route || `/pages/${encodeURIComponent(page)}/index`;
|
||||
return url.toString();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
interface ImportMetaEnv {
|
||||
readonly DEV: boolean;
|
||||
readonly PROD: boolean;
|
||||
readonly VITE_API_BASE_URL?: string;
|
||||
readonly VITE_APP_BASE_PATH?: string;
|
||||
readonly VITE_TEMPLATE_PREVIEW_URL?: string;
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
// 模板 CSS 使用 Taro 的 750 设计宽度,转换到预览容器单位。
|
||||
export function templatePreviewCss() {
|
||||
return {
|
||||
postcssPlugin: "template-preview-css",
|
||||
Once(root) {
|
||||
const file = root.source?.input.file || "";
|
||||
const templateStyle =
|
||||
file.includes("/packages/template-") && file.endsWith("/taro/style.css");
|
||||
const sharedFormStyle = file.endsWith("/apps/taro/src/components/forms.css");
|
||||
if (!templateStyle && !sharedFormStyle) return;
|
||||
root.walkRules((rule) => {
|
||||
rule.selector = rule.selector
|
||||
.split(",")
|
||||
.map(
|
||||
(selector) =>
|
||||
".component-template-preview__canvas " +
|
||||
selector
|
||||
.trim()
|
||||
.replace(
|
||||
/(^|[ >+~])(image|text|view)(?=[ .#:[>+~)]|$)/g,
|
||||
(_, prefix, tag) => prefix + { image: "img", text: "span", view: "div" }[tag],
|
||||
),
|
||||
)
|
||||
.join(", ");
|
||||
});
|
||||
root.walkDecls((declaration) => {
|
||||
// 组件预览中的固定按钮必须以页面画布为定位基准。
|
||||
if (declaration.prop === "position" && declaration.value === "fixed")
|
||||
declaration.value = "absolute";
|
||||
// 模板页面的视口高度按手机画布宽度计算,避免引用 Admin 浏览器高度。
|
||||
declaration.value = declaration.value.replace(/100vh/g, "178cqw");
|
||||
declaration.value = declaration.value.replace(
|
||||
/(-?(?:[0-9]*[.])?[0-9]+)px/g,
|
||||
(_, value) => Number((Number(value) / 7.5).toFixed(8)) + "cqw",
|
||||
);
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,9 +1,16 @@
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
applyPresentationValues,
|
||||
applyBrandPreviewValues,
|
||||
applyStandardEntityValues,
|
||||
filterSectionsForPreviewTarget,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
} from "../src/features/brand/presentation-bindings.ts";
|
||||
import {
|
||||
resolvePreviewSelection,
|
||||
previewTrustRecordId,
|
||||
} from "../src/features/brand/preview-selection.ts";
|
||||
|
||||
const config = {
|
||||
founder: "阿成",
|
||||
@@ -37,6 +44,21 @@ assert.equal(next.visualPresentation.inquiry.subtitle, "原说明");
|
||||
assert.equal(next.unrelatedSetting, true);
|
||||
assert.equal(config.founder, "阿成");
|
||||
|
||||
const previewSections = [
|
||||
{
|
||||
key: "home",
|
||||
fields: [
|
||||
{ key: "location", previewTarget: "home.location" },
|
||||
{ key: "hero", previewTarget: "home.hero" },
|
||||
],
|
||||
},
|
||||
{ key: "profile", fields: [{ key: "bio", previewTarget: "profile.bio" }] },
|
||||
];
|
||||
assert.deepEqual(filterSectionsForPreviewTarget(previewSections, "home.hero"), [
|
||||
{ key: "home", fields: [{ key: "hero", previewTarget: "home.hero" }] },
|
||||
]);
|
||||
assert.equal(filterSectionsForPreviewTarget(previewSections).length, 2);
|
||||
|
||||
const unsafe = applyPresentationValues(
|
||||
{ founder: "原主理人" },
|
||||
[
|
||||
@@ -108,3 +130,95 @@ const offering = applyPresentationValues(
|
||||
{ [presentationFieldName("offering", "background")]: "新背景" },
|
||||
);
|
||||
assert.deepEqual(offering.details, { background: "新背景", preserve: "保留" });
|
||||
|
||||
const brandDraft = applyBrandPreviewValues(
|
||||
{ description: "旧简介", address: "旧地址", config: { visualPresentation: {} } },
|
||||
{ visualPresentation: {} },
|
||||
[
|
||||
{
|
||||
key: "identity",
|
||||
fields: [
|
||||
{ key: "description", binding: "brand.description" },
|
||||
{ key: "address", binding: "brand.address" },
|
||||
{ key: "headline", binding: "brand.config.visualPresentation.home.title" },
|
||||
],
|
||||
},
|
||||
],
|
||||
{
|
||||
[presentationFieldName("identity", "description")]: "新简介",
|
||||
[presentationFieldName("identity", "address")]: "新地址",
|
||||
[presentationFieldName("identity", "headline")]: "新标题",
|
||||
},
|
||||
);
|
||||
assert.equal(brandDraft.description, "新简介");
|
||||
assert.equal(brandDraft.address, "新地址");
|
||||
assert.equal(brandDraft.config.visualPresentation.home.title, "新标题");
|
||||
|
||||
const entitySection = [
|
||||
{
|
||||
key: "card",
|
||||
fields: [
|
||||
{ key: "name", binding: "offering.name" },
|
||||
{ key: "summary", binding: "offering.summary" },
|
||||
{ key: "category", binding: "offering.config.categoryLabel" },
|
||||
],
|
||||
},
|
||||
];
|
||||
const updatedEntity = applyStandardEntityValues(
|
||||
{ id: "one", name: "旧名称", summary: "旧简介", config: { categoryLabel: "分类" } },
|
||||
"offering",
|
||||
entitySection,
|
||||
{ "card:name": "新名称", "card:summary": "新简介", "card:category": "新分类" },
|
||||
);
|
||||
assert.equal(updatedEntity.name, "新名称");
|
||||
assert.equal(updatedEntity.summary, "新简介");
|
||||
assert.equal(updatedEntity.id, "one");
|
||||
assert.deepEqual(updatedEntity.config, { categoryLabel: "分类" });
|
||||
assert.equal(readPresentationValue({}, "offering.name", undefined, updatedEntity), "新名称");
|
||||
|
||||
const targets = [
|
||||
{ key: "brand.hero", label: "主视觉", source: "brand", page: "home" },
|
||||
{ key: "offering.card", label: "餐品", source: "offering", page: "offerings" },
|
||||
];
|
||||
assert.deepEqual(resolvePreviewSelection("brand.hero", undefined, targets, "home"), {
|
||||
targetKey: "brand.hero",
|
||||
});
|
||||
assert.deepEqual(resolvePreviewSelection("offering.card", "one", targets, "offerings"), {
|
||||
targetKey: "offering.card",
|
||||
recordId: "one",
|
||||
});
|
||||
assert.deepEqual(resolvePreviewSelection("offering.card", undefined, targets, "offerings"), {
|
||||
targetKey: "offering.card",
|
||||
});
|
||||
assert.equal(resolvePreviewSelection("brand.hero", "one", targets, "home"), undefined);
|
||||
assert.equal(resolvePreviewSelection("brand.hero", undefined, targets, "offerings"), undefined);
|
||||
|
||||
// 未挂载的同源编辑入口不能清空已有字段。
|
||||
assert.deepEqual(
|
||||
applyPresentationValues(
|
||||
{ founder: "保留姓名", title: "保留职位" },
|
||||
[
|
||||
{
|
||||
key: "identity",
|
||||
fields: [
|
||||
{ key: "founder", binding: "brand.config.founder" },
|
||||
{ key: "title", binding: "brand.config.title" },
|
||||
],
|
||||
},
|
||||
],
|
||||
{ "identity:founder": "修改姓名" },
|
||||
),
|
||||
{ founder: "修改姓名", title: "保留职位" },
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
previewTrustRecordId(
|
||||
[
|
||||
{ id: "plain", type: "credential", config: {} },
|
||||
{ id: "structured", type: "credential", config: { stats: [] } },
|
||||
],
|
||||
"credential",
|
||||
),
|
||||
"structured",
|
||||
);
|
||||
assert.equal(previewTrustRecordId([], "credential"), undefined);
|
||||
@@ -0,0 +1,33 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { templatePreviewUrl } from "../src/lib/template-preview.ts";
|
||||
|
||||
test("template preview URL is resolved from one shared deployment address", () => {
|
||||
const url = templatePreviewUrl(
|
||||
"brand-a",
|
||||
"profile",
|
||||
"https://preview.example.test/app/",
|
||||
"https://admin.example.test",
|
||||
"/pages/profile/index",
|
||||
);
|
||||
assert.equal(
|
||||
url,
|
||||
"https://preview.example.test/app/?editor=1&parentOrigin=https%3A%2F%2Fadmin.example.test&brand=brand-a#/pages/profile/index",
|
||||
);
|
||||
});
|
||||
|
||||
test("the shared same-origin preview address is the default", () => {
|
||||
assert.equal(
|
||||
templatePreviewUrl("brand-a", "home", undefined),
|
||||
"http://localhost:3002/?editor=1&brand=brand-a#/pages/home/index",
|
||||
);
|
||||
assert.equal(templatePreviewUrl("brand-a", "home", "{"), undefined);
|
||||
assert.equal(templatePreviewUrl("brand-a", "home", "not a URL"), undefined);
|
||||
});
|
||||
|
||||
test("same-origin static preview uses its explicit entry document", () => {
|
||||
assert.equal(
|
||||
templatePreviewUrl("brand-a", "home", "/template-preview/index.html", "http://localhost:3005"),
|
||||
"http://localhost:3005/template-preview/index.html?editor=1&parentOrigin=http%3A%2F%2Flocalhost%3A3005&brand=brand-a#/pages/home/index",
|
||||
);
|
||||
});
|
||||
@@ -1,9 +1,25 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { templatePreviewCss } from "./template-preview-css.mjs";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
css: { postcss: { plugins: [templatePreviewCss()] } },
|
||||
base: process.env.VITE_APP_BASE_PATH ?? "/",
|
||||
resolve: {
|
||||
dedupe: ["react", "react-dom"],
|
||||
alias: {
|
||||
"@tarojs/components": `${process.cwd()}/src/features/brand/taro-web-components.jsx`,
|
||||
"@tarojs/taro": `${process.cwd()}/src/features/brand/taro-web-runtime.jsx`,
|
||||
},
|
||||
},
|
||||
define: {
|
||||
"process.env": "{}",
|
||||
"process.env.TARO_PLATFORM": JSON.stringify("web"),
|
||||
"process.env.TARO_ENV": JSON.stringify("h5"),
|
||||
PREVIEW_ALL_TEMPLATES: JSON.stringify(true),
|
||||
TEMPLATE_MANIFEST: JSON.stringify({ navigation: [] }),
|
||||
},
|
||||
server: {
|
||||
host: "0.0.0.0",
|
||||
port: Number(process.env.ADMIN_PORT ?? 3000),
|
||||
@@ -12,6 +28,19 @@ export default defineConfig({
|
||||
target: process.env.VITE_DEV_API_TARGET ?? "http://localhost:3001",
|
||||
rewrite: (path) => path.replace(/^\/api/, ""),
|
||||
},
|
||||
"/media": {
|
||||
target: process.env.VITE_MEDIA_API_TARGET ?? "http://localhost:3001",
|
||||
changeOrigin: true,
|
||||
},
|
||||
...(process.env.VITE_MEDIA_PROXY_TARGET
|
||||
? {
|
||||
[`/${(process.env.OBJECT_STORAGE_BUCKET ?? "personal-brand-media").replace(/^\/+/, "")}`]:
|
||||
{
|
||||
target: process.env.VITE_MEDIA_PROXY_TARGET,
|
||||
changeOrigin: true,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
build: { outDir: "dist" },
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
FROM node:22-alpine AS base
|
||||
ENV PNPM_HOME=/pnpm
|
||||
ENV PATH="$PNPM_HOME:$PATH"
|
||||
RUN corepack enable \
|
||||
&& apk add --no-cache openssl libc6-compat
|
||||
WORKDIR /app
|
||||
|
||||
FROM base AS build
|
||||
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json ./
|
||||
COPY tsconfig.base.json ./
|
||||
COPY packages ./packages
|
||||
COPY apps/api/package.json apps/api/package.json
|
||||
COPY apps/api/tsconfig.json apps/api/tsconfig.json
|
||||
COPY apps/api/prisma ./apps/api/prisma
|
||||
COPY apps/api/src ./apps/api/src
|
||||
RUN pnpm install --frozen-lockfile
|
||||
RUN pnpm --filter @personal-brand/config build
|
||||
RUN pnpm --filter @personal-brand/types build
|
||||
RUN pnpm --filter @personal-brand/validation build
|
||||
RUN pnpm --filter @personal-brand/api exec prisma generate
|
||||
RUN pnpm --filter @personal-brand/api build
|
||||
RUN pnpm --filter @personal-brand/api --prod deploy /out/api
|
||||
|
||||
FROM base AS runtime
|
||||
ENV NODE_ENV=production
|
||||
WORKDIR /app
|
||||
COPY --from=build /out/api ./
|
||||
COPY --from=build /app/apps/api/dist ./dist
|
||||
COPY --from=build /app/apps/api/prisma ./prisma
|
||||
COPY --from=build /app/packages/config/dist ./node_modules/@personal-brand/config/dist
|
||||
COPY --from=build /app/packages/types/dist ./node_modules/@personal-brand/types/dist
|
||||
COPY --from=build /app/packages/validation/dist ./node_modules/@personal-brand/validation/dist
|
||||
RUN mkdir -p /app/media /app/seed-media
|
||||
COPY apps/api/prisma/assets/ /app/seed-media/
|
||||
COPY docker/api-entrypoint.sh /usr/local/bin/api-entrypoint.sh
|
||||
RUN chmod +x /usr/local/bin/api-entrypoint.sh \
|
||||
&& chown -R node:node /app
|
||||
USER node
|
||||
EXPOSE 3001
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
CMD node -e "fetch('http://127.0.0.1:'+(process.env.API_PORT||3001)+'/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"
|
||||
ENTRYPOINT ["/usr/local/bin/api-entrypoint.sh"]
|
||||
CMD ["node", "dist/main.js"]
|
||||
@@ -8,7 +8,7 @@
|
||||
"lint": "eslint .",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "tsx --test test/**/*.test.ts",
|
||||
"test:integration": "pnpm build && node --env-file=.env test/run-integration.cjs",
|
||||
"test:integration": "pnpm build && node --env-file=.env test/run-integration.cjs && pnpm --filter @personal-brand/api exec tsx --test test/http.upload.test.js",
|
||||
"clean": "rimraf dist",
|
||||
"start": "node dist/main.js",
|
||||
"db:generate": "prisma generate",
|
||||
@@ -17,6 +17,10 @@
|
||||
"db:seed": "tsx prisma/seed.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.1149.0",
|
||||
"@aws-sdk/s3-request-presigner": "^3.1149.0",
|
||||
"@fastify/multipart": "^10.1.3",
|
||||
"@fastify/static": "^10.1.6",
|
||||
"@nestjs/common": "^11.0.11",
|
||||
"@nestjs/core": "^11.0.11",
|
||||
"@nestjs/platform-fastify": "^11.0.11",
|
||||
@@ -27,13 +31,13 @@
|
||||
"bcryptjs": "^2.4.3",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.1",
|
||||
"fastify": "^5.2.1",
|
||||
"fastify": "^5.11.3",
|
||||
"prisma": "^6.2.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.5",
|
||||
"prisma": "^6.2.1",
|
||||
"tsx": "^4.19.2"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 125 KiB |
|
After Width: | Height: | Size: 163 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 182 KiB |
|
After Width: | Height: | Size: 167 KiB |
|
After Width: | Height: | Size: 154 KiB |
|
After Width: | Height: | Size: 250 KiB |
|
After Width: | Height: | Size: 151 KiB |
|
After Width: | Height: | Size: 210 KiB |
@@ -0,0 +1,5 @@
|
||||
-- Normalize offering category storage: categoryKey is authoritative.
|
||||
-- Display labels are projected from the active template manifest.
|
||||
UPDATE "Offering"
|
||||
SET "config" = "config" - 'categoryLabel'
|
||||
WHERE "config" IS NOT NULL;
|
||||
@@ -0,0 +1,136 @@
|
||||
-- Replace development seed remote images with local media paths.
|
||||
UPDATE "Offering"
|
||||
SET "config" = CASE
|
||||
WHEN jsonb_typeof("config") = 'array' THEN
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
CASE
|
||||
WHEN jsonb_typeof(item->'url') = 'string' THEN
|
||||
jsonb_set(
|
||||
item,
|
||||
'{url}',
|
||||
to_jsonb(
|
||||
CASE
|
||||
WHEN item->>'url' LIKE '%1547592180-85f173990554%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN item->>'url' LIKE '%1603133872878-684f208fb84b%' THEN '/media/seed/seed-02.jpg'
|
||||
WHEN item->>'url' LIKE '%1559847844-5315695dadae%' THEN '/media/seed/seed-03.jpg'
|
||||
WHEN item->>'url' LIKE '%1513694203232-719a280e022f%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN item->>'url' LIKE '%1541123437800-1bb1317badc2%' THEN '/media/seed/seed-02.jpg'
|
||||
WHEN item->>'url' LIKE '%1505691938895-1758d7feb511%' THEN '/media/seed/seed-03.jpg'
|
||||
WHEN item->>'url' LIKE '%1600210492486-724fe5c67fb0%' THEN '/media/seed/seed-03.jpg'
|
||||
ELSE item->>'url'
|
||||
END
|
||||
)
|
||||
)
|
||||
ELSE item
|
||||
END
|
||||
)
|
||||
FROM jsonb_array_elements("config") AS item
|
||||
)
|
||||
ELSE "config"
|
||||
END
|
||||
WHERE jsonb_typeof("config") = 'array';
|
||||
|
||||
UPDATE "Offering"
|
||||
SET "config" = jsonb_set(
|
||||
"config",
|
||||
'{media}',
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
CASE
|
||||
WHEN jsonb_typeof(item->'url') = 'string' THEN
|
||||
jsonb_set(
|
||||
item,
|
||||
'{url}',
|
||||
to_jsonb(
|
||||
CASE
|
||||
WHEN item->>'url' LIKE '%1600210492486-724fe5c67fb0%' THEN '/media/seed/seed-03.jpg'
|
||||
ELSE item->>'url'
|
||||
END
|
||||
)
|
||||
)
|
||||
ELSE item
|
||||
END
|
||||
)
|
||||
FROM jsonb_array_elements("config"->'media') AS item
|
||||
)
|
||||
)
|
||||
WHERE "config" ? 'media'
|
||||
AND "config"::text LIKE '%1600210492486-724fe5c67fb0%';
|
||||
|
||||
UPDATE "Offering"
|
||||
SET "coverUrl" = '/media/seed/seed-03.jpg'
|
||||
WHERE "coverUrl" LIKE '%1600210492486-724fe5c67fb0%';
|
||||
|
||||
UPDATE "Offering"
|
||||
SET "coverUrl" = CASE
|
||||
WHEN "coverUrl" LIKE '%1547592180-85f173990554%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN "coverUrl" LIKE '%1603133872878-684f208fb84b%' THEN '/media/seed/seed-02.jpg'
|
||||
WHEN "coverUrl" LIKE '%1559847844-5315695dadae%' THEN '/media/seed/seed-03.jpg'
|
||||
WHEN "coverUrl" LIKE '%1513694203232-719a280e022f%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN "coverUrl" LIKE '%1541123437800-1bb1317badc2%' THEN '/media/seed/seed-02.jpg'
|
||||
WHEN "coverUrl" LIKE '%1505691938895-1758d7feb511%' THEN '/media/seed/seed-03.jpg'
|
||||
ELSE "coverUrl"
|
||||
END,
|
||||
"config" = CASE
|
||||
WHEN "config" ? 'media' THEN
|
||||
CASE
|
||||
WHEN jsonb_typeof("config"->'media') = 'array' THEN
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
CASE
|
||||
WHEN jsonb_typeof(item->'url') = 'string' THEN
|
||||
jsonb_set(
|
||||
item,
|
||||
'{url}',
|
||||
to_jsonb(
|
||||
CASE
|
||||
WHEN item->>'url' LIKE '%1547592180-85f173990554%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN item->>'url' LIKE '%1603133872878-684f208fb84b%' THEN '/media/seed/seed-02.jpg'
|
||||
WHEN item->>'url' LIKE '%1559847844-5315695dadae%' THEN '/media/seed/seed-03.jpg'
|
||||
WHEN item->>'url' LIKE '%1513694203232-719a280e022f%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN item->>'url' LIKE '%1541123437800-1bb1317badc2%' THEN '/media/seed/seed-02.jpg'
|
||||
WHEN item->>'url' LIKE '%1505691938895-1758d7feb511%' THEN '/media/seed/seed-03.jpg'
|
||||
ELSE item->>'url'
|
||||
END
|
||||
)
|
||||
)
|
||||
ELSE item
|
||||
END
|
||||
)
|
||||
FROM jsonb_array_elements("config"->'media') AS item
|
||||
)
|
||||
ELSE "config"->'media'
|
||||
END
|
||||
ELSE "config"
|
||||
END
|
||||
WHERE "config" IS NOT NULL;
|
||||
|
||||
UPDATE "Offering"
|
||||
SET "config" = jsonb_set(
|
||||
"config",
|
||||
'{detailHero}',
|
||||
to_jsonb(
|
||||
CASE
|
||||
WHEN "config"->>'detailHero' LIKE '%1600210492486-724fe5c67fb0%' THEN '/media/seed/seed-03.jpg'
|
||||
ELSE "config"->>'detailHero'
|
||||
END
|
||||
)
|
||||
)
|
||||
WHERE "config" ? 'detailHero';
|
||||
|
||||
UPDATE "BrandProfile"
|
||||
SET "config" = jsonb_set(
|
||||
"config",
|
||||
'{heroImage}',
|
||||
to_jsonb(
|
||||
CASE
|
||||
WHEN "config"->>'heroImage' LIKE '%1556761175-b413da4baf72%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN "config"->>'heroImage' LIKE '%1521737711867-e3b97375f902%' THEN '/media/seed/seed-02.jpg'
|
||||
WHEN "config"->>'heroImage' LIKE '%1513694203232-719a280e022f%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN "config"->>'heroImage' LIKE '%1547592180-85f173990554%' THEN '/media/seed/seed-01.jpg'
|
||||
ELSE "config"->>'heroImage'
|
||||
END
|
||||
)
|
||||
)
|
||||
WHERE "config" ? 'heroImage';
|
||||
@@ -0,0 +1,56 @@
|
||||
-- Normalize historical publication snapshots to canonical local media paths.
|
||||
UPDATE "BrandRelease"
|
||||
SET "snapshot" = replace(
|
||||
replace(
|
||||
replace(
|
||||
"snapshot"::text,
|
||||
'https://images.unsplash.com/photo-1547592180-85f173990554?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-01.jpg'
|
||||
),
|
||||
'https://images.unsplash.com/photo-1603133872878-684f208fb84b?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-02.jpg'
|
||||
),
|
||||
'https://images.unsplash.com/photo-1559847844-5315695dadae?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-03.jpg'
|
||||
)::jsonb
|
||||
WHERE "snapshot"::text LIKE '%images.unsplash.com%';
|
||||
|
||||
UPDATE "BrandRelease"
|
||||
SET "snapshot" = replace(
|
||||
replace(
|
||||
replace(
|
||||
"snapshot"::text,
|
||||
'https://images.unsplash.com/photo-1513694203232-719a280e022f?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-01.jpg'
|
||||
),
|
||||
'https://images.unsplash.com/photo-1541123437800-1bb1317badc2?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-02.jpg'
|
||||
),
|
||||
'https://images.unsplash.com/photo-1505691938895-1758d7feb511?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-03.jpg'
|
||||
)::jsonb
|
||||
WHERE "snapshot"::text LIKE '%images.unsplash.com%';
|
||||
|
||||
UPDATE "BrandRelease"
|
||||
SET "snapshot" = replace(
|
||||
replace(
|
||||
"snapshot"::text,
|
||||
'https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-03.jpg'
|
||||
),
|
||||
'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?auto=format&fit=crop&w=240&h=240&q=80',
|
||||
'/media/seed/seed-01.jpg'
|
||||
)::jsonb
|
||||
WHERE "snapshot"::text LIKE '%images.unsplash.com%';
|
||||
|
||||
UPDATE "BrandRelease"
|
||||
SET "snapshot" = replace(
|
||||
replace(
|
||||
"snapshot"::text,
|
||||
'https://images.unsplash.com/photo-1556761175-b413da4baf72?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-01.jpg'
|
||||
),
|
||||
'https://images.unsplash.com/photo-1521737711867-e3b97375f902?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-02.jpg'
|
||||
)::jsonb
|
||||
WHERE "snapshot"::text LIKE '%images.unsplash.com%';
|
||||
@@ -0,0 +1,2 @@
|
||||
DELETE FROM "BrandProfile"
|
||||
WHERE "slug" = 'linran-brand';
|
||||
@@ -0,0 +1,72 @@
|
||||
-- Restore collapsed seed media placeholders to their original per-role local files.
|
||||
UPDATE "Offering"
|
||||
SET "coverUrl" = CASE "coverUrl"
|
||||
WHEN '/media/seed/seed-01.jpg' THEN CASE "name"
|
||||
WHEN '红烧肉双拼套餐' THEN '/media/seed/food-package-01.jpg'
|
||||
WHEN '当代铸铜木核防暴装甲门' THEN '/media/seed/doors-hero.jpg'
|
||||
ELSE '/media/seed/personal-consulting.jpg'
|
||||
END
|
||||
WHEN '/media/seed/seed-02.jpg' THEN CASE "name"
|
||||
WHEN '小炒鸡套餐' THEN '/media/seed/food-package-02.jpg'
|
||||
WHEN '悬挑风琴式耐候双开院门' THEN '/media/seed/doors-yard-gate.jpg'
|
||||
ELSE '/media/seed/personal-advisory.jpg'
|
||||
END
|
||||
WHEN '/media/seed/seed-03.jpg' THEN CASE "name"
|
||||
WHEN '家庭聚餐私厨' THEN '/media/seed/food-private-chef.jpg'
|
||||
WHEN '通顶极窄边框实木室内门' THEN '/media/seed/doors-room-door.jpg'
|
||||
WHEN '石材及皮质背景墙一体门' THEN '/media/seed/doors-stone-wall.jpg'
|
||||
ELSE '/media/seed/personal-consulting.jpg'
|
||||
END
|
||||
END
|
||||
WHERE "coverUrl" IN ('/media/seed/seed-01.jpg', '/media/seed/seed-02.jpg', '/media/seed/seed-03.jpg');
|
||||
|
||||
UPDATE "Offering"
|
||||
SET "config" = replace(
|
||||
replace(
|
||||
replace(
|
||||
"config"::text,
|
||||
'/media/seed/seed-01.jpg',
|
||||
'/media/seed/food-package-01.jpg'
|
||||
),
|
||||
'/media/seed/seed-02.jpg',
|
||||
'/media/seed/food-package-02.jpg'
|
||||
),
|
||||
'/media/seed/seed-03.jpg',
|
||||
'/media/seed/food-private-chef.jpg'
|
||||
)::jsonb
|
||||
WHERE "config"::text LIKE '%/media/seed/seed-0%' AND "name" IN ('红烧肉双拼套餐', '小炒鸡套餐', '家庭聚餐私厨');
|
||||
|
||||
UPDATE "Offering"
|
||||
SET "config" = replace(
|
||||
replace(
|
||||
replace(
|
||||
"config"::text,
|
||||
'/media/seed/seed-01.jpg',
|
||||
'/media/seed/doors-hero.jpg'
|
||||
),
|
||||
'/media/seed/seed-02.jpg',
|
||||
'/media/seed/doors-yard-gate.jpg'
|
||||
),
|
||||
'/media/seed/seed-03.jpg',
|
||||
CASE "name"
|
||||
WHEN '通顶极窄边框实木室内门' THEN '/media/seed/doors-room-door.jpg'
|
||||
ELSE '/media/seed/doors-stone-wall.jpg'
|
||||
END
|
||||
)::jsonb
|
||||
WHERE "config"::text LIKE '%/media/seed/seed-0%' AND "name" LIKE '%门';
|
||||
|
||||
UPDATE "BrandProfile"
|
||||
SET "config" = replace(
|
||||
replace(
|
||||
replace(
|
||||
"config"::text,
|
||||
'/media/seed/seed-01.jpg',
|
||||
CASE "templateKey" WHEN 'doors' THEN '/media/seed/doors-hero.jpg' ELSE '/media/seed/personal-consulting.jpg' END
|
||||
),
|
||||
'/media/seed/seed-02.jpg',
|
||||
'/media/seed/personal-advisory.jpg'
|
||||
),
|
||||
'/media/seed/seed-03.jpg',
|
||||
'/media/seed/doors-room-door.jpg'
|
||||
)::jsonb
|
||||
WHERE "config"::text LIKE '%/media/seed/seed-0%';
|
||||
@@ -0,0 +1,32 @@
|
||||
-- Keep publication snapshots aligned with restored original seed media paths.
|
||||
UPDATE "BrandRelease"
|
||||
SET "snapshot" = replace(
|
||||
replace(
|
||||
replace(
|
||||
"snapshot"::text,
|
||||
'/media/seed/seed-01.jpg',
|
||||
'/media/seed/food-package-01.jpg'
|
||||
),
|
||||
'/media/seed/seed-02.jpg',
|
||||
'/media/seed/food-package-02.jpg'
|
||||
),
|
||||
'/media/seed/seed-03.jpg',
|
||||
'/media/seed/food-private-chef.jpg'
|
||||
)::jsonb
|
||||
WHERE "brandId" = '00000000-0000-0000-0000-000000000001';
|
||||
|
||||
UPDATE "BrandRelease"
|
||||
SET "snapshot" = replace(
|
||||
replace(
|
||||
replace(
|
||||
"snapshot"::text,
|
||||
'/media/seed/seed-01.jpg',
|
||||
'/media/seed/doors-hero.jpg'
|
||||
),
|
||||
'/media/seed/seed-02.jpg',
|
||||
'/media/seed/doors-yard-gate.jpg'
|
||||
),
|
||||
'/media/seed/seed-03.jpg',
|
||||
'/media/seed/doors-room-door.jpg'
|
||||
)::jsonb
|
||||
WHERE "brandId" = '00000000-0000-0000-0000-000000000002';
|
||||
@@ -0,0 +1,30 @@
|
||||
-- Restore non-runtime sample offerings by brand visual context.
|
||||
UPDATE "Offering" o
|
||||
SET "coverUrl" = '/media/seed/food-package-01.jpg'
|
||||
FROM "BrandProfile" b
|
||||
WHERE o."brandId" = b.id AND b.slug = 'default-brand' AND o.name IN ('家庭聚餐定制', '示例·今日套餐');
|
||||
|
||||
UPDATE "Offering" o
|
||||
SET "coverUrl" = '/media/seed/food-package-02.jpg'
|
||||
FROM "BrandProfile" b
|
||||
WHERE o."brandId" = b.id AND b.slug = 'default-brand' AND o.name IN ('示例·品牌定位咨询', '示例·聚餐定制');
|
||||
|
||||
UPDATE "Offering" o
|
||||
SET "coverUrl" = '/media/seed/doors-hero.jpg'
|
||||
FROM "BrandProfile" b
|
||||
WHERE o."brandId" = b.id AND b.slug = 'linjing-doors' AND o.name IN ('序章·入户门', '别墅入户大门');
|
||||
|
||||
UPDATE "Offering" o
|
||||
SET "coverUrl" = '/media/seed/doors-yard-gate.jpg'
|
||||
FROM "BrandProfile" b
|
||||
WHERE o."brandId" = b.id AND b.slug = 'linjing-doors' AND o.name IN ('庭院·边界门', '院门与围合系统');
|
||||
|
||||
UPDATE "Offering" o
|
||||
SET "coverUrl" = '/media/seed/doors-room-door.jpg'
|
||||
FROM "BrandProfile" b
|
||||
WHERE o."brandId" = b.id AND b.slug = 'linjing-doors' AND o.name IN ('室内户内门系统', '室内·静谧门');
|
||||
|
||||
UPDATE "Offering" o
|
||||
SET "coverUrl" = '/media/seed/doors-stone-wall.jpg'
|
||||
FROM "BrandProfile" b
|
||||
WHERE o."brandId" = b.id AND b.slug = 'linjing-doors' AND o.name = '一对一门系统设计咨询';
|
||||
@@ -1,5 +1,6 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
binaryTargets = ["linux-musl-openssl-3.0.x", "debian-openssl-3.0.x"]
|
||||
}
|
||||
|
||||
datasource db {
|
||||
|
||||