refactor: 拆分品牌业务类型与页面方案
CI / Static checks (push) Has been cancelled
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Taro builds (acheng-campus-food) (push) Has been cancelled
CI / Taro builds (atelier-solopreneur) (push) Has been cancelled
CI / Taro builds (linjing-editorial) (push) Has been cancelled
CI / Browser regression (push) Has been cancelled

This commit is contained in:
que01 committed 2026-10-20 17:04:30 +08:00
1 parent f02e2cafbb
commit 0d9f4a7d6f
86 files changed
+4111 -1543

No files matched your search

+10
View File
@@ -12,11 +12,20 @@ import { AdminCapabilityController } from "../src/modules/workspace/admin-capabi
import { AdminOfferingController } from "../src/modules/workspace/admin-offering.controller.js";
import { AdminInquiryController } from "../src/modules/workspace/admin-inquiry.controller.js";
import { AdminTemplatePackageController } from "../src/modules/admin/admin-template-package.controller.js";
import { TenantController } from "../src/modules/tenant/tenant.controller.js";
const expectedRoutes = new Set([
"GET /admin/brands/creation-options",
"POST /admin/brands",
"GET /admin/brands/members",
"POST /admin/brands/members",
"PATCH /admin/brands/members/:id",
"GET /admin/brands",
"POST /admin/brands/:brandId/switch",
"GET /admin/workspace",
"GET /admin/workspace/preview",
"POST /admin/workspace/install",
"GET /admin/workspace/template/options",
"GET /admin/workspace/template/preview",
"POST /admin/workspace/template/upgrade",
"POST /admin/workspace/template/rollback",
@@ -50,6 +59,7 @@ const expectedRoutes = new Set([
test("refactored admin controllers preserve their declared API routes", () => {
const controllers = [
TenantController,
AdminWorkspacePreviewController,
AdminTemplateController,
AdminCapabilityController,
+481 -32
View File
@@ -137,11 +137,12 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
const baseline = JSON.parse(empty.body);
assert.deepEqual(baseline.items.map((item) => item.packageKey).sort(), [
"acheng-campus-food",
"atelier-solopreneur",
"linjing-editorial",
]);
const linjingVersion = baseline.items.find((item) => item.packageKey === "linjing-editorial");
assert.ok(linjingVersion);
assert.equal(linjingVersion.version, "1.0.6");
assert.equal(linjingVersion.version, "1.0.7");
const linjingPreview = await request(
`/admin/templates/${linjingVersion.id}/preview?industry=doors`,
{ headers },
@@ -380,15 +381,12 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
assert.equal(rejectedImport.statusCode, 400, rejectedImport.body);
assert.match(JSON.parse(rejectedImport.body).error.message, /previewFixture/);
assert.equal(await prisma.templatePackageVersion.count(), versionCount);
const archive = createTemplateArchive("atelier-solopreneur");
const multipart = multipartArchive(archive);
const imported = await request("/admin/templates/import", {
method: "POST",
headers: { ...headers, ...multipart.headers },
rawPayload: multipart.payload,
// 预览只允许使用平台当前已部署的精确 renderer 版本;复用 prepare 阶段导入的基线版本,
// 避免测试自造一个 renderer 尚未部署的新版本。
const baselineVersion = await prisma.templatePackageVersion.findFirstOrThrow({
where: { packageKey: "atelier-solopreneur", version: "1.3.2", status: "published" },
});
assert.equal(imported.statusCode, 201);
const versionId = JSON.parse(imported.body).version.id;
const versionId = baselineVersion.id;
const businessCounts = () =>
Promise.all([
@@ -625,21 +623,17 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
assert.match(JSON.parse(incompatible.body).error.message, /不支持所选行业/);
assert.deepEqual(await businessCounts(), before);
const repeatedPublish = await request(`/admin/templates/${versionId}/publish`, {
method: "POST",
headers,
});
assert.equal(repeatedPublish.statusCode, 201);
assert.equal(JSON.parse(repeatedPublish.body).changed, false);
const retired = await request(`/admin/templates/${versionId}/retire`, {
method: "POST",
headers,
});
assert.equal(retired.statusCode, 409);
const published = await request(`/admin/templates/${versionId}/publish`, {
method: "POST",
headers,
});
assert.equal(published.statusCode, 201);
const retiredAfterPublish = await request(`/admin/templates/${versionId}/retire`, {
method: "POST",
headers,
});
assert.equal(retiredAfterPublish.statusCode, 201);
assert.equal(retired.statusCode, 201);
const retiredPreview = await request(`/admin/templates/${versionId}/preview?industry=personal`, {
headers,
});
@@ -1988,7 +1982,7 @@ test("visual template compatibility is enforced by catalog, preview, and version
}
assert.deepEqual(
visuals.find((visual) => visual.key === "linjing-editorial").supportedIndustryTemplates,
["personal", "doors"],
["doors"],
);
const incompatiblePreview = await request(
"/public/templates/preview?industry=food&visual=linjing-editorial",
@@ -2149,6 +2143,337 @@ test("seeded public workspaces keep personal, food, and doors brands isolated",
assert.equal(new Set(workspaces.map((workspace) => workspace.brand.id)).size, 2);
});
test("brand creation options are owner-scoped", async () => {
const unauthorized = await request("/admin/brands/creation-options");
assert.equal(unauthorized.statusCode, 401);
const customerForbidden = await request("/admin/brands/creation-options", {
headers: { authorization: `Bearer ${customerToken}` },
});
assert.equal(customerForbidden.statusCode, 403);
const ownerLogin = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const ownerToken = sessionToken(ownerLogin);
const editorUser = await prisma.adminUser.create({
data: {
username: `creation-options-editor-${randomUUID()}`,
passwordHash: "unused",
displayName: "建品牌权限测试编辑",
mustChangePassword: false,
},
});
const editorMembership = await prisma.brandMembership.create({
data: { adminUserId: editorUser.id, brandId, role: "editor" },
});
try {
const editorToken = signIdentity({
subject: editorUser.id,
brandId,
role: "admin",
tokenVersion: editorUser.tokenVersion,
});
const editorForbidden = await request("/admin/brands/creation-options", {
headers: { authorization: `Bearer ${editorToken}` },
});
assert.equal(editorForbidden.statusCode, 403);
const response = await request("/admin/brands/creation-options", {
headers: { authorization: `Bearer ${ownerToken}` },
});
assert.equal(response.statusCode, 200, response.body);
const options = JSON.parse(response.body);
assert.deepEqual(options.businesses.map((business) => business.key).sort(), [
"doors",
"food",
"personal",
]);
assert.ok(options.businesses.every((business) => business.name && business.description));
// 创建品牌只暴露每个页面方案的最新版本,避免新品牌起步在旧版本上。
assert.equal(options.pageSchemes.length, 3, JSON.stringify(options.pageSchemes));
const linjingScheme = options.pageSchemes.find((scheme) => scheme.name.includes("林境"));
assert.ok(linjingScheme);
assert.equal(linjingScheme.version, "1.0.7");
assert.deepEqual(linjingScheme.supportedBusinessTypes, ["doors"]);
assert.equal(linjingScheme.isLatestForPackage, true);
const atelierScheme = options.pageSchemes.find((scheme) => scheme.name.includes("工坊"));
assert.ok(atelierScheme);
assert.equal(atelierScheme.version, "1.3.2");
assert.deepEqual(atelierScheme.supportedBusinessTypes, ["personal"]);
assert.equal(
options.pageSchemes.some(
(scheme) =>
scheme.supportedBusinessTypes.includes("personal") &&
scheme.supportedBusinessTypes.includes("doors"),
),
false,
"页面方案不应同时兼容 personal 和 doors",
);
assert.equal(JSON.stringify(options).includes("visualTemplateKey"), false);
assert.equal(JSON.stringify(options).includes("packageKey"), false);
} finally {
await prisma.brandMembership.delete({ where: { id: editorMembership.id } });
await prisma.adminUser.delete({ where: { id: editorUser.id } });
}
});
test("owner can create an isolated brand", async () => {
const startedAt = new Date();
const suffix = randomUUID().slice(0, 8);
const personalSlug = `atelier-created-${suffix}`;
const doorsSlug = `linjing-created-${suffix}`;
// 集成 fixture 必须锁定精确版本,避免导入时间或历史版本影响测试语义。
const atelier = await prisma.templatePackageVersion.findFirstOrThrow({
where: {
packageKey: "atelier-solopreneur",
version: "1.3.2",
status: "published",
},
});
const linjing = await prisma.templatePackageVersion.findFirstOrThrow({
where: {
packageKey: "linjing-editorial",
version: "1.0.7",
status: "published",
},
});
const ownerLogin = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const ownerToken = sessionToken(ownerLogin);
const ownerIdentity = readIdentity(ownerToken);
const unauthorizedPayload = {
name: "未授权品牌",
slug: `unauthorized-${suffix}`,
businessType: "personal",
templatePackageVersionId: atelier.id,
};
const unauthorized = await request("/admin/brands", {
method: "POST",
payload: unauthorizedPayload,
});
assert.equal(unauthorized.statusCode, 401);
const customerForbidden = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${customerToken}` },
payload: unauthorizedPayload,
});
assert.equal(customerForbidden.statusCode, 403);
const incompatible = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "不兼容品牌",
slug: `incompatible-${suffix}`,
businessType: "personal",
templatePackageVersionId: linjing.id,
},
});
assert.equal(incompatible.statusCode, 400, incompatible.body);
assert.match(errorMessage(incompatible.body), /业务类型|页面方案|兼容/);
assert.equal(await prisma.brandProfile.count({ where: { slug: `incompatible-${suffix}` } }), 0);
try {
const created = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "新建独立工坊",
slug: personalSlug,
businessType: "personal",
templatePackageVersionId: atelier.id,
},
});
assert.equal(created.statusCode, 201, created.body);
const createdBrand = JSON.parse(created.body).brand;
assert.equal(createdBrand.slug, personalSlug);
assert.equal(createdBrand.templateKey, "personal");
const profile = await prisma.brandProfile.findUniqueOrThrow({
where: { id: createdBrand.id },
});
assert.equal(profile.templateKey, "personal");
assert.deepEqual(profile.config, {});
const installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId: createdBrand.id },
});
assert.equal(installation.templateKey, "personal");
assert.equal(installation.templatePackageVersionId, atelier.id);
assert.equal(installation.templateVersion, atelier.version);
assert.ok(
(await prisma.brandFieldDefinition.count({ where: { brandId: createdBrand.id } })) > 0,
);
const membership = await prisma.brandMembership.findUniqueOrThrow({
where: {
adminUserId_brandId: {
adminUserId: ownerIdentity.subject,
brandId: createdBrand.id,
},
},
});
assert.equal(membership.role, "owner");
assert.equal(membership.isEnabled, true);
const audit = await prisma.templatePackageAuditLog.findFirstOrThrow({
where: {
templatePackageVersionId: atelier.id,
actorId: ownerIdentity.subject,
action: "brand_created",
createdAt: { gte: startedAt },
},
orderBy: { createdAt: "desc" },
});
assert.equal(audit.metadata.brandId, createdBrand.id);
assert.equal(audit.metadata.businessType, "personal");
const newCookie = sessionToken(created);
assert.equal(readIdentity(newCookie).brandId, createdBrand.id);
const current = await request("/admin/config/brand", {
headers: { authorization: `Bearer ${newCookie}` },
});
assert.equal(current.statusCode, 200, current.body);
assert.equal(JSON.parse(current.body).id, createdBrand.id);
const duplicate = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "重复地址品牌",
slug: personalSlug,
businessType: "personal",
templatePackageVersionId: atelier.id,
},
});
assert.equal(duplicate.statusCode, 409, duplicate.body);
assert.equal(await prisma.brandProfile.count({ where: { slug: personalSlug } }), 1);
const invalidBusinessType = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "非法业务品牌",
slug: `invalid-business-${suffix}`,
businessType: "consulting",
templatePackageVersionId: atelier.id,
},
});
assert.equal(invalidBusinessType.statusCode, 400);
const incompatible = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "不兼容页面方案品牌",
slug: `incompatible-${suffix}`,
businessType: "personal",
templatePackageVersionId: linjing.id,
},
});
assert.equal(incompatible.statusCode, 400, incompatible.body);
assert.equal(await prisma.brandProfile.count({ where: { slug: `incompatible-${suffix}` } }), 0);
const doorsCreated = await request("/admin/brands", {
method: "POST",
headers: { authorization: `Bearer ${ownerToken}` },
payload: {
name: "新建林境门窗",
slug: doorsSlug,
businessType: "doors",
templatePackageVersionId: linjing.id,
},
});
assert.equal(doorsCreated.statusCode, 201, doorsCreated.body);
const doorsBrand = JSON.parse(doorsCreated.body).brand;
const doorsInstallation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId: doorsBrand.id },
});
assert.equal(doorsInstallation.templateKey, "doors");
assert.equal(doorsInstallation.templatePackageVersionId, linjing.id);
} finally {
await prisma.templatePackageAuditLog.deleteMany({
where: {
actorId: ownerIdentity.subject,
action: "brand_created",
createdAt: { gte: startedAt },
},
});
await prisma.brandProfile.deleteMany({
where: { slug: { in: [personalSlug, doorsSlug] } },
});
}
});
test("page scheme options are readable by owners and admins only", async () => {
const unauthorized = await request("/admin/workspace/template/options");
assert.equal(unauthorized.statusCode, 401);
const customerForbidden = await request("/admin/workspace/template/options", {
headers: { authorization: `Bearer ${customerToken}` },
});
assert.equal(customerForbidden.statusCode, 403);
const ownerLogin = await request("/admin/session/login", {
method: "POST",
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
});
const ownerToken = sessionToken(ownerLogin);
const members = [];
try {
for (const role of ["admin", "editor"]) {
const user = await prisma.adminUser.create({
data: {
username: `page-scheme-${role}-${randomUUID()}`,
passwordHash: "unused",
displayName: `页面方案${role}测试`,
mustChangePassword: false,
},
});
const membership = await prisma.brandMembership.create({
data: { adminUserId: user.id, brandId, role },
});
members.push({ userId: user.id, membershipId: membership.id });
const token = signIdentity({
subject: user.id,
brandId,
role: "admin",
tokenVersion: user.tokenVersion,
});
if (role === "admin") {
const adminResponse = await request("/admin/workspace/template/options", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(adminResponse.statusCode, 200, adminResponse.body);
const adminOptions = JSON.parse(adminResponse.body);
assert.equal(adminOptions.business.key, "food");
assert.equal(adminOptions.pageSchemes.length > 0, true);
assert.ok(
adminOptions.pageSchemes.every((scheme) =>
scheme.supportedBusinessTypes.includes("food"),
),
);
} else {
const editorForbidden = await request("/admin/workspace/template/options", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(editorForbidden.statusCode, 403);
}
}
const ownerResponse = await request("/admin/workspace/template/options", {
headers: { authorization: `Bearer ${ownerToken}` },
});
assert.equal(ownerResponse.statusCode, 200, ownerResponse.body);
const ownerOptions = JSON.parse(ownerResponse.body);
assert.equal(ownerOptions.business.key, "food");
assert.equal(JSON.stringify(ownerOptions).includes("visualTemplateKey"), false);
assert.equal(JSON.stringify(ownerOptions).includes("packageKey"), false);
} finally {
for (const item of members.reverse()) {
await prisma.brandMembership.delete({ where: { id: item.membershipId } });
await prisma.adminUser.delete({ where: { id: item.userId } });
}
}
});
test("public workspace uses brand-scoped capability installations and preserves status", async () => {
await prisma.capabilityInstallation.deleteMany({ where: { brandId } });
const installation = await prisma.capabilityInstallation.create({
@@ -2281,6 +2606,10 @@ test("editor membership can manage brand content but cannot change system settin
payload: { config: { visualTemplateKey: "unknown-visual" } },
});
assert.equal(visualUpdate.statusCode, 400);
const pageSchemePreview = await request("/admin/workspace/template/preview", {
headers: { authorization: `Bearer ${token}` },
});
assert.equal(pageSchemePreview.statusCode, 403);
} finally {
await prisma.brandMembership.update({
where: { id: membership.id },
@@ -2887,10 +3216,19 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
const initialManifest = structuredClone(installedPackageVersion.manifestSnapshot);
initialManifest.version = initialPackageVersion;
initialManifest.templateFields = [
{ key: "founder", binding: "brand.config.founder", label: "主理人" },
{ key: "founder", binding: "brand.config.templateData.founder", label: "主理人" },
];
initialManifest.assetSlots = [
{
key: "brand.logo",
binding: "brand.avatarUrl",
target: "brand",
label: "品牌标志",
help: "用于品牌身份展示。",
required: false,
kind: "logo",
},
];
initialManifest.entrypoints = { home: "pages/index/index" };
initialManifest.assetSlots = [{ key: "brand.logo", binding: "brand.avatarUrl" }];
initialManifest.requiredCapabilities = ["offerings"];
const initialPackageVersionRecord = await prisma.templatePackageVersion.create({
data: {
@@ -2911,9 +3249,20 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
const originalConfig =
originalBrand.config && typeof originalBrand.config === "object" ? originalBrand.config : {};
const existingFounder = "升级前的品牌主理人";
const originalTemplateData =
originalConfig.templateData &&
typeof originalConfig.templateData === "object" &&
!Array.isArray(originalConfig.templateData)
? originalConfig.templateData
: {};
await prisma.brandProfile.update({
where: { id: brandId },
data: { config: { ...originalConfig, founder: existingFounder } },
data: {
config: {
...originalConfig,
templateData: { ...originalTemplateData, founder: existingFounder },
},
},
});
await prisma.brandTemplateInstallation.update({
where: { id: installedRecord.id },
@@ -2927,15 +3276,32 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
const targetManifest = structuredClone(initialManifest);
targetManifest.version = packageVersion;
targetManifest.templateFields = [
{ key: "founder", binding: "brand.config.founder", label: "品牌主理人" },
{ key: "founder", binding: "brand.config.templateData.founder", label: "品牌主理人" },
];
targetManifest.entrypoints = {
...initialManifest.entrypoints,
home: "pages/home/index",
profile: "pages/profile/index",
gallery: "pages/gallery/index",
};
targetManifest.assetSlots = [
{ key: "brand.logo", binding: "brand.avatarUrl" },
{ key: "home.hero", binding: "brand.config.heroImage" },
{
key: "brand.logo",
binding: "brand.avatarUrl",
target: "brand",
label: "品牌标志",
help: "用于品牌身份展示。",
required: false,
kind: "logo",
},
{
key: "home.hero",
binding: "brand.config.heroImage",
target: "brand",
label: "首页主图",
help: "用于首页展示品牌重点内容。",
required: false,
kind: "image",
},
];
targetManifest.requiredCapabilities = [];
const packageVersionRecord = await prisma.templatePackageVersion.create({
@@ -2962,7 +3328,7 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
assert.equal(actionable.targetPackageVersionId, packageVersionRecord.id);
assert.equal(actionable.changes.brandFields.available, false);
assert.equal(actionable.conflicts.length, 1);
assert.equal(actionable.conflicts[0].binding, "brand.config.founder");
assert.equal(actionable.conflicts[0].binding, "brand.config.templateData.founder");
assert.equal(actionable.changes.pages.added.length, 1);
assert.equal(actionable.changes.assets.slots.added.length, 1);
assert.deepEqual(actionable.changes.capabilities.removed, ["offerings"]);
@@ -3001,7 +3367,9 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
expectedCurrentVersion: actionable.currentVersion,
expectedCurrentPackageVersionId: actionable.currentPackageVersionId,
confirm: true,
preservedBindings: [{ key: "founder", binding: "brand.config.founder", action: "preserve" }],
preservedBindings: [
{ key: "founder", binding: "brand.config.templateData.founder", action: "preserve" },
],
};
const upgradeAttempts = await Promise.all(
[0, 1].map(() =>
@@ -3020,7 +3388,8 @@ test("template ledger install, upgrade preview, and rollback stay brand-scoped",
packageVersionRecord.id,
);
assert.equal(
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).config.founder,
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).config.templateData
.founder,
existingFounder,
);
const retainedOldPackage = await prisma.templatePackageVersion.findUniqueOrThrow({
@@ -3391,6 +3760,86 @@ test("selected package version is reflected in public runtime workspace", async
assert.equal(body.visualTemplateManifest.key, selectedVersion.manifestSnapshot.visualTemplateKey);
});
test("legacy doors installation preview separates content package and platform renderer versions", async () => {
const doorsBrand = await prisma.brandProfile.findUniqueOrThrow({
where: { slug: "linjing-doors" },
});
const adminUser = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
const installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
where: { brandId: doorsBrand.id },
});
const currentPackage = await prisma.templatePackageVersion.findFirstOrThrow({
where: {
packageKey: "linjing-editorial",
version: "1.0.7",
status: "published",
},
});
// 模拟真实旧安装:内容包锁定 1.0.6,但平台 renderer 已是 1.0.7。
const legacyManifest = {
...currentPackage.manifestSnapshot,
version: "1.0.6",
supportedIndustryTemplates: ["personal", "doors"],
};
const legacyPackage = await prisma.templatePackageVersion.create({
data: {
templatePackageId: currentPackage.templatePackageId,
packageKey: currentPackage.packageKey,
version: "1.0.6",
displayName: currentPackage.displayName,
status: "published",
manifestSnapshot: legacyManifest,
validationReport: currentPackage.validationReport,
contentChecksum: `legacy-${randomUUID()}`,
archiveChecksum: `legacy-archive-${randomUUID()}`,
artifactPath: currentPackage.artifactPath,
importedById: adminUser.id,
},
});
const headers = {
authorization: `Bearer ${signIdentity({
subject: adminUser.id,
brandId: doorsBrand.id,
role: "admin",
tokenVersion: adminUser.tokenVersion,
})}`,
};
try {
await prisma.brandTemplateInstallation.update({
where: { brandId: doorsBrand.id },
data: {
templateVersion: legacyPackage.version,
templatePackageVersionId: legacyPackage.id,
contentChecksum: legacyPackage.contentChecksum,
configSnapshot: legacyPackage.manifestSnapshot,
},
});
const previewResponse = await request("/admin/workspace/template/preview", { headers });
assert.equal(previewResponse.statusCode, 200, previewResponse.body);
const preview = JSON.parse(previewResponse.body);
assert.equal(preview.currentVersion, "1.0.6");
assert.equal(preview.latestVersion, "1.0.7");
assert.equal(preview.canUpgrade, true);
assert.equal(preview.targetPackageVersionId, currentPackage.id);
assert.equal(preview.changes.renderer.available, true);
assert.equal(preview.changes.renderer.source, "platform_visual_manifest");
assert.equal(preview.changes.renderer.packageUpgradeChangesRenderer, false);
assert.ok(preview.changes.renderer.pages.length > 0);
} finally {
await prisma.brandTemplateInstallation.update({
where: { brandId: doorsBrand.id },
data: {
templateVersion: installation.templateVersion,
templatePackageVersionId: installation.templatePackageVersionId,
contentChecksum: installation.contentChecksum,
configSnapshot: installation.configSnapshot,
},
});
await prisma.templatePackageVersion.delete({ where: { id: legacyPackage.id } });
}
});
test("public workspace exposes declared brand and trust presentation data", async () => {
const doorsBrand = await prisma.brandProfile.findUnique({ where: { slug: "linjing-doors" } });
assert.ok(doorsBrand);
+25
View File
@@ -0,0 +1,25 @@
import assert from "node:assert/strict";
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import { test } from "node:test";
const projectRoot = path.resolve(import.meta.dirname, "../../..");
const seedPath = path.join(projectRoot, "apps/api/prisma/seed.ts");
const assetDirectory = path.join(projectRoot, "apps/api/prisma/assets");
test("开发 seed 引用的本地媒体都有随仓库分发的源文件", () => {
const seed = readFileSync(seedPath, "utf8");
const references = [...seed.matchAll(/["'](\/media\/seed\/[^"']+)["']/g)].map(
([, mediaPath]) => mediaPath,
);
assert.ok(references.length > 0, "seed 中没有找到本地媒体引用");
for (const mediaPath of new Set(references)) {
const filename = path.basename(mediaPath);
assert.equal(
existsSync(path.join(assetDirectory, filename)),
true,
`seed 引用的媒体缺少源文件: ${mediaPath}`,
);
}
});
@@ -10,7 +10,7 @@ import { createApp } from "../dist/main.js";
import { signIdentity } from "../dist/auth.js";
const prisma = new PrismaClient();
const packageKeys = ["acheng-campus-food", "linjing-editorial"];
const packageKeys = ["acheng-campus-food", "linjing-editorial", "atelier-solopreneur"];
function run(command, args, options = {}) {
const result = spawnSync(command, args, { stdio: "inherit", ...options });
+26 -1
View File
@@ -69,6 +69,14 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
authorizationTest: "admin can list and switch only enabled brand memberships",
successTest: "admin can list and switch only enabled brand memberships",
},
{
method: "GET",
path: "/admin/brands/creation-options",
auth: "roles",
roles: ["owner"],
authorizationTest: "brand creation options are owner-scoped",
successTest: "brand creation options are owner-scoped",
},
{
method: "GET",
path: "/admin/brands/members",
@@ -222,10 +230,19 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
{
method: "GET",
path: "/admin/workspace/template/preview",
auth: "brand",
auth: "roles",
roles: ["owner", "admin", "platform-admin"],
authorizationTest: "template ledger install, upgrade preview, and rollback stay brand-scoped",
successTest: "template ledger install, upgrade preview, and rollback stay brand-scoped",
},
{
method: "GET",
path: "/admin/workspace/template/options",
auth: "roles",
roles: ["owner", "admin", "platform-admin"],
authorizationTest: "page scheme options are readable by owners and admins only",
successTest: "page scheme options are readable by owners and admins only",
},
{
method: "GET",
path: "/customer/bookings",
@@ -436,6 +453,14 @@ export const ROUTE_COVERAGE: RouteCoverage[] = [
authorizationTest: "admin can list and switch only enabled brand memberships",
successTest: "admin can list and switch only enabled brand memberships",
},
{
method: "POST",
path: "/admin/brands",
auth: "roles",
roles: ["owner"],
authorizationTest: "owner can create an isolated brand",
successTest: "owner can create an isolated brand",
},
{
method: "POST",
path: "/admin/brands/members",
+68
View File
@@ -1,5 +1,7 @@
const assert = require("node:assert/strict");
const { randomBytes } = require("node:crypto");
const { existsSync } = require("node:fs");
const path = require("node:path");
const { spawnSync } = require("node:child_process");
const { PrismaClient } = require("@prisma/client");
@@ -32,7 +34,47 @@ async function main() {
const initialTrustCount = await fixtureDatabase.trustContent.count();
const initialFormCount = await fixtureDatabase.inquiryForm.count();
const initialReleases = await fixtureDatabase.brandRelease.findMany({ orderBy: { id: "asc" } });
// 模拟旧模板遗留数据:数组 config、失效封面和媒体引用。重复 seed 必须修复结构,
// 同时保留记录本身和停用状态。
const doorsBrand = await fixtureDatabase.brandProfile.findUniqueOrThrow({
where: { slug: "linjing-doors" },
});
const legacyOfferingName = "legacy-offering-repair-fixture";
await fixtureDatabase.offering.create({
data: {
brandId: doorsBrand.id,
kind: "service",
name: legacyOfferingName,
coverUrl: "/media/seed/seed-02.jpg",
isEnabled: false,
config: [{ url: "/media/seed/seed-02.jpg" }],
},
});
if (run("pnpm", ["db:seed"]) !== 0) return status;
const repairedLegacyOffering = await fixtureDatabase.offering.findUniqueOrThrow({
where: { brandId_name: { brandId: doorsBrand.id, name: legacyOfferingName } },
});
assert.equal(
Array.isArray(repairedLegacyOffering.config),
false,
"Repeated seed must repair legacy array config",
);
assert.ok(
repairedLegacyOffering.config &&
typeof repairedLegacyOffering.config === "object" &&
Array.isArray(repairedLegacyOffering.config.media),
"Repeated seed must rebuild legacy media config",
);
assert.notEqual(
repairedLegacyOffering.coverUrl,
"/media/seed/seed-02.jpg",
"Repeated seed must replace a missing local cover",
);
assert.equal(
repairedLegacyOffering.isEnabled,
false,
"Repeated seed must preserve disabled offering state",
);
assert.equal(
await fixtureDatabase.trustContent.count(),
initialTrustCount,
@@ -48,6 +90,32 @@ async function main() {
initialReleases,
"Repeated seed must preserve release history and snapshots",
);
const seededOfferings = await fixtureDatabase.offering.findMany({
select: { name: true, coverUrl: true, config: true },
});
assert.ok(seededOfferings.length > 0, "Seed must create offering fixtures");
for (const offering of seededOfferings) {
assert.ok(
offering.config && typeof offering.config === "object" && !Array.isArray(offering.config),
`Seed offering config must be an object: ${offering.name}`,
);
const config = offering.config;
const mediaUrls = Array.isArray(config.media)
? config.media.flatMap((item) =>
item && typeof item === "object" && typeof item.url === "string" ? [item.url] : [],
)
: [];
const localMedia = [offering.coverUrl, ...mediaUrls].filter(
(url) => typeof url === "string" && url.startsWith("/media/seed/"),
);
for (const mediaPath of new Set(localMedia)) {
assert.equal(
existsSync(path.join(__dirname, "prisma/assets", path.basename(mediaPath))),
true,
`Seed offering references missing media: ${offering.name} -> ${mediaPath}`,
);
}
}
await fixtureDatabase.adminUser.updateMany({
where: { username: "admin" },
data: { mustChangePassword: false },
@@ -45,7 +45,7 @@ async function main() {
.filter((entry) => entry.isDirectory() && entry.name !== targetMigration)
.map((entry) => entry.name)
.sort();
assert.equal(migrationDirs.at(-1), "20261018180000_add_customer_token_version");
assert.equal(migrationDirs.at(-1), "20261019100000_remove_brand_profile_defaults");
await admin.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
createdSchema = true;
@@ -180,8 +180,8 @@ test("template preview matrix keeps every deployed package, industry, and versio
}
}
}
// 3 个包 x 支持行业(1 + 1 + 2)x 2 个版本 = 8 个隔离模拟品牌。
assert.equal(visibleBrands.size, 8);
// 3 个包 × 每个包一个支持行业 × 2 个版本 = 6 个隔离模拟品牌。
assert.equal(visibleBrands.size, 6);
} finally {
for (const fixture of fixtures) rmSync(fixture.root, { recursive: true, force: true });
}
@@ -0,0 +1,33 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { compareTemplateVersions, latestTemplateVersion } from "../src/template-version-order.js";
test("模板版本按 SemVer 而不是导入时间判断最新版", () => {
const importedLaterOldVersion = {
version: "1.9.0",
importedAt: new Date("2026-10-20T00:00:00Z"),
};
const importedEarlierNewVersion = {
version: "1.10.0",
importedAt: new Date("2026-10-19T00:00:00Z"),
};
assert.equal(
latestTemplateVersion([importedEarlierNewVersion, importedLaterOldVersion])?.version,
"1.10.0",
);
assert.ok(compareTemplateVersions("1.10.0", "1.9.0") > 0);
});
test("模板版本排序正确处理预发布版本和同版本稳定性", () => {
assert.ok(compareTemplateVersions("1.0.0", "1.0.0-beta.2") > 0);
assert.ok(compareTemplateVersions("1.0.0-beta.10", "1.0.0-beta.2") > 0);
const first = {
version: "1.0.0",
importedAt: new Date("2026-10-19T00:00:00Z"),
};
const second = {
version: "1.0.0",
importedAt: new Date("2026-10-20T00:00:00Z"),
};
assert.equal(latestTemplateVersion([first, second]), second);
});