Compare commits

...
160 Commits
Author SHA1 Message Date
que01 4afb6bbbe8 fix: 拦截禁用业务的过期提交 2026-09-22 11:54:39 +08:00
que01 7821c0c98c test: 覆盖业务提供项生命周期操作 2026-09-22 11:25:03 +08:00
que01 2aafa871bc feat: 完善业务提供项生命周期管理 2026-09-22 11:11:52 +08:00
que01 754da72245 feat: 后台支持咨询跟进状态管理 2026-09-22 10:21:21 +08:00
que01 d981f63f65 test: 覆盖咨询跟进状态接口 2026-09-22 10:01:14 +08:00
que01 45822f9c57 feat: 增加咨询记录跟进状态 2026-09-22 09:29:56 +08:00
que01 25bf980d3c feat: 保存咨询提交的业务来源 2026-09-21 20:18:18 +08:00
que01 4754230e5b feat: 按业务提供项配置分流行动入口 2026-09-21 20:11:12 +08:00
que01 888a504423 feat: 在业务提供项公开详情中关联咨询表单 2026-09-21 20:08:22 +08:00
que01 c907734076 fix: 移除服务列表重复请求 2026-09-21 19:57:02 +08:00
que01 bf73c3ce08 test: 验证旧业务提供项路由已移除 2026-09-21 19:43:53 +08:00
que01 dd12fd170e refactor: 后台统一使用业务提供项管理 2026-09-21 19:33:27 +08:00
que01 40ea7d245b refactor: 移除业务提供项兼容客户端入口 2026-09-21 19:26:05 +08:00
que01 c3edc4f595 docs: 更新业务提供项公开契约 2026-09-21 19:16:46 +08:00
que01 a374614313 refactor: 统一前端业务提供项命名 2026-09-21 18:00:20 +08:00
que01 88cd8df40e refactor: 删除旧业务提供项路由 2026-09-21 17:44:00 +08:00
que01 fe7005d4d0 refactor: 收口业务提供项接口契约 2026-09-21 17:39:07 +08:00
que01 844a3bd715 refactor: 移除旧服务模型统一使用业务提供项 2026-09-21 17:11:45 +08:00
que01 ca85a583ce refactor: 统一服务兼容接口的数据来源 2026-09-21 16:38:09 +08:00
que01 537838532a feat: 回填旧服务的业务提供项关联 2026-09-21 16:31:50 +08:00
que01 600b1d64b4 refactor: 使用 Zod 校验扩展配置 2026-09-21 16:11:34 +08:00
que01 8baa042255 feat: 增加扩展配置校验器 2026-09-21 16:03:03 +08:00
que01 29d14378a7 feat: 建立工作流与能力注册表 2026-09-21 15:45:19 +08:00
que01 c00e188392 fix: 统一预约取消的工作流状态判断 2026-09-21 15:36:46 +08:00
que01 549b488d51 feat: 增加运行时工作空间契约 2026-09-21 15:24:34 +08:00
que01 36f5415483 test: 收口预约工作流状态历史验证 2026-09-21 15:12:17 +08:00
que01 e9d3f77639 feat: 建立预约工作流状态历史 2026-09-21 15:03:46 +08:00
que01 0381c0a902 feat: 为咨询表单增加提交语义 2026-09-21 14:53:07 +08:00
que01 73e21e6b0d feat: 增加品牌通用扩展配置 2026-09-21 14:10:25 +08:00
que01 270136d24e feat: 为预约建立业务提供项关联 2026-09-21 13:59:14 +08:00
que01 11d0424669 docs: 修正架构决策文档引用 2026-09-21 13:47:18 +08:00
que01 20bbc0a0a8 docs: 固化行业分叉前架构边界 2026-09-21 13:46:27 +08:00
que01 665a88eb30 fix: 完成管理端类型安全收口 2026-09-21 12:28:09 +08:00
que01 2712517e64 chore: 收紧管理端 lint 配置与类型断言 2026-09-21 12:19:24 +08:00
que01 ed2e3bd715 fix: 修正管理端 API 类型导出与无效依赖 2026-09-21 12:14:24 +08:00
que01 6f2cc51985 chore: 清理类型检查与控制器无效依赖 2026-09-21 12:08:54 +08:00
que01 6edb9d7a30 fix: 为微信登录补充请求校验 2026-09-21 11:51:38 +08:00
que01 41e4cc0f1c fix: 恢复客户会话控制器路由装饰器 2026-09-21 11:27:10 +08:00
que01 b2788966bf refactor: 抽离模板工作空间服务 2026-09-21 11:18:21 +08:00
que01 9e4f2620c6 refactor: 拆分后台工作空间控制器 2026-09-21 10:32:32 +08:00
que01 292b398ed7 docs: 固化分阶段交付与评审流程 2026-09-20 23:18:40 +08:00
que01 b38e1d4bda docs: 补充功能交付与评审清单 2026-09-20 23:16:39 +08:00
que01 84a21b0012 test: 补齐模板回滚授权与成功测试 2026-09-20 22:55:47 +08:00
que01 4191ba8df5 feat: 增加模板版本回滚能力 2026-09-20 22:38:31 +08:00
que01 74feb3579c feat: 接入模板升级管理界面 2026-09-20 17:58:52 +08:00
que01 44b6f6db64 feat: 增加模板升级预览与显式升级 2026-09-20 17:55:22 +08:00
que01 388032000a feat: 让模板声明驱动安装并保存快照 2026-09-20 17:48:33 +08:00
que01 a3434ce2b9 feat: 建立版本化模板注册表 2026-09-20 17:37:57 +08:00
que01 3524a6f322 docs: 明确模板配置包与插件边界 2026-09-20 17:33:29 +08:00
que01 bf5fba9480 feat: 完善模板与设置工作台 2026-09-20 17:19:04 +08:00
que01 07866f48d0 feat: 重构业务提供项管理工作台 2026-09-20 17:16:01 +08:00
que01 ecda0d0b00 feat: 完善后台信任内容工作台 2026-09-20 17:06:48 +08:00
que01 24ab55c0d0 feat: 重构品牌表达编辑工作台 2026-09-20 16:59:58 +08:00
que01 e402ba58d9 feat: 重构后台品牌工作台基础骨架 2026-09-20 16:41:57 +08:00
que01 ac4abc1305 fix: 固化后台API Client构建顺序 2026-09-20 16:10:39 +08:00
que01 1fab79546d fix: 显示动态咨询提交查询状态 2026-09-20 16:03:23 +08:00
que01 5a19edc0e4 feat: 增加后台动态咨询提交记录 2026-09-20 15:17:57 +08:00
que01 0fd6c664bf fix: 移除小程序不稳定错误组件依赖 2026-09-20 14:20:24 +08:00
que01 38eb3962b2 fix: 修复小程序组件依赖分析 2026-09-20 14:08:22 +08:00
que01 4987689cb0 fix: 展示工作空间真实请求错误 2026-09-20 13:57:43 +08:00
que01 aeb7eb7322 fix: 明确后台工作空间登录失效提示 2026-09-20 13:33:45 +08:00
que01 02966cf65c feat: 接入配置驱动的动态咨询表单 2026-09-20 12:28:47 +08:00
que01 8872316ad3 refactor: 完善小程序品牌组件视觉层 2026-09-20 12:05:42 +08:00
que01 e4adfc6b13 docs: 固化小程序设计与模板渲染规范 2026-09-20 11:59:36 +08:00
que01 17af0f6883 fix: 支持小程序本地API地址切换 2026-09-20 11:43:26 +08:00
que01 1a9dc426f6 feat: 接入小程序品牌组件基础层 2026-09-20 11:33:58 +08:00
que01 8fd399f4c2 feat: 接入小程序业务提供项详情渲染 2026-09-20 10:32:38 +08:00
que01 5e26999c72 feat: 增加公开业务提供项列表契约 2026-09-20 10:26:09 +08:00
que01 1a4e806ca8 fix: 强化工作空间字段运行时校验 2026-09-20 10:19:44 +08:00
que01 1503f042e0 feat: 完成动态咨询表单公开读取与提交 2026-09-20 10:02:25 +08:00
que01 4470302b3f fix: 收口模板主模板策略与提供项响应契约 2026-09-20 09:54:35 +08:00
que01 7e83d16cc9 feat: 接入后台动态咨询表单配置 2026-09-20 09:41:31 +08:00
que01 32d3db90de feat: 增加动态咨询表单配置接口 2026-09-20 09:37:40 +08:00
que01 46c3e5504e feat: 增加后台品牌工作空间配置页面 2026-09-20 09:31:11 +08:00
que01 6e1aca3e27 feat: 增加品牌工作空间模块与字段配置接口 2026-09-20 09:27:28 +08:00
que01 02aa698fb9 refactor: 将提供项详情改为结构化表单 2026-09-20 09:18:29 +08:00
que01 7f0830567e feat: 支持后台配置业务提供项详情内容 2026-09-20 09:14:00 +08:00
que01 09841aed05 feat: 增加后台业务提供项配置 2026-09-20 09:09:40 +08:00
que01 8e46c2c293 feat: 完善业务提供项详情内容契约 2026-09-20 09:04:10 +08:00
que01 0a96095e89 fix: 注册业务提供项公开控制器 2026-09-20 09:00:02 +08:00
que01 066f6595e4 feat: 增加业务提供项管理与详情接口 2026-09-20 08:55:38 +08:00
que01 a73e377f91 feat: 增加模板安装与品牌工作空间接口 2026-09-20 00:11:44 +08:00
que01 8795086ece feat: 增加品牌工作空间与业务提供项模型 2026-09-19 22:47:10 +08:00
que01 4f26dce212 docs: 设计品牌工作空间数据模型 2026-09-19 22:39:11 +08:00
que01 800f82521f docs: 固化模板工作空间与业务提供项模型 2026-09-19 22:37:21 +08:00
que01 6ee0dffdb8 feat: 在后台展示当前行业模板定义 2026-09-19 21:27:11 +08:00
que01 c6785892ed feat: 增加可替换行业模板定义接口 2026-09-19 21:20:20 +08:00
que01 2b1035dbc8 feat: 完善后台部署与API前缀配置 2026-09-19 21:12:53 +08:00
que01 c821d6c7db fix: 修复后台菜单页面路由匹配 2026-09-19 20:57:14 +08:00
que01 893a547967 refactor: 清理旧后台入口并优化页面分包 2026-09-19 19:02:25 +08:00
que01 8ea80f8c80 feat: 增加咨询记录详情抽屉 2026-09-19 18:56:12 +08:00
que01 5a5a74b084 refactor: 收口后台页面模块化结构 2026-09-19 18:53:49 +08:00
que01 10a2adbe87 refactor: 拆分后台服务管理模块 2026-09-19 18:51:51 +08:00
que01 54224d4110 refactor: 拆分后台信任内容模块 2026-09-19 18:50:38 +08:00
que01 bff6e4e9d6 refactor: 拆分后台咨询记录模块 2026-09-19 18:49:10 +08:00
que01 8033cabff9 style: 统一全仓代码格式 2026-09-19 18:46:26 +08:00
que01 d811478d0f refactor: 抽离管理后台基础设施模块 2026-09-19 18:44:47 +08:00
que01 cfa183015b docs: 完善工程治理与架构决策规范 2026-09-19 18:42:08 +08:00
que01 3c24235ad4 docs: 固化项目架构与交付规范 2026-09-19 18:39:55 +08:00
que01 718d357d88 style: 统一项目代码格式 2026-09-19 18:37:00 +08:00
que01 f0836ec056 refactor: 接入后台页面路由 2026-09-19 18:34:10 +08:00
que01 86da43b635 feat: 完善后台登录态与退出体验 2026-09-19 18:29:38 +08:00
que01 3dcc31d717 feat: 接入后台咨询记录管理 2026-09-19 18:26:52 +08:00
que01 c393a5231e fix: 修复后台配置接口与管理后台高优先级问题 2026-09-19 18:20:51 +08:00
que01 69bbeb1b1b feat: 接入后台通用服务管理页面 2026-09-19 17:54:45 +08:00
que01 ad70eef8eb feat: 接入后台信任内容管理页面 2026-09-19 17:50:20 +08:00
que01 f29e64724d feat: 建立 React 管理后台基础架构 2026-09-19 17:46:57 +08:00
que01 b7fbfa1646 feat: 增加个人品牌信任内容管理接口 2026-09-19 17:44:33 +08:00
que01 60db0a85db docs: 记录个人品牌产品主线 2026-09-19 17:09:27 +08:00
que01 e23d0baba7 fix: 提供可访问的后台登录入口 2026-09-19 16:59:34 +08:00
que01 e0fb508c0a fix: 同步服务配置共享类型 2026-09-19 16:51:38 +08:00
que01 d167b58a05 feat: 完善通用服务后台配置能力 2026-09-19 16:50:32 +08:00
que01 60ca897574 fix: 重做服务分类装饰纹样 2026-09-19 16:39:39 +08:00
que01 82ab99d8b5 fix: 精修服务订单与数量控件样式 2026-09-19 16:34:57 +08:00
que01 c919d7a866 fix: 使用微信原生底部导航 2026-09-19 16:15:31 +08:00
que01 3da24ede37 feat: 接入品牌图片资源并优化尺寸 2026-09-19 15:44:03 +08:00
que01 60c2937ee2 fix: 让订单文案随行业模板切换 2026-09-19 12:42:44 +08:00
que01 e807bba1cb feat: 后台支持切换行业模板 2026-09-19 12:38:31 +08:00
que01 8d93f34260 feat: 增加通用品牌咨询记录类型 2026-09-19 12:36:50 +08:00
que01 0228112846 refactor: 按行业模板驱动需求表单 2026-09-19 12:32:16 +08:00
que01 5b831b6740 feat: 增加行业模板注册与切换能力 2026-09-19 12:28:15 +08:00
que01 3c7ce2a8fa refactor: 引入品牌行业模板配置 2026-09-19 12:26:29 +08:00
que01 653fe596ac refactor: 将小程序文案纠偏为个人品牌语义 2026-09-19 12:20:08 +08:00
que01 a90a47f808 fix: 清理重复服务并增加唯一约束 2026-09-19 12:11:53 +08:00
que01 5ab8c34a78 fix: 修复预约页脚本语法错误 2026-09-19 12:09:11 +08:00
que01 3ddef14c08 test: 覆盖后台配置接口 2026-09-19 12:07:22 +08:00
que01 f485257e37 feat: 增加后台品牌与服务配置能力 2026-09-19 12:04:59 +08:00
que01 34ec893369 refactor: 模块化小程序配置与请求逻辑 2026-09-19 12:00:54 +08:00
que01 5b5ba9f7da test: 完善联调数据初始化与集成测试 2026-09-19 11:56:07 +08:00
que01 38e2a0fb64 fix: 完善预约订单交互与状态展示 2026-09-19 11:51:58 +08:00
que01 cd242767a6 fix: 修复小程序取消预约请求体 2026-09-19 11:42:26 +08:00
que01 e19b6258d7 feat: 完善预约与订单页面闭环 2026-09-19 11:40:51 +08:00
que01 a6592066c1 chore: 增加 API 请求链路日志 2026-09-19 11:29:55 +08:00
que01 89eecc1c46 fix: 使用编译产物启动 API 开发服务 2026-09-19 11:24:49 +08:00
que01 ccf1c6bc31 fix: 暴露开发环境 API 异常详情 2026-09-19 11:23:15 +08:00
que01 b4657ccdc0 fix: 增强微信登录和预约错误日志 2026-09-19 11:19:32 +08:00
que01 5db15538ad fix: 配置局域网 API 地址用于真机调试 2026-09-19 11:09:25 +08:00
que01 60cac4155a fix: 补齐小程序工程入口文件 2026-09-19 11:05:27 +08:00
que01 b7a53033bc chore: 配置微信小程序 AppID 2026-09-19 11:02:04 +08:00
que01 7c741b9823 docs: 更新小程序静态页面交付状态 2026-09-19 10:59:13 +08:00
que01 fee3c775ee fix: 按设计图优化预约套餐数量和商品卡 2026-09-19 10:57:21 +08:00
que01 14d7c6c90a feat: 提升小程序页面设计还原度 2026-09-19 10:53:37 +08:00
que01 21b2262294 fix: 严格区分预约和我的订单页面 2026-09-19 10:50:29 +08:00
que01 13ead2d426 fix: 对齐服务分类和订单视觉结构 2026-09-19 10:46:30 +08:00
que01 662649a08f fix: 修复小程序底部导航并精修首页 2026-09-19 10:43:28 +08:00
que01 2beda85a73 feat: 完善小程序预约和订单闭环 2026-09-19 10:41:28 +08:00
que01 6a66d20b81 feat: 增加小程序服务预约和订单页面 2026-09-19 10:37:51 +08:00
que01 63e5e3bd7b fix: 优化小程序原生标题层级 2026-09-19 10:35:43 +08:00
que01 990b105086 feat: 按设计图重做小程序首页 2026-09-19 10:32:27 +08:00
que01 255756c6dd feat: 增加小程序品牌首页 2026-09-19 10:14:30 +08:00
que01 3b05df6edf refactor: 集中管理共享状态常量 2026-09-19 09:52:09 +08:00
que01 868a4251ce feat: 接入小程序 API 客户端 2026-09-19 09:50:16 +08:00
que01 a6d30d1222 feat: 完善后台订单处理交互 2026-09-19 09:18:22 +08:00
que01 5fe750fbd4 feat: 接入管理后台订单列表 2026-09-19 09:14:05 +08:00
que01 b9939fe173 feat: 创建类型化 API 客户端 2026-09-19 01:11:27 +08:00
que01 02554ed86c docs: 增加 API OpenAPI 契约 2026-09-19 01:03:31 +08:00
que01 3640ec46ed test: 覆盖预约创建取消和状态流转 2026-09-19 01:00:43 +08:00
que01 21801212d2 test: 扩展客户接口集成测试 2026-09-19 00:58:56 +08:00
que01 3c59b6406b test: 增加 API HTTP 集成测试 2026-09-19 00:57:16 +08:00
que01 50f405932b test: 补充订单业务测试和数据库验证 2026-09-19 00:54:19 +08:00
148 changed files with 9478 additions and 146 deletions

No files matched your search

+1
View File
@@ -5,6 +5,7 @@ POSTGRES_PASSWORD=postgres
POSTGRES_DB=personal_brand
POSTGRES_PORT=5432
API_PORT=3001
API_PREFIX=
ADMIN_PORT=3000
SESSION_SECRET=replace-with-a-long-random-value
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
+65
View File
@@ -0,0 +1,65 @@
# Product Direction
- The core product is a personal-brand platform whose primary goal is to build trust and convert that trust into qualified inquiries or collaborations.
- Personal-brand identity, positioning, proof of work, communication expectations, and contact paths are higher priority than any single industry workflow.
- Industry behavior is implemented as replaceable templates. Food, consulting, design, photography, and future industries must not hard-code their terminology or fields into the shared brand model or shared UI.
- The food template is supported, but it is an example template rather than the product definition.
- Backend configuration is the source of truth for brand content, services, template selection, trust-building content, and industry-specific fields. The mini program only renders configuration and submits user input.
- Any delivered backend endpoint must have an automated test covering its authorization and successful behavior before it is considered complete.
- Keep personal-brand trust details explicit: biography, positioning, credentials, portfolio/proof, process, expectations, availability, contact methods, and clear follow-up status.
# Engineering Architecture Rules
## Backend boundaries
- NestJS controllers only handle transport concerns: authentication, DTO binding, status codes, and response shape.
- Domain behavior belongs in services; Prisma access must not be duplicated across controllers.
- DTOs are the runtime validation boundary. Do not use `Partial<T>` or plain TypeScript interfaces as request bodies for validated endpoints.
- Every protected endpoint must test missing credentials, invalid credentials or wrong role, and the successful authorized path.
- Public endpoints may only expose published content and must enforce brand isolation through the configured brand identifier.
## Admin frontend boundaries
- React pages must be split by feature under `apps/admin/src/features/<feature>/`; a page component should coordinate UI, not contain the entire application.
- Shared API construction, authentication-aware `fetch`, query keys, and error handling belong under `apps/admin/src/lib/`.
- Shared visual elements belong under `apps/admin/src/components/`; feature-specific forms and tables stay inside their feature module.
- Routing belongs in `apps/admin/src/app/` and navigation must use React Router. Do not use a local state variable as the primary page router.
- A mutation must close or reset a form only after `onSuccess`; failed requests must preserve user input and show an actionable error.
- API base URLs must come from `VITE_API_BASE_URL` with a documented local fallback; no feature may hard-code an environment-specific host.
- Admin session expiry must clear the token, notify the user, and return to the login screen consistently.
## Formatting, testing, and delivery
- Prettier is the formatting source of truth. New or changed files must pass `pnpm format:check`.
- Before delivery, run relevant type checks, API integration tests, and frontend production builds. Do not claim an endpoint is delivered without a passing automated test.
- Prefer cohesive commits that complete a reviewable unit of work; do not submit speculative fragments while the feature is broken.
- When a code review identifies a recurring design issue, update this file or a focused architecture document before implementing the next related feature.
- Before delivery, follow `docs/engineering-delivery-checklist.md`; a feature is incomplete when its API path, failure path, data migration, client contract, UI states, or user-visible operation semantics are unverified.
## Production engineering standards
- Record material architectural decisions in `docs/adr/` using the format `NNNN-title.md`: context, decision, alternatives, consequences, and migration plan. Do not silently introduce a second state-management, validation, routing, or persistence pattern.
- Treat the API Client types and DTOs as an explicit contract. Any response or request shape change must update the shared client, its tests, and the consuming feature in the same change.
- Keep API responses consistent: successful payloads use the established envelope, errors use the global error filter with a stable machine-readable code and `requestId`. Never expose stack traces or database errors to clients.
- Validate all external input at the boundary, use allow-lists for enums and template keys, and apply authorization before loading or mutating tenant/brand data. Never trust a client-supplied `brandId`.
- Secrets and environment-specific URLs belong in environment configuration. Commit `.env.example`, never real credentials, and fail fast when a required production variable is missing.
- Database changes must be additive and reversible where practical: update Prisma schema, migration, seed data, API behavior, and integration tests together. Avoid destructive migrations without an explicit migration plan.
- Follow a testing pyramid: focused unit tests for pure domain rules, API integration tests for authorization and persistence, and a small number of frontend interaction tests for critical flows. Tests must isolate data and clean up fixtures.
- Make asynchronous UI states explicit: loading, empty, error, success, and retry. Mutations must be idempotent where possible and must invalidate or update affected query caches.
- Keep observability intentional: include `requestId` in errors and logs, log state-changing admin actions without secrets, and use structured log fields rather than concatenated messages.
- Use dependency and type safety gates before merge: formatting, lint, typecheck, relevant tests, production build, and a clean diff. A known warning must be documented with an owner or follow-up issue.
- Prefer small, cohesive modules with one reason to change. A feature may depend on shared infrastructure, but shared infrastructure must not import feature modules.
- Public and admin behavior must be documented at the route or feature boundary, including authentication, roles, validation, status transitions, and failure behavior.
# Codex Code Guidelines
## 中文回复
- 所有回复使用简体中文。
- 技术术语保留 English,首次出现可添加中文解释。
- 代码变量名保持 English,注释使用中文。
## Git Commit
- 使用中文提交信息。
- 格式:`类型: 简短描述`。
+23 -8
View File
@@ -1,6 +1,6 @@
# Project Status
最后更新:2026-09-18
最后更新:2026-09-19
## 当前目标
@@ -8,7 +8,7 @@
## 当前阶段
后端基础与工程环境已建立,正在把 API 做到可以交给小程序和管理后台接入的程度。小程序和后台页面尚未接入真实 API。
后端基础、数据库环境和订单 API 已完成首轮验证,管理后台和小程序静态页面已接入首版结构,下一步进行真实资源与微信登录/预约联调。
## 已完成
@@ -27,11 +27,28 @@
- 管理员订单列表、状态、未读、标签和内部备忘能力。
- DTO 校验、全局异常响应、请求 ID和订单状态流转规则。
- Docker PostgreSQL Compose、seed 和 Prisma 脚本说明。
- 初始 Prisma migration,已在本地 PostgreSQL 应用并验证数据库 schema up to date。
- seed 已写入品牌、服务、标签和管理员数据,并完成数量核验。
- 管理员订单详情、状态/未读/标签筛选和未读数量接口。
- API 自动化业务规则测试:订单创建、客户取消、状态流转和标签品牌隔离,共 6 项通过。
- 修复 ESM 下 `bcryptjs` 导入和 Fastify 请求 ID middleware 的运行时问题。
- API 已通过真实 HTTP 验证:健康检查、公开品牌/服务读取和管理员登录。
- HTTP 集成测试:公开接口、管理员登录、错误密码、管理员权限边界、客户会话、预约 DTO 校验、创建/取消和状态流转,共 8 项通过。
- OpenAPI 3.1 契约:`docs/openapi.yaml`,覆盖当前公开、客户和管理员接口。
- 类型化 `@personal-brand/api-client`:支持公开内容、客户预约、管理员订单和统一错误处理,并有 2 项客户端测试。
- 已根据 `/home/que01/桌面/个人品牌设计图/` 确认 C 端页面视觉规范:暖白、米黄、砖红、深炭黑,16px 卡片圆角和大字号优先。
- 小程序已完成首页、服务列表、预约套餐和我的订单静态页面,页面标题使用微信原生导航栏。
- 已配置小程序 AppID:`wxd75d946d6978d183`。
- 服务分类、预约数量步进器、订单状态卡和底部导航已按设计图完成首版还原。
- 已执行多轮 Codex 代码审查并修复关键认证和权限问题。
## 最近提交
```text
fee3c77 fix: 按设计图优化预约套餐数量和商品卡
13ead2d fix: 对齐服务分类和订单视觉结构
255756c feat: 增加小程序品牌首页
本次工作:数据库初始化、订单管理接口、业务规则测试和运行时修复
f2687c5 chore: prepare portable postgres development environment
0e8b8e1 feat: add api http conventions and booking state rules
0d4caab feat: add admin order tags and read state
@@ -43,12 +60,10 @@ b89853b fix: harden api authentication and validation
## 下一步优先级
1. 在有 Docker/PostgreSQL 的机器执行 Prisma migration 和 seed,确认真实数据库可运行。
2. 修正并补齐 API 集成测试:客户隔离、订单提交、取消、状态机、管理员权限、标签归属。
3. 补管理员订单详情、筛选和未读数量接口。
4. 补 OpenAPI/Swagger 契约和统一响应示例。
5. 创建类型化 `api-client`,再接入管理后台和小程序。
6. 先接管理后台订单处理,再接小程序品牌展示和下单。
1. 接入真实品牌图片、电话和微信配置,并替换当前图片占位区域。
2. 在微信开发者工具/真机完成 `wx.login`、预约提交、订单查询和取消联调。
3. 完善管理后台订单详情、筛选和状态处理视觉页面。
4. 继续补充页面截图回归和真实素材下的移动端溢出检查。
## 未决问题
+65 -1
View File
@@ -40,7 +40,7 @@
- Monorepo:`pnpm workspace + Turborepo`
- 小程序:原生微信小程序 + TypeScript
- 管理后台:Next.js + TypeScript
- 管理后台:React + TypeScript + Vite;本地使用 Vite proxy,生产使用 Nginx 反向代理
- API:NestJS + TypeScript
- 数据库:PostgreSQL
- ORM:Prisma
@@ -48,6 +48,18 @@
- 后台登录:第一版账号密码,未来可绑定微信身份
- 发布:第一版人工使用微信开发者工具发布
## 行业分叉前的架构不变量
- `Brand Core` 只负责个人身份、信任、业务展示、联系与咨询;行业字段和行业流程不得反向进入核心模型。
- 模板是声明式配置包,负责行业表达和默认配置;复杂排期、报价、库存、支付和行业状态机属于独立 capability。
- `Offering` 是服务、产品、套餐和订阅的统一业务身份;`Service` 仅保留为迁移兼容入口,新的核心流程不得建立新的 Service 关联。
- 动态表单必须声明用途、目标对象和提交动作,不能让客户端根据字段猜测是否创建预约或订单。
- 订单或预约状态由带版本的 workflow 定义,核心只提供状态、权限、审计和非法跳转保护。
- 小程序和 Admin 消费后端生成的 runtime workspace contract,不根据 `templateKey` 编写行业分支。
- 所有扩展 JSON 必须带 schema version,并在 DTO 或 capability validator 边界校验。
行业模板扩展前,必须先完成 `docs/adr/0004-industry-fork-readiness.md` 中的 Offering、品牌行业字段、表单动作、workflow 和 runtime workspace 五项收口。
## 第一版范围
必须实现:
@@ -158,3 +170,55 @@ docs/
- 相关验证已执行,或明确说明无法执行的原因。
- 变更符合第一版范围和数据/API 约束。
- 用户能根据结果继续下一步工作。
## Trellis 风格交付流程
后续功能按固定阶段推进。阶段之间必须有可检查的产物,不能把“代码能运行”直接当作需求完成。
### 1. 任务定义
- 用一句话写清用户问题、目标用户和期望结果;
- 写明本次包含内容和明确不包含内容;
- 确认是否属于个人品牌核心、配置包,或未来功能插件;
- 检查 PRD、ADR、数据模型和当前状态,记录冲突和假设。
产物:任务说明、范围边界、验收场景。
### 2. 方案边界
- 先定义领域对象、状态转换、权限边界和 API 契约;
- 涉及模板时,先定义声明、版本、安装快照、升级和回滚语义;
- 涉及数据时,先确定迁移兼容、旧数据默认值和恢复策略;
- 明确失败路径、空状态、重复提交和用户可见文案。
产物:必要时新增 ADR;否则在任务记录中写出数据、接口和 UI 方案。
### 3. 实现
- 先完成一个端到端的最小闭环;
- Controller、Service、DTO、API Client 和页面按既有边界分层;
- 任何新增 endpoint 必须同时新增授权测试和成功测试;
- 任何 schema 变更必须同时更新 migration、seed、运行时代码和测试;
- 不在实现过程中顺手扩大产品范围。
产物:可运行的代码、迁移和契约变更。
### 4. 验证
- API:未授权、错误角色、成功、业务校验失败和数据隔离;
- 数据:迁移可执行,旧数据可读,重复执行行为明确;
- UI:loading、empty、error、retry、success、mutation failure 和重复点击;
- 契约:API Client、DTO、响应 envelope 和页面调用一致;
- 运行匹配的 typecheck、integration tests、production build、format check。
产物:测试结果和剩余风险记录。
### 5. Code Review 收口
- 按用户场景重新走一遍,而不是只看 diff;
- 检查是否存在“已实现但未测试”的操作;
- 检查接口名称、产品文案和实际行为是否一致;
- 检查回滚、删除、升级等破坏性语义是否明确;
- 发现重复问题时,先更新本文件或 ADR,再开始下一项相关开发。
只有五个阶段都完成,且没有未解释的高风险项,才允许提交该里程碑。
+4
View File
@@ -0,0 +1,4 @@
VITE_APP_BASE_PATH=/admin/
VITE_API_BASE_URL=/api
VITE_DEV_API_TARGET=http://localhost:3001
ADMIN_PORT=3000
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>个人品牌后台</title>
</head>
<body>
<main id="app"></main>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+16 -2
View File
@@ -2,11 +2,25 @@
"name": "@personal-brand/admin",
"private": true,
"type": "module",
"dependencies": {
"@personal-brand/api-client": "workspace:*",
"@tanstack/react-query": "^5.103.1",
"antd": "^6.6.4",
"react": "^19.3.0",
"react-dom": "^19.3.0",
"react-router-dom": "^7.18.4"
},
"scripts": {
"build": "tsc -p tsconfig.json",
"dev": "tsc -p tsconfig.json --watch",
"build": "pnpm --filter @personal-brand/api-client build && vite build",
"dev": "pnpm --filter @personal-brand/api-client build && vite",
"lint": "eslint .",
"typecheck": "tsc -p tsconfig.json --noEmit",
"clean": "rimraf dist"
},
"devDependencies": {
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.1.1",
"vite": "^8.3.0"
}
}
@@ -0,0 +1,31 @@
import { Space, Typography } from "antd";
import type { ReactNode } from "react";
export function AdminPageHeader({
title,
description,
extra,
}: {
title: string;
description?: string;
extra?: ReactNode;
}) {
return (
<Space
align="start"
style={{ width: "100%", justifyContent: "space-between", marginBottom: 24 }}
>
<div>
<Typography.Title level={2} style={{ margin: 0 }}>
{title}
</Typography.Title>
{description && (
<Typography.Paragraph type="secondary" style={{ margin: "8px 0 0" }}>
{description}
</Typography.Paragraph>
)}
</div>
{extra}
</Space>
);
}
+47
View File
@@ -0,0 +1,47 @@
import { Alert, Button, Card, Empty, Result, Spin } from "antd";
import type { ReactNode } from "react";
export function QueryState({
loading,
error,
onRetry,
children,
}: {
loading?: boolean;
error?: unknown;
onRetry?: () => void;
children: ReactNode;
}) {
if (loading)
return (
<Card>
<Spin />
</Card>
);
if (error) {
return (
<Result
status="error"
title="内容加载失败"
subTitle={error instanceof Error ? error.message : "请检查 API 服务后重试"}
extra={onRetry ? <Button onClick={onRetry}>重新加载</Button> : undefined}
/>
);
}
return <>{children}</>;
}
export function EmptyState({ description }: { description: string }) {
return <Empty description={description} image={Empty.PRESENTED_IMAGE_SIMPLE} />;
}
export function MutationError({ error }: { error?: unknown }) {
if (!error) return null;
return (
<Alert
type="error"
showIcon
message={error instanceof Error ? error.message : "操作失败,请重试"}
/>
);
}
+169
View File
@@ -0,0 +1,169 @@
import { Button, Card, Col, Form, Input, Row, Select, Space, Tag, Typography, message } from "antd";
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 { MutationError, QueryState } from "../../components/QueryState.js";
export function BrandPage() {
const client = createApiClient();
const queryClient = useQueryClient();
const [form] = Form.useForm<BrandProfile>();
const brand = useQuery({ queryKey: ["admin-brand"], queryFn: () => client.getAdminBrand() });
const template = useQuery({
queryKey: ["template", brand.data?.templateKey],
queryFn: () => client.getPublicTemplate(brand.data!.templateKey),
enabled: Boolean(brand.data?.templateKey),
});
const save = useMutation({
mutationFn: (values: Partial<BrandProfile>) => client.updateAdminBrand(values),
onSuccess: () => {
message.success("品牌表达已保存");
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
},
});
return (
<QueryState loading={brand.isLoading} error={brand.error} onRetry={() => void brand.refetch()}>
{!brand.data ? null : (
<>
<AdminPageHeader
title="品牌表达"
description="先让访客理解你是谁、服务谁,以及为什么值得信任。"
extra={<Tag color="blue">{template.data?.name ?? "当前模板"}</Tag>}
/>
<Row gutter={[24, 24]} align="top">
<Col xs={24} xl={15}>
<Form
form={form}
layout="vertical"
initialValues={brand.data}
onFinish={(values) => save.mutate(values)}
>
<Card
title="我是谁"
extra={<Typography.Text type="secondary">公开展示</Typography.Text>}
>
<Form.Item
name="name"
label="品牌名称"
help="可以是个人姓名、工作室名称或品牌名。"
rules={[{ required: true, message: "请输入品牌名称" }]}
>
<Input size="large" placeholder="例如:林然|品牌顾问" />
</Form.Item>
<Form.Item
name="tagline"
label="一句话定位"
help="用一句话说明你为谁提供什么价值。"
rules={[{ required: true, message: "请输入一句话定位" }]}
>
<Input size="large" placeholder="例如:帮助独立创作者建立可信的个人品牌" />
</Form.Item>
<Form.Item name="description" label="品牌简介" help="介绍背景、方法和合作风格。">
<Input.TextArea
rows={5}
showCount
maxLength={500}
placeholder="让第一次认识你的人快速建立基本信任。"
/>
</Form.Item>
</Card>
<Card title="如何联系与合作" style={{ marginTop: 24 }}>
<Row gutter={16}>
<Col xs={24} md={12}>
<Form.Item name="hours" label="可联系时间">
<Input placeholder="例如:工作日 10:00–18:00" />
</Form.Item>
</Col>
<Col xs={24} md={12}>
<Form.Item name="address" label="所在位置">
<Input placeholder="城市或服务范围" />
</Form.Item>
</Col>
<Col xs={24} md={12}>
<Form.Item name="contactPhone" label="联系电话">
<Input />
</Form.Item>
</Col>
<Col xs={24} md={12}>
<Form.Item name="contactWechat" label="微信号">
<Input />
</Form.Item>
</Col>
</Row>
<Form.Item
name="deliveryNote"
label="合作预期"
help="说明响应时间、合作方式或重要边界。"
>
<Input.TextArea rows={3} placeholder="例如:收到咨询后 1 个工作日内回复。" />
</Form.Item>
</Card>
<Card title="模板与品牌视觉" style={{ marginTop: 24 }}>
<Form.Item
name="templateKey"
label="业务表达模板"
help="模板只改变业务表达,不改变个人品牌主线。"
>
<Select
disabled
options={[
{ value: "personal", label: "个人品牌" },
{ value: "food", label: "餐饮模板" },
]}
/>
</Form.Item>
<Row gutter={16}>
<Col xs={24} md={12}>
<Form.Item name="avatarUrl" label="头像 URL">
<Input />
</Form.Item>
</Col>
<Col xs={24} md={12}>
<Form.Item name="coverUrl" label="品牌封面 URL">
<Input />
</Form.Item>
</Col>
</Row>
</Card>
<Space direction="vertical" style={{ width: "100%", marginTop: 24 }}>
<MutationError error={save.error} />
<Button type="primary" htmlType="submit" loading={save.isPending} size="large">
保存品牌表达
</Button>
</Space>
</Form>
</Col>
<Col xs={24} xl={9}>
<Card title="公开表达预览" style={{ position: "sticky", top: 24 }}>
<Typography.Text type="secondary">小程序首页将优先使用以下信息</Typography.Text>
<Typography.Title level={3}>{brand.data.name || "品牌名称"}</Typography.Title>
<Typography.Title level={5}>{brand.data.tagline || "一句话定位"}</Typography.Title>
<Typography.Paragraph>
{brand.data.description || "品牌简介将在这里展示。"}
</Typography.Paragraph>
<Typography.Text strong>合作方式</Typography.Text>
<Typography.Paragraph type="secondary">
{brand.data.deliveryNote || "补充你的响应时间和合作预期。"}
</Typography.Paragraph>
<Space wrap>
{brand.data.contactPhone && <Tag>电话:{brand.data.contactPhone}</Tag>}
{brand.data.contactWechat && <Tag>微信:{brand.data.contactWechat}</Tag>}
{brand.data.hours && <Tag>时间:{brand.data.hours}</Tag>}
</Space>
</Card>
{template.data && (
<Card title="模板说明" style={{ marginTop: 24 }}>
<Typography.Paragraph>{template.data.description}</Typography.Paragraph>
<Typography.Text type="secondary">
服务分类:{template.data.serviceCategories.join("、")}
</Typography.Text>
</Card>
)}
</Col>
</Row>
</>
)}
</QueryState>
);
}
@@ -0,0 +1,257 @@
import {
Badge,
Button,
Card,
Descriptions,
Drawer,
Select,
Space,
Table,
Tag,
message,
Input,
} from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { AdminBooking, InquirySubmission } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import { useState } from "react";
const statuses = ["received", "contacting", "confirmed", "completed", "cancelled"] as const;
const labels: Record<string, string> = {
received: "待处理",
contacting: "沟通中",
confirmed: "已确认",
completed: "已完成",
cancelled: "已取消",
};
const inquiryStatuses = [
"new",
"reviewing",
"replied",
"qualified",
"converted",
"closed",
] as const;
const inquiryLabels: Record<string, string> = {
new: "新提交",
reviewing: "评估中",
replied: "已回复",
qualified: "已确认需求",
converted: "已转化",
closed: "已关闭",
};
export function InquiriesPage() {
const client = createApiClient();
const queryClient = useQueryClient();
const [status, setStatus] = useState<string>();
const [selectedId, setSelectedId] = useState<string>();
const query = useQuery({
queryKey: ["admin-bookings", status],
queryFn: () => client.listAdminBookings(status ? { status: status as never } : {}),
});
const update = useMutation({
mutationFn: ({ id, value }: { id: string; value: never }) =>
client.updateAdminBookingStatus(id, value),
onSuccess: () => {
message.success("咨询状态已更新");
void queryClient.invalidateQueries({ queryKey: ["admin-bookings"] });
},
});
const read = useMutation({
mutationFn: (id: string) => client.markAdminBookingRead(id),
onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["admin-bookings"] }),
});
const detail = useQuery({
queryKey: ["admin-booking", selectedId],
queryFn: () => client.getAdminBooking(selectedId!),
enabled: Boolean(selectedId),
});
const submissions = useQuery({
queryKey: ["admin-inquiry-submissions"],
queryFn: () => client.listAdminInquirySubmissions(),
});
const updateSubmission = useMutation({
mutationFn: ({
id,
status,
adminNote,
}: {
id: string;
status: InquirySubmission["status"];
adminNote?: string;
}) =>
client.updateAdminInquirySubmission(id, {
status,
...(adminNote === undefined ? {} : { adminNote }),
}),
onSuccess: () => {
message.success("咨询跟进已更新");
void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-submissions"] });
},
});
return (
<Card
title="咨询记录"
extra={
<Space>
<Select
allowClear
placeholder="全部状态"
style={{ width: 130 }}
value={status}
onChange={setStatus}
options={statuses.map((value) => ({ value, label: labels[value] }))}
/>
<Badge
count={
query.data?.filter((item) => !(item as AdminBooking & { isRead?: boolean }).isRead)
.length ?? 0
}
showZero
/>
</Space>
}
>
<Table
rowKey="id"
loading={query.isLoading}
dataSource={query.data ?? []}
columns={[
{
title: "编号",
dataIndex: "bookingNo",
render: (value: string, item: AdminBooking) => (
<Button type="link" onClick={() => setSelectedId(item.id)}>
{value}
</Button>
),
},
{ title: "联系人", dataIndex: "customerName" },
{
title: "提交时间",
dataIndex: "createdAt",
render: (value: string) => new Date(value).toLocaleString("zh-CN"),
},
{
title: "状态",
dataIndex: "status",
render: (value: string) => <Tag>{labels[value] ?? value}</Tag>,
},
{
title: "操作",
render: (_: unknown, item: AdminBooking) => (
<Space>
<Select
size="small"
value={item.status}
onChange={(value) => update.mutate({ id: item.id, value: value as never })}
options={statuses.map((value) => ({ value, label: labels[value] }))}
/>
<Button size="small" onClick={() => read.mutate(item.id)}>
标记已读
</Button>
</Space>
),
},
]}
/>
<Drawer
title="咨询详情"
open={Boolean(selectedId)}
onClose={() => setSelectedId(undefined)}
loading={detail.isLoading}
width={520}
>
{detail.data && (
<Descriptions column={1} bordered size="small">
<Descriptions.Item label="编号">{detail.data.bookingNo}</Descriptions.Item>
<Descriptions.Item label="联系人">{detail.data.customerName}</Descriptions.Item>
<Descriptions.Item label="状态">
{labels[detail.data.status] ?? detail.data.status}
</Descriptions.Item>
<Descriptions.Item label="提交时间">
{new Date(detail.data.createdAt).toLocaleString("zh-CN")}
</Descriptions.Item>
<Descriptions.Item label="管理员备注">
{detail.data.adminNote || "暂无"}
</Descriptions.Item>
</Descriptions>
)}
</Drawer>
<Card
title={`动态咨询提交${submissions.data ? `(${submissions.data.length})` : ""}`}
style={{ marginTop: 24 }}
extra={
<Button onClick={() => void submissions.refetch()} loading={submissions.isFetching}>
刷新提交记录
</Button>
}
>
{submissions.isError && (
<Card type="inner" style={{ marginBottom: 16 }}>
动态咨询提交加载失败:
{submissions.error instanceof Error ? submissions.error.message : "未知错误"}
</Card>
)}
<Table<InquirySubmission>
rowKey="id"
loading={submissions.isLoading}
dataSource={submissions.data ?? []}
columns={[
{ title: "表单", dataIndex: ["inquiryForm", "name"] },
{
title: "来源业务",
dataIndex: ["offering", "name"],
render: (value) => value || "品牌咨询",
},
{
title: "状态",
dataIndex: "status",
render: (value) => <Tag>{inquiryLabels[value] ?? value}</Tag>,
},
{ title: "版本", dataIndex: "formVersion", render: (value) => `v${value}` },
{
title: "提交时间",
dataIndex: "createdAt",
render: (value: string) => new Date(value).toLocaleString("zh-CN"),
},
{
title: "内容",
dataIndex: "values",
render: (value: Record<string, unknown>) => JSON.stringify(value),
},
{
title: "跟进",
render: (_: unknown, item: InquirySubmission) => (
<Space>
<Select
size="small"
value={item.status}
options={inquiryStatuses.map((value) => ({
value,
label: inquiryLabels[value],
}))}
onChange={(value) => updateSubmission.mutate({ id: item.id, status: value })}
/>
<Input
size="small"
placeholder="备注"
defaultValue={item.adminNote ?? ""}
onPressEnter={(event) =>
updateSubmission.mutate({
id: item.id,
status: item.status,
adminNote: event.currentTarget.value,
})
}
/>
</Space>
),
},
]}
/>
</Card>
</Card>
);
}
@@ -0,0 +1,120 @@
import { Card, Col, List, Row, Space, Statistic, Tag, Typography } from "antd";
import { useQueries } from "@tanstack/react-query";
import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { QueryState } from "../../components/QueryState.js";
export function OverviewPage() {
const client = createApiClient();
const results = useQueries({
queries: [
{ queryKey: ["admin-overview-brand"], queryFn: () => client.getAdminBrand() },
{ queryKey: ["admin-overview-workspace"], queryFn: () => client.getAdminWorkspace() },
{ queryKey: ["admin-overview-trust"], queryFn: () => client.listAdminTrustContent() },
{ queryKey: ["admin-overview-offerings"], queryFn: () => client.listAdminOfferings() },
{
queryKey: ["admin-overview-submissions"],
queryFn: () => client.listAdminInquirySubmissions(),
},
],
});
const loading = results.some((result) => result.isLoading);
const error = results.find((result) => result.isError)?.error;
const retry = () => results.forEach((result) => void result.refetch());
const brand = results[0].data;
const workspace = results[1].data as
{ inquiryForm?: { isEnabled?: boolean }; modules?: Array<{ isEnabled?: boolean }> } | undefined;
const trust = results[2].data;
const offerings = results[3].data as Array<{ isEnabled?: boolean }> | undefined;
const submissions = results[4].data;
const checklist = [
{ label: "品牌定位已填写", done: Boolean(brand?.name && brand.tagline) },
{ label: "信任内容已发布", done: Boolean(trust?.some((item) => item.isPublished)) },
{ label: "至少有一个公开业务提供项", done: Boolean(offerings?.some((item) => item.isEnabled)) },
{ label: "咨询入口已配置", done: Boolean(workspace?.inquiryForm?.isEnabled) },
];
return (
<QueryState loading={loading} error={error} onRetry={retry}>
<AdminPageHeader
title="品牌概览"
description="从这里检查品牌表达、信任内容和业务承接是否完整。"
/>
<Space direction="vertical" size={24} style={{ width: "100%" }}>
<Card>
<Typography.Title level={3} style={{ marginTop: 0 }}>
{brand?.name || "未命名品牌"}
</Typography.Title>
<Typography.Paragraph type="secondary">
{brand?.tagline || "还没有设置一句话定位"}
</Typography.Paragraph>
<Tag color="blue">
当前模板:{brand?.templateKey === "food" ? "餐饮模板" : "个人品牌"}
</Tag>
</Card>
<Row gutter={[16, 16]}>
<Col xs={24} sm={12} lg={6}>
<Card>
<Statistic
title="信任内容"
value={trust?.filter((item) => item.isPublished).length ?? 0}
suffix="条已发布"
/>
</Card>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card>
<Statistic
title="业务提供项"
value={offerings?.filter((item) => item.isEnabled).length ?? 0}
suffix="项公开"
/>
</Card>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card>
<Statistic title="咨询提交" value={submissions?.length ?? 0} suffix="条" />
</Card>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card>
<Statistic
title="工作空间模块"
value={workspace?.modules?.filter((item) => item.isEnabled).length ?? 0}
suffix="个启用"
/>
</Card>
</Col>
</Row>
<Row gutter={[16, 16]}>
<Col xs={24} lg={12}>
<Card title="品牌完整度">
<List
dataSource={checklist}
renderItem={(item) => (
<List.Item>
<Space>
<Tag color={item.done ? "success" : "default"}>
{item.done ? "已完成" : "待完善"}
</Tag>
<span>{item.label}</span>
</Space>
</List.Item>
)}
/>
</Card>
</Col>
<Col xs={24} lg={12}>
<Card title="下一步建议">
<Typography.Paragraph>
先完善品牌定位和信任证明,再配置业务提供项与咨询入口。所有内容发布前都应通过小程序预览确认。
</Typography.Paragraph>
<Typography.Paragraph type="secondary" style={{ marginBottom: 0 }}>
餐饮模板只是业务表达样例,品牌信任主线仍应优先维护。
</Typography.Paragraph>
</Card>
</Col>
</Row>
</Space>
</QueryState>
);
}
@@ -0,0 +1,275 @@
import {
Button,
Card,
Form,
Input,
Modal,
Select,
Space,
Table,
Tag,
Typography,
message,
} from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
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 { MutationError, QueryState } from "../../components/QueryState.js";
export function ServicesPage() {
const client = createApiClient();
const queryClient = useQueryClient();
const [offeringForm] = Form.useForm();
const [offeringOpen, setOfferingOpen] = useState(false);
const [editingOffering, setEditingOffering] = useState<Offering | null>(null);
const offerings = useQuery({
queryKey: ["admin-offerings"],
queryFn: () => client.listAdminOfferings(),
});
const saveOffering = useMutation({
mutationFn: (values: Record<string, unknown>) =>
editingOffering
? client.updateAdminOffering(editingOffering.id, values)
: client.createAdminOffering(values as Omit<Offering, "id" | "brandId">),
onSuccess: () => {
message.success("业务提供项已保存");
setOfferingOpen(false);
setEditingOffering(null);
offeringForm.resetFields();
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
},
});
const deleteOffering = useMutation({
mutationFn: (id: string) => client.deleteAdminOffering(id),
onSuccess: () => {
message.success("业务提供项已删除");
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
},
});
const toggleOffering = useMutation({
mutationFn: ({ id, isEnabled }: { id: string; isEnabled: boolean }) =>
client.updateAdminOffering(id, { isEnabled }),
onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] }),
});
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: "service", isEnabled: true, sortOrder: 0, sections: [], media: [], cta: {} },
);
};
return (
<QueryState
loading={offerings.isLoading}
error={offerings.error}
onRetry={() => {
void offerings.refetch();
}}
>
<AdminPageHeader
title="业务提供项"
description="管理你向外提供的服务、产品、套餐和合作项目,让访客清楚知道如何与你合作。"
extra={
<Button type="primary" onClick={() => beginOffering()}>
新增业务提供项
</Button>
}
/>
<Card title="公开业务提供项" extra={<Tag color="blue">小程序优先展示</Tag>}>
<Table
rowKey="id"
loading={offerings.isLoading}
dataSource={offerings.data ?? []}
columns={[
{ title: "名称", dataIndex: "name" },
{
title: "业务类型",
dataIndex: "kind",
render: (value) => (
<Tag>
{(
{
service: "服务",
product: "定制产品",
package: "套餐",
subscription: "订阅",
} as Record<string, string>
)[String(value)] ?? String(value)}
</Tag>
),
},
{ title: "价格", dataIndex: "priceText" },
{
title: "状态",
dataIndex: "isEnabled",
render: (value) => (value ? "已启用" : "已停用"),
},
{
title: "操作",
render: (_: unknown, item: Offering) => (
<Space>
<Button size="small" onClick={() => beginOffering(item)}>
编辑详情
</Button>
<Button
size="small"
onClick={() =>
toggleOffering.mutate({ id: item.id, isEnabled: !item.isEnabled })
}
>
{item.isEnabled ? "禁用" : "启用"}
</Button>
<Button danger size="small" onClick={() => deleteOffering.mutate(item.id)}>
删除
</Button>
</Space>
),
},
]}
/>
{offerings.data?.length === 0 && (
<Typography.Paragraph type="secondary">
还没有公开业务提供项。创建后,小程序服务页会优先读取这些内容。
</Typography.Paragraph>
)}
<MutationError error={saveOffering.error} />
</Card>
<Modal
open={offeringOpen}
title={editingOffering ? "编辑业务提供项" : "新增业务提供项"}
onCancel={() => {
setOfferingOpen(false);
setEditingOffering(null);
offeringForm.resetFields();
}}
onOk={() => offeringForm.submit()}
confirmLoading={saveOffering.isPending}
>
<Form
form={offeringForm}
layout="vertical"
onFinish={(values) => saveOffering.mutate(values as Record<string, unknown>)}
>
<Form.Item name="kind" label="类型" rules={[{ required: true }]}>
<Select
options={[
{ value: "service", label: "服务" },
{ value: "product", label: "定制产品" },
{ value: "package", label: "套餐" },
{ value: "subscription", label: "订阅" },
]}
/>
</Form.Item>
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="summary" label="一句话说明">
<Input />
</Form.Item>
<Form.Item name="description" label="详细介绍">
<Input.TextArea rows={5} />
</Form.Item>
<Form.Item name="priceText" label="价格展示">
<Input />
</Form.Item>
<Form.Item name="coverUrl" label="封面图片 URL">
<Input />
</Form.Item>
<Form.List name="sections">
{(fields, { add, remove }) => (
<>
<Form.Item label="内容分区">
<Button onClick={() => add({ type: "text" })}>新增分区</Button>
</Form.Item>
{fields.map(({ key, name, ...restField }) => (
<Space key={key} align="start" style={{ display: "flex", marginBottom: 8 }}>
<Form.Item {...restField} name={[name, "type"]}>
<Select
style={{ width: 120 }}
options={[
{ value: "text", label: "文本" },
{ value: "image-list", label: "图片列表" },
{ value: "timeline", label: "时间线" },
{ value: "faq", label: "常见问题" },
]}
/>
</Form.Item>
<Form.Item {...restField} name={[name, "title"]}>
<Input placeholder="分区标题" />
</Form.Item>
<Form.Item {...restField} name={[name, "content"]}>
<Input placeholder="分区内容" />
</Form.Item>
<Button danger onClick={() => remove(name)}>
删除
</Button>
</Space>
))}
</>
)}
</Form.List>
<Form.List name="media">
{(fields, { add, remove }) => (
<>
<Form.Item label="媒体列表">
<Button onClick={() => add({ type: "image" })}>新增媒体</Button>
</Form.Item>
{fields.map(({ key, name, ...restField }) => (
<Space key={key} align="start" style={{ display: "flex", marginBottom: 8 }}>
<Form.Item {...restField} name={[name, "url"]}>
<Input placeholder="图片 URL" />
</Form.Item>
<Form.Item {...restField} name={[name, "alt"]}>
<Input placeholder="替代文本" />
</Form.Item>
<Button danger onClick={() => remove(name)}>
删除
</Button>
</Space>
))}
</>
)}
</Form.List>
<Form.Item label="行动按钮">
<Space>
<Form.Item name={["cta", "type"]} noStyle>
<Select
style={{ width: 150 }}
allowClear
placeholder="按钮行为"
options={[
{ value: "inquiry", label: "提交咨询" },
{ value: "booking", label: "预约服务" },
{ value: "contact", label: "联系品牌" },
{ value: "external-link", label: "外部链接" },
]}
/>
</Form.Item>
<Form.Item name={["cta", "label"]} noStyle>
<Input placeholder="按钮文案" />
</Form.Item>
</Space>
</Form.Item>
<Form.Item name="isEnabled" label="公开状态">
<Select
options={[
{ value: true, label: "已启用" },
{ value: false, label: "已停用" },
]}
/>
</Form.Item>
</Form>
</Modal>
</QueryState>
);
}
@@ -0,0 +1,176 @@
import {
Button,
Card,
Form,
Input,
Modal,
Popconfirm,
Select,
Space,
Table,
Tag,
message,
} from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { TrustContent, TrustContentInput } from "@personal-brand/api-client";
import { useState } from "react";
import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { MutationError, QueryState } from "../../components/QueryState.js";
const types = [
{ value: "profile", label: "个人经历" },
{ value: "experience", label: "工作经验" },
{ value: "credential", label: "资历与证明" },
{ value: "portfolio", label: "案例与作品" },
{ value: "process", label: "合作流程" },
{ value: "testimonial", label: "客户反馈" },
];
export function TrustContentPage() {
const client = createApiClient();
const queryClient = useQueryClient();
const [editing, setEditing] = useState<TrustContent | null>(null);
const [open, setOpen] = useState(false);
const [form] = Form.useForm<TrustContentInput>();
const query = useQuery({
queryKey: ["trust-content"],
queryFn: () => client.listAdminTrustContent(),
});
const save = useMutation({
mutationFn: (values: TrustContentInput) =>
editing
? client.updateAdminTrustContent(editing.id, values)
: client.createAdminTrustContent(values),
onSuccess: () => {
message.success("信任内容已保存");
setOpen(false);
setEditing(null);
form.resetFields();
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
},
});
const remove = useMutation({
mutationFn: (id: string) => client.deleteAdminTrustContent(id),
onSuccess: () => {
message.success("内容已删除");
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
},
});
const begin = (item?: TrustContent) => {
setEditing(item ?? null);
setOpen(true);
form.setFieldsValue(
item
? {
type: item.type,
title: item.title,
...(item.summary ? { summary: item.summary } : {}),
content: item.content,
...(item.coverUrl ? { coverUrl: item.coverUrl } : {}),
isPublished: item.isPublished,
}
: { type: "profile", isPublished: false },
);
};
return (
<QueryState loading={query.isLoading} error={query.error} onRetry={() => void query.refetch()}>
<AdminPageHeader
title="信任内容"
description="用经历、案例、资历、流程和反馈,让访客知道为什么可以信任你。"
extra={
<Button type="primary" onClick={() => begin()}>
新增信任内容
</Button>
}
/>
<Card>
<Table
rowKey="id"
dataSource={query.data ?? []}
columns={[
{
title: "证据类型",
dataIndex: "type",
render: (value) => (
<Tag>{types.find((item) => item.value === value)?.label ?? value}</Tag>
),
},
{ title: "标题", dataIndex: "title" },
{
title: "摘要",
dataIndex: "summary",
render: (value) => (typeof value === "string" && value ? value : "未填写"),
},
{
title: "状态",
dataIndex: "isPublished",
render: (value) => (
<Tag color={value ? "success" : "default"}>{value ? "已公开" : "草稿"}</Tag>
),
},
{
title: "操作",
render: (_: unknown, item: TrustContent) => (
<Space>
<Button size="small" onClick={() => begin(item)}>
编辑
</Button>
<Popconfirm
title="确认删除这条信任内容?"
description="删除后小程序将不再展示。"
onConfirm={() => remove.mutate(item.id)}
>
<Button size="small" danger loading={remove.isPending}>
删除
</Button>
</Popconfirm>
</Space>
),
},
]}
/>
<MutationError error={remove.error} />
</Card>
<Modal
open={open}
title={editing ? "编辑信任内容" : "新增信任内容"}
onCancel={() => {
setOpen(false);
setEditing(null);
form.resetFields();
}}
onOk={() => form.submit()}
confirmLoading={save.isPending}
destroyOnClose
>
<Form form={form} layout="vertical" onFinish={(values) => save.mutate(values)}>
<Form.Item name="type" label="证据类型" rules={[{ required: true }]}>
<Select options={types} />
</Form.Item>
<Form.Item name="title" label="标题" rules={[{ required: true }]}>
<Input placeholder="例如:服务过 30+ 位独立创作者" />
</Form.Item>
<Form.Item name="summary" label="摘要">
<Input />
</Form.Item>
<Form.Item name="content" label="详细内容" rules={[{ required: true }]}>
<Input.TextArea rows={8} showCount maxLength={2000} />
</Form.Item>
<Form.Item name="coverUrl" label="封面图片 URL">
<Input />
</Form.Item>
<Form.Item name="isPublished" label="公开状态">
<Select
options={[
{ value: true, label: "立即公开" },
{ value: false, label: "保存为草稿" },
]}
/>
</Form.Item>
<MutationError error={save.error} />
</Form>
</Modal>
</QueryState>
);
}
@@ -0,0 +1,413 @@
import {
Button,
Card,
Form,
Input,
Modal,
Select,
Space,
Table,
Tag,
Typography,
message,
} from "antd";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { createApiClient } from "../../lib/api.js";
import { ApiClientError } from "@personal-brand/api-client";
import type { BrandFieldDefinition, BrandModule } from "@personal-brand/api-client";
import { useState } from "react";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { MutationError } from "../../components/QueryState.js";
export function WorkspacePage() {
const client = createApiClient();
const queryClient = useQueryClient();
const [fieldOpen, setFieldOpen] = useState(false);
const [formOpen, setFormOpen] = useState(false);
const [form] = Form.useForm<Record<string, unknown>>();
const [inquiryForm] = Form.useForm<Record<string, unknown>>();
const query = useQuery({
queryKey: ["admin-workspace"],
queryFn: () => client.getAdminWorkspace(),
});
const install = useMutation({
mutationFn: (key: "personal" | "food") => client.installAdminTemplate(key),
onSuccess: () => {
message.success("模板已安装");
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
},
});
const updateModule = useMutation({
mutationFn: ({ id, body }: { id: string; body: Partial<BrandModule> }) =>
client.updateAdminModule(id, body),
onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }),
});
const createField = useMutation({
mutationFn: (values: Omit<BrandFieldDefinition, "id" | "source">) =>
client.createAdminField(values),
onSuccess: () => {
message.success("字段已创建");
setFieldOpen(false);
form.resetFields();
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
},
});
const removeField = useMutation({
mutationFn: (id: string) => client.deleteAdminField(id),
onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }),
});
const forms = useQuery({
queryKey: ["admin-inquiry-forms"],
queryFn: () => client.listAdminInquiryForms(),
});
const templatePreview = useQuery({
queryKey: ["admin-template-preview"],
queryFn: () => client.getAdminTemplateUpgradePreview(),
enabled: Boolean(query.data?.installations?.length),
});
const upgrade = useMutation({
mutationFn: () => client.upgradeAdminTemplate(),
onSuccess: () => {
message.success("模板已升级,已有内容未被覆盖");
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] });
},
});
const rollback = useMutation({
mutationFn: () => client.rollbackAdminTemplate(),
onSuccess: () => {
message.success("模板版本已回滚,现有内容未删除");
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] });
},
});
const createForm = useMutation({
mutationFn: (values: { name: string; fieldsSnapshot: unknown[] }) =>
client.createAdminInquiryForm(values),
onSuccess: () => {
message.success("咨询表单已创建");
setFormOpen(false);
inquiryForm.resetFields();
void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-forms"] });
},
});
if (query.isLoading) return <Card loading />;
if (query.isError || !query.data) {
const errorStatus =
query.error instanceof ApiClientError
? query.error.status
: (query.error as { status?: number } | null)?.status;
const expired = errorStatus === 401;
return (
<Card
title={expired ? "登录状态已失效" : "工作空间加载失败"}
extra={
expired ? (
<Button
type="primary"
onClick={() => window.dispatchEvent(new Event("admin-auth-expired"))}
>
重新登录
</Button>
) : (
<Button onClick={() => void query.refetch()}>重新请求</Button>
)
}
>
{expired
? "请重新登录后再访问工作空间。"
: query.error instanceof Error
? query.error.message
: "请检查 API 服务后刷新重试。"}
</Card>
);
}
const { modules, fields, installations } = query.data;
return (
<Space direction="vertical" size="large" style={{ width: "100%" }}>
<AdminPageHeader
title="模板与设置"
description="用行业模板组织业务表达,同时保留个人品牌定位、信任内容和合作方式的长期扩展空间。"
/>
<Card
title="行业模板"
extra={
<Space>
<Button onClick={() => install.mutate("personal")} loading={install.isPending}>
安装个人品牌模板
</Button>
<Button onClick={() => install.mutate("food")} loading={install.isPending}>
安装餐饮模板
</Button>
</Space>
}
>
<Typography.Paragraph type="secondary">
模板只提供行业表达样例,不会替代你的品牌定位、经历、作品和合作方式。
</Typography.Paragraph>
<Tag>{installations.length ? `已安装 ${installations.length} 个模板` : "尚未安装模板"}</Tag>
{installations.length > 0 && (
<Card size="small" style={{ marginTop: 16 }} title="模板版本">
<Space direction="vertical" style={{ width: "100%" }}>
<Typography.Text>
当前版本:{templatePreview.data?.currentVersion ?? "加载中"},最新版本:
{templatePreview.data?.latestVersion ?? "加载中"}
</Typography.Text>
{templatePreview.data?.canUpgrade ? (
<>
<Typography.Paragraph type="secondary" style={{ marginBottom: 0 }}>
可升级内容:新增 {templatePreview.data.missingModules.length} 个模块,新增{" "}
{templatePreview.data.missingFields.length} 个字段。已有内容不会被覆盖。
</Typography.Paragraph>
<Button
type="primary"
onClick={() => upgrade.mutate()}
loading={upgrade.isPending}
>
确认升级模板
</Button>
</>
) : (
<Tag color="green">已是最新版本</Tag>
)}
{templatePreview.data?.canRollback && (
<Button danger onClick={() => rollback.mutate()} loading={rollback.isPending}>
恢复上一版配置基线
</Button>
)}
<MutationError error={templatePreview.error} />
<MutationError error={upgrade.error} />
<MutationError error={rollback.error} />
</Space>
</Card>
)}
<MutationError error={install.error} />
</Card>
<Card
title="动态咨询表单"
extra={
<Button type="primary" onClick={() => setFormOpen(true)}>
新增表单
</Button>
}
>
<Table
rowKey="id"
loading={forms.isLoading}
dataSource={forms.data ?? []}
columns={[
{ title: "名称", dataIndex: "name" },
{ title: "版本", dataIndex: "version", render: (value) => <Tag>v{value}</Tag> },
{
title: "字段数",
dataIndex: "fieldsSnapshot",
render: (value: unknown[]) => value?.length ?? 0,
},
{ title: "状态", dataIndex: "isEnabled", render: (value) => (value ? "启用" : "停用") },
]}
/>
<MutationError error={createForm.error} />
</Card>
<Card title="页面模块">
<Table
rowKey="id"
dataSource={modules}
columns={[
{ title: "模块", dataIndex: "title" },
{ title: "类型", dataIndex: "type", render: (value) => <Tag>{value}</Tag> },
{ title: "来源", dataIndex: "source" },
{
title: "状态",
dataIndex: "isEnabled",
render: (value, item: BrandModule) => (
<Select
size="small"
value={Boolean(value)}
onChange={(next) =>
updateModule.mutate({ id: item.id, body: { isEnabled: Boolean(next) } })
}
options={[
{ value: true, label: "启用" },
{ value: false, label: "停用" },
]}
/>
),
},
{
title: "排序",
dataIndex: "sortOrder",
render: (value, item: BrandModule) => (
<Input
size="small"
type="number"
defaultValue={Number(value)}
onBlur={(event) =>
updateModule.mutate({
id: item.id,
body: { sortOrder: Number(event.target.value) },
})
}
/>
),
},
]}
/>
<MutationError error={updateModule.error} />
</Card>
<Card
title="自定义字段"
extra={
<Button type="primary" onClick={() => setFieldOpen(true)}>
新增字段
</Button>
}
>
<Table
rowKey="id"
dataSource={fields.filter((item) => item.source === "custom")}
columns={[
{ title: "字段", dataIndex: "label" },
{ title: "Key", dataIndex: "key" },
{ title: "作用域", dataIndex: "scope" },
{ title: "类型", dataIndex: "type" },
{
title: "操作",
render: (_: unknown, item: BrandFieldDefinition) => (
<Button danger size="small" onClick={() => removeField.mutate(item.id)}>
删除
</Button>
),
},
]}
/>
<MutationError error={createField.error} />
<MutationError error={removeField.error} />
</Card>
<Modal
open={fieldOpen}
title="新增自定义字段"
onCancel={() => {
setFieldOpen(false);
form.resetFields();
}}
onOk={() => form.submit()}
confirmLoading={createField.isPending}
>
<Form
form={form}
layout="vertical"
onFinish={(values) =>
createField.mutate({
...values,
required: Boolean(values.required),
isVisible: true,
sortOrder: 99,
} as Omit<BrandFieldDefinition, "id" | "source">)
}
>
<Form.Item name="scope" label="作用域" rules={[{ required: true }]}>
<Select
options={[
{ value: "profile", label: "品牌资料" },
{ value: "service", label: "服务" },
{ value: "inquiry", label: "咨询表单" },
]}
/>
</Form.Item>
<Form.Item name="key" label="字段 Key" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="label" label="显示名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="type" label="字段类型" rules={[{ required: true }]}>
<Select
options={[
"text",
"textarea",
"number",
"date",
"select",
"multi-select",
"image",
"url",
"phone",
].map((value) => ({ value, label: value }))}
/>
</Form.Item>
<Form.Item name="required" label="是否必填">
<Select
options={[
{ value: true, label: "是" },
{ value: false, label: "否" },
]}
/>
</Form.Item>
</Form>
</Modal>
<Modal
open={formOpen}
title="新增动态咨询表单"
onCancel={() => {
setFormOpen(false);
inquiryForm.resetFields();
}}
onOk={() => inquiryForm.submit()}
confirmLoading={createForm.isPending}
>
<Form
form={inquiryForm}
layout="vertical"
onFinish={(values) =>
createForm.mutate({
name: typeof values.name === "string" ? values.name : "",
fieldsSnapshot: Array.isArray(values.fieldsSnapshot) ? values.fieldsSnapshot : [],
})
}
>
<Form.Item name="name" label="表单名称" rules={[{ required: true }]}>
<Input placeholder="例如:合作咨询" />
</Form.Item>
<Form.List name="fieldsSnapshot">
{(fields, { add, remove }) => (
<>
<Form.Item label="表单字段">
<Button onClick={() => add({ type: "text", required: false })}>新增字段</Button>
</Form.Item>
{fields.map(({ key, name, ...restField }) => (
<Space key={key} align="start" style={{ display: "flex", marginBottom: 8 }}>
<Form.Item {...restField} name={[name, "key"]} rules={[{ required: true }]}>
<Input placeholder="Key" />
</Form.Item>
<Form.Item {...restField} name={[name, "label"]} rules={[{ required: true }]}>
<Input placeholder="字段名称" />
</Form.Item>
<Form.Item {...restField} name={[name, "type"]}>
<Select
style={{ width: 120 }}
options={[
"text",
"textarea",
"number",
"date",
"select",
"multi-select",
"image",
"url",
"phone",
].map((value) => ({ value, label: value }))}
/>
</Form.Item>
<Button danger onClick={() => remove(name)}>
删除
</Button>
</Space>
))}
</>
)}
</Form.List>
</Form>
</Modal>
</Space>
);
}
+22
View File
@@ -0,0 +1,22 @@
import { ApiClient } from "@personal-brand/api-client";
export const apiBaseUrl = import.meta.env.VITE_API_BASE_URL ?? "/api";
export async function authenticatedFetch(
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> {
const response = await fetch(input, init);
if (response.status === 401) {
localStorage.removeItem("adminToken");
window.dispatchEvent(new Event("admin-auth-expired"));
}
return response;
}
export function createApiClient(): ApiClient {
const token = localStorage.getItem("adminToken");
return new ApiClient({
baseUrl: apiBaseUrl,
...(token ? { token } : {}),
fetcher: authenticatedFetch,
});
}
-1
View File
@@ -1 +0,0 @@
export const adminAppName = "personal-brand-admin";
+155
View File
@@ -0,0 +1,155 @@
import React, { Suspense, useState } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { App, Button, Card, Form, Input, Layout, Menu, Space, Typography, message } from "antd";
import { createApiClient } from "./lib/api.js";
const FeatureInquiriesPage = React.lazy(() =>
import("./features/inquiries/InquiriesPage.js").then((module) => ({
default: module.InquiriesPage,
})),
);
const FeatureTrustContentPage = React.lazy(() =>
import("./features/trust-content/TrustContentPage.js").then((module) => ({
default: module.TrustContentPage,
})),
);
const FeatureServicesPage = React.lazy(() =>
import("./features/services/ServicesPage.js").then((module) => ({
default: module.ServicesPage,
})),
);
const FeatureBrandPage = React.lazy(() =>
import("./features/brand/BrandPage.js").then((module) => ({ default: module.BrandPage })),
);
const FeatureWorkspacePage = React.lazy(() =>
import("./features/workspace/WorkspacePage.js").then((module) => ({
default: module.WorkspacePage,
})),
);
const FeatureOverviewPage = React.lazy(() =>
import("./features/overview/OverviewPage.js").then((module) => ({
default: module.OverviewPage,
})),
);
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 }) {
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
async function submit(values: { username: string; password: string }) {
setLoading(true);
try {
const result = await api().loginAdmin(values.username, values.password);
localStorage.setItem("adminToken", result.token);
onLogin();
} catch (error) {
message.error(error instanceof Error ? error.message : "登录失败");
} finally {
setLoading(false);
}
}
return (
<Card title="个人品牌后台" style={{ maxWidth: 420, margin: "120px auto" }}>
<Form form={form} layout="vertical" onFinish={submit}>
<Form.Item name="username" label="账号" initialValue="admin" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="password" label="密码" rules={[{ required: true }]}>
<Input.Password />
</Form.Item>
<Button type="primary" htmlType="submit" loading={loading} block>
登录
</Button>
</Form>
</Card>
);
}
function Dashboard({ onLogout }: { onLogout: () => void }) {
const navigate = useNavigate();
const location = useLocation();
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: "inquiries", label: "咨询记录" },
];
return (
<Layout style={{ minHeight: "100vh" }}>
<Layout.Sider>
<Typography.Title level={4} style={{ color: "white", padding: 20 }}>
个人品牌
</Typography.Title>
<Menu
theme="dark"
selectedKeys={[page]}
onClick={({ key }) => navigate(`/admin/${key}`)}
items={items}
/>
</Layout.Sider>
<Layout>
<Layout.Header
style={{
background: "white",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Space>品牌管理后台</Space>
<Button type="text" onClick={onLogout}>
退出登录
</Button>
</Layout.Header>
<Layout.Content style={{ padding: 24 }}>
<Suspense fallback={<Card loading />}>
<Routes>
<Route path="/admin/overview" element={<FeatureOverviewPage />} />
<Route path="/admin/brand" element={<FeatureBrandPage />} />
<Route path="/admin/workspace" element={<FeatureWorkspacePage />} />
<Route path="/admin/trust" element={<FeatureTrustContentPage />} />
<Route path="/admin/services" element={<FeatureServicesPage />} />
<Route path="/admin/inquiries" element={<FeatureInquiriesPage />} />
<Route path="*" element={<Navigate to="/admin/overview" replace />} />
</Routes>
</Suspense>
</Layout.Content>
</Layout>
</Layout>
);
}
function Root() {
const [loggedIn, setLoggedIn] = useState(Boolean(localStorage.getItem("adminToken")));
React.useEffect(() => {
const expire = () => {
message.warning("登录状态已失效,请重新登录");
setLoggedIn(false);
};
window.addEventListener("admin-auth-expired", expire);
return () => window.removeEventListener("admin-auth-expired", expire);
}, []);
const logout = () => {
localStorage.removeItem("adminToken");
setLoggedIn(false);
};
return loggedIn ? <Dashboard onLogout={logout} /> : <Login onLogin={() => setLoggedIn(true)} />;
}
createRoot(document.getElementById("app")!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App>
<BrowserRouter>
<Root />
</BrowserRouter>
</App>
</QueryClientProvider>
</React.StrictMode>,
);
+8
View File
@@ -0,0 +1,8 @@
interface ImportMetaEnv {
readonly VITE_API_BASE_URL?: string;
readonly VITE_APP_BASE_PATH?: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
+10 -2
View File
@@ -1,5 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": { "outDir": "dist", "rootDir": "src", "lib": ["ES2022", "DOM"] },
"include": ["src/**/*.ts"]
"compilerOptions": {
"outDir": "dist",
"rootDir": "src",
"lib": ["ES2022", "DOM"],
"jsx": "react-jsx",
"module": "ESNext",
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true
},
"include": ["src/**/*.ts", "src/**/*.tsx"]
}
+18
View File
@@ -0,0 +1,18 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
base: process.env.VITE_APP_BASE_PATH ?? "/",
server: {
host: "0.0.0.0",
port: Number(process.env.ADMIN_PORT ?? 3000),
proxy: {
"/api": {
target: process.env.VITE_DEV_API_TARGET ?? "http://localhost:3001",
rewrite: (path) => path.replace(/^\/api/, ""),
},
},
},
build: { outDir: "dist" },
});
+5 -1
View File
@@ -4,9 +4,11 @@
"type": "module",
"scripts": {
"build": "tsc -p tsconfig.json",
"dev": "tsx watch src/main.ts",
"dev": "pnpm build && node --env-file=.env dist/main.js",
"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",
"clean": "rimraf dist",
"start": "node dist/main.js",
"db:generate": "prisma generate",
@@ -18,6 +20,8 @@
"@nestjs/common": "^11.0.11",
"@nestjs/core": "^11.0.11",
"@nestjs/platform-fastify": "^11.0.11",
"@personal-brand/config": "workspace:^",
"@personal-brand/validation": "workspace:^",
"@prisma/client": "^6.2.1",
"bcryptjs": "^2.4.3",
"class-transformer": "^0.5.1",
@@ -0,0 +1,187 @@
-- CreateEnum
CREATE TYPE "BookingStatus" AS ENUM ('received', 'contacting', 'confirmed', 'completed', 'cancelled');
-- CreateEnum
CREATE TYPE "BookingRequestType" AS ENUM ('package', 'private_chef');
-- CreateEnum
CREATE TYPE "ContactPreference" AS ENUM ('wechat', 'phone', 'none');
-- CreateEnum
CREATE TYPE "FulfillmentType" AS ENUM ('pickup', 'delivery');
-- CreateTable
CREATE TABLE "BrandProfile" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"tagline" TEXT,
"description" TEXT,
"avatarUrl" TEXT,
"coverUrl" TEXT,
"hours" TEXT,
"address" TEXT,
"deliveryNote" TEXT,
"contactPhone" TEXT,
"contactWechat" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "BrandProfile_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Service" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT NOT NULL,
"coverUrl" TEXT,
"priceText" TEXT,
"priceAmount" INTEGER,
"bookingEnabled" BOOLEAN NOT NULL DEFAULT true,
"isEnabled" BOOLEAN NOT NULL DEFAULT true,
"sortOrder" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Service_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "CustomerUser" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"openid" TEXT NOT NULL,
"lastLoginAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "CustomerUser_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Booking" (
"id" TEXT NOT NULL,
"bookingNo" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"customerUserId" TEXT NOT NULL,
"requestType" "BookingRequestType" NOT NULL,
"customerName" TEXT NOT NULL,
"phone" TEXT,
"wechatId" TEXT,
"contactPreference" "ContactPreference" NOT NULL,
"fulfillmentType" "FulfillmentType",
"serviceId" TEXT,
"requestedDate" TIMESTAMP(3),
"requestedTime" TEXT,
"deliveryAddress" TEXT,
"estimatedAmount" INTEGER,
"extraData" JSONB,
"note" TEXT,
"adminNote" TEXT,
"status" "BookingStatus" NOT NULL DEFAULT 'received',
"isRead" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Booking_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BookingItem" (
"id" TEXT NOT NULL,
"bookingId" TEXT NOT NULL,
"serviceId" TEXT,
"serviceNameSnapshot" TEXT NOT NULL,
"unitPriceSnapshot" INTEGER NOT NULL,
"quantity" INTEGER NOT NULL,
"subtotalSnapshot" INTEGER NOT NULL,
CONSTRAINT "BookingItem_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Tag" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"isPreset" BOOLEAN NOT NULL DEFAULT false,
"isEnabled" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Tag_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "AdminUser" (
"id" TEXT NOT NULL,
"username" TEXT NOT NULL,
"passwordHash" TEXT NOT NULL,
"displayName" TEXT NOT NULL,
"role" TEXT NOT NULL DEFAULT 'admin',
"isEnabled" BOOLEAN NOT NULL DEFAULT true,
"lastLoginAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "AdminUser_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BookingTag" (
"bookingId" TEXT NOT NULL,
"tagId" TEXT NOT NULL,
CONSTRAINT "BookingTag_pkey" PRIMARY KEY ("bookingId","tagId")
);
-- CreateIndex
CREATE INDEX "Service_brandId_isEnabled_sortOrder_idx" ON "Service"("brandId", "isEnabled", "sortOrder");
-- CreateIndex
CREATE UNIQUE INDEX "CustomerUser_brandId_openid_key" ON "CustomerUser"("brandId", "openid");
-- CreateIndex
CREATE UNIQUE INDEX "Booking_bookingNo_key" ON "Booking"("bookingNo");
-- CreateIndex
CREATE INDEX "Booking_brandId_status_createdAt_idx" ON "Booking"("brandId", "status", "createdAt");
-- CreateIndex
CREATE INDEX "Booking_customerUserId_createdAt_idx" ON "Booking"("customerUserId", "createdAt");
-- CreateIndex
CREATE UNIQUE INDEX "Tag_brandId_name_key" ON "Tag"("brandId", "name");
-- CreateIndex
CREATE UNIQUE INDEX "AdminUser_username_key" ON "AdminUser"("username");
-- AddForeignKey
ALTER TABLE "Service" ADD CONSTRAINT "Service_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CustomerUser" ADD CONSTRAINT "CustomerUser_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Booking" ADD CONSTRAINT "Booking_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Booking" ADD CONSTRAINT "Booking_customerUserId_fkey" FOREIGN KEY ("customerUserId") REFERENCES "CustomerUser"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Booking" ADD CONSTRAINT "Booking_serviceId_fkey" FOREIGN KEY ("serviceId") REFERENCES "Service"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BookingItem" ADD CONSTRAINT "BookingItem_bookingId_fkey" FOREIGN KEY ("bookingId") REFERENCES "Booking"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BookingItem" ADD CONSTRAINT "BookingItem_serviceId_fkey" FOREIGN KEY ("serviceId") REFERENCES "Service"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Tag" ADD CONSTRAINT "Tag_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BookingTag" ADD CONSTRAINT "BookingTag_bookingId_fkey" FOREIGN KEY ("bookingId") REFERENCES "Booking"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BookingTag" ADD CONSTRAINT "BookingTag_tagId_fkey" FOREIGN KEY ("tagId") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,2 @@
-- Prevent duplicate service names within one brand.
CREATE UNIQUE INDEX "Service_brandId_name_key" ON "Service"("brandId", "name");
@@ -0,0 +1 @@
ALTER TABLE "BrandProfile" ADD COLUMN "templateKey" TEXT NOT NULL DEFAULT 'food';
@@ -0,0 +1 @@
ALTER TYPE "BookingRequestType" ADD VALUE 'inquiry';
@@ -0,0 +1,2 @@
ALTER TABLE "Service" ADD COLUMN "categoryKey" TEXT NOT NULL DEFAULT 'standard';
ALTER TABLE "Service" ADD COLUMN "config" JSONB;
@@ -0,0 +1,2 @@
CREATE TABLE "TrustContent" ("id" TEXT NOT NULL,"brandId" TEXT NOT NULL,"type" TEXT NOT NULL,"title" TEXT NOT NULL,"summary" TEXT,"content" TEXT NOT NULL,"coverUrl" TEXT,"sortOrder" INTEGER NOT NULL DEFAULT 0,"isPublished" BOOLEAN NOT NULL DEFAULT true,"config" JSONB,"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,"updatedAt" TIMESTAMP(3) NOT NULL,CONSTRAINT "TrustContent_pkey" PRIMARY KEY ("id"),CONSTRAINT "TrustContent_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE CASCADE ON UPDATE CASCADE);
CREATE INDEX "TrustContent_brandId_type_sortOrder_idx" ON "TrustContent"("brandId","type","sortOrder");
@@ -0,0 +1,157 @@
-- AlterTable
ALTER TABLE "Service" ADD COLUMN "offeringId" TEXT;
-- CreateTable
CREATE TABLE "BrandTemplateInstallation" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"templateKey" TEXT NOT NULL,
"templateVersion" TEXT NOT NULL DEFAULT '1.0.0',
"installedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "BrandTemplateInstallation_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BrandModule" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"type" TEXT NOT NULL,
"title" TEXT NOT NULL,
"isEnabled" BOOLEAN NOT NULL DEFAULT true,
"sortOrder" INTEGER NOT NULL DEFAULT 0,
"source" TEXT NOT NULL DEFAULT 'core',
"config" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "BrandModule_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BrandFieldDefinition" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"scope" TEXT NOT NULL,
"key" TEXT NOT NULL,
"label" TEXT NOT NULL,
"type" TEXT NOT NULL,
"required" BOOLEAN NOT NULL DEFAULT false,
"isVisible" BOOLEAN NOT NULL DEFAULT true,
"sortOrder" INTEGER NOT NULL DEFAULT 0,
"source" TEXT NOT NULL DEFAULT 'custom',
"isOverridden" BOOLEAN NOT NULL DEFAULT false,
"options" JSONB,
"visibleWhen" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "BrandFieldDefinition_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Offering" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"kind" TEXT NOT NULL DEFAULT 'service',
"name" TEXT NOT NULL,
"summary" TEXT,
"description" TEXT,
"coverUrl" TEXT,
"priceText" TEXT,
"priceAmount" INTEGER,
"isEnabled" BOOLEAN NOT NULL DEFAULT true,
"sortOrder" INTEGER NOT NULL DEFAULT 0,
"config" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Offering_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "InquiryForm" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"offeringId" TEXT,
"name" TEXT NOT NULL,
"version" INTEGER NOT NULL DEFAULT 1,
"isEnabled" BOOLEAN NOT NULL DEFAULT true,
"fieldsSnapshot" JSONB NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "InquiryForm_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "InquirySubmission" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"inquiryFormId" TEXT NOT NULL,
"formVersion" INTEGER NOT NULL,
"fieldsSnapshot" JSONB NOT NULL,
"values" JSONB NOT NULL,
"activeFields" JSONB NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "InquirySubmission_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "BrandTemplateInstallation_brandId_idx" ON "BrandTemplateInstallation"("brandId");
-- CreateIndex
CREATE UNIQUE INDEX "BrandTemplateInstallation_brandId_templateKey_key" ON "BrandTemplateInstallation"("brandId", "templateKey");
-- CreateIndex
CREATE INDEX "BrandModule_brandId_isEnabled_sortOrder_idx" ON "BrandModule"("brandId", "isEnabled", "sortOrder");
-- CreateIndex
CREATE INDEX "BrandFieldDefinition_brandId_scope_sortOrder_idx" ON "BrandFieldDefinition"("brandId", "scope", "sortOrder");
-- CreateIndex
CREATE UNIQUE INDEX "BrandFieldDefinition_brandId_scope_key_key" ON "BrandFieldDefinition"("brandId", "scope", "key");
-- CreateIndex
CREATE INDEX "Offering_brandId_isEnabled_sortOrder_idx" ON "Offering"("brandId", "isEnabled", "sortOrder");
-- CreateIndex
CREATE UNIQUE INDEX "Offering_brandId_name_key" ON "Offering"("brandId", "name");
-- CreateIndex
CREATE INDEX "InquiryForm_brandId_isEnabled_idx" ON "InquiryForm"("brandId", "isEnabled");
-- CreateIndex
CREATE INDEX "InquirySubmission_brandId_createdAt_idx" ON "InquirySubmission"("brandId", "createdAt");
-- CreateIndex
CREATE INDEX "InquirySubmission_inquiryFormId_formVersion_idx" ON "InquirySubmission"("inquiryFormId", "formVersion");
-- AddForeignKey
ALTER TABLE "Service" ADD CONSTRAINT "Service_offeringId_fkey" FOREIGN KEY ("offeringId") REFERENCES "Offering"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BrandTemplateInstallation" ADD CONSTRAINT "BrandTemplateInstallation_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BrandModule" ADD CONSTRAINT "BrandModule_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BrandFieldDefinition" ADD CONSTRAINT "BrandFieldDefinition_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Offering" ADD CONSTRAINT "Offering_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "InquiryForm" ADD CONSTRAINT "InquiryForm_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "InquiryForm" ADD CONSTRAINT "InquiryForm_offeringId_fkey" FOREIGN KEY ("offeringId") REFERENCES "Offering"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "InquirySubmission" ADD CONSTRAINT "InquirySubmission_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "InquirySubmission" ADD CONSTRAINT "InquirySubmission_inquiryFormId_fkey" FOREIGN KEY ("inquiryFormId") REFERENCES "InquiryForm"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1 @@
ALTER TABLE "BrandTemplateInstallation" ADD COLUMN "configSnapshot" JSONB NOT NULL DEFAULT '{}';
@@ -0,0 +1 @@
ALTER TABLE "BrandTemplateInstallation" ADD COLUMN "previousSnapshots" JSONB NOT NULL DEFAULT '[]';
@@ -0,0 +1,20 @@
ALTER TABLE "Booking" ADD COLUMN "offeringId" TEXT;
ALTER TABLE "BookingItem" ADD COLUMN "offeringId" TEXT;
UPDATE "Booking" b
SET "offeringId" = s."offeringId"
FROM "Service" s
WHERE b."serviceId" = s."id" AND s."offeringId" IS NOT NULL;
UPDATE "BookingItem" bi
SET "offeringId" = s."offeringId"
FROM "Service" s
WHERE bi."serviceId" = s."id" AND s."offeringId" IS NOT NULL;
ALTER TABLE "Booking" ADD CONSTRAINT "Booking_offeringId_fkey"
FOREIGN KEY ("offeringId") REFERENCES "Offering"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "BookingItem" ADD CONSTRAINT "BookingItem_offeringId_fkey"
FOREIGN KEY ("offeringId") REFERENCES "Offering"("id") ON DELETE SET NULL ON UPDATE CASCADE;
CREATE INDEX "Booking_brandId_offeringId_idx" ON "Booking"("brandId", "offeringId");
CREATE INDEX "BookingItem_offeringId_idx" ON "BookingItem"("offeringId");
@@ -0,0 +1,11 @@
ALTER TABLE "BrandProfile" ADD COLUMN "config" JSONB;
UPDATE "BrandProfile"
SET "config" = jsonb_strip_nulls(jsonb_build_object(
'legacyIndustryFields', jsonb_strip_nulls(jsonb_build_object(
'hours', "hours",
'address', "address",
'deliveryNote', "deliveryNote"
))
))
WHERE "hours" IS NOT NULL OR "address" IS NOT NULL OR "deliveryNote" IS NOT NULL;
@@ -0,0 +1,3 @@
ALTER TABLE "InquiryForm" ADD COLUMN "purpose" TEXT NOT NULL DEFAULT 'inquiry';
ALTER TABLE "InquiryForm" ADD COLUMN "targetType" TEXT NOT NULL DEFAULT 'brand';
ALTER TABLE "InquiryForm" ADD COLUMN "submissionAction" TEXT NOT NULL DEFAULT 'create-inquiry';
@@ -0,0 +1,28 @@
ALTER TABLE "Booking" ADD COLUMN "workflowKey" TEXT NOT NULL DEFAULT 'booking.basic';
ALTER TABLE "Booking" ADD COLUMN "workflowVersion" TEXT NOT NULL DEFAULT '1.0.0';
ALTER TABLE "Booking" ADD COLUMN "currentState" TEXT NOT NULL DEFAULT 'received';
UPDATE "Booking" SET "currentState" = "status"::text;
CREATE TABLE "BookingStateTransition" (
"id" TEXT NOT NULL,
"bookingId" TEXT NOT NULL,
"workflowKey" TEXT NOT NULL,
"workflowVersion" TEXT NOT NULL,
"fromState" TEXT,
"toState" TEXT NOT NULL,
"actorRole" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "BookingStateTransition_pkey" PRIMARY KEY ("id")
);
ALTER TABLE "BookingStateTransition" ADD CONSTRAINT "BookingStateTransition_bookingId_fkey"
FOREIGN KEY ("bookingId") REFERENCES "Booking"("id") ON DELETE CASCADE ON UPDATE CASCADE;
CREATE INDEX "BookingStateTransition_bookingId_createdAt_idx"
ON "BookingStateTransition"("bookingId", "createdAt");
INSERT INTO "BookingStateTransition" (
"id", "bookingId", "workflowKey", "workflowVersion", "fromState", "toState", "actorRole", "createdAt"
)
SELECT gen_random_uuid()::text, "id", "workflowKey", "workflowVersion", NULL, "currentState", 'migration', "createdAt"
FROM "Booking";
@@ -0,0 +1,32 @@
INSERT INTO "Offering" (
"id", "brandId", "kind", "name", "summary", "description", "coverUrl",
"priceText", "priceAmount", "isEnabled", "sortOrder", "config", "createdAt", "updatedAt"
)
SELECT
gen_random_uuid()::text,
s."brandId",
'service',
s."name",
NULL,
s."description",
s."coverUrl",
s."priceText",
s."priceAmount",
s."isEnabled",
s."sortOrder",
s."config",
s."createdAt",
s."updatedAt"
FROM "Service" s
WHERE s."offeringId" IS NULL
AND NOT EXISTS (
SELECT 1 FROM "Offering" o
WHERE o."brandId" = s."brandId" AND o."name" = s."name"
);
UPDATE "Service" s
SET "offeringId" = o."id"
FROM "Offering" o
WHERE s."offeringId" IS NULL
AND o."brandId" = s."brandId"
AND o."name" = s."name";
@@ -0,0 +1,9 @@
-- Service data was backfilled into Offering before this migration.
ALTER TABLE "BookingItem" DROP CONSTRAINT IF EXISTS "BookingItem_serviceId_fkey";
ALTER TABLE "Booking" DROP CONSTRAINT IF EXISTS "Booking_serviceId_fkey";
ALTER TABLE "Offering" DROP CONSTRAINT IF EXISTS "Service_offeringId_fkey";
ALTER TABLE "BookingItem" DROP COLUMN IF EXISTS "serviceId";
ALTER TABLE "Booking" DROP COLUMN IF EXISTS "serviceId";
DROP INDEX IF EXISTS "Service_brandId_isEnabled_sortOrder_idx";
DROP INDEX IF EXISTS "Service_brandId_name_key";
DROP TABLE IF EXISTS "Service";
@@ -0,0 +1,11 @@
ALTER TABLE "InquirySubmission" ADD COLUMN "offeringId" TEXT;
ALTER TABLE "InquirySubmission"
ADD CONSTRAINT "InquirySubmission_offeringId_fkey"
FOREIGN KEY ("offeringId") REFERENCES "Offering"("id")
ON DELETE SET NULL ON UPDATE CASCADE;
CREATE INDEX "InquirySubmission_offeringId_idx" ON "InquirySubmission"("offeringId");
UPDATE "InquirySubmission" s
SET "offeringId" = f."offeringId"
FROM "InquiryForm" f
WHERE s."inquiryFormId" = f."id" AND f."offeringId" IS NOT NULL;
@@ -0,0 +1,14 @@
ALTER TABLE "InquirySubmission" ADD COLUMN "status" TEXT NOT NULL DEFAULT 'new';
ALTER TABLE "InquirySubmission" ADD COLUMN "adminNote" TEXT;
ALTER TABLE "InquirySubmission" ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
CREATE TABLE "InquirySubmissionStatusHistory" (
"id" TEXT NOT NULL,
"submissionId" TEXT NOT NULL,
"fromStatus" TEXT,
"toStatus" TEXT NOT NULL,
"adminNote" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "InquirySubmissionStatusHistory_pkey" PRIMARY KEY ("id"),
CONSTRAINT "InquirySubmissionStatusHistory_submissionId_fkey" FOREIGN KEY ("submissionId") REFERENCES "InquirySubmission"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE INDEX "InquirySubmissionStatusHistory_submissionId_createdAt_idx" ON "InquirySubmissionStatusHistory"("submissionId", "createdAt");
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
+170 -21
View File
@@ -18,6 +18,7 @@ enum BookingStatus {
enum BookingRequestType {
package
private_chef
inquiry
}
enum ContactPreference {
@@ -34,6 +35,7 @@ enum FulfillmentType {
model BrandProfile {
id String @id @default(uuid())
name String
templateKey String @default("food")
tagline String?
description String?
avatarUrl String?
@@ -43,33 +45,163 @@ model BrandProfile {
deliveryNote String?
contactPhone String?
contactWechat String?
config Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
services Service[]
bookings Booking[]
customerUsers CustomerUser[]
tags Tag[]
trustContents TrustContent[]
templateInstallations BrandTemplateInstallation[]
modules BrandModule[]
fieldDefinitions BrandFieldDefinition[]
offerings Offering[]
inquiryForms InquiryForm[]
inquirySubmissions InquirySubmission[]
}
model Service {
id String @id @default(uuid())
brandId String
brand BrandProfile @relation(fields: [brandId], references: [id])
name String
description String
coverUrl String?
priceText String?
priceAmount Int?
bookingEnabled Boolean @default(true)
isEnabled Boolean @default(true)
sortOrder Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
bookings Booking[]
bookingItems BookingItem[]
model BrandTemplateInstallation {
id String @id @default(uuid())
brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
templateKey String
templateVersion String @default("1.0.0")
configSnapshot Json
previousSnapshots Json @default("[]")
installedAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([brandId, templateKey])
@@index([brandId])
}
model BrandModule {
id String @id @default(uuid())
brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
type String
title String
isEnabled Boolean @default(true)
sortOrder Int @default(0)
source String @default("core")
config Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([brandId, isEnabled, sortOrder])
}
model BrandFieldDefinition {
id String @id @default(uuid())
brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
scope String
key String
label String
type String
required Boolean @default(false)
isVisible Boolean @default(true)
sortOrder Int @default(0)
source String @default("custom")
isOverridden Boolean @default(false)
options Json?
visibleWhen Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([brandId, scope, key])
@@index([brandId, scope, sortOrder])
}
model Offering {
id String @id @default(uuid())
brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
kind String @default("service")
name String
summary String?
description String?
coverUrl String?
priceText String?
priceAmount Int?
isEnabled Boolean @default(true)
sortOrder Int @default(0)
config Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
inquiryForms InquiryForm[]
inquirySubmissions InquirySubmission[]
bookings Booking[]
bookingItems BookingItem[]
@@unique([brandId, name])
@@index([brandId, isEnabled, sortOrder])
}
model InquiryForm {
id String @id @default(uuid())
brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
offeringId String?
offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull)
name String
purpose String @default("inquiry")
targetType String @default("brand")
submissionAction String @default("create-inquiry")
version Int @default(1)
isEnabled Boolean @default(true)
fieldsSnapshot Json
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
submissions InquirySubmission[]
@@index([brandId, isEnabled])
}
model InquirySubmission {
id String @id @default(uuid())
brandId String
inquiryFormId String
offeringId String?
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
inquiryForm InquiryForm @relation(fields: [inquiryFormId], references: [id], onDelete: Restrict)
offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull)
formVersion Int
fieldsSnapshot Json
values Json
activeFields Json
status String @default("new")
adminNote String?
updatedAt DateTime @updatedAt
statusHistory InquirySubmissionStatusHistory[]
createdAt DateTime @default(now())
@@index([brandId, createdAt])
@@index([inquiryFormId, formVersion])
}
model InquirySubmissionStatusHistory {
id String @id @default(uuid())
submissionId String
submission InquirySubmission @relation(fields: [submissionId], references: [id], onDelete: Cascade)
fromStatus String?
toStatus String
adminNote String?
createdAt DateTime @default(now())
@@index([submissionId, createdAt])
}
model TrustContent {
id String @id @default(uuid())
brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
type String
title String
summary String?
content String
coverUrl String?
sortOrder Int @default(0)
isPublished Boolean @default(true)
config Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([brandId, type, sortOrder])
}
model CustomerUser {
id String @id @default(uuid())
brandId String
@@ -95,8 +227,8 @@ model Booking {
wechatId String?
contactPreference ContactPreference
fulfillmentType FulfillmentType?
serviceId String?
service Service? @relation(fields: [serviceId], references: [id], onDelete: SetNull)
offeringId String?
offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull)
requestedDate DateTime?
requestedTime String?
deliveryAddress String?
@@ -105,21 +237,38 @@ model Booking {
note String?
adminNote String?
status BookingStatus @default(received)
workflowKey String @default("booking.basic")
workflowVersion String @default("1.0.0")
currentState String @default("received")
isRead Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
items BookingItem[]
tags BookingTag[]
stateTransitions BookingStateTransition[]
@@index([brandId, status, createdAt])
@@index([customerUserId, createdAt])
}
model BookingStateTransition {
id String @id @default(uuid())
bookingId String
booking Booking @relation(fields: [bookingId], references: [id], onDelete: Cascade)
workflowKey String
workflowVersion String
fromState String?
toState String
actorRole String
createdAt DateTime @default(now())
@@index([bookingId, createdAt])
}
model BookingItem {
id String @id @default(uuid())
bookingId String
booking Booking @relation(fields: [bookingId], references: [id], onDelete: Cascade)
serviceId String?
service Service? @relation(fields: [serviceId], references: [id], onDelete: SetNull)
offeringId String?
offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull)
serviceNameSnapshot String
unitPriceSnapshot Int
quantity Int
+35 -31
View File
@@ -1,5 +1,5 @@
import { PrismaClient } from "@prisma/client";
import { hash } from "bcryptjs";
import bcrypt from "bcryptjs";
const prisma = new PrismaClient();
@@ -10,6 +10,7 @@ async function main(): Promise<void> {
create: {
id: "00000000-0000-0000-0000-000000000001",
name: "阿成家常菜",
templateKey: "food",
tagline: "现做家常套餐,也为小型聚餐定制一桌热饭菜",
description: "每天认真做好一顿家常饭。",
hours: "周一至周六 10:30-20:00",
@@ -18,35 +19,38 @@ async function main(): Promise<void> {
},
});
await prisma.service.createMany({
data: [
{
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: "面议",
bookingEnabled: true,
sortOrder: 3,
},
],
skipDuplicates: true,
});
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" } });
}
for (const name of ["普通套餐", "私厨", "配送", "自取", "熟客", "重点跟进"]) {
await prisma.tag.upsert({
@@ -60,7 +64,7 @@ async function main(): Promise<void> {
update: {},
create: {
username: "admin",
passwordHash: await hash(process.env.SEED_ADMIN_PASSWORD ?? "change-me-now-123", 12),
passwordHash: await bcrypt.hash(process.env.SEED_ADMIN_PASSWORD ?? "change-me-now-123", 12),
displayName: "品牌管理员",
},
});
+6
View File
@@ -4,3 +4,9 @@ export class AdminLoginDto {
@IsString() username!: string;
@IsString() @MinLength(8) password!: string;
}
export class WechatLoginDto {
@IsString()
@MinLength(1)
code!: string;
}
+2 -4
View File
@@ -1,5 +1,5 @@
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { compare } from "bcryptjs";
import bcrypt from "bcryptjs";
import { PrismaService } from "./prisma.service.js";
import { signIdentity } from "./auth.js";
@@ -9,9 +9,7 @@ export class AdminAuthService {
async login(username: string, password: string): Promise<{ token: string; displayName: string }> {
const user = await this.prisma.adminUser.findUnique({ where: { username } });
// bcryptjs ships incomplete typings in this dependency version.
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
if (!user || !user.isEnabled || !(await compare(password, user.passwordHash))) {
if (!user || !user.isEnabled || !(await bcrypt.compare(password, user.passwordHash))) {
throw new UnauthorizedException("账号或密码错误");
}
await this.prisma.adminUser.update({
+356
View File
@@ -0,0 +1,356 @@
import {
BadRequestException,
UnauthorizedException,
ForbiddenException,
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Req,
} from "@nestjs/common";
import { Prisma } from "@prisma/client";
import type { FastifyRequest } from "fastify";
import { PrismaService } from "./prisma.service.js";
import { readIdentity } from "./auth.js";
import {
InstallTemplateDto,
CreateOfferingDto,
UpdateOfferingDto,
UpdateModuleDto,
CreateFieldDefinitionDto,
UpdateFieldDefinitionDto,
CreateInquiryFormDto,
UpdateInquiryFormDto,
UpdateInquirySubmissionDto,
} from "./admin.dto.js";
import { TemplateWorkspaceService } from "./template-workspace.service.js";
import { validateFieldSnapshot, validateOfferingConfig } from "@personal-brand/validation";
@Controller("admin/workspace")
class AdminWorkspaceController {
constructor(
private readonly prisma: PrismaService,
private readonly templateWorkspace: TemplateWorkspaceService,
) {}
private brandId(): string {
return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
}
@Get("offerings")
async listOfferings(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
const items = await this.prisma.offering.findMany({
where: { brandId: this.brandId() },
orderBy: { sortOrder: "asc" },
});
return items.map((item) => {
const config = (item.config ?? {}) as Record<string, unknown>;
return {
...item,
sections: config.sections ?? [],
media: config.media ?? [],
cta: config.cta ?? null,
};
});
}
@Post("offerings")
createOffering(
@Req() request: FastifyRequest,
@Body() body: CreateOfferingDto,
): Promise<unknown> {
this.requireAdmin(request);
const { config, sections, media, cta, ...fields } = body;
const configValue = {
...(config ?? {}),
...(sections === undefined ? {} : { sections }),
...(media === undefined ? {} : { media }),
...(cta === undefined ? {} : { cta }),
};
const configIssues = validateOfferingConfig(configValue);
if (configIssues.length) throw new BadRequestException("业务提供项配置无效");
return this.prisma.offering.create({
data: {
...fields,
brandId: this.brandId(),
config: configValue as Prisma.InputJsonValue,
},
});
}
@Patch("offerings/:id")
async updateOffering(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateOfferingDto,
): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.offering.findFirst({ where: { id, brandId: this.brandId() } });
if (!item) throw new BadRequestException("业务提供项不存在");
const { config, sections, media, cta, ...fields } = body;
const configValue = {
...(config ?? {}),
...(sections === undefined ? {} : { sections }),
...(media === undefined ? {} : { media }),
...(cta === undefined ? {} : { cta }),
};
if (validateOfferingConfig(configValue).length)
throw new BadRequestException("业务提供项配置无效");
return this.prisma.offering.update({
where: { id },
data: {
...fields,
...(config === undefined &&
sections === undefined &&
media === undefined &&
cta === undefined
? {}
: {
config: configValue as Prisma.InputJsonValue,
}),
},
});
}
@Delete("offerings/:id")
async deleteOffering(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.offering.findFirst({ where: { id, brandId: this.brandId() } });
if (!item) throw new BadRequestException("业务提供项不存在");
const [forms, bookings, items] = await Promise.all([
this.prisma.inquiryForm.count({ where: { offeringId: id } }),
this.prisma.booking.count({ where: { offeringId: id } }),
this.prisma.bookingItem.count({ where: { offeringId: id } }),
]);
if (forms || bookings || items)
throw new BadRequestException("业务提供项已有业务记录,只能禁用不能删除");
await this.prisma.offering.delete({ where: { id } });
return { deleted: true };
}
private requireAdmin(request: FastifyRequest): void {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
try {
identity = readIdentity(token);
} catch {
throw new UnauthorizedException("管理员登录态无效或已过期");
}
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
}
@Get()
async get(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
const brandId = this.brandId();
const [brand, installations, modules, fields, offerings, forms] = await Promise.all([
this.prisma.brandProfile.findUnique({ where: { id: brandId } }),
this.prisma.brandTemplateInstallation.findMany({ where: { brandId } }),
this.prisma.brandModule.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
this.prisma.brandFieldDefinition.findMany({
where: { brandId },
orderBy: { sortOrder: "asc" },
}),
this.prisma.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
this.prisma.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" } }),
]);
return { brand, installations, modules, fields, offerings, forms };
}
@Post("install")
async install(
@Req() request: FastifyRequest,
@Body() body: InstallTemplateDto,
): Promise<unknown> {
this.requireAdmin(request);
return this.templateWorkspace.install(this.brandId(), body.templateKey);
}
@Get("template/preview")
async previewTemplate(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.templateWorkspace.preview(this.brandId());
}
@Post("template/upgrade")
async upgradeTemplate(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.templateWorkspace.upgrade(this.brandId());
}
@Post("template/rollback")
async rollbackTemplate(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.templateWorkspace.rollback(this.brandId());
}
@Patch("modules/:id")
async updateModule(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateModuleDto,
): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.brandModule.findFirst({
where: { id, brandId: this.brandId() },
});
if (!item) throw new BadRequestException("品牌模块不存在");
const { config, ...fields } = body;
return this.prisma.brandModule.update({
where: { id },
data: {
...fields,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
@Post("fields")
createField(
@Req() request: FastifyRequest,
@Body() body: CreateFieldDefinitionDto,
): Promise<unknown> {
this.requireAdmin(request);
return this.prisma.brandFieldDefinition.create({
data: {
...body,
brandId: this.brandId(),
source: "custom",
options: body.options as Prisma.InputJsonValue,
visibleWhen: body.visibleWhen as Prisma.InputJsonValue,
},
});
}
@Patch("fields/:id")
async updateField(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateFieldDefinitionDto,
): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.brandFieldDefinition.findFirst({
where: { id, brandId: this.brandId() },
});
if (!item) throw new BadRequestException("品牌字段不存在");
const { options, visibleWhen, ...fields } = body;
return this.prisma.brandFieldDefinition.update({
where: { id },
data: {
...fields,
...(options === undefined ? {} : { options: options as Prisma.InputJsonValue }),
...(visibleWhen === undefined ? {} : { visibleWhen: visibleWhen as Prisma.InputJsonValue }),
},
});
}
@Delete("fields/:id")
async deleteField(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.brandFieldDefinition.findFirst({
where: { id, brandId: this.brandId(), source: "custom" },
});
if (!item) throw new BadRequestException("自定义字段不存在或不可删除");
await this.prisma.brandFieldDefinition.delete({ where: { id } });
return { deleted: true };
}
@Get("forms")
listForms(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.prisma.inquiryForm.findMany({
where: { brandId: this.brandId() },
orderBy: { updatedAt: "desc" },
});
}
@Get("submissions")
listSubmissions(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.prisma.inquirySubmission.findMany({
where: { brandId: this.brandId() },
include: {
inquiryForm: { select: { name: true } },
offering: { select: { id: true, name: true } },
},
orderBy: { createdAt: "desc" },
});
}
@Patch("submissions/:id")
async updateSubmission(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateInquirySubmissionDto,
): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.inquirySubmission.findFirst({
where: { id, brandId: this.brandId() },
});
if (!item) throw new BadRequestException("咨询记录不存在");
return this.prisma.$transaction(async (tx) => {
const updated = await tx.inquirySubmission.update({
where: { id },
data: {
status: body.status,
...(body.adminNote === undefined ? {} : { adminNote: body.adminNote }),
},
});
if (item.status !== body.status || body.adminNote !== undefined) {
await tx.inquirySubmissionStatusHistory.create({
data: {
submissionId: id,
fromStatus: item.status,
toStatus: body.status,
adminNote: body.adminNote ?? null,
},
});
}
return updated;
});
}
@Post("forms")
createForm(@Req() request: FastifyRequest, @Body() body: CreateInquiryFormDto): Promise<unknown> {
this.requireAdmin(request);
if (validateFieldSnapshot(body.fieldsSnapshot).length)
throw new BadRequestException("咨询表单字段定义无效");
return this.prisma.inquiryForm.create({
data: {
...body,
brandId: this.brandId(),
version: 1,
fieldsSnapshot: body.fieldsSnapshot as Prisma.InputJsonValue,
},
});
}
@Patch("forms/:id")
async updateForm(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateInquiryFormDto,
): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.inquiryForm.findFirst({
where: { id, brandId: this.brandId() },
});
if (!item) throw new BadRequestException("咨询表单不存在");
const { fieldsSnapshot, ...fields } = body;
if (fieldsSnapshot !== undefined && validateFieldSnapshot(fieldsSnapshot).length)
throw new BadRequestException("咨询表单字段定义无效");
return this.prisma.inquiryForm.update({
where: { id },
data: {
...fields,
...(fieldsSnapshot === undefined
? {}
: { fieldsSnapshot: fieldsSnapshot as Prisma.InputJsonValue }),
...(fieldsSnapshot === undefined ? {} : { version: { increment: 1 } }),
},
});
}
}
export { AdminWorkspaceController };
+163 -1
View File
@@ -1,4 +1,55 @@
import { IsArray, IsIn, IsOptional, IsString } from "class-validator";
import {
IsArray,
IsBoolean,
IsIn,
IsInt,
IsObject,
IsOptional,
IsString,
Matches,
Max,
Min,
} from "class-validator";
export class UpdateBrandDto {
@IsOptional() @IsString() name?: string;
@IsOptional() @IsIn(["food", "personal"]) templateKey?: "food" | "personal";
@IsOptional() @IsString() tagline?: string;
@IsOptional() @IsString() description?: string;
@IsOptional() @IsString() avatarUrl?: string;
@IsOptional() @IsString() coverUrl?: string;
@IsOptional() @IsString() hours?: string;
@IsOptional() @IsString() address?: string;
@IsOptional() @IsString() deliveryNote?: string;
@IsOptional() @IsString() contactPhone?: string;
@IsOptional() @IsString() contactWechat?: string;
@IsOptional() @IsObject() config?: Record<string, unknown>;
}
export class CreateTrustContentDto {
@IsIn(["profile", "experience", "credential", "portfolio", "process", "testimonial"])
type!: string;
@IsString() title!: string;
@IsOptional() @IsString() summary?: string;
@IsString() content!: string;
@IsOptional() @IsString() coverUrl?: string;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() @IsBoolean() isPublished?: boolean;
@IsOptional() config?: Record<string, unknown>;
}
export class UpdateTrustContentDto {
@IsOptional()
@IsIn(["profile", "experience", "credential", "portfolio", "process", "testimonial"])
type?: string;
@IsOptional() @IsString() title?: string;
@IsOptional() @IsString() summary?: string;
@IsOptional() @IsString() content?: string;
@IsOptional() @IsString() coverUrl?: string;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() @IsBoolean() isPublished?: boolean;
@IsOptional() config?: Record<string, unknown>;
}
export class UpdateBookingStatusDto {
@IsIn(["received", "contacting", "confirmed", "completed", "cancelled"])
@@ -9,6 +60,12 @@ export class UpdateBookingStatusDto {
adminNote?: string;
}
export class UpdateInquirySubmissionDto {
@IsIn(["new", "reviewing", "replied", "qualified", "converted", "closed"])
status!: "new" | "reviewing" | "replied" | "qualified" | "converted" | "closed";
@IsOptional() @IsString() adminNote?: string;
}
export class CreateTagDto {
@IsString() name!: string;
}
@@ -16,3 +73,108 @@ export class CreateTagDto {
export class UpdateBookingTagsDto {
@IsArray() @IsString({ each: true }) tagIds!: string[];
}
export class InstallTemplateDto {
@IsIn(["personal", "food"])
templateKey!: "personal" | "food";
}
export class CreateOfferingDto {
@IsIn(["service", "product", "package", "subscription"]) kind!: string;
@IsString() name!: string;
@IsOptional() @IsString() summary?: string;
@IsOptional() @IsString() description?: string;
@IsOptional() @IsString() coverUrl?: string;
@IsOptional() @IsString() priceText?: string;
@IsOptional() @IsInt() @Min(0) priceAmount?: number;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() @IsBoolean() isEnabled?: boolean;
@IsOptional() config?: Record<string, unknown>;
@IsOptional() sections?: Array<{
type: string;
title: string;
content?: string;
items?: unknown[];
}>;
@IsOptional() media?: Array<{ url: string; alt?: string; type?: string }>;
@IsOptional() cta?: { type: string; label: string; config?: Record<string, unknown> };
}
export class UpdateOfferingDto {
@IsOptional() @IsIn(["service", "product", "package", "subscription"]) kind?: string;
@IsOptional() @IsString() name?: string;
@IsOptional() @IsString() summary?: string;
@IsOptional() @IsString() description?: string;
@IsOptional() @IsString() coverUrl?: string;
@IsOptional() @IsString() priceText?: string;
@IsOptional() @IsInt() @Min(0) priceAmount?: number;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() @IsBoolean() isEnabled?: boolean;
@IsOptional() config?: Record<string, unknown>;
@IsOptional() sections?: Array<{
type: string;
title: string;
content?: string;
items?: unknown[];
}>;
@IsOptional() media?: Array<{ url: string; alt?: string; type?: string }>;
@IsOptional() cta?: { type: string; label: string; config?: Record<string, unknown> };
}
export class UpdateModuleDto {
@IsOptional() @IsString() title?: string;
@IsOptional() @IsBoolean() isEnabled?: boolean;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() config?: Record<string, unknown>;
}
export class CreateFieldDefinitionDto {
@IsIn(["profile", "service", "inquiry"]) scope!: string;
@IsString() @Matches(/^[a-z][a-z0-9_]*$/) key!: string;
@IsString() label!: string;
@IsIn(["text", "textarea", "number", "date", "select", "multi-select", "image", "url", "phone"])
type!: string;
@IsOptional() @IsBoolean() required?: boolean;
@IsOptional() @IsBoolean() isVisible?: boolean;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() @IsArray() options?: unknown[];
@IsOptional() @IsObject() visibleWhen?: Record<string, unknown>;
}
export class UpdateFieldDefinitionDto {
@IsOptional() @IsIn(["profile", "service", "inquiry"]) scope?: string;
@IsOptional() @IsString() @Matches(/^[a-z][a-z0-9_]*$/) key?: string;
@IsOptional() @IsString() label?: string;
@IsOptional()
@IsIn(["text", "textarea", "number", "date", "select", "multi-select", "image", "url", "phone"])
type?: string;
@IsOptional() @IsBoolean() required?: boolean;
@IsOptional() @IsBoolean() isVisible?: boolean;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() @IsArray() options?: unknown[];
@IsOptional() @IsObject() visibleWhen?: Record<string, unknown>;
}
export class CreateInquiryFormDto {
@IsString() name!: string;
@IsOptional() @IsString() offeringId?: string;
@IsOptional() @IsIn(["inquiry", "booking", "quote-request"]) purpose?: string;
@IsOptional() @IsIn(["brand", "offering"]) targetType?: string;
@IsOptional()
@IsIn(["create-inquiry", "create-booking", "create-quote"])
submissionAction?: string;
@IsArray() fieldsSnapshot!: unknown[];
@IsOptional() @IsBoolean() isEnabled?: boolean;
}
export class UpdateInquiryFormDto {
@IsOptional() @IsString() name?: string;
@IsOptional() @IsString() offeringId?: string;
@IsOptional() @IsIn(["inquiry", "booking", "quote-request"]) purpose?: string;
@IsOptional() @IsIn(["brand", "offering"]) targetType?: string;
@IsOptional()
@IsIn(["create-inquiry", "create-booking", "create-quote"])
submissionAction?: string;
@IsOptional() @IsArray() fieldsSnapshot?: unknown[];
@IsOptional() @IsBoolean() isEnabled?: boolean;
}
+10 -3
View File
@@ -5,6 +5,7 @@ import {
IsInt,
IsISO8601,
IsOptional,
IsObject,
IsString,
Max,
Min,
@@ -12,18 +13,19 @@ import {
} from "class-validator";
export class BookingItemDto {
@IsString() serviceId!: string;
@IsString() offeringId!: string;
@IsInt() @Min(1) @Max(50) quantity!: number;
}
export class CreateBookingDto {
@IsIn(["package", "private_chef"]) requestType!: "package" | "private_chef";
@IsIn(["package", "private_chef", "inquiry"]) requestType!:
"package" | "private_chef" | "inquiry";
@IsString() customerName!: string;
@IsOptional() @IsString() phone?: string;
@IsOptional() @IsString() wechatId?: string;
@IsIn(["wechat", "phone", "none"]) contactPreference!: "wechat" | "phone" | "none";
@IsOptional() @IsIn(["pickup", "delivery"]) fulfillmentType?: "pickup" | "delivery";
@IsOptional() @IsString() serviceId?: string;
@IsOptional() @IsString() offeringId?: string;
@IsOptional() @IsISO8601() requestedDate?: string;
@IsOptional() @IsString() requestedTime?: string;
@IsOptional() @IsString() deliveryAddress?: string;
@@ -32,3 +34,8 @@ export class CreateBookingDto {
@IsArray() @ValidateNested({ each: true }) @Type(() => BookingItemDto) items: BookingItemDto[] =
[];
}
export class CreateInquirySubmissionDto {
@IsString() formId!: string;
@IsObject() values!: Record<string, unknown>;
}
+93 -31
View File
@@ -1,21 +1,24 @@
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { BookingStatus, Prisma } from "@prisma/client";
import { PrismaService } from "./prisma.service.js";
import { canTransitionWorkflow, workflowRegistry } from "@personal-brand/config";
const BASIC_BOOKING_WORKFLOW = workflowRegistry["booking.basic"];
export interface CreateBookingInput {
requestType: "package" | "private_chef";
requestType: "package" | "private_chef" | "inquiry";
customerName: string;
phone?: string;
wechatId?: string;
contactPreference: "wechat" | "phone" | "none";
fulfillmentType?: "pickup" | "delivery";
serviceId?: string;
offeringId?: string;
requestedDate?: string;
requestedTime?: string;
deliveryAddress?: string;
note?: string;
extraData?: Prisma.InputJsonObject;
items?: Array<{ serviceId: string; quantity: number }>;
items?: Array<{ offeringId: string; quantity: number }>;
}
@Injectable()
@@ -49,26 +52,26 @@ export class BookingService {
) {
throw new BadRequestException("私厨需求必须填写日期、人数和地点");
}
const services = input.items?.length
? await this.prisma.service.findMany({
const offerings = input.items?.length
? await this.prisma.offering.findMany({
where: {
id: { in: input.items.map((item) => item.serviceId) },
id: { in: input.items.map((item) => item.offeringId) },
brandId,
isEnabled: true,
},
})
: [];
const serviceMap = new Map(services.map((service) => [service.id, service]));
const offeringMap = new Map(offerings.map((offering) => [offering.id, offering]));
const items = (input.items ?? []).map((item) => {
const service = serviceMap.get(item.serviceId);
if (!service || !service.bookingEnabled || service.priceAmount === null)
const offering = offeringMap.get(item.offeringId);
if (!offering || offering.priceAmount === null)
throw new BadRequestException("套餐不存在或暂不可预订");
return {
serviceId: service.id,
serviceNameSnapshot: service.name,
unitPriceSnapshot: service.priceAmount,
offeringId: offering.id,
serviceNameSnapshot: offering.name,
unitPriceSnapshot: offering.priceAmount,
quantity: item.quantity,
subtotalSnapshot: service.priceAmount * item.quantity,
subtotalSnapshot: offering.priceAmount * item.quantity,
};
});
const estimatedAmount = items.reduce((sum, item) => sum + item.subtotalSnapshot, 0) || null;
@@ -85,7 +88,7 @@ export class BookingService {
wechatId: input.wechatId?.trim() ?? null,
contactPreference: input.contactPreference,
fulfillmentType: input.fulfillmentType ?? null,
serviceId: items[0]?.serviceId ?? input.serviceId ?? null,
offeringId: items[0]?.offeringId ?? input.offeringId ?? null,
requestedDate: input.requestedDate
? new Date(`${input.requestedDate}T00:00:00.000Z`)
: null,
@@ -95,6 +98,14 @@ export class BookingService {
...(input.extraData ? { extraData: input.extraData } : {}),
note: input.note ?? null,
items: { create: items },
stateTransitions: {
create: {
workflowKey: BASIC_BOOKING_WORKFLOW.key,
workflowVersion: BASIC_BOOKING_WORKFLOW.version,
toState: "received",
actorRole: "customer",
},
},
},
select: { bookingNo: true, status: true, estimatedAmount: true, createdAt: true },
});
@@ -105,25 +116,63 @@ export class BookingService {
return this.prisma.booking.findMany({
where: { brandId, customerUserId },
orderBy: { createdAt: "desc" },
include: { items: true, service: { select: { name: true } } },
include: { items: true, offering: { select: { name: true } } },
});
}
async cancelForCustomer(brandId: string, customerUserId: string, id: string) {
const booking = await this.prisma.booking.findFirst({ where: { id, brandId, customerUserId } });
if (!booking) throw new NotFoundException("订单不存在");
if (booking.status !== "received") throw new BadRequestException("当前状态不可取消");
return this.prisma.booking.update({ where: { id }, data: { status: "cancelled" } });
if (!canTransitionWorkflow(booking.workflowKey, booking.currentState, "cancelled"))
throw new BadRequestException("当前状态不可取消");
return this.prisma.$transaction(async (tx) => {
const updated = await tx.booking.update({
where: { id },
data: { status: "cancelled", currentState: "cancelled" },
});
await tx.bookingStateTransition.create({
data: {
bookingId: id,
workflowKey: booking.workflowKey,
workflowVersion: booking.workflowVersion,
fromState: booking.currentState,
toState: "cancelled",
actorRole: "customer",
},
});
return updated;
});
}
async listForAdmin(brandId: string) {
async listForAdmin(
brandId: string,
options: { status?: BookingStatus; unreadOnly?: boolean; tagId?: string } = {},
) {
return this.prisma.booking.findMany({
where: { brandId },
where: {
brandId,
...(options.status ? { status: options.status } : {}),
...(options.unreadOnly ? { isRead: false } : {}),
...(options.tagId ? { tags: { some: { tagId: options.tagId } } } : {}),
},
orderBy: { createdAt: "desc" },
include: { items: true, tags: { include: { tag: true } } },
});
}
async getForAdmin(brandId: string, id: string) {
const booking = await this.prisma.booking.findFirst({
where: { id, brandId },
include: { items: true, tags: { include: { tag: true } }, offering: true },
});
if (!booking) throw new NotFoundException("订单不存在");
return booking;
}
async unreadCountForAdmin(brandId: string) {
return { count: await this.prisma.booking.count({ where: { brandId, isRead: false } }) };
}
async updateStatus(
brandId: string,
id: string,
@@ -132,18 +181,31 @@ export class BookingService {
) {
const booking = await this.prisma.booking.findFirst({ where: { id, brandId } });
if (!booking) throw new NotFoundException("订单不存在");
const allowed: Record<string, string[]> = {
received: ["contacting", "cancelled"],
contacting: ["confirmed", "cancelled"],
confirmed: ["completed", "cancelled"],
completed: [],
cancelled: [],
};
if (status !== booking.status && !allowed[booking.status]?.includes(status))
if (!canTransitionWorkflow(booking.workflowKey, booking.currentState, status))
throw new BadRequestException("不允许的订单状态流转");
return this.prisma.booking.update({
where: { id },
data: { status, ...(adminNote !== undefined ? { adminNote } : {}), isRead: true },
return this.prisma.$transaction(async (tx) => {
const updated = await tx.booking.update({
where: { id },
data: {
status,
currentState: status,
...(adminNote !== undefined ? { adminNote } : {}),
isRead: true,
},
});
if (status !== booking.currentState) {
await tx.bookingStateTransition.create({
data: {
bookingId: id,
workflowKey: booking.workflowKey,
workflowVersion: booking.workflowVersion,
fromState: booking.currentState,
toState: status,
actorRole: "admin",
},
});
}
return updated;
});
}
+23 -3
View File
@@ -7,7 +7,18 @@ import { randomUUID } from "node:crypto";
export class RequestIdMiddleware {
use(request: FastifyRequest, reply: FastifyReply, next: () => void): void {
const requestId = request.headers["x-request-id"]?.toString() ?? randomUUID();
reply.header("x-request-id", requestId);
if (typeof reply.header === "function") {
reply.header("x-request-id", requestId);
} else {
(reply as unknown as { setHeader: (name: string, value: string) => void }).setHeader(
"x-request-id",
requestId,
);
}
(request as FastifyRequest & { requestId?: string }).requestId = requestId;
if (process.env.NODE_ENV === "development") {
console.info("api request", { method: request.method, url: request.url, requestId });
}
next();
}
}
@@ -19,14 +30,23 @@ export class ApiExceptionFilter implements ExceptionFilter {
const response = context.getResponse<FastifyReply>();
const request = context.getRequest<FastifyRequest>();
const status = exception instanceof HttpException ? exception.getStatus() : 500;
const detail = exception instanceof HttpException ? exception.getResponse() : "服务器内部错误";
if (!(exception instanceof HttpException)) console.error("api unhandled error", exception);
const detail =
exception instanceof HttpException
? exception.getResponse()
: process.env.NODE_ENV === "development" && exception instanceof Error
? exception.message
: "服务器内部错误";
response.status(status).send({
data: null,
error: {
code: `HTTP_${status}`,
message: typeof detail === "string" ? detail : "请求失败",
},
requestId: request.headers["x-request-id"] ?? null,
requestId:
(request as FastifyRequest & { requestId?: string }).requestId ??
request.headers["x-request-id"] ??
null,
});
}
}
+370 -23
View File
@@ -1,29 +1,47 @@
import "reflect-metadata";
import {
BadRequestException,
UnauthorizedException,
ForbiddenException,
Body,
Controller,
Delete,
Get,
Module,
Param,
Post,
Patch,
Query,
Req,
ValidationPipe,
} from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { Prisma } from "@prisma/client";
import { BookingStatus, Prisma } from "@prisma/client";
import { FastifyAdapter } from "@nestjs/platform-fastify";
import type { NestFastifyApplication } from "@nestjs/platform-fastify";
import { PrismaService } from "./prisma.service.js";
import { WechatAuthService } from "./wechat-auth.js";
import { BookingService } from "./booking.service.js";
import { CreateBookingDto } from "./booking.dto.js";
import { CreateTagDto, UpdateBookingStatusDto, UpdateBookingTagsDto } from "./admin.dto.js";
import { CreateBookingDto, CreateInquirySubmissionDto } from "./booking.dto.js";
import {
CreateTagDto,
CreateTrustContentDto,
UpdateBookingStatusDto,
UpdateBookingTagsDto,
UpdateBrandDto,
UpdateTrustContentDto,
} from "./admin.dto.js";
import { AdminAuthService } from "./admin-auth.service.js";
import { AdminLoginDto } from "./admin-auth.dto.js";
import { AdminLoginDto, WechatLoginDto } from "./admin-auth.dto.js";
import type { FastifyRequest } from "fastify";
import { Transform } from "class-transformer";
import type { TransformFnParams } from "class-transformer";
import { IsBoolean, IsEnum, IsOptional, IsString } from "class-validator";
import { readIdentity, signIdentity } from "./auth.js";
import { ApiExceptionFilter, RequestIdMiddleware } from "./http.js";
import { getBrandTemplate, resolveCapabilities } from "@personal-brand/config";
import { AdminWorkspaceController } from "./admin-workspace.controller.js";
import { TemplateWorkspaceService } from "./template-workspace.service.js";
@Controller("health")
export class HealthController {
@@ -43,6 +61,7 @@ export class PublicController {
select: {
id: true,
name: true,
templateKey: true,
tagline: true,
description: true,
avatarUrl: true,
@@ -50,23 +69,200 @@ export class PublicController {
hours: true,
address: true,
deliveryNote: true,
contactPhone: true,
contactWechat: true,
},
});
}
}
@Get("services")
async services(): Promise<unknown> {
return this.prisma.service.findMany({
where: { isEnabled: true },
@Controller("public/trust-content")
export class PublicTrustContentController {
constructor(private readonly prisma: PrismaService) {}
@Get()
list(): Promise<unknown> {
return this.prisma.trustContent.findMany({
where: {
brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
isPublished: true,
},
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
});
}
}
@Controller("public/templates")
export class PublicTemplateController {
@Get(":key")
get(@Param("key") key: string): unknown {
const template = getBrandTemplate(key);
if (!template) throw new BadRequestException("行业模板不存在");
return template;
}
}
@Controller("public/workspace")
export class PublicWorkspaceController {
constructor(private readonly prisma: PrismaService) {}
@Get()
async get(): Promise<unknown> {
const brandId = process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
const [brand, modules, fields, offerings, inquiryForm, installation] = 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.findFirst({
where: { brandId, isEnabled: true },
orderBy: { updatedAt: "desc" },
}),
this.prisma.brandTemplateInstallation.findFirst({
where: { brandId },
orderBy: { updatedAt: "desc" },
}),
]);
const templateKey = installation?.templateKey ?? brand?.templateKey ?? "personal";
const template = getBrandTemplate(templateKey);
const runtimeModules = modules.map((module) => ({
key: module.type,
type: module.type,
title: module.title,
schemaVersion: "1.0",
sortOrder: module.sortOrder,
config: module.config,
}));
return {
contractVersion: "1.0",
brand,
template: template
? {
key: template.key,
version: installation?.templateVersion ?? template.version,
name: template.name,
}
: null,
capabilities: template?.capabilities ?? [],
runtimeCapabilities: template ? resolveCapabilities(template.capabilities) : [],
modules,
runtimeModules,
fields,
offerings,
inquiryForm,
};
}
}
@Controller("public/offerings")
export class PublicOfferingController {
constructor(private readonly prisma: PrismaService) {}
@Get()
async list(): Promise<unknown> {
const brandId = process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
const items = await this.prisma.offering.findMany({
where: { brandId, isEnabled: true },
orderBy: { sortOrder: "asc" },
select: {
id: true,
name: true,
description: true,
coverUrl: true,
priceText: true,
priceAmount: true,
bookingEnabled: true,
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));
}
@Get(":id")
async get(@Param("id") id: string): Promise<unknown> {
const item = await this.prisma.offering.findFirst({
where: {
id,
brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
isEnabled: true,
},
include: {
inquiryForms: {
where: { isEnabled: true },
orderBy: { updatedAt: "desc" },
select: { id: true, name: true, purpose: true, targetType: true, version: true },
},
},
});
if (!item) throw new BadRequestException("业务提供项不存在");
return this.present(item);
}
private present(item: { config: Prisma.JsonValue; [key: string]: unknown }): unknown {
const config = (item.config ?? {}) as Record<string, unknown>;
return {
...item,
sections: config.sections ?? [],
media: config.media ?? [],
cta: config.cta ?? null,
};
}
}
@Controller("public/inquiry-forms")
export class PublicInquiryFormController {
constructor(private readonly prisma: PrismaService) {}
@Get(":id")
async get(@Param("id") id: string): Promise<unknown> {
const form = await this.prisma.inquiryForm.findFirst({
where: {
id,
brandId: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
isEnabled: true,
OR: [{ offeringId: null }, { offering: { isEnabled: true } }],
},
});
if (!form) throw new BadRequestException("咨询表单不存在");
return form;
}
}
@Controller("customer/inquiry-submissions")
export class CustomerInquirySubmissionController {
constructor(private readonly prisma: PrismaService) {}
@Post()
async create(
@Req() request: FastifyRequest,
@Body() body: CreateInquirySubmissionDto,
): Promise<unknown> {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少客户登录态");
let identity;
try {
identity = readIdentity(token);
} catch {
throw new UnauthorizedException("客户登录态无效或已过期");
}
if (identity.role !== "customer") throw new ForbiddenException("无客户权限");
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("咨询表单不存在");
return this.prisma.inquirySubmission.create({
data: {
brandId: identity.brandId,
inquiryFormId: form.id,
offeringId: form.offeringId,
formVersion: form.version,
fieldsSnapshot: form.fieldsSnapshot as Prisma.InputJsonValue,
values: body.values as Prisma.InputJsonValue,
activeFields: Object.fromEntries(Object.keys(body.values).map((key) => [key, true])),
},
});
}
@@ -80,8 +276,8 @@ export class CustomerSessionController {
) {}
@Post("wechat")
async wechatLogin(@Body() body: { code?: string }): Promise<{ token: string }> {
const session = await this.wechatAuth.exchangeCode(body.code ?? "");
async wechatLogin(@Body() body: WechatLoginDto): Promise<{ token: string }> {
const session = await this.wechatAuth.exchangeCode(body.code);
const brand = await this.prisma.brandProfile.findFirst({ select: { id: true } });
if (!brand) throw new BadRequestException("品牌尚未初始化");
await this.prisma.customerUser.upsert({
@@ -104,6 +300,26 @@ export class AdminSessionController {
}
}
class AdminBookingQueryDto {
@IsOptional()
@IsEnum(BookingStatus)
status?: BookingStatus;
@IsOptional()
@Transform((params: TransformFnParams): unknown => {
const value: unknown = params.value;
if (value === "true") return true;
if (value === "false") return false;
return value;
})
@IsBoolean()
unreadOnly?: boolean;
@IsOptional()
@IsString()
tagId?: string;
}
@Controller("customer/bookings")
export class CustomerBookingController {
constructor(
@@ -162,10 +378,28 @@ export class CustomerBookingController {
export class AdminBookingController {
constructor(private readonly bookings: BookingService) {}
@Get()
list(@Req() request: FastifyRequest): Promise<unknown> {
list(@Req() request: FastifyRequest, @Query() query: AdminBookingQueryDto): Promise<unknown> {
this.requireAdmin(request);
return this.bookings.listForAdmin(
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
query,
);
}
@Get("unread-count")
unreadCount(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.bookings.unreadCountForAdmin(
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
);
}
@Get(":id")
detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
this.requireAdmin(request);
return this.bookings.getForAdmin(
process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001",
id,
);
}
@Post(":id/status")
@@ -226,9 +460,106 @@ export class AdminBookingController {
private requireAdmin(request: FastifyRequest): void {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new BadRequestException("缺少管理员登录态");
const identity = readIdentity(token);
if (identity.role !== "admin") throw new BadRequestException("无管理员权限");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
try {
identity = readIdentity(token);
} catch {
throw new UnauthorizedException("管理员登录态无效或已过期");
}
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
}
}
@Controller("admin/config")
export class AdminConfigController {
constructor(private readonly prisma: PrismaService) {}
private brandId(): string {
return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
}
private requireAdmin(request: FastifyRequest): void {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
let identity;
try {
identity = readIdentity(token);
} catch {
throw new UnauthorizedException("管理员登录态无效或已过期");
}
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
}
@Get("brand")
getBrand(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.prisma.brandProfile.findUnique({ where: { id: this.brandId() } });
}
@Patch("brand")
updateBrand(@Req() request: FastifyRequest, @Body() body: UpdateBrandDto): Promise<unknown> {
this.requireAdmin(request);
const { config, ...fields } = body;
return this.prisma.brandProfile.update({
where: { id: this.brandId() },
data: {
...fields,
...(config ? { config: config as Prisma.InputJsonValue } : {}),
},
});
}
@Get("trust-content")
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.prisma.trustContent.findMany({
where: { brandId: this.brandId() },
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
});
}
@Post("trust-content")
createTrustContent(
@Req() request: FastifyRequest,
@Body() body: CreateTrustContentDto,
): Promise<unknown> {
this.requireAdmin(request);
const { config, ...fields } = body;
return this.prisma.trustContent.create({
data: {
...fields,
brandId: this.brandId(),
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
@Patch("trust-content/:id")
async updateTrustContent(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateTrustContentDto,
): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.trustContent.findFirst({
where: { id, brandId: this.brandId() },
});
if (!item) throw new BadRequestException("信任内容不存在");
const { config, ...fields } = body;
return this.prisma.trustContent.update({
where: { id },
data: {
...fields,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
@Delete("trust-content/:id")
async deleteTrustContent(
@Req() request: FastifyRequest,
@Param("id") id: string,
): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.trustContent.findFirst({
where: { id, brandId: this.brandId() },
});
if (!item) throw new BadRequestException("信任内容不存在");
await this.prisma.trustContent.delete({ where: { id } });
return { deleted: true };
}
}
@@ -236,12 +567,26 @@ export class AdminBookingController {
controllers: [
HealthController,
PublicController,
PublicTrustContentController,
PublicTemplateController,
PublicWorkspaceController,
PublicOfferingController,
PublicInquiryFormController,
CustomerInquirySubmissionController,
AdminWorkspaceController,
CustomerSessionController,
AdminSessionController,
CustomerBookingController,
AdminBookingController,
AdminConfigController,
],
providers: [
PrismaService,
WechatAuthService,
BookingService,
AdminAuthService,
TemplateWorkspaceService,
],
providers: [PrismaService, WechatAuthService, BookingService, AdminAuthService],
exports: [PrismaService, WechatAuthService],
})
export class AppModule {}
@@ -252,6 +597,8 @@ export async function createApp(): Promise<NestFastifyApplication> {
new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }),
);
app.useGlobalFilters(new ApiExceptionFilter());
const apiPrefix = process.env.API_PREFIX?.replace(/^\/+|\/+$/g, "");
if (apiPrefix) app.setGlobalPrefix(apiPrefix);
app.use(new RequestIdMiddleware().use.bind(new RequestIdMiddleware()));
app.enableCors();
return app;
+158
View File
@@ -0,0 +1,158 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { getBrandTemplate } from "@personal-brand/config";
import { PrismaService } from "./prisma.service.js";
@Injectable()
export class TemplateWorkspaceService {
constructor(private readonly prisma: PrismaService) {}
async install(brandId: string, templateKey: "personal" | "food") {
const template = getBrandTemplate(templateKey);
if (!template) throw new BadRequestException("行业模板不存在");
const existing = await this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } });
if (existing)
throw new BadRequestException(
existing.templateKey === templateKey
? "该模板已经安装"
: "品牌已经安装主模板,请先完成模板切换流程",
);
return this.prisma.$transaction(async (tx) => {
const installation = await tx.brandTemplateInstallation.create({
data: {
brandId,
templateKey,
templateVersion: template.version,
configSnapshot: template as unknown as Prisma.InputJsonValue,
},
});
await tx.brandModule.createMany({
data: template.modules.map(({ type, title }, sortOrder) => ({
brandId,
type,
title,
sortOrder,
source: "template",
})),
});
await tx.brandFieldDefinition.createMany({
data: template.fields.map(({ scope, key, label, type, required }, sortOrder) => ({
brandId,
scope,
key,
label,
type,
sortOrder,
source: "core",
required,
})),
});
return { installation, template };
});
}
private async installation(brandId: string) {
const item = await this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } });
if (!item) throw new BadRequestException("尚未安装行业模板");
return item;
}
async preview(brandId: string) {
const installation = await this.installation(brandId);
const template = getBrandTemplate(installation.templateKey);
if (!template) throw new BadRequestException("已安装模板不存在");
const [modules, fields] = await Promise.all([
this.prisma.brandModule.findMany({ where: { brandId } }),
this.prisma.brandFieldDefinition.findMany({ where: { brandId } }),
]);
return {
currentVersion: installation.templateVersion,
latestVersion: template.version,
canUpgrade: installation.templateVersion !== template.version,
canRollback:
Array.isArray(installation.previousSnapshots) && installation.previousSnapshots.length > 0,
missingModules: template.modules.filter(
(item) =>
!modules.some((current) => current.type === item.type && current.source === "template"),
),
missingFields: template.fields.filter(
(item) =>
!fields.some((current) => current.scope === item.scope && current.key === item.key),
),
};
}
async upgrade(brandId: string) {
const installation = await this.installation(brandId);
const template = getBrandTemplate(installation.templateKey);
if (!template) throw new BadRequestException("已安装模板不存在");
if (installation.templateVersion === template.version)
throw new BadRequestException("当前模板已经是最新版本");
return this.prisma.$transaction(async (tx) => {
const [modules, fields] = await Promise.all([
tx.brandModule.findMany({ where: { brandId } }),
tx.brandFieldDefinition.findMany({ where: { brandId } }),
]);
const addedModules = template.modules.filter(
(item) =>
!modules.some((current) => current.type === item.type && current.source === "template"),
);
const addedFields = template.fields.filter(
(item) =>
!fields.some((current) => current.scope === item.scope && current.key === item.key),
);
await tx.brandModule.createMany({
data: addedModules.map(({ type, title }, index) => ({
brandId,
type,
title,
sortOrder: modules.length + index,
source: "template",
})),
});
await tx.brandFieldDefinition.createMany({
data: addedFields.map(({ scope, key, label, type, required }, index) => ({
brandId,
scope,
key,
label,
type,
required,
sortOrder: fields.length + index,
source: "template",
})),
});
const history = Array.isArray(installation.previousSnapshots)
? installation.previousSnapshots
: [];
const updated = await tx.brandTemplateInstallation.update({
where: { id: installation.id },
data: {
templateVersion: template.version,
configSnapshot: template as unknown as Prisma.InputJsonValue,
previousSnapshots: [...history, installation.configSnapshot],
},
});
return { installation: updated, addedModules, addedFields };
});
}
async rollback(brandId: string) {
const installation = await this.installation(brandId);
const history = Array.isArray(installation.previousSnapshots)
? installation.previousSnapshots
: [];
const previous = history.at(-1);
if (!previous || typeof previous !== "object" || Array.isArray(previous))
throw new BadRequestException("没有可回滚的模板版本");
const version = (previous as { version?: unknown }).version;
if (typeof version !== "string") throw new BadRequestException("模板快照无效");
const updated = await this.prisma.brandTemplateInstallation.update({
where: { id: installation.id },
data: {
templateVersion: version,
configSnapshot: previous,
previousSnapshots: history.slice(0, -1),
},
});
return {
installation: updated,
note: "已恢复上一版模板配置基线,现有模块、字段和业务内容未删除。",
};
}
}
+5
View File
@@ -1,4 +1,9 @@
declare module "bcryptjs" {
const bcrypt: {
compare(password: string, hash: string): Promise<boolean>;
hash(password: string, saltRounds: number): Promise<string>;
};
export default bcrypt;
export function compare(password: string, hash: string): Promise<boolean>;
export function hash(password: string, saltRounds: number): Promise<string>;
}
+17 -5
View File
@@ -28,13 +28,25 @@ export class WechatAuthService {
js_code: code,
grant_type: "authorization_code",
});
const response = await fetch(
`https://api.weixin.qq.com/sns/jscode2session?${query.toString()}`,
);
if (!response.ok) throw new ServiceUnavailableException("微信登录服务暂时不可用");
let response: Response;
try {
response = await fetch(`https://api.weixin.qq.com/sns/jscode2session?${query.toString()}`);
} catch (error) {
console.error(
"wechat session request failed",
error instanceof Error ? error.message : error,
);
throw new ServiceUnavailableException("微信登录服务暂时不可用");
}
if (!response.ok) {
console.error("wechat session http error", response.status);
throw new ServiceUnavailableException("微信登录服务暂时不可用");
}
const result = (await response.json()) as WechatSessionResponse;
if (!result.openid || !result.session_key)
if (!result.openid || !result.session_key) {
console.warn("wechat session rejected", { errcode: result.errcode, errmsg: result.errmsg });
throw new UnauthorizedException(result.errmsg ?? "微信登录失败");
}
return {
openid: result.openid,
sessionKey: result.session_key,
+122
View File
@@ -0,0 +1,122 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { BadRequestException, NotFoundException } from "@nestjs/common";
import { BookingService } from "../src/booking.service.js";
const brandId = "brand-1";
const customerId = "customer-1";
const offering = {
id: "service-1",
name: "套餐",
priceAmount: 2800,
};
function createPrisma(overrides: Record<string, unknown> = {}): any {
return {
offering: {
findMany: async () => [offering],
},
booking: {
create: async ({ data }: any) => ({
bookingNo: "AC-test",
status: "received",
estimatedAmount: data.estimatedAmount,
createdAt: new Date(),
}),
findFirst: async () => null,
update: async ({ data }: any) => ({ status: data.status }),
findMany: async () => [],
count: async () => 0,
},
tag: { findMany: async () => [] },
bookingTag: { deleteMany: {}, createMany: {} },
$transaction: async (callback: (tx: unknown) => unknown) => callback(undefined),
...overrides,
};
}
test("创建普通套餐订单时保存价格快照和预计金额", async () => {
const prisma = createPrisma();
const result = await new BookingService(prisma).create(brandId, customerId, {
requestType: "package",
customerName: "陈同学",
wechatId: "wx-test",
contactPreference: "wechat",
items: [{ offeringId: offering.id, quantity: 2 }],
});
assert.equal(result.estimatedAmount, 5600);
assert.equal(result.status, "received");
});
test("普通套餐不能在没有明细时创建", async () => {
await assert.rejects(
() =>
new BookingService(createPrisma()).create(brandId, customerId, {
requestType: "package",
customerName: "陈同学",
phone: "13800000000",
contactPreference: "phone",
}),
(error: unknown) => error instanceof BadRequestException,
);
});
test("客户只能取消自己的 received 订单", async () => {
const prisma = createPrisma({
booking: {
findFirst: async () => ({ id: "booking-1", status: "confirmed" }),
update: async () => ({ status: "cancelled" }),
},
});
await assert.rejects(
() => new BookingService(prisma).cancelForCustomer(brandId, customerId, "booking-1"),
(error: unknown) => error instanceof BadRequestException,
);
});
test("取消不存在或不属于当前客户的订单返回不存在", async () => {
await assert.rejects(
() => new BookingService(createPrisma()).cancelForCustomer(brandId, customerId, "missing"),
(error: unknown) => error instanceof NotFoundException,
);
});
test("订单状态只能按定义的状态机流转", async () => {
const prisma = createPrisma({
booking: {
findFirst: async () => ({
id: "booking-1",
status: "received",
currentState: "received",
workflowKey: "booking.basic",
workflowVersion: "1.0.0",
}),
update: async ({ data }: any) => data,
},
$transaction: async (callback: (tx: any) => unknown) =>
callback({
booking: { update: async ({ data }: any) => data },
bookingStateTransition: { create: async () => undefined },
}),
});
const bookings = new BookingService(prisma);
assert.equal(
(await bookings.updateStatus(brandId, "booking-1", "contacting")).status,
"contacting",
);
await assert.rejects(
() => bookings.updateStatus(brandId, "booking-1", "completed"),
(error: unknown) => error instanceof BadRequestException,
);
});
test("更新订单标签时拒绝其他品牌的标签", async () => {
const prisma = createPrisma({
booking: { findFirst: async () => ({ id: "booking-1", brandId }) },
tag: { findMany: async () => [] },
});
await assert.rejects(
() => new BookingService(prisma).updateTags(brandId, "booking-1", ["foreign-tag"]),
(error: unknown) => error instanceof BadRequestException,
);
});
+703
View File
@@ -0,0 +1,703 @@
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";
let app;
const prisma = new PrismaClient();
const brandId = process.env.DEFAULT_BRAND_ID;
const openid = `integration-${Date.now()}`;
let customerToken;
const createdBookingIds = [];
before(async () => {
await prisma.customerUser.create({ data: { brandId, openid } });
customerToken = signIdentity({ subject: openid, brandId, role: "customer" });
app = await createApp();
await app.init();
});
after(async () => {
await app.close();
await prisma.booking.deleteMany({ where: { id: { in: createdBookingIds } } });
await prisma.customerUser.deleteMany({ where: { openid } });
await prisma.$disconnect();
});
async function request(url, options = {}) {
return app
.getHttpAdapter()
.getInstance()
.inject({ method: "GET", url, ...options });
}
test("health and public content are available without authentication", async () => {
const health = await request("/health");
assert.equal(health.statusCode, 200);
assert.deepEqual(JSON.parse(health.body), { status: "ok", service: "personal-brand-api" });
const brand = await request("/public/brand");
assert.equal(brand.statusCode, 200);
assert.equal(JSON.parse(brand.body).name, "阿成家常菜");
const services = await request("/public/offerings");
assert.equal(services.statusCode, 200);
assert.ok(JSON.parse(services.body).length >= 3);
const removedServicesRoute = await request("/public/services");
assert.equal(removedServicesRoute.statusCode, 404);
});
test("admin can install a template and public workspace exposes enabled configuration", async () => {
await prisma.inquirySubmission.deleteMany({ where: { brandId } });
await prisma.inquiryForm.deleteMany({ where: { brandId } });
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandModule.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
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 before = await request("/admin/workspace");
assert.equal(before.statusCode, 401);
const installed = await request("/admin/workspace/install", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { templateKey: "personal" },
});
assert.equal(installed.statusCode, 201);
assert.equal(JSON.parse(installed.body).template.key, "personal");
try {
const previewUnauthorized = await request("/admin/workspace/template/preview");
assert.equal(previewUnauthorized.statusCode, 401);
const preview = await request("/admin/workspace/template/preview", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(preview.statusCode, 200);
assert.equal(JSON.parse(preview.body).canUpgrade, false);
const rollbackUnauthorized = await request("/admin/workspace/template/rollback", {
method: "POST",
});
assert.equal(rollbackUnauthorized.statusCode, 401);
const installedRecord = JSON.parse(installed.body).installation;
await prisma.brandTemplateInstallation.update({
where: { id: installedRecord.id },
data: {
templateVersion: "2.0.0",
previousSnapshots: [installedRecord.configSnapshot],
},
});
const rollback = await request("/admin/workspace/template/rollback", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
});
assert.equal(rollback.statusCode, 201);
assert.equal(JSON.parse(rollback.body).installation.templateVersion, "1.0.0");
assert.equal(JSON.parse(rollback.body).installation.previousSnapshots.length, 0);
assert.match(JSON.parse(rollback.body).note, /配置基线/);
const workspace = await request("/admin/workspace", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(workspace.statusCode, 200);
assert.equal(JSON.parse(workspace.body).installations.length, 1);
assert.equal(JSON.parse(workspace.body).fields.length, 5);
const publicWorkspace = await request("/public/workspace");
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, ["offerings", "inquiry"]);
assert.deepEqual(workspaceBody.runtimeCapabilities, [
{ key: "offerings", version: "1.0.0" },
{ key: "inquiry", version: "1.0.0" },
]);
assert.equal(workspaceBody.modules.length, 5);
assert.equal(workspaceBody.runtimeModules.length, 5);
assert.equal(workspaceBody.runtimeModules[0].schemaVersion, "1.0");
assert.equal(workspaceBody.inquiryForm, null);
const conflict = await request("/admin/workspace/install", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { templateKey: "food" },
});
assert.equal(conflict.statusCode, 400);
} finally {
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandModule.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
}
});
test("admin can customize workspace modules and fields with brand isolation", async () => {
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandModule.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
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 install = await request("/admin/workspace/install", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { templateKey: "food" },
});
assert.equal(install.statusCode, 201);
const workspace = await request("/admin/workspace", {
headers: { authorization: `Bearer ${token}` },
});
const moduleId = JSON.parse(workspace.body).modules[0].id;
const invalidField = await request("/admin/workspace/fields", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { scope: "unknown", key: "Bad-Key", label: "非法字段", type: "text" },
});
assert.equal(invalidField.statusCode, 400);
const updatedModule = await request(`/admin/workspace/modules/${moduleId}`, {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { title: "我的品牌介绍", isEnabled: false },
});
assert.equal(updatedModule.statusCode, 200);
const createdField = await request("/admin/workspace/fields", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: {
scope: "profile",
key: `region_${Date.now()}`,
label: "服务区域",
type: "text",
required: false,
},
});
assert.equal(createdField.statusCode, 201);
const fieldId = JSON.parse(createdField.body).id;
try {
const updatedField = await request(`/admin/workspace/fields/${fieldId}`, {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { label: "主要服务区域", visibleWhen: { mode: "all", rules: [] } },
});
assert.equal(updatedField.statusCode, 200);
const deletedField = await request(`/admin/workspace/fields/${fieldId}`, {
method: "DELETE",
headers: { authorization: `Bearer ${token}` },
});
assert.equal(deletedField.statusCode, 200);
} finally {
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandModule.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
}
});
test("admin can create and version an inquiry form", 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 offering = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } });
assert.ok(offering);
const created = await request("/admin/workspace/forms", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: {
name: "品牌合作咨询",
offeringId: offering.id,
fieldsSnapshot: [{ key: "project", type: "textarea", label: "项目背景", required: true }],
},
});
assert.equal(created.statusCode, 201);
const id = JSON.parse(created.body).id;
try {
const updated = await request(`/admin/workspace/forms/${id}`, {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { fieldsSnapshot: [{ key: "budget", type: "number", label: "预算" }] },
});
assert.equal(updated.statusCode, 200);
assert.equal(JSON.parse(updated.body).version, 2);
await prisma.offering.update({ where: { id: offering.id }, data: { isEnabled: false } });
assert.equal((await request(`/public/inquiry-forms/${id}`)).statusCode, 400);
const blockedSubmission = await request("/customer/inquiry-submissions", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: { formId: id, values: { budget: 1000 } },
});
assert.equal(blockedSubmission.statusCode, 400);
await prisma.offering.update({ where: { id: offering.id }, data: { isEnabled: true } });
const publicForm = await request(`/public/inquiry-forms/${id}`);
assert.equal(publicForm.statusCode, 200);
const publicOffering = await request(`/public/offerings/${offering.id}`);
assert.equal(publicOffering.statusCode, 200);
assert.equal(JSON.parse(publicOffering.body).inquiryForms[0].id, id);
const publicWorkspace = await request("/public/workspace");
assert.equal(publicWorkspace.statusCode, 200);
assert.equal(JSON.parse(publicWorkspace.body).inquiryForm.id, id);
const submission = await request("/customer/inquiry-submissions", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: { formId: id, values: { project: "品牌升级" } },
});
assert.equal(submission.statusCode, 201);
assert.equal(JSON.parse(submission.body).formVersion, 2);
assert.equal(JSON.parse(submission.body).offeringId, offering.id);
const adminSubmissionsWithoutToken = await request("/admin/workspace/submissions");
assert.equal(adminSubmissionsWithoutToken.statusCode, 401);
const adminSubmissions = await request("/admin/workspace/submissions", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(adminSubmissions.statusCode, 200);
assert.ok(
JSON.parse(adminSubmissions.body).some((item) => item.id === JSON.parse(submission.body).id),
);
const savedSubmission = JSON.parse(adminSubmissions.body).find(
(item) => item.id === JSON.parse(submission.body).id,
);
assert.equal(savedSubmission.offering.id, offering.id);
const customerUpdate = await request(`/admin/workspace/submissions/${savedSubmission.id}`, {
method: "PATCH",
headers: { authorization: `Bearer ${customerToken}` },
payload: { status: "replied" },
});
assert.equal(customerUpdate.statusCode, 403);
const updatedSubmission = await request(`/admin/workspace/submissions/${savedSubmission.id}`, {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { status: "reviewing", adminNote: "已开始评估需求" },
});
assert.equal(updatedSubmission.statusCode, 200);
assert.equal(JSON.parse(updatedSubmission.body).status, "reviewing");
assert.equal(JSON.parse(updatedSubmission.body).adminNote, "已开始评估需求");
const history = await prisma.inquirySubmissionStatusHistory.findMany({
where: { submissionId: savedSubmission.id },
});
assert.equal(history.length, 1);
assert.equal(history[0].toStatus, "reviewing");
} finally {
await prisma.inquirySubmission.deleteMany({ where: { inquiryFormId: id } });
await prisma.inquiryForm.delete({ where: { id } });
}
});
test("admin can manage offerings and public endpoint hides disabled offerings", 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 invalidConfig = await request("/admin/workspace/offerings", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: {
kind: "product",
name: `无效配置-${Date.now()}`,
config: { sections: "必须是数组" },
},
});
assert.equal(invalidConfig.statusCode, 400);
const created = await request("/admin/workspace/offerings", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: {
kind: "product",
name: `测试提供项-${Date.now()}`,
summary: "测试摘要",
isEnabled: true,
},
});
assert.equal(created.statusCode, 201);
const id = JSON.parse(created.body).id;
try {
const listed = await request("/admin/workspace/offerings", {
headers: { authorization: `Bearer ${token}` },
});
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);
const publicList = await request("/public/offerings");
assert.equal(publicList.statusCode, 200);
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}` },
payload: { isEnabled: false },
});
assert.equal(updated.statusCode, 200);
const hidden = await request(`/public/offerings/${id}`);
assert.equal(hidden.statusCode, 400);
const reenabled = await request(`/admin/workspace/offerings/${id}`, {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { isEnabled: true },
});
assert.equal(reenabled.statusCode, 200);
assert.equal((await request(`/public/offerings/${id}`)).statusCode, 200);
} finally {
const deleted = await request(`/admin/workspace/offerings/${id}`, {
method: "DELETE",
headers: { authorization: `Bearer ${token}` },
});
assert.equal(deleted.statusCode, 200);
assert.equal(await prisma.offering.findUnique({ where: { id } }), null);
}
});
test("offering with an inquiry form cannot be deleted", 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 offering = await prisma.offering.create({
data: { brandId, kind: "service", name: `保护测试-${Date.now()}`, description: "测试" },
});
const form = await prisma.inquiryForm.create({
data: { brandId, offeringId: offering.id, name: "保护测试表单", fieldsSnapshot: [] },
});
try {
const response = await request(`/admin/workspace/offerings/${offering.id}`, {
method: "DELETE",
headers: { authorization: `Bearer ${token}` },
});
assert.equal(response.statusCode, 400);
} finally {
await prisma.inquiryForm.delete({ where: { id: form.id } });
await prisma.offering.delete({ where: { id: offering.id } });
}
});
test("admin booking endpoints reject missing or customer credentials", async () => {
const missing = await request("/admin/bookings");
assert.equal(missing.statusCode, 401);
const customer = await request("/admin/bookings", {
headers: { authorization: "Bearer invalid-token" },
});
assert.equal(customer.statusCode, 401);
});
test("seeded admin can log in and read protected booking resources", async () => {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
assert.equal(login.statusCode, 201);
const token = JSON.parse(login.body).token;
assert.ok(token);
const count = await request("/admin/bookings/unread-count", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(count.statusCode, 200);
assert.equal(typeof JSON.parse(count.body).count, "number");
const tags = await request("/admin/bookings/tags", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(tags.statusCode, 200);
assert.equal(JSON.parse(tags.body).length, 6);
});
test("admin login validates credentials", async () => {
const response = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: "wrong-password" },
});
assert.equal(response.statusCode, 401);
});
test("admin can read and update brand and service configuration", async () => {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const adminToken = JSON.parse(login.body).token;
const removedAdminRoute = await request("/admin/config/services", {
headers: { authorization: `Bearer ${adminToken}` },
});
assert.equal(removedAdminRoute.statusCode, 404);
assert.ok(adminToken);
const unauthorized = await request("/admin/config/brand");
assert.equal(unauthorized.statusCode, 401);
const brandBefore = await prisma.brandProfile.findUnique({ where: { id: brandId } });
assert.ok(brandBefore);
const serviceBefore = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } });
assert.ok(serviceBefore);
let createdServiceId;
try {
const brand = await request("/admin/config/brand", {
headers: { authorization: `Bearer ${adminToken}` },
});
assert.equal(brand.statusCode, 200);
assert.equal(JSON.parse(brand.body).id, brandId);
const updatedBrand = await request("/admin/config/brand", {
method: "PATCH",
headers: { authorization: `Bearer ${adminToken}` },
payload: {
description: "集成测试品牌简介",
contactPhone: "13800000000",
templateKey: "personal",
},
});
assert.equal(updatedBrand.statusCode, 200);
assert.equal(JSON.parse(updatedBrand.body).description, "集成测试品牌简介");
assert.equal(JSON.parse(updatedBrand.body).templateKey, "personal");
const updatedService = await request(`/admin/workspace/offerings/${serviceBefore.id}`, {
method: "PATCH",
headers: { authorization: `Bearer ${adminToken}` },
payload: { priceText: "集成测试价格", sortOrder: 99 },
});
assert.equal(updatedService.statusCode, 200);
assert.equal(JSON.parse(updatedService.body).priceText, "集成测试价格");
assert.equal(JSON.parse(updatedService.body).sortOrder, 99);
const publicServices = await request("/public/offerings");
assert.equal(publicServices.statusCode, 200);
const projectedService = JSON.parse(publicServices.body).find(
(item) => item.id === serviceBefore.id,
);
assert.equal(projectedService.priceText, "集成测试价格");
const listedServices = await request("/admin/workspace/offerings", {
headers: { authorization: `Bearer ${adminToken}` },
});
assert.equal(listedServices.statusCode, 200);
assert.ok(JSON.parse(listedServices.body).some((item) => item.id === serviceBefore.id));
const createdService = await request("/admin/workspace/offerings", {
method: "POST",
headers: { authorization: `Bearer ${adminToken}` },
payload: {
name: "集成测试通用服务",
description: "通用品牌服务",
kind: "service",
config: { duration: 60 },
},
});
assert.equal(createdService.statusCode, 201);
const createdServiceBody = JSON.parse(createdService.body);
createdServiceId = createdServiceBody.id;
assert.equal(createdServiceBody.kind, "service");
const createdOffering = await prisma.offering.findUnique({
where: { id: createdServiceBody.id },
});
assert.equal(createdOffering?.name, "集成测试通用服务");
} finally {
await prisma.brandProfile.update({
where: { id: brandId },
data: {
description: brandBefore.description,
contactPhone: brandBefore.contactPhone,
templateKey: brandBefore.templateKey,
},
});
await prisma.offering.update({
where: { id: serviceBefore.id },
data: { priceText: serviceBefore.priceText, sortOrder: serviceBefore.sortOrder },
});
if (createdServiceId) {
await prisma.offering.delete({ where: { id: createdServiceId } });
}
}
});
test("admin can manage trust content", 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;
assert.equal((await request("/admin/config/trust-content")).statusCode, 401);
const created = await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { type: "profile", title: "关于我", content: "集成测试内容", summary: "测试摘要" },
});
assert.equal(created.statusCode, 201);
const id = JSON.parse(created.body).id;
const draft = await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { type: "experience", title: "草稿", content: "不应公开", isPublished: false },
});
assert.equal(draft.statusCode, 201);
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 === JSON.parse(draft.body).id));
try {
const list = await request("/admin/config/trust-content", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(list.statusCode, 200);
const updated = await request(`/admin/config/trust-content/${id}`, {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { content: "更新后的内容" },
});
assert.equal(updated.statusCode, 200);
assert.equal(JSON.parse(updated.body).content, "更新后的内容");
} finally {
const deleted = await request(`/admin/config/trust-content/${id}`, {
method: "DELETE",
headers: { authorization: `Bearer ${token}` },
});
assert.equal(deleted.statusCode, 200);
await prisma.trustContent.delete({ where: { id: JSON.parse(draft.body).id } });
}
});
test("customer booking endpoints require a valid customer session", async () => {
const missing = await request("/customer/bookings");
assert.equal(missing.statusCode, 400);
const list = await request("/customer/bookings", {
headers: { authorization: `Bearer ${customerToken}` },
});
assert.equal(list.statusCode, 200);
assert.deepEqual(JSON.parse(list.body), []);
});
test("wechat login validates the request DTO before exchanging the code", async () => {
const response = await request("/customer/session/wechat", {
method: "POST",
payload: {},
});
assert.equal(response.statusCode, 400);
});
test("customer booking DTO rejects incomplete package requests", async () => {
const response = await request("/customer/bookings", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: {
requestType: "package",
customerName: "集成测试客户",
contactPreference: "wechat",
},
});
assert.equal(response.statusCode, 400);
assert.equal(JSON.parse(response.body).error.code, "HTTP_400");
});
test("customer can create a generic inquiry without food-specific fields", async () => {
const response = await request("/customer/bookings", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: {
requestType: "inquiry",
customerName: "个人品牌咨询客户",
wechatId: "inquiry-wechat",
contactPreference: "wechat",
requestedTime: "下周三 14:00",
note: "希望讨论品牌合作方案",
},
});
assert.equal(response.statusCode, 201);
const body = JSON.parse(response.body);
const booking = await prisma.booking.findUnique({ where: { bookingNo: body.bookingNo } });
assert.ok(booking);
assert.equal(booking.requestType, "inquiry");
createdBookingIds.push(booking.id);
});
test("customer can create and cancel a package booking", async () => {
const service = await prisma.offering.findFirst({
where: { brandId, isEnabled: true, priceAmount: { not: null } },
});
assert.ok(service);
const created = await request("/customer/bookings", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: {
requestType: "package",
customerName: "集成测试客户",
wechatId: "integration-wechat",
contactPreference: "wechat",
items: [{ offeringId: service.id, quantity: 2 }],
},
});
assert.equal(created.statusCode, 201);
const createdBody = JSON.parse(created.body);
assert.equal(createdBody.estimatedAmount, service.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 initialTransitions = await prisma.bookingStateTransition.findMany({
where: { bookingId: booking.id },
});
assert.equal(initialTransitions.length, 1);
assert.equal(initialTransitions[0].toState, "received");
createdBookingIds.push(booking.id);
const cancelled = await request(`/customer/bookings/${booking.id}/cancel`, {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
});
assert.equal(cancelled.statusCode, 201);
assert.equal(JSON.parse(cancelled.body).status, "cancelled");
const transitions = await prisma.bookingStateTransition.findMany({
where: { bookingId: booking.id },
orderBy: { createdAt: "asc" },
});
assert.deepEqual(
transitions.map((item) => item.toState),
["received", "cancelled"],
);
});
test("admin can advance booking status but cannot skip the state machine", async () => {
const service = await prisma.offering.findFirst({
where: { brandId, isEnabled: true, priceAmount: { not: null } },
});
assert.ok(service);
const created = await request("/customer/bookings", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: {
requestType: "package",
customerName: "状态测试客户",
phone: "13800000000",
contactPreference: "phone",
items: [{ offeringId: service.id, quantity: 1 }],
},
});
const booking = await prisma.booking.findUnique({
where: { bookingNo: JSON.parse(created.body).bookingNo },
});
assert.ok(booking);
createdBookingIds.push(booking.id);
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const adminToken = JSON.parse(login.body).token;
const contacting = await request(`/admin/bookings/${booking.id}/status`, {
method: "POST",
headers: { authorization: `Bearer ${adminToken}` },
payload: { status: "contacting", adminNote: "已联系客户" },
});
assert.equal(contacting.statusCode, 201);
assert.equal(JSON.parse(contacting.body).status, "contacting");
const contactingState = await prisma.booking.findUnique({ where: { id: booking.id } });
assert.equal(contactingState?.currentState, "contacting");
const skipped = await request(`/admin/bookings/${booking.id}/status`, {
method: "POST",
headers: { authorization: `Bearer ${adminToken}` },
payload: { status: "completed" },
});
assert.equal(skipped.statusCode, 400);
});
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": true,
"rootDir": ".."
},
"include": ["./**/*.ts"]
}
+11
View File
@@ -0,0 +1,11 @@
const DEFAULT_API_BASE_URL = "http://172.16.6.123:3001";
App({
onLaunch() {
this.globalData = {
apiBaseUrl: wx.getStorageSync("apiBaseUrl") || DEFAULT_API_BASE_URL,
brand: {},
};
},
globalData: {},
});
+42
View File
@@ -0,0 +1,42 @@
{
"pages": [
"pages/index/index",
"pages/services/index",
"pages/booking/index",
"pages/bookings/index",
"pages/offering/detail",
"pages/inquiry/index"
],
"window": {
"navigationBarTitleText": "个人品牌",
"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"
}
]
}
}
+7
View File
@@ -0,0 +1,7 @@
@import "styles/tokens.wxss";
page {
background: var(--brand-color-bg);
color: var(--brand-color-text);
font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1022 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 794 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 769 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 913 B

@@ -0,0 +1,15 @@
Component({
options: { addGlobalClass: true },
properties: {
theme: { type: String, value: "primary" },
size: { type: String, value: "large" },
disabled: Boolean,
loading: Boolean,
block: { type: Boolean, value: true },
},
methods: {
handleTap(event) {
if (!this.data.disabled && !this.data.loading) this.triggerEvent("tap", event.detail);
},
},
});
@@ -0,0 +1,6 @@
{
"component": true,
"usingComponents": {
"t-button": "tdesign-miniprogram/button/button"
}
}
@@ -0,0 +1 @@
<t-button theme="{{theme}}" size="{{size}}" block="{{block}}" disabled="{{disabled}}" loading="{{loading}}" bind:tap="handleTap"><slot /></t-button>
@@ -0,0 +1,8 @@
:host {
display: block;
}
t-button {
--td-button-primary-bg-color: var(--brand-color-primary);
--td-button-primary-active-bg-color: var(--brand-color-primary-dark);
--td-button-radius: var(--brand-radius-control);
}
@@ -0,0 +1 @@
Component({ options: { addGlobalClass: true } });
@@ -0,0 +1 @@
{ "component": true }
@@ -0,0 +1 @@
<view class="card"><slot /></view>
@@ -0,0 +1,7 @@
.card {
padding: 28rpx;
background: var(--brand-color-surface);
border: 1rpx solid rgba(122, 74, 43, 0.1);
border-radius: var(--brand-radius-card);
box-shadow: 0 8rpx 24rpx rgba(122, 74, 43, 0.06);
}
@@ -0,0 +1 @@
Component({ properties: { description: { type: String, value: "暂无内容" } } });
@@ -0,0 +1 @@
{ "component": true, "usingComponents": { "t-empty": "tdesign-miniprogram/empty/empty" } }
@@ -0,0 +1 @@
<t-empty description="{{description}}" />
@@ -0,0 +1,3 @@
t-empty {
--td-empty-description-color: var(--brand-color-muted);
}
@@ -0,0 +1,19 @@
Component({
options: { addGlobalClass: true },
properties: {
label: String,
value: { type: String, value: "" },
placeholder: String,
type: { type: String, value: "text" },
required: Boolean,
maxlength: { type: Number, value: -1 },
},
methods: {
handleChange(event) {
this.triggerEvent("change", event.detail);
},
handleBlur(event) {
this.triggerEvent("blur", event.detail);
},
},
});
@@ -0,0 +1,7 @@
{
"component": true,
"usingComponents": {
"t-input": "tdesign-miniprogram/input/input",
"t-textarea": "tdesign-miniprogram/textarea/textarea"
}
}
@@ -0,0 +1 @@
<view class="field"><view wx:if="{{label}}" class="label">{{label}}<text wx:if="{{required}}" class="required"> *</text></view><view class="field-control"><t-textarea wx:if="{{type === 'textarea'}}" value="{{value}}" placeholder="{{placeholder}}" maxlength="{{maxlength}}" bind:change="handleChange" bind:blur="handleBlur" /><t-input wx:else value="{{value}}" type="{{type}}" placeholder="{{placeholder}}" maxlength="{{maxlength}}" bind:change="handleChange" bind:blur="handleBlur" /></view></view>
@@ -0,0 +1,30 @@
.field {
margin-bottom: 24rpx;
}
.label {
margin-bottom: 12rpx;
color: var(--brand-color-text);
font-size: 28rpx;
font-weight: 600;
}
.required {
color: var(--brand-color-primary);
}
.field-control {
padding: 4rpx 20rpx;
background: var(--brand-color-surface);
border: 1rpx solid #eadfce;
border-radius: var(--brand-radius-control);
}
t-input,
t-textarea {
--td-input-vertical-padding: 20rpx;
--td-input-bg-color: transparent;
--td-input-border-color: transparent;
--td-input-default-text-color: var(--brand-color-text);
--td-input-placeholder-text-color: #a98f7b;
--td-textarea-background-color: transparent;
--td-textarea-border-color: transparent;
--td-textarea-text-color: var(--brand-color-text);
--td-textarea-placeholder-color: #a98f7b;
}
@@ -0,0 +1 @@
Component({ properties: { text: { type: String, value: "加载中…" } } });
@@ -0,0 +1 @@
{ "component": true, "usingComponents": { "t-loading": "tdesign-miniprogram/loading/loading" } }
@@ -0,0 +1 @@
<view class="loading"><t-loading size="48rpx" text="{{text}}" layout="vertical" /></view>
@@ -0,0 +1,6 @@
.loading {
padding: 96rpx 0;
display: flex;
justify-content: center;
color: var(--brand-color-muted);
}
+6 -1
View File
@@ -2,8 +2,13 @@
"name": "@personal-brand/miniapp",
"private": true,
"type": "module",
"dependencies": {
"@personal-brand/api-client": "workspace:*",
"@personal-brand/types": "workspace:*",
"tdesign-miniprogram": "^1.16.1"
},
"scripts": {
"lint": "eslint . --ext .ts",
"lint": "eslint src --ext .ts",
"typecheck": "tsc -p tsconfig.json --noEmit",
"clean": "rimraf dist"
}
+92
View File
@@ -0,0 +1,92 @@
const { request, customerRequest } = require("../../utils/request");
const { getTemplate } = require("../../utils/templates");
Page({
data: {
service: {},
form: {},
offeringId: "",
quantity: 1,
fulfillment: "pickup",
submitting: false,
template: getTemplate("personal"),
},
onLoad(query) {
Promise.all([request("/public/offerings"), request("/public/brand")])
.then(([services, brand]) => {
const list = Array.isArray(services) ? services : [];
const service =
list.find((item) => item.id === query.offeringId || item.id === query.serviceId) ||
list.find((item) => item.priceAmount !== null) ||
{};
this.setData({
service,
offeringId: service.id || "",
template: getTemplate(brand.templateKey),
});
})
.catch(() => wx.showToast({ title: "服务加载失败", icon: "none" }));
},
input(event) {
this.setData({ ["form." + event.currentTarget.dataset.key]: event.detail.value });
},
chooseFulfillment(event) {
this.setData({ fulfillment: event.currentTarget.dataset.value });
},
increase() {
if (this.data.quantity < 50) this.setData({ quantity: this.data.quantity + 1 });
},
decrease() {
if (this.data.quantity > 1) this.setData({ quantity: this.data.quantity - 1 });
},
submit() {
const form = this.data.form;
if (!this.data.offeringId) return wx.showToast({ title: "请先选择服务", icon: "none" });
if (!form.customerName || !form.wechatId)
return wx.showToast({ title: "请填写称呼和联系方式", icon: "none" });
if (this.data.fulfillment === "delivery" && !form.deliveryAddress)
return wx.showToast({ title: "请填写" + this.data.template.locationLabel, icon: "none" });
this.setData({ submitting: true });
const send = () =>
customerRequest("/customer/bookings", {
method: "POST",
data: {
requestType: this.data.template.requestType,
customerName: form.customerName,
wechatId: form.wechatId,
contactPreference: "wechat",
fulfillmentType: this.data.fulfillment,
deliveryAddress: form.deliveryAddress,
requestedTime: form.requestedTime,
note: form.note,
items: [{ offeringId: this.data.offeringId, quantity: this.data.quantity }],
},
})
.then(() => {
this.setData({ submitting: false });
wx.showToast({ title: "预约已提交" });
setTimeout(() => wx.navigateTo({ url: "/pages/bookings/index" }), 500);
})
.catch((error) => {
this.setData({ submitting: false });
wx.showToast({ title: error.message || "提交失败", icon: "none" });
});
const token = wx.getStorageSync("customerToken");
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);
send();
})
.catch((error) => {
this.setData({ submitting: false });
wx.showToast({ title: error.message || "微信登录失败", icon: "none" });
}),
fail: (error) => {
this.setData({ submitting: false });
wx.showToast({ title: error.errMsg || "微信登录失败", icon: "none" });
},
});
},
});
+10
View File
@@ -0,0 +1,10 @@
{
"navigationBarTitleText": "提交需求",
"navigationBarBackgroundColor": "#FBF7F1",
"navigationBarTextStyle": "black",
"usingComponents": {
"brand-button": "/components/ui/brand-button/brand-button",
"brand-field": "/components/ui/brand-field/brand-field",
"brand-card": "/components/ui/brand-card/brand-card"
}
}
+7
View File
@@ -0,0 +1,7 @@
<view class="page">
<view class="product"><view class="product-image"><image wx:if="{{service.coverUrl}}" src="{{service.coverUrl}}" mode="aspectFill"/><view wx:else class="dish-placeholder"></view></view><view class="product-copy"><text class="name">{{service.name || '选择服务'}}</text><text class="price">{{service.priceText || '沟通报价'}}</text></view><text class="available">{{template.available}}</text></view>
<view class="quantity"><text>数量</text><view class="stepper"><button bindtap="decrease">−</button><text>{{quantity}} 份</text><button bindtap="increase">+</button></view></view>
<view class="fulfillment"><text class="field-title">{{template.modeLabel}}</text><view class="choices"><button class="choice {{fulfillment === 'pickup' ? 'active' : ''}}" data-value="pickup" bindtap="chooseFulfillment">{{template.modeA}}</button><button class="choice {{fulfillment === 'delivery' ? 'active' : ''}}" data-value="delivery" bindtap="chooseFulfillment">{{template.modeB}}</button></view></view>
<brand-card><view class="form"><brand-field label="怎么称呼" placeholder="请输入你的称呼" required value="{{form.customerName}}" bind:change="input" data-key="customerName"/><brand-field label="联系方式" placeholder="手机号或微信号" required value="{{form.wechatId}}" bind:change="input" data-key="wechatId"/><brand-field label="期望时间" placeholder="例如:下周三 14:00" value="{{form.requestedTime}}" bind:change="input" data-key="requestedTime"/><brand-field wx:if="{{fulfillment === 'delivery'}}" label="{{template.locationLabel}}" placeholder="{{template.locationPlaceholder}}" value="{{form.deliveryAddress}}" bind:change="input" data-key="deliveryAddress"/><brand-field label="{{template.requestType === 'package' ? '备注' : '需求说明'}}" placeholder="{{template.notePlaceholder}}" type="textarea" value="{{form.note}}" bind:change="input" data-key="note"/></view></brand-card>
<view class="notice">● {{template.submitNotice}}</view><brand-button loading="{{submitting}}" disabled="{{submitting}}" bind:tap="submit">{{submitting ? '提交中...' : template.submitLabel}}</brand-button>
</view>
+138
View File
@@ -0,0 +1,138 @@
.page {
min-height: 100vh;
padding: 24rpx 32rpx 60rpx;
background: #fbf7f1;
color: #2b2b2b;
}
.product {
display: flex;
align-items: center;
gap: 20rpx;
padding: 20rpx;
background: #f4ebd9;
border-radius: 16rpx;
}
.product-image {
width: 220rpx;
height: 180rpx;
overflow: hidden;
border-radius: 12rpx;
flex: none;
}
.product-image image,
.dish-placeholder {
width: 100%;
height: 100%;
display: block;
background: #c79555;
}
.product-copy {
flex: 1;
}
.name {
display: block;
font-size: 34rpx;
font-weight: 700;
}
.price {
display: block;
margin-top: 18rpx;
color: #b54a2c;
font-size: 38rpx;
}
.available {
color: #7a4a2b;
font-size: 26rpx;
white-space: nowrap;
align-self: flex-start;
margin-top: 14rpx;
}
.quantity,
.fulfillment {
margin-top: 20rpx;
padding: 28rpx;
background: #f4ebd9;
border-radius: 16rpx;
font-size: 32rpx;
}
.stepper {
float: right;
display: flex;
align-items: center;
gap: 18rpx;
}
.stepper button {
width: 56rpx;
height: 56rpx;
line-height: 52rpx;
padding: 0;
border-radius: 50%;
background: #fff;
color: #b54a2c;
}
.field-title {
font-weight: 700;
}
.choices {
display: flex;
gap: 16rpx;
margin-top: 18rpx;
}
.choice {
flex: 1;
border-radius: 12rpx;
background: #7a4a2b;
color: #fff;
}
.choice.active {
background: #b54a2c;
}
.form {
margin-top: 20rpx;
background: #fff;
border-radius: 16rpx;
padding: 8rpx 28rpx;
}
.form label {
display: flex;
justify-content: space-between;
gap: 20rpx;
padding: 28rpx 0;
border-bottom: 1rpx solid #eee;
font-size: 30rpx;
}
.form input,
.form textarea {
flex: 1;
text-align: right;
}
.form textarea {
min-height: 100rpx;
}
.notice {
margin: 20rpx 0;
padding: 24rpx;
background: #f4ebd9;
border-radius: 16rpx;
color: #7a4a2b;
}
.submit {
background: #b54a2c;
color: #fff;
border-radius: 12rpx;
font-size: 34rpx;
}
.stepper button {
display: flex;
width: 64rpx;
height: 64rpx;
align-items: center;
justify-content: center;
padding: 0;
border: 0;
border-radius: 16rpx;
background: #fff;
color: #b54a2c;
font-size: 40rpx;
line-height: 1;
}
+72
View File
@@ -0,0 +1,72 @@
const { request, customerRequest } = require("../../utils/request");
const { bookingViewModel } = require("../../utils/labels");
const { getTemplate } = require("../../utils/templates");
Page({
data: {
loading: true,
error: "",
bookings: [],
cancellingId: "",
template: getTemplate("personal"),
},
onLoad() {
this.load();
},
onShow() {
this.load();
},
load() {
const token = wx.getStorageSync("customerToken");
if (!token) return this.setData({ loading: false, bookings: [], error: "" });
this.setData({ loading: true, error: "" });
Promise.all([customerRequest("/customer/bookings"), request("/public/brand")])
.then(([items, brand]) => {
getApp().globalData.brand = brand;
const template = getTemplate(brand.templateKey);
this.setData({
template,
bookings: (Array.isArray(items) ? items : []).map((item) =>
bookingViewModel(item, template),
),
loading: false,
});
})
.catch((error) => this.setData({ loading: false, error: error.message || "网络请求失败" }));
},
retry() {
this.load();
},
contact() {
const brand = getApp().globalData.brand || {};
if (brand.contactPhone) return wx.makePhoneCall({ phoneNumber: brand.contactPhone });
if (brand.contactWechat)
return wx.showModal({
title: "联系品牌方",
content: "微信号:" + brand.contactWechat,
showCancel: false,
});
wx.showToast({ title: "暂未配置联系方式", icon: "none" });
},
cancel(e) {
const id = e.currentTarget.dataset.id;
if (this.data.cancellingId) return;
wx.showModal({
title: "取消预约",
content: "确定取消这笔预约吗?",
success: (result) => {
if (!result.confirm) return;
this.setData({ cancellingId: id });
customerRequest("/customer/bookings/" + id + "/cancel", { method: "POST", data: {} })
.then(() => {
this.setData({ cancellingId: "" });
wx.showToast({ title: "已取消预约", icon: "success" });
this.load();
})
.catch((error) => {
this.setData({ cancellingId: "" });
wx.showToast({ title: error.message || "取消失败", icon: "none" });
});
},
});
},
});
+9
View File
@@ -0,0 +1,9 @@
{
"navigationBarTitleText": "我的订单",
"navigationBarBackgroundColor": "#FBF7F1",
"navigationBarTextStyle": "black",
"usingComponents": {
"brand-loading": "/components/ui/brand-loading/brand-loading",
"brand-empty": "/components/ui/brand-empty/brand-empty"
}
}
+16
View File
@@ -0,0 +1,16 @@
<view class="page">
<view class="heading-row"><text class="heading">我的订单</text><text class="phone" bindtap="contact">☎</text></view>
<brand-loading wx:if="{{loading}}" />
<view wx:elif="{{error}}" class="inline-error"><text>{{error}}</text><button size="mini" bindtap="retry">重新加载</button></view>
<brand-empty wx:elif="{{!bookings.length}}" description="完成预约后,订单会显示在这里" />
<block wx:else>
<view class="status-banner"><view><text class="status-title">订单状态</text><text class="status-sub">查看每笔预约的最新进展</text></view><text class="check">✓</text></view>
<view wx:for="{{bookings}}" wx:key="id" class="card">
<view class="card-visual"><view class="dish-placeholder"></view><view class="card-main"><text class="name">{{item.serviceName}}</text><text class="summary">{{item.quantityLabel}} · {{item.fulfillmentLabel}} · {{item.requestedTime || '时间待确认'}}</text></view></view>
<view class="card-foot"><text class="price">{{item.estimatedAmount ? '¥'+item.estimatedAmount/100 : '人工沟通报价'}}</text><text class="status">{{item.statusLabel}}</text></view>
<view class="actions"><button class="contact" size="mini" bindtap="contact">{{template.contactLabel}}</button><button class="cancel" wx:if="{{item.status === 'received'}}" loading="{{cancellingId === item.id}}" disabled="{{!!cancellingId}}" size="mini" data-id="{{item.id}}" bindtap="cancel">{{cancellingId === item.id ? '取消中...' : template.cancelLabel}}</button></view>
<text class="cancel-note" wx:if="{{item.status === 'received'}}">{{template.cancelNote}}</text>
</view>
<view class="faq"><view class="faq-title">常见问题 <text>›</text></view><view>○ 怎么确认预约? <text>›</text></view><view>○ 配送范围有多远? <text>›</text></view><view>○ 可以改时间吗? <text>›</text></view></view>
</block>
</view>
+170
View File
@@ -0,0 +1,170 @@
.page {
min-height: 100vh;
padding: 24rpx 32rpx 60rpx;
background: #fbf7f1;
color: #2b2b2b;
}
.heading-row {
display: flex;
justify-content: space-between;
align-items: center;
margin: 12rpx 0 32rpx;
}
.heading {
font-size: 48rpx;
font-weight: 700;
}
.phone {
font-size: 48rpx;
color: #7a4a2b;
}
.status-banner {
position: relative;
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20rpx;
padding: 34rpx 32rpx;
background: #f4ebd9;
border-radius: 16rpx;
}
.status-title {
display: block;
font-size: 40rpx;
font-weight: 700;
}
.status-sub {
display: block;
margin-top: 10rpx;
font-size: 28rpx;
}
.check {
color: #b54a2c;
font-size: 88rpx;
line-height: 1;
}
.card {
margin-bottom: 18rpx;
padding: 22rpx;
background: #f4ebd9;
border-radius: 16rpx;
}
.card-visual {
display: flex;
gap: 20rpx;
align-items: center;
}
.dish-placeholder {
width: 190rpx;
height: 190rpx;
flex: none;
border-radius: 12rpx;
background: #c79555;
}
.name {
display: block;
font-size: 36rpx;
font-weight: 700;
margin-bottom: 14rpx;
}
.summary {
font-size: 28rpx;
line-height: 1.6;
}
.card-foot {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 24rpx;
padding: 18rpx 4rpx;
border-top: 1rpx solid #dfcda9;
}
.status {
padding: 8rpx 20rpx;
border: 1rpx solid #b54a2c;
border-radius: 30rpx;
color: #b54a2c;
}
.price {
color: #b54a2c;
font-size: 42rpx;
}
.actions {
display: flex;
gap: 16rpx;
margin-top: 18rpx;
}
.actions button {
flex: 1;
border-radius: 12rpx;
font-size: 29rpx;
}
.contact {
background: #2b2b2b;
color: #fff;
}
.cancel {
background: #b54a2c;
color: #fff;
}
.cancel-note {
display: block;
margin-top: 18rpx;
text-align: center;
font-size: 25rpx;
}
.faq {
margin-top: 24rpx;
padding: 28rpx 30rpx;
background: #fff;
border-radius: 16rpx;
}
.faq view {
padding: 20rpx 0;
border-bottom: 1rpx solid #eee;
font-size: 29rpx;
}
.faq view:last-child {
border-bottom: 0;
}
.faq-title {
font-size: 36rpx !important;
font-weight: 700;
}
.faq text {
float: right;
color: #7a4a2b;
font-size: 40rpx;
}
.state,
.empty {
text-align: center;
padding: 100rpx 20rpx;
color: #7a4a2b;
}
.check {
box-sizing: border-box;
display: flex;
width: 108rpx;
height: 108rpx;
align-items: center;
justify-content: center;
padding: 18rpx;
border: 8rpx solid #b54a2c;
border-radius: 50%;
color: #b54a2c;
font-size: 56rpx;
line-height: 1;
}
.inline-error {
padding: 72rpx 32rpx;
display: flex;
flex-direction: column;
align-items: center;
color: var(--brand-color-muted);
}
.inline-error button {
margin-top: 24rpx;
color: var(--brand-color-primary);
background: var(--brand-color-subtle);
}
+46
View File
@@ -0,0 +1,46 @@
const { request } = require("../../utils/request");
const config = require("../../utils/config");
const { getTemplate } = require("../../utils/templates");
Page({
data: { loading: true, error: "", brand: {}, services: [], copy: {} },
onLoad() {
this.load();
},
load() {
this.setData({ loading: true, error: "" });
Promise.all([request("/public/brand"), request("/public/offerings")])
.then(([brand, services]) => {
getApp().globalData.brand = brand;
wx.setNavigationBarTitle({ title: brand.name || "个人品牌" });
const copy = getTemplate(brand.templateKey);
this.setData({
brand: { ...brand, coverUrl: brand.coverUrl || "/assets/brand/home-hero.jpg" },
services,
copy,
loading: false,
});
})
.catch(() => this.setData({ loading: false, error: "暂时无法加载内容" }));
},
selectService(event) {
wx.navigateTo({
url: "/pages/booking/index?offeringId=" + encodeURIComponent(event.currentTarget.dataset.id),
});
},
goServices() {
wx.switchTab({ url: "/pages/services/index" });
},
goPrivateChef() {
wx.navigateTo({ url: "/pages/booking/index?type=private_chef" });
},
goBooking() {
wx.navigateTo({ url: "/pages/booking/index" });
},
goBookings() {
wx.switchTab({ url: "/pages/bookings/index" });
},
goHome() {
wx.switchTab({ url: "/pages/index/index" });
},
});
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff. Show more