feat: 收敛行业模板身份为品牌单一真相

- BrandProfile.templateKey 为唯一真相,安装记录降级为同模板的版本台账
- 安装只允许补建当前模板台账,跨行业模板请求返回 400,杜绝身份漂移
- preview 不再强制要求台账存在,台账缺失时以模板目录版本为准
- seed 按品牌身份补齐模板台账,消除「身份有、台账无」
- 记录 ADR 0026
This commit is contained in:
que01 committed 2026-10-14 13:55:54 +08:00
1 parent 896f3240f9
commit 6073e72940
4 files changed
+298 -40

No files matched your search

+49 -1
View File
@@ -1,5 +1,10 @@
import { PrismaClient, type Prisma } from "@prisma/client";
import { getTemplatePackageManifestForVisualKey } from "@personal-brand/config";
import {
getBrandTemplate,
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
getVisualTemplateManifest,
} from "@personal-brand/config";
import bcrypt from "bcryptjs";
import { buildBrandReleaseSnapshot } from "../src/brand-release.service.js";
@@ -768,6 +773,47 @@ async function ensureSeedRelease(brandId: string, actorId: string): Promise<void
});
}
/**
* 行业的模板台账只能有一个,且必须与品牌身份(BrandProfile.templateKey)一致。
* seed 之前只写品牌身份、不建台账,导致后台「尚未安装模板」而公开运行时已在跑该模板;
* 这里按品牌身份补齐台账,让「版本与升级」「回滚」有据可依。
*/
async function ensureTemplateInstallation(brandId: string): Promise<void> {
const brand = await prisma.brandProfile.findUniqueOrThrow({
where: { id: brandId },
select: { templateKey: true, config: true },
});
const template = getBrandTemplate(brand.templateKey);
if (!template) throw new Error("Development brand has an unknown industry template");
const config =
brand.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const configuredVisual =
typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : undefined;
const visualKey = configuredVisual ?? getDefaultVisualTemplateKey(template.key);
if (!getVisualTemplateManifest(visualKey))
throw new Error("Development brand has an unknown visual template");
const configSnapshot = {
schemaVersion: "1.0",
version: template.version,
industryTemplate: template,
visualTemplate: getVisualTemplateManifest(visualKey),
capabilities: template.capabilities,
} as unknown as Prisma.InputJsonValue;
const existing = await prisma.brandTemplateInstallation.findFirst({ where: { brandId } });
if (existing) {
await prisma.brandTemplateInstallation.update({
where: { id: existing.id },
data: { templateKey: template.key, templateVersion: template.version, configSnapshot },
});
return;
}
await prisma.brandTemplateInstallation.create({
data: { brandId, templateKey: template.key, templateVersion: template.version, configSnapshot },
});
}
async function main(): Promise<void> {
const brand = await prisma.brandProfile.upsert({
where: { id: "00000000-0000-0000-0000-000000000001" },
@@ -795,6 +841,7 @@ async function main(): Promise<void> {
});
await ensureRuntimeContent(brand.id, runtimeSeedTemplates.food);
await ensureTemplateInstallation(brand.id);
for (const name of ["普通套餐", "私厨", "配送", "自取", "熟客", "重点跟进"]) {
await prisma.tag.upsert({
@@ -851,6 +898,7 @@ async function main(): Promise<void> {
create: { adminUserId: admin.id, brandId: doorsBrand.id, role: "owner" },
});
await ensureRuntimeContent(doorsBrand.id, runtimeSeedTemplates.doors);
await ensureTemplateInstallation(doorsBrand.id);
await ensureSeedRelease(brand.id, admin.id);
await ensureSeedRelease(doorsBrand.id, admin.id);
}
+48 -26
View File
@@ -62,34 +62,47 @@ export class TemplateWorkspaceService {
});
}
async getEffectiveTemplateKey(brandId: string): Promise<BrandTemplateKey> {
const [installation, brand] = await Promise.all([
const [brand, installation] = await Promise.all([
this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true },
}),
this.prisma.brandTemplateInstallation.findFirst({
where: { brandId },
orderBy: { updatedAt: "desc" },
select: { templateKey: true },
}),
this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true },
}),
]);
const key =
getBrandTemplate(installation?.templateKey ?? brand?.templateKey ?? defaultBrandTemplateKey)
?.key ?? defaultBrandTemplateKey;
return key;
// BrandProfile.templateKey 是「品牌使用哪个行业模板」的唯一真相;
// 安装记录只是同一模板的版本台账,缺失时不能反过来改写品牌身份。
for (const candidate of [brand?.templateKey, installation?.templateKey]) {
const template = candidate ? getBrandTemplate(candidate) : undefined;
if (template) return template.key;
}
return defaultBrandTemplateKey;
}
async install(brandId: string, templateKey: BrandTemplateKey) {
const template = getBrandTemplate(templateKey);
if (!template) throw new BadRequestException("行业模板不存在");
const [existing, brand] = await Promise.all([
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { config: true, templateKey: true },
}),
]);
if (existing)
throw new BadRequestException(
existing.templateKey === templateKey
? "该模板已经安装"
: "品牌已经安装主模板,请先完成模板切换流程",
: "品牌已经安装主模板,更换行业模板不在本版本范围内",
);
// 一个品牌只使用一个行业模板(BrandProfile.templateKey 即身份)。安装只允许补建当前模板的版本台账,
// 不得换成别的行业模板,否则会出现「身份是 A、台账是 B」的漂移,并把发布快照接到不适配的视觉模板上。
const currentTemplate = brand?.templateKey ? getBrandTemplate(brand.templateKey) : undefined;
if (currentTemplate && currentTemplate.key !== templateKey)
throw new BadRequestException(
`当前品牌已在使用「${currentTemplate.name}」行业模板,更换行业模板不在本版本范围内`,
);
const brandConfig =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
@@ -119,14 +132,17 @@ 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 },
},
});
}
// 安装记录与品牌身份必须同时落库,否则会出现「品牌在跑 A 模板、台账记的是 B」的漂移。
// 已经自定义过视觉模板的品牌,补建台账时保留原选择,只把行业模板身份写回。
const nextConfig = (
brandConfig.visualTemplateKey === undefined
? { ...brandConfig, visualTemplateKey }
: brandConfig
) as Prisma.InputJsonValue;
await tx.brandProfile.update({
where: { id: brandId },
data: { templateKey, config: nextConfig },
});
const installation = await tx.brandTemplateInstallation.create({
data: {
brandId,
@@ -156,16 +172,22 @@ export class TemplateWorkspaceService {
return item;
}
async preview(brandId: string) {
const installation = await this.installation(brandId);
const template = getBrandTemplate(installation.templateKey);
if (!template) throw new BadRequestException("已安装模板不存在");
const fields = await this.prisma.brandFieldDefinition.findMany({ where: { brandId } });
const templateKey = await this.getEffectiveTemplateKey(brandId);
const template = getBrandTemplate(templateKey);
if (!template) throw new BadRequestException("当前行业模板不存在");
const [installation, fields] = await Promise.all([
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
this.prisma.brandFieldDefinition.findMany({ where: { brandId } }),
]);
// 品牌一直有行业模板,但版本台账可能还没建立;此时以模板目录的版本为准,不报错。
const currentVersion = installation?.templateVersion ?? template.version;
return {
currentVersion: installation.templateVersion,
templateKey,
currentVersion,
latestVersion: template.version,
canUpgrade: installation.templateVersion !== template.version,
canUpgrade: currentVersion !== template.version,
canRollback:
Array.isArray(installation.previousSnapshots) && installation.previousSnapshots.length > 0,
Array.isArray(installation?.previousSnapshots) && installation.previousSnapshots.length > 0,
missingFields: template.fields.filter(
(item) =>
!fields.some((current) => current.scope === item.scope && current.key === item.key),
+157 -13
View File
@@ -1092,6 +1092,11 @@ test("admin release lifecycle is authorized, brand-scoped, and versioned", async
assert.equal((await publishReleaseForTests("恢复集成测试基线")).statusCode, 201);
});
function errorMessage(body) {
const parsed = JSON.parse(body);
return parsed?.error?.message ?? parsed?.message ?? "";
}
async function request(url, options = {}) {
return app
.getHttpAdapter()
@@ -1182,6 +1187,114 @@ test("visual template compatibility is enforced by catalog, preview, and brand s
assert.equal(compatibleSwitch.statusCode, 200);
});
test("industry template state has a single source of truth", async () => {
const brand = await prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true, config: true },
});
assert.ok(brand);
const templateKey = brand.templateKey;
const visualTemplateKey = brand.config?.visualTemplateKey;
const installationBefore = await prisma.brandTemplateInstallation.findFirst({
where: { brandId },
});
const fieldsBefore = await prisma.brandFieldDefinition.findMany({ where: { brandId } });
const unauthorized = await request("/admin/workspace/template/preview");
assert.equal(unauthorized.statusCode, 401);
const forbidden = await request("/admin/workspace/template/preview", {
headers: { authorization: `Bearer ${customerToken}` },
});
assert.equal(forbidden.statusCode, 403);
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const headers = {
authorization: `Bearer ${JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token}`,
};
try {
// 品牌身份来自 BrandProfile.templateKey;即使版本台账缺失,预览也必须可用而不是 400。
const preview = await request("/admin/workspace/template/preview", { headers });
assert.equal(preview.statusCode, 200);
const previewBody = JSON.parse(preview.body);
assert.equal(previewBody.templateKey, templateKey);
assert.equal(previewBody.currentVersion, previewBody.latestVersion);
assert.equal(previewBody.canUpgrade, false);
assert.equal(previewBody.canRollback, Boolean(installationBefore?.previousSnapshots?.length));
const otherKey = templateKey === "personal" ? "food" : "personal";
// 安装其他行业模板必须被拒绝,且不能改写品牌身份或视觉模板。
const rejected = await request("/admin/workspace/install", {
method: "POST",
headers,
payload: { templateKey: otherKey },
});
assert.equal(rejected.statusCode, 400);
assert.match(errorMessage(rejected.body), /更换行业模板不在本版本范围内/);
const afterRejected = await prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true, config: true },
});
assert.equal(afterRejected.templateKey, templateKey);
assert.equal(afterRejected.config?.visualTemplateKey, visualTemplateKey);
// 台账已存在时重复安装当前模板应被拒绝。
if (installationBefore) {
const repeated = await request("/admin/workspace/install", {
method: "POST",
headers,
payload: { templateKey },
});
assert.equal(repeated.statusCode, 400);
assert.match(errorMessage(repeated.body), /已经安装/);
// 缺失的版本台账可以由安装补齐,且不改动品牌身份与视觉模板。
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
const repaired = await request("/admin/workspace/install", {
method: "POST",
headers,
payload: { templateKey },
});
assert.equal(repaired.statusCode, 201, repaired.body);
const installationAfter = await prisma.brandTemplateInstallation.findFirst({
where: { brandId },
});
assert.equal(installationAfter.templateKey, templateKey);
const afterRepair = await prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true, config: true },
});
assert.equal(afterRepair.templateKey, templateKey);
assert.equal(afterRepair.config?.visualTemplateKey, visualTemplateKey);
}
} finally {
const createdFieldIds = (await prisma.brandFieldDefinition.findMany({ where: { brandId } }))
.filter((item) => !fieldsBefore.some((current) => current.id === item.id))
.map((item) => item.id);
if (createdFieldIds.length)
await prisma.brandFieldDefinition.deleteMany({ where: { id: { in: createdFieldIds } } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
if (installationBefore) {
await prisma.brandTemplateInstallation.create({
data: {
brandId,
templateKey: installationBefore.templateKey,
templateVersion: installationBefore.templateVersion,
configSnapshot: installationBefore.configSnapshot,
},
});
}
await prisma.brandProfile.update({
where: { id: brandId },
data: { templateKey, config: brand.config },
});
}
});
test("seeded public workspaces keep personal, food, and doors brands isolated", async () => {
const expected = [
{
@@ -1536,7 +1649,8 @@ test("admin capability list includes template defaults and brand overrides", asy
await prisma.capabilityInstallation.deleteMany({ where: { brandId } });
});
test("admin can install doors industry template through the shared runtime contract", async () => {
test("installing another industry template is rejected without drifting brand identity", async () => {
const originalBrand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
await prisma.inquirySubmission.deleteMany({ where: { brandId } });
await prisma.inquiryForm.deleteMany({ where: { brandId } });
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
@@ -1546,27 +1660,40 @@ test("admin can install doors industry template through the shared runtime contr
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const headers = { authorization: `Bearer ${token}` };
try {
// 品牌身份是 food;装 doors 属于「更换行业模板」,不在本版本范围内。
const installed = await request("/admin/workspace/install", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
headers,
payload: { templateKey: "doors" },
});
assert.equal(installed.statusCode, 201);
assert.equal(JSON.parse(installed.body).template.key, "doors");
assert.equal(installed.statusCode, 400, installed.body);
assert.match(errorMessage(installed.body), /更换行业模板不在本版本范围内/);
// 拒绝之后不能留下任何漂移:品牌身份、视觉模板、台账都不变。
const brandAfter = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
assert.equal(brandAfter.templateKey, originalBrand.templateKey);
assert.deepEqual(brandAfter.config, originalBrand.config);
assert.equal(await prisma.brandTemplateInstallation.count({ where: { brandId } }), 0);
// 公开运行时仍按品牌身份走 food 模板,没有被 doors 污染。
const workspace = await request("/public/workspace");
assert.equal(workspace.statusCode, 200);
const body = JSON.parse(workspace.body);
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}` },
});
const samplePreview = await request("/admin/workspace/sample-content/preview", { headers });
assert.equal(samplePreview.statusCode, 200);
assert.equal(JSON.parse(samplePreview.body).templateKey, "doors");
assert.equal(JSON.parse(samplePreview.body).templateKey, originalBrand.templateKey);
} finally {
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
await prisma.brandProfile.update({
where: { id: brandId },
data: { templateKey: originalBrand.templateKey, config: originalBrand.config },
});
}
});
@@ -1671,7 +1798,7 @@ test("admin can preview and import sample content idempotently", async () => {
});
});
test("admin can install a template and public workspace exposes enabled configuration", async () => {
test("template ledger install, upgrade preview, and rollback stay brand-scoped", async () => {
await prisma.inquirySubmission.deleteMany({ where: { brandId } });
await prisma.inquiryForm.deleteMany({ where: { brandId } });
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
@@ -1687,14 +1814,31 @@ test("admin can install a template and public workspace exposes enabled configur
headers: { authorization: `Bearer ${customerToken}` },
});
assert.equal(customerAccess.statusCode, 403);
const currentTemplateKey = (
await prisma.brandProfile.findUniqueOrThrow({
where: { id: brandId },
select: { templateKey: true },
})
).templateKey;
const crossTemplate = await request("/admin/workspace/install", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { templateKey: currentTemplateKey === "personal" ? "food" : "personal" },
});
assert.equal(crossTemplate.statusCode, 400, crossTemplate.body);
const installed = await request("/admin/workspace/install", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { templateKey: "personal" },
payload: { templateKey: currentTemplateKey },
});
assert.equal(installed.statusCode, 201);
assert.equal(JSON.parse(installed.body).template.key, "personal");
assert.equal(JSON.parse(installed.body).visualTemplate.key, "linjing-editorial");
assert.equal(installed.statusCode, 201, installed.body);
assert.equal(JSON.parse(installed.body).template.key, currentTemplateKey);
assert.equal(
JSON.parse(installed.body).visualTemplate.supportedIndustryTemplates.includes(
currentTemplateKey,
),
true,
);
assert.equal(JSON.parse(installed.body).installation.configSnapshot.schemaVersion, "1.0");
try {
const previewUnauthorized = await request("/admin/workspace/template/preview");
@@ -0,0 +1,44 @@
# 0026 品牌单一行业模板与后台页面职责拆分
- 状态:已采纳
- 日期:2026-10-14
## 背景
后台的「模板与表单设置」页面把两类目标完全不同的事情放在了一起:日常经营(咨询入口表单、高级自定义字段)与半技术的模板治理(行业模板安装、模板版本升级/回滚、视觉模板切换、模板组合预览)。结果是运营者看到的页面既像内容配置页,又像技术设置页。
同时发现一个身份漂移问题:品牌的行业模板身份写在 `BrandProfile.templateKey`,但模板版本台账写在 `BrandTemplateInstallation`。旧实现里「品牌是否已使用某行业模板」以安装记录为准,`seed` 只写身份、不建台账,`install` 又允许换到另一个行业模板。于是可能出现「品牌在跑 A 模板、台账记的是 B」,并把发布快照接到不适配的视觉模板上。
## 决策
### 1. `BrandProfile.templateKey` 是唯一真相,一个品牌只使用一个行业模板
- `getEffectiveTemplateKey` 优先读 `BrandProfile.templateKey`,`BrandTemplateInstallation` 降级为同一模板的版本台账,缺失时不再反过来改写品牌身份。
- `install` 只允许为当前模板补建/修复台账;请求的行业模板与品牌身份不一致时返回 400,并说明「更换行业模板不在本版本范围内」。
- 安装写入时同时落 `templateKey` 与台账,保证身份与台账一致;已自定义视觉模板的品牌在补建台账时保留原视觉选择。
- `preview` 不再要求台账存在:台账缺失时以模板目录版本为当前版本,不报错。
### 2. 后台页面按「日常经营」与「模板治理」拆开
- `咨询表单与字段`(`/admin/workspace`)只负责咨询入口表单与高级自定义字段,归入「日常经营」,不再承载任何模板、视觉或组合预览。
- 模板治理归入「配置与发布 → 内容发布」的「选择表达方式」:行业模板只读展示、视觉模板选择、模板版本升级与回滚。视觉模板是行业模板的排版变体,不是新的行业身份。
## 替代方案
- 保留单一页面并把模板部分折叠收起:仍会让运营者看到技术设置,职责没有真正分开。
- 增加第二条「模板切换」流程支持换行业:属于产品范围扩张,且与「模板是可替换的行业表达、品牌身份跨行业稳定」的既有边界冲突。
- 只在 `seed` 里补齐台账而不加后端守卫:换行业模板仍会漂移,属于治标不治本。
## 后果
- 品牌身份、模板台账、发布快照三者不会再互相漂移;公开运行时始终跑品牌当前的行业模板。
- 行业模板不可在后台切换,切换到另一行业需要显式的产品与迁移方案。
- 视觉模板切换历史/回滚、模板组合预览从 UI 中移除。当前每个行业实际只适配一个视觉模板,这两块属于不可达的死 UI。
- 后台的模板治理不再是 owner 专属的高深设置,而是和发布放在同一处。
## 迁移计划
- 后端:`TemplateWorkspaceService` 守卫与 `preview` 调整;`seed` 新增 `ensureTemplateInstallation` 按品牌身份补齐台账。
- 前端:`WorkspacePage` 收敛为咨询表单与字段;`PublicationPage` 承接模板版本升级/回滚;`CapabilitiesPage`、`main.tsx` 导航与路由同步。
- 文档:更新 `apps/admin/design.md` 页面结构表。
- 验收:`pnpm check`,API 集成测试覆盖「台账缺失仍可预览」「跨行业安装被拒且身份不漂移」「删台账后同行业安装可修复」,并用真实渲染复核后台页面。