feat: 增加模板版本独立预览入口

This commit is contained in:
que01 committed 2026-10-16 17:28:07 +08:00
1 parent 413413efda
commit 6edde5a8d6
15 files changed
+781 -14

No files matched your search

@@ -1,14 +1,20 @@
import { Controller, Get, Param, Post, Query, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { AdminAccessService } from "../../admin-access.service.js";
import { ListTemplatePackagesQueryDto } from "./admin-template-package.dto.js";
import {
ListTemplatePackagesQueryDto,
PreviewTemplatePackageQueryDto,
} from "./admin-template-package.dto.js";
import { AdminTemplatePackageService } from "./admin-template-package.service.js";
import { AdminTemplatePreviewService } from "./admin-template-preview.service.js";
@Controller("admin/templates")
export class AdminTemplatePackageController {
constructor(
private readonly access: AdminAccessService,
private readonly templates: AdminTemplatePackageService,
private readonly previews: AdminTemplatePreviewService,
) {}
@Get()
@@ -40,4 +46,12 @@ export class AdminTemplatePackageController {
audit(@Param("id") id: string): ReturnType<AdminTemplatePackageService["audit"]> {
return this.templates.audit(id);
}
@Get(":id/preview")
preview(
@Param("id") id: string,
@Query() query: PreviewTemplatePackageQueryDto,
): ReturnType<AdminTemplatePreviewService["preview"]> {
return this.previews.preview(id, query.industry);
}
}
@@ -1,5 +1,5 @@
import { Type } from "class-transformer";
import { IsInt, IsOptional, Max, Min } from "class-validator";
import { IsInt, IsNotEmpty, IsOptional, IsString, Max, Min } from "class-validator";
export class ListTemplatePackagesQueryDto {
@IsOptional()
@@ -15,3 +15,9 @@ export class ListTemplatePackagesQueryDto {
@Max(100)
pageSize = 20;
}
export class PreviewTemplatePackageQueryDto {
@IsString()
@IsNotEmpty()
industry!: string;
}
@@ -5,7 +5,6 @@ import {
PayloadTooLargeException,
} from "@nestjs/common";
import { validateTemplatePackageManifest } from "@personal-brand/config";
import { Prisma } from "@prisma/client";
import type { FastifyRequest } from "fastify";
import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
@@ -35,6 +34,16 @@ type ChecksumFile = {
files: Array<{ path: string; bytes: number; sha256: string }>;
};
type JsonRecord = Record<string, unknown>;
function record(value: unknown): JsonRecord {
return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};
}
function array(value: unknown): unknown[] {
return Array.isArray(value) ? value : [];
}
function sha256(value: Buffer | string): string {
return createHash("sha256").update(value).digest("hex");
}
@@ -137,6 +146,7 @@ export class AdminTemplatePackageService {
contentChecksum: true,
archiveChecksum: true,
validationReport: true,
manifestSnapshot: true,
importedAt: true,
updatedAt: true,
templatePackage: { select: { id: true } },
@@ -145,9 +155,21 @@ export class AdminTemplatePackageService {
}),
]);
return {
items: versions.map(({ templatePackage, ...version }) => ({
items: versions.map(({ templatePackage, manifestSnapshot, ...version }) => ({
...version,
templatePackageId: templatePackage.id,
manifestSummary: {
runtimeContract:
typeof record(manifestSnapshot).runtimeContract === "string"
? (record(manifestSnapshot).runtimeContract as string)
: "",
supportedIndustryTemplates: array(
record(manifestSnapshot).supportedIndustryTemplates,
).filter((item): item is string => typeof item === "string"),
requiredCapabilities: array(record(manifestSnapshot).requiredCapabilities).filter(
(item): item is string => typeof item === "string",
),
},
})),
page,
pageSize,
@@ -164,7 +186,7 @@ export class AdminTemplatePackageService {
let storedArtifactPath: string | null = null;
try {
for await (const chunk of part.file) {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
const buffer = Buffer.from(chunk as Uint8Array);
bytes += buffer.length;
if (bytes > MAX_ARCHIVE_BYTES) throw new PayloadTooLargeException("模板包超过 50 MB 限制");
chunks.push(buffer);
@@ -272,13 +294,13 @@ export class AdminTemplatePackageService {
version: manifest.version,
displayName: manifest.displayName,
visualTemplateKey: manifest.visualTemplateKey ?? null,
manifestSnapshot: manifest as unknown as Prisma.InputJsonValue,
manifestSnapshot: manifest,
validationReport: {
formatVersion: "1",
errors: [],
fileCount: files.length,
extractedBytes: files.reduce((total, file) => total + file.bytes, 0),
} as Prisma.InputJsonValue,
},
contentChecksum: checksums.contentChecksum,
archiveChecksum,
artifactPath,
@@ -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 });
}
}
@@ -16,6 +16,8 @@ import { AdminUploadController } from "./admin-upload.controller.js";
import { AdminTemplatePackageController } from "./admin-template-package.controller.js";
import { AdminTemplatePackageService } from "./admin-template-package.service.js";
import { AdminTemplatePreviewService } from "./admin-template-preview.service.js";
@Module({
imports: [InfrastructureModule, BookingModule],
controllers: [
@@ -35,6 +37,7 @@ import { AdminTemplatePackageService } from "./admin-template-package.service.js
AdminMiniAppUploadService,
AdminUploadService,
AdminTemplatePackageService,
AdminTemplatePreviewService,
],
})
export class AdminModule {}