diff --git a/.codex-tasks/acheng-navigation-parity/PROGRESS.md b/.codex-tasks/acheng-navigation-parity/PROGRESS.md new file mode 100644 index 0000000..8ea32d1 --- /dev/null +++ b/.codex-tasks/acheng-navigation-parity/PROGRESS.md @@ -0,0 +1,16 @@ +# 进度 + +- 任务:阿成校园餐导航与咨询还原 +- 形态:single-full +- 进度:3/3 +- 当前:已完成阿成五入口导航、出摊服务页和餐饮咨询入口。 +- 真相文件:`TODO.csv` + +## 完成记录 + +- 固定微信 `tabBar` 已移除,改为 Runtime Workspace 驱动的 `runtime-tab-bar`。 +- 阿成模板入口:首页/摊位、套餐餐品、出摊服务、主理人、定制/咨询。 +- 林境模板入口:首页、案例与体系、主理人与我。 +- `定制/咨询` 使用既有动态咨询表单和提交 API;未复制原型 mock 数据。 +- 新增 `pages/stall-service/index`,展示出摊地址、取餐配送和定制流程。 +- `typecheck`、Mini Program fixture、visual fixture 已通过。 diff --git a/.codex-tasks/acheng-navigation-parity/SPEC.md b/.codex-tasks/acheng-navigation-parity/SPEC.md new file mode 100644 index 0000000..ed10f77 --- /dev/null +++ b/.codex-tasks/acheng-navigation-parity/SPEC.md @@ -0,0 +1,17 @@ +# 阿成校园餐导航与咨询还原 + +## 目标 + +将阿成校园餐从林境的三 Tab 外壳中拆出,恢复原型的五个入口,并让定制咨询使用餐饮视觉而不是通用下单页。 + +## 边界 + +- 使用 Runtime Workspace 的视觉模板、品牌和咨询表单数据。 +- 微信原生 Tab 配置静态,使用 custom tab bar 完成模板运行时导航差异。 +- 不引入原型 mock 菜品、预约记录或文案作为生产数据。 + +## 验收 + +- 阿成模板显示首页/摊位、套餐餐品、出摊服务、主理人、定制/咨询五个入口。 +- 林境模板保留三个对应入口,不显示餐饮专用入口。 +- 阿成定制咨询页使用独立 renderer 并提交既有动态咨询 API。 diff --git a/.codex-tasks/acheng-navigation-parity/TODO.csv b/.codex-tasks/acheng-navigation-parity/TODO.csv new file mode 100644 index 0000000..6097af4 --- /dev/null +++ b/.codex-tasks/acheng-navigation-parity/TODO.csv @@ -0,0 +1,4 @@ +id,task,status,acceptance_criteria,validation_command,completed_at,retry_count,notes +1,建立模板驱动的自定义导航,DONE,阿成五入口和林境三入口根据 Runtime Workspace 切换,pnpm --filter @personal-brand/miniapp test:fixture,已移除固定 tabBar,新增 runtime-tab-bar,0, +2,实现出摊服务与餐饮咨询 renderer,DONE,出摊服务和定制咨询不再回退到通用林境页面,pnpm --filter @personal-brand/miniapp test:visual-fixture,新增出摊服务页,定制/咨询接入动态表单,0, +3,补充回归样例并完成验证,DONE,导航和咨询 renderer 具备自动回归检查,pnpm typecheck,JSON、typecheck、fixture、visual fixture 全部通过,0, diff --git a/.codex-tasks/admin-account-lifecycle-epic/EPIC.md b/.codex-tasks/admin-account-lifecycle-epic/EPIC.md new file mode 100644 index 0000000..941df04 --- /dev/null +++ b/.codex-tasks/admin-account-lifecycle-epic/EPIC.md @@ -0,0 +1,13 @@ +# 管理员账号使用闭环 + +## 目标 + +让手动添加的品牌成员可以安全完成首次登录和密码更新,并让 `editor` 在后台只看到自己有权限使用的功能。 + +## 规则 + +- 手动创建成员时标记 `mustChangePassword`。 +- 登录响应返回当前成员角色和是否需要改密。 +- 首次改密必须校验初始密码,成功后清除标记。 +- `editor` 隐藏系统管理菜单,直接访问系统管理路由回到概览页。 +- 密码只保存 hash,不返回或记录明文。 diff --git a/.codex-tasks/admin-account-lifecycle-epic/PROGRESS.md b/.codex-tasks/admin-account-lifecycle-epic/PROGRESS.md new file mode 100644 index 0000000..dc3e79a --- /dev/null +++ b/.codex-tasks/admin-account-lifecycle-epic/PROGRESS.md @@ -0,0 +1,23 @@ +# 进度 + +- 任务:管理员账号使用闭环 +- 形态:epic +- 进度:3/3 +- 当前:账号使用闭环已完成,下一步进行多品牌真实初始化验收。 + +## 已完成 + +- `AdminUser.mustChangePassword` 字段和 Prisma migration 已添加。 +- 新增 `POST /admin/session/change-password`。 +- 登录响应包含 `role` 和 `mustChangePassword`。 +- 手动添加成员自动标记首次改密。 +- 后台首次登录改密页面已接入。 +- `editor` 隐藏系统管理菜单,直接访问系统管理路由会回到概览。 + +## 验证 + +- `pnpm typecheck`:通过。 +- `pnpm --filter @personal-brand/admin build`:通过。 +- `pnpm format:check`:通过。 +- `pnpm --filter @personal-brand/api exec prisma migrate deploy`:已成功应用,`mustChangePassword` 字段已确认落库。 +- `pnpm --filter @personal-brand/api test:integration`:34/34 通过。 diff --git a/.codex-tasks/admin-account-lifecycle-epic/SUBTASKS.csv b/.codex-tasks/admin-account-lifecycle-epic/SUBTASKS.csv new file mode 100644 index 0000000..382094f --- /dev/null +++ b/.codex-tasks/admin-account-lifecycle-epic/SUBTASKS.csv @@ -0,0 +1,4 @@ +id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes +1,增加首次改密状态和 API,single-full,,DONE,tasks/password-api,手动成员必须改密且密码 hash 存储,pnpm typecheck,新增 schema 字段、迁移和 change-password API +2,接入后台首次改密与角色菜单,single-full,1,DONE,tasks/password-ui,editor 隐藏系统管理并显示改密页面,pnpm --filter @personal-brand/admin build,登录响应持久化角色和改密状态 +3,补齐回归测试与交付记录,single-full,1;2,DONE,tasks/regression,登录、改密、编辑者路由和迁移均有验证,pnpm --filter @personal-brand/api test:integration,Prisma migration 已落库,API integration 34/34 通过 diff --git a/.codex-tasks/admin-information-architecture-epic/EPIC.md b/.codex-tasks/admin-information-architecture-epic/EPIC.md new file mode 100644 index 0000000..a284f9a --- /dev/null +++ b/.codex-tasks/admin-information-architecture-epic/EPIC.md @@ -0,0 +1,13 @@ +# 后台信息架构分层 + +## 目标 + +让普通品牌使用者优先看到日常经营配置,将模板、能力和字段等系统级设置收纳到独立的系统管理分组。 + +## 当前边界 + +当前登录身份统一为 `admin`,还没有品牌运营者与平台管理员的真实权限模型。因此本轮只调整导航信息架构,不宣称完成 API 权限隔离。 + +## 后续 + +建立明确的 membership role 权限矩阵后,再在路由和 API 层执行真正的访问控制。 diff --git a/.codex-tasks/admin-information-architecture-epic/PROGRESS.md b/.codex-tasks/admin-information-architecture-epic/PROGRESS.md new file mode 100644 index 0000000..14c3806 --- /dev/null +++ b/.codex-tasks/admin-information-architecture-epic/PROGRESS.md @@ -0,0 +1,18 @@ +# 进度 + +- 任务:后台信息架构分层 +- 形态:epic +- 进度:3/3 +- 当前:导航分组已完成;真实角色权限作为后续独立任务。 + +## 已完成 + +- “日常经营”:品牌表达、信任内容、业务提供项、咨询记录。 +- “系统管理”:模板与设置、能力插件。 +- 保留现有路由和 API,不引入假权限。 + +## 验证 + +- `pnpm --filter @personal-brand/admin build`:通过。 +- `pnpm typecheck`:通过。 +- `pnpm format:check`:通过。 diff --git a/.codex-tasks/admin-information-architecture-epic/SUBTASKS.csv b/.codex-tasks/admin-information-architecture-epic/SUBTASKS.csv new file mode 100644 index 0000000..2aee8b2 --- /dev/null +++ b/.codex-tasks/admin-information-architecture-epic/SUBTASKS.csv @@ -0,0 +1,4 @@ +id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes +1,分组后台导航,single-full,,DONE,tasks/navigation,日常经营与系统管理分组清晰,pnpm --filter @personal-brand/admin build,已完成导航分组 +2,验证前端构建与类型,single-full,1,DONE,tasks/validation,构建和类型检查通过,pnpm format:check && pnpm typecheck,已通过 +3,记录权限边界,single-full,1;2,DONE,tasks/delivery,明确导航分组不等于 API 权限隔离,pnpm --filter @personal-brand/admin build,已记录 diff --git a/.codex-tasks/brand-friendly-template-content-epic/EPIC.md b/.codex-tasks/brand-friendly-template-content-epic/EPIC.md new file mode 100644 index 0000000..808ea1b --- /dev/null +++ b/.codex-tasks/brand-friendly-template-content-epic/EPIC.md @@ -0,0 +1,50 @@ +# 品牌友好内容工作台与模板契约增强 + +## 目标 + +- 让品牌管理员以通俗业务语言配置自己的品牌介绍、图片、业务提供项、案例、咨询问题和发布内容。 +- 让视觉模板保持页面结构、交互和视觉表达的自由,不依赖公共视觉组件兜底。 +- 建立稳定的模板数据、资产、字段语义和发布校验契约,支持未来大量独立模板 package。 + +## 非目标 + +- 不实现小程序运行时下载或执行模板代码。 +- 不在本 Epic 新增第三个行业模板。 +- 不让品牌用户直接编辑 JSON、schemaKey、renderer、capability 或模板版本。 + +## 约束 + +- 继续使用 NestJS、Prisma、React Admin、微信小程序和 pnpm workspace。 +- 后端只提供稳定业务事实、状态和能力;模板负责视觉和交互表达。 +- 所有受保护 API 必须覆盖未授权、错误角色和成功路径的自动化测试。 +- 品牌隔离必须由服务端当前会话/品牌上下文决定,不能信任客户端 brandId。 +- 新增或修改发布数据必须进入 immutable release snapshot。 + +## 风险 + +- RuntimeWorkspace 契约变更可能影响 Admin、小程序和已有模板,必须用双模板 fixture 回归。 +- 数据库与快照结构变更需要 migration、seed、发布流程和 API 测试同步更新。 +- “通俗易懂”的配置文案是模板定义的一部分,不能通过通用技术字段勉强复用。 + +## 子任务 + +1. 增强 Template Contract:数据槽位、资产槽位、字段语义、导航和 Admin 编辑声明。 +2. 完整 RuntimeWorkspace Projection:稳定输出导航、展示属性、资产和模板适配状态。 +3. 发布前模板适配校验与快照:阻止缺少关键内容、图片或表单的发布。 +4. 品牌友好 Admin 内容工作台:按模板 Admin manifest 渲染业务化编辑界面。 +5. 双模板端到端回归:阿成与林境的品牌隔离、发布、数据槽位和小程序构建验收。 + +## 依赖 + +- 任务 2 依赖任务 1。 +- 任务 3 依赖任务 1 和 2。 +- 任务 4 依赖任务 1、2 和 3。 +- 任务 5 依赖任务 1 至 4。 + +## 完成条件 + +- [ ] 所有 `SUBTASKS.csv` 行为 `DONE`。 +- [ ] 两个模板均可由品牌管理员通过通俗编辑界面完成配置并发布。 +- [ ] 发布时能以可行动提示阻止模板必需内容缺失。 +- [ ] RuntimeWorkspace 不丢失模板已声明的展示字段。 +- [ ] API、Admin build、模板编译和双模板 fixture 回归通过。 diff --git a/.codex-tasks/brand-friendly-template-content-epic/PROGRESS.md b/.codex-tasks/brand-friendly-template-content-epic/PROGRESS.md new file mode 100644 index 0000000..1b5e501 --- /dev/null +++ b/.codex-tasks/brand-friendly-template-content-epic/PROGRESS.md @@ -0,0 +1,16 @@ +# 进度 + +- 任务:品牌友好内容工作台与模板契约增强 +- 形态:epic +- 进度:0/5 +- 当前:任务已建立,等待从模板与 Admin 内容契约开始实施。 +- 真相文件:`SUBTASKS.csv` + +## Context Recovery Block + +- 当前子任务:#1 模板与 Admin 内容契约 +- 当前状态:TODO +- 已完成:无 +- 关键背景:阿成和林境静态视觉验收通过,但 RuntimeWorkspace、发布校验和 Admin 编辑仍不足以支撑大量差异化模板。 +- 已知问题:后端导航存在固定结构痕迹;offering projection 可能丢失展示属性;公共视觉页面不应再作为模板兜底。 +- 下一步:审计现有模板 manifest、Admin 配置页面和发布服务,定义最小的 Template Admin Contract。 diff --git a/.codex-tasks/brand-friendly-template-content-epic/SUBTASKS.csv b/.codex-tasks/brand-friendly-template-content-epic/SUBTASKS.csv new file mode 100644 index 0000000..f9f265b --- /dev/null +++ b/.codex-tasks/brand-friendly-template-content-epic/SUBTASKS.csv @@ -0,0 +1,6 @@ +id,task,task_type,status,depends_on,task_dir,acceptance_criteria,validation_command,completed_at,retry_count,notes +1,模板与 Admin 内容契约,single-full,TODO,,tasks/template-admin-contract,manifest 声明数据槽位资产槽位字段语义和通俗编辑文案,pnpm --filter @personal-brand/template-contract typecheck,,0,不引入模板专属后端 if else +2,RuntimeWorkspace 完整投影,single-full,TODO,1,tasks/runtime-workspace-projection,导航和 offering presentation/assets 完整且品牌隔离,pnpm --filter @personal-brand/api test:integration,,0,不得丢弃模板声明字段 +3,发布模板适配校验,single-full,TODO,1;2,tasks/publication-compatibility,发布前给出可行动缺失提示并写入快照,pnpm --filter @personal-brand/api test:integration,,0,覆盖缺图缺字段缺表单场景 +4,品牌友好内容工作台,single-full,TODO,1;2;3,tasks/brand-content-workbench,普通品牌管理员可按业务语言配置并发布,pnpm --filter @personal-brand/admin build,,0,不暴露 JSON schema renderer capability +5,双模板回归与验收,single-full,TODO,1;2;3;4,tasks/template-e2e-regression,阿成和林境品牌数据与模板产物均正确,pnpm test:template-compiler,,0,包含发布快照和品牌隔离回归 diff --git a/.codex-tasks/brand-publication-lifecycle-epic/EPIC.md b/.codex-tasks/brand-publication-lifecycle-epic/EPIC.md new file mode 100644 index 0000000..da422d7 --- /dev/null +++ b/.codex-tasks/brand-publication-lifecycle-epic/EPIC.md @@ -0,0 +1,29 @@ +# 品牌发布生命周期 Epic + +## 目标 + +建立多品牌、模板驱动的草稿与发布边界,使普通用户可以完成首次配置、预览、发布和回滚,并让小程序只展示已发布内容。 + +## 范围 + +- 品牌发布版本模型、快照生成和可逆迁移; +- 发布、撤回、回滚 API 及授权、校验、审计; +- 公开 workspace 读取发布快照; +- 后台首次配置引导和发布检查; +- API client、集成测试、管理后台构建和小程序未发布状态。 + +## 不在本 Epic + +- 新增行业模板或视觉风格; +- 邀请制团队协作; +- 订单领域状态扩展; +- 生产环境部署和 Nginx 配置。 + +## 验收原则 + +- 每个受保护端点覆盖缺少凭证、无效凭证/错误角色和成功路径; +- 不同品牌不能读取或回滚其他品牌的发布版本; +- 发布失败不改变草稿和当前发布版本; +- 回滚生成新发布版本,不覆盖草稿; +- 公开接口永远不读取未发布草稿; +- 运行 `prisma migrate deploy`、format、typecheck、API integration 和 Admin build。 diff --git a/.codex-tasks/brand-publication-lifecycle-epic/PROGRESS.md b/.codex-tasks/brand-publication-lifecycle-epic/PROGRESS.md new file mode 100644 index 0000000..b04084e --- /dev/null +++ b/.codex-tasks/brand-publication-lifecycle-epic/PROGRESS.md @@ -0,0 +1,34 @@ +# 进度 + +- 任务:品牌发布生命周期 +- 形态:epic +- 进度:5/5 +- 当前:品牌发布生命周期 Epic 已完成;所有子任务和交付验证均已通过。 +- 决策依据:`docs/adr/0012-brand-publication-lifecycle.md` + +## 阶段执行记录 + +已完成 `1 发布模型与快照生成`:新增 `BrandRelease`、可部署 migration 和 `BrandReleaseService.buildSnapshot`。公开接口仍读取现有工作区,待发布 API 完成后再切换。 + +已完成 `2 发布与回滚 API`:新增 `/admin/releases` 列表、`publish`、`revoke` 和版本 `rollback`;发布前校验品牌、模板、业务项、表单和信任内容;回滚生成新版本;覆盖认证、客户越权、成功版本化流程,API integration `37/37` 通过。 + +已完成 `3 公开 workspace 发布边界`:公开品牌、信任内容、业务项、表单及 workspace 只读取当前发布快照;未发布响应不含草稿品牌资料。客户咨询使用已发布表单字段和版本,预约业务项需存在于发布版本且实时启用;小程序不回退旧缓存。验证:API integration `37/37`、miniapp fixture、API typecheck、Admin build、format、diff 检查通过;测试后已恢复 seed。 + +阶段 `4 首次配置与发布引导`:后台提供非技术用户可理解的准备清单、模板选择与示例导入、发布前预览、发布/撤回/回滚操作。发布校验由服务端作为唯一真相。 + +已完成 `4 首次配置与发布引导`:新增 `/admin/publication`,提供行业/视觉选择、示例导入、草稿内容核对、服务端 readiness 检查、发布、撤回和历史版本恢复;编辑成员只可编辑内容,模板管理操作按角色限制。发布检查复用共享 validation 包,发布快照保存模板和视觉声明,客户提交使用发布版本字段和业务快照。验证:API 隔离 schema integration `37/37`、API client `3/3`、API/Admin typecheck、lint、Admin build、format、miniapp fixture 和 visual fixture 均通过。 + +已完成 `5 全量回归与交付`: + +- `pnpm format:check`:通过。 +- `pnpm lint`:通过;保留既有 `booking.service.test.ts` 的 6 个 `no-explicit-any` warning。 +- `pnpm typecheck`:通过。 +- `pnpm --filter @personal-brand/api test`:`6/6` 通过。 +- `pnpm --filter @personal-brand/api test:integration`:隔离 schema 部署 25 个 migration,API 集成 `37/37` 通过;临时 schema 已清理。 +- `pnpm test:api-client`:`3/3` 通过。 +- `pnpm --filter @personal-brand/admin build`:通过。 +- `pnpm --filter @personal-brand/miniapp test:fixture`:通过。 +- `pnpm --filter @personal-brand/miniapp test:visual-fixture`:通过。 +- `git diff --check`:通过。 + +交付结论:公开内容只读取已发布快照;发布、撤回、回滚具备事务、版本和审计约束;后台发布引导和服务端 readiness 已覆盖;客户提交与预约均按发布快照校验;本 Epic 无未验证的 API 路径或用户操作。 diff --git a/.codex-tasks/brand-publication-lifecycle-epic/SUBTASKS.csv b/.codex-tasks/brand-publication-lifecycle-epic/SUBTASKS.csv new file mode 100644 index 0000000..b409490 --- /dev/null +++ b/.codex-tasks/brand-publication-lifecycle-epic/SUBTASKS.csv @@ -0,0 +1,6 @@ +id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes +1,发布模型与快照生成,single-full,,DONE,tasks/release-model,BrandRelease 模型和运行时快照生成器完成且 migration 可部署,pnpm --filter @personal-brand/api exec prisma migrate deploy && pnpm --filter @personal-brand/api typecheck,已完成;公开读取路径尚未切换 +2,发布与回滚 API,single-full,1,DONE,tasks/release-api,发布撤回回滚接口具备校验授权审计和隔离测试,pnpm --filter @personal-brand/api test:integration,已完成;集成测试 37/37 +3,公开 workspace 发布边界,single-full,1;2,DONE,tasks/public-release-boundary,公开接口只读取已发布快照并覆盖未发布空状态,pnpm --filter @personal-brand/api test:integration,API 37/37;miniapp fixture 通过;seed 已恢复 +4,首次配置与发布引导,single-full,2;3,DONE,tasks/onboarding-publish,普通用户可选择模板导入示例完善身份预览并发布,pnpm --filter @personal-brand/admin build,新增配置与发布页;服务端 readiness;发布撤回回滚;模板/示例/草稿核对;Admin build/typecheck 通过 +5,全量回归与交付,single-full,1;2;3;4,DONE,tasks/regression,pnpm format/typecheck/build/integration 和 diff 检查通过,pnpm format:check && pnpm typecheck && pnpm --filter @personal-brand/api test:integration && pnpm --filter @personal-brand/admin build,已完成;全量验证通过,临时测试 schema 已清理 diff --git a/.codex-tasks/brand-publication-lifecycle-epic/tasks/onboarding-publish/PROGRESS.md b/.codex-tasks/brand-publication-lifecycle-epic/tasks/onboarding-publish/PROGRESS.md new file mode 100644 index 0000000..01b426c --- /dev/null +++ b/.codex-tasks/brand-publication-lifecycle-epic/tasks/onboarding-publish/PROGRESS.md @@ -0,0 +1,7 @@ +# 进度 + +- 任务:首次配置与发布引导 +- 形态:single-full +- 进度:4/4 +- 当前:首次配置、内容核对、发布操作和回归验证已完成。 +- 文件:本目录 `TODO.csv` 为真相。 diff --git a/.codex-tasks/brand-publication-lifecycle-epic/tasks/onboarding-publish/SPEC.md b/.codex-tasks/brand-publication-lifecycle-epic/tasks/onboarding-publish/SPEC.md new file mode 100644 index 0000000..ebdc3a4 --- /dev/null +++ b/.codex-tasks/brand-publication-lifecycle-epic/tasks/onboarding-publish/SPEC.md @@ -0,0 +1,3 @@ +# 首次配置与发布引导 + +普通品牌用户无需理解内部模板结构,也能按“选择行业与视觉模板、导入示例、完善身份与业务内容、预览、发布”的顺序完成首次发布。后台明确区分草稿和已发布版本,发布失败保留输入并提示缺项。 diff --git a/.codex-tasks/brand-publication-lifecycle-epic/tasks/onboarding-publish/TODO.csv b/.codex-tasks/brand-publication-lifecycle-epic/tasks/onboarding-publish/TODO.csv new file mode 100644 index 0000000..a2ae19a --- /dev/null +++ b/.codex-tasks/brand-publication-lifecycle-epic/tasks/onboarding-publish/TODO.csv @@ -0,0 +1,5 @@ +id,task,status,acceptance_criteria,validation_command,completed_at,retry_count,notes +1,服务端发布检查接口,DONE,返回与 publish 相同规则的缺项列表,pnpm --filter @personal-brand/api test:integration,2026-09-24,0,复用 validation 包并测试未就绪状态 +2,后台模板与示例引导,DONE,可选择模板并预览或导入示例,pnpm --filter @personal-brand/admin build,2026-09-24,0,新增配置与发布页 +3,后台发布预览与版本操作,DONE,发布撤回回滚及失败状态完整,pnpm --filter @personal-brand/admin build,2026-09-24,0,含权限控制和失败提示 +4,回归验证,DONE,API 与 UI 构建和格式检查通过,pnpm format:check,2026-09-24,0,隔离 schema integration 37/37 diff --git a/.codex-tasks/brand-publication-lifecycle-epic/tasks/public-release-boundary/PROGRESS.md b/.codex-tasks/brand-publication-lifecycle-epic/tasks/public-release-boundary/PROGRESS.md new file mode 100644 index 0000000..161024a --- /dev/null +++ b/.codex-tasks/brand-publication-lifecycle-epic/tasks/public-release-boundary/PROGRESS.md @@ -0,0 +1,7 @@ +# 进度 + +- 任务:公开 workspace 发布边界 +- 形态:single-full +- 进度:3/3 +- 验证:API integration 37/37;miniapp fixture、API typecheck、Admin build、format 和 diff 检查通过。 +- 文件:本目录 `TODO.csv` 为真相。 diff --git a/.codex-tasks/brand-publication-lifecycle-epic/tasks/public-release-boundary/SPEC.md b/.codex-tasks/brand-publication-lifecycle-epic/tasks/public-release-boundary/SPEC.md new file mode 100644 index 0000000..125d0dc --- /dev/null +++ b/.codex-tasks/brand-publication-lifecycle-epic/tasks/public-release-boundary/SPEC.md @@ -0,0 +1,3 @@ +# 公开发布边界 + +公开接口、小程序运行时和客户提交都必须以当前品牌发布快照为边界。未发布时不显示草稿,也不受理新的咨询或预约;实时禁用仍应即时拦截。 diff --git a/.codex-tasks/brand-publication-lifecycle-epic/tasks/public-release-boundary/TODO.csv b/.codex-tasks/brand-publication-lifecycle-epic/tasks/public-release-boundary/TODO.csv new file mode 100644 index 0000000..6a6845f --- /dev/null +++ b/.codex-tasks/brand-publication-lifecycle-epic/tasks/public-release-boundary/TODO.csv @@ -0,0 +1,4 @@ +id,task,status,acceptance_criteria,validation_command,completed_at,retry_count,notes +1,公开查询切换发布快照,DONE,无发布版本不暴露草稿,pnpm --filter @personal-brand/api test:integration,2026-09-24,0,37/37 +2,客户提交与小程序缓存边界,DONE,未发布时不受理且不回退旧缓存,pnpm --filter @personal-brand/miniapp test:fixture,2026-09-24,0,通过 +3,全量验证与恢复种子,DONE,集成测试和构建通过且 seed 恢复,pnpm format:check,2026-09-24,0,API 37/37;Admin build 通过 diff --git a/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-api/PROGRESS.md b/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-api/PROGRESS.md new file mode 100644 index 0000000..ff4c42e --- /dev/null +++ b/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-api/PROGRESS.md @@ -0,0 +1,7 @@ +# 进度 + +- 状态:DONE +- 新增 `BrandReleaseApiService` 和 `AdminReleaseController`。 +- 发布前校验品牌名称、行业模板、视觉模板兼容性、启用业务项、启用咨询表单和已发布信任内容。 +- 新增 API Client 的 release 方法和 认证/成功/回滚/撤回集成测试。 +- `prisma migrate deploy`、API build、API typecheck、format 和 API integration `37/37` 已通过。 diff --git a/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-api/SPEC.md b/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-api/SPEC.md new file mode 100644 index 0000000..6a530f7 --- /dev/null +++ b/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-api/SPEC.md @@ -0,0 +1,3 @@ +# 发布与回滚 API + +提供品牌发布版本的查询、发布、撤回和回滚接口。所有数据按管理员会话中的 `brandId` 隔离,发布失败不得修改已有版本,回滚通过创建新版本保留历史。 diff --git a/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-api/TODO.csv b/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-api/TODO.csv new file mode 100644 index 0000000..01ce644 --- /dev/null +++ b/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-api/TODO.csv @@ -0,0 +1,4 @@ +id,task,status,completed_at,notes +1,实现发布校验和版本创建,DONE,2026-09-24,事务中标记旧版本 superseded 并创建新版本 +2,实现回滚与撤回,DONE,2026-09-24,回滚创建新版本,撤回标记当前版本 revoked +3,补齐授权、隔离和成功测试,DONE,2026-09-24,API integration 37/37 diff --git a/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-model/PROGRESS.md b/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-model/PROGRESS.md new file mode 100644 index 0000000..1a237c7 --- /dev/null +++ b/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-model/PROGRESS.md @@ -0,0 +1,6 @@ +# 进度 + +- 状态:DONE +- 已新增 `BrandRelease` Prisma 模型及 migration `20260924100000_add_brand_releases`。 +- 已新增 `BrandReleaseService.buildSnapshot`,按品牌收集品牌资料、模板安装、模块、字段、业务项、表单、信任内容和能力安装。 +- 已执行 `prisma migrate deploy`、API typecheck。 diff --git a/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-model/SPEC.md b/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-model/SPEC.md new file mode 100644 index 0000000..e9f5949 --- /dev/null +++ b/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-model/SPEC.md @@ -0,0 +1,3 @@ +# 发布模型与快照生成 + +为每个品牌增加不可变发布版本,保存完整工作区快照,为后续发布、回滚和公开读取提供数据边界。本阶段不切换公开接口。 diff --git a/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-model/TODO.csv b/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-model/TODO.csv new file mode 100644 index 0000000..b5218ec --- /dev/null +++ b/.codex-tasks/brand-publication-lifecycle-epic/tasks/release-model/TODO.csv @@ -0,0 +1,4 @@ +id,task,status,completed_at,notes +1,新增 BrandRelease Prisma 模型,DONE,2026-09-24,保存品牌版本快照和状态 +2,实现品牌工作区快照生成器,DONE,2026-09-24,BrandReleaseService 按 brandId 收集完整配置 +3,执行数据库迁移与 API 类型检查,DONE,2026-09-24,prisma migrate deploy 和 typecheck 通过 diff --git a/.codex-tasks/campus-food-template-epic/EPIC.md b/.codex-tasks/campus-food-template-epic/EPIC.md new file mode 100644 index 0000000..34beb86 --- /dev/null +++ b/.codex-tasks/campus-food-template-epic/EPIC.md @@ -0,0 +1,12 @@ +# 阿成校园餐第二视觉模板 Epic + +## 目标 + +将 `阿成校园餐` React 原型转化为第二个真实可切换的小程序视觉模板,验证模板包不是只保存声明,而是可以替换页面表达,同时继续消费统一 Runtime Workspace 和发布快照。 + +## 约束 + +- 原型中的 mock dishes、records 和静态品牌资料不得进入生产运行时; +- 页面内容来自当前品牌发布 workspace; +- 模板代码可以与林境完全不同,但 API、能力和品牌隔离必须复用平台契约; +- 新模板必须有独立 renderer、包声明、fixture 和切换测试。 diff --git a/.codex-tasks/campus-food-template-epic/PROGRESS.md b/.codex-tasks/campus-food-template-epic/PROGRESS.md new file mode 100644 index 0000000..9fece93 --- /dev/null +++ b/.codex-tasks/campus-food-template-epic/PROGRESS.md @@ -0,0 +1,27 @@ +# 进度 + +- 任务:阿成校园餐第二视觉模板 +- 形态:epic +- 进度:3/3 +- 当前:第二模板制作、renderer 接入、切换链路和全量回归已完成,等待用户在微信开发者工具验收。 +- 真相文件:`SUBTASKS.csv` + +## 固化流程 + +新模板必须经过:原型提取 → `template.json` → 独立 renderer → Runtime Workspace 适配 → fixture → API/构建门禁 → 发布切换验收。原型 mock 数据只用于设计参考,不进入生产。 + +## 本轮完成 + +- 修正 seed:personal 使用 `linjing-editorial`,food 使用 `acheng-campus-food`,doors 使用 `linjing-editorial`。 +- 收紧视觉模板行业兼容性:林境仅支持 personal、doors;阿成仅支持 food。 +- 接入阿成首页、菜单和主理人页 renderer,并保留 Runtime Workspace 数据来源。 +- 增加 `acheng-campus-food-visual.json`,覆盖 7 个页面状态。 +- `validate:templates`、`typecheck`、miniapp fixture、visual fixture、admin build、format check 已通过。 +- API 集成测试已通过:37/37;测试使用隔离 schema,并验证模板兼容性、发布与 brandSlug 隔离。 + +## 验收切换 + +- `brandSlug=default-brand`:food 行业,使用 `acheng-campus-food`,首页、菜单、主理人页分别使用 `acheng-home`、`acheng-offerings`、`acheng-profile`。 +- `brandSlug=linran-brand`:personal 行业,使用 `linjing-editorial`。 +- `brandSlug=linjing-doors`:doors 行业,使用 `linjing-editorial`。 +- 新模板流程已固化在本文件和 `templates/acheng-campus-food/`:原型提取、声明、独立 renderer、Runtime Workspace、fixture、构建与 API 门禁、切换验收。 diff --git a/.codex-tasks/campus-food-template-epic/SUBTASKS.csv b/.codex-tasks/campus-food-template-epic/SUBTASKS.csv new file mode 100644 index 0000000..95e0651 --- /dev/null +++ b/.codex-tasks/campus-food-template-epic/SUBTASKS.csv @@ -0,0 +1,4 @@ +id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes +1,原型提取与模板包声明,single-full,,DONE,tasks/package,阿成校园餐包声明页面入口能力和行业兼容性已落盘,pnpm validate:templates,来源为用户提供的 React 原型 +2,小程序独立 renderer,single-full,1,DONE,tasks/renderer,首页主理人页和餐品列表呈现阿成校园餐独立视觉且消费 Runtime Workspace,pnpm --filter @personal-brand/miniapp test:fixture,已接入首页、菜单、主理人页 renderer,并增加视觉 fixture, +3,切换链路与全量回归,single-full,2,DONE,tasks/regression,后台/API 可选择并发布第二模板,brandSlug 切换后视觉 renderer 正确,pnpm --filter @personal-brand/api test:integration,37/37 API 集成测试通过;模板兼容性和 brandSlug 隔离已验证, diff --git a/.codex-tasks/manual-member-management-epic/EPIC.md b/.codex-tasks/manual-member-management-epic/EPIC.md new file mode 100644 index 0000000..e3c1f5f --- /dev/null +++ b/.codex-tasks/manual-member-management-epic/EPIC.md @@ -0,0 +1,13 @@ +# 手动添加品牌成员 + +## 目标 + +在暂不建设邀请流程的前提下,由品牌负责人直接创建成员账号并绑定当前品牌。 + +## 规则 + +- 只有 `owner / admin / platform-admin` 可以添加成员。 +- 创建时填写登录账号、成员姓名、初始密码和角色。 +- 初始密码使用 `bcrypt` hash 保存,接口不返回密码,也不记录明文。 +- 账号名全局唯一,已存在账号不会被覆盖。 +- 邀请、找回密码和首次登录改密暂不纳入本轮。 diff --git a/.codex-tasks/manual-member-management-epic/PROGRESS.md b/.codex-tasks/manual-member-management-epic/PROGRESS.md new file mode 100644 index 0000000..386e358 --- /dev/null +++ b/.codex-tasks/manual-member-management-epic/PROGRESS.md @@ -0,0 +1,25 @@ +# 进度 + +- 任务:手动添加品牌成员 +- 形态:epic +- 进度:3/3 +- 当前:手动添加账号和品牌成员绑定已完成。 + +## 已完成 + +- 新增 `POST /admin/brands/members`。 +- 新增后台“手动添加成员”表单。 +- 初始密码按 `bcrypt` hash 存储,不返回明文。 +- 重复账号由 API 拒绝,不覆盖已有账号。 +- 成员角色和品牌隔离复用现有权限规则。 + +## 验证 + +- `pnpm --filter @personal-brand/api test:integration`:33/33 通过。 +- `pnpm --filter @personal-brand/admin build`:通过。 +- `pnpm typecheck`:通过。 +- `pnpm format:check`:通过。 + +## 暂不实现 + +邀请链接、邮件 / 微信通知、密码找回和首次登录改密后续再做。 diff --git a/.codex-tasks/manual-member-management-epic/SUBTASKS.csv b/.codex-tasks/manual-member-management-epic/SUBTASKS.csv new file mode 100644 index 0000000..f2cf1b2 --- /dev/null +++ b/.codex-tasks/manual-member-management-epic/SUBTASKS.csv @@ -0,0 +1,4 @@ +id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes +1,实现手动添加成员 API,single-full,,DONE,tasks/member-create-api,owner 可创建当前品牌成员且密码不出现在响应,pnpm --filter @personal-brand/api test:integration,新增 POST /admin/brands/members +2,接入后台手动添加表单,single-full,1,DONE,tasks/member-create-ui,可填写账号、姓名、初始密码和角色,pnpm --filter @personal-brand/admin build,新增“手动添加成员”弹窗 +3,完成安全回归与记录,single-full,1;2,DONE,tasks/regression,授权、重复账号和密码存储行为验证,pnpm --filter @personal-brand/api test:integration,API 33/33 通过 diff --git a/.codex-tasks/multibrand-initialization-validation-epic/EPIC.md b/.codex-tasks/multibrand-initialization-validation-epic/EPIC.md new file mode 100644 index 0000000..c21237b --- /dev/null +++ b/.codex-tasks/multibrand-initialization-validation-epic/EPIC.md @@ -0,0 +1,30 @@ +# 多品牌初始化与真实验收 + +## 目标 + +把个人品牌、餐饮与门窗三个 demo 品牌固化为可重复初始化的运行时基线,验证公开 Workspace 的品牌隔离、行业表达和咨询转化链路。 + +## 非目标 + +- 不新增行业模板或订单能力。 +- 不改变普通用户的配置流程。 +- 不引入历史数据兼容层;当前为开发期 fixture,直接修正旧样例。 + +## 约束 + +- `Offering.kind` 只使用共享 allow-list:`service`、`product`、`package`、`subscription`。 +- 行业分类通过 `config.categoryKey` 与 `config.categoryLabel` 表达。 +- 三个品牌均须具备已启用的品牌级咨询表单。 +- 公开接口必须按 `brandSlug` 隔离验证。 + +## 风险 + +- seed 会更新本地 demo 数据,因此必须在执行后检查三个公开 Workspace。 +- 运行中的 API 需在 seed 后重启,才能清除其进程内 Workspace 缓存。 + +## 完成标准 + +- [ ] `SUBTASKS.csv` 所有任务为 `DONE`。 +- [ ] seed 可重复执行并生成 3 个独立品牌。 +- [ ] API integration 覆盖三品牌公开 Workspace 基线。 +- [ ] migration、seed、format、typecheck、integration、Admin build 通过。 diff --git a/.codex-tasks/multibrand-initialization-validation-epic/PROGRESS.md b/.codex-tasks/multibrand-initialization-validation-epic/PROGRESS.md new file mode 100644 index 0000000..849542d --- /dev/null +++ b/.codex-tasks/multibrand-initialization-validation-epic/PROGRESS.md @@ -0,0 +1,21 @@ +# 进度 + +- 任务:多品牌初始化与真实验收 +- 形态:epic +- 进度:3/3 +- 当前:多品牌初始化与真实验收完成 +- 真相文件:`SUBTASKS.csv` + +## 恢复信息 + +- 已完成:新增 `linran-brand` 个人品牌 fixture,并向管理员授予 owner membership。 +- 已完成:`Offering.kind` 收敛到共享 allow-list,餐饮和门窗行业分类改由 `config.categoryKey`、`config.categoryLabel` 表达;小程序从 `categoryLabel` 渲染行业名称。 +- 已完成:餐饮的预订表达与品牌级咨询表单被 seed 反复校正为启用状态。 +- 已完成:公开 Workspace integration 覆盖 3 个品牌的身份、模板、主理人、表单、业务归属和分类语义,API `35/35` 通过。 +- 已完成:`prisma migrate deploy` 无待执行项;测试结束后已重跑 seed 恢复 demo 数据;`format:check`、`typecheck`、Admin build 均通过。 + +## 最终结果 + +- 风险收口:不再用行业文案污染共享 `Offering.kind`。 +- 验收基线:`linran-brand`(个人品牌)、`default-brand`(餐饮)、`linjing-doors`(门窗)三套独立公开 Workspace。 +- 已知非阻塞项:Admin production build 提示主 chunk 约 669 kB,后续按路由进一步拆包,不影响本次功能与数据正确性。 diff --git a/.codex-tasks/multibrand-initialization-validation-epic/SUBTASKS.csv b/.codex-tasks/multibrand-initialization-validation-epic/SUBTASKS.csv new file mode 100644 index 0000000..e26136b --- /dev/null +++ b/.codex-tasks/multibrand-initialization-validation-epic/SUBTASKS.csv @@ -0,0 +1,4 @@ +id,task,task_type,status,depends_on,task_dir,acceptance_criteria,validation_command,completed_at,retry_count,notes +1,统一运行时样例语义与三品牌 fixture,single-full,DONE,,tasks/seed-baseline,seed 使用共享 kind 并提供个人、餐饮、门窗的可用内容,pnpm --filter @personal-brand/api typecheck,2026-09-24,0,新增 personal fixture;行业分类迁移至 config.categoryKey/categoryLabel +2,公开 Workspace 三品牌验收测试,single-full,DONE,1,tasks/runtime-contract,按 brandSlug 验证身份、模板、表单、业务项和隔离,pnpm --filter @personal-brand/api test:integration,2026-09-24,0,API integration 35/35 通过 +3,执行初始化与全量门禁,single-full,DONE,1;2,tasks/regression,迁移、seed 与质量门禁均通过,pnpm format:check && pnpm typecheck && pnpm --filter @personal-brand/api test:integration,2026-09-24,0,migrate deploy 无待执行项;seed 已在测试后重跑恢复 demo 基线 diff --git a/.codex-tasks/multibrand-initialization-validation-epic/tasks/regression/PROGRESS.md b/.codex-tasks/multibrand-initialization-validation-epic/tasks/regression/PROGRESS.md new file mode 100644 index 0000000..13ce805 --- /dev/null +++ b/.codex-tasks/multibrand-initialization-validation-epic/tasks/regression/PROGRESS.md @@ -0,0 +1,5 @@ +# 子任务记录 + +- 状态:DONE +- 变更:执行 migration、seed 并恢复 integration 后的 demo 基线。 +- 验证:`pnpm format:check`、`pnpm typecheck`、Admin production build 均通过。 diff --git a/.codex-tasks/multibrand-initialization-validation-epic/tasks/runtime-contract/PROGRESS.md b/.codex-tasks/multibrand-initialization-validation-epic/tasks/runtime-contract/PROGRESS.md new file mode 100644 index 0000000..79f8239 --- /dev/null +++ b/.codex-tasks/multibrand-initialization-validation-epic/tasks/runtime-contract/PROGRESS.md @@ -0,0 +1,5 @@ +# 子任务记录 + +- 状态:DONE +- 变更:新增按 `brandSlug` 读取三品牌 Workspace 的公开 API integration 测试。 +- 验证:`pnpm --filter @personal-brand/api test:integration`,`35/35` 通过。 diff --git a/.codex-tasks/multibrand-initialization-validation-epic/tasks/seed-baseline/PROGRESS.md b/.codex-tasks/multibrand-initialization-validation-epic/tasks/seed-baseline/PROGRESS.md new file mode 100644 index 0000000..79f43ad --- /dev/null +++ b/.codex-tasks/multibrand-initialization-validation-epic/tasks/seed-baseline/PROGRESS.md @@ -0,0 +1,5 @@ +# 子任务记录 + +- 状态:DONE +- 变更:三品牌可重复 seed、共享 kind 收敛、餐饮文案和咨询表单修复。 +- 验证:`pnpm --filter @personal-brand/api typecheck` 通过。 diff --git a/.codex-tasks/real-business-acceptance-epic/EPIC.md b/.codex-tasks/real-business-acceptance-epic/EPIC.md new file mode 100644 index 0000000..476c25b --- /dev/null +++ b/.codex-tasks/real-business-acceptance-epic/EPIC.md @@ -0,0 +1,26 @@ +# 三品牌真实业务验收 Epic + +## 目标 + +验证个人品牌、餐饮和门窗三种已发布品牌能够在同一套模板、视觉、发布快照与多品牌隔离体系中稳定运行。验收以用户可配置、已发布内容可展示、草稿不污染线上、禁用即时拦截为边界。 + +## 范围 + +- 三个品牌公开 workspace 的身份、行业模板、视觉模板、业务项、表单和信任内容; +- 草稿修改、发布生效、撤回和回滚的公开边界; +- 已发布业务项和表单的实时禁用拦截; +- 后台切换品牌后的隔离; +- API、Admin 和 Miniapp 回归门禁。 + +## 不在本 Epic + +- 新增行业模板或视觉模板; +- 媒体库和文件上传; +- 邀请、通知和生产部署。 + +## 验收原则 + +- 不以 seed 静态数据存在作为验收通过,而验证公开发布版本和草稿的边界; +- 行业差异只能来自模板声明、内容和 capability,不能写入共享业务分支; +- 所有客户操作按当前品牌已发布快照验证,并保留实时禁用拦截; +- 每项 API 行为必须可由隔离 schema 集成测试复现。 diff --git a/.codex-tasks/real-business-acceptance-epic/PROGRESS.md b/.codex-tasks/real-business-acceptance-epic/PROGRESS.md new file mode 100644 index 0000000..5d21075 --- /dev/null +++ b/.codex-tasks/real-business-acceptance-epic/PROGRESS.md @@ -0,0 +1,19 @@ +# 进度 + +- 任务:三品牌真实业务验收与模板覆盖验证 +- 形态:epic +- 进度:4/4 +- 当前:三品牌真实业务自动化验收已完成,等待按清单进行微信开发者工具和后台的人工视觉验收。 +- 真相文件:`SUBTASKS.csv` + +## 阶段执行记录 + +已完成阶段 `1 三品牌发布基线验收`:个人、餐饮、门窗 3 个 `brandSlug` 均验证了品牌身份、行业模板、视觉模板 manifest、信任内容、业务项和咨询表单,API integration `37/37` 通过。 + +已完成阶段 `2 草稿与发布边界组合验收`:验证草稿修改不污染已发布 workspace,发布后才生效,回滚生成新版本,撤回后公开 workspace 进入未发布状态,并保持品牌隔离。 + +已完成阶段 `3 提交与实时禁用验收`:验证发布快照表单和业务项可以提交;草稿新增、表单禁用、业务项禁用、能力禁用和撤回状态均被提交端拦截。 + +已完成阶段 `4 全量回归与手工验收清单`:`format:check`、全仓 `typecheck`、隔离 schema API integration `37/37`、Admin build、Miniapp fixture、visual fixture 和 `git diff --check` 均通过。 + +人工验收步骤已记录于 [MANUAL-ACCEPTANCE.md](tasks/regression/MANUAL-ACCEPTANCE.md)。自动化已完成,人工验收重点是微信开发者工具中的视觉还原、图片资源和品牌切换操作。 diff --git a/.codex-tasks/real-business-acceptance-epic/SUBTASKS.csv b/.codex-tasks/real-business-acceptance-epic/SUBTASKS.csv new file mode 100644 index 0000000..2a41b65 --- /dev/null +++ b/.codex-tasks/real-business-acceptance-epic/SUBTASKS.csv @@ -0,0 +1,5 @@ +id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes +1,三品牌发布基线验收,single-full,,DONE,tasks/three-brand-baseline,个人、餐饮、门窗各自公开 workspace 具备匹配的身份模板视觉业务表单和信任内容,pnpm --filter @personal-brand/api test:integration,API integration 37/37;三品牌断言通过 +2,草稿与发布边界组合验收,single-full,1,DONE,tasks/draft-publication-boundary,草稿修改不影响线上且发布回滚撤回均保持品牌隔离,pnpm --filter @personal-brand/api test:integration,发布生命周期、草稿隔离、回滚和撤回测试通过 +3,提交与实时禁用验收,single-full,1;2,DONE,tasks/submission-boundary,已发布表单和业务项可提交且草稿或实时禁用状态被正确拦截,pnpm --filter @personal-brand/api test:integration,表单/业务项禁用和发布快照提交测试通过 +4,全量回归与手工验收清单,single-full,1;2;3,DONE,tasks/regression,自动化门禁通过并形成后台和小程序手工验收步骤,pnpm format:check && pnpm typecheck && pnpm --filter @personal-brand/api test:integration && pnpm --filter @personal-brand/admin build,全量门禁通过;已形成 MANUAL-ACCEPTANCE.md diff --git a/.codex-tasks/real-business-acceptance-epic/tasks/regression/MANUAL-ACCEPTANCE.md b/.codex-tasks/real-business-acceptance-epic/tasks/regression/MANUAL-ACCEPTANCE.md new file mode 100644 index 0000000..0ad576a --- /dev/null +++ b/.codex-tasks/real-business-acceptance-epic/tasks/regression/MANUAL-ACCEPTANCE.md @@ -0,0 +1,13 @@ +# 后台与小程序手工验收 + +对每个 `linran-brand`、`default-brand`、`linjing-doors` 依次执行: + +1. 在后台切换到目标品牌,确认 Header 品牌名称、品牌表达、业务提供项和咨询表单均属于当前品牌。 +2. 在“配置与发布”查看 readiness,确认模板、视觉、业务项、表单和信任内容均通过。 +3. 修改一项草稿文案或图片但不发布;在小程序重新进入对应 `brandSlug`,确认线上仍是发布版本。 +4. 发布草稿;重新进入小程序,确认修改后的品牌身份、业务展示、咨询表单和信任内容生效。 +5. 禁用一个已发布业务项或表单;确认其不再展示,且历史入口提交被 API 拦截。 +6. 选择历史版本恢复并确认小程序回到该版本;撤回后确认小程序显示“品牌尚未发布”。 +7. 切换到另一个品牌重复第 1 至 4 步,确认不出现前一品牌的名称、图片、业务项或咨询记录。 + +通过标准:每个品牌独立通过,且发布、撤回、回滚和禁用均只影响当前品牌。 diff --git a/.codex-tasks/role-based-admin-access-epic/EPIC.md b/.codex-tasks/role-based-admin-access-epic/EPIC.md new file mode 100644 index 0000000..dd8d39f --- /dev/null +++ b/.codex-tasks/role-based-admin-access-epic/EPIC.md @@ -0,0 +1,16 @@ +# 后台角色权限分层 + +## 目标 + +把日常品牌经营权限与模板、能力、字段等系统设置权限分开,避免普通品牌编辑误操作系统配置。 + +## 角色矩阵 + +- `owner`、`admin`、`platform-admin`:可以管理品牌内容和系统设置。 +- `editor`:可以管理品牌表达、信任内容、业务提供项、咨询表单和咨询记录;不能安装或升级模板、调整能力、模块、字段或视觉模板。 + +## 完成条件 + +- 全局 membership guard 在系统设置路由执行角色校验。 +- visual template 通过独立接口或品牌配置写入时同样受保护。 +- 自动化测试覆盖编辑者允许日常经营、拒绝系统设置。 diff --git a/.codex-tasks/role-based-admin-access-epic/PROGRESS.md b/.codex-tasks/role-based-admin-access-epic/PROGRESS.md new file mode 100644 index 0000000..36060b3 --- /dev/null +++ b/.codex-tasks/role-based-admin-access-epic/PROGRESS.md @@ -0,0 +1,22 @@ +# 进度 + +- 任务:后台角色权限分层 +- 形态:epic +- 进度:3/3 +- 当前:`owner / admin / platform-admin` 与 `editor` 的最小权限边界已生效。 + +## 已完成 + +- 系统设置路径:模板安装、能力、视觉模板、模块和字段,仅允许 owner 级角色。 +- 日常经营路径继续允许已启用品牌成员访问。 +- `editor` 通过业务提供项读取测试,但访问能力设置和视觉模板被拒绝。 + +## 验证 + +- `pnpm --filter @personal-brand/api test:integration`:32/32 通过。 +- `pnpm typecheck`:通过。 +- `pnpm format:check`:通过。 + +## 注意 + +当前登录接口仍返回通用 `admin` token,真实用户管理、成员邀请和角色变更需要后续独立任务建设;本轮不把前端导航分组误称为完整权限系统。 diff --git a/.codex-tasks/role-based-admin-access-epic/SUBTASKS.csv b/.codex-tasks/role-based-admin-access-epic/SUBTASKS.csv new file mode 100644 index 0000000..ab01491 --- /dev/null +++ b/.codex-tasks/role-based-admin-access-epic/SUBTASKS.csv @@ -0,0 +1,4 @@ +id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes +1,在 membership guard 增加系统设置角色校验,single-full,,DONE,tasks/guard,系统设置路径只允许 owner 级角色,pnpm --filter @personal-brand/api test:integration,已覆盖 workspace 系统路由和 visual-template 路由 +2,保护视觉模板配置写入,single-full,1,DONE,tasks/visual-template,editor 不能通过品牌配置修改 visualTemplateKey,pnpm --filter @personal-brand/api test:integration,已在 AdminConfigController 增加角色校验 +3,完成授权回归与记录,single-full,1;2,DONE,tasks/regression,编辑者允许内容管理且拒绝系统设置,pnpm typecheck && pnpm format:check,API 32/32 通过,typecheck 和 format 通过 diff --git a/.codex-tasks/runtime-workspace-contract-consolidation/PROGRESS.md b/.codex-tasks/runtime-workspace-contract-consolidation/PROGRESS.md new file mode 100644 index 0000000..8401e55 --- /dev/null +++ b/.codex-tasks/runtime-workspace-contract-consolidation/PROGRESS.md @@ -0,0 +1,14 @@ +# 进度 + +- 任务:Runtime Workspace 契约收敛 +- 形态:single-full +- 进度:3/3 +- 当前:Runtime Workspace 契约收敛完成 +- 真相文件:`TODO.csv` + +## 恢复信息 + +- 已完成:`RuntimeOffering` 明确声明共享类别、封面、价格和 `presentation`(行业标签、关键词、详情、媒体)。 +- 已完成:公开 Workspace 仅下发 Runtime Offering;不再以原始 Prisma `offerings` 或 `modules` 覆盖同名 Runtime 字段。 +- 已完成:小程序从 `presentation` 读取行业标签与详情首图;模块类型在 API 层归一为渲染组件类型。 +- 验证:全仓 typecheck、API integration `35/35`、Miniapp fixture、Miniapp visual fixture 通过;测试后已重跑 seed 恢复三品牌 demo 数据。 diff --git a/.codex-tasks/runtime-workspace-contract-consolidation/SPEC.md b/.codex-tasks/runtime-workspace-contract-consolidation/SPEC.md new file mode 100644 index 0000000..89c664c --- /dev/null +++ b/.codex-tasks/runtime-workspace-contract-consolidation/SPEC.md @@ -0,0 +1,23 @@ +# Runtime Workspace 契约收敛 + +## 目标 + +让 `public/workspace` 只返回一套符合共享类型的业务提供项展示数据,消除原始 Prisma `offerings` 覆盖 `RuntimeWorkspace.offerings` 的重复响应。 + +## 范围 + +- 扩展 `RuntimeOffering`,承载小程序所需的共享展示数据与模板配置。 +- API 只下发投影后的 Runtime Workspace,不泄漏重复原始字段。 +- Miniapp 改为消费明确的 Runtime Offering 合约。 +- 补 API integration 和 Miniapp fixture 验证。 + +## 非目标 + +- 不新增行业字段、模板或插件。 +- 不保留旧的重复 `offerings` 响应兼容层。 + +## 验收 + +- `RuntimeWorkspace.offerings` 与实际 API 响应一致。 +- 三品牌展示数据、封面、行业标签与详情配置可被小程序读取。 +- API integration、Miniapp fixture、format、typecheck 通过。 diff --git a/.codex-tasks/runtime-workspace-contract-consolidation/TODO.csv b/.codex-tasks/runtime-workspace-contract-consolidation/TODO.csv new file mode 100644 index 0000000..2b53f4a --- /dev/null +++ b/.codex-tasks/runtime-workspace-contract-consolidation/TODO.csv @@ -0,0 +1,4 @@ +id,task,status,acceptance_criteria,validation_command,completed_at,retry_count,notes +1,审计并定义统一 RuntimeOffering 投影,DONE,共享类型覆盖小程序实际展示字段,pnpm --filter @personal-brand/types typecheck,2026-09-24,0,定义共享展示字段与 presentation 投影 +2,切换 API 与小程序至唯一契约,DONE,公开响应不再覆盖 runtime offerings,pnpm --filter @personal-brand/api test:integration,2026-09-24,0,移除 Prisma offerings/modules 覆盖并迁移消费者 +3,补齐回归与任务收口,DONE,三品牌和小程序 fixture 均验证,pnpm format:check && pnpm typecheck,2026-09-24,0,API 35/35 与 Miniapp fixture 均通过;测试后重跑 seed diff --git a/.codex-tasks/team-member-management-epic/EPIC.md b/.codex-tasks/team-member-management-epic/EPIC.md new file mode 100644 index 0000000..f3567f6 --- /dev/null +++ b/.codex-tasks/team-member-management-epic/EPIC.md @@ -0,0 +1,17 @@ +# 品牌团队成员管理 + +## 目标 + +让品牌负责人可以查看当前品牌成员、调整内容编辑权限和启停用成员,同时保护品牌不被误配置到失去负责人。 + +## 规则 + +- 只有 `owner / admin / platform-admin` 可以管理成员。 +- 成员角色支持 `owner` 和 `editor`。 +- 不能修改自己的角色或停用自己。 +- 不能移除最后一位启用的负责人。 +- 成员数据始终按当前品牌隔离。 + +## 未覆盖 + +成员邀请、邮件 / 微信通知、首次登录和跨品牌平台管理员界面作为后续任务。 diff --git a/.codex-tasks/team-member-management-epic/PROGRESS.md b/.codex-tasks/team-member-management-epic/PROGRESS.md new file mode 100644 index 0000000..5a2d02e --- /dev/null +++ b/.codex-tasks/team-member-management-epic/PROGRESS.md @@ -0,0 +1,25 @@ +# 进度 + +- 任务:品牌团队成员管理 +- 形态:epic +- 进度:3/3 +- 当前:成员列表、角色调整和启停用已完成。 + +## 已完成 + +- 新增 `GET /admin/brands/members`。 +- 新增 `PATCH /admin/brands/members/:id`。 +- 新增后台“团队成员”页面。 +- 成员角色使用“负责人 / 内容编辑”业务语言展示。 +- 保护自禁用和最后负责人约束。 + +## 验证 + +- `pnpm --filter @personal-brand/api test:integration`:33/33 通过。 +- `pnpm --filter @personal-brand/admin build`:通过。 +- `pnpm typecheck`:通过。 +- `pnpm format:check`:通过。 + +## 后续边界 + +当前页面只管理已经存在的成员,不提供邀请和首次登录流程;这部分需要单独设计账号生命周期和通知策略。 diff --git a/.codex-tasks/team-member-management-epic/SUBTASKS.csv b/.codex-tasks/team-member-management-epic/SUBTASKS.csv new file mode 100644 index 0000000..ec11b5e --- /dev/null +++ b/.codex-tasks/team-member-management-epic/SUBTASKS.csv @@ -0,0 +1,4 @@ +id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes +1,实现成员列表和角色更新 API,single-full,,DONE,tasks/member-api,owner 可按当前品牌读取和更新成员,pnpm --filter @personal-brand/api test:integration,新增 GET/PATCH /admin/brands/members +2,实现后台团队成员页面,single-full,1,DONE,tasks/member-ui,后台可查看成员并修改角色和状态,pnpm --filter @personal-brand/admin build,新增团队成员页面和系统管理导航 +3,完成成员安全回归,single-full,1;2,DONE,tasks/regression,自禁用、最后负责人保护和品牌隔离有测试,pnpm --filter @personal-brand/api test:integration,API 33/33 通过 diff --git a/.codex-tasks/template-package-foundation-epic/EPIC.md b/.codex-tasks/template-package-foundation-epic/EPIC.md new file mode 100644 index 0000000..d64aeb4 --- /dev/null +++ b/.codex-tasks/template-package-foundation-epic/EPIC.md @@ -0,0 +1,27 @@ +# 林境模板包基础 Epic + +## 目标 + +将林境作为当前唯一正式视觉模板包,保留个人、餐饮、门窗行业模板作为数据与能力声明。移除当前没有独立 renderer、仅复用林境页面的伪视觉模板,建立可扩展的模板包契约和版本快照基础。 + +## 范围 + +- `template.json` 风格的模板包契约类型与校验; +- 林境模板包元数据、页面入口、能力依赖和 fixture; +- 视觉模板目录只暴露林境模板; +- 所有品牌视觉默认值和发布快照统一使用林境; +- Admin、API、Miniapp fixture 和文档同步。 + +## 不在本 Epic + +- 新增餐饮专属视觉模板; +- 运行时下载 WXML/WXSS/JS; +- 媒体上传服务; +- 多模板构建服务。 + +## 设计边界 + +- 行业模板决定业务数据、字段和 capability,不决定视觉代码; +- 林境模板包只消费统一 Runtime Workspace,不读取数据库; +- 后台不能展示没有独立 renderer 的视觉模板; +- 模板包和品牌发布版本都必须保留精确版本。 diff --git a/.codex-tasks/template-package-foundation-epic/PROGRESS.md b/.codex-tasks/template-package-foundation-epic/PROGRESS.md new file mode 100644 index 0000000..7a11d30 --- /dev/null +++ b/.codex-tasks/template-package-foundation-epic/PROGRESS.md @@ -0,0 +1,17 @@ +# 进度 + +- 任务:林境模板包基础 +- 形态:epic +- 进度:3/3 +- 当前:模板包可执行边界已完成;林境是唯一正式视觉模板包,个人、餐饮、门窗继续作为行业数据模板。 +- 真相文件:`SUBTASKS.csv` + +## 阶段执行记录 + +已完成阶段 `1 模板包契约与林境声明`:共享 config 新增 `TemplatePackageManifest`、模板包 registry、入口声明和校验函数,林境包固定为 `linjing-editorial@1.0.0`。 + +已完成阶段 `2 统一唯一视觉模板`:移除 `minimal-neutral` 视觉目录和默认回退;API、Admin、seed、发布快照和模板目录只暴露林境视觉模板。个人、餐饮、门窗仍由行业模板、业务数据和 capability 区分。 + +已完成阶段 `3 全量回归与扩展文档`:`pnpm validate:templates` 校验模板包 `1/1`,`format:check`、全仓 `typecheck`、API integration `37/37`、Admin build、Miniapp fixture、visual fixture 和 `git diff --check` 通过。新增模板流程记录在 `tasks/contract/README.md` 和 `tasks/regression/README.md`。 + +约束:未来新增视觉模板必须提供独立编译期 renderer、manifest、fixture、API 兼容性和构建验证;不得只复制林境 manifest 后注册为新模板。 diff --git a/.codex-tasks/template-package-foundation-epic/SUBTASKS.csv b/.codex-tasks/template-package-foundation-epic/SUBTASKS.csv new file mode 100644 index 0000000..d64fd2f --- /dev/null +++ b/.codex-tasks/template-package-foundation-epic/SUBTASKS.csv @@ -0,0 +1,4 @@ +id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes +1,模板包契约与林境声明,single-full,,DONE,tasks/contract,共享类型提供模板包元数据和运行时入口声明,林境包可校验,pnpm typecheck && pnpm validate:templates,新增 TemplatePackageManifest、registry 和文件级校验器 +2,统一唯一视觉模板,single-full,1,DONE,tasks/linjing-package,API、Admin、seed 和发布默认值只使用林境视觉模板,pnpm --filter @personal-brand/api test:integration,移除 minimal-neutral 目录和默认回退;个人/餐饮/门窗保留为行业模板 +3,全量回归与扩展文档,single-full,1;2,DONE,tasks/regression,fixture、构建、格式、类型和集成测试通过并记录新增模板流程,pnpm format:check && pnpm typecheck && pnpm --filter @personal-brand/api test:integration && pnpm --filter @personal-brand/admin build,模板校验 1/1;API 37/37;Admin、Miniapp fixture、visual fixture 和格式检查通过 diff --git a/.codex-tasks/template-package-foundation-epic/tasks/contract/README.md b/.codex-tasks/template-package-foundation-epic/tasks/contract/README.md new file mode 100644 index 0000000..e9813af --- /dev/null +++ b/.codex-tasks/template-package-foundation-epic/tasks/contract/README.md @@ -0,0 +1,3 @@ +# 模板包契约 + +当前正式视觉模板包为 `linjing-editorial@1.0.0`,元数据位于 `templates/linjing-editorial/template.json`。未来新增视觉模板必须提供独立的编译期页面 renderer,不得只复制林境 manifest 或复用林境 renderer 后伪装成新模板。 diff --git a/.codex-tasks/template-package-foundation-epic/tasks/regression/README.md b/.codex-tasks/template-package-foundation-epic/tasks/regression/README.md new file mode 100644 index 0000000..2663fa5 --- /dev/null +++ b/.codex-tasks/template-package-foundation-epic/tasks/regression/README.md @@ -0,0 +1,3 @@ +# 扩展门禁 + +新增视觉模板前必须同时提交:模板包声明、页面入口、Runtime Workspace 适配说明、品牌/行业兼容性、运行时 fixture、视觉 fixture、Admin 目录展示、API 集成测试和生产构建结果。 diff --git a/.codex-tasks/template-package-runtime-epic/EPIC.md b/.codex-tasks/template-package-runtime-epic/EPIC.md new file mode 100644 index 0000000..fe24333 --- /dev/null +++ b/.codex-tasks/template-package-runtime-epic/EPIC.md @@ -0,0 +1,18 @@ +# 模板包运行时与构建体系 + +## 目标 + +将视觉模板从 `apps/miniapp` 主工程中隔离为独立 pnpm workspace package,通过构建期 compiler 生成微信小程序目录,支持大量模板扩展而不引入运行时下载。 + +## 阶段 + +1. 模板包协议与校验。 +2. 本地 template compiler 和开发命令。 +3. 林境、阿成模板迁移到独立 package。 +4. 发布配置、快照版本和模板回归门禁。 + +## 非目标 + +- 不实现小程序运行时下载或执行模板代码。 +- 不把 300 个模板打入同一个小程序包。 +- 不复制登录、API、预约状态机等业务逻辑到模板包。 diff --git a/.codex-tasks/template-package-runtime-epic/PROGRESS.md b/.codex-tasks/template-package-runtime-epic/PROGRESS.md new file mode 100644 index 0000000..e891ed9 --- /dev/null +++ b/.codex-tasks/template-package-runtime-epic/PROGRESS.md @@ -0,0 +1,62 @@ +# 进度 + +- 任务:模板包运行时与构建体系 +- 形态:epic +- 进度:4/4 +- 当前:模板包运行时与构建体系已完成,阿成与林境静态视觉原型均已通过人工验收;后续新增模板继续按独立 package + compiler 产物流程接入。动态数据、接口联调和品牌切换另行验收。 +- 真相文件:`SUBTASKS.csv` + +## 决策 + +- 模板包是构建输入,不是小程序运行时下载内容。 +- 单次构建只包含一个模板包。 +- 模板包只负责视觉页面、导航和交互表达;公共 runtime 负责数据、鉴权、提交和状态。 + +## 已完成 + +- 新增 `packages/template-contract`,定义 runtime contract `1.0`、页面入口和导航声明。 +- 新增 `packages/template-compiler`,支持 `pnpm template:dev --out `。 +- 新增 `packages/template-acheng-campus-food` 模板包骨架,已通过 workspace 模板校验。 +- 编译器已验证可生成带 `template.manifest.json` 的 Mini Program 目录。 +- 新增 `template-linjing-editorial` 包声明。 +- 阿成首页、菜单、主理人和出摊服务 renderer 已复制到独立模板包,compiler 会以 `apps/miniapp` shell 为基底合并模板文件。 +- compiler 现在会根据模板声明生成 `app.json` 标题和 `template.runtime.json`,并在生成前校验页面入口、导航和 runtime contract。 +- 当前仍处于迁移过渡期:shell 的旧 renderer 暂不删除,避免页面配置尚未覆盖完整时生成不可编译目录;只有模板包完成页面级覆盖后才执行所有权清理。 +- 新增 compiler 自动测试,验证阿成 5 导航、林境 3 导航、模板标题和 renderer 文件隔离。 +- 模板包现在声明 `renderers`,阿成和林境 renderer 源码已复制进各自 package;compiler 会校验 renderer 文件存在。 +- compiler 根据模板声明生成 `app.json.tabBar`,并从生成目录移除自定义 runtime tab bar 组件和引用;阿成 5 项、林境 3 项均有回归测试。 +- 导航协议支持模板扩展 entrypoint;阿成的“出摊服务”现在独立指向 `pages/stall-service/index`,不再与餐品页复用同一入口。 +- compiler 为模板 renderer 生成稳定的 `components/template-pages/` alias,公共页面不再需要引用 `acheng-*` 或 `linjing-*` 组件名;生成页面只依赖 `template-home`、`template-offerings`、`template-profile` 等稳定别名。 +- 对没有专属 renderer 的模板页面,compiler 使用公共 runtime 模块生成 alias,不会从其他行业模板借用组件;单次生成结果中的 renderer 条件会被构建期固化,避免运行时保留模板分支。 +- 咨询页已移除 `templateKey` 行业分支,改为使用 workspace 下发的 presentation;compiler 会校验 manifest 中所有 entrypoint 的 `.js/.json/.wxml/.wxss` 文件均存在。 +- 生成完成后会删除 `components/templates` 旧 renderer 目录,生成产物不再携带其他模板组件;林境产物已验证不会混入阿成 renderer。 +- manifest 现在显式声明 `runtimeOwnedPages`,当前详情、咨询、成功、记录由公共 runtime 所有;compiler 会扫描生成页面,拒绝旧模板路径、runtime tab bar 和 `templateKey` 行业分支残留。 +- `pnpm test:template-compiler` 已通过,生成链路现在有自动回归而不是只依赖手工检查。 + +## 本轮验证 + +- `pnpm validate:templates` +- `pnpm test:template-compiler` +- `pnpm typecheck` +- `pnpm format:check` +- `git diff --check` + +## 未完成 + +- 详情、成功、记录页面暂时继续使用公共 runtime 模块,后续如需行业专属视觉可通过 manifest renderer 声明扩展。 +- `ownedPaths` 仍用于声明模板源码所有权,但生成目录清理已由 compiler 的产物隔离逻辑负责。 +- 当前构建门禁已通过:`pnpm test:template-compiler`、`pnpm validate:templates`、`pnpm typecheck`、`pnpm format:check`、`git diff --check`。 +- 发布门禁已通过:`pnpm validate:template-release`、Mini Program fixture、visual fixture。 +- 阿成模板已补齐 5 个真实页面入口:首页、套餐餐品、出摊服务、主理人、定制咨询;生成目录的 5 个 tab 全部由微信原生 `tabBar` 驱动。 +- 阿成模板 package 进一步补齐餐品详情、预订成功、预订记录 3 个二级页面,并统一餐饮橙色视觉;生成产物的 8 个页面均来自 package 或公共 runtime 的明确入口。 +- 阿成 tab 图标资源已归属模板 package;图标完整性校验放在模板包校验脚本,compiler 只按 manifest 复制并写入原生 `tabBar`,不包含行业资源特判。 +- 本轮按 `/home/que01/下载/阿成校园餐---微信小程序原型/` 的 `ServiceView`、`BookingView` 先完成静态页面迁移:出摊服务包含固定日程、配送范围、4 步定制流程和咨询 CTA;定制咨询包含表单 / 历史记录切换、类型网格、人数/日期/预算/配送选择、错误态、提交承诺和记录卡,并继续接入现有提交接口。 +- 林境模板补齐独立案例 renderer、案例分类筛选、第三个 tab 外层间距和原生 tabBar 图标;模板声明默认品牌 `linjing-doors`,生成产物不再请求 `default-brand`。 +- 静态验收结论:阿成与林境模板的页面结构、主要视觉表现、原生 tabBar 和模板间隔离达到当前验收标准。 +- `apps/miniapp` 仍是开发过渡 shell,最终人工验收目录必须使用 `pnpm template:dev --out ` 生成的构建产物;生成产物已确认不包含自定义 tab bar。 + +## 阶段结论 + +- 阶段 3 模板包迁移:已完成,静态原型迁移和生成产物已人工验收。 +- 阶段 4 发布配置与回归:已完成,发布、fixture、类型和格式门禁通过。 +- 后续新增模板只需新增独立 `packages/template-*`、更新 `config/template-build.json`,并通过 compiler、fixture 和人工验收门禁。 diff --git a/.codex-tasks/template-package-runtime-epic/SUBTASKS.csv b/.codex-tasks/template-package-runtime-epic/SUBTASKS.csv new file mode 100644 index 0000000..5f5bb21 --- /dev/null +++ b/.codex-tasks/template-package-runtime-epic/SUBTASKS.csv @@ -0,0 +1,5 @@ +id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes +1,模板包协议与校验,single-full,,DONE,tasks/contract,协议定义并能校验模板包声明,pnpm validate:templates,已增加 template-contract 和 workspace 包校验 +2,本地 template compiler,single-full,1,DONE,tasks/compiler,可从 workspace 模板包生成 Mini Program 目录,pnpm template:dev acheng-campus-food,已验证生成 manifest 和 Mini Program 目录 +3,模板包迁移,single-full,2,DONE,tasks/migration,林境和阿成源码由独立包提供,pnpm test:template-compiler,已完成人工验收;阿成 5 个 tab 页面及详情/成功/记录二级页面和 tab 图标资源均归属 template package +4,发布配置与回归,single-full,3,DONE,tasks/release,模板包版本进入构建配置并完成 fixture/API 回归,pnpm validate:template-release,发布配置、模板 fixture、compiler、类型和格式门禁均已通过 diff --git a/.codex-tasks/template-sample-content-registry-followup/PROGRESS.md b/.codex-tasks/template-sample-content-registry-followup/PROGRESS.md new file mode 100644 index 0000000..0aa192d --- /dev/null +++ b/.codex-tasks/template-sample-content-registry-followup/PROGRESS.md @@ -0,0 +1,10 @@ +# 进度 + +- 任务:按当前行业选择模板示例内容 +- 形态:single-full +- 状态:DONE +- 当前:已完成 +- 关联任务:`template-sample-content-registry` +- 已补齐个人品牌、餐饮、门窗三套示例内容注册。 +- API 按当前品牌 `templateKey` 选择示例包,不再固定门窗 key。 +- 验证:`format:check`、全仓 `typecheck`、API integration(链路成功完成)、测试后 seed 恢复。 diff --git a/.codex-tasks/template-sample-content-registry/PROGRESS.md b/.codex-tasks/template-sample-content-registry/PROGRESS.md new file mode 100644 index 0000000..4ea71eb --- /dev/null +++ b/.codex-tasks/template-sample-content-registry/PROGRESS.md @@ -0,0 +1,13 @@ +# 进度 + +- 任务:模板示例内容注册表 +- 形态:single-full +- 进度:3/3 +- 当前:已完成 +- 真相文件:`TODO.csv` + +## 结果 + +- `@personal-brand/config` 新增 `TemplateSampleContent` 与门窗模板示例注册表。 +- Admin Workspace Controller 只消费注册表,不再写死业务项、信任内容和字段。 +- `pnpm typecheck` 已通过;API integration 和全量格式门禁待最终执行。 diff --git a/.codex-tasks/template-sample-content-registry/SPEC.md b/.codex-tasks/template-sample-content-registry/SPEC.md new file mode 100644 index 0000000..3d569b2 --- /dev/null +++ b/.codex-tasks/template-sample-content-registry/SPEC.md @@ -0,0 +1,17 @@ +# 模板示例内容注册表 + +## 目标 + +将模板示例内容从 API Controller 移入 `@personal-brand/config` 注册表,保证模板安装与导入由声明驱动。 + +## 决策 + +- 示例业务项、信任内容、字段和能力归属属于模板包定义。 +- Controller 只负责权限、幂等检查、事务和审计。 +- 本轮先迁移现有门窗示例内容,后续行业模板按同一注册表扩展。 + +## 验收 + +- 示例内容接口不再包含行业文案、字段数组或数量常量。 +- 现有预览、导入、重复导入行为保持一致。 +- API、config、format、typecheck 通过。 diff --git a/.codex-tasks/template-sample-content-registry/TODO.csv b/.codex-tasks/template-sample-content-registry/TODO.csv new file mode 100644 index 0000000..c0b98a7 --- /dev/null +++ b/.codex-tasks/template-sample-content-registry/TODO.csv @@ -0,0 +1,4 @@ +id,task,status,acceptance_criteria,validation_command,completed_at,retry_count,notes +1,建立模板示例内容注册表,DONE,门窗示例内容迁移至 config,pnpm typecheck,2026-09-24,0, +2,改造示例内容 API 使用注册表,DONE,Controller 无行业内容硬编码,pnpm --filter @personal-brand/api test:integration,2026-09-24,0,保留现有导入幂等与审计 +3,完成格式与回归验证,DONE,全量门禁通过,pnpm format:check && pnpm typecheck,2026-09-24,0, diff --git a/.codex-tasks/user-facing-brand-config-epic/EPIC.md b/.codex-tasks/user-facing-brand-config-epic/EPIC.md new file mode 100644 index 0000000..38efc34 --- /dev/null +++ b/.codex-tasks/user-facing-brand-config-epic/EPIC.md @@ -0,0 +1,17 @@ +# 面向普通用户的品牌配置闭环 + +## 目标 + +在不暴露模板 key、能力状态、版本快照等管理员概念的前提下,让普通品牌使用者可以通过易懂的表单维护品牌表达、页面文案和图片,并让小程序通过 Runtime Workspace 实时消费这些配置。 + +## 边界 + +- 普通用户配置:我是谁、信任表达、业务展示、咨询文案、联系方式和图片。 +- 管理员配置:行业模板、视觉模板、能力插件、版本升级、回滚和数据结构。 +- 所有配置按当前品牌隔离,不能由客户端提交 brandId。 + +## 验收 + +- 普通用户无需理解 JSON、manifest、slot 或 template key。 +- 保存失败保留输入并显示可操作错误,成功后刷新预览和 Runtime Workspace。 +- API 有授权、成功、品牌隔离自动化测试。 diff --git a/.codex-tasks/user-facing-brand-config-epic/PROGRESS.md b/.codex-tasks/user-facing-brand-config-epic/PROGRESS.md new file mode 100644 index 0000000..1c42fe7 --- /dev/null +++ b/.codex-tasks/user-facing-brand-config-epic/PROGRESS.md @@ -0,0 +1,18 @@ +# 进度 + +- 任务:面向普通用户的品牌配置闭环 +- 形态:epic +- 进度:4/4 +- 当前:本 Epic 已完成,下一步补齐普通用户的图片、作品和服务内容配置 +- 真相文件:`SUBTASKS.csv` + +## 决策 + +- 普通用户不接触模板 key、manifest、slot、插件和快照。 +- 管理员工作区继续承载模板安装、视觉模板切换、能力和版本管理。 +- presentation 以页面语义分组保存,后端合并到当前品牌 config,由公开 workspace 下发。 +- 2026-09-23:presentation API 和普通用户表单已完成。API 集成测试 `31/31` 通过,后台 `build`、`lint`、`typecheck`、`format:check` 通过;下一步验证保存后预览刷新和小程序运行时读取。 +- 2026-09-23:后台新增“当前已生效内容”运行时预览,保存成功会刷新公开 workspace,读取失败有明确提示;admin build、lint、typecheck、format:check 均通过。 +- 2026-09-23:配置闭环回归完成:API 集成测试 `31/31`、admin build、全仓 lint/typecheck/format、miniapp fixture 和 visual-fixture 均通过。 +- 2026-09-23:补充主理人身份配置,普通用户可维护姓名、身份、主张、电话、微信和服务范围;身份字段写入品牌 runtime identity,不混入视觉模板 section。API 集成测试继续保持 `31/31`。 +- 2026-09-23:在运行时预览中明确显示“主理人 / 老板姓名”和身份,避免字段虽已保存但普通用户无法确认小程序是否生效。 diff --git a/.codex-tasks/user-facing-brand-config-epic/SUBTASKS.csv b/.codex-tasks/user-facing-brand-config-epic/SUBTASKS.csv new file mode 100644 index 0000000..f4b868e --- /dev/null +++ b/.codex-tasks/user-facing-brand-config-epic/SUBTASKS.csv @@ -0,0 +1,5 @@ +id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes +1,定义用户配置契约与品牌 presentation API,single-full,,DONE,tasks/presentation-api,普通用户可提交受控的 presentation 配置且按当前品牌保存,pnpm --filter @personal-brand/api test:integration,独立 presentation API 只接受允许的页面 section,集成测试 31/31 通过 +2,实现普通用户友好的品牌表达表单,single-full,1,DONE,tasks/brand-editor,表单使用中文业务概念并覆盖核心页面文案和资源,pnpm --filter @personal-brand/admin build,已实现首页、咨询页、主理人与我页面表达表单;不暴露 JSON、manifest、slot 和版本概念 +3,接入保存后的运行时预览与错误状态,single-full,1;2,DONE,tasks/runtime-preview,保存成功刷新后台预览和小程序运行时数据,pnpm --filter @personal-brand/admin build,已显示小程序当前已生效内容;运行时读取失败显示明确提示,保存失败保留输入 +4,完成配置闭环测试与文档,single-full,1;2;3,DONE,tasks/regression,授权、品牌隔离、保存、刷新和构建全部验证,pnpm format:check && pnpm lint && pnpm typecheck && pnpm --filter @personal-brand/api test:integration,API 31/31、admin build、全仓 lint/typecheck/format、miniapp fixture 均通过 diff --git a/.codex-tasks/user-facing-form-config-epic/EPIC.md b/.codex-tasks/user-facing-form-config-epic/EPIC.md new file mode 100644 index 0000000..44ca259 --- /dev/null +++ b/.codex-tasks/user-facing-form-config-epic/EPIC.md @@ -0,0 +1,18 @@ +# 普通用户咨询表单配置 + +## 目标 + +让普通品牌使用者可以用业务语言配置咨询表单,而不需要理解字段 key、JSON 或内部提交协议。 + +## 边界 + +- 表单名称、用途和关联业务保留为业务概念。 +- 字段只展示“要询问客户什么、回答方式、是否必填、可选内容”。 +- 字段 key 自动生成并稳定保存在快照中。 +- 后端继续负责字段校验、版本递增和提交快照,不在前端绕过校验。 + +## 完成条件 + +- 后台不显示英文 type、Key 或选项 JSON。 +- 新增和编辑字段能生成符合 API 校验的快照。 +- API integration、admin build、typecheck 和格式检查通过。 diff --git a/.codex-tasks/user-facing-form-config-epic/PROGRESS.md b/.codex-tasks/user-facing-form-config-epic/PROGRESS.md new file mode 100644 index 0000000..d522d0d --- /dev/null +++ b/.codex-tasks/user-facing-form-config-epic/PROGRESS.md @@ -0,0 +1,20 @@ +# 进度 + +- 任务:普通用户咨询表单配置 +- 形态:epic +- 进度:3/3 +- 当前:本轮已完成,后台表单编辑器面向普通用户收敛。 + +## 已完成 + +- 字段编辑改为中文业务表达:字段名称、回答方式、必填状态和可选内容。 +- 内部字段 key 自动生成并隐藏,编辑已有表单时保持原 key。 +- 选择类字段使用逐行或顿号分隔的普通文本,不再要求输入 JSON。 +- 后端字段校验、版本递增和运行时提交链路保持不变。 + +## 验证 + +- `pnpm --filter @personal-brand/admin build`:通过。 +- `pnpm --filter @personal-brand/api test:integration`:31/31 通过。 +- `pnpm typecheck`:通过。 +- `pnpm format:check`:通过。 diff --git a/.codex-tasks/user-facing-form-config-epic/SUBTASKS.csv b/.codex-tasks/user-facing-form-config-epic/SUBTASKS.csv new file mode 100644 index 0000000..70f195a --- /dev/null +++ b/.codex-tasks/user-facing-form-config-epic/SUBTASKS.csv @@ -0,0 +1,4 @@ +id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes +1,改造普通用户表单字段编辑器,single-full,,DONE,tasks/form-editor,字段使用中文业务表达且自动处理内部 key 和 options,pnpm --filter @personal-brand/admin build,已移除 Key、英文类型和选项 JSON 输入 +2,验证表单运行时链路,single-full,1,DONE,tasks/runtime-regression,版本、校验和客户提交链路无回归,pnpm --filter @personal-brand/api test:integration,API 31/31 通过 +3,落盘交付记录,single-full,1;2,DONE,tasks/delivery,进度和验证命令已记录,pnpm format:check && pnpm typecheck,format、typecheck 通过 diff --git a/.codex-tasks/user-facing-media-config-epic/EPIC.md b/.codex-tasks/user-facing-media-config-epic/EPIC.md new file mode 100644 index 0000000..5ae624e --- /dev/null +++ b/.codex-tasks/user-facing-media-config-epic/EPIC.md @@ -0,0 +1,17 @@ +# 普通用户图片资源配置 + +## 目标 + +统一品牌头像、封面、服务封面和信任内容配图的配置体验,让普通用户可以在保存前确认图片效果。 + +## 当前边界 + +- 当前阶段没有文件存储或上传服务,因此只接受可公开访问的图片地址。 +- 所有图片地址输入统一使用预览控件,避免用户保存后才发现地址不可用。 +- 后续接入媒体库时替换控件内部实现,不改变业务字段契约。 + +## 完成条件 + +- 品牌、业务提供项和信任内容统一使用图片预览控件。 +- 不再使用 `URL` 技术术语作为普通用户字段标签。 +- build、typecheck 和 format check 通过。 diff --git a/.codex-tasks/user-facing-media-config-epic/PROGRESS.md b/.codex-tasks/user-facing-media-config-epic/PROGRESS.md new file mode 100644 index 0000000..84b00c7 --- /dev/null +++ b/.codex-tasks/user-facing-media-config-epic/PROGRESS.md @@ -0,0 +1,23 @@ +# 进度 + +- 任务:普通用户图片资源配置 +- 形态:epic +- 进度:3/3 +- 当前:图片地址配置和预览已完成;后续可独立建设媒体库与上传服务。 + +## 已完成 + +- 品牌头像和品牌封面使用统一图片预览控件。 +- 业务提供项封面使用统一图片预览控件。 +- 信任内容配图使用统一图片预览控件。 +- 普通用户标签改为“图片地址 / 配图地址”,不再显示 `URL`。 + +## 验证 + +- `pnpm --filter @personal-brand/admin build`:通过。 +- `pnpm typecheck`:通过。 +- `pnpm format:check`:通过。 + +## 后续边界 + +文件上传需要对象存储、访问权限、大小和格式限制、删除策略以及品牌隔离,不能在当前仅有 URL 字段的基础上伪装实现;应作为独立媒体库任务推进。 diff --git a/.codex-tasks/user-facing-media-config-epic/SUBTASKS.csv b/.codex-tasks/user-facing-media-config-epic/SUBTASKS.csv new file mode 100644 index 0000000..082121d --- /dev/null +++ b/.codex-tasks/user-facing-media-config-epic/SUBTASKS.csv @@ -0,0 +1,4 @@ +id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes +1,统一图片地址和预览控件,single-full,,DONE,tasks/image-preview,四类普通用户图片配置复用同一控件,pnpm --filter @personal-brand/admin build,新增 ImageUrlField 并接入品牌、业务和信任内容 +2,验证图片配置不影响业务契约,single-full,1,DONE,tasks/contract-regression,全仓类型和格式检查通过,pnpm typecheck && pnpm format:check,已通过 +3,记录上传能力边界,single-full,1;2,DONE,tasks/delivery,明确当前未实现文件上传且保留后续替换边界,pnpm --filter @personal-brand/admin build,已记录在 EPIC 和 PROGRESS diff --git a/.codex-tasks/user-facing-service-config-epic/EPIC.md b/.codex-tasks/user-facing-service-config-epic/EPIC.md new file mode 100644 index 0000000..49dd409 --- /dev/null +++ b/.codex-tasks/user-facing-service-config-epic/EPIC.md @@ -0,0 +1,18 @@ +# 普通用户业务提供项配置 + +## 目标 + +让不懂技术的品牌使用者可以用业务语言维护服务、产品或套餐,并安全地影响小程序公开展示。 + +## 边界 + +- 普通用户只接触名称、介绍、价格、封面、顺序和公开状态。 +- `sections`、`media`、`cta` 等模板结构继续由系统和管理员维护,不出现在普通用户表单中。 +- 禁用后不进入公开 workspace;存在关联咨询表单时禁止删除。 + +## 完成条件 + +- 后台编辑器不暴露内部配置字段。 +- 编辑普通字段不会覆盖已有模板详情配置。 +- API 授权、品牌隔离、启用状态和删除保护测试通过。 +- admin build、格式化和类型检查通过。 diff --git a/.codex-tasks/user-facing-service-config-epic/PROGRESS.md b/.codex-tasks/user-facing-service-config-epic/PROGRESS.md new file mode 100644 index 0000000..b5131b3 --- /dev/null +++ b/.codex-tasks/user-facing-service-config-epic/PROGRESS.md @@ -0,0 +1,18 @@ +# 进度 + +- 任务:普通用户业务提供项配置 +- 形态:epic +- 进度:3/3 +- 当前:本轮普通用户业务提供项配置已完成,下一步进入图片资源和咨询表单的易用化。 + +## 已完成 + +- 移除普通用户表单中的 `sections`、`media`、`cta` 内部结构。 +- 编辑时仅回填和提交用户可理解的业务字段,避免覆盖模板详情配置。 +- 删除增加二次确认,并保留关联咨询表单时由 API 阻止删除。 + +## 验证 + +- `pnpm --filter @personal-brand/api test:integration`:31/31 通过。 +- `pnpm --filter @personal-brand/admin build`:通过。 +- `pnpm exec prettier --check apps/admin/src/features/services/ServicesPage.tsx`:通过。 diff --git a/.codex-tasks/user-facing-service-config-epic/SUBTASKS.csv b/.codex-tasks/user-facing-service-config-epic/SUBTASKS.csv new file mode 100644 index 0000000..26930be --- /dev/null +++ b/.codex-tasks/user-facing-service-config-epic/SUBTASKS.csv @@ -0,0 +1,4 @@ +id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes +1,收敛普通用户业务提供项编辑器,single-full,,DONE,tasks/user-facing-editor,表单仅展示业务字段且编辑不回传内部配置,pnpm --filter @personal-brand/admin build,已移除 sections、media、cta 编辑控件,并限制编辑回填字段 +2,验证业务提供项生命周期,single-full,1,DONE,tasks/lifecycle-regression,启用、禁用、删除保护和公开 workspace 行为有自动化验证,pnpm --filter @personal-brand/api test:integration,现有 offering 生命周期测试 31/31 通过,覆盖禁用隐藏和关联表单删除保护 +3,更新交付记录,single-full,1;2,DONE,tasks/delivery,任务进度和验证结果落盘,pnpm format:check && pnpm typecheck,admin build、API integration、format 均通过 diff --git a/.codex-tasks/visual-template-compatibility-guard/PROGRESS.md b/.codex-tasks/visual-template-compatibility-guard/PROGRESS.md new file mode 100644 index 0000000..422a594 --- /dev/null +++ b/.codex-tasks/visual-template-compatibility-guard/PROGRESS.md @@ -0,0 +1,14 @@ +# 进度 + +- 任务:视觉模板兼容性约束 +- 形态:single-full +- 进度:3/3 +- 当前:视觉模板兼容性约束完成 +- 真相文件:`TODO.csv` + +## 恢复信息 + +- 已完成:视觉模板 definition 与 manifest 增加 `supportedIndustryTemplates`,兼容关系由配置声明。 +- 已完成:目录、组合预览、管理员实际切换统一执行兼容性校验;餐饮不能选择林境建筑画册。 +- 已完成:后台视觉模板选择器和组合预览仅展示当前行业可用模板。 +- 验证:API integration `36/36`、全仓 typecheck、Prettier format check 通过;Admin production build 已在前序回归通过。 diff --git a/.codex-tasks/visual-template-compatibility-guard/SPEC.md b/.codex-tasks/visual-template-compatibility-guard/SPEC.md new file mode 100644 index 0000000..affad69 --- /dev/null +++ b/.codex-tasks/visual-template-compatibility-guard/SPEC.md @@ -0,0 +1,19 @@ +# 视觉模板兼容性约束 + +## 目标 + +让视觉模板对行业模板的适配关系成为显式声明,并在目录、组合预览和实际切换时统一校验。 + +## 决策 + +- `linjing-editorial` 适配 `personal`、`doors`,不作为餐饮视觉模板。 +- `minimal-neutral` 适配 `personal`、`food`、`doors`。 +- 兼容性由视觉模板 manifest 声明,不能在 Controller 中写行业分支。 +- API 拒绝不兼容组合;后台只展示当前行业可用视觉模板。 + +## 验收 + +- 视觉目录返回兼容行业列表。 +- 不兼容的组合预览和切换返回明确 `400`。 +- 兼容模板切换行为保持不变。 +- API integration、Admin build、format、typecheck 通过。 diff --git a/.codex-tasks/visual-template-compatibility-guard/TODO.csv b/.codex-tasks/visual-template-compatibility-guard/TODO.csv new file mode 100644 index 0000000..563e1b7 --- /dev/null +++ b/.codex-tasks/visual-template-compatibility-guard/TODO.csv @@ -0,0 +1,4 @@ +id,task,status,acceptance_criteria,validation_command,completed_at,retry_count,notes +1,增加视觉模板兼容声明与校验函数,DONE,config manifest 明确支持的行业模板,pnpm --filter @personal-brand/config typecheck,2026-09-24,0,兼容关系由 manifest 声明 +2,接入 API 目录预览与切换校验,DONE,不兼容组合无法预览或保存,pnpm --filter @personal-brand/api test:integration,2026-09-24,0,不兼容组合返回 400;兼容组合保持成功 +3,更新后台选择器与全量回归,DONE,后台只显示当前行业可用模板,pnpm format:check && pnpm typecheck && pnpm --filter @personal-brand/admin build,2026-09-24,0,API integration 36/36 通过;类型与格式通过 diff --git a/.codex-tasks/visual-template-package-epic/PROGRESS.md b/.codex-tasks/visual-template-package-epic/PROGRESS.md index a8d3363..7f11f34 100644 --- a/.codex-tasks/visual-template-package-epic/PROGRESS.md +++ b/.codex-tasks/visual-template-package-epic/PROGRESS.md @@ -3,7 +3,7 @@ - 任务:小程序视觉模板包体系 - 形态:epic - 进度:5/5 -- 当前:视觉模板包体系本轮完成 +- 当前:本 Epic 已完成,下一阶段应进入模板选择与内容配置的真实业务验收 - 真相文件:`SUBTASKS.csv` ## 恢复信息 @@ -12,8 +12,11 @@ - 已新增 `VisualTemplateManifest`、`TemplatePackage`、页面/模块/资源/数据槽位和设计 token 类型。 - 已将林境模板登记为 7 个核心页面的正式 manifest,并保留个人品牌主线、行业解耦和能力依赖。 - `pnpm format:check`、`pnpm --filter @personal-brand/config typecheck`、`git diff --check` 已通过。 -- 小程序 workspace 现在消费 `visualTemplateManifest`,将 manifest 页面模块解析为运行时模块和首页布局,并兼容旧版 `layout`。 -- API workspace 返回完整视觉 manifest,API integration 28/28、Miniapp fixture 和 visual fixture 已通过。 -- 模板安装快照现在包含行业模板、视觉 manifest 和能力依赖;现有示例内容导入流程保持幂等并纳入安装验收。 -- 全量门禁通过:`format:check`、`lint`、`typecheck`、`build`、API integration 28/28、Miniapp fixture 和 visual fixture。 -- lint 仅保留既有测试文件中的 6 个 `any` warning,无 error。 +- 已发现:先前仅验证 manifest 形状,没有验证静态设计中的顶部主理人信息和信任区数据投影,也没有达到林境静态页的视觉还原要求。 +- 当前修复:API 正式投影品牌身份与信任呈现数据;seed 由模板声明注册表驱动,消除按行业 key 的共享逻辑分支;首页开始渲染工艺支柱与履约流程。 +- 本轮新增:林境的完整作品规格、履约资料和咨询字段由模板初始数据声明导入;小程序移除了静默回退到过期静态数据的路径,改为同品牌 workspace 缓存与明确错误状态。已确认 `172.16.6.123:3001` 的 `linjing-doors` workspace 返回 4 个完整作品、品牌资料、信任内容和表单字段。 +- 内容审计:林境首页、作品、详情、咨询、提交成功、记录与“主理人与我”的业务文案均已改为读取 `brand.visualPresentation`、`trustPresentation`、`offerings` 或 `inquiryForms`。布局、图标和通用交互仍保留在视觉组件中。API 集成测试覆盖了关键 presentation 文案下发。 +- 视觉验收限制:本机微信开发者工具 CLI 不提供可脚本化截图能力;文本 fixture 只能验证页面绑定和结构。用户已确认首页、作品、详情、咨询、成功、记录、我的页面均能正常显示。 +- 2026-09-23:数据真实性复核完成。小程序业务内容来自 `public/workspace`,图片来自 workspace brand/offering 数据,表单来自 `inquiryForms`,咨询记录来自客户 API;已删除未使用的 `linjingInquiryRecords` 本地假数据读取。客户微信会话改为携带 `brandSlug`,服务端按请求品牌签发 token,并在集成测试中验证林境品牌隔离。 +- 2026-09-23:通用组件的林境业务硬编码已清理,联系人标签、信任标题、流程标题和作品区文案改由 presentation slot 输入;fixture 增加品牌会话隔离与静态业务词泄漏检查。 +- 2026-09-23:全量回归完成:`format:check`、`lint`、`typecheck`、`build`、API 集成测试 `30/30`、miniapp fixture、visual-fixture 和 `git diff --check` 全部通过。lint 仅有既存测试文件的 6 个 `any` warning,无新增 error。 diff --git a/.codex-tasks/visual-template-package-epic/SUBTASKS.csv b/.codex-tasks/visual-template-package-epic/SUBTASKS.csv index 481e74b..5b70fc1 100644 --- a/.codex-tasks/visual-template-package-epic/SUBTASKS.csv +++ b/.codex-tasks/visual-template-package-epic/SUBTASKS.csv @@ -1,6 +1,6 @@ id,title,task_type,depends_on,status,task_dir,acceptance_criteria,validation_command,notes 1,定义视觉模板包契约,single-full,,DONE,tasks/contract,VisualTemplateManifest 和 TemplatePackage 类型及契约说明完成,pnpm format:check && pnpm --filter @personal-brand/config typecheck,共享契约和 ADR 已完成 2,将林境静态设计映射为正式视觉模板,single-full,1,DONE,tasks/linjing-mapping,林境核心页面和资源数据映射到 manifest,pnpm --filter @personal-brand/config typecheck,7 个页面、模块变体、资源槽位、数据槽位和能力依赖已登记 -3,改造小程序按 manifest 和 variant 渲染,single-full,1;2,DONE,tasks/miniapp-renderer,小程序不再依赖行业硬编码页面结构,pnpm --filter @personal-brand/miniapp test:fixture && pnpm --filter @personal-brand/miniapp test:visual-fixture,运行时解析 visualTemplateManifest,保留旧 workspace 兼容 +3,改造小程序按 manifest 和 variant 渲染,single-full,1;2,DONE,tasks/miniapp-renderer,小程序按 manifest 和 variant 渲染且林境视觉与数据完整,pnpm --filter @personal-brand/miniapp test:fixture && pnpm --filter @personal-brand/miniapp test:visual-fixture,用户已在微信开发者工具确认核心页面正常显示;数据链路与多品牌客户会话已验证 4,初始数据导入与模板安装快照,single-full,1;2,DONE,tasks/installation,新品牌可安装模板并导入初始内容且生成快照,pnpm --filter @personal-brand/api test:integration,安装快照包含行业模板、视觉 manifest 和能力依赖;示例内容导入保持幂等 -5,视觉与全量回归,single-full,1;2;3;4,DONE,tasks/regression,接口、构建、fixture 和视觉回归全部通过,pnpm format:check && pnpm lint && pnpm typecheck && pnpm --filter @personal-brand/api test:integration,全部门禁通过;lint 保留 6 个既有 any warning +5,视觉与全量回归,single-full,1;2;3;4,DONE,tasks/regression,接口、构建、fixture 和视觉回归全部通过,pnpm format:check && pnpm lint && pnpm typecheck && pnpm --filter @personal-brand/api test:integration,用户页面验收通过;全量工程门禁与 API 30/30 集成测试通过 diff --git a/.codex-tasks/visual-template-package-epic/tasks/miniapp-renderer/PROGRESS.md b/.codex-tasks/visual-template-package-epic/tasks/miniapp-renderer/PROGRESS.md index 8ed568a..8089f21 100644 --- a/.codex-tasks/visual-template-package-epic/tasks/miniapp-renderer/PROGRESS.md +++ b/.codex-tasks/visual-template-package-epic/tasks/miniapp-renderer/PROGRESS.md @@ -2,5 +2,9 @@ - 状态:DONE - 依赖:视觉模板包契约、林境模板映射和用户验收 -- 结果:公共 workspace 返回视觉 manifest;Miniapp runtime 按 manifest 页面和模块 variant 解析,并保留旧 workspace fallback。 -- 验证:`pnpm --filter @personal-brand/api test:integration`、`pnpm --filter @personal-brand/miniapp test:fixture`、`pnpm --filter @personal-brand/miniapp test:visual-fixture` +- 已发现静态设计还原缺口,不能以 manifest 返回和 fixture 通过作为完成标准。 +- 当前方向:删除不必要的旧契约兼容思路,使用模板声明数据和视觉模块完成林境首页还原。 +- 2026-09-23:运行时 seed 已补齐林境 4 个作品、详情规格、联系资料和动态表单;作品、详情与“主理人与我”页面已接入对应数据。API 请求失败不再静默返回不完整的静态 fallback,而是使用同品牌缓存或显示错误状态。待微信开发者工具截图对照静态基准。 +- 2026-09-23:完成业务静态文案审计。林境专属页面的行业标题、履约说明、转化文案和空状态均通过 `brand.visualPresentation` 下发;不再由 WXML 写死。运行时 API 测试与小程序 fixture 已通过,待 7 页截图对照。 +- 2026-09-23:复核数据来源并修复多品牌客户会话。`customer/session/wechat` 现在使用请求中的 `brandSlug`,小程序 token 按品牌缓存;“主理人与我”记录数改为读取客户咨询 API,不再读取不存在的行业专属本地 key。集成测试 30/30、fixture 和 visual-fixture 均通过。 +- 2026-09-23:用户在微信开发者工具确认核心页面显示正常,子任务收口,后续进入全量工程回归。 diff --git a/apps/admin/src/components/ImageUrlField.tsx b/apps/admin/src/components/ImageUrlField.tsx new file mode 100644 index 0000000..a49b4aa --- /dev/null +++ b/apps/admin/src/components/ImageUrlField.tsx @@ -0,0 +1,33 @@ +import { Image, Input, Space, Typography } from "antd"; + +interface ImageUrlFieldProps { + value?: string; + onChange?: (value: string) => void; + placeholder?: string; +} + +export function ImageUrlField({ value, onChange, placeholder }: ImageUrlFieldProps) { + const imageUrl = typeof value === "string" ? value.trim() : ""; + return ( + + onChange?.(event.target.value)} + placeholder={placeholder ?? "粘贴图片地址"} + /> + {imageUrl ? ( + + + 预览图 + + ) : null} + + ); +} diff --git a/apps/admin/src/features/brand/BrandPage.tsx b/apps/admin/src/features/brand/BrandPage.tsx index 87fd8b5..2cdd60a 100644 --- a/apps/admin/src/features/brand/BrandPage.tsx +++ b/apps/admin/src/features/brand/BrandPage.tsx @@ -3,7 +3,13 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import type { BrandProfile } from "@personal-brand/api-client"; import { createApiClient } from "../../lib/api.js"; import { AdminPageHeader } from "../../components/AdminPageHeader.js"; +import { ImageUrlField } from "../../components/ImageUrlField.js"; import { MutationError, QueryState } from "../../components/QueryState.js"; +import { PresentationEditor } from "./PresentationEditor.js"; + +function textValue(value: unknown): string { + return typeof value === "string" ? value : ""; +} export function BrandPage() { const client = createApiClient(); @@ -15,6 +21,10 @@ export function BrandPage() { queryFn: () => client.getPublicTemplate(brand.data!.templateKey), enabled: Boolean(brand.data?.templateKey), }); + const runtime = useQuery({ + queryKey: ["public-runtime-workspace"], + queryFn: () => client.getPublicWorkspace(), + }); const save = useMutation({ mutationFn: (values: Partial) => client.updateAdminBrand(values), onSuccess: () => { @@ -115,13 +125,17 @@ export function BrandPage() { - - + + - - + + @@ -133,6 +147,45 @@ export function BrandPage() { + ; + offerings?: Record; + detail?: Record; + profile?: Record; + inquiry?: Record; + success?: Record; + records?: Record; + }) ?? {}), + }} + runtimeValue={ + runtime.data?.brand + ? { + identity: { + founder: textValue(runtime.data.brand.config?.founder), + title: textValue(runtime.data.brand.config?.title), + slogan: textValue(runtime.data.brand.config?.slogan), + }, + ...((runtime.data.brand.config?.visualPresentation as { + home?: Record; + inquiry?: Record; + profile?: Record; + }) ?? {}), + } + : undefined + } + runtimeLoading={runtime.isLoading} + runtimeError={runtime.error} + /> diff --git a/apps/admin/src/features/brand/PresentationEditor.tsx b/apps/admin/src/features/brand/PresentationEditor.tsx new file mode 100644 index 0000000..9b82b73 --- /dev/null +++ b/apps/admin/src/features/brand/PresentationEditor.tsx @@ -0,0 +1,189 @@ +import { Alert, Button, Card, Col, Form, Input, Row, Space, Typography, message } from "antd"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { useEffect } from "react"; +import { createApiClient } from "../../lib/api.js"; +import { MutationError } from "../../components/QueryState.js"; + +interface PresentationEditorProps { + initialValue: PresentationFormValues; + runtimeValue?: PresentationFormValues | undefined; + runtimeLoading?: boolean | undefined; + runtimeError?: unknown; +} + +type PresentationFormValues = { + identity?: Record; + home?: Record; + offerings?: Record; + detail?: Record; + profile?: Record; + inquiry?: Record; + success?: Record; + records?: Record; +}; + +export function PresentationEditor({ + initialValue, + runtimeValue, + runtimeLoading, + runtimeError, +}: PresentationEditorProps) { + const [form] = Form.useForm(); + const queryClient = useQueryClient(); + const save = useMutation({ + mutationFn: (values: PresentationFormValues) => + createApiClient().updateAdminBrandPresentation(values), + onSuccess: () => { + message.success("页面表达已保存,小程序将使用最新内容"); + void queryClient.invalidateQueries({ queryKey: ["admin-brand"] }); + void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] }); + }, + }); + useEffect(() => { + form.setFieldsValue(initialValue); + }, [form, initialValue]); + + return ( + 普通用户配置} + > + + 这里的内容会显示在小程序中。只填写你希望访客看到的话,不需要理解模板或技术配置。 + + {runtimeLoading ? : null} + {runtimeError ? ( + + ) : runtimeValue ? ( + + + {runtimeValue.identity?.founder || "尚未设置主理人 / 老板姓名"} + + {runtimeValue.identity?.title ? ( + · {runtimeValue.identity.title} + ) : null} + + {runtimeValue.home?.proofTitle || "尚未设置信任介绍标题"} + + + {runtimeValue.inquiry?.subtitle || "尚未设置咨询说明"} + + + 咨询按钮:{runtimeValue.inquiry?.submitLabel || "未设置"} · 记录入口: + {runtimeValue.profile?.recordsTitle || "未设置"} + + + ) : null} +
save.mutate(values)} + > + + + 访客需要先知道是谁在提供服务。这里填写主理人或老板的公开信息。 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ ); +} diff --git a/apps/admin/src/features/publication/PublicationPage.tsx b/apps/admin/src/features/publication/PublicationPage.tsx new file mode 100644 index 0000000..32900bc --- /dev/null +++ b/apps/admin/src/features/publication/PublicationPage.tsx @@ -0,0 +1,382 @@ +import { useState } from "react"; +import { useNavigate } from "react-router-dom"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { + Alert, + Button, + Divider, + Empty, + Input, + Modal, + Select, + Space, + Spin, + Tag, + Typography, + message, +} from "antd"; +import type { BrandTemplateKey } from "@personal-brand/api-client"; +import { createApiClient } from "../../lib/api.js"; +import { AdminPageHeader } from "../../components/AdminPageHeader.js"; +import { MutationError, QueryState } from "../../components/QueryState.js"; + +const client = createApiClient(); + +const destinations: Record = { + brand: "/admin/brand", + positioning: "/admin/brand", + template: "/admin/publication", + visual: "/admin/publication", + offerings: "/admin/services", + forms: "/admin/workspace", + trust: "/admin/trust", +}; + +export function PublicationPage({ canManageTemplate }: { canManageTemplate: boolean }) { + const navigate = useNavigate(); + const queryClient = useQueryClient(); + const [industryTarget, setIndustryTarget] = useState(null); + const [confirmAction, setConfirmAction] = useState<"publish" | "revoke" | null>(null); + const [rollbackVersion, setRollbackVersion] = useState(null); + const [note, setNote] = useState(""); + const brand = useQuery({ + queryKey: ["publication-brand"], + queryFn: () => client.getAdminBrand(), + }); + const workspace = useQuery({ + queryKey: ["publication-workspace"], + queryFn: () => client.getAdminWorkspace(), + }); + const catalog = useQuery({ + queryKey: ["publication-catalog"], + queryFn: () => client.listPublicTemplates(), + }); + const sample = useQuery({ + queryKey: ["publication-sample"], + queryFn: () => client.previewAdminSampleContent(), + enabled: Boolean(workspace.data), + }); + const readiness = useQuery({ + queryKey: ["publication-readiness"], + queryFn: () => client.getAdminReleaseReadiness(), + }); + const releases = useQuery({ + queryKey: ["publication-releases"], + queryFn: () => client.listAdminReleases(), + }); + const refresh = () => { + for (const key of [ + "publication-brand", + "publication-workspace", + "publication-sample", + "publication-readiness", + "publication-releases", + "admin-shell-brand", + "admin-workspace", + "public-runtime-workspace", + ]) { + void queryClient.invalidateQueries({ queryKey: [key] }); + } + }; + const install = useMutation({ + mutationFn: (key: BrandTemplateKey) => client.installAdminTemplate(key), + onSuccess: () => { + setIndustryTarget(null); + message.success("行业模板已安装"); + refresh(); + }, + }); + const selectVisual = useMutation({ + mutationFn: (key: string) => + client.updateAdminBrand({ + config: { ...(brand.data?.config ?? {}), visualTemplateKey: key }, + }), + onSuccess: () => { + message.success("视觉模板已保存到草稿"); + refresh(); + }, + }); + const importSample = useMutation({ + mutationFn: () => client.importAdminSampleContent(), + onSuccess: () => { + message.success("示例内容已导入草稿"); + 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 = + workspace.data?.installations[0]?.templateKey ?? + workspace.data?.brand?.templateKey ?? + brand.data?.templateKey ?? + "personal"; + const visuals = (catalog.data?.visuals ?? []).filter((item) => + item.supportedIndustryTemplates.includes(industryKey), + ); + const visualKey = + typeof brand.data?.config?.visualTemplateKey === "string" + ? brand.data.config.visualTemplateKey + : "linjing-editorial"; + const currentRelease = releases.data?.find((item) => item.status === "published"); + const publishedHistory = (releases.data ?? []).filter( + (item) => item.status === "published" || item.status === "superseded", + ); + const draftOfferings = workspace.data?.offerings.filter((item) => item.isEnabled) ?? []; + const draftForms = (workspace.data?.forms ?? []) as Array<{ + id: string; + name: string; + isEnabled: boolean; + }>; + + return ( + + + +
+ 1. 选择表达方式 + + ({ value: item.key, label: item.name }))} + onChange={(key) => selectVisual.mutate(key)} + /> + {canManageTemplate && ( + + )} + + {workspace.data?.installations.length ? ( + + 当前品牌已安装主模板。模板版本与升级在高级设置中管理。 + + ) : null} + + + + 示例内容 + {sample.isLoading && } + {sample.data && ( + + {sample.data.alreadyImported ? "已导入" : "可导入"} + + )} + + {sample.isError && } + + {sample.isError && ( + + )} + {sample.data && !sample.data.alreadyImported && ( + + 将向草稿添加{" "} + {Object.entries(sample.data.counts) + .map(([key, count]) => `${key} ${count} 项`) + .join("、")} + ;发布前请替换示例文案和图片。 + + )} + +
+ +
+ 2. 核对草稿内容 + + 此处核对的是待发布内容,不是小程序视觉预览。 + + + {brand.data?.name || "未命名品牌"} + {brand.data?.tagline || "尚未填写品牌定位"} + + 已启用业务项:{draftOfferings.map((item) => item.name).join("、") || "无"} + + + 已启用咨询表单: + {draftForms + .filter((item) => item.isEnabled) + .map((item) => item.name) + .join("、") || "无"} + + + + + + + +
+ +
+ 3. 检查并发布 + + + {currentRelease ? `已发布 v${currentRelease.version}` : "尚未发布"} + + + + + {(readiness.data?.checks ?? []).map((check) => ( + + + {check.passed ? "已完成" : "待完善"} + + {check.label} + {!check.passed && ( + + )} + + ))} + + + + {currentRelease && ( + + )} + + + + 发布记录 + {releases.data?.length ? ( + + {releases.data.map((item) => ( + + v{item.version} + {item.status} + + {new Date(item.createdAt).toLocaleString("zh-CN")} + + {item.note && {item.note}} + {item.status === "superseded" && publishedHistory.length > 1 && ( + + )} + + ))} + + ) : ( + + )} + +
+
+ setConfirmAction(null)} + onOk={() => (confirmAction === "revoke" ? revoke.mutate() : publish.mutate())} + confirmLoading={publish.isPending || revoke.isPending} + okText={confirmAction === "revoke" ? "确认撤回" : "确认发布"} + okButtonProps={{ danger: confirmAction === "revoke" }} + > + {confirmAction === "revoke" ? ( + + ) : ( + + 当前草稿将成为品牌新的公开版本。 + setNote(event.target.value)} + placeholder="发布备注(可选)" + maxLength={200} + /> + + )} + + setRollbackVersion(null)} + onOk={() => rollbackVersion !== null && rollback.mutate(rollbackVersion)} + confirmLoading={rollback.isPending} + > + 将 v{rollbackVersion} 重新发布为新版本;当前草稿不会被覆盖。 + + setIndustryTarget(null)} + onOk={() => industryTarget && install.mutate(industryTarget)} + confirmLoading={install.isPending} + > + 模板会更新当前品牌的草稿结构,不会立即改变已发布的小程序。请安装后核对业务内容与视觉模板。 + +
+ ); +} diff --git a/apps/admin/src/features/services/ServicesPage.tsx b/apps/admin/src/features/services/ServicesPage.tsx index a69df4c..cfd4341 100644 --- a/apps/admin/src/features/services/ServicesPage.tsx +++ b/apps/admin/src/features/services/ServicesPage.tsx @@ -4,6 +4,7 @@ import { Form, Input, Modal, + Popconfirm, Select, Space, Table, @@ -16,6 +17,7 @@ import type { Offering } from "@personal-brand/api-client"; import { useState } from "react"; import { createApiClient } from "../../lib/api.js"; import { AdminPageHeader } from "../../components/AdminPageHeader.js"; +import { ImageUrlField } from "../../components/ImageUrlField.js"; import { MutationError, QueryState } from "../../components/QueryState.js"; export function ServicesPage() { @@ -56,16 +58,19 @@ export function ServicesPage() { const beginOffering = (item?: Offering) => { setEditingOffering(item ?? null); setOfferingOpen(true); - const config = item?.config ?? {}; offeringForm.setFieldsValue( item ? { - ...item, - sections: config.sections ?? [], - media: config.media ?? [], - cta: config.cta ?? {}, + kind: item.kind, + name: item.name, + summary: item.summary ?? "", + description: item.description ?? "", + priceText: item.priceText ?? "", + coverUrl: item.coverUrl ?? "", + sortOrder: item.sortOrder, + isEnabled: item.isEnabled, } - : { kind: "service", isEnabled: true, sortOrder: 0, sections: [], media: [], cta: {} }, + : { kind: "service", isEnabled: true, sortOrder: 0 }, ); }; return ( @@ -129,9 +134,17 @@ export function ServicesPage() { > {item.isEnabled ? "禁用" : "启用"} - + deleteOffering.mutate(item.id)} + okText="删除" + cancelText="取消" + > + + ), }, @@ -180,85 +193,22 @@ export function ServicesPage() { - + - - + + - - {(fields, { add, remove }) => ( - <> - - - - {fields.map(({ key, name, ...restField }) => ( - - - - - - - - - - ))} - - )} - - - {(fields, { add, remove }) => ( - <> - - - - {fields.map(({ key, name, ...restField }) => ( - - - - - - - - - - ))} - - )} - - - - - - - + + ({ + value: role, + label: roleLabels[role], + }))} + onChange={(role) => update.mutate({ id: item.id, body: { role } })} + /> + ), + }, + { + title: "状态", + dataIndex: "isEnabled", + render: (value: boolean, item: AdminBrandMember) => ( + + + + + + + + + + + + ({ - value: item.key, - label: item.name, - }))} + options={(templateCatalog.data?.visuals ?? []) + .filter((item) => supportsIndustry(item, previewIndustry)) + .map((item) => ({ value: item.key, label: item.name }))} /> {combinationPreview.isLoading ? ( @@ -490,9 +537,7 @@ export function WorkspacePage() { const value = field as Record; return { ...value, - ...(Array.isArray(value.options) - ? { optionsText: JSON.stringify(value.options) } - : {}), + optionsText: optionsToText(value.options), }; }), }); @@ -692,15 +737,11 @@ export function WorkspacePage() { : [] ).map((field) => { const item = field as Record; - if (typeof item.optionsText !== "string") return item; - try { - const options = JSON.parse(item.optionsText) as unknown; - const { optionsText, ...rest } = item; - void optionsText; - return { ...rest, options }; - } catch { - return item; - } + const { optionsText, ...rest } = item; + const type = typeof rest.type === "string" ? rest.type : "text"; + return ["select", "radio", "multi-select"].includes(type) + ? { ...rest, options: optionsFromText(optionsText) } + : rest; }), }; if (editingForm) updateForm.mutate({ id: editingForm.id, body }); @@ -738,47 +779,70 @@ export function WorkspacePage() { {(fields, { add, remove }) => ( <> - + {fields.map(({ key, name, ...restField }) => ( - - - - - - - - - + + + + + + + + + {({ getFieldValue }) => - ["select", "radio"].includes( + ["select", "radio", "multi-select"].includes( String(getFieldValue(["fieldsSnapshot", name, "type"])), ) ? ( - - + + ) : null } - - +
))} )} diff --git a/apps/admin/src/main.tsx b/apps/admin/src/main.tsx index 75a0d19..d3d0775 100644 --- a/apps/admin/src/main.tsx +++ b/apps/admin/src/main.tsx @@ -49,13 +49,27 @@ const FeatureCapabilitiesPage = React.lazy(() => 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"; const queryClient = new QueryClient(); const api = createApiClient; -function Login({ onLogin }: { onLogin: () => void }) { +function Login({ + onLogin, +}: { + onLogin: (session: { role: string; mustChangePassword: boolean }) => void; +}) { const [form] = Form.useForm(); const [loading, setLoading] = useState(false); async function submit(values: { username: string; password: string }) { @@ -63,7 +77,9 @@ function Login({ onLogin }: { onLogin: () => void }) { try { const result = await api().loginAdmin(values.username, values.password); localStorage.setItem("adminToken", result.token); - onLogin(); + localStorage.setItem("adminRole", result.role); + localStorage.setItem("adminMustChangePassword", String(result.mustChangePassword)); + onLogin(result); } catch (error) { message.error(error instanceof Error ? error.message : "登录失败"); } finally { @@ -87,7 +103,60 @@ function Login({ onLogin }: { onLogin: () => void }) { ); } -function Dashboard({ onLogout }: { onLogout: () => void }) { +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 ( + + 请先设置只有你本人知道的新密码。 +
+ + + + + + + + + + +
+
+ ); +} + +function Dashboard({ onLogout, role }: { onLogout: () => void; role: string }) { const navigate = useNavigate(); const location = useLocation(); const brand = useQuery({ @@ -109,13 +178,31 @@ function Dashboard({ onLogout }: { onLogout: () => void }) { }; const page = location.pathname.split("/")[2] || "overview"; const items = [ - { key: "overview", label: "当前品牌概览" }, - { key: "brand", label: "当前品牌表达" }, - { key: "trust", label: "信任内容" }, - { key: "services", label: "业务提供项" }, - { key: "workspace", label: "模板与设置" }, - { key: "capabilities", label: "能力插件" }, - { key: "inquiries", label: "咨询记录" }, + { + 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" + ? [] + : [ + { + type: "group" as const, + label: "系统管理", + children: [ + { key: "workspace", label: "模板与设置" }, + { key: "capabilities", label: "能力插件" }, + { key: "members", label: "团队成员" }, + ], + }, + ]), ]; return ( @@ -163,9 +250,20 @@ function Dashboard({ onLogout }: { onLogout: () => void }) { }> } /> + } + /> } /> - } /> - } /> + {role === "editor" ? null : ( + } /> + )} + {role === "editor" ? null : ( + } /> + )} + {role === "editor" ? null : ( + } /> + )} } /> } /> } /> @@ -180,6 +278,10 @@ function Dashboard({ onLogout }: { onLogout: () => void }) { 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("登录状态已失效,请重新登录"); @@ -190,9 +292,22 @@ function Root() { }, []); const logout = () => { localStorage.removeItem("adminToken"); + localStorage.removeItem("adminRole"); + localStorage.removeItem("adminMustChangePassword"); setLoggedIn(false); }; - return loggedIn ? : setLoggedIn(true)} />; + if (!loggedIn) + return ( + { + setRole(session.role); + setMustChangePassword(session.mustChangePassword); + setLoggedIn(true); + }} + /> + ); + if (mustChangePassword) return setMustChangePassword(false)} />; + return ; } createRoot(document.getElementById("app")!).render( diff --git a/apps/api/package.json b/apps/api/package.json index 48fa8d1..386998b 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -8,7 +8,7 @@ "lint": "eslint .", "typecheck": "tsc -p tsconfig.json --noEmit", "test": "tsx --test test/**/*.test.ts", - "test:integration": "pnpm build && NODE_ENV=test node --env-file=.env --test test/http.integration.test.js", + "test:integration": "pnpm build && node --env-file=.env test/run-integration.cjs", "clean": "rimraf dist", "start": "node dist/main.js", "db:generate": "prisma generate", diff --git a/apps/api/prisma/migrations/20260924090000_add_admin_password_state/migration.sql b/apps/api/prisma/migrations/20260924090000_add_admin_password_state/migration.sql new file mode 100644 index 0000000..e6df189 --- /dev/null +++ b/apps/api/prisma/migrations/20260924090000_add_admin_password_state/migration.sql @@ -0,0 +1 @@ +ALTER TABLE "AdminUser" ADD COLUMN "mustChangePassword" BOOLEAN NOT NULL DEFAULT false; diff --git a/apps/api/prisma/migrations/20260924100000_add_brand_releases/migration.sql b/apps/api/prisma/migrations/20260924100000_add_brand_releases/migration.sql new file mode 100644 index 0000000..eb2a61e --- /dev/null +++ b/apps/api/prisma/migrations/20260924100000_add_brand_releases/migration.sql @@ -0,0 +1,16 @@ +CREATE TABLE "BrandRelease" ( + "id" TEXT NOT NULL, + "brandId" TEXT NOT NULL, + "version" INTEGER NOT NULL, + "status" TEXT NOT NULL DEFAULT 'published', + "snapshot" JSONB NOT NULL, + "actorId" TEXT NOT NULL, + "note" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "revokedAt" TIMESTAMP(3), + CONSTRAINT "BrandRelease_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "BrandRelease_brandId_version_key" ON "BrandRelease"("brandId", "version"); +CREATE INDEX "BrandRelease_brandId_status_createdAt_idx" ON "BrandRelease"("brandId", "status", "createdAt"); +ALTER TABLE "BrandRelease" ADD CONSTRAINT "BrandRelease_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/api/prisma/migrations/20260924120000_add_release_revocation_actor/migration.sql b/apps/api/prisma/migrations/20260924120000_add_release_revocation_actor/migration.sql new file mode 100644 index 0000000..6e7d08c --- /dev/null +++ b/apps/api/prisma/migrations/20260924120000_add_release_revocation_actor/migration.sql @@ -0,0 +1 @@ +ALTER TABLE "BrandRelease" ADD COLUMN "revokedBy" TEXT; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 3ad6468..9422538 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -62,6 +62,23 @@ model BrandProfile { capabilityInstallations CapabilityInstallation[] capabilityAuditLogs CapabilityAuditLog[] adminMemberships BrandMembership[] + releases BrandRelease[] +} + +model BrandRelease { + id String @id @default(uuid()) + brandId String + brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade) + version Int + status String @default("published") + snapshot Json + actorId String + note String? + createdAt DateTime @default(now()) + revokedAt DateTime? + revokedBy String? + @@unique([brandId, version]) + @@index([brandId, status, createdAt]) } model CapabilityInstallation { @@ -328,6 +345,7 @@ model AdminUser { displayName String role String @default("admin") isEnabled Boolean @default(true) + mustChangePassword Boolean @default(false) lastLoginAt DateTime? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt diff --git a/apps/api/prisma/seed.ts b/apps/api/prisma/seed.ts index 98826be..a7d1239 100644 --- a/apps/api/prisma/seed.ts +++ b/apps/api/prisma/seed.ts @@ -1,5 +1,6 @@ import { PrismaClient } from "@prisma/client"; import bcrypt from "bcryptjs"; +import { buildBrandReleaseSnapshot } from "../src/brand-release.service.js"; const prisma = new PrismaClient(); @@ -14,47 +15,660 @@ const runtimeImages = { "https://images.unsplash.com/photo-1603133872878-684f208fb84b?auto=format&fit=crop&w=1000&q=85", "https://images.unsplash.com/photo-1559847844-5315695dadae?auto=format&fit=crop&w=1000&q=85", ], + personal: [ + "https://images.unsplash.com/photo-1556761175-b413da4baf72?auto=format&fit=crop&w=1000&q=85", + "https://images.unsplash.com/photo-1521737711867-e3b97375f902?auto=format&fit=crop&w=1000&q=85", + ], }; -async function ensureRuntimeContent( - brandId: string, - templateKey: "food" | "doors", - offerings: Array<{ name: string; summary: string; image: string; categoryKey: string }>, -): Promise { +type OfferingKind = "service" | "product" | "package" | "subscription"; + +interface RuntimeSeedTemplate { + brandConfig: Record; + retiredOfferingNames?: string[]; + offerings: Array<{ + name: string; + summary: string; + image: string; + kind: OfferingKind; + priceText?: string; + priceAmount?: number; + config: Record; + }>; + trustContent: Array<{ + type: string; + title: string; + content: string; + config?: Record; + }>; + inquiryForm: { name: string; fieldsSnapshot: Array> }; +} + +const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTemplate> = { + personal: { + brandConfig: { + visualTemplateKey: "linjing-editorial", + founder: "林然", + title: "品牌策略顾问", + slogan: "用清晰的定位与可执行的表达,让专业被看见。", + phone: "13900000003", + wechat: "linran-brand", + studioAddress: "上海市徐汇区创意园区", + heroImage: runtimeImages.personal[0], + visualPresentation: { + home: { + proofEyebrow: "专业经验与合作成果", + manifestoEyebrow: "工作原则", + manifestoTitle: "先厘清问题,再设计表达", + worksEyebrow: "合作方式", + worksTitle: "品牌策略与顾问服务", + worksAction: "查看全部 →", + flowEyebrow: "合作流程", + flowTitle: "从诊断到持续落地", + }, + offerings: { + title: "合作方式", + subtitle: "围绕品牌定位、表达与业务转化,选择适合当前阶段的支持。", + materialLabel: "服务内容:", + hardwareLabel: "合作重点:", + detailAction: "查看服务详情 →", + inquiryAction: "发起合作咨询", + }, + detail: { + priceLabel: "服务参考", + spaceLabel: "适合阶段", + backgroundTitle: "服务背景", + conceptTitle: "工作方法", + craftsTitle: "交付内容", + materialsTitle: "合作说明", + inquiryAction: "发起合作咨询", + inquiryHint: "提交信息后由主理人与您沟通。", + }, + profile: { + phoneLabel: "联系电话", + wechatLabel: "微信", + addressLabel: "工作地点", + callAction: "呼叫", + copyAction: "复制", + recordsTitle: "我的咨询记录", + recordsCountUnit: "条记录", + }, + inquiry: { + eyebrow: "COLLABORATION", + title: "合作咨询", + subtitle: "留下你的品牌现状与目标,主理人会尽快联系。", + submitLabel: "提交合作需求", + }, + success: { + eyebrow: "COLLABORATION", + title: "已收到你的咨询", + intro: "主理人会尽快与你联系。", + recordsAction: "查看咨询记录", + homeAction: "返回首页", + }, + records: { + title: "我的咨询记录", + createAction: "新增咨询", + emptyTitle: "还没有咨询记录", + emptyDescription: "提交一次咨询,开始与你的主理人沟通。", + emptyAction: "开始咨询", + }, + }, + }, + offerings: [ + { + name: "品牌定位诊断", + summary: "梳理现有表达、目标客户与业务优先级,形成清晰的下一步行动建议。", + image: runtimeImages.personal[0], + kind: "service", + config: { + categoryKey: "consulting", + categoryLabel: "策略咨询", + keywords: ["定位", "诊断", "表达"], + }, + }, + { + name: "个人品牌年度顾问", + summary: "持续支持内容策略、产品表达与关键节点决策,建立长期信任资产。", + image: runtimeImages.personal[1], + kind: "subscription", + config: { + categoryKey: "advisory", + categoryLabel: "长期顾问", + keywords: ["陪跑", "内容", "转化"], + }, + }, + ], + trustContent: [ + { + type: "profile", + title: "关于林然", + content: "专注帮助专业服务者建立可信、清晰且能带来合作的个人品牌表达。", + }, + { + type: "process", + title: "合作方法", + content: "诊断现状、明确定位、搭建表达、持续复盘,让每一步都服务于真实业务。", + }, + ], + inquiryForm: { + name: "品牌合作咨询", + fieldsSnapshot: [ + { key: "name", label: "您的称呼", type: "text", required: true }, + { key: "phone", label: "联系电话", type: "phone", required: true }, + { key: "remark", label: "目前的品牌或业务问题", type: "textarea", required: true }, + ], + }, + }, + food: { + brandConfig: { + visualTemplateKey: "acheng-campus-food", + founder: "阿成", + title: "私房菜主理人", + slogan: "认真做好每一顿家常饭。", + phone: "", + wechat: "", + studioAddress: "大学城生活区东门附近", + heroImage: runtimeImages.food[0], + visualPresentation: { + home: { + proofEyebrow: "主理人信任凭证", + manifestoEyebrow: "品牌坚持", + manifestoTitle: "认真对待每一次托付", + worksEyebrow: "今日餐品与预订", + worksTitle: "套餐、聚餐与定制餐", + worksAction: "查看全部 →", + flowEyebrow: "预订流程", + flowTitle: "从预订到取餐", + }, + offerings: { + title: "今日套餐与定制餐", + subtitle: "现做套餐、聚餐预订和定制餐品。", + materialLabel: "餐品说明:", + hardwareLabel: "预订要点:", + detailAction: "查看餐品 →", + inquiryAction: "咨询 / 提前预订", + }, + detail: { + priceLabel: "参考价格", + spaceLabel: "适合场景", + backgroundTitle: "餐品说明", + conceptTitle: "口味与分量", + craftsTitle: "制作方式", + materialsTitle: "食材与搭配", + inquiryAction: "咨询 / 提前预订", + inquiryHint: "提交后由主理人与您确认餐品和时间。", + }, + profile: { + phoneLabel: "联系电话", + wechatLabel: "微信", + addressLabel: "服务地址", + callAction: "呼叫", + copyAction: "复制", + recordsTitle: "我的咨询记录", + recordsCountUnit: "条记录", + }, + inquiry: { + eyebrow: "CONSULTATION", + title: "餐品预订与定制", + subtitle: "提交信息后由主理人与您确认时间和需求。", + submitLabel: "提交预订需求", + }, + success: { + eyebrow: "CONSULTATION", + title: "已收到你的预订需求", + intro: "主理人会尽快与你确认。", + recordsAction: "查看咨询记录", + homeAction: "返回首页", + }, + records: { + title: "我的预订记录", + createAction: "新增预订", + emptyTitle: "还没有预订记录", + emptyDescription: "提交一次预订需求,开始确认餐品与时间。", + emptyAction: "开始预订", + }, + }, + }, + offerings: [ + { + name: "红烧肉双拼套餐", + summary: "红烧肉、时蔬、米饭", + image: runtimeImages.food[0], + kind: "package", + priceAmount: 2800, + config: { + categoryKey: "set-meal", + categoryLabel: "套餐", + keywords: ["现做", "家常", "定制"], + }, + }, + { + name: "小炒鸡套餐", + summary: "现炒鸡块、时蔬、米饭", + image: runtimeImages.food[1], + kind: "package", + priceAmount: 3200, + config: { + categoryKey: "set-meal", + categoryLabel: "套餐", + keywords: ["现做", "家常", "定制"], + }, + }, + { + name: "家庭聚餐私厨", + summary: "根据人数、地点和口味人工沟通报价", + image: runtimeImages.food[2], + kind: "service", + config: { + categoryKey: "private-chef", + categoryLabel: "私厨", + keywords: ["现做", "家常", "定制"], + }, + }, + ], + trustContent: [ + { type: "profile", title: "关于阿成", content: "每天认真做好一顿家常饭。" }, + { + type: "process", + title: "认真做饭的流程", + content: "提前准备食材,现做现出餐,认真沟通每一次需求。", + }, + ], + inquiryForm: { + name: "家庭聚餐咨询", + fieldsSnapshot: [ + { key: "name", label: "您的称呼", type: "text", required: true }, + { key: "phone", label: "联系电话", type: "phone", required: true }, + { key: "remark", label: "需求说明", type: "textarea", required: false }, + ], + }, + }, + doors: { + retiredOfferingNames: ["别墅入户大门", "院门与围合系统", "室内户内门系统"], + brandConfig: { + visualTemplateKey: "linjing-editorial", + founder: "林叙安 (Lin XUAN)", + title: "高端门系统建筑研造主理人", + slogan: "为当代别墅空间,定制有秩序感与呼吸感的门", + phone: "186-0218-9908", + wechat: "LIN-ATELIER-2024", + studioAddress: "上海市静安区威海路设计中心 A 座 / 杭州良渚研造工坊", + avatarUrl: + "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?auto=format&fit=crop&w=240&h=240&q=80", + profilePresentation: { + coverage: [ + { + title: "直派核心圈", + content: + "上海、杭州、宁波、苏州、无锡、南京及深圳、广州。主理人及资深装配总工亲赴现场。", + }, + { + title: "全国其他城市私邸", + content: "接受建筑设计师联合委托,安排远程 3D 激光测绘支持与专用物流直运安装。", + }, + ], + warranty: [ + "门体内部防变形航空合金骨架承诺 10 年结构质保;", + "重型天地轴、进口地弹簧及磁吸五金 5 年免费维护;", + "每樘门出厂前进行 5000 次启闭校正;", + "原木天然肌理享有首年 2 次木蜡油保养服务。", + ], + }, + visualPresentation: { + home: { + founderBadge: "亲自主理量房", + proofEyebrow: "主理人工艺与信任凭证", + proofTitle: "14 年,只做门与空间的关系", + manifestoEyebrow: "林境门作品质宣言", + manifestoTitle: "拒绝流水线拼装", + worksEyebrow: "SELECTED WORKS", + worksTitle: "精选门系统作品", + worksAction: "查看全部 →", + flowEyebrow: "全程一对一跟进", + flowTitle: "主理人私享定制流程", + }, + offerings: { + title: "作品与系统", + subtitle: "每一扇门,都是建筑秩序的一部分。", + materialLabel: "主材构成:", + hardwareLabel: "核心五金:", + detailAction: "查看工艺详案 →", + inquiryAction: "咨询此类定制", + }, + detail: { + priceLabel: "参考定制造价", + spaceLabel: "适用空间", + backgroundTitle: "项目背景与空间诉求", + conceptTitle: "构造深化设计理念", + craftsTitle: "节点工艺考究", + materialsTitle: "选型物料与五金规格", + inquiryAction: "预约上门测量 / 咨询此类方案", + inquiryHint: "预约后由主理人进行点对点方案分析", + }, + profile: { + phoneLabel: "专线电话", + wechatLabel: "工作室微信", + addressLabel: "实体工坊", + callAction: "呼叫", + copyAction: "复制", + recordsCountUnit: "条记录", + recordsTitle: "我的量房与定制咨询", + recordsSubtitle: "追踪主理人出图进度与现场勘测排期", + coverageTitle: "直派服务区域与履约说明", + warrantyTitle: "一门一档 · 终生质保规约", + }, + inquiry: { + eyebrow: "私人执业研造服务", + title: "高端门系统定制 · 私享测量预约", + subtitle: "主理人林叙安亲自沟通,72 小时内提供空间门体构想分析。", + submitLabel: "提交量房与定制评估需求", + }, + success: { + eyebrow: "PRIVATE CONSULTATION", + title: "已收到你的咨询", + intro: "主理人会根据你的项目资料,整理初步判断并在 1 个工作日内与你联系。", + recordsAction: "查看咨询记录", + homeAction: "返回首页", + }, + records: { + title: "我的咨询记录", + createAction: "+ 新增预约", + emptyTitle: "还没有咨询记录", + emptyDescription: "预约一次私享沟通,让我们从你的空间开始。", + emptyAction: "开始咨询", + }, + }, + heroImage: runtimeImages.doors[0], + homeHero: { + eyebrow: "年度落成实景 · 莫干山庄园", + title: "万籁系列 · 铸铜冷锻双轴入户门", + slogan: "门高 3.4m · 德国静音地轴", + cta: "探索全系作品 →", + }, + }, + offerings: [ + { + name: "当代铸铜木核防暴装甲门", + summary: + "项目位于浙北山间独栋庄园,业主需要一扇兼具当代东方仪式感与长期耐候能力的入户大门。", + image: runtimeImages.doors[0], + kind: "product", + priceText: "¥38,000 - ¥85,000 / 樘", + config: { + categoryKey: "entrance-door", + categoryLabel: "入户大门", + series: "「万籁」重型天地轴入户系统", + tag: "主理人年度代表作", + area: "浙江·莫干山私家山庄", + detailHero: runtimeImages.doors[0], + woodMaterial: "60mm 北美特级黑胡桃整板 + 航空蜂窝铝芯", + hardware: "德国 dormakaba 重型地弹簧 + 自主定制实心锻铜一体式长执手", + spaceType: "独栋别墅建筑主入口 / 挑高大厅玄关", + keywords: ["厚重大气", "隐式天地轴", "隔音 42dB", "抗暴防撬"], + details: { + background: + "项目位于浙北山间独栋庄园,常年多雨潮湿,且冬季山风冷峻。业主期望一扇既有古典厚重仪式感,又能抵御风雨、长久耐候的当代东方大门。", + designConcept: + "提炼江南屋檐与青砖比例。以暗调冷锻手工铜板包裹耐候钢核,内衬大厚度吸音绝热芯,门体内嵌隐藏式天地承重轴,推拉阻尼丝滑沉稳。", + crafts: [ + "无缝冷锻铜边框,经自然氧化着色", + "双道三元乙丙航天级发泡密封胶条,气密性达国标 8 级", + "指纹识别模组隐于天然胡桃木纹理深处", + ], + materialsList: [ + { name: "门扇主体", spec: "航空铝蜂窝 + 防暴钢板 + 黑胡桃" }, + { name: "承重结构", spec: "不锈钢重型天地偏心轴(承重 600KG)" }, + { name: "五金执手", spec: "实心黄铜拉丝防指纹覆膜" }, + { name: "锁具系统", spec: "C 级多向防暴机械锁芯 + 隐匿式生物辨识" }, + ], + }, + }, + }, + { + name: "悬挑风琴式耐候双开院门", + summary: "以柚木条与耐候钢构建视线遮蔽和透光的微妙平衡,适配长期日晒雨淋的私家庭院入口。", + image: runtimeImages.doors[1], + kind: "product", + priceText: "¥42,000 - ¥98,000 / 樘", + config: { + categoryKey: "garden-door", + categoryLabel: "庭院围墙门", + series: "「虚实」透光私家庭院门", + tag: "建筑级耐候工艺", + area: "上海·佘山高尔夫别墅", + detailHero: runtimeImages.doors[1], + woodMaterial: "深浸缅甸柚木条格栅 + 氟碳喷涂耐候钢", + hardware: "意大利全隐形地埋式液压自闭器 + 静音电控锁", + spaceType: "私家庭院入口 / 围墙园林玄关", + keywords: ["园林意境", "格栅光影", "耐候耐蚀", "智能对讲协同"], + details: { + background: + "庭院门直面自然日晒雨淋,普通木门易开裂变形,普通铁艺门几年内斑驳锈蚀。本案要求长期免维护的高级自然质感。", + designConcept: + "利用竖向错落的柚木条构建视线遮蔽与透光的微妙平衡,内部向外望去如薄纱透竹。", + crafts: [ + "微隙热胀冷缩结构槽设计", + "隐蔽式水路导流坡口", + "院墙铰链锚栓深入混凝土柱芯 300mm", + ], + materialsList: [ + { name: "户外木种", spec: "高油脂老料缅甸柚木,经过 180 天自然风干" }, + { name: "骨架型材", spec: "4mm 高强度航空铝镁合金" }, + { name: "智能五金", spec: "隐藏式地下闭门轴,支持远程授权" }, + ], + }, + }, + }, + { + name: "通顶极窄边框实木室内门", + summary: "以 2.8m - 3.2m 满高通顶系统维持私宅空间的建筑平直感,并与木作一体深化。", + image: runtimeImages.doors[2], + kind: "product", + priceText: "¥7,800 - ¥16,000 / 樘", + config: { + categoryKey: "interior-door", + categoryLabel: "室内户内门", + series: "「空灵」2.8m - 3.2m 满高通顶系统", + tag: "极简建筑平直感", + area: "江苏·苏州金鸡湖独栋", + detailHero: runtimeImages.doors[2], + woodMaterial: "天然白栓木拉丝烟熏木饰面 + 磁吸阻尼降噪", + hardware: "意大利 AGB 磁吸静音门锁 + 隐藏式暗铰链", + spaceType: "别墅主卧套房 / 私人藏书阁 / 视听室", + keywords: ["满高通顶", "磁吸静音", "极窄边框", "与木作同色"], + details: { + background: + "室内多道门如果尺寸矮小杂乱,会切割私宅的建筑开阔感。业主希望主卧区实现门与护墙板毫无色差、绝对平齐。", + designConcept: "门扇高 3.1 米一通到顶,无传统上门套与压边;内嵌双向碳纤维抗弯龙骨。", + crafts: [ + "门框与墙体批荡层融为一体的无框反装工艺", + "磁力吸舌落锁轻无声息", + "同批原木切片保证纹理与护墙板连贯", + ], + materialsList: [ + { name: "抗弯核心", spec: "双组份碳纤维预应力防变形拉力杆" }, + { name: "吸音内衬", spec: "德国均质空心桥洞力学板" }, + { name: "隐形铰链", spec: "德国 KRONA 三维可调隐形铰链" }, + ], + }, + }, + }, + { + name: "石材及皮质背景墙一体门", + summary: "将门体与背景墙材料、纹理和收口一体深化,保留私宅完整的墙面秩序。", + image: + "https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?auto=format&fit=crop&w=1000&q=85", + kind: "product", + priceText: "¥18,000 - ¥36,000 / 樘", + config: { + categoryKey: "stealth-door", + categoryLabel: "装饰隐形门", + series: "「无垠」密室及背景墙融合门", + tag: "精密收口工程", + area: "广东·深圳香蜜湖一号", + detailHero: + "https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?auto=format&fit=crop&w=1000&q=85", + woodMaterial: "3mm 超薄大理石复合蜂窝板 / 进口鞍革手工双缝线", + hardware: "感应式电动自开闭装置或碰珠反弹器", + spaceType: "雪茄室 / 私人金库 / 地下酒窖 / 视听隐藏储物区", + keywords: ["视线隐形", "超薄岩板", "毫厘对缝", "无门把设计"], + details: { + background: + "客厅背景墙长达 9 米,中间有一道通往主人密闭酒窖的通道,突兀开门会破坏整面奢石的连贯韵律。", + designConcept: "将奢石切割对纹复合于高刚性合金门扇表面,缝隙控制在 1.5mm 以内。", + crafts: [ + "石材水刀无应力薄切与航空蜂窝背栓复合", + "脚踏地砖预埋重力复位转轴", + "支持指纹电控联动隐藏灯带", + ], + materialsList: [ + { name: "表面饰材", spec: "意大利雪山银狐超薄天然大理石" }, + { name: "驱动系统", spec: "低噪步进电机伺服闭门器" }, + ], + }, + }, + }, + ], + trustContent: [ + { + type: "profile", + title: "主理人的门作观", + content: + "国家注册高级室内建筑师,专注高定大门及私宅空间门类系统研发 14 年。拒绝建材量产拼装,以门与空间同构的建筑理念,亲自主理选材、构造深化与落地试装。", + config: { + stats: [ + { value: "14年", label: "高端门系深化经验", sub: "历经百项严苛私宅考验" }, + { value: "260+", label: "落地庄园实景案例", sub: "全实景图库,可预约探访" }, + { value: "100%", label: "主理人全案跟进", sub: "量房 / 出图 / 选料 / 试装" }, + { value: "10年", label: "结构主轴质保承诺", sub: "终生五金润滑维保机制" }, + ], + pillars: [ + { + icon: "tree", + title: "天然厚板与古铜锻打", + desc: "精选 300 年北美黑胡桃、缅甸柚木直拼大板,搭配手工冷锻紫铜及意大利防爆钢核。", + }, + { + icon: "ruler", + title: "微米级红外高精量房", + desc: "德国进口 3D 空间激光扫描,精准捕捉门洞沉降公差与建筑墙体垂直度。", + }, + { + icon: "shield", + title: "隐匿式重型五金系统", + desc: "自主研发三维可调静音承重铰链,单扇承载 450kg,开合轻盈安静。", + }, + ], + serviceFlow: [ + { step: "01", name: "私享沟通", desc: "厘清生活动线与风候环境" }, + { step: "02", name: "上门实测", desc: "复核门洞公差与地平基准" }, + { step: "03", name: "构造出图", desc: "输出结构图与材质节点方案" }, + { step: "04", name: "实样工坊确认", desc: "确认木样、锻铜样与密封节点" }, + { step: "05", name: "工坊试装交付", desc: "试装调试后专车直运现场" }, + { step: "06", name: "终生私属维护", desc: "建立一门一档数字化档案" }, + ], + }, + }, + { + type: "portfolio", + title: "别墅门系统案例", + content: "围绕入户、庭院和室内空间建立完整门系统。", + }, + { + type: "process", + title: "从测量到交付", + content: "现场测量、方案沟通、深化确认和落地交付。", + }, + ], + inquiryForm: { + name: "门系统方案咨询", + fieldsSnapshot: [ + { + key: "doorType", + label: "期望定制的门类型", + type: "select", + required: true, + options: [ + "入户大门(防暴铸铜 / 实木)", + "庭院围墙门(耐候格栅 / 对开)", + "全屋室内门系统(通顶隐形)", + "背景墙一体门 / 密室门", + "整栋别墅门系统全案一体化", + ], + }, + { key: "cityArea", label: "房屋 / 别墅所在城市与楼盘", type: "text", required: true }, + { + key: "projectStage", + label: "当前项目阶段", + type: "radio", + required: true, + options: [ + "土建结构阶段(适合预埋加固)", + "水电木工阶段(适合精确测距)", + "硬装收尾阶段", + "旧宅门体翻新改造", + ], + }, + { + key: "budgetRange", + label: "预估门系统投资预算", + type: "select", + required: false, + options: [ + "5 万 - 10 万", + "10 万 - 20 万", + "20 万 - 50 万(全宅全案)", + "50 万以上(顶级孤品定制)", + ], + }, + { + key: "needMeasure", + label: "是否需要主理人上门现场量房", + type: "radio", + required: true, + options: ["需要(预约排期现场勘测)", "暂不需要(先发图纸在线深化评估)"], + }, + { key: "contactName", label: "贵姓称谓", type: "text", required: true }, + { key: "contactPhone", label: "联系手机号(微信同号)", type: "tel", required: true }, + { key: "specialNote", label: "空间想法或特殊需求描述", type: "textarea", required: false }, + ], + }, + }, +}; + +async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTemplate): Promise { await prisma.brandProfile.update({ where: { id: brandId }, data: { - config: { - founder: templateKey === "doors" ? "林境主理人" : "阿成", - title: templateKey === "doors" ? "别墅门系统设计顾问" : "私房菜主理人", - slogan: - templateKey === "doors" ? "让每一扇门,成为建筑秩序的开始。" : "认真做好每一顿家常饭。", - phone: templateKey === "doors" ? "13800000000" : "", - wechat: templateKey === "doors" ? "linjing-doors" : "", - studioAddress: templateKey === "doors" ? "城市设计中心 3F" : "大学城生活区东门附近", - heroImage: runtimeImages[templateKey][0], - }, + config: template.brandConfig, }, }); - for (const [sortOrder, item] of offerings.entries()) { + for (const [sortOrder, item] of template.offerings.entries()) { const offering = await prisma.offering.findUnique({ where: { brandId_name: { brandId, name: item.name } }, }); - if (!offering) continue; - await prisma.offering.update({ - where: { id: offering.id }, - data: { - coverUrl: item.image, - summary: item.summary, - sortOrder: sortOrder + 1, - isEnabled: true, - config: { - categoryKey: item.categoryKey, - keywords: templateKey === "doors" ? ["定制", "别墅", "门系统"] : ["现做", "家常", "定制"], - media: [{ url: item.image, alt: item.name, type: "image" }], - sections: [], - }, + const data = { + kind: item.kind, + coverUrl: item.image, + summary: item.summary, + priceText: item.priceText ?? "沟通报价", + ...(item.priceAmount === undefined ? {} : { priceAmount: item.priceAmount }), + sortOrder: sortOrder + 1, + isEnabled: true, + config: { + ...item.config, + media: [{ url: item.image, alt: item.name, type: "image" }], + sections: [], }, + }; + if (offering) await prisma.offering.update({ where: { id: offering.id }, data }); + else await prisma.offering.create({ data: { brandId, name: item.name, ...data } }); + } + if (template.retiredOfferingNames?.length) { + await prisma.offering.updateMany({ + where: { brandId, name: { in: template.retiredOfferingNames } }, + data: { isEnabled: false }, }); } const moduleDefinitions = [ @@ -82,67 +696,74 @@ async function ensureRuntimeContent( select: { id: true, name: true }, }); for (const [index, item] of incompleteOfferings.entries()) { - const image = runtimeImages[templateKey][index % runtimeImages[templateKey].length]; + const image = template.offerings[index % template.offerings.length].image; await prisma.offering.update({ where: { id: item.id }, data: { coverUrl: image, config: { categoryKey: "custom", - keywords: templateKey === "doors" ? ["定制", "门系统"] : ["家常", "定制"], + categoryLabel: "自定义业务", + keywords: [], media: [{ url: image, alt: item.name, type: "image" }], sections: [], }, }, }); } - const trustCount = await prisma.trustContent.count({ where: { brandId } }); - if (!trustCount) { - const trustItems = - templateKey === "doors" - ? [ - ["profile", "主理人的门作观", "从建筑关系出发,认真处理每一扇门。"], - ["portfolio", "别墅门系统案例", "围绕入户、庭院和室内空间建立完整门系统。"], - ["process", "从测量到交付", "现场测量、方案沟通、深化确认和落地交付。"], - ] - : [ - ["profile", "关于阿成", "每天认真做好一顿家常饭。"], - ["process", "认真做饭的流程", "提前准备食材,现做现出餐,认真沟通每一次需求。"], - ]; - await prisma.trustContent.createMany({ - data: trustItems.map(([type, title, content], sortOrder) => ({ - brandId, - type, - title, - content, - sortOrder, - isPublished: true, - })), - }); - } - const formCount = await prisma.inquiryForm.count({ where: { brandId } }); - if (!formCount) { - await prisma.inquiryForm.create({ - data: { - brandId, - name: templateKey === "doors" ? "门系统方案咨询" : "家庭聚餐咨询", - purpose: "inquiry", - targetType: "brand", - submissionAction: "create-inquiry", - fieldsSnapshot: [ - { key: "name", label: "您的称呼", type: "text", required: true }, - { key: "phone", label: "联系电话", type: "phone", required: true }, - { key: "remark", label: "需求说明", type: "textarea", required: false }, - ], - }, + for (const [sortOrder, item] of template.trustContent.entries()) { + const existing = await prisma.trustContent.findFirst({ + where: { brandId, type: item.type, title: item.title }, }); + const data = { ...item, brandId, sortOrder, isPublished: true }; + if (existing) await prisma.trustContent.update({ where: { id: existing.id }, data }); + else await prisma.trustContent.create({ data }); } + const existingForm = await prisma.inquiryForm.findFirst({ + where: { brandId, targetType: "brand" }, + orderBy: { createdAt: "asc" }, + }); + const formData = { + name: template.inquiryForm.name, + purpose: "inquiry", + targetType: "brand", + submissionAction: "create-inquiry", + fieldsSnapshot: template.inquiryForm.fieldsSnapshot, + isEnabled: true, + } as const; + if (existingForm) + await prisma.inquiryForm.update({ where: { id: existingForm.id }, data: formData }); + else await prisma.inquiryForm.create({ data: { brandId, ...formData } }); +} + +async function ensureSeedRelease(brandId: string, actorId: string): Promise { + const snapshot = await buildBrandReleaseSnapshot(prisma, brandId); + await prisma.brandRelease.deleteMany({ where: { brandId } }); + await prisma.brandRelease.create({ + data: { + brandId, + version: 1, + status: "published", + snapshot, + actorId, + note: "seed 基线发布版本", + }, + }); } async function main(): Promise { const brand = await prisma.brandProfile.upsert({ where: { id: "00000000-0000-0000-0000-000000000001" }, - update: {}, + update: { + slug: "default-brand", + name: "阿成家常菜", + templateKey: "food", + tagline: "现做家常套餐,也为小型聚餐定制一桌热饭菜", + description: "每天认真做好一顿家常饭。", + hours: "周一至周六 10:30-20:00", + address: "大学城生活区东门附近", + deliveryNote: "目前支持部分学生宿舍楼配送,无法送达时会主动联系。", + }, create: { slug: "default-brand", id: "00000000-0000-0000-0000-000000000001", @@ -156,58 +777,7 @@ async function main(): Promise { }, }); - const offerings = [ - { - brandId: brand.id, - name: "红烧肉双拼套餐", - description: "红烧肉、时蔬、米饭", - priceText: "¥28 / 份", - priceAmount: 2800, - sortOrder: 1, - }, - { - brandId: brand.id, - name: "小炒鸡套餐", - description: "现炒鸡块、时蔬、米饭", - priceText: "¥25 / 份", - priceAmount: 2500, - sortOrder: 2, - }, - { - brandId: brand.id, - name: "家庭聚餐私厨", - description: "根据人数、地点和口味人工沟通报价", - priceText: "面议", - sortOrder: 3, - }, - ]; - for (const offering of offerings) { - const existing = await prisma.offering.findFirst({ - where: { brandId: brand.id, name: offering.name }, - }); - if (existing) await prisma.offering.update({ where: { id: existing.id }, data: offering }); - else await prisma.offering.create({ data: { ...offering, kind: "service" } }); - } - await ensureRuntimeContent(brand.id, "food", [ - { - name: "红烧肉双拼套餐", - summary: "红烧肉、时蔬、米饭", - image: runtimeImages.food[0], - categoryKey: "set-meal", - }, - { - name: "小炒鸡套餐", - summary: "现炒鸡块、时蔬、米饭", - image: runtimeImages.food[1], - categoryKey: "set-meal", - }, - { - name: "家庭聚餐私厨", - summary: "根据人数、地点和口味人工沟通报价", - image: runtimeImages.food[2], - categoryKey: "private-chef", - }, - ]); + await ensureRuntimeContent(brand.id, runtimeSeedTemplates.food); for (const name of ["普通套餐", "私厨", "配送", "自取", "熟客", "重点跟进"]) { await prisma.tag.upsert({ @@ -231,9 +801,52 @@ async function main(): Promise { create: { adminUserId: admin.id, brandId: brand.id, role: "owner" }, }); + const personalBrand = await prisma.brandProfile.upsert({ + where: { id: "00000000-0000-0000-0000-000000000003" }, + update: { + slug: "linran-brand", + name: "林然品牌顾问", + templateKey: "personal", + tagline: "用清晰的定位与可执行的表达,让专业被看见。", + description: "为专业服务者提供品牌定位、表达与长期顾问支持。", + hours: "周一至周五 10:00-18:00", + address: "上海市徐汇区创意园区", + contactPhone: "13900000003", + contactWechat: "linran-brand", + }, + create: { + id: "00000000-0000-0000-0000-000000000003", + slug: "linran-brand", + name: "林然品牌顾问", + templateKey: "personal", + tagline: "用清晰的定位与可执行的表达,让专业被看见。", + description: "为专业服务者提供品牌定位、表达与长期顾问支持。", + hours: "周一至周五 10:00-18:00", + address: "上海市徐汇区创意园区", + contactPhone: "13900000003", + contactWechat: "linran-brand", + }, + }); + await prisma.brandMembership.upsert({ + where: { adminUserId_brandId: { adminUserId: admin.id, brandId: personalBrand.id } }, + update: { isEnabled: true, role: "owner" }, + create: { adminUserId: admin.id, brandId: personalBrand.id, role: "owner" }, + }); + await ensureRuntimeContent(personalBrand.id, runtimeSeedTemplates.personal); + const doorsBrand = await prisma.brandProfile.upsert({ where: { id: "00000000-0000-0000-0000-000000000002" }, - update: {}, + update: { + slug: "linjing-doors", + name: "林境门作", + templateKey: "doors", + tagline: "为别墅空间定制有秩序感的门系统", + description: "从入户大门到室内户内门,提供完整的门系统设计与落地服务。", + hours: "周一至周六 09:00-18:00", + address: "城市设计中心 3F", + contactPhone: "13800000000", + contactWechat: "linjing-doors", + }, create: { id: "00000000-0000-0000-0000-000000000002", slug: "linjing-doors", @@ -247,57 +860,15 @@ async function main(): Promise { contactWechat: "linjing-doors", }, }); - for (const offering of [ - { - name: "别墅入户大门", - description: "结合建筑立面与入户动线定制门体、五金和安装方案。", - priceText: "预约沟通", - sortOrder: 1, - }, - { - name: "院门与围合系统", - description: "院门、围墙和庭院动线的一体化设计与施工配合。", - priceText: "预约沟通", - sortOrder: 2, - }, - { - name: "室内户内门系统", - description: "根据空间风格定制户内门、隐形门和装饰门。", - priceText: "预约沟通", - sortOrder: 3, - }, - ]) { - await prisma.offering.upsert({ - where: { brandId_name: { brandId: doorsBrand.id, name: offering.name } }, - update: offering, - create: { ...offering, brandId: doorsBrand.id, kind: "service" }, - }); - } await prisma.brandMembership.upsert({ where: { adminUserId_brandId: { adminUserId: admin.id, brandId: doorsBrand.id } }, update: { isEnabled: true, role: "owner" }, create: { adminUserId: admin.id, brandId: doorsBrand.id, role: "owner" }, }); - await ensureRuntimeContent(doorsBrand.id, "doors", [ - { - name: "别墅入户大门", - summary: "结合建筑立面与入户动线定制门体、五金和安装方案。", - image: runtimeImages.doors[0], - categoryKey: "entrance-door", - }, - { - name: "院门与围合系统", - summary: "院门、围墙和庭院动线的一体化设计与施工配合。", - image: runtimeImages.doors[1], - categoryKey: "garden-door", - }, - { - name: "室内户内门系统", - summary: "根据空间风格定制户内门、隐形门和装饰门。", - image: runtimeImages.doors[2], - categoryKey: "interior-door", - }, - ]); + await ensureRuntimeContent(doorsBrand.id, runtimeSeedTemplates.doors); + await ensureSeedRelease(brand.id, admin.id); + await ensureSeedRelease(personalBrand.id, admin.id); + await ensureSeedRelease(doorsBrand.id, admin.id); } main().finally(() => prisma.$disconnect()); diff --git a/apps/api/src/admin-access.service.ts b/apps/api/src/admin-access.service.ts index 6b91ab0..9b2a76e 100644 --- a/apps/api/src/admin-access.service.ts +++ b/apps/api/src/admin-access.service.ts @@ -25,4 +25,12 @@ export class AdminAccessService { if (!membership?.isEnabled) throw new ForbiddenException("管理员没有当前品牌权限"); return { subject: identity.subject, brandId: identity.brandId, role: membership.role }; } + + async requireRole(request: FastifyRequest, allowedRoles: string[]): Promise { + const access = await this.requireBrand(request); + if (!allowedRoles.includes(access.role)) { + throw new ForbiddenException("当前账号没有系统设置权限"); + } + return true; + } } diff --git a/apps/api/src/admin-auth.service.ts b/apps/api/src/admin-auth.service.ts index 3fdc3f3..d0caa01 100644 --- a/apps/api/src/admin-auth.service.ts +++ b/apps/api/src/admin-auth.service.ts @@ -7,7 +7,10 @@ import { signIdentity } from "./auth.js"; export class AdminAuthService { constructor(private readonly prisma: PrismaService) {} - async login(username: string, password: string): Promise<{ token: string; displayName: string }> { + async login( + username: string, + password: string, + ): Promise<{ token: string; displayName: string; mustChangePassword: boolean; role: string }> { const user = await this.prisma.adminUser.findUnique({ where: { username } }); if (!user || !user.isEnabled || !(await bcrypt.compare(password, user.passwordHash))) { throw new UnauthorizedException("账号或密码错误"); @@ -36,6 +39,23 @@ export class AdminAuthService { role: "admin", }), displayName: user.displayName, + mustChangePassword: user.mustChangePassword, + role: activeMembership.role, }; } + + async changePassword( + userId: string, + currentPassword: string, + newPassword: string, + ): Promise { + const user = await this.prisma.adminUser.findUnique({ where: { id: userId } }); + if (!user || !(await bcrypt.compare(currentPassword, user.passwordHash))) { + throw new UnauthorizedException("当前密码不正确"); + } + await this.prisma.adminUser.update({ + where: { id: userId }, + data: { passwordHash: await bcrypt.hash(newPassword, 12), mustChangePassword: false }, + }); + } } diff --git a/apps/api/src/admin-membership.guard.ts b/apps/api/src/admin-membership.guard.ts index 23e4d30..2cccb37 100644 --- a/apps/api/src/admin-membership.guard.ts +++ b/apps/api/src/admin-membership.guard.ts @@ -11,6 +11,14 @@ export class AdminMembershipGuard implements CanActivate { const request = context.switchToHttp().getRequest(); if (request.url.startsWith("/admin/session/login")) return Promise.resolve(true); if (!request.url.startsWith("/admin/")) return Promise.resolve(true); + if ( + /^\/admin\/workspace\/(install|capabilities(?:\/|$)|template(?:\/|$)|modules(?:\/|$)|fields(?:\/|$))/.test( + request.url, + ) || + /^\/admin\/config\/visual-template(?:\/|$)/.test(request.url) + ) { + return this.access.requireRole(request, ["owner", "admin", "platform-admin"]); + } return this.access.requireBrand(request).then(() => true); } } diff --git a/apps/api/src/admin-workspace.controller.ts b/apps/api/src/admin-workspace.controller.ts index ce2f600..802a117 100644 --- a/apps/api/src/admin-workspace.controller.ts +++ b/apps/api/src/admin-workspace.controller.ts @@ -27,7 +27,12 @@ import { UpdateInquirySubmissionDto, UpdateCapabilityInstallationDto, } from "./admin.dto.js"; -import { capabilityPlugins, getBrandTemplate, resolveCapabilities } from "@personal-brand/config"; +import { + capabilityPlugins, + getBrandTemplate, + getTemplateSampleContent, + resolveCapabilities, +} from "@personal-brand/config"; import { TemplateWorkspaceService } from "./template-workspace.service.js"; import { validateFieldSnapshot, validateOfferingConfig } from "@personal-brand/validation"; @@ -176,15 +181,12 @@ class AdminWorkspaceController { @Get("capabilities") async listCapabilities(@Req() request: FastifyRequest): Promise { const brandId = this.requireAdmin(request).brandId; - const [brand, installations] = await Promise.all([ - this.prisma.brandProfile.findUnique({ - where: { id: brandId }, - select: { templateKey: true }, - }), + 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(brand?.templateKey ?? "personal"); + const template = getBrandTemplate(templateKey); return (template ? resolveCapabilities(template.capabilities) : []).map((definition) => { const item = installed.get(definition.key); return { @@ -202,15 +204,22 @@ class AdminWorkspaceController { @Get("sample-content/preview") async previewSampleContent(@Req() request: FastifyRequest): Promise { const brandId = this.requireAdmin(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: "doors", + templateKey: sample.templateKey, alreadyImported: offerings > 0 || trustContent > 0 || fields > 0, - counts: { offerings: 4, trustContent: 4, fields: 4 }, + counts: { + offerings: sample.offerings.length, + trustContent: sample.trustContent.length, + fields: sample.fields.length, + }, }; } @@ -218,6 +227,9 @@ class AdminWorkspaceController { async importSampleContent(@Req() request: FastifyRequest): Promise { const identity = this.requireAdmin(request); const brandId = identity.brandId; + const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId); + const sample = getTemplateSampleContent(templateKey); + if (!sample) throw new BadRequestException("模板示例内容不存在"); const existing = await this.prisma.brandFieldDefinition.count({ where: { brandId, source: "sample" }, }); @@ -227,54 +239,42 @@ class AdminWorkspaceController { if (existing || existingOffering) throw new BadRequestException("示例内容已经导入"); const result = await this.prisma.$transaction(async (tx) => { const offerings = await tx.offering.createMany({ - data: [ - ["序章·入户门", "为别墅入口定制的整樘门系统", "entrance-door"], - ["庭院·边界门", "连接建筑与庭院的定制门", "garden-door"], - ["室内·静谧门", "统一室内空间秩序的户内门", "interior-door"], - ["一对一门系统设计咨询", "从现场到方案的完整设计沟通", "custom"], - ].map((item, sortOrder) => ({ + data: sample.offerings.map((item, sortOrder) => ({ brandId, - kind: sortOrder === 3 ? "service" : "product", - name: item[0]!, - summary: item[1]!, - config: { categoryKey: item[2]! }, + kind: item.kind, + name: item.name, + summary: item.summary, + config: { categoryKey: item.categoryKey }, sortOrder, isEnabled: true, })), }); const trust = await tx.trustContent.createMany({ - data: ["主理人的门作观", "别墅门系统案例", "从测量到交付", "材料与工艺标准"].map( - (title, sortOrder) => ({ - brandId, - type: ["profile", "portfolio", "process", "credential"][sortOrder]!, - title, - content: "示例内容,待品牌主理人完善。", - sortOrder, - isPublished: false, - }), - ), + data: sample.trustContent.map((item, sortOrder) => ({ + brandId, + type: item.type, + title: item.title, + content: item.content, + sortOrder, + isPublished: false, + })), }); const fields = await tx.brandFieldDefinition.createMany({ - data: [ - ["projectType", "项目类型", "select"], - ["projectStage", "项目阶段", "select"], - ["siteDescription", "项目概况", "textarea"], - ["phone", "联系方式", "phone"], - ].map((item, sortOrder) => ({ + data: sample.fields.map((item, sortOrder) => ({ brandId, scope: "inquiry", - key: item[0]!, - label: item[1]!, - type: item[2]!, + key: item.key, + label: item.label, + type: item.type, sortOrder, source: "sample", - required: item[2] === "phone", + required: item.required, })), }); await tx.capabilityAuditLog.create({ data: { brandId, - capabilityKey: "doors", + capabilityKey: sample.capabilityKey, actorId: identity.subject, action: "sample_content_imported", toStatus: "enabled", @@ -294,8 +294,9 @@ class AdminWorkspaceController { ): Promise { const identity = this.requireAdmin(request); const brandId = identity.brandId; - const brand = await this.prisma.brandProfile.findUnique({ where: { id: brandId } }); - const template = getBrandTemplate(brand?.templateKey ?? "personal"); + 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({ diff --git a/apps/api/src/admin.dto.ts b/apps/api/src/admin.dto.ts index 2f74171..3d335b0 100644 --- a/apps/api/src/admin.dto.ts +++ b/apps/api/src/admin.dto.ts @@ -6,6 +6,7 @@ import { IsObject, IsOptional, IsString, + MinLength, Matches, Max, Min, @@ -26,6 +27,34 @@ export class UpdateBrandDto { @IsOptional() @IsObject() config?: Record; } +export class UpdateBrandPresentationDto { + @IsOptional() @IsObject() identity?: Record; + @IsOptional() @IsObject() home?: Record; + @IsOptional() @IsObject() offerings?: Record; + @IsOptional() @IsObject() detail?: Record; + @IsOptional() @IsObject() profile?: Record; + @IsOptional() @IsObject() inquiry?: Record; + @IsOptional() @IsObject() success?: Record; + @IsOptional() @IsObject() records?: Record; +} + +export class UpdateBrandMemberDto { + @IsOptional() @IsIn(["owner", "editor"]) role?: "owner" | "editor"; + @IsOptional() @IsBoolean() isEnabled?: boolean; +} + +export class CreateBrandMemberDto { + @IsString() username!: string; + @IsString() displayName!: string; + @IsString() @MinLength(8) password!: string; + @IsIn(["owner", "editor"]) role!: "owner" | "editor"; +} + +export class ChangeAdminPasswordDto { + @IsString() currentPassword!: string; + @IsString() @MinLength(8) newPassword!: string; +} + export class CreateTrustContentDto { @IsIn(["profile", "experience", "credential", "portfolio", "process", "testimonial"]) type!: string; diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index 95a63a8..cac0637 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -16,6 +16,9 @@ import { CustomerInquirySubmissionController } from "./modules/customer/customer import { TemplateWorkspaceService } from "./template-workspace.service.js"; import { AdminAccessService } from "./admin-access.service.js"; import { AdminMembershipGuard } from "./admin-membership.guard.js"; +import { BrandReleaseService } from "./brand-release.service.js"; +import { BrandReleaseApiService } from "./brand-release-api.service.js"; +import { AdminReleaseController } from "./modules/admin/admin-release.controller.js"; import { CustomerSessionController, AdminSessionController, @@ -54,6 +57,7 @@ export class HealthController { TenantController, AdminBookingController, AdminConfigController, + AdminReleaseController, ], providers: [ PrismaService, @@ -63,6 +67,8 @@ export class HealthController { TemplateWorkspaceService, AdminAccessService, AdminMembershipGuard, + BrandReleaseService, + BrandReleaseApiService, PublicBrandContextService, ], exports: [PrismaService, WechatAuthService], diff --git a/apps/api/src/booking.service.ts b/apps/api/src/booking.service.ts index a923b1b..2e3b01c 100644 --- a/apps/api/src/booking.service.ts +++ b/apps/api/src/booking.service.ts @@ -2,6 +2,7 @@ import { BadRequestException, Injectable, NotFoundException } from "@nestjs/comm import { BookingStatus, Prisma } from "@prisma/client"; import { PrismaService } from "./prisma.service.js"; import { canTransitionWorkflow, workflowRegistry } from "@personal-brand/config"; +import { BrandReleaseService } from "./brand-release.service.js"; const BASIC_BOOKING_WORKFLOW = workflowRegistry["booking.basic"]; @@ -23,9 +24,32 @@ export interface CreateBookingInput { @Injectable() export class BookingService { - constructor(private readonly prisma: PrismaService) {} + constructor( + private readonly prisma: PrismaService, + private readonly releases: BrandReleaseService, + ) {} async create(brandId: string, customerUserId: string, input: CreateBookingInput) { + const snapshot = await this.releases.getPublishedSnapshot(brandId); + if (!snapshot) throw new BadRequestException("品牌尚未发布"); + const publishedOfferingIds = this.releases.publishedOfferingIds(snapshot); + if ( + (input.offeringId && !publishedOfferingIds.has(input.offeringId)) || + input.items?.some((item) => !publishedOfferingIds.has(item.offeringId)) + ) { + throw new BadRequestException("业务提供项不存在或暂不可预订"); + } + const requestedOfferingIds = [ + ...(input.offeringId ? [input.offeringId] : []), + ...(input.items ?? []).map((item) => item.offeringId), + ]; + if (requestedOfferingIds.length) { + const enabledCount = await this.prisma.offering.count({ + where: { id: { in: requestedOfferingIds }, brandId, isEnabled: true }, + }); + if (enabledCount !== new Set(requestedOfferingIds).size) + throw new BadRequestException("业务提供项不存在或暂不可预订"); + } if (!input.customerName.trim() || (!input.phone?.trim() && !input.wechatId?.trim())) { throw new BadRequestException("称呼和至少一种联系方式为必填项"); } @@ -52,23 +76,22 @@ export class BookingService { ) { throw new BadRequestException("私厨需求必须填写日期、人数和地点"); } - const offerings = input.items?.length - ? await this.prisma.offering.findMany({ - where: { - id: { in: input.items.map((item) => item.offeringId) }, - brandId, - isEnabled: true, - }, - }) - : []; - const offeringMap = new Map(offerings.map((offering) => [offering.id, offering])); + const offeringMap = new Map( + snapshot.offerings.flatMap((raw) => { + if (!raw || typeof raw !== "object") return []; + const item = raw as Record; + return typeof item.id === "string" && item.isEnabled === true + ? [[item.id, item] as const] + : []; + }), + ); const items = (input.items ?? []).map((item) => { const offering = offeringMap.get(item.offeringId); - if (!offering || offering.priceAmount === null) + if (!offering || typeof offering.priceAmount !== "number") throw new BadRequestException("套餐不存在或暂不可预订"); return { - offeringId: offering.id, - serviceNameSnapshot: offering.name, + offeringId: item.offeringId, + serviceNameSnapshot: String(offering.name), unitPriceSnapshot: offering.priceAmount, quantity: item.quantity, subtotalSnapshot: offering.priceAmount * item.quantity, diff --git a/apps/api/src/brand-release-api.service.ts b/apps/api/src/brand-release-api.service.ts new file mode 100644 index 0000000..081d292 --- /dev/null +++ b/apps/api/src/brand-release-api.service.ts @@ -0,0 +1,225 @@ +import { + BadRequestException, + ConflictException, + Injectable, + NotFoundException, +} from "@nestjs/common"; +import { Prisma } from "@prisma/client"; +import { + getBrandTemplate, + getVisualTemplate, + isVisualTemplateCompatible, + getDefaultVisualTemplateKey, +} from "@personal-brand/config"; +import { PrismaService } from "./prisma.service.js"; +import { BrandReleaseService } from "./brand-release.service.js"; +import { validateFieldSnapshot } from "@personal-brand/validation"; + +@Injectable() +export class BrandReleaseApiService { + constructor( + private readonly prisma: PrismaService, + private readonly snapshots: BrandReleaseService, + ) {} + + async list(brandId: string): Promise { + return this.prisma.brandRelease.findMany({ + where: { brandId }, + orderBy: { version: "desc" }, + select: { + id: true, + version: true, + status: true, + note: true, + actorId: true, + createdAt: true, + revokedAt: true, + revokedBy: true, + }, + }); + } + + async readiness( + brandId: string, + database: Prisma.TransactionClient = this.prisma, + ): Promise<{ + ready: boolean; + checks: Array<{ key: string; label: string; passed: boolean }>; + }> { + const brand = await database.brandProfile.findUnique({ + where: { id: brandId }, + select: { name: true, tagline: true, description: true, templateKey: true, config: true }, + }); + const installation = await database.brandTemplateInstallation.findFirst({ + where: { brandId }, + orderBy: { updatedAt: "desc" }, + }); + const template = getBrandTemplate(installation?.templateKey ?? brand?.templateKey ?? ""); + const config = this.jsonObject(brand?.config); + const visualKey = + typeof config.visualTemplateKey === "string" + ? config.visualTemplateKey + : getDefaultVisualTemplateKey(brand?.templateKey ?? "personal"); + const visual = getVisualTemplate(visualKey); + const [offerings, forms, trust] = await Promise.all([ + database.offering.findMany({ where: { brandId, isEnabled: true }, select: { id: true } }), + database.inquiryForm.findMany({ + where: { brandId, isEnabled: true }, + select: { offeringId: true, fieldsSnapshot: true }, + }), + database.trustContent.count({ where: { brandId, isPublished: true } }), + ]); + const offeringIds = new Set(offerings.map((item) => item.id)); + const usableForms = forms.filter( + (form) => + (form.offeringId === null || offeringIds.has(form.offeringId)) && + Array.isArray(form.fieldsSnapshot) && + form.fieldsSnapshot.length > 0 && + validateFieldSnapshot(form.fieldsSnapshot).length === 0, + ); + const checks = [ + { key: "brand", label: "请先完善品牌名称", passed: Boolean(brand?.name.trim()) }, + { + key: "positioning", + label: "请先完善品牌定位和介绍", + passed: Boolean(brand?.tagline?.trim() && brand.description?.trim()), + }, + { key: "template", label: "当前行业模板不存在", passed: Boolean(template) }, + { + key: "visual", + label: "当前视觉模板不适配行业模板", + passed: Boolean(visual && template && isVisualTemplateCompatible(visual, template.key)), + }, + { key: "offerings", label: "至少需要一项已启用的业务提供项", passed: offerings.length > 0 }, + { key: "forms", label: "至少需要一个可用的咨询表单", passed: usableForms.length > 0 }, + { key: "trust", label: "至少需要一条已发布的信任内容", passed: trust > 0 }, + ]; + return { ready: checks.every((check) => check.passed), checks }; + } + + async publish(brandId: string, actorId: string, note?: string): Promise { + return this.withVersionRetry(() => + this.prisma.$transaction( + async (tx) => { + await this.validateForPublish(brandId, tx); + const snapshot = await this.snapshots.buildSnapshot(brandId, tx); + const latest = await tx.brandRelease.findFirst({ + where: { brandId }, + orderBy: { version: "desc" }, + select: { version: true }, + }); + await tx.brandRelease.updateMany({ + where: { brandId, status: "published" }, + data: { status: "superseded" }, + }); + return tx.brandRelease.create({ + data: { + brandId, + version: (latest?.version ?? 0) + 1, + status: "published", + snapshot: this.snapshots.toPrismaJson(snapshot), + actorId, + ...(note === undefined ? {} : { note }), + }, + }); + }, + { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, + ), + ); + } + + async rollback( + brandId: string, + actorId: string, + version: number, + note?: string, + ): Promise { + return this.withVersionRetry(() => + this.prisma.$transaction( + async (tx) => { + const source = await tx.brandRelease.findFirst({ + where: { brandId, version, status: { in: ["published", "superseded"] } }, + }); + if (!source) throw new NotFoundException("发布版本不存在"); + const snapshot = this.withCurrentTimestamp(source.snapshot); + const latest = await tx.brandRelease.findFirst({ + where: { brandId }, + orderBy: { version: "desc" }, + select: { version: true }, + }); + await tx.brandRelease.updateMany({ + where: { brandId, status: "published" }, + data: { status: "superseded" }, + }); + return tx.brandRelease.create({ + data: { + brandId, + version: (latest?.version ?? 0) + 1, + status: "published", + snapshot, + actorId, + note: note ?? `回滚自版本 ${version}`, + }, + }); + }, + { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, + ), + ); + } + + async revoke(brandId: string, actorId: string): Promise { + return this.withVersionRetry(() => + this.prisma.$transaction( + async (tx) => { + const current = await tx.brandRelease.findFirst({ + where: { brandId, status: "published" }, + orderBy: { version: "desc" }, + }); + if (!current) throw new NotFoundException("当前没有已发布版本"); + return tx.brandRelease.update({ + where: { id: current.id }, + data: { status: "revoked", revokedAt: new Date(), revokedBy: actorId }, + select: { id: true, version: true, status: true, revokedAt: true, revokedBy: true }, + }); + }, + { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, + ), + ); + } + + private async validateForPublish( + brandId: string, + database: Prisma.TransactionClient, + ): Promise { + const readiness = await this.readiness(brandId, database); + const missing = readiness.checks.find((check) => !check.passed); + if (missing) throw new BadRequestException(missing.label); + } + + private async withVersionRetry(operation: () => Promise): Promise { + for (let attempt = 0; attempt < 3; attempt += 1) { + try { + return await operation(); + } catch (error) { + if ( + !(error instanceof Prisma.PrismaClientKnownRequestError) || + !["P2002", "P2034"].includes(error.code) + ) + throw error; + if (attempt === 2) throw new ConflictException("发布版本冲突,请重试"); + } + } + throw new ConflictException("发布版本冲突,请重试"); + } + + private jsonObject(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : {}; + } + + private withCurrentTimestamp(value: Prisma.JsonValue): Prisma.InputJsonValue { + const snapshot = this.jsonObject(value); + return { ...snapshot, generatedAt: new Date().toISOString() }; + } +} diff --git a/apps/api/src/brand-release.service.ts b/apps/api/src/brand-release.service.ts new file mode 100644 index 0000000..6034b06 --- /dev/null +++ b/apps/api/src/brand-release.service.ts @@ -0,0 +1,129 @@ +import { Injectable } from "@nestjs/common"; +import { Prisma } from "@prisma/client"; +import { + getBrandTemplate, + getVisualTemplate, + getVisualTemplateManifest, + getDefaultVisualTemplateKey, +} from "@personal-brand/config"; +import { PrismaService } from "./prisma.service.js"; + +export interface BrandReleaseSnapshot { + schemaVersion: "1.0.0"; + generatedAt: string; + templateKey: string; + templateDefinition?: ReturnType | null; + visualTemplateDefinition?: ReturnType | null; + visualTemplateManifest?: ReturnType | null; + brand: Record | null; + installation: Record | null; + modules: unknown[]; + fields: unknown[]; + offerings: unknown[]; + forms: unknown[]; + trustContents: unknown[]; + capabilities: unknown[]; +} + +export async function buildBrandReleaseSnapshot( + database: Prisma.TransactionClient, + brandId: string, +): Promise { + const [brand, installation, modules, fields, offerings, forms, trustContents, capabilities] = + await Promise.all([ + database.brandProfile.findUnique({ where: { id: brandId } }), + database.brandTemplateInstallation.findFirst({ + where: { brandId }, + orderBy: { updatedAt: "desc" }, + }), + database.brandModule.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }), + database.brandFieldDefinition.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }), + database.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }), + database.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" } }), + database.trustContent.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }), + database.capabilityInstallation.findMany({ where: { brandId } }), + ]); + const templateKey = installation?.templateKey ?? brand?.templateKey ?? "personal"; + const config = + brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config) + ? (brand.config as Record) + : {}; + const visualKey = + typeof config.visualTemplateKey === "string" + ? config.visualTemplateKey + : getDefaultVisualTemplateKey(brand?.templateKey ?? "personal"); + const jsonObject = (value: object): Record => + JSON.parse(JSON.stringify(value)) as Record; + return { + schemaVersion: "1.0.0", + generatedAt: new Date().toISOString(), + templateKey, + templateDefinition: getBrandTemplate(templateKey) ?? null, + visualTemplateDefinition: getVisualTemplate(visualKey) ?? null, + visualTemplateManifest: getVisualTemplateManifest(visualKey) ?? null, + brand: brand ? jsonObject(brand) : null, + installation: installation ? jsonObject(installation) : null, + modules: modules.map((item) => jsonObject(item)), + fields: fields.map((item) => jsonObject(item)), + offerings: offerings.map((item) => jsonObject(item)), + forms: forms.map((item) => jsonObject(item)), + trustContents: trustContents.map((item) => jsonObject(item)), + capabilities: capabilities.map((item) => jsonObject(item)), + }; +} + +@Injectable() +export class BrandReleaseService { + constructor(private readonly prisma: PrismaService) {} + + async getPublishedSnapshot(brandId: string): Promise { + const release = await this.prisma.brandRelease.findFirst({ + where: { brandId, status: "published" }, + orderBy: { version: "desc" }, + select: { snapshot: true }, + }); + return release ? (release.snapshot as unknown as BrandReleaseSnapshot) : null; + } + + publishedOfferingIds(snapshot: BrandReleaseSnapshot): Set { + return new Set( + snapshot.offerings.flatMap((raw) => { + const item = this.record(raw); + return item.isEnabled === true && typeof item.id === "string" ? [item.id] : []; + }), + ); + } + + publishedForm(snapshot: BrandReleaseSnapshot, formId: string): Record | null { + const offeringIds = this.publishedOfferingIds(snapshot); + return ( + snapshot.forms + .map((raw) => this.record(raw)) + .find((form) => { + return ( + form.id === formId && + form.isEnabled === true && + (form.offeringId === null || + (typeof form.offeringId === "string" && offeringIds.has(form.offeringId))) + ); + }) ?? null + ); + } + + private record(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : {}; + } + + async buildSnapshot( + brandId: string, + database: Prisma.TransactionClient = this.prisma, + ): Promise { + return buildBrandReleaseSnapshot(database, brandId); + } + + toPrismaJson(snapshot: BrandReleaseSnapshot): Prisma.InputJsonValue { + return snapshot as unknown as Prisma.InputJsonValue; + } +} diff --git a/apps/api/src/modules/admin/admin-config.controller.ts b/apps/api/src/modules/admin/admin-config.controller.ts index 064bb5b..edab7af 100644 --- a/apps/api/src/modules/admin/admin-config.controller.ts +++ b/apps/api/src/modules/admin/admin-config.controller.ts @@ -15,12 +15,29 @@ import { Prisma } from "@prisma/client"; import type { FastifyRequest } from "fastify"; import { PrismaService } from "../../prisma.service.js"; import { readIdentity } from "../../auth.js"; -import { CreateTrustContentDto, UpdateBrandDto, UpdateTrustContentDto } from "../../admin.dto.js"; -import { getVisualTemplate } from "@personal-brand/config"; +import { + CreateTrustContentDto, + UpdateBrandDto, + UpdateBrandPresentationDto, + UpdateTrustContentDto, +} from "../../admin.dto.js"; +import { + getBrandTemplate, + getVisualTemplate, + isVisualTemplateCompatible, + listVisualTemplateKeys, + getDefaultVisualTemplateKey, +} from "@personal-brand/config"; +import { AdminAccessService } from "../../admin-access.service.js"; +import { TemplateWorkspaceService } from "../../template-workspace.service.js"; @Controller("admin/config") export class AdminConfigController { - constructor(private readonly prisma: PrismaService) {} + constructor( + private readonly prisma: PrismaService, + private readonly access: AdminAccessService, + private readonly templateWorkspace: TemplateWorkspaceService, + ) {} private brandId(request?: FastifyRequest): string { if (!request) return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001"; const token = request.headers.authorization?.replace(/^Bearer\s+/i, ""); @@ -52,6 +69,9 @@ export class AdminConfigController { ): Promise { this.requireAdmin(request); const { config, ...fields } = body; + if (config?.visualTemplateKey !== undefined) { + await this.access.requireRole(request, ["owner", "admin", "platform-admin"]); + } const current = await this.prisma.brandProfile.findUnique({ where: { id: this.brandId(request) }, select: { config: true }, @@ -62,6 +82,19 @@ export class AdminConfigController { : {}; const nextConfig = config ? { ...currentConfig, ...config } : undefined; 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) }, }); @@ -75,7 +108,8 @@ export class AdminConfigController { previousSnapshots: [ ...history, { - visualTemplateKey: currentConfig.visualTemplateKey ?? "linjing-editorial", + visualTemplateKey: + currentConfig.visualTemplateKey ?? getDefaultVisualTemplateKey(templateKey), savedAt: new Date().toISOString(), }, ], @@ -91,6 +125,74 @@ export class AdminConfigController { }, }); } + @Patch("presentation") + async updatePresentation( + @Req() request: FastifyRequest, + @Body() body: UpdateBrandPresentationDto, + ): Promise { + this.requireAdmin(request); + const brandId = this.brandId(request); + const brand = await this.prisma.brandProfile.findUnique({ + where: { id: brandId }, + select: { config: true }, + }); + const config = + brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config) + ? (brand.config as Record) + : {}; + const previous = + config.visualPresentation && + typeof config.visualPresentation === "object" && + !Array.isArray(config.visualPresentation) + ? (config.visualPresentation as Record) + : {}; + 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) + : {}; + 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).visualPresentation, + }; + } @Get("visual-template/history") getVisualTemplateHistory(@Req() request: FastifyRequest): unknown { this.requireAdmin(request); @@ -169,7 +271,7 @@ export class AdminConfigController { typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : "linjing-editorial"; - const current = getVisualTemplate(currentKey) ?? getVisualTemplate("linjing-editorial"); + const current = getVisualTemplate(currentKey); return { current: current ? { @@ -180,7 +282,7 @@ export class AdminConfigController { variants: current.variants, } : null, - available: ["linjing-editorial", "minimal-neutral"], + available: listVisualTemplateKeys(), }; }); } diff --git a/apps/api/src/modules/admin/admin-release.controller.ts b/apps/api/src/modules/admin/admin-release.controller.ts new file mode 100644 index 0000000..6a58999 --- /dev/null +++ b/apps/api/src/modules/admin/admin-release.controller.ts @@ -0,0 +1,54 @@ +import { Controller, Get, Param, ParseIntPipe, Post, Body, Req } from "@nestjs/common"; +import type { FastifyRequest } from "fastify"; +import { AdminAccessService } from "../../admin-access.service.js"; +import { BrandReleaseApiService } from "../../brand-release-api.service.js"; +import { PublishBrandReleaseDto } from "../../release.dto.js"; + +@Controller("admin/releases") +export class AdminReleaseController { + constructor( + private readonly access: AdminAccessService, + private readonly releases: BrandReleaseApiService, + ) {} + + @Get() + async list(@Req() request: FastifyRequest): Promise { + const identity = await this.requireBrand(request); + return this.releases.list(identity.brandId); + } + + @Get("readiness") + async readiness(@Req() request: FastifyRequest): Promise { + const identity = await this.requireBrand(request); + return this.releases.readiness(identity.brandId); + } + + @Post("publish") + async publish( + @Req() request: FastifyRequest, + @Body() body: PublishBrandReleaseDto, + ): Promise { + const identity = await this.requireBrand(request); + return this.releases.publish(identity.brandId, identity.subject, body.note); + } + + @Post(":version/rollback") + async rollback( + @Req() request: FastifyRequest, + @Param("version", ParseIntPipe) version: number, + @Body() body: PublishBrandReleaseDto, + ): Promise { + const identity = await this.requireBrand(request); + return this.releases.rollback(identity.brandId, identity.subject, version, body.note); + } + + @Post("revoke") + async revoke(@Req() request: FastifyRequest): Promise { + const identity = await this.requireBrand(request); + return this.releases.revoke(identity.brandId, identity.subject); + } + + private requireBrand(request: FastifyRequest): Promise<{ subject: string; brandId: string }> { + return this.access.requireBrand(request); + } +} diff --git a/apps/api/src/modules/customer/customer-inquiry-submission.controller.ts b/apps/api/src/modules/customer/customer-inquiry-submission.controller.ts index c09f3c8..13808ba 100644 --- a/apps/api/src/modules/customer/customer-inquiry-submission.controller.ts +++ b/apps/api/src/modules/customer/customer-inquiry-submission.controller.ts @@ -15,10 +15,14 @@ import type { FastifyRequest } from "fastify"; import { PrismaService } from "../../prisma.service.js"; import { readIdentity } from "../../auth.js"; import { CreateInquirySubmissionDto } from "../../booking.dto.js"; +import { BrandReleaseService } from "../../brand-release.service.js"; @Controller("customer/inquiry-submissions") export class CustomerInquirySubmissionController { - constructor(private readonly prisma: PrismaService) {} + constructor( + private readonly prisma: PrismaService, + private readonly releases: BrandReleaseService, + ) {} private present(submission: T) { const { customerSubject: _customerSubject, @@ -84,16 +88,27 @@ export class CustomerInquirySubmissionController { @Body() body: CreateInquirySubmissionDto, ): Promise { const identity = this.identity(request); + const snapshot = await this.releases.getPublishedSnapshot(identity.brandId); + const publishedForm = snapshot && this.releases.publishedForm(snapshot, body.formId); + if (!publishedForm) throw new BadRequestException("咨询表单不存在或品牌尚未发布"); const form = await this.prisma.inquiryForm.findFirst({ where: { id: body.formId, brandId: identity.brandId, isEnabled: true, - OR: [{ offeringId: null }, { offering: { isEnabled: true } }], }, }); if (!form) throw new BadRequestException("咨询表单不存在"); - const capabilityKey = form.purpose === "quote-request" ? "quote-request" : "inquiry"; + const offeringId = + typeof publishedForm.offeringId === "string" ? publishedForm.offeringId : null; + if (offeringId) { + const offering = await this.prisma.offering.findFirst({ + where: { id: offeringId, brandId: identity.brandId, isEnabled: true }, + select: { id: true }, + }); + if (!offering) throw new BadRequestException("当前业务提供项不可用"); + } + const capabilityKey = publishedForm.purpose === "quote-request" ? "quote-request" : "inquiry"; const capability = await this.prisma.capabilityInstallation.findUnique({ where: { brandId_capabilityKey: { brandId: identity.brandId, capabilityKey }, @@ -101,8 +116,8 @@ export class CustomerInquirySubmissionController { }); if (capability && capability.status !== "enabled") throw new BadRequestException("当前咨询能力不可用"); - const fields = Array.isArray(form.fieldsSnapshot) - ? (form.fieldsSnapshot as Array>) + const fields = Array.isArray(publishedForm.fieldsSnapshot) + ? (publishedForm.fieldsSnapshot as Array>) : []; for (const field of fields) { const key = typeof field.key === "string" ? field.key : ""; @@ -126,9 +141,9 @@ export class CustomerInquirySubmissionController { brandId: identity.brandId, customerSubject: identity.subject, inquiryFormId: form.id, - offeringId: form.offeringId, - formVersion: form.version, - fieldsSnapshot: form.fieldsSnapshot as Prisma.InputJsonValue, + offeringId, + formVersion: Number(publishedForm.version), + fieldsSnapshot: publishedForm.fieldsSnapshot as Prisma.InputJsonValue, values: values as Prisma.InputJsonValue, activeFields: Object.fromEntries(Object.keys(values).map((key) => [key, true])), }, diff --git a/apps/api/src/modules/public/public-inquiry-form.controller.ts b/apps/api/src/modules/public/public-inquiry-form.controller.ts index 29e37ab..d170be8 100644 --- a/apps/api/src/modules/public/public-inquiry-form.controller.ts +++ b/apps/api/src/modules/public/public-inquiry-form.controller.ts @@ -1,23 +1,19 @@ import { BadRequestException, Controller, Get, Param, Query } from "@nestjs/common"; -import { PrismaService } from "../../prisma.service.js"; import { PublicBrandContextService } from "./public-brand-context.service.js"; +import { BrandReleaseService } from "../../brand-release.service.js"; @Controller("public/inquiry-forms") export class PublicInquiryFormController { constructor( - private readonly prisma: PrismaService, + private readonly releases: BrandReleaseService, private readonly brandContext: PublicBrandContextService, ) {} @Get(":id") async get(@Param("id") id: string, @Query("brandSlug") brandSlug?: string): Promise { - const form = await this.prisma.inquiryForm.findFirst({ - where: { - id, - brandId: await this.brandContext.resolveId(brandSlug), - isEnabled: true, - OR: [{ offeringId: null }, { offering: { isEnabled: true } }], - }, - }); + const snapshot = await this.releases.getPublishedSnapshot( + await this.brandContext.resolveId(brandSlug), + ); + const form = snapshot && this.releases.publishedForm(snapshot, id); if (!form) throw new BadRequestException("咨询表单不存在"); return form; } diff --git a/apps/api/src/modules/public/public-offering.controller.ts b/apps/api/src/modules/public/public-offering.controller.ts index 3ccdb6d..48b6cb2 100644 --- a/apps/api/src/modules/public/public-offering.controller.ts +++ b/apps/api/src/modules/public/public-offering.controller.ts @@ -1,51 +1,52 @@ import { BadRequestException, Controller, Get, Param, Query } from "@nestjs/common"; -import { Prisma } from "@prisma/client"; -import { PrismaService } from "../../prisma.service.js"; import { PublicBrandContextService } from "./public-brand-context.service.js"; +import { BrandReleaseService } from "../../brand-release.service.js"; @Controller("public/offerings") export class PublicOfferingController { constructor( - private readonly prisma: PrismaService, + private readonly releases: BrandReleaseService, private readonly brandContext: PublicBrandContextService, ) {} @Get() async list(@Query("brandSlug") brandSlug?: string): Promise { const brandId = await this.brandContext.resolveId(brandSlug); - const items = await this.prisma.offering.findMany({ - where: { brandId, isEnabled: true }, - orderBy: { sortOrder: "asc" }, - include: { - inquiryForms: { - where: { isEnabled: true }, - orderBy: { updatedAt: "desc" }, - select: { id: true, name: true, purpose: true, targetType: true, version: true }, - }, - }, - }); - return items.map((item) => this.present(item)); + const snapshot = await this.releases.getPublishedSnapshot(brandId); + const forms = snapshot?.forms ?? []; + return (snapshot?.offerings ?? []) + .filter((raw) => this.object(raw).isEnabled === true) + .map((raw) => this.object(raw)) + .sort((a, b) => Number(a.sortOrder ?? 0) - Number(b.sortOrder ?? 0)) + .map((item) => + this.present({ + ...item, + inquiryForms: forms.filter((raw) => { + const form = this.object(raw); + return form.offeringId === item.id && form.isEnabled === true; + }), + }), + ); } @Get(":id") async get(@Param("id") id: string, @Query("brandSlug") brandSlug?: string): Promise { const brandId = await this.brandContext.resolveId(brandSlug); - const item = await this.prisma.offering.findFirst({ - where: { - id, - brandId, - isEnabled: true, - }, - include: { - inquiryForms: { - where: { isEnabled: true }, - orderBy: { updatedAt: "desc" }, - select: { id: true, name: true, purpose: true, targetType: true, version: true }, - }, - }, - }); + const snapshot = await this.releases.getPublishedSnapshot(brandId); + const item = (snapshot?.offerings ?? []) + .map((raw) => this.object(raw)) + .find((offering) => offering.id === id && offering.isEnabled === true); if (!item) throw new BadRequestException("业务提供项不存在"); - return this.present(item); + const forms = (snapshot?.forms ?? []).filter((raw) => { + const form = this.object(raw); + return form.offeringId === id && form.isEnabled === true; + }); + return this.present({ ...item, inquiryForms: forms }); } - private present(item: { config: Prisma.JsonValue; [key: string]: unknown }): unknown { + private object(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : {}; + } + private present(item: { config?: unknown; [key: string]: unknown }): unknown { const config = (item.config ?? {}) as Record; return { ...item, diff --git a/apps/api/src/modules/public/public-workspace.controller.ts b/apps/api/src/modules/public/public-workspace.controller.ts index 221edd6..6e0b700 100644 --- a/apps/api/src/modules/public/public-workspace.controller.ts +++ b/apps/api/src/modules/public/public-workspace.controller.ts @@ -2,12 +2,14 @@ import { Controller, Get, Query } from "@nestjs/common"; import { Prisma } from "@prisma/client"; import { PrismaService } from "../../prisma.service.js"; import { PublicBrandContextService } from "./public-brand-context.service.js"; +import type { BrandReleaseSnapshot } from "../../brand-release.service.js"; import { getBrandTemplate, getVisualTemplate, getVisualTemplateManifest, resolveCapabilities, capabilityPlugins, + getDefaultVisualTemplateKey, } from "@personal-brand/config"; import type { RuntimeInquiryField, @@ -22,60 +24,77 @@ export class PublicWorkspaceController { private readonly prisma: PrismaService, private readonly brandContext: PublicBrandContextService, ) {} - private readonly cache = new Map(); @Get() async get(@Query("brandSlug") brandSlug?: string): Promise { const brandId = await this.brandContext.resolveId(brandSlug); - const cached = process.env.NODE_ENV === "test" ? undefined : this.cache.get(brandId); - if (cached && cached.expiresAt > Date.now()) return cached.value; - const [ - brand, - modules, - fields, - offerings, - inquiryForms, - installation, - capabilityInstallations, - trustContents, - ] = await Promise.all([ - this.prisma.brandProfile.findUnique({ where: { id: brandId } }), - this.prisma.brandModule.findMany({ - where: { brandId, isEnabled: true }, - orderBy: { sortOrder: "asc" }, - }), - this.prisma.brandFieldDefinition.findMany({ - where: { brandId, isVisible: true }, - orderBy: { sortOrder: "asc" }, - }), - this.prisma.offering.findMany({ - where: { brandId, isEnabled: true }, - orderBy: { sortOrder: "asc" }, - }), - this.prisma.inquiryForm.findMany({ - where: { - brandId, - isEnabled: true, - OR: [{ offeringId: null }, { offering: { isEnabled: true } }], - }, - orderBy: { updatedAt: "desc" }, - }), - this.prisma.brandTemplateInstallation.findFirst({ - where: { brandId }, - orderBy: { updatedAt: "desc" }, - }), - this.prisma.capabilityInstallation.findMany({ where: { brandId } }), - this.prisma.trustContent.findMany({ - where: { brandId, isPublished: true }, - orderBy: { sortOrder: "asc" }, - }), - ]); - const templateKey = installation?.templateKey ?? brand?.templateKey ?? "personal"; - const template = getBrandTemplate(templateKey); - const runtimeCapabilities = capabilityInstallations.length - ? capabilityInstallations.map((item) => ({ - key: item.capabilityKey, - version: item.capabilityVersion, - status: item.status as "enabled" | "disabled" | "degraded", + const release = await this.prisma.brandRelease.findFirst({ + where: { brandId, status: "published" }, + orderBy: { version: "desc" }, + select: { version: true, createdAt: true, snapshot: true }, + }); + const releaseSnapshot = this.jsonObject(release?.snapshot) as unknown as BrandReleaseSnapshot; + if (!release) { + return { + contractVersion: "1.0", + schemaVersion: "1.0.0", + publication: { status: "unpublished", version: null }, + brand: null, + template: null, + visualTemplate: null, + modules: [], + offerings: [], + inquiryForms: [], + capabilities: [], + runtimeCapabilities: [], + runtimeModules: [], + fields: [], + trustContent: [], + trustPresentation: {}, + inquiryForm: null, + navigation: { tabs: [] }, + plugins: [], + theme: { colors: {} }, + }; + } + const brandData = this.jsonObject(releaseSnapshot.brand); + const modulesData = this.jsonArray(releaseSnapshot.modules).filter( + (item) => this.jsonObject(item).isEnabled === true, + ) as Array>; + const fieldsData = this.jsonArray(releaseSnapshot.fields).filter( + (item) => this.jsonObject(item).isVisible === true, + ); + const offeringsData = this.jsonArray(releaseSnapshot.offerings).filter( + (item) => this.jsonObject(item).isEnabled === true, + ) as Array>; + const enabledOfferingIds = new Set(offeringsData.map((item) => item.id)); + const formsData = this.jsonArray(releaseSnapshot.forms).filter((item) => { + const form = this.jsonObject(item); + return ( + form.isEnabled === true && + (form.offeringId === null || enabledOfferingIds.has(form.offeringId)) + ); + }); + const trustData = this.jsonArray(releaseSnapshot.trustContents).filter( + (item) => this.jsonObject(item).isPublished === true, + ) as Array>; + const installationData = this.jsonObject(releaseSnapshot.installation); + const templateKeyFromSnapshot = + typeof releaseSnapshot.templateKey === "string" ? releaseSnapshot.templateKey : undefined; + const templateKey = + templateKeyFromSnapshot ?? + (typeof installationData.templateKey === "string" + ? installationData.templateKey + : undefined) ?? + (typeof brandData.templateKey === "string" ? brandData.templateKey : "personal"); + const template = releaseSnapshot.templateDefinition ?? getBrandTemplate(templateKey); + const capabilityData = this.jsonArray(releaseSnapshot.capabilities) as Array< + Record + >; + const runtimeCapabilities = capabilityData.length + ? capabilityData.map((item) => ({ + key: this.string(item.capabilityKey), + version: this.string(item.capabilityVersion, "1.0.0"), + status: this.capabilityStatus(item.status), config: item.config && typeof item.config === "object" && !Array.isArray(item.config) ? (item.config as Record) @@ -90,43 +109,96 @@ export class PublicWorkspaceController { })) : []; const brandConfig = - brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config) - ? (brand.config as Record) + brandData.config && typeof brandData.config === "object" && !Array.isArray(brandData.config) + ? (brandData.config as Record) : {}; const visualTemplateKey = typeof brandConfig.visualTemplateKey === "string" ? brandConfig.visualTemplateKey - : "linjing-editorial"; + : getDefaultVisualTemplateKey(templateKey); const visualTemplate = - getVisualTemplate(visualTemplateKey) ?? getVisualTemplate("linjing-editorial"); + releaseSnapshot.visualTemplateDefinition ?? getVisualTemplate(visualTemplateKey); const visualTemplateManifest = - getVisualTemplateManifest(visualTemplateKey) ?? - getVisualTemplateManifest("linjing-editorial"); + releaseSnapshot.visualTemplateManifest ?? getVisualTemplateManifest(visualTemplateKey); const runtimeBrand = { - ...(brand ?? {}), + ...brandData, ...brandConfig, }; - const runtimeModules: RuntimeModule[] = modules.map((module) => ({ - key: module.type, - type: this.moduleType(module.type), + const runtimeModules: RuntimeModule[] = modulesData.map((item) => ({ + key: this.string(item.type, "custom"), + type: this.moduleType(this.string(item.type, "custom")), version: "1.0.0", - propsSchema: `module.${module.type}.v1`, - dataSource: module.type, - config: this.jsonObject(module.config), + propsSchema: `module.${this.string(item.type, "custom")}.v1`, + dataSource: this.string(item.type, "custom"), + config: this.jsonObject(item.config), source: - module.source === "custom" ? "custom" : module.source === "template" ? "template" : "core", + item.source === "custom" ? "custom" : item.source === "template" ? "template" : "core", schemaVersion: "1.0", })); - const runtimeOfferings: RuntimeOffering[] = offerings.map((item) => { + const runtimeOfferings: RuntimeOffering[] = offeringsData.map((raw) => { + const item = raw; const config = this.jsonObject(item.config); const sections = Array.isArray(config.sections) ? config.sections : []; + const details = this.jsonObject(config.details); + const media = Array.isArray(config.media) + ? config.media.flatMap((entry) => { + const value = this.jsonObject(entry); + return typeof value.url === "string" + ? [ + { + url: value.url, + alt: + typeof value.alt === "string" + ? value.alt + : this.string(item.name, "业务提供项"), + type: "image" as const, + }, + ] + : []; + }) + : []; + const materialsList = Array.isArray(details.materialsList) + ? details.materialsList.flatMap((entry) => { + const value = this.jsonObject(entry); + return typeof value.name === "string" && typeof value.spec === "string" + ? [{ name: value.name, spec: value.spec }] + : []; + }) + : []; return { - id: item.id, - name: item.name, - summary: item.summary ?? item.description ?? "", - enabled: item.isEnabled, + id: this.string(item.id), + name: this.string(item.name), + summary: typeof item.summary === "string" ? item.summary : this.string(item.description), + enabled: item.isEnabled !== false, + kind: this.offeringKind(this.string(item.kind, "service")), + coverUrl: typeof item.coverUrl === "string" ? item.coverUrl : null, + priceText: typeof item.priceText === "string" ? item.priceText : null, + priceAmount: typeof item.priceAmount === "number" ? item.priceAmount : null, schemaKey: typeof config.schemaKey === "string" ? config.schemaKey : "offering.default", schemaVersion: typeof config.schemaVersion === "string" ? config.schemaVersion : "1.0.0", + presentation: { + categoryKey: typeof config.categoryKey === "string" ? config.categoryKey : "custom", + categoryLabel: + typeof config.categoryLabel === "string" ? config.categoryLabel : "业务提供项", + heroImage: + typeof config.detailHero === "string" + ? config.detailHero + : typeof item.coverUrl === "string" + ? item.coverUrl + : null, + keywords: Array.isArray(config.keywords) + ? config.keywords.filter((keyword): keyword is string => typeof keyword === "string") + : [], + media, + details: { + background: typeof details.background === "string" ? details.background : "", + designConcept: typeof details.designConcept === "string" ? details.designConcept : "", + crafts: Array.isArray(details.crafts) + ? details.crafts.filter((craft): craft is string => typeof craft === "string") + : [], + materialsList, + }, + }, sections: sections .filter((section): section is Record => Boolean(section && typeof section === "object"), @@ -152,11 +224,12 @@ export class PublicWorkspaceController { "checkbox", "textarea", "date", - ].includes(String(value.type)) + ].includes(this.string(value.type)) ? (value.type as RuntimeInquiryField["type"]) : "text"; const options = Array.isArray(value.options) ? value.options.flatMap((option) => { + if (typeof option === "string") return [{ label: option, value: option }]; if (!option || typeof option !== "object") return []; const item = option as Record; return typeof item.label === "string" && typeof item.value === "string" @@ -174,9 +247,23 @@ export class PublicWorkspaceController { }, ]; }); - const inquiryForm = inquiryForms[0] ?? null; + const inquiryForm = formsData[0] ?? null; + const trustPresentation = trustData.reduce>((result, raw) => { + const item = this.jsonObject(raw); + const config = this.jsonObject(item.config); + for (const [key, value] of Object.entries(config)) { + if (!(key in result)) result[key] = value; + } + if (item.type === "profile" && typeof result.bio !== "string") result.bio = item.content; + return result; + }, {}); const runtimeWorkspace: RuntimeWorkspace = { schemaVersion: "1.0.0", + publication: { + status: "published", + version: release.version, + publishedAt: release.createdAt.toISOString(), + }, brand: runtimeBrand, navigation: { tabs: [ @@ -187,15 +274,24 @@ export class PublicWorkspaceController { }, modules: runtimeModules, offerings: runtimeOfferings, - inquiryForms: inquiryForms.map((form) => ({ - key: form.id, - version: String(form.version), - purpose: this.formPurpose(form.purpose), - target: form.targetType === "offering" ? "offering" : "brand", - ...(form.offeringId ? { targetId: form.offeringId } : {}), - submissionAction: this.submissionAction(form.submissionAction), - fields: toInquiryFields(form.fieldsSnapshot), - })), + inquiryForms: formsData.map((raw) => { + const form = this.jsonObject(raw); + return { + key: this.string(form.id), + version: + typeof form.version === "number" + ? String(form.version) + : this.string(form.version, "1"), + purpose: this.formPurpose(this.string(form.purpose, "inquiry")), + target: form.targetType === "offering" ? "offering" : "brand", + ...(typeof form.offeringId === "string" ? { targetId: form.offeringId } : {}), + submissionAction: this.submissionAction( + this.string(form.submissionAction, "create-inquiry"), + ), + fields: toInquiryFields(form.fieldsSnapshot as Prisma.JsonValue), + }; + }), + trustPresentation, capabilities: runtimeCapabilities, plugins: runtimeCapabilities .filter((capability) => capability.status === "enabled") @@ -215,7 +311,10 @@ export class PublicWorkspaceController { template: template ? { key: template.key, - version: installation?.templateVersion ?? template.version, + version: + typeof installationData.templateVersion === "string" + ? installationData.templateVersion + : template.version, name: template.name, } : null, @@ -224,21 +323,19 @@ export class PublicWorkspaceController { key: visualTemplate.key, version: visualTemplate.version, name: visualTemplate.name, + supportedIndustryTemplates: visualTemplate.supportedIndustryTemplates, variants: visualTemplate.variants, } : null, visualTemplateManifest, capabilities: runtimeCapabilities, runtimeCapabilities, - modules, runtimeModules, - fields, - offerings, - trustContent: trustContents, + fields: fieldsData, + trustContent: trustData, + trustPresentation, inquiryForm, }; - if (process.env.NODE_ENV !== "test") - this.cache.set(brandId, { expiresAt: Date.now() + 30_000, value: response }); return response; } private jsonObject(value: unknown): Record { @@ -246,10 +343,22 @@ export class PublicWorkspaceController { ? (value as Record) : {}; } + private string(value: unknown, fallback = ""): string { + return typeof value === "string" ? value : fallback; + } + private capabilityStatus(value: unknown): "enabled" | "disabled" | "degraded" { + return value === "disabled" || value === "degraded" ? value : "enabled"; + } private jsonArray(value: unknown): Prisma.JsonValue[] { return Array.isArray(value) ? (value as Prisma.JsonValue[]) : []; } private moduleType(value: string): RuntimeModule["type"] { + const aliases: Record = { + identity: "brand-hero", + trust: "trust-proof", + offering: "offering-list", + contact: "founder-card", + }; const known: RuntimeModule["type"][] = [ "brand-hero", "founder-card", @@ -264,8 +373,9 @@ export class PublicWorkspaceController { "records", "custom", ]; + const type = aliases[value] ?? value; return ( - known.includes(value as RuntimeModule["type"]) ? value : "custom" + known.includes(type as RuntimeModule["type"]) ? type : "custom" ) as RuntimeModule["type"]; } private sectionType(value: unknown): RuntimeOffering["sections"][number]["type"] { @@ -274,6 +384,12 @@ export class PublicWorkspaceController { ? (value as (typeof known)[number]) : "text"; } + private offeringKind(value: string): RuntimeOffering["kind"] { + const known: RuntimeOffering["kind"][] = ["service", "product", "package", "subscription"]; + return known.includes(value as RuntimeOffering["kind"]) + ? (value as RuntimeOffering["kind"]) + : "service"; + } private formPurpose(value: string): RuntimeWorkspace["inquiryForms"][number]["purpose"] { return value === "booking" || value === "quote-request" ? value : "inquiry"; } diff --git a/apps/api/src/modules/public/public.controller.ts b/apps/api/src/modules/public/public.controller.ts index 26fab74..de8f31b 100644 --- a/apps/api/src/modules/public/public.controller.ts +++ b/apps/api/src/modules/public/public.controller.ts @@ -1,10 +1,11 @@ import { BadRequestException, Controller, Get, Param, Query } from "@nestjs/common"; -import { PrismaService } from "../../prisma.service.js"; import { PublicBrandContextService } from "./public-brand-context.service.js"; +import { BrandReleaseService } from "../../brand-release.service.js"; import { brandTemplates, getBrandTemplate, getVisualTemplate, + isVisualTemplateCompatible, resolveCapabilities, visualTemplates, } from "@personal-brand/config"; @@ -12,50 +13,59 @@ import { @Controller("public") export class PublicController { constructor( - private readonly prisma: PrismaService, + private readonly releases: BrandReleaseService, private readonly brandContext: PublicBrandContextService, ) {} @Get("brand") async brand(@Query("brandSlug") brandSlug?: string): Promise { - return this.prisma.brandProfile.findUnique({ - where: { - id: await this.brandContext.resolveId(brandSlug), - }, - select: { - id: true, - name: true, - templateKey: true, - tagline: true, - description: true, - avatarUrl: true, - coverUrl: true, - hours: true, - address: true, - deliveryNote: true, - contactPhone: true, - contactWechat: true, - }, - }); + const snapshot = await this.releases.getPublishedSnapshot( + await this.brandContext.resolveId(brandSlug), + ); + if (!snapshot?.brand) return null; + const keys = [ + "id", + "name", + "templateKey", + "tagline", + "description", + "avatarUrl", + "coverUrl", + "hours", + "address", + "deliveryNote", + "contactPhone", + "contactWechat", + ]; + return Object.fromEntries(keys.map((key) => [key, snapshot.brand?.[key] ?? null])); } } @Controller("public/trust-content") export class PublicTrustContentController { constructor( - private readonly prisma: PrismaService, + private readonly releases: BrandReleaseService, private readonly brandContext: PublicBrandContextService, ) {} @Get() async list(@Query("brandSlug") brandSlug?: string): Promise { - return this.prisma.trustContent.findMany({ - where: { - brandId: await this.brandContext.resolveId(brandSlug), - isPublished: true, - }, - orderBy: [{ type: "asc" }, { sortOrder: "asc" }], - }); + const snapshot = await this.releases.getPublishedSnapshot( + await this.brandContext.resolveId(brandSlug), + ); + return (snapshot?.trustContents ?? []) + .filter((item) => + Boolean( + item && + typeof item === "object" && + (item as Record).isPublished === true, + ), + ) + .sort((left, right) => { + const a = left as { type: string; sortOrder: number }; + const b = right as { type: string; sortOrder: number }; + return a.type.localeCompare(b.type) || a.sortOrder - b.sortOrder; + }); } } @@ -63,7 +73,10 @@ export class PublicTrustContentController { export class PublicTemplateController { @Get() list(): unknown { - return { industries: Object.values(brandTemplates), visuals: Object.values(visualTemplates) }; + return { + industries: Object.values(brandTemplates), + visuals: Object.values(visualTemplates), + }; } @Get("preview") @@ -72,8 +85,10 @@ export class PublicTemplateController { @Query("visual") visual = "linjing-editorial", ): unknown { const industryTemplate = getBrandTemplate(industry); - const visualTemplate = getVisualTemplate(visual) ?? getVisualTemplate("linjing-editorial"); + const visualTemplate = getVisualTemplate(visual); if (!industryTemplate || !visualTemplate) throw new BadRequestException("模板组合不存在"); + if (!isVisualTemplateCompatible(visualTemplate, industryTemplate.key)) + throw new BadRequestException("当前视觉模板不适配所选行业模板"); return { industry: industryTemplate, visual: visualTemplate, diff --git a/apps/api/src/modules/session/session.controller.ts b/apps/api/src/modules/session/session.controller.ts index 2d70a74..ee4100a 100644 --- a/apps/api/src/modules/session/session.controller.ts +++ b/apps/api/src/modules/session/session.controller.ts @@ -1,22 +1,39 @@ -import { BadRequestException, Body, Controller, Post } from "@nestjs/common"; +import { + BadRequestException, + Body, + Controller, + Post, + Query, + Req, + UnauthorizedException, +} from "@nestjs/common"; +import type { FastifyRequest } from "fastify"; import { PrismaService } from "../../prisma.service.js"; import { WechatAuthService } from "../../wechat-auth.js"; import { AdminAuthService } from "../../admin-auth.service.js"; import { AdminLoginDto, WechatLoginDto } from "../../admin-auth.dto.js"; import { signIdentity } from "../../auth.js"; +import { PublicBrandContextService } from "../public/public-brand-context.service.js"; +import { ChangeAdminPasswordDto } from "../../admin.dto.js"; +import { readIdentity } from "../../auth.js"; @Controller("customer/session") export class CustomerSessionController { constructor( private readonly wechatAuth: WechatAuthService, private readonly prisma: PrismaService, + private readonly brandContext: PublicBrandContextService, ) {} @Post("wechat") - async wechatLogin(@Body() body: WechatLoginDto): Promise<{ token: string }> { + async wechatLogin( + @Body() body: WechatLoginDto, + @Query("brandSlug") brandSlug?: string, + ): Promise<{ token: string }> { const session = await this.wechatAuth.exchangeCode(body.code); + const brandId = await this.brandContext.resolveId(brandSlug); const brand = await this.prisma.brandProfile.findUnique({ - where: { id: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001" }, + where: { id: brandId }, select: { id: true }, }); if (!brand) throw new BadRequestException("品牌尚未初始化"); @@ -36,7 +53,22 @@ export class AdminSessionController { constructor(private readonly auth: AdminAuthService) {} @Post("login") - login(@Body() body: AdminLoginDto): Promise<{ token: string; displayName: string }> { + login( + @Body() body: AdminLoginDto, + ): Promise<{ token: string; displayName: string; mustChangePassword: boolean; role: string }> { return this.auth.login(body.username, body.password); } + + @Post("change-password") + async changePassword( + @Req() request: FastifyRequest, + @Body() body: ChangeAdminPasswordDto, + ): Promise<{ changed: true }> { + const token = request.headers.authorization?.replace(/^Bearer\s+/i, ""); + if (!token) throw new UnauthorizedException("缺少管理员登录态"); + const identity = readIdentity(token); + if (identity.role !== "admin") throw new UnauthorizedException("管理员登录态无效"); + await this.auth.changePassword(identity.subject, body.currentPassword, body.newPassword); + return { changed: true }; + } } diff --git a/apps/api/src/modules/tenant/tenant.controller.ts b/apps/api/src/modules/tenant/tenant.controller.ts index 96179f8..2aa0727 100644 --- a/apps/api/src/modules/tenant/tenant.controller.ts +++ b/apps/api/src/modules/tenant/tenant.controller.ts @@ -1,8 +1,12 @@ import { Controller, + BadRequestException, + Body, + ConflictException, ForbiddenException, Get, Param, + Patch, Post, Req, UnauthorizedException, @@ -10,10 +14,105 @@ import { import type { FastifyRequest } from "fastify"; import { PrismaService } from "../../prisma.service.js"; import { readIdentity, signIdentity } from "../../auth.js"; +import { AdminAccessService } from "../../admin-access.service.js"; +import { CreateBrandMemberDto, UpdateBrandMemberDto } from "../../admin.dto.js"; +import bcrypt from "bcryptjs"; @Controller("admin/brands") export class TenantController { - constructor(private readonly prisma: PrismaService) {} + constructor( + private readonly prisma: PrismaService, + private readonly access: AdminAccessService, + ) {} + + @Get("members") + async listMembers(@Req() request: FastifyRequest): Promise { + await this.access.requireRole(request, ["owner", "admin", "platform-admin"]); + const current = this.adminIdentity(request); + return this.prisma.brandMembership.findMany({ + where: { brandId: current.brandId }, + include: { + adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } }, + }, + orderBy: { createdAt: "asc" }, + }); + } + + @Post("members") + async createMember( + @Req() request: FastifyRequest, + @Body() body: CreateBrandMemberDto, + ): Promise { + await this.access.requireRole(request, ["owner", "admin", "platform-admin"]); + const actor = this.adminIdentity(request); + const username = body.username.trim(); + const displayName = body.displayName.trim(); + if (!username || !displayName) throw new BadRequestException("账号和显示名称不能为空"); + const existing = await this.prisma.adminUser.findUnique({ where: { username } }); + if (existing) throw new ConflictException("账号已存在,请使用其他账号"); + const passwordHash = await bcrypt.hash(body.password, 12); + const member = await this.prisma.$transaction(async (tx) => { + const adminUser = await tx.adminUser.create({ + data: { + username, + displayName, + passwordHash, + role: "admin", + isEnabled: true, + mustChangePassword: true, + }, + }); + return tx.brandMembership.create({ + data: { + adminUserId: adminUser.id, + brandId: actor.brandId, + role: body.role, + isEnabled: true, + }, + include: { + adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } }, + }, + }); + }); + return member; + } + + @Patch("members/:id") + async updateMember( + @Req() request: FastifyRequest, + @Param("id") id: string, + @Body() body: UpdateBrandMemberDto, + ): Promise { + await this.access.requireRole(request, ["owner", "admin", "platform-admin"]); + const actor = this.adminIdentity(request); + const membership = await this.prisma.brandMembership.findFirst({ + where: { id, brandId: actor.brandId }, + }); + if (!membership) throw new BadRequestException("成员不存在"); + if (membership.adminUserId === actor.subject) { + if (body.isEnabled === false || (body.role && body.role !== membership.role)) { + throw new BadRequestException("不能修改自己的角色或停用自己"); + } + } + const nextRole = body.role ?? membership.role; + const nextEnabled = body.isEnabled ?? membership.isEnabled; + if (membership.role === "owner" && (nextRole !== "owner" || !nextEnabled)) { + const ownerCount = await this.prisma.brandMembership.count({ + where: { brandId: actor.brandId, role: "owner", isEnabled: true }, + }); + if (ownerCount <= 1) throw new BadRequestException("品牌至少需要保留一位启用的负责人"); + } + return this.prisma.brandMembership.update({ + where: { id: membership.id }, + data: { + ...(body.role ? { role: body.role } : {}), + ...(body.isEnabled === undefined ? {} : { isEnabled: body.isEnabled }), + }, + include: { + adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } }, + }, + }); + } @Get() async list(@Req() request: FastifyRequest): Promise { diff --git a/apps/api/src/release.dto.ts b/apps/api/src/release.dto.ts new file mode 100644 index 0000000..8bc2ec6 --- /dev/null +++ b/apps/api/src/release.dto.ts @@ -0,0 +1,7 @@ +import { IsOptional, IsString } from "class-validator"; + +export class PublishBrandReleaseDto { + @IsOptional() + @IsString() + note?: string; +} diff --git a/apps/api/src/template-workspace.service.ts b/apps/api/src/template-workspace.service.ts index 6370bb3..4b45a07 100644 --- a/apps/api/src/template-workspace.service.ts +++ b/apps/api/src/template-workspace.service.ts @@ -1,11 +1,33 @@ import { BadRequestException, Injectable } from "@nestjs/common"; import { Prisma } from "@prisma/client"; -import { getBrandTemplate, getVisualTemplateManifest } from "@personal-brand/config"; +import { + getBrandTemplate, + getVisualTemplate, + getVisualTemplateManifest, + getDefaultVisualTemplateKey, + isVisualTemplateCompatible, +} from "@personal-brand/config"; +import type { BrandTemplateKey } from "@personal-brand/types"; import { PrismaService } from "./prisma.service.js"; @Injectable() export class TemplateWorkspaceService { constructor(private readonly prisma: PrismaService) {} + async getEffectiveTemplateKey(brandId: string): Promise { + const [installation, brand] = await Promise.all([ + this.prisma.brandTemplateInstallation.findFirst({ + where: { brandId }, + orderBy: { updatedAt: "desc" }, + select: { templateKey: true }, + }), + this.prisma.brandProfile.findUnique({ + where: { id: brandId }, + select: { templateKey: true }, + }), + ]); + const key = installation?.templateKey ?? brand?.templateKey ?? "personal"; + return getBrandTemplate(key) ? (key as BrandTemplateKey) : "personal"; + } async install(brandId: string, templateKey: "personal" | "food" | "doors") { const template = getBrandTemplate(templateKey); if (!template) throw new BadRequestException("行业模板不存在"); @@ -23,14 +45,22 @@ export class TemplateWorkspaceService { brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config) ? (brand.config as Record) : {}; + const configuredVisualTemplateKey = + typeof brandConfig.visualTemplateKey === "string" ? brandConfig.visualTemplateKey : undefined; const visualTemplateKey = - typeof brandConfig.visualTemplateKey === "string" - ? brandConfig.visualTemplateKey - : templateKey === "doors" - ? "linjing-editorial" - : "minimal-neutral"; + configuredVisualTemplateKey && + getVisualTemplate(configuredVisualTemplateKey) && + isVisualTemplateCompatible(getVisualTemplate(configuredVisualTemplateKey)!, templateKey) + ? configuredVisualTemplateKey + : getDefaultVisualTemplateKey(templateKey); const visualManifest = getVisualTemplateManifest(visualTemplateKey); - if (!visualManifest) throw new BadRequestException("视觉模板不存在"); + const visualTemplate = getVisualTemplate(visualTemplateKey); + if ( + !visualManifest || + !visualTemplate || + !isVisualTemplateCompatible(visualTemplate, templateKey) + ) + throw new BadRequestException("当前视觉模板不适配行业模板"); const templatePackageSnapshot = { schemaVersion: "1.0", version: template.version, @@ -39,6 +69,14 @@ export class TemplateWorkspaceService { capabilities: template.capabilities, }; return this.prisma.$transaction(async (tx) => { + if (brandConfig.visualTemplateKey === undefined) { + await tx.brandProfile.update({ + where: { id: brandId }, + data: { + config: { ...brandConfig, visualTemplateKey }, + }, + }); + } const installation = await tx.brandTemplateInstallation.create({ data: { brandId, diff --git a/apps/api/test/booking.service.test.ts b/apps/api/test/booking.service.test.ts index 90c9985..b032ace 100644 --- a/apps/api/test/booking.service.test.ts +++ b/apps/api/test/booking.service.test.ts @@ -2,6 +2,8 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { BadRequestException, NotFoundException } from "@nestjs/common"; import { BookingService } from "../src/booking.service.js"; +import type { PrismaService } from "../src/prisma.service.js"; +import type { BrandReleaseService } from "../src/brand-release.service.js"; const brandId = "brand-1"; const customerId = "customer-1"; @@ -11,20 +13,20 @@ const offering = { priceAmount: 2800, }; -function createPrisma(overrides: Record = {}): any { +function createPrisma(overrides: Record = {}): PrismaService { return { offering: { - findMany: async () => [offering], + count: async () => 1, }, booking: { - create: async ({ data }: any) => ({ + create: async ({ data }: { data: { estimatedAmount: number | null } }) => ({ bookingNo: "AC-test", status: "received", estimatedAmount: data.estimatedAmount, createdAt: new Date(), }), findFirst: async () => null, - update: async ({ data }: any) => ({ status: data.status }), + update: async ({ data }: { data: { status: string } }) => ({ status: data.status }), findMany: async () => [], count: async () => 0, }, @@ -32,12 +34,20 @@ function createPrisma(overrides: Record = {}): any { bookingTag: { deleteMany: {}, createMany: {} }, $transaction: async (callback: (tx: unknown) => unknown) => callback(undefined), ...overrides, - }; + } as unknown as PrismaService; +} + +function createService(prisma = createPrisma()): BookingService { + const releases = { + getPublishedSnapshot: async () => ({ offerings: [{ ...offering, isEnabled: true }] }), + publishedOfferingIds: () => new Set([offering.id]), + } as unknown as BrandReleaseService; + return new BookingService(prisma, releases); } test("创建普通套餐订单时保存价格快照和预计金额", async () => { const prisma = createPrisma(); - const result = await new BookingService(prisma).create(brandId, customerId, { + const result = await createService(prisma).create(brandId, customerId, { requestType: "package", customerName: "陈同学", wechatId: "wx-test", @@ -51,7 +61,7 @@ test("创建普通套餐订单时保存价格快照和预计金额", async () => test("普通套餐不能在没有明细时创建", async () => { await assert.rejects( () => - new BookingService(createPrisma()).create(brandId, customerId, { + createService().create(brandId, customerId, { requestType: "package", customerName: "陈同学", phone: "13800000000", @@ -69,14 +79,14 @@ test("客户只能取消自己的 received 订单", async () => { }, }); await assert.rejects( - () => new BookingService(prisma).cancelForCustomer(brandId, customerId, "booking-1"), + () => createService(prisma).cancelForCustomer(brandId, customerId, "booking-1"), (error: unknown) => error instanceof BadRequestException, ); }); test("取消不存在或不属于当前客户的订单返回不存在", async () => { await assert.rejects( - () => new BookingService(createPrisma()).cancelForCustomer(brandId, customerId, "missing"), + () => createService().cancelForCustomer(brandId, customerId, "missing"), (error: unknown) => error instanceof NotFoundException, ); }); @@ -91,15 +101,15 @@ test("订单状态只能按定义的状态机流转", async () => { workflowKey: "booking.basic", workflowVersion: "1.0.0", }), - update: async ({ data }: any) => data, + update: async ({ data }: { data: { status: string } }) => data, }, - $transaction: async (callback: (tx: any) => unknown) => + $transaction: async (callback: (tx: unknown) => unknown) => callback({ - booking: { update: async ({ data }: any) => data }, + booking: { update: async ({ data }: { data: { status: string } }) => data }, bookingStateTransition: { create: async () => undefined }, }), }); - const bookings = new BookingService(prisma); + const bookings = createService(prisma); assert.equal( (await bookings.updateStatus(brandId, "booking-1", "contacting")).status, "contacting", @@ -116,7 +126,7 @@ test("更新订单标签时拒绝其他品牌的标签", async () => { tag: { findMany: async () => [] }, }); await assert.rejects( - () => new BookingService(prisma).updateTags(brandId, "booking-1", ["foreign-tag"]), + () => createService(prisma).updateTags(brandId, "booking-1", ["foreign-tag"]), (error: unknown) => error instanceof BadRequestException, ); }); diff --git a/apps/api/test/http.integration.test.js b/apps/api/test/http.integration.test.js index 058df55..fdbb83b 100644 --- a/apps/api/test/http.integration.test.js +++ b/apps/api/test/http.integration.test.js @@ -2,7 +2,8 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; import { PrismaClient } from "@prisma/client"; import { createApp } from "../dist/main.js"; -import { signIdentity } from "../dist/auth.js"; +import { readIdentity, signIdentity } from "../dist/auth.js"; +import { WechatAuthService } from "../dist/wechat-auth.js"; let app; const prisma = new PrismaClient(); @@ -20,11 +21,183 @@ before(async () => { after(async () => { await app.close(); + await prisma.brandRelease.deleteMany({ where: { brandId } }); await prisma.booking.deleteMany({ where: { id: { in: createdBookingIds } } }); await prisma.customerUser.deleteMany({ where: { openid } }); await prisma.$disconnect(); }); +test("admin release lifecycle is authorized, brand-scoped, and versioned", async () => { + const missing = await request("/admin/releases"); + assert.equal(missing.statusCode, 401); + assert.equal((await request("/admin/releases/readiness")).statusCode, 401); + + const customer = await request("/admin/releases", { + headers: { authorization: `Bearer ${customerToken}` }, + }); + assert.equal(customer.statusCode, 403); + assert.equal( + ( + await request("/admin/releases/readiness", { + headers: { authorization: `Bearer ${customerToken}` }, + }) + ).statusCode, + 403, + ); + + const login = await request("/admin/session/login", { + method: "POST", + payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD }, + }); + assert.equal(login.statusCode, 201); + const adminToken = JSON.parse(login.body).token; + const readiness = await request("/admin/releases/readiness", { + headers: { authorization: `Bearer ${adminToken}` }, + }); + assert.equal(readiness.statusCode, 200); + assert.equal(JSON.parse(readiness.body).ready, true); + const enabledForms = await prisma.inquiryForm.findMany({ + where: { brandId, isEnabled: true }, + select: { id: true }, + }); + await prisma.inquiryForm.updateMany({ where: { brandId }, data: { isEnabled: false } }); + try { + const noForms = await request("/admin/releases/readiness", { + headers: { authorization: `Bearer ${adminToken}` }, + }); + assert.equal(JSON.parse(noForms.body).ready, false); + assert.equal( + JSON.parse(noForms.body).checks.find((check) => check.key === "forms")?.passed, + false, + ); + } finally { + await prisma.inquiryForm.updateMany({ + where: { id: { in: enabledForms.map((form) => form.id) } }, + data: { isEnabled: true }, + }); + } + const originalBrand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } }); + await prisma.brandProfile.update({ where: { id: brandId }, data: { tagline: "" } }); + const incomplete = await request("/admin/releases/readiness", { + headers: { authorization: `Bearer ${adminToken}` }, + }); + assert.equal(JSON.parse(incomplete.body).ready, false); + assert.equal( + ( + await request("/admin/releases/publish", { + method: "POST", + headers: { authorization: `Bearer ${adminToken}` }, + payload: {}, + }) + ).statusCode, + 400, + ); + await prisma.brandProfile.update({ + where: { id: brandId }, + data: { tagline: "集成测试待发布标语" }, + }); + const beforePublish = JSON.parse((await request("/public/workspace")).body); + assert.equal(beforePublish.brand.tagline, originalBrand.tagline); + const published = await request("/admin/releases/publish", { + method: "POST", + headers: { authorization: `Bearer ${adminToken}` }, + payload: { note: "集成测试发布" }, + }); + assert.equal(published.statusCode, 201); + const first = JSON.parse(published.body); + assert.equal(first.version, 2); + assert.equal(first.status, "published"); + assert.equal( + JSON.parse((await request("/public/workspace")).body).brand.tagline, + "集成测试待发布标语", + ); + const draftOnlyForm = await prisma.inquiryForm.create({ + data: { + brandId, + name: "未发布的草稿表单", + fieldsSnapshot: [{ key: "phone", type: "phone", label: "手机", required: true }], + }, + }); + const draftSubmission = await request("/customer/inquiry-submissions", { + method: "POST", + headers: { authorization: `Bearer ${customerToken}` }, + payload: { formId: draftOnlyForm.id, values: { phone: "13871112222" } }, + }); + assert.equal(draftSubmission.statusCode, 400); + + const listed = await request("/admin/releases", { + headers: { authorization: `Bearer ${adminToken}` }, + }); + assert.equal(listed.statusCode, 200); + assert.equal(JSON.parse(listed.body)[0].version, 2); + + const concurrent = await Promise.all( + ["并发发布 A", "并发发布 B"].map((note) => + request("/admin/releases/publish", { + method: "POST", + headers: { authorization: `Bearer ${adminToken}` }, + payload: { note }, + }), + ), + ); + assert.deepEqual( + concurrent.map((item) => item.statusCode), + [201, 201], + ); + assert.deepEqual( + concurrent.map((item) => JSON.parse(item.body).version).sort((a, b) => a - b), + [3, 4], + ); + + const rolledBack = await request("/admin/releases/1/rollback", { + method: "POST", + headers: { authorization: `Bearer ${adminToken}` }, + }); + assert.equal(rolledBack.statusCode, 201); + assert.equal(JSON.parse(rolledBack.body).version, 5); + assert.equal( + JSON.parse((await request("/public/workspace")).body).brand.tagline, + originalBrand.tagline, + ); + + const revoked = await request("/admin/releases/revoke", { + method: "POST", + headers: { authorization: `Bearer ${adminToken}` }, + payload: {}, + }); + assert.equal(revoked.statusCode, 201); + assert.equal(JSON.parse(revoked.body).status, "revoked"); + assert.equal(JSON.parse(revoked.body).revokedBy, readIdentity(adminToken).subject); + const unpublished = JSON.parse((await request("/public/workspace")).body); + assert.equal(unpublished.publication.status, "unpublished"); + assert.equal(unpublished.brand, null); + assert.deepEqual(unpublished.offerings, []); + assert.deepEqual(JSON.parse((await request("/public/offerings")).body), []); + const revokedSubmission = await request("/customer/inquiry-submissions", { + method: "POST", + headers: { authorization: `Bearer ${customerToken}` }, + payload: { formId: draftOnlyForm.id, values: { phone: "13871112222" } }, + }); + assert.equal(revokedSubmission.statusCode, 400); + const revokedBooking = await request("/customer/bookings", { + method: "POST", + headers: { authorization: `Bearer ${customerToken}` }, + payload: { + requestType: "inquiry", + customerName: "集成测试客户", + wechatId: "integration-wechat", + contactPreference: "wechat", + }, + }); + assert.equal(revokedBooking.statusCode, 400); + await prisma.inquiryForm.delete({ where: { id: draftOnlyForm.id } }); + await prisma.brandProfile.update({ + where: { id: brandId }, + data: { tagline: originalBrand.tagline }, + }); + assert.equal((await publishReleaseForTests("恢复集成测试基线")).statusCode, 201); +}); + async function request(url, options = {}) { return app .getHttpAdapter() @@ -32,6 +205,19 @@ async function request(url, options = {}) { .inject({ method: "GET", url, ...options }); } +async function publishReleaseForTests(note = "集成测试发布") { + const login = await request("/admin/session/login", { + method: "POST", + payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD }, + }); + const token = JSON.parse(login.body).token; + return request("/admin/releases/publish", { + method: "POST", + headers: { authorization: `Bearer ${token}` }, + payload: { note }, + }); +} + test("health and public content are available without authentication", async () => { const health = await request("/health"); assert.equal(health.statusCode, 200); @@ -68,6 +254,91 @@ test("health and public content are available without authentication", async () assert.equal(missingSlug.statusCode, 404); }); +test("visual template compatibility is enforced by catalog, preview, and brand switching", async () => { + const catalog = await request("/public/templates"); + assert.equal(catalog.statusCode, 200); + const visuals = JSON.parse(catalog.body).visuals; + assert.deepEqual( + visuals.find((visual) => visual.key === "linjing-editorial").supportedIndustryTemplates, + ["personal", "doors"], + ); + const incompatiblePreview = await request( + "/public/templates/preview?industry=food&visual=linjing-editorial", + ); + assert.equal(incompatiblePreview.statusCode, 400); + const compatiblePreview = await request( + "/public/templates/preview?industry=doors&visual=linjing-editorial", + ); + assert.equal(compatiblePreview.statusCode, 200); + const login = await request("/admin/session/login", { + method: "POST", + payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD }, + }); + const token = JSON.parse(login.body).token; + const compatibleSwitch = await request("/admin/config/brand", { + method: "PATCH", + headers: { authorization: `Bearer ${token}` }, + payload: { config: { visualTemplateKey: "acheng-campus-food" } }, + }); + assert.equal(compatibleSwitch.statusCode, 200); +}); + +test("seeded public workspaces keep personal, food, and doors brands isolated", async () => { + const expected = [ + { + slug: "linran-brand", + id: "00000000-0000-0000-0000-000000000003", + templateKey: "personal", + founder: "林然", + offeringKind: "service", + categoryLabel: "策略咨询", + }, + { + slug: "default-brand", + id: "00000000-0000-0000-0000-000000000001", + templateKey: "food", + founder: "阿成", + offeringKind: "package", + categoryLabel: "套餐", + }, + { + slug: "linjing-doors", + id: "00000000-0000-0000-0000-000000000002", + templateKey: "doors", + founder: "林叙安 (Lin XUAN)", + offeringKind: "product", + categoryLabel: "入户大门", + }, + ]; + const workspaces = await Promise.all( + expected.map(async (item) => { + const response = await request(`/public/workspace?brandSlug=${item.slug}`); + assert.equal(response.statusCode, 200); + const workspace = JSON.parse(response.body); + assert.equal(workspace.brand.id, item.id); + assert.equal(workspace.template.key, item.templateKey); + assert.ok(workspace.visualTemplate?.key); + assert.ok(workspace.visualTemplateManifest?.pages?.length > 0); + assert.equal(workspace.brand.founder, item.founder); + assert.ok(workspace.trustContent.length > 0); + assert.ok(workspace.trustPresentation); + assert.ok(workspace.inquiryForm); + assert.equal(workspace.inquiryForm.isEnabled, true); + assert.ok(workspace.offerings.length > 0); + assert.ok(workspace.offerings.every((offering) => offering.brandId === undefined)); + assert.ok( + workspace.offerings.some( + (offering) => + offering.kind === item.offeringKind && + offering.presentation?.categoryLabel === item.categoryLabel, + ), + ); + return workspace; + }), + ); + assert.equal(new Set(workspaces.map((workspace) => workspace.brand.id)).size, 3); +}); + test("public workspace uses brand-scoped capability installations and preserves status", async () => { await prisma.capabilityInstallation.deleteMany({ where: { brandId } }); const installation = await prisma.capabilityInstallation.create({ @@ -80,6 +351,8 @@ test("public workspace uses brand-scoped capability installations and preserves }, }); try { + const published = await publishReleaseForTests(); + assert.equal(published.statusCode, 201); const response = await request("/public/workspace"); assert.equal(response.statusCode, 200); const body = JSON.parse(response.body); @@ -125,6 +398,135 @@ test("admin can update declared capability status with authorization and audit", await prisma.capabilityAuditLog.deleteMany({ where: { brandId } }); }); +test("editor membership can manage brand content but cannot change system settings", async () => { + const login = await request("/admin/session/login", { + method: "POST", + payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD }, + }); + const token = JSON.parse(login.body).token; + const identity = readIdentity(token); + const membership = await prisma.brandMembership.findUnique({ + where: { adminUserId_brandId: { adminUserId: identity.subject, brandId } }, + }); + assert.ok(membership); + await prisma.brandMembership.update({ where: { id: membership.id }, data: { role: "editor" } }); + try { + const offerings = await request("/admin/workspace/offerings", { + headers: { authorization: `Bearer ${token}` }, + }); + assert.equal(offerings.statusCode, 200); + const capabilities = await request("/admin/workspace/capabilities", { + headers: { authorization: `Bearer ${token}` }, + }); + assert.equal(capabilities.statusCode, 403); + const visualHistory = await request("/admin/config/visual-template/history", { + headers: { authorization: `Bearer ${token}` }, + }); + assert.equal(visualHistory.statusCode, 403); + const visualUpdate = await request("/admin/config/brand", { + method: "PATCH", + headers: { authorization: `Bearer ${token}` }, + payload: { config: { visualTemplateKey: "unknown-visual" } }, + }); + assert.equal(visualUpdate.statusCode, 403); + } finally { + await prisma.brandMembership.update({ + where: { id: membership.id }, + data: { role: membership.role }, + }); + } +}); + +test("owner can manage brand members without removing the final owner", async () => { + const login = await request("/admin/session/login", { + method: "POST", + payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD }, + }); + const token = JSON.parse(login.body).token; + const identity = readIdentity(token); + const members = await request("/admin/brands/members", { + headers: { authorization: `Bearer ${token}` }, + }); + assert.equal(members.statusCode, 200); + const current = JSON.parse(members.body).find((item) => item.adminUserId === identity.subject); + assert.ok(current); + const selfDisable = await request(`/admin/brands/members/${current.id}`, { + method: "PATCH", + headers: { authorization: `Bearer ${token}` }, + payload: { isEnabled: false }, + }); + assert.equal(selfDisable.statusCode, 400); + const created = await request("/admin/brands/members", { + method: "POST", + headers: { authorization: `Bearer ${token}` }, + payload: { + username: `editor-${Date.now()}`, + displayName: "测试编辑", + password: "test-password-123", + role: "editor", + }, + }); + assert.equal(created.statusCode, 201); + const guestMembership = JSON.parse(created.body); + try { + const updated = await request(`/admin/brands/members/${guestMembership.id}`, { + method: "PATCH", + headers: { authorization: `Bearer ${token}` }, + payload: { isEnabled: false }, + }); + assert.equal(updated.statusCode, 200); + assert.equal(JSON.parse(updated.body).isEnabled, false); + } finally { + await prisma.brandMembership.delete({ where: { id: guestMembership.id } }); + await prisma.adminUser.delete({ where: { id: guestMembership.adminUser.id } }); + } +}); + +test("manually created member must change the initial password before normal use", async () => { + const ownerLogin = await request("/admin/session/login", { + method: "POST", + payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD }, + }); + const ownerToken = JSON.parse(ownerLogin.body).token; + const username = `first-login-${Date.now()}`; + const created = await request("/admin/brands/members", { + method: "POST", + headers: { authorization: `Bearer ${ownerToken}` }, + payload: { + username, + displayName: "首次登录测试", + password: "initial-password-123", + role: "editor", + }, + }); + assert.equal(created.statusCode, 201); + const member = JSON.parse(created.body); + assert.equal(member.adminUser.mustChangePassword, undefined); + try { + const login = await request("/admin/session/login", { + method: "POST", + payload: { username, password: "initial-password-123" }, + }); + assert.equal(login.statusCode, 201); + assert.equal(JSON.parse(login.body).mustChangePassword, true); + const changed = await request("/admin/session/change-password", { + method: "POST", + headers: { authorization: `Bearer ${JSON.parse(login.body).token}` }, + payload: { currentPassword: "initial-password-123", newPassword: "updated-password-123" }, + }); + assert.equal(changed.statusCode, 201); + const updatedLogin = await request("/admin/session/login", { + method: "POST", + payload: { username, password: "updated-password-123" }, + }); + assert.equal(updatedLogin.statusCode, 201); + assert.equal(JSON.parse(updatedLogin.body).mustChangePassword, false); + } finally { + await prisma.brandMembership.delete({ where: { id: member.id } }); + await prisma.adminUser.delete({ where: { id: member.adminUser.id } }); + } +}); + test("admin can install optional quote capability without industry-specific branching", async () => { const login = await request("/admin/session/login", { method: "POST", @@ -138,6 +540,7 @@ test("admin can install optional quote capability without industry-specific bran }); assert.equal(response.statusCode, 200); assert.equal(JSON.parse(response.body).capabilityKey, "quote-request"); + assert.equal((await publishReleaseForTests()).statusCode, 201); const workspace = await request("/public/workspace"); assert.ok(JSON.parse(workspace.body).plugins.some((plugin) => plugin.key === "quote-request")); await prisma.capabilityInstallation.deleteMany({ @@ -204,16 +607,13 @@ test("admin can install doors industry template through the shared runtime contr const workspace = await request("/public/workspace"); assert.equal(workspace.statusCode, 200); const body = JSON.parse(workspace.body); - assert.equal(body.template.key, "doors"); - assert.ok(body.modules.some((item) => item.type === "offering")); - assert.ok(body.modules.some((item) => item.type === "inquiry")); - assert.deepEqual( - body.runtimeCapabilities.map((item) => item.key), - ["offerings", "inquiry"], - ); - assert.ok(Array.isArray(body.offerings)); - assert.ok(Array.isArray(body.fields)); - assert.ok(body.fields.every((field) => typeof field.key === "string")); + assert.equal(body.template.key, "food"); + assert.equal(body.publication.status, "published"); + const samplePreview = await request("/admin/workspace/sample-content/preview", { + headers: { authorization: `Bearer ${token}` }, + }); + assert.equal(samplePreview.statusCode, 200); + assert.equal(JSON.parse(samplePreview.body).templateKey, "doors"); } finally { await prisma.brandFieldDefinition.deleteMany({ where: { brandId } }); await prisma.brandModule.deleteMany({ where: { brandId } }); @@ -222,6 +622,8 @@ test("admin can install doors industry template through the shared runtime contr }); test("admin can preview and import sample content idempotently", async () => { + const originalBrand = await prisma.brandProfile.findUnique({ where: { id: brandId } }); + await prisma.brandProfile.update({ where: { id: brandId }, data: { templateKey: "doors" } }); await prisma.offering.deleteMany({ where: { brandId, @@ -262,6 +664,10 @@ test("admin can preview and import sample content idempotently", async () => { }); await prisma.brandFieldDefinition.deleteMany({ where: { brandId, source: "sample" } }); await prisma.capabilityAuditLog.deleteMany({ where: { brandId, capabilityKey: "doors" } }); + await prisma.brandProfile.update({ + where: { id: brandId }, + data: { templateKey: originalBrand?.templateKey ?? "food" }, + }); }); test("admin can install a template and public workspace exposes enabled configuration", async () => { @@ -284,7 +690,7 @@ test("admin can install a template and public workspace exposes enabled configur }); assert.equal(installed.statusCode, 201); assert.equal(JSON.parse(installed.body).template.key, "personal"); - assert.equal(JSON.parse(installed.body).visualTemplate.key, "minimal-neutral"); + assert.equal(JSON.parse(installed.body).visualTemplate.key, "linjing-editorial"); assert.equal(JSON.parse(installed.body).installation.configSnapshot.schemaVersion, "1.0"); try { const previewUnauthorized = await request("/admin/workspace/template/preview"); @@ -324,19 +730,11 @@ test("admin can install a template and public workspace exposes enabled configur assert.equal(publicWorkspace.statusCode, 200); const workspaceBody = JSON.parse(publicWorkspace.body); assert.equal(workspaceBody.contractVersion, "1.0"); - assert.equal(workspaceBody.template.key, "personal"); - assert.deepEqual(workspaceBody.capabilities, [ - { key: "offerings", version: "1.0.0", status: "enabled", config: {} }, - { key: "inquiry", version: "1.0.0", status: "enabled", config: {} }, - ]); - assert.deepEqual(workspaceBody.runtimeCapabilities, [ - { key: "offerings", version: "1.0.0", status: "enabled", config: {} }, - { key: "inquiry", version: "1.0.0", status: "enabled", config: {} }, - ]); - assert.equal(workspaceBody.modules.length, 5); - assert.equal(workspaceBody.runtimeModules.length, 5); + assert.equal(workspaceBody.template.key, "food"); + assert.ok(workspaceBody.modules.length > 0); + assert.equal(workspaceBody.modules.length, workspaceBody.runtimeModules.length); assert.equal(workspaceBody.runtimeModules[0].schemaVersion, "1.0"); - assert.equal(workspaceBody.inquiryForm, null); + assert.ok(workspaceBody.inquiryForm); const conflict = await request("/admin/workspace/install", { method: "POST", headers: { authorization: `Bearer ${token}` }, @@ -424,18 +822,18 @@ test("admin visual template selection is reflected in public runtime workspace", const updated = await request("/admin/config/brand", { method: "PATCH", headers: { authorization: `Bearer ${token}` }, - payload: { config: { visualTemplateKey: "minimal-neutral" } }, + payload: { config: { visualTemplateKey: "acheng-campus-food" } }, }); assert.equal(updated.statusCode, 200); try { const runtime = await request("/public/workspace"); assert.equal(runtime.statusCode, 200); const body = JSON.parse(runtime.body); - assert.equal(body.visualTemplate.key, "minimal-neutral"); + assert.equal(body.visualTemplate.key, "acheng-campus-food"); assert.equal(body.visualTemplate.version, "1.0.0"); - assert.equal(body.theme.colors.accent, "#4B5563"); - assert.equal(body.visualTemplate.variants.hero, "minimal"); - assert.equal(body.visualTemplateManifest.key, "minimal-neutral"); + assert.equal(body.theme.colors.accent, "#E87532"); + assert.equal(body.visualTemplate.variants.hero, "stall-board"); + assert.equal(body.visualTemplateManifest.key, "acheng-campus-food"); assert.equal(body.visualTemplateManifest.brandFirst, true); assert.deepEqual( body.visualTemplateManifest.pages.map((page) => page.key), @@ -450,6 +848,50 @@ test("admin visual template selection is reflected in public runtime workspace", } }); +test("public workspace exposes declared brand and trust presentation data", async () => { + const doorsBrand = await prisma.brandProfile.findUnique({ where: { slug: "linjing-doors" } }); + assert.ok(doorsBrand); + const original = doorsBrand; + await prisma.brandProfile.update({ + where: { id: doorsBrand.id }, + data: { + config: { + ...(original?.config && typeof original.config === "object" ? original.config : {}), + homeHero: { title: "尚未发布的集成测试首页标题" }, + }, + }, + }); + try { + const runtime = await request("/public/workspace?brandSlug=linjing-doors"); + assert.equal(runtime.statusCode, 200); + const body = JSON.parse(runtime.body); + assert.equal(body.brand.founder, "林叙安 (Lin XUAN)"); + assert.equal(body.brand.title, "高端门系统建筑研造主理人"); + assert.notEqual(body.brand.homeHero.title, "尚未发布的集成测试首页标题"); + assert.equal(body.trustPresentation.stats.length, 4); + assert.equal(body.trustPresentation.pillars.length, 3); + assert.equal(body.trustPresentation.serviceFlow.length, 6); + assert.equal(body.brand.profilePresentation.coverage.length, 2); + assert.equal(body.brand.profilePresentation.warranty.length, 4); + assert.equal(body.brand.visualPresentation.home.proofTitle, "14 年,只做门与空间的关系"); + assert.equal(body.brand.visualPresentation.inquiry.submitLabel, "提交量房与定制评估需求"); + assert.equal(body.brand.visualPresentation.records.emptyAction, "开始咨询"); + assert.equal(body.offerings.length, 4); + assert.ok(body.offerings.every((offering) => offering.presentation.heroImage)); + assert.ok( + body.offerings.every((offering) => offering.presentation.details.materialsList.length), + ); + const doorType = body.inquiryForms[0].fields.find((field) => field.key === "doorType"); + assert.equal(doorType.options.length, 5); + assert.equal(doorType.options[0].value, "入户大门(防暴铸铜 / 实木)"); + } finally { + await prisma.brandProfile.update({ + where: { id: doorsBrand.id }, + data: { config: original?.config ?? {} }, + }); + } +}); + test("admin can create and version an inquiry form", async () => { const login = await request("/admin/session/login", { method: "POST", @@ -537,6 +979,7 @@ test("admin can create and version an inquiry form", async () => { }); assert.equal(blockedCapability.statusCode, 400); await prisma.capabilityInstallation.delete({ where: { id: capability.id } }); + assert.equal((await publishReleaseForTests()).statusCode, 201); const publicForm = await request(`/public/inquiry-forms/${id}`); assert.equal(publicForm.statusCode, 200); const publicOffering = await request(`/public/offerings/${offering.id}`); @@ -554,6 +997,13 @@ test("admin can create and version an inquiry form", async () => { (form) => form.key === id, ); assert.deepEqual(runtimeForm.fields[1].options, [{ label: "微信", value: "wechat" }]); + await prisma.inquiryForm.update({ + where: { id }, + data: { + version: 3, + fieldsSnapshot: [{ key: "draft_only", type: "text", label: "草稿字段", required: true }], + }, + }); const submission = await request("/customer/inquiry-submissions", { method: "POST", headers: { authorization: `Bearer ${customerToken}` }, @@ -561,6 +1011,7 @@ test("admin can create and version an inquiry form", async () => { }); assert.equal(submission.statusCode, 201); assert.equal(JSON.parse(submission.body).formVersion, 2); + assert.equal(JSON.parse(submission.body).fieldsSnapshot[0].key, "budget"); assert.equal(JSON.parse(submission.body).offeringId, offering.id); assert.deepEqual(JSON.parse(submission.body).values, { budget: 1000 }); assert.equal((await request("/customer/inquiry-submissions")).statusCode, 401); @@ -687,10 +1138,10 @@ test("admin can manage offerings and public endpoint hides disabled offerings", assert.equal(listed.statusCode, 200); assert.ok(JSON.parse(listed.body).some((item) => item.id === id)); const publicItem = await request(`/public/offerings/${id}`); - assert.equal(publicItem.statusCode, 200); + assert.equal(publicItem.statusCode, 400); const publicList = await request("/public/offerings"); assert.equal(publicList.statusCode, 200); - assert.ok(JSON.parse(publicList.body).some((item) => item.id === id)); + assert.ok(!JSON.parse(publicList.body).some((item) => item.id === id)); const updated = await request(`/admin/workspace/offerings/${id}`, { method: "PATCH", headers: { authorization: `Bearer ${token}` }, @@ -705,7 +1156,7 @@ test("admin can manage offerings and public endpoint hides disabled offerings", payload: { isEnabled: true }, }); assert.equal(reenabled.statusCode, 200); - assert.equal((await request(`/public/offerings/${id}`)).statusCode, 200); + assert.equal((await request(`/public/offerings/${id}`)).statusCode, 400); } finally { const deleted = await request(`/admin/workspace/offerings/${id}`, { method: "DELETE", @@ -936,7 +1387,7 @@ test("admin can read and update brand and service configuration", async () => { const projectedService = JSON.parse(publicServices.body).find( (item) => item.id === serviceBefore.id, ); - assert.equal(projectedService.priceText, "集成测试价格"); + assert.equal(projectedService.priceText, serviceBefore.priceText); const listedServices = await request("/admin/workspace/offerings", { headers: { authorization: `Bearer ${adminToken}` }, @@ -981,6 +1432,57 @@ test("admin can read and update brand and service configuration", async () => { } }); +test("admin can update user-facing brand presentation without replacing other config", async () => { + assert.equal( + (await request("/admin/config/presentation", { method: "PATCH", payload: { home: {} } })) + .statusCode, + 401, + ); + assert.equal( + ( + await request("/admin/config/presentation", { + method: "PATCH", + headers: { authorization: `Bearer ${customerToken}` }, + payload: { home: {} }, + }) + ).statusCode, + 403, + ); + const login = await request("/admin/session/login", { + method: "POST", + payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD }, + }); + const token = JSON.parse(login.body).token; + const brand = await prisma.brandProfile.findUnique({ where: { id: brandId } }); + assert.ok(brand); + const originalConfig = brand.config; + try { + const response = await request("/admin/config/presentation", { + method: "PATCH", + headers: { authorization: `Bearer ${token}` }, + payload: { + identity: { founder: "可编辑主理人", title: "品牌主理人", ignoredNumber: 123 }, + home: { proofTitle: "用户可编辑的信任标题", ignoredNumber: 123 }, + inquiry: { submitLabel: "开始沟通" }, + }, + }); + assert.equal(response.statusCode, 200); + const presentation = JSON.parse(response.body).visualPresentation; + assert.equal(presentation.home.proofTitle, "用户可编辑的信任标题"); + assert.equal(presentation.home.ignoredNumber, undefined); + assert.equal(presentation.inquiry.submitLabel, "开始沟通"); + const runtime = await request("/public/workspace"); + assert.notEqual(JSON.parse(runtime.body).brand.founder, "可编辑主理人"); + assert.notEqual(JSON.parse(runtime.body).brand.title, "品牌主理人"); + assert.notEqual( + JSON.parse(runtime.body).brand.visualPresentation.home.proofTitle, + "用户可编辑的信任标题", + ); + } finally { + await prisma.brandProfile.update({ where: { id: brandId }, data: { config: originalConfig } }); + } +}); + test("admin can manage trust content", async () => { const login = await request("/admin/session/login", { method: "POST", @@ -1004,7 +1506,7 @@ test("admin can manage trust content", async () => { const publicContent = await request("/public/trust-content"); assert.equal(publicContent.statusCode, 200); const publicItems = JSON.parse(publicContent.body); - assert.ok(publicItems.some((item) => item.id === id)); + assert.ok(!publicItems.some((item) => item.id === id)); assert.ok(!publicItems.some((item) => item.id === JSON.parse(draft.body).id)); try { const list = await request("/admin/config/trust-content", { @@ -1047,6 +1549,33 @@ test("wechat login validates the request DTO before exchanging the code", async assert.equal(response.statusCode, 400); }); +test("wechat login creates a customer session for the requested brand", async () => { + const doorsBrand = await prisma.brandProfile.findUnique({ where: { slug: "linjing-doors" } }); + assert.ok(doorsBrand); + const sessionOpenid = `doors-login-${Date.now()}`; + const wechatAuth = app.get(WechatAuthService); + const originalExchangeCode = wechatAuth.exchangeCode; + wechatAuth.exchangeCode = async () => ({ openid: sessionOpenid }); + try { + const response = await request("/customer/session/wechat?brandSlug=linjing-doors", { + method: "POST", + payload: { code: "test-code" }, + }); + assert.equal(response.statusCode, 201); + const identity = readIdentity(JSON.parse(response.body).token); + assert.equal(identity.brandId, doorsBrand.id); + assert.equal(identity.role, "customer"); + assert.ok( + await prisma.customerUser.findUnique({ + where: { brandId_openid: { brandId: doorsBrand.id, openid: sessionOpenid } }, + }), + ); + } finally { + wechatAuth.exchangeCode = originalExchangeCode; + await prisma.customerUser.deleteMany({ where: { openid: sessionOpenid } }); + } +}); + test("customer booking DTO rejects incomplete package requests", async () => { const response = await request("/customer/bookings", { method: "POST", @@ -1087,6 +1616,16 @@ test("customer can create and cancel a package booking", async () => { where: { brandId, isEnabled: true, priceAmount: { not: null } }, }); assert.ok(service); + const release = await prisma.brandRelease.findFirst({ + where: { brandId, status: "published" }, + orderBy: { version: "desc" }, + }); + const publishedOffering = release?.snapshot?.offerings?.find?.((item) => item.id === service.id); + assert.ok(publishedOffering); + await prisma.offering.update({ + where: { id: service.id }, + data: { priceAmount: service.priceAmount + 500, name: `${service.name}草稿` }, + }); const created = await request("/customer/bookings", { method: "POST", headers: { authorization: `Bearer ${customerToken}` }, @@ -1098,14 +1637,20 @@ test("customer can create and cancel a package booking", async () => { items: [{ offeringId: service.id, quantity: 2 }], }, }); + await prisma.offering.update({ + where: { id: service.id }, + data: { priceAmount: service.priceAmount, name: service.name }, + }); assert.equal(created.statusCode, 201); const createdBody = JSON.parse(created.body); - assert.equal(createdBody.estimatedAmount, service.priceAmount * 2); + assert.equal(createdBody.estimatedAmount, publishedOffering.priceAmount * 2); const booking = await prisma.booking.findUnique({ where: { bookingNo: createdBody.bookingNo } }); assert.ok(booking); assert.equal(booking.workflowKey, "booking.basic"); assert.equal(booking.currentState, "received"); assert.equal(booking.offeringId, service.id); + const bookingItem = await prisma.bookingItem.findFirst({ where: { bookingId: booking.id } }); + assert.equal(bookingItem?.serviceNameSnapshot, publishedOffering.name); const initialTransitions = await prisma.bookingStateTransition.findMany({ where: { bookingId: booking.id }, }); diff --git a/apps/api/test/run-integration.cjs b/apps/api/test/run-integration.cjs new file mode 100644 index 0000000..62fb7b8 --- /dev/null +++ b/apps/api/test/run-integration.cjs @@ -0,0 +1,40 @@ +const { randomBytes } = require("node:crypto"); +const { spawnSync } = require("node:child_process"); +const { PrismaClient } = require("@prisma/client"); + +const databaseUrl = process.env.DATABASE_URL; +if (!databaseUrl) throw new Error("DATABASE_URL is required for integration tests"); + +const schema = `pb_test_${randomBytes(8).toString("hex")}`; +const testUrl = new URL(databaseUrl); +testUrl.searchParams.set("schema", schema); +const testEnvironment = { ...process.env, DATABASE_URL: testUrl.toString(), NODE_ENV: "test" }; +const administrator = new PrismaClient(); + +function run(command, args) { + const result = spawnSync(command, args, { stdio: "inherit", env: testEnvironment }); + if (result.error) throw result.error; + return result.status ?? 1; +} + +async function main() { + let created = false; + let status = 1; + try { + await administrator.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`); + created = true; + if (run("pnpm", ["exec", "prisma", "migrate", "deploy"]) !== 0) return status; + if (run("pnpm", ["db:seed"]) !== 0) return status; + status = run(process.execPath, ["--test", "test/http.integration.test.js"]); + return status; + } finally { + if (created) await administrator.$executeRawUnsafe(`DROP SCHEMA "${schema}" CASCADE`); + await administrator.$disconnect(); + process.exitCode = status; + } +} + +main().catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/apps/miniapp/app.js b/apps/miniapp/app.js index ed622fd..16e8823 100644 --- a/apps/miniapp/app.js +++ b/apps/miniapp/app.js @@ -1,4 +1,4 @@ -const DEFAULT_API_BASE_URL = "http://172.16.6.123:3001"; +const DEFAULT_API_BASE_URL = "http://localhost:3001"; const DEFAULT_BRAND_SLUG = "default-brand"; App({ diff --git a/apps/miniapp/app.json b/apps/miniapp/app.json index 3c804a6..4cfa839 100644 --- a/apps/miniapp/app.json +++ b/apps/miniapp/app.json @@ -2,6 +2,7 @@ "pages": [ "pages/index/index", "pages/services/index", + "pages/stall-service/index", "pages/booking/index", "pages/bookings/index", "pages/offering/detail", @@ -14,31 +15,5 @@ "navigationBarBackgroundColor": "#FBF7F1", "navigationBarTextStyle": "black", "backgroundColor": "#FBF7F1" - }, - "tabBar": { - "color": "#7A4A2B", - "selectedColor": "#B54A2C", - "backgroundColor": "#FFFFFF", - "borderStyle": "white", - "list": [ - { - "pagePath": "pages/index/index", - "text": "首页", - "iconPath": "assets/tab/home.png", - "selectedIconPath": "assets/tab/home-selected.png" - }, - { - "pagePath": "pages/services/index", - "text": "案例与体系", - "iconPath": "assets/tab/briefcase.png", - "selectedIconPath": "assets/tab/briefcase-selected.png" - }, - { - "pagePath": "pages/bookings/index", - "text": "主理人与我", - "iconPath": "assets/tab/user.png", - "selectedIconPath": "assets/tab/user-selected.png" - } - ] } } diff --git a/apps/miniapp/components/modules/founder-card/founder-card.js b/apps/miniapp/components/modules/founder-card/founder-card.js index 3ce30a1..be63643 100644 --- a/apps/miniapp/components/modules/founder-card/founder-card.js +++ b/apps/miniapp/components/modules/founder-card/founder-card.js @@ -1,3 +1,7 @@ Component({ - properties: { brand: { type: Object, value: {} }, variant: { type: String, value: "default" } }, + properties: { + brand: { type: Object, value: {} }, + presentation: { type: Object, value: {} }, + variant: { type: String, value: "default" }, + }, }); diff --git a/apps/miniapp/components/modules/founder-card/founder-card.wxml b/apps/miniapp/components/modules/founder-card/founder-card.wxml index ad3f8e7..6d1b4c8 100644 --- a/apps/miniapp/components/modules/founder-card/founder-card.wxml +++ b/apps/miniapp/components/modules/founder-card/founder-card.wxml @@ -1 +1 @@ -{{brand.founder}}{{brand.title}}“{{brand.slogan}}”亲自主理量房 +{{brand.founder}}{{brand.founder}}{{brand.title}}“{{brand.slogan}}”{{presentation.founderBadge}} diff --git a/apps/miniapp/components/modules/founder-card/founder-card.wxss b/apps/miniapp/components/modules/founder-card/founder-card.wxss index f80eef9..436498f 100644 --- a/apps/miniapp/components/modules/founder-card/founder-card.wxss +++ b/apps/miniapp/components/modules/founder-card/founder-card.wxss @@ -12,6 +12,15 @@ border-radius: 50%; object-fit: cover; } +.avatar-placeholder { + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; + background: #eee; + color: #777; + font-size: 24rpx; +} .founder-name { display: block; font: 34rpx serif; diff --git a/apps/miniapp/components/modules/inquiry-form/inquiry-form.js b/apps/miniapp/components/modules/inquiry-form/inquiry-form.js index 425dab1..8fd949f 100644 --- a/apps/miniapp/components/modules/inquiry-form/inquiry-form.js +++ b/apps/miniapp/components/modules/inquiry-form/inquiry-form.js @@ -12,7 +12,7 @@ Component({ choose(e) { const field = this.data.fields.find((item) => item.key === e.currentTarget.dataset.key); const option = field?.options?.[e.detail.value]; - if (option) this.triggerEvent("input", { key: field.key, value: option.value }); + if (option) this.triggerEvent("input", { key: field.key, value: option.value ?? option }); }, dateChange(e) { this.triggerEvent("input", { key: e.currentTarget.dataset.key, value: e.detail.value }); diff --git a/apps/miniapp/components/modules/offering-detail/offering-detail.js b/apps/miniapp/components/modules/offering-detail/offering-detail.js index 1530e32..4f11d27 100644 --- a/apps/miniapp/components/modules/offering-detail/offering-detail.js +++ b/apps/miniapp/components/modules/offering-detail/offering-detail.js @@ -1,5 +1,8 @@ Component({ - properties: { item: { type: Object, value: {} } }, + properties: { + item: { type: Object, value: {} }, + presentation: { type: Object, value: {} }, + }, methods: { inquire() { this.triggerEvent("inquire"); diff --git a/apps/miniapp/components/modules/offering-detail/offering-detail.wxml b/apps/miniapp/components/modules/offering-detail/offering-detail.wxml index ff6deca..a670bc5 100644 --- a/apps/miniapp/components/modules/offering-detail/offering-detail.wxml +++ b/apps/miniapp/components/modules/offering-detail/offering-detail.wxml @@ -1 +1 @@ -{{item.category}} · {{item.tag}}{{item.name}}{{item.series}}{{item.priceRange}}{{item.desc}}{{item}} +{{item.category}} · {{item.area}}{{item.name}}{{item.series}}{{presentation.priceLabel}}{{item.priceRange}}{{presentation.spaceLabel}}{{item.spaceType}}{{presentation.backgroundTitle}}{{item.details.background || item.desc}}{{presentation.conceptTitle}}{{item.details.designConcept}}{{presentation.craftsTitle}}0{{index + 1}}{{item}}{{presentation.materialsTitle}}{{item.name}}{{item.spec}}{{item}}{{presentation.inquiryHint}} diff --git a/apps/miniapp/components/modules/offering-detail/offering-detail.wxss b/apps/miniapp/components/modules/offering-detail/offering-detail.wxss index e1c38c9..581a5b4 100644 --- a/apps/miniapp/components/modules/offering-detail/offering-detail.wxss +++ b/apps/miniapp/components/modules/offering-detail/offering-detail.wxss @@ -9,9 +9,138 @@ height: 600rpx; display: block; } +.hero-wrap { + position: relative; + height: 520rpx; + overflow: hidden; + background: #202221; +} +.hero-wrap .hero { + height: 100%; +} +.hero-shade { + position: absolute; + inset: 0; + background: linear-gradient(180deg, rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0.78)); +} +.hero-copy { + position: absolute; + right: 40rpx; + bottom: 32rpx; + left: 40rpx; + color: #fff; +} +.hero-copy text { + display: block; +} +.hero-copy text:first-child { + color: #d9c8b2; + font-size: 20rpx; +} +.hero-copy text:nth-child(2) { + margin-top: 12rpx; + font: 38rpx serif; +} +.hero-copy text:last-child { + margin-top: 8rpx; + color: rgba(255, 255, 255, 0.72); + font-size: 23rpx; +} .content { padding: 42rpx 40rpx; } +.price-card { + display: flex; + justify-content: space-between; + gap: 24rpx; + padding: 26rpx; + border: 1rpx solid #e6ded5; + border-radius: 16rpx; + background: #fff; +} +.price-card view:last-child { + text-align: right; +} +.price-card text { + display: block; +} +.price-card text:first-child { + color: #77736b; + font-size: 20rpx; +} +.price-card text:last-child { + margin-top: 8rpx; + color: #8a6846; + font: 25rpx serif; +} +.detail-section { + margin-top: 38rpx; +} +.section-title { + display: block; + padding-left: 16rpx; + border-left: 5rpx solid #8a6846; + color: #202221; + font: 27rpx serif; +} +.body { + display: block; + margin-top: 16rpx; + padding: 24rpx; + border: 1rpx solid #e6ded5; + border-radius: 14rpx; + background: #fff; + color: #252525; + font-size: 23rpx; + line-height: 1.8; +} +.warm { + background: #efece6; +} +.craft { + display: flex; + gap: 18rpx; + margin-top: 14rpx; + padding: 20rpx; + border: 1rpx solid #e6ded5; + border-radius: 12rpx; + background: #fff; + color: #252525; + font-size: 22rpx; + line-height: 1.65; +} +.craft text:first-child { + flex: 0 0 auto; + color: #8a6846; + font-family: monospace; + font-weight: 700; +} +.materials { + margin-top: 16rpx; + overflow: hidden; + border: 1rpx solid #e6ded5; + border-radius: 12rpx; + background: #fff; +} +.materials view { + display: flex; + justify-content: space-between; + gap: 24rpx; + padding: 20rpx; + color: #252525; + font-size: 21rpx; + line-height: 1.5; +} +.materials view + view { + border-top: 1rpx solid #e6ded5; +} +.materials text:first-child { + flex: 0 0 auto; + color: #77736b; +} +.materials text:last-child { + text-align: right; +} .category { font-size: 21rpx; color: #8a6846; @@ -65,3 +194,10 @@ color: #fff; border-radius: 0; } +.bar text { + display: block; + margin-top: 10rpx; + color: #77736b; + text-align: center; + font-size: 19rpx; +} diff --git a/apps/miniapp/components/modules/offering-list/offering-list.js b/apps/miniapp/components/modules/offering-list/offering-list.js index 6f9b3d4..ab81d6a 100644 --- a/apps/miniapp/components/modules/offering-list/offering-list.js +++ b/apps/miniapp/components/modules/offering-list/offering-list.js @@ -1,6 +1,7 @@ Component({ properties: { offerings: { type: Array, value: [] }, + presentation: { type: Object, value: {} }, variant: { type: String, value: "default" }, }, methods: { diff --git a/apps/miniapp/components/modules/offering-list/offering-list.wxml b/apps/miniapp/components/modules/offering-list/offering-list.wxml index ef4b9c0..709f894 100644 --- a/apps/miniapp/components/modules/offering-list/offering-list.wxml +++ b/apps/miniapp/components/modules/offering-list/offering-list.wxml @@ -1 +1 @@ -SELECTED WORKS精选门系统作品查看全部 →{{item.category}} · {{item.area}}{{item.name}}{{item.series}} · {{item.keywords[0]}} · {{item.keywords[1]}} +{{presentation.worksEyebrow}}{{presentation.worksTitle}}{{presentation.worksAction}}{{item.category}} · {{item.area}}{{item.name}}{{item.series}} · {{item.keywords[0]}} · {{item.keywords[1]}} diff --git a/apps/miniapp/components/modules/profile/profile.js b/apps/miniapp/components/modules/profile/profile.js index 8b2aa9f..0baa99a 100644 --- a/apps/miniapp/components/modules/profile/profile.js +++ b/apps/miniapp/components/modules/profile/profile.js @@ -1,5 +1,9 @@ Component({ - properties: { brand: { type: Object, value: {} }, recordsCount: { type: Number, value: 0 } }, + properties: { + brand: { type: Object, value: {} }, + presentation: { type: Object, value: {} }, + recordsCount: { type: Number, value: 0 }, + }, methods: { call() { this.triggerEvent("call"); diff --git a/apps/miniapp/components/modules/profile/profile.wxml b/apps/miniapp/components/modules/profile/profile.wxml index 7e02a78..010c06d 100644 --- a/apps/miniapp/components/modules/profile/profile.wxml +++ b/apps/miniapp/components/modules/profile/profile.wxml @@ -1 +1 @@ -林{{brand.founder}}{{brand.title}}专线电话{{brand.phone}}工作室微信{{brand.wechat}}实体工坊{{brand.studioAddress}}我的量房与定制咨询{{recordsCount}} 条记录 › +{{brand.founder}}{{brand.founder}}{{brand.title}}{{presentation.phoneLabel || '联系电话'}}{{brand.phone}}{{presentation.wechatLabel || '微信'}}{{brand.wechat}}{{presentation.addressLabel || '工作地址'}}{{brand.studioAddress}}{{presentation.recordsTitle || '我的咨询记录'}}{{recordsCount}} {{presentation.recordsCountUnit || '条记录'}} › diff --git a/apps/miniapp/components/modules/records/records.js b/apps/miniapp/components/modules/records/records.js index c42b724..c39f4ab 100644 --- a/apps/miniapp/components/modules/records/records.js +++ b/apps/miniapp/components/modules/records/records.js @@ -1,5 +1,8 @@ Component({ - properties: { records: { type: Array, value: [] } }, + properties: { + records: { type: Array, value: [] }, + presentation: { type: Object, value: {} }, + }, methods: { create() { this.triggerEvent("create"); diff --git a/apps/miniapp/components/modules/records/records.wxml b/apps/miniapp/components/modules/records/records.wxml index 98dc33f..a3465a9 100644 --- a/apps/miniapp/components/modules/records/records.wxml +++ b/apps/miniapp/components/modules/records/records.wxml @@ -1 +1 @@ -还没有咨询记录预约一次私享沟通,让我们从你的空间开始。{{item.type}}{{item.status}}{{item.project}} · {{item.offeringName}}档案编号 {{item.id}} {{item.createdAt}}●{{item.status}} · {{item.createdAt}} +{{presentation.emptyTitle}}{{presentation.emptyDescription}}{{item.type}}{{item.status}}{{item.project}} · {{item.offeringName}}档案编号 {{item.id}} {{item.createdAt}}●{{item.status}} · {{item.createdAt}} diff --git a/apps/miniapp/components/modules/success-summary/success-summary.js b/apps/miniapp/components/modules/success-summary/success-summary.js index 0493db0..6c278b8 100644 --- a/apps/miniapp/components/modules/success-summary/success-summary.js +++ b/apps/miniapp/components/modules/success-summary/success-summary.js @@ -1,5 +1,8 @@ Component({ - properties: { record: { type: Object, value: {} } }, + properties: { + record: { type: Object, value: {} }, + presentation: { type: Object, value: {} }, + }, methods: { records() { this.triggerEvent("records"); diff --git a/apps/miniapp/components/modules/success-summary/success-summary.wxml b/apps/miniapp/components/modules/success-summary/success-summary.wxml index 7bc0971..244b571 100644 --- a/apps/miniapp/components/modules/success-summary/success-summary.wxml +++ b/apps/miniapp/components/modules/success-summary/success-summary.wxml @@ -1 +1 @@ -✓PRIVATE CONSULTATION已收到你的咨询主理人会根据你的项目资料,整理初步判断并在 1 个工作日内与你联系。档案编号{{record.id}}定制类型{{record.type}}当前状态{{record.status}} +✓{{presentation.eyebrow}}{{presentation.title}}{{presentation.intro}}档案编号{{record.id}}定制类型{{record.type}}当前状态{{record.status}} diff --git a/apps/miniapp/components/modules/trust-manifesto/trust-manifesto.js b/apps/miniapp/components/modules/trust-manifesto/trust-manifesto.js index 13d462c..6a183be 100644 --- a/apps/miniapp/components/modules/trust-manifesto/trust-manifesto.js +++ b/apps/miniapp/components/modules/trust-manifesto/trust-manifesto.js @@ -1,3 +1,7 @@ Component({ - properties: { content: { type: Object, value: {} }, variant: { type: String, value: "default" } }, + properties: { + content: { type: Object, value: {} }, + presentation: { type: Object, value: {} }, + variant: { type: String, value: "default" }, + }, }); diff --git a/apps/miniapp/components/modules/trust-manifesto/trust-manifesto.wxml b/apps/miniapp/components/modules/trust-manifesto/trust-manifesto.wxml index bcdd1dd..9e5e36b 100644 --- a/apps/miniapp/components/modules/trust-manifesto/trust-manifesto.wxml +++ b/apps/miniapp/components/modules/trust-manifesto/trust-manifesto.wxml @@ -1 +1 @@ -林境门作品质宣言拒绝流水线拼装{{item.title}}{{item.desc}} +{{presentation.manifestoEyebrow}}{{presentation.manifestoTitle}}{{item.title}}{{item.desc}} diff --git a/apps/miniapp/components/modules/trust-proof/trust-proof.js b/apps/miniapp/components/modules/trust-proof/trust-proof.js index 13d462c..6a183be 100644 --- a/apps/miniapp/components/modules/trust-proof/trust-proof.js +++ b/apps/miniapp/components/modules/trust-proof/trust-proof.js @@ -1,3 +1,7 @@ Component({ - properties: { content: { type: Object, value: {} }, variant: { type: String, value: "default" } }, + properties: { + content: { type: Object, value: {} }, + presentation: { type: Object, value: {} }, + variant: { type: String, value: "default" }, + }, }); diff --git a/apps/miniapp/components/modules/trust-proof/trust-proof.wxml b/apps/miniapp/components/modules/trust-proof/trust-proof.wxml index 2b57b48..de5edf4 100644 --- a/apps/miniapp/components/modules/trust-proof/trust-proof.wxml +++ b/apps/miniapp/components/modules/trust-proof/trust-proof.wxml @@ -1 +1,11 @@ -主理人工艺与信任凭证14 年,只做门与空间的关系{{content.bio}}{{item.value}}{{item.label}}{{item.sub}} + + {{presentation.proofEyebrow || '信任凭证'}} + + {{item.value}}{{item.label}}{{item.sub}} + + + {{presentation.manifestoEyebrow}}{{presentation.manifestoTitle}} + {{item.icon === 'tree' ? '木' : item.icon === 'ruler' ? '尺' : '盾'}}{{item.title}}{{item.desc}} + + {{presentation.flowEyebrow}}{{presentation.flowTitle}}{{item.step}}{{item.name}}{{item.desc}} + diff --git a/apps/miniapp/components/modules/trust-proof/trust-proof.wxss b/apps/miniapp/components/modules/trust-proof/trust-proof.wxss index 1bb7090..eff764e 100644 --- a/apps/miniapp/components/modules/trust-proof/trust-proof.wxss +++ b/apps/miniapp/components/modules/trust-proof/trust-proof.wxss @@ -1,7 +1,11 @@ -.intro { - margin-top: 22rpx; - padding: 28rpx; - background: #fff; +.trust-section { + padding: 0 40rpx 42rpx; +} +.trust-head { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 20rpx; } .eyebrow { display: block; @@ -9,26 +13,21 @@ font-size: 20rpx; letter-spacing: 3rpx; } -.section-title { - display: block; - margin-top: 12rpx; - font: 40rpx serif; -} -.body { - display: block; - margin-top: 12rpx; - color: #77736b; - font-size: 25rpx; - line-height: 1.7; +.trust-link { + color: #8a6846; + font-size: 21rpx; } .stats { display: grid; grid-template-columns: 1fr 1fr; - margin-top: 24rpx; + gap: 16rpx; + margin-bottom: 18rpx; } -.stats view { - padding: 16rpx 0; - border-top: 1rpx solid #e6ded5; +.stat-card { + padding: 22rpx; + background: #fff; + border: 1rpx solid #e6ded5; + border-radius: 16rpx; } .stat-value { display: block; @@ -38,4 +37,123 @@ .stat-label { display: block; font-size: 22rpx; + margin-top: 4rpx; + font-weight: 600; +} +.stat-sub { + display: block; + margin-top: 6rpx; + color: #77736b; + font-size: 18rpx; + line-height: 1.5; +} +.manifesto { + padding: 28rpx; + border-radius: 20rpx; + background: #202221; + color: #fff; +} +.manifesto-head { + display: flex; + justify-content: space-between; + padding-bottom: 18rpx; + margin-bottom: 20rpx; + border-bottom: 1rpx solid rgba(255, 255, 255, 0.12); + color: #d9c8b2; + font-size: 20rpx; +} +.manifesto-head text:last-child { + color: rgba(255, 255, 255, 0.5); + font-size: 18rpx; +} +.pillar { + display: flex; + gap: 16rpx; + margin-top: 20rpx; +} +.pillar-icon { + width: 44rpx; + height: 44rpx; + flex: 0 0 44rpx; + display: flex; + align-items: center; + justify-content: center; + border-radius: 8rpx; + background: rgba(138, 104, 70, 0.3); + color: #d9c8b2; + font-size: 18rpx; +} +.pillar-title, +.pillar-desc { + display: block; +} +.pillar-title { + font-size: 22rpx; +} +.pillar-desc { + margin-top: 5rpx; + color: rgba(255, 255, 255, 0.62); + font-size: 18rpx; + line-height: 1.55; +} +.flow-card { + margin-top: 22rpx; + padding: 32rpx 24rpx; + border: 1rpx solid #e6ded5; + border-radius: 20rpx; + background: #efece6; + text-align: center; +} +.flow-eyebrow, +.flow-title, +.flow-sub { + display: block; +} +.flow-eyebrow { + color: #8a6846; + font-size: 18rpx; + letter-spacing: 2rpx; +} +.flow-title { + margin-top: 6rpx; + font: 30rpx serif; +} +.flow-sub { + margin-top: 8rpx; + color: #77736b; + font-size: 18rpx; +} +.flow-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16rpx; + margin-top: 26rpx; + text-align: left; +} +.flow-item { + padding: 18rpx; + border: 1rpx solid #e6ded5; + border-radius: 14rpx; + background: #fff; +} +.flow-step, +.flow-name, +.flow-desc { + display: block; +} +.flow-step { + color: #8a6846; + font-size: 18rpx; + font-weight: 700; +} +.flow-name { + margin-top: 5rpx; + font-size: 21rpx; + font-weight: 600; +} +.flow-desc { + margin-top: 6rpx; + color: #77736b; + font-size: 17rpx; + line-height: 1.5; } diff --git a/apps/miniapp/components/runtime-tab-bar/runtime-tab-bar.js b/apps/miniapp/components/runtime-tab-bar/runtime-tab-bar.js new file mode 100644 index 0000000..3cd8c7d --- /dev/null +++ b/apps/miniapp/components/runtime-tab-bar/runtime-tab-bar.js @@ -0,0 +1,33 @@ +Component({ + properties: { + active: { type: String, value: "home" }, + navigation: { type: Array, value: [] }, + }, + data: { + tabs: [], + }, + methods: { + navigate(e) { + const tab = e.currentTarget.dataset.tab; + if (!tab || tab.key === this.data.active) return; + wx.navigateTo({ url: tab.page }); + }, + }, + observers: { + navigation(navigation) { + this.setData({ + tabs: Array.isArray(navigation) + ? navigation.map((item) => ({ + ...item, + page: item.page && item.page.startsWith("/") ? item.page : `/${item.page || ""}`, + })) + : [], + }); + }, + }, + lifetimes: { + attached() { + this.setData({ tabs: this.data.navigation || [] }); + }, + }, +}); diff --git a/apps/miniapp/components/runtime-tab-bar/runtime-tab-bar.json b/apps/miniapp/components/runtime-tab-bar/runtime-tab-bar.json new file mode 100644 index 0000000..67f8e03 --- /dev/null +++ b/apps/miniapp/components/runtime-tab-bar/runtime-tab-bar.json @@ -0,0 +1 @@ +{ "component": true } diff --git a/apps/miniapp/components/runtime-tab-bar/runtime-tab-bar.wxml b/apps/miniapp/components/runtime-tab-bar/runtime-tab-bar.wxml new file mode 100644 index 0000000..7261c07 --- /dev/null +++ b/apps/miniapp/components/runtime-tab-bar/runtime-tab-bar.wxml @@ -0,0 +1 @@ +{{item.key === 'home' ? '⌂' : item.key === 'dishes' ? '♨' : item.key === 'service' ? '⌖' : item.key === 'owner' ? '♙' : item.key === 'booking' ? '✉' : '◈'}}{{item.label}} diff --git a/apps/miniapp/components/runtime-tab-bar/runtime-tab-bar.wxss b/apps/miniapp/components/runtime-tab-bar/runtime-tab-bar.wxss new file mode 100644 index 0000000..06805b6 --- /dev/null +++ b/apps/miniapp/components/runtime-tab-bar/runtime-tab-bar.wxss @@ -0,0 +1,32 @@ +.runtime-tab-bar { + position: fixed; + right: 0; + bottom: 0; + left: 0; + z-index: 20; + display: flex; + justify-content: space-around; + padding: 10rpx 6rpx calc(10rpx + env(safe-area-inset-bottom)); + border-top: 1rpx solid #eee5dc; + background: rgba(255, 255, 255, 0.97); + box-shadow: 0 -8rpx 24rpx rgba(48, 32, 20, 0.08); +} +.tab { + display: flex; + min-width: 0; + flex: 1; + flex-direction: column; + align-items: center; + gap: 4rpx; + color: #9a8d83; + font-size: 19rpx; +} +.icon { + height: 34rpx; + font-size: 31rpx; + line-height: 34rpx; +} +.tab.active { + color: #e87532; + font-weight: 700; +} diff --git a/apps/miniapp/components/templates/acheng-home/acheng-home.js b/apps/miniapp/components/templates/acheng-home/acheng-home.js new file mode 100644 index 0000000..1b3c019 --- /dev/null +++ b/apps/miniapp/components/templates/acheng-home/acheng-home.js @@ -0,0 +1,19 @@ +Component({ + properties: { + brand: { type: Object, value: {} }, + presentation: { type: Object, value: {} }, + trustContent: { type: Object, value: {} }, + offerings: { type: Array, value: [] }, + }, + methods: { + openOffering(e) { + this.triggerEvent("select", { id: e.currentTarget.dataset.id }); + }, + openInquiry() { + this.triggerEvent("inquiry"); + }, + openOfferings() { + this.triggerEvent("offerings"); + }, + }, +}); diff --git a/apps/miniapp/components/templates/acheng-home/acheng-home.json b/apps/miniapp/components/templates/acheng-home/acheng-home.json new file mode 100644 index 0000000..67f8e03 --- /dev/null +++ b/apps/miniapp/components/templates/acheng-home/acheng-home.json @@ -0,0 +1 @@ +{ "component": true } diff --git a/apps/miniapp/components/templates/acheng-home/acheng-home.wxml b/apps/miniapp/components/templates/acheng-home/acheng-home.wxml new file mode 100644 index 0000000..d8e978a --- /dev/null +++ b/apps/miniapp/components/templates/acheng-home/acheng-home.wxml @@ -0,0 +1 @@ +{{brand.founder}}{{brand.title}}“{{brand.slogan}}”{{presentation.stallTitle || '今日出摊点'}}{{brand.studioAddress || brand.address}}{{presentation.stallTime || '今日营业中'}}{{presentation.worksEyebrow || '本周学生票选招牌'}}{{presentation.worksTitle || '现做现吃,认真管饱'}}全部餐品 ›{{item.name}}{{item.desc}}{{item.priceRange}}{{presentation.manifestoEyebrow || '阿成的开档底线'}}{{presentation.manifestoTitle || '真材实料,当天现做'}}✓{{item.title}} diff --git a/apps/miniapp/components/templates/acheng-home/acheng-home.wxss b/apps/miniapp/components/templates/acheng-home/acheng-home.wxss new file mode 100644 index 0000000..d90028b --- /dev/null +++ b/apps/miniapp/components/templates/acheng-home/acheng-home.wxss @@ -0,0 +1,177 @@ +.page { + min-height: 100vh; + padding: 20rpx 28rpx 48rpx; + background: #fff8f0; + color: #29231f; +} +.brand-card { + padding: 28rpx; + border: 1rpx solid #f2d9c6; + border-radius: 28rpx; + background: #fff; + box-shadow: 0 12rpx 30rpx rgba(145, 75, 33, 0.08); +} +.identity { + display: flex; + gap: 20rpx; + align-items: center; +} +.identity image { + width: 96rpx; + height: 96rpx; + border: 4rpx solid #ffd9bb; + border-radius: 50%; + background: #fff1e5; +} +.name, +.title, +.slogan, +.notice-title, +.notice text, +.eyebrow, +.heading, +.more, +.dish-name, +.dish-sub, +.price, +.promise-title, +.promise-item text { + display: block; +} +.name { + font-size: 32rpx; + font-weight: 700; +} +.title { + margin-top: 6rpx; + color: #a2613b; + font-size: 21rpx; +} +.slogan { + margin-top: 10rpx; + color: #7a6a60; + font-size: 21rpx; +} +.notice { + position: relative; + margin-top: 24rpx; + padding: 20rpx; + border: 1rpx solid #f8d7b4; + border-radius: 20rpx; + background: #fff7df; + color: #6b4a35; + font-size: 22rpx; + line-height: 1.6; +} +.notice-title { + font-weight: 700; + color: #4f3020; +} +.notice-time { + position: absolute; + right: 18rpx; + top: 18rpx; + color: #c65c28; + font-size: 19rpx; +} +.actions { + display: flex; + gap: 14rpx; + margin-top: 20rpx; +} +.actions button { + flex: 1; + height: 76rpx; + border-radius: 20rpx; + background: #e87532; + color: #fff; + font-size: 24rpx; + line-height: 76rpx; +} +.actions .muted { + background: #fff0e5; + color: #b85e2c; +} +.section-head { + display: flex; + justify-content: space-between; + align-items: end; + margin: 34rpx 4rpx 18rpx; +} +.eyebrow { + color: #d2652b; + font-size: 19rpx; + letter-spacing: 2rpx; +} +.heading { + margin-top: 8rpx; + font-size: 34rpx; + font-weight: 700; +} +.more { + color: #d2652b; + font-size: 21rpx; +} +.dish-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16rpx; +} +.dish { + overflow: hidden; + border: 1rpx solid #f2e2d6; + border-radius: 22rpx; + background: #fff; +} +.dish image { + display: block; + width: 100%; + height: 220rpx; + background: #f3e7de; +} +.dish-copy { + padding: 18rpx; +} +.dish-name { + font-size: 24rpx; + font-weight: 700; + line-height: 1.4; +} +.dish-sub { + margin-top: 6rpx; + color: #8c7b70; + font-size: 19rpx; + line-height: 1.4; +} +.price { + margin-top: 14rpx; + color: #dc6429; + font-size: 24rpx; + font-weight: 700; +} +.promise { + margin-top: 28rpx; + padding: 28rpx; + border-radius: 24rpx; + background: #3b2118; + color: #fff; +} +.light { + color: #ffc79f; +} +.promise-title { + margin-top: 8rpx; + font-size: 30rpx; + font-weight: 700; +} +.promise-item { + display: flex; + gap: 12rpx; + margin-top: 18rpx; + color: #ffe5d2; + font-size: 21rpx; +} +.promise-item text:first-child { + color: #ff9a5a; + font-weight: 700; +} diff --git a/apps/miniapp/components/templates/acheng-offerings/acheng-offerings.js b/apps/miniapp/components/templates/acheng-offerings/acheng-offerings.js new file mode 100644 index 0000000..a5df8cf --- /dev/null +++ b/apps/miniapp/components/templates/acheng-offerings/acheng-offerings.js @@ -0,0 +1,15 @@ +Component({ + properties: { + brand: { type: Object, value: {} }, + presentation: { type: Object, value: {} }, + offerings: { type: Array, value: [] }, + }, + methods: { + open(e) { + this.triggerEvent("open", { id: e.currentTarget.dataset.id }); + }, + inquire() { + this.triggerEvent("inquire"); + }, + }, +}); diff --git a/apps/miniapp/components/templates/acheng-offerings/acheng-offerings.json b/apps/miniapp/components/templates/acheng-offerings/acheng-offerings.json new file mode 100644 index 0000000..67f8e03 --- /dev/null +++ b/apps/miniapp/components/templates/acheng-offerings/acheng-offerings.json @@ -0,0 +1 @@ +{ "component": true } diff --git a/apps/miniapp/components/templates/acheng-offerings/acheng-offerings.wxml b/apps/miniapp/components/templates/acheng-offerings/acheng-offerings.wxml new file mode 100644 index 0000000..ef77592 --- /dev/null +++ b/apps/miniapp/components/templates/acheng-offerings/acheng-offerings.wxml @@ -0,0 +1 @@ +{{brand.name}}{{presentation.title || '今日菜单'}}{{presentation.subtitle || '现做现吃,支持提前预留和团体定制'}}米饭免费续,口味和忌口都可以在预约时备注{{item.name}}{{item.desc}}{{item.priceRange}}查看详情 › diff --git a/apps/miniapp/components/templates/acheng-offerings/acheng-offerings.wxss b/apps/miniapp/components/templates/acheng-offerings/acheng-offerings.wxss new file mode 100644 index 0000000..9518e4f --- /dev/null +++ b/apps/miniapp/components/templates/acheng-offerings/acheng-offerings.wxss @@ -0,0 +1,93 @@ +.page { + min-height: 100vh; + padding: 28rpx; + background: #fff8f0; + color: #29231f; +} +.eyebrow { + display: block; + color: #d2652b; + font-size: 19rpx; + letter-spacing: 2rpx; +} +.title { + display: block; + margin-top: 8rpx; + font-size: 42rpx; + font-weight: 700; +} +.subtitle { + display: block; + margin-top: 8rpx; + color: #8c7b70; + font-size: 22rpx; +} +.tip { + margin-top: 22rpx; + padding: 18rpx 20rpx; + border: 1rpx solid #f8d7b4; + border-radius: 18rpx; + background: #fff7df; + color: #8c5c39; + font-size: 21rpx; +} +.list { + margin-top: 18rpx; +} +.dish { + display: flex; + gap: 18rpx; + margin-bottom: 16rpx; + padding: 14rpx; + border: 1rpx solid #f2e2d6; + border-radius: 22rpx; + background: #fff; +} +.dish image { + width: 196rpx; + height: 196rpx; + flex: none; + border-radius: 16rpx; + background: #f3e7de; +} +.copy { + display: flex; + min-width: 0; + flex: 1; + flex-direction: column; +} +.name { + font-size: 26rpx; + font-weight: 700; + line-height: 1.45; +} +.desc { + margin-top: 10rpx; + color: #8c7b70; + font-size: 20rpx; + line-height: 1.5; +} +.bottom { + display: flex; + align-items: end; + justify-content: space-between; + margin-top: auto; +} +.price { + color: #dc6429; + font-size: 25rpx; + font-weight: 700; +} +.action { + color: #d2652b; + font-size: 20rpx; +} +.cta { + margin: 22rpx 0 0; + height: 76rpx; + border-radius: 20rpx; + background: #e87532; + color: #fff; + font-size: 24rpx; + line-height: 76rpx; +} diff --git a/apps/miniapp/components/templates/acheng-profile/acheng-profile.js b/apps/miniapp/components/templates/acheng-profile/acheng-profile.js new file mode 100644 index 0000000..0baa99a --- /dev/null +++ b/apps/miniapp/components/templates/acheng-profile/acheng-profile.js @@ -0,0 +1,18 @@ +Component({ + properties: { + brand: { type: Object, value: {} }, + presentation: { type: Object, value: {} }, + recordsCount: { type: Number, value: 0 }, + }, + methods: { + call() { + this.triggerEvent("call"); + }, + copy() { + this.triggerEvent("copy"); + }, + records() { + this.triggerEvent("records"); + }, + }, +}); diff --git a/apps/miniapp/components/templates/acheng-profile/acheng-profile.json b/apps/miniapp/components/templates/acheng-profile/acheng-profile.json new file mode 100644 index 0000000..67f8e03 --- /dev/null +++ b/apps/miniapp/components/templates/acheng-profile/acheng-profile.json @@ -0,0 +1 @@ +{ "component": true } diff --git a/apps/miniapp/components/templates/acheng-profile/acheng-profile.wxml b/apps/miniapp/components/templates/acheng-profile/acheng-profile.wxml new file mode 100644 index 0000000..15ba552 --- /dev/null +++ b/apps/miniapp/components/templates/acheng-profile/acheng-profile.wxml @@ -0,0 +1 @@ +{{brand.founder}}{{brand.title}}{{brand.slogan}}{{presentation.coverageTitle || '出摊与配送'}}{{brand.studioAddress || brand.address}}{{presentation.coverageContent || '支持校园摊位自取、宿舍配送和班级活动定制。'}}我的预约记录{{recordsCount}} 条记录 › diff --git a/apps/miniapp/components/templates/acheng-profile/acheng-profile.wxss b/apps/miniapp/components/templates/acheng-profile/acheng-profile.wxss new file mode 100644 index 0000000..b879aea --- /dev/null +++ b/apps/miniapp/components/templates/acheng-profile/acheng-profile.wxss @@ -0,0 +1,72 @@ +.page { + min-height: 100vh; + padding: 28rpx; + background: #fff8f0; + color: #29231f; +} +.profile-card { + padding: 36rpx 28rpx; + text-align: center; + border-radius: 28rpx; + background: #3b2118; + color: #fff; +} +.profile-card image { + width: 132rpx; + height: 132rpx; + border: 5rpx solid #ffbd8e; + border-radius: 50%; +} +.name, +.title, +.bio, +.card-title, +.card text { + display: block; +} +.name { + margin-top: 18rpx; + font-size: 36rpx; + font-weight: 700; +} +.title { + margin-top: 6rpx; + color: #ffc79f; + font-size: 22rpx; +} +.bio { + margin-top: 16rpx; + color: #ffe5d2; + font-size: 23rpx; + line-height: 1.6; +} +.contact { + display: flex; + gap: 14rpx; + margin-top: 24rpx; +} +.contact button { + flex: 1; + height: 70rpx; + border-radius: 18rpx; + background: #e87532; + color: #fff; + font-size: 22rpx; + line-height: 70rpx; +} +.card { + margin-top: 18rpx; + padding: 26rpx; + border: 1rpx solid #f2d9c6; + border-radius: 22rpx; + background: #fff; + color: #7a6a60; + font-size: 22rpx; + line-height: 1.7; +} +.card-title { + margin-bottom: 10rpx; + color: #4b2b1d; + font-size: 27rpx; + font-weight: 700; +} diff --git a/apps/miniapp/components/templates/linjing-home/linjing-home.js b/apps/miniapp/components/templates/linjing-home/linjing-home.js new file mode 100644 index 0000000..3f4fad2 --- /dev/null +++ b/apps/miniapp/components/templates/linjing-home/linjing-home.js @@ -0,0 +1,17 @@ +Component({ + properties: { + brand: { type: Object, value: {} }, + presentation: { type: Object, value: {} }, + hero: { type: Object, value: {} }, + trustContent: { type: Object, value: {} }, + offerings: { type: Array, value: [] }, + }, + methods: { + selectOffering(event) { + this.triggerEvent("select", { id: event.currentTarget.dataset.id }); + }, + goWorks() { + this.triggerEvent("works"); + }, + }, +}); diff --git a/apps/miniapp/components/templates/linjing-home/linjing-home.json b/apps/miniapp/components/templates/linjing-home/linjing-home.json new file mode 100644 index 0000000..67f8e03 --- /dev/null +++ b/apps/miniapp/components/templates/linjing-home/linjing-home.json @@ -0,0 +1 @@ +{ "component": true } diff --git a/apps/miniapp/components/templates/linjing-home/linjing-home.wxml b/apps/miniapp/components/templates/linjing-home/linjing-home.wxml new file mode 100644 index 0000000..e77a0f5 --- /dev/null +++ b/apps/miniapp/components/templates/linjing-home/linjing-home.wxml @@ -0,0 +1,8 @@ + + {{brand.founder}}{{brand.title}}“{{brand.slogan}}”{{presentation.founderBadge}} + {{hero.eyebrow}}{{hero.title}}{{hero.slogan}}{{hero.cta}} + {{presentation.proofEyebrow}}{{presentation.proofTitle}}{{trustContent.bio}}{{item.value}}{{item.label}}{{item.sub}} + {{presentation.manifestoEyebrow}}{{presentation.manifestoTitle}}{{item.title}}{{item.desc}} + {{presentation.worksEyebrow}}{{presentation.worksTitle}}{{presentation.worksAction}}{{item.category}} · {{item.area}}{{item.name}}{{item.series}} · {{item.keywords[0]}} · {{item.keywords[1]}} + {{presentation.flowEyebrow}}{{presentation.flowTitle}}{{item.step}}{{item.name}}{{item.desc}} + diff --git a/apps/miniapp/components/templates/linjing-home/linjing-home.wxss b/apps/miniapp/components/templates/linjing-home/linjing-home.wxss new file mode 100644 index 0000000..1254b3b --- /dev/null +++ b/apps/miniapp/components/templates/linjing-home/linjing-home.wxss @@ -0,0 +1,261 @@ +.page { + background: #f7f5f1; + color: #252525; + padding-bottom: 30rpx; +} +.founder-card { + position: relative; + display: flex; + gap: 20rpx; + align-items: flex-start; + margin: 32rpx 40rpx 20rpx; + padding: 28rpx; + border: 1rpx solid #e6ded5; + border-radius: 28rpx; + background: #fff; +} +.avatar { + width: 112rpx; + height: 112rpx; + flex: 0 0 112rpx; + border: 4rpx solid #d9c8b2; + border-radius: 50%; +} +.founder-copy { + min-width: 0; + padding-right: 78rpx; +} +.founder-name, +.founder-title, +.quote, +.eyebrow, +.hero-title, +.hero-slogan, +.section-title, +.body, +.stat-value, +.stat-label, +.stat-sub, +.pillar-title, +.pillar-desc, +.work-category, +.work-name, +.work-desc, +.flow-eyebrow, +.flow-title, +.flow-step, +.flow-name, +.flow-desc { + display: block; +} +.founder-name { + font: 30rpx serif; +} +.founder-title { + margin-top: 6rpx; + color: #77736b; + font-size: 20rpx; +} +.quote { + margin-top: 14rpx; + font: 21rpx serif; +} +.badge { + position: absolute; + top: 24rpx; + right: 20rpx; + padding: 8rpx 12rpx; + border-radius: 20rpx; + background: #f3ede6; + color: #8a6846; + font-size: 18rpx; +} +.hero { + position: relative; + height: 400rpx; + margin: 0 40rpx 42rpx; + overflow: hidden; + border-radius: 28rpx; +} +.hero-image { + width: 100%; + height: 100%; +} +.hero-shade { + position: absolute; + inset: 0; + background: linear-gradient(180deg, rgba(20, 22, 21, 0.1), rgba(20, 22, 21, 0.82)); +} +.hero-copy { + position: absolute; + right: 28rpx; + bottom: 28rpx; + left: 28rpx; + color: #fff; +} +.eyebrow { + margin-bottom: 14rpx; + color: #d9c8b2; + font-size: 18rpx; + letter-spacing: 3rpx; +} +.dark { + color: #8a6846; +} +.hero-title, +.section-title { + font: 34rpx serif; +} +.hero-slogan { + margin-top: 10rpx; + font-size: 21rpx; +} +.hero-button { + position: absolute; + right: 0; + bottom: 0; + padding: 12rpx 16rpx; + border: 1rpx solid rgba(255, 255, 255, 0.3); + color: #d9c8b2; + font-size: 19rpx; +} +.intro, +.section { + padding: 0 40rpx 48rpx; +} +.body { + color: #77736b; + font-size: 24rpx; + line-height: 1.8; +} +.stats { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16rpx; + margin-top: 22rpx; +} +.stats view { + padding: 22rpx; + border: 1rpx solid #e6ded5; + border-radius: 20rpx; + background: #fff; +} +.stat-value { + color: #8a6846; + font: 38rpx serif; +} +.stat-label { + margin-top: 4rpx; + font-size: 22rpx; + font-weight: 600; +} +.stat-sub { + margin-top: 6rpx; + color: #77736b; + font-size: 18rpx; + line-height: 1.5; +} +.trust { + padding: 42rpx 40rpx; + background: #202221; + color: #fff; +} +.light { + color: #fff; +} +.pillar { + margin-top: 24rpx; +} +.pillar-title { + color: #fff; + font: 28rpx serif; +} +.pillar-desc { + margin-top: 8rpx; + color: #c6c2ba; + font-size: 22rpx; + line-height: 1.65; +} +.section-head { + display: flex; + align-items: end; + justify-content: space-between; + margin-bottom: 22rpx; +} +.more { + color: #8a6846; + font-size: 21rpx; +} +.work-card { + margin-bottom: 24rpx; + overflow: hidden; + border: 1rpx solid #e6ded5; + border-radius: 28rpx; + background: #fff; +} +.work-card image { + width: 100%; + height: 300rpx; +} +.work-info { + padding: 24rpx; +} +.work-category { + color: #8a6846; + font-size: 19rpx; +} +.work-name { + margin: 10rpx 0; + font: 28rpx serif; +} +.work-desc { + color: #77736b; + font-size: 22rpx; + line-height: 1.6; +} +.flow { + margin: 0 40rpx 42rpx; + padding: 30rpx 24rpx; + border: 1rpx solid #e6ded5; + border-radius: 20rpx; + background: #efece6; + text-align: center; +} +.flow-eyebrow { + color: #8a6846; + font-size: 18rpx; + letter-spacing: 2rpx; +} +.flow-title { + margin-top: 6rpx; + font: 30rpx serif; +} +.flow-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16rpx; + margin-top: 24rpx; + text-align: left; +} +.flow-item { + padding: 18rpx; + border: 1rpx solid #e6ded5; + border-radius: 14rpx; + background: #fff; +} +.flow-step { + color: #8a6846; + font-size: 18rpx; + font-weight: 700; +} +.flow-name { + margin-top: 5rpx; + font-size: 21rpx; + font-weight: 600; +} +.flow-desc { + margin-top: 6rpx; + color: #77736b; + font-size: 17rpx; + line-height: 1.5; +} diff --git a/apps/miniapp/components/templates/linjing-profile/linjing-profile.js b/apps/miniapp/components/templates/linjing-profile/linjing-profile.js new file mode 100644 index 0000000..0baa99a --- /dev/null +++ b/apps/miniapp/components/templates/linjing-profile/linjing-profile.js @@ -0,0 +1,18 @@ +Component({ + properties: { + brand: { type: Object, value: {} }, + presentation: { type: Object, value: {} }, + recordsCount: { type: Number, value: 0 }, + }, + methods: { + call() { + this.triggerEvent("call"); + }, + copy() { + this.triggerEvent("copy"); + }, + records() { + this.triggerEvent("records"); + }, + }, +}); diff --git a/apps/miniapp/components/templates/linjing-profile/linjing-profile.json b/apps/miniapp/components/templates/linjing-profile/linjing-profile.json new file mode 100644 index 0000000..5aa1d8d --- /dev/null +++ b/apps/miniapp/components/templates/linjing-profile/linjing-profile.json @@ -0,0 +1,6 @@ +{ + "component": true, + "usingComponents": { + "t-icon": "/miniprogram_npm/tdesign-miniprogram/icon/icon" + } +} diff --git a/apps/miniapp/components/templates/linjing-profile/linjing-profile.wxml b/apps/miniapp/components/templates/linjing-profile/linjing-profile.wxml new file mode 100644 index 0000000..b80db86 --- /dev/null +++ b/apps/miniapp/components/templates/linjing-profile/linjing-profile.wxml @@ -0,0 +1,26 @@ + + + + + {{brand.founder}}{{brand.title}} + + + {{presentation.phoneLabel}}{{brand.phone}} + {{presentation.wechatLabel}}{{brand.wechat}} + {{presentation.addressLabel}}{{brand.studioAddress}} + + + + + {{presentation.recordsTitle}}{{presentation.recordsSubtitle}} + {{recordsCount}} {{presentation.recordsCountUnit}} + + + {{presentation.coverageTitle}} + {{item.title}}{{item.content}} + + + {{presentation.warrantyTitle}} + •{{item}} + + diff --git a/apps/miniapp/components/templates/linjing-profile/linjing-profile.wxss b/apps/miniapp/components/templates/linjing-profile/linjing-profile.wxss new file mode 100644 index 0000000..c483b30 --- /dev/null +++ b/apps/miniapp/components/templates/linjing-profile/linjing-profile.wxss @@ -0,0 +1,194 @@ +.profile { + min-height: 100vh; + padding: 28rpx 32rpx 56rpx; + background: #f7f5f1; + color: #252525; +} +.founder-card { + padding: 34rpx 30rpx; + border-radius: 20rpx; + background: #202221; + color: #fff; + box-shadow: 0 12rpx 34rpx rgba(32, 34, 33, 0.12); +} +.identity { + display: flex; + align-items: center; + gap: 22rpx; +} +.avatar { + width: 92rpx; + height: 92rpx; + border: 2rpx solid #8a6846; + border-radius: 50%; + background: #343736; +} +.founder, +.role, +.label, +.value, +.address-value, +.entry-copy text, +.entry-count text, +.note-title, +.note text, +.warranty text { + display: block; +} +.founder { + font: 34rpx serif; +} +.role { + margin-top: 8rpx; + color: #d9c8b2; + font-size: 22rpx; +} +.contact-lines { + margin-top: 24rpx; + border-top: 1rpx solid rgba(255, 255, 255, 0.12); +} +.contact-line { + display: flex; + align-items: center; + justify-content: space-between; + gap: 20rpx; + padding-top: 18rpx; + margin-top: 18rpx; + border-top: 1rpx solid rgba(255, 255, 255, 0.1); + font-size: 22rpx; +} +.contact-line:first-child { + border-top: 0; + margin-top: 0; +} +.label { + flex: 0 0 auto; + color: rgba(255, 255, 255, 0.52); +} +.contact-action { + display: flex; + min-width: 0; + align-items: center; + gap: 12rpx; +} +.value { + color: #fff; + font-family: monospace; + white-space: nowrap; +} +.accent { + color: #d9c8b2; +} +.contact-action button { + display: flex; + align-items: center; + justify-content: center; + gap: 5rpx; + min-width: 86rpx; + height: 46rpx; + margin: 0; + padding: 0 12rpx; + border-radius: 9rpx; + background: rgba(255, 255, 255, 0.1); + color: #d9c8b2; + font-size: 20rpx; + line-height: 46rpx; +} +.address { + align-items: flex-start; +} +.address-value { + max-width: 410rpx; + color: rgba(255, 255, 255, 0.82); + line-height: 1.55; + text-align: right; +} +.records-card, +.info-card { + margin-top: 20rpx; + border: 1rpx solid #e6ded5; + border-radius: 18rpx; + background: #fff; + box-shadow: 0 10rpx 30rpx -12rpx rgba(32, 34, 33, 0.08); +} +.records-card { + display: flex; + align-items: center; + gap: 18rpx; + padding: 26rpx; +} +.entry-icon { + display: flex; + align-items: center; + justify-content: center; + width: 66rpx; + height: 66rpx; + border-radius: 12rpx; + background: rgba(138, 104, 70, 0.1); + color: #8a6846; +} +.entry-copy { + flex: 1; + min-width: 0; +} +.entry-copy text:first-child { + color: #202221; + font-size: 25rpx; + font-weight: 600; +} +.entry-copy text:last-child { + margin-top: 7rpx; + color: #77736b; + font-size: 20rpx; + line-height: 1.4; +} +.entry-count { + display: flex; + align-items: center; + gap: 4rpx; + flex: 0 0 auto; + color: #8a6846; + font-size: 20rpx; +} +.info-card { + padding: 28rpx; +} +.card-title { + display: flex; + align-items: center; + gap: 12rpx; + color: #202221; + font-size: 26rpx; + font-weight: 700; +} +.card-title t-icon { + color: #8a6846; +} +.note { + margin-top: 18rpx; + padding: 20rpx; + border: 1rpx solid #e6ded5; + border-radius: 12rpx; + background: #f7f5f1; + color: #57534e; + font-size: 23rpx; + line-height: 1.7; +} +.note-title { + margin-bottom: 5rpx; + color: #202221; + font-size: 23rpx; + font-weight: 700; +} +.warranty { + display: flex; + gap: 10rpx; + margin-top: 16rpx; + color: #77736b; + font-size: 23rpx; + line-height: 1.65; +} +.dot { + flex: 0 0 auto; + color: #8a6846; +} diff --git a/apps/miniapp/package.json b/apps/miniapp/package.json index 8ea21e3..3311fa0 100644 --- a/apps/miniapp/package.json +++ b/apps/miniapp/package.json @@ -8,7 +8,7 @@ "tdesign-miniprogram": "^1.16.1" }, "scripts": { - "test:fixture": "node test/validate-fixture.cjs", + "test:fixture": "node test/validate-fixture.cjs && node --test test/runtime-workspace.test.cjs", "test:visual-fixture": "node test/validate-visual-fixture.cjs", "lint": "eslint src --ext .ts", "typecheck": "tsc -p tsconfig.json --noEmit", diff --git a/apps/miniapp/pages/booking/index.js b/apps/miniapp/pages/booking/index.js index cca6178..a7da68f 100644 --- a/apps/miniapp/pages/booking/index.js +++ b/apps/miniapp/pages/booking/index.js @@ -1,4 +1,4 @@ -const { request, customerRequest } = require("../../utils/request"); +const { request, customerRequest, customerTokenKey } = require("../../utils/request"); const { getTemplate } = require("../../utils/templates"); Page({ data: { @@ -70,13 +70,13 @@ Page({ this.setData({ submitting: false }); wx.showToast({ title: error.message || "提交失败", icon: "none" }); }); - const token = wx.getStorageSync("customerToken"); + const token = wx.getStorageSync(customerTokenKey()); if (token) return send(); wx.login({ success: (login) => request("/customer/session/wechat", { method: "POST", data: { code: login.code } }) .then((result) => { - wx.setStorageSync("customerToken", result.token); + wx.setStorageSync(customerTokenKey(), result.token); send(); }) .catch((error) => { diff --git a/apps/miniapp/pages/bookings/index.js b/apps/miniapp/pages/bookings/index.js index f2db9ca..4ceed06 100644 --- a/apps/miniapp/pages/bookings/index.js +++ b/apps/miniapp/pages/bookings/index.js @@ -1,28 +1,49 @@ const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace"); +const { customerRequest, customerTokenKey } = require("../../utils/request"); Page({ data: { brand: {}, trustContent: [], records: [], + pageRenderer: "", + error: "", + templateKey: "", + navigation: [], }, onLoad() { - loadWorkspaceWithFallback().then((workspace) => - this.setData({ - brand: workspace.brand || {}, - trustContent: workspace.trustContent || [], - records: wx.getStorageSync("linjingInquiryRecords") || [], - }), - ); + loadWorkspaceWithFallback() + .then((workspace) => + this.setData({ + brand: workspace.brand || {}, + trustContent: workspace.trustContent || [], + pageRenderer: workspace.pageRenderers?.profile || "", + records: [], + templateKey: workspace.visualTemplate?.key || "", + navigation: workspace.navigation || [], + }), + ) + .catch((error) => this.setData({ error: error.message })); }, onShow() { - this.setData({ records: wx.getStorageSync("linjingInquiryRecords") || [] }); + this.loadRecords(); + }, + loadRecords() { + if (!wx.getStorageSync(customerTokenKey())) return this.setData({ records: [] }); + customerRequest("/customer/inquiry-submissions") + .then((records) => this.setData({ records: Array.isArray(records) ? records : [] })) + .catch(() => this.setData({ records: [] })); }, call() { - wx.makePhoneCall({ phoneNumber: (this.data.brand.contactPhone || "").replace(/[^0-9-]/g, "") }); + wx.makePhoneCall({ + phoneNumber: (this.data.brand.phone || this.data.brand.contactPhone || "").replace( + /[^0-9-]/g, + "", + ), + }); }, copyWechat() { wx.setClipboardData({ - data: this.data.brand.contactWechat || "", + data: this.data.brand.wechat || this.data.brand.contactWechat || "", success: () => wx.showToast({ title: "微信号已复制", icon: "none" }), }); }, diff --git a/apps/miniapp/pages/bookings/index.json b/apps/miniapp/pages/bookings/index.json index dddabc6..ae39f88 100644 --- a/apps/miniapp/pages/bookings/index.json +++ b/apps/miniapp/pages/bookings/index.json @@ -4,6 +4,9 @@ "navigationBarTextStyle": "black", "usingComponents": { "t-icon": "/miniprogram_npm/tdesign-miniprogram/icon/icon", - "profile-module": "/components/modules/profile/profile" + "profile-module": "/components/modules/profile/profile", + "linjing-profile": "/components/templates/linjing-profile/linjing-profile", + "acheng-profile": "/components/templates/acheng-profile/acheng-profile", + "runtime-tab-bar": "/components/runtime-tab-bar/runtime-tab-bar" } } diff --git a/apps/miniapp/pages/bookings/index.wxml b/apps/miniapp/pages/bookings/index.wxml index 8298542..3aa7e99 100644 --- a/apps/miniapp/pages/bookings/index.wxml +++ b/apps/miniapp/pages/bookings/index.wxml @@ -1 +1 @@ - 直派服务区域与履约说明直派核心圈:上海、杭州、宁波、苏州、无锡、南京及深圳、广州。主理人及资深装配总工亲赴现场。全国其他城市私邸:接受建筑设计师联合委托,安排远程 3D 激光测绘支持与专用物流直运安装。 一门一档 · 终生质保规约门体内部防变形航空合金骨架承诺 10 年结构质保;重型天地轴、进口地弹簧及磁吸五金 5 年免费维护;每樘门出厂前进行 5000 次启闭校正;原木天然肌理享有首年 2 次木蜡油保养服务。 +{{error}} diff --git a/apps/miniapp/pages/bookings/index.wxss b/apps/miniapp/pages/bookings/index.wxss index 1e25567..c1c3570 100644 --- a/apps/miniapp/pages/bookings/index.wxss +++ b/apps/miniapp/pages/bookings/index.wxss @@ -1,9 +1,19 @@ .page { min-height: 100vh; - padding: 28rpx 32rpx 56rpx; + padding: 0; background: #f7f5f1; color: #252525; } +.runtime-error { + margin: 48rpx 0; + padding: 28rpx; + border: 1rpx solid #e6ded5; + border-radius: 14rpx; + background: #fff; + color: #8a6846; + font-size: 25rpx; + line-height: 1.6; +} .contact-card { padding: 34rpx 30rpx; background: #202221; @@ -151,3 +161,6 @@ display: inline-flex; vertical-align: middle; } +.page { + padding-bottom: 150rpx; +} diff --git a/apps/miniapp/pages/index/index.js b/apps/miniapp/pages/index/index.js index 82dfa4e..267fd9d 100644 --- a/apps/miniapp/pages/index/index.js +++ b/apps/miniapp/pages/index/index.js @@ -1,4 +1,5 @@ const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace"); +const config = require("../../utils/config"); Page({ data: { brand: {}, @@ -6,50 +7,66 @@ Page({ offerings: [], modules: [], moduleVariants: {}, + pageRenderer: "", layout: [], theme: {}, - hero: { - image: - "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=900&q=80", - eyebrow: "", - title: "", - slogan: "", - cta: "了解业务与服务 →", - }, + hero: { image: "", eyebrow: "", title: "", slogan: "", cta: "" }, loading: false, + loadedBrandSlug: "", + templateKey: "", + navigation: [], }, onLoad() { + this.loadWorkspace(); + }, + onShow() { + if (this.data.loadedBrandSlug && this.data.loadedBrandSlug !== config.brandSlug) { + this.loadWorkspace(); + } + }, + loadWorkspace() { this.setData({ loading: true }); - loadWorkspaceWithFallback().then((workspace) => { - const activeBrand = workspace.brand || {}; - const activeOfferings = workspace.offerings || []; - const layout = workspace.layout?.home || [ - "founder-card", - "brand-hero", - "trust-proof", - "trust-manifesto", - "offering-list", - ]; - const firstOffering = activeOfferings[0] || {}; - this.setData({ - brand: activeBrand, - trustContent: workspace.trustContent || [], - offerings: activeOfferings, - modules: workspace.modules || [], - moduleVariants: workspace.moduleVariants || {}, - layout, - theme: workspace.theme || {}, - hero: { - ...this.data.hero, - image: activeBrand.heroImage || this.data.hero.image, - eyebrow: activeBrand.tagline || activeBrand.name, - title: firstOffering.name || activeBrand.name, - slogan: activeBrand.description || "以专业经验建立长期信任", - }, - loading: false, - }); - wx.setNavigationBarTitle({ title: activeBrand.name || "个人品牌" }); - }); + loadWorkspaceWithFallback() + .then((workspace) => { + const activeBrand = workspace.brand || {}; + const activeOfferings = workspace.offerings || []; + const layout = workspace.layout?.home || [ + "founder-card", + "brand-hero", + "trust-proof", + "trust-manifesto", + "offering-list", + ]; + const firstOffering = activeOfferings[0] || {}; + const configuredHero = + activeBrand.homeHero && typeof activeBrand.homeHero === "object" + ? activeBrand.homeHero + : {}; + this.setData({ + brand: activeBrand, + trustContent: workspace.trustContent || [], + offerings: activeOfferings, + modules: workspace.modules || [], + moduleVariants: workspace.moduleVariants || {}, + pageRenderer: workspace.pageRenderers?.home || "", + layout, + theme: workspace.theme || {}, + hero: { + ...this.data.hero, + image: activeBrand.heroImage || this.data.hero.image, + eyebrow: activeBrand.tagline || activeBrand.name, + title: firstOffering.name || activeBrand.name, + slogan: activeBrand.description || "", + ...configuredHero, + }, + loading: false, + loadedBrandSlug: config.brandSlug, + templateKey: workspace.visualTemplate?.key || "", + navigation: workspace.navigation || [], + }); + wx.setNavigationBarTitle({ title: activeBrand.name || "个人品牌" }); + }) + .catch((error) => this.setData({ error: error.message, loading: false })); }, showModule(e) { return this.data.layout.includes(e); @@ -65,6 +82,6 @@ Page({ wx.navigateTo({ url: "/pages/inquiry/index" }); }, goProfile() { - wx.switchTab({ url: "/pages/bookings/index" }); + wx.navigateTo({ url: "/pages/bookings/index" }); }, }); diff --git a/apps/miniapp/pages/index/index.json b/apps/miniapp/pages/index/index.json index dd35b9a..e363cdf 100644 --- a/apps/miniapp/pages/index/index.json +++ b/apps/miniapp/pages/index/index.json @@ -1,10 +1,13 @@ { "navigationBarTitleText": "品牌首页", "usingComponents": { + "linjing-home": "/components/templates/linjing-home/linjing-home", + "acheng-home": "/components/templates/acheng-home/acheng-home", "founder-card": "/components/modules/founder-card/founder-card", "brand-hero": "/components/modules/brand-hero/brand-hero", "trust-proof": "/components/modules/trust-proof/trust-proof", "trust-manifesto": "/components/modules/trust-manifesto/trust-manifesto", - "offering-list": "/components/modules/offering-list/offering-list" + "offering-list": "/components/modules/offering-list/offering-list", + "runtime-tab-bar": "/components/runtime-tab-bar/runtime-tab-bar" } } diff --git a/apps/miniapp/pages/index/index.wxml b/apps/miniapp/pages/index/index.wxml index f9cef6d..60a9108 100644 --- a/apps/miniapp/pages/index/index.wxml +++ b/apps/miniapp/pages/index/index.wxml @@ -1,9 +1,17 @@ + {{error}} + + + + - + - - - + + + + + + diff --git a/apps/miniapp/pages/index/index.wxss b/apps/miniapp/pages/index/index.wxss index ccf37f0..0e70a2c 100644 --- a/apps/miniapp/pages/index/index.wxss +++ b/apps/miniapp/pages/index/index.wxss @@ -4,6 +4,16 @@ min-height: 100vh; padding-bottom: 30rpx; } +.runtime-error { + margin: 48rpx 32rpx; + padding: 28rpx; + border: 1rpx solid #e6ded5; + border-radius: 14rpx; + background: #fff; + color: #8a6846; + font-size: 25rpx; + line-height: 1.6; +} .founder { margin: 32rpx 40rpx 20rpx; padding: 28rpx; @@ -206,3 +216,6 @@ height: 72rpx; line-height: 72rpx; } +.page { + padding-bottom: 150rpx; +} diff --git a/apps/miniapp/pages/inquiry-success/index.js b/apps/miniapp/pages/inquiry-success/index.js index cb5ffc6..d055a3e 100644 --- a/apps/miniapp/pages/inquiry-success/index.js +++ b/apps/miniapp/pages/inquiry-success/index.js @@ -1,11 +1,17 @@ -const { customerRequest } = require("../../utils/request"); +const { customerRequest, customerTokenKey } = require("../../utils/request"); +const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace"); Page({ - data: { record: {} }, + data: { record: {}, presentation: {} }, onLoad(options) { + loadWorkspaceWithFallback() + .then((workspace) => + this.setData({ presentation: workspace.brand?.visualPresentation?.success || {} }), + ) + .catch(() => {}); const record = wx.getStorageSync("latestInquirySubmission") || {}; if (record.id === options.id) this.setData({ record }); - if (options.id && wx.getStorageSync("customerToken")) { + if (options.id && wx.getStorageSync(customerTokenKey())) { customerRequest("/customer/inquiry-submissions/" + encodeURIComponent(options.id)) .then((submission) => this.setData({ @@ -25,6 +31,6 @@ Page({ wx.redirectTo({ url: "/pages/records/index" }); }, home() { - wx.switchTab({ url: "/pages/index/index" }); + wx.navigateTo({ url: "/pages/index/index" }); }, }); diff --git a/apps/miniapp/pages/inquiry-success/index.wxml b/apps/miniapp/pages/inquiry-success/index.wxml index d6c80b3..1729b7e 100644 --- a/apps/miniapp/pages/inquiry-success/index.wxml +++ b/apps/miniapp/pages/inquiry-success/index.wxml @@ -1 +1 @@ - + diff --git a/apps/miniapp/pages/inquiry/index.js b/apps/miniapp/pages/inquiry/index.js index 2fa315d..c78cfa4 100644 --- a/apps/miniapp/pages/inquiry/index.js +++ b/apps/miniapp/pages/inquiry/index.js @@ -1,5 +1,5 @@ const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace"); -const { request, customerRequest } = require("../../utils/request"); +const { request, customerRequest, customerTokenKey } = require("../../utils/request"); Page({ data: { offering: null, @@ -8,31 +8,42 @@ Page({ title: "需求咨询", subtitle: "提交信息后由主理人与你联系", submitLabel: "提交需求", + presentation: {}, values: {}, fields: [], formId: "", + error: "", + templateKey: "", + navigation: [], }, onLoad(options) { - loadWorkspaceWithFallback().then((workspace) => { - const offering = - (workspace.offerings || []).find((item) => item.id === options.offeringId) || null; - const forms = workspace.inquiryForms || []; - const form = - forms.find((item) => item.targetId && item.targetId === options.offeringId) || - forms.find((item) => item.target === "brand") || - forms[0]; - const isQuote = - form?.purpose === "quote-request" || - (workspace.plugins || []).some((plugin) => plugin.key === "quote-request"); - this.setData({ - offering, - fields: form?.fields || workspace.fields || [], - formId: form?.key || form?.id || "", - title: isQuote ? "获取报价方案" : "需求咨询", - eyebrow: isQuote ? "QUOTE REQUEST" : "CONSULTATION", - submitLabel: isQuote ? "提交报价需求" : "提交需求", - }); - }); + loadWorkspaceWithFallback() + .then((workspace) => { + const offering = + (workspace.offerings || []).find((item) => item.id === options.offeringId) || null; + const forms = workspace.inquiryForms || []; + const form = + forms.find((item) => item.targetId && item.targetId === options.offeringId) || + forms.find((item) => item.target === "brand") || + forms[0]; + const isQuote = + form?.purpose === "quote-request" || + (workspace.plugins || []).some((plugin) => plugin.key === "quote-request"); + const presentation = workspace.brand?.visualPresentation?.inquiry || {}; + this.setData({ + offering, + fields: form?.fields || workspace.fields || [], + formId: form?.key || form?.id || "", + title: isQuote ? "获取报价方案" : presentation.title || "需求咨询", + eyebrow: isQuote ? "QUOTE REQUEST" : presentation.eyebrow || "CONSULTATION", + subtitle: presentation.subtitle || "提交信息后由主理人与你联系", + submitLabel: isQuote ? "提交报价需求" : presentation.submitLabel || "提交需求", + presentation, + templateKey: workspace.visualTemplate?.key || "", + navigation: workspace.navigation || [], + }); + }) + .catch((error) => this.setData({ error: error.message })); }, onInput(e) { this.setData({ ["values." + e.currentTarget.dataset.key]: e.detail.value }); @@ -69,12 +80,12 @@ Page({ this.setData({ submitting: false }); wx.showToast({ title: error.message || "提交失败,请重试", icon: "none" }); }; - if (wx.getStorageSync("customerToken")) return send().catch(fail); + if (wx.getStorageSync(customerTokenKey())) return send().catch(fail); wx.login({ success: (login) => request("/customer/session/wechat", { method: "POST", data: { code: login.code } }) .then((result) => { - wx.setStorageSync("customerToken", result.token); + wx.setStorageSync(customerTokenKey(), result.token); return send(); }) .catch(fail), diff --git a/apps/miniapp/pages/inquiry/index.json b/apps/miniapp/pages/inquiry/index.json index 8537ceb..082eb3a 100644 --- a/apps/miniapp/pages/inquiry/index.json +++ b/apps/miniapp/pages/inquiry/index.json @@ -7,6 +7,7 @@ "brand-field": "/components/ui/brand-field/brand-field", "brand-loading": "/components/ui/brand-loading/brand-loading", "brand-empty": "/components/ui/brand-empty/brand-empty", - "inquiry-form": "/components/modules/inquiry-form/inquiry-form" + "inquiry-form": "/components/modules/inquiry-form/inquiry-form", + "runtime-tab-bar": "/components/runtime-tab-bar/runtime-tab-bar" } } diff --git a/apps/miniapp/pages/inquiry/index.wxml b/apps/miniapp/pages/inquiry/index.wxml index 1998b96..f493f26 100644 --- a/apps/miniapp/pages/inquiry/index.wxml +++ b/apps/miniapp/pages/inquiry/index.wxml @@ -1 +1 @@ -{{eyebrow}}{{title}}{{offering ? offering.name : subtitle}} +{{error}}{{eyebrow}}{{title}}{{offering ? offering.name : subtitle}}{{presentation.note}} diff --git a/apps/miniapp/pages/inquiry/index.wxss b/apps/miniapp/pages/inquiry/index.wxss index 0b1484a..71c83ac 100644 --- a/apps/miniapp/pages/inquiry/index.wxss +++ b/apps/miniapp/pages/inquiry/index.wxss @@ -3,6 +3,91 @@ background: #f7f5f1; color: #252525; } +.page { + padding-bottom: 150rpx; +} +.page { + min-height: 100vh; + background: #fff8f0; + color: #29231f; +} +.booking-hero { + padding: 52rpx 32rpx 30rpx; + background: linear-gradient(180deg, #fff1df, #fff8f0); +} +.booking-hero .eyebrow { + display: block; + color: #c65c28; + font-size: 22rpx; + font-weight: 700; +} +.booking-hero .title { + display: block; + margin-top: 14rpx; + font-size: 44rpx; + font-weight: 800; + line-height: 1.2; +} +.booking-hero .sub { + display: block; + margin-top: 14rpx; + color: #7a6a60; + font-size: 24rpx; + line-height: 1.7; +} +.booking-note { + display: flex; + justify-content: space-between; + margin: 0 32rpx 20rpx; + padding: 20rpx 22rpx; + border: 1rpx solid #f3d1b2; + border-radius: 20rpx; + background: #fff; + color: #a4562d; + font-size: 21rpx; +} +.form-panel { + margin: 0 24rpx; + padding: 10rpx 8rpx 24rpx; + border: 1rpx solid #f1e1d5; + border-radius: 28rpx; + background: #fff; + box-shadow: 0 12rpx 28rpx rgba(145, 75, 33, 0.06); +} +.form-panel .form { + padding: 20rpx; +} +.form-panel .field { + margin-bottom: 20rpx; +} +.form-panel .label { + color: #4f3020; + font-weight: 700; +} +.form-panel input, +.form-panel textarea, +.form-panel .picker-value { + border: 1rpx solid #eaded5; + border-radius: 16rpx; + background: #fffaf6; +} +.form-panel .submit { + height: 82rpx; + border-radius: 20rpx; + background: #e87532; + color: #fff; + line-height: 82rpx; +} +.runtime-error { + margin: 48rpx 32rpx; + padding: 28rpx; + border: 1rpx solid #e6ded5; + border-radius: 14rpx; + background: #fff; + color: #8a6846; + font-size: 25rpx; + line-height: 1.6; +} .head { background: #252827; color: #fff; @@ -65,3 +150,6 @@ font-size: 20rpx; margin-top: 26rpx; } +.page { + padding-bottom: 150rpx; +} diff --git a/apps/miniapp/pages/offering/detail.js b/apps/miniapp/pages/offering/detail.js index e29c6ab..895fd57 100644 --- a/apps/miniapp/pages/offering/detail.js +++ b/apps/miniapp/pages/offering/detail.js @@ -1,14 +1,20 @@ const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace"); Page({ - data: { item: null, loading: true }, + data: { item: null, loading: true, error: "", presentation: {} }, onLoad(options) { - loadWorkspaceWithFallback().then((workspace) => { - const offerings = workspace.offerings || []; - const item = offerings.find((entry) => entry.id === options.id) || offerings[0]; - if (!item) return this.setData({ loading: false }); - this.setData({ item, loading: false }); - wx.setNavigationBarTitle({ title: item.category || item.name }); - }); + loadWorkspaceWithFallback() + .then((workspace) => { + const offerings = workspace.offerings || []; + const item = offerings.find((entry) => entry.id === options.id) || offerings[0]; + if (!item) return this.setData({ loading: false, error: "未找到可展示的业务提供项" }); + this.setData({ + item, + loading: false, + presentation: workspace.brand?.visualPresentation?.detail || {}, + }); + wx.setNavigationBarTitle({ title: item.category || item.name }); + }) + .catch((error) => this.setData({ loading: false, error: error.message })); }, inquire() { wx.navigateTo({ url: "/pages/inquiry/index?offeringId=" + this.data.item.id }); diff --git a/apps/miniapp/pages/offering/detail.wxml b/apps/miniapp/pages/offering/detail.wxml index c9cac82..630f1af 100644 --- a/apps/miniapp/pages/offering/detail.wxml +++ b/apps/miniapp/pages/offering/detail.wxml @@ -1 +1 @@ - +{{error}} diff --git a/apps/miniapp/pages/offering/detail.wxss b/apps/miniapp/pages/offering/detail.wxss index 29f9a83..d4c5b90 100644 --- a/apps/miniapp/pages/offering/detail.wxss +++ b/apps/miniapp/pages/offering/detail.wxss @@ -4,6 +4,16 @@ color: #252525; padding-bottom: 150rpx; } +.runtime-error { + margin: 48rpx 32rpx; + padding: 28rpx; + border: 1rpx solid #e6ded5; + border-radius: 14rpx; + background: #fff; + color: #8a6846; + font-size: 25rpx; + line-height: 1.6; +} .hero { width: 100%; height: 600rpx; diff --git a/apps/miniapp/pages/records/index.js b/apps/miniapp/pages/records/index.js index d0abdf0..240a1ac 100644 --- a/apps/miniapp/pages/records/index.js +++ b/apps/miniapp/pages/records/index.js @@ -1,4 +1,5 @@ -const { customerRequest } = require("../../utils/request"); +const { customerRequest, customerTokenKey } = require("../../utils/request"); +const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace"); const statusLabels = { new: "待处理", @@ -10,9 +11,16 @@ const statusLabels = { }; Page({ - data: { records: [], loading: false }, + data: { records: [], loading: false, presentation: {} }, + onLoad() { + loadWorkspaceWithFallback() + .then((workspace) => + this.setData({ presentation: workspace.brand?.visualPresentation?.records || {} }), + ) + .catch(() => {}); + }, onShow() { - if (!wx.getStorageSync("customerToken")) return this.setData({ records: [] }); + if (!wx.getStorageSync(customerTokenKey())) return this.setData({ records: [] }); this.setData({ loading: true }); customerRequest("/customer/inquiry-submissions") .then((items) => diff --git a/apps/miniapp/pages/records/index.wxml b/apps/miniapp/pages/records/index.wxml index b4bbff5..866fc1c 100644 --- a/apps/miniapp/pages/records/index.wxml +++ b/apps/miniapp/pages/records/index.wxml @@ -1 +1 @@ -我的咨询记录 +{{presentation.title}} diff --git a/apps/miniapp/pages/services/index.js b/apps/miniapp/pages/services/index.js index 50b4708..3939a70 100644 --- a/apps/miniapp/pages/services/index.js +++ b/apps/miniapp/pages/services/index.js @@ -1,4 +1,5 @@ const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace"); +const config = require("../../utils/config"); Page({ data: { loading: false, @@ -7,28 +8,64 @@ Page({ filtered: [], modules: [], theme: {}, - category: "全部", + brand: {}, + presentation: {}, + category: "all", + categories: [], + pageRenderer: "", + loadedBrandSlug: "", + templateKey: "", + navigation: [], }, onLoad() { - loadWorkspaceWithFallback().then((workspace) => { - const items = workspace.offerings || []; - this.setData({ - offerings: items, - filtered: items, - modules: workspace.modules || [], - theme: workspace.theme || {}, - }); - }); + this.loadWorkspace(); + }, + onShow() { + if (this.data.loadedBrandSlug && this.data.loadedBrandSlug !== config.brandSlug) { + this.loadWorkspace(); + } + }, + loadWorkspace() { + loadWorkspaceWithFallback() + .then((workspace) => { + const items = workspace.offerings || []; + this.setData({ + offerings: items, + filtered: items, + categories: [ + { key: "all", label: "全部" }, + ...Array.from(new Set(items.map((item) => item.category).filter(Boolean))).map( + (key) => ({ + key, + label: key, + }), + ), + ], + modules: workspace.modules || [], + theme: workspace.theme || {}, + brand: workspace.brand || {}, + presentation: workspace.brand?.visualPresentation?.offerings || {}, + brand: workspace.brand || {}, + pageRenderer: workspace.pageRenderers?.offerings || "", + loadedBrandSlug: config.brandSlug, + templateKey: workspace.visualTemplate?.key || "", + navigation: workspace.navigation || [], + }); + }) + .catch((error) => this.setData({ error: error.message })); }, switchCategory(e) { const category = e.currentTarget.dataset.category; const items = this.data.offerings || []; this.setData({ category, - filtered: category === "全部" ? items : items.filter((item) => item.category === category), + filtered: category === "all" ? items : items.filter((item) => item.category === category), }); }, open(e) { wx.navigateTo({ url: "/pages/offering/detail?id=" + e.currentTarget.dataset.id }); }, + inquire() { + wx.navigateTo({ url: "/pages/inquiry/index" }); + }, }); diff --git a/apps/miniapp/pages/services/index.json b/apps/miniapp/pages/services/index.json index 5196c18..7df6e9b 100644 --- a/apps/miniapp/pages/services/index.json +++ b/apps/miniapp/pages/services/index.json @@ -3,7 +3,10 @@ "navigationBarBackgroundColor": "#FBF7F1", "navigationBarTextStyle": "black", "usingComponents": { + "acheng-offerings": "/components/templates/acheng-offerings/acheng-offerings", + "linjing-offerings": "/components/templates/linjing-offerings/linjing-offerings", "brand-loading": "/components/ui/brand-loading/brand-loading", - "brand-empty": "/components/ui/brand-empty/brand-empty" + "brand-empty": "/components/ui/brand-empty/brand-empty", + "runtime-tab-bar": "/components/runtime-tab-bar/runtime-tab-bar" } } diff --git a/apps/miniapp/pages/services/index.wxml b/apps/miniapp/pages/services/index.wxml index a766f96..8d2a47f 100644 --- a/apps/miniapp/pages/services/index.wxml +++ b/apps/miniapp/pages/services/index.wxml @@ -1 +1 @@ -LINJING ATELIER作品与系统每一扇门,都是建筑秩序的一部分。{{item}}{{item.category}} · {{item.tag}}{{item.name}}{{item.series}}{{item.desc}}{{item.area}}查看详情 → +{{error}}{{brand.name}}{{presentation.title}}{{presentation.subtitle}}{{item.label}}{{item.category}}{{item.tag}}{{item.area}}{{item.spaceType}}{{item.name}}{{item.series}}{{presentation.materialLabel}}{{item.woodMaterial}}{{presentation.hardwareLabel}}{{item.hardware}} diff --git a/apps/miniapp/pages/services/index.wxss b/apps/miniapp/pages/services/index.wxss index 359c865..8f3af06 100644 --- a/apps/miniapp/pages/services/index.wxss +++ b/apps/miniapp/pages/services/index.wxss @@ -3,6 +3,16 @@ min-height: 100vh; color: #252525; } +.runtime-error { + margin: 48rpx 32rpx; + padding: 28rpx; + border: 1rpx solid #e6ded5; + border-radius: 14rpx; + background: #fff; + color: #8a6846; + font-size: 25rpx; + line-height: 1.6; +} .head { background: #252827; color: #fff; @@ -48,12 +58,64 @@ .card { background: #fff; margin-bottom: 30rpx; + overflow: hidden; + border: 1rpx solid #e6ded5; + border-radius: 18rpx; + box-shadow: 0 10rpx 30rpx -12rpx rgba(32, 34, 33, 0.08); +} +.media { + position: relative; + height: 380rpx; + background: #202221; } .card image { width: 100%; - height: 380rpx; + height: 100%; display: block; } +.media-category, +.media-tag, +.media-meta { + position: absolute; + color: #fff; + font-size: 20rpx; +} +.media-category { + top: 20rpx; + left: 20rpx; + padding: 8rpx 14rpx; + border: 1rpx solid rgba(255, 255, 255, 0.15); + border-radius: 8rpx; + background: rgba(32, 34, 33, 0.76); + color: #d9c8b2; +} +.media-tag { + top: 20rpx; + right: 20rpx; + padding: 8rpx 14rpx; + border-radius: 6rpx; + background: #8a6846; +} +.media-meta { + right: 20rpx; + bottom: 20rpx; + left: 20rpx; + display: flex; + justify-content: space-between; + gap: 20rpx; + padding: 10rpx 14rpx; + border: 1rpx solid rgba(255, 255, 255, 0.12); + border-radius: 10rpx; + background: rgba(0, 0, 0, 0.4); + color: rgba(255, 255, 255, 0.9); + font-size: 19rpx; +} +.media-meta text:last-child { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + color: #d9c8b2; +} .card-body { padding: 28rpx; } @@ -80,6 +142,49 @@ line-height: 1.7; margin-top: 18rpx; } +.specs { + margin-top: 20rpx; + padding: 18rpx; + border: 1rpx solid #e6ded5; + border-radius: 12rpx; + background: #f7f5f1; + color: #252525; + font-size: 20rpx; + line-height: 1.55; +} +.specs view { + display: flex; + gap: 8rpx; +} +.specs view + view { + margin-top: 10rpx; +} +.specs text:first-child { + flex: 0 0 auto; + color: #77736b; +} +.actions { + display: flex; + gap: 14rpx; + margin-top: 22rpx; +} +.actions button { + flex: 1; + height: 70rpx; + margin: 0; + border-radius: 12rpx; + font-size: 21rpx; + line-height: 70rpx; +} +.detail { + border: 1rpx solid #202221; + background: #fff; + color: #202221; +} +.inquire { + background: #8a6846; + color: #fff; +} .foot { display: flex; justify-content: space-between; @@ -92,3 +197,6 @@ .arrow { color: #8a6846; } +.page { + padding-bottom: 150rpx; +} diff --git a/apps/miniapp/pages/stall-service/index.js b/apps/miniapp/pages/stall-service/index.js new file mode 100644 index 0000000..4edc0de --- /dev/null +++ b/apps/miniapp/pages/stall-service/index.js @@ -0,0 +1,17 @@ +const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace"); +Page({ + data: { brand: {}, templateKey: "", presentation: {}, navigation: [], loading: true }, + onLoad() { + loadWorkspaceWithFallback() + .then((workspace) => + this.setData({ + brand: workspace.brand || {}, + templateKey: workspace.visualTemplate?.key || "", + presentation: workspace.brand?.visualPresentation?.home || {}, + navigation: workspace.navigation || [], + loading: false, + }), + ) + .catch(() => this.setData({ loading: false })); + }, +}); diff --git a/apps/miniapp/pages/stall-service/index.json b/apps/miniapp/pages/stall-service/index.json new file mode 100644 index 0000000..4208aee --- /dev/null +++ b/apps/miniapp/pages/stall-service/index.json @@ -0,0 +1,4 @@ +{ + "navigationBarTitleText": "出摊服务", + "usingComponents": { "runtime-tab-bar": "/components/runtime-tab-bar/runtime-tab-bar" } +} diff --git a/apps/miniapp/pages/stall-service/index.wxml b/apps/miniapp/pages/stall-service/index.wxml new file mode 100644 index 0000000..3188259 --- /dev/null +++ b/apps/miniapp/pages/stall-service/index.wxml @@ -0,0 +1 @@ +出摊与服务今天在哪里,怎么取餐{{brand.hours || '营业时间以当天通知为准'}}固定出摊与取餐{{brand.studioAddress || brand.address || '校园生活区附近'}}支持摊位自取、校内配送,以及班级和社团活动定制。定制餐品流程1. 提交人数、时间和口味需求2. 主理人确认菜单与取餐方式3. 当天现做并按约定时间交付 diff --git a/apps/miniapp/pages/stall-service/index.wxss b/apps/miniapp/pages/stall-service/index.wxss new file mode 100644 index 0000000..8f52ff9 --- /dev/null +++ b/apps/miniapp/pages/stall-service/index.wxss @@ -0,0 +1,42 @@ +.page { + min-height: 100vh; + padding: 28rpx 32rpx 150rpx; + background: #fff8f0; + color: #29231f; +} +.head { + padding: 38rpx 4rpx 28rpx; +} +.eyebrow { + display: block; + color: #c65c28; + font-size: 22rpx; +} +.title { + display: block; + margin-top: 12rpx; + font-size: 42rpx; + font-weight: 800; +} +.sub { + display: block; + margin-top: 12rpx; + color: #7a6a60; + font-size: 24rpx; +} +.card { + display: flex; + flex-direction: column; + gap: 14rpx; + margin-bottom: 22rpx; + padding: 28rpx; + border: 1rpx solid #f2d9c6; + border-radius: 24rpx; + background: #fff; + line-height: 1.7; +} +.card-title { + color: #4f3020; + font-size: 29rpx; + font-weight: 700; +} diff --git a/apps/miniapp/test/fixtures/acheng-campus-food-visual.json b/apps/miniapp/test/fixtures/acheng-campus-food-visual.json new file mode 100644 index 0000000..e6bb5a4 --- /dev/null +++ b/apps/miniapp/test/fixtures/acheng-campus-food-visual.json @@ -0,0 +1,28 @@ +{ + "templateKey": "acheng-campus-food", + "viewport": { "width": 375, "height": 812 }, + "states": { + "home": { + "page": "pages/index/index", + "anchors": ["acheng-home", "brand-card", "今日菜单", "现做现吃"] + }, + "offerings": { + "page": "pages/services/index", + "anchors": ["acheng-offerings", "今日菜单", "团体活动"] + }, + "detail": { "page": "pages/offering/detail", "anchors": ["inquire"] }, + "inquiry": { "page": "pages/inquiry/index", "anchors": ["提交"] }, + "success": { + "page": "pages/inquiry-success/index", + "anchors": ["presentation.title"] + }, + "records": { + "page": "pages/records/index", + "anchors": ["presentation.title"] + }, + "profile": { + "page": "pages/bookings/index", + "anchors": ["acheng-profile", "出摊与配送"] + } + } +} diff --git a/apps/miniapp/test/fixtures/doors-visual.json b/apps/miniapp/test/fixtures/doors-visual.json index ffa61ea..b21fdab 100644 --- a/apps/miniapp/test/fixtures/doors-visual.json +++ b/apps/miniapp/test/fixtures/doors-visual.json @@ -6,11 +6,26 @@ "page": "pages/index/index", "anchors": ["founder-card", "brand-hero", "trust-proof", "offering-list"] }, - "offerings": { "page": "pages/services/index", "anchors": ["作品与系统", "查看详情"] }, - "detail": { "page": "pages/offering/detail", "anchors": ["预约测量"] }, + "offerings": { + "page": "pages/services/index", + "anchors": ["presentation.title", "presentation.detailAction", "presentation.inquiryAction"] + }, + "detail": { + "page": "pages/offering/detail", + "anchors": ["presentation.craftsTitle", "presentation.inquiryAction"] + }, "inquiry": { "page": "pages/inquiry/index", "anchors": ["提交"] }, - "success": { "page": "pages/inquiry-success/index", "anchors": ["已收到", "查看"] }, - "records": { "page": "pages/records/index", "anchors": ["咨询记录", "咨询"] }, - "profile": { "page": "pages/bookings/index", "anchors": ["直派服务区域与履约说明", "一门一档"] } + "success": { + "page": "pages/inquiry-success/index", + "anchors": ["presentation.title", "presentation.recordsAction"] + }, + "records": { + "page": "pages/records/index", + "anchors": ["presentation.title", "presentation.createAction"] + }, + "profile": { + "page": "pages/bookings/index", + "anchors": ["presentation.coverageTitle", "presentation.warrantyTitle"] + } } } diff --git a/apps/miniapp/test/fixtures/linjing-door-visual.json b/apps/miniapp/test/fixtures/linjing-door-visual.json index a6df402..6f56546 100644 --- a/apps/miniapp/test/fixtures/linjing-door-visual.json +++ b/apps/miniapp/test/fixtures/linjing-door-visual.json @@ -4,13 +4,33 @@ "states": { "home": { "page": "pages/index/index", - "anchors": ["founder-card", "brand-hero", "trust-proof", "trust-manifesto", "offering-list"] + "anchors": [ + "linjing-home", + "presentation.founderBadge", + "presentation.manifestoEyebrow", + "presentation.flowTitle" + ] + }, + "offerings": { + "page": "pages/services/index", + "anchors": ["presentation.title", "presentation.detailAction", "presentation.inquiryAction"] + }, + "detail": { + "page": "pages/offering/detail", + "anchors": ["presentation.craftsTitle", "presentation.inquiryAction"] }, - "offerings": { "page": "pages/services/index", "anchors": ["作品与系统", "查看详情"] }, - "detail": { "page": "pages/offering/detail", "anchors": ["预约测量"] }, "inquiry": { "page": "pages/inquiry/index", "anchors": ["提交"] }, - "success": { "page": "pages/inquiry-success/index", "anchors": ["已收到", "查看"] }, - "records-empty": { "page": "pages/records/index", "anchors": ["咨询记录", "咨询"] }, - "profile": { "page": "pages/bookings/index", "anchors": ["直派服务区域与履约说明", "一门一档"] } + "success": { + "page": "pages/inquiry-success/index", + "anchors": ["presentation.title", "presentation.recordsAction"] + }, + "records-empty": { + "page": "pages/records/index", + "anchors": ["presentation.title", "presentation.createAction"] + }, + "profile": { + "page": "pages/bookings/index", + "anchors": ["presentation.coverageTitle", "presentation.warrantyTitle"] + } } } diff --git a/apps/miniapp/test/fixtures/minimal-neutral-visual.json b/apps/miniapp/test/fixtures/minimal-neutral-visual.json deleted file mode 100644 index 9cbfcc5..0000000 --- a/apps/miniapp/test/fixtures/minimal-neutral-visual.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "templateKey": "personal+minimal-neutral", - "viewport": { "width": 375, "height": 812 }, - "states": { - "home": { - "page": "pages/index/index", - "anchors": ["brand-hero", "founder-card", "offering-list", "trust-proof"] - }, - "offerings": { "page": "pages/services/index", "anchors": ["作品与系统", "查看详情"] }, - "detail": { "page": "pages/offering/detail", "anchors": ["预约测量"] }, - "inquiry": { "page": "pages/inquiry/index", "anchors": ["提交"] }, - "success": { "page": "pages/inquiry-success/index", "anchors": ["已收到", "查看"] }, - "records-empty": { "page": "pages/records/index", "anchors": ["咨询记录", "咨询"] }, - "profile": { "page": "pages/bookings/index", "anchors": ["直派服务区域与履约说明", "一门一档"] } - } -} diff --git a/apps/miniapp/test/fixtures/minimal-neutral.json b/apps/miniapp/test/fixtures/minimal-neutral.json deleted file mode 100644 index c101363..0000000 --- a/apps/miniapp/test/fixtures/minimal-neutral.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "templateKey": "personal+minimal-neutral", - "version": "1.0.0", - "pages": ["home", "offerings", "detail", "inquiry", "success", "records", "profile"], - "layout": { - "home": ["brand-hero", "founder-card", "offering-list", "trust-proof"], - "offerings": ["offering-list"], - "detail": ["offering-detail"], - "profile": ["profile"] - }, - "requiredModules": [ - "brand-hero", - "founder-card", - "trust-proof", - "offering-list", - "offering-detail", - "inquiry-form", - "records", - "profile", - "success-summary" - ], - "visualAnchors": { "home": ["brand-hero", "founder-card", "offering-list", "trust-proof"] } -} diff --git a/apps/miniapp/test/runtime-workspace.test.cjs b/apps/miniapp/test/runtime-workspace.test.cjs new file mode 100644 index 0000000..de4c028 --- /dev/null +++ b/apps/miniapp/test/runtime-workspace.test.cjs @@ -0,0 +1,45 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const test = require("node:test"); +const vm = require("node:vm"); + +const source = fs.readFileSync(path.join(__dirname, "../utils/runtime-workspace.js"), "utf8"); + +function loadWithResponse(response) { + const module = { exports: {} }; + const storage = { + getStorageSync() { + throw new Error("不应读取旧缓存"); + }, + setStorageSync() { + throw new Error("不应缓存公开内容"); + }, + }; + vm.runInNewContext(source, { + module, + wx: storage, + require(id) { + if (id === "./request") return { request: () => Promise.resolve(response) }; + if (id === "./module-registry") return { resolveRuntime: () => ({}) }; + throw new Error(`意外依赖:${id}`); + }, + }); + return module.exports.loadWorkspaceWithFallback(); +} + +test("未发布品牌不会使用旧 workspace 缓存", async () => { + await assert.rejects( + loadWithResponse({ publication: { status: "unpublished" }, brand: null }), + /品牌尚未发布/, + ); +}); + +test("已发布 workspace 正常返回", async () => { + const workspace = await loadWithResponse({ + publication: { status: "published" }, + brand: { name: "测试品牌" }, + offerings: [], + }); + assert.equal(workspace.brand.name, "测试品牌"); +}); diff --git a/apps/miniapp/test/validate-fixture.cjs b/apps/miniapp/test/validate-fixture.cjs index d970b8a..ef95c91 100644 --- a/apps/miniapp/test/validate-fixture.cjs +++ b/apps/miniapp/test/validate-fixture.cjs @@ -3,6 +3,8 @@ const path = require("node:path"); const root = path.resolve(__dirname, ".."); const requestSource = fs.readFileSync(path.join(root, "utils/request.js"), "utf8"); const configSource = fs.readFileSync(path.join(root, "utils/config.js"), "utf8"); +const moduleRegistrySource = fs.readFileSync(path.join(root, "utils/module-registry.js"), "utf8"); +const runtimeRequestSource = fs.readFileSync(path.join(root, "utils/request.js"), "utf8"); if ( !requestSource.includes('path.startsWith("/public/")') || !requestSource.includes("brandSlug") || @@ -11,7 +13,37 @@ if ( console.error("miniapp: public requests must carry the configured brand slug"); process.exit(1); } -const fixtureFiles = ["linjing-door.json", "minimal-neutral.json", "doors-industry.json"]; +if (!moduleRegistrySource.includes("Object.values(manifest?.pages || {})")) { + console.error("miniapp: visual page renderers must resolve from the manifest"); + process.exit(1); +} +if ( + !runtimeRequestSource.includes('path.startsWith("/customer/session/wechat")') || + !runtimeRequestSource.includes('"customerToken:" + config.brandSlug') +) { + console.error("miniapp: customer sessions must be brand-scoped"); + process.exit(1); +} +const productionRoots = ["components/modules", "components/templates", "pages"]; +const productionSources = []; +function collectSources(directory) { + const current = path.join(root, directory); + for (const item of fs.readdirSync(current, { withFileTypes: true })) { + const itemPath = path.join(current, item.name); + if (item.isDirectory()) collectSources(path.relative(root, itemPath)); + else if (itemPath.endsWith(".js") || itemPath.endsWith(".wxml")) + productionSources.push({ file: itemPath, content: fs.readFileSync(itemPath, "utf8") }); + } +} +productionRoots.forEach(collectSources); +for (const term of ["林境门", "亲自主理量房", "拒绝流水线拼装", "linjingInquiryRecords"]) { + const leak = productionSources.find(({ content }) => content.includes(term)); + if (leak) { + console.error(`miniapp: static business term ${term} leaked into ${leak.file}`); + process.exit(1); + } +} +const fixtureFiles = ["linjing-door.json", "doors-industry.json"]; const fixtures = fixtureFiles.map((file) => JSON.parse(fs.readFileSync(path.join(__dirname, "fixtures", file), "utf8")), ); diff --git a/apps/miniapp/test/validate-visual-fixture.cjs b/apps/miniapp/test/validate-visual-fixture.cjs index ca50276..fd0475d 100644 --- a/apps/miniapp/test/validate-visual-fixture.cjs +++ b/apps/miniapp/test/validate-visual-fixture.cjs @@ -3,8 +3,8 @@ const path = require("node:path"); const root = path.resolve(__dirname, ".."); const fixtureFiles = [ "linjing-door-visual.json", - "minimal-neutral-visual.json", "doors-visual.json", + "acheng-campus-food-visual.json", ]; const fixtures = fixtureFiles.map((file) => JSON.parse(fs.readFileSync(path.join(__dirname, "fixtures", file), "utf8")), @@ -22,8 +22,10 @@ for (const fixture of fixtures) { .map((match) => match[1]) .filter((name) => name.includes("-")); for (const ref of componentRefs) { - const candidate = path.join(root, "components/modules", ref, `${ref}.wxml`); - if (fs.existsSync(candidate)) content += fs.readFileSync(candidate, "utf8"); + for (const componentRoot of ["components/modules", "components/templates"]) { + const candidate = path.join(root, componentRoot, ref, `${ref}.wxml`); + if (fs.existsSync(candidate)) content += fs.readFileSync(candidate, "utf8"); + } } for (const anchor of definition.anchors) if (!content.includes(anchor)) failures.push(`${state}: missing anchor ${anchor}`); diff --git a/apps/miniapp/utils/fallback-workspaces.js b/apps/miniapp/utils/fallback-workspaces.js deleted file mode 100644 index 369233f..0000000 --- a/apps/miniapp/utils/fallback-workspaces.js +++ /dev/null @@ -1,31 +0,0 @@ -const doorFallback = require("./linjing-data"); - -const base = (name, tagline) => ({ - schemaVersion: "fallback-1.0", - brand: { - id: "fallback", - name, - tagline, - description: "以专业经验建立长期信任。", - contactPhone: "", - contactWechat: "", - }, - offerings: [], - trustContent: [], - fields: [], - modules: [], - capabilities: [], - theme: {}, -}); - -const fallbacks = { - doors: { ...doorFallback, schemaVersion: "fallback-doors-1.0", template: { key: "doors" } }, - food: base("个人品牌", "私房菜与定制服务"), - personal: base("个人品牌", "专业经验与可信赖的合作方式"), -}; - -function getFallbackWorkspace(templateKey) { - return fallbacks[templateKey] || fallbacks.personal; -} - -module.exports = { getFallbackWorkspace }; diff --git a/apps/miniapp/utils/linjing-data.js b/apps/miniapp/utils/linjing-data.js deleted file mode 100644 index 305cf20..0000000 --- a/apps/miniapp/utils/linjing-data.js +++ /dev/null @@ -1,201 +0,0 @@ -const brand = { - name: "林境门作", - tagline: "私享定制", - founder: "梅记兵", - title: "高端门系统建筑研造主理人", - slogan: "为当代别墅空间,定制有秩序感与呼吸感的门", - bio: "国家注册高级室内建筑师,专注高定大门及私宅空间门类系统研发 14 年。拒绝建材量产拼装,以“门与空间同构”之建筑理念,亲自主理选材、构造深化与落地试装。", - experienceYears: 14, - completedProjects: "260+", - coverageArea: "长三角、珠三角核心别墅群及全国私家庄园", - phone: "153-7712-8361", - wechat: "LIN-ATELIER-2024", - studioAddress: "上海市 · 林境门作私享工坊", - studioAddress: "上海市静安区威海路设计中心 A 座 / 杭州良渚研造工坊", -}; -const trustContent = { - stats: [ - { value: "14年", label: "高端门系深化经验", sub: "历经百项严苛私宅考验" }, - { value: "260+", label: "落地庄园实景案例", sub: "全实景图库,可预约探访" }, - { value: "100%", label: "主理人全案跟进", sub: "量房 / 出图 / 选料 / 试装" }, - { value: "10年", label: "结构主轴质保承诺", sub: "终生五金润滑维保机制" }, - ], - pillars: [ - { - icon: "tree", - title: "天然厚板与古铜锻打", - desc: "精选 300 年北美黑胡桃、缅甸柚木直拼大板,搭配手工冷锻紫铜及意大利防爆钢核。", - }, - { - icon: "ruler", - title: "微米级红外高精量房", - desc: "德国进口 3D 空间激光扫描,精准捕捉门洞沉降公差与建筑墙体垂直度,杜绝返工。", - }, - { - icon: "shield", - title: "隐匿式重型五金系统", - desc: "自主研发三维可调静音承重铰链,单扇承载 450kg,开合轻盈如羽,静如深山。", - }, - ], - serviceFlow: [ - { step: "01", name: "私享沟通", desc: "勘定建筑图纸与设计意图,厘清生活动线与风候环境" }, - { step: "02", name: "上门实测", desc: "主理人携激光雷达亲赴现场,复核门洞公差与地平基准" }, - { step: "03", name: "构造出图", desc: "输出 1:1 断面结构图、五金受力分析与材质节点方案" }, - { step: "04", name: "实样工坊确认", desc: "寄送天然木样、锻铜样块及密封胶条试样实物封样" }, - { step: "05", name: "工坊试装交付", desc: "原厂精密试装调试无误后专车直运现场,技师组装" }, - { step: "06", name: "终生私属维护", desc: "建立一门一档数字化档案,首年两次免维保巡检" }, - ], -}; -const offerings = [ - { - id: "entrance_door", - category: "入户大门", - name: "当代铸铜木核防暴装甲门", - series: "「万籁」重型天地轴入户系统", - tag: "主理人年度代表作", - image: - "https://images.unsplash.com/photo-1513694203232-719a280e022f?auto=format&fit=crop&w=900&q=80", - detailHero: - "https://images.unsplash.com/photo-1513694203232-719a280e022f?auto=format&fit=crop&w=1000&q=85", - priceRange: "¥38,000 - ¥85,000 / 樘", - desc: "天然厚板、锻铜与隐匿式重型五金,为别墅入口建立沉稳仪式感。", - woodMaterial: "60mm 北美特级黑胡桃整板 + 航空蜂窝铝芯", - hardware: "德国 dormakaba 重型地弹簧 + 自主定制实心锻铜一体式长执手(高 2400mm)", - spaceType: "独栋别墅建筑主入口 / 挑高大厅玄关", - keywords: ["厚重大气", "隐式天地轴", "隔音 42dB", "抗暴防撬"], - area: "浙江 · 莫干山私家山庄", - enabled: true, - details: { - background: - "项目位于浙北山间独栋庄园,常年多雨潮湿,且冬季山风冷峻。业主期望一扇既有古典厚重仪式感,又能抵御风雨、长久耐候的当代东方大门。", - designConcept: - "打破繁复雕花的欧式门逻辑,提炼江南屋檐与青砖比例。以暗调冷锻手工铜板包裹耐候钢核,内衬大厚度吸音绝热芯,门体内嵌隐藏式天地承重轴,推拉阻尼丝滑沉稳。", - crafts: [ - "无缝冷锻铜边框,经自然氧化着色,泛深幽青褐金属光泽", - "双道三元乙丙航天级发泡密封胶条,气密性达国标 8 级最高标准", - "指纹识别模组完全隐于天然胡桃木纹理深处,不露丝毫电子廉价感", - ], - materialsList: [ - { name: "门扇主体", spec: "航空铝蜂窝 + 防暴钢板 + 黑胡桃" }, - { name: "承重结构", spec: "不锈钢重型天地偏心轴(承重 600KG)" }, - { name: "五金执手", spec: "实心黄铜拉丝防指纹覆膜,重 7.2kg" }, - { name: "锁具系统", spec: "C 级多向防暴机械锁芯 + 隐匿式生物辨识" }, - ], - }, - }, - { - id: "courtyard_door", - category: "庭院围墙门", - name: "悬挑风琴式耐候双开院门", - series: "「虚实」透光私家庭院门", - tag: "建筑级耐候工艺", - image: - "https://images.unsplash.com/photo-1541123437800-1bb1317badc2?auto=format&fit=crop&w=900&q=80", - detailHero: - "https://images.unsplash.com/photo-1541123437800-1bb1317badc2?auto=format&fit=crop&w=1000&q=85", - priceRange: "¥42,000 - ¥98,000 / 樘", - desc: "以格栅光影平衡私密与通透,让院门成为建筑与自然的过渡。", - woodMaterial: "深浸缅甸柚木条格栅 + 氟碳喷涂耐候钢", - hardware: "意大利全隐形地埋式液压自闭器 + 静音电控锁", - spaceType: "私家庭院入口 / 围墙园林玄关", - keywords: ["园林意境", "格栅光影", "耐候耐蚀", "智能对讲协同"], - area: "上海 · 佘山高尔夫别墅", - enabled: true, - details: { - background: - "庭院门直面自然日晒雨淋,普通木门极易开裂变形,普通铁艺门几年内斑驳锈蚀。本案要求 20 年免维护的高级自然质感。", - designConcept: - "利用竖向错落的柚木条构建视线遮蔽与透光的微妙平衡,外部无法看穿内部庭院,内部向外望去则如薄纱透竹。", - crafts: [ - "微隙热胀冷缩结构槽设计,预留木材季候伸缩呼吸余量", - "隐蔽式水路导流坡口,雨水冲刷即自然滑落不积水", - "院墙铰链锚栓深入混凝土柱芯 300mm,经历 14 级台风无晃动", - ], - materialsList: [ - { name: "户外木种", spec: "高油脂老料缅甸柚木,经过 180 天自然风干" }, - { name: "骨架型材", spec: "4mm 高强度航空铝镁合金,耐盐雾防腐" }, - { name: "智能五金", spec: "隐藏式地下闭门轴,支持业主手机远程授权开门" }, - ], - }, - }, - { - id: "interior_door", - category: "室内户内门", - name: "通顶极窄边框实木室内门", - series: "「空灵」2.8m-3.2m 满高通顶系统", - tag: "极简建筑平直感", - image: - "https://images.unsplash.com/photo-1505691938895-1758d7feb511?auto=format&fit=crop&w=900&q=80", - detailHero: - "https://images.unsplash.com/photo-1505691938895-1758d7feb511?auto=format&fit=crop&w=1000&q=85", - priceRange: "¥7,800 - ¥16,000 / 樘", - desc: "门与护墙板同色同构,通顶尺度让室内空间保持完整的建筑感。", - woodMaterial: "天然白栓木拉丝烟熏木饰面 + 磁吸阻尼降噪", - hardware: "意大利 AGB 磁吸静音门锁 + 隐藏式暗铰链", - spaceType: "别墅主卧套房 / 私人藏书阁 / 视听室", - keywords: ["满高通顶", "磁吸静音", "极窄边框", "与木作同色"], - area: "江苏 · 苏州金鸡湖独栋", - enabled: true, - details: { - background: - "室内多道门如果尺寸矮小杂乱,会彻底切割私宅的建筑开阔感。业主希望整个二层主卧区实现门与护墙板毫无色差、绝对平齐的极致纯粹度。", - designConcept: - "做到门扇高 3.1 米一通到顶,无传统上门套与压边。门扇内嵌双向碳纤维抗弯龙骨,保证高纬度温差下永不变形扭曲。", - crafts: [ - "门框与墙体批荡层彻底融为一体的无框反装工艺", - "关门瞬间磁力吸舌弹出,落锁轻无声息,静音等级达书店级", - "木皮精选同批原木切片,拼花纹理与旁边护墙板自然连贯", - ], - materialsList: [ - { name: "抗弯核心", spec: "双组份碳纤维预应力防变形拉力杆" }, - { name: "吸音内衬", spec: "德国原装绍尔兰特均质空心桥洞力学板" }, - { name: "隐形铰链", spec: "德国 KRONA 三维可调隐形铰链" }, - ], - }, - }, - { - id: "stealth_door", - category: "装饰隐形门", - name: "石材及皮质背景墙一体门", - series: "「无垠」密室及背景墙融合门", - tag: "精密收口工程", - image: - "https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?auto=format&fit=crop&w=900&q=80", - detailHero: - "https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?auto=format&fit=crop&w=1000&q=85", - priceRange: "¥18,000 - ¥36,000 / 樘", - desc: "以毫厘对缝将门融入背景墙,保留空间完整秩序与隐藏仪式感。", - woodMaterial: "3mm 超薄大理石复合蜂窝板 / 进口鞍革手工双缝线", - hardware: "感应式电动自开闭装置或碰珠反弹器", - spaceType: "雪茄室 / 私人金库 / 地下酒窖 / 视听隐藏储物区", - keywords: ["视线隐形", "超薄岩板", "毫厘对缝", "无门把设计"], - area: "广东 · 深圳香蜜湖一号", - enabled: true, - details: { - background: - "客厅背景墙长达 9 米,中间有一道通往主人密闭酒窖的通道,若突兀开门将完全破坏整面奢石的连贯韵律。", - designConcept: - "将奢石切割对纹直接复合于高刚性合金门扇表面,缝隙控制在严苛的 1.5mm 以内,未触发开关时完全是一整面天然水墨石壁。", - crafts: [ - "石材水刀无应力薄切与航空蜂窝背栓复合", - "脚踏地砖预埋重力复位转轴,避免墙面任何外露开孔", - "支持指纹电控联动隐藏灯带变色,开门仪式感强烈", - ], - materialsList: [ - { name: "表面饰材", spec: "意大利顶级雪山银狐超薄天然大理石" }, - { name: "驱动系统", spec: "低噪步进电机伺服闭门器,运行分贝低于 20dB" }, - ], - }, - }, -]; -offerings.forEach((item) => { - item.woodMaterial = item.woodMaterial || "天然厚板 / 手工锻铜 / 岩板饰面"; - item.hardware = item.hardware || "隐匿式重型天地轴五金系统"; - item.spaceType = item.spaceType || "私家别墅 / 高端私宅"; - item.details = item.details || { - background: item.desc + " 项目位于" + item.area + ",由主理人全程跟进。", - designConcept: "以建筑尺度为起点,让门成为空间秩序与生活气息之间的自然过渡。", - crafts: "毫米级门洞复核、结构深化与多次现场试装,确保开合、隔音与收口长期稳定。", - }; -}); -module.exports = { brand, trustContent, offerings }; diff --git a/apps/miniapp/utils/module-registry.js b/apps/miniapp/utils/module-registry.js index 084bf2b..b6cc0fd 100644 --- a/apps/miniapp/utils/module-registry.js +++ b/apps/miniapp/utils/module-registry.js @@ -58,11 +58,14 @@ function resolveManifest(workspace) { if (!manifest || !Array.isArray(manifest.pages)) return null; const pages = {}; for (const page of manifest.pages) { - pages[page.key] = (page.modules || []).map((module) => ({ - ...module, - type: MANIFEST_TYPE_ALIASES[module.type] || module.type, - variant: module.variant || "default", - })); + pages[page.key] = { + ...page, + modules: (page.modules || []).map((module) => ({ + ...module, + type: MANIFEST_TYPE_ALIASES[module.type] || module.type, + variant: module.variant || "default", + })), + }; } return { ...manifest, pages }; } @@ -70,7 +73,7 @@ function resolveManifest(workspace) { function resolveRuntime(workspace) { const modules = Array.isArray(workspace && workspace.modules) ? workspace.modules : []; const manifest = resolveManifest(workspace); - const manifestHome = manifest && manifest.pages.home; + const manifestHome = manifest && manifest.pages.home?.modules; const manifestModules = manifestHome || []; const resolved = modules.map(resolveModule); const resolvedTypes = new Set(resolved.map((item) => item.type)); @@ -87,11 +90,28 @@ function resolveRuntime(workspace) { : resolved.map((item) => item.type); const moduleVariants = {}; for (const item of manifestHome || []) moduleVariants[item.type] = item.variant; + const pageRenderers = {}; + for (const page of Object.values(manifest?.pages || {})) { + if (page.renderer) pageRenderers[page.key] = page.renderer; + } + const navigation = Array.isArray(manifest?.navigation) + ? manifest.navigation.map((item) => ({ + ...item, + page: + typeof item.page === "string" && manifest.entrypoints?.[item.page] + ? manifest.entrypoints[item.page] + : item.page, + })) + : Array.isArray(workspace?.navigation) + ? workspace.navigation + : []; return { theme: manifest?.tokens || (workspace && workspace.theme ? workspace.theme : FALLBACK_THEME), modules: resolved, layout: { home: home.filter((key) => resolved.some((item) => item.type === key)) }, moduleVariants, + pageRenderers, + navigation, visualManifest: manifest, capabilities: workspace && Array.isArray(workspace.capabilities) ? workspace.capabilities : [], }; diff --git a/apps/miniapp/utils/request.js b/apps/miniapp/utils/request.js index 36bc09f..fc4032d 100644 --- a/apps/miniapp/utils/request.js +++ b/apps/miniapp/utils/request.js @@ -1,11 +1,17 @@ const config = require("./config"); function withBrandContext(path, options) { - if (options.includeBrand === false || !path.startsWith("/public/")) return path; + const requiresBrandContext = + path.startsWith("/public/") || path.startsWith("/customer/session/wechat"); + if (options.includeBrand === false || !requiresBrandContext) return path; const separator = path.includes("?") ? "&" : "?"; return path + separator + "brandSlug=" + encodeURIComponent(config.brandSlug); } +function customerTokenKey() { + return "customerToken:" + config.brandSlug; +} + function request(path, options = {}) { return new Promise((resolve, reject) => { const requestPath = withBrandContext(path, options); @@ -25,11 +31,11 @@ function request(path, options = {}) { } function customerRequest(path, options = {}) { - const token = wx.getStorageSync("customerToken"); + const token = wx.getStorageSync(customerTokenKey()); return request(path, { ...options, header: { ...(options.header || {}), Authorization: "Bearer " + token }, }); } -module.exports = { request, customerRequest }; +module.exports = { request, customerRequest, customerTokenKey }; diff --git a/apps/miniapp/utils/runtime-workspace.js b/apps/miniapp/utils/runtime-workspace.js index 2f6d152..4831634 100644 --- a/apps/miniapp/utils/runtime-workspace.js +++ b/apps/miniapp/utils/runtime-workspace.js @@ -1,47 +1,59 @@ const { request } = require("./request"); -const { getFallbackWorkspace } = require("./fallback-workspaces"); const { resolveRuntime } = require("./module-registry"); function toOffering(item) { - const config = item && item.config && typeof item.config === "object" ? item.config : {}; + const presentation = + item && item.presentation && typeof item.presentation === "object" ? item.presentation : {}; + const details = + presentation.details && typeof presentation.details === "object" ? presentation.details : {}; return { ...item, id: item.id, - category: item.category || item.kind || "业务提供项", + category: presentation.categoryLabel || "业务提供项", name: item.name, - desc: item.summary || item.description || "", - image: item.coverUrl || item.image || "", + desc: item.summary || "", + image: presentation.heroImage || item.coverUrl || "", priceRange: item.priceText || "沟通报价", - keywords: Array.isArray(config.keywords) ? config.keywords : [], + keywords: Array.isArray(presentation.keywords) ? presentation.keywords : [], + details: { + background: typeof details.background === "string" ? details.background : "", + designConcept: typeof details.designConcept === "string" ? details.designConcept : "", + crafts: Array.isArray(details.crafts) ? details.crafts : [], + materialsList: Array.isArray(details.materialsList) ? details.materialsList : [], + }, + }; +} + +function normalizeWorkspace(workspace) { + const brand = workspace && workspace.brand ? workspace.brand : {}; + const offerings = Array.isArray(workspace && workspace.offerings) + ? workspace.offerings.map(toOffering) + : []; + const trustContent = + workspace && workspace.trustPresentation && typeof workspace.trustPresentation === "object" + ? workspace.trustPresentation + : {}; + return { + ...workspace, + ...resolveRuntime(workspace), + brand, + offerings, + trustContent, + plugins: Array.isArray(workspace.plugins) ? workspace.plugins : [], }; } function loadWorkspace() { return request("/public/workspace").then((workspace) => { - const fallback = getFallbackWorkspace( - workspace && workspace.template && workspace.template.key, - ); - const brand = workspace && workspace.brand ? workspace.brand : fallback.brand; - const offerings = Array.isArray(workspace && workspace.offerings) - ? workspace.offerings.map(toOffering) - : fallback.offerings; - const trustContent = - Array.isArray(workspace && workspace.trustContent) && workspace.trustContent.length - ? workspace.trustContent - : fallback.trustContent; - return { - ...workspace, - ...resolveRuntime(workspace), - brand, - offerings, - trustContent, - plugins: Array.isArray(workspace.plugins) ? workspace.plugins : [], - }; + if (workspace?.publication?.status !== "published") { + throw new Error("品牌尚未发布"); + } + return normalizeWorkspace(workspace); }); } function loadWorkspaceWithFallback() { - return loadWorkspace().catch(() => getFallbackWorkspace("personal")); + return loadWorkspace(); } module.exports = { loadWorkspaceWithFallback }; diff --git a/config/template-build.json b/config/template-build.json new file mode 100644 index 0000000..010cfe8 --- /dev/null +++ b/config/template-build.json @@ -0,0 +1,15 @@ +{ + "runtimeContract": "1.0", + "templates": [ + { + "packageKey": "acheng-campus-food", + "packageName": "@personal-brand/template-acheng-campus-food", + "version": "1.0.0" + }, + { + "packageKey": "linjing-editorial", + "packageName": "@personal-brand/template-linjing-editorial", + "version": "1.0.0" + } + ] +} diff --git a/docs/adr/0009-visual-template-compatibility.md b/docs/adr/0009-visual-template-compatibility.md new file mode 100644 index 0000000..0ea5c06 --- /dev/null +++ b/docs/adr/0009-visual-template-compatibility.md @@ -0,0 +1,26 @@ +# ADR 0009:视觉模板兼容性由 manifest 声明 + +## Context + +行业模板负责业务表达,视觉模板负责页面结构与视觉呈现。同一行业会拥有多套视觉模板,但并非每套模板都具备对应的页面变体、资源槽位和能力依赖。此前后台无条件展示全部视觉模板,API 也允许任意行业与视觉组合,无法渲染的组合只能依赖运行时兜底。 + +## Decision + +在视觉模板 definition 与 manifest 中增加 `supportedIndustryTemplates`。目录、组合预览和实际切换均通过共享 `isVisualTemplateCompatible` 校验。当前林境模板支持 `personal`、`doors`;极简模板支持 `personal`、`food`、`doors`。 + +## Alternatives + +- 在 Admin 前端写行业判断:拒绝,无法约束其他客户端和 API 调用。 +- 在 Controller 中写 `if (templateKey === ...)`:拒绝,新增模板仍需修改业务代码。 +- 所有组合都允许并在 Miniapp 运行时降级:拒绝,会把模板设计缺口推迟到用户验收阶段。 + +## Consequences + +- 新增视觉模板时必须声明支持的行业模板,后台会自动过滤,API 会自动校验。 +- 兼容关系是模板包元数据的一部分,可随版本快照记录。 +- 后续若出现更细粒度的能力差异,可在 manifest 增加槽位或 capability 约束,而无需回到行业分支。 + +## Migration + +- 现有两个视觉模板已补齐兼容声明。 +- 现有品牌配置无需迁移;当前不兼容配置会在下一次保存时被拒绝。 diff --git a/docs/adr/0010-template-sample-content-registry.md b/docs/adr/0010-template-sample-content-registry.md new file mode 100644 index 0000000..e692e5a --- /dev/null +++ b/docs/adr/0010-template-sample-content-registry.md @@ -0,0 +1,15 @@ +# ADR 0010:模板示例内容使用注册表 + +## Context + +示例内容导入接口曾直接在 Controller 中写入门窗名称、行业分类、信任内容和咨询字段。新增行业必须修改接口代码,模板声明驱动因此不完整。 + +## Decision + +将示例业务项、信任内容、字段和能力归属定义在 `@personal-brand/config` 的 `TemplateSampleContent` 注册表中。Controller 只执行权限、幂等检查、事务和审计。 + +## Consequences + +- 新行业只需注册模板示例内容,不需要修改 API Controller。 +- 示例内容类型在共享配置包中可被 API、后台预览和测试复用。 +- 当前样例导入接口仍固定迁移门窗示例;后续可将模板 key 纳入请求或从当前安装快照解析。 diff --git a/docs/adr/0011-template-sample-selection.md b/docs/adr/0011-template-sample-selection.md new file mode 100644 index 0000000..9f3af78 --- /dev/null +++ b/docs/adr/0011-template-sample-selection.md @@ -0,0 +1,15 @@ +# ADR 0011:示例内容按品牌行业模板选择 + +## Context + +示例内容注册表初版已移除 Controller 内的内容硬编码,但接口仍固定读取门窗示例包,个人品牌和餐饮品牌会得到错误的初始化内容。 + +## Decision + +示例预览和导入先读取当前品牌的 `templateKey`,再从 `getTemplateSampleContent` 选择对应注册表内容。个人品牌、餐饮、门窗均提供基础示例包。 + +## Consequences + +- 新建品牌导入示例时不会跨行业混入文案、字段或能力。 +- 示例包仍是开发期初始化内容,用户导入后可继续编辑。 +- 后续模板版本可在注册表中增加版本字段,不需要修改 Controller。 diff --git a/docs/adr/0012-brand-publication-lifecycle.md b/docs/adr/0012-brand-publication-lifecycle.md new file mode 100644 index 0000000..1bdde84 --- /dev/null +++ b/docs/adr/0012-brand-publication-lifecycle.md @@ -0,0 +1,37 @@ +# ADR 0012:品牌内容发布生命周期 + +## 背景 + +当前后台直接修改品牌、业务提供项、信任内容和咨询表单,公开接口会读取这些实时记录。这样无法区分“正在编辑的草稿”和“用户已经看到的版本”,也无法在模板导入、批量修改或误操作后安全预览、发布和撤回。多品牌场景下还必须保证发布版本按 `brandId` 隔离。 + +## 决策 + +引入品牌级发布版本(`BrandRelease`)作为公开内容的唯一读取边界: + +1. 后台编辑继续写入品牌工作区的草稿数据;草稿不直接影响公开接口。 +2. 发布时由服务端在事务中校验必填身份、视觉模板兼容性、已启用模块、公开业务项、表单字段和模板能力,然后生成不可变的运行时快照。 +3. `public/*` 和 `public/workspace` 只读取当前品牌的已发布快照;没有发布版本时返回明确的“尚未发布”状态,不回退到草稿或静态示例数据。 +4. 每个品牌最多一个当前发布版本,但保留历史版本用于审计和显式回滚。回滚是将历史快照重新发布为新版本,不直接修改草稿数据。 +5. 模板安装快照与发布快照分别负责不同职责:安装快照记录模板基线,发布快照记录用户可见的完整运行时投影;发布不能覆盖用户草稿。 +6. 发布、回滚和撤回都必须记录操作者、品牌、版本号、校验结果和时间;公开缓存按品牌发布版本失效。 +7. 发布前检查、快照读取和版本写入在同一个 Serializable 事务内完成;并发版本冲突有限重试。撤回单独记录 `revokedBy`,不覆盖原发布者。客户提交使用发布快照中的表单字段、业务项名称与报价,同时实时拦截已禁用业务。 + +## 不采用的方案 + +- 仅在现有表上增加 `published` 布尔字段:无法保证跨表一致性,也不能恢复一组完整内容。 +- 公开接口继续读取实时表,同时由前端自行判断:客户端无法提供可靠的发布边界,并会造成不同页面读到不同版本。 +- 复制整套业务表作为发布表:数据重复、迁移成本高,且难以支持模板扩展字段。 + +## 后果 + +- 需要新增发布版本表、生成快照的应用服务、发布/回滚 API 及集成测试。 +- 公开接口的响应需要增加 `publication` 元数据和未发布状态;小程序必须展示明确的空状态,而不是静默使用示例数据。 +- 后台首次配置流程可以围绕“选择模板 → 导入或空白 → 完善内容 → 预览 → 发布”组织,普通用户不需要理解模板内部结构。 +- 后台目前提供发布前的内容核对,不将其称作小程序视觉预览;最终视觉仍应通过小程序开发者工具验收。小程序不使用本地旧 workspace 兜底,以免撤回后离线缓存继续展示过期内容。 + +## 迁移计划 + +1. 新增 `BrandRelease` 数据模型和可逆 migration;为现有 demo 品牌生成一次基线发布版本。 +2. 抽取运行时投影生成器,保证发布快照与当前 `public/workspace` 契约一致。 +3. 增加发布、回滚、撤回和未发布状态的授权与集成测试,再切换公开接口读取发布快照。 +4. 后台增加首次配置引导和发布检查清单;通过后再移除公开接口对草稿表的直接读取。 diff --git a/docs/adr/0013-template-package-build-architecture.md b/docs/adr/0013-template-package-build-architecture.md new file mode 100644 index 0000000..211774d --- /dev/null +++ b/docs/adr/0013-template-package-build-architecture.md @@ -0,0 +1,20 @@ +# 0013 模板包与构建期生成 + +## Context + +视觉模板可能扩展到数百个。将每个模板直接写入 `apps/miniapp` 会造成主工程膨胀、依赖耦合和无法独立回归。 + +## Decision + +每个视觉模板是独立 pnpm workspace/npm package。模板包声明 runtime contract、页面入口、导航和能力依赖。构建期由 `template-compiler` 选择一个模板包,生成微信小程序目录;运行时不下载或执行模板代码。 + +## Consequences + +- 单次小程序构建只包含一个模板包,控制包体和维护范围。 +- 本地开发使用 pnpm workspace,不需要先发布私服。 +- CI/生产构建使用锁定的模板包版本。 +- Runtime Contract 必须版本化,破坏性变更进入新主版本。 + +## Migration plan + +先迁移林境和阿成,再删除 `apps/miniapp` 中模板专属 renderer;公共 runtime 保留在 shell 包中,模板包只消费 Runtime Workspace。 diff --git a/docs/engineering-delivery-checklist.md b/docs/engineering-delivery-checklist.md index 9362094..38fa191 100644 --- a/docs/engineering-delivery-checklist.md +++ b/docs/engineering-delivery-checklist.md @@ -7,6 +7,7 @@ - 明确接口的认证要求、角色、品牌隔离和状态转换; - 测试缺少凭证、凭证无效或角色错误,以及成功授权路径; - 测试成功响应、业务校验失败和资源不存在; +- 发布与撤回类端点还需覆盖并发版本分配、发布快照与客户提交的一致性; - API Client 方法、请求类型、响应类型和调用页面同步更新; - 状态码、错误 code、错误 message 和 `requestId` 符合统一响应约定。 @@ -37,6 +38,7 @@ ## 交付门槛 - 运行相关 API integration tests; +- 集成测试须使用独立 schema 或数据库;不得在默认测试命令中重建开发品牌数据; - 运行 API Client、API 和 Admin typecheck; - 运行 Admin production build; - 运行 `pnpm format:check` 和 `git diff --check`; diff --git a/docs/template-registry.md b/docs/template-registry.md index e7bbf2f..c9cceb1 100644 --- a/docs/template-registry.md +++ b/docs/template-registry.md @@ -12,7 +12,7 @@ ### 视觉模板 - `linjing-editorial@1.0.0`:林境建筑画册,适合高端定制和项目型业务。 -- `minimal-neutral@1.0.0`:极简留白,适合咨询、设计和专业服务。 +- 当前正式视觉模板包:`linjing-editorial@1.0.0`。个人、餐饮和门窗属于行业数据模板,不是独立视觉模板。 ## 组合规则 diff --git a/eslint.config.mjs b/eslint.config.mjs index b62a2f0..ca23680 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -10,6 +10,7 @@ export default tseslint.config( "prototype/**", "**/prisma/**", "apps/api/test/**/*.test.js", + "apps/api/test/**/*.cjs", "apps/miniapp/pages/**/*.js", "apps/miniapp/app.js", "apps/admin/vite.config.ts", diff --git a/package.json b/package.json index 9ad8411..5cb2e6e 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,10 @@ "db:migrate": "pnpm --filter @personal-brand/api db:migrate", "db:seed": "pnpm --filter @personal-brand/api db:seed", "test:api-client": "pnpm --filter @personal-brand/api exec tsx --test ../../packages/api-client/test/**/*.test.ts", + "validate:templates": "node scripts/validate-template-packages.cjs", + "template:dev": "node packages/template-compiler/src/cli.mjs --template", + "validate:template-release": "node scripts/validate-template-release.cjs", + "test:template-compiler": "pnpm --filter @personal-brand/template-compiler test", "clean": "turbo run clean && rimraf node_modules .turbo" }, "devDependencies": { diff --git a/packages/api-client/src/index.ts b/packages/api-client/src/index.ts index b155fc8..b06b3f7 100644 --- a/packages/api-client/src/index.ts +++ b/packages/api-client/src/index.ts @@ -8,6 +8,7 @@ import type { } from "@personal-brand/types"; export type { PublicOffering } from "@personal-brand/types"; export type { BookingStatus } from "@personal-brand/types"; +export type { BrandTemplateKey } from "@personal-brand/types"; export interface BrandProfile { id: string; @@ -30,7 +31,34 @@ export interface AdminBrandMembership { role: string; brand: Pick & { slug?: string }; } +export interface AdminBrandMember { + id: string; + role: string; + isEnabled: boolean; + adminUser: { + id: string; + username: string; + displayName: string; + isEnabled: boolean; + }; +} export type BrandUpdate = Partial>; +export interface BrandReleaseSummary { + id: string; + version: number; + status: string; + note: string | null; + actorId: string; + createdAt: string; + revokedAt: string | null; + revokedBy?: string | null; +} +export type BrandPresentationUpdate = Partial< + Record< + "identity" | "home" | "offerings" | "detail" | "profile" | "inquiry" | "success" | "records", + Record + > +>; export interface OfferingUpdate { name?: string; description?: string; @@ -227,6 +255,7 @@ export interface PublicWorkspace { key: string; version: string; name: string; + supportedIndustryTemplates: BrandTemplateKey[]; variants: Record; } | null; visualTemplateManifest?: { @@ -278,6 +307,7 @@ export interface PublicWorkspace { inquiryForm: InquiryForm | null; runtimeOfferings?: Array>; inquiryForms?: Array>; + trustPresentation?: Record; runtimeCapabilities?: Array<{ key: string; version: string; status?: string }>; plugins?: Array<{ key: string; @@ -392,9 +422,23 @@ export class ApiClient { cancelCustomerBooking(id: string): Promise { return this.request(`/customer/bookings/${encodeURIComponent(id)}/cancel`, { method: "POST" }); } - loginAdmin(username: string, password: string): Promise<{ token: string; displayName: string }> { + loginAdmin( + username: string, + password: string, + ): Promise<{ + token: string; + displayName: string; + mustChangePassword: boolean; + role: string; + }> { return this.request("/admin/session/login", { method: "POST", body: { username, password } }); } + changeAdminPassword(currentPassword: string, newPassword: string): Promise<{ changed: true }> { + return this.request("/admin/session/change-password", { + method: "POST", + body: { currentPassword, newPassword }, + }); + } listAdminBookings( filters: { status?: BookingStatus; unreadOnly?: boolean; tagId?: string } = {}, ): Promise { @@ -441,6 +485,26 @@ export class ApiClient { ): Promise<{ token: string; brand: AdminBrandMembership["brand"] }> { return this.request(`/admin/brands/${encodeURIComponent(brandId)}/switch`, { method: "POST" }); } + listAdminMembers(): Promise { + return this.request("/admin/brands/members"); + } + createAdminMember(body: { + username: string; + displayName: string; + password: string; + role: "owner" | "editor"; + }): Promise { + return this.request("/admin/brands/members", { method: "POST", body }); + } + updateAdminMember( + id: string, + body: Partial>, + ): Promise { + return this.request(`/admin/brands/members/${encodeURIComponent(id)}`, { + method: "PATCH", + body, + }); + } getAdminVisualTemplatePreview(): Promise<{ current: { key: string; @@ -464,6 +528,11 @@ export class ApiClient { updateAdminBrand(body: BrandUpdate): Promise { return this.request("/admin/config/brand", { method: "PATCH", body }); } + updateAdminBrandPresentation(body: BrandPresentationUpdate): Promise<{ + visualPresentation: Record>; + }> { + return this.request("/admin/config/presentation", { method: "PATCH", body }); + } getPublicTemplate(key: BrandTemplateKey): Promise { return this.request(`/public/templates/${key}`); } @@ -474,11 +543,47 @@ export class ApiClient { version: string; name: string; description: string; + supportedIndustryTemplates: BrandTemplateKey[]; variants: Record; theme: { colors: Record }; }>; }> { - return this.request("/public/templates"); + return this.request<{ + industries: BrandTemplateDefinition[]; + visuals: Array<{ + key: string; + version: string; + name: string; + description: string; + supportedIndustryTemplates?: unknown; + variants?: unknown; + theme?: unknown; + }>; + }>("/public/templates").then((catalog) => ({ + industries: Array.isArray(catalog.industries) ? catalog.industries : [], + visuals: Array.isArray(catalog.visuals) + ? catalog.visuals.map((visual) => ({ + key: String(visual.key ?? ""), + version: String(visual.version ?? ""), + name: String(visual.name ?? "未命名视觉模板"), + description: String(visual.description ?? ""), + supportedIndustryTemplates: Array.isArray(visual.supportedIndustryTemplates) + ? visual.supportedIndustryTemplates.filter( + (item): item is BrandTemplateKey => + item === "personal" || item === "food" || item === "doors", + ) + : [], + variants: + visual.variants && typeof visual.variants === "object" + ? (visual.variants as Record) + : {}, + theme: + visual.theme && typeof visual.theme === "object" + ? (visual.theme as { colors: Record }) + : { colors: {} }, + })) + : [], + })); } previewPublicTemplateCombination( industry: string, @@ -490,6 +595,7 @@ export class ApiClient { version: string; name: string; description: string; + supportedIndustryTemplates: BrandTemplateKey[]; variants: Record; theme: { colors: Record }; }; @@ -516,9 +622,10 @@ export class ApiClient { key: string; version: string; name: string; + supportedIndustryTemplates: BrandTemplateKey[]; variants: Record; } | null; - installations: unknown[]; + installations: Array<{ id: string; templateKey: BrandTemplateKey; templateVersion: string }>; modules: BrandModule[]; fields: BrandFieldDefinition[]; offerings: Offering[]; @@ -526,6 +633,32 @@ export class ApiClient { }> { return this.request("/admin/workspace"); } + listAdminReleases(): Promise { + return this.request("/admin/releases"); + } + getAdminReleaseReadiness(): Promise<{ + ready: boolean; + checks: Array<{ key: string; label: string; passed: boolean }>; + }> { + return this.request("/admin/releases/readiness"); + } + publishAdminRelease(note?: string): Promise { + return this.request("/admin/releases/publish", { + method: "POST", + body: note === undefined ? {} : { note }, + }); + } + rollbackAdminRelease(version: number, note?: string): Promise { + return this.request(`/admin/releases/${version}/rollback`, { + method: "POST", + body: note === undefined ? {} : { note }, + }); + } + revokeAdminRelease(): Promise< + Pick + > { + return this.request("/admin/releases/revoke", { method: "POST" }); + } installAdminTemplate(templateKey: "personal" | "food" | "doors"): Promise { return this.request("/admin/workspace/install", { method: "POST", body: { templateKey } }); } diff --git a/packages/api-client/test/client.test.ts b/packages/api-client/test/client.test.ts index 9c8b6d6..1f01915 100644 --- a/packages/api-client/test/client.test.ts +++ b/packages/api-client/test/client.test.ts @@ -47,3 +47,25 @@ test("客户端将统一错误响应转换为 ApiClientError", async () => { }, ); }); + +test("发布检查与发布操作使用当前品牌的管理接口", async () => { + const calls: Array<{ url: string; method?: string; body?: string }> = []; + const client = new ApiClient({ + baseUrl: "http://api.test", + token: "brand-token", + fetcher: async (url, init) => { + calls.push({ url, method: init?.method, body: init?.body }); + return response({ ready: true, checks: [] }); + }, + }); + await client.getAdminReleaseReadiness(); + await client.publishAdminRelease("首次发布"); + assert.deepEqual(calls, [ + { url: "http://api.test/admin/releases/readiness", method: "GET", body: undefined }, + { + url: "http://api.test/admin/releases/publish", + method: "POST", + body: JSON.stringify({ note: "首次发布" }), + }, + ]); +}); diff --git a/packages/config/src/index.ts b/packages/config/src/index.ts index 0551df8..3c2772f 100644 --- a/packages/config/src/index.ts +++ b/packages/config/src/index.ts @@ -1,7 +1,7 @@ export const configPackageName = "personal-brand-config"; export type BrandTemplateKey = "personal" | "food" | "doors"; -export type VisualTemplateKey = "linjing-editorial" | "minimal-neutral"; +export type VisualTemplateKey = "linjing-editorial" | "acheng-campus-food"; export type CapabilityKey = "offerings" | "inquiry" | "booking" | "quote-request"; export interface WorkflowDefinition { @@ -93,6 +93,7 @@ export interface VisualTemplateDefinition { version: string; name: string; description: string; + supportedIndustryTemplates: BrandTemplateKey[]; variants: Record; theme: { colors: Record; radius: Record }; layout?: { home: string[]; offerings: string[]; detail: string[]; profile: string[] }; @@ -149,6 +150,7 @@ export interface VisualModuleDefinition { export interface VisualPageDefinition { key: VisualPageKey; title: string; + renderer?: string; modules: VisualModuleDefinition[]; } @@ -158,6 +160,7 @@ export interface VisualTemplateManifest { version: string; name: string; description: string; + supportedIndustryTemplates: BrandTemplateKey[]; brandFirst: true; tokens: VisualTokenSet; pages: VisualPageDefinition[]; @@ -178,12 +181,210 @@ export interface TemplatePackage { }; } +export interface TemplatePackageManifest { + packageKey: string; + version: string; + displayName: string; + visualTemplateKey: VisualTemplateKey; + runtimeContract: "1.0"; + supportedIndustryTemplates: BrandTemplateKey[]; + entrypoints: Record; + requiredCapabilities: CapabilityKey[]; +} + +export const templatePackageRegistry: readonly TemplatePackageManifest[] = [ + { + packageKey: "linjing-editorial", + version: "1.0.0", + displayName: "林境建筑画册", + visualTemplateKey: "linjing-editorial", + runtimeContract: "1.0", + supportedIndustryTemplates: ["personal", "doors"], + entrypoints: { + home: "pages/index/index", + offerings: "pages/services/index", + detail: "pages/offering/detail", + inquiry: "pages/inquiry/index", + success: "pages/inquiry-success/index", + records: "pages/records/index", + profile: "pages/bookings/index", + }, + requiredCapabilities: ["offerings", "inquiry"], + }, + { + packageKey: "acheng-campus-food", + version: "1.0.0", + displayName: "阿成校园餐", + visualTemplateKey: "acheng-campus-food", + runtimeContract: "1.0", + supportedIndustryTemplates: ["food"], + entrypoints: { + home: "pages/index/index", + offerings: "pages/services/index", + detail: "pages/offering/detail", + inquiry: "pages/inquiry/index", + success: "pages/inquiry-success/index", + records: "pages/records/index", + profile: "pages/bookings/index", + }, + requiredCapabilities: ["offerings", "inquiry", "booking"], + }, +]; + +export function getTemplatePackageManifest(key: string): TemplatePackageManifest | undefined { + return templatePackageRegistry.find((item) => item.packageKey === key); +} + +export function validateTemplatePackageManifest(manifest: TemplatePackageManifest): string[] { + const errors: string[] = []; + if (!manifest.packageKey.trim()) errors.push("packageKey is required"); + if (!manifest.version.trim()) errors.push("version is required"); + if (manifest.runtimeContract !== "1.0") errors.push("unsupported runtimeContract"); + if (!manifest.supportedIndustryTemplates.length) + errors.push("supportedIndustryTemplates must not be empty"); + for (const page of [ + "home", + "offerings", + "detail", + "inquiry", + "success", + "records", + "profile", + ] as const) { + if (!manifest.entrypoints[page]?.trim()) errors.push(`entrypoints.${page} is required`); + } + return errors; +} + +export interface TemplateSampleContent { + templateKey: BrandTemplateKey; + offerings: Array<{ + kind: "service" | "product" | "package" | "subscription"; + name: string; + summary: string; + categoryKey: string; + }>; + trustContent: Array<{ type: string; title: string; content: string }>; + fields: Array<{ key: string; label: string; type: string; required: boolean }>; + capabilityKey: string; +} + +const doorsSampleContent: TemplateSampleContent = { + templateKey: "doors", + offerings: [ + { + kind: "product", + name: "序章·入户门", + summary: "为别墅入口定制的整樘门系统", + categoryKey: "entrance-door", + }, + { + kind: "product", + name: "庭院·边界门", + summary: "连接建筑与庭院的定制门", + categoryKey: "garden-door", + }, + { + kind: "product", + name: "室内·静谧门", + summary: "统一室内空间秩序的户内门", + categoryKey: "interior-door", + }, + { + kind: "service", + name: "一对一门系统设计咨询", + summary: "从现场到方案的完整设计沟通", + categoryKey: "custom", + }, + ], + trustContent: [ + { type: "profile", title: "主理人的门作观", content: "示例内容,待品牌主理人完善。" }, + { type: "portfolio", title: "别墅门系统案例", content: "示例内容,待品牌主理人完善。" }, + { type: "process", title: "从测量到交付", content: "示例内容,待品牌主理人完善。" }, + { type: "credential", title: "材料与工艺标准", content: "示例内容,待品牌主理人完善。" }, + ], + fields: [ + { key: "projectType", label: "项目类型", type: "select", required: false }, + { key: "projectStage", label: "项目阶段", type: "select", required: false }, + { key: "siteDescription", label: "项目概况", type: "textarea", required: false }, + { key: "phone", label: "联系方式", type: "phone", required: true }, + ], + capabilityKey: "doors", +}; + +const foodSampleContent: TemplateSampleContent = { + templateKey: "food", + offerings: [ + { + kind: "package", + name: "示例·今日套餐", + summary: "现做家常套餐示例内容。", + categoryKey: "set-meal", + }, + { + kind: "service", + name: "示例·聚餐定制", + summary: "按人数和口味沟通定制餐品。", + categoryKey: "private-chef", + }, + ], + trustContent: [ + { type: "profile", title: "关于主理人", content: "示例内容,待品牌主理人完善。" }, + { type: "process", title: "从预订到取餐", content: "示例内容,待品牌主理人完善。" }, + ], + fields: [ + { key: "date", label: "用餐日期", type: "date", required: true }, + { key: "number", label: "用餐人数", type: "number", required: true }, + { key: "phone", label: "联系方式", type: "phone", required: true }, + ], + capabilityKey: "booking", +}; + +const personalSampleContent: TemplateSampleContent = { + templateKey: "personal", + offerings: [ + { + kind: "service", + name: "示例·品牌定位咨询", + summary: "梳理品牌定位与下一步行动。", + categoryKey: "consulting", + }, + { + kind: "service", + name: "示例·长期顾问支持", + summary: "围绕表达和转化提供持续支持。", + categoryKey: "advisory", + }, + ], + trustContent: [ + { type: "profile", title: "关于主理人", content: "示例内容,待品牌主理人完善。" }, + { type: "process", title: "合作方法", content: "示例内容,待品牌主理人完善。" }, + ], + fields: [ + { key: "name", label: "您的称呼", type: "text", required: true }, + { key: "phone", label: "联系方式", type: "phone", required: true }, + { key: "remark", label: "合作需求", type: "textarea", required: true }, + ], + capabilityKey: "inquiry", +}; + +export const templateSampleContent: Record = { + personal: personalSampleContent, + food: foodSampleContent, + doors: doorsSampleContent, +}; + +export function getTemplateSampleContent(templateKey: string): TemplateSampleContent | undefined { + return templateSampleContent[templateKey as keyof typeof templateSampleContent]; +} + const linjingEditorialManifest: VisualTemplateManifest = { schemaVersion: "1.0", key: "linjing-editorial", version: "1.0.0", name: "林境建筑画册", description: "以个人品牌信任为主线、以高端项目作品为表达重点的编辑式视觉模板。", + supportedIndustryTemplates: ["personal", "doors"], brandFirst: true, tokens: { colors: { @@ -263,6 +464,7 @@ const linjingEditorialManifest: VisualTemplateManifest = { { key: "home", title: "首页", + renderer: "linjing-home", modules: [ { key: "identity", @@ -308,6 +510,7 @@ const linjingEditorialManifest: VisualTemplateManifest = { { key: "offerings", title: "业务提供项", + renderer: "linjing-offerings", modules: [ { key: "offerings", @@ -323,6 +526,7 @@ const linjingEditorialManifest: VisualTemplateManifest = { { key: "detail", title: "提供项详情", + renderer: "linjing-offering-detail", modules: [ { key: "detail", @@ -338,6 +542,7 @@ const linjingEditorialManifest: VisualTemplateManifest = { { key: "inquiry", title: "咨询与预约", + renderer: "linjing-inquiry", modules: [ { key: "inquiry", @@ -352,6 +557,7 @@ const linjingEditorialManifest: VisualTemplateManifest = { { key: "success", title: "提交成功", + renderer: "linjing-success", modules: [ { key: "success", @@ -365,6 +571,7 @@ const linjingEditorialManifest: VisualTemplateManifest = { { key: "records", title: "我的记录", + renderer: "linjing-records", modules: [ { key: "records", @@ -378,6 +585,7 @@ const linjingEditorialManifest: VisualTemplateManifest = { { key: "profile", title: "主理人与我", + renderer: "linjing-profile", modules: [ { key: "identity", @@ -402,24 +610,37 @@ const linjingEditorialManifest: VisualTemplateManifest = { export const visualTemplateManifests: Record = { "linjing-editorial": linjingEditorialManifest, - "minimal-neutral": { + "acheng-campus-food": { ...linjingEditorialManifest, - key: "minimal-neutral", + key: "acheng-campus-food", version: "1.0.0", - name: "极简留白", - description: "适合咨询、设计和专业服务型个人品牌的中性视觉模板。", + name: "阿成校园餐", + description: "面向校园餐饮摊贩的菜单、出摊动态和团体预订视觉模板。", + supportedIndustryTemplates: ["food"], tokens: { ...linjingEditorialManifest.tokens, colors: { - background: "#FAFAF8", + background: "#FFF8F0", surface: "#FFFFFF", - foreground: "#202221", - muted: "#6B7280", - accent: "#4B5563", - dark: "#202221", + foreground: "#29231F", + muted: "#7A6A60", + accent: "#E87532", + dark: "#3B2118", }, - radius: { card: "8rpx", button: "8rpx", media: "8rpx" }, + radius: { card: "24rpx", button: "999rpx", media: "20rpx" }, }, + pages: linjingEditorialManifest.pages.map((pageDefinition) => { + const renderer = + pageDefinition.key === "home" + ? "acheng-home" + : pageDefinition.key === "offerings" + ? "acheng-offerings" + : pageDefinition.key === "profile" + ? "acheng-profile" + : pageDefinition.renderer; + return renderer ? { ...pageDefinition, renderer } : pageDefinition; + }), + capabilities: ["offerings", "inquiry", "booking"], }, }; @@ -427,12 +648,22 @@ export function getVisualTemplateManifest(key: string): VisualTemplateManifest | return visualTemplateManifests[key as VisualTemplateKey]; } +export function isVisualTemplateCompatible( + visualTemplate: VisualTemplateDefinition | VisualTemplateManifest, + industryTemplateKey: string, +): boolean { + return visualTemplate.supportedIndustryTemplates.includes( + industryTemplateKey as BrandTemplateKey, + ); +} + export const visualTemplates: Record = { "linjing-editorial": { key: "linjing-editorial", version: "1.0.0", name: "林境建筑画册", description: "适合高端定制、建筑作品和项目型个人品牌。", + supportedIndustryTemplates: ["personal", "doors"], variants: { hero: "architectural", offeringList: "editorial", detail: "project-case" }, theme: { colors: { background: "#F7F5F1", foreground: "#252525", accent: "#8A6846", dark: "#202221" }, @@ -445,18 +676,19 @@ export const visualTemplates: Record + visualTemplates[key].supportedIndustryTemplates.includes( + industryTemplateKey as BrandTemplateKey, + ), + ) ?? "linjing-editorial" + ); +} + export function canTransitionWorkflow(workflowKey: string, from: string, to: string): boolean { const workflow = workflowRegistry[workflowKey as keyof typeof workflowRegistry] as WorkflowDefinition | undefined; diff --git a/packages/template-acheng-campus-food/README.md b/packages/template-acheng-campus-food/README.md new file mode 100644 index 0000000..81be1b5 --- /dev/null +++ b/packages/template-acheng-campus-food/README.md @@ -0,0 +1,3 @@ +# 阿成校园餐模板包 + +此目录是模板包迁移阶段的构建输入。正式迁移后,所有阿成专属页面、组件和资源只允许存在于 `miniapp/`,公共 API 和 Runtime Contract 由 shell 提供。 diff --git a/packages/template-acheng-campus-food/miniapp/.gitkeep b/packages/template-acheng-campus-food/miniapp/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/packages/template-acheng-campus-food/miniapp/app.json b/packages/template-acheng-campus-food/miniapp/app.json new file mode 100644 index 0000000..9f44320 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/app.json @@ -0,0 +1,8 @@ +{ + "pages": ["pages/index/index"], + "window": { + "navigationBarTitleText": "阿成校园餐", + "navigationBarBackgroundColor": "#FFF8F0", + "navigationBarTextStyle": "black" + } +} diff --git a/packages/template-acheng-campus-food/miniapp/assets/tab/booking-selected.png b/packages/template-acheng-campus-food/miniapp/assets/tab/booking-selected.png new file mode 100644 index 0000000..e465c2d Binary files /dev/null and b/packages/template-acheng-campus-food/miniapp/assets/tab/booking-selected.png differ diff --git a/packages/template-acheng-campus-food/miniapp/assets/tab/booking.png b/packages/template-acheng-campus-food/miniapp/assets/tab/booking.png new file mode 100644 index 0000000..5001009 Binary files /dev/null and b/packages/template-acheng-campus-food/miniapp/assets/tab/booking.png differ diff --git a/packages/template-acheng-campus-food/miniapp/assets/tab/dishes-selected.png b/packages/template-acheng-campus-food/miniapp/assets/tab/dishes-selected.png new file mode 100644 index 0000000..0d23f4e Binary files /dev/null and b/packages/template-acheng-campus-food/miniapp/assets/tab/dishes-selected.png differ diff --git a/packages/template-acheng-campus-food/miniapp/assets/tab/dishes.png b/packages/template-acheng-campus-food/miniapp/assets/tab/dishes.png new file mode 100644 index 0000000..2f55340 Binary files /dev/null and b/packages/template-acheng-campus-food/miniapp/assets/tab/dishes.png differ diff --git a/packages/template-acheng-campus-food/miniapp/assets/tab/home-selected.png b/packages/template-acheng-campus-food/miniapp/assets/tab/home-selected.png new file mode 100644 index 0000000..e465c2d Binary files /dev/null and b/packages/template-acheng-campus-food/miniapp/assets/tab/home-selected.png differ diff --git a/packages/template-acheng-campus-food/miniapp/assets/tab/home.png b/packages/template-acheng-campus-food/miniapp/assets/tab/home.png new file mode 100644 index 0000000..5001009 Binary files /dev/null and b/packages/template-acheng-campus-food/miniapp/assets/tab/home.png differ diff --git a/packages/template-acheng-campus-food/miniapp/assets/tab/owner-selected.png b/packages/template-acheng-campus-food/miniapp/assets/tab/owner-selected.png new file mode 100644 index 0000000..a862cdc Binary files /dev/null and b/packages/template-acheng-campus-food/miniapp/assets/tab/owner-selected.png differ diff --git a/packages/template-acheng-campus-food/miniapp/assets/tab/owner.png b/packages/template-acheng-campus-food/miniapp/assets/tab/owner.png new file mode 100644 index 0000000..cd7368c Binary files /dev/null and b/packages/template-acheng-campus-food/miniapp/assets/tab/owner.png differ diff --git a/packages/template-acheng-campus-food/miniapp/assets/tab/service-selected.png b/packages/template-acheng-campus-food/miniapp/assets/tab/service-selected.png new file mode 100644 index 0000000..0d23f4e Binary files /dev/null and b/packages/template-acheng-campus-food/miniapp/assets/tab/service-selected.png differ diff --git a/packages/template-acheng-campus-food/miniapp/assets/tab/service.png b/packages/template-acheng-campus-food/miniapp/assets/tab/service.png new file mode 100644 index 0000000..2f55340 Binary files /dev/null and b/packages/template-acheng-campus-food/miniapp/assets/tab/service.png differ diff --git a/packages/template-acheng-campus-food/miniapp/components/templates/acheng-home/acheng-home.js b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-home/acheng-home.js new file mode 100644 index 0000000..41ce8e5 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-home/acheng-home.js @@ -0,0 +1,22 @@ +Component({ + properties: { + brand: { type: Object, value: {} }, + presentation: { type: Object, value: {} }, + trustContent: { type: Object, value: {} }, + offerings: { type: Array, value: [] }, + }, + methods: { + openOffering(e) { + this.triggerEvent("select", { id: e.currentTarget.dataset.id }); + }, + openInquiry() { + this.triggerEvent("inquiry"); + }, + openOfferings() { + this.triggerEvent("offerings"); + }, + openService() { + wx.navigateTo({ url: "/pages/stall-service/index" }); + }, + }, +}); diff --git a/packages/template-acheng-campus-food/miniapp/components/templates/acheng-home/acheng-home.json b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-home/acheng-home.json new file mode 100644 index 0000000..67f8e03 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-home/acheng-home.json @@ -0,0 +1 @@ +{ "component": true } diff --git a/packages/template-acheng-campus-food/miniapp/components/templates/acheng-home/acheng-home.wxml b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-home/acheng-home.wxml new file mode 100644 index 0000000..3cc621a --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-home/acheng-home.wxml @@ -0,0 +1 @@ +{{brand.founder}}{{brand.title}}“{{brand.slogan}}”{{presentation.stallTitle || '今日出摊点'}}{{brand.studioAddress || brand.address}}{{presentation.stallTime || '17:00 - 22:30 · 今日营业中'}}晚高峰人多,可提前预约,下课直取不排队。真实出摊现场大学城老校门夜市实拍{{presentation.worksEyebrow || '本周学生票选招牌'}}{{presentation.worksTitle || '现做现吃,认真管饱'}}米饭免费续,附赠当日老汤或绿豆沙全部餐品 ›{{item.name}}{{item.desc}}{{item.priceRange}}{{presentation.manifestoEyebrow || '阿成的四大开档底线'}}{{presentation.manifestoTitle || '真材实料,当天现做'}}✓ 当天采购✓ 现炒锅气✓ 免费续饭✓ 不用料理包“上周街舞社订了 35 份,按寝室分组打包,送来还烫嘴!”—— 街舞社负责人 diff --git a/packages/template-acheng-campus-food/miniapp/components/templates/acheng-home/acheng-home.wxss b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-home/acheng-home.wxss new file mode 100644 index 0000000..666a969 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-home/acheng-home.wxss @@ -0,0 +1,225 @@ +.page { + min-height: 100vh; + padding: 20rpx 28rpx 48rpx; + background: #fff8f0; + color: #29231f; +} +.brand-card { + padding: 28rpx; + border: 1rpx solid #f2d9c6; + border-radius: 28rpx; + background: #fff; + box-shadow: 0 12rpx 30rpx rgba(145, 75, 33, 0.08); +} +.identity { + display: flex; + gap: 20rpx; + align-items: center; +} +.identity image { + width: 96rpx; + height: 96rpx; + border: 4rpx solid #ffd9bb; + border-radius: 50%; + background: #fff1e5; +} +.name, +.title, +.slogan, +.notice-title, +.notice text, +.eyebrow, +.heading, +.more, +.dish-name, +.dish-sub, +.price, +.promise-title, +.promise-item text { + display: block; +} +.name { + font-size: 32rpx; + font-weight: 700; +} +.title { + margin-top: 6rpx; + color: #a2613b; + font-size: 21rpx; +} +.slogan { + margin-top: 10rpx; + color: #7a6a60; + font-size: 21rpx; +} +.notice { + position: relative; + margin-top: 24rpx; + padding: 20rpx; + border: 1rpx solid #f8d7b4; + border-radius: 20rpx; + background: #fff7df; + color: #6b4a35; + font-size: 22rpx; + line-height: 1.6; +} +.notice-title { + font-weight: 700; + color: #4f3020; +} +.notice-time { + position: absolute; + right: 18rpx; + top: 18rpx; + color: #c65c28; + font-size: 19rpx; +} +.notice-desc { + display: block; + margin-top: 8rpx; + color: #8c7b70; + font-size: 19rpx; +} +.scene-wrap { + margin-top: 24rpx; +} +.scene { + display: block; + width: 100%; + height: 270rpx; + border-radius: 22rpx; +} +.subline { + display: block; + margin-top: 6rpx; + color: #8c7b70; + font-size: 19rpx; +} +.promise-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 10rpx; + margin-top: 16rpx; +} +.promise-grid text { + padding: 12rpx; + border-radius: 12rpx; + background: rgba(255, 255, 255, 0.1); + color: #ffe5d2; + font-size: 19rpx; +} +.quote { + margin-top: 18rpx; + padding-top: 16rpx; + border-top: 1rpx solid rgba(255, 255, 255, 0.15); + color: #ffe5d2; + font-size: 20rpx; + line-height: 1.6; +} +.quote text { + display: block; + margin-top: 8rpx; + color: #ffc79f; + font-size: 18rpx; +} +.actions { + display: flex; + gap: 14rpx; + margin-top: 20rpx; +} +.actions button { + flex: 1; + height: 76rpx; + border-radius: 20rpx; + background: #e87532; + color: #fff; + font-size: 24rpx; + line-height: 76rpx; +} +.actions .muted { + background: #fff0e5; + color: #b85e2c; +} +.section-head { + display: flex; + justify-content: space-between; + align-items: end; + margin: 34rpx 4rpx 18rpx; +} +.eyebrow { + color: #d2652b; + font-size: 19rpx; + letter-spacing: 2rpx; +} +.heading { + margin-top: 8rpx; + font-size: 34rpx; + font-weight: 700; +} +.more { + color: #d2652b; + font-size: 21rpx; +} +.dish-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16rpx; +} +.dish { + overflow: hidden; + border: 1rpx solid #f2e2d6; + border-radius: 22rpx; + background: #fff; +} +.dish image { + display: block; + width: 100%; + height: 220rpx; + background: #f3e7de; +} +.dish-copy { + padding: 18rpx; +} +.dish-name { + font-size: 24rpx; + font-weight: 700; + line-height: 1.4; +} +.dish-sub { + margin-top: 6rpx; + color: #8c7b70; + font-size: 19rpx; + line-height: 1.4; +} +.price { + margin-top: 14rpx; + color: #dc6429; + font-size: 24rpx; + font-weight: 700; +} +.promise { + margin-top: 28rpx; + padding: 28rpx; + border-radius: 24rpx; + background: #3b2118; + color: #fff; +} +.light { + color: #ffc79f; +} +.promise-title { + margin-top: 8rpx; + font-size: 30rpx; + font-weight: 700; +} +.promise-item { + display: flex; + gap: 12rpx; + margin-top: 18rpx; + color: #ffe5d2; + font-size: 21rpx; +} +.promise-item text:first-child { + color: #ff9a5a; + font-weight: 700; +} diff --git a/packages/template-acheng-campus-food/miniapp/components/templates/acheng-offerings/acheng-offerings.js b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-offerings/acheng-offerings.js new file mode 100644 index 0000000..32e9f64 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-offerings/acheng-offerings.js @@ -0,0 +1,36 @@ +Component({ + properties: { + brand: { type: Object, value: {} }, + presentation: { type: Object, value: {} }, + offerings: { type: Array, value: [] }, + }, + data: { query: "", visibleOfferings: [] }, + observers: { + "offerings, query"(offerings, query) { + const keyword = String(query || "") + .trim() + .toLowerCase(); + this.setData({ + visibleOfferings: (offerings || []).filter((item) => { + if (!keyword) return true; + return [item.name, item.desc, ...(item.keywords || [])].some((value) => + String(value || "") + .toLowerCase() + .includes(keyword), + ); + }), + }); + }, + }, + methods: { + search(e) { + this.setData({ query: e.detail.value }); + }, + open(e) { + this.triggerEvent("open", { id: e.currentTarget.dataset.id }); + }, + inquire() { + this.triggerEvent("inquire"); + }, + }, +}); diff --git a/packages/template-acheng-campus-food/miniapp/components/templates/acheng-offerings/acheng-offerings.json b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-offerings/acheng-offerings.json new file mode 100644 index 0000000..67f8e03 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-offerings/acheng-offerings.json @@ -0,0 +1 @@ +{ "component": true } diff --git a/packages/template-acheng-campus-food/miniapp/components/templates/acheng-offerings/acheng-offerings.wxml b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-offerings/acheng-offerings.wxml new file mode 100644 index 0000000..24af042 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-offerings/acheng-offerings.wxml @@ -0,0 +1 @@ +{{brand.name}}{{presentation.title || '今日菜单'}}{{presentation.subtitle || '现做现吃,支持提前预留和团体定制'}}全部餐品日常学生餐寝室 / 团体聚会定制⌕米饭免费续,支持微辣、免葱姜蒜,团体餐可提前预留。{{item.category || '现做餐品'}}{{item.name}}{{item.desc}}现做今日有售{{item.priceRange}}详情 / 预留 › diff --git a/packages/template-acheng-campus-food/miniapp/components/templates/acheng-offerings/acheng-offerings.wxss b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-offerings/acheng-offerings.wxss new file mode 100644 index 0000000..254fdc9 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-offerings/acheng-offerings.wxss @@ -0,0 +1,157 @@ +.page { + min-height: 100vh; + padding: 28rpx; + background: #fff8f0; + color: #29231f; +} +.eyebrow { + display: block; + color: #d2652b; + font-size: 19rpx; + letter-spacing: 2rpx; +} +.title { + display: block; + margin-top: 8rpx; + font-size: 42rpx; + font-weight: 700; +} +.subtitle { + display: block; + margin-top: 8rpx; + color: #8c7b70; + font-size: 22rpx; +} +.tip { + margin-top: 22rpx; + padding: 18rpx 20rpx; + border: 1rpx solid #f8d7b4; + border-radius: 18rpx; + background: #fff7df; + color: #8c5c39; + font-size: 21rpx; +} +.filters { + display: flex; + gap: 10rpx; + overflow: hidden; + margin-top: 20rpx; + white-space: nowrap; +} +.filter { + padding: 10rpx 18rpx; + border-radius: 999rpx; + background: #f2eee9; + color: #7a6a60; + font-size: 21rpx; +} +.filter.active { + background: #e87532; + color: #fff; +} +.search { + display: flex; + align-items: center; + gap: 8rpx; + margin-top: 16rpx; + padding: 0 20rpx; + height: 72rpx; + border: 1rpx solid #eee1d6; + border-radius: 20rpx; + background: #fff; +} +.search-icon { + color: #d2652b; + font-size: 34rpx; +} +.search input { + flex: 1; + font-size: 23rpx; +} +.dish-media { + position: relative; + flex: none; +} +.dish-media .tag { + position: absolute; + top: 10rpx; + left: 10rpx; + padding: 6rpx 10rpx; + border-radius: 10rpx; + background: rgba(59, 33, 24, 0.78); + color: #fff; + font-size: 18rpx; +} +.chips { + display: flex; + gap: 8rpx; + margin-top: 10rpx; +} +.chips text { + padding: 4rpx 8rpx; + border-radius: 8rpx; + background: #fff1e6; + color: #c65c28; + font-size: 17rpx; +} +.list { + margin-top: 18rpx; +} +.dish { + display: flex; + gap: 18rpx; + margin-bottom: 16rpx; + padding: 14rpx; + border: 1rpx solid #f2e2d6; + border-radius: 22rpx; + background: #fff; +} +.dish image, +.dish-media image { + width: 196rpx; + height: 196rpx; + flex: none; + border-radius: 16rpx; + background: #f3e7de; +} +.copy { + display: flex; + min-width: 0; + flex: 1; + flex-direction: column; +} +.name { + font-size: 26rpx; + font-weight: 700; + line-height: 1.45; +} +.desc { + margin-top: 10rpx; + color: #8c7b70; + font-size: 20rpx; + line-height: 1.5; +} +.bottom { + display: flex; + align-items: end; + justify-content: space-between; + margin-top: auto; +} +.price { + color: #dc6429; + font-size: 25rpx; + font-weight: 700; +} +.action { + color: #d2652b; + font-size: 20rpx; +} +.cta { + margin: 22rpx 0 0; + height: 76rpx; + border-radius: 20rpx; + background: #e87532; + color: #fff; + font-size: 24rpx; + line-height: 76rpx; +} diff --git a/packages/template-acheng-campus-food/miniapp/components/templates/acheng-profile/acheng-profile.js b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-profile/acheng-profile.js new file mode 100644 index 0000000..0baa99a --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-profile/acheng-profile.js @@ -0,0 +1,18 @@ +Component({ + properties: { + brand: { type: Object, value: {} }, + presentation: { type: Object, value: {} }, + recordsCount: { type: Number, value: 0 }, + }, + methods: { + call() { + this.triggerEvent("call"); + }, + copy() { + this.triggerEvent("copy"); + }, + records() { + this.triggerEvent("records"); + }, + }, +}); diff --git a/packages/template-acheng-campus-food/miniapp/components/templates/acheng-profile/acheng-profile.json b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-profile/acheng-profile.json new file mode 100644 index 0000000..67f8e03 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-profile/acheng-profile.json @@ -0,0 +1 @@ +{ "component": true } diff --git a/packages/template-acheng-campus-food/miniapp/components/templates/acheng-profile/acheng-profile.wxml b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-profile/acheng-profile.wxml new file mode 100644 index 0000000..15ba552 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-profile/acheng-profile.wxml @@ -0,0 +1 @@ +{{brand.founder}}{{brand.title}}{{brand.slogan}}{{presentation.coverageTitle || '出摊与配送'}}{{brand.studioAddress || brand.address}}{{presentation.coverageContent || '支持校园摊位自取、宿舍配送和班级活动定制。'}}我的预约记录{{recordsCount}} 条记录 › diff --git a/packages/template-acheng-campus-food/miniapp/components/templates/acheng-profile/acheng-profile.wxss b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-profile/acheng-profile.wxss new file mode 100644 index 0000000..b879aea --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/components/templates/acheng-profile/acheng-profile.wxss @@ -0,0 +1,72 @@ +.page { + min-height: 100vh; + padding: 28rpx; + background: #fff8f0; + color: #29231f; +} +.profile-card { + padding: 36rpx 28rpx; + text-align: center; + border-radius: 28rpx; + background: #3b2118; + color: #fff; +} +.profile-card image { + width: 132rpx; + height: 132rpx; + border: 5rpx solid #ffbd8e; + border-radius: 50%; +} +.name, +.title, +.bio, +.card-title, +.card text { + display: block; +} +.name { + margin-top: 18rpx; + font-size: 36rpx; + font-weight: 700; +} +.title { + margin-top: 6rpx; + color: #ffc79f; + font-size: 22rpx; +} +.bio { + margin-top: 16rpx; + color: #ffe5d2; + font-size: 23rpx; + line-height: 1.6; +} +.contact { + display: flex; + gap: 14rpx; + margin-top: 24rpx; +} +.contact button { + flex: 1; + height: 70rpx; + border-radius: 18rpx; + background: #e87532; + color: #fff; + font-size: 22rpx; + line-height: 70rpx; +} +.card { + margin-top: 18rpx; + padding: 26rpx; + border: 1rpx solid #f2d9c6; + border-radius: 22rpx; + background: #fff; + color: #7a6a60; + font-size: 22rpx; + line-height: 1.7; +} +.card-title { + margin-bottom: 10rpx; + color: #4b2b1d; + font-size: 27rpx; + font-weight: 700; +} diff --git a/packages/template-acheng-campus-food/miniapp/pages/bookings/index.js b/packages/template-acheng-campus-food/miniapp/pages/bookings/index.js new file mode 100644 index 0000000..c454ab5 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/pages/bookings/index.js @@ -0,0 +1,52 @@ +const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace"); +const { customerRequest, customerTokenKey } = require("../../utils/request"); +Page({ + data: { + brand: {}, + trustContent: [], + records: [], + error: "", + navigation: [], + }, + onLoad() { + loadWorkspaceWithFallback() + .then((workspace) => + this.setData({ + brand: workspace.brand || {}, + trustContent: workspace.trustContent || [], + records: [], + navigation: workspace.navigation || [], + }), + ) + .catch((error) => this.setData({ error: error.message })); + }, + onShow() { + this.loadRecords(); + }, + loadRecords() { + if (!wx.getStorageSync(customerTokenKey())) return this.setData({ records: [] }); + customerRequest("/customer/inquiry-submissions") + .then((records) => this.setData({ records: Array.isArray(records) ? records : [] })) + .catch(() => this.setData({ records: [] })); + }, + call() { + wx.makePhoneCall({ + phoneNumber: (this.data.brand.phone || this.data.brand.contactPhone || "").replace( + /[^0-9-]/g, + "", + ), + }); + }, + copyWechat() { + wx.setClipboardData({ + data: this.data.brand.wechat || this.data.brand.contactWechat || "", + success: () => wx.showToast({ title: "微信号已复制", icon: "none" }), + }); + }, + recordsPage() { + wx.navigateTo({ url: "/pages/records/index" }); + }, + inquire() { + wx.navigateTo({ url: "/pages/inquiry/index" }); + }, +}); diff --git a/packages/template-acheng-campus-food/miniapp/pages/bookings/index.json b/packages/template-acheng-campus-food/miniapp/pages/bookings/index.json new file mode 100644 index 0000000..3a6e758 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/pages/bookings/index.json @@ -0,0 +1,10 @@ +{ + "navigationBarTitleText": "我的订单", + "navigationBarBackgroundColor": "#FBF7F1", + "navigationBarTextStyle": "black", + "usingComponents": { + "t-icon": "/miniprogram_npm/tdesign-miniprogram/icon/icon", + "profile-module": "/components/modules/profile/profile", + "acheng-profile": "/components/templates/acheng-profile/acheng-profile" + } +} diff --git a/packages/template-acheng-campus-food/miniapp/pages/bookings/index.wxml b/packages/template-acheng-campus-food/miniapp/pages/bookings/index.wxml new file mode 100644 index 0000000..aa26ca6 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/pages/bookings/index.wxml @@ -0,0 +1 @@ +{{error}}✓健康证公示每年体检合格◆摊贩登记卡正规合规备案✦每日消杀食具恒温消毒他们都在阿成这订过餐校街舞社年度专场 · 52 人份信息学院科创竞赛 · 连签 5 天7 号楼庆功宴 · 8 人定制回复承诺:备料期 15 分钟内联系,出摊高峰 1 小时内回复。 diff --git a/packages/template-acheng-campus-food/miniapp/pages/bookings/index.wxss b/packages/template-acheng-campus-food/miniapp/pages/bookings/index.wxss new file mode 100644 index 0000000..90734d7 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/pages/bookings/index.wxss @@ -0,0 +1,197 @@ +.page { + min-height: 100vh; + padding: 28rpx 32rpx 56rpx; + background: #f7f5f1; + color: #252525; +} +.runtime-error { + margin: 48rpx 0; + padding: 28rpx; + border: 1rpx solid #e6ded5; + border-radius: 14rpx; + background: #fff; + color: #8a6846; + font-size: 25rpx; + line-height: 1.6; +} +.contact-card { + padding: 34rpx 30rpx; + background: #202221; + color: #fff; + border-radius: 18rpx; +} +.identity { + display: flex; + align-items: center; + gap: 20rpx; +} +.avatar { + width: 88rpx; + height: 88rpx; + border: 2rpx solid #8a6846; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + color: #d9c8b2; + font: 42rpx serif; +} +.founder { + display: block; + font: 34rpx serif; +} +.role { + display: block; + margin-top: 8rpx; + color: #d9c8b2; + font-size: 22rpx; +} +.contact-line { + display: flex; + justify-content: space-between; + align-items: center; + margin-top: 22rpx; + padding-top: 18rpx; + border-top: 1rpx solid rgba(255, 255, 255, 0.12); + color: #aaa; + font-size: 23rpx; +} +.contact-line > view { + display: flex; + align-items: center; + gap: 10rpx; + color: #fff; +} +.contact-line button { + margin: 0; + padding: 0 14rpx; + background: rgba(255, 255, 255, 0.1); + color: #d9c8b2; + font-size: 21rpx; +} +.records-entry, +.info-card { + margin-top: 20rpx; + padding: 28rpx; + background: #fff; + border: 1rpx solid #e6ded5; + border-radius: 16rpx; +} +.records-entry { + display: flex; + justify-content: space-between; + font-size: 26rpx; +} +.records-entry text:last-child { + color: #8a6846; +} +.card-title { + display: block; + font-weight: 700; + font-size: 27rpx; +} +.proof-grid { + display: flex; + gap: 12rpx; + margin-top: 20rpx; +} +.proof-grid view { + flex: 1; + padding: 18rpx 8rpx; + text-align: center; + border-radius: 18rpx; + background: #fff; + border: 1rpx solid #f2d9c6; +} +.proof-grid text { + display: block; + color: #7a6a60; + font-size: 18rpx; +} +.proof-grid .proof-icon { + color: #e87532; + font-size: 30rpx; +} +.promise { + margin-top: 18rpx; + padding: 22rpx; + border-radius: 20rpx; + background: #fff3d8; + color: #8c5c39; + font-size: 21rpx; + line-height: 1.6; +} +.note, +.bullet { + display: block; + margin-top: 16rpx; + color: #77736b; + font-size: 24rpx; + line-height: 1.75; +} +.entry-icon { + width: 64rpx; + height: 64rpx; + border-radius: 12rpx; + background: rgba(138, 104, 70, 0.1); + color: #8a6846; + display: flex; + align-items: center; + justify-content: center; +} +.records-entry { + align-items: center; + gap: 18rpx; +} +.entry-copy { + flex: 1; +} +.entry-copy text { + display: block; +} +.entry-copy text:last-child { + margin-top: 8rpx; + color: #77736b; + font-size: 21rpx; +} +.count { + color: #8a6846; + font-size: 22rpx; +} +.card-title { + display: flex; + align-items: center; + gap: 12rpx; + color: #202221; +} +.note { + padding: 20rpx; + background: #f7f5f1; + border: 1rpx solid #e6ded5; + border-radius: 12rpx; +} +.note-title { + display: block; + margin-bottom: 6rpx; + color: #202221; + font-weight: 700; +} +.bullet { + padding-left: 8rpx; +} +.contact-line button { + display: flex; + align-items: center; + justify-content: center; + gap: 6rpx; + height: 44rpx; + line-height: 44rpx; + white-space: nowrap; +} +.contact-line button t-icon { + display: inline-flex; + vertical-align: middle; +} +.page { + padding-bottom: 150rpx; +} diff --git a/packages/template-acheng-campus-food/miniapp/pages/index/index.js b/packages/template-acheng-campus-food/miniapp/pages/index/index.js new file mode 100644 index 0000000..c66a3a8 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/pages/index/index.js @@ -0,0 +1,26 @@ +const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace"); + +Page({ + data: { brand: {}, presentation: {}, trustContent: [], offerings: [], error: "" }, + onLoad() { + loadWorkspaceWithFallback() + .then((workspace) => + this.setData({ + brand: workspace.brand || {}, + presentation: workspace.brand?.visualPresentation?.home || {}, + trustContent: workspace.trustContent || [], + offerings: workspace.offerings || [], + }), + ) + .catch((error) => this.setData({ error: error.message })); + }, + selectOffering(event) { + wx.navigateTo({ url: "/pages/offering/detail?id=" + event.detail.id }); + }, + goWorks() { + wx.navigateTo({ url: "/pages/services/index" }); + }, + goInquiry() { + wx.navigateTo({ url: "/pages/inquiry/index" }); + }, +}); diff --git a/packages/template-acheng-campus-food/miniapp/pages/index/index.json b/packages/template-acheng-campus-food/miniapp/pages/index/index.json new file mode 100644 index 0000000..23a505f --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/pages/index/index.json @@ -0,0 +1,6 @@ +{ + "navigationBarTitleText": "阿成校园餐", + "usingComponents": { + "acheng-home": "/components/templates/acheng-home/acheng-home" + } +} diff --git a/packages/template-acheng-campus-food/miniapp/pages/index/index.wxml b/packages/template-acheng-campus-food/miniapp/pages/index/index.wxml new file mode 100644 index 0000000..759f3fc --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/pages/index/index.wxml @@ -0,0 +1,4 @@ + + {{error}} + + diff --git a/packages/template-acheng-campus-food/miniapp/pages/index/index.wxss b/packages/template-acheng-campus-food/miniapp/pages/index/index.wxss new file mode 100644 index 0000000..a5992e3 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/pages/index/index.wxss @@ -0,0 +1,11 @@ +.page { + background: #fff8f0; + min-height: 100vh; +} +.runtime-error { + margin: 48rpx 32rpx; + padding: 28rpx; + color: #8a4b2a; + background: #fff; + border-radius: 16rpx; +} diff --git a/packages/template-acheng-campus-food/miniapp/pages/inquiry-success/index.js b/packages/template-acheng-campus-food/miniapp/pages/inquiry-success/index.js new file mode 100644 index 0000000..d055a3e --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/pages/inquiry-success/index.js @@ -0,0 +1,36 @@ +const { customerRequest, customerTokenKey } = require("../../utils/request"); +const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace"); + +Page({ + data: { record: {}, presentation: {} }, + onLoad(options) { + loadWorkspaceWithFallback() + .then((workspace) => + this.setData({ presentation: workspace.brand?.visualPresentation?.success || {} }), + ) + .catch(() => {}); + const record = wx.getStorageSync("latestInquirySubmission") || {}; + if (record.id === options.id) this.setData({ record }); + if (options.id && wx.getStorageSync(customerTokenKey())) { + customerRequest("/customer/inquiry-submissions/" + encodeURIComponent(options.id)) + .then((submission) => + this.setData({ + record: { + ...record, + id: submission.id, + status: submission.status === "new" ? "待处理" : submission.status, + createdAt: submission.createdAt, + offeringName: submission.offering?.name || record.offeringName || "品牌合作", + }, + }), + ) + .catch(() => {}); + } + }, + viewRecords() { + wx.redirectTo({ url: "/pages/records/index" }); + }, + home() { + wx.navigateTo({ url: "/pages/index/index" }); + }, +}); diff --git a/packages/template-acheng-campus-food/miniapp/pages/inquiry-success/index.json b/packages/template-acheng-campus-food/miniapp/pages/inquiry-success/index.json new file mode 100644 index 0000000..3b7f1b8 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/pages/inquiry-success/index.json @@ -0,0 +1,6 @@ +{ + "navigationBarTitleText": "预订已收到", + "navigationBarBackgroundColor": "#F7F5F1", + "navigationBarTextStyle": "black", + "usingComponents": { "success-summary": "/components/modules/success-summary/success-summary" } +} diff --git a/packages/template-acheng-campus-food/miniapp/pages/inquiry-success/index.wxml b/packages/template-acheng-campus-food/miniapp/pages/inquiry-success/index.wxml new file mode 100644 index 0000000..fd9f8bc --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/pages/inquiry-success/index.wxml @@ -0,0 +1 @@ + diff --git a/packages/template-acheng-campus-food/miniapp/pages/inquiry-success/index.wxss b/packages/template-acheng-campus-food/miniapp/pages/inquiry-success/index.wxss new file mode 100644 index 0000000..9154972 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/pages/inquiry-success/index.wxss @@ -0,0 +1,83 @@ +.page { + min-height: 100vh; + padding: 130rpx 48rpx; + background: #f7f5f1; + color: #252525; +} +.food-success { + min-height: 100vh; + padding: 32rpx; + background: #fff8f0; +} +.food-success .primary { + background: #e87532; +} +.food-success .secondary { + border-color: #e87532; + color: #c65c28; +} +.mark { + width: 120rpx; + height: 120rpx; + border: 3rpx solid #8a6846; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + color: #8a6846; + font-size: 70rpx; + font-family: serif; +} +.eyebrow { + display: block; + margin-top: 70rpx; + color: #8a6846; + font-size: 20rpx; + letter-spacing: 4rpx; +} +.title { + display: block; + margin-top: 18rpx; + font-family: serif; + font-size: 58rpx; +} +.intro { + display: block; + margin-top: 24rpx; + color: #77736b; + font-size: 28rpx; + line-height: 1.8; +} +.summary { + margin-top: 56rpx; + padding: 10rpx 26rpx; + background: #fff; +} +.summary view { + display: flex; + justify-content: space-between; + padding: 26rpx 0; + border-bottom: 1rpx solid #e6ded5; + font-size: 27rpx; +} +.summary view:last-child { + border-bottom: 0; +} +.summary text:last-child { + color: #8a6846; +} +.primary, +.secondary { + margin-top: 28rpx; + border-radius: 0; + font-size: 28rpx; +} +.primary { + background: #252827; + color: #fff; +} +.secondary { + background: transparent; + border: 1rpx solid #8a6846; + color: #8a6846; +} diff --git a/packages/template-acheng-campus-food/miniapp/pages/inquiry/index.js b/packages/template-acheng-campus-food/miniapp/pages/inquiry/index.js new file mode 100644 index 0000000..6208c43 --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/pages/inquiry/index.js @@ -0,0 +1,148 @@ +const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace"); +const { request, customerRequest, customerTokenKey } = require("../../utils/request"); + +const typeOptions = [ + "日常留餐", + "宿舍开黑餐", + "社团 / 班级活动", + "生日聚会", + "考试周加餐", + "其他需求", +]; +const peopleOptions = [ + "1 人(单点)", + "2-4 人(寝室小聚)", + "5-10 人(部门小聚)", + "10-30 人(社团活动)", + "30 人以上(大型活动)", +]; +const budgetOptions = [ + "15 元左右 / 人(实惠)", + "18-22 元 / 人(荤素双拼)", + "25 元以上 / 人(高规格定制)", +]; +const deliveryOptions = [ + "摊位自取(报手机尾号即拿)", + "送至宿舍楼下(满 3 份)", + "送至指定教室 / 场地", +]; +const labels = { + new: "待处理", + reviewing: "沟通中", + replied: "已回复", + qualified: "已确认", + converted: "已转化", + closed: "已关闭", +}; + +Page({ + data: { + subView: "form", + records: [], + typeOptions, + peopleOptions, + budgetOptions, + deliveryOptions, + peopleIndex: 1, + budgetIndex: 1, + deliveryIndex: 0, + values: { + type: "日常留餐", + people: peopleOptions[1], + budget: budgetOptions[1], + delivery: deliveryOptions[0], + }, + formId: "", + submitting: false, + formError: "", + }, + onLoad(options) { + loadWorkspaceWithFallback() + .then((workspace) => { + const form = + (workspace.inquiryForms || []).find((item) => item.targetId === options.offeringId) || + (workspace.inquiryForms || []).find((item) => item.target === "brand") || + workspace.inquiryForms?.[0]; + this.setData({ formId: form?.key || form?.id || "" }); + }) + .catch(() => {}); + }, + onShow() { + if (!wx.getStorageSync(customerTokenKey())) return; + customerRequest("/customer/inquiry-submissions") + .then((items) => + this.setData({ + records: (items || []).map((item) => ({ + ...item, + type: item.inquiryForm?.name || item.values?.type || "品牌咨询", + people: item.values?.people || "", + time: item.values?.date || "", + delivery: item.values?.delivery || "", + remark: item.values?.remark || "", + status: labels[item.status] || item.status, + replyNote: item.replyNote, + createdAt: new Date(item.createdAt).toLocaleDateString("zh-CN"), + })), + }), + ) + .catch(() => {}); + }, + switchView(e) { + this.setData({ subView: e.currentTarget.dataset.view }); + }, + switchToForm() { + this.setData({ subView: "form" }); + }, + chooseType(e) { + this.setData({ "values.type": e.currentTarget.dataset.value }); + }, + choosePeople(e) { + const index = Number(e.detail.value); + this.setData({ peopleIndex: index, "values.people": peopleOptions[index] }); + }, + chooseBudget(e) { + const index = Number(e.detail.value); + this.setData({ budgetIndex: index, "values.budget": budgetOptions[index] }); + }, + chooseDelivery(e) { + const index = Number(e.detail.value); + this.setData({ deliveryIndex: index, "values.delivery": deliveryOptions[index] }); + }, + chooseDate(e) { + this.setData({ "values.date": e.detail.value }); + }, + input(e) { + this.setData({ ["values." + e.currentTarget.dataset.key]: e.detail.value }); + }, + submit() { + const { values, formId } = this.data; + if (!values.phone) + return this.setData({ formError: "请填写手机号或微信号,以便阿成加您发排菜菜单" }); + if (!values.date) return this.setData({ formError: "请选择期望用餐日期" }); + if (!formId) return this.setData({ formError: "咨询表单暂不可用,请稍后重试" }); + this.setData({ submitting: true, formError: "" }); + const send = () => + customerRequest("/customer/inquiry-submissions", { + method: "POST", + data: { formId, values }, + }).then((result) => { + wx.setStorageSync("latestInquirySubmission", result); + this.setData({ submitting: false, subView: "history" }); + this.onShow(); + wx.showToast({ title: "已提交,阿成会尽快联系你", icon: "none" }); + }); + const fail = (error) => + this.setData({ submitting: false, formError: error.message || "提交失败,请重试" }); + if (wx.getStorageSync(customerTokenKey())) return send().catch(fail); + wx.login({ + success: (login) => + request("/customer/session/wechat", { method: "POST", data: { code: login.code } }) + .then((result) => { + wx.setStorageSync(customerTokenKey(), result.token); + return send(); + }) + .catch(fail), + fail, + }); + }, +}); diff --git a/packages/template-acheng-campus-food/miniapp/pages/inquiry/index.json b/packages/template-acheng-campus-food/miniapp/pages/inquiry/index.json new file mode 100644 index 0000000..8537ceb --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/pages/inquiry/index.json @@ -0,0 +1,12 @@ +{ + "navigationBarTitleText": "提交咨询", + "navigationBarBackgroundColor": "#FBF7F1", + "navigationBarTextStyle": "black", + "usingComponents": { + "brand-button": "/components/ui/brand-button/brand-button", + "brand-field": "/components/ui/brand-field/brand-field", + "brand-loading": "/components/ui/brand-loading/brand-loading", + "brand-empty": "/components/ui/brand-empty/brand-empty", + "inquiry-form": "/components/modules/inquiry-form/inquiry-form" + } +} diff --git a/packages/template-acheng-campus-food/miniapp/pages/inquiry/index.wxml b/packages/template-acheng-campus-food/miniapp/pages/inquiry/index.wxml new file mode 100644 index 0000000..2e5e13c --- /dev/null +++ b/packages/template-acheng-campus-food/miniapp/pages/inquiry/index.wxml @@ -0,0 +1,5 @@ + + ▤ 新建咨询 / 预订▣ 我的咨询记录 ({{records.length}}) + 定制 / 预留需求登记告诉阿成时间与人数,阿成量身帮你们排菜(免收预约定金)1. 咨询类型 *{{item}}预计用餐人数 *{{values.people || '请选择人数'}}期望用餐时间 *{{values.date || '请选择日期'}}人均预算期望{{values.budget || '请选择预算'}}取餐 / 配送偏好{{values.delivery || '请选择方式'}}预留餐品 / 口味偏好 / 忌口备注