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

+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> {