feat: 增加模板版本独立预览入口
This commit is contained in:
1 parent
413413efda
commit
6edde5a8d6
15 files changed
+781
-14
No files matched your search
@@ -1,14 +1,20 @@
|
||||
import { Controller, Get, Param, Post, Query, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { ListTemplatePackagesQueryDto } from "./admin-template-package.dto.js";
|
||||
import {
|
||||
ListTemplatePackagesQueryDto,
|
||||
PreviewTemplatePackageQueryDto,
|
||||
} from "./admin-template-package.dto.js";
|
||||
import { AdminTemplatePackageService } from "./admin-template-package.service.js";
|
||||
|
||||
import { AdminTemplatePreviewService } from "./admin-template-preview.service.js";
|
||||
|
||||
@Controller("admin/templates")
|
||||
export class AdminTemplatePackageController {
|
||||
constructor(
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly templates: AdminTemplatePackageService,
|
||||
private readonly previews: AdminTemplatePreviewService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@@ -40,4 +46,12 @@ export class AdminTemplatePackageController {
|
||||
audit(@Param("id") id: string): ReturnType<AdminTemplatePackageService["audit"]> {
|
||||
return this.templates.audit(id);
|
||||
}
|
||||
|
||||
@Get(":id/preview")
|
||||
preview(
|
||||
@Param("id") id: string,
|
||||
@Query() query: PreviewTemplatePackageQueryDto,
|
||||
): ReturnType<AdminTemplatePreviewService["preview"]> {
|
||||
return this.previews.preview(id, query.industry);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Type } from "class-transformer";
|
||||
import { IsInt, IsOptional, Max, Min } from "class-validator";
|
||||
import { IsInt, IsNotEmpty, IsOptional, IsString, Max, Min } from "class-validator";
|
||||
|
||||
export class ListTemplatePackagesQueryDto {
|
||||
@IsOptional()
|
||||
@@ -15,3 +15,9 @@ export class ListTemplatePackagesQueryDto {
|
||||
@Max(100)
|
||||
pageSize = 20;
|
||||
}
|
||||
|
||||
export class PreviewTemplatePackageQueryDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
industry!: string;
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
PayloadTooLargeException,
|
||||
} from "@nestjs/common";
|
||||
import { validateTemplatePackageManifest } from "@personal-brand/config";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { createHash } from "node:crypto";
|
||||
import { execFile } from "node:child_process";
|
||||
@@ -35,6 +34,16 @@ type ChecksumFile = {
|
||||
files: Array<{ path: string; bytes: number; sha256: string }>;
|
||||
};
|
||||
|
||||
type JsonRecord = Record<string, unknown>;
|
||||
|
||||
function record(value: unknown): JsonRecord {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};
|
||||
}
|
||||
|
||||
function array(value: unknown): unknown[] {
|
||||
return Array.isArray(value) ? value : [];
|
||||
}
|
||||
|
||||
function sha256(value: Buffer | string): string {
|
||||
return createHash("sha256").update(value).digest("hex");
|
||||
}
|
||||
@@ -137,6 +146,7 @@ export class AdminTemplatePackageService {
|
||||
contentChecksum: true,
|
||||
archiveChecksum: true,
|
||||
validationReport: true,
|
||||
manifestSnapshot: true,
|
||||
importedAt: true,
|
||||
updatedAt: true,
|
||||
templatePackage: { select: { id: true } },
|
||||
@@ -145,9 +155,21 @@ export class AdminTemplatePackageService {
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
items: versions.map(({ templatePackage, ...version }) => ({
|
||||
items: versions.map(({ templatePackage, manifestSnapshot, ...version }) => ({
|
||||
...version,
|
||||
templatePackageId: templatePackage.id,
|
||||
manifestSummary: {
|
||||
runtimeContract:
|
||||
typeof record(manifestSnapshot).runtimeContract === "string"
|
||||
? (record(manifestSnapshot).runtimeContract as string)
|
||||
: "",
|
||||
supportedIndustryTemplates: array(
|
||||
record(manifestSnapshot).supportedIndustryTemplates,
|
||||
).filter((item): item is string => typeof item === "string"),
|
||||
requiredCapabilities: array(record(manifestSnapshot).requiredCapabilities).filter(
|
||||
(item): item is string => typeof item === "string",
|
||||
),
|
||||
},
|
||||
})),
|
||||
page,
|
||||
pageSize,
|
||||
@@ -164,7 +186,7 @@ export class AdminTemplatePackageService {
|
||||
let storedArtifactPath: string | null = null;
|
||||
try {
|
||||
for await (const chunk of part.file) {
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
const buffer = Buffer.from(chunk as Uint8Array);
|
||||
bytes += buffer.length;
|
||||
if (bytes > MAX_ARCHIVE_BYTES) throw new PayloadTooLargeException("模板包超过 50 MB 限制");
|
||||
chunks.push(buffer);
|
||||
@@ -272,13 +294,13 @@ export class AdminTemplatePackageService {
|
||||
version: manifest.version,
|
||||
displayName: manifest.displayName,
|
||||
visualTemplateKey: manifest.visualTemplateKey ?? null,
|
||||
manifestSnapshot: manifest as unknown as Prisma.InputJsonValue,
|
||||
manifestSnapshot: manifest,
|
||||
validationReport: {
|
||||
formatVersion: "1",
|
||||
errors: [],
|
||||
fileCount: files.length,
|
||||
extractedBytes: files.reduce((total, file) => total + file.bytes, 0),
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
contentChecksum: checksums.contentChecksum,
|
||||
archiveChecksum,
|
||||
artifactPath,
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
|
||||
import {
|
||||
capabilityRegistry,
|
||||
getBrandTemplate,
|
||||
getTemplatePackageManifest,
|
||||
getVisualTemplate,
|
||||
getVisualTemplateManifest,
|
||||
validateTemplatePackageManifest,
|
||||
} from "@personal-brand/config";
|
||||
import type { TemplatePackageManifest, TemplateSampleContent } from "@personal-brand/config";
|
||||
import { validateFieldSnapshot } from "@personal-brand/validation";
|
||||
import type { BrandReleaseSnapshot } from "../../brand-release.service.js";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { assemblePublicWorkspace } from "../public/public-workspace.snapshot-assembler.js";
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
function array(value: unknown): unknown[] {
|
||||
return Array.isArray(value) ? value : [];
|
||||
}
|
||||
|
||||
// 预览投影会遍历这些嵌套声明,必须先校验结构,不能只检查顶层数组。
|
||||
function hasPreviewStructure(manifest: Record<string, unknown>): boolean {
|
||||
const records = (value: unknown): value is Record<string, unknown>[] =>
|
||||
Array.isArray(value) &&
|
||||
value.every((item) => item !== null && typeof item === "object" && !Array.isArray(item));
|
||||
const strings = (item: Record<string, unknown>, keys: string[]) =>
|
||||
keys.every((key) => typeof item[key] === "string" && String(item[key]).trim().length > 0);
|
||||
const fields = (value: unknown) =>
|
||||
records(value) &&
|
||||
value.every(
|
||||
(field) =>
|
||||
strings(field, ["key", "binding"]) &&
|
||||
(field.options === undefined ||
|
||||
(records(field.options) &&
|
||||
field.options.every((option) => strings(option, ["value", "label"])))),
|
||||
);
|
||||
return (
|
||||
records(manifest.dataSlots) &&
|
||||
manifest.dataSlots.every(
|
||||
(slot) => strings(slot, ["key", "source"]) && typeof slot.required === "boolean",
|
||||
) &&
|
||||
records(manifest.navigation) &&
|
||||
manifest.navigation.every((tab) => strings(tab, ["key", "label", "page"])) &&
|
||||
records(record(manifest.admin).sections) &&
|
||||
(record(manifest.admin).sections as Record<string, unknown>[]).every(
|
||||
(section) => strings(section, ["key", "target"]) && fields(section.fields),
|
||||
) &&
|
||||
(manifest.templateFields === undefined ||
|
||||
(records(manifest.templateFields) &&
|
||||
manifest.templateFields.every((field) => strings(field, ["key"])))) &&
|
||||
(manifest.trustContentTypes === undefined ||
|
||||
(records(manifest.trustContentTypes) &&
|
||||
manifest.trustContentTypes.every((declaration) => strings(declaration, ["type"]))))
|
||||
);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminTemplatePreviewService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
async preview(id: string, industry: string) {
|
||||
const version = await this.prisma.templatePackageVersion.findUnique({ where: { id } });
|
||||
if (!version) throw new BadRequestException("模板版本不存在");
|
||||
if (version.status === "retired") throw new ConflictException("已撤回的模板版本不能创建新预览");
|
||||
if (version.status !== "imported" && version.status !== "published")
|
||||
throw new ConflictException(`模板版本当前状态为 ${version.status},不能预览`);
|
||||
|
||||
const rawManifest = record(version.manifestSnapshot);
|
||||
const packageKey = version.packageKey;
|
||||
const visualTemplateKey =
|
||||
typeof rawManifest.visualTemplateKey === "string"
|
||||
? rawManifest.visualTemplateKey
|
||||
: packageKey;
|
||||
const manifest = {
|
||||
...rawManifest,
|
||||
visualTemplateKey,
|
||||
} as unknown as TemplatePackageManifest;
|
||||
try {
|
||||
if (validateTemplatePackageManifest(manifest).length || !hasPreviewStructure(rawManifest)) {
|
||||
throw new Error("Invalid manifest");
|
||||
}
|
||||
} catch {
|
||||
throw new BadRequestException("模板版本的 manifest 不符合预览契约");
|
||||
}
|
||||
if (manifest.packageKey !== packageKey || manifest.version !== version.version)
|
||||
throw new BadRequestException("模板版本与 manifest 元数据不一致");
|
||||
const industryTemplate = getBrandTemplate(industry);
|
||||
const blockers: string[] = [];
|
||||
if (!industryTemplate) blockers.push(`行业模板 ${industry} 不存在`);
|
||||
if (
|
||||
!Array.isArray(rawManifest.supportedIndustryTemplates) ||
|
||||
!rawManifest.supportedIndustryTemplates.includes(industry)
|
||||
) {
|
||||
blockers.push("该模板版本不支持所选行业");
|
||||
}
|
||||
if (rawManifest.runtimeContract !== "1.0")
|
||||
blockers.push("Runtime contract 不受当前预览运行时支持");
|
||||
|
||||
const trustedManifest = getTemplatePackageManifest(packageKey);
|
||||
if (
|
||||
!trustedManifest ||
|
||||
trustedManifest.version !== version.version ||
|
||||
trustedManifest.visualTemplateKey !== visualTemplateKey
|
||||
) {
|
||||
blockers.push("模板声明的 renderer 尚未部署到当前平台");
|
||||
}
|
||||
const requiredCapabilities = array(rawManifest.requiredCapabilities).filter(
|
||||
(key): key is keyof typeof capabilityRegistry =>
|
||||
typeof key === "string" && Object.hasOwn(capabilityRegistry, key),
|
||||
);
|
||||
if (requiredCapabilities.length !== array(rawManifest.requiredCapabilities).length)
|
||||
blockers.push("模板依赖了当前平台未注册的 capability");
|
||||
if (
|
||||
industryTemplate &&
|
||||
requiredCapabilities.some((key) => !industryTemplate.capabilities.includes(key))
|
||||
) {
|
||||
blockers.push("模板依赖的 capability 与所选行业不兼容");
|
||||
}
|
||||
|
||||
const sample = record(rawManifest.sampleContent)[industry] as TemplateSampleContent | undefined;
|
||||
const missingSampleSlots = this.missingSampleSlots(manifest, sample);
|
||||
if (missingSampleSlots.length)
|
||||
blockers.push(`preview sample 缺少必需数据:${missingSampleSlots.join("、")}`);
|
||||
if (sample?.templateKey !== industry) blockers.push("sample 所属行业与所选行业不一致");
|
||||
if (!Array.isArray(sample?.fields) || validateFieldSnapshot(sample.fields).length)
|
||||
blockers.push("sample 咨询字段不符合表单契约");
|
||||
if (
|
||||
!Array.isArray(sample?.offerings) ||
|
||||
sample.offerings.some(
|
||||
(item) =>
|
||||
!item ||
|
||||
typeof item.name !== "string" ||
|
||||
!item.name.trim() ||
|
||||
!["service", "product", "package", "subscription"].includes(item.kind) ||
|
||||
typeof item.summary !== "string" ||
|
||||
typeof item.categoryKey !== "string",
|
||||
)
|
||||
)
|
||||
blockers.push("sample 业务记录不完整");
|
||||
if (
|
||||
!Array.isArray(sample?.trustContent) ||
|
||||
sample.trustContent.some(
|
||||
(item) =>
|
||||
!item ||
|
||||
typeof item.title !== "string" ||
|
||||
typeof item.content !== "string" ||
|
||||
!manifest.trustContentTypes?.some((declaration) => declaration.type === item.type),
|
||||
)
|
||||
)
|
||||
blockers.push("sample 信任记录不符合模板声明");
|
||||
if (blockers.length) {
|
||||
throw new BadRequestException(`模板预览被阻断:${blockers.join(";")}`);
|
||||
}
|
||||
|
||||
const workspace = this.buildSampleWorkspace(version.id, manifest, industryTemplate!, sample!);
|
||||
return {
|
||||
template: {
|
||||
id: version.id,
|
||||
packageKey,
|
||||
version: version.version,
|
||||
displayName: version.displayName,
|
||||
status: version.status,
|
||||
contentChecksum: version.contentChecksum,
|
||||
visualTemplateKey,
|
||||
navigation: manifest.navigation.map(
|
||||
(tab: TemplatePackageManifest["navigation"][number]) => ({
|
||||
key: tab.key,
|
||||
label: tab.label,
|
||||
page: tab.page,
|
||||
}),
|
||||
),
|
||||
pages: Object.keys(manifest.entrypoints),
|
||||
},
|
||||
industry: {
|
||||
key: industryTemplate!.key,
|
||||
version: industryTemplate!.version,
|
||||
name: industryTemplate!.name,
|
||||
},
|
||||
compatibility: {
|
||||
runtimeContract: manifest.runtimeContract,
|
||||
renderer: { key: visualTemplateKey, version: version.version, trusted: true },
|
||||
requiredCapabilities,
|
||||
missingSampleSlots: [],
|
||||
},
|
||||
workspace,
|
||||
};
|
||||
}
|
||||
|
||||
private missingSampleSlots(
|
||||
manifest: TemplatePackageManifest,
|
||||
sample: TemplateSampleContent | undefined,
|
||||
): string[] {
|
||||
if (!sample) return ["preview sample"];
|
||||
const offerings = Array.isArray(sample.offerings) ? sample.offerings : [];
|
||||
const trustContent = Array.isArray(sample.trustContent) ? sample.trustContent : [];
|
||||
const fields = Array.isArray(sample.fields) ? sample.fields : [];
|
||||
const missing: string[] = [];
|
||||
for (const slot of manifest.dataSlots.filter((item) => item.required)) {
|
||||
const count =
|
||||
slot.source === "offering"
|
||||
? offerings.length
|
||||
: slot.source === "trust"
|
||||
? trustContent.length
|
||||
: slot.source === "inquiry"
|
||||
? fields.length
|
||||
: slot.source === "brand"
|
||||
? 1
|
||||
: slot.source === "records"
|
||||
? 1
|
||||
: 0;
|
||||
if (!count) missing.push(slot.key);
|
||||
}
|
||||
if (typeof sample.inquiryFormName !== "string" || !sample.inquiryFormName.trim())
|
||||
missing.push("inquiry.form.name");
|
||||
if (!sample.capabilityKey || !Object.hasOwn(capabilityRegistry, sample.capabilityKey))
|
||||
missing.push("capability");
|
||||
return missing;
|
||||
}
|
||||
|
||||
private buildSampleWorkspace(
|
||||
versionId: string,
|
||||
manifest: TemplatePackageManifest,
|
||||
industryTemplate: NonNullable<ReturnType<typeof getBrandTemplate>>,
|
||||
sample: TemplateSampleContent,
|
||||
) {
|
||||
const brandConfig = record(sample.brandConfig);
|
||||
const visualTemplateKey = manifest.visualTemplateKey;
|
||||
const brand = {
|
||||
id: `template-preview:${versionId}`,
|
||||
slug: `template-preview-${manifest.packageKey}`,
|
||||
name: `${manifest.displayName}示例品牌`,
|
||||
templateKey: industryTemplate.key,
|
||||
tagline: `${industryTemplate.name}模板示例`,
|
||||
description: "这是模板预览数据,不属于任何真实品牌。",
|
||||
avatarUrl: null,
|
||||
coverUrl: null,
|
||||
hours: "示例营业时间",
|
||||
address: "示例服务范围",
|
||||
deliveryNote: "预览模式不会提交咨询或创建客户记录。",
|
||||
contactPhone: null,
|
||||
contactWechat: null,
|
||||
config: { ...brandConfig, visualTemplateKey },
|
||||
};
|
||||
const snapshot: BrandReleaseSnapshot = {
|
||||
schemaVersion: "1.0.0",
|
||||
generatedAt: new Date(0).toISOString(),
|
||||
templateKey: industryTemplate.key,
|
||||
templateDefinition: industryTemplate,
|
||||
visualTemplateDefinition: getVisualTemplate(visualTemplateKey) ?? null,
|
||||
visualTemplateManifest: getVisualTemplateManifest(visualTemplateKey) ?? null,
|
||||
templatePackageManifest: manifest,
|
||||
brand,
|
||||
installation: {
|
||||
templateKey: industryTemplate.key,
|
||||
templateVersion: industryTemplate.version,
|
||||
},
|
||||
fields: [],
|
||||
offerings: sample.offerings.map((item, sortOrder) => ({
|
||||
id: `template-preview:${versionId}:offering:${sortOrder + 1}`,
|
||||
...item,
|
||||
isEnabled: true,
|
||||
sortOrder,
|
||||
config: { ...record(item.config), categoryKey: item.categoryKey },
|
||||
})),
|
||||
forms: [
|
||||
{
|
||||
id: `template-preview:${versionId}:inquiry`,
|
||||
name: sample.inquiryFormName,
|
||||
isEnabled: true,
|
||||
purpose: sample.capabilityKey === "booking" ? "booking" : "inquiry",
|
||||
targetType: "brand",
|
||||
offeringId: null,
|
||||
submissionAction: "create-inquiry",
|
||||
fieldsSnapshot: sample.fields,
|
||||
},
|
||||
],
|
||||
trustContents: sample.trustContent.map((item, sortOrder) => ({
|
||||
id: `template-preview:${versionId}:trust:${sortOrder + 1}`,
|
||||
...item,
|
||||
isPublished: true,
|
||||
sortOrder,
|
||||
})),
|
||||
capabilities: array(manifest.requiredCapabilities).map((key) => ({
|
||||
capabilityKey: key,
|
||||
capabilityVersion:
|
||||
typeof capabilityRegistry[key as keyof typeof capabilityRegistry]?.version === "string"
|
||||
? capabilityRegistry[key as keyof typeof capabilityRegistry].version
|
||||
: "1.0.0",
|
||||
status: "enabled",
|
||||
config: {},
|
||||
})),
|
||||
};
|
||||
return assemblePublicWorkspace({ release: null, snapshot, draftSnapshot: snapshot });
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@ import { AdminUploadController } from "./admin-upload.controller.js";
|
||||
import { AdminTemplatePackageController } from "./admin-template-package.controller.js";
|
||||
import { AdminTemplatePackageService } from "./admin-template-package.service.js";
|
||||
|
||||
import { AdminTemplatePreviewService } from "./admin-template-preview.service.js";
|
||||
|
||||
@Module({
|
||||
imports: [InfrastructureModule, BookingModule],
|
||||
controllers: [
|
||||
@@ -35,6 +37,7 @@ import { AdminTemplatePackageService } from "./admin-template-package.service.js
|
||||
AdminMiniAppUploadService,
|
||||
AdminUploadService,
|
||||
AdminTemplatePackageService,
|
||||
AdminTemplatePreviewService,
|
||||
],
|
||||
})
|
||||
export class AdminModule {}
|
||||
@@ -11,6 +11,7 @@ import { AdminTemplateController } from "../src/modules/workspace/admin-template
|
||||
import { AdminCapabilityController } from "../src/modules/workspace/admin-capability.controller.js";
|
||||
import { AdminOfferingController } from "../src/modules/workspace/admin-offering.controller.js";
|
||||
import { AdminInquiryController } from "../src/modules/workspace/admin-inquiry.controller.js";
|
||||
import { AdminTemplatePackageController } from "../src/modules/admin/admin-template-package.controller.js";
|
||||
|
||||
const expectedRoutes = new Set([
|
||||
"GET /admin/workspace",
|
||||
@@ -38,6 +39,12 @@ const expectedRoutes = new Set([
|
||||
"GET /admin/uploads/config",
|
||||
"POST /admin/uploads/presign",
|
||||
"PUT /admin/uploads/local",
|
||||
"GET /admin/templates",
|
||||
"POST /admin/templates/import",
|
||||
"POST /admin/templates/:id/publish",
|
||||
"POST /admin/templates/:id/retire",
|
||||
"GET /admin/templates/:id/audit",
|
||||
"GET /admin/templates/:id/preview",
|
||||
]);
|
||||
|
||||
test("refactored admin controllers preserve their declared API routes", () => {
|
||||
@@ -49,6 +56,7 @@ test("refactored admin controllers preserve their declared API routes", () => {
|
||||
AdminInquiryController,
|
||||
AdminUploadController,
|
||||
AdminLocalUploadController,
|
||||
AdminTemplatePackageController,
|
||||
];
|
||||
const scanner = new MetadataScanner();
|
||||
const routes = controllers.flatMap((controller) =>
|
||||
|
||||
@@ -41,14 +41,14 @@ function multipartArchive(archive) {
|
||||
};
|
||||
}
|
||||
|
||||
function createTemplateArchive() {
|
||||
function createTemplateArchive(template = "acheng-campus-food") {
|
||||
const output = mkdtempSync(path.join(os.tmpdir(), "personal-brand-template-pack-"));
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
[
|
||||
path.resolve(process.cwd(), "../../scripts/template-pack.cjs"),
|
||||
"--template",
|
||||
"acheng-campus-food",
|
||||
template,
|
||||
"--out",
|
||||
output,
|
||||
],
|
||||
@@ -154,6 +154,143 @@ test("模板目录只允许平台模板管理员访问,并支持安全、幂
|
||||
assert.equal(JSON.parse(invalidRetire.body).changed, false);
|
||||
});
|
||||
|
||||
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 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,
|
||||
});
|
||||
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(body.workspace.brand.config.visualTemplateKey, "atelier-solopreneur");
|
||||
assert.equal(body.template.pages.includes("profile"), true);
|
||||
assert.equal(body.template.pages.includes("inquiry"), true);
|
||||
const stored = await prisma.templatePackageVersion.findUniqueOrThrow({
|
||||
where: { id: versionId },
|
||||
});
|
||||
const failures = [
|
||||
[{ ...stored.manifestSnapshot, sampleContent: {} }, /缺少必需数据/],
|
||||
[{ ...stored.manifestSnapshot, requiredCapabilities: ["unknown"] }, /未注册的 capability/],
|
||||
[{ ...stored.manifestSnapshot, visualTemplateKey: "unknown" }, /renderer/],
|
||||
[{ ...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 {
|
||||
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 },
|
||||
});
|
||||
}
|
||||
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);
|
||||
});
|
||||
|
||||
test("admin routes remain guarded when an API prefix is configured", async () => {
|
||||
process.env.API_PREFIX = "api";
|
||||
try {
|
||||
@@ -3657,7 +3794,7 @@ test("atelier template imports selected package and preserves draft publication
|
||||
payload: { templateKey: "personal" },
|
||||
});
|
||||
assert.equal(installation.visualTemplate.key, "atelier-solopreneur");
|
||||
assert.equal(installation.visualTemplate.tokens.colors.accent, "#183329");
|
||||
assert.equal(installation.visualTemplate.tokens.colors.accent, "#1f3a5f");
|
||||
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 });
|
||||
|
||||
Reference in new issue
Block a user