fix: 收口模板预览状态与媒体矩阵
This commit is contained in:
1 parent
5bf54096be
commit
b1e8012ded
28 files changed
+1015
-56
No files matched your search
@@ -106,7 +106,10 @@ export const Image = React.forwardRef(({ mode, src, style, ...props }, ref) => {
|
||||
ref,
|
||||
src:
|
||||
assets && typeof src === "string" && src.startsWith("/assets/")
|
||||
? assets[src]?.dataUrl
|
||||
? // 导入包资源以 /assets 开头;本地多模板预览的 renderer 可能额外携带包 key 前缀。
|
||||
(assets[src]?.dataUrl ??
|
||||
assets[src.replace(`/assets/${key}/`, "/assets/")]?.dataUrl ??
|
||||
src)
|
||||
: resolveImageSource(src, key),
|
||||
style: { objectFit: mode === "aspectFit" ? "contain" : "cover", ...style },
|
||||
});
|
||||
|
||||
@@ -361,8 +361,11 @@ export class AdminTemplatePackageService {
|
||||
const version = await this.prisma.templatePackageVersion.findUnique({ where: { id } });
|
||||
if (!version) throw new BadRequestException("模板版本不存在");
|
||||
if (version.status === target) return { changed: false, version: this.publicVersion(version) };
|
||||
// retired 是目录可见性的终态,但平台管理员可以显式重新发布;品牌安装与历史快照不受影响。
|
||||
const valid =
|
||||
target === "published" ? version.status === "imported" : version.status === "published";
|
||||
target === "published"
|
||||
? version.status === "imported" || version.status === "retired"
|
||||
: version.status === "published";
|
||||
if (!valid) throw new ConflictException(`模板版本当前状态为 ${version.status},不能执行此操作`);
|
||||
const updated = await this.prisma.$transaction(async (tx) => {
|
||||
const changed = await tx.templatePackageVersion.updateMany({
|
||||
|
||||
@@ -440,7 +440,11 @@ export class AdminTemplatePreviewService {
|
||||
templateKey: industryTemplate.key,
|
||||
tagline: identity?.tagline ?? `${industryTemplate.name}模板示例`,
|
||||
description: identity?.description ?? "这是模板预览数据,不属于任何真实品牌。",
|
||||
avatarUrl: identity?.avatarUrl ?? null,
|
||||
avatarUrl:
|
||||
identity?.avatarUrl ??
|
||||
(typeof brandConfig.avatarUrl === "string" && brandConfig.avatarUrl.trim()
|
||||
? brandConfig.avatarUrl
|
||||
: null),
|
||||
coverUrl: identity?.coverUrl ?? null,
|
||||
hours: identity?.hours ?? "示例营业时间",
|
||||
address: identity?.address ?? "示例服务范围",
|
||||
|
||||
@@ -275,7 +275,7 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
|
||||
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 === "missing",
|
||||
(asset) => asset.binding === "brand.avatarUrl" && asset.status === "ready",
|
||||
),
|
||||
);
|
||||
assert.ok(
|
||||
@@ -283,6 +283,8 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
|
||||
(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,/,
|
||||
@@ -491,6 +493,20 @@ test("平台模板管理员可以按行业预览版本,且预览不写入品
|
||||
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 () => {
|
||||
|
||||
@@ -115,6 +115,25 @@ test("template preview matrix keeps every deployed package, industry, and versio
|
||||
assert.equal(firstPreview.preview.safety.submissions, "disabled");
|
||||
assert.ok(firstPreview.workspace.offerings.length > 0);
|
||||
|
||||
// 每个已部署包的预览都必须有可显示的主理人身份和已验证媒体槽位。
|
||||
assert.match(firstPreview.workspace.brand.founder ?? "", /\S/);
|
||||
assert.match(firstPreview.workspace.brand.avatarUrl ?? "", /^\/assets\//);
|
||||
assert.equal(firstPreview.preview.assets.length, fixture.manifest.assetSlots.length);
|
||||
assert.deepEqual(
|
||||
firstPreview.preview.assets.map((item) => item.status),
|
||||
fixture.manifest.assetSlots.map(() => "ready"),
|
||||
);
|
||||
assert.deepEqual(
|
||||
firstPreview.preview.diagnostics.filter((item) => item.code !== "LEGACY_PREVIEW_SAMPLE"),
|
||||
[],
|
||||
);
|
||||
assert.equal(
|
||||
firstPreview.preview.fixtureSource,
|
||||
fixture.manifest.packageKey === "atelier-solopreneur"
|
||||
? "previewFixture"
|
||||
: "legacy-sampleContent",
|
||||
);
|
||||
|
||||
// 版本 ID 进入模拟品牌 ID,不同版本不会共享同一模拟品牌身份。
|
||||
assert.match(firstPreview.workspace.brand.id, new RegExp(`^template-preview:${first.id}`));
|
||||
assert.match(
|
||||
|
||||
@@ -102,7 +102,7 @@ test("模板管理可重试预览,并切换我的、详情和禁止提交的
|
||||
);
|
||||
await expect(modal.getByText("演示数据:独立预览内容")).toBeVisible();
|
||||
await modal.getByText("资源诊断", { exact: true }).click();
|
||||
await expect(modal.getByText("内容缺失", { exact: true }).first()).toBeVisible();
|
||||
await expect(modal.getByText("内容缺失", { exact: true })).toHaveCount(0);
|
||||
await expect(modal.getByText("包内资源已验证", { exact: true }).first()).toBeVisible();
|
||||
await captureVisualEvidence("home");
|
||||
const choosePage = async (label: string) => {
|
||||
@@ -119,7 +119,7 @@ test("模板管理可重试预览,并切换我的、详情和禁止提交的
|
||||
await modal.getByLabel("预览页面").click();
|
||||
await page.locator(".ant-select-item-option-content").getByText("首页", { exact: true }).click();
|
||||
await modal.getByText("资源诊断", { exact: true }).click();
|
||||
await expect(modal.getByText("内容缺失", { exact: true }).first()).toBeVisible();
|
||||
await expect(modal.getByText("内容缺失", { exact: true })).toHaveCount(0);
|
||||
await expect(modal.getByText("包内资源已验证", { exact: true }).first()).toBeVisible();
|
||||
await choosePage("我的");
|
||||
await expect(modal.locator(".component-template-preview")).toContainText("我的咨询记录");
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { test, expect, type Page } from "@playwright/test";
|
||||
|
||||
type PackedManifest = {
|
||||
packageKey: string;
|
||||
version: string;
|
||||
displayName: string;
|
||||
supportedIndustryTemplates: string[];
|
||||
};
|
||||
|
||||
type PackedChecksums = {
|
||||
contentChecksum: string;
|
||||
};
|
||||
|
||||
type PreviewVersion = {
|
||||
id: string;
|
||||
packageKey: string;
|
||||
version: string;
|
||||
displayName: string;
|
||||
status: "imported";
|
||||
manifestSnapshot: PackedManifest;
|
||||
importedBy: { displayName: string };
|
||||
validationReport: Record<string, unknown>;
|
||||
manifestSummary: { supportedIndustryTemplates: string[] };
|
||||
artifactPath: string;
|
||||
archiveChecksum: string;
|
||||
contentChecksum: string;
|
||||
};
|
||||
|
||||
type PreviewBundle = {
|
||||
preview: Record<string, unknown>;
|
||||
version: PreviewVersion;
|
||||
};
|
||||
|
||||
type MediaCase = {
|
||||
packageKey: string;
|
||||
industry: string;
|
||||
founder: string;
|
||||
};
|
||||
|
||||
const mediaCases: MediaCase[] = [
|
||||
{ packageKey: "acheng-campus-food", industry: "food", founder: "阿成" },
|
||||
{ packageKey: "atelier-solopreneur", industry: "personal", founder: "林予 · 示例主理人" },
|
||||
{ packageKey: "linjing-editorial", industry: "personal", founder: "示例主理人" },
|
||||
{ packageKey: "linjing-editorial", industry: "doors", founder: "示例主理人" },
|
||||
];
|
||||
|
||||
async function buildPreviewFixture(mediaCase: MediaCase) {
|
||||
// 使用真实 template:pack 产物和 API preview service,避免在浏览器测试里手写演示数据。
|
||||
const output = await new Promise<string>((resolve, reject) => {
|
||||
const temporary = path.join(
|
||||
os.tmpdir(),
|
||||
`template-preview-media-${mediaCase.packageKey}-${mediaCase.industry}`,
|
||||
);
|
||||
try {
|
||||
rmSync(temporary, { recursive: true, force: true });
|
||||
mkdirSync(temporary, { recursive: true });
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
[
|
||||
path.resolve(process.cwd(), "../../scripts/template-pack.cjs"),
|
||||
"--template",
|
||||
mediaCase.packageKey,
|
||||
"--out",
|
||||
temporary,
|
||||
],
|
||||
{ cwd: path.resolve(process.cwd(), "../.."), stdio: "ignore" },
|
||||
);
|
||||
const archive = readdirSync(temporary).find((file) => file.endsWith(".tar.gz"));
|
||||
assert.ok(archive);
|
||||
const root = path.join(temporary, archive.slice(0, -7));
|
||||
const manifest = JSON.parse(
|
||||
readFileSync(path.join(root, "template.json"), "utf8"),
|
||||
) as PackedManifest;
|
||||
const checksums = JSON.parse(
|
||||
readFileSync(path.join(root, "checksums.json"), "utf8"),
|
||||
) as PackedChecksums;
|
||||
const archivePath = path.join(temporary, archive);
|
||||
const version: PreviewVersion = {
|
||||
id: `preview-media-${mediaCase.packageKey}-${mediaCase.industry}`,
|
||||
packageKey: manifest.packageKey,
|
||||
version: manifest.version,
|
||||
displayName: manifest.displayName,
|
||||
status: "imported",
|
||||
manifestSnapshot: manifest,
|
||||
importedBy: { displayName: "模板管理员" },
|
||||
validationReport: {},
|
||||
manifestSummary: { supportedIndustryTemplates: manifest.supportedIndustryTemplates },
|
||||
artifactPath: archivePath,
|
||||
archiveChecksum: "",
|
||||
contentChecksum: checksums.contentChecksum,
|
||||
};
|
||||
const serialized = JSON.stringify({ version, industry: mediaCase.industry });
|
||||
const stdout = execFileSync(
|
||||
process.execPath,
|
||||
[
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
`
|
||||
import 'reflect-metadata';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { AdminTemplatePreviewAssetsService } from './dist/modules/admin/admin-template-preview-assets.service.js';
|
||||
import { AdminTemplatePreviewService } from './dist/modules/admin/admin-template-preview.service.js';
|
||||
let input = '';
|
||||
for await (const chunk of process.stdin) input += chunk;
|
||||
const { version, industry } = JSON.parse(input);
|
||||
version.archiveChecksum = createHash('sha256').update(readFileSync(version.artifactPath)).digest('hex');
|
||||
const service = new AdminTemplatePreviewService(
|
||||
{
|
||||
templatePackageVersion: { findUnique: async () => version },
|
||||
templatePackageAuditLog: { create: async () => ({}) },
|
||||
},
|
||||
new AdminTemplatePreviewAssetsService(),
|
||||
);
|
||||
process.stdout.write(JSON.stringify(await service.preview(version.id, industry, 'visual-matrix-admin')));
|
||||
`,
|
||||
],
|
||||
{
|
||||
cwd: path.resolve("../api"),
|
||||
input: serialized,
|
||||
encoding: "utf8",
|
||||
maxBuffer: 32 * 1024 * 1024,
|
||||
},
|
||||
);
|
||||
resolve(JSON.stringify({ preview: JSON.parse(stdout) as Record<string, unknown>, version }));
|
||||
} catch (error) {
|
||||
reject(error instanceof Error ? error : new Error(String(error)));
|
||||
} finally {
|
||||
rmSync(temporary, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
return JSON.parse(output) as PreviewBundle;
|
||||
}
|
||||
|
||||
async function selectPreviewIndustry(page: Page, industry: string) {
|
||||
await page.getByLabel("预览行业").click();
|
||||
await page
|
||||
.locator(".ant-select-item-option-content")
|
||||
.getByText(industry, { exact: true })
|
||||
.click();
|
||||
}
|
||||
|
||||
test("导入包预览矩阵展示身份、资源和完整媒体槽位", async ({ page }) => {
|
||||
const evidenceDirectory = process.env.TEMPLATE_PREVIEW_VISUAL_EVIDENCE;
|
||||
let sequence = 0;
|
||||
|
||||
for (const mediaCase of mediaCases) {
|
||||
sequence += 1;
|
||||
await test.step(`${mediaCase.packageKey}/${mediaCase.industry}`, async () => {
|
||||
const { preview, version } = await buildPreviewFixture(mediaCase);
|
||||
assert.ok(version);
|
||||
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 += 1;
|
||||
return route.fulfill({
|
||||
status: attempts === 1 ? 400 : 200,
|
||||
json:
|
||||
attempts === 1
|
||||
? { error: { code: "HTTP_400", message: "预览测试失败,请重试" } }
|
||||
: preview,
|
||||
});
|
||||
}
|
||||
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:3000"}/admin/templates`);
|
||||
const modal = page.getByRole("dialog");
|
||||
await page.getByRole("button", { name: /预览/ }).click();
|
||||
await expect(modal.getByText("预览测试失败,请重试")).toBeVisible();
|
||||
await modal.getByRole("button", { name: /重试/ }).click();
|
||||
await expect(modal.locator(".component-template-preview")).toContainText(mediaCase.founder);
|
||||
|
||||
if (mediaCase.industry !== version.manifestSummary.supportedIndustryTemplates[0]) {
|
||||
await selectPreviewIndustry(page, mediaCase.industry);
|
||||
}
|
||||
|
||||
// 覆盖此前疏漏:不仅检查数据存在,还要证明包内媒体渲染为可显示图像。
|
||||
const images = modal.locator('.component-template-preview img[src^="data:image/"]');
|
||||
await expect(images.first()).toBeVisible();
|
||||
const imageCount = await images.count();
|
||||
expect(imageCount).toBeGreaterThan(0);
|
||||
await expect
|
||||
.poll(() =>
|
||||
Promise.all(
|
||||
Array.from({ length: imageCount }, (_, index) =>
|
||||
images.nth(index).evaluate((image: HTMLImageElement) => image.naturalWidth),
|
||||
),
|
||||
).then((values) => Math.min(...values)),
|
||||
)
|
||||
.toBeGreaterThan(0);
|
||||
|
||||
// 独立 fixture 与补齐后的 legacy sample 都不应显示资源缺失。
|
||||
await expect(modal.getByText("内容缺失", { exact: true })).toHaveCount(0);
|
||||
expect(writes).toEqual([]);
|
||||
|
||||
if (evidenceDirectory) {
|
||||
mkdirSync(evidenceDirectory, { recursive: true });
|
||||
await page.screenshot({
|
||||
path: path.join(
|
||||
evidenceDirectory,
|
||||
`${String(sequence).padStart(2, "0")}-${mediaCase.packageKey}-${mediaCase.industry}.png`,
|
||||
),
|
||||
});
|
||||
}
|
||||
await page.unroute("**/api/**");
|
||||
});
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user