import { BadRequestException, ConflictException, Injectable, NotFoundException, } from "@nestjs/common"; import { Prisma } from "@prisma/client"; import { getBrandTemplate, getVisualTemplate, isVisualTemplateCompatible, getDefaultVisualTemplateKey, getTemplatePackageManifestForVisualKey, } from "@personal-brand/config"; import { isTrustContentComplete } from "@personal-brand/types"; import { PrismaService } from "./prisma.service.js"; import { BrandReleaseService } from "./brand-release.service.js"; import { validateFieldSnapshot } from "@personal-brand/validation"; @Injectable() export class BrandReleaseApiService { constructor( private readonly prisma: PrismaService, private readonly snapshots: BrandReleaseService, ) {} async list(brandId: string): Promise { return this.prisma.brandRelease.findMany({ where: { brandId }, orderBy: { version: "desc" }, select: { id: true, version: true, status: true, note: true, actorId: true, createdAt: true, revokedAt: true, revokedBy: true, }, }); } async readiness( brandId: string, database: Prisma.TransactionClient = this.prisma, ): Promise<{ ready: boolean; checks: Array<{ key: string; label: string; passed: boolean; help?: string; destination?: string; }>; }> { const brand = await database.brandProfile.findUnique({ where: { id: brandId }, select: { name: true, tagline: true, description: true, templateKey: true, config: true }, }); const installation = await database.brandTemplateInstallation.findFirst({ where: { brandId }, orderBy: { updatedAt: "desc" }, }); const template = getBrandTemplate(installation?.templateKey ?? brand?.templateKey ?? ""); const config = this.jsonObject(brand?.config); const visualKey = typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : getDefaultVisualTemplateKey(brand?.templateKey ?? "personal"); const visual = getVisualTemplate(visualKey); const packageManifest = getTemplatePackageManifestForVisualKey(visualKey); const [offerings, forms, trustItems] = await Promise.all([ database.offering.findMany({ where: { brandId, isEnabled: true }, select: { id: true, name: true, coverUrl: true, config: true }, }), database.inquiryForm.findMany({ where: { brandId, isEnabled: true }, select: { offeringId: true, fieldsSnapshot: true }, }), database.trustContent.findMany({ where: { brandId, isPublished: true }, select: { type: true, title: true, content: true, config: true }, }), ]); const validTrustItems = trustItems.filter((item) => isTrustContentComplete( item, packageManifest?.trustContentTypes?.find((type) => type.type === item.type), ), ); const offeringIds = new Set(offerings.map((item) => item.id)); const usableForms = forms.filter( (form) => (form.offeringId === null || offeringIds.has(form.offeringId)) && Array.isArray(form.fieldsSnapshot) && form.fieldsSnapshot.length > 0 && validateFieldSnapshot(form.fieldsSnapshot).length === 0, ); const checks: Array<{ key: string; label: string; passed: boolean; help?: string; destination?: string; }> = [ { key: "brand", label: "请先完善品牌名称", passed: Boolean(brand?.name.trim()), destination: "/admin/brand", }, { key: "positioning", label: "请先完善品牌定位和介绍", passed: Boolean(brand?.tagline?.trim() && brand.description?.trim()), destination: "/admin/brand", }, { key: "template", label: "当前行业模板不存在", passed: Boolean(template) }, { key: "visual", label: "当前视觉模板不适配行业模板", passed: Boolean(visual && template && isVisualTemplateCompatible(visual, template.key)), destination: "/admin/publication", }, { key: "offerings", label: "至少需要一项已启用的业务提供项", passed: offerings.length > 0, destination: "/admin/services", }, { key: "forms", label: "至少需要一个可用的咨询表单", passed: usableForms.length > 0, destination: "/admin/workspace", }, { key: "trust", label: "至少需要一条已发布的信任内容", passed: validTrustItems.length > 0, destination: "/admin/trust", }, ]; const publishedTrustTypes = new Set(validTrustItems.map((item) => item.type)); for (const type of packageManifest?.trustContentTypes ?? []) { if (type.required !== true) continue; checks.push({ key: `trust:${type.type}`, label: `请完善${type.label}`, passed: publishedTrustTypes.has(type.type) && (type.maxPublishedItems === undefined || trustItems.filter((item) => item.type === type.type).length <= type.maxPublishedItems), help: [ "请完整填写该区块的可编辑字段。", type.maxPublishedItems === undefined ? undefined : `此区块最多保留 ${type.maxPublishedItems} 条公开记录。`, type.help, ] .filter(Boolean) .join(" "), destination: "/admin/trust", }); } const brandRecord = { ...this.jsonObject(brand), config }; for (const section of packageManifest?.admin.sections ?? []) { for (const field of section.fields) { if (field.required !== true) continue; const present = this.resolveBinding(field.binding, { brand: brandRecord, offerings, }); checks.push({ key: `content:${section.key}:${field.key}`, label: present ? `${section.title}:${field.label}` : `请补充「${section.title}」中的「${field.label}」`, passed: present, help: section.description, destination: section.target === "offering" ? "/admin/services" : section.target === "trust" ? "/admin/trust" : section.target === "inquiry" ? "/admin/workspace" : "/admin/brand", }); } } for (const slot of packageManifest?.assetSlots ?? []) { if (slot.required !== true) continue; const present = slot.target === "offering" ? offerings.length > 0 && offerings.every((item) => Boolean(item.coverUrl?.trim())) : slot.target === "brand" ? this.resolveBinding(slot.binding, { brand: brandRecord, offerings }) : trustItems.length > 0; checks.push({ key: `asset:${String(slot.key)}`, label: present ? `已添加${String(slot.label)}` : `请添加${String(slot.label)}`, passed: present, help: String(slot.help), destination: slot.target === "offering" ? "/admin/services" : "/admin/brand", }); } return { ready: checks.every((check) => check.passed), checks }; } private resolveBinding( binding: string, context: { brand: Record; offerings: Array<{ id: string; name: string; coverUrl: string | null; config: unknown }>; }, ): boolean { const segments = binding.split("."); let value: unknown; if (segments[0] === "brand") value = context.brand; else if (segments[0] === "offering") value = context.offerings[0]; else return false; for (const segment of segments.slice(1)) { if (!value || typeof value !== "object" || Array.isArray(value)) return false; value = (value as Record)[segment]; } return typeof value === "string" ? value.trim().length > 0 : Boolean(value); } async publish(brandId: string, actorId: string, note?: string): Promise { return this.withVersionRetry(() => this.prisma.$transaction( async (tx) => { await this.validateForPublish(brandId, tx); const snapshot = await this.snapshots.buildSnapshot(brandId, tx); const latest = await tx.brandRelease.findFirst({ where: { brandId }, orderBy: { version: "desc" }, select: { version: true }, }); await tx.brandRelease.updateMany({ where: { brandId, status: "published" }, data: { status: "superseded" }, }); return tx.brandRelease.create({ data: { brandId, version: (latest?.version ?? 0) + 1, status: "published", snapshot: this.snapshots.toPrismaJson(snapshot), actorId, ...(note === undefined ? {} : { note }), }, }); }, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, ), ); } async rollback( brandId: string, actorId: string, version: number, note?: string, ): Promise { return this.withVersionRetry(() => this.prisma.$transaction( async (tx) => { const source = await tx.brandRelease.findFirst({ where: { brandId, version, status: { in: ["published", "superseded"] } }, }); if (!source) throw new NotFoundException("发布版本不存在"); const snapshot = this.withCurrentTimestamp(source.snapshot); const latest = await tx.brandRelease.findFirst({ where: { brandId }, orderBy: { version: "desc" }, select: { version: true }, }); await tx.brandRelease.updateMany({ where: { brandId, status: "published" }, data: { status: "superseded" }, }); return tx.brandRelease.create({ data: { brandId, version: (latest?.version ?? 0) + 1, status: "published", snapshot, actorId, note: note ?? `回滚自版本 ${version}`, }, }); }, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, ), ); } async revoke(brandId: string, actorId: string): Promise { return this.withVersionRetry(() => this.prisma.$transaction( async (tx) => { const current = await tx.brandRelease.findFirst({ where: { brandId, status: "published" }, orderBy: { version: "desc" }, }); if (!current) throw new NotFoundException("当前没有已发布版本"); return tx.brandRelease.update({ where: { id: current.id }, data: { status: "revoked", revokedAt: new Date(), revokedBy: actorId }, select: { id: true, version: true, status: true, revokedAt: true, revokedBy: true }, }); }, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, ), ); } private async validateForPublish( brandId: string, database: Prisma.TransactionClient, ): Promise { const readiness = await this.readiness(brandId, database); const missing = readiness.checks.find((check) => !check.passed); if (missing) throw new BadRequestException(missing.label); } private async withVersionRetry(operation: () => Promise): Promise { for (let attempt = 0; attempt < 3; attempt += 1) { try { return await operation(); } catch (error) { if ( !(error instanceof Prisma.PrismaClientKnownRequestError) || !["P2002", "P2034"].includes(error.code) ) throw error; if (attempt === 2) throw new ConflictException("发布版本冲突,请重试"); } } throw new ConflictException("发布版本冲突,请重试"); } private jsonObject(value: unknown): Record { return value && typeof value === "object" && !Array.isArray(value) ? (value as Record) : {}; } private withCurrentTimestamp(value: Prisma.JsonValue): Prisma.InputJsonValue { const snapshot = this.jsonObject(value); return { ...snapshot, generatedAt: new Date().toISOString() }; } }