Compare commits

...
Author SHA1 Message Date
que01 083a323c1f feat: 搭建设计生成工作台骨架 2026-10-15 15:54:21 +08:00
que01 bf4bbf81c7 refactor: 拆分管理端入口并优化构建分包 2026-10-15 15:10:21 +08:00
que01 0f6ad8b993 docs: 记录API模块边界决策 2026-10-15 14:59:21 +08:00
que01 2ad009f5c0 refactor: 拆分媒体上传职责并锁定API路由 2026-10-15 14:52:59 +08:00
que01 6f18c67315 refactor: 拆分品牌展示编辑器职责 2026-10-15 14:42:20 +08:00
que01 b23120477f refactor: 拆分后台工作区与API模块 2026-10-15 14:35:16 +08:00
que01 12bc263d3b test: 补充小程序发布服务边界测试 2026-10-15 14:35:16 +08:00
que01 7c0f22ad7a refactor: 拆分小程序发布与后台发布页面职责 2026-10-15 14:20:17 +08:00
que01 8973338c64 fix: 完善记录错误状态与缓存失效策略 2026-10-15 13:58:39 +08:00
que01 476e3d93dd fix: 修复 API 前缀下的管理端鉴权绕过 2026-10-15 13:42:29 +08:00
que01 3ae7b462f5 refactor: 将数据库访问从控制器下沉到服务层 2026-10-14 17:53:49 +08:00
que01 f158f906d5 fix: 修复系统一致性与安全问题 2026-10-14 17:36:46 +08:00
que01 aaeec14733 fix: 保证品牌模板身份不被台账漂移 2026-10-14 16:27:23 +08:00
que01 6073e72940 feat: 收敛行业模板身份为品牌单一真相
- BrandProfile.templateKey 为唯一真相,安装记录降级为同模板的版本台账
- 安装只允许补建当前模板台账,跨行业模板请求返回 400,杜绝身份漂移
- preview 不再强制要求台账存在,台账缺失时以模板目录版本为准
- seed 按品牌身份补齐模板台账,消除「身份有、台账无」
- 记录 ADR 0026
2026-10-14 13:55:54 +08:00
que01 896f3240f9 refactor: 拆分模板治理与咨询表单页面
- /admin/workspace 收敛为「咨询表单与字段」,只做咨询入口表单与高级自定义字段
- 行业模板版本升级/回滚迁入「配置与发布 → 内容发布 → 选择表达方式」
- 移除行业模板安装入口、视觉模板历史与模板组合预览等不可达 UI
- 表单下拉的业务选项改用本品牌后台数据,避免公开接口回退默认品牌导致跨品牌串数据
- 侧栏导航与设计文档同步
2026-10-14 13:55:35 +08:00
que01 7b1e9eee47 fix: 校验咨询表单关联业务并修正发布清单文案
- 关联的业务提供项必须存在且属于当前品牌,非法 id 返回 400 而不是数据库外键错误
- targetType 由 offeringId 推导,允许传 null 改回品牌通用入口
- 业务被停用时在发布准备度里点名说明,避免静默卡住发布
- 发布清单条目改为中性描述,是否达标交给状态标签表达
2026-10-14 13:55:00 +08:00
que01 47d6309cba style: 重做后台页头层级与页面命名
- 页头标题 24px 降到 20px,说明 14px 降到 13px,标题与说明间距 8px 收到 6px
- 页头到主体间距从 24px 提到 32px,与卡片间 16px 拉开层级
- 说明文字增加 880px 最大宽度,长句不再横跨整行
- 页面标题与侧栏导航用词对齐:信任内容、业务提供项、小程序页面、能力插件
- 信任内容页说明文案精简到一行内
- 概览页对象主标题降到 18px,避免与页面标题同级
- design.md 同步字号表、页头规范与导航命名约定
2026-10-14 12:07:33 +08:00
que01 ebab77057a fix: 修复信任内容列表展示问题
- 列表按模板声明的类型顺序排列,与必填清单顺序一致
- 类型标签并入说明行,去掉与类型重复的标签;展示位置改为可读页面名
- 类型未识别时页面名补充中文映射(service/inquiry)
- 无配图时按类型显示线性图标,替换统一的文件图标
- 摘要长文本按前 3 个字段截断,避免单行超长
- 记录行改为顶部对齐,操作按钮垂直居中,行内段落间距交给 gap
- Modal destroyOnClose 迁移到 destroyOnHidden,消除 antd 弃用告警
- 发布必填清单显示同类已配置条数,已配置区块显示总数
2026-10-14 11:47:56 +08:00
que01 3ef46b0aa8 feat: 完善后台设计语言细节
- 统一说明文案层级:Typography.Paragraph 次要文案迁移到 admin-section-description
- 状态色补齐边框与中间调令牌,Alert/错误条/Descriptions 与 StatusTag 同源
- 咨询详情描述列表去表格线,改为键值展示并统一令牌
- 新增 BrandMark,侧栏与登录页标识改用品牌首字
- 信任内容改用列表行,空状态、表格骨架屏、主按钮脏检查落地
- design.md 同步令牌映射、切换控件选型与组件清单
2026-10-14 11:21:31 +08:00
que01 2f26828f09 feat: 统一 Admin 后台设计语言
用中性灰底 + 单一强调色重做后台视觉,并集中到一套令牌:

- 新增 apps/admin/src/lib/theme.ts,通过 ConfigProvider 注入主题令牌
- 新增 apps/admin/src/styles/admin.css 与 AdminSection、MetricCard、StatusTag 组件
- 侧栏改白底浅色并补图标,顶栏改 56px 白底,内容区最大宽 1200px
- 全部页面接入状态标签,antd 原生彩色 Tag 与内联色值清零
- 登录与改密页、加载态骨架屏、错误提示条统一
- brand 页两个 Tab 统一为白卡片容器,消除双标题与宽度不一致

设计规范见 apps/admin/design.md。
2026-10-14 10:54:05 +08:00
que01 bb94d80e13 fix: 修正 H5 按钮高度令牌不生效
共享按钮令牌声明在 app.css 的 page 选择器里,而 H5 渲染树没有 page 元素,导致
var(--brand-button-height) 解析失败、min-height 退化成 auto:H5 预览按钮实际高 38px
(内容撑开),与小程序 88rpx(375px 视口等于 44px)不一致,也违反模板完成度规则的
双端 reset 一致要求。

- 令牌改为同时声明在 page 与 body 上,值仍只写一次;微信端取 page,H5 取 body;
- 新增浏览器守卫,断言首页按钮 min-height 解析为 44px 且实际高度一致;
- 在模板完成度规则中记录该根因,避免声明被挪回单一 page 选择器。

验证:weapp 产物输出 page,body{--brand-button-height:88rpx},H5 输出 page,body{2.2rem};
浏览器实测 375px 视口下 min-height/height 均为 44px,430px 视口为 50.45px,与小程序
rpx 缩放一致;把声明改回 page-only 后守卫按预期失败(Received: "auto"),恢复后 12 项
浏览器回归全部通过;六类产物指纹残留为 0;format、lint、typecheck 通过。
2026-10-13 23:44:12 +08:00
que01 29e5666d74 refactor: 共享按钮尺寸令牌改用中性命名
--taro-button-height / --taro-button-compact-height 是本仓库自有的共享令牌,却借用了
框架名。源码级中性命名比产物替换更彻底,也不会出现源码与产物两套名字,因此改为
--brand-button-height / --brand-button-compact-height,与既有的 brand-button 组件命名一致;
产物遮蔽仍按同一张表处理 Taro 自身的标识符。

验证:weapp 的 app-origin.wxss 输出 page{--brand-button-height:88rpx} 与
button{min-height:var(--brand-button-height)};H5 与后台产物的声明与引用同步改名;
六类产物残留指纹均为 0;H5 预览 11 项浏览器回归通过;遮蔽前后后台产物用生产静态
服务器跑同一套测试,失败内容逐字节一致;format、lint、typecheck 通过。
2026-10-13 23:30:07 +08:00
que01 d34cb182e3 test: 修正首页行动按钮的失效断言
首页行动按钮在 inquiry 能力停用时退化为 Text,H5 端 Button 又渲染为 taro-button-core
自定义元素,两种情况都没有原生 button,因此按标签断言恒为 0。改为按稳定的
.home-action 类名断言,H5 预览的 11 项浏览器回归由 10 通过恢复为全部通过。
2026-10-13 23:18:56 +08:00
que01 4d1cd8f365 feat: 遮蔽后台静态产物中的 Taro 指纹
Traefik 把 wechat.app.que01.top 上除 /api、/media 以外的路径直接转发到 Admin 静态
服务器且没有鉴权,因此 /admin/assets/*.js 可以被任意下载。后台产物里的模板 renderer
glob 路径(packages/template-*/taro/index.tsx)与按钮尺寸令牌(--taro-button-height)
同样暴露技术栈,此前只遮蔽了 Taro 双端产物。

- mask-taro.cjs 增加 admin 目标,覆盖 apps/admin/dist,接入根脚本 build:admin:preview;
- deploy:package 在后台构建后校验 apps/admin/dist,命中指纹即中止打包;
- 补充遮蔽目标测试与文档(ADR 0025、README、部署说明、交付清单)。

验证:后台产物遮蔽后 glob key 与运行时查找同步改名;未遮蔽/已遮蔽产物用生产静态
服务器跑同一套后台浏览器测试,失败内容逐字节一致(既有失败与本改动无关);H5 预览
11 项浏览器回归全部通过;admin 构建、lint、typecheck、deploy 与 API 测试通过。
2026-10-13 23:18:43 +08:00
que01 9ad2776515 feat: 遮蔽产物中的 Taro 指纹
H5 预览与小程序产物会带出 taro_tmpl、taro-*-core、taro.js、--taro-button-height、
project.config.json 的 projectname 等指纹,而 Taro 4.3 没有隐藏这些名称的配置。
改为在 build:h5、build:weapp、build:preview 之后按 apps/taro/config/mask.config.json
做构建后处理:

- 同一张替换表同时作用于文件名与文本内容,重命名后引用保持同步,长度 ≥ 40 的 base64/哈希片段原样保留;
- 遮蔽后仍命中 forbidden 词表时构建失败,并把 project.config.json 的 projectname/description 中性化;
- dev:h5、dev:preview 保持原始命名,便于本地调试;改架构名只改 mask.config.json;
- 产物契约测试先用 unmask() 还原再断言,浏览器测试选择器写成 :is(<源码名>, <遮蔽名>)。

取舍与迁移见 docs/adr/0025-build-output-stack-masking.md。
2026-10-13 23:03:32 +08:00
que01 53713e5935 fix: 上传缓存目录不再污染仓库
miniprogram-ci 的 SummerCompiler 用 path.join("", md5(projectPath + "|summer"))
建编译缓存,得到的是相对路径,会创建在进程工作目录下。上传子进程此前继承
API 进程的工作目录,于是每次上传都在 apps/api 下留下一个 32 位十六进制空目录。

把上传子进程的工作目录固定到 MINIAPP_UPLOAD_WORKSPACE(默认系统临时目录),
缓存随之落在临时目录,仓库保持干净;projectPath 一直是绝对路径,行为不受影响。

用真实 ensureCacheDir 验证目录落在临时工作目录,并断言仓库内不再新增缓存目录。
2026-10-13 22:11:33 +08:00
que01 ac3f433ee6 feat: 重做小程序发布任务卡片并支持配置请求地址
- 发布任务卡片拆为 MiniAppReleaseCard,状态用中文映射并附下一步说明,构建日志收进折叠面板,构建中自动滚动到底部
- 小程序配置增加“小程序请求地址”字段,展示当前生效域名,未配置时直接提示原因与修复位置
- 顶部上传按钮在无任务时自动创建发布任务,不再报“还没有可发布的内容版本”
- 构建轮询在任务被判定为中断后停止,避免页面空转请求
2026-10-13 21:59:00 +08:00
que01 44fe7a0142 fix: 打通小程序代码上传链路
小程序上传此前连续失败,根因分散在状态机、产物路径、模块导入、私钥解析和进程隔离上,逐项修复:

- 构建进度改用 updateBuild 只写 buildStatus/buildLogs,不再用 updateStatus 记录进度,避免状态机拒绝自我迁移而返回 409
- 产物目录锚定仓库根目录,不再随 API 进程工作目录变成 apps/api/apps/taro/dist
- miniprogram-ci 为 CommonJS 包,动态导入后从 default 归一化取 Project/upload,替换原有的类型断言
- 上传私钥统一还原成合法 PEM;输入框曾把换行吞成单行,导致 OpenSSL 解码失败,现保存时校验、上传时自动修复存量数据
- 上传改在独立子进程执行,miniprogram-ci 崩溃或超时不再终止 API 进程,失败返回 502 并保留微信原始错误
- 构建超过 MINIAPP_BUILD_STALE_MS 无进度即视为中断,允许重新上传,避免任务永久卡在 building
- 构建前校验请求地址与 AppID,请求地址支持在品牌配置中维护,环境变量仅作回落,避免再打出指向 localhost 的包
- 小程序 /media/ 按请求地址的 origin 解析,不再依赖网关剥离 /api 前缀

新增对应单测与集成断言,并更新部署说明。
2026-10-13 21:58:48 +08:00
que01 f52577ff9e fix: 兼容线上小程序构建状态迁移 2026-10-13 20:34:40 +08:00
que01 8e90b8ca09 fix: 分离小程序构建状态与发布状态 2026-10-13 20:31:49 +08:00
que01 998e32e49c feat: 展示小程序构建过程和日志 2026-10-13 20:20:13 +08:00
que01 8b4d27b0ee fix: 按模板包定位小程序构建产物 2026-10-13 20:06:52 +08:00
que01 26f1157083 fix: 恢复小程序上传配置并固定产物目录 2026-10-13 19:56:45 +08:00
que01 ad949ab370 feat: 简化小程序上传入口 2026-10-13 17:58:57 +08:00
que01 d5a84b51a7 fix: 恢复 API 编译运行并支持 watch 2026-10-13 17:53:57 +08:00
que01 760f41a584 chore: API 开发模式支持热重载 2026-10-13 17:51:45 +08:00
que01 20f880a761 fix: 修正发布中心标签页内容归属 2026-10-13 17:47:38 +08:00
que01 ab1531d9b0 feat: 拆分发布中心内容和小程序标签页 2026-10-13 17:41:52 +08:00
que01 3d0252d187 feat: 支持小程序上传配置加密存储 2026-10-13 17:28:40 +08:00
que01 526a9db789 feat: 实现小程序代码发布任务闭环 2026-10-13 17:13:24 +08:00
que01 9b35b8e7a7 docs: 确认小程序发布中心架构 2026-10-13 17:12:47 +08:00
que01 14b6541bee fix: 避免编辑覆盖层触发画布选中 2026-10-13 16:28:15 +08:00
que01 00edcedbcf fix: 优化预览区域选择提示布局 2026-10-13 16:04:19 +08:00
que01 dcf1d76944 fix: 修复本地图片上传与发布进程切换 2026-10-13 16:00:42 +08:00
que01 7f67f4d685 chore: 增加部署状态与备份保留 2026-10-13 15:14:27 +08:00
que01 d2ca528543 fix: 完善部署回滚健康检查
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Browser regression (push) Has been cancelled
2026-10-13 15:05:02 +08:00
que01 47a24e0d53 chore: 固化一键生产部署流程
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Browser regression (push) Has been cancelled
2026-10-13 14:56:16 +08:00
que01 c78deafee3 fix: 清理模板编译失败产物并登记审查 2026-10-13 11:37:43 +08:00
que01 3330b536dc fix: 统一小程序按钮契约并补齐模板图标 2026-10-13 11:12:53 +08:00
que01 07629a4596 fix: 补全小程序媒体地址并支持构建注入 AppID 2026-10-13 09:51:38 +08:00
que01 5c6ad02f46 chore: 完善生产发布与部署校验 2026-10-13 09:19:57 +08:00
que01 048c42207c chore: 添加生产级 Docker 部署配置与 ARM64 支持
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Browser regression (push) Has been cancelled
2026-10-12 18:19:29 +08:00
que01 67735afd45 chore: 忽略本地调试产物 2026-10-12 15:33:03 +08:00
que01 0574a85632 fix: 修复预览 loading 与媒体代理 2026-10-12 15:31:25 +08:00
que01 18ddf125be fix: 修复品牌预览渲染循环与区域点选 2026-10-12 12:00:46 +08:00
que01 bb0709b8cc feat: 能力插件元数据与运行时消费闭环 2026-10-12 11:20:43 +08:00
que01 076c6124c8 refactor: Taro 模板发现与校验收敛为目录驱动 2026-10-12 10:06:20 +08:00
que01 89fdfd7d83 refactor: 模板注册与默认模板收敛到目录驱动 2026-10-12 10:00:46 +08:00
que01 f87b26b201 merge: 合并代码结构标准重构 2026-10-12 05:11:26 +08:00
que01 466dc66907 refactor: 拆分业务、信任内容与公共工作台模块 2026-10-12 05:11:26 +08:00
que01 357f271639 refactor: 拆分 API Client 资源模块 2026-10-12 03:37:05 +08:00
que01 f3adf7bc15 style: 格式化工作台控制器 2026-10-12 03:36:57 +08:00
que01 4512d2601d refactor: 拆分工作台业务服务边界 2026-10-12 03:29:30 +08:00
que01 d0902d6568 refactor: 拆分模板配置契约与注册逻辑 2026-10-12 03:26:43 +08:00
que01 7e1dd543fb refactor: 拆分工作台查询与模板变更逻辑 2026-10-12 03:17:28 +08:00
que01 3003e7801d refactor: 建立代码标准并拆分品牌编辑状态 2026-10-12 03:08:24 +08:00
que01 567921e726 feat: 还原示例图片并优化媒体选择交互 2026-10-12 02:48:14 +08:00
que01 03f947e9b8 feat: 迁移示例媒体到本地存储 2026-10-12 02:09:08 +08:00
que01 6ac2d9421b feat: 支持本地媒体存储与上传回退 2026-10-12 01:39:56 +08:00
que01 aa42e7b866 fix: 修复 Admin 浏览器运行缺少 process 2026-10-12 01:05:18 +08:00
que01 e09b56e0f3 feat: 完善媒体存储状态与上传失败提示 2026-10-12 01:00:02 +08:00
que01 84956b8fe2 feat: 接入对象存储图片直传 2026-10-12 00:55:30 +08:00
que01 f57c0ca0ea ci: 增加发布产物打包脚本 2026-10-12 00:46:07 +08:00
que01 9c15a822e9 ci: 增加部署后发布验收脚本 2026-10-12 00:44:21 +08:00
que01 85f37d2eae ci: 建立完整发布门禁流水线 2026-10-12 00:41:14 +08:00
que01 222055595c docs: 明确模板预览产物结构 2026-10-12 00:26:18 +08:00
que01 b1d5c2b4b0 docs: 补充生产发布基线 2026-10-12 00:23:36 +08:00
que01 787a50369f fix: 收敛分类键运行时契约 2026-10-12 00:03:03 +08:00
que01 422162e580 chore: 移除林然演示品牌数据 2026-10-11 23:26:54 +08:00
que01 26bcb2b66e feat: 完善模板字段编辑与分类治理 2026-10-11 23:07:53 +08:00
que01 91322fa9a0 feat: 统一业务内容双入口编辑预览 2026-10-11 12:55:13 +08:00
que01 bfbcee45bb feat: 业务视图切换联动字段分组 2026-10-10 17:37:12 +08:00
que01 46b1690f6c feat: 分组业务编辑字段与预览目标 2026-10-10 17:34:22 +08:00
que01 0e0ca201a7 feat: 业务编辑支持列表与详情实时预览 2026-10-10 17:31:47 +08:00
que01 569156c977 feat: 业务编辑弹窗接入预览画布 2026-10-10 17:21:00 +08:00
que01 20e7e8bb81 feat: 业务列表支持跳转页面编辑 2026-10-10 17:12:43 +08:00
que01 20eb160abf feat: 打通业务与页面编辑入口 2026-10-10 17:08:19 +08:00
que01 d0ef25cfb3 refactor: 抽取业务与信任内容公共编辑器 2026-10-10 17:03:41 +08:00
que01 d2ce2d2a84 feat: 接入模板诊断人工审阅登记 2026-10-10 16:43:12 +08:00
que01 f57e1b1336 fix: 修复编辑器与 API Client lint 问题 2026-10-10 16:33:31 +08:00
que01 22a82dbfba fix: 完善模板可视化编辑闭环与通用验收 2026-10-10 16:20:08 +08:00
que01 fa6b492bce feat: 完善编辑工作台保存与离开体验 2026-10-10 11:22:49 +08:00
que01 860d9266fe feat: 构建品牌视图与三栏页面编辑工作台 2026-10-10 10:38:47 +08:00
que01 a2932b1134 refactor: 整理品牌配置与小程序编辑工作区 2026-10-10 10:20:14 +08:00
que01 849ae5df05 feat: 完善模板区域预览与详情页编辑边界 2026-10-10 09:51:12 +08:00
que01 df2b1f6031 fix: 补齐餐饮首页可编辑区域 2026-10-09 17:53:47 +08:00
que01 66dbba5748 feat: 完成模板区域与咨询字段编辑闭环 2026-10-09 17:33:39 +08:00
que01 c5db30f817 feat: 补齐模板预览区域与编辑绑定 2026-10-09 16:14:06 +08:00
que01 541304a763 fix: 修复预览成功页与记录页运行时报错 2026-10-09 15:24:15 +08:00
que01 fd2e970d8b fix: 修复组件预览底部按钮溢出与咨询表单缺失 2026-10-09 15:12:40 +08:00
que01 5b85fe769f feat: 完善后台可视化模板编辑与区域绑定 2026-10-09 14:26:05 +08:00
que01 0b14b5a814 feat: 建立组件化模板预览基线并规划可视化编辑 2026-10-09 12:32:24 +08:00
381 changed files with 41730 additions and 9180 deletions

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、类型和构建通过
1 id title status task_type depends_on acceptance_criteria validation_command task_dir notes
2 1 建立现状基线与页面覆盖清单 DONE single-full 记录当前布局层级、Card 使用、响应式问题和关键交互 测试基线截图与 DOM 检查 .codex-tasks/admin-editor-workspace/tasks/01-baseline/ 已完成代码结构基线与验证记录
3 2 重构品牌配置的信息架构 DONE single-full 1 品牌资料按身份联系模板视觉分组且减少卡片嵌套 Admin typecheck; browser brand page test .codex-tasks/admin-editor-workspace/tasks/02-information-architecture/ 已完成分组与模板说明层级调整
4 3 重构小程序页面编辑工作区 DONE single-full 1;2 页面导航预览画布编辑面板形成稳定三栏或响应式两栏布局 Admin build; browser editor test .codex-tasks/admin-editor-workspace/tasks/03-workspace-ui/ 完整宽度两栏工作区,窄屏堆叠;详情页只读;未选中显示引导
5 4 统一编辑器视觉系统与状态样式 DONE single-full 3 间距层级按钮选区空状态错误状态统一且无 Card 堆叠 Prettier; Admin build; screenshot review .codex-tasks/admin-editor-workspace/tasks/04-visual-system/ 统一导航工具条、画布边界、区域按钮和面板间距;已检查 1280 与 390 截图
6 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
1 id task status acceptance_criteria validation_command completed_at retry_count notes
2 1 采集真实基线 DONE before 报告已存档 node scripts/template-doctor.mjs 2026-10-10 0 退出 1 保留实际问题
3 2 修复公共编辑和字段绑定 DONE 真实 manifest 修改保存重载测试通过 playwright admin-editor.spec.ts 2026-10-10 1 修复共享字段未挂载覆盖
4 3 执行审计验证并归档边界 DONE 保留未验证和失败项 pnpm format:check 2026-10-10 0 详情按钮与原型全量验收未完成
5 4 补齐详情公共文案和真实卡片字段 DONE 所有展示字段有对应入口 pnpm validate:templates 2026-10-10 0 详情正文与底部按钮独立目标;真实卡片字段补齐;模板契约 19 项通过
6 5 验证真实声明的浏览器编辑闭环 DONE 两个模板真实声明保存重载测试通过 playwright admin-editor.spec.ts 2026-10-10 0 2 项真实 manifest 浏览器通过;含逐页画布内部点击、字段面板、列表子项修改重载和多宽检查
7 6 验证数据库保存发布隔离 DONE 新增字段真实持久化发布回归通过 pnpm --filter @personal-brand/api test:integration 2026-10-10 0 41 项集成通过;193 个真实绑定隔离数据库保存草稿发布验证
8 7 归档动态映射和视觉验收 DONE 逐项证据与门槛验证完成 pnpm template:doctor 2026-10-10 4 78 条动态审查归档;最终画布检查通过;原型结构与视觉边界详见 docs/template-audit-2026-10-10.md
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -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
1 id task task_type status depends_on task_dir acceptance_criteria validation_command completed_at retry_count notes
2 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 项通过
3 2 修复通用选区绑定与模板发现 single-full DONE 1 tasks/contract 混合来源及重复记录映射正确且契约测试通过 pnpm validate:templates; pnpm --filter @personal-brand/admin typecheck; 浏览器测试 2026-10-09 0 区域来源按 binding 推导;餐饮首页身份目标和业务卡片目标对齐;切页及记录失效选择已有清理逻辑
4 3 整理选区面板与保存交互 single-full DONE 2 tasks/inspector 布局及失败和未保存切换验证通过 pnpm --filter @personal-brand/admin typecheck; 浏览器测试 2026-10-09 0 选区字段改单列自适应并移除固定最小高度;保持保存失败输入不重置
5 4 接通咨询字段编辑 single-full DONE 2;3 tasks/inquiry 配置保存重载一致且历史提交不受损 pnpm --filter @personal-brand/admin typecheck; 浏览器测试 2026-10-09 0 咨询字段可独立点选并编辑标题、类型、必填、选项;预览草稿不提交真实咨询
6 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
1 template page visible_content renderer_target manifest_editor source status evidence
2 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 已覆盖 契约测试 + 浏览器点选
3 acheng-campus-food offerings 菜单说明、业务卡片 acheng-campus-food.offerings.menu; acheng-campus-food.offerings.item 对应 sections 已声明 brand; offering 已覆盖 契约测试 + 浏览器点选
4 acheng-campus-food service 出摊说明、日程、配送、流程 acheng-campus-food.service.service; trust:schedule; trust:coverage; trust:process 对应 sections / trust declarations 已声明 brand; trust 待第二阶段复核 已存在浏览器点选路径
5 acheng-campus-food profile 主理人与信任内容 acheng-campus-food.profile.identity; trust:credential; trust:case; trust:promise 对应 sections / trust declarations 已声明 brand; trust 待第二阶段复核 已存在 renderer target
6 acheng-campus-food detail 餐品详情、详情说明 acheng-campus-food.detail.dishDetail; acheng-campus-food.detail.detailCopy 对应 sections 已声明 offering; brand 已覆盖 浏览器已验证底栏与编辑入口
7 acheng-campus-food inquiry 页面文案、访客表单 acheng-campus-food.inquiry.booking 对应 section 已声明;Admin 已允许 inquiry section 编辑 brand; inquiry 首批已修复 浏览器已验证表单展示
8 acheng-campus-food success 提交结果文案 acheng-campus-food.success.successCopy 对应 section 已声明 brand 待第二阶段复核 已验证页面可切换
9 acheng-campus-food records 记录页文案 acheng-campus-food.records.recordsCopy 对应 section 已声明 brand; records 待第二阶段复核 已验证页面可切换
10 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 已覆盖 契约测试 + 浏览器点选
11 linjing-editorial offerings 案例说明、业务卡片 linjing-editorial.offerings.cases; linjing-editorial.offerings.item 对应 sections 已声明 brand; offering 待第二阶段复核 已有 renderer target
12 linjing-editorial profile 身份、履约、联系方式、信任内容 linjing-editorial.profile.identity; linjing-editorial.profile.profileDetails; trust:* 对应 sections / trust declarations 已声明 brand; trust 已覆盖 契约测试 + 浏览器点选
13 linjing-editorial detail 案例详情、详情说明 linjing-editorial.detail.projectDetail; linjing-editorial.detail.detailCopy 对应 sections 已声明 offering; brand 待第二阶段复核 已有 renderer target
+25
View File
@@ -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/**
+19 -4
View File
@@ -10,9 +10,24 @@ ADMIN_PORT=3000
SESSION_SECRET=replace-with-a-long-random-value
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
SEED_ADMIN_PASSWORD=change-me-now-123
OBJECT_STORAGE_ENDPOINT=
OBJECT_STORAGE_BUCKET=
OBJECT_STORAGE_ACCESS_KEY=
OBJECT_STORAGE_SECRET_KEY=
OBJECT_STORAGE_ENDPOINT=http://localhost:9000
OBJECT_STORAGE_PUBLIC_URL=http://localhost:9000/personal-brand-media
OBJECT_STORAGE_BUCKET=personal-brand-media
OBJECT_STORAGE_ACCESS_KEY=minioadmin
OBJECT_STORAGE_SECRET_KEY=minioadmin
WECHAT_APP_ID=
WECHAT_APP_SECRET=
WECHAT_UPLOAD_PRIVATE_KEY=
MINIAPP_CREDENTIAL_ENCRYPTION_KEY=replace-with-32-byte-random-secret
# 小程序代码构建产物根目录,相对路径按仓库根目录解析;默认 apps/taro/dist
# MINIAPP_ARTIFACT_ROOT=apps/taro/dist
# 构建超过该毫秒数没有进度更新即视为中断,允许重新上传;默认 15 分钟
# MINIAPP_BUILD_STALE_MS=900000
# 小程序请求地址在后台「小程序上传配置」维护,这里仅为回落值;
# 未设置时由 PUBLIC_BASE_URL + MINIAPP_API_PATH 推导
# MINIAPP_API_BASE_URL=https://wechat.app.que01.top/api
# MINIAPP_API_PATH=/api
# 单个品牌的 AppID 在后台“小程序上传配置”维护,这里只作为回落值
# WEAPP_APP_ID=
# 上传子进程工作目录;miniprogram-ci 的编译缓存放这里,默认系统临时目录
# MINIAPP_UPLOAD_WORKSPACE=/tmp/personal-brand-miniapp-upload
+31
View File
@@ -0,0 +1,31 @@
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=skip
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=
# 小程序请求地址正常情况下在后台「小程序上传配置」维护;
# 这里仅作为后台未配置时的回落值(否则由 PUBLIC_BASE_URL + /api 推导)
# MINIAPP_API_BASE_URL=https://wechat.app.que01.top/api
# MINIAPP_BUILD_STALE_MS=900000
+122
View File
@@ -0,0 +1,122 @@
name: CI
on:
pull_request:
push:
branches: [main]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
static:
name: Static checks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9.15.0
- uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm check
- run: pnpm template:doctor
build:
name: Production build
runs-on: ubuntu-latest
needs: [static]
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9.15.0
- uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm build:admin:preview
- uses: actions/upload-artifact@v4
with:
name: admin-dist
path: apps/admin/dist
retention-days: 7
api:
name: API integration
runs-on: ubuntu-latest
needs: [static]
services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: personal_brand
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres -d personal_brand"
--health-interval 5s
--health-timeout 5s
--health-retries 12
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/personal_brand
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9.15.0
- uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm --filter @personal-brand/api test:integration
browser:
name: Browser regression
runs-on: ubuntu-latest
needs: [build]
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9.15.0
- uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm --filter @personal-brand/taro exec playwright install --with-deps chromium
- run: pnpm --filter @personal-brand/api test:integration
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/personal_brand
- name: Start API
run: pnpm --filter @personal-brand/api start > /tmp/api.log 2>&1 &
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/personal_brand
NODE_ENV: development
- name: Start mini program preview
run: pnpm --filter @personal-brand/taro dev:h5 > /tmp/taro.log 2>&1 &
env:
API_BASE_URL: http://localhost:3001
BRAND_SLUG: default-brand
TEMPLATE_KEY: acheng-campus-food
- name: Start admin
run: pnpm --filter @personal-brand/admin dev > /tmp/admin.log 2>&1 &
env:
VITE_API_BASE_URL: /api
VITE_DEV_API_TARGET: http://localhost:3001
VITE_TEMPLATE_PREVIEW_URL: http://localhost:3002
- name: Wait for services
run: |
curl --retry 30 --retry-delay 1 --retry-connrefused -fsS http://localhost:3001/health
curl --retry 30 --retry-delay 1 --retry-connrefused -fsS http://localhost:3002
curl --retry 30 --retry-delay 1 --retry-connrefused -fsS http://localhost:3000
- run: pnpm --filter @personal-brand/taro exec playwright test --config=playwright.config.ts --reporter=line
+8 -1
View File
@@ -2,11 +2,13 @@ node_modules/
.pnpm-store/
.turbo/
dist/
packages/config/dist/
.next/
coverage/
.env
.env.*
!.env.example
.env.production
!.env.production.example
*.log
.DS_Store
apps/miniapp/miniprogram_npm/
@@ -14,8 +16,13 @@ apps/miniapp/project.private.config.json
.worktrees/
apps/taro/src/assets/
apps/admin/public/template-preview/
apps/taro/test-results/
apps/taro/playwright-report/
media/
**/.swc/
.codex-tasks/
docker-compose.override.yml
.env.production
+1
View File
@@ -1,6 +1,7 @@
node_modules
.turbo
dist
apps/admin/public/template-preview
.next
prototype
pnpm-lock.yaml
+2
View File
@@ -1,5 +1,7 @@
# Product Direction
- 模板新增、绑定修改及宣称完成前,执行 pnpm template:doctor 并遵循 docs/template-completion-rules.md。静态校验、输入框出现、mock 成功不能单独证明完成;回归使用真实 manifest,按区域全部可见变量验收。
- The core product is a personal-brand platform whose primary goal is to build trust and convert that trust into qualified inquiries or collaborations.
- Personal-brand identity, positioning, proof of work, communication expectations, and contact paths are higher priority than any single industry workflow.
- Industry behavior is implemented as replaceable templates. Food, consulting, design, photography, and future industries must not hard-code their terminology or fields into the shared brand model or shared UI.
+2 -1
View File
@@ -2,4 +2,5 @@ VITE_APP_BASE_PATH=/admin/
VITE_API_BASE_URL=/api
VITE_DEV_API_TARGET=http://localhost:3001
ADMIN_PORT=3000
VITE_TEMPLATE_PREVIEW_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
+418
View File
@@ -0,0 +1,418 @@
# Admin Design Language
本文件是 `@personal-brand/admin` 管理后台的视觉与交互规范,是后台 UI 的唯一设计来源。
设计目标:**简洁、干净**。留白充足、层级靠排版建立、装饰最少。信息架构与业务语义不在本文件范围内,如需变更请走产品文档。
适用范围:`apps/admin/src` 下所有页面、组件与样式。新增 UI 前先读本文件,冲突以本文件为准。
- 本文件同时作为 AI 设计工具的规范输入:在 MasterGo「AI 快搭」中直接上传本文件即可,无需重复描述视觉规则。生成提示词见 `docs/design/admin-mastergo-guide.md`。
- 技术约束:antd 6 + React 19 + React Router 7 + TanStack Query 5。不引入新的 UI 库、状态管理、校验或路由方案。
- 主题令牌统一在根节点通过 `ConfigProvider` 注入,页面与组件内不得写零散色值。
- 共享视觉元素放 `apps/admin/src/components/`,页面专属组件留在各自的 `features/` 目录。
- 中文界面。桌面优先,最小可用宽度 1024px;窄屏允许侧栏折叠,不提供移动端专用布局。
---
## 1. 颜色
中性灰打底,只保留一个强调色。禁止渐变、彩色大面积色块、玻璃拟态。
### 基础色
| 用途 | 令牌 | 值 |
| ---------------------- | ---------------------- | --------- |
| 页面底色 | `colorBgLayout` | `#F7F8FA` |
| 卡片/容器底色 | `colorBgContainer` | `#FFFFFF` |
| 次级填充(表头、悬停) | `colorFillQuaternary` | `#FAFAFB` |
| 悬停底色 | `colorFillTertiary` | `#F7F8FA` |
| 容器边框 | `colorBorderSecondary` | `#E7E9EC` |
| 行分隔线 | `colorSplit` | `#F0F1F3` |
| 控件边框 | `colorBorder` | `#D8DBE0` |
### 文字色
| 用途 | 令牌 | 值 |
| ------------- | --------------------- | --------- |
| 主文字 | `colorText` | `#1C1F23` |
| 次要文字 | `colorTextSecondary` | `#6B7280` |
| 辅助/占位文字 | `colorTextTertiary` | `#9AA1AC` |
| 禁用文字 | `colorTextQuaternary` | `#C3C7CF` |
### 强调色
| 用途 | 令牌 | 值 |
| ------------- | -------------------- | --------- |
| 主色 | `colorPrimary` | `#2563EB` |
| 主色悬停 | `colorPrimaryHover` | `#1D4ED8` |
| 主色按下 | `colorPrimaryActive` | `#1E40AF` |
| 选中底色 | `colorPrimaryBg` | `#EFF4FF` |
| 选中/链接文字 | `colorLink` | `#2563EB` |
强调色只用于:主按钮、选中态、链接、关键数字、聚焦描边。不得用于大面积背景。
例外:小程序预览区(iframe / 模拟器内)显示的是模板自身的品牌色(例如餐饮模板的砖红 `#B54A2C`),与后台无关,不视为违规,也不要「修正」成后台强调色。
### 状态色
状态一律用「浅底 + 深字」,不使用 antd 的实心鲜艳 Tag。
| 语义 | 底色 | 边框 | 文字色 |
| ------------- | --------- | --------- | --------- |
| 成功 / 已发布 | `#ECFDF3` | `#ABEFC6` | `#067647` |
| 警告 / 进行中 | `#FFFAEB` | `#FEDF89` | `#B54708` |
| 错误 / 失败 | `#FEF3F2` | `#FBD5D1` | `#B42318` |
| 中性 / 草稿 | `#F2F4F7` | `#E7E9EC` | `#475467` |
| 信息 / 系统态 | `#EFF4FF` | `#B2CCFF` | `#2563EB` |
- 底色 + 边框 + 深色文字三件套同时用于 `StatusTag`、`Alert`、错误条与空状态,不得混用其他色阶。
- 需要中间调的场合(图标、进度条完成态)使用中间色:成功 `#12B76A`、警告 `#F79009`、错误 `#F04438`、信息 `#2563EB`。
---
## 2. 排版
系统无衬线字体栈:`Inter`、`PingFang SC`、`Noto Sans SC`、`sans-serif`。
| 角色 | 字号 | 字重 | 行高 |
| ------------------ | ---- | ---- | ---- |
| 页面标题 | 20px | 600 | 1.4 |
| 区块/卡片标题 | 16px | 600 | 1.45 |
| 卡片内对象主标题 | 18px | 600 | 1.45 |
| 强调正文、品牌名 | 15px | 600 | 1.5 |
| 正文 | 14px | 400 | 1.5 |
| 表单标签、次要正文 | 13px | 400 | 1.5 |
| 辅助说明、时间戳 | 12px | 400 | 1.5 |
| 指标数值 | 28px | 600 | 1.2 |
- 层级靠字号与字重建立,不靠颜色、下划线、边框。
- 中文不使用斜体;英文与数字不加字距。
- 一段说明文字最长不超过 2 行,超出应改写或省略。
- 中英文与数字之间保留一个空格。
---
## 3. 间距与布局
8pt 网格。间距只使用 `4 / 8 / 12 / 16 / 24 / 32`。
| 场景 | 值 |
| ---------------- | ------------ |
| 页面内容区内边距 | 24px |
| 内容最大宽度 | 1200px,居中 |
| 页面头部到主体 | 32px |
| 卡片内边距 | 20px |
| 卡片之间 | 16px |
| 表单字段之间 | 16px |
| 标签与输入框之间 | 6px |
| 行内元素之间 | 8px |
| 小节标题到内容 | 12px |
外壳尺寸:
- 侧栏宽 232px,折叠宽 0(`breakpoint="lg"`)。
- 顶栏高 56px,与侧栏品牌区对齐。
---
## 4. 形状与层次
| 元素 | 圆角 | 说明 |
| ------------------ | ---- | ------------------------------- |
| 卡片 | 10px | 默认 1px `#E7E9EC` 边框,无阴影 |
| 弹窗 | 12px | 极轻阴影 |
| 按钮、输入框、下拉 | 6px | 统一 |
| 状态标签 | 6px | 高 24px,内边距 `2px 8px` |
| 图片/头像缩略图 | 8px | 头像用圆形 |
| 进度条 | 3px | 高 6px |
- 层次手段优先级:留白 > 字号字重 > 1px 浅边框 > 阴影。
- 阴影仅用于浮层:`0 1px 2px rgba(16, 24, 40, 0.04)`,弹窗可加 `0 8px 24px rgba(16, 24, 40, 0.08)`。
- 卡片不使用阴影,不叠加边框与阴影。
---
## 5. 组件规范
### 侧栏导航
- 白底,右侧 1px `#E7E9EC` 分隔线。不使用深色主题(现有 `theme="dark"` 需移除)。
- 顶部品牌区:24x24 圆角 6px 标识 + 品牌名,高 56px。
- 分组标题:12px `#9AA1AC`,上下留白 8px,不加图标、不做大写英文。
- 菜单项:高 36px,圆角 6px,左侧 16px 线性图标(描边 1.5px),文字 14px。
- 三态:默认深灰文字无底色;悬停 `#F7F8FA`;选中 `#EFF4FF` 底 + `#2563EB` 文字与图标 + 字重 500。
### 顶栏
- 高 56px,白底,底部 1px 分隔线,左右内边距 24px。
- 左侧:品牌名 14px/600 + 灰色 13px「品牌工作区」+ 角色标签。
- 角色标签:负责人 `#EFF4FF`/`#2563EB`,内容编辑 `#F2F4F7`/`#475467`。
- 右侧:品牌切换下拉(尺寸 `small`、白底细边框)+ 「退出登录」文字按钮。
- 顶栏不随机滚动,内容区独立滚动。
### 页面头部
统一通过 `AdminPageHeader` 渲染:页面标题 20px/600 + 可选副标题 13px 次要色 + 右侧操作区。标题与副标题间距 6px,页头到主体 32px(明显大于卡片之间的 16px)。页面内不得再手写标题层级。
- 页面标题必须与侧栏导航用词一致,不额外添加「小程序内容:」这类前缀;页面职责写进副标题。
- 副标题一句话讲清这一页做什么,最长不超过 2 行;能由页面内文案表达的细节不要重复写在这里。
### 卡片
- 标题 16px/600,标题区底部间距 12px,标题右侧放次要操作(文字按钮)。
- 卡片只承载一个主题;一个页面最多两级卡片嵌套,避免再嵌套。
### 按钮
| 类型 | 场景 |
| -------------------- | ---------------------------------------- |
| 主按钮(实心强调色) | 每个页面/卡片最多一个,用于当前主流程 |
| 次按钮(白底细边框) | 并列的次要操作 |
| 文字按钮 | 表格行内操作、列表「去处理」、返回类操作 |
| 危险按钮 | 删除、撤回、卸载等不可逆操作 |
- 高度:默认 32px,主流程按钮 40px。
- 等待态用 `loading`,禁用态用 `disabled`,禁止用文字变形表达状态。
### 表单
- 标签在输入框上方,13px `#475467`,必填星号 `#B42318`。
- 帮助文本 12px `#9AA1AC`,错误文本 12px `#B42318`,都显示在字段下方。
- 输入框聚焦:1.5px `#2563EB` 描边 + `#EFF4FF` 2px 外发光。
- 提交失败必须保留用户输入,错误提示定位到字段或表单顶部,禁止弹窗后清空。
### 数据表格
- 无竖线;表头底色 `#FAFAFB`,13px `#6B7280`。
- 行高 52px(含头像/双行内容时 60px)。
- 行分隔线 `#F0F1F3`;悬停行底色 `#FAFAFB`。
- 操作列统一放最右,使用文字按钮,最多 2 个直接操作,更多收进「更多」下拉。
- 空数据不显示空表头,改用空状态组件。
### 状态标签
- 统一组件,按语义取色,默认 `尺寸 = 24px 高 / 12px 字`。
- 发布状态机映射:`building` 信息、`uploaded` 中性、`under_review` 警告、`approved` 成功、`rejected` 错误、`published` 成功、`failed` 错误、`superseded` 中性。
- 同一列表内标签宽度尽量对齐,避免视觉跳动。
### 弹窗
- 宽 480px(简单表单)或 560px(多字段),圆角 12px。
- 标题 16px/600,底部操作右对齐:次按钮在左、主按钮在右。
- 提交中禁用关闭与重复提交。
### 描述列表(键值展示)
用于咨询详情、版本信息等只读信息:字段名 13px `#6B7280`,值 14px `#1C1F23`,行间距 12px,不使用表格线。
落地:`<Descriptions className="admin-descriptions" column={1} size="small">`,字号与间距由 `admin.css` 与 `Descriptions` 令牌统一,不逐处传 `bordered`。
### Tabs
- 顶部 1px 分隔线,选中项底部 2px 强调色下划线 + 深色文字,未选中 14px `#6B7280`。
- 不超过 5 个 Tab,超出改用左侧分段导航。
### 切换控件选型
同一层级切换控件只允许两种,按范围选择,不得混用:
| 场景 | 控件 | 现状 |
| ---------------------------------------- | ----------- | ------------------------------ |
| 页面级分区(内容结构不同、各自独立成段) | `Tabs` | 配置与发布 |
| 区块内视图切换(同一份数据换视角) | `Segmented` | 小程序页面、业务提供项编辑弹窗 |
`Segmented` 用作「取值选择」(如能力状态降级/启用/停用)时按表单控件处理,不受本表约束。
### 标题层级
页面内标题只用三档,禁止再用 `Typography.Title level` 直接指定字号:
| 用途 | 类名 | 字号 |
| ---------------------- | --------------------- | ---------- |
| 区块标题 | `admin-section-title` | 16px / 600 |
| 面板内小标题、表单分组 | `admin-subhead` | 15px / 600 |
| 列表行、条目名称 | `admin-row-title` | 14px / 600 |
页面级标题只由 `AdminPageHeader` 输出(20px / 600),一个页面只出现一次。
### 进度
- 高 6px,圆角 3px,轨道 `#F0F1F3`,进度条强调色;完成态用成功色。
- 进度条上方 14px 文案说明当前含义,不允许只有一根进度条。
---
## 6. 状态设计
每个远程数据页面必须显式实现四种状态,不得出现无反馈的白屏。
| 状态 | 规范 |
| -------- | ----------------------------------------------------------------------------------- |
| 加载中 | 骨架屏,形状与最终内容一致;不用居中转圈 |
| 空数据 | 居中:极简线性图形 + 15px/600 标题 + 13px 灰色说明 + 主操作按钮 |
| 请求失败 | 卡片内错误条:`#FEF3F2` 底 + 1px 浅红边框 + 圆角 8px + 文案 14px + 「重试」文字按钮 |
| 成功反馈 | 右上角轻量 toast,白底圆角 8px,280–320px 宽 |
- 行内操作使用按钮 `loading` 表达进行中,不用全局遮罩。
- 提交成功后:关闭弹窗、重置表单、刷新受影响列表;提交失败保持原状。
- 幂等写操作要防止重复点击(提交中禁用)。
落地约定:
- 空状态统一用 `EmptyState`(`components/EmptyState.tsx`);表格内用 `compact` 变体,整块区域用默认变体。禁止再使用 antd 默认 `Empty` 插画。
- 列表 / 表格加载统一用 `TableSkeleton`、`ListSkeleton`(`components/TableSkeleton.tsx`)替换内容区,不使用 antd `Table` 的转圈遮罩;卡片级加载用 `LoadingStack`。
- 卡片内的写操作只在「有未保存修改」时使用主按钮,其余状态用次要按钮并禁用,同时用 `StatusTag` 标明修改状态。
- 发布准备度、内容检查这类清单,条目文案只描述「检查什么」(中性名词),是否达标由「已完成 / 待完善」标签表达;帮助文案只在待完善时展示。禁止出现「已完成 · 请先完善…」这类自相矛盾的措辞。
---
## 7. 页面结构
以下为各页面的视觉结构约定,业务逻辑不变。
| 页面 | 结构要点 |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| 登录 | 居中 400px 卡片,标识 + 说明 + 表单 + 通栏主按钮;错误态展示在字段下方 |
| 首次改密 | 同登录卡片形态,说明文案 + 三个密码字段 + 「保存新密码」 |
| 品牌概览 | 品牌卡 + 三张指标卡(等宽一行)+ 两栏(发布准备度 / 品牌内容检查) |
| 配置与发布 | 三 Tab(内容发布 / 小程序发布 / 小程序配置);内容发布含「选择表达方式」(行业模板 + 视觉模板 + 版本升级/回滚)+ 发布状态卡 + 草稿卡 + 历史版本表 |
| 小程序页面 | 左右两栏:左 380px 编辑面板,右预览画布;预览内选中区域虚线高亮 + 区域名气泡 |
| 信任内容 | 列表行(类型图标或配图 + 标题 + 发布状态标签 + 类型/展示位置说明 + 两行摘要 + 行内操作),按模板类型顺序排列,不用表格 |
| 业务提供项 | 表格(名称 / 价格 / 状态开关 / 排序 / 操作)+ 新增弹窗 |
| 咨询记录 | 顶部三指标 + 左 380px 列表 + 右详情的主从布局 |
| 咨询表单与字段 | 咨询表单表(名称 / 版本 / 字段数 / 状态 / 操作)+ 新增与编辑弹窗(含选项编辑);高级自定义字段表 + 新增弹窗 |
| 能力插件 | 插件卡片列表(图标 + 名称 + 说明 + 开关),停用态降低对比度 |
| 团队成员 | 表格(成员 / 角色 / 状态 / 最近登录 / 操作)+ 邀请弹窗 |
两栏页面在小屏下折叠为单列,编辑/预览改为上下排列。
---
## 8. 无障碍与细节
- 正文与背景对比度不低于 4.5:1;标签文字与标签底色不低于 4.5:1。
- 可点击元素最小热区 32x32px;纯图标按钮必须带 `aria-label`。
- 焦点可见:所有可交互元素保留 1.5px 强调色聚焦描边。
- 状态不能只靠颜色区分,需同时有文字。
- 数字使用等宽数字排版(`font-variant-numeric: tabular-nums`),避免指标和价格跳动。
---
## 9. 禁止项
- 渐变、玻璃拟态、拟物纹理、装饰性插画铺满界面。
- 深色侧栏、彩色大面积色块、实心鲜艳 Tag。
- 重阴影、多重边框、卡片再套卡片超过两级。
- emoji 作为图标;图标与文字混排时不对齐基线。
- 页面内写死色值、圆角、间距魔法数字。
- 一个页面出现多个主按钮竞争视觉焦点。
---
## 10. antd 令牌映射
落地时在 Admin 根节点用 `ConfigProvider` 注入,不逐页覆盖。
```ts
const theme = {
token: {
colorPrimary: "#2563EB",
colorLink: "#2563EB",
colorText: "#1C1F23",
colorTextSecondary: "#6B7280",
colorTextTertiary: "#9AA1AC",
colorTextQuaternary: "#C3C7CF",
colorBgLayout: "#F7F8FA",
colorBgContainer: "#FFFFFF",
colorBorder: "#D8DBE0",
colorBorderSecondary: "#E7E9EC",
colorSplit: "#F0F1F3",
colorFillTertiary: "#F7F8FA",
colorFillQuaternary: "#FAFAFB",
colorSuccess: "#12B76A",
colorSuccessBg: "#ECFDF3",
colorSuccessBorder: "#ABEFC6",
colorSuccessText: "#067647",
colorWarning: "#F79009",
colorWarningBg: "#FFFAEB",
colorWarningBorder: "#FEDF89",
colorWarningText: "#B54708",
colorError: "#F04438",
colorErrorBg: "#FEF3F2",
colorErrorBorder: "#FBD5D1",
colorErrorText: "#B42318",
colorInfo: "#2563EB",
colorInfoBg: "#EFF4FF",
colorInfoBorder: "#B2CCFF",
colorInfoText: "#2563EB",
borderRadius: 6,
borderRadiusLG: 10,
borderRadiusSM: 4,
fontSize: 14,
fontFamily:
"Inter, 'PingFang SC', 'Noto Sans SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
controlHeight: 32,
controlHeightLG: 40,
boxShadow: "0 1px 2px rgba(16, 24, 40, 0.04)",
boxShadowSecondary: "0 8px 24px rgba(16, 24, 40, 0.08)",
wireframe: false,
},
components: {
Layout: {
headerHeight: 56,
headerBg: "#FFFFFF",
headerPadding: "0 24px",
siderBg: "#FFFFFF",
bodyBg: "#F7F8FA",
triggerBg: "#FFFFFF",
triggerColor: "#475467",
triggerHeight: 40,
},
Menu: {
itemHeight: 36,
itemBorderRadius: 6,
itemBg: "transparent",
itemColor: "#475467",
itemHoverBg: "#F7F8FA",
itemHoverColor: "#1C1F23",
itemSelectedBg: "#EFF4FF",
itemSelectedColor: "#2563EB",
itemMarginInline: 8,
itemMarginBlock: 2,
groupTitleColor: "#9AA1AC",
groupTitleFontSize: 12,
collapsedWidth: 0,
subMenuItemBg: "transparent",
},
Card: { paddingLG: 20, headerFontSize: 16, headerHeight: 52, headerHeightSM: 44 },
Table: {
headerBg: "#FAFAFB",
headerColor: "#6B7280",
rowHoverBg: "#FAFAFB",
headerSplitColor: "transparent",
borderColor: "#F0F1F3",
cellPaddingBlock: 16,
headerBorderRadius: 8,
},
Button: { fontWeight: 500, primaryShadow: "none", defaultShadow: "none" },
Progress: { defaultColor: "#2563EB", remainingColor: "#F0F1F3", lineBorderRadius: 3 },
Tag: { defaultBg: "#F2F4F7", defaultColor: "#475467", borderRadiusSM: 6 },
Tabs: { inkBarColor: "#2563EB", itemSelectedColor: "#1C1F23", itemColor: "#6B7280" },
Form: { labelColor: "#475467", labelFontSize: 13, verticalLabelPadding: "0 0 6px" },
Modal: { borderRadiusLG: 12 },
Statistic: { titleFontSize: 12, contentFontSize: 28 },
Alert: { borderRadius: 8 },
Descriptions: {
labelBg: "#FAFAFB",
labelColor: "#6B7280",
contentColor: "#1C1F23",
itemPaddingBottom: 12,
},
},
};
```
可执行来源是 `apps/admin/src/lib/theme.ts`,本块为同值快照;改令牌时两处一起改。
- 新增页面优先使用令牌与共享组件;禁止在 JSX 内写内联色值、字号、圆角(唯一的例外是通过 CSS 变量透传的数据色,例如视觉模板色板的 `--swatch-color`)。
- 共享视觉组件清单:`AdminPageHeader`、`AdminSection`、`StatusTag`、`EmptyState`、`TableSkeleton` / `ListSkeleton`、`MetricCard`、`QueryState`。
+1
View File
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"dependencies": {
"@ant-design/icons": "^6.3.4",
"@personal-brand/api-client": "workspace:*",
"@tanstack/react-query": "^5.103.1",
"antd": "^6.6.4",
+155
View File
@@ -0,0 +1,155 @@
import { useQuery } from "@tanstack/react-query";
import {
AppstoreOutlined,
BarsOutlined,
CloudUploadOutlined,
FormOutlined,
MessageOutlined,
MobileOutlined,
SafetyCertificateOutlined,
TeamOutlined,
ThunderboltOutlined,
} from "@ant-design/icons";
import { useLocation, useNavigate } from "react-router-dom";
import { createApiClient } from "../lib/api.js";
import { BrandMark } from "../components/BrandMark.js";
import { StatusTag } from "../components/StatusTag.js";
import {
FeatureBrandPage,
FeatureCapabilitiesPage,
FeatureInquiriesPage,
FeatureMembersPage,
FeatureOverviewPage,
FeaturePublicationPage,
FeatureServicesPage,
FeatureTrustContentPage,
FeatureWorkspacePage,
} from "./routes.js";
import { LoadingStack } from "../components/LoadingStack.js";
import { AdminMenu } from "../components/AdminMenu.js";
import { adminMessage as message } from "../components/AdminMessage.js";
import { AdminButton } from "../components/AdminButton.js";
import { AdminSelect } from "../components/AdminSelect.js";
import { AdminLayout } from "../components/AdminLayout.js";
import { Navigate, Route, Routes } from "react-router-dom";
import { Suspense } from "react";
export function Dashboard({ onLogout, role }: { onLogout: () => void; role: string }) {
const navigate = useNavigate();
const location = useLocation();
const brand = useQuery({
queryKey: ["admin-shell-brand"],
queryFn: () => createApiClient().getAdminBrand(),
});
const memberships = useQuery({
queryKey: ["admin-brand-memberships"],
queryFn: () => createApiClient().listAdminBrands(),
});
const switchBrand = async (brandId: string) => {
try {
const result = await createApiClient().switchAdminBrand(brandId);
localStorage.setItem("adminToken", result.token);
window.location.reload();
} catch (error) {
message.error(error instanceof Error ? error.message : "品牌切换失败");
}
};
const page = location.pathname.split("/")[2] || "overview";
const items = [
{
type: "group" as const,
label: "日常经营",
children: [
{ key: "overview", label: "当前品牌概览", icon: <AppstoreOutlined /> },
{ key: "publication", label: "配置与发布", icon: <CloudUploadOutlined /> },
{ key: "brand", label: "小程序页面", icon: <MobileOutlined /> },
{ key: "trust", label: "信任内容", icon: <SafetyCertificateOutlined /> },
{ key: "services", label: "业务提供项", icon: <BarsOutlined /> },
{ key: "inquiries", label: "咨询记录", icon: <MessageOutlined /> },
{ key: "workspace", label: "咨询表单与字段", icon: <FormOutlined /> },
],
},
...(role === "editor"
? []
: [
{
type: "group" as const,
label: "系统管理",
children: [
{ key: "capabilities", label: "能力插件", icon: <ThunderboltOutlined /> },
{ key: "members", label: "团队成员", icon: <TeamOutlined /> },
],
},
]),
];
return (
<AdminLayout className="admin-shell">
<AdminLayout.Sider className="admin-sider" breakpoint="lg" collapsedWidth={0} width={232}>
<div className="admin-sider-brand">
<BrandMark name={brand.data?.name} />
<span className="admin-sider-brand-name">品牌工作区</span>
</div>
<AdminMenu
selectedKeys={[page]}
onClick={({ key }) => navigate(`/admin/${key}`)}
items={items}
/>
</AdminLayout.Sider>
<AdminLayout className="admin-main">
<AdminLayout.Header className="admin-header">
<div className="admin-header-left">
<span className="admin-header-brand">{brand.data?.name || "当前品牌"}</span>
<span className="admin-header-context">品牌工作区</span>
<StatusTag
tone={role === "owner" ? "info" : "neutral"}
label={role === "owner" ? "负责人" : "内容编辑"}
/>
<AdminSelect
size="small"
variant="outlined"
className="admin-brand-switcher"
value={brand.data?.id}
loading={memberships.isLoading}
onChange={(value) => {
if (value) void switchBrand(value);
}}
options={(memberships.data ?? []).map((item) => ({
value: item.brand.id,
label: item.brand.name,
}))}
/>
</div>
<AdminButton type="text" onClick={onLogout}>
退出登录
</AdminButton>
</AdminLayout.Header>
<AdminLayout.Content className="admin-content">
<div className="admin-content-inner">
<Suspense fallback={<LoadingStack />}>
<Routes>
<Route path="/" element={<Navigate to="overview" replace />} />
<Route path="overview" element={<FeatureOverviewPage />} />
<Route
path="publication"
element={<FeaturePublicationPage canManageTemplate={role !== "editor"} />}
/>
<Route path="brand" element={<FeatureBrandPage />} />
<Route path="trust" element={<FeatureTrustContentPage />} />
<Route path="services" element={<FeatureServicesPage />} />
<Route path="inquiries" element={<FeatureInquiriesPage />} />
<Route path="workspace" element={<FeatureWorkspacePage />} />
{role === "editor" ? null : (
<>
<Route path="capabilities" element={<FeatureCapabilitiesPage />} />
<Route path="members" element={<FeatureMembersPage />} />
</>
)}
<Route path="*" element={<Navigate to="overview" replace />} />
</Routes>
</Suspense>
</div>
</AdminLayout.Content>
</AdminLayout>
</AdminLayout>
);
}
+38
View File
@@ -0,0 +1,38 @@
import React, { useState } from "react";
import { ChangePassword, Login } from "../features/auth/AuthPages.js";
import { Dashboard } from "./Dashboard.js";
import { adminMessage as message } from "../components/AdminMessage.js";
export function Root() {
const [loggedIn, setLoggedIn] = useState(Boolean(localStorage.getItem("adminToken")));
const [role, setRole] = useState(localStorage.getItem("adminRole") || "owner");
const [mustChangePassword, setMustChangePassword] = useState(
localStorage.getItem("adminMustChangePassword") === "true",
);
React.useEffect(() => {
const expire = () => {
message.warning("登录状态已失效,请重新登录");
setLoggedIn(false);
};
window.addEventListener("admin-auth-expired", expire);
return () => window.removeEventListener("admin-auth-expired", expire);
}, []);
const logout = () => {
localStorage.removeItem("adminToken");
localStorage.removeItem("adminRole");
localStorage.removeItem("adminMustChangePassword");
setLoggedIn(false);
};
if (!loggedIn)
return (
<Login
onLogin={(session) => {
setRole(session.role);
setMustChangePassword(session.mustChangePassword);
setLoggedIn(true);
}}
/>
);
if (mustChangePassword) return <ChangePassword onComplete={() => setMustChangePassword(false)} />;
return <Dashboard onLogout={logout} role={role} />;
}
+45
View File
@@ -0,0 +1,45 @@
import React from "react";
export const FeatureInquiriesPage = React.lazy(() =>
import("../features/inquiries/InquiriesPage.js").then((module) => ({
default: module.InquiriesPage,
})),
);
export const FeatureTrustContentPage = React.lazy(() =>
import("../features/trust-content/TrustContentPage.js").then((module) => ({
default: module.TrustContentPage,
})),
);
export const FeatureServicesPage = React.lazy(() =>
import("../features/services/ServicesPage.js").then((module) => ({
default: module.ServicesPage,
})),
);
export const FeatureBrandPage = React.lazy(() =>
import("../features/brand/BrandPage.js").then((module) => ({ default: module.BrandPage })),
);
export const FeatureWorkspacePage = React.lazy(() =>
import("../features/workspace/WorkspacePage.js").then((module) => ({
default: module.WorkspacePage,
})),
);
export const FeatureOverviewPage = React.lazy(() =>
import("../features/overview/OverviewPage.js").then((module) => ({
default: module.OverviewPage,
})),
);
export const FeatureCapabilitiesPage = React.lazy(() =>
import("../features/capabilities/CapabilitiesPage.js").then((module) => ({
default: module.CapabilitiesPage,
})),
);
export const FeatureMembersPage = React.lazy(() =>
import("../features/team/MembersPage.js").then((module) => ({
default: module.MembersPage,
})),
);
export const FeaturePublicationPage = React.lazy(() =>
import("../features/publication/PublicationPage.js").then((module) => ({
default: module.PublicationPage,
})),
);
@@ -0,0 +1,6 @@
import { Button } from "antd";
import type { ButtonProps } from "antd";
export function AdminButton(props: ButtonProps) {
return <Button {...props} />;
}
+6
View File
@@ -0,0 +1,6 @@
import { Card } from "antd";
import type { CardProps } from "antd";
export function AdminCard(props: CardProps) {
return <Card {...props} />;
}
@@ -0,0 +1,14 @@
import { App, ConfigProvider } from "antd";
import type { ConfigProviderProps } from "antd";
import type { ReactNode } from "react";
export function AdminConfigProvider({
children,
...props
}: ConfigProviderProps & { children?: ReactNode }) {
return (
<ConfigProvider {...props}>
<App>{children}</App>
</ConfigProvider>
);
}
+1
View File
@@ -0,0 +1 @@
export { Form as AdminForm, Input as AdminInput } from "antd";
+12
View File
@@ -0,0 +1,12 @@
import { Layout } from "antd";
import type { BasicProps } from "antd/es/layout/layout";
function AdminLayoutBase(props: BasicProps) {
return <Layout {...props} />;
}
export const AdminLayout = Object.assign(AdminLayoutBase, {
Sider: Layout.Sider,
Header: Layout.Header,
Content: Layout.Content,
});
+6
View File
@@ -0,0 +1,6 @@
import { Menu } from "antd";
import type { MenuProps } from "antd";
export function AdminMenu(props: MenuProps) {
return <Menu {...props} />;
}
@@ -0,0 +1 @@
export { message as adminMessage } from "antd";
+5 -15
View File
@@ -1,4 +1,3 @@
import { Space, Typography } from "antd";
import type { ReactNode } from "react";
export function AdminPageHeader({
@@ -11,21 +10,12 @@ export function AdminPageHeader({
extra?: ReactNode;
}) {
return (
<Space
align="start"
style={{ width: "100%", justifyContent: "space-between", marginBottom: 24 }}
>
<div>
<Typography.Title level={2} style={{ margin: 0 }}>
{title}
</Typography.Title>
{description && (
<Typography.Paragraph type="secondary" style={{ margin: "8px 0 0" }}>
{description}
</Typography.Paragraph>
)}
<header className="admin-page-header">
<div className="admin-page-header-text">
<h1 className="admin-page-header-title">{title}</h1>
{description ? <p className="admin-page-header-description">{description}</p> : null}
</div>
{extra}
</Space>
</header>
);
}
@@ -0,0 +1,28 @@
import type { ReactNode } from "react";
export function AdminSection({
title,
description,
extra,
children,
}: {
title?: ReactNode;
description?: ReactNode;
extra?: ReactNode;
children: ReactNode;
}) {
return (
<section className="admin-section">
{title ? (
<div className="admin-section-head">
<div>
<h2 className="admin-section-title">{title}</h2>
{description ? <p className="admin-section-description">{description}</p> : null}
</div>
{extra}
</div>
) : null}
{children}
</section>
);
}
@@ -0,0 +1,6 @@
import { Select } from "antd";
import type { SelectProps } from "antd";
export function AdminSelect(props: SelectProps) {
return <Select {...props} />;
}
@@ -0,0 +1,6 @@
import { Skeleton } from "antd";
import type { SkeletonProps } from "antd";
export function AdminSkeleton(props: SkeletonProps) {
return <Skeleton {...props} />;
}
+17
View File
@@ -0,0 +1,17 @@
/**
* 品牌标识:取品牌名首字渲染单字标记,未取到品牌时回落到中性字。
* 视觉规则见 apps/admin/design.md 的「侧栏导航」。
*/
export function BrandMark({
name,
fallback = "品",
className = "admin-sider-brand-mark",
}: {
name?: string | null | undefined;
fallback?: string;
className?: string;
}) {
const trimmed = name?.trim() ?? "";
const mark = Array.from(trimmed)[0] ?? fallback;
return <span className={className}>{mark}</span>;
}
+25
View File
@@ -0,0 +1,25 @@
import type { ReactNode } from "react";
export function EmptyState({
icon,
title,
description,
action,
compact = false,
}: {
icon?: ReactNode;
title: string;
description?: string;
action?: ReactNode;
compact?: boolean;
}) {
const className = compact ? "admin-empty admin-empty--compact" : "admin-empty";
return (
<div className={className}>
{icon ? <span className="admin-empty__icon">{icon}</span> : null}
<p className="admin-empty__title">{title}</p>
{description ? <p className="admin-empty__description">{description}</p> : null}
{action ? <div className="admin-empty__action">{action}</div> : null}
</div>
);
}
+124 -15
View File
@@ -1,33 +1,142 @@
import { Image, Input, Space, Typography } from "antd";
import { CloudUploadOutlined, DeleteOutlined, PictureOutlined } from "@ant-design/icons";
import { Alert, Button, Image, Popconfirm, Spin, Upload, message } from "antd";
import { useEffect, useMemo, useState } from "react";
import { apiBaseUrl, createApiClient } from "../lib/api.js";
interface ImageUrlFieldProps {
id?: string;
value?: string;
onChange?: (value: string) => void;
placeholder?: string;
scope?: "brand" | "offering" | "trust";
}
export function ImageUrlField({ value, onChange, placeholder }: ImageUrlFieldProps) {
export function ImageUrlField({ id, value, onChange, placeholder, scope }: ImageUrlFieldProps) {
const imageUrl = typeof value === "string" ? value.trim() : "";
const [uploading, setUploading] = useState(false);
const [storageStatus, setStorageStatus] = useState<
"loading" | "ok" | "unavailable" | "unconfigured"
>("loading");
const client = useMemo(() => createApiClient(), []);
useEffect(() => {
let active = true;
client
.getUploadConfig()
.then((config) => {
if (active) setStorageStatus(config.configured ? config.status : "unconfigured");
})
.catch(() => {
if (active) setStorageStatus("unavailable");
});
return () => {
active = false;
};
}, [client]);
async function upload(file: File) {
if (!file.type.startsWith("image/")) {
message.error("仅支持图片文件");
return;
}
if (file.size > 10 * 1024 * 1024) {
message.error("图片不能超过 10MB");
return;
}
setUploading(true);
try {
const presign = await client.createPresignedUpload({
fileName: file.name,
contentType: file.type,
...(scope ? { scope } : {}),
});
const isLocalUpload = presign.mode === "local";
const uploadUrl = isLocalUpload
? `${apiBaseUrl.replace(/\/$/, "")}${presign.uploadUrl}`
: presign.uploadUrl;
const response = await fetch(uploadUrl, {
method: "PUT",
headers: {
"content-type": file.type,
...(isLocalUpload
? { authorization: `Bearer ${localStorage.getItem("adminToken") ?? ""}` }
: {}),
},
body: file,
});
if (!response.ok) throw new Error(`upload failed: ${response.status}`);
onChange?.(presign.publicUrl);
} catch (error) {
message.error(error instanceof Error ? error.message : "图片上传失败,请重试");
} finally {
setUploading(false);
}
}
return (
<Space direction="vertical" size={8} style={{ width: "100%" }}>
<Input
value={value}
onChange={(event) => onChange?.(event.target.value)}
placeholder={placeholder ?? "粘贴图片地址"}
/>
<div className="admin-field-stack-xs admin-block">
{storageStatus !== "ok" ? (
<Alert
type={storageStatus === "loading" ? "info" : "warning"}
showIcon
message={
storageStatus === "loading"
? "正在检查媒体存储..."
: storageStatus === "unconfigured"
? "媒体存储未配置,请先设置对象存储"
: "媒体存储不可用,请检查对象存储配置"
}
/>
) : null}
{imageUrl ? (
<Space align="start">
<div className="admin-media-preview">
<Image
src={imageUrl}
width={96}
height={64}
alt={placeholder ?? "图片预览"}
width="100%"
height={180}
preview
fallback="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="
style={{ objectFit: "cover", borderRadius: 8, background: "#f5f5f5" }}
/>
<Typography.Text type="secondary">预览图</Typography.Text>
</Space>
<Popconfirm title="移除这张图片?" onConfirm={() => onChange?.("")}>
<Button danger size="small" icon={<DeleteOutlined />} className="admin-thumb-remove">
移除
</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}
</Space>
<input {...(id ? { id } : {})} type="hidden" value={imageUrl} />
</div>
);
}
@@ -0,0 +1,17 @@
import { AdminCard } from "./AdminCard.js";
import { AdminSkeleton } from "./AdminSkeleton.js";
export function LoadingStack({ rows = 3 }: { rows?: number }) {
return (
<div className="admin-loading-stack">
<AdminCard>
<AdminSkeleton active paragraph={{ rows: 2 }} title={false} />
</AdminCard>
{Array.from({ length: rows }).map((_, index) => (
<AdminCard key={index}>
<AdminSkeleton active paragraph={{ rows: 1 }} title={false} />
</AdminCard>
))}
</div>
);
}
+25
View File
@@ -0,0 +1,25 @@
import { Card } from "antd";
import type { ReactNode } from "react";
export function MetricCard({
label,
value,
suffix,
extra,
}: {
label: ReactNode;
value: ReactNode;
suffix?: ReactNode;
extra?: ReactNode;
}) {
return (
<Card>
<div className="admin-metric-label">{label}</div>
<div className="admin-metric-value">
{value}
{suffix ? <span className="admin-metric-suffix">{suffix}</span> : null}
</div>
{extra}
</Card>
);
}
+27 -27
View File
@@ -1,5 +1,10 @@
import { Alert, Button, Card, Empty, Result, Spin } from "antd";
import { Button } from "antd";
import type { ReactNode } from "react";
import { LoadingStack } from "./LoadingStack.js";
function errorMessage(error: unknown, fallback: string) {
return error instanceof Error ? error.message : fallback;
}
export function QueryState({
loading,
@@ -12,36 +17,31 @@ export function QueryState({
onRetry?: () => void;
children?: ReactNode;
}) {
if (loading)
return (
<Card>
<Spin />
</Card>
);
if (error) {
return (
<Result
status="error"
title="内容加载失败"
subTitle={error instanceof Error ? error.message : "请检查 API 服务后重试"}
extra={onRetry ? <Button onClick={onRetry}>重新加载</Button> : undefined}
/>
);
}
if (loading) return <LoadingStack />;
if (error) return <ErrorNote error={error} onRetry={onRetry} />;
return <>{children}</>;
}
export function EmptyState({ description }: { description: string }) {
return <Empty description={description} image={Empty.PRESENTED_IMAGE_SIMPLE} />;
export function ErrorNote({
error,
onRetry,
}: {
error?: unknown;
onRetry?: (() => void) | undefined;
}) {
if (!error) return null;
return (
<div className="admin-error-note" role="alert">
<span>{errorMessage(error, "操作失败,请重试")}</span>
{onRetry ? (
<Button type="link" size="small" onClick={onRetry}>
重试
</Button>
) : null}
</div>
);
}
export function MutationError({ error }: { error?: unknown }) {
if (!error) return null;
return (
<Alert
type="error"
showIcon
message={error instanceof Error ? error.message : "操作失败,请重试"}
/>
);
return <ErrorNote error={error} />;
}
@@ -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 "../lib/presentation/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}
className="admin-form-column"
>
<Alert
type="info"
showIcon
message={
source === "offering"
? `正在编辑业务提供项:${recordName}`
: `正在编辑信任内容:${recordName}`
}
description={
context === "visual"
? "这里修改的是业务或信任记录本身;业务提供项列表中打开同一项目,看到并修改的是同一份数据。"
: "这里修改的内容也会显示在小程序页面对应的卡片、列表或详情中;两处入口修改的是同一份数据。"
}
/>
{save.isPending ? <Typography.Text type="secondary">正在保存内容…</Typography.Text> : null}
<p className="admin-section-description">{section.description}</p>
<div className="admin-flex-1">
<RecordContentFields section={section} />
</div>
<div className="admin-actions admin-offset-top-lg">
<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>
</div>
</Form>
);
}
+67
View File
@@ -0,0 +1,67 @@
export type StatusTone = "success" | "warning" | "error" | "info" | "neutral";
const TONE_BY_STATUS: Record<string, StatusTone> = {
published: "success",
approved: "success",
completed: "success",
active: "success",
enabled: "success",
building: "info",
built: "neutral",
uploaded: "info",
pending: "neutral",
draft: "neutral",
superseded: "neutral",
disabled: "neutral",
review: "warning",
reviewing: "warning",
under_review: "warning",
processing: "warning",
rejected: "error",
failed: "error",
error: "error",
};
const LABELS: Record<string, string> = {
published: "已发布",
approved: "已通过",
completed: "已完成",
active: "已启用",
enabled: "已公开",
building: "构建中",
built: "待上传",
uploaded: "已上传微信",
pending: "待处理",
draft: "草稿",
superseded: "已过期",
disabled: "已停用",
review: "审核中",
reviewing: "审核中",
under_review: "审核中",
processing: "处理中",
rejected: "已拒绝",
failed: "失败",
error: "异常",
};
export function statusLabel(status: string | null | undefined, fallback = "未知"): string {
if (!status) return fallback;
return LABELS[status] ?? status;
}
export function StatusTag({
status,
label,
tone,
}: {
status?: string | null;
label?: string;
tone?: StatusTone;
}) {
const resolvedTone = tone ?? (status ? TONE_BY_STATUS[status] : undefined) ?? "neutral";
return (
<span className="admin-status-tag" data-tone={resolvedTone}>
{label ?? statusLabel(status)}
</span>
);
}
@@ -0,0 +1,29 @@
import { Skeleton } from "antd";
export function TableSkeleton({ rows = 4 }: { rows?: number }) {
return (
<div className="admin-table-skeleton" role="status" aria-live="polite">
{Array.from({ length: rows }).map((_, index) => (
<div key={index} className="admin-table-skeleton__row">
<Skeleton.Input active size="small" block />
</div>
))}
</div>
);
}
export function ListSkeleton({ rows = 3 }: { rows?: number }) {
return (
<div className="admin-list-skeleton" role="status" aria-live="polite">
{Array.from({ length: rows }).map((_, index) => (
<div key={index} className="admin-list-skeleton__row">
<Skeleton.Input active size="small" className="admin-list-skeleton__thumb" />
<div className="admin-list-skeleton__body">
<Skeleton.Input active size="small" block />
<Skeleton.Input active size="small" block />
</div>
</div>
))}
</div>
);
}
@@ -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}
className="admin-block"
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}
/>
);
}
+111 -24
View File
@@ -1,5 +1,12 @@
import { Button, Form, Input, Space } from "antd";
import { Button, Card, Collapse, Form, Input, Space, Typography } from "antd";
import {
CaretDownOutlined,
CaretUpOutlined,
DeleteOutlined,
PlusOutlined,
} from "@ant-design/icons";
import type { TemplateAdminField } from "@personal-brand/api-client";
import { EmptyState } from "./EmptyState.js";
export function TemplateListField({
field,
@@ -21,30 +28,110 @@ export function TemplateListField({
},
]}
>
{(rows, { add, remove }, { errors }) => (
<Space direction="vertical" style={{ width: "100%" }}>
{rows.map((row, index) => (
<Space key={row.key} align="start" wrap>
{field.itemFields?.map((itemField) => (
<Form.Item
key={itemField.key}
name={[row.name, itemField.key]}
label={`${index + 1}. ${itemField.label}`}
rules={
itemField.required === false
? []
: [{ required: true, message: `请填写${itemField.label}` }]
}
>
{itemField.input === "textarea" ? <Input.TextArea rows={2} /> : <Input />}
</Form.Item>
))}
<Button onClick={() => remove(row.name)}>删除</Button>
</Space>
))}
{(rows, { add, remove, move }, { errors }) => (
<div className="admin-stack admin-stack-tight">
{rows.length === 0 ? <EmptyState compact title={`还没有${field.label}内容`} /> : null}
{rows.map((row, index) => {
const titleField = field.itemFields?.[0];
const primaryTitle = titleField ? (
<Form.Item
noStyle
shouldUpdate={(prev: unknown, next: unknown) => {
const previous = Array.isArray(prev)
? (prev[row.name] as Record<string, unknown> | undefined)
: undefined;
const nextRow = Array.isArray(next)
? (next[row.name] as Record<string, unknown> | undefined)
: undefined;
return previous?.[titleField.key] !== nextRow?.[titleField.key];
}}
>
{({ getFieldValue }) => {
const value = String(
getFieldValue([...name, row.name, titleField.key] as const) ?? "",
);
return (
<Typography.Text
strong
>{`${index + 1}. ${value || titleField.label}`}</Typography.Text>
);
}}
</Form.Item>
) : (
<Typography.Text strong>{`${index + 1}. ${field.label}`}</Typography.Text>
);
return (
<Card
key={row.key}
size="small"
title={primaryTitle}
extra={
<Space size={0}>
<Button
type="text"
size="small"
aria-label={`上移第 ${index + 1} 项`}
icon={<CaretUpOutlined />}
disabled={index === 0}
onClick={() => move(index, index - 1)}
/>
<Button
type="text"
size="small"
aria-label={`下移第 ${index + 1} 项`}
icon={<CaretDownOutlined />}
disabled={index === rows.length - 1}
onClick={() => move(index, index + 1)}
/>
<Button
type="text"
danger
size="small"
aria-label={`删除第 ${index + 1} 项`}
icon={<DeleteOutlined />}
onClick={() => remove(row.name)}
/>
</Space>
}
>
{field.itemFields?.map((itemField) => (
<Form.Item
key={itemField.key}
name={[row.name, itemField.key]}
label={itemField.label}
rules={
itemField.required === false
? []
: [{ required: true, message: `请填写${itemField.label}` }]
}
>
{itemField.input === "textarea" ? <Input.TextArea rows={2} /> : <Input />}
</Form.Item>
))}
</Card>
);
})}
{rows.length > 1 ? (
<Collapse
ghost
items={[
{
key: "sort-help",
label: "排序说明",
children: (
<Typography.Text type="secondary">
使用每张卡片右上角的箭头调整顺序,保存后预览也会按当前顺序展示。
</Typography.Text>
),
},
]}
/>
) : null}
<Form.ErrorList errors={errors} />
<Button onClick={() => add()}>新增{field.label}</Button>
</Space>
<Button block icon={<PlusOutlined />} onClick={() => add()}>
新增{field.label}
</Button>
</div>
)}
</Form.List>
</Form.Item>
@@ -0,0 +1,14 @@
import type { Offering, TemplateAdminSection, TrustContent } from "@personal-brand/api-client";
import type { PresentationValues } from "../../lib/presentation/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 "../../lib/presentation/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,
};
}
+117
View File
@@ -0,0 +1,117 @@
import { useState } from "react";
import { createApiClient } from "../../lib/api.js";
import { BrandMark } from "../../components/BrandMark.js";
import { adminMessage as message } from "../../components/AdminMessage.js";
import { AdminButton } from "../../components/AdminButton.js";
import { AdminCard } from "../../components/AdminCard.js";
import { AdminForm, AdminInput } from "../../components/AdminForm.js";
export function Login({
onLogin,
}: {
onLogin: (session: { role: string; mustChangePassword: boolean }) => void;
}) {
const [form] = AdminForm.useForm();
const [loading, setLoading] = useState(false);
async function submit(values: { username: string; password: string }) {
setLoading(true);
try {
const result = await createApiClient().loginAdmin(values.username, values.password);
localStorage.setItem("adminToken", result.token);
localStorage.setItem("adminRole", result.role);
localStorage.setItem("adminMustChangePassword", String(result.mustChangePassword));
onLogin(result);
} catch (error) {
message.error(error instanceof Error ? error.message : "登录失败");
} finally {
setLoading(false);
}
}
return (
<div className="admin-auth">
<AdminCard className="admin-auth-card">
<div className="admin-auth-brand">
<BrandMark />
<span className="admin-header-brand">个人品牌后台</span>
</div>
<p className="admin-auth-hint">管理你的品牌表达、内容发布与客户咨询。</p>
<AdminForm form={form} layout="vertical" onFinish={submit}>
<AdminForm.Item
name="username"
label="账号"
initialValue="admin"
rules={[{ required: true }]}
>
<AdminInput />
</AdminForm.Item>
<AdminForm.Item name="password" label="密码" rules={[{ required: true }]}>
<AdminInput.Password />
</AdminForm.Item>
<AdminButton type="primary" size="large" htmlType="submit" loading={loading} block>
登录
</AdminButton>
</AdminForm>
<p className="admin-auth-footnote">仅限授权成员访问。</p>
</AdminCard>
</div>
);
}
export function ChangePassword({ onComplete }: { onComplete: () => void }) {
const [form] = AdminForm.useForm<{
currentPassword: string;
newPassword: string;
confirmPassword: string;
}>();
const [loading, setLoading] = useState(false);
async function submit(values: {
currentPassword: string;
newPassword: string;
confirmPassword: string;
}) {
if (values.newPassword !== values.confirmPassword) {
message.error("两次输入的新密码不一致");
return;
}
setLoading(true);
try {
await createApiClient().changeAdminPassword(values.currentPassword, values.newPassword);
localStorage.setItem("adminMustChangePassword", "false");
message.success("密码已更新");
onComplete();
} catch (error) {
message.error(error instanceof Error ? error.message : "密码更新失败");
} finally {
setLoading(false);
}
}
return (
<div className="admin-auth">
<AdminCard className="admin-auth-card">
<div className="admin-auth-brand">
<BrandMark />
<span className="admin-header-brand">首次登录需要修改密码</span>
</div>
<p className="admin-auth-hint">请先设置只有你本人知道的新密码。</p>
<AdminForm form={form} layout="vertical" onFinish={submit}>
<AdminForm.Item name="currentPassword" label="初始密码" rules={[{ required: true }]}>
<AdminInput.Password />
</AdminForm.Item>
<AdminForm.Item
name="newPassword"
label="新密码"
rules={[{ required: true, min: 8, message: "请输入至少 8 位新密码" }]}
>
<AdminInput.Password />
</AdminForm.Item>
<AdminForm.Item name="confirmPassword" label="确认密码" rules={[{ required: true }]}>
<AdminInput.Password />
</AdminForm.Item>
<AdminButton type="primary" size="large" htmlType="submit" loading={loading} block>
保存新密码
</AdminButton>
</AdminForm>
</AdminCard>
</div>
);
}
@@ -0,0 +1,56 @@
.brand-page__content[hidden] {
display: none;
}
.brand-page__toolbar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
padding: 8px 12px;
border: 1px solid var(--admin-border);
border-radius: 10px;
background: var(--admin-fill-quiet);
margin-bottom: 16px;
}
.brand-page__toolbar .ant-segmented {
background: var(--admin-surface);
}
.brand-page__toolbar-actions {
display: flex;
align-items: center;
gap: 12px;
}
@media (max-width: 575px) {
.brand-page__toolbar {
flex-wrap: wrap;
}
}
.brand-page__settings {
min-width: 0;
}
.brand-settings-section {
padding: 20px;
border: 1px solid var(--admin-border);
border-radius: 10px;
background: var(--admin-surface);
}
.brand-settings-section + .brand-settings-section {
margin-top: 16px;
}
.brand-page__template-note {
margin-top: 16px;
}
@media (max-width: 1199px) {
.brand-page__template-note {
position: static;
}
}
+121 -44
View File
@@ -1,13 +1,24 @@
import { Button, Card, Col, Form, Input, Row, Select, Space, Tag, Typography, message } from "antd";
import { Alert, Button, Col, Form, Input, Row, Select, Segmented, message } from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { Link, useLocation } from "react-router-dom";
import type { BrandProfile } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { ImageUrlField } from "../../components/ImageUrlField.js";
import { MutationError, QueryState } from "../../components/QueryState.js";
import { StatusTag } from "../../components/StatusTag.js";
import { PresentationEditor } from "./PresentationEditor.js";
import type { PreviewSelection } from "./preview-selection.js";
import "./BrandPage.css";
import { useEditorDraft } from "./use-editor-draft.js";
export function BrandPage() {
const location = useLocation();
const initialSelection = location.state as PreviewSelection | undefined;
const [panel, setPanel] = useState("pages");
const [dirty, setDirty] = useState(false);
useEditorDraft(dirty);
const client = createApiClient();
const queryClient = useQueryClient();
const [form] = Form.useForm<BrandProfile>();
@@ -16,16 +27,26 @@ export function BrandPage() {
queryKey: ["admin-workspace"],
queryFn: () => client.getAdminWorkspace(),
});
const previewWorkspace = useQuery({
queryKey: ["admin-preview-workspace"],
queryFn: () => client.getAdminPreviewWorkspace(),
});
const template = useQuery({
queryKey: ["template", brand.data?.templateKey],
queryFn: () => client.getPublicTemplate(brand.data!.templateKey),
enabled: Boolean(brand.data?.templateKey),
});
const templateCatalog = useQuery({
queryKey: ["template-catalog"],
queryFn: () => client.listPublicTemplates(),
});
const save = useMutation({
mutationFn: (values: Partial<BrandProfile>) => client.updateAdminBrand(values),
onSuccess: () => {
setDirty(false);
message.success("品牌表达已保存");
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
},
});
return (
@@ -33,29 +54,58 @@ export function BrandPage() {
{!brand.data ? null : (
<>
<AdminPageHeader
title="品牌资料"
description="先让访客理解你是谁、服务谁,以及为什么值得信任。"
extra={<Tag color="blue">{template.data?.name ?? "当前模板"}</Tag>}
title="小程序页面"
description={
template.data?.description
? `先让访客理解你是谁、服务谁,以及为什么值得信任。${template.data.description}`
: "先让访客理解你是谁、服务谁,以及为什么值得信任。"
}
extra={<StatusTag tone="info" label={template.data?.name ?? "当前模板"} />}
/>
<Row gutter={[24, 24]} align="top">
<Col xs={24} xl={16}>
<div className="brand-page__toolbar">
<Segmented
aria-label="工作台视图"
value={panel}
onChange={(value) => setPanel(String(value))}
options={[
{ value: "pages", label: "页面编辑" },
{ value: "brand", label: "品牌资料" },
]}
/>
<div className="brand-page__toolbar-actions">
<StatusTag
tone={dirty ? "warning" : "neutral"}
label={dirty ? "品牌资料有未保存修改" : "草稿工作区"}
/>
<Link to="/admin/publication">检查与发布 →</Link>
</div>
</div>
<div className="brand-page__content" hidden={panel !== "brand"}>
<div className="brand-page__settings">
<Form
form={form}
layout="vertical"
initialValues={brand.data}
onValuesChange={() => setDirty(true)}
onFinish={(values) => save.mutate(values)}
>
<Card
title="我是谁"
extra={<Typography.Text type="secondary">公开展示</Typography.Text>}
>
<section className="brand-settings-section" aria-labelledby="brand-identity-title">
<div className="admin-section-head">
<div>
<h2 id="brand-identity-title" className="admin-section-title">
我是谁
</h2>
<p className="admin-section-description">公开展示的品牌身份和定位。</p>
</div>
<StatusTag tone="neutral" label="品牌基础信息" />
</div>
<Form.Item
name="name"
label="品牌名称"
help="可以是个人姓名、工作室名称或品牌名。"
rules={[{ required: true, message: "请输入品牌名称" }]}
>
<Input size="large" placeholder="例如:林然|品牌顾问" />
<Input size="large" placeholder="例如:品牌主理人|品牌顾问" />
</Form.Item>
<Form.Item
name="tagline"
@@ -73,8 +123,18 @@ export function BrandPage() {
placeholder="让第一次认识你的人快速建立基本信任。"
/>
</Form.Item>
</Card>
<Card title="如何联系与合作" style={{ marginTop: 24 }}>
</section>
<section className="brand-settings-section" aria-labelledby="brand-contact-title">
<div className="admin-section-head">
<div>
<h2 id="brand-contact-title" className="admin-section-title">
如何联系与合作
</h2>
<p className="admin-section-description">
让访客知道联系渠道、服务范围和响应预期。
</p>
</div>
</div>
<Row gutter={16}>
<Col xs={24} md={12}>
<Form.Item name="hours" label="可联系时间">
@@ -104,8 +164,18 @@ export function BrandPage() {
>
<Input.TextArea rows={3} placeholder="例如:收到咨询后 1 个工作日内回复。" />
</Form.Item>
</Card>
<Card title="模板与品牌视觉" style={{ marginTop: 24 }}>
</section>
<section className="brand-settings-section" aria-labelledby="brand-visual-title">
<div className="admin-section-head">
<div>
<h2 id="brand-visual-title" className="admin-section-title">
模板与品牌视觉
</h2>
<p className="admin-section-description">
模板负责业务表达,品牌信息仍由你统一维护。
</p>
</div>
</div>
<Form.Item
name="templateKey"
label="业务表达模板"
@@ -113,10 +183,10 @@ export function BrandPage() {
>
<Select
disabled
options={[
{ value: "personal", label: "个人品牌" },
{ value: "food", label: "餐饮模板" },
]}
options={(templateCatalog.data?.industries ?? []).map((item) => ({
value: item.key,
label: item.name,
}))}
/>
</Form.Item>
<Row gutter={16}>
@@ -124,44 +194,51 @@ export function BrandPage() {
<Form.Item
name="avatarUrl"
label="头像图片地址"
help="粘贴一张可公开访问的图片地址。"
help="点击上传或粘贴一张可公开访问的图片地址。"
>
<ImageUrlField />
<ImageUrlField scope="brand" />
</Form.Item>
</Col>
<Col xs={24} md={12}>
<Form.Item name="coverUrl" label="品牌封面图片地址" help="建议使用横向图片。">
<ImageUrlField />
<Form.Item
name="coverUrl"
label="品牌封面图片地址"
help="点击上传,或粘贴一张横向图片地址。"
>
<ImageUrlField scope="brand" />
</Form.Item>
</Col>
</Row>
</Card>
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
</section>
<div className="admin-actions admin-offset-top-lg">
<MutationError error={save.error} />
<Button type="primary" htmlType="submit" loading={save.isPending} size="large">
保存品牌表达
</Button>
</Space>
</div>
</Form>
<PresentationEditor
templateContent={workspace.data?.templateContent}
config={brand.data.config}
brand={brand.data}
loading={workspace.isLoading}
error={workspace.error}
</div>
{template.data ? (
<Alert
className="brand-page__template-note"
type="info"
showIcon
message={`当前使用:${template.data.name}`}
description={`适用场景:${template.data.serviceCategories.join("、") || "通用品牌展示"}`}
/>
</Col>
<Col xs={24} xl={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>
) : null}
</div>
<div hidden={panel !== "pages"}>
<PresentationEditor
templateContent={workspace.data?.templateContent}
previewWorkspace={previewWorkspace.data}
config={brand.data.config}
brand={brand.data}
loading={workspace.isLoading}
error={workspace.error}
{...(initialSelection ? { initialSelection } : {})}
/>
</div>
</>
)}
</QueryState>
@@ -0,0 +1,173 @@
.component-template-preview-shell {
height: 100%;
}
.component-template-preview__tools {
display: flex;
gap: 8px;
padding: 8px 12px;
border-bottom: 1px solid var(--admin-border);
background: #fff;
}
.component-template-preview__tools button {
padding: 4px 12px;
border: 1px solid var(--admin-border);
border-radius: 6px;
background: #fff;
cursor: pointer;
}
.component-template-preview__tools button[aria-pressed="true"] {
border-color: var(--admin-primary);
color: var(--admin-primary);
}
.component-template-preview {
position: relative;
width: 100%;
height: calc(100% - 49px);
min-height: 510px;
padding: 24px 16px;
overflow-x: hidden;
overflow-y: auto;
background: var(--admin-fill);
}
.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) {
--brand-button-height: 11.7333333cqw;
--brand-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(--brand-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 var(--admin-primary);
border-radius: 4px;
}
.component-template-preview__outline.is-selected {
z-index: 6;
border-color: var(--admin-primary);
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 var(--admin-primary) !important;
border-radius: 4px !important;
background: #fff !important;
color: var(--admin-primary) !important;
font-size: 12px !important;
line-height: 20px !important;
cursor: pointer;
}
.component-template-preview__outline span {
position: absolute;
top: 0;
left: 0;
max-width: calc(100% - 8px);
transform: translateY(-100%);
padding: 2px 7px;
overflow: hidden;
border-radius: 4px 4px 0 0;
background: var(--admin-primary);
color: #fff;
font-size: 12px;
line-height: 18px;
text-overflow: ellipsis;
white-space: nowrap;
}
.component-template-preview__outline.is-selected span {
top: 4px;
transform: none;
}
.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,248 @@
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.filter(
(item) => item.key !== selection?.targetKey,
)) {
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;
if (event.target instanceof Element && event.target.closest("[data-editor-overlay]")) {
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,141 @@
import { Alert, Button, Form, Input, Select, Space, Switch, 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)}
>
<p className="admin-section-description admin-offset-bottom">
{record.name} · 编辑字段:{field.label}
</p>
<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 ? <h4 className="admin-subhead admin-offset-bottom-xs">选项</h4> : 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
className="admin-offset-top-lg"
type="primary"
htmlType="submit"
loading={save.isPending}
>
保存表单字段
</Button>
</Form>
);
}
@@ -0,0 +1,174 @@
.presentation-editor {
margin-top: 0;
}
.presentation-editor__header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 16px;
}
.presentation-editor > .ant-space {
display: flex;
width: 100%;
margin-bottom: 24px !important;
padding: 6px;
border: 1px solid var(--admin-border);
border-radius: 10px;
background: var(--admin-fill-quiet);
}
@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 var(--admin-border);
border-radius: 12px;
overflow: hidden;
background: var(--admin-surface);
}
.presentation-editor__preview {
grid-area: preview;
padding: 20px !important;
background: var(--admin-fill);
min-width: 0;
}
.presentation-editor__inspector {
grid-area: inspector;
padding: 24px !important;
min-width: 0;
border-left: 1px solid var(--admin-border);
}
.presentation-editor__outline {
grid-area: outline;
padding: 20px 12px;
border-right: 1px solid var(--admin-border);
}
.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: var(--admin-primary-bg);
color: var(--admin-primary);
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__form {
display: flex;
flex-direction: column;
min-height: 0;
}
.presentation-editor__form-body {
flex: 1;
}
.presentation-editor__inspector .presentation-editor__form-body > section {
padding: 16px;
border: 1px solid var(--admin-border);
border-radius: 12px;
background: var(--admin-fill);
}
.presentation-editor__inspector .presentation-editor__form-body > section + section {
margin-top: 16px;
}
.presentation-editor__form-actions {
position: sticky;
bottom: 0;
z-index: 2;
padding: 16px 0 4px;
border-top: 1px solid var(--admin-border);
background: var(--admin-surface);
}
.presentation-editor__form-actions .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 var(--admin-border);
}
.presentation-editor__inspector {
border-left: 0;
border-top: 1px solid var(--admin-border);
}
}
@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,75 @@
import {
Alert,
Button,
Card,
Divider,
Col,
Form,
Grid,
Input,
InputNumber,
Row,
Select,
Segmented,
Space,
Tag,
Typography,
message,
} from "antd";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Alert, Button, Grid, Select, Segmented, Space, Typography } from "antd";
import { useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import type { AdminTemplateContent, TemplateAdminField } from "@personal-brand/api-client";
import type {
AdminTemplateContent,
RuntimeWorkspace,
TemplateAdminSection,
} from "@personal-brand/api-client";
import type { BrandProfile } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import { ImageUrlField } from "../../components/ImageUrlField.js";
import { TemplateListField } from "../../components/TemplateListField.js";
import { MutationError } from "../../components/QueryState.js";
import { StatusTag } from "../../components/StatusTag.js";
import { RecordContentEditor } from "../../components/RecordContentEditor.js";
import { TemplatePreview } from "./TemplatePreview.js";
import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js";
import {
resolvePreviewSelection,
previewTrustRecordId,
type PreviewSelection,
type PreviewTarget,
} from "./preview-selection.js";
import {
applyPresentationValues,
filterSectionsForPreviewTarget,
presentationFieldName,
readPresentationValue,
type PresentationValues,
} from "./presentation-bindings.js";
} from "../../lib/presentation/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";
import type { RecordDraft } from "./presentation-editor-record-preview.js";
import { pageTitle, previewTargetSource, trustSection } from "./presentation-editor-helpers.js";
import { useDraftWorkspace } from "./use-draft-workspace.js";
import { PresentationFormPanel } from "./PresentationFormPanel.js";
interface PresentationEditorProps {
templateContent: AdminTemplateContent | null | undefined;
previewWorkspace?: RuntimeWorkspace | undefined;
config: Record<string, unknown> | null | undefined;
brand: BrandProfile;
loading?: boolean;
error?: unknown;
}
function renderField(field: TemplateAdminField) {
if (field.input === "textarea")
return (
<Input.TextArea
rows={3}
maxLength={field.maxLength}
showCount={!!field.maxLength}
placeholder={field.placeholder}
/>
);
if (field.input === "image")
return <ImageUrlField {...(field.placeholder ? { placeholder: field.placeholder } : {})} />;
if (field.input === "number")
return <InputNumber style={{ width: "100%" }} placeholder={field.placeholder} />;
if (field.input === "boolean")
return (
<Select
options={[
{ value: true, label: "是" },
{ value: false, label: "否" },
]}
/>
);
if (field.input === "select" || field.input === "multi-select")
return (
<Select
{...(field.input === "multi-select" ? { mode: "multiple" as const } : {})}
options={field.options ?? []}
/>
);
return (
<Input
type={field.input === "phone" ? "tel" : "text"}
maxLength={field.maxLength}
placeholder={field.placeholder}
/>
);
initialSelection?: PreviewSelection;
}
export function PresentationEditor({
templateContent,
previewWorkspace,
config,
brand,
loading,
error,
initialSelection,
}: PresentationEditorProps) {
const [form] = Form.useForm<PresentationValues>();
const queryClient = useQueryClient();
const navigate = useNavigate();
const breakpoints = Grid.useBreakpoint();
const [activePage, setActivePage] = useState<string>();
const [activeTarget, setActiveTarget] = useState<string>();
const sections = useMemo(() => {
const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({
...field,
binding: field.binding ?? `brand.config.templateData.${field.key}`,
}));
return [
...(declaredTemplateFields.length
? [
{
key: "template-data",
title: "模板专属内容",
description: "这些字段由当前小程序模板定义,保存后发布才会对外展示。",
page: templateContent?.templateFields?.[0]?.page ?? "home",
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 [selection, setSelection] = useState<PreviewSelection | undefined>(initialSelection);
const [hasInitializedSelection, setHasInitializedSelection] = useState(Boolean(initialSelection));
const [detailOfferingId, setDetailOfferingId] = useState<string>();
const [recordDraft, setRecordDraft] = useState<RecordDraft>();
const [inquiryDraft, setInquiryDraft] =
useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>();
const [brandDirty, setBrandDirty] = useState(false);
const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft);
const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand");
const sections = useBrandPresentationSections(templateContent);
const pageOptions = useMemo(() => {
const pages = new Map<string, string>();
for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label);
@@ -144,12 +84,97 @@ export function PresentationEditor({
? activePage
: pageOptions[0]?.value;
const visibleSections = sections.filter((section) => section.page === selectedPage);
const visibleTargets = visibleSections.flatMap((section) =>
(section.previewTargets ?? []).map((target) => ({ ...target, page: section.page })),
const recordSections = useMemo(
() =>
(templateContent?.trustContentTypes ?? [])
.filter((item) => item.pages?.includes(selectedPage ?? ""))
.map((item) => trustSection(item, selectedPage ?? "home")),
[templateContent, selectedPage],
);
const visibleTargets = useMemo<PreviewTarget[]>(
() =>
[...(templateContent?.admin.sections ?? []), ...recordSections]
.filter(
(section) =>
section.page === selectedPage &&
(selectedPage !== "detail" || section.target === "brand"),
)
.flatMap((section) =>
(section.previewTargets ?? []).map((target) => ({
...target,
page: section.page,
source: previewTargetSource(section, target.key),
...(section.key.startsWith("trust:") ? { trustType: section.key.slice(6) } : {}),
})),
)
.concat(
selectedPage === "inquiry" && inquiryRuntime
? inquiryRuntime.fields.map((field) => ({
key: `inquiry-field:${field.key}`,
label: field.label,
page: "inquiry",
source: "inquiry" as const,
}))
: [],
),
[templateContent, selectedPage, recordSections, inquiryRuntime],
);
const activeTarget = selection?.targetKey;
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
const editableSections = filterSectionsForPreviewTarget(visibleSections, selectedTarget?.key);
const handleTargetSelected = useCallback((key: string) => setActiveTarget(key), []);
const selectedSection = [...(templateContent?.admin.sections ?? []), ...recordSections].find(
(section) =>
section.page === selectedPage &&
section.previewTargets?.some((target) => target.key === selectedTarget?.key),
);
const selectedRecordSource =
selectedTarget?.source === "offering" || selectedTarget?.source === "trust"
? selectedTarget.source
: undefined;
const { offeringsQuery, trustQuery, selectedRecord } = usePresentationRecordQueries(
selectedRecordSource,
selection?.recordId,
);
const editableSections = filterSectionsForPreviewTarget(
visibleSections.filter((section) =>
section.fields.some((field) => field.binding.startsWith("brand.")),
),
selectedTarget?.key,
);
const recordSection = useMemo(
() =>
selectedSection && selection?.targetKey
? {
...selectedSection,
fields: selectedSection.fields.filter(
(field) => field.previewTarget === selection.targetKey,
),
}
: undefined,
[selectedSection, selection?.targetKey],
);
const handleTargetSelected = useCallback(
(next?: PreviewSelection) => {
const select = () =>
setSelection(
next
? resolvePreviewSelection(
next.targetKey,
next.recordId,
visibleTargets,
selectedPage ?? "home",
)
: undefined,
);
if (recordDraft || inquiryDraft)
guardDraft(() => {
setInquiryDraft(undefined);
setRecordDraft(undefined);
select();
});
else select();
},
[visibleTargets, selectedPage, recordDraft, inquiryDraft, guardDraft],
);
const relatedTargets = [
...(templateContent?.admin.sections ?? [])
.filter((section) => section.page === selectedPage && section.target !== "brand")
@@ -180,55 +205,112 @@ export function PresentationEditor({
},
],
);
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,
);
}
const relevantPageLinks = selectedSection
? pageLinks.filter((item) => {
if (item.target.startsWith("trust:")) return selectedSection.target === "trust";
return item.target === selectedSection.target;
})
: pageLinks;
const formState = useBrandPresentationForm({ brand, config, sections });
const { form, initialValues } = formState;
const save = useBrandSaveMutation({ ...formState, brand, config, sections, queryClient });
useEffect(() => {
const initialPage =
typeof initialSelection === "object" && "page" in initialSelection
? String(initialSelection.page)
: undefined;
if (initialPage) {
setActivePage(
pageOptions.some((item) => item.value === initialPage)
? initialPage
: pageOptions[0]?.value,
);
return;
}
return values;
}, [config, sections]);
const save = useMutation({
mutationFn: (values: PresentationValues) => {
const nextConfig = applyPresentationValues(config, sections, values);
return createApiClient().updateAdminBrand({ config: nextConfig });
},
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: ["public-runtime-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["publication-readiness"] });
},
if (!activePage && pageOptions.length) setActivePage(pageOptions[0]?.value);
}, [activePage, initialSelection, pageOptions]);
useEffect(() => {
if (hasInitializedSelection) return;
if (!pageOptions.length) return;
if (!initialSelection) return;
const requestedPage =
typeof initialSelection === "object" && "page" in initialSelection
? String(initialSelection.page)
: undefined;
const resolvedPage =
requestedPage && pageOptions.some((item) => item.value === requestedPage)
? requestedPage
: (pageOptions[0]?.value ?? "home");
setSelection(
resolvePreviewSelection(
initialSelection.targetKey,
initialSelection.recordId,
visibleTargets,
resolvedPage,
),
);
setActivePage(resolvedPage);
setHasInitializedSelection(true);
}, [hasInitializedSelection, initialSelection, pageOptions, selectedPage, visibleTargets]);
useEffect(() => {
if (!initialSelection) setSelection(undefined);
}, [initialSelection, selectedPage, templateContent?.displayName]);
useEffect(() => {
if (!selection?.recordId) return;
const records =
selectedTarget?.source === "trust"
? previewWorkspace?.trustItems
: previewWorkspace?.offerings;
if (records && !records.some((item) => item.id === selection.recordId)) setSelection(undefined);
}, [
previewWorkspace?.offerings,
previewWorkspace?.trustItems,
selectedTarget?.source,
selection,
]);
useEffect(
() => setRecordDraft(undefined),
[selection?.targetKey, selection?.recordId, selectedPage],
);
const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({
brand,
config,
sections,
form,
onDirty: () => setBrandDirty(true),
});
useEffect(() => {
form.setFieldsValue(initialValues);
}, [form, initialValues]);
useEffect(() => {
if (!pageOptions.some((item) => item.value === activePage))
setActivePage(pageOptions[0]?.value);
}, [activePage, pageOptions]);
useEffect(() => setActiveTarget(undefined), [selectedPage]);
const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection });
useEffect(() => resetPreview(), [config, initialValues, resetPreview]);
const draftWorkspace = useDraftWorkspace({
previewWorkspace,
previewBrand,
inquiryRuntime,
inquiryDraft,
recordDraft,
selectedRecord,
recordSection,
recordPreview,
templateContent,
});
const selectedDetailOfferingId =
detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId)
? detailOfferingId
: draftWorkspace?.offerings[0]?.id;
return (
<Card
title="小程序页面配置"
extra={templateContent ? <Tag color="blue">{templateContent.displayName}</Tag> : null}
style={{ marginTop: 32 }}
styles={{ body: { minHeight: breakpoints.md ? 760 : 620 } }}
>
<Typography.Paragraph type="secondary">
按小程序页面查找内容。这里修改的是草稿,发布后访客才会看到更新。
</Typography.Paragraph>
<section className="presentation-editor" aria-labelledby="presentation-editor-title">
<div className="presentation-editor__header">
<div>
<h2 id="presentation-editor-title" className="admin-section-title">
小程序页面配置
</h2>
<p className="admin-section-description">
按页面查找内容。这里修改的是草稿,发布后访客才会看到更新。
</p>
</div>
{templateContent ? <StatusTag tone="info" label={templateContent.displayName} /> : null}
</div>
{loading ? <Alert type="info" showIcon message="正在读取当前模板的编辑项目" /> : null}
{error ? (
<Alert type="warning" showIcon message="模板编辑项目读取失败,请刷新后重试。" />
@@ -238,173 +320,313 @@ export function PresentationEditor({
) : null}
{templateContent ? (
<>
<Space wrap style={{ marginBottom: 24 }}>
<Space className="presentation-editor__navigation" wrap>
{breakpoints.xs ? (
<Select
aria-label="选择小程序页面"
value={selectedPage}
options={pageOptions}
onChange={setActivePage}
style={{ minWidth: 180 }}
onChange={(value) =>
guardDraft(() => {
setBrandDirty(false);
form.setFieldsValue(initialValues);
resetPreview();
setRecordDraft(undefined);
setInquiryDraft(undefined);
setActivePage(value);
})
}
className="admin-field-w-2xl"
/>
) : (
<Segmented
value={selectedPage}
options={pageOptions}
onChange={(value) => setActivePage(String(value))}
onChange={(value) =>
guardDraft(() => {
setBrandDirty(false);
form.setFieldsValue(initialValues);
resetPreview();
setRecordDraft(undefined);
setInquiryDraft(undefined);
setActivePage(String(value));
})
}
/>
)}
</Space>
<Row gutter={[24, 24]} align="top">
<Col xs={24} xl={12}>
<Typography.Title level={5}>页面预览</Typography.Title>
<div className="presentation-editor__workspace">
<div className="presentation-editor__preview">
<h3 className="admin-section-title admin-flush">页面预览</h3>
{selectedPage === "detail" && draftWorkspace?.offerings.length ? (
<Select
aria-label="选择详情页业务内容"
className="admin-block admin-offset-bottom-sm"
value={selectedDetailOfferingId}
options={draftWorkspace.offerings.map((item) => ({
value: item.id,
label: item.name,
}))}
onChange={(value) => {
setDetailOfferingId(value);
setSelection(undefined);
}}
/>
) : null}
<TemplatePreview
brand={brand}
brand={previewBrand}
{...(draftWorkspace ? { workspace: draftWorkspace } : {})}
page={selectedPage ?? "home"}
route={`/pages/${encodeURIComponent(selectedPage ?? "home")}/index`}
{...(selectedPage === "detail" && selectedDetailOfferingId
? { offeringId: selectedDetailOfferingId }
: {})}
{...(activeTarget ? { targetKey: activeTarget } : {})}
{...(selection ? { selection } : {})}
targets={visibleTargets}
onTargetSelected={handleTargetSelected}
/>
</div>
<aside className="presentation-editor__outline" aria-label="页面区域">
<h3 className="admin-section-title admin-flush">页面区域</h3>
<p className="admin-section-description">选择区域,编辑对应内容</p>
{visibleTargets.length ? (
<Space wrap style={{ marginTop: 16 }}>
<Space className="presentation-editor__regions admin-offset-top" wrap>
{visibleTargets.map((target) => (
<Button
key={target.key}
className={
visibleTargets.some((parent) => parent.children?.includes(target.key))
? "is-child-region"
: ""
}
aria-pressed={activeTarget === target.key}
type={activeTarget === target.key ? "primary" : "default"}
onClick={() => 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}
</Button>
))}
</Space>
) : null}
</Col>
<Col xs={24} xl={12}>
<Typography.Title level={5}>
{!visibleTargets.length ? (
<Typography.Text type="secondary">此页为动态预览</Typography.Text>
) : null}
</aside>
<div className="presentation-editor__inspector">
<h3 className="admin-section-title admin-flush">
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
</Typography.Title>
<Form
form={form}
layout="vertical"
initialValues={initialValues}
onFinish={(values) => save.mutate(values)}
style={{ minHeight: 540, display: "flex", flexDirection: "column" }}
>
<div style={{ flex: 1 }}>
{editableSections.map((section, index) => (
<section key={section.key} aria-labelledby={`section-${section.key}`}>
{selectedTarget && index > 0 ? <Divider /> : null}
<Typography.Title id={`section-${section.key}`} level={5}>
{selectedTarget
? fieldTargetTitle(section, selectedTarget.label)
: section.title}
</Typography.Title>
{!selectedTarget ? (
<Typography.Paragraph type="secondary">
{section.description}
</Typography.Paragraph>
) : null}
<Row gutter={16}>
{section.fields.map((field) => (
<Col
key={field.key}
xs={24}
md={field.input === "textarea" || field.input === "list" ? 24 : 12}
</h3>
<StatusTag
tone={
save.isError
? "error"
: save.isPending || brandDirty || recordDraft || inquiryDraft
? "warning"
: "neutral"
}
label={
save.isPending
? "正在保存"
: save.isError
? "保存失败,请重试"
: brandDirty || recordDraft || inquiryDraft
? "有未保存修改"
: "草稿已同步"
}
/>
{selectedPage === "detail" && !selectedTarget ? (
<Alert
type="info"
showIcon
message="详情页由所选业务内容动态生成"
description="选择业务内容预览详情,记录内容在业务提供项中维护;公共标题和按钮文案可从左侧区域列表配置,对全部详情生效。"
action={
<Button
onClick={() => {
void navigate("/admin/services");
}}
>
管理业务内容
</Button>
}
/>
) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? (
<InquiryPreviewEditor
runtime={
draftWorkspace?.inquiryForms.find((item) => item.key === inquiryRuntime.key) ??
inquiryRuntime
}
fieldKey={activeTarget.slice("inquiry-field:".length)}
onDraft={setInquiryDraft}
onSaved={() => setInquiryDraft(undefined)}
/>
) : selectedTarget?.composite ? (
<Alert
type="info"
showIcon
message="这是一个组合区域"
description={
<Space wrap>
{(selectedTarget.children ?? []).map((childKey) => {
const child = visibleTargets.find((item) => item.key === childKey);
if (!child) return null;
return (
<Button
key={child.key}
onClick={() => {
const recordId =
child.source === "offering"
? selectedPage === "detail"
? selectedDetailOfferingId
: draftWorkspace?.offerings[0]?.id
: child.source === "trust"
? previewTrustRecordId(
draftWorkspace?.trustItems ?? [],
child.trustType,
)
: undefined;
handleTargetSelected({
targetKey: child.key,
...(recordId ? { recordId } : {}),
});
}}
>
{field.input === "list" ? (
<TemplateListField
field={field}
name={presentationFieldName(section.key, field.key)}
/>
) : (
<Form.Item
name={presentationFieldName(section.key, field.key)}
label={field.label}
{...(field.help ? { help: field.help } : {})}
{...(field.required
? { rules: [{ required: true, message: `请填写${field.label}` }] }
: {})}
>
{renderField(field)}
</Form.Item>
)}
</Col>
))}
</Row>
</section>
))}
{pageLinks.length ? (
<Alert
type="info"
showIcon
style={{ marginBottom: 24 }}
message="这个页面还有关联内容"
description={
<Space wrap>
{pageLinks.map((item) => (
编辑{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
key={item.target}
type="link"
size="small"
onClick={() => {
if (item.target.startsWith("trust:")) {
void navigate(
`/admin/trust?type=${encodeURIComponent(item.target.slice(6))}`,
);
return;
}
void navigate(
item.target === "offering"
? "/admin/services"
: "/admin/workspace",
);
if (selectedRecordSource === "offering")
void offeringsQuery.refetch();
else void trustQuery.refetch();
}}
style={{ padding: 0 }}
>
{item.label}
重试
</Button>
))}
</Space>
),
}
: {})}
/>
)
) : selectedRecordSource ? (
<Alert
type="info"
showIcon
message="此区域尚未配置内容"
description="创建并启用对应内容后,即可在预览中点选编辑。"
action={
<Button
onClick={() =>
guardDraft(() => {
void navigate(
selectedRecordSource === "trust"
? `/admin/trust?type=${encodeURIComponent(selectedTarget?.trustType ?? "")}`
: "/admin/services",
);
})
}
/>
) : null}
{!editableSections.length && !pageLinks.length ? (
<Typography.Paragraph type="secondary">
这个页面没有单独的品牌文案配置。
</Typography.Paragraph>
) : null}
>
配置此区域内容
</Button>
}
/>
) : !selectedTarget ? (
<div className="presentation-editor__empty">
<h3 className="admin-subhead">选择要编辑的区域</h3>
<p className="admin-section-description">
点击预览中的内容,或使用区域列表,查看并修改对应字段。
</p>
</div>
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
<MutationError error={save.error} />
<Button type="primary" htmlType="submit" loading={save.isPending}>
保存页面内容
</Button>
</Space>
</Form>
</Col>
</Row>
) : (
<PresentationFormPanel
form={form}
initialValues={initialValues}
editableSections={editableSections}
relevantPageLinks={relevantPageLinks}
selectedTarget={selectedTarget}
save={{
error: save.error,
isPending: save.isPending,
mutate: (values) => save.mutate(values),
}}
onValuesChange={handleValuesChange}
/>
)}
</div>
</div>
</>
) : null}
</Card>
</section>
);
}
function pageTitle(page: string): string {
return (
(
{
home: "首页",
offerings: "业务展示",
service: "服务说明",
detail: "详情页",
inquiry: "咨询页",
success: "提交成功页",
records: "记录页",
profile: "主理人页",
} as Record<string, string>
)[page] ?? page
);
}
function fieldTargetTitle(section: { title: string }, targetLabel: string): string {
return section.title === targetLabel ? targetLabel : `${targetLabel} · ${section.title}`;
}
@@ -0,0 +1,134 @@
import { Alert, Button, Col, Divider, Form, Row, Space } from "antd";
import type { FormInstance } from "antd";
import { useNavigate } from "react-router-dom";
import type { TemplateAdminSection } from "@personal-brand/api-client";
import { TemplateFieldRenderer } from "../../components/TemplateFieldRenderer.js";
import { TemplateListField } from "../../components/TemplateListField.js";
import { MutationError } from "../../components/QueryState.js";
import {
presentationFieldName,
type PresentationValues,
} from "../../lib/presentation/presentation-bindings.js";
import { fieldTargetTitle } from "./presentation-editor-helpers.js";
import type { PreviewTarget } from "./preview-selection.js";
interface PresentationFormPanelProps {
form: FormInstance<PresentationValues>;
initialValues: PresentationValues;
editableSections: TemplateAdminSection[];
relevantPageLinks: { target: string; label: string | undefined }[];
selectedTarget: PreviewTarget | undefined;
save: {
error: unknown;
isPending: boolean;
mutate: (values: PresentationValues) => void;
};
onValuesChange: (changed: PresentationValues, allValues: PresentationValues) => void;
}
export function PresentationFormPanel({
form,
initialValues,
editableSections,
relevantPageLinks,
selectedTarget,
save,
onValuesChange,
}: PresentationFormPanelProps) {
const navigate = useNavigate();
const hasEditableFields = editableSections.some((section) => section.fields.length);
return (
<Form
form={form}
layout="vertical"
initialValues={initialValues}
onValuesChange={onValuesChange}
onFinish={() => save.mutate(form.getFieldsValue(true) as PresentationValues)}
className="presentation-editor__form"
>
<div className="presentation-editor__form-body">
{editableSections.map((section, index) => (
<section key={section.key} aria-labelledby={`section-${section.key}`}>
{selectedTarget && index > 0 ? <Divider /> : null}
<h4 id={`section-${section.key}`} className="admin-subhead">
{selectedTarget ? fieldTargetTitle(section, selectedTarget.label) : section.title}
</h4>
{!selectedTarget ? (
<p className="admin-section-description admin-offset-bottom">{section.description}</p>
) : null}
<Row gutter={16}>
{section.fields.map((field) => (
<Col key={field.key} xs={24} md={24}>
{field.input === "list" ? (
<TemplateListField
field={field}
name={presentationFieldName(section.key, field.key)}
/>
) : (
<Form.Item
name={presentationFieldName(section.key, field.key)}
label={field.label}
{...(field.help ? { help: field.help } : {})}
{...(field.required
? {
rules: [{ required: true, message: `请填写${field.label}` }],
}
: {})}
>
<TemplateFieldRenderer field={field} />
</Form.Item>
)}
</Col>
))}
</Row>
</section>
))}
{relevantPageLinks.length ? (
<Alert
type="info"
showIcon
className="admin-offset-bottom-lg"
message="这个页面还有关联内容"
description={
<Space wrap>
{relevantPageLinks.map((item) => (
<Button
key={item.target}
type="link"
onClick={() => {
if (item.target.startsWith("trust:")) {
void navigate(
`/admin/trust?type=${encodeURIComponent(item.target.slice(6))}`,
);
return;
}
void navigate(
item.target === "offering" ? "/admin/services" : "/admin/workspace",
);
}}
className="admin-link-flush"
>
{item.label}
</Button>
))}
</Space>
}
/>
) : null}
{!hasEditableFields && !relevantPageLinks.length ? (
<p className="admin-section-description">这个页面没有单独的品牌文案配置。</p>
) : null}
{selectedTarget && !hasEditableFields && relevantPageLinks.length ? (
<p className="admin-section-description">此区域内容由对应的业务管理页面维护。</p>
) : null}
</div>
<div className="presentation-editor__form-actions admin-actions admin-offset-top-lg">
<MutationError error={save.error} />
<Button type="primary" htmlType="submit" loading={save.isPending}>
保存页面内容
</Button>
</div>
</Form>
);
}
@@ -4,8 +4,8 @@
height: min(72vh, 760px);
min-height: 560px;
overflow: hidden;
border: 1px solid #e8e8e8;
background: #f3f4f6;
border: 1px solid var(--admin-border);
background: var(--admin-fill);
}
.template-preview iframe {
@@ -4,42 +4,51 @@ import type {
BrandProfile,
EditorPreviewFrameMessage,
EditorPreviewHostMessage,
RuntimeWorkspace,
} from "@personal-brand/api-client";
import { templatePreviewUrl } from "../../lib/template-preview.js";
import { ComponentTemplatePreview } from "./ComponentTemplatePreview.js";
import { resolveTemplateRenderer } from "./component-renderers.jsx";
import type { PreviewSelection, PreviewTarget } from "./preview-selection.js";
import "./TemplatePreview.css";
export function TemplatePreview({
brand,
workspace,
page,
offeringId,
targetKey,
route,
selection,
targets,
onTargetSelected,
}: {
brand: BrandProfile;
workspace?: RuntimeWorkspace;
page: string;
offeringId?: string;
targetKey?: string;
route: string;
onTargetSelected: (key: string) => void;
selection?: PreviewSelection;
targets: PreviewTarget[];
onTargetSelected: (selection?: PreviewSelection) => void;
}) {
const frame = useRef<HTMLIFrameElement>(null);
const useComponent = Boolean(workspace && resolveTemplateRenderer(workspace));
const [ready, setReady] = useState(false);
const [error, setError] = useState("");
const [reloadKey, setReloadKey] = useState(0);
const config = brand.config ?? {};
const templateKey =
typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : brand.templateKey;
const url = useMemo(
() =>
templatePreviewUrl(
templateKey,
brand.slug,
page,
import.meta.env.VITE_TEMPLATE_PREVIEW_URLS,
window.location.origin,
route,
),
[brand.slug, page, reloadKey, route, templateKey],
);
const url = useMemo(() => {
const value = templatePreviewUrl(
brand.slug,
page,
import.meta.env.VITE_TEMPLATE_PREVIEW_URL || "/template-preview/index.html",
window.location.origin,
`/pages/${encodeURIComponent(page)}/index`,
);
if (!value) return undefined;
const preview = new URL(value);
preview.searchParams.set("refresh", String(reloadKey));
return preview.toString();
}, [brand.slug, page, reloadKey]);
const origin = useMemo(() => (url ? new URL(url).origin : ""), [url]);
const brandDraft = useMemo(
() => ({
@@ -70,7 +79,7 @@ export function TemplatePreview({
if (message?.protocol !== "personal-brand-editor-preview" || message.version !== 1) return;
if (message.type === "ready") setReady(true);
if (message.type === "targetSelected" && message.page === page)
onTargetSelected(message.targetKey);
onTargetSelected({ targetKey: message.targetKey });
};
window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage);
@@ -80,12 +89,21 @@ export function TemplatePreview({
if (!ready || !frame.current?.contentWindow || !origin) return;
const send = (message: EditorPreviewHostMessage) =>
frame.current?.contentWindow?.postMessage(message, origin);
send({
protocol: "personal-brand-editor-preview",
version: 1,
type: "brandDraft",
brand: brandDraft,
});
if (workspace) {
send({
protocol: "personal-brand-editor-preview",
version: 1,
type: "workspaceDraft",
workspace,
});
} else {
send({
protocol: "personal-brand-editor-preview",
version: 1,
type: "brandDraft",
brand: brandDraft,
});
}
if (targetKey)
send({
protocol: "personal-brand-editor-preview",
@@ -93,7 +111,7 @@ export function TemplatePreview({
type: "focusTarget",
targetKey,
});
}, [brandDraft, origin, ready, targetKey]);
}, [brandDraft, origin, ready, targetKey, workspace]);
useEffect(() => {
const refresh = () => setReloadKey((value) => value + 1);
@@ -101,35 +119,50 @@ export function TemplatePreview({
return () => window.removeEventListener("template-preview-refresh", refresh);
}, []);
if (!url)
if (!useComponent && !url)
return (
<Alert
type="warning"
showIcon
message="尚未配置模板预览服务"
description="请在 Admin 环境变量 VITE_TEMPLATE_PREVIEW_URLS 中为模板配置 H5 预览地址。"
message="页面预览暂不可用"
description="请确认模板预览资源已构建并发布,或本地预览服务正在运行。"
/>
);
return (
<div className="template-preview">
{!ready && !error ? (
<div className="template-preview__loading">
<Spin tip="正在加载页面预览" />
</div>
{workspace && useComponent ? (
<ComponentTemplatePreview
workspace={workspace}
page={page}
{...(offeringId ? { offeringId } : {})}
{...(targetKey ? { targetKey } : {})}
{...(selection ? { selection } : {})}
targets={targets}
onTargetSelected={onTargetSelected}
/>
) : null}
{error ? (
<Alert type="error" showIcon message="页面预览加载失败" description={error} />
{!useComponent ? (
<>
{!ready && !error ? (
<div className="template-preview__loading">
<Spin tip="正在加载页面预览" />
</div>
) : null}
{error ? (
<Alert type="error" showIcon message="页面预览加载失败" description={error} />
) : null}
<iframe
key={url}
ref={frame}
title="小程序页面预览"
src={url}
referrerPolicy="origin"
onError={() => setError("请检查预览服务地址和网络连接。")}
style={{ opacity: ready ? 1 : 0 }}
/>
</>
) : null}
<iframe
key={url}
ref={frame}
title="小程序页面预览"
src={url}
referrerPolicy="origin"
onError={() => setError("请检查预览服务地址和网络连接。")}
style={{ opacity: ready ? 1 : 0 }}
/>
</div>
);
}
+10
View File
@@ -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>
);
};
}
@@ -0,0 +1,93 @@
import type {
AdminTemplateContent,
TemplateAdminField,
TemplateAdminSection,
} from "@personal-brand/api-client";
export function trustSection(
declaration: NonNullable<AdminTemplateContent["trustContentTypes"]>[number],
page: string,
): TemplateAdminSection {
const key = `trust:${declaration.type}`;
return {
key,
title: declaration.label,
description: declaration.help ?? "编辑当前展示内容。",
page,
target: "trust",
previewTargets: [
{ key, label: declaration.label },
...(declaration.previewTargets ?? []).filter(
(target) => !target.page || target.page === page,
),
],
fields: [
{
key: "title",
binding: "trust.title",
label: declaration.adminFields.title,
input: "text" as const,
required: true,
},
...(["summary", "content"] as const)
.filter((field) => !declaration.hideStandardFields?.includes(field))
.map((field) => ({
key: field,
binding: `trust.${field}`,
label: declaration.adminFields[field],
input: "textarea" as const,
previewTarget: `trust:${declaration.type}`,
...(field === "summary" && declaration.adminFields.summaryHelp
? { 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}`,
})),
};
}
export 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 pageTitle(page: string): string {
return (
(
{
home: "首页",
offerings: "业务展示",
service: "服务说明",
detail: "详情页",
inquiry: "咨询页",
success: "提交成功页",
records: "记录页",
profile: "主理人页",
} as Record<string, string>
)[page] ?? page
);
}
export function fieldTargetTitle(section: { title: string }, targetLabel: string): string {
return section.title === targetLabel ? targetLabel : `${targetLabel} · ${section.title}`;
}
@@ -0,0 +1,41 @@
import { useMemo } from "react";
import type { Offering, TemplateAdminSection, TrustContent } from "@personal-brand/api-client";
import {
applyPresentationValues,
applyStandardEntityValues,
} from "../../lib/presentation/presentation-bindings.js";
import type { PresentationValues } from "../../lib/presentation/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 "../../lib/presentation/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,128 @@
import { useMemo } from "react";
import type {
AdminTemplateContent,
BrandProfile,
Offering,
RuntimeWorkspace,
TemplateAdminSection,
TrustContent,
} from "@personal-brand/api-client";
import { projectBrandAliases, projectTrustPresentation } from "@personal-brand/api-client";
import {
presentationFieldName,
type PresentationValues,
} from "../../lib/presentation/presentation-bindings.js";
import type { RecordDraft } from "./presentation-editor-record-preview.js";
interface DraftWorkspaceInput {
previewWorkspace: RuntimeWorkspace | undefined;
previewBrand: BrandProfile;
inquiryRuntime: RuntimeWorkspace["inquiryForms"][number] | undefined;
inquiryDraft: RuntimeWorkspace["inquiryForms"][number]["fields"] | undefined;
recordDraft: RecordDraft | undefined;
selectedRecord: Offering | TrustContent | undefined;
recordSection: TemplateAdminSection | undefined;
recordPreview: { config: Record<string, unknown>; standard: Record<string, unknown> } | undefined;
templateContent: AdminTemplateContent | null | undefined;
}
export function useDraftWorkspace(input: DraftWorkspaceInput): RuntimeWorkspace | undefined {
const { previewWorkspace, previewBrand, inquiryRuntime, inquiryDraft } = input;
return useMemo(() => {
if (!previewWorkspace) return undefined;
const previewConfig = previewBrand.config ?? {};
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,
),
};
const { recordDraft, selectedRecord, recordSection, recordPreview } = input;
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,
input.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;
}, [input, previewWorkspace, previewBrand, inquiryRuntime, inquiryDraft]);
}
@@ -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,43 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Alert, Button, Card, Form, Input, Select, Table, Tag, message } from "antd";
import type { CapabilityInstallation } from "@personal-brand/api-client";
import { Button, Card, Col, Row } from "antd";
import { AppstoreOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { EmptyState } from "../../components/EmptyState.js";
import { QueryState } from "../../components/QueryState.js";
import { createApiClient } from "../../lib/api.js";
const statusLabels = { enabled: "已启用", disabled: "已停用", degraded: "降级" } as const;
import { CapabilityCard } from "./components/CapabilityCard.js";
import { useCapabilityQuery } from "./hooks/useCapabilityQueries.js";
export function CapabilitiesPage() {
const queryClient = useQueryClient();
const query = useQuery({
queryKey: ["admin", "capabilities"],
queryFn: () => createApiClient().listAdminCapabilities(),
});
const mutation = useMutation({
mutationFn: ({
key,
values,
}: {
key: string;
values: {
capabilityVersion: string;
status: CapabilityInstallation["status"];
configText?: string;
};
}) =>
createApiClient().updateAdminCapability(key, {
capabilityVersion: values.capabilityVersion,
status: values.status,
config: values.configText ? (JSON.parse(values.configText) as Record<string, unknown>) : {},
}),
onSuccess: () => {
message.success("能力配置已更新");
void queryClient.invalidateQueries({ queryKey: ["admin", "capabilities"] });
},
onError: (error) => message.error(error instanceof Error ? error.message : "更新失败"),
});
const sampleMutation = useMutation({
mutationFn: () => createApiClient().importAdminSampleContent(),
onSuccess: (result) => message.success(`已导入 ${result.counts.offerings} 项示例业务`),
onError: (error) => message.error(error instanceof Error ? error.message : "导入失败"),
});
if (query.isLoading) return <QueryState loading />;
if (query.isError) return <QueryState error={query.error} />;
const items = query.data ?? [];
return (
<div>
<AdminPageHeader title="能力插件" description="管理当前模板声明的业务能力及其运行状态。" />
<Alert
type="info"
showIcon
message="能力状态会影响公开 Runtime Workspace;停用不会删除历史数据。"
style={{ marginBottom: 16 }}
/>
<Button
onClick={() => sampleMutation.mutate()}
loading={sampleMutation.isPending}
style={{ marginBottom: 16 }}
>
导入门窗示例内容
</Button>
<Table
rowKey="capabilityKey"
dataSource={items}
locale={{ emptyText: "当前还没有品牌级能力覆盖,系统将使用模板默认能力。" }}
columns={[
{ title: "能力", dataIndex: "capabilityKey" },
{
title: "来源",
dataIndex: "source",
render: (value: CapabilityInstallation["source"]) => (
<Tag>{value === "brand" ? "品牌覆盖" : "模板默认"}</Tag>
),
},
{ title: "版本", dataIndex: "capabilityVersion" },
{
title: "状态",
dataIndex: "status",
render: (value: CapabilityInstallation["status"]) => (
<Tag
color={value === "enabled" ? "green" : value === "degraded" ? "orange" : "default"}
>
{statusLabels[value]}
</Tag>
),
},
{
title: "操作",
render: (_: unknown, record: CapabilityInstallation) => (
<CapabilityEditor
record={record}
loading={mutation.isPending}
onSubmit={(values) => mutation.mutate({ key: record.capabilityKey, values })}
/>
),
},
]}
/>
</div>
);
}
const navigate = useNavigate();
const query = useCapabilityQuery();
function CapabilityEditor({
record,
loading,
onSubmit,
}: {
record: CapabilityInstallation;
loading: boolean;
onSubmit: (values: {
capabilityVersion: string;
status: CapabilityInstallation["status"];
configText?: string;
}) => void;
}) {
const [form] = Form.useForm();
return (
<Card size="small" style={{ maxWidth: 420 }}>
<Form
form={form}
layout="inline"
initialValues={{
capabilityVersion: record.capabilityVersion,
status: record.status,
configText: record.config ? JSON.stringify(record.config) : "",
}}
onFinish={onSubmit}
>
<Form.Item name="capabilityVersion" rules={[{ required: true, message: "请输入版本" }]}>
<Input placeholder="版本" style={{ width: 100 }} />
</Form.Item>
<Form.Item name="status">
<Select
options={Object.entries(statusLabels).map(([value, label]) => ({ value, label }))}
style={{ width: 100 }}
<QueryState loading={query.isLoading} error={query.error} onRetry={() => void query.refetch()}>
<AdminPageHeader
title="能力插件"
description="以经营者视角调整模板能力的开关与展示设置;保存后进入草稿,发布后生效。"
/>
{query.data?.length ? (
<Row gutter={[16, 16]} className="admin-equal-height">
{query.data.map((capability) => (
<Col key={capability.capabilityKey} xs={24} lg={12}>
<CapabilityCard capability={capability} />
</Col>
))}
</Row>
) : (
<Card>
<EmptyState
icon={<AppstoreOutlined />}
title="当前模板没有可配置能力"
description="能力的开关由品牌当前使用的行业模板决定;更换行业模板不在本版本范围内。"
action={<Button onClick={() => navigate("/admin/publication")}>查看模板与发布</Button>}
/>
</Form.Item>
<Form.Item name="configText">
<Input placeholder="JSON 配置(可选)" style={{ width: 180 }} />
</Form.Item>
<Button type="primary" htmlType="submit" loading={loading}>
保存
</Button>
</Form>
</Card>
</Card>
)}
<p className="admin-page-header-description admin-offset-top">
技术信息仅用于排查问题,不作为运营判断依据。
</p>
</QueryState>
);
}
@@ -0,0 +1,155 @@
import { Button, Card, Input, Space, Switch, Typography } from "antd";
import { useState } from "react";
import { ErrorNote } from "../../../components/QueryState.js";
import { StatusTag } from "../../../components/StatusTag.js";
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;
}
function sameConfig(current: Record<string, unknown>, baseline: Record<string, unknown>): boolean {
const currentKeys = Object.keys(current ?? {}).sort();
const baselineKeys = Object.keys(baseline ?? {}).sort();
if (currentKeys.length !== baselineKeys.length) return false;
return currentKeys.every(
(key, index) =>
key === baselineKeys[index] && JSON.stringify(current[key]) === JSON.stringify(baseline[key]),
);
}
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 dirty = status !== capability.status || !sameConfig(config, capability.config ?? {});
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 className="admin-row-line">
{capability.displayName ?? "未命名能力"}
<CapabilityStatusTag status={status} />
<StatusTag tone="neutral" label={sourceLabels[capability.source]} />
</span>
}
extra={
<Space>
{dirty ? <StatusTag tone="warning" label="有未保存修改" /> : null}
<Button
type={dirty ? "primary" : "default"}
disabled={!dirty}
loading={mutation.isPending}
onClick={() => void save()}
>
保存草稿
</Button>
</Space>
}
>
{mutation.isError ? (
<div className="admin-offset-bottom">
<ErrorNote error={mutation.error} />
</div>
) : null}
{capability.description ? (
<p className="admin-section-description">{capability.description}</p>
) : null}
{capability.impact ? (
<p className="admin-section-description">影响:{capability.impact}</p>
) : null}
<div className="admin-field-stack">
<div>
<span className="admin-field-label">运行状态</span>
<div className="admin-offset-top-sm">
<CapabilityStatusControl
status={status}
onChange={setStatus}
disabled={mutation.isPending}
/>
</div>
<p className="admin-section-description admin-flush">保存后进入草稿,发布后生效。</p>
{status === "disabled" && capability.disablePolicy ? (
<p className="admin-section-description admin-flush admin-text-warning">
{disablePolicyLabels[capability.disablePolicy]}
</p>
) : null}
</div>
{capability.configFields?.length ? (
<div>
<span className="admin-field-label">能力设置</span>
<div className="admin-field-stack admin-offset-top-sm">
{capability.configFields.map((field) => (
<div key={field.key}>
<span className="admin-field-label">{field.label}</span>
{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,58 @@
import { Segmented, Space, Switch, Typography } from "antd";
import type { CapabilityStatus } from "../types.js";
import { StatusTag } from "../../../components/StatusTag.js";
import type { StatusTone } from "../../../components/StatusTag.js";
const statusLabels: Record<CapabilityStatus, string> = {
enabled: "启用",
disabled: "停用",
degraded: "降级",
};
const statusTones: Record<CapabilityStatus, StatusTone> = {
enabled: "success",
disabled: "neutral",
degraded: "warning",
};
export function CapabilityStatusTag({ status }: { status: CapabilityStatus }) {
return <StatusTag tone={statusTones[status]} label={statusLabels[status]} />;
}
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")
);
}
@@ -1,20 +1,15 @@
import {
Badge,
Button,
Card,
Descriptions,
Drawer,
Select,
Space,
Table,
Tag,
message,
Input,
} from "antd";
import { Badge, Button, Descriptions, Drawer, Select, Space, Table, message, Input } from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { AdminBooking, InquirySubmission } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import { useState } from "react";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { EmptyState } from "../../components/EmptyState.js";
import { AdminSection } from "../../components/AdminSection.js";
import { ErrorNote } from "../../components/QueryState.js";
import { ListSkeleton, TableSkeleton } from "../../components/TableSkeleton.js";
import { StatusTag } from "../../components/StatusTag.js";
import type { StatusTone } from "../../components/StatusTag.js";
const statuses = ["received", "contacting", "confirmed", "completed", "cancelled"] as const;
const labels: Record<string, string> = {
@@ -41,6 +36,20 @@ const inquiryLabels: Record<string, string> = {
closed: "已关闭",
};
const statusTones: Record<string, StatusTone> = {
received: "info",
new: "info",
contacting: "warning",
reviewing: "warning",
confirmed: "success",
replied: "success",
qualified: "success",
converted: "success",
completed: "success",
cancelled: "error",
closed: "neutral",
};
export function InquiriesPage() {
const client = createApiClient();
const queryClient = useQueryClient();
@@ -94,192 +103,222 @@ export function InquiriesPage() {
onError: (error) => message.error(error instanceof Error ? error.message : "更新失败,请重试"),
});
return (
<Card
title="咨询记录"
extra={
<Space>
<Select
allowClear
placeholder="全部状态"
style={{ width: 130 }}
value={status}
onChange={setStatus}
options={statuses.map((value) => ({ value, label: labels[value] }))}
/>
<Badge
count={
query.data?.filter((item) => !(item as AdminBooking & { isRead?: boolean }).isRead)
.length ?? 0
}
showZero
/>
</Space>
}
>
<Table
rowKey="id"
loading={query.isLoading}
dataSource={query.data ?? []}
columns={[
{
title: "编号",
dataIndex: "bookingNo",
render: (value: string, item: AdminBooking) => (
<Button type="link" onClick={() => setSelectedId(item.id)}>
{value}
</Button>
),
},
{ title: "联系人", dataIndex: "customerName" },
{
title: "提交时间",
dataIndex: "createdAt",
render: (value: string) => new Date(value).toLocaleString("zh-CN"),
},
{
title: "状态",
dataIndex: "status",
render: (value: string) => <Tag>{labels[value] ?? value}</Tag>,
},
{
title: "操作",
render: (_: unknown, item: AdminBooking) => (
<Space>
<Select
size="small"
value={item.status}
onChange={(value) => update.mutate({ id: item.id, value: value as never })}
options={statuses.map((value) => ({ value, label: labels[value] }))}
/>
<Button size="small" onClick={() => read.mutate(item.id)}>
标记已读
</Button>
</Space>
),
},
]}
/>
<Drawer
title="咨询详情"
open={Boolean(selectedId)}
onClose={() => setSelectedId(undefined)}
loading={detail.isLoading}
width={520}
<>
<AdminPageHeader title="咨询记录" description="查看访客提交的咨询和预约,并跟进处理进度。" />
<AdminSection
title="预约咨询"
extra={
<Space>
<Select
allowClear
placeholder="全部状态"
className="admin-field-w-md"
value={status}
onChange={setStatus}
options={statuses.map((value) => ({ value, label: labels[value] }))}
/>
<Badge
count={
query.data?.filter((item) => !(item as AdminBooking & { isRead?: boolean }).isRead)
.length ?? 0
}
showZero
/>
</Space>
}
>
{detail.data && (
<Descriptions column={1} bordered size="small">
<Descriptions.Item label="编号">{detail.data.bookingNo}</Descriptions.Item>
<Descriptions.Item label="联系人">{detail.data.customerName}</Descriptions.Item>
<Descriptions.Item label="状态">
{labels[detail.data.status] ?? detail.data.status}
</Descriptions.Item>
<Descriptions.Item label="提交时间">
{new Date(detail.data.createdAt).toLocaleString("zh-CN")}
</Descriptions.Item>
<Descriptions.Item label="管理员备注">
{detail.data.adminNote || "暂无"}
</Descriptions.Item>
</Descriptions>
{query.isLoading && !query.data ? (
<TableSkeleton />
) : (
<Table
rowKey="id"
locale={{
emptyText: (
<EmptyState
compact
title="还没有预约咨询"
description="访客在小程序提交预约后,会出现在这里。"
/>
),
}}
dataSource={query.data ?? []}
columns={[
{
title: "编号",
dataIndex: "bookingNo",
render: (value: string, item: AdminBooking) => (
<Button type="link" onClick={() => setSelectedId(item.id)}>
{value}
</Button>
),
},
{ title: "联系人", dataIndex: "customerName" },
{
title: "提交时间",
dataIndex: "createdAt",
render: (value: string) => new Date(value).toLocaleString("zh-CN"),
},
{
title: "状态",
dataIndex: "status",
render: (value: string) => (
<StatusTag
tone={statusTones[value] ?? "neutral"}
label={labels[value] ?? value}
/>
),
},
{
title: "操作",
render: (_: unknown, item: AdminBooking) => (
<Space>
<Select
size="small"
value={item.status}
onChange={(value) => update.mutate({ id: item.id, value: value as never })}
options={statuses.map((value) => ({ value, label: labels[value] }))}
/>
<Button type="link" size="small" onClick={() => read.mutate(item.id)}>
标记已读
</Button>
</Space>
),
},
]}
/>
)}
</Drawer>
<Card
<Drawer
title="咨询详情"
open={Boolean(selectedId)}
onClose={() => setSelectedId(undefined)}
loading={detail.isLoading}
width={520}
>
{detail.data && (
<Descriptions className="admin-descriptions" column={1} size="small">
<Descriptions.Item label="编号">{detail.data.bookingNo}</Descriptions.Item>
<Descriptions.Item label="联系人">{detail.data.customerName}</Descriptions.Item>
<Descriptions.Item label="状态">
{labels[detail.data.status] ?? detail.data.status}
</Descriptions.Item>
<Descriptions.Item label="提交时间">
{new Date(detail.data.createdAt).toLocaleString("zh-CN")}
</Descriptions.Item>
<Descriptions.Item label="管理员备注">
{detail.data.adminNote || "暂无"}
</Descriptions.Item>
</Descriptions>
)}
</Drawer>
</AdminSection>
<AdminSection
title={`动态咨询提交${submissions.data ? `(${submissions.data.length})` : ""}`}
style={{ marginTop: 24 }}
description="按模板表单提交的咨询记录,字段随表单配置变化。"
extra={
<Button onClick={() => void submissions.refetch()} loading={submissions.isFetching}>
刷新提交记录
</Button>
}
>
{submissions.isError && (
<Card type="inner" style={{ marginBottom: 16 }}>
动态咨询提交加载失败:
{submissions.error instanceof Error ? submissions.error.message : "未知错误"}
<Button type="link" onClick={() => void submissions.refetch()}>
重试
</Button>
</Card>
)}
<Space style={{ marginBottom: 12 }}>
{submissions.isError ? (
<ErrorNote error={submissions.error} onRetry={() => void submissions.refetch()} />
) : null}
<Space
className={`admin-offset-bottom-sm ${submissions.isError ? "admin-offset-top" : ""}`}
>
<Select
allowClear
placeholder="动态咨询状态"
style={{ width: 140 }}
className="admin-field-w-md"
value={submissionStatus}
onChange={setSubmissionStatus}
options={inquiryStatuses.map((value) => ({ value, label: inquiryLabels[value] }))}
/>
</Space>
<Table<InquirySubmission>
rowKey="id"
loading={submissions.isLoading}
dataSource={(submissions.data ?? []).filter(
(item) => !submissionStatus || item.status === submissionStatus,
)}
locale={{ emptyText: submissions.isLoading ? "加载中" : "暂无动态咨询提交" }}
columns={[
{ title: "表单", dataIndex: ["inquiryForm", "name"] },
{
title: "来源业务",
dataIndex: ["offering", "name"],
render: (value: string | null | undefined) => value || "品牌咨询",
},
{
title: "状态",
dataIndex: "status",
render: (value: InquirySubmission["status"]) => (
<Tag>{inquiryLabels[value] ?? value}</Tag>
{submissions.isLoading && !submissions.data ? (
<ListSkeleton rows={3} />
) : (
<Table<InquirySubmission>
rowKey="id"
dataSource={(submissions.data ?? []).filter(
(item) => !submissionStatus || item.status === submissionStatus,
)}
locale={{
emptyText: (
<EmptyState
compact
title="暂无动态咨询提交"
description="按模板表单提交的咨询会汇总在这里。"
/>
),
},
{ title: "版本", dataIndex: "formVersion", render: (value) => `v${value}` },
{
title: "提交时间",
dataIndex: "createdAt",
render: (value: string) => new Date(value).toLocaleString("zh-CN"),
},
{
title: "内容",
dataIndex: "values",
render: (value: Record<string, unknown>) => {
const entries = Object.entries(value ?? {});
return entries.length
? entries.map(([key, item]) => `${key}: ${String(item)}`).join(";")
: "暂无内容";
}}
columns={[
{ title: "表单", dataIndex: ["inquiryForm", "name"] },
{
title: "来源业务",
dataIndex: ["offering", "name"],
render: (value: string | null | undefined) => value || "品牌咨询",
},
},
{
title: "跟进",
render: (_: unknown, item: InquirySubmission) => (
<Space>
<Button size="small" onClick={() => setSelectedSubmission(item)}>
查看
</Button>
<Select
size="small"
value={item.status}
options={inquiryStatuses.map((value) => ({
value,
label: inquiryLabels[value],
}))}
onChange={(value) => updateSubmission.mutate({ id: item.id, status: value })}
{
title: "状态",
dataIndex: "status",
render: (value: InquirySubmission["status"]) => (
<StatusTag
tone={statusTones[value] ?? "neutral"}
label={inquiryLabels[value] ?? value}
/>
<Input
size="small"
placeholder="备注"
defaultValue={item.adminNote ?? ""}
onPressEnter={(event) =>
updateSubmission.mutate({
id: item.id,
status: item.status,
adminNote: event.currentTarget.value,
})
}
/>
</Space>
),
},
]}
/>
),
},
{ title: "版本", dataIndex: "formVersion", render: (value) => `v${value}` },
{
title: "提交时间",
dataIndex: "createdAt",
render: (value: string) => new Date(value).toLocaleString("zh-CN"),
},
{
title: "内容",
dataIndex: "values",
render: (value: Record<string, unknown>) => {
const entries = Object.entries(value ?? {});
return entries.length
? entries.map(([key, item]) => `${key}: ${String(item)}`).join(";")
: "暂无内容";
},
},
{
title: "跟进",
render: (_: unknown, item: InquirySubmission) => (
<Space>
<Button type="link" size="small" onClick={() => setSelectedSubmission(item)}>
查看
</Button>
<Select
size="small"
value={item.status}
options={inquiryStatuses.map((value) => ({
value,
label: inquiryLabels[value],
}))}
onChange={(value) => updateSubmission.mutate({ id: item.id, status: value })}
/>
<Input
size="small"
placeholder="备注"
defaultValue={item.adminNote ?? ""}
onPressEnter={(event) =>
updateSubmission.mutate({
id: item.id,
status: item.status,
adminNote: event.currentTarget.value,
})
}
/>
</Space>
),
},
]}
/>
)}
<Drawer
title="动态咨询详情"
open={Boolean(selectedSubmission)}
@@ -287,7 +326,7 @@ export function InquiriesPage() {
width={520}
>
{selectedSubmission && (
<Descriptions column={1} bordered size="small">
<Descriptions className="admin-descriptions" column={1} size="small">
<Descriptions.Item label="表单">
{selectedSubmission.inquiryForm?.name || "品牌咨询"}
</Descriptions.Item>
@@ -314,7 +353,7 @@ export function InquiriesPage() {
</Descriptions>
)}
</Drawer>
</Card>
</Card>
</AdminSection>
</>
);
}
@@ -1,9 +1,11 @@
import { Button, Card, Col, List, Progress, Row, Space, Statistic, Tag, Typography } from "antd";
import { Button, Card, Col, Progress, Row } from "antd";
import { useQueries, useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { QueryState } from "../../components/QueryState.js";
import { MetricCard } from "../../components/MetricCard.js";
import { StatusTag } from "../../components/StatusTag.js";
export function OverviewPage() {
const navigate = useNavigate();
@@ -82,41 +84,32 @@ export function OverviewPage() {
title="品牌概览"
description="从这里检查品牌表达、信任内容和业务承接是否完整。"
/>
<Space direction="vertical" size={24} style={{ width: "100%" }}>
<div className="admin-stack">
<Card>
<Typography.Title level={3} style={{ marginTop: 0 }}>
{brand?.name || "未命名品牌"}
</Typography.Title>
<Typography.Paragraph type="secondary">
{brand?.tagline || "还没有设置一句话定位"}
</Typography.Paragraph>
<Tag color="blue">
当前模板:{workspace?.templateContent?.displayName ?? "尚未安装模板"}
</Tag>
<h2 className="admin-brand-title">{brand?.name || "未命名品牌"}</h2>
<p className="admin-brand-tagline">{brand?.tagline || "还没有设置一句话定位"}</p>
<StatusTag
tone="info"
label={`当前模板:${workspace?.templateContent?.displayName ?? "尚未安装模板"}`}
/>
</Card>
<Row gutter={[16, 16]}>
<Col xs={24} sm={12} lg={6}>
<Card>
<Statistic
title="信任证明"
value={trust?.filter((item) => item.isPublished).length ?? 0}
suffix="条已发布"
/>
</Card>
<Col xs={24} sm={8}>
<MetricCard
label="信任证明"
value={trust?.filter((item) => item.isPublished).length ?? 0}
suffix="条已发布"
/>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card>
<Statistic
title="业务展示内容"
value={offerings?.filter((item) => item.isEnabled).length ?? 0}
suffix="项公开"
/>
</Card>
<Col xs={24} sm={8}>
<MetricCard
label="业务展示内容"
value={offerings?.filter((item) => item.isEnabled).length ?? 0}
suffix="项公开"
/>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card>
<Statistic title="咨询提交" value={submissions?.length ?? 0} suffix="条" />
</Card>
<Col xs={24} sm={8}>
<MetricCard label="咨询提交" value={submissions?.length ?? 0} suffix="条" />
</Col>
</Row>
<Row gutter={[16, 16]}>
@@ -133,63 +126,57 @@ export function OverviewPage() {
percent={completionPercent}
status={readiness.data?.ready ? "success" : "active"}
/>
<Typography.Paragraph type="secondary">
<p className="admin-section-description admin-offset-top-sm admin-offset-bottom">
{readiness.data?.ready
? "当前草稿已满足发布条件,可以进入发布页上线。"
: `还有 ${incompleteChecks.length} 项需要完善,完成后才能发布。`}
</Typography.Paragraph>
</p>
{incompleteChecks.length > 0 && (
<List
size="small"
dataSource={incompleteChecks.slice(0, 4)}
renderItem={(item) => (
<List.Item
actions={[
<Button
key={item.key}
type="link"
size="small"
onClick={() => navigate(item.destination ?? "/admin/publication")}
>
去处理
</Button>,
]}
>
{item.label}
</List.Item>
)}
/>
<ul className="admin-list">
{incompleteChecks.slice(0, 4).map((item) => (
<li key={item.key} className="admin-row">
<span className="admin-row-title">{item.label}</span>
<Button
type="link"
size="small"
onClick={() => navigate(item.destination ?? "/admin/publication")}
>
去处理
</Button>
</li>
))}
</ul>
)}
</Card>
</Col>
<Col xs={24} lg={12}>
<Card title="品牌内容检查">
<List
dataSource={checks}
renderItem={(item) => (
<List.Item>
<Space>
<Tag color={item.passed ? "success" : "default"}>
{item.passed ? "已完成" : "待完善"}
</Tag>
<span>{item.label}</span>
{!item.passed && (
<Button
type="link"
size="small"
onClick={() => navigate(item.destination ?? "/admin/publication")}
>
去处理
</Button>
)}
</Space>
</List.Item>
)}
/>
<ul className="admin-list">
{checks.map((item) => (
<li key={item.key} className="admin-row">
<div className="admin-row-line">
<StatusTag
tone={item.passed ? "success" : "neutral"}
label={item.passed ? "已完成" : "待完善"}
/>
<span className="admin-row-title">{item.label}</span>
</div>
{!item.passed ? (
<Button
type="link"
size="small"
onClick={() => navigate(item.destination ?? "/admin/publication")}
>
去处理
</Button>
) : null}
</li>
))}
</ul>
</Card>
</Col>
</Row>
</Space>
</div>
</QueryState>
);
}
@@ -0,0 +1,163 @@
import { useEffect, useRef } from "react";
import { Button, Card, Collapse, Flex, Space, Tooltip, Typography } from "antd";
import type { MiniAppReleaseTask } from "@personal-brand/api-client";
import { ErrorNote } from "../../components/QueryState.js";
import { StatusTag } from "../../components/StatusTag.js";
import type { StatusTone } from "../../components/StatusTag.js";
type ReleaseStatus = MiniAppReleaseTask["status"];
const STALE_BUILDING_MS = 15 * 60 * 1000;
function isStaleBuilding(task: MiniAppReleaseTask): boolean {
if (task.buildStatus !== "building") return false;
const updatedAt = new Date(task.updatedAt).getTime();
return !Number.isNaN(updatedAt) && Date.now() - updatedAt >= STALE_BUILDING_MS;
}
const statusView: Record<ReleaseStatus, { label: string; tone: StatusTone; hint: string }> = {
built: { label: "待上传", tone: "neutral", hint: "代码已构建,可上传到微信。" },
uploaded: { label: "已上传微信", tone: "info", hint: "请在微信后台上传体验版并提交审核。" },
under_review: {
label: "审核中",
tone: "warning",
hint: "等待微信审核结果,通过后回到本页标记。",
},
approved: { label: "审核通过", tone: "success", hint: "审核已通过,确认无误后标记为已发布。" },
published: { label: "已发布", tone: "success", hint: "该版本已发布,可继续编辑内容后再次上传。" },
rejected: { label: "已驳回", tone: "error", hint: "微信驳回后需修改内容并重新构建上传。" },
failed: { label: "失败", tone: "error", hint: "上次构建或上传失败,可直接重试。" },
};
function formatTime(value: string): string {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
return date.toLocaleString("zh-CN", { hour12: false });
}
function formatLogTime(value: string): string {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return "";
return date.toLocaleTimeString("zh-CN", { hour12: false });
}
export function MiniAppReleaseCard({
task,
uploading,
onUpload,
onStatusChange,
}: {
task: MiniAppReleaseTask;
uploading: boolean;
onUpload: () => void;
onStatusChange: (status: ReleaseStatus) => void;
}) {
const logRef = useRef<HTMLPreElement>(null);
const logs = task.buildLogs ?? [];
const status = statusView[task.status];
const building = task.buildStatus === "building";
const staleBuilding = isStaleBuilding(task);
useEffect(() => {
if (!building) return;
const node = logRef.current;
if (node) node.scrollTop = node.scrollHeight;
}, [building, logs.length]);
const actions = (
<Space wrap>
{(task.status === "built" || task.status === "failed" || staleBuilding) && (
<Button
type={task.status === "built" && !staleBuilding ? "primary" : "default"}
size="small"
loading={uploading}
onClick={onUpload}
>
{task.status === "built" && !staleBuilding ? "上传微信" : "重试上传微信"}
</Button>
)}
{task.status === "uploaded" && (
<Button size="small" onClick={() => onStatusChange("under_review")}>
标记提交审核
</Button>
)}
{task.status === "under_review" && (
<>
<Button size="small" onClick={() => onStatusChange("approved")}>
审核通过
</Button>
<Button size="small" danger onClick={() => onStatusChange("rejected")}>
审核驳回
</Button>
</>
)}
{task.status === "approved" && (
<Button size="small" type="primary" onClick={() => onStatusChange("published")}>
标记已发布
</Button>
)}
</Space>
);
return (
<Card size="small" styles={{ body: { padding: 16 } }}>
<Flex justify="space-between" align="flex-start" gap={12} wrap>
<Space direction="vertical" size={4}>
<Space wrap size={8} align="center">
<Typography.Text strong>品牌内容 v{task.version}</Typography.Text>
<StatusTag label={status.label} tone={status.tone} />
{building && (
<StatusTag tone="warning" label={staleBuilding ? "构建已中断" : "构建中"} />
)}
{task.weappUploadId && (
<Typography.Text type="secondary">微信版本 {task.weappUploadId}</Typography.Text>
)}
</Space>
<span className="admin-text-xs">
{staleBuilding ? "超过 15 分钟没有新的构建输出,可能已中断;可直接重试。" : status.hint}
</span>
<Tooltip title={`创建于 ${formatTime(task.createdAt)}`}>
<span className="admin-text-xs-quiet">更新于 {formatTime(task.updatedAt)}</span>
</Tooltip>
</Space>
{actions}
</Flex>
{task.error && (
<div className="admin-offset-top-md">
<ErrorNote error={new Error(task.error)} />
</div>
)}
{logs.length > 0 && (
<Collapse
ghost
size="small"
className="admin-offset-top-sm"
{...(building || task.buildStatus === "failed" ? { defaultActiveKey: ["logs"] } : {})}
items={[
{
key: "logs",
label: <span className="admin-text-xs">构建日志({logs.length} 行)</span>,
children: (
<pre ref={logRef} className="admin-log">
{logs.map((log, index) => (
<div
key={`${log.at}-${index}`}
className="admin-log__line"
data-stream={log.stream}
>
<span className="admin-log__time">{formatLogTime(log.at)}</span>
{" "}
{log.message}
</div>
))}
</pre>
),
},
]}
/>
)}
</Card>
);
}
@@ -0,0 +1,112 @@
import { Alert, Button, Form, Input, Space } from "antd";
import type { FormInstance } from "antd";
import type { MiniAppReleaseSettings } from "@personal-brand/api-client";
import { AdminSection } from "../../components/AdminSection.js";
import { MutationError } from "../../components/QueryState.js";
import { StatusTag } from "../../components/StatusTag.js";
export type MiniAppSettingsValues = {
appId: string;
apiBaseUrl: string;
privateKey?: string;
};
interface MiniAppSettingsTabProps {
form: FormInstance<MiniAppSettingsValues>;
settings: MiniAppReleaseSettings | undefined;
saving: boolean;
error?: unknown;
onSave: (values: MiniAppSettingsValues) => void;
}
export function MiniAppSettingsTab({
form,
settings,
saving,
error,
onSave,
}: MiniAppSettingsTabProps) {
return (
<div className="admin-stack admin-stack-lg">
<AdminSection
title="小程序上传配置"
description="AppID 用于服务端调用微信官方上传工具;上传私钥保存前会使用 AES-256-GCM 加密。"
>
{settings?.buildError ? (
<Alert
type="warning"
showIcon
className="admin-offset-bottom"
message="小程序构建参数未就绪"
description={settings.buildError}
/>
) : (
<Alert
type="info"
showIcon
className="admin-offset-bottom"
message={`请求域名 ${settings?.requestDomain ?? "未确认"}`}
description="该域名在构建时写入小程序包,必须与微信后台“开发设置 → 服务器域名 → request 合法域名”一致;不一致会导致小程序打开即加载失败。"
/>
)}
<Form form={form} layout="vertical" onFinish={onSave}>
<Form.Item
name="appId"
label="微信 AppID"
rules={[{ required: true, message: "请输入微信 AppID" }]}
>
<Input maxLength={100} />
</Form.Item>
<Form.Item
name="apiBaseUrl"
label="小程序请求地址"
rules={[
{ required: true, message: "请输入小程序请求地址" },
{
validator: (_rule, value: string) =>
!value || /^https:\/\/[^/]+/.test(value)
? Promise.resolve()
: Promise.reject(
new Error(
"公网地址必须以 https:// 开头,例如 https://wechat.app.que01.top/api",
),
),
},
]}
extra="构建时写入小程序包,必须与微信后台“开发设置 → 服务器域名 → request 合法域名”一致。修改后需重新构建并上传代码才生效。"
>
<Input maxLength={200} placeholder="https://wechat.app.que01.top/api" />
</Form.Item>
<Form.Item
name="privateKey"
label="上传私钥"
help={
settings?.hasStoredCredentials
? "已加密保存。留空保持现有私钥,输入新值可替换。"
: "粘贴微信开发者工具导出的 private.<appid>.key 全文,必须保留换行。"
}
>
<Input.TextArea
rows={5}
autoComplete="off"
spellCheck={false}
placeholder={"-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"}
className="admin-code-input"
/>
</Form.Item>
<Space>
<Button type="primary" loading={saving} htmlType="submit">
保存上传配置
</Button>
{settings?.hasStoredCredentials ? (
<StatusTag tone="success" label="已加密保存上传凭据" />
) : (
<StatusTag tone="warning" label="未配置上传私钥" />
)}
</Space>
<MutationError error={error} />
</Form>
</AdminSection>
</div>
);
}
@@ -1,24 +1,31 @@
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useQueryClient } from "@tanstack/react-query";
import {
Alert,
Button,
Divider,
Empty,
Input,
Modal,
Form,
Select,
Space,
Spin,
Tag,
Tabs,
Typography,
message,
} from "antd";
import type { BrandTemplateKey } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { MutationError, QueryState } from "../../components/QueryState.js";
import { AdminSection } from "../../components/AdminSection.js";
import { EmptyState } from "../../components/EmptyState.js";
import { ErrorNote, MutationError, QueryState } from "../../components/QueryState.js";
import { StatusTag, statusLabel } from "../../components/StatusTag.js";
import { MiniAppReleaseCard } from "./MiniAppReleaseCard.js";
import { MiniAppSettingsTab, type MiniAppSettingsValues } from "./MiniAppSettingsTab.js";
import { usePublicationQueries } from "./use-publication-queries.js";
import { usePublicationMutations } from "./use-publication-mutations.js";
const client = createApiClient();
@@ -39,38 +46,32 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
const [confirmAction, setConfirmAction] = useState<"publish" | "revoke" | null>(null);
const [rollbackVersion, setRollbackVersion] = useState<number | null>(null);
const [note, setNote] = useState("");
const brand = useQuery({
queryKey: ["publication-brand"],
queryFn: () => client.getAdminBrand(),
});
const workspace = useQuery({
queryKey: ["publication-workspace"],
queryFn: () => client.getAdminWorkspace(),
});
const catalog = useQuery({
queryKey: ["publication-catalog"],
queryFn: () => client.listPublicTemplates(),
});
const sample = useQuery({
queryKey: ["publication-sample"],
queryFn: () => client.previewAdminSampleContent(),
enabled: Boolean(workspace.data),
});
const readiness = useQuery({
queryKey: ["publication-readiness"],
queryFn: () => client.getAdminReleaseReadiness(),
});
const releases = useQuery({
queryKey: ["publication-releases"],
queryFn: () => client.listAdminReleases(),
});
const [activeTab, setActiveTab] = useState("content");
const [miniAppSettingsForm] = Form.useForm<MiniAppSettingsValues>();
const queries = usePublicationQueries(miniAppSettingsForm);
const {
brand,
workspace,
catalog,
sample,
readiness,
releases,
miniAppReleases,
miniAppSettings,
templatePreview,
loading,
error,
retry,
} = queries;
const refresh = () => {
for (const key of [
"publication-brand",
"publication-workspace",
"publication-sample",
"publication-readiness",
"publication-template-preview",
"publication-releases",
"publication-miniapp-releases",
"admin-shell-brand",
"admin-workspace",
"public-runtime-workspace",
@@ -78,83 +79,42 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
void queryClient.invalidateQueries({ queryKey: [key] });
}
};
const install = useMutation({
mutationFn: (key: BrandTemplateKey) => client.installAdminTemplate(key),
onSuccess: () => {
setIndustryTarget(null);
message.success("行业模板已安装");
refresh();
},
const mutations = usePublicationMutations({
refresh,
brandConfig: brand.data?.config,
onInstallClose: () => setIndustryTarget(null),
onPublishClose: () => setConfirmAction(null),
onNoteClear: () => setNote(""),
onRollbackClose: () => setRollbackVersion(null),
});
const selectVisual = useMutation({
mutationFn: (key: string) =>
client.updateAdminBrand({
config: { ...(brand.data?.config ?? {}), visualTemplateKey: key },
}),
onSuccess: () => {
message.success("视觉模板已保存到草稿");
refresh();
},
});
const importSample = useMutation({
mutationFn: () => client.importAdminSampleContent(),
onSuccess: ({ counts }) => {
message.success(
counts.inquiryForms
? "示例内容和客户咨询表单已导入草稿"
: "示例内容已导入草稿,现有客户咨询表单已保留",
);
refresh();
},
});
const publish = useMutation({
mutationFn: () => client.publishAdminRelease(note.trim() || undefined),
onSuccess: () => {
setConfirmAction(null);
setNote("");
message.success("品牌已发布");
refresh();
},
});
const revoke = useMutation({
mutationFn: () => client.revokeAdminRelease(),
onSuccess: () => {
setConfirmAction(null);
message.success("品牌已撤回,小程序将显示未发布状态");
refresh();
},
});
const rollback = useMutation({
mutationFn: (version: number) => client.rollbackAdminRelease(version),
onSuccess: () => {
setRollbackVersion(null);
message.success("历史版本已重新发布");
refresh();
},
});
const loading = [brand, workspace, catalog, readiness, releases].some((query) => query.isLoading);
const error = [brand, workspace, catalog, readiness, releases].find(
(query) => query.isError,
)?.error;
const retry = () => {
void brand.refetch();
void workspace.refetch();
void catalog.refetch();
void readiness.refetch();
void releases.refetch();
};
const {
install,
upgradeTemplate,
rollbackTemplate,
selectVisual,
importSample,
publish,
revoke,
rollback,
uploadLatestMiniAppRelease,
saveMiniAppSettings,
uploadMiniAppRelease,
updateMiniAppStatus,
} = mutations;
const industryKey =
workspace.data?.installations[0]?.templateKey ??
workspace.data?.brand?.templateKey ??
brand.data?.templateKey ??
"personal";
const visuals = (catalog.data?.visuals ?? []).filter((item) =>
item.supportedIndustryTemplates.includes(industryKey),
catalog.data?.industries[0]?.key ??
null;
const visuals = (catalog.data?.visuals ?? []).filter(
(item) =>
typeof industryKey === "string" && item.supportedIndustryTemplates.includes(industryKey),
);
const visualKey =
typeof brand.data?.config?.visualTemplateKey === "string"
? brand.data.config.visualTemplateKey
: "linjing-editorial";
: (visuals[0]?.key ?? null);
const currentRelease = releases.data?.find((item) => item.status === "published");
const publishedHistory = (releases.data ?? []).filter(
(item) => item.status === "published" || item.status === "superseded",
@@ -166,187 +126,428 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
isEnabled: boolean;
}>;
const contentTab = null;
const miniAppSettingsTab = (
<div className="admin-stack admin-stack-lg">
<AdminSection
title="小程序上传配置"
description="AppID 用于服务端调用微信官方上传工具;上传私钥保存前会使用 AES-256-GCM 加密。"
>
{miniAppSettings.data?.buildError ? (
<Alert
type="warning"
showIcon
className="admin-offset-bottom"
message="小程序构建参数未就绪"
description={miniAppSettings.data.buildError}
/>
) : (
<Alert
type="info"
showIcon
className="admin-offset-bottom"
message={`请求域名 ${miniAppSettings.data?.requestDomain ?? "未确认"}`}
description="该域名在构建时写入小程序包,必须与微信后台“开发设置 → 服务器域名 → request 合法域名”一致;不一致会导致小程序打开即加载失败。"
/>
)}
<Form
form={miniAppSettingsForm}
layout="vertical"
onFinish={(values) => saveMiniAppSettings.mutate(values)}
>
<Form.Item
name="appId"
label="微信 AppID"
rules={[{ required: true, message: "请输入微信 AppID" }]}
>
<Input maxLength={100} />
</Form.Item>
<Form.Item
name="apiBaseUrl"
label="小程序请求地址"
rules={[
{ required: true, message: "请输入小程序请求地址" },
{
validator: (_rule, value: string) =>
!value || /^https:\/\/[^/]+/.test(value)
? Promise.resolve()
: Promise.reject(
new Error(
"公网地址必须以 https:// 开头,例如 https://wechat.app.que01.top/api",
),
),
},
]}
extra="构建时写入小程序包,必须与微信后台“开发设置 → 服务器域名 → request 合法域名”一致。修改后需重新构建并上传代码才生效。"
>
<Input maxLength={200} placeholder="https://wechat.app.que01.top/api" />
</Form.Item>
<Form.Item
name="privateKey"
label="上传私钥"
help={
miniAppSettings.data?.hasStoredCredentials
? "已加密保存。留空保持现有私钥,输入新值可替换。"
: "粘贴微信开发者工具导出的 private.<appid>.key 全文,必须保留换行。"
}
>
<Input.TextArea
rows={5}
autoComplete="off"
spellCheck={false}
placeholder={"-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"}
className="admin-code-input"
/>
</Form.Item>
<Space>
<Button type="primary" loading={saveMiniAppSettings.isPending} htmlType="submit">
保存上传配置
</Button>
{miniAppSettings.data?.hasStoredCredentials ? (
<StatusTag tone="success" label="已加密保存上传凭据" />
) : (
<StatusTag tone="warning" label="未配置上传私钥" />
)}
</Space>
<MutationError error={saveMiniAppSettings.error} />
</Form>
</AdminSection>
</div>
);
return (
<QueryState loading={loading} error={error} onRetry={retry}>
<AdminPageHeader
title="配置与发布"
description="编辑内容不会立即影响小程序;确认后统一发布当前品牌。"
/>
<Space direction="vertical" size={24} style={{ width: "100%" }}>
<section>
<Typography.Title level={4}>1. 选择表达方式</Typography.Title>
<Space wrap>
<Select
aria-label="行业模板"
style={{ width: 220 }}
value={industryKey}
disabled={!canManageTemplate || Boolean(workspace.data?.installations.length)}
options={(catalog.data?.industries ?? []).map((item) => ({
value: item.key,
label: item.name,
}))}
onChange={(key: BrandTemplateKey) => setIndustryTarget(key)}
/>
<Select
aria-label="视觉模板"
style={{ width: 220 }}
value={visualKey}
disabled={!canManageTemplate}
loading={selectVisual.isPending}
options={visuals.map((item) => ({ value: item.key, label: item.name }))}
onChange={(key) => selectVisual.mutate(key)}
/>
{canManageTemplate && (
<Button onClick={() => navigate("/admin/workspace")}>高级模板设置</Button>
)}
</Space>
{workspace.data?.installations.length ? (
<Typography.Paragraph type="secondary" style={{ marginTop: 8 }}>
当前品牌已安装主模板。模板版本与升级在高级设置中管理。
</Typography.Paragraph>
) : null}
<MutationError error={install.error || selectVisual.error} />
<Divider />
<Space wrap>
<Typography.Text>示例内容</Typography.Text>
{sample.isLoading && <Spin size="small" />}
{sample.data && (
<Tag color={sample.data.alreadyImported ? "green" : "blue"}>
{sample.data.alreadyImported ? "已导入" : "可导入"}
</Tag>
)}
<Button
disabled={!canManageTemplate || !sample.data || sample.data.alreadyImported}
loading={importSample.isPending}
onClick={() => importSample.mutate()}
>
导入示例内容
</Button>
{sample.isError && <Button onClick={() => void sample.refetch()}>重试</Button>}
</Space>
{sample.isError && (
<Alert
type="error"
message={sample.error instanceof Error ? sample.error.message : "示例内容加载失败"}
showIcon
style={{ marginTop: 8 }}
/>
)}
{sample.data && !sample.data.alreadyImported && (
<Typography.Paragraph type="secondary" style={{ marginTop: 8 }}>
将向草稿添加{" "}
{Object.entries(sample.data.counts)
.map(([key, count]) => `${key} ${count} 项`)
.join("、")}
;发布前请替换示例文案和图片。
</Typography.Paragraph>
)}
<MutationError error={importSample.error} />
</section>
<section>
<Typography.Title level={4}>2. 核对草稿内容</Typography.Title>
<Typography.Paragraph type="secondary">
此处核对的是待发布内容,不是小程序视觉预览。
</Typography.Paragraph>
<Space direction="vertical" style={{ width: "100%" }}>
<Typography.Text strong>{brand.data?.name || "未命名品牌"}</Typography.Text>
<Typography.Text>{brand.data?.tagline || "尚未填写品牌定位"}</Typography.Text>
<Typography.Text>
已启用业务项:{draftOfferings.map((item) => item.name).join("、") || "无"}
</Typography.Text>
<Typography.Text>
已启用咨询表单:
{draftForms
.filter((item) => item.isEnabled)
.map((item) => item.name)
.join("、") || "无"}
</Typography.Text>
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
items={[
{
key: "content",
label: "内容发布",
children: contentTab,
},
{ key: "miniapp", label: "小程序发布", children: null },
{
key: "settings",
label: "小程序配置",
children:
activeTab === "settings" ? (
<MiniAppSettingsTab
form={miniAppSettingsForm}
settings={miniAppSettings.data}
saving={saveMiniAppSettings.isPending}
error={saveMiniAppSettings.error}
onSave={(values) => saveMiniAppSettings.mutate(values)}
/>
) : null,
},
]}
/>
{activeTab === "content" && (
<div className="admin-stack">
<AdminSection
title="选择表达方式"
description="行业模板决定内容结构,视觉模板决定小程序的排版风格。"
>
<Space wrap>
<Select
aria-label="行业模板"
className="admin-field-w-xl"
value={industryKey}
disabled={!canManageTemplate || Boolean(workspace.data?.installations.length)}
options={(catalog.data?.industries ?? []).map((item) => ({
value: item.key,
label: item.name,
}))}
onChange={(key: BrandTemplateKey) => setIndustryTarget(key)}
/>
<Select
aria-label="视觉模板"
className="admin-field-w-xl"
value={visualKey}
disabled={!canManageTemplate}
loading={selectVisual.isPending}
options={visuals.map((item) => ({ value: item.key, label: item.name }))}
onChange={(key) => selectVisual.mutate(key)}
/>
</Space>
{industryKey ? (
<div className="admin-offset-top-sm">
<Space wrap>
<StatusTag
tone="neutral"
label={`当前版本 ${templatePreview.data?.currentVersion ?? "加载中"}`}
/>
<StatusTag
tone="info"
label={`最新版本 ${templatePreview.data?.latestVersion ?? "加载中"}`}
/>
{templatePreview.data?.canUpgrade ? (
<Button
type="primary"
size="small"
disabled={!canManageTemplate}
loading={upgradeTemplate.isPending}
onClick={() => upgradeTemplate.mutate()}
>
升级模板
</Button>
) : (
<StatusTag tone="success" label="已是最新版本" />
)}
{templatePreview.data?.canRollback ? (
<Button
danger
size="small"
disabled={!canManageTemplate}
loading={rollbackTemplate.isPending}
onClick={() => rollbackTemplate.mutate()}
>
回滚到上一版
</Button>
) : null}
</Space>
<p className="admin-section-description admin-offset-top-sm">
行业模板随品牌身份固定,只能升级版本、不能更换行业;升级只补充字段与模块,不覆盖已有内容。视觉模板只替换排版风格。
</p>
<MutationError
error={templatePreview.error || upgradeTemplate.error || rollbackTemplate.error}
/>
</div>
) : null}
<MutationError error={install.error || selectVisual.error} />
<Divider className="admin-divider" />
<Space wrap>
<Typography.Text>示例内容</Typography.Text>
{sample.isLoading && <Spin size="small" />}
{sample.data && (
<StatusTag
tone={sample.data.alreadyImported ? "success" : "info"}
label={sample.data.alreadyImported ? "已导入" : "可导入"}
/>
)}
<Button
disabled={!canManageTemplate || !sample.data || sample.data.alreadyImported}
loading={importSample.isPending}
onClick={() => importSample.mutate()}
>
导入示例内容
</Button>
{sample.isError && <Button onClick={() => void sample.refetch()}>重试</Button>}
</Space>
{sample.isError && (
<div className="admin-offset-top-sm">
<ErrorNote error={sample.error} onRetry={() => void sample.refetch()} />
</div>
)}
{sample.data && !sample.data.alreadyImported && (
<p className="admin-section-description admin-offset-top-sm">
将向草稿添加{" "}
{Object.entries(sample.data.counts)
.map(([key, count]) => `${key} ${count} 项`)
.join("、")}
;发布前请替换示例文案和图片。
</p>
)}
<MutationError error={importSample.error} />
</AdminSection>
<AdminSection
title="核对草稿内容"
description="此处核对的是待发布内容,不是小程序视觉预览。"
>
<ul className="admin-list">
<li className="admin-row">
<div className="admin-row-main">
<div className="admin-row-line">
<span className="admin-row-title">{brand.data?.name || "未命名品牌"}</span>
<span className="admin-row-meta">
{brand.data?.tagline || "尚未填写品牌定位"}
</span>
</div>
</div>
</li>
<li className="admin-row">
<div className="admin-row-main">
<div className="admin-row-line">
<span className="admin-row-title">已启用业务项</span>
<span className="admin-row-meta">
{draftOfferings.map((item) => item.name).join("、") || "无"}
</span>
</div>
</div>
</li>
<li className="admin-row">
<div className="admin-row-main">
<div className="admin-row-line">
<span className="admin-row-title">已启用咨询表单</span>
<span className="admin-row-meta">
{draftForms
.filter((item) => item.isEnabled)
.map((item) => item.name)
.join("、") || "无"}
</span>
</div>
</div>
</li>
</ul>
<Space wrap className="admin-offset-top">
<Button onClick={() => navigate("/admin/brand")}>编辑小程序页面</Button>
<Button onClick={() => navigate("/admin/services")}>编辑业务展示和详情</Button>
<Button onClick={() => navigate("/admin/trust")}>编辑信任证明</Button>
</Space>
</Space>
</section>
<section>
<Typography.Title level={4}>3. 检查并发布</Typography.Title>
<Space wrap style={{ marginBottom: 12 }}>
<Tag color={currentRelease ? "green" : "default"}>
{currentRelease ? `已发布 v${currentRelease.version}` : "尚未发布"}
</Tag>
<Button onClick={() => void readiness.refetch()}>重新检查</Button>
</Space>
<Space direction="vertical" style={{ width: "100%" }}>
{(readiness.data?.checks ?? []).map((check) => (
<Space key={check.key}>
<Tag color={check.passed ? "success" : "warning"}>
{check.passed ? "已完成" : "待完善"}
</Tag>
<Typography.Text>{check.label}</Typography.Text>
{check.help ? (
<Typography.Text type="secondary">{check.help}</Typography.Text>
) : null}
{!check.passed && (
<Button
type="link"
onClick={() =>
navigate(check.destination ?? destinations[check.key] ?? "/admin/overview")
}
>
去处理
</Button>
</AdminSection>
<AdminSection
title="检查并发布"
extra={
<Space wrap>
<StatusTag
tone={currentRelease ? "success" : "neutral"}
label={currentRelease ? `已发布 v${currentRelease.version}` : "尚未发布"}
/>
<Button onClick={() => void readiness.refetch()}>重新检查</Button>
</Space>
}
>
<ul className="admin-list">
{(readiness.data?.checks ?? []).map((check) => (
<li key={check.key} className="admin-row">
<div className="admin-row-main">
<div className="admin-row-line">
<StatusTag
tone={check.passed ? "success" : "warning"}
label={check.passed ? "已完成" : "待完善"}
/>
<span className="admin-row-title">{check.label}</span>
{!check.passed && check.help ? (
<span className="admin-row-meta">{check.help}</span>
) : null}
</div>
</div>
{!check.passed ? (
<Button
type="link"
size="small"
onClick={() =>
navigate(check.destination ?? destinations[check.key] ?? "/admin/overview")
}
>
去处理
</Button>
) : null}
</li>
))}
</ul>
<Space wrap className="admin-offset-top">
<Button
type="primary"
disabled={!readiness.data?.ready}
onClick={() => setConfirmAction("publish")}
>
发布当前草稿
</Button>
{currentRelease && (
<Button danger onClick={() => setConfirmAction("revoke")}>
撤回当前版本
</Button>
)}
</Space>
<MutationError error={publish.error || revoke.error} />
<Divider className="admin-divider" />
<h3 className="admin-section-title">发布记录</h3>
{releases.data?.length ? (
<ul className="admin-list admin-offset-top-xs">
{releases.data.map((item) => (
<li key={item.id} className="admin-row">
<div className="admin-row-main">
<div className="admin-row-line">
<span className="admin-row-title">v{item.version}</span>
<StatusTag
tone={item.status === "published" ? "success" : "neutral"}
label={statusLabel(item.status)}
/>
<span className="admin-row-meta">
{new Date(item.createdAt).toLocaleString("zh-CN")}
</span>
{item.note ? <span className="admin-row-meta">{item.note}</span> : null}
</div>
</div>
{item.status === "superseded" && publishedHistory.length > 1 ? (
<Button
type="link"
size="small"
onClick={() => setRollbackVersion(item.version)}
>
恢复此版本
</Button>
) : null}
</li>
))}
</ul>
) : (
<EmptyState
compact
title="暂无发布记录"
description="完成检查并发布后,这里会保留每个版本的记录。"
/>
)}
<MutationError error={rollback.error} />
</AdminSection>
</div>
)}
{activeTab === "miniapp" && (
<div className="admin-stack admin-stack-lg">
<AdminSection
title="小程序代码发布"
description="使用微信官方工具上传代码;审核与发布状态需按微信平台结果人工确认。"
extra={
<Space wrap>
<Button
type="primary"
disabled={!currentRelease}
loading={uploadLatestMiniAppRelease.isPending}
onClick={() => uploadLatestMiniAppRelease.mutate()}
>
上传当前版本到微信
</Button>
{miniAppSettings.data?.hasStoredCredentials ? (
<StatusTag tone="success" label="已配置上传凭据" />
) : (
<StatusTag tone="warning" label="未配置上传凭据" />
)}
</Space>
))}
</Space>
<Space wrap style={{ marginTop: 16 }}>
<Button
type="primary"
disabled={!readiness.data?.ready}
onClick={() => setConfirmAction("publish")}
>
发布当前草稿
</Button>
{currentRelease && (
<Button danger onClick={() => setConfirmAction("revoke")}>
撤回当前版本
</Button>
}
>
{miniAppReleases.data?.length ? (
<div className="admin-stack admin-stack-tight">
{miniAppReleases.data.map((task) => (
<MiniAppReleaseCard
key={task.id}
task={task}
uploading={uploadMiniAppRelease.isPending}
onUpload={() => uploadMiniAppRelease.mutate(task.id)}
onStatusChange={(status) => updateMiniAppStatus.mutate({ id: task.id, status })}
/>
))}
</div>
) : (
<EmptyState
compact
title="暂无小程序发布任务"
description="先发布品牌内容,再上传当前版本到微信。"
/>
)}
</Space>
<MutationError error={publish.error || revoke.error} />
<Divider />
<Typography.Title level={5}>发布记录</Typography.Title>
{releases.data?.length ? (
<Space direction="vertical" style={{ width: "100%" }}>
{releases.data.map((item) => (
<Space key={item.id} wrap>
<Typography.Text>v{item.version}</Typography.Text>
<Tag color={item.status === "published" ? "green" : "default"}>{item.status}</Tag>
<Typography.Text type="secondary">
{new Date(item.createdAt).toLocaleString("zh-CN")}
</Typography.Text>
{item.note && <Typography.Text>{item.note}</Typography.Text>}
{item.status === "superseded" && publishedHistory.length > 1 && (
<Button size="small" onClick={() => setRollbackVersion(item.version)}>
恢复此版本
</Button>
)}
</Space>
))}
</Space>
) : (
<Empty description="暂无发布记录" />
)}
<MutationError error={rollback.error} />
</section>
</Space>
</AdminSection>
</div>
)}
<Modal
title={confirmAction === "revoke" ? "确认撤回品牌" : "确认发布品牌"}
open={confirmAction !== null}
onCancel={() => setConfirmAction(null)}
onOk={() => (confirmAction === "revoke" ? revoke.mutate() : publish.mutate())}
onOk={() => (confirmAction === "revoke" ? revoke.mutate() : publish.mutate(note.trim()))}
confirmLoading={publish.isPending || revoke.isPending}
okText={confirmAction === "revoke" ? "确认撤回" : "确认发布"}
okButtonProps={{ danger: confirmAction === "revoke" }}
@@ -357,7 +558,7 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
message="撤回后,小程序将显示品牌尚未发布,新的咨询和预约会停止受理。"
/>
) : (
<Space direction="vertical" style={{ width: "100%" }}>
<div className="admin-stack">
<Typography.Text>当前草稿将成为品牌新的公开版本。</Typography.Text>
<Input
value={note}
@@ -365,7 +566,7 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
placeholder="发布备注(可选)"
maxLength={200}
/>
</Space>
</div>
)}
</Modal>
<Modal
@@ -0,0 +1,152 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { message } from "antd";
import type { BrandTemplateKey } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
const client = createApiClient();
interface MutationOptions {
refresh: () => void;
brandConfig: Record<string, unknown> | null | undefined;
onInstallClose: () => void;
onPublishClose: () => void;
onNoteClear: () => void;
onRollbackClose: () => void;
}
export function usePublicationMutations({
refresh,
onInstallClose,
onPublishClose,
onNoteClear,
onRollbackClose,
brandConfig,
}: MutationOptions) {
const queryClient = useQueryClient();
const install = useMutation({
mutationFn: (key: BrandTemplateKey) => client.installAdminTemplate(key),
onSuccess: () => {
onInstallClose();
message.success("行业模板已安装");
refresh();
},
});
const upgradeTemplate = useMutation({
mutationFn: () => client.upgradeAdminTemplate(),
onSuccess: () => {
message.success("行业模板已升级,现有内容未被覆盖");
refresh();
},
});
const rollbackTemplate = useMutation({
mutationFn: () => client.rollbackAdminTemplate(),
onSuccess: () => {
message.success("行业模板配置基线已回滚");
refresh();
},
});
const selectVisual = useMutation({
mutationFn: (key: string) =>
client.updateAdminBrand({
config: { ...(brandConfig ?? {}), visualTemplateKey: key },
}),
onSuccess: () => {
message.success("视觉模板已保存到草稿");
refresh();
},
});
const importSample = useMutation<Awaited<ReturnType<typeof client.importAdminSampleContent>>>({
mutationFn: () => client.importAdminSampleContent(),
onSuccess: ({ counts }) => {
message.success(
counts.inquiryForms
? "示例内容和客户咨询表单已导入草稿"
: "示例内容已导入草稿,现有客户咨询表单已保留",
);
refresh();
},
});
const publish = useMutation({
mutationFn: (note: string) => client.publishAdminRelease(note || undefined),
onSuccess: () => {
onPublishClose();
onNoteClear();
message.success("品牌已发布");
refresh();
},
});
const revoke = useMutation({
mutationFn: () => client.revokeAdminRelease(),
onSuccess: () => {
onPublishClose();
message.success("品牌已撤回,小程序将显示未发布状态");
refresh();
},
});
const rollback = useMutation({
mutationFn: (version: number) => client.rollbackAdminRelease(version),
onSuccess: () => {
onRollbackClose();
message.success("历史版本已重新发布");
refresh();
},
});
const uploadLatestMiniAppRelease = useMutation({
mutationFn: async () => {
const latest = await client.getLatestAdminMiniAppRelease();
const task = latest ?? (await client.createAdminMiniAppRelease());
return client.uploadAdminMiniAppRelease(task.id);
},
onSuccess: () => {
message.success("小程序代码已上传");
void queryClient.invalidateQueries({ queryKey: ["publication-miniapp-releases"] });
},
});
const saveMiniAppSettings = useMutation({
mutationFn: (values: { appId: string; apiBaseUrl: string; privateKey?: string }) =>
client.updateAdminMiniAppSettings({
appId: values.appId,
apiBaseUrl: values.apiBaseUrl,
...(values.privateKey ? { privateKey: values.privateKey } : {}),
}),
onSuccess: () => {
message.success("小程序上传配置已保存");
void queryClient.invalidateQueries({ queryKey: ["publication-miniapp-settings"] });
},
});
const uploadMiniAppRelease = useMutation({
mutationFn: (id: string) => client.uploadAdminMiniAppRelease(id),
onSuccess: () => {
message.success("小程序代码已上传");
void queryClient.invalidateQueries({ queryKey: ["publication-miniapp-releases"] });
},
});
const updateMiniAppStatus = useMutation({
mutationFn: ({
id,
status,
}: {
id: string;
status: Parameters<typeof client.updateAdminMiniAppReleaseStatus>[1]["status"];
}) => client.updateAdminMiniAppReleaseStatus(id, { status }),
onSuccess: () => {
message.success("小程序发布状态已更新");
void queryClient.invalidateQueries({ queryKey: ["publication-miniapp-releases"] });
},
});
return {
install,
upgradeTemplate,
rollbackTemplate,
selectVisual,
importSample,
publish,
revoke,
rollback,
uploadLatestMiniAppRelease,
saveMiniAppSettings,
uploadMiniAppRelease,
updateMiniAppStatus,
};
}
@@ -0,0 +1,117 @@
import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import type { FormInstance } from "antd";
import { createApiClient } from "../../lib/api.js";
const client = createApiClient();
export function usePublicationQueries(
miniAppSettingsForm: FormInstance<{
appId: string;
apiBaseUrl: string;
privateKey?: string;
}>,
) {
const brand = useQuery<Awaited<ReturnType<typeof client.getAdminBrand>>>({
queryKey: ["publication-brand"],
queryFn: () => client.getAdminBrand(),
});
const workspace = useQuery<Awaited<ReturnType<typeof client.getAdminWorkspace>>>({
queryKey: ["publication-workspace"],
queryFn: () => client.getAdminWorkspace(),
});
const catalog = useQuery<Awaited<ReturnType<typeof client.listPublicTemplates>>>({
queryKey: ["publication-catalog"],
queryFn: () => client.listPublicTemplates(),
});
const sample = useQuery<Awaited<ReturnType<typeof client.previewAdminSampleContent>>>({
queryKey: ["publication-sample"],
queryFn: () => client.previewAdminSampleContent(),
enabled: Boolean(workspace.data),
});
const readiness = useQuery<Awaited<ReturnType<typeof client.getAdminReleaseReadiness>>>({
queryKey: ["publication-readiness"],
queryFn: () => client.getAdminReleaseReadiness(),
});
const releases = useQuery<Awaited<ReturnType<typeof client.listAdminReleases>>>({
queryKey: ["publication-releases"],
queryFn: () => client.listAdminReleases(),
});
const miniAppReleases = useQuery<Awaited<ReturnType<typeof client.listAdminMiniAppReleases>>>({
queryKey: ["publication-miniapp-releases"],
queryFn: () => client.listAdminMiniAppReleases(),
});
const miniAppSettings = useQuery<Awaited<ReturnType<typeof client.getAdminMiniAppSettings>>>({
queryKey: ["publication-miniapp-settings"],
queryFn: () => client.getAdminMiniAppSettings(),
});
const templatePreview = useQuery<
Awaited<ReturnType<typeof client.getAdminTemplateUpgradePreview>>
>({
queryKey: ["publication-template-preview"],
queryFn: () => client.getAdminTemplateUpgradePreview(),
});
useEffect(() => {
if (!miniAppSettings.data) return;
miniAppSettingsForm.setFieldsValue({
appId: miniAppSettings.data.appId,
apiBaseUrl: miniAppSettings.data.apiBaseUrl,
privateKey: "",
});
}, [miniAppSettings.data, miniAppSettingsForm]);
useEffect(() => {
const building = miniAppReleases.data?.find(
(task) =>
task.buildStatus === "building" &&
Date.now() - new Date(task.updatedAt).getTime() < 15 * 60 * 1000,
);
if (!building) return;
const timer = setInterval(() => void miniAppReleases.refetch(), 1500);
return () => clearInterval(timer);
}, [miniAppReleases]);
const loading = [
brand,
workspace,
catalog,
readiness,
releases,
miniAppReleases,
miniAppSettings,
].some((query) => query.isLoading);
const error = [
brand,
workspace,
catalog,
readiness,
releases,
miniAppReleases,
miniAppSettings,
].find((query) => query.isError)?.error;
const retry = () => {
void brand.refetch();
void workspace.refetch();
void catalog.refetch();
void readiness.refetch();
void releases.refetch();
void miniAppReleases.refetch();
void miniAppSettings.refetch();
};
return {
brand,
workspace,
catalog,
sample,
readiness,
releases,
miniAppReleases,
miniAppSettings,
templatePreview,
loading,
error,
retry,
};
}
@@ -0,0 +1,181 @@
import { Alert, Button, Form, Input, Modal, Segmented, Select } 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">
<h4 className="admin-subhead">基础信息</h4>
<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>
<h4 className="admin-subhead">
{previewPage === "offerings" ? "列表展示字段" : "详情展示字段"}
</h4>
<p className="admin-section-description admin-offset-bottom">
这里只编辑左侧预览对应的字段;它们与小程序页面编辑的是同一份业务数据。
</p>
<RecordContentFields
section={{
...templateFieldSection,
fields: activeTemplateFields,
}}
sectionKey="offering"
/>
</div>
) : null}
{editingOffering ? (
<Button htmlType="button" onClick={onEditInBrand}>
在小程序页面编辑
</Button>
) : null}
</div>
</Form>
</div>
</Modal>
);
}
@@ -0,0 +1,124 @@
import { Button, Popconfirm, Space, Table } from "antd";
import type { Offering } from "@personal-brand/api-client";
import { AdminSection } from "../../components/AdminSection.js";
import { EmptyState } from "../../components/EmptyState.js";
import { TableSkeleton } from "../../components/TableSkeleton.js";
import { MutationError } from "../../components/QueryState.js";
import { StatusTag } from "../../components/StatusTag.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) => (
<StatusTag tone="neutral" label={offeringKindLabels[String(value)] ?? String(value)} />
),
},
{ title: "价格", dataIndex: "priceText" },
{
title: "状态",
dataIndex: "isEnabled",
render: (value: boolean) => (
<StatusTag tone={value ? "success" : "neutral"} label={value ? "已启用" : "已停用"} />
),
},
{
title: "操作",
render: (_: unknown, item: Offering) => (
<Space>
<Button type="link" size="small" onClick={() => onEdit(item)}>
编辑详情
</Button>
<Button
type="link"
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
type="link"
danger
size="small"
loading={deleteOffering.isPending && deleteOffering.variables === item.id}
>
删除
</Button>
</Popconfirm>
</Space>
),
},
];
return (
<AdminSection
title={`${pageLabel}中的内容`}
description={
detailSectionTitles.length
? `编辑单项详情时,附加字段将用于:${detailSectionTitles.join("、")}。列表中的名称、说明、价格和封面也会显示在业务展示页。`
: "已启用的项目会公开展示。"
}
>
{loading && items.length === 0 ? (
<TableSkeleton />
) : (
<Table
scroll={{ x: 760 }}
rowKey="id"
dataSource={items}
columns={columns}
locale={{
emptyText: (
<EmptyState
compact
title="还没有业务提供项"
description="创建后,小程序业务展示页会优先读取这些内容。"
/>
),
}}
/>
)}
<MutationError error={saveError} />
<MutationError error={toggleOffering.error} />
<MutationError error={deleteOffering.error} />
</AdminSection>
);
}
@@ -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 var(--admin-border);
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: var(--admin-fill);
border: 1px solid var(--admin-border);
}
.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 var(--admin-border);
}
.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;
}
}
+114 -308
View File
@@ -1,330 +1,136 @@
import {
Button,
Form,
Input,
Modal,
Popconfirm,
Select,
Space,
Table,
Tag,
Typography,
message,
} from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Button } from "antd";
import type { Offering, TemplateAdminField } from "@personal-brand/api-client";
import { useState } from "react";
import { createApiClient } from "../../lib/api.js";
import { useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { ImageUrlField } from "../../components/ImageUrlField.js";
import { TemplateListField } from "../../components/TemplateListField.js";
import {
applyPresentationValues,
presentationFieldName,
readPresentationValue,
} from "../brand/presentation-bindings.js";
import { MutationError, QueryState } from "../../components/QueryState.js";
import { QueryState } from "../../components/QueryState.js";
import { OfferingEditorModal } from "./OfferingEditorModal.js";
import { OfferingsTable } from "./OfferingsTable.js";
import { detailPageLabel, hasTemplateDetailCopy, offeringPageLabel } from "./offering-model.js";
import { buildOfferingPreviewWorkspace, previewTargetsByPage } from "./offering-preview.js";
import { useOfferingEditor } from "./use-offering-editor.js";
import { useOfferingMutations, useOfferingQueries } from "./use-offering-data.js";
type PreviewPage = "offerings" | "detail";
export function ServicesPage() {
const client = createApiClient();
const queryClient = useQueryClient();
const [offeringForm] = Form.useForm();
const [offeringOpen, setOfferingOpen] = useState(false);
const [editingOffering, setEditingOffering] = useState<Offering | null>(null);
const offerings = useQuery({
queryKey: ["admin-offerings"],
queryFn: () => client.listAdminOfferings(),
});
const workspace = useQuery({
queryKey: ["admin-workspace-offering-fields"],
queryFn: () => client.getAdminWorkspace(),
});
const templateFields: TemplateAdminField[] = (
workspace.data?.templateContent?.admin.sections ?? []
)
.filter((section) => section.target === "offering")
.flatMap((section) =>
section.fields.filter((field) => field.binding.startsWith("offering.config.")),
);
const offeringPageLabel =
workspace.data?.templateContent?.navigation.find((item) => item.page === "offerings")?.label ??
"业务展示页";
const detailPageLabel =
workspace.data?.templateContent?.navigation.find((item) => item.page === "detail")?.label ??
"详情页";
const detailSections = (workspace.data?.templateContent?.admin.sections ?? []).filter(
(section) => section.target === "offering" && section.page === "detail",
);
const hasTemplateDetailCopy = templateFields.some(
(field) => field.binding === "offering.config.details.background",
);
const saveOffering = useMutation({
mutationFn: (values: Record<string, unknown>) => {
const fields = Object.fromEntries(
Object.entries(values).filter(([key]) => key !== "config" && !key.startsWith("offering:")),
);
const config = applyPresentationValues(
editingOffering?.config,
[{ key: "offering", fields: templateFields }],
values,
);
const body = { ...fields, config };
return editingOffering
? client.updateAdminOffering(editingOffering.id, body)
: client.createAdminOffering(body as Omit<Offering, "id" | "brandId">);
},
const navigate = useNavigate();
const { offerings, workspace, previewWorkspace, templateFields, retry } = useOfferingQueries();
const editor = useOfferingEditor(templateFields);
const mutations = useOfferingMutations({
editingOffering: editor.editingOffering,
templateFields,
onSuccess: () => {
message.success("业务提供项已保存");
setOfferingOpen(false);
setEditingOffering(null);
offeringForm.resetFields();
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
editor.closeOffering();
editor.offeringForm.resetFields();
},
});
const deleteOffering = useMutation({
mutationFn: (id: string) => client.deleteAdminOffering(id),
onSuccess: () => {
message.success("业务提供项已删除");
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
},
});
const toggleOffering = useMutation({
mutationFn: ({ id, isEnabled }: { id: string; isEnabled: boolean }) =>
client.updateAdminOffering(id, { isEnabled }),
onSuccess: () => {
message.success("业务提供项状态已更新");
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
},
});
const beginOffering = (item?: Offering) => {
setEditingOffering(item ?? null);
setOfferingOpen(true);
offeringForm.setFieldsValue(
item
? {
kind: item.kind,
name: item.name,
summary: item.summary ?? "",
description: item.description ?? "",
priceText: item.priceText ?? "",
coverUrl: item.coverUrl ?? "",
sortOrder: item.sortOrder,
isEnabled: item.isEnabled,
...Object.fromEntries(
templateFields.map((field) => [
presentationFieldName("offering", field.key),
readPresentationValue(item.config, field.binding, field),
]),
),
}
: {
kind: "service",
isEnabled: true,
sortOrder: 0,
...Object.fromEntries(
templateFields.map((field) => [
presentationFieldName("offering", field.key),
field.input === "list" ? [] : undefined,
]),
),
},
);
const sections = workspace.data?.templateContent?.admin.sections ?? [];
const previewTargets = useMemo(() => previewTargetsByPage(sections), [sections]);
const listTarget = previewTargets.offerings.find((target) =>
templateFields.some((field) => field.previewTarget === target.key),
) ?? {
key: "offering.list.item",
label: "业务卡片",
page: "offerings",
source: "offering",
};
const detailTarget = previewTargets.detail.find((target) => target.source === "offering");
const listFields = useMemo(
() => templateFields.filter((field) => field.previewTarget === listTarget.key),
[templateFields, listTarget.key],
);
const detailFields = useMemo(
() => templateFields.filter((field) => field.previewTarget === detailTarget?.key),
[templateFields, detailTarget?.key],
);
const otherFields = useMemo(
() =>
templateFields.filter(
(field) => !listFields.includes(field) && !detailFields.includes(field),
),
[templateFields, listFields, detailFields],
);
const activeTemplateFields: TemplateAdminField[] =
editor.previewPage === "offerings"
? [...listFields, ...otherFields.filter((field) => field.page === "offerings")]
: [...detailFields, ...otherFields.filter((field) => field.page === "detail")];
const previewWorkspaceDraft = useMemo(() => {
if (!previewWorkspace.data || !editor.editingOffering) return undefined;
return buildOfferingPreviewWorkspace({
previewWorkspace: previewWorkspace.data,
editingOffering: editor.editingOffering,
templateFields,
formValues: editor.formValues,
});
}, [
previewWorkspace.data,
editor.editingOffering,
templateFields,
editor.formValues,
editor.offeringDraftVersion,
]);
const navigateToBrand = () => {
if (!editor.editingOffering) return;
void navigate("/admin/brand", {
state: {
targetKey:
editor.previewPage === "offerings"
? listTarget.key
: (detailTarget?.key ?? listTarget.key),
recordId: editor.editingOffering.id,
},
});
};
return (
<QueryState
loading={offerings.isLoading || workspace.isLoading}
error={offerings.error || workspace.error}
onRetry={() => {
void offerings.refetch();
void workspace.refetch();
}}
onRetry={retry}
>
<AdminPageHeader
title="小程序内容:业务展示与详情"
description={`在「${offeringPageLabel}」管理访客能选择的服务、产品或案例;每项内容的补充资料会显示在对应的「${detailPageLabel}」。`}
title="业务提供项"
description={`在「${offeringPageLabel(workspace.data?.templateContent ?? undefined)}」管理访客能选择的服务、产品或案例;每项内容的补充资料会显示在对应的「${detailPageLabel(workspace.data?.templateContent ?? undefined)}」。`}
extra={
<Button type="primary" onClick={() => beginOffering()}>
<Button type="primary" onClick={() => editor.beginOffering()}>
新增业务提供项
</Button>
}
/>
<section aria-label="业务提供项列表">
<Space wrap style={{ marginBottom: 16 }}>
<Typography.Title level={5} style={{ margin: 0 }}>
{offeringPageLabel}中的内容
</Typography.Title>
<Tag color="blue">已启用的项目会公开展示</Tag>
</Space>
{detailSections.length ? (
<Typography.Paragraph type="secondary">
编辑单项详情时,附加字段将用于:
{detailSections.map((section) => section.title).join("、")}
。列表中的名称、说明、价格和封面也会显示在业务展示页。
</Typography.Paragraph>
) : null}
<Table
scroll={{ x: 760 }}
rowKey="id"
loading={offerings.isLoading}
dataSource={offerings.data ?? []}
columns={[
{ title: "名称", dataIndex: "name" },
{
title: "业务类型",
dataIndex: "kind",
render: (value) => (
<Tag>
{(
{
service: "服务",
product: "定制产品",
package: "套餐",
subscription: "订阅",
} as Record<string, string>
)[String(value)] ?? String(value)}
</Tag>
),
},
{ title: "价格", dataIndex: "priceText" },
{
title: "状态",
dataIndex: "isEnabled",
render: (value) => (value ? "已启用" : "已停用"),
},
{
title: "操作",
render: (_: unknown, item: Offering) => (
<Space>
<Button size="small" onClick={() => beginOffering(item)}>
编辑详情
</Button>
<Button
size="small"
loading={toggleOffering.isPending && toggleOffering.variables?.id === item.id}
onClick={() =>
toggleOffering.mutate({ id: item.id, isEnabled: !item.isEnabled })
}
>
{item.isEnabled ? "禁用" : "启用"}
</Button>
<Popconfirm
title="确认删除这项业务提供项?"
description="如果它已经关联咨询表单,系统会阻止删除。"
onConfirm={() => deleteOffering.mutate(item.id)}
okText="删除"
cancelText="取消"
>
<Button
danger
size="small"
loading={deleteOffering.isPending && deleteOffering.variables === item.id}
>
删除
</Button>
</Popconfirm>
</Space>
),
},
]}
/>
{offerings.data?.length === 0 && (
<Typography.Paragraph type="secondary">
还没有公开业务提供项。创建后,小程序服务页会优先读取这些内容。
</Typography.Paragraph>
)}
<MutationError error={saveOffering.error} />
<MutationError error={toggleOffering.error} />
<MutationError error={deleteOffering.error} />
</section>
<Modal
open={offeringOpen}
title={editingOffering ? "编辑业务提供项" : "新增业务提供项"}
onCancel={() => {
setOfferingOpen(false);
setEditingOffering(null);
offeringForm.resetFields();
}}
onOk={() => offeringForm.submit()}
confirmLoading={saveOffering.isPending}
>
<Form
form={offeringForm}
layout="vertical"
onFinish={(values) => saveOffering.mutate(values as Record<string, unknown>)}
>
<Form.Item name="kind" label="类型" rules={[{ required: true }]}>
<Select
options={[
{ value: "service", label: "服务" },
{ value: "product", label: "定制产品" },
{ value: "package", label: "套餐" },
{ value: "subscription", label: "订阅" },
]}
/>
</Form.Item>
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="summary" label="一句话说明">
<Input />
</Form.Item>
{!hasTemplateDetailCopy ? (
<Form.Item name="description" label="详细介绍">
<Input.TextArea rows={5} />
</Form.Item>
) : null}
<Form.Item name="priceText" label="价格展示">
<Input placeholder="例如:按现场评估报价 / ¥ 2,800 起" />
</Form.Item>
<Form.Item
name="coverUrl"
label="封面图片地址"
help="填写图片地址;图片上传能力将在后续媒体管理中提供。"
>
<ImageUrlField placeholder="粘贴服务或产品封面图片地址" />
</Form.Item>
<Form.Item
name="sortOrder"
label="展示顺序"
help="数字越小越靠前,不确定时填写 0。"
rules={[{ type: "number", min: 0, max: 9999 }]}
>
<Input type="number" min={0} max={9999} />
</Form.Item>
<Form.Item name="isEnabled" label="公开状态">
<Select
options={[
{ value: true, label: "已启用" },
{ value: false, label: "已停用" },
]}
/>
</Form.Item>
{templateFields.map((field) =>
field.input === "list" ? (
<TemplateListField
key={field.key}
field={field}
name={presentationFieldName("offering", field.key)}
/>
) : (
<Form.Item
key={field.key}
name={presentationFieldName("offering", field.key)}
label={field.label}
help={field.help}
>
{field.input === "textarea" ? (
<Input.TextArea rows={3} />
) : field.input === "image" ? (
<ImageUrlField />
) : (
<Input />
)}
</Form.Item>
),
)}
</Form>
</Modal>
<OfferingsTable
pageLabel={offeringPageLabel(workspace.data?.templateContent ?? undefined)}
detailSectionTitles={sections
.filter((section) => section.target === "offering" && section.page === "detail")
.map((section) => section.title)}
items={offerings.data ?? []}
loading={offerings.isLoading}
saveError={mutations.saveOffering.error}
toggleOffering={mutations.toggleOffering}
deleteOffering={mutations.deleteOffering}
onEdit={(item: Offering) => editor.beginOffering(item)}
/>
<OfferingEditorModal
open={editor.offeringOpen}
editingOffering={editor.editingOffering}
form={editor.offeringForm}
previewPage={editor.previewPage}
previewWorkspace={previewWorkspaceDraft}
previewTargets={previewTargets}
activeTemplateFields={activeTemplateFields}
templateFieldSection={editor.templateFieldSection}
hasTemplateDetailCopy={hasTemplateDetailCopy(templateFields)}
listTarget={listTarget}
detailTarget={detailTarget}
saving={mutations.saveOffering.isPending}
onClose={editor.closeOffering}
onPreviewPageChange={(page: PreviewPage) => editor.setPreviewPage(page)}
onValuesChange={(values) => editor.handleValuesChange(null, values)}
onFinish={(values) => mutations.saveOffering.mutate(values)}
onEditInBrand={navigateToBrand}
/>
</QueryState>
);
}
@@ -0,0 +1,87 @@
import type {
AdminTemplateContent,
Offering,
TemplateAdminField,
} from "@personal-brand/api-client";
import {
applyPresentationValues,
presentationFieldName,
readPresentationValue,
} from "../../lib/presentation/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 "../../lib/presentation/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,
};
}
+21 -21
View File
@@ -1,23 +1,12 @@
import {
Alert,
Button,
Card,
Form,
Input,
Modal,
Select,
Space,
Table,
Tag,
Typography,
message,
} from "antd";
import { Alert, Button, Card, Form, Input, Modal, Select, Space, Table, message } from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { AdminBrandMember } from "@personal-brand/api-client";
import { useState } from "react";
import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { MutationError, QueryState } from "../../components/QueryState.js";
import { EmptyState } from "../../components/EmptyState.js";
import { StatusTag } from "../../components/StatusTag.js";
const roleLabels: Record<string, string> = {
owner: "负责人",
@@ -81,14 +70,22 @@ export function MembersPage() {
<Alert
type="info"
showIcon
className="admin-offset-bottom"
message="请将初始账号和密码安全地交给成员"
description="当前采用负责人手动添加方式;系统不会再次显示成员初始密码。"
style={{ marginBottom: 16 }}
/>
<Table
rowKey="id"
loading={members.isLoading}
dataSource={members.data ?? []}
locale={{
emptyText: (
<EmptyState
compact
title="还没有其他成员"
description="添加协作者后,他们可以按角色维护当前品牌。"
/>
),
}}
columns={[
{
title: "成员",
@@ -127,9 +124,12 @@ export function MembersPage() {
title: "说明",
render: (_: unknown, item: AdminBrandMember) => (
<Space>
<Tag>{roleLabels[item.role] ?? item.role}</Tag>
<StatusTag
tone={item.role === "owner" ? "info" : "neutral"}
label={roleLabels[item.role] ?? item.role}
/>
{!item.adminUser.isEnabled ? (
<Typography.Text type="danger">账号已停用</Typography.Text>
<StatusTag tone="warning" label="账号已停用" />
) : null}
</Space>
),
@@ -148,7 +148,7 @@ export function MembersPage() {
}}
onOk={() => addForm.submit()}
confirmLoading={create.isPending}
destroyOnClose
destroyOnHidden
>
<Form
form={addForm}
@@ -169,14 +169,14 @@ export function MembersPage() {
label="登录账号"
rules={[{ required: true, message: "请输入登录账号" }]}
>
<Input placeholder="例如:linran" />
<Input placeholder="例如:brand-owner" />
</Form.Item>
<Form.Item
name="displayName"
label="成员姓名"
rules={[{ required: true, message: "请输入成员姓名" }]}
>
<Input placeholder="例如:林然" />
<Input placeholder="例如:品牌主理人" />
</Form.Item>
<Form.Item
name="password"
@@ -1,185 +1,55 @@
import {
Button,
Divider,
Form,
Input,
List,
Modal,
Popconfirm,
Select,
Space,
Table,
Tag,
Typography,
message,
} from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { isTrustContentComplete } from "@personal-brand/api-client";
import type {
TemplateAdminField,
TrustContent,
TrustContentInput,
} from "@personal-brand/api-client";
import { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { createApiClient } from "../../lib/api.js";
import { Button, Form } from "antd";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { ImageUrlField } from "../../components/ImageUrlField.js";
import { TemplateListField } from "../../components/TemplateListField.js";
import { MutationError, QueryState } from "../../components/QueryState.js";
const types = [
{
value: "schedule",
label: "时间与服务安排",
help: "说明你通常什么时候提供服务、接受预约或处理订单。多项内容可以分行填写。",
},
{
value: "coverage",
label: "服务范围与方式",
help: "说明服务地点、覆盖范围、适用对象或承接边界。多项内容可以分行填写。",
},
{
value: "process",
label: "合作流程",
help: "说明客户从提出需求到完成合作会经历哪些步骤,每行写一步。",
},
{
value: "credential",
label: "资质与专业证明",
help: "说明资质、经验、制作标准或让客户放心的专业依据。",
},
{
value: "case",
label: "案例与客户反馈",
help: "写代表性案例、服务结果或客户评价,多条内容可以分行填写。",
},
{
value: "promise",
label: "服务承诺与响应说明",
help: "说明回复时间、交付承诺、售后方式或合作预期。",
},
];
type TrustTypeOption = {
type: string;
label: string;
adminFields: {
title: string;
summary: string;
content: string;
summaryHelp?: string;
summaryPlaceholder?: string;
};
pages?: string[];
help?: string;
placeholder?: string;
required?: boolean;
configFields?: TemplateAdminField[];
hideStandardFields?: Array<"summary" | "content">;
maxPublishedItems?: number;
};
const fallbackTypes: TrustTypeOption[] = types.map(({ value, label, help }) => ({
type: value,
label,
adminFields: { title: "标题", summary: "摘要", content: "详细内容" },
help,
}));
import { AdminSection } from "../../components/AdminSection.js";
import { QueryState } from "../../components/QueryState.js";
import { StatusTag } from "../../components/StatusTag.js";
import { TrustContentEditorModal } from "./components/TrustContentEditorModal.js";
import { TrustContentList } from "./components/TrustContentList.js";
import { TrustRequirementsList } from "./components/TrustRequirementsList.js";
import type { TrustTypeOption } from "./domain/trust-content-domain.js";
import {
createTrustPageLabelResolver,
groupTrustContentByType,
selectTrustTypeOptions,
sortTrustContentByTypeOrder,
} from "./domain/trust-content-domain.js";
import { useTrustContentEditor } from "./hooks/useTrustContentEditor.js";
import { useTrustContentQueries } from "./hooks/useTrustContentQueries.js";
export function TrustContentPage() {
const client = createApiClient();
const queryClient = useQueryClient();
const [editing, setEditing] = useState<TrustContent | null>(null);
const [open, setOpen] = useState(false);
const [form] = Form.useForm<TrustContentInput>();
const [searchParams] = useSearchParams();
const selectedType = Form.useWatch("type", form);
const query = useQuery({
queryKey: ["trust-content"],
queryFn: () => client.listAdminTrustContent(),
const { query, workspace } = useTrustContentQueries();
const availableTypes = selectTrustTypeOptions(workspace.data?.templateContent?.trustContentTypes);
const pageLabel = createTrustPageLabelResolver(workspace.data?.templateContent?.navigation);
const items = sortTrustContentByTypeOrder(query.data ?? [], availableTypes);
const contentByType = groupTrustContentByType(items);
const firstMissingRequiredType =
availableTypes.find((item) => item.required && !contentByType.has(item.type))?.type ??
availableTypes[0]?.type ??
"credential";
const {
begin,
closeEditor,
editing,
form: editorForm,
open,
remove,
save,
} = useTrustContentEditor({
availableTypes,
contentByType,
firstMissingRequiredType,
});
const workspace = useQuery({
queryKey: ["admin-workspace-trust-types"],
queryFn: () => client.getAdminWorkspace(),
});
const availableTypes: TrustTypeOption[] = workspace.data?.templateContent?.trustContentTypes
?.length
? workspace.data.templateContent.trustContentTypes
: fallbackTypes;
const pageLabel = (page: string) =>
workspace.data?.templateContent?.navigation.find((item) => item.page === page)?.label ??
(
{ home: "首页", offerings: "业务展示页", detail: "详情页", profile: "主理人页" } as Record<
string,
string
>
)[page] ??
page;
const selectedType = Form.useWatch("type", editorForm);
const selectedTypeMeta: TrustTypeOption | undefined = availableTypes.find(
(item) => item.type === selectedType,
);
const trustPageLabels = [
...new Set(availableTypes.flatMap((item) => item.pages ?? []).map(pageLabel)),
];
const trustPlacement = trustPageLabels.length
? `小程序的${trustPageLabels.join("、")}中`
: "小程序对应的信任展示区域中";
const selectedTypeMeta = availableTypes.find((item) => item.type === selectedType);
const contentByType = new Map<string, TrustContent>();
for (const item of query.data ?? []) {
const current = contentByType.get(item.type);
const hasConfig = Object.keys(item.config ?? {}).length > 0;
const currentHasConfig = Object.keys(current?.config ?? {}).length > 0;
if (
!current ||
(item.isPublished && !current.isPublished) ||
(item.isPublished === current.isPublished && hasConfig && !currentHasConfig)
) {
contentByType.set(item.type, item);
}
}
const firstMissingRequiredType =
availableTypes.find((item) => item.required && !contentByType.has(item.type))?.type ??
availableTypes[0]?.type ??
"credential";
const requestedType = searchParams.get("type");
const save = useMutation({
mutationFn: (values: TrustContentInput) =>
editing
? client.updateAdminTrustContent(editing.id, values)
: client.createAdminTrustContent(values),
onSuccess: () => {
message.success("品牌内容已保存为草稿,发布后小程序才会更新");
setOpen(false);
setEditing(null);
form.resetFields();
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
},
});
const remove = useMutation({
mutationFn: (id: string) => client.deleteAdminTrustContent(id),
onSuccess: () => {
message.success("品牌内容已删除");
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
},
});
const begin = (item?: TrustContent, type?: string) => {
setEditing(item ?? null);
setOpen(true);
form.setFieldsValue(
item
? {
type: item.type,
title: item.title,
...(item.summary ? { summary: item.summary } : {}),
content: item.content,
config: item.config ?? {},
...(item.coverUrl ? { coverUrl: item.coverUrl } : {}),
isPublished: item.isPublished,
}
: { type: type ?? firstMissingRequiredType, isPublished: false, config: {} },
);
};
useEffect(() => {
if (!requestedType || !availableTypes.some((item) => item.type === requestedType)) return;
begin(contentByType.get(requestedType), requestedType);
}, [requestedType, availableTypes.length]);
return (
<QueryState
loading={query.isLoading || workspace.isLoading}
@@ -187,228 +57,54 @@ export function TrustContentPage() {
onRetry={() => void Promise.all([query.refetch(), workspace.refetch()])}
>
<AdminPageHeader
title="小程序内容:品牌介绍与信任"
description={`填写真实的经历、案例、资历、流程和服务说明。这些内容会显示在${trustPlacement};保存后需发布品牌,小程序才会更新。`}
title="信任内容"
description={`填写真实的经历、案例、资历、流程与服务说明,发布品牌后即会展示在${trustPlacement}。`}
extra={
<Button type="primary" onClick={() => begin()}>
添加品牌内容
</Button>
}
/>
<section aria-labelledby="trust-requirements-title">
<Typography.Title id="trust-requirements-title" level={5}>
当前模板需要配置的内容
</Typography.Title>
<Typography.Paragraph type="secondary">
标记为“发布必填”的项目需要填写完整后,才能发布小程序。
</Typography.Paragraph>
<List
size="small"
dataSource={availableTypes}
renderItem={(item) => {
const content = contentByType.get(item.type);
const publishedCount = (query.data ?? []).filter(
(record) => record.type === item.type && record.isPublished,
).length;
const tooMany =
item.maxPublishedItems !== undefined && publishedCount > item.maxPublishedItems;
const complete = Boolean(content && isTrustContentComplete(content, item) && !tooMany);
return (
<List.Item
actions={[
<Button
key={item.type}
type="link"
size="small"
onClick={() => (content ? begin(content) : begin(undefined, item.type))}
>
{content ? "编辑" : "新增"}
</Button>,
]}
>
<Space wrap>
<Typography.Text strong>{item.label}</Typography.Text>
{item.required && <Tag color="orange">发布必填</Tag>}
{(item.pages ?? []).map((page) => (
<Tag key={page}>{pageLabel(page)}</Tag>
))}
<Tag color={complete ? "success" : "default"}>
{tooMany
? `公开内容过多(${publishedCount} 条)`
: complete
? "内容完整"
: content
? "需要完善"
: "尚未填写"}
</Tag>
{item.help && <Typography.Text type="secondary">{item.help}</Typography.Text>}
</Space>
</List.Item>
);
}}
/>
</section>
<Divider />
<section aria-label="已配置的品牌内容">
<Table
rowKey="id"
dataSource={query.data ?? []}
locale={{ emptyText: "还没有品牌内容,请先按上方模板要求添加。" }}
columns={[
{
title: "内容类型",
dataIndex: "type",
render: (value) => (
<Tag>{availableTypes.find((item) => item.type === value)?.label ?? value}</Tag>
),
},
{ title: "标题", dataIndex: "title" },
{
title: "内容预览",
ellipsis: { showTitle: true },
render: (_value: unknown, item: TrustContent) => {
const meta = availableTypes.find((type) => type.type === item.type);
if (meta?.hideStandardFields?.includes("content")) {
return (
meta.configFields
?.flatMap((field) => {
const value = item.config?.[field.key];
if (Array.isArray(value))
return value.length ? [`${field.label}:${value.length} 项`] : [];
return typeof value === "string" && value.trim()
? [`${field.label}:${value}`]
: [];
})
.join(";") || "尚未填写区块内容"
);
}
return item.summary || item.content || "未填写";
},
},
{
title: "发布状态",
dataIndex: "isPublished",
render: (value) => (
<Tag color={value ? "success" : "default"}>{value ? "随发布展示" : "草稿"}</Tag>
),
},
{
title: "操作",
render: (_: unknown, item: TrustContent) => (
<Space>
<Button size="small" onClick={() => begin(item)}>
编辑
</Button>
<Popconfirm
title="确认删除这条信任内容?"
description="删除后需发布品牌,才会更新小程序展示。"
onConfirm={() => remove.mutate(item.id)}
>
<Button size="small" danger loading={remove.isPending}>
删除
</Button>
</Popconfirm>
</Space>
),
},
]}
/>
<MutationError error={remove.error} />
</section>
<Modal
open={open}
title={editing ? "编辑品牌内容" : "添加品牌内容"}
onCancel={() => {
setOpen(false);
setEditing(null);
form.resetFields();
}}
onOk={() => form.submit()}
confirmLoading={save.isPending}
destroyOnClose
<AdminSection
title="当前模板需要配置的内容"
description="标记为「发布必填」的项目需要填写完整后,才能发布小程序。"
>
<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>
<TrustRequirementsList
availableTypes={availableTypes}
contentByType={contentByType}
items={items}
pageLabel={pageLabel}
onEdit={begin}
/>
</AdminSection>
<AdminSection
title="已配置的品牌内容"
description="同一类型可以保存多条;标记为草稿的内容不会随品牌发布展示。"
extra={<StatusTag tone="info" label={`共 ${items.length} 条`} />}
>
<TrustContentList
availableTypes={availableTypes}
items={items}
pageLabel={pageLabel}
removeError={remove.error}
removePendingId={remove.isPending ? remove.variables : undefined}
onCreate={() => begin()}
onEdit={(item) => begin(item)}
onDelete={(id) => remove.mutate(id)}
/>
</AdminSection>
<TrustContentEditorModal
availableTypes={availableTypes}
editing={editing}
form={editorForm}
open={open}
pageLabel={pageLabel}
saveError={save.error}
savePending={save.isPending}
selectedTypeMeta={selectedTypeMeta}
onCancel={closeEditor}
onFinish={(values) => save.mutate(values)}
/>
</QueryState>
);
}
@@ -0,0 +1,123 @@
import { Form, Input, Modal, Select } 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}
destroyOnHidden
>
<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 ? (
<p className="admin-section-description admin-offset-bottom">
这类内容会显示在:{selectedTypeMeta.pages.map(pageLabel).join("、")}
</p>
) : 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,92 @@
import { Button, Popconfirm } from "antd";
import { FileTextOutlined } from "@ant-design/icons";
import type { TrustContent } from "@personal-brand/api-client";
import { EmptyState } from "../../../components/EmptyState.js";
import { MutationError } from "../../../components/QueryState.js";
import { StatusTag } from "../../../components/StatusTag.js";
import type { TrustTypeOption } from "../domain/trust-content-domain.js";
import { getTrustContentPreview } from "../domain/trust-content-domain.js";
import { TrustContentTypeIcon } from "./TrustContentTypeIcon.js";
export function TrustContentList({
availableTypes,
items,
pageLabel,
removeError,
removePendingId,
onCreate,
onEdit,
onDelete,
}: {
availableTypes: TrustTypeOption[];
items: TrustContent[];
pageLabel: (page: string) => string;
removeError: unknown;
removePendingId?: string | undefined;
onCreate: () => void;
onEdit: (item: TrustContent) => void;
onDelete: (id: string) => void;
}) {
if (!items.length) {
return (
<section aria-label="已配置的品牌内容">
<EmptyState
icon={<FileTextOutlined />}
title="还没有品牌内容"
description="按上方模板要求逐项添加,访客才能看到你的经历与证明。"
action={<Button onClick={onCreate}>添加品牌内容</Button>}
/>
</section>
);
}
return (
<section aria-label="已配置的品牌内容">
<ul className="admin-list">
{items.map((item) => {
const typeMeta = availableTypes.find((type) => type.type === item.type);
const pages = (typeMeta?.pages ?? []).map(pageLabel);
const meta = [typeMeta?.label ?? item.type]
.concat(pages.length ? `展示于${pages.join("、")}` : [])
.join(" · ");
return (
<li key={item.id} className="admin-row admin-record">
<div className="admin-record__thumb">
{item.coverUrl ? (
<img src={item.coverUrl} alt="" loading="lazy" />
) : (
<TrustContentTypeIcon type={item.type} />
)}
</div>
<div className="admin-row-main">
<div className="admin-row-line">
<span className="admin-row-title">{item.title}</span>
<StatusTag
tone={item.isPublished ? "success" : "neutral"}
label={item.isPublished ? "已发布" : "草稿"}
/>
</div>
<p className="admin-row-meta">{meta}</p>
<p className="admin-row-summary">{getTrustContentPreview(item, typeMeta)}</p>
</div>
<div className="admin-record__actions">
<Button type="link" size="small" onClick={() => onEdit(item)}>
编辑
</Button>
<Popconfirm
title="确认删除这条品牌内容?"
description="删除后需发布品牌,才会更新小程序展示。"
onConfirm={() => onDelete(item.id)}
>
<Button type="link" size="small" danger loading={removePendingId === item.id}>
删除
</Button>
</Popconfirm>
</div>
</li>
);
})}
</ul>
<MutationError error={removeError} />
</section>
);
}
@@ -0,0 +1,24 @@
import {
ApartmentOutlined,
ClockCircleOutlined,
EnvironmentOutlined,
FileTextOutlined,
SafetyCertificateOutlined,
StarOutlined,
CheckCircleOutlined,
} from "@ant-design/icons";
import type { ReactNode } from "react";
// 类型图标只为让列表可扫读,模板未声明的类型回落到通用图标。
const TYPE_ICONS: Record<string, ReactNode> = {
schedule: <ClockCircleOutlined />,
coverage: <EnvironmentOutlined />,
process: <ApartmentOutlined />,
credential: <SafetyCertificateOutlined />,
case: <StarOutlined />,
promise: <CheckCircleOutlined />,
};
export function TrustContentTypeIcon({ type }: { type: string }) {
return <>{TYPE_ICONS[type] ?? <FileTextOutlined />}</>;
}
@@ -0,0 +1,73 @@
import { Button } 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";
import { StatusTag } from "../../../components/StatusTag.js";
export function TrustRequirementsList({
availableTypes,
contentByType,
items,
pageLabel,
onEdit,
}: {
availableTypes: TrustTypeOption[];
contentByType: Map<string, TrustContent>;
items: TrustContent[];
pageLabel: (page: string) => string;
onEdit: (item?: TrustContent, type?: string) => void;
}) {
return (
<ul className="admin-list">
{availableTypes.map((item) => {
const content = contentByType.get(item.type);
const publishedCount = items.filter(
(record) => record.type === item.type && record.isPublished,
).length;
const configuredCount = items.filter((record) => record.type === item.type).length;
const tooMany =
item.maxPublishedItems !== undefined && publishedCount > item.maxPublishedItems;
const complete = Boolean(content && isTrustContentComplete(content, item) && !tooMany);
return (
<li key={item.type} className="admin-row">
<div className="admin-row-main">
<div className="admin-row-line">
<span className="admin-row-title">{item.label}</span>
{item.required ? <StatusTag tone="warning" label="发布必填" /> : null}
<StatusTag
tone={tooMany ? "error" : complete ? "success" : "neutral"}
label={
tooMany
? `公开内容过多(${publishedCount} 条)`
: complete
? "内容完整"
: content
? "需要完善"
: "尚未填写"
}
/>
{configuredCount > 1 ? (
<span className="admin-row-meta">已配置 {configuredCount} 条</span>
) : null}
{(item.pages ?? []).map((page) => (
<span key={page} className="admin-row-meta">
{pageLabel(page)}
</span>
))}
</div>
{item.help ? <p className="admin-row-help">{item.help}</p> : null}
</div>
<Button
type="link"
size="small"
onClick={() => (content ? onEdit(content) : onEdit(undefined, item.type))}
>
{content ? "编辑" : "新增"}
</Button>
</li>
);
})}
</ul>
);
}
@@ -0,0 +1,152 @@
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: "业务展示页",
service: "服务介绍页",
detail: "详情页",
profile: "主理人页",
inquiry: "咨询页",
};
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")) {
const fragments =
typeMeta.configFields?.flatMap((field) => {
const value = item.config?.[field.key];
if (Array.isArray(value)) {
return value.length ? [`${field.label}:${value.length} 项`] : [];
}
if (typeof value !== "string") return [];
const text = value.trim();
return text ? [`${field.label}:${stripFieldLabel(field.label, text)}`] : [];
}) ?? [];
if (!fragments.length) return "尚未填写区块内容";
return fragments.length > 3 ? `${fragments.slice(0, 3).join(";")}…` : fragments.join(";");
}
return item.summary || item.content || "未填写";
}
// 模板示例数据常把展示前缀写进值内(如“地点:…”),与字段名重复时去掉。
function stripFieldLabel(label: string, value: string): string {
const match = /^([^::]{1,8})[::]\s*/.exec(value);
if (!match) return value;
const token = (match[1] ?? "").trim();
if (token && sharesMeaningfulOverlap(label, token)) return value.slice(match[0].length);
return value;
}
// 前缀与字段名只要有两个连续字重合,就视为重复标签。
function sharesMeaningfulOverlap(label: string, token: string): boolean {
if (token.length < 2) return label.includes(token);
for (let index = 0; index + 2 <= token.length; index += 1) {
if (label.includes(token.slice(index, index + 2))) return true;
}
return false;
}
// 列表按模板声明的类型顺序排列,与「当前模板需要配置的内容」保持一致。
export function sortTrustContentByTypeOrder(
items: TrustContent[],
availableTypes: TrustTypeOption[],
): TrustContent[] {
const orderOf = new Map(availableTypes.map((item, index) => [item.type, index]));
return [...items].sort((left, right) => {
const leftOrder = orderOf.get(left.type) ?? availableTypes.length;
const rightOrder = orderOf.get(right.type) ?? availableTypes.length;
if (leftOrder !== rightOrder) return leftOrder - rightOrder;
return left.title.localeCompare(right.title, "zh-Hans-CN");
});
}
Loaded 100 of 381 files, more files were not shown because too many files have changed in this diff. Show more