import { BadRequestException, Injectable } from "@nestjs/common"; import { Prisma } from "@prisma/client"; import { getBrandTemplate, getVisualTemplate, getVisualTemplateManifest, getDefaultVisualTemplateKey, isVisualTemplateCompatible, } from "@personal-brand/config"; import type { BrandTemplateKey } from "@personal-brand/types"; import { PrismaService } from "./prisma.service.js"; @Injectable() export class TemplateWorkspaceService { constructor(private readonly prisma: PrismaService) {} async getEffectiveTemplateKey(brandId: string): Promise { const [installation, brand] = await Promise.all([ this.prisma.brandTemplateInstallation.findFirst({ where: { brandId }, orderBy: { updatedAt: "desc" }, select: { templateKey: true }, }), this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { templateKey: true }, }), ]); const key = installation?.templateKey ?? brand?.templateKey ?? "personal"; return getBrandTemplate(key) ? (key as BrandTemplateKey) : "personal"; } async install(brandId: string, templateKey: "personal" | "food" | "doors") { 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 } }), ]); if (existing) throw new BadRequestException( existing.templateKey === templateKey ? "该模板已经安装" : "品牌已经安装主模板,请先完成模板切换流程", ); 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) => { if (brandConfig.visualTemplateKey === undefined) { await tx.brandProfile.update({ where: { id: brandId }, data: { config: { ...brandConfig, visualTemplateKey }, }, }); } 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 installation = await this.installation(brandId); const template = getBrandTemplate(installation.templateKey); if (!template) throw new BadRequestException("已安装模板不存在"); const fields = await this.prisma.brandFieldDefinition.findMany({ where: { brandId } }); return { currentVersion: installation.templateVersion, latestVersion: template.version, canUpgrade: installation.templateVersion !== 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: "已恢复上一版模板配置基线,现有模块、字段和业务内容未删除。", }; } }