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
227 changed files with 17279 additions and 3866 deletions

No files matched your search

+14
View File
@@ -17,3 +17,17 @@ OBJECT_STORAGE_ACCESS_KEY=minioadmin
OBJECT_STORAGE_SECRET_KEY=minioadmin OBJECT_STORAGE_SECRET_KEY=minioadmin
WECHAT_APP_ID= WECHAT_APP_ID=
WECHAT_APP_SECRET= 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
+6 -1
View File
@@ -8,7 +8,7 @@ DATABASE_URL=postgresql://personal_brand:replace-with-a-long-database-password@1
SESSION_SECRET=replace-with-at-least-32-random-characters SESSION_SECRET=replace-with-at-least-32-random-characters
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001 DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
SEED_ADMIN_PASSWORD=replace-with-a-one-time-initial-password SEED_ADMIN_PASSWORD=replace-with-a-one-time-initial-password
SEED_MODE=seed SEED_MODE=skip
API_PORT=3001 API_PORT=3001
API_PREFIX= API_PREFIX=
@@ -24,3 +24,8 @@ OBJECT_STORAGE_REGION=us-east-1
WECHAT_APP_ID= WECHAT_APP_ID=
WECHAT_APP_SECRET= WECHAT_APP_SECRET=
# 小程序请求地址正常情况下在后台「小程序上传配置」维护;
# 这里仅作为后台未配置时的回落值(否则由 PUBLIC_BASE_URL + /api 推导)
# MINIAPP_API_BASE_URL=https://wechat.app.que01.top/api
# MINIAPP_BUILD_STALE_MS=900000
+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`。
+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"; import type { ReactNode } from "react";
export function AdminPageHeader({ export function AdminPageHeader({
@@ -11,21 +10,12 @@ export function AdminPageHeader({
extra?: ReactNode; extra?: ReactNode;
}) { }) {
return ( return (
<Space <header className="admin-page-header">
align="start" <div className="admin-page-header-text">
style={{ width: "100%", justifyContent: "space-between", marginBottom: 24 }} <h1 className="admin-page-header-title">{title}</h1>
> {description ? <p className="admin-page-header-description">{description}</p> : null}
<div>
<Typography.Title level={2} style={{ margin: 0 }}>
{title}
</Typography.Title>
{description && (
<Typography.Paragraph type="secondary" style={{ margin: "8px 0 0" }}>
{description}
</Typography.Paragraph>
)}
</div> </div>
{extra} {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>
);
}
+19 -27
View File
@@ -1,7 +1,7 @@
import { CloudUploadOutlined, DeleteOutlined, PictureOutlined } from "@ant-design/icons"; import { CloudUploadOutlined, DeleteOutlined, PictureOutlined } from "@ant-design/icons";
import { Alert, Button, Image, Popconfirm, Space, Spin, Upload, message } from "antd"; import { Alert, Button, Image, Popconfirm, Spin, Upload, message } from "antd";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { createApiClient } from "../lib/api.js"; import { apiBaseUrl, createApiClient } from "../lib/api.js";
interface ImageUrlFieldProps { interface ImageUrlFieldProps {
id?: string; id?: string;
@@ -50,23 +50,31 @@ export function ImageUrlField({ id, value, onChange, placeholder, scope }: Image
contentType: file.type, contentType: file.type,
...(scope ? { scope } : {}), ...(scope ? { scope } : {}),
}); });
const response = await fetch(presign.uploadUrl, { const isLocalUpload = presign.mode === "local";
const uploadUrl = isLocalUpload
? `${apiBaseUrl.replace(/\/$/, "")}${presign.uploadUrl}`
: presign.uploadUrl;
const response = await fetch(uploadUrl, {
method: "PUT", method: "PUT",
headers: { "content-type": file.type }, headers: {
"content-type": file.type,
...(isLocalUpload
? { authorization: `Bearer ${localStorage.getItem("adminToken") ?? ""}` }
: {}),
},
body: file, body: file,
}); });
if (!response.ok) throw new Error(`upload failed: ${response.status}`); if (!response.ok) throw new Error(`upload failed: ${response.status}`);
onChange?.(presign.publicUrl); onChange?.(presign.publicUrl);
} catch { } catch (error) {
setStorageStatus("unavailable"); message.error(error instanceof Error ? error.message : "图片上传失败,请重试");
message.error("图片上传失败,请检查对象存储后重试");
} finally { } finally {
setUploading(false); setUploading(false);
} }
} }
return ( return (
<Space direction="vertical" size={4} style={{ width: "100%" }}> <div className="admin-field-stack-xs admin-block">
{storageStatus !== "ok" ? ( {storageStatus !== "ok" ? (
<Alert <Alert
type={storageStatus === "loading" ? "info" : "warning"} type={storageStatus === "loading" ? "info" : "warning"}
@@ -81,33 +89,17 @@ export function ImageUrlField({ id, value, onChange, placeholder, scope }: Image
/> />
) : null} ) : null}
{imageUrl ? ( {imageUrl ? (
<div <div className="admin-media-preview">
style={{
position: "relative",
width: "100%",
minHeight: 140,
borderRadius: 8,
overflow: "hidden",
border: "1px solid #d9d9d9",
background: "#f5f5f5",
}}
>
<Image <Image
src={imageUrl} src={imageUrl}
alt={placeholder ?? "图片预览"} alt={placeholder ?? "图片预览"}
width="100%" width="100%"
height={180} height={180}
preview preview
style={{ objectFit: "cover" }}
fallback="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" fallback="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="
/> />
<Popconfirm title="移除这张图片?" onConfirm={() => onChange?.("")}> <Popconfirm title="移除这张图片?" onConfirm={() => onChange?.("")}>
<Button <Button danger size="small" icon={<DeleteOutlined />} className="admin-thumb-remove">
danger
size="small"
icon={<DeleteOutlined />}
style={{ position: "absolute", top: 8, right: 8 }}
>
移除 移除
</Button> </Button>
</Popconfirm> </Popconfirm>
@@ -145,6 +137,6 @@ export function ImageUrlField({ id, value, onChange, placeholder, scope }: Image
</Button> </Button>
) : null} ) : null}
<input {...(id ? { id } : {})} type="hidden" value={imageUrl} /> <input {...(id ? { id } : {})} type="hidden" value={imageUrl} />
</Space> </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 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({ export function QueryState({
loading, loading,
@@ -12,36 +17,31 @@ export function QueryState({
onRetry?: () => void; onRetry?: () => void;
children?: ReactNode; children?: ReactNode;
}) { }) {
if (loading) if (loading) return <LoadingStack />;
return ( if (error) return <ErrorNote error={error} onRetry={onRetry} />;
<Card>
<Spin />
</Card>
);
if (error) {
return (
<Result
status="error"
title="内容加载失败"
subTitle={error instanceof Error ? error.message : "请检查 API 服务后重试"}
extra={onRetry ? <Button onClick={onRetry}>重新加载</Button> : undefined}
/>
);
}
return <>{children}</>; return <>{children}</>;
} }
export function EmptyState({ description }: { description: string }) { export function ErrorNote({
return <Empty description={description} image={Empty.PRESENTED_IMAGE_SIMPLE} />; 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 }) { export function MutationError({ error }: { error?: unknown }) {
if (!error) return null; return <ErrorNote error={error} />;
return (
<Alert
type="error"
showIcon
message={error instanceof Error ? error.message : "操作失败,请重试"}
/>
);
} }
@@ -4,7 +4,7 @@ import type { TemplateAdminSection } from "@personal-brand/api-client";
import { TemplateListField } from "./TemplateListField.js"; import { TemplateListField } from "./TemplateListField.js";
import { TemplateFieldRenderer } from "./TemplateFieldRenderer.js"; import { TemplateFieldRenderer } from "./TemplateFieldRenderer.js";
import { MutationError } from "./QueryState.js"; import { MutationError } from "./QueryState.js";
import { presentationFieldName } from "../features/brand/presentation-bindings.js"; import { presentationFieldName } from "../lib/presentation/presentation-bindings.js";
import { useRecordContentEditorState } from "./record-content/useRecordContentEditorState.js"; import { useRecordContentEditorState } from "./record-content/useRecordContentEditorState.js";
import type { RecordContentEditorProps, RecordContentSource } from "./record-content/types.js"; import type { RecordContentEditorProps, RecordContentSource } from "./record-content/types.js";
@@ -71,7 +71,7 @@ export function RecordContentEditor({
initialValues={initialValues} initialValues={initialValues}
onValuesChange={handleValuesChange} onValuesChange={handleValuesChange}
onFinish={submit} onFinish={submit}
style={{ minHeight: 0, display: "flex", flexDirection: "column" }} className="admin-form-column"
> >
<Alert <Alert
type="info" type="info"
@@ -88,11 +88,11 @@ export function RecordContentEditor({
} }
/> />
{save.isPending ? <Typography.Text type="secondary">正在保存内容…</Typography.Text> : null} {save.isPending ? <Typography.Text type="secondary">正在保存内容…</Typography.Text> : null}
<Typography.Paragraph type="secondary">{section.description}</Typography.Paragraph> <p className="admin-section-description">{section.description}</p>
<div style={{ flex: 1 }}> <div className="admin-flex-1">
<RecordContentFields section={section} /> <RecordContentFields section={section} />
</div> </div>
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}> <div className="admin-actions admin-offset-top-lg">
<MutationError error={save.error} /> <MutationError error={save.error} />
<Space wrap> <Space wrap>
<Button type="primary" htmlType="submit" loading={save.isPending}> <Button type="primary" htmlType="submit" loading={save.isPending}>
@@ -114,7 +114,7 @@ export function RecordContentEditor({
</Button> </Button>
) : null} ) : null}
</Space> </Space>
</Space> </div>
</Form> </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>
);
}
@@ -51,7 +51,7 @@ export function TemplateFieldRenderer({
value={typeof value === "number" ? value : null} value={typeof value === "number" ? value : null}
onChange={(input) => onChange?.(input ?? undefined)} onChange={(input) => onChange?.(input ?? undefined)}
min={0} min={0}
style={{ width: "100%" }} className="admin-block"
placeholder={field.placeholder} placeholder={field.placeholder}
/> />
); );
@@ -1,4 +1,4 @@
import { Button, Card, Collapse, Empty, Form, Input, Space, Typography } from "antd"; import { Button, Card, Collapse, Form, Input, Space, Typography } from "antd";
import { import {
CaretDownOutlined, CaretDownOutlined,
CaretUpOutlined, CaretUpOutlined,
@@ -6,6 +6,7 @@ import {
PlusOutlined, PlusOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import type { TemplateAdminField } from "@personal-brand/api-client"; import type { TemplateAdminField } from "@personal-brand/api-client";
import { EmptyState } from "./EmptyState.js";
export function TemplateListField({ export function TemplateListField({
field, field,
@@ -28,13 +29,8 @@ export function TemplateListField({
]} ]}
> >
{(rows, { add, remove, move }, { errors }) => ( {(rows, { add, remove, move }, { errors }) => (
<Space direction="vertical" size={12} style={{ width: "100%" }}> <div className="admin-stack admin-stack-tight">
{rows.length === 0 ? ( {rows.length === 0 ? <EmptyState compact title={`还没有${field.label}内容`} /> : null}
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={`还没有${field.label}内容`}
/>
) : null}
{rows.map((row, index) => { {rows.map((row, index) => {
const titleField = field.itemFields?.[0]; const titleField = field.itemFields?.[0];
const primaryTitle = titleField ? ( const primaryTitle = titleField ? (
@@ -135,7 +131,7 @@ export function TemplateListField({
<Button block icon={<PlusOutlined />} onClick={() => add()}> <Button block icon={<PlusOutlined />} onClick={() => add()}>
新增{field.label} 新增{field.label}
</Button> </Button>
</Space> </div>
)} )}
</Form.List> </Form.List>
</Form.Item> </Form.Item>
@@ -1,5 +1,5 @@
import type { Offering, TemplateAdminSection, TrustContent } from "@personal-brand/api-client"; import type { Offering, TemplateAdminSection, TrustContent } from "@personal-brand/api-client";
import type { PresentationValues } from "../../features/brand/presentation-bindings.js"; import type { PresentationValues } from "../../lib/presentation/presentation-bindings.js";
export type RecordContentSource = "offering" | "trust"; export type RecordContentSource = "offering" | "trust";
@@ -10,7 +10,7 @@ import {
presentationFieldName, presentationFieldName,
readPresentationValue, readPresentationValue,
type PresentationValues, type PresentationValues,
} from "../../features/brand/presentation-bindings.js"; } from "../../lib/presentation/presentation-bindings.js";
import type { RecordContentSource } from "./types.js"; import type { RecordContentSource } from "./types.js";
function createInitialValues( function createInitialValues(
+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>
);
}
+24 -46
View File
@@ -1,19 +1,29 @@
.brand-page__content {
max-width: 960px;
}
.brand-page__content[hidden] { .brand-page__content[hidden] {
display: none; display: none;
} }
.brand-page__toolbar { .brand-page__toolbar {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
gap: 16px; gap: 16px;
padding: 16px 0; padding: 8px 12px;
border-bottom: 1px solid #e5e7eb; border: 1px solid var(--admin-border);
margin-bottom: 20px; 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) { @media (max-width: 575px) {
.brand-page__toolbar { .brand-page__toolbar {
flex-wrap: wrap; flex-wrap: wrap;
@@ -25,54 +35,22 @@
} }
.brand-settings-section { .brand-settings-section {
padding: 24px 0; padding: 20px;
border-top: 1px solid #f0f0f0; border: 1px solid var(--admin-border);
border-radius: 10px;
background: var(--admin-surface);
} }
.brand-settings-section:first-child { .brand-settings-section + .brand-settings-section {
padding-top: 8px; margin-top: 16px;
border-top: 0;
}
.brand-settings-section__header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 20px;
}
.brand-settings-section__header .ant-typography {
margin: 0;
}
.brand-settings-section__header .ant-typography + .ant-typography {
display: block;
margin-top: 4px;
} }
.brand-page__template-note { .brand-page__template-note {
margin-top: 24px; margin-top: 16px;
} }
@media (max-width: 1199px) { @media (max-width: 1199px) {
.brand-page__content {
display: block;
}
.brand-page__template-note { .brand-page__template-note {
position: static; position: static;
margin-top: 24px;
}
}
@media (max-width: 575px) {
.brand-settings-section__header {
display: block;
}
.brand-settings-section__header .ant-tag {
display: inline-block;
margin-top: 10px;
} }
} }
+27 -38
View File
@@ -1,17 +1,4 @@
import { import { Alert, Button, Col, Form, Input, Row, Select, Segmented, message } from "antd";
Alert,
Button,
Col,
Form,
Input,
Row,
Select,
Segmented,
Space,
Tag,
Typography,
message,
} from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react"; import { useState } from "react";
import { Link, useLocation } from "react-router-dom"; import { Link, useLocation } from "react-router-dom";
@@ -20,6 +7,7 @@ import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js"; import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { ImageUrlField } from "../../components/ImageUrlField.js"; import { ImageUrlField } from "../../components/ImageUrlField.js";
import { MutationError, QueryState } from "../../components/QueryState.js"; import { MutationError, QueryState } from "../../components/QueryState.js";
import { StatusTag } from "../../components/StatusTag.js";
import { PresentationEditor } from "./PresentationEditor.js"; import { PresentationEditor } from "./PresentationEditor.js";
import type { PreviewSelection } from "./preview-selection.js"; import type { PreviewSelection } from "./preview-selection.js";
import "./BrandPage.css"; import "./BrandPage.css";
@@ -66,13 +54,13 @@ export function BrandPage() {
{!brand.data ? null : ( {!brand.data ? null : (
<> <>
<AdminPageHeader <AdminPageHeader
title="小程序工作台" title="小程序页面"
description={ description={
template.data?.description template.data?.description
? `先让访客理解你是谁、服务谁,以及为什么值得信任。${template.data.description}` ? `先让访客理解你是谁、服务谁,以及为什么值得信任。${template.data.description}`
: "先让访客理解你是谁、服务谁,以及为什么值得信任。" : "先让访客理解你是谁、服务谁,以及为什么值得信任。"
} }
extra={<Tag color="blue">{template.data?.name ?? "当前模板"}</Tag>} extra={<StatusTag tone="info" label={template.data?.name ?? "当前模板"} />}
/> />
<div className="brand-page__toolbar"> <div className="brand-page__toolbar">
<Segmented <Segmented
@@ -84,12 +72,13 @@ export function BrandPage() {
{ value: "brand", label: "品牌资料" }, { value: "brand", label: "品牌资料" },
]} ]}
/> />
<Space> <div className="brand-page__toolbar-actions">
<Tag color={dirty ? "orange" : "default"}> <StatusTag
{dirty ? "品牌资料有未保存修改" : "草稿工作区"} tone={dirty ? "warning" : "neutral"}
</Tag> label={dirty ? "品牌资料有未保存修改" : "草稿工作区"}
/>
<Link to="/admin/publication">检查与发布 →</Link> <Link to="/admin/publication">检查与发布 →</Link>
</Space> </div>
</div> </div>
<div className="brand-page__content" hidden={panel !== "brand"}> <div className="brand-page__content" hidden={panel !== "brand"}>
<div className="brand-page__settings"> <div className="brand-page__settings">
@@ -101,14 +90,14 @@ export function BrandPage() {
onFinish={(values) => save.mutate(values)} onFinish={(values) => save.mutate(values)}
> >
<section className="brand-settings-section" aria-labelledby="brand-identity-title"> <section className="brand-settings-section" aria-labelledby="brand-identity-title">
<div className="brand-settings-section__header"> <div className="admin-section-head">
<div> <div>
<Typography.Title id="brand-identity-title" level={4}> <h2 id="brand-identity-title" className="admin-section-title">
我是谁 我是谁
</Typography.Title> </h2>
<Typography.Text type="secondary">公开展示的品牌身份和定位。</Typography.Text> <p className="admin-section-description">公开展示的品牌身份和定位。</p>
</div> </div>
<Tag>品牌基础信息</Tag> <StatusTag tone="neutral" label="品牌基础信息" />
</div> </div>
<Form.Item <Form.Item
name="name" name="name"
@@ -136,14 +125,14 @@ export function BrandPage() {
</Form.Item> </Form.Item>
</section> </section>
<section className="brand-settings-section" aria-labelledby="brand-contact-title"> <section className="brand-settings-section" aria-labelledby="brand-contact-title">
<div className="brand-settings-section__header"> <div className="admin-section-head">
<div> <div>
<Typography.Title id="brand-contact-title" level={4}> <h2 id="brand-contact-title" className="admin-section-title">
如何联系与合作 如何联系与合作
</Typography.Title> </h2>
<Typography.Text type="secondary"> <p className="admin-section-description">
让访客知道联系渠道、服务范围和响应预期。 让访客知道联系渠道、服务范围和响应预期。
</Typography.Text> </p>
</div> </div>
</div> </div>
<Row gutter={16}> <Row gutter={16}>
@@ -177,14 +166,14 @@ export function BrandPage() {
</Form.Item> </Form.Item>
</section> </section>
<section className="brand-settings-section" aria-labelledby="brand-visual-title"> <section className="brand-settings-section" aria-labelledby="brand-visual-title">
<div className="brand-settings-section__header"> <div className="admin-section-head">
<div> <div>
<Typography.Title id="brand-visual-title" level={4}> <h2 id="brand-visual-title" className="admin-section-title">
模板与品牌视觉 模板与品牌视觉
</Typography.Title> </h2>
<Typography.Text type="secondary"> <p className="admin-section-description">
模板负责业务表达,品牌信息仍由你统一维护。 模板负责业务表达,品牌信息仍由你统一维护。
</Typography.Text> </p>
</div> </div>
</div> </div>
<Form.Item <Form.Item
@@ -221,12 +210,12 @@ export function BrandPage() {
</Col> </Col>
</Row> </Row>
</section> </section>
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}> <div className="admin-actions admin-offset-top-lg">
<MutationError error={save.error} /> <MutationError error={save.error} />
<Button type="primary" htmlType="submit" loading={save.isPending} size="large"> <Button type="primary" htmlType="submit" loading={save.isPending} size="large">
保存品牌表达 保存品牌表达
</Button> </Button>
</Space> </div>
</Form> </Form>
</div> </div>
{template.data ? ( {template.data ? (
@@ -6,21 +6,21 @@
display: flex; display: flex;
gap: 8px; gap: 8px;
padding: 8px 12px; padding: 8px 12px;
border-bottom: 1px solid #e8e8e8; border-bottom: 1px solid var(--admin-border);
background: #fff; background: #fff;
} }
.component-template-preview__tools button { .component-template-preview__tools button {
padding: 4px 12px; padding: 4px 12px;
border: 1px solid #d9d9d9; border: 1px solid var(--admin-border);
border-radius: 6px; border-radius: 6px;
background: #fff; background: #fff;
cursor: pointer; cursor: pointer;
} }
.component-template-preview__tools button[aria-pressed="true"] { .component-template-preview__tools button[aria-pressed="true"] {
border-color: #1677ff; border-color: var(--admin-primary);
color: #1677ff; color: var(--admin-primary);
} }
.component-template-preview { .component-template-preview {
@@ -31,7 +31,7 @@
padding: 24px 16px; padding: 24px 16px;
overflow-x: hidden; overflow-x: hidden;
overflow-y: auto; overflow-y: auto;
background: #f3f4f6; background: var(--admin-fill);
} }
.component-template-preview__canvas { .component-template-preview__canvas {
@@ -49,8 +49,8 @@
} }
:where(.component-template-preview__canvas) { :where(.component-template-preview__canvas) {
--taro-button-height: 11.7333333cqw; --brand-button-height: 11.7333333cqw;
--taro-button-compact-height: 6.1333333cqw; --brand-button-compact-height: 6.1333333cqw;
} }
.component-template-preview__canvas, .component-template-preview__canvas,
@@ -68,7 +68,7 @@
align-items: center; align-items: center;
justify-content: center; justify-content: center;
width: 100%; width: 100%;
min-height: var(--taro-button-height); min-height: var(--brand-button-height);
appearance: none; appearance: none;
margin: 0; margin: 0;
padding: 0; padding: 0;
@@ -102,13 +102,13 @@
position: absolute; position: absolute;
z-index: 5; z-index: 5;
pointer-events: none; pointer-events: none;
border: 2px solid #91caff; border: 2px solid var(--admin-primary);
border-radius: 4px; border-radius: 4px;
} }
.component-template-preview__outline.is-selected { .component-template-preview__outline.is-selected {
z-index: 6; z-index: 6;
border-color: #1677ff; border-color: var(--admin-primary);
box-shadow: 0 0 0 3px rgba(22, 119, 255, 0.16); box-shadow: 0 0 0 3px rgba(22, 119, 255, 0.16);
} }
@@ -117,10 +117,10 @@
z-index: 7; z-index: 7;
width: max-content !important; width: max-content !important;
padding: 2px 8px !important; padding: 2px 8px !important;
border: 1px solid #1677ff !important; border: 1px solid var(--admin-primary) !important;
border-radius: 4px !important; border-radius: 4px !important;
background: #fff !important; background: #fff !important;
color: #0958d9 !important; color: var(--admin-primary) !important;
font-size: 12px !important; font-size: 12px !important;
line-height: 20px !important; line-height: 20px !important;
cursor: pointer; cursor: pointer;
@@ -128,13 +128,14 @@
.component-template-preview__outline span { .component-template-preview__outline span {
position: absolute; position: absolute;
bottom: 100%; top: 0;
left: 0; left: 0;
max-width: 100%; max-width: calc(100% - 8px);
transform: translateY(-100%);
padding: 2px 7px; padding: 2px 7px;
overflow: hidden; overflow: hidden;
border-radius: 4px 4px 0 0; border-radius: 4px 4px 0 0;
background: #1677ff; background: var(--admin-primary);
color: #fff; color: #fff;
font-size: 12px; font-size: 12px;
line-height: 18px; line-height: 18px;
@@ -142,6 +143,11 @@
white-space: nowrap; white-space: nowrap;
} }
.component-template-preview__outline.is-selected span {
top: 4px;
transform: none;
}
.component-template-preview__tools[hidden] { .component-template-preview__tools[hidden] {
display: none; display: none;
} }
@@ -89,7 +89,9 @@ export function ComponentTemplatePreview({
position(node, outlines.selected); position(node, outlines.selected);
host.append(node); host.append(node);
} }
for (const outline of outlines.composite) { for (const outline of outlines.composite.filter(
(item) => item.key !== selection?.targetKey,
)) {
const node = document.createElement("button"); const node = document.createElement("button");
node.type = "button"; node.type = "button";
node.className = "component-template-preview__composite-select"; node.className = "component-template-preview__composite-select";
@@ -205,6 +207,9 @@ export function ComponentTemplatePreview({
onPointerLeave={() => setHovered(null)} onPointerLeave={() => setHovered(null)}
onClickCapture={(event) => { onClickCapture={(event) => {
if (mode !== "edit" || !targets.length) return; 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"); const canvas = root.current?.querySelector(".component-template-preview__canvas");
if (!event.target || !(event.target instanceof Node) || !canvas?.contains(event.target)) if (!event.target || !(event.target instanceof Node) || !canvas?.contains(event.target))
return; return;
@@ -1,4 +1,4 @@
import { Alert, Button, Form, Input, Select, Space, Switch, Typography, message } from "antd"; import { Alert, Button, Form, Input, Select, Space, Switch, message } from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react"; import { useEffect } from "react";
import type { RuntimeWorkspace } from "@personal-brand/api-client"; import type { RuntimeWorkspace } from "@personal-brand/api-client";
@@ -79,9 +79,9 @@ export function InquiryPreviewEditor({
onValuesChange={(_, values) => onDraft(update(values))} onValuesChange={(_, values) => onDraft(update(values))}
onFinish={(values) => save.mutate(values)} onFinish={(values) => save.mutate(values)}
> >
<Typography.Paragraph type="secondary"> <p className="admin-section-description admin-offset-bottom">
{record.name} · 编辑字段:{field.label} {record.name} · 编辑字段:{field.label}
</Typography.Paragraph> </p>
<Form.Item <Form.Item
name="label" name="label"
label="字段标题" label="字段标题"
@@ -109,7 +109,7 @@ export function InquiryPreviewEditor({
<Form.List name="options"> <Form.List name="options">
{(fields, { add, remove }) => ( {(fields, { add, remove }) => (
<div> <div>
{fields.length ? <Typography.Title level={5}>选项</Typography.Title> : null} {fields.length ? <h4 className="admin-subhead admin-offset-bottom-xs">选项</h4> : null}
{fields.map(({ key, name }) => ( {fields.map(({ key, name }) => (
<Space key={key} align="start"> <Space key={key} align="start">
<Form.Item name={[name, "label"]} label="选项名称" rules={[{ required: true }]}> <Form.Item name={[name, "label"]} label="选项名称" rules={[{ required: true }]}>
@@ -128,7 +128,12 @@ export function InquiryPreviewEditor({
)} )}
</Form.List> </Form.List>
<MutationError error={save.error} /> <MutationError error={save.error} />
<Button style={{ marginTop: 24 }} type="primary" htmlType="submit" loading={save.isPending}> <Button
className="admin-offset-top-lg"
type="primary"
htmlType="submit"
loading={save.isPending}
>
保存表单字段 保存表单字段
</Button> </Button>
</Form> </Form>
@@ -1,6 +1,5 @@
.presentation-editor { .presentation-editor {
margin-top: 0; margin-top: 0;
padding-top: 8px;
} }
.presentation-editor__header { .presentation-editor__header {
@@ -8,15 +7,7 @@
align-items: flex-start; align-items: flex-start;
justify-content: space-between; justify-content: space-between;
gap: 16px; gap: 16px;
margin-bottom: 24px; margin-bottom: 16px;
}
.presentation-editor__header .ant-typography {
margin-top: 0;
}
.presentation-editor__header .ant-typography + .ant-typography {
margin-bottom: 0;
} }
.presentation-editor > .ant-space { .presentation-editor > .ant-space {
@@ -24,9 +15,9 @@
width: 100%; width: 100%;
margin-bottom: 24px !important; margin-bottom: 24px !important;
padding: 6px; padding: 6px;
border: 1px solid #e8e8e8; border: 1px solid var(--admin-border);
border-radius: 10px; border-radius: 10px;
background: #fafafa; background: var(--admin-fill-quiet);
} }
@media (max-width: 575px) { @media (max-width: 575px) {
@@ -45,16 +36,16 @@
grid-template-columns: 200px minmax(300px, 1fr) minmax(280px, 360px); grid-template-columns: 200px minmax(300px, 1fr) minmax(280px, 360px);
grid-template-areas: "outline preview inspector"; grid-template-areas: "outline preview inspector";
margin: 0 !important; margin: 0 !important;
border: 1px solid #e5e7eb; border: 1px solid var(--admin-border);
border-radius: 12px; border-radius: 12px;
overflow: hidden; overflow: hidden;
background: #fff; background: var(--admin-surface);
} }
.presentation-editor__preview { .presentation-editor__preview {
grid-area: preview; grid-area: preview;
padding: 20px !important; padding: 20px !important;
background: #f8fafc; background: var(--admin-fill);
min-width: 0; min-width: 0;
} }
@@ -62,13 +53,13 @@
grid-area: inspector; grid-area: inspector;
padding: 24px !important; padding: 24px !important;
min-width: 0; min-width: 0;
border-left: 1px solid #e5e7eb; border-left: 1px solid var(--admin-border);
} }
.presentation-editor__outline { .presentation-editor__outline {
grid-area: outline; grid-area: outline;
padding: 20px 12px; padding: 20px 12px;
border-right: 1px solid #e5e7eb; border-right: 1px solid var(--admin-border);
} }
.presentation-editor__regions { .presentation-editor__regions {
display: flex; display: flex;
@@ -90,8 +81,8 @@
padding-left: 24px; padding-left: 24px;
} }
.presentation-editor__regions .ant-btn[aria-pressed="true"] { .presentation-editor__regions .ant-btn[aria-pressed="true"] {
background: #e6f4ff; background: var(--admin-primary-bg);
color: #0958d9; color: var(--admin-primary);
font-weight: 600; font-weight: 600;
} }
@@ -117,26 +108,37 @@
margin-bottom: 20px; margin-bottom: 20px;
} }
.presentation-editor__inspector form > section { .presentation-editor__form {
padding: 16px; display: flex;
border: 1px solid #e5e7eb; flex-direction: column;
border-radius: 12px; min-height: 0;
background: #f8fafc;
} }
.presentation-editor__inspector form > section + section { .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; margin-top: 16px;
} }
.presentation-editor__inspector form > .ant-space:last-child { .presentation-editor__form-actions {
position: sticky; position: sticky;
bottom: 0; bottom: 0;
z-index: 2; z-index: 2;
padding: 16px 0 4px; padding: 16px 0 4px;
border-top: 1px solid #e5e7eb; border-top: 1px solid var(--admin-border);
background: #fff; background: var(--admin-surface);
} }
.presentation-editor__inspector form > .ant-space:last-child .ant-btn-primary {
.presentation-editor__form-actions .ant-btn-primary {
min-width: 140px; min-width: 140px;
} }
.presentation-editor__inspector > .ant-tag { .presentation-editor__inspector > .ant-tag {
@@ -150,11 +152,11 @@
} }
.presentation-editor__outline { .presentation-editor__outline {
border-right: 0; border-right: 0;
border-bottom: 1px solid #e5e7eb; border-bottom: 1px solid var(--admin-border);
} }
.presentation-editor__inspector { .presentation-editor__inspector {
border-left: 0; border-left: 0;
border-top: 1px solid #e5e7eb; border-top: 1px solid var(--admin-border);
} }
} }
@@ -1,31 +1,14 @@
import { import { Alert, Button, Grid, Select, Segmented, Space, Typography } from "antd";
Alert,
Button,
Divider,
Col,
Form,
Grid,
Row,
Select,
Segmented,
Space,
Tag,
Typography,
} from "antd";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import type { import type {
AdminTemplateContent, AdminTemplateContent,
RuntimeWorkspace, RuntimeWorkspace,
TemplateAdminField,
TemplateAdminSection, TemplateAdminSection,
} from "@personal-brand/api-client"; } from "@personal-brand/api-client";
import type { BrandProfile } from "@personal-brand/api-client"; import type { BrandProfile } from "@personal-brand/api-client";
import { projectBrandAliases, projectTrustPresentation } from "@personal-brand/api-client"; import { StatusTag } from "../../components/StatusTag.js";
import { TemplateListField } from "../../components/TemplateListField.js";
import { TemplateFieldRenderer } from "../../components/TemplateFieldRenderer.js";
import { MutationError } from "../../components/QueryState.js";
import { RecordContentEditor } from "../../components/RecordContentEditor.js"; import { RecordContentEditor } from "../../components/RecordContentEditor.js";
import { TemplatePreview } from "./TemplatePreview.js"; import { TemplatePreview } from "./TemplatePreview.js";
import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js"; import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js";
@@ -37,9 +20,8 @@ import {
} from "./preview-selection.js"; } from "./preview-selection.js";
import { import {
filterSectionsForPreviewTarget, filterSectionsForPreviewTarget,
presentationFieldName,
type PresentationValues, type PresentationValues,
} from "./presentation-bindings.js"; } from "../../lib/presentation/presentation-bindings.js";
import "./PresentationEditor.css"; import "./PresentationEditor.css";
import { useEditorDraft } from "./use-editor-draft.js"; import { useEditorDraft } from "./use-editor-draft.js";
import { import {
@@ -50,6 +32,10 @@ import {
useBrandPreviewDraft, useBrandPreviewDraft,
} from "./presentation-editor-state.js"; } from "./presentation-editor-state.js";
import { useRecordPreview } from "./presentation-editor-record-preview.js"; import { useRecordPreview } from "./presentation-editor-record-preview.js";
import type { RecordDraft } from "./presentation-editor-record-preview.js";
import { pageTitle, previewTargetSource, trustSection } from "./presentation-editor-helpers.js";
import { useDraftWorkspace } from "./use-draft-workspace.js";
import { PresentationFormPanel } from "./PresentationFormPanel.js";
interface PresentationEditorProps { interface PresentationEditorProps {
templateContent: AdminTemplateContent | null | undefined; templateContent: AdminTemplateContent | null | undefined;
@@ -61,73 +47,6 @@ interface PresentationEditorProps {
initialSelection?: PreviewSelection; initialSelection?: PreviewSelection;
} }
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}`,
})),
};
}
function previewTargetSource(
section: TemplateAdminSection,
targetKey: string,
): "brand" | "offering" | "trust" | "inquiry" {
const fields = section.fields.filter((field) => field.previewTarget === targetKey);
if (fields.some((field) => field.binding.startsWith("offering."))) return "offering";
if (fields.some((field) => field.binding.startsWith("trust."))) return "trust";
if (fields.some((field) => field.binding.startsWith("brand."))) return "brand";
return section.target;
}
export function PresentationEditor({ export function PresentationEditor({
templateContent, templateContent,
previewWorkspace, previewWorkspace,
@@ -144,11 +63,7 @@ export function PresentationEditor({
const [selection, setSelection] = useState<PreviewSelection | undefined>(initialSelection); const [selection, setSelection] = useState<PreviewSelection | undefined>(initialSelection);
const [hasInitializedSelection, setHasInitializedSelection] = useState(Boolean(initialSelection)); const [hasInitializedSelection, setHasInitializedSelection] = useState(Boolean(initialSelection));
const [detailOfferingId, setDetailOfferingId] = useState<string>(); const [detailOfferingId, setDetailOfferingId] = useState<string>();
const [recordDraft, setRecordDraft] = useState<{ const [recordDraft, setRecordDraft] = useState<RecordDraft>();
source: "offering" | "trust";
id: string;
values: PresentationValues;
}>();
const [inquiryDraft, setInquiryDraft] = const [inquiryDraft, setInquiryDraft] =
useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>(); useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>();
const [brandDirty, setBrandDirty] = useState(false); const [brandDirty, setBrandDirty] = useState(false);
@@ -367,113 +282,17 @@ export function PresentationEditor({
}); });
const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection }); const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection });
useEffect(() => resetPreview(), [config, initialValues, resetPreview]); useEffect(() => resetPreview(), [config, initialValues, resetPreview]);
const previewConfig = previewBrand.config; const draftWorkspace = useDraftWorkspace({
const draftWorkspace = useMemo(() => {
if (!previewWorkspace) return undefined;
const next: RuntimeWorkspace = {
...previewWorkspace,
templateData: {
...previewWorkspace.templateData,
...(previewConfig.templateData &&
typeof previewConfig.templateData === "object" &&
!Array.isArray(previewConfig.templateData)
? (previewConfig.templateData as Record<string, unknown>)
: {}),
},
inquiryForms: previewWorkspace.inquiryForms.map((item) =>
item.key === inquiryRuntime?.key && inquiryDraft ? { ...item, fields: inquiryDraft } : item,
),
brand: projectBrandAliases(
{
...previewWorkspace.brand,
...(previewBrand as unknown as Record<string, unknown>),
config: previewConfig,
},
previewConfig,
),
};
if (!recordDraft || !selectedRecord || !recordSection || recordDraft.id !== selectedRecord.id)
return next;
const config = recordPreview?.config;
const standard = recordPreview?.standard;
if (!config || !standard) return next;
if (recordDraft.source === "trust") {
next.trustItems = next.trustItems.map((item) =>
item.id === recordDraft.id
? {
...item,
title: typeof standard.title === "string" ? standard.title : item.title,
summary: typeof standard.summary === "string" ? standard.summary : item.summary,
content: typeof standard.content === "string" ? standard.content : item.content,
config,
}
: item,
);
next.trustPresentation = projectTrustPresentation(
next.trustItems,
templateContent?.trustContentTypes ?? [],
);
} else {
next.offerings = next.offerings.map((item) =>
item.id === recordDraft.id
? {
...item,
name:
(recordDraft.values[presentationFieldName(recordSection.key, "name")] as string) ||
item.name,
summary:
(recordDraft.values[
presentationFieldName(recordSection.key, "summary")
] as string) || item.summary,
priceText:
(recordDraft.values[
presentationFieldName(recordSection.key, "priceText")
] as string) || null,
coverUrl:
(recordDraft.values[
presentationFieldName(recordSection.key, "coverUrl")
] as string) || null,
presentation: {
...item.presentation,
...config,
...(config.presentation && typeof config.presentation === "object"
? (config.presentation as Record<string, unknown>)
: {}),
...(typeof config.area === "string" ? { area: config.area } : {}),
...(typeof config.series === "string" ? { series: config.series } : {}),
...(typeof config.spaceType === "string" ? { spaceType: config.spaceType } : {}),
heroImage:
typeof config.detailHero === "string"
? config.detailHero
: typeof standard.coverUrl === "string"
? standard.coverUrl
: null,
details: {
...item.presentation.details,
...(config.details &&
typeof config.details === "object" &&
"background" in config.details
? (config.details as RuntimeWorkspace["offerings"][number]["presentation"]["details"])
: {}),
},
},
}
: item,
);
}
return next;
}, [
previewWorkspace, previewWorkspace,
previewBrand, previewBrand,
previewConfig, inquiryRuntime,
inquiryDraft,
recordDraft, recordDraft,
selectedRecord, selectedRecord,
recordSection, recordSection,
recordPreview, recordPreview,
templateContent, templateContent,
inquiryDraft, });
inquiryRuntime,
]);
const selectedDetailOfferingId = const selectedDetailOfferingId =
detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId) detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId)
? detailOfferingId ? detailOfferingId
@@ -483,14 +302,14 @@ export function PresentationEditor({
<section className="presentation-editor" aria-labelledby="presentation-editor-title"> <section className="presentation-editor" aria-labelledby="presentation-editor-title">
<div className="presentation-editor__header"> <div className="presentation-editor__header">
<div> <div>
<Typography.Title id="presentation-editor-title" level={3}> <h2 id="presentation-editor-title" className="admin-section-title">
小程序页面配置 小程序页面配置
</Typography.Title> </h2>
<Typography.Paragraph type="secondary"> <p className="admin-section-description">
按页面查找内容。这里修改的是草稿,发布后访客才会看到更新。 按页面查找内容。这里修改的是草稿,发布后访客才会看到更新。
</Typography.Paragraph> </p>
</div> </div>
{templateContent ? <Tag color="blue">{templateContent.displayName}</Tag> : null} {templateContent ? <StatusTag tone="info" label={templateContent.displayName} /> : null}
</div> </div>
{loading ? <Alert type="info" showIcon message="正在读取当前模板的编辑项目" /> : null} {loading ? <Alert type="info" showIcon message="正在读取当前模板的编辑项目" /> : null}
{error ? ( {error ? (
@@ -517,7 +336,7 @@ export function PresentationEditor({
setActivePage(value); setActivePage(value);
}) })
} }
style={{ minWidth: 180 }} className="admin-field-w-2xl"
/> />
) : ( ) : (
<Segmented <Segmented
@@ -538,11 +357,11 @@ export function PresentationEditor({
</Space> </Space>
<div className="presentation-editor__workspace"> <div className="presentation-editor__workspace">
<div className="presentation-editor__preview"> <div className="presentation-editor__preview">
<Typography.Title level={5}>页面预览</Typography.Title> <h3 className="admin-section-title admin-flush">页面预览</h3>
{selectedPage === "detail" && draftWorkspace?.offerings.length ? ( {selectedPage === "detail" && draftWorkspace?.offerings.length ? (
<Select <Select
aria-label="选择详情页业务内容" aria-label="选择详情页业务内容"
style={{ width: "100%", marginBottom: 12 }} className="admin-block admin-offset-bottom-sm"
value={selectedDetailOfferingId} value={selectedDetailOfferingId}
options={draftWorkspace.offerings.map((item) => ({ options={draftWorkspace.offerings.map((item) => ({
value: item.id, value: item.id,
@@ -568,10 +387,10 @@ export function PresentationEditor({
/> />
</div> </div>
<aside className="presentation-editor__outline" aria-label="页面区域"> <aside className="presentation-editor__outline" aria-label="页面区域">
<Typography.Title level={5}>页面区域</Typography.Title> <h3 className="admin-section-title admin-flush">页面区域</h3>
<Typography.Paragraph type="secondary">选择区域,编辑对应内容</Typography.Paragraph> <p className="admin-section-description">选择区域,编辑对应内容</p>
{visibleTargets.length ? ( {visibleTargets.length ? (
<Space className="presentation-editor__regions" wrap style={{ marginTop: 16 }}> <Space className="presentation-editor__regions admin-offset-top" wrap>
{visibleTargets.map((target) => ( {visibleTargets.map((target) => (
<Button <Button
key={target.key} key={target.key}
@@ -610,18 +429,27 @@ export function PresentationEditor({
) : null} ) : null}
</aside> </aside>
<div className="presentation-editor__inspector"> <div className="presentation-editor__inspector">
<Typography.Title level={5}> <h3 className="admin-section-title admin-flush">
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")} {selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
</Typography.Title> </h3>
<Tag color={brandDirty || recordDraft || inquiryDraft ? "orange" : "default"}> <StatusTag
{save.isPending tone={
? "正在保存" save.isError
: save.isError ? "error"
? "保存失败,请重试" : save.isPending || brandDirty || recordDraft || inquiryDraft
: brandDirty || recordDraft || inquiryDraft ? "warning"
? "有未保存修改" : "neutral"
: "草稿已同步"} }
</Tag> label={
save.isPending
? "正在保存"
: save.isError
? "保存失败,请重试"
: brandDirty || recordDraft || inquiryDraft
? "有未保存修改"
: "草稿已同步"
}
/>
{selectedPage === "detail" && !selectedTarget ? ( {selectedPage === "detail" && !selectedTarget ? (
<Alert <Alert
type="info" type="info"
@@ -775,118 +603,25 @@ export function PresentationEditor({
/> />
) : !selectedTarget ? ( ) : !selectedTarget ? (
<div className="presentation-editor__empty"> <div className="presentation-editor__empty">
<Typography.Title level={5}>选择要编辑的区域</Typography.Title> <h3 className="admin-subhead">选择要编辑的区域</h3>
<Typography.Paragraph type="secondary"> <p className="admin-section-description">
点击预览中的内容,或使用区域列表,查看并修改对应字段。 点击预览中的内容,或使用区域列表,查看并修改对应字段。
</Typography.Paragraph> </p>
</div> </div>
) : ( ) : (
<Form <PresentationFormPanel
form={form} form={form}
layout="vertical"
initialValues={initialValues} initialValues={initialValues}
editableSections={editableSections}
relevantPageLinks={relevantPageLinks}
selectedTarget={selectedTarget}
save={{
error: save.error,
isPending: save.isPending,
mutate: (values) => save.mutate(values),
}}
onValuesChange={handleValuesChange} onValuesChange={handleValuesChange}
onFinish={() => save.mutate(form.getFieldsValue(true) as PresentationValues)} />
style={{ minHeight: 0, 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={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
style={{ marginBottom: 24 }}
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",
);
}}
style={{ padding: 0 }}
>
{item.label}
</Button>
))}
</Space>
}
/>
) : null}
{!editableSections.some((section) => section.fields.length) &&
!relevantPageLinks.length ? (
<Typography.Paragraph type="secondary">
这个页面没有单独的品牌文案配置。
</Typography.Paragraph>
) : null}
{selectedTarget &&
!editableSections.some((section) => section.fields.length) &&
relevantPageLinks.length ? (
<Typography.Paragraph type="secondary">
此区域内容由对应的业务管理页面维护。
</Typography.Paragraph>
) : null}
</div>
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
<MutationError error={save.error} />
<Button type="primary" htmlType="submit" loading={save.isPending}>
保存页面内容
</Button>
</Space>
</Form>
)} )}
</div> </div>
</div> </div>
@@ -895,24 +630,3 @@ export function PresentationEditor({
</section> </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); height: min(72vh, 760px);
min-height: 560px; min-height: 560px;
overflow: hidden; overflow: hidden;
border: 1px solid #e8e8e8; border: 1px solid var(--admin-border);
background: #f3f4f6; background: var(--admin-fill);
} }
.template-preview iframe { .template-preview iframe {
@@ -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}`;
}
@@ -1,8 +1,10 @@
import { useMemo } from "react"; import { useMemo } from "react";
import type { Offering, TrustContent } from "@personal-brand/api-client"; import type { Offering, TemplateAdminSection, TrustContent } from "@personal-brand/api-client";
import type { TemplateAdminSection } from "@personal-brand/api-client"; import {
import { applyPresentationValues, applyStandardEntityValues } from "./presentation-bindings.js"; applyPresentationValues,
import type { PresentationValues } from "./presentation-bindings.js"; applyStandardEntityValues,
} from "../../lib/presentation/presentation-bindings.js";
import type { PresentationValues } from "../../lib/presentation/presentation-bindings.js";
export interface RecordDraft { export interface RecordDraft {
source: "offering" | "trust"; source: "offering" | "trust";
@@ -18,7 +18,7 @@ import {
presentationFieldName, presentationFieldName,
readPresentationValue, readPresentationValue,
type PresentationValues, type PresentationValues,
} from "./presentation-bindings.js"; } from "../../lib/presentation/presentation-bindings.js";
const standardBrandBindings = [ const standardBrandBindings = [
"brand.name", "brand.name",
@@ -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]);
}
@@ -1,20 +1,24 @@
import { Card, Col, Empty, Row, Typography } from "antd"; 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 { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { EmptyState } from "../../components/EmptyState.js";
import { QueryState } from "../../components/QueryState.js"; import { QueryState } from "../../components/QueryState.js";
import { CapabilityCard } from "./components/CapabilityCard.js"; import { CapabilityCard } from "./components/CapabilityCard.js";
import { useCapabilityQuery } from "./hooks/useCapabilityQueries.js"; import { useCapabilityQuery } from "./hooks/useCapabilityQueries.js";
export function CapabilitiesPage() { export function CapabilitiesPage() {
const navigate = useNavigate();
const query = useCapabilityQuery(); const query = useCapabilityQuery();
return ( return (
<QueryState loading={query.isLoading} error={query.error} onRetry={() => void query.refetch()}> <QueryState loading={query.isLoading} error={query.error} onRetry={() => void query.refetch()}>
<AdminPageHeader <AdminPageHeader
title="能力管理" title="能力插件"
description="以经营者视角调整模板能力的开关与展示设置;保存后进入草稿,发布后生效。" description="以经营者视角调整模板能力的开关与展示设置;保存后进入草稿,发布后生效。"
/> />
{query.data?.length ? ( {query.data?.length ? (
<Row gutter={[16, 16]}> <Row gutter={[16, 16]} className="admin-equal-height">
{query.data.map((capability) => ( {query.data.map((capability) => (
<Col key={capability.capabilityKey} xs={24} lg={12}> <Col key={capability.capabilityKey} xs={24} lg={12}>
<CapabilityCard capability={capability} /> <CapabilityCard capability={capability} />
@@ -23,12 +27,17 @@ export function CapabilitiesPage() {
</Row> </Row>
) : ( ) : (
<Card> <Card>
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前模板没有可配置能力。" /> <EmptyState
icon={<AppstoreOutlined />}
title="当前模板没有可配置能力"
description="能力的开关由品牌当前使用的行业模板决定;更换行业模板不在本版本范围内。"
action={<Button onClick={() => navigate("/admin/publication")}>查看模板与发布</Button>}
/>
</Card> </Card>
)} )}
<Typography.Text type="secondary" style={{ display: "block", marginTop: 16 }}> <p className="admin-page-header-description admin-offset-top">
技术信息仅用于排查问题,不作为运营判断依据。 技术信息仅用于排查问题,不作为运营判断依据。
</Typography.Text> </p>
</QueryState> </QueryState>
); );
} }
@@ -1,5 +1,7 @@
import { Alert, Button, Card, Input, Switch, Tag, Typography } from "antd"; import { Button, Card, Input, Space, Switch, Typography } from "antd";
import { useState } from "react"; import { useState } from "react";
import { ErrorNote } from "../../../components/QueryState.js";
import { StatusTag } from "../../../components/StatusTag.js";
import { useCapabilityMutation } from "../hooks/useCapabilityQueries.js"; import { useCapabilityMutation } from "../hooks/useCapabilityQueries.js";
import type { AdminCapability, CapabilityStatus } from "../types.js"; import type { AdminCapability, CapabilityStatus } from "../types.js";
import { CapabilityStatusControl, CapabilityStatusTag } from "./CapabilityStatusControl.js"; import { CapabilityStatusControl, CapabilityStatusTag } from "./CapabilityStatusControl.js";
@@ -27,10 +29,21 @@ function readSwitchValue(value: unknown): boolean {
return value === true; 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 }) { export function CapabilityCard({ capability }: { capability: AdminCapability }) {
const [status, setStatus] = useState<CapabilityStatus>(capability.status); const [status, setStatus] = useState<CapabilityStatus>(capability.status);
const [config, setConfig] = useState<Record<string, unknown>>(capability.config); const [config, setConfig] = useState<Record<string, unknown>>(capability.config);
const mutation = useCapabilityMutation(); const mutation = useCapabilityMutation();
const dirty = status !== capability.status || !sameConfig(config, capability.config ?? {});
const save = async () => { const save = async () => {
await mutation.mutateAsync({ await mutation.mutateAsync({
@@ -46,61 +59,61 @@ export function CapabilityCard({ capability }: { capability: AdminCapability })
return ( return (
<Card <Card
title={ title={
<span> <span className="admin-row-line">
{capability.displayName ?? "未命名能力"} {capability.displayName ?? "未命名能力"}
<Tag style={{ marginLeft: 8 }}>{sourceLabels[capability.source]}</Tag>
<CapabilityStatusTag status={status} /> <CapabilityStatusTag status={status} />
<StatusTag tone="neutral" label={sourceLabels[capability.source]} />
</span> </span>
} }
extra={ extra={
<Button type="primary" loading={mutation.isPending} onClick={() => void save()}> <Space>
保存草稿 {dirty ? <StatusTag tone="warning" label="有未保存修改" /> : null}
</Button> <Button
type={dirty ? "primary" : "default"}
disabled={!dirty}
loading={mutation.isPending}
onClick={() => void save()}
>
保存草稿
</Button>
</Space>
} }
> >
{mutation.isError ? ( {mutation.isError ? (
<Alert <div className="admin-offset-bottom">
type="error" <ErrorNote error={mutation.error} />
showIcon </div>
message="保存失败,已保留当前输入"
description={
mutation.error instanceof Error ? mutation.error.message : "请检查网络或稍后重试"
}
style={{ marginBottom: 16 }}
/>
) : null} ) : null}
{capability.description ? ( {capability.description ? (
<Typography.Paragraph>{capability.description}</Typography.Paragraph> <p className="admin-section-description">{capability.description}</p>
) : null} ) : null}
{capability.impact ? ( {capability.impact ? (
<Typography.Paragraph type="secondary">影响:{capability.impact}</Typography.Paragraph> <p className="admin-section-description">影响:{capability.impact}</p>
) : null} ) : null}
<div style={{ display: "grid", gap: 12 }}> <div className="admin-field-stack">
<div> <div>
<Typography.Text strong>运行状态</Typography.Text> <span className="admin-field-label">运行状态</span>
<div style={{ marginTop: 8 }}> <div className="admin-offset-top-sm">
<CapabilityStatusControl <CapabilityStatusControl
status={status} status={status}
onChange={setStatus} onChange={setStatus}
disabled={mutation.isPending} disabled={mutation.isPending}
/> />
</div> </div>
<Typography.Paragraph type="secondary" style={{ marginBottom: 0 }}> <p className="admin-section-description admin-flush">保存后进入草稿,发布后生效。</p>
保存后进入草稿,发布后生效。
</Typography.Paragraph>
{status === "disabled" && capability.disablePolicy ? ( {status === "disabled" && capability.disablePolicy ? (
<Typography.Paragraph type="warning" style={{ marginBottom: 0 }}> <p className="admin-section-description admin-flush admin-text-warning">
{disablePolicyLabels[capability.disablePolicy]} {disablePolicyLabels[capability.disablePolicy]}
</Typography.Paragraph> </p>
) : null} ) : null}
</div> </div>
{capability.configFields?.length ? ( {capability.configFields?.length ? (
<div> <div>
<Typography.Text strong>能力设置</Typography.Text> <span className="admin-field-label">能力设置</span>
<div style={{ display: "grid", gap: 12, marginTop: 8 }}> <div className="admin-field-stack admin-offset-top-sm">
{capability.configFields.map((field) => ( {capability.configFields.map((field) => (
<div key={field.key}> <div key={field.key}>
<Typography.Text>{field.label}</Typography.Text> <span className="admin-field-label">{field.label}</span>
{field.input === "switch" ? ( {field.input === "switch" ? (
<div> <div>
<Switch <Switch
@@ -1,5 +1,7 @@
import { Segmented, Space, Switch, Tag, Typography } from "antd"; import { Segmented, Space, Switch, Typography } from "antd";
import type { CapabilityStatus } from "../types.js"; import type { CapabilityStatus } from "../types.js";
import { StatusTag } from "../../../components/StatusTag.js";
import type { StatusTone } from "../../../components/StatusTag.js";
const statusLabels: Record<CapabilityStatus, string> = { const statusLabels: Record<CapabilityStatus, string> = {
enabled: "启用", enabled: "启用",
@@ -7,14 +9,14 @@ const statusLabels: Record<CapabilityStatus, string> = {
degraded: "降级", degraded: "降级",
}; };
const statusColors: Record<CapabilityStatus, string> = { const statusTones: Record<CapabilityStatus, StatusTone> = {
enabled: "green", enabled: "success",
disabled: "default", disabled: "neutral",
degraded: "orange", degraded: "warning",
}; };
export function CapabilityStatusTag({ status }: { status: CapabilityStatus }) { export function CapabilityStatusTag({ status }: { status: CapabilityStatus }) {
return <Tag color={statusColors[status]}>{statusLabels[status]}</Tag>; return <StatusTag tone={statusTones[status]} label={statusLabels[status]} />;
} }
export function CapabilityStatusControl({ export function CapabilityStatusControl({
@@ -1,20 +1,15 @@
import { import { Badge, Button, Descriptions, Drawer, Select, Space, Table, message, Input } from "antd";
Badge,
Button,
Card,
Descriptions,
Drawer,
Select,
Space,
Table,
Tag,
message,
Input,
} from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { AdminBooking, InquirySubmission } from "@personal-brand/api-client"; import type { AdminBooking, InquirySubmission } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js"; import { createApiClient } from "../../lib/api.js";
import { useState } from "react"; 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 statuses = ["received", "contacting", "confirmed", "completed", "cancelled"] as const;
const labels: Record<string, string> = { const labels: Record<string, string> = {
@@ -41,6 +36,20 @@ const inquiryLabels: Record<string, string> = {
closed: "已关闭", 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() { export function InquiriesPage() {
const client = createApiClient(); const client = createApiClient();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
@@ -94,192 +103,222 @@ export function InquiriesPage() {
onError: (error) => message.error(error instanceof Error ? error.message : "更新失败,请重试"), onError: (error) => message.error(error instanceof Error ? error.message : "更新失败,请重试"),
}); });
return ( return (
<Card <>
title="咨询记录" <AdminPageHeader title="咨询记录" description="查看访客提交的咨询和预约,并跟进处理进度。" />
extra={ <AdminSection
<Space> title="预约咨询"
<Select extra={
allowClear <Space>
placeholder="全部状态" <Select
style={{ width: 130 }} allowClear
value={status} placeholder="全部状态"
onChange={setStatus} className="admin-field-w-md"
options={statuses.map((value) => ({ value, label: labels[value] }))} value={status}
/> onChange={setStatus}
<Badge options={statuses.map((value) => ({ value, label: labels[value] }))}
count={ />
query.data?.filter((item) => !(item as AdminBooking & { isRead?: boolean }).isRead) <Badge
.length ?? 0 count={
} query.data?.filter((item) => !(item as AdminBooking & { isRead?: boolean }).isRead)
showZero .length ?? 0
/> }
</Space> 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}
> >
{detail.data && ( {query.isLoading && !query.data ? (
<Descriptions column={1} bordered size="small"> <TableSkeleton />
<Descriptions.Item label="编号">{detail.data.bookingNo}</Descriptions.Item> ) : (
<Descriptions.Item label="联系人">{detail.data.customerName}</Descriptions.Item> <Table
<Descriptions.Item label="状态"> rowKey="id"
{labels[detail.data.status] ?? detail.data.status} locale={{
</Descriptions.Item> emptyText: (
<Descriptions.Item label="提交时间"> <EmptyState
{new Date(detail.data.createdAt).toLocaleString("zh-CN")} compact
</Descriptions.Item> title="还没有预约咨询"
<Descriptions.Item label="管理员备注"> description="访客在小程序提交预约后,会出现在这里。"
{detail.data.adminNote || "暂无"} />
</Descriptions.Item> ),
</Descriptions> }}
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> <Drawer
<Card 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})` : ""}`} title={`动态咨询提交${submissions.data ? `(${submissions.data.length})` : ""}`}
style={{ marginTop: 24 }} description="按模板表单提交的咨询记录,字段随表单配置变化。"
extra={ extra={
<Button onClick={() => void submissions.refetch()} loading={submissions.isFetching}> <Button onClick={() => void submissions.refetch()} loading={submissions.isFetching}>
刷新提交记录 刷新提交记录
</Button> </Button>
} }
> >
{submissions.isError && ( {submissions.isError ? (
<Card type="inner" style={{ marginBottom: 16 }}> <ErrorNote error={submissions.error} onRetry={() => void submissions.refetch()} />
动态咨询提交加载失败: ) : null}
{submissions.error instanceof Error ? submissions.error.message : "未知错误"} <Space
<Button type="link" onClick={() => void submissions.refetch()}> className={`admin-offset-bottom-sm ${submissions.isError ? "admin-offset-top" : ""}`}
重试 >
</Button>
</Card>
)}
<Space style={{ marginBottom: 12 }}>
<Select <Select
allowClear allowClear
placeholder="动态咨询状态" placeholder="动态咨询状态"
style={{ width: 140 }} className="admin-field-w-md"
value={submissionStatus} value={submissionStatus}
onChange={setSubmissionStatus} onChange={setSubmissionStatus}
options={inquiryStatuses.map((value) => ({ value, label: inquiryLabels[value] }))} options={inquiryStatuses.map((value) => ({ value, label: inquiryLabels[value] }))}
/> />
</Space> </Space>
<Table<InquirySubmission> {submissions.isLoading && !submissions.data ? (
rowKey="id" <ListSkeleton rows={3} />
loading={submissions.isLoading} ) : (
dataSource={(submissions.data ?? []).filter( <Table<InquirySubmission>
(item) => !submissionStatus || item.status === submissionStatus, rowKey="id"
)} dataSource={(submissions.data ?? []).filter(
locale={{ emptyText: submissions.isLoading ? "加载中" : "暂无动态咨询提交" }} (item) => !submissionStatus || item.status === submissionStatus,
columns={[ )}
{ title: "表单", dataIndex: ["inquiryForm", "name"] }, locale={{
{ emptyText: (
title: "来源业务", <EmptyState
dataIndex: ["offering", "name"], compact
render: (value: string | null | undefined) => value || "品牌咨询", title="暂无动态咨询提交"
}, description="按模板表单提交的咨询会汇总在这里。"
{ />
title: "状态",
dataIndex: "status",
render: (value: InquirySubmission["status"]) => (
<Tag>{inquiryLabels[value] ?? value}</Tag>
), ),
}, }}
{ title: "版本", dataIndex: "formVersion", render: (value) => `v${value}` }, columns={[
{ { title: "表单", dataIndex: ["inquiryForm", "name"] },
title: "提交时间", {
dataIndex: "createdAt", title: "来源业务",
render: (value: string) => new Date(value).toLocaleString("zh-CN"), dataIndex: ["offering", "name"],
}, render: (value: string | null | undefined) => value || "品牌咨询",
{
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: "状态",
title: "跟进", dataIndex: "status",
render: (_: unknown, item: InquirySubmission) => ( render: (value: InquirySubmission["status"]) => (
<Space> <StatusTag
<Button size="small" onClick={() => setSelectedSubmission(item)}> tone={statusTones[value] ?? "neutral"}
查看 label={inquiryLabels[value] ?? value}
</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="备注" { title: "版本", dataIndex: "formVersion", render: (value) => `v${value}` },
defaultValue={item.adminNote ?? ""} {
onPressEnter={(event) => title: "提交时间",
updateSubmission.mutate({ dataIndex: "createdAt",
id: item.id, render: (value: string) => new Date(value).toLocaleString("zh-CN"),
status: item.status, },
adminNote: event.currentTarget.value, {
}) title: "内容",
} dataIndex: "values",
/> render: (value: Record<string, unknown>) => {
</Space> 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 <Drawer
title="动态咨询详情" title="动态咨询详情"
open={Boolean(selectedSubmission)} open={Boolean(selectedSubmission)}
@@ -287,7 +326,7 @@ export function InquiriesPage() {
width={520} width={520}
> >
{selectedSubmission && ( {selectedSubmission && (
<Descriptions column={1} bordered size="small"> <Descriptions className="admin-descriptions" column={1} size="small">
<Descriptions.Item label="表单"> <Descriptions.Item label="表单">
{selectedSubmission.inquiryForm?.name || "品牌咨询"} {selectedSubmission.inquiryForm?.name || "品牌咨询"}
</Descriptions.Item> </Descriptions.Item>
@@ -314,7 +353,7 @@ export function InquiriesPage() {
</Descriptions> </Descriptions>
)} )}
</Drawer> </Drawer>
</Card> </AdminSection>
</Card> </>
); );
} }
@@ -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 { useQueries, useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { createApiClient } from "../../lib/api.js"; import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js"; import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { QueryState } from "../../components/QueryState.js"; import { QueryState } from "../../components/QueryState.js";
import { MetricCard } from "../../components/MetricCard.js";
import { StatusTag } from "../../components/StatusTag.js";
export function OverviewPage() { export function OverviewPage() {
const navigate = useNavigate(); const navigate = useNavigate();
@@ -82,41 +84,32 @@ export function OverviewPage() {
title="品牌概览" title="品牌概览"
description="从这里检查品牌表达、信任内容和业务承接是否完整。" description="从这里检查品牌表达、信任内容和业务承接是否完整。"
/> />
<Space direction="vertical" size={24} style={{ width: "100%" }}> <div className="admin-stack">
<Card> <Card>
<Typography.Title level={3} style={{ marginTop: 0 }}> <h2 className="admin-brand-title">{brand?.name || "未命名品牌"}</h2>
{brand?.name || "未命名品牌"} <p className="admin-brand-tagline">{brand?.tagline || "还没有设置一句话定位"}</p>
</Typography.Title> <StatusTag
<Typography.Paragraph type="secondary"> tone="info"
{brand?.tagline || "还没有设置一句话定位"} label={`当前模板:${workspace?.templateContent?.displayName ?? "尚未安装模板"}`}
</Typography.Paragraph> />
<Tag color="blue">
当前模板:{workspace?.templateContent?.displayName ?? "尚未安装模板"}
</Tag>
</Card> </Card>
<Row gutter={[16, 16]}> <Row gutter={[16, 16]}>
<Col xs={24} sm={12} lg={6}> <Col xs={24} sm={8}>
<Card> <MetricCard
<Statistic label="信任证明"
title="信任证明" value={trust?.filter((item) => item.isPublished).length ?? 0}
value={trust?.filter((item) => item.isPublished).length ?? 0} suffix="条已发布"
suffix="条已发布" />
/>
</Card>
</Col> </Col>
<Col xs={24} sm={12} lg={6}> <Col xs={24} sm={8}>
<Card> <MetricCard
<Statistic label="业务展示内容"
title="业务展示内容" value={offerings?.filter((item) => item.isEnabled).length ?? 0}
value={offerings?.filter((item) => item.isEnabled).length ?? 0} suffix="项公开"
suffix="项公开" />
/>
</Card>
</Col> </Col>
<Col xs={24} sm={12} lg={6}> <Col xs={24} sm={8}>
<Card> <MetricCard label="咨询提交" value={submissions?.length ?? 0} suffix="条" />
<Statistic title="咨询提交" value={submissions?.length ?? 0} suffix="条" />
</Card>
</Col> </Col>
</Row> </Row>
<Row gutter={[16, 16]}> <Row gutter={[16, 16]}>
@@ -133,63 +126,57 @@ export function OverviewPage() {
percent={completionPercent} percent={completionPercent}
status={readiness.data?.ready ? "success" : "active"} 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 {readiness.data?.ready
? "当前草稿已满足发布条件,可以进入发布页上线。" ? "当前草稿已满足发布条件,可以进入发布页上线。"
: `还有 ${incompleteChecks.length} 项需要完善,完成后才能发布。`} : `还有 ${incompleteChecks.length} 项需要完善,完成后才能发布。`}
</Typography.Paragraph> </p>
{incompleteChecks.length > 0 && ( {incompleteChecks.length > 0 && (
<List <ul className="admin-list">
size="small" {incompleteChecks.slice(0, 4).map((item) => (
dataSource={incompleteChecks.slice(0, 4)} <li key={item.key} className="admin-row">
renderItem={(item) => ( <span className="admin-row-title">{item.label}</span>
<List.Item <Button
actions={[ type="link"
<Button size="small"
key={item.key} onClick={() => navigate(item.destination ?? "/admin/publication")}
type="link" >
size="small" 去处理
onClick={() => navigate(item.destination ?? "/admin/publication")} </Button>
> </li>
去处理 ))}
</Button>, </ul>
]}
>
{item.label}
</List.Item>
)}
/>
)} )}
</Card> </Card>
</Col> </Col>
<Col xs={24} lg={12}> <Col xs={24} lg={12}>
<Card title="品牌内容检查"> <Card title="品牌内容检查">
<List <ul className="admin-list">
dataSource={checks} {checks.map((item) => (
renderItem={(item) => ( <li key={item.key} className="admin-row">
<List.Item> <div className="admin-row-line">
<Space> <StatusTag
<Tag color={item.passed ? "success" : "default"}> tone={item.passed ? "success" : "neutral"}
{item.passed ? "已完成" : "待完善"} label={item.passed ? "已完成" : "待完善"}
</Tag> />
<span>{item.label}</span> <span className="admin-row-title">{item.label}</span>
{!item.passed && ( </div>
<Button {!item.passed ? (
type="link" <Button
size="small" type="link"
onClick={() => navigate(item.destination ?? "/admin/publication")} size="small"
> onClick={() => navigate(item.destination ?? "/admin/publication")}
去处理 >
</Button> 去处理
)} </Button>
</Space> ) : null}
</List.Item> </li>
)} ))}
/> </ul>
</Card> </Card>
</Col> </Col>
</Row> </Row>
</Space> </div>
</QueryState> </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 { useState } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
import { import {
Alert, Alert,
Button, Button,
Divider, Divider,
Empty,
Input, Input,
Modal, Modal,
Form,
Select, Select,
Space, Space,
Spin, Spin,
Tag, Tabs,
Typography, Typography,
message, message,
} from "antd"; } from "antd";
import type { BrandTemplateKey } from "@personal-brand/api-client"; import type { BrandTemplateKey } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js"; import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js"; import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { 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(); const client = createApiClient();
@@ -39,38 +46,32 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
const [confirmAction, setConfirmAction] = useState<"publish" | "revoke" | null>(null); const [confirmAction, setConfirmAction] = useState<"publish" | "revoke" | null>(null);
const [rollbackVersion, setRollbackVersion] = useState<number | null>(null); const [rollbackVersion, setRollbackVersion] = useState<number | null>(null);
const [note, setNote] = useState(""); const [note, setNote] = useState("");
const brand = useQuery({ const [activeTab, setActiveTab] = useState("content");
queryKey: ["publication-brand"], const [miniAppSettingsForm] = Form.useForm<MiniAppSettingsValues>();
queryFn: () => client.getAdminBrand(), const queries = usePublicationQueries(miniAppSettingsForm);
}); const {
const workspace = useQuery({ brand,
queryKey: ["publication-workspace"], workspace,
queryFn: () => client.getAdminWorkspace(), catalog,
}); sample,
const catalog = useQuery({ readiness,
queryKey: ["publication-catalog"], releases,
queryFn: () => client.listPublicTemplates(), miniAppReleases,
}); miniAppSettings,
const sample = useQuery({ templatePreview,
queryKey: ["publication-sample"], loading,
queryFn: () => client.previewAdminSampleContent(), error,
enabled: Boolean(workspace.data), retry,
}); } = queries;
const readiness = useQuery({
queryKey: ["publication-readiness"],
queryFn: () => client.getAdminReleaseReadiness(),
});
const releases = useQuery({
queryKey: ["publication-releases"],
queryFn: () => client.listAdminReleases(),
});
const refresh = () => { const refresh = () => {
for (const key of [ for (const key of [
"publication-brand", "publication-brand",
"publication-workspace", "publication-workspace",
"publication-sample", "publication-sample",
"publication-readiness", "publication-readiness",
"publication-template-preview",
"publication-releases", "publication-releases",
"publication-miniapp-releases",
"admin-shell-brand", "admin-shell-brand",
"admin-workspace", "admin-workspace",
"public-runtime-workspace", "public-runtime-workspace",
@@ -78,71 +79,28 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
void queryClient.invalidateQueries({ queryKey: [key] }); void queryClient.invalidateQueries({ queryKey: [key] });
} }
}; };
const install = useMutation({ const mutations = usePublicationMutations({
mutationFn: (key: BrandTemplateKey) => client.installAdminTemplate(key), refresh,
onSuccess: () => { brandConfig: brand.data?.config,
setIndustryTarget(null); onInstallClose: () => setIndustryTarget(null),
message.success("行业模板已安装"); onPublishClose: () => setConfirmAction(null),
refresh(); onNoteClear: () => setNote(""),
}, onRollbackClose: () => setRollbackVersion(null),
}); });
const selectVisual = useMutation({ const {
mutationFn: (key: string) => install,
client.updateAdminBrand({ upgradeTemplate,
config: { ...(brand.data?.config ?? {}), visualTemplateKey: key }, rollbackTemplate,
}), selectVisual,
onSuccess: () => { importSample,
message.success("视觉模板已保存到草稿"); publish,
refresh(); revoke,
}, rollback,
}); uploadLatestMiniAppRelease,
const importSample = useMutation({ saveMiniAppSettings,
mutationFn: () => client.importAdminSampleContent(), uploadMiniAppRelease,
onSuccess: ({ counts }) => { updateMiniAppStatus,
message.success( } = mutations;
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 industryKey = const industryKey =
workspace.data?.installations[0]?.templateKey ?? workspace.data?.installations[0]?.templateKey ??
workspace.data?.brand?.templateKey ?? workspace.data?.brand?.templateKey ??
@@ -168,187 +126,428 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
isEnabled: boolean; 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 ( return (
<QueryState loading={loading} error={error} onRetry={retry}> <QueryState loading={loading} error={error} onRetry={retry}>
<AdminPageHeader <AdminPageHeader
title="配置与发布" title="配置与发布"
description="编辑内容不会立即影响小程序;确认后统一发布当前品牌。" description="编辑内容不会立即影响小程序;确认后统一发布当前品牌。"
/> />
<Space direction="vertical" size={24} style={{ width: "100%" }}> <Tabs
<section> activeKey={activeTab}
<Typography.Title level={4}>1. 选择表达方式</Typography.Title> onChange={setActiveTab}
<Space wrap> items={[
<Select {
aria-label="行业模板" key: "content",
style={{ width: 220 }} label: "内容发布",
value={industryKey} children: contentTab,
disabled={!canManageTemplate || Boolean(workspace.data?.installations.length)} },
options={(catalog.data?.industries ?? []).map((item) => ({ { key: "miniapp", label: "小程序发布", children: null },
value: item.key, {
label: item.name, key: "settings",
}))} label: "小程序配置",
onChange={(key: BrandTemplateKey) => setIndustryTarget(key)} children:
/> activeTab === "settings" ? (
<Select <MiniAppSettingsTab
aria-label="视觉模板" form={miniAppSettingsForm}
style={{ width: 220 }} settings={miniAppSettings.data}
value={visualKey} saving={saveMiniAppSettings.isPending}
disabled={!canManageTemplate} error={saveMiniAppSettings.error}
loading={selectVisual.isPending} onSave={(values) => saveMiniAppSettings.mutate(values)}
options={visuals.map((item) => ({ value: item.key, label: item.name }))} />
onChange={(key) => selectVisual.mutate(key)} ) : null,
/> },
{canManageTemplate && ( ]}
<Button onClick={() => navigate("/admin/workspace")}>高级模板设置</Button> />
)} {activeTab === "content" && (
</Space> <div className="admin-stack">
{workspace.data?.installations.length ? ( <AdminSection
<Typography.Paragraph type="secondary" style={{ marginTop: 8 }}> title="选择表达方式"
当前品牌已安装主模板。模板版本与升级在高级设置中管理。 description="行业模板决定内容结构,视觉模板决定小程序的排版风格。"
</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>
<Space wrap> <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/brand")}>编辑小程序页面</Button>
<Button onClick={() => navigate("/admin/services")}>编辑业务展示和详情</Button> <Button onClick={() => navigate("/admin/services")}>编辑业务展示和详情</Button>
<Button onClick={() => navigate("/admin/trust")}>编辑信任证明</Button> <Button onClick={() => navigate("/admin/trust")}>编辑信任证明</Button>
</Space> </Space>
</Space> </AdminSection>
</section> <AdminSection
title="检查并发布"
<section> extra={
<Typography.Title level={4}>3. 检查并发布</Typography.Title> <Space wrap>
<Space wrap style={{ marginBottom: 12 }}> <StatusTag
<Tag color={currentRelease ? "green" : "default"}> tone={currentRelease ? "success" : "neutral"}
{currentRelease ? `已发布 v${currentRelease.version}` : "尚未发布"} label={currentRelease ? `已发布 v${currentRelease.version}` : "尚未发布"}
</Tag> />
<Button onClick={() => void readiness.refetch()}>重新检查</Button> <Button onClick={() => void readiness.refetch()}>重新检查</Button>
</Space> </Space>
<Space direction="vertical" style={{ width: "100%" }}> }
{(readiness.data?.checks ?? []).map((check) => ( >
<Space key={check.key}> <ul className="admin-list">
<Tag color={check.passed ? "success" : "warning"}> {(readiness.data?.checks ?? []).map((check) => (
{check.passed ? "已完成" : "待完善"} <li key={check.key} className="admin-row">
</Tag> <div className="admin-row-main">
<Typography.Text>{check.label}</Typography.Text> <div className="admin-row-line">
{check.help ? ( <StatusTag
<Typography.Text type="secondary">{check.help}</Typography.Text> tone={check.passed ? "success" : "warning"}
) : null} label={check.passed ? "已完成" : "待完善"}
{!check.passed && ( />
<Button <span className="admin-row-title">{check.label}</span>
type="link" {!check.passed && check.help ? (
onClick={() => <span className="admin-row-meta">{check.help}</span>
navigate(check.destination ?? destinations[check.key] ?? "/admin/overview") ) : null}
} </div>
> </div>
去处理 {!check.passed ? (
</Button> <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> >
<Space wrap style={{ marginTop: 16 }}> {miniAppReleases.data?.length ? (
<Button <div className="admin-stack admin-stack-tight">
type="primary" {miniAppReleases.data.map((task) => (
disabled={!readiness.data?.ready} <MiniAppReleaseCard
onClick={() => setConfirmAction("publish")} key={task.id}
> task={task}
发布当前草稿 uploading={uploadMiniAppRelease.isPending}
</Button> onUpload={() => uploadMiniAppRelease.mutate(task.id)}
{currentRelease && ( onStatusChange={(status) => updateMiniAppStatus.mutate({ id: task.id, status })}
<Button danger onClick={() => setConfirmAction("revoke")}> />
撤回当前版本 ))}
</Button> </div>
) : (
<EmptyState
compact
title="暂无小程序发布任务"
description="先发布品牌内容,再上传当前版本到微信。"
/>
)} )}
</Space> </AdminSection>
<MutationError error={publish.error || revoke.error} /> </div>
<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>
<Modal <Modal
title={confirmAction === "revoke" ? "确认撤回品牌" : "确认发布品牌"} title={confirmAction === "revoke" ? "确认撤回品牌" : "确认发布品牌"}
open={confirmAction !== null} open={confirmAction !== null}
onCancel={() => setConfirmAction(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} confirmLoading={publish.isPending || revoke.isPending}
okText={confirmAction === "revoke" ? "确认撤回" : "确认发布"} okText={confirmAction === "revoke" ? "确认撤回" : "确认发布"}
okButtonProps={{ danger: confirmAction === "revoke" }} okButtonProps={{ danger: confirmAction === "revoke" }}
@@ -359,7 +558,7 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
message="撤回后,小程序将显示品牌尚未发布,新的咨询和预约会停止受理。" message="撤回后,小程序将显示品牌尚未发布,新的咨询和预约会停止受理。"
/> />
) : ( ) : (
<Space direction="vertical" style={{ width: "100%" }}> <div className="admin-stack">
<Typography.Text>当前草稿将成为品牌新的公开版本。</Typography.Text> <Typography.Text>当前草稿将成为品牌新的公开版本。</Typography.Text>
<Input <Input
value={note} value={note}
@@ -367,7 +566,7 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
placeholder="发布备注(可选)" placeholder="发布备注(可选)"
maxLength={200} maxLength={200}
/> />
</Space> </div>
)} )}
</Modal> </Modal>
<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,
};
}
@@ -1,4 +1,4 @@
import { Alert, Button, Form, Input, Modal, Segmented, Select, Typography } from "antd"; import { Alert, Button, Form, Input, Modal, Segmented, Select } from "antd";
import type { import type {
Offering, Offering,
RuntimeWorkspace, RuntimeWorkspace,
@@ -103,7 +103,7 @@ export function OfferingEditorModal({
onFinish={onFinish} onFinish={onFinish}
> >
<div className="service-offering-editor__form-scroll"> <div className="service-offering-editor__form-scroll">
<Typography.Title level={5}>基础信息</Typography.Title> <h4 className="admin-subhead">基础信息</h4>
<Form.Item name="kind" label="类型" rules={[{ required: true }]}> <Form.Item name="kind" label="类型" rules={[{ required: true }]}>
<Select <Select
options={[ options={[
@@ -153,12 +153,12 @@ export function OfferingEditorModal({
</Form.Item> </Form.Item>
{activeTemplateFields.length ? ( {activeTemplateFields.length ? (
<div> <div>
<Typography.Title level={5}> <h4 className="admin-subhead">
{previewPage === "offerings" ? "列表展示字段" : "详情展示字段"} {previewPage === "offerings" ? "列表展示字段" : "详情展示字段"}
</Typography.Title> </h4>
<Typography.Paragraph type="secondary"> <p className="admin-section-description admin-offset-bottom">
这里只编辑左侧预览对应的字段;它们与小程序页面编辑的是同一份业务数据。 这里只编辑左侧预览对应的字段;它们与小程序页面编辑的是同一份业务数据。
</Typography.Paragraph> </p>
<RecordContentFields <RecordContentFields
section={{ section={{
...templateFieldSection, ...templateFieldSection,
@@ -1,6 +1,10 @@
import { Button, Popconfirm, Space, Table, Tag, Typography } from "antd"; import { Button, Popconfirm, Space, Table } from "antd";
import type { Offering } from "@personal-brand/api-client"; 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 { MutationError } from "../../components/QueryState.js";
import { StatusTag } from "../../components/StatusTag.js";
import type { useOfferingMutations } from "./use-offering-data.js"; import type { useOfferingMutations } from "./use-offering-data.js";
type OfferingsTableProps = { type OfferingsTableProps = {
@@ -36,22 +40,27 @@ export function OfferingsTable({
{ {
title: "业务类型", title: "业务类型",
dataIndex: "kind", dataIndex: "kind",
render: (value: unknown) => <Tag>{offeringKindLabels[String(value)] ?? String(value)}</Tag>, render: (value: unknown) => (
<StatusTag tone="neutral" label={offeringKindLabels[String(value)] ?? String(value)} />
),
}, },
{ title: "价格", dataIndex: "priceText" }, { title: "价格", dataIndex: "priceText" },
{ {
title: "状态", title: "状态",
dataIndex: "isEnabled", dataIndex: "isEnabled",
render: (value: boolean) => (value ? "已启用" : "已停用"), render: (value: boolean) => (
<StatusTag tone={value ? "success" : "neutral"} label={value ? "已启用" : "已停用"} />
),
}, },
{ {
title: "操作", title: "操作",
render: (_: unknown, item: Offering) => ( render: (_: unknown, item: Offering) => (
<Space> <Space>
<Button size="small" onClick={() => onEdit(item)}> <Button type="link" size="small" onClick={() => onEdit(item)}>
编辑详情 编辑详情
</Button> </Button>
<Button <Button
type="link"
size="small" size="small"
loading={toggleOffering.isPending && toggleOffering.variables?.id === item.id} loading={toggleOffering.isPending && toggleOffering.variables?.id === item.id}
onClick={() => toggleOffering.mutate({ id: item.id, isEnabled: !item.isEnabled })} onClick={() => toggleOffering.mutate({ id: item.id, isEnabled: !item.isEnabled })}
@@ -66,6 +75,7 @@ export function OfferingsTable({
cancelText="取消" cancelText="取消"
> >
<Button <Button
type="link"
danger danger
size="small" size="small"
loading={deleteOffering.isPending && deleteOffering.variables === item.id} loading={deleteOffering.isPending && deleteOffering.variables === item.id}
@@ -79,35 +89,36 @@ export function OfferingsTable({
]; ];
return ( return (
<section aria-label="业务提供项列表"> <AdminSection
<Space wrap style={{ marginBottom: 16 }}> title={`${pageLabel}中的内容`}
<Typography.Title level={5} style={{ margin: 0 }}> description={
{pageLabel}中的内容 detailSectionTitles.length
</Typography.Title> ? `编辑单项详情时,附加字段将用于:${detailSectionTitles.join("、")}。列表中的名称、说明、价格和封面也会显示在业务展示页。`
<Tag color="blue">已启用的项目会公开展示</Tag> : "已启用的项目会公开展示。"
</Space> }
{detailSectionTitles.length ? ( >
<Typography.Paragraph type="secondary"> {loading && items.length === 0 ? (
编辑单项详情时,附加字段将用于: <TableSkeleton />
{detailSectionTitles.join("、")} ) : (
。列表中的名称、说明、价格和封面也会显示在业务展示页。 <Table
</Typography.Paragraph> scroll={{ x: 760 }}
) : null} rowKey="id"
<Table dataSource={items}
scroll={{ x: 760 }} columns={columns}
rowKey="id" locale={{
loading={loading} emptyText: (
dataSource={items} <EmptyState
columns={columns} compact
/> title="还没有业务提供项"
{items.length === 0 && ( description="创建后,小程序业务展示页会优先读取这些内容。"
<Typography.Paragraph type="secondary"> />
还没有公开业务提供项。创建后,小程序服务页会优先读取这些内容。 ),
</Typography.Paragraph> }}
/>
)} )}
<MutationError error={saveError} /> <MutationError error={saveError} />
<MutationError error={toggleOffering.error} /> <MutationError error={toggleOffering.error} />
<MutationError error={deleteOffering.error} /> <MutationError error={deleteOffering.error} />
</section> </AdminSection>
); );
} }
@@ -11,7 +11,7 @@
display: flex; display: flex;
flex-direction: column; flex-direction: column;
height: 72vh; height: 72vh;
border: 1px solid #e5e7eb; border: 1px solid var(--admin-border);
border-radius: 12px; border-radius: 12px;
overflow: hidden; overflow: hidden;
} }
@@ -47,8 +47,8 @@
overflow-y: auto; overflow-y: auto;
padding: 20px 16px 24px; padding: 20px 16px 24px;
border-radius: 12px; border-radius: 12px;
background: #f8fafc; background: var(--admin-fill);
border: 1px solid #e5e7eb; border: 1px solid var(--admin-border);
} }
.service-offering-editor__form-scroll > .ant-typography:first-child { .service-offering-editor__form-scroll > .ant-typography:first-child {
@@ -62,7 +62,7 @@
.service-offering-editor__form-scroll .ant-typography h5.ant-typography { .service-offering-editor__form-scroll .ant-typography h5.ant-typography {
margin: 28px 0 4px; margin: 28px 0 4px;
padding-bottom: 8px; padding-bottom: 8px;
border-bottom: 1px solid #e5e7eb; border-bottom: 1px solid var(--admin-border);
} }
.service-offering-editor__form-scroll > .ant-typography-secondary { .service-offering-editor__form-scroll > .ant-typography-secondary {
@@ -92,7 +92,7 @@ export function ServicesPage() {
onRetry={retry} onRetry={retry}
> >
<AdminPageHeader <AdminPageHeader
title="小程序内容:业务展示与详情" title="业务提供项"
description={`在「${offeringPageLabel(workspace.data?.templateContent ?? undefined)}」管理访客能选择的服务、产品或案例;每项内容的补充资料会显示在对应的「${detailPageLabel(workspace.data?.templateContent ?? undefined)}」。`} description={`在「${offeringPageLabel(workspace.data?.templateContent ?? undefined)}」管理访客能选择的服务、产品或案例;每项内容的补充资料会显示在对应的「${detailPageLabel(workspace.data?.templateContent ?? undefined)}」。`}
extra={ extra={
<Button type="primary" onClick={() => editor.beginOffering()}> <Button type="primary" onClick={() => editor.beginOffering()}>
@@ -7,7 +7,7 @@ import {
applyPresentationValues, applyPresentationValues,
presentationFieldName, presentationFieldName,
readPresentationValue, readPresentationValue,
} from "../brand/presentation-bindings.js"; } from "../../lib/presentation/presentation-bindings.js";
export type OfferingFormValues = Record<string, unknown>; export type OfferingFormValues = Record<string, unknown>;
@@ -5,7 +5,7 @@ import type {
TemplateAdminField, TemplateAdminField,
} from "@personal-brand/api-client"; } from "@personal-brand/api-client";
import type { PreviewTarget } from "../brand/preview-selection.js"; import type { PreviewTarget } from "../brand/preview-selection.js";
import { applyPresentationValues } from "../brand/presentation-bindings.js"; import { applyPresentationValues } from "../../lib/presentation/presentation-bindings.js";
export function previewTargetsByPage( export function previewTargetsByPage(
sections: AdminTemplateContent["admin"]["sections"], sections: AdminTemplateContent["admin"]["sections"],
+19 -19
View File
@@ -1,23 +1,12 @@
import { import { Alert, Button, Card, Form, Input, Modal, Select, Space, Table, message } from "antd";
Alert,
Button,
Card,
Form,
Input,
Modal,
Select,
Space,
Table,
Tag,
Typography,
message,
} from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { AdminBrandMember } from "@personal-brand/api-client"; import type { AdminBrandMember } from "@personal-brand/api-client";
import { useState } from "react"; import { useState } from "react";
import { createApiClient } from "../../lib/api.js"; import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js"; import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { MutationError, QueryState } from "../../components/QueryState.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> = { const roleLabels: Record<string, string> = {
owner: "负责人", owner: "负责人",
@@ -81,14 +70,22 @@ export function MembersPage() {
<Alert <Alert
type="info" type="info"
showIcon showIcon
className="admin-offset-bottom"
message="请将初始账号和密码安全地交给成员" message="请将初始账号和密码安全地交给成员"
description="当前采用负责人手动添加方式;系统不会再次显示成员初始密码。" description="当前采用负责人手动添加方式;系统不会再次显示成员初始密码。"
style={{ marginBottom: 16 }}
/> />
<Table <Table
rowKey="id" rowKey="id"
loading={members.isLoading}
dataSource={members.data ?? []} dataSource={members.data ?? []}
locale={{
emptyText: (
<EmptyState
compact
title="还没有其他成员"
description="添加协作者后,他们可以按角色维护当前品牌。"
/>
),
}}
columns={[ columns={[
{ {
title: "成员", title: "成员",
@@ -127,9 +124,12 @@ export function MembersPage() {
title: "说明", title: "说明",
render: (_: unknown, item: AdminBrandMember) => ( render: (_: unknown, item: AdminBrandMember) => (
<Space> <Space>
<Tag>{roleLabels[item.role] ?? item.role}</Tag> <StatusTag
tone={item.role === "owner" ? "info" : "neutral"}
label={roleLabels[item.role] ?? item.role}
/>
{!item.adminUser.isEnabled ? ( {!item.adminUser.isEnabled ? (
<Typography.Text type="danger">账号已停用</Typography.Text> <StatusTag tone="warning" label="账号已停用" />
) : null} ) : null}
</Space> </Space>
), ),
@@ -148,7 +148,7 @@ export function MembersPage() {
}} }}
onOk={() => addForm.submit()} onOk={() => addForm.submit()}
confirmLoading={create.isPending} confirmLoading={create.isPending}
destroyOnClose destroyOnHidden
> >
<Form <Form
form={addForm} form={addForm}
@@ -1,14 +1,17 @@
import { Button, Divider, Form, Typography } from "antd"; import { Button, Form } from "antd";
import { AdminPageHeader } from "../../components/AdminPageHeader.js"; import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { AdminSection } from "../../components/AdminSection.js";
import { QueryState } from "../../components/QueryState.js"; import { QueryState } from "../../components/QueryState.js";
import { StatusTag } from "../../components/StatusTag.js";
import { TrustContentEditorModal } from "./components/TrustContentEditorModal.js"; import { TrustContentEditorModal } from "./components/TrustContentEditorModal.js";
import { TrustContentTable } from "./components/TrustContentTable.js"; import { TrustContentList } from "./components/TrustContentList.js";
import { TrustRequirementsList } from "./components/TrustRequirementsList.js"; import { TrustRequirementsList } from "./components/TrustRequirementsList.js";
import type { TrustTypeOption } from "./domain/trust-content-domain.js"; import type { TrustTypeOption } from "./domain/trust-content-domain.js";
import { import {
createTrustPageLabelResolver, createTrustPageLabelResolver,
groupTrustContentByType, groupTrustContentByType,
selectTrustTypeOptions, selectTrustTypeOptions,
sortTrustContentByTypeOrder,
} from "./domain/trust-content-domain.js"; } from "./domain/trust-content-domain.js";
import { useTrustContentEditor } from "./hooks/useTrustContentEditor.js"; import { useTrustContentEditor } from "./hooks/useTrustContentEditor.js";
import { useTrustContentQueries } from "./hooks/useTrustContentQueries.js"; import { useTrustContentQueries } from "./hooks/useTrustContentQueries.js";
@@ -17,7 +20,8 @@ export function TrustContentPage() {
const { query, workspace } = useTrustContentQueries(); const { query, workspace } = useTrustContentQueries();
const availableTypes = selectTrustTypeOptions(workspace.data?.templateContent?.trustContentTypes); const availableTypes = selectTrustTypeOptions(workspace.data?.templateContent?.trustContentTypes);
const pageLabel = createTrustPageLabelResolver(workspace.data?.templateContent?.navigation); const pageLabel = createTrustPageLabelResolver(workspace.data?.templateContent?.navigation);
const contentByType = groupTrustContentByType(query.data ?? []); const items = sortTrustContentByTypeOrder(query.data ?? [], availableTypes);
const contentByType = groupTrustContentByType(items);
const firstMissingRequiredType = const firstMissingRequiredType =
availableTypes.find((item) => item.required && !contentByType.has(item.type))?.type ?? availableTypes.find((item) => item.required && !contentByType.has(item.type))?.type ??
availableTypes[0]?.type ?? availableTypes[0]?.type ??
@@ -53,37 +57,42 @@ export function TrustContentPage() {
onRetry={() => void Promise.all([query.refetch(), workspace.refetch()])} onRetry={() => void Promise.all([query.refetch(), workspace.refetch()])}
> >
<AdminPageHeader <AdminPageHeader
title="小程序内容:品牌介绍与信任" title="信任内容"
description={`填写真实的经历、案例、资历、流程和服务说明。这些内容会显示在${trustPlacement};保存后需发布品牌,小程序才会更新。`} description={`填写真实的经历、案例、资历、流程与服务说明,发布品牌后即会展示在${trustPlacement}。`}
extra={ extra={
<Button type="primary" onClick={() => begin()}> <Button type="primary" onClick={() => begin()}>
添加品牌内容 添加品牌内容
</Button> </Button>
} }
/> />
<section aria-labelledby="trust-requirements-title"> <AdminSection
<Typography.Title id="trust-requirements-title" level={5}> title="当前模板需要配置的内容"
当前模板需要配置的内容 description="标记为「发布必填」的项目需要填写完整后,才能发布小程序。"
</Typography.Title> >
<Typography.Paragraph type="secondary">
标记为“发布必填”的项目需要填写完整后,才能发布小程序。
</Typography.Paragraph>
<TrustRequirementsList <TrustRequirementsList
availableTypes={availableTypes} availableTypes={availableTypes}
contentByType={contentByType} contentByType={contentByType}
items={query.data ?? []} items={items}
pageLabel={pageLabel}
onEdit={begin} onEdit={begin}
/> />
</section> </AdminSection>
<Divider /> <AdminSection
<TrustContentTable title="已配置的品牌内容"
availableTypes={availableTypes} description="同一类型可以保存多条;标记为草稿的内容不会随品牌发布展示。"
items={query.data ?? []} extra={<StatusTag tone="info" label={`共 ${items.length} 条`} />}
removeError={remove.error} >
removePending={remove.isPending} <TrustContentList
onEdit={(item) => begin(item)} availableTypes={availableTypes}
onDelete={(id) => remove.mutate(id)} 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 <TrustContentEditorModal
availableTypes={availableTypes} availableTypes={availableTypes}
editing={editing} editing={editing}
@@ -1,4 +1,4 @@
import { Form, Input, Modal, Select, Typography } from "antd"; import { Form, Input, Modal, Select } from "antd";
import type { FormInstance } from "antd"; import type { FormInstance } from "antd";
import type { TrustContent, TrustContentInput } from "@personal-brand/api-client"; import type { TrustContent, TrustContentInput } from "@personal-brand/api-client";
import { ImageUrlField } from "../../../components/ImageUrlField.js"; import { ImageUrlField } from "../../../components/ImageUrlField.js";
@@ -36,7 +36,7 @@ export function TrustContentEditorModal({
onCancel={onCancel} onCancel={onCancel}
onOk={() => form.submit()} onOk={() => form.submit()}
confirmLoading={savePending} confirmLoading={savePending}
destroyOnClose destroyOnHidden
> >
<Form <Form
form={form} form={form}
@@ -49,9 +49,9 @@ export function TrustContentEditorModal({
/> />
</Form.Item> </Form.Item>
{selectedTypeMeta?.pages?.length ? ( {selectedTypeMeta?.pages?.length ? (
<Typography.Paragraph type="secondary"> <p className="admin-section-description admin-offset-bottom">
这类内容会显示在:{selectedTypeMeta.pages.map(pageLabel).join("、")} 这类内容会显示在:{selectedTypeMeta.pages.map(pageLabel).join("、")}
</Typography.Paragraph> </p>
) : null} ) : null}
<Form.Item <Form.Item
name="title" name="title"
@@ -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>
);
}
@@ -1,77 +0,0 @@
import { Button, Popconfirm, Space, Table, Tag } from "antd";
import type { TrustContent } from "@personal-brand/api-client";
import type { TrustTypeOption } from "../domain/trust-content-domain.js";
import { getTrustContentPreview } from "../domain/trust-content-domain.js";
import { MutationError } from "../../../components/QueryState.js";
export function TrustContentTable({
availableTypes,
items,
removeError,
removePending,
onEdit,
onDelete,
}: {
availableTypes: TrustTypeOption[];
items: TrustContent[];
removeError: unknown;
removePending: boolean;
onEdit: (item: TrustContent) => void;
onDelete: (id: string) => void;
}) {
return (
<section aria-label="已配置的品牌内容">
<Table
rowKey="id"
dataSource={items}
locale={{ emptyText: "还没有品牌内容,请先按上方模板要求添加。" }}
columns={[
{
title: "内容类型",
dataIndex: "type",
render: (value) => (
<Tag>{availableTypes.find((item) => item.type === value)?.label ?? value}</Tag>
),
},
{ title: "标题", dataIndex: "title" },
{
title: "内容预览",
ellipsis: { showTitle: true },
render: (_value: unknown, item: TrustContent) =>
getTrustContentPreview(
item,
availableTypes.find((type) => type.type === item.type),
),
},
{
title: "发布状态",
dataIndex: "isPublished",
render: (value) => (
<Tag color={value ? "success" : "default"}>{value ? "随发布展示" : "草稿"}</Tag>
),
},
{
title: "操作",
render: (_: unknown, item: TrustContent) => (
<Space>
<Button size="small" onClick={() => onEdit(item)}>
编辑
</Button>
<Popconfirm
title="确认删除这条信任内容?"
description="删除后需发布品牌,才会更新小程序展示。"
onConfirm={() => onDelete(item.id)}
>
<Button size="small" danger loading={removePending}>
删除
</Button>
</Popconfirm>
</Space>
),
},
]}
/>
<MutationError error={removeError} />
</section>
);
}
@@ -0,0 +1,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 />}</>;
}
@@ -1,65 +1,73 @@
import { Button, List, Space, Tag, Typography } from "antd"; import { Button } from "antd";
import { isTrustContentComplete } from "@personal-brand/api-client"; import { isTrustContentComplete } from "@personal-brand/api-client";
import type { TrustContent } from "@personal-brand/api-client"; import type { TrustContent } from "@personal-brand/api-client";
import type { TrustTypeOption } from "../domain/trust-content-domain.js"; import type { TrustTypeOption } from "../domain/trust-content-domain.js";
import { StatusTag } from "../../../components/StatusTag.js";
export function TrustRequirementsList({ export function TrustRequirementsList({
availableTypes, availableTypes,
contentByType, contentByType,
items, items,
pageLabel,
onEdit, onEdit,
}: { }: {
availableTypes: TrustTypeOption[]; availableTypes: TrustTypeOption[];
contentByType: Map<string, TrustContent>; contentByType: Map<string, TrustContent>;
items: TrustContent[]; items: TrustContent[];
pageLabel: (page: string) => string;
onEdit: (item?: TrustContent, type?: string) => void; onEdit: (item?: TrustContent, type?: string) => void;
}) { }) {
return ( return (
<List <ul className="admin-list">
size="small" {availableTypes.map((item) => {
dataSource={availableTypes}
renderItem={(item) => {
const content = contentByType.get(item.type); const content = contentByType.get(item.type);
const publishedCount = items.filter( const publishedCount = items.filter(
(record) => record.type === item.type && record.isPublished, (record) => record.type === item.type && record.isPublished,
).length; ).length;
const configuredCount = items.filter((record) => record.type === item.type).length;
const tooMany = const tooMany =
item.maxPublishedItems !== undefined && publishedCount > item.maxPublishedItems; item.maxPublishedItems !== undefined && publishedCount > item.maxPublishedItems;
const complete = Boolean(content && isTrustContentComplete(content, item) && !tooMany); const complete = Boolean(content && isTrustContentComplete(content, item) && !tooMany);
return ( return (
<List.Item <li key={item.type} className="admin-row">
actions={[ <div className="admin-row-main">
<Button <div className="admin-row-line">
key={item.type} <span className="admin-row-title">{item.label}</span>
type="link" {item.required ? <StatusTag tone="warning" label="发布必填" /> : null}
size="small" <StatusTag
onClick={() => (content ? onEdit(content) : onEdit(undefined, item.type))} tone={tooMany ? "error" : complete ? "success" : "neutral"}
> label={
{content ? "编辑" : "新增"} tooMany
</Button>, ? `公开内容过多(${publishedCount} 条)`
]} : complete
> ? "内容完整"
<Space wrap> : content
<Typography.Text strong>{item.label}</Typography.Text> ? "需要完善"
{item.required && <Tag color="orange">发布必填</Tag>} : "尚未填写"
{(item.pages ?? []).map((page) => ( }
<Tag key={page}>{page}</Tag> />
))} {configuredCount > 1 ? (
<Tag color={complete ? "success" : "default"}> <span className="admin-row-meta">已配置 {configuredCount} 条</span>
{tooMany ) : null}
? `公开内容过多(${publishedCount} 条)` {(item.pages ?? []).map((page) => (
: complete <span key={page} className="admin-row-meta">
? "内容完整" {pageLabel(page)}
: content </span>
? "需要完善" ))}
: "尚未填写"} </div>
</Tag> {item.help ? <p className="admin-row-help">{item.help}</p> : null}
{item.help && <Typography.Text type="secondary">{item.help}</Typography.Text>} </div>
</Space> <Button
</List.Item> type="link"
size="small"
onClick={() => (content ? onEdit(content) : onEdit(undefined, item.type))}
>
{content ? "编辑" : "新增"}
</Button>
</li>
); );
}} })}
/> </ul>
); );
} }
@@ -65,8 +65,10 @@ export const fallbackTrustTypes: TrustTypeOption[] = fallbackTypeSeeds.map(
const pageLabels: Record<string, string> = { const pageLabels: Record<string, string> = {
home: "首页", home: "首页",
offerings: "业务展示页", offerings: "业务展示页",
service: "服务介绍页",
detail: "详情页", detail: "详情页",
profile: "主理人页", profile: "主理人页",
inquiry: "咨询页",
}; };
export function createTrustPageLabelResolver(navigation?: Array<{ page: string; label: string }>) { export function createTrustPageLabelResolver(navigation?: Array<{ page: string; label: string }>) {
@@ -100,18 +102,51 @@ export function groupTrustContentByType(items: TrustContent[]) {
export function getTrustContentPreview(item: TrustContent, typeMeta?: TrustTypeOption): string { export function getTrustContentPreview(item: TrustContent, typeMeta?: TrustTypeOption): string {
if (typeMeta?.hideStandardFields?.includes("content")) { if (typeMeta?.hideStandardFields?.includes("content")) {
return ( const fragments =
typeMeta.configFields typeMeta.configFields?.flatMap((field) => {
?.flatMap((field) => { const value = item.config?.[field.key];
const value = item.config?.[field.key]; if (Array.isArray(value)) {
if (Array.isArray(value)) { return value.length ? [`${field.label}:${value.length} 项`] : [];
return value.length ? [`${field.label}:${value.length} 项`] : []; }
} if (typeof value !== "string") return [];
return typeof value === "string" && value.trim() ? [`${field.label}:${value}`] : []; const text = value.trim();
}) return text ? [`${field.label}:${stripFieldLabel(field.label, text)}`] : [];
.join(";") || "尚未填写区块内容" }) ?? [];
); if (!fragments.length) return "尚未填写区块内容";
return fragments.length > 3 ? `${fragments.slice(0, 3).join(";")}…` : fragments.join(";");
} }
return item.summary || item.content || "未填写"; 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");
});
}
@@ -1,23 +1,15 @@
import { Button, Card, Form, Input, Modal, Select, Space, Table, Tag, Typography } from "antd";
import { useNavigate } from "react-router-dom";
import { ApiClientError } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import type {
BrandFieldDefinition,
BrandTemplateKey,
InquiryForm,
} from "@personal-brand/api-client";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react"; import { useState } from "react";
import { import { useQueryClient } from "@tanstack/react-query";
useWorkspaceQueries, import { Button, Card, Form, Input, Modal, Select, Space, Table } from "antd";
useTemplateMutations, import type { BrandFieldDefinition, InquiryForm } from "@personal-brand/api-client";
useFieldMutations,
useInquiryFormMutations,
} from "./workspace-mutations.js";
import { supportsIndustry, type IndustryTarget } from "./workspace-templates.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js"; import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { MutationError } from "../../components/QueryState.js"; import { AdminSection } from "../../components/AdminSection.js";
import { EmptyState } from "../../components/EmptyState.js";
import { MutationError, QueryState } from "../../components/QueryState.js";
import { StatusTag } from "../../components/StatusTag.js";
import { ListSkeleton } from "../../components/TableSkeleton.js";
import { useFieldMutations, useInquiryFormMutations } from "./workspace-mutations.js";
import { useFormWorkspaceQueries } from "./workspace-queries.js";
export const inquiryFieldTypes = [ export const inquiryFieldTypes = [
{ value: "text", label: "简短文字" }, { value: "text", label: "简短文字" },
@@ -31,6 +23,20 @@ export const inquiryFieldTypes = [
{ value: "multi-select", label: "多项选择" }, { value: "multi-select", label: "多项选择" },
]; ];
const fieldScopes = [
{ value: "profile", label: "品牌资料" },
{ value: "service", label: "业务提供项" },
{ value: "inquiry", label: "咨询表单" },
];
function fieldTypeLabel(type: unknown): string {
return inquiryFieldTypes.find((item) => item.value === type)?.label ?? "自定义";
}
function fieldScopeLabel(scope: unknown): string {
return fieldScopes.find((item) => item.value === scope)?.label ?? "其他";
}
export function readOptionLabel(option: unknown): string { export function readOptionLabel(option: unknown): string {
const value = option as { label?: unknown } | null | undefined; const value = option as { label?: unknown } | null | undefined;
return typeof value?.label === "string" ? value.label : ""; return typeof value?.label === "string" ? value.label : "";
@@ -44,16 +50,12 @@ export function normalizeOptionLabels(options: unknown): Array<{ label: string;
} }
export function WorkspacePage() { export function WorkspacePage() {
const navigate = useNavigate();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const { workspace, forms } = useFormWorkspaceQueries();
const [fieldOpen, setFieldOpen] = useState(false); const [fieldOpen, setFieldOpen] = useState(false);
const [formOpen, setFormOpen] = useState(false); const [formOpen, setFormOpen] = useState(false);
const [editingForm, setEditingForm] = useState<InquiryForm | null>(null); const [editingForm, setEditingForm] = useState<InquiryForm | null>(null);
const [visualTarget, setVisualTarget] = useState<string | null>(null); const [fieldForm] = Form.useForm<Record<string, unknown>>();
const [industryTarget, setIndustryTarget] = useState<IndustryTarget | null>(null);
const [previewIndustry, setPreviewIndustry] = useState<BrandTemplateKey | null>(null);
const [previewVisual, setPreviewVisual] = useState<string | null>(null);
const [form] = Form.useForm<Record<string, unknown>>();
const [inquiryForm] = Form.useForm<Record<string, unknown>>(); const [inquiryForm] = Form.useForm<Record<string, unknown>>();
const openNewInquiryForm = () => { const openNewInquiryForm = () => {
setEditingForm(null); setEditingForm(null);
@@ -68,40 +70,8 @@ export function WorkspacePage() {
}); });
setFormOpen(true); setFormOpen(true);
}; };
const { query, runtimeQuery, templateCatalog, forms, templatePreview } = useWorkspaceQueries();
const previewIndustryKey =
previewIndustry ??
query.data?.brand.templateKey ??
query.data?.installations[0]?.templateKey ??
templateCatalog.data?.industries[0]?.key;
const previewVisualKey =
previewVisual ??
runtimeQuery.data?.visualTemplate?.key ??
(templateCatalog.data?.visuals ?? []).find((visual) =>
supportsIndustry(visual, previewIndustryKey ?? ""),
)?.key;
const combinationPreview = useQuery({
queryKey: ["template-combination-preview", previewIndustryKey, previewVisualKey],
queryFn: () =>
createApiClient().previewPublicTemplateCombination(
previewIndustryKey ?? "",
previewVisualKey ?? "",
),
enabled: Boolean(templateCatalog.data && previewIndustryKey && previewVisualKey),
});
const compatibleVisuals = (templateCatalog.data?.visuals ?? []).filter((visual) =>
supportsIndustry(visual, query.data?.brand?.templateKey ?? ""),
);
const { visualTemplate, rollbackVisual, install, upgrade, rollback } = useTemplateMutations({
runtimeConfig: runtimeQuery.data?.brand?.config ?? undefined,
queryClient,
});
const visualHistory = useQuery({
queryKey: ["visual-template-history"],
queryFn: () => createApiClient().getAdminVisualTemplateHistory(),
});
const { createField, removeField } = useFieldMutations({ const { createField, removeField } = useFieldMutations({
form, form: fieldForm,
queryClient, queryClient,
onClose: () => setFieldOpen(false), onClose: () => setFieldOpen(false),
}); });
@@ -113,389 +83,131 @@ export function WorkspacePage() {
setEditingForm(null); setEditingForm(null);
}, },
}); });
if (query.isLoading) return <Card loading />;
if (query.isError || !query.data) {
const errorStatus =
query.error instanceof ApiClientError
? query.error.status
: (query.error as { status?: number } | null)?.status;
const expired = errorStatus === 401;
return (
<Card
title={expired ? "登录状态已失效" : "工作空间加载失败"}
extra={
expired ? (
<Button
type="primary"
onClick={() => window.dispatchEvent(new Event("admin-auth-expired"))}
>
重新登录
</Button>
) : (
<Button onClick={() => void query.refetch()}>重新请求</Button>
)
}
>
{expired
? "请重新登录后再访问工作空间。"
: query.error instanceof Error
? query.error.message
: "请检查 API 服务后刷新重试。"}
</Card>
);
}
const { fields, installations } = query.data;
return ( return (
<Space direction="vertical" size="large" style={{ width: "100%" }}> <QueryState
loading={workspace.isLoading || forms.isLoading}
error={workspace.error || forms.error}
onRetry={() => void Promise.all([workspace.refetch(), forms.refetch()])}
>
<AdminPageHeader <AdminPageHeader
title="模板与表单设置" title="咨询表单与字段"
description="日常小程序内容请从页面配置、业务展示和信任证明进入;这里主要管理模板、咨询入口和负责人设置。" description="这里决定客户在小程序里能提交什么。保存后需在“配置与发布”发布,小程序才会更新。"
/> />
<Card title="先完成日常配置" style={{ marginBottom: 24 }}> <AdminSection
<Typography.Paragraph type="secondary"> title="咨询表单"
下面这些入口面向日常经营,不需要理解模板或技术设置。完成后回到“配置与发布”统一检查并上线。 description="每份表单对应小程序里的一个咨询入口;字段与选项由你在这里维护。"
</Typography.Paragraph>
<Space wrap>
<Button onClick={() => navigate("/admin/brand")}>配置小程序页面</Button>
<Button onClick={() => navigate("/admin/services")}>添加业务展示内容</Button>
<Button onClick={() => navigate("/admin/trust")}>补充信任证明</Button>
<Button type="primary" onClick={() => navigate("/admin/publication")}>
检查并发布
</Button>
</Space>
</Card>
<Card title="小程序当前状态" loading={runtimeQuery.isLoading}>
{runtimeQuery.isError ? (
<Typography.Text type="danger">公开运行时工作空间暂时无法加载。</Typography.Text>
) : (
<Space direction="vertical" style={{ width: "100%" }}>
<Space wrap>
<Tag color="green">小程序数据已同步</Tag>
<Tag>公开业务 {runtimeQuery.data?.offerings?.length ?? 0} 项</Tag>
<Tag>已启用能力 {runtimeQuery.data?.capabilities?.length ?? 0} 项</Tag>
</Space>
<Typography.Paragraph type="secondary" style={{ marginBottom: 0 }}>
小程序和后台预览会使用同一份已发布内容。这里的能力由当前模板自动提供,通常不需要手动调整。
</Typography.Paragraph>
<Space direction="vertical" style={{ width: "100%" }}>
<Typography.Text strong>已启用的服务能力</Typography.Text>
{(runtimeQuery.data?.plugins ?? []).map((plugin) => (
<Card key={plugin.key} size="small">
<Space wrap>
<Typography.Text strong>{plugin.displayName}</Typography.Text>
<Tag color={plugin.status === "enabled" ? "green" : "orange"}>
{plugin.status}
</Tag>
</Space>
<Typography.Paragraph type="secondary" style={{ margin: "8px 0 0" }}>
这项能力已接入当前小程序流程,无需单独配置技术参数。
</Typography.Paragraph>
</Card>
))}
{!runtimeQuery.data?.plugins?.length && (
<Typography.Text type="secondary">当前模板未启用能力插件。</Typography.Text>
)}
</Space>
<Space wrap>
<Typography.Text strong>视觉模板</Typography.Text>
<Select
value={runtimeQuery.data?.visualTemplate?.key}
loading={visualTemplate.isPending}
onChange={(key) => setVisualTarget(key ?? null)}
options={[
...compatibleVisuals.map((visual) => ({ value: visual.key, label: visual.name })),
]}
/>
{runtimeQuery.data?.visualTemplate && (
<Tag>
v{runtimeQuery.data.visualTemplate.version} ·{" "}
{Object.values(runtimeQuery.data.visualTemplate.variants).join(" / ")}
</Tag>
)}
</Space>
<MutationError error={visualTemplate.error} />
<Space direction="vertical" style={{ width: "100%" }}>
<Typography.Text strong>视觉模板切换历史</Typography.Text>
{visualHistory.data?.history.length ? (
visualHistory.data.history.map((item) => (
<Tag key={`${item.visualTemplateKey}-${item.savedAt}`}>
{item.visualTemplateKey} · {item.savedAt}
</Tag>
))
) : (
<Typography.Text type="secondary">暂无历史版本</Typography.Text>
)}
{visualHistory.data?.history.length ? (
<Button
danger
size="small"
onClick={() => rollbackVisual.mutate()}
loading={rollbackVisual.isPending}
>
回滚上一版视觉模板
</Button>
) : null}
<MutationError error={rollbackVisual.error} />
</Space>
<Space direction="vertical" style={{ width: "100%" }}>
<Typography.Text strong>可用视觉模板</Typography.Text>
<Space wrap>
{compatibleVisuals.map((visual) => (
<Card key={visual.key} size="small" style={{ width: 260 }}>
<Typography.Text strong>{visual.name}</Typography.Text>
<Typography.Paragraph type="secondary" ellipsis={{ rows: 2 }}>
{visual.description}
</Typography.Paragraph>
<Space wrap>
{Object.entries(visual.theme.colors).map(([name, color]) => (
<Tag key={name} color={color.startsWith("#") ? "default" : "blue"}>
{name}
</Tag>
))}
</Space>
<Typography.Paragraph
type="secondary"
style={{ marginTop: 12, marginBottom: 0 }}
>
{Object.values(visual.variants).join(" / ")}
</Typography.Paragraph>
</Card>
))}
</Space>
</Space>
<Modal
title="确认切换视觉模板"
open={visualTarget !== null}
onCancel={() => setVisualTarget(null)}
onOk={() => {
if (visualTarget) visualTemplate.mutate(visualTarget);
setVisualTarget(null);
}}
confirmLoading={visualTemplate.isPending}
>
<Typography.Paragraph>
当前模板:{runtimeQuery.data?.visualTemplate?.name ?? "林境建筑画册"}
</Typography.Paragraph>
<Typography.Paragraph>目标模板:林境建筑画册</Typography.Paragraph>
<Typography.Paragraph type="secondary">
只会替换视觉主题和模块变体,不会覆盖品牌内容、业务提供项或咨询记录。
</Typography.Paragraph>
</Modal>
</Space>
)}
</Card>
<Card
title="行业模板"
extra={
<Space>
{(templateCatalog.data?.industries ?? []).map((item) => (
<Button
key={item.key}
onClick={() => setIndustryTarget(item)}
loading={install.isPending}
>
安装{item.name}
</Button>
))}
</Space>
}
>
<Typography.Paragraph type="secondary">
模板只提供行业表达样例,不会替代你的品牌定位、经历、作品和合作方式。
</Typography.Paragraph>
<Tag>{installations.length ? `已安装 ${installations.length} 个模板` : "尚未安装模板"}</Tag>
{installations.length > 0 && (
<Card size="small" style={{ marginTop: 16 }} title="模板版本">
<Space direction="vertical" style={{ width: "100%" }}>
<Typography.Text>
当前版本:{templatePreview.data?.currentVersion ?? "加载中"},最新版本:
{templatePreview.data?.latestVersion ?? "加载中"}
</Typography.Text>
{templatePreview.data?.canUpgrade ? (
<>
<Typography.Paragraph type="secondary" style={{ marginBottom: 0 }}>
可升级内容:新增 {templatePreview.data.missingModules.length} 个模块,新增{" "}
{templatePreview.data.missingFields.length} 个字段。已有内容不会被覆盖。
</Typography.Paragraph>
<Button
type="primary"
onClick={() => upgrade.mutate()}
loading={upgrade.isPending}
>
确认升级模板
</Button>
</>
) : (
<Tag color="green">已是最新版本</Tag>
)}
{templatePreview.data?.canRollback && (
<Button danger onClick={() => rollback.mutate()} loading={rollback.isPending}>
恢复上一版配置基线
</Button>
)}
<MutationError error={templatePreview.error} />
<MutationError error={upgrade.error} />
<MutationError error={rollback.error} />
</Space>
</Card>
)}
<MutationError error={install.error} />
</Card>
<Modal
title="确认安装行业模板"
open={industryTarget !== null}
onCancel={() => setIndustryTarget(null)}
onOk={() => {
if (industryTarget) install.mutate(industryTarget.key);
setIndustryTarget(null);
}}
confirmLoading={install.isPending}
>
<Typography.Title level={5}>{industryTarget?.name}</Typography.Title>
<Typography.Paragraph>{industryTarget?.description}</Typography.Paragraph>
<Typography.Paragraph type="secondary">
模板会初始化模块、字段和默认业务表达,不会覆盖已有品牌内容。依赖能力:
{industryTarget?.capabilities.join("、") || "无"}。
</Typography.Paragraph>
</Modal>
<Card
title="模板组合预览"
style={{ marginBottom: 24 }}
extra={<Typography.Text type="secondary">高级预览</Typography.Text>}
>
<Typography.Paragraph type="secondary">
用于负责人确认行业表达和视觉风格是否匹配,日常内容配置通常不需要使用这里。
</Typography.Paragraph>
<Space wrap>
<Select
value={previewIndustryKey ?? null}
onChange={(key) => setPreviewIndustry(key)}
options={(templateCatalog.data?.industries ?? []).map((item) => ({
value: item.key,
label: item.name,
}))}
/>
<Select
value={previewVisualKey ?? null}
onChange={(key) => setPreviewVisual(key)}
options={(templateCatalog.data?.visuals ?? [])
.filter((item) => supportsIndustry(item, previewIndustryKey ?? ""))
.map((item) => ({ value: item.key, label: item.name }))}
/>
</Space>
{combinationPreview.isLoading ? (
<Card loading style={{ marginTop: 16 }} />
) : combinationPreview.data ? (
<Space direction="vertical" style={{ width: "100%", marginTop: 16 }}>
<Typography.Text strong>
{combinationPreview.data.industry.name} × {combinationPreview.data.visual.name}
</Typography.Text>
<Space wrap></Space>
<Typography.Text type="secondary">
能力:
{combinationPreview.data.runtime.capabilities.map((item) => item.key).join("、") ||
"无"}
</Typography.Text>
</Space>
) : null}
</Card>
<Card
title="动态咨询表单"
extra={ extra={
<Button type="primary" onClick={openNewInquiryForm}> <Button type="primary" onClick={openNewInquiryForm}>
新增表单 新增表单
</Button> </Button>
} }
> >
<Table {forms.isLoading && !forms.data ? (
rowKey="id" <ListSkeleton rows={2} />
loading={forms.isLoading} ) : (
dataSource={forms.data ?? []} <Table
locale={{ emptyText: "还没有咨询入口,点击右上角即可从默认表单开始。" }} rowKey="id"
columns={[ dataSource={forms.data ?? []}
{ title: "名称", dataIndex: "name" }, pagination={false}
{ title: "版本", dataIndex: "version", render: (value) => <Tag>v{value}</Tag> }, locale={{
{ emptyText: (
title: "字段数", <EmptyState
dataIndex: "fieldsSnapshot", compact
render: (value: unknown[]) => value?.length ?? 0, title="还没有咨询入口"
}, description="先新增一份表单,再配置希望客户填写的问题。"
{ title: "状态", dataIndex: "isEnabled", render: (value) => (value ? "启用" : "停用") }, />
{
title: "操作",
render: (_: unknown, item: InquiryForm) => (
<Space>
<Button
size="small"
onClick={() => {
setEditingForm(item);
inquiryForm.resetFields();
inquiryForm.setFieldsValue({
name: item.name,
purpose: item.purpose,
offeringId: item.offeringId ?? undefined,
fieldsSnapshot: item.fieldsSnapshot.map((field: unknown) => {
const value = field as Record<string, unknown>;
return {
...value,
options: normalizeOptionLabels(value.options),
};
}),
});
setFormOpen(true);
}}
>
编辑
</Button>
<Select
size="small"
value={item.isEnabled}
options={[
{ value: true, label: "启用" },
{ value: false, label: "停用" },
]}
onChange={(isEnabled) =>
updateForm.mutate({ id: item.id, body: { isEnabled } })
}
/>
</Space>
), ),
}, }}
]} columns={[
/> { title: "名称", dataIndex: "name" },
{
title: "作用范围",
render: (_: unknown, item: InquiryForm) => {
const offeringName = (workspace.data?.offerings ?? []).find(
(offering) => offering.id === item.offeringId,
)?.name;
return offeringName ? `仅「${offeringName}」` : "品牌通用";
},
},
{
title: "版本",
dataIndex: "version",
render: (value) => <StatusTag tone="neutral" label={`v${value}`} />,
},
{
title: "字段数",
dataIndex: "fieldsSnapshot",
render: (value: unknown[]) => value?.length ?? 0,
},
{
title: "状态",
dataIndex: "isEnabled",
render: (value: boolean) => (
<StatusTag
tone={value ? "success" : "warning"}
label={value ? "已启用" : "已停用"}
/>
),
},
{
title: "操作",
render: (_: unknown, item: InquiryForm) => (
<Space>
<Button
type="link"
size="small"
onClick={() => {
setEditingForm(item);
inquiryForm.resetFields();
inquiryForm.setFieldsValue({
name: item.name,
purpose: item.purpose,
offeringId: item.offeringId ?? undefined,
fieldsSnapshot: item.fieldsSnapshot.map((field: unknown) => {
const value = field as Record<string, unknown>;
return {
...value,
options: normalizeOptionLabels(value.options),
};
}),
});
setFormOpen(true);
}}
>
编辑
</Button>
</Space>
),
},
]}
/>
)}
<MutationError error={createForm.error} /> <MutationError error={createForm.error} />
<MutationError error={updateForm.error} /> <MutationError error={updateForm.error} />
</Card> </AdminSection>
<Card <AdminSection
title="高级自定义字段" title="高级自定义字段"
extra={ description="仅在某个字段需要跨业务复用时才在这里添加;日常问题直接写在表单里即可。"
<Space> extra={<Button onClick={() => setFieldOpen(true)}>新增字段</Button>}
<Typography.Text type="secondary">负责人设置</Typography.Text>
<Button type="primary" onClick={() => setFieldOpen(true)}>
新增字段
</Button>
</Space>
}
> >
<Table <Table
rowKey="id" rowKey="id"
dataSource={fields.filter((item) => item.source === "custom")} dataSource={(workspace.data?.fields ?? []).filter((item) => item.source === "custom")}
pagination={false}
locale={{
emptyText: (
<EmptyState
compact
title="还没有高级自定义字段"
description="绝大多数业务不需要用到这一层。"
/>
),
}}
columns={[ columns={[
{ title: "字段", dataIndex: "label" }, { title: "字段", dataIndex: "label" },
{ { title: "使用位置", dataIndex: "scope", render: fieldScopeLabel },
title: "使用位置", { title: "填写方式", dataIndex: "type", render: fieldTypeLabel },
dataIndex: "scope",
render: (value) =>
({ profile: "品牌资料", service: "业务提供项", inquiry: "咨询表单" })[
String(value)
] ?? "其他",
},
{
title: "填写方式",
dataIndex: "type",
render: (value) =>
inquiryFieldTypes.find((item) => item.value === value)?.label ?? "自定义",
},
{ {
title: "操作", title: "操作",
render: (_: unknown, item: BrandFieldDefinition) => ( render: (_: unknown, item: BrandFieldDefinition) => (
@@ -508,19 +220,19 @@ export function WorkspacePage() {
/> />
<MutationError error={createField.error} /> <MutationError error={createField.error} />
<MutationError error={removeField.error} /> <MutationError error={removeField.error} />
</Card> </AdminSection>
<Modal <Modal
open={fieldOpen} open={fieldOpen}
title="新增自定义字段" title="新增自定义字段"
onCancel={() => { onCancel={() => {
setFieldOpen(false); setFieldOpen(false);
form.resetFields(); fieldForm.resetFields();
}} }}
onOk={() => form.submit()} onOk={() => fieldForm.submit()}
confirmLoading={createField.isPending} confirmLoading={createField.isPending}
> >
<Form <Form
form={form} form={fieldForm}
layout="vertical" layout="vertical"
onFinish={(values) => onFinish={(values) =>
createField.mutate({ createField.mutate({
@@ -535,41 +247,20 @@ export function WorkspacePage() {
} as Omit<BrandFieldDefinition, "id" | "source">) } as Omit<BrandFieldDefinition, "id" | "source">)
} }
> >
<Form.Item name="scope" label="作用域" rules={[{ required: true }]}>
<Select
options={[
{ value: "profile", label: "品牌资料" },
{ value: "service", label: "服务" },
{ value: "inquiry", label: "咨询表单" },
]}
/>
</Form.Item>
<Form.Item name="key" hidden rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="label" label="显示名称" rules={[{ required: true }]}> <Form.Item name="label" label="显示名称" rules={[{ required: true }]}>
<Input /> <Input placeholder="例如:项目预算区间" />
</Form.Item> </Form.Item>
<Form.Item name="type" label="字段类型" rules={[{ required: true }]}> <Form.Item name="scope" label="使用位置" rules={[{ required: true }]}>
<Select options={fieldScopes} />
</Form.Item>
<Form.Item name="type" label="填写方式" rules={[{ required: true }]}>
<Select options={inquiryFieldTypes} />
</Form.Item>
<Form.Item name="required" label="是否必填" initialValue={false}>
<Select <Select
options={[ options={[
"text", { value: true, label: "必填" },
"textarea", { value: false, label: "选填" },
"number",
"date",
"select",
"multi-select",
"image",
"url",
"phone",
].map((value) => ({ value, label: value }))}
/>
</Form.Item>
<Form.Item name="required" label="是否必填">
<Select
options={[
{ value: true, label: "是" },
{ value: false, label: "否" },
]} ]}
/> />
</Form.Item> </Form.Item>
@@ -577,7 +268,7 @@ export function WorkspacePage() {
</Modal> </Modal>
<Modal <Modal
open={formOpen} open={formOpen}
title={editingForm ? "编辑动态咨询表单" : "新增动态咨询表单"} title={editingForm ? "编辑咨询表单" : "新增咨询表单"}
onCancel={() => { onCancel={() => {
setFormOpen(false); setFormOpen(false);
setEditingForm(null); setEditingForm(null);
@@ -587,9 +278,9 @@ export function WorkspacePage() {
confirmLoading={createForm.isPending || updateForm.isPending} confirmLoading={createForm.isPending || updateForm.isPending}
width={760} width={760}
> >
<Typography.Paragraph type="secondary"> <p className="admin-section-description admin-offset-bottom">
先确定客户要提交的事情,再设置你希望客户填写的问题。保存后还需要在“配置与发布”中检查并发布,才会在小程序生效。 先确定客户要提交的事情,再设置希望客户填写的问题。保存后需在“配置与发布”发布,才会在小程序生效。
</Typography.Paragraph> </p>
<Form <Form
form={inquiryForm} form={inquiryForm}
layout="vertical" layout="vertical"
@@ -605,7 +296,11 @@ export function WorkspacePage() {
purpose === "quote-request" ? "create-quote" : "create-inquiry"; purpose === "quote-request" ? "create-quote" : "create-inquiry";
const body = { const body = {
name: typeof values.name === "string" ? values.name : "", name: typeof values.name === "string" ? values.name : "",
...(typeof values.offeringId === "string" ? { offeringId: values.offeringId } : {}), // 显式传 null 才能解除关联;省略字段会被后端当成「不改动」。
offeringId:
typeof values.offeringId === "string" && values.offeringId
? values.offeringId
: null,
purpose, purpose,
targetType, targetType,
submissionAction, submissionAction,
@@ -617,10 +312,7 @@ export function WorkspacePage() {
const { options, ...rest } = item; const { options, ...rest } = item;
const type = typeof rest.type === "string" ? rest.type : "text"; const type = typeof rest.type === "string" ? rest.type : "text";
return ["select", "radio", "multi-select"].includes(type) return ["select", "radio", "multi-select"].includes(type)
? { ? { ...rest, options: normalizeOptionLabels(options) }
...rest,
options: normalizeOptionLabels(options),
}
: rest; : rest;
}), }),
}; };
@@ -637,7 +329,7 @@ export function WorkspacePage() {
> >
<Input placeholder="例如:预约上门测量、家庭聚餐预订" /> <Input placeholder="例如:预约上门测量、家庭聚餐预订" />
</Form.Item> </Form.Item>
<Space style={{ display: "flex" }} align="start"> <div className="admin-form-row">
<Form.Item <Form.Item
name="purpose" name="purpose"
label="客户要做什么" label="客户要做什么"
@@ -645,7 +337,7 @@ export function WorkspacePage() {
initialValue="inquiry" initialValue="inquiry"
> >
<Select <Select
style={{ width: 160 }} className="admin-field-w-lg"
options={[ options={[
{ value: "inquiry", label: "需求咨询" }, { value: "inquiry", label: "需求咨询" },
{ value: "quote-request", label: "获取报价" }, { value: "quote-request", label: "获取报价" },
@@ -653,18 +345,22 @@ export function WorkspacePage() {
]} ]}
/> />
</Form.Item> </Form.Item>
<Form.Item name="offeringId" label="关联哪项业务" help="不选择表示这是品牌通用入口。"> <Form.Item
name="offeringId"
label="在哪儿出现"
help="留空 = 品牌通用入口,任何页面都能进入;选择某项业务后,这份表单只在该业务的详情页使用。"
>
<Select <Select
allowClear allowClear
style={{ width: 220 }} className="admin-field-w-xl"
placeholder="品牌级表单" placeholder="品牌级表单"
options={(runtimeQuery.data?.offerings ?? []).map((item) => ({ options={(workspace.data?.offerings ?? []).map((item) => ({
value: item.id, value: item.id,
label: item.name, label: item.isEnabled ? item.name : `${item.name}(已停用)`,
}))} }))}
/> />
</Form.Item> </Form.Item>
</Space> </div>
<Form.List name="fieldsSnapshot"> <Form.List name="fieldsSnapshot">
{(fields, { add, remove }) => ( {(fields, { add, remove }) => (
<> <>
@@ -685,36 +381,36 @@ export function WorkspacePage() {
</Button> </Button>
</Form.Item> </Form.Item>
{fields.map(({ key, name, ...restField }) => ( {fields.map(({ key, name, ...restField }) => (
<Card key={key} size="small" style={{ marginBottom: 12 }}> <Card key={key} size="small" className="admin-offset-bottom-sm">
<Form.Item {...restField} name={[name, "key"]} hidden> <Form.Item {...restField} name={[name, "key"]} hidden>
<Input /> <Input />
</Form.Item> </Form.Item>
<Space align="start" style={{ display: "flex" }}> <div className="admin-form-row">
<Form.Item <Form.Item
{...restField} {...restField}
name={[name, "label"]} name={[name, "label"]}
label="要询问客户什么" label="要询问客户什么"
rules={[{ required: true, message: "请填写字段名称" }]} rules={[{ required: true, message: "请填写字段名称" }]}
style={{ flex: 1 }} className="admin-flex-1"
> >
<Input placeholder="例如:联系电话、预计预算、项目地址" /> <Input placeholder="例如:联系电话、预计预算、项目地址" />
</Form.Item> </Form.Item>
<Form.Item {...restField} name={[name, "type"]} label="回答方式"> <Form.Item {...restField} name={[name, "type"]} label="回答方式">
<Select style={{ width: 150 }} options={inquiryFieldTypes} /> <Select className="admin-field-w-md" options={inquiryFieldTypes} />
</Form.Item> </Form.Item>
<Form.Item {...restField} name={[name, "required"]} label="必填"> <Form.Item {...restField} name={[name, "required"]} label="必填">
<Select <Select
style={{ width: 90 }} className="admin-field-w-sm"
options={[ options={[
{ value: true, label: "必填" }, { value: true, label: "必填" },
{ value: false, label: "选填" }, { value: false, label: "选填" },
]} ]}
/> />
</Form.Item> </Form.Item>
<Button danger onClick={() => remove(name)} style={{ marginTop: 30 }}> <Button danger onClick={() => remove(name)} className="admin-field-offset">
删除 删除
</Button> </Button>
</Space> </div>
<Form.Item noStyle shouldUpdate> <Form.Item noStyle shouldUpdate>
{({ getFieldValue }) => {({ getFieldValue }) =>
["select", "radio", "multi-select"].includes( ["select", "radio", "multi-select"].includes(
@@ -732,35 +428,35 @@ export function WorkspacePage() {
}, },
]} ]}
> >
{(optionFields, { add, remove }, { errors }) => ( {(
optionFields,
{ add: addOption, remove: removeOption },
{ errors },
) => (
<> <>
{optionFields.map((optionField) => ( {optionFields.map((optionField) => (
<Space <div key={optionField.key} className="admin-form-row-center">
key={optionField.key}
align="center"
style={{ display: "flex" }}
>
<Form.Item <Form.Item
{...optionField} {...optionField}
name={[optionField.name, "label"]} name={[optionField.name, "label"]}
initialValue="" initialValue=""
rules={[{ required: true, message: "请填写选项内容" }]} rules={[{ required: true, message: "请填写选项内容" }]}
style={{ flex: 1, minWidth: 240, marginBottom: 8 }} className="admin-flex-1 admin-offset-bottom-xs"
> >
<Input placeholder="例如:预算内" /> <Input placeholder="例如:预算内" />
</Form.Item> </Form.Item>
<Button <Button
danger danger
onClick={() => remove(optionField.name)} onClick={() => removeOption(optionField.name)}
style={{ marginBottom: 8 }} className="admin-offset-bottom-xs"
> >
删除 删除
</Button> </Button>
</Space> </div>
))} ))}
<Button <Button
onClick={() => add({ label: "", value: "" })} onClick={() => addOption({ label: "", value: "" })}
style={{ marginBottom: 8 }} className="admin-offset-bottom-xs"
> >
新增选项 新增选项
</Button> </Button>
@@ -778,6 +474,6 @@ export function WorkspacePage() {
</Form.List> </Form.List>
</Form> </Form>
</Modal> </Modal>
</Space> </QueryState>
); );
} }
@@ -1,94 +1,9 @@
import { message } from "antd"; import { message } from "antd";
import { useMutation, useQuery } from "@tanstack/react-query"; import { useMutation } from "@tanstack/react-query";
import type { FormInstance } from "antd"; import type { FormInstance } from "antd";
import type { import type { BrandFieldDefinition, InquiryForm } from "@personal-brand/api-client";
BrandFieldDefinition,
BrandTemplateKey,
InquiryForm,
} from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js"; import { createApiClient } from "../../lib/api.js";
export function useWorkspaceQueries(client = createApiClient()) {
const query = useQuery({
queryKey: ["admin-workspace"],
queryFn: () => client.getAdminWorkspace(),
});
const runtimeQuery = useQuery({
queryKey: ["public-runtime-workspace"],
queryFn: () => client.getPublicWorkspace(),
});
const templateCatalog = useQuery({
queryKey: ["template-catalog"],
queryFn: () => client.listPublicTemplates(),
});
const forms = useQuery({
queryKey: ["admin-inquiry-forms"],
queryFn: () => client.listAdminInquiryForms(),
});
const templatePreview = useQuery({
queryKey: ["admin-template-preview"],
queryFn: () => client.getAdminTemplateUpgradePreview(),
enabled: Boolean(query.data?.installations?.length),
});
return { query, runtimeQuery, templateCatalog, forms, templatePreview };
}
interface TemplateMutationOptions {
client?: ReturnType<typeof createApiClient>;
runtimeConfig: Record<string, unknown> | undefined;
queryClient: {
invalidateQueries: (options: { queryKey: readonly unknown[] }) => Promise<void>;
};
}
export function useTemplateMutations({
client = createApiClient(),
runtimeConfig,
queryClient,
}: TemplateMutationOptions) {
const visualTemplate = useMutation({
mutationFn: (key: string) =>
client.updateAdminBrand({ config: { ...(runtimeConfig ?? {}), visualTemplateKey: key } }),
onSuccess: () => {
message.success("视觉模板已切换");
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
},
});
const rollbackVisual = useMutation({
mutationFn: () => client.rollbackAdminVisualTemplate(),
onSuccess: () => {
message.success("视觉模板已回滚");
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["visual-template-history"] });
},
});
const install = useMutation({
mutationFn: (key: BrandTemplateKey) => client.installAdminTemplate(key),
onSuccess: () => {
message.success("模板已安装");
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
},
});
const upgrade = useMutation({
mutationFn: () => client.upgradeAdminTemplate(),
onSuccess: () => {
message.success("模板已升级,已有内容未被覆盖");
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] });
},
});
const rollback = useMutation({
mutationFn: () => client.rollbackAdminTemplate(),
onSuccess: () => {
message.success("模板版本已回滚,现有内容未删除");
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] });
},
});
return { visualTemplate, rollbackVisual, install, upgrade, rollback };
}
interface FieldMutationOptions { interface FieldMutationOptions {
client?: ReturnType<typeof createApiClient>; client?: ReturnType<typeof createApiClient>;
form: FormInstance<Record<string, unknown>>; form: FormInstance<Record<string, unknown>>;
@@ -137,7 +52,7 @@ export function useInquiryFormMutations({
const createForm = useMutation({ const createForm = useMutation({
mutationFn: (values: { mutationFn: (values: {
name: string; name: string;
offeringId?: string; offeringId?: string | null;
purpose?: InquiryForm["purpose"]; purpose?: InquiryForm["purpose"];
targetType?: InquiryForm["targetType"]; targetType?: InquiryForm["targetType"];
submissionAction?: InquiryForm["submissionAction"]; submissionAction?: InquiryForm["submissionAction"];
@@ -154,7 +69,7 @@ export function useInquiryFormMutations({
mutationFn: ({ id, body }: { id: string; body: Partial<InquiryForm> }) => mutationFn: ({ id, body }: { id: string; body: Partial<InquiryForm> }) =>
client.updateAdminInquiryForm(id, { client.updateAdminInquiryForm(id, {
...(body.name === undefined ? {} : { name: body.name }), ...(body.name === undefined ? {} : { name: body.name }),
...(body.offeringId == null ? {} : { offeringId: body.offeringId }), ...(body.offeringId === undefined ? {} : { offeringId: body.offeringId }),
...(body.fieldsSnapshot === undefined ? {} : { fieldsSnapshot: body.fieldsSnapshot }), ...(body.fieldsSnapshot === undefined ? {} : { fieldsSnapshot: body.fieldsSnapshot }),
...(body.isEnabled === undefined ? {} : { isEnabled: body.isEnabled }), ...(body.isEnabled === undefined ? {} : { isEnabled: body.isEnabled }),
}), }),
@@ -0,0 +1,21 @@
import { useQuery } from "@tanstack/react-query";
import { createApiClient } from "../../lib/api.js";
/**
* 咨询表单与自定义字段只需要两份后台数据:品牌工作空间(含本品牌业务提供项)和表单列表。
*
* 注意:这里不能用 `getPublicWorkspace()` 取业务提供项。公开工作空间不带 brandSlug 时会回退到
* 默认品牌,管理其它品牌时下拉框会列出别的品牌的业务(跨品牌串数据)。
*/
export function useFormWorkspaceQueries(client = createApiClient()) {
return {
workspace: useQuery({
queryKey: ["admin-workspace"],
queryFn: () => client.getAdminWorkspace(),
}),
forms: useQuery({
queryKey: ["admin-inquiry-forms"],
queryFn: () => client.listAdminInquiryForms(),
}),
};
}
@@ -1,18 +0,0 @@
import type { BrandTemplateKey } from "@personal-brand/api-client";
export interface IndustryTarget {
key: BrandTemplateKey;
name: string;
description: string;
capabilities: string[];
}
export function supportsIndustry(
visual: { supportedIndustryTemplates?: unknown },
industry: string,
): boolean {
return (
Array.isArray(visual.supportedIndustryTemplates) &&
visual.supportedIndustryTemplates.includes(industry)
);
}
+106
View File
@@ -0,0 +1,106 @@
import { ConfigProvider } from "antd";
import type { ThemeConfig } from "antd";
export const adminTheme: ThemeConfig = {
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,
},
},
};
ConfigProvider.config({ theme: adminTheme });
+24 -312
View File
@@ -1,326 +1,38 @@
import React, { Suspense, useState } from "react"; import React from "react";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useQuery } from "@tanstack/react-query"; import zhCN from "antd/locale/zh_CN";
import { import { BrowserRouter } from "react-router-dom";
App, import { Root } from "./app/Root.js";
Button,
Card,
Form,
Input,
Layout,
Menu,
Select,
Space,
Tag,
Typography,
message,
} from "antd";
import { createApiClient } from "./lib/api.js"; import { createApiClient } from "./lib/api.js";
const FeatureInquiriesPage = React.lazy(() => import { adminTheme } from "./lib/theme.js";
import("./features/inquiries/InquiriesPage.js").then((module) => ({ import { AdminConfigProvider } from "./components/AdminConfigProvider.js";
default: module.InquiriesPage, import "./styles/admin.css";
})),
);
const FeatureTrustContentPage = React.lazy(() =>
import("./features/trust-content/TrustContentPage.js").then((module) => ({
default: module.TrustContentPage,
})),
);
const FeatureServicesPage = React.lazy(() =>
import("./features/services/ServicesPage.js").then((module) => ({
default: module.ServicesPage,
})),
);
const FeatureBrandPage = React.lazy(() =>
import("./features/brand/BrandPage.js").then((module) => ({ default: module.BrandPage })),
);
const FeatureWorkspacePage = React.lazy(() =>
import("./features/workspace/WorkspacePage.js").then((module) => ({
default: module.WorkspacePage,
})),
);
const FeatureOverviewPage = React.lazy(() =>
import("./features/overview/OverviewPage.js").then((module) => ({
default: module.OverviewPage,
})),
);
const FeatureCapabilitiesPage = React.lazy(() =>
import("./features/capabilities/CapabilitiesPage.js").then((module) => ({
default: module.CapabilitiesPage,
})),
);
const FeatureMembersPage = React.lazy(() =>
import("./features/team/MembersPage.js").then((module) => ({
default: module.MembersPage,
})),
);
const FeaturePublicationPage = React.lazy(() =>
import("./features/publication/PublicationPage.js").then((module) => ({
default: module.PublicationPage,
})),
);
import { BrowserRouter, Navigate, Route, Routes, useLocation, useNavigate } from "react-router-dom";
import "antd/dist/reset.css"; import "antd/dist/reset.css";
const queryClient = new QueryClient(); const queryClient = new QueryClient({
const api = createApiClient; defaultOptions: {
queries: {
function Login({ staleTime: 30_000,
onLogin, retry: 2,
}: { refetchOnWindowFocus: false,
onLogin: (session: { role: string; mustChangePassword: boolean }) => void;
}) {
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
async function submit(values: { username: string; password: string }) {
setLoading(true);
try {
const result = await api().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 (
<Card title="个人品牌后台" style={{ maxWidth: 420, margin: "120px auto" }}>
<Form form={form} layout="vertical" onFinish={submit}>
<Form.Item name="username" label="账号" initialValue="admin" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="password" label="密码" rules={[{ required: true }]}>
<Input.Password />
</Form.Item>
<Button type="primary" htmlType="submit" loading={loading} block>
登录
</Button>
</Form>
</Card>
);
}
function ChangePassword({ onComplete }: { onComplete: () => void }) {
const [form] = Form.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 api().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 (
<Card title="首次登录需要修改密码" style={{ maxWidth: 420, margin: "120px auto" }}>
<Typography.Paragraph type="secondary">请先设置只有你本人知道的新密码。</Typography.Paragraph>
<Form form={form} layout="vertical" onFinish={submit}>
<Form.Item name="currentPassword" label="初始密码" rules={[{ required: true }]}>
<Input.Password />
</Form.Item>
<Form.Item
name="newPassword"
label="新密码"
rules={[{ required: true, min: 8, message: "请输入至少 8 位新密码" }]}
>
<Input.Password />
</Form.Item>
<Form.Item name="confirmPassword" label="确认新密码" rules={[{ required: true }]}>
<Input.Password />
</Form.Item>
<Button type="primary" htmlType="submit" loading={loading} block>
保存新密码
</Button>
</Form>
</Card>
);
}
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: "当前品牌概览" },
{ key: "publication", label: "配置与发布" },
{ key: "brand", label: "小程序页面" },
{ key: "trust", label: "信任内容" },
{ key: "services", label: "业务提供项" },
{ key: "inquiries", label: "咨询记录" },
],
}, },
...(role === "editor" mutations: {
? [] retry: 0,
: [ },
{ },
type: "group" as const, });
label: "系统管理",
children: [ export const api = createApiClient;
{ key: "workspace", label: "模板与表单设置" },
{ key: "capabilities", label: "能力插件" },
{ key: "members", label: "团队成员" },
],
},
]),
];
return (
<Layout style={{ minHeight: "100vh" }}>
<Layout.Sider breakpoint="lg" collapsedWidth={0}>
<Typography.Title level={4} style={{ color: "white", padding: 20 }}>
当前品牌工作区
</Typography.Title>
<Menu
theme="dark"
selectedKeys={[page]}
onClick={({ key }) => navigate(`/admin/${key}`)}
items={items}
/>
</Layout.Sider>
<Layout>
<Layout.Header
style={{
background: "white",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Space>
<Typography.Text strong>{brand.data?.name || "当前品牌"}</Typography.Text>
<Typography.Text type="secondary">品牌工作区</Typography.Text>
<Tag color={role === "owner" ? "blue" : "default"}>
{role === "owner" ? "负责人" : "内容编辑"}
</Tag>
<Select
size="small"
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,
}))}
/>
</Space>
<Button type="text" onClick={onLogout}>
退出登录
</Button>
</Layout.Header>
<Layout.Content style={{ padding: 24 }}>
<Suspense fallback={<Card loading />}>
<Routes>
<Route path="/admin/overview" element={<FeatureOverviewPage />} />
<Route
path="/admin/publication"
element={<FeaturePublicationPage canManageTemplate={role !== "editor"} />}
/>
<Route path="/admin/brand" element={<FeatureBrandPage />} />
{role === "editor" ? null : (
<Route path="/admin/workspace" element={<FeatureWorkspacePage />} />
)}
{role === "editor" ? null : (
<Route path="/admin/capabilities" element={<FeatureCapabilitiesPage />} />
)}
{role === "editor" ? null : (
<Route path="/admin/members" element={<FeatureMembersPage />} />
)}
<Route path="/admin/trust" element={<FeatureTrustContentPage />} />
<Route path="/admin/services" element={<FeatureServicesPage />} />
<Route path="/admin/inquiries" element={<FeatureInquiriesPage />} />
<Route path="*" element={<Navigate to="/admin/overview" replace />} />
</Routes>
</Suspense>
</Layout.Content>
</Layout>
</Layout>
);
}
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} />;
}
createRoot(document.getElementById("app")!).render( createRoot(document.getElementById("app")!).render(
<React.StrictMode> <React.StrictMode>
<QueryClientProvider client={queryClient}> <AdminConfigProvider locale={zhCN} theme={adminTheme}>
<App> <QueryClientProvider client={queryClient}>
<BrowserRouter> <BrowserRouter>
<Root /> <Root />
</BrowserRouter> </BrowserRouter>
</App> </QueryClientProvider>
</QueryClientProvider> </AdminConfigProvider>
</React.StrictMode>, </React.StrictMode>,
); );
+856
View File
@@ -0,0 +1,856 @@
/*
* 后台全局样式。视觉规则见 apps/admin/design.md。
* 颜色令牌与 apps/admin/src/lib/theme.ts 保持一致,改动需同步。
*/
:root {
--admin-bg: #f7f8fa;
--admin-surface: #ffffff;
--admin-border: #e7e9ec;
--admin-divider: #f0f1f3;
--admin-text: #1c1f23;
--admin-text-secondary: #6b7280;
--admin-text-tertiary: #9aa1ac;
--admin-primary: #2563eb;
--admin-primary-bg: #eff4ff;
--admin-fill: #f7f8fa;
--admin-fill-quiet: #fafafb;
--admin-tone-success-bg: #ecfdf3;
--admin-tone-success-border: #abefc6;
--admin-tone-success-fg: #067647;
--admin-tone-warning-bg: #fffaeb;
--admin-tone-warning-border: #fedf89;
--admin-tone-warning-fg: #b54708;
--admin-tone-error-bg: #fef3f2;
--admin-tone-error-border: #fbd5d1;
--admin-tone-error-fg: #b42318;
--admin-tone-neutral-bg: #f2f4f7;
--admin-tone-neutral-border: #e7e9ec;
--admin-tone-neutral-fg: #475467;
--admin-tone-info-bg: #eff4ff;
--admin-tone-info-border: #b2ccff;
--admin-tone-info-fg: #2563eb;
}
html,
body,
#app {
height: 100%;
}
body {
margin: 0;
background: var(--admin-bg);
color: var(--admin-text);
font-variant-numeric: tabular-nums;
-webkit-font-smoothing: antialiased;
}
:where(a, button, [tabindex]):focus-visible {
outline: 2px solid var(--admin-primary);
outline-offset: 2px;
}
/* 外壳 */
.admin-shell {
min-height: 100vh;
}
.admin-sider,
.admin-sider .ant-layout-sider-children {
border-right: 1px solid var(--admin-border);
}
.admin-sider.ant-layout-sider-collapsed,
.admin-sider.ant-layout-sider-zero-width,
.admin-sider.ant-layout-sider-zero-width .ant-layout-sider-children {
border-right: 0;
}
.admin-sider .ant-layout-sider-zero-width-trigger {
border: 1px solid var(--admin-border);
border-left: 0;
border-radius: 0 6px 6px 0;
box-shadow: none;
}
.admin-sider-brand {
display: flex;
align-items: center;
gap: 10px;
height: 56px;
padding: 0 20px;
}
.admin-sider-brand-mark {
width: 24px;
height: 24px;
border-radius: 6px;
background: var(--admin-primary);
color: #fff;
font-size: 13px;
font-weight: 600;
display: inline-flex;
align-items: center;
justify-content: center;
flex: none;
}
.admin-sider-brand-name {
font-size: 14px;
font-weight: 600;
color: var(--admin-text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.admin-sider .ant-menu {
border-inline-end: 0;
padding: 4px 0 12px;
}
.admin-sider .ant-menu-item-group-title {
padding: 16px 24px 6px;
font-size: 12px;
}
.admin-main {
display: flex;
flex-direction: column;
min-height: 100vh;
min-width: 0;
}
.admin-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
border-bottom: 1px solid var(--admin-border);
}
.admin-header-left {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.admin-header-brand {
font-size: 14px;
font-weight: 600;
color: var(--admin-text);
}
.admin-header-context {
font-size: 13px;
color: var(--admin-text-tertiary);
}
.admin-brand-switcher {
min-width: 140px;
}
.admin-equal-height > .ant-col > .ant-card {
height: 100%;
}
.admin-content {
flex: 1;
padding: 24px;
}
.admin-content-inner {
max-width: 1200px;
margin: 0 auto;
}
/* 页面头部 */
.admin-page-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
margin-bottom: 32px;
}
.admin-page-header-text {
flex: 1 1 auto;
min-width: 0;
}
.admin-page-header-title {
margin: 0;
font-size: 20px;
font-weight: 600;
line-height: 1.4;
color: var(--admin-text);
}
.admin-page-header-description {
margin: 6px 0 0;
max-width: 880px;
font-size: 13px;
line-height: 1.6;
color: var(--admin-text-secondary);
}
/* 区块与列表 */
.admin-section {
padding: 20px;
border: 1px solid var(--admin-border);
border-radius: 10px;
background: var(--admin-surface);
}
.admin-section + .admin-section {
margin-top: 16px;
}
.admin-section-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 12px;
}
.admin-section-head:last-child {
margin-bottom: 0;
}
.admin-section-title {
margin: 0;
font-size: 16px;
font-weight: 600;
line-height: 1.45;
color: var(--admin-text);
}
.admin-subhead {
margin: 0;
font-size: 15px;
font-weight: 600;
line-height: 1.45;
color: var(--admin-text);
}
.admin-section-description {
margin: 6px 0 0;
font-size: 13px;
line-height: 1.5;
color: var(--admin-text-secondary);
}
.admin-stack {
display: flex;
flex-direction: column;
gap: 16px;
}
.admin-stack-lg {
gap: 16px;
}
.admin-stack-tight {
gap: 12px;
}
.admin-actions {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 12px;
}
.admin-row-title {
font-size: 14px;
font-weight: 600;
color: var(--admin-text);
}
.admin-row-meta {
font-size: 12px;
color: var(--admin-text-tertiary);
}
.admin-row-summary {
font-size: 13px;
line-height: 1.5;
color: var(--admin-text-secondary);
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
/* 列表行 */
.admin-list {
margin: 0;
padding: 0;
list-style: none;
}
.admin-row.admin-record {
align-items: flex-start;
gap: 12px;
}
.admin-record__thumb {
flex: none;
display: inline-flex;
align-items: center;
justify-content: center;
margin-top: 2px;
width: 48px;
height: 48px;
border-radius: 8px;
border: 1px solid var(--admin-border);
background: var(--admin-fill);
color: var(--admin-text-tertiary);
font-size: 18px;
overflow: hidden;
}
.admin-record__thumb img {
width: 100%;
height: 100%;
object-fit: cover;
}
.admin-record__actions {
flex: none;
display: flex;
align-items: center;
align-self: center;
gap: 4px;
}
.admin-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 14px 0;
border-bottom: 1px solid var(--admin-divider);
}
.admin-row:last-child {
border-bottom: 0;
}
.admin-row-main {
display: flex;
flex-direction: column;
gap: 4px;
flex: 1 1 auto;
min-width: 0;
}
/* 行内段落默认自带浏览器下边距,行内布局统一交给 gap 控制。 */
.admin-row-main > .admin-row-meta,
.admin-row-main > .admin-row-summary,
.admin-row-main > .admin-row-help {
margin: 0;
}
.admin-row-line {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.admin-row-help {
margin: 6px 0 0;
font-size: 13px;
line-height: 1.5;
color: var(--admin-text-secondary);
}
.admin-field-stack {
display: grid;
gap: 12px;
}
.admin-field-label {
display: block;
font-size: 13px;
font-weight: 500;
color: var(--admin-text-secondary);
margin-bottom: 6px;
}
.admin-offset-top {
margin-top: 16px;
}
.admin-offset-top-xs {
margin-top: 4px;
}
.admin-divider {
margin: 16px 0;
}
.admin-offset-top-sm {
margin-top: 8px;
}
.admin-offset-top-md {
margin-top: 12px;
}
.admin-offset-bottom {
margin-bottom: 16px;
}
.admin-text-xs {
font-size: 12px;
line-height: 1.5;
color: var(--admin-text-secondary);
}
.admin-text-xs-quiet {
font-size: 12px;
color: var(--admin-text-tertiary);
}
.admin-text-warning {
color: var(--admin-tone-warning-fg);
}
.admin-flush {
margin-bottom: 0;
}
.admin-flush-top {
margin-top: 0;
}
.admin-block {
width: 100%;
}
.admin-offset-bottom-sm {
margin-bottom: 12px;
}
.admin-offset-bottom-lg {
margin-bottom: 24px;
}
.admin-offset-top-lg {
margin-top: 24px;
}
.admin-link-flush {
padding: 0;
}
.admin-form-row {
display: flex;
align-items: flex-start;
gap: 16px;
flex-wrap: wrap;
}
.admin-form-row-center {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
}
.admin-flex-1 {
flex: 1;
min-width: 0;
}
.admin-field-w-sm {
width: 90px;
}
.admin-field-w-md {
width: 150px;
}
.admin-field-w-lg {
width: 160px;
}
.admin-field-w-xl {
width: 220px;
}
.admin-field-w-2xl {
width: 180px;
}
.admin-field-stack-xs {
display: grid;
gap: 4px;
}
.admin-form-column {
display: flex;
flex-direction: column;
min-height: 0;
}
.admin-brand-title {
margin: 0;
font-size: 18px;
font-weight: 600;
line-height: 1.45;
color: var(--admin-text);
}
.admin-brand-tagline {
margin: 6px 0 12px;
font-size: 14px;
line-height: 1.5;
color: var(--admin-text-secondary);
}
.admin-field-offset {
margin-top: 30px;
}
.admin-offset-bottom-xs {
margin-bottom: 8px;
}
.admin-visual-card {
width: 260px;
}
.admin-swatch {
display: inline-flex;
align-items: center;
gap: 4px;
height: 24px;
padding: 0 8px;
border-radius: 6px;
background: var(--admin-fill);
color: var(--admin-text-secondary);
font-size: 12px;
}
.admin-swatch::before {
content: "";
width: 10px;
height: 10px;
border-radius: 3px;
border: 1px solid var(--admin-border);
background: var(--swatch-color, transparent);
}
/* 描述列表(键值展示) */
.admin-descriptions .ant-descriptions-item-label {
font-size: 13px;
}
/* 状态标签 */
.admin-status-tag {
display: inline-flex;
align-items: center;
gap: 4px;
height: 24px;
padding: 0 8px;
border-radius: 6px;
font-size: 12px;
font-weight: 500;
line-height: 1;
white-space: nowrap;
background: var(--admin-tone-neutral-bg);
color: var(--admin-tone-neutral-fg);
}
.admin-status-tag[data-tone="success"] {
background: var(--admin-tone-success-bg);
color: var(--admin-tone-success-fg);
}
.admin-status-tag[data-tone="warning"] {
background: var(--admin-tone-warning-bg);
color: var(--admin-tone-warning-fg);
}
.admin-status-tag[data-tone="error"] {
background: var(--admin-tone-error-bg);
color: var(--admin-tone-error-fg);
}
.admin-status-tag[data-tone="info"] {
background: var(--admin-tone-info-bg);
color: var(--admin-tone-info-fg);
}
/* 指标卡 */
.admin-metric-label {
font-size: 12px;
color: var(--admin-text-tertiary);
}
.admin-metric-value {
margin-top: 8px;
font-size: 28px;
font-weight: 600;
line-height: 1.2;
color: var(--admin-text);
}
.admin-metric-suffix {
margin-left: 6px;
font-size: 12px;
font-weight: 400;
color: var(--admin-text-tertiary);
}
/* 反馈 */
.admin-empty {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
padding: 40px 24px;
}
.admin-empty--compact {
padding: 24px 16px;
}
.admin-empty__icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
margin-bottom: 12px;
border-radius: 10px;
background: var(--admin-fill);
color: var(--admin-text-tertiary);
font-size: 20px;
}
.admin-empty--compact .admin-empty__icon {
width: 32px;
height: 32px;
margin-bottom: 8px;
font-size: 16px;
}
.admin-empty__title {
margin: 0;
font-size: 15px;
font-weight: 600;
line-height: 1.5;
color: var(--admin-text);
}
.admin-empty--compact .admin-empty__title {
font-size: 14px;
}
.admin-empty__description {
margin: 6px 0 0;
max-width: 360px;
font-size: 13px;
line-height: 1.6;
color: var(--admin-text-secondary);
}
.admin-empty__action {
margin-top: 16px;
}
.admin-empty--compact .admin-empty__action {
margin-top: 12px;
}
.admin-table-skeleton {
border-top: 1px solid var(--admin-divider);
}
.admin-table-skeleton__row {
display: flex;
align-items: center;
min-height: 52px;
padding: 0 16px;
border-bottom: 1px solid var(--admin-divider);
}
.admin-table-skeleton__row:last-child {
border-bottom: 0;
}
.admin-table-skeleton__row .ant-skeleton {
width: 100%;
}
.admin-table-skeleton__row .ant-skeleton-input {
width: 60%;
min-width: 120px;
}
.admin-list-skeleton {
display: flex;
flex-direction: column;
}
.admin-list-skeleton__row {
display: flex;
align-items: center;
gap: 12px;
padding: 14px 0;
border-bottom: 1px solid var(--admin-divider);
}
.admin-list-skeleton__row:last-child {
border-bottom: 0;
}
.admin-list-skeleton__thumb .ant-skeleton-input {
width: 48px;
min-width: 48px;
height: 48px;
}
.admin-list-skeleton__body {
flex: 1;
display: grid;
gap: 8px;
min-width: 0;
}
.admin-list-skeleton__body .ant-skeleton-input:last-child {
width: 45%;
}
.admin-error-note {
padding: 12px 16px;
border: 1px solid var(--admin-tone-error-border);
border-radius: 8px;
background: var(--admin-tone-error-bg);
color: var(--admin-tone-error-fg);
font-size: 14px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.admin-loading-stack {
display: flex;
flex-direction: column;
gap: 16px;
}
.admin-log {
margin: 0;
padding: 16px;
border-radius: 8px;
background: #1c1f23;
color: #e4e7ec;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
line-height: 1.7;
max-height: 280px;
overflow: auto;
white-space: pre-wrap;
word-break: break-all;
}
.admin-log__line {
color: #e4e7ec;
white-space: pre-wrap;
word-break: break-all;
}
.admin-log__line[data-stream="stderr"] {
color: #fda29b;
}
.admin-log__time {
color: #98a2b3;
}
.admin-code-input {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
.admin-thumb {
width: 80px;
height: 80px;
object-fit: cover;
border-radius: 8px;
border: 1px solid var(--admin-border);
}
.admin-thumb-remove {
position: absolute;
top: 8px;
right: 8px;
}
.admin-thumb-wrap {
position: relative;
display: inline-block;
}
.admin-media-preview {
position: relative;
width: 100%;
min-height: 140px;
border-radius: 8px;
overflow: hidden;
border: 1px solid var(--admin-border);
background: var(--admin-fill);
}
@media (max-width: 1024px) {
.admin-content {
padding: 16px;
}
}
/* 登录与改密 */
.admin-auth {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
background: var(--admin-bg);
}
.admin-auth-card {
width: 100%;
max-width: 400px;
}
.admin-auth-card .ant-card-body {
padding: 32px;
}
.admin-auth-brand {
display: flex;
align-items: center;
gap: 10px;
}
.admin-auth-hint {
margin: 8px 0 20px;
font-size: 13px;
color: var(--admin-text-secondary);
}
.admin-auth-footnote {
margin: 16px 0 0;
font-size: 12px;
color: var(--admin-text-tertiary);
text-align: center;
}
@@ -6,7 +6,7 @@ import {
filterSectionsForPreviewTarget, filterSectionsForPreviewTarget,
presentationFieldName, presentationFieldName,
readPresentationValue, readPresentationValue,
} from "../src/features/brand/presentation-bindings.ts"; } from "../src/lib/presentation/presentation-bindings.ts";
import { import {
resolvePreviewSelection, resolvePreviewSelection,
previewTrustRecordId, previewTrustRecordId,
+13 -1
View File
@@ -43,5 +43,17 @@ export default defineConfig({
: {}), : {}),
}, },
}, },
build: { outDir: "dist" }, build: {
outDir: "dist",
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes("/node_modules/.pnpm/react-dom@")) return "react-runtime";
if (id.includes("/node_modules/.pnpm/react@")) return "react-runtime";
if (id.includes("/node_modules/.pnpm/scheduler@")) return "react-runtime";
return undefined;
},
},
},
},
}); });
+2 -1
View File
@@ -4,7 +4,7 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"build": "tsc -p tsconfig.json", "build": "tsc -p tsconfig.json",
"dev": "pnpm build && node --env-file=.env dist/main.js", "dev": "pnpm build && node --env-file=.env --watch dist/main.js",
"lint": "eslint .", "lint": "eslint .",
"typecheck": "tsc -p tsconfig.json --noEmit", "typecheck": "tsc -p tsconfig.json --noEmit",
"test": "tsx --test test/**/*.test.ts", "test": "tsx --test test/**/*.test.ts",
@@ -32,6 +32,7 @@
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.14.1", "class-validator": "^0.14.1",
"fastify": "^5.11.3", "fastify": "^5.11.3",
"miniprogram-ci": "^2.1.31",
"prisma": "^6.2.1", "prisma": "^6.2.1",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1" "rxjs": "^7.8.1"
@@ -0,0 +1,21 @@
CREATE TYPE "MiniAppReleaseStatus" AS ENUM ('built', 'uploaded', 'under_review', 'rejected', 'approved', 'published', 'failed');
CREATE TABLE "MiniAppReleaseTask" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"releaseId" TEXT,
"version" INTEGER NOT NULL,
"status" "MiniAppReleaseStatus" NOT NULL DEFAULT 'built',
"artifactPath" TEXT,
"actorId" TEXT NOT NULL,
"error" TEXT,
"weappUploadId" TEXT,
"audit" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "MiniAppReleaseTask_pkey" PRIMARY KEY ("id")
);
CREATE INDEX "MiniAppReleaseTask_brandId_createdAt_idx" ON "MiniAppReleaseTask"("brandId", "createdAt" DESC);
CREATE UNIQUE INDEX "MiniAppReleaseTask_brandId_version_key" ON "MiniAppReleaseTask"("brandId", "version");
ALTER TABLE "MiniAppReleaseTask" ADD CONSTRAINT "MiniAppReleaseTask_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "MiniAppReleaseTask" ADD CONSTRAINT "MiniAppReleaseTask_releaseId_fkey" FOREIGN KEY ("releaseId") REFERENCES "BrandRelease"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1 @@
ALTER TABLE "BrandProfile" ADD COLUMN "miniAppSettings" JSONB;
@@ -0,0 +1,3 @@
ALTER TABLE "MiniAppReleaseTask" ADD COLUMN "buildLogs" JSONB;
CREATE TYPE "MiniAppBuildStatus" AS ENUM ('idle', 'building', 'success', 'failed');
ALTER TABLE "MiniAppReleaseTask" ADD COLUMN "buildStatus" "MiniAppBuildStatus" NOT NULL DEFAULT 'idle';
@@ -0,0 +1,57 @@
DO $$
DECLARE
has_building_value boolean;
has_build_failed_value boolean;
BEGIN
SELECT EXISTS (
SELECT 1
FROM unnest(enum_range(NULL::"MiniAppReleaseStatus")) AS enum_value
WHERE enum_value::text = 'building'
)
INTO has_building_value;
SELECT EXISTS (
SELECT 1
FROM unnest(enum_range(NULL::"MiniAppReleaseStatus")) AS enum_value
WHERE enum_value::text = 'build_failed'
)
INTO has_build_failed_value;
IF has_building_value OR has_build_failed_value THEN
UPDATE "MiniAppReleaseTask"
SET "buildStatus" = 'failed'::"MiniAppBuildStatus"
WHERE status::text = 'build_failed';
UPDATE "MiniAppReleaseTask"
SET "buildStatus" = 'building'::"MiniAppBuildStatus"
WHERE status::text = 'building';
CREATE TYPE "MiniAppReleaseStatusNormalized" AS ENUM (
'built',
'uploaded',
'under_review',
'rejected',
'approved',
'published',
'failed'
);
ALTER TABLE "MiniAppReleaseTask" ALTER COLUMN status DROP DEFAULT;
ALTER TABLE "MiniAppReleaseTask"
ALTER COLUMN status TYPE "MiniAppReleaseStatusNormalized"
USING CASE status::text
WHEN 'building' THEN 'built'::"MiniAppReleaseStatusNormalized"
WHEN 'build_failed' THEN 'failed'::"MiniAppReleaseStatusNormalized"
ELSE status::text::"MiniAppReleaseStatusNormalized"
END;
DROP TYPE "MiniAppReleaseStatus";
ALTER TYPE "MiniAppReleaseStatusNormalized" RENAME TO "MiniAppReleaseStatus";
ALTER TABLE "MiniAppReleaseTask"
ALTER COLUMN status SET DEFAULT 'built'::"MiniAppReleaseStatus";
END IF;
END
$$;
+278 -220
View File
@@ -1,5 +1,5 @@
generator client { generator client {
provider = "prisma-client-js" provider = "prisma-client-js"
binaryTargets = ["linux-musl-openssl-3.0.x", "debian-openssl-3.0.x"] binaryTargets = ["linux-musl-openssl-3.0.x", "debian-openssl-3.0.x"]
} }
@@ -34,254 +34,308 @@ enum FulfillmentType {
} }
model BrandProfile { model BrandProfile {
id String @id @default(uuid()) id String @id @default(uuid())
slug String @unique @default("default-brand") slug String @unique @default("default-brand")
name String name String
templateKey String @default("food") templateKey String @default("food")
tagline String? tagline String?
description String? description String?
avatarUrl String? avatarUrl String?
coverUrl String? coverUrl String?
hours String? hours String?
address String? address String?
deliveryNote String? deliveryNote String?
contactPhone String? contactPhone String?
contactWechat String? contactWechat String?
config Json? miniAppSettings Json?
createdAt DateTime @default(now()) config Json?
updatedAt DateTime @updatedAt createdAt DateTime @default(now())
bookings Booking[] updatedAt DateTime @updatedAt
customerUsers CustomerUser[] bookings Booking[]
tags Tag[] customerUsers CustomerUser[]
trustContents TrustContent[] tags Tag[]
templateInstallations BrandTemplateInstallation[] trustContents TrustContent[]
fieldDefinitions BrandFieldDefinition[] templateInstallations BrandTemplateInstallation[]
offerings Offering[] fieldDefinitions BrandFieldDefinition[]
inquiryForms InquiryForm[] offerings Offering[]
inquirySubmissions InquirySubmission[] inquiryForms InquiryForm[]
inquirySubmissions InquirySubmission[]
capabilityInstallations CapabilityInstallation[] capabilityInstallations CapabilityInstallation[]
capabilityAuditLogs CapabilityAuditLog[] capabilityAuditLogs CapabilityAuditLog[]
adminMemberships BrandMembership[] adminMemberships BrandMembership[]
releases BrandRelease[] releases BrandRelease[]
miniAppReleases MiniAppReleaseTask[]
} }
model BrandRelease { model BrandRelease {
id String @id @default(uuid()) id String @id @default(uuid())
brandId String brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade) brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
version Int version Int
status String @default("published") status String @default("published")
snapshot Json snapshot Json
actorId String actorId String
note String? note String?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
revokedAt DateTime? revokedAt DateTime?
revokedBy String? revokedBy String?
miniAppReleases MiniAppReleaseTask[]
@@unique([brandId, version]) @@unique([brandId, version])
@@index([brandId, status, createdAt]) @@index([brandId, status, createdAt])
} }
model CapabilityInstallation { model CapabilityInstallation {
id String @id @default(uuid()) id String @id @default(uuid())
brandId String brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade) brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
capabilityKey String capabilityKey String
capabilityVersion String capabilityVersion String
status String @default("enabled") status String @default("enabled")
config Json? config Json?
installedAt DateTime @default(now()) installedAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@@unique([brandId, capabilityKey]) @@unique([brandId, capabilityKey])
@@index([brandId, status]) @@index([brandId, status])
} }
enum MiniAppReleaseStatus {
built
uploaded
under_review
rejected
approved
published
failed
}
model MiniAppReleaseTask {
id String @id @default(uuid())
brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
releaseId String?
release BrandRelease? @relation(fields: [releaseId], references: [id], onDelete: SetNull)
version Int
status MiniAppReleaseStatus @default(built)
artifactPath String?
buildLogs Json?
buildStatus MiniAppBuildStatus @default(idle)
actorId String
error String?
weappUploadId String?
audit Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([brandId, version])
@@index([brandId, createdAt])
}
enum MiniAppBuildStatus {
idle
building
success
failed
}
model CapabilityAuditLog { model CapabilityAuditLog {
id String @id @default(uuid()) id String @id @default(uuid())
brandId String brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade) brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
capabilityKey String capabilityKey String
actorId String actorId String
action String action String
fromStatus String? fromStatus String?
toStatus String toStatus String
config Json? config Json?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
@@index([brandId, capabilityKey, createdAt]) @@index([brandId, capabilityKey, createdAt])
} }
model BrandTemplateInstallation { model BrandTemplateInstallation {
id String @id @default(uuid()) id String @id @default(uuid())
brandId String brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade) brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
templateKey String templateKey String
templateVersion String @default("1.0.0") templateVersion String @default("1.0.0")
configSnapshot Json configSnapshot Json
previousSnapshots Json @default("[]") previousSnapshots Json @default("[]")
installedAt DateTime @default(now()) installedAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@@unique([brandId, templateKey]) @@unique([brandId, templateKey])
@@index([brandId]) @@index([brandId])
} }
model BrandFieldDefinition { model BrandFieldDefinition {
id String @id @default(uuid()) id String @id @default(uuid())
brandId String brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade) brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
scope String scope String
key String key String
label String label String
type String type String
required Boolean @default(false) required Boolean @default(false)
isVisible Boolean @default(true) isVisible Boolean @default(true)
sortOrder Int @default(0) sortOrder Int @default(0)
source String @default("custom") source String @default("custom")
isOverridden Boolean @default(false) isOverridden Boolean @default(false)
options Json? options Json?
visibleWhen Json? visibleWhen Json?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@@unique([brandId, scope, key]) @@unique([brandId, scope, key])
@@index([brandId, scope, sortOrder]) @@index([brandId, scope, sortOrder])
} }
model Offering { model Offering {
id String @id @default(uuid()) id String @id @default(uuid())
brandId String brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade) brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
kind String @default("service") kind String @default("service")
name String name String
summary String? summary String?
description String? description String?
coverUrl String? coverUrl String?
priceText String? priceText String?
priceAmount Int? priceAmount Int?
isEnabled Boolean @default(true) isEnabled Boolean @default(true)
sortOrder Int @default(0) sortOrder Int @default(0)
config Json? config Json?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
inquiryForms InquiryForm[] inquiryForms InquiryForm[]
inquirySubmissions InquirySubmission[] inquirySubmissions InquirySubmission[]
bookings Booking[] bookings Booking[]
bookingItems BookingItem[] bookingItems BookingItem[]
@@unique([brandId, name]) @@unique([brandId, name])
@@index([brandId, isEnabled, sortOrder]) @@index([brandId, isEnabled, sortOrder])
} }
model InquiryForm { model InquiryForm {
id String @id @default(uuid()) id String @id @default(uuid())
brandId String brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade) brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
offeringId String? offeringId String?
offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull) offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull)
name String name String
purpose String @default("inquiry") purpose String @default("inquiry")
targetType String @default("brand") targetType String @default("brand")
submissionAction String @default("create-inquiry") submissionAction String @default("create-inquiry")
version Int @default(1) version Int @default(1)
isEnabled Boolean @default(true) isEnabled Boolean @default(true)
fieldsSnapshot Json fieldsSnapshot Json
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
submissions InquirySubmission[] submissions InquirySubmission[]
@@index([brandId, isEnabled]) @@index([brandId, isEnabled])
} }
model InquirySubmission { model InquirySubmission {
id String @id @default(uuid()) id String @id @default(uuid())
brandId String brandId String
inquiryFormId String inquiryFormId String
offeringId String? offeringId String?
customerSubject String customerSubject String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade) brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
inquiryForm InquiryForm @relation(fields: [inquiryFormId], references: [id], onDelete: Restrict) inquiryForm InquiryForm @relation(fields: [inquiryFormId], references: [id], onDelete: Restrict)
offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull) offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull)
formVersion Int formVersion Int
fieldsSnapshot Json fieldsSnapshot Json
values Json values Json
activeFields Json activeFields Json
status String @default("new") status String @default("new")
adminNote String? adminNote String?
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
statusHistory InquirySubmissionStatusHistory[] statusHistory InquirySubmissionStatusHistory[]
createdAt DateTime @default(now()) createdAt DateTime @default(now())
@@index([brandId, createdAt]) @@index([brandId, createdAt])
@@index([brandId, customerSubject, createdAt]) @@index([brandId, customerSubject, createdAt])
@@index([inquiryFormId, formVersion]) @@index([inquiryFormId, formVersion])
} }
model InquirySubmissionStatusHistory { model InquirySubmissionStatusHistory {
id String @id @default(uuid()) id String @id @default(uuid())
submissionId String submissionId String
submission InquirySubmission @relation(fields: [submissionId], references: [id], onDelete: Cascade) submission InquirySubmission @relation(fields: [submissionId], references: [id], onDelete: Cascade)
fromStatus String? fromStatus String?
toStatus String toStatus String
adminNote String? adminNote String?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
@@index([submissionId, createdAt]) @@index([submissionId, createdAt])
} }
model TrustContent { model TrustContent {
id String @id @default(uuid()) id String @id @default(uuid())
brandId String brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade) brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
type String type String
title String title String
summary String? summary String?
content String content String
coverUrl String? coverUrl String?
sortOrder Int @default(0) sortOrder Int @default(0)
isPublished Boolean @default(true) isPublished Boolean @default(true)
config Json? config Json?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@@index([brandId, type, sortOrder]) @@index([brandId, type, sortOrder])
} }
model CustomerUser { model CustomerUser {
id String @id @default(uuid()) id String @id @default(uuid())
brandId String brandId String
brand BrandProfile @relation(fields: [brandId], references: [id]) brand BrandProfile @relation(fields: [brandId], references: [id])
openid String openid String
lastLoginAt DateTime @default(now()) lastLoginAt DateTime @default(now())
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
bookings Booking[] bookings Booking[]
@@unique([brandId, openid]) @@unique([brandId, openid])
} }
model Booking { model Booking {
id String @id @default(uuid()) id String @id @default(uuid())
bookingNo String @unique bookingNo String @unique
brandId String brandId String
brand BrandProfile @relation(fields: [brandId], references: [id]) brand BrandProfile @relation(fields: [brandId], references: [id])
customerUserId String customerUserId String
customerUser CustomerUser @relation(fields: [customerUserId], references: [id]) customerUser CustomerUser @relation(fields: [customerUserId], references: [id])
requestType BookingRequestType requestType BookingRequestType
customerName String customerName String
phone String? phone String?
wechatId String? wechatId String?
contactPreference ContactPreference contactPreference ContactPreference
fulfillmentType FulfillmentType? fulfillmentType FulfillmentType?
offeringId String? offeringId String?
offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull) offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull)
requestedDate DateTime? requestedDate DateTime?
requestedTime String? requestedTime String?
deliveryAddress String? deliveryAddress String?
estimatedAmount Int? estimatedAmount Int?
extraData Json? extraData Json?
note String? note String?
adminNote String? adminNote String?
status BookingStatus @default(received) status BookingStatus @default(received)
workflowKey String @default("booking.basic") workflowKey String @default("booking.basic")
workflowVersion String @default("1.0.0") workflowVersion String @default("1.0.0")
currentState String @default("received") currentState String @default("received")
isRead Boolean @default(false) isRead Boolean @default(false)
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
items BookingItem[] items BookingItem[]
tags BookingTag[] tags BookingTag[]
stateTransitions BookingStateTransition[] stateTransitions BookingStateTransition[]
@@index([brandId, status, createdAt]) @@index([brandId, status, createdAt])
@@index([customerUserId, createdAt]) @@index([customerUserId, createdAt])
} }
@@ -296,57 +350,60 @@ model BookingStateTransition {
toState String toState String
actorRole String actorRole String
createdAt DateTime @default(now()) createdAt DateTime @default(now())
@@index([bookingId, createdAt]) @@index([bookingId, createdAt])
} }
model BookingItem { model BookingItem {
id String @id @default(uuid()) id String @id @default(uuid())
bookingId String bookingId String
booking Booking @relation(fields: [bookingId], references: [id], onDelete: Cascade) booking Booking @relation(fields: [bookingId], references: [id], onDelete: Cascade)
offeringId String? offeringId String?
offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull) offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull)
serviceNameSnapshot String serviceNameSnapshot String
unitPriceSnapshot Int unitPriceSnapshot Int
quantity Int quantity Int
subtotalSnapshot Int subtotalSnapshot Int
} }
model Tag { model Tag {
id String @id @default(uuid()) id String @id @default(uuid())
brandId String brandId String
brand BrandProfile @relation(fields: [brandId], references: [id]) brand BrandProfile @relation(fields: [brandId], references: [id])
name String name String
isPreset Boolean @default(false) isPreset Boolean @default(false)
isEnabled Boolean @default(true) isEnabled Boolean @default(true)
createdAt DateTime @default(now()) createdAt DateTime @default(now())
bookings BookingTag[] bookings BookingTag[]
@@unique([brandId, name]) @@unique([brandId, name])
} }
model AdminUser { model AdminUser {
id String @id @default(uuid()) id String @id @default(uuid())
username String @unique username String @unique
passwordHash String passwordHash String
displayName String displayName String
role String @default("admin") role String @default("admin")
isEnabled Boolean @default(true) isEnabled Boolean @default(true)
mustChangePassword Boolean @default(false) mustChangePassword Boolean @default(false)
lastLoginAt DateTime? lastLoginAt DateTime?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
memberships BrandMembership[] memberships BrandMembership[]
} }
model BrandMembership { model BrandMembership {
id String @id @default(uuid()) id String @id @default(uuid())
adminUserId String adminUserId String
brandId String brandId String
role String @default("admin") role String @default("admin")
isEnabled Boolean @default(true) isEnabled Boolean @default(true)
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
adminUser AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Cascade) adminUser AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Cascade)
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade) brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
@@unique([adminUserId, brandId]) @@unique([adminUserId, brandId])
@@index([brandId, isEnabled]) @@index([brandId, isEnabled])
} }
@@ -356,5 +413,6 @@ model BookingTag {
tagId String tagId String
booking Booking @relation(fields: [bookingId], references: [id], onDelete: Cascade) booking Booking @relation(fields: [bookingId], references: [id], onDelete: Cascade)
tag Tag @relation(fields: [tagId], references: [id], onDelete: Cascade) tag Tag @relation(fields: [tagId], references: [id], onDelete: Cascade)
@@id([bookingId, tagId]) @@id([bookingId, tagId])
} }
+49 -1
View File
@@ -1,5 +1,10 @@
import { PrismaClient, type Prisma } from "@prisma/client"; import { PrismaClient, type Prisma } from "@prisma/client";
import { getTemplatePackageManifestForVisualKey } from "@personal-brand/config"; import {
getBrandTemplate,
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
getVisualTemplateManifest,
} from "@personal-brand/config";
import bcrypt from "bcryptjs"; import bcrypt from "bcryptjs";
import { buildBrandReleaseSnapshot } from "../src/brand-release.service.js"; import { buildBrandReleaseSnapshot } from "../src/brand-release.service.js";
@@ -768,6 +773,47 @@ async function ensureSeedRelease(brandId: string, actorId: string): Promise<void
}); });
} }
/**
* 行业的模板台账只能有一个,且必须与品牌身份(BrandProfile.templateKey)一致。
* seed 之前只写品牌身份、不建台账,导致后台「尚未安装模板」而公开运行时已在跑该模板;
* 这里按品牌身份补齐台账,让「版本与升级」「回滚」有据可依。
*/
async function ensureTemplateInstallation(brandId: string): Promise<void> {
const brand = await prisma.brandProfile.findUniqueOrThrow({
where: { id: brandId },
select: { templateKey: true, config: true },
});
const template = getBrandTemplate(brand.templateKey);
if (!template) throw new Error("Development brand has an unknown industry template");
const config =
brand.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const configuredVisual =
typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : undefined;
const visualKey = configuredVisual ?? getDefaultVisualTemplateKey(template.key);
if (!getVisualTemplateManifest(visualKey))
throw new Error("Development brand has an unknown visual template");
const configSnapshot = {
schemaVersion: "1.0",
version: template.version,
industryTemplate: template,
visualTemplate: getVisualTemplateManifest(visualKey),
capabilities: template.capabilities,
} as unknown as Prisma.InputJsonValue;
const existing = await prisma.brandTemplateInstallation.findFirst({ where: { brandId } });
if (existing) {
await prisma.brandTemplateInstallation.update({
where: { id: existing.id },
data: { templateKey: template.key, templateVersion: template.version, configSnapshot },
});
return;
}
await prisma.brandTemplateInstallation.create({
data: { brandId, templateKey: template.key, templateVersion: template.version, configSnapshot },
});
}
async function main(): Promise<void> { async function main(): Promise<void> {
const brand = await prisma.brandProfile.upsert({ const brand = await prisma.brandProfile.upsert({
where: { id: "00000000-0000-0000-0000-000000000001" }, where: { id: "00000000-0000-0000-0000-000000000001" },
@@ -795,6 +841,7 @@ async function main(): Promise<void> {
}); });
await ensureRuntimeContent(brand.id, runtimeSeedTemplates.food); await ensureRuntimeContent(brand.id, runtimeSeedTemplates.food);
await ensureTemplateInstallation(brand.id);
for (const name of ["普通套餐", "私厨", "配送", "自取", "熟客", "重点跟进"]) { for (const name of ["普通套餐", "私厨", "配送", "自取", "熟客", "重点跟进"]) {
await prisma.tag.upsert({ await prisma.tag.upsert({
@@ -851,6 +898,7 @@ async function main(): Promise<void> {
create: { adminUserId: admin.id, brandId: doorsBrand.id, role: "owner" }, create: { adminUserId: admin.id, brandId: doorsBrand.id, role: "owner" },
}); });
await ensureRuntimeContent(doorsBrand.id, runtimeSeedTemplates.doors); await ensureRuntimeContent(doorsBrand.id, runtimeSeedTemplates.doors);
await ensureTemplateInstallation(doorsBrand.id);
await ensureSeedRelease(brand.id, admin.id); await ensureSeedRelease(brand.id, admin.id);
await ensureSeedRelease(doorsBrand.id, admin.id); await ensureSeedRelease(doorsBrand.id, admin.id);
} }
+6
View File
@@ -19,6 +19,12 @@ export class AdminAccessService {
throw new UnauthorizedException("管理员登录态无效或已过期"); throw new UnauthorizedException("管理员登录态无效或已过期");
} }
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限"); if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
const user = await this.prisma.adminUser.findUnique({
where: { id: identity.subject },
select: { mustChangePassword: true },
});
if (!user || user.mustChangePassword)
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
const membership = await this.prisma.brandMembership.findUnique({ const membership = await this.prisma.brandMembership.findUnique({
where: { adminUserId_brandId: { adminUserId: identity.subject, brandId: identity.brandId } }, where: { adminUserId_brandId: { adminUserId: identity.subject, brandId: identity.brandId } },
}); });
+11 -5
View File
@@ -3,19 +3,25 @@ import type { CanActivate, ExecutionContext } from "@nestjs/common";
import type { FastifyRequest } from "fastify"; import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "./admin-access.service.js"; import { AdminAccessService } from "./admin-access.service.js";
const PATH_METADATA = "path";
@Injectable() @Injectable()
export class AdminMembershipGuard implements CanActivate { export class AdminMembershipGuard implements CanActivate {
constructor(private readonly access: AdminAccessService) {} constructor(private readonly access: AdminAccessService) {}
canActivate(context: ExecutionContext): Promise<boolean> { canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<FastifyRequest>(); const request = context.switchToHttp().getRequest<FastifyRequest>();
if (request.url.startsWith("/admin/session/login")) return Promise.resolve(true); const handlerPath = Reflect.getMetadata(PATH_METADATA, context.getHandler());
if (!request.url.startsWith("/admin/")) return Promise.resolve(true); const controllerPath = Reflect.getMetadata(PATH_METADATA, context.getClass());
const routePath = `${controllerPath ?? ""}/${handlerPath ?? ""}`.replace(/^\/+|\/+$/g, "");
if (routePath === "admin/session/login") return Promise.resolve(true);
if (routePath === "admin/session/change-password") return Promise.resolve(true);
if (!routePath.startsWith("admin/")) return Promise.resolve(true);
if ( if (
/^\/admin\/workspace\/(install|capabilities(?:\/|$)|template(?:\/|$)|fields(?:\/|$))/.test( /^admin\/workspace\/(install|capabilities(?:\/|$)|template(?:\/|$)|fields(?:\/|$))/.test(
request.url, routePath,
) || ) ||
/^\/admin\/config\/visual-template(?:\/|$)/.test(request.url) /^admin\/config\/visual-template(?:\/|$)/.test(routePath)
) { ) {
return this.access.requireRole(request, ["owner", "admin", "platform-admin"]); return this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
} }
-463
View File
@@ -1,463 +0,0 @@
import {
BadRequestException,
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Req,
} from "@nestjs/common";
import { Prisma } from "@prisma/client";
import type { FastifyRequest } from "fastify";
import { PrismaService } from "./prisma.service.js";
import {
InstallTemplateDto,
CreateOfferingDto,
UpdateOfferingDto,
CreateFieldDefinitionDto,
UpdateFieldDefinitionDto,
CreateInquiryFormDto,
UpdateInquiryFormDto,
UpdateInquirySubmissionDto,
UpdateCapabilityInstallationDto,
} from "./admin.dto.js";
import {
capabilityRegistry,
capabilityMetadata,
validateCapabilityConfig,
capabilityPlugins,
getBrandTemplate,
getTemplateSampleContent,
} from "@personal-brand/config";
import { TemplateWorkspaceService } from "./template-workspace.service.js";
import { validateFieldSnapshot } from "@personal-brand/validation";
import { AdminOfferingService } from "./modules/workspace/admin-offering.service.js";
import { AdminWorkspaceService } from "./modules/workspace/admin-workspace.service.js";
import { requireAdminIdentity } from "./modules/workspace/admin-access.identity.js";
@Controller("admin/workspace")
class AdminWorkspaceController {
constructor(
private readonly prisma: PrismaService,
private readonly templateWorkspace: TemplateWorkspaceService,
private readonly offeringService: AdminOfferingService,
private readonly workspaceService: AdminWorkspaceService,
) {}
@Get("offerings")
listOfferings(@Req() request: FastifyRequest): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
return this.offeringService.list(brandId);
}
@Post("offerings")
createOffering(
@Req() request: FastifyRequest,
@Body() body: CreateOfferingDto,
): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
return this.offeringService.create(brandId, body);
}
@Patch("offerings/:id")
async updateOffering(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateOfferingDto,
): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
return this.offeringService.update(brandId, id, body);
}
@Delete("offerings/:id")
async deleteOffering(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
return this.offeringService.delete(brandId, id);
}
@Get()
get(@Req() request: FastifyRequest): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
return this.workspaceService.get(brandId);
}
@Get("preview")
async getPreviewWorkspace(@Req() request: FastifyRequest): Promise<unknown> {
const { brandId } = requireAdminIdentity(request);
return this.workspaceService.getPreview(brandId);
}
@Post("install")
async install(
@Req() request: FastifyRequest,
@Body() body: InstallTemplateDto,
): Promise<unknown> {
const { brandId } = requireAdminIdentity(request);
return this.templateWorkspace.install(brandId, body.templateKey);
}
@Get("capabilities")
async listCapabilities(@Req() request: FastifyRequest): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
const [templateKey, installations] = await Promise.all([
this.templateWorkspace.getEffectiveTemplateKey(brandId),
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
]);
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
const template = getBrandTemplate(templateKey);
const optionalCapabilityKeys = Object.entries(capabilityRegistry)
.filter(([, definition]) => "optional" in definition && definition.optional)
.map(([key]) => key);
return [...new Set([...(template?.capabilities ?? []), ...optionalCapabilityKeys])]
.map((key) => capabilityRegistry[key as keyof typeof capabilityRegistry])
.filter(Boolean)
.map((definition) => {
const item = installed.get(definition.key);
const metadata = capabilityMetadata(definition.key);
return {
id: item?.id ?? null,
capabilityKey: definition.key,
capabilityVersion: item?.capabilityVersion ?? definition.version,
status: item?.status ?? "enabled",
config: item?.config ?? {},
source: item ? "brand" : "template",
...(metadata ?? {}),
updatedAt: item?.updatedAt ?? null,
};
});
}
@Get("sample-content/preview")
async previewSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
const sample = getTemplateSampleContent(templateKey);
if (!sample) throw new BadRequestException("模板示例内容不存在");
const [offerings, trustContent, fields] = await Promise.all([
this.prisma.offering.count({ where: { brandId } }),
this.prisma.trustContent.count({ where: { brandId } }),
this.prisma.brandFieldDefinition.count({ where: { brandId, source: "sample" } }),
]);
return {
templateKey: sample.templateKey,
alreadyImported: offerings > 0 || trustContent > 0 || fields > 0,
counts: {
offerings: sample.offerings.length,
trustContent: sample.trustContent.length,
fields: sample.fields.length,
inquiryForms: 1,
},
willCreateInquiryForm:
(await this.prisma.inquiryForm.count({ where: { brandId, isEnabled: true } })) === 0,
};
}
@Post("sample-content/import")
async importSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
const identity = requireAdminIdentity(request);
const brandId = identity.brandId;
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
const sample = getTemplateSampleContent(templateKey);
if (!sample) throw new BadRequestException("模板示例内容不存在");
const fieldIssues = validateFieldSnapshot(sample.fields);
if (fieldIssues.length) throw new BadRequestException("模板咨询表单示例字段无效");
const existing = await this.prisma.brandFieldDefinition.count({
where: { brandId, source: "sample" },
});
const existingOffering = await this.prisma.offering.count({
where: { brandId, name: "序章·入户门" },
});
if (existing || existingOffering) throw new BadRequestException("示例内容已经导入");
const result = await this.prisma.$transaction(async (tx) => {
const offerings = await tx.offering.createMany({
data: sample.offerings.map((item, sortOrder) => ({
brandId,
kind: item.kind,
name: item.name,
summary: item.summary,
config: { categoryKey: item.categoryKey },
sortOrder,
isEnabled: true,
})),
});
const trust = await tx.trustContent.createMany({
data: sample.trustContent.map((item, sortOrder) => ({
brandId,
type: item.type,
title: item.title,
content: item.content,
...(item.config ? { config: item.config as Prisma.InputJsonValue } : {}),
sortOrder,
isPublished: false,
})),
});
const fields = await tx.brandFieldDefinition.createMany({
data: sample.fields.map((item, sortOrder) => ({
brandId,
scope: "inquiry",
key: item.key,
label: item.label,
type: item.type,
sortOrder,
source: "sample",
required: item.required,
})),
});
const hasEnabledForm = await tx.inquiryForm.count({ where: { brandId, isEnabled: true } });
const inquiryForm = hasEnabledForm
? null
: await tx.inquiryForm.create({
data: {
brandId,
name: sample.inquiryFormName,
purpose: "inquiry",
targetType: "brand",
submissionAction: "create-inquiry",
fieldsSnapshot: sample.fields,
isEnabled: true,
},
});
await tx.capabilityAuditLog.create({
data: {
brandId,
capabilityKey: sample.capabilityKey,
actorId: identity.subject,
action: "sample_content_imported",
toStatus: "enabled",
config: {
offerings: offerings.count,
trustContent: trust.count,
fields: fields.count,
inquiryForms: inquiryForm ? 1 : 0,
},
},
});
return {
offerings: offerings.count,
trustContent: trust.count,
fields: fields.count,
inquiryForms: inquiryForm ? 1 : 0,
};
});
return { imported: true, counts: result };
}
@Patch("capabilities/:key")
async updateCapability(
@Req() request: FastifyRequest,
@Param("key") key: string,
@Body() body: UpdateCapabilityInstallationDto,
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const brandId = identity.brandId;
const template = getBrandTemplate(
await this.templateWorkspace.getEffectiveTemplateKey(brandId),
);
if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins))
throw new BadRequestException("能力未被当前模板声明");
const existing = await this.prisma.capabilityInstallation.findUnique({
where: { brandId_capabilityKey: { brandId, capabilityKey: key } },
});
const definition = capabilityRegistry[key as keyof typeof capabilityRegistry];
if (definition && "disablePolicy" in definition && definition.disablePolicy === "disabled")
throw new BadRequestException("核心能力不可移除");
const configErrors = validateCapabilityConfig(key as never, body.config);
if (configErrors === null) throw new BadRequestException("能力配置字段无效");
if (Object.keys(configErrors).length)
throw new BadRequestException({ message: "能力配置字段无效", errors: configErrors });
return this.prisma.$transaction(async (tx) => {
const installation = await tx.capabilityInstallation.upsert({
where: { brandId_capabilityKey: { brandId, capabilityKey: key } },
create: {
brandId,
capabilityKey: key,
capabilityVersion: definition?.version ?? "1.0.0",
status: body.status,
config: (body.config ?? {}) as Prisma.InputJsonValue,
},
update: {
...(definition ? { capabilityVersion: definition.version } : {}),
status: body.status,
...(body.config === undefined ? {} : { config: body.config as Prisma.InputJsonValue }),
},
});
await tx.capabilityAuditLog.create({
data: {
brandId,
capabilityKey: key,
actorId: identity.subject,
action: existing ? "updated" : "installed",
fromStatus: existing?.status ?? null,
toStatus: body.status,
config: (body.config ?? existing?.config ?? {}) as Prisma.InputJsonValue,
},
});
return installation;
});
}
@Get("template/preview")
async previewTemplate(@Req() request: FastifyRequest): Promise<unknown> {
const { brandId } = requireAdminIdentity(request);
return this.templateWorkspace.preview(brandId);
}
@Post("template/upgrade")
async upgradeTemplate(@Req() request: FastifyRequest): Promise<unknown> {
const { brandId } = requireAdminIdentity(request);
return this.templateWorkspace.upgrade(brandId);
}
@Post("template/rollback")
async rollbackTemplate(@Req() request: FastifyRequest): Promise<unknown> {
const { brandId } = requireAdminIdentity(request);
return this.templateWorkspace.rollback(brandId);
}
@Post("fields")
createField(
@Req() request: FastifyRequest,
@Body() body: CreateFieldDefinitionDto,
): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
return this.prisma.brandFieldDefinition.create({
data: {
...body,
brandId,
source: "custom",
options: body.options as Prisma.InputJsonValue,
visibleWhen: body.visibleWhen as Prisma.InputJsonValue,
},
});
}
@Patch("fields/:id")
async updateField(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateFieldDefinitionDto,
): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
const item = await this.prisma.brandFieldDefinition.findFirst({
where: { id, brandId },
});
if (!item) throw new BadRequestException("品牌字段不存在");
const { options, visibleWhen, ...fields } = body;
return this.prisma.brandFieldDefinition.update({
where: { id },
data: {
...fields,
...(options === undefined ? {} : { options: options as Prisma.InputJsonValue }),
...(visibleWhen === undefined ? {} : { visibleWhen: visibleWhen as Prisma.InputJsonValue }),
},
});
}
@Delete("fields/:id")
async deleteField(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
const item = await this.prisma.brandFieldDefinition.findFirst({
where: { id, brandId, source: "custom" },
});
if (!item) throw new BadRequestException("自定义字段不存在或不可删除");
await this.prisma.brandFieldDefinition.delete({ where: { id } });
return { deleted: true };
}
@Get("forms")
listForms(@Req() request: FastifyRequest): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
return this.prisma.inquiryForm.findMany({
where: { brandId },
orderBy: { updatedAt: "desc" },
});
}
@Get("submissions")
listSubmissions(@Req() request: FastifyRequest): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
return this.prisma.inquirySubmission.findMany({
where: { brandId },
include: {
inquiryForm: { select: { name: true } },
offering: { select: { id: true, name: true } },
},
orderBy: { createdAt: "desc" },
});
}
@Patch("submissions/:id")
async updateSubmission(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateInquirySubmissionDto,
): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
const item = await this.prisma.inquirySubmission.findFirst({
where: { id, brandId },
});
if (!item) throw new BadRequestException("咨询记录不存在");
return this.prisma.$transaction(async (tx) => {
const updated = await tx.inquirySubmission.update({
where: { id },
data: {
status: body.status,
...(body.adminNote === undefined ? {} : { adminNote: body.adminNote }),
},
});
if (item.status !== body.status || body.adminNote !== undefined) {
await tx.inquirySubmissionStatusHistory.create({
data: {
submissionId: id,
fromStatus: item.status,
toStatus: body.status,
adminNote: body.adminNote ?? null,
},
});
}
return updated;
});
}
@Post("forms")
createForm(@Req() request: FastifyRequest, @Body() body: CreateInquiryFormDto): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
if (validateFieldSnapshot(body.fieldsSnapshot).length)
throw new BadRequestException("咨询表单字段定义无效");
return this.prisma.inquiryForm.create({
data: {
...body,
brandId,
version: 1,
fieldsSnapshot: body.fieldsSnapshot as Prisma.InputJsonValue,
},
});
}
@Patch("forms/:id")
async updateForm(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateInquiryFormDto,
): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
const item = await this.prisma.inquiryForm.findFirst({
where: { id, brandId },
});
if (!item) throw new BadRequestException("咨询表单不存在");
const { fieldsSnapshot, ...fields } = body;
if (fieldsSnapshot !== undefined && validateFieldSnapshot(fieldsSnapshot).length)
throw new BadRequestException("咨询表单字段定义无效");
return this.prisma.inquiryForm.update({
where: { id },
data: {
...fields,
...(fieldsSnapshot === undefined
? {}
: { fieldsSnapshot: fieldsSnapshot as Prisma.InputJsonValue }),
...(fieldsSnapshot === undefined ? {} : { version: { increment: 1 } }),
},
});
}
}
export { AdminWorkspaceController };
+3 -4
View File
@@ -13,10 +13,8 @@ import {
} from "class-validator"; } from "class-validator";
import { brandTemplateKeys } from "@personal-brand/config"; import { brandTemplateKeys } from "@personal-brand/config";
import type { BrandTemplateKey } from "@personal-brand/config"; import type { BrandTemplateKey } from "@personal-brand/config";
export class UpdateBrandDto { export class UpdateBrandDto {
@IsOptional() @IsString() name?: string; @IsOptional() @IsString() name?: string;
@IsOptional() @IsIn(brandTemplateKeys) templateKey?: BrandTemplateKey;
@IsOptional() @IsString() tagline?: string; @IsOptional() @IsString() tagline?: string;
@IsOptional() @IsString() description?: string; @IsOptional() @IsString() description?: string;
@IsOptional() @IsString() avatarUrl?: string; @IsOptional() @IsString() avatarUrl?: string;
@@ -184,7 +182,7 @@ export class UpdateFieldDefinitionDto {
export class CreateInquiryFormDto { export class CreateInquiryFormDto {
@IsString() name!: string; @IsString() name!: string;
@IsOptional() @IsString() offeringId?: string; @IsOptional() @IsString() offeringId?: string | null;
@IsOptional() @IsIn(["inquiry", "booking", "quote-request"]) purpose?: string; @IsOptional() @IsIn(["inquiry", "booking", "quote-request"]) purpose?: string;
@IsOptional() @IsIn(["brand", "offering"]) targetType?: string; @IsOptional() @IsIn(["brand", "offering"]) targetType?: string;
@IsOptional() @IsOptional()
@@ -196,7 +194,8 @@ export class CreateInquiryFormDto {
export class UpdateInquiryFormDto { export class UpdateInquiryFormDto {
@IsOptional() @IsString() name?: string; @IsOptional() @IsString() name?: string;
@IsOptional() @IsString() offeringId?: string; // 允许显式传 null 表示「改回品牌通用入口」,因此不能只用 @IsString。
@IsOptional() @IsString() offeringId?: string | null;
@IsOptional() @IsIn(["inquiry", "booking", "quote-request"]) purpose?: string; @IsOptional() @IsIn(["inquiry", "booking", "quote-request"]) purpose?: string;
@IsOptional() @IsIn(["brand", "offering"]) targetType?: string; @IsOptional() @IsIn(["brand", "offering"]) targetType?: string;
@IsOptional() @IsOptional()
+20 -80
View File
@@ -1,94 +1,34 @@
import "reflect-metadata"; import "reflect-metadata";
import { Controller, Get, Module, ValidationPipe } from "@nestjs/common"; import { Module, ValidationPipe } from "@nestjs/common";
import { APP_GUARD } from "@nestjs/core";
import type { NestFastifyApplication } from "@nestjs/platform-fastify"; import type { NestFastifyApplication } from "@nestjs/platform-fastify";
import { PrismaService } from "./prisma.service.js";
import { WechatAuthService } from "./wechat-auth.js";
import { BookingService } from "./booking.service.js";
import { AdminAuthService } from "./admin-auth.service.js";
import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js"; import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js";
import { AdminWorkspaceController } from "./admin-workspace.controller.js";
import {
PublicWorkspaceController,
PublicWorkspaceService,
} from "./modules/public/public-workspace.controller.js";
import { PublicBrandContextService } from "./modules/public/public-brand-context.service.js";
import { AdminOfferingService } from "./modules/workspace/admin-offering.service.js";
import { AdminWorkspaceService } from "./modules/workspace/admin-workspace.service.js";
import { AdminConfigController } from "./modules/admin/admin-config.controller.js";
import { AdminUploadController } from "./modules/admin/admin-upload.controller.js";
import { AdminLocalUploadController } from "./modules/admin/admin-local-upload.controller.js";
import { PublicOfferingController } from "./modules/public/public-offering.controller.js";
import { PublicInquiryFormController } from "./modules/public/public-inquiry-form.controller.js";
import { CustomerInquirySubmissionController } from "./modules/customer/customer-inquiry-submission.controller.js";
import { TemplateWorkspaceService } from "./template-workspace.service.js";
import { AdminAccessService } from "./admin-access.service.js";
import { AdminMembershipGuard } from "./admin-membership.guard.js"; import { AdminMembershipGuard } from "./admin-membership.guard.js";
import { BrandReleaseService } from "./brand-release.service.js"; import { AdminModule } from "./modules/admin/admin.module.js";
import { BrandReleaseApiService } from "./brand-release-api.service.js"; import { CustomerModule } from "./modules/customer/customer.module.js";
import { AdminReleaseController } from "./modules/admin/admin-release.controller.js"; import { HealthModule } from "./modules/health.module.js";
import { import { InfrastructureModule } from "./modules/infrastructure.module.js";
CustomerSessionController, import { PublicModule } from "./modules/public/public.module.js";
AdminSessionController, import { SessionModule } from "./modules/session/session.module.js";
} from "./modules/session/session.controller.js"; import { TenantModule } from "./modules/tenant/tenant.module.js";
import { AdminBookingController } from "./modules/admin/admin-booking.controller.js"; import { WorkspaceModule } from "./modules/workspace/workspace.module.js";
import { CustomerBookingController } from "./modules/customer/customer-booking.controller.js";
import { TenantController } from "./modules/tenant/tenant.controller.js";
import {
PublicController,
PublicTemplateController,
PublicTrustContentController,
} from "./modules/public/public.controller.js";
@Controller("health")
export class HealthController {
@Get()
check(): { status: string; service: string } {
return { status: "ok", service: "personal-brand-api" };
}
}
@Module({ @Module({
controllers: [ imports: [
HealthController, InfrastructureModule,
PublicController, PublicModule,
PublicTrustContentController, CustomerModule,
PublicTemplateController, SessionModule,
PublicWorkspaceController, TenantModule,
PublicOfferingController, WorkspaceModule,
PublicInquiryFormController, AdminModule,
CustomerInquirySubmissionController, HealthModule,
AdminWorkspaceController,
CustomerSessionController,
AdminSessionController,
CustomerBookingController,
TenantController,
AdminBookingController,
AdminConfigController,
AdminReleaseController,
AdminUploadController,
AdminLocalUploadController,
], ],
providers: [ providers: [{ provide: APP_GUARD, useClass: AdminMembershipGuard }],
PrismaService,
WechatAuthService,
BookingService,
AdminAuthService,
TemplateWorkspaceService,
AdminAccessService,
AdminMembershipGuard,
BrandReleaseService,
BrandReleaseApiService,
PublicBrandContextService,
PublicWorkspaceService,
AdminOfferingService,
AdminWorkspaceService,
],
exports: [PrismaService, WechatAuthService],
}) })
export class AppModule {} export class AppModule {}
export function configureApp(app: NestFastifyApplication): void { export function configureApp(app: NestFastifyApplication): void {
app.useGlobalGuards(app.get(AdminMembershipGuard));
app.useGlobalPipes( app.useGlobalPipes(
new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }), new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }),
); );
+11
View File
@@ -22,6 +22,8 @@ export interface CreateBookingInput {
items?: Array<{ offeringId: string; quantity: number }>; items?: Array<{ offeringId: string; quantity: number }>;
} }
export type CustomerIdentity = { brandId: string; openid: string };
@Injectable() @Injectable()
export class BookingService { export class BookingService {
constructor( constructor(
@@ -29,6 +31,15 @@ export class BookingService {
private readonly releases: BrandReleaseService, private readonly releases: BrandReleaseService,
) {} ) {}
async requireCustomer(identity: CustomerIdentity): Promise<string> {
const customer = await this.prisma.customerUser.findUnique({
where: { brandId_openid: identity },
select: { id: true },
});
if (!customer) throw new BadRequestException("请先完成微信登录");
return customer.id;
}
async create(brandId: string, customerUserId: string, input: CreateBookingInput) { async create(brandId: string, customerUserId: string, input: CreateBookingInput) {
const snapshot = await this.releases.getPublishedSnapshot(brandId); const snapshot = await this.releases.getPublishedSnapshot(brandId);
if (!snapshot) throw new BadRequestException("品牌尚未发布"); if (!snapshot) throw new BadRequestException("品牌尚未发布");
+27 -18
View File
@@ -78,7 +78,7 @@ export class BrandReleaseApiService {
}), }),
database.inquiryForm.findMany({ database.inquiryForm.findMany({
where: { brandId, isEnabled: true }, where: { brandId, isEnabled: true },
select: { offeringId: true, fieldsSnapshot: true }, select: { offeringId: true, name: true, fieldsSnapshot: true },
}), }),
database.trustContent.findMany({ database.trustContent.findMany({
where: { brandId, isPublished: true }, where: { brandId, isPublished: true },
@@ -92,12 +92,17 @@ export class BrandReleaseApiService {
), ),
); );
const offeringIds = new Set(offerings.map((item) => item.id)); const offeringIds = new Set(offerings.map((item) => item.id));
const validFields = (form: { fieldsSnapshot: unknown }) =>
Array.isArray(form.fieldsSnapshot) &&
form.fieldsSnapshot.length > 0 &&
validateFieldSnapshot(form.fieldsSnapshot).length === 0;
const usableForms = forms.filter( const usableForms = forms.filter(
(form) => (form) => (form.offeringId === null || offeringIds.has(form.offeringId)) && validFields(form),
(form.offeringId === null || offeringIds.has(form.offeringId)) && );
Array.isArray(form.fieldsSnapshot) && // 挂在某个业务上的表单,一旦该业务被停用就再也进不去,小程序也没有入口。这种情况要在发布清单里说清楚,
form.fieldsSnapshot.length > 0 && // 否则只会显示「可用的咨询表单:待完善」,运营者不知道去哪儿改。
validateFieldSnapshot(form.fieldsSnapshot).length === 0, const dormantForms = forms.filter(
(form) => form.offeringId !== null && !offeringIds.has(form.offeringId) && validFields(form),
); );
const checks: Array<{ const checks: Array<{
key: string; key: string;
@@ -108,38 +113,43 @@ export class BrandReleaseApiService {
}> = [ }> = [
{ {
key: "brand", key: "brand",
label: "请先完善品牌名称", label: "品牌名称",
passed: Boolean(brand?.name.trim()), passed: Boolean(brand?.name.trim()),
destination: "/admin/brand", destination: "/admin/brand",
}, },
{ {
key: "positioning", key: "positioning",
label: "请先完善品牌定位和介绍", label: "品牌定位和介绍",
passed: Boolean(brand?.tagline?.trim() && brand.description?.trim()), passed: Boolean(brand?.tagline?.trim() && brand.description?.trim()),
destination: "/admin/brand", destination: "/admin/brand",
}, },
{ key: "template", label: "当前行业模板不存在", passed: Boolean(template) }, { key: "template", label: "行业模板配置", passed: Boolean(template) },
{ {
key: "visual", key: "visual",
label: "当前视觉模板不适配行业模板", label: "视觉模板与行业模板的适配",
passed: Boolean(visual && template && isVisualTemplateCompatible(visual, template.key)), passed: Boolean(visual && template && isVisualTemplateCompatible(visual, template.key)),
destination: "/admin/publication", destination: "/admin/publication",
}, },
{ {
key: "offerings", key: "offerings",
label: "至少需要一项已启用的业务提供项", label: "已启用的业务提供项",
passed: offerings.length > 0, passed: offerings.length > 0,
destination: "/admin/services", destination: "/admin/services",
}, },
{ {
key: "forms", key: "forms",
label: "至少需要一个可用的咨询表单", label: "可用的咨询表单",
passed: usableForms.length > 0, passed: usableForms.length > 0,
...(dormantForms.length === 0
? {}
: {
help: `「${dormantForms.map((form) => form.name).join("」「")}」关联的业务提供项已停用,该表单在小程序里没有入口;请启用对应业务,或把表单改回品牌通用入口。`,
}),
destination: "/admin/workspace", destination: "/admin/workspace",
}, },
{ {
key: "trust", key: "trust",
label: "至少需要一条已发布的信任内容", label: "已发布的信任内容",
passed: validTrustItems.length > 0, passed: validTrustItems.length > 0,
destination: "/admin/trust", destination: "/admin/trust",
}, },
@@ -149,7 +159,7 @@ export class BrandReleaseApiService {
if (type.required !== true) continue; if (type.required !== true) continue;
checks.push({ checks.push({
key: `trust:${type.type}`, key: `trust:${type.type}`,
label: `请完善${type.label}`, label: type.label,
passed: passed:
publishedTrustTypes.has(type.type) && publishedTrustTypes.has(type.type) &&
(type.maxPublishedItems === undefined || (type.maxPublishedItems === undefined ||
@@ -176,9 +186,8 @@ export class BrandReleaseApiService {
}); });
checks.push({ checks.push({
key: `content:${section.key}:${field.key}`, key: `content:${section.key}:${field.key}`,
label: present // 检查项只描述「要检查什么」,是否完成由 UI 的状态标签表达,避免出现「已完成 · 请先完善…」这类自相矛盾的文案。
? `${section.title}:${field.label}` label: `${section.title}:${field.label}`,
: `请补充「${section.title}」中的「${field.label}」`,
passed: present, passed: present,
help: section.description, help: section.description,
destination: destination:
@@ -202,7 +211,7 @@ export class BrandReleaseApiService {
: trustItems.length > 0; : trustItems.length > 0;
checks.push({ checks.push({
key: `asset:${String(slot.key)}`, key: `asset:${String(slot.key)}`,
label: present ? `已添加${String(slot.label)}` : `请添加${String(slot.label)}`, label: String(slot.label),
passed: present, passed: present,
help: String(slot.help), help: String(slot.help),
destination: slot.target === "offering" ? "/admin/services" : "/admin/brand", destination: slot.target === "offering" ? "/admin/services" : "/admin/brand",
+1 -1
View File
@@ -45,7 +45,7 @@ export async function buildBrandReleaseSnapshot(
database.trustContent.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }), database.trustContent.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
database.capabilityInstallation.findMany({ where: { brandId } }), database.capabilityInstallation.findMany({ where: { brandId } }),
]); ]);
const templateKey = installation?.templateKey ?? brand?.templateKey ?? defaultBrandTemplateKey; const templateKey = brand?.templateKey ?? installation?.templateKey ?? defaultBrandTemplateKey;
const config = const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config) brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>) ? (brand.config as Record<string, unknown>)
+6
View File
@@ -31,6 +31,12 @@ export async function createApp(): Promise<NestFastifyApplication> {
} }
if (process.env.NODE_ENV !== "test") { if (process.env.NODE_ENV !== "test") {
process.on("unhandledRejection", (reason) => {
console.error("[api] unhandled rejection", reason);
});
process.on("uncaughtException", (error) => {
console.error("[api] uncaught exception", error);
});
const app = await createApp(); const app = await createApp();
await app.listen({ port: Number(process.env.API_PORT ?? 3001), host: "0.0.0.0" }); await app.listen({ port: Number(process.env.API_PORT ?? 3001), host: "0.0.0.0" });
} }
@@ -0,0 +1,223 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import {
defaultVisualTemplateKey,
getBrandTemplate,
getDefaultVisualTemplateKey,
getVisualTemplate,
isVisualTemplateCompatible,
listVisualTemplateKeys,
} from "@personal-brand/config";
import { PrismaService } from "../../prisma.service.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import type { UpdateBrandDto, UpdateBrandPresentationDto } from "../../admin.dto.js";
@Injectable()
export class AdminBrandConfigService {
constructor(
private readonly prisma: PrismaService,
private readonly templateWorkspace: TemplateWorkspaceService,
) {}
getBrand(brandId: string) {
return this.prisma.brandProfile.findUnique({ where: { id: brandId } });
}
async updateBrand(brandId: string, body: UpdateBrandDto) {
const { config, ...fields } = body;
const current = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { config: true },
});
const currentConfig = this.jsonObject(current?.config);
const nextConfig = {
...currentConfig,
...(config ?? {}),
...(fields.description !== undefined && config?.slogan === undefined
? { slogan: fields.description }
: {}),
};
if (config?.visualTemplateKey && config.visualTemplateKey !== currentConfig.visualTemplateKey) {
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
const visualTemplate =
typeof config.visualTemplateKey === "string"
? getVisualTemplate(config.visualTemplateKey)
: undefined;
if (
!visualTemplate ||
!getBrandTemplate(templateKey) ||
!isVisualTemplateCompatible(visualTemplate, templateKey)
)
throw new BadRequestException("当前视觉模板不适配该行业模板");
const installation = await this.prisma.brandTemplateInstallation.findFirst({
where: { brandId },
});
if (installation) {
const history = Array.isArray(installation.previousSnapshots)
? installation.previousSnapshots
: [];
await this.prisma.brandTemplateInstallation.update({
where: { id: installation.id },
data: {
previousSnapshots: [
...history,
{
visualTemplateKey:
currentConfig.visualTemplateKey ?? getDefaultVisualTemplateKey(templateKey),
savedAt: new Date().toISOString(),
},
],
},
});
}
}
return this.prisma.brandProfile.update({
where: { id: brandId },
data: {
...fields,
...(Object.keys(nextConfig).length ? { config: nextConfig } : {}),
},
});
}
async updatePresentation(brandId: string, body: UpdateBrandPresentationDto) {
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { config: true },
});
const config = this.jsonObject(brand?.config);
const previous = this.jsonObject(config.visualPresentation);
const nextPresentation = { ...previous };
const identity = body.identity;
const identityFields = ["founder", "title", "slogan", "phone", "wechat", "studioAddress"];
const nextIdentity = identity
? Object.fromEntries(
identityFields
.filter((key) => typeof identity[key] === "string")
.map((key) => [key, identity[key]]),
)
: {};
for (const section of [
"home",
"offerings",
"detail",
"profile",
"inquiry",
"success",
"records",
] as const) {
const input = body[section];
if (!input) continue;
const current = this.jsonObject(previous[section]);
const values = Object.fromEntries(
Object.entries(input).filter(([, value]) => typeof value === "string"),
);
nextPresentation[section] = { ...current, ...values };
}
const updated = await this.prisma.brandProfile.update({
where: { id: brandId },
data: {
config: {
...config,
...nextIdentity,
visualPresentation: nextPresentation,
} as Prisma.InputJsonValue,
},
select: { config: true },
});
return {
visualPresentation: this.jsonObject(updated.config).visualPresentation,
};
}
async visualTemplateHistory(brandId: string) {
const installation = await this.prisma.brandTemplateInstallation.findFirst({
where: { brandId },
select: { previousSnapshots: true },
});
return {
history: Array.isArray(installation?.previousSnapshots)
? installation.previousSnapshots.filter(
(item) =>
item &&
typeof item === "object" &&
!Array.isArray(item) &&
"visualTemplateKey" in item,
)
: [],
};
}
async rollbackVisualTemplate(brandId: string) {
const [brand, installation] = await Promise.all([
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
]);
const config = this.jsonObject(brand?.config);
const history = Array.isArray(installation?.previousSnapshots)
? installation.previousSnapshots
: [];
const index = [...history]
.map((item, i) => ({ item, i }))
.reverse()
.find(
({ item }) =>
item && typeof item === "object" && !Array.isArray(item) && "visualTemplateKey" in item,
)?.i;
const previous =
index === undefined ? undefined : (history[index] as { visualTemplateKey?: unknown });
if (!previous || typeof previous.visualTemplateKey !== "string")
throw new BadRequestException("没有可回滚的视觉模板版本");
await this.prisma.$transaction([
this.prisma.brandProfile.update({
where: { id: brandId },
data: {
config: {
...config,
visualTemplateKey: previous.visualTemplateKey,
},
},
}),
...(installation
? [
this.prisma.brandTemplateInstallation.update({
where: { id: installation.id },
data: { previousSnapshots: history.slice(0, index) },
}),
]
: []),
]);
return { visualTemplateKey: previous.visualTemplateKey, rolledBack: true };
}
async visualTemplatePreview(brandId: string) {
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { config: true },
});
const config = this.jsonObject(brand?.config);
const currentKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: defaultVisualTemplateKey;
const current = getVisualTemplate(currentKey);
return {
current: current
? {
key: current.key,
version: current.version,
name: current.name,
theme: current.theme,
variants: current.variants,
}
: null,
available: listVisualTemplateKeys(),
};
}
private jsonObject(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
}
@@ -11,9 +11,7 @@ import {
Req, Req,
UnauthorizedException, UnauthorizedException,
} from "@nestjs/common"; } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import type { FastifyRequest } from "fastify"; import type { FastifyRequest } from "fastify";
import { PrismaService } from "../../prisma.service.js";
import { readIdentity } from "../../auth.js"; import { readIdentity } from "../../auth.js";
import { import {
CreateTrustContentDto, CreateTrustContentDto,
@@ -21,23 +19,16 @@ import {
UpdateBrandPresentationDto, UpdateBrandPresentationDto,
UpdateTrustContentDto, UpdateTrustContentDto,
} from "../../admin.dto.js"; } from "../../admin.dto.js";
import {
defaultVisualTemplateKey,
getBrandTemplate,
getVisualTemplate,
isVisualTemplateCompatible,
listVisualTemplateKeys,
getDefaultVisualTemplateKey,
} from "@personal-brand/config";
import { AdminAccessService } from "../../admin-access.service.js"; import { AdminAccessService } from "../../admin-access.service.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js"; import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
@Controller("admin/config") @Controller("admin/config")
export class AdminConfigController { export class AdminConfigController {
constructor( constructor(
private readonly prisma: PrismaService,
private readonly access: AdminAccessService, private readonly access: AdminAccessService,
private readonly templateWorkspace: TemplateWorkspaceService, private readonly templateWorkspace: TemplateWorkspaceService,
private readonly brandConfig: AdminBrandConfigService,
) {} ) {}
private brandId(request?: FastifyRequest): string { private brandId(request?: FastifyRequest): string {
if (!request) return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001"; if (!request) return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
@@ -61,7 +52,7 @@ export class AdminConfigController {
@Get("brand") @Get("brand")
getBrand(@Req() request: FastifyRequest): Promise<unknown> { getBrand(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request); this.requireAdmin(request);
return this.prisma.brandProfile.findUnique({ where: { id: this.brandId(request) } }); return this.brandConfig.getBrand(this.brandId(request));
} }
@Patch("brand") @Patch("brand")
async updateBrand( async updateBrand(
@@ -69,70 +60,11 @@ export class AdminConfigController {
@Body() body: UpdateBrandDto, @Body() body: UpdateBrandDto,
): Promise<unknown> { ): Promise<unknown> {
this.requireAdmin(request); this.requireAdmin(request);
const { config, ...fields } = body; const { config } = body;
if (config?.visualTemplateKey !== undefined) { if (config?.visualTemplateKey !== undefined) {
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]); await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
} }
const current = await this.prisma.brandProfile.findUnique({ return this.brandConfig.updateBrand(this.brandId(request), body);
where: { id: this.brandId(request) },
select: { config: true },
});
const currentConfig =
current?.config && typeof current.config === "object" && !Array.isArray(current.config)
? (current.config as Record<string, unknown>)
: {};
const nextConfig = {
...currentConfig,
...(config ?? {}),
// 兼容旧模板:品牌简介的唯一编辑入口是 BrandProfile.description,
// 旧视觉模板仍从 config.slogan 读取,保存时保持两者同步。
...(fields.description !== undefined && config?.slogan === undefined
? { slogan: fields.description }
: {}),
};
if (config?.visualTemplateKey && config.visualTemplateKey !== currentConfig.visualTemplateKey) {
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(
this.brandId(request),
);
const visualTemplate =
typeof config.visualTemplateKey === "string"
? getVisualTemplate(config.visualTemplateKey)
: undefined;
if (
!visualTemplate ||
!getBrandTemplate(templateKey) ||
!isVisualTemplateCompatible(visualTemplate, templateKey)
)
throw new BadRequestException("当前视觉模板不适配该行业模板");
const installation = await this.prisma.brandTemplateInstallation.findFirst({
where: { brandId: this.brandId(request) },
});
if (installation) {
const history = Array.isArray(installation.previousSnapshots)
? installation.previousSnapshots
: [];
await this.prisma.brandTemplateInstallation.update({
where: { id: installation.id },
data: {
previousSnapshots: [
...history,
{
visualTemplateKey:
currentConfig.visualTemplateKey ?? getDefaultVisualTemplateKey(templateKey),
savedAt: new Date().toISOString(),
},
],
},
});
}
}
return this.prisma.brandProfile.update({
where: { id: this.brandId(request) },
data: {
...fields,
...(Object.keys(nextConfig).length ? { config: nextConfig } : {}),
},
});
} }
@Patch("presentation") @Patch("presentation")
async updatePresentation( async updatePresentation(
@@ -141,167 +73,27 @@ export class AdminConfigController {
): Promise<unknown> { ): Promise<unknown> {
this.requireAdmin(request); this.requireAdmin(request);
const brandId = this.brandId(request); const brandId = this.brandId(request);
const brand = await this.prisma.brandProfile.findUnique({ return this.brandConfig.updatePresentation(brandId, body);
where: { id: brandId },
select: { config: true },
});
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const previous =
config.visualPresentation &&
typeof config.visualPresentation === "object" &&
!Array.isArray(config.visualPresentation)
? (config.visualPresentation as Record<string, unknown>)
: {};
const nextPresentation = { ...previous };
const identity = body.identity;
const identityFields = ["founder", "title", "slogan", "phone", "wechat", "studioAddress"];
const nextIdentity = identity
? Object.fromEntries(
identityFields
.filter((key) => typeof identity[key] === "string")
.map((key) => [key, identity[key]]),
)
: {};
for (const section of [
"home",
"offerings",
"detail",
"profile",
"inquiry",
"success",
"records",
] as const) {
const input = body[section];
if (!input) continue;
const current =
previous[section] &&
typeof previous[section] === "object" &&
!Array.isArray(previous[section])
? (previous[section] as Record<string, unknown>)
: {};
const values = Object.fromEntries(
Object.entries(input).filter(([, value]) => typeof value === "string"),
);
nextPresentation[section] = { ...current, ...values };
}
const updated = await this.prisma.brandProfile.update({
where: { id: brandId },
data: {
config: {
...config,
...nextIdentity,
visualPresentation: nextPresentation,
} as Prisma.InputJsonValue,
},
select: { config: true },
});
return {
visualPresentation: (updated.config as Record<string, unknown>).visualPresentation,
};
} }
@Get("visual-template/history") @Get("visual-template/history")
getVisualTemplateHistory(@Req() request: FastifyRequest): unknown { getVisualTemplateHistory(@Req() request: FastifyRequest): unknown {
this.requireAdmin(request); this.requireAdmin(request);
return this.prisma.brandTemplateInstallation return this.brandConfig.visualTemplateHistory(this.brandId(request));
.findFirst({ where: { brandId: this.brandId(request) }, select: { previousSnapshots: true } })
.then((installation) => ({
history: Array.isArray(installation?.previousSnapshots)
? installation.previousSnapshots.filter(
(item) =>
item &&
typeof item === "object" &&
!Array.isArray(item) &&
"visualTemplateKey" in item,
)
: [],
}));
} }
@Post("visual-template/rollback") @Post("visual-template/rollback")
async rollbackVisualTemplate(@Req() request: FastifyRequest): Promise<unknown> { async rollbackVisualTemplate(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request); this.requireAdmin(request);
const brandId = this.brandId(request); return this.brandConfig.rollbackVisualTemplate(this.brandId(request));
const [brand, installation] = await Promise.all([
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
]);
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const history = Array.isArray(installation?.previousSnapshots)
? installation.previousSnapshots
: [];
const index = [...history]
.map((item, i) => ({ item, i }))
.reverse()
.find(
({ item }) =>
item && typeof item === "object" && !Array.isArray(item) && "visualTemplateKey" in item,
)?.i;
const previous =
index === undefined ? undefined : (history[index] as { visualTemplateKey?: unknown });
if (!previous || typeof previous.visualTemplateKey !== "string")
throw new BadRequestException("没有可回滚的视觉模板版本");
await this.prisma.$transaction([
this.prisma.brandProfile.update({
where: { id: brandId },
data: {
config: {
...config,
visualTemplateKey: previous.visualTemplateKey,
},
},
}),
...(installation
? [
this.prisma.brandTemplateInstallation.update({
where: { id: installation.id },
data: { previousSnapshots: history.slice(0, index) },
}),
]
: []),
]);
return { visualTemplateKey: previous.visualTemplateKey, rolledBack: true };
} }
@Get("visual-template/preview") @Get("visual-template/preview")
getVisualTemplatePreview(@Req() request: FastifyRequest): unknown { getVisualTemplatePreview(@Req() request: FastifyRequest): unknown {
this.requireAdmin(request); this.requireAdmin(request);
return this.prisma.brandProfile return this.brandConfig.visualTemplatePreview(this.brandId(request));
.findUnique({ where: { id: this.brandId(request) }, select: { config: true } })
.then((brand) => {
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const currentKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: defaultVisualTemplateKey;
const current = getVisualTemplate(currentKey);
return {
current: current
? {
key: current.key,
version: current.version,
name: current.name,
theme: current.theme,
variants: current.variants,
}
: null,
available: listVisualTemplateKeys(),
};
});
} }
@Get("trust-content") @Get("trust-content")
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> { listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request); this.requireAdmin(request);
return this.prisma.trustContent.findMany({ return this.templateWorkspace.listTrustContent(this.brandId(request));
where: { brandId: this.brandId(request) },
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
});
} }
@Post("trust-content") @Post("trust-content")
createTrustContent( createTrustContent(
@@ -327,11 +119,6 @@ export class AdminConfigController {
@Param("id") id: string, @Param("id") id: string,
): Promise<unknown> { ): Promise<unknown> {
this.requireAdmin(request); this.requireAdmin(request);
const item = await this.prisma.trustContent.findFirst({ return this.templateWorkspace.deleteTrustContent(this.brandId(request), id);
where: { id, brandId: this.brandId(request) },
});
if (!item) throw new BadRequestException("信任内容不存在");
await this.prisma.trustContent.delete({ where: { id } });
return { deleted: true };
} }
} }
@@ -1,23 +1,14 @@
import { BadRequestException, Controller, Put, Query, Req } from "@nestjs/common"; import { Controller, Put, Query, Req } from "@nestjs/common";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import type { FastifyRequest } from "fastify"; import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "../../admin-access.service.js"; import { AdminAccessService } from "../../admin-access.service.js";
import { AdminUploadService } from "./admin-upload.service.js";
const allowedExtensions = new Map([
["image/jpeg", ".jpg"],
["image/png", ".png"],
["image/webp", ".webp"],
["image/avif", ".avif"],
]);
@Controller("admin/uploads") @Controller("admin/uploads")
export class AdminLocalUploadController { export class AdminLocalUploadController {
constructor(private readonly access: AdminAccessService) {} constructor(
private readonly access: AdminAccessService,
private get mediaRoot(): string { private readonly uploads: AdminUploadService,
return path.resolve(process.env.LOCAL_MEDIA_ROOT || path.join(process.cwd(), "media")); ) {}
}
@Put("local") @Put("local")
async upload( async upload(
@@ -26,30 +17,11 @@ export class AdminLocalUploadController {
): Promise<{ saved: true }> { ): Promise<{ saved: true }> {
await this.access.requireBrand(request); await this.access.requireBrand(request);
const rawKey = key ?? (request.query as { key?: string }).key; const rawKey = key ?? (request.query as { key?: string }).key;
const decodedKey = (rawKey ?? "").includes("%") await this.uploads.saveLocal(
? decodeURIComponent(rawKey as string) rawKey ?? "",
: (rawKey ?? ""); request.headers["content-type"] ?? "",
if ( request.body as Buffer,
!decodedKey || );
decodedKey.includes("..") ||
decodedKey.startsWith("/") ||
!/^\d{4}\//.test(decodedKey)
) {
throw new BadRequestException("上传 key 无效");
}
if (!allowedExtensions.has(request.headers["content-type"] ?? "")) {
throw new BadRequestException("仅支持图片上传");
}
const contentType = allowedExtensions.get(request.headers["content-type"] ?? "");
if (!contentType || !decodedKey.endsWith(contentType)) {
throw new BadRequestException("上传文件类型与 key 不一致");
}
const target = path.join(this.mediaRoot, decodedKey);
if (!target.startsWith(path.resolve(this.mediaRoot))) {
throw new BadRequestException("上传 key 无效");
}
await mkdir(path.dirname(target), { recursive: true });
await writeFile(target, request.body as Buffer);
return { saved: true }; return { saved: true };
} }
} }
@@ -0,0 +1,47 @@
import { Injectable } from "@nestjs/common";
import { spawn } from "node:child_process";
import { REPOSITORY_ROOT } from "./miniapp-artifact.js";
interface BuildProcess {
stdout: NodeJS.ReadableStream;
stderr: NodeJS.ReadableStream;
on: (event: "close" | "error", listener: (code: number | null) => void) => void;
}
@Injectable()
export class AdminMiniAppBuildService {
run(
templateKey: string,
buildConfig: { apiBaseUrl: string; appId: string },
onLog: (message: string, stream: "stdout" | "stderr") => void,
): Promise<{ exitCode: number }> {
return new Promise((resolvePromise, rejectPromise) => {
const child = spawn("pnpm", ["--filter", "@personal-brand/taro", "build:weapp"], {
cwd: REPOSITORY_ROOT,
env: {
...process.env,
TEMPLATE_KEY: templateKey,
TARO_ENV: "weapp",
API_BASE_URL: buildConfig.apiBaseUrl,
WEAPP_APP_ID: buildConfig.appId,
},
shell: process.platform === "win32",
}) as BuildProcess;
const readStream = (stream: NodeJS.ReadableStream, name: "stdout" | "stderr") => {
let buffer = "";
stream.on("data", (chunk: Buffer | string) => {
buffer += chunk.toString();
for (const message of buffer.split("\n").slice(0, -1)) onLog(message, name);
buffer = buffer.slice(buffer.lastIndexOf("\n") + 1);
});
stream.on("end", () => {
if (buffer) onLog(buffer, name);
});
};
readStream(child.stdout, "stdout");
readStream(child.stderr, "stderr");
child.on("close", (code) => resolvePromise({ exitCode: code ?? 1 }));
child.on("error", () => rejectPromise(new Error("小程序构建进程启动失败")));
});
}
}
@@ -0,0 +1,85 @@
import { Body, Controller, Get, Param, Patch, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "../../admin-access.service.js";
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
import { AdminMiniAppSettingsService } from "./admin-miniapp-settings.service.js";
import { AdminMiniAppUploadService } from "./admin-miniapp-upload.service.js";
import { UpdateMiniAppSettingsDto } from "./admin-miniapp-settings.dto.js";
import {
CreateMiniAppReleaseDto,
UpdateMiniAppReleaseStatusDto,
UploadMiniAppReleaseDto,
} from "./admin-miniapp-release.dto.js";
type AdminIdentity = { subject: string; brandId: string };
@Controller("admin/miniapp-releases")
export class AdminMiniAppReleaseController {
constructor(
private readonly access: AdminAccessService,
private readonly releases: AdminMiniAppReleaseService,
private readonly settingsService: AdminMiniAppSettingsService,
private readonly uploads: AdminMiniAppUploadService,
) {}
@Get("latest")
async latest(@Req() request: FastifyRequest): Promise<unknown> {
const identity = await this.identity(request);
return (await this.releases.latest(identity.brandId)) ?? null;
}
@Get("settings")
async settings(@Req() request: FastifyRequest): Promise<unknown> {
const identity = await this.identity(request);
return this.settingsService.get(identity.brandId);
}
@Patch("settings")
async updateSettings(
@Req() request: FastifyRequest,
@Body() body: UpdateMiniAppSettingsDto & { privateKey?: string },
): Promise<unknown> {
const identity = await this.identity(request);
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
return this.settingsService.update(identity.brandId, body);
}
@Get()
list(@Req() request: FastifyRequest): Promise<unknown[]> {
return this.identity(request).then(({ brandId }) => this.releases.list(brandId));
}
@Post()
create(@Req() request: FastifyRequest, @Body() body: CreateMiniAppReleaseDto): Promise<unknown> {
return this.identity(request).then(({ brandId, subject }) =>
this.releases.create(brandId, subject, body),
);
}
@Post(":id/upload")
upload(
@Req() request: FastifyRequest,
@Param("id") taskId: string,
@Body() body: UploadMiniAppReleaseDto,
): Promise<unknown> {
return this.identity(request).then(({ brandId, subject }) =>
this.uploads.run(brandId, subject, taskId, body),
);
}
@Patch(":id/status")
updateStatus(
@Req() request: FastifyRequest,
@Param("id") taskId: string,
@Body() body: UpdateMiniAppReleaseStatusDto,
): Promise<unknown> {
return this.identity(request).then(({ brandId, subject }) =>
this.releases.updateStatus(brandId, subject, taskId, body),
);
}
private async identity(request: FastifyRequest): Promise<AdminIdentity> {
const { subject, brandId } = await this.access.requireBrand(request);
return { subject, brandId };
}
}
@@ -0,0 +1,40 @@
import { Type } from "class-transformer";
import { IsIn, IsOptional, IsString, IsUUID, MaxLength } from "class-validator";
export class CreateMiniAppReleaseDto {
@IsOptional()
@IsUUID()
releaseId?: string;
}
export class UpdateMiniAppReleaseStatusDto {
@IsIn(["uploaded", "under_review", "approved", "rejected", "failed", "built", "published"])
status!: "uploaded" | "under_review" | "approved" | "rejected" | "failed" | "built" | "published";
@IsOptional()
@IsString()
@MaxLength(2000)
error?: string;
@IsOptional()
@IsString()
@MaxLength(200)
weappUploadId?: string;
}
export class UploadMiniAppReleaseDto {
@IsOptional()
@IsString()
@MaxLength(100)
version?: string;
@IsOptional()
@IsString()
@MaxLength(500)
desc?: string;
@IsOptional()
@Type(() => Number)
@IsIn([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
robot?: number;
}
Loaded 100 of 227 files, more files were not shown because too many files have changed in this diff. Show more