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

@@ -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 } : {}),
};
}
}