428 lines
17 KiB
TypeScript
428 lines
17 KiB
TypeScript
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
|
||
import {
|
||
capabilityRegistry,
|
||
getBrandTemplate,
|
||
getTemplatePackageManifest,
|
||
getVisualTemplate,
|
||
getVisualTemplateManifest,
|
||
validateTemplatePackageManifest,
|
||
} from "@personal-brand/config";
|
||
import type {
|
||
TemplatePackageManifest,
|
||
TemplatePreviewFixture,
|
||
TemplateSampleContent,
|
||
} from "@personal-brand/config";
|
||
import { validateFieldSnapshot, validateTemplatePreviewFixture } from "@personal-brand/validation";
|
||
import type { BrandReleaseSnapshot } from "../../brand-release.service.js";
|
||
import { PrismaService } from "../../prisma.service.js";
|
||
import { assemblePublicWorkspace } from "../public/public-workspace.snapshot-assembler.js";
|
||
import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-assets.service.js";
|
||
|
||
function record(value: unknown): Record<string, unknown> {
|
||
return value && typeof value === "object" && !Array.isArray(value)
|
||
? (value as Record<string, unknown>)
|
||
: {};
|
||
}
|
||
function array(value: unknown): unknown[] {
|
||
return Array.isArray(value) ? value : [];
|
||
}
|
||
|
||
// 预览投影会遍历这些嵌套声明,必须先校验结构,不能只检查顶层数组。
|
||
function hasPreviewStructure(manifest: Record<string, unknown>): boolean {
|
||
const records = (value: unknown): value is Record<string, unknown>[] =>
|
||
Array.isArray(value) &&
|
||
value.every((item) => item !== null && typeof item === "object" && !Array.isArray(item));
|
||
const strings = (item: Record<string, unknown>, keys: string[]) =>
|
||
keys.every((key) => typeof item[key] === "string" && String(item[key]).trim().length > 0);
|
||
const fields = (value: unknown) =>
|
||
records(value) &&
|
||
value.every(
|
||
(field) =>
|
||
strings(field, ["key", "binding"]) &&
|
||
(field.options === undefined ||
|
||
(records(field.options) &&
|
||
field.options.every((option) => strings(option, ["value", "label"])))),
|
||
);
|
||
return (
|
||
records(manifest.dataSlots) &&
|
||
manifest.dataSlots.every(
|
||
(slot) => strings(slot, ["key", "source"]) && typeof slot.required === "boolean",
|
||
) &&
|
||
records(manifest.navigation) &&
|
||
manifest.navigation.every((tab) => strings(tab, ["key", "label", "page"])) &&
|
||
records(manifest.assetSlots) &&
|
||
manifest.assetSlots.every(
|
||
(slot) =>
|
||
strings(slot, ["key", "label", "binding", "target"]) && typeof slot.required === "boolean",
|
||
) &&
|
||
records(record(manifest.admin).sections) &&
|
||
(record(manifest.admin).sections as Record<string, unknown>[]).every(
|
||
(section) => strings(section, ["key", "target"]) && fields(section.fields),
|
||
) &&
|
||
(manifest.templateFields === undefined ||
|
||
(records(manifest.templateFields) &&
|
||
manifest.templateFields.every((field) => strings(field, ["key"])))) &&
|
||
(manifest.trustContentTypes === undefined ||
|
||
(records(manifest.trustContentTypes) &&
|
||
manifest.trustContentTypes.every((declaration) => strings(declaration, ["type"]))))
|
||
);
|
||
}
|
||
|
||
@Injectable()
|
||
export class AdminTemplatePreviewService {
|
||
constructor(
|
||
private readonly prisma: PrismaService,
|
||
private readonly assets: AdminTemplatePreviewAssetsService,
|
||
) {}
|
||
async preview(id: string, industry: string, actorId: string, requestId?: string) {
|
||
const version = await this.prisma.templatePackageVersion.findUnique({ where: { id } });
|
||
if (!version) throw new BadRequestException("模板版本不存在");
|
||
if (version.status === "retired") throw new ConflictException("已撤回的模板版本不能创建新预览");
|
||
if (version.status !== "imported" && version.status !== "published")
|
||
throw new ConflictException(`模板版本当前状态为 ${version.status},不能预览`);
|
||
|
||
const rawManifest = record(version.manifestSnapshot);
|
||
const packageKey = version.packageKey;
|
||
const visualTemplateKey =
|
||
typeof rawManifest.visualTemplateKey === "string"
|
||
? rawManifest.visualTemplateKey
|
||
: packageKey;
|
||
const manifest = {
|
||
...rawManifest,
|
||
visualTemplateKey,
|
||
} as unknown as TemplatePackageManifest;
|
||
try {
|
||
if (validateTemplatePackageManifest(manifest).length || !hasPreviewStructure(rawManifest)) {
|
||
throw new Error("Invalid manifest");
|
||
}
|
||
} catch {
|
||
throw new BadRequestException("模板版本的 manifest 不符合预览契约");
|
||
}
|
||
if (manifest.packageKey !== packageKey || manifest.version !== version.version)
|
||
throw new BadRequestException("模板版本与 manifest 元数据不一致");
|
||
const industryTemplate = getBrandTemplate(industry);
|
||
const blockers: string[] = [];
|
||
if (!industryTemplate) blockers.push(`行业模板 ${industry} 不存在`);
|
||
if (
|
||
!Array.isArray(rawManifest.supportedIndustryTemplates) ||
|
||
!rawManifest.supportedIndustryTemplates.includes(industry)
|
||
) {
|
||
blockers.push("该模板版本不支持所选行业");
|
||
}
|
||
if (rawManifest.runtimeContract !== "1.0")
|
||
blockers.push("Runtime contract 不受当前预览运行时支持");
|
||
|
||
const trustedManifest = getTemplatePackageManifest(packageKey);
|
||
if (
|
||
!trustedManifest ||
|
||
trustedManifest.version !== version.version ||
|
||
trustedManifest.visualTemplateKey !== visualTemplateKey
|
||
) {
|
||
blockers.push("模板声明的 renderer 尚未部署到当前平台");
|
||
}
|
||
const requiredCapabilities = array(rawManifest.requiredCapabilities).filter(
|
||
(key): key is keyof typeof capabilityRegistry =>
|
||
typeof key === "string" && Object.hasOwn(capabilityRegistry, key),
|
||
);
|
||
if (requiredCapabilities.length !== array(rawManifest.requiredCapabilities).length)
|
||
blockers.push("模板依赖了当前平台未注册的 capability");
|
||
if (
|
||
industryTemplate &&
|
||
requiredCapabilities.some((key) => !industryTemplate.capabilities.includes(key))
|
||
) {
|
||
blockers.push("模板依赖的 capability 与所选行业不兼容");
|
||
}
|
||
if (blockers.length) throw new BadRequestException(`模板预览被阻断:${blockers.join(";")}`);
|
||
|
||
const fixtureDeclared = rawManifest.previewFixture !== undefined;
|
||
const fixture = record(rawManifest.previewFixture)[industry] as
|
||
TemplatePreviewFixture | undefined;
|
||
if (fixtureDeclared) {
|
||
const issues = validateTemplatePreviewFixture(fixture);
|
||
if (issues.length)
|
||
throw new BadRequestException(
|
||
`模板 previewFixture 不符合预览契约:${issues.map((issue) => `${issue.path}: ${issue.message}`).join(";")}`,
|
||
);
|
||
}
|
||
// 一旦包声明独立 fixture,缺失或无效时禁止偷偷回退到 bootstrap sample。
|
||
const sample = fixtureDeclared
|
||
? fixture!.content
|
||
: (record(rawManifest.sampleContent)[industry] as TemplateSampleContent | undefined);
|
||
const missingSampleSlots = this.missingSampleSlots(manifest, sample);
|
||
if (missingSampleSlots.length)
|
||
blockers.push(`preview sample 缺少必需数据:${missingSampleSlots.join("、")}`);
|
||
if (sample?.templateKey !== industry) blockers.push("sample 所属行业与所选行业不一致");
|
||
if (sample && !industryTemplate!.capabilities.some((key) => key === sample.capabilityKey))
|
||
blockers.push("preview sample 的咨询 capability 与所选行业不兼容");
|
||
if (!Array.isArray(sample?.fields) || validateFieldSnapshot(sample.fields).length)
|
||
blockers.push("sample 咨询字段不符合表单契约");
|
||
if (
|
||
!Array.isArray(sample?.offerings) ||
|
||
sample.offerings.some(
|
||
(item) =>
|
||
!item ||
|
||
typeof item.name !== "string" ||
|
||
!item.name.trim() ||
|
||
!["service", "product", "package", "subscription"].includes(item.kind) ||
|
||
typeof item.summary !== "string" ||
|
||
typeof item.categoryKey !== "string",
|
||
)
|
||
)
|
||
blockers.push("sample 业务记录不完整");
|
||
if (
|
||
!Array.isArray(sample?.trustContent) ||
|
||
sample.trustContent.some(
|
||
(item) =>
|
||
!item ||
|
||
typeof item.title !== "string" ||
|
||
typeof item.content !== "string" ||
|
||
!manifest.trustContentTypes?.some((declaration) => declaration.type === item.type),
|
||
)
|
||
)
|
||
blockers.push("sample 信任记录不符合模板声明");
|
||
for (const declaration of manifest.trustContentTypes ?? []) {
|
||
if (
|
||
declaration.required &&
|
||
!array(sample?.trustContent).some((item) => record(item).type === declaration.type)
|
||
)
|
||
blockers.push(`preview sample 缺少必需信任内容:${declaration.type}`);
|
||
}
|
||
if (blockers.length) {
|
||
throw new BadRequestException(`模板预览被阻断:${blockers.join(";")}`);
|
||
}
|
||
|
||
const resources = await this.assets.read(version);
|
||
const workspace = this.buildSampleWorkspace(
|
||
version.id,
|
||
manifest,
|
||
industryTemplate!,
|
||
sample!,
|
||
fixture?.brand,
|
||
);
|
||
await this.prisma.templatePackageAuditLog.create({
|
||
data: {
|
||
templatePackageVersionId: version.id,
|
||
actorId,
|
||
action: "previewed",
|
||
...(requestId ? { requestId } : {}),
|
||
metadata: {
|
||
industry,
|
||
contentChecksum: version.contentChecksum,
|
||
fixtureSource: fixtureDeclared ? "previewFixture" : "legacy-sampleContent",
|
||
},
|
||
},
|
||
});
|
||
return {
|
||
template: {
|
||
id: version.id,
|
||
packageKey,
|
||
version: version.version,
|
||
displayName: version.displayName,
|
||
status: version.status,
|
||
contentChecksum: version.contentChecksum,
|
||
visualTemplateKey,
|
||
navigation: manifest.navigation.map(
|
||
(tab: TemplatePackageManifest["navigation"][number]) => ({
|
||
key: tab.key,
|
||
label: tab.label,
|
||
page: tab.page,
|
||
}),
|
||
),
|
||
pages: Object.keys(manifest.entrypoints),
|
||
},
|
||
industry: {
|
||
key: industryTemplate!.key,
|
||
version: industryTemplate!.version,
|
||
name: industryTemplate!.name,
|
||
},
|
||
compatibility: {
|
||
runtimeContract: manifest.runtimeContract,
|
||
renderer: { key: visualTemplateKey, version: version.version, trusted: true },
|
||
requiredCapabilities,
|
||
missingSampleSlots: [],
|
||
},
|
||
preview: {
|
||
assetFiles: resources.files,
|
||
fixtureSource: fixtureDeclared
|
||
? ("previewFixture" as const)
|
||
: ("legacy-sampleContent" as const),
|
||
safety: {
|
||
submissions: "disabled" as const,
|
||
customerRecords: "disabled" as const,
|
||
contactActions: "disabled" as const,
|
||
},
|
||
diagnostics: [
|
||
...resources.diagnostics,
|
||
...(fixtureDeclared
|
||
? []
|
||
: [
|
||
{
|
||
code: "LEGACY_PREVIEW_SAMPLE",
|
||
severity: "warning" as const,
|
||
message: "该版本尚未提供独立预览数据,当前兼容使用品牌起始内容。",
|
||
},
|
||
]),
|
||
],
|
||
pages: Object.keys(manifest.entrypoints).map((page) => ({
|
||
key: page,
|
||
modules: manifest.admin.sections
|
||
.filter((section) => section.page === page)
|
||
.map((section) => ({
|
||
key: section.key,
|
||
title: section.title,
|
||
bindings: section.fields.map((field) => field.binding),
|
||
})),
|
||
})),
|
||
assets: manifest.assetSlots.map((slot) => {
|
||
const resolve = (source: Record<string, unknown>, path: string[]) =>
|
||
path.reduce<unknown>((value, key) => record(value)[key], source);
|
||
const sources =
|
||
slot.target === "brand"
|
||
? [record(workspace.brand)]
|
||
: slot.target === "offering"
|
||
? sample!.offerings
|
||
: sample!.trustContent;
|
||
const path = slot.binding.split(".").slice(1);
|
||
const values = sources.map((source) => resolve(record(source), path));
|
||
const populated = values.filter(
|
||
(value) => typeof value === "string" && value.trim().length > 0,
|
||
).length;
|
||
const verified = values.filter(
|
||
(value) => typeof value === "string" && Object.hasOwn(resources.files, value),
|
||
).length;
|
||
return {
|
||
key: slot.key,
|
||
label: slot.label,
|
||
binding: slot.binding,
|
||
required: slot.required,
|
||
populated,
|
||
total: sources.length,
|
||
status:
|
||
populated !== sources.length ||
|
||
!sources.length ||
|
||
values.some(
|
||
(value) =>
|
||
typeof value === "string" &&
|
||
value.startsWith("/assets/") &&
|
||
!Object.hasOwn(resources.files, value),
|
||
)
|
||
? ("missing" as const)
|
||
: verified === sources.length
|
||
? ("ready" as const)
|
||
: ("unverified" as const),
|
||
};
|
||
}),
|
||
},
|
||
workspace,
|
||
};
|
||
}
|
||
|
||
private missingSampleSlots(
|
||
manifest: TemplatePackageManifest,
|
||
sample: TemplateSampleContent | undefined,
|
||
): string[] {
|
||
if (!sample) return ["preview sample"];
|
||
const offerings = Array.isArray(sample.offerings) ? sample.offerings : [];
|
||
const trustContent = Array.isArray(sample.trustContent) ? sample.trustContent : [];
|
||
const fields = Array.isArray(sample.fields) ? sample.fields : [];
|
||
const missing: string[] = [];
|
||
for (const slot of manifest.dataSlots.filter((item) => item.required)) {
|
||
const count =
|
||
slot.source === "offering"
|
||
? offerings.length
|
||
: slot.source === "trust"
|
||
? trustContent.length
|
||
: slot.source === "inquiry"
|
||
? fields.length
|
||
: slot.source === "brand"
|
||
? 1
|
||
: slot.source === "records"
|
||
? 1
|
||
: 0;
|
||
if (!count) missing.push(slot.key);
|
||
}
|
||
if (typeof sample.inquiryFormName !== "string" || !sample.inquiryFormName.trim())
|
||
missing.push("inquiry.form.name");
|
||
if (!sample.capabilityKey || !Object.hasOwn(capabilityRegistry, sample.capabilityKey))
|
||
missing.push("capability");
|
||
return missing;
|
||
}
|
||
|
||
private buildSampleWorkspace(
|
||
versionId: string,
|
||
manifest: TemplatePackageManifest,
|
||
industryTemplate: NonNullable<ReturnType<typeof getBrandTemplate>>,
|
||
sample: TemplateSampleContent,
|
||
identity?: TemplatePreviewFixture["brand"],
|
||
) {
|
||
const brandConfig = record(sample.brandConfig);
|
||
const visualTemplateKey = manifest.visualTemplateKey;
|
||
const brand = {
|
||
id: `template-preview:${versionId}`,
|
||
slug: `template-preview-${manifest.packageKey}`,
|
||
name: identity?.name ?? `${manifest.displayName}示例品牌`,
|
||
templateKey: industryTemplate.key,
|
||
tagline: identity?.tagline ?? `${industryTemplate.name}模板示例`,
|
||
description: identity?.description ?? "这是模板预览数据,不属于任何真实品牌。",
|
||
avatarUrl: identity?.avatarUrl ?? null,
|
||
coverUrl: identity?.coverUrl ?? null,
|
||
hours: identity?.hours ?? "示例营业时间",
|
||
address: identity?.address ?? "示例服务范围",
|
||
deliveryNote: identity?.deliveryNote ?? "预览模式不会提交咨询或创建客户记录。",
|
||
contactPhone: null,
|
||
contactWechat: null,
|
||
config: { ...brandConfig, visualTemplateKey },
|
||
};
|
||
const snapshot: BrandReleaseSnapshot = {
|
||
schemaVersion: "1.0.0",
|
||
generatedAt: new Date(0).toISOString(),
|
||
templateKey: industryTemplate.key,
|
||
templateDefinition: industryTemplate,
|
||
visualTemplateDefinition: getVisualTemplate(visualTemplateKey) ?? null,
|
||
visualTemplateManifest: getVisualTemplateManifest(visualTemplateKey) ?? null,
|
||
templatePackageManifest: manifest,
|
||
brand,
|
||
installation: {
|
||
templateKey: industryTemplate.key,
|
||
templateVersion: industryTemplate.version,
|
||
},
|
||
fields: [],
|
||
offerings: sample.offerings.map((item, sortOrder) => ({
|
||
id: `template-preview:${versionId}:offering:${sortOrder + 1}`,
|
||
...item,
|
||
isEnabled: true,
|
||
sortOrder,
|
||
config: { ...record(item.config), categoryKey: item.categoryKey },
|
||
})),
|
||
forms: [
|
||
{
|
||
id: `template-preview:${versionId}:inquiry`,
|
||
name: sample.inquiryFormName,
|
||
isEnabled: true,
|
||
purpose: sample.capabilityKey === "booking" ? "booking" : "inquiry",
|
||
targetType: "brand",
|
||
offeringId: null,
|
||
submissionAction: "create-inquiry",
|
||
fieldsSnapshot: sample.fields,
|
||
},
|
||
],
|
||
trustContents: sample.trustContent.map((item, sortOrder) => ({
|
||
id: `template-preview:${versionId}:trust:${sortOrder + 1}`,
|
||
...item,
|
||
isPublished: true,
|
||
sortOrder,
|
||
})),
|
||
capabilities: array(manifest.requiredCapabilities).map((key) => ({
|
||
capabilityKey: key,
|
||
capabilityVersion:
|
||
typeof capabilityRegistry[key as keyof typeof capabilityRegistry]?.version === "string"
|
||
? capabilityRegistry[key as keyof typeof capabilityRegistry].version
|
||
: "1.0.0",
|
||
status: "enabled",
|
||
config: {},
|
||
})),
|
||
};
|
||
return assemblePublicWorkspace({ release: null, snapshot, draftSnapshot: snapshot });
|
||
}
|
||
}
|