feat: 完成真实咨询提交闭环
This commit is contained in:
1 parent
16b0967dc5
commit
ba0069ae6d
9 files changed
+259
-70
No files matched your search
+8
@@ -0,0 +1,8 @@
|
||||
ALTER TABLE "InquirySubmission" ADD COLUMN "customerSubject" TEXT;
|
||||
|
||||
UPDATE "InquirySubmission" SET "customerSubject" = 'legacy' WHERE "customerSubject" IS NULL;
|
||||
|
||||
ALTER TABLE "InquirySubmission" ALTER COLUMN "customerSubject" SET NOT NULL;
|
||||
|
||||
CREATE INDEX "InquirySubmission_brandId_customerSubject_createdAt_idx"
|
||||
ON "InquirySubmission"("brandId", "customerSubject", "createdAt");
|
||||
@@ -190,6 +190,7 @@ model InquirySubmission {
|
||||
brandId String
|
||||
inquiryFormId String
|
||||
offeringId String?
|
||||
customerSubject String
|
||||
brand BrandProfile @relation(fields: [brandId], references: [id], onDelete: Cascade)
|
||||
inquiryForm InquiryForm @relation(fields: [inquiryFormId], references: [id], onDelete: Restrict)
|
||||
offering Offering? @relation(fields: [offeringId], references: [id], onDelete: SetNull)
|
||||
@@ -203,6 +204,7 @@ model InquirySubmission {
|
||||
statusHistory InquirySubmissionStatusHistory[]
|
||||
createdAt DateTime @default(now())
|
||||
@@index([brandId, createdAt])
|
||||
@@index([brandId, customerSubject, createdAt])
|
||||
@@index([inquiryFormId, formVersion])
|
||||
}
|
||||
|
||||
|
||||
+103
-47
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -462,7 +462,9 @@ test("admin can create and version an inquiry form", async () => {
|
||||
const updated = await request(`/admin/workspace/forms/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { fieldsSnapshot: [{ key: "budget", type: "number", label: "预算" }] },
|
||||
payload: {
|
||||
fieldsSnapshot: [{ key: "budget", type: "number", label: "预算", required: true }],
|
||||
},
|
||||
});
|
||||
assert.equal(updated.statusCode, 200);
|
||||
assert.equal(JSON.parse(updated.body).version, 2);
|
||||
@@ -475,6 +477,27 @@ test("admin can create and version an inquiry form", async () => {
|
||||
});
|
||||
assert.equal(blockedSubmission.statusCode, 400);
|
||||
await prisma.offering.update({ where: { id: offering.id }, data: { isEnabled: true } });
|
||||
const missingRequired = await request("/customer/inquiry-submissions", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
payload: { formId: id, values: {} },
|
||||
});
|
||||
assert.equal(missingRequired.statusCode, 400);
|
||||
const capability = await prisma.capabilityInstallation.create({
|
||||
data: {
|
||||
brandId,
|
||||
capabilityKey: "inquiry",
|
||||
capabilityVersion: "1.0.0",
|
||||
status: "disabled",
|
||||
},
|
||||
});
|
||||
const blockedCapability = await request("/customer/inquiry-submissions", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
payload: { formId: id, values: { budget: 1000 } },
|
||||
});
|
||||
assert.equal(blockedCapability.statusCode, 400);
|
||||
await prisma.capabilityInstallation.delete({ where: { id: capability.id } });
|
||||
const publicForm = await request(`/public/inquiry-forms/${id}`);
|
||||
assert.equal(publicForm.statusCode, 200);
|
||||
const publicOffering = await request(`/public/offerings/${offering.id}`);
|
||||
@@ -483,14 +506,34 @@ test("admin can create and version an inquiry form", async () => {
|
||||
const publicWorkspace = await request("/public/workspace");
|
||||
assert.equal(publicWorkspace.statusCode, 200);
|
||||
assert.equal(JSON.parse(publicWorkspace.body).inquiryForm.id, id);
|
||||
assert.ok(
|
||||
JSON.parse(publicWorkspace.body).inquiryForms.some(
|
||||
(form) => form.key === id && form.targetId === offering.id,
|
||||
),
|
||||
);
|
||||
const submission = await request("/customer/inquiry-submissions", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
payload: { formId: id, values: { project: "品牌升级" } },
|
||||
payload: { formId: id, values: { budget: 1000, ignored: "not persisted" } },
|
||||
});
|
||||
assert.equal(submission.statusCode, 201);
|
||||
assert.equal(JSON.parse(submission.body).formVersion, 2);
|
||||
assert.equal(JSON.parse(submission.body).offeringId, offering.id);
|
||||
assert.deepEqual(JSON.parse(submission.body).values, { budget: 1000 });
|
||||
assert.equal((await request("/customer/inquiry-submissions")).statusCode, 401);
|
||||
const adminCannotListCustomerSubmissions = await request("/customer/inquiry-submissions", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(adminCannotListCustomerSubmissions.statusCode, 403);
|
||||
const customerSubmissions = await request("/customer/inquiry-submissions", {
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
});
|
||||
assert.equal(customerSubmissions.statusCode, 200);
|
||||
assert.ok(
|
||||
JSON.parse(customerSubmissions.body).some(
|
||||
(item) => item.id === JSON.parse(submission.body).id,
|
||||
),
|
||||
);
|
||||
const adminSubmissionsWithoutToken = await request("/admin/workspace/submissions");
|
||||
assert.equal(adminSubmissionsWithoutToken.statusCode, 401);
|
||||
const adminSubmissions = await request("/admin/workspace/submissions", {
|
||||
|
||||
Reference in new issue
Block a user