fix: 完善模板可视化编辑闭环与通用验收
This commit is contained in:
1 parent
fa6b492bce
commit
22a82dbfba
39 files changed
+7773
-443
No files matched your search
@@ -199,7 +199,7 @@ class AdminWorkspaceController {
|
||||
@Get("preview")
|
||||
async getPreviewWorkspace(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const { brandId } = this.requireAdmin(request);
|
||||
return this.publicWorkspace.getForBrandId(brandId);
|
||||
return this.publicWorkspace.getForBrandId(brandId, true);
|
||||
}
|
||||
private jsonObject(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
|
||||
@@ -18,6 +18,7 @@ import type {
|
||||
RuntimeTrustItem,
|
||||
RuntimeWorkspace,
|
||||
} from "@personal-brand/types";
|
||||
import { buildBrandReleaseSnapshot } from "../../brand-release.service.js";
|
||||
import {
|
||||
projectBrandAliases,
|
||||
projectOfferingDetails,
|
||||
@@ -30,14 +31,16 @@ import {
|
||||
export class PublicWorkspaceService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getForBrandId(brandId: string): Promise<unknown> {
|
||||
async getForBrandId(brandId: string, draft = false): Promise<unknown> {
|
||||
const release = await this.prisma.brandRelease.findFirst({
|
||||
where: { brandId, status: "published" },
|
||||
orderBy: { version: "desc" },
|
||||
select: { version: true, createdAt: true, snapshot: true },
|
||||
});
|
||||
const releaseSnapshot = this.jsonObject(release?.snapshot) as unknown as BrandReleaseSnapshot;
|
||||
if (!release) {
|
||||
const draftSnapshot = draft ? await buildBrandReleaseSnapshot(this.prisma, brandId) : null;
|
||||
const sourceSnapshot = draftSnapshot ?? release?.snapshot;
|
||||
const releaseSnapshot = this.jsonObject(sourceSnapshot) as unknown as BrandReleaseSnapshot;
|
||||
if (!release && !draftSnapshot) {
|
||||
return {
|
||||
contractVersion: "1.0",
|
||||
schemaVersion: "1.0.0",
|
||||
@@ -258,9 +261,9 @@ export class PublicWorkspaceService {
|
||||
const runtimeWorkspace: RuntimeWorkspace = {
|
||||
schemaVersion: "1.0.0",
|
||||
publication: {
|
||||
status: "published",
|
||||
version: release.version,
|
||||
publishedAt: release.createdAt.toISOString(),
|
||||
status: draftSnapshot ? "draft" : "published",
|
||||
version: draftSnapshot ? null : (release?.version ?? null),
|
||||
...(!draftSnapshot && release ? { publishedAt: release.createdAt.toISOString() } : {}),
|
||||
},
|
||||
brand: runtimeBrand,
|
||||
templateData,
|
||||
|
||||
@@ -28,6 +28,254 @@ after(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
test("real template declarations persist brand offering and trust bindings through draft and publication", async (context) => {
|
||||
const user = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
|
||||
const { runtimeContractForBinding } = await import("@personal-brand/types");
|
||||
const readPath = (object, path) => path.reduce((value, key) => value?.[key], object);
|
||||
const writePath = (object, path, value) => {
|
||||
const [key, ...tail] = path;
|
||||
if (!tail.length) object[key] = value;
|
||||
else {
|
||||
object[key] ??= {};
|
||||
writePath(object[key], tail, value);
|
||||
}
|
||||
};
|
||||
let checked = 0;
|
||||
for (const slug of ["default-brand", "linjing-doors"]) {
|
||||
const original = await prisma.brandProfile.findUniqueOrThrow({ where: { slug } });
|
||||
const originalOffering = await prisma.offering.findFirstOrThrow({
|
||||
where: { brandId: original.id, isEnabled: true },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
});
|
||||
const originalReleases = await prisma.brandRelease.findMany({
|
||||
where: { brandId: original.id },
|
||||
});
|
||||
const originalTrust = await prisma.trustContent.findMany({
|
||||
where: { brandId: original.id, isPublished: true },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
});
|
||||
const headers = {
|
||||
authorization: `Bearer ${signIdentity({ subject: user.id, brandId: original.id, role: "admin" })}`,
|
||||
};
|
||||
const manifest = JSON.parse(
|
||||
(await request("/admin/workspace", { headers })).body,
|
||||
).templateContent;
|
||||
const fields = [
|
||||
...manifest.admin.sections.flatMap((section) => section.fields),
|
||||
...(manifest.templateFields ?? []),
|
||||
];
|
||||
const distinct = [...new Map(fields.map((field) => [field.binding, field])).values()];
|
||||
const brandPatch = { config: structuredClone(original.config ?? {}) };
|
||||
const offeringPatch = { config: structuredClone(originalOffering.config ?? {}) };
|
||||
const expected = [];
|
||||
for (const field of distinct) {
|
||||
const [source, ...path] = field.binding.split(".");
|
||||
if (!["brand", "offering"].includes(source)) continue;
|
||||
const token = "binding-" + slug + "-" + field.key;
|
||||
const value =
|
||||
field.input === "list"
|
||||
? [
|
||||
field.itemValueKey
|
||||
? token
|
||||
: Object.fromEntries(
|
||||
(field.itemFields ?? []).map((child) => [child.key, token + "-" + child.key]),
|
||||
),
|
||||
]
|
||||
: field.input === "image"
|
||||
? "https://example.com/" + token + ".jpg"
|
||||
: field.input === "phone"
|
||||
? "13800138001"
|
||||
: field.input === "number"
|
||||
? 73
|
||||
: field.input === "boolean"
|
||||
? true
|
||||
: token;
|
||||
writePath(source === "brand" ? brandPatch : offeringPatch, path, value);
|
||||
expected.push({ field, source, path, value });
|
||||
}
|
||||
delete brandPatch.config.visualTemplateKey;
|
||||
const createdTrustIds = [];
|
||||
try {
|
||||
assert.equal(
|
||||
(await request("/admin/config/brand", { method: "PATCH", headers, payload: brandPatch }))
|
||||
.statusCode,
|
||||
200,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await request("/admin/workspace/offerings/" + originalOffering.id, {
|
||||
method: "PATCH",
|
||||
headers,
|
||||
payload: offeringPatch,
|
||||
})
|
||||
).statusCode,
|
||||
200,
|
||||
);
|
||||
const savedBrand = JSON.parse((await request("/admin/config/brand", { headers })).body);
|
||||
const expectedTrust = [];
|
||||
for (const declaration of manifest.trustContentTypes) {
|
||||
const records = originalTrust.filter((item) => item.type === declaration.type);
|
||||
let record =
|
||||
records.find((item) => Object.keys(item.config ?? {}).length > 0) ?? records[0];
|
||||
if (!record) {
|
||||
record = await prisma.trustContent.create({
|
||||
data: {
|
||||
brandId: original.id,
|
||||
type: declaration.type,
|
||||
title: "字段验收占位",
|
||||
content: "字段验收占位",
|
||||
isPublished: true,
|
||||
config: {},
|
||||
},
|
||||
});
|
||||
createdTrustIds.push(record.id);
|
||||
}
|
||||
const patch = { config: structuredClone(record.config ?? {}) };
|
||||
const trustFields = [
|
||||
...["title", "summary", "content"]
|
||||
.filter((key) => !declaration.hideStandardFields?.includes(key))
|
||||
.map((key) => ({ key, binding: "trust." + key, input: "text" })),
|
||||
...(declaration.configFields ?? []),
|
||||
];
|
||||
for (const field of trustFields) {
|
||||
const token = "binding-" + slug + "-" + declaration.type + "-" + field.key;
|
||||
const path = field.binding.split(".").slice(1);
|
||||
const existing = readPath(record, path);
|
||||
const value =
|
||||
field.input === "list"
|
||||
? Array.from(
|
||||
{ length: Array.isArray(existing) && existing.length ? existing.length : 1 },
|
||||
(_, index) =>
|
||||
Object.fromEntries(
|
||||
(field.itemFields ?? []).map((child) => [
|
||||
child.key,
|
||||
token + "-" + index + "-" + child.key,
|
||||
]),
|
||||
),
|
||||
)
|
||||
: token;
|
||||
writePath(patch, path, value);
|
||||
expectedTrust.push({ id: record.id, path, value, binding: field.binding });
|
||||
}
|
||||
const updated = await request("/admin/config/trust-content/" + record.id, {
|
||||
method: "PATCH",
|
||||
headers,
|
||||
payload: patch,
|
||||
});
|
||||
assert.equal(updated.statusCode, 200, updated.body);
|
||||
}
|
||||
const savedTrust = JSON.parse(
|
||||
(await request("/admin/config/trust-content", { headers })).body,
|
||||
);
|
||||
const savedOffering = JSON.parse(
|
||||
(await request("/admin/workspace/offerings", { headers })).body,
|
||||
).find((item) => item.id === originalOffering.id);
|
||||
const draft = JSON.parse((await request("/admin/workspace/preview", { headers })).body);
|
||||
for (const item of expectedTrust) {
|
||||
assert.deepEqual(
|
||||
readPath(
|
||||
savedTrust.find((record) => record.id === item.id),
|
||||
item.path,
|
||||
),
|
||||
item.value,
|
||||
item.binding + " persistence",
|
||||
);
|
||||
assert.deepEqual(
|
||||
readPath(
|
||||
draft.trustItems.find((record) => record.id === item.id),
|
||||
item.path,
|
||||
),
|
||||
item.value,
|
||||
item.binding + " draft projection",
|
||||
);
|
||||
checked += 1;
|
||||
}
|
||||
for (const item of expected) {
|
||||
assert.deepEqual(
|
||||
readPath(item.source === "brand" ? savedBrand : savedOffering, item.path),
|
||||
item.value,
|
||||
item.field.binding + " persistence",
|
||||
);
|
||||
const contract = runtimeContractForBinding(item.field.binding);
|
||||
assert.ok(contract, item.field.binding);
|
||||
let runtimePath = contract.runtimePath.replace(/^workspace\./, "");
|
||||
if (item.field.binding === "offering.config.detailHero")
|
||||
runtimePath = "offerings[].presentation.heroImage";
|
||||
const offeringIndex = draft.offerings.findIndex(
|
||||
(offering) => offering.id === originalOffering.id,
|
||||
);
|
||||
runtimePath = runtimePath.replace("offerings[]", "offerings." + offeringIndex);
|
||||
assert.deepEqual(
|
||||
readPath(draft, runtimePath.split(".")),
|
||||
item.value,
|
||||
item.field.binding + " draft projection",
|
||||
);
|
||||
checked += 1;
|
||||
}
|
||||
const publish = await request("/admin/releases/publish", {
|
||||
method: "POST",
|
||||
headers,
|
||||
payload: { note: "真实声明全部品牌和业务字段验收" },
|
||||
});
|
||||
assert.equal(publish.statusCode, 201, publish.body);
|
||||
const publicWorkspace = JSON.parse(
|
||||
(await request("/public/workspace?brandSlug=" + slug)).body,
|
||||
);
|
||||
assert.deepEqual(publicWorkspace.brand, draft.brand);
|
||||
assert.deepEqual(publicWorkspace.templateData, draft.templateData);
|
||||
assert.deepEqual(publicWorkspace.offerings, draft.offerings);
|
||||
assert.deepEqual(publicWorkspace.trustItems, draft.trustItems);
|
||||
assert.deepEqual(publicWorkspace.trustPresentation, draft.trustPresentation);
|
||||
} finally {
|
||||
const columns = [
|
||||
"name",
|
||||
"tagline",
|
||||
"description",
|
||||
"avatarUrl",
|
||||
"contactPhone",
|
||||
"contactWechat",
|
||||
"address",
|
||||
"coverUrl",
|
||||
"hours",
|
||||
"deliveryNote",
|
||||
"config",
|
||||
];
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: original.id },
|
||||
data: Object.fromEntries(columns.map((key) => [key, original[key]])),
|
||||
});
|
||||
const offeringColumns = ["name", "summary", "description", "priceText", "coverUrl", "config"];
|
||||
await prisma.offering.update({
|
||||
where: { id: originalOffering.id },
|
||||
data: Object.fromEntries(offeringColumns.map((key) => [key, originalOffering[key]])),
|
||||
});
|
||||
await prisma.brandRelease.deleteMany({
|
||||
where: { brandId: original.id, id: { notIn: originalReleases.map((item) => item.id) } },
|
||||
});
|
||||
for (const record of originalTrust)
|
||||
await prisma.trustContent.update({
|
||||
where: { id: record.id },
|
||||
data: {
|
||||
title: record.title,
|
||||
summary: record.summary,
|
||||
content: record.content,
|
||||
config: record.config,
|
||||
},
|
||||
});
|
||||
await prisma.trustContent.deleteMany({ where: { id: { in: createdTrustIds } } });
|
||||
for (const release of originalReleases)
|
||||
await prisma.brandRelease.update({
|
||||
where: { id: release.id },
|
||||
data: { status: release.status },
|
||||
});
|
||||
}
|
||||
}
|
||||
assert.ok(checked > 100, "真实声明应覆盖两个模板全部品牌和业务字段");
|
||||
context.diagnostic(
|
||||
"Validated " + checked + " manifest bindings through persistence draft and publication",
|
||||
);
|
||||
});
|
||||
|
||||
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");
|
||||
@@ -1325,11 +1573,15 @@ test("admin can install a template and public workspace exposes enabled configur
|
||||
}
|
||||
});
|
||||
|
||||
test("admin preview workspace is brand-scoped and exposes only the published runtime", async () => {
|
||||
test("admin preview workspace is authorized and brand-scoped draft runtime", async () => {
|
||||
const user = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
|
||||
const token = signIdentity({ subject: user.id, brandId, role: "admin" });
|
||||
const unauthorized = await request("/admin/workspace/preview");
|
||||
assert.equal(unauthorized.statusCode, 401);
|
||||
const invalid = await request("/admin/workspace/preview", {
|
||||
headers: { authorization: "Bearer invalid-preview-token" },
|
||||
});
|
||||
assert.equal(invalid.statusCode, 401);
|
||||
const wrongRole = await request("/admin/workspace/preview", {
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
});
|
||||
@@ -1339,12 +1591,39 @@ test("admin preview workspace is brand-scoped and exposes only the published run
|
||||
});
|
||||
assert.equal(authorized.statusCode, 200);
|
||||
const workspace = JSON.parse(authorized.body);
|
||||
assert.equal(workspace.publication?.status, "published");
|
||||
assert.equal(workspace.publication?.status, "draft");
|
||||
assert.equal(
|
||||
workspace.brand.slug,
|
||||
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).slug,
|
||||
);
|
||||
assert.equal(workspace.brand.visualTemplateKey, "acheng-campus-food");
|
||||
const unpublishedBrand = await prisma.brandProfile.create({
|
||||
data: {
|
||||
slug: "unpublished-preview-fixture",
|
||||
name: "未发布预览品牌",
|
||||
templateKey: "personal",
|
||||
config: { visualTemplateKey: "linjing-editorial" },
|
||||
adminMemberships: { create: { adminUserId: user.id, role: "owner" } },
|
||||
},
|
||||
});
|
||||
try {
|
||||
const draftToken = signIdentity({
|
||||
subject: user.id,
|
||||
brandId: unpublishedBrand.id,
|
||||
role: "admin",
|
||||
});
|
||||
const draft = await request("/admin/workspace/preview", {
|
||||
headers: { authorization: `Bearer ${draftToken}` },
|
||||
});
|
||||
assert.equal(draft.statusCode, 200);
|
||||
assert.equal(JSON.parse(draft.body).brand.slug, unpublishedBrand.slug);
|
||||
assert.equal(JSON.parse(draft.body).publication.status, "draft");
|
||||
const publicResult = await request("/public/workspace?brandSlug=" + unpublishedBrand.slug);
|
||||
assert.equal(JSON.parse(publicResult.body).publication.status, "unpublished");
|
||||
assert.equal(JSON.parse(publicResult.body).brand, null);
|
||||
} finally {
|
||||
await prisma.brandProfile.delete({ where: { id: unpublishedBrand.id } });
|
||||
}
|
||||
});
|
||||
|
||||
test("admin can customize workspace fields with brand isolation", async () => {
|
||||
@@ -1518,7 +1797,8 @@ test("edited template facts reach public workspace only after publication", asyn
|
||||
const changedDetailHero = "https://example.com/integration-detail.jpg";
|
||||
const changedDetailBackground = "集成测试案例详情正文";
|
||||
const changedTemplateData = "集成测试设计理念";
|
||||
const changedStats = [{ value: "42", label: "测试成果" }];
|
||||
const changedStats = [{ value: "42", label: "测试成果", sub: "持久化子标题" }];
|
||||
const changedDescription = "唯一品牌简介保存发布验证";
|
||||
const obsolete = await prisma.trustContent.create({
|
||||
data: {
|
||||
brandId: doorsBrand.id,
|
||||
@@ -1537,6 +1817,7 @@ test("edited template facts reach public workspace only after publication", asyn
|
||||
method: "PATCH",
|
||||
headers,
|
||||
payload: {
|
||||
description: changedDescription,
|
||||
config: {
|
||||
homeHero: { ...brandConfig.homeHero, title: changedTitle },
|
||||
visualPresentation: {
|
||||
@@ -1553,6 +1834,8 @@ test("edited template facts reach public workspace only after publication", asyn
|
||||
},
|
||||
});
|
||||
assert.equal(brandUpdate.statusCode, 200);
|
||||
const reloadedBrand = await request("/admin/config/brand", { headers });
|
||||
assert.equal(JSON.parse(reloadedBrand.body).description, changedDescription);
|
||||
const trustUpdate = await request(`/admin/config/trust-content/${trust.id}`, {
|
||||
method: "PATCH",
|
||||
headers,
|
||||
@@ -1575,9 +1858,21 @@ test("edited template facts reach public workspace only after publication", asyn
|
||||
},
|
||||
});
|
||||
assert.equal(offeringUpdate.statusCode, 200);
|
||||
const preview = await request("/admin/workspace/preview", { headers });
|
||||
assert.equal(preview.statusCode, 200);
|
||||
const savedDraft = JSON.parse(preview.body);
|
||||
assert.equal(savedDraft.publication.status, "draft");
|
||||
assert.equal(savedDraft.brand.description, changedDescription);
|
||||
assert.equal(savedDraft.templateData.designPhilosophy, changedTemplateData);
|
||||
assert.deepEqual(savedDraft.trustPresentation.stats, changedStats);
|
||||
assert.equal(
|
||||
savedDraft.offerings.find((item) => item.id === offering.id).presentation.area,
|
||||
changedArea,
|
||||
);
|
||||
|
||||
const draftView = JSON.parse((await request("/public/workspace?brandSlug=linjing-doors")).body);
|
||||
assert.deepEqual(draftView.brand.homeHero, before.brand.homeHero);
|
||||
assert.equal(draftView.brand.description, before.brand.description);
|
||||
assert.equal(
|
||||
draftView.brand.visualPresentation.success.intro,
|
||||
before.brand.visualPresentation.success.intro,
|
||||
@@ -1603,6 +1898,7 @@ 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.brand.description, changedDescription);
|
||||
assert.equal(afterPublish.templateData.designPhilosophy, changedTemplateData);
|
||||
assert.equal(Object.hasOwn(afterPublish.templateData, "internalOnly"), false);
|
||||
assert.equal(afterPublish.brand.visualPresentation.success.intro, changedIntro);
|
||||
@@ -1623,7 +1919,7 @@ test("edited template facts reach public workspace only after publication", asyn
|
||||
await prisma.trustContent.delete({ where: { id: obsolete.id } });
|
||||
await prisma.brandProfile.update({
|
||||
where: { id: doorsBrand.id },
|
||||
data: { config: originalBrandConfig },
|
||||
data: { config: originalBrandConfig, description: doorsBrand.description },
|
||||
});
|
||||
await prisma.trustContent.update({
|
||||
where: { id: trust.id },
|
||||
|
||||
Reference in new issue
Block a user