feat: 收口多品牌与模板构建基础

This commit is contained in:
que01 committed 2026-09-25 02:55:46 +08:00
1 parent 0425a1c672
commit 77224ea51f
317 files changed
+11290 -1158

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@
"lint": "eslint .",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "tsx --test test/**/*.test.ts",
"test:integration": "pnpm build && NODE_ENV=test node --env-file=.env --test test/http.integration.test.js",
"test:integration": "pnpm build && node --env-file=.env test/run-integration.cjs",
"clean": "rimraf dist",
"start": "node dist/main.js",
"db:generate": "prisma generate",
@@ -0,0 +1 @@
ALTER TABLE "AdminUser" ADD COLUMN "mustChangePassword" BOOLEAN NOT NULL DEFAULT false;
@@ -0,0 +1,16 @@
CREATE TABLE "BrandRelease" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"version" INTEGER NOT NULL,
"status" TEXT NOT NULL DEFAULT 'published',
"snapshot" JSONB NOT NULL,
"actorId" TEXT NOT NULL,
"note" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"revokedAt" TIMESTAMP(3),
CONSTRAINT "BrandRelease_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "BrandRelease_brandId_version_key" ON "BrandRelease"("brandId", "version");
CREATE INDEX "BrandRelease_brandId_status_createdAt_idx" ON "BrandRelease"("brandId", "status", "createdAt");
ALTER TABLE "BrandRelease" ADD CONSTRAINT "BrandRelease_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1 @@
ALTER TABLE "BrandRelease" ADD COLUMN "revokedBy" TEXT;
+18
View File
@@ -62,6 +62,23 @@ model BrandProfile {
capabilityInstallations CapabilityInstallation[]
capabilityAuditLogs CapabilityAuditLog[]
adminMemberships BrandMembership[]
releases BrandRelease[]
}
model BrandRelease {
id String @id @default(uuid())
brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
version Int
status String @default("published")
snapshot Json
actorId String
note String?
createdAt DateTime @default(now())
revokedAt DateTime?
revokedBy String?
@@unique([brandId, version])
@@index([brandId, status, createdAt])
}
model CapabilityInstallation {
@@ -328,6 +345,7 @@ model AdminUser {
displayName String
role String @default("admin")
isEnabled Boolean @default(true)
mustChangePassword Boolean @default(false)
lastLoginAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
+742 -171
View File
@@ -1,5 +1,6 @@
import { PrismaClient } from "@prisma/client";
import bcrypt from "bcryptjs";
import { buildBrandReleaseSnapshot } from "../src/brand-release.service.js";
const prisma = new PrismaClient();
@@ -14,47 +15,660 @@ const runtimeImages = {
"https://images.unsplash.com/photo-1603133872878-684f208fb84b?auto=format&fit=crop&w=1000&q=85",
"https://images.unsplash.com/photo-1559847844-5315695dadae?auto=format&fit=crop&w=1000&q=85",
],
personal: [
"https://images.unsplash.com/photo-1556761175-b413da4baf72?auto=format&fit=crop&w=1000&q=85",
"https://images.unsplash.com/photo-1521737711867-e3b97375f902?auto=format&fit=crop&w=1000&q=85",
],
};
async function ensureRuntimeContent(
brandId: string,
templateKey: "food" | "doors",
offerings: Array<{ name: string; summary: string; image: string; categoryKey: string }>,
): Promise<void> {
type OfferingKind = "service" | "product" | "package" | "subscription";
interface RuntimeSeedTemplate {
brandConfig: Record<string, unknown>;
retiredOfferingNames?: string[];
offerings: Array<{
name: string;
summary: string;
image: string;
kind: OfferingKind;
priceText?: string;
priceAmount?: number;
config: Record<string, unknown>;
}>;
trustContent: Array<{
type: string;
title: string;
content: string;
config?: Record<string, unknown>;
}>;
inquiryForm: { name: string; fieldsSnapshot: Array<Record<string, unknown>> };
}
const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTemplate> = {
personal: {
brandConfig: {
visualTemplateKey: "linjing-editorial",
founder: "林然",
title: "品牌策略顾问",
slogan: "用清晰的定位与可执行的表达,让专业被看见。",
phone: "13900000003",
wechat: "linran-brand",
studioAddress: "上海市徐汇区创意园区",
heroImage: runtimeImages.personal[0],
visualPresentation: {
home: {
proofEyebrow: "专业经验与合作成果",
manifestoEyebrow: "工作原则",
manifestoTitle: "先厘清问题,再设计表达",
worksEyebrow: "合作方式",
worksTitle: "品牌策略与顾问服务",
worksAction: "查看全部 →",
flowEyebrow: "合作流程",
flowTitle: "从诊断到持续落地",
},
offerings: {
title: "合作方式",
subtitle: "围绕品牌定位、表达与业务转化,选择适合当前阶段的支持。",
materialLabel: "服务内容:",
hardwareLabel: "合作重点:",
detailAction: "查看服务详情 →",
inquiryAction: "发起合作咨询",
},
detail: {
priceLabel: "服务参考",
spaceLabel: "适合阶段",
backgroundTitle: "服务背景",
conceptTitle: "工作方法",
craftsTitle: "交付内容",
materialsTitle: "合作说明",
inquiryAction: "发起合作咨询",
inquiryHint: "提交信息后由主理人与您沟通。",
},
profile: {
phoneLabel: "联系电话",
wechatLabel: "微信",
addressLabel: "工作地点",
callAction: "呼叫",
copyAction: "复制",
recordsTitle: "我的咨询记录",
recordsCountUnit: "条记录",
},
inquiry: {
eyebrow: "COLLABORATION",
title: "合作咨询",
subtitle: "留下你的品牌现状与目标,主理人会尽快联系。",
submitLabel: "提交合作需求",
},
success: {
eyebrow: "COLLABORATION",
title: "已收到你的咨询",
intro: "主理人会尽快与你联系。",
recordsAction: "查看咨询记录",
homeAction: "返回首页",
},
records: {
title: "我的咨询记录",
createAction: "新增咨询",
emptyTitle: "还没有咨询记录",
emptyDescription: "提交一次咨询,开始与你的主理人沟通。",
emptyAction: "开始咨询",
},
},
},
offerings: [
{
name: "品牌定位诊断",
summary: "梳理现有表达、目标客户与业务优先级,形成清晰的下一步行动建议。",
image: runtimeImages.personal[0],
kind: "service",
config: {
categoryKey: "consulting",
categoryLabel: "策略咨询",
keywords: ["定位", "诊断", "表达"],
},
},
{
name: "个人品牌年度顾问",
summary: "持续支持内容策略、产品表达与关键节点决策,建立长期信任资产。",
image: runtimeImages.personal[1],
kind: "subscription",
config: {
categoryKey: "advisory",
categoryLabel: "长期顾问",
keywords: ["陪跑", "内容", "转化"],
},
},
],
trustContent: [
{
type: "profile",
title: "关于林然",
content: "专注帮助专业服务者建立可信、清晰且能带来合作的个人品牌表达。",
},
{
type: "process",
title: "合作方法",
content: "诊断现状、明确定位、搭建表达、持续复盘,让每一步都服务于真实业务。",
},
],
inquiryForm: {
name: "品牌合作咨询",
fieldsSnapshot: [
{ key: "name", label: "您的称呼", type: "text", required: true },
{ key: "phone", label: "联系电话", type: "phone", required: true },
{ key: "remark", label: "目前的品牌或业务问题", type: "textarea", required: true },
],
},
},
food: {
brandConfig: {
visualTemplateKey: "acheng-campus-food",
founder: "阿成",
title: "私房菜主理人",
slogan: "认真做好每一顿家常饭。",
phone: "",
wechat: "",
studioAddress: "大学城生活区东门附近",
heroImage: runtimeImages.food[0],
visualPresentation: {
home: {
proofEyebrow: "主理人信任凭证",
manifestoEyebrow: "品牌坚持",
manifestoTitle: "认真对待每一次托付",
worksEyebrow: "今日餐品与预订",
worksTitle: "套餐、聚餐与定制餐",
worksAction: "查看全部 →",
flowEyebrow: "预订流程",
flowTitle: "从预订到取餐",
},
offerings: {
title: "今日套餐与定制餐",
subtitle: "现做套餐、聚餐预订和定制餐品。",
materialLabel: "餐品说明:",
hardwareLabel: "预订要点:",
detailAction: "查看餐品 →",
inquiryAction: "咨询 / 提前预订",
},
detail: {
priceLabel: "参考价格",
spaceLabel: "适合场景",
backgroundTitle: "餐品说明",
conceptTitle: "口味与分量",
craftsTitle: "制作方式",
materialsTitle: "食材与搭配",
inquiryAction: "咨询 / 提前预订",
inquiryHint: "提交后由主理人与您确认餐品和时间。",
},
profile: {
phoneLabel: "联系电话",
wechatLabel: "微信",
addressLabel: "服务地址",
callAction: "呼叫",
copyAction: "复制",
recordsTitle: "我的咨询记录",
recordsCountUnit: "条记录",
},
inquiry: {
eyebrow: "CONSULTATION",
title: "餐品预订与定制",
subtitle: "提交信息后由主理人与您确认时间和需求。",
submitLabel: "提交预订需求",
},
success: {
eyebrow: "CONSULTATION",
title: "已收到你的预订需求",
intro: "主理人会尽快与你确认。",
recordsAction: "查看咨询记录",
homeAction: "返回首页",
},
records: {
title: "我的预订记录",
createAction: "新增预订",
emptyTitle: "还没有预订记录",
emptyDescription: "提交一次预订需求,开始确认餐品与时间。",
emptyAction: "开始预订",
},
},
},
offerings: [
{
name: "红烧肉双拼套餐",
summary: "红烧肉、时蔬、米饭",
image: runtimeImages.food[0],
kind: "package",
priceAmount: 2800,
config: {
categoryKey: "set-meal",
categoryLabel: "套餐",
keywords: ["现做", "家常", "定制"],
},
},
{
name: "小炒鸡套餐",
summary: "现炒鸡块、时蔬、米饭",
image: runtimeImages.food[1],
kind: "package",
priceAmount: 3200,
config: {
categoryKey: "set-meal",
categoryLabel: "套餐",
keywords: ["现做", "家常", "定制"],
},
},
{
name: "家庭聚餐私厨",
summary: "根据人数、地点和口味人工沟通报价",
image: runtimeImages.food[2],
kind: "service",
config: {
categoryKey: "private-chef",
categoryLabel: "私厨",
keywords: ["现做", "家常", "定制"],
},
},
],
trustContent: [
{ type: "profile", title: "关于阿成", content: "每天认真做好一顿家常饭。" },
{
type: "process",
title: "认真做饭的流程",
content: "提前准备食材,现做现出餐,认真沟通每一次需求。",
},
],
inquiryForm: {
name: "家庭聚餐咨询",
fieldsSnapshot: [
{ key: "name", label: "您的称呼", type: "text", required: true },
{ key: "phone", label: "联系电话", type: "phone", required: true },
{ key: "remark", label: "需求说明", type: "textarea", required: false },
],
},
},
doors: {
retiredOfferingNames: ["别墅入户大门", "院门与围合系统", "室内户内门系统"],
brandConfig: {
visualTemplateKey: "linjing-editorial",
founder: "林叙安 (Lin XUAN)",
title: "高端门系统建筑研造主理人",
slogan: "为当代别墅空间,定制有秩序感与呼吸感的门",
phone: "186-0218-9908",
wechat: "LIN-ATELIER-2024",
studioAddress: "上海市静安区威海路设计中心 A 座 / 杭州良渚研造工坊",
avatarUrl:
"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?auto=format&fit=crop&w=240&h=240&q=80",
profilePresentation: {
coverage: [
{
title: "直派核心圈",
content:
"上海、杭州、宁波、苏州、无锡、南京及深圳、广州。主理人及资深装配总工亲赴现场。",
},
{
title: "全国其他城市私邸",
content: "接受建筑设计师联合委托,安排远程 3D 激光测绘支持与专用物流直运安装。",
},
],
warranty: [
"门体内部防变形航空合金骨架承诺 10 年结构质保;",
"重型天地轴、进口地弹簧及磁吸五金 5 年免费维护;",
"每樘门出厂前进行 5000 次启闭校正;",
"原木天然肌理享有首年 2 次木蜡油保养服务。",
],
},
visualPresentation: {
home: {
founderBadge: "亲自主理量房",
proofEyebrow: "主理人工艺与信任凭证",
proofTitle: "14 年,只做门与空间的关系",
manifestoEyebrow: "林境门作品质宣言",
manifestoTitle: "拒绝流水线拼装",
worksEyebrow: "SELECTED WORKS",
worksTitle: "精选门系统作品",
worksAction: "查看全部 →",
flowEyebrow: "全程一对一跟进",
flowTitle: "主理人私享定制流程",
},
offerings: {
title: "作品与系统",
subtitle: "每一扇门,都是建筑秩序的一部分。",
materialLabel: "主材构成:",
hardwareLabel: "核心五金:",
detailAction: "查看工艺详案 →",
inquiryAction: "咨询此类定制",
},
detail: {
priceLabel: "参考定制造价",
spaceLabel: "适用空间",
backgroundTitle: "项目背景与空间诉求",
conceptTitle: "构造深化设计理念",
craftsTitle: "节点工艺考究",
materialsTitle: "选型物料与五金规格",
inquiryAction: "预约上门测量 / 咨询此类方案",
inquiryHint: "预约后由主理人进行点对点方案分析",
},
profile: {
phoneLabel: "专线电话",
wechatLabel: "工作室微信",
addressLabel: "实体工坊",
callAction: "呼叫",
copyAction: "复制",
recordsCountUnit: "条记录",
recordsTitle: "我的量房与定制咨询",
recordsSubtitle: "追踪主理人出图进度与现场勘测排期",
coverageTitle: "直派服务区域与履约说明",
warrantyTitle: "一门一档 · 终生质保规约",
},
inquiry: {
eyebrow: "私人执业研造服务",
title: "高端门系统定制 · 私享测量预约",
subtitle: "主理人林叙安亲自沟通,72 小时内提供空间门体构想分析。",
submitLabel: "提交量房与定制评估需求",
},
success: {
eyebrow: "PRIVATE CONSULTATION",
title: "已收到你的咨询",
intro: "主理人会根据你的项目资料,整理初步判断并在 1 个工作日内与你联系。",
recordsAction: "查看咨询记录",
homeAction: "返回首页",
},
records: {
title: "我的咨询记录",
createAction: "+ 新增预约",
emptyTitle: "还没有咨询记录",
emptyDescription: "预约一次私享沟通,让我们从你的空间开始。",
emptyAction: "开始咨询",
},
},
heroImage: runtimeImages.doors[0],
homeHero: {
eyebrow: "年度落成实景 · 莫干山庄园",
title: "万籁系列 · 铸铜冷锻双轴入户门",
slogan: "门高 3.4m · 德国静音地轴",
cta: "探索全系作品 →",
},
},
offerings: [
{
name: "当代铸铜木核防暴装甲门",
summary:
"项目位于浙北山间独栋庄园,业主需要一扇兼具当代东方仪式感与长期耐候能力的入户大门。",
image: runtimeImages.doors[0],
kind: "product",
priceText: "¥38,000 - ¥85,000 / 樘",
config: {
categoryKey: "entrance-door",
categoryLabel: "入户大门",
series: "「万籁」重型天地轴入户系统",
tag: "主理人年度代表作",
area: "浙江·莫干山私家山庄",
detailHero: runtimeImages.doors[0],
woodMaterial: "60mm 北美特级黑胡桃整板 + 航空蜂窝铝芯",
hardware: "德国 dormakaba 重型地弹簧 + 自主定制实心锻铜一体式长执手",
spaceType: "独栋别墅建筑主入口 / 挑高大厅玄关",
keywords: ["厚重大气", "隐式天地轴", "隔音 42dB", "抗暴防撬"],
details: {
background:
"项目位于浙北山间独栋庄园,常年多雨潮湿,且冬季山风冷峻。业主期望一扇既有古典厚重仪式感,又能抵御风雨、长久耐候的当代东方大门。",
designConcept:
"提炼江南屋檐与青砖比例。以暗调冷锻手工铜板包裹耐候钢核,内衬大厚度吸音绝热芯,门体内嵌隐藏式天地承重轴,推拉阻尼丝滑沉稳。",
crafts: [
"无缝冷锻铜边框,经自然氧化着色",
"双道三元乙丙航天级发泡密封胶条,气密性达国标 8 级",
"指纹识别模组隐于天然胡桃木纹理深处",
],
materialsList: [
{ name: "门扇主体", spec: "航空铝蜂窝 + 防暴钢板 + 黑胡桃" },
{ name: "承重结构", spec: "不锈钢重型天地偏心轴(承重 600KG)" },
{ name: "五金执手", spec: "实心黄铜拉丝防指纹覆膜" },
{ name: "锁具系统", spec: "C 级多向防暴机械锁芯 + 隐匿式生物辨识" },
],
},
},
},
{
name: "悬挑风琴式耐候双开院门",
summary: "以柚木条与耐候钢构建视线遮蔽和透光的微妙平衡,适配长期日晒雨淋的私家庭院入口。",
image: runtimeImages.doors[1],
kind: "product",
priceText: "¥42,000 - ¥98,000 / 樘",
config: {
categoryKey: "garden-door",
categoryLabel: "庭院围墙门",
series: "「虚实」透光私家庭院门",
tag: "建筑级耐候工艺",
area: "上海·佘山高尔夫别墅",
detailHero: runtimeImages.doors[1],
woodMaterial: "深浸缅甸柚木条格栅 + 氟碳喷涂耐候钢",
hardware: "意大利全隐形地埋式液压自闭器 + 静音电控锁",
spaceType: "私家庭院入口 / 围墙园林玄关",
keywords: ["园林意境", "格栅光影", "耐候耐蚀", "智能对讲协同"],
details: {
background:
"庭院门直面自然日晒雨淋,普通木门易开裂变形,普通铁艺门几年内斑驳锈蚀。本案要求长期免维护的高级自然质感。",
designConcept:
"利用竖向错落的柚木条构建视线遮蔽与透光的微妙平衡,内部向外望去如薄纱透竹。",
crafts: [
"微隙热胀冷缩结构槽设计",
"隐蔽式水路导流坡口",
"院墙铰链锚栓深入混凝土柱芯 300mm",
],
materialsList: [
{ name: "户外木种", spec: "高油脂老料缅甸柚木,经过 180 天自然风干" },
{ name: "骨架型材", spec: "4mm 高强度航空铝镁合金" },
{ name: "智能五金", spec: "隐藏式地下闭门轴,支持远程授权" },
],
},
},
},
{
name: "通顶极窄边框实木室内门",
summary: "以 2.8m - 3.2m 满高通顶系统维持私宅空间的建筑平直感,并与木作一体深化。",
image: runtimeImages.doors[2],
kind: "product",
priceText: "¥7,800 - ¥16,000 / 樘",
config: {
categoryKey: "interior-door",
categoryLabel: "室内户内门",
series: "「空灵」2.8m - 3.2m 满高通顶系统",
tag: "极简建筑平直感",
area: "江苏·苏州金鸡湖独栋",
detailHero: runtimeImages.doors[2],
woodMaterial: "天然白栓木拉丝烟熏木饰面 + 磁吸阻尼降噪",
hardware: "意大利 AGB 磁吸静音门锁 + 隐藏式暗铰链",
spaceType: "别墅主卧套房 / 私人藏书阁 / 视听室",
keywords: ["满高通顶", "磁吸静音", "极窄边框", "与木作同色"],
details: {
background:
"室内多道门如果尺寸矮小杂乱,会切割私宅的建筑开阔感。业主希望主卧区实现门与护墙板毫无色差、绝对平齐。",
designConcept: "门扇高 3.1 米一通到顶,无传统上门套与压边;内嵌双向碳纤维抗弯龙骨。",
crafts: [
"门框与墙体批荡层融为一体的无框反装工艺",
"磁力吸舌落锁轻无声息",
"同批原木切片保证纹理与护墙板连贯",
],
materialsList: [
{ name: "抗弯核心", spec: "双组份碳纤维预应力防变形拉力杆" },
{ name: "吸音内衬", spec: "德国均质空心桥洞力学板" },
{ name: "隐形铰链", spec: "德国 KRONA 三维可调隐形铰链" },
],
},
},
},
{
name: "石材及皮质背景墙一体门",
summary: "将门体与背景墙材料、纹理和收口一体深化,保留私宅完整的墙面秩序。",
image:
"https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?auto=format&fit=crop&w=1000&q=85",
kind: "product",
priceText: "¥18,000 - ¥36,000 / 樘",
config: {
categoryKey: "stealth-door",
categoryLabel: "装饰隐形门",
series: "「无垠」密室及背景墙融合门",
tag: "精密收口工程",
area: "广东·深圳香蜜湖一号",
detailHero:
"https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?auto=format&fit=crop&w=1000&q=85",
woodMaterial: "3mm 超薄大理石复合蜂窝板 / 进口鞍革手工双缝线",
hardware: "感应式电动自开闭装置或碰珠反弹器",
spaceType: "雪茄室 / 私人金库 / 地下酒窖 / 视听隐藏储物区",
keywords: ["视线隐形", "超薄岩板", "毫厘对缝", "无门把设计"],
details: {
background:
"客厅背景墙长达 9 米,中间有一道通往主人密闭酒窖的通道,突兀开门会破坏整面奢石的连贯韵律。",
designConcept: "将奢石切割对纹复合于高刚性合金门扇表面,缝隙控制在 1.5mm 以内。",
crafts: [
"石材水刀无应力薄切与航空蜂窝背栓复合",
"脚踏地砖预埋重力复位转轴",
"支持指纹电控联动隐藏灯带",
],
materialsList: [
{ name: "表面饰材", spec: "意大利雪山银狐超薄天然大理石" },
{ name: "驱动系统", spec: "低噪步进电机伺服闭门器" },
],
},
},
},
],
trustContent: [
{
type: "profile",
title: "主理人的门作观",
content:
"国家注册高级室内建筑师,专注高定大门及私宅空间门类系统研发 14 年。拒绝建材量产拼装,以门与空间同构的建筑理念,亲自主理选材、构造深化与落地试装。",
config: {
stats: [
{ value: "14年", label: "高端门系深化经验", sub: "历经百项严苛私宅考验" },
{ value: "260+", label: "落地庄园实景案例", sub: "全实景图库,可预约探访" },
{ value: "100%", label: "主理人全案跟进", sub: "量房 / 出图 / 选料 / 试装" },
{ value: "10年", label: "结构主轴质保承诺", sub: "终生五金润滑维保机制" },
],
pillars: [
{
icon: "tree",
title: "天然厚板与古铜锻打",
desc: "精选 300 年北美黑胡桃、缅甸柚木直拼大板,搭配手工冷锻紫铜及意大利防爆钢核。",
},
{
icon: "ruler",
title: "微米级红外高精量房",
desc: "德国进口 3D 空间激光扫描,精准捕捉门洞沉降公差与建筑墙体垂直度。",
},
{
icon: "shield",
title: "隐匿式重型五金系统",
desc: "自主研发三维可调静音承重铰链,单扇承载 450kg,开合轻盈安静。",
},
],
serviceFlow: [
{ step: "01", name: "私享沟通", desc: "厘清生活动线与风候环境" },
{ step: "02", name: "上门实测", desc: "复核门洞公差与地平基准" },
{ step: "03", name: "构造出图", desc: "输出结构图与材质节点方案" },
{ step: "04", name: "实样工坊确认", desc: "确认木样、锻铜样与密封节点" },
{ step: "05", name: "工坊试装交付", desc: "试装调试后专车直运现场" },
{ step: "06", name: "终生私属维护", desc: "建立一门一档数字化档案" },
],
},
},
{
type: "portfolio",
title: "别墅门系统案例",
content: "围绕入户、庭院和室内空间建立完整门系统。",
},
{
type: "process",
title: "从测量到交付",
content: "现场测量、方案沟通、深化确认和落地交付。",
},
],
inquiryForm: {
name: "门系统方案咨询",
fieldsSnapshot: [
{
key: "doorType",
label: "期望定制的门类型",
type: "select",
required: true,
options: [
"入户大门(防暴铸铜 / 实木)",
"庭院围墙门(耐候格栅 / 对开)",
"全屋室内门系统(通顶隐形)",
"背景墙一体门 / 密室门",
"整栋别墅门系统全案一体化",
],
},
{ key: "cityArea", label: "房屋 / 别墅所在城市与楼盘", type: "text", required: true },
{
key: "projectStage",
label: "当前项目阶段",
type: "radio",
required: true,
options: [
"土建结构阶段(适合预埋加固)",
"水电木工阶段(适合精确测距)",
"硬装收尾阶段",
"旧宅门体翻新改造",
],
},
{
key: "budgetRange",
label: "预估门系统投资预算",
type: "select",
required: false,
options: [
"5 万 - 10 万",
"10 万 - 20 万",
"20 万 - 50 万(全宅全案)",
"50 万以上(顶级孤品定制)",
],
},
{
key: "needMeasure",
label: "是否需要主理人上门现场量房",
type: "radio",
required: true,
options: ["需要(预约排期现场勘测)", "暂不需要(先发图纸在线深化评估)"],
},
{ key: "contactName", label: "贵姓称谓", type: "text", required: true },
{ key: "contactPhone", label: "联系手机号(微信同号)", type: "tel", required: true },
{ key: "specialNote", label: "空间想法或特殊需求描述", type: "textarea", required: false },
],
},
},
};
async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTemplate): Promise<void> {
await prisma.brandProfile.update({
where: { id: brandId },
data: {
config: {
founder: templateKey === "doors" ? "林境主理人" : "阿成",
title: templateKey === "doors" ? "别墅门系统设计顾问" : "私房菜主理人",
slogan:
templateKey === "doors" ? "让每一扇门,成为建筑秩序的开始。" : "认真做好每一顿家常饭。",
phone: templateKey === "doors" ? "13800000000" : "",
wechat: templateKey === "doors" ? "linjing-doors" : "",
studioAddress: templateKey === "doors" ? "城市设计中心 3F" : "大学城生活区东门附近",
heroImage: runtimeImages[templateKey][0],
},
config: template.brandConfig,
},
});
for (const [sortOrder, item] of offerings.entries()) {
for (const [sortOrder, item] of template.offerings.entries()) {
const offering = await prisma.offering.findUnique({
where: { brandId_name: { brandId, name: item.name } },
});
if (!offering) continue;
await prisma.offering.update({
where: { id: offering.id },
data: {
coverUrl: item.image,
summary: item.summary,
sortOrder: sortOrder + 1,
isEnabled: true,
config: {
categoryKey: item.categoryKey,
keywords: templateKey === "doors" ? ["定制", "别墅", "门系统"] : ["现做", "家常", "定制"],
media: [{ url: item.image, alt: item.name, type: "image" }],
sections: [],
},
const data = {
kind: item.kind,
coverUrl: item.image,
summary: item.summary,
priceText: item.priceText ?? "沟通报价",
...(item.priceAmount === undefined ? {} : { priceAmount: item.priceAmount }),
sortOrder: sortOrder + 1,
isEnabled: true,
config: {
...item.config,
media: [{ url: item.image, alt: item.name, type: "image" }],
sections: [],
},
};
if (offering) await prisma.offering.update({ where: { id: offering.id }, data });
else await prisma.offering.create({ data: { brandId, name: item.name, ...data } });
}
if (template.retiredOfferingNames?.length) {
await prisma.offering.updateMany({
where: { brandId, name: { in: template.retiredOfferingNames } },
data: { isEnabled: false },
});
}
const moduleDefinitions = [
@@ -82,67 +696,74 @@ async function ensureRuntimeContent(
select: { id: true, name: true },
});
for (const [index, item] of incompleteOfferings.entries()) {
const image = runtimeImages[templateKey][index % runtimeImages[templateKey].length];
const image = template.offerings[index % template.offerings.length].image;
await prisma.offering.update({
where: { id: item.id },
data: {
coverUrl: image,
config: {
categoryKey: "custom",
keywords: templateKey === "doors" ? ["定制", "门系统"] : ["家常", "定制"],
categoryLabel: "自定义业务",
keywords: [],
media: [{ url: image, alt: item.name, type: "image" }],
sections: [],
},
},
});
}
const trustCount = await prisma.trustContent.count({ where: { brandId } });
if (!trustCount) {
const trustItems =
templateKey === "doors"
? [
["profile", "主理人的门作观", "从建筑关系出发,认真处理每一扇门。"],
["portfolio", "别墅门系统案例", "围绕入户、庭院和室内空间建立完整门系统。"],
["process", "从测量到交付", "现场测量、方案沟通、深化确认和落地交付。"],
]
: [
["profile", "关于阿成", "每天认真做好一顿家常饭。"],
["process", "认真做饭的流程", "提前准备食材,现做现出餐,认真沟通每一次需求。"],
];
await prisma.trustContent.createMany({
data: trustItems.map(([type, title, content], sortOrder) => ({
brandId,
type,
title,
content,
sortOrder,
isPublished: true,
})),
});
}
const formCount = await prisma.inquiryForm.count({ where: { brandId } });
if (!formCount) {
await prisma.inquiryForm.create({
data: {
brandId,
name: templateKey === "doors" ? "门系统方案咨询" : "家庭聚餐咨询",
purpose: "inquiry",
targetType: "brand",
submissionAction: "create-inquiry",
fieldsSnapshot: [
{ key: "name", label: "您的称呼", type: "text", required: true },
{ key: "phone", label: "联系电话", type: "phone", required: true },
{ key: "remark", label: "需求说明", type: "textarea", required: false },
],
},
for (const [sortOrder, item] of template.trustContent.entries()) {
const existing = await prisma.trustContent.findFirst({
where: { brandId, type: item.type, title: item.title },
});
const data = { ...item, brandId, sortOrder, isPublished: true };
if (existing) await prisma.trustContent.update({ where: { id: existing.id }, data });
else await prisma.trustContent.create({ data });
}
const existingForm = await prisma.inquiryForm.findFirst({
where: { brandId, targetType: "brand" },
orderBy: { createdAt: "asc" },
});
const formData = {
name: template.inquiryForm.name,
purpose: "inquiry",
targetType: "brand",
submissionAction: "create-inquiry",
fieldsSnapshot: template.inquiryForm.fieldsSnapshot,
isEnabled: true,
} as const;
if (existingForm)
await prisma.inquiryForm.update({ where: { id: existingForm.id }, data: formData });
else await prisma.inquiryForm.create({ data: { brandId, ...formData } });
}
async function ensureSeedRelease(brandId: string, actorId: string): Promise<void> {
const snapshot = await buildBrandReleaseSnapshot(prisma, brandId);
await prisma.brandRelease.deleteMany({ where: { brandId } });
await prisma.brandRelease.create({
data: {
brandId,
version: 1,
status: "published",
snapshot,
actorId,
note: "seed 基线发布版本",
},
});
}
async function main(): Promise<void> {
const brand = await prisma.brandProfile.upsert({
where: { id: "00000000-0000-0000-0000-000000000001" },
update: {},
update: {
slug: "default-brand",
name: "阿成家常菜",
templateKey: "food",
tagline: "现做家常套餐,也为小型聚餐定制一桌热饭菜",
description: "每天认真做好一顿家常饭。",
hours: "周一至周六 10:30-20:00",
address: "大学城生活区东门附近",
deliveryNote: "目前支持部分学生宿舍楼配送,无法送达时会主动联系。",
},
create: {
slug: "default-brand",
id: "00000000-0000-0000-0000-000000000001",
@@ -156,58 +777,7 @@ async function main(): Promise<void> {
},
});
const offerings = [
{
brandId: brand.id,
name: "红烧肉双拼套餐",
description: "红烧肉、时蔬、米饭",
priceText: "¥28 / 份",
priceAmount: 2800,
sortOrder: 1,
},
{
brandId: brand.id,
name: "小炒鸡套餐",
description: "现炒鸡块、时蔬、米饭",
priceText: "¥25 / 份",
priceAmount: 2500,
sortOrder: 2,
},
{
brandId: brand.id,
name: "家庭聚餐私厨",
description: "根据人数、地点和口味人工沟通报价",
priceText: "面议",
sortOrder: 3,
},
];
for (const offering of offerings) {
const existing = await prisma.offering.findFirst({
where: { brandId: brand.id, name: offering.name },
});
if (existing) await prisma.offering.update({ where: { id: existing.id }, data: offering });
else await prisma.offering.create({ data: { ...offering, kind: "service" } });
}
await ensureRuntimeContent(brand.id, "food", [
{
name: "红烧肉双拼套餐",
summary: "红烧肉、时蔬、米饭",
image: runtimeImages.food[0],
categoryKey: "set-meal",
},
{
name: "小炒鸡套餐",
summary: "现炒鸡块、时蔬、米饭",
image: runtimeImages.food[1],
categoryKey: "set-meal",
},
{
name: "家庭聚餐私厨",
summary: "根据人数、地点和口味人工沟通报价",
image: runtimeImages.food[2],
categoryKey: "private-chef",
},
]);
await ensureRuntimeContent(brand.id, runtimeSeedTemplates.food);
for (const name of ["普通套餐", "私厨", "配送", "自取", "熟客", "重点跟进"]) {
await prisma.tag.upsert({
@@ -231,9 +801,52 @@ async function main(): Promise<void> {
create: { adminUserId: admin.id, brandId: brand.id, role: "owner" },
});
const personalBrand = await prisma.brandProfile.upsert({
where: { id: "00000000-0000-0000-0000-000000000003" },
update: {
slug: "linran-brand",
name: "林然品牌顾问",
templateKey: "personal",
tagline: "用清晰的定位与可执行的表达,让专业被看见。",
description: "为专业服务者提供品牌定位、表达与长期顾问支持。",
hours: "周一至周五 10:00-18:00",
address: "上海市徐汇区创意园区",
contactPhone: "13900000003",
contactWechat: "linran-brand",
},
create: {
id: "00000000-0000-0000-0000-000000000003",
slug: "linran-brand",
name: "林然品牌顾问",
templateKey: "personal",
tagline: "用清晰的定位与可执行的表达,让专业被看见。",
description: "为专业服务者提供品牌定位、表达与长期顾问支持。",
hours: "周一至周五 10:00-18:00",
address: "上海市徐汇区创意园区",
contactPhone: "13900000003",
contactWechat: "linran-brand",
},
});
await prisma.brandMembership.upsert({
where: { adminUserId_brandId: { adminUserId: admin.id, brandId: personalBrand.id } },
update: { isEnabled: true, role: "owner" },
create: { adminUserId: admin.id, brandId: personalBrand.id, role: "owner" },
});
await ensureRuntimeContent(personalBrand.id, runtimeSeedTemplates.personal);
const doorsBrand = await prisma.brandProfile.upsert({
where: { id: "00000000-0000-0000-0000-000000000002" },
update: {},
update: {
slug: "linjing-doors",
name: "林境门作",
templateKey: "doors",
tagline: "为别墅空间定制有秩序感的门系统",
description: "从入户大门到室内户内门,提供完整的门系统设计与落地服务。",
hours: "周一至周六 09:00-18:00",
address: "城市设计中心 3F",
contactPhone: "13800000000",
contactWechat: "linjing-doors",
},
create: {
id: "00000000-0000-0000-0000-000000000002",
slug: "linjing-doors",
@@ -247,57 +860,15 @@ async function main(): Promise<void> {
contactWechat: "linjing-doors",
},
});
for (const offering of [
{
name: "别墅入户大门",
description: "结合建筑立面与入户动线定制门体、五金和安装方案。",
priceText: "预约沟通",
sortOrder: 1,
},
{
name: "院门与围合系统",
description: "院门、围墙和庭院动线的一体化设计与施工配合。",
priceText: "预约沟通",
sortOrder: 2,
},
{
name: "室内户内门系统",
description: "根据空间风格定制户内门、隐形门和装饰门。",
priceText: "预约沟通",
sortOrder: 3,
},
]) {
await prisma.offering.upsert({
where: { brandId_name: { brandId: doorsBrand.id, name: offering.name } },
update: offering,
create: { ...offering, brandId: doorsBrand.id, kind: "service" },
});
}
await prisma.brandMembership.upsert({
where: { adminUserId_brandId: { adminUserId: admin.id, brandId: doorsBrand.id } },
update: { isEnabled: true, role: "owner" },
create: { adminUserId: admin.id, brandId: doorsBrand.id, role: "owner" },
});
await ensureRuntimeContent(doorsBrand.id, "doors", [
{
name: "别墅入户大门",
summary: "结合建筑立面与入户动线定制门体、五金和安装方案。",
image: runtimeImages.doors[0],
categoryKey: "entrance-door",
},
{
name: "院门与围合系统",
summary: "院门、围墙和庭院动线的一体化设计与施工配合。",
image: runtimeImages.doors[1],
categoryKey: "garden-door",
},
{
name: "室内户内门系统",
summary: "根据空间风格定制户内门、隐形门和装饰门。",
image: runtimeImages.doors[2],
categoryKey: "interior-door",
},
]);
await ensureRuntimeContent(doorsBrand.id, runtimeSeedTemplates.doors);
await ensureSeedRelease(brand.id, admin.id);
await ensureSeedRelease(personalBrand.id, admin.id);
await ensureSeedRelease(doorsBrand.id, admin.id);
}
main().finally(() => prisma.$disconnect());
+8
View File
@@ -25,4 +25,12 @@ export class AdminAccessService {
if (!membership?.isEnabled) throw new ForbiddenException("管理员没有当前品牌权限");
return { subject: identity.subject, brandId: identity.brandId, role: membership.role };
}
async requireRole(request: FastifyRequest, allowedRoles: string[]): Promise<boolean> {
const access = await this.requireBrand(request);
if (!allowedRoles.includes(access.role)) {
throw new ForbiddenException("当前账号没有系统设置权限");
}
return true;
}
}
+21 -1
View File
@@ -7,7 +7,10 @@ import { signIdentity } from "./auth.js";
export class AdminAuthService {
constructor(private readonly prisma: PrismaService) {}
async login(username: string, password: string): Promise<{ token: string; displayName: string }> {
async login(
username: string,
password: string,
): Promise<{ token: string; displayName: string; mustChangePassword: boolean; role: string }> {
const user = await this.prisma.adminUser.findUnique({ where: { username } });
if (!user || !user.isEnabled || !(await bcrypt.compare(password, user.passwordHash))) {
throw new UnauthorizedException("账号或密码错误");
@@ -36,6 +39,23 @@ export class AdminAuthService {
role: "admin",
}),
displayName: user.displayName,
mustChangePassword: user.mustChangePassword,
role: activeMembership.role,
};
}
async changePassword(
userId: string,
currentPassword: string,
newPassword: string,
): Promise<void> {
const user = await this.prisma.adminUser.findUnique({ where: { id: userId } });
if (!user || !(await bcrypt.compare(currentPassword, user.passwordHash))) {
throw new UnauthorizedException("当前密码不正确");
}
await this.prisma.adminUser.update({
where: { id: userId },
data: { passwordHash: await bcrypt.hash(newPassword, 12), mustChangePassword: false },
});
}
}
+8
View File
@@ -11,6 +11,14 @@ export class AdminMembershipGuard implements CanActivate {
const request = context.switchToHttp().getRequest<FastifyRequest>();
if (request.url.startsWith("/admin/session/login")) return Promise.resolve(true);
if (!request.url.startsWith("/admin/")) return Promise.resolve(true);
if (
/^\/admin\/workspace\/(install|capabilities(?:\/|$)|template(?:\/|$)|modules(?:\/|$)|fields(?:\/|$))/.test(
request.url,
) ||
/^\/admin\/config\/visual-template(?:\/|$)/.test(request.url)
) {
return this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
}
return this.access.requireBrand(request).then(() => true);
}
}
+43 -42
View File
@@ -27,7 +27,12 @@ import {
UpdateInquirySubmissionDto,
UpdateCapabilityInstallationDto,
} from "./admin.dto.js";
import { capabilityPlugins, getBrandTemplate, resolveCapabilities } from "@personal-brand/config";
import {
capabilityPlugins,
getBrandTemplate,
getTemplateSampleContent,
resolveCapabilities,
} from "@personal-brand/config";
import { TemplateWorkspaceService } from "./template-workspace.service.js";
import { validateFieldSnapshot, validateOfferingConfig } from "@personal-brand/validation";
@@ -176,15 +181,12 @@ class AdminWorkspaceController {
@Get("capabilities")
async listCapabilities(@Req() request: FastifyRequest): Promise<unknown> {
const brandId = this.requireAdmin(request).brandId;
const [brand, installations] = await Promise.all([
this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true },
}),
const [templateKey, installations] = await Promise.all([
this.templateWorkspace.getEffectiveTemplateKey(brandId),
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
]);
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
const template = getBrandTemplate(brand?.templateKey ?? "personal");
const template = getBrandTemplate(templateKey);
return (template ? resolveCapabilities(template.capabilities) : []).map((definition) => {
const item = installed.get(definition.key);
return {
@@ -202,15 +204,22 @@ class AdminWorkspaceController {
@Get("sample-content/preview")
async previewSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
const brandId = this.requireAdmin(request).brandId;
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
const sample = getTemplateSampleContent(templateKey);
if (!sample) throw new BadRequestException("模板示例内容不存在");
const [offerings, trustContent, fields] = await Promise.all([
this.prisma.offering.count({ where: { brandId } }),
this.prisma.trustContent.count({ where: { brandId } }),
this.prisma.brandFieldDefinition.count({ where: { brandId, source: "sample" } }),
]);
return {
templateKey: "doors",
templateKey: sample.templateKey,
alreadyImported: offerings > 0 || trustContent > 0 || fields > 0,
counts: { offerings: 4, trustContent: 4, fields: 4 },
counts: {
offerings: sample.offerings.length,
trustContent: sample.trustContent.length,
fields: sample.fields.length,
},
};
}
@@ -218,6 +227,9 @@ class AdminWorkspaceController {
async importSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
const identity = this.requireAdmin(request);
const brandId = identity.brandId;
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
const sample = getTemplateSampleContent(templateKey);
if (!sample) throw new BadRequestException("模板示例内容不存在");
const existing = await this.prisma.brandFieldDefinition.count({
where: { brandId, source: "sample" },
});
@@ -227,54 +239,42 @@ class AdminWorkspaceController {
if (existing || existingOffering) throw new BadRequestException("示例内容已经导入");
const result = await this.prisma.$transaction(async (tx) => {
const offerings = await tx.offering.createMany({
data: [
["序章·入户门", "为别墅入口定制的整樘门系统", "entrance-door"],
["庭院·边界门", "连接建筑与庭院的定制门", "garden-door"],
["室内·静谧门", "统一室内空间秩序的户内门", "interior-door"],
["一对一门系统设计咨询", "从现场到方案的完整设计沟通", "custom"],
].map((item, sortOrder) => ({
data: sample.offerings.map((item, sortOrder) => ({
brandId,
kind: sortOrder === 3 ? "service" : "product",
name: item[0]!,
summary: item[1]!,
config: { categoryKey: item[2]! },
kind: item.kind,
name: item.name,
summary: item.summary,
config: { categoryKey: item.categoryKey },
sortOrder,
isEnabled: true,
})),
});
const trust = await tx.trustContent.createMany({
data: ["主理人的门作观", "别墅门系统案例", "从测量到交付", "材料与工艺标准"].map(
(title, sortOrder) => ({
brandId,
type: ["profile", "portfolio", "process", "credential"][sortOrder]!,
title,
content: "示例内容,待品牌主理人完善。",
sortOrder,
isPublished: false,
}),
),
data: sample.trustContent.map((item, sortOrder) => ({
brandId,
type: item.type,
title: item.title,
content: item.content,
sortOrder,
isPublished: false,
})),
});
const fields = await tx.brandFieldDefinition.createMany({
data: [
["projectType", "项目类型", "select"],
["projectStage", "项目阶段", "select"],
["siteDescription", "项目概况", "textarea"],
["phone", "联系方式", "phone"],
].map((item, sortOrder) => ({
data: sample.fields.map((item, sortOrder) => ({
brandId,
scope: "inquiry",
key: item[0]!,
label: item[1]!,
type: item[2]!,
key: item.key,
label: item.label,
type: item.type,
sortOrder,
source: "sample",
required: item[2] === "phone",
required: item.required,
})),
});
await tx.capabilityAuditLog.create({
data: {
brandId,
capabilityKey: "doors",
capabilityKey: sample.capabilityKey,
actorId: identity.subject,
action: "sample_content_imported",
toStatus: "enabled",
@@ -294,8 +294,9 @@ class AdminWorkspaceController {
): Promise<unknown> {
const identity = this.requireAdmin(request);
const brandId = identity.brandId;
const brand = await this.prisma.brandProfile.findUnique({ where: { id: brandId } });
const template = getBrandTemplate(brand?.templateKey ?? "personal");
const template = getBrandTemplate(
await this.templateWorkspace.getEffectiveTemplateKey(brandId),
);
if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins))
throw new BadRequestException("能力未被当前模板声明");
const existing = await this.prisma.capabilityInstallation.findUnique({
+29
View File
@@ -6,6 +6,7 @@ import {
IsObject,
IsOptional,
IsString,
MinLength,
Matches,
Max,
Min,
@@ -26,6 +27,34 @@ export class UpdateBrandDto {
@IsOptional() @IsObject() config?: Record<string, unknown>;
}
export class UpdateBrandPresentationDto {
@IsOptional() @IsObject() identity?: Record<string, unknown>;
@IsOptional() @IsObject() home?: Record<string, unknown>;
@IsOptional() @IsObject() offerings?: Record<string, unknown>;
@IsOptional() @IsObject() detail?: Record<string, unknown>;
@IsOptional() @IsObject() profile?: Record<string, unknown>;
@IsOptional() @IsObject() inquiry?: Record<string, unknown>;
@IsOptional() @IsObject() success?: Record<string, unknown>;
@IsOptional() @IsObject() records?: Record<string, unknown>;
}
export class UpdateBrandMemberDto {
@IsOptional() @IsIn(["owner", "editor"]) role?: "owner" | "editor";
@IsOptional() @IsBoolean() isEnabled?: boolean;
}
export class CreateBrandMemberDto {
@IsString() username!: string;
@IsString() displayName!: string;
@IsString() @MinLength(8) password!: string;
@IsIn(["owner", "editor"]) role!: "owner" | "editor";
}
export class ChangeAdminPasswordDto {
@IsString() currentPassword!: string;
@IsString() @MinLength(8) newPassword!: string;
}
export class CreateTrustContentDto {
@IsIn(["profile", "experience", "credential", "portfolio", "process", "testimonial"])
type!: string;
+6
View File
@@ -16,6 +16,9 @@ import { CustomerInquirySubmissionController } from "./modules/customer/customer
import { TemplateWorkspaceService } from "./template-workspace.service.js";
import { AdminAccessService } from "./admin-access.service.js";
import { AdminMembershipGuard } from "./admin-membership.guard.js";
import { BrandReleaseService } from "./brand-release.service.js";
import { BrandReleaseApiService } from "./brand-release-api.service.js";
import { AdminReleaseController } from "./modules/admin/admin-release.controller.js";
import {
CustomerSessionController,
AdminSessionController,
@@ -54,6 +57,7 @@ export class HealthController {
TenantController,
AdminBookingController,
AdminConfigController,
AdminReleaseController,
],
providers: [
PrismaService,
@@ -63,6 +67,8 @@ export class HealthController {
TemplateWorkspaceService,
AdminAccessService,
AdminMembershipGuard,
BrandReleaseService,
BrandReleaseApiService,
PublicBrandContextService,
],
exports: [PrismaService, WechatAuthService],
+37 -14
View File
@@ -2,6 +2,7 @@ import { BadRequestException, Injectable, NotFoundException } from "@nestjs/comm
import { BookingStatus, Prisma } from "@prisma/client";
import { PrismaService } from "./prisma.service.js";
import { canTransitionWorkflow, workflowRegistry } from "@personal-brand/config";
import { BrandReleaseService } from "./brand-release.service.js";
const BASIC_BOOKING_WORKFLOW = workflowRegistry["booking.basic"];
@@ -23,9 +24,32 @@ export interface CreateBookingInput {
@Injectable()
export class BookingService {
constructor(private readonly prisma: PrismaService) {}
constructor(
private readonly prisma: PrismaService,
private readonly releases: BrandReleaseService,
) {}
async create(brandId: string, customerUserId: string, input: CreateBookingInput) {
const snapshot = await this.releases.getPublishedSnapshot(brandId);
if (!snapshot) throw new BadRequestException("品牌尚未发布");
const publishedOfferingIds = this.releases.publishedOfferingIds(snapshot);
if (
(input.offeringId && !publishedOfferingIds.has(input.offeringId)) ||
input.items?.some((item) => !publishedOfferingIds.has(item.offeringId))
) {
throw new BadRequestException("业务提供项不存在或暂不可预订");
}
const requestedOfferingIds = [
...(input.offeringId ? [input.offeringId] : []),
...(input.items ?? []).map((item) => item.offeringId),
];
if (requestedOfferingIds.length) {
const enabledCount = await this.prisma.offering.count({
where: { id: { in: requestedOfferingIds }, brandId, isEnabled: true },
});
if (enabledCount !== new Set(requestedOfferingIds).size)
throw new BadRequestException("业务提供项不存在或暂不可预订");
}
if (!input.customerName.trim() || (!input.phone?.trim() && !input.wechatId?.trim())) {
throw new BadRequestException("称呼和至少一种联系方式为必填项");
}
@@ -52,23 +76,22 @@ export class BookingService {
) {
throw new BadRequestException("私厨需求必须填写日期、人数和地点");
}
const offerings = input.items?.length
? await this.prisma.offering.findMany({
where: {
id: { in: input.items.map((item) => item.offeringId) },
brandId,
isEnabled: true,
},
})
: [];
const offeringMap = new Map(offerings.map((offering) => [offering.id, offering]));
const offeringMap = new Map(
snapshot.offerings.flatMap((raw) => {
if (!raw || typeof raw !== "object") return [];
const item = raw as Record<string, unknown>;
return typeof item.id === "string" && item.isEnabled === true
? [[item.id, item] as const]
: [];
}),
);
const items = (input.items ?? []).map((item) => {
const offering = offeringMap.get(item.offeringId);
if (!offering || offering.priceAmount === null)
if (!offering || typeof offering.priceAmount !== "number")
throw new BadRequestException("套餐不存在或暂不可预订");
return {
offeringId: offering.id,
serviceNameSnapshot: offering.name,
offeringId: item.offeringId,
serviceNameSnapshot: String(offering.name),
unitPriceSnapshot: offering.priceAmount,
quantity: item.quantity,
subtotalSnapshot: offering.priceAmount * item.quantity,
+225
View File
@@ -0,0 +1,225 @@
import {
BadRequestException,
ConflictException,
Injectable,
NotFoundException,
} from "@nestjs/common";
import { Prisma } from "@prisma/client";
import {
getBrandTemplate,
getVisualTemplate,
isVisualTemplateCompatible,
getDefaultVisualTemplateKey,
} from "@personal-brand/config";
import { PrismaService } from "./prisma.service.js";
import { BrandReleaseService } from "./brand-release.service.js";
import { validateFieldSnapshot } from "@personal-brand/validation";
@Injectable()
export class BrandReleaseApiService {
constructor(
private readonly prisma: PrismaService,
private readonly snapshots: BrandReleaseService,
) {}
async list(brandId: string): Promise<unknown[]> {
return this.prisma.brandRelease.findMany({
where: { brandId },
orderBy: { version: "desc" },
select: {
id: true,
version: true,
status: true,
note: true,
actorId: true,
createdAt: true,
revokedAt: true,
revokedBy: true,
},
});
}
async readiness(
brandId: string,
database: Prisma.TransactionClient = this.prisma,
): Promise<{
ready: boolean;
checks: Array<{ key: string; label: string; passed: boolean }>;
}> {
const brand = await database.brandProfile.findUnique({
where: { id: brandId },
select: { name: true, tagline: true, description: true, templateKey: true, config: true },
});
const installation = await database.brandTemplateInstallation.findFirst({
where: { brandId },
orderBy: { updatedAt: "desc" },
});
const template = getBrandTemplate(installation?.templateKey ?? brand?.templateKey ?? "");
const config = this.jsonObject(brand?.config);
const visualKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: getDefaultVisualTemplateKey(brand?.templateKey ?? "personal");
const visual = getVisualTemplate(visualKey);
const [offerings, forms, trust] = await Promise.all([
database.offering.findMany({ where: { brandId, isEnabled: true }, select: { id: true } }),
database.inquiryForm.findMany({
where: { brandId, isEnabled: true },
select: { offeringId: true, fieldsSnapshot: true },
}),
database.trustContent.count({ where: { brandId, isPublished: true } }),
]);
const offeringIds = new Set(offerings.map((item) => item.id));
const usableForms = forms.filter(
(form) =>
(form.offeringId === null || offeringIds.has(form.offeringId)) &&
Array.isArray(form.fieldsSnapshot) &&
form.fieldsSnapshot.length > 0 &&
validateFieldSnapshot(form.fieldsSnapshot).length === 0,
);
const checks = [
{ key: "brand", label: "请先完善品牌名称", passed: Boolean(brand?.name.trim()) },
{
key: "positioning",
label: "请先完善品牌定位和介绍",
passed: Boolean(brand?.tagline?.trim() && brand.description?.trim()),
},
{ key: "template", label: "当前行业模板不存在", passed: Boolean(template) },
{
key: "visual",
label: "当前视觉模板不适配行业模板",
passed: Boolean(visual && template && isVisualTemplateCompatible(visual, template.key)),
},
{ key: "offerings", label: "至少需要一项已启用的业务提供项", passed: offerings.length > 0 },
{ key: "forms", label: "至少需要一个可用的咨询表单", passed: usableForms.length > 0 },
{ key: "trust", label: "至少需要一条已发布的信任内容", passed: trust > 0 },
];
return { ready: checks.every((check) => check.passed), checks };
}
async publish(brandId: string, actorId: string, note?: string): Promise<unknown> {
return this.withVersionRetry(() =>
this.prisma.$transaction(
async (tx) => {
await this.validateForPublish(brandId, tx);
const snapshot = await this.snapshots.buildSnapshot(brandId, tx);
const latest = await tx.brandRelease.findFirst({
where: { brandId },
orderBy: { version: "desc" },
select: { version: true },
});
await tx.brandRelease.updateMany({
where: { brandId, status: "published" },
data: { status: "superseded" },
});
return tx.brandRelease.create({
data: {
brandId,
version: (latest?.version ?? 0) + 1,
status: "published",
snapshot: this.snapshots.toPrismaJson(snapshot),
actorId,
...(note === undefined ? {} : { note }),
},
});
},
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
),
);
}
async rollback(
brandId: string,
actorId: string,
version: number,
note?: string,
): Promise<unknown> {
return this.withVersionRetry(() =>
this.prisma.$transaction(
async (tx) => {
const source = await tx.brandRelease.findFirst({
where: { brandId, version, status: { in: ["published", "superseded"] } },
});
if (!source) throw new NotFoundException("发布版本不存在");
const snapshot = this.withCurrentTimestamp(source.snapshot);
const latest = await tx.brandRelease.findFirst({
where: { brandId },
orderBy: { version: "desc" },
select: { version: true },
});
await tx.brandRelease.updateMany({
where: { brandId, status: "published" },
data: { status: "superseded" },
});
return tx.brandRelease.create({
data: {
brandId,
version: (latest?.version ?? 0) + 1,
status: "published",
snapshot,
actorId,
note: note ?? `回滚自版本 ${version}`,
},
});
},
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
),
);
}
async revoke(brandId: string, actorId: string): Promise<unknown> {
return this.withVersionRetry(() =>
this.prisma.$transaction(
async (tx) => {
const current = await tx.brandRelease.findFirst({
where: { brandId, status: "published" },
orderBy: { version: "desc" },
});
if (!current) throw new NotFoundException("当前没有已发布版本");
return tx.brandRelease.update({
where: { id: current.id },
data: { status: "revoked", revokedAt: new Date(), revokedBy: actorId },
select: { id: true, version: true, status: true, revokedAt: true, revokedBy: true },
});
},
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
),
);
}
private async validateForPublish(
brandId: string,
database: Prisma.TransactionClient,
): Promise<void> {
const readiness = await this.readiness(brandId, database);
const missing = readiness.checks.find((check) => !check.passed);
if (missing) throw new BadRequestException(missing.label);
}
private async withVersionRetry<T>(operation: () => Promise<T>): Promise<T> {
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return await operation();
} catch (error) {
if (
!(error instanceof Prisma.PrismaClientKnownRequestError) ||
!["P2002", "P2034"].includes(error.code)
)
throw error;
if (attempt === 2) throw new ConflictException("发布版本冲突,请重试");
}
}
throw new ConflictException("发布版本冲突,请重试");
}
private jsonObject(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
private withCurrentTimestamp(value: Prisma.JsonValue): Prisma.InputJsonValue {
const snapshot = this.jsonObject(value);
return { ...snapshot, generatedAt: new Date().toISOString() };
}
}
+129
View File
@@ -0,0 +1,129 @@
import { Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import {
getBrandTemplate,
getVisualTemplate,
getVisualTemplateManifest,
getDefaultVisualTemplateKey,
} from "@personal-brand/config";
import { PrismaService } from "./prisma.service.js";
export interface BrandReleaseSnapshot {
schemaVersion: "1.0.0";
generatedAt: string;
templateKey: string;
templateDefinition?: ReturnType<typeof getBrandTemplate> | null;
visualTemplateDefinition?: ReturnType<typeof getVisualTemplate> | null;
visualTemplateManifest?: ReturnType<typeof getVisualTemplateManifest> | null;
brand: Record<string, unknown> | null;
installation: Record<string, unknown> | null;
modules: unknown[];
fields: unknown[];
offerings: unknown[];
forms: unknown[];
trustContents: unknown[];
capabilities: unknown[];
}
export async function buildBrandReleaseSnapshot(
database: Prisma.TransactionClient,
brandId: string,
): Promise<BrandReleaseSnapshot> {
const [brand, installation, modules, fields, offerings, forms, trustContents, capabilities] =
await Promise.all([
database.brandProfile.findUnique({ where: { id: brandId } }),
database.brandTemplateInstallation.findFirst({
where: { brandId },
orderBy: { updatedAt: "desc" },
}),
database.brandModule.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
database.brandFieldDefinition.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
database.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
database.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" } }),
database.trustContent.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
database.capabilityInstallation.findMany({ where: { brandId } }),
]);
const templateKey = installation?.templateKey ?? brand?.templateKey ?? "personal";
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const visualKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: getDefaultVisualTemplateKey(brand?.templateKey ?? "personal");
const jsonObject = (value: object): Record<string, unknown> =>
JSON.parse(JSON.stringify(value)) as Record<string, unknown>;
return {
schemaVersion: "1.0.0",
generatedAt: new Date().toISOString(),
templateKey,
templateDefinition: getBrandTemplate(templateKey) ?? null,
visualTemplateDefinition: getVisualTemplate(visualKey) ?? null,
visualTemplateManifest: getVisualTemplateManifest(visualKey) ?? null,
brand: brand ? jsonObject(brand) : null,
installation: installation ? jsonObject(installation) : null,
modules: modules.map((item) => jsonObject(item)),
fields: fields.map((item) => jsonObject(item)),
offerings: offerings.map((item) => jsonObject(item)),
forms: forms.map((item) => jsonObject(item)),
trustContents: trustContents.map((item) => jsonObject(item)),
capabilities: capabilities.map((item) => jsonObject(item)),
};
}
@Injectable()
export class BrandReleaseService {
constructor(private readonly prisma: PrismaService) {}
async getPublishedSnapshot(brandId: string): Promise<BrandReleaseSnapshot | null> {
const release = await this.prisma.brandRelease.findFirst({
where: { brandId, status: "published" },
orderBy: { version: "desc" },
select: { snapshot: true },
});
return release ? (release.snapshot as unknown as BrandReleaseSnapshot) : null;
}
publishedOfferingIds(snapshot: BrandReleaseSnapshot): Set<string> {
return new Set(
snapshot.offerings.flatMap((raw) => {
const item = this.record(raw);
return item.isEnabled === true && typeof item.id === "string" ? [item.id] : [];
}),
);
}
publishedForm(snapshot: BrandReleaseSnapshot, formId: string): Record<string, unknown> | null {
const offeringIds = this.publishedOfferingIds(snapshot);
return (
snapshot.forms
.map((raw) => this.record(raw))
.find((form) => {
return (
form.id === formId &&
form.isEnabled === true &&
(form.offeringId === null ||
(typeof form.offeringId === "string" && offeringIds.has(form.offeringId)))
);
}) ?? null
);
}
private record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
async buildSnapshot(
brandId: string,
database: Prisma.TransactionClient = this.prisma,
): Promise<BrandReleaseSnapshot> {
return buildBrandReleaseSnapshot(database, brandId);
}
toPrismaJson(snapshot: BrandReleaseSnapshot): Prisma.InputJsonValue {
return snapshot as unknown as Prisma.InputJsonValue;
}
}
@@ -15,12 +15,29 @@ import { Prisma } from "@prisma/client";
import type { FastifyRequest } from "fastify";
import { PrismaService } from "../../prisma.service.js";
import { readIdentity } from "../../auth.js";
import { CreateTrustContentDto, UpdateBrandDto, UpdateTrustContentDto } from "../../admin.dto.js";
import { getVisualTemplate } from "@personal-brand/config";
import {
CreateTrustContentDto,
UpdateBrandDto,
UpdateBrandPresentationDto,
UpdateTrustContentDto,
} from "../../admin.dto.js";
import {
getBrandTemplate,
getVisualTemplate,
isVisualTemplateCompatible,
listVisualTemplateKeys,
getDefaultVisualTemplateKey,
} from "@personal-brand/config";
import { AdminAccessService } from "../../admin-access.service.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
@Controller("admin/config")
export class AdminConfigController {
constructor(private readonly prisma: PrismaService) {}
constructor(
private readonly prisma: PrismaService,
private readonly access: AdminAccessService,
private readonly templateWorkspace: TemplateWorkspaceService,
) {}
private brandId(request?: FastifyRequest): string {
if (!request) return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
@@ -52,6 +69,9 @@ export class AdminConfigController {
): Promise<unknown> {
this.requireAdmin(request);
const { config, ...fields } = body;
if (config?.visualTemplateKey !== undefined) {
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
}
const current = await this.prisma.brandProfile.findUnique({
where: { id: this.brandId(request) },
select: { config: true },
@@ -62,6 +82,19 @@ export class AdminConfigController {
: {};
const nextConfig = config ? { ...currentConfig, ...config } : undefined;
if (config?.visualTemplateKey && config.visualTemplateKey !== currentConfig.visualTemplateKey) {
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(
this.brandId(request),
);
const visualTemplate =
typeof config.visualTemplateKey === "string"
? getVisualTemplate(config.visualTemplateKey)
: undefined;
if (
!visualTemplate ||
!getBrandTemplate(templateKey) ||
!isVisualTemplateCompatible(visualTemplate, templateKey)
)
throw new BadRequestException("当前视觉模板不适配该行业模板");
const installation = await this.prisma.brandTemplateInstallation.findFirst({
where: { brandId: this.brandId(request) },
});
@@ -75,7 +108,8 @@ export class AdminConfigController {
previousSnapshots: [
...history,
{
visualTemplateKey: currentConfig.visualTemplateKey ?? "linjing-editorial",
visualTemplateKey:
currentConfig.visualTemplateKey ?? getDefaultVisualTemplateKey(templateKey),
savedAt: new Date().toISOString(),
},
],
@@ -91,6 +125,74 @@ export class AdminConfigController {
},
});
}
@Patch("presentation")
async updatePresentation(
@Req() request: FastifyRequest,
@Body() body: UpdateBrandPresentationDto,
): Promise<unknown> {
this.requireAdmin(request);
const brandId = this.brandId(request);
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { config: true },
});
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const previous =
config.visualPresentation &&
typeof config.visualPresentation === "object" &&
!Array.isArray(config.visualPresentation)
? (config.visualPresentation as Record<string, unknown>)
: {};
const nextPresentation = { ...previous };
const identity = body.identity;
const identityFields = ["founder", "title", "slogan", "phone", "wechat", "studioAddress"];
const nextIdentity = identity
? Object.fromEntries(
identityFields
.filter((key) => typeof identity[key] === "string")
.map((key) => [key, identity[key]]),
)
: {};
for (const section of [
"home",
"offerings",
"detail",
"profile",
"inquiry",
"success",
"records",
] as const) {
const input = body[section];
if (!input) continue;
const current =
previous[section] &&
typeof previous[section] === "object" &&
!Array.isArray(previous[section])
? (previous[section] as Record<string, unknown>)
: {};
const values = Object.fromEntries(
Object.entries(input).filter(([, value]) => typeof value === "string"),
);
nextPresentation[section] = { ...current, ...values };
}
const updated = await this.prisma.brandProfile.update({
where: { id: brandId },
data: {
config: {
...config,
...nextIdentity,
visualPresentation: nextPresentation,
} as Prisma.InputJsonValue,
},
select: { config: true },
});
return {
visualPresentation: (updated.config as Record<string, unknown>).visualPresentation,
};
}
@Get("visual-template/history")
getVisualTemplateHistory(@Req() request: FastifyRequest): unknown {
this.requireAdmin(request);
@@ -169,7 +271,7 @@ export class AdminConfigController {
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: "linjing-editorial";
const current = getVisualTemplate(currentKey) ?? getVisualTemplate("linjing-editorial");
const current = getVisualTemplate(currentKey);
return {
current: current
? {
@@ -180,7 +282,7 @@ export class AdminConfigController {
variants: current.variants,
}
: null,
available: ["linjing-editorial", "minimal-neutral"],
available: listVisualTemplateKeys(),
};
});
}
@@ -0,0 +1,54 @@
import { Controller, Get, Param, ParseIntPipe, Post, Body, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "../../admin-access.service.js";
import { BrandReleaseApiService } from "../../brand-release-api.service.js";
import { PublishBrandReleaseDto } from "../../release.dto.js";
@Controller("admin/releases")
export class AdminReleaseController {
constructor(
private readonly access: AdminAccessService,
private readonly releases: BrandReleaseApiService,
) {}
@Get()
async list(@Req() request: FastifyRequest): Promise<unknown[]> {
const identity = await this.requireBrand(request);
return this.releases.list(identity.brandId);
}
@Get("readiness")
async readiness(@Req() request: FastifyRequest): Promise<unknown> {
const identity = await this.requireBrand(request);
return this.releases.readiness(identity.brandId);
}
@Post("publish")
async publish(
@Req() request: FastifyRequest,
@Body() body: PublishBrandReleaseDto,
): Promise<unknown> {
const identity = await this.requireBrand(request);
return this.releases.publish(identity.brandId, identity.subject, body.note);
}
@Post(":version/rollback")
async rollback(
@Req() request: FastifyRequest,
@Param("version", ParseIntPipe) version: number,
@Body() body: PublishBrandReleaseDto,
): Promise<unknown> {
const identity = await this.requireBrand(request);
return this.releases.rollback(identity.brandId, identity.subject, version, body.note);
}
@Post("revoke")
async revoke(@Req() request: FastifyRequest): Promise<unknown> {
const identity = await this.requireBrand(request);
return this.releases.revoke(identity.brandId, identity.subject);
}
private requireBrand(request: FastifyRequest): Promise<{ subject: string; brandId: string }> {
return this.access.requireBrand(request);
}
}
@@ -15,10 +15,14 @@ import type { FastifyRequest } from "fastify";
import { PrismaService } from "../../prisma.service.js";
import { readIdentity } from "../../auth.js";
import { CreateInquirySubmissionDto } from "../../booking.dto.js";
import { BrandReleaseService } from "../../brand-release.service.js";
@Controller("customer/inquiry-submissions")
export class CustomerInquirySubmissionController {
constructor(private readonly prisma: PrismaService) {}
constructor(
private readonly prisma: PrismaService,
private readonly releases: BrandReleaseService,
) {}
private present<T extends { customerSubject: string; adminNote?: string | null }>(submission: T) {
const {
customerSubject: _customerSubject,
@@ -84,16 +88,27 @@ export class CustomerInquirySubmissionController {
@Body() body: CreateInquirySubmissionDto,
): Promise<unknown> {
const identity = this.identity(request);
const snapshot = await this.releases.getPublishedSnapshot(identity.brandId);
const publishedForm = snapshot && this.releases.publishedForm(snapshot, body.formId);
if (!publishedForm) throw new BadRequestException("咨询表单不存在或品牌尚未发布");
const form = await this.prisma.inquiryForm.findFirst({
where: {
id: body.formId,
brandId: identity.brandId,
isEnabled: true,
OR: [{ offeringId: null }, { offering: { isEnabled: true } }],
},
});
if (!form) throw new BadRequestException("咨询表单不存在");
const capabilityKey = form.purpose === "quote-request" ? "quote-request" : "inquiry";
const offeringId =
typeof publishedForm.offeringId === "string" ? publishedForm.offeringId : null;
if (offeringId) {
const offering = await this.prisma.offering.findFirst({
where: { id: offeringId, brandId: identity.brandId, isEnabled: true },
select: { id: true },
});
if (!offering) throw new BadRequestException("当前业务提供项不可用");
}
const capabilityKey = publishedForm.purpose === "quote-request" ? "quote-request" : "inquiry";
const capability = await this.prisma.capabilityInstallation.findUnique({
where: {
brandId_capabilityKey: { brandId: identity.brandId, capabilityKey },
@@ -101,8 +116,8 @@ export class CustomerInquirySubmissionController {
});
if (capability && capability.status !== "enabled")
throw new BadRequestException("当前咨询能力不可用");
const fields = Array.isArray(form.fieldsSnapshot)
? (form.fieldsSnapshot as Array<Record<string, unknown>>)
const fields = Array.isArray(publishedForm.fieldsSnapshot)
? (publishedForm.fieldsSnapshot as Array<Record<string, unknown>>)
: [];
for (const field of fields) {
const key = typeof field.key === "string" ? field.key : "";
@@ -126,9 +141,9 @@ export class CustomerInquirySubmissionController {
brandId: identity.brandId,
customerSubject: identity.subject,
inquiryFormId: form.id,
offeringId: form.offeringId,
formVersion: form.version,
fieldsSnapshot: form.fieldsSnapshot as Prisma.InputJsonValue,
offeringId,
formVersion: Number(publishedForm.version),
fieldsSnapshot: publishedForm.fieldsSnapshot as Prisma.InputJsonValue,
values: values as Prisma.InputJsonValue,
activeFields: Object.fromEntries(Object.keys(values).map((key) => [key, true])),
},
@@ -1,23 +1,19 @@
import { BadRequestException, Controller, Get, Param, Query } from "@nestjs/common";
import { PrismaService } from "../../prisma.service.js";
import { PublicBrandContextService } from "./public-brand-context.service.js";
import { BrandReleaseService } from "../../brand-release.service.js";
@Controller("public/inquiry-forms")
export class PublicInquiryFormController {
constructor(
private readonly prisma: PrismaService,
private readonly releases: BrandReleaseService,
private readonly brandContext: PublicBrandContextService,
) {}
@Get(":id")
async get(@Param("id") id: string, @Query("brandSlug") brandSlug?: string): Promise<unknown> {
const form = await this.prisma.inquiryForm.findFirst({
where: {
id,
brandId: await this.brandContext.resolveId(brandSlug),
isEnabled: true,
OR: [{ offeringId: null }, { offering: { isEnabled: true } }],
},
});
const snapshot = await this.releases.getPublishedSnapshot(
await this.brandContext.resolveId(brandSlug),
);
const form = snapshot && this.releases.publishedForm(snapshot, id);
if (!form) throw new BadRequestException("咨询表单不存在");
return form;
}
@@ -1,51 +1,52 @@
import { BadRequestException, Controller, Get, Param, Query } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { PrismaService } from "../../prisma.service.js";
import { PublicBrandContextService } from "./public-brand-context.service.js";
import { BrandReleaseService } from "../../brand-release.service.js";
@Controller("public/offerings")
export class PublicOfferingController {
constructor(
private readonly prisma: PrismaService,
private readonly releases: BrandReleaseService,
private readonly brandContext: PublicBrandContextService,
) {}
@Get()
async list(@Query("brandSlug") brandSlug?: string): Promise<unknown> {
const brandId = await this.brandContext.resolveId(brandSlug);
const items = await this.prisma.offering.findMany({
where: { brandId, isEnabled: true },
orderBy: { sortOrder: "asc" },
include: {
inquiryForms: {
where: { isEnabled: true },
orderBy: { updatedAt: "desc" },
select: { id: true, name: true, purpose: true, targetType: true, version: true },
},
},
});
return items.map((item) => this.present(item));
const snapshot = await this.releases.getPublishedSnapshot(brandId);
const forms = snapshot?.forms ?? [];
return (snapshot?.offerings ?? [])
.filter((raw) => this.object(raw).isEnabled === true)
.map((raw) => this.object(raw))
.sort((a, b) => Number(a.sortOrder ?? 0) - Number(b.sortOrder ?? 0))
.map((item) =>
this.present({
...item,
inquiryForms: forms.filter((raw) => {
const form = this.object(raw);
return form.offeringId === item.id && form.isEnabled === true;
}),
}),
);
}
@Get(":id")
async get(@Param("id") id: string, @Query("brandSlug") brandSlug?: string): Promise<unknown> {
const brandId = await this.brandContext.resolveId(brandSlug);
const item = await this.prisma.offering.findFirst({
where: {
id,
brandId,
isEnabled: true,
},
include: {
inquiryForms: {
where: { isEnabled: true },
orderBy: { updatedAt: "desc" },
select: { id: true, name: true, purpose: true, targetType: true, version: true },
},
},
});
const snapshot = await this.releases.getPublishedSnapshot(brandId);
const item = (snapshot?.offerings ?? [])
.map((raw) => this.object(raw))
.find((offering) => offering.id === id && offering.isEnabled === true);
if (!item) throw new BadRequestException("业务提供项不存在");
return this.present(item);
const forms = (snapshot?.forms ?? []).filter((raw) => {
const form = this.object(raw);
return form.offeringId === id && form.isEnabled === true;
});
return this.present({ ...item, inquiryForms: forms });
}
private present(item: { config: Prisma.JsonValue; [key: string]: unknown }): unknown {
private object(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
private present(item: { config?: unknown; [key: string]: unknown }): unknown {
const config = (item.config ?? {}) as Record<string, unknown>;
return {
...item,
@@ -2,12 +2,14 @@ import { Controller, Get, Query } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { PrismaService } from "../../prisma.service.js";
import { PublicBrandContextService } from "./public-brand-context.service.js";
import type { BrandReleaseSnapshot } from "../../brand-release.service.js";
import {
getBrandTemplate,
getVisualTemplate,
getVisualTemplateManifest,
resolveCapabilities,
capabilityPlugins,
getDefaultVisualTemplateKey,
} from "@personal-brand/config";
import type {
RuntimeInquiryField,
@@ -22,60 +24,77 @@ export class PublicWorkspaceController {
private readonly prisma: PrismaService,
private readonly brandContext: PublicBrandContextService,
) {}
private readonly cache = new Map<string, { expiresAt: number; value: unknown }>();
@Get()
async get(@Query("brandSlug") brandSlug?: string): Promise<unknown> {
const brandId = await this.brandContext.resolveId(brandSlug);
const cached = process.env.NODE_ENV === "test" ? undefined : this.cache.get(brandId);
if (cached && cached.expiresAt > Date.now()) return cached.value;
const [
brand,
modules,
fields,
offerings,
inquiryForms,
installation,
capabilityInstallations,
trustContents,
] = await Promise.all([
this.prisma.brandProfile.findUnique({ where: { id: brandId } }),
this.prisma.brandModule.findMany({
where: { brandId, isEnabled: true },
orderBy: { sortOrder: "asc" },
}),
this.prisma.brandFieldDefinition.findMany({
where: { brandId, isVisible: true },
orderBy: { sortOrder: "asc" },
}),
this.prisma.offering.findMany({
where: { brandId, isEnabled: true },
orderBy: { sortOrder: "asc" },
}),
this.prisma.inquiryForm.findMany({
where: {
brandId,
isEnabled: true,
OR: [{ offeringId: null }, { offering: { isEnabled: true } }],
},
orderBy: { updatedAt: "desc" },
}),
this.prisma.brandTemplateInstallation.findFirst({
where: { brandId },
orderBy: { updatedAt: "desc" },
}),
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
this.prisma.trustContent.findMany({
where: { brandId, isPublished: true },
orderBy: { sortOrder: "asc" },
}),
]);
const templateKey = installation?.templateKey ?? brand?.templateKey ?? "personal";
const template = getBrandTemplate(templateKey);
const runtimeCapabilities = capabilityInstallations.length
? capabilityInstallations.map((item) => ({
key: item.capabilityKey,
version: item.capabilityVersion,
status: item.status as "enabled" | "disabled" | "degraded",
const release = await this.prisma.brandRelease.findFirst({
where: { brandId, status: "published" },
orderBy: { version: "desc" },
select: { version: true, createdAt: true, snapshot: true },
});
const releaseSnapshot = this.jsonObject(release?.snapshot) as unknown as BrandReleaseSnapshot;
if (!release) {
return {
contractVersion: "1.0",
schemaVersion: "1.0.0",
publication: { status: "unpublished", version: null },
brand: null,
template: null,
visualTemplate: null,
modules: [],
offerings: [],
inquiryForms: [],
capabilities: [],
runtimeCapabilities: [],
runtimeModules: [],
fields: [],
trustContent: [],
trustPresentation: {},
inquiryForm: null,
navigation: { tabs: [] },
plugins: [],
theme: { colors: {} },
};
}
const brandData = this.jsonObject(releaseSnapshot.brand);
const modulesData = this.jsonArray(releaseSnapshot.modules).filter(
(item) => this.jsonObject(item).isEnabled === true,
) as Array<Record<string, unknown>>;
const fieldsData = this.jsonArray(releaseSnapshot.fields).filter(
(item) => this.jsonObject(item).isVisible === true,
);
const offeringsData = this.jsonArray(releaseSnapshot.offerings).filter(
(item) => this.jsonObject(item).isEnabled === true,
) as Array<Record<string, unknown>>;
const enabledOfferingIds = new Set(offeringsData.map((item) => item.id));
const formsData = this.jsonArray(releaseSnapshot.forms).filter((item) => {
const form = this.jsonObject(item);
return (
form.isEnabled === true &&
(form.offeringId === null || enabledOfferingIds.has(form.offeringId))
);
});
const trustData = this.jsonArray(releaseSnapshot.trustContents).filter(
(item) => this.jsonObject(item).isPublished === true,
) as Array<Record<string, unknown>>;
const installationData = this.jsonObject(releaseSnapshot.installation);
const templateKeyFromSnapshot =
typeof releaseSnapshot.templateKey === "string" ? releaseSnapshot.templateKey : undefined;
const templateKey =
templateKeyFromSnapshot ??
(typeof installationData.templateKey === "string"
? installationData.templateKey
: undefined) ??
(typeof brandData.templateKey === "string" ? brandData.templateKey : "personal");
const template = releaseSnapshot.templateDefinition ?? getBrandTemplate(templateKey);
const capabilityData = this.jsonArray(releaseSnapshot.capabilities) as Array<
Record<string, unknown>
>;
const runtimeCapabilities = capabilityData.length
? capabilityData.map((item) => ({
key: this.string(item.capabilityKey),
version: this.string(item.capabilityVersion, "1.0.0"),
status: this.capabilityStatus(item.status),
config:
item.config && typeof item.config === "object" && !Array.isArray(item.config)
? (item.config as Record<string, unknown>)
@@ -90,43 +109,96 @@ export class PublicWorkspaceController {
}))
: [];
const brandConfig =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
brandData.config && typeof brandData.config === "object" && !Array.isArray(brandData.config)
? (brandData.config as Record<string, unknown>)
: {};
const visualTemplateKey =
typeof brandConfig.visualTemplateKey === "string"
? brandConfig.visualTemplateKey
: "linjing-editorial";
: getDefaultVisualTemplateKey(templateKey);
const visualTemplate =
getVisualTemplate(visualTemplateKey) ?? getVisualTemplate("linjing-editorial");
releaseSnapshot.visualTemplateDefinition ?? getVisualTemplate(visualTemplateKey);
const visualTemplateManifest =
getVisualTemplateManifest(visualTemplateKey) ??
getVisualTemplateManifest("linjing-editorial");
releaseSnapshot.visualTemplateManifest ?? getVisualTemplateManifest(visualTemplateKey);
const runtimeBrand = {
...(brand ?? {}),
...brandData,
...brandConfig,
};
const runtimeModules: RuntimeModule[] = modules.map((module) => ({
key: module.type,
type: this.moduleType(module.type),
const runtimeModules: RuntimeModule[] = modulesData.map((item) => ({
key: this.string(item.type, "custom"),
type: this.moduleType(this.string(item.type, "custom")),
version: "1.0.0",
propsSchema: `module.${module.type}.v1`,
dataSource: module.type,
config: this.jsonObject(module.config),
propsSchema: `module.${this.string(item.type, "custom")}.v1`,
dataSource: this.string(item.type, "custom"),
config: this.jsonObject(item.config),
source:
module.source === "custom" ? "custom" : module.source === "template" ? "template" : "core",
item.source === "custom" ? "custom" : item.source === "template" ? "template" : "core",
schemaVersion: "1.0",
}));
const runtimeOfferings: RuntimeOffering[] = offerings.map((item) => {
const runtimeOfferings: RuntimeOffering[] = offeringsData.map((raw) => {
const item = raw;
const config = this.jsonObject(item.config);
const sections = Array.isArray(config.sections) ? config.sections : [];
const details = this.jsonObject(config.details);
const media = Array.isArray(config.media)
? config.media.flatMap((entry) => {
const value = this.jsonObject(entry);
return typeof value.url === "string"
? [
{
url: value.url,
alt:
typeof value.alt === "string"
? value.alt
: this.string(item.name, "业务提供项"),
type: "image" as const,
},
]
: [];
})
: [];
const materialsList = Array.isArray(details.materialsList)
? details.materialsList.flatMap((entry) => {
const value = this.jsonObject(entry);
return typeof value.name === "string" && typeof value.spec === "string"
? [{ name: value.name, spec: value.spec }]
: [];
})
: [];
return {
id: item.id,
name: item.name,
summary: item.summary ?? item.description ?? "",
enabled: item.isEnabled,
id: this.string(item.id),
name: this.string(item.name),
summary: typeof item.summary === "string" ? item.summary : this.string(item.description),
enabled: item.isEnabled !== false,
kind: this.offeringKind(this.string(item.kind, "service")),
coverUrl: typeof item.coverUrl === "string" ? item.coverUrl : null,
priceText: typeof item.priceText === "string" ? item.priceText : null,
priceAmount: typeof item.priceAmount === "number" ? item.priceAmount : null,
schemaKey: typeof config.schemaKey === "string" ? config.schemaKey : "offering.default",
schemaVersion: typeof config.schemaVersion === "string" ? config.schemaVersion : "1.0.0",
presentation: {
categoryKey: typeof config.categoryKey === "string" ? config.categoryKey : "custom",
categoryLabel:
typeof config.categoryLabel === "string" ? config.categoryLabel : "业务提供项",
heroImage:
typeof config.detailHero === "string"
? config.detailHero
: typeof item.coverUrl === "string"
? item.coverUrl
: null,
keywords: Array.isArray(config.keywords)
? config.keywords.filter((keyword): keyword is string => typeof keyword === "string")
: [],
media,
details: {
background: typeof details.background === "string" ? details.background : "",
designConcept: typeof details.designConcept === "string" ? details.designConcept : "",
crafts: Array.isArray(details.crafts)
? details.crafts.filter((craft): craft is string => typeof craft === "string")
: [],
materialsList,
},
},
sections: sections
.filter((section): section is Record<string, unknown> =>
Boolean(section && typeof section === "object"),
@@ -152,11 +224,12 @@ export class PublicWorkspaceController {
"checkbox",
"textarea",
"date",
].includes(String(value.type))
].includes(this.string(value.type))
? (value.type as RuntimeInquiryField["type"])
: "text";
const options = Array.isArray(value.options)
? value.options.flatMap((option) => {
if (typeof option === "string") return [{ label: option, value: option }];
if (!option || typeof option !== "object") return [];
const item = option as Record<string, unknown>;
return typeof item.label === "string" && typeof item.value === "string"
@@ -174,9 +247,23 @@ export class PublicWorkspaceController {
},
];
});
const inquiryForm = inquiryForms[0] ?? null;
const inquiryForm = formsData[0] ?? null;
const trustPresentation = trustData.reduce<Record<string, unknown>>((result, raw) => {
const item = this.jsonObject(raw);
const config = this.jsonObject(item.config);
for (const [key, value] of Object.entries(config)) {
if (!(key in result)) result[key] = value;
}
if (item.type === "profile" && typeof result.bio !== "string") result.bio = item.content;
return result;
}, {});
const runtimeWorkspace: RuntimeWorkspace = {
schemaVersion: "1.0.0",
publication: {
status: "published",
version: release.version,
publishedAt: release.createdAt.toISOString(),
},
brand: runtimeBrand,
navigation: {
tabs: [
@@ -187,15 +274,24 @@ export class PublicWorkspaceController {
},
modules: runtimeModules,
offerings: runtimeOfferings,
inquiryForms: inquiryForms.map((form) => ({
key: form.id,
version: String(form.version),
purpose: this.formPurpose(form.purpose),
target: form.targetType === "offering" ? "offering" : "brand",
...(form.offeringId ? { targetId: form.offeringId } : {}),
submissionAction: this.submissionAction(form.submissionAction),
fields: toInquiryFields(form.fieldsSnapshot),
})),
inquiryForms: formsData.map((raw) => {
const form = this.jsonObject(raw);
return {
key: this.string(form.id),
version:
typeof form.version === "number"
? String(form.version)
: this.string(form.version, "1"),
purpose: this.formPurpose(this.string(form.purpose, "inquiry")),
target: form.targetType === "offering" ? "offering" : "brand",
...(typeof form.offeringId === "string" ? { targetId: form.offeringId } : {}),
submissionAction: this.submissionAction(
this.string(form.submissionAction, "create-inquiry"),
),
fields: toInquiryFields(form.fieldsSnapshot as Prisma.JsonValue),
};
}),
trustPresentation,
capabilities: runtimeCapabilities,
plugins: runtimeCapabilities
.filter((capability) => capability.status === "enabled")
@@ -215,7 +311,10 @@ export class PublicWorkspaceController {
template: template
? {
key: template.key,
version: installation?.templateVersion ?? template.version,
version:
typeof installationData.templateVersion === "string"
? installationData.templateVersion
: template.version,
name: template.name,
}
: null,
@@ -224,21 +323,19 @@ export class PublicWorkspaceController {
key: visualTemplate.key,
version: visualTemplate.version,
name: visualTemplate.name,
supportedIndustryTemplates: visualTemplate.supportedIndustryTemplates,
variants: visualTemplate.variants,
}
: null,
visualTemplateManifest,
capabilities: runtimeCapabilities,
runtimeCapabilities,
modules,
runtimeModules,
fields,
offerings,
trustContent: trustContents,
fields: fieldsData,
trustContent: trustData,
trustPresentation,
inquiryForm,
};
if (process.env.NODE_ENV !== "test")
this.cache.set(brandId, { expiresAt: Date.now() + 30_000, value: response });
return response;
}
private jsonObject(value: unknown): Record<string, unknown> {
@@ -246,10 +343,22 @@ export class PublicWorkspaceController {
? (value as Record<string, unknown>)
: {};
}
private string(value: unknown, fallback = ""): string {
return typeof value === "string" ? value : fallback;
}
private capabilityStatus(value: unknown): "enabled" | "disabled" | "degraded" {
return value === "disabled" || value === "degraded" ? value : "enabled";
}
private jsonArray(value: unknown): Prisma.JsonValue[] {
return Array.isArray(value) ? (value as Prisma.JsonValue[]) : [];
}
private moduleType(value: string): RuntimeModule["type"] {
const aliases: Record<string, RuntimeModule["type"]> = {
identity: "brand-hero",
trust: "trust-proof",
offering: "offering-list",
contact: "founder-card",
};
const known: RuntimeModule["type"][] = [
"brand-hero",
"founder-card",
@@ -264,8 +373,9 @@ export class PublicWorkspaceController {
"records",
"custom",
];
const type = aliases[value] ?? value;
return (
known.includes(value as RuntimeModule["type"]) ? value : "custom"
known.includes(type as RuntimeModule["type"]) ? type : "custom"
) as RuntimeModule["type"];
}
private sectionType(value: unknown): RuntimeOffering["sections"][number]["type"] {
@@ -274,6 +384,12 @@ export class PublicWorkspaceController {
? (value as (typeof known)[number])
: "text";
}
private offeringKind(value: string): RuntimeOffering["kind"] {
const known: RuntimeOffering["kind"][] = ["service", "product", "package", "subscription"];
return known.includes(value as RuntimeOffering["kind"])
? (value as RuntimeOffering["kind"])
: "service";
}
private formPurpose(value: string): RuntimeWorkspace["inquiryForms"][number]["purpose"] {
return value === "booking" || value === "quote-request" ? value : "inquiry";
}
@@ -1,10 +1,11 @@
import { BadRequestException, Controller, Get, Param, Query } from "@nestjs/common";
import { PrismaService } from "../../prisma.service.js";
import { PublicBrandContextService } from "./public-brand-context.service.js";
import { BrandReleaseService } from "../../brand-release.service.js";
import {
brandTemplates,
getBrandTemplate,
getVisualTemplate,
isVisualTemplateCompatible,
resolveCapabilities,
visualTemplates,
} from "@personal-brand/config";
@@ -12,50 +13,59 @@ import {
@Controller("public")
export class PublicController {
constructor(
private readonly prisma: PrismaService,
private readonly releases: BrandReleaseService,
private readonly brandContext: PublicBrandContextService,
) {}
@Get("brand")
async brand(@Query("brandSlug") brandSlug?: string): Promise<unknown> {
return this.prisma.brandProfile.findUnique({
where: {
id: await this.brandContext.resolveId(brandSlug),
},
select: {
id: true,
name: true,
templateKey: true,
tagline: true,
description: true,
avatarUrl: true,
coverUrl: true,
hours: true,
address: true,
deliveryNote: true,
contactPhone: true,
contactWechat: true,
},
});
const snapshot = await this.releases.getPublishedSnapshot(
await this.brandContext.resolveId(brandSlug),
);
if (!snapshot?.brand) return null;
const keys = [
"id",
"name",
"templateKey",
"tagline",
"description",
"avatarUrl",
"coverUrl",
"hours",
"address",
"deliveryNote",
"contactPhone",
"contactWechat",
];
return Object.fromEntries(keys.map((key) => [key, snapshot.brand?.[key] ?? null]));
}
}
@Controller("public/trust-content")
export class PublicTrustContentController {
constructor(
private readonly prisma: PrismaService,
private readonly releases: BrandReleaseService,
private readonly brandContext: PublicBrandContextService,
) {}
@Get()
async list(@Query("brandSlug") brandSlug?: string): Promise<unknown> {
return this.prisma.trustContent.findMany({
where: {
brandId: await this.brandContext.resolveId(brandSlug),
isPublished: true,
},
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
});
const snapshot = await this.releases.getPublishedSnapshot(
await this.brandContext.resolveId(brandSlug),
);
return (snapshot?.trustContents ?? [])
.filter((item) =>
Boolean(
item &&
typeof item === "object" &&
(item as Record<string, unknown>).isPublished === true,
),
)
.sort((left, right) => {
const a = left as { type: string; sortOrder: number };
const b = right as { type: string; sortOrder: number };
return a.type.localeCompare(b.type) || a.sortOrder - b.sortOrder;
});
}
}
@@ -63,7 +73,10 @@ export class PublicTrustContentController {
export class PublicTemplateController {
@Get()
list(): unknown {
return { industries: Object.values(brandTemplates), visuals: Object.values(visualTemplates) };
return {
industries: Object.values(brandTemplates),
visuals: Object.values(visualTemplates),
};
}
@Get("preview")
@@ -72,8 +85,10 @@ export class PublicTemplateController {
@Query("visual") visual = "linjing-editorial",
): unknown {
const industryTemplate = getBrandTemplate(industry);
const visualTemplate = getVisualTemplate(visual) ?? getVisualTemplate("linjing-editorial");
const visualTemplate = getVisualTemplate(visual);
if (!industryTemplate || !visualTemplate) throw new BadRequestException("模板组合不存在");
if (!isVisualTemplateCompatible(visualTemplate, industryTemplate.key))
throw new BadRequestException("当前视觉模板不适配所选行业模板");
return {
industry: industryTemplate,
visual: visualTemplate,
@@ -1,22 +1,39 @@
import { BadRequestException, Body, Controller, Post } from "@nestjs/common";
import {
BadRequestException,
Body,
Controller,
Post,
Query,
Req,
UnauthorizedException,
} from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { PrismaService } from "../../prisma.service.js";
import { WechatAuthService } from "../../wechat-auth.js";
import { AdminAuthService } from "../../admin-auth.service.js";
import { AdminLoginDto, WechatLoginDto } from "../../admin-auth.dto.js";
import { signIdentity } from "../../auth.js";
import { PublicBrandContextService } from "../public/public-brand-context.service.js";
import { ChangeAdminPasswordDto } from "../../admin.dto.js";
import { readIdentity } from "../../auth.js";
@Controller("customer/session")
export class CustomerSessionController {
constructor(
private readonly wechatAuth: WechatAuthService,
private readonly prisma: PrismaService,
private readonly brandContext: PublicBrandContextService,
) {}
@Post("wechat")
async wechatLogin(@Body() body: WechatLoginDto): Promise<{ token: string }> {
async wechatLogin(
@Body() body: WechatLoginDto,
@Query("brandSlug") brandSlug?: string,
): Promise<{ token: string }> {
const session = await this.wechatAuth.exchangeCode(body.code);
const brandId = await this.brandContext.resolveId(brandSlug);
const brand = await this.prisma.brandProfile.findUnique({
where: { id: process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001" },
where: { id: brandId },
select: { id: true },
});
if (!brand) throw new BadRequestException("品牌尚未初始化");
@@ -36,7 +53,22 @@ export class AdminSessionController {
constructor(private readonly auth: AdminAuthService) {}
@Post("login")
login(@Body() body: AdminLoginDto): Promise<{ token: string; displayName: string }> {
login(
@Body() body: AdminLoginDto,
): Promise<{ token: string; displayName: string; mustChangePassword: boolean; role: string }> {
return this.auth.login(body.username, body.password);
}
@Post("change-password")
async changePassword(
@Req() request: FastifyRequest,
@Body() body: ChangeAdminPasswordDto,
): Promise<{ changed: true }> {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少管理员登录态");
const identity = readIdentity(token);
if (identity.role !== "admin") throw new UnauthorizedException("管理员登录态无效");
await this.auth.changePassword(identity.subject, body.currentPassword, body.newPassword);
return { changed: true };
}
}
@@ -1,8 +1,12 @@
import {
Controller,
BadRequestException,
Body,
ConflictException,
ForbiddenException,
Get,
Param,
Patch,
Post,
Req,
UnauthorizedException,
@@ -10,10 +14,105 @@ import {
import type { FastifyRequest } from "fastify";
import { PrismaService } from "../../prisma.service.js";
import { readIdentity, signIdentity } from "../../auth.js";
import { AdminAccessService } from "../../admin-access.service.js";
import { CreateBrandMemberDto, UpdateBrandMemberDto } from "../../admin.dto.js";
import bcrypt from "bcryptjs";
@Controller("admin/brands")
export class TenantController {
constructor(private readonly prisma: PrismaService) {}
constructor(
private readonly prisma: PrismaService,
private readonly access: AdminAccessService,
) {}
@Get("members")
async listMembers(@Req() request: FastifyRequest): Promise<unknown> {
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
const current = this.adminIdentity(request);
return this.prisma.brandMembership.findMany({
where: { brandId: current.brandId },
include: {
adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } },
},
orderBy: { createdAt: "asc" },
});
}
@Post("members")
async createMember(
@Req() request: FastifyRequest,
@Body() body: CreateBrandMemberDto,
): Promise<unknown> {
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
const actor = this.adminIdentity(request);
const username = body.username.trim();
const displayName = body.displayName.trim();
if (!username || !displayName) throw new BadRequestException("账号和显示名称不能为空");
const existing = await this.prisma.adminUser.findUnique({ where: { username } });
if (existing) throw new ConflictException("账号已存在,请使用其他账号");
const passwordHash = await bcrypt.hash(body.password, 12);
const member = await this.prisma.$transaction(async (tx) => {
const adminUser = await tx.adminUser.create({
data: {
username,
displayName,
passwordHash,
role: "admin",
isEnabled: true,
mustChangePassword: true,
},
});
return tx.brandMembership.create({
data: {
adminUserId: adminUser.id,
brandId: actor.brandId,
role: body.role,
isEnabled: true,
},
include: {
adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } },
},
});
});
return member;
}
@Patch("members/:id")
async updateMember(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateBrandMemberDto,
): Promise<unknown> {
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
const actor = this.adminIdentity(request);
const membership = await this.prisma.brandMembership.findFirst({
where: { id, brandId: actor.brandId },
});
if (!membership) throw new BadRequestException("成员不存在");
if (membership.adminUserId === actor.subject) {
if (body.isEnabled === false || (body.role && body.role !== membership.role)) {
throw new BadRequestException("不能修改自己的角色或停用自己");
}
}
const nextRole = body.role ?? membership.role;
const nextEnabled = body.isEnabled ?? membership.isEnabled;
if (membership.role === "owner" && (nextRole !== "owner" || !nextEnabled)) {
const ownerCount = await this.prisma.brandMembership.count({
where: { brandId: actor.brandId, role: "owner", isEnabled: true },
});
if (ownerCount <= 1) throw new BadRequestException("品牌至少需要保留一位启用的负责人");
}
return this.prisma.brandMembership.update({
where: { id: membership.id },
data: {
...(body.role ? { role: body.role } : {}),
...(body.isEnabled === undefined ? {} : { isEnabled: body.isEnabled }),
},
include: {
adminUser: { select: { id: true, username: true, displayName: true, isEnabled: true } },
},
});
}
@Get()
async list(@Req() request: FastifyRequest): Promise<unknown> {
+7
View File
@@ -0,0 +1,7 @@
import { IsOptional, IsString } from "class-validator";
export class PublishBrandReleaseDto {
@IsOptional()
@IsString()
note?: string;
}
+45 -7
View File
@@ -1,11 +1,33 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { getBrandTemplate, getVisualTemplateManifest } from "@personal-brand/config";
import {
getBrandTemplate,
getVisualTemplate,
getVisualTemplateManifest,
getDefaultVisualTemplateKey,
isVisualTemplateCompatible,
} from "@personal-brand/config";
import type { BrandTemplateKey } from "@personal-brand/types";
import { PrismaService } from "./prisma.service.js";
@Injectable()
export class TemplateWorkspaceService {
constructor(private readonly prisma: PrismaService) {}
async getEffectiveTemplateKey(brandId: string): Promise<BrandTemplateKey> {
const [installation, brand] = await Promise.all([
this.prisma.brandTemplateInstallation.findFirst({
where: { brandId },
orderBy: { updatedAt: "desc" },
select: { templateKey: true },
}),
this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true },
}),
]);
const key = installation?.templateKey ?? brand?.templateKey ?? "personal";
return getBrandTemplate(key) ? (key as BrandTemplateKey) : "personal";
}
async install(brandId: string, templateKey: "personal" | "food" | "doors") {
const template = getBrandTemplate(templateKey);
if (!template) throw new BadRequestException("行业模板不存在");
@@ -23,14 +45,22 @@ export class TemplateWorkspaceService {
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const configuredVisualTemplateKey =
typeof brandConfig.visualTemplateKey === "string" ? brandConfig.visualTemplateKey : undefined;
const visualTemplateKey =
typeof brandConfig.visualTemplateKey === "string"
? brandConfig.visualTemplateKey
: templateKey === "doors"
? "linjing-editorial"
: "minimal-neutral";
configuredVisualTemplateKey &&
getVisualTemplate(configuredVisualTemplateKey) &&
isVisualTemplateCompatible(getVisualTemplate(configuredVisualTemplateKey)!, templateKey)
? configuredVisualTemplateKey
: getDefaultVisualTemplateKey(templateKey);
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
if (!visualManifest) throw new BadRequestException("视觉模板不存在");
const visualTemplate = getVisualTemplate(visualTemplateKey);
if (
!visualManifest ||
!visualTemplate ||
!isVisualTemplateCompatible(visualTemplate, templateKey)
)
throw new BadRequestException("当前视觉模板不适配行业模板");
const templatePackageSnapshot = {
schemaVersion: "1.0",
version: template.version,
@@ -39,6 +69,14 @@ export class TemplateWorkspaceService {
capabilities: template.capabilities,
};
return this.prisma.$transaction(async (tx) => {
if (brandConfig.visualTemplateKey === undefined) {
await tx.brandProfile.update({
where: { id: brandId },
data: {
config: { ...brandConfig, visualTemplateKey },
},
});
}
const installation = await tx.brandTemplateInstallation.create({
data: {
brandId,
+24 -14
View File
@@ -2,6 +2,8 @@ import assert from "node:assert/strict";
import { test } from "node:test";
import { BadRequestException, NotFoundException } from "@nestjs/common";
import { BookingService } from "../src/booking.service.js";
import type { PrismaService } from "../src/prisma.service.js";
import type { BrandReleaseService } from "../src/brand-release.service.js";
const brandId = "brand-1";
const customerId = "customer-1";
@@ -11,20 +13,20 @@ const offering = {
priceAmount: 2800,
};
function createPrisma(overrides: Record<string, unknown> = {}): any {
function createPrisma(overrides: Record<string, unknown> = {}): PrismaService {
return {
offering: {
findMany: async () => [offering],
count: async () => 1,
},
booking: {
create: async ({ data }: any) => ({
create: async ({ data }: { data: { estimatedAmount: number | null } }) => ({
bookingNo: "AC-test",
status: "received",
estimatedAmount: data.estimatedAmount,
createdAt: new Date(),
}),
findFirst: async () => null,
update: async ({ data }: any) => ({ status: data.status }),
update: async ({ data }: { data: { status: string } }) => ({ status: data.status }),
findMany: async () => [],
count: async () => 0,
},
@@ -32,12 +34,20 @@ function createPrisma(overrides: Record<string, unknown> = {}): any {
bookingTag: { deleteMany: {}, createMany: {} },
$transaction: async (callback: (tx: unknown) => unknown) => callback(undefined),
...overrides,
};
} as unknown as PrismaService;
}
function createService(prisma = createPrisma()): BookingService {
const releases = {
getPublishedSnapshot: async () => ({ offerings: [{ ...offering, isEnabled: true }] }),
publishedOfferingIds: () => new Set([offering.id]),
} as unknown as BrandReleaseService;
return new BookingService(prisma, releases);
}
test("创建普通套餐订单时保存价格快照和预计金额", async () => {
const prisma = createPrisma();
const result = await new BookingService(prisma).create(brandId, customerId, {
const result = await createService(prisma).create(brandId, customerId, {
requestType: "package",
customerName: "陈同学",
wechatId: "wx-test",
@@ -51,7 +61,7 @@ test("创建普通套餐订单时保存价格快照和预计金额", async () =>
test("普通套餐不能在没有明细时创建", async () => {
await assert.rejects(
() =>
new BookingService(createPrisma()).create(brandId, customerId, {
createService().create(brandId, customerId, {
requestType: "package",
customerName: "陈同学",
phone: "13800000000",
@@ -69,14 +79,14 @@ test("客户只能取消自己的 received 订单", async () => {
},
});
await assert.rejects(
() => new BookingService(prisma).cancelForCustomer(brandId, customerId, "booking-1"),
() => createService(prisma).cancelForCustomer(brandId, customerId, "booking-1"),
(error: unknown) => error instanceof BadRequestException,
);
});
test("取消不存在或不属于当前客户的订单返回不存在", async () => {
await assert.rejects(
() => new BookingService(createPrisma()).cancelForCustomer(brandId, customerId, "missing"),
() => createService().cancelForCustomer(brandId, customerId, "missing"),
(error: unknown) => error instanceof NotFoundException,
);
});
@@ -91,15 +101,15 @@ test("订单状态只能按定义的状态机流转", async () => {
workflowKey: "booking.basic",
workflowVersion: "1.0.0",
}),
update: async ({ data }: any) => data,
update: async ({ data }: { data: { status: string } }) => data,
},
$transaction: async (callback: (tx: any) => unknown) =>
$transaction: async (callback: (tx: unknown) => unknown) =>
callback({
booking: { update: async ({ data }: any) => data },
booking: { update: async ({ data }: { data: { status: string } }) => data },
bookingStateTransition: { create: async () => undefined },
}),
});
const bookings = new BookingService(prisma);
const bookings = createService(prisma);
assert.equal(
(await bookings.updateStatus(brandId, "booking-1", "contacting")).status,
"contacting",
@@ -116,7 +126,7 @@ test("更新订单标签时拒绝其他品牌的标签", async () => {
tag: { findMany: async () => [] },
});
await assert.rejects(
() => new BookingService(prisma).updateTags(brandId, "booking-1", ["foreign-tag"]),
() => createService(prisma).updateTags(brandId, "booking-1", ["foreign-tag"]),
(error: unknown) => error instanceof BadRequestException,
);
});
+580 -35
View File
@@ -2,7 +2,8 @@ import assert from "node:assert/strict";
import { after, before, test } from "node:test";
import { PrismaClient } from "@prisma/client";
import { createApp } from "../dist/main.js";
import { signIdentity } from "../dist/auth.js";
import { readIdentity, signIdentity } from "../dist/auth.js";
import { WechatAuthService } from "../dist/wechat-auth.js";
let app;
const prisma = new PrismaClient();
@@ -20,11 +21,183 @@ before(async () => {
after(async () => {
await app.close();
await prisma.brandRelease.deleteMany({ where: { brandId } });
await prisma.booking.deleteMany({ where: { id: { in: createdBookingIds } } });
await prisma.customerUser.deleteMany({ where: { openid } });
await prisma.$disconnect();
});
test("admin release lifecycle is authorized, brand-scoped, and versioned", async () => {
const missing = await request("/admin/releases");
assert.equal(missing.statusCode, 401);
assert.equal((await request("/admin/releases/readiness")).statusCode, 401);
const customer = await request("/admin/releases", {
headers: { authorization: `Bearer ${customerToken}` },
});
assert.equal(customer.statusCode, 403);
assert.equal(
(
await request("/admin/releases/readiness", {
headers: { authorization: `Bearer ${customerToken}` },
})
).statusCode,
403,
);
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
assert.equal(login.statusCode, 201);
const adminToken = JSON.parse(login.body).token;
const readiness = await request("/admin/releases/readiness", {
headers: { authorization: `Bearer ${adminToken}` },
});
assert.equal(readiness.statusCode, 200);
assert.equal(JSON.parse(readiness.body).ready, true);
const enabledForms = await prisma.inquiryForm.findMany({
where: { brandId, isEnabled: true },
select: { id: true },
});
await prisma.inquiryForm.updateMany({ where: { brandId }, data: { isEnabled: false } });
try {
const noForms = await request("/admin/releases/readiness", {
headers: { authorization: `Bearer ${adminToken}` },
});
assert.equal(JSON.parse(noForms.body).ready, false);
assert.equal(
JSON.parse(noForms.body).checks.find((check) => check.key === "forms")?.passed,
false,
);
} finally {
await prisma.inquiryForm.updateMany({
where: { id: { in: enabledForms.map((form) => form.id) } },
data: { isEnabled: true },
});
}
const originalBrand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
await prisma.brandProfile.update({ where: { id: brandId }, data: { tagline: "" } });
const incomplete = await request("/admin/releases/readiness", {
headers: { authorization: `Bearer ${adminToken}` },
});
assert.equal(JSON.parse(incomplete.body).ready, false);
assert.equal(
(
await request("/admin/releases/publish", {
method: "POST",
headers: { authorization: `Bearer ${adminToken}` },
payload: {},
})
).statusCode,
400,
);
await prisma.brandProfile.update({
where: { id: brandId },
data: { tagline: "集成测试待发布标语" },
});
const beforePublish = JSON.parse((await request("/public/workspace")).body);
assert.equal(beforePublish.brand.tagline, originalBrand.tagline);
const published = await request("/admin/releases/publish", {
method: "POST",
headers: { authorization: `Bearer ${adminToken}` },
payload: { note: "集成测试发布" },
});
assert.equal(published.statusCode, 201);
const first = JSON.parse(published.body);
assert.equal(first.version, 2);
assert.equal(first.status, "published");
assert.equal(
JSON.parse((await request("/public/workspace")).body).brand.tagline,
"集成测试待发布标语",
);
const draftOnlyForm = await prisma.inquiryForm.create({
data: {
brandId,
name: "未发布的草稿表单",
fieldsSnapshot: [{ key: "phone", type: "phone", label: "手机", required: true }],
},
});
const draftSubmission = await request("/customer/inquiry-submissions", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: { formId: draftOnlyForm.id, values: { phone: "13871112222" } },
});
assert.equal(draftSubmission.statusCode, 400);
const listed = await request("/admin/releases", {
headers: { authorization: `Bearer ${adminToken}` },
});
assert.equal(listed.statusCode, 200);
assert.equal(JSON.parse(listed.body)[0].version, 2);
const concurrent = await Promise.all(
["并发发布 A", "并发发布 B"].map((note) =>
request("/admin/releases/publish", {
method: "POST",
headers: { authorization: `Bearer ${adminToken}` },
payload: { note },
}),
),
);
assert.deepEqual(
concurrent.map((item) => item.statusCode),
[201, 201],
);
assert.deepEqual(
concurrent.map((item) => JSON.parse(item.body).version).sort((a, b) => a - b),
[3, 4],
);
const rolledBack = await request("/admin/releases/1/rollback", {
method: "POST",
headers: { authorization: `Bearer ${adminToken}` },
});
assert.equal(rolledBack.statusCode, 201);
assert.equal(JSON.parse(rolledBack.body).version, 5);
assert.equal(
JSON.parse((await request("/public/workspace")).body).brand.tagline,
originalBrand.tagline,
);
const revoked = await request("/admin/releases/revoke", {
method: "POST",
headers: { authorization: `Bearer ${adminToken}` },
payload: {},
});
assert.equal(revoked.statusCode, 201);
assert.equal(JSON.parse(revoked.body).status, "revoked");
assert.equal(JSON.parse(revoked.body).revokedBy, readIdentity(adminToken).subject);
const unpublished = JSON.parse((await request("/public/workspace")).body);
assert.equal(unpublished.publication.status, "unpublished");
assert.equal(unpublished.brand, null);
assert.deepEqual(unpublished.offerings, []);
assert.deepEqual(JSON.parse((await request("/public/offerings")).body), []);
const revokedSubmission = await request("/customer/inquiry-submissions", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: { formId: draftOnlyForm.id, values: { phone: "13871112222" } },
});
assert.equal(revokedSubmission.statusCode, 400);
const revokedBooking = await request("/customer/bookings", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: {
requestType: "inquiry",
customerName: "集成测试客户",
wechatId: "integration-wechat",
contactPreference: "wechat",
},
});
assert.equal(revokedBooking.statusCode, 400);
await prisma.inquiryForm.delete({ where: { id: draftOnlyForm.id } });
await prisma.brandProfile.update({
where: { id: brandId },
data: { tagline: originalBrand.tagline },
});
assert.equal((await publishReleaseForTests("恢复集成测试基线")).statusCode, 201);
});
async function request(url, options = {}) {
return app
.getHttpAdapter()
@@ -32,6 +205,19 @@ async function request(url, options = {}) {
.inject({ method: "GET", url, ...options });
}
async function publishReleaseForTests(note = "集成测试发布") {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).token;
return request("/admin/releases/publish", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { note },
});
}
test("health and public content are available without authentication", async () => {
const health = await request("/health");
assert.equal(health.statusCode, 200);
@@ -68,6 +254,91 @@ test("health and public content are available without authentication", async ()
assert.equal(missingSlug.statusCode, 404);
});
test("visual template compatibility is enforced by catalog, preview, and brand switching", async () => {
const catalog = await request("/public/templates");
assert.equal(catalog.statusCode, 200);
const visuals = JSON.parse(catalog.body).visuals;
assert.deepEqual(
visuals.find((visual) => visual.key === "linjing-editorial").supportedIndustryTemplates,
["personal", "doors"],
);
const incompatiblePreview = await request(
"/public/templates/preview?industry=food&visual=linjing-editorial",
);
assert.equal(incompatiblePreview.statusCode, 400);
const compatiblePreview = await request(
"/public/templates/preview?industry=doors&visual=linjing-editorial",
);
assert.equal(compatiblePreview.statusCode, 200);
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).token;
const compatibleSwitch = await request("/admin/config/brand", {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { config: { visualTemplateKey: "acheng-campus-food" } },
});
assert.equal(compatibleSwitch.statusCode, 200);
});
test("seeded public workspaces keep personal, food, and doors brands isolated", async () => {
const expected = [
{
slug: "linran-brand",
id: "00000000-0000-0000-0000-000000000003",
templateKey: "personal",
founder: "林然",
offeringKind: "service",
categoryLabel: "策略咨询",
},
{
slug: "default-brand",
id: "00000000-0000-0000-0000-000000000001",
templateKey: "food",
founder: "阿成",
offeringKind: "package",
categoryLabel: "套餐",
},
{
slug: "linjing-doors",
id: "00000000-0000-0000-0000-000000000002",
templateKey: "doors",
founder: "林叙安 (Lin XUAN)",
offeringKind: "product",
categoryLabel: "入户大门",
},
];
const workspaces = await Promise.all(
expected.map(async (item) => {
const response = await request(`/public/workspace?brandSlug=${item.slug}`);
assert.equal(response.statusCode, 200);
const workspace = JSON.parse(response.body);
assert.equal(workspace.brand.id, item.id);
assert.equal(workspace.template.key, item.templateKey);
assert.ok(workspace.visualTemplate?.key);
assert.ok(workspace.visualTemplateManifest?.pages?.length > 0);
assert.equal(workspace.brand.founder, item.founder);
assert.ok(workspace.trustContent.length > 0);
assert.ok(workspace.trustPresentation);
assert.ok(workspace.inquiryForm);
assert.equal(workspace.inquiryForm.isEnabled, true);
assert.ok(workspace.offerings.length > 0);
assert.ok(workspace.offerings.every((offering) => offering.brandId === undefined));
assert.ok(
workspace.offerings.some(
(offering) =>
offering.kind === item.offeringKind &&
offering.presentation?.categoryLabel === item.categoryLabel,
),
);
return workspace;
}),
);
assert.equal(new Set(workspaces.map((workspace) => workspace.brand.id)).size, 3);
});
test("public workspace uses brand-scoped capability installations and preserves status", async () => {
await prisma.capabilityInstallation.deleteMany({ where: { brandId } });
const installation = await prisma.capabilityInstallation.create({
@@ -80,6 +351,8 @@ test("public workspace uses brand-scoped capability installations and preserves
},
});
try {
const published = await publishReleaseForTests();
assert.equal(published.statusCode, 201);
const response = await request("/public/workspace");
assert.equal(response.statusCode, 200);
const body = JSON.parse(response.body);
@@ -125,6 +398,135 @@ test("admin can update declared capability status with authorization and audit",
await prisma.capabilityAuditLog.deleteMany({ where: { brandId } });
});
test("editor membership can manage brand content but cannot change system settings", async () => {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).token;
const identity = readIdentity(token);
const membership = await prisma.brandMembership.findUnique({
where: { adminUserId_brandId: { adminUserId: identity.subject, brandId } },
});
assert.ok(membership);
await prisma.brandMembership.update({ where: { id: membership.id }, data: { role: "editor" } });
try {
const offerings = await request("/admin/workspace/offerings", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(offerings.statusCode, 200);
const capabilities = await request("/admin/workspace/capabilities", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(capabilities.statusCode, 403);
const visualHistory = await request("/admin/config/visual-template/history", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(visualHistory.statusCode, 403);
const visualUpdate = await request("/admin/config/brand", {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { config: { visualTemplateKey: "unknown-visual" } },
});
assert.equal(visualUpdate.statusCode, 403);
} finally {
await prisma.brandMembership.update({
where: { id: membership.id },
data: { role: membership.role },
});
}
});
test("owner can manage brand members without removing the final owner", async () => {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).token;
const identity = readIdentity(token);
const members = await request("/admin/brands/members", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(members.statusCode, 200);
const current = JSON.parse(members.body).find((item) => item.adminUserId === identity.subject);
assert.ok(current);
const selfDisable = await request(`/admin/brands/members/${current.id}`, {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { isEnabled: false },
});
assert.equal(selfDisable.statusCode, 400);
const created = await request("/admin/brands/members", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: {
username: `editor-${Date.now()}`,
displayName: "测试编辑",
password: "test-password-123",
role: "editor",
},
});
assert.equal(created.statusCode, 201);
const guestMembership = JSON.parse(created.body);
try {
const updated = await request(`/admin/brands/members/${guestMembership.id}`, {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { isEnabled: false },
});
assert.equal(updated.statusCode, 200);
assert.equal(JSON.parse(updated.body).isEnabled, false);
} finally {
await prisma.brandMembership.delete({ where: { id: guestMembership.id } });
await prisma.adminUser.delete({ where: { id: guestMembership.adminUser.id } });
}
});
test("manually created member must change the initial password before normal use", async () => {
const ownerLogin = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const ownerToken = JSON.parse(ownerLogin.body).token;
const username = `first-login-${Date.now()}`;
const created = await request("/admin/brands/members", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
username,
displayName: "首次登录测试",
password: "initial-password-123",
role: "editor",
},
});
assert.equal(created.statusCode, 201);
const member = JSON.parse(created.body);
assert.equal(member.adminUser.mustChangePassword, undefined);
try {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username, password: "initial-password-123" },
});
assert.equal(login.statusCode, 201);
assert.equal(JSON.parse(login.body).mustChangePassword, true);
const changed = await request("/admin/session/change-password", {
method: "POST",
headers: { authorization: `Bearer ${JSON.parse(login.body).token}` },
payload: { currentPassword: "initial-password-123", newPassword: "updated-password-123" },
});
assert.equal(changed.statusCode, 201);
const updatedLogin = await request("/admin/session/login", {
method: "POST",
payload: { username, password: "updated-password-123" },
});
assert.equal(updatedLogin.statusCode, 201);
assert.equal(JSON.parse(updatedLogin.body).mustChangePassword, false);
} finally {
await prisma.brandMembership.delete({ where: { id: member.id } });
await prisma.adminUser.delete({ where: { id: member.adminUser.id } });
}
});
test("admin can install optional quote capability without industry-specific branching", async () => {
const login = await request("/admin/session/login", {
method: "POST",
@@ -138,6 +540,7 @@ test("admin can install optional quote capability without industry-specific bran
});
assert.equal(response.statusCode, 200);
assert.equal(JSON.parse(response.body).capabilityKey, "quote-request");
assert.equal((await publishReleaseForTests()).statusCode, 201);
const workspace = await request("/public/workspace");
assert.ok(JSON.parse(workspace.body).plugins.some((plugin) => plugin.key === "quote-request"));
await prisma.capabilityInstallation.deleteMany({
@@ -204,16 +607,13 @@ test("admin can install doors industry template through the shared runtime contr
const workspace = await request("/public/workspace");
assert.equal(workspace.statusCode, 200);
const body = JSON.parse(workspace.body);
assert.equal(body.template.key, "doors");
assert.ok(body.modules.some((item) => item.type === "offering"));
assert.ok(body.modules.some((item) => item.type === "inquiry"));
assert.deepEqual(
body.runtimeCapabilities.map((item) => item.key),
["offerings", "inquiry"],
);
assert.ok(Array.isArray(body.offerings));
assert.ok(Array.isArray(body.fields));
assert.ok(body.fields.every((field) => typeof field.key === "string"));
assert.equal(body.template.key, "food");
assert.equal(body.publication.status, "published");
const samplePreview = await request("/admin/workspace/sample-content/preview", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(samplePreview.statusCode, 200);
assert.equal(JSON.parse(samplePreview.body).templateKey, "doors");
} finally {
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandModule.deleteMany({ where: { brandId } });
@@ -222,6 +622,8 @@ test("admin can install doors industry template through the shared runtime contr
});
test("admin can preview and import sample content idempotently", async () => {
const originalBrand = await prisma.brandProfile.findUnique({ where: { id: brandId } });
await prisma.brandProfile.update({ where: { id: brandId }, data: { templateKey: "doors" } });
await prisma.offering.deleteMany({
where: {
brandId,
@@ -262,6 +664,10 @@ test("admin can preview and import sample content idempotently", async () => {
});
await prisma.brandFieldDefinition.deleteMany({ where: { brandId, source: "sample" } });
await prisma.capabilityAuditLog.deleteMany({ where: { brandId, capabilityKey: "doors" } });
await prisma.brandProfile.update({
where: { id: brandId },
data: { templateKey: originalBrand?.templateKey ?? "food" },
});
});
test("admin can install a template and public workspace exposes enabled configuration", async () => {
@@ -284,7 +690,7 @@ test("admin can install a template and public workspace exposes enabled configur
});
assert.equal(installed.statusCode, 201);
assert.equal(JSON.parse(installed.body).template.key, "personal");
assert.equal(JSON.parse(installed.body).visualTemplate.key, "minimal-neutral");
assert.equal(JSON.parse(installed.body).visualTemplate.key, "linjing-editorial");
assert.equal(JSON.parse(installed.body).installation.configSnapshot.schemaVersion, "1.0");
try {
const previewUnauthorized = await request("/admin/workspace/template/preview");
@@ -324,19 +730,11 @@ test("admin can install a template and public workspace exposes enabled configur
assert.equal(publicWorkspace.statusCode, 200);
const workspaceBody = JSON.parse(publicWorkspace.body);
assert.equal(workspaceBody.contractVersion, "1.0");
assert.equal(workspaceBody.template.key, "personal");
assert.deepEqual(workspaceBody.capabilities, [
{ key: "offerings", version: "1.0.0", status: "enabled", config: {} },
{ key: "inquiry", version: "1.0.0", status: "enabled", config: {} },
]);
assert.deepEqual(workspaceBody.runtimeCapabilities, [
{ key: "offerings", version: "1.0.0", status: "enabled", config: {} },
{ key: "inquiry", version: "1.0.0", status: "enabled", config: {} },
]);
assert.equal(workspaceBody.modules.length, 5);
assert.equal(workspaceBody.runtimeModules.length, 5);
assert.equal(workspaceBody.template.key, "food");
assert.ok(workspaceBody.modules.length > 0);
assert.equal(workspaceBody.modules.length, workspaceBody.runtimeModules.length);
assert.equal(workspaceBody.runtimeModules[0].schemaVersion, "1.0");
assert.equal(workspaceBody.inquiryForm, null);
assert.ok(workspaceBody.inquiryForm);
const conflict = await request("/admin/workspace/install", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
@@ -424,18 +822,18 @@ test("admin visual template selection is reflected in public runtime workspace",
const updated = await request("/admin/config/brand", {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { config: { visualTemplateKey: "minimal-neutral" } },
payload: { config: { visualTemplateKey: "acheng-campus-food" } },
});
assert.equal(updated.statusCode, 200);
try {
const runtime = await request("/public/workspace");
assert.equal(runtime.statusCode, 200);
const body = JSON.parse(runtime.body);
assert.equal(body.visualTemplate.key, "minimal-neutral");
assert.equal(body.visualTemplate.key, "acheng-campus-food");
assert.equal(body.visualTemplate.version, "1.0.0");
assert.equal(body.theme.colors.accent, "#4B5563");
assert.equal(body.visualTemplate.variants.hero, "minimal");
assert.equal(body.visualTemplateManifest.key, "minimal-neutral");
assert.equal(body.theme.colors.accent, "#E87532");
assert.equal(body.visualTemplate.variants.hero, "stall-board");
assert.equal(body.visualTemplateManifest.key, "acheng-campus-food");
assert.equal(body.visualTemplateManifest.brandFirst, true);
assert.deepEqual(
body.visualTemplateManifest.pages.map((page) => page.key),
@@ -450,6 +848,50 @@ test("admin visual template selection is reflected in public runtime workspace",
}
});
test("public workspace exposes declared brand and trust presentation data", async () => {
const doorsBrand = await prisma.brandProfile.findUnique({ where: { slug: "linjing-doors" } });
assert.ok(doorsBrand);
const original = doorsBrand;
await prisma.brandProfile.update({
where: { id: doorsBrand.id },
data: {
config: {
...(original?.config && typeof original.config === "object" ? original.config : {}),
homeHero: { title: "尚未发布的集成测试首页标题" },
},
},
});
try {
const runtime = await request("/public/workspace?brandSlug=linjing-doors");
assert.equal(runtime.statusCode, 200);
const body = JSON.parse(runtime.body);
assert.equal(body.brand.founder, "林叙安 (Lin XUAN)");
assert.equal(body.brand.title, "高端门系统建筑研造主理人");
assert.notEqual(body.brand.homeHero.title, "尚未发布的集成测试首页标题");
assert.equal(body.trustPresentation.stats.length, 4);
assert.equal(body.trustPresentation.pillars.length, 3);
assert.equal(body.trustPresentation.serviceFlow.length, 6);
assert.equal(body.brand.profilePresentation.coverage.length, 2);
assert.equal(body.brand.profilePresentation.warranty.length, 4);
assert.equal(body.brand.visualPresentation.home.proofTitle, "14 年,只做门与空间的关系");
assert.equal(body.brand.visualPresentation.inquiry.submitLabel, "提交量房与定制评估需求");
assert.equal(body.brand.visualPresentation.records.emptyAction, "开始咨询");
assert.equal(body.offerings.length, 4);
assert.ok(body.offerings.every((offering) => offering.presentation.heroImage));
assert.ok(
body.offerings.every((offering) => offering.presentation.details.materialsList.length),
);
const doorType = body.inquiryForms[0].fields.find((field) => field.key === "doorType");
assert.equal(doorType.options.length, 5);
assert.equal(doorType.options[0].value, "入户大门(防暴铸铜 / 实木)");
} finally {
await prisma.brandProfile.update({
where: { id: doorsBrand.id },
data: { config: original?.config ?? {} },
});
}
});
test("admin can create and version an inquiry form", async () => {
const login = await request("/admin/session/login", {
method: "POST",
@@ -537,6 +979,7 @@ test("admin can create and version an inquiry form", async () => {
});
assert.equal(blockedCapability.statusCode, 400);
await prisma.capabilityInstallation.delete({ where: { id: capability.id } });
assert.equal((await publishReleaseForTests()).statusCode, 201);
const publicForm = await request(`/public/inquiry-forms/${id}`);
assert.equal(publicForm.statusCode, 200);
const publicOffering = await request(`/public/offerings/${offering.id}`);
@@ -554,6 +997,13 @@ test("admin can create and version an inquiry form", async () => {
(form) => form.key === id,
);
assert.deepEqual(runtimeForm.fields[1].options, [{ label: "微信", value: "wechat" }]);
await prisma.inquiryForm.update({
where: { id },
data: {
version: 3,
fieldsSnapshot: [{ key: "draft_only", type: "text", label: "草稿字段", required: true }],
},
});
const submission = await request("/customer/inquiry-submissions", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
@@ -561,6 +1011,7 @@ test("admin can create and version an inquiry form", async () => {
});
assert.equal(submission.statusCode, 201);
assert.equal(JSON.parse(submission.body).formVersion, 2);
assert.equal(JSON.parse(submission.body).fieldsSnapshot[0].key, "budget");
assert.equal(JSON.parse(submission.body).offeringId, offering.id);
assert.deepEqual(JSON.parse(submission.body).values, { budget: 1000 });
assert.equal((await request("/customer/inquiry-submissions")).statusCode, 401);
@@ -687,10 +1138,10 @@ test("admin can manage offerings and public endpoint hides disabled offerings",
assert.equal(listed.statusCode, 200);
assert.ok(JSON.parse(listed.body).some((item) => item.id === id));
const publicItem = await request(`/public/offerings/${id}`);
assert.equal(publicItem.statusCode, 200);
assert.equal(publicItem.statusCode, 400);
const publicList = await request("/public/offerings");
assert.equal(publicList.statusCode, 200);
assert.ok(JSON.parse(publicList.body).some((item) => item.id === id));
assert.ok(!JSON.parse(publicList.body).some((item) => item.id === id));
const updated = await request(`/admin/workspace/offerings/${id}`, {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
@@ -705,7 +1156,7 @@ test("admin can manage offerings and public endpoint hides disabled offerings",
payload: { isEnabled: true },
});
assert.equal(reenabled.statusCode, 200);
assert.equal((await request(`/public/offerings/${id}`)).statusCode, 200);
assert.equal((await request(`/public/offerings/${id}`)).statusCode, 400);
} finally {
const deleted = await request(`/admin/workspace/offerings/${id}`, {
method: "DELETE",
@@ -936,7 +1387,7 @@ test("admin can read and update brand and service configuration", async () => {
const projectedService = JSON.parse(publicServices.body).find(
(item) => item.id === serviceBefore.id,
);
assert.equal(projectedService.priceText, "集成测试价格");
assert.equal(projectedService.priceText, serviceBefore.priceText);
const listedServices = await request("/admin/workspace/offerings", {
headers: { authorization: `Bearer ${adminToken}` },
@@ -981,6 +1432,57 @@ test("admin can read and update brand and service configuration", async () => {
}
});
test("admin can update user-facing brand presentation without replacing other config", async () => {
assert.equal(
(await request("/admin/config/presentation", { method: "PATCH", payload: { home: {} } }))
.statusCode,
401,
);
assert.equal(
(
await request("/admin/config/presentation", {
method: "PATCH",
headers: { authorization: `Bearer ${customerToken}` },
payload: { home: {} },
})
).statusCode,
403,
);
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).token;
const brand = await prisma.brandProfile.findUnique({ where: { id: brandId } });
assert.ok(brand);
const originalConfig = brand.config;
try {
const response = await request("/admin/config/presentation", {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: {
identity: { founder: "可编辑主理人", title: "品牌主理人", ignoredNumber: 123 },
home: { proofTitle: "用户可编辑的信任标题", ignoredNumber: 123 },
inquiry: { submitLabel: "开始沟通" },
},
});
assert.equal(response.statusCode, 200);
const presentation = JSON.parse(response.body).visualPresentation;
assert.equal(presentation.home.proofTitle, "用户可编辑的信任标题");
assert.equal(presentation.home.ignoredNumber, undefined);
assert.equal(presentation.inquiry.submitLabel, "开始沟通");
const runtime = await request("/public/workspace");
assert.notEqual(JSON.parse(runtime.body).brand.founder, "可编辑主理人");
assert.notEqual(JSON.parse(runtime.body).brand.title, "品牌主理人");
assert.notEqual(
JSON.parse(runtime.body).brand.visualPresentation.home.proofTitle,
"用户可编辑的信任标题",
);
} finally {
await prisma.brandProfile.update({ where: { id: brandId }, data: { config: originalConfig } });
}
});
test("admin can manage trust content", async () => {
const login = await request("/admin/session/login", {
method: "POST",
@@ -1004,7 +1506,7 @@ test("admin can manage trust content", async () => {
const publicContent = await request("/public/trust-content");
assert.equal(publicContent.statusCode, 200);
const publicItems = JSON.parse(publicContent.body);
assert.ok(publicItems.some((item) => item.id === id));
assert.ok(!publicItems.some((item) => item.id === id));
assert.ok(!publicItems.some((item) => item.id === JSON.parse(draft.body).id));
try {
const list = await request("/admin/config/trust-content", {
@@ -1047,6 +1549,33 @@ test("wechat login validates the request DTO before exchanging the code", async
assert.equal(response.statusCode, 400);
});
test("wechat login creates a customer session for the requested brand", async () => {
const doorsBrand = await prisma.brandProfile.findUnique({ where: { slug: "linjing-doors" } });
assert.ok(doorsBrand);
const sessionOpenid = `doors-login-${Date.now()}`;
const wechatAuth = app.get(WechatAuthService);
const originalExchangeCode = wechatAuth.exchangeCode;
wechatAuth.exchangeCode = async () => ({ openid: sessionOpenid });
try {
const response = await request("/customer/session/wechat?brandSlug=linjing-doors", {
method: "POST",
payload: { code: "test-code" },
});
assert.equal(response.statusCode, 201);
const identity = readIdentity(JSON.parse(response.body).token);
assert.equal(identity.brandId, doorsBrand.id);
assert.equal(identity.role, "customer");
assert.ok(
await prisma.customerUser.findUnique({
where: { brandId_openid: { brandId: doorsBrand.id, openid: sessionOpenid } },
}),
);
} finally {
wechatAuth.exchangeCode = originalExchangeCode;
await prisma.customerUser.deleteMany({ where: { openid: sessionOpenid } });
}
});
test("customer booking DTO rejects incomplete package requests", async () => {
const response = await request("/customer/bookings", {
method: "POST",
@@ -1087,6 +1616,16 @@ test("customer can create and cancel a package booking", async () => {
where: { brandId, isEnabled: true, priceAmount: { not: null } },
});
assert.ok(service);
const release = await prisma.brandRelease.findFirst({
where: { brandId, status: "published" },
orderBy: { version: "desc" },
});
const publishedOffering = release?.snapshot?.offerings?.find?.((item) => item.id === service.id);
assert.ok(publishedOffering);
await prisma.offering.update({
where: { id: service.id },
data: { priceAmount: service.priceAmount + 500, name: `${service.name}草稿` },
});
const created = await request("/customer/bookings", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
@@ -1098,14 +1637,20 @@ test("customer can create and cancel a package booking", async () => {
items: [{ offeringId: service.id, quantity: 2 }],
},
});
await prisma.offering.update({
where: { id: service.id },
data: { priceAmount: service.priceAmount, name: service.name },
});
assert.equal(created.statusCode, 201);
const createdBody = JSON.parse(created.body);
assert.equal(createdBody.estimatedAmount, service.priceAmount * 2);
assert.equal(createdBody.estimatedAmount, publishedOffering.priceAmount * 2);
const booking = await prisma.booking.findUnique({ where: { bookingNo: createdBody.bookingNo } });
assert.ok(booking);
assert.equal(booking.workflowKey, "booking.basic");
assert.equal(booking.currentState, "received");
assert.equal(booking.offeringId, service.id);
const bookingItem = await prisma.bookingItem.findFirst({ where: { bookingId: booking.id } });
assert.equal(bookingItem?.serviceNameSnapshot, publishedOffering.name);
const initialTransitions = await prisma.bookingStateTransition.findMany({
where: { bookingId: booking.id },
});
+40
View File
@@ -0,0 +1,40 @@
const { randomBytes } = require("node:crypto");
const { spawnSync } = require("node:child_process");
const { PrismaClient } = require("@prisma/client");
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) throw new Error("DATABASE_URL is required for integration tests");
const schema = `pb_test_${randomBytes(8).toString("hex")}`;
const testUrl = new URL(databaseUrl);
testUrl.searchParams.set("schema", schema);
const testEnvironment = { ...process.env, DATABASE_URL: testUrl.toString(), NODE_ENV: "test" };
const administrator = new PrismaClient();
function run(command, args) {
const result = spawnSync(command, args, { stdio: "inherit", env: testEnvironment });
if (result.error) throw result.error;
return result.status ?? 1;
}
async function main() {
let created = false;
let status = 1;
try {
await administrator.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
created = true;
if (run("pnpm", ["exec", "prisma", "migrate", "deploy"]) !== 0) return status;
if (run("pnpm", ["db:seed"]) !== 0) return status;
status = run(process.execPath, ["--test", "test/http.integration.test.js"]);
return status;
} finally {
if (created) await administrator.$executeRawUnsafe(`DROP SCHEMA "${schema}" CASCADE`);
await administrator.$disconnect();
process.exitCode = status;
}
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});