feat: 增加模板版本独立预览入口

This commit is contained in:
que01 committed 2026-10-16 17:28:07 +08:00
1 parent 413413efda
commit 6edde5a8d6
15 files changed
+781 -14

No files matched your search

@@ -1,13 +1,14 @@
import { useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Alert, Button, List, Modal, Table, Tag, Typography, message } from "antd";
import { ReloadOutlined, UploadOutlined } from "@ant-design/icons";
import { EyeOutlined, ReloadOutlined, UploadOutlined } from "@ant-design/icons";
import type { TemplatePackageVersion } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
import { AdminSection } from "../../components/AdminSection.js";
import { EmptyState } from "../../components/EmptyState.js";
import { ErrorNote, QueryState } from "../../components/QueryState.js";
import { TemplatePackagePreviewModal } from "./TemplatePackagePreviewModal.js";
const client = createApiClient();
@@ -23,6 +24,7 @@ export function TemplateManagementPage() {
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [auditId, setAuditId] = useState<string | null>(null);
const [previewVersion, setPreviewVersion] = useState<TemplatePackageVersion | null>(null);
const queryClient = useQueryClient();
const packages = useQuery({
queryKey: ["admin-template-packages", page, pageSize],
@@ -167,7 +169,7 @@ export function TemplateManagementPage() {
key: "report",
render: (_, item) => {
const report = item.validationReport;
return `${String(report.fileCount ?? "-")} 个,${formatBytes(report.extractedBytes)}`;
return `${typeof report.fileCount === "number" ? report.fileCount : "-"} 个,${formatBytes(report.extractedBytes)}`;
},
},
{
@@ -188,6 +190,14 @@ export function TemplateManagementPage() {
key: "actions",
render: (_, item) => (
<span>
<Button
type="link"
icon={<EyeOutlined />}
onClick={() => setPreviewVersion(item)}
disabled={!item.manifestSummary?.supportedIndustryTemplates?.length}
>
预览
</Button>
<Button
type="link"
loading={lifecycle.isPending && lifecycle.variables?.id === item.id}
@@ -247,6 +257,12 @@ export function TemplateManagementPage() {
/>
</QueryState>
</Modal>
{previewVersion ? (
<TemplatePackagePreviewModal
version={previewVersion}
onClose={() => setPreviewVersion(null)}
/>
) : null}
</div>
);
}
@@ -0,0 +1,123 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Alert, Modal, Select, Typography } from "antd";
import type { TemplatePackageVersion } from "@personal-brand/api-client";
import { createApiClient } from "../../lib/api.js";
import { QueryState } from "../../components/QueryState.js";
import { EmptyState } from "../../components/EmptyState.js";
import { ComponentTemplatePreview } from "../brand/ComponentTemplatePreview.js";
const pageLabels: Record<string, string> = {
home: "首页",
offerings: "业务列表",
service: "服务",
profile: "我的 / 主理人",
detail: "业务详情",
inquiry: "咨询表单",
records: "咨询记录",
success: "提交结果",
};
export function TemplatePackagePreviewModal({
version,
onClose,
}: {
version: TemplatePackageVersion;
onClose: () => void;
}) {
const [industry, setIndustry] = useState(version.manifestSummary?.supportedIndustryTemplates[0]);
const [page, setPage] = useState("home");
const [offeringId, setOfferingId] = useState<string>();
const client = createApiClient();
const preview = useQuery({
queryKey: ["admin-template-package-preview", version.id, industry],
queryFn: () => client.previewAdminTemplatePackage(version.id, industry!),
enabled: Boolean(industry),
retry: false,
gcTime: 0,
});
const data = preview.data;
return (
<Modal
title={`${version.displayName} · ${version.version} 版本预览`}
open
footer={null}
width={960}
onCancel={onClose}
>
<div className="admin-stack">
<Select
aria-label="预览行业"
value={industry}
placeholder="选择行业"
options={(version.manifestSummary?.supportedIndustryTemplates ?? []).map((value) => ({
label: value,
value,
}))}
onChange={(value) => {
setIndustry(value);
setPage("home");
setOfferingId(undefined);
}}
/>
<Alert
type="info"
showIcon
message="模板演示预览"
description="演示内容不属于真实品牌,咨询提交和客户记录读取已禁用。"
/>
{!industry ? (
<EmptyState title="没有可预览的行业" description="请检查模板包的行业兼容声明。" />
) : (
<QueryState
loading={preview.isLoading}
error={preview.error}
onRetry={() => void preview.refetch()}
>
{data ? (
<>
<Typography.Paragraph type="secondary">
{data.industry.name} · Runtime {data.compatibility.runtimeContract} · renderer{" "}
{data.compatibility.renderer.key}@{data.compatibility.renderer.version}
</Typography.Paragraph>
<Select
aria-label="预览页面"
value={page}
options={data.template.pages.map((value) => ({
value,
label:
data.template.navigation.find((tab) => tab.page === value)?.label ??
pageLabels[value] ??
value,
}))}
onChange={setPage}
/>
{page === "detail" ? (
<Select
aria-label="预览业务记录"
value={offeringId ?? data.workspace.offerings[0]?.id}
options={data.workspace.offerings.map((item) => ({
label: item.name,
value: item.id,
}))}
onChange={setOfferingId}
/>
) : null}
<ComponentTemplatePreview
key={`${version.id}:${industry}:${page}`}
workspace={data.workspace}
page={page}
{...((offeringId ?? data.workspace.offerings[0]?.id)
? { offeringId: offeringId ?? data.workspace.offerings[0]!.id }
: {})}
targets={[]}
onTargetSelected={() => undefined}
/>
</>
) : null}
</QueryState>
)}
</div>
</Modal>
);
}
@@ -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 {}
+8
View File
@@ -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) =>
+140 -3
View File
@@ -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 });
+1 -1
View File
@@ -218,7 +218,7 @@ export function Inquiry({
)}
<Button
className="submit-button"
disabled={sending}
disabled={sending || preview}
loading={sending}
onClick={() => void submit()}
>
@@ -0,0 +1,89 @@
import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { test, expect } from "@playwright/test";
// 使用真实包和生产投影生成 UI fixture;HTTP 授权与持久化由 API 集成测试覆盖。
const manifest = JSON.parse(
fs.readFileSync("../../packages/template-atelier-solopreneur/template.json", "utf8"),
);
const version = {
id: "preview-browser-version",
packageKey: manifest.packageKey,
version: manifest.version,
displayName: manifest.displayName,
status: "imported",
contentChecksum: "fixture-checksum",
manifestSnapshot: manifest,
importedBy: { displayName: "模板管理员" },
validationReport: {},
manifestSummary: { supportedIndustryTemplates: manifest.supportedIndustryTemplates },
};
test("模板管理可重试预览,并切换我的、详情和禁止提交的咨询内页", async ({ page }) => {
// 独立 Node ESM 进程避免 Playwright CJS transform 改写 API 的 import-only 依赖。
const fixture = JSON.parse(
execFileSync(
process.execPath,
[
"--input-type=module",
"-e",
`
import 'reflect-metadata';
import { AdminTemplatePreviewService } from './dist/modules/admin/admin-template-preview.service.js';
let input = '';
for await (const chunk of process.stdin) input += chunk;
const version = JSON.parse(input);
const service = new AdminTemplatePreviewService({ templatePackageVersion: { findUnique: async () => version } });
process.stdout.write(JSON.stringify(await service.preview(version.id, 'personal')));
`,
],
{ cwd: path.resolve("../api"), input: JSON.stringify(version), encoding: "utf8" },
),
);
await page.setViewportSize({ width: 1440, height: 1000 });
await page.addInitScript(() => {
localStorage.setItem("adminToken", "fixture-token");
localStorage.setItem("adminPlatformTemplateRole", "template_admin");
});
let attempts = 0;
const writes: string[] = [];
await page.route("**/api/**", async (route) => {
const url = new URL(route.request().url());
if (route.request().method() !== "GET") writes.push(url.pathname);
if (url.pathname.endsWith("/preview")) {
attempts++;
if (attempts === 1)
return route.fulfill({
status: 400,
json: { error: { code: "HTTP_400", message: "预览测试失败,请重试" } },
});
return route.fulfill({ json: fixture });
}
if (url.pathname.endsWith("/admin/templates"))
return route.fulfill({ json: { items: [version], page: 1, pageSize: 20, total: 1 } });
if (url.pathname.endsWith("/admin/brands")) return route.fulfill({ json: [] });
return route.fulfill({ json: { name: "测试工作区" } });
});
await page.goto(`${process.env.ADMIN_URL || "http://localhost:3016"}/admin/templates`);
await page.getByRole("button", { name: /预览/ }).click();
const modal = page.getByRole("dialog");
await expect(modal.getByText("预览测试失败,请重试")).toBeVisible();
await modal.getByRole("button", { name: /重试/ }).click();
await expect(modal.locator(".atelier-founder-name")).toHaveText(
manifest.sampleContent.personal.brandConfig.founder,
);
const choosePage = async (label: string) => {
await modal.getByLabel("预览页面").click();
await page.locator(".ant-select-item-option-content").getByText(label, { exact: true }).click();
};
await choosePage("我的");
await expect(modal.locator(".component-template-preview")).toContainText("我的咨询记录");
await choosePage("业务详情");
await expect(modal.locator(".component-template-preview")).toContainText(
manifest.sampleContent.personal.offerings[0].name,
);
await choosePage("咨询表单");
await expect(modal.locator(".inquiry-form")).toBeVisible();
await expect(modal.locator(".inquiry-form button").last()).toBeDisabled();
expect(writes).toEqual([]);
});
+14 -1
View File
@@ -2,7 +2,7 @@
> 任务 ID:TMP-PLATFORM-001
>
> 状态:实施中,Phase 0/1 已完成,Phase 2 导入基础链路已完成,目录发布与独立预览待继续推进
> 状态:实施中,Phase 0/1/2 已完成,Phase 3 已接入版本预览 API 和管理页,完整 fixture、资源诊断与隔离预览仍待验收
>
> 唯一任务入口:本文档
>
@@ -402,6 +402,19 @@ Phase 2 当前进度(2026-10-16):
退出门禁:预览不创建品牌和业务数据;不同版本、行业和资源组合不会串数据;页面失败时保留上传和选择上下文;真实 Runtime 和预览数据映射有测试。
Phase 3 当前实现(2026-10-16):
- 增加 `GET /admin/templates/:id/preview?industry=<key>`,只允许平台模板管理员;DTO 校验查询,服务读取数据库版本的 `manifestSnapshot.sampleContent`,不读取当前品牌内容,不创建品牌或业务记录。
- `imported` 和 `published` 可预览;`retired` 和其他不可用状态返回 `409`。不存在的版本、非法行业组合、Runtime/renderer/capability/sample 校验失败返回 `400`,沿用统一错误 envelope。
- 使用 `assemblePublicWorkspace` 投影演示快照,Client 和 Admin 同步接入;模板管理页按行业选择,并可查看首页、我的、业务详情和咨询等内页,失败保留选择并支持重试。
- 当前 renderer 兼容策略保守地要求部署 registry 的 package key、visual key 和版本一致;这只是第一步兼容门禁,尚未引入独立 renderer version/hash。API 不执行导入包源码,Admin 只挂载已部署 renderer。
- 当前预览为请求内存上下文,模拟 ID 使用 `template-preview:` 前缀,咨询组件使用 `preview` 模式并禁用提交;客户记录组件沿用不读取客户 API 的预览模式。
- 自动化:API 集成测试覆盖缺少/无效凭证、普通品牌管理员和 customer 拒绝、真实 atelier 包预览、行业不兼容、无 renderer、无 capability、缺 sample、撤回状态及全局业务表计数不变。浏览器交互使用真实 manifest 和同一生产投影生成 fixture,HTTP mock 仅证明页面交互,不代替 API 授权/数据库证据。
- 预览入口增加嵌套声明结构门禁;集成测试覆盖 `dataSlots`、`navigation`、`templateFields`、`trustContentTypes` 和 Admin section 的畸形输入,返回可操作的 `400` 错误。
- 本轮验证:API HTTP integration `52/52`、upload `2/2`、API unit `49/49`、Client `6/6`、Admin unit `6/6`、Playwright 预览交互 `1/1`;全仓 typecheck、Admin production build、变更范围 lint、format、`template:check` 通过。`template:doctor` 未解决项为 `0`,模板完成度仍为 `unverified`。Playwright 运行前需构建 API/config 并启动 Admin:`ADMIN_PORT=3016 pnpm --filter @personal-brand/admin dev`,随后在 `apps/taro` 运行 `pnpm exec playwright test test/browser/template-management.spec.ts`。
- 咨询按钮改动另行完成 atelier 的 `weapp` 和 `h5` 构建,参数为 `TEMPLATE_KEY=atelier-solopreneur API_BASE_URL=https://wechat.app.que01.top/api WEAPP_APP_ID=wxd75d946d6978d183 pnpm --filter @personal-brand/taro build:<weapp|h5>`;产物包含对应 AppID/API 地址并通过 masking 检查。本轮不作为微信真机视觉验收。
- 本阶段尚未完成:独立 `previewFixture` 与 bootstrap sample 的拆分、包内完整身份和媒体 fixture、按 checksum 提供导入资源、逐资源缺失诊断、画布内 CTA 导航、预览审计、短期 session/origin/CSP 隔离、跨模板/行业/版本矩阵及最终视觉验收。因此以上阶段清单仍保留未完成状态。
### Phase 4:品牌安装、bootstrap 和发布
- [ ] 区分行业安装和视觉包安装,保存精确版本与 checksum 快照;
+4
View File
@@ -42,6 +42,7 @@ export type {
TemplatePackageAuditEntry,
TemplatePackageImportResult,
TemplatePackageList,
TemplatePackagePreview,
TemplatePackageVersion,
} from "./resources/template.js";
export type { TrustContent, TrustContentInput } from "./types/trust.js";
@@ -249,6 +250,9 @@ export class ApiClient
retireAdminTemplatePackage = (
...arguments_: Parameters<TemplateMethods["retireAdminTemplatePackage"]>
) => this.resources.template.retireAdminTemplatePackage(...arguments_);
previewAdminTemplatePackage = (
...arguments_: Parameters<TemplateMethods["previewAdminTemplatePackage"]>
) => this.resources.template.previewAdminTemplatePackage(...arguments_);
listAdminTemplatePackageAudit = (
...arguments_: Parameters<TemplateMethods["listAdminTemplatePackageAudit"]>
) => this.resources.template.listAdminTemplatePackageAudit(...arguments_);
@@ -16,6 +16,7 @@ export interface TemplateMethods {
publishAdminTemplatePackage(id: string): Promise<TemplatePackageActionResult>;
retireAdminTemplatePackage(id: string): Promise<TemplatePackageActionResult>;
listAdminTemplatePackageAudit(id: string): Promise<TemplatePackageAuditEntry[]>;
previewAdminTemplatePackage(id: string, industry: string): Promise<TemplatePackagePreview>;
getPublicTemplate(key: BrandTemplateKey): Promise<BrandTemplateDefinition>;
listPublicTemplates(): Promise<{
industries: BrandTemplateDefinition[];
@@ -108,6 +109,30 @@ export interface TemplatePackageVersion {
importedAt: string;
updatedAt: string;
importedBy: { id: string; username: string; displayName: string };
manifestSummary?: {
runtimeContract: string;
supportedIndustryTemplates: string[];
requiredCapabilities: string[];
};
}
export interface TemplatePackagePreview {
template: Pick<
TemplatePackageVersion,
"id" | "packageKey" | "version" | "displayName" | "status" | "contentChecksum"
> & {
visualTemplateKey: string;
navigation: Array<{ key: string; label: string; page: string }>;
pages: string[];
};
industry: { key: string; version: string; name: string };
compatibility: {
runtimeContract: string;
renderer: { key: string; version: string; trusted: boolean };
requiredCapabilities: string[];
missingSampleSlots: string[];
};
workspace: RuntimeWorkspace;
}
export interface TemplatePackageList {
@@ -180,6 +205,10 @@ export function templateMethods({ request }: { request: RequestFn }): TemplateMe
request(`/admin/templates/${encodeURIComponent(id)}/retire`, { method: "POST" }),
listAdminTemplatePackageAudit: (id) =>
request(`/admin/templates/${encodeURIComponent(id)}/audit`),
previewAdminTemplatePackage: (id, industry) =>
request(
`/admin/templates/${encodeURIComponent(id)}/preview?industry=${encodeURIComponent(industry)}`,
),
getPublicTemplate: (key) => request(`/public/templates/${key}`),
listPublicTemplates: () =>
request<{
+5
View File
@@ -115,9 +115,14 @@ test("模板目录客户端发送分页并支持版本发布和审计", async ()
await client.listAdminTemplatePackages({ page: 2, pageSize: 10 });
await client.publishAdminTemplatePackage("version/1");
await client.listAdminTemplatePackageAudit("version/1");
await client.previewAdminTemplatePackage("version/1", "personal & design");
assert.deepEqual(calls, [
{ url: "http://api.test/admin/templates?page=2&pageSize=10", method: "GET" },
{ url: "http://api.test/admin/templates/version%2F1/publish", method: "POST" },
{ url: "http://api.test/admin/templates/version%2F1/audit", method: "GET" },
{
url: "http://api.test/admin/templates/version%2F1/preview?industry=personal%20%26%20design",
method: "GET",
},
]);
});