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(submission: T) { const { customerSubject: _customerSubject, adminNote: _adminNote, ...publicSubmission } = submission; void _customerSubject; void _adminNote; return publicSubmission; } private identity(request: FastifyRequest): ReturnType { 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 { 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 { 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 { 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>) : []; 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 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); } }