import { BadRequestException, Injectable } from "@nestjs/common"; import { Prisma } from "@prisma/client"; import { validateTemplatePackageManifest } from "@personal-brand/config"; import type { TemplatePackageManifest } from "@personal-brand/config"; import type { CreateTrustContentDto, UpdateTrustContentDto } from "../admin.dto.js"; import { PrismaService } from "../prisma.service.js"; import { record } from "./manifest-diff.helpers.js"; @Injectable() export class TrustContentService { constructor(private readonly prisma: PrismaService) {} async getTrustContentTypes(brandId: string): Promise { const installation = await this.prisma.brandTemplateInstallation.findUnique({ where: { brandId }, include: { templatePackageVersion: true }, }); if (!installation?.templatePackageVersion) throw new BadRequestException("品牌没有锁定精确视觉模板包版本"); const manifest = record( installation.templatePackageVersion.manifestSnapshot, ) as unknown as TemplatePackageManifest; if (validateTemplatePackageManifest(manifest).length) throw new BadRequestException("当前安装的模板包不符合统一模板契约"); return manifest.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 }), }, }); } listTrustContent(brandId: string) { return this.prisma.trustContent.findMany({ where: { brandId }, orderBy: [{ type: "asc" }, { sortOrder: "asc" }], }); } async deleteTrustContent(brandId: string, id: string) { const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } }); if (!item) throw new BadRequestException("信任内容不存在"); await this.prisma.trustContent.delete({ where: { id } }); return { deleted: true }; } }