refactor: 将数据库访问从控制器下沉到服务层

This commit is contained in:
que01 committed 2026-10-14 17:53:49 +08:00
1 parent f158f906d5
commit 3ae7b462f5
21 files changed
+1046 -857

No files matched your search

@@ -0,0 +1,153 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { validateFieldSnapshot } from "@personal-brand/validation";
import { PrismaService } from "../../prisma.service.js";
import type {
CreateFieldDefinitionDto,
CreateInquiryFormDto,
UpdateFieldDefinitionDto,
UpdateInquiryFormDto,
UpdateInquirySubmissionDto,
} from "../../admin.dto.js";
@Injectable()
export class AdminInquiryService {
constructor(private readonly prisma: PrismaService) {}
createField(brandId: string, body: CreateFieldDefinitionDto) {
return this.prisma.brandFieldDefinition.create({
data: {
...body,
brandId,
source: "custom",
options: body.options as Prisma.InputJsonValue,
visibleWhen: body.visibleWhen as Prisma.InputJsonValue,
},
});
}
async updateField(brandId: string, id: string, body: UpdateFieldDefinitionDto) {
const item = await this.prisma.brandFieldDefinition.findFirst({
where: { id, brandId },
});
if (!item) throw new BadRequestException("品牌字段不存在");
const { options, visibleWhen, ...fields } = body;
return this.prisma.brandFieldDefinition.update({
where: { id },
data: {
...fields,
...(options === undefined ? {} : { options: options as Prisma.InputJsonValue }),
...(visibleWhen === undefined ? {} : { visibleWhen: visibleWhen as Prisma.InputJsonValue }),
},
});
}
async deleteField(brandId: string, id: string) {
const item = await this.prisma.brandFieldDefinition.findFirst({
where: { id, brandId, source: "custom" },
});
if (!item) throw new BadRequestException("自定义字段不存在或不可删除");
await this.prisma.brandFieldDefinition.delete({ where: { id } });
return { deleted: true };
}
listForms(brandId: string) {
return this.prisma.inquiryForm.findMany({
where: { brandId },
orderBy: { updatedAt: "desc" },
});
}
async createForm(brandId: string, body: CreateInquiryFormDto) {
if (validateFieldSnapshot(body.fieldsSnapshot).length)
throw new BadRequestException("咨询表单字段定义无效");
const { offeringId, ...fields } = body;
const targetType = await this.resolveFormTarget(brandId, offeringId);
return this.prisma.inquiryForm.create({
data: {
...fields,
brandId,
targetType,
offeringId: offeringId ?? null,
version: 1,
fieldsSnapshot: body.fieldsSnapshot as Prisma.InputJsonValue,
},
});
}
async updateForm(brandId: string, id: string, body: UpdateInquiryFormDto) {
const item = await this.prisma.inquiryForm.findFirst({
where: { id, brandId },
});
if (!item) throw new BadRequestException("咨询表单不存在");
const { fieldsSnapshot, offeringId, ...fields } = body;
if (fieldsSnapshot !== undefined && validateFieldSnapshot(fieldsSnapshot).length)
throw new BadRequestException("咨询表单字段定义无效");
const target =
offeringId === undefined
? {}
: { offeringId, targetType: await this.resolveFormTarget(brandId, offeringId) };
return this.prisma.inquiryForm.update({
where: { id },
data: {
...fields,
...target,
...(fieldsSnapshot === undefined
? {}
: { fieldsSnapshot: fieldsSnapshot as Prisma.InputJsonValue }),
...(fieldsSnapshot === undefined ? {} : { version: { increment: 1 } }),
},
});
}
listSubmissions(brandId: string) {
return this.prisma.inquirySubmission.findMany({
where: { brandId },
include: {
inquiryForm: { select: { name: true } },
offering: { select: { id: true, name: true } },
},
orderBy: { createdAt: "desc" },
});
}
async updateSubmission(brandId: string, id: string, body: UpdateInquirySubmissionDto) {
const item = await this.prisma.inquirySubmission.findFirst({
where: { id, brandId },
});
if (!item) throw new BadRequestException("咨询记录不存在");
return this.prisma.$transaction(async (tx) => {
const updated = await tx.inquirySubmission.update({
where: { id },
data: {
status: body.status,
...(body.adminNote === undefined ? {} : { adminNote: body.adminNote }),
},
});
if (item.status !== body.status || body.adminNote !== undefined) {
await tx.inquirySubmissionStatusHistory.create({
data: {
submissionId: id,
fromStatus: item.status,
toStatus: body.status,
adminNote: body.adminNote ?? null,
},
});
}
return updated;
});
}
private async resolveFormTarget(
brandId: string,
offeringId: string | null | undefined,
): Promise<"brand" | "offering"> {
if (offeringId === undefined || offeringId === null) return "brand";
const offering = await this.prisma.offering.findFirst({
where: { id: offeringId, brandId },
select: { id: true },
});
if (!offering) throw new BadRequestException("关联的业务提供项不存在或不属于当前品牌");
return "offering";
}
}
@@ -0,0 +1,124 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { getTemplateSampleContent } from "@personal-brand/config";
import { validateFieldSnapshot } from "@personal-brand/validation";
import { PrismaService } from "../../prisma.service.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
@Injectable()
export class AdminSampleContentService {
constructor(
private readonly prisma: PrismaService,
private readonly templateWorkspace: TemplateWorkspaceService,
) {}
async preview(brandId: string) {
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
const sample = getTemplateSampleContent(templateKey);
if (!sample) throw new BadRequestException("模板示例内容不存在");
const [offerings, trustContent, fields, enabledForms] = await Promise.all([
this.prisma.offering.count({ where: { brandId } }),
this.prisma.trustContent.count({ where: { brandId } }),
this.prisma.brandFieldDefinition.count({ where: { brandId, source: "sample" } }),
this.prisma.inquiryForm.count({ where: { brandId, isEnabled: true } }),
]);
return {
templateKey: sample.templateKey,
alreadyImported: offerings > 0 || trustContent > 0 || fields > 0,
counts: {
offerings: sample.offerings.length,
trustContent: sample.trustContent.length,
fields: sample.fields.length,
inquiryForms: 1,
},
willCreateInquiryForm: enabledForms === 0,
};
}
async import(brandId: string, actorId: string) {
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
const sample = getTemplateSampleContent(templateKey);
if (!sample) throw new BadRequestException("模板示例内容不存在");
if (validateFieldSnapshot(sample.fields).length)
throw new BadRequestException("模板咨询表单示例字段无效");
const existing = await this.prisma.brandFieldDefinition.count({
where: { brandId, source: "sample" },
});
const existingOffering = await this.prisma.offering.count({
where: { brandId, name: { in: sample.offerings.map((item) => item.name) } },
});
if (existing || existingOffering) throw new BadRequestException("示例内容已经导入");
const result = await this.prisma.$transaction(async (tx) => {
const offerings = await tx.offering.createMany({
data: sample.offerings.map((item, sortOrder) => ({
brandId,
kind: item.kind,
name: item.name,
summary: item.summary,
config: { categoryKey: item.categoryKey },
sortOrder,
isEnabled: true,
})),
});
const trust = await tx.trustContent.createMany({
data: sample.trustContent.map((item, sortOrder) => ({
brandId,
type: item.type,
title: item.title,
content: item.content,
...(item.config ? { config: item.config as Prisma.InputJsonValue } : {}),
sortOrder,
isPublished: false,
})),
});
const fields = await tx.brandFieldDefinition.createMany({
data: sample.fields.map((item, sortOrder) => ({
brandId,
scope: "inquiry",
key: item.key,
label: item.label,
type: item.type,
sortOrder,
source: "sample",
required: item.required,
})),
});
const hasEnabledForm = await tx.inquiryForm.count({ where: { brandId, isEnabled: true } });
const inquiryForm = hasEnabledForm
? null
: await tx.inquiryForm.create({
data: {
brandId,
name: sample.inquiryFormName,
purpose: "inquiry",
targetType: "brand",
submissionAction: "create-inquiry",
fieldsSnapshot: sample.fields,
isEnabled: true,
},
});
await tx.capabilityAuditLog.create({
data: {
brandId,
capabilityKey: sample.capabilityKey,
actorId,
action: "sample_content_imported",
toStatus: "enabled",
config: {
offerings: offerings.count,
trustContent: trust.count,
fields: fields.count,
inquiryForms: inquiryForm ? 1 : 0,
},
},
});
return {
offerings: offerings.count,
trustContent: trust.count,
fields: fields.count,
inquiryForms: inquiryForm ? 1 : 0,
};
});
return { imported: true, counts: result };
}
}
@@ -0,0 +1,101 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import {
capabilityMetadata,
capabilityPlugins,
capabilityRegistry,
getBrandTemplate,
validateCapabilityConfig,
} from "@personal-brand/config";
import { PrismaService } from "../../prisma.service.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import type { UpdateCapabilityInstallationDto } from "../../admin.dto.js";
@Injectable()
export class AdminWorkspaceCapabilitiesService {
constructor(
private readonly prisma: PrismaService,
private readonly templateWorkspace: TemplateWorkspaceService,
) {}
async list(brandId: string) {
const [templateKey, installations] = await Promise.all([
this.templateWorkspace.getEffectiveTemplateKey(brandId),
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
]);
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
const template = getBrandTemplate(templateKey);
const optionalCapabilityKeys = Object.entries(capabilityRegistry)
.filter(([, definition]) => "optional" in definition && definition.optional)
.map(([key]) => key);
return [...new Set([...(template?.capabilities ?? []), ...optionalCapabilityKeys])]
.map((key) => capabilityRegistry[key as keyof typeof capabilityRegistry])
.filter(Boolean)
.map((definition) => {
const item = installed.get(definition.key);
const metadata = capabilityMetadata(definition.key);
return {
id: item?.id ?? null,
capabilityKey: definition.key,
capabilityVersion: item?.capabilityVersion ?? definition.version,
status: item?.status ?? "enabled",
config: item?.config ?? {},
source: item ? "brand" : "template",
...(metadata ?? {}),
updatedAt: item?.updatedAt ?? null,
};
});
}
async update(
brandId: string,
actorId: string,
key: string,
body: UpdateCapabilityInstallationDto,
) {
const template = getBrandTemplate(
await this.templateWorkspace.getEffectiveTemplateKey(brandId),
);
if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins))
throw new BadRequestException("能力未被当前模板声明");
const existing = await this.prisma.capabilityInstallation.findUnique({
where: { brandId_capabilityKey: { brandId, capabilityKey: key } },
});
const definition = capabilityRegistry[key as keyof typeof capabilityRegistry];
if (definition && "disablePolicy" in definition && definition.disablePolicy === "disabled")
throw new BadRequestException("核心能力不可移除");
const configErrors = validateCapabilityConfig(key as never, body.config);
if (configErrors === null) throw new BadRequestException("能力配置字段无效");
if (Object.keys(configErrors).length)
throw new BadRequestException({ message: "能力配置字段无效", errors: configErrors });
return this.prisma.$transaction(async (tx) => {
const installation = await tx.capabilityInstallation.upsert({
where: { brandId_capabilityKey: { brandId, capabilityKey: key } },
create: {
brandId,
capabilityKey: key,
capabilityVersion: definition?.version ?? "1.0.0",
status: body.status,
config: (body.config ?? {}) as Prisma.InputJsonValue,
},
update: {
...(definition ? { capabilityVersion: definition.version } : {}),
status: body.status,
...(body.config === undefined ? {} : { config: body.config as Prisma.InputJsonValue }),
},
});
await tx.capabilityAuditLog.create({
data: {
brandId,
capabilityKey: key,
actorId,
action: existing ? "updated" : "installed",
fromStatus: existing?.status ?? null,
toStatus: body.status,
config: (body.config ?? existing?.config ?? {}) as Prisma.InputJsonValue,
},
});
return installation;
});
}
}
@@ -5,7 +5,7 @@ import {
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
} from "@personal-brand/config";
import { PublicWorkspaceService } from "../public/public-workspace.controller.js";
import { PublicWorkspaceService } from "../public/public-workspace.service.js";
@Injectable()
export class AdminWorkspaceService {