refactor: 将数据库访问从控制器下沉到服务层
This commit is contained in:
1 parent
f158f906d5
commit
3ae7b462f5
21 files changed
+1046
-857
No files matched your search
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
ForbiddenException,
|
||||
@@ -10,19 +9,14 @@ import {
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
} from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
import { CreateInquirySubmissionDto } from "../../booking.dto.js";
|
||||
import { BrandReleaseService } from "../../brand-release.service.js";
|
||||
import { CustomerInquirySubmissionService } from "./customer-inquiry-submission.service.js";
|
||||
|
||||
@Controller("customer/inquiry-submissions")
|
||||
export class CustomerInquirySubmissionController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly releases: BrandReleaseService,
|
||||
) {}
|
||||
constructor(private readonly submissions: CustomerInquirySubmissionService) {}
|
||||
private present<T extends { customerSubject: string; adminNote?: string | null }>(submission: T) {
|
||||
const {
|
||||
customerSubject: _customerSubject,
|
||||
@@ -49,36 +43,18 @@ export class CustomerInquirySubmissionController {
|
||||
@Get()
|
||||
async list(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const submissions = await this.prisma.inquirySubmission.findMany({
|
||||
where: { brandId: identity.brandId, customerSubject: identity.subject },
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
inquiryForm: { select: { name: true, purpose: true } },
|
||||
offering: { select: { id: true, name: true } },
|
||||
statusHistory: {
|
||||
select: { fromStatus: true, toStatus: true, createdAt: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
},
|
||||
},
|
||||
});
|
||||
const submissions = await this.submissions.listForCustomer(identity.brandId, identity.subject);
|
||||
return submissions.map((submission) => this.present(submission));
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
async get(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const submission = await this.prisma.inquirySubmission.findFirst({
|
||||
where: { id, brandId: identity.brandId, customerSubject: identity.subject },
|
||||
include: {
|
||||
inquiryForm: { select: { name: true, purpose: true } },
|
||||
offering: { select: { id: true, name: true } },
|
||||
statusHistory: {
|
||||
select: { fromStatus: true, toStatus: true, createdAt: true },
|
||||
orderBy: { createdAt: "asc" },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!submission) throw new NotFoundException("咨询记录不存在");
|
||||
const submission = await this.submissions.getForCustomer(
|
||||
identity.brandId,
|
||||
identity.subject,
|
||||
id,
|
||||
);
|
||||
return this.present(submission);
|
||||
}
|
||||
|
||||
@@ -88,92 +64,7 @@ export class CustomerInquirySubmissionController {
|
||||
@Body() body: CreateInquirySubmissionDto,
|
||||
): Promise<unknown> {
|
||||
const identity = this.identity(request);
|
||||
const snapshot = await this.releases.getPublishedSnapshot(identity.brandId);
|
||||
const publishedForm = snapshot && this.releases.publishedForm(snapshot, body.formId);
|
||||
if (!publishedForm) throw new BadRequestException("咨询表单不存在或品牌尚未发布");
|
||||
const form = await this.prisma.inquiryForm.findFirst({
|
||||
where: {
|
||||
id: body.formId,
|
||||
brandId: identity.brandId,
|
||||
isEnabled: true,
|
||||
},
|
||||
});
|
||||
if (!form) throw new BadRequestException("咨询表单不存在");
|
||||
const offeringId =
|
||||
typeof publishedForm.offeringId === "string" ? publishedForm.offeringId : null;
|
||||
if (offeringId) {
|
||||
const offering = await this.prisma.offering.findFirst({
|
||||
where: { id: offeringId, brandId: identity.brandId, isEnabled: true },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!offering) throw new BadRequestException("当前业务提供项不可用");
|
||||
}
|
||||
const capabilityKey = publishedForm.purpose === "quote-request" ? "quote-request" : "inquiry";
|
||||
const capability = await this.prisma.capabilityInstallation.findUnique({
|
||||
where: {
|
||||
brandId_capabilityKey: { brandId: identity.brandId, capabilityKey },
|
||||
},
|
||||
});
|
||||
if (capability && capability.status !== "enabled")
|
||||
throw new BadRequestException("当前咨询能力不可用");
|
||||
const fields = Array.isArray(publishedForm.fieldsSnapshot)
|
||||
? (publishedForm.fieldsSnapshot as Array<Record<string, unknown>>)
|
||||
: [];
|
||||
for (const field of fields) {
|
||||
const key = typeof field.key === "string" ? field.key : "";
|
||||
const label = typeof field.label === "string" ? field.label : key;
|
||||
const value = body.values[key];
|
||||
const textValue = typeof value === "string" || typeof value === "number" ? String(value) : "";
|
||||
const empty = value === undefined || value === null || value === "";
|
||||
if (field.required === true && empty) throw new BadRequestException(`${label}不能为空`);
|
||||
if (empty) continue;
|
||||
if ((field.type === "phone" || field.type === "tel") && !/^1\d{10}$/.test(textValue))
|
||||
throw new BadRequestException(`${label}格式不正确`);
|
||||
if (field.type === "number" && !Number.isFinite(Number(value)))
|
||||
throw new BadRequestException(`${label}必须是数字`);
|
||||
}
|
||||
const visibleFields = fields.filter((field) => this.isVisibleField(field, body.values));
|
||||
const allowedKeys = new Set(visibleFields.map((field) => String(field.key)));
|
||||
const values = Object.fromEntries(
|
||||
Object.entries(body.values).filter(([key]) => allowedKeys.has(key)),
|
||||
);
|
||||
const submission = await this.prisma.inquirySubmission.create({
|
||||
data: {
|
||||
brandId: identity.brandId,
|
||||
customerSubject: identity.subject,
|
||||
inquiryFormId: form.id,
|
||||
offeringId,
|
||||
formVersion: Number(publishedForm.version),
|
||||
fieldsSnapshot: publishedForm.fieldsSnapshot as Prisma.InputJsonValue,
|
||||
values: values as Prisma.InputJsonValue,
|
||||
activeFields: Object.fromEntries(Object.keys(values).map((key) => [key, true])),
|
||||
},
|
||||
});
|
||||
const submission = await this.submissions.create(identity.brandId, identity.subject, body);
|
||||
return this.present(submission);
|
||||
}
|
||||
|
||||
private visibilityRuleMatches(rule: unknown, values: Record<string, unknown>): boolean {
|
||||
if (!rule || typeof rule !== "object") return true;
|
||||
const item = rule as Record<string, unknown>;
|
||||
if (typeof item.field !== "string") return true;
|
||||
const value = values[item.field];
|
||||
switch (item.operator) {
|
||||
case "exists":
|
||||
return Array.isArray(value) ? value.length > 0 : Boolean(value);
|
||||
case "equals":
|
||||
return value === item.value;
|
||||
case "not-equals":
|
||||
return value !== item.value;
|
||||
case "in":
|
||||
return Array.isArray(item.value) && typeof value === "string" && item.value.includes(value);
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private isVisibleField(field: Record<string, unknown>, values: Record<string, unknown>): boolean {
|
||||
return (Array.isArray(field.visibleWhen) ? field.visibleWhen : []).every((rule) =>
|
||||
this.visibilityRuleMatches(rule, values),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user