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", {
|
||||
|
||||
@@ -1 +1,13 @@
|
||||
Page({ data: { record: {} }, onLoad(options) { const records = wx.getStorageSync("linjingInquiryRecords") || []; this.setData({ record: records.find((item) => item.id === options.id) || records[0] || {} }); }, viewRecords() { wx.redirectTo({ url: "/pages/records/index" }); }, home() { wx.switchTab({ url: "/pages/index/index" }); } });
|
||||
Page({
|
||||
data: { record: {} },
|
||||
onLoad(options) {
|
||||
const record = wx.getStorageSync("latestInquirySubmission") || {};
|
||||
this.setData({ record: record.id === options.id ? record : {} });
|
||||
},
|
||||
viewRecords() {
|
||||
wx.redirectTo({ url: "/pages/records/index" });
|
||||
},
|
||||
home() {
|
||||
wx.switchTab({ url: "/pages/index/index" });
|
||||
},
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
const { loadWorkspaceWithFallback } = require("../../utils/runtime-workspace");
|
||||
const { request, customerRequest } = require("../../utils/request");
|
||||
Page({
|
||||
data: {
|
||||
offering: null,
|
||||
@@ -9,18 +10,24 @@ Page({
|
||||
submitLabel: "提交需求",
|
||||
values: {},
|
||||
fields: [],
|
||||
formId: "",
|
||||
},
|
||||
onLoad(options) {
|
||||
loadWorkspaceWithFallback().then((workspace) => {
|
||||
const offering =
|
||||
(workspace.offerings || []).find((item) => item.id === options.offeringId) || null;
|
||||
const form = (workspace.inquiryForms || [])[0];
|
||||
const forms = workspace.inquiryForms || [];
|
||||
const form =
|
||||
forms.find((item) => item.targetId && item.targetId === options.offeringId) ||
|
||||
forms.find((item) => item.target === "brand") ||
|
||||
forms[0];
|
||||
const isQuote =
|
||||
form?.purpose === "quote-request" ||
|
||||
(workspace.plugins || []).some((plugin) => plugin.key === "quote-request");
|
||||
this.setData({
|
||||
offering,
|
||||
fields: form?.fields || workspace.fields || [],
|
||||
formId: form?.key || form?.id || "",
|
||||
title: isQuote ? "获取报价方案" : "需求咨询",
|
||||
eyebrow: isQuote ? "QUOTE REQUEST" : "CONSULTATION",
|
||||
submitLabel: isQuote ? "提交报价需求" : "提交需求",
|
||||
@@ -35,24 +42,43 @@ Page({
|
||||
},
|
||||
submit() {
|
||||
const values = this.data.values;
|
||||
if (!values.name || !values.phone)
|
||||
return wx.showToast({ title: "请填写联系人和手机号", icon: "none" });
|
||||
const missing = this.data.fields.find(
|
||||
(field) => field.required && (values[field.key] === undefined || values[field.key] === ""),
|
||||
);
|
||||
if (missing) return wx.showToast({ title: "请填写" + missing.label, icon: "none" });
|
||||
if (!this.data.formId) return wx.showToast({ title: "咨询表单暂不可用", icon: "none" });
|
||||
this.setData({ submitting: true });
|
||||
setTimeout(() => {
|
||||
const id = "LJ" + Date.now().toString().slice(-8);
|
||||
const record = {
|
||||
id,
|
||||
offeringName: this.data.offering ? this.data.offering.name : "门系统定制咨询",
|
||||
type: values.doorType || "门系统定制",
|
||||
project: values.city || "待确认项目",
|
||||
status: "待主理人复核图纸",
|
||||
createdAt: new Date().toLocaleDateString("zh-CN"),
|
||||
values,
|
||||
};
|
||||
const records = wx.getStorageSync("linjingInquiryRecords") || [];
|
||||
wx.setStorageSync("linjingInquiryRecords", [record].concat(records));
|
||||
const send = () =>
|
||||
customerRequest("/customer/inquiry-submissions", {
|
||||
method: "POST",
|
||||
data: { formId: this.data.formId, values },
|
||||
}).then((submission) => {
|
||||
const record = {
|
||||
id: submission.id,
|
||||
offeringName: this.data.offering ? this.data.offering.name : "品牌合作",
|
||||
type: this.data.title,
|
||||
project: "已提交需求",
|
||||
status: submission.status === "new" ? "待处理" : submission.status,
|
||||
createdAt: submission.createdAt,
|
||||
};
|
||||
wx.setStorageSync("latestInquirySubmission", record);
|
||||
this.setData({ submitting: false });
|
||||
wx.redirectTo({ url: "/pages/inquiry-success/index?id=" + submission.id });
|
||||
});
|
||||
const fail = (error) => {
|
||||
this.setData({ submitting: false });
|
||||
wx.redirectTo({ url: "/pages/inquiry-success/index?id=" + id });
|
||||
}, 500);
|
||||
wx.showToast({ title: error.message || "提交失败,请重试", icon: "none" });
|
||||
};
|
||||
if (wx.getStorageSync("customerToken")) return send().catch(fail);
|
||||
wx.login({
|
||||
success: (login) =>
|
||||
request("/customer/session/wechat", { method: "POST", data: { code: login.code } })
|
||||
.then((result) => {
|
||||
wx.setStorageSync("customerToken", result.token);
|
||||
return send();
|
||||
})
|
||||
.catch(fail),
|
||||
fail,
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -1 +1,39 @@
|
||||
Page({ data: { records: [] }, onShow() { this.setData({ records: wx.getStorageSync("linjingInquiryRecords") || [] }); }, inquire() { wx.navigateTo({ url: "/pages/inquiry/index" }); } });
|
||||
const { customerRequest } = require("../../utils/request");
|
||||
|
||||
const statusLabels = {
|
||||
new: "待处理",
|
||||
reviewing: "沟通中",
|
||||
replied: "已回复",
|
||||
qualified: "已确认",
|
||||
converted: "已转化",
|
||||
closed: "已关闭",
|
||||
};
|
||||
|
||||
Page({
|
||||
data: { records: [], loading: false },
|
||||
onShow() {
|
||||
if (!wx.getStorageSync("customerToken")) return this.setData({ records: [] });
|
||||
this.setData({ loading: true });
|
||||
customerRequest("/customer/inquiry-submissions")
|
||||
.then((items) =>
|
||||
this.setData({
|
||||
loading: false,
|
||||
records: items.map((item) => ({
|
||||
...item,
|
||||
type: item.inquiryForm?.name || "品牌咨询",
|
||||
status: statusLabels[item.status] || item.status,
|
||||
project: "咨询记录",
|
||||
offeringName: item.offering?.name || "品牌合作",
|
||||
createdAt: new Date(item.createdAt).toLocaleDateString("zh-CN"),
|
||||
})),
|
||||
}),
|
||||
)
|
||||
.catch((error) => {
|
||||
this.setData({ loading: false });
|
||||
wx.showToast({ title: error.message || "记录加载失败", icon: "none" });
|
||||
});
|
||||
},
|
||||
inquire() {
|
||||
wx.navigateTo({ url: "/pages/inquiry/index" });
|
||||
},
|
||||
});
|
||||
@@ -327,12 +327,15 @@ export class ApiClient {
|
||||
createCustomerInquirySubmission(
|
||||
formId: string,
|
||||
values: Record<string, unknown>,
|
||||
): Promise<unknown> {
|
||||
): Promise<InquirySubmission> {
|
||||
return this.request("/customer/inquiry-submissions", {
|
||||
method: "POST",
|
||||
body: { formId, values },
|
||||
});
|
||||
}
|
||||
listCustomerInquirySubmissions(): Promise<InquirySubmission[]> {
|
||||
return this.request("/customer/inquiry-submissions");
|
||||
}
|
||||
createCustomerSession(code: string): Promise<{ token: string }> {
|
||||
return this.request("/customer/session/wechat", { method: "POST", body: { code } });
|
||||
}
|
||||
|
||||
@@ -99,6 +99,7 @@ export interface RuntimeInquiryForm {
|
||||
version: string;
|
||||
purpose: "inquiry" | "booking" | "quote-request";
|
||||
target: "brand" | "offering";
|
||||
targetId?: string;
|
||||
submissionAction: "create-inquiry" | "create-booking" | "create-quote";
|
||||
fields: RuntimeInquiryField[];
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user