Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d2ca528543 | ||
|
|
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 |
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
|
SESSION_SECRET=replace-with-a-long-random-value
|
||||||
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
||||||
SEED_ADMIN_PASSWORD=change-me-now-123
|
SEED_ADMIN_PASSWORD=change-me-now-123
|
||||||
OBJECT_STORAGE_ENDPOINT=
|
OBJECT_STORAGE_ENDPOINT=http://localhost:9000
|
||||||
OBJECT_STORAGE_BUCKET=
|
OBJECT_STORAGE_PUBLIC_URL=http://localhost:9000/personal-brand-media
|
||||||
OBJECT_STORAGE_ACCESS_KEY=
|
OBJECT_STORAGE_BUCKET=personal-brand-media
|
||||||
OBJECT_STORAGE_SECRET_KEY=
|
OBJECT_STORAGE_ACCESS_KEY=minioadmin
|
||||||
|
OBJECT_STORAGE_SECRET_KEY=minioadmin
|
||||||
WECHAT_APP_ID=
|
WECHAT_APP_ID=
|
||||||
WECHAT_APP_SECRET=
|
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: 24
|
||||||
|
cache: pnpm
|
||||||
|
- run: pnpm install --frozen-lockfile
|
||||||
|
- run: pnpm check
|
||||||
|
- run: pnpm template:doctor
|
||||||
|
|
||||||
|
build:
|
||||||
|
name: Production build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [static]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: 9.15.0
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
cache: pnpm
|
||||||
|
- run: pnpm install --frozen-lockfile
|
||||||
|
- run: pnpm build:admin:preview
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: admin-dist
|
||||||
|
path: apps/admin/dist
|
||||||
|
retention-days: 7
|
||||||
|
|
||||||
|
api:
|
||||||
|
name: API integration
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [static]
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
env:
|
||||||
|
POSTGRES_USER: postgres
|
||||||
|
POSTGRES_PASSWORD: postgres
|
||||||
|
POSTGRES_DB: personal_brand
|
||||||
|
ports:
|
||||||
|
- 5432:5432
|
||||||
|
options: >-
|
||||||
|
--health-cmd "pg_isready -U postgres -d personal_brand"
|
||||||
|
--health-interval 5s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 12
|
||||||
|
env:
|
||||||
|
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/personal_brand
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: 9.15.0
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
cache: pnpm
|
||||||
|
- run: pnpm install --frozen-lockfile
|
||||||
|
- run: pnpm --filter @personal-brand/api test:integration
|
||||||
|
|
||||||
|
browser:
|
||||||
|
name: Browser regression
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [build]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: 9.15.0
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
cache: pnpm
|
||||||
|
- run: pnpm install --frozen-lockfile
|
||||||
|
- run: pnpm --filter @personal-brand/taro exec playwright install --with-deps chromium
|
||||||
|
- run: pnpm --filter @personal-brand/api test:integration
|
||||||
|
env:
|
||||||
|
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/personal_brand
|
||||||
|
- name: Start API
|
||||||
|
run: pnpm --filter @personal-brand/api start > /tmp/api.log 2>&1 &
|
||||||
|
env:
|
||||||
|
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/personal_brand
|
||||||
|
NODE_ENV: development
|
||||||
|
- name: Start mini program preview
|
||||||
|
run: pnpm --filter @personal-brand/taro dev:h5 > /tmp/taro.log 2>&1 &
|
||||||
|
env:
|
||||||
|
API_BASE_URL: http://localhost:3001
|
||||||
|
BRAND_SLUG: default-brand
|
||||||
|
TEMPLATE_KEY: acheng-campus-food
|
||||||
|
- name: Start admin
|
||||||
|
run: pnpm --filter @personal-brand/admin dev > /tmp/admin.log 2>&1 &
|
||||||
|
env:
|
||||||
|
VITE_API_BASE_URL: /api
|
||||||
|
VITE_DEV_API_TARGET: http://localhost:3001
|
||||||
|
VITE_TEMPLATE_PREVIEW_URL: http://localhost:3002
|
||||||
|
- name: Wait for services
|
||||||
|
run: |
|
||||||
|
curl --retry 30 --retry-delay 1 --retry-connrefused -fsS http://localhost:3001/health
|
||||||
|
curl --retry 30 --retry-delay 1 --retry-connrefused -fsS http://localhost:3002
|
||||||
|
curl --retry 30 --retry-delay 1 --retry-connrefused -fsS http://localhost:3000
|
||||||
|
- run: pnpm --filter @personal-brand/taro exec playwright test --config=playwright.config.ts --reporter=line
|
||||||
@@ -2,11 +2,13 @@ node_modules/
|
|||||||
.pnpm-store/
|
.pnpm-store/
|
||||||
.turbo/
|
.turbo/
|
||||||
dist/
|
dist/
|
||||||
|
packages/config/dist/
|
||||||
.next/
|
.next/
|
||||||
coverage/
|
coverage/
|
||||||
.env
|
.env
|
||||||
.env.*
|
|
||||||
!.env.example
|
!.env.example
|
||||||
|
.env.production
|
||||||
|
!.env.production.example
|
||||||
*.log
|
*.log
|
||||||
.DS_Store
|
.DS_Store
|
||||||
apps/miniapp/miniprogram_npm/
|
apps/miniapp/miniprogram_npm/
|
||||||
@@ -14,8 +16,13 @@ apps/miniapp/project.private.config.json
|
|||||||
|
|
||||||
.worktrees/
|
.worktrees/
|
||||||
apps/taro/src/assets/
|
apps/taro/src/assets/
|
||||||
|
apps/admin/public/template-preview/
|
||||||
|
|
||||||
apps/taro/test-results/
|
apps/taro/test-results/
|
||||||
apps/taro/playwright-report/
|
apps/taro/playwright-report/
|
||||||
|
media/
|
||||||
|
|
||||||
**/.swc/
|
**/.swc/
|
||||||
|
.codex-tasks/
|
||||||
|
docker-compose.override.yml
|
||||||
|
.env.production
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
node_modules
|
node_modules
|
||||||
.turbo
|
.turbo
|
||||||
dist
|
dist
|
||||||
|
apps/admin/public/template-preview
|
||||||
.next
|
.next
|
||||||
prototype
|
prototype
|
||||||
pnpm-lock.yaml
|
pnpm-lock.yaml
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# Product Direction
|
# 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.
|
- 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.
|
- 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.
|
- 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,4 +2,5 @@ VITE_APP_BASE_PATH=/admin/
|
|||||||
VITE_API_BASE_URL=/api
|
VITE_API_BASE_URL=/api
|
||||||
VITE_DEV_API_TARGET=http://localhost:3001
|
VITE_DEV_API_TARGET=http://localhost:3001
|
||||||
ADMIN_PORT=3000
|
ADMIN_PORT=3000
|
||||||
VITE_TEMPLATE_PREVIEW_URLS={"acheng-campus-food":"http://localhost:3002","linjing-editorial":"http://localhost:3003"}
|
VITE_TEMPLATE_PREVIEW_URL=http://localhost:3002
|
||||||
|
VITE_MEDIA_PROXY_TARGET=http://localhost:9000
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@ant-design/icons": "^6.3.4",
|
||||||
"@personal-brand/api-client": "workspace:*",
|
"@personal-brand/api-client": "workspace:*",
|
||||||
"@tanstack/react-query": "^5.103.1",
|
"@tanstack/react-query": "^5.103.1",
|
||||||
"antd": "^6.6.4",
|
"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 {
|
interface ImageUrlFieldProps {
|
||||||
|
id?: string;
|
||||||
value?: string;
|
value?: string;
|
||||||
onChange?: (value: string) => void;
|
onChange?: (value: string) => void;
|
||||||
placeholder?: string;
|
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 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 (
|
return (
|
||||||
<Space direction="vertical" size={8} style={{ width: "100%" }}>
|
<Space direction="vertical" size={4} style={{ width: "100%" }}>
|
||||||
<Input
|
{storageStatus !== "ok" ? (
|
||||||
value={value}
|
<Alert
|
||||||
onChange={(event) => onChange?.(event.target.value)}
|
type={storageStatus === "loading" ? "info" : "warning"}
|
||||||
placeholder={placeholder ?? "粘贴图片地址"}
|
showIcon
|
||||||
|
message={
|
||||||
|
storageStatus === "loading"
|
||||||
|
? "正在检查媒体存储..."
|
||||||
|
: storageStatus === "unconfigured"
|
||||||
|
? "媒体存储未配置,请先设置对象存储"
|
||||||
|
: "媒体存储不可用,请检查对象存储配置"
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
|
) : null}
|
||||||
{imageUrl ? (
|
{imageUrl ? (
|
||||||
<Space align="start">
|
<div
|
||||||
|
style={{
|
||||||
|
position: "relative",
|
||||||
|
width: "100%",
|
||||||
|
minHeight: 140,
|
||||||
|
borderRadius: 8,
|
||||||
|
overflow: "hidden",
|
||||||
|
border: "1px solid #d9d9d9",
|
||||||
|
background: "#f5f5f5",
|
||||||
|
}}
|
||||||
|
>
|
||||||
<Image
|
<Image
|
||||||
src={imageUrl}
|
src={imageUrl}
|
||||||
width={96}
|
alt={placeholder ?? "图片预览"}
|
||||||
height={64}
|
width="100%"
|
||||||
|
height={180}
|
||||||
preview
|
preview
|
||||||
|
style={{ objectFit: "cover" }}
|
||||||
fallback="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="
|
fallback="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="
|
||||||
style={{ objectFit: "cover", borderRadius: 8, background: "#f5f5f5" }}
|
|
||||||
/>
|
/>
|
||||||
<Typography.Text type="secondary">预览图</Typography.Text>
|
<Popconfirm title="移除这张图片?" onConfirm={() => onChange?.("")}>
|
||||||
</Space>
|
<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}
|
) : null}
|
||||||
|
<input {...(id ? { id } : {})} type="hidden" value={imageUrl} />
|
||||||
</Space>
|
</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";
|
import type { TemplateAdminField } from "@personal-brand/api-client";
|
||||||
|
|
||||||
export function TemplateListField({
|
export function TemplateListField({
|
||||||
@@ -21,15 +27,82 @@ export function TemplateListField({
|
|||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
>
|
>
|
||||||
{(rows, { add, remove }, { errors }) => (
|
{(rows, { add, remove, move }, { errors }) => (
|
||||||
<Space direction="vertical" style={{ width: "100%" }}>
|
<Space direction="vertical" size={12} style={{ width: "100%" }}>
|
||||||
{rows.map((row, index) => (
|
{rows.length === 0 ? (
|
||||||
<Space key={row.key} align="start" wrap>
|
<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) => (
|
{field.itemFields?.map((itemField) => (
|
||||||
<Form.Item
|
<Form.Item
|
||||||
key={itemField.key}
|
key={itemField.key}
|
||||||
name={[row.name, itemField.key]}
|
name={[row.name, itemField.key]}
|
||||||
label={`${index + 1}. ${itemField.label}`}
|
label={itemField.label}
|
||||||
rules={
|
rules={
|
||||||
itemField.required === false
|
itemField.required === false
|
||||||
? []
|
? []
|
||||||
@@ -39,11 +112,29 @@ export function TemplateListField({
|
|||||||
{itemField.input === "textarea" ? <Input.TextArea rows={2} /> : <Input />}
|
{itemField.input === "textarea" ? <Input.TextArea rows={2} /> : <Input />}
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
))}
|
))}
|
||||||
<Button onClick={() => remove(row.name)}>删除</Button>
|
</Card>
|
||||||
</Space>
|
);
|
||||||
))}
|
})}
|
||||||
|
{rows.length > 1 ? (
|
||||||
|
<Collapse
|
||||||
|
ghost
|
||||||
|
items={[
|
||||||
|
{
|
||||||
|
key: "sort-help",
|
||||||
|
label: "排序说明",
|
||||||
|
children: (
|
||||||
|
<Typography.Text type="secondary">
|
||||||
|
使用每张卡片右上角的箭头调整顺序,保存后预览也会按当前顺序展示。
|
||||||
|
</Typography.Text>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
<Form.ErrorList errors={errors} />
|
<Form.ErrorList errors={errors} />
|
||||||
<Button onClick={() => add()}>新增{field.label}</Button>
|
<Button block icon={<PlusOutlined />} onClick={() => add()}>
|
||||||
|
新增{field.label}
|
||||||
|
</Button>
|
||||||
</Space>
|
</Space>
|
||||||
)}
|
)}
|
||||||
</Form.List>
|
</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 { 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 type { BrandProfile } from "@personal-brand/api-client";
|
||||||
import { createApiClient } from "../../lib/api.js";
|
import { createApiClient } from "../../lib/api.js";
|
||||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
||||||
import { MutationError, QueryState } from "../../components/QueryState.js";
|
import { MutationError, QueryState } from "../../components/QueryState.js";
|
||||||
import { PresentationEditor } from "./PresentationEditor.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() {
|
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 client = createApiClient();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const [form] = Form.useForm<BrandProfile>();
|
const [form] = Form.useForm<BrandProfile>();
|
||||||
@@ -16,16 +39,26 @@ export function BrandPage() {
|
|||||||
queryKey: ["admin-workspace"],
|
queryKey: ["admin-workspace"],
|
||||||
queryFn: () => client.getAdminWorkspace(),
|
queryFn: () => client.getAdminWorkspace(),
|
||||||
});
|
});
|
||||||
|
const previewWorkspace = useQuery({
|
||||||
|
queryKey: ["admin-preview-workspace"],
|
||||||
|
queryFn: () => client.getAdminPreviewWorkspace(),
|
||||||
|
});
|
||||||
const template = useQuery({
|
const template = useQuery({
|
||||||
queryKey: ["template", brand.data?.templateKey],
|
queryKey: ["template", brand.data?.templateKey],
|
||||||
queryFn: () => client.getPublicTemplate(brand.data!.templateKey),
|
queryFn: () => client.getPublicTemplate(brand.data!.templateKey),
|
||||||
enabled: Boolean(brand.data?.templateKey),
|
enabled: Boolean(brand.data?.templateKey),
|
||||||
});
|
});
|
||||||
|
const templateCatalog = useQuery({
|
||||||
|
queryKey: ["template-catalog"],
|
||||||
|
queryFn: () => client.listPublicTemplates(),
|
||||||
|
});
|
||||||
const save = useMutation({
|
const save = useMutation({
|
||||||
mutationFn: (values: Partial<BrandProfile>) => client.updateAdminBrand(values),
|
mutationFn: (values: Partial<BrandProfile>) => client.updateAdminBrand(values),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
|
setDirty(false);
|
||||||
message.success("品牌表达已保存");
|
message.success("品牌表达已保存");
|
||||||
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
|
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
return (
|
return (
|
||||||
@@ -33,29 +66,57 @@ export function BrandPage() {
|
|||||||
{!brand.data ? null : (
|
{!brand.data ? null : (
|
||||||
<>
|
<>
|
||||||
<AdminPageHeader
|
<AdminPageHeader
|
||||||
title="品牌资料"
|
title="小程序工作台"
|
||||||
description="先让访客理解你是谁、服务谁,以及为什么值得信任。"
|
description={
|
||||||
|
template.data?.description
|
||||||
|
? `先让访客理解你是谁、服务谁,以及为什么值得信任。${template.data.description}`
|
||||||
|
: "先让访客理解你是谁、服务谁,以及为什么值得信任。"
|
||||||
|
}
|
||||||
extra={<Tag color="blue">{template.data?.name ?? "当前模板"}</Tag>}
|
extra={<Tag color="blue">{template.data?.name ?? "当前模板"}</Tag>}
|
||||||
/>
|
/>
|
||||||
<Row gutter={[24, 24]} align="top">
|
<div className="brand-page__toolbar">
|
||||||
<Col xs={24} xl={16}>
|
<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={form}
|
form={form}
|
||||||
layout="vertical"
|
layout="vertical"
|
||||||
initialValues={brand.data}
|
initialValues={brand.data}
|
||||||
|
onValuesChange={() => setDirty(true)}
|
||||||
onFinish={(values) => save.mutate(values)}
|
onFinish={(values) => save.mutate(values)}
|
||||||
>
|
>
|
||||||
<Card
|
<section className="brand-settings-section" aria-labelledby="brand-identity-title">
|
||||||
title="我是谁"
|
<div className="brand-settings-section__header">
|
||||||
extra={<Typography.Text type="secondary">公开展示</Typography.Text>}
|
<div>
|
||||||
>
|
<Typography.Title id="brand-identity-title" level={4}>
|
||||||
|
我是谁
|
||||||
|
</Typography.Title>
|
||||||
|
<Typography.Text type="secondary">公开展示的品牌身份和定位。</Typography.Text>
|
||||||
|
</div>
|
||||||
|
<Tag>品牌基础信息</Tag>
|
||||||
|
</div>
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name="name"
|
name="name"
|
||||||
label="品牌名称"
|
label="品牌名称"
|
||||||
help="可以是个人姓名、工作室名称或品牌名。"
|
help="可以是个人姓名、工作室名称或品牌名。"
|
||||||
rules={[{ required: true, message: "请输入品牌名称" }]}
|
rules={[{ required: true, message: "请输入品牌名称" }]}
|
||||||
>
|
>
|
||||||
<Input size="large" placeholder="例如:林然|品牌顾问" />
|
<Input size="large" placeholder="例如:品牌主理人|品牌顾问" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name="tagline"
|
name="tagline"
|
||||||
@@ -73,8 +134,18 @@ export function BrandPage() {
|
|||||||
placeholder="让第一次认识你的人快速建立基本信任。"
|
placeholder="让第一次认识你的人快速建立基本信任。"
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Card>
|
</section>
|
||||||
<Card title="如何联系与合作" style={{ marginTop: 24 }}>
|
<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}>
|
<Row gutter={16}>
|
||||||
<Col xs={24} md={12}>
|
<Col xs={24} md={12}>
|
||||||
<Form.Item name="hours" label="可联系时间">
|
<Form.Item name="hours" label="可联系时间">
|
||||||
@@ -104,8 +175,18 @@ export function BrandPage() {
|
|||||||
>
|
>
|
||||||
<Input.TextArea rows={3} placeholder="例如:收到咨询后 1 个工作日内回复。" />
|
<Input.TextArea rows={3} placeholder="例如:收到咨询后 1 个工作日内回复。" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Card>
|
</section>
|
||||||
<Card title="模板与品牌视觉" style={{ marginTop: 24 }}>
|
<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
|
<Form.Item
|
||||||
name="templateKey"
|
name="templateKey"
|
||||||
label="业务表达模板"
|
label="业务表达模板"
|
||||||
@@ -113,10 +194,10 @@ export function BrandPage() {
|
|||||||
>
|
>
|
||||||
<Select
|
<Select
|
||||||
disabled
|
disabled
|
||||||
options={[
|
options={(templateCatalog.data?.industries ?? []).map((item) => ({
|
||||||
{ value: "personal", label: "个人品牌" },
|
value: item.key,
|
||||||
{ value: "food", label: "餐饮模板" },
|
label: item.name,
|
||||||
]}
|
}))}
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Row gutter={16}>
|
<Row gutter={16}>
|
||||||
@@ -124,18 +205,22 @@ export function BrandPage() {
|
|||||||
<Form.Item
|
<Form.Item
|
||||||
name="avatarUrl"
|
name="avatarUrl"
|
||||||
label="头像图片地址"
|
label="头像图片地址"
|
||||||
help="粘贴一张可公开访问的图片地址。"
|
help="点击上传或粘贴一张可公开访问的图片地址。"
|
||||||
>
|
>
|
||||||
<ImageUrlField />
|
<ImageUrlField scope="brand" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Col>
|
</Col>
|
||||||
<Col xs={24} md={12}>
|
<Col xs={24} md={12}>
|
||||||
<Form.Item name="coverUrl" label="品牌封面图片地址" help="建议使用横向图片。">
|
<Form.Item
|
||||||
<ImageUrlField />
|
name="coverUrl"
|
||||||
|
label="品牌封面图片地址"
|
||||||
|
help="点击上传,或粘贴一张横向图片地址。"
|
||||||
|
>
|
||||||
|
<ImageUrlField scope="brand" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Col>
|
</Col>
|
||||||
</Row>
|
</Row>
|
||||||
</Card>
|
</section>
|
||||||
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
|
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
|
||||||
<MutationError error={save.error} />
|
<MutationError error={save.error} />
|
||||||
<Button type="primary" htmlType="submit" loading={save.isPending} size="large">
|
<Button type="primary" htmlType="submit" loading={save.isPending} size="large">
|
||||||
@@ -143,25 +228,28 @@ export function BrandPage() {
|
|||||||
</Button>
|
</Button>
|
||||||
</Space>
|
</Space>
|
||||||
</Form>
|
</Form>
|
||||||
|
</div>
|
||||||
|
{template.data ? (
|
||||||
|
<Alert
|
||||||
|
className="brand-page__template-note"
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
message={`当前使用:${template.data.name}`}
|
||||||
|
description={`适用场景:${template.data.serviceCategories.join("、") || "通用品牌展示"}`}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div hidden={panel !== "pages"}>
|
||||||
<PresentationEditor
|
<PresentationEditor
|
||||||
templateContent={workspace.data?.templateContent}
|
templateContent={workspace.data?.templateContent}
|
||||||
|
previewWorkspace={previewWorkspace.data}
|
||||||
config={brand.data.config}
|
config={brand.data.config}
|
||||||
brand={brand.data}
|
brand={brand.data}
|
||||||
loading={workspace.isLoading}
|
loading={workspace.isLoading}
|
||||||
error={workspace.error}
|
error={workspace.error}
|
||||||
|
{...(initialSelection ? { initialSelection } : {})}
|
||||||
/>
|
/>
|
||||||
</Col>
|
</div>
|
||||||
<Col xs={24} xl={8}>
|
|
||||||
{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>
|
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</QueryState>
|
</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%;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,135 +1,160 @@
|
|||||||
import {
|
import {
|
||||||
Alert,
|
Alert,
|
||||||
Button,
|
Button,
|
||||||
Card,
|
|
||||||
Divider,
|
Divider,
|
||||||
Col,
|
Col,
|
||||||
Form,
|
Form,
|
||||||
Grid,
|
Grid,
|
||||||
Input,
|
|
||||||
InputNumber,
|
|
||||||
Row,
|
Row,
|
||||||
Select,
|
Select,
|
||||||
Segmented,
|
Segmented,
|
||||||
Space,
|
Space,
|
||||||
Tag,
|
Tag,
|
||||||
Typography,
|
Typography,
|
||||||
message,
|
|
||||||
} from "antd";
|
} from "antd";
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import type { AdminTemplateContent, TemplateAdminField } from "@personal-brand/api-client";
|
import type {
|
||||||
|
AdminTemplateContent,
|
||||||
|
RuntimeWorkspace,
|
||||||
|
TemplateAdminField,
|
||||||
|
TemplateAdminSection,
|
||||||
|
} from "@personal-brand/api-client";
|
||||||
import type { BrandProfile } from "@personal-brand/api-client";
|
import type { BrandProfile } from "@personal-brand/api-client";
|
||||||
import { createApiClient } from "../../lib/api.js";
|
import { projectBrandAliases, projectTrustPresentation } from "@personal-brand/api-client";
|
||||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
|
||||||
import { TemplateListField } from "../../components/TemplateListField.js";
|
import { TemplateListField } from "../../components/TemplateListField.js";
|
||||||
|
import { TemplateFieldRenderer } from "../../components/TemplateFieldRenderer.js";
|
||||||
import { MutationError } from "../../components/QueryState.js";
|
import { MutationError } from "../../components/QueryState.js";
|
||||||
|
import { RecordContentEditor } from "../../components/RecordContentEditor.js";
|
||||||
import { TemplatePreview } from "./TemplatePreview.js";
|
import { TemplatePreview } from "./TemplatePreview.js";
|
||||||
|
import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js";
|
||||||
|
import {
|
||||||
|
resolvePreviewSelection,
|
||||||
|
previewTrustRecordId,
|
||||||
|
type PreviewSelection,
|
||||||
|
type PreviewTarget,
|
||||||
|
} from "./preview-selection.js";
|
||||||
import {
|
import {
|
||||||
applyPresentationValues,
|
|
||||||
filterSectionsForPreviewTarget,
|
filterSectionsForPreviewTarget,
|
||||||
presentationFieldName,
|
presentationFieldName,
|
||||||
readPresentationValue,
|
|
||||||
type PresentationValues,
|
type PresentationValues,
|
||||||
} from "./presentation-bindings.js";
|
} from "./presentation-bindings.js";
|
||||||
|
import "./PresentationEditor.css";
|
||||||
|
import { useEditorDraft } from "./use-editor-draft.js";
|
||||||
|
import {
|
||||||
|
usePresentationRecordQueries,
|
||||||
|
useBrandPresentationSections,
|
||||||
|
useBrandSaveMutation,
|
||||||
|
useBrandPresentationForm,
|
||||||
|
useBrandPreviewDraft,
|
||||||
|
} from "./presentation-editor-state.js";
|
||||||
|
import { useRecordPreview } from "./presentation-editor-record-preview.js";
|
||||||
|
|
||||||
interface PresentationEditorProps {
|
interface PresentationEditorProps {
|
||||||
templateContent: AdminTemplateContent | null | undefined;
|
templateContent: AdminTemplateContent | null | undefined;
|
||||||
|
previewWorkspace?: RuntimeWorkspace | undefined;
|
||||||
config: Record<string, unknown> | null | undefined;
|
config: Record<string, unknown> | null | undefined;
|
||||||
brand: BrandProfile;
|
brand: BrandProfile;
|
||||||
loading?: boolean;
|
loading?: boolean;
|
||||||
error?: unknown;
|
error?: unknown;
|
||||||
|
initialSelection?: PreviewSelection;
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderField(field: TemplateAdminField) {
|
function trustSection(
|
||||||
if (field.input === "textarea")
|
declaration: NonNullable<AdminTemplateContent["trustContentTypes"]>[number],
|
||||||
return (
|
page: string,
|
||||||
<Input.TextArea
|
): TemplateAdminSection {
|
||||||
rows={3}
|
const key = `trust:${declaration.type}`;
|
||||||
maxLength={field.maxLength}
|
return {
|
||||||
showCount={!!field.maxLength}
|
key,
|
||||||
placeholder={field.placeholder}
|
title: declaration.label,
|
||||||
/>
|
description: declaration.help ?? "编辑当前展示内容。",
|
||||||
);
|
page,
|
||||||
if (field.input === "image")
|
target: "trust",
|
||||||
return <ImageUrlField {...(field.placeholder ? { placeholder: field.placeholder } : {})} />;
|
previewTargets: [
|
||||||
if (field.input === "number")
|
{ key, label: declaration.label },
|
||||||
return <InputNumber style={{ width: "100%" }} placeholder={field.placeholder} />;
|
...(declaration.previewTargets ?? []).filter(
|
||||||
if (field.input === "boolean")
|
(target) => !target.page || target.page === page,
|
||||||
return (
|
),
|
||||||
<Select
|
],
|
||||||
options={[
|
fields: [
|
||||||
{ value: true, label: "是" },
|
{
|
||||||
{ value: false, label: "否" },
|
key: "title",
|
||||||
]}
|
binding: "trust.title",
|
||||||
/>
|
label: declaration.adminFields.title,
|
||||||
);
|
input: "text" as const,
|
||||||
if (field.input === "select" || field.input === "multi-select")
|
required: true,
|
||||||
return (
|
},
|
||||||
<Select
|
...(["summary", "content"] as const)
|
||||||
{...(field.input === "multi-select" ? { mode: "multiple" as const } : {})}
|
.filter((field) => !declaration.hideStandardFields?.includes(field))
|
||||||
options={field.options ?? []}
|
.map((field) => ({
|
||||||
/>
|
key: field,
|
||||||
);
|
binding: `trust.${field}`,
|
||||||
return (
|
label: declaration.adminFields[field],
|
||||||
<Input
|
input: "textarea" as const,
|
||||||
type={field.input === "phone" ? "tel" : "text"}
|
previewTarget: `trust:${declaration.type}`,
|
||||||
maxLength={field.maxLength}
|
...(field === "summary" && declaration.adminFields.summaryHelp
|
||||||
placeholder={field.placeholder}
|
? { help: declaration.adminFields.summaryHelp }
|
||||||
/>
|
: {}),
|
||||||
|
...(field === "content" && declaration.required ? { required: true } : {}),
|
||||||
|
})),
|
||||||
|
...(declaration.configFields ?? [])
|
||||||
|
.filter((field) => {
|
||||||
|
const target = declaration.previewTargets?.find(
|
||||||
|
(target) => target.key === field.previewTarget,
|
||||||
);
|
);
|
||||||
|
return !target?.page || target.page === page;
|
||||||
|
})
|
||||||
|
.map((field) => ({
|
||||||
|
...field,
|
||||||
|
previewTarget: field.previewTarget ?? `trust:${declaration.type}`,
|
||||||
|
})),
|
||||||
|
].map((field) => ({
|
||||||
|
...field,
|
||||||
|
previewTarget: (field as TemplateAdminField).previewTarget ?? `trust:${declaration.type}`,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function previewTargetSource(
|
||||||
|
section: TemplateAdminSection,
|
||||||
|
targetKey: string,
|
||||||
|
): "brand" | "offering" | "trust" | "inquiry" {
|
||||||
|
const fields = section.fields.filter((field) => field.previewTarget === targetKey);
|
||||||
|
if (fields.some((field) => field.binding.startsWith("offering."))) return "offering";
|
||||||
|
if (fields.some((field) => field.binding.startsWith("trust."))) return "trust";
|
||||||
|
if (fields.some((field) => field.binding.startsWith("brand."))) return "brand";
|
||||||
|
return section.target;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function PresentationEditor({
|
export function PresentationEditor({
|
||||||
templateContent,
|
templateContent,
|
||||||
|
previewWorkspace,
|
||||||
config,
|
config,
|
||||||
brand,
|
brand,
|
||||||
loading,
|
loading,
|
||||||
error,
|
error,
|
||||||
|
initialSelection,
|
||||||
}: PresentationEditorProps) {
|
}: PresentationEditorProps) {
|
||||||
const [form] = Form.useForm<PresentationValues>();
|
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const breakpoints = Grid.useBreakpoint();
|
const breakpoints = Grid.useBreakpoint();
|
||||||
const [activePage, setActivePage] = useState<string>();
|
const [activePage, setActivePage] = useState<string>();
|
||||||
const [activeTarget, setActiveTarget] = useState<string>();
|
const [selection, setSelection] = useState<PreviewSelection | undefined>(initialSelection);
|
||||||
const sections = useMemo(() => {
|
const [hasInitializedSelection, setHasInitializedSelection] = useState(Boolean(initialSelection));
|
||||||
const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({
|
const [detailOfferingId, setDetailOfferingId] = useState<string>();
|
||||||
...field,
|
const [recordDraft, setRecordDraft] = useState<{
|
||||||
binding: field.binding ?? `brand.config.templateData.${field.key}`,
|
source: "offering" | "trust";
|
||||||
}));
|
id: string;
|
||||||
return [
|
values: PresentationValues;
|
||||||
...(declaredTemplateFields.length
|
}>();
|
||||||
? [
|
const [inquiryDraft, setInquiryDraft] =
|
||||||
{
|
useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>();
|
||||||
key: "template-data",
|
const [brandDirty, setBrandDirty] = useState(false);
|
||||||
title: "模板专属内容",
|
const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft);
|
||||||
description: "这些字段由当前小程序模板定义,保存后发布才会对外展示。",
|
const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand");
|
||||||
page: templateContent?.templateFields?.[0]?.page ?? "home",
|
const sections = useBrandPresentationSections(templateContent);
|
||||||
target: "brand" as const,
|
|
||||||
fields: declaredTemplateFields,
|
|
||||||
},
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
...(templateContent?.admin.sections ?? []),
|
|
||||||
]
|
|
||||||
.map((section) => ({
|
|
||||||
...section,
|
|
||||||
fields: section.fields.filter(
|
|
||||||
(field) =>
|
|
||||||
field.binding.startsWith("brand.config.") ||
|
|
||||||
[
|
|
||||||
"brand.avatarUrl",
|
|
||||||
"brand.description",
|
|
||||||
"brand.contactPhone",
|
|
||||||
"brand.contactWechat",
|
|
||||||
"brand.address",
|
|
||||||
].includes(field.binding),
|
|
||||||
),
|
|
||||||
}))
|
|
||||||
.filter((section) => section.fields.length > 0);
|
|
||||||
}, [templateContent]);
|
|
||||||
const pageOptions = useMemo(() => {
|
const pageOptions = useMemo(() => {
|
||||||
const pages = new Map<string, string>();
|
const pages = new Map<string, string>();
|
||||||
for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label);
|
for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label);
|
||||||
@@ -144,12 +169,97 @@ export function PresentationEditor({
|
|||||||
? activePage
|
? activePage
|
||||||
: pageOptions[0]?.value;
|
: pageOptions[0]?.value;
|
||||||
const visibleSections = sections.filter((section) => section.page === selectedPage);
|
const visibleSections = sections.filter((section) => section.page === selectedPage);
|
||||||
const visibleTargets = visibleSections.flatMap((section) =>
|
const recordSections = useMemo(
|
||||||
(section.previewTargets ?? []).map((target) => ({ ...target, page: section.page })),
|
() =>
|
||||||
|
(templateContent?.trustContentTypes ?? [])
|
||||||
|
.filter((item) => item.pages?.includes(selectedPage ?? ""))
|
||||||
|
.map((item) => trustSection(item, selectedPage ?? "home")),
|
||||||
|
[templateContent, selectedPage],
|
||||||
);
|
);
|
||||||
|
const visibleTargets = useMemo<PreviewTarget[]>(
|
||||||
|
() =>
|
||||||
|
[...(templateContent?.admin.sections ?? []), ...recordSections]
|
||||||
|
.filter(
|
||||||
|
(section) =>
|
||||||
|
section.page === selectedPage &&
|
||||||
|
(selectedPage !== "detail" || section.target === "brand"),
|
||||||
|
)
|
||||||
|
.flatMap((section) =>
|
||||||
|
(section.previewTargets ?? []).map((target) => ({
|
||||||
|
...target,
|
||||||
|
page: section.page,
|
||||||
|
source: previewTargetSource(section, target.key),
|
||||||
|
...(section.key.startsWith("trust:") ? { trustType: section.key.slice(6) } : {}),
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.concat(
|
||||||
|
selectedPage === "inquiry" && inquiryRuntime
|
||||||
|
? inquiryRuntime.fields.map((field) => ({
|
||||||
|
key: `inquiry-field:${field.key}`,
|
||||||
|
label: field.label,
|
||||||
|
page: "inquiry",
|
||||||
|
source: "inquiry" as const,
|
||||||
|
}))
|
||||||
|
: [],
|
||||||
|
),
|
||||||
|
[templateContent, selectedPage, recordSections, inquiryRuntime],
|
||||||
|
);
|
||||||
|
const activeTarget = selection?.targetKey;
|
||||||
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
|
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
|
||||||
const editableSections = filterSectionsForPreviewTarget(visibleSections, selectedTarget?.key);
|
const selectedSection = [...(templateContent?.admin.sections ?? []), ...recordSections].find(
|
||||||
const handleTargetSelected = useCallback((key: string) => setActiveTarget(key), []);
|
(section) =>
|
||||||
|
section.page === selectedPage &&
|
||||||
|
section.previewTargets?.some((target) => target.key === selectedTarget?.key),
|
||||||
|
);
|
||||||
|
const selectedRecordSource =
|
||||||
|
selectedTarget?.source === "offering" || selectedTarget?.source === "trust"
|
||||||
|
? selectedTarget.source
|
||||||
|
: undefined;
|
||||||
|
const { offeringsQuery, trustQuery, selectedRecord } = usePresentationRecordQueries(
|
||||||
|
selectedRecordSource,
|
||||||
|
selection?.recordId,
|
||||||
|
);
|
||||||
|
const editableSections = filterSectionsForPreviewTarget(
|
||||||
|
visibleSections.filter((section) =>
|
||||||
|
section.fields.some((field) => field.binding.startsWith("brand.")),
|
||||||
|
),
|
||||||
|
selectedTarget?.key,
|
||||||
|
);
|
||||||
|
const recordSection = useMemo(
|
||||||
|
() =>
|
||||||
|
selectedSection && selection?.targetKey
|
||||||
|
? {
|
||||||
|
...selectedSection,
|
||||||
|
fields: selectedSection.fields.filter(
|
||||||
|
(field) => field.previewTarget === selection.targetKey,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
[selectedSection, selection?.targetKey],
|
||||||
|
);
|
||||||
|
const handleTargetSelected = useCallback(
|
||||||
|
(next?: PreviewSelection) => {
|
||||||
|
const select = () =>
|
||||||
|
setSelection(
|
||||||
|
next
|
||||||
|
? resolvePreviewSelection(
|
||||||
|
next.targetKey,
|
||||||
|
next.recordId,
|
||||||
|
visibleTargets,
|
||||||
|
selectedPage ?? "home",
|
||||||
|
)
|
||||||
|
: undefined,
|
||||||
|
);
|
||||||
|
if (recordDraft || inquiryDraft)
|
||||||
|
guardDraft(() => {
|
||||||
|
setInquiryDraft(undefined);
|
||||||
|
setRecordDraft(undefined);
|
||||||
|
select();
|
||||||
|
});
|
||||||
|
else select();
|
||||||
|
},
|
||||||
|
[visibleTargets, selectedPage, recordDraft, inquiryDraft, guardDraft],
|
||||||
|
);
|
||||||
const relatedTargets = [
|
const relatedTargets = [
|
||||||
...(templateContent?.admin.sections ?? [])
|
...(templateContent?.admin.sections ?? [])
|
||||||
.filter((section) => section.page === selectedPage && section.target !== "brand")
|
.filter((section) => section.page === selectedPage && section.target !== "brand")
|
||||||
@@ -180,55 +290,208 @@ export function PresentationEditor({
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
const initialValues = useMemo(() => {
|
const relevantPageLinks = selectedSection
|
||||||
const values: PresentationValues = {};
|
? pageLinks.filter((item) => {
|
||||||
for (const section of sections) {
|
if (item.target.startsWith("trust:")) return selectedSection.target === "trust";
|
||||||
for (const field of section.fields) {
|
return item.target === selectedSection.target;
|
||||||
values[presentationFieldName(section.key, field.key)] = readPresentationValue(
|
})
|
||||||
|
: pageLinks;
|
||||||
|
const formState = useBrandPresentationForm({ brand, config, sections });
|
||||||
|
const { form, initialValues } = formState;
|
||||||
|
const save = useBrandSaveMutation({ ...formState, brand, config, sections, queryClient });
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const initialPage =
|
||||||
|
typeof initialSelection === "object" && "page" in initialSelection
|
||||||
|
? String(initialSelection.page)
|
||||||
|
: undefined;
|
||||||
|
if (initialPage) {
|
||||||
|
setActivePage(
|
||||||
|
pageOptions.some((item) => item.value === initialPage)
|
||||||
|
? initialPage
|
||||||
|
: pageOptions[0]?.value,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!activePage && pageOptions.length) setActivePage(pageOptions[0]?.value);
|
||||||
|
}, [activePage, initialSelection, pageOptions]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (hasInitializedSelection) return;
|
||||||
|
if (!pageOptions.length) return;
|
||||||
|
if (!initialSelection) return;
|
||||||
|
const requestedPage =
|
||||||
|
typeof initialSelection === "object" && "page" in initialSelection
|
||||||
|
? String(initialSelection.page)
|
||||||
|
: undefined;
|
||||||
|
const resolvedPage =
|
||||||
|
requestedPage && pageOptions.some((item) => item.value === requestedPage)
|
||||||
|
? requestedPage
|
||||||
|
: (pageOptions[0]?.value ?? "home");
|
||||||
|
setSelection(
|
||||||
|
resolvePreviewSelection(
|
||||||
|
initialSelection.targetKey,
|
||||||
|
initialSelection.recordId,
|
||||||
|
visibleTargets,
|
||||||
|
resolvedPage,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
setActivePage(resolvedPage);
|
||||||
|
setHasInitializedSelection(true);
|
||||||
|
}, [hasInitializedSelection, initialSelection, pageOptions, selectedPage, visibleTargets]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!initialSelection) setSelection(undefined);
|
||||||
|
}, [initialSelection, selectedPage, templateContent?.displayName]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!selection?.recordId) return;
|
||||||
|
const records =
|
||||||
|
selectedTarget?.source === "trust"
|
||||||
|
? previewWorkspace?.trustItems
|
||||||
|
: previewWorkspace?.offerings;
|
||||||
|
if (records && !records.some((item) => item.id === selection.recordId)) setSelection(undefined);
|
||||||
|
}, [
|
||||||
|
previewWorkspace?.offerings,
|
||||||
|
previewWorkspace?.trustItems,
|
||||||
|
selectedTarget?.source,
|
||||||
|
selection,
|
||||||
|
]);
|
||||||
|
useEffect(
|
||||||
|
() => setRecordDraft(undefined),
|
||||||
|
[selection?.targetKey, selection?.recordId, selectedPage],
|
||||||
|
);
|
||||||
|
const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({
|
||||||
|
brand,
|
||||||
config,
|
config,
|
||||||
field.binding,
|
sections,
|
||||||
field,
|
form,
|
||||||
|
onDirty: () => setBrandDirty(true),
|
||||||
|
});
|
||||||
|
const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection });
|
||||||
|
useEffect(() => resetPreview(), [config, initialValues, resetPreview]);
|
||||||
|
const previewConfig = previewBrand.config;
|
||||||
|
const draftWorkspace = useMemo(() => {
|
||||||
|
if (!previewWorkspace) return undefined;
|
||||||
|
const next: RuntimeWorkspace = {
|
||||||
|
...previewWorkspace,
|
||||||
|
templateData: {
|
||||||
|
...previewWorkspace.templateData,
|
||||||
|
...(previewConfig.templateData &&
|
||||||
|
typeof previewConfig.templateData === "object" &&
|
||||||
|
!Array.isArray(previewConfig.templateData)
|
||||||
|
? (previewConfig.templateData as Record<string, unknown>)
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
inquiryForms: previewWorkspace.inquiryForms.map((item) =>
|
||||||
|
item.key === inquiryRuntime?.key && inquiryDraft ? { ...item, fields: inquiryDraft } : item,
|
||||||
|
),
|
||||||
|
brand: projectBrandAliases(
|
||||||
|
{
|
||||||
|
...previewWorkspace.brand,
|
||||||
|
...(previewBrand as unknown as Record<string, unknown>),
|
||||||
|
config: previewConfig,
|
||||||
|
},
|
||||||
|
previewConfig,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
if (!recordDraft || !selectedRecord || !recordSection || recordDraft.id !== selectedRecord.id)
|
||||||
|
return next;
|
||||||
|
const config = recordPreview?.config;
|
||||||
|
const standard = recordPreview?.standard;
|
||||||
|
if (!config || !standard) return next;
|
||||||
|
if (recordDraft.source === "trust") {
|
||||||
|
next.trustItems = next.trustItems.map((item) =>
|
||||||
|
item.id === recordDraft.id
|
||||||
|
? {
|
||||||
|
...item,
|
||||||
|
title: typeof standard.title === "string" ? standard.title : item.title,
|
||||||
|
summary: typeof standard.summary === "string" ? standard.summary : item.summary,
|
||||||
|
content: typeof standard.content === "string" ? standard.content : item.content,
|
||||||
|
config,
|
||||||
|
}
|
||||||
|
: item,
|
||||||
|
);
|
||||||
|
next.trustPresentation = projectTrustPresentation(
|
||||||
|
next.trustItems,
|
||||||
|
templateContent?.trustContentTypes ?? [],
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
next.offerings = next.offerings.map((item) =>
|
||||||
|
item.id === recordDraft.id
|
||||||
|
? {
|
||||||
|
...item,
|
||||||
|
name:
|
||||||
|
(recordDraft.values[presentationFieldName(recordSection.key, "name")] as string) ||
|
||||||
|
item.name,
|
||||||
|
summary:
|
||||||
|
(recordDraft.values[
|
||||||
|
presentationFieldName(recordSection.key, "summary")
|
||||||
|
] as string) || item.summary,
|
||||||
|
priceText:
|
||||||
|
(recordDraft.values[
|
||||||
|
presentationFieldName(recordSection.key, "priceText")
|
||||||
|
] as string) || null,
|
||||||
|
coverUrl:
|
||||||
|
(recordDraft.values[
|
||||||
|
presentationFieldName(recordSection.key, "coverUrl")
|
||||||
|
] as string) || null,
|
||||||
|
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 standard.coverUrl === "string"
|
||||||
|
? standard.coverUrl
|
||||||
|
: null,
|
||||||
|
details: {
|
||||||
|
...item.presentation.details,
|
||||||
|
...(config.details &&
|
||||||
|
typeof config.details === "object" &&
|
||||||
|
"background" in config.details
|
||||||
|
? (config.details as RuntimeWorkspace["offerings"][number]["presentation"]["details"])
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: item,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
return next;
|
||||||
return values;
|
}, [
|
||||||
}, [config, sections]);
|
previewWorkspace,
|
||||||
|
previewBrand,
|
||||||
const save = useMutation({
|
previewConfig,
|
||||||
mutationFn: (values: PresentationValues) => {
|
recordDraft,
|
||||||
const nextConfig = applyPresentationValues(config, sections, values);
|
selectedRecord,
|
||||||
return createApiClient().updateAdminBrand({ config: nextConfig });
|
recordSection,
|
||||||
},
|
recordPreview,
|
||||||
onSuccess: () => {
|
templateContent,
|
||||||
message.success("页面内容已保存为草稿,发布后小程序才会更新");
|
inquiryDraft,
|
||||||
window.dispatchEvent(new Event("template-preview-refresh"));
|
inquiryRuntime,
|
||||||
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
|
]);
|
||||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
const selectedDetailOfferingId =
|
||||||
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
|
detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId)
|
||||||
void queryClient.invalidateQueries({ queryKey: ["publication-readiness"] });
|
? detailOfferingId
|
||||||
},
|
: draftWorkspace?.offerings[0]?.id;
|
||||||
});
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
form.setFieldsValue(initialValues);
|
|
||||||
}, [form, initialValues]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!pageOptions.some((item) => item.value === activePage))
|
|
||||||
setActivePage(pageOptions[0]?.value);
|
|
||||||
}, [activePage, pageOptions]);
|
|
||||||
useEffect(() => setActiveTarget(undefined), [selectedPage]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card
|
<section className="presentation-editor" aria-labelledby="presentation-editor-title">
|
||||||
title="小程序页面配置"
|
<div className="presentation-editor__header">
|
||||||
extra={templateContent ? <Tag color="blue">{templateContent.displayName}</Tag> : null}
|
<div>
|
||||||
style={{ marginTop: 32 }}
|
<Typography.Title id="presentation-editor-title" level={3}>
|
||||||
styles={{ body: { minHeight: breakpoints.md ? 760 : 620 } }}
|
小程序页面配置
|
||||||
>
|
</Typography.Title>
|
||||||
<Typography.Paragraph type="secondary">
|
<Typography.Paragraph type="secondary">
|
||||||
按小程序页面查找内容。这里修改的是草稿,发布后访客才会看到更新。
|
按页面查找内容。这里修改的是草稿,发布后访客才会看到更新。
|
||||||
</Typography.Paragraph>
|
</Typography.Paragraph>
|
||||||
|
</div>
|
||||||
|
{templateContent ? <Tag color="blue">{templateContent.displayName}</Tag> : null}
|
||||||
|
</div>
|
||||||
{loading ? <Alert type="info" showIcon message="正在读取当前模板的编辑项目" /> : null}
|
{loading ? <Alert type="info" showIcon message="正在读取当前模板的编辑项目" /> : null}
|
||||||
{error ? (
|
{error ? (
|
||||||
<Alert type="warning" showIcon message="模板编辑项目读取失败,请刷新后重试。" />
|
<Alert type="warning" showIcon message="模板编辑项目读取失败,请刷新后重试。" />
|
||||||
@@ -238,57 +501,293 @@ export function PresentationEditor({
|
|||||||
) : null}
|
) : null}
|
||||||
{templateContent ? (
|
{templateContent ? (
|
||||||
<>
|
<>
|
||||||
<Space wrap style={{ marginBottom: 24 }}>
|
<Space className="presentation-editor__navigation" wrap>
|
||||||
{breakpoints.xs ? (
|
{breakpoints.xs ? (
|
||||||
<Select
|
<Select
|
||||||
aria-label="选择小程序页面"
|
aria-label="选择小程序页面"
|
||||||
value={selectedPage}
|
value={selectedPage}
|
||||||
options={pageOptions}
|
options={pageOptions}
|
||||||
onChange={setActivePage}
|
onChange={(value) =>
|
||||||
|
guardDraft(() => {
|
||||||
|
setBrandDirty(false);
|
||||||
|
form.setFieldsValue(initialValues);
|
||||||
|
resetPreview();
|
||||||
|
setRecordDraft(undefined);
|
||||||
|
setInquiryDraft(undefined);
|
||||||
|
setActivePage(value);
|
||||||
|
})
|
||||||
|
}
|
||||||
style={{ minWidth: 180 }}
|
style={{ minWidth: 180 }}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<Segmented
|
<Segmented
|
||||||
value={selectedPage}
|
value={selectedPage}
|
||||||
options={pageOptions}
|
options={pageOptions}
|
||||||
onChange={(value) => setActivePage(String(value))}
|
onChange={(value) =>
|
||||||
|
guardDraft(() => {
|
||||||
|
setBrandDirty(false);
|
||||||
|
form.setFieldsValue(initialValues);
|
||||||
|
resetPreview();
|
||||||
|
setRecordDraft(undefined);
|
||||||
|
setInquiryDraft(undefined);
|
||||||
|
setActivePage(String(value));
|
||||||
|
})
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Space>
|
</Space>
|
||||||
<Row gutter={[24, 24]} align="top">
|
<div className="presentation-editor__workspace">
|
||||||
<Col xs={24} xl={12}>
|
<div className="presentation-editor__preview">
|
||||||
<Typography.Title level={5}>页面预览</Typography.Title>
|
<Typography.Title level={5}>页面预览</Typography.Title>
|
||||||
|
{selectedPage === "detail" && draftWorkspace?.offerings.length ? (
|
||||||
|
<Select
|
||||||
|
aria-label="选择详情页业务内容"
|
||||||
|
style={{ width: "100%", marginBottom: 12 }}
|
||||||
|
value={selectedDetailOfferingId}
|
||||||
|
options={draftWorkspace.offerings.map((item) => ({
|
||||||
|
value: item.id,
|
||||||
|
label: item.name,
|
||||||
|
}))}
|
||||||
|
onChange={(value) => {
|
||||||
|
setDetailOfferingId(value);
|
||||||
|
setSelection(undefined);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
<TemplatePreview
|
<TemplatePreview
|
||||||
brand={brand}
|
brand={previewBrand}
|
||||||
|
{...(draftWorkspace ? { workspace: draftWorkspace } : {})}
|
||||||
page={selectedPage ?? "home"}
|
page={selectedPage ?? "home"}
|
||||||
route={`/pages/${encodeURIComponent(selectedPage ?? "home")}/index`}
|
{...(selectedPage === "detail" && selectedDetailOfferingId
|
||||||
|
? { offeringId: selectedDetailOfferingId }
|
||||||
|
: {})}
|
||||||
{...(activeTarget ? { targetKey: activeTarget } : {})}
|
{...(activeTarget ? { targetKey: activeTarget } : {})}
|
||||||
|
{...(selection ? { selection } : {})}
|
||||||
|
targets={visibleTargets}
|
||||||
onTargetSelected={handleTargetSelected}
|
onTargetSelected={handleTargetSelected}
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
|
<aside className="presentation-editor__outline" aria-label="页面区域">
|
||||||
|
<Typography.Title level={5}>页面区域</Typography.Title>
|
||||||
|
<Typography.Paragraph type="secondary">选择区域,编辑对应内容</Typography.Paragraph>
|
||||||
{visibleTargets.length ? (
|
{visibleTargets.length ? (
|
||||||
<Space wrap style={{ marginTop: 16 }}>
|
<Space className="presentation-editor__regions" wrap style={{ marginTop: 16 }}>
|
||||||
{visibleTargets.map((target) => (
|
{visibleTargets.map((target) => (
|
||||||
<Button
|
<Button
|
||||||
key={target.key}
|
key={target.key}
|
||||||
|
className={
|
||||||
|
visibleTargets.some((parent) => parent.children?.includes(target.key))
|
||||||
|
? "is-child-region"
|
||||||
|
: ""
|
||||||
|
}
|
||||||
|
aria-pressed={activeTarget === target.key}
|
||||||
type={activeTarget === target.key ? "primary" : "default"}
|
type={activeTarget === target.key ? "primary" : "default"}
|
||||||
onClick={() => setActiveTarget(target.key)}
|
onClick={() => {
|
||||||
|
const recordId =
|
||||||
|
target.source === "offering"
|
||||||
|
? selectedPage === "detail"
|
||||||
|
? selectedDetailOfferingId
|
||||||
|
: draftWorkspace?.offerings[0]?.id
|
||||||
|
: target.source === "trust"
|
||||||
|
? previewTrustRecordId(
|
||||||
|
draftWorkspace?.trustItems ?? [],
|
||||||
|
target.trustType,
|
||||||
|
)
|
||||||
|
: undefined;
|
||||||
|
handleTargetSelected({
|
||||||
|
targetKey: target.key,
|
||||||
|
...(recordId ? { recordId } : {}),
|
||||||
|
});
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{target.label}
|
{target.label}
|
||||||
</Button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</Space>
|
</Space>
|
||||||
) : null}
|
) : null}
|
||||||
</Col>
|
{!visibleTargets.length ? (
|
||||||
<Col xs={24} xl={12}>
|
<Typography.Text type="secondary">此页为动态预览</Typography.Text>
|
||||||
|
) : null}
|
||||||
|
</aside>
|
||||||
|
<div className="presentation-editor__inspector">
|
||||||
<Typography.Title level={5}>
|
<Typography.Title level={5}>
|
||||||
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
|
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
|
||||||
</Typography.Title>
|
</Typography.Title>
|
||||||
|
<Tag color={brandDirty || recordDraft || inquiryDraft ? "orange" : "default"}>
|
||||||
|
{save.isPending
|
||||||
|
? "正在保存"
|
||||||
|
: save.isError
|
||||||
|
? "保存失败,请重试"
|
||||||
|
: brandDirty || recordDraft || inquiryDraft
|
||||||
|
? "有未保存修改"
|
||||||
|
: "草稿已同步"}
|
||||||
|
</Tag>
|
||||||
|
{selectedPage === "detail" && !selectedTarget ? (
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
message="详情页由所选业务内容动态生成"
|
||||||
|
description="选择业务内容预览详情,记录内容在业务提供项中维护;公共标题和按钮文案可从左侧区域列表配置,对全部详情生效。"
|
||||||
|
action={
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
void navigate("/admin/services");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
管理业务内容
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? (
|
||||||
|
<InquiryPreviewEditor
|
||||||
|
runtime={
|
||||||
|
draftWorkspace?.inquiryForms.find((item) => item.key === inquiryRuntime.key) ??
|
||||||
|
inquiryRuntime
|
||||||
|
}
|
||||||
|
fieldKey={activeTarget.slice("inquiry-field:".length)}
|
||||||
|
onDraft={setInquiryDraft}
|
||||||
|
onSaved={() => setInquiryDraft(undefined)}
|
||||||
|
/>
|
||||||
|
) : selectedTarget?.composite ? (
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
message="这是一个组合区域"
|
||||||
|
description={
|
||||||
|
<Space wrap>
|
||||||
|
{(selectedTarget.children ?? []).map((childKey) => {
|
||||||
|
const child = visibleTargets.find((item) => item.key === childKey);
|
||||||
|
if (!child) return null;
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
key={child.key}
|
||||||
|
onClick={() => {
|
||||||
|
const recordId =
|
||||||
|
child.source === "offering"
|
||||||
|
? selectedPage === "detail"
|
||||||
|
? selectedDetailOfferingId
|
||||||
|
: draftWorkspace?.offerings[0]?.id
|
||||||
|
: child.source === "trust"
|
||||||
|
? previewTrustRecordId(
|
||||||
|
draftWorkspace?.trustItems ?? [],
|
||||||
|
child.trustType,
|
||||||
|
)
|
||||||
|
: undefined;
|
||||||
|
handleTargetSelected({
|
||||||
|
targetKey: child.key,
|
||||||
|
...(recordId ? { recordId } : {}),
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
编辑{child.label}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Space>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
) : selectedRecordSource && selection?.recordId && selectedSection ? (
|
||||||
|
selectedRecord ? (
|
||||||
|
<RecordContentEditor
|
||||||
|
key={`${selectedRecordSource}:${selectedRecord.id}:${selectedSection.key}`}
|
||||||
|
source={selectedRecordSource}
|
||||||
|
record={selectedRecord}
|
||||||
|
section={recordSection!}
|
||||||
|
context="visual"
|
||||||
|
onDraft={(values) =>
|
||||||
|
setRecordDraft({
|
||||||
|
source: selectedRecordSource,
|
||||||
|
id: selectedRecord.id,
|
||||||
|
values,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
onSaved={() => setRecordDraft(undefined)}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Alert
|
||||||
|
type={
|
||||||
|
(
|
||||||
|
selectedRecordSource === "offering"
|
||||||
|
? offeringsQuery.isError
|
||||||
|
: trustQuery.isError
|
||||||
|
)
|
||||||
|
? "error"
|
||||||
|
: "info"
|
||||||
|
}
|
||||||
|
message={
|
||||||
|
(
|
||||||
|
selectedRecordSource === "offering"
|
||||||
|
? offeringsQuery.isError
|
||||||
|
: trustQuery.isError
|
||||||
|
)
|
||||||
|
? "内容读取失败"
|
||||||
|
: (
|
||||||
|
selectedRecordSource === "offering"
|
||||||
|
? offeringsQuery.isSuccess
|
||||||
|
: trustQuery.isSuccess
|
||||||
|
)
|
||||||
|
? "对应内容已不存在,请重新选择页面中的区域"
|
||||||
|
: "正在读取对应内容"
|
||||||
|
}
|
||||||
|
{...((
|
||||||
|
selectedRecordSource === "offering"
|
||||||
|
? offeringsQuery.isError
|
||||||
|
: trustQuery.isError
|
||||||
|
)
|
||||||
|
? {
|
||||||
|
action: (
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
onClick={() => {
|
||||||
|
if (selectedRecordSource === "offering")
|
||||||
|
void offeringsQuery.refetch();
|
||||||
|
else void trustQuery.refetch();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
重试
|
||||||
|
</Button>
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: {})}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
) : selectedRecordSource ? (
|
||||||
|
<Alert
|
||||||
|
type="info"
|
||||||
|
showIcon
|
||||||
|
message="此区域尚未配置内容"
|
||||||
|
description="创建并启用对应内容后,即可在预览中点选编辑。"
|
||||||
|
action={
|
||||||
|
<Button
|
||||||
|
onClick={() =>
|
||||||
|
guardDraft(() => {
|
||||||
|
void navigate(
|
||||||
|
selectedRecordSource === "trust"
|
||||||
|
? `/admin/trust?type=${encodeURIComponent(selectedTarget?.trustType ?? "")}`
|
||||||
|
: "/admin/services",
|
||||||
|
);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
配置此区域内容
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
) : !selectedTarget ? (
|
||||||
|
<div className="presentation-editor__empty">
|
||||||
|
<Typography.Title level={5}>选择要编辑的区域</Typography.Title>
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
点击预览中的内容,或使用区域列表,查看并修改对应字段。
|
||||||
|
</Typography.Paragraph>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
<Form
|
<Form
|
||||||
form={form}
|
form={form}
|
||||||
layout="vertical"
|
layout="vertical"
|
||||||
initialValues={initialValues}
|
initialValues={initialValues}
|
||||||
onFinish={(values) => save.mutate(values)}
|
onValuesChange={handleValuesChange}
|
||||||
style={{ minHeight: 540, display: "flex", flexDirection: "column" }}
|
onFinish={() => save.mutate(form.getFieldsValue(true) as PresentationValues)}
|
||||||
|
style={{ minHeight: 0, display: "flex", flexDirection: "column" }}
|
||||||
>
|
>
|
||||||
<div style={{ flex: 1 }}>
|
<div style={{ flex: 1 }}>
|
||||||
{editableSections.map((section, index) => (
|
{editableSections.map((section, index) => (
|
||||||
@@ -306,11 +805,7 @@ export function PresentationEditor({
|
|||||||
) : null}
|
) : null}
|
||||||
<Row gutter={16}>
|
<Row gutter={16}>
|
||||||
{section.fields.map((field) => (
|
{section.fields.map((field) => (
|
||||||
<Col
|
<Col key={field.key} xs={24} md={24}>
|
||||||
key={field.key}
|
|
||||||
xs={24}
|
|
||||||
md={field.input === "textarea" || field.input === "list" ? 24 : 12}
|
|
||||||
>
|
|
||||||
{field.input === "list" ? (
|
{field.input === "list" ? (
|
||||||
<TemplateListField
|
<TemplateListField
|
||||||
field={field}
|
field={field}
|
||||||
@@ -322,10 +817,14 @@ export function PresentationEditor({
|
|||||||
label={field.label}
|
label={field.label}
|
||||||
{...(field.help ? { help: field.help } : {})}
|
{...(field.help ? { help: field.help } : {})}
|
||||||
{...(field.required
|
{...(field.required
|
||||||
? { rules: [{ required: true, message: `请填写${field.label}` }] }
|
? {
|
||||||
|
rules: [
|
||||||
|
{ required: true, message: `请填写${field.label}` },
|
||||||
|
],
|
||||||
|
}
|
||||||
: {})}
|
: {})}
|
||||||
>
|
>
|
||||||
{renderField(field)}
|
<TemplateFieldRenderer field={field} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
)}
|
)}
|
||||||
</Col>
|
</Col>
|
||||||
@@ -333,7 +832,7 @@ export function PresentationEditor({
|
|||||||
</Row>
|
</Row>
|
||||||
</section>
|
</section>
|
||||||
))}
|
))}
|
||||||
{pageLinks.length ? (
|
{relevantPageLinks.length ? (
|
||||||
<Alert
|
<Alert
|
||||||
type="info"
|
type="info"
|
||||||
showIcon
|
showIcon
|
||||||
@@ -341,7 +840,7 @@ export function PresentationEditor({
|
|||||||
message="这个页面还有关联内容"
|
message="这个页面还有关联内容"
|
||||||
description={
|
description={
|
||||||
<Space wrap>
|
<Space wrap>
|
||||||
{pageLinks.map((item) => (
|
{relevantPageLinks.map((item) => (
|
||||||
<Button
|
<Button
|
||||||
key={item.target}
|
key={item.target}
|
||||||
type="link"
|
type="link"
|
||||||
@@ -367,11 +866,19 @@ export function PresentationEditor({
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
{!editableSections.length && !pageLinks.length ? (
|
{!editableSections.some((section) => section.fields.length) &&
|
||||||
|
!relevantPageLinks.length ? (
|
||||||
<Typography.Paragraph type="secondary">
|
<Typography.Paragraph type="secondary">
|
||||||
这个页面没有单独的品牌文案配置。
|
这个页面没有单独的品牌文案配置。
|
||||||
</Typography.Paragraph>
|
</Typography.Paragraph>
|
||||||
) : null}
|
) : null}
|
||||||
|
{selectedTarget &&
|
||||||
|
!editableSections.some((section) => section.fields.length) &&
|
||||||
|
relevantPageLinks.length ? (
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
此区域内容由对应的业务管理页面维护。
|
||||||
|
</Typography.Paragraph>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
|
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
|
||||||
<MutationError error={save.error} />
|
<MutationError error={save.error} />
|
||||||
@@ -380,11 +887,12 @@ export function PresentationEditor({
|
|||||||
</Button>
|
</Button>
|
||||||
</Space>
|
</Space>
|
||||||
</Form>
|
</Form>
|
||||||
</Col>
|
)}
|
||||||
</Row>
|
</div>
|
||||||
|
</div>
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
</Card>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,42 +4,51 @@ import type {
|
|||||||
BrandProfile,
|
BrandProfile,
|
||||||
EditorPreviewFrameMessage,
|
EditorPreviewFrameMessage,
|
||||||
EditorPreviewHostMessage,
|
EditorPreviewHostMessage,
|
||||||
|
RuntimeWorkspace,
|
||||||
} from "@personal-brand/api-client";
|
} from "@personal-brand/api-client";
|
||||||
import { templatePreviewUrl } from "../../lib/template-preview.js";
|
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";
|
import "./TemplatePreview.css";
|
||||||
|
|
||||||
export function TemplatePreview({
|
export function TemplatePreview({
|
||||||
brand,
|
brand,
|
||||||
|
workspace,
|
||||||
page,
|
page,
|
||||||
|
offeringId,
|
||||||
targetKey,
|
targetKey,
|
||||||
route,
|
selection,
|
||||||
|
targets,
|
||||||
onTargetSelected,
|
onTargetSelected,
|
||||||
}: {
|
}: {
|
||||||
brand: BrandProfile;
|
brand: BrandProfile;
|
||||||
|
workspace?: RuntimeWorkspace;
|
||||||
page: string;
|
page: string;
|
||||||
|
offeringId?: string;
|
||||||
targetKey?: string;
|
targetKey?: string;
|
||||||
route: string;
|
selection?: PreviewSelection;
|
||||||
onTargetSelected: (key: string) => void;
|
targets: PreviewTarget[];
|
||||||
|
onTargetSelected: (selection?: PreviewSelection) => void;
|
||||||
}) {
|
}) {
|
||||||
const frame = useRef<HTMLIFrameElement>(null);
|
const frame = useRef<HTMLIFrameElement>(null);
|
||||||
|
const useComponent = Boolean(workspace && resolveTemplateRenderer(workspace));
|
||||||
const [ready, setReady] = useState(false);
|
const [ready, setReady] = useState(false);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [reloadKey, setReloadKey] = useState(0);
|
const [reloadKey, setReloadKey] = useState(0);
|
||||||
const config = brand.config ?? {};
|
const url = useMemo(() => {
|
||||||
const templateKey =
|
const value = templatePreviewUrl(
|
||||||
typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : brand.templateKey;
|
|
||||||
const url = useMemo(
|
|
||||||
() =>
|
|
||||||
templatePreviewUrl(
|
|
||||||
templateKey,
|
|
||||||
brand.slug,
|
brand.slug,
|
||||||
page,
|
page,
|
||||||
import.meta.env.VITE_TEMPLATE_PREVIEW_URLS,
|
import.meta.env.VITE_TEMPLATE_PREVIEW_URL || "/template-preview/index.html",
|
||||||
window.location.origin,
|
window.location.origin,
|
||||||
route,
|
`/pages/${encodeURIComponent(page)}/index`,
|
||||||
),
|
|
||||||
[brand.slug, page, reloadKey, route, templateKey],
|
|
||||||
);
|
);
|
||||||
|
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 origin = useMemo(() => (url ? new URL(url).origin : ""), [url]);
|
||||||
const brandDraft = useMemo(
|
const brandDraft = useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
@@ -70,7 +79,7 @@ export function TemplatePreview({
|
|||||||
if (message?.protocol !== "personal-brand-editor-preview" || message.version !== 1) return;
|
if (message?.protocol !== "personal-brand-editor-preview" || message.version !== 1) return;
|
||||||
if (message.type === "ready") setReady(true);
|
if (message.type === "ready") setReady(true);
|
||||||
if (message.type === "targetSelected" && message.page === page)
|
if (message.type === "targetSelected" && message.page === page)
|
||||||
onTargetSelected(message.targetKey);
|
onTargetSelected({ targetKey: message.targetKey });
|
||||||
};
|
};
|
||||||
window.addEventListener("message", onMessage);
|
window.addEventListener("message", onMessage);
|
||||||
return () => window.removeEventListener("message", onMessage);
|
return () => window.removeEventListener("message", onMessage);
|
||||||
@@ -80,12 +89,21 @@ export function TemplatePreview({
|
|||||||
if (!ready || !frame.current?.contentWindow || !origin) return;
|
if (!ready || !frame.current?.contentWindow || !origin) return;
|
||||||
const send = (message: EditorPreviewHostMessage) =>
|
const send = (message: EditorPreviewHostMessage) =>
|
||||||
frame.current?.contentWindow?.postMessage(message, origin);
|
frame.current?.contentWindow?.postMessage(message, origin);
|
||||||
|
if (workspace) {
|
||||||
|
send({
|
||||||
|
protocol: "personal-brand-editor-preview",
|
||||||
|
version: 1,
|
||||||
|
type: "workspaceDraft",
|
||||||
|
workspace,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
send({
|
send({
|
||||||
protocol: "personal-brand-editor-preview",
|
protocol: "personal-brand-editor-preview",
|
||||||
version: 1,
|
version: 1,
|
||||||
type: "brandDraft",
|
type: "brandDraft",
|
||||||
brand: brandDraft,
|
brand: brandDraft,
|
||||||
});
|
});
|
||||||
|
}
|
||||||
if (targetKey)
|
if (targetKey)
|
||||||
send({
|
send({
|
||||||
protocol: "personal-brand-editor-preview",
|
protocol: "personal-brand-editor-preview",
|
||||||
@@ -93,7 +111,7 @@ export function TemplatePreview({
|
|||||||
type: "focusTarget",
|
type: "focusTarget",
|
||||||
targetKey,
|
targetKey,
|
||||||
});
|
});
|
||||||
}, [brandDraft, origin, ready, targetKey]);
|
}, [brandDraft, origin, ready, targetKey, workspace]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const refresh = () => setReloadKey((value) => value + 1);
|
const refresh = () => setReloadKey((value) => value + 1);
|
||||||
@@ -101,18 +119,31 @@ export function TemplatePreview({
|
|||||||
return () => window.removeEventListener("template-preview-refresh", refresh);
|
return () => window.removeEventListener("template-preview-refresh", refresh);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
if (!url)
|
if (!useComponent && !url)
|
||||||
return (
|
return (
|
||||||
<Alert
|
<Alert
|
||||||
type="warning"
|
type="warning"
|
||||||
showIcon
|
showIcon
|
||||||
message="尚未配置模板预览服务"
|
message="页面预览暂不可用"
|
||||||
description="请在 Admin 环境变量 VITE_TEMPLATE_PREVIEW_URLS 中为模板配置 H5 预览地址。"
|
description="请确认模板预览资源已构建并发布,或本地预览服务正在运行。"
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="template-preview">
|
<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 ? (
|
{!ready && !error ? (
|
||||||
<div className="template-preview__loading">
|
<div className="template-preview__loading">
|
||||||
<Spin tip="正在加载页面预览" />
|
<Spin tip="正在加载页面预览" />
|
||||||
@@ -130,6 +161,8 @@ export function TemplatePreview({
|
|||||||
onError={() => setError("请检查预览服务地址和网络连接。")}
|
onError={() => setError("请检查预览服务地址和网络连接。")}
|
||||||
style={{ opacity: ready ? 1 : 0 }}
|
style={{ opacity: ready ? 1 : 0 }}
|
||||||
/>
|
/>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
</div>
|
</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>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -31,11 +31,14 @@ function asObject(value: unknown): Record<string, unknown> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function safePath(binding: string): string[] | null {
|
function safePath(binding: string): string[] | null {
|
||||||
const prefix = ["brand.config.", "offering.config.", "trust.config."].find((candidate) =>
|
const prefixes = ["brand.config.", "offering.config.", "trust.config."];
|
||||||
binding.startsWith(candidate),
|
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) return null;
|
if (!prefix && !standardField) return null;
|
||||||
const path = binding.slice(prefix.length).split(".");
|
const path = prefix ? binding.slice(prefix.length).split(".") : [binding.split(".")[1] ?? ""];
|
||||||
if (path.some((part) => !part || ["__proto__", "prototype", "constructor"].includes(part)))
|
if (path.some((part) => !part || ["__proto__", "prototype", "constructor"].includes(part)))
|
||||||
return null;
|
return null;
|
||||||
return path;
|
return path;
|
||||||
@@ -49,10 +52,15 @@ export function readPresentationValue(
|
|||||||
config: Record<string, unknown> | null | undefined,
|
config: Record<string, unknown> | null | undefined,
|
||||||
binding: string,
|
binding: string,
|
||||||
field?: PresentationField,
|
field?: PresentationField,
|
||||||
|
brand?: Record<string, unknown>,
|
||||||
): unknown {
|
): unknown {
|
||||||
const path = safePath(binding);
|
const path = safePath(binding);
|
||||||
if (!path) return undefined;
|
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];
|
for (const part of path) value = asObject(value)[part];
|
||||||
if (field?.input === "list") {
|
if (field?.input === "list") {
|
||||||
if (!Array.isArray(value)) return [];
|
if (!Array.isArray(value)) return [];
|
||||||
@@ -88,9 +96,11 @@ export function applyPresentationValues(
|
|||||||
let nextConfig = { ...asObject(config) };
|
let nextConfig = { ...asObject(config) };
|
||||||
for (const section of sections) {
|
for (const section of sections) {
|
||||||
for (const field of section.fields) {
|
for (const field of section.fields) {
|
||||||
|
if (!field.binding.includes(".config.")) continue;
|
||||||
const path = safePath(field.binding);
|
const path = safePath(field.binding);
|
||||||
if (!path) continue;
|
if (!path) continue;
|
||||||
const raw = values[presentationFieldName(section.key, field.key)];
|
const raw = values[presentationFieldName(section.key, field.key)];
|
||||||
|
if (raw === undefined) continue;
|
||||||
const value =
|
const value =
|
||||||
field.input === "list" && Array.isArray(raw)
|
field.input === "list" && Array.isArray(raw)
|
||||||
? field.itemValueKey
|
? field.itemValueKey
|
||||||
@@ -104,3 +114,51 @@ export function applyPresentationValues(
|
|||||||
}
|
}
|
||||||
return nextConfig;
|
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 { Card, Col, Empty, Row, Typography } from "antd";
|
||||||
import { Alert, Button, Card, Form, Input, Select, Table, Tag, message } from "antd";
|
|
||||||
import type { CapabilityInstallation } from "@personal-brand/api-client";
|
|
||||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||||
import { QueryState } from "../../components/QueryState.js";
|
import { QueryState } from "../../components/QueryState.js";
|
||||||
import { createApiClient } from "../../lib/api.js";
|
import { CapabilityCard } from "./components/CapabilityCard.js";
|
||||||
|
import { useCapabilityQuery } from "./hooks/useCapabilityQueries.js";
|
||||||
const statusLabels = { enabled: "已启用", disabled: "已停用", degraded: "降级" } as const;
|
|
||||||
|
|
||||||
export function CapabilitiesPage() {
|
export function CapabilitiesPage() {
|
||||||
const queryClient = useQueryClient();
|
const query = useCapabilityQuery();
|
||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function CapabilityEditor({
|
|
||||||
record,
|
|
||||||
loading,
|
|
||||||
onSubmit,
|
|
||||||
}: {
|
|
||||||
record: CapabilityInstallation;
|
|
||||||
loading: boolean;
|
|
||||||
onSubmit: (values: {
|
|
||||||
capabilityVersion: string;
|
|
||||||
status: CapabilityInstallation["status"];
|
|
||||||
configText?: string;
|
|
||||||
}) => void;
|
|
||||||
}) {
|
|
||||||
const [form] = Form.useForm();
|
|
||||||
return (
|
return (
|
||||||
<Card size="small" style={{ maxWidth: 420 }}>
|
<QueryState loading={query.isLoading} error={query.error} onRetry={() => void query.refetch()}>
|
||||||
<Form
|
<AdminPageHeader
|
||||||
form={form}
|
title="能力管理"
|
||||||
layout="inline"
|
description="以经营者视角调整模板能力的开关与展示设置;保存后进入草稿,发布后生效。"
|
||||||
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>
|
{query.data?.length ? (
|
||||||
<Form.Item name="configText">
|
<Row gutter={[16, 16]}>
|
||||||
<Input placeholder="JSON 配置(可选)" style={{ width: 180 }} />
|
{query.data.map((capability) => (
|
||||||
</Form.Item>
|
<Col key={capability.capabilityKey} xs={24} lg={12}>
|
||||||
<Button type="primary" htmlType="submit" loading={loading}>
|
<CapabilityCard capability={capability} />
|
||||||
保存
|
</Col>
|
||||||
</Button>
|
))}
|
||||||
</Form>
|
</Row>
|
||||||
|
) : (
|
||||||
|
<Card>
|
||||||
|
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前模板没有可配置能力。" />
|
||||||
</Card>
|
</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?.installations[0]?.templateKey ??
|
||||||
workspace.data?.brand?.templateKey ??
|
workspace.data?.brand?.templateKey ??
|
||||||
brand.data?.templateKey ??
|
brand.data?.templateKey ??
|
||||||
"personal";
|
catalog.data?.industries[0]?.key ??
|
||||||
const visuals = (catalog.data?.visuals ?? []).filter((item) =>
|
null;
|
||||||
item.supportedIndustryTemplates.includes(industryKey),
|
const visuals = (catalog.data?.visuals ?? []).filter(
|
||||||
|
(item) =>
|
||||||
|
typeof industryKey === "string" && item.supportedIndustryTemplates.includes(industryKey),
|
||||||
);
|
);
|
||||||
const visualKey =
|
const visualKey =
|
||||||
typeof brand.data?.config?.visualTemplateKey === "string"
|
typeof brand.data?.config?.visualTemplateKey === "string"
|
||||||
? brand.data.config.visualTemplateKey
|
? brand.data.config.visualTemplateKey
|
||||||
: "linjing-editorial";
|
: (visuals[0]?.key ?? null);
|
||||||
const currentRelease = releases.data?.find((item) => item.status === "published");
|
const currentRelease = releases.data?.find((item) => item.status === "published");
|
||||||
const publishedHistory = (releases.data ?? []).filter(
|
const publishedHistory = (releases.data ?? []).filter(
|
||||||
(item) => item.status === "published" || item.status === "superseded",
|
(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 {
|
import { Button } from "antd";
|
||||||
Button,
|
|
||||||
Form,
|
|
||||||
Input,
|
|
||||||
Modal,
|
|
||||||
Popconfirm,
|
|
||||||
Select,
|
|
||||||
Space,
|
|
||||||
Table,
|
|
||||||
Tag,
|
|
||||||
Typography,
|
|
||||||
message,
|
|
||||||
} from "antd";
|
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import type { Offering, TemplateAdminField } from "@personal-brand/api-client";
|
import type { Offering, TemplateAdminField } from "@personal-brand/api-client";
|
||||||
import { useState } from "react";
|
import { useMemo } from "react";
|
||||||
import { createApiClient } from "../../lib/api.js";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
import { QueryState } from "../../components/QueryState.js";
|
||||||
import { TemplateListField } from "../../components/TemplateListField.js";
|
import { OfferingEditorModal } from "./OfferingEditorModal.js";
|
||||||
import {
|
import { OfferingsTable } from "./OfferingsTable.js";
|
||||||
applyPresentationValues,
|
import { detailPageLabel, hasTemplateDetailCopy, offeringPageLabel } from "./offering-model.js";
|
||||||
presentationFieldName,
|
import { buildOfferingPreviewWorkspace, previewTargetsByPage } from "./offering-preview.js";
|
||||||
readPresentationValue,
|
import { useOfferingEditor } from "./use-offering-editor.js";
|
||||||
} from "../brand/presentation-bindings.js";
|
import { useOfferingMutations, useOfferingQueries } from "./use-offering-data.js";
|
||||||
import { MutationError, QueryState } from "../../components/QueryState.js";
|
|
||||||
|
type PreviewPage = "offerings" | "detail";
|
||||||
|
|
||||||
export function ServicesPage() {
|
export function ServicesPage() {
|
||||||
const client = createApiClient();
|
const navigate = useNavigate();
|
||||||
const queryClient = useQueryClient();
|
const { offerings, workspace, previewWorkspace, templateFields, retry } = useOfferingQueries();
|
||||||
const [offeringForm] = Form.useForm();
|
const editor = useOfferingEditor(templateFields);
|
||||||
const [offeringOpen, setOfferingOpen] = useState(false);
|
const mutations = useOfferingMutations({
|
||||||
const [editingOffering, setEditingOffering] = useState<Offering | null>(null);
|
editingOffering: editor.editingOffering,
|
||||||
const offerings = useQuery({
|
templateFields,
|
||||||
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">);
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
message.success("业务提供项已保存");
|
editor.closeOffering();
|
||||||
setOfferingOpen(false);
|
editor.offeringForm.resetFields();
|
||||||
setEditingOffering(null);
|
|
||||||
offeringForm.resetFields();
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const deleteOffering = useMutation({
|
|
||||||
mutationFn: (id: string) => client.deleteAdminOffering(id),
|
const sections = workspace.data?.templateContent?.admin.sections ?? [];
|
||||||
onSuccess: () => {
|
const previewTargets = useMemo(() => previewTargetsByPage(sections), [sections]);
|
||||||
message.success("业务提供项已删除");
|
const listTarget = previewTargets.offerings.find((target) =>
|
||||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
templateFields.some((field) => field.previewTarget === target.key),
|
||||||
},
|
) ?? {
|
||||||
});
|
key: "offering.list.item",
|
||||||
const toggleOffering = useMutation({
|
label: "业务卡片",
|
||||||
mutationFn: ({ id, isEnabled }: { id: string; isEnabled: boolean }) =>
|
page: "offerings",
|
||||||
client.updateAdminOffering(id, { isEnabled }),
|
source: "offering",
|
||||||
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 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 (
|
return (
|
||||||
<QueryState
|
<QueryState
|
||||||
loading={offerings.isLoading || workspace.isLoading}
|
loading={offerings.isLoading || workspace.isLoading}
|
||||||
error={offerings.error || workspace.error}
|
error={offerings.error || workspace.error}
|
||||||
onRetry={() => {
|
onRetry={retry}
|
||||||
void offerings.refetch();
|
|
||||||
void workspace.refetch();
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<AdminPageHeader
|
<AdminPageHeader
|
||||||
title="小程序内容:业务展示与详情"
|
title="小程序内容:业务展示与详情"
|
||||||
description={`在「${offeringPageLabel}」管理访客能选择的服务、产品或案例;每项内容的补充资料会显示在对应的「${detailPageLabel}」。`}
|
description={`在「${offeringPageLabel(workspace.data?.templateContent ?? undefined)}」管理访客能选择的服务、产品或案例;每项内容的补充资料会显示在对应的「${detailPageLabel(workspace.data?.templateContent ?? undefined)}」。`}
|
||||||
extra={
|
extra={
|
||||||
<Button type="primary" onClick={() => beginOffering()}>
|
<Button type="primary" onClick={() => editor.beginOffering()}>
|
||||||
新增业务提供项
|
新增业务提供项
|
||||||
</Button>
|
</Button>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<section aria-label="业务提供项列表">
|
<OfferingsTable
|
||||||
<Space wrap style={{ marginBottom: 16 }}>
|
pageLabel={offeringPageLabel(workspace.data?.templateContent ?? undefined)}
|
||||||
<Typography.Title level={5} style={{ margin: 0 }}>
|
detailSectionTitles={sections
|
||||||
{offeringPageLabel}中的内容
|
.filter((section) => section.target === "offering" && section.page === "detail")
|
||||||
</Typography.Title>
|
.map((section) => section.title)}
|
||||||
<Tag color="blue">已启用的项目会公开展示</Tag>
|
items={offerings.data ?? []}
|
||||||
</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}
|
loading={offerings.isLoading}
|
||||||
dataSource={offerings.data ?? []}
|
saveError={mutations.saveOffering.error}
|
||||||
columns={[
|
toggleOffering={mutations.toggleOffering}
|
||||||
{ title: "名称", dataIndex: "name" },
|
deleteOffering={mutations.deleteOffering}
|
||||||
{
|
onEdit={(item: Offering) => editor.beginOffering(item)}
|
||||||
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 && (
|
<OfferingEditorModal
|
||||||
<Typography.Paragraph type="secondary">
|
open={editor.offeringOpen}
|
||||||
还没有公开业务提供项。创建后,小程序服务页会优先读取这些内容。
|
editingOffering={editor.editingOffering}
|
||||||
</Typography.Paragraph>
|
form={editor.offeringForm}
|
||||||
)}
|
previewPage={editor.previewPage}
|
||||||
<MutationError error={saveOffering.error} />
|
previewWorkspace={previewWorkspaceDraft}
|
||||||
<MutationError error={toggleOffering.error} />
|
previewTargets={previewTargets}
|
||||||
<MutationError error={deleteOffering.error} />
|
activeTemplateFields={activeTemplateFields}
|
||||||
</section>
|
templateFieldSection={editor.templateFieldSection}
|
||||||
<Modal
|
hasTemplateDetailCopy={hasTemplateDetailCopy(templateFields)}
|
||||||
open={offeringOpen}
|
listTarget={listTarget}
|
||||||
title={editingOffering ? "编辑业务提供项" : "新增业务提供项"}
|
detailTarget={detailTarget}
|
||||||
onCancel={() => {
|
saving={mutations.saveOffering.isPending}
|
||||||
setOfferingOpen(false);
|
onClose={editor.closeOffering}
|
||||||
setEditingOffering(null);
|
onPreviewPageChange={(page: PreviewPage) => editor.setPreviewPage(page)}
|
||||||
offeringForm.resetFields();
|
onValuesChange={(values) => editor.handleValuesChange(null, values)}
|
||||||
}}
|
onFinish={(values) => mutations.saveOffering.mutate(values)}
|
||||||
onOk={() => offeringForm.submit()}
|
onEditInBrand={navigateToBrand}
|
||||||
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>
|
|
||||||
</QueryState>
|
</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="登录账号"
|
label="登录账号"
|
||||||
rules={[{ required: true, message: "请输入登录账号" }]}
|
rules={[{ required: true, message: "请输入登录账号" }]}
|
||||||
>
|
>
|
||||||
<Input placeholder="例如:linran" />
|
<Input placeholder="例如:brand-owner" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name="displayName"
|
name="displayName"
|
||||||
label="成员姓名"
|
label="成员姓名"
|
||||||
rules={[{ required: true, message: "请输入成员姓名" }]}
|
rules={[{ required: true, message: "请输入成员姓名" }]}
|
||||||
>
|
>
|
||||||
<Input placeholder="例如:林然" />
|
<Input placeholder="例如:品牌主理人" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name="password"
|
name="password"
|
||||||
|
|||||||
@@ -1,185 +1,51 @@
|
|||||||
import {
|
import { Button, Divider, Form, Typography } from "antd";
|
||||||
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 { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
import { QueryState } from "../../components/QueryState.js";
|
||||||
import { TemplateListField } from "../../components/TemplateListField.js";
|
import { TrustContentEditorModal } from "./components/TrustContentEditorModal.js";
|
||||||
import { MutationError, QueryState } from "../../components/QueryState.js";
|
import { TrustContentTable } from "./components/TrustContentTable.js";
|
||||||
|
import { TrustRequirementsList } from "./components/TrustRequirementsList.js";
|
||||||
const types = [
|
import type { TrustTypeOption } from "./domain/trust-content-domain.js";
|
||||||
{
|
import {
|
||||||
value: "schedule",
|
createTrustPageLabelResolver,
|
||||||
label: "时间与服务安排",
|
groupTrustContentByType,
|
||||||
help: "说明你通常什么时候提供服务、接受预约或处理订单。多项内容可以分行填写。",
|
selectTrustTypeOptions,
|
||||||
},
|
} from "./domain/trust-content-domain.js";
|
||||||
{
|
import { useTrustContentEditor } from "./hooks/useTrustContentEditor.js";
|
||||||
value: "coverage",
|
import { useTrustContentQueries } from "./hooks/useTrustContentQueries.js";
|
||||||
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,
|
|
||||||
}));
|
|
||||||
|
|
||||||
export function TrustContentPage() {
|
export function TrustContentPage() {
|
||||||
const client = createApiClient();
|
const { query, workspace } = useTrustContentQueries();
|
||||||
const queryClient = useQueryClient();
|
const availableTypes = selectTrustTypeOptions(workspace.data?.templateContent?.trustContentTypes);
|
||||||
const [editing, setEditing] = useState<TrustContent | null>(null);
|
const pageLabel = createTrustPageLabelResolver(workspace.data?.templateContent?.navigation);
|
||||||
const [open, setOpen] = useState(false);
|
const contentByType = groupTrustContentByType(query.data ?? []);
|
||||||
const [form] = Form.useForm<TrustContentInput>();
|
const firstMissingRequiredType =
|
||||||
const [searchParams] = useSearchParams();
|
availableTypes.find((item) => item.required && !contentByType.has(item.type))?.type ??
|
||||||
const selectedType = Form.useWatch("type", form);
|
availableTypes[0]?.type ??
|
||||||
const query = useQuery({
|
"credential";
|
||||||
queryKey: ["trust-content"],
|
const {
|
||||||
queryFn: () => client.listAdminTrustContent(),
|
begin,
|
||||||
|
closeEditor,
|
||||||
|
editing,
|
||||||
|
form: editorForm,
|
||||||
|
open,
|
||||||
|
remove,
|
||||||
|
save,
|
||||||
|
} = useTrustContentEditor({
|
||||||
|
availableTypes,
|
||||||
|
contentByType,
|
||||||
|
firstMissingRequiredType,
|
||||||
});
|
});
|
||||||
const workspace = useQuery({
|
const selectedType = Form.useWatch("type", editorForm);
|
||||||
queryKey: ["admin-workspace-trust-types"],
|
const selectedTypeMeta: TrustTypeOption | undefined = availableTypes.find(
|
||||||
queryFn: () => client.getAdminWorkspace(),
|
(item) => item.type === selectedType,
|
||||||
});
|
);
|
||||||
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 trustPageLabels = [
|
const trustPageLabels = [
|
||||||
...new Set(availableTypes.flatMap((item) => item.pages ?? []).map(pageLabel)),
|
...new Set(availableTypes.flatMap((item) => item.pages ?? []).map(pageLabel)),
|
||||||
];
|
];
|
||||||
const trustPlacement = trustPageLabels.length
|
const trustPlacement = trustPageLabels.length
|
||||||
? `小程序的${trustPageLabels.join("、")}中`
|
? `小程序的${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 (
|
return (
|
||||||
<QueryState
|
<QueryState
|
||||||
loading={query.isLoading || workspace.isLoading}
|
loading={query.isLoading || workspace.isLoading}
|
||||||
@@ -202,213 +68,34 @@ export function TrustContentPage() {
|
|||||||
<Typography.Paragraph type="secondary">
|
<Typography.Paragraph type="secondary">
|
||||||
标记为“发布必填”的项目需要填写完整后,才能发布小程序。
|
标记为“发布必填”的项目需要填写完整后,才能发布小程序。
|
||||||
</Typography.Paragraph>
|
</Typography.Paragraph>
|
||||||
<List
|
<TrustRequirementsList
|
||||||
size="small"
|
availableTypes={availableTypes}
|
||||||
dataSource={availableTypes}
|
contentByType={contentByType}
|
||||||
renderItem={(item) => {
|
items={query.data ?? []}
|
||||||
const content = contentByType.get(item.type);
|
onEdit={begin}
|
||||||
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>
|
|
||||||
);
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</section>
|
</section>
|
||||||
<Divider />
|
<Divider />
|
||||||
<section aria-label="已配置的品牌内容">
|
<TrustContentTable
|
||||||
<Table
|
availableTypes={availableTypes}
|
||||||
rowKey="id"
|
items={query.data ?? []}
|
||||||
dataSource={query.data ?? []}
|
removeError={remove.error}
|
||||||
locale={{ emptyText: "还没有品牌内容,请先按上方模板要求添加。" }}
|
removePending={remove.isPending}
|
||||||
columns={[
|
onEdit={(item) => begin(item)}
|
||||||
{
|
onDelete={(id) => remove.mutate(id)}
|
||||||
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} />
|
<TrustContentEditorModal
|
||||||
</section>
|
availableTypes={availableTypes}
|
||||||
<Modal
|
editing={editing}
|
||||||
|
form={editorForm}
|
||||||
open={open}
|
open={open}
|
||||||
title={editing ? "编辑品牌内容" : "添加品牌内容"}
|
pageLabel={pageLabel}
|
||||||
onCancel={() => {
|
saveError={save.error}
|
||||||
setOpen(false);
|
savePending={save.isPending}
|
||||||
setEditing(null);
|
selectedTypeMeta={selectedTypeMeta}
|
||||||
form.resetFields();
|
onCancel={closeEditor}
|
||||||
}}
|
onFinish={(values) => save.mutate(values)}
|
||||||
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>
|
|
||||||
</QueryState>
|
</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 {
|
import { Button, Card, Form, Input, Modal, Select, Space, Table, Tag, Typography } from "antd";
|
||||||
Button,
|
|
||||||
Card,
|
|
||||||
Form,
|
|
||||||
Input,
|
|
||||||
Modal,
|
|
||||||
Select,
|
|
||||||
Space,
|
|
||||||
Table,
|
|
||||||
Tag,
|
|
||||||
Typography,
|
|
||||||
message,
|
|
||||||
} from "antd";
|
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { createApiClient } from "../../lib/api.js";
|
|
||||||
import { ApiClientError } from "@personal-brand/api-client";
|
import { ApiClientError } from "@personal-brand/api-client";
|
||||||
|
import { createApiClient } from "../../lib/api.js";
|
||||||
import type {
|
import type {
|
||||||
BrandFieldDefinition,
|
BrandFieldDefinition,
|
||||||
BrandTemplateKey,
|
BrandTemplateKey,
|
||||||
InquiryForm,
|
InquiryForm,
|
||||||
} from "@personal-brand/api-client";
|
} from "@personal-brand/api-client";
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { useState } from "react";
|
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 { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||||
import { MutationError } from "../../components/QueryState.js";
|
import { MutationError } from "../../components/QueryState.js";
|
||||||
|
|
||||||
const inquiryFieldTypes = [
|
export const inquiryFieldTypes = [
|
||||||
{ value: "text", label: "简短文字" },
|
{ value: "text", label: "简短文字" },
|
||||||
{ value: "textarea", label: "详细说明" },
|
{ value: "textarea", label: "详细说明" },
|
||||||
{ value: "phone", label: "联系电话" },
|
{ value: "phone", label: "联系电话" },
|
||||||
@@ -36,53 +31,28 @@ const inquiryFieldTypes = [
|
|||||||
{ value: "multi-select", label: "多项选择" },
|
{ value: "multi-select", label: "多项选择" },
|
||||||
];
|
];
|
||||||
|
|
||||||
function optionsToText(options: unknown): string {
|
export function readOptionLabel(option: unknown): string {
|
||||||
if (!Array.isArray(options)) return "";
|
const value = option as { label?: unknown } | null | undefined;
|
||||||
return options
|
return typeof value?.label === "string" ? value.label : "";
|
||||||
.map((option) => {
|
|
||||||
if (!option || typeof option !== "object") return "";
|
|
||||||
const label = (option as { label?: unknown }).label;
|
|
||||||
return typeof label === "string" ? label : "";
|
|
||||||
})
|
|
||||||
.filter(Boolean)
|
|
||||||
.join("\n");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function optionsFromText(value: unknown): Array<{ label: string; value: string }> {
|
export function normalizeOptionLabels(options: unknown): Array<{ label: string; value: string }> {
|
||||||
if (typeof value !== "string") return [];
|
return (Array.isArray(options) ? options : [])
|
||||||
return value
|
.map(readOptionLabel)
|
||||||
.split(/\r?\n|、|,/)
|
.filter((label) => label.trim())
|
||||||
.map((item) => item.trim())
|
.map((label) => ({ label, value: label }));
|
||||||
.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 WorkspacePage() {
|
export function WorkspacePage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const client = createApiClient();
|
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const [fieldOpen, setFieldOpen] = useState(false);
|
const [fieldOpen, setFieldOpen] = useState(false);
|
||||||
const [formOpen, setFormOpen] = useState(false);
|
const [formOpen, setFormOpen] = useState(false);
|
||||||
const [editingForm, setEditingForm] = useState<InquiryForm | null>(null);
|
const [editingForm, setEditingForm] = useState<InquiryForm | null>(null);
|
||||||
const [visualTarget, setVisualTarget] = useState<string | null>(null);
|
const [visualTarget, setVisualTarget] = useState<string | null>(null);
|
||||||
const [industryTarget, setIndustryTarget] = useState<{
|
const [industryTarget, setIndustryTarget] = useState<IndustryTarget | null>(null);
|
||||||
key: "personal" | "food" | "doors";
|
const [previewIndustry, setPreviewIndustry] = useState<BrandTemplateKey | null>(null);
|
||||||
name: string;
|
const [previewVisual, setPreviewVisual] = useState<string | null>(null);
|
||||||
description: string;
|
|
||||||
capabilities: string[];
|
|
||||||
} | null>(null);
|
|
||||||
const [previewIndustry, setPreviewIndustry] = useState<BrandTemplateKey>("personal");
|
|
||||||
const [previewVisual, setPreviewVisual] = useState("linjing-editorial");
|
|
||||||
const [form] = Form.useForm<Record<string, unknown>>();
|
const [form] = Form.useForm<Record<string, unknown>>();
|
||||||
const [inquiryForm] = Form.useForm<Record<string, unknown>>();
|
const [inquiryForm] = Form.useForm<Record<string, unknown>>();
|
||||||
const openNewInquiryForm = () => {
|
const openNewInquiryForm = () => {
|
||||||
@@ -98,126 +68,49 @@ export function WorkspacePage() {
|
|||||||
});
|
});
|
||||||
setFormOpen(true);
|
setFormOpen(true);
|
||||||
};
|
};
|
||||||
const query = useQuery({
|
const { query, runtimeQuery, templateCatalog, forms, templatePreview } = useWorkspaceQueries();
|
||||||
queryKey: ["admin-workspace"],
|
const previewIndustryKey =
|
||||||
queryFn: () => client.getAdminWorkspace(),
|
previewIndustry ??
|
||||||
});
|
query.data?.brand.templateKey ??
|
||||||
const runtimeQuery = useQuery({
|
query.data?.installations[0]?.templateKey ??
|
||||||
queryKey: ["public-runtime-workspace"],
|
templateCatalog.data?.industries[0]?.key;
|
||||||
queryFn: () => client.getPublicWorkspace(),
|
const previewVisualKey =
|
||||||
});
|
previewVisual ??
|
||||||
const templateCatalog = useQuery({
|
runtimeQuery.data?.visualTemplate?.key ??
|
||||||
queryKey: ["template-catalog"],
|
(templateCatalog.data?.visuals ?? []).find((visual) =>
|
||||||
queryFn: () => client.listPublicTemplates(),
|
supportsIndustry(visual, previewIndustryKey ?? ""),
|
||||||
});
|
)?.key;
|
||||||
const combinationPreview = useQuery({
|
const combinationPreview = useQuery({
|
||||||
queryKey: ["template-combination-preview", previewIndustry, previewVisual],
|
queryKey: ["template-combination-preview", previewIndustryKey, previewVisualKey],
|
||||||
queryFn: () => client.previewPublicTemplateCombination(previewIndustry, previewVisual),
|
queryFn: () =>
|
||||||
enabled: Boolean(templateCatalog.data),
|
createApiClient().previewPublicTemplateCombination(
|
||||||
|
previewIndustryKey ?? "",
|
||||||
|
previewVisualKey ?? "",
|
||||||
|
),
|
||||||
|
enabled: Boolean(templateCatalog.data && previewIndustryKey && previewVisualKey),
|
||||||
});
|
});
|
||||||
const compatibleVisuals = (templateCatalog.data?.visuals ?? []).filter((visual) =>
|
const compatibleVisuals = (templateCatalog.data?.visuals ?? []).filter((visual) =>
|
||||||
supportsIndustry(visual, query.data?.brand?.templateKey ?? "personal"),
|
supportsIndustry(visual, query.data?.brand?.templateKey ?? ""),
|
||||||
);
|
);
|
||||||
const visualTemplate = useMutation({
|
const { visualTemplate, rollbackVisual, install, upgrade, rollback } = useTemplateMutations({
|
||||||
mutationFn: (key: string) =>
|
runtimeConfig: runtimeQuery.data?.brand?.config ?? undefined,
|
||||||
client.updateAdminBrand({
|
queryClient,
|
||||||
config: { ...(runtimeQuery.data?.brand?.config ?? {}), visualTemplateKey: key },
|
|
||||||
}),
|
|
||||||
onSuccess: () => {
|
|
||||||
message.success("视觉模板已切换");
|
|
||||||
void runtimeQuery.refetch();
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
const visualHistory = useQuery({
|
const visualHistory = useQuery({
|
||||||
queryKey: ["visual-template-history"],
|
queryKey: ["visual-template-history"],
|
||||||
queryFn: () => client.getAdminVisualTemplateHistory(),
|
queryFn: () => createApiClient().getAdminVisualTemplateHistory(),
|
||||||
});
|
});
|
||||||
const rollbackVisual = useMutation({
|
const { createField, removeField } = useFieldMutations({
|
||||||
mutationFn: () => client.rollbackAdminVisualTemplate(),
|
form,
|
||||||
onSuccess: () => {
|
queryClient,
|
||||||
message.success("视觉模板已回滚");
|
onClose: () => setFieldOpen(false),
|
||||||
void runtimeQuery.refetch();
|
|
||||||
void visualHistory.refetch();
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
const install = useMutation({
|
const { createForm, updateForm } = useInquiryFormMutations({
|
||||||
mutationFn: (key: "personal" | "food" | "doors") => client.installAdminTemplate(key),
|
form: inquiryForm,
|
||||||
onSuccess: () => {
|
queryClient,
|
||||||
message.success("模板已安装");
|
onClose: () => {
|
||||||
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("咨询表单已更新");
|
|
||||||
setFormOpen(false);
|
setFormOpen(false);
|
||||||
setEditingForm(null);
|
setEditingForm(null);
|
||||||
inquiryForm.resetFields();
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-forms"] });
|
|
||||||
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (query.isLoading) return <Card loading />;
|
if (query.isLoading) return <Card loading />;
|
||||||
@@ -306,9 +199,9 @@ export function WorkspacePage() {
|
|||||||
<Space wrap>
|
<Space wrap>
|
||||||
<Typography.Text strong>视觉模板</Typography.Text>
|
<Typography.Text strong>视觉模板</Typography.Text>
|
||||||
<Select
|
<Select
|
||||||
value={runtimeQuery.data?.visualTemplate?.key ?? "linjing-editorial"}
|
value={runtimeQuery.data?.visualTemplate?.key}
|
||||||
loading={visualTemplate.isPending}
|
loading={visualTemplate.isPending}
|
||||||
onChange={(key) => setVisualTarget(key)}
|
onChange={(key) => setVisualTarget(key ?? null)}
|
||||||
options={[
|
options={[
|
||||||
...compatibleVisuals.map((visual) => ({ value: visual.key, label: visual.name })),
|
...compatibleVisuals.map((visual) => ({ value: visual.key, label: visual.name })),
|
||||||
]}
|
]}
|
||||||
@@ -475,18 +368,18 @@ export function WorkspacePage() {
|
|||||||
</Typography.Paragraph>
|
</Typography.Paragraph>
|
||||||
<Space wrap>
|
<Space wrap>
|
||||||
<Select
|
<Select
|
||||||
value={previewIndustry}
|
value={previewIndustryKey ?? null}
|
||||||
onChange={setPreviewIndustry}
|
onChange={(key) => setPreviewIndustry(key)}
|
||||||
options={(templateCatalog.data?.industries ?? []).map((item) => ({
|
options={(templateCatalog.data?.industries ?? []).map((item) => ({
|
||||||
value: item.key,
|
value: item.key,
|
||||||
label: item.name,
|
label: item.name,
|
||||||
}))}
|
}))}
|
||||||
/>
|
/>
|
||||||
<Select
|
<Select
|
||||||
value={previewVisual}
|
value={previewVisualKey ?? null}
|
||||||
onChange={setPreviewVisual}
|
onChange={(key) => setPreviewVisual(key)}
|
||||||
options={(templateCatalog.data?.visuals ?? [])
|
options={(templateCatalog.data?.visuals ?? [])
|
||||||
.filter((item) => supportsIndustry(item, previewIndustry))
|
.filter((item) => supportsIndustry(item, previewIndustryKey ?? ""))
|
||||||
.map((item) => ({ value: item.key, label: item.name }))}
|
.map((item) => ({ value: item.key, label: item.name }))}
|
||||||
/>
|
/>
|
||||||
</Space>
|
</Space>
|
||||||
@@ -541,11 +434,11 @@ export function WorkspacePage() {
|
|||||||
name: item.name,
|
name: item.name,
|
||||||
purpose: item.purpose,
|
purpose: item.purpose,
|
||||||
offeringId: item.offeringId ?? undefined,
|
offeringId: item.offeringId ?? undefined,
|
||||||
fieldsSnapshot: item.fieldsSnapshot.map((field) => {
|
fieldsSnapshot: item.fieldsSnapshot.map((field: unknown) => {
|
||||||
const value = field as Record<string, unknown>;
|
const value = field as Record<string, unknown>;
|
||||||
return {
|
return {
|
||||||
...value,
|
...value,
|
||||||
optionsText: optionsToText(value.options),
|
options: normalizeOptionLabels(value.options),
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -719,12 +612,15 @@ export function WorkspacePage() {
|
|||||||
fieldsSnapshot: (Array.isArray(values.fieldsSnapshot)
|
fieldsSnapshot: (Array.isArray(values.fieldsSnapshot)
|
||||||
? values.fieldsSnapshot
|
? values.fieldsSnapshot
|
||||||
: []
|
: []
|
||||||
).map((field) => {
|
).map((field: unknown) => {
|
||||||
const item = field as Record<string, 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";
|
const type = typeof rest.type === "string" ? rest.type : "text";
|
||||||
return ["select", "radio", "multi-select"].includes(type)
|
return ["select", "radio", "multi-select"].includes(type)
|
||||||
? { ...rest, options: optionsFromText(optionsText) }
|
? {
|
||||||
|
...rest,
|
||||||
|
options: normalizeOptionLabels(options),
|
||||||
|
}
|
||||||
: rest;
|
: rest;
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
@@ -824,18 +720,54 @@ export function WorkspacePage() {
|
|||||||
["select", "radio", "multi-select"].includes(
|
["select", "radio", "multi-select"].includes(
|
||||||
String(getFieldValue(["fieldsSnapshot", name, "type"])),
|
String(getFieldValue(["fieldsSnapshot", name, "type"])),
|
||||||
) ? (
|
) ? (
|
||||||
<Form.Item
|
<Form.List
|
||||||
{...restField}
|
name={[name, "options"]}
|
||||||
name={[name, "optionsText"]}
|
rules={[
|
||||||
label="可选内容"
|
{
|
||||||
help="每行填写一个选项,也可以用顿号分隔。"
|
validator: (_, value: unknown) =>
|
||||||
rules={[{ required: true, message: "请至少填写一个选项" }]}
|
Array.isArray(value) &&
|
||||||
|
value.some((option: unknown) => readOptionLabel(option).trim())
|
||||||
|
? Promise.resolve()
|
||||||
|
: Promise.reject(new Error("请至少添加一个选项")),
|
||||||
|
},
|
||||||
|
]}
|
||||||
>
|
>
|
||||||
<Input.TextArea
|
{(optionFields, { add, remove }, { errors }) => (
|
||||||
rows={2}
|
<>
|
||||||
placeholder="例如:预算内、需要沟通、暂不确定"
|
{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>
|
</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
|
) : null
|
||||||
}
|
}
|
||||||
</Form.Item>
|
</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)
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,25 +1,13 @@
|
|||||||
export function templatePreviewUrl(
|
export function templatePreviewUrl(
|
||||||
templateKey: string,
|
|
||||||
brandSlug: string | undefined,
|
brandSlug: string | undefined,
|
||||||
page: string,
|
page: string,
|
||||||
configured: string | undefined,
|
configured: string | undefined,
|
||||||
parentOrigin?: string,
|
parentOrigin?: string,
|
||||||
route?: string,
|
route?: string,
|
||||||
): string | undefined {
|
): string | undefined {
|
||||||
let urls: Record<string, unknown>;
|
const raw = configured || "http://localhost:3002";
|
||||||
try {
|
try {
|
||||||
const parsed: unknown = configured ? JSON.parse(configured) : {};
|
const url = new URL(raw, parentOrigin);
|
||||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
urls = parsed as Record<string, unknown>;
|
|
||||||
} catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
const raw = urls[templateKey];
|
|
||||||
if (typeof raw !== "string" || !raw) return undefined;
|
|
||||||
try {
|
|
||||||
const url = new URL(raw);
|
|
||||||
url.searchParams.set("editor", "1");
|
url.searchParams.set("editor", "1");
|
||||||
if (parentOrigin) url.searchParams.set("parentOrigin", parentOrigin);
|
if (parentOrigin) url.searchParams.set("parentOrigin", parentOrigin);
|
||||||
if (brandSlug) url.searchParams.set("brand", brandSlug);
|
if (brandSlug) url.searchParams.set("brand", brandSlug);
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
interface ImportMetaEnv {
|
interface ImportMetaEnv {
|
||||||
|
readonly DEV: boolean;
|
||||||
|
readonly PROD: boolean;
|
||||||
readonly VITE_API_BASE_URL?: string;
|
readonly VITE_API_BASE_URL?: string;
|
||||||
readonly VITE_APP_BASE_PATH?: string;
|
readonly VITE_APP_BASE_PATH?: string;
|
||||||
readonly VITE_TEMPLATE_PREVIEW_URLS?: string;
|
readonly VITE_TEMPLATE_PREVIEW_URL?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ImportMeta {
|
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,10 +1,16 @@
|
|||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import {
|
import {
|
||||||
applyPresentationValues,
|
applyPresentationValues,
|
||||||
|
applyBrandPreviewValues,
|
||||||
|
applyStandardEntityValues,
|
||||||
filterSectionsForPreviewTarget,
|
filterSectionsForPreviewTarget,
|
||||||
presentationFieldName,
|
presentationFieldName,
|
||||||
readPresentationValue,
|
readPresentationValue,
|
||||||
} from "../src/features/brand/presentation-bindings.ts";
|
} from "../src/features/brand/presentation-bindings.ts";
|
||||||
|
import {
|
||||||
|
resolvePreviewSelection,
|
||||||
|
previewTrustRecordId,
|
||||||
|
} from "../src/features/brand/preview-selection.ts";
|
||||||
|
|
||||||
const config = {
|
const config = {
|
||||||
founder: "阿成",
|
founder: "阿成",
|
||||||
@@ -124,3 +130,95 @@ const offering = applyPresentationValues(
|
|||||||
{ [presentationFieldName("offering", "background")]: "新背景" },
|
{ [presentationFieldName("offering", "background")]: "新背景" },
|
||||||
);
|
);
|
||||||
assert.deepEqual(offering.details, { background: "新背景", preserve: "保留" });
|
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);
|
||||||
@@ -2,12 +2,11 @@ import assert from "node:assert/strict";
|
|||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
import { templatePreviewUrl } from "../src/lib/template-preview.ts";
|
import { templatePreviewUrl } from "../src/lib/template-preview.ts";
|
||||||
|
|
||||||
test("template preview URL is resolved from generic deployment configuration", () => {
|
test("template preview URL is resolved from one shared deployment address", () => {
|
||||||
const url = templatePreviewUrl(
|
const url = templatePreviewUrl(
|
||||||
"new-template",
|
|
||||||
"brand-a",
|
"brand-a",
|
||||||
"profile",
|
"profile",
|
||||||
JSON.stringify({ "new-template": "https://preview.example.test/app/" }),
|
"https://preview.example.test/app/",
|
||||||
"https://admin.example.test",
|
"https://admin.example.test",
|
||||||
"/pages/profile/index",
|
"/pages/profile/index",
|
||||||
);
|
);
|
||||||
@@ -17,11 +16,18 @@ test("template preview URL is resolved from generic deployment configuration", (
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("missing, malformed or invalid template preview configuration fails closed", () => {
|
test("the shared same-origin preview address is the default", () => {
|
||||||
assert.equal(templatePreviewUrl("missing", "brand-a", "home", undefined), undefined);
|
|
||||||
assert.equal(templatePreviewUrl("missing", "brand-a", "home", "{"), undefined);
|
|
||||||
assert.equal(
|
assert.equal(
|
||||||
templatePreviewUrl("broken", "brand-a", "home", JSON.stringify({ broken: "not a URL" })),
|
templatePreviewUrl("brand-a", "home", undefined),
|
||||||
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 { defineConfig } from "vite";
|
||||||
import react from "@vitejs/plugin-react";
|
import react from "@vitejs/plugin-react";
|
||||||
|
import { templatePreviewCss } from "./template-preview-css.mjs";
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [react()],
|
plugins: [react()],
|
||||||
|
css: { postcss: { plugins: [templatePreviewCss()] } },
|
||||||
base: process.env.VITE_APP_BASE_PATH ?? "/",
|
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: {
|
server: {
|
||||||
host: "0.0.0.0",
|
host: "0.0.0.0",
|
||||||
port: Number(process.env.ADMIN_PORT ?? 3000),
|
port: Number(process.env.ADMIN_PORT ?? 3000),
|
||||||
@@ -12,6 +28,19 @@ export default defineConfig({
|
|||||||
target: process.env.VITE_DEV_API_TARGET ?? "http://localhost:3001",
|
target: process.env.VITE_DEV_API_TARGET ?? "http://localhost:3001",
|
||||||
rewrite: (path) => path.replace(/^\/api/, ""),
|
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" },
|
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 .",
|
"lint": "eslint .",
|
||||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||||
"test": "tsx --test test/**/*.test.ts",
|
"test": "tsx --test test/**/*.test.ts",
|
||||||
"test:integration": "pnpm build && node --env-file=.env test/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",
|
"clean": "rimraf dist",
|
||||||
"start": "node dist/main.js",
|
"start": "node dist/main.js",
|
||||||
"db:generate": "prisma generate",
|
"db:generate": "prisma generate",
|
||||||
@@ -17,6 +17,10 @@
|
|||||||
"db:seed": "tsx prisma/seed.ts"
|
"db:seed": "tsx prisma/seed.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"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/common": "^11.0.11",
|
||||||
"@nestjs/core": "^11.0.11",
|
"@nestjs/core": "^11.0.11",
|
||||||
"@nestjs/platform-fastify": "^11.0.11",
|
"@nestjs/platform-fastify": "^11.0.11",
|
||||||
@@ -27,13 +31,13 @@
|
|||||||
"bcryptjs": "^2.4.3",
|
"bcryptjs": "^2.4.3",
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.14.1",
|
"class-validator": "^0.14.1",
|
||||||
"fastify": "^5.2.1",
|
"fastify": "^5.11.3",
|
||||||
|
"prisma": "^6.2.1",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.1"
|
"rxjs": "^7.8.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^22.10.5",
|
"@types/node": "^22.10.5",
|
||||||
"prisma": "^6.2.1",
|
|
||||||
"tsx": "^4.19.2"
|
"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 {
|
generator client {
|
||||||
provider = "prisma-client-js"
|
provider = "prisma-client-js"
|
||||||
|
binaryTargets = ["linux-musl-openssl-3.0.x", "debian-openssl-3.0.x"]
|
||||||
}
|
}
|
||||||
|
|
||||||
datasource db {
|
datasource db {
|
||||||
|
|||||||
@@ -7,19 +7,16 @@ const prisma = new PrismaClient();
|
|||||||
|
|
||||||
const runtimeImages = {
|
const runtimeImages = {
|
||||||
doors: [
|
doors: [
|
||||||
"https://images.unsplash.com/photo-1513694203232-719a280e022f?auto=format&fit=crop&w=1000&q=85",
|
"/media/seed/doors-hero.jpg",
|
||||||
"https://images.unsplash.com/photo-1541123437800-1bb1317badc2?auto=format&fit=crop&w=1000&q=85",
|
"/media/seed/doors-yard-gate.jpg",
|
||||||
"https://images.unsplash.com/photo-1505691938895-1758d7feb511?auto=format&fit=crop&w=1000&q=85",
|
"/media/seed/doors-room-door.jpg",
|
||||||
],
|
],
|
||||||
food: [
|
food: [
|
||||||
"https://images.unsplash.com/photo-1547592180-85f173990554?auto=format&fit=crop&w=1000&q=85",
|
"/media/seed/food-package-01.jpg",
|
||||||
"https://images.unsplash.com/photo-1603133872878-684f208fb84b?auto=format&fit=crop&w=1000&q=85",
|
"/media/seed/food-package-02.jpg",
|
||||||
"https://images.unsplash.com/photo-1559847844-5315695dadae?auto=format&fit=crop&w=1000&q=85",
|
"/media/seed/food-private-chef.jpg",
|
||||||
],
|
|
||||||
personal: [
|
|
||||||
"https://images.unsplash.com/photo-1556761175-b413da4baf72?auto=format&fit=crop&w=1000&q=85",
|
|
||||||
"https://images.unsplash.com/photo-1521737711867-e3b97375f902?auto=format&fit=crop&w=1000&q=85",
|
|
||||||
],
|
],
|
||||||
|
personal: ["/media/seed/personal-consulting.jpg", "/media/seed/personal-advisory.jpg"],
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
type OfferingKind = "service" | "product" | "package" | "subscription";
|
type OfferingKind = "service" | "product" | "package" | "subscription";
|
||||||
@@ -53,11 +50,10 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
|||||||
brandConfig: {
|
brandConfig: {
|
||||||
visualTemplateKey: "linjing-editorial",
|
visualTemplateKey: "linjing-editorial",
|
||||||
templateData: { designPhilosophy: "先厘清问题,再设计表达" },
|
templateData: { designPhilosophy: "先厘清问题,再设计表达" },
|
||||||
founder: "林然",
|
|
||||||
title: "品牌策略顾问",
|
title: "品牌策略顾问",
|
||||||
slogan: "用清晰的定位与可执行的表达,让专业被看见。",
|
slogan: "用清晰的定位与可执行的表达,让专业被看见。",
|
||||||
phone: "13900000003",
|
phone: "13900000003",
|
||||||
wechat: "linran-brand",
|
wechat: "personal-brand",
|
||||||
studioAddress: "上海市徐汇区创意园区",
|
studioAddress: "上海市徐汇区创意园区",
|
||||||
heroImage: runtimeImages.personal[0],
|
heroImage: runtimeImages.personal[0],
|
||||||
visualPresentation: {
|
visualPresentation: {
|
||||||
@@ -128,7 +124,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
|||||||
kind: "service",
|
kind: "service",
|
||||||
config: {
|
config: {
|
||||||
categoryKey: "consulting",
|
categoryKey: "consulting",
|
||||||
categoryLabel: "策略咨询",
|
|
||||||
keywords: ["定位", "诊断", "表达"],
|
keywords: ["定位", "诊断", "表达"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -139,7 +134,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
|||||||
kind: "subscription",
|
kind: "subscription",
|
||||||
config: {
|
config: {
|
||||||
categoryKey: "advisory",
|
categoryKey: "advisory",
|
||||||
categoryLabel: "长期顾问",
|
|
||||||
keywords: ["陪跑", "内容", "转化"],
|
keywords: ["陪跑", "内容", "转化"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -147,7 +141,7 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
|||||||
trustContent: [
|
trustContent: [
|
||||||
{
|
{
|
||||||
type: "credential",
|
type: "credential",
|
||||||
title: "关于林然",
|
title: "关于主理人",
|
||||||
content: "专注帮助专业服务者建立可信、清晰且能带来合作的个人品牌表达。",
|
content: "专注帮助专业服务者建立可信、清晰且能带来合作的个人品牌表达。",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -248,7 +242,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
|||||||
priceAmount: 2800,
|
priceAmount: 2800,
|
||||||
config: {
|
config: {
|
||||||
categoryKey: "set-meal",
|
categoryKey: "set-meal",
|
||||||
categoryLabel: "套餐",
|
|
||||||
keywords: ["现做", "家常", "定制"],
|
keywords: ["现做", "家常", "定制"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -260,7 +253,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
|||||||
priceAmount: 3200,
|
priceAmount: 3200,
|
||||||
config: {
|
config: {
|
||||||
categoryKey: "set-meal",
|
categoryKey: "set-meal",
|
||||||
categoryLabel: "套餐",
|
|
||||||
keywords: ["现做", "家常", "定制"],
|
keywords: ["现做", "家常", "定制"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -271,7 +263,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
|||||||
kind: "service",
|
kind: "service",
|
||||||
config: {
|
config: {
|
||||||
categoryKey: "private-chef",
|
categoryKey: "private-chef",
|
||||||
categoryLabel: "私厨",
|
|
||||||
keywords: ["现做", "家常", "定制"],
|
keywords: ["现做", "家常", "定制"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -307,8 +298,7 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
|||||||
phone: "186-0218-9908",
|
phone: "186-0218-9908",
|
||||||
wechat: "LIN-ATELIER-2024",
|
wechat: "LIN-ATELIER-2024",
|
||||||
studioAddress: "上海市静安区威海路设计中心 A 座 / 杭州良渚研造工坊",
|
studioAddress: "上海市静安区威海路设计中心 A 座 / 杭州良渚研造工坊",
|
||||||
avatarUrl:
|
avatarUrl: "/media/seed/personal-avatar.jpg",
|
||||||
"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?auto=format&fit=crop&w=240&h=240&q=80",
|
|
||||||
profilePresentation: {
|
profilePresentation: {
|
||||||
coverage: [
|
coverage: [
|
||||||
{
|
{
|
||||||
@@ -410,7 +400,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
|||||||
priceText: "¥38,000 - ¥85,000 / 樘",
|
priceText: "¥38,000 - ¥85,000 / 樘",
|
||||||
config: {
|
config: {
|
||||||
categoryKey: "entrance-door",
|
categoryKey: "entrance-door",
|
||||||
categoryLabel: "入户大门",
|
|
||||||
series: "「万籁」重型天地轴入户系统",
|
series: "「万籁」重型天地轴入户系统",
|
||||||
tag: "主理人年度代表作",
|
tag: "主理人年度代表作",
|
||||||
area: "浙江·莫干山私家山庄",
|
area: "浙江·莫干山私家山庄",
|
||||||
@@ -446,7 +435,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
|||||||
priceText: "¥42,000 - ¥98,000 / 樘",
|
priceText: "¥42,000 - ¥98,000 / 樘",
|
||||||
config: {
|
config: {
|
||||||
categoryKey: "garden-door",
|
categoryKey: "garden-door",
|
||||||
categoryLabel: "庭院围墙门",
|
|
||||||
series: "「虚实」透光私家庭院门",
|
series: "「虚实」透光私家庭院门",
|
||||||
tag: "建筑级耐候工艺",
|
tag: "建筑级耐候工艺",
|
||||||
area: "上海·佘山高尔夫别墅",
|
area: "上海·佘山高尔夫别墅",
|
||||||
@@ -481,7 +469,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
|||||||
priceText: "¥7,800 - ¥16,000 / 樘",
|
priceText: "¥7,800 - ¥16,000 / 樘",
|
||||||
config: {
|
config: {
|
||||||
categoryKey: "interior-door",
|
categoryKey: "interior-door",
|
||||||
categoryLabel: "室内户内门",
|
|
||||||
series: "「空灵」2.8m - 3.2m 满高通顶系统",
|
series: "「空灵」2.8m - 3.2m 满高通顶系统",
|
||||||
tag: "极简建筑平直感",
|
tag: "极简建筑平直感",
|
||||||
area: "江苏·苏州金鸡湖独栋",
|
area: "江苏·苏州金鸡湖独栋",
|
||||||
@@ -510,18 +497,15 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
|||||||
{
|
{
|
||||||
name: "石材及皮质背景墙一体门",
|
name: "石材及皮质背景墙一体门",
|
||||||
summary: "将门体与背景墙材料、纹理和收口一体深化,保留私宅完整的墙面秩序。",
|
summary: "将门体与背景墙材料、纹理和收口一体深化,保留私宅完整的墙面秩序。",
|
||||||
image:
|
image: "/media/seed/doors-stone-wall.jpg",
|
||||||
"https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?auto=format&fit=crop&w=1000&q=85",
|
|
||||||
kind: "product",
|
kind: "product",
|
||||||
priceText: "¥18,000 - ¥36,000 / 樘",
|
priceText: "¥18,000 - ¥36,000 / 樘",
|
||||||
config: {
|
config: {
|
||||||
categoryKey: "stealth-door",
|
categoryKey: "stealth-door",
|
||||||
categoryLabel: "装饰隐形门",
|
|
||||||
series: "「无垠」密室及背景墙融合门",
|
series: "「无垠」密室及背景墙融合门",
|
||||||
tag: "精密收口工程",
|
tag: "精密收口工程",
|
||||||
area: "广东·深圳香蜜湖一号",
|
area: "广东·深圳香蜜湖一号",
|
||||||
detailHero:
|
detailHero: "/media/seed/doors-stone-wall.jpg",
|
||||||
"https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?auto=format&fit=crop&w=1000&q=85",
|
|
||||||
woodMaterial: "3mm 超薄大理石复合蜂窝板 / 进口鞍革手工双缝线",
|
woodMaterial: "3mm 超薄大理石复合蜂窝板 / 进口鞍革手工双缝线",
|
||||||
hardware: "感应式电动自开闭装置或碰珠反弹器",
|
hardware: "感应式电动自开闭装置或碰珠反弹器",
|
||||||
spaceType: "雪茄室 / 私人金库 / 地下酒窖 / 视听隐藏储物区",
|
spaceType: "雪茄室 / 私人金库 / 地下酒窖 / 视听隐藏储物区",
|
||||||
@@ -729,7 +713,6 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
|
|||||||
coverUrl: image,
|
coverUrl: image,
|
||||||
config: {
|
config: {
|
||||||
categoryKey: "custom",
|
categoryKey: "custom",
|
||||||
categoryLabel: "自定义业务",
|
|
||||||
keywords: [],
|
keywords: [],
|
||||||
media: [{ url: image, alt: item.name, type: "image" }],
|
media: [{ url: image, alt: item.name, type: "image" }],
|
||||||
sections: [],
|
sections: [],
|
||||||
@@ -827,6 +810,7 @@ async function main(): Promise<void> {
|
|||||||
username: "admin",
|
username: "admin",
|
||||||
passwordHash: await bcrypt.hash(process.env.SEED_ADMIN_PASSWORD ?? "change-me-now-123", 12),
|
passwordHash: await bcrypt.hash(process.env.SEED_ADMIN_PASSWORD ?? "change-me-now-123", 12),
|
||||||
displayName: "品牌管理员",
|
displayName: "品牌管理员",
|
||||||
|
mustChangePassword: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
await prisma.brandMembership.upsert({
|
await prisma.brandMembership.upsert({
|
||||||
@@ -835,39 +819,6 @@ async function main(): Promise<void> {
|
|||||||
create: { adminUserId: admin.id, brandId: brand.id, role: "owner" },
|
create: { adminUserId: admin.id, brandId: brand.id, role: "owner" },
|
||||||
});
|
});
|
||||||
|
|
||||||
const personalBrand = await prisma.brandProfile.upsert({
|
|
||||||
where: { id: "00000000-0000-0000-0000-000000000003" },
|
|
||||||
update: {
|
|
||||||
slug: "linran-brand",
|
|
||||||
name: "林然品牌顾问",
|
|
||||||
templateKey: "personal",
|
|
||||||
tagline: "用清晰的定位与可执行的表达,让专业被看见。",
|
|
||||||
description: "为专业服务者提供品牌定位、表达与长期顾问支持。",
|
|
||||||
hours: "周一至周五 10:00-18:00",
|
|
||||||
address: "上海市徐汇区创意园区",
|
|
||||||
contactPhone: "13900000003",
|
|
||||||
contactWechat: "linran-brand",
|
|
||||||
},
|
|
||||||
create: {
|
|
||||||
id: "00000000-0000-0000-0000-000000000003",
|
|
||||||
slug: "linran-brand",
|
|
||||||
name: "林然品牌顾问",
|
|
||||||
templateKey: "personal",
|
|
||||||
tagline: "用清晰的定位与可执行的表达,让专业被看见。",
|
|
||||||
description: "为专业服务者提供品牌定位、表达与长期顾问支持。",
|
|
||||||
hours: "周一至周五 10:00-18:00",
|
|
||||||
address: "上海市徐汇区创意园区",
|
|
||||||
contactPhone: "13900000003",
|
|
||||||
contactWechat: "linran-brand",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
await prisma.brandMembership.upsert({
|
|
||||||
where: { adminUserId_brandId: { adminUserId: admin.id, brandId: personalBrand.id } },
|
|
||||||
update: { isEnabled: true, role: "owner" },
|
|
||||||
create: { adminUserId: admin.id, brandId: personalBrand.id, role: "owner" },
|
|
||||||
});
|
|
||||||
await ensureRuntimeContent(personalBrand.id, runtimeSeedTemplates.personal);
|
|
||||||
|
|
||||||
const doorsBrand = await prisma.brandProfile.upsert({
|
const doorsBrand = await prisma.brandProfile.upsert({
|
||||||
where: { id: "00000000-0000-0000-0000-000000000002" },
|
where: { id: "00000000-0000-0000-0000-000000000002" },
|
||||||
update: {
|
update: {
|
||||||
@@ -901,7 +852,6 @@ async function main(): Promise<void> {
|
|||||||
});
|
});
|
||||||
await ensureRuntimeContent(doorsBrand.id, runtimeSeedTemplates.doors);
|
await ensureRuntimeContent(doorsBrand.id, runtimeSeedTemplates.doors);
|
||||||
await ensureSeedRelease(brand.id, admin.id);
|
await ensureSeedRelease(brand.id, admin.id);
|
||||||
await ensureSeedRelease(personalBrand.id, admin.id);
|
|
||||||
await ensureSeedRelease(doorsBrand.id, admin.id);
|
await ensureSeedRelease(doorsBrand.id, admin.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||