import { BadRequestException, Injectable } from "@nestjs/common"; import { Prisma } from "@prisma/client"; import { type BrandTemplateKey, defaultBrandTemplateKey, getBrandTemplate, getVisualTemplate, getVisualTemplateManifest, getDefaultVisualTemplateKey, getTemplatePackageManifestForVisualKey, isVisualTemplateCompatible, } from "@personal-brand/config"; import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.js"; import { PrismaService } from "./prisma.service.js"; @Injectable() export class TemplateWorkspaceService { constructor(private readonly prisma: PrismaService) {} async getTrustContentTypes(brandId: string): Promise { const brand = await this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { templateKey: true, config: true }, }); const config = brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config) ? (brand.config as Record) : {}; const visualKey = typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : getDefaultVisualTemplateKey(brand?.templateKey ?? defaultBrandTemplateKey); return ( getTemplatePackageManifestForVisualKey(visualKey)?.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 }), }, }); } async getEffectiveTemplateKey(brandId: string): Promise { const [brand, installation] = await Promise.all([ this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { templateKey: true }, }), this.prisma.brandTemplateInstallation.findFirst({ 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; } async install(brandId: string, templateKey: BrandTemplateKey) { const template = getBrandTemplate(templateKey); if (!template) throw new BadRequestException("行业模板不存在"); const [existing, brand] = await Promise.all([ this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }), this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true, templateKey: true }, }), ]); if (existing) throw new BadRequestException( existing.templateKey === templateKey ? "该模板已经安装" : "品牌已经安装主模板,更换行业模板不在本版本范围内", ); // 一个品牌只使用一个行业模板(BrandProfile.templateKey 即身份)。安装只允许补建当前模板的版本台账, // 不得换成别的行业模板,否则会出现「身份是 A、台账是 B」的漂移,并把发布快照接到不适配的视觉模板上。 const currentTemplate = brand?.templateKey ? getBrandTemplate(brand.templateKey) : undefined; if (currentTemplate && currentTemplate.key !== templateKey) throw new BadRequestException( `当前品牌已在使用「${currentTemplate.name}」行业模板,更换行业模板不在本版本范围内`, ); const brandConfig = brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config) ? (brand.config as Record) : {}; const configuredVisualTemplateKey = typeof brandConfig.visualTemplateKey === "string" ? brandConfig.visualTemplateKey : undefined; const visualTemplateKey = configuredVisualTemplateKey && getVisualTemplate(configuredVisualTemplateKey) && isVisualTemplateCompatible(getVisualTemplate(configuredVisualTemplateKey)!, templateKey) ? configuredVisualTemplateKey : getDefaultVisualTemplateKey(templateKey); const visualManifest = getVisualTemplateManifest(visualTemplateKey); const visualTemplate = getVisualTemplate(visualTemplateKey); if ( !visualManifest || !visualTemplate || !isVisualTemplateCompatible(visualTemplate, templateKey) ) throw new BadRequestException("当前视觉模板不适配行业模板"); const templatePackageSnapshot = { schemaVersion: "1.0", version: template.version, industryTemplate: template, visualTemplate: visualManifest, capabilities: template.capabilities, }; 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 }, }); const installation = await tx.brandTemplateInstallation.create({ data: { brandId, templateKey, templateVersion: template.version, configSnapshot: templatePackageSnapshot as unknown 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 installation(brandId: string) { const item = await this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }); 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, fields] = await Promise.all([ this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }), this.prisma.brandFieldDefinition.findMany({ where: { brandId } }), ]); // 品牌一直有行业模板,但版本台账可能还没建立;此时以模板目录的版本为准,不报错。 const currentVersion = installation?.templateVersion ?? template.version; return { templateKey, currentVersion, latestVersion: template.version, canUpgrade: currentVersion !== template.version, canRollback: Array.isArray(installation?.previousSnapshots) && installation.previousSnapshots.length > 0, missingFields: template.fields.filter( (item) => !fields.some((current) => current.scope === item.scope && current.key === item.key), ), }; } async upgrade(brandId: string) { const installation = await this.installation(brandId); const template = getBrandTemplate(installation.templateKey); if (!template) throw new BadRequestException("已安装模板不存在"); if (installation.templateVersion === template.version) throw new BadRequestException("当前模板已经是最新版本"); return this.prisma.$transaction(async (tx) => { const fields = await tx.brandFieldDefinition.findMany({ where: { brandId } }); const addedFields = template.fields.filter( (item) => !fields.some((current) => current.scope === item.scope && current.key === item.key), ); await tx.brandFieldDefinition.createMany({ data: addedFields.map(({ scope, key, label, type, required }, index) => ({ brandId, scope, key, label, type, required, sortOrder: fields.length + index, source: "template", })), }); const history = Array.isArray(installation.previousSnapshots) ? installation.previousSnapshots : []; const updated = await tx.brandTemplateInstallation.update({ where: { id: installation.id }, data: { templateVersion: template.version, configSnapshot: template as unknown as Prisma.InputJsonValue, previousSnapshots: [...history, installation.configSnapshot], }, }); return { installation: updated, addedFields }; }); } async rollback(brandId: string) { const installation = await this.installation(brandId); 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 updated = await this.prisma.brandTemplateInstallation.update({ where: { id: installation.id }, data: { templateVersion: version, configSnapshot: previous, previousSnapshots: history.slice(0, -1), }, }); return { installation: updated, note: "已恢复上一版模板配置基线,现有模块、字段和业务内容未删除。", }; } }