fix: 收敛模板编辑发布契约并还原餐饮页面视觉

This commit is contained in:
que01 committed 2026-10-08 13:36:59 +08:00
1 parent 20bcb43534
commit f4061a24bd
102 files changed
+4510 -870

No files matched your search

+52 -69
View File
@@ -1,7 +1,7 @@
import { PrismaClient } from "@prisma/client";
import { PrismaClient, type Prisma } from "@prisma/client";
import { getTemplatePackageManifestForVisualKey } from "@personal-brand/config";
import bcrypt from "bcryptjs";
import { buildBrandReleaseSnapshot } from "../src/brand-release.service.js";
import { getTemplateSampleContent } from "@personal-brand/config";
const prisma = new PrismaClient();
@@ -20,7 +20,7 @@ const runtimeImages = {
"https://images.unsplash.com/photo-1556761175-b413da4baf72?auto=format&fit=crop&w=1000&q=85",
"https://images.unsplash.com/photo-1521737711867-e3b97375f902?auto=format&fit=crop&w=1000&q=85",
],
};
} as const;
type OfferingKind = "service" | "product" | "package" | "subscription";
@@ -41,9 +41,10 @@ interface RuntimeSeedTemplate {
type: string;
title: string;
content: string;
summary?: string;
config?: Record<string, unknown>;
}>;
inquiryForm: { name: string; fieldsSnapshot: Array<Record<string, unknown>> };
inquiryForm?: { name: string; fieldsSnapshot: Array<Record<string, unknown>> };
}
const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTemplate> = {
@@ -51,6 +52,7 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
templateKey: "personal",
brandConfig: {
visualTemplateKey: "linjing-editorial",
templateData: { designPhilosophy: "先厘清问题,再设计表达" },
founder: "林然",
title: "品牌策略顾问",
slogan: "用清晰的定位与可执行的表达,让专业被看见。",
@@ -186,8 +188,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
flowTitle: "从预订到取餐",
},
service: {
coverageLabel: "取餐与配送",
stepLabel: "步骤",
processAction: "立即预订",
},
offerings: {
@@ -277,24 +277,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
},
],
trustContent: [
{
type: "schedule",
title: "每周出摊日程",
summary: "周一至周五晚餐与夜宵档",
content: "二号校门外小吃商业街 · 17:00 - 22:30\n周六、周日承接团体单与夜市流动出摊",
},
{
type: "coverage",
title: "取餐与配送范围",
summary: "提前预订,按约定时间取餐或配送",
content: "摊位现场自取;满 3 份可配送至校内宿舍楼栋或实验楼门前。",
},
{
type: "process",
title: "定制餐品流程",
summary: "从需求沟通到保温交付",
content: "提交基本需求\n确认菜单与预算\n当日新鲜烹饪打包\n保温直达交付",
},
{
type: "credential",
title: "食品安全与制作承诺",
@@ -312,20 +294,13 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
content: "备料期 15 分钟内联系,出摊高峰 1 小时内回复。",
},
],
inquiryForm: {
name: "家庭聚餐咨询",
fieldsSnapshot: [
{ key: "name", label: "您的称呼", type: "text", required: true },
{ key: "phone", label: "联系电话", type: "phone", required: true },
{ key: "remark", label: "需求说明", type: "textarea", required: false },
],
},
},
doors: {
templateKey: "doors",
retiredOfferingNames: ["别墅入户大门", "院门与围合系统", "室内户内门系统"],
brandConfig: {
visualTemplateKey: "linjing-editorial",
templateData: { designPhilosophy: "让门与空间建立长期、克制的关系" },
founder: "林叙安 (Lin XUAN)",
title: "高端门系统建筑研造主理人",
slogan: "为当代别墅空间,定制有秩序感与呼吸感的门",
@@ -679,40 +654,39 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
};
async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTemplate): Promise<void> {
const packageSample = getTemplateSampleContent(template.templateKey);
const sampleOfferings = packageSample?.offerings ?? [];
const offerings = template.offerings.map((item, index) => ({
...item,
...(sampleOfferings[index]
? {
name: sampleOfferings[index].name,
summary: sampleOfferings[index].summary,
config: {
...item.config,
categoryKey: sampleOfferings[index].categoryKey,
},
}
: {}),
}));
// 模板 package 的 sampleContent 只用于导入预览;演示品牌使用明确的品牌 fixture,
// 避免把模板示例内容误当成所有品牌的数据库初始数据。
const trustContent = template.trustContent;
const inquiryFields = (packageSample?.fields ?? template.inquiryForm.fieldsSnapshot).map(
(field) => ({
...field,
...(Array.isArray(field.options)
? {
options: field.options.map((option) =>
typeof option === "string" ? { label: option, value: option } : option,
),
}
: {}),
}),
);
// 这里只初始化明确的开发演示品牌;餐饮结构化槽位和表单取自对应 package,
// 新增生产模板无需添加 seed 分支,品牌样例内容仍须由管理员显式导入。
const offerings = template.offerings;
const foodSample =
template.templateKey === "food"
? getTemplatePackageManifestForVisualKey("acheng-campus-food")?.sampleContent?.food
: undefined;
if (template.templateKey === "food" && !foodSample)
throw new Error("Food development sample is missing");
const trustContent = foodSample
? foodSample.trustContent.map((item) => {
const fixture = template.trustContent.find((entry) => entry.type === item.type);
return { ...item, ...fixture, config: { ...item.config, ...fixture?.config } };
})
: template.trustContent;
const inquiryFields = foodSample?.fields ?? template.inquiryForm?.fieldsSnapshot;
const inquiryFormName = foodSample?.inquiryFormName ?? template.inquiryForm?.name;
if (!inquiryFields?.length || !inquiryFormName)
throw new Error("Development inquiry fixture is missing");
const existingBrand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
const existingConfig =
existingBrand.config &&
typeof existingBrand.config === "object" &&
!Array.isArray(existingBrand.config)
? (existingBrand.config as Record<string, unknown>)
: {};
await prisma.brandProfile.update({
where: { id: brandId },
data: {
config: template.brandConfig,
config: { ...existingConfig, ...template.brandConfig } as Prisma.InputJsonValue,
...(existingBrand.slug === "default-brand" && !existingBrand.avatarUrl
? { avatarUrl: "/assets/owner/portrait.jpg" }
: {}),
},
});
for (const [sortOrder, item] of offerings.entries()) {
@@ -747,7 +721,8 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
select: { id: true, name: true },
});
for (const [index, item] of incompleteOfferings.entries()) {
const image = template.offerings[index % template.offerings.length].image;
const image = template.offerings[index % template.offerings.length]?.image;
if (!image) throw new Error("Development fixture has no offering image");
await prisma.offering.update({
where: { id: item.id },
data: {
@@ -764,9 +739,17 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
}
for (const [sortOrder, item] of trustContent.entries()) {
const existing = await prisma.trustContent.findFirst({
where: { brandId, type: item.type, title: item.title },
where: { brandId, type: item.type },
orderBy: [{ isPublished: "desc" }, { sortOrder: "asc" }],
});
const data = { ...item, brandId, sortOrder, isPublished: true };
const { config, ...fields } = item;
const data = {
...fields,
brandId,
sortOrder,
isPublished: true,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
};
if (existing) await prisma.trustContent.update({ where: { id: existing.id }, data });
else await prisma.trustContent.create({ data });
}
@@ -775,7 +758,7 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
orderBy: { createdAt: "asc" },
});
const formData = {
name: template.inquiryForm.name,
name: inquiryFormName,
purpose: "inquiry",
targetType: "brand",
submissionAction: "create-inquiry",
@@ -788,14 +771,14 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
}
async function ensureSeedRelease(brandId: string, actorId: string): Promise<void> {
if (await prisma.brandRelease.findFirst({ where: { brandId } })) return;
const snapshot = await buildBrandReleaseSnapshot(prisma, brandId);
await prisma.brandRelease.deleteMany({ where: { brandId } });
await prisma.brandRelease.create({
data: {
brandId,
version: 1,
status: "published",
snapshot,
snapshot: snapshot as unknown as Prisma.InputJsonValue,
actorId,
note: "seed 基线发布版本",
},
@@ -0,0 +1,85 @@
/** 仅恢复开发餐饮品牌的原型视觉槽位,不覆盖已有结构化编辑和发布历史。 */
import "reflect-metadata";
import fs from "node:fs";
import { PrismaClient, type Prisma } from "@prisma/client";
import { getTemplatePackageManifestForVisualKey } from "@personal-brand/config";
import { BrandReleaseService } from "../src/brand-release.service.js";
import { BrandReleaseApiService } from "../src/brand-release-api.service.js";
import type { PrismaService } from "../src/prisma.service.js";
const prisma = new PrismaClient();
const note = "餐饮主理人原型视觉槽位迁移 v1";
try {
const brand = await prisma.brandProfile.findUniqueOrThrow({ where: { slug: "default-brand" } });
const config = (brand.config ?? {}) as Record<string, unknown>;
if (brand.templateKey !== "food" || config.visualTemplateKey !== "acheng-campus-food")
throw new Error("Migration is restricted to the development food brand");
const previous = await prisma.brandRelease.findFirst({
where: { brandId: brand.id },
orderBy: { version: "desc" },
});
if (await prisma.brandRelease.findFirst({ where: { brandId: brand.id, note } })) {
console.log("Already migrated; no changes");
} else {
const trust = await prisma.trustContent.findMany({
where: { brandId: brand.id },
orderBy: [{ sortOrder: "asc" }, { createdAt: "asc" }],
});
const backup = `/tmp/food-owner-visual-backup-${Date.now()}.json`;
fs.writeFileSync(backup, JSON.stringify({ brand, trust, previous }, null, 2), { mode: 0o600 });
console.log(`Backup: ${backup}`);
if (!process.argv.includes("--apply"))
console.log("Dry run; pass --apply to migrate and publish");
else {
const sample =
getTemplatePackageManifestForVisualKey("acheng-campus-food")!.sampleContent!.food!;
const service = new BrandReleaseService(prisma as PrismaService);
const publisher = new BrandReleaseApiService(prisma as PrismaService, service);
await prisma.$transaction(async (tx) => {
await tx.brandProfile.update({
where: { id: brand.id },
data: { avatarUrl: brand.avatarUrl || "/assets/owner/portrait.jpg" },
});
for (const type of ["credential", "case", "promise"]) {
const item = trust.find((item) => item.type === type && item.isPublished);
if (!item) continue;
const defaults = sample.trustContent.find((item) => item.type === type)!;
const existing = (item.config ?? {}) as Record<string, unknown>;
// 只补迁移前已确认的开发样例内容;用户改写的正文不能被模板样例遮挡。
const known =
type === "credential"
? item.content === "当天采购,现做现出餐;食具每日清洁消毒,按约定标注和分装。"
: item.content === defaults.content;
if (!known) continue;
await tx.trustContent.update({
where: { id: item.id },
data: {
config: { ...defaults.config, ...existing } as Prisma.InputJsonValue,
},
});
}
const readiness = await publisher.readiness(brand.id, tx);
if (!readiness.ready)
throw new Error(JSON.stringify(readiness.checks.filter((check) => !check.passed)));
const snapshot = await service.buildSnapshot(brand.id, tx);
await tx.brandRelease.updateMany({
where: { brandId: brand.id, status: "published" },
data: { status: "superseded" },
});
await tx.brandRelease.create({
data: {
brandId: brand.id,
version: (previous?.version ?? 0) + 1,
actorId: previous?.actorId ?? "content-migration",
note,
snapshot: snapshot as unknown as Prisma.InputJsonValue,
},
});
});
console.log(
"Owner visual slots migrated and published; existing edits and historical releases retained",
);
}
}
} finally {
await prisma.$disconnect();
}
@@ -0,0 +1,157 @@
/** 开发餐饮品牌的幂等内容迁移。保留旧记录为草稿,历史快照和提交不变。 */
import "reflect-metadata";
import fs from "node:fs";
import type { Prisma } from "@prisma/client";
import { PrismaClient } from "@prisma/client";
import { getTemplatePackageManifestForVisualKey } from "@personal-brand/config";
import { BrandReleaseService } from "../src/brand-release.service.js";
import { BrandReleaseApiService } from "../src/brand-release-api.service.js";
import type { PrismaService } from "../src/prisma.service.js";
const prisma = new PrismaClient();
const note = "餐饮模板结构化内容迁移 v3";
try {
const brand = await prisma.brandProfile.findUniqueOrThrow({ where: { slug: "default-brand" } });
if (
brand.templateKey !== "food" ||
(brand.config as Record<string, unknown>)?.visualTemplateKey !== "acheng-campus-food"
)
throw new Error("Migration is restricted to the development food brand");
const previous = await prisma.brandRelease.findFirst({
where: { brandId: brand.id },
orderBy: { version: "desc" },
});
if (previous?.note === note) {
console.log("Already migrated; no changes");
} else {
const trust = await prisma.trustContent.findMany({
where: { brandId: brand.id },
orderBy: { updatedAt: "desc" },
});
const forms = await prisma.inquiryForm.findMany({ where: { brandId: brand.id } });
const backup = `/tmp/food-template-content-backup-${Date.now()}.json`;
fs.writeFileSync(backup, JSON.stringify({ brand, trust, forms, previous }, null, 2), {
mode: 0o600,
});
console.log(`Backup: ${backup}`);
if (!process.argv.includes("--apply")) {
console.log("Dry run; pass --apply to migrate and publish");
} else {
const sample =
getTemplatePackageManifestForVisualKey("acheng-campus-food")!.sampleContent!.food!;
const releaseService = new BrandReleaseService(prisma as PrismaService);
const publisher = new BrandReleaseApiService(prisma as PrismaService, releaseService);
await prisma.$transaction(async (tx) => {
for (const type of ["schedule", "coverage", "process"]) {
const candidates = trust.filter((item) => item.type === type);
const structured = candidates.find(
(item) => item.config && Object.keys(item.config as object).length,
);
const current = structured ?? candidates[0];
const defaults = sample.trustContent.find((item) => item.type === type)!;
const config = {
...defaults.config,
...((structured?.config as Record<string, unknown>) ?? {}),
};
// 已有的结构化配置保留。旧配送记录中的用户地点保留在自取说明中。
if (type === "coverage") {
const custom = candidates.find(
(item) =>
item.title !== defaults.title && item.content !== "示例内容,待品牌主理人完善。",
);
if (custom && !structured)
config.pickupDetail = `${custom.content}。${String(config.pickupDetail)}`;
}
if (type === "schedule") {
if (config.weekdayDetail === "二号校门外小吃商业街 #07 号铺位 · 17:00 - 22:30")
config.weekdayDetail = defaults.config!.weekdayDetail;
if (config.weekendDetail === "白天承接团体单;晚间 18:00 - 23:00 体育馆南侧流动出摊")
config.weekendDetail = defaults.config!.weekendDetail;
const custom = candidates.find((item) => !item.config && item.summary && item.content);
if (custom) {
config.weekdayHours = custom.summary!.replace(/^周一(?:到|至)周五\s*/, "");
config.weekendHours = custom.content.replace(/^周六(?:到|至)周(?:天|日)\s*/, "");
}
}
if (current)
await tx.trustContent.update({
where: { id: current.id },
data: {
title: defaults.title,
content: "",
summary: null,
config: config as Prisma.InputJsonValue,
isPublished: true,
},
});
else
await tx.trustContent.create({
data: {
brandId: brand.id,
type,
title: defaults.title,
content: "",
config: config as Prisma.InputJsonValue,
isPublished: true,
},
});
await tx.trustContent.updateMany({
where: {
brandId: brand.id,
type,
id: {
in: candidates.filter((item) => item.id !== current?.id).map((item) => item.id),
},
},
data: { isPublished: false },
});
}
const supportedTypes = getTemplatePackageManifestForVisualKey(
"acheng-campus-food",
)!.trustContentTypes!.map((item) => item.type);
await tx.trustContent.updateMany({
where: { brandId: brand.id, type: { notIn: supportedTypes } },
data: { isPublished: false },
});
const form = forms.find((item) => item.targetType === "brand" && item.isEnabled);
if (!form) throw new Error("Expected existing brand inquiry form");
const oldFields = form.fieldsSnapshot as Array<Record<string, unknown>>;
const keys = new Set(sample.fields.map((field) => field.key));
const fields = [
...sample.fields.map((field) => ({
...field,
...oldFields.find((old) => old.key === field.key),
})),
...oldFields.filter((field) => !keys.has(String(field.key))),
];
await tx.inquiryForm.update({
where: { id: form.id },
data: {
name: sample.inquiryFormName,
fieldsSnapshot: fields as Prisma.InputJsonValue,
version: { increment: 1 },
},
});
const readiness = await publisher.readiness(brand.id, tx);
if (!readiness.ready)
throw new Error(JSON.stringify(readiness.checks.filter((check) => !check.passed)));
const snapshot = await releaseService.buildSnapshot(brand.id, tx);
await tx.brandRelease.updateMany({
where: { brandId: brand.id, status: "published" },
data: { status: "superseded" },
});
await tx.brandRelease.create({
data: {
brandId: brand.id,
version: (previous?.version ?? 0) + 1,
actorId: previous?.actorId ?? "content-migration",
note,
snapshot: snapshot as unknown as Prisma.InputJsonValue,
},
});
});
console.log("Migrated and published development food brand; old content retained as drafts");
}
}
} finally {
await prisma.$disconnect();
}
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "../tsconfig.json",
"compilerOptions": { "rootDir": "..", "noEmit": true },
"include": ["*.ts", "../src/**/*.ts", "../prisma/seed.ts"]
}
+153
View File
@@ -0,0 +1,153 @@
import fs from "node:fs";
import vm from "node:vm";
import assert from "node:assert/strict";
process.env.NODE_ENV = "test";
const { createApp } = await import("../dist/main.js");
const app = await createApp();
try {
await app.init();
const response = await app
.getHttpAdapter()
.getInstance()
.inject({ method: "GET", url: "/public/workspace?brandSlug=default-brand" });
assert.equal(response.statusCode, 200);
const workspace = JSON.parse(response.body) as Record<string, unknown>;
const trustItems = workspace.trustItems as { id?: string }[];
assert.ok(trustItems.every((item) => typeof item.id === "string"));
const live = await fetch(
`http://127.0.0.1:${process.env.API_PORT ?? 3001}/public/workspace?brandSlug=default-brand`,
);
assert.equal(live.status, 200);
const liveWorkspace = (await live.json()) as Record<string, unknown>;
assert.deepEqual(liveWorkspace.trustItems, workspace.trustItems);
assert.deepEqual(liveWorkspace.inquiryForms, workspace.inquiryForms);
fs.writeFileSync("/tmp/food-template-public-workspace.json", JSON.stringify(workspace, null, 2));
let page:
| {
data: Record<string, unknown>;
load: () => Promise<void>;
setData: (value: Record<string, unknown>) => void;
}
| undefined;
vm.runInNewContext(
fs.readFileSync("../../dist/miniapp/default-brand/pages/stall-service/index.js", "utf8"),
{
Page(value: typeof page) {
page = value;
},
require(name: string) {
return name.includes("runtime-workspace")
? { loadWorkspaceWithFallback: () => Promise.resolve(workspace) }
: { openPage() {} };
},
},
);
assert.ok(page);
page.setData = (data) => Object.assign(page!.data, data);
await page.load();
const data = page.data as {
schedule: { rows: unknown[] };
coverage: { config: { pickupDetail: string; deliveryDetail: string } };
process: { steps: unknown[] };
};
assert.equal(data.schedule.rows.length, 2);
assert.ok(data.coverage.config.pickupDetail && data.coverage.config.deliveryDetail);
assert.equal(data.process.steps.length, 4);
const forms = workspace.inquiryForms as { fields: { key: string }[] }[];
for (const key of ["type", "people", "date", "budget", "delivery", "remark", "phone"])
assert.ok(forms.some((form) => form.fields.some((field) => field.key === key)));
fs.writeFileSync("/tmp/food-template-service-page-data.json", JSON.stringify(page.data, null, 2));
let inquiry:
| {
data: Record<string, unknown>;
onLoad: (options: Record<string, unknown>) => Promise<void>;
setData: (value: Record<string, unknown>) => void;
}
| undefined;
vm.runInNewContext(
fs.readFileSync("../../dist/miniapp/default-brand/pages/inquiry/index.js", "utf8"),
{
Page(value: typeof inquiry) {
inquiry = value;
},
require(name: string) {
return name.includes("runtime-workspace")
? { loadWorkspaceWithFallback: () => Promise.resolve(workspace) }
: {};
},
},
);
assert.ok(inquiry);
inquiry.setData = (value) => Object.assign(inquiry!.data, value);
await inquiry.onLoad({});
const inquiryFields = inquiry.data.fields as {
key: string;
useChips: boolean;
halfWidth: boolean;
}[];
assert.equal(inquiryFields.find((field) => field.key === "type")?.useChips, true);
assert.equal(inquiryFields.filter((field) => field.halfWidth).length, 4);
fs.writeFileSync(
"/tmp/food-template-inquiry-page-data.json",
JSON.stringify(inquiry.data, null, 2),
);
console.log(
"Actual database -> published API -> generated page: 2 schedule cards, 2 delivery columns, 4 steps, food inquiry fields verified",
);
const doorsResponse = await app
.getHttpAdapter()
.getInstance()
.inject({ method: "GET", url: "/public/workspace?brandSlug=linjing-doors" });
assert.equal(doorsResponse.statusCode, 200);
const doors = JSON.parse(doorsResponse.body) as {
trustItems: { type: string; content: string; config: Record<string, unknown> }[];
trustPresentation: Record<string, unknown>;
};
assert.equal(
doors.trustItems.some((item: { type: string }) => item.type === "profile"),
false,
);
const credentials = doors.trustItems.filter(
(item: { type: string }) => item.type === "credential",
);
const primary = credentials.find(
(item: { config: object }) => Object.keys(item.config).length > 0,
);
assert.ok(primary);
assert.deepEqual(doors.trustPresentation.stats, primary.config.stats);
const liveDoors = await fetch(
`http://127.0.0.1:${process.env.API_PORT ?? 3001}/public/workspace?brandSlug=linjing-doors`,
);
assert.equal(liveDoors.status, 200);
const liveDoorsWorkspace = (await liveDoors.json()) as Record<string, unknown>;
assert.deepEqual(liveDoorsWorkspace.trustPresentation, doors.trustPresentation);
type DoorsPage = {
data: { trustPresentation: { bio: string } };
setData: (value: object) => void;
onLoad: () => void;
};
let doorsPage: DoorsPage | undefined;
vm.runInNewContext(
fs.readFileSync("../../dist/miniapp/linjing-doors/pages/index/index.js", "utf8"),
{
Page(value: DoorsPage) {
doorsPage = value;
},
require() {
return { loadWorkspaceWithFallback: () => Promise.resolve(doors) };
},
wx: { setNavigationBarTitle() {} },
},
);
assert.ok(doorsPage);
doorsPage.setData = (value: object) => Object.assign(doorsPage!.data, value);
doorsPage.onLoad();
await new Promise((resolve) => setImmediate(resolve));
assert.equal(doorsPage.data.trustPresentation.bio, primary.content);
fs.writeFileSync("/tmp/linjing-template-page-data.json", JSON.stringify(doorsPage.data, null, 2));
console.log(
"Linjing published API -> generated page: declared credential stats and biography verified; obsolete profile excluded",
);
} finally {
await app.close();
}
+37 -2
View File
@@ -183,6 +183,11 @@ class AdminWorkspaceController {
? {
displayName: manifest.displayName,
admin: manifest.admin,
navigation: manifest.navigation.map(({ key, label, page }) => ({ key, label, page })),
templateFields: (manifest.templateFields ?? []).map((field) => ({
...field,
binding: field.binding ?? `brand.config.templateData.${field.key}`,
})),
assetSlots: manifest.assetSlots,
trustContentTypes: manifest.trustContentTypes ?? [],
}
@@ -244,7 +249,10 @@ class AdminWorkspaceController {
offerings: sample.offerings.length,
trustContent: sample.trustContent.length,
fields: sample.fields.length,
inquiryForms: 1,
},
willCreateInquiryForm:
(await this.prisma.inquiryForm.count({ where: { brandId, isEnabled: true } })) === 0,
};
}
@@ -255,6 +263,8 @@ class AdminWorkspaceController {
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
const sample = getTemplateSampleContent(templateKey);
if (!sample) throw new BadRequestException("模板示例内容不存在");
const fieldIssues = validateFieldSnapshot(sample.fields);
if (fieldIssues.length) throw new BadRequestException("模板咨询表单示例字段无效");
const existing = await this.prisma.brandFieldDefinition.count({
where: { brandId, source: "sample" },
});
@@ -280,6 +290,7 @@ class AdminWorkspaceController {
type: item.type,
title: item.title,
content: item.content,
...(item.config ? { config: item.config as Prisma.InputJsonValue } : {}),
sortOrder,
isPublished: false,
})),
@@ -296,6 +307,20 @@ class AdminWorkspaceController {
required: item.required,
})),
});
const hasEnabledForm = await tx.inquiryForm.count({ where: { brandId, isEnabled: true } });
const inquiryForm = hasEnabledForm
? null
: await tx.inquiryForm.create({
data: {
brandId,
name: sample.inquiryFormName,
purpose: "inquiry",
targetType: "brand",
submissionAction: "create-inquiry",
fieldsSnapshot: sample.fields,
isEnabled: true,
},
});
await tx.capabilityAuditLog.create({
data: {
brandId,
@@ -303,10 +328,20 @@ class AdminWorkspaceController {
actorId: identity.subject,
action: "sample_content_imported",
toStatus: "enabled",
config: { offerings: offerings.count, trustContent: trust.count, fields: fields.count },
config: {
offerings: offerings.count,
trustContent: trust.count,
fields: fields.count,
inquiryForms: inquiryForm ? 1 : 0,
},
},
});
return { offerings: offerings.count, trustContent: trust.count, fields: fields.count };
return {
offerings: offerings.count,
trustContent: trust.count,
fields: fields.count,
inquiryForms: inquiryForm ? 1 : 0,
};
});
return { imported: true, counts: result };
}
+6 -9
View File
@@ -56,28 +56,25 @@ export class ChangeAdminPasswordDto {
}
export class CreateTrustContentDto {
@IsIn(["schedule", "coverage", "process", "credential", "case", "promise"])
type!: string;
@IsString() type!: string;
@IsString() title!: string;
@IsOptional() @IsString() summary?: string;
@IsString() content!: string;
@IsOptional() @IsString() coverUrl?: string;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() @IsBoolean() isPublished?: boolean;
@IsOptional() config?: Record<string, unknown>;
@IsOptional() @IsObject() config?: Record<string, unknown>;
}
export class UpdateTrustContentDto {
@IsOptional()
@IsIn(["schedule", "coverage", "process", "credential", "case", "promise"])
type?: string;
@IsOptional() @IsString() type?: string;
@IsOptional() @IsString() title?: string;
@IsOptional() @IsString() summary?: string;
@IsOptional() @IsString() content?: string;
@IsOptional() @IsString() coverUrl?: string;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() @IsBoolean() isPublished?: boolean;
@IsOptional() config?: Record<string, unknown>;
@IsOptional() @IsObject() config?: Record<string, unknown>;
}
export class UpdateBookingStatusDto {
@@ -125,7 +122,7 @@ export class CreateOfferingDto {
@IsOptional() @IsInt() @Min(0) priceAmount?: number;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() @IsBoolean() isEnabled?: boolean;
@IsOptional() config?: Record<string, unknown>;
@IsOptional() @IsObject() config?: Record<string, unknown>;
@IsOptional() sections?: Array<{
type: string;
title: string;
@@ -146,7 +143,7 @@ export class UpdateOfferingDto {
@IsOptional() @IsInt() @Min(0) priceAmount?: number;
@IsOptional() @IsInt() @Min(0) @Max(9999) sortOrder?: number;
@IsOptional() @IsBoolean() isEnabled?: boolean;
@IsOptional() config?: Record<string, unknown>;
@IsOptional() @IsObject() config?: Record<string, unknown>;
@IsOptional() sections?: Array<{
type: string;
title: string;
+20 -5
View File
@@ -12,6 +12,7 @@ import {
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
} from "@personal-brand/config";
import { isTrustContentComplete } from "@personal-brand/types";
import { PrismaService } from "./prisma.service.js";
import { BrandReleaseService } from "./brand-release.service.js";
import { validateFieldSnapshot } from "@personal-brand/validation";
@@ -80,11 +81,14 @@ export class BrandReleaseApiService {
}),
database.trustContent.findMany({
where: { brandId, isPublished: true },
select: { type: true, title: true, content: true },
select: { type: true, title: true, content: true, config: true },
}),
]);
const validTrustItems = trustItems.filter(
(item) => item.title.trim().length > 0 && item.content.trim().length > 0,
const validTrustItems = trustItems.filter((item) =>
isTrustContentComplete(
item,
packageManifest?.trustContentTypes?.find((type) => type.type === item.type),
),
);
const offeringIds = new Set(offerings.map((item) => item.id));
const usableForms = forms.filter(
@@ -145,8 +149,19 @@ export class BrandReleaseApiService {
checks.push({
key: `trust:${type.type}`,
label: `请完善${type.label}`,
passed: publishedTrustTypes.has(type.type),
help: ["标题和详细内容都填写后才能发布。", type.help].filter(Boolean).join(" "),
passed:
publishedTrustTypes.has(type.type) &&
(type.maxPublishedItems === undefined ||
trustItems.filter((item) => item.type === type.type).length <= type.maxPublishedItems),
help: [
"请完整填写该区块的可编辑字段。",
type.maxPublishedItems === undefined
? undefined
: `此区块最多保留 ${type.maxPublishedItems} 条公开记录。`,
type.help,
]
.filter(Boolean)
.join(" "),
destination: "/admin/trust",
});
}
@@ -80,7 +80,15 @@ export class AdminConfigController {
current?.config && typeof current.config === "object" && !Array.isArray(current.config)
? (current.config as Record<string, unknown>)
: {};
const nextConfig = config ? { ...currentConfig, ...config } : undefined;
const nextConfig = {
...currentConfig,
...(config ?? {}),
// 兼容旧模板:品牌简介的唯一编辑入口是 BrandProfile.description,
// 旧视觉模板仍从 config.slogan 读取,保存时保持两者同步。
...(fields.description !== undefined && config?.slogan === undefined
? { slogan: fields.description }
: {}),
};
if (config?.visualTemplateKey && config.visualTemplateKey !== currentConfig.visualTemplateKey) {
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(
this.brandId(request),
@@ -121,7 +129,7 @@ export class AdminConfigController {
where: { id: this.brandId(request) },
data: {
...fields,
...(nextConfig ? { config: nextConfig as Prisma.InputJsonValue } : {}),
...(Object.keys(nextConfig).length ? { config: nextConfig } : {}),
},
});
}
@@ -300,34 +308,17 @@ export class AdminConfigController {
@Body() body: CreateTrustContentDto,
): Promise<unknown> {
this.requireAdmin(request);
const { config, ...fields } = body;
return this.prisma.trustContent.create({
data: {
...fields,
brandId: this.brandId(request),
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
const brandId = this.brandId(request);
return this.templateWorkspace.createTrustContent(brandId, body);
}
@Patch("trust-content/:id")
async updateTrustContent(
updateTrustContent(
@Req() request: FastifyRequest,
@Param("id") id: string,
@Body() body: UpdateTrustContentDto,
): Promise<unknown> {
this.requireAdmin(request);
const item = await this.prisma.trustContent.findFirst({
where: { id, brandId: this.brandId(request) },
});
if (!item) throw new BadRequestException("信任内容不存在");
const { config, ...fields } = body;
return this.prisma.trustContent.update({
where: { id },
data: {
...fields,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
return this.templateWorkspace.updateTrustContent(this.brandId(request), id, body);
}
@Delete("trust-content/:id")
async deleteTrustContent(
@@ -18,6 +18,13 @@ import type {
RuntimeTrustItem,
RuntimeWorkspace,
} from "@personal-brand/types";
import {
projectBrandAliases,
projectOfferingDetails,
projectTemplateData,
projectTrustItem,
projectTrustPresentation,
} from "@personal-brand/types";
@Controller("public/workspace")
export class PublicWorkspaceController {
@@ -113,15 +120,19 @@ export class PublicWorkspaceController {
const templatePackageManifest =
releaseSnapshot.templatePackageManifest ??
getTemplatePackageManifestForVisualKey(visualTemplateKey);
const runtimeBrand = {
...brandData,
...brandConfig,
};
// 标准 BrandProfile 字段优先,兼容旧模板仍使用的 config 字段。
// 这样后台编辑 description/contactPhone 等标准字段后,旧模板也会立即读取新值。
const runtimeBrand = projectBrandAliases(brandData, brandConfig);
const declaredTemplateFields = templatePackageManifest?.templateFields ?? [];
const templateData = projectTemplateData(
brandConfig,
declaredTemplateFields.map((field) => field.key),
);
const runtimeOfferings: RuntimeOffering[] = offeringsData.map((raw) => {
const item = raw;
const config = this.jsonObject(item.config);
const sections = Array.isArray(config.sections) ? config.sections : [];
const details = this.jsonObject(config.details);
const details = projectOfferingDetails(config);
const media = Array.isArray(config.media)
? config.media.flatMap((entry) => {
const value = this.jsonObject(entry);
@@ -139,14 +150,6 @@ export class PublicWorkspaceController {
: [];
})
: [];
const materialsList = Array.isArray(details.materialsList)
? details.materialsList.flatMap((entry) => {
const value = this.jsonObject(entry);
return typeof value.name === "string" && typeof value.spec === "string"
? [{ name: value.name, spec: value.spec }]
: [];
})
: [];
return {
id: this.string(item.id),
name: this.string(item.name),
@@ -187,12 +190,10 @@ export class PublicWorkspaceController {
: [],
media,
details: {
background: typeof details.background === "string" ? details.background : "",
designConcept: typeof details.designConcept === "string" ? details.designConcept : "",
crafts: Array.isArray(details.crafts)
? details.crafts.filter((craft): craft is string => typeof craft === "string")
: [],
materialsList,
background: details.background,
designConcept: details.designConcept,
crafts: details.crafts,
materialsList: details.materialsList,
},
},
sections: sections
@@ -211,18 +212,25 @@ export class PublicWorkspaceController {
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(this.string(value.type))
? (value.type as RuntimeInquiryField["type"])
: "text";
const sourceType = this.string(value.type);
const type =
sourceType === "phone"
? "tel"
: sourceType === "multi-select"
? "checkbox"
: [
"text",
"tel",
"number",
"select",
"radio",
"checkbox",
"checkbox",
"textarea",
"date",
].includes(sourceType)
? (sourceType as RuntimeInquiryField["type"])
: "text";
const options = Array.isArray(value.options)
? value.options.flatMap((option) => {
if (typeof option === "string") return [{ label: option, value: option }];
@@ -243,28 +251,14 @@ export class PublicWorkspaceController {
},
];
});
const trustPresentation = trustData.reduce<Record<string, unknown>>((result, raw) => {
const item = this.jsonObject(raw);
const config = this.jsonObject(item.config);
for (const [key, value] of Object.entries(config)) {
if (!(key in result)) result[key] = value;
}
if (item.type === "profile" && typeof result.bio !== "string") result.bio = item.content;
return result;
}, {});
const trustDeclarations = templatePackageManifest?.trustContentTypes ?? [];
const trustItems: RuntimeTrustItem[] = trustData.flatMap((raw) => {
const item = this.jsonObject(raw);
if (typeof item.type !== "string" || typeof item.title !== "string") return [];
return [
{
type: item.type,
title: item.title,
summary: typeof item.summary === "string" ? item.summary : null,
content: typeof item.content === "string" ? item.content : "",
config: this.jsonObject(item.config),
},
];
const item = projectTrustItem(this.jsonObject(raw));
return item && trustDeclarations.some((declaration) => declaration.type === item.type)
? [item]
: [];
});
const trustPresentation = projectTrustPresentation(trustItems, trustDeclarations);
const runtimeWorkspace: RuntimeWorkspace = {
schemaVersion: "1.0.0",
publication: {
@@ -273,6 +267,7 @@ export class PublicWorkspaceController {
publishedAt: release.createdAt.toISOString(),
},
brand: runtimeBrand,
templateData,
navigation: {
tabs:
templatePackageManifest?.navigation.map((tab) => ({
@@ -5,14 +5,61 @@ import {
getVisualTemplate,
getVisualTemplateManifest,
getDefaultVisualTemplateKey,
getTemplatePackageManifestForVisualKey,
isVisualTemplateCompatible,
} from "@personal-brand/config";
import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.js";
import type { BrandTemplateKey } from "@personal-brand/types";
import { PrismaService } from "./prisma.service.js";
@Injectable()
export class TemplateWorkspaceService {
constructor(private readonly prisma: PrismaService) {}
async getTrustContentTypes(brandId: string): Promise<string[]> {
const brand = await this.prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true, config: true },
});
const config =
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
? (brand.config as Record<string, unknown>)
: {};
const visualKey =
typeof config.visualTemplateKey === "string"
? config.visualTemplateKey
: getDefaultVisualTemplateKey(brand?.templateKey ?? "personal");
return (
getTemplatePackageManifestForVisualKey(visualKey)?.trustContentTypes?.map(
(item) => item.type,
) ?? []
);
}
async createTrustContent(brandId: string, body: CreateTrustContentDto) {
if (!(await this.getTrustContentTypes(brandId)).includes(body.type))
throw new BadRequestException("当前模板不支持此信任内容类型");
const { config, ...fields } = body;
return this.prisma.trustContent.create({
data: {
...fields,
brandId,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
async updateTrustContent(brandId: string, id: string, body: UpdateTrustContentDto) {
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
if (!item) throw new BadRequestException("信任内容不存在");
if (body.type !== undefined && !(await this.getTrustContentTypes(brandId)).includes(body.type))
throw new BadRequestException("当前模板不支持此信任内容类型");
const { config, ...fields } = body;
return this.prisma.trustContent.update({
where: { id },
data: {
...fields,
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
},
});
}
async getEffectiveTemplateKey(brandId: string): Promise<BrandTemplateKey> {
const [installation, brand] = await Promise.all([
this.prisma.brandTemplateInstallation.findFirst({
+358 -7
View File
@@ -28,6 +28,211 @@ after(async () => {
await prisma.$disconnect();
});
test("food structured edits survive publication and reach the generated page slots", async () => {
const { readFileSync } = await import("node:fs");
const { runInNewContext } = await import("node:vm");
const user = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
const headers = {
authorization: `Bearer ${signIdentity({ subject: user.id, brandId, role: "admin" })}`,
};
const records = await prisma.trustContent.findMany({
where: {
brandId,
type: { in: ["schedule", "coverage", "process", "credential", "case", "promise"] },
isPublished: true,
},
});
const latest = await prisma.brandRelease.findFirstOrThrow({
where: { brandId },
orderBy: { version: "desc" },
});
const before = JSON.parse((await request("/public/workspace")).body);
try {
for (const item of records) {
const url = `/admin/config/trust-content/${item.id}`;
assert.equal(
(await request(url, { method: "PATCH", payload: { config: {} } })).statusCode,
401,
);
assert.equal(
(
await request(url, {
method: "PATCH",
headers: { authorization: `Bearer ${customerToken}` },
payload: { config: {} },
})
).statusCode,
403,
);
assert.equal(
(await request(url, { method: "PATCH", headers, payload: { config: "invalid" } }))
.statusCode,
400,
);
const config = { ...item.config };
if (item.type === "schedule") {
config.weekdayDetail = "测试工作日地点";
config.weekendDetail = "测试周末地点";
}
if (item.type === "coverage") {
config.pickupDetail = "测试自取说明";
config.deliveryDetail = "测试配送说明";
}
if (item.type === "process")
config.steps = [{ title: "测试第一步", detail: "测试步骤说明" }, ...config.steps.slice(1)];
if (item.type === "credential")
config.standards = [{ title: "编辑后的卫生标准", detail: "编辑后的说明" }];
if (item.type === "case")
config.entries = [
{ badge: "测", title: "编辑后的合作案例", detail: "编辑后的交付", result: "完成" },
];
if (item.type === "promise")
config.commitments = [
{ label: "测试时段", detail: "编辑后的回复说明", highlight: "30 分钟内" },
];
assert.equal(
(
await request(url, {
method: "PATCH",
headers,
payload: {
content: ["schedule", "coverage", "process"].includes(item.type) ? "" : item.content,
config,
},
})
).statusCode,
200,
);
}
assert.deepEqual(
JSON.parse((await request("/public/workspace")).body).trustItems,
before.trustItems,
);
assert.equal(
(
await request("/admin/releases/publish", {
method: "POST",
headers,
payload: { note: "结构化页面集成测试" },
})
).statusCode,
201,
);
const workspace = JSON.parse((await request("/public/workspace")).body);
let page;
runInNewContext(
readFileSync(
new URL(
"../../../packages/template-acheng-campus-food/miniapp/pages/stall-service/index.js",
import.meta.url,
),
"utf8",
),
{
Page(value) {
page = value;
},
require(name) {
return name.includes("runtime-workspace")
? { loadWorkspaceWithFallback: () => Promise.resolve(workspace) }
: { openPage() {} };
},
},
);
page.setData = (data) => Object.assign(page.data, data);
await page.load();
assert.equal(page.data.schedule.rows.length, 2);
assert.equal(page.data.schedule.rows[0].detail, "测试工作日地点");
assert.equal(page.data.schedule.rows[1].detail, "测试周末地点");
assert.equal(page.data.coverage.config.pickupDetail, "测试自取说明");
assert.equal(page.data.coverage.config.deliveryDetail, "测试配送说明");
assert.equal(page.data.process.steps.length, 4);
assert.equal(page.data.process.steps[0].detail, "测试步骤说明");
let owner;
runInNewContext(
readFileSync(
new URL(
"../../../packages/template-acheng-campus-food/miniapp/pages/bookings/index.js",
import.meta.url,
),
"utf8",
),
{
Page(value) {
owner = value;
},
require(name) {
return name.includes("runtime-workspace")
? { loadWorkspaceWithFallback: () => Promise.resolve(workspace) }
: {};
},
},
);
owner.setData = (data) => Object.assign(owner.data, data);
owner.onLoad();
await new Promise((resolve) => setImmediate(resolve));
assert.equal(owner.data.credentials[0].config.standards[0].title, "编辑后的卫生标准");
assert.equal(owner.data.cases[0].entries[0].result, "完成");
assert.equal(owner.data.promises[0].config.commitments[0].highlight, "30 分钟内");
assert.ok(workspace.trustItems.every((item) => typeof item.summary === "string"));
assert.ok(workspace.trustItems.every((item) => typeof item.id === "string"));
assert.equal(
new Set(workspace.trustItems.map((item) => item.id)).size,
workspace.trustItems.length,
);
const schedule = records.find((item) => item.type === "schedule");
await request(`/admin/config/trust-content/${schedule.id}`, {
method: "PATCH",
headers,
payload: { config: {} },
});
const blocked = await request("/admin/releases/publish", {
method: "POST",
headers,
payload: {},
});
assert.equal(blocked.statusCode, 400);
await prisma.trustContent.update({
where: { id: schedule.id },
data: { config: schedule.config },
});
const duplicate = await prisma.trustContent.create({
data: {
brandId,
type: "schedule",
title: "重复公开日程",
content: "",
config: schedule.config,
isPublished: true,
},
});
try {
const duplicateReadiness = JSON.parse(
(await request("/admin/releases/readiness", { headers })).body,
);
assert.equal(
duplicateReadiness.checks.find((check) => check.key === "trust:schedule").passed,
false,
);
assert.equal(
(await request("/admin/releases/publish", { method: "POST", headers, payload: {} }))
.statusCode,
400,
);
} finally {
await prisma.trustContent.delete({ where: { id: duplicate.id } });
}
} finally {
for (const item of records)
await prisma.trustContent.update({
where: { id: item.id },
data: { config: item.config, content: item.content },
});
await prisma.brandRelease.deleteMany({ where: { brandId, version: { gt: latest.version } } });
await prisma.brandRelease.update({ where: { id: latest.id }, data: { status: latest.status } });
}
});
test("admin release lifecycle is authorized, brand-scoped, and versioned", async () => {
const missing = await request("/admin/releases");
assert.equal(missing.statusCode, 401);
@@ -241,6 +446,7 @@ test("admin release lifecycle is authorized, brand-scoped, and versioned", async
isPublished: scheduleTrust.isPublished,
title: scheduleTrust.title,
content: scheduleTrust.content,
config: scheduleTrust.config,
};
try {
await prisma.trustContent.update({
@@ -274,7 +480,7 @@ test("admin release lifecycle is authorized, brand-scoped, and versioned", async
);
await prisma.trustContent.update({
where: { id: scheduleTrust.id },
data: { title: originalScheduleTrust.title, content: " \n " },
data: { title: originalScheduleTrust.title, content: " \n ", config: {} },
});
const missingContent = JSON.parse(
(
@@ -920,6 +1126,7 @@ test("admin can install doors industry template through the shared runtime contr
test("admin can preview and import sample content idempotently", async () => {
const originalBrand = await prisma.brandProfile.findUnique({ where: { id: brandId } });
const originalForms = await prisma.inquiryForm.findMany({ where: { brandId } });
const originalSampleTrust = await prisma.trustContent.findMany({
where: { brandId, content: "示例内容,待品牌主理人完善。" },
});
@@ -934,6 +1141,15 @@ test("admin can preview and import sample content idempotently", async () => {
where: { brandId, content: "示例内容,待品牌主理人完善。" },
});
await prisma.brandFieldDefinition.deleteMany({ where: { brandId, source: "sample" } });
if (!originalForms.some((item) => item.isEnabled)) {
await prisma.inquiryForm.create({
data: {
brandId,
name: "现有客户表单",
fieldsSnapshot: [{ key: "phone", label: "联系电话", type: "tel", required: true }],
},
});
}
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
@@ -943,11 +1159,35 @@ test("admin can preview and import sample content idempotently", async () => {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(preview.statusCode, 200);
assert.equal(JSON.parse(preview.body).willCreateInquiryForm, false);
const imported = await request("/admin/workspace/sample-content/import", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
});
assert.equal(imported.statusCode, 201);
assert.equal(JSON.parse(imported.body).counts.inquiryForms, 0);
assert.ok(await prisma.inquiryForm.findFirst({ where: { brandId, name: "现有客户表单" } }));
await prisma.offering.deleteMany({
where: {
brandId,
name: { in: ["序章·入户门", "庭院·边界门", "室内·静谧门", "一对一门系统设计咨询"] },
},
});
await prisma.trustContent.deleteMany({
where: { brandId, content: "示例内容,待品牌主理人完善。" },
});
await prisma.brandFieldDefinition.deleteMany({ where: { brandId, source: "sample" } });
await prisma.inquiryForm.deleteMany({ where: { brandId } });
const importedWithoutForm = await request("/admin/workspace/sample-content/import", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
});
assert.equal(importedWithoutForm.statusCode, 201);
assert.equal(JSON.parse(importedWithoutForm.body).counts.inquiryForms, 1);
const importedForm = await prisma.inquiryForm.findFirstOrThrow({
where: { brandId, name: "门系统咨询表单" },
});
assert.ok(Array.isArray(importedForm.fieldsSnapshot) && importedForm.fieldsSnapshot.length > 0);
const duplicate = await request("/admin/workspace/sample-content/import", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
@@ -970,6 +1210,14 @@ test("admin can preview and import sample content idempotently", async () => {
});
}
await prisma.brandFieldDefinition.deleteMany({ where: { brandId, source: "sample" } });
await prisma.inquiryForm.deleteMany({ where: { brandId, name: "门系统咨询表单" } });
if (originalForms.length) {
await prisma.inquiryForm.createMany({
data: originalForms.map(
({ id: _id, createdAt: _createdAt, updatedAt: _updatedAt, ...item }) => item,
),
});
}
await prisma.capabilityAuditLog.deleteMany({ where: { brandId, capabilityKey: "doors" } });
await prisma.brandProfile.update({
where: { id: brandId },
@@ -1039,8 +1287,14 @@ test("admin can install a template and public workspace exposes enabled configur
const templateContent = JSON.parse(workspace.body).templateContent;
assert.equal(templateContent.displayName, "阿成校园餐");
assert.ok(templateContent.trustContentTypes.some((item) => item.type === "schedule"));
assert.ok(templateContent.trustContentTypes.some((item) => item.label === "出摊与营业安排"));
assert.ok(templateContent.trustContentTypes.some((item) => item.label === "每周出摊安排"));
assert.ok(templateContent.admin.sections.some((section) => section.title === "首页出摊信息"));
assert.ok(
templateContent.admin.sections
.filter((section) => section.title === "首页出摊信息")
.every((section) => section.page === "home"),
);
assert.ok(templateContent.navigation.some((item) => item.page === "home" && item.label));
assert.ok(
templateContent.admin.sections
.flatMap((section) => section.fields)
@@ -1197,7 +1451,14 @@ test("public workspace exposes declared brand and trust presentation data", asyn
);
const doorType = body.inquiryForms[0].fields.find((field) => field.key === "doorType");
assert.equal(doorType.options.length, 5);
assert.equal(doorType.options[0].value, "入户大门(防暴铸铜 / 实木)");
assert.equal(doorType.options[0].value, "entry");
const phone = body.inquiryForms[0].fields.find((field) => field.key === "contactPhone");
assert.equal(phone.type, "tel");
const foodWorkspace = await request("/public/workspace?brandSlug=default-brand");
const foodPhone = JSON.parse(foodWorkspace.body).inquiryForms[0].fields.find(
(field) => field.key === "phone",
);
assert.equal(foodPhone.type, "tel");
} finally {
await prisma.brandProfile.update({
where: { id: doorsBrand.id },
@@ -1233,7 +1494,20 @@ test("edited template facts reach public workspace only after publication", asyn
const changedIntro = "集成测试发布后联系说明";
const changedHint = "集成测试咨询后处理说明";
const changedDetailHero = "https://example.com/integration-detail.jpg";
const changedDetailBackground = "集成测试案例详情正文";
const changedTemplateData = "集成测试设计理念";
const changedStats = [{ value: "42", label: "测试成果" }];
const obsolete = await prisma.trustContent.create({
data: {
brandId: doorsBrand.id,
type: "profile",
title: "旧类型不得覆盖模板配置",
content: "旧简介",
config: { stats: [{ value: "旧值", label: "不得显示" }], internalOnly: "不得公开" },
isPublished: true,
sortOrder: -100,
},
});
try {
const brandConfig = originalBrandConfig ?? {};
const presentation = brandConfig.visualPresentation ?? {};
@@ -1248,6 +1522,11 @@ test("edited template facts reach public workspace only after publication", asyn
success: { ...presentation.success, intro: changedIntro },
detail: { ...presentation.detail, inquiryHint: changedHint },
},
templateData: {
...(brandConfig.templateData ?? {}),
designPhilosophy: changedTemplateData,
internalOnly: "不得公开",
},
},
},
});
@@ -1266,6 +1545,10 @@ test("edited template facts reach public workspace only after publication", asyn
...(offering.config ?? {}),
area: changedArea,
detailHero: changedDetailHero,
details: {
...((offering.config ?? {}).details ?? {}),
background: changedDetailBackground,
},
},
},
});
@@ -1298,12 +1581,24 @@ test("edited template facts reach public workspace only after publication", asyn
(await request("/public/workspace?brandSlug=linjing-doors")).body,
);
assert.equal(afterPublish.brand.homeHero.title, changedTitle);
assert.equal(afterPublish.templateData.designPhilosophy, changedTemplateData);
assert.equal(Object.hasOwn(afterPublish.templateData, "internalOnly"), false);
assert.equal(afterPublish.brand.visualPresentation.success.intro, changedIntro);
assert.equal(afterPublish.brand.visualPresentation.detail.inquiryHint, changedHint);
assert.deepEqual(afterPublish.trustPresentation.stats, changedStats);
assert.equal(
afterPublish.trustItems.some((item) => item.type === "profile"),
false,
);
assert.equal(Object.hasOwn(afterPublish.trustPresentation, "internalOnly"), false);
assert.equal(afterPublish.offerings[0].presentation.area, changedArea);
assert.equal(afterPublish.offerings[0].presentation.heroImage, changedDetailHero);
assert.equal(
afterPublish.offerings[0].presentation.details.background,
changedDetailBackground,
);
} finally {
await prisma.trustContent.delete({ where: { id: obsolete.id } });
await prisma.brandProfile.update({
where: { id: doorsBrand.id },
data: { config: originalBrandConfig },
@@ -1377,6 +1672,15 @@ test("admin can create and version an inquiry form", async () => {
label: "联系渠道",
options: [{ label: "微信", value: "wechat" }],
},
{
key: "topics",
type: "multi-select",
label: "关注方向",
options: [
{ label: "咨询", value: "consulting" },
{ label: "设计", value: "design" },
],
},
],
},
});
@@ -1425,20 +1729,25 @@ test("admin can create and version an inquiry form", async () => {
assert.equal((await publishReleaseForTests()).statusCode, 201);
const publicForm = await request(`/public/inquiry-forms/${id}`);
assert.equal(publicForm.statusCode, 200);
assert.equal(
JSON.parse(publicForm.body).fieldsSnapshot.find((field) => field.key === "topics").type,
"multi-select",
);
const publicOffering = await request(`/public/offerings/${offering.id}`);
assert.equal(publicOffering.statusCode, 200);
assert.equal(JSON.parse(publicOffering.body).inquiryForms[0].id, id);
const publicWorkspace = await request("/public/workspace");
assert.equal(publicWorkspace.statusCode, 200);
assert.ok(JSON.parse(publicWorkspace.body).inquiryForms.some((form) => form.key === id));
const runtimeForm = JSON.parse(publicWorkspace.body).inquiryForms.find(
(form) => form.key === id,
);
assert.ok(runtimeForm);
assert.equal(runtimeForm.fields.find((field) => field.key === "topics").type, "checkbox");
assert.ok(
JSON.parse(publicWorkspace.body).inquiryForms.some(
(form) => form.key === id && form.targetId === offering.id,
),
);
const runtimeForm = JSON.parse(publicWorkspace.body).inquiryForms.find(
(form) => form.key === id,
);
assert.deepEqual(runtimeForm.fields[1].options, [{ label: "微信", value: "wechat" }]);
await prisma.inquiryForm.update({
where: { id },
@@ -1833,6 +2142,8 @@ test("admin can read and update brand and service configuration", async () => {
assert.equal(updatedBrand.statusCode, 200);
assert.equal(JSON.parse(updatedBrand.body).description, "集成测试品牌简介");
assert.equal(JSON.parse(updatedBrand.body).templateKey, "personal");
const updatedConfig = JSON.parse(updatedBrand.body).config;
assert.equal(updatedConfig.slogan, "集成测试品牌简介");
const updatedService = await request(`/admin/workspace/offerings/${serviceBefore.id}`, {
method: "PATCH",
@@ -1950,6 +2261,26 @@ test("admin can manage trust content", async () => {
});
const token = JSON.parse(login.body).token;
assert.equal((await request("/admin/config/trust-content")).statusCode, 401);
assert.equal(
(
await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: "Bearer invalid" },
payload: { type: "schedule", title: "安排", content: "时间" },
})
).statusCode,
401,
);
assert.equal(
(
await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: { type: "schedule", title: "安排", content: "时间" },
})
).statusCode,
403,
);
const created = await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
@@ -1957,6 +2288,25 @@ test("admin can manage trust content", async () => {
});
assert.equal(created.statusCode, 201);
const id = JSON.parse(created.body).id;
const schedule = await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: {
type: "schedule",
title: "每周营业安排",
summary: "周一至周五 17:00 - 22:30",
content: "周六、周日承接团体单",
},
});
assert.equal(schedule.statusCode, 201);
assert.equal(JSON.parse(schedule.body).summary, "周一至周五 17:00 - 22:30");
assert.equal(JSON.parse(schedule.body).content, "周六、周日承接团体单");
const unsupported = await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { type: "unregistered-template-type", title: "不支持", content: "不应保存" },
});
assert.equal(unsupported.statusCode, 400);
const draft = await request("/admin/config/trust-content", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
@@ -1981,6 +2331,7 @@ test("admin can manage trust content", async () => {
assert.equal(updated.statusCode, 200);
assert.equal(JSON.parse(updated.body).content, "更新后的内容");
} finally {
await prisma.trustContent.delete({ where: { id: JSON.parse(schedule.body).id } });
const deleted = await request(`/admin/config/trust-content/${id}`, {
method: "DELETE",
headers: { authorization: `Bearer ${token}` },
+23
View File
@@ -1,3 +1,4 @@
const assert = require("node:assert/strict");
const { randomBytes } = require("node:crypto");
const { spawnSync } = require("node:child_process");
const { PrismaClient } = require("@prisma/client");
@@ -10,6 +11,7 @@ const testUrl = new URL(databaseUrl);
testUrl.searchParams.set("schema", schema);
const testEnvironment = { ...process.env, DATABASE_URL: testUrl.toString(), NODE_ENV: "test" };
const administrator = new PrismaClient();
const fixtureDatabase = new PrismaClient({ datasourceUrl: testUrl.toString() });
function run(command, args) {
const result = spawnSync(command, args, { stdio: "inherit", env: testEnvironment });
@@ -25,9 +27,30 @@ async function main() {
created = true;
if (run("pnpm", ["exec", "prisma", "migrate", "deploy"]) !== 0) return status;
if (run("pnpm", ["db:seed"]) !== 0) return status;
const initialTrustCount = await fixtureDatabase.trustContent.count();
const initialFormCount = await fixtureDatabase.inquiryForm.count();
const initialReleases = await fixtureDatabase.brandRelease.findMany({ orderBy: { id: "asc" } });
if (run("pnpm", ["db:seed"]) !== 0) return status;
assert.equal(
await fixtureDatabase.trustContent.count(),
initialTrustCount,
"Repeated seed must not duplicate trust content",
);
assert.equal(
await fixtureDatabase.inquiryForm.count(),
initialFormCount,
"Repeated seed must not duplicate forms",
);
assert.deepEqual(
await fixtureDatabase.brandRelease.findMany({ orderBy: { id: "asc" } }),
initialReleases,
"Repeated seed must preserve release history and snapshots",
);
console.log("Seed idempotency verified: content, forms and release history preserved");
status = run(process.execPath, ["--test", "test/http.integration.test.js"]);
return status;
} finally {
await fixtureDatabase.$disconnect();
if (created) await administrator.$executeRawUnsafe(`DROP SCHEMA "${schema}" CASCADE`);
await administrator.$disconnect();
process.exitCode = status;