为 miniprogram-ci 和 Jimp 依赖增加兼容 patch 与 smoke test;修复平台模板管理员路由漏配;收紧模板契约校验;为 admin/customer 增加 token 撤销和集中会话存储;同步品牌切换角色、doctor source hash、多屏宽截图证据和 CI 构建门禁。
4904 lines
193 KiB
JavaScript
4904 lines
193 KiB
JavaScript
import assert from "node:assert/strict";
|
|
import { createHash, randomUUID } from "node:crypto";
|
|
import { execFileSync } from "node:child_process";
|
|
import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { after, before, test } from "node:test";
|
|
import bcrypt from "bcryptjs";
|
|
import { PrismaClient } from "@prisma/client";
|
|
import { getTemplatePackageManifest, getVisualTemplateManifest } from "@personal-brand/config";
|
|
import { createApp } from "../dist/main.js";
|
|
import { readIdentity, signIdentity } from "../dist/auth.js";
|
|
import { WechatAuthService } from "../dist/wechat-auth.js";
|
|
import { AdminMiniAppReleaseService } from "../dist/modules/admin/admin-miniapp-release.service.js";
|
|
|
|
let app;
|
|
const prisma = new PrismaClient();
|
|
const brandId = process.env.DEFAULT_BRAND_ID;
|
|
|
|
const openid = `integration-${Date.now()}`;
|
|
let customerToken;
|
|
const createdBookingIds = [];
|
|
|
|
before(async () => {
|
|
process.env.TEMPLATE_ARTIFACT_ROOT = mkdtempSync(
|
|
path.join(os.tmpdir(), "personal-brand-template-artifacts-"),
|
|
);
|
|
await prisma.customerUser.create({ data: { brandId, openid } });
|
|
customerToken = signIdentity({ subject: openid, brandId, role: "customer" });
|
|
app = await createApp();
|
|
await app.init();
|
|
});
|
|
|
|
function multipartArchive(archive) {
|
|
const boundary = "----personal-brand-template-test";
|
|
const prefix = Buffer.from(
|
|
`--${boundary}\r\nContent-Disposition: form-data; name="archive"; filename="template.tar.gz"\r\nContent-Type: application/gzip\r\n\r\n`,
|
|
);
|
|
const suffix = Buffer.from(`\r\n--${boundary}--\r\n`);
|
|
return {
|
|
payload: Buffer.concat([prefix, archive, suffix]),
|
|
headers: { "content-type": `multipart/form-data; boundary=${boundary}` },
|
|
};
|
|
}
|
|
|
|
function createTemplateArchive(template = "acheng-campus-food", mutateManifest) {
|
|
const output = mkdtempSync(path.join(os.tmpdir(), "personal-brand-template-pack-"));
|
|
try {
|
|
execFileSync(
|
|
process.execPath,
|
|
[
|
|
path.resolve(process.cwd(), "../../scripts/template-pack.cjs"),
|
|
"--template",
|
|
template,
|
|
"--out",
|
|
output,
|
|
],
|
|
{ cwd: path.resolve(process.cwd(), "../.."), stdio: "ignore" },
|
|
);
|
|
const filename = readdirSync(output).find((item) => item.endsWith(".tar.gz"));
|
|
assert.ok(filename);
|
|
if (mutateManifest) {
|
|
const packageName = filename.slice(0, -7);
|
|
const directory = path.join(output, packageName);
|
|
const manifestPath = path.join(directory, "template.json");
|
|
const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
|
|
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,
|
|
sha256: item.sha256,
|
|
}));
|
|
checksums.contentChecksum = createHash("sha256")
|
|
.update(JSON.stringify(canonicalEntries))
|
|
.digest("hex");
|
|
writeFileSync(checksumPath, JSON.stringify(checksums));
|
|
execFileSync("tar", ["-czf", path.join(output, filename), "-C", output, packageName]);
|
|
}
|
|
return readFileSync(path.join(output, filename));
|
|
} finally {
|
|
rmSync(output, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
test("模板目录只允许平台模板管理员访问,并支持安全、幂等导入", async () => {
|
|
const missing = await request("/admin/templates");
|
|
assert.equal(missing.statusCode, 401);
|
|
const customer = await request("/admin/templates", {
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
});
|
|
assert.equal(customer.statusCode, 403);
|
|
const ordinaryUser = await prisma.adminUser.create({
|
|
data: {
|
|
username: `template-viewer-${Date.now()}`,
|
|
passwordHash: "not-used-by-this-test",
|
|
displayName: "普通管理员",
|
|
platformTemplateRole: "none",
|
|
mustChangePassword: false,
|
|
},
|
|
});
|
|
try {
|
|
const ordinary = await request("/admin/templates", {
|
|
headers: {
|
|
authorization: `Bearer ${signIdentity({ subject: ordinaryUser.id, brandId, role: "admin" })}`,
|
|
},
|
|
});
|
|
assert.equal(ordinary.statusCode, 403);
|
|
} finally {
|
|
await prisma.adminUser.delete({ where: { id: ordinaryUser.id } });
|
|
}
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
|
});
|
|
assert.equal(login.statusCode, 201);
|
|
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
|
|
const empty = await request("/admin/templates", { headers });
|
|
assert.equal(empty.statusCode, 200);
|
|
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.6");
|
|
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("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, imported.body);
|
|
assert.equal(JSON.parse(imported.body).imported, true);
|
|
const repeated = await request("/admin/templates/import", {
|
|
method: "POST",
|
|
headers: { ...headers, ...multipartArchive(archive).headers },
|
|
rawPayload: multipartArchive(archive).payload,
|
|
});
|
|
assert.equal(repeated.statusCode, 201);
|
|
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, 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 },
|
|
});
|
|
assert.ok(importedVersion.validationReport.files.length > 0);
|
|
assert.ok(
|
|
importedVersion.validationReport.files.every((file) => /^[a-f0-9]{64}$/.test(file.sha256)),
|
|
);
|
|
const publishMissing = await request(`/admin/templates/${versionId}/publish`, { method: "POST" });
|
|
assert.equal(publishMissing.statusCode, 401);
|
|
const publishCustomer = await request(`/admin/templates/${versionId}/publish`, {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
});
|
|
assert.equal(publishCustomer.statusCode, 403);
|
|
const published = await request(`/admin/templates/${versionId}/publish`, {
|
|
method: "POST",
|
|
headers,
|
|
});
|
|
assert.equal(published.statusCode, 201);
|
|
assert.equal(JSON.parse(published.body).version.status, "published");
|
|
const repeatedPublish = await request(`/admin/templates/${versionId}/publish`, {
|
|
method: "POST",
|
|
headers,
|
|
});
|
|
assert.equal(JSON.parse(repeatedPublish.body).changed, false);
|
|
const audit = await request(`/admin/templates/${versionId}/audit`, { headers });
|
|
assert.equal(audit.statusCode, 200);
|
|
assert.deepEqual(
|
|
JSON.parse(audit.body).map((item) => item.action),
|
|
["imported", "published"],
|
|
);
|
|
const retired = await request(`/admin/templates/${versionId}/retire`, {
|
|
method: "POST",
|
|
headers: { ...headers, "x-request-id": "template-retire-test" },
|
|
});
|
|
assert.equal(retired.statusCode, 201);
|
|
assert.equal(JSON.parse(retired.body).version.status, "retired");
|
|
const invalidRetire = await request(`/admin/templates/${versionId}/retire`, {
|
|
method: "POST",
|
|
headers,
|
|
});
|
|
assert.equal(invalidRetire.statusCode, 201);
|
|
assert.equal(JSON.parse(invalidRetire.body).changed, false);
|
|
});
|
|
|
|
test("模板失败指标仅平台模板管理员可查,按窗口聚合且不暴露操作内容", async () => {
|
|
const missing = await request("/admin/template-operations/failures");
|
|
assert.equal(missing.statusCode, 401);
|
|
const customer = await request("/admin/template-operations/failures", {
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
});
|
|
assert.equal(customer.statusCode, 403);
|
|
|
|
const ordinaryUser = await prisma.adminUser.create({
|
|
data: {
|
|
username: `metrics-viewer-${randomUUID()}`,
|
|
passwordHash: "unused",
|
|
displayName: "普通管理员",
|
|
platformTemplateRole: "none",
|
|
mustChangePassword: false,
|
|
},
|
|
});
|
|
const headers = {
|
|
authorization: `Bearer ${signIdentity({ subject: ordinaryUser.id, brandId, role: "admin" })}`,
|
|
};
|
|
try {
|
|
const forbidden = await request("/admin/template-operations/failures", { headers });
|
|
assert.equal(forbidden.statusCode, 403);
|
|
} finally {
|
|
await prisma.adminUser.delete({ where: { id: ordinaryUser.id } });
|
|
}
|
|
|
|
const templateAdminWithoutMembership = await prisma.adminUser.create({
|
|
data: {
|
|
username: `metrics-platform-${randomUUID()}`,
|
|
passwordHash: "unused",
|
|
displayName: "平台模板管理员",
|
|
platformTemplateRole: "template_admin",
|
|
mustChangePassword: false,
|
|
},
|
|
});
|
|
try {
|
|
const response = await request("/admin/template-operations/failures", {
|
|
headers: {
|
|
authorization: `Bearer ${signIdentity({
|
|
subject: templateAdminWithoutMembership.id,
|
|
brandId: "00000000-0000-0000-0000-000000000000",
|
|
role: "admin",
|
|
})}`,
|
|
},
|
|
});
|
|
assert.equal(response.statusCode, 200, response.body);
|
|
} finally {
|
|
await prisma.adminUser.delete({ where: { id: templateAdminWithoutMembership.id } });
|
|
}
|
|
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
|
});
|
|
assert.equal(login.statusCode, 201);
|
|
const adminHeaders = { authorization: `Bearer ${JSON.parse(login.body).token}` };
|
|
const now = Date.now();
|
|
const recentRequestId = `metrics-${randomUUID()}`;
|
|
await prisma.templateOperationFailureEvent.createMany({
|
|
data: [
|
|
{
|
|
action: "preview",
|
|
resultCode: "HTTP_409",
|
|
requestId: recentRequestId,
|
|
actorId: "metrics-test-actor",
|
|
brandId,
|
|
packageKey: "metrics-test-package",
|
|
version: "1.0.0",
|
|
createdAt: new Date(now - 1000),
|
|
},
|
|
{
|
|
action: "preview",
|
|
resultCode: "HTTP_400",
|
|
createdAt: new Date(now - 2 * 24 * 60 * 60 * 1000),
|
|
},
|
|
{
|
|
action: "import",
|
|
resultCode: "HTTP_400",
|
|
createdAt: new Date(now - 200 * 24 * 60 * 60 * 1000),
|
|
},
|
|
],
|
|
});
|
|
const invalidWindow = await request("/admin/template-operations/failures?days=91", {
|
|
headers: adminHeaders,
|
|
});
|
|
assert.equal(invalidWindow.statusCode, 400);
|
|
const response = await request("/admin/template-operations/failures?days=1", {
|
|
headers: adminHeaders,
|
|
});
|
|
assert.equal(response.statusCode, 200, response.body);
|
|
const report = JSON.parse(response.body);
|
|
assert.equal(report.days, 1);
|
|
assert.equal(report.backfilled, false);
|
|
assert.equal(report.failures.find((item) => item.action === "preview").count, 1);
|
|
assert.equal(report.failures.find((item) => item.action === "import").count, 0);
|
|
assert.equal(report.failures.find((item) => item.action === "build").count, 0);
|
|
assert.equal(JSON.stringify(report).includes(recentRequestId), false);
|
|
assert.deepEqual(Object.keys(report.failures[0]).sort(), ["action", "count"]);
|
|
});
|
|
|
|
test("平台模板管理员可以按行业预览版本,且预览不写入品牌数据", async () => {
|
|
const missing = await request("/admin/templates/preview-version/preview?industry=personal");
|
|
assert.equal(missing.statusCode, 401);
|
|
const customer = await request("/admin/templates/preview-version/preview?industry=personal", {
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
});
|
|
assert.equal(customer.statusCode, 403);
|
|
const invalid = await request("/admin/templates/preview-version/preview?industry=personal", {
|
|
headers: { authorization: "Bearer invalid-preview-token" },
|
|
});
|
|
assert.equal(invalid.statusCode, 401);
|
|
const ordinaryUser = await prisma.adminUser.create({
|
|
data: {
|
|
username: `preview-viewer-${randomUUID()}`,
|
|
passwordHash: "unused",
|
|
displayName: "品牌管理员",
|
|
platformTemplateRole: "none",
|
|
},
|
|
});
|
|
try {
|
|
const ordinary = await request("/admin/templates/preview-version/preview?industry=personal", {
|
|
headers: {
|
|
authorization: `Bearer ${signIdentity({ subject: ordinaryUser.id, brandId, role: "admin" })}`,
|
|
},
|
|
});
|
|
assert.equal(ordinary.statusCode, 403);
|
|
} finally {
|
|
await prisma.adminUser.delete({ where: { id: ordinaryUser.id } });
|
|
}
|
|
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
|
});
|
|
assert.equal(login.statusCode, 201);
|
|
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
|
|
const invalidArchive = createTemplateArchive("atelier-solopreneur", (manifest) => {
|
|
manifest.previewFixture.personal.safety.submissions = "enabled";
|
|
});
|
|
const invalidMultipart = multipartArchive(invalidArchive);
|
|
const versionCount = await prisma.templatePackageVersion.count();
|
|
const rejectedImport = await request("/admin/templates/import", {
|
|
method: "POST",
|
|
headers: { ...headers, ...invalidMultipart.headers },
|
|
rawPayload: invalidMultipart.payload,
|
|
});
|
|
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,
|
|
});
|
|
assert.equal(imported.statusCode, 201);
|
|
const versionId = JSON.parse(imported.body).version.id;
|
|
|
|
const businessCounts = () =>
|
|
Promise.all([
|
|
prisma.brandProfile.count(),
|
|
prisma.offering.count(),
|
|
prisma.trustContent.count(),
|
|
prisma.inquiryForm.count(),
|
|
prisma.brandRelease.count(),
|
|
prisma.customerUser.count(),
|
|
prisma.inquirySubmission.count(),
|
|
prisma.brandTemplateInstallation.count(),
|
|
]);
|
|
const before = await businessCounts();
|
|
const preview = await request(`/admin/templates/${versionId}/preview?industry=personal`, {
|
|
headers: { ...headers, "x-request-id": "independent-template-preview" },
|
|
});
|
|
assert.equal(preview.statusCode, 200, preview.body);
|
|
const body = JSON.parse(preview.body);
|
|
assert.equal(body.template.id, versionId);
|
|
assert.equal(body.industry.key, "personal");
|
|
assert.equal(body.workspace.publication.status, "draft");
|
|
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(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");
|
|
assert.equal(body.workspace.brand.name, "独立工坊 · 演示品牌");
|
|
assert.equal(body.workspace.brand.founder, "林予 · 示例主理人");
|
|
assert.equal(body.workspace.brand.contactPhone, null);
|
|
assert.equal(body.preview.safety.submissions, "disabled");
|
|
assert.ok(body.preview.pages.find((page) => page.key === "home").modules.length > 0);
|
|
assert.ok(
|
|
body.preview.assets.some(
|
|
(asset) => asset.binding === "brand.avatarUrl" && asset.status === "ready",
|
|
),
|
|
);
|
|
assert.ok(
|
|
body.preview.assets.some(
|
|
(asset) => asset.binding === "offering.coverUrl" && asset.status === "ready",
|
|
),
|
|
);
|
|
assert.match(body.preview.assetFiles["/assets/avatar.jpg"].dataUrl, /^data:image\/jpeg;base64,/);
|
|
assert.match(body.preview.assetFiles["/assets/avatar.jpg"].sha256, /^[a-f0-9]{64}$/);
|
|
assert.match(
|
|
body.preview.assetFiles["/assets/cases/campus.jpg"].dataUrl,
|
|
/^data:image\/jpeg;base64,/,
|
|
);
|
|
assert.match(body.preview.assetFiles["/assets/cases/campus.jpg"].sha256, /^[a-f0-9]{64}$/);
|
|
const previewAudit = await request(`/admin/templates/${versionId}/audit`, { headers });
|
|
assert.equal(previewAudit.statusCode, 200);
|
|
const event = JSON.parse(previewAudit.body).find((entry) => entry.action === "previewed");
|
|
assert.equal(event.requestId, "independent-template-preview");
|
|
assert.deepEqual(event.metadata, {
|
|
industry: "personal",
|
|
contentChecksum: body.template.contentChecksum,
|
|
fixtureSource: "previewFixture",
|
|
});
|
|
assert.ok(event.actor.id);
|
|
|
|
// Preview session 只复用同一管理员、同一版本和行业的已构建投影;复用不产生第二条预览审计。
|
|
assert.match(body.preview.session.token, /^[a-f0-9]{64}$/);
|
|
const anotherTemplateAdmin = await prisma.adminUser.create({
|
|
data: {
|
|
username: `preview-session-${randomUUID()}`,
|
|
passwordHash: "unused",
|
|
displayName: "另一位模板管理员",
|
|
platformTemplateRole: "template_admin",
|
|
},
|
|
});
|
|
const anotherHeaders = {
|
|
authorization: `Bearer ${signIdentity({
|
|
subject: anotherTemplateAdmin.id,
|
|
brandId,
|
|
role: "admin",
|
|
})}`,
|
|
};
|
|
try {
|
|
const auditCount = await prisma.templatePackageAuditLog.count({
|
|
where: { templatePackageVersionId: versionId, action: "previewed" },
|
|
});
|
|
const mismatchedActor = await request(
|
|
`/admin/templates/${versionId}/preview?industry=personal&session=${body.preview.session.token}`,
|
|
{ headers: anotherHeaders },
|
|
);
|
|
assert.equal(mismatchedActor.statusCode, 400, mismatchedActor.body);
|
|
assert.match(JSON.parse(mismatchedActor.body).error.message, /不匹配/);
|
|
const reused = await request(
|
|
`/admin/templates/${versionId}/preview?industry=personal&session=${body.preview.session.token}`,
|
|
{ headers },
|
|
);
|
|
assert.equal(reused.statusCode, 200, reused.body);
|
|
const reusedBody = JSON.parse(reused.body);
|
|
assert.equal(reusedBody.preview.session.token, body.preview.session.token);
|
|
assert.deepEqual(reusedBody.workspace.brand, body.workspace.brand);
|
|
assert.equal(
|
|
await prisma.templatePackageAuditLog.count({
|
|
where: { templatePackageVersionId: versionId, action: "previewed" },
|
|
}),
|
|
auditCount,
|
|
);
|
|
const unknownSession = await request(
|
|
`/admin/templates/${versionId}/preview?industry=personal&session=${"0".repeat(64)}`,
|
|
{ headers },
|
|
);
|
|
assert.equal(unknownSession.statusCode, 400, unknownSession.body);
|
|
assert.match(JSON.parse(unknownSession.body).error.message, /不存在或已过期/);
|
|
} finally {
|
|
await prisma.adminUser.delete({ where: { id: anotherTemplateAdmin.id } });
|
|
}
|
|
|
|
const stored = await prisma.templatePackageVersion.findUniqueOrThrow({
|
|
where: { id: versionId },
|
|
});
|
|
const failures = [
|
|
[{ ...stored.manifestSnapshot, previewFixture: {} }, /previewFixture/],
|
|
[{ ...stored.manifestSnapshot, previewFixture: { personal: null } }, /previewFixture/],
|
|
[
|
|
{
|
|
...stored.manifestSnapshot,
|
|
previewFixture: {
|
|
personal: {
|
|
...stored.manifestSnapshot.previewFixture.personal,
|
|
safety: { submissions: "enabled" },
|
|
},
|
|
},
|
|
},
|
|
/previewFixture/,
|
|
],
|
|
[
|
|
{
|
|
...stored.manifestSnapshot,
|
|
previewFixture: {
|
|
personal: {
|
|
...stored.manifestSnapshot.previewFixture.personal,
|
|
brand: {
|
|
...stored.manifestSnapshot.previewFixture.personal.brand,
|
|
contactPhone: "13800000000",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
/previewFixture/,
|
|
],
|
|
[
|
|
{
|
|
...stored.manifestSnapshot,
|
|
previewFixture: {
|
|
personal: {
|
|
...stored.manifestSnapshot.previewFixture.personal,
|
|
content: {
|
|
...stored.manifestSnapshot.previewFixture.personal.content,
|
|
templateKey: "food",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
/所属行业|must match its key/,
|
|
],
|
|
[{ ...stored.manifestSnapshot, requiredCapabilities: ["unknown"] }, /未注册的 capability/],
|
|
[
|
|
{ ...stored.manifestSnapshot, visualTemplateKey: "unknown" },
|
|
/visualTemplateKey must match packageKey|元数据/,
|
|
],
|
|
[{ ...stored.manifestSnapshot, runtimeContract: "9.0" }, /契约/],
|
|
[{ ...stored.manifestSnapshot, dataSlots: [null] }, /契约/],
|
|
[{ ...stored.manifestSnapshot, navigation: [null] }, /契约/],
|
|
[{ ...stored.manifestSnapshot, trustContentTypes: {} }, /契约/],
|
|
[{ ...stored.manifestSnapshot, templateFields: [null] }, /契约/],
|
|
[{ ...stored.manifestSnapshot, admin: { sections: [{ fields: [null] }] } }, /契约/],
|
|
];
|
|
try {
|
|
await prisma.templatePackageVersion.update({
|
|
where: { id: versionId },
|
|
data: { archiveChecksum: "0".repeat(64) },
|
|
});
|
|
const corrupt = await request(`/admin/templates/${versionId}/preview?industry=personal`, {
|
|
headers,
|
|
});
|
|
assert.equal(corrupt.statusCode, 409, corrupt.body);
|
|
assert.match(JSON.parse(corrupt.body).error.message, /摘要不一致/);
|
|
await prisma.templatePackageVersion.update({
|
|
where: { id: versionId },
|
|
data: { archiveChecksum: stored.archiveChecksum },
|
|
});
|
|
// 独立演示内容不依赖 bootstrap sampleContent。
|
|
await prisma.templatePackageVersion.update({
|
|
where: { id: versionId },
|
|
data: { manifestSnapshot: { ...stored.manifestSnapshot, sampleContent: {} } },
|
|
});
|
|
const independent = await request(`/admin/templates/${versionId}/preview?industry=personal`, {
|
|
headers,
|
|
});
|
|
assert.equal(independent.statusCode, 200, independent.body);
|
|
assert.equal(JSON.parse(independent.body).workspace.brand.founder, "林予 · 示例主理人");
|
|
const legacyManifest = { ...stored.manifestSnapshot };
|
|
delete legacyManifest.previewFixture;
|
|
await prisma.templatePackageVersion.update({
|
|
where: { id: versionId },
|
|
data: { manifestSnapshot: legacyManifest },
|
|
});
|
|
const legacy = await request(`/admin/templates/${versionId}/preview?industry=personal`, {
|
|
headers,
|
|
});
|
|
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 },
|
|
data: { manifestSnapshot },
|
|
});
|
|
const rejected = await request(`/admin/templates/${versionId}/preview?industry=personal`, {
|
|
headers,
|
|
});
|
|
assert.equal(rejected.statusCode, 400, rejected.body);
|
|
assert.match(JSON.parse(rejected.body).error.message, reason);
|
|
}
|
|
} finally {
|
|
await prisma.templatePackageVersion.update({
|
|
where: { id: versionId },
|
|
data: { manifestSnapshot: stored.manifestSnapshot, archiveChecksum: stored.archiveChecksum },
|
|
});
|
|
}
|
|
const noIndustry = await request(`/admin/templates/${versionId}/preview`, { headers });
|
|
assert.equal(noIndustry.statusCode, 400);
|
|
const absent = await request("/admin/templates/missing/preview?industry=personal", { headers });
|
|
assert.equal(absent.statusCode, 400);
|
|
|
|
const incompatible = await request(`/admin/templates/${versionId}/preview?industry=doors`, {
|
|
headers,
|
|
});
|
|
assert.equal(incompatible.statusCode, 400);
|
|
assert.match(JSON.parse(incompatible.body).error.message, /不支持所选行业/);
|
|
assert.deepEqual(await businessCounts(), before);
|
|
|
|
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);
|
|
const retiredPreview = await request(`/admin/templates/${versionId}/preview?industry=personal`, {
|
|
headers,
|
|
});
|
|
assert.equal(retiredPreview.statusCode, 409);
|
|
|
|
// 撤回是目录可见性状态;平台管理员必须能显式恢复已撤回版本。
|
|
const republished = await request(`/admin/templates/${versionId}/publish`, {
|
|
method: "POST",
|
|
headers,
|
|
});
|
|
assert.equal(republished.statusCode, 201, republished.body);
|
|
assert.equal(JSON.parse(republished.body).changed, true);
|
|
assert.equal(JSON.parse(republished.body).version.status, "published");
|
|
const republishedPreview = await request(
|
|
`/admin/templates/${versionId}/preview?industry=personal`,
|
|
{ headers },
|
|
);
|
|
assert.equal(republishedPreview.statusCode, 200, republishedPreview.body);
|
|
});
|
|
|
|
test("admin routes remain guarded when an API prefix is configured", async () => {
|
|
process.env.API_PREFIX = "api";
|
|
try {
|
|
const prefixedApp = await createApp();
|
|
await prefixedApp.init();
|
|
const injected = prefixedApp.getHttpAdapter().getInstance();
|
|
const missingAuth = await injected.inject({ method: "GET", url: "/api/admin/bookings" });
|
|
assert.equal(missingAuth.statusCode, 401);
|
|
const customerAuth = await injected.inject({
|
|
method: "GET",
|
|
url: "/api/admin/bookings",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
});
|
|
assert.equal(customerAuth.statusCode, 403);
|
|
const login = await injected.inject({
|
|
method: "POST",
|
|
url: "/api/admin/session/login",
|
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
|
});
|
|
assert.equal(login.statusCode, 201);
|
|
await prefixedApp.close();
|
|
} finally {
|
|
process.env.API_PREFIX = "";
|
|
}
|
|
});
|
|
|
|
after(async () => {
|
|
await app.close();
|
|
await prisma.brandRelease.deleteMany({ where: { brandId } });
|
|
await prisma.miniAppReleaseTask.deleteMany({ where: { brandId } });
|
|
await prisma.booking.deleteMany({ where: { id: { in: createdBookingIds } } });
|
|
await prisma.customerUser.deleteMany({ where: { openid } });
|
|
await prisma.$disconnect();
|
|
});
|
|
|
|
test("miniapp release tasks are authorized, idempotent, and state checked", async () => {
|
|
const missing = await request("/admin/miniapp-releases");
|
|
assert.equal(missing.statusCode, 401);
|
|
assert.equal(
|
|
(
|
|
await request("/admin/miniapp-releases", {
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
})
|
|
).statusCode,
|
|
403,
|
|
);
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
|
});
|
|
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
|
|
const current = JSON.parse((await request("/admin/releases", { headers })).body).find(
|
|
(item) => item.status === "published",
|
|
);
|
|
assert.ok(current);
|
|
const created = await request("/admin/miniapp-releases", {
|
|
method: "POST",
|
|
headers,
|
|
payload: {},
|
|
});
|
|
assert.equal(created.statusCode, 201);
|
|
assert.equal(JSON.parse(created.body).version, current.version);
|
|
await prisma.miniAppReleaseAttempt.create({
|
|
data: {
|
|
taskId: JSON.parse(created.body).id,
|
|
brandId,
|
|
actorId: "integration-test",
|
|
phase: "build",
|
|
attempt: 1,
|
|
leaseToken: "integration-secret-lease-token",
|
|
leaseExpiresAt: new Date(Date.now() + 60_000),
|
|
},
|
|
});
|
|
const listedAttempts = await request("/admin/miniapp-releases", { headers });
|
|
assert.equal(listedAttempts.statusCode, 200);
|
|
assert.equal(listedAttempts.body.includes("integration-secret-lease-token"), false);
|
|
assert.equal(JSON.parse(listedAttempts.body)[0].attempts[0].phase, "build");
|
|
const repeated = await request("/admin/miniapp-releases", {
|
|
method: "POST",
|
|
headers,
|
|
payload: {},
|
|
});
|
|
assert.equal(JSON.parse(repeated.body).id, JSON.parse(created.body).id);
|
|
const taskId = JSON.parse(created.body).id;
|
|
const skipped = await request(`/admin/miniapp-releases/${taskId}/status`, {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: { status: "published" },
|
|
});
|
|
assert.equal(skipped.statusCode, 409);
|
|
const uploaded = await request(`/admin/miniapp-releases/${taskId}/status`, {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: { status: "uploaded", weappUploadId: "test-upload" },
|
|
});
|
|
assert.equal(uploaded.statusCode, 200);
|
|
assert.equal(JSON.parse(uploaded.body).status, "uploaded");
|
|
assert.equal(JSON.parse(uploaded.body).uploadStatus, "uploaded");
|
|
const underReview = await request(`/admin/miniapp-releases/${taskId}/status`, {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: { status: "under_review" },
|
|
});
|
|
assert.equal(JSON.parse(underReview.body).status, "under_review");
|
|
assert.equal(JSON.parse(underReview.body).reviewStatus, "under_review");
|
|
const approved = await request(`/admin/miniapp-releases/${taskId}/status`, {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: { status: "approved" },
|
|
});
|
|
assert.equal(JSON.parse(approved.body).status, "approved");
|
|
assert.equal(JSON.parse(approved.body).reviewStatus, "approved");
|
|
const published = await request(`/admin/miniapp-releases/${taskId}/status`, {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: { status: "published" },
|
|
});
|
|
assert.equal(JSON.parse(published.body).status, "published");
|
|
|
|
const buildingTask = await prisma.miniAppReleaseTask.create({
|
|
data: {
|
|
brandId,
|
|
version: 900001,
|
|
actorId: "integration-test",
|
|
status: "built",
|
|
buildStatus: "building",
|
|
},
|
|
});
|
|
const busy = await request(`/admin/miniapp-releases/${buildingTask.id}/upload`, {
|
|
method: "POST",
|
|
headers,
|
|
payload: {},
|
|
});
|
|
assert.equal(busy.statusCode, 409);
|
|
await prisma.miniAppReleaseTask.delete({ where: { id: buildingTask.id } });
|
|
});
|
|
|
|
test("API restart recovers an expired persisted miniapp build attempt", async () => {
|
|
const task = await prisma.miniAppReleaseTask.create({
|
|
data: {
|
|
brandId,
|
|
version: 900002,
|
|
actorId: "integration-restart-test",
|
|
status: "built",
|
|
buildStatus: "idle",
|
|
},
|
|
});
|
|
try {
|
|
const runningApi = app.get(AdminMiniAppReleaseService);
|
|
const first = await runningApi.acquireAttempt(
|
|
brandId,
|
|
"integration-restart-test",
|
|
task.id,
|
|
"build",
|
|
);
|
|
assert.equal(
|
|
(await prisma.miniAppReleaseAttempt.findUniqueOrThrow({ where: { id: first.id } })).status,
|
|
"running",
|
|
);
|
|
|
|
await app.close();
|
|
await prisma.miniAppReleaseAttempt.update({
|
|
where: { id: first.id },
|
|
data: { leaseExpiresAt: new Date(Date.now() - 1_000) },
|
|
});
|
|
app = await createApp();
|
|
await app.init();
|
|
|
|
const restartedApi = app.get(AdminMiniAppReleaseService);
|
|
const recovered = await restartedApi.acquireAttempt(
|
|
brandId,
|
|
"integration-restart-test",
|
|
task.id,
|
|
"build",
|
|
);
|
|
const attempts = await prisma.miniAppReleaseAttempt.findMany({
|
|
where: { taskId: task.id, phase: "build" },
|
|
orderBy: { attempt: "asc" },
|
|
});
|
|
assert.equal(recovered.attempt, 2);
|
|
assert.equal(attempts[0].status, "timed_out");
|
|
assert.equal(attempts[1].status, "running");
|
|
assert.equal(
|
|
(await prisma.miniAppReleaseTask.findUniqueOrThrow({ where: { id: task.id } })).buildStatus,
|
|
"building",
|
|
);
|
|
} finally {
|
|
await prisma.miniAppReleaseTask.delete({ where: { id: task.id } });
|
|
}
|
|
});
|
|
|
|
test("miniapp release settings never expose or persist plaintext private keys", async () => {
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
|
});
|
|
const headers = { authorization: `Bearer ${JSON.parse(login.body).token}` };
|
|
const { generateKeyPairSync } = await import("node:crypto");
|
|
const privateKey = generateKeyPairSync("rsa", {
|
|
modulusLength: 2048,
|
|
privateKeyEncoding: { type: "pkcs8", format: "pem" },
|
|
publicKeyEncoding: { type: "spki", format: "pem" },
|
|
}).privateKey;
|
|
const invalid = await request("/admin/miniapp-releases/settings", {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: {
|
|
appId: "wxtestsettings",
|
|
privateKey: "-----BEGIN PRIVATE KEY-----\nMIIB\n-----END PRIVATE KEY-----",
|
|
},
|
|
});
|
|
assert.equal(invalid.statusCode, 400);
|
|
const rejected = await request("/admin/miniapp-releases/settings", {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: { appId: "wxtestsettings", apiBaseUrl: "http://wechat.example.com/api" },
|
|
});
|
|
assert.equal(rejected.statusCode, 400);
|
|
const saved = await request("/admin/miniapp-releases/settings", {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: {
|
|
appId: "wxtestsettings",
|
|
apiBaseUrl: "https://wechat.example.com/api/",
|
|
privateKey,
|
|
},
|
|
});
|
|
assert.equal(saved.statusCode, 200);
|
|
const body = JSON.parse(saved.body);
|
|
assert.equal(body.appId, "wxtestsettings");
|
|
assert.equal(body.apiBaseUrl, "https://wechat.example.com/api");
|
|
assert.equal(body.requestDomain, "wechat.example.com");
|
|
assert.equal(body.hasStoredCredentials, true);
|
|
assert.equal(body.privateKey, undefined);
|
|
assert.equal(body.credential?.algorithm, "aes-256-gcm");
|
|
assert.ok(body.requestDomain === null || typeof body.requestDomain === "string");
|
|
assert.ok(body.buildError === null || typeof body.buildError === "string");
|
|
if (typeof body.requestDomain === "string") assert.ok(!body.requestDomain.includes("localhost"));
|
|
const brand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
|
|
const credential = brand.miniAppSettings?.credential;
|
|
assert.ok(credential);
|
|
assert.equal(brand.miniAppSettings.apiBaseUrl, "https://wechat.example.com/api");
|
|
assert.equal(typeof credential.ciphertext, "string");
|
|
assert.ok(!JSON.stringify(brand.miniAppSettings).includes(privateKey));
|
|
const missing = await request("/admin/miniapp-releases/settings");
|
|
assert.equal(missing.statusCode, 401);
|
|
const forbidden = await request("/admin/miniapp-releases/settings", {
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
});
|
|
assert.equal(forbidden.statusCode, 403);
|
|
});
|
|
|
|
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 originalPublicWorkspace = JSON.parse(
|
|
(await request("/public/workspace?brandSlug=" + slug)).body,
|
|
);
|
|
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 unpublishedWorkspace = JSON.parse(
|
|
(await request("/public/workspace?brandSlug=" + slug)).body,
|
|
);
|
|
for (const key of ["brand", "templateData", "offerings", "trustItems", "trustPresentation"])
|
|
assert.deepEqual(
|
|
unpublishedWorkspace[key],
|
|
originalPublicWorkspace[key],
|
|
slug + " unpublished edits must preserve public " + key,
|
|
);
|
|
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");
|
|
const user = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
|
|
const headers = {
|
|
authorization: `Bearer ${signIdentity({ subject: user.id, brandId, role: "admin" })}`,
|
|
};
|
|
const records = await prisma.trustContent.findMany({
|
|
where: {
|
|
brandId,
|
|
type: { in: ["schedule", "coverage", "process", "credential", "case", "promise"] },
|
|
isPublished: true,
|
|
},
|
|
});
|
|
const latest = await prisma.brandRelease.findFirstOrThrow({
|
|
where: { brandId },
|
|
orderBy: { version: "desc" },
|
|
});
|
|
const before = JSON.parse((await request("/public/workspace")).body);
|
|
try {
|
|
for (const item of records) {
|
|
const url = `/admin/config/trust-content/${item.id}`;
|
|
assert.equal(
|
|
(await request(url, { method: "PATCH", payload: { config: {} } })).statusCode,
|
|
401,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await request(url, {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: { config: {} },
|
|
})
|
|
).statusCode,
|
|
403,
|
|
);
|
|
assert.equal(
|
|
(await request(url, { method: "PATCH", headers, payload: { config: "invalid" } }))
|
|
.statusCode,
|
|
400,
|
|
);
|
|
const config = { ...item.config };
|
|
if (item.type === "schedule") {
|
|
config.weekdayDetail = "测试工作日地点";
|
|
config.weekendDetail = "测试周末地点";
|
|
}
|
|
if (item.type === "coverage") {
|
|
config.pickupDetail = "测试自取说明";
|
|
config.deliveryDetail = "测试配送说明";
|
|
}
|
|
if (item.type === "process")
|
|
config.steps = [{ title: "测试第一步", detail: "测试步骤说明" }, ...config.steps.slice(1)];
|
|
if (item.type === "credential")
|
|
config.standards = [{ title: "编辑后的卫生标准", detail: "编辑后的说明" }];
|
|
if (item.type === "case")
|
|
config.entries = [
|
|
{ badge: "测", title: "编辑后的合作案例", detail: "编辑后的交付", result: "完成" },
|
|
];
|
|
if (item.type === "promise")
|
|
config.commitments = [
|
|
{ label: "测试时段", detail: "编辑后的回复说明", highlight: "30 分钟内" },
|
|
];
|
|
assert.equal(
|
|
(
|
|
await request(url, {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: {
|
|
content: ["schedule", "coverage", "process"].includes(item.type) ? "" : item.content,
|
|
config,
|
|
},
|
|
})
|
|
).statusCode,
|
|
200,
|
|
);
|
|
}
|
|
assert.deepEqual(
|
|
JSON.parse((await request("/public/workspace")).body).trustItems,
|
|
before.trustItems,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await request("/admin/releases/publish", {
|
|
method: "POST",
|
|
headers,
|
|
payload: { note: "结构化页面集成测试" },
|
|
})
|
|
).statusCode,
|
|
201,
|
|
);
|
|
const workspace = JSON.parse((await request("/public/workspace")).body);
|
|
let page;
|
|
runInNewContext(
|
|
readFileSync(
|
|
new URL(
|
|
"../../../packages/template-acheng-campus-food/miniapp/pages/stall-service/index.js",
|
|
import.meta.url,
|
|
),
|
|
"utf8",
|
|
),
|
|
{
|
|
Page(value) {
|
|
page = value;
|
|
},
|
|
require(name) {
|
|
return name.includes("runtime-workspace")
|
|
? { loadWorkspaceWithFallback: () => Promise.resolve(workspace) }
|
|
: { openPage() {} };
|
|
},
|
|
},
|
|
);
|
|
page.setData = (data) => Object.assign(page.data, data);
|
|
await page.load();
|
|
assert.equal(page.data.schedule.rows.length, 2);
|
|
assert.equal(page.data.schedule.rows[0].detail, "测试工作日地点");
|
|
assert.equal(page.data.schedule.rows[1].detail, "测试周末地点");
|
|
assert.equal(page.data.coverage.config.pickupDetail, "测试自取说明");
|
|
assert.equal(page.data.coverage.config.deliveryDetail, "测试配送说明");
|
|
assert.equal(page.data.process.steps.length, 4);
|
|
assert.equal(page.data.process.steps[0].detail, "测试步骤说明");
|
|
let owner;
|
|
runInNewContext(
|
|
readFileSync(
|
|
new URL(
|
|
"../../../packages/template-acheng-campus-food/miniapp/pages/bookings/index.js",
|
|
import.meta.url,
|
|
),
|
|
"utf8",
|
|
),
|
|
{
|
|
Page(value) {
|
|
owner = value;
|
|
},
|
|
require(name) {
|
|
return name.includes("runtime-workspace")
|
|
? { loadWorkspaceWithFallback: () => Promise.resolve(workspace) }
|
|
: {};
|
|
},
|
|
},
|
|
);
|
|
owner.setData = (data) => Object.assign(owner.data, data);
|
|
owner.onLoad();
|
|
await new Promise((resolve) => setImmediate(resolve));
|
|
assert.equal(owner.data.credentials[0].config.standards[0].title, "编辑后的卫生标准");
|
|
assert.equal(owner.data.cases[0].entries[0].result, "完成");
|
|
assert.equal(owner.data.promises[0].config.commitments[0].highlight, "30 分钟内");
|
|
assert.ok(workspace.trustItems.every((item) => typeof item.summary === "string"));
|
|
assert.ok(workspace.trustItems.every((item) => typeof item.id === "string"));
|
|
assert.equal(
|
|
new Set(workspace.trustItems.map((item) => item.id)).size,
|
|
workspace.trustItems.length,
|
|
);
|
|
const schedule = records.find((item) => item.type === "schedule");
|
|
await request(`/admin/config/trust-content/${schedule.id}`, {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: { config: {} },
|
|
});
|
|
const blocked = await request("/admin/releases/publish", {
|
|
method: "POST",
|
|
headers,
|
|
payload: {},
|
|
});
|
|
assert.equal(blocked.statusCode, 400);
|
|
await prisma.trustContent.update({
|
|
where: { id: schedule.id },
|
|
data: { config: schedule.config },
|
|
});
|
|
const duplicate = await prisma.trustContent.create({
|
|
data: {
|
|
brandId,
|
|
type: "schedule",
|
|
title: "重复公开日程",
|
|
content: "",
|
|
config: schedule.config,
|
|
isPublished: true,
|
|
},
|
|
});
|
|
try {
|
|
const duplicateReadiness = JSON.parse(
|
|
(await request("/admin/releases/readiness", { headers })).body,
|
|
);
|
|
assert.equal(
|
|
duplicateReadiness.checks.find((check) => check.key === "trust:schedule").passed,
|
|
false,
|
|
);
|
|
assert.equal(
|
|
(await request("/admin/releases/publish", { method: "POST", headers, payload: {} }))
|
|
.statusCode,
|
|
400,
|
|
);
|
|
} finally {
|
|
await prisma.trustContent.delete({ where: { id: duplicate.id } });
|
|
}
|
|
} finally {
|
|
for (const item of records)
|
|
await prisma.trustContent.update({
|
|
where: { id: item.id },
|
|
data: { config: item.config, content: item.content },
|
|
});
|
|
await prisma.brandRelease.deleteMany({ where: { brandId, version: { gt: latest.version } } });
|
|
await prisma.brandRelease.update({ where: { id: latest.id }, data: { status: latest.status } });
|
|
}
|
|
});
|
|
|
|
test("admin release lifecycle is authorized, brand-scoped, and versioned", async () => {
|
|
const missing = await request("/admin/releases");
|
|
assert.equal(missing.statusCode, 401);
|
|
assert.equal((await request("/admin/releases/readiness")).statusCode, 401);
|
|
|
|
const customer = await request("/admin/releases", {
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
});
|
|
assert.equal(customer.statusCode, 403);
|
|
assert.equal(
|
|
(
|
|
await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
})
|
|
).statusCode,
|
|
403,
|
|
);
|
|
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
|
});
|
|
assert.equal(login.statusCode, 201);
|
|
const adminToken = JSON.parse(login.body).token;
|
|
const readiness = await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
});
|
|
assert.equal(readiness.statusCode, 200);
|
|
assert.equal(JSON.parse(readiness.body).ready, true);
|
|
const adminUser = await prisma.adminUser.findUniqueOrThrow({
|
|
where: { username: "admin" },
|
|
select: { id: true },
|
|
});
|
|
const doorsAdminToken = signIdentity({
|
|
subject: adminUser.id,
|
|
brandId: "00000000-0000-0000-0000-000000000002",
|
|
role: "admin",
|
|
});
|
|
const doorsReadiness = await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${doorsAdminToken}` },
|
|
});
|
|
assert.equal(doorsReadiness.statusCode, 200);
|
|
assert.equal(
|
|
JSON.parse(doorsReadiness.body).checks.find((check) => check.key === "forms")?.passed,
|
|
true,
|
|
);
|
|
const doorsReadinessBody = JSON.parse(doorsReadiness.body);
|
|
assert.equal(
|
|
doorsReadinessBody.checks.find((check) => check.key === "trust:process")?.passed,
|
|
true,
|
|
);
|
|
assert.equal(
|
|
doorsReadinessBody.checks.find((check) => check.key === "trust:credential")?.passed,
|
|
true,
|
|
);
|
|
assert.equal(
|
|
doorsReadinessBody.checks.some((check) => check.key === "trust:schedule"),
|
|
false,
|
|
);
|
|
const doorsProcessTrust = await prisma.trustContent.findFirstOrThrow({
|
|
where: { brandId: "00000000-0000-0000-0000-000000000002", type: "process", isPublished: true },
|
|
});
|
|
const originalDoorsProcessTrust = {
|
|
isPublished: doorsProcessTrust.isPublished,
|
|
title: doorsProcessTrust.title,
|
|
content: doorsProcessTrust.content,
|
|
};
|
|
try {
|
|
await prisma.trustContent.update({
|
|
where: { id: doorsProcessTrust.id },
|
|
data: { isPublished: false },
|
|
});
|
|
const unpublishedDoors = JSON.parse(
|
|
(
|
|
await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${doorsAdminToken}` },
|
|
})
|
|
).body,
|
|
);
|
|
assert.equal(unpublishedDoors.ready, false);
|
|
assert.equal(
|
|
unpublishedDoors.checks.find((check) => check.key === "trust:process")?.passed,
|
|
false,
|
|
);
|
|
await prisma.trustContent.update({
|
|
where: { id: doorsProcessTrust.id },
|
|
data: { isPublished: true, title: " " },
|
|
});
|
|
const blankDoorsTitle = JSON.parse(
|
|
(
|
|
await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${doorsAdminToken}` },
|
|
})
|
|
).body,
|
|
);
|
|
assert.equal(blankDoorsTitle.ready, false);
|
|
assert.equal(
|
|
blankDoorsTitle.checks.find((check) => check.key === "trust:process")?.passed,
|
|
false,
|
|
);
|
|
await prisma.trustContent.update({
|
|
where: { id: doorsProcessTrust.id },
|
|
data: { title: originalDoorsProcessTrust.title, content: " \n " },
|
|
});
|
|
const blankDoorsContent = JSON.parse(
|
|
(
|
|
await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${doorsAdminToken}` },
|
|
})
|
|
).body,
|
|
);
|
|
assert.equal(blankDoorsContent.ready, false);
|
|
assert.equal(
|
|
blankDoorsContent.checks.find((check) => check.key === "trust:process")?.passed,
|
|
false,
|
|
);
|
|
await prisma.trustContent.update({
|
|
where: { id: doorsProcessTrust.id },
|
|
data: originalDoorsProcessTrust,
|
|
});
|
|
const restoredDoors = JSON.parse(
|
|
(
|
|
await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${doorsAdminToken}` },
|
|
})
|
|
).body,
|
|
);
|
|
assert.equal(restoredDoors.checks.find((check) => check.key === "trust:process")?.passed, true);
|
|
} finally {
|
|
await prisma.trustContent.update({
|
|
where: { id: doorsProcessTrust.id },
|
|
data: originalDoorsProcessTrust,
|
|
});
|
|
}
|
|
const doorsCredentialTrust = await prisma.trustContent.findFirstOrThrow({
|
|
where: {
|
|
brandId: "00000000-0000-0000-0000-000000000002",
|
|
type: "credential",
|
|
isPublished: true,
|
|
},
|
|
});
|
|
const originalDoorsCredentialTrust = {
|
|
isPublished: doorsCredentialTrust.isPublished,
|
|
title: doorsCredentialTrust.title,
|
|
content: doorsCredentialTrust.content,
|
|
};
|
|
try {
|
|
await prisma.trustContent.update({
|
|
where: { id: doorsCredentialTrust.id },
|
|
data: { isPublished: false },
|
|
});
|
|
const missingDoorsCredential = JSON.parse(
|
|
(
|
|
await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${doorsAdminToken}` },
|
|
})
|
|
).body,
|
|
);
|
|
assert.equal(missingDoorsCredential.ready, false);
|
|
assert.equal(
|
|
missingDoorsCredential.checks.find((check) => check.key === "trust:credential")?.passed,
|
|
false,
|
|
);
|
|
await prisma.trustContent.update({
|
|
where: { id: doorsCredentialTrust.id },
|
|
data: { isPublished: true, content: " \n " },
|
|
});
|
|
const blankDoorsCredential = JSON.parse(
|
|
(
|
|
await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${doorsAdminToken}` },
|
|
})
|
|
).body,
|
|
);
|
|
assert.equal(blankDoorsCredential.ready, false);
|
|
assert.equal(
|
|
blankDoorsCredential.checks.find((check) => check.key === "trust:credential")?.passed,
|
|
false,
|
|
);
|
|
} finally {
|
|
await prisma.trustContent.update({
|
|
where: { id: doorsCredentialTrust.id },
|
|
data: originalDoorsCredentialTrust,
|
|
});
|
|
}
|
|
const enabledForms = await prisma.inquiryForm.findMany({
|
|
where: { brandId, isEnabled: true },
|
|
select: { id: true },
|
|
});
|
|
await prisma.inquiryForm.updateMany({ where: { brandId }, data: { isEnabled: false } });
|
|
try {
|
|
const noForms = await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
});
|
|
assert.equal(JSON.parse(noForms.body).ready, false);
|
|
assert.equal(
|
|
JSON.parse(noForms.body).checks.find((check) => check.key === "forms")?.passed,
|
|
false,
|
|
);
|
|
} finally {
|
|
await prisma.inquiryForm.updateMany({
|
|
where: { id: { in: enabledForms.map((form) => form.id) } },
|
|
data: { isEnabled: true },
|
|
});
|
|
}
|
|
const scheduleTrust = await prisma.trustContent.findFirst({
|
|
where: { brandId, type: "schedule", isPublished: true },
|
|
});
|
|
assert.ok(scheduleTrust);
|
|
const originalScheduleTrust = {
|
|
isPublished: scheduleTrust.isPublished,
|
|
title: scheduleTrust.title,
|
|
content: scheduleTrust.content,
|
|
config: scheduleTrust.config,
|
|
};
|
|
try {
|
|
await prisma.trustContent.update({
|
|
where: { id: scheduleTrust.id },
|
|
data: { isPublished: false },
|
|
});
|
|
const missingTrust = await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
});
|
|
const missingTrustBody = JSON.parse(missingTrust.body);
|
|
assert.equal(missingTrustBody.ready, false);
|
|
assert.equal(
|
|
missingTrustBody.checks.find((check) => check.key === "trust:schedule")?.passed,
|
|
false,
|
|
);
|
|
await prisma.trustContent.update({
|
|
where: { id: scheduleTrust.id },
|
|
data: { isPublished: true, title: " " },
|
|
});
|
|
const missingTitle = JSON.parse(
|
|
(
|
|
await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
})
|
|
).body,
|
|
);
|
|
assert.equal(missingTitle.ready, false);
|
|
assert.equal(
|
|
missingTitle.checks.find((check) => check.key === "trust:schedule")?.passed,
|
|
false,
|
|
);
|
|
await prisma.trustContent.update({
|
|
where: { id: scheduleTrust.id },
|
|
data: { title: originalScheduleTrust.title, content: " \n ", config: {} },
|
|
});
|
|
const missingContent = JSON.parse(
|
|
(
|
|
await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
})
|
|
).body,
|
|
);
|
|
assert.equal(missingContent.ready, false);
|
|
assert.equal(
|
|
missingContent.checks.find((check) => check.key === "trust:schedule")?.passed,
|
|
false,
|
|
);
|
|
await prisma.trustContent.update({
|
|
where: { id: scheduleTrust.id },
|
|
data: originalScheduleTrust,
|
|
});
|
|
const validTrust = JSON.parse(
|
|
(
|
|
await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
})
|
|
).body,
|
|
);
|
|
assert.equal(validTrust.checks.find((check) => check.key === "trust:schedule")?.passed, true);
|
|
} finally {
|
|
await prisma.trustContent.update({
|
|
where: { id: scheduleTrust.id },
|
|
data: originalScheduleTrust,
|
|
});
|
|
}
|
|
const originalBrand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
|
|
const originalConfig = originalBrand.config;
|
|
const originalOffering = await prisma.offering.findFirstOrThrow({ where: { brandId } });
|
|
await prisma.brandProfile.update({
|
|
where: { id: brandId },
|
|
data: {
|
|
config: {
|
|
...(originalConfig && typeof originalConfig === "object" ? originalConfig : {}),
|
|
heroImage: "",
|
|
founder: "",
|
|
},
|
|
},
|
|
});
|
|
const missingBrandContent = JSON.parse(
|
|
(
|
|
await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
})
|
|
).body,
|
|
);
|
|
assert.equal(missingBrandContent.ready, false);
|
|
assert.equal(
|
|
missingBrandContent.checks.find((check) => check.key === "asset:brand.stallHero")?.passed,
|
|
false,
|
|
);
|
|
assert.equal(
|
|
missingBrandContent.checks.find((check) => check.key === "content:identity:founder")
|
|
?.destination,
|
|
"/admin/brand",
|
|
);
|
|
assert.match(
|
|
missingBrandContent.checks.find((check) => check.key === "asset:brand.stallHero")?.help,
|
|
/真实摊位/,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await request("/admin/releases/publish", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: {},
|
|
})
|
|
).statusCode,
|
|
400,
|
|
);
|
|
await prisma.brandProfile.update({
|
|
where: { id: brandId },
|
|
data: { config: originalConfig },
|
|
});
|
|
await prisma.offering.update({ where: { id: originalOffering.id }, data: { coverUrl: null } });
|
|
const missingOfferingImage = JSON.parse(
|
|
(
|
|
await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
})
|
|
).body,
|
|
);
|
|
assert.equal(missingOfferingImage.ready, false);
|
|
assert.equal(
|
|
missingOfferingImage.checks.find((check) => check.key === "asset:offering.cover")?.passed,
|
|
false,
|
|
);
|
|
await prisma.offering.update({
|
|
where: { id: originalOffering.id },
|
|
data: { coverUrl: originalOffering.coverUrl },
|
|
});
|
|
await prisma.brandProfile.update({ where: { id: brandId }, data: { tagline: "" } });
|
|
const incomplete = await request("/admin/releases/readiness", {
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
});
|
|
assert.equal(JSON.parse(incomplete.body).ready, false);
|
|
assert.equal(
|
|
(
|
|
await request("/admin/releases/publish", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: {},
|
|
})
|
|
).statusCode,
|
|
400,
|
|
);
|
|
await prisma.brandProfile.update({
|
|
where: { id: brandId },
|
|
data: { tagline: "集成测试待发布标语" },
|
|
});
|
|
const beforePublish = JSON.parse((await request("/public/workspace")).body);
|
|
assert.equal(beforePublish.brand.tagline, originalBrand.tagline);
|
|
const published = await request("/admin/releases/publish", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: { note: "集成测试发布" },
|
|
});
|
|
assert.equal(published.statusCode, 201);
|
|
const first = JSON.parse(published.body);
|
|
assert.equal(first.version, 2);
|
|
assert.equal(first.status, "published");
|
|
assert.equal(
|
|
JSON.parse((await request("/public/workspace")).body).brand.tagline,
|
|
"集成测试待发布标语",
|
|
);
|
|
const draftOnlyForm = await prisma.inquiryForm.create({
|
|
data: {
|
|
brandId,
|
|
name: "未发布的草稿表单",
|
|
fieldsSnapshot: [{ key: "phone", type: "phone", label: "手机", required: true }],
|
|
},
|
|
});
|
|
const draftSubmission = await request("/customer/inquiry-submissions", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: { formId: draftOnlyForm.id, values: { phone: "13871112222" } },
|
|
});
|
|
assert.equal(draftSubmission.statusCode, 400);
|
|
|
|
const listed = await request("/admin/releases", {
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
});
|
|
assert.equal(listed.statusCode, 200);
|
|
assert.equal(JSON.parse(listed.body)[0].version, 2);
|
|
|
|
const concurrent = await Promise.all(
|
|
["并发发布 A", "并发发布 B"].map((note) =>
|
|
request("/admin/releases/publish", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: { note },
|
|
}),
|
|
),
|
|
);
|
|
assert.deepEqual(
|
|
concurrent.map((item) => item.statusCode),
|
|
[201, 201],
|
|
);
|
|
assert.deepEqual(
|
|
concurrent.map((item) => JSON.parse(item.body).version).sort((a, b) => a - b),
|
|
[3, 4],
|
|
);
|
|
|
|
const rolledBack = await request("/admin/releases/1/rollback", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
});
|
|
assert.equal(rolledBack.statusCode, 201);
|
|
assert.equal(JSON.parse(rolledBack.body).version, 5);
|
|
assert.equal(
|
|
JSON.parse((await request("/public/workspace")).body).brand.tagline,
|
|
originalBrand.tagline,
|
|
);
|
|
|
|
const revoked = await request("/admin/releases/revoke", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: {},
|
|
});
|
|
assert.equal(revoked.statusCode, 201);
|
|
assert.equal(JSON.parse(revoked.body).status, "revoked");
|
|
assert.equal(JSON.parse(revoked.body).revokedBy, readIdentity(adminToken).subject);
|
|
const unpublished = JSON.parse((await request("/public/workspace")).body);
|
|
assert.equal(unpublished.publication.status, "unpublished");
|
|
assert.equal(unpublished.brand, null);
|
|
assert.deepEqual(unpublished.offerings, []);
|
|
assert.deepEqual(JSON.parse((await request("/public/offerings")).body), []);
|
|
const revokedSubmission = await request("/customer/inquiry-submissions", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: { formId: draftOnlyForm.id, values: { phone: "13871112222" } },
|
|
});
|
|
assert.equal(revokedSubmission.statusCode, 400);
|
|
const revokedBooking = await request("/customer/bookings", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: {
|
|
requestType: "inquiry",
|
|
customerName: "集成测试客户",
|
|
wechatId: "integration-wechat",
|
|
contactPreference: "wechat",
|
|
},
|
|
});
|
|
assert.equal(revokedBooking.statusCode, 400);
|
|
await prisma.inquiryForm.delete({ where: { id: draftOnlyForm.id } });
|
|
await prisma.brandProfile.update({
|
|
where: { id: brandId },
|
|
data: { tagline: originalBrand.tagline },
|
|
});
|
|
assert.equal((await publishReleaseForTests("恢复集成测试基线")).statusCode, 201);
|
|
});
|
|
|
|
function errorMessage(body) {
|
|
const parsed = JSON.parse(body);
|
|
return parsed?.error?.message ?? parsed?.message ?? "";
|
|
}
|
|
|
|
async function request(url, options = {}) {
|
|
const { rawPayload, ...injectOptions } = options;
|
|
return app
|
|
.getHttpAdapter()
|
|
.getInstance()
|
|
.inject({
|
|
method: "GET",
|
|
url,
|
|
...injectOptions,
|
|
...(rawPayload ? { payload: rawPayload } : {}),
|
|
});
|
|
}
|
|
|
|
async function publishReleaseForTests(note = "集成测试发布") {
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
|
});
|
|
const token = JSON.parse(login.body).token;
|
|
return request("/admin/releases/publish", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { note },
|
|
});
|
|
}
|
|
|
|
test("health and public content are available without authentication", async () => {
|
|
const health = await request("/health");
|
|
assert.equal(health.statusCode, 200);
|
|
assert.deepEqual(JSON.parse(health.body), { status: "ok", service: "personal-brand-api" });
|
|
|
|
const brand = await request("/public/brand");
|
|
assert.equal(brand.statusCode, 200);
|
|
assert.equal(JSON.parse(brand.body).name, "阿成家常菜");
|
|
|
|
const services = await request("/public/offerings");
|
|
assert.equal(services.statusCode, 200);
|
|
assert.ok(JSON.parse(services.body).length >= 3);
|
|
const removedServicesRoute = await request("/public/services");
|
|
assert.equal(removedServicesRoute.statusCode, 404);
|
|
|
|
const workspace = await request("/public/workspace");
|
|
assert.equal(workspace.statusCode, 200);
|
|
const runtime = JSON.parse(workspace.body);
|
|
assert.equal(runtime.schemaVersion, "1.0.0");
|
|
assert.ok(Array.isArray(runtime.navigation.tabs));
|
|
assert.ok(Array.isArray(runtime.offerings));
|
|
assert.ok(Array.isArray(runtime.inquiryForms));
|
|
assert.ok(Array.isArray(runtime.capabilities));
|
|
assert.ok(runtime.theme.colors.background);
|
|
assert.ok(Array.isArray(runtime.plugins));
|
|
const inquiryPlugin = runtime.plugins.find((plugin) => plugin.key === "inquiry");
|
|
assert.ok(inquiryPlugin);
|
|
assert.deepEqual(inquiryPlugin.config, {});
|
|
assert.deepEqual(inquiryPlugin.purposeBindings, ["inquiry"]);
|
|
assert.equal(runtime.brand.founder, "阿成");
|
|
assert.ok(runtime.offerings.every((item) => item.coverUrl));
|
|
assert.ok(runtime.trustPresentation);
|
|
assert.ok(Array.isArray(runtime.trustItems));
|
|
assert.ok(runtime.trustItems.every((item) => item.type && item.title && "config" in item));
|
|
const bySlug = await request("/public/workspace?brandSlug=default-brand");
|
|
assert.equal(bySlug.statusCode, 200);
|
|
assert.equal(JSON.parse(bySlug.body).brand.id, brandId);
|
|
const missingSlug = await request("/public/workspace?brandSlug=missing-brand");
|
|
assert.equal(missingSlug.statusCode, 404);
|
|
});
|
|
|
|
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;
|
|
for (const visual of visuals) {
|
|
const manifest = getVisualTemplateManifest(visual.key);
|
|
const packageManifest = getTemplatePackageManifest(visual.key);
|
|
assert.ok(manifest, `Catalog visual must be installable: ${visual.key}`);
|
|
assert.ok(packageManifest, `Catalog visual must have a package manifest: ${visual.key}`);
|
|
assert.equal(manifest.key, visual.key);
|
|
assert.equal(manifest.key, packageManifest.visualTemplateKey);
|
|
assert.equal(manifest.version, packageManifest.version);
|
|
assert.equal(visual.version, packageManifest.version);
|
|
assert.deepEqual(manifest.supportedIndustryTemplates, visual.supportedIndustryTemplates);
|
|
}
|
|
assert.deepEqual(
|
|
visuals.find((visual) => visual.key === "linjing-editorial").supportedIndustryTemplates,
|
|
["personal", "doors"],
|
|
);
|
|
const incompatiblePreview = await request(
|
|
"/public/templates/preview?industry=food&visual=linjing-editorial",
|
|
);
|
|
assert.equal(incompatiblePreview.statusCode, 400);
|
|
const compatiblePreview = await request(
|
|
"/public/templates/preview?industry=doors&visual=linjing-editorial",
|
|
);
|
|
assert.equal(compatiblePreview.statusCode, 200);
|
|
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 installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
|
|
where: { brandId },
|
|
});
|
|
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 () => {
|
|
const brand = await prisma.brandProfile.findUnique({
|
|
where: { id: brandId },
|
|
select: { templateKey: true, config: true },
|
|
});
|
|
assert.ok(brand);
|
|
const templateKey = brand.templateKey;
|
|
assert.equal(Object.hasOwn(brand.config ?? {}, "visualTemplateKey"), false);
|
|
const installation = await prisma.brandTemplateInstallation.findUnique({
|
|
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);
|
|
const forbidden = await request("/admin/workspace/template/preview", {
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
});
|
|
assert.equal(forbidden.statusCode, 403);
|
|
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
|
});
|
|
const headers = {
|
|
authorization: `Bearer ${JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token}`,
|
|
};
|
|
|
|
try {
|
|
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(installation.previousSnapshots?.length));
|
|
|
|
const otherKey = templateKey === "personal" ? "food" : "personal";
|
|
|
|
// 安装其他行业模板必须被拒绝,且不能改写品牌身份或版本引用。
|
|
const rejected = await request("/admin/workspace/install", {
|
|
method: "POST",
|
|
headers,
|
|
payload: {
|
|
templateKey: otherKey,
|
|
templatePackageVersionId: installation.templatePackageVersionId,
|
|
},
|
|
});
|
|
assert.equal(rejected.statusCode, 400);
|
|
assert.match(errorMessage(rejected.body), /更换行业模板不在本版本范围内/);
|
|
const afterRejected = await prisma.brandProfile.findUnique({
|
|
where: { id: brandId },
|
|
select: { templateKey: true, config: true },
|
|
});
|
|
assert.equal(afterRejected.templateKey, templateKey);
|
|
assert.equal(Object.hasOwn(afterRejected.config ?? {}, "visualTemplateKey"), false);
|
|
|
|
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 } });
|
|
}
|
|
});
|
|
|
|
test("seeded public workspaces keep personal, food, and doors brands isolated", async () => {
|
|
const expected = [
|
|
{
|
|
slug: "default-brand",
|
|
id: "00000000-0000-0000-0000-000000000001",
|
|
templateKey: "food",
|
|
founder: "阿成",
|
|
offeringKind: "package",
|
|
categoryLabel: "套餐",
|
|
},
|
|
{
|
|
slug: "linjing-doors",
|
|
id: "00000000-0000-0000-0000-000000000002",
|
|
templateKey: "doors",
|
|
founder: "林叙安 (Lin XUAN)",
|
|
offeringKind: "product",
|
|
categoryLabel: "入户大门",
|
|
},
|
|
];
|
|
const workspaces = await Promise.all(
|
|
expected.map(async (item) => {
|
|
const response = await request(`/public/workspace?brandSlug=${item.slug}`);
|
|
assert.equal(response.statusCode, 200);
|
|
const workspace = JSON.parse(response.body);
|
|
assert.equal(workspace.brand.id, item.id);
|
|
assert.equal(workspace.template.key, item.templateKey);
|
|
assert.ok(workspace.visualTemplate?.key);
|
|
assert.ok(workspace.visualTemplateManifest?.pages?.length > 0);
|
|
assert.equal(workspace.navigation.tabs.length, item.templateKey === "food" ? 5 : 3);
|
|
assert.equal("templatePackageManifest" in workspace, false);
|
|
assert.equal(workspace.brand.founder, item.founder);
|
|
assert.ok(workspace.trustPresentation);
|
|
assert.ok(workspace.inquiryForms.length > 0);
|
|
assert.ok(workspace.offerings.length > 0);
|
|
assert.ok(workspace.offerings.every((offering) => offering.brandId === undefined));
|
|
assert.ok(
|
|
workspace.offerings.some(
|
|
(offering) =>
|
|
offering.kind === item.offeringKind &&
|
|
offering.presentation?.categoryLabel === item.categoryLabel,
|
|
),
|
|
);
|
|
if (item.templateKey === "doors") {
|
|
assert.ok(workspace.offerings.some((offering) => offering.presentation.series));
|
|
assert.ok(workspace.offerings.some((offering) => offering.presentation.hardware));
|
|
}
|
|
return workspace;
|
|
}),
|
|
);
|
|
assert.equal(new Set(workspaces.map((workspace) => workspace.brand.id)).size, 2);
|
|
});
|
|
|
|
test("public workspace uses brand-scoped capability installations and preserves status", async () => {
|
|
await prisma.capabilityInstallation.deleteMany({ where: { brandId } });
|
|
const installation = await prisma.capabilityInstallation.create({
|
|
data: {
|
|
brandId,
|
|
capabilityKey: "inquiry",
|
|
capabilityVersion: "1.0.0",
|
|
status: "disabled",
|
|
config: { source: "integration-test" },
|
|
},
|
|
});
|
|
try {
|
|
const published = await publishReleaseForTests();
|
|
assert.equal(published.statusCode, 201);
|
|
const response = await request("/public/workspace");
|
|
assert.equal(response.statusCode, 200);
|
|
const body = JSON.parse(response.body);
|
|
assert.deepEqual(body.capabilities, [
|
|
{
|
|
key: "inquiry",
|
|
version: "1.0.0",
|
|
status: "disabled",
|
|
config: { source: "integration-test" },
|
|
metadata: {
|
|
key: "inquiry",
|
|
version: "1.0.0",
|
|
displayName: "通用咨询",
|
|
description: "接收客户的一对一合作咨询。",
|
|
impact: "停用后所有通用咨询表单都无法提交。",
|
|
optional: false,
|
|
disablePolicy: "allowed",
|
|
allowedPages: ["inquiry", "success"],
|
|
requiredModules: ["inquiry", "records", "success-summary"],
|
|
purposeBindings: ["inquiry"],
|
|
entryNavigationKey: "inquiry",
|
|
configFields: [
|
|
{ key: "entryLabel", label: "入口文案", input: "text", required: false },
|
|
{ key: "submitHint", label: "提交提示", input: "text", required: false },
|
|
{ key: "disabledHint", label: "停用提示", input: "text", required: false },
|
|
],
|
|
},
|
|
},
|
|
]);
|
|
assert.notEqual(body.capabilities[0].status, "enabled");
|
|
} finally {
|
|
await prisma.capabilityInstallation.delete({ where: { id: installation.id } });
|
|
}
|
|
});
|
|
|
|
test("admin can update declared capability status with authorization and audit", async () => {
|
|
const unauthorized = await request("/admin/workspace/capabilities/inquiry", {
|
|
method: "PATCH",
|
|
payload: { status: "disabled" },
|
|
});
|
|
assert.equal(unauthorized.statusCode, 401);
|
|
const customerForbidden = await request("/admin/workspace/capabilities/inquiry", {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: { status: "disabled" },
|
|
});
|
|
assert.equal(customerForbidden.statusCode, 403);
|
|
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 updated = await request("/admin/workspace/capabilities/inquiry", {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { status: "disabled", config: { entryLabel: "合作咨询", disabledHint: "咨询已暂停" } },
|
|
});
|
|
assert.equal(updated.statusCode, 200);
|
|
assert.equal(JSON.parse(updated.body).status, "disabled");
|
|
assert.equal(JSON.parse(updated.body).capabilityVersion, "1.0.0");
|
|
const invalidConfig = await request("/admin/workspace/capabilities/inquiry", {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { status: "disabled", config: { unknown: "字段" } },
|
|
});
|
|
assert.equal(invalidConfig.statusCode, 400);
|
|
const saved = await prisma.capabilityInstallation.findUnique({
|
|
where: { brandId_capabilityKey: { brandId, capabilityKey: "inquiry" } },
|
|
});
|
|
assert.deepEqual(saved?.config, { entryLabel: "合作咨询", disabledHint: "咨询已暂停" });
|
|
const audit = await prisma.capabilityAuditLog.findFirst({
|
|
where: { brandId, capabilityKey: "inquiry" },
|
|
orderBy: { createdAt: "desc" },
|
|
});
|
|
assert.ok(audit);
|
|
assert.equal(audit.toStatus, "disabled");
|
|
await prisma.capabilityInstallation.deleteMany({ where: { brandId } });
|
|
await prisma.capabilityAuditLog.deleteMany({ where: { brandId } });
|
|
});
|
|
|
|
test("editor membership can manage brand content but cannot change system settings", 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 identity = readIdentity(token);
|
|
const membership = await prisma.brandMembership.findUnique({
|
|
where: { adminUserId_brandId: { adminUserId: identity.subject, brandId } },
|
|
});
|
|
assert.ok(membership);
|
|
await prisma.brandMembership.update({ where: { id: membership.id }, data: { role: "editor" } });
|
|
try {
|
|
const offerings = await request("/admin/workspace/offerings", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(offerings.statusCode, 200);
|
|
const capabilities = await request("/admin/workspace/capabilities", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(capabilities.statusCode, 403);
|
|
const visualUpdate = await request("/admin/config/brand", {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { config: { visualTemplateKey: "unknown-visual" } },
|
|
});
|
|
assert.equal(visualUpdate.statusCode, 400);
|
|
} finally {
|
|
await prisma.brandMembership.update({
|
|
where: { id: membership.id },
|
|
data: { role: membership.role },
|
|
});
|
|
}
|
|
});
|
|
|
|
test("owner can manage brand members without removing the final owner", 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 identity = readIdentity(token);
|
|
const members = await request("/admin/brands/members", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(members.statusCode, 200);
|
|
const current = JSON.parse(members.body).find((item) => item.adminUserId === identity.subject);
|
|
assert.ok(current);
|
|
const selfDisable = await request(`/admin/brands/members/${current.id}`, {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { isEnabled: false },
|
|
});
|
|
assert.equal(selfDisable.statusCode, 400);
|
|
const created = await request("/admin/brands/members", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: {
|
|
username: `editor-${Date.now()}`,
|
|
displayName: "测试编辑",
|
|
password: "test-password-123",
|
|
role: "editor",
|
|
},
|
|
});
|
|
assert.equal(created.statusCode, 201);
|
|
const guestMembership = JSON.parse(created.body);
|
|
try {
|
|
const updated = await request(`/admin/brands/members/${guestMembership.id}`, {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { isEnabled: false },
|
|
});
|
|
assert.equal(updated.statusCode, 200);
|
|
assert.equal(JSON.parse(updated.body).isEnabled, false);
|
|
} finally {
|
|
await prisma.brandMembership.delete({ where: { id: guestMembership.id } });
|
|
await prisma.adminUser.delete({ where: { id: guestMembership.adminUser.id } });
|
|
}
|
|
});
|
|
|
|
test("manually created member must change the initial password before normal use", async () => {
|
|
const ownerLogin = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
|
});
|
|
const ownerToken = JSON.parse(ownerLogin.body).token;
|
|
const username = `first-login-${Date.now()}`;
|
|
const created = await request("/admin/brands/members", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${ownerToken}` },
|
|
payload: {
|
|
username,
|
|
displayName: "首次登录测试",
|
|
password: "initial-password-123",
|
|
role: "editor",
|
|
},
|
|
});
|
|
assert.equal(created.statusCode, 201);
|
|
const member = JSON.parse(created.body);
|
|
assert.equal(member.adminUser.mustChangePassword, undefined);
|
|
try {
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username, password: "initial-password-123" },
|
|
});
|
|
assert.equal(login.statusCode, 201);
|
|
assert.equal(JSON.parse(login.body).mustChangePassword, true);
|
|
const blocked = await request("/admin/brands/members", {
|
|
headers: { authorization: `Bearer ${JSON.parse(login.body).token}` },
|
|
});
|
|
assert.equal(blocked.statusCode, 403);
|
|
assert.match(errorMessage(blocked.body), /初始密码/);
|
|
const changed = await request("/admin/session/change-password", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${JSON.parse(login.body).token}` },
|
|
payload: { currentPassword: "initial-password-123", newPassword: "updated-password-123" },
|
|
});
|
|
assert.equal(changed.statusCode, 201);
|
|
const updatedLogin = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username, password: "updated-password-123" },
|
|
});
|
|
assert.equal(updatedLogin.statusCode, 201);
|
|
assert.equal(JSON.parse(updatedLogin.body).mustChangePassword, false);
|
|
} finally {
|
|
await prisma.brandMembership.delete({ where: { id: member.id } });
|
|
await prisma.adminUser.delete({ where: { id: member.adminUser.id } });
|
|
}
|
|
});
|
|
|
|
test("admin can install optional quote capability without industry-specific branching", async () => {
|
|
const quoteListUser = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
|
|
const quoteToken = signIdentity({ subject: quoteListUser.id, brandId, role: "admin" });
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
|
});
|
|
const token = JSON.parse(login.body).token;
|
|
const response = await request("/admin/workspace/capabilities/quote-request", {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { status: "enabled", config: { entryLabel: "获取报价", submitHint: "48 小时内回复" } },
|
|
});
|
|
assert.equal(response.statusCode, 200);
|
|
assert.equal(JSON.parse(response.body).capabilityKey, "quote-request");
|
|
assert.equal(JSON.parse(response.body).capabilityVersion, "1.0.0");
|
|
const list = await request("/admin/workspace/capabilities", {
|
|
headers: { authorization: `Bearer ${quoteToken}` },
|
|
});
|
|
assert.equal(
|
|
JSON.parse(list.body).find((item) => item.capabilityKey === "quote-request")?.optional,
|
|
true,
|
|
);
|
|
assert.equal((await publishReleaseForTests()).statusCode, 201);
|
|
const workspace = await request("/public/workspace");
|
|
const quotePlugin = JSON.parse(workspace.body).plugins.find(
|
|
(plugin) => plugin.key === "quote-request",
|
|
);
|
|
assert.ok(quotePlugin);
|
|
assert.deepEqual(quotePlugin.config, { entryLabel: "获取报价", submitHint: "48 小时内回复" });
|
|
await prisma.capabilityInstallation.deleteMany({
|
|
where: { brandId, capabilityKey: "quote-request" },
|
|
});
|
|
await prisma.capabilityAuditLog.deleteMany({
|
|
where: { brandId, capabilityKey: "quote-request" },
|
|
});
|
|
});
|
|
|
|
test("admin capability list includes template defaults and brand overrides", async () => {
|
|
await prisma.capabilityInstallation.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 defaults = await request("/admin/workspace/capabilities", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(defaults.statusCode, 200);
|
|
const defaultBody = JSON.parse(defaults.body);
|
|
assert.ok(
|
|
defaultBody.some(
|
|
(item) =>
|
|
item.capabilityKey === "inquiry" &&
|
|
item.source === "template" &&
|
|
item.optional === false &&
|
|
item.disablePolicy === "allowed" &&
|
|
item.configFields?.some((field) => field.key === "entryLabel"),
|
|
),
|
|
);
|
|
await prisma.capabilityInstallation.create({
|
|
data: {
|
|
brandId,
|
|
capabilityKey: "inquiry",
|
|
capabilityVersion: "1.0.0",
|
|
status: "disabled",
|
|
config: { entryLabel: "品牌自定义咨询" },
|
|
},
|
|
});
|
|
const overrides = await request("/admin/workspace/capabilities", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
const override = JSON.parse(overrides.body).find((item) => item.capabilityKey === "inquiry");
|
|
assert.equal(override.source, "brand");
|
|
assert.equal(override.status, "disabled");
|
|
assert.deepEqual(override.config, { entryLabel: "品牌自定义咨询" });
|
|
await prisma.capabilityInstallation.deleteMany({ where: { brandId } });
|
|
});
|
|
|
|
test("installing another industry template is rejected without drifting brand identity", async () => {
|
|
const originalBrand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: 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 },
|
|
});
|
|
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
|
const headers = { authorization: `Bearer ${token}` };
|
|
try {
|
|
// 品牌身份是 food;装 doors 属于「更换行业模板」,不在本版本范围内。
|
|
const installed = await request("/admin/workspace/install", {
|
|
method: "POST",
|
|
headers,
|
|
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.equal(Object.hasOwn(brandAfter.config ?? {}, "visualTemplateKey"), false);
|
|
assert.deepEqual(
|
|
await prisma.brandTemplateInstallation.findUniqueOrThrow({ where: { brandId } }),
|
|
installationBefore,
|
|
);
|
|
|
|
// 公开运行时仍按品牌身份走 food 模板,没有被 doors 污染。
|
|
const workspace = await request("/public/workspace");
|
|
assert.equal(workspace.statusCode, 200);
|
|
const body = JSON.parse(workspace.body);
|
|
assert.equal(body.template.key, "food");
|
|
assert.equal(body.publication.status, "published");
|
|
|
|
const samplePreview = await request("/admin/workspace/sample-content/preview", { headers });
|
|
assert.equal(samplePreview.statusCode, 200);
|
|
assert.equal(JSON.parse(samplePreview.body).templateKey, originalBrand.templateKey);
|
|
} finally {
|
|
assert.equal(
|
|
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).templateKey,
|
|
originalBrand.templateKey,
|
|
);
|
|
}
|
|
});
|
|
|
|
test("cross template requests are rejected without creating a drifted installation", async () => {
|
|
const originalBrand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: 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 },
|
|
});
|
|
const headers = {
|
|
authorization: `Bearer ${JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token}`,
|
|
};
|
|
try {
|
|
const rejected = await request("/admin/workspace/install", {
|
|
method: "POST",
|
|
headers,
|
|
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.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 {
|
|
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: "示例内容,待品牌主理人完善。" },
|
|
});
|
|
assert.equal(originalBrand?.templateKey, "food");
|
|
const packageVersionId = originalInstallation.templatePackageVersionId;
|
|
assert.ok(packageVersionId);
|
|
await prisma.offering.deleteMany({
|
|
where: {
|
|
brandId,
|
|
name: { in: ["序章·入户门", "庭院·边界门", "室内·静谧门", "一对一门系统设计咨询"] },
|
|
},
|
|
});
|
|
await prisma.trustContent.deleteMany({
|
|
where: { brandId, content: "示例内容,待品牌主理人完善。" },
|
|
});
|
|
await prisma.brandFieldDefinition.deleteMany({ where: { brandId, source: "sample" } });
|
|
await prisma.inquiryForm.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 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");
|
|
assert.equal(JSON.parse(preview.body).willCreateInquiryForm, false);
|
|
assert.equal(await prisma.templateBootstrapImport.count({ where: { brandId } }), 0);
|
|
const missingConfirmation = await request("/admin/workspace/sample-content/import", {
|
|
method: "POST",
|
|
headers,
|
|
payload: { strategy: "missing_only", confirm: false },
|
|
});
|
|
assert.equal(missingConfirmation.statusCode, 400);
|
|
const imported = await request("/admin/workspace/sample-content/import", {
|
|
method: "POST",
|
|
headers,
|
|
payload: {
|
|
templatePackageVersionId: packageVersionId,
|
|
strategy: "missing_only",
|
|
confirm: true,
|
|
},
|
|
});
|
|
assert.equal(imported.statusCode, 201);
|
|
assert.equal(JSON.parse(imported.body).counts.inquiryForms, 0);
|
|
assert.ok(await prisma.inquiryForm.findFirst({ where: { brandId, name: "现有客户表单" } }));
|
|
assert.equal(
|
|
await prisma.templateBootstrapImport.count({ where: { brandId, status: "imported" } }),
|
|
1,
|
|
);
|
|
const duplicate = await request("/admin/workspace/sample-content/import", {
|
|
method: "POST",
|
|
headers,
|
|
payload: {
|
|
templatePackageVersionId: packageVersionId,
|
|
strategy: "missing_only",
|
|
confirm: true,
|
|
},
|
|
});
|
|
assert.equal(duplicate.statusCode, 201);
|
|
assert.equal(JSON.parse(duplicate.body).alreadyImported, true);
|
|
await prisma.offering.deleteMany({
|
|
where: {
|
|
brandId,
|
|
name: { in: ["序章·入户门", "庭院·边界门", "室内·静谧门", "一对一门系统设计咨询"] },
|
|
},
|
|
});
|
|
await prisma.trustContent.deleteMany({
|
|
where: { brandId, content: "示例内容,待品牌主理人完善。" },
|
|
});
|
|
if (originalSampleTrust.length) {
|
|
await prisma.trustContent.createMany({
|
|
data: originalSampleTrust.map(
|
|
({ id: _id, createdAt: _createdAt, updatedAt: _updatedAt, ...item }) => item,
|
|
),
|
|
});
|
|
}
|
|
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(
|
|
({ id: _id, createdAt: _createdAt, updatedAt: _updatedAt, ...item }) => item,
|
|
),
|
|
});
|
|
}
|
|
await prisma.capabilityAuditLog.deleteMany({ where: { brandId, capabilityKey: "doors" } });
|
|
await prisma.templateBootstrapImport.deleteMany({ where: { brandId } });
|
|
assert.deepEqual(
|
|
await prisma.brandTemplateInstallation.findUniqueOrThrow({ where: { brandId } }),
|
|
originalInstallation,
|
|
);
|
|
await prisma.brandProfile.update({
|
|
where: { id: brandId },
|
|
data: { templateKey: originalBrand?.templateKey ?? "food", config: originalBrand?.config },
|
|
});
|
|
});
|
|
|
|
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 } });
|
|
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 before = await request("/admin/workspace");
|
|
assert.equal(before.statusCode, 401);
|
|
const customerAccess = await request("/admin/workspace", {
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
});
|
|
assert.equal(customerAccess.statusCode, 403);
|
|
const originalBrand = await prisma.brandProfile.findUniqueOrThrow({
|
|
where: { id: brandId },
|
|
select: { templateKey: true, config: true },
|
|
});
|
|
const currentTemplateKey = originalBrand.templateKey;
|
|
const crossTemplate = await request("/admin/workspace/install", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
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,
|
|
templatePackageVersionId: originalInstallation.templatePackageVersionId,
|
|
},
|
|
});
|
|
assert.equal(installed.statusCode, 201, installed.body);
|
|
assert.equal(JSON.parse(installed.body).template.key, currentTemplateKey);
|
|
assert.equal(
|
|
JSON.parse(installed.body).visualTemplate.supportedIndustryTemplates.includes(
|
|
currentTemplateKey,
|
|
),
|
|
true,
|
|
);
|
|
assert.equal(
|
|
JSON.parse(installed.body).installation.configSnapshot.packageKey,
|
|
originalInstallation.configSnapshot.packageKey,
|
|
);
|
|
const installedRecord = JSON.parse(installed.body).installation;
|
|
const createdVersionIds = [];
|
|
let historicalReleaseId;
|
|
let historicalFormId;
|
|
let historicalSubmissionId;
|
|
let historicalReleaseSnapshot;
|
|
try {
|
|
const previewUnauthorized = await request("/admin/workspace/template/preview");
|
|
assert.equal(previewUnauthorized.statusCode, 401);
|
|
const preview = await request("/admin/workspace/template/preview", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(preview.statusCode, 200);
|
|
const admin = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
|
|
const latestExistingRelease = await prisma.brandRelease.findFirst({
|
|
where: { brandId },
|
|
orderBy: { version: "desc" },
|
|
});
|
|
assert.ok(
|
|
latestExistingRelease,
|
|
"integration fixture should have a published release snapshot",
|
|
);
|
|
historicalReleaseSnapshot = latestExistingRelease.snapshot;
|
|
const historicalRelease = await prisma.brandRelease.create({
|
|
data: {
|
|
brandId,
|
|
version: latestExistingRelease.version + 1,
|
|
snapshot: historicalReleaseSnapshot,
|
|
actorId: admin.id,
|
|
note: "Phase 6 历史快照回归",
|
|
},
|
|
});
|
|
historicalReleaseId = historicalRelease.id;
|
|
const historicalForm = await prisma.inquiryForm.create({
|
|
data: {
|
|
brandId,
|
|
name: "Phase 6 历史咨询表单",
|
|
fieldsSnapshot: [{ key: "message", label: "留言", type: "text", required: true }],
|
|
},
|
|
});
|
|
historicalFormId = historicalForm.id;
|
|
const historicalSubmission = await prisma.inquirySubmission.create({
|
|
data: {
|
|
brandId,
|
|
inquiryFormId: historicalForm.id,
|
|
customerSubject: "phase6-history-customer",
|
|
formVersion: 1,
|
|
fieldsSnapshot: historicalForm.fieldsSnapshot,
|
|
values: { message: "历史咨询内容" },
|
|
activeFields: ["message"],
|
|
},
|
|
});
|
|
historicalSubmissionId = historicalSubmission.id;
|
|
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({
|
|
where: { packageKey },
|
|
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: "集成测试基线包",
|
|
status: "published",
|
|
manifestSnapshot: initialManifest,
|
|
validationReport: {},
|
|
contentChecksum: `checksum-${initialPackageVersion}`,
|
|
archiveChecksum: `archive-${initialPackageVersion}`,
|
|
artifactPath: "/tmp/template-upgrade-initial-test",
|
|
importedById: admin.id,
|
|
},
|
|
});
|
|
createdVersionIds.push(initialPackageVersionRecord.id);
|
|
const originalConfig =
|
|
originalBrand.config && typeof originalBrand.config === "object" ? originalBrand.config : {};
|
|
const existingFounder = "升级前的品牌主理人";
|
|
await prisma.brandProfile.update({
|
|
where: { id: brandId },
|
|
data: { config: { ...originalConfig, founder: existingFounder } },
|
|
});
|
|
await prisma.brandTemplateInstallation.update({
|
|
where: { id: installedRecord.id },
|
|
data: {
|
|
templateVersion: initialPackageVersion,
|
|
templatePackageVersionId: initialPackageVersionRecord.id,
|
|
contentChecksum: initialPackageVersionRecord.contentChecksum,
|
|
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: "集成测试升级包",
|
|
status: "published",
|
|
manifestSnapshot: targetManifest,
|
|
validationReport: {},
|
|
contentChecksum: `checksum-${packageVersion}`,
|
|
archiveChecksum: `archive-${packageVersion}`,
|
|
artifactPath: "/tmp/template-upgrade-test",
|
|
importedById: admin.id,
|
|
},
|
|
});
|
|
createdVersionIds.push(packageVersionRecord.id);
|
|
const actionablePreview = await request("/admin/workspace/template/preview", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
const actionable = JSON.parse(actionablePreview.body);
|
|
assert.equal(actionable.canUpgrade, true);
|
|
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.changes.pages.added.length, 1);
|
|
assert.equal(actionable.changes.assets.slots.added.length, 1);
|
|
assert.deepEqual(actionable.changes.capabilities.removed, ["offerings"]);
|
|
assert.equal(actionable.changes.renderer.available, true);
|
|
assert.equal(actionable.changes.renderer.packageUpgradeChangesRenderer, false);
|
|
assert.equal(actionable.changes.assets.files.available, false);
|
|
const missingConfirm = await request("/admin/workspace/template/upgrade", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: {
|
|
templatePackageVersionId: packageVersionRecord.id,
|
|
expectedContentChecksum: packageVersionRecord.contentChecksum,
|
|
expectedCurrentVersion: actionable.currentVersion,
|
|
expectedCurrentPackageVersionId: actionable.currentPackageVersionId,
|
|
confirm: false,
|
|
preservedBindings: [],
|
|
},
|
|
});
|
|
assert.equal(missingConfirm.statusCode, 400);
|
|
const unresolvedConflict = await request("/admin/workspace/template/upgrade", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: {
|
|
templatePackageVersionId: packageVersionRecord.id,
|
|
expectedContentChecksum: packageVersionRecord.contentChecksum,
|
|
expectedCurrentVersion: actionable.currentVersion,
|
|
expectedCurrentPackageVersionId: actionable.currentPackageVersionId,
|
|
confirm: true,
|
|
preservedBindings: [],
|
|
},
|
|
});
|
|
assert.equal(unresolvedConflict.statusCode, 409);
|
|
const upgradePayload = {
|
|
templatePackageVersionId: packageVersionRecord.id,
|
|
expectedContentChecksum: packageVersionRecord.contentChecksum,
|
|
expectedCurrentVersion: actionable.currentVersion,
|
|
expectedCurrentPackageVersionId: actionable.currentPackageVersionId,
|
|
confirm: true,
|
|
preservedBindings: [{ key: "founder", binding: "brand.config.founder", action: "preserve" }],
|
|
};
|
|
const upgradeAttempts = await Promise.all(
|
|
[0, 1].map(() =>
|
|
request("/admin/workspace/template/upgrade", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: upgradePayload,
|
|
}),
|
|
),
|
|
);
|
|
assert.deepEqual(upgradeAttempts.map((item) => item.statusCode).sort(), [201, 409]);
|
|
const upgraded = upgradeAttempts.find((item) => item.statusCode === 201);
|
|
assert.ok(upgraded);
|
|
assert.equal(
|
|
JSON.parse(upgraded.body).installation.templatePackageVersionId,
|
|
packageVersionRecord.id,
|
|
);
|
|
assert.equal(
|
|
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).config.founder,
|
|
existingFounder,
|
|
);
|
|
const retainedOldPackage = await prisma.templatePackageVersion.findUniqueOrThrow({
|
|
where: { id: initialPackageVersionRecord.id },
|
|
});
|
|
assert.equal(retainedOldPackage.contentChecksum, initialPackageVersionRecord.contentChecksum);
|
|
const retainedRelease = await prisma.brandRelease.findUniqueOrThrow({
|
|
where: { id: historicalReleaseId },
|
|
});
|
|
assert.deepEqual(retainedRelease.snapshot, historicalReleaseSnapshot);
|
|
assert.equal(
|
|
(await prisma.inquirySubmission.findUniqueOrThrow({ where: { id: historicalSubmissionId } }))
|
|
.values.message,
|
|
"历史咨询内容",
|
|
);
|
|
await prisma.$disconnect();
|
|
await prisma.$connect();
|
|
await app.close();
|
|
app = await createApp();
|
|
await app.init();
|
|
const afterApiRestart = await request("/admin/workspace/template/preview", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(afterApiRestart.statusCode, 200);
|
|
assert.equal(JSON.parse(afterApiRestart.body).currentPackageVersionId, packageVersionRecord.id);
|
|
const rollbackUnauthorized = await request("/admin/workspace/template/rollback", {
|
|
method: "POST",
|
|
payload: { expectedCurrentVersion: packageVersion, confirm: true },
|
|
});
|
|
assert.equal(rollbackUnauthorized.statusCode, 401);
|
|
const upgradeUnauthorized = await request("/admin/workspace/template/upgrade", {
|
|
method: "POST",
|
|
payload: {},
|
|
});
|
|
assert.equal(upgradeUnauthorized.statusCode, 401);
|
|
const upgradeForbidden = await request("/admin/workspace/template/upgrade", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: {},
|
|
});
|
|
assert.equal(upgradeForbidden.statusCode, 403);
|
|
const upgradeInvalidDto = await request("/admin/workspace/template/upgrade", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: {},
|
|
});
|
|
assert.equal(upgradeInvalidDto.statusCode, 400);
|
|
const rollbackMissingConfirmation = await request("/admin/workspace/template/rollback", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { expectedCurrentVersion: packageVersion, confirm: false },
|
|
});
|
|
assert.equal(rollbackMissingConfirmation.statusCode, 400);
|
|
const rollbackStaleVersion = await request("/admin/workspace/template/rollback", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { expectedCurrentVersion: actionable.currentVersion, confirm: true },
|
|
});
|
|
assert.equal(rollbackStaleVersion.statusCode, 409);
|
|
const rollback = await request("/admin/workspace/template/rollback", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { expectedCurrentVersion: packageVersion, confirm: true },
|
|
});
|
|
assert.equal(rollback.statusCode, 201);
|
|
assert.equal(JSON.parse(rollback.body).installation.templateVersion, initialPackageVersion);
|
|
assert.equal(
|
|
JSON.parse(rollback.body).installation.templatePackageVersionId,
|
|
initialPackageVersionRecord.id,
|
|
);
|
|
assert.equal(JSON.parse(rollback.body).installation.previousSnapshots.length, 0);
|
|
assert.match(JSON.parse(rollback.body).note, /配置基线/);
|
|
const operationAudit = await prisma.templatePackageAuditLog.findMany({
|
|
where: {
|
|
templatePackageVersionId: packageVersionRecord.id,
|
|
action: { in: ["brand_upgrade", "brand_rollback"] },
|
|
},
|
|
orderBy: { createdAt: "asc" },
|
|
});
|
|
assert.deepEqual(
|
|
operationAudit.map((item) => item.action),
|
|
["brand_upgrade", "brand_rollback"],
|
|
);
|
|
assert.equal(operationAudit[0].metadata.brandId, brandId);
|
|
assert.equal(operationAudit[0].metadata.contentChecksum, packageVersionRecord.contentChecksum);
|
|
assert.ok(operationAudit[0].requestId);
|
|
const workspace = await request("/admin/workspace", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(workspace.statusCode, 200);
|
|
assert.equal(JSON.parse(workspace.body).installations.length, 1);
|
|
assert.equal(JSON.parse(workspace.body).fields.length, 5);
|
|
const templateContent = JSON.parse(workspace.body).templateContent;
|
|
assert.equal(templateContent.displayName, "阿成校园餐");
|
|
assert.ok(templateContent.trustContentTypes.some((item) => item.type === "schedule"));
|
|
assert.ok(templateContent.trustContentTypes.some((item) => item.label === "每周出摊安排"));
|
|
assert.ok(templateContent.admin.sections.some((section) => section.title === "首页出摊信息"));
|
|
assert.ok(
|
|
templateContent.admin.sections
|
|
.filter((section) => section.title === "首页出摊信息")
|
|
.every((section) => section.page === "home"),
|
|
);
|
|
assert.ok(templateContent.navigation.some((item) => item.page === "home" && item.label));
|
|
assert.ok(
|
|
templateContent.admin.sections
|
|
.flatMap((section) => section.fields)
|
|
.some((field) => field.binding === "brand.config.heroImage"),
|
|
);
|
|
const publicWorkspace = await request("/public/workspace");
|
|
assert.equal(publicWorkspace.statusCode, 200);
|
|
const workspaceBody = JSON.parse(publicWorkspace.body);
|
|
assert.equal(workspaceBody.contractVersion, "1.0");
|
|
assert.equal(workspaceBody.template.key, "food");
|
|
assert.equal("templateContent" in workspaceBody, false);
|
|
assert.equal("runtimeModules" in workspaceBody, false);
|
|
assert.equal("runtimeCapabilities" in workspaceBody, false);
|
|
assert.equal("fields" in workspaceBody, false);
|
|
assert.equal("trustContent" in workspaceBody, false);
|
|
assert.equal("inquiryForm" in workspaceBody, false);
|
|
assert.equal("modules" in workspaceBody, false);
|
|
assert.ok(workspaceBody.inquiryForms.length > 0);
|
|
const conflict = await request("/admin/workspace/install", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { templateKey: "food" },
|
|
});
|
|
assert.equal(conflict.statusCode, 400);
|
|
} finally {
|
|
if (historicalSubmissionId)
|
|
await prisma.inquirySubmission.deleteMany({ where: { id: historicalSubmissionId } });
|
|
if (historicalFormId) await prisma.inquiryForm.deleteMany({ where: { id: historicalFormId } });
|
|
if (historicalReleaseId)
|
|
await prisma.brandRelease.deleteMany({ where: { id: historicalReleaseId } });
|
|
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 },
|
|
});
|
|
}
|
|
});
|
|
|
|
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}` },
|
|
});
|
|
assert.equal(wrongRole.statusCode, 403);
|
|
const authorized = await request("/admin/workspace/preview", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(authorized.statusCode, 200);
|
|
const workspace = JSON.parse(authorized.body);
|
|
assert.equal(workspace.publication?.status, "draft");
|
|
assert.equal(
|
|
workspace.brand.slug,
|
|
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).slug,
|
|
);
|
|
assert.equal(workspace.visualTemplate.key, "acheng-campus-food");
|
|
const unpublishedBrand = await prisma.brandProfile.create({
|
|
data: {
|
|
slug: "unpublished-preview-fixture",
|
|
name: "未发布预览品牌",
|
|
templateKey: "personal",
|
|
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, 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);
|
|
} finally {
|
|
await prisma.brandProfile.delete({ where: { id: unpublishedBrand.id } });
|
|
}
|
|
});
|
|
|
|
test("admin can customize workspace fields with brand isolation", async () => {
|
|
await prisma.brandFieldDefinition.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 workspace = await request("/admin/workspace", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
const invalidField = await request("/admin/workspace/fields", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { scope: "unknown", key: "Bad-Key", label: "非法字段", type: "text" },
|
|
});
|
|
assert.equal(invalidField.statusCode, 400);
|
|
const createdField = await request("/admin/workspace/fields", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: {
|
|
scope: "profile",
|
|
key: `region_${Date.now()}`,
|
|
label: "服务区域",
|
|
type: "text",
|
|
required: false,
|
|
},
|
|
});
|
|
assert.equal(createdField.statusCode, 201);
|
|
const fieldId = JSON.parse(createdField.body).id;
|
|
try {
|
|
const updatedField = await request(`/admin/workspace/fields/${fieldId}`, {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { label: "主要服务区域", visibleWhen: { mode: "all", rules: [] } },
|
|
});
|
|
assert.equal(updatedField.statusCode, 200);
|
|
const deletedField = await request(`/admin/workspace/fields/${fieldId}`, {
|
|
method: "DELETE",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(deletedField.statusCode, 200);
|
|
} finally {
|
|
await prisma.brandFieldDefinition.deleteMany({ where: { brandId } });
|
|
}
|
|
});
|
|
|
|
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 installation = await prisma.brandTemplateInstallation.findUniqueOrThrow({
|
|
where: { brandId },
|
|
});
|
|
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 () => {
|
|
const doorsBrand = await prisma.brandProfile.findUnique({ where: { slug: "linjing-doors" } });
|
|
assert.ok(doorsBrand);
|
|
const original = doorsBrand;
|
|
await prisma.brandProfile.update({
|
|
where: { id: doorsBrand.id },
|
|
data: {
|
|
config: {
|
|
...(original?.config && typeof original.config === "object" ? original.config : {}),
|
|
homeHero: { title: "尚未发布的集成测试首页标题" },
|
|
},
|
|
},
|
|
});
|
|
try {
|
|
const runtime = await request("/public/workspace?brandSlug=linjing-doors");
|
|
assert.equal(runtime.statusCode, 200);
|
|
const body = JSON.parse(runtime.body);
|
|
assert.equal(body.brand.founder, "林叙安 (Lin XUAN)");
|
|
assert.equal(body.brand.title, "高端门系统建筑研造主理人");
|
|
assert.notEqual(body.brand.homeHero.title, "尚未发布的集成测试首页标题");
|
|
assert.equal(body.trustPresentation.stats.length, 4);
|
|
assert.equal(body.trustPresentation.pillars.length, 3);
|
|
assert.equal(body.trustPresentation.serviceFlow.length, 6);
|
|
assert.equal(body.brand.profilePresentation.coverage.length, 2);
|
|
assert.equal(body.brand.profilePresentation.warranty.length, 4);
|
|
assert.equal(body.brand.visualPresentation.home.proofTitle, "14 年,只做门与空间的关系");
|
|
assert.equal(body.brand.visualPresentation.inquiry.submitLabel, "提交量房与定制评估需求");
|
|
assert.equal(body.brand.visualPresentation.records.emptyAction, "开始咨询");
|
|
assert.equal(body.offerings.length, 4);
|
|
assert.ok(body.offerings.every((offering) => offering.presentation.heroImage));
|
|
assert.ok(
|
|
body.offerings.every((offering) => offering.presentation.details.materialsList.length),
|
|
);
|
|
const doorType = body.inquiryForms[0].fields.find((field) => field.key === "doorType");
|
|
assert.equal(doorType.options.length, 5);
|
|
assert.equal(doorType.options[0].value, "entry");
|
|
const phone = body.inquiryForms[0].fields.find((field) => field.key === "contactPhone");
|
|
assert.equal(phone.type, "tel");
|
|
const foodWorkspace = await request("/public/workspace?brandSlug=default-brand");
|
|
const foodPhone = JSON.parse(foodWorkspace.body).inquiryForms[0].fields.find(
|
|
(field) => field.key === "phone",
|
|
);
|
|
assert.equal(foodPhone.type, "tel");
|
|
} finally {
|
|
await prisma.brandProfile.update({
|
|
where: { id: doorsBrand.id },
|
|
data: { config: original?.config ?? {} },
|
|
});
|
|
}
|
|
});
|
|
|
|
test("edited template facts reach public workspace only after publication", async () => {
|
|
const doorsBrand = await prisma.brandProfile.findUniqueOrThrow({
|
|
where: { slug: "linjing-doors" },
|
|
});
|
|
const trust = await prisma.trustContent.findFirstOrThrow({
|
|
where: { brandId: doorsBrand.id, type: "credential", isPublished: true },
|
|
orderBy: { sortOrder: "asc" },
|
|
});
|
|
const offering = await prisma.offering.findFirstOrThrow({
|
|
where: { brandId: doorsBrand.id, isEnabled: true },
|
|
orderBy: { sortOrder: "asc" },
|
|
});
|
|
const adminUser = await prisma.adminUser.findUniqueOrThrow({
|
|
where: { username: "admin" },
|
|
select: { id: true },
|
|
});
|
|
const token = signIdentity({ subject: adminUser.id, brandId: doorsBrand.id, role: "admin" });
|
|
const headers = { authorization: `Bearer ${token}` };
|
|
const originalBrandConfig = doorsBrand.config;
|
|
const originalTrustConfig = trust.config;
|
|
const originalOfferingConfig = offering.config;
|
|
const before = JSON.parse((await request("/public/workspace?brandSlug=linjing-doors")).body);
|
|
const changedTitle = "集成测试定制首页标题";
|
|
const changedArea = "集成测试项目地点";
|
|
const changedIntro = "集成测试发布后联系说明";
|
|
const changedHint = "集成测试咨询后处理说明";
|
|
const changedDetailHero = "https://example.com/integration-detail.jpg";
|
|
const changedDetailBackground = "集成测试案例详情正文";
|
|
const changedTemplateData = "集成测试设计理念";
|
|
const changedStats = [{ value: "42", label: "测试成果", sub: "持久化子标题" }];
|
|
const changedDescription = "唯一品牌简介保存发布验证";
|
|
const obsolete = await prisma.trustContent.create({
|
|
data: {
|
|
brandId: doorsBrand.id,
|
|
type: "profile",
|
|
title: "旧类型不得覆盖模板配置",
|
|
content: "旧简介",
|
|
config: { stats: [{ value: "旧值", label: "不得显示" }], internalOnly: "不得公开" },
|
|
isPublished: true,
|
|
sortOrder: -100,
|
|
},
|
|
});
|
|
try {
|
|
const brandConfig = originalBrandConfig ?? {};
|
|
const presentation = brandConfig.visualPresentation ?? {};
|
|
const brandUpdate = await request("/admin/config/brand", {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: {
|
|
description: changedDescription,
|
|
config: {
|
|
homeHero: { ...brandConfig.homeHero, title: changedTitle },
|
|
visualPresentation: {
|
|
...presentation,
|
|
success: { ...presentation.success, intro: changedIntro },
|
|
detail: { ...presentation.detail, inquiryHint: changedHint },
|
|
},
|
|
templateData: {
|
|
...(brandConfig.templateData ?? {}),
|
|
designPhilosophy: changedTemplateData,
|
|
internalOnly: "不得公开",
|
|
},
|
|
},
|
|
},
|
|
});
|
|
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,
|
|
payload: { config: { ...(trust.config ?? {}), stats: changedStats } },
|
|
});
|
|
assert.equal(trustUpdate.statusCode, 200);
|
|
const offeringUpdate = await request(`/admin/workspace/offerings/${offering.id}`, {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: {
|
|
config: {
|
|
...(offering.config ?? {}),
|
|
area: changedArea,
|
|
detailHero: changedDetailHero,
|
|
details: {
|
|
...((offering.config ?? {}).details ?? {}),
|
|
background: changedDetailBackground,
|
|
},
|
|
},
|
|
},
|
|
});
|
|
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,
|
|
);
|
|
assert.equal(
|
|
draftView.brand.visualPresentation.detail.inquiryHint,
|
|
before.brand.visualPresentation.detail.inquiryHint,
|
|
);
|
|
assert.deepEqual(draftView.trustPresentation.stats, before.trustPresentation.stats);
|
|
assert.equal(draftView.offerings[0].presentation.area, before.offerings[0].presentation.area);
|
|
assert.equal(
|
|
draftView.offerings[0].presentation.heroImage,
|
|
before.offerings[0].presentation.heroImage,
|
|
);
|
|
|
|
const publish = await request("/admin/releases/publish", {
|
|
method: "POST",
|
|
headers,
|
|
payload: { note: "集成测试模板内容编辑" },
|
|
});
|
|
assert.equal(publish.statusCode, 201);
|
|
const afterPublish = JSON.parse(
|
|
(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);
|
|
assert.equal(afterPublish.brand.visualPresentation.detail.inquiryHint, changedHint);
|
|
assert.deepEqual(afterPublish.trustPresentation.stats, changedStats);
|
|
assert.equal(
|
|
afterPublish.trustItems.some((item) => item.type === "profile"),
|
|
false,
|
|
);
|
|
assert.equal(Object.hasOwn(afterPublish.trustPresentation, "internalOnly"), false);
|
|
assert.equal(afterPublish.offerings[0].presentation.area, changedArea);
|
|
assert.equal(afterPublish.offerings[0].presentation.heroImage, changedDetailHero);
|
|
assert.equal(
|
|
afterPublish.offerings[0].presentation.details.background,
|
|
changedDetailBackground,
|
|
);
|
|
} finally {
|
|
await prisma.trustContent.delete({ where: { id: obsolete.id } });
|
|
await prisma.brandProfile.update({
|
|
where: { id: doorsBrand.id },
|
|
data: { config: originalBrandConfig, description: doorsBrand.description },
|
|
});
|
|
await prisma.trustContent.update({
|
|
where: { id: trust.id },
|
|
data: { config: originalTrustConfig },
|
|
});
|
|
await prisma.offering.update({
|
|
where: { id: offering.id },
|
|
data: { config: originalOfferingConfig },
|
|
});
|
|
const restored = await request("/admin/releases/publish", {
|
|
method: "POST",
|
|
headers,
|
|
payload: { note: "恢复集成测试模板基线" },
|
|
});
|
|
assert.equal(restored.statusCode, 201);
|
|
}
|
|
});
|
|
|
|
test("admin can create and version an inquiry form", 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 offering = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } });
|
|
assert.ok(offering);
|
|
const created = await request("/admin/workspace/forms", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: {
|
|
name: "品牌合作咨询",
|
|
offeringId: offering.id,
|
|
fieldsSnapshot: [{ key: "project", type: "textarea", label: "项目背景", required: true }],
|
|
},
|
|
});
|
|
assert.equal(created.statusCode, 201);
|
|
const id = JSON.parse(created.body).id;
|
|
try {
|
|
const disabledForm = await request(`/admin/workspace/forms/${id}`, {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { isEnabled: false },
|
|
});
|
|
assert.equal(disabledForm.statusCode, 200);
|
|
assert.equal(JSON.parse(disabledForm.body).isEnabled, false);
|
|
assert.equal((await request(`/public/inquiry-forms/${id}`)).statusCode, 400);
|
|
const blockedDisabledForm = await request("/customer/inquiry-submissions", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: { formId: id, values: { budget: 1000 } },
|
|
});
|
|
assert.equal(blockedDisabledForm.statusCode, 400);
|
|
const enabledForm = await request(`/admin/workspace/forms/${id}`, {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { isEnabled: true },
|
|
});
|
|
assert.equal(enabledForm.statusCode, 200);
|
|
const updated = await request(`/admin/workspace/forms/${id}`, {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: {
|
|
fieldsSnapshot: [
|
|
{ key: "budget", type: "number", label: "预算", required: true },
|
|
{
|
|
key: "contact_method",
|
|
type: "select",
|
|
label: "联系渠道",
|
|
options: [{ label: "微信", value: "wechat" }],
|
|
},
|
|
{
|
|
key: "topics",
|
|
type: "multi-select",
|
|
label: "关注方向",
|
|
options: [
|
|
{ label: "咨询", value: "consulting" },
|
|
{ label: "设计", value: "design" },
|
|
],
|
|
},
|
|
{
|
|
key: "wechat",
|
|
type: "text",
|
|
label: "微信号",
|
|
visibleWhen: [{ field: "contact_method", operator: "equals", value: "wechat" }],
|
|
},
|
|
],
|
|
},
|
|
});
|
|
assert.equal(updated.statusCode, 200);
|
|
assert.equal(JSON.parse(updated.body).version, 2);
|
|
await prisma.offering.update({ where: { id: offering.id }, data: { isEnabled: false } });
|
|
assert.equal((await request(`/public/inquiry-forms/${id}`)).statusCode, 400);
|
|
const blockedSubmission = await request("/customer/inquiry-submissions", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: { formId: id, values: { budget: 1000 } },
|
|
});
|
|
assert.equal(blockedSubmission.statusCode, 400);
|
|
await prisma.offering.update({ where: { id: offering.id }, data: { isEnabled: true } });
|
|
const missingRequired = await request("/customer/inquiry-submissions", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: { formId: id, values: {} },
|
|
});
|
|
assert.equal(missingRequired.statusCode, 400);
|
|
// 业务校验错误必须透传具体原因,不能被统一改写为"请求失败"。
|
|
assert.equal(JSON.parse(missingRequired.body).error.code, "HTTP_400");
|
|
assert.equal(JSON.parse(missingRequired.body).error.message, "咨询表单不存在或品牌尚未发布");
|
|
const invalidBody = await request("/customer/inquiry-submissions", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: { formId: id },
|
|
});
|
|
assert.equal(invalidBody.statusCode, 400);
|
|
assert.notEqual(JSON.parse(invalidBody.body).error.message, "请求失败");
|
|
const capability = await prisma.capabilityInstallation.create({
|
|
data: {
|
|
brandId,
|
|
capabilityKey: "inquiry",
|
|
capabilityVersion: "1.0.0",
|
|
status: "disabled",
|
|
},
|
|
});
|
|
const blockedCapability = await request("/customer/inquiry-submissions", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: { formId: id, values: { budget: 1000 } },
|
|
});
|
|
assert.equal(blockedCapability.statusCode, 400);
|
|
await prisma.capabilityInstallation.delete({ where: { id: capability.id } });
|
|
assert.equal((await publishReleaseForTests()).statusCode, 201);
|
|
const publicForm = await request(`/public/inquiry-forms/${id}`);
|
|
assert.equal(publicForm.statusCode, 200);
|
|
assert.equal(
|
|
JSON.parse(publicForm.body).fieldsSnapshot.find((field) => field.key === "topics").type,
|
|
"multi-select",
|
|
);
|
|
const publicOffering = await request(`/public/offerings/${offering.id}`);
|
|
assert.equal(publicOffering.statusCode, 200);
|
|
assert.equal(JSON.parse(publicOffering.body).inquiryForms[0].id, id);
|
|
assert.equal(
|
|
(await request("/public/offerings/00000000-0000-0000-0000-000000000000")).statusCode,
|
|
404,
|
|
);
|
|
const publicWorkspace = await request("/public/workspace");
|
|
assert.equal(publicWorkspace.statusCode, 200);
|
|
const runtimeForm = JSON.parse(publicWorkspace.body).inquiryForms.find(
|
|
(form) => form.key === id,
|
|
);
|
|
assert.ok(runtimeForm);
|
|
assert.equal(runtimeForm.fields.find((field) => field.key === "topics").type, "checkbox");
|
|
assert.ok(
|
|
JSON.parse(publicWorkspace.body).inquiryForms.some(
|
|
(form) => form.key === id && form.targetId === offering.id,
|
|
),
|
|
);
|
|
assert.deepEqual(runtimeForm.fields[1].options, [{ label: "微信", value: "wechat" }]);
|
|
assert.deepEqual(runtimeForm.fields[3].visibleWhen, [
|
|
{ field: "contact_method", operator: "equals", value: "wechat" },
|
|
]);
|
|
await prisma.inquiryForm.update({
|
|
where: { id },
|
|
data: {
|
|
version: 3,
|
|
fieldsSnapshot: [{ key: "draft_only", type: "text", label: "草稿字段", required: true }],
|
|
},
|
|
});
|
|
const submission = await request("/customer/inquiry-submissions", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: {
|
|
formId: id,
|
|
values: {
|
|
budget: 1000,
|
|
contact_method: "wechat",
|
|
ignored: "not persisted",
|
|
wechat: "brand-wechat",
|
|
},
|
|
},
|
|
});
|
|
assert.equal(submission.statusCode, 201);
|
|
assert.equal(JSON.parse(submission.body).formVersion, 2);
|
|
assert.equal(JSON.parse(submission.body).fieldsSnapshot[0].key, "budget");
|
|
assert.equal(JSON.parse(submission.body).offeringId, offering.id);
|
|
assert.deepEqual(JSON.parse(submission.body).values, {
|
|
budget: 1000,
|
|
contact_method: "wechat",
|
|
wechat: "brand-wechat",
|
|
});
|
|
assert.equal((await request("/customer/inquiry-submissions")).statusCode, 401);
|
|
const adminCannotListCustomerSubmissions = await request("/customer/inquiry-submissions", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(adminCannotListCustomerSubmissions.statusCode, 403);
|
|
const customerSubmissions = await request("/customer/inquiry-submissions", {
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
});
|
|
assert.equal(customerSubmissions.statusCode, 200);
|
|
assert.ok(
|
|
JSON.parse(customerSubmissions.body).some(
|
|
(item) => item.id === JSON.parse(submission.body).id,
|
|
),
|
|
);
|
|
const customerSubmission = await request(
|
|
`/customer/inquiry-submissions/${JSON.parse(submission.body).id}`,
|
|
{ headers: { authorization: `Bearer ${customerToken}` } },
|
|
);
|
|
assert.equal(customerSubmission.statusCode, 200);
|
|
assert.equal(JSON.parse(customerSubmission.body).customerSubject, undefined);
|
|
const missingCustomerSubmission = await request(
|
|
"/customer/inquiry-submissions/00000000-0000-0000-0000-000000000000",
|
|
{ headers: { authorization: `Bearer ${customerToken}` } },
|
|
);
|
|
assert.equal(missingCustomerSubmission.statusCode, 404);
|
|
const adminSubmissionsWithoutToken = await request("/admin/workspace/submissions");
|
|
assert.equal(adminSubmissionsWithoutToken.statusCode, 401);
|
|
const adminSubmissions = await request("/admin/workspace/submissions", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(adminSubmissions.statusCode, 200);
|
|
assert.ok(
|
|
JSON.parse(adminSubmissions.body).some((item) => item.id === JSON.parse(submission.body).id),
|
|
);
|
|
const savedSubmission = JSON.parse(adminSubmissions.body).find(
|
|
(item) => item.id === JSON.parse(submission.body).id,
|
|
);
|
|
assert.equal(savedSubmission.offering.id, offering.id);
|
|
const customerUpdate = await request(`/admin/workspace/submissions/${savedSubmission.id}`, {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: { status: "replied" },
|
|
});
|
|
assert.equal(customerUpdate.statusCode, 403);
|
|
const updatedSubmission = await request(`/admin/workspace/submissions/${savedSubmission.id}`, {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { status: "reviewing", adminNote: "已开始评估需求" },
|
|
});
|
|
assert.equal(updatedSubmission.statusCode, 200);
|
|
assert.equal(JSON.parse(updatedSubmission.body).status, "reviewing");
|
|
assert.equal(JSON.parse(updatedSubmission.body).adminNote, "已开始评估需求");
|
|
const customerSubmissionAfterUpdate = await request(
|
|
`/customer/inquiry-submissions/${savedSubmission.id}`,
|
|
{ headers: { authorization: `Bearer ${customerToken}` } },
|
|
);
|
|
assert.equal(customerSubmissionAfterUpdate.statusCode, 200);
|
|
const customerBody = JSON.parse(customerSubmissionAfterUpdate.body);
|
|
assert.equal(customerBody.adminNote, undefined);
|
|
assert.equal(customerBody.statusHistory[0].toStatus, "reviewing");
|
|
assert.equal(customerBody.statusHistory[0].adminNote, undefined);
|
|
const history = await prisma.inquirySubmissionStatusHistory.findMany({
|
|
where: { submissionId: savedSubmission.id },
|
|
});
|
|
assert.equal(history.length, 1);
|
|
assert.equal(history[0].toStatus, "reviewing");
|
|
} finally {
|
|
await prisma.inquirySubmission.deleteMany({ where: { inquiryFormId: id } });
|
|
await prisma.inquiryForm.delete({ where: { id } });
|
|
}
|
|
});
|
|
|
|
test("admin workspace data stays inside the acting brand", 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 actingBrandId = readIdentity(token).brandId;
|
|
const otherBrand = await prisma.brandProfile.findFirst({
|
|
where: { id: { not: actingBrandId } },
|
|
});
|
|
assert.ok(otherBrand);
|
|
|
|
const switchResponse = await request(`/admin/brands/${otherBrand.id}/switch`, {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(switchResponse.statusCode, 201);
|
|
const switchedToken = JSON.parse(switchResponse.body).token;
|
|
assert.equal(readIdentity(switchedToken).brandId, otherBrand.id);
|
|
|
|
const workspace = await request("/admin/workspace", {
|
|
headers: { authorization: `Bearer ${switchedToken}` },
|
|
});
|
|
assert.equal(workspace.statusCode, 200);
|
|
const offeringBrandIds = [
|
|
...new Set(JSON.parse(workspace.body).offerings.map((item) => item.brandId)),
|
|
];
|
|
assert.deepEqual(offeringBrandIds, [otherBrand.id]);
|
|
|
|
// 公开工作空间不带 brandSlug 时会回退到默认品牌;后台下拉框若直接用它会串到别的品牌,
|
|
// 这里把这个差异固定下来,防止再次被接回 Admin。
|
|
const publicWorkspace = await request("/public/workspace");
|
|
const publicOfferingIds = JSON.parse(publicWorkspace.body).offerings.map((item) => item.id);
|
|
const foreignIds = JSON.parse(workspace.body)
|
|
.offerings.map((item) => item.id)
|
|
.filter((id) => publicOfferingIds.includes(id));
|
|
assert.deepEqual(foreignIds, []);
|
|
});
|
|
|
|
test("inquiry form offering link is validated against the brand", 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 headers = { authorization: `Bearer ${token}` };
|
|
const offering = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } });
|
|
assert.ok(offering);
|
|
const otherBrandOffering = await prisma.offering.findFirst({
|
|
where: { brandId: { not: brandId } },
|
|
});
|
|
assert.ok(otherBrandOffering);
|
|
const fields = [{ key: "project", type: "textarea", label: "项目背景", required: true }];
|
|
|
|
// 不存在的业务 id:必须是可读的 400,而不是数据库外键错误。
|
|
const unknown = await request("/admin/workspace/forms", {
|
|
method: "POST",
|
|
headers,
|
|
payload: { name: "非法关联表单", offeringId: randomUUID(), fieldsSnapshot: fields },
|
|
});
|
|
assert.equal(unknown.statusCode, 400);
|
|
assert.match(errorMessage(unknown.body), /关联的业务提供项不存在/);
|
|
|
|
// 其他品牌的业务 id:品牌隔离必须拦住。
|
|
const crossBrand = await request("/admin/workspace/forms", {
|
|
method: "POST",
|
|
headers,
|
|
payload: {
|
|
name: "跨品牌关联表单",
|
|
offeringId: otherBrandOffering.id,
|
|
fieldsSnapshot: fields,
|
|
},
|
|
});
|
|
assert.equal(crossBrand.statusCode, 400);
|
|
assert.match(errorMessage(crossBrand.body), /不属于当前品牌/);
|
|
assert.equal(await prisma.inquiryForm.count({ where: { brandId, name: "跨品牌关联表单" } }), 0);
|
|
|
|
// 合法的关联:targetType 由后端推导为 offering,写入后仍然只能被本品牌看到。
|
|
const created = await request("/admin/workspace/forms", {
|
|
method: "POST",
|
|
headers,
|
|
payload: { name: "业务专属表单", offeringId: offering.id, fieldsSnapshot: fields },
|
|
});
|
|
assert.equal(created.statusCode, 201);
|
|
const form = JSON.parse(created.body);
|
|
assert.equal(form.offeringId, offering.id);
|
|
assert.equal(form.targetType, "offering");
|
|
try {
|
|
const hijack = await request(`/admin/workspace/forms/${form.id}`, {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: { offeringId: otherBrandOffering.id },
|
|
});
|
|
assert.equal(hijack.statusCode, 400);
|
|
const unchanged = await prisma.inquiryForm.findUnique({ where: { id: form.id } });
|
|
assert.equal(unchanged.offeringId, offering.id);
|
|
|
|
// 解除关联:显式传 null 才能回到品牌通用入口。
|
|
const unlinked = await request(`/admin/workspace/forms/${form.id}`, {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: { offeringId: null },
|
|
});
|
|
assert.equal(unlinked.statusCode, 200);
|
|
const unlinkedBody = JSON.parse(unlinked.body);
|
|
assert.equal(unlinkedBody.offeringId, null);
|
|
assert.equal(unlinkedBody.targetType, "brand");
|
|
} finally {
|
|
await prisma.inquiryForm.delete({ where: { id: form.id } });
|
|
}
|
|
});
|
|
|
|
test("release readiness explains a form whose offering was disabled", 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 headers = { authorization: `Bearer ${token}` };
|
|
const offering = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } });
|
|
assert.ok(offering);
|
|
const form = await prisma.inquiryForm.create({
|
|
data: {
|
|
brandId,
|
|
name: "随业务停用的表单",
|
|
offeringId: offering.id,
|
|
targetType: "offering",
|
|
purpose: "inquiry",
|
|
submissionAction: "create-inquiry",
|
|
fieldsSnapshot: [{ key: "project", type: "textarea", label: "项目背景", required: true }],
|
|
isEnabled: true,
|
|
},
|
|
});
|
|
const originalFormEnabled = form.isEnabled;
|
|
await prisma.offering.update({ where: { id: offering.id }, data: { isEnabled: false } });
|
|
try {
|
|
const readiness = await request("/admin/releases/readiness", { headers });
|
|
assert.equal(readiness.statusCode, 200);
|
|
const formsCheck = JSON.parse(readiness.body).checks.find((check) => check.key === "forms");
|
|
assert.equal(formsCheck.passed, false);
|
|
assert.match(formsCheck.help, /随业务停用的表单/);
|
|
assert.match(formsCheck.help, /关联的业务提供项已停用/);
|
|
} finally {
|
|
await prisma.offering.update({ where: { id: offering.id }, data: { isEnabled: true } });
|
|
await prisma.inquiryForm.deleteMany({ where: { id: form.id } });
|
|
}
|
|
assert.equal(originalFormEnabled, true);
|
|
});
|
|
|
|
test("admin rejects invalid dynamic inquiry field definitions", 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 invalid = await request("/admin/workspace/forms", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: {
|
|
name: "非法字段表单",
|
|
fieldsSnapshot: [{ key: "ContactMethod", type: "select", label: "渠道", options: [] }],
|
|
},
|
|
});
|
|
assert.equal(invalid.statusCode, 400);
|
|
});
|
|
|
|
test("admin can manage offerings and public endpoint hides disabled offerings", 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 invalidConfig = await request("/admin/workspace/offerings", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: {
|
|
kind: "product",
|
|
name: `无效配置-${Date.now()}`,
|
|
config: { sections: "必须是数组" },
|
|
},
|
|
});
|
|
assert.equal(invalidConfig.statusCode, 400);
|
|
const created = await request("/admin/workspace/offerings", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: {
|
|
kind: "product",
|
|
name: `测试提供项-${Date.now()}`,
|
|
summary: "测试摘要",
|
|
isEnabled: true,
|
|
},
|
|
});
|
|
assert.equal(created.statusCode, 201);
|
|
const id = JSON.parse(created.body).id;
|
|
try {
|
|
const listed = await request("/admin/workspace/offerings", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(listed.statusCode, 200);
|
|
assert.ok(JSON.parse(listed.body).some((item) => item.id === id));
|
|
const withCategory = await request(`/admin/workspace/offerings/${id}`, {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { config: { categoryKey: "set-meal" } },
|
|
});
|
|
assert.equal(withCategory.statusCode, 200);
|
|
const preview = await request("/admin/workspace/preview", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(preview.statusCode, 200);
|
|
const draft = JSON.parse(preview.body);
|
|
const previewOffering = draft.offerings.find((item) => item.id === id);
|
|
assert.equal(previewOffering?.presentation?.categoryKey, "set-meal");
|
|
assert.equal(previewOffering?.presentation?.categoryLabel, "套餐");
|
|
const publicItem = await request(`/public/offerings/${id}`);
|
|
assert.equal(publicItem.statusCode, 404);
|
|
const publicList = await request("/public/offerings");
|
|
assert.equal(publicList.statusCode, 200);
|
|
assert.ok(!JSON.parse(publicList.body).some((item) => item.id === id));
|
|
const updated = await request(`/admin/workspace/offerings/${id}`, {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { isEnabled: false },
|
|
});
|
|
assert.equal(updated.statusCode, 200);
|
|
const hidden = await request(`/public/offerings/${id}`);
|
|
assert.equal(hidden.statusCode, 404);
|
|
const reenabled = await request(`/admin/workspace/offerings/${id}`, {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { isEnabled: true },
|
|
});
|
|
assert.equal(reenabled.statusCode, 200);
|
|
assert.equal((await request(`/public/offerings/${id}`)).statusCode, 404);
|
|
} finally {
|
|
const deleted = await request(`/admin/workspace/offerings/${id}`, {
|
|
method: "DELETE",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(deleted.statusCode, 200);
|
|
assert.equal(await prisma.offering.findUnique({ where: { id } }), null);
|
|
}
|
|
});
|
|
|
|
test("offering with an inquiry form cannot be deleted", 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 offering = await prisma.offering.create({
|
|
data: { brandId, kind: "service", name: `保护测试-${Date.now()}`, description: "测试" },
|
|
});
|
|
const form = await prisma.inquiryForm.create({
|
|
data: { brandId, offeringId: offering.id, name: "保护测试表单", fieldsSnapshot: [] },
|
|
});
|
|
try {
|
|
const response = await request(`/admin/workspace/offerings/${offering.id}`, {
|
|
method: "DELETE",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(response.statusCode, 400);
|
|
} finally {
|
|
await prisma.inquiryForm.delete({ where: { id: form.id } });
|
|
await prisma.offering.delete({ where: { id: offering.id } });
|
|
}
|
|
});
|
|
|
|
test("admin booking endpoints reject missing or customer credentials", async () => {
|
|
const missing = await request("/admin/bookings");
|
|
assert.equal(missing.statusCode, 401);
|
|
|
|
const customer = await request("/admin/bookings", {
|
|
headers: { authorization: "Bearer invalid-token" },
|
|
});
|
|
assert.equal(customer.statusCode, 401);
|
|
});
|
|
|
|
test("seeded admin can log in and read protected booking resources", async () => {
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
|
});
|
|
assert.equal(login.statusCode, 201);
|
|
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
|
assert.ok(token);
|
|
|
|
const count = await request("/admin/bookings/unread-count", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(count.statusCode, 200);
|
|
assert.equal(typeof JSON.parse(count.body).count, "number");
|
|
|
|
const tags = await request("/admin/bookings/tags", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(tags.statusCode, 200);
|
|
assert.equal(JSON.parse(tags.body).length, 6);
|
|
});
|
|
|
|
test("admin login validates credentials", async () => {
|
|
const response = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username: "admin", password: "wrong-password" },
|
|
});
|
|
assert.equal(response.statusCode, 401);
|
|
});
|
|
|
|
test("admin logout revokes the current token", async () => {
|
|
const username = `logout-admin-${randomUUID()}`;
|
|
const password = "logout-password-123";
|
|
const user = await prisma.adminUser.create({
|
|
data: {
|
|
username,
|
|
passwordHash: await bcrypt.hash(password, 12),
|
|
displayName: "登出测试管理员",
|
|
mustChangePassword: false,
|
|
},
|
|
});
|
|
await prisma.brandMembership.create({
|
|
data: { brandId, adminUserId: user.id, role: "owner", isEnabled: true },
|
|
});
|
|
try {
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username, password },
|
|
});
|
|
assert.equal(login.statusCode, 201, login.body);
|
|
const token = JSON.parse(login.body).token;
|
|
const headers = { authorization: `Bearer ${token}` };
|
|
const before = await request("/admin/bookings/unread-count", { headers });
|
|
assert.equal(before.statusCode, 200);
|
|
|
|
const logout = await request("/admin/session/logout", { method: "POST", headers });
|
|
assert.equal(logout.statusCode, 201);
|
|
const after = await request("/admin/bookings/unread-count", { headers });
|
|
assert.equal(after.statusCode, 401);
|
|
} finally {
|
|
await prisma.adminUser.delete({ where: { id: user.id } });
|
|
}
|
|
});
|
|
|
|
test("customer logout revokes the current token", async () => {
|
|
const openid = `logout-${randomUUID()}`;
|
|
await prisma.customerUser.create({ data: { brandId, openid } });
|
|
const token = signIdentity({ subject: openid, brandId, role: "customer" });
|
|
const headers = { authorization: `Bearer ${token}` };
|
|
const before = await request("/customer/inquiry-submissions", { headers });
|
|
assert.equal(before.statusCode, 200);
|
|
|
|
const logout = await request("/customer/session/logout", { method: "POST", headers });
|
|
assert.equal(logout.statusCode, 201);
|
|
const after = await request("/customer/inquiry-submissions", { headers });
|
|
assert.equal(after.statusCode, 401);
|
|
});
|
|
|
|
test("admin login does not auto-grant ownership to users without memberships", async () => {
|
|
const username = `no-membership-${Date.now()}`;
|
|
const user = await prisma.adminUser.create({
|
|
data: {
|
|
username,
|
|
passwordHash: await bcrypt.hash("initial-password-123", 12),
|
|
displayName: "未分配品牌管理员",
|
|
mustChangePassword: false,
|
|
},
|
|
});
|
|
try {
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username, password: "initial-password-123" },
|
|
});
|
|
assert.equal(login.statusCode, 403);
|
|
assert.equal(await prisma.brandMembership.count({ where: { adminUserId: user.id } }), 0);
|
|
} finally {
|
|
await prisma.adminUser.delete({ where: { id: user.id } });
|
|
}
|
|
});
|
|
|
|
test("changing an admin password revokes existing admin tokens", async () => {
|
|
const username = `token-version-${Date.now()}`;
|
|
const user = await prisma.adminUser.create({
|
|
data: {
|
|
username,
|
|
passwordHash: await bcrypt.hash("initial-password-123", 12),
|
|
displayName: "Token 版本管理员",
|
|
mustChangePassword: false,
|
|
memberships: {
|
|
create: { brandId, role: "admin", isEnabled: true },
|
|
},
|
|
},
|
|
});
|
|
try {
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username, password: "initial-password-123" },
|
|
});
|
|
assert.equal(login.statusCode, 201, login.body);
|
|
const token = JSON.parse(login.body).token;
|
|
const headers = { authorization: `Bearer ${token}` };
|
|
const before = await request("/admin/bookings/unread-count", { headers });
|
|
assert.equal(before.statusCode, 200, before.body);
|
|
|
|
const changed = await request("/admin/session/change-password", {
|
|
method: "POST",
|
|
headers,
|
|
payload: { currentPassword: "initial-password-123", newPassword: "changed-password-456" },
|
|
});
|
|
assert.equal(changed.statusCode, 201, changed.body);
|
|
|
|
const after = await request("/admin/bookings/unread-count", { headers });
|
|
assert.equal(after.statusCode, 401, after.body);
|
|
} finally {
|
|
await prisma.adminUser.delete({ where: { id: user.id } });
|
|
}
|
|
});
|
|
|
|
test("admin can list and switch only enabled brand memberships", 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 brands = await request("/admin/brands", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(brands.statusCode, 200);
|
|
const memberships = JSON.parse(brands.body);
|
|
assert.ok(memberships.some((item) => item.brand.id === brandId));
|
|
assert.ok(memberships.some((item) => item.brand.slug === "linjing-doors"));
|
|
assert.ok(memberships.length >= 2);
|
|
const denied = await request("/admin/brands/00000000-0000-0000-0000-000000000000/switch", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(denied.statusCode, 403);
|
|
});
|
|
|
|
test("brand switching isolates admin configuration, offerings, and public workspace", async () => {
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
|
});
|
|
assert.equal(login.statusCode, 201);
|
|
const defaultToken = JSON.parse(login.body).token;
|
|
const memberships = JSON.parse(
|
|
(
|
|
await request("/admin/brands", {
|
|
headers: { authorization: `Bearer ${defaultToken}` },
|
|
})
|
|
).body,
|
|
);
|
|
const doorsBrand = memberships.find((item) => item.brand.slug === "linjing-doors")?.brand;
|
|
assert.ok(doorsBrand);
|
|
|
|
const switched = await request(`/admin/brands/${doorsBrand.id}/switch`, {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${defaultToken}` },
|
|
});
|
|
assert.equal(switched.statusCode, 201);
|
|
const doorsToken = JSON.parse(switched.body).token;
|
|
|
|
const [
|
|
defaultConfig,
|
|
doorsConfig,
|
|
defaultOfferings,
|
|
doorsOfferings,
|
|
defaultAdminWorkspace,
|
|
doorsAdminWorkspace,
|
|
doorsWorkspace,
|
|
] = await Promise.all([
|
|
request("/admin/config/brand", {
|
|
headers: { authorization: `Bearer ${defaultToken}` },
|
|
}),
|
|
request("/admin/config/brand", {
|
|
headers: { authorization: `Bearer ${doorsToken}` },
|
|
}),
|
|
request("/admin/workspace/offerings", {
|
|
headers: { authorization: `Bearer ${defaultToken}` },
|
|
}),
|
|
request("/admin/workspace/offerings", {
|
|
headers: { authorization: `Bearer ${doorsToken}` },
|
|
}),
|
|
request("/admin/workspace", {
|
|
headers: { authorization: `Bearer ${defaultToken}` },
|
|
}),
|
|
request("/admin/workspace", {
|
|
headers: { authorization: `Bearer ${doorsToken}` },
|
|
}),
|
|
request("/public/workspace?brandSlug=linjing-doors"),
|
|
]);
|
|
assert.equal(defaultConfig.statusCode, 200);
|
|
assert.equal(doorsConfig.statusCode, 200);
|
|
assert.equal(JSON.parse(defaultConfig.body).id, brandId);
|
|
assert.equal(JSON.parse(doorsConfig.body).id, doorsBrand.id);
|
|
assert.equal(defaultOfferings.statusCode, 200);
|
|
assert.equal(doorsOfferings.statusCode, 200);
|
|
assert.notDeepEqual(
|
|
JSON.parse(defaultOfferings.body).map((item) => item.id),
|
|
JSON.parse(doorsOfferings.body).map((item) => item.id),
|
|
);
|
|
assert.equal(doorsWorkspace.statusCode, 200);
|
|
assert.equal(JSON.parse(doorsWorkspace.body).brand.id, doorsBrand.id);
|
|
assert.equal(JSON.parse(doorsWorkspace.body).template.key, "doors");
|
|
assert.equal(defaultAdminWorkspace.statusCode, 200);
|
|
assert.equal(doorsAdminWorkspace.statusCode, 200);
|
|
assert.equal(JSON.parse(defaultAdminWorkspace.body).templateContent.displayName, "阿成校园餐");
|
|
assert.equal(JSON.parse(doorsAdminWorkspace.body).templateContent.displayName, "林境建筑画册");
|
|
});
|
|
|
|
test("disabled brand membership blocks existing admin token", 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 admin = await prisma.adminUser.findUnique({ where: { username: "admin" } });
|
|
assert.ok(admin);
|
|
const membership = await prisma.brandMembership.findUnique({
|
|
where: { adminUserId_brandId: { adminUserId: admin.id, brandId } },
|
|
});
|
|
assert.ok(membership);
|
|
await prisma.brandMembership.update({ where: { id: membership.id }, data: { isEnabled: false } });
|
|
try {
|
|
const response = await request("/admin/workspace", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(response.statusCode, 403);
|
|
} finally {
|
|
await prisma.brandMembership.update({
|
|
where: { id: membership.id },
|
|
data: { isEnabled: true },
|
|
});
|
|
}
|
|
});
|
|
|
|
test("admin can read and update brand and service configuration", async () => {
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
|
});
|
|
const adminToken = JSON.parse(login.body).token;
|
|
const removedAdminRoute = await request("/admin/config/services", {
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
});
|
|
assert.equal(removedAdminRoute.statusCode, 404);
|
|
assert.ok(adminToken);
|
|
|
|
const unauthorized = await request("/admin/config/brand");
|
|
assert.equal(unauthorized.statusCode, 401);
|
|
|
|
const brandBefore = await prisma.brandProfile.findUnique({ where: { id: brandId } });
|
|
assert.ok(brandBefore);
|
|
const serviceBefore = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } });
|
|
assert.ok(serviceBefore);
|
|
let createdServiceId;
|
|
|
|
try {
|
|
const brand = await request("/admin/config/brand", {
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
});
|
|
assert.equal(brand.statusCode, 200);
|
|
assert.equal(JSON.parse(brand.body).id, brandId);
|
|
|
|
const updatedBrand = await request("/admin/config/brand", {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: {
|
|
description: "集成测试品牌简介",
|
|
contactPhone: "13800000000",
|
|
},
|
|
});
|
|
assert.equal(updatedBrand.statusCode, 200);
|
|
assert.equal(JSON.parse(updatedBrand.body).description, "集成测试品牌简介");
|
|
assert.equal(JSON.parse(updatedBrand.body).templateKey, brandBefore.templateKey);
|
|
const updatedConfig = JSON.parse(updatedBrand.body).config;
|
|
assert.equal(updatedConfig.slogan, "集成测试品牌简介");
|
|
|
|
const updatedService = await request(`/admin/workspace/offerings/${serviceBefore.id}`, {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: { priceText: "集成测试价格", sortOrder: 99 },
|
|
});
|
|
assert.equal(updatedService.statusCode, 200);
|
|
assert.equal(JSON.parse(updatedService.body).priceText, "集成测试价格");
|
|
assert.equal(JSON.parse(updatedService.body).sortOrder, 99);
|
|
const publicServices = await request("/public/offerings");
|
|
assert.equal(publicServices.statusCode, 200);
|
|
const projectedService = JSON.parse(publicServices.body).find(
|
|
(item) => item.id === serviceBefore.id,
|
|
);
|
|
assert.equal(projectedService.priceText, serviceBefore.priceText);
|
|
|
|
const listedServices = await request("/admin/workspace/offerings", {
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
});
|
|
assert.equal(listedServices.statusCode, 200);
|
|
assert.ok(JSON.parse(listedServices.body).some((item) => item.id === serviceBefore.id));
|
|
|
|
const createdService = await request("/admin/workspace/offerings", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: {
|
|
name: "集成测试通用服务",
|
|
description: "通用品牌服务",
|
|
kind: "service",
|
|
config: { duration: 60 },
|
|
},
|
|
});
|
|
assert.equal(createdService.statusCode, 201);
|
|
const createdServiceBody = JSON.parse(createdService.body);
|
|
createdServiceId = createdServiceBody.id;
|
|
assert.equal(createdServiceBody.kind, "service");
|
|
const createdOffering = await prisma.offering.findUnique({
|
|
where: { id: createdServiceBody.id },
|
|
});
|
|
assert.equal(createdOffering?.name, "集成测试通用服务");
|
|
} finally {
|
|
await prisma.brandProfile.update({
|
|
where: { id: brandId },
|
|
data: {
|
|
description: brandBefore.description,
|
|
contactPhone: brandBefore.contactPhone,
|
|
templateKey: brandBefore.templateKey,
|
|
},
|
|
});
|
|
await prisma.offering.update({
|
|
where: { id: serviceBefore.id },
|
|
data: { priceText: serviceBefore.priceText, sortOrder: serviceBefore.sortOrder },
|
|
});
|
|
if (createdServiceId) {
|
|
await prisma.offering.delete({ where: { id: createdServiceId } });
|
|
}
|
|
}
|
|
});
|
|
|
|
test("admin can update user-facing brand presentation without replacing other config", async () => {
|
|
assert.equal(
|
|
(await request("/admin/config/presentation", { method: "PATCH", payload: { home: {} } }))
|
|
.statusCode,
|
|
401,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await request("/admin/config/presentation", {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: { home: {} },
|
|
})
|
|
).statusCode,
|
|
403,
|
|
);
|
|
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 brand = await prisma.brandProfile.findUnique({ where: { id: brandId } });
|
|
assert.ok(brand);
|
|
const originalConfig = brand.config;
|
|
try {
|
|
const response = await request("/admin/config/presentation", {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: {
|
|
identity: { founder: "可编辑主理人", title: "品牌主理人", ignoredNumber: 123 },
|
|
home: { proofTitle: "用户可编辑的信任标题", ignoredNumber: 123 },
|
|
inquiry: { submitLabel: "开始沟通" },
|
|
},
|
|
});
|
|
assert.equal(response.statusCode, 200);
|
|
const presentation = JSON.parse(response.body).visualPresentation;
|
|
assert.equal(presentation.home.proofTitle, "用户可编辑的信任标题");
|
|
assert.equal(presentation.home.ignoredNumber, undefined);
|
|
assert.equal(presentation.inquiry.submitLabel, "开始沟通");
|
|
const runtime = await request("/public/workspace");
|
|
assert.notEqual(JSON.parse(runtime.body).brand.founder, "可编辑主理人");
|
|
assert.notEqual(JSON.parse(runtime.body).brand.title, "品牌主理人");
|
|
assert.notEqual(
|
|
JSON.parse(runtime.body).brand.visualPresentation.home.proofTitle,
|
|
"用户可编辑的信任标题",
|
|
);
|
|
} finally {
|
|
await prisma.brandProfile.update({ where: { id: brandId }, data: { config: originalConfig } });
|
|
}
|
|
});
|
|
|
|
test("admin can manage trust content", 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;
|
|
assert.equal((await request("/admin/config/trust-content")).statusCode, 401);
|
|
assert.equal(
|
|
(
|
|
await request("/admin/config/trust-content", {
|
|
method: "POST",
|
|
headers: { authorization: "Bearer invalid" },
|
|
payload: { type: "schedule", title: "安排", content: "时间" },
|
|
})
|
|
).statusCode,
|
|
401,
|
|
);
|
|
assert.equal(
|
|
(
|
|
await request("/admin/config/trust-content", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: { type: "schedule", title: "安排", content: "时间" },
|
|
})
|
|
).statusCode,
|
|
403,
|
|
);
|
|
const created = await request("/admin/config/trust-content", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { type: "credential", title: "关于我", content: "集成测试内容", summary: "测试摘要" },
|
|
});
|
|
assert.equal(created.statusCode, 201);
|
|
const id = JSON.parse(created.body).id;
|
|
const schedule = await request("/admin/config/trust-content", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: {
|
|
type: "schedule",
|
|
title: "每周营业安排",
|
|
summary: "周一至周五 17:00 - 22:30",
|
|
content: "周六、周日承接团体单",
|
|
},
|
|
});
|
|
assert.equal(schedule.statusCode, 201);
|
|
assert.equal(JSON.parse(schedule.body).summary, "周一至周五 17:00 - 22:30");
|
|
assert.equal(JSON.parse(schedule.body).content, "周六、周日承接团体单");
|
|
const unsupported = await request("/admin/config/trust-content", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { type: "unregistered-template-type", title: "不支持", content: "不应保存" },
|
|
});
|
|
assert.equal(unsupported.statusCode, 400);
|
|
const draft = await request("/admin/config/trust-content", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { type: "promise", title: "草稿", content: "不应公开", isPublished: false },
|
|
});
|
|
assert.equal(draft.statusCode, 201);
|
|
const publicContent = await request("/public/trust-content");
|
|
assert.equal(publicContent.statusCode, 200);
|
|
const publicItems = JSON.parse(publicContent.body);
|
|
assert.ok(!publicItems.some((item) => item.id === id));
|
|
assert.ok(!publicItems.some((item) => item.id === JSON.parse(draft.body).id));
|
|
try {
|
|
const list = await request("/admin/config/trust-content", {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(list.statusCode, 200);
|
|
const updated = await request(`/admin/config/trust-content/${id}`, {
|
|
method: "PATCH",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
payload: { content: "更新后的内容" },
|
|
});
|
|
assert.equal(updated.statusCode, 200);
|
|
assert.equal(JSON.parse(updated.body).content, "更新后的内容");
|
|
} finally {
|
|
await prisma.trustContent.delete({ where: { id: JSON.parse(schedule.body).id } });
|
|
const deleted = await request(`/admin/config/trust-content/${id}`, {
|
|
method: "DELETE",
|
|
headers: { authorization: `Bearer ${token}` },
|
|
});
|
|
assert.equal(deleted.statusCode, 200);
|
|
await prisma.trustContent.delete({ where: { id: JSON.parse(draft.body).id } });
|
|
}
|
|
});
|
|
|
|
test("customer booking endpoints require a valid customer session", async () => {
|
|
const missing = await request("/customer/bookings");
|
|
assert.equal(missing.statusCode, 401);
|
|
|
|
const list = await request("/customer/bookings", {
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
});
|
|
assert.equal(list.statusCode, 200);
|
|
assert.deepEqual(JSON.parse(list.body), []);
|
|
});
|
|
|
|
test("wechat login validates the request DTO before exchanging the code", async () => {
|
|
const response = await request("/customer/session/wechat", {
|
|
method: "POST",
|
|
payload: {},
|
|
});
|
|
assert.equal(response.statusCode, 400);
|
|
});
|
|
|
|
test("wechat login creates a customer session for the requested brand", async () => {
|
|
const doorsBrand = await prisma.brandProfile.findUnique({ where: { slug: "linjing-doors" } });
|
|
assert.ok(doorsBrand);
|
|
const sessionOpenid = `doors-login-${Date.now()}`;
|
|
const wechatAuth = app.get(WechatAuthService);
|
|
const originalExchangeCode = wechatAuth.exchangeCode;
|
|
wechatAuth.exchangeCode = async () => ({ openid: sessionOpenid });
|
|
try {
|
|
const response = await request("/customer/session/wechat?brandSlug=linjing-doors", {
|
|
method: "POST",
|
|
payload: { code: "test-code" },
|
|
});
|
|
assert.equal(response.statusCode, 201);
|
|
const identity = readIdentity(JSON.parse(response.body).token);
|
|
assert.equal(identity.brandId, doorsBrand.id);
|
|
assert.equal(identity.role, "customer");
|
|
assert.ok(
|
|
await prisma.customerUser.findUnique({
|
|
where: { brandId_openid: { brandId: doorsBrand.id, openid: sessionOpenid } },
|
|
}),
|
|
);
|
|
} finally {
|
|
wechatAuth.exchangeCode = originalExchangeCode;
|
|
await prisma.customerUser.deleteMany({ where: { openid: sessionOpenid } });
|
|
}
|
|
});
|
|
|
|
test("customer booking DTO rejects incomplete package requests", async () => {
|
|
const response = await request("/customer/bookings", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: {
|
|
requestType: "package",
|
|
customerName: "集成测试客户",
|
|
contactPreference: "wechat",
|
|
},
|
|
});
|
|
assert.equal(response.statusCode, 400);
|
|
assert.equal(JSON.parse(response.body).error.code, "HTTP_400");
|
|
});
|
|
|
|
test("customer can create a generic inquiry without food-specific fields", async () => {
|
|
const response = await request("/customer/bookings", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: {
|
|
requestType: "inquiry",
|
|
customerName: "个人品牌咨询客户",
|
|
wechatId: "inquiry-wechat",
|
|
contactPreference: "wechat",
|
|
requestedTime: "下周三 14:00",
|
|
note: "希望讨论品牌合作方案",
|
|
},
|
|
});
|
|
assert.equal(response.statusCode, 201);
|
|
const body = JSON.parse(response.body);
|
|
const booking = await prisma.booking.findUnique({ where: { bookingNo: body.bookingNo } });
|
|
assert.ok(booking);
|
|
assert.equal(booking.requestType, "inquiry");
|
|
createdBookingIds.push(booking.id);
|
|
});
|
|
|
|
test("customer can create and cancel a package booking", async () => {
|
|
const service = await prisma.offering.findFirst({
|
|
where: { brandId, isEnabled: true, priceAmount: { not: null } },
|
|
});
|
|
assert.ok(service);
|
|
const release = await prisma.brandRelease.findFirst({
|
|
where: { brandId, status: "published" },
|
|
orderBy: { version: "desc" },
|
|
});
|
|
const publishedOffering = release?.snapshot?.offerings?.find?.((item) => item.id === service.id);
|
|
assert.ok(publishedOffering);
|
|
await prisma.offering.update({
|
|
where: { id: service.id },
|
|
data: { priceAmount: service.priceAmount + 500, name: `${service.name}草稿` },
|
|
});
|
|
const created = await request("/customer/bookings", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: {
|
|
requestType: "package",
|
|
customerName: "集成测试客户",
|
|
wechatId: "integration-wechat",
|
|
contactPreference: "wechat",
|
|
items: [{ offeringId: service.id, quantity: 2 }],
|
|
},
|
|
});
|
|
await prisma.offering.update({
|
|
where: { id: service.id },
|
|
data: { priceAmount: service.priceAmount, name: service.name },
|
|
});
|
|
assert.equal(created.statusCode, 201);
|
|
const createdBody = JSON.parse(created.body);
|
|
assert.equal(createdBody.estimatedAmount, publishedOffering.priceAmount * 2);
|
|
const booking = await prisma.booking.findUnique({ where: { bookingNo: createdBody.bookingNo } });
|
|
assert.ok(booking);
|
|
assert.equal(booking.workflowKey, "booking.basic");
|
|
assert.equal(booking.currentState, "received");
|
|
assert.equal(booking.offeringId, service.id);
|
|
const bookingItem = await prisma.bookingItem.findFirst({ where: { bookingId: booking.id } });
|
|
assert.equal(bookingItem?.serviceNameSnapshot, publishedOffering.name);
|
|
const initialTransitions = await prisma.bookingStateTransition.findMany({
|
|
where: { bookingId: booking.id },
|
|
});
|
|
assert.equal(initialTransitions.length, 1);
|
|
assert.equal(initialTransitions[0].toState, "received");
|
|
createdBookingIds.push(booking.id);
|
|
|
|
const cancelled = await request(`/customer/bookings/${booking.id}/cancel`, {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
});
|
|
assert.equal(cancelled.statusCode, 201);
|
|
assert.equal(JSON.parse(cancelled.body).status, "cancelled");
|
|
const transitions = await prisma.bookingStateTransition.findMany({
|
|
where: { bookingId: booking.id },
|
|
orderBy: { createdAt: "asc" },
|
|
});
|
|
assert.deepEqual(
|
|
transitions.map((item) => item.toState),
|
|
["received", "cancelled"],
|
|
);
|
|
});
|
|
|
|
test("admin can advance booking status but cannot skip the state machine", async () => {
|
|
const service = await prisma.offering.findFirst({
|
|
where: { brandId, isEnabled: true, priceAmount: { not: null } },
|
|
});
|
|
assert.ok(service);
|
|
const created = await request("/customer/bookings", {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${customerToken}` },
|
|
payload: {
|
|
requestType: "package",
|
|
customerName: "状态测试客户",
|
|
phone: "13800000000",
|
|
contactPreference: "phone",
|
|
items: [{ offeringId: service.id, quantity: 1 }],
|
|
},
|
|
});
|
|
const booking = await prisma.booking.findUnique({
|
|
where: { bookingNo: JSON.parse(created.body).bookingNo },
|
|
});
|
|
assert.ok(booking);
|
|
createdBookingIds.push(booking.id);
|
|
|
|
const login = await request("/admin/session/login", {
|
|
method: "POST",
|
|
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
|
});
|
|
const adminToken = JSON.parse(login.body).token;
|
|
const contacting = await request(`/admin/bookings/${booking.id}/status`, {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: { status: "contacting", adminNote: "已联系客户" },
|
|
});
|
|
assert.equal(contacting.statusCode, 201);
|
|
assert.equal(JSON.parse(contacting.body).status, "contacting");
|
|
const contactingState = await prisma.booking.findUnique({ where: { id: booking.id } });
|
|
assert.equal(contactingState?.currentState, "contacting");
|
|
|
|
const skipped = await request(`/admin/bookings/${booking.id}/status`, {
|
|
method: "POST",
|
|
headers: { authorization: `Bearer ${adminToken}` },
|
|
payload: { status: "completed" },
|
|
});
|
|
assert.equal(skipped.statusCode, 400);
|
|
});
|
|
|
|
test("atelier template imports selected package and preserves draft publication isolation", async () => {
|
|
const slug = "atelier-acceptance-" + randomUUID();
|
|
const user = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
|
|
const originalOther = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } });
|
|
const brand = await prisma.brandProfile.create({
|
|
data: {
|
|
slug,
|
|
name: "品牌小程序工坊",
|
|
templateKey: "personal",
|
|
tagline: "独立开发者 · 品牌小程序构建",
|
|
description: "专注个人品牌表达、内容管理与咨询承接。",
|
|
config: {
|
|
founder: "验收主理人",
|
|
title: "产品设计 / 全栈开发",
|
|
visualPresentation: { home: { subtitle: "保留已有品牌说明" } },
|
|
},
|
|
},
|
|
});
|
|
const headers = {
|
|
authorization: `Bearer ${signIdentity({ subject: user.id, brandId: brand.id, role: "admin" })}`,
|
|
};
|
|
await prisma.brandMembership.create({
|
|
data: { brandId: brand.id, adminUserId: user.id, role: "owner" },
|
|
});
|
|
const json = async (url, options = {}) => {
|
|
const response = await request(url, options);
|
|
assert.ok(response.statusCode < 300, response.body);
|
|
return JSON.parse(response.body);
|
|
};
|
|
try {
|
|
for (const path of ["preview", "import"]) {
|
|
const method = path === "import" ? "POST" : "GET";
|
|
const url = "/admin/workspace/sample-content/" + path;
|
|
assert.equal((await request(url, { method })).statusCode, 401);
|
|
assert.equal(
|
|
(await request(url, { method, headers: { authorization: "Bearer invalid" } })).statusCode,
|
|
401,
|
|
);
|
|
assert.equal(
|
|
(await request(url, { method, headers: { authorization: `Bearer ${customerToken}` } }))
|
|
.statusCode,
|
|
403,
|
|
);
|
|
}
|
|
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",
|
|
headers: { ...headers, ...packageArchive.headers },
|
|
rawPayload: packageArchive.payload,
|
|
});
|
|
assert.equal(importedPackage.statusCode, 201, importedPackage.body);
|
|
const selectedPackage = JSON.parse(importedPackage.body).version;
|
|
const publishedPackage = await request(`/admin/templates/${selectedPackage.id}/publish`, {
|
|
method: "POST",
|
|
headers,
|
|
});
|
|
assert.equal(publishedPackage.statusCode, 201, publishedPackage.body);
|
|
const installation = await json("/admin/workspace/install", {
|
|
method: "POST",
|
|
headers,
|
|
payload: { templateKey: "personal", templatePackageVersionId: selectedPackage.id },
|
|
});
|
|
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", {
|
|
method: "POST",
|
|
headers,
|
|
payload: {
|
|
templatePackageVersionId: selectedPackage.id,
|
|
strategy: "missing_only",
|
|
confirm: true,
|
|
},
|
|
});
|
|
const imported = await json("/admin/config/brand", { headers });
|
|
assert.equal(imported.config.visualPresentation.home.subtitle, "保留已有品牌说明");
|
|
assert.equal(imported.config.atelier.deliverables.length, 7);
|
|
const form = await prisma.inquiryForm.findFirstOrThrow({ where: { brandId: brand.id } });
|
|
assert.equal(form.name, "品牌小程序需求意向单");
|
|
assert.deepEqual(
|
|
form.fieldsSnapshot.map((field) => field.key),
|
|
["name", "industry", "needs", "timeline", "contact"],
|
|
);
|
|
const duplicateImport = await request("/admin/workspace/sample-content/import", {
|
|
method: "POST",
|
|
headers,
|
|
payload: {
|
|
templatePackageVersionId: selectedPackage.id,
|
|
strategy: "missing_only",
|
|
confirm: true,
|
|
},
|
|
});
|
|
assert.equal(duplicateImport.statusCode, 201);
|
|
assert.equal(JSON.parse(duplicateImport.body).alreadyImported, true);
|
|
const manifest = (await json("/admin/workspace", { headers })).templateContent;
|
|
const exampleOffering = await prisma.offering.findFirstOrThrow({
|
|
where: { brandId: brand.id },
|
|
});
|
|
assert.match(exampleOffering.coverUrl, /^\/assets\/cases\//);
|
|
const sampleRuntime = await json("/admin/workspace/preview", { headers });
|
|
for (const item of sampleRuntime.offerings) {
|
|
assert.equal(item.presentation.categoryLabel, "案例展示");
|
|
assert.equal(item.priceText, "按需求确认范围与报价");
|
|
assert.ok(item.presentation.spaceType);
|
|
assert.ok(item.presentation.details.background);
|
|
assert.ok(item.presentation.details.designConcept);
|
|
assert.ok(item.presentation.details.crafts.length);
|
|
assert.ok(item.presentation.details.materialsList.length);
|
|
}
|
|
const offeringFields = [
|
|
...new Map(
|
|
manifest.admin.sections
|
|
.flatMap((section) => section.fields)
|
|
.filter((field) => field.binding.startsWith("offering."))
|
|
.map((field) => [field.binding, field]),
|
|
).values(),
|
|
];
|
|
const offeringPatch = { config: structuredClone(exampleOffering.config) };
|
|
for (const field of offeringFields) {
|
|
const token = "atelier-offering-" + 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/atelier-case.jpg"
|
|
: field.input === "select"
|
|
? field.options[0].value
|
|
: token;
|
|
const path = field.binding.split(".").slice(1);
|
|
const last = path.pop();
|
|
const parent = path.reduce((current, key) => (current[key] ??= {}), offeringPatch);
|
|
parent[last] = value;
|
|
}
|
|
await json("/admin/workspace/offerings/" + exampleOffering.id, {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: offeringPatch,
|
|
});
|
|
const storedOffering = await prisma.offering.findUniqueOrThrow({
|
|
where: { id: exampleOffering.id },
|
|
});
|
|
const draftOffering = (await json("/admin/workspace/preview", { headers })).offerings.find(
|
|
(item) => item.id === exampleOffering.id,
|
|
);
|
|
const { runtimeContractForBinding } = await import("@personal-brand/types");
|
|
for (const field of offeringFields) {
|
|
const path = field.binding.split(".").slice(1);
|
|
const read = (value, path) => path.reduce((current, key) => current?.[key], value);
|
|
assert.deepEqual(
|
|
read(storedOffering, path),
|
|
read(offeringPatch, path),
|
|
field.binding + " offering persistence",
|
|
);
|
|
const runtimePath =
|
|
field.binding === "offering.config.detailHero"
|
|
? ["presentation", "heroImage"]
|
|
: runtimeContractForBinding(field.binding)
|
|
.runtimePath.replace("workspace.offerings[].", "")
|
|
.split(".");
|
|
assert.deepEqual(
|
|
read(draftOffering, runtimePath),
|
|
read(offeringPatch, path),
|
|
field.binding + " offering projection",
|
|
);
|
|
}
|
|
await prisma.offering.update({
|
|
where: { id: exampleOffering.id },
|
|
data: {
|
|
name: exampleOffering.name,
|
|
summary: exampleOffering.summary,
|
|
coverUrl: exampleOffering.coverUrl,
|
|
priceText: exampleOffering.priceText,
|
|
config: exampleOffering.config,
|
|
},
|
|
});
|
|
const defaults = structuredClone(imported.config);
|
|
const patch = { config: structuredClone(defaults) };
|
|
delete patch.config.visualTemplateKey;
|
|
const read = (value, path) => path.reduce((current, key) => current?.[key], value);
|
|
const write = (value, path, replacement) => {
|
|
const last = path.pop();
|
|
const parent = path.reduce((current, key) => (current[key] ??= {}), value);
|
|
parent[last] = replacement;
|
|
};
|
|
const fields = [
|
|
...new Map(
|
|
manifest.admin.sections
|
|
.flatMap((section) => section.fields)
|
|
.filter((field) => field.binding.startsWith("brand."))
|
|
.map((field) => [field.binding, field]),
|
|
).values(),
|
|
];
|
|
for (const field of fields) {
|
|
const token = "验收-" + field.key;
|
|
const value =
|
|
field.input === "list"
|
|
? [
|
|
Object.fromEntries(
|
|
field.itemFields.map((child) => [child.key, token + "-" + child.key]),
|
|
),
|
|
]
|
|
: field.input === "image"
|
|
? "https://example.com/atelier-avatar.jpg"
|
|
: token;
|
|
write(patch, field.binding.split(".").slice(1), value);
|
|
}
|
|
await json("/admin/config/brand", { method: "PATCH", headers, payload: patch });
|
|
const saved = await json("/admin/config/brand", { headers });
|
|
const draft = await json("/admin/workspace/preview", { headers });
|
|
for (const field of fields) {
|
|
const path = field.binding.split(".").slice(1);
|
|
assert.deepEqual(read(saved, path), read(patch, path), field.binding + " persistence");
|
|
assert.deepEqual(
|
|
read(draft.brand, path[0] === "config" ? path.slice(1) : path),
|
|
read(patch, path),
|
|
field.binding + " preview",
|
|
);
|
|
}
|
|
assert.equal((await json("/public/workspace?brandSlug=" + slug)).brand, null);
|
|
// 恢复设计基线用于视觉回归,再验证发布后的草稿隔离。
|
|
await json("/admin/config/brand", {
|
|
method: "PATCH",
|
|
headers,
|
|
payload: { config: defaults, avatarUrl: null, contactWechat: null },
|
|
});
|
|
await prisma.trustContent.updateMany({
|
|
where: { brandId: brand.id },
|
|
data: { isPublished: true },
|
|
});
|
|
const readiness = await json("/admin/releases/readiness", { headers });
|
|
assert.equal(
|
|
readiness.checks.find((check) => check.key === "template-package-version")?.passed,
|
|
true,
|
|
);
|
|
await json("/admin/releases/publish", {
|
|
method: "POST",
|
|
headers,
|
|
payload: { note: "宣传模板独立品牌验收" },
|
|
});
|
|
const release = await prisma.brandRelease.findFirstOrThrow({
|
|
where: { brandId: brand.id, status: "published" },
|
|
orderBy: { version: "desc" },
|
|
});
|
|
assert.equal(release.snapshot.installation.templatePackageVersionId, selectedPackage.id);
|
|
assert.equal(release.snapshot.templatePackageManifest.packageKey, selectedPackage.packageKey);
|
|
const published = await json("/public/workspace?brandSlug=" + slug);
|
|
assert.equal(published.brand.visualPresentation.home.subtitle, "保留已有品牌说明");
|
|
const next = structuredClone(defaults);
|
|
next.visualPresentation.home.title = "仅草稿可见的新标题";
|
|
await json("/admin/config/brand", { method: "PATCH", headers, payload: { config: next } });
|
|
assert.equal(
|
|
(await json("/admin/workspace/preview", { headers })).brand.visualPresentation.home.title,
|
|
"仅草稿可见的新标题",
|
|
);
|
|
assert.equal(
|
|
(await json("/public/workspace?brandSlug=" + slug)).brand.visualPresentation.home.title,
|
|
defaults.visualPresentation.home.title,
|
|
);
|
|
await json("/admin/releases/publish", {
|
|
method: "POST",
|
|
headers,
|
|
payload: { note: "发布新标题" },
|
|
});
|
|
assert.equal(
|
|
(await json("/public/workspace?brandSlug=" + slug)).brand.visualPresentation.home.title,
|
|
"仅草稿可见的新标题",
|
|
);
|
|
const atelierCustomer = await prisma.customerUser.create({
|
|
data: { brandId: brand.id, openid: "atelier-test-customer" },
|
|
});
|
|
const customerHeaders = {
|
|
authorization: `Bearer ${signIdentity({ subject: "atelier-test-customer", brandId: brand.id, role: "customer" })}`,
|
|
};
|
|
assert.equal(
|
|
(
|
|
await request("/customer/inquiry-submissions", {
|
|
method: "POST",
|
|
headers: customerHeaders,
|
|
payload: { formId: form.id, values: {} },
|
|
})
|
|
).statusCode,
|
|
400,
|
|
);
|
|
const submitted = await json("/customer/inquiry-submissions", {
|
|
method: "POST",
|
|
headers: customerHeaders,
|
|
payload: {
|
|
formId: form.id,
|
|
values: {
|
|
name: "验收品牌",
|
|
industry: "独立设计 / 建筑",
|
|
needs: "展示作品与承接合作",
|
|
timeline: "先期评估",
|
|
contact: "acceptance_wechat",
|
|
},
|
|
},
|
|
});
|
|
assert.ok(submitted.id);
|
|
assert.equal(
|
|
(await prisma.inquirySubmission.findUniqueOrThrow({ where: { id: submitted.id } })).brandId,
|
|
brand.id,
|
|
);
|
|
assert.deepEqual(
|
|
(await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } })).config,
|
|
originalOther.config,
|
|
);
|
|
if (process.env.ATELIER_ACCEPTANCE_OUTPUT) {
|
|
const { mkdir, writeFile } = await import("node:fs/promises");
|
|
await mkdir(process.env.ATELIER_ACCEPTANCE_OUTPUT, { recursive: true });
|
|
await writeFile(
|
|
process.env.ATELIER_ACCEPTANCE_OUTPUT + "/published-runtime.json",
|
|
JSON.stringify(published, null, 2),
|
|
);
|
|
}
|
|
} finally {
|
|
await prisma.customerUser.deleteMany({ where: { brandId: brand.id } });
|
|
await prisma.brandProfile.delete({ where: { id: brand.id } });
|
|
}
|
|
});
|