fix: 完善模板可视化编辑闭环与通用验收

This commit is contained in:
que01 committed 2026-10-10 16:20:08 +08:00
1 parent fa6b492bce
commit 22a82dbfba
39 files changed
+7773 -443

No files matched your search

@@ -21,7 +21,7 @@ export function TemplateListField({
},
]}
>
{(rows, { add, remove }, { errors }) => (
{(rows, { add, remove, move }, { errors }) => (
<Space direction="vertical" style={{ width: "100%" }}>
{rows.map((row, index) => (
<Space key={row.key} align="start" wrap>
@@ -40,6 +40,20 @@ export function TemplateListField({
</Form.Item>
))}
<Button onClick={() => remove(row.name)}>删除</Button>
<Button
aria-label={`上移第 ${index + 1} 项`}
disabled={index === 0}
onClick={() => move(index, index - 1)}
>
上移
</Button>
<Button
aria-label={`下移第 ${index + 1} 项`}
disabled={index === rows.length - 1}
onClick={() => move(index, index + 1)}
>
下移
</Button>
</Space>
))}
<Form.ErrorList errors={errors} />
@@ -44,7 +44,7 @@ export function ComponentTemplatePreview({
if (target?.composite) composite = candidate;
candidate = candidate.parentElement?.closest<HTMLElement>("[data-editor-target]") ?? null;
}
return composite ?? deepest;
return deepest ?? composite;
},
[targets],
);
@@ -36,6 +36,7 @@ import { TemplatePreview } from "./TemplatePreview.js";
import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js";
import {
resolvePreviewSelection,
previewTrustRecordId,
type PreviewSelection,
type PreviewTarget,
} from "./preview-selection.js";
@@ -72,7 +73,12 @@ function trustSection(
description: declaration.help ?? "编辑当前展示内容。",
page,
target: "trust",
previewTargets: [{ key, label: declaration.label }],
previewTargets: [
{ key, label: declaration.label },
...(declaration.previewTargets ?? []).filter(
(target) => !target.page || target.page === page,
),
],
fields: [
{
key: "title",
@@ -94,11 +100,21 @@ function trustSection(
: {}),
...(field === "content" && declaration.required ? { required: true } : {}),
})),
...(declaration.configFields ?? []).map((field) => ({
...field,
previewTarget: `trust:${declaration.type}`,
})),
].map((field) => ({ ...field, previewTarget: `trust:${declaration.type}` })),
...(declaration.configFields ?? [])
.filter((field) => {
const target = declaration.previewTargets?.find(
(target) => target.key === field.previewTarget,
);
return !target?.page || target.page === page;
})
.map((field) => ({
...field,
previewTarget: field.previewTarget ?? `trust:${declaration.type}`,
})),
].map((field) => ({
...field,
previewTarget: (field as TemplateAdminField).previewTarget ?? `trust:${declaration.type}`,
})),
};
}
@@ -185,18 +201,14 @@ export function PresentationEditor({
binding: field.binding ?? `brand.config.templateData.${field.key}`,
}));
return [
...(declaredTemplateFields.length
? [
{
key: "template-data",
title: "模板专属内容",
description: "这些字段由当前小程序模板定义,保存后发布才会对外展示。",
page: templateContent?.templateFields?.[0]?.page ?? "home",
target: "brand" as const,
fields: declaredTemplateFields,
},
]
: []),
...[...new Set(declaredTemplateFields.map((field) => field.page ?? "home"))].map((page) => ({
key: `template-data:${page}`,
title: "模板专属内容",
description: "这些字段由当前小程序模板定义,保存后发布才会对外展示。",
page,
target: "brand" as const,
fields: declaredTemplateFields.filter((field) => (field.page ?? "home") === page),
})),
...(templateContent?.admin.sections ?? []),
].map((section) => ({
...section,
@@ -204,6 +216,8 @@ export function PresentationEditor({
(field) =>
field.binding.startsWith("brand.config.") ||
[
"brand.name",
"brand.tagline",
"brand.avatarUrl",
"brand.description",
"brand.contactPhone",
@@ -226,12 +240,7 @@ export function PresentationEditor({
const selectedPage = pageOptions.some((item) => item.value === activePage)
? activePage
: pageOptions[0]?.value;
const visibleSections = sections.filter(
(section) =>
section.page === selectedPage &&
// 详情页内容来自所选业务记录;不再展示一套额外的品牌级详情编辑器。
!(selectedPage === "detail" && section.target === "brand"),
);
const visibleSections = sections.filter((section) => section.page === selectedPage);
const recordSections = useMemo(
() =>
(templateContent?.trustContentTypes ?? [])
@@ -242,12 +251,17 @@ export function PresentationEditor({
const visibleTargets = useMemo<PreviewTarget[]>(
() =>
[...(templateContent?.admin.sections ?? []), ...recordSections]
.filter((section) => section.page === selectedPage && selectedPage !== "detail")
.filter(
(section) =>
section.page === selectedPage &&
(selectedPage !== "detail" || section.target === "brand"),
)
.flatMap((section) =>
(section.previewTargets ?? []).map((target) => ({
...target,
page: section.page,
source: previewTargetSource(section, target.key),
...(section.key.startsWith("trust:") ? { trustType: section.key.slice(6) } : {}),
})),
)
.concat(
@@ -384,9 +398,22 @@ export function PresentationEditor({
const save = useMutation({
mutationFn: (values: PresentationValues) => {
const nextConfig = applyPresentationValues(config, sections, values);
// 页面内容编辑不提交模板选择,避免触发切换模板的权限校验。
const { visualTemplateKey: _visualTemplateKey, ...contentConfig } = nextConfig;
const standard = applyStandardBrandValues(
brand as unknown as Record<string, unknown>,
sections,
values,
);
const changed = Object.fromEntries(
Object.entries(standard).filter(
([key, value]) =>
key !== "config" && value !== (brand as unknown as Record<string, unknown>)[key],
),
);
return createApiClient().updateAdminBrand({
config: nextConfig,
...applyStandardBrandValues(brand as unknown as Record<string, unknown>, sections, values),
...changed,
config: contentConfig,
});
},
onSuccess: () => {
@@ -436,23 +463,48 @@ export function PresentationEditor({
[brand, previewBrandValues, previewConfig],
);
const handleValuesChange = useCallback(
(_changed: PresentationValues, allValues: PresentationValues) => {
(changed: PresentationValues, allValues: PresentationValues) => {
setBrandDirty(true);
const synchronized: PresentationValues = {
...(form.getFieldsValue(true) as PresentationValues),
...allValues,
};
for (const section of sections) {
for (const field of section.fields) {
const name = presentationFieldName(section.key, field.key);
if (!Object.prototype.hasOwnProperty.call(changed, name)) continue;
for (const peer of sections) {
for (const item of peer.fields) {
if (item.binding === field.binding)
synchronized[presentationFieldName(peer.key, item.key)] = changed[name];
}
}
}
}
form.setFieldsValue(synchronized);
const next = applyBrandPreviewValues(
brand as unknown as Record<string, unknown>,
config,
sections,
allValues,
synchronized,
);
setPreviewConfig((next.config as Record<string, unknown>) ?? {});
setPreviewBrandValues(next);
},
[brand, config, sections],
[brand, config, sections, form],
);
const draftWorkspace = useMemo(() => {
if (!previewWorkspace) return undefined;
const next: RuntimeWorkspace = {
...previewWorkspace,
templateData: {
...previewWorkspace.templateData,
...(previewConfig.templateData &&
typeof previewConfig.templateData === "object" &&
!Array.isArray(previewConfig.templateData)
? (previewConfig.templateData as Record<string, unknown>)
: {}),
},
inquiryForms: previewWorkspace.inquiryForms.map((item) =>
item.key === inquiryRuntime?.key && inquiryDraft ? { ...item, fields: inquiryDraft } : item,
),
@@ -657,9 +709,10 @@ export function PresentationEditor({
? selectedDetailOfferingId
: draftWorkspace?.offerings[0]?.id
: target.source === "trust"
? draftWorkspace?.trustItems.find(
(item) => target.key === `trust:${item.type}`,
)?.id
? previewTrustRecordId(
draftWorkspace?.trustItems ?? [],
target.trustType,
)
: undefined;
handleTargetSelected({
targetKey: target.key,
@@ -689,12 +742,21 @@ export function PresentationEditor({
? "有未保存修改"
: "草稿已同步"}
</Tag>
{selectedPage === "detail" ? (
{selectedPage === "detail" && !selectedTarget ? (
<Alert
type="info"
showIcon
message="详情页由所选业务内容动态生成"
description="选择不同的业务内容即可预览对应详情;内容请在业务提供项中维护。"
description="选择业务内容预览详情,记录内容在业务提供项中维护;公共标题和按钮文案可从左侧区域列表配置,对全部详情生效。"
action={
<Button
onClick={() => {
void navigate("/admin/services");
}}
>
管理业务内容
</Button>
}
/>
) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? (
<InquiryPreviewEditor
@@ -726,9 +788,10 @@ export function PresentationEditor({
? selectedDetailOfferingId
: draftWorkspace?.offerings[0]?.id
: child.source === "trust"
? draftWorkspace?.trustItems.find(
(item) => child.key === `trust:${item.type}`,
)?.id
? previewTrustRecordId(
draftWorkspace?.trustItems ?? [],
child.trustType,
)
: undefined;
handleTargetSelected({
targetKey: child.key,
@@ -807,6 +870,28 @@ export function PresentationEditor({
: {})}
/>
)
) : selectedRecordSource ? (
<Alert
type="info"
showIcon
message="此区域尚未配置内容"
description="创建并启用对应内容后,即可在预览中点选编辑。"
action={
<Button
onClick={() =>
guardDraft(() => {
void navigate(
selectedRecordSource === "trust"
? `/admin/trust?type=${encodeURIComponent(selectedTarget?.trustType ?? "")}`
: "/admin/services",
);
})
}
>
配置此区域内容
</Button>
}
/>
) : !selectedTarget ? (
<div className="presentation-editor__empty">
<Typography.Title level={5}>选择要编辑的区域</Typography.Title>
@@ -820,7 +905,7 @@ export function PresentationEditor({
layout="vertical"
initialValues={initialValues}
onValuesChange={handleValuesChange}
onFinish={(values) => save.mutate(values)}
onFinish={() => save.mutate(form.getFieldsValue(true) as PresentationValues)}
style={{ minHeight: 0, display: "flex", flexDirection: "column" }}
>
<div style={{ flex: 1 }}>
@@ -34,7 +34,7 @@ function safePath(binding: string): string[] | null {
const prefixes = ["brand.config.", "offering.config.", "trust.config."];
const prefix = prefixes.find((candidate) => binding.startsWith(candidate));
const standardField =
/^(brand\.(avatarUrl|description|contactPhone|contactWechat|address|hours|deliveryNote)|offering\.(name|summary|description|coverUrl|priceText)|trust\.(title|summary|content|coverUrl))$/.test(
/^(brand\.(name|tagline|avatarUrl|description|contactPhone|contactWechat|address|hours|deliveryNote)|offering\.(name|summary|description|coverUrl|priceText)|trust\.(title|summary|content|coverUrl))$/.test(
binding,
);
if (!prefix && !standardField) return null;
@@ -100,6 +100,7 @@ export function applyPresentationValues(
const path = safePath(field.binding);
if (!path) continue;
const raw = values[presentationFieldName(section.key, field.key)];
if (raw === undefined) continue;
const value =
field.input === "list" && Array.isArray(raw)
? field.itemValueKey
@@ -1,11 +1,21 @@
export type PreviewSelection = { targetKey: string; recordId?: string };
// 与模板 slot 一致,优先选择承载结构化内容的记录。
export function previewTrustRecordId(
items: { id?: string; type: string; config: Record<string, unknown> }[],
type: string | undefined,
): string | undefined {
const matches = items.filter((item) => item.type === type);
return (matches.find((item) => Object.keys(item.config).length > 0) ?? matches[0])?.id;
}
export type PreviewTarget = {
key: string;
label: string;
source: "brand" | "offering" | "trust" | "inquiry";
page: string;
composite?: boolean;
trustType?: string;
children?: string[];
};
@@ -18,6 +28,6 @@ export function resolvePreviewSelection(
const target = targets.find((item) => item.key === targetKey && item.page === page);
if (!target) return undefined;
if (recordId && target.source !== "offering" && target.source !== "trust") return undefined;
if (!recordId && (target.source === "offering" || target.source === "trust")) return undefined;
// 空区域仍可选中,编辑面板提供创建内容的入口。
return recordId ? { targetKey, recordId } : { targetKey };
}
+37 -2
View File
@@ -7,7 +7,10 @@ import {
presentationFieldName,
readPresentationValue,
} from "../src/features/brand/presentation-bindings.ts";
import { resolvePreviewSelection } from "../src/features/brand/preview-selection.ts";
import {
resolvePreviewSelection,
previewTrustRecordId,
} from "../src/features/brand/preview-selection.ts";
const config = {
founder: "阿成",
@@ -184,6 +187,38 @@ assert.deepEqual(resolvePreviewSelection("offering.card", "one", targets, "offer
targetKey: "offering.card",
recordId: "one",
});
assert.equal(resolvePreviewSelection("offering.card", undefined, targets, "offerings"), undefined);
assert.deepEqual(resolvePreviewSelection("offering.card", undefined, targets, "offerings"), {
targetKey: "offering.card",
});
assert.equal(resolvePreviewSelection("brand.hero", "one", targets, "home"), undefined);
assert.equal(resolvePreviewSelection("brand.hero", undefined, targets, "offerings"), undefined);
// 未挂载的同源编辑入口不能清空已有字段。
assert.deepEqual(
applyPresentationValues(
{ founder: "保留姓名", title: "保留职位" },
[
{
key: "identity",
fields: [
{ key: "founder", binding: "brand.config.founder" },
{ key: "title", binding: "brand.config.title" },
],
},
],
{ "identity:founder": "修改姓名" },
),
{ founder: "修改姓名", title: "保留职位" },
);
assert.equal(
previewTrustRecordId(
[
{ id: "plain", type: "credential", config: {} },
{ id: "structured", type: "credential", config: { stats: [] } },
],
"credential",
),
"structured",
);
assert.equal(previewTrustRecordId([], "credential"), undefined);
+1 -1
View File
@@ -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,
+300 -4
View File
@@ -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 },
+443 -206
View File
@@ -1,4 +1,73 @@
import { test, expect } from "@playwright/test";
import fs from "node:fs";
import { test, expect, type Page } from "@playwright/test";
// 从真实 DOM 点选区域,避免侧栏测试掩盖画布目标无法激活。
async function verifyCanvasTargets(page: Page, manifest: any, pageKey: string) {
const preview = page.locator(".component-template-preview");
const targets = manifest.admin.sections
.filter(
(section: any) =>
section.page === pageKey && (pageKey !== "detail" || section.target === "brand"),
)
.flatMap((section: any) =>
(section.previewTargets ?? [])
.filter((target: any) => !target.composite)
.map((target: any) => target.key),
);
if (pageKey !== "detail") {
targets.push(
...manifest.trustContentTypes.flatMap((item: any) =>
(item.previewTargets ?? [])
.filter((target: any) => target.page === pageKey)
.map((target: any) => target.key),
),
);
targets.push(
...manifest.trustContentTypes
.filter((item: any) => item.pages.includes(pageKey))
.map((item: any) => "trust:" + item.type),
);
}
for (const target of new Set<string>(targets)) {
const elements = preview.locator(`[data-editor-target="${target}"]`);
for (let index = 0; index < (await elements.count()); index++) {
const element = elements.nth(index);
if (!(await element.isVisible())) continue;
const leafIndex = await element.evaluate((node, key) => {
return Array.from(node.querySelectorAll("*")).findIndex((child) => {
const rect = child.getBoundingClientRect();
return (
child.childElementCount === 0 &&
rect.width > 0 &&
rect.height > 0 &&
child.closest("[data-editor-target]")?.getAttribute("data-editor-target") === key
);
});
}, target);
// 点击区内真实叶子内容,避开圆角的透明区域及嵌套子选区。
const content = leafIndex >= 0 ? element.locator("*").nth(leafIndex) : element;
await content.scrollIntoViewIfNeeded();
const point = await content.evaluate((node) => {
const rect = node.getBoundingClientRect();
const x = rect.left + rect.width / 2;
const y = rect.top + rect.height / 2;
return {
x,
y,
target: document
.elementFromPoint(x, y)
?.closest("[data-editor-target]")
?.getAttribute("data-editor-target"),
};
});
expect(point.target, "实际命中区域:" + target).toBe(target);
await page.mouse.click(point.x, point.y);
await expect(
preview.locator(".component-template-preview__outline.is-selected"),
).toHaveAttribute("data-selected-target", target);
}
}
}
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
const brand = {
@@ -94,157 +163,44 @@ const runtimeWorkspace = {
capabilities: [],
theme: { colors: {} },
};
const templateContent = {
displayName: "餐饮模板",
navigation: [
{ key: "home", page: "home", label: "首页" },
{ key: "offerings", page: "offerings", label: "套餐餐品" },
{ key: "service", page: "service", label: "出摊服务" },
{ key: "detail", page: "detail", label: "详情页" },
{ key: "inquiry", page: "inquiry", label: "定制/咨询" },
{ key: "success", page: "success", label: "提交成功页" },
{ key: "records", page: "records", label: "记录页" },
],
assetSlots: [],
trustContentTypes: [
{
type: "schedule",
label: "每周出摊安排",
adminFields: { title: "安排标题", summary: "安排摘要", content: "安排正文" },
hideStandardFields: ["summary", "content"],
pages: ["service"],
configFields: [
{
key: "weekdayLabel",
binding: "trust.config.weekdayLabel",
label: "工作日标题",
input: "text",
},
{
key: "weekdayDetail",
binding: "trust.config.weekdayDetail",
label: "工作日地点",
input: "text",
},
{
key: "weekendLabel",
binding: "trust.config.weekendLabel",
label: "周末标题",
input: "text",
},
{
key: "weekendDetail",
binding: "trust.config.weekendDetail",
label: "周末地点",
input: "text",
},
],
},
],
admin: {
sections: [
{
key: "detailCopy",
title: "餐品说明",
description: "编辑详情页说明",
page: "detail",
target: "brand",
previewTargets: [{ key: "acheng-campus-food.detail.detailCopy", label: "餐品说明" }],
fields: [
{
key: "priceLabel",
binding: "brand.config.visualPresentation.detail.priceLabel",
label: "价格标题",
input: "text",
previewTarget: "acheng-campus-food.detail.detailCopy",
},
],
},
{
key: "offering-card",
title: "餐品卡片",
description: "编辑单条餐品",
page: "offerings",
target: "offering",
previewTargets: [{ key: "acheng-campus-food.offerings.item", label: "餐品卡片" }],
fields: [
{
key: "name",
binding: "offering.name",
label: "餐品名称",
input: "text",
previewTarget: "acheng-campus-food.offerings.item",
},
{
key: "summary",
binding: "offering.summary",
label: "餐品简介",
input: "textarea",
previewTarget: "acheng-campus-food.offerings.item",
},
],
},
{
key: "home",
title: "首页内容",
description: "首页可编辑项",
page: "home",
target: "brand",
previewTargets: [
{
key: "food.home.brand-card",
label: "品牌信息区",
composite: true,
children: ["food.home.identity", "food.home.location", "food.home.actions"],
},
{ key: "food.home.identity", label: "主理人身份" },
{ key: "food.home.location", label: "服务地点" },
{ key: "food.home.offerings-heading", label: "餐品区域标题" },
{ key: "food.home.actions", label: "首页操作按钮" },
],
fields: [
{
key: "identity",
binding: "brand.config.founder",
previewTarget: "food.home.identity",
label: "主理人姓名",
input: "text",
},
{
key: "stallTitle",
binding: "brand.config.visualPresentation.home.stallTitle",
previewTarget: "food.home.location",
label: "出摊信息标题",
input: "text",
},
{
key: "stallTime",
binding: "brand.config.visualPresentation.home.stallTime",
previewTarget: "food.home.location",
label: "营业时间说明",
input: "text",
},
{
key: "worksTitle",
binding: "brand.config.visualPresentation.home.worksTitle",
previewTarget: "food.home.offerings-heading",
label: "招牌餐品标题",
input: "text",
},
{
key: "primaryAction",
binding: "brand.config.visualPresentation.home.primaryAction",
previewTarget: "food.home.actions",
label: "咨询按钮",
input: "text",
},
],
},
],
},
};
const templateContent = JSON.parse(
fs.readFileSync("../../packages/template-acheng-campus-food/template.json", "utf8"),
);
// 根据真实声明生成完整列表数据,让每种内容区域都实际渲染。
const additionalFoodTrust = templateContent.trustContentTypes
.filter((item: { type: string }) => item.type !== "schedule")
.map(
(declaration: {
type: string;
label: string;
configFields?: Array<{ key: string; input: string; itemFields?: Array<{ key: string }> }>;
}) => ({
id: "food-" + declaration.type,
type: declaration.type,
title: declaration.label,
summary: "测试摘要",
content: "测试正文",
isPublished: true,
sortOrder: 0,
config: Object.fromEntries(
(declaration.configFields ?? []).map((field) => [
field.key,
field.input === "list"
? [
Object.fromEntries(
(field.itemFields ?? []).map((child) => [child.key, child.key + "测试值"]),
),
]
: field.key + "测试值",
]),
),
}),
);
runtimeWorkspace.trustItems.push(...additionalFoodTrust);
test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ page }) => {
test.setTimeout(60000);
let rejectOfferingSave = false;
await page.setViewportSize({ width: 1920, height: 1000 });
await page.route("http://localhost:3001/public/workspace**", (route) =>
@@ -266,7 +222,9 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
if (url.pathname === "/admin/brands")
return route.fulfill({ json: [{ id: brand.id, role: "owner", brand }] });
if (url.pathname === "/admin/config/brand" && request.method() === "PATCH") {
Object.assign(brand, request.postDataJSON());
const patch = request.postDataJSON();
if (patch.config) patch.config = { ...brand.config, ...patch.config };
Object.assign(brand, patch);
Object.assign(runtimeWorkspace.brand, brand);
return route.fulfill({ json: brand });
}
@@ -309,7 +267,7 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
return route.fulfill({ json: adminOffering });
}
if (url.pathname === "/admin/config/trust-content")
return route.fulfill({ json: [adminTrust] });
return route.fulfill({ json: [adminTrust, ...additionalFoodTrust] });
if (
url.pathname === `/admin/config/trust-content/${adminTrust.id}` &&
request.method() === "PATCH"
@@ -439,17 +397,17 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
"data-selected-record-id",
adminOffering.id,
);
await page.getByLabel("餐品名称").fill("编辑后的家庭餐");
await page.getByLabel("名称", { exact: true }).fill("编辑后的家庭餐");
await expect(page.getByText("有未保存修改", { exact: true })).toBeVisible();
await page.getByText("出摊服务", { exact: true }).click();
await expect(page.getByRole("dialog", { name: "有尚未保存的修改" })).toBeVisible();
await page.getByRole("button", { name: "继续编辑" }).click();
await expect(page.getByLabel("餐品名称")).toHaveValue("编辑后的家庭餐");
await expect(page.getByLabel("名称", { exact: true })).toHaveValue("编辑后的家庭餐");
await expect(preview.locator(".offering-card")).toContainText("编辑后的家庭餐");
rejectOfferingSave = true;
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect(page.getByText("保存暂时失败,请重试", { exact: true })).toBeVisible();
await expect(page.getByLabel("餐品名称")).toHaveValue("编辑后的家庭餐");
await expect(page.getByLabel("名称", { exact: true })).toHaveValue("编辑后的家庭餐");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect.poll(() => adminOffering.name).toBe("编辑后的家庭餐");
await page.reload();
@@ -492,9 +450,22 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
await expect(preview.locator(".food-detail .bar button")).toBeVisible();
await preview.screenshot({ path: "../../.codex-tasks/preview-proportion/detail.png" });
await expect(page.getByText("详情页由所选业务内容动态生成")).toBeVisible();
await expect(page.getByRole("button", { name: "点选编辑" })).toHaveCount(0);
await expect(page.getByRole("button", { name: "点选编辑" })).toBeVisible();
await expect(page.getByLabel("价格标题")).toHaveCount(0);
await expect(page.getByLabel("餐品介绍")).toHaveCount(0);
await page.getByRole("button", { name: "详情页咨询入口", exact: true }).click();
await preview.locator(".food-detail .bar button").click();
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveAttribute(
"data-selected-target",
"acheng-campus-food.detail.action",
);
await page.getByLabel("咨询按钮文字", { exact: true }).fill("详情公共按钮回归");
await expect(preview.locator(".food-detail .bar button")).toContainText("详情公共按钮回归");
await page.getByRole("button", { name: "保存页面内容" }).click();
await expect(page.getByText("页面内容已保存为草稿,发布后小程序才会更新")).toBeVisible();
await page.reload();
await page.getByText("详情页", { exact: true }).click();
await expect(preview.locator(".food-detail .bar button")).toContainText("详情公共按钮回归");
await page.getByText("定制/咨询", { exact: true }).click();
await expect(preview.locator(".inquiry-form .form-field")).toHaveCount(2);
await expect(preview.locator(".inquiry-form")).toContainText("称呼");
@@ -543,81 +514,178 @@ test("Admin 按通用预览目标筛选字段并同步品牌草稿", async ({ pa
path: "../../.codex-tasks/preview-proportion/menu-" + width + ".png",
});
}
await preview.locator(".component-template-preview__canvas").evaluate((element) => {
(element as HTMLElement).style.width = "";
});
const inspector = page.locator(".presentation-editor__inspector");
for (const pageKey of [
"home",
"offerings",
"profile",
"service",
"detail",
"inquiry",
"success",
"records",
]) {
const label =
templateContent.navigation.find((item: { page: string }) => item.page === pageKey)?.label ??
(
{ detail: "详情页", inquiry: "咨询页", success: "提交成功页", records: "记录页" } as Record<
string,
string
>
)[pageKey];
await page.getByText(label, { exact: true }).click();
await verifyCanvasTargets(page, templateContent, pageKey);
for (const section of templateContent.admin.sections.filter(
(item: { page: string }) => item.page === pageKey,
)) {
if (pageKey === "detail" && section.target !== "brand") continue;
for (const target of section.previewTargets ?? []) {
if (target.composite) continue;
await page
.locator(".presentation-editor__regions")
.getByRole("button", { name: target.label, exact: true })
.click();
const fields = section.fields.filter(
(field: { previewTarget: string }) => field.previewTarget === target.key,
);
for (const field of fields)
await expect(
inspector.locator(".ant-form-item-label").getByTitle(field.label, { exact: true }),
).toBeVisible();
}
}
if (pageKey !== "detail") {
for (const declaration of templateContent.trustContentTypes.filter(
(item: { pages: string[] }) => item.pages.includes(pageKey),
)) {
await page
.locator(".presentation-editor__regions")
.getByRole("button", { name: declaration.label, exact: true })
.click();
await expect(
inspector.getByLabel(declaration.adminFields.title, { exact: true }),
).toBeVisible();
for (const field of declaration.configFields ?? []) {
await expect(
inspector.locator(".ant-form-item-label").getByTitle(field.label, { exact: true }),
).toBeVisible();
}
}
}
for (const width of [320, 390]) {
await preview.locator(".component-template-preview__canvas").evaluate((element, size) => {
(element as HTMLElement).style.width = size + "px";
}, width);
await expect
.poll(() =>
preview
.locator(".component-template-preview__canvas")
.evaluate((element) => element.scrollWidth - element.clientWidth),
)
.toBeLessThanOrEqual(1);
await preview.screenshot({
path:
"../../.codex-tasks/template-audit-execution/raw/food-" + pageKey + "-" + width + ".png",
});
}
await preview.locator(".component-template-preview__canvas").evaluate((element) => {
(element as HTMLElement).style.width = "";
});
await preview.screenshot({
path: "../../.codex-tasks/template-audit-execution/raw/food-" + pageKey + ".png",
});
}
});
test("林境模板支持首页和主理人区域点选", async ({ page }) => {
test.setTimeout(60000);
await page.setViewportSize({ width: 1600, height: 900 });
const editorialBrand = {
...structuredClone(brand),
templateKey: "personal",
avatarUrl: "/assets/acheng-campus-food/owner/portrait.jpg",
config: {
visualTemplateKey: "linjing-editorial",
founder: "林境主理人",
title: "建筑设计师",
heroImage: "/assets/tab/home.png",
heroImage: "/assets/acheng-campus-food/owner/portrait.jpg",
homeHero: { title: "林境作品" },
visualPresentation: {
home: {
proofEyebrow: "专业积累",
proofTitle: "信任介绍",
manifestoEyebrow: "工作方法",
manifestoTitle: "专业方法",
worksEyebrow: "代表项目",
worksTitle: "作品与服务",
worksAction: "查看作品",
flowEyebrow: "合作方式",
flowTitle: "合作流程",
},
},
},
};
const editorialPillars = [
{ title: "比例与空间", desc: "根据建筑比例设计" },
{ title: "材料与工艺", desc: "可验证的材料标准" },
];
const editorialFlow = [
{ step: "01", name: "需求沟通", desc: "了解现场条件" },
{ step: "02", name: "方案确认", desc: "明确交付范围" },
{ step: "03", name: "制作安装", desc: "按方案实施" },
{ step: "04", name: "验收跟进", desc: "长期维护" },
];
const editorialWorkspace = {
...structuredClone(runtimeWorkspace),
brand: {
...structuredClone(runtimeWorkspace.brand),
...editorialBrand,
...editorialBrand.config,
founder: "林境主理人",
title: "建筑设计师",
heroImage: "/assets/tab/home.png",
heroImage: "/assets/acheng-campus-food/owner/portrait.jpg",
homeHero: { title: "林境作品" },
},
offerings: [],
trustItems: [],
};
const editorialContent = {
displayName: "林境模板",
navigation: [
{ key: "home", page: "home", label: "首页" },
{ key: "profile", page: "profile", label: "主理人与我" },
offerings: structuredClone(runtimeWorkspace.offerings).map((item) => ({
...item,
coverUrl: "/assets/acheng-campus-food/owner/portrait.jpg",
})),
trustItems: [
{
id: "credential-fixture",
type: "credential",
title: "专业资历",
summary: "建筑与门系统经验",
content: "持续服务私宅项目",
config: {
pillars: editorialPillars,
serviceFlow: editorialFlow,
stats: [
{ value: "10 年", label: "从业经验", sub: "持续服务私宅" },
{ value: "200+", label: "项目落地", sub: "覆盖多个城市" },
{ value: "30+", label: "合作品牌", sub: "长期协作" },
{ value: "98%", label: "客户好评", sub: "来自真实反馈" },
],
},
},
],
assetSlots: [],
trustContentTypes: [],
admin: {
sections: [
{
key: "home",
title: "首页主视觉",
page: "home",
target: "brand",
previewTargets: [{ key: "editorial.home.hero", label: "首页主视觉" }],
fields: [
{
key: "heroTitle",
binding: "brand.config.homeHero.title",
label: "首页标题",
input: "text",
previewTarget: "editorial.home.hero",
},
],
},
{
key: "identity",
title: "主理人与联系方式",
page: "profile",
target: "brand",
previewTargets: [
{ key: "linjing-editorial.profile.identity", label: "主理人与联系方式" },
],
fields: [
{
key: "founder",
binding: "brand.config.founder",
label: "主理人姓名",
input: "text",
previewTarget: "linjing-editorial.profile.identity",
},
],
},
trustPresentation: {
pillars: editorialPillars,
serviceFlow: editorialFlow,
stats: [
{ value: "10 年", label: "从业经验", sub: "持续服务私宅" },
{ value: "200+", label: "项目落地", sub: "覆盖多个城市" },
{ value: "30+", label: "合作品牌", sub: "长期协作" },
{ value: "98%", label: "客户好评", sub: "来自真实反馈" },
],
},
};
const editorialContent = JSON.parse(
fs.readFileSync("../../packages/template-linjing-editorial/template.json", "utf8"),
);
await page.route("**/api/**", (route) => {
const url = new URL(route.request().url());
const path = url.pathname.replace(/^\/api/, "");
@@ -629,7 +697,34 @@ test("林境模板支持首页和主理人区域点选", async ({ page }) => {
return route.fulfill({
json: [{ id: editorialBrand.id, role: "owner", brand: editorialBrand }],
});
if (path === "/admin/config/brand") return route.fulfill({ json: editorialBrand });
if (path === "/admin/config/brand") {
if (route.request().method() === "PATCH") {
const patch = route.request().postDataJSON();
if (patch.config) patch.config = { ...editorialBrand.config, ...patch.config };
Object.assign(editorialBrand, patch);
Object.assign(editorialWorkspace.brand, editorialBrand, editorialBrand.config);
}
return route.fulfill({ json: editorialBrand });
}
if (
path === "/admin/config/trust-content/credential-fixture" &&
route.request().method() === "PATCH"
) {
Object.assign(editorialWorkspace.trustItems[0], route.request().postDataJSON());
Object.assign(editorialWorkspace.trustPresentation, editorialWorkspace.trustItems[0].config);
return route.fulfill({ json: editorialWorkspace.trustItems[0] });
}
if (path === "/admin/workspace/offerings") return route.fulfill({ json: [adminOffering] });
if (
path === "/admin/workspace/offerings/" + adminOffering.id &&
route.request().method() === "PATCH"
) {
Object.assign(adminOffering, route.request().postDataJSON());
Object.assign(editorialWorkspace.offerings[0].presentation, adminOffering.config);
return route.fulfill({ json: adminOffering });
}
if (path === "/admin/config/trust-content")
return route.fulfill({ json: editorialWorkspace.trustItems });
if (path === "/public/templates/personal")
return route.fulfill({
json: { name: "个人品牌", description: "林境模板", serviceCategories: [] },
@@ -661,12 +756,154 @@ test("林境模板支持首页和主理人区域点选", async ({ page }) => {
preview.locator(".hero-image").evaluate((image: HTMLImageElement) => image.naturalWidth),
)
.toBeGreaterThan(0);
const stats = preview.locator('[data-editor-target="editorial.home.proof.stats"]');
await expect(stats.locator(":scope > *")).toHaveCount(4);
expect(
await stats.evaluate(
(element) => getComputedStyle(element).gridTemplateColumns.split(" ").length,
),
).toBe(2);
await preview.screenshot({
path: "../../.codex-tasks/template-audit-execution/raw/linjing-stats.png",
});
await stats.click();
const inspector = page.locator(".presentation-editor__inspector");
await expect(inspector.getByRole("heading", { name: "信任数据" })).toBeVisible();
await expect(page.getByLabel("1. 数字或成果")).toHaveValue("10 年");
await expect(page.getByLabel("2. 说明")).toHaveValue("项目落地");
await page.getByLabel("1. 数字或成果").fill("25 年");
await expect(stats.locator(".stat-value").first()).toContainText("25 年");
await inspector.getByRole("button", { name: "保存此项内容" }).click();
await expect.poll(() => editorialWorkspace.trustItems[0].config.stats[0].value).toBe("25 年");
await preview.locator(".founder-name").click();
await expect(inspector.getByRole("heading", { name: "主理人介绍", exact: true })).toBeVisible();
for (const label of ["主理人姓名", "身份或职位", "主理人简介", "主理人标签"])
await expect(inspector.getByLabel(label, { exact: true })).toBeVisible();
await inspector.getByLabel("主理人简介").fill("跨页面共享的简介回归");
await expect(preview.locator(".founder-copy .quote")).toContainText("跨页面共享的简介回归");
await inspector.getByRole("button", { name: "保存页面内容" }).click();
await expect.poll(() => editorialBrand.description).toBe("跨页面共享的简介回归");
await page.reload();
await expect(preview.locator(".founder-copy .quote")).toContainText("跨页面共享的简介回归");
await expect(stats.locator(".stat-value").first()).toContainText("25 年");
await page.getByRole("button", { name: "信任数据", exact: true }).click();
await expect(page.getByLabel("1. 数字或成果")).toHaveValue("25 年");
await preview.locator('[data-editor-target="editorial.home.hero"]').click();
await expect(page.getByLabel("首页标题")).toBeVisible();
await expect(page.getByLabel("首页主标题")).toBeVisible();
await page.getByLabel("设计理念", { exact: true }).fill("模板专属理念回归");
await expect(preview.locator(".hero-slogan")).toContainText("模板专属理念回归");
await page.getByRole("button", { name: "保存页面内容" }).click();
await expect(page.getByText("页面内容已保存为草稿,发布后小程序才会更新")).toBeVisible();
await page.reload();
await expect(preview.locator(".hero-slogan")).toContainText("模板专属理念回归");
await page.getByRole("button", { name: "信任数据", exact: true }).click();
await page.getByRole("button", { name: "下移第 1 项", exact: true }).click();
await expect(stats.locator(".stat-value").first()).toContainText("200+");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect.poll(() => editorialWorkspace.trustItems[0].config.stats[0].value).toBe("200+");
await page.reload();
await expect(stats.locator(".stat-value").first()).toContainText("200+");
await preview.locator(".pillar-title").first().click();
await expect(page.getByLabel("1. 方法说明")).toBeVisible();
await page.getByLabel("1. 方法名称").fill("方法名称回归");
await expect(preview.locator(".pillar-title").first()).toContainText("方法名称回归");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect(page.getByText("内容已保存为草稿,发布后访客才会看到更新")).toBeVisible();
await page.reload();
await expect(preview.locator(".pillar-title").first()).toContainText("方法名称回归");
await preview.locator(".flow-name").first().click();
await expect(page.getByLabel("1. 步骤编号")).toBeVisible();
await expect(page.getByLabel("1. 步骤名称")).toBeVisible();
await page.getByLabel("1. 步骤说明").fill("步骤说明回归");
await expect(preview.locator(".flow-desc").first()).toContainText("步骤说明回归");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect(page.getByText("内容已保存为草稿,发布后访客才会看到更新")).toBeVisible();
await page.reload();
await expect(preview.locator(".flow-desc").first()).toContainText("步骤说明回归");
await preview.locator(".work-card").click();
for (const label of ["案例类别", "项目地点", "产品系列", "项目关键词"])
await expect(inspector.getByText(label, { exact: true })).toBeVisible();
await page.getByLabel("项目地点", { exact: true }).fill("项目地点回归");
await expect(preview.locator(".work-category")).toContainText("项目地点回归");
await page.getByRole("button", { name: "保存此项内容" }).click();
await expect(page.getByText("内容已保存为草稿,发布后访客才会看到更新")).toBeVisible();
await page.reload();
await expect(preview.locator(".work-category")).toContainText("项目地点回归");
await page.getByText("主理人与我", { exact: true }).click();
await expect(preview.locator(".component-template-preview__outline.is-selected")).toHaveCount(0);
await preview.locator('[data-editor-target="linjing-editorial.profile.identity"]').click();
await expect(page.getByRole("button", { name: "信任数据", exact: true })).toHaveCount(0);
await expect(page.getByLabel("主理人姓名")).toBeVisible();
await page.getByLabel("主理人姓名").fill("修改后的主理人");
await expect(preview.locator(".editorial-profile .founder")).toContainText("修改后的主理人");
await page.getByRole("button", { name: "保存页面内容" }).click();
await expect(page.getByText("页面内容已保存为草稿,发布后小程序才会更新")).toBeVisible();
await page.getByRole("button", { name: "服务范围与适用对象", exact: true }).click();
await expect(page.getByText("此区域尚未配置内容")).toBeVisible();
await expect(page.getByRole("button", { name: "配置此区域内容" })).toBeVisible();
for (const pageKey of [
"home",
"offerings",
"profile",
"detail",
"inquiry",
"success",
"records",
]) {
const label =
editorialContent.navigation.find((item: { page: string }) => item.page === pageKey)?.label ??
(
{ detail: "详情页", inquiry: "咨询页", success: "提交成功页", records: "记录页" } as Record<
string,
string
>
)[pageKey];
await page.getByText(label, { exact: true }).click();
await verifyCanvasTargets(page, editorialContent, pageKey);
for (const section of editorialContent.admin.sections.filter(
(item: { page: string }) => item.page === pageKey,
)) {
if (pageKey === "detail" && section.target !== "brand") continue;
for (const target of section.previewTargets ?? []) {
if (target.composite) continue;
await page
.locator(".presentation-editor__regions")
.getByRole("button", { name: target.label, exact: true })
.click();
const fields = section.fields.filter(
(field: { previewTarget: string }) => field.previewTarget === target.key,
);
for (const field of fields)
await expect(
inspector.locator(".ant-form-item-label").getByTitle(field.label, { exact: true }),
).toBeVisible();
}
}
for (const width of [320, 390]) {
await preview.locator(".component-template-preview__canvas").evaluate((element, size) => {
(element as HTMLElement).style.width = size + "px";
}, width);
await expect
.poll(() =>
preview
.locator(".component-template-preview__canvas")
.evaluate((element) => element.scrollWidth - element.clientWidth),
)
.toBeLessThanOrEqual(1);
await preview.screenshot({
path:
"../../.codex-tasks/template-audit-execution/raw/linjing-" +
pageKey +
"-" +
width +
".png",
});
}
await preview.locator(".component-template-preview__canvas").evaluate((element) => {
(element as HTMLElement).style.width = "";
});
await preview.screenshot({
path: "../../.codex-tasks/template-audit-execution/raw/linjing-" + pageKey + ".png",
});
}
});