feat: 完成模板管理阶段4闭环

This commit is contained in:
que01 committed 2026-10-17 13:56:19 +08:00
1 parent b1e8012ded
commit d1958a7d7f
26 files changed
+1179 -310

No files matched your search

@@ -0,0 +1,43 @@
-- AlterTable
ALTER TABLE "BrandTemplateInstallation" ADD COLUMN "contentChecksum" TEXT,
ADD COLUMN "templatePackageVersionId" TEXT,
ADD COLUMN "visualTemplateKey" TEXT;
-- CreateTable
CREATE TABLE "TemplateBootstrapImport" (
"id" TEXT NOT NULL,
"brandId" TEXT NOT NULL,
"templatePackageVersionId" TEXT NOT NULL,
"packageKey" TEXT NOT NULL,
"packageVersion" TEXT NOT NULL,
"contentChecksum" TEXT NOT NULL,
"actorId" TEXT NOT NULL,
"strategy" TEXT NOT NULL DEFAULT 'missing_only',
"status" TEXT NOT NULL,
"result" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "TemplateBootstrapImport_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "BrandTemplateInstallation_templatePackageVersionId_idx" ON "BrandTemplateInstallation"("templatePackageVersionId");
-- CreateIndex
CREATE INDEX "TemplateBootstrapImport_brandId_createdAt_idx" ON "TemplateBootstrapImport"("brandId", "createdAt");
-- CreateIndex
CREATE INDEX "TemplateBootstrapImport_templatePackageVersionId_createdAt_idx" ON "TemplateBootstrapImport"("templatePackageVersionId", "createdAt");
-- CreateIndex
CREATE INDEX "TemplateBootstrapImport_actorId_createdAt_idx" ON "TemplateBootstrapImport"("actorId", "createdAt");
-- AddForeignKey
ALTER TABLE "BrandTemplateInstallation" ADD CONSTRAINT "BrandTemplateInstallation_templatePackageVersionId_fkey" FOREIGN KEY ("templatePackageVersionId") REFERENCES "TemplatePackageVersion"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "TemplateBootstrapImport" ADD CONSTRAINT "TemplateBootstrapImport_brandId_fkey" FOREIGN KEY ("brandId") REFERENCES "BrandProfile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "TemplateBootstrapImport" ADD CONSTRAINT "TemplateBootstrapImport_templatePackageVersionId_fkey" FOREIGN KEY ("templatePackageVersionId") REFERENCES "TemplatePackageVersion"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+38 -9
View File
@@ -65,6 +65,7 @@ model BrandProfile {
adminMemberships BrandMembership[]
releases BrandRelease[]
miniAppReleases MiniAppReleaseTask[]
bootstrapImports TemplateBootstrapImport[]
}
model BrandRelease {
@@ -167,18 +168,23 @@ model CapabilityAuditLog {
}
model BrandTemplateInstallation {
id String @id @default(uuid())
brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
templateKey String
templateVersion String @default("1.0.0")
configSnapshot Json
previousSnapshots Json @default("[]")
installedAt DateTime @default(now())
updatedAt DateTime @updatedAt
id String @id @default(uuid())
brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
templateKey String
templateVersion String @default("1.0.0")
visualTemplateKey String?
templatePackageVersionId String?
templatePackageVersion TemplatePackageVersion? @relation("BrandTemplateInstallationPackageVersion", fields: [templatePackageVersionId], references: [id], onDelete: SetNull)
contentChecksum String?
configSnapshot Json
previousSnapshots Json @default("[]")
installedAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([brandId, templateKey])
@@index([brandId])
@@index([templatePackageVersionId])
}
model BrandFieldDefinition {
@@ -433,6 +439,8 @@ model TemplatePackageVersion {
importedById String
importedBy AdminUser @relation("TemplatePackageImportedBy", fields: [importedById], references: [id], onDelete: Restrict)
auditLogs TemplatePackageAuditLog[]
installations BrandTemplateInstallation[] @relation("BrandTemplateInstallationPackageVersion")
bootstrapImports TemplateBootstrapImport[]
importedAt DateTime @default(now())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -442,6 +450,27 @@ model TemplatePackageVersion {
@@index([importedById, importedAt])
}
model TemplateBootstrapImport {
id String @id @default(uuid())
brandId String
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
templatePackageVersionId String
templatePackageVersion TemplatePackageVersion @relation(fields: [templatePackageVersionId], references: [id], onDelete: Restrict)
packageKey String
packageVersion String
contentChecksum String
actorId String
strategy String @default("missing_only")
status String
result Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([brandId, createdAt])
@@index([templatePackageVersionId, createdAt])
@@index([actorId, createdAt])
}
model TemplatePackageAuditLog {
id String @id @default(uuid())
templatePackageVersionId String
+25 -19
View File
@@ -643,23 +643,29 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
};
async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTemplate): Promise<void> {
// 这里只初始化明确的开发演示品牌;餐饮结构化槽位和表单取自对应 package,
// 这里只初始化明确的开发演示品牌;业务内容统一来自视觉包 sampleContent,
// 新增生产模板无需添加 seed 分支,品牌样例内容仍须由管理员显式导入。
const offerings = template.offerings;
const foodSample =
template.templateKey === "food"
? getTemplatePackageManifestForVisualKey("acheng-campus-food")?.sampleContent?.food
: undefined;
if (template.templateKey === "food" && !foodSample)
throw new Error("Food development sample is missing");
const trustContent = foodSample
? foodSample.trustContent.map((item) => {
const fixture = template.trustContent.find((entry) => entry.type === item.type);
return { ...item, ...fixture, config: { ...item.config, ...fixture?.config } };
})
: template.trustContent;
const inquiryFields = foodSample?.fields ?? template.inquiryForm?.fieldsSnapshot;
const inquiryFormName = foodSample?.inquiryFormName ?? template.inquiryForm?.name;
const visualKey = template.templateKey === "food" ? "acheng-campus-food" : "linjing-editorial";
const packageSample =
getTemplatePackageManifestForVisualKey(visualKey)?.sampleContent?.[template.templateKey];
if (!packageSample)
throw new Error(`Development sample is missing for ${visualKey}/${template.templateKey}`);
const offerings = packageSample.offerings.map((item) => ({
name: item.name,
summary: item.summary,
image: item.coverUrl ?? "",
kind: item.kind as OfferingKind,
priceText: item.priceText,
priceAmount: item.priceAmount,
config: { categoryKey: item.categoryKey, ...(item.config ?? {}) },
}));
const trustContent = packageSample.trustContent;
const inquiryFields = packageSample.fields;
const inquiryFormName = packageSample.inquiryFormName;
const seedBrandConfig = {
...(packageSample.brandConfig ?? {}),
...template.brandConfig,
};
if (!inquiryFields?.length || !inquiryFormName)
throw new Error("Development inquiry fixture is missing");
const existingBrand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
@@ -672,7 +678,7 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
await prisma.brandProfile.update({
where: { id: brandId },
data: {
config: { ...existingConfig, ...template.brandConfig } as Prisma.InputJsonValue,
config: { ...existingConfig, ...seedBrandConfig } as Prisma.InputJsonValue,
...(existingBrand.slug === "default-brand" && !existingBrand.avatarUrl
? { avatarUrl: "/assets/owner/portrait.jpg" }
: {}),
@@ -710,7 +716,7 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
select: { id: true, name: true },
});
for (const [index, item] of incompleteOfferings.entries()) {
const image = template.offerings[index % template.offerings.length]?.image;
const image = offerings[index % offerings.length]?.image;
if (!image) throw new Error("Development fixture has no offering image");
await prisma.offering.update({
where: { id: item.id },
@@ -727,7 +733,7 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
}
for (const [sortOrder, item] of trustContent.entries()) {
const existing = await prisma.trustContent.findFirst({
where: { brandId, type: item.type },
where: { brandId, type: item.type, title: item.title },
orderBy: [{ isPublished: "desc" }, { sortOrder: "asc" }],
});
const { config, ...fields } = item;
+13
View File
@@ -1,6 +1,7 @@
import {
IsArray,
IsBoolean,
IsUUID,
IsIn,
IsInt,
IsObject,
@@ -103,6 +104,18 @@ export class UpdateBookingTagsDto {
export class InstallTemplateDto {
@IsIn(brandTemplateKeys)
templateKey!: BrandTemplateKey;
@IsOptional() @IsUUID() templatePackageVersionId?: string;
}
export class PreviewTemplateSampleDto {
@IsOptional() @IsUUID() templatePackageVersionId?: string;
@IsOptional() @IsIn(["missing_only"]) strategy?: "missing_only";
}
export class ImportTemplateSampleDto {
@IsOptional() @IsUUID() templatePackageVersionId?: string;
@IsIn(["missing_only"]) strategy!: "missing_only";
@IsBoolean() confirm!: boolean;
}
export class UpdateCapabilityInstallationDto {
+42 -1
View File
@@ -12,6 +12,8 @@ import {
isVisualTemplateCompatible,
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
validateTemplatePackageManifest,
type TemplatePackageManifest,
} from "@personal-brand/config";
import { isTrustContentComplete } from "@personal-brand/types";
import { PrismaService } from "./prisma.service.js";
@@ -63,6 +65,19 @@ export class BrandReleaseApiService {
where: { brandId },
orderBy: { updatedAt: "desc" },
});
const packageVersion = installation?.templatePackageVersionId
? await database.templatePackageVersion.findUnique({
where: { id: installation.templatePackageVersionId },
select: {
packageKey: true,
version: true,
visualTemplateKey: true,
status: true,
contentChecksum: true,
manifestSnapshot: true,
},
})
: null;
const template = getBrandTemplate(installation?.templateKey ?? brand?.templateKey ?? "");
const config = this.jsonObject(brand?.config);
const visualKey =
@@ -70,7 +85,22 @@ export class BrandReleaseApiService {
? config.visualTemplateKey
: getDefaultVisualTemplateKey(brand?.templateKey ?? defaultBrandTemplateKey);
const visual = getVisualTemplate(visualKey);
const packageManifest = getTemplatePackageManifestForVisualKey(visualKey);
const storedManifest = packageVersion?.manifestSnapshot as unknown as
TemplatePackageManifest | undefined;
const packageManifest = storedManifest ?? getTemplatePackageManifestForVisualKey(visualKey);
const packageVersionValid =
!installation?.templatePackageVersionId ||
Boolean(
packageVersion &&
packageVersion.status === "published" &&
/^[a-f0-9]{64}$/.test(packageVersion.contentChecksum) &&
packageVersion.packageKey === (storedManifest?.packageKey ?? "") &&
packageVersion.version === (storedManifest?.version ?? "") &&
(packageVersion.visualTemplateKey ?? packageVersion.packageKey) ===
(storedManifest?.visualTemplateKey ?? packageVersion.packageKey) &&
storedManifest?.supportedIndustryTemplates.includes(brand?.templateKey ?? "") &&
validateTemplatePackageManifest(storedManifest).length === 0,
);
const [offerings, forms, trustItems] = await Promise.all([
database.offering.findMany({
where: { brandId, isEnabled: true },
@@ -124,6 +154,17 @@ export class BrandReleaseApiService {
destination: "/admin/brand",
},
{ key: "template", label: "行业模板配置", passed: Boolean(template) },
{
key: "template-package-version",
label: "模板包版本台账",
passed: packageVersionValid,
...(packageVersionValid
? {}
: {
help: "当前安装记录引用的模板包版本不可用、未发布或与 manifest 不一致,请重新安装已发布版本。",
}),
destination: "/admin/publication",
},
{
key: "visual",
label: "视觉模板与行业模板的适配",
+6 -1
View File
@@ -38,6 +38,7 @@ export async function buildBrandReleaseSnapshot(
database.brandTemplateInstallation.findFirst({
where: { brandId },
orderBy: { updatedAt: "desc" },
include: { templatePackageVersion: true },
}),
database.brandFieldDefinition.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
database.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
@@ -63,7 +64,11 @@ export async function buildBrandReleaseSnapshot(
templateDefinition: getBrandTemplate(templateKey) ?? null,
visualTemplateDefinition: getVisualTemplate(visualKey) ?? null,
visualTemplateManifest: getVisualTemplateManifest(visualKey) ?? null,
templatePackageManifest: getTemplatePackageManifestForVisualKey(visualKey) ?? null,
templatePackageManifest:
(installation?.templatePackageVersion?.manifestSnapshot as unknown as
TemplatePackageManifest | undefined) ??
getTemplatePackageManifestForVisualKey(visualKey) ??
null,
brand: brand ? jsonObject(brand) : null,
installation: installation ? jsonObject(installation) : null,
fields: fields.map((item) => jsonObject(item)),
@@ -1,6 +1,10 @@
import { Body, Controller, Get, Param, Patch, Post, Req } from "@nestjs/common";
import { Body, Controller, Get, Param, Patch, Post, Query, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { UpdateCapabilityInstallationDto } from "../../admin.dto.js";
import {
ImportTemplateSampleDto,
PreviewTemplateSampleDto,
UpdateCapabilityInstallationDto,
} from "../../admin.dto.js";
import { requireAdminIdentity } from "./admin-access.identity.js";
import { AdminSampleContentService } from "./admin-sample-content.service.js";
import { AdminWorkspaceCapabilitiesService } from "./admin-workspace-capabilities.service.js";
@@ -18,14 +22,20 @@ class AdminCapabilityController {
}
@Get("sample-content/preview")
previewSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
return this.sampleContentService.preview(requireAdminIdentity(request).brandId);
previewSampleContent(
@Req() request: FastifyRequest,
@Query() query: PreviewTemplateSampleDto,
): Promise<unknown> {
return this.sampleContentService.preview(requireAdminIdentity(request).brandId, query);
}
@Post("sample-content/import")
importSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
importSampleContent(
@Req() request: FastifyRequest,
@Body() body: ImportTemplateSampleDto,
): Promise<unknown> {
const identity = requireAdminIdentity(request);
return this.sampleContentService.import(identity.brandId, identity.subject);
return this.sampleContentService.import(identity.brandId, identity.subject, body);
}
@Patch("capabilities/:key")
@@ -1,181 +1,424 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { getTemplateSampleContent, getDefaultVisualTemplateKey } from "@personal-brand/config";
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
import { Prisma, type TemplatePackageVersion } from "@prisma/client";
import {
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
getTemplateSampleContent,
getVisualTemplate,
isVisualTemplateCompatible,
validateTemplatePackageManifest,
type TemplatePackageManifest,
type TemplateSampleContent,
} from "@personal-brand/config";
import { validateFieldSnapshot } from "@personal-brand/validation";
import { PrismaService } from "../../prisma.service.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
type BootstrapSource = {
kind: "package_version" | "registry";
manifest: TemplatePackageManifest;
sample: TemplateSampleContent;
version?: TemplatePackageVersion;
};
type Counts = {
brandConfig: number;
offerings: number;
trustContent: number;
fields: number;
inquiryForms: number;
};
type Action = { type: keyof Counts; key: string; action: "create" | "skip" };
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
function deepMergeMissing(
defaults: Record<string, unknown>,
saved: Record<string, unknown>,
path = "",
): { value: Record<string, unknown>; missingPaths: string[] } {
const value = { ...saved };
const missingPaths: string[] = [];
for (const [key, fallback] of Object.entries(defaults)) {
const currentPath = path ? `${path}.${key}` : key;
if (!Object.prototype.hasOwnProperty.call(saved, key)) {
value[key] = fallback;
missingPaths.push(currentPath);
continue;
}
const current = saved[key];
if (
fallback &&
current &&
typeof fallback === "object" &&
typeof current === "object" &&
!Array.isArray(fallback) &&
!Array.isArray(current)
) {
const nested = deepMergeMissing(
fallback as Record<string, unknown>,
current as Record<string, unknown>,
currentPath,
);
value[key] = nested.value;
missingPaths.push(...nested.missingPaths);
}
}
return { value, missingPaths };
}
function asJson(value: unknown): Prisma.InputJsonValue {
return value as Prisma.InputJsonValue;
}
@Injectable()
export class AdminSampleContentService {
constructor(
private readonly prisma: PrismaService,
private readonly templateWorkspace: TemplateWorkspaceService,
_templateWorkspace: TemplateWorkspaceService,
) {}
async preview(brandId: string) {
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
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 sample = getTemplateSampleContent(
templateKey,
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: getDefaultVisualTemplateKey(templateKey),
async preview(brandId: string, query?: { templatePackageVersionId?: string }) {
const { brand, source, visualTemplateKey } = await this.resolveSource(
brandId,
query?.templatePackageVersionId,
);
if (!sample) throw new BadRequestException("模板示例内容不存在");
const [offerings, trustContent, fields, enabledForms] = await Promise.all([
this.prisma.offering.count({ where: { brandId } }),
this.prisma.trustContent.count({ where: { brandId } }),
this.prisma.brandFieldDefinition.count({ where: { brandId, source: "sample" } }),
this.prisma.inquiryForm.count({ where: { brandId, isEnabled: true } }),
]);
const plan = await this.buildPlan(brandId, brand.config, source);
return {
templateKey: sample.templateKey,
alreadyImported: offerings > 0 || trustContent > 0 || fields > 0,
counts: {
offerings: sample.offerings.length,
trustContent: sample.trustContent.length,
fields: sample.fields.length,
inquiryForms: 1,
},
willCreateInquiryForm: enabledForms === 0,
templateKey: source.sample.templateKey,
visualTemplateKey,
source: this.publicSource(source),
alreadyImported: plan.alreadyImported,
willCreateInquiryForm: plan.counts.inquiryForms > 0,
counts: plan.counts,
skipped: plan.skipped,
plan: plan.actions,
missingConfigKeys: plan.missingConfigKeys,
};
}
async import(brandId: string, actorId: string) {
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { config: true },
async import(
brandId: string,
actorId: string,
body: { templatePackageVersionId?: string; strategy: "missing_only"; confirm: boolean },
) {
if (body.confirm !== true) throw new BadRequestException("导入示例内容必须显式确认");
if (body.strategy !== "missing_only")
throw new BadRequestException("当前只支持 missing_only 导入策略");
const { brand, source } = await this.resolveSource(brandId, body.templatePackageVersionId);
if (!source.version)
throw new BadRequestException("品牌尚未安装可追溯的已发布模板包版本,不能导入示例内容");
const plan = await this.buildPlan(brandId, brand.config, source);
const priorImport = await this.prisma.templateBootstrapImport.findFirst({
where: {
brandId,
templatePackageVersionId: source.version.id,
contentChecksum: source.version.contentChecksum,
status: "imported",
},
orderBy: { createdAt: "desc" },
});
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const sample = getTemplateSampleContent(
templateKey,
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: getDefaultVisualTemplateKey(templateKey),
);
if (!sample) throw new BadRequestException("模板示例内容不存在");
if (validateFieldSnapshot(sample.fields).length)
throw new BadRequestException("模板咨询表单示例字段无效");
const existing = await this.prisma.brandFieldDefinition.count({
where: { brandId, source: "sample" },
});
const existingOffering = await this.prisma.offering.count({
where: { brandId, name: { in: sample.offerings.map((item) => item.name) } },
});
if (existing || existingOffering) throw new BadRequestException("示例内容已经导入");
if (priorImport) {
return {
imported: true,
alreadyImported: true,
source: this.publicSource(source),
counts: priorImport.result ?? plan.counts,
};
}
const result = await this.prisma.$transaction(async (tx) => {
if (sample.brandConfig) {
// 仅显式导入时补齐缺失配置,已有品牌内容(包括空值)始终优先。
const merge = (
defaults: Record<string, unknown>,
saved: Record<string, unknown>,
): Record<string, unknown> =>
Object.fromEntries(
[...new Set([...Object.keys(defaults), ...Object.keys(saved)])].map((key) => {
const a = defaults[key];
const b = saved[key];
if (!Object.prototype.hasOwnProperty.call(saved, key)) return [key, a];
return [
key,
a &&
b &&
typeof a === "object" &&
typeof b === "object" &&
!Array.isArray(a) &&
!Array.isArray(b)
? merge(a as Record<string, unknown>, b as Record<string, unknown>)
: b,
];
}),
);
const counts: Counts = {
brandConfig: 0,
offerings: 0,
trustContent: 0,
fields: 0,
inquiryForms: 0,
};
if (plan.missingConfigKeys.length) {
const merged = deepMergeMissing(record(source.sample.brandConfig), record(brand.config));
await tx.brandProfile.update({
where: { id: brandId },
data: { config: merge(sample.brandConfig, config) as Prisma.InputJsonValue },
data: { config: asJson(merged.value) },
});
counts.brandConfig = merged.missingPaths.length;
}
const offerings = await tx.offering.createMany({
data: sample.offerings.map((item, sortOrder) => ({
for (const item of source.sample.offerings) {
const name = String(item.name ?? "");
if (!name || plan.existingOfferingNames.has(name)) continue;
await tx.offering.create({
data: {
brandId,
kind: String(item.kind ?? "service"),
name,
...(typeof item.summary === "string" ? { summary: item.summary } : {}),
...(typeof item.coverUrl === "string" ? { coverUrl: item.coverUrl } : {}),
...(typeof item.priceText === "string" ? { priceText: item.priceText } : {}),
config: asJson({
...record(item.config),
...(item.categoryKey ? { categoryKey: item.categoryKey } : {}),
}),
sortOrder: counts.offerings,
isEnabled: true,
},
});
counts.offerings += 1;
}
for (const item of source.sample.trustContent) {
const type = String(item.type ?? "");
const title = String(item.title ?? "");
if (!type || !title || plan.existingTrustKeys.has(`${type}\0${title}`)) continue;
await tx.trustContent.create({
data: {
brandId,
type,
title,
content: String(item.content ?? ""),
...(typeof item.summary === "string" ? { summary: item.summary } : {}),
...(item.config ? { config: asJson(item.config) } : {}),
sortOrder: counts.trustContent,
isPublished: false,
},
});
counts.trustContent += 1;
}
for (const item of source.sample.fields) {
const key = String(item.key ?? "");
if (!key || plan.existingFieldKeys.has(key)) continue;
await tx.brandFieldDefinition.create({
data: {
brandId,
scope: "inquiry",
key,
label: String(item.label ?? key),
type: String(item.type ?? "text"),
sortOrder: counts.fields,
source: "sample",
required: item.required === true,
},
});
counts.fields += 1;
}
if (plan.counts.inquiryForms) {
await tx.inquiryForm.create({
data: {
brandId,
name: source.sample.inquiryFormName,
purpose: "inquiry",
targetType: "brand",
submissionAction: "create-inquiry",
fieldsSnapshot: asJson(source.sample.fields),
isEnabled: true,
},
});
counts.inquiryForms = 1;
}
const importResult = { ...counts, skipped: plan.skipped, actions: plan.actions };
await tx.templateBootstrapImport.create({
data: {
brandId,
kind: item.kind,
name: item.name,
summary: item.summary,
...(item.coverUrl ? { coverUrl: item.coverUrl } : {}),
...(item.priceText ? { priceText: item.priceText } : {}),
config: { ...item.config, categoryKey: item.categoryKey } as Prisma.InputJsonValue,
sortOrder,
isEnabled: true,
})),
templatePackageVersionId: source.version!.id,
packageKey: source.version!.packageKey,
packageVersion: source.version!.version,
contentChecksum: source.version!.contentChecksum,
actorId,
strategy: "missing_only",
status: "imported",
result: asJson(importResult),
},
});
const trust = await tx.trustContent.createMany({
data: sample.trustContent.map((item, sortOrder) => ({
brandId,
type: item.type,
title: item.title,
content: item.content,
...(item.config ? { config: item.config as Prisma.InputJsonValue } : {}),
sortOrder,
isPublished: false,
})),
});
const fields = await tx.brandFieldDefinition.createMany({
data: sample.fields.map((item, sortOrder) => ({
brandId,
scope: "inquiry",
key: item.key,
label: item.label,
type: item.type,
sortOrder,
source: "sample",
required: item.required,
})),
});
const hasEnabledForm = await tx.inquiryForm.count({ where: { brandId, isEnabled: true } });
const inquiryForm = hasEnabledForm
? null
: await tx.inquiryForm.create({
data: {
brandId,
name: sample.inquiryFormName,
purpose: "inquiry",
targetType: "brand",
submissionAction: "create-inquiry",
fieldsSnapshot: sample.fields,
isEnabled: true,
},
});
await tx.capabilityAuditLog.create({
data: {
brandId,
capabilityKey: sample.capabilityKey,
capabilityKey: source.sample.capabilityKey,
actorId,
action: "sample_content_imported",
toStatus: "enabled",
config: {
offerings: offerings.count,
trustContent: trust.count,
fields: fields.count,
inquiryForms: inquiryForm ? 1 : 0,
},
config: asJson({ source: this.publicSource(source), ...importResult }),
},
});
return {
offerings: offerings.count,
trustContent: trust.count,
fields: fields.count,
inquiryForms: inquiryForm ? 1 : 0,
};
return counts;
});
return { imported: true, counts: result };
return {
imported: true,
alreadyImported: false,
source: this.publicSource(source),
counts: result,
};
}
private async resolveSource(brandId: string, requestedVersionId?: string) {
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true, config: true },
});
if (!brand) throw new NotFoundException("品牌不存在");
const config = record(brand.config);
const visualTemplateKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: getDefaultVisualTemplateKey(brand.templateKey);
const installation = requestedVersionId
? null
: await this.prisma.brandTemplateInstallation.findFirst({
where: { brandId },
orderBy: { updatedAt: "desc" },
select: { templatePackageVersionId: true },
});
const versionId = requestedVersionId ?? installation?.templatePackageVersionId ?? undefined;
let source: BootstrapSource;
if (versionId) {
const version = await this.prisma.templatePackageVersion.findUnique({
where: { id: versionId },
});
if (!version) throw new BadRequestException("指定的模板包版本不存在");
if (version.status !== "published")
throw new BadRequestException("只有已发布的模板包版本可用于 bootstrap");
const manifest = version.manifestSnapshot as unknown as TemplatePackageManifest;
const issues = validateTemplatePackageManifest(manifest);
if (issues.length)
throw new BadRequestException(`模板包 manifest 无效:${issues.join(";")}`);
if (
manifest.packageKey !== version.packageKey ||
manifest.version !== version.version ||
!/^[a-f0-9]{64}$/.test(version.contentChecksum) ||
(version.visualTemplateKey ?? version.packageKey) !==
(manifest.visualTemplateKey ?? version.packageKey) ||
!manifest.supportedIndustryTemplates.includes(brand.templateKey)
)
throw new BadRequestException("模板包版本与品牌行业或版本台账不匹配");
const sample = manifest.sampleContent?.[brand.templateKey];
if (!sample) throw new BadRequestException("该模板包没有当前行业的 bootstrap sampleContent");
source = { kind: "package_version", version, manifest, sample };
} else {
const manifest = getTemplatePackageManifestForVisualKey(visualTemplateKey);
const sample = getTemplateSampleContent(brand.templateKey, visualTemplateKey);
if (!manifest || !sample || requestedVersionId)
throw new BadRequestException("当前模板没有可用的 bootstrap sampleContent");
source = { kind: "registry", manifest, sample };
}
const visual = getVisualTemplate(visualTemplateKey);
if (!visual || !isVisualTemplateCompatible(visual, brand.templateKey))
throw new BadRequestException("当前视觉模板与品牌行业不兼容");
if (source.sample.templateKey !== brand.templateKey)
throw new BadRequestException("sampleContent 行业与品牌不匹配");
const fieldIssues = validateFieldSnapshot(source.sample.fields);
if (fieldIssues.length)
throw new BadRequestException(`bootstrap 表单字段无效:${fieldIssues.join(";")}`);
return { brand, source, visualTemplateKey };
}
private async buildPlan(brandId: string, savedConfig: unknown, source: BootstrapSource) {
const sample = source.sample;
const configMerge = deepMergeMissing(record(sample.brandConfig), record(savedConfig));
const [offerings, trustContent, fields, enabledForm, previous] = await Promise.all([
this.prisma.offering.findMany({ where: { brandId }, select: { name: true } }),
this.prisma.trustContent.findMany({
where: { brandId },
select: { type: true, title: true },
}),
this.prisma.brandFieldDefinition.findMany({
where: { brandId, scope: "inquiry" },
select: { key: true },
}),
this.prisma.inquiryForm.findFirst({
where: { brandId, isEnabled: true },
select: { id: true },
}),
source.version
? this.prisma.templateBootstrapImport.findFirst({
where: {
brandId,
templatePackageVersionId: source.version.id,
contentChecksum: source.version.contentChecksum,
status: "imported",
},
select: { id: true },
})
: Promise.resolve(null),
]);
const offeringNames = new Set(offerings.map((item) => item.name));
const trustKeys = new Set(trustContent.map((item) => `${item.type}\0${item.title}`));
const fieldKeys = new Set(fields.map((item) => item.key));
const actions: Action[] = [];
if (sample.brandConfig) {
for (const key of configMerge.missingPaths)
actions.push({ type: "brandConfig", key, action: "create" });
}
for (const item of sample.offerings) {
const key = String(item.name ?? "(missing name)");
actions.push({
type: "offerings",
key,
action: key !== "(missing name)" && !offeringNames.has(key) ? "create" : "skip",
});
}
for (const item of sample.trustContent) {
const type = String(item.type ?? "");
const title = String(item.title ?? "");
const key = `${type}/${title}`;
actions.push({
type: "trustContent",
key,
action: type && title && !trustKeys.has(`${type}\0${title}`) ? "create" : "skip",
});
}
for (const item of sample.fields) {
const key = String(item.key ?? "(missing key)");
actions.push({
type: "fields",
key,
action: key !== "(missing key)" && !fieldKeys.has(key) ? "create" : "skip",
});
}
actions.push({
type: "inquiryForms",
key: sample.inquiryFormName,
action: enabledForm ? "skip" : "create",
});
const count = (type: keyof Counts, action: Action["action"]) =>
actions.filter((item) => item.type === type && item.action === action).length;
return {
alreadyImported: Boolean(previous),
counts: {
brandConfig: count("brandConfig", "create"),
offerings: count("offerings", "create"),
trustContent: count("trustContent", "create"),
fields: count("fields", "create"),
inquiryForms: count("inquiryForms", "create"),
} satisfies Counts,
skipped: {
brandConfig: 0,
offerings: count("offerings", "skip"),
trustContent: count("trustContent", "skip"),
fields: count("fields", "skip"),
inquiryForms: count("inquiryForms", "skip"),
} satisfies Counts,
actions,
missingConfigKeys: configMerge.missingPaths,
existingOfferingNames: offeringNames,
existingTrustKeys: trustKeys,
existingFieldKeys: fieldKeys,
};
}
private publicSource(source: BootstrapSource) {
return {
kind: source.kind,
packageKey: source.manifest.packageKey,
version: source.manifest.version,
contentChecksum: source.version?.contentChecksum ?? null,
...(source.version ? { templatePackageVersionId: source.version.id } : {}),
};
}
}
@@ -24,7 +24,11 @@ class AdminWorkspacePreviewController {
@Post("install")
install(@Req() request: FastifyRequest, @Body() body: InstallTemplateDto): Promise<unknown> {
return this.templateWorkspace.install(requireAdminIdentity(request).brandId, body.templateKey);
return this.templateWorkspace.install(
requireAdminIdentity(request).brandId,
body.templateKey,
body.templatePackageVersionId,
);
}
}
@@ -17,7 +17,10 @@ export class AdminWorkspaceService {
async get(brandId: string): Promise<unknown> {
const [brand, installations, fields, offerings, forms] = await Promise.all([
this.prisma.brandProfile.findUnique({ where: { id: brandId } }),
this.prisma.brandTemplateInstallation.findMany({ where: { brandId } }),
this.prisma.brandTemplateInstallation.findMany({
where: { brandId },
orderBy: { updatedAt: "desc" },
}),
this.prisma.brandFieldDefinition.findMany({
where: { brandId },
orderBy: { sortOrder: "asc" },
+52 -1
View File
@@ -1,4 +1,5 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import type { TemplatePackageVersion } from "@prisma/client";
import { Prisma } from "@prisma/client";
import {
type BrandTemplateKey,
@@ -95,7 +96,7 @@ export class TemplateWorkspaceService {
}
return defaultBrandTemplateKey;
}
async install(brandId: string, templateKey: BrandTemplateKey) {
async install(brandId: string, templateKey: BrandTemplateKey, templatePackageVersionId?: string) {
const template = getBrandTemplate(templateKey);
if (!template) throw new BadRequestException("行业模板不存在");
const [existing, brand] = await Promise.all([
@@ -141,6 +142,11 @@ export class TemplateWorkspaceService {
visualTemplate: visualManifest,
capabilities: template.capabilities,
};
const packageVersion = await this.resolveInstallablePackageVersion(
templateKey,
visualTemplateKey,
templatePackageVersionId,
);
return this.prisma.$transaction(async (tx) => {
// 安装记录与品牌身份必须同时落库,否则会出现「品牌在跑 A 模板、台账记的是 B」的漂移。
// 已经自定义过视觉模板的品牌,补建台账时保留原选择,只把行业模板身份写回。
@@ -158,6 +164,9 @@ export class TemplateWorkspaceService {
brandId,
templateKey,
templateVersion: template.version,
visualTemplateKey,
templatePackageVersionId: packageVersion?.id ?? null,
contentChecksum: packageVersion?.contentChecksum ?? null,
configSnapshot: templatePackageSnapshot as unknown as Prisma.InputJsonValue,
},
});
@@ -176,6 +185,42 @@ export class TemplateWorkspaceService {
return { installation, template, visualTemplate: visualManifest };
});
}
private async resolveInstallablePackageVersion(
templateKey: BrandTemplateKey,
visualTemplateKey: string,
templatePackageVersionId?: string,
): Promise<TemplatePackageVersion | null> {
const version = templatePackageVersionId
? await this.prisma.templatePackageVersion.findUnique({
where: { id: templatePackageVersionId },
})
: await this.prisma.templatePackageVersion.findFirst({
where: { packageKey: visualTemplateKey, status: "published" },
orderBy: { importedAt: "desc" },
});
if (!version) {
if (templatePackageVersionId) throw new BadRequestException("指定的模板包版本不存在");
return null;
}
if (version.status !== "published")
throw new BadRequestException("只有已发布的模板包版本可以安装到品牌");
const manifest = record(version.manifestSnapshot);
const manifestVisualTemplateKey =
typeof manifest.visualTemplateKey === "string"
? manifest.visualTemplateKey
: version.packageKey;
if (
manifest.packageKey !== version.packageKey ||
manifest.version !== version.version ||
manifestVisualTemplateKey !== visualTemplateKey ||
!Array.isArray(manifest.supportedIndustryTemplates) ||
!manifest.supportedIndustryTemplates.includes(templateKey)
) {
throw new BadRequestException("模板包版本与行业或视觉模板不匹配");
}
return version;
}
private async installation(brandId: string) {
const item = await this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } });
if (!item) throw new BadRequestException("尚未安装行业模板");
@@ -266,3 +311,9 @@ export class TemplateWorkspaceService {
};
}
}
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
+112 -33
View File
@@ -2283,6 +2283,7 @@ test("admin can preview and import sample content idempotently", async () => {
where: { brandId, content: "示例内容,待品牌主理人完善。" },
});
await prisma.brandProfile.update({ where: { id: brandId }, data: { templateKey: "doors" } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
await prisma.offering.deleteMany({
where: {
brandId,
@@ -2307,44 +2308,77 @@ test("admin can preview and import sample content idempotently", async () => {
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}` };
const archive = createTemplateArchive("acheng-campus-food");
const uploaded = multipartArchive(archive);
const importedPackage = await request("/admin/templates/import", {
method: "POST",
headers: { ...headers, ...uploaded.headers },
rawPayload: uploaded.payload,
});
assert.equal(importedPackage.statusCode, 201, importedPackage.body);
const packageVersionId = JSON.parse(importedPackage.body).version.id;
const publishedPackage = await request(`/admin/templates/${packageVersionId}/publish`, {
method: "POST",
headers,
});
assert.equal(publishedPackage.statusCode, 201, publishedPackage.body);
await prisma.brandProfile.update({
where: { id: brandId },
data: { templateKey: "food", config: { visualTemplateKey: "acheng-campus-food" } },
});
await prisma.brandTemplateInstallation.create({
data: {
brandId,
templateKey: "food",
visualTemplateKey: "acheng-campus-food",
templatePackageVersionId: packageVersionId,
contentChecksum: JSON.parse(importedPackage.body).version.contentChecksum,
templateVersion: JSON.parse(importedPackage.body).version.version,
configSnapshot: { schemaVersion: "1.0" },
},
});
const preview = await request("/admin/workspace/sample-content/preview", {
headers: { authorization: `Bearer ${token}` },
headers,
});
assert.equal(preview.statusCode, 200);
assert.equal(JSON.parse(preview.body).source.templatePackageVersionId, packageVersionId);
assert.equal(JSON.parse(preview.body).source.kind, "package_version");
assert.equal(JSON.parse(preview.body).willCreateInquiryForm, false);
assert.equal(await prisma.templateBootstrapImport.count({ where: { brandId } }), 0);
const missingConfirmation = await request("/admin/workspace/sample-content/import", {
method: "POST",
headers,
payload: { strategy: "missing_only", confirm: false },
});
assert.equal(missingConfirmation.statusCode, 400);
const imported = await request("/admin/workspace/sample-content/import", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
headers,
payload: {
templatePackageVersionId: packageVersionId,
strategy: "missing_only",
confirm: true,
},
});
assert.equal(imported.statusCode, 201);
assert.equal(JSON.parse(imported.body).counts.inquiryForms, 0);
assert.ok(await prisma.inquiryForm.findFirst({ where: { brandId, name: "现有客户表单" } }));
await prisma.offering.deleteMany({
where: {
brandId,
name: { in: ["序章·入户门", "庭院·边界门", "室内·静谧门", "一对一门系统设计咨询"] },
},
});
await prisma.trustContent.deleteMany({
where: { brandId, content: "示例内容,待品牌主理人完善。" },
});
await prisma.brandFieldDefinition.deleteMany({ where: { brandId, source: "sample" } });
await prisma.inquiryForm.deleteMany({ where: { brandId } });
const importedWithoutForm = await request("/admin/workspace/sample-content/import", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
});
assert.equal(importedWithoutForm.statusCode, 201);
assert.equal(JSON.parse(importedWithoutForm.body).counts.inquiryForms, 1);
const importedForm = await prisma.inquiryForm.findFirstOrThrow({
where: { brandId, name: "门系统咨询表单" },
});
assert.ok(Array.isArray(importedForm.fieldsSnapshot) && importedForm.fieldsSnapshot.length > 0);
assert.equal(
await prisma.templateBootstrapImport.count({ where: { brandId, status: "imported" } }),
1,
);
const duplicate = await request("/admin/workspace/sample-content/import", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
headers,
payload: {
templatePackageVersionId: packageVersionId,
strategy: "missing_only",
confirm: true,
},
});
assert.equal(duplicate.statusCode, 400);
assert.equal(duplicate.statusCode, 201);
assert.equal(JSON.parse(duplicate.body).alreadyImported, true);
await prisma.offering.deleteMany({
where: {
brandId,
@@ -2371,9 +2405,16 @@ test("admin can preview and import sample content idempotently", async () => {
});
}
await prisma.capabilityAuditLog.deleteMany({ where: { brandId, capabilityKey: "doors" } });
await prisma.templateBootstrapImport.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
await prisma.templatePackageAuditLog.deleteMany({
where: { templatePackageVersionId: packageVersionId },
});
await prisma.templatePackageVersion.delete({ where: { id: packageVersionId } });
await prisma.templatePackage.deleteMany({ where: { packageKey: "acheng-campus-food" } });
await prisma.brandProfile.update({
where: { id: brandId },
data: { templateKey: originalBrand?.templateKey ?? "food" },
data: { templateKey: originalBrand?.templateKey ?? "food", config: originalBrand?.config },
});
});
@@ -4006,16 +4047,37 @@ test("atelier template imports selected package and preserves draft publication
headers,
payload: { config: { visualTemplateKey: "atelier-solopreneur" } },
});
const packageArchive = multipartArchive(createTemplateArchive("atelier-solopreneur"));
const importedPackage = await request("/admin/templates/import", {
method: "POST",
headers: { ...headers, ...packageArchive.headers },
rawPayload: packageArchive.payload,
});
assert.equal(importedPackage.statusCode, 201, importedPackage.body);
const selectedPackage = JSON.parse(importedPackage.body).version;
const publishedPackage = await request(`/admin/templates/${selectedPackage.id}/publish`, {
method: "POST",
headers,
});
assert.equal(publishedPackage.statusCode, 201, publishedPackage.body);
const installation = await json("/admin/workspace/install", {
method: "POST",
headers,
payload: { templateKey: "personal" },
payload: { templateKey: "personal", templatePackageVersionId: selectedPackage.id },
});
assert.equal(installation.visualTemplate.key, "atelier-solopreneur");
assert.equal(installation.visualTemplate.tokens.colors.accent, "#1f3a5f");
const preview = await json("/admin/workspace/sample-content/preview", { headers });
assert.equal(preview.counts.fields, 5);
await json("/admin/workspace/sample-content/import", { method: "POST", headers });
await json("/admin/workspace/sample-content/import", {
method: "POST",
headers,
payload: {
templatePackageVersionId: selectedPackage.id,
strategy: "missing_only",
confirm: true,
},
});
const imported = await json("/admin/config/brand", { headers });
assert.equal(imported.config.visualPresentation.home.subtitle, "保留已有品牌说明");
assert.equal(imported.config.atelier.deliverables.length, 7);
@@ -4025,11 +4087,17 @@ test("atelier template imports selected package and preserves draft publication
form.fieldsSnapshot.map((field) => field.key),
["name", "industry", "needs", "timeline", "contact"],
);
assert.equal(
(await request("/admin/workspace/sample-content/import", { method: "POST", headers }))
.statusCode,
400,
);
const duplicateImport = await request("/admin/workspace/sample-content/import", {
method: "POST",
headers,
payload: {
templatePackageVersionId: selectedPackage.id,
strategy: "missing_only",
confirm: true,
},
});
assert.equal(duplicateImport.statusCode, 201);
assert.equal(JSON.parse(duplicateImport.body).alreadyImported, true);
const manifest = (await json("/admin/workspace", { headers })).templateContent;
const exampleOffering = await prisma.offering.findFirstOrThrow({
where: { brandId: brand.id },
@@ -4171,11 +4239,22 @@ test("atelier template imports selected package and preserves draft publication
where: { brandId: brand.id },
data: { isPublished: true },
});
const readiness = await json("/admin/releases/readiness", { headers });
assert.equal(
readiness.checks.find((check) => check.key === "template-package-version")?.passed,
true,
);
await json("/admin/releases/publish", {
method: "POST",
headers,
payload: { note: "宣传模板独立品牌验收" },
});
const release = await prisma.brandRelease.findFirstOrThrow({
where: { brandId: brand.id, status: "published" },
orderBy: { version: "desc" },
});
assert.equal(release.snapshot.installation.templatePackageVersionId, selectedPackage.id);
assert.equal(release.snapshot.templatePackageManifest.packageKey, selectedPackage.packageKey);
const published = await json("/public/workspace?brandSlug=" + slug);
assert.equal(published.brand.visualPresentation.home.subtitle, "保留已有品牌说明");
const next = structuredClone(defaults);