feat: 增加模板版本独立预览入口
This commit is contained in:
1 parent
413413efda
commit
6edde5a8d6
15 files changed
+781
-14
No files matched your search
@@ -0,0 +1,298 @@
|
||||
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
|
||||
import {
|
||||
capabilityRegistry,
|
||||
getBrandTemplate,
|
||||
getTemplatePackageManifest,
|
||||
getVisualTemplate,
|
||||
getVisualTemplateManifest,
|
||||
validateTemplatePackageManifest,
|
||||
} from "@personal-brand/config";
|
||||
import type { TemplatePackageManifest, TemplateSampleContent } from "@personal-brand/config";
|
||||
import { validateFieldSnapshot } 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";
|
||||
|
||||
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(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) {}
|
||||
async preview(id: string, industry: 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 与所选行业不兼容");
|
||||
}
|
||||
|
||||
const sample = 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 (!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 信任记录不符合模板声明");
|
||||
if (blockers.length) {
|
||||
throw new BadRequestException(`模板预览被阻断:${blockers.join(";")}`);
|
||||
}
|
||||
|
||||
const workspace = this.buildSampleWorkspace(version.id, manifest, industryTemplate!, sample!);
|
||||
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: [],
|
||||
},
|
||||
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,
|
||||
) {
|
||||
const brandConfig = record(sample.brandConfig);
|
||||
const visualTemplateKey = manifest.visualTemplateKey;
|
||||
const brand = {
|
||||
id: `template-preview:${versionId}`,
|
||||
slug: `template-preview-${manifest.packageKey}`,
|
||||
name: `${manifest.displayName}示例品牌`,
|
||||
templateKey: industryTemplate.key,
|
||||
tagline: `${industryTemplate.name}模板示例`,
|
||||
description: "这是模板预览数据,不属于任何真实品牌。",
|
||||
avatarUrl: null,
|
||||
coverUrl: null,
|
||||
hours: "示例营业时间",
|
||||
address: "示例服务范围",
|
||||
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 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user