refactor: 完成公开与客户控制器拆分

This commit is contained in:
que01 committed 2026-09-23 12:40:40 +08:00
1 parent 178ffc2c11
commit 4902a564f0
5 files changed
+214 -223

No files matched your search

@@ -0,0 +1,137 @@
import {
BadRequestException,
Body,
Controller,
ForbiddenException,
Get,
NotFoundException,
Param,
Post,
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";
@Controller("customer/inquiry-submissions")
export class CustomerInquirySubmissionController {
constructor(private readonly prisma: PrismaService) {}
private present<T extends { customerSubject: string; adminNote?: string | null }>(submission: T) {
const {
customerSubject: _customerSubject,
adminNote: _adminNote,
...publicSubmission
} = submission;
void _customerSubject;
void _adminNote;
return publicSubmission;
}
private identity(request: FastifyRequest): ReturnType<typeof readIdentity> {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少客户登录态");
try {
const identity = readIdentity(token);
if (identity.role !== "customer") throw new ForbiddenException("无客户权限");
return identity;
} catch (error) {
if (error instanceof ForbiddenException) throw error;
throw new UnauthorizedException("客户登录态无效或已过期");
}
}
@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" },
},
},
});
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("咨询记录不存在");
return this.present(submission);
}
@Post()
async create(
@Req() request: FastifyRequest,
@Body() body: CreateInquirySubmissionDto,
): Promise<unknown> {
const identity = this.identity(request);
const form = await this.prisma.inquiryForm.findFirst({
where: {
id: body.formId,
brandId: identity.brandId,
isEnabled: true,
OR: [{ offeringId: null }, { offering: { isEnabled: true } }],
},
});
if (!form) throw new BadRequestException("咨询表单不存在");
const capabilityKey = form.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(form.fieldsSnapshot)
? (form.fieldsSnapshot as Array<Record<string, unknown>>)
: [];
for (const field of fields) {
const key = typeof field.key === "string" ? field.key : "";
const value = body.values[key];
const empty = value === undefined || value === null || value === "";
if (field.required === true && empty)
throw new BadRequestException(`${String(field.label ?? key)}不能为空`);
if (empty) continue;
if ((field.type === "phone" || field.type === "tel") && !/^1\d{10}$/.test(String(value)))
throw new BadRequestException(`${String(field.label ?? key)}格式不正确`);
if (field.type === "number" && !Number.isFinite(Number(value)))
throw new BadRequestException(`${String(field.label ?? key)}必须是数字`);
}
const allowedKeys = new Set(fields.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: form.offeringId,
formVersion: form.version,
fieldsSnapshot: form.fieldsSnapshot as Prisma.InputJsonValue,
values: values as Prisma.InputJsonValue,
activeFields: Object.fromEntries(Object.keys(values).map((key) => [key, true])),
},
});
return this.present(submission);
}
}