统一模板包 visual 契约并补齐完成证据;修复 release 版本一致性、管理员 token 撤销、CORS 与默认品牌配置;收敛依赖安全风险并完成全量回归验证。
766 lines
31 KiB
TypeScript
766 lines
31 KiB
TypeScript
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
|
|
import type { TemplatePackageVersion } from "@prisma/client";
|
|
import { Prisma } from "@prisma/client";
|
|
import {
|
|
type BrandTemplateKey,
|
|
getBrandTemplate,
|
|
getVisualTemplate,
|
|
getVisualTemplateManifest,
|
|
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";
|
|
import { recordTemplateOperationFailure } from "./modules/admin/template-operation-failure.js";
|
|
|
|
@Injectable()
|
|
export class TemplateWorkspaceService {
|
|
constructor(private readonly prisma: PrismaService) {}
|
|
async getTrustContentTypes(brandId: string): Promise<string[]> {
|
|
const installation = await this.prisma.brandTemplateInstallation.findUnique({
|
|
where: { brandId },
|
|
include: { templatePackageVersion: true },
|
|
});
|
|
if (!installation?.templatePackageVersion)
|
|
throw new BadRequestException("品牌没有锁定精确视觉模板包版本");
|
|
const manifest = record(
|
|
installation.templatePackageVersion.manifestSnapshot,
|
|
) as unknown as TemplatePackageManifest;
|
|
if (validateTemplatePackageManifest(manifest).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))
|
|
throw new BadRequestException("当前模板不支持此信任内容类型");
|
|
const { config, ...fields } = body;
|
|
return this.prisma.trustContent.create({
|
|
data: {
|
|
...fields,
|
|
brandId,
|
|
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
|
},
|
|
});
|
|
}
|
|
async updateTrustContent(brandId: string, id: string, body: UpdateTrustContentDto) {
|
|
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
|
|
if (!item) throw new BadRequestException("信任内容不存在");
|
|
if (body.type !== undefined && !(await this.getTrustContentTypes(brandId)).includes(body.type))
|
|
throw new BadRequestException("当前模板不支持此信任内容类型");
|
|
const { config, ...fields } = body;
|
|
return this.prisma.trustContent.update({
|
|
where: { id },
|
|
data: {
|
|
...fields,
|
|
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
|
},
|
|
});
|
|
}
|
|
|
|
listTrustContent(brandId: string) {
|
|
return this.prisma.trustContent.findMany({
|
|
where: { brandId },
|
|
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
|
|
});
|
|
}
|
|
|
|
async deleteTrustContent(brandId: string, id: string) {
|
|
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
|
|
if (!item) throw new BadRequestException("信任内容不存在");
|
|
await this.prisma.trustContent.delete({ where: { id } });
|
|
return { deleted: true };
|
|
}
|
|
async getEffectiveTemplateKey(brandId: string): Promise<BrandTemplateKey> {
|
|
const [brand, installation] = await Promise.all([
|
|
this.prisma.brandProfile.findUnique({
|
|
where: { id: brandId },
|
|
select: { templateKey: true },
|
|
}),
|
|
this.prisma.brandTemplateInstallation.findUnique({
|
|
where: { brandId },
|
|
select: { templateKey: true },
|
|
}),
|
|
]);
|
|
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,
|
|
actorId: string,
|
|
requestId?: string,
|
|
) {
|
|
try {
|
|
return await this.installTemplate(brandId, templateKey, templatePackageVersionId);
|
|
} catch (error) {
|
|
await recordTemplateOperationFailure(this.prisma, {
|
|
action: error instanceof ConflictException ? "install_conflict" : "install",
|
|
error,
|
|
...(requestId ? { requestId } : {}),
|
|
actorId,
|
|
brandId,
|
|
});
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
private async installTemplate(
|
|
brandId: string,
|
|
templateKey: BrandTemplateKey,
|
|
templatePackageVersionId: string,
|
|
) {
|
|
const template = getBrandTemplate(templateKey);
|
|
if (!template) throw new BadRequestException("行业模板不存在");
|
|
const [existing, brand] = await Promise.all([
|
|
this.prisma.brandTemplateInstallation.findUnique({ where: { brandId } }),
|
|
this.prisma.brandProfile.findUnique({
|
|
where: { id: brandId },
|
|
select: { templateKey: true },
|
|
}),
|
|
]);
|
|
// 一个品牌只使用一个行业模板(BrandProfile.templateKey 即身份)。安装只允许补建当前模板的版本台账,
|
|
// 不得换成别的行业模板,否则会出现「身份是 A、台账是 B」的漂移,并把发布快照接到不适配的视觉模板上。
|
|
const currentTemplate = brand?.templateKey ? getBrandTemplate(brand.templateKey) : undefined;
|
|
if (currentTemplate && currentTemplate.key !== templateKey)
|
|
throw new BadRequestException(
|
|
`当前品牌已在使用「${currentTemplate.name}」行业模板,更换行业模板不在本版本范围内`,
|
|
);
|
|
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 (
|
|
!visualManifest ||
|
|
!visualTemplate ||
|
|
!isVisualTemplateCompatible(visualTemplate, templateKey)
|
|
)
|
|
throw new BadRequestException("当前视觉模板不适配行业模板");
|
|
return this.prisma.$transaction(async (tx) => {
|
|
await tx.brandProfile.update({
|
|
where: { id: brandId },
|
|
data: { templateKey },
|
|
});
|
|
const installation = await tx.brandTemplateInstallation.create({
|
|
data: {
|
|
brandId,
|
|
templateKey,
|
|
templateVersion: template.version,
|
|
templatePackageVersionId: packageVersion.id,
|
|
contentChecksum: packageVersion.contentChecksum,
|
|
configSnapshot: packageVersion.manifestSnapshot as Prisma.InputJsonValue,
|
|
},
|
|
});
|
|
await tx.brandFieldDefinition.createMany({
|
|
data: template.fields.map(({ scope, key, label, type, required }, sortOrder) => ({
|
|
brandId,
|
|
scope,
|
|
key,
|
|
label,
|
|
type,
|
|
sortOrder,
|
|
source: "core",
|
|
required,
|
|
})),
|
|
});
|
|
return { installation, template, visualTemplate: visualManifest };
|
|
});
|
|
}
|
|
private async resolveInstallablePackageVersion(
|
|
templateKey: BrandTemplateKey,
|
|
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);
|
|
if (
|
|
manifest.packageKey !== version.packageKey ||
|
|
manifest.version !== version.version ||
|
|
typeof manifest.visualTemplateKey !== "string" ||
|
|
manifest.packageKey !== manifest.visualTemplateKey ||
|
|
!Array.isArray(manifest.supportedIndustryTemplates) ||
|
|
!manifest.supportedIndustryTemplates.includes(templateKey)
|
|
) {
|
|
throw new BadRequestException("模板包版本与行业或视觉模板不匹配");
|
|
}
|
|
if (validateTemplatePackageManifest(manifest).length)
|
|
throw new BadRequestException("模板包版本不符合统一模板契约");
|
|
return version;
|
|
}
|
|
|
|
async selectVersion(
|
|
brandId: string,
|
|
body: {
|
|
templatePackageVersionId: string;
|
|
expectedCurrentPackageVersionId?: string | null;
|
|
confirm: boolean;
|
|
},
|
|
actorId: string,
|
|
requestId?: string,
|
|
) {
|
|
try {
|
|
return await this.selectVersionUnrecorded(brandId, body, actorId, requestId);
|
|
} catch (error) {
|
|
await recordTemplateOperationFailure(this.prisma, {
|
|
action: "select_version",
|
|
error,
|
|
...(requestId ? { requestId } : {}),
|
|
actorId,
|
|
brandId,
|
|
});
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
private async selectVersionUnrecorded(
|
|
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.findUnique({
|
|
where: { brandId },
|
|
include: { templatePackageVersion: true },
|
|
});
|
|
if (!item) throw new BadRequestException("尚未安装行业模板");
|
|
return item;
|
|
}
|
|
async preview(brandId: string) {
|
|
const templateKey = await this.getEffectiveTemplateKey(brandId);
|
|
const template = getBrandTemplate(templateKey);
|
|
if (!template) throw new BadRequestException("当前行业模板不存在");
|
|
const installation = await this.installation(brandId);
|
|
const brand = await this.prisma.brandProfile.findUnique({
|
|
where: { id: brandId },
|
|
select: { config: true },
|
|
});
|
|
const config = record(brand?.config);
|
|
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 currentDeclarations = manifestRecords(currentManifest.templateFields);
|
|
const targetDeclarations = manifestRecords(targetManifest.templateFields);
|
|
const currentByKey = new Map(currentDeclarations.map((item) => [String(item.key), item]));
|
|
const targetByKey = new Map(targetDeclarations.map((item) => [String(item.key), item]));
|
|
const addedBindings = targetDeclarations.filter((item) => !currentByKey.has(String(item.key)));
|
|
const removedBindings = currentDeclarations.filter(
|
|
(item) => !targetByKey.has(String(item.key)),
|
|
);
|
|
const changedBindings = targetDeclarations.flatMap((item) => {
|
|
const current = currentByKey.get(String(item.key));
|
|
if (!current || JSON.stringify(current) === JSON.stringify(item)) return [];
|
|
return [{ key: String(item.key), current, proposed: item }];
|
|
});
|
|
const conflicts = [
|
|
...addedBindings.flatMap((item) =>
|
|
hasBindingValue(config, item.binding)
|
|
? [
|
|
{
|
|
key: String(item.key),
|
|
binding: String(item.binding),
|
|
reason: "新增字段已有同路径品牌值,升级会原样保留",
|
|
},
|
|
]
|
|
: [],
|
|
),
|
|
...changedBindings.flatMap(({ key, current }) =>
|
|
hasBindingValue(config, current.binding)
|
|
? [{ key, binding: String(current.binding), reason: "该品牌配置已填写,升级不会覆盖" }]
|
|
: [],
|
|
),
|
|
...removedBindings.flatMap((item) =>
|
|
hasBindingValue(config, item.binding)
|
|
? [
|
|
{
|
|
key: String(item.key),
|
|
binding: String(item.binding),
|
|
reason: "新版不再声明该字段,已有品牌值仍会保留",
|
|
},
|
|
]
|
|
: [],
|
|
),
|
|
];
|
|
const currentEntrypoints = record(currentManifest.entrypoints);
|
|
const targetEntrypoints = record(targetManifest.entrypoints);
|
|
const currentAssets = manifestRecords(currentManifest.assetSlots);
|
|
const targetAssets = manifestRecords(targetManifest.assetSlots);
|
|
const [currentFiles, targetFiles] = await Promise.all([
|
|
currentPackage ? readPackageFiles(currentPackage) : Promise.resolve([]),
|
|
targetPackage ? readPackageFiles(targetPackage) : Promise.resolve([]),
|
|
]);
|
|
const currentCapabilities = stringList(currentManifest.requiredCapabilities);
|
|
const targetCapabilities = stringList(targetManifest.requiredCapabilities);
|
|
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
|
|
return {
|
|
templateKey,
|
|
currentVersion,
|
|
latestVersion: targetPackage?.version ?? template.version,
|
|
currentPackageVersionId: currentPackage.id,
|
|
currentContentChecksum: currentPackage.contentChecksum,
|
|
targetPackageVersionId: targetPackage?.id ?? null,
|
|
targetContentChecksum: targetPackage?.contentChecksum ?? null,
|
|
canUpgrade: Boolean(targetPackage && targetPackage.id !== currentPackage.id),
|
|
canRollback:
|
|
Array.isArray(installation?.previousSnapshots) && installation.previousSnapshots.length > 0,
|
|
changes: {
|
|
brandFields: { available: false, reason: "行业字段不由视觉模板包声明" },
|
|
templateBindings: {
|
|
added: addedBindings,
|
|
changed: changedBindings,
|
|
removed: removedBindings,
|
|
},
|
|
pages: compareRecords(currentEntrypoints, targetEntrypoints),
|
|
modules: {
|
|
available: Boolean(visualManifest),
|
|
source: "platform_visual_manifest",
|
|
packageUpgradeChangesRenderer: false,
|
|
pages:
|
|
visualManifest?.pages.map((page) => ({
|
|
key: page.key,
|
|
renderer: page.renderer ?? null,
|
|
modules: page.modules,
|
|
})) ?? [],
|
|
},
|
|
assets: {
|
|
slots: compareKeyedRecords(currentAssets, targetAssets),
|
|
files: compareFiles(currentFiles, targetFiles),
|
|
},
|
|
capabilities: {
|
|
added: targetCapabilities.filter((item) => !currentCapabilities.includes(item)),
|
|
removed: currentCapabilities.filter((item) => !targetCapabilities.includes(item)),
|
|
},
|
|
renderer: {
|
|
available: Boolean(visualManifest),
|
|
source: "platform_visual_manifest",
|
|
packageUpgradeChangesRenderer: false,
|
|
pages:
|
|
visualManifest?.pages.map((page) => ({
|
|
key: page.key,
|
|
renderer: page.renderer ?? null,
|
|
})) ?? [],
|
|
},
|
|
package: {
|
|
currentContentChecksum: currentPackage?.contentChecksum ?? null,
|
|
targetContentChecksum: targetPackage?.contentChecksum ?? null,
|
|
runtimeContract: {
|
|
current: currentManifest.runtimeContract ?? null,
|
|
target: targetManifest.runtimeContract ?? null,
|
|
},
|
|
},
|
|
},
|
|
conflicts,
|
|
};
|
|
}
|
|
async upgrade(brandId: string, body: UpgradeTemplateDto, actorId: string, requestId?: string) {
|
|
try {
|
|
return await this.upgradeUnrecorded(brandId, body, actorId, requestId);
|
|
} catch (error) {
|
|
await recordTemplateOperationFailure(this.prisma, {
|
|
action: error instanceof ConflictException ? "install_conflict" : "upgrade",
|
|
error,
|
|
...(requestId ? { requestId } : {}),
|
|
actorId,
|
|
brandId,
|
|
});
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
private async upgradeUnrecorded(
|
|
brandId: string,
|
|
body: UpgradeTemplateDto,
|
|
actorId: string,
|
|
requestId?: string,
|
|
) {
|
|
if (!body.confirm) throw new BadRequestException("升级模板必须显式确认");
|
|
const installation = await this.installation(brandId);
|
|
const target = await this.prisma.templatePackageVersion.findUnique({
|
|
where: { id: body.templatePackageVersionId },
|
|
});
|
|
if (!target || target.status !== "published")
|
|
throw new BadRequestException("目标模板包版本不存在或未发布");
|
|
if (target.contentChecksum !== body.expectedContentChecksum)
|
|
throw new ConflictException("目标模板包内容已变化,请重新预览升级差异");
|
|
if (installation.templateVersion !== body.expectedCurrentVersion)
|
|
throw new ConflictException("品牌模板版本已变化,请重新预览升级差异");
|
|
if (
|
|
(body.expectedCurrentPackageVersionId ?? null) !==
|
|
(installation.templatePackageVersionId ?? null)
|
|
)
|
|
throw new ConflictException("当前模板包版本已变化,请重新预览升级差异");
|
|
const preview = await this.preview(brandId);
|
|
const expectedConflicts = preview.conflicts
|
|
.map(({ key, binding }) => `${key}\u0000${binding}`)
|
|
.sort();
|
|
const preserved = body.preservedBindings
|
|
.map(({ key, binding, action }) => {
|
|
if (action !== "preserve") throw new BadRequestException("当前只允许保留已有品牌配置");
|
|
return `${key}\u0000${binding}`;
|
|
})
|
|
.sort();
|
|
if (JSON.stringify(expectedConflicts) !== JSON.stringify(preserved))
|
|
throw new ConflictException("冲突处理与当前预览不一致,请重新预览并逐项确认");
|
|
const manifest = record(target.manifestSnapshot);
|
|
if (
|
|
target.packageKey !==
|
|
record(installation.templatePackageVersion?.manifestSnapshot).visualTemplateKey ||
|
|
manifest.packageKey !== target.packageKey ||
|
|
manifest.version !== target.version ||
|
|
!Array.isArray(manifest.supportedIndustryTemplates) ||
|
|
!manifest.supportedIndustryTemplates.includes(installation.templateKey)
|
|
)
|
|
throw new BadRequestException("目标模板包与当前品牌安装不兼容");
|
|
return this.prisma.$transaction(async (tx) => {
|
|
const history = Array.isArray(installation.previousSnapshots)
|
|
? installation.previousSnapshots
|
|
: [];
|
|
const claimed = await tx.brandTemplateInstallation.updateMany({
|
|
where: {
|
|
id: installation.id,
|
|
templateVersion: body.expectedCurrentVersion,
|
|
templatePackageVersionId: installation.templatePackageVersionId,
|
|
},
|
|
data: {
|
|
templatePackageVersionId: target.id,
|
|
contentChecksum: target.contentChecksum,
|
|
templateVersion: target.version,
|
|
configSnapshot: manifest as Prisma.InputJsonValue,
|
|
previousSnapshots: [...history, installation.configSnapshot],
|
|
},
|
|
});
|
|
if (claimed.count !== 1)
|
|
throw new ConflictException("品牌模板版本已变化,请重新预览升级差异");
|
|
const updated = await tx.brandTemplateInstallation.findUniqueOrThrow({
|
|
where: { id: installation.id },
|
|
});
|
|
await tx.templatePackageAuditLog.create({
|
|
data: {
|
|
templatePackageVersionId: target.id,
|
|
actorId,
|
|
action: "brand_upgrade",
|
|
...(requestId ? { requestId } : {}),
|
|
metadata: {
|
|
brandId,
|
|
fromVersionId: installation.templatePackageVersionId,
|
|
fromVersion: installation.templateVersion,
|
|
toVersionId: target.id,
|
|
toVersion: target.version,
|
|
contentChecksum: target.contentChecksum,
|
|
preservedBindings: body.preservedBindings.map(({ key, binding }) => ({ key, binding })),
|
|
},
|
|
},
|
|
});
|
|
return { installation: updated, preservedBindings: body.preservedBindings };
|
|
});
|
|
}
|
|
async rollback(brandId: string, actorId: string, body: RollbackTemplateDto, requestId?: string) {
|
|
try {
|
|
return await this.rollbackUnrecorded(brandId, actorId, body, requestId);
|
|
} catch (error) {
|
|
await recordTemplateOperationFailure(this.prisma, {
|
|
action: "rollback",
|
|
error,
|
|
...(requestId ? { requestId } : {}),
|
|
actorId,
|
|
brandId,
|
|
});
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
private async rollbackUnrecorded(
|
|
brandId: string,
|
|
actorId: string,
|
|
body: RollbackTemplateDto,
|
|
requestId?: string,
|
|
) {
|
|
if (!body.confirm) throw new BadRequestException("回滚模板必须显式确认");
|
|
const installation = await this.installation(brandId);
|
|
if (installation.templateVersion !== body.expectedCurrentVersion)
|
|
throw new ConflictException("品牌模板版本已变化,请刷新后重试回滚");
|
|
const history = Array.isArray(installation.previousSnapshots)
|
|
? installation.previousSnapshots
|
|
: [];
|
|
const previous = history.at(-1);
|
|
if (!previous || typeof previous !== "object" || Array.isArray(previous))
|
|
throw new BadRequestException("没有可回滚的模板版本");
|
|
const version = (previous as { version?: unknown }).version;
|
|
if (typeof version !== "string") throw new BadRequestException("模板快照无效");
|
|
const previousManifest = record(previous);
|
|
const previousPackage =
|
|
typeof previousManifest.packageKey === "string"
|
|
? await this.prisma.templatePackageVersion.findFirst({
|
|
where: { packageKey: previousManifest.packageKey, version },
|
|
})
|
|
: null;
|
|
if (!previousPackage)
|
|
throw new BadRequestException("历史模板包版本不存在,不能回滚到未锁定版本");
|
|
if (
|
|
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) => {
|
|
const changed = await tx.brandTemplateInstallation.updateMany({
|
|
where: {
|
|
id: installation.id,
|
|
templateVersion: installation.templateVersion,
|
|
templatePackageVersionId: installation.templatePackageVersionId,
|
|
},
|
|
data: {
|
|
templateVersion: version,
|
|
templatePackageVersionId: previousPackage.id,
|
|
contentChecksum: previousPackage.contentChecksum,
|
|
configSnapshot: previous,
|
|
previousSnapshots: history.slice(0, -1),
|
|
},
|
|
});
|
|
if (changed.count !== 1) throw new ConflictException("品牌模板版本已变化,请刷新后重试回滚");
|
|
if (installation.templatePackageVersionId) {
|
|
await tx.templatePackageAuditLog.create({
|
|
data: {
|
|
templatePackageVersionId: installation.templatePackageVersionId,
|
|
actorId,
|
|
action: "brand_rollback",
|
|
...(requestId ? { requestId } : {}),
|
|
metadata: {
|
|
brandId,
|
|
fromVersionId: installation.templatePackageVersionId,
|
|
fromVersion: installation.templateVersion,
|
|
toVersionId: previousPackage.id,
|
|
toVersion: version,
|
|
},
|
|
},
|
|
});
|
|
}
|
|
return tx.brandTemplateInstallation.findUniqueOrThrow({ where: { id: installation.id } });
|
|
});
|
|
return {
|
|
installation: updated,
|
|
note: "已恢复上一版模板配置基线,现有模块、字段和业务内容未删除。",
|
|
};
|
|
}
|
|
}
|
|
|
|
function readPackageFiles(
|
|
version: Pick<TemplatePackageVersion, "validationReport">,
|
|
): Record<string, unknown>[] {
|
|
return manifestRecords(record(version.validationReport).files);
|
|
}
|
|
|
|
function record(value: unknown): Record<string, unknown> {
|
|
return value && typeof value === "object" && !Array.isArray(value)
|
|
? (value as Record<string, unknown>)
|
|
: {};
|
|
}
|
|
|
|
function manifestRecords(value: unknown): Record<string, unknown>[] {
|
|
return Array.isArray(value)
|
|
? value.filter((item): item is Record<string, unknown> =>
|
|
Boolean(item && typeof item === "object" && !Array.isArray(item)),
|
|
)
|
|
: [];
|
|
}
|
|
|
|
function stringList(value: unknown): string[] {
|
|
return Array.isArray(value)
|
|
? value.filter((item): item is string => typeof item === "string")
|
|
: [];
|
|
}
|
|
|
|
function hasBindingValue(config: Record<string, unknown>, binding: unknown): boolean {
|
|
if (typeof binding !== "string" || !binding.startsWith("brand.config.")) return false;
|
|
const value = binding
|
|
.slice("brand.config.".length)
|
|
.split(".")
|
|
.reduce<unknown>((current, key) => record(current)[key], config);
|
|
return value !== undefined && value !== null && value !== "";
|
|
}
|
|
|
|
function compareRecords(current: Record<string, unknown>, target: Record<string, unknown>) {
|
|
const currentKeys = Object.keys(current);
|
|
const targetKeys = Object.keys(target);
|
|
return {
|
|
added: targetKeys
|
|
.filter((key) => !(key in current))
|
|
.map((key) => ({ key, target: target[key] })),
|
|
removed: currentKeys
|
|
.filter((key) => !(key in target))
|
|
.map((key) => ({ key, current: current[key] })),
|
|
changed: targetKeys
|
|
.filter(
|
|
(key) => key in current && JSON.stringify(current[key]) !== JSON.stringify(target[key]),
|
|
)
|
|
.map((key) => ({ key, current: current[key], target: target[key] })),
|
|
};
|
|
}
|
|
|
|
function compareKeyedRecords(
|
|
current: Record<string, unknown>[],
|
|
target: Record<string, unknown>[],
|
|
) {
|
|
const currentByKey = new Map(
|
|
current
|
|
.filter((item) => typeof item.key === "string")
|
|
.map((item) => [item.key as string, item]),
|
|
);
|
|
const targetByKey = new Map(
|
|
target.filter((item) => typeof item.key === "string").map((item) => [item.key as string, item]),
|
|
);
|
|
return {
|
|
added: [...targetByKey].filter(([key]) => !currentByKey.has(key)).map(([, item]) => item),
|
|
removed: [...currentByKey].filter(([key]) => !targetByKey.has(key)).map(([, item]) => item),
|
|
changed: [...targetByKey].flatMap(([key, item]) => {
|
|
const previous = currentByKey.get(key);
|
|
return previous && JSON.stringify(previous) !== JSON.stringify(item)
|
|
? [{ key, current: previous, target: item }]
|
|
: [];
|
|
}),
|
|
};
|
|
}
|
|
|
|
function compareFiles(current: Record<string, unknown>[], target: Record<string, unknown>[]) {
|
|
const currentByPath = new Map(
|
|
current
|
|
.filter((item) => typeof item.path === "string")
|
|
.map((item) => [item.path as string, item]),
|
|
);
|
|
const targetByPath = new Map(
|
|
target
|
|
.filter((item) => typeof item.path === "string")
|
|
.map((item) => [item.path as string, item]),
|
|
);
|
|
const available = currentByPath.size > 0 && targetByPath.size > 0;
|
|
return {
|
|
available,
|
|
...(available
|
|
? {
|
|
added: [...targetByPath]
|
|
.filter(([path]) => !currentByPath.has(path))
|
|
.map(([, item]) => item),
|
|
removed: [...currentByPath]
|
|
.filter(([path]) => !targetByPath.has(path))
|
|
.map(([, item]) => item),
|
|
changed: [...targetByPath].flatMap(([path, item]) => {
|
|
const previous = currentByPath.get(path);
|
|
return previous && previous.sha256 !== item.sha256
|
|
? [{ path, current: previous, target: item }]
|
|
: [];
|
|
}),
|
|
}
|
|
: { reason: "版本验证报告未包含完整文件清单" }),
|
|
};
|
|
}
|