feat: 完成真实咨询提交闭环

This commit is contained in:
que01 committed 2026-09-23 09:30:47 +08:00
1 parent 16b0967dc5
commit ba0069ae6d
9 files changed
+259 -70

No files matched your search

+103 -47
View File
@@ -167,7 +167,7 @@ export class PublicWorkspaceController {
modules,
fields,
offerings,
inquiryForm,
inquiryForms,
installation,
capabilityInstallations,
trustContents,
@@ -185,8 +185,12 @@ export class PublicWorkspaceController {
where: { brandId, isEnabled: true },
orderBy: { sortOrder: "asc" },
}),
this.prisma.inquiryForm.findFirst({
where: { brandId, isEnabled: true },
this.prisma.inquiryForm.findMany({
where: {
brandId,
isEnabled: true,
OR: [{ offeringId: null }, { offering: { isEnabled: true } }],
},
orderBy: { updatedAt: "desc" },
}),
this.prisma.brandTemplateInstallation.findFirst({
@@ -261,26 +265,26 @@ export class PublicWorkspaceController {
})),
};
});
const inquiryFields: RuntimeInquiryField[] = this.jsonArray(
inquiryForm?.fieldsSnapshot,
).flatMap((field) => {
if (!field || typeof field !== "object") return [];
const value = field as Record<string, unknown>;
if (typeof value.key !== "string" || typeof value.label !== "string") return [];
const type = [
"text",
"tel",
"number",
"select",
"radio",
"checkbox",
"textarea",
"date",
].includes(String(value.type))
? (value.type as RuntimeInquiryField["type"])
: "text";
return [{ key: value.key, label: value.label, type, required: value.required === true }];
});
const toInquiryFields = (snapshot: Prisma.JsonValue): RuntimeInquiryField[] =>
this.jsonArray(snapshot).flatMap((field) => {
if (!field || typeof field !== "object") return [];
const value = field as Record<string, unknown>;
if (typeof value.key !== "string" || typeof value.label !== "string") return [];
const type = [
"text",
"tel",
"number",
"select",
"radio",
"checkbox",
"textarea",
"date",
].includes(String(value.type))
? (value.type as RuntimeInquiryField["type"])
: "text";
return [{ key: value.key, label: value.label, type, required: value.required === true }];
});
const inquiryForm = inquiryForms[0] ?? null;
const runtimeWorkspace: RuntimeWorkspace = {
schemaVersion: "1.0.0",
brand: (brand ?? {}) as Record<string, unknown>,
@@ -293,18 +297,15 @@ export class PublicWorkspaceController {
},
modules: runtimeModules,
offerings: runtimeOfferings,
inquiryForms: inquiryForm
? [
{
key: inquiryForm.id,
version: String(inquiryForm.version),
purpose: this.formPurpose(inquiryForm.purpose),
target: inquiryForm.targetType === "offering" ? "offering" : "brand",
submissionAction: this.submissionAction(inquiryForm.submissionAction),
fields: inquiryFields,
},
]
: [],
inquiryForms: inquiryForms.map((form) => ({
key: form.id,
version: String(form.version),
purpose: this.formPurpose(form.purpose),
target: form.targetType === "offering" ? "offering" : "brand",
...(form.offeringId ? { targetId: form.offeringId } : {}),
submissionAction: this.submissionAction(form.submissionAction),
fields: toInquiryFields(form.fieldsSnapshot),
})),
capabilities: runtimeCapabilities,
plugins: runtimeCapabilities
.filter((capability) => capability.status === "enabled")
@@ -462,20 +463,46 @@ export class PublicInquiryFormController {
@Controller("customer/inquiry-submissions")
export class CustomerInquirySubmissionController {
constructor(private readonly prisma: PrismaService) {}
private present<T extends { customerSubject: string }>(
submission: T,
): Omit<T, "customerSubject"> {
const { customerSubject: _customerSubject, ...publicSubmission } = submission;
void _customerSubject;
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 } },
},
});
return submissions.map((submission) => this.present(submission));
}
@Post()
async create(
@Req() request: FastifyRequest,
@Body() body: CreateInquirySubmissionDto,
): Promise<unknown> {
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
if (!token) throw new UnauthorizedException("缺少客户登录态");
let identity;
try {
identity = readIdentity(token);
} catch {
throw new UnauthorizedException("客户登录态无效或已过期");
}
if (identity.role !== "customer") throw new ForbiddenException("无客户权限");
const identity = this.identity(request);
const form = await this.prisma.inquiryForm.findFirst({
where: {
id: body.formId,
@@ -485,17 +512,46 @@ export class CustomerInquirySubmissionController {
},
});
if (!form) throw new BadRequestException("咨询表单不存在");
return this.prisma.inquirySubmission.create({
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: body.values as Prisma.InputJsonValue,
activeFields: Object.fromEntries(Object.keys(body.values).map((key) => [key, true])),
values: values as Prisma.InputJsonValue,
activeFields: Object.fromEntries(Object.keys(values).map((key) => [key, true])),
},
});
return this.present(submission);
}
}