refactor: 统一模板契约并修复预览版本

This commit is contained in:
que01 committed 2026-10-18 17:09:09 +08:00
1 parent cd2992c00a
commit 50b87e48de
56 files changed
+7849 -5756

No files matched your search

@@ -1,23 +1,11 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import {
defaultVisualTemplateKey,
getBrandTemplate,
getDefaultVisualTemplateKey,
getVisualTemplate,
isVisualTemplateCompatible,
listVisualTemplateKeys,
} from "@personal-brand/config";
import { PrismaService } from "../../prisma.service.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import type { UpdateBrandDto, UpdateBrandPresentationDto } from "../../admin.dto.js";
@Injectable()
export class AdminBrandConfigService {
constructor(
private readonly prisma: PrismaService,
private readonly templateWorkspace: TemplateWorkspaceService,
) {}
constructor(private readonly prisma: PrismaService) {}
getBrand(brandId: string) {
return this.prisma.brandProfile.findUnique({ where: { id: brandId } });
@@ -27,56 +15,28 @@ export class AdminBrandConfigService {
const { config, ...fields } = body;
const current = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { config: true },
select: { config: true, templateKey: true },
});
if (!current) throw new BadRequestException("品牌不存在");
const currentConfig = this.jsonObject(current?.config);
if (config && Object.hasOwn(config, "visualTemplateKey"))
throw new BadRequestException("模板选择必须通过精确模板包版本操作");
const configFields = config ?? {};
const nextConfig = {
...currentConfig,
...(config ?? {}),
...(fields.description !== undefined && config?.slogan === undefined
...configFields,
...(fields.description !== undefined && configFields.slogan === undefined
? { slogan: fields.description }
: {}),
};
if (config?.visualTemplateKey && config.visualTemplateKey !== currentConfig.visualTemplateKey) {
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
const visualTemplate =
typeof config.visualTemplateKey === "string"
? getVisualTemplate(config.visualTemplateKey)
: undefined;
if (
!visualTemplate ||
!getBrandTemplate(templateKey) ||
!isVisualTemplateCompatible(visualTemplate, templateKey)
)
throw new BadRequestException("当前视觉模板不适配该行业模板");
const installation = await this.prisma.brandTemplateInstallation.findFirst({
where: { brandId },
return this.prisma.$transaction(async (tx) => {
return tx.brandProfile.update({
where: { id: brandId },
data: {
...fields,
...(Object.keys(nextConfig).length ? { config: nextConfig } : {}),
},
});
if (installation) {
const history = Array.isArray(installation.previousSnapshots)
? installation.previousSnapshots
: [];
await this.prisma.brandTemplateInstallation.update({
where: { id: installation.id },
data: {
previousSnapshots: [
...history,
{
visualTemplateKey:
currentConfig.visualTemplateKey ?? getDefaultVisualTemplateKey(templateKey),
savedAt: new Date().toISOString(),
},
],
},
});
}
}
return this.prisma.brandProfile.update({
where: { id: brandId },
data: {
...fields,
...(Object.keys(nextConfig).length ? { config: nextConfig } : {}),
},
});
}
@@ -130,91 +90,6 @@ export class AdminBrandConfigService {
};
}
async visualTemplateHistory(brandId: string) {
const installation = await this.prisma.brandTemplateInstallation.findFirst({
where: { brandId },
select: { previousSnapshots: true },
});
return {
history: Array.isArray(installation?.previousSnapshots)
? installation.previousSnapshots.filter(
(item) =>
item &&
typeof item === "object" &&
!Array.isArray(item) &&
"visualTemplateKey" in item,
)
: [],
};
}
async rollbackVisualTemplate(brandId: string) {
const [brand, installation] = await Promise.all([
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
]);
const config = this.jsonObject(brand?.config);
const history = Array.isArray(installation?.previousSnapshots)
? installation.previousSnapshots
: [];
const index = [...history]
.map((item, i) => ({ item, i }))
.reverse()
.find(
({ item }) =>
item && typeof item === "object" && !Array.isArray(item) && "visualTemplateKey" in item,
)?.i;
const previous =
index === undefined ? undefined : (history[index] as { visualTemplateKey?: unknown });
if (!previous || typeof previous.visualTemplateKey !== "string")
throw new BadRequestException("没有可回滚的视觉模板版本");
await this.prisma.$transaction([
this.prisma.brandProfile.update({
where: { id: brandId },
data: {
config: {
...config,
visualTemplateKey: previous.visualTemplateKey,
},
},
}),
...(installation
? [
this.prisma.brandTemplateInstallation.update({
where: { id: installation.id },
data: { previousSnapshots: history.slice(0, index) },
}),
]
: []),
]);
return { visualTemplateKey: previous.visualTemplateKey, rolledBack: true };
}
async visualTemplatePreview(brandId: string) {
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { config: true },
});
const config = this.jsonObject(brand?.config);
const currentKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: defaultVisualTemplateKey;
const current = getVisualTemplate(currentKey);
return {
current: current
? {
key: current.key,
version: current.version,
name: current.name,
theme: current.theme,
variants: current.variants,
}
: null,
available: listVisualTemplateKeys(),
};
}
private jsonObject(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
@@ -60,10 +60,6 @@ export class AdminConfigController {
@Body() body: UpdateBrandDto,
): Promise<unknown> {
this.requireAdmin(request);
const { config } = body;
if (config?.visualTemplateKey !== undefined) {
await this.access.requireRole(request, ["owner", "admin", "platform-admin"]);
}
return this.brandConfig.updateBrand(this.brandId(request), body);
}
@Patch("presentation")
@@ -75,21 +71,6 @@ export class AdminConfigController {
const brandId = this.brandId(request);
return this.brandConfig.updatePresentation(brandId, body);
}
@Get("visual-template/history")
getVisualTemplateHistory(@Req() request: FastifyRequest): unknown {
this.requireAdmin(request);
return this.brandConfig.visualTemplateHistory(this.brandId(request));
}
@Post("visual-template/rollback")
async rollbackVisualTemplate(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
return this.brandConfig.rollbackVisualTemplate(this.brandId(request));
}
@Get("visual-template/preview")
getVisualTemplatePreview(@Req() request: FastifyRequest): unknown {
this.requireAdmin(request);
return this.brandConfig.visualTemplatePreview(this.brandId(request));
}
@Get("trust-content")
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
this.requireAdmin(request);
@@ -26,9 +26,9 @@ type Manifest = {
packageKey: string;
version: string;
displayName: string;
visualTemplateKey?: string;
supportedIndustryTemplates?: string[];
previewFixture?: Prisma.InputJsonValue;
visualTemplateKey: string;
supportedIndustryTemplates: string[];
previewFixture: Prisma.InputJsonValue;
};
type ChecksumFile = {
@@ -146,7 +146,6 @@ export class AdminTemplatePackageService {
packageKey: true,
version: true,
displayName: true,
visualTemplateKey: true,
status: true,
contentChecksum: true,
archiveChecksum: true,
@@ -302,7 +301,6 @@ export class AdminTemplatePackageService {
packageKey,
version: manifest.version,
displayName: manifest.displayName,
visualTemplateKey: manifest.visualTemplateKey ?? null,
manifestSnapshot: manifest,
validationReport: {
formatVersion: "1",
@@ -495,7 +493,6 @@ export class AdminTemplatePackageService {
packageKey: string;
version: string;
displayName: string;
visualTemplateKey: string | null;
status: string;
contentChecksum: string;
archiveChecksum: string;
@@ -506,7 +503,6 @@ export class AdminTemplatePackageService {
packageKey: version.packageKey,
version: version.version,
displayName: version.displayName,
visualTemplateKey: version.visualTemplateKey,
status: version.status,
contentChecksum: version.contentChecksum,
archiveChecksum: version.archiveChecksum,
@@ -184,22 +184,25 @@ export class AdminTemplatePreviewService {
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;
const visualTemplateKey = rawManifest.visualTemplateKey as string;
const manifest = rawManifest as unknown as TemplatePackageManifest;
let manifestIssues: string[];
try {
if (validateTemplatePackageManifest(manifest).length || !hasPreviewStructure(rawManifest)) {
throw new Error("Invalid manifest");
}
manifestIssues = validateTemplatePackageManifest(manifest);
} catch {
throw new BadRequestException("模板版本的 manifest 不符合预览契约");
}
if (manifest.packageKey !== packageKey || manifest.version !== version.version)
if (manifestIssues.length)
throw new BadRequestException(
`模板版本的 manifest 不符合预览契约:${manifestIssues.join(";")}`,
);
if (!hasPreviewStructure(rawManifest))
throw new BadRequestException("模板版本的 manifest 不符合预览契约");
if (
manifest.packageKey !== packageKey ||
manifest.version !== version.version ||
manifest.packageKey !== manifest.visualTemplateKey
)
throw new BadRequestException("模板版本与 manifest 元数据不一致");
const industryTemplate = getBrandTemplate(industry);
const blockers: string[] = [];
@@ -235,20 +238,14 @@ export class AdminTemplatePreviewService {
}
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 fixtureIssues = validateTemplatePreviewFixture(fixture);
if (fixtureIssues.length)
throw new BadRequestException(
`模板 previewFixture 不符合预览契约:${fixtureIssues.map((issue) => `${issue.path}: ${issue.message}`).join(";")}`,
);
const sample = fixture!.content as TemplateSampleContent;
const missingSampleSlots = this.missingSampleSlots(manifest, sample);
if (missingSampleSlots.length)
blockers.push(`preview sample 缺少必需数据:${missingSampleSlots.join("、")}`);
@@ -331,26 +328,13 @@ export class AdminTemplatePreviewService {
},
preview: {
assetFiles: resources.files,
fixtureSource: fixtureDeclared
? ("previewFixture" as const)
: ("legacy-sampleContent" as const),
fixtureSource: "previewFixture" 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: "该版本尚未提供独立预览数据,当前兼容使用品牌起始内容。",
},
]),
],
diagnostics: resources.diagnostics,
pages: Object.keys(manifest.entrypoints).map((page) => ({
key: page,
modules: manifest.admin.sections
@@ -463,7 +447,7 @@ export class AdminTemplatePreviewService {
deliveryNote: identity?.deliveryNote ?? "预览模式不会提交咨询或创建客户记录。",
contactPhone: null,
contactWechat: null,
config: { ...brandConfig, visualTemplateKey },
config: brandConfig,
};
const snapshot: BrandReleaseSnapshot = {
schemaVersion: "1.0.0",
@@ -477,6 +461,7 @@ export class AdminTemplatePreviewService {
installation: {
templateKey: industryTemplate.key,
templateVersion: industryTemplate.version,
visualTemplateKey,
},
fields: [],
offerings: sample.offerings.map((item, sortOrder) => ({
@@ -3,13 +3,7 @@ import type { Prisma } from "@prisma/client";
import {
capabilityMetadata,
capabilityPlugins,
defaultBrandTemplateKey,
type BrandTemplateKey,
getBrandTemplate,
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
getVisualTemplate,
getVisualTemplateManifest,
resolveCapabilities,
} from "@personal-brand/config";
import type { RuntimeTrustItem, RuntimeWorkspace } from "@personal-brand/types";
@@ -94,12 +88,8 @@ export function assemblePublicWorkspace(input: {
(item) => asRecord(item).isPublished === true,
) as Array<Record<string, unknown>>;
const installationData = asRecord(releaseSnapshot.installation);
const templateKey =
asString(brandData.templateKey) ||
asString(releaseSnapshot.templateKey) ||
asString(installationData.templateKey) ||
defaultBrandTemplateKey;
const template = releaseSnapshot.templateDefinition ?? getBrandTemplate(templateKey);
const templateKey = asString(releaseSnapshot.templateKey);
const template = releaseSnapshot.templateDefinition;
const capabilityData = asArray(releaseSnapshot.capabilities) as Array<Record<string, unknown>>;
const capabilityRecord = (item: Record<string, unknown>, fallbackVersion = "1.0.0") => {
const key = asString(item.capabilityKey) || asString(item.key);
@@ -120,15 +110,19 @@ export function assemblePublicWorkspace(input: {
)
: [];
const brandConfig = asRecord(brandData.config);
const visualTemplateKey =
asString(brandConfig.visualTemplateKey) || getDefaultVisualTemplateKey(templateKey);
const visualTemplate =
releaseSnapshot.visualTemplateDefinition ?? getVisualTemplate(visualTemplateKey);
const visualTemplateManifest =
releaseSnapshot.visualTemplateManifest ?? getVisualTemplateManifest(visualTemplateKey);
const templatePackageManifest =
releaseSnapshot.templatePackageManifest ??
getTemplatePackageManifestForVisualKey(visualTemplateKey);
const visualTemplate = releaseSnapshot.visualTemplateDefinition;
const visualTemplateManifest = releaseSnapshot.visualTemplateManifest;
const templatePackageManifest = releaseSnapshot.templatePackageManifest;
const visualTemplateKey = asString(templatePackageManifest?.visualTemplateKey);
if (
!templateKey ||
!visualTemplateKey ||
!templatePackageManifest ||
!template ||
!visualTemplate ||
!visualTemplateManifest
)
throw new Error("发布快照缺少统一模板契约字段");
const categoryOptions = new Map(
(templatePackageManifest?.admin.sections ?? [])
.filter((section) => section.target === "offering")
@@ -192,10 +186,8 @@ export function assemblePublicWorkspace(input: {
status: "enabled" as const,
config: capabilities.find((capability) => capability.key === plugin.key)?.config ?? {},
})),
theme: visualTemplate?.theme ?? {
colors: { background: "#F7F5F1", foreground: "#252525", accent: "#8A6846" },
},
...(visualTemplate?.layout ? { layout: visualTemplate.layout } : {}),
theme: visualTemplate.theme,
...(visualTemplate.layout ? { layout: visualTemplate.layout } : {}),
};
return {
...runtimeWorkspace,
@@ -2,8 +2,6 @@ import { BadRequestException, Controller, Get, Param, Query } from "@nestjs/comm
import { PublicBrandContextService } from "./public-brand-context.service.js";
import { BrandReleaseService } from "../../brand-release.service.js";
import {
defaultBrandTemplateKey,
defaultVisualTemplateKey,
brandTemplateKeys,
getBrandTemplate,
getVisualTemplate,
@@ -82,10 +80,7 @@ export class PublicTemplateController {
}
@Get("preview")
preview(
@Query("industry") industry = defaultBrandTemplateKey,
@Query("visual") visual = defaultVisualTemplateKey,
): unknown {
preview(@Query("industry") industry: string, @Query("visual") visual: string): unknown {
const industryTemplate = getBrandTemplate(industry);
const visualTemplate = getVisualTemplate(visual);
if (!industryTemplate || !visualTemplate) throw new BadRequestException("模板组合不存在");
@@ -1,9 +1,6 @@
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
import { Prisma, type TemplatePackageVersion } from "@prisma/client";
import {
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
getTemplateSampleContent,
getVisualTemplate,
isVisualTemplateCompatible,
validateTemplatePackageManifest,
@@ -15,10 +12,10 @@ import { PrismaService } from "../../prisma.service.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
type BootstrapSource = {
kind: "package_version" | "registry";
kind: "package_version";
manifest: TemplatePackageManifest;
sample: TemplateSampleContent;
version?: TemplatePackageVersion;
version: TemplatePackageVersion;
};
type Counts = {
@@ -111,8 +108,6 @@ export class AdminSampleContentService {
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: {
@@ -263,50 +258,35 @@ export class AdminSampleContentService {
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({
: await this.prisma.brandTemplateInstallation.findUnique({
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 };
}
if (!versionId) throw new BadRequestException("品牌没有精确模板包安装版本,必须先完成模板安装");
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 ||
manifest.packageKey !== manifest.visualTemplateKey ||
!/^[a-f0-9]{64}$/.test(version.contentChecksum) ||
!manifest.supportedIndustryTemplates.includes(brand.templateKey)
)
throw new BadRequestException("模板包版本与品牌行业或版本台账不匹配");
const sample = manifest.sampleContent?.[brand.templateKey];
if (!sample) throw new BadRequestException("该模板包没有当前行业的 bootstrap sampleContent");
const source: BootstrapSource = { kind: "package_version", version, manifest, sample };
const visualTemplateKey = manifest.visualTemplateKey;
const visual = getVisualTemplate(visualTemplateKey);
if (!visual || !isVisualTemplateCompatible(visual, brand.templateKey))
throw new BadRequestException("当前视觉模板与品牌行业不兼容");
@@ -417,8 +397,8 @@ export class AdminSampleContentService {
kind: source.kind,
packageKey: source.manifest.packageKey,
version: source.manifest.version,
contentChecksum: source.version?.contentChecksum ?? null,
...(source.version ? { templatePackageVersionId: source.version.id } : {}),
contentChecksum: source.version.contentChecksum,
templatePackageVersionId: source.version.id,
};
}
}
@@ -1,6 +1,6 @@
import { Controller, Get, Post, Body, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { InstallTemplateDto } from "../../admin.dto.js";
import { InstallTemplateDto, SelectTemplateVersionDto } from "../../admin.dto.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { requireAdminIdentity } from "./admin-access.identity.js";
import { AdminWorkspaceService } from "./admin-workspace.service.js";
@@ -52,6 +52,21 @@ class AdminWorkspacePreviewController {
throw error;
}
}
@Post("template/select-version")
async selectVersion(
@Req() request: FastifyRequest,
@Body() body: SelectTemplateVersionDto,
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
return this.templateWorkspace.selectVersion(
identity.brandId,
body,
identity.subject,
requestId,
);
}
}
export { AdminWorkspacePreviewController };
@@ -1,10 +1,5 @@
import { Injectable } from "@nestjs/common";
import { BadRequestException, Injectable } from "@nestjs/common";
import { PrismaService } from "../../prisma.service.js";
import {
defaultBrandTemplateKey,
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
} from "@personal-brand/config";
import { PublicWorkspaceService } from "../public/public-workspace.service.js";
@Injectable()
@@ -15,11 +10,11 @@ export class AdminWorkspaceService {
) {}
async get(brandId: string): Promise<unknown> {
const [brand, installations, fields, offerings, forms] = await Promise.all([
const [brand, installation, fields, offerings, forms] = await Promise.all([
this.prisma.brandProfile.findUnique({ where: { id: brandId } }),
this.prisma.brandTemplateInstallation.findMany({
this.prisma.brandTemplateInstallation.findUnique({
where: { brandId },
orderBy: { updatedAt: "desc" },
include: { templatePackageVersion: true },
}),
this.prisma.brandFieldDefinition.findMany({
where: { brandId },
@@ -28,36 +23,50 @@ export class AdminWorkspaceService {
this.prisma.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
this.prisma.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" } }),
]);
const config = this.jsonObject(brand?.config);
const templateKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: getDefaultVisualTemplateKey(brand?.templateKey ?? defaultBrandTemplateKey);
const manifest = getTemplatePackageManifestForVisualKey(templateKey);
if (!installation?.templatePackageVersion)
throw new BadRequestException("品牌没有锁定精确视觉模板包版本");
const manifest = installation.templatePackageVersion.manifestSnapshot as {
visualTemplateKey: string;
displayName: string;
admin: unknown;
navigation: Array<{ key: string; label: string; page: string }>;
templateFields?: Array<Record<string, unknown> & { key: string; binding?: string }>;
assetSlots: unknown[];
trustContentTypes?: unknown[];
};
return {
brand,
installations,
installations: [
{
...installation,
visualTemplateKey: manifest.visualTemplateKey,
},
],
fields,
offerings,
forms,
templateContent: manifest
? {
displayName: manifest.displayName,
admin: manifest.admin,
navigation: manifest.navigation.map(({ key, label, page }) => ({ key, label, page })),
templateFields: (manifest.templateFields ?? []).map((field) => ({
...field,
binding: field.binding ?? `brand.config.templateData.${field.key}`,
})),
assetSlots: manifest.assetSlots,
trustContentTypes: manifest.trustContentTypes ?? [],
}
: null,
templateContent: {
displayName: manifest.displayName,
admin: manifest.admin,
navigation: manifest.navigation.map(({ key, label, page }) => ({ key, label, page })),
templateFields: (manifest.templateFields ?? []).map((field) => ({
...field,
binding: field.binding ?? `brand.config.templateData.${field.key}`,
})),
assetSlots: manifest.assetSlots,
trustContentTypes: manifest.trustContentTypes ?? [],
},
};
}
getPreview(brandId: string): Promise<unknown> {
async getPreview(brandId: string): Promise<unknown> {
const installation = await this.prisma.brandTemplateInstallation.findUnique({
where: { brandId },
select: { templatePackageVersionId: true },
});
if (!installation?.templatePackageVersionId)
throw new BadRequestException("品牌没有锁定精确模板包版本");
return this.publicWorkspace.getForBrandId(brandId, true);
}