import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common"; import { Prisma, type TemplatePackageVersion } from "@prisma/client"; import { getVisualTemplate, isVisualTemplateCompatible, validateTemplatePackageManifest, type TemplatePackageManifest, type TemplateSampleContent, } from "@personal-brand/config"; import { validateFieldSnapshot } from "@personal-brand/validation"; import { PrismaService } from "../../prisma.service.js"; type BootstrapSource = { kind: "package_version"; manifest: TemplatePackageManifest; sample: TemplateSampleContent; version: TemplatePackageVersion; }; type Counts = { brandConfig: number; offerings: number; trustContent: number; fields: number; inquiryForms: number; }; type Action = { type: keyof Counts; key: string; action: "create" | "skip" }; function record(value: unknown): Record { return value && typeof value === "object" && !Array.isArray(value) ? (value as Record) : {}; } function deepMergeMissing( defaults: Record, saved: Record, path = "", ): { value: Record; missingPaths: string[] } { const value = { ...saved }; const missingPaths: string[] = []; for (const [key, fallback] of Object.entries(defaults)) { const currentPath = path ? `${path}.${key}` : key; if (!Object.prototype.hasOwnProperty.call(saved, key)) { value[key] = fallback; missingPaths.push(currentPath); continue; } const current = saved[key]; if ( fallback && current && typeof fallback === "object" && typeof current === "object" && !Array.isArray(fallback) && !Array.isArray(current) ) { const nested = deepMergeMissing( fallback as Record, current as Record, currentPath, ); value[key] = nested.value; missingPaths.push(...nested.missingPaths); } } return { value, missingPaths }; } function asJson(value: unknown): Prisma.InputJsonValue { return value as Prisma.InputJsonValue; } @Injectable() export class AdminSampleContentService { constructor(private readonly prisma: PrismaService) {} async preview(brandId: string, query?: { templatePackageVersionId?: string }) { const { brand, source, visualTemplateKey } = await this.resolveSource( brandId, query?.templatePackageVersionId, ); const plan = await this.buildPlan(brandId, brand.config, source); return { templateKey: source.sample.templateKey, visualTemplateKey, source: this.publicSource(source), alreadyImported: plan.alreadyImported, willCreateInquiryForm: plan.counts.inquiryForms > 0, counts: plan.counts, skipped: plan.skipped, plan: plan.actions, missingConfigKeys: plan.missingConfigKeys, }; } async import( brandId: string, actorId: string, body: { templatePackageVersionId?: string; strategy: "missing_only"; confirm: boolean }, ) { if (body.confirm !== true) throw new BadRequestException("导入示例内容必须显式确认"); if (body.strategy !== "missing_only") throw new BadRequestException("当前只支持 missing_only 导入策略"); const { brand, source } = await this.resolveSource(brandId, body.templatePackageVersionId); const plan = await this.buildPlan(brandId, brand.config, source); const priorImport = await this.prisma.templateBootstrapImport.findFirst({ where: { brandId, templatePackageVersionId: source.version.id, contentChecksum: source.version.contentChecksum, status: "imported", }, orderBy: { createdAt: "desc" }, }); if (priorImport) { return { imported: true, alreadyImported: true, source: this.publicSource(source), counts: priorImport.result ?? plan.counts, }; } const result = await this.prisma.$transaction(async (tx) => { const counts: Counts = { brandConfig: 0, offerings: 0, trustContent: 0, fields: 0, inquiryForms: 0, }; if (plan.missingConfigKeys.length) { const merged = deepMergeMissing(record(source.sample.brandConfig), record(brand.config)); await tx.brandProfile.update({ where: { id: brandId }, data: { config: asJson(merged.value) }, }); counts.brandConfig = merged.missingPaths.length; } for (const item of source.sample.offerings) { const name = String(item.name ?? ""); if (!name || plan.existingOfferingNames.has(name)) continue; await tx.offering.create({ data: { brandId, kind: String(item.kind ?? "service"), name, ...(typeof item.summary === "string" ? { summary: item.summary } : {}), ...(typeof item.coverUrl === "string" ? { coverUrl: item.coverUrl } : {}), ...(typeof item.priceText === "string" ? { priceText: item.priceText } : {}), config: asJson({ ...record(item.config), ...(item.categoryKey ? { categoryKey: item.categoryKey } : {}), }), sortOrder: counts.offerings, isEnabled: true, }, }); counts.offerings += 1; } for (const item of source.sample.trustContent) { const type = String(item.type ?? ""); const title = String(item.title ?? ""); if (!type || !title || plan.existingTrustKeys.has(`${type}\0${title}`)) continue; await tx.trustContent.create({ data: { brandId, type, title, content: String(item.content ?? ""), ...(typeof item.summary === "string" ? { summary: item.summary } : {}), ...(item.config ? { config: asJson(item.config) } : {}), sortOrder: counts.trustContent, isPublished: false, }, }); counts.trustContent += 1; } for (const item of source.sample.fields) { const key = String(item.key ?? ""); if (!key || plan.existingFieldKeys.has(key)) continue; await tx.brandFieldDefinition.create({ data: { brandId, scope: "inquiry", key, label: String(item.label ?? key), type: String(item.type ?? "text"), sortOrder: counts.fields, source: "sample", required: item.required === true, }, }); counts.fields += 1; } if (plan.counts.inquiryForms) { await tx.inquiryForm.create({ data: { brandId, name: source.sample.inquiryFormName, purpose: "inquiry", targetType: "brand", submissionAction: "create-inquiry", fieldsSnapshot: asJson(source.sample.fields), isEnabled: true, }, }); counts.inquiryForms = 1; } const importResult = { ...counts, skipped: plan.skipped, actions: plan.actions }; await tx.templateBootstrapImport.create({ data: { brandId, templatePackageVersionId: source.version.id, packageKey: source.version.packageKey, packageVersion: source.version.version, contentChecksum: source.version.contentChecksum, actorId, strategy: "missing_only", status: "imported", result: asJson(importResult), }, }); await tx.capabilityAuditLog.create({ data: { brandId, capabilityKey: source.sample.capabilityKey, actorId, action: "sample_content_imported", toStatus: "enabled", config: asJson({ source: this.publicSource(source), ...importResult }), }, }); return counts; }); return { imported: true, alreadyImported: false, source: this.publicSource(source), counts: result, }; } private async resolveSource(brandId: string, requestedVersionId?: string) { const brand = await this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { templateKey: true, config: true }, }); if (!brand) throw new NotFoundException("品牌不存在"); const installation = requestedVersionId ? null : await this.prisma.brandTemplateInstallation.findUnique({ where: { brandId }, select: { templatePackageVersionId: true }, }); const versionId = requestedVersionId ?? installation?.templatePackageVersionId ?? undefined; if (!versionId) throw new BadRequestException("品牌没有精确模板包安装版本,必须先完成模板安装"); const version = await this.prisma.templatePackageVersion.findUnique({ where: { id: versionId }, }); if (!version) throw new BadRequestException("指定的模板包版本不存在"); if (version.status !== "published") throw new BadRequestException("只有已发布的模板包版本可用于 bootstrap"); const manifest = version.manifestSnapshot as unknown as TemplatePackageManifest; const issues = validateTemplatePackageManifest(manifest); if (issues.length) throw new BadRequestException(`模板包 manifest 无效:${issues.join(";")}`); if ( manifest.packageKey !== version.packageKey || manifest.version !== version.version || manifest.packageKey !== manifest.visualTemplateKey || !/^[a-f0-9]{64}$/.test(version.contentChecksum) || !manifest.supportedIndustryTemplates.includes(brand.templateKey) ) throw new BadRequestException("模板包版本与品牌行业或版本台账不匹配"); const sample = manifest.sampleContent?.[brand.templateKey]; if (!sample) throw new BadRequestException("该模板包没有当前行业的 bootstrap sampleContent"); const source: BootstrapSource = { kind: "package_version", version, manifest, sample }; const visualTemplateKey = manifest.visualTemplateKey; const visual = getVisualTemplate(visualTemplateKey); if (!visual || !isVisualTemplateCompatible(visual, brand.templateKey)) throw new BadRequestException("当前视觉模板与品牌行业不兼容"); if (source.sample.templateKey !== brand.templateKey) throw new BadRequestException("sampleContent 行业与品牌不匹配"); const fieldIssues = validateFieldSnapshot(source.sample.fields); if (fieldIssues.length) throw new BadRequestException( `bootstrap 表单字段无效:${fieldIssues.map((issue) => `${issue.path}: ${issue.message}`).join(";")}`, ); return { brand, source, visualTemplateKey }; } private async buildPlan(brandId: string, savedConfig: unknown, source: BootstrapSource) { const sample = source.sample; const configMerge = deepMergeMissing(record(sample.brandConfig), record(savedConfig)); const [offerings, trustContent, fields, enabledForm, previous] = await Promise.all([ this.prisma.offering.findMany({ where: { brandId }, select: { name: true } }), this.prisma.trustContent.findMany({ where: { brandId }, select: { type: true, title: true }, }), this.prisma.brandFieldDefinition.findMany({ where: { brandId, scope: "inquiry" }, select: { key: true }, }), this.prisma.inquiryForm.findFirst({ where: { brandId, isEnabled: true }, select: { id: true }, }), source.version ? this.prisma.templateBootstrapImport.findFirst({ where: { brandId, templatePackageVersionId: source.version.id, contentChecksum: source.version.contentChecksum, status: "imported", }, select: { id: true }, }) : Promise.resolve(null), ]); const offeringNames = new Set(offerings.map((item) => item.name)); const trustKeys = new Set(trustContent.map((item) => `${item.type}\0${item.title}`)); const fieldKeys = new Set(fields.map((item) => item.key)); const actions: Action[] = []; if (sample.brandConfig) { for (const key of configMerge.missingPaths) actions.push({ type: "brandConfig", key, action: "create" }); } for (const item of sample.offerings) { const key = String(item.name ?? "(missing name)"); actions.push({ type: "offerings", key, action: key !== "(missing name)" && !offeringNames.has(key) ? "create" : "skip", }); } for (const item of sample.trustContent) { const type = String(item.type ?? ""); const title = String(item.title ?? ""); const key = `${type}/${title}`; actions.push({ type: "trustContent", key, action: type && title && !trustKeys.has(`${type}\0${title}`) ? "create" : "skip", }); } for (const item of sample.fields) { const key = String(item.key ?? "(missing key)"); actions.push({ type: "fields", key, action: key !== "(missing key)" && !fieldKeys.has(key) ? "create" : "skip", }); } actions.push({ type: "inquiryForms", key: sample.inquiryFormName, action: enabledForm ? "skip" : "create", }); const count = (type: keyof Counts, action: Action["action"]) => actions.filter((item) => item.type === type && item.action === action).length; return { alreadyImported: Boolean(previous), counts: { brandConfig: count("brandConfig", "create"), offerings: count("offerings", "create"), trustContent: count("trustContent", "create"), fields: count("fields", "create"), inquiryForms: count("inquiryForms", "create"), } satisfies Counts, skipped: { brandConfig: 0, offerings: count("offerings", "skip"), trustContent: count("trustContent", "skip"), fields: count("fields", "skip"), inquiryForms: count("inquiryForms", "skip"), } satisfies Counts, actions, missingConfigKeys: configMerge.missingPaths, existingOfferingNames: offeringNames, existingTrustKeys: trustKeys, existingFieldKeys: fieldKeys, }; } private publicSource(source: BootstrapSource) { return { kind: source.kind, packageKey: source.manifest.packageKey, version: source.manifest.version, contentChecksum: source.version.contentChecksum, templatePackageVersionId: source.version.id, }; } }