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

+7 -1
View File
@@ -106,7 +106,13 @@ export class UpdateBookingTagsDto {
export class InstallTemplateDto {
@IsIn(brandTemplateKeys)
templateKey!: BrandTemplateKey;
@IsOptional() @IsUUID() templatePackageVersionId?: string;
@IsUUID() templatePackageVersionId!: string;
}
export class SelectTemplateVersionDto {
@IsUUID() templatePackageVersionId!: string;
@IsOptional() @IsUUID() expectedCurrentPackageVersionId?: string | null;
@IsBoolean() confirm!: boolean;
}
export class UpgradeTemplateDto {
+18 -28
View File
@@ -6,12 +6,9 @@ import {
} from "@nestjs/common";
import { Prisma } from "@prisma/client";
import {
defaultBrandTemplateKey,
getBrandTemplate,
getVisualTemplate,
isVisualTemplateCompatible,
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
validateTemplatePackageManifest,
type TemplatePackageManifest,
} from "@personal-brand/config";
@@ -61,9 +58,8 @@ export class BrandReleaseApiService {
where: { id: brandId },
select: { name: true, tagline: true, description: true, templateKey: true, config: true },
});
const installation = await database.brandTemplateInstallation.findFirst({
const installation = await database.brandTemplateInstallation.findUnique({
where: { brandId },
orderBy: { updatedAt: "desc" },
});
const packageVersion = installation?.templatePackageVersionId
? await database.templatePackageVersion.findUnique({
@@ -71,36 +67,30 @@ export class BrandReleaseApiService {
select: {
packageKey: true,
version: true,
visualTemplateKey: true,
status: true,
contentChecksum: true,
manifestSnapshot: true,
},
})
: null;
const template = getBrandTemplate(installation?.templateKey ?? brand?.templateKey ?? "");
const config = this.jsonObject(brand?.config);
const visualKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: getDefaultVisualTemplateKey(brand?.templateKey ?? defaultBrandTemplateKey);
const template = getBrandTemplate(brand?.templateKey ?? "");
const storedManifest = packageVersion?.manifestSnapshot as TemplatePackageManifest | undefined;
const visualKey = storedManifest?.visualTemplateKey ?? "";
const visual = getVisualTemplate(visualKey);
const storedManifest = packageVersion?.manifestSnapshot as unknown as
TemplatePackageManifest | undefined;
const packageManifest = storedManifest ?? getTemplatePackageManifestForVisualKey(visualKey);
const packageVersionValid =
!installation?.templatePackageVersionId ||
Boolean(
packageVersion &&
packageVersion.status === "published" &&
/^[a-f0-9]{64}$/.test(packageVersion.contentChecksum) &&
packageVersion.packageKey === (storedManifest?.packageKey ?? "") &&
packageVersion.version === (storedManifest?.version ?? "") &&
(packageVersion.visualTemplateKey ?? packageVersion.packageKey) ===
(storedManifest?.visualTemplateKey ?? packageVersion.packageKey) &&
storedManifest?.supportedIndustryTemplates.includes(brand?.templateKey ?? "") &&
validateTemplatePackageManifest(storedManifest).length === 0,
);
const packageManifest = storedManifest;
const packageVersionValid = Boolean(
installation?.templatePackageVersionId &&
packageVersion &&
packageVersion.status === "published" &&
/^[a-f0-9]{64}$/.test(packageVersion.contentChecksum) &&
packageVersion.packageKey === (storedManifest?.packageKey ?? "") &&
packageVersion.version === (storedManifest?.version ?? "") &&
packageVersion.packageKey === storedManifest?.packageKey &&
packageVersion.packageKey === storedManifest?.visualTemplateKey &&
storedManifest?.supportedIndustryTemplates.includes(brand?.templateKey ?? "") &&
validateTemplatePackageManifest(storedManifest).length === 0,
);
const config = this.jsonObject(brand?.config);
const [offerings, forms, trustItems] = await Promise.all([
database.offering.findMany({
where: { brandId, isEnabled: true },
+10 -19
View File
@@ -1,12 +1,9 @@
import { Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import {
defaultBrandTemplateKey,
getBrandTemplate,
getVisualTemplate,
getVisualTemplateManifest,
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
} from "@personal-brand/config";
import type { TemplatePackageManifest } from "@personal-brand/config";
import { PrismaService } from "./prisma.service.js";
@@ -35,9 +32,8 @@ export async function buildBrandReleaseSnapshot(
const [brand, installation, fields, offerings, forms, trustContents, capabilities] =
await Promise.all([
database.brandProfile.findUnique({ where: { id: brandId } }),
database.brandTemplateInstallation.findFirst({
database.brandTemplateInstallation.findUnique({
where: { brandId },
orderBy: { updatedAt: "desc" },
include: { templatePackageVersion: true },
}),
database.brandFieldDefinition.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
@@ -46,15 +42,14 @@ export async function buildBrandReleaseSnapshot(
database.trustContent.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
database.capabilityInstallation.findMany({ where: { brandId } }),
]);
const templateKey = brand?.templateKey ?? installation?.templateKey ?? defaultBrandTemplateKey;
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const visualKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: getDefaultVisualTemplateKey(brand?.templateKey ?? defaultBrandTemplateKey);
if (!brand) throw new Error("品牌不存在,不能生成发布快照");
if (!installation?.templatePackageVersion) throw new Error("品牌安装没有锁定精确视觉模板包版本");
const templateKey = brand.templateKey;
const packageManifest = installation.templatePackageVersion.manifestSnapshot as unknown as
TemplatePackageManifest | undefined;
const visualKey = packageManifest?.visualTemplateKey;
if (!packageManifest || typeof visualKey !== "string")
throw new Error("品牌安装与模板包 manifest 不一致");
const jsonObject = (value: object): Record<string, unknown> =>
JSON.parse(JSON.stringify(value)) as Record<string, unknown>;
return {
@@ -64,11 +59,7 @@ export async function buildBrandReleaseSnapshot(
templateDefinition: getBrandTemplate(templateKey) ?? null,
visualTemplateDefinition: getVisualTemplate(visualKey) ?? null,
visualTemplateManifest: getVisualTemplateManifest(visualKey) ?? null,
templatePackageManifest:
(installation?.templatePackageVersion?.manifestSnapshot as unknown as
TemplatePackageManifest | undefined) ??
getTemplatePackageManifestForVisualKey(visualKey) ??
null,
templatePackageManifest: packageManifest,
brand: brand ? jsonObject(brand) : null,
installation: installation ? jsonObject(installation) : null,
fields: fields.map((item) => jsonObject(item)),
@@ -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);
}
+171 -150
View File
@@ -1,45 +1,35 @@
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
import type { TemplatePackageVersion } from "@prisma/client";
import { Prisma } from "@prisma/client";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import {
type BrandTemplateKey,
defaultBrandTemplateKey,
getBrandTemplate,
getVisualTemplate,
getVisualTemplateManifest,
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
isVisualTemplateCompatible,
validateTemplatePackageManifest,
} from "@personal-brand/config";
import type { TemplatePackageManifest } from "@personal-brand/config";
import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.js";
import type { RollbackTemplateDto, UpgradeTemplateDto } from "./admin.dto.js";
import { PrismaService } from "./prisma.service.js";
const execFileAsync = promisify(execFile);
@Injectable()
export class TemplateWorkspaceService {
constructor(private readonly prisma: PrismaService) {}
async getTrustContentTypes(brandId: string): Promise<string[]> {
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true, config: true },
const installation = await this.prisma.brandTemplateInstallation.findUnique({
where: { brandId },
include: { templatePackageVersion: true },
});
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const visualKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: getDefaultVisualTemplateKey(brand?.templateKey ?? defaultBrandTemplateKey);
return (
getTemplatePackageManifestForVisualKey(visualKey)?.trustContentTypes?.map(
(item) => item.type,
) ?? []
);
if (!installation?.templatePackageVersion)
throw new BadRequestException("品牌没有锁定精确视觉模板包版本");
const manifest = record(
installation.templatePackageVersion.manifestSnapshot,
) as unknown as TemplatePackageManifest;
if (validateTemplatePackageManifest(manifest as unknown as TemplatePackageManifest).length)
throw new BadRequestException("当前安装的模板包不符合统一模板契约");
return manifest.trustContentTypes?.map((item) => item.type) ?? [];
}
async createTrustContent(brandId: string, body: CreateTrustContentDto) {
if (!(await this.getTrustContentTypes(brandId)).includes(body.type))
@@ -87,28 +77,25 @@ export class TemplateWorkspaceService {
where: { id: brandId },
select: { templateKey: true },
}),
this.prisma.brandTemplateInstallation.findFirst({
this.prisma.brandTemplateInstallation.findUnique({
where: { brandId },
orderBy: { updatedAt: "desc" },
select: { templateKey: true },
}),
]);
// BrandProfile.templateKey 是「品牌使用哪个行业模板」的唯一真相;
// 安装记录只是同一模板的版本台账,缺失时不能反过来改写品牌身份。
for (const candidate of [brand?.templateKey, installation?.templateKey]) {
const template = candidate ? getBrandTemplate(candidate) : undefined;
if (template) return template.key;
}
return defaultBrandTemplateKey;
const template = brand?.templateKey ? getBrandTemplate(brand.templateKey) : undefined;
if (!template) throw new BadRequestException("品牌没有有效的行业模型声明");
if (installation && installation.templateKey !== template.key)
throw new BadRequestException("品牌行业模型与模板安装不一致,请修复安装数据");
return template.key;
}
async install(brandId: string, templateKey: BrandTemplateKey, templatePackageVersionId?: string) {
async install(brandId: string, templateKey: BrandTemplateKey, templatePackageVersionId: string) {
const template = getBrandTemplate(templateKey);
if (!template) throw new BadRequestException("行业模板不存在");
const [existing, brand] = await Promise.all([
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
this.prisma.brandTemplateInstallation.findUnique({ where: { brandId } }),
this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { config: true, templateKey: true },
select: { templateKey: true },
}),
]);
// 一个品牌只使用一个行业模板(BrandProfile.templateKey 即身份)。安装只允许补建当前模板的版本台账,
@@ -118,20 +105,13 @@ export class TemplateWorkspaceService {
throw new BadRequestException(
`当前品牌已在使用「${currentTemplate.name}」行业模板,更换行业模板不在本版本范围内`,
);
if (existing && existing.templateKey === templateKey)
throw new BadRequestException("该模板已经安装");
const brandConfig =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const configuredVisualTemplateKey =
typeof brandConfig.visualTemplateKey === "string" ? brandConfig.visualTemplateKey : undefined;
const visualTemplateKey =
configuredVisualTemplateKey &&
getVisualTemplate(configuredVisualTemplateKey) &&
isVisualTemplateCompatible(getVisualTemplate(configuredVisualTemplateKey)!, templateKey)
? configuredVisualTemplateKey
: getDefaultVisualTemplateKey(templateKey);
if (existing) throw new BadRequestException("品牌已经安装模板包,请使用明确的升级流程");
const packageVersion = await this.resolveInstallablePackageVersion(
templateKey,
templatePackageVersionId,
);
const packageManifest = packageVersion.manifestSnapshot as unknown as TemplatePackageManifest;
const visualTemplateKey = packageManifest.visualTemplateKey;
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
const visualTemplate = getVisualTemplate(visualTemplateKey);
if (
@@ -140,39 +120,19 @@ export class TemplateWorkspaceService {
!isVisualTemplateCompatible(visualTemplate, templateKey)
)
throw new BadRequestException("当前视觉模板不适配行业模板");
const templatePackageSnapshot = {
schemaVersion: "1.0",
version: template.version,
industryTemplate: template,
visualTemplate: visualManifest,
capabilities: template.capabilities,
};
const packageVersion = await this.resolveInstallablePackageVersion(
templateKey,
visualTemplateKey,
templatePackageVersionId,
);
return this.prisma.$transaction(async (tx) => {
// 安装记录与品牌身份必须同时落库,否则会出现「品牌在跑 A 模板、台账记的是 B」的漂移。
// 已经自定义过视觉模板的品牌,补建台账时保留原选择,只把行业模板身份写回。
const nextConfig = (
brandConfig.visualTemplateKey === undefined
? { ...brandConfig, visualTemplateKey }
: brandConfig
) as Prisma.InputJsonValue;
await tx.brandProfile.update({
where: { id: brandId },
data: { templateKey, config: nextConfig },
data: { templateKey },
});
const installation = await tx.brandTemplateInstallation.create({
data: {
brandId,
templateKey,
templateVersion: template.version,
visualTemplateKey,
templatePackageVersionId: packageVersion?.id ?? null,
contentChecksum: packageVersion?.contentChecksum ?? null,
configSnapshot: templatePackageSnapshot as unknown as Prisma.InputJsonValue,
templatePackageVersionId: packageVersion.id,
contentChecksum: packageVersion.contentChecksum,
configSnapshot: packageVersion.manifestSnapshot as Prisma.InputJsonValue,
},
});
await tx.brandFieldDefinition.createMany({
@@ -192,42 +152,112 @@ export class TemplateWorkspaceService {
}
private async resolveInstallablePackageVersion(
templateKey: BrandTemplateKey,
visualTemplateKey: string,
templatePackageVersionId?: string,
): Promise<TemplatePackageVersion | null> {
const version = templatePackageVersionId
? await this.prisma.templatePackageVersion.findUnique({
where: { id: templatePackageVersionId },
})
: await this.prisma.templatePackageVersion.findFirst({
where: { packageKey: visualTemplateKey, status: "published" },
orderBy: { importedAt: "desc" },
});
if (!version) {
if (templatePackageVersionId) throw new BadRequestException("指定的模板包版本不存在");
return null;
}
templatePackageVersionId: string,
): Promise<TemplatePackageVersion> {
const version = await this.prisma.templatePackageVersion.findUnique({
where: { id: templatePackageVersionId },
});
if (!version) throw new BadRequestException("指定的模板包版本不存在");
if (version.status !== "published")
throw new BadRequestException("只有已发布的模板包版本可以安装到品牌");
const manifest = record(version.manifestSnapshot);
const manifestVisualTemplateKey =
typeof manifest.visualTemplateKey === "string"
? manifest.visualTemplateKey
: version.packageKey;
if (
manifest.packageKey !== version.packageKey ||
manifest.version !== version.version ||
manifestVisualTemplateKey !== visualTemplateKey ||
typeof manifest.visualTemplateKey !== "string" ||
manifest.packageKey !== manifest.visualTemplateKey ||
!Array.isArray(manifest.supportedIndustryTemplates) ||
!manifest.supportedIndustryTemplates.includes(templateKey)
) {
throw new BadRequestException("模板包版本与行业或视觉模板不匹配");
}
if (validateTemplatePackageManifest(manifest as unknown as TemplatePackageManifest).length)
throw new BadRequestException("模板包版本不符合统一模板契约");
return version;
}
async selectVersion(
brandId: string,
body: {
templatePackageVersionId: string;
expectedCurrentPackageVersionId?: string | null;
confirm: boolean;
},
actorId: string,
requestId?: string,
) {
if (!body.confirm) throw new BadRequestException("选择模板版本必须显式确认");
const [installation, brand, target] = await Promise.all([
this.installation(brandId),
this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true },
}),
this.prisma.templatePackageVersion.findUnique({
where: { id: body.templatePackageVersionId },
}),
]);
if (!brand) throw new BadRequestException("品牌不存在");
if (body.expectedCurrentPackageVersionId !== installation.templatePackageVersionId)
throw new ConflictException("当前模板版本已变化,请刷新后重试");
if (!target || target.status !== "published")
throw new BadRequestException("指定模板包版本不存在或未发布");
const manifest = record(target.manifestSnapshot) as unknown as TemplatePackageManifest;
if (
target.packageKey !== manifest.packageKey ||
target.version !== manifest.version ||
manifest.packageKey !== manifest.visualTemplateKey ||
!manifest.supportedIndustryTemplates?.includes(brand.templateKey) ||
validateTemplatePackageManifest(manifest).length
)
throw new BadRequestException("指定模板包版本不符合当前品牌的统一模板契约");
if (target.id === installation.templatePackageVersionId)
return { installation, unchanged: true };
const history = Array.isArray(installation.previousSnapshots)
? installation.previousSnapshots
: [];
const updated = await this.prisma.$transaction(async (tx) => {
const changed = await tx.brandTemplateInstallation.updateMany({
where: {
id: installation.id,
templatePackageVersionId: installation.templatePackageVersionId,
},
data: {
templatePackageVersionId: target.id,
templateVersion: target.version,
contentChecksum: target.contentChecksum,
configSnapshot: manifest as unknown as Prisma.InputJsonValue,
previousSnapshots: [...history, installation.configSnapshot],
},
});
if (changed.count !== 1) throw new ConflictException("当前模板版本已变化,请刷新后重试");
await tx.templatePackageAuditLog.create({
data: {
templatePackageVersionId: target.id,
actorId,
action: "brand_template_selected",
...(requestId ? { requestId } : {}),
metadata: {
brandId,
fromVersionId: installation.templatePackageVersionId,
toVersionId: target.id,
contentChecksum: target.contentChecksum,
},
},
});
return tx.brandTemplateInstallation.findUniqueOrThrow({
where: { id: installation.id },
include: { templatePackageVersion: true },
});
});
return { installation: updated, unchanged: false };
}
private async installation(brandId: string) {
const item = await this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } });
const item = await this.prisma.brandTemplateInstallation.findUnique({
where: { brandId },
include: { templatePackageVersion: true },
});
if (!item) throw new BadRequestException("尚未安装行业模板");
return item;
}
@@ -235,30 +265,37 @@ export class TemplateWorkspaceService {
const templateKey = await this.getEffectiveTemplateKey(brandId);
const template = getBrandTemplate(templateKey);
if (!template) throw new BadRequestException("当前行业模板不存在");
const [installation, brand] = await Promise.all([
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
]);
// 品牌一直有行业模板,但版本台账可能还没建立;此时以模板目录的版本为准,不报错。
const currentVersion = installation?.templateVersion ?? template.version;
const installation = await this.installation(brandId);
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { config: true },
});
const config = record(brand?.config);
const visualTemplateKey =
installation?.visualTemplateKey ??
(typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : undefined) ??
getDefaultVisualTemplateKey(templateKey);
const currentPackage = installation?.templatePackageVersionId
? await this.prisma.templatePackageVersion.findUnique({
where: { id: installation.templatePackageVersionId },
})
: null;
const targetPackage = visualTemplateKey
? await this.prisma.templatePackageVersion.findFirst({
where: { packageKey: visualTemplateKey, status: "published" },
orderBy: { importedAt: "desc" },
})
: null;
if (!installation.templatePackageVersion || !installation.templatePackageVersionId)
throw new BadRequestException("品牌安装没有锁定精确视觉模板包版本");
const currentVersion = installation.templateVersion;
const visualTemplateKey = record(
installation.templatePackageVersion.manifestSnapshot,
).visualTemplateKey;
if (typeof visualTemplateKey !== "string")
throw new BadRequestException("已安装模板版本缺少 visualTemplateKey 声明");
const [currentPackage, targetPackage] = await Promise.all([
this.prisma.templatePackageVersion.findUnique({
where: { id: installation.templatePackageVersionId },
}),
this.prisma.templatePackageVersion.findFirst({
where: { packageKey: visualTemplateKey, status: "published" },
orderBy: { importedAt: "desc" },
}),
]);
if (!currentPackage) throw new BadRequestException("当前安装引用的模板包版本不存在");
if (
currentPackage.packageKey !== visualTemplateKey ||
record(currentPackage.manifestSnapshot).visualTemplateKey !== visualTemplateKey
)
throw new BadRequestException("品牌安装与模板包视觉声明不一致");
const targetManifest = record(targetPackage?.manifestSnapshot);
const currentManifest = record(currentPackage?.manifestSnapshot);
const currentManifest = record(currentPackage.manifestSnapshot);
const currentDeclarations = manifestRecords(currentManifest.templateFields);
const targetDeclarations = manifestRecords(targetManifest.templateFields);
const currentByKey = new Map(currentDeclarations.map((item) => [String(item.key), item]));
@@ -316,12 +353,11 @@ export class TemplateWorkspaceService {
templateKey,
currentVersion,
latestVersion: targetPackage?.version ?? template.version,
currentPackageVersionId: currentPackage?.id ?? null,
currentContentChecksum:
currentPackage?.contentChecksum ?? installation?.contentChecksum ?? null,
currentPackageVersionId: currentPackage.id,
currentContentChecksum: currentPackage.contentChecksum,
targetPackageVersionId: targetPackage?.id ?? null,
targetContentChecksum: targetPackage?.contentChecksum ?? null,
canUpgrade: Boolean(targetPackage && targetPackage.id !== currentPackage?.id),
canUpgrade: Boolean(targetPackage && targetPackage.id !== currentPackage.id),
canRollback:
Array.isArray(installation?.previousSnapshots) && installation.previousSnapshots.length > 0,
changes: {
@@ -404,7 +440,8 @@ export class TemplateWorkspaceService {
throw new ConflictException("冲突处理与当前预览不一致,请重新预览并逐项确认");
const manifest = record(target.manifestSnapshot);
if (
target.packageKey !== installation.visualTemplateKey ||
target.packageKey !==
record(installation.templatePackageVersion?.manifestSnapshot).visualTemplateKey ||
manifest.packageKey !== target.packageKey ||
manifest.version !== target.version ||
!Array.isArray(manifest.supportedIndustryTemplates) ||
@@ -474,12 +511,15 @@ export class TemplateWorkspaceService {
where: { packageKey: previousManifest.packageKey, version },
})
: null;
if (!previousPackage)
throw new BadRequestException("历史模板包版本不存在,不能回滚到未锁定版本");
if (
previousPackage &&
(previousPackage.packageKey !== installation.visualTemplateKey ||
!stringList(record(previousPackage.manifestSnapshot).supportedIndustryTemplates).includes(
installation.templateKey,
))
previousPackage.packageKey !==
record(installation.templatePackageVersion?.manifestSnapshot).visualTemplateKey ||
previousPackage.packageKey !== record(previousPackage.manifestSnapshot).visualTemplateKey ||
!stringList(record(previousPackage.manifestSnapshot).supportedIndustryTemplates).includes(
installation.templateKey,
)
)
throw new BadRequestException("上一版模板包与当前品牌行业或视觉模板不兼容");
const updated = await this.prisma.$transaction(async (tx) => {
@@ -491,8 +531,8 @@ export class TemplateWorkspaceService {
},
data: {
templateVersion: version,
templatePackageVersionId: previousPackage?.id ?? null,
contentChecksum: previousPackage?.contentChecksum ?? null,
templatePackageVersionId: previousPackage.id,
contentChecksum: previousPackage.contentChecksum,
configSnapshot: previous,
previousSnapshots: history.slice(0, -1),
},
@@ -509,7 +549,7 @@ export class TemplateWorkspaceService {
brandId,
fromVersionId: installation.templatePackageVersionId,
fromVersion: installation.templateVersion,
toVersionId: previousPackage?.id ?? null,
toVersionId: previousPackage.id,
toVersion: version,
},
},
@@ -525,28 +565,9 @@ export class TemplateWorkspaceService {
}
async function readPackageFiles(
version: Pick<
TemplatePackageVersion,
"artifactPath" | "validationReport" | "packageKey" | "version"
>,
version: Pick<TemplatePackageVersion, "validationReport">,
): Promise<Record<string, unknown>[]> {
const stored = manifestRecords(record(version.validationReport).files);
if (stored.length) return stored;
const root = `${version.packageKey}-${version.version}`;
const checksumEntry = `${root}/checksums.json`;
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(version.packageKey) || root.includes("/")) return [];
try {
const { stdout: entries } = await execFileAsync("tar", ["-tzf", version.artifactPath], {
maxBuffer: 4 * 1024 * 1024,
});
if (!entries.split("\n").some((entry) => entry === checksumEntry)) return [];
const { stdout } = await execFileAsync("tar", ["-xOzf", version.artifactPath, checksumEntry], {
maxBuffer: 4 * 1024 * 1024,
});
return manifestRecords(record(JSON.parse(stdout)).files);
} catch {
return [];
}
return manifestRecords(record(version.validationReport).files);
}
function record(value: unknown): Record<string, unknown> {