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 { RollbackTemplateDto, UpgradeTemplateDto } from "../admin.dto.js"; import { PrismaService } from "../prisma.service.js"; import { recordTemplateOperationFailure } from "../modules/admin/template-operation-failure.js"; import { latestTemplateVersion } from "../template-version-order.js"; import { compareFiles, compareKeyedRecords, compareRecords, hasBindingValue, manifestRecords, readPackageFiles, record, stringList, } from "./manifest-diff.helpers.js"; @Injectable() export class TemplateInstallationService { constructor(private readonly prisma: PrismaService) {} async getEffectiveTemplateKey(brandId: string): Promise { 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 }, }), ]); if (!brand) throw new BadRequestException("品牌不存在"); // 一个品牌只使用一个行业模板(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) => { const installation = await tx.brandTemplateInstallation.create({ data: { brandId, templateKey, templateVersion: packageVersion.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 }; }); } async resolveInstallablePackageVersion( templateKey: BrandTemplateKey, templatePackageVersionId: string, ): Promise { 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; const visualTemplate = typeof manifest.visualTemplateKey === "string" ? getVisualTemplate(manifest.visualTemplateKey) : undefined; if ( target.packageKey !== manifest.packageKey || target.version !== manifest.version || manifest.packageKey !== manifest.visualTemplateKey || !manifest.supportedIndustryTemplates?.includes(brand.templateKey) || !visualTemplate || !isVisualTemplateCompatible(visualTemplate, 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, publishedTargets] = await Promise.all([ this.prisma.templatePackageVersion.findUnique({ where: { id: installation.templatePackageVersionId }, }), this.prisma.templatePackageVersion.findMany({ where: { packageKey: visualTemplateKey, status: "published" }, }), ]); const targetPackage = latestTemplateVersion( publishedTargets.filter((candidate) => { const manifest = record(candidate.manifestSnapshot); return ( candidate.packageKey === visualTemplateKey && manifest.packageKey === candidate.packageKey && manifest.version === candidate.version && manifest.visualTemplateKey === visualTemplateKey && Array.isArray(manifest.supportedIndustryTemplates) && manifest.supportedIndustryTemplates.includes(installation.templateKey) && validateTemplatePackageManifest(manifest).length === 0 ); }), ); 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: "已恢复上一版模板配置基线,现有模块、字段和业务内容未删除。", }; } }