refactor: 统一模板契约并修复预览版本

This commit is contained in:
que01 committed 2026-10-18 17:09:09 +08:00
1 parent cd2992c00a
commit 50b87e48de
56 files changed
+7849 -5756

No files matched your search

+238 -243
View File
@@ -66,11 +66,22 @@ function createTemplateArchive(template = "acheng-campus-food", mutateManifest)
mutateManifest(manifest);
const content = Buffer.from(JSON.stringify(manifest));
writeFileSync(manifestPath, content);
const packageJsonPath = path.join(directory, "package.json");
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
packageJson.version = manifest.version;
const packageContent = Buffer.from(JSON.stringify(packageJson));
writeFileSync(packageJsonPath, packageContent);
const checksumPath = path.join(directory, "checksums.json");
const checksums = JSON.parse(readFileSync(checksumPath, "utf8"));
checksums.version = manifest.version;
const entry = checksums.files.find((item) => item.path === "template.json");
entry.bytes = content.length;
entry.sha256 = createHash("sha256").update(content).digest("hex");
const packageEntry = checksums.files.find((item) => item.path === "package.json");
if (packageEntry) {
packageEntry.bytes = packageContent.length;
packageEntry.sha256 = createHash("sha256").update(packageContent).digest("hex");
}
const canonicalEntries = checksums.files.map((item) => ({
bytes: item.bytes,
path: item.path,
@@ -122,16 +133,30 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
const empty = await request("/admin/templates", { headers });
assert.equal(empty.statusCode, 200);
assert.deepEqual(JSON.parse(empty.body).items, []);
assert.equal(JSON.parse(empty.body).total, 0);
const baseline = JSON.parse(empty.body);
assert.deepEqual(baseline.items.map((item) => item.packageKey).sort(), [
"acheng-campus-food",
"linjing-editorial",
]);
const linjingVersion = baseline.items.find((item) => item.packageKey === "linjing-editorial");
assert.ok(linjingVersion);
assert.equal(linjingVersion.version, "1.0.5");
const linjingPreview = await request(
`/admin/templates/${linjingVersion.id}/preview?industry=doors`,
{ headers },
);
assert.equal(linjingPreview.statusCode, 200, linjingPreview.body);
assert.equal(JSON.parse(linjingPreview.body).compatibility.renderer.key, "linjing-editorial");
const archive = createTemplateArchive();
const archive = createTemplateArchive("atelier-solopreneur", (manifest) => {
manifest.version = "99.0.0";
});
const imported = await request("/admin/templates/import", {
method: "POST",
headers: { ...headers, ...multipartArchive(archive).headers },
rawPayload: multipartArchive(archive).payload,
});
assert.equal(imported.statusCode, 201);
assert.equal(imported.statusCode, 201, imported.body);
assert.equal(JSON.parse(imported.body).imported, true);
const repeated = await request("/admin/templates/import", {
method: "POST",
@@ -142,9 +167,13 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
assert.equal(JSON.parse(repeated.body).idempotent, true);
const listed = await request("/admin/templates", { headers });
const listedBody = JSON.parse(listed.body);
assert.equal(listedBody.items.length, 1);
assert.equal(listedBody.items[0].status, "imported");
const versionId = listedBody.items[0].id;
assert.equal(listedBody.items.length, baseline.items.length + 1);
const newVersion = listedBody.items.find(
(item) => item.packageKey === "atelier-solopreneur" && item.version === "99.0.0",
);
assert.ok(newVersion);
assert.equal(newVersion.status, "imported");
const versionId = newVersion.id;
const importedVersion = await prisma.templatePackageVersion.findUniqueOrThrow({
where: { id: versionId },
});
@@ -349,7 +378,7 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
assert.match(body.workspace.brand.id, /^template-preview:/);
assert.equal(body.workspace.offerings.length > 0, true);
assert.equal(body.workspace.inquiryForms.length, 1);
assert.equal(body.workspace.brand.config.visualTemplateKey, "atelier-solopreneur");
assert.equal(Object.hasOwn(body.workspace.brand.config ?? {}, "visualTemplateKey"), false);
assert.equal(body.template.pages.includes("profile"), true);
assert.equal(body.template.pages.includes("inquiry"), true);
assert.equal(body.preview.fixtureSource, "previewFixture");
@@ -483,10 +512,10 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
},
},
},
/所属行业/,
/所属行业|must match its key/,
],
[{ ...stored.manifestSnapshot, requiredCapabilities: ["unknown"] }, /未注册的 capability/],
[{ ...stored.manifestSnapshot, visualTemplateKey: "unknown" }, /renderer/],
[{ ...stored.manifestSnapshot, visualTemplateKey: "unknown" }, /元数据/],
[{ ...stored.manifestSnapshot, runtimeContract: "9.0" }, /契约/],
[{ ...stored.manifestSnapshot, dataSlots: [null] }, /契约/],
[{ ...stored.manifestSnapshot, navigation: [null] }, /契约/],
@@ -508,7 +537,7 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
where: { id: versionId },
data: { archiveChecksum: stored.archiveChecksum },
});
// 独立演示内容不依赖 bootstrap;旧包则显式标明兼容来源。
// 独立演示内容不依赖 bootstrap sampleContent。
await prisma.templatePackageVersion.update({
where: { id: versionId },
data: { manifestSnapshot: { ...stored.manifestSnapshot, sampleContent: {} } },
@@ -527,9 +556,8 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
const legacy = await request(`/admin/templates/${versionId}/preview?industry=personal`, {
headers,
});
assert.equal(legacy.statusCode, 200, legacy.body);
assert.equal(JSON.parse(legacy.body).preview.fixtureSource, "legacy-sampleContent");
assert.equal(JSON.parse(legacy.body).preview.diagnostics[0].code, "LEGACY_PREVIEW_SAMPLE");
assert.equal(legacy.statusCode, 400, legacy.body);
assert.match(JSON.parse(legacy.body).error.message, /previewFixture/);
for (const [manifestSnapshot, reason] of failures) {
await prisma.templatePackageVersion.update({
where: { id: versionId },
@@ -1848,7 +1876,7 @@ test("health and public content are available without authentication", async ()
assert.equal(missingSlug.statusCode, 404);
});
test("visual template compatibility is enforced by catalog, preview, and brand switching", async () => {
test("visual template compatibility is enforced by catalog, preview, and version selection", async () => {
const catalog = await request("/public/templates");
assert.equal(catalog.statusCode, 200);
const visuals = JSON.parse(catalog.body).visuals;
@@ -1875,12 +1903,20 @@ test("visual template compatibility is enforced by catalog, preview, and brand s
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const compatibleSwitch = await request("/admin/config/brand", {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { config: { visualTemplateKey: "acheng-campus-food" } },
const installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId },
});
assert.equal(compatibleSwitch.statusCode, 200);
const compatibleSwitch = await request("/admin/workspace/template/select-version", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: {
templatePackageVersionId: installation.templatePackageVersionId,
expectedCurrentPackageVersionId: installation.templatePackageVersionId,
confirm: true,
},
});
assert.equal(compatibleSwitch.statusCode, 201);
assert.equal(JSON.parse(compatibleSwitch.body).unchanged, true);
});
test("industry template state has a single source of truth", async () => {
@@ -1890,11 +1926,16 @@ test("industry template state has a single source of truth", async () => {
});
assert.ok(brand);
const templateKey = brand.templateKey;
const visualTemplateKey = brand.config?.visualTemplateKey;
const installationBefore = await prisma.brandTemplateInstallation.findFirst({
assert.equal(Object.hasOwn(brand.config ?? {}, "visualTemplateKey"), false);
const installation = await prisma.brandTemplateInstallation.findUnique({
where: { brandId },
});
const fieldsBefore = await prisma.brandFieldDefinition.findMany({ where: { brandId } });
assert.ok(installation?.templatePackageVersionId);
const packageVersion = await prisma.templatePackageVersion.findUniqueOrThrow({
where: { id: installation.templatePackageVersionId },
});
assert.equal(packageVersion.version, installation.templateVersion);
assert.equal(packageVersion.packageKey, installation.configSnapshot.packageKey);
const unauthorized = await request("/admin/workspace/template/preview");
assert.equal(unauthorized.statusCode, 401);
@@ -1912,22 +1953,24 @@ test("industry template state has a single source of truth", async () => {
};
try {
// 品牌身份来自 BrandProfile.templateKey;即使版本台账缺失,预览也必须可用而不是 400。
const preview = await request("/admin/workspace/template/preview", { headers });
assert.equal(preview.statusCode, 200);
const previewBody = JSON.parse(preview.body);
assert.equal(previewBody.templateKey, templateKey);
assert.equal(previewBody.currentVersion, previewBody.latestVersion);
assert.equal(previewBody.canUpgrade, false);
assert.equal(previewBody.canRollback, Boolean(installationBefore?.previousSnapshots?.length));
assert.equal(previewBody.canRollback, Boolean(installation.previousSnapshots?.length));
const otherKey = templateKey === "personal" ? "food" : "personal";
// 安装其他行业模板必须被拒绝,且不能改写品牌身份或视觉模板。
// 安装其他行业模板必须被拒绝,且不能改写品牌身份或版本引用。
const rejected = await request("/admin/workspace/install", {
method: "POST",
headers,
payload: { templateKey: otherKey },
payload: {
templateKey: otherKey,
templatePackageVersionId: installation.templatePackageVersionId,
},
});
assert.equal(rejected.statusCode, 400);
assert.match(errorMessage(rejected.body), /更换行业模板不在本版本范围内/);
@@ -1936,58 +1979,17 @@ test("industry template state has a single source of truth", async () => {
select: { templateKey: true, config: true },
});
assert.equal(afterRejected.templateKey, templateKey);
assert.equal(afterRejected.config?.visualTemplateKey, visualTemplateKey);
assert.equal(Object.hasOwn(afterRejected.config ?? {}, "visualTemplateKey"), false);
// 台账已存在时重复安装当前模板应被拒绝。
if (installationBefore) {
const repeated = await request("/admin/workspace/install", {
method: "POST",
headers,
payload: { templateKey },
});
assert.equal(repeated.statusCode, 400);
assert.match(errorMessage(repeated.body), /已经安装/);
// 缺失的版本台账可以由安装补齐,且不改动品牌身份与视觉模板。
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
const repaired = await request("/admin/workspace/install", {
method: "POST",
headers,
payload: { templateKey },
});
assert.equal(repaired.statusCode, 201, repaired.body);
const installationAfter = await prisma.brandTemplateInstallation.findFirst({
where: { brandId },
});
assert.equal(installationAfter.templateKey, templateKey);
const afterRepair = await prisma.brandProfile.findUnique({
where: { id: brandId },
select: { templateKey: true, config: true },
});
assert.equal(afterRepair.templateKey, templateKey);
assert.equal(afterRepair.config?.visualTemplateKey, visualTemplateKey);
}
} finally {
const createdFieldIds = (await prisma.brandFieldDefinition.findMany({ where: { brandId } }))
.filter((item) => !fieldsBefore.some((current) => current.id === item.id))
.map((item) => item.id);
if (createdFieldIds.length)
await prisma.brandFieldDefinition.deleteMany({ where: { id: { in: createdFieldIds } } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
if (installationBefore) {
await prisma.brandTemplateInstallation.create({
data: {
brandId,
templateKey: installationBefore.templateKey,
templateVersion: installationBefore.templateVersion,
configSnapshot: installationBefore.configSnapshot,
},
});
}
await prisma.brandProfile.update({
where: { id: brandId },
data: { templateKey, config: brand.config },
const repeated = await request("/admin/workspace/install", {
method: "POST",
headers,
payload: { templateKey, templatePackageVersionId: installation.templatePackageVersionId },
});
assert.equal(repeated.statusCode, 400);
assert.match(errorMessage(repeated.body), /已经安装/);
} finally {
await prisma.brandTemplateInstallation.findUniqueOrThrow({ where: { brandId } });
}
});
@@ -2158,16 +2160,12 @@ test("editor membership can manage brand content but cannot change system settin
headers: { authorization: `Bearer ${token}` },
});
assert.equal(capabilities.statusCode, 403);
const visualHistory = await request("/admin/config/visual-template/history", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(visualHistory.statusCode, 403);
const visualUpdate = await request("/admin/config/brand", {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { config: { visualTemplateKey: "unknown-visual" } },
});
assert.equal(visualUpdate.statusCode, 403);
assert.equal(visualUpdate.statusCode, 400);
} finally {
await prisma.brandMembership.update({
where: { id: membership.id },
@@ -2352,10 +2350,9 @@ test("admin capability list includes template defaults and brand overrides", asy
test("installing another industry template is rejected without drifting brand identity", async () => {
const originalBrand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
await prisma.inquirySubmission.deleteMany({ where: { brandId } });
await prisma.inquiryForm.deleteMany({ where: { brandId } });
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
const installationBefore = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId },
});
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
@@ -2367,16 +2364,22 @@ test("installing another industry template is rejected without drifting brand id
const installed = await request("/admin/workspace/install", {
method: "POST",
headers,
payload: { templateKey: "doors" },
payload: {
templateKey: "doors",
templatePackageVersionId: installationBefore.templatePackageVersionId,
},
});
assert.equal(installed.statusCode, 400, installed.body);
assert.match(errorMessage(installed.body), /更换行业模板不在本版本范围内/);
// 拒绝之后不能留下任何漂移:品牌身份、视觉模板、台账都不变。
// 拒绝之后品牌身份和 package version 引用保持不变。
const brandAfter = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
assert.equal(brandAfter.templateKey, originalBrand.templateKey);
assert.deepEqual(brandAfter.config, originalBrand.config);
assert.equal(await prisma.brandTemplateInstallation.count({ where: { brandId } }), 0);
assert.equal(Object.hasOwn(brandAfter.config ?? {}, "visualTemplateKey"), false);
assert.deepEqual(
await prisma.brandTemplateInstallation.findUniqueOrThrow({ where: { brandId } }),
installationBefore,
);
// 公开运行时仍按品牌身份走 food 模板,没有被 doors 污染。
const workspace = await request("/public/workspace");
@@ -2389,28 +2392,17 @@ test("installing another industry template is rejected without drifting brand id
assert.equal(samplePreview.statusCode, 200);
assert.equal(JSON.parse(samplePreview.body).templateKey, originalBrand.templateKey);
} finally {
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
await prisma.brandProfile.update({
where: { id: brandId },
data: { templateKey: originalBrand.templateKey, config: originalBrand.config },
});
assert.equal(
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).templateKey,
originalBrand.templateKey,
);
}
});
test("cross template requests are rejected even when a drifted ledger already exists", async () => {
test("cross template requests are rejected without creating a drifted installation", async () => {
const originalBrand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
await prisma.inquirySubmission.deleteMany({ where: { brandId } });
await prisma.inquiryForm.deleteMany({ where: { brandId } });
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.create({
data: {
brandId,
templateKey: "doors",
templateVersion: "1.0.0",
configSnapshot: { schemaVersion: "1.0" },
},
const installationBefore = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId },
});
const login = await request("/admin/session/login", {
method: "POST",
@@ -2423,36 +2415,44 @@ test("cross template requests are rejected even when a drifted ledger already ex
const rejected = await request("/admin/workspace/install", {
method: "POST",
headers,
payload: { templateKey: "doors" },
payload: {
templateKey: "doors",
templatePackageVersionId: installationBefore.templatePackageVersionId,
},
});
assert.equal(rejected.statusCode, 400, rejected.body);
assert.match(errorMessage(rejected.body), /更换行业模板不在本版本范围内/);
const brandAfter = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
assert.equal(brandAfter.templateKey, originalBrand.templateKey);
assert.equal(await prisma.brandTemplateInstallation.count({ where: { brandId } }), 1);
assert.deepEqual(
await prisma.brandTemplateInstallation.findUniqueOrThrow({ where: { brandId } }),
installationBefore,
);
const workspace = await request("/public/workspace");
assert.equal(workspace.statusCode, 200);
assert.equal(JSON.parse(workspace.body).template.key, originalBrand.templateKey);
} finally {
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
await prisma.brandProfile.update({
where: { id: brandId },
data: { templateKey: originalBrand.templateKey, config: originalBrand.config },
});
assert.equal(
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).templateKey,
originalBrand.templateKey,
);
}
});
test("admin can preview and import sample content idempotently", async () => {
const originalBrand = await prisma.brandProfile.findUnique({ where: { id: brandId } });
const originalInstallation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId },
});
const originalForms = await prisma.inquiryForm.findMany({ where: { brandId } });
const originalSampleTrust = await prisma.trustContent.findMany({
where: { brandId, content: "示例内容,待品牌主理人完善。" },
});
await prisma.brandProfile.update({ where: { id: brandId }, data: { templateKey: "doors" } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
assert.equal(originalBrand?.templateKey, "food");
const packageVersionId = originalInstallation.templatePackageVersionId;
assert.ok(packageVersionId);
await prisma.offering.deleteMany({
where: {
brandId,
@@ -2463,53 +2463,23 @@ 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 }],
},
});
}
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 },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const headers = { authorization: `Bearer ${token}` };
const archive = createTemplateArchive("acheng-campus-food");
const uploaded = multipartArchive(archive);
const importedPackage = await request("/admin/templates/import", {
method: "POST",
headers: { ...headers, ...uploaded.headers },
rawPayload: uploaded.payload,
});
assert.equal(importedPackage.statusCode, 201, importedPackage.body);
const packageVersionId = JSON.parse(importedPackage.body).version.id;
const publishedPackage = await request(`/admin/templates/${packageVersionId}/publish`, {
method: "POST",
headers,
});
assert.equal(publishedPackage.statusCode, 201, publishedPackage.body);
await prisma.brandProfile.update({
where: { id: brandId },
data: { templateKey: "food", config: { visualTemplateKey: "acheng-campus-food" } },
});
await prisma.brandTemplateInstallation.create({
data: {
brandId,
templateKey: "food",
visualTemplateKey: "acheng-campus-food",
templatePackageVersionId: packageVersionId,
contentChecksum: JSON.parse(importedPackage.body).version.contentChecksum,
templateVersion: JSON.parse(importedPackage.body).version.version,
configSnapshot: { schemaVersion: "1.0" },
},
});
const preview = await request("/admin/workspace/sample-content/preview", {
headers,
});
const preview = await request(
`/admin/workspace/sample-content/preview?templatePackageVersionId=${packageVersionId}`,
{ headers },
);
assert.equal(preview.statusCode, 200);
assert.equal(JSON.parse(preview.body).source.templatePackageVersionId, packageVersionId);
assert.equal(JSON.parse(preview.body).source.kind, "package_version");
@@ -2566,6 +2536,7 @@ 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: "门系统咨询表单" } });
await prisma.inquiryForm.deleteMany({ where: { brandId, name: "现有客户表单" } });
if (originalForms.length) {
await prisma.inquiryForm.createMany({
data: originalForms.map(
@@ -2575,12 +2546,10 @@ test("admin can preview and import sample content idempotently", async () => {
}
await prisma.capabilityAuditLog.deleteMany({ where: { brandId, capabilityKey: "doors" } });
await prisma.templateBootstrapImport.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
await prisma.templatePackageAuditLog.deleteMany({
where: { templatePackageVersionId: packageVersionId },
});
await prisma.templatePackageVersion.delete({ where: { id: packageVersionId } });
await prisma.templatePackage.deleteMany({ where: { packageKey: "acheng-campus-food" } });
assert.deepEqual(
await prisma.brandTemplateInstallation.findUniqueOrThrow({ where: { brandId } }),
originalInstallation,
);
await prisma.brandProfile.update({
where: { id: brandId },
data: { templateKey: originalBrand?.templateKey ?? "food", config: originalBrand?.config },
@@ -2588,6 +2557,9 @@ test("admin can preview and import sample content idempotently", async () => {
});
test("template ledger install, upgrade preview, and rollback stay brand-scoped", async () => {
const originalInstallation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId },
});
await prisma.inquirySubmission.deleteMany({ where: { brandId } });
await prisma.inquiryForm.deleteMany({ where: { brandId } });
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
@@ -2611,13 +2583,19 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
const crossTemplate = await request("/admin/workspace/install", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { templateKey: currentTemplateKey === "personal" ? "food" : "personal" },
payload: {
templateKey: currentTemplateKey === "personal" ? "food" : "personal",
templatePackageVersionId: originalInstallation.templatePackageVersionId,
},
});
assert.equal(crossTemplate.statusCode, 400, crossTemplate.body);
const installed = await request("/admin/workspace/install", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { templateKey: currentTemplateKey },
payload: {
templateKey: currentTemplateKey,
templatePackageVersionId: originalInstallation.templatePackageVersionId,
},
});
assert.equal(installed.statusCode, 201, installed.body);
assert.equal(JSON.parse(installed.body).template.key, currentTemplateKey);
@@ -2627,7 +2605,10 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
),
true,
);
assert.equal(JSON.parse(installed.body).installation.configSnapshot.schemaVersion, "1.0");
assert.equal(
JSON.parse(installed.body).installation.configSnapshot.packageKey,
originalInstallation.configSnapshot.packageKey,
);
const installedRecord = JSON.parse(installed.body).installation;
const createdVersionIds = [];
let historicalReleaseId;
@@ -2681,7 +2662,10 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
},
});
historicalSubmissionId = historicalSubmission.id;
const packageKey = installedRecord.visualTemplateKey;
const installedPackageVersion = await prisma.templatePackageVersion.findUniqueOrThrow({
where: { id: originalInstallation.templatePackageVersionId },
});
const packageKey = installedPackageVersion.packageKey;
const packageVersion = `9.${Date.now()}.0`;
const initialPackageVersion = "1.0.0-phase6-test";
const templatePackage = await prisma.templatePackage.upsert({
@@ -2689,23 +2673,22 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
create: { packageKey },
update: {},
});
const initialManifest = structuredClone(installedPackageVersion.manifestSnapshot);
initialManifest.version = initialPackageVersion;
initialManifest.templateFields = [
{ key: "founder", binding: "brand.config.founder", label: "主理人" },
];
initialManifest.entrypoints = { home: "pages/index/index" };
initialManifest.assetSlots = [{ key: "brand.logo", binding: "brand.avatarUrl" }];
initialManifest.requiredCapabilities = ["offerings"];
const initialPackageVersionRecord = await prisma.templatePackageVersion.create({
data: {
templatePackageId: templatePackage.id,
packageKey,
version: initialPackageVersion,
displayName: "集成测试基线包",
visualTemplateKey: packageKey,
status: "published",
manifestSnapshot: {
packageKey,
version: initialPackageVersion,
supportedIndustryTemplates: [currentTemplateKey],
requiredCapabilities: ["offerings"],
templateFields: [{ key: "founder", binding: "brand.config.founder", label: "主理人" }],
entrypoints: { home: "pages/index/index" },
assetSlots: [{ key: "brand.logo", binding: "brand.avatarUrl" }],
},
manifestSnapshot: initialManifest,
validationReport: {},
contentChecksum: `checksum-${initialPackageVersion}`,
archiveChecksum: `archive-${initialPackageVersion}`,
@@ -2730,28 +2713,28 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
configSnapshot: initialPackageVersionRecord.manifestSnapshot,
},
});
const targetManifest = structuredClone(initialManifest);
targetManifest.version = packageVersion;
targetManifest.templateFields = [
{ key: "founder", binding: "brand.config.founder", label: "品牌主理人" },
];
targetManifest.entrypoints = {
home: "pages/home/index",
profile: "pages/profile/index",
};
targetManifest.assetSlots = [
{ key: "brand.logo", binding: "brand.avatarUrl" },
{ key: "home.hero", binding: "brand.config.heroImage" },
];
targetManifest.requiredCapabilities = [];
const packageVersionRecord = await prisma.templatePackageVersion.create({
data: {
templatePackageId: templatePackage.id,
packageKey,
version: packageVersion,
displayName: "集成测试升级包",
visualTemplateKey: packageKey,
status: "published",
manifestSnapshot: {
packageKey,
version: packageVersion,
supportedIndustryTemplates: [currentTemplateKey],
requiredCapabilities: [],
templateFields: [
{ key: "founder", binding: "brand.config.founder", label: "品牌主理人" },
],
entrypoints: { home: "pages/home/index", profile: "pages/profile/index" },
assetSlots: [
{ key: "brand.logo", binding: "brand.avatarUrl" },
{ key: "home.hero", binding: "brand.config.heroImage" },
],
},
manifestSnapshot: targetManifest,
validationReport: {},
contentChecksum: `checksum-${packageVersion}`,
archiveChecksum: `archive-${packageVersion}`,
@@ -2913,7 +2896,6 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
assert.equal(operationAudit[0].metadata.brandId, brandId);
assert.equal(operationAudit[0].metadata.contentChecksum, packageVersionRecord.contentChecksum);
assert.ok(operationAudit[0].requestId);
await prisma.templatePackageVersion.deleteMany({ where: { id: { in: createdVersionIds } } });
const workspace = await request("/admin/workspace", {
headers: { authorization: `Bearer ${token}` },
});
@@ -2964,6 +2946,17 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
await prisma.templatePackageVersion.deleteMany({ where: { id: { in: createdVersionIds } } });
await prisma.brandTemplateInstallation.create({
data: {
brandId,
templateKey: originalInstallation.templateKey,
templateVersion: originalInstallation.templateVersion,
templatePackageVersionId: originalInstallation.templatePackageVersionId,
contentChecksum: originalInstallation.contentChecksum,
configSnapshot: originalInstallation.configSnapshot,
previousSnapshots: originalInstallation.previousSnapshots,
},
});
await prisma.brandProfile.update({
where: { id: brandId },
data: { templateKey: originalBrand.templateKey, config: originalBrand.config },
@@ -2994,13 +2987,12 @@ test("admin preview workspace is authorized and brand-scoped draft runtime", asy
workspace.brand.slug,
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).slug,
);
assert.equal(workspace.brand.visualTemplateKey, "acheng-campus-food");
assert.equal(workspace.visualTemplate.key, "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" } },
},
});
@@ -3013,9 +3005,7 @@ test("admin preview workspace is authorized and brand-scoped draft runtime", asy
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");
assert.equal(draft.statusCode, 400);
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);
@@ -3026,18 +3016,11 @@ test("admin preview workspace is authorized and brand-scoped draft runtime", asy
test("admin can customize workspace fields with brand isolation", async () => {
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const install = await request("/admin/workspace/install", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: { templateKey: "food" },
});
assert.equal(install.statusCode, 201);
const workspace = await request("/admin/workspace", {
headers: { authorization: `Bearer ${token}` },
});
@@ -3074,45 +3057,37 @@ test("admin can customize workspace fields with brand isolation", async () => {
assert.equal(deletedField.statusCode, 200);
} finally {
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
await prisma.brandTemplateInstallation.deleteMany({ where: { brandId } });
}
});
test("admin visual template selection is reflected in public runtime workspace", async () => {
test("selected package version is reflected in public runtime workspace", async () => {
const login = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
const before = await request("/public/workspace");
assert.equal(before.statusCode, 200);
const updated = await request("/admin/config/brand", {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { config: { visualTemplateKey: "acheng-campus-food" } },
const installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId },
});
assert.equal(updated.statusCode, 200);
try {
const runtime = await request("/public/workspace");
assert.equal(runtime.statusCode, 200);
const body = JSON.parse(runtime.body);
assert.equal(body.visualTemplate.key, "acheng-campus-food");
assert.equal(body.visualTemplate.version, "1.0.0");
assert.equal(body.theme.colors.accent, "#E87532");
assert.equal(body.visualTemplate.variants.hero, "stall-board");
assert.equal(body.visualTemplateManifest.key, "acheng-campus-food");
assert.equal(body.visualTemplateManifest.brandFirst, true);
assert.deepEqual(
body.visualTemplateManifest.pages.map((page) => page.key),
["home", "offerings", "detail", "inquiry", "success", "records", "profile"],
);
} finally {
await request("/admin/config/brand", {
method: "PATCH",
headers: { authorization: `Bearer ${token}` },
payload: { config: JSON.parse(before.body).brand?.config ?? {} },
});
}
const selectedVersion = await prisma.templatePackageVersion.findUniqueOrThrow({
where: { id: installation.templatePackageVersionId },
});
const updated = await request("/admin/workspace/template/select-version", {
method: "POST",
headers: { authorization: `Bearer ${token}` },
payload: {
templatePackageVersionId: installation.templatePackageVersionId,
expectedCurrentPackageVersionId: installation.templatePackageVersionId,
confirm: true,
},
});
assert.equal(updated.statusCode, 201);
assert.equal(JSON.parse(updated.body).unchanged, true);
const runtime = await request("/public/workspace");
assert.equal(runtime.statusCode, 200);
const body = JSON.parse(runtime.body);
assert.equal(body.visualTemplate.key, selectedVersion.manifestSnapshot.visualTemplateKey);
assert.equal(body.visualTemplateManifest.key, selectedVersion.manifestSnapshot.visualTemplateKey);
});
test("public workspace exposes declared brand and trust presentation data", async () => {
@@ -4445,7 +4420,6 @@ test("atelier template imports selected package and preserves draft publication
tagline: "独立开发者 · 品牌小程序构建",
description: "专注个人品牌表达、内容管理与咨询承接。",
config: {
visualTemplateKey: "linjing-editorial",
founder: "验收主理人",
title: "产品设计 / 全栈开发",
visualPresentation: { home: { subtitle: "保留已有品牌说明" } },
@@ -4478,11 +4452,20 @@ test("atelier template imports selected package and preserves draft publication
403,
);
}
await json("/admin/config/brand", {
method: "PATCH",
headers,
payload: { config: { visualTemplateKey: "atelier-solopreneur" } },
});
const rejectSelectVersion = async (requestHeaders, expectedStatus) => {
const response = await request("/admin/workspace/template/select-version", {
method: "POST",
headers: requestHeaders,
payload: {
templatePackageVersionId: "00000000-0000-4000-8000-000000000001",
confirm: true,
},
});
assert.equal(response.statusCode, expectedStatus);
};
await rejectSelectVersion({}, 401);
await rejectSelectVersion({ authorization: "Bearer invalid" }, 401);
await rejectSelectVersion({ authorization: `Bearer ${customerToken}` }, 403);
const packageArchive = multipartArchive(createTemplateArchive("atelier-solopreneur"));
const importedPackage = await request("/admin/templates/import", {
method: "POST",
@@ -4503,6 +4486,18 @@ test("atelier template imports selected package and preserves draft publication
});
assert.equal(installation.visualTemplate.key, "atelier-solopreneur");
assert.equal(installation.visualTemplate.tokens.colors.accent, "#1f3a5f");
const selectedAgain = await json("/admin/workspace/template/select-version", {
method: "POST",
headers,
payload: {
templatePackageVersionId: selectedPackage.id,
expectedCurrentPackageVersionId: selectedPackage.id,
confirm: true,
},
});
assert.equal(selectedAgain.unchanged, true);
const selectedBrand = await json("/admin/config/brand", { headers });
assert.equal(Object.hasOwn(selectedBrand.config ?? {}, "visualTemplateKey"), false);
const preview = await json("/admin/workspace/sample-content/preview", { headers });
assert.equal(preview.counts.fields, 5);
await json("/admin/workspace/sample-content/import", {