fix: 校验咨询表单关联业务并修正发布清单文案

- 关联的业务提供项必须存在且属于当前品牌,非法 id 返回 400 而不是数据库外键错误
- targetType 由 offeringId 推导,允许传 null 改回品牌通用入口
- 业务被停用时在发布准备度里点名说明,避免静默卡住发布
- 发布清单条目改为中性描述,是否达标交给状态标签表达
This commit is contained in:
que01 committed 2026-10-14 13:55:00 +08:00
1 parent 47d6309cba
commit 7b1e9eee47
6 files changed
+223 -25

No files matched your search

+33 -3
View File
@@ -419,14 +419,21 @@ class AdminWorkspaceController {
}
@Post("forms")
createForm(@Req() request: FastifyRequest, @Body() body: CreateInquiryFormDto): Promise<unknown> {
async createForm(
@Req() request: FastifyRequest,
@Body() body: CreateInquiryFormDto,
): Promise<unknown> {
const brandId = requireAdminIdentity(request).brandId;
if (validateFieldSnapshot(body.fieldsSnapshot).length)
throw new BadRequestException("咨询表单字段定义无效");
const { offeringId, ...fields } = body;
const targetType = await this.resolveFormTarget(brandId, offeringId);
return this.prisma.inquiryForm.create({
data: {
...body,
...fields,
brandId,
targetType,
offeringId: offeringId ?? null,
version: 1,
fieldsSnapshot: body.fieldsSnapshot as Prisma.InputJsonValue,
},
@@ -444,13 +451,19 @@ class AdminWorkspaceController {
where: { id, brandId },
});
if (!item) throw new BadRequestException("咨询表单不存在");
const { fieldsSnapshot, ...fields } = body;
const { fieldsSnapshot, offeringId, ...fields } = body;
if (fieldsSnapshot !== undefined && validateFieldSnapshot(fieldsSnapshot).length)
throw new BadRequestException("咨询表单字段定义无效");
// offeringId 由用户输入决定表单入口,必须和 targetType 一起改写,避免出现「targetType 是品牌、却挂着业务 id」的漂移。
const target =
offeringId === undefined
? {}
: { offeringId, targetType: await this.resolveFormTarget(brandId, offeringId) };
return this.prisma.inquiryForm.update({
where: { id },
data: {
...fields,
...target,
...(fieldsSnapshot === undefined
? {}
: { fieldsSnapshot: fieldsSnapshot as Prisma.InputJsonValue }),
@@ -458,6 +471,23 @@ class AdminWorkspaceController {
},
});
}
/**
* 表单可以挂在品牌上,也可以只服务某一个业务提供项。关联的业务必须存在且属于当前品牌,
* 否则直接拒绝,不能让数据库外键错误(或跨品牌 id)落库。
*/
private async resolveFormTarget(
brandId: string,
offeringId: string | null | undefined,
): Promise<"brand" | "offering"> {
if (offeringId === undefined || offeringId === null) return "brand";
const offering = await this.prisma.offering.findFirst({
where: { id: offeringId, brandId },
select: { id: true },
});
if (!offering) throw new BadRequestException("关联的业务提供项不存在或不属于当前品牌");
return "offering";
}
}
export { AdminWorkspaceController };
+3 -2
View File
@@ -184,7 +184,7 @@ export class UpdateFieldDefinitionDto {
export class CreateInquiryFormDto {
@IsString() name!: string;
@IsOptional() @IsString() offeringId?: string;
@IsOptional() @IsString() offeringId?: string | null;
@IsOptional() @IsIn(["inquiry", "booking", "quote-request"]) purpose?: string;
@IsOptional() @IsIn(["brand", "offering"]) targetType?: string;
@IsOptional()
@@ -196,7 +196,8 @@ export class CreateInquiryFormDto {
export class UpdateInquiryFormDto {
@IsOptional() @IsString() name?: string;
@IsOptional() @IsString() offeringId?: string;
// 允许显式传 null 表示「改回品牌通用入口」,因此不能只用 @IsString。
@IsOptional() @IsString() offeringId?: string | null;
@IsOptional() @IsIn(["inquiry", "booking", "quote-request"]) purpose?: string;
@IsOptional() @IsIn(["brand", "offering"]) targetType?: string;
@IsOptional()
+27 -18
View File
@@ -78,7 +78,7 @@ export class BrandReleaseApiService {
}),
database.inquiryForm.findMany({
where: { brandId, isEnabled: true },
select: { offeringId: true, fieldsSnapshot: true },
select: { offeringId: true, name: true, fieldsSnapshot: true },
}),
database.trustContent.findMany({
where: { brandId, isPublished: true },
@@ -92,12 +92,17 @@ export class BrandReleaseApiService {
),
);
const offeringIds = new Set(offerings.map((item) => item.id));
const validFields = (form: { fieldsSnapshot: unknown }) =>
Array.isArray(form.fieldsSnapshot) &&
form.fieldsSnapshot.length > 0 &&
validateFieldSnapshot(form.fieldsSnapshot).length === 0;
const usableForms = forms.filter(
(form) =>
(form.offeringId === null || offeringIds.has(form.offeringId)) &&
Array.isArray(form.fieldsSnapshot) &&
form.fieldsSnapshot.length > 0 &&
validateFieldSnapshot(form.fieldsSnapshot).length === 0,
(form) => (form.offeringId === null || offeringIds.has(form.offeringId)) && validFields(form),
);
// 挂在某个业务上的表单,一旦该业务被停用就再也进不去,小程序也没有入口。这种情况要在发布清单里说清楚,
// 否则只会显示「可用的咨询表单:待完善」,运营者不知道去哪儿改。
const dormantForms = forms.filter(
(form) => form.offeringId !== null && !offeringIds.has(form.offeringId) && validFields(form),
);
const checks: Array<{
key: string;
@@ -108,38 +113,43 @@ export class BrandReleaseApiService {
}> = [
{
key: "brand",
label: "请先完善品牌名称",
label: "品牌名称",
passed: Boolean(brand?.name.trim()),
destination: "/admin/brand",
},
{
key: "positioning",
label: "请先完善品牌定位和介绍",
label: "品牌定位和介绍",
passed: Boolean(brand?.tagline?.trim() && brand.description?.trim()),
destination: "/admin/brand",
},
{ key: "template", label: "当前行业模板不存在", passed: Boolean(template) },
{ key: "template", label: "行业模板配置", passed: Boolean(template) },
{
key: "visual",
label: "当前视觉模板不适配行业模板",
label: "视觉模板与行业模板的适配",
passed: Boolean(visual && template && isVisualTemplateCompatible(visual, template.key)),
destination: "/admin/publication",
},
{
key: "offerings",
label: "至少需要一项已启用的业务提供项",
label: "已启用的业务提供项",
passed: offerings.length > 0,
destination: "/admin/services",
},
{
key: "forms",
label: "至少需要一个可用的咨询表单",
label: "可用的咨询表单",
passed: usableForms.length > 0,
...(dormantForms.length === 0
? {}
: {
help: `「${dormantForms.map((form) => form.name).join("」「")}」关联的业务提供项已停用,该表单在小程序里没有入口;请启用对应业务,或把表单改回品牌通用入口。`,
}),
destination: "/admin/workspace",
},
{
key: "trust",
label: "至少需要一条已发布的信任内容",
label: "已发布的信任内容",
passed: validTrustItems.length > 0,
destination: "/admin/trust",
},
@@ -149,7 +159,7 @@ export class BrandReleaseApiService {
if (type.required !== true) continue;
checks.push({
key: `trust:${type.type}`,
label: `请完善${type.label}`,
label: type.label,
passed:
publishedTrustTypes.has(type.type) &&
(type.maxPublishedItems === undefined ||
@@ -176,9 +186,8 @@ export class BrandReleaseApiService {
});
checks.push({
key: `content:${section.key}:${field.key}`,
label: present
? `${section.title}:${field.label}`
: `请补充「${section.title}」中的「${field.label}」`,
// 检查项只描述「要检查什么」,是否完成由 UI 的状态标签表达,避免出现「已完成 · 请先完善…」这类自相矛盾的文案。
label: `${section.title}:${field.label}`,
passed: present,
help: section.description,
destination:
@@ -202,7 +211,7 @@ export class BrandReleaseApiService {
: trustItems.length > 0;
checks.push({
key: `asset:${String(slot.key)}`,
label: present ? `已添加${String(slot.label)}` : `请添加${String(slot.label)}`,
label: String(slot.label),
passed: present,
help: String(slot.help),
destination: slot.target === "offering" ? "/admin/services" : "/admin/brand",
+150
View File
@@ -1,4 +1,5 @@
import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
import { after, before, test } from "node:test";
import { PrismaClient } from "@prisma/client";
import { createApp } from "../dist/main.js";
@@ -2353,6 +2354,155 @@ test("admin can create and version an inquiry form", async () => {
}
});
test("admin workspace data stays inside the acting brand", async () => {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const actingBrandId = readIdentity(token).brandId;
const otherBrand = await prisma.brandProfile.findFirst({
where: { id: { not: actingBrandId } },
});
assert.ok(otherBrand);
const switchResponse = await request(`/admin/brands/${otherBrand.id}/switch`, {
method: "POST",
headers: { authorization: `Bearer ${token}` },
});
assert.equal(switchResponse.statusCode, 201);
const switchedToken = JSON.parse(switchResponse.body).token;
assert.equal(readIdentity(switchedToken).brandId, otherBrand.id);
const workspace = await request("/admin/workspace", {
headers: { authorization: `Bearer ${switchedToken}` },
});
assert.equal(workspace.statusCode, 200);
const offeringBrandIds = [
...new Set(JSON.parse(workspace.body).offerings.map((item) => item.brandId)),
];
assert.deepEqual(offeringBrandIds, [otherBrand.id]);
// 公开工作空间不带 brandSlug 时会回退到默认品牌;后台下拉框若直接用它会串到别的品牌,
// 这里把这个差异固定下来,防止再次被接回 Admin。
const publicWorkspace = await request("/public/workspace");
const publicOfferingIds = JSON.parse(publicWorkspace.body).offerings.map((item) => item.id);
const foreignIds = JSON.parse(workspace.body)
.offerings.map((item) => item.id)
.filter((id) => publicOfferingIds.includes(id));
assert.deepEqual(foreignIds, []);
});
test("inquiry form offering link is validated against the brand", async () => {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const headers = { authorization: `Bearer ${token}` };
const offering = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } });
assert.ok(offering);
const otherBrandOffering = await prisma.offering.findFirst({
where: { brandId: { not: brandId } },
});
assert.ok(otherBrandOffering);
const fields = [{ key: "project", type: "textarea", label: "项目背景", required: true }];
// 不存在的业务 id:必须是可读的 400,而不是数据库外键错误。
const unknown = await request("/admin/workspace/forms", {
method: "POST",
headers,
payload: { name: "非法关联表单", offeringId: randomUUID(), fieldsSnapshot: fields },
});
assert.equal(unknown.statusCode, 400);
assert.match(errorMessage(unknown.body), /关联的业务提供项不存在/);
// 其他品牌的业务 id:品牌隔离必须拦住。
const crossBrand = await request("/admin/workspace/forms", {
method: "POST",
headers,
payload: {
name: "跨品牌关联表单",
offeringId: otherBrandOffering.id,
fieldsSnapshot: fields,
},
});
assert.equal(crossBrand.statusCode, 400);
assert.match(errorMessage(crossBrand.body), /不属于当前品牌/);
assert.equal(await prisma.inquiryForm.count({ where: { brandId, name: "跨品牌关联表单" } }), 0);
// 合法的关联:targetType 由后端推导为 offering,写入后仍然只能被本品牌看到。
const created = await request("/admin/workspace/forms", {
method: "POST",
headers,
payload: { name: "业务专属表单", offeringId: offering.id, fieldsSnapshot: fields },
});
assert.equal(created.statusCode, 201);
const form = JSON.parse(created.body);
assert.equal(form.offeringId, offering.id);
assert.equal(form.targetType, "offering");
try {
const hijack = await request(`/admin/workspace/forms/${form.id}`, {
method: "PATCH",
headers,
payload: { offeringId: otherBrandOffering.id },
});
assert.equal(hijack.statusCode, 400);
const unchanged = await prisma.inquiryForm.findUnique({ where: { id: form.id } });
assert.equal(unchanged.offeringId, offering.id);
// 解除关联:显式传 null 才能回到品牌通用入口。
const unlinked = await request(`/admin/workspace/forms/${form.id}`, {
method: "PATCH",
headers,
payload: { offeringId: null },
});
assert.equal(unlinked.statusCode, 200);
const unlinkedBody = JSON.parse(unlinked.body);
assert.equal(unlinkedBody.offeringId, null);
assert.equal(unlinkedBody.targetType, "brand");
} finally {
await prisma.inquiryForm.delete({ where: { id: form.id } });
}
});
test("release readiness explains a form whose offering was disabled", async () => {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const headers = { authorization: `Bearer ${token}` };
const offering = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } });
assert.ok(offering);
const form = await prisma.inquiryForm.create({
data: {
brandId,
name: "随业务停用的表单",
offeringId: offering.id,
targetType: "offering",
purpose: "inquiry",
submissionAction: "create-inquiry",
fieldsSnapshot: [{ key: "project", type: "textarea", label: "项目背景", required: true }],
isEnabled: true,
},
});
const originalFormEnabled = form.isEnabled;
await prisma.offering.update({ where: { id: offering.id }, data: { isEnabled: false } });
try {
const readiness = await request("/admin/releases/readiness", { headers });
assert.equal(readiness.statusCode, 200);
const formsCheck = JSON.parse(readiness.body).checks.find((check) => check.key === "forms");
assert.equal(formsCheck.passed, false);
assert.match(formsCheck.help, /随业务停用的表单/);
assert.match(formsCheck.help, /关联的业务提供项已停用/);
} finally {
await prisma.offering.update({ where: { id: offering.id }, data: { isEnabled: true } });
await prisma.inquiryForm.deleteMany({ where: { id: form.id } });
}
assert.equal(originalFormEnabled, true);
});
test("admin rejects invalid dynamic inquiry field definitions", async () => {
const login = await request("/admin/session/login", {
method: "POST",
+7
View File
@@ -33,6 +33,13 @@ BrandProfile
品牌或 Offering 使用的咨询表单定义,带版本号。字段来自 `BrandFieldDefinition`,提交时保存字段定义快照和 active 状态。
`targetType` 与 `offeringId` 必须一致,由服务端根据 `offeringId` 推导,避免出现「标成品牌通用、却挂着业务 id」的漂移:
- `offeringId` 为空:品牌通用入口,小程序任一咨询按钮都能进入;
- `offeringId` 有值:只在该 Offering 的详情页使用,小程序按 `offeringId` 选择对应表单,找不到时回退到品牌通用表单;
- 关联的 Offering 必须存在且属于当前品牌,否则拒绝写入(不允许跨品牌关联);
- 关联的 Offering 被停用后,该表单在小程序里没有入口;发布准备度会把这种情况连同表单名一起说明,提示启用业务或改回品牌通用入口。
### InquirySubmission
保留现有 `Booking` 作为历史兼容入口,新增通用咨询提交语义。新提交记录保存表单版本、字段定义快照、用户值和 active 字段集合。
+3 -2
View File
@@ -15,7 +15,7 @@ export interface InquiryMethods {
): Promise<InquirySubmission>;
createAdminInquiryForm(body: {
name: string;
offeringId?: string;
offeringId?: string | null;
fieldsSnapshot: unknown[];
isEnabled?: boolean;
purpose?: InquiryForm["purpose"];
@@ -26,7 +26,8 @@ export interface InquiryMethods {
id: string,
body: Partial<{
name: string;
offeringId: string;
/** 传 null 表示改回品牌通用入口。 */
offeringId: string | null;
fieldsSnapshot: unknown[];
isEnabled: boolean;
purpose?: InquiryForm["purpose"];